Alexey Vyskubov’s Post

This is a post about interesting behavour of "del" in Python. Do you think that "del x" calls x.__del__()? Well... >>> class Foo: ...   def __del__(self): ...     print("Deleting") >>> bar = Foo() >>> baz = bar >>> del bar Nothing is printed. Why? Now try >>> del baz Deleting The problem here is that bar and baz are the same object, and what "del" does is - removes the name (done) - decrements reference count for object (done, after "del bar" it is 1, baz still refers to the same object) - calls __del__, *if reference count is 0* (NOT done after "del bar", as the reference count is 1) When "del baz" is called, reference count finally reaches 0, and __del__ is called. While this kinda makes sense, it can be surprising and non-intuitive, if you don't really understand what is happening behind the scene. #python #gotcha

To view or add a comment, sign in

Explore content categories