how to overload sqrt in a module?

Steven D'Aprano steve at REMOVETHIScyber.com.au
Fri Mar 3 11:21:01 CET 2006


On Thu, 02 Mar 2006 22:35:51 -0800, Michael McNeil Forbes wrote:

> What I was thinking was: is there some way to pass a parameter to the 
> module on import so that the module can then use the correct environment.
> 
> If I could pass a dictionary to the module with all of the overloaded 
> functions, then they could become part of the module's environment and 
> used appropriately.  I could not find a way of passing such a dictionary.

Not on import, but 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?


-- 
Steven.




More information about the Python-list mailing list