Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python Argument Binders

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 
like image 631
Dustin Getz Avatar asked Nov 10 '08 14:11

Dustin Getz


People also ask

What is bind () in Python?

In Tkinter, bind is defined as a Tkinter function for binding events which may occur by initiating the code written in the program and to handle such events occurring in the program are handled by the binding function where Python provides a binding function known as bind() where it can bind any Python methods and ...

What is Agrument for Python?

The terms parameter and argument can be used for the same thing: information that are passed into a function. From a function's perspective: A parameter is the variable listed inside the parentheses in the function definition. An argument is the value that are sent to the function when it is called.

What is Variadic function in Python?

Variadic parameters (Variable Length argument) are Python's solution to that problem. A Variadic Parameter accepts arbitrary arguments and collects them into a data structure without raising an error for unmatched parameters numbers.


2 Answers

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) 
like image 122
Jeremy Avatar answered Oct 11 '22 18:10

Jeremy


I'm not overly familiar with boost::bind, but the partial function from functools may be a good start:

>>> from functools import partial  >>> def f(a, b): ...     return a+b  >>> p = partial(f, 1, 2) >>> p() 3  >>> p2 = partial(f, 1) >>> p2(7) 8 
like image 28
Matthew Trevor Avatar answered Oct 11 '22 19:10

Matthew Trevor