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

Steven D'Aprano steve at pearwood.info
Thu Apr 21 22:00:17 EDT 2016

On Thu, Apr 21, 2016 at 09:43:17AM -0400, Random832 wrote:
> 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__)? 

I don't understand your question. Or rather, if I have understood it, 
the question has a trivial answer: you don't have to override anything.

class MyDict(dict):

d = MyDict()
d.attr = 1

will do what you appear to be asking. If that's not what you actually 
mean, then you need to explain more carefully.

I will also point out that your question is based on a point of 
confusion. You ask:

"So what method should be overridden..."

but the answer to this in general must be "What makes you think a single 
method is sufficient?" This doesn't just apply to dicts, it applies in 
general to any class.

"What method do I override to make a subclass of int implement 
arithmetic with wrap-around (e.g. 999+1 = 0, 501*2 = 2)?"

> 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.

This doesn't make anything any clearer for me.

> 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?

Anywhere you have to operate with code that does "if isinstance(x, 
dict)" checks.

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

Because defaultdict provides __missing__ in addition to the standard 
dict operations. Is there a problem with the current docs?


More information about the Python-ideas mailing list