Code design for a sub-class of built-ins

Steven D'Aprano steve at REMOVETHIScyber.com.au
Wed Jul 5 02:00:05 EDT 2006


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.


>>     def __len__(self):
>>         if self == self.magic:
>>             print "Nobody expects the Spanish Inquisition!"
>>         return str.__len__(self)
>>     def upper(self):
>>         if self == self.magic:
>>             print "Nobody expects the Spanish Inquisition!"
>>         return str.upper(self)
>>     # and so on for every last string method...
> 
> My my my....

Exactly. Don't think I don't know this is a horrible strategy -- that's
why I'm asking for ideas for a better way to do it *wink*


>> The obvious problem is, I have to create a custom method for every
>> string method --
> 
> which makes subclassing almost useless - except to pass isinstance()
> tests.

Yep.


>> and if strings gain any new methods in some future version of Python,
>> my subclass won't exhibit the correct behaviour.
> 
> 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.


Thanks,


-- 
Steven.




More information about the Python-list mailing list