Is there any way to find out sizeof an object

  • Thread starter srinivasan srinivas
  • Start date
S

srinivasan srinivas

Hi,
I have written a class which has some attributes. I want to know how do i find out the size of an instance of this class??
class T(object):
    def __init__(self, fn_name, *args, **kwds):
        self.fn_name = fn_name
        self.args = args
        self.kwds = kwds
Thanks,
Srini


Bollywood, fun, friendship, sports and more. You name it, we have it on http://in.promos.yahoo.com/groups/bestofyahoo/
 
M

Martin v. Löwis

I have written a class which has some attributes. I want to know how
do i find out the size of an instance of this class??
class T(object):
def __init__(self, fn_name, *args, **kwds):
self.fn_name = fn_name
self.args = args
self.kwds = kwds

In Python 2.6, you can use sys.getsizeof to find out how large an object
is. Notice that this is a really tricky question: Assuming you have

t = T(1,2,3, a="hello", b="world")

then you should certainly consider the size atleast

sys.getsizeof(t) + sys.getsizeof(t.__dict__)

But then you also have the attribute values (i.e. the tuple resp.
dict), which you might want to account for:

+ sys.getsizeof(t.args) + sys.getsizeof(t.dict)

Now, what to do about the sizes of the various items in the dict
and the tuple? One could do

total = ... # from above
for o in t.args:
total+=sys.getsizeof(o)
for k,v in t.kwds.items():
total+=sys.getsizeof(k)+sys.getsizeof(v)

However, that might be accounting too much, since the at least
the keys of the dict are shared across other dicts. Likewise,
the integers are shared, and the string literals (as written
above) would be shared if the very same T constructor is run
twice.

In short, "size of an instance" can't be answered without
a specific instance (i.e. you can't answer it in advance for
all instances), plus even for a single instance, its difficult
to answer.

Regards,
Martin
 
P

Paddy

Hi,
I have written a class which has some attributes. I want to know how do i find out the size of an instance of this class??
class T(object):
    def __init__(self, fn_name, *args, **kwds):
        self.fn_name = fn_name
        self.args = args
        self.kwds = kwds
Thanks,
Srini

      Bollywood, fun, friendship, sports and more. You name it, we have it onhttp://in.promos.yahoo.com/groups/bestofyahoo/

Check memory
Create a million
Check memory
Do maths!

;-)

- Paddy.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,770
Messages
2,569,584
Members
45,077
Latest member
SangMoor21

Latest Threads

Top