How do I match my functions variable names to the default values using python and inspect?
def foo(x:int,y:int=5) -> int: return a+b
inspect.getfullargspec(foo)
FullArgSpec(args=['x', 'y'], varargs=None, varkw=None, defaults=(4,), kwonlyargs=[], kwonlydefaults=None, annotations={'x': <class 'int'>, 'y': <class 'int'>, 'return': <class 'int'>})
I can get the args and get the defaults, but the aren't 1:1 when you try to line them up.
If you were to zip the two arrays into a dictionary, the x would get mapped to 4 and y isn't mapped to anything. But the result should be y=4.
Thanks
You can use inspect.signature() which returns a Signature object for your function. Then you can easily access to the arguments with their respective annotation and default values.
In [96]: s = inspect.signature(foo)
In [97]: s.parameters
Out[97]: mappingproxy({'x': <Parameter "x: int">, 'y': <Parameter "y: int = 5">})
In [98]: s.parameters['x']
Out[98]: <Parameter "x: int">
In [99]: s.parameters['y']
Out[99]: <Parameter "y: int = 5">
Or separately access to annotation or defaults:
In [106]: s.parameters['y'].annotation
Out[106]: int
In [107]: s.parameters['y'].default
Out[107]: 5
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