Skip to content

CLN: annotate __str__ and __repr__ methods #29467

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 1 commit into from
Nov 7, 2019
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
4 changes: 2 additions & 2 deletions pandas/_libs/internals.pyx
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,7 @@ cdef class BlockPlacement:
self._as_array = arr
self._has_array = True

def __str__(self):
def __str__(self) -> str:
cdef:
slice s = self._ensure_has_slice()
if s is not None:
Expand All @@ -63,7 +63,7 @@ cdef class BlockPlacement:

return '%s(%r)' % (self.__class__.__name__, v)

def __repr__(self):
def __repr__(self) -> str:
return str(self)

def __len__(self):
Expand Down
4 changes: 2 additions & 2 deletions pandas/_libs/interval.pyx
Original file line number Diff line number Diff line change
Expand Up @@ -377,15 +377,15 @@ cdef class Interval(IntervalMixin):

return left, right

def __repr__(self):
def __repr__(self) -> str:

left, right = self._repr_base()
name = type(self).__name__
repr_str = '{name}({left!r}, {right!r}, closed={closed!r})'.format(
name=name, left=left, right=right, closed=self.closed)
return repr_str

def __str__(self):
def __str__(self) -> str:

left, right = self._repr_base()
start_symbol = '[' if self.closed_left else '('
Expand Down
4 changes: 2 additions & 2 deletions pandas/_libs/intervaltree.pxi.in
Original file line number Diff line number Diff line change
Expand Up @@ -195,7 +195,7 @@ cdef class IntervalTree(IntervalMixin):
return (result.to_array().astype('intp'),
missing.to_array().astype('intp'))

def __repr__(self):
def __repr__(self) -> str:
return ('<IntervalTree[{dtype},{closed}]: '
'{n_elements} elements>'.format(
dtype=self.dtype, closed=self.closed,
Expand Down Expand Up @@ -394,7 +394,7 @@ cdef class {{dtype_title}}Closed{{closed_title}}IntervalNode:
else:
result.extend(self.center_left_indices)

def __repr__(self):
def __repr__(self) -> str:
if self.is_leaf_node:
return ('<{{dtype_title}}Closed{{closed_title}}IntervalNode: '
'%s elements (terminal)>' % self.n_elements)
Expand Down
4 changes: 2 additions & 2 deletions pandas/_libs/sparse.pyx
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,7 @@ cdef class IntIndex(SparseIndex):
args = (self.length, self.indices)
return IntIndex, args

def __repr__(self):
def __repr__(self) -> str:
output = 'IntIndex\n'
output += 'Indices: %s\n' % repr(self.indices)
return output
Expand Down Expand Up @@ -341,7 +341,7 @@ cdef class BlockIndex(SparseIndex):
args = (self.length, self.blocs, self.blengths)
return BlockIndex, args

def __repr__(self):
def __repr__(self) -> str:
output = 'BlockIndex\n'
output += 'Block locations: %s\n' % repr(self.blocs)
output += 'Block lengths: %s' % repr(self.blengths)
Expand Down
2 changes: 1 addition & 1 deletion pandas/_libs/tslibs/c_timestamp.pyx
Original file line number Diff line number Diff line change
Expand Up @@ -124,7 +124,7 @@ cdef class _Timestamp(datetime):
# now __reduce_ex__ is defined and higher priority than __reduce__
return self.__reduce__()

def __repr__(self):
def __repr__(self) -> str:
stamp = self._repr_base
zone = None

Expand Down
4 changes: 2 additions & 2 deletions pandas/_libs/tslibs/nattype.pyx
Original file line number Diff line number Diff line change
Expand Up @@ -259,10 +259,10 @@ cdef class _NaT(datetime):
"""
return self.to_datetime64()

def __repr__(self):
def __repr__(self) -> str:
return 'NaT'

def __str__(self):
def __str__(self) -> str:
return 'NaT'

def isoformat(self, sep='T'):
Expand Down
2 changes: 1 addition & 1 deletion pandas/_libs/tslibs/offsets.pyx
Original file line number Diff line number Diff line change
Expand Up @@ -422,7 +422,7 @@ class _BaseOffset:
# that allows us to use methods that can go in a `cdef class`
return self * 1

def __repr__(self):
def __repr__(self) -> str:
className = getattr(self, '_outputName', type(self).__name__)

if abs(self.n) != 1:
Expand Down
4 changes: 2 additions & 2 deletions pandas/_libs/tslibs/period.pyx
Original file line number Diff line number Diff line change
Expand Up @@ -2215,12 +2215,12 @@ cdef class _Period:
def freqstr(self):
return self.freq.freqstr

def __repr__(self):
def __repr__(self) -> str:
base, mult = get_freq_code(self.freq)
formatted = period_format(self.ordinal, base)
return "Period('%s', '%s')" % (formatted, self.freqstr)

def __str__(self):
def __str__(self) -> str:
"""
Return a string representation for a particular DataFrame
"""
Expand Down
4 changes: 2 additions & 2 deletions pandas/_libs/tslibs/timedeltas.pyx
Original file line number Diff line number Diff line change
Expand Up @@ -1142,10 +1142,10 @@ cdef class _Timedelta(timedelta):

return fmt.format(**comp_dict)

def __repr__(self):
def __repr__(self) -> str:
return "Timedelta('{val}')".format(val=self._repr_base(format='long'))

def __str__(self):
def __str__(self) -> str:
return self._repr_base(format='long')

def __bool__(self):
Expand Down
2 changes: 1 addition & 1 deletion pandas/core/arrays/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -913,7 +913,7 @@ def view(self, dtype=None) -> Union[ABCExtensionArray, np.ndarray]:
# Printing
# ------------------------------------------------------------------------

def __repr__(self):
def __repr__(self) -> str:
from pandas.io.formats.printing import format_object_summary

template = "{class_name}{data}\nLength: {length}, dtype: {dtype}"
Expand Down
2 changes: 1 addition & 1 deletion pandas/core/arrays/categorical.py
Original file line number Diff line number Diff line change
Expand Up @@ -2048,7 +2048,7 @@ def _get_repr(self, length=True, na_rep="NaN", footer=True):
result = formatter.to_string()
return str(result)

def __repr__(self):
def __repr__(self) -> str:
"""
String representation.
"""
Expand Down
2 changes: 1 addition & 1 deletion pandas/core/arrays/integer.py
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@ class _IntegerDtype(ExtensionDtype):
type = None # type: Type
na_value = np.nan

def __repr__(self):
def __repr__(self) -> str:
sign = "U" if self.is_unsigned_integer else ""
return "{sign}Int{size}Dtype()".format(sign=sign, size=8 * self.itemsize)

Expand Down
2 changes: 1 addition & 1 deletion pandas/core/arrays/interval.py
Original file line number Diff line number Diff line change
Expand Up @@ -860,7 +860,7 @@ def _format_data(self):

return summary

def __repr__(self):
def __repr__(self) -> str:
template = (
"{class_name}"
"{data}\n"
Expand Down
2 changes: 1 addition & 1 deletion pandas/core/arrays/numpy_.py
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ def __init__(self, dtype):
self._name = dtype.name
self._type = dtype.type

def __repr__(self):
def __repr__(self) -> str:
return "PandasDtype({!r})".format(self.name)

@property
Expand Down
2 changes: 1 addition & 1 deletion pandas/core/arrays/sparse/array.py
Original file line number Diff line number Diff line change
Expand Up @@ -1515,7 +1515,7 @@ def _add_comparison_ops(cls):
# ----------
# Formatting
# -----------
def __repr__(self):
def __repr__(self) -> str:
return "{self}\nFill: {fill}\n{index}".format(
self=printing.pprint_thing(self),
fill=printing.pprint_thing(self.fill_value),
Expand Down
2 changes: 1 addition & 1 deletion pandas/core/arrays/sparse/dtype.py
Original file line number Diff line number Diff line change
Expand Up @@ -165,7 +165,7 @@ def subtype(self):
def name(self):
return "Sparse[{}, {}]".format(self.subtype.name, self.fill_value)

def __repr__(self):
def __repr__(self) -> str:
return self.name

@classmethod
Expand Down
2 changes: 1 addition & 1 deletion pandas/core/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,7 @@ def _constructor(self):
"""class constructor (for this class it's just `__class__`"""
return self.__class__

def __repr__(self):
def __repr__(self) -> str:
"""
Return a string representation for a particular object.
"""
Expand Down
2 changes: 1 addition & 1 deletion pandas/core/computation/expr.py
Original file line number Diff line number Diff line change
Expand Up @@ -834,7 +834,7 @@ def assigner(self):
def __call__(self):
return self.terms(self.env)

def __repr__(self):
def __repr__(self) -> str:
return printing.pprint_thing(self.terms)

def __len__(self):
Expand Down
10 changes: 5 additions & 5 deletions pandas/core/computation/ops.py
Original file line number Diff line number Diff line change
Expand Up @@ -82,7 +82,7 @@ def __init__(self, name, env, side=None, encoding=None):
def local_name(self):
return self.name.replace(_LOCAL_TAG, "")

def __repr__(self):
def __repr__(self) -> str:
return pprint_thing(self.name)

def __call__(self, *args, **kwargs):
Expand Down Expand Up @@ -182,7 +182,7 @@ def _resolve_name(self):
def name(self):
return self.value

def __repr__(self):
def __repr__(self) -> str:
# in python 2 str() of float
# can truncate shorter than repr()
return repr(self.name)
Expand All @@ -204,7 +204,7 @@ def __init__(self, op, operands, *args, **kwargs):
def __iter__(self):
return iter(self.operands)

def __repr__(self):
def __repr__(self) -> str:
"""
Print a generic n-ary operator and its operands using infix notation.
"""
Expand Down Expand Up @@ -557,7 +557,7 @@ def __call__(self, env):
operand = self.operand(env)
return self.func(operand)

def __repr__(self):
def __repr__(self) -> str:
return pprint_thing("{0}({1})".format(self.op, self.operand))

@property
Expand All @@ -582,7 +582,7 @@ def __call__(self, env):
with np.errstate(all="ignore"):
return self.func.func(*operands)

def __repr__(self):
def __repr__(self) -> str:
operands = map(str, self.operands)
return pprint_thing("{0}({1})".format(self.op, ",".join(operands)))

Expand Down
6 changes: 3 additions & 3 deletions pandas/core/computation/pytables.py
Original file line number Diff line number Diff line change
Expand Up @@ -229,7 +229,7 @@ def convert_values(self):


class FilterBinOp(BinOp):
def __repr__(self):
def __repr__(self) -> str:
return pprint_thing(
"[Filter : [{lhs}] -> [{op}]".format(lhs=self.filter[0], op=self.filter[1])
)
Expand Down Expand Up @@ -295,7 +295,7 @@ def evaluate(self):


class ConditionBinOp(BinOp):
def __repr__(self):
def __repr__(self) -> str:
return pprint_thing("[Condition : [{cond}]]".format(cond=self.condition))

def invert(self):
Expand Down Expand Up @@ -545,7 +545,7 @@ def __init__(self, where, queryables=None, encoding=None, scope_level=0):
)
self.terms = self.parse()

def __repr__(self):
def __repr__(self) -> str:
if self.terms is not None:
return pprint_thing(self.terms)
return pprint_thing(self.expr)
Expand Down
2 changes: 1 addition & 1 deletion pandas/core/computation/scope.py
Original file line number Diff line number Diff line change
Expand Up @@ -139,7 +139,7 @@ def __init__(
self.resolvers = DeepChainMap(*resolvers)
self.temps = {}

def __repr__(self):
def __repr__(self) -> str:
scope_keys = _get_pretty_string(list(self.scope.keys()))
res_keys = _get_pretty_string(list(self.resolvers.keys()))
unicode_str = "{name}(scope={scope_keys}, resolvers={res_keys})"
Expand Down
2 changes: 1 addition & 1 deletion pandas/core/dtypes/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -71,7 +71,7 @@ class property**.

_metadata = () # type: Tuple[str, ...]

def __str__(self):
def __str__(self) -> str:
return self.name

def __eq__(self, other):
Expand Down
8 changes: 4 additions & 4 deletions pandas/core/dtypes/dtypes.py
Original file line number Diff line number Diff line change
Expand Up @@ -415,7 +415,7 @@ def __eq__(self, other: Any) -> bool:
return True
return hash(self) == hash(other)

def __repr__(self):
def __repr__(self) -> str_type:
tpl = "CategoricalDtype(categories={}ordered={})"
if self.categories is None:
data = "None, "
Expand Down Expand Up @@ -752,7 +752,7 @@ def construct_from_string(cls, string):

raise TypeError("Could not construct DatetimeTZDtype")

def __str__(self):
def __str__(self) -> str_type:
return "datetime64[{unit}, {tz}]".format(unit=self.unit, tz=self.tz)

@property
Expand Down Expand Up @@ -889,7 +889,7 @@ def construct_from_string(cls, string):
pass
raise TypeError("could not construct PeriodDtype")

def __str__(self):
def __str__(self) -> str_type:
return self.name

@property
Expand Down Expand Up @@ -1068,7 +1068,7 @@ def construct_from_string(cls, string):
def type(self):
return Interval

def __str__(self):
def __str__(self) -> str_type:
if self.subtype is None:
return "interval"
return "interval[{subtype}]".format(subtype=self.subtype)
Expand Down
2 changes: 1 addition & 1 deletion pandas/core/generic.py
Original file line number Diff line number Diff line change
Expand Up @@ -2107,7 +2107,7 @@ def __setstate__(self, state):
# ----------------------------------------------------------------------
# Rendering Methods

def __repr__(self):
def __repr__(self) -> str:
# string representation based upon iterating over self
# (since, by definition, `PandasContainers` are iterable)
prepr = "[%s]" % ",".join(map(pprint_thing, self))
Expand Down
2 changes: 1 addition & 1 deletion pandas/core/groupby/groupby.py
Original file line number Diff line number Diff line change
Expand Up @@ -402,7 +402,7 @@ def __init__(
def __len__(self):
return len(self.groups)

def __repr__(self):
def __repr__(self) -> str:
# TODO: Better repr for GroupBy object
return object.__repr__(self)

Expand Down
4 changes: 2 additions & 2 deletions pandas/core/groupby/grouper.py
Original file line number Diff line number Diff line change
Expand Up @@ -210,7 +210,7 @@ def _set_grouper(self, obj, sort=False):
def groups(self):
return self.grouper.groups

def __repr__(self):
def __repr__(self) -> str:
attrs_list = (
"{}={!r}".format(attr_name, getattr(self, attr_name))
for attr_name in self._attributes
Expand Down Expand Up @@ -372,7 +372,7 @@ def __init__(

self.grouper = self.grouper.astype("timedelta64[ns]")

def __repr__(self):
def __repr__(self) -> str:
return "Grouping({0})".format(self.name)

def __iter__(self):
Expand Down
6 changes: 3 additions & 3 deletions pandas/core/indexes/frozen.py
Original file line number Diff line number Diff line change
Expand Up @@ -105,10 +105,10 @@ def _disabled(self, *args, **kwargs):
)
)

def __str__(self):
def __str__(self) -> str:
return pprint_thing(self, quote_strings=True, escape_chars=("\t", "\r", "\n"))

def __repr__(self):
def __repr__(self) -> str:
return "%s(%s)" % (self.__class__.__name__, str(self))

__setitem__ = __setslice__ = __delitem__ = __delslice__ = _disabled
Expand Down Expand Up @@ -148,7 +148,7 @@ def values(self):
arr = self.view(np.ndarray).copy()
return arr

def __repr__(self):
def __repr__(self) -> str:
"""
Return a string representation for this object.
"""
Expand Down
Loading