how to overload sqrt in a module?

Michael McNeil Forbes mforbes at lnsDOTmit.edu
Fri Mar 3 01:49:11 EST 2006


> On Thu, 2 Mar 2006 16:12:53 -0800, Michael McNeil Forbes wrote:
>
>> 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.
>>
On Fri, 3 Mar 2006, Dennis Lee Bieber wrote:
> 	Since Python doesn't dispatch based on parameter types, there are
> only two choices that I can see...
>
> 	Either the CALLER already knows what the arguments are, and has
> coded an explicit call to the version of the function desired...

The caller does know in my case, but wants to reuse old code that performs 
a complicated computation using the standard math functions.  I was 
thinking that maybe there was some way for the caller to pass the 
appropriate functions to the module on import, but could not find a way of 
doing this.

> 	OR, the caller imports and calls your special module, and your
> special module has to import ALL possible override modules and supply a
> function that determines which of the modules is to be used...

This is essentially what numpy.sqrt() etc. does as pointed out by Robert 
Kern.  The numpy.sqrt() seems to check if the argument is real, complex, 
or some other type and calls either math.sqrt, cmath.sqrt or x.sqrt() 
appropriately.  This works for my problem: I just wondered if there was a 
more generic solution without having to do this work.

Thanks,
Michael.



More information about the Python-list mailing list