OT: Re: Just took a look in the perl newsgroup....

Michael Chermside mcherm at mcherm.com
Tue May 20 08:57:57 EDT 2003


  [... discussion of "case statements" in python...]
Michael Chermside writes:
>    # One simple approach
>    if x = 1:
>        do_something_1()
>    elif x = 2:
>        do_something_2()
>    elif x = 3:
>        do_something_3()
>
>
>    # Another (very powerful) approach
>    do_something = my_func_dict[x]
>    do_something()

Bengt Richter replies:
> Unfortunately the choice in rebinding inside of the do_something_x's
> is either local or global, which typically leaves the scope of the
> above sandwiched in the middle and unmodifiable by reasonable means.

I don't understand what you mean.

Clearly using the first option (the if-elif-else statement) has just
as much access to variables as a hypothetical case statement would
have (they're both statements). So I guess (correct me if I'm wrong)
you're griping only about the approach where one uses a dict of
functions.

But nested scopes come to our rescue here. For instance:

global_var = 3
def f(x):
    outer_var = 4
    def g(x):
        inner_var = 5
        sum_vars = {
            1: lambda: global_var + outer_var + inner_var + 6,
            2: lambda: global_var + outer_var + inner_var + 7,
        }[x]
        print sum_vars()
    g(x)
    
f(1) # prints "18" (== 3+4+5+6)

Of course, the use of lambda here limits me to expressions
only (no statements). Often, that's enough, but if it weren't,
then the following would serve:

global_var = 3
def f(x):
    outer_var = 4
    def g(x):
        inner_var = 5
        def case_1():
            print "option 1: ", global_var, outer_var, inner_var
        def case_2():
            print "option 2: ", global_var, outer_var, inner_var
        { 1: case_1, 2: case_2 }[x]()
    g(x)
    
f(1) # prints "option 1: 3 4 5"


And if you find this awkward... well, that's what the if-elif-else
is for!

So what is this limitation you spoke of?

-- Michael Chermside






More information about the Python-list mailing list