Where is the default parameter in Python function

后端 未结 5 1580
情深已故
情深已故 2021-01-05 08:52

I think many people have seen the python\'s function which receives default parameters. For example:

def foo(a=[]):
    a.append(3)
    return a
5条回答
  •  暗喜
    暗喜 (楼主)
    2021-01-05 09:23

    As others already said, the default values are stored in the function object.

    For example, in CPython you can do this:

    >>> def f(a=[]):
    ...     pass
    ...
    >>> f.func_defaults
    ([],)
    >>> f.func_code.co_varnames
    ('a',)
    >>>
    

    However, co_varnames may contain more than names of args so it needs further processing and these attributes might not even be there in other Python implementations. Therefore you should use the inspect module instead which takes care of all implementation details for you:

    >>> import inspect
    >>> spec = inspect.getargspec(f)
    >>> spec
    ArgSpec(args=['a'], varargs=None, keywords=None, defaults=([],))
    >>>
    

    The ArgSpec is a named tuple so you can access all values as attributes:

    >>> spec.args
    ['a']
    >>> spec.defaults
    ([],)
    >>>
    

    As the documentation says, the defaults tuple always corresponds to the n last arguments from args. This gives you your mapping.

    To create a dict you could do this:

    >>> dict(zip(spec.args[-len(spec.defaults):], spec.defaults))
    {'a': []}
    >>>
    

提交回复
热议问题