Skip to content

Instantly share code, notes, and snippets.

@testautomation
Created February 16, 2020 19:06
Show Gist options
  • Save testautomation/ebdec1de8c173d7443ccfebd21205b4f to your computer and use it in GitHub Desktop.
Save testautomation/ebdec1de8c173d7443ccfebd21205b4f to your computer and use it in GitHub Desktop.
How Can We Best Switch in Python?
# BLOG: https://medium.com/swlh/how-can-we-best-switch-in-python-458fb33f7835
def explain_char(character):
"""
switch using if / elif / else
"""
something = ''
if character == 'a':
something = 'first letter of alphabet'
elif character == 'l':
something = 'letter of lover'
elif character == 'z':
something = 'last letter of alphabet'
else:
something = 'some other character'
print(f'{character}: {something}')
explain_char('a')
explain_char('b')
explain_char('a')
explain_char('l')
explain_char('z')
print('\n')
# globals
characters = {
'a': 'first letter of alphabet',
'l': 'letter of love',
'z': 'last letter of alphabet'
}
def explain_char_with_dict(character):
"""
switch using a dictionary and get()
"""
something = characters.get(character, 'some other character')
print(f'{character}: {something}')
explain_char_with_dict('a')
explain_char_with_dict('b')
explain_char_with_dict('a')
explain_char_with_dict('l')
explain_char_with_dict('z')
print('\n')
def explain_char_with_dict_existence(character):
"""
switch using a dictionary with var existnce check
"""
something = ''
if character in characters:
something = characters[character]
else:
something = 'some other character'
print(f'{character}: {something}')
explain_char_with_dict_existence('a')
explain_char_with_dict_existence('b')
explain_char_with_dict_existence('a')
explain_char_with_dict_existence('l')
explain_char_with_dict_existence('z')
print('\n')
from collections import defaultdict
def explain_char_defaultdict(character):
"""
switch using `defaultdict` from `collections` module
"""
character_with_default = defaultdict(lambda: 'some other character',
characters)
print(f'{character}: {character_with_default[character]}')
explain_char_defaultdict('a')
explain_char_defaultdict('b')
explain_char_defaultdict('a')
explain_char_defaultdict('l')
explain_char_defaultdict('z')
print('\n')
@testautomation
Copy link
Author

@testautomation
Copy link
Author

output will be 4 x

a: first letter of alphabet
b: some other character
a: first letter of alphabet
l: letter of lover
z: last letter of alphabet

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment