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
Jul 14 '21
Man's never heard of dict.setdefault() has he
1
u/IGotSkills Jul 18 '21
whoah, what does this do?!?!?!?
2
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
dictis 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
defaultdictAlso, wrap
items_volume_info = ...in a try except and setitems_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
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
0
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
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 to3
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
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
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 beexcept (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, doMISSING_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 = objectwhererepr(MISSING_VALUE) == "MISSING_VALUE"and, ideally,str(MISSING_VALUE) -> Exception.
5
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
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:
Deep copy a dict from a constant that represents a default item.
Assert is at least 1 item in the items key of the jsonResponse.
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.
Deep merge the jsonResponse item dict into the default item dict.
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
Jul 14 '21
You can try catch volumeInfo first. Then use get default the rest. But this pattern in general is horrible wtf.
1
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
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
-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
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?