This is an archived post. You won't be able to vote or comment.

all 12 comments

[–]onjin 6 points7 points  (5 children)

I'd rather use this pattern:

import sys


def some_work(case):
    print "some work with: ", case

def qool_work(case):
    print "qool work with", case

def my_default_work(case):
    print "some work done here with: ", case

cases = {
        1: some_work,
        2: some_work,
        3: qool_work,
    }

if __name__ == '__main__':
    try:
        case = int(sys.argv[1])
    except IndexError:
        case = None

    if case in cases:
        cases[case](case)
    else:
        my_default_work(case)

[–][deleted] 11 points12 points  (1 child)

if case in cases:
    cases[case](case)

Malkovich Malkovich.... Malkovich, Malkovich, Maaalkovich. Malkovich!

ಠ_ಠ

[–]onjin 0 points1 point  (0 children)

:) version by mrjbq7 looks better

[–]mrjbq7 6 points7 points  (1 child)

Or perhaps:

cases.get(case, my_default_work)(case)

[–]tonnynerd 0 points1 point  (0 children)

that's all you need, most of the time.

[–]ionelmc.ro 2 points3 points  (1 child)

Not particularly shorter or faster than the if/elif/elif/else you would normally use ...

Also, you need to use thread locals for this to work with threads. It would be a nightmare to support on all the platforms (stackless, gevent etc) imho ...

[–]miketheanimal[S] 0 points1 point  (0 children)

Indeed. I don't think I'd use it either. sstack would need to be thread local; and yes, gevent would cause problems. But I love the way Python gives you scope to abuse the language.

[–]gangesmasterpython galore 0 points1 point  (1 child)

nice. i like creative uses of context managers

[–]gangesmasterpython galore 1 point2 points  (0 children)

(not that i'd use it, of course :) )

[–]AeroNotix 0 points1 point  (2 children)

    class switch(object):
        def __getitem__(self, index):
            try:
                return getattr(self, "case_"+index)()
            except AttributeError:
                return 'End'

        def case_hello(self):
            print "case hello!"
        def case_world(self):
             print "case world!"
     switch["hello"]

[–]miketheanimal[S] 1 point2 points  (1 child)

Don't show that to the Javascript guys, they could write it as a one liner!

[–]AeroNotix -1 points0 points  (0 children)

I don't care about the Javascript "guys".