how to overload sqrt in a module?

Kent Johnson kent at kentsjohnson.com
Thu Mar 2 20:58:11 EST 2006


Michael McNeil Forbes wrote:
> I would like to write a module that provides some mathematical functions 
> on top of those defined in math, cmath etc. but I would like to make it 
> work with "any" type that overloads the math functions.
> 
> Thus, I would like to write:
> 
> module_f.py
> ----
> def f(x):
>    """ Compute sqrt of x """
>    return sqrt(x)
> 
>>>> from math import *
>>>> import module_f
>>>> module_f.f(3)
> 
> Traceback (most recent call last):
>    File "<stdin>", line 1, in ?
>    File "module_f.py", line 2, in f
>      return sqrt(x)
> NameError: global name 'sqrt' is not defined
> 
> I understand why sqrt is not in scope, but my question is: what is the 
> best way to do this?

You need to import math in the module that uses it. Imports in one 
module don't (in general) affect the variables available in another module.

module_f.py
----
from math import sqrt # more explicit than from math import *
def f(x):
    """ Compute sqrt of x """
    return sqrt(x)

Kent



More information about the Python-list mailing list