Trying to understand how scope works in Python. It seems to work a bit differently than in other languages like C++ and Java. When I run the code below
def foo():
y = 5
x = 2
foo()
print(x+y)it returns a name not defined error. That's expected since the scope of y disappeared before it could be used. However, when I run the following code
x = 2
if True:
y = 3
print(x+y)It works just fine. The program identifies y even though it is in another scope. When trying out the same thing in other languages like C++
int x = 2;
if (true)
{
y = 2;
}
cout<<x + y<<endl;it gives a not declared in this scope error. That's what I expected in Python but clearly that's not the case. Python somehow keeps track of variables inside the scope of an if statement or loop even after it exits and the variables were not declared outside of it. Can anyone explain how scope in Python differs from scope in C++ or Java? How does Python treat scope differently?
Python variables are scoped to the innermost function, class, or module in which they're assigned. Control blocks like if and while blocks don't count, so a variable assigned inside an if is still scoped to a function, class, or module.
(Implicit functions defined by a generator expression or list/set/dict comprehension do count, as do lambda expressions. You can't stuff an assignment statement into any of those, but lambda parameters and for clause targets are implicit assignment.)
Yes, they're in the same "local scope", and actually code like this is common in Python:
if condition:
x = 'something'
else:
x = 'something else'
use(x)
Note that x isn't declared or initialized before the condition, like it would be in C or Java, for example.
In other words, Python does not have block-level scopes. Be careful, though, with examples such as
if False:
x = 3
print(x)
which would clearly raise a NameError exception.