Back to articles
Handling missing dict keys, revisited

Handling missing dict keys, revisited

via Dev.toKelvin Wangonya

A while back, I wrote a post showing how to handle missing dict keys. In summary: Using setdefault Using defaultdict Implementing __missing__ While the advice there still stands, I've been reading through Fluent Python and came across two things worth being aware of when subclassing dict : __contains__ doesn't call __missing__ , so k in d returns False for keys not yet set, even if __missing__ would handle them dict.get doesn't call __missing__ , so .get(k) won't use your custom default Both are by design and often what you want. __missing__ is only used by d[key] , not other dict methods. Even defaultdict follows the same rule: only d[key] triggers the default factory and methods like .get() and in do not. Overriding get is tempting but tricky. A naive implementation might look like this: class M ( dict ): def __missing__ ( self , key ): value = " my default value " self [ key ] = value return value def get ( self , key , default = None ): try : return self [ key ] # triggers __missin

Continue reading on Dev.to

Opens in a new tab

Read Full Article
2 views

Related Articles