简体   繁体   中英

Weird Python / numpy UnboundLocalError behaviour

I am working on Python 2.7.12 and numpy 1.12.0 and observing the following behavior. Is this expected? I assumed that " a " to be in the scope wrt " f2 " in both the cases how is accessing the " a " different than accessing a[ind, :] ?

import numpy as np
def f1():
   a = np.zeros((1, 10))
   def f2():
      print locals()
      v = [0] * 10
      v[3] = 1
      a += v
   f2()


def f11():
   a = np.zeros((1, 10))
   def f2():
      print locals()
      v = [0] * 10
      v[3] = 1
      a[0,:] = v
   f2()

Result::

>>> f11()
{'a': array([[ 0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.,  0.]])}
>>> f1()
{}
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 8, in f1
  File "<stdin>", line 7, in f2
UnboundLocalError: local variable 'a' referenced before assignment
>>>

In your first example, you used augmented assignment :

a += v

That makes a a local variable ; all binding actions, including assignment, makes a variable local. This is determined at compile time. See the Naming and binding section of the Python execution model:

If a name is bound in a block, it is a local variable of that block.

[...]

The following constructs bind names: [...] targets that are identifiers if occurring in an assignment, [...] .

a is a target that is an identifier.

Because a is considered a local, attempting to read the reference before it has been bound, will throw a UnboundLocal exception. The augmented assignment has to read a before it can assign back to a , hence the exception.

Your second example does not bind to a anywhere in f2 ; assigning to a slice of a won't alter the name a itself. You assigned to a[0,:] ; that's not an identifier, that's a slice.

You can make the first example work by replacing a += v with np.add(a, v, out=a) .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM