__dict__ attribute for built-in types

Duncan Booth duncan.booth at invalid.invalid
Thu Oct 27 07:03:17 EDT 2011


candide <candide at free.invalid> wrote:

> I realize that built-in types objects don't provide a __dict__ 
attribute 
> and thereby i can't set an attribute to a such object, for instance
> 
> 
> >>> a=[42,421]
> >>> a.foo="bar"
> Traceback (most recent call last):
>    File "<stdin>", line 1, in <module>
> AttributeError: 'list' object has no attribute 'foo'
> >>> a.__dict__
> Traceback (most recent call last):
>    File "<stdin>", line 1, in <module>
> AttributeError: 'list' object has no attribute '__dict__'
> >>>
> 
> 
> So, i was wondering :
> 
> -- why this behaviour ?

Types without a __dict__ use less memory. Also, if you couldn't have a 
type that didn't have a `__dict__` then any `dict` would also need its 
own `__dict__` which would either result in infinite memory use or 
recursive dictionaries.

It isn't just built-in types, you can choose for any type you define 
whether or not to have a '__dict__' attribute

>>> class Fixed(object):
	__slots__ = ('foo', 'bar')
	readonly = 42

	
>>> f = Fixed()
>>> f.foo, f.bar = 1, 2
>>> f.foo, f.bar, f.readonly
(1, 2, 42)
>>> f.readonly = 24
Traceback (most recent call last):
  File "<pyshell#31>", line 1, in <module>
    f.readonly = 24
AttributeError: 'Fixed' object attribute 'readonly' is read-only
>>> f.baz = 'whatever'
Traceback (most recent call last):
  File "<pyshell#32>", line 1, in <module>
    f.baz = 'whatever'
AttributeError: 'Fixed' object has no attribute 'baz'

> -- where the official documentation refers to this point ?
> 
See http://docs.python.org/reference/datamodel.html for the docs about 
__slots__

There is also the API documentation which describes at a low level how 
to control whether or not instances have a dict:
 http://docs.python.org/c-api/typeobj.html#tp_dictoffset

I'm not sure though where you find a higher level statement of which 
builtin types have a __dict__.

-- 
Duncan Booth http://kupuguy.blogspot.com



More information about the Python-list mailing list