Fix Python – How can I read a function’s signature including default argument values?

Question

Asked By – Spì

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')".

Now we will see solution for issue: How can I read a function’s signature including default argument values?


Answer

import inspect

def foo(a, b, x='blah'):
    pass

print(inspect.signature(foo))
# (a, b, x='blah')

Python 3.5+ recommends inspect.signature().

This question is answered By – unutbu

This answer is collected from stackoverflow and reviewed by FixPython community admins, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0