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. On Mon, May 2, 2016 at 5:06 PM, Eric Snow <ericsnowcurrently@gmail.com> wrote:
On Mon, May 2, 2016 at 8:35 AM, Bruce Leban <bruce@leban.us> wrote:
Using a single letter (or short) variable name works well most of the time <snip>
x = foo() with: y = x + 1 x = y + 2
Hmm. That reminds me of the "given" syntax (PEP 3150: https://www.python.org/dev/peps/pep-3150/). This is like allowing blocks of code to be treated as first-order, a la Ruby. Then again, functions give us just about all we need, and the "given" syntax basically gives us multi-line lambdas. :) Perhaps it's time to dust off that proposal.
There is a difference. "given" or whatever it's called requires the variables to be declared and initialized at the top, while this would automatically delete any references created in the block. On Mon, May 2, 2016 at 8:31 AM, Guido van Rossum <guido@python.org> wrote:
The choice of keyword is not entirely arbitrary; if we can't come up with a decent keyword the feature is dead. But the introduction would have to include a `from __future__ import <something>` statement anyway for at least one, maybe two release cycles (we did this with the `with` statement itself, around 2.4/2.5). So Django will have plenty of time to change.
Note that the "auto-deleting block" (for want of a better descriptive name) could be introduced with a contextual keyword. Currently <identifier> : is not valid syntax so any identifier could be used for these blocks without requiring it to be recognized as a keyword in other contexts. --- Bruce