On Mon, May 2, 2016 at 8:21 AM, Random832
<random832@fastmail.com> wrote:
On Mon, May 2, 2016, at 10:35, Bruce Leban wrote:
> Using a single letter (or short) variable name works well most of the
> time
> but has one problem: the variable can leak. It's easy to forget to write
> the del statement. Imagine a block statement that had the effect of
> deleting any variables initialized in the block.
<snip>
Should it delete the variables, or should it be a new scope? They're
subtly different.
If the former, how do you differentiate a variable initialized in the
block from a variable assigned in the block? What if you really *do*
want to keep one of them? (The answer in both cases if it's a new scope
would be to use "nonlocal")
Fair question. It's not a new scope because it's too clumsy to have to declare every variable outside the block nonlocal. If a variable X is not local to the enclosing scope (or declared global), then it's local to the block. I don't think you can do this at runtime; I think it has to be determined at compile time. Consider:
def foo(i):
if i:
x = 1
with:
x = 2
y = 3
This should not del x regardless of the value of i. In the following case the variable in the block affects the outer scope. Consider:
def foo(i):
with:
y = 3
return y
Treating this as
def foo(i):
y = 3
del y
return y
has the right result (unbound error). Without the block return y would be a reference to a global variable.