35
35
from .umath import absolute , isinf , isfinite , isnat
36
36
from . import multiarray
37
37
from .multiarray import (array , dragon4_positional , dragon4_scientific ,
38
- datetime_as_string , datetime_data , ndarray ,
39
- set_legacy_print_mode )
38
+ datetime_as_string , datetime_data , ndarray )
40
39
from .fromnumeric import any
41
40
from .numeric import concatenate , asarray , errstate
42
41
from .numerictypes import (longlong , intc , int_ , float64 , complex128 ,
43
42
flexible )
44
43
from .overrides import array_function_dispatch , set_module
44
+ from .printoptions import format_options
45
45
import operator
46
46
import warnings
47
47
import contextlib
48
48
49
- _format_options = {
50
- 'edgeitems' : 3 , # repr N leading and trailing items of each dimension
51
- 'threshold' : 1000 , # total items > triggers array summarization
52
- 'floatmode' : 'maxprec' ,
53
- 'precision' : 8 , # precision of floating point representations
54
- 'suppress' : False , # suppress printing small floating values in exp format
55
- 'linewidth' : 75 ,
56
- 'nanstr' : 'nan' ,
57
- 'infstr' : 'inf' ,
58
- 'sign' : '-' ,
59
- 'formatter' : None ,
60
- # Internally stored as an int to simplify comparisons; converted from/to
61
- # str/False on the way in/out.
62
- 'legacy' : sys .maxsize ,
63
- 'override_repr' : None ,
64
- }
65
49
66
50
def _make_options_dict (precision = None , threshold = None , edgeitems = None ,
67
51
linewidth = None , suppress = None , nanstr = None , infstr = None ,
@@ -295,25 +279,21 @@ def set_printoptions(precision=None, threshold=None, edgeitems=None,
295
279
array([ 0. , 1.11, 2.22, ..., 7.78, 8.89, 10. ])
296
280
297
281
"""
298
- opt = _make_options_dict (precision , threshold , edgeitems , linewidth ,
299
- suppress , nanstr , infstr , sign , formatter ,
300
- floatmode , legacy , override_repr )
282
+ new_opt = _make_options_dict (precision , threshold , edgeitems , linewidth ,
283
+ suppress , nanstr , infstr , sign , formatter ,
284
+ floatmode , legacy )
301
285
# formatter and override_repr are always reset
302
- opt ['formatter' ] = formatter
303
- opt ['override_repr' ] = override_repr
304
- _format_options .update (opt )
305<
F438
/code>
-
306
- # set the C variable for legacy mode
307
- if _format_options ['legacy' ] == 113 :
308
- set_legacy_print_mode (113 )
309
- # reset the sign option in legacy mode to avoid confusion
310
- _format_options ['sign' ] = '-'
311
- elif _format_options ['legacy' ] == 121 :
312
- set_legacy_print_mode (121 )
313
- elif _format_options ['legacy' ] == 125 :
314
- set_legacy_print_mode (125 )
315
- elif _format_options ['legacy' ] == sys .maxsize :
316
- set_legacy_print_mode (0 )
286
+ new_opt ['formatter' ] = formatter
287
+ new_opt ['override_repr' ] = override_repr
288
+
289
+ updated_opt = format_options .get () | new_opt
290
+ updated_opt .update (new_opt )
291
+
292
+ if updated_opt ['legacy' ] == 113 :
293
+ updated_opt ['sign' ] = '-'
294
+
295
+ token = format_options .set (updated_opt )
296
+ return token
317
297
318
298
319
299
@set_module ('numpy' )
@@ -355,7 +335,7 @@ def get_printoptions():
355
335
100
356
336
357
337
"""
358
- opts = _format_options .copy ()
338
+ opts = format_options . get () .copy ()
359
339
opts ['legacy' ] = {
360
340
113 : '1.13' , 121 : '1.21' , 125 : '1.25' , sys .maxsize : False ,
361
341
}[opts ['legacy' ]]
@@ -364,7 +344,7 @@ def get_printoptions():
364
344
365
345
def _get_legacy_print_mode ():
366
346
"""Return the legacy print mode as an int."""
367
- return _format_options ['legacy' ]
347
+ return format_options . get () ['legacy' ]
368
348
369
349
370
350
@set_module ('numpy' )
@@ -393,13 +373,12 @@ def printoptions(*args, **kwargs):
393
373
--------
394
374
set_printoptions, get_printoptions
395
375
396
- """
397
- opts = np . get_printoptions ( )
376
+ """
377
+ token = set_printoptions ( * args , ** kwargs )
398
378
try :
399
- np .set_printoptions (* args , ** kwargs )
400
- yield np .get_printoptions ()
379
+ yield get_printoptions ()
401
380
finally :
402
- np . set_printoptions ( ** opts )
381
+ format_options . reset ( token )
403
382
404
383
405
384
def _leading_trailing (a , edgeitems , index = ()):
@@ -757,7 +736,7 @@ def array2string(a, max_line_width=None, precision=None,
757
736
overrides = _make_options_dict (precision , threshold , edgeitems ,
758
737
max_line_width , suppress_small , None , None ,
759
738
sign , formatter , floatmode , legacy )
760
- options = _format_options .copy ()
739
+ options = format_options . get () .copy ()
761
740
options .update (overrides )
762
741
763
742
if options ['legacy' ] <= 113 :
@@ -980,7 +959,6 @@ def __init__(self, data, precision, floatmode, suppress_small, sign=False,
980
959
self .sign = sign
981
960
self .exp_format = False
982
961
self .large_exponent = False
983
-
984
962
self .fillFormat (data )
985
963
986
964
def fillFormat (self , data ):
@@ -1062,22 +1040,23 @@ def fillFormat(self, data):
1062
1040
# if there are non-finite values, may need to increase pad_left
1063
1041
if data .size != finite_vals .size :
1064
1042
neginf = self .sign != '-' or any (data [isinf (data )] < 0 )
1065
- nanlen = len (_format_options ['nanstr' ])
1066
- inflen = len (_format_options ['infstr' ]) + neginf
1067
1043
offset = self .pad_right + 1 # +1 for decimal pt
1044
+ current_options = format_options .get ()
1068
1045
self .pad_left = max (
1069
- self .pad_left , nanlen - offset , inflen - offset
1046
+ self .pad_left , len (current_options ['nanstr' ]) - offset ,
1047
+ len (current_options ['infstr' ]) + neginf - offset
1070
1048
)
1071
1049
1072
1050
def __call__ (self , x ):
1073
1051
if not np .isfinite (x ):
1074
1052
with errstate (invalid = 'ignore' ):
1053
+ current_options = format_options .get ()
1075
1054
if np .isnan (x ):
1076
1055
sign = '+' if self .sign == '+' else ''
1077
- ret = sign + _format_options ['nanstr' ]
1056
+ ret = sign + current_options ['nanstr' ]
1078
1057
else : # isinf
1079
1058
sign = '-' if x < 0 else '+' if self .sign == '+' else ''
1080
- ret = sign + _format_options ['infstr' ]
1059
+ ret = sign + current_options ['infstr' ]
1081
1060
return ' ' * (
1082
1061
self .pad_left + self .pad_right + 1 - len (ret )
1083
1062
) + ret
@@ -1468,10 +1447,10 @@ def _void_scalar_to_string(x, is_repr=True):
1468
1447
scalartypes.c.src code, and is placed here because it uses the elementwise
1469
1448
formatters defined above.
1470
1449
"""
1471
- options = _format_options .copy ()
1450
+ options = format_options . get () .copy ()
1472
1451
1473
1452
if options ["legacy" ] <= 125 :
1474
- return StructuredVoidFormat .from_data (array (x ), ** _format_options )(x )
1453
+ return StructuredVoidFormat .from_data (array (x ), ** options )(x )
1475
1454
1476
1455
if options .get ('formatter' ) is None :
1477
1456
options ['formatter' ] = {}
@@ -1515,7 +1494,7 @@ def dtype_is_implied(dtype):
1515
1494
array([1, 2, 3], dtype=int8)
1516
1495
"""
1517
1496
dtype = np .dtype (dtype )
1518
- if _format_options ['legacy' ] <= 113 and dtype .type == np .bool :
1497
+ if format_options . get () ['legacy' ] <= 113 and dtype .type == np .bool :
1519
1498
return False
1520
1499
1521
1500
# not just void types
F438
can be structured, and names are not part of the repr
@@ -1565,12 +1544,13 @@ def _array_repr_implementation(
1565
1544
arr , max_line_width = None , precision = None , suppress_small = None ,
1566
1545
array2string = array2string ):
1567
1546
"""Internal version of array_repr() that allows overriding array2string."""
1568
- override_repr = _format_options ["override_repr" ]
1547
+ current_options = format_options .get ()
1548
+ override_repr = current_options ["override_repr" ]
1569
1549
if override_repr is not None :
1570
1550
return override_repr (arr )
1571
1551
1572
1552
if max_line_width is None :
1573
- max_line_width = _format_options ['linewidth' ]
1553
+ max_line_width = current_options ['linewidth' ]
1574
1554
1575
1555
if type (arr ) is not ndarray :
1576
1556
class_name = type (arr ).__name__
@@ -1582,7 +1562,7 @@ def _array_repr_implementation(
1582
1562
prefix = class_name + "("
1583
1563
suffix = ")" if skipdtype else ","
1584
1564
1585
- if (_format_options ['legacy' ] <= 113 and
1565
+ if (current_options ['legacy' ] <= 113 and
1586
1566
arr .shape == () and not arr .dtype .names ):
1587
1567
lst = repr (arr .item ())
1588
1568
elif arr .size > 0 or arr .shape == (0 ,):
@@ -1603,7 +1583,7 @@ def _array_repr_implementation(
1603
1583
# Note: This line gives the correct result even when rfind returns -1.
1604
1584
last_line_len = len (arr_str ) - (arr_str .rfind ('\n ' ) + 1 )
1605
1585
spacer = " "
1606
- if _format_options ['legacy' ] <= 113 :
1586
+ if current_options ['legacy' ] <= 113 :
1607
1587
if issubclass (arr .dtype .type , flexible ):
1608
1588
spacer = '\n ' + ' ' * len (class_name + "(" )
1609
1589
elif last_line_len + len (dtype_str ) + 1 > max_line_width :
@@ -1677,7 +1657,7 @@ def _array_str_implementation(
1677
1657
a , max_line_width = None , precision = None , suppress_small = None ,
1678
1658
array2string = array2string ):
1679
1659
"""Internal version of array_str() that allows overriding array2string."""
1680
- if (_format_options ['legacy' ] <= 113 and
1660
+ if (format_options . get () ['legacy' ] <= 113 and
1681
1661
a .shape == () and not a .dtype .names ):
1682
1662
return str (a .item ())
1683
1663
0 commit comments