The Wayback Machine - https://web.archive.org/web/20150120120833/http://codingstyleguide.com/style/180/python-pythonic-way-to-implement-switchcase-statements
Add Guideline
Programming Languages
  • C x 9
  • C# x 24
  • C++ x 19
  • CoffeeScript x 4
  • CSS x 4
  • Erlang x 6
  • Go x 4
  • Haskell x 3
  • HTML x 7
  • Java x 20
  • JavaScript x 34
  • Lisp x 4
  • MATLAB x 4
  • Objective-C x 18
  • OCaml x 2
  • Perl x 4
  • PHP x 19
  • PL/SQL x 1
  • Python x 21
  • QML x 1
  • Ruby x 21
  • Rust x 1
  • Scala x 2
  • Swift x 3
  • Pythonic way to implement switch/case statements

    2
    Python posted by zio_tom78 (26) on Apr 1 '14, 21:02

    Programmers familiar with languages like C/C++/Pascal often find puzzling the lack of a switch/case statement in Python, like the following one (C):

    switch(x) {
    case 1: y = 'a'; break;
    case 2: do_something(); break;
    default: panic();
    }
    

    The most straightforward way to do this in Python would be to use a sequence of nested if:

    if x == 1:
        y = 'a'
    elif x == 2:
        do_something()
    else:
        panic()
    

    A better way to do this in Python is to use a dictionary. Here is an example:

    city = raw_input("Enter the city you want to visit: ")
    known_cities = {"Paris": "France",
                    "Rome": "Italy",
                    "Madrid": "Spain"}
    try:
        print "The city you chose is in ", known_cities[city]
    except KeyError:
        print "I've never heard of ", city
    

    If the actions you must perform are quite different depending on the value of x, then the value associated with each key can be a function:

    def connect_to_db():
        print "I am going to connect to the DB"
    
    def disconnect_from_db():
        print "I am going to disconnect myself from the DB"
    
    available_actions = {"connect": connect_to_db,
                         "disconnect": disconnect_from_db}
    action = raw_input("What should I do now? ")
    try:
        available_actions[action]()
    except KeyError:
        print "Unrecognized command ", action
    

    A clever way to avoid the explicit catch to KeyError is to query the dictionary using get and passing a null function as the default argument:

    available_actions.get(action, lambda: None)()
    

    This replaces the tryexcept construct in the previous example.

    9 months, 3 weeks ago zio_tom78 (26)

    Refactoring: the dictionay variable should be inlined

    9 months, 3 weeks lenzai

    Why use get and a dummy function as default value? This will just hide bugs in case you provide unsupported values. Might be useful in rare occasions but most of the time you want to be informed if you provide an invalid value.

    9 months, 3 weeks Hub1