I have a question about local and global variables and global objects in Python. Look at this code:
var = 0
class Test():
var = 0
test = Test()
def sum():
Test.var += 1
test.var += 1
var += 1
sum()
If I run that code, the exception is triggered in the line “var += 1” only. The two previous lines work. I read this question from the Python FAQ. I think that there is no exception in the first two lines of the function because the “Test” and “test” are referenced. The member “var” is assigned, but “Test” and “test” are global because are referenced to get the member. The FAQ said: “In Python, variables that are only referenced inside a function are implicitly global. If a variable is assigned a new value anywhere within the function’s body, it’s assumed to be a local.”
So, the question is… is my assumption true?
Correct. And they refer to the class attribute
var, not the global one you defined.Or to put it another way,
Testandtestare available in the global namespace soTest.varandtest.varwork.If the value of
varwas not changed insum(), you would get 0 since the lines above it have changed theTestclass attribute not the global. Adding someprints in sum and removing thevar += 1…gives:
But the moment I try to assign a value to var within the sum function, I get an error even before that line:
Because
varis now being assigned a value in sum(), it’s considered local but has not been defined prior to that line. (Which implies that python is doing some ‘looking ahead’ or checkingvariable scopein sum() since it raised the error for the firstprint varbeforevarwas re-assinged. Puttingvar = 50instead ofvar += 1raises the same error.)To work with the global var:
output:
Edit: Regarding the ‘look ahead’ behaviour I mentioned. Was going to post a question about it but it’s been explained well in this answer: https://stackoverflow.com/a/370380/1431750 (to Python variable scope error)