Skip to content

Instantly share code, notes, and snippets.

@giorgiberia
Created August 16, 2021 07:47
Show Gist options
  • Save giorgiberia/6b0a48bdaa243de297b919c86bb5d177 to your computer and use it in GitHub Desktop.
Save giorgiberia/6b0a48bdaa243de297b919c86bb5d177 to your computer and use it in GitHub Desktop.
python 3.10 match case examples
http_code = "418"
match http_code:
case "200":
print("OK")
do_something_good()
case "404":
print("Not Found")
do_something_bad()
case "418":
print("I'm a teapot")
make_coffee()
case _:
print("Code not found")
# --------------------------------------------------
match x:
case host, port:
mode = "http"
case host, port, mode:
pass
# equivalent
if isinstance(x, tuple) and len(x) == 2:
host, port = x
mode = "http"
elif isinstance(x, tuple) and len(x) == 3:
host, port, mode = x
# ---------------------------------------------------
quit = 4
match quit:
case True:
print("Quitting")
exit()
case False:
print("System is on")
case _:
print("Boolean Value was not passed")
# ---------------------------------------------------
match media_object:
case Image(type="jpg"):
# Return as-is
return media_object
case Image(type="png") | Image(type="gif"):
return render_as(media_object, "jpg")
case Video():
raise ValueError("Can't extract frames from video yet")
case other_type:
raise Exception(f"Media type {media_object} can't be handled yet")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment