Use "with suppress()" to suppress python exceptions
Using
```Python
with suppress(OSError):
os.remove('somefile.tmp')
```
instead of
```Python
try:
os.remove('somefile.tmp')
except OSError:
pass
```
makes the code more compact and more readable IMO.
This pattern was recommended by Raymond Hettinger, a Python Core
Developer in his talk "Transforming Code into Beautiful, Idiomatic Python" at https://www.youtube.com/watch?v=OSGv2VnC0go. The transcript is available at https://github.com/JeffPaine/beautiful_idiomatic_python
This commit is contained in:
@@ -7,6 +7,7 @@ import re
|
||||
from functools import lru_cache
|
||||
from hashlib import md5
|
||||
from mimetypes import guess_type
|
||||
from contextlib import suppress
|
||||
|
||||
path_name_map = {}
|
||||
|
||||
@@ -140,10 +141,8 @@ def is_image(path):
|
||||
def data_for_path(path):
|
||||
ans = raw_data_for_path(path)
|
||||
if not is_image(path) and not os.path.samefile(path, os.devnull):
|
||||
try:
|
||||
with suppress(UnicodeDecodeError):
|
||||
ans = ans.decode('utf-8')
|
||||
except UnicodeDecodeError:
|
||||
pass
|
||||
return ans
|
||||
|
||||
|
||||
|
||||
@@ -9,6 +9,7 @@ import warnings
|
||||
from collections import defaultdict
|
||||
from functools import partial
|
||||
from gettext import gettext as _
|
||||
from contextlib import suppress
|
||||
|
||||
from kitty.cli import CONFIG_HELP, parse_args
|
||||
from kitty.constants import appname
|
||||
@@ -511,10 +512,8 @@ usage = 'file_or_directory_left file_or_directory_right'
|
||||
|
||||
def terminate_processes(processes):
|
||||
for pid in processes:
|
||||
try:
|
||||
with suppress(Exception):
|
||||
os.kill(pid, signal.SIGKILL)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
|
||||
def main(args):
|
||||
|
||||
Reference in New Issue
Block a user