Python 3.2 documentation refers to Collin Winter's functional module which contains function compose:
The compose() function implements function composition. In other words, it returns a wrapper around the outer and inner callables, such that the return value from inner is fed directly to outer.
Unfortunately, this module hasn't been updated since July 2006; I wonder if there's any replacement available.
For now, I only need compose function. Is the following original functional.compose definition still good for Python 3?
def compose(func_1, func_2, unpack=False):
"""
compose(func_1, func_2, unpack=False) -> function
The function returned by compose is a composition of func_1 and func_2.
That is, compose(func_1, func_2)(5) == func_1(func_2(5))
"""
if not callable(func_1):
raise TypeError("First argument to compose must be callable")
if not callable(func_2):
raise TypeError("Second argument to compose must be callable")
if unpack:
def composition(*args, **kwargs):
return func_1(*func_2(*args, **kwargs))
else:
def composition(*args, **kwargs):
return func_1(func_2(*args, **kwargs))
return composition
This SO question is somewhat related; it asks whether Python should support special syntax for compose.
callablebuilt in keyword - it is usually replaced withhasattr(obj, "__call__")otherwise, the code above should work.callable()was added back to the language in 3.2.callable, but if you're happy with 3.2, just copy, paste and credit.functionalmodule has a replacement in Python 3.functionalto Py3, I slapped one together at github. But I ran into a problem with the copyright/license stuff that stalled me. I think it might be easier to reimplement it from scratch.