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:
+2
-3
@@ -9,6 +9,7 @@
|
||||
# will replay the commands and pause at the end waiting for user to press enter
|
||||
|
||||
import sys
|
||||
from contextlib import suppress
|
||||
|
||||
|
||||
CSI = '\033['
|
||||
@@ -158,7 +159,5 @@ def replay(raw):
|
||||
def main(path):
|
||||
raw = open(path).read()
|
||||
replay(raw)
|
||||
try:
|
||||
with suppress(EOFError, KeyboardInterrupt):
|
||||
input()
|
||||
except (EOFError, KeyboardInterrupt):
|
||||
pass
|
||||
|
||||
Reference in New Issue
Block a user