Python 3.10 match如何比较1和True?
How does Python 3.10 match compares 1 and True?
PEP 622, Literal Patterns 表示如下:
Note that because equality (__eq__) is used, and the equivalency between Booleans and the integers 0 and 1, there is no practical difference between the following two:
case True:
...
case 1:
...
and True.__eq__(1)
and (1).__eq__(True)
both returns True, but when I 运行 these two code snippets with CPython, it seems like case True
and case 1
不一样。
$ python3.10
>>> match 1:
... case True:
... print('a') # not executed
...
>>> match True:
... case 1:
... print('a') # executed
...
a
1
和 True
实际比较如何?
查看模式匹配规范,这属于 "literal pattern":
A literal pattern succeeds if the subject value compares equal to the
value expressed by the literal, using the following comparisons rules:
- Numbers and strings are compared using the == operator.
- The singleton literals None, True and False are compared using the is
operator.
所以当模式是:
case True:
使用is
,1 is True
为false。另一方面,
case 1:
使用 ==
,1 == True
为真。
PEP 622, Literal Patterns 表示如下:
Note that because equality (__eq__) is used, and the equivalency between Booleans and the integers 0 and 1, there is no practical difference between the following two:
case True: ... case 1: ...
and True.__eq__(1)
and (1).__eq__(True)
both returns True, but when I 运行 these two code snippets with CPython, it seems like case True
and case 1
不一样。
$ python3.10
>>> match 1:
... case True:
... print('a') # not executed
...
>>> match True:
... case 1:
... print('a') # executed
...
a
1
和 True
实际比较如何?
查看模式匹配规范,这属于 "literal pattern":
A literal pattern succeeds if the subject value compares equal to the value expressed by the literal, using the following comparisons rules:
- Numbers and strings are compared using the == operator.
- The singleton literals None, True and False are compared using the is operator.
所以当模式是:
case True:
使用is
,1 is True
为false。另一方面,
case 1:
使用 ==
,1 == True
为真。