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

the above raise an error at if not args saying UnboundLocalError: local variable 'args' referenced before assignment.

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

but this works despite using args

why is the first one not using the blah's args in if not args:?

ealeon
  • 12,074
  • 24
  • 92
  • 173
  • http://eli.thegreenplace.net/2011/05/15/understanding-unboundlocalerror-in-python/ – lucasg Nov 14 '13 at 15:45
  • possible duplicate of [Passing argument from Parent function to nested function Python](http://stackoverflow.com/q/14678434) and [Closure in python?](http://stackoverflow.com/q18274051) – Martijn Pieters Nov 14 '13 at 15:50

1 Answers1

3

Problem is when python sees a assignment inside a function then it considers that variable as local variable and will not fetch its value from enclosing or global scope when we execute the function.

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 foo is a mutable object here and you try to perform an in-place operation on it then python is not going to complain for that.

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

Output:

[]
[1]

Docs: Why am I getting an UnboundLocalError when the variable has a value?

Ashwini Chaudhary
  • 244,495
  • 58
  • 464
  • 504