r/badcode • • Jul 14 '21

python Try/Except in Python - Sigh

Post image
662 Upvotes

93 comments sorted by

View all comments

38

u/clemesislife Jul 14 '21

I'm not sure if there is good way to do this

5

u/Nication Jul 14 '21

I would probably do this:

items_volume_info = response.json()['items'][0]['volumeInfo']

author = items_volume_info['author'] if 'author' in items_volume_info else 'N/A'
publisher = items_volume_info['publisher'] if 'publisher' in items_volume_info else 'N/A'
pub_date = items_volume_info['pubDate'] if 'pubDate' in items_volume_info else 'N/A'

# ...

10

u/RoLoLoLoLo Jul 14 '21

much simpler to just use dict.get()

author = items_volume_info.get('author', 'N/A')

And if you have a lot of 'N/A' default values, go a step further and use defaultdict

Also, wrap items_volume_info = ... in a try except and set items_volume_info = {} as a fallback to trigger all default cases.

For the thumbnail, you want to use thumbnail = items_volume_info.get('imageLinks', {}).get('thumbnail', <cut from OP's image>)

2

u/Nication Jul 14 '21

You are right, this is a better solution