Subclassing built-in classes

Steve Holden steve at holdenweb.com
Thu Oct 5 08:20:43 EDT 2006


MonkeeSage wrote:
> I know that python doesn't allow extending built-in objects like the
> str class; but you can subclass them using a class of the same name and
> thus shadow them to get the same general effect (albeit you have to use
> the explicit constructor rather than literals).
> 
> class str(str):
>   def display(self):
>     print self
> str('blah').display()
> 
> I was just playing around and realized that assigning to
> __builtins__.str (or if you prefer sys.modules['__builtin__'].str) has
> the same effect.
> 
> class mystr(str):
>   def display(self):
>     print self
> __builtins__.str = mystr
> str('blah').display()
> 
> So that made me wonder...couldn't python (in theory) allow for literals
> to use extended classes by using the object in __builtins__.<class> as
> the class for literals? By default it would be the standard base class,
> but it could also be a custom subclass. Would that be possible / easy /
> worthwhile to do?
> 
Unfortunately the literals are interpreted during bytecode generation, 
before the compiled program is available, and your modifications to 
__builtns__ haven't been made, so the answer is "no", I'm afraid.

regards
  Steve
-- 
Steve Holden       +44 150 684 7255  +1 800 494 3119
Holden Web LLC/Ltd          http://www.holdenweb.com
Skype: holdenweb       http://holdenweb.blogspot.com
Recent Ramblings     http://del.icio.us/steve.holden




More information about the Python-list mailing list