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.
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.
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.
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?
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
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.
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.
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.
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?
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.
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
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.
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.
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.
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.
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.
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
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.
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).
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.)
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).
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.
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?
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.
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.
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 😆
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?
2
u/pekkalacd Oct 04 '21
There’s empty exceptions. How will they know what piece causes the error?
76
u/[deleted] Jul 14 '21
Man's never heard of
dict.setdefault()has he30
u/AchillesDev Jul 14 '21
Everyone in this thread needs to review the collections module.
38
u/clemesislife Jul 14 '21
I'm not sure if there is good way to do this
5
u/LegloBluda Jul 14 '21 edited Jul 14 '21
Maybe not the shortest solution, but it doesn't include anything additional, and, in my opinion, is the cleanest and most readable.
6
u/[deleted] Jul 14 '21
Why is it bad?
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
3
u/RyanNerd shameless Jul 14 '21
Ah... Programming by exception what a horrible design pattern you've discovered.
1
u/Attack_Bovines Jul 14 '21
Here’s what I would do instead:
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
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.
-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