Python Basic Objects Learning Notes
Recently revisiting the book “Python Source Code Analysis”, I’ve recorded the key points about Python basic objects as follows:
Python Integer Objects
- Python integers use C language’s long type for storage
- Python int addition checks if the result overflows, and automatically converts to pyLongObject if it does
- Documentation in Python is seamlessly integrated into the language implementation
|
|
-
Small integer objects are completely cached in memory, other integer objects take turns using a block of memory space
-
Small integer objects are created in _PyInt_Init called during Python initialization, and exist until the Python virtual machine exits
Python String Objects
- After pyStringObject is created, the internally maintained string cannot be changed
- Is the intern mechanism only used when character array length is 0 or 1? The code provided in the book is too simplified and doesn’t explain clearly, but looking at the demonstration results later, it seems all strings implement the intern mechanism
- String concatenation operations severely impact Python program execution efficiency. Using join only allocates memory once, greatly improving efficiency. Usage example:
|
|
Python Dict Objects
-
Python’s dict uses hashtable instead of R-B Tree.
-
Uses open addressing to resolve conflicts.
-
To ensure continuity of the conflict detection chain, uses pseudo-deletion technique - deleted active objects are set to dummy state
-
To reduce conflicts, when load factor exceeds 2/3, table size is changed, increasing by 4x each time. If the number of active elements in the table exceeds 50000 (giant table),
growth rate is slowed down to 2x each time. It can be seen that Python dict has high lookup efficiency, while being very economical with memory usage, also considering reduced growth factor for giant tables.Python List Objects
-
PyListObject is similar to Vector in STL.
-
Python is very frugal with memory usage - if the new size after list change is less than 1/2 of allocated memory, it shrinks the memory.
-
Inserting elements in the middle of PyList requires moving subsequent elements one by one, similar to C arrays, so insertions and deletions of middle elements should be avoided.
-
Comparison of STL and PyListObject automatic expansion algorithms: personally I think list would be more appropriately named array, hehe
|
|
- Regarding the choice of growth factor, there’s discussion here:
http://en.w3support.net/index.php?db=so&id=1100311
p70 typo in the book: “allcated/2” should be “allocated/2”
Original link: http://www.cppblog.com/xguru/archive/2011/07/21/Python_object.html