2 questions about scope

Andrew Dalke adalke at mindspring.com
Mon Oct 25 15:25:41 EDT 2004


Neal D. Becker wrote:
> Actually, these don't introduce a block in c++ either.  The braces do.

In C++

for (int i=0; i<100; spam(i), ++i)
    ;

the 'i' is in the for statement's scope even though there
are no braces.

To respond to the OP's question, one big difference between
C++ and Python's scoping systems is that Python doesn't have
a distinct variable declaration.  In C++ you could say

{
   char i[] = "something";
   ...
   for (int i=0; i<100; i++) {
     ...
   }
}

and the compiler knows you want a new variable 'i'.

In Python, the equivalent might be

   i = "something"
   for i in range(100):
     ...

There's nothing to tell Python that the 'i' used
in the for statement is different than the i in the
outer scope, so it assumes you meant the same variable.

The only scopes created in Python are for modules,
classes, and functions.  As I pointed out a couple
weeks ago, you could fake scope with a class statement,
as in

   i = "something"
   class scope:
     for i in range(100):
       ...

but you really shouldn't.  Or use a function scope,

   i = "something"
   def scope():
     for i in range(100):
       ...
   scope()

I mostly use the last when I want some non-trivial
initialization in my module and don't want the various
variables hanging around in the process space.  I'll
also follow it up with a "del scope" so that no one
can reference the initialization code.


				Andrew
				dalke at dalkescientific.com



More information about the Python-list mailing list