Overriding builtin types

  • Thread starter Lonnie Princehouse
  • Start date
L

Lonnie Princehouse

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
types?

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

--------------------
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
elegant.

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...



-ljp
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,579
Members
45,053
Latest member
BrodieSola

Latest Threads

Top