In Python, we have a keyword called nonlocal
. Is it the same as static
in C++? If we have nested functions in Python, instead of using nonlocal
inside an inner function, can't we just declare the variable in the outer function? That way it will be truly nonlocal
.
Clarification: static
keyword as used below in C++:
#include <iostream>
int foo () {
static int sVar = 5;
sVar++;
return sVar;
}
using namespace std;
int main () {
int iter = 0;
do {
cout << "Svar :" foo() << endl;
iter++;
} while (iter < 3);
}
gives output over iterations:
Svar :6
Svar :7
Svar :8
So, variable Svar
is preserving it's value.
If we have nested functions in python, instead of using nonlocal inside inner function, can't we just declare the variable in the outer function?
No. If you omit the nonlocal
the assignment in the inner function will create a new local copy, ignoring the declaration in the outer context.
def test1():
x = "Foo"
def test1_inner():
x = "Bar"
test1_inner()
return x
def test2():
x = "Foo"
def test2_inner():
nonlocal x
x = "Bar"
test2_inner()
return x
print(test1())
print(test2())
... emits:
Foo
Bar
Is it the same as static in C++?
C++ static
variables are really just global variables with a narrower scope (i.e. they are persistent global context which is stored across function invocations).
Python nonlocal
is just about nested scope resolution; there is no global persistence across invocations of the outer function (but would be across multiple invocations of the inner function from the same outer function invocation).