Global variables confusion in python

De openkb
Aller à : Navigation, rechercher

Sommaire

Questions

I have a global variables that I am using as a default variable. Depending on what happens in my program I need the ability to change those defaults and have the changes persist through the remaining operation of my code. I want them changed and defined everywhere hence I used a global variable. Here is some test code that shows how I am trying to modify these variables.

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

    • The program thinks that myGlobal hasn t been defined in main. But
    it has. Why?
    • When i call a subroutine after I have changed myGlobal. I didn t want that to happen.

What is the proper way to accomplish what I am 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:])

Answers

If you want to assign to, rather than read a module-global variable from within a function, you need the global keyword:

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

Otherwise the assignment will just create a new local variable that shadows your global variable (so changes to it will not affect the global variable, like it is the case in your example).

That said, you could also use a class here to have your functions share state in a nicer way:

class MyApp(object):
  def main(self, argv):
    self.myVar = "bar"
    self.mySub()

  def mySub(self):
    print self.myVar

MyApp().main(sys.argv[1:])

Source

License : cc by-sa 3.0

http://stackoverflow.com/questions/9936466/global-variables-confusion-in-python

Related

Outils personnels
Espaces de noms

Variantes
Actions
Navigation
Outils