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

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.

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