Does declaring variables in a function called from __init__ still use a key-sharing dictionary?
does object key-sharing happen when attributes are declared in a function that is called by
__init__
?
Yes, regardless of where you set the attributes from, granted that after initialization both have the same set of keys, instance dictionaries use a shared-key dictionary implementation. Both cases presented have a reduced memory footprint.
You can test this by using sys.getsizeof
to grab the size of the instance dictionary and then compare it with a similar dict created from it. dict.__sizeof__
's implementation discriminates based on this to return different sizes:
# on 64bit version of Python 3.6.1
print(sys.getsizeof(vars(c)))
112
print(getsizeof(dict(vars(c))))
240
so, to find out, all you need to do is compare these.
As for your edit:
"If a single key is added that is not in the prototypical set of keys, you loose the key sharing"
Correct, this is one of the two things I've (currently) found that break the shared-key usage:
- Using a non-string key in the instance dict. This can only be done in silly ways. (You could do it using
vars(inst).update
) The contents of the dictionaries of two instances of the same class deviating, this can be done by altering instance dictionaries. (single key added to that is not in the prototypical set of keys)
I'm not certain if this happens when a single key is added, this is an implementation detail that might change. (addendum: see Martijn's comments)
For a related discussion on this see a Q&A I did here: Why is the __dict__ of instances so small in Python 3?
Both these things will cause CPython to use a 'normal' dictionary instead. This, of course, is an implementation detail that shouldn't be relied upon. You might or might not find it in other implementations of Python and or future versions of CPython.
I think you are referring to the following paragraph of the PEP (in the Split-Table dictionaries section):
When resizing a split dictionary it is converted to a combined table. If resizing is as a result of storing an instance attribute, and there is only instance of a class, then the dictionary will be re-split immediately. Since most OO code will set attributes in the
__init__
method, all attributes will be set before a second instance is created and no more resizing will be necessary as all further instance dictionaries will have the correct size.
So a dictionary keys will remain shared, no matter what additions are made, before a second instance can be created. Doing so in __init__
is the most logical method of achieving this.
This does not mean that attributes set at a later time are not shared; they can still be shared between instances; so long as you don't cause any of the dictionaries to be combined. So after you create a second instance, the keys stop being shared only if any of the following happens:
- a new attribute causes the dictionary to be resized
- a new attribute is not a string attribute (dictionaries are highly optimised for the common all-keys-are-strings case).
- an attribute is inserted in a different order; for example
a.foo = None
is set first, and then second instanceb
setsb.bar = None
first, hereb
has an incompatible insertion order, as the shared dictionary hasfoo
first. - an attribute is deleted. This kills sharing even for one instance. Don't delete attributes if you care about shared dictionaries.
So the moment you have two instances (and two dictionaries sharing keys), the keys won't be re-split as long as you don't trigger any of the above cases, your instances will continue to share keys.
It also means that delegating setting attributes to a helper method called from __init__
is not going to affect the above scenario, those attributes are still set before a second instance is created. After all __init__
won't be able to return yet before that second method has returned.
In other words, you should not worry too much about where you set your attributes. Setting them in the __init__
method lets you avoid combining scenarios more easily, but any attribute set before a second instance is created is guaranteed to be part of the shared keys.
As for how to test this: look at the memory size with the sys.getsizeof()
function; if creating a copy of the __dict__
mapping results in a larger object, the __dict__
table was shared:
import sys
def shared(instance):
return sys.getsizeof(vars(instance)) < sys.getsizeof(dict(vars(instance)))
A quick demo:
>>> class Foo:
... pass
...
>>> a, b = Foo(), Foo() # two instances
>>> shared(a), shared(b) # they both share the keys
(True, True)
>>> a.bar = 'baz' # adding a single key
>>> shared(a), shared(b) # no change, the keys are still shared!
(True, True)
>>> a.spam, a.ham, a.monty, a.eric = (
... 'eggs', 'eggs and spam', 'python',
... 'idle') # more keys still
>>> shared(a), shared(b) # no change, the keys are still shared!
(True, True)
>>> a.holy, a.bunny, a.life = (
... 'grail', 'of caerbannog',
... 'of brian') # more keys, resize time
>>> shared(a), shared(b) # oops, we killed it
(False, False)
Only when the threshold was reached (for an empty dictionary with 8 spare slots, the resize takes place when you add a 6th key), did the dictionaries loose the shared property.
Dictionaries are resized when they are about 2/3rd full, and a resize generally doubles the table size. So the next resize will take place when the 11th key is added, then at 22, then 43, etc. So for a large instance dictionary, you have a lot more breathing room.