Skip to content

Commit 5719a5a

Browse files
author
y-p
committed
ENH: Migrate print_config usage to use core.config, register options on pkg load
1 parent 0167e24 commit 5719a5a

File tree

8 files changed

+82
-101
lines changed

8 files changed

+82
-101
lines changed

pandas/__init__.py

+3
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,9 @@
2222
from pandas.version import version as __version__
2323
from pandas.info import __doc__
2424

25+
# let init-time option registration happen
26+
import pandas.core.config_init
27+
2528
from pandas.core.api import *
2629
from pandas.sparse.api import *
2730
from pandas.stats.api import *

pandas/core/common.py

+9-6
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,8 @@
1919

2020
from pandas.util.py3compat import StringIO, BytesIO
2121

22+
from pandas.core.config import get_option
23+
2224
# XXX: HACK for NumPy 1.5.1 to suppress warnings
2325
try:
2426
np.seterr(all='ignore')
@@ -1113,7 +1115,7 @@ def in_interactive_session():
11131115
# 2) If you need to send something to the console, use console_encode().
11141116
#
11151117
# console_encode() should (hopefully) choose the right encoding for you
1116-
# based on the encoding set in fmt.print_config.encoding.
1118+
# based on the encoding set in option "print_config.encoding"
11171119
#
11181120
# 3) if you need to write something out to file, use
11191121
# pprint_thing_encoded(encoding).
@@ -1165,16 +1167,17 @@ def pprint_thing(thing, _nest_lvl=0):
11651167
result - unicode object on py2, str on py3. Always Unicode.
11661168
11671169
"""
1168-
from pandas.core.format import print_config
1170+
11691171
if thing is None:
11701172
result = ''
11711173
elif (py3compat.PY3 and hasattr(thing,'__next__')) or \
11721174
hasattr(thing,'next'):
11731175
return unicode(thing)
11741176
elif (isinstance(thing, dict) and
1175-
_nest_lvl < print_config.pprint_nest_depth):
1177+
_nest_lvl < get_option("print_config.pprint_nest_depth")):
11761178
result = _pprint_dict(thing, _nest_lvl)
1177-
elif _is_sequence(thing) and _nest_lvl < print_config.pprint_nest_depth:
1179+
elif _is_sequence(thing) and _nest_lvl < \
1180+
get_option("print_config.pprint_nest_depth"):
11781181
result = _pprint_seq(thing, _nest_lvl)
11791182
else:
11801183
# when used internally in the package, everything
@@ -1202,12 +1205,12 @@ def pprint_thing_encoded(object, encoding='utf-8', errors='replace'):
12021205

12031206

12041207
def console_encode(object):
1205-
from pandas.core.format import print_config
12061208
"""
12071209
this is the sanctioned way to prepare something for
12081210
sending *to the console*, it delegates to pprint_thing() to get
12091211
a unicode representation of the object relies on the global encoding
12101212
set in print_config.encoding. Use this everywhere
12111213
where you output to the console.
12121214
"""
1213-
return pprint_thing_encoded(object, print_config.encoding)
1215+
return pprint_thing_encoded(object,
1216+
get_option("print_config.encoding"))

pandas/core/format.py

+51-79
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,8 @@
1111
from pandas.core.common import adjoin, isnull, notnull
1212
from pandas.core.index import MultiIndex, _ensure_index
1313
from pandas.util import py3compat
14-
14+
from pandas.core.config import get_option, set_option, \
15+
reset_options
1516
import pandas.core.common as com
1617
import pandas.lib as lib
1718

@@ -69,7 +70,7 @@ def __init__(self, series, buf=None, header=True, length=True,
6970
self.header = header
7071

7172
if float_format is None:
72-
float_format = print_config.float_format
73+
float_format = get_option("print_config.float_format")
7374
self.float_format = float_format
7475

7576
def _get_footer(self):
@@ -145,11 +146,11 @@ def to_string(self):
145146
_strlen = len
146147
else:
147148
def _encode_diff(x):
148-
return len(x) - len(x.decode(print_config.encoding))
149+
return len(x) - len(x.decode(get_option("print_config.encoding")))
149150

150151
def _strlen(x):
151152
try:
152-
return len(x.decode(print_config.encoding))
153+
return len(x.decode(get_option("print_config.encoding")))
153154
except UnicodeError:
154155
return len(x)
155156

@@ -176,7 +177,7 @@ def __init__(self, frame, buf=None, columns=None, col_space=None,
176177
self.show_index_names = index_names
177178

178179
if sparsify is None:
179-
sparsify = print_config.multi_sparse
180+
sparsify = get_option("print_config.multi_sparse")
180181

181182
self.sparsify = sparsify
182183

@@ -188,7 +189,7 @@ def __init__(self, frame, buf=None, columns=None, col_space=None,
188189
self.index = index
189190

190191
if justify is None:
191-
self.justify = print_config.colheader_justify
192+
self.justify = get_option("print_config.colheader_justify")
192193
else:
193194
self.justify = justify
194195

@@ -697,13 +698,13 @@ def format_array(values, formatter, float_format=None, na_rep='NaN',
697698
fmt_klass = GenericArrayFormatter
698699

699700
if space is None:
700-
space = print_config.column_space
701+
space = get_option("print_config.column_space")
701702

702703
if float_format is None:
703-
float_format = print_config.float_format
704+
float_format = get_option("print_config.float_format")
704705

705706
if digits is None:
706-
digits = print_config.precision
707+
digits = get_option("print_config.precision")
707708

708709
fmt_obj = fmt_klass(values, digits, na_rep=na_rep,
709710
float_format=float_format,
@@ -739,9 +740,9 @@ def _have_unicode(self):
739740

740741
def _format_strings(self, use_unicode=False):
741742
if self.float_format is None:
742-
float_format = print_config.float_format
743+
float_format = get_option("print_config.float_format")
743744
if float_format is None:
744-
fmt_str = '%% .%dg' % print_config.precision
745+
fmt_str = '%% .%dg' % get_option("print_config.precision")
745746
float_format = lambda x: fmt_str % x
746747
else:
747748
float_format = self.float_format
@@ -863,7 +864,7 @@ def _make_fixed_width(strings, justify='right', minimum=None):
863864
if minimum is not None:
864865
max_len = max(minimum, max_len)
865866

866-
conf_max = print_config.max_colwidth
867+
conf_max = get_option("print_config.max_colwidth")
867868
if conf_max is not None and max_len > conf_max:
868869
max_len = conf_max
869870

@@ -974,34 +975,56 @@ def set_printoptions(precision=None, column_space=None, max_rows=None,
974975
elements in outer levels within groups)
975976
"""
976977
if precision is not None:
977-
print_config.precision = precision
978+
set_option("print_config.precision", precision)
978979
if column_space is not None:
979-
print_config.column_space = column_space
980+
set_option("print_config.column_space", column_space)
980981
if max_rows is not None:
981-
print_config.max_rows = max_rows
982+
set_option("print_config.max_rows", max_rows)
982983
if max_colwidth is not None:
983-
print_config.max_colwidth = max_colwidth
984+
set_option("print_config.max_colwidth", max_colwidth)
984985
if max_columns is not None:
985-
print_config.max_columns = max_columns
986+
set_option("print_config.max_columns", max_columns)
986987
if colheader_justify is not None:
987-
print_config.colheader_justify = colheader_justify
988+
set_option("print_config.colheader_justify", colheader_justify)
988989
if notebook_repr_html is not None:
989-
print_config.notebook_repr_html = notebook_repr_html
990+
set_option("print_config.notebook_repr_html", notebook_repr_html)
990991
if date_dayfirst is not None:
991-
print_config.date_dayfirst = date_dayfirst
992+
set_option("print_config.date_dayfirst", date_dayfirst)
992993
if date_yearfirst is not None:
993-
print_config.date_yearfirst = date_yearfirst
994+
set_option("print_config.date_yearfirst", date_yearfirst)
994995
if pprint_nest_depth is not None:
995-
print_config.pprint_nest_depth = pprint_nest_depth
996+
set_option("print_config.pprint_nest_depth", pprint_nest_depth)
996997
if multi_sparse is not None:
997-
print_config.multi_sparse = multi_sparse
998+
set_option("print_config.multi_sparse", multi_sparse)
998999
if encoding is not None:
999-
print_config.encoding = encoding
1000-
1000+
set_option("print_config.encoding", encoding)
10011001

10021002
def reset_printoptions():
1003-
print_config.reset()
1003+
reset_options("print_config.")
1004+
1005+
def detect_console_encoding():
1006+
"""
1007+
Try to find the most capable encoding supported by the console.
1008+
slighly modified from the way IPython handles the same issue.
1009+
"""
1010+
import locale
1011+
1012+
encoding = None
1013+
try:
1014+
encoding=sys.stdin.encoding
1015+
except AttributeError:
1016+
pass
10041017

1018+
if not encoding or encoding =='ascii': # try again for something better
1019+
try:
1020+
encoding = locale.getpreferredencoding()
1021+
except Exception:
1022+
pass
1023+
1024+
if not encoding: # when all else fails. this will usually be "ascii"
1025+
encoding = sys.getdefaultencoding()
1026+
1027+
return encoding
10051028

10061029
class EngFormatter(object):
10071030
"""
@@ -1109,59 +1132,8 @@ def set_eng_float_format(precision=None, accuracy=3, use_eng_prefix=False):
11091132
"being renamed to 'accuracy'", FutureWarning)
11101133
accuracy = precision
11111134

1112-
print_config.float_format = EngFormatter(accuracy, use_eng_prefix)
1113-
print_config.column_space = max(12, accuracy + 9)
1114-
1115-
1116-
class _GlobalPrintConfig(object):
1117-
"""
1118-
Holds the console formatting settings for DataFrame and friends
1119-
"""
1120-
1121-
def __init__(self):
1122-
self.precision = self.digits = 7
1123-
self.float_format = None
1124-
self.column_space = 12
1125-
self.max_rows = 200
1126-
self.max_colwidth = 50
1127-
self.max_columns = 0
1128-
self.colheader_justify = 'right'
1129-
self.notebook_repr_html = True
1130-
self.date_dayfirst = False
1131-
self.date_yearfirst = False
1132-
self.pprint_nest_depth = 3
1133-
self.multi_sparse = True
1134-
self.encoding = self.detect_encoding()
1135-
1136-
def detect_encoding(self):
1137-
"""
1138-
Try to find the most capable encoding supported by the console.
1139-
slighly modified from the way IPython handles the same issue.
1140-
"""
1141-
import locale
1142-
1143-
encoding = None
1144-
try:
1145-
encoding = sys.stdin.encoding
1146-
except AttributeError:
1147-
pass
1148-
1149-
if not encoding or encoding == 'ascii': # try again for better
1150-
try:
1151-
encoding = locale.getpreferredencoding()
1152-
except Exception:
1153-
pass
1154-
1155-
if not encoding: # when all else fails. this will usually be "ascii"
1156-
encoding = sys.getdefaultencoding()
1157-
1158-
return encoding
1159-
1160-
def reset(self):
1161-
self.__init__()
1162-
1163-
print_config = _GlobalPrintConfig()
1164-
1135+
set_option("print_config.float_format", EngFormatter(accuracy, use_eng_prefix))
1136+
set_option("print_config.column_space", max(12, accuracy + 9))
11651137

11661138
def _put_lines(buf, lines):
11671139
if any(isinstance(x, unicode) for x in lines):

pandas/core/frame.py

+6-5
Original file line numberDiff line numberDiff line change
@@ -44,6 +44,8 @@
4444
import pandas.core.nanops as nanops
4545
import pandas.lib as lib
4646

47+
from pandas.core.config import get_option
48+
4749
#----------------------------------------------------------------------
4850
# Docstring templates
4951

@@ -579,12 +581,11 @@ def _need_info_repr_(self):
579581
Check if it is needed to use info/summary view to represent a
580582
particular DataFrame.
581583
"""
582-
config = fmt.print_config
583584

584585
terminal_width, terminal_height = get_terminal_size()
585-
max_rows = (terminal_height if config.max_rows == 0
586-
else config.max_rows)
587-
max_columns = config.max_columns
586+
max_rows = (terminal_height if get_option("print_config.max_rows") == 0
587+
else get_option("print_config.max_rows"))
588+
max_columns = get_option("print_config.max_columns")
588589

589590
if max_columns > 0:
590591
if len(self.index) <= max_rows and \
@@ -628,7 +629,7 @@ def _repr_html_(self):
628629
Return a html representation for a particular DataFrame.
629630
Mainly for IPython notebook.
630631
"""
631-
if fmt.print_config.notebook_repr_html:
632+
if get_option("print_config.notebook_repr_html"):
632633
if self._need_info_repr_():
633634
return None
634635
else:

pandas/core/index.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@
1313
import pandas._algos as _algos
1414
from pandas.lib import Timestamp
1515
from pandas.util import py3compat
16+
from pandas.core.config import get_option
1617

1718
__all__ = ['Index']
1819

@@ -1514,8 +1515,7 @@ def format(self, space=2, sparsify=None, adjoin=True, names=False,
15141515
result_levels.append(level)
15151516

15161517
if sparsify is None:
1517-
import pandas.core.format as fmt
1518-
sparsify = fmt.print_config.multi_sparse
1518+
sparsify = get_option("print_config.multi_sparse")
15191519

15201520
if sparsify:
15211521
# little bit of a kludge job for #1217

pandas/core/series.py

+3-2
Original file line numberDiff line numberDiff line change
@@ -33,6 +33,7 @@
3333
from pandas.util.decorators import Appender, Substitution, cache_readonly
3434

3535
from pandas.compat.scipy import scoreatpercentile as _quantile
36+
from pandas.core.config import get_option
3637

3738
__all__ = ['Series', 'TimeSeries']
3839

@@ -914,8 +915,8 @@ def reset_index(self, level=None, drop=False, name=None, inplace=False):
914915
def __repr__(self):
915916
"""Clean string representation of a Series"""
916917
width, height = get_terminal_size()
917-
max_rows = (height if fmt.print_config.max_rows == 0
918-
else fmt.print_config.max_rows)
918+
max_rows = (height if get_option("print_config.max_rows") == 0
919+
else get_option("print_config.max_rows"))
919920
if len(self.index) > (max_rows or 1000):
920921
result = self._tidy_repr(min(30, max_rows - 4))
921922
elif len(self.index) > 0:

pandas/tests/test_format.py

+5-4
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,7 @@
1919
import pandas.util.testing as tm
2020
import pandas
2121
import pandas as pd
22+
from pandas.core.config import set_option,get_option
2223

2324
_frame = DataFrame(tm.getSeriesData())
2425

@@ -64,7 +65,7 @@ def test_repr_tuples(self):
6465

6566
def test_repr_truncation(self):
6667
max_len = 20
67-
fmt.print_config.max_colwidth = max_len
68+
set_option("print_config.max_colwidth", max_len)
6869
df = DataFrame({'A': np.random.randn(10),
6970
'B': [tm.rands(np.random.randint(max_len - 1,
7071
max_len + 1)) for i in range(10)]})
@@ -76,10 +77,10 @@ def test_repr_truncation(self):
7677
else:
7778
self.assert_('...' not in line)
7879

79-
fmt.print_config.max_colwidth = None
80+
set_option("print_config.max_colwidth", 999999)
8081
self.assert_('...' not in repr(df))
8182

82-
fmt.print_config.max_colwidth = max_len + 2
83+
set_option("print_config.max_colwidth", max_len + 2)
8384
self.assert_('...' not in repr(df))
8485

8586
def test_repr_should_return_str (self):
@@ -425,7 +426,7 @@ def test_to_string_float_formatting(self):
425426
assert(df_s == expected)
426427

427428
fmt.reset_printoptions()
428-
self.assertEqual(fmt.print_config.precision, 7)
429+
self.assertEqual(get_option("print_config.precision"), 7)
429430

430431
df = DataFrame({'x': [1e9, 0.2512]})
431432
df_s = df.to_string()

0 commit comments

Comments
 (0)