I'm having troubles understanding global variables in python. I am trying to keep track of when a function gets called and once it does I want it to be unavailable to the user. However for some reason its not working :\

psycStat = False
def main():

   form = cgi.FieldStorage()
   global gasStat
   global psycStat
   psycStat = True   
   print "pyscStat"
   print psycStat

   if form.has_key('form'):
      page = form['form'].value   
      if(page == "choose"):   
         if(form.getvalue('Radio')):
            choice = form.getvalue('Radio')
            choose(choice)
         else:
            printChoose()
      elif(page == "psyc"):               
         if not psycStat:
            global psycStat
            psycStat = True
            print("PsycStat:")
            print psycStat

            choice= form.getvalue('Radio')
            pysc(choice)
         else:
            print("Already did psycstat")
      else:
         if(form.getvalue('another')):
            printChoose()
         else:
            printGoodbye()            
   else:
      printChoose()

For some odd reason if i leave the "global/psycStat = True" right below main() psycStat changes to true. However if its inside the if statment psycStat is True up until main() is called again, where it gets reset to False. I'm confused. Thanks for your help

Can you isolate the problem in a code that can be run on its own?

I think using global statement in python is unfortunate. 99% of the cases, it is bad design. Most basic books on programming suggest the same and not only in python.
See stackoverflow

Try setting up a module and importing it, or use a good OO design that separates concerns.

i guess i'm trying to do what this guy is suggesting in the the stackoverflow link

I've used it in quick & dirty, single-use scripts to automate some one-time task. Anything bigger than that, or that needs to be reused, and I'll find a more elegant way.

Where I am trying to change a global variable is here

global pStatus	
			if not pStatus:
				pStatus = True
				choice= form.getvalue('Radio')
				pysc(choice)
			else:
				print("Already did psycstat")
				printChoose()

which is inside main(). @ pStatus = True, pStatus does equal True,
but when main() is called again pStatus is reset to False. the weird part is if i do

main()
        global pStatus
        pStatus = True

oustide of any "if" statements it works :\

Do not use things you do not understand. You may fix this error, or you may just make the error more subtle. You have no way of knowing since you don't understand it. This code has everything that you shouldn't do. And is probably done by a lazy coder. Pass the variable back and forth or learn to use classes (or spend the rest of your life beating your head against this wall).

def a_function_with_a_name_that_has_some_meaning(psyc_stat=False):
    print psyc_stat
    psyc_stat = not psyc_stat
    print psyc_stat
    return psyc_stat

ps = a_function_with_a_name_that_has_some_meaning()
print "-" * 10
ps = a_function_with_a_name_that_has_some_meaning(ps)
"""
My Results

False
True
----------
True
False
"""

Edited 6 Years Ago by woooee: n/a

so are you helping me or are you making me feel "lazy" because I obviously just started python cgi scripting and am not quite sure how global variables work and decided to ask for help.

Hi Meisterluv!

You are not your code. Do not take this personally.

Global statement in python is - as I said earlier - a necessary evil. Most people with years of programming practice never used it.

If you show a code that is not complete and running, it is hard to catch an error.

I do not think that the problem is in python. Using (changing) globals in most languages I know is generally a bad idea.

Some techniques to avoid globals:
1. Use a global module

#module globs.py
glob1=True
glob2="I am a global"

#module main.py
import globs

def fucnt(anything):
    globs.glob1=False

2. Use OO design with classes. In most the cases the application object or other singleton holds the global context.
3. Use classical structural programming with the context (your global variables as a dict or other object) passing

This article has been dead for over six months. Start a new discussion instead.