4 ms·
> (To the best of my knowledge, there is as of 2020 no purely pythonic way to write one-lined try-blocks.) You can do this using contexlib. For example the fol
by c-jiph 6y ago
> (To the best of my knowledge, there is as of 2020 no purely pythonic way to write one-lined try-blocks.)
You can do this using contexlib. For example the following in pwk:
try: { print(os.listdir("/"+s.strip())) } except: pass
Can be written in pure Python as:
with contextlib.suppress(Exception): print(os.listdir("/"+s.strip()))
(Assuming contextlib is imported, and you're okay with letting things which don't extend Exception slip through.)
You could probably also make a context manager which takes a function/lambda to define how to handle exceptions etc.
- uranusjr 6y ago`contextlib.suppress(BaseException)` is possible if you really want to (although both this and the bare except clause should be avoided anyway).