__dict__ attribute for built-in types

Hrvoje Niksic hniksic at xemacs.org
Fri Oct 28 05:08:13 EDT 2011


candide <candide at free.invalid> writes:

> Le 28/10/2011 00:57, Hrvoje Niksic a écrit :
>
>> was used at class definition time to suppress it.  Built-in and
>> extension types can choose whether to implement __dict__.
>>
>
> Is it possible in the CPython implementation to write something like this :
>
> "foo".bar = 42
>
> without raising an attribute error ?

No, and for good reason.  Strings are immutable, so that you needn't
care which particular instance of "foo" you're looking at, they're all
equivalent.  The interpreter uses that fact to cache instances of short
strings such as Python identifiers, so that most places that look at a
string like "foo" are in fact dealing with the same instance.  If one
could change an attribute of a particular instance of "foo", it would no
longer be allowed for the interpreter to transparently cache them.  The
same goes for integers and other immutable built-in objects.

If you really need to attach state to strings, subclass them as Steven
explained.  All code that accepts strings (including all built-ins) will
work just fine, transparent caching will not happen, and attributes are
writable.



More information about the Python-list mailing list