Python context manager can’t do too much
No, the official document implements a method suppress to handle exceptions
from contextlib import suppress
with suppress(FileNotFoundError):
os.remove('somefile.tmp')
with suppress(FileNotFoundError):
os.remove('someotherfile.tmp')
Then the document states that the above code is equivalent to:
try:
os.remove('somefile.tmp')
except FileNotFoundError:
pass
try:
os.remove('someotherfile.tmp')
except FileNotFoundError:
pass
I checked the source code of suppress, the implementation is actually very simple:
class suppress(ContextDecorator):
def __init__(self, *exceptions):
self._exceptions = exceptions
def __enter__(self):
pass
def __exit__(self, exctype, excinst, exctb):
return exctype is not None and issubclass(exctype, self._exceptions)
It is implemented by using the context manager, but I am not satisfied that the decorator is not used, and every time you want to use suppress, you must add with
So realized a version with decorator:
import os
from contextlib import ContextDecorator
class suppress(ContextDecorator):
def __init__(self, *exceptions):
self._exceptions = exceptions
def __enter__(self):
print(1)
def __exit__(self, exctype, excinst, exctb):
print(3)
return exctype is not None and issubclass(exctype, self._exceptions)
@suppress(FileNotFoundError)
def test_exception():
print(2)
os.remove('data.py')
test_exception()
operation result:
1
2
3
There is no abnormal pop-up, and the number is printed out, indicating that the effect is successful
If you can directly replace this part of the source code, then the next time you use it, you can add a decorator directly to the function to handle the exception of the function.