Definindo Aliases com o Operador as no Pattern Matching - Python
O operador as
def print_person(person):
match person:
case "Tom" | "Tomas" | "Tommy" as name:
print(f"Name: {name}")
case _:
print("Undefined")
print_person("Tom") # Name: Tom
print_person("Tomas") # Name: Tomas
print_person("Bob") # Undefined
Aqui, o primeiro padrão corresponde a três strings: "Tom"
"Tomas"
"Tommy"
as
name
O alias pode ser aplicado tanto a valores individuais dentro do padrão quanto ao padrão inteiro:
def print_person(person):
match person:
case ("Tom" | "Tomas" as name, 37 | 38 as age): # aliases para valores individuais
print(f"Tom| Name: {name} Age: {age}")
case ("Bob" | "Robert", 41 | 42) as bob: # alias para o padrão inteiro
print(f"Bob| Name: {bob[0]} Age: {bob[1]}")
case _:
print("Undefined")
print_person(("Tomas", 38)) # Tom| Name: Tomas Age: 38
print_person(("Robert", 41)) # Bob| Name: Robert Age: 41
Em geral, os aliases são mais úteis em dados com estruturas mais complexas. Por exemplo:
class Person:
__match_args__ = ("name", "age")
def __init__(self, name, age):
self.name = name
self.age = age
def print_family(family):
match family:
case (Person() as husband, Person() as wife):
print(f"Husband. Name: {husband.name} Age: {husband.age}")
print(f"Wife. Name: {wife.name} Age: {wife.age}")
case _:
print("Undefined")
print_family((Person("Tom", 37), Person("Alice", 33)))
# Husband. Name: Tom Age: 37
# Wife. Name: Alice Age: 33
print_family((Person("Sam", 28), Person("Kate", 25)))
# Husband. Name: Sam Age: 28
# Wife. Name: Kate Age: 25
Aqui, a função print_family
Person
husband
wife