Overriding builtin types

Lonnie Princehouse fnord at u.washington.edu
Fri Mar 5 20:53:53 CET 2004

Dear gurus-at-large,

Does anyone know if there's a mechanism to make the interpreter use
user-defined classes for interpreting literals, instead of the builtin

For instance, wouldn't it be cool if the following code raised an

class IllegalValue(Exception): pass

class NaturalNumber(int):
  base_init = int.__init__
  one = 1
  def __init__(self, value):
    NaturalNumber.base_init(self, value)
    if self < NaturalNumber.one:
      raise IllegalValue

__builtins__.int = NaturalNumber

print -1

I realize that there are other ways to do this, e.g. print
NaturalNumber(-1), but the above just seems like it would be much more

Right now the only way I can see of doing it is to tack on a
pre-interpreter that will substitute LITERAL ->
ArbitraryFunction(LITERAL) implicitly, but that's a lot of effort and
hardly efficient...


More information about the Python-list mailing list