0

I am trying to come up with a succinct example for garbage collection of an object that no variable name holds a reference to, however this code doesn't seem to work. I would like to understand why to better understand the inner-workings of Python. It seems to have exposed something I misunderstood.

some_name = [['some_nested_lst_object_with_an_str_object']]
id(some_name)
'''
you don't normally need to do this.
This is done for the reference example.
Accessing garbage collector:
'''
import gc
print(gc.collect())
'''
If I assign something new to ''*some_name*'',
the reference to the previous object will be lost:
'''
some_name
print(gc.collect())
some_name = [[['something_new']]]
some_name
print(gc.collect())
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
AturSams
  • 7,568
  • 18
  • 64
  • 98
  • You can see if the ref count for that object is actually zero or not. See: https://stackoverflow.com/questions/510406/is-there-a-way-to-get-the-current-ref-count-of-an-object-in-python – rdas Apr 08 '19 at 04:09

1 Answers1

2

Python uses reference counting, to free objects, normally. Only in the case of cyclic references, garbage collection is needed:

some_name = [123]
print(gc.collect())
some_name = [] # previous some_name-object is freed directly
some_name.append(some_name) # cyclic reference
print(gc.collect()) # 0
some_name = None
print(gc.collect()) # 1
Daniel
  • 42,087
  • 4
  • 55
  • 81