How can I bind arguments to a Python method to store a nullary functor for later invocation? Similar to C++'s boost::bind
.
For example:
def add(x, y):
return x + y
add_5 = magic_function(add, 5)
assert add_5(3) == 8
How can I bind arguments to a Python method to store a nullary functor for later invocation? Similar to C++'s boost::bind
.
For example:
def add(x, y):
return x + y
add_5 = magic_function(add, 5)
assert add_5(3) == 8
functools.partial
returns a callable wrapping a function with some or all of the arguments frozen.The above usage is equivalent to the following
lambda
.I'm not overly familiar with boost::bind, but the
partial
function fromfunctools
may be a good start:If
functools.partial
is not available then it can be easily emulated:Or
This would work, too:
Functors can be defined this way in Python. They're callable objects. The "binding" merely sets argument values.
You can do things like
lambdas allow you to create a new unnamed function with less arguments and call the function!
edit
https://docs.python.org/2/library/functools.html#functools.partial
if you are planning to use named argument binding in the function call this is also applicable:
Note though that