Reputation: 16032
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
Upvotes: 4
Views: 1180
Reputation: 16032
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
Upvotes: 2
Reputation: 9701
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.
Upvotes: 1