subclassing extension type and assignment to __class__

gregory lielens gregory.lielens at fft.be
Sun Nov 28 16:45:33 EST 2004


> Sorry for the confusion. This looks like a situation best handled with
> embedding rather than inheritance. The PClass and PClass2 wrapper classes
> can share whatever relationship _PClass and _PClass2 share.
> 
> class PClass:
>     def __init__(inst=None):
>         if inst is None:
>             inst = _PClass()
>         self._inst = inst
>     def override_method(self, ...):
>         self._inst.override_method(...)
>     def new_method(self, ...):
>         ...
> 
> class PClass2:
>         self._inst = _PClass2()
>     def troublesome_method(self):
>         base = PClass(self._inst.troublesome_method())
>         ...
>         return base

Yes I was affraid this would be the conclusion: embedding instead of 
inheritance...But this means that not only the method that need to be 
modified need to be rewritten in python, all the other ones also just to 
  delegate to the embedded instance...
This is not too practical, even if such writing can be more or less 
automatized...
For my purpose it seems that there was a big step backward between 
python 2.2 and 2.3, and I am surprised this has been mostly 
unnoticed...This problem should be common for many people trying to 
write mixed C/C++ / python classes. I found some reference on this in 
the list archive, a few people beeing anoyed by it, but the proposition 
to make the test about assignment to class less strict was not retained 
it seems...I plan to experiment a little  with the python C 
implementation to see what happen if I bypass this test...

> Alternatively you could provide a way to pass PClass back to the extension module
> for _PClass2.troublesome_method to use instead of _PClass when creating a return
> object. But the embedding approach seems more appropriate when _PClass is not to
> be used directly.

Yes but again this is not so practical, the purpose of the _PClass / 
PClass implementation was to make the bindings as light, and as easy to 
implement / extend as possible, and both the embedding and  the creation 
of PClass within _PClass2 methods defeat this purpose...

I think allowing assignment to class for native types should be done if 
possible, for example if the new class is a derived type (possibly using 
__slots__)... I saw a post on this by Guido, but the reason why it was 
not possible is not clear to me and the thread died without further 
explanations...Maybe my experiments will show me what happen, or someone 
more knowledgeable than me can explain why this is not possible?

Greg.



More information about the Python-list mailing list