How to close a file when using with and try..except?

I wrote this example to show what is __exit__not executed when an exception occurs:

class A(object):
    def __enter__(self):
        print('enter')
    def __exit__(self):
        print('exit')
try:
    with A() as a:
        raise RunTimeError()
except Exception as e:
    print('except')

Conclusion:

enter
except

So, what is the correct way to use the operator withand catch exceptions, while making sure to __exit__execute at the end? Thank!

+4
source share
1 answer

The function is called , regardless of whether the body causes errors or not. Your function must have additional parameters (exception type), (exception object), and (generated trace). __exit__withexc_typeexc_valuetraceback

, with Error, : None. , .

, , , , , .

, , , :

class A(object):
    def __enter__(self):
        self.file = open('some_file.txt')
        return self.file

    def __exit__(self, exc_type, exc_value, traceback):
        print(('exit', exc_type, exc_value, traceback))
        # close the file, regardless of exceptions
        self.file.close()
        return False  # silence the exception?

- :

with A():
    raise Exception

, __exit__ :

('exit', <class 'Exception'>, Exception(), <traceback object at 0x7fc512c924c8>)

, . , , , SQL .

__exit__ ( , Python None). , __exit__ True, : with. with. , - .

class SilenceExceptions(object):
    def __enter__(self):
        pass

    def __exit__(self, exc_type, exc_value, traceback):
        return True  # silence ALL exceptions

:

with SilenceExceptions():
    raise Error

, "" __exit__.

+3

Source: https://habr.com/ru/post/1691227/


All Articles