Which one should I use, if x is not None or if x is None?

Asked 2 years ago, Updated 2 years ago, 99 views

I if not x is none thought a good representation to read more. google style guide in if x is not none , to write.

Is it because of the speed difference between you two? Or is it because if not x is None is less readable?

python coding-style boolean-expression

2022-09-22 15:44

1 Answers

The reason why if xis not None is recommended instead of not xisy when writing code is because In the compiler, no matter what you use, you use not (xisy) in the same way This is because there is room for human reading to be interpreted as (not x) is y.

As shown below, there is no difference in performance speed because the two are compiled in the same byte code.

Python 2.6.2
>>> import dis
>>> def f(x):
...    ...    return x is not None
...
>>> dis.dis(f)
  2           0 LOAD_FAST                0 (x)
              3 LOAD_CONST               0 (None)
              6 COMPARE_OP               9 (is not)
              9 RETURN_VALUE
>>> def g(x):
...   ...   return not x is None
...
>>> dis.dis(g)
  2           0 LOAD_FAST                0 (x)
              3 LOAD_CONST               0 (None)
              6 COMPARE_OP               9 (is not)
              9 RETURN_VALUE


2022-09-22 15:44

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.