pythonmemory-leaksobjgraph

Does it have memory leak?


I read objgraph document recently, and I confused about the following code

>>> class MyBigFatObject(object):
...     pass
...
>>> def computate_something(_cache={}):
...     _cache[42] = dict(foo=MyBigFatObject(),
...                       bar=MyBigFatObject())
...     # a very explicit and easy-to-find "leak" but oh well
...     x = MyBigFatObject() # this one doesn't leak

It show that "a very explict and easy-to-find 'leak'". Do this has memory leak? Is it the dict _cache?


Solution

  • _cache is a keyword argument with a mutable default, which is indeed mutated in the function body. This'll store MyBigFatObjects instances permanently in that mutable keyword argument.

    This is not so much a leak as a misunderstanding of the longevity of mutable keyword arguments. The function itself could still call del _cache[42] to delete these objects.

    See "Least Astonishment" and the Mutable Default Argument for more information on the subject.