Python:如果不是val,则如果val为None [英] Python: if not val, vs if val is None

查看:65
本文介绍了Python:如果不是val,则如果val为None的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直以if not value的样式进行编码,但是,一些指南引起了我的注意,尽管这种样式有效,但似乎存在两个潜在的问题:

I've always coded in the style of if not value, however, a few guides have brought to my attention that while this style works, it seems to have 2 potential problems:

  1. 它不完全可读; if value is None当然更容易理解.
  2. 这以后可能会产生影响(并引起细微的错误),因为[]0之类的东西也将评估为False.
  1. It's not completely readable; if value is None is surely more understandable.
  2. This can have implications later (and cause subtle bugs), since things like [] and 0 will evaluate to False as well.

我也开始将此想法应用于其他比较,例如:

I am also starting to apply this idea to other comparisons, such as:

  • if not valueif value is False
  • if not valueif value is []
  • if not value vs if value is False
  • if not value vs if value is []

列表也是如此...

问题是,您对这项原则走了多远?在确保代码安全的同时,在哪里划清界线?

The question is, how far do you go with the principle? Where to draw the line, while keeping your code safe?

无论如何,我应该始终使用if value is None样式吗?

Should I always use the if value is None style no matter what?

推荐答案

如果需要,请使用与None的比较.如果您只是想检查该值是否被认为是错误的,请使用"if not value"(空列表,none,false).

Use a comparison to None if that's what you want. Use "if not value" if you just want to check if the value is considered false (empty list, none, false).

我发现如果没有价值"看起来更加简洁和Pythonic.

I find "if not value" to be cleaner looking and Pythonic.

此外,请谨慎使用列表.比较空列表时,请勿使用is.如果知道要获取列表,请使用"if"检查列表是否包含任何内容(或len()).尝试在解释器中输入以下内容:

Also, be careful with lists. You should not use is when comparing for an empty list. If you know you're getting a list, use "if " to check if it has any contents (or len()). Try typing this into the interpreter:

>>> a = []
>>> a is []
False

这是因为您刚刚创建的临时列表在内存中的地址与在"a"处存储的地址不同.您不会在None,False或True上看到它,因为这些都是单例值(它们都指向内存的同一部分),因此使用'is'关键字即可.

This is because the temporary list you just made has a different address in memory than the one stored at 'a'. You don't see this with None, False, or True because these are all values that are singletons (they all refer to the same section of memory) so using the 'is' keyword works.

您还将发现CPython可以对字符串进行实习,因此以下工作有效.

You'll also find that CPython interns strings so the following works.

>>> 'a' is 'a'
True

您不应依靠此.这是一个实现细节,并非特定于每个版本的Python.

You should not rely on this. It is an implementation detail and this is not specified to work with every version of Python.

这篇关于Python:如果不是val,则如果val为None的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆