Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extending SWIG builtin classes

Tags:

c++

python

swig

The -builtin option of SWIG has the advantage of being faster, and of being exempt of a bug with multiple inheritance.
The setback is I can't set any attribute on the generated classes or any subclass :
-I can extend a python builtin type like list, without hassle, by subclassing it :

class Thing(list):
    pass

Thing.myattr = 'anything' # No problem

-However using the same approach on a SWIG builtin type, the following happens :

class Thing(SWIGBuiltinClass):
    pass

Thing.myattr = 'anything'

AttributeError: type object 'Thing' has no attribute 'myattr'

How could I work around this problem ?

like image 655
MONK Avatar asked Jun 24 '11 15:06

MONK


1 Answers

I found a solution quite by accident. I was experimenting with metaclasses, thinking I could manage to override the setattr and getattr functions of the builtin type in the subclass.

Doing this I discovered the builtins already have a metaclass (SwigPyObjectType), so my metaclass had to inherit it.

And that's it. This alone solved the problem. I would be glad if someone could explain why :

SwigPyObjectType = type(SWIGBuiltinClass)

class Meta(SwigPyObjectType):
    pass

class Thing(SWIGBuiltinClass):
    __metaclass__ = Meta

Thing.myattr = 'anything' # Works fine this time
like image 136
MONK Avatar answered Nov 19 '22 20:11

MONK