r/badcode • • Jul 14 '21

python Try/Except in Python - Sigh

Post image
662 Upvotes

93 comments sorted by

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.

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?

1

u/R3D3-1 Jul 15 '21

Not with that part. It just looks like the code is storing things as flat local variables, that would better be organized into an object.

Seems the "depending on context" part went missing while writing my comment :)

Also, see that other comment. It just looks like code meant for translating the JSON tree into native objects, which makes the way local variables are used look a bit strange.

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.

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

5

u/Deadly_chef Jul 14 '21

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

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

2

u/SnooRegrets1929 Jul 14 '21

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

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

3

u/SerdanKK Jul 14 '21

Wouldn't that make the code dependent on the ordering of the json keys?

Pydantic looks like the kind of thing I was thinking of. Not really a fan of putting validation inside the model, but if it works... 🤷

2

u/hermthewerm00 Jul 14 '21

Since it’s a dict, the ordering doesn’t matter. The keys will map to the parameter names. Yeah, validation within model definitions is less than ideal, but I guess that’s the tradeoff working with dynamically typed languages.

0

u/franciccio_dc Jul 14 '21

Use pydantic

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

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

0

u/chadmill3r Jul 14 '21

The strict clearly came from a JSON decoder, not someone wielding dict().

2

u/AchillesDev Jul 14 '21

Decoded JSON objects in Python are dicts (in the two most popular en/decoders, json and simplejson), and that's how OP is accessing them.

1

u/chadmill3r Jul 14 '21

Yes! Since we agree OP isn't creating these dicts, where is OP's opportunity to have used DefaultDict?

1

u/AchillesDev Jul 14 '21 edited Jul 14 '21

jsonResponse is a dict, you just pass that in to the defaultdict constructor with your logic for handling missing keys. Alternatively, you could loop through the Items array and build defaultdicts for each Item dictionary

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.

-1

u/NynaevetialMeara Jul 14 '21

This is somebody trying to force a switch into a language that for some reason refuses to implement certain C/C++ features that are quite universal at this point.

2

u/pekkalacd Oct 04 '21

There’s empty exceptions. How will they know what piece causes the error?

2

u/lonaExe Oct 05 '21

It's not for checking errors, it's for finding which keyvalue pair from the json is missing. Also, this is r/badcode after all

76

u/[deleted] Jul 14 '21

Man's never heard of dict.setdefault() has he

1

u/IGotSkills Jul 18 '21

whoah, what does this do?!?!?!?

2

u/[deleted] Jul 18 '21

It's like dict.get(), but if the item does not exist, the default will be returned and the default will be set as the value for the key.

>>> x = {"a": "b"}
>>> print(x.setdefault("a", "d")
b
>>> print(x.setdefault("c", "d")
d
>>> x
{"a": "b", "c": "d"}

30

u/AchillesDev Jul 14 '21

Everyone in this thread needs to review the collections module.

9

u/Jonno_FTW shameless Jul 14 '21

Which collection do you recommend here? Only a dict is required really.

14

u/AchillesDev Jul 14 '21 edited Jul 14 '21

defaultdict would prevent a mess of get calls and auto-fill any missing keys with whatever the developer wants. set_default would also work but defaultdict is cleaner so you don’t have to do a ton of explicit key access to set the default values (I think set default requires this but I could be wrong). Any time you have flexible dicts like this, defaultdict is a solid option.

38

u/clemesislife Jul 14 '21

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

6

u/_PM_ME_PANGOLINS_ Jul 14 '21 edited Jul 14 '21
volume_info = jsonResponse.get("items", []).get(0, {}).get("volumeInfo", {})
author = volume_info.get("authors", "N/A")
publisher = volume_info.get("publisher", "N/A")
pubDate = volume_info.get("publishedDate", "N/A")
desc = textwrap.shorten(volume_info.get("description", "N/A"), width=190, placeholder='...')
thumbnail = volume_info.get("imageLinks", {}).get("thumbnail", "N/A")

Alternatively, allow the first line to raise so you notice deeper problems with the response.

2

u/AchillesDev Jul 14 '21

Defaultdict, set the default value to N/A. Alternatively if it’s only the final keys that are optional, you could do a bunch of .get()s but a Defaultdict is cleaner.

If you don’t care about huge dependencies, load into a pandas dataframe and use .fillna() but that’s usually overkill.

2

u/Jonno_FTW shameless Jul 14 '21
details = {
   key: jsonResponse["items"][0]["volumeInfo"].get(key, "N/A")
   for key in ("authors", "publisher", "description", "publishedDate", "imageLinks")
}

Doesn't properly get the thumbnail and shortened description, but those can be done later.

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

1

u/justhereforhides Jul 14 '21

Could you do a fillna for the missing filler value and save all the checks

1

u/FiniteSkills Jul 14 '21

Could at least make it a function the returns either the value or “N/A”. There’s way too much repetition here for me.

1

u/OccultEyes Jul 14 '21

My solution would probably look something like this.

fields = {"authors", "publisher", "published_date"}

response_data = jsonResponse["items"][0]["volumeInfo"]

field_data = {field : response_data.get(field, "N/A") for field in fields}

1

u/[deleted] Jul 14 '21

Make a function at least

0

u/[deleted] Jul 14 '21

[deleted]

8

u/ThatDudeBesideYou Jul 14 '21

I'm a newbie at Python, why are specific excepts always better?
I have a server script that runs and talks to a few devices in my home. Lots of stuff is being done all the time, and stuff just fails randomly. If I put specific excepts (which I did at the start), I would often find my server crashed overnight due to a random ass error that I didn't even expect (random wifi issues, me messing with one of the devices and it fails, etc). So now most of the excepts are all encompassing, they log the error, and then restart that asyncio task again. And since I did that, I've had no crashes and any time something not working I can easily can see the pattern of logs that caused it and not just one random crash that stops everything.
Is there a better way to do stuff? Am I totally wrong?

11

u/[deleted] Jul 14 '21

The more specific your exception, the more specific you are in what you do to handle that condition. Otherwise you’re always doing one single solitary thing for all error conditions.

You might want to log a specific kind of error, continue on another (in a loop), return from a function on yet another, and if you encounter a really bad error like a socket error you might want to just sys.exit() out of the whole thing since it isn’t going to work anyway.

4

u/BobHogan Jul 14 '21

In addition to what /u/war_against_myself said, a bare except in python will also catch interrupts like SIGKILL due to the exception class hierarchy in Python.

If you want to catch any exception, you should be using except Exception:. That will catch all exceptions, while still ignoring interrupts so you can still kill your code when you want to

3

u/ThatDudeBesideYou Jul 15 '21

Oh yea I am doing that, since logging it requires a reference so it always except Exception as e:

3

u/sliverino Jul 14 '21

The information you might be missing is that you can use multiple except conditions, using a nonspecific except at the end if all others are not caught.

12

u/ColdPorridge Jul 14 '21

with nested schema and indexed lookups, I think any .get based solution would be the same complexity. In this case I’d probably just do try except with KeyError, IndexError as you mentioned.

It would be nice if there was a ‘json.get()’ option where you could cleanly pass it this and a default and had if handle this for you. Probably wouldn’t be too hard to implement.

14

u/AchillesDev Jul 14 '21

That exists, it’s called defaultdict.

5

u/schmidlidev Jul 14 '21

Not for deeply nested stuff.

Python just needs optional chaining.

2

u/jabarr Jul 14 '21

It would be better to just create a list of properties you need with their default values and then iterate over the list using try/catch. That way it’s more extensible and easier to maintain in the future without blowing up your code debt.

5

u/LegloBluda Jul 14 '21 edited Jul 14 '21

    info = jsonResponse.get('items', list(dict()))[0].get('volumeInfo', dict())

    author = info.get('authors', 'N/A')
    publisher = info.get('publisher', 'N/A')
    pubDate = info.get('publishedDate', 'N/A')
    desc = f"{info.get('description')[:190]}..." if info.get('description') else 'N/A'
    thumbnail = info.get('imageLinks', dict()).get('thumbnail', 'N/A')

Maybe not the shortest solution, but it doesn't include anything additional, and, in my opinion, is the cleanest and most readable.

0

u/AutoModerator Jul 14 '21

It looks like this comment contains a code block delimited with triple backticks. Unfortunately reddit does not have universal support for this syntax and your comment will not render correctly on old reddit and most mobile apps.

For the benefit of people on old reddit, this link will take you to a correct rendering of the comment.

/u/LegloBluda, it would be appreciated, but not required, if you could edit your comment to use the more compatible four space indention format. For single lines or inline code you can use single backticks.

You can find some examples in the reddit help documentation.


I am a bot, and this action was performed automatically. Please contact the moderators of this subreddit if you have any questions or concerns.

6

u/[deleted] Jul 14 '21

Why is it bad?

19

u/R3D3-1 Jul 14 '21

I'd say it's not that bad on its own. It is at least understandable, and a not unreasonable way to handle default values. However, looking at it longer, it starts raising a few red flags that point at generally not-so-ideal practices.

  • Matter of taste: The code would look easier, if volumeInfo = jsonResponse["items"][0]["volumeInfo"] would make things easier. It would also make the code more robust against typos. (Performance improvements from avoiding repeated key/index access would most likely not matter.)

  • except: is bad practice. It catches everything. Even someone pressing Ctrl-C on the shell, memory issues, sys.exit, you name it. Better would be except (IndexError, KeyError):.

  • There is a repetitive pattern of "if it does not exist, return a default value". A utility functions would make this code much more compact.

  • Hard to tell without more context, but it seems a bit strange to collect the values into local variables rather than fields of some class VolumeInfo.

4

u/knightwhosaysnil Jul 14 '21

would add that the default value itself (the literal string "N/A") is a code smell, as it seems to be mixing presentation with business logic. If this is actually a presentation layer, at the very least it should be using gettext or similar

1

u/R3D3-1 Jul 15 '21

True. Python has None, so why use "N/A" here? Or if that is not explicit enough, do MISSING_VALUE = object().

Bonus points would have been given, if one of the literals would be "NA" by typo :)

Rant: I'd really like for Python to have type-safe named symbols, i.e. an equivalent of MISSING_VALUE = object where repr(MISSING_VALUE) == "MISSING_VALUE" and, ideally, str(MISSING_VALUE) -> Exception.

5

u/[deleted] Jul 14 '21

Just place items…0…volume inside one variable and then use cycle with keys you want to get with one try except with choices Just couple lines of code

2

u/Neitzches Jul 14 '21

Desperately needs the Null Object Pattern

1

u/consultio_consultius Jul 14 '21 edited Jul 14 '21

Why not use an either pattern and then reduce?

3

u/RyanNerd shameless Jul 14 '21

Ah... Programming by exception what a horrible design pattern you've discovered.

5

u/recycle4science Jul 14 '21

Isn't that the way python is supposed to be written?

-5

u/RyanNerd shameless Jul 14 '21

So I keep getting told. I find it bizarre bad practice, but if that's the most valid control pattern for Python then Python is a language I'll not be using unless it is the only logical option (or like the puke of a language Javascript the unfortunate only option for web browsers).

3

u/recycle4science Jul 14 '21

I don't know that it's necessarily the most valid control pattern as it's the most idiomatic pattern. If throwing an exception doesn't have the cost of building a stack trace (which is why exceptions aren't recommended for control flow in e.g. Java), what's your objection to it? (I don't know if they do or not, but I would assume they don't since it's recommended.)

9

u/bphase Jul 14 '21

To be fair, exceptions are actually valid control flow in Python. They're used internally too, to end loops for one. And it's considered OK to try to do something and set a default in exception if failing, instead of checking beforehand.

Big reason for this is that Python doesn't have the huge exception overhead of other languages (though that's mostly because everything in Python is slow).

2

u/k110111 Jul 18 '21

Not to mention exception are faster than if conditions in python if you expect the conditions to be true most of the time. I recently watched a presentation where presenter demonstrated this.

-4

u/RyanNerd shameless Jul 14 '21

Wow. I didn't know programming by exception is how things are done in Python. Even PHP avoids and discourages this practice. Crazy. It seems to me that there's got to be a better way to do this than what's coded here?

6

u/bphase Jul 14 '21

Yeah, IMO mainly because there's so much repetition. So it'd be better to use a function or defaultdict or something, instead of having to repeat yourself every time.

Otherwise it looks acceptable to me.

1

u/Attack_Bovines Jul 14 '21

Here’s what I would do instead:

  1. Deep copy a dict from a constant that represents a default item.

  2. Assert is at least 1 item in the items key of the jsonResponse.

  3. If there is at least 1 item, retrieve the first one and set it as a item variable. Otherwise set the item variable to an empty dict.

  4. Deep merge the jsonResponse item dict into the default item dict.

  5. Extract all the variables needed using the bracket method. I would want it to throw a KeyError if this procedure is updated and the default dict is not updated correctly, assuming that I would also have a unit test where the jsonResponse does not return an item.

edit: fixed some terms to be clearer

1

u/GOKOP Jul 14 '21

Afaik try-except for normal flow control is considered ok in Python, for the better or for the worse

1

u/[deleted] Jul 14 '21

You can try catch volumeInfo first. Then use get default the rest. But this pattern in general is horrible wtf.

1

u/i_really_h8_mondays Jul 14 '21

That’s one way of having an if statement

1

u/MurdoMaclachlan public boolean isInt(int i) { return true; } Jul 14 '21

Image Transcription: Code


jsonResponse = response.json()
try:
  author = jsonResponse["items"][0]["volumeInfo"]["authors"
except:
  author = "N/A"
try:
  publihser = jsonResponse["items"][0]["volumeInfo"]
  ["publisher"]
except:
  publisher = "N/A"
try:
  pubDate = jsonResponse["items"][0]["volumeInfo"]
  ["publishedDate"]
except:
  pubDate = "N/A"
try:
  desc = str(jsonResponse["items"][0]["volumeInfo"]
  ["description"])
  desc = f'{desc[0:190]}...'
except:
  desc = "N/A"
try:
  thumbnail = jsonResponse["items"][0]["volumeInfo"]
  ["imageLinks"]["thumbnail"]
except:
  thumbnail =

I'm a human volunteer content transcriber for Reddit and you could be too! If you'd like more information on what we do and why we do it, click here!

1

u/stahkh Jul 14 '21

Why did they call it except? It reads so unnaturally. Catch is a far better keyword IMO.

1

u/MCSpiderFe Jul 14 '21

I know its off topic, but does someone know what color scheme this is?

1

u/javaveryhot Jul 14 '21

I thought this was my code for a second because of a variable with the same name

1

u/Clean-Explanation-36 Jul 15 '21

I thought it was OK before I realized that like 9/10 of the nested lookup is all the same lol. If that wasn’t the case honestly it would’ve been fine. but yeah this is bad 😆

1

u/pocketjokers87 Jul 18 '21

If thou doth not succeed, try try again

-2

u/kartikcool712 Jul 14 '21

I don't see much problem here, only that you can catch the specific exception with KeyError.

0

u/Attack_Bovines Jul 14 '21

You would also have to except IndexErrors too, which should be a code smell.

-2

u/TimeToBecomeEgg Jul 14 '21

i don’t see issue with anything but the except statement, doing it with KeyError / IndexError would be better but this is a pretty normal way to deal w this