How are variables and memory managed in Python? Does it have a stack and a heap and what algorithm is used to manage memory? Given this knowledge are there any recommendations on memory management for large number/data crunching?
Share
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Automagically! No, really, you just create an object and the Python Virtual Machine handles the memory needed and where it shall be placed in the memory layout.
When we are talking about
CPythonit uses a private heap for storing objects. From the CPython C API documentation:Memory reclamation is mostly handled by reference counting. That is, the Python VM keeps an internal journal of how many references refer to an object, and automatically garbage collects it when there are no more references referring to it. In addition, there is a mechanism to break circular references (which reference counting can’t handle) by detecting unreachable “islands” of objects, somewhat in reverse of traditional GC algorithms that try to find all the reachable objects.
NOTE: Please keep in mind that this information is
CPythonspecific. Other python implementations, such aspypy,iron python,jythonand others may differ from one another and from CPython when it comes to their implementation specifics. To understand that better, it may help to understand that there is a difference between Python the semantics (the language) and the underlying implementationNow I can not speak about this, but I am sure that NumPy (the most popular python library for number crunching) has mechanisms that handle memory consumption gracefully.
If you would like to know more about Python’s Internals take a look at these resources: