pythonargumentsinspect

How can I read a function's signature including default argument values?


Given a function object, how can I get its signature? For example, for:

def my_method(first, second, third='something'):
    pass

I would like to get "my_method(first, second, third='something')".


Solution

  • import inspect
    
    def foo(a, b, x='blah'):
        pass
    
    print(inspect.signature(foo))
    # (a, b, x='blah')
    

    Python 3.5+ recommends inspect.signature().