Python“在”中不检查类型?
>>> False in [0]
True
>>> type(False) == type(0)
False
我偶然发现这一点的原因是:
在单元测试中,我为每种类型创建了有效和无效示例值的列表。 (“我的类型”我的意思是,它们并不 100% 等于 python 类型) 因此,我想迭代所有值的列表,如果它们在我的有效值中,则期望它们通过,另一方面,如果它们不在我的有效值中,则期望它们失败。 现在效果不太好:
>>> valid_values = [-1, 0, 1, 2, 3]
>>> invalid_values = [True, False, "foo"]
>>> for value in valid_values + invalid_values:
... if value in valid_values:
... print 'valid value:', value
...
valid value: -1
valid value: 0
valid value: 1
valid value: 2
valid value: 3
valid value: True
valid value: False
当然我不同意最后两个“有效”值。
这是否意味着我真的必须迭代我的 valid_values 并比较类型?
>>> False in [0]
True
>>> type(False) == type(0)
False
The reason I stumbled upon this:
For my unit-testing I created lists of valid and invalid example values for each of my types. (with 'my types' I mean, they are not 100% equal to the python types)
So I want to iterate the list of all values and expect them to pass if they are in my valid values, and on the other hand, fail if they are not.
That does not work so well now:
>>> valid_values = [-1, 0, 1, 2, 3]
>>> invalid_values = [True, False, "foo"]
>>> for value in valid_values + invalid_values:
... if value in valid_values:
... print 'valid value:', value
...
valid value: -1
valid value: 0
valid value: 1
valid value: 2
valid value: 3
valid value: True
valid value: False
Of course I disagree with the last two 'valid' values.
Does this mean I really have to iterate through my valid_values and compare the type?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
问题不在于缺少类型检查,而是因为在 Python 中
bool
是int
的子类。试试这个:The problem is not the missing type checking, but because in Python
bool
is a subclass ofint
. Try this:根据 文档,
__contains__
已完成通过迭代集合并按==
测试元素。因此,实际的问题是由False == 0
是True
这一事实引起的。According to the documentation,
__contains__
is done by iterating over the collection and testing elements by==
. Hence the actual problem is caused by the fact, thatFalse == 0
isTrue
.正如其他人所写的,“in”代码不会执行您希望它执行的操作。你还需要别的东西。
如果您确实想要进行类型检查(检查的是完全相同的类型),那么您可以在列表中包含该类型:
处理子类型有点困难,并且取决于您想要做什么。
As others have written, the "in" code does not do what you want it to do. You'll need something else.
If you really want a type check (where the check is for exactly the same type) then you can include the type in the list:
Handling subtypes is a bit more difficult, and will depend on what you want to do.
由于
True == 1
和False == 0
很难区分两者。一种可能但丑陋的方法(也不能保证在所有 Python 实现中都有效,但在 CPython 中应该没问题):
Since
True == 1
andFalse == 0
it's hard to differentiate between the two.One possible but ugly approach (which is also not guaranteed to work in all Python implementations but should be OK in CPython):