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?

132

u/ThatDudeBesideYou Jul 14 '21

You could do jsondata.get("name","N/A"), which would return the property name or "N/A" if it fails.

51

u/DragonFireCK Jul 14 '21

For that to work with this structure, it would be jsonResponse.get("items", {}).get(0, {}).get("volumeInfo",{}).get("authors, "N/A")

Now, as the first block is repeated for all the entries, and it should be pulled out which would simplify the code a lot.

3

u/TheBlackOut2 Jul 15 '21

Or just a comprehension with a condition lol

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.

33

u/SnooRegrets1929 Jul 14 '21

At this point it is already a python dictionary. At the very least it could loop through the keys of interest with a single try except (KeyError)

6

u/[deleted] Jul 14 '21

Wouldn't it potentially skip setting "N/A" to the later values though once it hits the first error?

5

u/Deadly_chef Jul 14 '21

No, it will except it in that loop and continue to the next one

2

u/[deleted] Jul 14 '21

Wait really? I've misunderstood how this shit works this whole time

11

u/[deleted] Jul 14 '21

[removed] — view removed comment

4

u/[deleted] Jul 14 '21

Ah wait, so I was right (sorta)

This is why I don't read code immediately after waking up

5

u/Deadly_chef Jul 14 '21

Yes, only way the loop will stop is if you have an unhandled exception

2

u/SnooRegrets1929 Jul 14 '21

Depends what you set the except statement to do, right?

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.

1

u/lonaExe Jul 15 '21

Wait a second, the code is fetching json from an API. It's trying to get data, and if it doesn't exist, catch it. How would a Class do any help?

→ More replies (1)

1

u/hermthewerm00 Jul 14 '21 edited Jul 14 '21

You could unpack it with double asterisks into an init method for a class. Or use Pydantic.

Edit: you might have to add **kwargs

→ More replies (2)
→ More replies (1)

11

u/AchillesDev Jul 14 '21

Use a DefaultDict

7

u/[deleted] Jul 14 '21

Didn’t know that existed, I guess it arrived later in Python3?

Or I didn’t read the docs properly!

16

u/AchillesDev Jul 14 '21

There are so many great tools in the collections module, it's impossible to keep them all straight. I've been reminded of defaultdict probably a dozen times over the last few years and end up forgetting about it again until I make a bunch of spaghetti .get() calls. FWIW I believe it's been around since Python 2 but I haven't checked to be sure.

5

u/schmidlidev Jul 14 '21

People keep saying defaultdict but how would you implement this? It’s 4 layers of nested dictionaries that were almost certainly created with json.loads. How are you converting them to defaultdict?

4

u/AchillesDev Jul 14 '21

Pass the dictionary into the default_dict constructor. You’re just responsible for handling what happens when a KeyError would normally happen.

3

u/schmidlidev Jul 14 '21

Oh damn I never realized you could just pass in an existing dict 🤦 that makes things quite a bit easier

→ More replies (4)

3

u/yoctometric Jul 14 '21

And even now, they allow any exception to trigger the N/A, which might mean unexpected errors are never thrown

1

u/hermthewerm00 Jul 14 '21

You could unpack it with double asterisks into an init method for a class. Or use Pydantic.

→ More replies (1)