[Python-ideas] Pattern Matching Syntax

Terry Reedy tjreedy at udel.edu
Thu May 3 18:09:32 EDT 2018


On 5/3/2018 8:41 AM, Robert Roskam wrote:

> However, I don't see that the conversation ever really resolved, so I'd 
> like restart the conversation on some kind of pattern matching syntax in 
> Python.

For the cases not handled by dicts, I believe chained conditional 
expressions work.

"""
# Pattern matching with guards
x = 'three'

number = match x:
     1 => "one"
     y if y is str => f'The string is {y}'
     _ => "anything"

print(number)  # The string is three
"""

Is handled by

def f(x):
     return ('one' if x == 1 else
             f'The string is {x}' if isinstance(x, str) else
             'anything')

for x in 1, '2', 3: print(f(x))

I don't like the ordering, but this was Guido's decision.

 >     1, 2, 3, 4 => "one to four"

"one to four' if x in (1,2,3,4)

 >    x:int => f'{x} is a int'
 >    x:float => f'{x} is a float'
 >    x:str => f'{x} is a string'

tx = type(x)
f'{x} is a {tx}' if tx in (int, float, str) else None



-- 
Terry Jan Reedy



More information about the Python-ideas mailing list