python使用 ‘if x is not None’ 还是’if not x is None’

今天爱分享给大家带来python使用 ‘if x is not None’ 还是’if not x is None’,希望能够帮助到大家。
性能上没有什么区别,他们编译成相同的字节码


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


在风格上,我尽量避免 ‘not x is y’ 这种形式,虽然编译器会认为和 ‘not (x is y)’一样,但是读代码的人或许会误解为 ‘(not x) is y’

如果写作 ‘x is not y’ 就不会有歧义

最佳实践


if x is not None:
    # Do something about x


原文链接:https://blog.itblood.com/3886.html,转载请注明出处。
0
已婚妇女VS恶魔战士自慰妓女和育婴地牢1.0汉化版[PC+安卓/2.17G] [爆款RPG/AI汉化]
已婚妇女VS恶魔战士自慰妓女和育婴地牢1.0汉化版[PC+安卓/2.17G] [爆款RPG/AI汉化]
刚刚 有人购买 去瞅瞅看

站点公告

显示验证码
没有账号?注册  忘记密码?