Skip to content
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

STY: Changed x.__class__ to type(x) #29816

Closed
wants to merge 3 commits into from
Closed
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
2 changes: 1 addition & 1 deletion pandas/_libs/internals.pyx
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,7 @@ cdef class BlockPlacement:
else:
v = self._as_array

return f'{self.__class__.__name__}({v})'
return f'{type(self).__name__}({v})'

def __repr__(self) -> str:
return str(self)
Expand Down
21 changes: 9 additions & 12 deletions pandas/_libs/tslibs/c_timestamp.pyx
Original file line number Diff line number Diff line change
Expand Up @@ -87,7 +87,7 @@ cdef class _Timestamp(datetime):
return PyObject_RichCompareBool(val, other, op)

try:
ots = self.__class__(other)
ots = type(self)(other)
except ValueError:
return self._compare_outside_nanorange(other, op)
else:
Expand All @@ -96,7 +96,7 @@ cdef class _Timestamp(datetime):
if ndim != -1:
if ndim == 0:
if is_datetime64_object(other):
other = self.__class__(other)
other = type(self)(other)
elif is_array(other):
# zero-dim array, occurs if try comparison with
# datetime64 scalar on the left hand side
Expand All @@ -105,7 +105,7 @@ cdef class _Timestamp(datetime):
# the numpy C api to extract it.
other = cnp.PyArray_ToScalar(cnp.PyArray_DATA(other),
other)
other = self.__class__(other)
other = type(self)(other)
else:
return NotImplemented
elif is_array(other):
Expand Down Expand Up @@ -226,8 +226,7 @@ cdef class _Timestamp(datetime):

if is_timedelta64_object(other):
other_int = other.astype('timedelta64[ns]').view('i8')
return self.__class__(self.value + other_int,
tz=self.tzinfo, freq=self.freq)
return type(self)(self.value + other_int, tz=self.tzinfo, freq=self.freq)

elif is_integer_object(other):
maybe_integer_op_deprecated(self)
Expand All @@ -238,8 +237,7 @@ cdef class _Timestamp(datetime):
elif self.freq is None:
raise NullFrequencyError(
"Cannot add integral value to Timestamp without freq.")
return self.__class__((self.freq * other).apply(self),
freq=self.freq)
return type(self)((self.freq * other).apply(self), freq=self.freq)

elif PyDelta_Check(other) or hasattr(other, 'delta'):
# delta --> offsets.Tick
Expand All @@ -253,8 +251,7 @@ cdef class _Timestamp(datetime):
other.seconds * 1000000 +
other.microseconds) * 1000

result = self.__class__(self.value + nanos,
tz=self.tzinfo, freq=self.freq)
result = type(self)(self.value + nanos, tz=self.tzinfo, freq=self.freq)
return result

elif is_array(other):
Expand All @@ -272,7 +269,7 @@ cdef class _Timestamp(datetime):

result = datetime.__add__(self, other)
if PyDateTime_Check(result):
result = self.__class__(result)
result = type(self)(result)
result.nanosecond = self.nanosecond
return result

Expand Down Expand Up @@ -304,9 +301,9 @@ cdef class _Timestamp(datetime):
if (PyDateTime_Check(self)
and (PyDateTime_Check(other) or is_datetime64_object(other))):
if isinstance(self, _Timestamp):
other = self.__class__(other)
other = type(self)(other)
else:
self = other.__class__(self)
self = type(other)(self)

# validate tz's
if not tz_compare(self.tzinfo, other.tzinfo):
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 @@ -363,7 +363,7 @@ class _BaseOffset:
attrs = [(k, v) for k, v in all_paras.items()
if (k not in exclude) and (k[0] != '_')]
attrs = sorted(set(attrs))
params = tuple([str(self.__class__)] + attrs)
params = tuple([str(type(self))] + attrs)
return params

@property
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 @@ -923,7 +923,7 @@ def __repr__(self) -> str:
data = format_object_summary(
self, self._formatter(), indent_for_name=False
).rstrip(", \n")
class_name = "<{}>\n".format(self.__class__.__name__)
class_name = "<{}>\n".format(type(self).__name__)
return template.format(
class_name=class_name, data=data, length=len(self), dtype=self.dtype
)
Expand Down
4 changes: 2 additions & 2 deletions pandas/core/arrays/interval.py
Original file line number Diff line number Diff line change
Expand Up @@ -870,7 +870,7 @@ def __repr__(self) -> str:
# repr does. So we include a newline in our template, and strip
# any trailing newlines from format_object_summary
data = self._format_data()
class_name = "<{}>\n".format(self.__class__.__name__)
class_name = "<{}>\n".format(type(self).__name__)
return template.format(
class_name=class_name,
data=data,
Expand All @@ -880,7 +880,7 @@ def __repr__(self) -> str:
)

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

@property
Expand Down
4 changes: 2 additions & 2 deletions pandas/core/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,7 @@ class PandasObject(DirNamesMixin):
@property
def _constructor(self):
"""class constructor (for this class it's just `__class__`"""
return self.__class__
return type(self)

def __repr__(self) -> str:
"""
Expand Down Expand Up @@ -1185,7 +1185,7 @@ def _reduce(
if func is None:
raise TypeError(
"{klass} cannot perform the operation {op}".format(
klass=self.__class__.__name__, op=name
klass=type(self).__name__, op=name
)
)
return func(skipna=skipna, **kwds)
Expand Down
2 changes: 1 addition & 1 deletion pandas/core/common.py
Original file line number Diff line number Diff line change
Expand Up @@ -317,7 +317,7 @@ def get_callable_name(obj):
return get_callable_name(obj.func)
# fall back to class name
if hasattr(obj, "__call__"):
return obj.__class__.__name__
return type(obj).__name__
# everything failed (probably because the argument
# wasn't actually callable); we return None
# instead of the empty string in this case to allow
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 @@ -435,7 +435,7 @@ def visit(self, node, **kwargs):
e.msg = "Python keyword not valid identifier in numexpr query"
raise e

method = "visit_" + node.__class__.__name__
method = "visit_" + type(node).__name__
visitor = getattr(self, method)
return visitor(node, **kwargs)

Expand Down
2 changes: 1 addition & 1 deletion pandas/core/computation/ops.py
Original file line number Diff line number Diff line change
Expand Up @@ -145,7 +145,7 @@ def type(self):
def raw(self) -> str:
return pprint_thing(
"{0}(name={1!r}, type={2})"
"".format(self.__class__.__name__, self.name, self.type)
"".format(type(self).__name__, self.name, self.type)
)

@property
Expand Down
2 changes: 1 addition & 1 deletion pandas/core/computation/pytables.py
Original file line number Diff line number Diff line change
Expand Up @@ -440,7 +440,7 @@ def visit_Attribute(self, node, **kwargs):
attr = node.attr
value = node.value

ctx = node.ctx.__class__
ctx = type(node.ctx)
if ctx == ast.Load:
# resolve the value
resolved = self.visit(value)
Expand Down
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 @@ -253,7 +253,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 @@ -1536,7 +1536,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 @@ -1561,7 +1561,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 @@ -1867,7 +1867,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 @@ -2061,7 +2061,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
10 changes: 5 additions & 5 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 = type(self).__name__
data = self._format_data()
attrs = self._format_attrs()
space = self._format_space()
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):
if isinstance(other, (tuple, FrozenList)):
Expand All @@ -85,12 +85,12 @@ def __eq__(self, other):
__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
Loading