Reputation:
How can I know if a parameter is positional-only or not? To be more specific, I just want a function to tell me a
is a positional-only parameter, while b
is not, as in the following example.
from inspect import getfullargspec
from typing import get_type_hints
def add(a: int, /, b: int):
raise NotImplementedError
print(get_type_hints(add))
# {'b': <class 'int'>, 'a': <class 'int'>}
print(getfullargspec(add))
# FullArgSpec(args=['a', 'b'], varargs=None, varkw=None, defaults=None, kwonlyargs=[], kwonlydefaults=None, annotations={'a': <class 'int'>, 'b': <class 'int'>})
I have tried get_type_hints
and getfullargspec
, but seems none of them return relevant information.
Upvotes: 3
Views: 367
Reputation: 5560
You can inspect the signature via the following, which I based on a similar example in the docs:
import inspect
signature = inspect.signature(add)
positional_only_args = [param
for param in signature.parameters.values()
if param.kind == param.POSITIONAL_ONLY]
# [<Parameter "a: int">]
If you want strictly the name of the parameter, then you can use param.name
.
Upvotes: 5