Reputation: 99428
From Learning Python
>>> x = 42
>>> x = 'shrubbery' # Reclaim 42 now?
Because Python caches and reuses small integers and small strings, as mentioned earlier, the object 42 here is probably not literally reclaimed; instead, it will likely remain in a system table to be reused the next time you generate a 42 in your code. Most kinds of objects, though, are reclaimed immediately when they are no longer referenced; for those that are not, the caching mechanism is irrelevant to your code.
What kinds of objects does CPython cache when they are no longer referenced?
What kinds of objects does CPython not cache when they are no longer referenced?
Does CPython cache an object no longer referenced, only when the object is immutable? Or does it have nothing to do with the (im)mutability of the object?
Thanks.
Upvotes: 0
Views: 52
Reputation: 531165
Immutability is a big part of it: you wouldn't want your new empty set to be a reference to an existing empty set, only to see it updated without you knowing it when the "original" is updated.
However, the objects that CPython is caching are generally not arbitrary objects created during the life of the program. The small integers are created on startup, whether or not they are ultimately used. (I don't know about the small strings; it's possible they are only created as necessary, but cached from then on.)
Upvotes: 1