python global variable trouble
I am having troubles using global variables in python...
In my program, i have declared 2 global variables, global SYNC_DATA and global SYNC_TOTAL_SIZE
Now in one of my functions, I am able to use the global variable SYNC_DATA without declaring it as global again 开发者_如何学编程in the function; however , I am not able to use the other global variable SYNC_TOTAL_SIZE in the same way. I have to declare the latter as global in the function again to use it. I get this error if i use it without declaring as global in the function - "UnboundLocalError: local variable 'SYNC_TOTAL_SIZE' referenced before assignment"
Why is it so that sometimes I can access global variables without declaring them as global in functions and sometimes not? And why Is it that we have to again declare it as global in the function when it is already declared once in the beginning... Why doesn`t the function just check the variable in the global namespace if it does not find it in its namespace directly?
Assuming SYNC_TOTAL_SIZE
is not declared as local variable. It depends on what operations you are performing on global variables, for just reading the global variable there is no need to declare it as global, but if you are modifying the value of global variable you have to declare it with global
.
Because SYNC_TOTAL_SIZE
is probably used somewhere else in that code as non-global, which makes Python find it and think it isn't global. Another reason may be that you just read it in some function and so it doesn't need a global
declaration (see this question for more details). For an exact diagnosis, post a minimal code snippet that demonstrates your problem.
The advice is to always say global
when you mean it.
精彩评论