Does Python Garbage Collector Behave Any Different With A _ Single Underscore Variable Name And Is It Really A "throwaway" Variable?
Solution 1:
Note: the following applies to CPython (the standard interpreter)
To understand the garbage collector first you must understand what a name
is, what an object
is and what an object's reference count is
Take the following function
def foo():
_ = {}
When the function is being executed the function's locals dictionary and the global objects internally held by CPython look something like this. (This is an over simplified explanation)
-------------------- ------------------------
| name | object_id | | id | reference_count |
-------------------- ------------------------
| _ | 1 | | 1 | 1 |
When the function is complete it's locals dictionary is destroyed and any objects that were referenced have their reference_count decremented
------------------------
| id | reference_count |
------------------------
| 1 | 0 |
The garbage collector will eventually delete the object with id 1
as it no longer has any references to it, the names of the references (variable names) do not matter.
The variable could have been named anything and it wouldn't matter to the garbage collector only the object's reference count
Post a Comment for "Does Python Garbage Collector Behave Any Different With A _ Single Underscore Variable Name And Is It Really A "throwaway" Variable?"