how to overload sqrt in a module?

david mugnai asdrubale at
Fri Mar 3 10:46:09 CET 2006

On Thu, 02 Mar 2006 19:24:48 -0800, mforbes wrote:


> 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).

If I don't misunderstood the problem, you can define an "init" method for
your module_g

(code not tested)

_functions = {}
def init(mathmodule):
  _function['sqrt'] = getattr(mathmodule, 'sqrt', None)

def _get(name):
    return _functions[name]
  except KeyError:
    raise TypeError("you have to initialize module_g")

def sqrt(x):
  return _get('sqrt')(x)

import math
import module_g

print module_g.sqrt(2)


More information about the Python-list mailing list