Ashwin Geet D'Sa
Ashwin Geet D'Sa

Reputation: 7369

How to get the size of each local variable in python?

I have referred stack-overflow question here which indicates the use of getsizeof() function to obtain the size(memory in bytes) of a variable.

My current question is, how can we obtain the size of all the local variable in a program? (Assuming that we have a huge list of local variables).

Currently, I have tried the below program;

import numpy as np
from sys import getsizeof

a = 5
b = np.ones((5,5))

print("Size of a:", getsizeof(a))
print("Size of b:", getsizeof(b))

list_of_locals = locals().keys()

### list_of_locals contains the variable names
for var in list(list_of_locals):
    print("variable {} has size {}".format(var,getsizeof(var)))

which has an output:

Size of a: 28
Size of b: 312
variable __name__ has size 57
variable __doc__ has size 56
variable __package__ has size 60
variable __loader__ has size 59
variable __spec__ has size 57
variable __annotations__ has size 64
variable __builtins__ has size 61
variable __file__ has size 57
variable __cached__ has size 59
variable np has size 51
variable getsizeof has size 58
variable a has size 50
variable b has size 50

The input for getsizeof(obj), should be an object. In in this case it turns out to be character 'a' and 'b' and not the actual variable a and b.

Is there any alternative way to get the size of all the local variables, or can any modifications be done to the program to get the size of all the local variables?

The program also has an incorrect output

Upvotes: 1

Views: 2444

Answers (1)

abel1502
abel1502

Reputation: 980

You should use list_of_locals = locals().values() - you are currently getting the list of local variable names, and this would get the values, which is exactly what you want.

Upvotes: 1

Related Questions