17

Can anyone explain this to me? (Python 3.3.2, numpy 1.7.1):

>>> a = np.array([[1,2],[3,4]])
>>> a    # just a peek
array([[1, 2],
       [3, 4]])
>>> a.resize(3,2)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: cannot resize an array references or is referenced
by another array in this way.  Use the resize function
>>> a = np.array([[1,2],[3,4]])
>>> a.resize(3,2)
>>> a
array([[1, 2],
       [3, 4],
       [0, 0]])
>>> a = np.array([[1,2],[3,4]])
>>> print(a)   # look properly this time
[[1 2]
 [3 4]]
>>> a.resize(3,2)
>>> a
array([[1, 2],
       [3, 4],
       [0, 0]])

Why does taking a peek at the array create a reference to it? (or, at least, why does that reference persist after I'm done looking?) Also, is it just me or does that Exception need a bit of a rewrite?

1
  • 2
    It's not just you. The exception message is missing a "which" in front of "references" and could use a healthy dose of punctuation and capitalization. Commented Feb 10, 2014 at 7:04

1 Answer 1

16

From the documentation (emphasis mine):

The purpose of the reference count check is to make sure you do not use this array as a buffer for another Python object and then reallocate the memory. However, reference counts can increase in other ways so if you are sure that you have not shared the memory for this array with another Python object, then you may safely set refcheck to False.

Your "peek", unlike print, does not decrement the reference count afterwards. This is because, in the interpreter, the result of the last computation is assigned to _. Try:

print(_) # shows array
a.resize((3, 2), refcheck=False) # works

Alternatively, if you do any other computation (e.g. just 1 + 2) in-between, this will dereference your array from _.

Sign up to request clarification or add additional context in comments.

3 Comments

Make sense (more so than the error message). Perhaps it shouldn't, though... I understood that creating a view on an array will create a reference - what other operations do so?
In this case, it's only because you're using the interpreter, which assigns the result of the last computation to _. I agree that the error message isn't terribly helpful!
Got it! I actually didn't know about _ until now. Sneaky... Thanks!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.