diff --git a/pandas/_libs/internals.pyx b/pandas/_libs/internals.pyx index ba108c4524b9c..603caed805e58 100644 --- a/pandas/_libs/internals.pyx +++ b/pandas/_libs/internals.pyx @@ -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) diff --git a/pandas/_libs/tslibs/c_timestamp.pyx b/pandas/_libs/tslibs/c_timestamp.pyx index c6c98e996b745..02e252219453b 100644 --- a/pandas/_libs/tslibs/c_timestamp.pyx +++ b/pandas/_libs/tslibs/c_timestamp.pyx @@ -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: @@ -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 @@ -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): @@ -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) @@ -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 @@ -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): @@ -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 @@ -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): diff --git a/pandas/_libs/tslibs/offsets.pyx b/pandas/_libs/tslibs/offsets.pyx index 68a0a4a403c81..4ba9f5f30894a 100644 --- a/pandas/_libs/tslibs/offsets.pyx +++ b/pandas/_libs/tslibs/offsets.pyx @@ -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 diff --git a/pandas/core/arrays/base.py b/pandas/core/arrays/base.py index a444a4e46d0d7..bf50d6e9b50e7 100644 --- a/pandas/core/arrays/base.py +++ b/pandas/core/arrays/base.py @@ -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 ) diff --git a/pandas/core/arrays/interval.py b/pandas/core/arrays/interval.py index cb482665b3534..ab558b8fa75d6 100644 --- a/pandas/core/arrays/interval.py +++ b/pandas/core/arrays/interval.py @@ -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, @@ -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 diff --git a/pandas/core/base.py b/pandas/core/base.py index 176a92132e20a..83d6ac76cdd98 100644 --- a/pandas/core/base.py +++ b/pandas/core/base.py @@ -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: """ @@ -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) diff --git a/pandas/core/common.py b/pandas/core/common.py index 41b6ebbd2f196..d62f1557952a8 100644 --- a/pandas/core/common.py +++ b/pandas/core/common.py @@ -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 diff --git a/pandas/core/computation/expr.py b/pandas/core/computation/expr.py index 95785af8dc5ea..e608f82b03ade 100644 --- a/pandas/core/computation/expr.py +++ b/pandas/core/computation/expr.py @@ -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) diff --git a/pandas/core/computation/ops.py b/pandas/core/computation/ops.py index 983382dce717a..4852e498537f2 100644 --- a/pandas/core/computation/ops.py +++ b/pandas/core/computation/ops.py @@ -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 diff --git a/pandas/core/computation/pytables.py b/pandas/core/computation/pytables.py index 58bbfd0a1bdee..65e38ff290ce4 100644 --- a/pandas/core/computation/pytables.py +++ b/pandas/core/computation/pytables.py @@ -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) diff --git a/pandas/core/dtypes/dtypes.py b/pandas/core/dtypes/dtypes.py index 523c8e8bd02d0..db252b71a51b8 100644 --- a/pandas/core/dtypes/dtypes.py +++ b/pandas/core/dtypes/dtypes.py @@ -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 diff --git a/pandas/core/generic.py b/pandas/core/generic.py index 2e2ae4e1dfa0a..fbaf00d8172ea 100644 --- a/pandas/core/generic.py +++ b/pandas/core/generic.py @@ -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 @@ -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__ ) ) @@ -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__() @@ -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): @@ -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): """ diff --git a/pandas/core/groupby/base.py b/pandas/core/groupby/base.py index 407cd8342d486..e088400b25f0f 100644 --- a/pandas/core/groupby/base.py +++ b/pandas/core/groupby/base.py @@ -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): diff --git a/pandas/core/groupby/generic.py b/pandas/core/groupby/generic.py index 99ef281e842b1..4726cdfb05a70 100644 --- a/pandas/core/groupby/generic.py +++ b/pandas/core/groupby/generic.py @@ -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: diff --git a/pandas/core/groupby/grouper.py b/pandas/core/groupby/grouper.py index dc924455b141d..9b2f43d8dd484 100644 --- a/pandas/core/groupby/grouper.py +++ b/pandas/core/groupby/grouper.py @@ -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})" diff --git a/pandas/core/indexes/base.py b/pandas/core/indexes/base.py index 486cc0cd9032d..c333e054d18e3 100644 --- a/pandas/core/indexes/base.py +++ b/pandas/core/indexes/base.py @@ -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) @@ -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() @@ -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] @@ -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): """ @@ -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__ ) ) diff --git a/pandas/core/indexes/datetimes.py b/pandas/core/indexes/datetimes.py index ab9f57ff9ac69..0d368845ea4f2 100644 --- a/pandas/core/indexes/datetimes.py +++ b/pandas/core/indexes/datetimes.py @@ -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""" diff --git a/pandas/core/indexes/frozen.py b/pandas/core/indexes/frozen.py index 2c9521d23f71a..8bc01a877c203 100644 --- a/pandas/core/indexes/frozen.py +++ b/pandas/core/indexes/frozen.py @@ -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)): @@ -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)) @@ -99,7 +99,7 @@ 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__ ) ) @@ -107,7 +107,7 @@ 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 @@ -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 diff --git a/pandas/core/indexes/interval.py b/pandas/core/indexes/interval.py index 35e8405e0f1aa..a9e119f3c5f87 100644 --- a/pandas/core/indexes/interval.py +++ b/pandas/core/indexes/interval.py @@ -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): @@ -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) @@ -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) # -------------------------------------------------------------------- diff --git a/pandas/core/indexes/multi.py b/pandas/core/indexes/multi.py index 048112cbf0836..d151fb7260a58 100644 --- a/pandas/core/indexes/multi.py +++ b/pandas/core/indexes/multi.py @@ -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 @@ -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""" @@ -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() diff --git a/pandas/core/indexes/range.py b/pandas/core/indexes/range.py index f7bbbee461e8d..f300cde3b5bcc 100644 --- a/pandas/core/indexes/range.py +++ b/pandas/core/indexes/range.py @@ -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 @@ -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"]) @@ -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 diff --git a/pandas/core/indexing.py b/pandas/core/indexing.py index b52015b738c6e..1f5783436813e 100755 --- a/pandas/core/indexing.py +++ b/pandas/core/indexing.py @@ -105,7 +105,7 @@ class _NDFrameIndexer(_NDFrameIndexerBase): def __call__(self, axis=None): # we need to return a copy of ourselves - new_self = self.__class__(self.name, self.obj) + new_self = type(self)(self.name, self.obj) if axis is not None: axis = self.obj._get_axis_number(axis) diff --git a/pandas/core/internals/blocks.py b/pandas/core/internals/blocks.py index 2d6ffb7277742..5fac8cea67bab 100644 --- a/pandas/core/internals/blocks.py +++ b/pandas/core/internals/blocks.py @@ -257,11 +257,11 @@ def make_block_same_class(self, values, placement=None, ndim=None): placement = self.mgr_locs if ndim is None: ndim = self.ndim - return make_block(values, placement=placement, ndim=ndim, klass=self.__class__) + return make_block(values, placement=placement, ndim=ndim, klass=type(self)) def __repr__(self) -> str: # don't want to print out all of the items here - name = pprint_thing(self.__class__.__name__) + name = pprint_thing(type(self).__name__) if self._is_single_block: result = "{name}: {len} dtype: {dtype}".format( diff --git a/pandas/core/internals/concat.py b/pandas/core/internals/concat.py index f981c00fdad36..6c4ab2882d67f 100644 --- a/pandas/core/internals/concat.py +++ b/pandas/core/internals/concat.py @@ -122,7 +122,7 @@ def __init__(self, block, shape, indexers=None): def __repr__(self) -> str: return "{name}({block!r}, {indexers})".format( - name=self.__class__.__name__, block=self.block, indexers=self.indexers + name=type(self).__name__, block=self.block, indexers=self.indexers ) @cache_readonly diff --git a/pandas/core/internals/managers.py b/pandas/core/internals/managers.py index c37a8ea5e42a4..4dc2cac0ad534 100644 --- a/pandas/core/internals/managers.py +++ b/pandas/core/internals/managers.py @@ -154,7 +154,7 @@ def make_empty(self, axes=None): blocks = np.array([], dtype=self.array_dtype) else: blocks = [] - return self.__class__(blocks, axes) + return type(self)(blocks, axes) def __nonzero__(self): return True @@ -321,7 +321,7 @@ def __len__(self) -> int: return len(self.items) def __repr__(self) -> str: - output = pprint_thing(self.__class__.__name__) + output = pprint_thing(type(self).__name__) for i, ax in enumerate(self.axes): if i == 0: output += "\nItems: {ax}".format(ax=ax) @@ -435,7 +435,7 @@ def apply( if len(result_blocks) == 0: return self.make_empty(axes or self.axes) - bm = self.__class__( + bm = type(self)( result_blocks, axes or self.axes, do_integrity_check=do_integrity_check ) bm._consolidate_inplace() @@ -524,7 +524,7 @@ def get_axe(block, qs, axes): for b in blocks ] - return self.__class__(blocks, new_axes) + return type(self)(blocks, new_axes) # single block, i.e. ndim == {1} values = concat_compat([b.values for b in blocks]) @@ -634,7 +634,7 @@ def comp(s, regex=False): rb = new_rb result_blocks.extend(rb) - bm = self.__class__(result_blocks, self.axes) + bm = type(self)(result_blocks, self.axes) bm._consolidate_inplace() return bm @@ -729,7 +729,7 @@ def combine(self, blocks, copy=True): axes = list(self.axes) axes[0] = self.items.take(indexer) - return self.__class__(new_blocks, axes, do_integrity_check=False) + return type(self)(new_blocks, axes, do_integrity_check=False) def get_slice(self, slobj, axis=0): if axis >= self.ndim: @@ -746,7 +746,7 @@ def get_slice(self, slobj, axis=0): new_axes = list(self.axes) new_axes[axis] = new_axes[axis][slobj] - bm = self.__class__(new_blocks, new_axes, do_integrity_check=False) + bm = type(self)(new_blocks, new_axes, do_integrity_check=False) bm._consolidate_inplace() return bm @@ -922,7 +922,7 @@ def consolidate(self): if self.is_consolidated(): return self - bm = self.__class__(self.blocks, self.axes) + bm = type(self)(self.blocks, self.axes) bm._is_consolidated = False bm._consolidate_inplace() return bm @@ -1256,7 +1256,7 @@ def reindex_indexer( new_axes = list(self.axes) new_axes[axis] = new_axis - return self.__class__(new_blocks, new_axes) + return type(self)(new_blocks, new_axes) def _slice_take_blocks_ax0(self, slice_or_indexer, fill_tuple=None): """ @@ -1526,9 +1526,7 @@ def get_slice(self, slobj, axis=0): if axis >= self.ndim: raise IndexError("Requested axis not found in manager") - return self.__class__( - self._block._slice(slobj), self.index[slobj], fastpath=True - ) + return type(self)(self._block._slice(slobj), self.index[slobj], fastpath=True) @property def index(self): diff --git a/pandas/core/resample.py b/pandas/core/resample.py index 2433e3f52b4a9..58c4a97d651d8 100644 --- a/pandas/core/resample.py +++ b/pandas/core/resample.py @@ -96,7 +96,7 @@ def __str__(self) -> str: if getattr(self.groupby, k, None) is not None ) return "{klass} [{attrs}]".format( - klass=self.__class__.__name__, attrs=", ".join(attrs) + klass=type(self).__name__, attrs=", ".join(attrs) ) def __getattr__(self, attr): @@ -885,7 +885,7 @@ def count(self): result = self._downsample("count") if not len(self.ax): if self._selected_obj.ndim == 1: - result = self._selected_obj.__class__( + result = type(self._selected_obj)( [], index=result.index, dtype="int64", name=self._selected_obj.name ) else: diff --git a/pandas/core/series.py b/pandas/core/series.py index a9ecf97dad68b..cfcd5577e9ee0 100644 --- a/pandas/core/series.py +++ b/pandas/core/series.py @@ -256,9 +256,7 @@ def __init__( elif is_extension_array_dtype(data): pass elif isinstance(data, (set, frozenset)): - raise TypeError( - "{0!r} type is unordered".format(data.__class__.__name__) - ) + raise TypeError("{0!r} type is unordered".format(type(data).__name__)) elif isinstance(data, ABCSparseArray): # handle sparse passed here (and force conversion) data = data.to_dense() @@ -1573,7 +1571,7 @@ def to_string( raise AssertionError( "result must be of type unicode, type" " of result is {0!r}" - "".format(result.__class__.__name__) + "".format(type(result).__name__) ) if buf is None: diff --git a/pandas/core/window/rolling.py b/pandas/core/window/rolling.py index 7f3404100f71c..d8aa362080093 100644 --- a/pandas/core/window/rolling.py +++ b/pandas/core/window/rolling.py @@ -204,7 +204,7 @@ def _get_window(self, other=None, win_type: Optional[str] = None) -> int: @property def _window_type(self) -> str: - return self.__class__.__name__ + return type(self).__name__ def __repr__(self) -> str: """ diff --git a/pandas/errors/__init__.py b/pandas/errors/__init__.py index 73cc40ae0e0d3..34838af5fd6e4 100644 --- a/pandas/errors/__init__.py +++ b/pandas/errors/__init__.py @@ -178,6 +178,6 @@ def __str__(self) -> str: if self.methodtype == "classmethod": name = self.class_instance.__name__ else: - name = self.class_instance.__class__.__name__ + name = type(self.class_instance).__name__ msg = "This {methodtype} must be defined in the concrete class {name}" return msg.format(methodtype=self.methodtype, name=name) diff --git a/pandas/io/clipboard/__init__.py b/pandas/io/clipboard/__init__.py index 4f690a57893d1..8a438bc035c96 100644 --- a/pandas/io/clipboard/__init__.py +++ b/pandas/io/clipboard/__init__.py @@ -96,7 +96,7 @@ def _stringifyText(text): if not isinstance(text, acceptedTypes): raise PyperclipException( f"only str, int, float, and bool values" - f"can be copied to the clipboard, not {text.__class__.__name__}" + f"can be copied to the clipboard, not {type(text).__name__}" ) return str(text) diff --git a/pandas/io/formats/format.py b/pandas/io/formats/format.py index b18f0db622b3e..f8f5d337185c4 100644 --- a/pandas/io/formats/format.py +++ b/pandas/io/formats/format.py @@ -352,7 +352,7 @@ def to_string(self) -> str: if len(series) == 0: return "{name}([], {footer})".format( - name=self.series.__class__.__name__, footer=footer + name=type(self.series).__name__, footer=footer ) fmt_index, have_header = self._get_formatted_index() diff --git a/pandas/io/formats/printing.py b/pandas/io/formats/printing.py index a4f1488fb6b69..8218799129952 100644 --- a/pandas/io/formats/printing.py +++ b/pandas/io/formats/printing.py @@ -321,7 +321,7 @@ def format_object_summary( if display_width is None: display_width = get_option("display.width") or 80 if name is None: - name = obj.__class__.__name__ + name = type(obj).__name__ if indent_for_name: name_len = len(name) diff --git a/pandas/io/packers.py b/pandas/io/packers.py index 253441ab25813..bb7b00571b0df 100644 --- a/pandas/io/packers.py +++ b/pandas/io/packers.py @@ -404,7 +404,7 @@ def encode(obj): if isinstance(obj, RangeIndex): return { "typ": "range_index", - "klass": obj.__class__.__name__, + "klass": type(obj).__name__, "name": getattr(obj, "name", None), "start": obj._range.start, "stop": obj._range.stop, @@ -413,7 +413,7 @@ def encode(obj): elif isinstance(obj, PeriodIndex): return { "typ": "period_index", - "klass": obj.__class__.__name__, + "klass": type(obj).__name__, "name": getattr(obj, "name", None), "freq": getattr(obj, "freqstr", None), "dtype": obj.dtype.name, @@ -429,7 +429,7 @@ def encode(obj): obj = obj.tz_convert("UTC") return { "typ": "datetime_index", - "klass": obj.__class__.__name__, + "klass": type(obj).__name__, "name": getattr(obj, "name", None), "dtype": obj.dtype.name, "data": convert(obj.asi8), @@ -444,7 +444,7 @@ def encode(obj): typ = "interval_array" return { "typ": typ, - "klass": obj.__class__.__name__, + "klass": type(obj).__name__, "name": getattr(obj, "name", None), "left": getattr(obj, "left", None), "right": getattr(obj, "right", None), @@ -453,7 +453,7 @@ def encode(obj): elif isinstance(obj, MultiIndex): return { "typ": "multi_index", - "klass": obj.__class__.__name__, + "klass": type(obj).__name__, "names": getattr(obj, "names", None), "dtype": obj.dtype.name, "data": convert(obj.values), @@ -462,7 +462,7 @@ def encode(obj): else: return { "typ": "index", - "klass": obj.__class__.__name__, + "klass": type(obj).__name__, "name": getattr(obj, "name", None), "dtype": obj.dtype.name, "data": convert(obj.values), @@ -472,7 +472,7 @@ def encode(obj): elif isinstance(obj, Categorical): return { "typ": "category", - "klass": obj.__class__.__name__, + "klass": type(obj).__name__, "name": getattr(obj, "name", None), "codes": obj.codes, "categories": obj.categories, @@ -483,7 +483,7 @@ def encode(obj): elif isinstance(obj, Series): return { "typ": "series", - "klass": obj.__class__.__name__, + "klass": type(obj).__name__, "name": getattr(obj, "name", None), "index": obj.index, "dtype": obj.dtype.name, @@ -498,7 +498,7 @@ def encode(obj): # the block manager return { "typ": "block_manager", - "klass": obj.__class__.__name__, + "klass": type(obj).__name__, "axes": data.axes, "blocks": [ { @@ -506,7 +506,7 @@ def encode(obj): "values": convert(b.values), "shape": b.values.shape, "dtype": b.dtype.name, - "klass": b.__class__.__name__, + "klass": type(b).__name__, "compress": compressor, } for b in data.blocks @@ -553,7 +553,7 @@ def encode(obj): elif isinstance(obj, BlockIndex): return { "typ": "block_index", - "klass": obj.__class__.__name__, + "klass": type(obj).__name__, "blocs": obj.blocs, "blengths": obj.blengths, "length": obj.length, @@ -561,7 +561,7 @@ def encode(obj): elif isinstance(obj, IntIndex): return { "typ": "int_index", - "klass": obj.__class__.__name__, + "klass": type(obj).__name__, "indices": obj.indices, "length": obj.length, } diff --git a/pandas/io/pytables.py b/pandas/io/pytables.py index 18ae081caf69d..e6f7e3c2492ef 100644 --- a/pandas/io/pytables.py +++ b/pandas/io/pytables.py @@ -3733,7 +3733,7 @@ def create_axes( # the non_index_axes info info = _get_info(self.info, i) info["names"] = list(a.names) - info["type"] = a.__class__.__name__ + info["type"] = type(a).__name__ self.non_index_axes.append((i, append_axis)) diff --git a/pandas/io/stata.py b/pandas/io/stata.py index 567eeb7f5cdc8..9c350afed1d33 100644 --- a/pandas/io/stata.py +++ b/pandas/io/stata.py @@ -857,11 +857,11 @@ def __str__(self) -> str: def __repr__(self) -> str: # not perfect :-/ - return "{cls}({obj})".format(cls=self.__class__, obj=self) + return "{cls}({obj})".format(cls=type(self), obj=self) def __eq__(self, other): return ( - isinstance(other, self.__class__) + isinstance(other, type(self)) and self.string == other.string and self.value == other.value ) diff --git a/pandas/tests/extension/base/dtype.py b/pandas/tests/extension/base/dtype.py index a5040c8cfc2fc..d1e1717225e15 100644 --- a/pandas/tests/extension/base/dtype.py +++ b/pandas/tests/extension/base/dtype.py @@ -96,7 +96,7 @@ def test_eq(self, dtype): assert dtype != "anonther_type" def test_construct_from_string(self, dtype): - dtype_instance = dtype.__class__.construct_from_string(dtype.name) - assert isinstance(dtype_instance, dtype.__class__) + dtype_instance = type(dtype).construct_from_string(dtype.name) + assert isinstance(dtype_instance, type(dtype)) with pytest.raises(TypeError): - dtype.__class__.construct_from_string("another_type") + type(dtype).construct_from_string("another_type") diff --git a/pandas/tests/extension/base/ops.py b/pandas/tests/extension/base/ops.py index 5e4fb6d69e52c..00d620439ed87 100644 --- a/pandas/tests/extension/base/ops.py +++ b/pandas/tests/extension/base/ops.py @@ -123,9 +123,7 @@ def test_direct_arith_with_series_returns_not_implemented(self, data): result = data.__add__(other) assert result is NotImplemented else: - raise pytest.skip( - "{} does not implement add".format(data.__class__.__name__) - ) + raise pytest.skip("{} does not implement add".format(type(data).__name__)) class BaseComparisonOpsTests(BaseOpsUtil): @@ -170,5 +168,5 @@ def test_direct_arith_with_series_returns_not_implemented(self, data): assert result is NotImplemented else: raise pytest.skip( - "{} does not implement __eq__".format(data.__class__.__name__) + "{} does not implement __eq__".format(type(data).__name__) ) diff --git a/pandas/tests/extension/base/printing.py b/pandas/tests/extension/base/printing.py index 0f10efbf32a49..5d17a4b0cbee2 100644 --- a/pandas/tests/extension/base/printing.py +++ b/pandas/tests/extension/base/printing.py @@ -18,7 +18,7 @@ def test_array_repr(self, data, size): data = type(data)._concat_same_type([data] * 5) result = repr(data) - assert data.__class__.__name__ in result + assert type(data).__name__ in result assert "Length: {}".format(len(data)) in result assert str(data.dtype) in result if size == "big": diff --git a/pandas/tests/frame/test_apply.py b/pandas/tests/frame/test_apply.py index 3c97a87c95bd2..d9cbec820e92a 100644 --- a/pandas/tests/frame/test_apply.py +++ b/pandas/tests/frame/test_apply.py @@ -642,7 +642,7 @@ def test_applymap_box(self): } ) - result = df.applymap(lambda x: "{0}".format(x.__class__.__name__)) + result = df.applymap(lambda x: "{0}".format(type(x).__name__)) expected = pd.DataFrame( { "a": ["Timestamp", "Timestamp"], diff --git a/pandas/tests/indexes/common.py b/pandas/tests/indexes/common.py index c35c4c3568f74..102949fe3f05e 100644 --- a/pandas/tests/indexes/common.py +++ b/pandas/tests/indexes/common.py @@ -244,7 +244,7 @@ def test_str(self): idx = self.create_index() idx.name = "foo" assert "'foo'" in str(idx) - assert idx.__class__.__name__ in str(idx) + assert type(idx).__name__ in str(idx) def test_repr_max_seq_item_setting(self): # GH10182 @@ -260,8 +260,8 @@ def test_copy_name(self, indices): if isinstance(indices, MultiIndex): return - first = indices.__class__(indices, copy=True, name="mario") - second = first.__class__(first, copy=False) + first = type(indices)(indices, copy=True, name="mario") + second = type(first)(first, copy=False) # Even though "copy=False", we want a new object. assert first is not second @@ -292,7 +292,7 @@ def test_ensure_copied_data(self, indices): # MultiIndex and CategoricalIndex are tested separately return - index_type = indices.__class__ + index_type = type(indices) result = index_type(indices.values, copy=True, **init_kwargs) tm.assert_index_equal(indices, result) tm.assert_numpy_array_equal( @@ -502,7 +502,7 @@ def test_difference_base(self, sort, indices): cases = [klass(second.values) for klass in [np.array, Series, list]] for case in cases: if isinstance(indices, (DatetimeIndex, TimedeltaIndex)): - assert result.__class__ == answer.__class__ + assert type(result) == type(answer) tm.assert_numpy_array_equal( result.sort_values().asi8, answer.sort_values().asi8 ) @@ -677,9 +677,9 @@ def test_hasnans_isnans(self, indices): values[1] = np.nan if isinstance(indices, PeriodIndex): - idx = indices.__class__(values, freq=indices.freq) + idx = type(indices)(values, freq=indices.freq) else: - idx = indices.__class__(values) + idx = type(indices)(values) expected = np.array([False] * len(idx), dtype=bool) expected[1] = True @@ -716,9 +716,9 @@ def test_fillna(self, indices): values[1] = np.nan if isinstance(indices, PeriodIndex): - idx = indices.__class__(values, freq=indices.freq) + idx = type(indices)(values, freq=indices.freq) else: - idx = indices.__class__(values) + idx = type(indices)(values) expected = np.array([False] * len(idx), dtype=bool) expected[1] = True diff --git a/pandas/tests/indexes/datetimelike.py b/pandas/tests/indexes/datetimelike.py index e6e38ce9921f5..42244626749b9 100644 --- a/pandas/tests/indexes/datetimelike.py +++ b/pandas/tests/indexes/datetimelike.py @@ -38,7 +38,7 @@ def test_str(self): idx.name = "foo" assert not "length={}".format(len(idx)) in str(idx) assert "'foo'" in str(idx) - assert idx.__class__.__name__ in str(idx) + assert type(idx).__name__ in str(idx) if hasattr(idx, "tz"): if idx.tz is not None: diff --git a/pandas/tests/indexes/multi/test_missing.py b/pandas/tests/indexes/multi/test_missing.py index 15bbd2ce97c3c..31de40512c474 100644 --- a/pandas/tests/indexes/multi/test_missing.py +++ b/pandas/tests/indexes/multi/test_missing.py @@ -42,9 +42,9 @@ def test_fillna(idx): values[1] = np.nan if isinstance(index, PeriodIndex): - idx = index.__class__(values, freq=index.freq) + idx = type(index)(values, freq=index.freq) else: - idx = index.__class__(values) + idx = type(index)(values) expected = np.array([False] * len(idx), dtype=bool) expected[1] = True @@ -115,7 +115,7 @@ def test_hasnans_isnans(idx): values = index.values values[1] = np.nan - index = idx.__class__(values) + index = type(idx)(values) expected = np.array([False] * len(index), dtype=bool) expected[1] = True diff --git a/pandas/tests/indexes/period/test_partial_slicing.py b/pandas/tests/indexes/period/test_partial_slicing.py index 50a12baf352d9..501c2a4d8edcc 100644 --- a/pandas/tests/indexes/period/test_partial_slicing.py +++ b/pandas/tests/indexes/period/test_partial_slicing.py @@ -123,7 +123,7 @@ def test_range_slice_outofbounds(self): for idx in [didx, pidx]: df = DataFrame(dict(units=[100 + i for i in range(10)]), index=idx) - empty = DataFrame(index=idx.__class__([], freq="D"), columns=["units"]) + empty = DataFrame(index=type(idx)([], freq="D"), columns=["units"]) empty["units"] = empty["units"].astype("int64") tm.assert_frame_equal(df["2013/09/01":"2013/09/30"], empty) diff --git a/pandas/tests/indexes/test_base.py b/pandas/tests/indexes/test_base.py index 21c828328e5b8..ad0e98b5d0f76 100644 --- a/pandas/tests/indexes/test_base.py +++ b/pandas/tests/indexes/test_base.py @@ -752,7 +752,7 @@ def test_fancy(self): @pytest.mark.parametrize("dtype", [np.int_, np.bool_]) def test_empty_fancy(self, index, dtype): empty_arr = np.array([], dtype=dtype) - empty_index = index.__class__([]) + empty_index = type(index)([]) assert index[[]].identical(empty_index) assert index[empty_arr].identical(empty_index) @@ -762,7 +762,7 @@ def test_empty_fancy_raises(self, index): # pd.DatetimeIndex is excluded, because it overrides getitem and should # be tested separately. empty_farr = np.array([], dtype=np.float_) - empty_index = index.__class__([]) + empty_index = type(index)([]) assert index[[]].identical(empty_index) # np.ndarray only accepts ndarray of int & bool dtypes, so should Index @@ -2446,8 +2446,8 @@ def test_copy_name(self): # GH12309 index = self.create_index() - first = index.__class__(index, copy=True, name="mario") - second = first.__class__(first, copy=False) + first = type(index)(index, copy=True, name="mario") + second = type(first)(first, copy=False) # Even though "copy=False", we want a new object. assert first is not second diff --git a/pandas/tests/reshape/test_concat.py b/pandas/tests/reshape/test_concat.py index bb8339439d339..63f1ef7595f31 100644 --- a/pandas/tests/reshape/test_concat.py +++ b/pandas/tests/reshape/test_concat.py @@ -949,7 +949,7 @@ def test_append_preserve_index_name(self): all_indexes = indexes_can_append + indexes_cannot_append_with_other - @pytest.mark.parametrize("index", all_indexes, ids=lambda x: x.__class__.__name__) + @pytest.mark.parametrize("index", all_indexes, ids=lambda x: type(x).__name__) def test_append_same_columns_type(self, index): # GH18359 @@ -979,7 +979,7 @@ def test_append_same_columns_type(self, index): @pytest.mark.parametrize( "df_columns, series_index", combinations(indexes_can_append, r=2), - ids=lambda x: x.__class__.__name__, + ids=lambda x: type(x).__name__, ) def test_append_different_columns_types(self, df_columns, series_index): # GH18359 @@ -1004,12 +1004,12 @@ def test_append_different_columns_types(self, df_columns, series_index): tm.assert_frame_equal(result, expected) @pytest.mark.parametrize( - "index_can_append", indexes_can_append, ids=lambda x: x.__class__.__name__ + "index_can_append", indexes_can_append, ids=lambda x: type(x).__name__ ) @pytest.mark.parametrize( "index_cannot_append_with_other", indexes_cannot_append_with_other, - ids=lambda x: x.__class__.__name__, + ids=lambda x: type(x).__name__, ) def test_append_different_columns_types_raises( self, index_can_append, index_cannot_append_with_other diff --git a/pandas/tests/series/test_apply.py b/pandas/tests/series/test_apply.py index bdbfa333ef33a..1c29da6a87015 100644 --- a/pandas/tests/series/test_apply.py +++ b/pandas/tests/series/test_apply.py @@ -92,7 +92,7 @@ def test_apply_box(self): s = pd.Series(vals) assert s.dtype == "datetime64[ns]" # boxed value must be Timestamp instance - res = s.apply(lambda x: "{0}_{1}_{2}".format(x.__class__.__name__, x.day, x.tz)) + res = s.apply(lambda x: "{0}_{1}_{2}".format(type(x).__name__, x.day, x.tz)) exp = pd.Series(["Timestamp_1_None", "Timestamp_2_None"]) tm.assert_series_equal(res, exp) @@ -102,7 +102,7 @@ def test_apply_box(self): ] s = pd.Series(vals) assert s.dtype == "datetime64[ns, US/Eastern]" - res = s.apply(lambda x: "{0}_{1}_{2}".format(x.__class__.__name__, x.day, x.tz)) + res = s.apply(lambda x: "{0}_{1}_{2}".format(type(x).__name__, x.day, x.tz)) exp = pd.Series(["Timestamp_1_US/Eastern", "Timestamp_2_US/Eastern"]) tm.assert_series_equal(res, exp) @@ -110,7 +110,7 @@ def test_apply_box(self): vals = [pd.Timedelta("1 days"), pd.Timedelta("2 days")] s = pd.Series(vals) assert s.dtype == "timedelta64[ns]" - res = s.apply(lambda x: "{0}_{1}".format(x.__class__.__name__, x.days)) + res = s.apply(lambda x: "{0}_{1}".format(type(x).__name__, x.days)) exp = pd.Series(["Timedelta_1", "Timedelta_2"]) tm.assert_series_equal(res, exp) @@ -118,7 +118,7 @@ def test_apply_box(self): vals = [pd.Period("2011-01-01", freq="M"), pd.Period("2011-01-02", freq="M")] s = pd.Series(vals) assert s.dtype == "Period[M]" - res = s.apply(lambda x: "{0}_{1}".format(x.__class__.__name__, x.freqstr)) + res = s.apply(lambda x: "{0}_{1}".format(type(x).__name__, x.freqstr)) exp = pd.Series(["Period_M", "Period_M"]) tm.assert_series_equal(res, exp) @@ -614,7 +614,7 @@ def test_map_box(self): s = pd.Series(vals) assert s.dtype == "datetime64[ns]" # boxed value must be Timestamp instance - res = s.map(lambda x: "{0}_{1}_{2}".format(x.__class__.__name__, x.day, x.tz)) + res = s.map(lambda x: "{0}_{1}_{2}".format(type(x).__name__, x.day, x.tz)) exp = pd.Series(["Timestamp_1_None", "Timestamp_2_None"]) tm.assert_series_equal(res, exp) @@ -624,7 +624,7 @@ def test_map_box(self): ] s = pd.Series(vals) assert s.dtype == "datetime64[ns, US/Eastern]" - res = s.map(lambda x: "{0}_{1}_{2}".format(x.__class__.__name__, x.day, x.tz)) + res = s.map(lambda x: "{0}_{1}_{2}".format(type(x).__name__, x.day, x.tz)) exp = pd.Series(["Timestamp_1_US/Eastern", "Timestamp_2_US/Eastern"]) tm.assert_series_equal(res, exp) @@ -632,7 +632,7 @@ def test_map_box(self): vals = [pd.Timedelta("1 days"), pd.Timedelta("2 days")] s = pd.Series(vals) assert s.dtype == "timedelta64[ns]" - res = s.map(lambda x: "{0}_{1}".format(x.__class__.__name__, x.days)) + res = s.map(lambda x: "{0}_{1}".format(type(x).__name__, x.days)) exp = pd.Series(["Timedelta_1", "Timedelta_2"]) tm.assert_series_equal(res, exp) @@ -640,7 +640,7 @@ def test_map_box(self): vals = [pd.Period("2011-01-01", freq="M"), pd.Period("2011-01-02", freq="M")] s = pd.Series(vals) assert s.dtype == "Period[M]" - res = s.map(lambda x: "{0}_{1}".format(x.__class__.__name__, x.freqstr)) + res = s.map(lambda x: "{0}_{1}".format(type(x).__name__, x.freqstr)) exp = pd.Series(["Period_M", "Period_M"]) tm.assert_series_equal(res, exp) diff --git a/pandas/tests/test_base.py b/pandas/tests/test_base.py index f24bb9e72aef5..e65388be2ba7d 100644 --- a/pandas/tests/test_base.py +++ b/pandas/tests/test_base.py @@ -400,7 +400,7 @@ def test_value_counts_unique_nunique(self): result = o.unique() if isinstance(o, Index): - assert isinstance(result, o.__class__) + assert isinstance(result, type(o)) tm.assert_index_equal(result, orig) assert result.dtype == orig.dtype elif is_datetime64tz_dtype(o): diff --git a/pandas/tests/tseries/holiday/test_holiday.py b/pandas/tests/tseries/holiday/test_holiday.py index 06869fcd7a4f8..7748b965f8962 100644 --- a/pandas/tests/tseries/holiday/test_holiday.py +++ b/pandas/tests/tseries/holiday/test_holiday.py @@ -238,7 +238,7 @@ class TestCalendar(AbstractHolidayCalendar): rules = [] calendar = get_calendar("TestCalendar") - assert TestCalendar == calendar.__class__ + assert TestCalendar == type(calendar) def test_factory(): diff --git a/pandas/tests/tseries/offsets/test_offsets.py b/pandas/tests/tseries/offsets/test_offsets.py index d70780741aa88..ae78d5a55bb5e 100644 --- a/pandas/tests/tseries/offsets/test_offsets.py +++ b/pandas/tests/tseries/offsets/test_offsets.py @@ -358,7 +358,7 @@ def _check_offsetfunc_works(self, offset, funcname, dt, expected, normalize=Fals ts = Timestamp(dt) + Nano(5) if ( - offset_s.__class__.__name__ == "DateOffset" + type(offset_s).__name__ == "DateOffset" and (funcname == "apply" or normalize) and ts.nanosecond > 0 ): @@ -395,7 +395,7 @@ def _check_offsetfunc_works(self, offset, funcname, dt, expected, normalize=Fals ts = Timestamp(dt, tz=tz) + Nano(5) if ( - offset_s.__class__.__name__ == "DateOffset" + type(offset_s).__name__ == "DateOffset" and (funcname == "apply" or normalize) and ts.nanosecond > 0 ): diff --git a/pandas/tseries/holiday.py b/pandas/tseries/holiday.py index 9417dc4b48499..2e5477ea00e39 100644 --- a/pandas/tseries/holiday.py +++ b/pandas/tseries/holiday.py @@ -363,7 +363,7 @@ def __init__(self, name=None, rules=None): """ super().__init__() if name is None: - name = self.__class__.__name__ + name = type(self).__name__ self.name = name if rules is not None: diff --git a/pandas/tseries/offsets.py b/pandas/tseries/offsets.py index e516d30d5490f..8e6285895ec37 100644 --- a/pandas/tseries/offsets.py +++ b/pandas/tseries/offsets.py @@ -311,7 +311,7 @@ def apply_index(self, i): raise NotImplementedError( "DateOffset subclass {name} " "does not have a vectorized " - "implementation".format(name=self.__class__.__name__) + "implementation".format(name=type(self).__name__) ) kwds = self.kwds relativedelta_fast = { @@ -402,7 +402,7 @@ def rollback(self, dt): """ dt = as_timestamp(dt) if not self.onOffset(dt): - dt = dt - self.__class__(1, normalize=self.normalize, **self.kwds) + dt = dt - type(self)(1, normalize=self.normalize, **self.kwds) return dt def rollforward(self, dt): @@ -416,7 +416,7 @@ def rollforward(self, dt): """ dt = as_timestamp(dt) if not self.onOffset(dt): - dt = dt + self.__class__(1, normalize=self.normalize, **self.kwds) + dt = dt + type(self)(1, normalize=self.normalize, **self.kwds) return dt def onOffset(self, dt): diff --git a/pandas/util/_depr_module.py b/pandas/util/_depr_module.py index 45e7db9281837..ae3c6359d20e0 100644 --- a/pandas/util/_depr_module.py +++ b/pandas/util/_depr_module.py @@ -32,7 +32,7 @@ def __init__(self, deprmod, deprmodto=None, removals=None, moved=None): self.moved = moved # For introspection purposes. - self.self_dir = frozenset(dir(self.__class__)) + self.self_dir = frozenset(dir(type(self))) def __dir__(self): deprmodule = self._import_deprmod() diff --git a/pandas/util/testing.py b/pandas/util/testing.py index bcd12eba1651a..96f98c4c7ebf6 100644 --- a/pandas/util/testing.py +++ b/pandas/util/testing.py @@ -713,7 +713,7 @@ def repr_class(x): return x try: - return x.__class__.__name__ + return type(x).__name__ except AttributeError: return repr(type(x)) @@ -782,13 +782,13 @@ def assert_is_valid_plot_return_object(objs): msg = ( "one of 'objs' is not a matplotlib Axes instance, type " "encountered {name!r}" - ).format(name=el.__class__.__name__) + ).format(name=type(el).__name__) assert isinstance(el, (plt.Axes, dict)), msg else: assert isinstance(objs, (plt.Artist, tuple, dict)), ( "objs is neither an ndarray of Artist instances nor a " 'single Artist instance, tuple, or dict, "objs" is a {name!r}'.format( - name=objs.__class__.__name__ + name=type(objs).__name__ ) )