Alternate numeric proposal

Chris Gonnerman chris.gonnerman at
Mon Jul 23 01:05:26 EDT 2001

I have been following (and participating) in the integer division
argument for some time (and a divisive one it is, too), and while
standing in the shower (really!) an idea came to me.

Why don't we add a hook to Python to control the numeric evaluation
rules directly?

An object containing methods to handle numerical operations would
be registered with a statement like this:

    __builtins__.numerics = MyNumericObject()

Operations involving only builtin types would use the operations
as defined in the given object; a default version would apply if
not given.  The default could be set in, for instance:

    import advanced_math
    __builtins__.numerics = advanced_math.numeric_ops

(where the .numeric_ops is a singleton already instantiated when
the import statement is issued).

Similarly, there could be a standard option for the "tutorial"
mode where integer division yields a float:

    import tutorial_math
    __builtins__.numerics = tutorial_math.numeric_ops

For that matter, the assignment to __builtins__ could be in the
body of the imported module...  (I'm thinking as I type, can you

Now comes the programmer who wants rational arithmetic.  In his/her
program there is a line:

    import rational_math

(near the top of course) and all mathematics in this program return
rationals.  The business major says:

    import fixedpoint_math

and away he/she goes.

The module writer says, HEY, what about me?  I need consistent math
in my module!

Hmmm... I'm not sure here, I must admit.  The module writer could, 
of course, say:

    def module_level_function(args, go, here):
        old_math = __builtins__.numerics
        import advanced_math
        ... some statements go here ...
        __builtins__.numerics = old_math
        return retval

but that is ugly (looks like some Visual Basic I saw last week).

Perhaps Python could look for a variable, say:

    __numerics__ = advanced_math.numerics

in the module scope before looking for the __builtins__.numerics
object; this would allow module writers to declare specific 
requirements for their own modules without harming anyone else.

On second (third?) thought, setting the default in is
probably not a good idea.  Instead, the default should be None,
and "standard" builtin math should be used when 
__builtins__.numerics is None.

This would allow for the following:


    class RationalMathClass:
        ... code goes here ...

    numerics = RationalMathClass()

    if __builtins__.numerics is None:
        __builtins__.numerics = numerics

Thus the first module imported in the program sets the standard 
for the entire environment.

Hmm... I'm still not entirely pleased with this proposal, but
perhaps there is the kernel of a useful idea here.  

More information about the Python-list mailing list