[Python-Dev] Why are class dictionaries not accessible?

Guido van Rossum guido at python.org
Wed Jun 22 11:11:19 EDT 2016

On Wed, Jun 22, 2016 at 7:17 AM, Random832 <random832 at fastmail.com> wrote:

> The documentation states: """Objects such as modules and instances have
> an updateable __dict__ attribute; however, other objects may have write
> restrictions on their __dict__ attributes (for example, classes use a
> dictproxy to prevent direct dictionary updates)."""
> However, it's not clear from that *why* direct dictionary updates are
> undesirable. This not only prevents you from getting a reference to the
> real class dict (which is the apparent goal), but is also the
> fundamental reason why you can't use a metaclass to put, say, an
> OrderedDict in its place - because the type constructor has to copy the
> dict that was used in class preparation into a new dict rather than
> using the one that was actually returned by __prepare__.
> [Also, the name of the type used for this is mappingproxy, not
> dictproxy]

This is done in order to force all mutations of the class dict to go
through attribute assignments on the class. The latter takes care of
updating the class struct, e.g. if you were to add an `__add__` method
dynamically it would update tp_as_number->nb_add. If you could modify the
dict object directly it would be more difficult to arrange for this side

--Guido van Rossum (python.org/~guido)
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-dev/attachments/20160622/ab914771/attachment.html>

More information about the Python-Dev mailing list