Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python get arguments for partial functions

I am looking to do something similar to what was asked here Getting list of parameter names inside python function, but using partial functions. ie. I need to get the possible arguments for a partial function. I can get the keyword arguments using:

my_partial_func.keywords

but I am currently struggling to get the non-keyword arguments. The inspect module also yields nothing for this particular case. Any suggestions would be great.

like image 755
Jim Jeffries Avatar asked May 23 '11 13:05

Jim Jeffries


People also ask

What is the use of partial in Python?

Partial is a higher order function which takes a function as input (like map and filter) but it also returns a function that can be used in the same way as any other function in your program. We can also use partial on object methods, for e.g. to generate a list of default strings −

What happens when you pass multiple arguments to a partial object?

If you pass more arguments to a partial object, Python appends them to the args argument. When you pass additional keyword arguments to a partial object, Python extends and overrides the kwargs arguments. Therefore, it’s possible to call the double like this:

What is a partial function in C++?

Partial functions allow one to derive a function with x parameters to a function with fewer parameters and fixed values set for the more limited function. This code will return 8. An important note: the default values will start replacing variables from the left. The 2 will replace x. y will equal 4 when dbl (4) is called.

What is a double function in Python?

In Python, the double function is called a partial function. In practice, you use partial functions when you want to reduce the number of arguments of a function to simplify the function’s signature.


1 Answers

.args contains the arguments passed to the partial function. If you want to get the arguments that the original function expects, use the inspect solution you linked on the .func attribute.

You can find this out by calling dir on a functools.partial object:

>>> dir(x)
['__call__', '__class__', '__delattr__', '__dict__', '__doc__', '__format__', '__getattribute__', '__hash__', '__init__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'args', 'func', 'keywords']
like image 176
Katriel Avatar answered Sep 19 '22 17:09

Katriel