0

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.

Tim
  • 1
  • 141
  • 372
  • 590
  • It doesn't matter, there are no general principles, and it's all subject to change without notice. This is not the kind of thing you need to be worrying about. – user2357112 Jul 12 '17 at 16:24
  • *"[small integers](https://stackoverflow.com/questions/15171695/whats-with-the-integer-cache-inside-python) and [small strings](https://stackoverflow.com/questions/6931880/how-can-a-non-assigned-string-in-python-have-an-address-in-memory)"* – jonrsharpe Jul 12 '17 at 21:18

1 Answers1

1

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.)

chepner
  • 497,756
  • 71
  • 530
  • 681
  • Immutability is important if you do still have references to the objects, but not if you don't. – user2357112 Jul 12 '17 at 16:29
  • Another note is it's an implementation detail, cpython may do this differently than say pypy – anthony sottile Jul 12 '17 at 16:37
  • Mostly, I wanted to emphasize that it's not going to cache *every* immutable object simply because it is safe to do so; the overhead of tracking the object cache is often costs more than what you would save by avoiding "duplicate" objects. – chepner Jul 12 '17 at 16:41