Creating a local variable scope.

Dave Angel davea at
Mon Nov 30 11:29:10 CET 2009

markolopa wrote:
> On Nov 30, 4:46 am, Dave Angel <da... at> wrote:
>> markolopa wrote:
>>> Antoher 15 minutes lost because of that Python "feature"... Is it only
>>> me???
>> Yep, I think so.
> Not very consoling but thanks anyway!...:-))))
>>  You're proposing a much more complex scoping rule,
>> where if a variable already exists before entering a loop, then the loop
>> uses that existing variable, but if not, it creates its own local one
>> and destroys it when exiting the loop.
> Alternatively you could forbid the creation of a variable in a inner
> block if it already exists. 
Somehow you seem to think there's some syntax for "creating" a 
variable.  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 a 
variable (except the global statement, which does it sort-of).  So you'd 
be disallowing the following:

    counter = 5
    for item in itemlist:
           if item > 19:
                counter = counter + 5

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.

> Either that or forbid the usage of the
> variable in an outter block later if it exists both in an inner and
> outer block.
You need to define "exists" in order to make discussion unambiguous.  
Without extra declarations of some type, I can't believe there's any way 
to make any variation of this concept work in the general case.
> Aren't there languages that forbid the declarations of variables in a
> function with the same name as global variables? I know that this is
> an extreme defensive measure, but I have to say that I like it.
> Allowing to create a new variable when a variable with the same name
> is already exists in the namespace makes for harm that good, for me at
> least. Of course this issue is much broader than the one I proposed
> initially.
I can't think of any, among the 35 languages I've programmed in 
professionally over the years.  All right, to be fair, about half of 
those were assembly languages at various levels.  And I don't believe I 
worked in any assembly language that even had separate scoping for 


More information about the Python-list mailing list