Logo

Programming-Idioms

This language bar is your friend. Select your favorite languages!
  • Python

Idiom #206 Switch statement with strings

Execute different procedures foo, bar, baz and barfl if the string str contains the name of the respective procedure. Do it in a way natural to the language.

match str:
    case 'foo': foo()
    case 'bar': bar()
    case 'baz': baz()
    case 'barfl': barfl()

Python 3
switch = {'foo': foo, 
	'bar': bar, 
	'baz': baz, 
	'barfl': barfl
	}

switch_funct = switch.get(string)
if switch_funct : switch_funct()

Python does not natively support switch statements, but we can use a dictionary to replicate one.

The get() method will return the value of the given key if it exists and None otherwise where foo, bar, baz, and barf1 are all declared functions.

We then can check if the get method returned a value, and if it did, execute the returned function.
(def whitelist #{#'foo #'bar #'baz #'barfl})
(some-> str symbol resolve whitelist (.call))

str can contain fully qualified function name, like "clojure.string/upper-case".

set #{} is a function of an item: returns it back, if contains it, or nil otherwise.

#' is a literal for var.

some-> takes care of nil checks after each step.

This will throw, if whitelisted var contains not callable (e.g. number) or expects arguments.

New implementation...
< >
tkoenig