[Python-Dev] statically nested scopes

Tim Peters tim_one@email.msn.com
Thu, 2 Nov 2000 02:02:04 -0500

[Jeremy Hylton]
> ...
>     Guido once explained that his original reservation about nested
>     scopes was a reaction to their overuse in Pascal.  In large Pascal
>     programs he was familiar with, block structure was overused as an
>     organizing principle for the program, leading to hard-to-read
>     code.

Note that this problem will be much worse in Python:  in Pascal, you could
always "look up" for the closest-containing func/proc that explicitly
declares a referenced vrbl.  In Python, you have to indirectly *deduce*
which vrbls are local to a def, by searching the entire body for an
appearance as a binding target.  So you have to "look up" and "look down"
from the reference point, and it's easy to miss a binding target.

    i = 6
    def f(x):
        def g():
            print i
        # ...
        # skip to the next page
        # ...
        for i in x:  # ah, i *is* local to f, so this is what g sees

>    def bank_account(initial_balance):
>        balance = [initial_balance]
>        def deposit(amount):
>            balance[0] = balance[0] + amount
>        def withdraw(amount):
>            balance[0] = balance[0] - amount
>        return deposit, withdraw

Unfortunately for proponents, this is exactly the kind of SICP example that
is much better done via a class.  Not only is the closure version strained
by comparison, but as is usual it manages to create a bank account with a
write-only balance <0.9 wink>.

    def deposit(amount):
        global bank_account.balance
        balance += amount

is one old suggested way to explicitly declare non-local names and the
enclosing block to which they are local (and in analogy with current
"global", mandatory if you want to rebind the non-local name, optional if
you only want to reference it).  There are subtleties here, but explicit is
better than implicit, and the subtleties are only subtler if you refuse
(like Scheme) to make the intent explicit.

for-real-fun-think-about-"exec"-abuses-ly y'rs  - tim