finefoot
finefoot

Reputation: 11232

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?

Upvotes: 1

Views: 57

Answers (2)

Sayandip Dutta
Sayandip Dutta

Reputation: 15872

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'],)

Upvotes: 3

Robert Seaman
Robert Seaman

Reputation: 2582

Variables inside of the function scope are not meant to be accessed outside.

What you should do is use a global variable to store your cache:

GLOBAL_CACHE = []

def f(x, cache=GLOBAL_CACHE):
    cache.append(x)

Upvotes: 1

Related Questions