For the below, I get NameError: name 'x' is not defined
. But there is an x defined when otherFcn() is called. From this error, I learned that Python looks for a nonlocal variable from where the function is defined, not where the function is called.
def otherFcn():
print('inside of fcn ', x)
def main():
x = 12
otherFcn()
main()
But why then does this below print "inside secFcn 100"? Shouldn't it print "inside of secFcn 24" if Python looks for what x is at the point where the function is defined and not at the point where the function is called.
def main():
x = 24
def secFcn():
print('inside secFcn ', x)
x = 100
secFcn()
main()
CodePudding user response:
Shouldn't it print "inside of secFcn 24" if Python looks for what x is at the point where the function is defined and not at the point where the function is called.
It looks for the variable in the scope where the function was defined, but it does not look for the value the variable had at the time the function was defined. It looks up the current value of the variable.
At the time secFcn
tries to use x
, x
evaluates to 100
, not 24
.
CodePudding user response:
From this error, I learned that Python looks for a nonlocal variable from where the function is defined, not where the function is called.
This is not true. What you’re experiencing is a general programming concept known as “Scope.” In both examples x
is a local variable with function scope, and in both cases that function is main()
.
Your error occurs in the first example because you’re trying to access x
outside of its scope. As far as Python is concerned that variable doesn’t exist within the scope of otherFcn()
.
The second example allows secFcn()
to access x
because of where that function is defined. By defining it in main()
you’re giving it local scope within main()
and it can access the other variables with that same scope, or with “higher” scope.
If you had defined x
in global scope then it would share scope with otherFcn()
and would be accessible. Similarly it would also be accessible by secFcn()
because the scope of x
would be “higher” in the hierarchy than the scope of secFcn()
.
Implementation details will differ from language to language, and I’m sure someone else on here has a clearer or more technically savvy way of explaining it, but as far as I understand it that’s how it works in Python and there’s also quite a bit more to it, so I recommend googling “variable scope in Python” or similar.
Hope that helps,
—K