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

@@ -8,6 +8,7 @@ import shlex
import sys
import traceback
from functools import lru_cache
from contextlib import suppress
from .cli import (
emph, green, italic, parse_option_spec, print_help_for_seq, title
@@ -68,10 +69,8 @@ class Completer:
def __init__(self):
self.matches = []
ddir = cache_dir()
try:
with suppress(FileExistsError):
os.makedirs(ddir)
except FileExistsError:
pass
self.history_path = os.path.join(ddir, 'shell.history')
def complete(self, text, state):
@@ -86,10 +85,8 @@ class Completer:
return self.matches[state]
def __enter__(self):
try:
with suppress(Exception):
readline.read_history_file(self.history_path)
except Exception:
pass
readline.set_completer(self.complete)
delims = readline.get_completer_delims()
readline.set_completer_delims(delims.replace('-', ''))