diff --git a/pandas/core/arrays/base.py b/pandas/core/arrays/base.py index cf145064fd7b1..9f0551276fd02 100644 --- a/pandas/core/arrays/base.py +++ b/pandas/core/arrays/base.py @@ -53,6 +53,7 @@ class ExtensionArray(object): * __repr__ : A default repr for the ExtensionArray. * _formatter : Print scalars inside a Series or DataFrame. + * _repr_extra : Extra information to be included in the default repr. Some methods require casting the ExtensionArray to an ndarray of Python objects with ``self.astype(object)``, which may be expensive. When @@ -699,7 +700,7 @@ def __repr__(self): template = ( u'{class_name}' u'{data}\n' - u'Length: {length}, dtype: {dtype}' + u'Length: {length}, dtype: {dtype}{extra}' ) # the short repr has no trailing newline, while the truncated # repr does. So we include a newline in our template, and strip @@ -707,9 +708,13 @@ def __repr__(self): data = format_object_summary(self, self._formatter(), indent_for_name=False).rstrip(', \n') class_name = u'<{}>\n'.format(self.__class__.__name__) + extra = self._repr_extra() + if extra: + extra = ', {}'.format(extra) return template.format(class_name=class_name, data=data, length=len(self), - dtype=self.dtype) + dtype=self.dtype, + extra=extra) def _formatter(self, boxed=False): # type: (bool) -> Callable[[Any], Optional[str]] @@ -739,6 +744,20 @@ def _formatter(self, boxed=False): return str return repr + def _repr_extra(self): + """ + Additional text to be placed into the default repr. + + This text is placed after the ``dtype: ``, section + of the repr, and is separated by a comma and a space. + + Returns + ------- + str: + The additional text to be included in the repr. + """ + return '' + def _formatting_values(self): # type: () -> np.ndarray # At the moment, this has to be an array since we use result.dtype diff --git a/pandas/tests/extension/decimal/array.py b/pandas/tests/extension/decimal/array.py index 79e81f1034c6d..ddc3625f32a69 100644 --- a/pandas/tests/extension/decimal/array.py +++ b/pandas/tests/extension/decimal/array.py @@ -144,6 +144,9 @@ def _reduce(self, name, skipna=True, **kwargs): "the {} operation".format(name)) return op(axis=0) + def _repr_extra(self): + return 'prec: {}'.format(self.dtype.context.prec) + def to_decimal(values, context=None): return DecimalArray([decimal.Decimal(x) for x in values], context=context) diff --git a/pandas/tests/extension/decimal/test_decimal.py b/pandas/tests/extension/decimal/test_decimal.py index 6281c5360cd03..8e2c6ee68138f 100644 --- a/pandas/tests/extension/decimal/test_decimal.py +++ b/pandas/tests/extension/decimal/test_decimal.py @@ -399,3 +399,14 @@ def _formatting_values(self): with tm.assert_produces_warning(DeprecationWarning, check_stacklevel=check_stacklevel): repr(ser) + + +def test_repr(): + arr = to_decimal(([1, 2, 3])) + result = repr(arr) + expected = ( + "\n" + "[Decimal('1'), Decimal('2'), Decimal('3')]\n" + "Length: 3, dtype: decimal, prec: 28" + ) + assert result == expected