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.
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 −
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:
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.
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.
.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']
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With