Paul Sokolovsky writes:
> I'd encourage everyone who thinks "I need a very special operator
> just for me",
I don't think anybody who posts here thinks that, though. They think
"wow, I could really use this, and I bet other people too."
math.isclose probably tempts somebody somewhere in the world about
once a minute. Of course they often find out differently -- and
mostly when they do, they're OK with that. (There are also joke or
half-joke proposals, but that's a different thing, and we're all in on
those jokes.)
> instead think in terms "Python needs ability to define custom
> operators".
Reading that *literally* (I take it seriously, below): Python has that
ability already. It's just that the set of operator *symbols* is
fixed (in a given version of Python), and almost exhausted for
numerical types (but see below ;-). This has an important implication
for readability: the associativity and precedence order of the symbols
is also fixed, and only needs to be learned once.[1]
If you always want isclose behavior for float "equality", you can't
monkey patch (and you don't want to, I think), but you can subclass:
import math
class Real(float):
exact_eq = float.__eq__
def__eq__(self, other):
return math.isclose(self, other)
or
class AltReal(float):
def __matmul__(self, other): # is self at other? close enuff!
return math.isclose(self,other)
Getting serious, as promised: Of course there will be work to do
ensuring that all floats (more likely, all numbers) are converted to
Reals in each entry point of the module, and probably a lot of
duplication where "_private" versions of functions don't do the
conversion, and "public" versions of them do. That could be avoided
with custom operator symbols in many cases.
But imposing this work is a deliberate choice of the language
designers, for readability reasons, and maybe others. Perhaps it
should be reconsidered, but I'm quite conservative on this one.
> Recent example: implementation of "from __future__ import braces":
> https://github.com/NeKitDS/braces.py .
I strongly recommend the idiom:
import __future__ as __watch_out_for_jokes__
(Recent? Isn't that more than a decade old? Hmmm:
>>> from __future__ import braces
File "<stdin>", line 1
SyntaxError: not a chance
Different implementation, I guess. :-D :-þ :-D :-þ :-D :-þ :-D)
Steve
Footnotes:
[1] This is not always a benefit. Occasionally there's a
conventional assignment of symbols to operations where the "natural"
behavior of the operations doesn't fit well with the associativity and
precedence of the operators of 3rd grade arithmetic. But as a rule
it's helpful.
_______________________________________________
Python-ideas mailing list -- [email protected]
To unsubscribe send an email to [email protected]
https://mail.python.org/mailman3/lists/python-ideas.python.org/
Message archived at
https://mail.python.org/archives/list/[email protected]/message/BVZNVCAQCLPPSXU7JWQCQJJKEJCFB33F/
Code of Conduct: http://python.org/psf/codeofconduct/