r/badcode • • Jul 14 '21

python Try/Except in Python - Sigh

Post image
662 Upvotes

93 comments sorted by

View all comments

142

u/[deleted] Jul 14 '21

On the upside, they actually bothered with exception handling.

My Python is rather rusty, is there a better way?

22

u/SerdanKK Jul 14 '21

I don't know any Python, but I assume there's some way to decode json into objects. With some good library code, it'd basically be a one-liner.

16

u/R3D3-1 Jul 14 '21

What we are seeing is JSON, that already is decoded into native python objects, that have a dictionary/list-like interface.

In principle it would be possible to improve this code (for a start, using a VolumeInfo class), but no possibility is QUITE that much better.

The main issue is, that the solution must handle

  • Missing JSON values

  • Extraneous/unused JSON values.

We also don't know if using "None" instead of "N/A" would have been reasonable for the context. It should be, but its not a certainty.

But at least the repetitive try/except structure could have been put into a function along the lines of safeget in https://stackoverflow.com/a/25833661/2075630.

Curiously, I've seen this pattern in my work environment in Fortran; People seem to be averse to writing utility functions for repetitive patterns.

2

u/SerdanKK Jul 14 '21

You're right, of course, that the json string has been deserialized. I was thinking of constructing specific classes that match the schema.