how to overload sqrt in a module?
mforbes at lns.mit.edu
mforbes at lns.mit.edu
Fri Mar 3 04:24:48 CET 2006
>> 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
I know, but the point is that I want to allow the user of the module to be
able to specify which sqrt function should be used depending on the type
of x. Importing math in the module would prevent the user from using f()
with complex types (or dimensioned types for another example).
That is why I suggested the ugly, but functional solution
module_g.py
-----------
def g(x,a_math):
"""Compute sqrt of x using a_math.sqrt)
return a_math.sqrt(x)
The user can at least specify to use cmath instead of math:
>>> import cmath, module_g
>>> module_g.g(8j,cmath)
(2+2j)
Michael.
More information about the Python-list
mailing list