Creating a local variable scope.

markolopa marko.loparic at gmail.com
Tue Dec 1 17:16:59 EST 2009


Hi Dave,

Since you feel like discussing my weird idea of Python reform :-) lets
go...

On 30 Nov, 11:29, Dave Angel <da... at ieee.org> wrote:
> Somehow you seem to think there's some syntax for "creating" avariable.  In fact, what's happening is you're binding/rebinding a name
> to an object.  And if you forbid doing this inside the loop, for names
> that exist outside the loop, then most of the useful work the loop does
> becomes impossible.  Remember, in Python, there's no declaration of avariable(except the global statement, which does it sort-of).

You are right, I have not used precise terms. Let's use examples then.

> So you'd
> be disallowing the following:
>
>     counter = 5
>     for item in itemlist:
>            if item > 19:
>                 counter = counter + 5

In this example, I would allow the expected behaviour. Since "counter"
was bound in the outer loop, the new binding got in the inner loop
would persist after the end of the "if" and the "for" block.

Other examples:

if True:
   a = 5
print a

would produce an error while

a = 3
if True:
    a = 5
print a

would print 5 (and not 3).

But now I realise that one of my bugs wouldn't be solved, so I believe
you have managed to convince me that my idea does not make much
sense...:-)

> The only way I can think you possibly want this is if you're just
> referring to "loop variables", such as "item" in the above example.  The
> problem is that on many loops, for example a "while" loop, there's no
> such thing.

This would already be great. I believe that most bugs I've had related
to this issue are due to accidental reuse of loop variables. But
treating the loop variables as a special case is perhaps not very
elegant.

Greetings,
Marko



More information about the Python-list mailing list