Jim Jeffries
Jim Jeffries

Reputation: 10081

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.

Upvotes: 10

Views: 7290

Answers (2)

Sakari Cajanus
Sakari Cajanus

Reputation: 467

You can use partial.func.__code__.co_varnames:

import functools

p = functools.partial(lambda a, b: a > b, {a: 1})

print(p.args)
# ({'a': 1},)

print(p.func.__code__.co_varnames)
# ('a', 'b')

Upvotes: 0

Katriel
Katriel

Reputation: 123742

.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']

Upvotes: 8

Related Questions