Skip to content

Commit

Permalink
STY: x.__class__ to type(x) #batch-2 (pandas-dev#29893)
Browse files Browse the repository at this point in the history
  • Loading branch information
ShaharNaveh authored and proost committed Dec 19, 2019
1 parent 58a1265 commit 558abce
Show file tree
Hide file tree
Showing 11 changed files with 35 additions and 37 deletions.
2 changes: 1 addition & 1 deletion pandas/core/dtypes/dtypes.py
Original file line number Diff line number Diff line change
Expand Up @@ -420,7 +420,7 @@ def __repr__(self) -> str_type:
if self.categories is None:
data = "None, "
else:
data = self.categories._format_data(name=self.__class__.__name__)
data = self.categories._format_data(name=type(self).__name__)
return tpl.format(data=data, ordered=self._ordered)

@staticmethod
Expand Down
10 changes: 5 additions & 5 deletions pandas/core/generic.py
Original file line number Diff line number Diff line change
Expand Up @@ -251,7 +251,7 @@ def _validate_dtype(self, dtype):
if dtype.kind == "V":
raise NotImplementedError(
"compound dtypes are not implemented"
" in the {0} constructor".format(self.__class__.__name__)
" in the {0} constructor".format(type(self).__name__)
)

return dtype
Expand Down Expand Up @@ -1534,7 +1534,7 @@ def __nonzero__(self):
raise ValueError(
"The truth value of a {0} is ambiguous. "
"Use a.empty, a.bool(), a.item(), a.any() or a.all().".format(
self.__class__.__name__
type(self).__name__
)
)

Expand All @@ -1559,7 +1559,7 @@ def bool(self):
elif is_scalar(v):
raise ValueError(
"bool cannot act on a non-boolean single element "
"{0}".format(self.__class__.__name__)
"{0}".format(type(self).__name__)
)

self.__nonzero__()
Expand Down Expand Up @@ -1865,7 +1865,7 @@ def _drop_labels_or_levels(self, keys, axis=0):
def __hash__(self):
raise TypeError(
"{0!r} objects are mutable, thus they cannot be"
" hashed".format(self.__class__.__name__)
" hashed".format(type(self).__name__)
)

def __iter__(self):
Expand Down Expand Up @@ -2059,7 +2059,7 @@ def __repr__(self) -> str:
# string representation based upon iterating over self
# (since, by definition, `PandasContainers` are iterable)
prepr = "[%s]" % ",".join(map(pprint_thing, self))
return f"{self.__class__.__name__}({prepr})"
return f"{type(self).__name__}({prepr})"

def _repr_latex_(self):
"""
Expand Down
2 changes: 1 addition & 1 deletion pandas/core/groupby/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@ def _gotitem(self, key, ndim, subset=None):
except IndexError:
groupby = self._groupby

self = self.__class__(subset, groupby=groupby, parent=self, **kwargs)
self = type(self)(subset, groupby=groupby, parent=self, **kwargs)
self._reset_cache()
if subset.ndim == 2:
if is_scalar(key) and key in subset or is_list_like(key):
Expand Down
2 changes: 1 addition & 1 deletion pandas/core/groupby/generic.py
Original file line number Diff line number Diff line change
Expand Up @@ -473,7 +473,7 @@ def _transform_general(self, func, *args, **kwargs):
"""
Transform with a non-str `func`.
"""
klass = self._selected_obj.__class__
klass = type(self._selected_obj)

results = []
for name, group in self:
Expand Down
2 changes: 1 addition & 1 deletion pandas/core/groupby/grouper.py
Original file line number Diff line number Diff line change
Expand Up @@ -211,7 +211,7 @@ def __repr__(self) -> str:
if getattr(self, attr_name) is not None
)
attrs = ", ".join(attrs_list)
cls_name = self.__class__.__name__
cls_name = type(self).__name__
return f"{cls_name}({attrs})"


Expand Down
12 changes: 6 additions & 6 deletions pandas/core/indexes/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -815,7 +815,7 @@ def take(self, indices, axis=0, allow_fill=True, fill_value=None, **kwargs):
else:
if allow_fill and fill_value is not None:
msg = "Unable to fill values because {0} cannot contain NA"
raise ValueError(msg.format(self.__class__.__name__))
raise ValueError(msg.format(type(self).__name__))
taken = self.values.take(indices)
return self._shallow_copy(taken)

Expand Down Expand Up @@ -948,7 +948,7 @@ def __repr__(self):
"""
Return a string representation for this object.
"""
klass = self.__class__.__name__
klass_name = type(self).__name__
data = self._format_data()
attrs = self._format_attrs()
space = self._format_space()
Expand All @@ -959,7 +959,7 @@ def __repr__(self):
if data is None:
data = ""

res = f"{klass}({data}{prepr})"
res = f"{klass_name}({data}{prepr})"

return res

Expand Down Expand Up @@ -1287,7 +1287,7 @@ def _set_names(self, values, level=None):
for name in values:
if not is_hashable(name):
raise TypeError(
"{}.name must be a hashable type".format(self.__class__.__name__)
"{}.name must be a hashable type".format(type(self).__name__)
)
self.name = values[0]

Expand Down Expand Up @@ -1794,7 +1794,7 @@ def is_all_dates(self) -> bool:
def __reduce__(self):
d = dict(data=self._data)
d.update(self._get_attributes_dict())
return _new_Index, (self.__class__, d), None
return _new_Index, (type(self), d), None

def __setstate__(self, state):
"""
Expand Down Expand Up @@ -2290,7 +2290,7 @@ def __nonzero__(self):
raise ValueError(
"The truth value of a {0} is ambiguous. "
"Use a.empty, a.bool(), a.item(), a.any() or a.all().".format(
self.__class__.__name__
type(self).__name__
)
)

Expand Down
2 changes: 1 addition & 1 deletion pandas/core/indexes/datetimes.py
Original file line number Diff line number Diff line change
Expand Up @@ -423,7 +423,7 @@ def __reduce__(self):

d = dict(data=self._data)
d.update(self._get_attributes_dict())
return _new_DatetimeIndex, (self.__class__, d), None
return _new_DatetimeIndex, (type(self), d), None

def __setstate__(self, state):
"""Necessary for making this object picklable"""
Expand Down
14 changes: 7 additions & 7 deletions pandas/core/indexes/frozen.py
Original file line number Diff line number Diff line change
Expand Up @@ -69,13 +69,13 @@ def difference(self, other) -> "FrozenList":

def __getitem__(self, n):
if isinstance(n, slice):
return self.__class__(super().__getitem__(n))
return type(self)(super().__getitem__(n))
return super().__getitem__(n)

def __radd__(self, other):
if isinstance(other, tuple):
other = list(other)
return self.__class__(other + list(self))
return type(self)(other + list(self))

def __eq__(self, other) -> bool:
if isinstance(other, (tuple, FrozenList)):
Expand All @@ -85,12 +85,12 @@ def __eq__(self, other) -> bool:
__req__ = __eq__

def __mul__(self, other):
return self.__class__(super().__mul__(other))
return type(self)(super().__mul__(other))

__imul__ = __mul__

def __reduce__(self):
return self.__class__, (list(self),)
return type(self), (list(self),)

def __hash__(self):
return hash(tuple(self))
Expand All @@ -99,15 +99,15 @@ def _disabled(self, *args, **kwargs):
"""This method will not function because object is immutable."""
raise TypeError(
"'{cls}' does not support mutable operations.".format(
cls=self.__class__.__name__
cls=type(self).__name__
)
)

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

def __repr__(self) -> str:
return f"{self.__class__.__name__}({str(self)})"
return f"{type(self).__name__}({str(self)})"

__setitem__ = __setslice__ = __delitem__ = __delslice__ = _disabled
pop = append = extend = remove = sort = insert = _disabled
Expand All @@ -132,7 +132,7 @@ def __new__(cls, data, dtype=None, copy=False):
def _disabled(self, *args, **kwargs):
"""This method will not function because object is immutable."""
raise TypeError(
"'{cls}' does not support mutable operations.".format(cls=self.__class__)
"'{cls}' does not support mutable operations.".format(cls=type(self))
)

__setitem__ = __setslice__ = __delitem__ = __delslice__ = _disabled
Expand Down
6 changes: 3 additions & 3 deletions pandas/core/indexes/interval.py
Original file line number Diff line number Diff line change
Expand Up @@ -497,7 +497,7 @@ def __array_wrap__(self, result, context=None):
def __reduce__(self):
d = dict(left=self.left, right=self.right)
d.update(self._get_attributes_dict())
return _new_IntervalIndex, (self.__class__, d), None
return _new_IntervalIndex, (type(self), d), None

@Appender(_index_shared_docs["copy"])
def copy(self, deep=False, name=None):
Expand All @@ -512,7 +512,7 @@ def copy(self, deep=False, name=None):

@Appender(_index_shared_docs["astype"])
def astype(self, dtype, copy=True):
with rewrite_exception("IntervalArray", self.__class__.__name__):
with rewrite_exception("IntervalArray", type(self).__name__):
new_values = self.values.astype(dtype, copy=copy)
if is_interval_dtype(new_values):
return self._shallow_copy(new_values.left, new_values.right)
Expand Down Expand Up @@ -1205,7 +1205,7 @@ def _format_attrs(self):
return attrs

def _format_space(self):
space = " " * (len(self.__class__.__name__) + 1)
space = " " * (len(type(self).__name__) + 1)
return "\n{space}".format(space=space)

# --------------------------------------------------------------------
Expand Down
8 changes: 3 additions & 5 deletions pandas/core/indexes/multi.py
Original file line number Diff line number Diff line change
Expand Up @@ -1245,9 +1245,7 @@ def _set_names(self, names, level=None, validate=True):
# All items in 'names' need to be hashable:
if not is_hashable(name):
raise TypeError(
"{}.name must be a hashable type".format(
self.__class__.__name__
)
"{}.name must be a hashable type".format(type(self).__name__)
)
self._names[lev] = name

Expand Down Expand Up @@ -1911,7 +1909,7 @@ def __reduce__(self):
sortorder=self.sortorder,
names=list(self.names),
)
return ibase._new_Index, (self.__class__, d), None
return ibase._new_Index, (type(self), d), None

def __setstate__(self, state):
"""Necessary for making this object picklable"""
Expand Down Expand Up @@ -3264,7 +3262,7 @@ def astype(self, dtype, copy=True):
elif not is_object_dtype(dtype):
msg = (
"Setting {cls} dtype to anything other than object is not supported"
).format(cls=self.__class__)
).format(cls=type(self))
raise TypeError(msg)
elif copy is True:
return self._shallow_copy()
Expand Down
12 changes: 6 additions & 6 deletions pandas/core/indexes/range.py
Original file line number Diff line number Diff line change
Expand Up @@ -179,7 +179,7 @@ def _get_data_as_items(self):
def __reduce__(self):
d = self._get_attributes_dict()
d.update(dict(self._get_data_as_items()))
return ibase._new_Index, (self.__class__, d), None
return ibase._new_Index, (type(self), d), None

# --------------------------------------------------------------------
# Rendering Methods
Expand Down Expand Up @@ -592,27 +592,27 @@ def _union(self, other, sort):
and (start_s - end_o) <= step_s
and (start_o - end_s) <= step_s
):
return self.__class__(start_r, end_r + step_s, step_s)
return type(self)(start_r, end_r + step_s, step_s)
if (
(step_s % 2 == 0)
and (abs(start_s - start_o) <= step_s / 2)
and (abs(end_s - end_o) <= step_s / 2)
):
return self.__class__(start_r, end_r + step_s / 2, step_s / 2)
return type(self)(start_r, end_r + step_s / 2, step_s / 2)
elif step_o % step_s == 0:
if (
(start_o - start_s) % step_s == 0
and (start_o + step_s >= start_s)
and (end_o - step_s <= end_s)
):
return self.__class__(start_r, end_r + step_s, step_s)
return type(self)(start_r, end_r + step_s, step_s)
elif step_s % step_o == 0:
if (
(start_s - start_o) % step_o == 0
and (start_s + step_o >= start_o)
and (end_s - step_o <= end_o)
):
return self.__class__(start_r, end_r + step_o, step_o)
return type(self)(start_r, end_r + step_o, step_o)
return self._int64index._union(other, sort=sort)

@Appender(_index_shared_docs["join"])
Expand Down Expand Up @@ -781,7 +781,7 @@ def _evaluate_numeric_binop(self, other):
rstart = op(left.start, right)
rstop = op(left.stop, right)

result = self.__class__(rstart, rstop, rstep, **attrs)
result = type(self)(rstart, rstop, rstep, **attrs)

# for compat with numpy / Int64Index
# even if we can represent as a RangeIndex, return
Expand Down

0 comments on commit 558abce

Please sign in to comment.