Home > Enterprise >  why __del__ dunder method act different in vs code vs jupyter notebook
why __del__ dunder method act different in vs code vs jupyter notebook

Time:04-26

del methods in python class has two different output in different text editors

class test:
    def __init__(self) :
        print("init")
    def __del__(self):
        print("del")
a=test()

outpuu in vs code :

init del out put in jupyter :

init

CodePudding user response:

When you run the Python script in the terminal (which is similar as in vscode), after the last line has been executed, the script terminates. When a script terminates, the desctructor of the class test() is called. A desctructor is defined in __del__() method in a class.

In Jupyter notebook, the script does not terminate and is up for your next code chunk (apols the terminology might be slightly off here). The __del__() method is not called.

CodePudding user response:

It is explicitely stated in Python Language Reference. Data model / Special method names / Basic customization says (emphasize mine):

object.del(self)

Called when the instance is about to be destroyed...
It is not guaranteed that del() methods are called for objects that still exist when the interpreter exits.

That means that different environments may have different usage regarding the calling of __del__

  • Related