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

Ben Finney ben+python at benfinney.id.au
Fri Apr 22 01:17:34 EDT 2016


Random832 <random832 at fastmail.com> writes:

> On Thu, Apr 21, 2016, at 23:49, Steven D'Aprano wrote:
> > Where does attribute lookup come into this?
>
> Because looking up an attribute implies getting an item from the
> object or class's __dict__ with a string key of the name of the
> attribute (see below for the documented basis for this assumption).

No, that's not what it implies. The ‘__dict__’ of an object is an
implementation detail, and is not necessarily used for attribute lookup.

As the documentation says:

    A class has a namespace implemented by a dictionary object. Class
    attribute references are translated to lookups in this dictionary,
    e.g., C.x is translated to C.__dict__["x"] (although there are a
    number of hooks which allow for other means of locating attributes).

    <URL:https://docs.python.org/3.5/reference/datamodel.html>

So no, attribute lookup does not imply getting an item from any
particular dictionary. Nothing in the documentation implies that — if
you find an exception, please file a bug report for that part of the
documentation.

> How are you not following this? I don't believe you're not messing
> with me.

Steven follows quite well; he is trying to get you to explain your
meaning so we can find where the mismatch is.

> > > Given a type, how do I get a reference to the dict instance that
> > > was passed to the type's constructor?
> > 
> > I believe that the answer to that is, you can't.
>
> I hadn't yet realized, when I asked this question, that the class
> __dict__ "mappingproxy" is a new object (that isn't even a dict! "A
> class has a namespace implemented by a dictionary object" was also
> wrong) and doesn't retain a reference to the passed-in dict nor
> reflect changes to it.

That's right. As documented, attribute lookup does not imply any
dictionary lookup for the attribute.

Attribute lookup by name is one thing. Dictionary lookup by key is quite
a different thing. Please let's keep the two distinct in any discussions.

-- 
 \        “Ubi dubium, ibi libertas.” (“Where there is doubt, there is |
  `\                                                        freedom.”) |
_o__)                                                                  |
Ben Finney



More information about the Python-ideas mailing list