pythonpython-3.xfunctionscoping

UnboundLocalError, can't modify the parameter "where it is not associated with a value", while it's associated with its default value


i'd checked some other similar questions trying to find out what's wrong with this but they didn't help a lot as i needed to change the value in the function myself which i don't want to, and i want the user to be able to do that.

Here's the code:

import threading

def showColor(color = "Green"):
    class loading(threading.Thread):
        def __init__(self):
            threading.Thread.__init__(self)
        def run():
            c = '>'+color+'<'
            print(c)
showColor("Red")

I REALLY have no idea why is this happening... i know it's definitely because of that global, local thing but i still can't fix it if i don't give it a value right inside of the function itself too... traceback:

cannot access local variable 'color' where it is not associated with a value

But... i mean it is associated with a value right? how can i fix it?


Solution

  • The problem is that the class should NOT be inside the function and must be defined outside of it and INSTEAD be CALLED inside the function.

    don't know how i didn't notice that i could do this instead

    So it'll be like this:

    import threading
    
    class loading(threading.Thread):
        def __init__(self):
            threading.Thread.__init__(self)
    
        def run(color):
            c = '>'+color+'<'
            print(c)
    
    def showColor(color="Green"):
        loading.run(color)
    
    showColor("Red")