The missing Python switch statement.
Which I disagreed. Indeed, in order to code like having same effect it might need extra work or duplicated code, just to have similar result as produced by Switch, an example from README:
def fall_through_by_default(val): values = [] with Switch(val, fall_through=True) as case: if case(1): values.append('Found 1') if case(2): values.append('Found 2') if case(3, fall_through=False): values.append('Found 3') if case(4): values.append('Found 4') if case.default: values.append('No love for 1, 2, 3 or 4?') return values assert fall_through_by_default(1) == ['Found 1', 'Found 2', 'Found 3'] assert fall_through_by_default(2) == ['Found 2', 'Found 3'] assert fall_through_by_default(3) == ['Found 3'] assert fall_through_by_default(4) == ['Found 4'] assert fall_through_by_default('anything else') == ['No love for 1, 2, 3 or 4?']
As I staring at this Switch context manager, I really can’t see a very good reason for me to use it except it vaguely resembles of C switch from the look of it if you stand up and walk away for ten feet, then look back at your monitor.
The syntax of Python makes it not so eye pleasing, unless you use switch for reasonable amount, then it’d be good reason to add it to the dependency, or just code in old way.
Here is a parting example, showing that you could make calls to test cases:
with Switch(val) as case: if case(1): values.append('Found 1') if case.call(lambda v: v < 100): values.append('Found <100') if case.default: values.append('No love for anything lower than 100?')
switch is written by Dariusz Górecki under the Simplified BSD License (2-clause) for Python 2 and 3, currently version 1.0.3 (2014-03-31).
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.