Python中的x is not None vs. not x is None

坚持写博客,分享自己的在学习、工作中的所得

  1. 给自己做备忘
  2. 对知识点记录、总结,加深理解
  3. 给有需要的人一些帮助,少踩一个坑,多走几步路

尽量以合适的方式排版,图文兼有
如果写的有误,或者有不理解的,均可在评论区留言
如果内容对你有帮助,欢迎点赞 👍 收藏 ⭐留言 📝。
虽然平台并不会有任何奖励,但是我会很开心,可以让我保持写博客的热情



🐍Python中的x is not None vs. not x is None

在Python中,要判断一个变量是否为None时,是不能使用==判断的,而是使用is运算符;

但是当要判断一个变量是否不为None时,是使用x is not None还是使用not x is None?这两者之间有没有什么区别呢?

not is vs. is not

答案是使用is not运算符而不是not ... is。虽然这两个表达式在功能上是相同的,但前者更具可读性和首选。

使用is not
使用is not
使用is not

谷歌的风格指南(2.14 True/False Evaluations)PEP-8都使用x is not None

差异比较

x = None
if not x is None:
    print('x is not None')
else:
    print('x is None')
    
if x is not None:
    print('x is not None')
else:
    print('x is None')
x is None
x is None
x = []
if not x is None:
    print('x is not None')
else:
    print('x is None')
    
if x is not None:
    print('x is not None')
else:
    print('x is None')
x is not None
x is not None
import dis
dis.dis("x is not None")
  1           0 LOAD_NAME                0 (x)
              2 LOAD_CONST               0 (None)
              4 COMPARE_OP               9 (is not)
              6 RETURN_VALUE
dis.dis("not x is None")
  1           0 LOAD_NAME                0 (x)
              2 LOAD_CONST               0 (None)
              4 COMPARE_OP               9 (is not)
              6 RETURN_VALUE

在这里插入图片描述

上面的例子中,not x is None的结果与x is not None相同是因为运算符的优先级is的优先级要比not的优先级高

虽然编译后都是一样的,运行的结果也没有差异,但是语义上可能会有误解:

if not x is None可能会被理解为if (not x) is None

if x is not None则避免了这种情况

在编程中尽量避免使容易产生歧义的if not x is None

总结

  1. 使用x is not None
  2. x is not Nonenot x is None的结果没有差异,但是后者容易出现歧义,可读性差


如果内容对你有帮助,或者觉得写的不错
🏳️‍🌈欢迎点赞 👍 收藏 ⭐留言 📝
有问题,请在评论区留言

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

斌zz

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值