Get names of positional arguments from function's signature

醉酒当歌 提交于 2019-12-10 09:31:51

问题


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


来源:https://stackoverflow.com/questions/42352703/get-names-of-positional-arguments-from-functions-signature

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!