[Tutor] object size in python is in what units?
eryksun
eryksun at gmail.com
Tue Jul 23 21:45:36 CEST 2013
On Tue, Jul 23, 2013 at 4:17 AM, Jim Mooney <cybervigilante at gmail.com> wrote:
>
> Okay, ID stands for a location fixed until the object disappears, but we
> don't know where that location is. But what about object offsets from self?
> Is the beginning of self.spam always the same distance from the beginning of
> self.eggs? Or can I just forget the hard ground of assembler-metaphors
> entirely as I float off into abstractville? I guess the fixed lengths I kept
> getting on re-runs were coincidental but not to be relied on.
Instance attributes are stored either in a dict or directly as slots.
In Cpython, the location of the slots that are used for the dict, weak
references, and other slots that you define are relative to the object
base address.
Normally each instance of a class has a slot for a reference count
(e.g. sys.getrefcount(obj)), a pointer to the type (e.g. type(obj)), a
pointer to a dict (e.g. vars(obj)), and a pointer to a linked list of
weak references (e.g. weakref.getweakrefs(obj)). You can override this
for __dict__ and __weakref__ and add your own slots by defining
__slots__:
class Example(object):
__slots__ = '__dict__', 'v'
Instances of Example have a dict and a slot named 'v', but they don't
allow weak references (i.e. the __weakref__ slot).
>>> ex = Example()
>>> ex.v, ex.w = 5, 10
>>> weakref.ref(ex)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: cannot create weak reference to 'Example' object
Example's dict has a member_descriptor for the 'v' slot. Instead of
just using ex.v, we can be weird and manually bind the descriptor:
>>> vars(Example)['v'].__get__(ex)
5
And do the same for the __dict__ getset_descriptor:
>>> vars(Example)['__dict__'].__get__(ex)
{'w': 10}
CPython doesn't actually use the __dict__ getset_descriptor from the
type's dict. It already has the instance dict offset as a field in the
type structure.
More information about the Tutor
mailing list