Get names of positional arguments from function

2019-05-07 05:11发布

问题:

Using Python 3.x, I'm trying to get the name of all positional arguments from some function i.e:

def foo(a, b, c=1):
    return

Right now I'm doing this:

from inspect import signature, _empty
args =[x for x, p in signature(foo).parameters.items() if p.default == _empty]

When the function alows *args i.e:

def foo(a, b, c=1, *args):
    return

I'm adding the line:

args.remove("args")

I was wondering if there is a better way to achieve this.


As suggested by Jim Fasarakis-Hilliard one better way to deal with *args case is using Parameter.kind:

from inspect import signature, Parameter
args =[]
for x, p in signature(foo).parameters.items():
    if p.default == Parameter.empty and p.kind != Parameter.VAR_POSITIONAL:
        args.append(x)

回答1:

Yes, you can achieve a more robust solution by additionally checking if the .kind attribute of the parameter is not equal to Parameter.VAR_POSITIONAL.

For *args, this is the value that is set when you build the signature object from a function:

>>> def foo(a, b, c=1, *args): pass
>>> print(signature(foo).parameters['args'].kind)
VAR_POSITIONAL

So just import Parameter from inspect and add or the condition that kind != Parameter.VAR_POSITIONAL:

>>> from inspect import Parameter
>>> Parameter.VAR_POSITIONAL == p['args'].kind
True