Search code examples
pythonpycairo

Write an extension to an existing python module


I want to write an extension to python's lib cairo. The plan is as follows:

cairo has a class named "Context" which is the canvas that the user draws geometric objects on it.

For example let cr be an instance of Context, then

cr.move_to(a,b)
cr.line_to(c,d)

will move the pen to (a,b) and then draw a line to (c,d).

I want to add another method to this lib, for example it's named "My_line_to": this function will draw an curve between (a,b) and (c,d),not a straight line.( I still call it line_to() because it's geodesic line in hyperbolic geometry)

The usage is

cr.my_move_to(a,b)
cr.my_line_to(c,d)

I think I'd better make this extension into another file named "MyDrawer.py", but I have no idea how to implement this. I want to know what is the standard/elegant way to write one's extension of an existing module in this case?


Solution

  • Subclassing is your friend here. Just subclass the Context class and define an additional method.

    from cairo import Context # or whatever is the path name
    class ExtendedContext(Context): # subclass from ExtendedContext - inherits all methods and variables from Context
        def my_line_to(self, x, y):
            # define code here
        def my_move_to(self, x, y):
            # define code here
    

    Then, when you want to use this new class, just import it and use it.