1

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

2
  • How are you defining "local"? The code you show is really checking all the globals (since you aren't in a function definition, there is no local scope, only the module's global scope, which is what locals() is returning). Commented May 6, 2020 at 17:54
  • Well, you are right, here the locals() show the variables in the global scope as they are same. My my intention was to obtain the size of the variables. Well, even if I move these contents inside a function, the problem still exists. Commented May 6, 2020 at 18:10

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Well, It is close to the solution. I used: print("variable {} has size {}".format(var,getsizeof(locals()[var])))

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.