Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get names of positional arguments from function's signature

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)
like image 385
David de la Iglesia Avatar asked Feb 20 '17 19:02

David de la Iglesia


1 Answers

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
like image 57
Dimitris Fasarakis Hilliard Avatar answered Sep 21 '22 11:09

Dimitris Fasarakis Hilliard