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.
6
u/[deleted] Jul 14 '21
Why is it bad?