Search code examples
pythonsignatureinspect

How to check if default value for python function argument is set using inspect?


I'm trying to identify the parameters of a function for which default values are not set. I'm using inspect.signature(func).parameters.value() function which gives a list of function parameters. Since I'm using PyCharm, I can see that the parameters for which the default value is not set have their Parameter.default attribute set to inspect._empty. I'm declaring the function in the following way:

def f(a, b=1):
    pass

So, the default value of a is inspect._empty. Since inspect._empty is a private attribute, I thought that there might be a method for checking if a value is inspect._empty, but I couldn't find it.


Solution

  • You can do it like this:

    import inspect
    
    
    def foo(a, b=1):
        pass
    
    
    for param in inspect.signature(foo).parameters.values():
        if param.default is param.empty:
            print(param.name)
    

    Output:

    a
    

    param.empty holds the same object inspect._empty. I suppose that this way of using it is recommended because of the example in the official documentation of inspect module:

    Example: print all keyword-only arguments without default values:
    
    >>>
    >>> def foo(a, b, *, c, d=10):
    ...     pass
    
    >>> sig = signature(foo)
    >>> for param in sig.parameters.values():
    ...     if (param.kind == param.KEYWORD_ONLY and
    ...                        param.default is param.empty):
    ...         print('Parameter:', param)
    Parameter: c