codekingpro/portable-devtools
115k
1import gc
2import sys
3import textwrap
4
5import pytest
6from hypothesis import given
7from hypothesis.extra import numpy as hynp
8
9import numpy as np
10from numpy._core.arrayprint import _typelessdata
11from numpy.testing import (
12 HAS_REFCOUNT,
13 IS_WASM,
14 assert_,
15 assert_equal,
16 assert_raises,
17 assert_raises_regex,
18)
19from numpy.testing._private.utils import run_threaded
20
21
22class TestArrayRepr:
23 def test_nan_inf(self):
24 x = np.array([np.nan, np.inf])
25 assert_equal(repr(x), 'array([nan, inf])')
26
27 def test_subclass(self):
28 class sub(np.ndarray):
29 pass
30
31 # one dimensional
32 x1d = np.array([1, 2]).view(sub)
33 assert_equal(repr(x1d), 'sub([1, 2])')
34
35 # two dimensional
36 x2d = np.array([[1, 2], [3, 4]]).view(sub)
37 assert_equal(repr(x2d),
38 'sub([[1, 2],\n'
39 ' [3, 4]])')
40
41 # two dimensional with flexible dtype
42 xstruct = np.ones((2, 2), dtype=[('a', '<i4')]).view(sub)
43 assert_equal(repr(xstruct),
44 "sub([[(1,), (1,)],\n"
45 " [(1,), (1,)]], dtype=[('a', '<i4')])"
46 )
47
48 @pytest.mark.xfail(reason="See gh-10544")
49 def test_object_subclass(self):
50 class sub(np.ndarray):
51 def __new__(cls, inp):
52 obj = np.asarray(inp).view(cls)
53 return obj
54
55 def __getitem__(self, ind):
56 ret = super().__getitem__(ind)
57 return sub(ret)
58
59 # test that object + subclass is OK:
60 x = sub([None, None])
61 assert_equal(repr(x), 'sub([None, None], dtype=object)')
62 assert_equal(str(x), '[None None]')
63
64 x = sub([None, sub([None, None])])
65 assert_equal(repr(x),
66 'sub([None, sub([None, None], dtype=object)], dtype=object)')
67 assert_equal(str(x), '[None sub([None, None], dtype=object)]')
68
69 def test_0d_object_subclass(self):
70 # make sure that subclasses which return 0ds instead
71 # of scalars don't cause infinite recursion in str
72 class sub(np.ndarray):
73 def __new__(cls, inp):
74 obj = np.asarray(inp).view(cls)
75 return obj
76
77 def __getitem__(self, ind):
78 ret = super().__getitem__(ind)
79 return sub(ret)
80
81 x = sub(1)
82 assert_equal(repr(x), 'sub(1)')
83 assert_equal(str(x), '1')
84
85 x = sub([1, 1])
86 assert_equal(repr(x), 'sub([1, 1])')
87 assert_equal(str(x), '[1 1]')
88
89 # check it works properly with object arrays too
90 x = sub(None)
91 assert_equal(repr(x), 'sub(None, dtype=object)')
92 assert_equal(str(x), 'None')
93
94 # plus recursive object arrays (even depth > 1)
95 y = sub(None)
96 x[()] = y
97 y[()] = x
98 assert_equal(repr(x),
99 'sub(sub(sub(..., dtype=object), dtype=object), dtype=object)')
100 assert_equal(str(x), '...')
101 x[()] = 0 # resolve circular references for garbage collector
102
103 # nested 0d-subclass-object
104 x = sub(None)
105 x[()] = sub(None)
106 assert_equal(repr(x), 'sub(sub(None, dtype=object), dtype=object)')
107 assert_equal(str(x), 'None')
108
109 # gh-10663
110 class DuckCounter(np.ndarray):
111 def __getitem__(self, item):
112 result = super().__getitem__(item)
113 if not isinstance(result, DuckCounter):
114 result = result[...].view(DuckCounter)
115 return result
116
117 def to_string(self):
118 return {0: 'zero', 1: 'one', 2: 'two'}.get(self.item(), 'many')
119
120 def __str__(self):
121 if self.shape == ():
122 return self.to_string()
123 else:
124 fmt = {'all': lambda x: x.to_string()}
125 return np.array2string(self, formatter=fmt)
126
127 dc = np.arange(5).view(DuckCounter)
128 assert_equal(str(dc), "[zero one two many many]")
129 assert_equal(str(dc[0]), "zero")
130
131 def test_self_containing(self):
132 arr0d = np.array(None)
133 arr0d[()] = arr0d
134 assert_equal(repr(arr0d),
135 'array(array(..., dtype=object), dtype=object)')
136 arr0d[()] = 0 # resolve recursion for garbage collector
137
138 arr1d = np.array([None, None])
139 arr1d[1] = arr1d
140 assert_equal(repr(arr1d),
141 'array([None, array(..., dtype=object)], dtype=object)')
142 arr1d[1] = 0 # resolve recursion for garbage collector
143
144 first = np.array(None)
145 second = np.array(None)
146 first[()] = second
147 second[()] = first
148 assert_equal(repr(first),
149 'array(array(array(..., dtype=object), dtype=object), dtype=object)')
150 first[()] = 0 # resolve circular references for garbage collector
151
152 def test_containing_list(self):
153 # printing square brackets directly would be ambiguous
154 arr1d = np.array([None, None])
155 arr1d[0] = [1, 2]
156 arr1d[1] = [3]
157 assert_equal(repr(arr1d),
158 'array([list([1, 2]), list([3])], dtype=object)')
159
160 def test_void_scalar_recursion(self):
161 # gh-9345
162 repr(np.void(b'test')) # RecursionError ?
163
164 def test_fieldless_structured(self):
165 # gh-10366
166 no_fields = np.dtype([])
167 arr_no_fields = np.empty(4, dtype=no_fields)
168 assert_equal(repr(arr_no_fields), 'array([(), (), (), ()], dtype=[])')
169
170
171class TestComplexArray:
172 def test_str(self):
173 rvals = [0, 1, -1, np.inf, -np.inf, np.nan]
174 cvals = [complex(rp, ip) for rp in rvals for ip in rvals]
175 dtypes = [np.complex64, np.cdouble, np.clongdouble]
176 actual = [str(np.array([c], dt)) for c in cvals for dt in dtypes]
177 wanted = [
178 '[0.+0.j]', '[0.+0.j]', '[0.+0.j]',
179 '[0.+1.j]', '[0.+1.j]', '[0.+1.j]',
180 '[0.-1.j]', '[0.-1.j]', '[0.-1.j]',
181 '[0.+infj]', '[0.+infj]', '[0.+infj]',
182 '[0.-infj]', '[0.-infj]', '[0.-infj]',
183 '[0.+nanj]', '[0.+nanj]', '[0.+nanj]',
184 '[1.+0.j]', '[1.+0.j]', '[1.+0.j]',
185 '[1.+1.j]', '[1.+1.j]', '[1.+1.j]',
186 '[1.-1.j]', '[1.-1.j]', '[1.-1.j]',
187 '[1.+infj]', '[1.+infj]', '[1.+infj]',
188 '[1.-infj]', '[1.-infj]', '[1.-infj]',
189 '[1.+nanj]', '[1.+nanj]', '[1.+nanj]',
190 '[-1.+0.j]', '[-1.+0.j]', '[-1.+0.j]',
191 '[-1.+1.j]', '[-1.+1.j]', '[-1.+1.j]',
192 '[-1.-1.j]', '[-1.-1.j]', '[-1.-1.j]',
193 '[-1.+infj]', '[-1.+infj]', '[-1.+infj]',
194 '[-1.-infj]', '[-1.-infj]', '[-1.-infj]',
195 '[-1.+nanj]', '[-1.+nanj]', '[-1.+nanj]',
196 '[inf+0.j]', '[inf+0.j]', '[inf+0.j]',
197 '[inf+1.j]', '[inf+1.j]', '[inf+1.j]',
198 '[inf-1.j]', '[inf-1.j]', '[inf-1.j]',
199 '[inf+infj]', '[inf+infj]', '[inf+infj]',
200 '[inf-infj]', '[inf-infj]', '[inf-infj]',
201 '[inf+nanj]', '[inf+nanj]', '[inf+nanj]',
202 '[-inf+0.j]', '[-inf+0.j]', '[-inf+0.j]',
203 '[-inf+1.j]', '[-inf+1.j]', '[-inf+1.j]',
204 '[-inf-1.j]', '[-inf-1.j]', '[-inf-1.j]',
205 '[-inf+infj]', '[-inf+infj]', '[-inf+infj]',
206 '[-inf-infj]', '[-inf-infj]', '[-inf-infj]',
207 '[-inf+nanj]', '[-inf+nanj]', '[-inf+nanj]',
208 '[nan+0.j]', '[nan+0.j]', '[nan+0.j]',
209 '[nan+1.j]', '[nan+1.j]', '[nan+1.j]',
210 '[nan-1.j]', '[nan-1.j]', '[nan-1.j]',
211 '[nan+infj]', '[nan+infj]', '[nan+infj]',
212 '[nan-infj]', '[nan-infj]', '[nan-infj]',
213 '[nan+nanj]', '[nan+nanj]', '[nan+nanj]']
214
215 for res, val in zip(actual, wanted):
216 assert_equal(res, val)
217
218class TestArray2String:
219 def test_basic(self):
220 """Basic test of array2string."""
221 a = np.arange(3)
222 assert_(np.array2string(a) == '[0 1 2]')
223 assert_(np.array2string(a, max_line_width=4, legacy='1.13') == '[0 1\n 2]')
224 assert_(np.array2string(a, max_line_width=4) == '[0\n 1\n 2]')
225
226 def test_unexpected_kwarg(self):
227 # ensure than an appropriate TypeError
228 # is raised when array2string receives
229 # an unexpected kwarg
230
231 with assert_raises_regex(TypeError, 'nonsense'):
232 np.array2string(np.array([1, 2, 3]),
233 nonsense=None)
234
235 def test_format_function(self):
236 """Test custom format function for each element in array."""
237 def _format_function(x):
238 if np.abs(x) < 1:
239 return '.'
240 elif np.abs(x) < 2:
241 return 'o'
242 else:
243 return 'O'
244
245 x = np.arange(3)
246 x_hex = "[0x0 0x1 0x2]"
247 x_oct = "[0o0 0o1 0o2]"
248 assert_(np.array2string(x, formatter={'all': _format_function}) ==
249 "[. o O]")
250 assert_(np.array2string(x, formatter={'int_kind': _format_function}) ==
251 "[. o O]")
252 assert_(np.array2string(x, formatter={'all': lambda x: f"{x:.4f}"}) ==
253 "[0.0000 1.0000 2.0000]")
254 assert_equal(np.array2string(x, formatter={'int': hex}),
255 x_hex)
256 assert_equal(np.array2string(x, formatter={'int': oct}),
257 x_oct)
258
259 x = np.arange(3.)
260 assert_(np.array2string(x, formatter={'float_kind': lambda x: f"{x:.2f}"}) ==
261 "[0.00 1.00 2.00]")
262 assert_(np.array2string(x, formatter={'float': lambda x: f"{x:.2f}"}) ==
263 "[0.00 1.00 2.00]")
264
265 s = np.array(['abc', 'def'])
266 assert_(np.array2string(s, formatter={'numpystr': lambda s: s * 2}) ==
267 '[abcabc defdef]')
268
269 def test_structure_format_mixed(self):
270 dt = np.dtype([('name', np.str_, 16), ('grades', np.float64, (2,))])
271 x = np.array([('Sarah', (8.0, 7.0)), ('John', (6.0, 7.0))], dtype=dt)
272 assert_equal(np.array2string(x),
273 "[('Sarah', [8., 7.]) ('John', [6., 7.])]")
274
275 np.set_printoptions(legacy='1.13')
276 try:
277 # for issue #5692
278 A = np.zeros(shape=10, dtype=[("A", "M8[s]")])
279 A[5:].fill(np.datetime64('NaT'))
280 assert_equal(
281 np.array2string(A),
282 textwrap.dedent("""\
283 [('1970-01-01T00:00:00',) ('1970-01-01T00:00:00',) ('1970-01-01T00:00:00',)
284 ('1970-01-01T00:00:00',) ('1970-01-01T00:00:00',) ('NaT',) ('NaT',)
285 ('NaT',) ('NaT',) ('NaT',)]""")
286 )
287 finally:
288 np.set_printoptions(legacy=False)
289
290 # same again, but with non-legacy behavior
291 assert_equal(
292 np.array2string(A),
293 textwrap.dedent("""\
294 [('1970-01-01T00:00:00',) ('1970-01-01T00:00:00',)
295 ('1970-01-01T00:00:00',) ('1970-01-01T00:00:00',)
296 ('1970-01-01T00:00:00',) ( 'NaT',)
297 ( 'NaT',) ( 'NaT',)
298 ( 'NaT',) ( 'NaT',)]""")
299 )
300
301 # and again, with timedeltas
302 A = np.full(10, 123456, dtype=[("A", "m8[s]")])
303 A[5:].fill(np.datetime64('NaT'))
304 assert_equal(
305 np.array2string(A),
306 textwrap.dedent("""\
307 [(123456,) (123456,) (123456,) (123456,) (123456,) ( 'NaT',) ( 'NaT',)
308 ( 'NaT',) ( 'NaT',) ( 'NaT',)]""")
309 )
310
311 def test_structure_format_int(self):
312 # See #8160
313 struct_int = np.array([([1, -1],), ([123, 1],)],
314 dtype=[('B', 'i4', 2)])
315 assert_equal(np.array2string(struct_int),
316 "[([ 1, -1],) ([123, 1],)]")
317 struct_2dint = np.array([([[0, 1], [2, 3]],), ([[12, 0], [0, 0]],)],
318 dtype=[('B', 'i4', (2, 2))])
319 assert_equal(np.array2string(struct_2dint),
320 "[([[ 0, 1], [ 2, 3]],) ([[12, 0], [ 0, 0]],)]")
321
322 def test_structure_format_float(self):
323 # See #8172
324 array_scalar = np.array(
325 (1., 2.1234567890123456789, 3.), dtype=('f8,f8,f8'))
326 assert_equal(np.array2string(array_scalar), "(1., 2.12345679, 3.)")
327
328 def test_unstructured_void_repr(self):
329 a = np.array([27, 91, 50, 75, 7, 65, 10, 8, 27, 91, 51, 49, 109, 82, 101, 100],
330 dtype='u1').view('V8')
331 assert_equal(repr(a[0]),
332 r"np.void(b'\x1B\x5B\x32\x4B\x07\x41\x0A\x08')")
333 assert_equal(str(a[0]), r"b'\x1B\x5B\x32\x4B\x07\x41\x0A\x08'")
334 assert_equal(repr(a),
335 r"array([b'\x1B\x5B\x32\x4B\x07\x41\x0A\x08',"
336 "\n"
337 r" b'\x1B\x5B\x33\x31\x6D\x52\x65\x64'], dtype='|V8')")
338
339 assert_equal(eval(repr(a), vars(np)), a)
340 assert_equal(eval(repr(a[0]), {'np': np}), a[0])
341
342 def test_edgeitems_kwarg(self):
343 # previously the global print options would be taken over the kwarg
344 arr = np.zeros(3, int)
345 assert_equal(
346 np.array2string(arr, edgeitems=1, threshold=0),
347 "[0 ... 0]"
348 )
349
350 def test_summarize_1d(self):
351 A = np.arange(1001)
352 strA = '[ 0 1 2 ... 998 999 1000]'
353 assert_equal(str(A), strA)
354
355 reprA = 'array([ 0, 1, 2, ..., 998, 999, 1000])'
356 try:
357 np.set_printoptions(legacy='2.1')
358 assert_equal(repr(A), reprA)
359 finally:
360 np.set_printoptions(legacy=False)
361
362 assert_equal(repr(A), reprA.replace(')', ', shape=(1001,))'))
363
364 def test_summarize_2d(self):
365 A = np.arange(1002).reshape(2, 501)
366 strA = '[[ 0 1 2 ... 498 499 500]\n' \
367 ' [ 501 502 503 ... 999 1000 1001]]'
368 assert_equal(str(A), strA)
369
370 reprA = 'array([[ 0, 1, 2, ..., 498, 499, 500],\n' \
371 ' [ 501, 502, 503, ..., 999, 1000, 1001]])'
372 try:
373 np.set_printoptions(legacy='2.1')
374 assert_equal(repr(A), reprA)
375 finally:
376 np.set_printoptions(legacy=False)
377
378 assert_equal(repr(A), reprA.replace(')', ', shape=(2, 501))'))
379
380 def test_summarize_2d_dtype(self):
381 A = np.arange(1002, dtype='i2').reshape(2, 501)
382 strA = '[[ 0 1 2 ... 498 499 500]\n' \
383 ' [ 501 502 503 ... 999 1000 1001]]'
384 assert_equal(str(A), strA)
385
386 reprA = ('array([[ 0, 1, 2, ..., 498, 499, 500],\n'
387 ' [ 501, 502, 503, ..., 999, 1000, 1001]],\n'
388 ' shape=(2, 501), dtype=int16)')
389 assert_equal(repr(A), reprA)
390
391 def test_summarize_structure(self):
392 A = (np.arange(2002, dtype="<i8").reshape(2, 1001)
393 .view([('i', "<i8", (1001,))]))
394 strA = ("[[([ 0, 1, 2, ..., 998, 999, 1000],)]\n"
395 " [([1001, 1002, 1003, ..., 1999, 2000, 2001],)]]")
396 assert_equal(str(A), strA)
397
398 reprA = ("array([[([ 0, 1, 2, ..., 998, 999, 1000],)],\n"
399 " [([1001, 1002, 1003, ..., 1999, 2000, 2001],)]],\n"
400 " dtype=[('i', '<i8', (1001,))])")
401 assert_equal(repr(A), reprA)
402
403 B = np.ones(2002, dtype=">i8").view([('i', ">i8", (2, 1001))])
404 strB = "[([[1, 1, 1, ..., 1, 1, 1], [1, 1, 1, ..., 1, 1, 1]],)]"
405 assert_equal(str(B), strB)
406
407 reprB = (
408 "array([([[1, 1, 1, ..., 1, 1, 1], [1, 1, 1, ..., 1, 1, 1]],)],\n"
409 " dtype=[('i', '>i8', (2, 1001))])"
410 )
411 assert_equal(repr(B), reprB)
412
413 C = (np.arange(22, dtype="<i8").reshape(2, 11)
414 .view([('i1', "<i8"), ('i10', "<i8", (10,))]))
415 strC = "[[( 0, [ 1, ..., 10])]\n [(11, [12, ..., 21])]]"
416 assert_equal(np.array2string(C, threshold=1, edgeitems=1), strC)
417
418 def test_linewidth(self):
419 a = np.full(6, 1)
420
421 def make_str(a, width, **kw):
422 return np.array2string(a, separator="", max_line_width=width, **kw)
423
424 assert_equal(make_str(a, 8, legacy='1.13'), '[111111]')
425 assert_equal(make_str(a, 7, legacy='1.13'), '[111111]')
426 assert_equal(make_str(a, 5, legacy='1.13'), '[1111\n'
427 ' 11]')
428
429 assert_equal(make_str(a, 8), '[111111]')
430 assert_equal(make_str(a, 7), '[11111\n'
431 ' 1]')
432 assert_equal(make_str(a, 5), '[111\n'
433 ' 111]')
434
435 b = a[None, None, :]
436
437 assert_equal(make_str(b, 12, legacy='1.13'), '[[[111111]]]')
438 assert_equal(make_str(b, 9, legacy='1.13'), '[[[111111]]]')
439 assert_equal(make_str(b, 8, legacy='1.13'), '[[[11111\n'
440 ' 1]]]')
441
442 assert_equal(make_str(b, 12), '[[[111111]]]')
443 assert_equal(make_str(b, 9), '[[[111\n'
444 ' 111]]]')
445 assert_equal(make_str(b, 8), '[[[11\n'
446 ' 11\n'
447 ' 11]]]')
448
449 def test_wide_element(self):
450 a = np.array(['xxxxx'])
451 assert_equal(
452 np.array2string(a, max_line_width=5),
453 "['xxxxx']"
454 )
455 assert_equal(
456 np.array2string(a, max_line_width=5, legacy='1.13'),
457 "[ 'xxxxx']"
458 )
459
460 def test_multiline_repr(self):
461 class MultiLine:
462 def __repr__(self):
463 return "Line 1\nLine 2"
464
465 a = np.array([[None, MultiLine()], [MultiLine(), None]])
466
467 assert_equal(
468 np.array2string(a),
469 '[[None Line 1\n'
470 ' Line 2]\n'
471 ' [Line 1\n'
472 ' Line 2 None]]'
473 )
474 assert_equal(
475 np.array2string(a, max_line_width=5),
476 '[[None\n'
477 ' Line 1\n'
478 ' Line 2]\n'
479 ' [Line 1\n'
480 ' Line 2\n'
481 ' None]]'
482 )
483 assert_equal(
484 repr(a),
485 'array([[None, Line 1\n'
486 ' Line 2],\n'
487 ' [Line 1\n'
488 ' Line 2, None]], dtype=object)'
489 )
490
491 class MultiLineLong:
492 def __repr__(self):
493 return "Line 1\nLooooooooooongestLine2\nLongerLine 3"
494
495 a = np.array([[None, MultiLineLong()], [MultiLineLong(), None]])
496 assert_equal(
497 repr(a),
498 'array([[None, Line 1\n'
499 ' LooooooooooongestLine2\n'
500 ' LongerLine 3 ],\n'
501 ' [Line 1\n'
502 ' LooooooooooongestLine2\n'
503 ' LongerLine 3 , None]], dtype=object)'
504 )
505 assert_equal(
506 np.array_repr(a, 20),
507 'array([[None,\n'
508 ' Line 1\n'
509 ' LooooooooooongestLine2\n'
510 ' LongerLine 3 ],\n'
511 ' [Line 1\n'
512 ' LooooooooooongestLine2\n'
513 ' LongerLine 3 ,\n'
514 ' None]],\n'
515 ' dtype=object)'
516 )
517
518 def test_nested_array_repr(self):
519 a = np.empty((2, 2), dtype=object)
520 a[0, 0] = np.eye(2)
521 a[0, 1] = np.eye(3)
522 a[1, 0] = None
523 a[1, 1] = np.ones((3, 1))
524 assert_equal(
525 repr(a),
526 'array([[array([[1., 0.],\n'
527 ' [0., 1.]]), array([[1., 0., 0.],\n'
528 ' [0., 1., 0.],\n'
529 ' [0., 0., 1.]])],\n'
530 ' [None, array([[1.],\n'
531 ' [1.],\n'
532 ' [1.]])]], dtype=object)'
533 )
534
535 @given(hynp.from_dtype(np.dtype("U")))
536 def test_any_text(self, text):
537 # This test checks that, given any value that can be represented in an
538 # array of dtype("U") (i.e. unicode string), ...
539 a = np.array([text, text, text])
540 # casting a list of them to an array does not e.g. truncate the value
541 assert_equal(a[0], text)
542 text = text.item() # use raw python strings for repr below
543 # and that np.array2string puts a newline in the expected location
544 expected_repr = f"[{text!r} {text!r}\n {text!r}]"
545 result = np.array2string(a, max_line_width=len(repr(text)) * 2 + 3)
546 assert_equal(result, expected_repr)
547
548 @pytest.mark.skipif(not HAS_REFCOUNT, reason="Python lacks refcounts")
549 @pytest.mark.thread_unsafe(reason="garbage collector is global state")
550 def test_refcount(self):
551 # make sure we do not hold references to the array due to a recursive
552 # closure (gh-10620)
553 gc.disable()
554 a = np.arange(2)
555 r1 = sys.getrefcount(a)
556 np.array2string(a)
557 np.array2string(a)
558 r2 = sys.getrefcount(a)
559 gc.collect()
560 gc.enable()
561 assert_(r1 == r2)
562
563 def test_with_sign(self):
564 # mixed negative and positive value array
565 a = np.array([-2, 0, 3])
566 assert_equal(
567 np.array2string(a, sign='+'),
568 '[-2 +0 +3]'
569 )
570 assert_equal(
571 np.array2string(a, sign='-'),
572 '[-2 0 3]'
573 )
574 assert_equal(
575 np.array2string(a, sign=' '),
576 '[-2 0 3]'
577 )
578 # all non-negative array
579 a = np.array([2, 0, 3])
580 assert_equal(
581 np.array2string(a, sign='+'),
582 '[+2 +0 +3]'
583 )
584 assert_equal(
585 np.array2string(a, sign='-'),
586 '[2 0 3]'
587 )
588 assert_equal(
589 np.array2string(a, sign=' '),
590 '[ 2 0 3]'
591 )
592 # all negative array
593 a = np.array([-2, -1, -3])
594 assert_equal(
595 np.array2string(a, sign='+'),
596 '[-2 -1 -3]'
597 )
598 assert_equal(
599 np.array2string(a, sign='-'),
600 '[-2 -1 -3]'
601 )
602 assert_equal(
603 np.array2string(a, sign=' '),
604 '[-2 -1 -3]'
605 )
606 # 2d array mixed negative and positive
607 a = np.array([[10, -1, 1, 1], [10, 10, 10, 10]])
608 assert_equal(
609 np.array2string(a, sign='+'),
610 '[[+10 -1 +1 +1]\n [+10 +10 +10 +10]]'
611 )
612 assert_equal(
613 np.array2string(a, sign='-'),
614 '[[10 -1 1 1]\n [10 10 10 10]]'
615 )
616 assert_equal(
617 np.array2string(a, sign=' '),
618 '[[10 -1 1 1]\n [10 10 10 10]]'
619 )
620 # 2d array all positive
621 a = np.array([[10, 0, 1, 1], [10, 10, 10, 10]])
622 assert_equal(
623 np.array2string(a, sign='+'),
624 '[[+10 +0 +1 +1]\n [+10 +10 +10 +10]]'
625 )
626 assert_equal(
627 np.array2string(a, sign='-'),
628 '[[10 0 1 1]\n [10 10 10 10]]'
629 )
630 assert_equal(
631 np.array2string(a, sign=' '),
632 '[[ 10 0 1 1]\n [ 10 10 10 10]]'
633 )
634 # 2d array all negative
635 a = np.array([[-10, -1, -1, -1], [-10, -10, -10, -10]])
636 assert_equal(
637 np.array2string(a, sign='+'),
638 '[[-10 -1 -1 -1]\n [-10 -10 -10 -10]]'
639 )
640 assert_equal(
641 np.array2string(a, sign='-'),
642 '[[-10 -1 -1 -1]\n [-10 -10 -10 -10]]'
643 )
644 assert_equal(
645 np.array2string(a, sign=' '),
646 '[[-10 -1 -1 -1]\n [-10 -10 -10 -10]]'
647 )
648
649
650class TestPrintOptions:
651 """Test getting and setting global print options."""
652
653 def setup_method(self):
654 self.oldopts = np.get_printoptions()
655
656 def teardown_method(self):
657 np.set_printoptions(**self.oldopts)
658
659 def test_basic(self):
660 x = np.array([1.5, 0, 1.234567890])
661 assert_equal(repr(x), "array([1.5 , 0. , 1.23456789])")
662 ret = np.set_printoptions(precision=4)
663 assert_equal(repr(x), "array([1.5 , 0. , 1.2346])")
664 assert ret is None
665
666 def test_precision_zero(self):
667 np.set_printoptions(precision=0)
668 for values, string in (
669 ([0.], "0."), ([.3], "0."), ([-.3], "-0."), ([.7], "1."),
670 ([1.5], "2."), ([-1.5], "-2."), ([-15.34], "-15."),
671 ([100.], "100."), ([.2, -1, 122.51], " 0., -1., 123."),
672 ([0], "0"), ([-12], "-12"), ([complex(.3, -.7)], "0.-1.j")):
673 x = np.array(values)
674 assert_equal(repr(x), f"array([{string}])")
675
676 def test_formatter(self):
677 x = np.arange(3)
678 np.set_printoptions(formatter={'all': lambda x: str(x - 1)})
679 assert_equal(repr(x), "array([-1, 0, 1])")
680
681 def test_formatter_reset(self):
682 x = np.arange(3)
683 np.set_printoptions(formatter={'all': lambda x: str(x - 1)})
684 assert_equal(repr(x), "array([-1, 0, 1])")
685 np.set_printoptions(formatter={'int': None})
686 assert_equal(repr(x), "array([0, 1, 2])")
687
688 np.set_printoptions(formatter={'all': lambda x: str(x - 1)})
689 assert_equal(repr(x), "array([-1, 0, 1])")
690 np.set_printoptions(formatter={'all': None})
691 assert_equal(repr(x), "array([0, 1, 2])")
692
693 np.set_printoptions(formatter={'int': lambda x: str(x - 1)})
694 assert_equal(repr(x), "array([-1, 0, 1])")
695 np.set_printoptions(formatter={'int_kind': None})
696 assert_equal(repr(x), "array([0, 1, 2])")
697
698 x = np.arange(3.)
699 np.set_printoptions(formatter={'float': lambda x: str(x - 1)})
700 assert_equal(repr(x), "array([-1.0, 0.0, 1.0])")
701 np.set_printoptions(formatter={'float_kind': None})
702 assert_equal(repr(x), "array([0., 1., 2.])")
703
704 def test_override_repr(self):
705 x = np.arange(3)
706 np.set_printoptions(override_repr=lambda x: "FOO")
707 assert_equal(repr(x), "FOO")
708 np.set_printoptions(override_repr=None)
709 assert_equal(repr(x), "array([0, 1, 2])")
710
711 with np.printoptions(override_repr=lambda x: "BAR"):
712 assert_equal(repr(x), "BAR")
713 assert_equal(repr(x), "array([0, 1, 2])")
714
715 def test_0d_arrays(self):
716 assert_equal(str(np.array('café', '<U4')), 'café')
717
718 assert_equal(repr(np.array('café', '<U4')),
719 "array('café', dtype='<U4')")
720 assert_equal(str(np.array('test', np.str_)), 'test')
721
722 a = np.zeros(1, dtype=[('a', '<i4', (3,))])
723 assert_equal(str(a[0]), '([0, 0, 0],)')
724
725 assert_equal(repr(np.datetime64('2005-02-25')[...]),
726 "array('2005-02-25', dtype='datetime64[D]')")
727
728 assert_equal(repr(np.timedelta64('10', 'Y')[...]),
729 "array(10, dtype='timedelta64[Y]')")
730
731 # repr of 0d arrays is affected by printoptions
732 x = np.array(1)
733 np.set_printoptions(formatter={'all': lambda x: "test"})
734 assert_equal(repr(x), "array(test)")
735 # str is unaffected
736 assert_equal(str(x), "1")
737
738 # check it works
739 np.array2string(np.array(1.), legacy='1.13')
740
741 def test_float_spacing(self):
742 x = np.array([1., 2., 3.])
743 y = np.array([1., 2., -10.])
744 z = np.array([100., 2., -1.])
745 w = np.array([-100., 2., 1.])
746
747 assert_equal(repr(x), 'array([1., 2., 3.])')
748 assert_equal(repr(y), 'array([ 1., 2., -10.])')
749 assert_equal(repr(np.array(y[0])), 'array(1.)')
750 assert_equal(repr(np.array(y[-1])), 'array(-10.)')
751 assert_equal(repr(z), 'array([100., 2., -1.])')
752 assert_equal(repr(w), 'array([-100., 2., 1.])')
753
754 assert_equal(repr(np.array([np.nan, np.inf])), 'array([nan, inf])')
755 assert_equal(repr(np.array([np.nan, -np.inf])), 'array([ nan, -inf])')
756
757 x = np.array([np.inf, 100000, 1.1234])
758 y = np.array([np.inf, 100000, -1.1234])
759 z = np.array([np.inf, 1.1234, -1e120])
760 np.set_printoptions(precision=2)
761 assert_equal(repr(x), 'array([ inf, 1.00e+05, 1.12e+00])')
762 assert_equal(repr(y), 'array([ inf, 1.00e+05, -1.12e+00])')
763 assert_equal(repr(z), 'array([ inf, 1.12e+000, -1.00e+120])')
764
765 def test_bool_spacing(self):
766 assert_equal(repr(np.array([True, True])),
767 'array([ True, True])')
768 assert_equal(repr(np.array([True, False])),
769 'array([ True, False])')
770 assert_equal(repr(np.array([True])),
771 'array([ True])')
772 assert_equal(repr(np.array(True)),
773 'array(True)')
774 assert_equal(repr(np.array(False)),
775 'array(False)')
776
777 def test_sign_spacing(self):
778 a = np.arange(4.)
779 b = np.array([1.234e9])
780 c = np.array([1.0 + 1.0j, 1.123456789 + 1.123456789j], dtype='c16')
781
782 assert_equal(repr(a), 'array([0., 1., 2., 3.])')
783 assert_equal(repr(np.array(1.)), 'array(1.)')
784 assert_equal(repr(b), 'array([1.234e+09])')
785 assert_equal(repr(np.array([0.])), 'array([0.])')
786 assert_equal(repr(c),
787 "array([1. +1.j , 1.12345679+1.12345679j])")
788 assert_equal(repr(np.array([0., -0.])), 'array([ 0., -0.])')
789
790 np.set_printoptions(sign=' ')
791 assert_equal(repr(a), 'array([ 0., 1., 2., 3.])')
792 assert_equal(repr(np.array(1.)), 'array( 1.)')
793 assert_equal(repr(b), 'array([ 1.234e+09])')
794 assert_equal(repr(c),
795 "array([ 1. +1.j , 1.12345679+1.12345679j])")
796 assert_equal(repr(np.array([0., -0.])), 'array([ 0., -0.])')
797
798 np.set_printoptions(sign='+')
799 assert_equal(repr(a), 'array([+0., +1., +2., +3.])')
800 assert_equal(repr(np.array(1.)), 'array(+1.)')
801 assert_equal(repr(b), 'array([+1.234e+09])')
802 assert_equal(repr(c),
803 "array([+1. +1.j , +1.12345679+1.12345679j])")
804
805 np.set_printoptions(legacy='1.13')
806 assert_equal(repr(a), 'array([ 0., 1., 2., 3.])')
807 assert_equal(repr(b), 'array([ 1.23400000e+09])')
808 assert_equal(repr(-b), 'array([ -1.23400000e+09])')
809 assert_equal(repr(np.array(1.)), 'array(1.0)')
810 assert_equal(repr(np.array([0.])), 'array([ 0.])')
811 assert_equal(repr(c),
812 "array([ 1.00000000+1.j , 1.12345679+1.12345679j])")
813 # gh-10383
814 assert_equal(str(np.array([-1., 10])), "[ -1. 10.]")
815
816 assert_raises(TypeError, np.set_printoptions, wrongarg=True)
817
818 def test_float_overflow_nowarn(self):
819 # make sure internal computations in FloatingFormat don't
820 # warn about overflow
821 repr(np.array([1e4, 0.1], dtype='f2'))
822
823 def test_sign_spacing_structured(self):
824 a = np.ones(2, dtype='<f,<f')
825 assert_equal(repr(a),
826 "array([(1., 1.), (1., 1.)], dtype=[('f0', '<f4'), ('f1', '<f4')])")
827 assert_equal(repr(a[0]),
828 "np.void((1.0, 1.0), dtype=[('f0', '<f4'), ('f1', '<f4')])")
829
830 def test_floatmode(self):
831 x = np.array([0.6104, 0.922, 0.457, 0.0906, 0.3733, 0.007244,
832 0.5933, 0.947, 0.2383, 0.4226], dtype=np.float16)
833 y = np.array([0.2918820979355541, 0.5064172631089138,
834 0.2848750619642916, 0.4342965294660567,
835 0.7326538397312751, 0.3459503329096204,
836 0.0862072768214508, 0.39112753029631175],
837 dtype=np.float64)
838 z = np.arange(6, dtype=np.float16) / 10
839 c = np.array([1.0 + 1.0j, 1.123456789 + 1.123456789j], dtype='c16')
840
841 # also make sure 1e23 is right (is between two fp numbers)
842 w = np.array([f'1e{i}' for i in range(25)], dtype=np.float64)
843 # note: we construct w from the strings `1eXX` instead of doing
844 # `10.**arange(24)` because it turns out the two are not equivalent in
845 # python. On some architectures `1e23 != 10.**23`.
846 wp = np.array([1.234e1, 1e2, 1e123])
847
848 # unique mode
849 np.set_printoptions(floatmode='unique')
850 assert_equal(repr(x),
851 "array([0.6104 , 0.922 , 0.457 , 0.0906 , 0.3733 , 0.007244,\n"
852 " 0.5933 , 0.947 , 0.2383 , 0.4226 ], dtype=float16)")
853 assert_equal(repr(y),
854 "array([0.2918820979355541 , 0.5064172631089138 , 0.2848750619642916 ,\n"
855 " 0.4342965294660567 , 0.7326538397312751 , 0.3459503329096204 ,\n"
856 " 0.0862072768214508 , 0.39112753029631175])")
857 assert_equal(repr(z),
858 "array([0. , 0.1, 0.2, 0.3, 0.4, 0.5], dtype=float16)")
859 assert_equal(repr(w),
860 "array([1.e+00, 1.e+01, 1.e+02, 1.e+03, 1.e+04, 1.e+05, 1.e+06, 1.e+07,\n"
861 " 1.e+08, 1.e+09, 1.e+10, 1.e+11, 1.e+12, 1.e+13, 1.e+14, 1.e+15,\n"
862 " 1.e+16, 1.e+17, 1.e+18, 1.e+19, 1.e+20, 1.e+21, 1.e+22, 1.e+23,\n"
863 " 1.e+24])")
864 assert_equal(repr(wp), "array([1.234e+001, 1.000e+002, 1.000e+123])")
865 assert_equal(repr(c),
866 "array([1. +1.j , 1.123456789+1.123456789j])")
867
868 # maxprec mode, precision=8
869 np.set_printoptions(floatmode='maxprec', precision=8)
870 assert_equal(repr(x),
871 "array([0.6104 , 0.922 , 0.457 , 0.0906 , 0.3733 , 0.007244,\n"
872 " 0.5933 , 0.947 , 0.2383 , 0.4226 ], dtype=float16)")
873 assert_equal(repr(y),
874 "array([0.2918821 , 0.50641726, 0.28487506, 0.43429653, 0.73265384,\n"
875 " 0.34595033, 0.08620728, 0.39112753])")
876 assert_equal(repr(z),
877 "array([0. , 0.1, 0.2, 0.3, 0.4, 0.5], dtype=float16)")
878 assert_equal(repr(w[::5]),
879 "array([1.e+00, 1.e+05, 1.e+10, 1.e+15, 1.e+20])")
880 assert_equal(repr(wp), "array([1.234e+001, 1.000e+002, 1.000e+123])")
881 assert_equal(repr(c),
882 "array([1. +1.j , 1.12345679+1.12345679j])")
883
884 # fixed mode, precision=4
885 np.set_printoptions(floatmode='fixed', precision=4)
886 assert_equal(repr(x),
887 "array([0.6104, 0.9219, 0.4570, 0.0906, 0.3733, 0.0072, 0.5933, 0.9468,\n"
888 " 0.2383, 0.4226], dtype=float16)")
889 assert_equal(repr(y),
890 "array([0.2919, 0.5064, 0.2849, 0.4343, 0.7327, 0.3460, 0.0862, 0.3911])")
891 assert_equal(repr(z),
892 "array([0.0000, 0.1000, 0.2000, 0.3000, 0.3999, 0.5000], dtype=float16)")
893 assert_equal(repr(w[::5]),
894 "array([1.0000e+00, 1.0000e+05, 1.0000e+10, 1.0000e+15, 1.0000e+20])")
895 assert_equal(repr(wp), "array([1.2340e+001, 1.0000e+002, 1.0000e+123])")
896 assert_equal(repr(np.zeros(3)), "array([0.0000, 0.0000, 0.0000])")
897 assert_equal(repr(c),
898 "array([1.0000+1.0000j, 1.1235+1.1235j])")
899 # for larger precision, representation error becomes more apparent:
900 np.set_printoptions(floatmode='fixed', precision=8)
901 assert_equal(repr(z),
902 "array([0.00000000, 0.09997559, 0.19995117, 0.30004883, 0.39990234,\n"
903 " 0.50000000], dtype=float16)")
904
905 # maxprec_equal mode, precision=8
906 np.set_printoptions(floatmode='maxprec_equal', precision=8)
907 assert_equal(repr(x),
908 "array([0.610352, 0.921875, 0.457031, 0.090576, 0.373291, 0.007244,\n"
909 " 0.593262, 0.946777, 0.238281, 0.422607], dtype=float16)")
910 assert_equal(repr(y),
911 "array([0.29188210, 0.50641726, 0.28487506, 0.43429653, 0.73265384,\n"
912 " 0.34595033, 0.08620728, 0.39112753])")
913 assert_equal(repr(z),
914 "array([0.0, 0.1, 0.2, 0.3, 0.4, 0.5], dtype=float16)")
915 assert_equal(repr(w[::5]),
916 "array([1.e+00, 1.e+05, 1.e+10, 1.e+15, 1.e+20])")
917 assert_equal(repr(wp), "array([1.234e+001, 1.000e+002, 1.000e+123])")
918 assert_equal(repr(c),
919 "array([1.00000000+1.00000000j, 1.12345679+1.12345679j])")
920
921 # test unique special case (gh-18609)
922 a = np.float64.fromhex('-1p-97')
923 assert_equal(np.float64(np.array2string(a, floatmode='unique')), a)
924
925 test_cases_gh_28679 = [
926 (np.half([999, 999]), "[999. 999.]"),
927 (np.half([999, 1000]), "[9.99e+02 1.00e+03]"),
928 (np.single([999999, 999999]), "[999999. 999999.]"),
929 (np.single([999999, -1000000]), "[ 9.99999e+05 -1.00000e+06]"),
930 (
931 np.complex64([999999 + 999999j, 999999 + 999999j]),
932 "[999999.+999999.j 999999.+999999.j]"
933 ),
934 (
935 np.complex64([999999 + 999999j, 999999 + -1000000j]),
936 "[999999.+9.99999e+05j 999999.-1.00000e+06j]"
937 ),
938 ]
939
940 @pytest.mark.parametrize("input_array, expected_str", test_cases_gh_28679)
941 def test_gh_28679(self, input_array, expected_str):
942 # test cutoff to exponent notation for half, single, and complex64
943 assert_equal(str(input_array), expected_str)
944
945 test_cases_legacy_2_2 = [
946 (np.half([1.e3, 1.e4, 65504]), "[ 1000. 10000. 65504.]"),
947 (np.single([1.e6, 1.e7]), "[ 1000000. 10000000.]"),
948 (np.single([1.e7, 1.e8]), "[1.e+07 1.e+08]"),
949 ]
950
951 @pytest.mark.parametrize("input_array, expected_str", test_cases_legacy_2_2)
952 def test_legacy_2_2_mode(self, input_array, expected_str):
953 # test legacy cutoff to exponent notation for half and single
954 with np.printoptions(legacy='2.2'):
955 assert_equal(str(input_array), expected_str)
956
957 @pytest.mark.parametrize("legacy", ['1.13', '1.21', '1.25', '2.1', '2.2'])
958 def test_legacy_get_options(self, legacy):
959 # test legacy get options works okay
960 with np.printoptions(legacy=legacy):
961 p_opt = np.get_printoptions()
962 assert_equal(p_opt["legacy"], legacy)
963
964 def test_legacy_mode_scalars(self):
965 # in legacy mode, str of floats get truncated, and complex scalars
966 # use * for non-finite imaginary part
967 np.set_printoptions(legacy='1.13')
968 assert_equal(str(np.float64(1.123456789123456789)), '1.12345678912')
969 assert_equal(str(np.complex128(complex(1, np.nan))), '(1+nan*j)')
970
971 np.set_printoptions(legacy=False)
972 assert_equal(str(np.float64(1.123456789123456789)),
973 '1.1234567891234568')
974 assert_equal(str(np.complex128(complex(1, np.nan))), '(1+nanj)')
975
976 def test_legacy_stray_comma(self):
977 np.set_printoptions(legacy='1.13')
978 assert_equal(str(np.arange(10000)), '[ 0 1 2 ..., 9997 9998 9999]')
979
980 np.set_printoptions(legacy=False)
981 assert_equal(str(np.arange(10000)), '[ 0 1 2 ... 9997 9998 9999]')
982
983 def test_dtype_linewidth_wrapping(self):
984 np.set_printoptions(linewidth=75)
985 assert_equal(repr(np.arange(10, 20., dtype='f4')),
986 "array([10., 11., 12., 13., 14., 15., 16., 17., 18., 19.], dtype=float32)")
987 assert_equal(repr(np.arange(10, 23., dtype='f4')), textwrap.dedent("""\
988 array([10., 11., 12., 13., 14., 15., 16., 17., 18., 19., 20., 21., 22.],
989 dtype=float32)"""))
990
991 styp = '<U4'
992 assert_equal(repr(np.ones(3, dtype=styp)),
993 f"array(['1', '1', '1'], dtype='{styp}')")
994 assert_equal(repr(np.ones(12, dtype=styp)), textwrap.dedent(f"""\
995 array(['1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1'],
996 dtype='{styp}')"""))
997
998 @pytest.mark.parametrize(
999 ['native'],
1000 [
1001 ('bool',),
1002 ('uint8',),
1003 ('uint16',),
1004 ('uint32',),
1005 ('uint64',),
1006 ('int8',),
1007 ('int16',),
1008 ('int32',),
1009 ('int64',),
1010 ('float16',),
1011 ('float32',),
1012 ('float64',),
1013 ('U1',), # 4-byte width string
1014 ],
1015 )
1016 def test_dtype_endianness_repr(self, native):
1017 '''
1018 there was an issue where
1019 repr(array([0], dtype='<u2')) and repr(array([0], dtype='>u2'))
1020 both returned the same thing:
1021 array([0], dtype=uint16)
1022 even though their dtypes have different endianness.
1023 '''
1024 native_dtype = np.dtype(native)
1025 non_native_dtype = native_dtype.newbyteorder()
1026 non_native_repr = repr(np.array([1], non_native_dtype))
1027 native_repr = repr(np.array([1], native_dtype))
1028 # preserve the sensible default of only showing dtype if nonstandard
1029 assert ('dtype' in native_repr) ^ (native_dtype in _typelessdata),\
1030 ("an array's repr should show dtype if and only if the type "
1031 'of the array is NOT one of the standard types '
1032 '(e.g., int32, bool, float64).')
1033 if non_native_dtype.itemsize > 1:
1034 # if the type is >1 byte, the non-native endian version
1035 # must show endianness.
1036 assert non_native_repr != native_repr
1037 assert f"dtype='{non_native_dtype.byteorder}" in non_native_repr
1038
1039 def test_linewidth_repr(self):
1040 a = np.full(7, fill_value=2)
1041 np.set_printoptions(linewidth=17)
1042 assert_equal(
1043 repr(a),
1044 textwrap.dedent("""\
1045 array([2, 2, 2,
1046 2, 2, 2,
1047 2])""")
1048 )
1049 np.set_printoptions(linewidth=17, legacy='1.13')
1050 assert_equal(
1051 repr(a),
1052 textwrap.dedent("""\
1053 array([2, 2, 2,
1054 2, 2, 2, 2])""")
1055 )
1056
1057 a = np.full(8, fill_value=2)
1058
1059 np.set_printoptions(linewidth=18, legacy=False)
1060 assert_equal(
1061 repr(a),
1062 textwrap.dedent("""\
1063 array([2, 2, 2,
1064 2, 2, 2,
1065 2, 2])""")
1066 )
1067
1068 np.set_printoptions(linewidth=18, legacy='1.13')
1069 assert_equal(
1070 repr(a),
1071 textwrap.dedent("""\
1072 array([2, 2, 2, 2,
1073 2, 2, 2, 2])""")
1074 )
1075
1076 def test_linewidth_str(self):
1077 a = np.full(18, fill_value=2)
1078 np.set_printoptions(linewidth=18)
1079 assert_equal(
1080 str(a),
1081 textwrap.dedent("""\
1082 [2 2 2 2 2 2 2 2
1083 2 2 2 2 2 2 2 2
1084 2 2]""")
1085 )
1086 np.set_printoptions(linewidth=18, legacy='1.13')
1087 assert_equal(
1088 str(a),
1089 textwrap.dedent("""\
1090 [2 2 2 2 2 2 2 2 2
1091 2 2 2 2 2 2 2 2 2]""")
1092 )
1093
1094 def test_edgeitems(self):
1095 np.set_printoptions(edgeitems=1, threshold=1)
1096 a = np.arange(27).reshape((3, 3, 3))
1097 assert_equal(
1098 repr(a),
1099 textwrap.dedent("""\
1100 array([[[ 0, ..., 2],
1101 ...,
1102 [ 6, ..., 8]],
1103
1104 ...,
1105
1106 [[18, ..., 20],
1107 ...,
1108 [24, ..., 26]]], shape=(3, 3, 3))""")
1109 )
1110
1111 b = np.zeros((3, 3, 1, 1))
1112 assert_equal(
1113 repr(b),
1114 textwrap.dedent("""\
1115 array([[[[0.]],
1116
1117 ...,
1118
1119 [[0.]]],
1120
1121
1122 ...,
1123
1124
1125 [[[0.]],
1126
1127 ...,
1128
1129 [[0.]]]], shape=(3, 3, 1, 1))""")
1130 )
1131
1132 # 1.13 had extra trailing spaces, and was missing newlines
1133 try:
1134 np.set_printoptions(legacy='1.13')
1135 assert_equal(repr(a), (
1136 "array([[[ 0, ..., 2],\n"
1137 " ..., \n"
1138 " [ 6, ..., 8]],\n"
1139 "\n"
1140 " ..., \n"
1141 " [[18, ..., 20],\n"
1142 " ..., \n"
1143 " [24, ..., 26]]])")
1144 )
1145 assert_equal(repr(b), (
1146 "array([[[[ 0.]],\n"
1147 "\n"
1148 " ..., \n"
1149 " [[ 0.]]],\n"
1150 "\n"
1151 "\n"
1152 " ..., \n"
1153 " [[[ 0.]],\n"
1154 "\n"
1155 " ..., \n"
1156 " [[ 0.]]]])")
1157 )
1158 finally:
1159 np.set_printoptions(legacy=False)
1160
1161 def test_edgeitems_structured(self):
1162 np.set_printoptions(edgeitems=1, threshold=1)
1163 A = np.arange(5 * 2 * 3, dtype="<i8").view([('i', "<i8", (5, 2, 3))])
1164 reprA = (
1165 "array([([[[ 0, ..., 2], [ 3, ..., 5]], ..., "
1166 "[[24, ..., 26], [27, ..., 29]]],)],\n"
1167 " dtype=[('i', '<i8', (5, 2, 3))])"
1168 )
1169 assert_equal(repr(A), reprA)
1170
1171 def test_bad_args(self):
1172 assert_raises(ValueError, np.set_printoptions, threshold=float('nan'))
1173 assert_raises(TypeError, np.set_printoptions, threshold='1')
1174 assert_raises(TypeError, np.set_printoptions, threshold=b'1')
1175
1176 assert_raises(TypeError, np.set_printoptions, precision='1')
1177 assert_raises(TypeError, np.set_printoptions, precision=1.5)
1178
1179def test_unicode_object_array():
1180 expected = "array(['é'], dtype=object)"
1181 x = np.array(['\xe9'], dtype=object)
1182 assert_equal(repr(x), expected)
1183
1184
1185class TestContextManager:
1186 def test_ctx_mgr(self):
1187 # test that context manager actually works
1188 with np.printoptions(precision=2):
1189 s = str(np.array([2.0]) / 3)
1190 assert_equal(s, '[0.67]')
1191
1192 def test_ctx_mgr_restores(self):
1193 # test that print options are actually restored
1194 opts = np.get_printoptions()
1195 with np.printoptions(precision=opts['precision'] - 1,
1196 linewidth=opts['linewidth'] - 4):
1197 pass
1198 assert_equal(np.get_printoptions(), opts)
1199
1200 def test_ctx_mgr_exceptions(self):
