TL;DR
How can I get superkeys to be autovivified in a Python dict when assigning values to subkeys, without also getting them autovivified when checking for subkeys?
Background: Normally in Python, setting values in a nested dictionary requires manually ensuring that higher-level keys exist before assigning to their sub-keys. That is,
my_dict[1][2] = 3
will not reliably work as intended without first doing something like
if 1 not in my_dict:
my_dict[1] = {}
Now, it is possible to set up a kind of autovivification by making my_dict
an instance of a class that overrides __missing__
, as shown e.g. in https://stackoverflow.com/a/19829714/6670909.
Question: However, that solution silently autovivifies higher-level keys if you check for the existence of a sub-key in such a nested dict. That leads to the following unfortunateness:
>>> vd = Vividict()
>>> 1 in vd
False
>>> 2 in vd[1]
False
>>> 1 in vd
True
How can I avoid that misleading result? In Perl, by the way, I can get the desired behavior by doing
no autovivification qw/exists/;
And basically I'd like to replicate that behavior in Python if possible.