Reputation: 92460
I am working on a personal API project that involves accepting requests with keywords many of which are required. Because of this I find myself writing defensively with a lot of code that looks like this:
def post(self, urlSafeKey=None):
if urlSafeKey:
# do a bunch
# of stuff
# here
else:
self.abort(400, detail="A key parameter is required")
I've been told to prefer if - else
over testing negatives with if not
for readability but when I go through and change all these blocks to something like this…
def post(self, urlSafeKey=None):
if not urlSafeKey: self.abort(400, detail="A key parameter is required")
# do a bunch
# of stuff
# here
…it looks cleaner and shorter, but I worry that it's an annoying stylistic habit and in the end might be less clear.
Is there a consensus on this in the Python world?
Upvotes: 2
Views: 75
Reputation: 882251
Assuming self.abort
raises an exception (and thus terminates function post
), I do believe it's best to avoid nesting the normal-case code inside an if
. import this
at an interactive interpreter prompt to be reminded of the "Zen of Python", one of whose koans is "flat is better than nested":-).
As for the one-liner
if not urlSafeKey: self.abort(400, detail="A key parameter is required")
it's a bit long for my personal tastes -- I prefer if
-based one liners to be limited to very short and concise cases, such as if cond: return
, if cond: continue
, if cond: break
, and otherwise use two lines. But this is really a minor (purely lexical!) issue compared with preferring the avoidance of nesting (i.e, check for "I'm done" conditions and exit the function or loop as early as you know it's done), which is a Python-Zen-level issue!-)
Upvotes: 2
Reputation: 11728
In general, following the best practice is best practice
. I don't recommend oneline statements. But I see nothing wrong with testing for not urlSafeKey
.
def post(self, urlSafeKey=None):
if not urlSafeKey:
self.abort(400, detail="A key parameter is required")
# do a bunch
# of stuff
# here
Upvotes: 2