Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does Python 3.10 match compares 1 and True?

PEP 622, 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?

like image 476
umitu Avatar asked Oct 14 '21 21:10

umitu


People also ask

Does Python 3.9 have match?

As of early 2021, the match keyword does not exist in the released Python versions <= 3.9. Since Python doesn't have any functionality similar to switch/case in other languages, you'd typically use nested if/elif/else statements or a dictionary.

How does match case work in Python?

You can keep using “match” or “case” as a variable name in other parts of your program. The case other is equivalent to else in an if-elif-else statement and can be more simply written as case _ . We're using the print() function here to simply print text to the screen.

Which version of Python has pattern matching?

'Structural Pattern Matching' was newly introduced in Python 3.10. The syntax for this new feature was proposed in PEP 622 in JUne 2020. The pattern matching statement of Python was inspired by similar syntax found in Scala, Erlang, and other languages.

What is structural pattern matching Python?

The match statement evaluates the “subject” (the value after the match keyword), and checks it against the pattern (the code next to case ). A pattern is able to do two different things: Verify that the subject has certain structure. In your case, the [action, obj] pattern matches any sequence of exactly two elements.


Video Answer


1 Answers

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.

like image 129
juanpa.arrivillaga Avatar answered Sep 23 '22 19:09

juanpa.arrivillaga