0

Imagine a hypothetical situation where a function returns two values: a huge dataset you are not interested in and a small summary you want. If your script (not interactive shell) has code like

_, the_answer = deep_thought.ask(the_ultimate_question)

, will the garbage collector treat _ any different than any other name and free memory any quicker than with

mostly_harmless, the_answer = deep_thought.ask(the_ultimate_question)

assuming mostly_harmless will never by used. At first I assumed it wouldn't but after reading this: python garbage collection and _ underscore in interpreter environment I started having doubts. I hope someone here will know the answer or find it quicker than me.

Also, for bonus points, how does it compare performance-wise with

the_answer = deep_thought.ask(the_ultimate_question)[1]

?

int_ua
  • 1,646
  • 2
  • 18
  • 32

1 Answers1

0

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

Iain Shelvington
  • 31,030
  • 3
  • 31
  • 50