3

A regular python dict forbids attribute access:

>>> d = {}
>>> d.a = 1
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'dict' object has no attribute 'a'

However, a subclass of dict does not forbid attribute access:

>>> class MyDict(dict):
...     pass
...
>>> d = MyDict()
>>> d.a = 1
>>> d.a
1
>>> d.__dict__
{'a': 1}

I would have expected subclasses of dict to also forbid attribute access. If you wanted attribute access in the subclass, I would have thought that you would need to override __setattr__ for example.

What explains why a subclass of dict does not forbid attribute access by default?

Matthew Moisen
  • 16,701
  • 27
  • 128
  • 231
  • 1
    FWIW, one of the popular use-cases of subclassing `dict` (or `UserDict`) is to provide "dot notation access" (search for it on SO, you'd be surprised how many times this comes up) – DeepSpace May 07 '21 at 15:04
  • Either way, this question is a bit misleading. The default dict class forbids accessing and "on-the-fly" creation of **non-existing** attributes. Of course you can access existing ones, like `items`, `pop` etc – DeepSpace May 07 '21 at 15:06
  • 1
    https://stackoverflow.com/a/59474131/476 – deceze May 07 '21 at 15:09
  • Being a C-based class `dict` lacks a ... per-instance `__dict__` to store arbitrary attributes in. It’s not *forbidding* it’s *lack of storage options*. Why? On top of whatever C limitations, this would be very rarely needed and `__dict__`s are quite sizeable memory-wise. – JL Peyret May 07 '21 at 15:31

0 Answers0