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

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


import inspectdef foo(a, b, x='blah'):    passprint(inspect.getargspec(foo))# ArgSpec(args=['a', 'b', 'x'], varargs=None, keywords=None, defaults=('blah',))

However, note that inspect.getargspec() is deprecated since Python 3.0.

Python 3.0--3.4 recommends inspect.getfullargspec().

Python 3.5+ recommends inspect.signature().


Arguably the easiest way to find the signature for a function would be help(function):

>>> def function(arg1, arg2="foo", *args, **kwargs): pass>>> help(function)Help on function function in module __main__:function(arg1, arg2='foo', *args, **kwargs)

Also, in Python 3 a method was added to the inspect module called signature, which is designed to represent the signature of a callable object and its return annotation:

>>> from inspect import signature>>> def foo(a, *, b:int, **kwargs):...     pass>>> sig = signature(foo)>>> str(sig)'(a, *, b:int, **kwargs)'>>> str(sig.parameters['b'])'b:int'>>> sig.parameters['b'].annotation<class 'int'>


#! /usr/bin/env pythonimport inspectfrom collections import namedtupleDefaultArgSpec = namedtuple('DefaultArgSpec', 'has_default default_value')def _get_default_arg(args, defaults, arg_index):    """ Method that determines if an argument has default value or not,    and if yes what is the default value for the argument    :param args: array of arguments, eg: ['first_arg', 'second_arg', 'third_arg']    :param defaults: array of default values, eg: (42, 'something')    :param arg_index: index of the argument in the argument array for which,    this function checks if a default value exists or not. And if default value    exists it would return the default value. Example argument: 1    :return: Tuple of whether there is a default or not, and if yes the default    value, eg: for index 2 i.e. for "second_arg" this function returns (True, 42)    """    if not defaults:        return DefaultArgSpec(False, None)    args_with_no_defaults = len(args) - len(defaults)    if arg_index < args_with_no_defaults:        return DefaultArgSpec(False, None)    else:        value = defaults[arg_index - args_with_no_defaults]        if (type(value) is str):            value = '"%s"' % value        return DefaultArgSpec(True, value)def get_method_sig(method):    """ Given a function, it returns a string that pretty much looks how the    function signature would be written in python.    :param method: a python method    :return: A string similar describing the pythong method signature.    eg: "my_method(first_argArg, second_arg=42, third_arg='something')"    """    # The return value of ArgSpec is a bit weird, as the list of arguments and    # list of defaults are returned in separate array.    # eg: ArgSpec(args=['first_arg', 'second_arg', 'third_arg'],    # varargs=None, keywords=None, defaults=(42, 'something'))    argspec = inspect.getargspec(method)    arg_index=0    args = []    # Use the args and defaults array returned by argspec and find out    # which arguments has default    for arg in argspec.args:        default_arg = _get_default_arg(argspec.args, argspec.defaults, arg_index)        if default_arg.has_default:            args.append("%s=%s" % (arg, default_arg.default_value))        else:            args.append(arg)        arg_index += 1    return "%s(%s)" % (method.__name__, ", ".join(args))if __name__ == '__main__':    def my_method(first_arg, second_arg=42, third_arg='something'):        pass    print get_method_sig(my_method)    # my_method(first_argArg, second_arg=42, third_arg="something")