Created
October 25, 2013 16:03
-
-
Save pjwerneck/7157090 to your computer and use it in GitHub Desktop.
A switch/case structure using python context managers and decorators. This is just demonstrating the usage (or abuse) of context managers and should not be used in production code.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| class switch(object): | |
| def __init__(self, expr): | |
| self.expr = expr | |
| self.cases = {} | |
| self._default = None | |
| def __call__(self, expr): | |
| def inner(f): | |
| self.cases[expr] = f | |
| return f | |
| return inner | |
| def __enter__(self): | |
| return self | |
| def __exit__(self, exc_type, exc_value, traceback): | |
| return self.cases.get(self.expr, self._default)() | |
| def default(self, f): | |
| self._default = f | |
| return f | |
| x = 1 | |
| with switch(x) as case: | |
| @case(1) | |
| def f(): | |
| print 'case 1' | |
| @case(2) | |
| def f(): | |
| print 'case 2' | |
| @case.default | |
| def f(): | |
| print 'default' |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment