In this lesson, you’ll learn about a intern objects, which are a subset of objects that Python pre-creates in memory and keeps in the global namespace. These variables are extremely likely to be used in many programs, and this prevents memory allocation calls for consistently used objects.
00:10 The core Python developers knew this, and so they created something called intern objects. Interned objects are pre-created objects in memory that can be accessed from anywhere in your program. Before creating a new object in memory, Python will check to see if it already exists as one of these intern objects.
00:33 If it does, the name will point to it. If not, a new object is created for the name to point to. You can think of these intern objects as a cache. It prevents Python from having to repeatedly create some of the most common objects used in Python programs.
00:52 You can manually intern objects, but Python defaults to interning some integers and strings for you. What gets interned automatically depends on the Python implementation, but in CPython 3.7, integers between -5 and 256 are interned, as with strings that are less than 20 characters and contain only ASCII letters, digits, or underscores.
01:51 Some string objects are interned, too. These two short strings on the left are interned because they meet the interning criteria. But on the right, the strings contain an exclamation mark, which causes them to fail the criteria for automatic interning.
02:22 Also, interning rules may appear different when running code in a script, rather than in the interactive shell directly. This is because some compilers used to compile Python scripts are smart enough to optimize different names if they detect they’re pointing to the same values, even if they fall outside the range for pre-interned objects.
Become a Member to join the conversation.