Skip to content

Instantly share code, notes, and snippets.

@elidchan
Last active May 14, 2020 19:32
Show Gist options
  • Save elidchan/913b2e81026312745e8c1e7dac3b904f to your computer and use it in GitHub Desktop.
Save elidchan/913b2e81026312745e8c1e7dac3b904f to your computer and use it in GitHub Desktop.
Python switch statement
"""
Python switch statement
Usage:
```
from datetime import datetime
# import switch and case (below)
def spring_message(coils=3, is_expanded=False):
msg = ('\/' if is_expanded else '|/') * coils
print(msg)
return msg
def summer_message(current_time):
msg = "Summertime (at {time}) and the living's easy.".format(time=current_time.strftime('%I:%M%p'))
print(msg)
return msg
def fall_message():
msg = 'Have a nice trip - see you next fall!'
print(msg)
return msg
def winter_message(periods=1):
msg = 'Winter is coming{ellipsis}'.format(ellipsis='.' * periods)
print(msg)
return msg
season = 'spring'
switch(
season,
dict(
spring=case(spring_message, coils=7, is_expanded=False),
summer=case(summer_message, current_time=datetime.utcnow().time()),
fall=case(fall_message),
winter=case(winter_message, periods=5, continue_to='spring'),
),
default=42,
)
```
"""
from functools import partial
class Sentinel:
pass
def switch(value, cases, default=Sentinel):
try:
casing = cases[value]
except KeyError:
if default is Sentinel:
raise
casing = default
case_value = casing() if callable(casing) else casing
if hasattr(casing, 'continue_to') and casing.continue_to is not None:
return switch(casing.continue_to, cases, default=default)
return case_value
def case(func, continue_to=None, *args, **kwargs):
partial_func = partial(func, *args, **kwargs)
partial_func.continue_to = continue_to
return partial_func
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment