Skip to content

Instantly share code, notes, and snippets.

@iahuang
Created January 14, 2020 04:05
Show Gist options
  • Save iahuang/805269c3a8fda9d692eb5c3fb2602856 to your computer and use it in GitHub Desktop.
Save iahuang/805269c3a8fda9d692eb5c3fb2602856 to your computer and use it in GitHub Desktop.
Very hacky implementation of switch/case syntax for Python
import types
def switch(x, *args):
for c in args:
if type(c.val) == types.LambdaType:
c.val()
if c.should_break:
return
elif c.matches(x):
return c.val
for c in args:
if c.bottom == case_DEFAULT:
return c.val
class case_DEFAULT:
pass
class case:
def __init__(self, bottom, top=None):
self.bottom = bottom
self.top = top
self.should_break = False
def matches(self, x):
if self.top == None:
return x == self.bottom
return x >= self.bottom and x <= self.top
def __call__(self, val):
self.val = val
return self
def brk(self):
self.should_break = True
return self
def default(val):
return case(case_DEFAULT)(val)
grade = switch(101,
case(0, 60)(lambda: print('ur bad at school lmaoooo')).brk(),
case(60, 69)('D'),
case(70, 79)('C'),
case(80, 89)('B'),
case(90, 100)('A'),
default('lmao')
)
print(grade)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment