how to overload sqrt in a module?

Michael McNeil Forbes mforbes at nt05.phys.washington.edu
Thu Mar 2 19:12:53 EST 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?

Here is one fairly ugly solution:

module_g.py
-----------
def g(x,math):
    return math.sqrt(x)

>>> import math, cmath, module_g
>>> module_g.g(2,math)
1.4142135623730951
>>> module_g.g(-2,cmath)
1.4142135623730951j

I am sure there is a better way of doing this that makes use of the 
type of the argument (Dynamical scoping would solve the 
problem but we don't want to go there...).  Note that the following 
function would work fine

def f(x):
    return abs(x)

because of the special member __abs__ attached to the type.  There is no 
corresponding member for sqrt, sin etc.

What is the "proper" pythonic way to do this?

Michael.



More information about the Python-list mailing list