contextlib.suppress .. how..?
Rune Hansén Steinnes-Westum
1 min read
have I missed this? New in version Python 3.4..
Today I needed to retrieve a long-winded chat history from our corporate Teams .. thingie. Naturally, I fired up m365 and pulled a json
from the server.
While parsing the json
I got more than a couple of TypeError
and KeyError
...errors which I squashed with a try-except
. All of a sudden I heard Raymond Hettinger whispering in my ear .. "there has to be a better way!" - and lo and behold. Raymond was right!!
from contextlib import suppress
import json
with open("exportedchat.json", "r") as innfile, suppress(TypeError), suppress(KeyError):
doc = json.loads(fp)
for chatline in doc:
print(chatline["from"]["user"]["displayName"])
This is so much cleaner than try->except->pass
0
Subscribe to my newsletter
Read articles from Rune Hansén Steinnes-Westum directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by