Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python garbage collection and _ underscore in interpreter environment

If a class is defined in interpreter environment:

class C(object):
    def __init__(self, val):
        self.x = val

Then instantiated without names:

>>> C(1)
>>> C(2)
>>> 

Then we can use underscore _ to refer to C(2), so here is my question:

  • Since the underscore '_' refer to C(2), can we say the reference counter for C(2) is still 1? So the python gc will not free the memory taken by C(2)?
  • As far as I know, after these C(2) is executed, no names will refer to C(1), so can I say as soon as C(2) is executed, C(1)'s memory will be freed by python gc?

These are actually 4 questions, one bold font to one.

gc: short for garbage collection

EDIT

Let me make my first question more clear by commenting directly into the codes.

>>> C(1) # Press Enter Key and run
>>> 
>>> At Here, what is the exact reference count for the previous anonymous object "C(1)"? 
>>> And how to prove?
>>> 
>>> C(2) # Press Enter Key and run
>>> 
>>> At Here, what is the exact reference count for the previous anonymous object "C(1)"?
>>> And how to prove?
like image 866
Charles Avatar asked Dec 05 '25 04:12

Charles


1 Answers

@allen, thank you so much for your answer.

Based on your guess, I made the following code:

In [3]: {'a': 1}
Out[3]: {'a': 1}

In [4]: C(1)
   ...: print(_)
   ...: print(type(_))
   ...: print(number_of_instances(C))
   ...:
{'a': 1}
<class 'dict'>
0

In [5]:

So the _ underscore is only used for storing the value of last expression in interpreter of "Single Step Mode", not for "Continuous Mode".

This might be a common mistake made by beginners.

Anyway, thank you so much for your answer!

like image 121
Charles Avatar answered Dec 07 '25 19:12

Charles