Python feature request : operator for function composition

Dustan DustanGroups at gmail.com
Mon Feb 4 10:00:30 EST 2008


On Feb 2, 11:09 pm, Kay Schluehr <kay.schlu... at gmx.net> wrote:
[snip]

While you're waiting for it to be implemented, you can build your own
version as a decorator. Here's an example written in haste:

>>> class composer(object):
	def __init__(self, *funcs):
		self.funcs = funcs
	def __and__(self, other):
		if isinstance(other, composer):
			return composer(*(self.funcs+other.funcs))
		else:
			return composer(*(self.funcs+(other,)))
	def __call__(self, *args, **kargs):
		for func in reversed(self.funcs):
			args = (func(*args, **kargs),)
			if kargs:
				kargs = {}
		return args[0]


>>> @composer
def double(x):
	return 2*x

>>> @composer
def square(x):
	return x*x

>>> double_square = double & square
>>> square_double = square & double
>>> double_square(2)
8
>>> square_double(2)
16
>>> double_square(3)
18
>>> square_double(3)
36
>>> double_square(4)
32
>>> square_double(4)
64

Probably not the best implementation, but you get the idea.



More information about the Python-list mailing list