4

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?

Manny
  • 41
  • 2
  • Objects in Python are not deleted, only a reference to it will be removed. Then the garbage collector will actually remove objects that are not referenced anymore. Since the object is not aware of all references to it, it is not trivial to implement what you desire. – Klaus D. May 08 '18 at 05:05
  • Ok, so it's not trivial. The instance does not have to de-reference itself, I just need to be able to do it through a method somehow. Or maybe I'm misunderstanding the whole thing. If I were to re-assign the variable agent_1 to another instance, would the instance previously assigned to it get cleaned up? – Manny May 08 '18 at 06:07
  • Does this answer your question? [Python object deleting itself](https://stackoverflow.com/questions/293431/python-object-deleting-itself) – Anonymous Feb 09 '20 at 20:14

0 Answers0