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