[Python-ideas] Infix functions
Steven D'Aprano
steve at pearwood.info
Sun Feb 23 02:23:06 CET 2014
On Sat, Feb 22, 2014 at 08:34:51PM +0100, Hannu Krosing wrote:
> Why not use multiple "operator characters" for user-defined infix
> operators, like postgreSQL does ?
>
> a *% b ++ c *% (d *. e)
How would that work in Python? Give an example (a toy or pretend example
is fine) for how I would define an operator ^& for ints.
> We could even define that the characters in the combined operator define
> precendece so the
> above could be written as
Who is "we"? The programmer of the module, or the Python core devs? In
other words, are the precedences set once, in the language, or in each
module that uses them?
If I import an object x from one module with precedences set one way,
and an object y from another module with precedences set another way,
and try to use them in the same expression, whose precedences win?
An unrelated thought: there are currently eight ASCII symbols used for
non-comparison operators in Python: ~%^&*-+/ (did I miss any?). Of
those, three can be used as unary operators ~-+ and so should not be
allowed in the second position. So with eight symbols available in the
first position, and five in the second, that gives us 40 new infix
operators. But one of them ** is already used, so 39.
To my mind, 39 arbitrary infix operators is both too many and too few.
Too many, because, really, who needs 39 new infix operators? Who will
remember them all? But too few, because it means that when you want a
new operator, you have to force it into one of those 39 (48 if you can
re-use one of existing operators, 52 if you include comparison operators
> >= < <= but not equality and inequality). For example, I'd like to use
∪ and ∩ for set union and intersection, but instead those two operations
get mapped to & and | and I can never remember which is which. I'd like
to use operators such as ⊕ ⊗. But so long as Python operators are ASCII
only, that cannot happen.
But then, I have a mathematics background. I'm having trouble thinking
of examples outside of maths where I would want to define infix
operators at all, instead of just using a method or function.
--
Steven
More information about the Python-ideas
mailing list