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 12:27:43 +02:00
parent d6e750727f
commit 2b095f720e
22 changed files with 68 additions and 138 deletions
+5 -12
View File
@@ -11,6 +11,7 @@ import re
import string
import sys
from time import monotonic
from contextlib import suppress
from .constants import (
appname, is_macos, is_wayland, supports_primary_selection
@@ -28,19 +29,15 @@ def load_shaders(name):
def safe_print(*a, **k):
try:
with suppress(Exception):
print(*a, **k)
except Exception:
pass
def log_error(*a, **k):
from .fast_data_types import log_error_string
try:
with suppress(Exception):
msg = k.get('sep', ' ').join(map(str, a)) + k.get('end', '')
log_error_string(msg.replace('\0', ''))
except Exception:
pass
def ceil_int(x):
@@ -258,15 +255,11 @@ class startup_notification_handler:
def remove_socket_file(s, path=None):
try:
with suppress(EnvironmentError):
s.close()
except EnvironmentError:
pass
if path:
try:
with suppress(EnvironmentError):
os.unlink(path)
except EnvironmentError:
pass
def unix_socket_paths(name, ext='.lock'):