Given a python function
def func(a, b, *c, **d):
pass
I can get the names of arguments:
>>> print(func.__code__.co_varnames)
('a', 'b', 'c', 'd')
But how do I know, that c is *args and d is **kwargs??
CodePudding user response:
As far as I know, this information is only accessible via the Signature
object returned by inspect.signature
. Where that function gets the information, I do not know. (It may be something stored by the implementation that is not otherwise exposed at the Python level.)
>>> import inspect
>>> inspect.signature(func).parameters['a'].kind
<_ParameterKind.POSITIONAL_OR_KEYWORD: 1>
>>> inspect.signature(func).parameters['c'].kind
<_ParameterKind.VAR_POSITIONAL: 2>
>>> inspect.signature(func).parameters['d'].kind
<_ParameterKind.VAR_KEYWORD: 4>
If you look at the definition of _signature_from_function
, you'll see it determines the kind by looking at the flags in func.__code__.co_objects
and applying some left-to-right logic on the names you see in func.__code__.co_varnames
.