I have read Replacements for switch statement in Python? and none of the answers seem to fully emulate a switch.

I know you can use if elif else or a dictionary but I'm wondering... is it possible in Python to fully emulate a switch including fall-through and default (without defining an enormous function before-hand)?

I am not overly concerned with performance and am mainly interested in readability and want to get the logical layout of a switch statement as in C-like languages in Python

Is this achievable or not?

有帮助吗?

解决方案

As you don't want to use a dictionary or if elif else, the closest possible emulation, AFAIK, would be something like this:

class switch(object):
    def __init__(self, value):
        self.value = value
        self.fall = False

    def __iter__(self):
        """Return the match method once, then stop"""
        yield self.match
        raise StopIteration

    def match(self, *args):
        """Indicate whether or not to enter a case suite"""
        if self.fall or not args:
            return True
        elif self.value in args: # changed for v1.5, see below
            self.fall = True
            return True
        else:
            return False

import string
c = 'A'
for case in switch(c):
    if case(*string.lowercase): # note the * for unpacking as arguments
        print "c is lowercase!"
        break
    if case(*string.uppercase):
        print "c is uppercase!"
        break
    if case('!', '?', '.'): # normal argument passing style also applies
        print "c is a sentence terminator!"
        break
    if case(): # default
        print "I dunno what c was!"

@Author Brian Beck

@source: http://code.activestate.com/recipes/410692/ <- there are other suggestions there, you might want to check to see if any is good enough for you.

Note that you will have to use (or import this class switch)

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top