Python's scope rules

Tim Peters tim.one at home.com
Sat Dec 23 02:49:55 EST 2000


[Alex Martelli]
> ...
> I think you can say 'will' rather than 'would', as I see no
> reason why PEP 227 should not make it into Python 2.1.

Me neither, but that doesn't matter.  What's important is that Guido doesn't
have strong objections.

> I do hope that Python keeps the simplicity of avoiding the
> distinction between 'let' and 'set!' (creation of a new
> binding in this scope, vs modification of existing binding
> in some nested scope), variable-declarations, or other
> complexities to allow fancy stuff such as rebinding of
> lexically-nested-scoped variables.

Guido's (*possibly* wishful) hope is that 90% of scope complaints are due to
"the lambda problem", i.e. the need to abuse the default argument mechanism
to "import" local names into a nested lambda's scope.  Since lambda syntax
allows only an expression (and not a stmt), and all binding constructs are
stmts, there's no possibility of rebinding within the body of a lambda
anyway.

So, the hope is that 90% of all scope complaints will go away, and then the
remaining 10% are 10x easier to ignore <wink>.  The reluctant possibility of
extending this someday remains open, though.

> I know of no language that allows that without constraints --
> say that your scope is currently nested 5 levels deep and
> there's a binding for 'x' in each nested scope, how do you
> specify 'the x that's bound exactly 3 levels up from this one'?

def f():
    i = 1
    def g():
        i = 2
        def h():
            global f.i
            # i now refers to the i local to f

is one backward-compatible syntax suggested in the past.  There were others.
I didn't much like any of them.  But that doesn't matter <wink>:  Guido
didn't like them either.

> Java specifically disallows homonym variables in nested
> scopes, and maybe that should be considered as a part of
> PEP 227 -- such homonimy frequently causes confusion in
> languages which allow it, I think, and apparently Java's
> designers agree.

Guido will never go for any scheme that prohibits shadowing of global or
builtin names.  Given that, it would be a wart to make local names "more
special" than those.  Java, of course, doesn't have global or builtin names
to contend with, so doesn't have this problem (although Java has a related
problem:  it allows locals to shadow field names, else you couldn't change
the fields in base classes without possibly needing to rewrite bodies of
subclasses too).

Python 2.1 should have a new warning mechanism (PEP 230), and I hope we can
warn about shadowing at compile time.

cattle-prod-vs-electric-chair-is-a-hard-choice-ly y'rs  - tim





More information about the Python-list mailing list