Thursday, June 20, 2013

Proxy Pattern for Extending non-extendable Python Class

graph_tool library is based on boost C++ library and provides Vertex class binding for Python. If we wanted to extend this Vertex class and add some attributes and methods, it wouldn't let us do that due to private constructor in C++ code.

RuntimeError: This class cannot be instantiated from Python

We can overcome this obstacle using Proxy pattern.

In the __getattr__ method, if the attribute(or function name) is not in the Subclass MyVertex, then it looks for attributes of Vertex object that is defined inside MyVertex.
 Here is the code:

No comments: