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)
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With