Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why doesn't del <object> delete it?

Tags:

python

The code below creates a "tee" object that tees stdout to a file as well as the terminal.

If do del t as below when I'm done tee-ing, the object doesn't get deleted and the __del__() member doesn't get called (so the tee-ing continues):

t = tee("foo.txt")
print("bar")
del t

But if I call __del__() directly, things work fine:

t = tee("foo.txt")
print("bar")
t.__del__()

Why doesn't the del work? What's the right way to do this?

class tee():
    def __init__(self, filepath):
        self.old_stdout = sys.stdout
        self.old_stderr = sys.stderr
        self.name = filepath

        sys.stdout = self
        sys.stderr = self

    def write(self, text):
        self.old_stdout.write(text)
        with open(self.name, 'a',  encoding="utf-8") as f:
           f.write(text)

    def flush(self):
        pass

    def __del__(self):
        sys.stdout = self.old_stdout
        sys.stdout = self.old_stderr
like image 991
nerdfever.com Avatar asked Mar 19 '26 19:03

nerdfever.com


1 Answers

Note del x doesn’t directly call x.__del__() — the former decrements the reference count for x by one, and the latter is only called when x’s reference count reaches zero.
Taken from the data model section of the Python 3 documentation.

You've referenced the class inside the constructor:

sys.stdout = self
sys.stderr = self

The reference will remain and as a result the object will stay “alive”.

like image 196
sowlosc Avatar answered Mar 21 '26 09:03

sowlosc