Follow

If you wanted to write a conditional to check whether both a and b are None or neither are None, would you use comparison chaining for either condition, both conditions, or neither?

Chaining:

if a is b is None:

if a is not None is not b:

Non-chaining:

if a is None and b is None:

if a is not None and b is not None:

@pganssle Another pattern would be to use any() or all() with a list-comprehension -- which would be good if there's a chance that a "c" or "d" will show up. That is:
if any(x is None for x in (a, b)):
#python

@meejah Yeah, that seems a bit of premature optimization for variable literals, though. I'm pretty sure it will always be faster and more compact to use chaining on the "is" case even if the number of elements grows:

if a is b is c is d:
...

This doesn't need to construct a tuple, a generator, or invoke a function.

For the `is not` case you need N - 1 "None"s to compare N variables, so:

if a is not None is not b is not None is not c:
...

So there's a stronger case for `all(x is not None for x in (a, b, c, d))`.

@pganssle Yeah .. I guess I should remember that a lot of these "style" type questions don't have a right answer ;)
Sometimes I find it makes things more-clear to assign to a variable too, like:
required = (a, b, c, d)
if any(x is None for x in required):
raise ValueError(...)

Sign in to participate in the conversation
Qoto Mastodon

QOTO: Question Others to Teach Ourselves
An inclusive, Academic Freedom, instance
All cultures welcome.
Hate speech and harassment strictly forbidden.