0

I'm running into an unbound local error message that I am not understanding. I am setting the default value of a variable to None (just so it is initialized) then in the next function, I run an if statement to check if it is still None, or if I have assigned it something else, and that is when I am getting the error. Please see the code below. Any help would be good.

from sys import stdout

restore_out = None

def toggle_out (toggle=1):
    if toggle == 0:
        if restore_out == None:
            restore_out = stdout
        stdout = None
    elif toggle == 1 and restore_out != None:
        stdout = restore_out

I'm using this to toggle standard output, so when I run a command with os.system('some command') that there is no output.

The code is supposed to call toggle_out(0) to turn it off, and toggle_out(1) to re-enable it.

Please let me know if anything comes to mind.

Ken
  • 125
  • 1
  • 12
  • 1
    Your function tries to reassign `restore_out` (i.e. `restore_out = stdout`) but it doesn't declare `global restore_out`. So `restore_out` is treated as a variable local to the function, and at the point when the `if` and `elif` statements are executed, it isn't initialised. – slothrop May 12 '23 at 21:00
  • this is a very common error, if you just google it you will get many results from StackOverflow that discuss this error. The duplicate target was the top hit when I searched for "unboundlocal error python stackoverflow" – juanpa.arrivillaga May 12 '23 at 22:35

1 Answers1

0

You are trying to assign a value to a variable within a function that was defined outside of that function's scope. In your case, you are trying to assign a value to stdout and restore_out variables inside the function toggle_out, which are defined outside of the function's scope.

When you define a variable inside a function, Python assumes that you are creating a new variable that is local to that function. This means that if you try to access or modify a variable that was defined outside of the function's scope, Python will assume that you are referring to a different variable.

You can use the global keyword to explicitly tell Python that you want to use the variables that were defined outside of the function's scope.

from sys import stdout

restore_out = None

def toggle_out (toggle=1):
    global stdout, restore_out
    if toggle == 0:
        if restore_out == None:
            restore_out = stdout
        stdout = None
    elif toggle == 1 and restore_out != None:
        stdout = restore_out
Anton Petrov
  • 315
  • 1
  • 3
  • 12