abcd
abcd

Reputation: 10751

Unbound local in a function within a function

I have the following code (written in Python 2.X):

def banana(x):
    def apple(stuff):
        x /= 10
        return stuff - x
    return apple(11)

When I call banana, I get the following error:

In [25]: import test

In [26]: test.banana(10)
---------------------------------------------------------------------------
UnboundLocalError                         Traceback (most recent call last)
<ipython-input-26-313a8e4dfaff> in <module>()
----> 1 test.banana(10)

/home/dan/Science/dopa_net/test.py in banana(x)
      3         x /= 10
      4         return stuff - x
----> 5     return apple(11)

/home/dan/Science/dopa_net/test.py in apple(stuff)
      1 def banana(x):
      2     def apple(stuff):
----> 3         x /= 10
      4         return stuff - x
      5     return apple(11)

UnboundLocalError: local variable 'x' referenced before assignment

It seems to me that x, defined in banana's scope, should be available to apple, much as a constant defined at the level of a module is available to functions within that module.

I looked around on SO to see what I'd done wrong, and I got the impression that I should have declared x as a global within apple. This, however, failed for me as well:

In [27]: reload(test)
Out[27]: <module 'test' from 'test.py'>

In [28]: test.banana(10)
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-28-313a8e4dfaff> in <module>()
----> 1 test.banana(10)

/home/dan/Science/dopa_net/test.py in banana(x)
      4         x /= 10
      5         return stuff - x
----> 6     return apple(11)

/home/dan/Science/dopa_net/test.py in apple(stuff)
      2     def apple(stuff):
      3         global x
----> 4         x /= 10
      5         return stuff - x
      6     return apple(11)

NameError: global name 'x' is not defined

What's going on here?

Upvotes: 1

Views: 53

Answers (1)

BrenBarn
BrenBarn

Reputation: 251383

"Global" means global to the module. Your x is not global; it is local to banana, but not to apple.

In Python 3, you can use nonlocal x to make x assignable inside apple. In Python 2 there is no way to assign to x from inside apple. You must use a workaround such as making x a mutable object and mutating it (instead of assigning to it) in apple.

Upvotes: 3

Related Questions