Python UnboundLocalError

def blah(self, args):
    def do_blah():
        if not args:
            args = ['blah']
        for arg in args:
            print arg  

the above leads to an error if not argssaying that UnboundLocalError: the local variable 'args' mentioned before the assignment.

def blah(self, args):
    def do_blah():
        for arg in args:       <-- args here
            print arg  

but it works despite using args

why doesn't the first use blah's arguments if not args:?

+4
source share
1 answer

The problem is that when python sees the destination inside the function, then it treats this variable as a local variable and will not extract its value from the closing or global scope when the function is executed.

args = ['blah']

foo = 'bar'
def func():
    print foo    #This is not going to print 'bar'
    foo = 'spam'  #Assignment here, so the previous line is going to raise an error.
    print foo
func()    

Output:

  File "/home/monty/py/so.py", line 6, in <module>
    func()
  File "/home/monty/py/so.py", line 3, in func
    print foo
UnboundLocalError: local variable 'foo' referenced before assignment

Note that if it foois a mutable object here, and you are trying to perform an in-place operation on it, then python will not complain about it.

foo = []
def func():
    print foo
    foo.append(1)
    print foo
func()  

Output:

[]
[1]

: UnboundLocalError, ?

+3

All Articles