Skip to content

ruff 0.0.284 #54548

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
Aug 15, 2023
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
2 changes: 1 addition & 1 deletion .pre-commit-config.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ repos:
hooks:
- id: black
- repo: https://github.com/astral-sh/ruff-pre-commit
rev: v0.0.282
rev: v0.0.284
hooks:
- id: ruff
args: [--exit-non-zero-on-fix]
Expand Down
7 changes: 4 additions & 3 deletions pandas/core/arrays/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -479,7 +479,7 @@ def __contains__(self, item: object) -> bool | np.bool_:
return (item == self).any() # type: ignore[union-attr]

# error: Signature of "__eq__" incompatible with supertype "object"
def __eq__(self, other: Any) -> ArrayLike: # type: ignore[override]
def __eq__(self, other: object) -> ArrayLike: # type: ignore[override]
"""
Return for `self == other` (element-wise equality).
"""
Expand All @@ -492,11 +492,12 @@ def __eq__(self, other: Any) -> ArrayLike: # type: ignore[override]
raise AbstractMethodError(self)

# error: Signature of "__ne__" incompatible with supertype "object"
def __ne__(self, other: Any) -> ArrayLike: # type: ignore[override]
def __ne__(self, other: object) -> ArrayLike: # type: ignore[override]
"""
Return for `self != other` (element-wise in-equality).
"""
return ~(self == other)
# error: Unsupported operand type for ~ ("ExtensionArray")
return ~(self == other) # type: ignore[operator]

def to_numpy(
self,
Expand Down
2 changes: 1 addition & 1 deletion pandas/core/arrays/string_.py
Original file line number Diff line number Diff line change
Expand Up @@ -574,7 +574,7 @@ def _str_map(
arr = np.asarray(self)

if is_integer_dtype(dtype) or is_bool_dtype(dtype):
constructor: type[IntegerArray] | type[BooleanArray]
constructor: type[IntegerArray | BooleanArray]
if is_integer_dtype(dtype):
constructor = IntegerArray
else:
Expand Down
2 changes: 1 addition & 1 deletion pandas/core/arrays/string_arrow.py
Original file line number Diff line number Diff line change
Expand Up @@ -262,7 +262,7 @@ def _str_map(
arr = np.asarray(self)

if is_integer_dtype(dtype) or is_bool_dtype(dtype):
constructor: type[IntegerArray] | type[BooleanArray]
constructor: type[IntegerArray | BooleanArray]
if is_integer_dtype(dtype):
constructor = IntegerArray
else:
Expand Down
6 changes: 3 additions & 3 deletions pandas/core/dtypes/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -110,7 +110,7 @@ class property**.
def __str__(self) -> str:
return self.name

def __eq__(self, other: Any) -> bool:
def __eq__(self, other: object) -> bool:
"""
Check whether 'other' is equal to self.

Expand Down Expand Up @@ -144,7 +144,7 @@ def __hash__(self) -> int:
# we need to avoid that and thus use hash function with old behavior
return object_hash(tuple(getattr(self, attr) for attr in self._metadata))

def __ne__(self, other: Any) -> bool:
def __ne__(self, other: object) -> bool:
return not self.__eq__(other)

@property
Expand Down Expand Up @@ -422,7 +422,7 @@ def __repr__(self) -> str:
def __str__(self) -> str:
return self.name

def __eq__(self, other: Any) -> bool:
def __eq__(self, other: object) -> bool:
if isinstance(other, str) and other == self.name:
return True
return super().__eq__(other)
Expand Down
14 changes: 7 additions & 7 deletions pandas/core/dtypes/dtypes.py
Original file line number Diff line number Diff line change
Expand Up @@ -388,7 +388,7 @@ def __hash__(self) -> int:
# We *do* want to include the real self.ordered here
return int(self._hash_categories)

def __eq__(self, other: Any) -> bool:
def __eq__(self, other: object) -> bool:
"""
Rules for CDT equality:
1) Any CDT is equal to the string 'category'
Expand Down Expand Up @@ -860,7 +860,7 @@ def __hash__(self) -> int:
# TODO: update this.
return hash(str(self))

def __eq__(self, other: Any) -> bool:
def __eq__(self, other: object) -> bool:
if isinstance(other, str):
if other.startswith("M8["):
other = f"datetime64[{other[3:]}"
Expand Down Expand Up @@ -1052,13 +1052,13 @@ def name(self) -> str_type:
def na_value(self) -> NaTType:
return NaT

def __eq__(self, other: Any) -> bool:
def __eq__(self, other: object) -> bool:
if isinstance(other, str):
return other in [self.name, self.name.title()]

return super().__eq__(other)

def __ne__(self, other: Any) -> bool:
def __ne__(self, other: object) -> bool:
return not self.__eq__(other)

@classmethod
Expand Down Expand Up @@ -1301,7 +1301,7 @@ def __hash__(self) -> int:
# make myself hashable
return hash(str(self))

def __eq__(self, other: Any) -> bool:
def __eq__(self, other: object) -> bool:
if isinstance(other, str):
return other.lower() in (self.name.lower(), str(self).lower())
elif not isinstance(other, IntervalDtype):
Expand Down Expand Up @@ -1647,7 +1647,7 @@ def __hash__(self) -> int:
# __eq__, so we explicitly do it here.
return super().__hash__()

def __eq__(self, other: Any) -> bool:
def __eq__(self, other: object) -> bool:
# We have to override __eq__ to handle NA values in _metadata.
# The base class does simple == checks, which fail for NA.
if isinstance(other, str):
Expand Down Expand Up @@ -2062,7 +2062,7 @@ def __hash__(self) -> int:
# make myself hashable
return hash(str(self))

def __eq__(self, other: Any) -> bool:
def __eq__(self, other: object) -> bool:
if not isinstance(other, type(self)):
return super().__eq__(other)
return self.pyarrow_dtype == other.pyarrow_dtype
Expand Down
2 changes: 1 addition & 1 deletion pandas/core/frame.py
Original file line number Diff line number Diff line change
Expand Up @@ -3416,7 +3416,7 @@ def to_xml(

lxml = import_optional_dependency("lxml.etree", errors="ignore")

TreeBuilder: type[EtreeXMLFormatter] | type[LxmlXMLFormatter]
TreeBuilder: type[EtreeXMLFormatter | LxmlXMLFormatter]

if parser == "lxml":
if lxml is not None:
Expand Down
16 changes: 11 additions & 5 deletions pandas/core/indexes/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -458,7 +458,7 @@ def _can_hold_strings(self) -> bool:
@property
def _engine_type(
self,
) -> type[libindex.IndexEngine] | type[libindex.ExtensionEngine]:
) -> type[libindex.IndexEngine | libindex.ExtensionEngine]:
return self._engine_types.get(self.dtype, libindex.ObjectEngine)

# whether we support partial string indexing. Overridden
Expand All @@ -481,7 +481,7 @@ def __new__(
copy: bool = False,
name=None,
tupleize_cols: bool = True,
) -> Index:
) -> Self:
from pandas.core.indexes.range import RangeIndex

name = maybe_extract_name(name, data, cls)
Expand All @@ -500,7 +500,9 @@ def __new__(
result = RangeIndex(start=data, copy=copy, name=name)
if dtype is not None:
return result.astype(dtype, copy=False)
return result
# error: Incompatible return value type (got "MultiIndex",
# expected "Self")
return result # type: ignore[return-value]
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm not sure why mypy didn't find this previously: self == other can return an ExtensionArray and it seems that it doesn't define __invert__


elif is_ea_or_datetimelike_dtype(dtype):
# non-EA dtype indexes have special casting logic, so we punt here
Expand All @@ -523,7 +525,7 @@ def __new__(
elif is_scalar(data):
raise cls._raise_scalar_data_error(data)
elif hasattr(data, "__array__"):
return Index(np.asarray(data), dtype=dtype, copy=copy, name=name)
return cls(np.asarray(data), dtype=dtype, copy=copy, name=name)
elif not is_list_like(data) and not isinstance(data, memoryview):
# 2022-11-16 the memoryview check is only necessary on some CI
# builds, not clear why
Expand All @@ -540,7 +542,11 @@ def __new__(
# 10697
from pandas.core.indexes.multi import MultiIndex

return MultiIndex.from_tuples(data, names=name)
# error: Incompatible return value type (got "MultiIndex",
# expected "Self")
return MultiIndex.from_tuples( # type: ignore[return-value]
data, names=name
)
# other iterable of some kind

if not isinstance(data, (list, tuple)):
Expand Down
3 changes: 2 additions & 1 deletion pandas/core/indexes/category.py
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,7 @@
from pandas._typing import (
Dtype,
DtypeObj,
Self,
npt,
)

Expand Down Expand Up @@ -210,7 +211,7 @@ def __new__(
dtype: Dtype | None = None,
copy: bool = False,
name: Hashable | None = None,
) -> CategoricalIndex:
) -> Self:
name = maybe_extract_name(name, data, cls)

if is_scalar(data):
Expand Down
7 changes: 2 additions & 5 deletions pandas/core/indexes/frozen.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,10 +8,7 @@
"""
from __future__ import annotations

from typing import (
Any,
NoReturn,
)
from typing import NoReturn

from pandas.core.base import PandasObject

Expand Down Expand Up @@ -80,7 +77,7 @@ def __radd__(self, other):
other = list(other)
return type(self)(other + list(self))

def __eq__(self, other: Any) -> bool:
def __eq__(self, other: object) -> bool:
if isinstance(other, (tuple, FrozenList)):
other = list(other)
return super().__eq__(other)
Expand Down
3 changes: 2 additions & 1 deletion pandas/core/indexes/interval.py
Original file line number Diff line number Diff line change
Expand Up @@ -93,6 +93,7 @@
Dtype,
DtypeObj,
IntervalClosedType,
Self,
npt,
)
_index_doc_kwargs = dict(ibase._index_doc_kwargs)
Expand Down Expand Up @@ -225,7 +226,7 @@ def __new__(
copy: bool = False,
name: Hashable | None = None,
verify_integrity: bool = True,
) -> IntervalIndex:
) -> Self:
name = maybe_extract_name(name, data, cls)

with rewrite_exception("IntervalArray", cls.__name__):
Expand Down
3 changes: 2 additions & 1 deletion pandas/core/indexes/multi.py
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,7 @@
IgnoreRaise,
IndexLabel,
Scalar,
Self,
Shape,
npt,
)
Expand Down Expand Up @@ -330,7 +331,7 @@ def __new__(
copy: bool = False,
name=None,
verify_integrity: bool = True,
) -> MultiIndex:
) -> Self:
# compat with Index
if name is not None:
names = name
Expand Down
4 changes: 2 additions & 2 deletions pandas/core/indexes/range.py
Original file line number Diff line number Diff line change
Expand Up @@ -139,12 +139,12 @@ def __new__(
dtype: Dtype | None = None,
copy: bool = False,
name: Hashable | None = None,
) -> RangeIndex:
) -> Self:
cls._validate_dtype(dtype)
name = maybe_extract_name(name, start, cls)

# RangeIndex
if isinstance(start, RangeIndex):
if isinstance(start, cls):
return start.copy(name=name)
elif isinstance(start, range):
return cls._simple_new(start, name=name)
Expand Down
2 changes: 1 addition & 1 deletion pandas/core/tools/datetimes.py
Original file line number Diff line number Diff line change
Expand Up @@ -133,7 +133,7 @@ class FulldatetimeDict(YearMonthDayDict, total=False):
def _guess_datetime_format_for_array(arr, dayfirst: bool | None = False) -> str | None:
# Try to guess the format based on the first non-NaN element, return None if can't
if (first_non_null := tslib.first_non_null(arr)) != -1:
if type(first_non_nan_element := arr[first_non_null]) is str:
if type(first_non_nan_element := arr[first_non_null]) is str: # noqa: E721
# GH#32264 np.str_ object
guessed_format = guess_datetime_format(
first_non_nan_element, dayfirst=dayfirst
Expand Down
2 changes: 1 addition & 1 deletion pandas/core/tools/numeric.py
Original file line number Diff line number Diff line change
Expand Up @@ -291,7 +291,7 @@ def to_numeric(
IntegerArray,
)

klass: type[IntegerArray] | type[BooleanArray] | type[FloatingArray]
klass: type[IntegerArray | BooleanArray | FloatingArray]
if is_integer_dtype(data.dtype):
klass = IntegerArray
elif is_bool_dtype(data.dtype):
Expand Down
27 changes: 20 additions & 7 deletions pandas/io/common.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@
import tarfile
from typing import (
IO,
TYPE_CHECKING,
Any,
AnyStr,
DefaultDict,
Expand All @@ -51,13 +52,7 @@

from pandas._typing import (
BaseBuffer,
CompressionDict,
CompressionOptions,
FilePath,
ReadBuffer,
ReadCsvBuffer,
StorageOptions,
WriteBuffer,
)
from pandas.compat import (
get_bz2_file,
Expand All @@ -84,6 +79,19 @@
BaseBufferT = TypeVar("BaseBufferT", bound=BaseBuffer)


if TYPE_CHECKING:
from types import TracebackType

from pandas._typing import (
CompressionDict,
CompressionOptions,
FilePath,
ReadBuffer,
StorageOptions,
WriteBuffer,
)


@dataclasses.dataclass
class IOArgs:
"""
Expand Down Expand Up @@ -138,7 +146,12 @@ def close(self) -> None:
def __enter__(self) -> IOHandles[AnyStr]:
return self

def __exit__(self, *args: Any) -> None:
def __exit__(
self,
exc_type: type[BaseException] | None,
exc_value: BaseException | None,
traceback: TracebackType | None,
) -> None:
self.close()


Expand Down
3 changes: 2 additions & 1 deletion pandas/io/parsers/readers.py
Original file line number Diff line number Diff line change
Expand Up @@ -79,6 +79,7 @@
HashableT,
IndexLabel,
ReadCsvBuffer,
Self,
StorageOptions,
)
_doc_read_csv_and_table = (
Expand Down Expand Up @@ -1776,7 +1777,7 @@ def get_chunk(self, size: int | None = None) -> DataFrame:
size = min(size, self.nrows - self._currow)
return self.read(nrows=size)

def __enter__(self) -> TextFileReader:
def __enter__(self) -> Self:
return self

def __exit__(
Expand Down
Loading