Overriding builtin types

Discussion in 'Python' started by Lonnie Princehouse, Mar 5, 2004.

  1. 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
    Lonnie Princehouse, Mar 5, 2004
    #1
    1. Advertising

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

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. =?ISO-8859-1?Q?BJ=F6rn_Lindqvist?=

    subclassing builtin types

    =?ISO-8859-1?Q?BJ=F6rn_Lindqvist?=, Oct 8, 2004, in forum: Python
    Replies:
    2
    Views:
    3,490
    Alex Martelli
    Oct 8, 2004
  2. Raja Raman Sundararajan

    Overriding builtin getattr method

    Raja Raman Sundararajan, Oct 3, 2006, in forum: Python
    Replies:
    4
    Views:
    358
    Raja Raman Sundararajan
    Oct 3, 2006
  3. =?iso-8859-1?q?Erik_Wikstr=F6m?=

    Pointer to operator for builtin types

    =?iso-8859-1?q?Erik_Wikstr=F6m?=, Dec 15, 2006, in forum: C++
    Replies:
    6
    Views:
    373
    =?iso-8859-1?q?Erik_Wikstr=F6m?=
    Dec 15, 2006
  4. Colin J. Williams
    Replies:
    1
    Views:
    264
    Michael Amrhein
    Aug 15, 2007
  5. bdb112
    Replies:
    2
    Views:
    300
    Chris Torek
    Jul 2, 2011
Loading...

Share This Page