Subclassing built-in classes

Maric Michaud maric at aristote.info
Thu Oct 5 10:59:59 EDT 2006


Le jeudi 05 octobre 2006 15:52, Steve Holden a écrit :
> > But what prevents to interpret literals as a call to __builtins__ objects
> > and functions ? optimization ? what else ?
>
>
> When are literals interpreted? During translation into bytecode.

agreed, but what's the problem with this ?

We can actually monkey patch all buitins like in this example :

In [1]: oldstr=str

In [2]: class mystr(str) :
   ...:     def __new__(*a, **kw) :
   ...:         print 'called : ', a, kw
   ...:         return oldstr.__new__(*a, **kw)
   ...:
   ...:

In [3]: import __builtin__

In [4]: __builtin__.str = mystr
called :  (<class '__main__.mystr'>, <ItplNS 'In 
[${self.cache.prompt_count}]: ' >) {}
called :  (<class '__main__.mystr'>, 5) {}
...


If the generated bytecode of {k:v} is more or less the same as the one 
gernerated by dict(((k,v))), monkey patching dict will work for dict literals 
too.

Also, this should work with scalars,  'a string' be translated in what 
actually is produced by str('a string') (of course the internal code for 
building scalars should still be there).

If that is feasible without big refactoring and do not introduce noticeable 
performance loss is what I don't know, but it could be a nice feature of 
__builtin__ module IMO (at less I expected it to work like this when I first 
tried it).

-- 
_____________

Maric Michaud
_____________

Aristote - www.aristote.info
3 place des tapis
69004 Lyon
Tel: +33 426 880 097



More information about the Python-list mailing list