[Tutor] scope/namespaces

Kent Johnson kent37 at tds.net
Tue Apr 24 15:18:18 CEST 2007


Ezra Taylor wrote:
> Hello Kent:
>                     How can we limit this functionality so that python 
> behaves similar to other know languages.  Maybe I should be asking what 
> are the benifits of allow variables not being bound to a block of code.

Why is this a problem? Don't try to turn Python into Java, you might as
well stay with Java.

One advantage is, you can define a variable in a conditional block or a
try block without having to declare it first. For example:
if something:
   x = 3
else:
   x = 5

or
try:
   x = foo()
finally:
   cleanup()

# do something with x

It has long annoyed my that in Java these snippets would have to be
prefixed with
int x;

Kent
> 
> Ezra
> 
> On 4/24/07, *Kent Johnson* <kent37 at tds.net <mailto:kent37 at tds.net>> wrote:
> 
>     ammar azif wrote:
>      > Something in python disturbs me ,
>      >
>      > when i write a for loop,
>      >
>      > i am able to access the variable declared in that loop after the loop
>      > finishes which i am not able to do in languages like c/c++ or
>     java. Is
>      > it different in python?
> 
>     Yes, it is different. In Python a block is not a scope. Names bound
>     within the block, including the loop variable, are accessible outside
>     the block.
> 
>     Kent
>     _______________________________________________
>     Tutor maillist  -  Tutor at python.org <mailto:Tutor at python.org>
>     http://mail.python.org/mailman/listinfo/tutor
> 
> 
> 
> 
> -- 
> Ezra Taylor




More information about the Tutor mailing list