[Python-3000] Sky pie: a "var" keyword

Jim Jewett jimjjewett at gmail.com
Mon Oct 9 15:46:51 CEST 2006


"Neil Toronto" <ntoronto at cs.byu.edu> wrote:

> It occurs to me that some of Python's gotchas are due to the compiler
> not being able to determine whether the user intends to *create* a
> variable, or *modify* one.

Yes, but there may not be any solution.  One of python's greatest
strengths is the lack of boilerplate.  I doubt there is any way to
indicate this intent without an explicit notation that either looks
magic or becomes boilerplate.

> The "global" gotcha:

> x = 0
> def f():
>    print x   # 'local variable 'x' referenced before assignment'
>    x = 3

Because it is ambiguous.  The print indicates that you want (read)
access to an existing variable, but the assignment indicates that you
want (write) access to that variable.  Did you mean

    x = 0
    def f():
        global x  # modify the existing variable
        print x
        x = 3
or
    x = 0
    def f():
        x = x  # shadow the existing variable
        print x
        x = 3


> A "var" keyword fixes them all. The "global" gotcha:

> x = 0
> def f():
>    print x   # no exception - prints "0"
>    x = 3

But which of the above would this mean?

Below, it sounds like you're adding an implicit global.  In Lisp, this
is somewhat controlled by first declaring the variable special (at the
top level) and then using a conventionally strange name on top of it.
If you could create top-level variables easily (as it looks like from
the x=0 line), people would get nasty suprises about what turned out
to be top-level -- and what changed from local to toplevel after later
code ran.

> The read-only lexical scoping gotcha:

> def f():
>    var x = 0
>    def g():
>        x = 3   # alters outer 'x'

For people coming from another language, "var" isn't likely to mean
"by the way, this gets modified elsewhere".  The existing idiom of

    def f():
        x = [0]
        def g():
            x[0] = 3

is at least strange enough to warn people that they need to read carefully.

-jJ


More information about the Python-3000 mailing list