Case Statements

Marko Rauhamaa marko at pacujo.net
Wed Mar 16 05:16:46 EDT 2016


Christian Gollwitzer <auriocus at gmx.de>:

> That happens indeed if one were to simulate polymorphism using switch
> statements, but not for other cases.

There are not many other cases. Decoding is the only generally valid
case I can think of.

> In Python, you need to go the other way round, you don't have a
> switch, but you can simulate it via function tables or polymorphism.

Let's look at one case that I routinely implement using switch
statements in C: finite state machines. The reaction of an entity to a
stimulus depends on the state of the entity. That clearly is a case of
polymorphism.

There there is the reaction to system errors. However, there usually are
not so many options to consider that one would yearn for a switch
statement:

    try:
        bytes = self.tcpconn.read()
    except socket.error as e:
        if e.errno == errno.EAGAIN:
            raise incomplete
        raise
                                                        
What other cases do you have in mind?

> The difference between a switch and its simulation via function
> pointer tables etc. is the scope. In a true switch statement, the code
> blocks access the same variables. You can't truly simulate an if
> statement in Python [...] Same with switch. You can use a hash table
> etc. to simulate switches, but only if the codeblocks are independent.

Such assignments are usually done to an object's data attributes.
Closures have "self" accessible to them so they can naturally update
"self.x" in the polymorphic methods.

> Same with switch. You can use a hash table etc. to simulate switches,
> but only if the codeblocks are independent. Otherwise, if-elif chains
> are the way to go. Command line parsing is a case where switch
> statements are often used, e.g. in shell scripts.

You have the same thing in C:

     if (!strcmp(arg, "now"))
         do_it_now();
     else if (!strcmp(arg, "soon"))
         do_it_now();
     else if  (!strcmp(arg, "later"))
         do_it_later();
     else complain();


Marko



More information about the Python-list mailing list