> 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 -- http://mail.python.org/mailman/listinfo/python-list