pythonmemory

python- how to display size of all variables


I want to print the memory size of all variables in my scope simultaneously.

Something similar to:

for obj in locals().values():
    print sys.getsizeof(obj)

But with variable names before each value so I can see which variables I need to delete or split into batches.

Ideas?


Solution

  • You can iterate over both the key and value of a dictionary using .items()

    from __future__ import print_function  # for Python2
    import sys
    
    local_vars = list(locals().items())
    for var, obj in local_vars:
        print(var, sys.getsizeof(obj))