I have a function, f:
def f(required_arg, optional_arg=None):
pass
How can I return a list of required argument names of f?
Using isinstance on the results of inspect.signature doesn't seem to work:
>>> import inspect
>>> params = inspect.signature(f).parameters
>>> for arg_name, v in params.items():
>>> print(v.default)
>>> print(arg_name, isinstance(v.default, inspect._empty))
>>> print(arg_name, isinstance(v.default, inspect.Parameter.empty))
<class 'inspect._empty'>
required_arg False
required_arg False
None
optional_arg False
optional_arg False
You should be using is instead of isinstance:
>>> import inspect
>>> params = inspect.signature(f).parameters
>>> for arg_name, v in params.items():
>>> print(v.default is inspect._empty)
True
False
Here is an example of what @GreenCloakGuy is referring to in his comment:
def f(required_arg, optional_arg=None):
"""Directive on what this function is intended to accomplish.
Args:
required_arg (str): Argument used to ... thing.
optional_arg (str): Argument used to ... other thing.
"""
pass
Calling help(f) will produce this output for the user:
Help on function f in module __main__:
f(required_arg, optional_arg=None)
Directive on what this function is intended to accomplish.
Args:
required_arg (str): Argument used to ... thing.
optional_arg (str): Argument used to ... other thing.
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