[Python-ideas] Override dict.__new__ to raise if cls is not dict; do the same for str, list, etc.

Random832 random832 at fastmail.com
Thu Apr 21 09:43:17 EDT 2016


On Thu, Apr 21, 2016, at 07:17, Steven D'Aprano wrote:
> and it runs counter to a documented feature of dicts, that they can be 
> subclassed and given a __missing__ method:
> 
> "If a SUBCLASS OF DICT [emphasis added] defines a method __missing__() 
> and key is not present, the d[key] operation calls that method ..."

So what method should be overridden to make a dict subclass useful as a
class or object dictionary (i.e. for attribute lookup to work with names
that have not been stored with dict.__setitem__)? Overriding __getitem__
or __missing__ doesn't work. My only consolation is that defaultdict
doesn't work either.

I can't even figure out how to get the real class dict, as I would need
if I were overriding __getattribute__ explicitly in the metaclass (which
also doesn't work) - cls.__dict__ returns a mappingproxy.

Alternatively, where, other than object and class dicts, are you
actually required to have a subclass of dict rather than a UserDict or
other duck-typed mapping?



Incidentally, why is __missing__ documented under defaultdict as "in
addition to the standard dict operations"?


More information about the Python-ideas mailing list