how to overload sqrt in a module?

Michael McNeil Forbes mforbes at lnsDOTmit.edu
Sun Mar 5 01:52:50 EST 2006


On Fri, 3 Mar 2006, david mugnai wrote:

[snip]
>
> If I don't misunderstood the problem, you can define an "init" method for
> your module_g
>
> (code not tested)
>
> module_g.py
> -----------
>
> _functions = {}
> def init(mathmodule):
>  _function['sqrt'] = getattr(mathmodule, 'sqrt', None)
>
> def _get(name):
>  try:
>    return _functions[name]
>  except KeyError:
>    raise TypeError("you have to initialize module_g")
>
> def sqrt(x):
>  return _get('sqrt')(x)
>
> main.py
> -------
>
> import math
> import module_g
>
> module_g.init(math)
> print module_g.sqrt(2)

Thanks, this gets me close.  Is there anything really bad about the 
following?  It works exactly as I would like, but I don't want to get in 
trouble down the road:

module_f
--------
import math as my_math

def set_math(custom_math):
     globals()['my_math'] = custom_math

def f(x):
     return my_math.sqrt(x)

>>> import module_f
>>> module_f.f(2)
1.4142135623730951
>>> import cmath
>>> module_f.set_math(cmath)
>>> module_f.f(2j)
(1+1j)

Or, if one wants to use the "from __ import *" form:

from math import *

def set_math(custom_math):
     globals().update(custom_math.__dict__)

def f(x):
     return sqrt(x)

Michael



More information about the Python-list mailing list