Onkar Lapate’s Post

If Python is a "memory managed" language, but who is managing it? Reference Counter! Reference counter is what decides exactly when an object lives and when it dies in python. As discussed in previous posts, every object in Python carries a hidden counter. This counter tracks exactly how many variables are currently pointing to it. How it works? 1. Assignments: When we do y = x, Python finds the object x is pointing to and increments its counter (+1). 2. Deletions: When we do del x, Python finds the object x is pointing to and decrements its counter (-1). 3. Scope Exit: When a function finishes, all variables inside that function disappear. Python automatically decrements the counter of the objects they pointed to (-1). The moment that counter hits 0, Python immediately deletes the object and frees the memory. While this system is fast, it isn't "thread-safe". If two threads try to update the counter at the exact same time, the tally can get corrupted. That is exactly the reason, Python has Global Interpreter Lock(GIL) in place. Will discuss about it in more detail in next post. I am trying to learn Python Internals in detail and will share my learnings. Do follow along and tell your experiences in comments. #Python #PythonInternals #SoftwareEngineering #BackendDevelopment

  • diagram

To view or add a comment, sign in

Explore content categories