0

When I try to delete one instance of a class, it causes unexpected output from the __del__ method of another instance:

class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age
        print('{0} has been born!'.format(self.name))

    def __str__(self):
        return '{0} is {1} years old'.format(self.name, self.age)

    def __del__(self):
        print('{0} is deleted!'.format(self.name))

p1 = Person("John", 20)
p2 = Person("Mary", 27)

print(p1)
print(p2)

del(p2)

Output is:

John has been born!
Mary has been born!
John is 20 years old
Mary is 27 years old
Mary is deleted!
John is deleted!

Why "John is deleted!"?

1 Answer 1

2

John is deleted because your script ends. All module globals are cleared at that point.

Just to be clear, it is not the del call that clears Mary here. del just clears the variable from the global namespace, which in turn decrements the reference count to that object. Once the reference count reaches 0, the __del__ method is called and the object is cleared from memory.

But your script namespace is an object too; it is stored in sys.modules under the __main__ key, and once it is done running, the Python interpreter exits and clears out all modules in sys.modules. This causes refenence counts to drop, and for John this means that it'll be cleared too.

You could add a print statement after del(p2):

print('Script complete')

and you'll see that inserted between the is deleted! outputs:

Mary is deleted!
Script complete
John is deleted!
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks! It's almost clear. I need to going much deeper in theory.
A small addition: It is not guaranteed that __del__ will ever be called.
@Matthias: indeed, for Python versions < 3.4 if there is a circular reference involved then __del__ methods are not called at all as the circular reference is never broken.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.