Is there a way to determine the size of the object in Python?

Asked 2 years ago, Updated 2 years ago, 166 views

In C/C++, I found out by using sizeof() I wonder if Python has a similar function.

I am writing an XML file that determines the size of the value by the size of the field You should always check the field size when you change the value of a particular field.

If it's a string, you can check the length, but I don't know what to do with int or float

python object memory memory-management sizeof

2022-09-22 22:23

1 Answers

Python 2.6 and later uses the sys function in the module sys.getsizeof.

sys.getsizeof returns the size of the object in bytes. Objects don't matter what they come in, and the Python built-in type (int or float) gives accurate values, but objects such as user-defined classes may have slightly different results depending on the implementation.

getsizeof() is implemented by calling the _sizeof__ method of the object internally If the object is managed by the garbage collector, an overhead can be added to __sizeof__ to return a larger value.

Examples of use are

import sys

class foo():
    mystr = "hello python world!"
x = 1000
y = foo()
print(sys.getsizeof(x))
print(sys.getsizeof(y))


2022-09-22 22:23

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.