[Python-Dev] switch in Python.

Thomas Wouters thomas@xs4all.net
Tue, 13 Nov 2001 01:14:18 +0100


I uploaded a proof-of-concept of the switch statement to SourceForge:

https://sourceforge.net/tracker/index.php?func=detail&aid=481118&group_id=5470&atid=305470

It's a diff against the current CVS tree, taken from 'src/' -- so apply in
src/ with -p0. 

It's a quick and almost certainly buggy hack. It bypasses the c_consts_dict
in an ugly way, and might break code that tries to do stuff with code
objects. It probably doesn't keep track of the stack properly, and skips
SET_LINENO opcodes. It only allows string or numerical literals, though it
does get the '1000 == 1000.0 == 1000L' trick for free. It doesn't contain
changes to docs or dis.py, and it doesn't use a future statement. It _does_
contain a change to distutils, because it uses a variable 'switch' :-) And I
haven't profiled it in any way. In my defense, I don't recall writing it, so
I was probably sleeping at the time (or at least I should have been.)

Anyway, here's how it works:

"""
def whatis(x):
    switch x:
        case "number one":
            return "The Larch."
        case "spam", "Spam", "SPAM":
            return "It's " + "SPAM "*31
        case 1.1:
            return "one dot one"
        case 1000L:
            return "a lot."
        case 1j:
            return "Not *really* there."
    else:
        return "D'oh, donno that!"

for val in (1j, "number one", 1.1, 1000, 1000L, 1000.0, 1000.0005,
        "SPAM", "spam", "spaM", "eggs and ham"):
    print "What is", repr(val), "?"
    print whatis(val)
    print
"""


thomas@stalker:~/python-cvs/dist/src$ ./python example.py

What is 1j ?
Not *really* there.

What is 'number one' ?
The Larch.

What is 1.1000000000000001 ?
one dot one

What is 1000 ?
a lot.

What is 1000L ?
a lot.

What is 1000.0 ?
a lot.

What is 1000.0005 ?
D'oh, donno that!

What is 'SPAM' ?
It's SPAM SPAM SPAM SPAM SPAM SPAM SPAM SPAM SPAM SPAM SPAM SPAM SPAM SPAM
SPAM SPAM SPAM SPAM SPAM SPAM SPAM SPAM SPAM SPAM SPAM SPAM SPAM SPAM SPAM
SPAM SPAM 
What is 'spam' ?
It's SPAM SPAM SPAM SPAM SPAM SPAM SPAM SPAM SPAM SPAM SPAM SPAM SPAM SPAM
SPAM SPAM SPAM SPAM SPAM SPAM SPAM SPAM SPAM SPAM SPAM SPAM SPAM SPAM SPAM
SPAM SPAM 
What is 'spaM' ?
D'oh, donno that!

What is 'eggs and ham' ?
D'oh, donno that!


-- 
Thomas Wouters <thomas@xs4all.net>

Hi! I'm a .signature virus! copy me into your .signature file to help me spread!