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:
Luflosi
2019-06-03 11:50:07 +02:00
parent d6e750727f
commit 2b095f720e
22 changed files with 68 additions and 138 deletions

View File

@@ -3,6 +3,7 @@
# License: GPL v3 Copyright: 2018, Kovid Goyal <kovid at kovidgoyal.net>
import os
from contextlib import suppress
from kitty.cli import parse_args
from kitty.constants import cache_dir
@@ -27,10 +28,8 @@ class HistoryCompleter:
self.history_path = None
if name:
ddir = os.path.join(cache_dir(), 'ask')
try:
with suppress(FileExistsError):
os.makedirs(ddir)
except FileExistsError:
pass
self.history_path = os.path.join(ddir, name)
def complete(self, text, state):
@@ -50,10 +49,8 @@ class HistoryCompleter:
def __enter__(self):
if self.history_path:
try:
with suppress(Exception):
readline.read_history_file(self.history_path)
except Exception:
pass
readline.set_completer(self.complete)
return self
@@ -106,10 +103,8 @@ def main(args):
print(styled(args.message, bold=True))
prompt = '> '
try:
with suppress(KeyboardInterrupt, EOFError):
ans['response'] = input(prompt)
except (KeyboardInterrupt, EOFError):
pass
return ans

View File

@@ -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

View File

@@ -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):

View File

@@ -8,6 +8,7 @@ import sys
from base64 import standard_b64encode
from collections import defaultdict, deque
from itertools import count
from contextlib import suppress
from kitty.utils import fit_image
@@ -172,10 +173,8 @@ class ImageManager:
if in_flight:
pl = in_flight.popleft()
if payload.startswith('ENOENT:'):
try:
with suppress(Exception):
self.resend_image(image_id, pl)
except Exception:
pass
if not in_flight:
self.placements_in_flight.pop(image_id, None)

View File

@@ -7,6 +7,7 @@ import string
import subprocess
from functools import lru_cache
from gettext import gettext as _
from contextlib import suppress
from kitty.config import cached_values_for
from kitty.constants import config_dir
@@ -293,24 +294,20 @@ class UnicodeInput(Handler):
self.update_codepoints()
self.current_char = None
if self.mode is HEX:
try:
with suppress(Exception):
if self.line_edit.current_input.startswith(INDEX_CHAR) and len(self.line_edit.current_input) > 1:
self.current_char = chr(self.table.codepoint_at_hint(self.line_edit.current_input[1:]))
else:
code = int(self.line_edit.current_input, 16)
self.current_char = chr(code)
except Exception:
pass
elif self.mode is NAME:
cc = self.table.current_codepoint
if cc:
self.current_char = chr(cc)
else:
try:
with suppress(Exception):
if self.line_edit.current_input:
self.current_char = chr(self.table.codepoint_at_hint(self.line_edit.current_input.lstrip(INDEX_CHAR)))
except Exception:
pass
if self.current_char is not None:
code = ord(self.current_char)
if not codepoint_ok(code):
@@ -483,10 +480,8 @@ def main(args):
handler = UnicodeInput(cached_values)
loop.loop(handler)
if handler.current_char and loop.return_code == 0:
try:
with suppress(Exception):
handler.recent.remove(ord(handler.current_char))
except Exception:
pass
recent = [ord(handler.current_char)] + handler.recent
cached_values['recent'] = recent[:len(DEFAULT_SET)]
return handler.current_char