[Python-ideas] Add additional special method lookups to math module

Masklinn masklinn at masklinn.net
Wed Nov 9 21:15:25 CET 2011


On 2011-11-09, at 21:06 , Jeremy Sanders wrote:
> Case Van Horsen wrote:
>> Currently the functions round(), math.ceil(), math.floor(), and
>> math.trunc() all check for the existence of a special method
>> (__round__, __ceil__, __floor__, and __trunc__). Would it be possible
>> to enhance the math and cmath modules to check for the existence of a
>> special method for (almost) functions? For example, math.sin(obj)
>> would first check for obj.__sin__.
> 
> Wouldn't duct typing the functions in math and cmath be equivalent and 
> wouldn't slow down normal users?
> 
> Howver, I'm not convinced that it's very nice changing the behaviour of 
> built-in modules depending on the presence another module anyway, I'd just 
> supply another module with the same api - people could always mess around 
> with the import path if they really want to override the default.
> 
> import math
> 
> def mysin(x):
>   xxxx
> math.sin = mysin
> 
> Jeremy
> 
This would mean custom numerical types wouldn't be drop-in compatible with existing numerical *code*, which I am under the impression is what Case Van Horsen wants (and is a desirable outcome).

Furthermore, your second paragraph is not correct: Case does not propose "changing the behavior of built-in modules depending on the presence of another module", Case proposes adding *method hooks* to existing math and cmath functions. These would be protocols allowing custom numerical types to implement `math`/`cmath`'s operation in a sensible manner, as is already possible for four methods he mentions, as well as a number of other Python operations[0], including prominent numerical ones[1].

[0] http://docs.python.org/reference/datamodel.html
[1] http://docs.python.org/reference/datamodel.html#emulating-numeric-types


More information about the Python-ideas mailing list