Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

numpy.getbuffer causes AttributeError: 'module' object has no attribute 'getbuffer'

I want to get a buffer from a numpy array in Python 3. I have found the following code:

$ python3
Python 3.2.3 (default, Sep 25 2013, 18:25:56) 
[GCC 4.6.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import numpy
>>> a = numpy.arange(10)
>>> numpy.getbuffer(a)

However it produces the error on the last step:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'module' object has no attribute 'getbuffer'

Why am I doing wrong? The code works fine for Python 2. The numpy version I'm using is 1.6.1.

like image 881
Evgenii.Balai Avatar asked Feb 17 '14 04:02

Evgenii.Balai


2 Answers

According to Developer notes on the transition to Python 3:

PyBuffer (object)

Since there is a native buffer object in Py3, the memoryview, the newbuffer and getbuffer functions are removed from multiarray in Py3: their functionality is taken over by the new memoryview object.

>>> import numpy
>>> a = numpy.arange(10)
>>> memoryview(a)
<memory at 0xb60ae094>
>>> m = _
>>> m[0] = 9
>>> a
array([9, 1, 2, 3, 4, 5, 6, 7, 8, 9])
like image 85
falsetru Avatar answered Nov 01 '22 09:11

falsetru


Numpy's arr.tobytes() seems to be significantly faster than bytes(memoryview(arr)) in returning a bytes object. So, you may want to have a look at tobytes() as well.

Profiling for Windows 7 on Intel i7 CPU, CPython v3.5.0, numpy v1.10.1.

(Edit Note: same result order on Ubuntu 16.04, Intel i7 CPU, CPython v3.6.5, numpy v1.14.5.)

setup = '''import numpy as np; x = np.random.random(n).reshape(n//10, -1)'''

results

globals: {'n': 100}, tested 1e+06 times

   time (s) speedup                  methods
0  0.163005   6.03x              x.tobytes()
1  0.491887   2.00x         x.data.tobytes()
2  0.598286   1.64x  memoryview(x).tobytes()
3  0.964653   1.02x            bytes(x.data)
4  0.982743             bytes(memoryview(x))


globals: {'n': 1000}, tested 1e+06 times

   time (s) speedup                  methods
0  0.378260   3.21x              x.tobytes()
1  0.708204   1.71x         x.data.tobytes()
2  0.827941   1.47x  memoryview(x).tobytes()
3  1.189048   1.02x            bytes(x.data)
4  1.213423             bytes(memoryview(x))


globals: {'n': 10000}, tested 1e+06 times

   time (s) speedup                  methods
0  3.393949   1.34x              x.tobytes()
1  3.739483   1.22x         x.data.tobytes()
2  4.033783   1.13x  memoryview(x).tobytes()
3  4.469730   1.02x            bytes(x.data)
4  4.543620             bytes(memoryview(x))
like image 26
mab Avatar answered Nov 01 '22 08:11

mab