Python Switch(Match-Case) Kullanımı
Python 3.10 sürümü ile match-case yapısına kavuştu. Daha önceki sürümlerde bunu yapabilmek için if-else veya dictionary gibi seçenekleri kullanıyorduk.
Kısaca switch-case nedir?
Switch-case bir ifadeyi bir duruma karşı değerlendiren ve ardından bazı kodları yürüten bir ifadedir.Karşılaşılan koşula veya koşullara bağlı olarak programın akışını kontrol edebilir.Aynı işlemler if-else ile yapılabilir ancak switch-case uzun işlemlerde kod okunabilirliğine büyük bir katkı sağlamaktadır. Diğer programlama dillerinde oldukça sık kullanılan bir yapıdır.Python ise bu özelliğe PEP 634 Structural Pattern Matching ile kavuştu.
Python'da Match-Case nasıl kullanılır?
Basit bir örnekle match-case kullanımı şu şekildedir 👇
day = 'Monday'
match day :
case 'Monday':
print('Yeeep today is Monday')
case 'Tuesday':
print('Today is Tuesday')
case 'Wednesday':
print('Today is Wednesday')
case 'Thursday':
print('Today is Thursday')
case 'Friday':
print('Today is Friday')
case 'Saturday':
print('Today is Saturday')
case 'Sunday':
print('Today is Sunday')
Output:
# Yeeep today is Monday
Ortak koşul için kullanımı 👇
day = 'Friday'
match day :
case 'Monday':
print('Yeeep today is Monday')
case 'Tuesday':
print('Today is Tuesday')
case 'Wednesday':
print('Today is Wednesday')
case 'Thursday':
print('Today is Thursday')
case 'Friday' | 'Saturday': # iki koşulu birleştirdik
print('No work tomorrow')
case 'Sunday':
print('Today is Sunday')
Output:
# No work tomorrow
Verilen değerin ilk indexine bakarak işlem yapabiliriz👇
response_code = 404
match int(str(response_code)[0]) :
case 2:
print('Success')
case 3:
print('Redirection')
case 4:
print('Client errors')
case 5:
print('Server errors')
Output:
# Client errors
Match-Case ile Default Değer Atama
Bulunan duruma uygun bir case yoksa default bir değerin olması çok işimize yarar. Bunu şu şekilde kullanabiliriz 👇
response_code = 600
match int(str(response_code)[0]) :
case 2:
print('Success')
case 3:
print('Redirection')
case 4:
print('Client errors')
case 5:
print('Server errors')
case _:
print("FATAL ERROR")
Output:
# FATAL ERROR
Match-Case ile Structure Eşleştirme
Basit bir örnek olarak 👇
for item in [[1, 2], [9, 10], [1, 2, 3], [1], [0, 0, 0, 0, 0]]:
match item:
case [x]:
print(f"single value: {x}")
case [x, y]:
print(f"two values: {x} and {y}")
case [x, y, z]:
print(f"three values: {x}, {y} and {z}")
case _:
print("too many values")
Output:
# two values: 1 and 2
# two values: 9 and 10
# three values: 1, 2 and 3
# single value: 1
# too many values
Match-Case ile Type Kontrolü
def type_of(var):
match var:
case int() | float() as var:
return "Number"
case dict() as var:
return "Dictionary"
case list() as var:
return "List"
case tuple() as var:
return "Tuple"
case set() as var:
return "Set"
case str() as var:
return "String"
case _:
return "Something else"
# print(type_of(3))
Output:
# Number
# print(type_of({'color': 'blue'}))
Output:
# Dictionary
Match-Case ile Pattern Guards
Pattern guards case dalına dahil edilebilecek boolean ifadelerdir. Case sadece if koşulu doğru olursa değerlendirilir.
class Dog:
def __init__(self, name):
self.name = name
class Cat:
def __init__(self, age):
self.age = age
def classify(pet):
match pet:
case Cat(age=age) if age % 2 == 0:
print("This cat has an even age!")
case Dog(name=name) if sorted(name) == list(name):
print("This dog's name is in alphabetical order!")
case _:
print("I have nothing interesting to say about this pet.")
#classify(Cat(4))
Output:
#This cat has an even age!
# classify(Dog('abc'))
Output:
# This dog's name is in alphabetical order!
# classify(Dog('alphabet'))
Output:
# I have nothing interesting to say about this pet.
Sonuç olarak
Bu makalede basit örneklerle temel match-case kullanımını anlatmak istedim.Daha farklı şekillerde kullanımı mümkün olmakla birlikte Python için harika bir yenilik.
Ayrıca bire real-life örneği olarak şu repoyu inceleyebilirsiniz
Kaynaklar
(ncik-roberts.github.io/posts/pep622.html)
(datagy.io/python-switch-case)
(peps.python.org/pep-0622)
(mybluelinux.com/python-casematch-structural..)
更多推荐
所有评论(0)