how to overload sqrt in a module?

Michael McNeil Forbes mforbes at lnsDOTmit.edu
Sun Mar 5 02:07:12 EST 2006


On Fri, 3 Mar 2006, Steven D'Aprano wrote:

> ... you can do this:
>
> import my_module
> my_module.set_environment("math") # or cmath, or numeric, or whatever
>
> Your my_module will be like this:
>
> # Warning: untested code.
> ENVIRON = None  # global variables sometimes have their uses
>
> def f(x):
>    if ENVIRON is None:
>        raise ValueError("Uninitialised module!")
>        # or use a custom exception
>    return ENVIRON.sqrt(x)
>
> def set_environment(name):
>    global ENVIRON
>    ENVIRON = __import__(name)
>
>
> Does this help?

Yes.  However, this raises a question: Is this any different than 
directly modifying the globals, or is it just syntactic sugar.

import math as my_math

def set_environment(name):
     globals()['ENVIRON'] = __import__(name)

Thanks,
Michael.



More information about the Python-list mailing list