Search code examples
pythonfunctionargumentsmutable

Using a mutable default argument, how to access the object from outside the function?


If I have something like this:

def f(x, cache=[]):
    cache.append(x)

How can I access cache from outside f?


Solution

  • You can use __defaults__ magic:

    >>> def f(x, cache=[]):
    ...     cache.append(x)
    >>> f.__defaults__
    ([],)
    >>> f(2)
    >>> f.__defaults__
    ([2],)
    >>> f('a')
    >>> f.__defaults__
    ([2, 'a'],)
    >>> c, = f.__defaults__
    >>> c
    [2, 'a']
    

    Just for the sake of completeness, inspect.getfullargspec can also be used, which is more explicit:

    >>> import inspect
    >>> inspect.getfullargspec(f)
    FullArgSpec(args=['x', 'cache'], varargs=None, varkw=None, defaults=([2, 'a'],), kwonlyargs=[], kwonlydefaults=None, annotations={})
    >>> inspect.getfullargspec(f).defaults
    ([2, 'a'],)