Debian Codegraph @

lib-python/3/test/test_buffer.py

raw symbols SCIP
1 #
2 # The ndarray object from _testbuffer.c is a complete implementation of
3 # a PEP-3118 buffer provider. It is independent from NumPy's ndarray
4 # and the tests don't require NumPy.
5 #
6 # If NumPy is present, some tests check both ndarray implementations
7 # against each other.
8 #
9 # Most ndarray tests also check that memoryview(ndarray) behaves in
10 # the same way as the original. Thus, a substantial part of the
11 # memoryview tests is now in this module.
12 #
13 # Written and designed by Stefan Krah for Python 3.3.
14 #
15
16 import contextlib
17 import unittest
18 from test import support
19 from test.support import os_helper
20 from itertools import permutations, product
21 from random import randrange, sample, choice
22 import warnings
23 import sys, array, io, os
24 from decimal import Decimal
25 from fractions import Fraction
26
27 try:
28 from _testbuffer import *
29 except ImportError:
30 ndarray = None
31
32 try:
33 import struct
34 except ImportError:
35 struct = None
36
37 try:
38 import ctypes
39 except ImportError:
40 ctypes = None
41
42 try:
43 with os_helper.EnvironmentVarGuard() as os.environ, \
44 warnings.catch_warnings():
45 from numpy import ndarray as numpy_array
46 except ImportError:
47 numpy_array = None
48
49 try:
50 import _testcapi
51 except ImportError:
52 _testcapi = None
53
54
55 SHORT_TEST = True
56
57
58 # ======================================================================
59 # Random lists by format specifier
60 # ======================================================================
61
62 # Native format chars and their ranges.
63 NATIVE = {
64 '?':0, 'c':0, 'b':0, 'B':0,
65 'h':0, 'H':0, 'i':0, 'I':0,
66 'l':0, 'L':0, 'n':0, 'N':0,
67 'f':0, 'd':0, 'P':0
68 }
69
70 # NumPy does not have 'n' or 'N':
71 if numpy_array:
72 del NATIVE['n']
73 del NATIVE['N']
74
75 if struct:
76 try:
77 # Add "qQ" if present in native mode.
78 struct.pack('Q', 2**64-1)
79 NATIVE['q'] = 0
80 NATIVE['Q'] = 0
81 except struct.error:
82 pass
83
84 # Standard format chars and their ranges.
85 STANDARD = {
86 '?':(0, 2), 'c':(0, 1<<8),
87 'b':(-(1<<7), 1<<7), 'B':(0, 1<<8),
88 'h':(-(1<<15), 1<<15), 'H':(0, 1<<16),
89 'i':(-(1<<31), 1<<31), 'I':(0, 1<<32),
90 'l':(-(1<<31), 1<<31), 'L':(0, 1<<32),
91 'q':(-(1<<63), 1<<63), 'Q':(0, 1<<64),
92 'f':(-(1<<63), 1<<63), 'd':(-(1<<1023), 1<<1023)
93 }
94
95 def native_type_range(fmt):
96 """Return range of a native type."""
97 if fmt == 'c':
98 lh = (0, 256)
99 elif fmt == '?':
100 lh = (0, 2)
101 elif fmt == 'f':
102 lh = (-(1<<63), 1<<63)
103 elif fmt == 'd':
104 lh = (-(1<<1023), 1<<1023)
105 else:
106 for exp in (128, 127, 64, 63, 32, 31, 16, 15, 8, 7):
107 try:
108 struct.pack(fmt, (1<<exp)-1)
109 break
110 except struct.error:
111 pass
112 lh = (-(1<<exp), 1<<exp) if exp & 1 else (0, 1<<exp)
113 return lh
114
115 fmtdict = {
116 '':NATIVE,
117 '@':NATIVE,
118 '<':STANDARD,
119 '>':STANDARD,
120 '=':STANDARD,
121 '!':STANDARD
122 }
123
124 if struct:
125 for fmt in fmtdict['@']:
126 fmtdict['@'][fmt] = native_type_range(fmt)
127
128 MEMORYVIEW = NATIVE.copy()
129 ARRAY = NATIVE.copy()
130 for k in NATIVE:
131 if not k in "bBhHiIlLfd":
132 del ARRAY[k]
133
134 BYTEFMT = NATIVE.copy()
135 for k in NATIVE:
136 if not k in "Bbc":
137 del BYTEFMT[k]
138
139 fmtdict['m'] = MEMORYVIEW
140 fmtdict['@m'] = MEMORYVIEW
141 fmtdict['a'] = ARRAY
142 fmtdict['b'] = BYTEFMT
143 fmtdict['@b'] = BYTEFMT
144
145 # Capabilities of the test objects:
146 MODE = 0
147 MULT = 1
148 cap = { # format chars # multiplier
149 'ndarray': (['', '@', '<', '>', '=', '!'], ['', '1', '2', '3']),
150 'array': (['a'], ['']),
151 'numpy': ([''], ['']),
152 'memoryview': (['@m', 'm'], ['']),
153 'bytefmt': (['@b', 'b'], ['']),
154 }
155
156 def randrange_fmt(mode, char, obj):
157 """Return random item for a type specified by a mode and a single
158 format character."""
159 x = randrange(*fmtdict[mode][char])
160 if char == 'c':
161 x = bytes([x])
162 if obj == 'numpy' and x == b'\x00':
163 # http://projects.scipy.org/numpy/ticket/1925
164 x = b'\x01'
165 if char == '?':
166 x = bool(x)
167 if char == 'f' or char == 'd':
168 x = struct.pack(char, x)
169 x = struct.unpack(char, x)[0]
170 return x
171
172 def gen_item(fmt, obj):
173 """Return single random item."""
174 mode, chars = fmt.split('#')
175 x = []
176 for c in chars:
177 x.append(randrange_fmt(mode, c, obj))
178 return x[0] if len(x) == 1 else tuple(x)
179
180 def gen_items(n, fmt, obj):
181 """Return a list of random items (or a scalar)."""
182 if n == 0:
183 return gen_item(fmt, obj)
184 lst = [0] * n
185 for i in range(n):
186 lst[i] = gen_item(fmt, obj)
187 return lst
188
189 def struct_items(n, obj):
190 mode = choice(cap[obj][MODE])
191 xfmt = mode + '#'
192 fmt = mode.strip('amb')
193 nmemb = randrange(2, 10) # number of struct members
194 for _ in range(nmemb):
195 char = choice(tuple(fmtdict[mode]))
196 multiplier = choice(cap[obj][MULT])
197 xfmt += (char * int(multiplier if multiplier else 1))
198 fmt += (multiplier + char)
199 items = gen_items(n, xfmt, obj)
200 item = gen_item(xfmt, obj)
201 return fmt, items, item
202
203 def randitems(n, obj='ndarray', mode=None, char=None):
204 """Return random format, items, item."""
205 if mode is None:
206 mode = choice(cap[obj][MODE])
207 if char is None:
208 char = choice(tuple(fmtdict[mode]))
209 multiplier = choice(cap[obj][MULT])
210 fmt = mode + '#' + char * int(multiplier if multiplier else 1)
211 items = gen_items(n, fmt, obj)
212 item = gen_item(fmt, obj)
213 fmt = mode.strip('amb') + multiplier + char
214 return fmt, items, item
215
216 def iter_mode(n, obj='ndarray'):
217 """Iterate through supported mode/char combinations."""
218 for mode in cap[obj][MODE]:
219 for char in fmtdict[mode]:
220 yield randitems(n, obj, mode, char)
221
222 def iter_format(nitems, testobj='ndarray'):
223 """Yield (format, items, item) for all possible modes and format
224 characters plus one random compound format string."""
225 for t in iter_mode(nitems, testobj):
226 yield t
227 if testobj != 'ndarray':
228 return
229 yield struct_items(nitems, testobj)
230
231
232 def is_byte_format(fmt):
233 return 'c' in fmt or 'b' in fmt or 'B' in fmt
234
235 def is_memoryview_format(fmt):
236 """format suitable for memoryview"""
237 x = len(fmt)
238 return ((x == 1 or (x == 2 and fmt[0] == '@')) and
239 fmt[x-1] in MEMORYVIEW)
240
241 NON_BYTE_FORMAT = [c for c in fmtdict['@'] if not is_byte_format(c)]
242
243
244 # ======================================================================
245 # Multi-dimensional tolist(), slicing and slice assignments
246 # ======================================================================
247
248 def atomp(lst):
249 """Tuple items (representing structs) are regarded as atoms."""
250 return not isinstance(lst, list)
251
252 def listp(lst):
253 return isinstance(lst, list)
254
255 def prod(lst):
256 """Product of list elements."""
257 if len(lst) == 0:
258 return 0
259 x = lst[0]
260 for v in lst[1:]:
261 x *= v
262 return x
263
264 def strides_from_shape(ndim, shape, itemsize, layout):
265 """Calculate strides of a contiguous array. Layout is 'C' or
266 'F' (Fortran)."""
267 if ndim == 0:
268 return ()
269 if layout == 'C':
270 strides = list(shape[1:]) + [itemsize]
271 for i in range(ndim-2, -1, -1):
272 strides[i] *= strides[i+1]
273 else:
274 strides = [itemsize] + list(shape[:-1])
275 for i in range(1, ndim):
276 strides[i] *= strides[i-1]
277 return strides
278
279 def _ca(items, s):
280 """Convert flat item list to the nested list representation of a
281 multidimensional C array with shape 's'."""
282 if atomp(items):
283 return items
284 if len(s) == 0:
285 return items[0]
286 lst = [0] * s[0]
287 stride = len(items) // s[0] if s[0] else 0
288 for i in range(s[0]):
289 start = i*stride
290 lst[i] = _ca(items[start:start+stride], s[1:])
291 return lst
292
293 def _fa(items, s):
294 """Convert flat item list to the nested list representation of a
295 multidimensional Fortran array with shape 's'."""
296 if atomp(items):
297 return items
298 if len(s) == 0:
299 return items[0]
300 lst = [0] * s[0]
301 stride = s[0]
302 for i in range(s[0]):
303 lst[i] = _fa(items[i::stride], s[1:])
304 return lst
305
306 def carray(items, shape):
307 if listp(items) and not 0 in shape and prod(shape) != len(items):
308 raise ValueError("prod(shape) != len(items)")
309 return _ca(items, shape)
310
311 def farray(items, shape):
312 if listp(items) and not 0 in shape and prod(shape) != len(items):
313 raise ValueError("prod(shape) != len(items)")
314 return _fa(items, shape)
315
316 def indices(shape):
317 """Generate all possible tuples of indices."""
318 iterables = [range(v) for v in shape]
319 return product(*iterables)
320
321 def getindex(ndim, ind, strides):
322 """Convert multi-dimensional index to the position in the flat list."""
323 ret = 0
324 for i in range(ndim):
325 ret += strides[i] * ind[i]
326 return ret
327
328 def transpose(src, shape):
329 """Transpose flat item list that is regarded as a multi-dimensional
330 matrix defined by shape: dest...[k][j][i] = src[i][j][k]... """
331 if not shape:
332 return src
333 ndim = len(shape)
334 sstrides = strides_from_shape(ndim, shape, 1, 'C')
335 dstrides = strides_from_shape(ndim, shape[::-1], 1, 'C')
336 dest = [0] * len(src)
337 for ind in indices(shape):
338 fr = getindex(ndim, ind, sstrides)
339 to = getindex(ndim, ind[::-1], dstrides)
340 dest[to] = src[fr]
341 return dest
342
343 def _flatten(lst):
344 """flatten list"""
345 if lst == []:
346 return lst
347 if atomp(lst):
348 return [lst]
349 return _flatten(lst[0]) + _flatten(lst[1:])
350
351 def flatten(lst):
352 """flatten list or return scalar"""
353 if atomp(lst): # scalar
354 return lst
355 return _flatten(lst)
356
357 def slice_shape(lst, slices):
358 """Get the shape of lst after slicing: slices is a list of slice
359 objects."""
360 if atomp(lst):
361 return []
362 return [len(lst[slices[0]])] + slice_shape(lst[0], slices[1:])
363
364 def multislice(lst, slices):
365 """Multi-dimensional slicing: slices is a list of slice objects."""
366 if atomp(lst):
367 return lst
368 return [multislice(sublst, slices[1:]) for sublst in lst[slices[0]]]
369
370 def m_assign(llst, rlst, lslices, rslices):
371 """Multi-dimensional slice assignment: llst and rlst are the operands,
372 lslices and rslices are lists of slice objects. llst and rlst must
373 have the same structure.
374
375 For a two-dimensional example, this is not implemented in Python:
376
377 llst[0:3:2, 0:3:2] = rlst[1:3:1, 1:3:1]
378
379 Instead we write:
380
381 lslices = [slice(0,3,2), slice(0,3,2)]
382 rslices = [slice(1,3,1), slice(1,3,1)]
383 multislice_assign(llst, rlst, lslices, rslices)
384 """
385 if atomp(rlst):
386 return rlst
387 rlst = [m_assign(l, r, lslices[1:], rslices[1:])
388 for l, r in zip(llst[lslices[0]], rlst[rslices[0]])]
389 llst[lslices[0]] = rlst
390 return llst
391
392 def cmp_structure(llst, rlst, lslices, rslices):
393 """Compare the structure of llst[lslices] and rlst[rslices]."""
394 lshape = slice_shape(llst, lslices)
395 rshape = slice_shape(rlst, rslices)
396 if (len(lshape) != len(rshape)):
397 return -1
398 for i in range(len(lshape)):
399 if lshape[i] != rshape[i]:
400 return -1
401 if lshape[i] == 0:
402 return 0
403 return 0
404
405 def multislice_assign(llst, rlst, lslices, rslices):
406 """Return llst after assigning: llst[lslices] = rlst[rslices]"""
407 if cmp_structure(llst, rlst, lslices, rslices) < 0:
408 raise ValueError("lvalue and rvalue have different structures")
409 return m_assign(llst, rlst, lslices, rslices)
410
411
412 # ======================================================================
413 # Random structures
414 # ======================================================================
415
416 #
417 # PEP-3118 is very permissive with respect to the contents of a
418 # Py_buffer. In particular:
419 #
420 # - shape can be zero
421 # - strides can be any integer, including zero
422 # - offset can point to any location in the underlying
423 # memory block, provided that it is a multiple of
424 # itemsize.
425 #
426 # The functions in this section test and verify random structures
427 # in full generality. A structure is valid iff it fits in the
428 # underlying memory block.
429 #
430 # The structure 't' (short for 'tuple') is fully defined by:
431 #
432 # t = (memlen, itemsize, ndim, shape, strides, offset)
433 #
434
435 def verify_structure(memlen, itemsize, ndim, shape, strides, offset):
436 """Verify that the parameters represent a valid array within
437 the bounds of the allocated memory:
438 char *mem: start of the physical memory block
439 memlen: length of the physical memory block
440 offset: (char *)buf - mem
441 """
442 if offset % itemsize:
443 return False
444 if offset < 0 or offset+itemsize > memlen:
445 return False
446 if any(v % itemsize for v in strides):
447 return False
448
449 if ndim <= 0:
450 return ndim == 0 and not shape and not strides
451 if 0 in shape:
452 return True
453
454 imin = sum(strides[j]*(shape[j]-1) for j in range(ndim)
455 if strides[j] <= 0)
456 imax = sum(strides[j]*(shape[j]-1) for j in range(ndim)
457 if strides[j] > 0)
458
459 return 0 <= offset+imin and offset+imax+itemsize <= memlen
460
461 def get_item(lst, indices):
462 for i in indices:
463 lst = lst[i]
464 return lst
465
466 def memory_index(indices, t):
467 """Location of an item in the underlying memory."""
468 memlen, itemsize, ndim, shape, strides, offset = t
469 p = offset
470 for i in range(ndim):
471 p += strides[i]*indices[i]
472 return p
473
474 def is_overlapping(t):
475 """The structure 't' is overlapping if at least one memory location
476 is visited twice while iterating through all possible tuples of
477 indices."""
478 memlen, itemsize, ndim, shape, strides, offset = t
479 visited = 1<<memlen
480 for ind in indices(shape):
481 i = memory_index(ind, t)
482 bit = 1<<i
483 if visited & bit:
484 return True
485 visited |= bit
486 return False
487
488 def rand_structure(itemsize, valid, maxdim=5, maxshape=16, shape=()):
489 """Return random structure:
490 (memlen, itemsize, ndim, shape, strides, offset)
491 If 'valid' is true, the returned structure is valid, otherwise invalid.
492 If 'shape' is given, use that instead of creating a random shape.
493 """
494 if not shape:
495 ndim = randrange(maxdim+1)
496 if (ndim == 0):
497 if valid:
498 return itemsize, itemsize, ndim, (), (), 0
499 else:
500 nitems = randrange(1, 16+1)
501 memlen = nitems * itemsize
502 offset = -itemsize if randrange(2) == 0 else memlen
503 return memlen, itemsize, ndim, (), (), offset
504
505 minshape = 2
506 n = randrange(100)
507 if n >= 95 and valid:
508 minshape = 0
509 elif n >= 90:
510 minshape = 1
511 shape = [0] * ndim
512
513 for i in range(ndim):
514 shape[i] = randrange(minshape, maxshape+1)
515 else:
516 ndim = len(shape)
517
518 maxstride = 5
519 n = randrange(100)
520 zero_stride = True if n >= 95 and n & 1 else False
521
522 strides = [0] * ndim
523 strides[ndim-1] = itemsize * randrange(-maxstride, maxstride+1)
524 if not zero_stride and strides[ndim-1] == 0:
525 strides[ndim-1] = itemsize
526
527 for i in range(ndim-2, -1, -1):
528 maxstride *= shape[i+1] if shape[i+1] else 1
529 if zero_stride:
530 strides[i] = itemsize * randrange(-maxstride, maxstride+1)
531 else:
532 strides[i] = ((1,-1)[randrange(2)] *
533 itemsize * randrange(1, maxstride+1))
534
535 imin = imax = 0
536 if not 0 in shape:
537 imin = sum(strides[j]*(shape[j]-1) for j in range(ndim)
538 if strides[j] <= 0)
539 imax = sum(strides[j]*(shape[j]-1) for j in range(ndim)
540 if strides[j] > 0)
541
542 nitems = imax - imin
543 if valid:
544 offset = -imin * itemsize
545 memlen = offset + (imax+1) * itemsize
546 else:
547 memlen = (-imin + imax) * itemsize
548 offset = -imin-itemsize if randrange(2) == 0 else memlen
549 return memlen, itemsize, ndim, shape, strides, offset
550
551 def randslice_from_slicelen(slicelen, listlen):
552 """Create a random slice of len slicelen that fits into listlen."""
553 maxstart = listlen - slicelen
554 start = randrange(maxstart+1)
555 maxstep = (listlen - start) // slicelen if slicelen else 1
556 step = randrange(1, maxstep+1)
557 stop = start + slicelen * step
558 s = slice(start, stop, step)
559 _, _, _, control = slice_indices(s, listlen)
560 if control != slicelen:
561 raise RuntimeError
562 return s
563
564 def randslice_from_shape(ndim, shape):
565 """Create two sets of slices for an array x with shape 'shape'
566 such that shapeof(x[lslices]) == shapeof(x[rslices])."""
567 lslices = [0] * ndim
568 rslices = [0] * ndim
569 for n in range(ndim):
570 l = shape[n]
571 slicelen = randrange(1, l+1) if l > 0 else 0
572 lslices[n] = randslice_from_slicelen(slicelen, l)
573 rslices[n] = randslice_from_slicelen(slicelen, l)
574 return tuple(lslices), tuple(rslices)
575
576 def rand_aligned_slices(maxdim=5, maxshape=16):
577 """Create (lshape, rshape, tuple(lslices), tuple(rslices)) such that
578 shapeof(x[lslices]) == shapeof(y[rslices]), where x is an array
579 with shape 'lshape' and y is an array with shape 'rshape'."""
580 ndim = randrange(1, maxdim+1)
581 minshape = 2
582 n = randrange(100)
583 if n >= 95:
584 minshape = 0
585 elif n >= 90:
586 minshape = 1
587 all_random = True if randrange(100) >= 80 else False
588 lshape = [0]*ndim; rshape = [0]*ndim
589 lslices = [0]*ndim; rslices = [0]*ndim
590
591 for n in range(ndim):
592 small = randrange(minshape, maxshape+1)
593 big = randrange(minshape, maxshape+1)
594 if big < small:
595 big, small = small, big
596
597 # Create a slice that fits the smaller value.
598 if all_random:
599 start = randrange(-small, small+1)
600 stop = randrange(-small, small+1)
601 step = (1,-1)[randrange(2)] * randrange(1, small+2)
602 s_small = slice(start, stop, step)
603 _, _, _, slicelen = slice_indices(s_small, small)
604 else:
605 slicelen = randrange(1, small+1) if small > 0 else 0
606 s_small = randslice_from_slicelen(slicelen, small)
607
608 # Create a slice of the same length for the bigger value.
609 s_big = randslice_from_slicelen(slicelen, big)
610 if randrange(2) == 0:
611 rshape[n], lshape[n] = big, small
612 rslices[n], lslices[n] = s_big, s_small
613 else:
614 rshape[n], lshape[n] = small, big
615 rslices[n], lslices[n] = s_small, s_big
616
617 return lshape, rshape, tuple(lslices), tuple(rslices)
618
619 def randitems_from_structure(fmt, t):
620 """Return a list of random items for structure 't' with format
621 'fmtchar'."""
622 memlen, itemsize, _, _, _, _ = t
623 return gen_items(memlen//itemsize, '#'+fmt, 'numpy')
624
625 def ndarray_from_structure(items, fmt, t, flags=0):
626 """Return ndarray from the tuple returned by rand_structure()"""
627 memlen, itemsize, ndim, shape, strides, offset = t
628 return ndarray(items, shape=shape, strides=strides, format=fmt,
629 offset=offset, flags=ND_WRITABLE|flags)
630
631 def numpy_array_from_structure(items, fmt, t):
632 """Return numpy_array from the tuple returned by rand_structure()"""
633 memlen, itemsize, ndim, shape, strides, offset = t
634 buf = bytearray(memlen)
635 for j, v in enumerate(items):
636 struct.pack_into(fmt, buf, j*itemsize, v)
637 return numpy_array(buffer=buf, shape=shape, strides=strides,
638 dtype=fmt, offset=offset)
639
640
641 # ======================================================================
642 # memoryview casts
643 # ======================================================================
644
645 def cast_items(exporter, fmt, itemsize, shape=None):
646 """Interpret the raw memory of 'exporter' as a list of items with
647 size 'itemsize'. If shape=None, the new structure is assumed to
648 be 1-D with n * itemsize = bytelen. If shape is given, the usual
649 constraint for contiguous arrays prod(shape) * itemsize = bytelen
650 applies. On success, return (items, shape). If the constraints
651 cannot be met, return (None, None). If a chunk of bytes is interpreted
652 as NaN as a result of float conversion, return ('nan', None)."""
653 bytelen = exporter.nbytes
654 if shape:
655 if prod(shape) * itemsize != bytelen:
656 return None, shape
657 elif shape == []:
658 if exporter.ndim == 0 or itemsize != bytelen:
659 return None, shape
660 else:
661 n, r = divmod(bytelen, itemsize)
662 shape = [n]
663 if r != 0:
664 return None, shape
665
666 mem = exporter.tobytes()
667 byteitems = [mem[i:i+itemsize] for i in range(0, len(mem), itemsize)]
668
669 items = []
670 for v in byteitems:
671 item = struct.unpack(fmt, v)[0]
672 if item != item:
673 return 'nan', shape
674 items.append(item)
675
676 return (items, shape) if shape != [] else (items[0], shape)
677
678 def gencastshapes():
679 """Generate shapes to test casting."""
680 for n in range(32):
681 yield [n]
682 ndim = randrange(4, 6)
683 minshape = 1 if randrange(100) > 80 else 2
684 yield [randrange(minshape, 5) for _ in range(ndim)]
685 ndim = randrange(2, 4)
686 minshape = 1 if randrange(100) > 80 else 2
687 yield [randrange(minshape, 5) for _ in range(ndim)]
688
689
690 # ======================================================================
691 # Actual tests
692 # ======================================================================
693
694 def genslices(n):
695 """Generate all possible slices for a single dimension."""
696 return product(range(-n, n+1), range(-n, n+1), range(-n, n+1))
697
698 def genslices_ndim(ndim, shape):
699 """Generate all possible slice tuples for 'shape'."""
700 iterables = [genslices(shape[n]) for n in range(ndim)]
701 return product(*iterables)
702
703 def rslice(n, allow_empty=False):
704 """Generate random slice for a single dimension of length n.
705 If zero=True, the slices may be empty, otherwise they will
706 be non-empty."""
707 minlen = 0 if allow_empty or n == 0 else 1
708 slicelen = randrange(minlen, n+1)
709 return randslice_from_slicelen(slicelen, n)
710
711 def rslices(n, allow_empty=False):
712 """Generate random slices for a single dimension."""
713 for _ in range(5):
714 yield rslice(n, allow_empty)
715
716 def rslices_ndim(ndim, shape, iterations=5):
717 """Generate random slice tuples for 'shape'."""
718 # non-empty slices
719 for _ in range(iterations):
720 yield tuple(rslice(shape[n]) for n in range(ndim))
721 # possibly empty slices
722 for _ in range(iterations):
723 yield tuple(rslice(shape[n], allow_empty=True) for n in range(ndim))
724 # invalid slices
725 yield tuple(slice(0,1,0) for _ in range(ndim))
726
727 def rpermutation(iterable, r=None):
728 pool = tuple(iterable)
729 r = len(pool) if r is None else r
730 yield tuple(sample(pool, r))
731
732 def ndarray_print(nd):
733 """Print ndarray for debugging."""
734 try:
735 x = nd.tolist()
736 except (TypeError, NotImplementedError):
737 x = nd.tobytes()
738 if isinstance(nd, ndarray):
739 offset = nd.offset
740 flags = nd.flags
741 else:
742 offset = 'unknown'
743 flags = 'unknown'
744 print("ndarray(%s, shape=%s, strides=%s, suboffsets=%s, offset=%s, "
745 "format='%s', itemsize=%s, flags=%s)" %
746 (x, nd.shape, nd.strides, nd.suboffsets, offset,
747 nd.format, nd.itemsize, flags))
748 sys.stdout.flush()
749
750
751 ITERATIONS = 100
752 MAXDIM = 5
753 MAXSHAPE = 10
754
755 if SHORT_TEST:
756 ITERATIONS = 10
757 MAXDIM = 3
758 MAXSHAPE = 4
759 genslices = rslices
760 genslices_ndim = rslices_ndim
761 permutations = rpermutation
762
763
764 @unittest.skipUnless(struct, 'struct module required for this test.')
765 @unittest.skipUnless(ndarray, 'ndarray object required for this test')
766 class TestBufferProtocol(unittest.TestCase):
767
768 def setUp(self):
769 # The suboffsets tests need sizeof(void *).
770 self.sizeof_void_p = get_sizeof_void_p()
771
772 def verify(self, result, *, obj,
773 itemsize, fmt, readonly,
774 ndim, shape, strides,
775 lst, sliced=False, cast=False):
776 # Verify buffer contents against expected values.
777 if shape:
778 expected_len = prod(shape)*itemsize
779 else:
780 if not fmt: # array has been implicitly cast to unsigned bytes
781 expected_len = len(lst)
782 else: # ndim = 0
783 expected_len = itemsize
784
785 # Reconstruct suboffsets from strides. Support for slicing
786 # could be added, but is currently only needed for test_getbuf().
787 suboffsets = ()
788 if result.suboffsets:
789 self.assertGreater(ndim, 0)
790
791 suboffset0 = 0
792 for n in range(1, ndim):
793 if shape[n] == 0:
794 break
795 if strides[n] <= 0:
796 suboffset0 += -strides[n] * (shape[n]-1)
797
798 suboffsets = [suboffset0] + [-1 for v in range(ndim-1)]
799
800 # Not correct if slicing has occurred in the first dimension.
801 stride0 = self.sizeof_void_p
802 if strides[0] < 0:
803 stride0 = -stride0
804 strides = [stride0] + list(strides[1:])
805
806 self.assertIs(result.obj, obj)
807 self.assertEqual(result.nbytes, expected_len)
808 self.assertEqual(result.itemsize, itemsize)
809 self.assertEqual(result.format, fmt)
810 self.assertIs(result.readonly, readonly)
811 self.assertEqual(result.ndim, ndim)
812 self.assertEqual(result.shape, tuple(shape))
813 if not (sliced and suboffsets):
814 self.assertEqual(result.strides, tuple(strides))
815 self.assertEqual(result.suboffsets, tuple(suboffsets))
816
817 if isinstance(result, ndarray) or is_memoryview_format(fmt):
818 rep = result.tolist() if fmt else result.tobytes()
819 self.assertEqual(rep, lst)
820
821 if not fmt: # array has been cast to unsigned bytes,
822 return # the remaining tests won't work.
823
824 # PyBuffer_GetPointer() is the definition how to access an item.
825 # If PyBuffer_GetPointer(indices) is correct for all possible
826 # combinations of indices, the buffer is correct.
827 #
828 # Also test tobytes() against the flattened 'lst', with all items
829 # packed to bytes.
830 if not cast: # casts chop up 'lst' in different ways
831 b = bytearray()
832 buf_err = None
833 for ind in indices(shape):
834 try:
835 item1 = get_pointer(result, ind)
836 item2 = get_item(lst, ind)
837 if isinstance(item2, tuple):
838 x = struct.pack(fmt, *item2)
839 else:
840 x = struct.pack(fmt, item2)
841 b.extend(x)
842 except BufferError:
843 buf_err = True # re-exporter does not provide full buffer
844 break
845 self.assertEqual(item1, item2)
846
847 if not buf_err:
848 # test tobytes()
849 self.assertEqual(result.tobytes(), b)
850
851 # test hex()
852 m = memoryview(result)
853 h = "".join("%02x" % c for c in b)
854 self.assertEqual(m.hex(), h)
855
856 # lst := expected multi-dimensional logical representation
857 # flatten(lst) := elements in C-order
858 ff = fmt if fmt else 'B'
859 flattened = flatten(lst)
860
861 # Rules for 'A': if the array is already contiguous, return
862 # the array unaltered. Otherwise, return a contiguous 'C'
863 # representation.
864 for order in ['C', 'F', 'A']:
865 expected = result
866 if order == 'F':
867 if not is_contiguous(result, 'A') or \
868 is_contiguous(result, 'C'):
869 # For constructing the ndarray, convert the
870 # flattened logical representation to Fortran order.
871 trans = transpose(flattened, shape)
872 expected = ndarray(trans, shape=shape, format=ff,
873 flags=ND_FORTRAN)
874 else: # 'C', 'A'
875 if not is_contiguous(result, 'A') or \
876 is_contiguous(result, 'F') and order == 'C':
877 # The flattened list is already in C-order.
878 expected = ndarray(flattened, shape=shape, format=ff)
879
880 contig = get_contiguous(result, PyBUF_READ, order)
881 self.assertEqual(contig.tobytes(), b)
882 self.assertTrue(cmp_contig(contig, expected))
883
884 if ndim == 0:
885 continue
886
887 nmemb = len(flattened)
888 ro = 0 if readonly else ND_WRITABLE
889
890 ### See comment in test_py_buffer_to_contiguous for an
891 ### explanation why these tests are valid.
892
893 # To 'C'
894 contig = py_buffer_to_contiguous(result, 'C', PyBUF_FULL_RO)
895 self.assertEqual(len(contig), nmemb * itemsize)
896 initlst = [struct.unpack_from(fmt, contig, n*itemsize)
897 for n in range(nmemb)]
898 if len(initlst[0]) == 1:
899 initlst = [v[0] for v in initlst]
900
901 y = ndarray(initlst, shape=shape, flags=ro, format=fmt)
902 self.assertEqual(memoryview(y), memoryview(result))
903
904 contig_bytes = memoryview(result).tobytes()
905 self.assertEqual(contig_bytes, contig)
906
907 contig_bytes = memoryview(result).tobytes(order=None)
908 self.assertEqual(contig_bytes, contig)
909
910 contig_bytes = memoryview(result).tobytes(order='C')
911 self.assertEqual(contig_bytes, contig)
912
913 # To 'F'
914 contig = py_buffer_to_contiguous(result, 'F', PyBUF_FULL_RO)
915 self.assertEqual(len(contig), nmemb * itemsize)
916 initlst = [struct.unpack_from(fmt, contig, n*itemsize)
917 for n in range(nmemb)]
918 if len(initlst[0]) == 1:
919 initlst = [v[0] for v in initlst]
920
921 y = ndarray(initlst, shape=shape, flags=ro|ND_FORTRAN,
922 format=fmt)
923 self.assertEqual(memoryview(y), memoryview(result))
924
925 contig_bytes = memoryview(result).tobytes(order='F')
926 self.assertEqual(contig_bytes, contig)
927
928 # To 'A'
929 contig = py_buffer_to_contiguous(result, 'A', PyBUF_FULL_RO)
930 self.assertEqual(len(contig), nmemb * itemsize)
931 initlst = [struct.unpack_from(fmt, contig, n*itemsize)
932 for n in range(nmemb)]
933 if len(initlst[0]) == 1:
934 initlst = [v[0] for v in initlst]
935
936 f = ND_FORTRAN if is_contiguous(result, 'F') else 0
937 y = ndarray(initlst, shape=shape, flags=f|ro, format=fmt)
938 self.assertEqual(memoryview(y), memoryview(result))
939
940 contig_bytes = memoryview(result).tobytes(order='A')
941 self.assertEqual(contig_bytes, contig)
942
943 if is_memoryview_format(fmt):
944 try:
945 m = memoryview(result)
946 except BufferError: # re-exporter does not provide full information
947 return
948 ex = result.obj if isinstance(result, memoryview) else result
949
950 def check_memoryview(m, expected_readonly=readonly):
951 self.assertIs(m.obj, ex)
952 self.assertEqual(m.nbytes, expected_len)
953 self.assertEqual(m.itemsize, itemsize)
954 self.assertEqual(m.format, fmt)
955 self.assertEqual(m.readonly, expected_readonly)
956 self.assertEqual(m.ndim, ndim)
957 self.assertEqual(m.shape, tuple(shape))
958 if not (sliced and suboffsets):
959 self.assertEqual(m.strides, tuple(strides))
960 self.assertEqual(m.suboffsets, tuple(suboffsets))
961
962 n = 1 if ndim == 0 else len(lst)
963 self.assertEqual(len(m), n)
964
965 rep = result.tolist() if fmt else result.tobytes()
966 self.assertEqual(rep, lst)
967 self.assertEqual(m, result)
968
969 check_memoryview(m)
970 with m.toreadonly() as mm:
971 check_memoryview(mm, expected_readonly=True)
972 m.tobytes() # Releasing mm didn't release m
973
974 def verify_getbuf(self, orig_ex, ex, req, sliced=False):
975 def match(req, flag):
976 return ((req&flag) == flag)
977
978 if (# writable request to read-only exporter
979 (ex.readonly and match(req, PyBUF_WRITABLE)) or
980 # cannot match explicit contiguity request
981 (match(req, PyBUF_C_CONTIGUOUS) and not ex.c_contiguous) or
982 (match(req, PyBUF_F_CONTIGUOUS) and not ex.f_contiguous) or
983 (match(req, PyBUF_ANY_CONTIGUOUS) and not ex.contiguous) or
984 # buffer needs suboffsets
985 (not match(req, PyBUF_INDIRECT) and ex.suboffsets) or
986 # buffer without strides must be C-contiguous
987 (not match(req, PyBUF_STRIDES) and not ex.c_contiguous) or
988 # PyBUF_SIMPLE|PyBUF_FORMAT and PyBUF_WRITABLE|PyBUF_FORMAT
989 (not match(req, PyBUF_ND) and match(req, PyBUF_FORMAT))):
990
991 self.assertRaises(BufferError, ndarray, ex, getbuf=req)
992 return
993
994 if isinstance(ex, ndarray) or is_memoryview_format(ex.format):
995 lst = ex.tolist()
996 else:
997 nd = ndarray(ex, getbuf=PyBUF_FULL_RO)
998 lst = nd.tolist()
999
1000 # The consumer may have requested default values or a NULL format.
1001 ro = False if match(req, PyBUF_WRITABLE) else ex.readonly
1002 fmt = ex.format
1003 itemsize = ex.itemsize
1004 ndim = ex.ndim
1005 if not match(req, PyBUF_FORMAT):
1006 # itemsize refers to the original itemsize before the cast.
1007 # The equality product(shape) * itemsize = len still holds.
1008 # The equality calcsize(format) = itemsize does _not_ hold.
1009 fmt = ''
1010 lst = orig_ex.tobytes() # Issue 12834
1011 if not match(req, PyBUF_ND):
1012 ndim = 1
1013 shape = orig_ex.shape if match(req, PyBUF_ND) else ()
1014 strides = orig_ex.strides if match(req, PyBUF_STRIDES) else ()
1015
1016 nd = ndarray(ex, getbuf=req)
1017 self.verify(nd, obj=ex,
1018 itemsize=itemsize, fmt=fmt, readonly=ro,
1019 ndim=ndim, shape=shape, strides=strides,
1020 lst=lst, sliced=sliced)
1021
1022 @support.requires_resource('cpu')
1023 def test_ndarray_getbuf(self):
1024 requests = (
1025 # distinct flags
1026 PyBUF_INDIRECT, PyBUF_STRIDES, PyBUF_ND, PyBUF_SIMPLE,
1027 PyBUF_C_CONTIGUOUS, PyBUF_F_CONTIGUOUS, PyBUF_ANY_CONTIGUOUS,
1028 # compound requests
1029 PyBUF_FULL, PyBUF_FULL_RO,
1030 PyBUF_RECORDS, PyBUF_RECORDS_RO,
1031 PyBUF_STRIDED, PyBUF_STRIDED_RO,
1032 PyBUF_CONTIG, PyBUF_CONTIG_RO,
1033 )
1034 # items and format
1035 items_fmt = (
1036 ([True if x % 2 else False for x in range(12)], '?'),
1037 ([1,2,3,4,5,6,7,8,9,10,11,12], 'b'),
1038 ([1,2,3,4,5,6,7,8,9,10,11,12], 'B'),
1039 ([(2**31-x) if x % 2 else (-2**31+x) for x in range(12)], 'l')
1040 )
1041 # shape, strides, offset
1042 structure = (
1043 ([], [], 0),
1044 ([1,3,1], [], 0),
1045 ([12], [], 0),
1046 ([12], [-1], 11),
1047 ([6], [2], 0),
1048 ([6], [-2], 11),
1049 ([3, 4], [], 0),
1050 ([3, 4], [-4, -1], 11),
1051 ([2, 2], [4, 1], 4),
1052 ([2, 2], [-4, -1], 8)
1053 )
1054 # ndarray creation flags
1055 ndflags = (
1056 0, ND_WRITABLE, ND_FORTRAN, ND_FORTRAN|ND_WRITABLE,
1057 ND_PIL, ND_PIL|ND_WRITABLE
1058 )
1059 # flags that can actually be used as flags
1060 real_flags = (0, PyBUF_WRITABLE, PyBUF_FORMAT,
1061 PyBUF_WRITABLE|PyBUF_FORMAT)
1062
1063 for items, fmt in items_fmt:
1064 itemsize = struct.calcsize(fmt)
1065 for shape, strides, offset in structure:
1066 strides = [v * itemsize for v in strides]
1067 offset *= itemsize
1068 for flags in ndflags:
1069
1070 if strides and (flags&ND_FORTRAN):
1071 continue
1072 if not shape and (flags&ND_PIL):
1073 continue
1074
1075 _items = items if shape else items[0]
1076 ex1 = ndarray(_items, format=fmt, flags=flags,
1077 shape=shape, strides=strides, offset=offset)
1078 ex2 = ex1[::-2] if shape else None
1079
1080 m1 = memoryview(ex1)
1081 if ex2:
1082 m2 = memoryview(ex2)
1083 if ex1.ndim == 0 or (ex1.ndim == 1 and shape and strides):
1084 self.assertEqual(m1, ex1)
1085 if ex2 and ex2.ndim == 1 and shape and strides:
1086 self.assertEqual(m2, ex2)
1087
1088 for req in requests:
1089 for bits in real_flags:
1090 self.verify_getbuf(ex1, ex1, req|bits)
1091 self.verify_getbuf(ex1, m1, req|bits)
1092 if ex2:
1093 self.verify_getbuf(ex2, ex2, req|bits,
1094 sliced=True)
1095 self.verify_getbuf(ex2, m2, req|bits,
1096 sliced=True)
1097
1098 items = [1,2,3,4,5,6,7,8,9,10,11,12]
1099
1100 # ND_GETBUF_FAIL
1101 ex = ndarray(items, shape=[12], flags=ND_GETBUF_FAIL)
1102 self.assertRaises(BufferError, ndarray, ex)
1103
1104 # Request complex structure from a simple exporter. In this
1105 # particular case the test object is not PEP-3118 compliant.
1106 base = ndarray([9], [1])
1107 ex = ndarray(base, getbuf=PyBUF_SIMPLE)
1108 self.assertRaises(BufferError, ndarray, ex, getbuf=PyBUF_WRITABLE)
1109 self.assertRaises(BufferError, ndarray, ex, getbuf=PyBUF_ND)
1110 self.assertRaises(BufferError, ndarray, ex, getbuf=PyBUF_STRIDES)
1111 self.assertRaises(BufferError, ndarray, ex, getbuf=PyBUF_C_CONTIGUOUS)
1112 self.assertRaises(BufferError, ndarray, ex, getbuf=PyBUF_F_CONTIGUOUS)
1113 self.assertRaises(BufferError, ndarray, ex, getbuf=PyBUF_ANY_CONTIGUOUS)
1114 nd = ndarray(ex, getbuf=PyBUF_SIMPLE)
1115
1116 # Issue #22445: New precise contiguity definition.
1117 for shape in [1,12,1], [7,0,7]:
1118 for order in 0, ND_FORTRAN:
1119 ex = ndarray(items, shape=shape, flags=order|ND_WRITABLE)
1120 self.assertTrue(is_contiguous(ex, 'F'))
1121 self.assertTrue(is_contiguous(ex, 'C'))
1122
1123 for flags in requests:
1124 nd = ndarray(ex, getbuf=flags)
1125 self.assertTrue(is_contiguous(nd, 'F'))
1126 self.assertTrue(is_contiguous(nd, 'C'))
1127
1128 def test_ndarray_exceptions(self):
1129 nd = ndarray([9], [1])
1130 ndm = ndarray([9], [1], flags=ND_VAREXPORT)
1131
1132 # Initialization of a new ndarray or mutation of an existing array.
1133 for c in (ndarray, nd.push, ndm.push):
1134 # Invalid types.
1135 self.assertRaises(TypeError, c, {1,2,3})
1136 self.assertRaises(TypeError, c, [1,2,'3'])
1137 self.assertRaises(TypeError, c, [1,2,(3,4)])
1138 self.assertRaises(TypeError, c, [1,2,3], shape={3})
1139 self.assertRaises(TypeError, c, [1,2,3], shape=[3], strides={1})
1140 self.assertRaises(TypeError, c, [1,2,3], shape=[3], offset=[])
1141 self.assertRaises(TypeError, c, [1], shape=[1], format={})
1142 self.assertRaises(TypeError, c, [1], shape=[1], flags={})
1143 self.assertRaises(TypeError, c, [1], shape=[1], getbuf={})
1144
1145 # ND_FORTRAN flag is only valid without strides.
1146 self.assertRaises(TypeError, c, [1], shape=[1], strides=[1],
1147 flags=ND_FORTRAN)
1148
1149 # ND_PIL flag is only valid with ndim > 0.
1150 self.assertRaises(TypeError, c, [1], shape=[], flags=ND_PIL)
1151
1152 # Invalid items.
1153 self.assertRaises(ValueError, c, [], shape=[1])
1154 self.assertRaises(ValueError, c, ['XXX'], shape=[1], format="L")
1155 # Invalid combination of items and format.
1156 self.assertRaises(struct.error, c, [1000], shape=[1], format="B")
1157 self.assertRaises(ValueError, c, [1,(2,3)], shape=[2], format="B")
1158 self.assertRaises(ValueError, c, [1,2,3], shape=[3], format="QL")
1159
1160 # Invalid ndim.
1161 n = ND_MAX_NDIM+1
1162 self.assertRaises(ValueError, c, [1]*n, shape=[1]*n)
1163
1164 # Invalid shape.
1165 self.assertRaises(ValueError, c, [1], shape=[-1])
1166 self.assertRaises(ValueError, c, [1,2,3], shape=['3'])
1167 self.assertRaises(OverflowError, c, [1], shape=[2**128])
1168 # prod(shape) * itemsize != len(items)
1169 self.assertRaises(ValueError, c, [1,2,3,4,5], shape=[2,2], offset=3)
1170
1171 # Invalid strides.
1172 self.assertRaises(ValueError, c, [1,2,3], shape=[3], strides=['1'])
1173 self.assertRaises(OverflowError, c, [1], shape=[1],
1174 strides=[2**128])
1175
1176 # Invalid combination of strides and shape.
1177 self.assertRaises(ValueError, c, [1,2], shape=[2,1], strides=[1])
1178 # Invalid combination of strides and format.
1179 self.assertRaises(ValueError, c, [1,2,3,4], shape=[2], strides=[3],
1180 format="L")
1181
1182 # Invalid offset.
1183 self.assertRaises(ValueError, c, [1,2,3], shape=[3], offset=4)
1184 self.assertRaises(ValueError, c, [1,2,3], shape=[1], offset=3,
1185 format="L")
1186
1187 # Invalid format.
1188 self.assertRaises(ValueError, c, [1,2,3], shape=[3], format="")
1189 self.assertRaises(struct.error, c, [(1,2,3)], shape=[1],
1190 format="@#$")
1191
1192 # Striding out of the memory bounds.
1193 items = [1,2,3,4,5,6,7,8,9,10]
1194 self.assertRaises(ValueError, c, items, shape=[2,3],
1195 strides=[-3, -2], offset=5)
1196
1197 # Constructing consumer: format argument invalid.
1198 self.assertRaises(TypeError, c, bytearray(), format="Q")
1199
1200 # Constructing original base object: getbuf argument invalid.
1201 self.assertRaises(TypeError, c, [1], shape=[1], getbuf=PyBUF_FULL)
1202
1203 # Shape argument is mandatory for original base objects.
1204 self.assertRaises(TypeError, c, [1])
1205
1206
1207 # PyBUF_WRITABLE request to read-only provider.
1208 self.assertRaises(BufferError, ndarray, b'123', getbuf=PyBUF_WRITABLE)
1209
1210 # ND_VAREXPORT can only be specified during construction.
1211 nd = ndarray([9], [1], flags=ND_VAREXPORT)
1212 self.assertRaises(ValueError, nd.push, [1], [1], flags=ND_VAREXPORT)
1213
1214 # Invalid operation for consumers: push/pop
1215 nd = ndarray(b'123')
1216 self.assertRaises(BufferError, nd.push, [1], [1])
1217 self.assertRaises(BufferError, nd.pop)
1218
1219 # ND_VAREXPORT not set: push/pop fail with exported buffers
1220 nd = ndarray([9], [1])
1221 nd.push([1], [1])
1222 m = memoryview(nd)
1223 self.assertRaises(BufferError, nd.push, [1], [1])
1224 self.assertRaises(BufferError, nd.pop)
1225 m.release()
1226 nd.pop()
1227
1228 # Single remaining buffer: pop fails
1229 self.assertRaises(BufferError, nd.pop)
1230 del nd
1231
1232 # get_pointer()
1233 self.assertRaises(TypeError, get_pointer, {}, [1,2,3])
1234 self.assertRaises(TypeError, get_pointer, b'123', {})
1235
1236 nd = ndarray(list(range(100)), shape=[1]*100)
1237 self.assertRaises(ValueError, get_pointer, nd, [5])
1238
1239 nd = ndarray(list(range(12)), shape=[3,4])
1240 self.assertRaises(ValueError, get_pointer, nd, [2,3,4])
1241 self.assertRaises(ValueError, get_pointer, nd, [3,3])
1242 self.assertRaises(ValueError, get_pointer, nd, [-3,3])
1243 self.assertRaises(OverflowError, get_pointer, nd, [1<<64,3])
1244
1245 # tolist() needs format
1246 ex = ndarray([1,2,3], shape=[3], format='L')
1247 nd = ndarray(ex, getbuf=PyBUF_SIMPLE)
1248 self.assertRaises(ValueError, nd.tolist)
1249
1250 # memoryview_from_buffer()
1251 ex1 = ndarray([1,2,3], shape=[3], format='L')
1252 ex2 = ndarray(ex1)
1253 nd = ndarray(ex2)
1254 self.assertRaises(TypeError, nd.memoryview_from_buffer)
1255
1256 nd = ndarray([(1,)*200], shape=[1], format='L'*200)
1257 self.assertRaises(TypeError, nd.memoryview_from_buffer)
1258
1259 n = ND_MAX_NDIM
1260 nd = ndarray(list(range(n)), shape=[1]*n)
1261 self.assertRaises(ValueError, nd.memoryview_from_buffer)
1262
1263 # get_contiguous()
1264 nd = ndarray([1], shape=[1])
1265 self.assertRaises(TypeError, get_contiguous, 1, 2, 3, 4, 5)
1266 self.assertRaises(TypeError, get_contiguous, nd, "xyz", 'C')
1267 self.assertRaises(OverflowError, get_contiguous, nd, 2**64, 'C')
1268 self.assertRaises(TypeError, get_contiguous, nd, PyBUF_READ, 961)
1269 self.assertRaises(UnicodeEncodeError, get_contiguous, nd, PyBUF_READ,
1270 '\u2007')
1271 self.assertRaises(ValueError, get_contiguous, nd, PyBUF_READ, 'Z')
1272 self.assertRaises(ValueError, get_contiguous, nd, 255, 'A')
1273
1274 # cmp_contig()
1275 nd = ndarray([1], shape=[1])
1276 self.assertRaises(TypeError, cmp_contig, 1, 2, 3, 4, 5)
1277 self.assertRaises(TypeError, cmp_contig, {}, nd)
1278 self.assertRaises(TypeError, cmp_contig, nd, {})
1279
1280 # is_contiguous()
1281 nd = ndarray([1], shape=[1])
1282 self.assertRaises(TypeError, is_contiguous, 1, 2, 3, 4, 5)
1283 self.assertRaises(TypeError, is_contiguous, {}, 'A')
1284 self.assertRaises(TypeError, is_contiguous, nd, 201)
1285
1286 def test_ndarray_linked_list(self):
1287 for perm in permutations(range(5)):
1288 m = [0]*5
1289 nd = ndarray([1,2,3], shape=[3], flags=ND_VAREXPORT)
1290 m[0] = memoryview(nd)
1291
1292 for i in range(1, 5):
1293 nd.push([1,2,3], shape=[3])
1294 m[i] = memoryview(nd)
1295
1296 for i in range(5):
1297 m[perm[i]].release()
1298
1299 self.assertRaises(BufferError, nd.pop)
1300 del nd
1301
1302 def test_ndarray_format_scalar(self):
1303 # ndim = 0: scalar
1304 for fmt, scalar, _ in iter_format(0):
1305 itemsize = struct.calcsize(fmt)
1306 nd = ndarray(scalar, shape=(), format=fmt)
1307 self.verify(nd, obj=None,
1308 itemsize=itemsize, fmt=fmt, readonly=True,
1309 ndim=0, shape=(), strides=(),
1310 lst=scalar)
1311
1312 def test_ndarray_format_shape(self):
1313 # ndim = 1, shape = [n]
1314 nitems = randrange(1, 10)
1315 for fmt, items, _ in iter_format(nitems):
1316 itemsize = struct.calcsize(fmt)
1317 for flags in (0, ND_PIL):
1318 nd = ndarray(items, shape=[nitems], format=fmt, flags=flags)
1319 self.verify(nd, obj=None,
1320 itemsize=itemsize, fmt=fmt, readonly=True,
1321 ndim=1, shape=(nitems,), strides=(itemsize,),
1322 lst=items)
1323
1324 def test_ndarray_format_strides(self):
1325 # ndim = 1, strides
1326 nitems = randrange(1, 30)
1327 for fmt, items, _ in iter_format(nitems):
1328 itemsize = struct.calcsize(fmt)
1329 for step in range(-5, 5):
1330 if step == 0:
1331 continue
1332
1333 shape = [len(items[::step])]
1334 strides = [step*itemsize]
1335 offset = itemsize*(nitems-1) if step < 0 else 0
1336
1337 for flags in (0, ND_PIL):
1338 nd = ndarray(items, shape=shape, strides=strides,
1339 format=fmt, offset=offset, flags=flags)
1340 self.verify(nd, obj=None,
1341 itemsize=itemsize, fmt=fmt, readonly=True,
1342 ndim=1, shape=shape, strides=strides,
1343 lst=items[::step])
1344
1345 def test_ndarray_fortran(self):
1346 items = [1,2,3,4,5,6,7,8,9,10,11,12]
1347 ex = ndarray(items, shape=(3, 4), strides=(1, 3))
1348 nd = ndarray(ex, getbuf=PyBUF_F_CONTIGUOUS|PyBUF_FORMAT)
1349 self.assertEqual(nd.tolist(), farray(items, (3, 4)))
1350
1351 def test_ndarray_multidim(self):
1352 for ndim in range(5):
1353 shape_t = [randrange(2, 10) for _ in range(ndim)]
1354 nitems = prod(shape_t)
1355 for shape in permutations(shape_t):
1356
1357 fmt, items, _ = randitems(nitems)
1358 itemsize = struct.calcsize(fmt)
1359
1360 for flags in (0, ND_PIL):
1361 if ndim == 0 and flags == ND_PIL:
1362 continue
1363
1364 # C array
1365 nd = ndarray(items, shape=shape, format=fmt, flags=flags)
1366
1367 strides = strides_from_shape(ndim, shape, itemsize, 'C')
1368 lst = carray(items, shape)
1369 self.verify(nd, obj=None,
1370 itemsize=itemsize, fmt=fmt, readonly=True,
1371 ndim=ndim, shape=shape, strides=strides,
1372 lst=lst)
1373
1374 if is_memoryview_format(fmt):
1375 # memoryview: reconstruct strides
1376 ex = ndarray(items, shape=shape, format=fmt)
1377 nd = ndarray(ex, getbuf=PyBUF_CONTIG_RO|PyBUF_FORMAT)
1378 self.assertTrue(nd.strides == ())
1379 mv = nd.memoryview_from_buffer()
1380 self.verify(mv, obj=None,
1381 itemsize=itemsize, fmt=fmt, readonly=True,
1382 ndim=ndim, shape=shape, strides=strides,
1383 lst=lst)
1384
1385 # Fortran array
1386 nd = ndarray(items, shape=shape, format=fmt,
1387 flags=flags|ND_FORTRAN)
1388
1389 strides = strides_from_shape(ndim, shape, itemsize, 'F')
1390 lst = farray(items, shape)
1391 self.verify(nd, obj=None,
1392 itemsize=itemsize, fmt=fmt, readonly=True,
1393 ndim=ndim, shape=shape, strides=strides,
1394 lst=lst)
1395
1396 def test_ndarray_index_invalid(self):
1397 # not writable
1398 nd = ndarray([1], shape=[1])
1399 self.assertRaises(TypeError, nd.__setitem__, 1, 8)
1400 mv = memoryview(nd)
1401 self.assertEqual(mv, nd)
1402 self.assertRaises(TypeError, mv.__setitem__, 1, 8)
1403
1404 # cannot be deleted
1405 nd = ndarray([1], shape=[1], flags=ND_WRITABLE)
1406 self.assertRaises(TypeError, nd.__delitem__, 1)
1407 mv = memoryview(nd)
1408 self.assertEqual(mv, nd)
1409 self.assertRaises(TypeError, mv.__delitem__, 1)
1410
1411 # overflow
1412 nd = ndarray([1], shape=[1], flags=ND_WRITABLE)
1413 self.assertRaises(OverflowError, nd.__getitem__, 1<<64)
1414 self.assertRaises(OverflowError, nd.__setitem__, 1<<64, 8)
1415 mv = memoryview(nd)
1416 self.assertEqual(mv, nd)
1417 self.assertRaises(IndexError, mv.__getitem__, 1<<64)
1418 self.assertRaises(IndexError, mv.__setitem__, 1<<64, 8)
1419
1420 # format
1421 items = [1,2,3,4,5,6,7,8]
1422 nd = ndarray(items, shape=[len(items)], format="B", flags=ND_WRITABLE)
1423 self.assertRaises(struct.error, nd.__setitem__, 2, 300)
1424 self.assertRaises(ValueError, nd.__setitem__, 1, (100, 200))
1425 mv = memoryview(nd)
1426 self.assertEqual(mv, nd)
1427 self.assertRaises(ValueError, mv.__setitem__, 2, 300)
1428 self.assertRaises(TypeError, mv.__setitem__, 1, (100, 200))
1429
1430 items = [(1,2), (3,4), (5,6)]
1431 nd = ndarray(items, shape=[len(items)], format="LQ", flags=ND_WRITABLE)
1432 self.assertRaises(ValueError, nd.__setitem__, 2, 300)
1433 self.assertRaises(struct.error, nd.__setitem__, 1, (b'\x001', 200))
1434
1435 def test_ndarray_index_scalar(self):
1436 # scalar
1437 nd = ndarray(1, shape=(), flags=ND_WRITABLE)
1438 mv = memoryview(nd)
1439 self.assertEqual(mv, nd)
1440
1441 x = nd[()]; self.assertEqual(x, 1)
1442 x = nd[...]; self.assertEqual(x.tolist(), nd.tolist())
1443
1444 x = mv[()]; self.assertEqual(x, 1)
1445 x = mv[...]; self.assertEqual(x.tolist(), nd.tolist())
1446
1447 self.assertRaises(TypeError, nd.__getitem__, 0)
1448 self.assertRaises(TypeError, mv.__getitem__, 0)
1449 self.assertRaises(TypeError, nd.__setitem__, 0, 8)
1450 self.assertRaises(TypeError, mv.__setitem__, 0, 8)
1451
1452 self.assertEqual(nd.tolist(), 1)
1453 self.assertEqual(mv.tolist(), 1)
1454
1455 nd[()] = 9; self.assertEqual(nd.tolist(), 9)
1456 mv[()] = 9; self.assertEqual(mv.tolist(), 9)
1457
1458 nd[...] = 5; self.assertEqual(nd.tolist(), 5)
1459 mv[...] = 5; self.assertEqual(mv.tolist(), 5)
1460
1461 def test_ndarray_index_null_strides(self):
1462 ex = ndarray(list(range(2*4)), shape=[2, 4], flags=ND_WRITABLE)
1463 nd = ndarray(ex, getbuf=PyBUF_CONTIG)
1464
1465 # Sub-views are only possible for full exporters.
1466 self.assertRaises(BufferError, nd.__getitem__, 1)
1467 # Same for slices.
1468 self.assertRaises(BufferError, nd.__getitem__, slice(3,5,1))
1469
1470 def test_ndarray_index_getitem_single(self):
1471 # getitem
1472 for fmt, items, _ in iter_format(5):
1473 nd = ndarray(items, shape=[5], format=fmt)
1474 for i in range(-5, 5):
1475 self.assertEqual(nd[i], items[i])
1476
1477 self.assertRaises(IndexError, nd.__getitem__, -6)
1478 self.assertRaises(IndexError, nd.__getitem__, 5)
1479
1480 if is_memoryview_format(fmt):
1481 mv = memoryview(nd)
1482 self.assertEqual(mv, nd)
1483 for i in range(-5, 5):
1484 self.assertEqual(mv[i], items[i])
1485
1486 self.assertRaises(IndexError, mv.__getitem__, -6)
1487 self.assertRaises(IndexError, mv.__getitem__, 5)
1488
1489 # getitem with null strides
1490 for fmt, items, _ in iter_format(5):
1491 ex = ndarray(items, shape=[5], flags=ND_WRITABLE, format=fmt)
1492 nd = ndarray(ex, getbuf=PyBUF_CONTIG|PyBUF_FORMAT)
1493
1494 for i in range(-5, 5):
1495 self.assertEqual(nd[i], items[i])
1496
1497 if is_memoryview_format(fmt):
1498 mv = nd.memoryview_from_buffer()
1499 self.assertIs(mv.__eq__(nd), NotImplemented)
1500 for i in range(-5, 5):
1501 self.assertEqual(mv[i], items[i])
1502
1503 # getitem with null format
1504 items = [1,2,3,4,5]
1505 ex = ndarray(items, shape=[5])
1506 nd = ndarray(ex, getbuf=PyBUF_CONTIG_RO)
1507 for i in range(-5, 5):
1508 self.assertEqual(nd[i], items[i])
1509
1510 # getitem with null shape/strides/format
1511 items = [1,2,3,4,5]
1512 ex = ndarray(items, shape=[5])
1513 nd = ndarray(ex, getbuf=PyBUF_SIMPLE)
1514
1515 for i in range(-5, 5):
1516 self.assertEqual(nd[i], items[i])
1517
1518 def test_ndarray_index_setitem_single(self):
1519 # assign single value
1520 for fmt, items, single_item in iter_format(5):
1521 nd = ndarray(items, shape=[5], format=fmt, flags=ND_WRITABLE)
1522 for i in range(5):
1523 items[i] = single_item
1524 nd[i] = single_item
1525 self.assertEqual(nd.tolist(), items)
1526
1527 self.assertRaises(IndexError, nd.__setitem__, -6, single_item)
1528 self.assertRaises(IndexError, nd.__setitem__, 5, single_item)
1529
1530 if not is_memoryview_format(fmt):
1531 continue
1532
1533 nd = ndarray(items, shape=[5], format=fmt, flags=ND_WRITABLE)
1534 mv = memoryview(nd)
1535 self.assertEqual(mv, nd)
1536 for i in range(5):
1537 items[i] = single_item
1538 mv[i] = single_item
1539 self.assertEqual(mv.tolist(), items)
1540
1541 self.assertRaises(IndexError, mv.__setitem__, -6, single_item)
1542 self.assertRaises(IndexError, mv.__setitem__, 5, single_item)
1543
1544
1545 # assign single value: lobject = robject
1546 for fmt, items, single_item in iter_format(5):
1547 nd = ndarray(items, shape=[5], format=fmt, flags=ND_WRITABLE)
1548 for i in range(-5, 4):
1549 items[i] = items[i+1]
1550 nd[i] = nd[i+1]
1551 self.assertEqual(nd.tolist(), items)
1552
1553 if not is_memoryview_format(fmt):
1554 continue
1555
1556 nd = ndarray(items, shape=[5], format=fmt, flags=ND_WRITABLE)
1557 mv = memoryview(nd)
1558 self.assertEqual(mv, nd)
1559 for i in range(-5, 4):
1560 items[i] = items[i+1]
1561 mv[i] = mv[i+1]
1562 self.assertEqual(mv.tolist(), items)
1563
1564 def test_ndarray_index_getitem_multidim(self):
1565 shape_t = (2, 3, 5)
1566 nitems = prod(shape_t)
1567 for shape in permutations(shape_t):
1568
1569 fmt, items, _ = randitems(nitems)
1570
1571 for flags in (0, ND_PIL):
1572 # C array
1573 nd = ndarray(items, shape=shape, format=fmt, flags=flags)
1574 lst = carray(items, shape)
1575
1576 for i in range(-shape[0], shape[0]):
1577 self.assertEqual(lst[i], nd[i].tolist())
1578 for j in range(-shape[1], shape[1]):
1579 self.assertEqual(lst[i][j], nd[i][j].tolist())
1580 for k in range(-shape[2], shape[2]):
1581 self.assertEqual(lst[i][j][k], nd[i][j][k])
1582
1583 # Fortran array
1584 nd = ndarray(items, shape=shape, format=fmt,
1585 flags=flags|ND_FORTRAN)
1586 lst = farray(items, shape)
1587
1588 for i in range(-shape[0], shape[0]):
1589 self.assertEqual(lst[i], nd[i].tolist())
1590 for j in range(-shape[1], shape[1]):
1591 self.assertEqual(lst[i][j], nd[i][j].tolist())
1592 for k in range(shape[2], shape[2]):
1593 self.assertEqual(lst[i][j][k], nd[i][j][k])
1594
1595 def test_ndarray_sequence(self):
1596 nd = ndarray(1, shape=())
1597 self.assertRaises(TypeError, eval, "1 in nd", locals())
1598 mv = memoryview(nd)
1599 self.assertEqual(mv, nd)
1600 self.assertRaises(TypeError, eval, "1 in mv", locals())
1601
1602 for fmt, items, _ in iter_format(5):
1603 nd = ndarray(items, shape=[5], format=fmt)
1604 for i, v in enumerate(nd):
1605 self.assertEqual(v, items[i])
1606 self.assertTrue(v in nd)
1607
1608 if is_memoryview_format(fmt):
1609 mv = memoryview(nd)
1610 for i, v in enumerate(mv):
1611 self.assertEqual(v, items[i])
1612 self.assertTrue(v in mv)
1613
1614 def test_ndarray_slice_invalid(self):
1615 items = [1,2,3,4,5,6,7,8]
1616
1617 # rvalue is not an exporter
1618 xl = ndarray(items, shape=[8], flags=ND_WRITABLE)
1619 ml = memoryview(xl)
1620 self.assertRaises(TypeError, xl.__setitem__, slice(0,8,1), items)
1621 self.assertRaises(TypeError, ml.__setitem__, slice(0,8,1), items)
1622
1623 # rvalue is not a full exporter
1624 xl = ndarray(items, shape=[8], flags=ND_WRITABLE)
1625 ex = ndarray(items, shape=[8], flags=ND_WRITABLE)
1626 xr = ndarray(ex, getbuf=PyBUF_ND)
1627 self.assertRaises(BufferError, xl.__setitem__, slice(0,8,1), xr)
1628
1629 # zero step
1630 nd = ndarray(items, shape=[8], format="L", flags=ND_WRITABLE)
1631 mv = memoryview(nd)
1632 self.assertRaises(ValueError, nd.__getitem__, slice(0,1,0))
1633 self.assertRaises(ValueError, mv.__getitem__, slice(0,1,0))
1634
1635 nd = ndarray(items, shape=[2,4], format="L", flags=ND_WRITABLE)
1636 mv = memoryview(nd)
1637
1638 self.assertRaises(ValueError, nd.__getitem__,
1639 (slice(0,1,1), slice(0,1,0)))
1640 self.assertRaises(ValueError, nd.__getitem__,
1641 (slice(0,1,0), slice(0,1,1)))
1642 self.assertRaises(TypeError, nd.__getitem__, "@%$")
1643 self.assertRaises(TypeError, nd.__getitem__, ("@%$", slice(0,1,1)))
1644 self.assertRaises(TypeError, nd.__getitem__, (slice(0,1,1), {}))
1645
1646 # memoryview: not implemented
1647 self.assertRaises(NotImplementedError, mv.__getitem__,
1648 (slice(0,1,1), slice(0,1,0)))
1649 self.assertRaises(TypeError, mv.__getitem__, "@%$")
1650
1651 # differing format
1652 xl = ndarray(items, shape=[8], format="B", flags=ND_WRITABLE)
1653 xr = ndarray(items, shape=[8], format="b")
1654 ml = memoryview(xl)
1655 mr = memoryview(xr)
1656 self.assertRaises(ValueError, xl.__setitem__, slice(0,1,1), xr[7:8])
1657 self.assertEqual(xl.tolist(), items)
1658 self.assertRaises(ValueError, ml.__setitem__, slice(0,1,1), mr[7:8])
1659 self.assertEqual(ml.tolist(), items)
1660
1661 # differing itemsize
1662 xl = ndarray(items, shape=[8], format="B", flags=ND_WRITABLE)
1663 yr = ndarray(items, shape=[8], format="L")
1664 ml = memoryview(xl)
1665 mr = memoryview(xr)
1666 self.assertRaises(ValueError, xl.__setitem__, slice(0,1,1), xr[7:8])
1667 self.assertEqual(xl.tolist(), items)
1668 self.assertRaises(ValueError, ml.__setitem__, slice(0,1,1), mr[7:8])
1669 self.assertEqual(ml.tolist(), items)
1670
1671 # differing ndim
1672 xl = ndarray(items, shape=[2, 4], format="b", flags=ND_WRITABLE)
1673 xr = ndarray(items, shape=[8], format="b")
1674 ml = memoryview(xl)
1675 mr = memoryview(xr)
1676 self.assertRaises(ValueError, xl.__setitem__, slice(0,1,1), xr[7:8])
1677 self.assertEqual(xl.tolist(), [[1,2,3,4], [5,6,7,8]])
1678 self.assertRaises(NotImplementedError, ml.__setitem__, slice(0,1,1),
1679 mr[7:8])
1680
1681 # differing shape
1682 xl = ndarray(items, shape=[8], format="b", flags=ND_WRITABLE)
1683 xr = ndarray(items, shape=[8], format="b")
1684 ml = memoryview(xl)
1685 mr = memoryview(xr)
1686 self.assertRaises(ValueError, xl.__setitem__, slice(0,2,1), xr[7:8])
1687 self.assertEqual(xl.tolist(), items)
1688 self.assertRaises(ValueError, ml.__setitem__, slice(0,2,1), mr[7:8])
1689 self.assertEqual(ml.tolist(), items)
1690
1691 # _testbuffer.c module functions
1692 self.assertRaises(TypeError, slice_indices, slice(0,1,2), {})
1693 self.assertRaises(TypeError, slice_indices, "###########", 1)
1694 self.assertRaises(ValueError, slice_indices, slice(0,1,0), 4)
1695
1696 x = ndarray(items, shape=[8], format="b", flags=ND_PIL)
1697 self.assertRaises(TypeError, x.add_suboffsets)
1698
1699 ex = ndarray(items, shape=[8], format="B")
1700 x = ndarray(ex, getbuf=PyBUF_SIMPLE)
1701 self.assertRaises(TypeError, x.add_suboffsets)
1702
1703 def test_ndarray_slice_zero_shape(self):
1704 items = [1,2,3,4,5,6,7,8,9,10,11,12]
1705
1706 x = ndarray(items, shape=[12], format="L", flags=ND_WRITABLE)
1707 y = ndarray(items, shape=[12], format="L")
1708 x[4:4] = y[9:9]
1709 self.assertEqual(x.tolist(), items)
1710
1711 ml = memoryview(x)
1712 mr = memoryview(y)
1713 self.assertEqual(ml, x)
1714 self.assertEqual(ml, y)
1715 ml[4:4] = mr[9:9]
1716 self.assertEqual(ml.tolist(), items)
1717
1718 x = ndarray(items, shape=[3, 4], format="L", flags=ND_WRITABLE)
1719 y = ndarray(items, shape=[4, 3], format="L")
1720 x[1:2, 2:2] = y[1:2, 3:3]
1721 self.assertEqual(x.tolist(), carray(items, [3, 4]))
1722
1723 def test_ndarray_slice_multidim(self):
1724 shape_t = (2, 3, 5)
1725 ndim = len(shape_t)
1726 nitems = prod(shape_t)
1727 for shape in permutations(shape_t):
1728
1729 fmt, items, _ = randitems(nitems)
1730 itemsize = struct.calcsize(fmt)
1731
1732 for flags in (0, ND_PIL):
1733 nd = ndarray(items, shape=shape, format=fmt, flags=flags)
1734 lst = carray(items, shape)
1735
1736 for slices in rslices_ndim(ndim, shape):
1737
1738 listerr = None
1739 try:
1740 sliced = multislice(lst, slices)
1741 except Exception as e:
1742 listerr = e.__class__
1743
1744 nderr = None
1745 try:
1746 ndsliced = nd[slices]
1747 except Exception as e:
1748 nderr = e.__class__
1749
1750 if nderr or listerr:
1751 self.assertIs(nderr, listerr)
1752 else:
1753 self.assertEqual(ndsliced.tolist(), sliced)
1754
1755 def test_ndarray_slice_redundant_suboffsets(self):
1756 shape_t = (2, 3, 5, 2)
1757 ndim = len(shape_t)
1758 nitems = prod(shape_t)
1759 for shape in permutations(shape_t):
1760
1761 fmt, items, _ = randitems(nitems)
1762 itemsize = struct.calcsize(fmt)
1763
1764 nd = ndarray(items, shape=shape, format=fmt)
1765 nd.add_suboffsets()
1766 ex = ndarray(items, shape=shape, format=fmt)
1767 ex.add_suboffsets()
1768 mv = memoryview(ex)
1769 lst = carray(items, shape)
1770
1771 for slices in rslices_ndim(ndim, shape):
1772
1773 listerr = None
1774 try:
1775 sliced = multislice(lst, slices)
1776 except Exception as e:
1777 listerr = e.__class__
1778
1779 nderr = None
1780 try:
1781 ndsliced = nd[slices]
1782 except Exception as e:
1783 nderr = e.__class__
1784
1785 if nderr or listerr:
1786 self.assertIs(nderr, listerr)
1787 else:
1788 self.assertEqual(ndsliced.tolist(), sliced)
1789
1790 def test_ndarray_slice_assign_single(self):
1791 for fmt, items, _ in iter_format(5):
1792 for lslice in genslices(5):
1793 for rslice in genslices(5):
1794 for flags in (0, ND_PIL):
1795
1796 f = flags|ND_WRITABLE
1797 nd = ndarray(items, shape=[5], format=fmt, flags=f)
1798 ex = ndarray(items, shape=[5], format=fmt, flags=f)
1799 mv = memoryview(ex)
1800
1801 lsterr = None
1802 diff_structure = None
1803 lst = items[:]
1804 try:
1805 lval = lst[lslice]
1806 rval = lst[rslice]
1807 lst[lslice] = lst[rslice]
1808 diff_structure = len(lval) != len(rval)
1809 except Exception as e:
1810 lsterr = e.__class__
1811
1812 nderr = None
1813 try:
1814 nd[lslice] = nd[rslice]
1815 except Exception as e:
1816 nderr = e.__class__
1817
1818 if diff_structure: # ndarray cannot change shape
1819 self.assertIs(nderr, ValueError)
1820 else:
1821 self.assertEqual(nd.tolist(), lst)
1822 self.assertIs(nderr, lsterr)
1823
1824 if not is_memoryview_format(fmt):
1825 continue
1826
1827 mverr = None
1828 try:
1829 mv[lslice] = mv[rslice]
1830 except Exception as e:
1831 mverr = e.__class__
1832
1833 if diff_structure: # memoryview cannot change shape
1834 self.assertIs(mverr, ValueError)
1835 else:
1836 self.assertEqual(mv.tolist(), lst)
1837 self.assertEqual(mv, nd)
1838 self.assertIs(mverr, lsterr)
1839 self.verify(mv, obj=ex,
1840 itemsize=nd.itemsize, fmt=fmt, readonly=False,
1841 ndim=nd.ndim, shape=nd.shape, strides=nd.strides,
1842 lst=nd.tolist())
1843
1844 def test_ndarray_slice_assign_multidim(self):
1845 shape_t = (2, 3, 5)
1846 ndim = len(shape_t)
1847 nitems = prod(shape_t)
1848 for shape in permutations(shape_t):
1849
1850 fmt, items, _ = randitems(nitems)
1851
1852 for flags in (0, ND_PIL):
1853 for _ in range(ITERATIONS):
1854 lslices, rslices = randslice_from_shape(ndim, shape)
1855
1856 nd = ndarray(items, shape=shape, format=fmt,
1857 flags=flags|ND_WRITABLE)
1858 lst = carray(items, shape)
1859
1860 listerr = None
1861 try:
1862 result = multislice_assign(lst, lst, lslices, rslices)
1863 except Exception as e:
1864 listerr = e.__class__
1865
1866 nderr = None
1867 try:
1868 nd[lslices] = nd[rslices]
1869 except Exception as e:
1870 nderr = e.__class__
1871
1872 if nderr or listerr:
1873 self.assertIs(nderr, listerr)
1874 else:
1875 self.assertEqual(nd.tolist(), result)
1876
1877 def test_ndarray_random(self):
1878 # construction of valid arrays
1879 for _ in range(ITERATIONS):
1880 for fmt in fmtdict['@']:
1881 itemsize = struct.calcsize(fmt)
1882
1883 t = rand_structure(itemsize, True, maxdim=MAXDIM,
1884 maxshape=MAXSHAPE)
1885 self.assertTrue(verify_structure(*t))
1886 items = randitems_from_structure(fmt, t)
1887
1888 x = ndarray_from_structure(items, fmt, t)
1889 xlist = x.tolist()
1890
1891 mv = memoryview(x)
1892 if is_memoryview_format(fmt):
1893 mvlist = mv.tolist()
1894 self.assertEqual(mvlist, xlist)
1895
1896 if t[2] > 0:
1897 # ndim > 0: test against suboffsets representation.
1898 y = ndarray_from_structure(items, fmt, t, flags=ND_PIL)
1899 ylist = y.tolist()
1900 self.assertEqual(xlist, ylist)
1901
1902 mv = memoryview(y)
1903 if is_memoryview_format(fmt):
1904 self.assertEqual(mv, y)
1905 mvlist = mv.tolist()
1906 self.assertEqual(mvlist, ylist)
1907
1908 if numpy_array:
1909 shape = t[3]
1910 if 0 in shape:
1911 continue # http://projects.scipy.org/numpy/ticket/1910
1912 z = numpy_array_from_structure(items, fmt, t)
1913 self.verify(x, obj=None,
1914 itemsize=z.itemsize, fmt=fmt, readonly=False,
1915 ndim=z.ndim, shape=z.shape, strides=z.strides,
1916 lst=z.tolist())
1917
1918 def test_ndarray_random_invalid(self):
1919 # exceptions during construction of invalid arrays
1920 for _ in range(ITERATIONS):
1921 for fmt in fmtdict['@']:
1922 itemsize = struct.calcsize(fmt)
1923
1924 t = rand_structure(itemsize, False, maxdim=MAXDIM,
1925 maxshape=MAXSHAPE)
1926 self.assertFalse(verify_structure(*t))
1927 items = randitems_from_structure(fmt, t)
1928
1929 nderr = False
1930 try:
1931 x = ndarray_from_structure(items, fmt, t)
1932 except Exception as e:
1933 nderr = e.__class__
1934 self.assertTrue(nderr)
1935
1936 if numpy_array:
1937 numpy_err = False
1938 try:
1939 y = numpy_array_from_structure(items, fmt, t)
1940 except Exception as e:
1941 numpy_err = e.__class__
1942
1943 if 0: # http://projects.scipy.org/numpy/ticket/1910
1944 self.assertTrue(numpy_err)
1945
1946 def test_ndarray_random_slice_assign(self):
1947 # valid slice assignments
1948 for _ in range(ITERATIONS):
1949 for fmt in fmtdict['@']:
1950 itemsize = struct.calcsize(fmt)
1951
1952 lshape, rshape, lslices, rslices = \
1953 rand_aligned_slices(maxdim=MAXDIM, maxshape=MAXSHAPE)
1954 tl = rand_structure(itemsize, True, shape=lshape)
1955 tr = rand_structure(itemsize, True, shape=rshape)
1956 self.assertTrue(verify_structure(*tl))
1957 self.assertTrue(verify_structure(*tr))
1958 litems = randitems_from_structure(fmt, tl)
1959 ritems = randitems_from_structure(fmt, tr)
1960
1961 xl = ndarray_from_structure(litems, fmt, tl)
1962 xr = ndarray_from_structure(ritems, fmt, tr)
1963 xl[lslices] = xr[rslices]
1964 xllist = xl.tolist()
1965 xrlist = xr.tolist()
1966
1967 ml = memoryview(xl)
1968 mr = memoryview(xr)
1969 self.assertEqual(ml.tolist(), xllist)
1970 self.assertEqual(mr.tolist(), xrlist)
1971
1972 if tl[2] > 0 and tr[2] > 0:
1973 # ndim > 0: test against suboffsets representation.
1974 yl = ndarray_from_structure(litems, fmt, tl, flags=ND_PIL)
1975 yr = ndarray_from_structure(ritems, fmt, tr, flags=ND_PIL)
1976 yl[lslices] = yr[rslices]
1977 yllist = yl.tolist()
1978 yrlist = yr.tolist()
1979 self.assertEqual(xllist, yllist)
1980 self.assertEqual(xrlist, yrlist)
1981
1982 ml = memoryview(yl)
1983 mr = memoryview(yr)
1984 self.assertEqual(ml.tolist(), yllist)
1985 self.assertEqual(mr.tolist(), yrlist)
1986
1987 if numpy_array:
1988 if 0 in lshape or 0 in rshape:
1989 continue # http://projects.scipy.org/numpy/ticket/1910
1990
1991 zl = numpy_array_from_structure(litems, fmt, tl)
1992 zr = numpy_array_from_structure(ritems, fmt, tr)
1993 zl[lslices] = zr[rslices]
1994
1995 if not is_overlapping(tl) and not is_overlapping(tr):
1996 # Slice assignment of overlapping structures
1997 # is undefined in NumPy.
1998 self.verify(xl, obj=None,
1999 itemsize=zl.itemsize, fmt=fmt, readonly=False,
2000 ndim=zl.ndim, shape=zl.shape,
2001 strides=zl.strides, lst=zl.tolist())
2002
2003 self.verify(xr, obj=None,
2004 itemsize=zr.itemsize, fmt=fmt, readonly=False,
2005 ndim=zr.ndim, shape=zr.shape,
2006 strides=zr.strides, lst=zr.tolist())
2007
2008 def test_ndarray_re_export(self):
2009 items = [1,2,3,4,5,6,7,8,9,10,11,12]
2010
2011 nd = ndarray(items, shape=[3,4], flags=ND_PIL)
2012 ex = ndarray(nd)
2013
2014 self.assertTrue(ex.flags & ND_PIL)
2015 self.assertIs(ex.obj, nd)
2016 self.assertEqual(ex.suboffsets, (0, -1))
2017 self.assertFalse(ex.c_contiguous)
2018 self.assertFalse(ex.f_contiguous)
2019 self.assertFalse(ex.contiguous)
2020
2021 def test_ndarray_zero_shape(self):
2022 # zeros in shape
2023 for flags in (0, ND_PIL):
2024 nd = ndarray([1,2,3], shape=[0], flags=flags)
2025 mv = memoryview(nd)
2026 self.assertEqual(mv, nd)
2027 self.assertEqual(nd.tolist(), [])
2028 self.assertEqual(mv.tolist(), [])
2029
2030 nd = ndarray([1,2,3], shape=[0,3,3], flags=flags)
2031 self.assertEqual(nd.tolist(), [])
2032
2033 nd = ndarray([1,2,3], shape=[3,0,3], flags=flags)
2034 self.assertEqual(nd.tolist(), [[], [], []])
2035
2036 nd = ndarray([1,2,3], shape=[3,3,0], flags=flags)
2037 self.assertEqual(nd.tolist(),
2038 [[[], [], []], [[], [], []], [[], [], []]])
2039
2040 def test_ndarray_zero_strides(self):
2041 # zero strides
2042 for flags in (0, ND_PIL):
2043 nd = ndarray([1], shape=[5], strides=[0], flags=flags)
2044 mv = memoryview(nd)
2045 self.assertEqual(mv, nd)
2046 self.assertEqual(nd.tolist(), [1, 1, 1, 1, 1])
2047 self.assertEqual(mv.tolist(), [1, 1, 1, 1, 1])
2048
2049 def test_ndarray_offset(self):
2050 nd = ndarray(list(range(20)), shape=[3], offset=7)
2051 self.assertEqual(nd.offset, 7)
2052 self.assertEqual(nd.tolist(), [7,8,9])
2053
2054 def test_ndarray_memoryview_from_buffer(self):
2055 for flags in (0, ND_PIL):
2056 nd = ndarray(list(range(3)), shape=[3], flags=flags)
2057 m = nd.memoryview_from_buffer()
2058 self.assertEqual(m, nd)
2059
2060 def test_ndarray_get_pointer(self):
2061 for flags in (0, ND_PIL):
2062 nd = ndarray(list(range(3)), shape=[3], flags=flags)
2063 for i in range(3):
2064 self.assertEqual(nd[i], get_pointer(nd, [i]))
2065
2066 def test_ndarray_tolist_null_strides(self):
2067 ex = ndarray(list(range(20)), shape=[2,2,5])
2068
2069 nd = ndarray(ex, getbuf=PyBUF_ND|PyBUF_FORMAT)
2070 self.assertEqual(nd.tolist(), ex.tolist())
2071
2072 m = memoryview(ex)
2073 self.assertEqual(m.tolist(), ex.tolist())
2074
2075 def test_ndarray_cmp_contig(self):
2076
2077 self.assertFalse(cmp_contig(b"123", b"456"))
2078
2079 x = ndarray(list(range(12)), shape=[3,4])
2080 y = ndarray(list(range(12)), shape=[4,3])
2081 self.assertFalse(cmp_contig(x, y))
2082
2083 x = ndarray([1], shape=[1], format="B")
2084 self.assertTrue(cmp_contig(x, b'\x01'))
2085 self.assertTrue(cmp_contig(b'\x01', x))
2086
2087 def test_ndarray_hash(self):
2088
2089 a = array.array('L', [1,2,3])
2090 nd = ndarray(a)
2091 self.assertRaises(ValueError, hash, nd)
2092
2093 # one-dimensional
2094 b = bytes(list(range(12)))
2095
2096 nd = ndarray(list(range(12)), shape=[12])
2097 self.assertEqual(hash(nd), hash(b))
2098
2099 # C-contiguous
2100 nd = ndarray(list(range(12)), shape=[3,4])
2101 self.assertEqual(hash(nd), hash(b))
2102
2103 nd = ndarray(list(range(12)), shape=[3,2,2])
2104 self.assertEqual(hash(nd), hash(b))
2105
2106 # Fortran contiguous
2107 b = bytes(transpose(list(range(12)), shape=[4,3]))
2108 nd = ndarray(list(range(12)), shape=[3,4], flags=ND_FORTRAN)
2109 self.assertEqual(hash(nd), hash(b))
2110
2111 b = bytes(transpose(list(range(12)), shape=[2,3,2]))
2112 nd = ndarray(list(range(12)), shape=[2,3,2], flags=ND_FORTRAN)
2113 self.assertEqual(hash(nd), hash(b))
2114
2115 # suboffsets
2116 b = bytes(list(range(12)))
2117 nd = ndarray(list(range(12)), shape=[2,2,3], flags=ND_PIL)
2118 self.assertEqual(hash(nd), hash(b))
2119
2120 # non-byte formats
2121 nd = ndarray(list(range(12)), shape=[2,2,3], format='L')
2122 self.assertEqual(hash(nd), hash(nd.tobytes()))
2123
2124 def test_py_buffer_to_contiguous(self):
2125
2126 # The requests are used in _testbuffer.c:py_buffer_to_contiguous
2127 # to generate buffers without full information for testing.
2128 requests = (
2129 # distinct flags
2130 PyBUF_INDIRECT, PyBUF_STRIDES, PyBUF_ND, PyBUF_SIMPLE,
2131 # compound requests
2132 PyBUF_FULL, PyBUF_FULL_RO,
2133 PyBUF_RECORDS, PyBUF_RECORDS_RO,
2134 PyBUF_STRIDED, PyBUF_STRIDED_RO,
2135 PyBUF_CONTIG, PyBUF_CONTIG_RO,
2136 )
2137
2138 # no buffer interface
2139 self.assertRaises(TypeError, py_buffer_to_contiguous, {}, 'F',
2140 PyBUF_FULL_RO)
2141
2142 # scalar, read-only request
2143 nd = ndarray(9, shape=(), format="L", flags=ND_WRITABLE)
2144 for order in ['C', 'F', 'A']:
2145 for request in requests:
2146 b = py_buffer_to_contiguous(nd, order, request)
2147 self.assertEqual(b, nd.tobytes())
2148
2149 # zeros in shape
2150 nd = ndarray([1], shape=[0], format="L", flags=ND_WRITABLE)
2151 for order in ['C', 'F', 'A']:
2152 for request in requests:
2153 b = py_buffer_to_contiguous(nd, order, request)
2154 self.assertEqual(b, b'')
2155
2156 nd = ndarray(list(range(8)), shape=[2, 0, 7], format="L",
2157 flags=ND_WRITABLE)
2158 for order in ['C', 'F', 'A']:
2159 for request in requests:
2160 b = py_buffer_to_contiguous(nd, order, request)
2161 self.assertEqual(b, b'')
2162
2163 ### One-dimensional arrays are trivial, since Fortran and C order
2164 ### are the same.
2165
2166 # one-dimensional
2167 for f in [0, ND_FORTRAN]:
2168 nd = ndarray([1], shape=[1], format="h", flags=f|ND_WRITABLE)
2169 ndbytes = nd.tobytes()
2170 for order in ['C', 'F', 'A']:
2171 for request in requests:
2172 b = py_buffer_to_contiguous(nd, order, request)
2173 self.assertEqual(b, ndbytes)
2174
2175 nd = ndarray([1, 2, 3], shape=[3], format="b", flags=f|ND_WRITABLE)
2176 ndbytes = nd.tobytes()
2177 for order in ['C', 'F', 'A']:
2178 for request in requests:
2179 b = py_buffer_to_contiguous(nd, order, request)
2180 self.assertEqual(b, ndbytes)
2181
2182 # one-dimensional, non-contiguous input
2183 nd = ndarray([1, 2, 3], shape=[2], strides=[2], flags=ND_WRITABLE)
2184 ndbytes = nd.tobytes()
2185 for order in ['C', 'F', 'A']:
2186 for request in [PyBUF_STRIDES, PyBUF_FULL]:
2187 b = py_buffer_to_contiguous(nd, order, request)
2188 self.assertEqual(b, ndbytes)
2189
2190 nd = nd[::-1]
2191 ndbytes = nd.tobytes()
2192 for order in ['C', 'F', 'A']:
2193 for request in requests:
2194 try:
2195 b = py_buffer_to_contiguous(nd, order, request)
2196 except BufferError:
2197 continue
2198 self.assertEqual(b, ndbytes)
2199
2200 ###
2201 ### Multi-dimensional arrays:
2202 ###
2203 ### The goal here is to preserve the logical representation of the
2204 ### input array but change the physical representation if necessary.
2205 ###
2206 ### _testbuffer example:
2207 ### ====================
2208 ###
2209 ### C input array:
2210 ### --------------
2211 ### >>> nd = ndarray(list(range(12)), shape=[3, 4])
2212 ### >>> nd.tolist()
2213 ### [[0, 1, 2, 3],
2214 ### [4, 5, 6, 7],
2215 ### [8, 9, 10, 11]]
2216 ###
2217 ### Fortran output:
2218 ### ---------------
2219 ### >>> py_buffer_to_contiguous(nd, 'F', PyBUF_FULL_RO)
2220 ### >>> b'\x00\x04\x08\x01\x05\t\x02\x06\n\x03\x07\x0b'
2221 ###
2222 ### The return value corresponds to this input list for
2223 ### _testbuffer's ndarray:
2224 ### >>> nd = ndarray([0,4,8,1,5,9,2,6,10,3,7,11], shape=[3,4],
2225 ### flags=ND_FORTRAN)
2226 ### >>> nd.tolist()
2227 ### [[0, 1, 2, 3],
2228 ### [4, 5, 6, 7],
2229 ### [8, 9, 10, 11]]
2230 ###
2231 ### The logical array is the same, but the values in memory are now
2232 ### in Fortran order.
2233 ###
2234 ### NumPy example:
2235 ### ==============
2236 ### _testbuffer's ndarray takes lists to initialize the memory.
2237 ### Here's the same sequence in NumPy:
2238 ###
2239 ### C input:
2240 ### --------
2241 ### >>> nd = ndarray(buffer=bytearray(list(range(12))),
2242 ### shape=[3, 4], dtype='B')
2243 ### >>> nd
2244 ### array([[ 0, 1, 2, 3],
2245 ### [ 4, 5, 6, 7],
2246 ### [ 8, 9, 10, 11]], dtype=uint8)
2247 ###
2248 ### Fortran output:
2249 ### ---------------
2250 ### >>> fortran_buf = nd.tostring(order='F')
2251 ### >>> fortran_buf
2252 ### b'\x00\x04\x08\x01\x05\t\x02\x06\n\x03\x07\x0b'
2253 ###
2254 ### >>> nd = ndarray(buffer=fortran_buf, shape=[3, 4],
2255 ### dtype='B', order='F')
2256 ###
2257 ### >>> nd
2258 ### array([[ 0, 1, 2, 3],
2259 ### [ 4, 5, 6, 7],
2260 ### [ 8, 9, 10, 11]], dtype=uint8)
2261 ###
2262
2263 # multi-dimensional, contiguous input
2264 lst = list(range(12))
2265 for f in [0, ND_FORTRAN]:
2266 nd = ndarray(lst, shape=[3, 4], flags=f|ND_WRITABLE)
2267 if numpy_array:
2268 na = numpy_array(buffer=bytearray(lst),
2269 shape=[3, 4], dtype='B',
2270 order='C' if f == 0 else 'F')
2271
2272 # 'C' request
2273 if f == ND_FORTRAN: # 'F' to 'C'
2274 x = ndarray(transpose(lst, [4, 3]), shape=[3, 4],
2275 flags=ND_WRITABLE)
2276 expected = x.tobytes()
2277 else:
2278 expected = nd.tobytes()
2279 for request in requests:
2280 try:
2281 b = py_buffer_to_contiguous(nd, 'C', request)
2282 except BufferError:
2283 continue
2284
2285 self.assertEqual(b, expected)
2286
2287 # Check that output can be used as the basis for constructing
2288 # a C array that is logically identical to the input array.
2289 y = ndarray([v for v in b], shape=[3, 4], flags=ND_WRITABLE)
2290 self.assertEqual(memoryview(y), memoryview(nd))
2291
2292 if numpy_array:
2293 self.assertEqual(b, na.tostring(order='C'))
2294
2295 # 'F' request
2296 if f == 0: # 'C' to 'F'
2297 x = ndarray(transpose(lst, [3, 4]), shape=[4, 3],
2298 flags=ND_WRITABLE)
2299 else:
2300 x = ndarray(lst, shape=[3, 4], flags=ND_WRITABLE)
2301 expected = x.tobytes()
2302 for request in [PyBUF_FULL, PyBUF_FULL_RO, PyBUF_INDIRECT,
2303 PyBUF_STRIDES, PyBUF_ND]:
2304 try:
2305 b = py_buffer_to_contiguous(nd, 'F', request)
2306 except BufferError:
2307 continue
2308 self.assertEqual(b, expected)
2309
2310 # Check that output can be used as the basis for constructing
2311 # a Fortran array that is logically identical to the input array.
2312 y = ndarray([v for v in b], shape=[3, 4], flags=ND_FORTRAN|ND_WRITABLE)
2313 self.assertEqual(memoryview(y), memoryview(nd))
2314
2315 if numpy_array:
2316 self.assertEqual(b, na.tostring(order='F'))
2317
2318 # 'A' request
2319 if f == ND_FORTRAN:
2320 x = ndarray(lst, shape=[3, 4], flags=ND_WRITABLE)
2321 expected = x.tobytes()
2322 else:
2323 expected = nd.tobytes()
2324 for request in [PyBUF_FULL, PyBUF_FULL_RO, PyBUF_INDIRECT,
2325 PyBUF_STRIDES, PyBUF_ND]:
2326 try:
2327 b = py_buffer_to_contiguous(nd, 'A', request)
2328 except BufferError:
2329 continue
2330
2331 self.assertEqual(b, expected)
2332
2333 # Check that output can be used as the basis for constructing
2334 # an array with order=f that is logically identical to the input
2335 # array.
2336 y = ndarray([v for v in b], shape=[3, 4], flags=f|ND_WRITABLE)
2337 self.assertEqual(memoryview(y), memoryview(nd))
2338
2339 if numpy_array:
2340 self.assertEqual(b, na.tostring(order='A'))
2341
2342 # multi-dimensional, non-contiguous input
2343 nd = ndarray(list(range(12)), shape=[3, 4], flags=ND_WRITABLE|ND_PIL)
2344
2345 # 'C'
2346 b = py_buffer_to_contiguous(nd, 'C', PyBUF_FULL_RO)
2347 self.assertEqual(b, nd.tobytes())
2348 y = ndarray([v for v in b], shape=[3, 4], flags=ND_WRITABLE)
2349 self.assertEqual(memoryview(y), memoryview(nd))
2350
2351 # 'F'
2352 b = py_buffer_to_contiguous(nd, 'F', PyBUF_FULL_RO)
2353 x = ndarray(transpose(lst, [3, 4]), shape=[4, 3], flags=ND_WRITABLE)
2354 self.assertEqual(b, x.tobytes())
2355 y = ndarray([v for v in b], shape=[3, 4], flags=ND_FORTRAN|ND_WRITABLE)
2356 self.assertEqual(memoryview(y), memoryview(nd))
2357
2358 # 'A'
2359 b = py_buffer_to_contiguous(nd, 'A', PyBUF_FULL_RO)
2360 self.assertEqual(b, nd.tobytes())
2361 y = ndarray([v for v in b], shape=[3, 4], flags=ND_WRITABLE)
2362 self.assertEqual(memoryview(y), memoryview(nd))
2363
2364 def test_memoryview_construction(self):
2365
2366 items_shape = [(9, []), ([1,2,3], [3]), (list(range(2*3*5)), [2,3,5])]
2367
2368 # NumPy style, C-contiguous:
2369 for items, shape in items_shape:
2370
2371 # From PEP-3118 compliant exporter:
2372 ex = ndarray(items, shape=shape)
2373 m = memoryview(ex)
2374 self.assertTrue(m.c_contiguous)
2375 self.assertTrue(m.contiguous)
2376
2377 ndim = len(shape)
2378 strides = strides_from_shape(ndim, shape, 1, 'C')
2379 lst = carray(items, shape)
2380
2381 self.verify(m, obj=ex,
2382 itemsize=1, fmt='B', readonly=True,
2383 ndim=ndim, shape=shape, strides=strides,
2384 lst=lst)
2385
2386 # From memoryview:
2387 m2 = memoryview(m)
2388 self.verify(m2, obj=ex,
2389 itemsize=1, fmt='B', readonly=True,
2390 ndim=ndim, shape=shape, strides=strides,
2391 lst=lst)
2392
2393 # PyMemoryView_FromBuffer(): no strides
2394 nd = ndarray(ex, getbuf=PyBUF_CONTIG_RO|PyBUF_FORMAT)
2395 self.assertEqual(nd.strides, ())
2396 m = nd.memoryview_from_buffer()
2397 self.verify(m, obj=None,
2398 itemsize=1, fmt='B', readonly=True,
2399 ndim=ndim, shape=shape, strides=strides,
2400 lst=lst)
2401
2402 # PyMemoryView_FromBuffer(): no format, shape, strides
2403 nd = ndarray(ex, getbuf=PyBUF_SIMPLE)
2404 self.assertEqual(nd.format, '')
2405 self.assertEqual(nd.shape, ())
2406 self.assertEqual(nd.strides, ())
2407 m = nd.memoryview_from_buffer()
2408
2409 lst = [items] if ndim == 0 else items
2410 self.verify(m, obj=None,
2411 itemsize=1, fmt='B', readonly=True,
2412 ndim=1, shape=[ex.nbytes], strides=(1,),
2413 lst=lst)
2414
2415 # NumPy style, Fortran contiguous:
2416 for items, shape in items_shape:
2417
2418 # From PEP-3118 compliant exporter:
2419 ex = ndarray(items, shape=shape, flags=ND_FORTRAN)
2420 m = memoryview(ex)
2421 self.assertTrue(m.f_contiguous)
2422 self.assertTrue(m.contiguous)
2423
2424 ndim = len(shape)
2425 strides = strides_from_shape(ndim, shape, 1, 'F')
2426 lst = farray(items, shape)
2427
2428 self.verify(m, obj=ex,
2429 itemsize=1, fmt='B', readonly=True,
2430 ndim=ndim, shape=shape, strides=strides,
2431 lst=lst)
2432
2433 # From memoryview:
2434 m2 = memoryview(m)
2435 self.verify(m2, obj=ex,
2436 itemsize=1, fmt='B', readonly=True,
2437 ndim=ndim, shape=shape, strides=strides,
2438 lst=lst)
2439
2440 # PIL style:
2441 for items, shape in items_shape[1:]:
2442
2443 # From PEP-3118 compliant exporter:
2444 ex = ndarray(items, shape=shape, flags=ND_PIL)
2445 m = memoryview(ex)
2446
2447 ndim = len(shape)
2448 lst = carray(items, shape)
2449
2450 self.verify(m, obj=ex,
2451 itemsize=1, fmt='B', readonly=True,
2452 ndim=ndim, shape=shape, strides=ex.strides,
2453 lst=lst)
2454
2455 # From memoryview:
2456 m2 = memoryview(m)
2457 self.verify(m2, obj=ex,
2458 itemsize=1, fmt='B', readonly=True,
2459 ndim=ndim, shape=shape, strides=ex.strides,
2460 lst=lst)
2461
2462 # Invalid number of arguments:
2463 self.assertRaises(TypeError, memoryview, b'9', 'x')
2464 # Not a buffer provider:
2465 self.assertRaises(TypeError, memoryview, {})
2466 # Non-compliant buffer provider:
2467 ex = ndarray([1,2,3], shape=[3])
2468 nd = ndarray(ex, getbuf=PyBUF_SIMPLE)
2469 self.assertRaises(BufferError, memoryview, nd)
2470 nd = ndarray(ex, getbuf=PyBUF_CONTIG_RO|PyBUF_FORMAT)
2471 self.assertRaises(BufferError, memoryview, nd)
2472
2473 # ndim > 64
2474 nd = ndarray([1]*128, shape=[1]*128, format='L')
2475 self.assertRaises(ValueError, memoryview, nd)
2476 self.assertRaises(ValueError, nd.memoryview_from_buffer)
2477 self.assertRaises(ValueError, get_contiguous, nd, PyBUF_READ, 'C')
2478 self.assertRaises(ValueError, get_contiguous, nd, PyBUF_READ, 'F')
2479 self.assertRaises(ValueError, get_contiguous, nd[::-1], PyBUF_READ, 'C')
2480
2481 def test_memoryview_cast_zero_shape(self):
2482 # Casts are undefined if buffer is multidimensional and shape
2483 # contains zeros. These arrays are regarded as C-contiguous by
2484 # Numpy and PyBuffer_GetContiguous(), so they are not caught by
2485 # the test for C-contiguity in memory_cast().
2486 items = [1,2,3]
2487 for shape in ([0,3,3], [3,0,3], [0,3,3]):
2488 ex = ndarray(items, shape=shape)
2489 self.assertTrue(ex.c_contiguous)
2490 msrc = memoryview(ex)
2491 self.assertRaises(TypeError, msrc.cast, 'c')
2492 # Monodimensional empty view can be cast (issue #19014).
2493 for fmt, _, _ in iter_format(1, 'memoryview'):
2494 msrc = memoryview(b'')
2495 m = msrc.cast(fmt)
2496 self.assertEqual(m.tobytes(), b'')
2497 self.assertEqual(m.tolist(), [])
2498
2499 check_sizeof = support.check_sizeof
2500
2501 def test_memoryview_sizeof(self):
2502 check = self.check_sizeof
2503 vsize = support.calcvobjsize
2504 base_struct = 'Pnin 2P2n2i5P P'
2505 per_dim = '3n'
2506
2507 items = list(range(8))
2508 check(memoryview(b''), vsize(base_struct + 1 * per_dim))
2509 a = ndarray(items, shape=[2, 4], format="b")
2510 check(memoryview(a), vsize(base_struct + 2 * per_dim))
2511 a = ndarray(items, shape=[2, 2, 2], format="b")
2512 check(memoryview(a), vsize(base_struct + 3 * per_dim))
2513
2514 def test_memoryview_struct_module(self):
2515
2516 class INT(object):
2517 def __init__(self, val):
2518 self.val = val
2519 def __int__(self):
2520 return self.val
2521
2522 class IDX(object):
2523 def __init__(self, val):
2524 self.val = val
2525 def __index__(self):
2526 return self.val
2527
2528 def f(): return 7
2529
2530 values = [INT(9), IDX(9),
2531 2.2+3j, Decimal("-21.1"), 12.2, Fraction(5, 2),
2532 [1,2,3], {4,5,6}, {7:8}, (), (9,),
2533 True, False, None, Ellipsis,
2534 b'a', b'abc', bytearray(b'a'), bytearray(b'abc'),
2535 'a', 'abc', r'a', r'abc',
2536 f, lambda x: x]
2537
2538 for fmt, items, item in iter_format(10, 'memoryview'):
2539 ex = ndarray(items, shape=[10], format=fmt, flags=ND_WRITABLE)
2540 nd = ndarray(items, shape=[10], format=fmt, flags=ND_WRITABLE)
2541 m = memoryview(ex)
2542
2543 struct.pack_into(fmt, nd, 0, item)
2544 m[0] = item
2545 self.assertEqual(m[0], nd[0])
2546
2547 itemsize = struct.calcsize(fmt)
2548 if 'P' in fmt:
2549 continue
2550
2551 for v in values:
2552 struct_err = None
2553 try:
2554 struct.pack_into(fmt, nd, itemsize, v)
2555 except struct.error:
2556 struct_err = struct.error
2557
2558 mv_err = None
2559 try:
2560 m[1] = v
2561 except (TypeError, ValueError) as e:
2562 mv_err = e.__class__
2563
2564 if struct_err or mv_err:
2565 self.assertIsNot(struct_err, None)
2566 self.assertIsNot(mv_err, None)
2567 else:
2568 self.assertEqual(m[1], nd[1])
2569
2570 def test_memoryview_cast_zero_strides(self):
2571 # Casts are undefined if strides contains zeros. These arrays are
2572 # (sometimes!) regarded as C-contiguous by Numpy, but not by
2573 # PyBuffer_GetContiguous().
2574 ex = ndarray([1,2,3], shape=[3], strides=[0])
2575 self.assertFalse(ex.c_contiguous)
2576 msrc = memoryview(ex)
2577 self.assertRaises(TypeError, msrc.cast, 'c')
2578
2579 def test_memoryview_cast_invalid(self):
2580 # invalid format
2581 for sfmt in NON_BYTE_FORMAT:
2582 sformat = '@' + sfmt if randrange(2) else sfmt
2583 ssize = struct.calcsize(sformat)
2584 for dfmt in NON_BYTE_FORMAT:
2585 dformat = '@' + dfmt if randrange(2) else dfmt
2586 dsize = struct.calcsize(dformat)
2587 ex = ndarray(list(range(32)), shape=[32//ssize], format=sformat)
2588 msrc = memoryview(ex)
2589 self.assertRaises(TypeError, msrc.cast, dfmt, [32//dsize])
2590
2591 for sfmt, sitems, _ in iter_format(1):
2592 ex = ndarray(sitems, shape=[1], format=sfmt)
2593 msrc = memoryview(ex)
2594 for dfmt, _, _ in iter_format(1):
2595 if not is_memoryview_format(dfmt):
2596 self.assertRaises(ValueError, msrc.cast, dfmt,
2597 [32//dsize])
2598 else:
2599 if not is_byte_format(sfmt) and not is_byte_format(dfmt):
2600 self.assertRaises(TypeError, msrc.cast, dfmt,
2601 [32//dsize])
2602
2603 # invalid shape
2604 size_h = struct.calcsize('h')
2605 size_d = struct.calcsize('d')
2606 ex = ndarray(list(range(2*2*size_d)), shape=[2,2,size_d], format='h')
2607 msrc = memoryview(ex)
2608 self.assertRaises(TypeError, msrc.cast, shape=[2,2,size_h], format='d')
2609
2610 ex = ndarray(list(range(120)), shape=[1,2,3,4,5])
2611 m = memoryview(ex)
2612
2613 # incorrect number of args
2614 self.assertRaises(TypeError, m.cast)
2615 self.assertRaises(TypeError, m.cast, 1, 2, 3)
2616
2617 # incorrect dest format type
2618 self.assertRaises(TypeError, m.cast, {})
2619
2620 # incorrect dest format
2621 self.assertRaises(ValueError, m.cast, "X")
2622 self.assertRaises(ValueError, m.cast, "@X")
2623 self.assertRaises(ValueError, m.cast, "@XY")
2624
2625 # dest format not implemented
2626 self.assertRaises(ValueError, m.cast, "=B")
2627 self.assertRaises(ValueError, m.cast, "!L")
2628 self.assertRaises(ValueError, m.cast, "<P")
2629 self.assertRaises(ValueError, m.cast, ">l")
2630 self.assertRaises(ValueError, m.cast, "BI")
2631 self.assertRaises(ValueError, m.cast, "xBI")
2632
2633 # src format not implemented
2634 ex = ndarray([(1,2), (3,4)], shape=[2], format="II")
2635 m = memoryview(ex)
2636 self.assertRaises(NotImplementedError, m.__getitem__, 0)
2637 self.assertRaises(NotImplementedError, m.__setitem__, 0, 8)
2638 self.assertRaises(NotImplementedError, m.tolist)
2639
2640 # incorrect shape type
2641 ex = ndarray(list(range(120)), shape=[1,2,3,4,5])
2642 m = memoryview(ex)
2643 self.assertRaises(TypeError, m.cast, "B", shape={})
2644
2645 # incorrect shape elements
2646 ex = ndarray(list(range(120)), shape=[2*3*4*5])
2647 m = memoryview(ex)
2648 self.assertRaises(OverflowError, m.cast, "B", shape=[2**64])
2649 self.assertRaises(ValueError, m.cast, "B", shape=[-1])
2650 self.assertRaises(ValueError, m.cast, "B", shape=[2,3,4,5,6,7,-1])
2651 self.assertRaises(ValueError, m.cast, "B", shape=[2,3,4,5,6,7,0])
2652 self.assertRaises(TypeError, m.cast, "B", shape=[2,3,4,5,6,7,'x'])
2653
2654 # N-D -> N-D cast
2655 ex = ndarray(list([9 for _ in range(3*5*7*11)]), shape=[3,5,7,11])
2656 m = memoryview(ex)
2657 self.assertRaises(TypeError, m.cast, "I", shape=[2,3,4,5])
2658
2659 # cast with ndim > 64
2660 nd = ndarray(list(range(128)), shape=[128], format='I')
2661 m = memoryview(nd)
2662 self.assertRaises(ValueError, m.cast, 'I', [1]*128)
2663
2664 # view->len not a multiple of itemsize
2665 ex = ndarray(list([9 for _ in range(3*5*7*11)]), shape=[3*5*7*11])
2666 m = memoryview(ex)
2667 self.assertRaises(TypeError, m.cast, "I", shape=[2,3,4,5])
2668
2669 # product(shape) * itemsize != buffer size
2670 ex = ndarray(list([9 for _ in range(3*5*7*11)]), shape=[3*5*7*11])
2671 m = memoryview(ex)
2672 self.assertRaises(TypeError, m.cast, "B", shape=[2,3,4,5])
2673
2674 # product(shape) * itemsize overflow
2675 nd = ndarray(list(range(128)), shape=[128], format='I')
2676 m1 = memoryview(nd)
2677 nd = ndarray(list(range(128)), shape=[128], format='B')
2678 m2 = memoryview(nd)
2679 if sys.maxsize == 2**63-1:
2680 self.assertRaises(TypeError, m1.cast, 'B',
2681 [7, 7, 73, 127, 337, 92737, 649657])
2682 self.assertRaises(ValueError, m1.cast, 'B',
2683 [2**20, 2**20, 2**10, 2**10, 2**3])
2684 self.assertRaises(ValueError, m2.cast, 'I',
2685 [2**20, 2**20, 2**10, 2**10, 2**1])
2686 else:
2687 self.assertRaises(TypeError, m1.cast, 'B',
2688 [1, 2147483647])
2689 self.assertRaises(ValueError, m1.cast, 'B',
2690 [2**10, 2**10, 2**5, 2**5, 2**1])
2691 self.assertRaises(ValueError, m2.cast, 'I',
2692 [2**10, 2**10, 2**5, 2**3, 2**1])
2693
2694 def test_memoryview_cast(self):
2695 bytespec = (
2696 ('B', lambda ex: list(ex.tobytes())),
2697 ('b', lambda ex: [x-256 if x > 127 else x for x in list(ex.tobytes())]),
2698 ('c', lambda ex: [bytes(chr(x), 'latin-1') for x in list(ex.tobytes())]),
2699 )
2700
2701 def iter_roundtrip(ex, m, items, fmt):
2702 srcsize = struct.calcsize(fmt)
2703 for bytefmt, to_bytelist in bytespec:
2704
2705 m2 = m.cast(bytefmt)
2706 lst = to_bytelist(ex)
2707 self.verify(m2, obj=ex,
2708 itemsize=1, fmt=bytefmt, readonly=False,
2709 ndim=1, shape=[31*srcsize], strides=(1,),
2710 lst=lst, cast=True)
2711
2712 m3 = m2.cast(fmt)
2713 self.assertEqual(m3, ex)
2714 lst = ex.tolist()
2715 self.verify(m3, obj=ex,
2716 itemsize=srcsize, fmt=fmt, readonly=False,
2717 ndim=1, shape=[31], strides=(srcsize,),
2718 lst=lst, cast=True)
2719
2720 # cast from ndim = 0 to ndim = 1
2721 srcsize = struct.calcsize('I')
2722 ex = ndarray(9, shape=[], format='I')
2723 destitems, destshape = cast_items(ex, 'B', 1)
2724 m = memoryview(ex)
2725 m2 = m.cast('B')
2726 self.verify(m2, obj=ex,
2727 itemsize=1, fmt='B', readonly=True,
2728 ndim=1, shape=destshape, strides=(1,),
2729 lst=destitems, cast=True)
2730
2731 # cast from ndim = 1 to ndim = 0
2732 destsize = struct.calcsize('I')
2733 ex = ndarray([9]*destsize, shape=[destsize], format='B')
2734 destitems, destshape = cast_items(ex, 'I', destsize, shape=[])
2735 m = memoryview(ex)
2736 m2 = m.cast('I', shape=[])
2737 self.verify(m2, obj=ex,
2738 itemsize=destsize, fmt='I', readonly=True,
2739 ndim=0, shape=(), strides=(),
2740 lst=destitems, cast=True)
2741
2742 # array.array: roundtrip to/from bytes
2743 for fmt, items, _ in iter_format(31, 'array'):
2744 ex = array.array(fmt, items)
2745 m = memoryview(ex)
2746 iter_roundtrip(ex, m, items, fmt)
2747
2748 # ndarray: roundtrip to/from bytes
2749 for fmt, items, _ in iter_format(31, 'memoryview'):
2750 ex = ndarray(items, shape=[31], format=fmt, flags=ND_WRITABLE)
2751 m = memoryview(ex)
2752 iter_roundtrip(ex, m, items, fmt)
2753
2754 @support.requires_resource('cpu')
2755 def test_memoryview_cast_1D_ND(self):
2756 # Cast between C-contiguous buffers. At least one buffer must
2757 # be 1D, at least one format must be 'c', 'b' or 'B'.
2758 for _tshape in gencastshapes():
2759 for char in fmtdict['@']:
2760 # Casts to _Bool are undefined if the source contains values
2761 # other than 0 or 1.
2762 if char == "?":
2763 continue
2764 tfmt = ('', '@')[randrange(2)] + char
2765 tsize = struct.calcsize(tfmt)
2766 n = prod(_tshape) * tsize
2767 obj = 'memoryview' if is_byte_format(tfmt) else 'bytefmt'
2768 for fmt, items, _ in iter_format(n, obj):
2769 size = struct.calcsize(fmt)
2770 shape = [n] if n > 0 else []
2771 tshape = _tshape + [size]
2772
2773 ex = ndarray(items, shape=shape, format=fmt)
2774 m = memoryview(ex)
2775
2776 titems, tshape = cast_items(ex, tfmt, tsize, shape=tshape)
2777
2778 if titems is None:
2779 self.assertRaises(TypeError, m.cast, tfmt, tshape)
2780 continue
2781 if titems == 'nan':
2782 continue # NaNs in lists are a recipe for trouble.
2783
2784 # 1D -> ND
2785 nd = ndarray(titems, shape=tshape, format=tfmt)
2786
2787 m2 = m.cast(tfmt, shape=tshape)
2788 ndim = len(tshape)
2789 strides = nd.strides
2790 lst = nd.tolist()
2791 self.verify(m2, obj=ex,
2792 itemsize=tsize, fmt=tfmt, readonly=True,
2793 ndim=ndim, shape=tshape, strides=strides,
2794 lst=lst, cast=True)
2795
2796 # ND -> 1D
2797 m3 = m2.cast(fmt)
2798 m4 = m2.cast(fmt, shape=shape)
2799 ndim = len(shape)
2800 strides = ex.strides
2801 lst = ex.tolist()
2802
2803 self.verify(m3, obj=ex,
2804 itemsize=size, fmt=fmt, readonly=True,
2805 ndim=ndim, shape=shape, strides=strides,
2806 lst=lst, cast=True)
2807
2808 self.verify(m4, obj=ex,
2809 itemsize=size, fmt=fmt, readonly=True,
2810 ndim=ndim, shape=shape, strides=strides,
2811 lst=lst, cast=True)
2812
2813 if ctypes:
2814 # format: "T{>l:x:>d:y:}"
2815 class BEPoint(ctypes.BigEndianStructure):
2816 _fields_ = [("x", ctypes.c_long), ("y", ctypes.c_double)]
2817 point = BEPoint(100, 200.1)
2818 m1 = memoryview(point)
2819 m2 = m1.cast('B')
2820 self.assertEqual(m2.obj, point)
2821 self.assertEqual(m2.itemsize, 1)
2822 self.assertIs(m2.readonly, False)
2823 self.assertEqual(m2.ndim, 1)
2824 self.assertEqual(m2.shape, (m2.nbytes,))
2825 self.assertEqual(m2.strides, (1,))
2826 self.assertEqual(m2.suboffsets, ())
2827
2828 x = ctypes.c_double(1.2)
2829 m1 = memoryview(x)
2830 m2 = m1.cast('c')
2831 self.assertEqual(m2.obj, x)
2832 self.assertEqual(m2.itemsize, 1)
2833 self.assertIs(m2.readonly, False)
2834 self.assertEqual(m2.ndim, 1)
2835 self.assertEqual(m2.shape, (m2.nbytes,))
2836 self.assertEqual(m2.strides, (1,))
2837 self.assertEqual(m2.suboffsets, ())
2838
2839 def test_memoryview_tolist(self):
2840
2841 # Most tolist() tests are in self.verify() etc.
2842
2843 a = array.array('h', list(range(-6, 6)))
2844 m = memoryview(a)
2845 self.assertEqual(m, a)
2846 self.assertEqual(m.tolist(), a.tolist())
2847
2848 a = a[2::3]
2849 m = m[2::3]
2850 self.assertEqual(m, a)
2851 self.assertEqual(m.tolist(), a.tolist())
2852
2853 ex = ndarray(list(range(2*3*5*7*11)), shape=[11,2,7,3,5], format='L')
2854 m = memoryview(ex)
2855 self.assertEqual(m.tolist(), ex.tolist())
2856
2857 ex = ndarray([(2, 5), (7, 11)], shape=[2], format='lh')
2858 m = memoryview(ex)
2859 self.assertRaises(NotImplementedError, m.tolist)
2860
2861 ex = ndarray([b'12345'], shape=[1], format="s")
2862 m = memoryview(ex)
2863 self.assertRaises(NotImplementedError, m.tolist)
2864
2865 ex = ndarray([b"a",b"b",b"c",b"d",b"e",b"f"], shape=[2,3], format='s')
2866 m = memoryview(ex)
2867 self.assertRaises(NotImplementedError, m.tolist)
2868
2869 def test_memoryview_repr(self):
2870 m = memoryview(bytearray(9))
2871 r = m.__repr__()
2872 self.assertTrue(r.startswith("<memory"))
2873
2874 m.release()
2875 r = m.__repr__()
2876 self.assertTrue(r.startswith("<released"))
2877
2878 def test_memoryview_sequence(self):
2879
2880 for fmt in ('d', 'f'):
2881 inf = float(3e400)
2882 ex = array.array(fmt, [1.0, inf, 3.0])
2883 m = memoryview(ex)
2884 self.assertIn(1.0, m)
2885 self.assertIn(5e700, m)
2886 self.assertIn(3.0, m)
2887
2888 ex = ndarray(9.0, [], format='f')
2889 m = memoryview(ex)
2890 self.assertRaises(TypeError, eval, "9.0 in m", locals())
2891
2892 @contextlib.contextmanager
2893 def assert_out_of_bounds_error(self, dim):
2894 with self.assertRaises(IndexError) as cm:
2895 yield
2896 self.assertEqual(str(cm.exception),
2897 "index out of bounds on dimension %d" % (dim,))
2898
2899 def test_memoryview_index(self):
2900
2901 # ndim = 0
2902 ex = ndarray(12.5, shape=[], format='d')
2903 m = memoryview(ex)
2904 self.assertEqual(m[()], 12.5)
2905 self.assertEqual(m[...], m)
2906 self.assertEqual(m[...], ex)
2907 self.assertRaises(TypeError, m.__getitem__, 0)
2908
2909 ex = ndarray((1,2,3), shape=[], format='iii')
2910 m = memoryview(ex)
2911 self.assertRaises(NotImplementedError, m.__getitem__, ())
2912
2913 # range
2914 ex = ndarray(list(range(7)), shape=[7], flags=ND_WRITABLE)
2915 m = memoryview(ex)
2916
2917 self.assertRaises(IndexError, m.__getitem__, 2**64)
2918 self.assertRaises(TypeError, m.__getitem__, 2.0)
2919 self.assertRaises(TypeError, m.__getitem__, 0.0)
2920
2921 # out of bounds
2922 self.assertRaises(IndexError, m.__getitem__, -8)
2923 self.assertRaises(IndexError, m.__getitem__, 8)
2924
2925 # multi-dimensional
2926 ex = ndarray(list(range(12)), shape=[3,4], flags=ND_WRITABLE)
2927 m = memoryview(ex)
2928
2929 self.assertEqual(m[0, 0], 0)
2930 self.assertEqual(m[2, 0], 8)
2931 self.assertEqual(m[2, 3], 11)
2932 self.assertEqual(m[-1, -1], 11)
2933 self.assertEqual(m[-3, -4], 0)
2934
2935 # out of bounds
2936 for index in (3, -4):
2937 with self.assert_out_of_bounds_error(dim=1):
2938 m[index, 0]
2939 for index in (4, -5):
2940 with self.assert_out_of_bounds_error(dim=2):
2941 m[0, index]
2942 self.assertRaises(IndexError, m.__getitem__, (2**64, 0))
2943 self.assertRaises(IndexError, m.__getitem__, (0, 2**64))
2944
2945 self.assertRaises(TypeError, m.__getitem__, (0, 0, 0))
2946 self.assertRaises(TypeError, m.__getitem__, (0.0, 0.0))
2947
2948 # Not implemented: multidimensional sub-views
2949 self.assertRaises(NotImplementedError, m.__getitem__, ())
2950 self.assertRaises(NotImplementedError, m.__getitem__, 0)
2951
2952 def test_memoryview_assign(self):
2953
2954 # ndim = 0
2955 ex = ndarray(12.5, shape=[], format='f', flags=ND_WRITABLE)
2956 m = memoryview(ex)
2957 m[()] = 22.5
2958 self.assertEqual(m[()], 22.5)
2959 m[...] = 23.5
2960 self.assertEqual(m[()], 23.5)
2961 self.assertRaises(TypeError, m.__setitem__, 0, 24.7)
2962
2963 # read-only
2964 ex = ndarray(list(range(7)), shape=[7])
2965 m = memoryview(ex)
2966 self.assertRaises(TypeError, m.__setitem__, 2, 10)
2967
2968 # range
2969 ex = ndarray(list(range(7)), shape=[7], flags=ND_WRITABLE)
2970 m = memoryview(ex)
2971
2972 self.assertRaises(IndexError, m.__setitem__, 2**64, 9)
2973 self.assertRaises(TypeError, m.__setitem__, 2.0, 10)
2974 self.assertRaises(TypeError, m.__setitem__, 0.0, 11)
2975
2976 # out of bounds
2977 self.assertRaises(IndexError, m.__setitem__, -8, 20)
2978 self.assertRaises(IndexError, m.__setitem__, 8, 25)
2979
2980 # pack_single() success:
2981 for fmt in fmtdict['@']:
2982 if fmt == 'c' or fmt == '?':
2983 continue
2984 ex = ndarray([1,2,3], shape=[3], format=fmt, flags=ND_WRITABLE)
2985 m = memoryview(ex)
2986 i = randrange(-3, 3)
2987 m[i] = 8
2988 self.assertEqual(m[i], 8)
2989 self.assertEqual(m[i], ex[i])
2990
2991 ex = ndarray([b'1', b'2', b'3'], shape=[3], format='c',
2992 flags=ND_WRITABLE)
2993 m = memoryview(ex)
2994 m[2] = b'9'
2995 self.assertEqual(m[2], b'9')
2996
2997 ex = ndarray([True, False, True], shape=[3], format='?',
2998 flags=ND_WRITABLE)
2999 m = memoryview(ex)
3000 m[1] = True
3001 self.assertIs(m[1], True)
3002
3003 # pack_single() exceptions:
3004 nd = ndarray([b'x'], shape=[1], format='c', flags=ND_WRITABLE)
3005 m = memoryview(nd)
3006 self.assertRaises(TypeError, m.__setitem__, 0, 100)
3007
3008 ex = ndarray(list(range(120)), shape=[1,2,3,4,5], flags=ND_WRITABLE)
3009 m1 = memoryview(ex)
3010
3011 for fmt, _range in fmtdict['@'].items():
3012 if (fmt == '?'): # PyObject_IsTrue() accepts anything
3013 continue
3014 if fmt == 'c': # special case tested above
3015 continue
3016 m2 = m1.cast(fmt)
3017 lo, hi = _range
3018 if fmt == 'd' or fmt == 'f':
3019 lo, hi = -2**1024, 2**1024
3020 if fmt != 'P': # PyLong_AsVoidPtr() accepts negative numbers
3021 self.assertRaises(ValueError, m2.__setitem__, 0, lo-1)
3022 self.assertRaises(TypeError, m2.__setitem__, 0, "xyz")
3023 self.assertRaises(ValueError, m2.__setitem__, 0, hi)
3024
3025 # invalid item
3026 m2 = m1.cast('c')
3027 self.assertRaises(ValueError, m2.__setitem__, 0, b'\xff\xff')
3028
3029 # format not implemented
3030 ex = ndarray(list(range(1)), shape=[1], format="xL", flags=ND_WRITABLE)
3031 m = memoryview(ex)
3032 self.assertRaises(NotImplementedError, m.__setitem__, 0, 1)
3033
3034 ex = ndarray([b'12345'], shape=[1], format="s", flags=ND_WRITABLE)
3035 m = memoryview(ex)
3036 self.assertRaises(NotImplementedError, m.__setitem__, 0, 1)
3037
3038 # multi-dimensional
3039 ex = ndarray(list(range(12)), shape=[3,4], flags=ND_WRITABLE)
3040 m = memoryview(ex)
3041 m[0,1] = 42
3042 self.assertEqual(ex[0][1], 42)
3043 m[-1,-1] = 43
3044 self.assertEqual(ex[2][3], 43)
3045 # errors
3046 for index in (3, -4):
3047 with self.assert_out_of_bounds_error(dim=1):
3048 m[index, 0] = 0
3049 for index in (4, -5):
3050 with self.assert_out_of_bounds_error(dim=2):
3051 m[0, index] = 0
3052 self.assertRaises(IndexError, m.__setitem__, (2**64, 0), 0)
3053 self.assertRaises(IndexError, m.__setitem__, (0, 2**64), 0)
3054
3055 self.assertRaises(TypeError, m.__setitem__, (0, 0, 0), 0)
3056 self.assertRaises(TypeError, m.__setitem__, (0.0, 0.0), 0)
3057
3058 # Not implemented: multidimensional sub-views
3059 self.assertRaises(NotImplementedError, m.__setitem__, 0, [2, 3])
3060
3061 def test_memoryview_slice(self):
3062
3063 ex = ndarray(list(range(12)), shape=[12], flags=ND_WRITABLE)
3064 m = memoryview(ex)
3065
3066 # zero step
3067 self.assertRaises(ValueError, m.__getitem__, slice(0,2,0))
3068 self.assertRaises(ValueError, m.__setitem__, slice(0,2,0),
3069 bytearray([1,2]))
3070
3071 # 0-dim slicing (identity function)
3072 self.assertRaises(NotImplementedError, m.__getitem__, ())
3073
3074 # multidimensional slices
3075 ex = ndarray(list(range(12)), shape=[12], flags=ND_WRITABLE)
3076 m = memoryview(ex)
3077
3078 self.assertRaises(NotImplementedError, m.__getitem__,
3079 (slice(0,2,1), slice(0,2,1)))
3080 self.assertRaises(NotImplementedError, m.__setitem__,
3081 (slice(0,2,1), slice(0,2,1)), bytearray([1,2]))
3082
3083 # invalid slice tuple
3084 self.assertRaises(TypeError, m.__getitem__, (slice(0,2,1), {}))
3085 self.assertRaises(TypeError, m.__setitem__, (slice(0,2,1), {}),
3086 bytearray([1,2]))
3087
3088 # rvalue is not an exporter
3089 self.assertRaises(TypeError, m.__setitem__, slice(0,1,1), [1])
3090
3091 # non-contiguous slice assignment
3092 for flags in (0, ND_PIL):
3093 ex1 = ndarray(list(range(12)), shape=[12], strides=[-1], offset=11,
3094 flags=ND_WRITABLE|flags)
3095 ex2 = ndarray(list(range(24)), shape=[12], strides=[2], flags=flags)
3096 m1 = memoryview(ex1)
3097 m2 = memoryview(ex2)
3098
3099 ex1[2:5] = ex1[2:5]
3100 m1[2:5] = m2[2:5]
3101
3102 self.assertEqual(m1, ex1)
3103 self.assertEqual(m2, ex2)
3104
3105 ex1[1:3][::-1] = ex2[0:2][::1]
3106 m1[1:3][::-1] = m2[0:2][::1]
3107
3108 self.assertEqual(m1, ex1)
3109 self.assertEqual(m2, ex2)
3110
3111 ex1[4:1:-2][::-1] = ex1[1:4:2][::1]
3112 m1[4:1:-2][::-1] = m1[1:4:2][::1]
3113
3114 self.assertEqual(m1, ex1)
3115 self.assertEqual(m2, ex2)
3116
3117 def test_memoryview_array(self):
3118
3119 def cmptest(testcase, a, b, m, singleitem):
3120 for i, _ in enumerate(a):
3121 ai = a[i]
3122 mi = m[i]
3123 testcase.assertEqual(ai, mi)
3124 a[i] = singleitem
3125 if singleitem != ai:
3126 testcase.assertNotEqual(a, m)
3127 testcase.assertNotEqual(a, b)
3128 else:
3129 testcase.assertEqual(a, m)
3130 testcase.assertEqual(a, b)
3131 m[i] = singleitem
3132 testcase.assertEqual(a, m)
3133 testcase.assertEqual(b, m)
3134 a[i] = ai
3135 m[i] = mi
3136
3137 for n in range(1, 5):
3138 for fmt, items, singleitem in iter_format(n, 'array'):
3139 for lslice in genslices(n):
3140 for rslice in genslices(n):
3141
3142 a = array.array(fmt, items)
3143 b = array.array(fmt, items)
3144 m = memoryview(b)
3145
3146 self.assertEqual(m, a)
3147 self.assertEqual(m.tolist(), a.tolist())
3148 self.assertEqual(m.tobytes(), a.tobytes())
3149 self.assertEqual(len(m), len(a))
3150
3151 cmptest(self, a, b, m, singleitem)
3152
3153 array_err = None
3154 have_resize = None
3155 try:
3156 al = a[lslice]
3157 ar = a[rslice]
3158 a[lslice] = a[rslice]
3159 have_resize = len(al) != len(ar)
3160 except Exception as e:
3161 array_err = e.__class__
3162
3163 m_err = None
3164 try:
3165 m[lslice] = m[rslice]
3166 except Exception as e:
3167 m_err = e.__class__
3168
3169 if have_resize: # memoryview cannot change shape
3170 self.assertIs(m_err, ValueError)
3171 elif m_err or array_err:
3172 self.assertIs(m_err, array_err)
3173 else:
3174 self.assertEqual(m, a)
3175 self.assertEqual(m.tolist(), a.tolist())
3176 self.assertEqual(m.tobytes(), a.tobytes())
3177 cmptest(self, a, b, m, singleitem)
3178
3179 def test_memoryview_compare_special_cases(self):
3180
3181 a = array.array('L', [1, 2, 3])
3182 b = array.array('L', [1, 2, 7])
3183
3184 # Ordering comparisons raise:
3185 v = memoryview(a)
3186 w = memoryview(b)
3187 for attr in ('__lt__', '__le__', '__gt__', '__ge__'):
3188 self.assertIs(getattr(v, attr)(w), NotImplemented)
3189 self.assertIs(getattr(a, attr)(v), NotImplemented)
3190
3191 # Released views compare equal to themselves:
3192 v = memoryview(a)
3193 v.release()
3194 self.assertEqual(v, v)
3195 self.assertNotEqual(v, a)
3196 self.assertNotEqual(a, v)
3197
3198 v = memoryview(a)
3199 w = memoryview(a)
3200 w.release()
3201 self.assertNotEqual(v, w)
3202 self.assertNotEqual(w, v)
3203
3204 # Operand does not implement the buffer protocol:
3205 v = memoryview(a)
3206 self.assertNotEqual(v, [1, 2, 3])
3207
3208 # NaNs
3209 nd = ndarray([(0, 0)], shape=[1], format='l x d x', flags=ND_WRITABLE)
3210 nd[0] = (-1, float('nan'))
3211 self.assertNotEqual(memoryview(nd), nd)
3212
3213 # Depends on issue #15625: the struct module does not understand 'u'.
3214 a = array.array('u', 'xyz')
3215 v = memoryview(a)
3216 self.assertNotEqual(a, v)
3217 self.assertNotEqual(v, a)
3218
3219 # Some ctypes format strings are unknown to the struct module.
3220 if ctypes:
3221 # format: "T{>l:x:>l:y:}"
3222 class BEPoint(ctypes.BigEndianStructure):
3223 _fields_ = [("x", ctypes.c_long), ("y", ctypes.c_long)]
3224 point = BEPoint(100, 200)
3225 a = memoryview(point)
3226 b = memoryview(point)
3227 self.assertNotEqual(a, b)
3228 self.assertNotEqual(a, point)
3229 self.assertNotEqual(point, a)
3230 self.assertRaises(NotImplementedError, a.tolist)
3231
3232 def test_memoryview_compare_ndim_zero(self):
3233
3234 nd1 = ndarray(1729, shape=[], format='@L')
3235 nd2 = ndarray(1729, shape=[], format='L', flags=ND_WRITABLE)
3236 v = memoryview(nd1)
3237 w = memoryview(nd2)
3238 self.assertEqual(v, w)
3239 self.assertEqual(w, v)
3240 self.assertEqual(v, nd2)
3241 self.assertEqual(nd2, v)
3242 self.assertEqual(w, nd1)
3243 self.assertEqual(nd1, w)
3244
3245 self.assertFalse(v.__ne__(w))
3246 self.assertFalse(w.__ne__(v))
3247
3248 w[()] = 1728
3249 self.assertNotEqual(v, w)
3250 self.assertNotEqual(w, v)
3251 self.assertNotEqual(v, nd2)
3252 self.assertNotEqual(nd2, v)
3253 self.assertNotEqual(w, nd1)
3254 self.assertNotEqual(nd1, w)
3255
3256 self.assertFalse(v.__eq__(w))
3257 self.assertFalse(w.__eq__(v))
3258
3259 nd = ndarray(list(range(12)), shape=[12], flags=ND_WRITABLE|ND_PIL)
3260 ex = ndarray(list(range(12)), shape=[12], flags=ND_WRITABLE|ND_PIL)
3261 m = memoryview(ex)
3262
3263 self.assertEqual(m, nd)
3264 m[9] = 100
3265 self.assertNotEqual(m, nd)
3266
3267 # struct module: equal
3268 nd1 = ndarray((1729, 1.2, b'12345'), shape=[], format='Lf5s')
3269 nd2 = ndarray((1729, 1.2, b'12345'), shape=[], format='hf5s',
3270 flags=ND_WRITABLE)
3271 v = memoryview(nd1)
3272 w = memoryview(nd2)
3273 self.assertEqual(v, w)
3274 self.assertEqual(w, v)
3275 self.assertEqual(v, nd2)
3276 self.assertEqual(nd2, v)
3277 self.assertEqual(w, nd1)
3278 self.assertEqual(nd1, w)
3279
3280 # struct module: not equal
3281 nd1 = ndarray((1729, 1.2, b'12345'), shape=[], format='Lf5s')
3282 nd2 = ndarray((-1729, 1.2, b'12345'), shape=[], format='hf5s',
3283 flags=ND_WRITABLE)
3284 v = memoryview(nd1)
3285 w = memoryview(nd2)
3286 self.assertNotEqual(v, w)
3287 self.assertNotEqual(w, v)
3288 self.assertNotEqual(v, nd2)
3289 self.assertNotEqual(nd2, v)
3290 self.assertNotEqual(w, nd1)
3291 self.assertNotEqual(nd1, w)
3292 self.assertEqual(v, nd1)
3293 self.assertEqual(w, nd2)
3294
3295 def test_memoryview_compare_ndim_one(self):
3296
3297 # contiguous
3298 nd1 = ndarray([-529, 576, -625, 676, -729], shape=[5], format='@h')
3299 nd2 = ndarray([-529, 576, -625, 676, 729], shape=[5], format='@h')
3300 v = memoryview(nd1)
3301 w = memoryview(nd2)
3302
3303 self.assertEqual(v, nd1)
3304 self.assertEqual(w, nd2)
3305 self.assertNotEqual(v, nd2)
3306 self.assertNotEqual(w, nd1)
3307 self.assertNotEqual(v, w)
3308
3309 # contiguous, struct module
3310 nd1 = ndarray([-529, 576, -625, 676, -729], shape=[5], format='<i')
3311 nd2 = ndarray([-529, 576, -625, 676, 729], shape=[5], format='>h')
3312 v = memoryview(nd1)
3313 w = memoryview(nd2)
3314
3315 self.assertEqual(v, nd1)
3316 self.assertEqual(w, nd2)
3317 self.assertNotEqual(v, nd2)
3318 self.assertNotEqual(w, nd1)
3319 self.assertNotEqual(v, w)
3320
3321 # non-contiguous
3322 nd1 = ndarray([-529, -625, -729], shape=[3], format='@h')
3323 nd2 = ndarray([-529, 576, -625, 676, -729], shape=[5], format='@h')
3324 v = memoryview(nd1)
3325 w = memoryview(nd2)
3326
3327 self.assertEqual(v, nd2[::2])
3328 self.assertEqual(w[::2], nd1)
3329 self.assertEqual(v, w[::2])
3330 self.assertEqual(v[::-1], w[::-2])
3331
3332 # non-contiguous, struct module
3333 nd1 = ndarray([-529, -625, -729], shape=[3], format='!h')
3334 nd2 = ndarray([-529, 576, -625, 676, -729], shape=[5], format='<l')
3335 v = memoryview(nd1)
3336 w = memoryview(nd2)
3337
3338 self.assertEqual(v, nd2[::2])
3339 self.assertEqual(w[::2], nd1)
3340 self.assertEqual(v, w[::2])
3341 self.assertEqual(v[::-1], w[::-2])
3342
3343 # non-contiguous, suboffsets
3344 nd1 = ndarray([-529, -625, -729], shape=[3], format='@h')
3345 nd2 = ndarray([-529, 576, -625, 676, -729], shape=[5], format='@h',
3346 flags=ND_PIL)
3347 v = memoryview(nd1)
3348 w = memoryview(nd2)
3349
3350 self.assertEqual(v, nd2[::2])
3351 self.assertEqual(w[::2], nd1)
3352 self.assertEqual(v, w[::2])
3353 self.assertEqual(v[::-1], w[::-2])
3354
3355 # non-contiguous, suboffsets, struct module
3356 nd1 = ndarray([-529, -625, -729], shape=[3], format='h 0c')
3357 nd2 = ndarray([-529, 576, -625, 676, -729], shape=[5], format='> h',
3358 flags=ND_PIL)
3359 v = memoryview(nd1)
3360 w = memoryview(nd2)
3361
3362 self.assertEqual(v, nd2[::2])
3363 self.assertEqual(w[::2], nd1)
3364 self.assertEqual(v, w[::2])
3365 self.assertEqual(v[::-1], w[::-2])
3366
3367 def test_memoryview_compare_zero_shape(self):
3368
3369 # zeros in shape
3370 nd1 = ndarray([900, 961], shape=[0], format='@h')
3371 nd2 = ndarray([-900, -961], shape=[0], format='@h')
3372 v = memoryview(nd1)
3373 w = memoryview(nd2)
3374
3375 self.assertEqual(v, nd1)
3376 self.assertEqual(w, nd2)
3377 self.assertEqual(v, nd2)
3378 self.assertEqual(w, nd1)
3379 self.assertEqual(v, w)
3380
3381 # zeros in shape, struct module
3382 nd1 = ndarray([900, 961], shape=[0], format='= h0c')
3383 nd2 = ndarray([-900, -961], shape=[0], format='@ i')
3384 v = memoryview(nd1)
3385 w = memoryview(nd2)
3386
3387 self.assertEqual(v, nd1)
3388 self.assertEqual(w, nd2)
3389 self.assertEqual(v, nd2)
3390 self.assertEqual(w, nd1)
3391 self.assertEqual(v, w)
3392
3393 def test_memoryview_compare_zero_strides(self):
3394
3395 # zero strides
3396 nd1 = ndarray([900, 900, 900, 900], shape=[4], format='@L')
3397 nd2 = ndarray([900], shape=[4], strides=[0], format='L')
3398 v = memoryview(nd1)
3399 w = memoryview(nd2)
3400
3401 self.assertEqual(v, nd1)
3402 self.assertEqual(w, nd2)
3403 self.assertEqual(v, nd2)
3404 self.assertEqual(w, nd1)
3405 self.assertEqual(v, w)
3406
3407 # zero strides, struct module
3408 nd1 = ndarray([(900, 900)]*4, shape=[4], format='@ Li')
3409 nd2 = ndarray([(900, 900)], shape=[4], strides=[0], format='!L h')
3410 v = memoryview(nd1)
3411 w = memoryview(nd2)
3412
3413 self.assertEqual(v, nd1)
3414 self.assertEqual(w, nd2)
3415 self.assertEqual(v, nd2)
3416 self.assertEqual(w, nd1)
3417 self.assertEqual(v, w)
3418
3419 def test_memoryview_compare_random_formats(self):
3420
3421 # random single character native formats
3422 n = 10
3423 for char in fmtdict['@m']:
3424 fmt, items, singleitem = randitems(n, 'memoryview', '@', char)
3425 for flags in (0, ND_PIL):
3426 nd = ndarray(items, shape=[n], format=fmt, flags=flags)
3427 m = memoryview(nd)
3428 self.assertEqual(m, nd)
3429
3430 nd = nd[::-3]
3431 m = memoryview(nd)
3432 self.assertEqual(m, nd)
3433
3434 # random formats
3435 n = 10
3436 for _ in range(100):
3437 fmt, items, singleitem = randitems(n)
3438 for flags in (0, ND_PIL):
3439 nd = ndarray(items, shape=[n], format=fmt, flags=flags)
3440 m = memoryview(nd)
3441 self.assertEqual(m, nd)
3442
3443 nd = nd[::-3]
3444 m = memoryview(nd)
3445 self.assertEqual(m, nd)
3446
3447 def test_memoryview_compare_multidim_c(self):
3448
3449 # C-contiguous, different values
3450 nd1 = ndarray(list(range(-15, 15)), shape=[3, 2, 5], format='@h')
3451 nd2 = ndarray(list(range(0, 30)), shape=[3, 2, 5], format='@h')
3452 v = memoryview(nd1)
3453 w = memoryview(nd2)
3454
3455 self.assertEqual(v, nd1)
3456 self.assertEqual(w, nd2)
3457 self.assertNotEqual(v, nd2)
3458 self.assertNotEqual(w, nd1)
3459 self.assertNotEqual(v, w)
3460
3461 # C-contiguous, different values, struct module
3462 nd1 = ndarray([(0, 1, 2)]*30, shape=[3, 2, 5], format='=f q xxL')
3463 nd2 = ndarray([(-1.2, 1, 2)]*30, shape=[3, 2, 5], format='< f 2Q')
3464 v = memoryview(nd1)
3465 w = memoryview(nd2)
3466
3467 self.assertEqual(v, nd1)
3468 self.assertEqual(w, nd2)
3469 self.assertNotEqual(v, nd2)
3470 self.assertNotEqual(w, nd1)
3471 self.assertNotEqual(v, w)
3472
3473 # C-contiguous, different shape
3474 nd1 = ndarray(list(range(30)), shape=[2, 3, 5], format='L')
3475 nd2 = ndarray(list(range(30)), shape=[3, 2, 5], format='L')
3476 v = memoryview(nd1)
3477 w = memoryview(nd2)
3478
3479 self.assertEqual(v, nd1)
3480 self.assertEqual(w, nd2)
3481 self.assertNotEqual(v, nd2)
3482 self.assertNotEqual(w, nd1)
3483 self.assertNotEqual(v, w)
3484
3485 # C-contiguous, different shape, struct module
3486 nd1 = ndarray([(0, 1, 2)]*21, shape=[3, 7], format='! b B xL')
3487 nd2 = ndarray([(0, 1, 2)]*21, shape=[7, 3], format='= Qx l xxL')
3488 v = memoryview(nd1)
3489 w = memoryview(nd2)
3490
3491 self.assertEqual(v, nd1)
3492 self.assertEqual(w, nd2)
3493 self.assertNotEqual(v, nd2)
3494 self.assertNotEqual(w, nd1)
3495 self.assertNotEqual(v, w)
3496
3497 # C-contiguous, different format, struct module
3498 nd1 = ndarray(list(range(30)), shape=[2, 3, 5], format='L')
3499 nd2 = ndarray(list(range(30)), shape=[2, 3, 5], format='l')
3500 v = memoryview(nd1)
3501 w = memoryview(nd2)
3502
3503 self.assertEqual(v, nd1)
3504 self.assertEqual(w, nd2)
3505 self.assertEqual(v, nd2)
3506 self.assertEqual(w, nd1)
3507 self.assertEqual(v, w)
3508
3509 def test_memoryview_compare_multidim_fortran(self):
3510
3511 # Fortran-contiguous, different values
3512 nd1 = ndarray(list(range(-15, 15)), shape=[5, 2, 3], format='@h',
3513 flags=ND_FORTRAN)
3514 nd2 = ndarray(list(range(0, 30)), shape=[5, 2, 3], format='@h',
3515 flags=ND_FORTRAN)
3516 v = memoryview(nd1)
3517 w = memoryview(nd2)
3518
3519 self.assertEqual(v, nd1)
3520 self.assertEqual(w, nd2)
3521 self.assertNotEqual(v, nd2)
3522 self.assertNotEqual(w, nd1)
3523 self.assertNotEqual(v, w)
3524
3525 # Fortran-contiguous, different values, struct module
3526 nd1 = ndarray([(2**64-1, -1)]*6, shape=[2, 3], format='=Qq',
3527 flags=ND_FORTRAN)
3528 nd2 = ndarray([(-1, 2**64-1)]*6, shape=[2, 3], format='=qQ',
3529 flags=ND_FORTRAN)
3530 v = memoryview(nd1)
3531 w = memoryview(nd2)
3532
3533 self.assertEqual(v, nd1)
3534 self.assertEqual(w, nd2)
3535 self.assertNotEqual(v, nd2)
3536 self.assertNotEqual(w, nd1)
3537 self.assertNotEqual(v, w)
3538
3539 # Fortran-contiguous, different shape
3540 nd1 = ndarray(list(range(-15, 15)), shape=[2, 3, 5], format='l',
3541 flags=ND_FORTRAN)
3542 nd2 = ndarray(list(range(-15, 15)), shape=[3, 2, 5], format='l',
3543 flags=ND_FORTRAN)
3544 v = memoryview(nd1)
3545 w = memoryview(nd2)
3546
3547 self.assertEqual(v, nd1)
3548 self.assertEqual(w, nd2)
3549 self.assertNotEqual(v, nd2)
3550 self.assertNotEqual(w, nd1)
3551 self.assertNotEqual(v, w)
3552
3553 # Fortran-contiguous, different shape, struct module
3554 nd1 = ndarray(list(range(-15, 15)), shape=[2, 3, 5], format='0ll',
3555 flags=ND_FORTRAN)
3556 nd2 = ndarray(list(range(-15, 15)), shape=[3, 2, 5], format='l',
3557 flags=ND_FORTRAN)
3558 v = memoryview(nd1)
3559 w = memoryview(nd2)
3560
3561 self.assertEqual(v, nd1)
3562 self.assertEqual(w, nd2)
3563 self.assertNotEqual(v, nd2)
3564 self.assertNotEqual(w, nd1)
3565 self.assertNotEqual(v, w)
3566
3567 # Fortran-contiguous, different format, struct module
3568 nd1 = ndarray(list(range(30)), shape=[5, 2, 3], format='@h',
3569 flags=ND_FORTRAN)
3570 nd2 = ndarray(list(range(30)), shape=[5, 2, 3], format='@b',
3571 flags=ND_FORTRAN)
3572 v = memoryview(nd1)
3573 w = memoryview(nd2)
3574
3575 self.assertEqual(v, nd1)
3576 self.assertEqual(w, nd2)
3577 self.assertEqual(v, nd2)
3578 self.assertEqual(w, nd1)
3579 self.assertEqual(v, w)
3580
3581 def test_memoryview_compare_multidim_mixed(self):
3582
3583 # mixed C/Fortran contiguous
3584 lst1 = list(range(-15, 15))
3585 lst2 = transpose(lst1, [3, 2, 5])
3586 nd1 = ndarray(lst1, shape=[3, 2, 5], format='@l')
3587 nd2 = ndarray(lst2, shape=[3, 2, 5], format='l', flags=ND_FORTRAN)
3588 v = memoryview(nd1)
3589 w = memoryview(nd2)
3590
3591 self.assertEqual(v, nd1)
3592 self.assertEqual(w, nd2)
3593 self.assertEqual(v, w)
3594
3595 # mixed C/Fortran contiguous, struct module
3596 lst1 = [(-3.3, -22, b'x')]*30
3597 lst1[5] = (-2.2, -22, b'x')
3598 lst2 = transpose(lst1, [3, 2, 5])
3599 nd1 = ndarray(lst1, shape=[3, 2, 5], format='d b c')
3600 nd2 = ndarray(lst2, shape=[3, 2, 5], format='d h c', flags=ND_FORTRAN)
3601 v = memoryview(nd1)
3602 w = memoryview(nd2)
3603
3604 self.assertEqual(v, nd1)
3605 self.assertEqual(w, nd2)
3606 self.assertEqual(v, w)
3607
3608 # different values, non-contiguous
3609 ex1 = ndarray(list(range(40)), shape=[5, 8], format='@I')
3610 nd1 = ex1[3:1:-1, ::-2]
3611 ex2 = ndarray(list(range(40)), shape=[5, 8], format='I')
3612 nd2 = ex2[1:3:1, ::-2]
3613 v = memoryview(nd1)
3614 w = memoryview(nd2)
3615
3616 self.assertEqual(v, nd1)
3617 self.assertEqual(w, nd2)
3618 self.assertNotEqual(v, nd2)
3619 self.assertNotEqual(w, nd1)
3620 self.assertNotEqual(v, w)
3621
3622 # same values, non-contiguous, struct module
3623 ex1 = ndarray([(2**31-1, -2**31)]*22, shape=[11, 2], format='=ii')
3624 nd1 = ex1[3:1:-1, ::-2]
3625 ex2 = ndarray([(2**31-1, -2**31)]*22, shape=[11, 2], format='>ii')
3626 nd2 = ex2[1:3:1, ::-2]
3627 v = memoryview(nd1)
3628 w = memoryview(nd2)
3629
3630 self.assertEqual(v, nd1)
3631 self.assertEqual(w, nd2)
3632 self.assertEqual(v, nd2)
3633 self.assertEqual(w, nd1)
3634 self.assertEqual(v, w)
3635
3636 # different shape
3637 ex1 = ndarray(list(range(30)), shape=[2, 3, 5], format='b')
3638 nd1 = ex1[1:3:, ::-2]
3639 nd2 = ndarray(list(range(30)), shape=[3, 2, 5], format='b')
3640 nd2 = ex2[1:3:, ::-2]
3641 v = memoryview(nd1)
3642 w = memoryview(nd2)
3643
3644 self.assertEqual(v, nd1)
3645 self.assertEqual(w, nd2)
3646 self.assertNotEqual(v, nd2)
3647 self.assertNotEqual(w, nd1)
3648 self.assertNotEqual(v, w)
3649
3650 # different shape, struct module
3651 ex1 = ndarray(list(range(30)), shape=[2, 3, 5], format='B')
3652 nd1 = ex1[1:3:, ::-2]
3653 nd2 = ndarray(list(range(30)), shape=[3, 2, 5], format='b')
3654 nd2 = ex2[1:3:, ::-2]
3655 v = memoryview(nd1)
3656 w = memoryview(nd2)
3657
3658 self.assertEqual(v, nd1)
3659 self.assertEqual(w, nd2)
3660 self.assertNotEqual(v, nd2)
3661 self.assertNotEqual(w, nd1)
3662 self.assertNotEqual(v, w)
3663
3664 # different format, struct module
3665 ex1 = ndarray([(2, b'123')]*30, shape=[5, 3, 2], format='b3s')
3666 nd1 = ex1[1:3:, ::-2]
3667 nd2 = ndarray([(2, b'123')]*30, shape=[5, 3, 2], format='i3s')
3668 nd2 = ex2[1:3:, ::-2]
3669 v = memoryview(nd1)
3670 w = memoryview(nd2)
3671
3672 self.assertEqual(v, nd1)
3673 self.assertEqual(w, nd2)
3674 self.assertNotEqual(v, nd2)
3675 self.assertNotEqual(w, nd1)
3676 self.assertNotEqual(v, w)
3677
3678 def test_memoryview_compare_multidim_zero_shape(self):
3679
3680 # zeros in shape
3681 nd1 = ndarray(list(range(30)), shape=[0, 3, 2], format='i')
3682 nd2 = ndarray(list(range(30)), shape=[5, 0, 2], format='@i')
3683 v = memoryview(nd1)
3684 w = memoryview(nd2)
3685
3686 self.assertEqual(v, nd1)
3687 self.assertEqual(w, nd2)
3688 self.assertNotEqual(v, nd2)
3689 self.assertNotEqual(w, nd1)
3690 self.assertNotEqual(v, w)
3691
3692 # zeros in shape, struct module
3693 nd1 = ndarray(list(range(30)), shape=[0, 3, 2], format='i')
3694 nd2 = ndarray(list(range(30)), shape=[5, 0, 2], format='@i')
3695 v = memoryview(nd1)
3696 w = memoryview(nd2)
3697
3698 self.assertEqual(v, nd1)
3699 self.assertEqual(w, nd2)
3700 self.assertNotEqual(v, nd2)
3701 self.assertNotEqual(w, nd1)
3702 self.assertNotEqual(v, w)
3703
3704 def test_memoryview_compare_multidim_zero_strides(self):
3705
3706 # zero strides
3707 nd1 = ndarray([900]*80, shape=[4, 5, 4], format='@L')
3708 nd2 = ndarray([900], shape=[4, 5, 4], strides=[0, 0, 0], format='L')
3709 v = memoryview(nd1)
3710 w = memoryview(nd2)
3711
3712 self.assertEqual(v, nd1)
3713 self.assertEqual(w, nd2)
3714 self.assertEqual(v, nd2)
3715 self.assertEqual(w, nd1)
3716 self.assertEqual(v, w)
3717 self.assertEqual(v.tolist(), w.tolist())
3718
3719 # zero strides, struct module
3720 nd1 = ndarray([(1, 2)]*10, shape=[2, 5], format='=lQ')
3721 nd2 = ndarray([(1, 2)], shape=[2, 5], strides=[0, 0], format='<lQ')
3722 v = memoryview(nd1)
3723 w = memoryview(nd2)
3724
3725 self.assertEqual(v, nd1)
3726 self.assertEqual(w, nd2)
3727 self.assertEqual(v, nd2)
3728 self.assertEqual(w, nd1)
3729 self.assertEqual(v, w)
3730
3731 def test_memoryview_compare_multidim_suboffsets(self):
3732
3733 # suboffsets
3734 ex1 = ndarray(list(range(40)), shape=[5, 8], format='@I')
3735 nd1 = ex1[3:1:-1, ::-2]
3736 ex2 = ndarray(list(range(40)), shape=[5, 8], format='I', flags=ND_PIL)
3737 nd2 = ex2[1:3:1, ::-2]
3738 v = memoryview(nd1)
3739 w = memoryview(nd2)
3740
3741 self.assertEqual(v, nd1)
3742 self.assertEqual(w, nd2)
3743 self.assertNotEqual(v, nd2)
3744 self.assertNotEqual(w, nd1)
3745 self.assertNotEqual(v, w)
3746
3747 # suboffsets, struct module
3748 ex1 = ndarray([(2**64-1, -1)]*40, shape=[5, 8], format='=Qq',
3749 flags=ND_WRITABLE)
3750 ex1[2][7] = (1, -2)
3751 nd1 = ex1[3:1:-1, ::-2]
3752
3753 ex2 = ndarray([(2**64-1, -1)]*40, shape=[5, 8], format='>Qq',
3754 flags=ND_PIL|ND_WRITABLE)
3755 ex2[2][7] = (1, -2)
3756 nd2 = ex2[1:3:1, ::-2]
3757
3758 v = memoryview(nd1)
3759 w = memoryview(nd2)
3760
3761 self.assertEqual(v, nd1)
3762 self.assertEqual(w, nd2)
3763 self.assertEqual(v, nd2)
3764 self.assertEqual(w, nd1)
3765 self.assertEqual(v, w)
3766
3767 # suboffsets, different shape
3768 ex1 = ndarray(list(range(30)), shape=[2, 3, 5], format='b',
3769 flags=ND_PIL)
3770 nd1 = ex1[1:3:, ::-2]
3771 nd2 = ndarray(list(range(30)), shape=[3, 2, 5], format='b')
3772 nd2 = ex2[1:3:, ::-2]
3773 v = memoryview(nd1)
3774 w = memoryview(nd2)
3775
3776 self.assertEqual(v, nd1)
3777 self.assertEqual(w, nd2)
3778 self.assertNotEqual(v, nd2)
3779 self.assertNotEqual(w, nd1)
3780 self.assertNotEqual(v, w)
3781
3782 # suboffsets, different shape, struct module
3783 ex1 = ndarray([(2**8-1, -1)]*40, shape=[2, 3, 5], format='Bb',
3784 flags=ND_PIL|ND_WRITABLE)
3785 nd1 = ex1[1:2:, ::-2]
3786
3787 ex2 = ndarray([(2**8-1, -1)]*40, shape=[3, 2, 5], format='Bb')
3788 nd2 = ex2[1:2:, ::-2]
3789
3790 v = memoryview(nd1)
3791 w = memoryview(nd2)
3792
3793 self.assertEqual(v, nd1)
3794 self.assertEqual(w, nd2)
3795 self.assertNotEqual(v, nd2)
3796 self.assertNotEqual(w, nd1)
3797 self.assertNotEqual(v, w)
3798
3799 # suboffsets, different format
3800 ex1 = ndarray(list(range(30)), shape=[5, 3, 2], format='i', flags=ND_PIL)
3801 nd1 = ex1[1:3:, ::-2]
3802 ex2 = ndarray(list(range(30)), shape=[5, 3, 2], format='@I', flags=ND_PIL)
3803 nd2 = ex2[1:3:, ::-2]
3804 v = memoryview(nd1)
3805 w = memoryview(nd2)
3806
3807 self.assertEqual(v, nd1)
3808 self.assertEqual(w, nd2)
3809 self.assertEqual(v, nd2)
3810 self.assertEqual(w, nd1)
3811 self.assertEqual(v, w)
3812
3813 # suboffsets, different format, struct module
3814 ex1 = ndarray([(b'hello', b'', 1)]*27, shape=[3, 3, 3], format='5s0sP',
3815 flags=ND_PIL|ND_WRITABLE)
3816 ex1[1][2][2] = (b'sushi', b'', 1)
3817 nd1 = ex1[1:3:, ::-2]
3818
3819 ex2 = ndarray([(b'hello', b'', 1)]*27, shape=[3, 3, 3], format='5s0sP',
3820 flags=ND_PIL|ND_WRITABLE)
3821 ex1[1][2][2] = (b'sushi', b'', 1)
3822 nd2 = ex2[1:3:, ::-2]
3823
3824 v = memoryview(nd1)
3825 w = memoryview(nd2)
3826
3827 self.assertEqual(v, nd1)
3828 self.assertEqual(w, nd2)
3829 self.assertNotEqual(v, nd2)
3830 self.assertNotEqual(w, nd1)
3831 self.assertNotEqual(v, w)
3832
3833 # initialize mixed C/Fortran + suboffsets
3834 lst1 = list(range(-15, 15))
3835 lst2 = transpose(lst1, [3, 2, 5])
3836 nd1 = ndarray(lst1, shape=[3, 2, 5], format='@l', flags=ND_PIL)
3837 nd2 = ndarray(lst2, shape=[3, 2, 5], format='l', flags=ND_FORTRAN|ND_PIL)
3838 v = memoryview(nd1)
3839 w = memoryview(nd2)
3840
3841 self.assertEqual(v, nd1)
3842 self.assertEqual(w, nd2)
3843 self.assertEqual(v, w)
3844
3845 # initialize mixed C/Fortran + suboffsets, struct module
3846 lst1 = [(b'sashimi', b'sliced', 20.05)]*30
3847 lst1[11] = (b'ramen', b'spicy', 9.45)
3848 lst2 = transpose(lst1, [3, 2, 5])
3849
3850 nd1 = ndarray(lst1, shape=[3, 2, 5], format='< 10p 9p d', flags=ND_PIL)
3851 nd2 = ndarray(lst2, shape=[3, 2, 5], format='> 10p 9p d',
3852 flags=ND_FORTRAN|ND_PIL)
3853 v = memoryview(nd1)
3854 w = memoryview(nd2)
3855
3856 self.assertEqual(v, nd1)
3857 self.assertEqual(w, nd2)
3858 self.assertEqual(v, w)
3859
3860 def test_memoryview_compare_not_equal(self):
3861
3862 # items not equal
3863 for byteorder in ['=', '<', '>', '!']:
3864 x = ndarray([2**63]*120, shape=[3,5,2,2,2], format=byteorder+'Q')
3865 y = ndarray([2**63]*120, shape=[3,5,2,2,2], format=byteorder+'Q',
3866 flags=ND_WRITABLE|ND_FORTRAN)
3867 y[2][3][1][1][1] = 1
3868 a = memoryview(x)
3869 b = memoryview(y)
3870 self.assertEqual(a, x)
3871 self.assertEqual(b, y)
3872 self.assertNotEqual(a, b)
3873 self.assertNotEqual(a, y)
3874 self.assertNotEqual(b, x)
3875
3876 x = ndarray([(2**63, 2**31, 2**15)]*120, shape=[3,5,2,2,2],
3877 format=byteorder+'QLH')
3878 y = ndarray([(2**63, 2**31, 2**15)]*120, shape=[3,5,2,2,2],
3879 format=byteorder+'QLH', flags=ND_WRITABLE|ND_FORTRAN)
3880 y[2][3][1][1][1] = (1, 1, 1)
3881 a = memoryview(x)
3882 b = memoryview(y)
3883 self.assertEqual(a, x)
3884 self.assertEqual(b, y)
3885 self.assertNotEqual(a, b)
3886 self.assertNotEqual(a, y)
3887 self.assertNotEqual(b, x)
3888
3889 def test_memoryview_check_released(self):
3890
3891 a = array.array('d', [1.1, 2.2, 3.3])
3892
3893 m = memoryview(a)
3894 m.release()
3895
3896 # PyMemoryView_FromObject()
3897 self.assertRaises(ValueError, memoryview, m)
3898 # memoryview.cast()
3899 self.assertRaises(ValueError, m.cast, 'c')
3900 # getbuffer()
3901 self.assertRaises(ValueError, ndarray, m)
3902 # memoryview.tolist()
3903 self.assertRaises(ValueError, m.tolist)
3904 # memoryview.tobytes()
3905 self.assertRaises(ValueError, m.tobytes)
3906 # sequence
3907 self.assertRaises(ValueError, eval, "1.0 in m", locals())
3908 # subscript
3909 self.assertRaises(ValueError, m.__getitem__, 0)
3910 # assignment
3911 self.assertRaises(ValueError, m.__setitem__, 0, 1)
3912
3913 for attr in ('obj', 'nbytes', 'readonly', 'itemsize', 'format', 'ndim',
3914 'shape', 'strides', 'suboffsets', 'c_contiguous',
3915 'f_contiguous', 'contiguous'):
3916 self.assertRaises(ValueError, m.__getattribute__, attr)
3917
3918 # richcompare
3919 b = array.array('d', [1.1, 2.2, 3.3])
3920 m1 = memoryview(a)
3921 m2 = memoryview(b)
3922
3923 self.assertEqual(m1, m2)
3924 m1.release()
3925 self.assertNotEqual(m1, m2)
3926 self.assertNotEqual(m1, a)
3927 self.assertEqual(m1, m1)
3928
3929 def test_memoryview_tobytes(self):
3930 # Many implicit tests are already in self.verify().
3931
3932 t = (-529, 576, -625, 676, -729)
3933
3934 nd = ndarray(t, shape=[5], format='@h')
3935 m = memoryview(nd)
3936 self.assertEqual(m, nd)
3937 self.assertEqual(m.tobytes(), nd.tobytes())
3938
3939 nd = ndarray([t], shape=[1], format='>hQiLl')
3940 m = memoryview(nd)
3941 self.assertEqual(m, nd)
3942 self.assertEqual(m.tobytes(), nd.tobytes())
3943
3944 nd = ndarray([t for _ in range(12)], shape=[2,2,3], format='=hQiLl')
3945 m = memoryview(nd)
3946 self.assertEqual(m, nd)
3947 self.assertEqual(m.tobytes(), nd.tobytes())
3948
3949 nd = ndarray([t for _ in range(120)], shape=[5,2,2,3,2],
3950 format='<hQiLl')
3951 m = memoryview(nd)
3952 self.assertEqual(m, nd)
3953 self.assertEqual(m.tobytes(), nd.tobytes())
3954
3955 # Unknown formats are handled: tobytes() purely depends on itemsize.
3956 if ctypes:
3957 # format: "T{>l:x:>l:y:}"
3958 class BEPoint(ctypes.BigEndianStructure):
3959 _fields_ = [("x", ctypes.c_long), ("y", ctypes.c_long)]
3960 point = BEPoint(100, 200)
3961 a = memoryview(point)
3962 self.assertEqual(a.tobytes(), bytes(point))
3963
3964 def test_memoryview_get_contiguous(self):
3965 # Many implicit tests are already in self.verify().
3966
3967 # no buffer interface
3968 self.assertRaises(TypeError, get_contiguous, {}, PyBUF_READ, 'F')
3969
3970 # writable request to read-only object
3971 self.assertRaises(BufferError, get_contiguous, b'x', PyBUF_WRITE, 'C')
3972
3973 # writable request to non-contiguous object
3974 nd = ndarray([1, 2, 3], shape=[2], strides=[2])
3975 self.assertRaises(BufferError, get_contiguous, nd, PyBUF_WRITE, 'A')
3976
3977 # scalar, read-only request from read-only exporter
3978 nd = ndarray(9, shape=(), format="L")
3979 for order in ['C', 'F', 'A']:
3980 m = get_contiguous(nd, PyBUF_READ, order)
3981 self.assertEqual(m, nd)
3982 self.assertEqual(m[()], 9)
3983
3984 # scalar, read-only request from writable exporter
3985 nd = ndarray(9, shape=(), format="L", flags=ND_WRITABLE)
3986 for order in ['C', 'F', 'A']:
3987 m = get_contiguous(nd, PyBUF_READ, order)
3988 self.assertEqual(m, nd)
3989 self.assertEqual(m[()], 9)
3990
3991 # scalar, writable request
3992 for order in ['C', 'F', 'A']:
3993 nd[()] = 9
3994 m = get_contiguous(nd, PyBUF_WRITE, order)
3995 self.assertEqual(m, nd)
3996 self.assertEqual(m[()], 9)
3997
3998 m[()] = 10
3999 self.assertEqual(m[()], 10)
4000 self.assertEqual(nd[()], 10)
4001
4002 # zeros in shape
4003 nd = ndarray([1], shape=[0], format="L", flags=ND_WRITABLE)
4004 for order in ['C', 'F', 'A']:
4005 m = get_contiguous(nd, PyBUF_READ, order)
4006 self.assertRaises(IndexError, m.__getitem__, 0)
4007 self.assertEqual(m, nd)
4008 self.assertEqual(m.tolist(), [])
4009
4010 nd = ndarray(list(range(8)), shape=[2, 0, 7], format="L",
4011 flags=ND_WRITABLE)
4012 for order in ['C', 'F', 'A']:
4013 m = get_contiguous(nd, PyBUF_READ, order)
4014 self.assertEqual(ndarray(m).tolist(), [[], []])
4015
4016 # one-dimensional
4017 nd = ndarray([1], shape=[1], format="h", flags=ND_WRITABLE)
4018 for order in ['C', 'F', 'A']:
4019 m = get_contiguous(nd, PyBUF_WRITE, order)
4020 self.assertEqual(m, nd)
4021 self.assertEqual(m.tolist(), nd.tolist())
4022
4023 nd = ndarray([1, 2, 3], shape=[3], format="b", flags=ND_WRITABLE)
4024 for order in ['C', 'F', 'A']:
4025 m = get_contiguous(nd, PyBUF_WRITE, order)
4026 self.assertEqual(m, nd)
4027 self.assertEqual(m.tolist(), nd.tolist())
4028
4029 # one-dimensional, non-contiguous
4030 nd = ndarray([1, 2, 3], shape=[2], strides=[2], flags=ND_WRITABLE)
4031 for order in ['C', 'F', 'A']:
4032 m = get_contiguous(nd, PyBUF_READ, order)
4033 self.assertEqual(m, nd)
4034 self.assertEqual(m.tolist(), nd.tolist())
4035 self.assertRaises(TypeError, m.__setitem__, 1, 20)
4036 self.assertEqual(m[1], 3)
4037 self.assertEqual(nd[1], 3)
4038
4039 nd = nd[::-1]
4040 for order in ['C', 'F', 'A']:
4041 m = get_contiguous(nd, PyBUF_READ, order)
4042 self.assertEqual(m, nd)
4043 self.assertEqual(m.tolist(), nd.tolist())
4044 self.assertRaises(TypeError, m.__setitem__, 1, 20)
4045 self.assertEqual(m[1], 1)
4046 self.assertEqual(nd[1], 1)
4047
4048 # multi-dimensional, contiguous input
4049 nd = ndarray(list(range(12)), shape=[3, 4], flags=ND_WRITABLE)
4050 for order in ['C', 'A']:
4051 m = get_contiguous(nd, PyBUF_WRITE, order)
4052 self.assertEqual(ndarray(m).tolist(), nd.tolist())
4053
4054 self.assertRaises(BufferError, get_contiguous, nd, PyBUF_WRITE, 'F')
4055 m = get_contiguous(nd, PyBUF_READ, order)
4056 self.assertEqual(ndarray(m).tolist(), nd.tolist())
4057
4058 nd = ndarray(list(range(12)), shape=[3, 4],
4059 flags=ND_WRITABLE|ND_FORTRAN)
4060 for order in ['F', 'A']:
4061 m = get_contiguous(nd, PyBUF_WRITE, order)
4062 self.assertEqual(ndarray(m).tolist(), nd.tolist())
4063
4064 self.assertRaises(BufferError, get_contiguous, nd, PyBUF_WRITE, 'C')
4065 m = get_contiguous(nd, PyBUF_READ, order)
4066 self.assertEqual(ndarray(m).tolist(), nd.tolist())
4067
4068 # multi-dimensional, non-contiguous input
4069 nd = ndarray(list(range(12)), shape=[3, 4], flags=ND_WRITABLE|ND_PIL)
4070 for order in ['C', 'F', 'A']:
4071 self.assertRaises(BufferError, get_contiguous, nd, PyBUF_WRITE,
4072 order)
4073 m = get_contiguous(nd, PyBUF_READ, order)
4074 self.assertEqual(ndarray(m).tolist(), nd.tolist())
4075
4076 # flags
4077 nd = ndarray([1,2,3,4,5], shape=[3], strides=[2])
4078 m = get_contiguous(nd, PyBUF_READ, 'C')
4079 self.assertTrue(m.c_contiguous)
4080
4081 def test_memoryview_serializing(self):
4082
4083 # C-contiguous
4084 size = struct.calcsize('i')
4085 a = array.array('i', [1,2,3,4,5])
4086 m = memoryview(a)
4087 buf = io.BytesIO(m)
4088 b = bytearray(5*size)
4089 buf.readinto(b)
4090 self.assertEqual(m.tobytes(), b)
4091
4092 # C-contiguous, multi-dimensional
4093 size = struct.calcsize('L')
4094 nd = ndarray(list(range(12)), shape=[2,3,2], format="L")
4095 m = memoryview(nd)
4096 buf = io.BytesIO(m)
4097 b = bytearray(2*3*2*size)
4098 buf.readinto(b)
4099 self.assertEqual(m.tobytes(), b)
4100
4101 # Fortran contiguous, multi-dimensional
4102 #size = struct.calcsize('L')
4103 #nd = ndarray(list(range(12)), shape=[2,3,2], format="L",
4104 # flags=ND_FORTRAN)
4105 #m = memoryview(nd)
4106 #buf = io.BytesIO(m)
4107 #b = bytearray(2*3*2*size)
4108 #buf.readinto(b)
4109 #self.assertEqual(m.tobytes(), b)
4110
4111 def test_memoryview_hash(self):
4112
4113 # bytes exporter
4114 b = bytes(list(range(12)))
4115 m = memoryview(b)
4116 self.assertEqual(hash(b), hash(m))
4117
4118 # C-contiguous
4119 mc = m.cast('c', shape=[3,4])
4120 self.assertEqual(hash(mc), hash(b))
4121
4122 # non-contiguous
4123 mx = m[::-2]
4124 b = bytes(list(range(12))[::-2])
4125 self.assertEqual(hash(mx), hash(b))
4126
4127 # Fortran contiguous
4128 nd = ndarray(list(range(30)), shape=[3,2,5], flags=ND_FORTRAN)
4129 m = memoryview(nd)
4130 self.assertEqual(hash(m), hash(nd))
4131
4132 # multi-dimensional slice
4133 nd = ndarray(list(range(30)), shape=[3,2,5])
4134 x = nd[::2, ::, ::-1]
4135 m = memoryview(x)
4136 self.assertEqual(hash(m), hash(x))
4137
4138 # multi-dimensional slice with suboffsets
4139 nd = ndarray(list(range(30)), shape=[2,5,3], flags=ND_PIL)
4140 x = nd[::2, ::, ::-1]
4141 m = memoryview(x)
4142 self.assertEqual(hash(m), hash(x))
4143
4144 # equality-hash invariant
4145 x = ndarray(list(range(12)), shape=[12], format='B')
4146 a = memoryview(x)
4147
4148 y = ndarray(list(range(12)), shape=[12], format='b')
4149 b = memoryview(y)
4150
4151 self.assertEqual(a, b)
4152 self.assertEqual(hash(a), hash(b))
4153
4154 # non-byte formats
4155 nd = ndarray(list(range(12)), shape=[2,2,3], format='L')
4156 m = memoryview(nd)
4157 self.assertRaises(ValueError, m.__hash__)
4158
4159 nd = ndarray(list(range(-6, 6)), shape=[2,2,3], format='h')
4160 m = memoryview(nd)
4161 self.assertRaises(ValueError, m.__hash__)
4162
4163 nd = ndarray(list(range(12)), shape=[2,2,3], format='= L')
4164 m = memoryview(nd)
4165 self.assertRaises(ValueError, m.__hash__)
4166
4167 nd = ndarray(list(range(-6, 6)), shape=[2,2,3], format='< h')
4168 m = memoryview(nd)
4169 self.assertRaises(ValueError, m.__hash__)
4170
4171 def test_memoryview_release(self):
4172
4173 # Create re-exporter from getbuffer(memoryview), then release the view.
4174 a = bytearray([1,2,3])
4175 m = memoryview(a)
4176 nd = ndarray(m) # re-exporter
4177 self.assertRaises(BufferError, m.release)
4178 del nd
4179 m.release()
4180
4181 a = bytearray([1,2,3])
4182 m = memoryview(a)
4183 nd1 = ndarray(m, getbuf=PyBUF_FULL_RO, flags=ND_REDIRECT)
4184 nd2 = ndarray(nd1, getbuf=PyBUF_FULL_RO, flags=ND_REDIRECT)
4185 self.assertIs(nd2.obj, m)
4186 self.assertRaises(BufferError, m.release)
4187 del nd1, nd2
4188 m.release()
4189
4190 # chained views
4191 a = bytearray([1,2,3])
4192 m1 = memoryview(a)
4193 m2 = memoryview(m1)
4194 nd = ndarray(m2) # re-exporter
4195 m1.release()
4196 self.assertRaises(BufferError, m2.release)
4197 del nd
4198 m2.release()
4199
4200 a = bytearray([1,2,3])
4201 m1 = memoryview(a)
4202 m2 = memoryview(m1)
4203 nd1 = ndarray(m2, getbuf=PyBUF_FULL_RO, flags=ND_REDIRECT)
4204 nd2 = ndarray(nd1, getbuf=PyBUF_FULL_RO, flags=ND_REDIRECT)
4205 self.assertIs(nd2.obj, m2)
4206 m1.release()
4207 self.assertRaises(BufferError, m2.release)
4208 del nd1, nd2
4209 m2.release()
4210
4211 # Allow changing layout while buffers are exported.
4212 nd = ndarray([1,2,3], shape=[3], flags=ND_VAREXPORT)
4213 m1 = memoryview(nd)
4214
4215 nd.push([4,5,6,7,8], shape=[5]) # mutate nd
4216 m2 = memoryview(nd)
4217
4218 x = memoryview(m1)
4219 self.assertEqual(x.tolist(), m1.tolist())
4220
4221 y = memoryview(m2)
4222 self.assertEqual(y.tolist(), m2.tolist())
4223 self.assertEqual(y.tolist(), nd.tolist())
4224 m2.release()
4225 y.release()
4226
4227 nd.pop() # pop the current view
4228 self.assertEqual(x.tolist(), nd.tolist())
4229
4230 del nd
4231 m1.release()
4232 x.release()
4233
4234 # If multiple memoryviews share the same managed buffer, implicit
4235 # release() in the context manager's __exit__() method should still
4236 # work.
4237 def catch22(b):
4238 with memoryview(b) as m2:
4239 pass
4240
4241 x = bytearray(b'123')
4242 with memoryview(x) as m1:
4243 catch22(m1)
4244 self.assertEqual(m1[0], ord(b'1'))
4245
4246 x = ndarray(list(range(12)), shape=[2,2,3], format='l')
4247 y = ndarray(x, getbuf=PyBUF_FULL_RO, flags=ND_REDIRECT)
4248 z = ndarray(y, getbuf=PyBUF_FULL_RO, flags=ND_REDIRECT)
4249 self.assertIs(z.obj, x)
4250 with memoryview(z) as m:
4251 catch22(m)
4252 self.assertEqual(m[0:1].tolist(), [[[0, 1, 2], [3, 4, 5]]])
4253
4254 # Test garbage collection.
4255 for flags in (0, ND_REDIRECT):
4256 x = bytearray(b'123')
4257 with memoryview(x) as m1:
4258 del x
4259 y = ndarray(m1, getbuf=PyBUF_FULL_RO, flags=flags)
4260 with memoryview(y) as m2:
4261 del y
4262 z = ndarray(m2, getbuf=PyBUF_FULL_RO, flags=flags)
4263 with memoryview(z) as m3:
4264 del z
4265 catch22(m3)
4266 catch22(m2)
4267 catch22(m1)
4268 self.assertEqual(m1[0], ord(b'1'))
4269 self.assertEqual(m2[1], ord(b'2'))
4270 self.assertEqual(m3[2], ord(b'3'))
4271 del m3
4272 del m2
4273 del m1
4274
4275 x = bytearray(b'123')
4276 with memoryview(x) as m1:
4277 del x
4278 y = ndarray(m1, getbuf=PyBUF_FULL_RO, flags=flags)
4279 with memoryview(y) as m2:
4280 del y
4281 z = ndarray(m2, getbuf=PyBUF_FULL_RO, flags=flags)
4282 with memoryview(z) as m3:
4283 del z
4284 catch22(m1)
4285 catch22(m2)
4286 catch22(m3)
4287 self.assertEqual(m1[0], ord(b'1'))
4288 self.assertEqual(m2[1], ord(b'2'))
4289 self.assertEqual(m3[2], ord(b'3'))
4290 del m1, m2, m3
4291
4292 # memoryview.release() fails if the view has exported buffers.
4293 x = bytearray(b'123')
4294 with self.assertRaises(BufferError):
4295 with memoryview(x) as m:
4296 ex = ndarray(m)
4297 m[0] == ord(b'1')
4298
4299 def test_memoryview_redirect(self):
4300
4301 nd = ndarray([1.0 * x for x in range(12)], shape=[12], format='d')
4302 a = array.array('d', [1.0 * x for x in range(12)])
4303
4304 for x in (nd, a):
4305 y = ndarray(x, getbuf=PyBUF_FULL_RO, flags=ND_REDIRECT)
4306 z = ndarray(y, getbuf=PyBUF_FULL_RO, flags=ND_REDIRECT)
4307 m = memoryview(z)
4308
4309 self.assertIs(y.obj, x)
4310 self.assertIs(z.obj, x)
4311 self.assertIs(m.obj, x)
4312
4313 self.assertEqual(m, x)
4314 self.assertEqual(m, y)
4315 self.assertEqual(m, z)
4316
4317 self.assertEqual(m[1:3], x[1:3])
4318 self.assertEqual(m[1:3], y[1:3])
4319 self.assertEqual(m[1:3], z[1:3])
4320 del y, z
4321 self.assertEqual(m[1:3], x[1:3])
4322
4323 def test_memoryview_from_static_exporter(self):
4324
4325 fmt = 'B'
4326 lst = [0,1,2,3,4,5,6,7,8,9,10,11]
4327
4328 # exceptions
4329 self.assertRaises(TypeError, staticarray, 1, 2, 3)
4330
4331 # view.obj==x
4332 x = staticarray()
4333 y = memoryview(x)
4334 self.verify(y, obj=x,
4335 itemsize=1, fmt=fmt, readonly=True,
4336 ndim=1, shape=[12], strides=[1],
4337 lst=lst)
4338 for i in range(12):
4339 self.assertEqual(y[i], i)
4340 del x
4341 del y
4342
4343 x = staticarray()
4344 y = memoryview(x)
4345 del y
4346 del x
4347
4348 x = staticarray()
4349 y = ndarray(x, getbuf=PyBUF_FULL_RO)
4350 z = ndarray(y, getbuf=PyBUF_FULL_RO)
4351 m = memoryview(z)
4352 self.assertIs(y.obj, x)
4353 self.assertIs(m.obj, z)
4354 self.verify(m, obj=z,
4355 itemsize=1, fmt=fmt, readonly=True,
4356 ndim=1, shape=[12], strides=[1],
4357 lst=lst)
4358 del x, y, z, m
4359
4360 x = staticarray()
4361 y = ndarray(x, getbuf=PyBUF_FULL_RO, flags=ND_REDIRECT)
4362 z = ndarray(y, getbuf=PyBUF_FULL_RO, flags=ND_REDIRECT)
4363 m = memoryview(z)
4364 self.assertIs(y.obj, x)
4365 self.assertIs(z.obj, x)
4366 self.assertIs(m.obj, x)
4367 self.verify(m, obj=x,
4368 itemsize=1, fmt=fmt, readonly=True,
4369 ndim=1, shape=[12], strides=[1],
4370 lst=lst)
4371 del x, y, z, m
4372
4373 # view.obj==NULL
4374 x = staticarray(legacy_mode=True)
4375 y = memoryview(x)
4376 self.verify(y, obj=None,
4377 itemsize=1, fmt=fmt, readonly=True,
4378 ndim=1, shape=[12], strides=[1],
4379 lst=lst)
4380 for i in range(12):
4381 self.assertEqual(y[i], i)
4382 del x
4383 del y
4384
4385 x = staticarray(legacy_mode=True)
4386 y = memoryview(x)
4387 del y
4388 del x
4389
4390 x = staticarray(legacy_mode=True)
4391 y = ndarray(x, getbuf=PyBUF_FULL_RO)
4392 z = ndarray(y, getbuf=PyBUF_FULL_RO)
4393 m = memoryview(z)
4394 self.assertIs(y.obj, None)
4395 self.assertIs(m.obj, z)
4396 self.verify(m, obj=z,
4397 itemsize=1, fmt=fmt, readonly=True,
4398 ndim=1, shape=[12], strides=[1],
4399 lst=lst)
4400 del x, y, z, m
4401
4402 x = staticarray(legacy_mode=True)
4403 y = ndarray(x, getbuf=PyBUF_FULL_RO, flags=ND_REDIRECT)
4404 z = ndarray(y, getbuf=PyBUF_FULL_RO, flags=ND_REDIRECT)
4405 m = memoryview(z)
4406 # Clearly setting view.obj==NULL is inferior, since it
4407 # messes up the redirection chain:
4408 self.assertIs(y.obj, None)
4409 self.assertIs(z.obj, y)
4410 self.assertIs(m.obj, y)
4411 self.verify(m, obj=y,
4412 itemsize=1, fmt=fmt, readonly=True,
4413 ndim=1, shape=[12], strides=[1],
4414 lst=lst)
4415 del x, y, z, m
4416
4417 def test_memoryview_getbuffer_undefined(self):
4418
4419 # getbufferproc does not adhere to the new documentation
4420 nd = ndarray([1,2,3], [3], flags=ND_GETBUF_FAIL|ND_GETBUF_UNDEFINED)
4421 self.assertRaises(BufferError, memoryview, nd)
4422
4423 def test_issue_7385(self):
4424 x = ndarray([1,2,3], shape=[3], flags=ND_GETBUF_FAIL)
4425 self.assertRaises(BufferError, memoryview, x)
4426
4427 @support.cpython_only
4428 def test_pybuffer_size_from_format(self):
4429 # basic tests
4430 for format in ('', 'ii', '3s'):
4431 self.assertEqual(_testcapi.PyBuffer_SizeFromFormat(format),
4432 struct.calcsize(format))
4433
4434
4435 if __name__ == "__main__":
4436 unittest.main()