Re: 2 questions about scope
From: Andrew Dalke (adalke_at_mindspring.com)
Date: 10/25/04
- Next message: Peter Otten: "Re: fastest table lookup"
- Previous message: Alex Martelli: "Re: Python vs PHP"
- In reply to: Neal D. Becker: "Re: 2 questions about scope"
- Next in thread: Alex Martelli: "Re: 2 questions about scope"
- Reply: Alex Martelli: "Re: 2 questions about scope"
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
Date: Mon, 25 Oct 2004 19:25:41 GMT
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@dalkescientific.com
- Next message: Peter Otten: "Re: fastest table lookup"
- Previous message: Alex Martelli: "Re: Python vs PHP"
- In reply to: Neal D. Becker: "Re: 2 questions about scope"
- Next in thread: Alex Martelli: "Re: 2 questions about scope"
- Reply: Alex Martelli: "Re: 2 questions about scope"
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
Relevant Pages
|
|