The execution order in Python methods

I tried looking at a few different examples, but I'm not quite sure why this is not working. Let's say I have a code like this:

def loadVariable(): global count count = 0 def loadDictionary(): location = 'some location' global myDict myDict = pickle.load(open(location, 'rb')) def main(): loadVariable() loadDictionary() for item in myDict: if item.startswith("rt"): count += 1 item = item[3:] if __name__ == '__main__': main() 

In my eyes, the if statement is executed, which runs the main () method. Then the variable that is global is loaded, the dictionary is loaded and the for loop is executed.

However, when I run the code, they tell me that before the assignment, the value of the local variable is referenced. Why is this happening?

Edit (An explanation of some of the things I wrote in the comments):

This does not work (although I think that since global is used incorrectly here):

 global count def loadVariables() count = 0 def main(): loadVariables() rest of code etc 

This also does not work:

 def loadVariables() count = 0 def main(): global count loadVariables() rest of code etc 

The only way I got to this is to use the link above, which should treat the account as a list:

 def loadVariables(): global count count = [0] def main(): loadVariables(): rest of code etc count[0] += 1 
+4
source share
3 answers

global means that inside the function containing the global declaration, the name in the global declaration refers to a global variable. This does not mean that "this thing is a global variable, treat it like a global everywhere." In main names count and myDict refer to local variables because main does not declare that it wants to use global variables.

+4
source

The problem is that you are not declaring count as a global variable in the main function, so when the compiler sees what you (ultimately) assign to it, it assumes that it is a local variable. Since this value is read before it is assigned, you get an exception.

So, the most basic fix is ​​to simply add global count at the beginning of main() , but I think avoiding globals would be a better option. Why not return the loadVariable and loadDictionary their results, and not assign them global? If in main() you did count = loadVariable() , count will be a local variable, and you won't have a problem later trying to reassign it.

+2
source

Here is a simple example of how global works

 global_var = 0 def updater(): global global_var global_var += 1 def stuff(x): updater() return global_var + x if __name__ == '__main__': stuff(2) # returns 3 
0
source

Source: https://habr.com/ru/post/1497628/


All Articles