object() can't have attributes

Chris Angelico rosuav at gmail.com
Wed Dec 23 10:58:36 EST 2015


On Wed, Dec 23, 2015 at 11:46 PM, Neal Becker <ndbecker2 at gmail.com> wrote:
> I'm a bit surprised that an object() can't have attributes:
>
> In [30]: o = object()
>
> In [31]: o.x = 2
> ---------------------------------------------------------------------------
> AttributeError                            Traceback (most recent call last)
> <ipython-input-31-815c47907397> in <module>()
> ----> 1 o.x = 2
>
> AttributeError: 'object' object has no attribute 'x'

BTW, the reason for this is that the base 'object' type doesn't have a
__dict__. When you create a subclass, you get a __dict__ by default;
but you can override this.

$ python3
Python 3.6.0a0 (default:6e114c4023f5, Dec 20 2015, 19:15:28)
[GCC 4.9.2] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> object().__dict__
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'object' object has no attribute '__dict__'
>>> import sys
>>> class NS(object): pass
...
>>> class empty(object): __slots__ = ()
...
>>> sys.getsizeof(object())
16
>>> sys.getsizeof(NS())
56
>>> sys.getsizeof(empty())
16

The cost of supporting arbitrary attributes is significant. It's
common enough in custom classes that you have to explicitly ask for
the cut-down version, but when all you need is a sentinel, that's a
slab of memory and functionality that you just don't need, so it's not
there.

ChrisA



More information about the Python-list mailing list