Interning own classes like strings for speed and size?

Rami Chowdhury rami.chowdhury at merton.oxon.org
Tue Dec 28 21:24:11 EST 2010


On Wed, Dec 29, 2010 at 00:45, Christian Heimes <lists at cheimes.de> wrote:
> Am 28.12.2010 21:16, schrieb Hrvoje Niksic:
>> Christian Heimes <lists at cheimes.de> writes:
>>
>>> Also this code is going to use much more memory than an ordinary tuple
>>> since every instance of InternedTuple has a __dict__ attribute. This
>>> code works but I had to move the cache outside the class because of
>>> __slots__.
>>
>> Wouldn't it work inside the class as well?  __slots__ applies to
>> instances, not to classes themselves.  In Python 3.1:
>
> You are right as long as you don't try to rebind the variable. I
> recalled that class attributes of classes with __slots__ behave slightly
> different than ordinary classes. For example you can't have a writeable
> slot and class default values at the same time.
>
>>>> class Example2(object):
> ...     __slots__ = ()
> ...     _cache = {}
> ...
>>>> Example2()._cache
> {}
>>>> Example2()._cache = {}
> Traceback (most recent call last):
>  File "<stdin>", line 1, in <module>
> AttributeError: 'Example2' object attribute '_cache' is read-only

Forgive me if I'm misunderstanding, but if you want to cache instances
of a class, surely

>> Example2()._cache = {}

would defeat the purpose, at least for that instance of Example2? The
slot seems writeable enough, after all

>> Example2()._cache['foo'] = 'bar'

seems to work?


-- 
Rami Chowdhury
"Never assume malice when stupidity will suffice." -- Hanlon's Razor
+44-7581-430-517 / +1-408-597-7068 / +88-0189-245544



More information about the Python-list mailing list