Code design for a sub-class of built-ins

Bruno Desthuilliers onurb at xiludom.gro
Wed Jul 5 05:41:47 EDT 2006


Steven D'Aprano wrote:
> On Tue, 04 Jul 2006 19:26:36 +0200, Bruno Desthuilliers wrote:
> 
> 
>>Steven D'Aprano wrote:
>>
>>>I'm having problems with sub-classes of built-in types.
>>>
>>>Here is a contrived example of my subclass. It isn't supposed
>>>to be practical, useful code, but it illustrates my problem.
>>>
>>>class MyStr(str):
>>>    """Just like ordinary strings, except it exhibits special behaviour
>>>    for one particular value.
>>>    """
>>>    magic = "surprise"
>>
>>>    def __init__(self, value):
>>>        str.__init__(self, value)
>>
>>You don't need to override __init__ here.
> 
> 
> Perhaps not, but in a more realistic example I might need to.

Perhaps, but I can only comment on the example you gave !-)
Also, *you* are aware of this, but please keep in mind that cl.py is
read by a lot of newbies.

(snip)

>>You could replace subclassing by composition/delegation using the
>>__getattr__ hook, but this would break tests on type/class :(
>>
>>Or you could keep subclassing and use the __getattribute__ hook, but
>>this is more tricky and IIRC may have negative impact on lookup perfs.
>>
>>Or you could use a metaclass to decorate (appropriate) str methods with
>>a decorator doing the additional stuff.
>>
>>choose your poison !-)
> 
> 
> Interesting... That will give me something to experiment with.

AFAICT, the last solution is probably the better of the three (well, at
least it's the better I can think of actually).

For the record, care to give more informations about your real use case?

-- 
bruno desthuilliers
python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in 'onurb at xiludom.gro'.split('@')])"



More information about the Python-list mailing list