[Python-Dev] Re: Caching objects in memory
Guido van Rossum
gvanrossum at gmail.com
Mon Apr 25 18:57:08 CEST 2005
> I was in my second class of the Python workshop I'm giving here in one
> Argentine University, and I was explaining how to think using
> name/object and not variable/value.
>
> Using id() for being pedagogic about the objects, the kids saw that
> id(3) was always the same, but id([]) not. I explained to them that
> Python, in some circumstances, caches the object, and I kept them
> happy enough.
>
> But I really don't know what objects and in which circumstances.
Aargh! Bad explanation. Or at least you're missing something:
*mutable* objects (like lists) can *never* be cached, because they
have explicit object semantics. For example each time the expression
[] is evaluated it *must* produce a fresh list object (though it may
be recycled from a GC'ed list object -- or any other GC'ed object, for
that matter).
But for *immutable* objects (like numbers, strings and tuples) the
implementation is free to use caching. In practice, I believe ints
between -5 and 100 are cached, and 1-character strings are often
cached (but not always).
Hope this helps! I would think this is in the docs somewhere but
probably not in a place where one would ever think to look...
--
--Guido van Rossum (home page: http://www.python.org/~guido/)
More information about the Python-Dev
mailing list