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

Bengt Richter bokr at oz.net
Wed May 28 14:49:29 EDT 2003


On 28 May 2003 09:11:25 -0400, aahz at pythoncraft.com (Aahz) wrote:

>In article <mailman.1054126363.18886.python-list at python.org>,
>Michael Chermside  <mcherm at mcherm.com> wrote:
>>
>>Thanks, I think I get it now. What you're saying is that if you
>>use a dict of functions as a stand-in for a case statement, then
>>the functions can modify GLOBAL variables, and (of course) variables
>>local to the functions themselves, but they can't modify nested-scope
>>variables. So it's as if you can write a case statement, but
>>within the cases you can't SET any variables (except global
>>variables or variables that exist only within the case itself).
>>
>>That's a big limitation. I guess I should probably fall back on
>>just promoting if-elif-else as the solution for "case" in Python.
>
>It's less of a limitation in Python.  The problem is that you're limiting
>yourself by thinking of "variables".  Use a mutable object passed in to
>the functions (or even a global object), and Tim's your uncle.  This is
>one of the key reasons I push for using name/binding instead of
>variable/reference -- it keeps attention focused on Pythonic idioms.

IMO that's still a workaround for the case (;-) where you want to rebind
in the same scope. But I just thought of an alternative, which see below
in stripped-down version of previous example:

====< xcase.py >========================================================
def f(x):
    def g(x):
        inner_var = 5      
        ## a local case structure with rebinding in local scope
        try: raise `x`
        except '1':
            # case code in same scope as case
            inner_var = '<<value bound in scope of "case" 1)>>'
        except '2':
            inner_var = '<<value bound in scope of "case" 2>>'
        except:
            inner_var = '<<value bound in scope of "case" default>>'
        print 'inner_var as seen at end of "case":', inner_var
    g(x)

for i in range(3): print '---- f(%s) -----'%i; f(i)
========================================================================
[11:47] C:\pywk\clp>xcase.py
---- f(0) -----
inner_var as seen at end of "case": <<value bound in scope of "case" default>>
---- f(1) -----
inner_var as seen at end of "case": <<value bound in scope of "case" 1)>>
---- f(2) -----
inner_var as seen at end of "case": <<value bound in scope of "case" 2>>

Regards,
Bengt Richter




More information about the Python-list mailing list