Skip to content

Commit

Permalink
chore(python): Enable additional ruff lint rule sets (#18721)
Browse files Browse the repository at this point in the history
  • Loading branch information
alexander-beedie committed Sep 13, 2024
1 parent 6c08041 commit 7232554
Show file tree
Hide file tree
Showing 81 changed files with 261 additions and 257 deletions.
2 changes: 1 addition & 1 deletion py-polars/docs/source/conf.py
Original file line number Diff line number Diff line change
Expand Up @@ -205,7 +205,7 @@ def linkcode_resolve(domain: str, info: dict[str, Any]) -> str | None:
# Accessing deprecated objects will generate noisy warnings
warnings.simplefilter("ignore", FutureWarning)
obj = getattr(obj, part)
except AttributeError:
except AttributeError: # noqa: PERF203
return None

try:
Expand Down
8 changes: 4 additions & 4 deletions py-polars/docs/source/reference/api.rst
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@ Examples
@pl.api.register_expr_namespace("greetings")
class Greetings:
def __init__(self, expr: pl.Expr):
def __init__(self, expr: pl.Expr) -> None:
self._expr = expr
def hello(self) -> pl.Expr:
Expand Down Expand Up @@ -80,7 +80,7 @@ Examples
@pl.api.register_dataframe_namespace("split")
class SplitFrame:
def __init__(self, df: pl.DataFrame):
def __init__(self, df: pl.DataFrame) -> None:
self._df = df
def by_alternate_rows(self) -> list[pl.DataFrame]:
Expand Down Expand Up @@ -112,7 +112,7 @@ Examples
@pl.api.register_lazyframe_namespace("types")
class DTypeOperations:
def __init__(self, ldf: pl.LazyFrame):
def __init__(self, ldf: pl.LazyFrame) -> None:
self._ldf = ldf
def upcast_integer_types(self) -> pl.LazyFrame:
Expand Down Expand Up @@ -145,7 +145,7 @@ Examples
@pl.api.register_series_namespace("math")
class MathShortcuts:
def __init__(self, s: pl.Series):
def __init__(self, s: pl.Series) -> None:
self._s = s
def square(self) -> pl.Series:
Expand Down
4 changes: 3 additions & 1 deletion py-polars/polars/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,8 @@

__register_startup_deps()

from typing import Any

from polars import api, exceptions, plugins, selectors
from polars._utils.polars_version import get_polars_version as _get_polars_version

Expand Down Expand Up @@ -380,7 +382,7 @@
]


def __getattr__(name: str): # type: ignore[no-untyped-def]
def __getattr__(name: str) -> Any:
# Deprecate re-export of exceptions at top-level
if name in dir(exceptions):
from polars._utils.deprecation import issue_deprecation_warning
Expand Down
2 changes: 1 addition & 1 deletion py-polars/polars/_utils/async_.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@


class _GeventDataFrameResult(Generic[T]):
__slots__ = ("_watcher", "_value", "_result")
__slots__ = ("_result", "_value", "_watcher")

def __init__(self) -> None:
if not _GEVENT_AVAILABLE:
Expand Down
4 changes: 2 additions & 2 deletions py-polars/polars/_utils/slice.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ class PolarsSlice:
is_unbounded: bool
obj: FrameOrSeries

def __init__(self, obj: FrameOrSeries):
def __init__(self, obj: FrameOrSeries) -> None:
self.obj = obj

@staticmethod
Expand Down Expand Up @@ -116,7 +116,7 @@ class LazyPolarsSlice:

obj: LazyFrame

def __init__(self, obj: LazyFrame):
def __init__(self, obj: LazyFrame) -> None:
self.obj = obj

def apply(self, s: slice) -> LazyFrame:
Expand Down
4 changes: 2 additions & 2 deletions py-polars/polars/_utils/udfs.py
Original file line number Diff line number Diff line change
Expand Up @@ -330,7 +330,7 @@ class BytecodeParser:
_map_target_name: str | None = None
_caller_variables: dict[str, Any] | None = None

def __init__(self, function: Callable[[Any], Any], map_target: MapTarget):
def __init__(self, function: Callable[[Any], Any], map_target: MapTarget) -> None:
"""
Initialize BytecodeParser instance and prepare to introspect UDFs.
Expand Down Expand Up @@ -745,7 +745,7 @@ def __init__(
instructions: Iterator[Instruction],
function: Callable[[Any], Any],
caller_variables: dict[str, Any] | None,
):
) -> None:
self._function = function
self._caller_variables = caller_variables
self._original_instructions = list(instructions)
Expand Down
5 changes: 2 additions & 3 deletions py-polars/polars/_utils/various.py
Original file line number Diff line number Diff line change
Expand Up @@ -128,9 +128,8 @@ def is_sequence(
val: object, *, include_series: bool = False
) -> TypeGuard[Sequence[Any]]:
"""Check whether the given input is a numpy array or python sequence."""
return (
(_check_for_numpy(val) and isinstance(val, np.ndarray))
or isinstance(val, (pl.Series, Sequence) if include_series else Sequence)
return (_check_for_numpy(val) and isinstance(val, np.ndarray)) or (
isinstance(val, (pl.Series, Sequence) if include_series else Sequence)
and not isinstance(val, str)
)

Expand Down
10 changes: 5 additions & 5 deletions py-polars/polars/api.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,8 +11,8 @@


__all__ = [
"register_expr_namespace",
"register_dataframe_namespace",
"register_expr_namespace",
"register_lazyframe_namespace",
"register_series_namespace",
]
Expand Down Expand Up @@ -84,7 +84,7 @@ def register_expr_namespace(name: str) -> Callable[[type[NS]], type[NS]]:
--------
>>> @pl.api.register_expr_namespace("pow_n")
... class PowersOfN:
... def __init__(self, expr: pl.Expr):
... def __init__(self, expr: pl.Expr) -> None:
... self._expr = expr
...
... def next(self, p: int) -> pl.Expr:
Expand Down Expand Up @@ -137,7 +137,7 @@ def register_dataframe_namespace(name: str) -> Callable[[type[NS]], type[NS]]:
--------
>>> @pl.api.register_dataframe_namespace("split")
... class SplitFrame:
... def __init__(self, df: pl.DataFrame):
... def __init__(self, df: pl.DataFrame) -> None:
... self._df = df
...
... def by_first_letter_of_column_names(self) -> list[pl.DataFrame]:
Expand Down Expand Up @@ -235,7 +235,7 @@ def register_lazyframe_namespace(name: str) -> Callable[[type[NS]], type[NS]]:
--------
>>> @pl.api.register_lazyframe_namespace("types")
... class DTypeOperations:
... def __init__(self, lf: pl.LazyFrame):
... def __init__(self, lf: pl.LazyFrame) -> None:
... self._lf = lf
...
... def split_by_column_dtypes(self) -> list[pl.LazyFrame]:
Expand Down Expand Up @@ -336,7 +336,7 @@ def register_series_namespace(name: str) -> Callable[[type[NS]], type[NS]]:
--------
>>> @pl.api.register_series_namespace("math")
... class MathShortcuts:
... def __init__(self, s: pl.Series):
... def __init__(self, s: pl.Series) -> None:
... self._s = s
...
... def square(self) -> pl.Series:
Expand Down
8 changes: 7 additions & 1 deletion py-polars/polars/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,12 @@
else:
from typing_extensions import TypeAlias

if sys.version_info >= (3, 11):
from typing import Self
else:
from typing_extensions import Self


__all__ = ["Config"]

TableFormatNames: TypeAlias = Literal[
Expand Down Expand Up @@ -160,7 +166,7 @@ def __init__(self, *, restore_defaults: bool = False, **options: Any) -> None:
raise AttributeError(msg)
getattr(self, opt)(value)

def __enter__(self) -> Config:
def __enter__(self) -> Self:
"""Support setting temporary Config options that are reset on scope exit."""
self._original_state = self._original_state or self.save()
return self
Expand Down
4 changes: 2 additions & 2 deletions py-polars/polars/dataframe/_html.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ def __init__(
elements: list[str],
tag: str,
attributes: dict[str, str] | None = None,
):
) -> None:
self.tag = tag
self.elements = elements
self.attributes = attributes
Expand Down Expand Up @@ -54,7 +54,7 @@ def __init__(
max_cols: int = 75,
max_rows: int = 40,
from_series: bool = False,
):
) -> None:
self.df = df
self.elements: list[str] = []
self.max_cols = max_cols
Expand Down
16 changes: 7 additions & 9 deletions py-polars/polars/dataframe/frame.py
Original file line number Diff line number Diff line change
Expand Up @@ -351,7 +351,7 @@ def __init__(
orient: Orientation | None = None,
infer_schema_length: int | None = N_INFER_DEFAULT,
nan_to_null: bool = False,
):
) -> None:
if data is None:
self._df = dict_to_pydf(
{}, schema=schema, schema_overrides=schema_overrides
Expand Down Expand Up @@ -1106,10 +1106,10 @@ def __bool__(self) -> NoReturn:
)
raise TypeError(msg)

def __eq__(self, other: Any) -> DataFrame: # type: ignore[override]
def __eq__(self, other: object) -> DataFrame: # type: ignore[override]
return self._comp(other, "eq")

def __ne__(self, other: Any) -> DataFrame: # type: ignore[override]
def __ne__(self, other: object) -> DataFrame: # type: ignore[override]
return self._comp(other, "neq")

def __gt__(self, other: Any) -> DataFrame:
Expand Down Expand Up @@ -3428,7 +3428,7 @@ def write_excel(
hidden_columns = ()
hidden_columns = _expand_selectors(df, hidden_columns)
if isinstance(column_widths, int):
column_widths = {column: column_widths for column in df.columns}
column_widths = dict.fromkeys(df.columns, column_widths)
else:
column_widths = _expand_selector_dicts( # type: ignore[assignment]
df, column_widths, expand_keys=True, expand_values=False
Expand Down Expand Up @@ -3740,10 +3740,8 @@ def write_parquet(
if compression is None:
compression = "uncompressed"
if isinstance(file, (str, Path)):
if (
partition_by is not None
or pyarrow_options is not None
and pyarrow_options.get("partition_cols")
if partition_by is not None or (
pyarrow_options is not None and pyarrow_options.get("partition_cols")
):
file = normalize_filepath(file, check_not_directory=False)
else:
Expand Down Expand Up @@ -5999,7 +5997,7 @@ def group_by(
│ c ┆ 3 ┆ 1 │
└─────┴─────┴─────┘
"""
for _key, value in named_by.items():
for value in named_by.values():
if not isinstance(value, (str, pl.Expr, pl.Series)):
msg = (
f"Expected Polars expression or object convertible to one, got {type(value)}.\n\n"
Expand Down
6 changes: 3 additions & 3 deletions py-polars/polars/dataframe/group_by.py
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ def __init__(
*by: IntoExpr | Iterable[IntoExpr],
maintain_order: bool,
**named_by: IntoExpr,
):
) -> None:
"""
Utility class for performing a group by operation over the given DataFrame.
Expand Down Expand Up @@ -772,7 +772,7 @@ def __init__(
offset: str | timedelta | None,
closed: ClosedInterval,
group_by: IntoExpr | Iterable[IntoExpr] | None,
):
) -> None:
period = parse_as_duration_string(period)
offset = parse_as_duration_string(offset)

Expand Down Expand Up @@ -909,7 +909,7 @@ def __init__(
label: Label,
group_by: IntoExpr | Iterable[IntoExpr] | None,
start_by: StartBy,
):
) -> None:
every = parse_as_duration_string(every)
period = parse_as_duration_string(period)
offset = parse_as_duration_string(offset)
Expand Down
18 changes: 9 additions & 9 deletions py-polars/polars/datatypes/classes.py
Original file line number Diff line number Diff line change
Expand Up @@ -325,7 +325,7 @@ def __init__(
self,
precision: int | None = None,
scale: int = 0,
):
) -> None:
# Issuing the warning on `__init__` does not trigger when the class is used
# without being instantiated, but it's better than nothing
from polars._utils.unstable import issue_unstable_warning
Expand Down Expand Up @@ -422,7 +422,7 @@ class Datetime(TemporalType):

def __init__(
self, time_unit: TimeUnit = "us", time_zone: str | timezone | None = None
):
) -> None:
if time_unit not in ("ms", "us", "ns"):
msg = (
"invalid `time_unit`"
Expand Down Expand Up @@ -475,7 +475,7 @@ class Duration(TemporalType):

time_unit: TimeUnit

def __init__(self, time_unit: TimeUnit = "us"):
def __init__(self, time_unit: TimeUnit = "us") -> None:
if time_unit not in ("ms", "us", "ns"):
msg = (
"invalid `time_unit`"
Expand Down Expand Up @@ -518,7 +518,7 @@ class Categorical(DataType):
def __init__(
self,
ordering: CategoricalOrdering | None = "physical",
):
) -> None:
self.ordering = ordering

def __repr__(self) -> str:
Expand Down Expand Up @@ -554,7 +554,7 @@ class Enum(DataType):

categories: Series

def __init__(self, categories: Series | Iterable[str]):
def __init__(self, categories: Series | Iterable[str]) -> None:
# Issuing the warning on `__init__` does not trigger when the class is used
# without being instantiated, but it's better than nothing
from polars._utils.unstable import issue_unstable_warning
Expand Down Expand Up @@ -654,7 +654,7 @@ class List(NestedType):

inner: PolarsDataType

def __init__(self, inner: PolarsDataType | PythonDataType):
def __init__(self, inner: PolarsDataType | PythonDataType) -> None:
self.inner = polars.datatypes.parse_into_dtype(inner)

def __eq__(self, other: PolarsDataType) -> bool: # type: ignore[override]
Expand Down Expand Up @@ -713,7 +713,7 @@ def __init__(
shape: int | tuple[int, ...] | None = None,
*,
width: int | None = None,
):
) -> None:
if width is not None:
from polars._utils.deprecation import issue_deprecation_warning

Expand Down Expand Up @@ -803,7 +803,7 @@ class Field:
name: str
dtype: PolarsDataType

def __init__(self, name: str, dtype: PolarsDataType):
def __init__(self, name: str, dtype: PolarsDataType) -> None:
self.name = name
self.dtype = polars.datatypes.parse_into_dtype(dtype)

Expand Down Expand Up @@ -858,7 +858,7 @@ class Struct(NestedType):

fields: list[Field]

def __init__(self, fields: Sequence[Field] | SchemaDict):
def __init__(self, fields: Sequence[Field] | SchemaDict) -> None:
if isinstance(fields, Mapping):
self.fields = [Field(name, dtype) for name, dtype in fields.items()]
else:
Expand Down
2 changes: 1 addition & 1 deletion py-polars/polars/datatypes/convert.py
Original file line number Diff line number Diff line change
Expand Up @@ -318,7 +318,7 @@ def numpy_char_code_to_dtype(dtype_char: str) -> PolarsDataType:
return Binary
try:
return DataTypeMappings.NUMPY_KIND_AND_ITEMSIZE_TO_DTYPE[
(dtype.kind, dtype.itemsize)
dtype.kind, dtype.itemsize
]
except KeyError: # pragma: no cover
msg = f"cannot parse numpy data type {dtype!r} into Polars data type"
Expand Down
Loading

0 comments on commit 7232554

Please sign in to comment.