Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to bind arguments to given values in Python functions? [duplicate]

Tags:

python

I have a number of functions with a combination of positional and keyword arguments, and I would like to bind one of their arguments to a given value (which is known only after the function definition). Is there a general way of doing that?

My first attempt was:

def f(a,b,c): print a,b,c  def _bind(f, a): return lambda b,c: f(a,b,c)  bound_f = bind(f, 1) 

However, for this I need to know the exact args passed to f, and cannot use a single function to bind all the functions I'm interested in (since they have different argument lists).

like image 612
user265454 Avatar asked Jul 06 '10 16:07

user265454


People also ask

How do you pass an argument to a function in Python?

Information can be passed into functions as arguments. Arguments are specified after the function name, inside the parentheses. You can add as many arguments as you want, just separate them with a comma.

How do you pass multiple keyword arguments in Python?

In the function, multiple keyword arguments are received as a dictionary whose key is argument name and whose value is its value. It can also be used with positional arguments. By adding ** to a dictionary object when calling a function, you can pass each element to each argument.

What are the two methods of passing arguments to functions in Python?

By default, arguments may be passed to a Python function either by position or explicitly by keyword.

How are arguments passed in Python by value or by reference give an example?

If you pass immutable arguments like integers, strings or tuples to a function, the passing acts like Call-by-value. It's different, if we pass mutable arguments. All parameters (arguments) in the Python language are passed by reference.


2 Answers

>>> from functools import partial >>> def f(a, b, c): ...   print a, b, c ... >>> bound_f = partial(f, 1) >>> bound_f(2, 3) 1 2 3 
like image 60
MattH Avatar answered Oct 03 '22 13:10

MattH


You probably want the partial function from functools.

like image 37
Daniel Roseman Avatar answered Oct 03 '22 11:10

Daniel Roseman