""" Pythonic switch/case implementation Switch/case is faster than condition list because it is converted into a hash table look up when compiled to machine code. Python already offers easy and fast and flexible access to hash table usage that you can use. Mind, however, principles of simplicity and readability so use this way of implementation only in case of high number of choices. """ __author__ = "Bárdos Dávid" unknown = "X" # Step by step implementation cases = {"A": "a", # adding values "B": "b", "X": "x"} def switch(expression): """lightning fast switch=>case implementation""" return cases[expression] # usage result = switch(unknown) print(result) # ------------------------------------------------------------------------------------- # The same in only 2 lines. Note that it is shorter than it would un switch/case syntax cases_a = {"A": "aa", "B": "bb", "X": "xx"} print(cases_a[unknown]) # ------------------------------------------------------------------------------------- # The same in only 2 lines with X as default value that is returned when no cases fits cases_b = {"A": "aaa", "B": "bbb"} print(cases_b.get(unknown, "xxx")) # ------------------------------------------------------------------------------------- # The same with function calls, with default value def a(): print("aaaa") def b(): print("bbbb") def x(): print("xxxx") cases_c = {"A": a, "B": b} cases_c.get(unknown, x)() # ------------------------------------------------------------------------------------- # Function calls without default value cases_c = {"A": a, "B": b, "X": x} cases_c[unknown]()
Run
Reset
Share
Import
Link
Embed
Language▼
English
中文
Python Fiddle
Python Cloud IDE
Follow @python_fiddle
Browser Version Not Supported
Due to Python Fiddle's reliance on advanced JavaScript techniques, older browsers might have problems running it correctly. Please download the latest version of your favourite browser.
Chrome 10+
Firefox 4+
Safari 5+
IE 10+
Let me try anyway!
url:
Go
Python Snippet
Stackoverflow Question