[Python-ideas] π = math.pi

Nick Coghlan ncoghlan at gmail.com
Sat Jun 3 03:44:07 EDT 2017

On 3 June 2017 at 15:55, Chris Angelico <rosuav at gmail.com> wrote:
> On Sat, Jun 3, 2017 at 3:42 PM, Pavol Lisy <pavol.lisy at gmail.com> wrote:
>> Sorry for probably stupid question! Is something like ->
>>     class A:
>>         def __oper__(self, '⊞', other):
>>             return something(self.value, other)
>>     a = A()
>>     a ⊞ 3
>> thinkable?
> No, because operators need to be defined before you get to individual
> objects, and they need precedence and associativity. So it'd have to
> be defined at the compiler level.
> Also, having arbitrary operators gets extremely confusing. It's not
> easy to reason about code when you don't know what's even an operator.
> Not a stupid question, but one for which the answer is "definitely not
> like that".

A useful background read on this question specifically in the context
of Python is PEP 465 (which added A at B for matrix multiplication), and
in particular its discussion of the rejected alternatives:

For most purposes, the existing set of operators is sufficient, since
we can alias them for unusual purposes (e.g. "/" for path joining in
pathlib) when we don't need access to the more conventional meaning
(division in that case, since "dividing one path segment by another"
is nonsensical) and context makes it possible for the reader to
understand what is going on ("filepath = segment1 / segment2 /
segment3" looks a lot like writing out a filesystem path as a string
and the name of the assignment target makes it clear this is a
filesystem path operation, not a division operation).

Matrix multiplication turned out to be a genuine expection, since all
the other binary operators had well defined meanings as
elementwise-operators, so borrowing one of them for matrix
multiplication meant losing access to the corresponding elementwise
operation, and there typically *weren't* enough hints from the context
to let you know whether "*" was by element or the dot product.


Nick Coghlan   |   ncoghlan at gmail.com   |   Brisbane, Australia

More information about the Python-ideas mailing list