Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find the required arguments of a function object in python?

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
like image 747
Lord Elrond Avatar asked Oct 29 '25 19:10

Lord Elrond


2 Answers

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
like image 140
Lord Elrond Avatar answered Oct 31 '25 09:10

Lord Elrond


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:

Output:

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.
like image 39
S3DEV Avatar answered Oct 31 '25 10:10

S3DEV