[Tutor] object size in python is in what units?

eryksun eryksun at gmail.com
Tue Jul 23 23:07:56 CEST 2013


On Tue, Jul 23, 2013 at 2:27 PM, Jim Mooney <cybervigilante at gmail.com> wrote:
>
> And yet I still get 36 with this:
>
> bigKronk = Kronk('supercalifracilisticexpalidocious, even though the sound
> of it is really quite atrocious')
> sys.getsizeof(bigKronk)
> 36

I just noticed that you're using an old-style class. Remember to
inherit from object in 2.x.

The size of 36 bytes on 32-bit Windows Python gives it away. An
old-style instance needs an extra pointer to the class object because
its type is actually types.InstanceType.

> So I guess the object is only pointing to its contents.  Which I assume
> means an object is just a bunch of names bound to pointers.

That depends on the object. Built-in objects can have widely varying
structure (beyond the base refcount and type tag). An immutable object
such as a string or tuple will usually have its data allocated with
the object itself, while a list has a pointer to an array, which can
change while the base address of the list itself remains constant.

When it comes to __sizeof__, most types include their variable size as
well -- but not all do (e.g. a NumPy array doesn't). Typically the
size doesn't include the size of referenced objects. You'd have to
calculate that yourself by walking the references. It's up to you what
to include in your own __sizeof__ method; just don't do something
silly like this:

    class NegativeSize(object):
        __slots__ = ()
        def __sizeof__(self):
            return -1

    >>> sys.getsizeof(NegativeSize())
    -1


More information about the Tutor mailing list