[Python-ideas] Infix application of binary functions

Carl M. Johnson cmjohnson.mailinglist at gmail.com
Thu Jul 22 05:34:12 CEST 2010


This can be done in Python today:

>>> class Infix(object):
...     def __init__(self, func):
...         self.func = func
...         self.arg1 = self.arg2 = self.not_set = object()
...
...     def __radd__(self, arg1):
...         self.arg1 = arg1
...         if self.arg2 is self.not_set:
...             return self
...         else:
...             return self.func(self.arg1, self.arg2)
...
...     def __add__(self, arg2):
...         self.arg2 = arg2
...         if self.arg1 is self.not_set:
...             return self
...         else:
...             return self.func(self.arg1, self.arg2)
...
>>> @Infix
... def add(one, two):
...     return one + two
...
>>> @Infix
... def mul(one, two):
...     return one * two
...
>>> @Infix
... def power(one, two):
...     return one ** two
...
>>> 1 + add + 1
2
>>> 2 + mul + 2
4
>>> 3 + power + 3
27

Enjoy.

-- Carl Johnson



More information about the Python-ideas mailing list