Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading