Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Delete class instance from memory

In my program I create an un-ending amount of class instances. the amount depends on how long the program is running. However I don't need the instances at all after a certain code being run. How could i remove them completely from memory?

Simple example code:

class Player:
    def __init__(self, color):
        self.color = color

for n in range(1000):
    p = Player('black')

Would del p in this case completely remove that instance?

like image 571
Bas Velden Avatar asked Feb 01 '26 23:02

Bas Velden


1 Answers

Python will remove them from memory for you when they are no longer referred to. If you have Player instances that refer to other Player instances (ex: p.teammates = [list of Players]) you could end up with circular references that may prevent them from being garbage collected. In this case you should consider the weakref module.

for example:

>>>sam = Player('blue')
>>>rob = Player('green')
>>>sam.team = [sam, rob]
>>>rob.team = [sam, rob]
>>> #sam and rob may not be deleted because they contain 
>>> #references to eachother so the reference count cannot reach 0
>>>del sam #del is a way to manually dereference an object in an interactive prompt. Otherwise the interpreter cannot know you won't use it again unlike when the entire code is known at the beginning.
>>>print(rob.team[0].color) #this prints 'blue' proving that sam hasn't been deleted yet
blue

so how do we fix it?

>>>sam = Player('blue')
>>>rob = Player('green')
>>>sam.team = [weakref.ref(sam), weakref.ref(rob)]
>>>rob.team = [weakref.ref(sam), weakref.ref(rob)]
>>> #now sam and rob can be deleted, but we've changed the contents of `p.team` a bit:
>>> #if they both still exist:
>>>rob.team[0]() is sam #calling a `ref` object returns the object it refers to if it still exists
True
>>>del sam
>>>rob.team[0]() #calling a `ref` object that has been deleted returns `None`
None
>>>rob.team[0]().color #sam no longer exists so we can't get his color
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'NoneType' object has no attribute 'color'
like image 195
Aaron Avatar answered Feb 03 '26 12:02

Aaron