Mixing global variables in python

I have global variables that I use as the default variable. Depending on what happens in my program, I need to change these default values ​​and save the changes to the remaining operation of my code. I want them to change and be defined everywhere, so I used a global variable. Here are some test codes that show how I am trying to change these variables.

When I do this, I have the following problems ...

  • The program considers that myGlobal not defined in the main. But there is one in it. What for?
  • When I call a subroutine after I change myGlobal . I did not want this to happen.

What is the correct way to accomplish what I'm trying to do here? Examples?

 #!/usr/bin/python import sys myGlobal = "foo" print "********************" print "MyGlobal %s" % myGlobal print "********************" def main(argv): #UnboundLocalError: local variable 'myGlobal' referenced before assignment print '1. Printing the global again: ' + myGlobal myGlobal = "bar" print "2. Change the global and print again: " + myGlobal # now call a subroutine mySub() # Checks for output file, if it doesn't exist creates one def mySub(): # Why isn't the global "bar" not "foo"? print '3. Printing the global again: ' + myGlobal myGlobal = "black sheep" print "4. Change the global and print again: " + myGlobal if __name__ == "__main__": main(sys.argv[1:]) 
+6
source share
2 answers

If you want to assign, rather than read, a global variable from a function, you will need the global :

 def main(argv): global myGlobal #... myGlobal = "bar" 

Otherwise, the assignment will simply create a new local variable that obscures your global variable (therefore, changes to it will not affect the global variable, as is the case in your example).

However, you could also use the class here so that your functions share state:

 class MyApp(object): def main(self, argv): self.myVar = "bar" self.mySub() def mySub(self): print self.myVar MyApp().main(sys.argv[1:]) 
+8
source

What you are looking for is a global operator in python. Insert global myGlobal in front of your code blocks into main and mySub , and there you have predictable behavior. Having said that, if you need to pass state information between functions, use function arguments. This is a lot neat.

+2
source

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


All Articles