Search code examples
pythonvariablesglobal

Python local variable confusion


I got a problem coding python and I am feeling quite helpless :(

Here is my Code (it is greatly simplified, because my code is multiple hundreds of lines long):

def coax():
   #some tkinter stuff...
   text = ""
   def refresh():
      try:
         do_something(text)
         text = "Hello"
      except:
         do_something_else(text)

do_something() and do_something_else() are other functions, that don't matter in this case.

What I know by now, is that by the statement text = "Hello" it is now a local variable. I don't want it to be a local variable. I want to change the text variable in coax(), not create a new local in refresh().

I tried to use global (I know this is a very inelegant solution and should not be used). Code looked like this:

def coax():
   #some tkinter stuff...
   text = ""
   def refresh():
      global text
      try:
         do_something(text)
         text = "Hello"
      except:
         do_something_else(text)

This gave me a "NameError: name 'text' is not defined" exception in the except block. What am I doing wrong? Where can I improve the code?


Solution

  • global does not work because both text variables are local, but they are just at different "levels" of local. To make a variable refer to another local variable in a surrounding function, use nonlocal instead:

    def coax():
       #some tkinter stuff...
       text = ""
       def refresh():
          nonlocal text
          try:
             do_something(text)
             text = "Hello"
          except:
             do_something_else(text)