Skip to content

Commit 5a79e96

Browse files
committed
move tests to generically tests for index
generify __unicode__ for Index
1 parent bd9b2af commit 5a79e96

File tree

7 files changed

+91
-33
lines changed

7 files changed

+91
-33
lines changed

pandas/core/index.py

+27-7
Original file line numberDiff line numberDiff line change
@@ -410,15 +410,35 @@ def __unicode__(self):
410410
Invoked by unicode(df) in py2 only. Yields a Unicode String in both
411411
py2/py3.
412412
"""
413-
prepr = com.pprint_thing(self, escape_chars=('\t', '\r', '\n'),
414-
quote_strings=True)
413+
klass = self.__class__.__name__
414+
space = ' ' * (len(klass) + 1)
415+
data = self._format_data()
416+
attrs = self._format_attrs()
417+
prepr = (u(",\n%s") % space).join([u("%s=%s") % (k, v)
418+
for k, v in attrs])
419+
res = u("%s(%s,\n%s%s)") % (klass,
420+
data,
421+
space,
422+
prepr)
423+
424+
return res
415425

416-
name_attr=''
417-
if self.name:
418-
name_attr = u(" %s=%s,") % ('name', self.name)
426+
def _format_data(self):
427+
"""
428+
Return the formatted data as a unicode string
429+
"""
430+
return com.pprint_thing(self, escape_chars=('\t', '\r', '\n'),
431+
quote_strings=True)
419432

420-
return "%s(%s,%s dtype='%s')" % (type(self).__name__,
421-
prepr, name_attr, self.dtype)
433+
def _format_attrs(self):
434+
"""
435+
Return a list of tuples of the (attr,formatted_value)
436+
"""
437+
attrs = []
438+
if self.name is not None:
439+
attrs.append(('name',default_pprint(self.name)))
440+
attrs.append(('dtype',"'%s'" % self.dtype))
441+
return attrs
422442

423443
def to_series(self, **kwargs):
424444
"""

pandas/tests/test_index.py

+35-2
Original file line numberDiff line numberDiff line change
@@ -118,6 +118,18 @@ def test_ndarray_compat_properties(self):
118118
idx.nbytes
119119
idx.values.nbytes
120120

121+
def test_repr_roundtrip(self):
122+
123+
idx = self.create_index()
124+
tm.assert_index_equal(eval(repr(idx)),idx)
125+
126+
def test_str(self):
127+
128+
# test the string repr
129+
idx = self.create_index()
130+
idx.name = 'foo'
131+
self.assertTrue("name=u'foo'" in str(idx))
132+
self.assertTrue(idx.__class__.__name__ in str(idx))
121133

122134
class TestIndex(Base, tm.TestCase):
123135
_holder = Index
@@ -2052,6 +2064,26 @@ def test_slice_keep_name(self):
20522064

20532065
class DatetimeLike(Base):
20542066

2067+
def test_repr_roundtrip(self):
2068+
raise nose.SkipTest("Short reprs are not supported repr for Datetimelike indexes")
2069+
2070+
def test_str(self):
2071+
2072+
# test the string repr
2073+
idx = self.create_index()
2074+
idx.name = 'foo'
2075+
self.assertTrue("length=%s" % len(idx) in str(idx))
2076+
self.assertTrue("name=u'foo'" in str(idx))
2077+
self.assertTrue(idx.__class__.__name__ in str(idx))
2078+
2079+
if hasattr(idx,'tz'):
2080+
if idx.tz is not None:
2081+
self.assertTrue("tz='%s'" % idx.tz in str(idx))
2082+
else:
2083+
self.assertTrue("tz=None" in str(idx))
2084+
if hasattr(idx,'freq'):
2085+
self.assertTrue("freq='%s'" % idx.freqstr in str(idx))
2086+
20552087
def test_view(self):
20562088

20572089
i = self.create_index()
@@ -3951,8 +3983,9 @@ def test_repr_with_unicode_data(self):
39513983
index = pd.DataFrame(d).set_index(["a", "b"]).index
39523984
self.assertFalse("\\u" in repr(index)) # we don't want unicode-escaped
39533985

3954-
def test_repr_roundtrip(self):
3955-
tm.assert_index_equal(eval(repr(self.index)), self.index)
3986+
def test_str(self):
3987+
# tested elsewhere
3988+
pass
39563989

39573990
def test_unicode_string_with_unicode(self):
39583991
d = {"a": [u("\u05d0"), 2, 3], "b": [4, 5, 6], "c": [7, 8, 9]}

pandas/tseries/base.py

+27-10
Original file line numberDiff line numberDiff line change
@@ -260,31 +260,48 @@ def _formatter_func(self):
260260
"""
261261
return str
262262

263-
def _format_footer(self):
264-
raise AbstractMethodError(self)
263+
def _format_data(self):
264+
"""
265+
Return the formatted data as a unicode string
266+
"""
265267

266-
def __unicode__(self):
267268
formatter = self._formatter_func
268-
summary = str(self.__class__) + '\n'
269-
270269
n = len(self)
271270
if n == 0:
272-
pass
271+
summary = ''
273272
elif n == 1:
274273
first = formatter(self[0])
275-
summary += '[%s]\n' % first
274+
summary = '[%s]' % first
276275
elif n == 2:
277276
first = formatter(self[0])
278277
last = formatter(self[-1])
279-
summary += '[%s, %s]\n' % (first, last)
278+
summary = '[%s, %s]' % (first, last)
280279
else:
281280
first = formatter(self[0])
282281
last = formatter(self[-1])
283-
summary += '[%s, ..., %s]\n' % (first, last)
282+
summary = '[%s, ..., %s]' % (first, last)
284283

285-
summary += self._format_footer()
286284
return summary
287285

286+
def _format_attrs(self):
287+
"""
288+
Return a list of tuples of the (attr,formatted_value)
289+
"""
290+
attrs = super(DatetimeIndexOpsMixin, self)._format_attrs()
291+
attrs.append(('length',len(self)))
292+
for attrib in self._attributes:
293+
if attrib == 'freq':
294+
freq = self.freqstr
295+
if freq is not None:
296+
freq = "'%s'" % freq
297+
attrs.append(('freq',freq))
298+
elif attrib == 'tz':
299+
tz = self.tz
300+
if tz is not None:
301+
tz = "'%s'" % tz
302+
attrs.append(('tz',tz))
303+
return attrs
304+
288305
@cache_readonly
289306
def _resolution(self):
290307
from pandas.tseries.frequencies import Resolution

pandas/tseries/index.py

-4
Original file line numberDiff line numberDiff line change
@@ -683,10 +683,6 @@ def _format_native_types(self, na_rep=u('NaT'),
683683
def to_datetime(self, dayfirst=False):
684684
return self.copy()
685685

686-
def _format_footer(self):
687-
tagline = 'Length: %d, Freq: %s, Timezone: %s'
688-
return tagline % (len(self), self.freqstr, self.tz)
689-
690686
def astype(self, dtype):
691687
dtype = np.dtype(dtype)
692688

pandas/tseries/period.py

+1-5
Original file line numberDiff line numberDiff line change
@@ -387,7 +387,7 @@ def to_datetime(self, dayfirst=False):
387387
qyear = _field_accessor('qyear', 1)
388388
days_in_month = _field_accessor('days_in_month', 11, "The number of days in the month")
389389
daysinmonth = days_in_month
390-
390+
391391
def _get_object_array(self):
392392
freq = self.freq
393393
return np.array([ Period._from_ordinal(ordinal=x, freq=freq) for x in self.values], copy=False)
@@ -697,10 +697,6 @@ def __array_finalize__(self, obj):
697697
self.name = getattr(obj, 'name', None)
698698
self._reset_identity()
699699

700-
def _format_footer(self):
701-
tagline = 'Length: %d, Freq: %s'
702-
return tagline % (len(self), self.freqstr)
703-
704700
def take(self, indices, axis=None):
705701
"""
706702
Analogous to ndarray.take

pandas/tseries/tdi.py

-4
Original file line numberDiff line numberDiff line change
@@ -274,10 +274,6 @@ def _formatter_func(self):
274274
from pandas.core.format import _get_format_timedelta64
275275
return _get_format_timedelta64(self, box=True)
276276

277-
def _format_footer(self):
278-
tagline = 'Length: %d, Freq: %s'
279-
return tagline % (len(self), self.freqstr)
280-
281277
def __setstate__(self, state):
282278
"""Necessary for making this object picklable"""
283279
if isinstance(state, dict):

pandas/util/testing.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -1633,7 +1633,7 @@ class _AssertRaisesContextmanager(object):
16331633
def __init__(self, exception, regexp=None, *args, **kwargs):
16341634
self.exception = exception
16351635
if regexp is not None and not hasattr(regexp, "search"):
1636-
regexp = re.compile(regexp)
1636+
regexp = re.compile(regexp, re.DOTALL)
16371637
self.regexp = regexp
16381638

16391639
def __enter__(self):

0 commit comments

Comments
 (0)