Skip to content

Instantly share code, notes, and snippets.

@acatton
Last active July 5, 2021 06:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save acatton/b76b3457a7ef349ebd94 to your computer and use it in GitHub Desktop.
Save acatton/b76b3457a7ef349ebd94 to your computer and use it in GitHub Desktop.
For people saying there's no such thing as memory leak in python
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import functools
def memoize(func):
CACHE = dict()
@functools.wraps(func)
def wrapper(*args, **kwargs):
key = (tuple(args), frozenset(kwargs.items()))
try:
return CACHE[key]
except KeyError:
ret = func(*args, **kwargs)
CACHE[key] = ret
return ret
def fib(n):
if n < 2:
return 1
return fib(n - 1) + fib(n - 2)
for i in range(50):
print(i, ':', fib(i))
# Do some other stuff...
# See how the memory usage evolves
@xieshuaix
Copy link

I found out about this issue with functools.wraps as well. Have you figured out why it causes problem? Thanks!

@acatton
Copy link
Author

acatton commented Jul 5, 2021

@xieshuaix this is not a functools.wraps issue. The issue is that CACHE is caught in the closure.

It's not about the functools.wraps but more about how it's used.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment