0

I would like to develop a Python decorator that tells me the real memory size of the objects in a Python function.

from pympler import asizeof
import functools

def get_size(func):
  @functools.wraps(func)
  def wrapper(*args, **kwargs):
        func(*args, **kwargs)
        print(f"Memory allocation (KB) of variables of the function {func.__name__!r}")
        for key in locals().keys(): 
          print(f"size of object {key} is {asizeof.asizeof(key)/10**3}")
  return wrapper

@get_size
def my_function():
  nums = [1,2,3,4,5]
  more_nums = [nums, nums, nums, nums, nums]

my_function()

The current output is not what I am looking for, as it takes the function as the only object, not the objects in contains inside (nums, more_nums) which are the ones of interest to me.

Memory allocation (KB) of variables of the function 'my_function'
size of object args is 0.056
size of object kwargs is 0.056
size of object func is 0.056
G. Macia
  • 1,204
  • 3
  • 23
  • 38
  • I don't think you can do this. The wrapper wraps *around* the call to the function, it doesn't run inside the function. So it doesn't have access to the function's local variables. – Barmar Jan 19 '23 at 12:59
  • Good point, it makes sense. My current pain is that I am copy-pasting the same two lines every time I would like to know the memory allocation of the variables in a function. I wish for a cleaner way – G. Macia Jan 19 '23 at 13:17

0 Answers0