Home  >  Article  >  Backend Development  >  Use if x is not None or if not x is None

Use if x is not None or if not x is None

anonymity
anonymityOriginal
2019-05-24 13:48:354180browse

Should I use if x is not None or if not x is None?

Google's style guide and PEP-8 both use if x is not None, so is there some slight performance difference between them?

Use if x is not None or if not x is None

It was found through testing that there is no performance difference because they compile to the same bytecode:

Python 2.6.2 (r262:71600, Apr 15 2009, 07:20:39)>>> 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

But in terms of usage style, try to avoid not x is y. Although the compiler always treats this as not (x is y), readers may misunderstand the construction as (not x) is y. So if x is not y there is no such ambiguity.

The above is the detailed content of Use if x is not None or if not x is None. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn