-1

I have been getting into the festive spirit and have set a code challenge to light up my tree with a get request using Flask.

Currently, I am hitting a UnboundLocalError: local variable 'test' referenced before assignment

I don't understand how to set up a variable that one thread can set to either true or false and the other reads it and lights up my tree.


import threading
from flask import Flask
app = Flask(__name__)
test = 'best'


@app.route('/')
def hello():
    test = not test
    return "Hello World!"

def background():
    from gpiozero import LEDBoard
    from gpiozero.tools import random_values
    from signal import pause
    from time import sleep
    tree = LEDBoard(*range(2,28),pwm=True)
    while True:
        if test:
            for led in tree:
                led.source_delay = 0.1
                led.source = random_values()
            sleep(0.2)

def foreground():
    app.run(host='0.0.0.0')



test = True
b = threading.Thread(name='background', target=background)
f = threading.Thread(name='foreground', target=foreground)

b.start()
f.start()

What is the best way for me to share the test variable and alternate it between true and false between the 2 threads without some heavy engineering such as using a database or writing out to a text file?

apollowebdesigns
  • 658
  • 11
  • 26
  • 1
    Does this answer your question? [UnboundLocalError on local variable when reassigned after first use](https://stackoverflow.com/questions/370357/unboundlocalerror-on-local-variable-when-reassigned-after-first-use) – manveti Dec 10 '20 at 19:33
  • As a side note, `test = not test` is not atomic. If you do that operation on multiple threads you run the risk that another thread will run between resolving `not test` and assigning to `test`. – tdelaney Dec 10 '20 at 19:56

1 Answers1

1

In hello, you assign a value to test in test = not test, so Python considers it a local variable in this function.

If you mean to use the global test, add global test at the start of the function.

Thierry Lathuille
  • 23,663
  • 10
  • 44
  • 50