Creating a local variable scope.

markolopa marko.loparic at
Mon Nov 30 10:13:35 CET 2009

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. Either that or forbid the usage of the
variable in an outter block later if it exists both in an inner and
outer block.

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

> I think if you had your wish, you'd find that you had more exceptions
> where you had to pre-declare things, than the times when you avoided the
> bugs you describe.  

You are probably right, otherwise Guido would have done what I
suggest... but I really don't see why.

> I don't like languages that make me write extra
> stuff 100 times, to save one instance of extra debugging.  If Python
> already required declarations, then I might buy your arguments.  But it
> wouldn't be Python.

My guess is that if the change I propose was implemented, the number
additional lines that would be needed to make the present python code
work would be 1 in a thousand or less. Of course I may be wrong...
Besides this additional line can make the code more readable,
strassing the fact that the variable inside the block actually
"belongs" to outside.

> In your particular case, the compiler couldn't guess whether you used
> the first loop to decide which domain to use in the second loop,

That is what I wish the compiler should forbid...:->

> or
> whether you accidentally reused the same name without giving it a new
> value in the new loop.  

That is what I do regularly...8->

> If you need to use the same name, you could
> always follow your loops with the del statement to invalidate the name.

Several people have suggested explicit destruction of the variables I
don't need. Python allows it but of course this does not solve my
problem. It does not make sense to use such a clean language as Python
and regularly delete all variables used inside the blocks when leaving
it. And of course the bug comes because I have no idea that I am using
the same name again.


More information about the Python-list mailing list