Tutorial by Examples

Well, if you want a switch/case construct, the most straightforward way to go is to use the good old if/else construct: def switch(value): if value == 1: return "one" if value == 2: return "two" if value == 42: return "the answer to...
Another straightforward way to go is to create a dictionary of functions: switch = { 1: lambda: 'one', 2: lambda: 'two', 42: lambda: 'the answer of life the universe and everything', } then you add a default function: def default_case(): raise Exception('No case found!') ...
You can use a class to mimic the switch/case structure. The following is using introspection of a class (using the getattr() function that resolves a string into a bound method on an instance) to resolve the "case" part. Then that introspecting method is aliased to the __call__ method to ...
Another way, which is very readable and elegant, but far less efficient than a if/else structure, is to build a class such as follows, that will read and store the value to compare with, expose itself within the context as a callable that will return true if it matches the stored value: class Switc...

Page 1 of 1