pythonwith-statementobject-destruction

With statement, auto-delete object


Is it possible to delete an object form inside its class?

class A():
    def __init__(self):
        print("init")
        self.b="c"
    def __enter__(self):
        print("enter")
        return self
    def __exit__(self, type, value, traceback):
        print("exit")      

with A() as a:
    print(a.b)
print(a.b)

returns:

init
enter
c
exit
c

How comes I still have access to the a object after exiting the with ? Is there a way to auto-delete the object in __exit__?


Solution

  • class A():
        def __init__(self):
            print("init")
            self.b="c"
        def __enter__(self):
            print("enter")
            return self
        def __exit__(self, type, value, traceback):
            print("exit") 
            del self.b
    
    with A() as a:
        print(a.b)
    print(a.b)
    

    You can't delete instance of class A itself within __exit__. The best you can do is delete the property b.

    init
    enter
    c
    exit
    Traceback (most recent call last):
      File "main.py", line 14, in <module>
        print(a.b)
    AttributeError: A instance has no attribute 'b'