Subclassing built-in classes

MonkeeSage MonkeeSage at gmail.com
Thu Oct 5 07:49:57 EDT 2006


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?

Regards,
Jordan




More information about the Python-list mailing list