Introduction
Right now if you want to have the Python infix operators as functions, for example for usage as HOFs, the easiest way is to import operator
to get the desired result:
# Using infix notation
1 + 1
# Using operator.py
import operator
operator.add(1, 1)
Why do I care? I am playing around with Hissp, a Lisp that compiles into Python, and the regular operators do not work there. So we spam (operator..add)
to do additions and (operator..sub)
to do subtractions. And it is in this use-case that I run into the problem very quickly.
My problem
One major flaw of the functions is that they are hardcoded to allow only two arguments, which makes them less flexible and more clunky:
# Using infix notation
1 + 2 + 3 + 4
# Using operator.py
from operator import add
add(1, add(2, add(3, 4)))
where it would probably easier to just have
add(1, 2, 3, 4)
Why this behaviour?
Well a quick search of operator.py
shows this:
def add(a, b):
"Same as a + b."
return a + b
How do we fix this?
We just need to be able to handle an arbitrary number of arguments.
Ideally, I would use functools.reduce()
but in order to reduce (no pun intended) the number of modules needed to be imported, a different approach must be taken, a couple of which are possible.
The best way I can see is with a for loop:
def add(*args):
subtotal = args[0]
for i in args[1:]:
subtotal += i
return subtotal
Anyway, this should only be half an hour and a PR away. Please tell me any suggestions on my proposal.
EDIT: Probably should make this a separate library instead