how to overload sqrt in a module?
Michael McNeil Forbes
mforbes at nt05.phys.washington.edu
Fri Mar 3 01:12:53 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:
""" Compute sqrt of x """
>>> from math import *
>>> import module_f
Traceback (most recent call last):
File "<stdin>", line 1, in ?
File "module_f.py", line 2, in f
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:
>>> import math, cmath, module_g
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
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?
More information about the Python-list