Skip to content

REF: de-duplicate _format_attrs #41655

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 3 commits into from
May 25, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 14 additions & 3 deletions pandas/core/indexes/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -1158,14 +1158,18 @@ def _format_data(self, name=None) -> str_t:
is_justify = False

return format_object_summary(
self, self._formatter_func, is_justify=is_justify, name=name
self,
self._formatter_func,
is_justify=is_justify,
name=name,
line_break_each_value=self._is_multi,
)

def _format_attrs(self):
def _format_attrs(self) -> list[tuple[str_t, str_t | int]]:
"""
Return a list of tuples of the (attr,formatted_value).
"""
return format_object_attrs(self)
return format_object_attrs(self, include_dtype=not self._is_multi)

def _mpl_repr(self):
# how to represent ourselves to matplotlib
Expand Down Expand Up @@ -2407,6 +2411,13 @@ def is_all_dates(self) -> bool:
)
return self._is_all_dates

@cache_readonly
def _is_multi(self) -> bool:
"""
Cached check equivalent to isinstance(self, MultiIndex)
"""
return isinstance(self, ABCMultiIndex)

# --------------------------------------------------------------------
# Pickle Methods

Expand Down
9 changes: 2 additions & 7 deletions pandas/core/indexes/category.py
Original file line number Diff line number Diff line change
Expand Up @@ -324,13 +324,8 @@ def _format_attrs(self):
# error: "CategoricalIndex" has no attribute "ordered"
("ordered", self.ordered), # type: ignore[attr-defined]
]
if self.name is not None:
attrs.append(("name", ibase.default_pprint(self.name)))
attrs.append(("dtype", f"'{self.dtype.name}'"))
max_seq_items = get_option("display.max_seq_items") or len(self)
if len(self) > max_seq_items:
attrs.append(("length", len(self)))
return attrs
extra = super()._format_attrs()
return attrs + extra

def _format_with_header(self, header: list[str], na_rep: str = "NaN") -> list[str]:
from pandas.io.formats.printing import pprint_thing
Expand Down
4 changes: 3 additions & 1 deletion pandas/core/indexes/datetimelike.py
Original file line number Diff line number Diff line change
Expand Up @@ -361,7 +361,9 @@ def _format_attrs(self):
freq = self.freqstr
if freq is not None:
freq = repr(freq)
attrs.append(("freq", freq))
# Argument 1 to "append" of "list" has incompatible type
# "Tuple[str, Optional[str]]"; expected "Tuple[str, Union[str, int]]"
attrs.append(("freq", freq)) # type: ignore[arg-type]
return attrs

def _summary(self, name=None) -> str:
Expand Down
45 changes: 1 addition & 44 deletions pandas/core/indexes/interval.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,8 +16,6 @@

import numpy as np

from pandas._config import get_option

from pandas._libs import lib
from pandas._libs.interval import (
Interval,
Expand Down Expand Up @@ -80,7 +78,6 @@
from pandas.core.indexes.base import (
Index,
_index_shared_docs,
default_pprint,
ensure_index,
maybe_extract_name,
)
Expand Down Expand Up @@ -919,49 +916,9 @@ def _format_native_types(self, na_rep="NaN", quoting=None, **kwargs):
return super()._format_native_types(na_rep=na_rep, quoting=quoting, **kwargs)

def _format_data(self, name=None) -> str:

# TODO: integrate with categorical and make generic
# name argument is unused here; just for compat with base / categorical
n = len(self)
max_seq_items = min((get_option("display.max_seq_items") or n) // 10, 10)

formatter = str

if n == 0:
summary = "[]"
elif n == 1:
first = formatter(self[0])
summary = f"[{first}]"
elif n == 2:
first = formatter(self[0])
last = formatter(self[-1])
summary = f"[{first}, {last}]"
else:

if n > max_seq_items:
n = min(max_seq_items // 2, 10)
head = [formatter(x) for x in self[:n]]
tail = [formatter(x) for x in self[-n:]]
head_joined = ", ".join(head)
tail_joined = ", ".join(tail)
summary = f"[{head_joined} ... {tail_joined}]"
else:
tail = [formatter(x) for x in self]
joined = ", ".join(tail)
summary = f"[{joined}]"

return summary + "," + self._format_space()

def _format_attrs(self):
attrs = []
if self.name is not None:
attrs.append(("name", default_pprint(self.name)))
attrs.append(("dtype", f"'{self.dtype}'"))
return attrs

def _format_space(self) -> str:
space = " " * (len(type(self).__name__) + 1)
return f"\n{space}"
return self._data._format_data() + "," + self._format_space()

# --------------------------------------------------------------------
# Set Operations
Expand Down
20 changes: 1 addition & 19 deletions pandas/core/indexes/multi.py
Original file line number Diff line number Diff line change
Expand Up @@ -89,11 +89,7 @@
lexsort_indexer,
)

from pandas.io.formats.printing import (
format_object_attrs,
format_object_summary,
pprint_thing,
)
from pandas.io.formats.printing import pprint_thing

if TYPE_CHECKING:
from pandas import (
Expand Down Expand Up @@ -1287,20 +1283,6 @@ def _formatter_func(self, tup):
formatter_funcs = [level._formatter_func for level in self.levels]
return tuple(func(val) for func, val in zip(formatter_funcs, tup))

def _format_data(self, name=None) -> str:
"""
Return the formatted data as a unicode string
"""
return format_object_summary(
self, self._formatter_func, name=name, line_break_each_value=True
)

def _format_attrs(self):
"""
Return a list of tuples of the (attr,formatted_value).
"""
return format_object_attrs(self, include_dtype=False)

def _format_native_types(self, na_rep="nan", **kwargs):
new_levels = []
new_codes = []
Expand Down