Python Argument Binders

Dustin Getz picture Dustin Getz · Nov 10, 2008 · Viewed 28k times · Source

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

Answer

Jeremy picture Jeremy · Nov 10, 2008

functools.partial returns a callable wrapping a function with some or all of the arguments frozen.

import sys
import functools

print_hello = functools.partial(sys.stdout.write, "Hello world\n")

print_hello()
Hello world

The above usage is equivalent to the following lambda.

print_hello = lambda *a, **kw: sys.stdout.write("Hello world\n", *a, **kw)