Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to inspect positional-only parameters?

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.


1 Answers

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.

like image 60
Kraigolas Avatar answered Dec 22 '25 10:12

Kraigolas



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!