Q: Python 2.0 preliminary features?

Neel Krishnaswami neelk at brick.cswv.com
Sat Oct 9 18:35:29 EDT 1999


On Sat, 09 Oct 1999 07:00:27 GMT, Alexander Williams 
<thantos at brimstone.mecha> wrote:
>
>Note that you can do away with the 'global' statement altogether in
>Python-With-Lexical-Scope/Closure since you can create an empty object
>named 'Global' in the top-level scope which will then be accessible in
>all others (as long as you're smart enough to not shadow it).

Actually, you can't. You still need a keyword of some kind to 
explain what is and isn't shadowed.

The problem is that in Python variables are both created with and
modified by an assignment statement. This means that it's not 
possible to unambiguously tell from the syntax whether you want
to create a new variable in the current scope or modify a variable
in an enclosing scope. IOW, what should the following code do?

def puzzle(s):
    def inner():
        s = "Nee"
    inner()
    return s

What should puzzle("Shrubbery") return? "Shrubbery" or "Nee"? Right now
the ``s = "Nee"'' statement creates a new variable binding as well as 
performs an assignment, so puzzle("Shrubbery") returns "Shrubbery". 

Scheme and Dylan avoid this problem by separating declaration and
assignment into the let and set! (:= for Dylan) forms. Thus the
spelling of the two versions is unambiguous:

(define (puzzle-1 s)
  (let ((inner (lambda ()
                 (let ((s "Nee")) ()))))
    (inner)
    s))

(define (puzzle-2 s)
  (let ((inner (lambda ()
                 (set! s "Nee"))))
    (inner)
    s))

If we wanted to keep the current overloading of "=", Python would need
a "nonlocal" keyword to disambiguate. (This is kind of the backwards
of the Scheme solution.) So the Python tranlation of puzzle-2 would
be this:

def puzzle_2(s):
    def inner():
        nonlocal s    # We want use the s from an enclosing scope
        s = "Nee"
        return s
    inner()
    return s

IMO it's not quite as elegant as the Scheme version, but the difference
is small enough to be a matter of taste.


Neel




More information about the Python-list mailing list