Frage

If I have a function or a method, can I find which parameters are "pre-assigned?" E.g. If I write

 def action(one, two, three=3): pass

can I get list of the parameters that have an assignment operator in them? In this case, of course it would be

 ['three']

I think the answer may lie with inspect. inspect.getargspec(action) is really close as it returns a tuple of the default arguments, but it doesn't say to which parameter each argument belongs.

War es hilfreich?

Lösung

From the inspect.getargspec() documentation:

defaults is a tuple of default argument values or None if there are no default arguments; if this tuple has n elements, they correspond to the last n elements listed in args.

Emphasis mine.

So, to match your defaults to the arguments, use:

dict(zip(argspec.args[-len(argspec.defaults):], argspec.defaults))

to get a dictionary mapping argument names to their defaults:

>>> import inspect
>>> def action(one, two, three=3): pass
... 
>>> argspec = inspect.getargspec(action)
>>> dict(zip(argspec.args[-len(argspec.defaults):], argspec.defaults))
{'three': 3}
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top