PEP622 #Literal patterns says the following:
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 run these two code snippets with CPython, it seems like case True
and case 1
are not same.
$ python3.10
>>> match 1:
... case True:
... print('a') # not executed
...
>>> match True:
... case 1:
... print('a') # executed
...
a
How are 1 and True actually compared?
CodePudding user response:
Looking at the pattern matching specification, this falls under a "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.
So when the pattern is:
case True:
It uses is
, and 1 is True
is false. On the other hand,
case 1:
Uses ==
, and 1 == True
is true.