Whats a Match Statement in Python
Python offers a new statement called "match" as of version 3.10. This is known from other programming languages under the term switch-case.
This is a selection control mechanism with which the value of a variable can be analyzed and the appropriate program can be played.
user = "admin"
match user:
case "admin":
print("logged in as admin")
case "default":
print("logged in as default")
case _:
print("No valid user-type")
>>> logged in as admin
The match-case is a very lucid, short, and optimized notation to avoid if-elif-else statements. Read more about the 3.10+ version match statement here!
Implementing Match Statements in older Python versions
In older Python versions, the Switch/Match statement can also be implemented.
For this purpose, we use dictionaries for one-to-one key-value mappings.
cases = {
"admin": lambda: print("logged in as admin"),
"default": lambda: print("logged in as default"),
}
Using this, we can use pythons build-in method get(key[,default])
to returns the value for the specified key in the dict.
get(key: Any) -> Any | None
This would return the value from our key, or None if the key is not inside the dict.
To set a default (case _: ...
), we can give another param, which will be returned, when the key is not found.
get(key: Any, default: Any) -> Any
In our example the final code therefor would look something like this:
user = "admin"
cases = {
"admin": lambda: print("logged in as admin"),
"default": lambda: print("logged in as default"),
}
default = lambda: print("No valid user-type")
func = cases.get(user,default)
func()
>>> logged in as admin
If all statements should do the same, we of course can make this code simpler in just setting the values into the dict.
cases = {
"admin": "logged in as admin",
"default": "logged in as default",
}
default = "No valid user-type"
print(cases.get(user,default))
>>> logged in as admin
Top comments (0)