Hide keyboard shortcuts

Hot-keys on this page

r m x p   toggle line displays

j k   next/prev highlighted chunk

0   (zero) top of page

1   (one) first highlighted chunk

1"""Array printing function 

2 

3$Id: arrayprint.py,v 1.9 2005/09/13 13:58:44 teoliphant Exp $ 

4 

5""" 

6__all__ = ["array2string", "array_str", "array_repr", "set_string_function", 

7 "set_printoptions", "get_printoptions", "printoptions", 

8 "format_float_positional", "format_float_scientific"] 

9__docformat__ = 'restructuredtext' 

10 

11# 

12# Written by Konrad Hinsen <hinsenk@ere.umontreal.ca> 

13# last revision: 1996-3-13 

14# modified by Jim Hugunin 1997-3-3 for repr's and str's (and other details) 

15# and by Perry Greenfield 2000-4-1 for numarray 

16# and by Travis Oliphant 2005-8-22 for numpy 

17 

18 

19# Note: Both scalartypes.c.src and arrayprint.py implement strs for numpy 

20# scalars but for different purposes. scalartypes.c.src has str/reprs for when 

21# the scalar is printed on its own, while arrayprint.py has strs for when 

22# scalars are printed inside an ndarray. Only the latter strs are currently 

23# user-customizable. 

24 

25import functools 

26import numbers 

27try: 

28 from _thread import get_ident 

29except ImportError: 

30 from _dummy_thread import get_ident 

31 

32import numpy as np 

33from . import numerictypes as _nt 

34from .umath import absolute, isinf, isfinite, isnat 

35from . import multiarray 

36from .multiarray import (array, dragon4_positional, dragon4_scientific, 

37 datetime_as_string, datetime_data, ndarray, 

38 set_legacy_print_mode) 

39from .fromnumeric import any 

40from .numeric import concatenate, asarray, errstate 

41from .numerictypes import (longlong, intc, int_, float_, complex_, bool_, 

42 flexible) 

43from .overrides import array_function_dispatch, set_module 

44import warnings 

45import contextlib 

46 

47_format_options = { 

48 'edgeitems': 3, # repr N leading and trailing items of each dimension 

49 'threshold': 1000, # total items > triggers array summarization 

50 'floatmode': 'maxprec', 

51 'precision': 8, # precision of floating point representations 

52 'suppress': False, # suppress printing small floating values in exp format 

53 'linewidth': 75, 

54 'nanstr': 'nan', 

55 'infstr': 'inf', 

56 'sign': '-', 

57 'formatter': None, 

58 'legacy': False} 

59 

60def _make_options_dict(precision=None, threshold=None, edgeitems=None, 

61 linewidth=None, suppress=None, nanstr=None, infstr=None, 

62 sign=None, formatter=None, floatmode=None, legacy=None): 

63 """ make a dictionary out of the non-None arguments, plus sanity checks """ 

64 

65 options = {k: v for k, v in locals().items() if v is not None} 

66 

67 if suppress is not None: 

68 options['suppress'] = bool(suppress) 

69 

70 modes = ['fixed', 'unique', 'maxprec', 'maxprec_equal'] 

71 if floatmode not in modes + [None]: 

72 raise ValueError("floatmode option must be one of " + 

73 ", ".join('"{}"'.format(m) for m in modes)) 

74 

75 if sign not in [None, '-', '+', ' ']: 

76 raise ValueError("sign option must be one of ' ', '+', or '-'") 

77 

78 if legacy not in [None, False, '1.13']: 

79 warnings.warn("legacy printing option can currently only be '1.13' or " 

80 "`False`", stacklevel=3) 

81 if threshold is not None: 

82 # forbid the bad threshold arg suggested by stack overflow, gh-12351 

83 if not isinstance(threshold, numbers.Number): 

84 raise TypeError("threshold must be numeric") 

85 if np.isnan(threshold): 

86 raise ValueError("threshold must be non-NAN, try " 

87 "sys.maxsize for untruncated representation") 

88 return options 

89 

90 

91@set_module('numpy') 

92def set_printoptions(precision=None, threshold=None, edgeitems=None, 

93 linewidth=None, suppress=None, nanstr=None, infstr=None, 

94 formatter=None, sign=None, floatmode=None, *, legacy=None): 

95 """ 

96 Set printing options. 

97 

98 These options determine the way floating point numbers, arrays and 

99 other NumPy objects are displayed. 

100 

101 Parameters 

102 ---------- 

103 precision : int or None, optional 

104 Number of digits of precision for floating point output (default 8). 

105 May be None if `floatmode` is not `fixed`, to print as many digits as 

106 necessary to uniquely specify the value. 

107 threshold : int, optional 

108 Total number of array elements which trigger summarization 

109 rather than full repr (default 1000). 

110 To always use the full repr without summarization, pass `sys.maxsize`. 

111 edgeitems : int, optional 

112 Number of array items in summary at beginning and end of 

113 each dimension (default 3). 

114 linewidth : int, optional 

115 The number of characters per line for the purpose of inserting 

116 line breaks (default 75). 

117 suppress : bool, optional 

118 If True, always print floating point numbers using fixed point 

119 notation, in which case numbers equal to zero in the current precision 

120 will print as zero. If False, then scientific notation is used when 

121 absolute value of the smallest number is < 1e-4 or the ratio of the 

122 maximum absolute value to the minimum is > 1e3. The default is False. 

123 nanstr : str, optional 

124 String representation of floating point not-a-number (default nan). 

125 infstr : str, optional 

126 String representation of floating point infinity (default inf). 

127 sign : string, either '-', '+', or ' ', optional 

128 Controls printing of the sign of floating-point types. If '+', always 

129 print the sign of positive values. If ' ', always prints a space 

130 (whitespace character) in the sign position of positive values. If 

131 '-', omit the sign character of positive values. (default '-') 

132 formatter : dict of callables, optional 

133 If not None, the keys should indicate the type(s) that the respective 

134 formatting function applies to. Callables should return a string. 

135 Types that are not specified (by their corresponding keys) are handled 

136 by the default formatters. Individual types for which a formatter 

137 can be set are: 

138 

139 - 'bool' 

140 - 'int' 

141 - 'timedelta' : a `numpy.timedelta64` 

142 - 'datetime' : a `numpy.datetime64` 

143 - 'float' 

144 - 'longfloat' : 128-bit floats 

145 - 'complexfloat' 

146 - 'longcomplexfloat' : composed of two 128-bit floats 

147 - 'numpystr' : types `numpy.string_` and `numpy.unicode_` 

148 - 'object' : `np.object_` arrays 

149 - 'str' : all other strings 

150 

151 Other keys that can be used to set a group of types at once are: 

152 

153 - 'all' : sets all types 

154 - 'int_kind' : sets 'int' 

155 - 'float_kind' : sets 'float' and 'longfloat' 

156 - 'complex_kind' : sets 'complexfloat' and 'longcomplexfloat' 

157 - 'str_kind' : sets 'str' and 'numpystr' 

158 floatmode : str, optional 

159 Controls the interpretation of the `precision` option for 

160 floating-point types. Can take the following values 

161 (default maxprec_equal): 

162 

163 * 'fixed': Always print exactly `precision` fractional digits, 

164 even if this would print more or fewer digits than 

165 necessary to specify the value uniquely. 

166 * 'unique': Print the minimum number of fractional digits necessary 

167 to represent each value uniquely. Different elements may 

168 have a different number of digits. The value of the 

169 `precision` option is ignored. 

170 * 'maxprec': Print at most `precision` fractional digits, but if 

171 an element can be uniquely represented with fewer digits 

172 only print it with that many. 

173 * 'maxprec_equal': Print at most `precision` fractional digits, 

174 but if every element in the array can be uniquely 

175 represented with an equal number of fewer digits, use that 

176 many digits for all elements. 

177 legacy : string or `False`, optional 

178 If set to the string `'1.13'` enables 1.13 legacy printing mode. This 

179 approximates numpy 1.13 print output by including a space in the sign 

180 position of floats and different behavior for 0d arrays. If set to 

181 `False`, disables legacy mode. Unrecognized strings will be ignored 

182 with a warning for forward compatibility. 

183 

184 .. versionadded:: 1.14.0 

185 

186 See Also 

187 -------- 

188 get_printoptions, printoptions, set_string_function, array2string 

189 

190 Notes 

191 ----- 

192 `formatter` is always reset with a call to `set_printoptions`. 

193 

194 Use `printoptions` as a context manager to set the values temporarily. 

195 

196 Examples 

197 -------- 

198 Floating point precision can be set: 

199 

200 >>> np.set_printoptions(precision=4) 

201 >>> np.array([1.123456789]) 

202 [1.1235] 

203 

204 Long arrays can be summarised: 

205 

206 >>> np.set_printoptions(threshold=5) 

207 >>> np.arange(10) 

208 array([0, 1, 2, ..., 7, 8, 9]) 

209 

210 Small results can be suppressed: 

211 

212 >>> eps = np.finfo(float).eps 

213 >>> x = np.arange(4.) 

214 >>> x**2 - (x + eps)**2 

215 array([-4.9304e-32, -4.4409e-16, 0.0000e+00, 0.0000e+00]) 

216 >>> np.set_printoptions(suppress=True) 

217 >>> x**2 - (x + eps)**2 

218 array([-0., -0., 0., 0.]) 

219 

220 A custom formatter can be used to display array elements as desired: 

221 

222 >>> np.set_printoptions(formatter={'all':lambda x: 'int: '+str(-x)}) 

223 >>> x = np.arange(3) 

224 >>> x 

225 array([int: 0, int: -1, int: -2]) 

226 >>> np.set_printoptions() # formatter gets reset 

227 >>> x 

228 array([0, 1, 2]) 

229 

230 To put back the default options, you can use: 

231 

232 >>> np.set_printoptions(edgeitems=3, infstr='inf', 

233 ... linewidth=75, nanstr='nan', precision=8, 

234 ... suppress=False, threshold=1000, formatter=None) 

235 

236 Also to temporarily override options, use `printoptions` as a context manager: 

237 

238 >>> with np.printoptions(precision=2, suppress=True, threshold=5): 

239 ... np.linspace(0, 10, 10) 

240 array([ 0. , 1.11, 2.22, ..., 7.78, 8.89, 10. ]) 

241 

242 """ 

243 opt = _make_options_dict(precision, threshold, edgeitems, linewidth, 

244 suppress, nanstr, infstr, sign, formatter, 

245 floatmode, legacy) 

246 # formatter is always reset 

247 opt['formatter'] = formatter 

248 _format_options.update(opt) 

249 

250 # set the C variable for legacy mode 

251 if _format_options['legacy'] == '1.13': 

252 set_legacy_print_mode(113) 

253 # reset the sign option in legacy mode to avoid confusion 

254 _format_options['sign'] = '-' 

255 elif _format_options['legacy'] is False: 

256 set_legacy_print_mode(0) 

257 

258 

259@set_module('numpy') 

260def get_printoptions(): 

261 """ 

262 Return the current print options. 

263 

264 Returns 

265 ------- 

266 print_opts : dict 

267 Dictionary of current print options with keys 

268 

269 - precision : int 

270 - threshold : int 

271 - edgeitems : int 

272 - linewidth : int 

273 - suppress : bool 

274 - nanstr : str 

275 - infstr : str 

276 - formatter : dict of callables 

277 - sign : str 

278 

279 For a full description of these options, see `set_printoptions`. 

280 

281 See Also 

282 -------- 

283 set_printoptions, printoptions, set_string_function 

284 

285 """ 

286 return _format_options.copy() 

287 

288 

289@set_module('numpy') 

290@contextlib.contextmanager 

291def printoptions(*args, **kwargs): 

292 """Context manager for setting print options. 

293 

294 Set print options for the scope of the `with` block, and restore the old 

295 options at the end. See `set_printoptions` for the full description of 

296 available options. 

297 

298 Examples 

299 -------- 

300 

301 >>> from numpy.testing import assert_equal 

302 >>> with np.printoptions(precision=2): 

303 ... np.array([2.0]) / 3 

304 array([0.67]) 

305 

306 The `as`-clause of the `with`-statement gives the current print options: 

307 

308 >>> with np.printoptions(precision=2) as opts: 

309 ... assert_equal(opts, np.get_printoptions()) 

310 

311 See Also 

312 -------- 

313 set_printoptions, get_printoptions 

314 

315 """ 

316 opts = np.get_printoptions() 

317 try: 

318 np.set_printoptions(*args, **kwargs) 

319 yield np.get_printoptions() 

320 finally: 

321 np.set_printoptions(**opts) 

322 

323 

324def _leading_trailing(a, edgeitems, index=()): 

325 """ 

326 Keep only the N-D corners (leading and trailing edges) of an array. 

327 

328 Should be passed a base-class ndarray, since it makes no guarantees about 

329 preserving subclasses. 

330 """ 

331 axis = len(index) 

332 if axis == a.ndim: 

333 return a[index] 

334 

335 if a.shape[axis] > 2*edgeitems: 

336 return concatenate(( 

337 _leading_trailing(a, edgeitems, index + np.index_exp[ :edgeitems]), 

338 _leading_trailing(a, edgeitems, index + np.index_exp[-edgeitems:]) 

339 ), axis=axis) 

340 else: 

341 return _leading_trailing(a, edgeitems, index + np.index_exp[:]) 

342 

343 

344def _object_format(o): 

345 """ Object arrays containing lists should be printed unambiguously """ 

346 if type(o) is list: 

347 fmt = 'list({!r})' 

348 else: 

349 fmt = '{!r}' 

350 return fmt.format(o) 

351 

352def repr_format(x): 

353 return repr(x) 

354 

355def str_format(x): 

356 return str(x) 

357 

358def _get_formatdict(data, *, precision, floatmode, suppress, sign, legacy, 

359 formatter, **kwargs): 

360 # note: extra arguments in kwargs are ignored 

361 

362 # wrapped in lambdas to avoid taking a code path with the wrong type of data 

363 formatdict = { 

364 'bool': lambda: BoolFormat(data), 

365 'int': lambda: IntegerFormat(data), 

366 'float': lambda: FloatingFormat( 

367 data, precision, floatmode, suppress, sign, legacy=legacy), 

368 'longfloat': lambda: FloatingFormat( 

369 data, precision, floatmode, suppress, sign, legacy=legacy), 

370 'complexfloat': lambda: ComplexFloatingFormat( 

371 data, precision, floatmode, suppress, sign, legacy=legacy), 

372 'longcomplexfloat': lambda: ComplexFloatingFormat( 

373 data, precision, floatmode, suppress, sign, legacy=legacy), 

374 'datetime': lambda: DatetimeFormat(data, legacy=legacy), 

375 'timedelta': lambda: TimedeltaFormat(data), 

376 'object': lambda: _object_format, 

377 'void': lambda: str_format, 

378 'numpystr': lambda: repr_format, 

379 'str': lambda: str} 

380 

381 # we need to wrap values in `formatter` in a lambda, so that the interface 

382 # is the same as the above values. 

383 def indirect(x): 

384 return lambda: x 

385 

386 if formatter is not None: 

387 fkeys = [k for k in formatter.keys() if formatter[k] is not None] 

388 if 'all' in fkeys: 

389 for key in formatdict.keys(): 

390 formatdict[key] = indirect(formatter['all']) 

391 if 'int_kind' in fkeys: 

392 for key in ['int']: 

393 formatdict[key] = indirect(formatter['int_kind']) 

394 if 'float_kind' in fkeys: 

395 for key in ['float', 'longfloat']: 

396 formatdict[key] = indirect(formatter['float_kind']) 

397 if 'complex_kind' in fkeys: 

398 for key in ['complexfloat', 'longcomplexfloat']: 

399 formatdict[key] = indirect(formatter['complex_kind']) 

400 if 'str_kind' in fkeys: 

401 for key in ['numpystr', 'str']: 

402 formatdict[key] = indirect(formatter['str_kind']) 

403 for key in formatdict.keys(): 

404 if key in fkeys: 

405 formatdict[key] = indirect(formatter[key]) 

406 

407 return formatdict 

408 

409def _get_format_function(data, **options): 

410 """ 

411 find the right formatting function for the dtype_ 

412 """ 

413 dtype_ = data.dtype 

414 dtypeobj = dtype_.type 

415 formatdict = _get_formatdict(data, **options) 

416 if issubclass(dtypeobj, _nt.bool_): 

417 return formatdict['bool']() 

418 elif issubclass(dtypeobj, _nt.integer): 

419 if issubclass(dtypeobj, _nt.timedelta64): 

420 return formatdict['timedelta']() 

421 else: 

422 return formatdict['int']() 

423 elif issubclass(dtypeobj, _nt.floating): 

424 if issubclass(dtypeobj, _nt.longfloat): 

425 return formatdict['longfloat']() 

426 else: 

427 return formatdict['float']() 

428 elif issubclass(dtypeobj, _nt.complexfloating): 

429 if issubclass(dtypeobj, _nt.clongfloat): 

430 return formatdict['longcomplexfloat']() 

431 else: 

432 return formatdict['complexfloat']() 

433 elif issubclass(dtypeobj, (_nt.unicode_, _nt.string_)): 

434 return formatdict['numpystr']() 

435 elif issubclass(dtypeobj, _nt.datetime64): 

436 return formatdict['datetime']() 

437 elif issubclass(dtypeobj, _nt.object_): 

438 return formatdict['object']() 

439 elif issubclass(dtypeobj, _nt.void): 

440 if dtype_.names is not None: 

441 return StructuredVoidFormat.from_data(data, **options) 

442 else: 

443 return formatdict['void']() 

444 else: 

445 return formatdict['numpystr']() 

446 

447 

448def _recursive_guard(fillvalue='...'): 

449 """ 

450 Like the python 3.2 reprlib.recursive_repr, but forwards *args and **kwargs 

451 

452 Decorates a function such that if it calls itself with the same first 

453 argument, it returns `fillvalue` instead of recursing. 

454 

455 Largely copied from reprlib.recursive_repr 

456 """ 

457 

458 def decorating_function(f): 

459 repr_running = set() 

460 

461 @functools.wraps(f) 

462 def wrapper(self, *args, **kwargs): 

463 key = id(self), get_ident() 

464 if key in repr_running: 

465 return fillvalue 

466 repr_running.add(key) 

467 try: 

468 return f(self, *args, **kwargs) 

469 finally: 

470 repr_running.discard(key) 

471 

472 return wrapper 

473 

474 return decorating_function 

475 

476 

477# gracefully handle recursive calls, when object arrays contain themselves 

478@_recursive_guard() 

479def _array2string(a, options, separator=' ', prefix=""): 

480 # The formatter __init__s in _get_format_function cannot deal with 

481 # subclasses yet, and we also need to avoid recursion issues in 

482 # _formatArray with subclasses which return 0d arrays in place of scalars 

483 data = asarray(a) 

484 if a.shape == (): 

485 a = data 

486 

487 if a.size > options['threshold']: 

488 summary_insert = "..." 

489 data = _leading_trailing(data, options['edgeitems']) 

490 else: 

491 summary_insert = "" 

492 

493 # find the right formatting function for the array 

494 format_function = _get_format_function(data, **options) 

495 

496 # skip over "[" 

497 next_line_prefix = " " 

498 # skip over array( 

499 next_line_prefix += " "*len(prefix) 

500 

501 lst = _formatArray(a, format_function, options['linewidth'], 

502 next_line_prefix, separator, options['edgeitems'], 

503 summary_insert, options['legacy']) 

504 return lst 

505 

506 

507def _array2string_dispatcher( 

508 a, max_line_width=None, precision=None, 

509 suppress_small=None, separator=None, prefix=None, 

510 style=None, formatter=None, threshold=None, 

511 edgeitems=None, sign=None, floatmode=None, suffix=None, 

512 *, legacy=None): 

513 return (a,) 

514 

515 

516@array_function_dispatch(_array2string_dispatcher, module='numpy') 

517def array2string(a, max_line_width=None, precision=None, 

518 suppress_small=None, separator=' ', prefix="", 

519 style=np._NoValue, formatter=None, threshold=None, 

520 edgeitems=None, sign=None, floatmode=None, suffix="", 

521 *, legacy=None): 

522 """ 

523 Return a string representation of an array. 

524 

525 Parameters 

526 ---------- 

527 a : array_like 

528 Input array. 

529 max_line_width : int, optional 

530 Inserts newlines if text is longer than `max_line_width`. 

531 Defaults to ``numpy.get_printoptions()['linewidth']``. 

532 precision : int or None, optional 

533 Floating point precision. 

534 Defaults to ``numpy.get_printoptions()['precision']``. 

535 suppress_small : bool, optional 

536 Represent numbers "very close" to zero as zero; default is False. 

537 Very close is defined by precision: if the precision is 8, e.g., 

538 numbers smaller (in absolute value) than 5e-9 are represented as 

539 zero. 

540 Defaults to ``numpy.get_printoptions()['suppress']``. 

541 separator : str, optional 

542 Inserted between elements. 

543 prefix : str, optional 

544 suffix: str, optional 

545 The length of the prefix and suffix strings are used to respectively 

546 align and wrap the output. An array is typically printed as:: 

547 

548 prefix + array2string(a) + suffix 

549 

550 The output is left-padded by the length of the prefix string, and 

551 wrapping is forced at the column ``max_line_width - len(suffix)``. 

552 It should be noted that the content of prefix and suffix strings are 

553 not included in the output. 

554 style : _NoValue, optional 

555 Has no effect, do not use. 

556 

557 .. deprecated:: 1.14.0 

558 formatter : dict of callables, optional 

559 If not None, the keys should indicate the type(s) that the respective 

560 formatting function applies to. Callables should return a string. 

561 Types that are not specified (by their corresponding keys) are handled 

562 by the default formatters. Individual types for which a formatter 

563 can be set are: 

564 

565 - 'bool' 

566 - 'int' 

567 - 'timedelta' : a `numpy.timedelta64` 

568 - 'datetime' : a `numpy.datetime64` 

569 - 'float' 

570 - 'longfloat' : 128-bit floats 

571 - 'complexfloat' 

572 - 'longcomplexfloat' : composed of two 128-bit floats 

573 - 'void' : type `numpy.void` 

574 - 'numpystr' : types `numpy.string_` and `numpy.unicode_` 

575 - 'str' : all other strings 

576 

577 Other keys that can be used to set a group of types at once are: 

578 

579 - 'all' : sets all types 

580 - 'int_kind' : sets 'int' 

581 - 'float_kind' : sets 'float' and 'longfloat' 

582 - 'complex_kind' : sets 'complexfloat' and 'longcomplexfloat' 

583 - 'str_kind' : sets 'str' and 'numpystr' 

584 threshold : int, optional 

585 Total number of array elements which trigger summarization 

586 rather than full repr. 

587 Defaults to ``numpy.get_printoptions()['threshold']``. 

588 edgeitems : int, optional 

589 Number of array items in summary at beginning and end of 

590 each dimension. 

591 Defaults to ``numpy.get_printoptions()['edgeitems']``. 

592 sign : string, either '-', '+', or ' ', optional 

593 Controls printing of the sign of floating-point types. If '+', always 

594 print the sign of positive values. If ' ', always prints a space 

595 (whitespace character) in the sign position of positive values. If 

596 '-', omit the sign character of positive values. 

597 Defaults to ``numpy.get_printoptions()['sign']``. 

598 floatmode : str, optional 

599 Controls the interpretation of the `precision` option for 

600 floating-point types. 

601 Defaults to ``numpy.get_printoptions()['floatmode']``. 

602 Can take the following values: 

603 

604 - 'fixed': Always print exactly `precision` fractional digits, 

605 even if this would print more or fewer digits than 

606 necessary to specify the value uniquely. 

607 - 'unique': Print the minimum number of fractional digits necessary 

608 to represent each value uniquely. Different elements may 

609 have a different number of digits. The value of the 

610 `precision` option is ignored. 

611 - 'maxprec': Print at most `precision` fractional digits, but if 

612 an element can be uniquely represented with fewer digits 

613 only print it with that many. 

614 - 'maxprec_equal': Print at most `precision` fractional digits, 

615 but if every element in the array can be uniquely 

616 represented with an equal number of fewer digits, use that 

617 many digits for all elements. 

618 legacy : string or `False`, optional 

619 If set to the string `'1.13'` enables 1.13 legacy printing mode. This 

620 approximates numpy 1.13 print output by including a space in the sign 

621 position of floats and different behavior for 0d arrays. If set to 

622 `False`, disables legacy mode. Unrecognized strings will be ignored 

623 with a warning for forward compatibility. 

624 

625 .. versionadded:: 1.14.0 

626 

627 Returns 

628 ------- 

629 array_str : str 

630 String representation of the array. 

631 

632 Raises 

633 ------ 

634 TypeError 

635 if a callable in `formatter` does not return a string. 

636 

637 See Also 

638 -------- 

639 array_str, array_repr, set_printoptions, get_printoptions 

640 

641 Notes 

642 ----- 

643 If a formatter is specified for a certain type, the `precision` keyword is 

644 ignored for that type. 

645 

646 This is a very flexible function; `array_repr` and `array_str` are using 

647 `array2string` internally so keywords with the same name should work 

648 identically in all three functions. 

649 

650 Examples 

651 -------- 

652 >>> x = np.array([1e-16,1,2,3]) 

653 >>> np.array2string(x, precision=2, separator=',', 

654 ... suppress_small=True) 

655 '[0.,1.,2.,3.]' 

656 

657 >>> x = np.arange(3.) 

658 >>> np.array2string(x, formatter={'float_kind':lambda x: "%.2f" % x}) 

659 '[0.00 1.00 2.00]' 

660 

661 >>> x = np.arange(3) 

662 >>> np.array2string(x, formatter={'int':lambda x: hex(x)}) 

663 '[0x0 0x1 0x2]' 

664 

665 """ 

666 

667 overrides = _make_options_dict(precision, threshold, edgeitems, 

668 max_line_width, suppress_small, None, None, 

669 sign, formatter, floatmode, legacy) 

670 options = _format_options.copy() 

671 options.update(overrides) 

672 

673 if options['legacy'] == '1.13': 

674 if style is np._NoValue: 

675 style = repr 

676 

677 if a.shape == () and a.dtype.names is None: 

678 return style(a.item()) 

679 elif style is not np._NoValue: 

680 # Deprecation 11-9-2017 v1.14 

681 warnings.warn("'style' argument is deprecated and no longer functional" 

682 " except in 1.13 'legacy' mode", 

683 DeprecationWarning, stacklevel=3) 

684 

685 if options['legacy'] != '1.13': 

686 options['linewidth'] -= len(suffix) 

687 

688 # treat as a null array if any of shape elements == 0 

689 if a.size == 0: 

690 return "[]" 

691 

692 return _array2string(a, options, separator, prefix) 

693 

694 

695def _extendLine(s, line, word, line_width, next_line_prefix, legacy): 

696 needs_wrap = len(line) + len(word) > line_width 

697 if legacy != '1.13': 

698 s# don't wrap lines if it won't help 

699 if len(line) <= len(next_line_prefix): 

700 needs_wrap = False 

701 

702 if needs_wrap: 

703 s += line.rstrip() + "\n" 

704 line = next_line_prefix 

705 line += word 

706 return s, line 

707 

708 

709def _formatArray(a, format_function, line_width, next_line_prefix, 

710 separator, edge_items, summary_insert, legacy): 

711 """formatArray is designed for two modes of operation: 

712 

713 1. Full output 

714 

715 2. Summarized output 

716 

717 """ 

718 def recurser(index, hanging_indent, curr_width): 

719 """ 

720 By using this local function, we don't need to recurse with all the 

721 arguments. Since this function is not created recursively, the cost is 

722 not significant 

723 """ 

724 axis = len(index) 

725 axes_left = a.ndim - axis 

726 

727 if axes_left == 0: 

728 return format_function(a[index]) 

729 

730 # when recursing, add a space to align with the [ added, and reduce the 

731 # length of the line by 1 

732 next_hanging_indent = hanging_indent + ' ' 

733 if legacy == '1.13': 

734 next_width = curr_width 

735 else: 

736 next_width = curr_width - len(']') 

737 

738 a_len = a.shape[axis] 

739 show_summary = summary_insert and 2*edge_items < a_len 

740 if show_summary: 

741 leading_items = edge_items 

742 trailing_items = edge_items 

743 else: 

744 leading_items = 0 

745 trailing_items = a_len 

746 

747 # stringify the array with the hanging indent on the first line too 

748 s = '' 

749 

750 # last axis (rows) - wrap elements if they would not fit on one line 

751 if axes_left == 1: 

752 # the length up until the beginning of the separator / bracket 

753 if legacy == '1.13': 

754 elem_width = curr_width - len(separator.rstrip()) 

755 else: 

756 elem_width = curr_width - max(len(separator.rstrip()), len(']')) 

757 

758 line = hanging_indent 

759 for i in range(leading_items): 

760 word = recurser(index + (i,), next_hanging_indent, next_width) 

761 s, line = _extendLine( 

762 s, line, word, elem_width, hanging_indent, legacy) 

763 line += separator 

764 

765 if show_summary: 

766 s, line = _extendLine( 

767 s, line, summary_insert, elem_width, hanging_indent, legacy) 

768 if legacy == '1.13': 

769 line += ", " 

770 else: 

771 line += separator 

772 

773 for i in range(trailing_items, 1, -1): 

774 word = recurser(index + (-i,), next_hanging_indent, next_width) 

775 s, line = _extendLine( 

776 s, line, word, elem_width, hanging_indent, legacy) 

777 line += separator 

778 

779 if legacy == '1.13': 

780 # width of the separator is not considered on 1.13 

781 elem_width = curr_width 

782 word = recurser(index + (-1,), next_hanging_indent, next_width) 

783 s, line = _extendLine( 

784 s, line, word, elem_width, hanging_indent, legacy) 

785 

786 s += line 

787 

788 # other axes - insert newlines between rows 

789 else: 

790 s = '' 

791 line_sep = separator.rstrip() + '\n'*(axes_left - 1) 

792 

793 for i in range(leading_items): 

794 nested = recurser(index + (i,), next_hanging_indent, next_width) 

795 s += hanging_indent + nested + line_sep 

796 

797 if show_summary: 

798 if legacy == '1.13': 

799 # trailing space, fixed nbr of newlines, and fixed separator 

800 s += hanging_indent + summary_insert + ", \n" 

801 else: 

802 s += hanging_indent + summary_insert + line_sep 

803 

804 for i in range(trailing_items, 1, -1): 

805 nested = recurser(index + (-i,), next_hanging_indent, 

806 next_width) 

807 s += hanging_indent + nested + line_sep 

808 

809 nested = recurser(index + (-1,), next_hanging_indent, next_width) 

810 s += hanging_indent + nested 

811 

812 # remove the hanging indent, and wrap in [] 

813 s = '[' + s[len(hanging_indent):] + ']' 

814 return s 

815 

816 try: 

817 # invoke the recursive part with an initial index and prefix 

818 return recurser(index=(), 

819 hanging_indent=next_line_prefix, 

820 curr_width=line_width) 

821 finally: 

822 # recursive closures have a cyclic reference to themselves, which 

823 # requires gc to collect (gh-10620). To avoid this problem, for 

824 # performance and PyPy friendliness, we break the cycle: 

825 recurser = None 

826 

827def _none_or_positive_arg(x, name): 

828 if x is None: 

829 return -1 

830 if x < 0: 

831 raise ValueError("{} must be >= 0".format(name)) 

832 return x 

833 

834class FloatingFormat: 

835 """ Formatter for subtypes of np.floating """ 

836 def __init__(self, data, precision, floatmode, suppress_small, sign=False, 

837 *, legacy=None): 

838 # for backcompatibility, accept bools 

839 if isinstance(sign, bool): 

840 sign = '+' if sign else '-' 

841 

842 self._legacy = legacy 

843 if self._legacy == '1.13': 

844 # when not 0d, legacy does not support '-' 

845 if data.shape != () and sign == '-': 

846 sign = ' ' 

847 

848 self.floatmode = floatmode 

849 if floatmode == 'unique': 

850 self.precision = None 

851 else: 

852 self.precision = precision 

853 

854 self.precision = _none_or_positive_arg(self.precision, 'precision') 

855 

856 self.suppress_small = suppress_small 

857 self.sign = sign 

858 self.exp_format = False 

859 self.large_exponent = False 

860 

861 self.fillFormat(data) 

862 

863 def fillFormat(self, data): 

864 # only the finite values are used to compute the number of digits 

865 finite_vals = data[isfinite(data)] 

866 

867 # choose exponential mode based on the non-zero finite values: 

868 abs_non_zero = absolute(finite_vals[finite_vals != 0]) 

869 if len(abs_non_zero) != 0: 

870 max_val = np.max(abs_non_zero) 

871 min_val = np.min(abs_non_zero) 

872 with errstate(over='ignore'): # division can overflow 

873 if max_val >= 1.e8 or (not self.suppress_small and 

874 (min_val < 0.0001 or max_val/min_val > 1000.)): 

875 self.exp_format = True 

876 

877 # do a first pass of printing all the numbers, to determine sizes 

878 if len(finite_vals) == 0: 

879 self.pad_left = 0 

880 self.pad_right = 0 

881 self.trim = '.' 

882 self.exp_size = -1 

883 self.unique = True 

884 elif self.exp_format: 

885 trim, unique = '.', True 

886 if self.floatmode == 'fixed' or self._legacy == '1.13': 

887 trim, unique = 'k', False 

888 strs = (dragon4_scientific(x, precision=self.precision, 

889 unique=unique, trim=trim, sign=self.sign == '+') 

890 for x in finite_vals) 

891 frac_strs, _, exp_strs = zip(*(s.partition('e') for s in strs)) 

892 int_part, frac_part = zip(*(s.split('.') for s in frac_strs)) 

893 self.exp_size = max(len(s) for s in exp_strs) - 1 

894 

895 self.trim = 'k' 

896 self.precision = max(len(s) for s in frac_part) 

897 

898 # for back-compat with np 1.13, use 2 spaces & sign and full prec 

899 if self._legacy == '1.13': 

900 self.pad_left = 3 

901 else: 

902 # this should be only 1 or 2. Can be calculated from sign. 

903 self.pad_left = max(len(s) for s in int_part) 

904 # pad_right is only needed for nan length calculation 

905 self.pad_right = self.exp_size + 2 + self.precision 

906 

907 self.unique = False 

908 else: 

909 # first pass printing to determine sizes 

910 trim, unique = '.', True 

911 if self.floatmode == 'fixed': 

912 trim, unique = 'k', False 

913 strs = (dragon4_positional(x, precision=self.precision, 

914 fractional=True, 

915 unique=unique, trim=trim, 

916 sign=self.sign == '+') 

917 for x in finite_vals) 

918 int_part, frac_part = zip(*(s.split('.') for s in strs)) 

919 if self._legacy == '1.13': 

920 self.pad_left = 1 + max(len(s.lstrip('-+')) for s in int_part) 

921 else: 

922 self.pad_left = max(len(s) for s in int_part) 

923 self.pad_right = max(len(s) for s in frac_part) 

924 self.exp_size = -1 

925 

926 if self.floatmode in ['fixed', 'maxprec_equal']: 

927 self.precision = self.pad_right 

928 self.unique = False 

929 self.trim = 'k' 

930 else: 

931 self.unique = True 

932 self.trim = '.' 

933 

934 if self._legacy != '1.13': 

935 # account for sign = ' ' by adding one to pad_left 

936 if self.sign == ' ' and not any(np.signbit(finite_vals)): 

937 self.pad_left += 1 

938 

939 # if there are non-finite values, may need to increase pad_left 

940 if data.size != finite_vals.size: 

941 neginf = self.sign != '-' or any(data[isinf(data)] < 0) 

942 nanlen = len(_format_options['nanstr']) 

943 inflen = len(_format_options['infstr']) + neginf 

944 offset = self.pad_right + 1 # +1 for decimal pt 

945 self.pad_left = max(self.pad_left, nanlen - offset, inflen - offset) 

946 

947 def __call__(self, x): 

948 if not np.isfinite(x): 

949 with errstate(invalid='ignore'): 

950 if np.isnan(x): 

951 sign = '+' if self.sign == '+' else '' 

952 ret = sign + _format_options['nanstr'] 

953 else: # isinf 

954 sign = '-' if x < 0 else '+' if self.sign == '+' else '' 

955 ret = sign + _format_options['infstr'] 

956 return ' '*(self.pad_left + self.pad_right + 1 - len(ret)) + ret 

957 

958 if self.exp_format: 

959 return dragon4_scientific(x, 

960 precision=self.precision, 

961 unique=self.unique, 

962 trim=self.trim, 

963 sign=self.sign == '+', 

964 pad_left=self.pad_left, 

965 exp_digits=self.exp_size) 

966 else: 

967 return dragon4_positional(x, 

968 precision=self.precision, 

969 unique=self.unique, 

970 fractional=True, 

971 trim=self.trim, 

972 sign=self.sign == '+', 

973 pad_left=self.pad_left, 

974 pad_right=self.pad_right) 

975 

976 

977@set_module('numpy') 

978def format_float_scientific(x, precision=None, unique=True, trim='k', 

979 sign=False, pad_left=None, exp_digits=None): 

980 """ 

981 Format a floating-point scalar as a decimal string in scientific notation. 

982 

983 Provides control over rounding, trimming and padding. Uses and assumes 

984 IEEE unbiased rounding. Uses the "Dragon4" algorithm. 

985 

986 Parameters 

987 ---------- 

988 x : python float or numpy floating scalar 

989 Value to format. 

990 precision : non-negative integer or None, optional 

991 Maximum number of digits to print. May be None if `unique` is 

992 `True`, but must be an integer if unique is `False`. 

993 unique : boolean, optional 

994 If `True`, use a digit-generation strategy which gives the shortest 

995 representation which uniquely identifies the floating-point number from 

996 other values of the same type, by judicious rounding. If `precision` 

997 was omitted, print all necessary digits, otherwise digit generation is 

998 cut off after `precision` digits and the remaining value is rounded. 

999 If `False`, digits are generated as if printing an infinite-precision 

1000 value and stopping after `precision` digits, rounding the remaining 

1001 value. 

1002 trim : one of 'k', '.', '0', '-', optional 

1003 Controls post-processing trimming of trailing digits, as follows: 

1004 

1005 * 'k' : keep trailing zeros, keep decimal point (no trimming) 

1006 * '.' : trim all trailing zeros, leave decimal point 

1007 * '0' : trim all but the zero before the decimal point. Insert the 

1008 zero if it is missing. 

1009 * '-' : trim trailing zeros and any trailing decimal point 

1010 sign : boolean, optional 

1011 Whether to show the sign for positive values. 

1012 pad_left : non-negative integer, optional 

1013 Pad the left side of the string with whitespace until at least that 

1014 many characters are to the left of the decimal point. 

1015 exp_digits : non-negative integer, optional 

1016 Pad the exponent with zeros until it contains at least this many digits. 

1017 If omitted, the exponent will be at least 2 digits. 

1018 

1019 Returns 

1020 ------- 

1021 rep : string 

1022 The string representation of the floating point value 

1023 

1024 See Also 

1025 -------- 

1026 format_float_positional 

1027 

1028 Examples 

1029 -------- 

1030 >>> np.format_float_scientific(np.float32(np.pi)) 

1031 '3.1415927e+00' 

1032 >>> s = np.float32(1.23e24) 

1033 >>> np.format_float_scientific(s, unique=False, precision=15) 

1034 '1.230000071797338e+24' 

1035 >>> np.format_float_scientific(s, exp_digits=4) 

1036 '1.23e+0024' 

1037 """ 

1038 precision = _none_or_positive_arg(precision, 'precision') 

1039 pad_left = _none_or_positive_arg(pad_left, 'pad_left') 

1040 exp_digits = _none_or_positive_arg(exp_digits, 'exp_digits') 

1041 return dragon4_scientific(x, precision=precision, unique=unique, 

1042 trim=trim, sign=sign, pad_left=pad_left, 

1043 exp_digits=exp_digits) 

1044 

1045 

1046@set_module('numpy') 

1047def format_float_positional(x, precision=None, unique=True, 

1048 fractional=True, trim='k', sign=False, 

1049 pad_left=None, pad_right=None): 

1050 """ 

1051 Format a floating-point scalar as a decimal string in positional notation. 

1052 

1053 Provides control over rounding, trimming and padding. Uses and assumes 

1054 IEEE unbiased rounding. Uses the "Dragon4" algorithm. 

1055 

1056 Parameters 

1057 ---------- 

1058 x : python float or numpy floating scalar 

1059 Value to format. 

1060 precision : non-negative integer or None, optional 

1061 Maximum number of digits to print. May be None if `unique` is 

1062 `True`, but must be an integer if unique is `False`. 

1063 unique : boolean, optional 

1064 If `True`, use a digit-generation strategy which gives the shortest 

1065 representation which uniquely identifies the floating-point number from 

1066 other values of the same type, by judicious rounding. If `precision` 

1067 was omitted, print out all necessary digits, otherwise digit generation 

1068 is cut off after `precision` digits and the remaining value is rounded. 

1069 If `False`, digits are generated as if printing an infinite-precision 

1070 value and stopping after `precision` digits, rounding the remaining 

1071 value. 

1072 fractional : boolean, optional 

1073 If `True`, the cutoff of `precision` digits refers to the total number 

1074 of digits after the decimal point, including leading zeros. 

1075 If `False`, `precision` refers to the total number of significant 

1076 digits, before or after the decimal point, ignoring leading zeros. 

1077 trim : one of 'k', '.', '0', '-', optional 

1078 Controls post-processing trimming of trailing digits, as follows: 

1079 

1080 * 'k' : keep trailing zeros, keep decimal point (no trimming) 

1081 * '.' : trim all trailing zeros, leave decimal point 

1082 * '0' : trim all but the zero before the decimal point. Insert the 

1083 zero if it is missing. 

1084 * '-' : trim trailing zeros and any trailing decimal point 

1085 sign : boolean, optional 

1086 Whether to show the sign for positive values. 

1087 pad_left : non-negative integer, optional 

1088 Pad the left side of the string with whitespace until at least that 

1089 many characters are to the left of the decimal point. 

1090 pad_right : non-negative integer, optional 

1091 Pad the right side of the string with whitespace until at least that 

1092 many characters are to the right of the decimal point. 

1093 

1094 Returns 

1095 ------- 

1096 rep : string 

1097 The string representation of the floating point value 

1098 

1099 See Also 

1100 -------- 

1101 format_float_scientific 

1102 

1103 Examples 

1104 -------- 

1105 >>> np.format_float_positional(np.float32(np.pi)) 

1106 '3.1415927' 

1107 >>> np.format_float_positional(np.float16(np.pi)) 

1108 '3.14' 

1109 >>> np.format_float_positional(np.float16(0.3)) 

1110 '0.3' 

1111 >>> np.format_float_positional(np.float16(0.3), unique=False, precision=10) 

1112 '0.3000488281' 

1113 """ 

1114 precision = _none_or_positive_arg(precision, 'precision') 

1115 pad_left = _none_or_positive_arg(pad_left, 'pad_left') 

1116 pad_right = _none_or_positive_arg(pad_right, 'pad_right') 

1117 return dragon4_positional(x, precision=precision, unique=unique, 

1118 fractional=fractional, trim=trim, 

1119 sign=sign, pad_left=pad_left, 

1120 pad_right=pad_right) 

1121 

1122 

1123class IntegerFormat: 

1124 def __init__(self, data): 

1125 if data.size > 0: 

1126 max_str_len = max(len(str(np.max(data))), 

1127 len(str(np.min(data)))) 

1128 else: 

1129 max_str_len = 0 

1130 self.format = '%{}d'.format(max_str_len) 

1131 

1132 def __call__(self, x): 

1133 return self.format % x 

1134 

1135 

1136class BoolFormat: 

1137 def __init__(self, data, **kwargs): 

1138 # add an extra space so " True" and "False" have the same length and 

1139 # array elements align nicely when printed, except in 0d arrays 

1140 self.truestr = ' True' if data.shape != () else 'True' 

1141 

1142 def __call__(self, x): 

1143 return self.truestr if x else "False" 

1144 

1145 

1146class ComplexFloatingFormat: 

1147 """ Formatter for subtypes of np.complexfloating """ 

1148 def __init__(self, x, precision, floatmode, suppress_small, 

1149 sign=False, *, legacy=None): 

1150 # for backcompatibility, accept bools 

1151 if isinstance(sign, bool): 

1152 sign = '+' if sign else '-' 

1153 

1154 floatmode_real = floatmode_imag = floatmode 

1155 if legacy == '1.13': 

1156 floatmode_real = 'maxprec_equal' 

1157 floatmode_imag = 'maxprec' 

1158 

1159 self.real_format = FloatingFormat( 

1160 x.real, precision, floatmode_real, suppress_small, 

1161 sign=sign, legacy=legacy 

1162 ) 

1163 self.imag_format = FloatingFormat( 

1164 x.imag, precision, floatmode_imag, suppress_small, 

1165 sign='+', legacy=legacy 

1166 ) 

1167 

1168 def __call__(self, x): 

1169 r = self.real_format(x.real) 

1170 i = self.imag_format(x.imag) 

1171 

1172 # add the 'j' before the terminal whitespace in i 

1173 sp = len(i.rstrip()) 

1174 i = i[:sp] + 'j' + i[sp:] 

1175 

1176 return r + i 

1177 

1178 

1179class _TimelikeFormat: 

1180 def __init__(self, data): 

1181 non_nat = data[~isnat(data)] 

1182 if len(non_nat) > 0: 

1183 # Max str length of non-NaT elements 

1184 max_str_len = max(len(self._format_non_nat(np.max(non_nat))), 

1185 len(self._format_non_nat(np.min(non_nat)))) 

1186 else: 

1187 max_str_len = 0 

1188 if len(non_nat) < data.size: 

1189 # data contains a NaT 

1190 max_str_len = max(max_str_len, 5) 

1191 self._format = '%{}s'.format(max_str_len) 

1192 self._nat = "'NaT'".rjust(max_str_len) 

1193 

1194 def _format_non_nat(self, x): 

1195 # override in subclass 

1196 raise NotImplementedError 

1197 

1198 def __call__(self, x): 

1199 if isnat(x): 

1200 return self._nat 

1201 else: 

1202 return self._format % self._format_non_nat(x) 

1203 

1204 

1205class DatetimeFormat(_TimelikeFormat): 

1206 def __init__(self, x, unit=None, timezone=None, casting='same_kind', 

1207 legacy=False): 

1208 # Get the unit from the dtype 

1209 if unit is None: 

1210 if x.dtype.kind == 'M': 

1211 unit = datetime_data(x.dtype)[0] 

1212 else: 

1213 unit = 's' 

1214 

1215 if timezone is None: 

1216 timezone = 'naive' 

1217 self.timezone = timezone 

1218 self.unit = unit 

1219 self.casting = casting 

1220 self.legacy = legacy 

1221 

1222 # must be called after the above are configured 

1223 super(DatetimeFormat, self).__init__(x) 

1224 

1225 def __call__(self, x): 

1226 if self.legacy == '1.13': 

1227 return self._format_non_nat(x) 

1228 return super(DatetimeFormat, self).__call__(x) 

1229 

1230 def _format_non_nat(self, x): 

1231 return "'%s'" % datetime_as_string(x, 

1232 unit=self.unit, 

1233 timezone=self.timezone, 

1234 casting=self.casting) 

1235 

1236 

1237class TimedeltaFormat(_TimelikeFormat): 

1238 def _format_non_nat(self, x): 

1239 return str(x.astype('i8')) 

1240 

1241 

1242class SubArrayFormat: 

1243 def __init__(self, format_function): 

1244 self.format_function = format_function 

1245 

1246 def __call__(self, arr): 

1247 if arr.ndim <= 1: 

1248 return "[" + ", ".join(self.format_function(a) for a in arr) + "]" 

1249 return "[" + ", ".join(self.__call__(a) for a in arr) + "]" 

1250 

1251 

1252class StructuredVoidFormat: 

1253 """ 

1254 Formatter for structured np.void objects. 

1255 

1256 This does not work on structured alias types like np.dtype(('i4', 'i2,i2')), 

1257 as alias scalars lose their field information, and the implementation 

1258 relies upon np.void.__getitem__. 

1259 """ 

1260 def __init__(self, format_functions): 

1261 self.format_functions = format_functions 

1262 

1263 @classmethod 

1264 def from_data(cls, data, **options): 

1265 """ 

1266 This is a second way to initialize StructuredVoidFormat, using the raw data 

1267 as input. Added to avoid changing the signature of __init__. 

1268 """ 

1269 format_functions = [] 

1270 for field_name in data.dtype.names: 

1271 format_function = _get_format_function(data[field_name], **options) 

1272 if data.dtype[field_name].shape != (): 

1273 format_function = SubArrayFormat(format_function) 

1274 format_functions.append(format_function) 

1275 return cls(format_functions) 

1276 

1277 def __call__(self, x): 

1278 str_fields = [ 

1279 format_function(field) 

1280 for field, format_function in zip(x, self.format_functions) 

1281 ] 

1282 if len(str_fields) == 1: 

1283 return "({},)".format(str_fields[0]) 

1284 else: 

1285 return "({})".format(", ".join(str_fields)) 

1286 

1287 

1288def _void_scalar_repr(x): 

1289 """ 

1290 Implements the repr for structured-void scalars. It is called from the 

1291 scalartypes.c.src code, and is placed here because it uses the elementwise 

1292 formatters defined above. 

1293 """ 

1294 return StructuredVoidFormat.from_data(array(x), **_format_options)(x) 

1295 

1296 

1297_typelessdata = [int_, float_, complex_, bool_] 

1298if issubclass(intc, int): 

1299 _typelessdata.append(intc) 

1300if issubclass(longlong, int): 

1301 _typelessdata.append(longlong) 

1302 

1303 

1304def dtype_is_implied(dtype): 

1305 """ 

1306 Determine if the given dtype is implied by the representation of its values. 

1307 

1308 Parameters 

1309 ---------- 

1310 dtype : dtype 

1311 Data type 

1312 

1313 Returns 

1314 ------- 

1315 implied : bool 

1316 True if the dtype is implied by the representation of its values. 

1317 

1318 Examples 

1319 -------- 

1320 >>> np.core.arrayprint.dtype_is_implied(int) 

1321 True 

1322 >>> np.array([1, 2, 3], int) 

1323 array([1, 2, 3]) 

1324 >>> np.core.arrayprint.dtype_is_implied(np.int8) 

1325 False 

1326 >>> np.array([1, 2, 3], np.int8) 

1327 array([1, 2, 3], dtype=int8) 

1328 """ 

1329 dtype = np.dtype(dtype) 

1330 if _format_options['legacy'] == '1.13' and dtype.type == bool_: 

1331 return False 

1332 

1333 # not just void types can be structured, and names are not part of the repr 

1334 if dtype.names is not None: 

1335 return False 

1336 

1337 return dtype.type in _typelessdata 

1338 

1339 

1340def dtype_short_repr(dtype): 

1341 """ 

1342 Convert a dtype to a short form which evaluates to the same dtype. 

1343 

1344 The intent is roughly that the following holds 

1345 

1346 >>> from numpy import * 

1347 >>> dt = np.int64([1, 2]).dtype 

1348 >>> assert eval(dtype_short_repr(dt)) == dt 

1349 """ 

1350 if dtype.names is not None: 

1351 # structured dtypes give a list or tuple repr 

1352 return str(dtype) 

1353 elif issubclass(dtype.type, flexible): 

1354 # handle these separately so they don't give garbage like str256 

1355 return "'%s'" % str(dtype) 

1356 

1357 typename = dtype.name 

1358 # quote typenames which can't be represented as python variable names 

1359 if typename and not (typename[0].isalpha() and typename.isalnum()): 

1360 typename = repr(typename) 

1361 

1362 return typename 

1363 

1364 

1365def _array_repr_implementation( 

1366 arr, max_line_width=None, precision=None, suppress_small=None, 

1367 array2string=array2string): 

1368 """Internal version of array_repr() that allows overriding array2string.""" 

1369 if max_line_width is None: 

1370 max_line_width = _format_options['linewidth'] 

1371 

1372 if type(arr) is not ndarray: 

1373 class_name = type(arr).__name__ 

1374 else: 

1375 class_name = "array" 

1376 

1377 skipdtype = dtype_is_implied(arr.dtype) and arr.size > 0 

1378 

1379 prefix = class_name + "(" 

1380 suffix = ")" if skipdtype else "," 

1381 

1382 if (_format_options['legacy'] == '1.13' and 

1383 arr.shape == () and not arr.dtype.names): 

1384 lst = repr(arr.item()) 

1385 elif arr.size > 0 or arr.shape == (0,): 

1386 lst = array2string(arr, max_line_width, precision, suppress_small, 

1387 ', ', prefix, suffix=suffix) 

1388 else: # show zero-length shape unless it is (0,) 

1389 lst = "[], shape=%s" % (repr(arr.shape),) 

1390 

1391 arr_str = prefix + lst + suffix 

1392 

1393 if skipdtype: 

1394 return arr_str 

1395 

1396 dtype_str = "dtype={})".format(dtype_short_repr(arr.dtype)) 

1397 

1398 # compute whether we should put dtype on a new line: Do so if adding the 

1399 # dtype would extend the last line past max_line_width. 

1400 # Note: This line gives the correct result even when rfind returns -1. 

1401 last_line_len = len(arr_str) - (arr_str.rfind('\n') + 1) 

1402 spacer = " " 

1403 if _format_options['legacy'] == '1.13': 

1404 if issubclass(arr.dtype.type, flexible): 

1405 spacer = '\n' + ' '*len(class_name + "(") 

1406 elif last_line_len + len(dtype_str) + 1 > max_line_width: 

1407 spacer = '\n' + ' '*len(class_name + "(") 

1408 

1409 return arr_str + spacer + dtype_str 

1410 

1411 

1412def _array_repr_dispatcher( 

1413 arr, max_line_width=None, precision=None, suppress_small=None): 

1414 return (arr,) 

1415 

1416 

1417@array_function_dispatch(_array_repr_dispatcher, module='numpy') 

1418def array_repr(arr, max_line_width=None, precision=None, suppress_small=None): 

1419 """ 

1420 Return the string representation of an array. 

1421 

1422 Parameters 

1423 ---------- 

1424 arr : ndarray 

1425 Input array. 

1426 max_line_width : int, optional 

1427 Inserts newlines if text is longer than `max_line_width`. 

1428 Defaults to ``numpy.get_printoptions()['linewidth']``. 

1429 precision : int, optional 

1430 Floating point precision. 

1431 Defaults to ``numpy.get_printoptions()['precision']``. 

1432 suppress_small : bool, optional 

1433 Represent numbers "very close" to zero as zero; default is False. 

1434 Very close is defined by precision: if the precision is 8, e.g., 

1435 numbers smaller (in absolute value) than 5e-9 are represented as 

1436 zero. 

1437 Defaults to ``numpy.get_printoptions()['suppress']``. 

1438 

1439 Returns 

1440 ------- 

1441 string : str 

1442 The string representation of an array. 

1443 

1444 See Also 

1445 -------- 

1446 array_str, array2string, set_printoptions 

1447 

1448 Examples 

1449 -------- 

1450 >>> np.array_repr(np.array([1,2])) 

1451 'array([1, 2])' 

1452 >>> np.array_repr(np.ma.array([0.])) 

1453 'MaskedArray([0.])' 

1454 >>> np.array_repr(np.array([], np.int32)) 

1455 'array([], dtype=int32)' 

1456 

1457 >>> x = np.array([1e-6, 4e-7, 2, 3]) 

1458 >>> np.array_repr(x, precision=6, suppress_small=True) 

1459 'array([0.000001, 0. , 2. , 3. ])' 

1460 

1461 """ 

1462 return _array_repr_implementation( 

1463 arr, max_line_width, precision, suppress_small) 

1464 

1465 

1466@_recursive_guard() 

1467def _guarded_repr_or_str(v): 

1468 if isinstance(v, bytes): 

1469 return repr(v) 

1470 return str(v) 

1471 

1472 

1473def _array_str_implementation( 

1474 a, max_line_width=None, precision=None, suppress_small=None, 

1475 array2string=array2string): 

1476 """Internal version of array_str() that allows overriding array2string.""" 

1477 if (_format_options['legacy'] == '1.13' and 

1478 a.shape == () and not a.dtype.names): 

1479 return str(a.item()) 

1480 

1481 # the str of 0d arrays is a special case: It should appear like a scalar, 

1482 # so floats are not truncated by `precision`, and strings are not wrapped 

1483 # in quotes. So we return the str of the scalar value. 

1484 if a.shape == (): 

1485 # obtain a scalar and call str on it, avoiding problems for subclasses 

1486 # for which indexing with () returns a 0d instead of a scalar by using 

1487 # ndarray's getindex. Also guard against recursive 0d object arrays. 

1488 return _guarded_repr_or_str(np.ndarray.__getitem__(a, ())) 

1489 

1490 return array2string(a, max_line_width, precision, suppress_small, ' ', "") 

1491 

1492 

1493def _array_str_dispatcher( 

1494 a, max_line_width=None, precision=None, suppress_small=None): 

1495 return (a,) 

1496 

1497 

1498@array_function_dispatch(_array_str_dispatcher, module='numpy') 

1499def array_str(a, max_line_width=None, precision=None, suppress_small=None): 

1500 """ 

1501 Return a string representation of the data in an array. 

1502 

1503 The data in the array is returned as a single string. This function is 

1504 similar to `array_repr`, the difference being that `array_repr` also 

1505 returns information on the kind of array and its data type. 

1506 

1507 Parameters 

1508 ---------- 

1509 a : ndarray 

1510 Input array. 

1511 max_line_width : int, optional 

1512 Inserts newlines if text is longer than `max_line_width`. 

1513 Defaults to ``numpy.get_printoptions()['linewidth']``. 

1514 precision : int, optional 

1515 Floating point precision. 

1516 Defaults to ``numpy.get_printoptions()['precision']``. 

1517 suppress_small : bool, optional 

1518 Represent numbers "very close" to zero as zero; default is False. 

1519 Very close is defined by precision: if the precision is 8, e.g., 

1520 numbers smaller (in absolute value) than 5e-9 are represented as 

1521 zero. 

1522 Defaults to ``numpy.get_printoptions()['suppress']``. 

1523 

1524 See Also 

1525 -------- 

1526 array2string, array_repr, set_printoptions 

1527 

1528 Examples 

1529 -------- 

1530 >>> np.array_str(np.arange(3)) 

1531 '[0 1 2]' 

1532 

1533 """ 

1534 return _array_str_implementation( 

1535 a, max_line_width, precision, suppress_small) 

1536 

1537 

1538# needed if __array_function__ is disabled 

1539_array2string_impl = getattr(array2string, '__wrapped__', array2string) 

1540_default_array_str = functools.partial(_array_str_implementation, 

1541 array2string=_array2string_impl) 

1542_default_array_repr = functools.partial(_array_repr_implementation, 

1543 array2string=_array2string_impl) 

1544 

1545 

1546def set_string_function(f, repr=True): 

1547 """ 

1548 Set a Python function to be used when pretty printing arrays. 

1549 

1550 Parameters 

1551 ---------- 

1552 f : function or None 

1553 Function to be used to pretty print arrays. The function should expect 

1554 a single array argument and return a string of the representation of 

1555 the array. If None, the function is reset to the default NumPy function 

1556 to print arrays. 

1557 repr : bool, optional 

1558 If True (default), the function for pretty printing (``__repr__``) 

1559 is set, if False the function that returns the default string 

1560 representation (``__str__``) is set. 

1561 

1562 See Also 

1563 -------- 

1564 set_printoptions, get_printoptions 

1565 

1566 Examples 

1567 -------- 

1568 >>> def pprint(arr): 

1569 ... return 'HA! - What are you going to do now?' 

1570 ... 

1571 >>> np.set_string_function(pprint) 

1572 >>> a = np.arange(10) 

1573 >>> a 

1574 HA! - What are you going to do now? 

1575 >>> _ = a 

1576 >>> # [0 1 2 3 4 5 6 7 8 9] 

1577 

1578 We can reset the function to the default: 

1579 

1580 >>> np.set_string_function(None) 

1581 >>> a 

1582 array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]) 

1583 

1584 `repr` affects either pretty printing or normal string representation. 

1585 Note that ``__repr__`` is still affected by setting ``__str__`` 

1586 because the width of each array element in the returned string becomes 

1587 equal to the length of the result of ``__str__()``. 

1588 

1589 >>> x = np.arange(4) 

1590 >>> np.set_string_function(lambda x:'random', repr=False) 

1591 >>> x.__str__() 

1592 'random' 

1593 >>> x.__repr__() 

1594 'array([0, 1, 2, 3])' 

1595 

1596 """ 

1597 if f is None: 

1598 if repr: 

1599 return multiarray.set_string_function(_default_array_repr, 1) 

1600 else: 

1601 return multiarray.set_string_function(_default_array_str, 0) 

1602 else: 

1603 return multiarray.set_string_function(f, repr) 

1604 

1605set_string_function(_default_array_str, False) 

1606set_string_function(_default_array_repr, True)