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

@@ -7,6 +7,7 @@ import subprocess
import time
from collections import namedtuple
from urllib.request import urlopen
from contextlib import suppress
from .config import atomic_save
from .constants import cache_dir, get_boss, kitty_exe, version
@@ -56,7 +57,7 @@ def parse_line(line):
def read_cache():
notified_versions = {}
try:
with suppress(FileNotFoundError):
with open(version_notification_log()) as f:
for line in f:
try:
@@ -64,8 +65,6 @@ def read_cache():
except Exception:
continue
notified_versions[n.version] = n
except FileNotFoundError:
pass
return notified_versions
@@ -100,10 +99,8 @@ def run_worker():
import time
import random
time.sleep(random.randint(1000, 4000) / 1000)
try:
with suppress(BrokenPipeError): # happens if parent process is killed before us
print(get_released_version())
except BrokenPipeError:
pass # happens if parent process is killed before us
def update_check(timer_id=None):