-1

In Python3, the Truth Value Testing in PEP8 says that for if A is None:, it can be converted to if not A:. Like so, since the code below looks so messy and hard to grasp at once, can it be expressed more succinct in one way or another?

if A is not None and B is not None and C is not None:

Seungho Lee
  • 1,068
  • 4
  • 16
  • 42
  • 3
    You have your logic reversed. `if A is None` can _sometimes_ be replaced by `if not A`, and `if A is not None` can _sometimes_ be replaced be `if A`, depending on the possible values of `A`. So it might be appropriate to replace your `if` statement with `if A and B and C` depending on the context. – khelwood Oct 10 '18 at 17:35
  • `if A:` and `if A is not None:` are **not** semantically equivalent. I'm pretty sure PEP8 does *not* say this, since this isn't an issue of style. – juanpa.arrivillaga Oct 10 '18 at 17:51
  • `A = 0` -- > `if A:` would not enter the if-block. `if A is not None:` would enter the if-block – Patrick Artner Oct 10 '18 at 17:53
  • I edited the logic as you've pointed out! Thank you! – Seungho Lee Oct 10 '18 at 18:30

2 Answers2

3

any() and all() can be used with a comprehension to help in these cases also.

if all([x is not None for x in [A,B,C]]):
superbeck
  • 501
  • 1
  • 4
  • 9
2

I agree with superbeck using any() or all() but you cal also check if None exist in a list including A, B, C

if not (None in [A,B,C]): or more intuitively if None not in [A, B, C]: (Blckknght)


side note (deeper dive)

Either way I would discourage using if A and B and C: because if A is not None and if A does different thing.

if A: calls A.__nonzero__() and uses return value of that function.

if A is not None is tests identity in Python. Because there is one and only one instance of None present in a running Python script/program

check this post and this post

OLIVER.KOO
  • 5,654
  • 3
  • 30
  • 62