Dup Ver Goto 📝

MatchCase

PT2/lang/python/syntax does not exist
To
160 lines, 398 words, 3548 chars Page 'MatchCase' does not exist.

This arrived in Python 3.10.

Examples

Source: learnpython.com

command = 'Hello, World!'
match command:
    case 'Hello, World!':
        print('Hello to you too!')
    case 'Goodbye, World!':
        print('See you later')
    case other:
        print('No match found')

# Hello to you too!
def file_handler_v1(command):
    match command.split():
        case ['show']:
            print('List all files and directories: ')
            # code to list files
        case ['remove', *files]:
            print('Removing files: {}'.format(files))
            # code to remove files
        case _:
            print('Command not recognized')

Match list

a = ["hello","world","flibble"]
b = a + ["wibble"]
for x in [a,b]:
  match x:
    case ['hello',*xs]:
      print(xs)

# ['world', 'flibble']
# ['world', 'flibble', 'wibble']

Match dict

c = { "hello": "world" }
match c:
  case {"hello":x}:
    print(x)

Substring match

Source: stackoverflow

Use the str(x) if substr in x pattern:

my_str = "iwill/predict_something"
match my_str:
   case str(x) if 'predict' in x:
       print("match!")
   case _:
       print("nah, dog")

More Examples

Source geeksforgeeks

parameter = "Geeksforgeeks"

match parameter:

    case first  : 
        do_something(first)

    case second : 
          do_something(second)

    case third : 
        do_something(third)
        .............
        ............
    case "One" |  "Tother"  : 
        print("or !")
    case n :
        do_something(n)
    case _  : 
        no_match()

Structural Matching


def runMatch(data_input):
    match data_input:
        case["a"]:
            print("The list only contains a and is just a single list")

        case["a", *other_items]:
            print(f"The 'a' is the first element\
            and {other_items} are the rest  of the elements !")

        case[*first_items, "d"] | (*first_items, "d"):
            print(f"The 'd' is the last item and\
            {first_items} are the previous elements before it !")

        case  _:
            print("No case matches with this one !")

Dataclass Structural Matching

from dataclasses import dataclass

@dataclass
class Person:
    name: str
    age: int
    salary: int


@dataclass
class Programmer:
    name: str
    language: str
    framework: str


def runMatch(instance):
    match instance:
        case Programmer("Om", language="Python",
                        framework="Django"):
            print("He is Om and he is a Python programmer and \
            uses Django Framework!")

        case Programmer("Rishabh", "C++"):
            print("He is Rishabh and is a C++ programmer !")

        case Person("Vishal", age=5, salary=100):
            print("He is vishal and he is a kid !")

        case Programmer(name, language, framework):
            print(f"He is programmer , his name is {name} ,\
            he works in {language} and uses {framework} !")

        case Person():
            print("He is just a person !")

        case _:
            print("This person is nothiing !")


if __name__ == "__main__":
    programmer1 = Programmer("Om", "Python", "Django")
    programmer2 = Programmer("Rishabh", "C++", None)
    programmer3 = Programmer("Sankalp", "Javascript", "React")
    person1 = Person("Vishal", 5, 100)
    runMatch(programmer1)
    runMatch(programmer2)
    runMatch(person1)
    runMatch(programmer3)