M
Michael McNeil Forbes
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)
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)
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.
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)
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)
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.