I am trying to delete an instance of a class by calling a method outside of the main program in which it was created. I have gathered from searching around that in order to be garbage collected an instance must have no referrers. Using a del
statement in the main program will do this, but I will need to delete instances through methods as well, otherwise the instances will quickly pile up. The code I have is something like this:
class Agent_type:
def __init__(self, type_name, properties):
self.type_name = type_name
self.properties = properties
self.agent_set = set()
class Agent:
def __init__(self, agent_type):
self.properties = agent_type.properties
self.agent_type = agent_type
agent_type.agent_set.update([self])
def kill(self):
self.agent_type.agent_set.remove(self)
del self
def kill(agent):
agent.agent_type.agent_set.remove(agent)
del agent
programmer = Agent_type('programmer', {'language' : 'python'})
agent_1 = Agent(programmer)
print(agent_1)
print(programmer.agent_set)
agent_1.die()
# kill(agent_1)
print(programmer.agent_set)
print(agent_1)
del(agent_1)
print(programmer.agent_set)
try:
print(agent_1)
except:
print("agent deleted")
The output I get is:
<__main__.Agent object at 0x01A59290>
{<__main__.Agent object at 0x01A59290>}
set()
<__main__.Agent object at 0x01A59290>
set()
agent deleted
And the output does not change if I run kill(agent_1)
rather than agent_1.die()
. What I need here is to have either the kill or die method remove all references to the instance so that it is actually deleted. Is this possible, and if so how can I do it?