diff --git a/py-polars/polars/_typing.py b/py-polars/polars/_typing.py index 9a349bd6c943..1670b08aeb2f 100644 --- a/py-polars/polars/_typing.py +++ b/py-polars/polars/_typing.py @@ -4,11 +4,8 @@ from typing import ( TYPE_CHECKING, Any, - List, Literal, Protocol, - Tuple, - Type, TypedDict, TypeVar, Union, @@ -52,29 +49,29 @@ def __arrow_c_stream__(self, requested_schema: object | None = None) -> object: # Data types PolarsDataType: TypeAlias = Union["DataTypeClass", "DataType"] -PolarsTemporalType: TypeAlias = Union[Type["TemporalType"], "TemporalType"] -PolarsIntegerType: TypeAlias = Union[Type["IntegerType"], "IntegerType"] +PolarsTemporalType: TypeAlias = Union[type["TemporalType"], "TemporalType"] +PolarsIntegerType: TypeAlias = Union[type["IntegerType"], "IntegerType"] OneOrMoreDataTypes: TypeAlias = Union[PolarsDataType, Iterable[PolarsDataType]] PythonDataType: TypeAlias = Union[ - Type[int], - Type[float], - Type[bool], - Type[str], - Type["date"], - Type["time"], - Type["datetime"], - Type["timedelta"], - Type[List[Any]], - Type[Tuple[Any, ...]], - Type[bytes], - Type[object], - Type["Decimal"], - Type[None], + type[int], + type[float], + type[bool], + type[str], + type["date"], + type["time"], + type["datetime"], + type["timedelta"], + type[list[Any]], + type[tuple[Any, ...]], + type[bytes], + type[object], + type["Decimal"], + type[None], ] SchemaDefinition: TypeAlias = Union[ Mapping[str, Union[PolarsDataType, PythonDataType]], - Sequence[Union[str, Tuple[str, Union[PolarsDataType, PythonDataType, None]]]], + Sequence[Union[str, tuple[str, Union[PolarsDataType, PythonDataType, None]]]], ] SchemaDict: TypeAlias = Mapping[str, PolarsDataType] @@ -82,7 +79,7 @@ def __arrow_c_stream__(self, requested_schema: object | None = None) -> object: TemporalLiteral: TypeAlias = Union["date", "time", "datetime", "timedelta"] NonNestedLiteral: TypeAlias = Union[NumericLiteral, TemporalLiteral, str, bool, bytes] # Python literal types (can convert into a `lit` expression) -PythonLiteral: TypeAlias = Union[NonNestedLiteral, List[Any]] +PythonLiteral: TypeAlias = Union[NonNestedLiteral, list[Any]] # Inputs that can convert into a `col` expression IntoExprColumn: TypeAlias = Union["Expr", "Series", str] # Inputs that can convert into an expression @@ -201,7 +198,7 @@ def __arrow_c_stream__(self, requested_schema: object | None = None) -> object: # Excel IO ColumnFormatDict: TypeAlias = Mapping[ # dict of colname(s) or selector(s) to format string or dict - Union[ColumnNameOrSelector, Tuple[ColumnNameOrSelector, ...]], + Union[ColumnNameOrSelector, tuple[ColumnNameOrSelector, ...]], Union[str, Mapping[str, str]], ] ConditionalFormatDict: TypeAlias = Mapping[ @@ -211,12 +208,12 @@ def __arrow_c_stream__(self, requested_schema: object | None = None) -> object: ] ColumnTotalsDefinition: TypeAlias = Union[ # dict of colname(s) to str, a collection of str, or a boolean - Mapping[Union[ColumnNameOrSelector, Tuple[ColumnNameOrSelector]], str], + Mapping[Union[ColumnNameOrSelector, tuple[ColumnNameOrSelector]], str], Sequence[str], bool, ] ColumnWidthsDefinition: TypeAlias = Union[ - Mapping[ColumnNameOrSelector, Union[Tuple[str, ...], int]], int + Mapping[ColumnNameOrSelector, Union[tuple[str, ...], int]], int ] RowTotalsDefinition: TypeAlias = Union[ # dict of colname to str(s), a collection of str, or a boolean @@ -231,7 +228,7 @@ def __arrow_c_stream__(self, requested_schema: object | None = None) -> object: # typevars for core polars types PolarsType = TypeVar("PolarsType", "DataFrame", "LazyFrame", "Series", "Expr") FrameType = TypeVar("FrameType", "DataFrame", "LazyFrame") -BufferInfo: TypeAlias = Tuple[int, int, int] +BufferInfo: TypeAlias = tuple[int, int, int] # type alias for supported spreadsheet engines ExcelSpreadsheetEngine: TypeAlias = Literal["xlsx2csv", "openpyxl", "calamine"] diff --git a/py-polars/polars/_utils/async_.py b/py-polars/polars/_utils/async_.py index ac2f0b947ad5..966f28cecdb6 100644 --- a/py-polars/polars/_utils/async_.py +++ b/py-polars/polars/_utils/async_.py @@ -1,6 +1,6 @@ from __future__ import annotations -from collections.abc import Awaitable, Generator +from collections.abc import Awaitable from typing import TYPE_CHECKING, Any, Generic, TypeVar from polars._utils.wrap import wrap_df @@ -8,6 +8,7 @@ if TYPE_CHECKING: from asyncio.futures import Future + from collections.abc import Generator from polars.polars import PyDataFrame diff --git a/py-polars/polars/_utils/construction/dataframe.py b/py-polars/polars/_utils/construction/dataframe.py index 3be09d2af433..f174fbc736cf 100644 --- a/py-polars/polars/_utils/construction/dataframe.py +++ b/py-polars/polars/_utils/construction/dataframe.py @@ -1,7 +1,7 @@ from __future__ import annotations import contextlib -from collections.abc import Generator, Iterable, Mapping, MutableMapping, Sequence +from collections.abc import Generator, Mapping from datetime import date, datetime, time, timedelta from functools import singledispatch from itertools import islice, zip_longest @@ -59,6 +59,8 @@ from polars.polars import PyDataFrame if TYPE_CHECKING: + from collections.abc import Iterable, MutableMapping, Sequence + from polars import DataFrame, Expr, Series from polars._typing import ( Orientation, diff --git a/py-polars/polars/_utils/construction/series.py b/py-polars/polars/_utils/construction/series.py index 2b5590608002..121378b6d873 100644 --- a/py-polars/polars/_utils/construction/series.py +++ b/py-polars/polars/_utils/construction/series.py @@ -1,7 +1,7 @@ from __future__ import annotations import contextlib -from collections.abc import Generator, Iterable, Iterator, Sequence +from collections.abc import Generator, Iterator from datetime import date, datetime, time, timedelta from itertools import islice from typing import ( @@ -62,6 +62,8 @@ from polars.polars import PySeries if TYPE_CHECKING: + from collections.abc import Iterable, Sequence + from polars import DataFrame, Series from polars._typing import PolarsDataType from polars.dependencies import pandas as pd diff --git a/py-polars/polars/_utils/construction/utils.py b/py-polars/polars/_utils/construction/utils.py index 8c1e890d2c07..8b73728c92fc 100644 --- a/py-polars/polars/_utils/construction/utils.py +++ b/py-polars/polars/_utils/construction/utils.py @@ -1,13 +1,14 @@ from __future__ import annotations import sys -from collections.abc import Sequence from functools import lru_cache from typing import TYPE_CHECKING, Any, Callable, get_type_hints from polars.dependencies import _check_for_pydantic, pydantic if TYPE_CHECKING: + from collections.abc import Sequence + import pandas as pd PANDAS_SIMPLE_NUMPY_DTYPES = { diff --git a/py-polars/polars/_utils/convert.py b/py-polars/polars/_utils/convert.py index d6a5388a387d..cc23c77f73ac 100644 --- a/py-polars/polars/_utils/convert.py +++ b/py-polars/polars/_utils/convert.py @@ -1,6 +1,5 @@ from __future__ import annotations -from collections.abc import Sequence from datetime import datetime, time, timedelta, timezone from decimal import Context from functools import lru_cache @@ -26,6 +25,7 @@ from polars.dependencies import _ZONEINFO_AVAILABLE, zoneinfo if TYPE_CHECKING: + from collections.abc import Sequence from datetime import date, tzinfo from decimal import Decimal diff --git a/py-polars/polars/_utils/getitem.py b/py-polars/polars/_utils/getitem.py index 216502478e31..2ab09ba9af8c 100644 --- a/py-polars/polars/_utils/getitem.py +++ b/py-polars/polars/_utils/getitem.py @@ -1,6 +1,6 @@ from __future__ import annotations -from collections.abc import Iterable, Sequence +from collections.abc import Sequence from typing import TYPE_CHECKING, Any, NoReturn, overload import polars._reexport as pl @@ -23,6 +23,8 @@ from polars.meta.index_type import get_index_type if TYPE_CHECKING: + from collections.abc import Iterable + from polars import DataFrame, Series from polars._typing import ( MultiColSelector, diff --git a/py-polars/polars/_utils/udfs.py b/py-polars/polars/_utils/udfs.py index f490075c390c..0ff968ed59ec 100644 --- a/py-polars/polars/_utils/udfs.py +++ b/py-polars/polars/_utils/udfs.py @@ -10,14 +10,12 @@ import warnings from bisect import bisect_left from collections import defaultdict -from collections.abc import Iterator from dis import get_instructions from inspect import signature from itertools import count, zip_longest from pathlib import Path from typing import ( TYPE_CHECKING, - AbstractSet, Any, Callable, ClassVar, @@ -29,6 +27,8 @@ from polars._utils.various import re_escape if TYPE_CHECKING: + from collections.abc import Iterator + from collections.abc import Set as AbstractSet from dis import Instruction if sys.version_info >= (3, 10): diff --git a/py-polars/polars/convert/general.py b/py-polars/polars/convert/general.py index 6046fad41449..cee4b925e9e9 100644 --- a/py-polars/polars/convert/general.py +++ b/py-polars/polars/convert/general.py @@ -3,7 +3,7 @@ import io import itertools import re -from collections.abc import Iterable, Mapping, Sequence +from collections.abc import Iterable, Sequence from typing import TYPE_CHECKING, Any, overload import polars._reexport as pl @@ -25,6 +25,8 @@ from polars.exceptions import NoDataError if TYPE_CHECKING: + from collections.abc import Mapping + from polars import DataFrame, Series from polars._typing import Orientation, SchemaDefinition, SchemaDict from polars.dependencies import numpy as np diff --git a/py-polars/polars/convert/normalize.py b/py-polars/polars/convert/normalize.py index c90a8f4033e2..d6e24ddc8af5 100644 --- a/py-polars/polars/convert/normalize.py +++ b/py-polars/polars/convert/normalize.py @@ -4,7 +4,6 @@ import json from collections import abc -from collections.abc import Sequence from typing import TYPE_CHECKING, Any from polars._utils.unstable import unstable @@ -12,20 +11,13 @@ from polars.datatypes.constants import N_INFER_DEFAULT if TYPE_CHECKING: - from polars.schema import Schema - -import sys + from collections.abc import Sequence -if sys.version_info >= (3, 9): + from polars.schema import Schema - def _remove_prefix(text: str, prefix: str) -> str: - return text.removeprefix(prefix) -else: - def _remove_prefix(text: str, prefix: str) -> str: - if text.startswith(prefix): - return text[len(prefix) :] - return text +def _remove_prefix(text: str, prefix: str) -> str: + return text.removeprefix(prefix) def _simple_json_normalize( diff --git a/py-polars/polars/dataframe/_html.py b/py-polars/polars/dataframe/_html.py index e5c870b2d030..6f034eab0f41 100644 --- a/py-polars/polars/dataframe/_html.py +++ b/py-polars/polars/dataframe/_html.py @@ -3,13 +3,13 @@ from __future__ import annotations import os -from collections.abc import Iterable from textwrap import dedent from typing import TYPE_CHECKING from polars.dependencies import html if TYPE_CHECKING: + from collections.abc import Iterable from types import TracebackType from polars import DataFrame diff --git a/py-polars/polars/dataframe/frame.py b/py-polars/polars/dataframe/frame.py index 970641eb0e60..911d057a1f46 100644 --- a/py-polars/polars/dataframe/frame.py +++ b/py-polars/polars/dataframe/frame.py @@ -7,11 +7,8 @@ import random from collections import defaultdict from collections.abc import ( - Collection, Generator, Iterable, - Iterator, - Mapping, Sequence, Sized, ) @@ -117,6 +114,11 @@ if TYPE_CHECKING: import sys + from collections.abc import ( + Collection, + Iterator, + Mapping, + ) from datetime import timedelta from io import IOBase from typing import Literal @@ -3975,8 +3977,9 @@ def unpack_table_name(name: str) -> tuple[str | None, str | None, str]: else (connection, False) ) with ( - conn if can_close_conn else contextlib.nullcontext() - ), conn.cursor() as cursor: + conn if can_close_conn else contextlib.nullcontext(), + conn.cursor() as cursor, + ): catalog, db_schema, unpacked_table_name = unpack_table_name(table_name) n_rows: int if adbc_version >= (0, 7): diff --git a/py-polars/polars/dataframe/group_by.py b/py-polars/polars/dataframe/group_by.py index 13840a87686c..ce3cf054a7a0 100644 --- a/py-polars/polars/dataframe/group_by.py +++ b/py-polars/polars/dataframe/group_by.py @@ -1,6 +1,5 @@ from __future__ import annotations -from collections.abc import Iterable from typing import TYPE_CHECKING, Callable from polars import functions as F @@ -9,6 +8,7 @@ if TYPE_CHECKING: import sys + from collections.abc import Iterable from datetime import timedelta from polars import DataFrame diff --git a/py-polars/polars/dataframe/plotting.py b/py-polars/polars/dataframe/plotting.py index 75a2b92aa09e..11828cd54ebc 100644 --- a/py-polars/polars/dataframe/plotting.py +++ b/py-polars/polars/dataframe/plotting.py @@ -1,6 +1,6 @@ from __future__ import annotations -from typing import TYPE_CHECKING, Callable, Dict, Union +from typing import TYPE_CHECKING, Callable, Union from polars.dependencies import altair as alt @@ -27,7 +27,7 @@ from typing_extensions import Unpack Encoding: TypeAlias = Union[X, Y, Color, Order, Size, Tooltip] - Encodings: TypeAlias = Dict[str, Encoding] + Encodings: TypeAlias = dict[str, Encoding] def _maybe_extract_shorthand(encoding: Encoding) -> Encoding: diff --git a/py-polars/polars/datatypes/classes.py b/py-polars/polars/datatypes/classes.py index c9f47f203e7a..bb538b4f01e8 100644 --- a/py-polars/polars/datatypes/classes.py +++ b/py-polars/polars/datatypes/classes.py @@ -2,7 +2,7 @@ import contextlib from collections import OrderedDict -from collections.abc import Iterable, Iterator, Mapping, Sequence +from collections.abc import Mapping from datetime import timezone from inspect import isclass from typing import TYPE_CHECKING, Any @@ -15,6 +15,8 @@ from polars.polars import dtype_str_repr as _dtype_str_repr if TYPE_CHECKING: + from collections.abc import Iterable, Iterator, Sequence + from polars import Series from polars._typing import ( CategoricalOrdering, diff --git a/py-polars/polars/datatypes/constructor.py b/py-polars/polars/datatypes/constructor.py index 8a2a59a6622e..bcd77f9b54a0 100644 --- a/py-polars/polars/datatypes/constructor.py +++ b/py-polars/polars/datatypes/constructor.py @@ -1,7 +1,6 @@ from __future__ import annotations import functools -from collections.abc import Sequence from decimal import Decimal as PyDecimal from typing import TYPE_CHECKING, Any, Callable @@ -17,6 +16,8 @@ _DOCUMENTING = True if TYPE_CHECKING: + from collections.abc import Sequence + from polars._typing import PolarsDataType if not _DOCUMENTING: diff --git a/py-polars/polars/datatypes/group.py b/py-polars/polars/datatypes/group.py index e96fb01a5537..3332dd4a7e7f 100644 --- a/py-polars/polars/datatypes/group.py +++ b/py-polars/polars/datatypes/group.py @@ -1,6 +1,5 @@ from __future__ import annotations -from collections.abc import Iterable from typing import TYPE_CHECKING, Any from polars.datatypes.classes import ( @@ -28,6 +27,7 @@ if TYPE_CHECKING: import sys + from collections.abc import Iterable from polars._typing import ( PolarsDataType, diff --git a/py-polars/polars/dependencies.py b/py-polars/polars/dependencies.py index 74e716bb5b4b..9770c2035ce8 100644 --- a/py-polars/polars/dependencies.py +++ b/py-polars/polars/dependencies.py @@ -150,6 +150,7 @@ def _lazy_import(module_name: str) -> tuple[ModuleType, bool]: import json import pickle import subprocess + import zoneinfo import altair import deltalake @@ -162,11 +163,6 @@ def _lazy_import(module_name: str) -> tuple[ModuleType, bool]: import pyarrow import pydantic import pyiceberg - - if sys.version_info >= (3, 9): - import zoneinfo - else: - from backports import zoneinfo else: # infrequently-used builtins dataclasses, _ = _lazy_import("dataclasses") diff --git a/py-polars/polars/expr/datetime.py b/py-polars/polars/expr/datetime.py index b8c4e7e0a037..9aaed1352d09 100644 --- a/py-polars/polars/expr/datetime.py +++ b/py-polars/polars/expr/datetime.py @@ -1,7 +1,6 @@ from __future__ import annotations import datetime as dt -from collections.abc import Iterable from typing import TYPE_CHECKING import polars._reexport as pl @@ -14,6 +13,8 @@ from polars.datatypes import DTYPE_TEMPORAL_UNITS, Date, Int32 if TYPE_CHECKING: + from collections.abc import Iterable + from polars import Expr from polars._typing import ( Ambiguous, diff --git a/py-polars/polars/expr/expr.py b/py-polars/polars/expr/expr.py index c764c20a95f8..341f99876b21 100644 --- a/py-polars/polars/expr/expr.py +++ b/py-polars/polars/expr/expr.py @@ -4,7 +4,7 @@ import math import operator import warnings -from collections.abc import Collection, Iterable, Mapping, Sequence +from collections.abc import Collection, Mapping, Sequence from datetime import timedelta from functools import reduce from io import BytesIO, StringIO @@ -14,9 +14,7 @@ Any, Callable, ClassVar, - FrozenSet, NoReturn, - Set, TypeVar, ) @@ -66,6 +64,7 @@ if TYPE_CHECKING: import sys + from collections.abc import Iterable from io import IOBase from polars import DataFrame, LazyFrame, Series @@ -5768,7 +5767,7 @@ def is_in(self, other: Expr | Collection[Any] | Series) -> Expr: └───────────┴──────────────────┴──────────┘ """ if isinstance(other, Collection) and not isinstance(other, str): - if isinstance(other, (Set, FrozenSet)): + if isinstance(other, (set, frozenset)): other = list(other) other = F.lit(pl.Series(other))._pyexpr else: diff --git a/py-polars/polars/expr/struct.py b/py-polars/polars/expr/struct.py index 127f78eba057..57b8b6eddfb3 100644 --- a/py-polars/polars/expr/struct.py +++ b/py-polars/polars/expr/struct.py @@ -1,13 +1,14 @@ from __future__ import annotations import os -from collections.abc import Iterable, Sequence from typing import TYPE_CHECKING from polars._utils.parse import parse_into_list_of_expressions from polars._utils.wrap import wrap_expr if TYPE_CHECKING: + from collections.abc import Iterable, Sequence + from polars import Expr from polars._typing import IntoExpr diff --git a/py-polars/polars/expr/whenthen.py b/py-polars/polars/expr/whenthen.py index e063a75b85a2..65ad722f2cce 100644 --- a/py-polars/polars/expr/whenthen.py +++ b/py-polars/polars/expr/whenthen.py @@ -1,6 +1,5 @@ from __future__ import annotations -from collections.abc import Iterable from typing import TYPE_CHECKING, Any import polars.functions as F @@ -12,6 +11,8 @@ from polars.expr.expr import Expr if TYPE_CHECKING: + from collections.abc import Iterable + from polars._typing import IntoExpr from polars.polars import PyExpr diff --git a/py-polars/polars/functions/aggregation/horizontal.py b/py-polars/polars/functions/aggregation/horizontal.py index c3a49b8c2521..5406a77d287d 100644 --- a/py-polars/polars/functions/aggregation/horizontal.py +++ b/py-polars/polars/functions/aggregation/horizontal.py @@ -1,7 +1,6 @@ from __future__ import annotations import contextlib -from collections.abc import Iterable from typing import TYPE_CHECKING import polars.functions as F @@ -13,6 +12,8 @@ import polars.polars as plr if TYPE_CHECKING: + from collections.abc import Iterable + from polars import Expr from polars._typing import IntoExpr diff --git a/py-polars/polars/functions/as_datatype.py b/py-polars/polars/functions/as_datatype.py index 12c896524b09..30398daa01d9 100644 --- a/py-polars/polars/functions/as_datatype.py +++ b/py-polars/polars/functions/as_datatype.py @@ -1,7 +1,6 @@ from __future__ import annotations import contextlib -from collections.abc import Iterable from typing import TYPE_CHECKING, overload from polars import functions as F @@ -17,6 +16,7 @@ if TYPE_CHECKING: + from collections.abc import Iterable from typing import Literal from polars import Expr, Series diff --git a/py-polars/polars/functions/business.py b/py-polars/polars/functions/business.py index 6877e215ead3..2f92c40e987e 100644 --- a/py-polars/polars/functions/business.py +++ b/py-polars/polars/functions/business.py @@ -1,7 +1,6 @@ from __future__ import annotations import contextlib -from collections.abc import Iterable from datetime import date from typing import TYPE_CHECKING @@ -12,6 +11,8 @@ import polars.polars as plr if TYPE_CHECKING: + from collections.abc import Iterable + from polars import Expr from polars._typing import IntoExprColumn diff --git a/py-polars/polars/functions/eager.py b/py-polars/polars/functions/eager.py index a1b06ce36b17..e65f4aa949c0 100644 --- a/py-polars/polars/functions/eager.py +++ b/py-polars/polars/functions/eager.py @@ -1,7 +1,7 @@ from __future__ import annotations import contextlib -from collections.abc import Iterable, Sequence +from collections.abc import Sequence from functools import reduce from itertools import chain from typing import TYPE_CHECKING, get_args @@ -17,6 +17,8 @@ import polars.polars as plr if TYPE_CHECKING: + from collections.abc import Iterable + from polars import DataFrame, Expr, LazyFrame, Series from polars._typing import FrameType, JoinStrategy, PolarsType diff --git a/py-polars/polars/functions/lazy.py b/py-polars/polars/functions/lazy.py index 8f754aa04b2a..61cead9871d8 100644 --- a/py-polars/polars/functions/lazy.py +++ b/py-polars/polars/functions/lazy.py @@ -1,7 +1,7 @@ from __future__ import annotations import contextlib -from collections.abc import Iterable, Sequence +from collections.abc import Sequence from typing import TYPE_CHECKING, Any, Callable, overload import polars._reexport as pl @@ -21,7 +21,7 @@ import polars.polars as plr if TYPE_CHECKING: - from collections.abc import Awaitable, Collection + from collections.abc import Awaitable, Collection, Iterable from typing import Literal from polars import DataFrame, Expr, LazyFrame, Series diff --git a/py-polars/polars/functions/whenthen.py b/py-polars/polars/functions/whenthen.py index 1d2a7ae542ea..b9d9040cceb3 100644 --- a/py-polars/polars/functions/whenthen.py +++ b/py-polars/polars/functions/whenthen.py @@ -1,7 +1,6 @@ from __future__ import annotations import contextlib -from collections.abc import Iterable from typing import TYPE_CHECKING, Any import polars._reexport as pl @@ -11,6 +10,8 @@ import polars.polars as plr if TYPE_CHECKING: + from collections.abc import Iterable + from polars._typing import IntoExprColumn diff --git a/py-polars/polars/interchange/protocol.py b/py-polars/polars/interchange/protocol.py index 07adc753a014..4865baa35ae6 100644 --- a/py-polars/polars/interchange/protocol.py +++ b/py-polars/polars/interchange/protocol.py @@ -1,6 +1,5 @@ from __future__ import annotations -from collections.abc import Iterable, Sequence from enum import IntEnum from typing import ( TYPE_CHECKING, @@ -8,7 +7,6 @@ ClassVar, Literal, Protocol, - Tuple, TypedDict, ) @@ -16,6 +14,7 @@ if TYPE_CHECKING: import sys + from collections.abc import Iterable, Sequence from polars.interchange.buffer import PolarsBuffer from polars.interchange.column import PolarsColumn @@ -70,7 +69,7 @@ class DtypeKind(IntEnum): CATEGORICAL = 23 -Dtype: TypeAlias = Tuple[DtypeKind, int, str, str] # see Column.dtype +Dtype: TypeAlias = tuple[DtypeKind, int, str, str] # see Column.dtype class ColumnNullType(IntEnum): diff --git a/py-polars/polars/io/_utils.py b/py-polars/polars/io/_utils.py index b6056b36c13e..68d4b604d6a6 100644 --- a/py-polars/polars/io/_utils.py +++ b/py-polars/polars/io/_utils.py @@ -2,16 +2,19 @@ import glob import re -from collections.abc import Iterator, Sequence from contextlib import contextmanager from io import BytesIO, StringIO from pathlib import Path -from typing import IO, Any, ContextManager, overload +from typing import IO, TYPE_CHECKING, Any, overload from polars._utils.various import is_int_sequence, is_str_sequence, normalize_filepath from polars.dependencies import _FSSPEC_AVAILABLE, fsspec from polars.exceptions import NoDataError +if TYPE_CHECKING: + from collections.abc import Iterator, Sequence + from contextlib import AbstractContextManager as ContextManager + def parse_columns_arg( columns: Sequence[str] | Sequence[int] | str | int | None, diff --git a/py-polars/polars/io/csv/_utils.py b/py-polars/polars/io/csv/_utils.py index 9973a4b49daf..bdc910de5aa4 100644 --- a/py-polars/polars/io/csv/_utils.py +++ b/py-polars/polars/io/csv/_utils.py @@ -1,9 +1,10 @@ from __future__ import annotations -from collections.abc import Sequence from typing import TYPE_CHECKING if TYPE_CHECKING: + from collections.abc import Sequence + from polars import DataFrame diff --git a/py-polars/polars/io/csv/functions.py b/py-polars/polars/io/csv/functions.py index d019c86e889b..2e0562ceaee7 100644 --- a/py-polars/polars/io/csv/functions.py +++ b/py-polars/polars/io/csv/functions.py @@ -2,7 +2,7 @@ import contextlib import os -from collections.abc import Mapping, Sequence +from collections.abc import Sequence from io import BytesIO, StringIO from pathlib import Path from typing import IO, TYPE_CHECKING, Any, Callable @@ -31,6 +31,8 @@ from polars.polars import PyDataFrame, PyLazyFrame if TYPE_CHECKING: + from collections.abc import Mapping + from polars import DataFrame, LazyFrame from polars._typing import CsvEncoding, PolarsDataType, SchemaDict diff --git a/py-polars/polars/io/database/_cursor_proxies.py b/py-polars/polars/io/database/_cursor_proxies.py index c86b26c15aa6..d25abc3acce5 100644 --- a/py-polars/polars/io/database/_cursor_proxies.py +++ b/py-polars/polars/io/database/_cursor_proxies.py @@ -1,13 +1,12 @@ from __future__ import annotations -from collections.abc import Iterable from typing import TYPE_CHECKING, Any from polars.io.database._utils import _run_async if TYPE_CHECKING: import sys - from collections.abc import Coroutine + from collections.abc import Coroutine, Iterable import pyarrow as pa diff --git a/py-polars/polars/io/database/_executor.py b/py-polars/polars/io/database/_executor.py index 32b369e9aa62..278e3e8e0738 100644 --- a/py-polars/polars/io/database/_executor.py +++ b/py-polars/polars/io/database/_executor.py @@ -1,7 +1,7 @@ from __future__ import annotations import re -from collections.abc import Coroutine, Iterable, Sequence +from collections.abc import Coroutine, Sequence from contextlib import suppress from inspect import Parameter, signature from typing import TYPE_CHECKING, Any @@ -22,7 +22,7 @@ if TYPE_CHECKING: import sys - from collections.abc import Iterator + from collections.abc import Iterable, Iterator from types import TracebackType import pyarrow as pa diff --git a/py-polars/polars/io/database/functions.py b/py-polars/polars/io/database/functions.py index 30d43d37e49a..ac5dcaaac3e7 100644 --- a/py-polars/polars/io/database/functions.py +++ b/py-polars/polars/io/database/functions.py @@ -1,7 +1,6 @@ from __future__ import annotations import re -from collections.abc import Iterable from typing import TYPE_CHECKING, Any, Literal, overload from polars.datatypes import N_INFER_DEFAULT @@ -11,6 +10,7 @@ if TYPE_CHECKING: import sys + from collections.abc import Iterable if sys.version_info >= (3, 10): from typing import TypeAlias diff --git a/py-polars/polars/io/ipc/functions.py b/py-polars/polars/io/ipc/functions.py index 0a4e2ab83a50..6d64a560d094 100644 --- a/py-polars/polars/io/ipc/functions.py +++ b/py-polars/polars/io/ipc/functions.py @@ -2,7 +2,6 @@ import contextlib import os -from collections.abc import Sequence from pathlib import Path from typing import IO, TYPE_CHECKING, Any @@ -29,6 +28,8 @@ from polars.polars import read_ipc_schema as _read_ipc_schema if TYPE_CHECKING: + from collections.abc import Sequence + from polars import DataFrame, DataType, LazyFrame from polars._typing import SchemaDict diff --git a/py-polars/polars/io/spreadsheet/_utils.py b/py-polars/polars/io/spreadsheet/_utils.py index 173a1c744251..c535662fa33b 100644 --- a/py-polars/polars/io/spreadsheet/_utils.py +++ b/py-polars/polars/io/spreadsheet/_utils.py @@ -1,9 +1,11 @@ from __future__ import annotations -from collections.abc import Iterator from contextlib import contextmanager from pathlib import Path -from typing import Any, cast +from typing import TYPE_CHECKING, Any, cast + +if TYPE_CHECKING: + from collections.abc import Iterator @contextmanager diff --git a/py-polars/polars/io/spreadsheet/_write_utils.py b/py-polars/polars/io/spreadsheet/_write_utils.py index a8a627fa0880..8489b359a416 100644 --- a/py-polars/polars/io/spreadsheet/_write_utils.py +++ b/py-polars/polars/io/spreadsheet/_write_utils.py @@ -1,6 +1,6 @@ from __future__ import annotations -from collections.abc import Iterable, Sequence +from collections.abc import Sequence from io import BytesIO from pathlib import Path from typing import TYPE_CHECKING, Any, overload @@ -22,6 +22,7 @@ from polars.selectors import _expand_selector_dicts, _expand_selectors, numeric if TYPE_CHECKING: + from collections.abc import Iterable from typing import Literal from xlsxwriter import Workbook diff --git a/py-polars/polars/lazyframe/frame.py b/py-polars/polars/lazyframe/frame.py index 31802477078d..9e65f918d385 100644 --- a/py-polars/polars/lazyframe/frame.py +++ b/py-polars/polars/lazyframe/frame.py @@ -3,7 +3,7 @@ import contextlib import os import warnings -from collections.abc import Collection, Iterable, Mapping, Sequence +from collections.abc import Collection, Mapping from datetime import date, datetime, time, timedelta from functools import lru_cache, partial, reduce from io import BytesIO, StringIO @@ -88,7 +88,7 @@ if TYPE_CHECKING: import sys - from collections.abc import Awaitable + from collections.abc import Awaitable, Iterable, Sequence from io import IOBase from typing import Literal diff --git a/py-polars/polars/lazyframe/group_by.py b/py-polars/polars/lazyframe/group_by.py index 26f7e7a50a90..1143ea9c4831 100644 --- a/py-polars/polars/lazyframe/group_by.py +++ b/py-polars/polars/lazyframe/group_by.py @@ -1,6 +1,5 @@ from __future__ import annotations -from collections.abc import Iterable from typing import TYPE_CHECKING, Callable from polars import functions as F @@ -9,6 +8,8 @@ from polars._utils.wrap import wrap_ldf if TYPE_CHECKING: + from collections.abc import Iterable + from polars import DataFrame, LazyFrame from polars._typing import IntoExpr, RollingInterpolationMethod, SchemaDict from polars.polars import PyLazyGroupBy diff --git a/py-polars/polars/ml/torch.py b/py-polars/polars/ml/torch.py index 3b9838ee48d4..f92f2ab30fe9 100644 --- a/py-polars/polars/ml/torch.py +++ b/py-polars/polars/ml/torch.py @@ -1,7 +1,6 @@ # mypy: disable-error-code="unused-ignore" from __future__ import annotations -from collections.abc import Sequence from typing import TYPE_CHECKING from polars._utils.unstable import issue_unstable_warning @@ -11,6 +10,7 @@ if TYPE_CHECKING: import sys + from collections.abc import Sequence from torch import Tensor, memory_format diff --git a/py-polars/polars/plugins.py b/py-polars/polars/plugins.py index 832ce836751a..a501f8b5ed09 100644 --- a/py-polars/polars/plugins.py +++ b/py-polars/polars/plugins.py @@ -1,7 +1,6 @@ from __future__ import annotations import contextlib -from collections.abc import Iterable from functools import lru_cache from pathlib import Path from typing import TYPE_CHECKING, Any @@ -13,6 +12,8 @@ import polars.polars as plr if TYPE_CHECKING: + from collections.abc import Iterable + from polars import Expr from polars._typing import IntoExpr diff --git a/py-polars/polars/schema.py b/py-polars/polars/schema.py index cec526744cc2..72eb8b86d25e 100644 --- a/py-polars/polars/schema.py +++ b/py-polars/polars/schema.py @@ -1,7 +1,7 @@ from __future__ import annotations from collections import OrderedDict -from collections.abc import Iterable, Mapping +from collections.abc import Mapping from typing import TYPE_CHECKING from polars.datatypes import DataType @@ -10,6 +10,8 @@ BaseSchema = OrderedDict[str, DataType] if TYPE_CHECKING: + from collections.abc import Iterable + from polars._typing import PythonDataType diff --git a/py-polars/polars/series/array.py b/py-polars/polars/series/array.py index 4d4fcd2c1a69..877ec303fcfb 100644 --- a/py-polars/polars/series/array.py +++ b/py-polars/polars/series/array.py @@ -1,6 +1,5 @@ from __future__ import annotations -from collections.abc import Sequence from typing import TYPE_CHECKING, Callable from polars import functions as F @@ -8,6 +7,7 @@ from polars.series.utils import expr_dispatch if TYPE_CHECKING: + from collections.abc import Sequence from datetime import date, datetime, time from polars import Series diff --git a/py-polars/polars/series/datetime.py b/py-polars/polars/series/datetime.py index 4b640c5e1ae3..dcf65ff15312 100644 --- a/py-polars/polars/series/datetime.py +++ b/py-polars/polars/series/datetime.py @@ -1,6 +1,5 @@ from __future__ import annotations -from collections.abc import Iterable from typing import TYPE_CHECKING from polars._utils.deprecation import deprecate_function @@ -10,6 +9,7 @@ if TYPE_CHECKING: import datetime as dt + from collections.abc import Iterable from polars import Expr, Series from polars._typing import ( diff --git a/py-polars/polars/series/list.py b/py-polars/polars/series/list.py index 5975b5715b55..cf70f5225f56 100644 --- a/py-polars/polars/series/list.py +++ b/py-polars/polars/series/list.py @@ -1,6 +1,5 @@ from __future__ import annotations -from collections.abc import Sequence from typing import TYPE_CHECKING, Any, Callable from polars import functions as F @@ -8,6 +7,7 @@ from polars.series.utils import expr_dispatch if TYPE_CHECKING: + from collections.abc import Sequence from datetime import date, datetime, time from polars import Expr, Series diff --git a/py-polars/polars/series/series.py b/py-polars/polars/series/series.py index 9ec5b5f402de..c66d1f0a4abc 100644 --- a/py-polars/polars/series/series.py +++ b/py-polars/polars/series/series.py @@ -3,7 +3,7 @@ import contextlib import math import os -from collections.abc import Collection, Generator, Iterable, Mapping, Sequence +from collections.abc import Iterable, Sequence from contextlib import nullcontext from datetime import date, datetime, time, timedelta from decimal import Decimal as PyDecimal @@ -110,6 +110,7 @@ if TYPE_CHECKING: import sys + from collections.abc import Collection, Generator, Mapping import jax import numpy.typing as npt diff --git a/py-polars/polars/series/string.py b/py-polars/polars/series/string.py index 4ac977d89fa3..af9ce66850c4 100644 --- a/py-polars/polars/series/string.py +++ b/py-polars/polars/series/string.py @@ -1,6 +1,5 @@ from __future__ import annotations -from collections.abc import Mapping from typing import TYPE_CHECKING from polars._utils.deprecation import deprecate_function @@ -10,6 +9,8 @@ from polars.series.utils import expr_dispatch if TYPE_CHECKING: + from collections.abc import Mapping + from polars import Expr, Series from polars._typing import ( Ambiguous, diff --git a/py-polars/polars/series/struct.py b/py-polars/polars/series/struct.py index 8327da79b8a4..e8137a23be32 100644 --- a/py-polars/polars/series/struct.py +++ b/py-polars/polars/series/struct.py @@ -1,6 +1,5 @@ from __future__ import annotations -from collections.abc import Sequence from typing import TYPE_CHECKING from polars._utils.various import BUILDING_SPHINX_DOCS, sphinx_accessor @@ -9,6 +8,8 @@ from polars.series.utils import expr_dispatch if TYPE_CHECKING: + from collections.abc import Sequence + from polars import DataFrame, Series from polars.polars import PySeries elif BUILDING_SPHINX_DOCS: diff --git a/py-polars/polars/sql/context.py b/py-polars/polars/sql/context.py index f2396307d05a..c48290e547c4 100644 --- a/py-polars/polars/sql/context.py +++ b/py-polars/polars/sql/context.py @@ -2,7 +2,6 @@ import contextlib import re -from collections.abc import Collection, Mapping from typing import ( TYPE_CHECKING, Callable, @@ -29,6 +28,7 @@ if TYPE_CHECKING: import sys + from collections.abc import Collection, Mapping from types import TracebackType from typing import Any, Final, Literal diff --git a/py-polars/polars/testing/parametric/strategies/core.py b/py-polars/polars/testing/parametric/strategies/core.py index fbe48f377003..984853afe057 100644 --- a/py-polars/polars/testing/parametric/strategies/core.py +++ b/py-polars/polars/testing/parametric/strategies/core.py @@ -1,6 +1,6 @@ from __future__ import annotations -from collections.abc import Collection, Mapping, Sequence +from collections.abc import Mapping from dataclasses import dataclass from typing import TYPE_CHECKING, Any, overload @@ -17,6 +17,7 @@ from polars.testing.parametric.strategies.dtype import _instantiate_dtype, dtypes if TYPE_CHECKING: + from collections.abc import Collection, Sequence from typing import Literal from hypothesis.strategies import DrawFn, SearchStrategy diff --git a/py-polars/polars/testing/parametric/strategies/data.py b/py-polars/polars/testing/parametric/strategies/data.py index 0566876bc58f..f63b6d8a8945 100644 --- a/py-polars/polars/testing/parametric/strategies/data.py +++ b/py-polars/polars/testing/parametric/strategies/data.py @@ -3,7 +3,7 @@ from __future__ import annotations import decimal -from collections.abc import Mapping, Sequence +from collections.abc import Mapping from datetime import datetime, timedelta, timezone from typing import TYPE_CHECKING, Any, Literal @@ -61,6 +61,7 @@ ) if TYPE_CHECKING: + from collections.abc import Sequence from datetime import date, time from hypothesis.strategies import SearchStrategy diff --git a/py-polars/polars/testing/parametric/strategies/dtype.py b/py-polars/polars/testing/parametric/strategies/dtype.py index 75fe13e3052e..fff1ad58c726 100644 --- a/py-polars/polars/testing/parametric/strategies/dtype.py +++ b/py-polars/polars/testing/parametric/strategies/dtype.py @@ -1,6 +1,5 @@ from __future__ import annotations -from collections.abc import Collection, Sequence from typing import TYPE_CHECKING import hypothesis.strategies as st @@ -36,6 +35,8 @@ ) if TYPE_CHECKING: + from collections.abc import Collection, Sequence + from hypothesis.strategies import DrawFn, SearchStrategy from polars._typing import CategoricalOrdering, PolarsDataType, TimeUnit diff --git a/py-polars/tests/docs/run_doctest.py b/py-polars/tests/docs/run_doctest.py index dec347ea47ea..404070deae85 100644 --- a/py-polars/tests/docs/run_doctest.py +++ b/py-polars/tests/docs/run_doctest.py @@ -35,7 +35,6 @@ import sys import unittest import warnings -from collections.abc import Iterator from pathlib import Path from tempfile import TemporaryDirectory from typing import TYPE_CHECKING, Any @@ -43,6 +42,7 @@ import polars as pl if TYPE_CHECKING: + from collections.abc import Iterator from types import ModuleType diff --git a/py-polars/tests/unit/conftest.py b/py-polars/tests/unit/conftest.py index 436e3282255a..ead5bee2c265 100644 --- a/py-polars/tests/unit/conftest.py +++ b/py-polars/tests/unit/conftest.py @@ -6,8 +6,7 @@ import string import sys import tracemalloc -from collections.abc import Generator -from typing import Any, List, cast +from typing import TYPE_CHECKING, Any, cast import numpy as np import pytest @@ -15,6 +14,9 @@ import polars as pl from polars.testing.parametric import load_profile +if TYPE_CHECKING: + from collections.abc import Generator + load_profile( profile=os.environ.get("POLARS_HYPOTHESIS_PROFILE", "fast"), # type: ignore[arg-type] ) @@ -129,7 +131,7 @@ def str_ints_df() -> pl.DataFrame: @pytest.fixture(params=ISO8601_FORMATS_DATETIME) def iso8601_format_datetime(request: pytest.FixtureRequest) -> list[str]: - return cast(List[str], request.param) + return cast(list[str], request.param) ISO8601_TZ_AWARE_FORMATS_DATETIME = [] @@ -152,7 +154,7 @@ def iso8601_format_datetime(request: pytest.FixtureRequest) -> list[str]: @pytest.fixture(params=ISO8601_TZ_AWARE_FORMATS_DATETIME) def iso8601_tz_aware_format_datetime(request: pytest.FixtureRequest) -> list[str]: - return cast(List[str], request.param) + return cast(list[str], request.param) ISO8601_FORMATS_DATE = [] @@ -164,7 +166,7 @@ def iso8601_tz_aware_format_datetime(request: pytest.FixtureRequest) -> list[str @pytest.fixture(params=ISO8601_FORMATS_DATE) def iso8601_format_date(request: pytest.FixtureRequest) -> list[str]: - return cast(List[str], request.param) + return cast(list[str], request.param) class MemoryUsage: diff --git a/py-polars/tests/unit/constructors/test_constructors.py b/py-polars/tests/unit/constructors/test_constructors.py index fd4437859a46..d340433ddf10 100644 --- a/py-polars/tests/unit/constructors/test_constructors.py +++ b/py-polars/tests/unit/constructors/test_constructors.py @@ -4,7 +4,7 @@ from datetime import date, datetime, time, timedelta, timezone from decimal import Decimal from random import shuffle -from typing import TYPE_CHECKING, Any, List, Literal, NamedTuple +from typing import TYPE_CHECKING, Any, Literal, NamedTuple import numpy as np import pandas as pd @@ -280,7 +280,7 @@ class PageView(BaseModel): "top": 123 }] """ - adapter: TypeAdapter[Any] = TypeAdapter(List[PageView]) + adapter: TypeAdapter[Any] = TypeAdapter(list[PageView]) models = adapter.validate_json(data_json) result = pl.DataFrame(models) diff --git a/py-polars/tests/unit/constructors/test_dataframe.py b/py-polars/tests/unit/constructors/test_dataframe.py index 180b2de39e41..5e56630e7552 100644 --- a/py-polars/tests/unit/constructors/test_dataframe.py +++ b/py-polars/tests/unit/constructors/test_dataframe.py @@ -2,14 +2,17 @@ import sys from collections import OrderedDict -from collections.abc import Iterator, Mapping -from typing import Any +from collections.abc import Mapping +from typing import TYPE_CHECKING, Any import pytest import polars as pl from polars.exceptions import DataOrientationWarning, InvalidOperationError +if TYPE_CHECKING: + from collections.abc import Iterator + def test_df_mixed_dtypes_string() -> None: data = {"x": [["abc", 12, 34.5]], "y": [1]} diff --git a/py-polars/tests/unit/dataframe/test_df.py b/py-polars/tests/unit/dataframe/test_df.py index 9af77bf58c92..2389bef36c88 100644 --- a/py-polars/tests/unit/dataframe/test_df.py +++ b/py-polars/tests/unit/dataframe/test_df.py @@ -3,7 +3,6 @@ import sys import typing from collections import OrderedDict -from collections.abc import Iterator, Sequence from datetime import date, datetime, time, timedelta, timezone from decimal import Decimal from io import BytesIO @@ -33,6 +32,7 @@ from tests.unit.conftest import INTEGER_DTYPES if TYPE_CHECKING: + from collections.abc import Iterator, Sequence from zoneinfo import ZoneInfo from polars import Expr diff --git a/py-polars/tests/unit/datatypes/test_parse.py b/py-polars/tests/unit/datatypes/test_parse.py index c95763033b32..0979292e8e50 100644 --- a/py-polars/tests/unit/datatypes/test_parse.py +++ b/py-polars/tests/unit/datatypes/test_parse.py @@ -4,12 +4,9 @@ from typing import ( TYPE_CHECKING, Any, - Dict, ForwardRef, - List, NamedTuple, Optional, - Tuple, Union, ) @@ -63,9 +60,9 @@ def test_parse_py_type_into_dtype(input: Any, expected: PolarsDataType) -> None: @pytest.mark.parametrize( ("input", "expected"), [ - (List[int], pl.List(pl.Int64())), - (Tuple[str, ...], pl.List(pl.String())), - (Tuple[datetime, datetime], pl.List(pl.Datetime("us"))), + (list[int], pl.List(pl.Int64())), + (tuple[str, ...], pl.List(pl.String())), + (tuple[datetime, datetime], pl.List(pl.Datetime("us"))), ], ) def test_parse_generic_into_dtype(input: Any, expected: PolarsDataType) -> None: @@ -76,9 +73,9 @@ def test_parse_generic_into_dtype(input: Any, expected: PolarsDataType) -> None: @pytest.mark.parametrize( "input", [ - Dict[str, float], - Tuple[int, str], - Tuple[int, float, float], + dict[str, float], + tuple[int, str], + tuple[int, float, float], ], ) def test_parse_generic_into_dtype_invalid(input: Any) -> None: diff --git a/py-polars/tests/unit/io/cloud/test_aws.py b/py-polars/tests/unit/io/cloud/test_aws.py index 7b6625786611..6f2116421822 100644 --- a/py-polars/tests/unit/io/cloud/test_aws.py +++ b/py-polars/tests/unit/io/cloud/test_aws.py @@ -1,7 +1,6 @@ from __future__ import annotations import multiprocessing -from collections.abc import Iterator from typing import TYPE_CHECKING, Any, Callable import boto3 @@ -12,6 +11,7 @@ from polars.testing import assert_frame_equal if TYPE_CHECKING: + from collections.abc import Iterator from pathlib import Path pytestmark = [ diff --git a/py-polars/tests/unit/io/database/test_async.py b/py-polars/tests/unit/io/database/test_async.py index 0934c06249e4..3bdea8207d2c 100644 --- a/py-polars/tests/unit/io/database/test_async.py +++ b/py-polars/tests/unit/io/database/test_async.py @@ -1,7 +1,6 @@ from __future__ import annotations import asyncio -from collections.abc import Iterable from math import ceil from typing import TYPE_CHECKING, Any, overload @@ -14,6 +13,7 @@ from polars.testing import assert_frame_equal if TYPE_CHECKING: + from collections.abc import Iterable from pathlib import Path SURREAL_MOCK_DATA: list[dict[str, Any]] = [ diff --git a/py-polars/tests/unit/io/database/test_write.py b/py-polars/tests/unit/io/database/test_write.py index 9623e8475d4d..d7230a66222c 100644 --- a/py-polars/tests/unit/io/database/test_write.py +++ b/py-polars/tests/unit/io/database/test_write.py @@ -21,12 +21,7 @@ @pytest.mark.write_disk @pytest.mark.parametrize( ("engine", "uri_connection"), - [ - ("sqlalchemy", True), - ("sqlalchemy", False), - ("adbc", True), - ("adbc", False) - ], + [("sqlalchemy", True), ("sqlalchemy", False), ("adbc", True), ("adbc", False)], ) class TestWriteDatabase: """Database write tests that share common pytest/parametrize options.""" diff --git a/py-polars/tests/unit/io/test_spreadsheet.py b/py-polars/tests/unit/io/test_spreadsheet.py index 2953a35cc002..7483f371b51c 100644 --- a/py-polars/tests/unit/io/test_spreadsheet.py +++ b/py-polars/tests/unit/io/test_spreadsheet.py @@ -2,7 +2,6 @@ import warnings from collections import OrderedDict -from collections.abc import Sequence from datetime import date, datetime from io import BytesIO from pathlib import Path @@ -18,6 +17,8 @@ from tests.unit.conftest import FLOAT_DTYPES, NUMERIC_DTYPES if TYPE_CHECKING: + from collections.abc import Sequence + from polars._typing import ExcelSpreadsheetEngine, SelectorType pytestmark = pytest.mark.slow() diff --git a/py-polars/tests/unit/io/test_utils.py b/py-polars/tests/unit/io/test_utils.py index 967b9ebe3669..e115aec4f71f 100644 --- a/py-polars/tests/unit/io/test_utils.py +++ b/py-polars/tests/unit/io/test_utils.py @@ -1,11 +1,14 @@ from __future__ import annotations -from collections.abc import Sequence +from typing import TYPE_CHECKING import pytest from polars.io._utils import looks_like_url, parse_columns_arg, parse_row_index_args +if TYPE_CHECKING: + from collections.abc import Sequence + @pytest.mark.parametrize( ("columns", "expected"), diff --git a/py-polars/tests/unit/operations/map/test_map_elements.py b/py-polars/tests/unit/operations/map/test_map_elements.py index ce147be9ef27..0ef231bc8943 100644 --- a/py-polars/tests/unit/operations/map/test_map_elements.py +++ b/py-polars/tests/unit/operations/map/test_map_elements.py @@ -340,9 +340,10 @@ def test_map_elements_chunked_14390() -> None: def test_cabbage_strategy_14396() -> None: df = pl.DataFrame({"x": [1, 2, 3]}) - with pytest.raises( - ValueError, match="strategy 'cabbage' is not supported" - ), pytest.warns(PolarsInefficientMapWarning): + with ( + pytest.raises(ValueError, match="strategy 'cabbage' is not supported"), + pytest.warns(PolarsInefficientMapWarning), + ): df.select(pl.col("x").map_elements(lambda x: 2 * x, strategy="cabbage")) # type: ignore[arg-type] diff --git a/py-polars/tests/unit/operations/map/test_map_groups.py b/py-polars/tests/unit/operations/map/test_map_groups.py index b829c61130ba..772f4d088249 100644 --- a/py-polars/tests/unit/operations/map/test_map_groups.py +++ b/py-polars/tests/unit/operations/map/test_map_groups.py @@ -1,7 +1,6 @@ from __future__ import annotations -from collections.abc import Sequence -from typing import Any +from typing import TYPE_CHECKING, Any import numpy as np import pytest @@ -10,6 +9,9 @@ from polars.exceptions import ComputeError from polars.testing import assert_frame_equal +if TYPE_CHECKING: + from collections.abc import Sequence + def test_map_groups() -> None: df = pl.DataFrame( diff --git a/py-polars/tests/unit/operations/namespaces/temporal/test_add_business_days.py b/py-polars/tests/unit/operations/namespaces/temporal/test_add_business_days.py index 5fe78225670e..4d646e2bba49 100644 --- a/py-polars/tests/unit/operations/namespaces/temporal/test_add_business_days.py +++ b/py-polars/tests/unit/operations/namespaces/temporal/test_add_business_days.py @@ -1,7 +1,6 @@ from __future__ import annotations import datetime as dt -import sys from datetime import date, datetime, timedelta from typing import TYPE_CHECKING @@ -11,19 +10,13 @@ from hypothesis import assume, given import polars as pl -from polars.dependencies import _ZONEINFO_AVAILABLE from polars.exceptions import ComputeError, InvalidOperationError from polars.testing import assert_series_equal if TYPE_CHECKING: from polars._typing import Roll, TimeUnit -if sys.version_info >= (3, 9): - from zoneinfo import ZoneInfo -elif _ZONEINFO_AVAILABLE: - # Import from submodule due to typing issue with backports.zoneinfo package: - # https://github.com/pganssle/zoneinfo/issues/125 - from backports.zoneinfo._zoneinfo import ZoneInfo +from zoneinfo import ZoneInfo def test_add_business_days() -> None: diff --git a/py-polars/tests/unit/operations/namespaces/temporal/test_to_datetime.py b/py-polars/tests/unit/operations/namespaces/temporal/test_to_datetime.py index 5bb09a0f8d1c..f07106ee76ac 100644 --- a/py-polars/tests/unit/operations/namespaces/temporal/test_to_datetime.py +++ b/py-polars/tests/unit/operations/namespaces/temporal/test_to_datetime.py @@ -1,25 +1,17 @@ from __future__ import annotations -import sys from datetime import date, datetime from typing import TYPE_CHECKING +from zoneinfo import ZoneInfo import hypothesis.strategies as st import pytest from hypothesis import given import polars as pl -from polars.dependencies import _ZONEINFO_AVAILABLE from polars.exceptions import ComputeError, InvalidOperationError from polars.testing import assert_series_equal -if sys.version_info >= (3, 9): - from zoneinfo import ZoneInfo -elif _ZONEINFO_AVAILABLE: - # Import from submodule due to typing issue with backports.zoneinfo package: - # https://github.com/pganssle/zoneinfo/issues/125 - from backports.zoneinfo._zoneinfo import ZoneInfo - if TYPE_CHECKING: from hypothesis.strategies import DrawFn diff --git a/py-polars/tests/unit/operations/test_comparison.py b/py-polars/tests/unit/operations/test_comparison.py index 72771ff64eab..26f95e269339 100644 --- a/py-polars/tests/unit/operations/test_comparison.py +++ b/py-polars/tests/unit/operations/test_comparison.py @@ -2,7 +2,7 @@ import math from contextlib import nullcontext -from typing import TYPE_CHECKING, Any, ContextManager +from typing import TYPE_CHECKING, Any import pytest @@ -11,6 +11,8 @@ from polars.testing import assert_frame_equal if TYPE_CHECKING: + from contextlib import AbstractContextManager as ContextManager + from polars._typing import PolarsDataType diff --git a/py-polars/tests/unit/operations/test_cross_join.py b/py-polars/tests/unit/operations/test_cross_join.py index 94830371ed35..f424da5ab170 100644 --- a/py-polars/tests/unit/operations/test_cross_join.py +++ b/py-polars/tests/unit/operations/test_cross_join.py @@ -1,17 +1,8 @@ -import sys from datetime import datetime +from zoneinfo import ZoneInfo import pytest -from polars.dependencies import _ZONEINFO_AVAILABLE - -if sys.version_info >= (3, 9): - from zoneinfo import ZoneInfo -elif _ZONEINFO_AVAILABLE: - # Import from submodule due to typing issue with backports.zoneinfo package: - # https://github.com/pganssle/zoneinfo/issues/125 - from backports.zoneinfo._zoneinfo import ZoneInfo - import polars as pl diff --git a/py-polars/tests/unit/operations/test_ewm_by.py b/py-polars/tests/unit/operations/test_ewm_by.py index e804f6b6d5d8..8004303238d4 100644 --- a/py-polars/tests/unit/operations/test_ewm_by.py +++ b/py-polars/tests/unit/operations/test_ewm_by.py @@ -1,25 +1,18 @@ from __future__ import annotations -import sys from datetime import date, datetime, timedelta from typing import TYPE_CHECKING import pytest import polars as pl -from polars.dependencies import _ZONEINFO_AVAILABLE from polars.exceptions import InvalidOperationError from polars.testing import assert_frame_equal, assert_series_equal if TYPE_CHECKING: from polars._typing import PolarsIntegerType, TimeUnit -if sys.version_info >= (3, 9): - from zoneinfo import ZoneInfo -elif _ZONEINFO_AVAILABLE: - # Import from submodule due to typing issue with backports.zoneinfo package: - # https://github.com/pganssle/zoneinfo/issues/125 - from backports.zoneinfo._zoneinfo import ZoneInfo +from zoneinfo import ZoneInfo @pytest.mark.parametrize("sort", [True, False]) diff --git a/py-polars/tests/unit/operations/test_interpolate.py b/py-polars/tests/unit/operations/test_interpolate.py index e80d4102466c..bac0693205da 100644 --- a/py-polars/tests/unit/operations/test_interpolate.py +++ b/py-polars/tests/unit/operations/test_interpolate.py @@ -1,24 +1,17 @@ from __future__ import annotations -import sys from datetime import date, datetime, time, timedelta from typing import TYPE_CHECKING, Any import pytest import polars as pl -from polars.dependencies import _ZONEINFO_AVAILABLE from polars.testing import assert_frame_equal if TYPE_CHECKING: from polars._typing import PolarsDataType, PolarsTemporalType -if sys.version_info >= (3, 9): - from zoneinfo import ZoneInfo -elif _ZONEINFO_AVAILABLE: - # Import from submodule due to typing issue with backports.zoneinfo package: - # https://github.com/pganssle/zoneinfo/issues/125 - from backports.zoneinfo._zoneinfo import ZoneInfo +from zoneinfo import ZoneInfo @pytest.mark.parametrize( diff --git a/py-polars/tests/unit/series/test_series.py b/py-polars/tests/unit/series/test_series.py index dad4f28f352e..491890b5dc13 100644 --- a/py-polars/tests/unit/series/test_series.py +++ b/py-polars/tests/unit/series/test_series.py @@ -1,7 +1,6 @@ from __future__ import annotations import math -from collections.abc import Iterator from datetime import date, datetime, time, timedelta from typing import TYPE_CHECKING, Any, cast @@ -32,6 +31,7 @@ from tests.unit.utils.pycapsule_utils import PyCapsuleStreamHolder if TYPE_CHECKING: + from collections.abc import Iterator from zoneinfo import ZoneInfo from polars._typing import EpochTimeUnit, PolarsDataType, TimeUnit diff --git a/py-polars/tests/unit/sql/test_joins.py b/py-polars/tests/unit/sql/test_joins.py index 3a1e90bed1b4..43c00ed8b3d5 100644 --- a/py-polars/tests/unit/sql/test_joins.py +++ b/py-polars/tests/unit/sql/test_joins.py @@ -295,10 +295,13 @@ def test_join_misc_16255() -> None: ) def test_non_equi_joins(constraint: str) -> None: # no support (yet) for non equi-joins in polars joins - with pytest.raises( - SQLInterfaceError, - match=r"only equi-join constraints are supported", - ), pl.SQLContext({"tbl": pl.DataFrame({"a": [1, 2, 3], "b": [4, 3, 2]})}) as ctx: + with ( + pytest.raises( + SQLInterfaceError, + match=r"only equi-join constraints are supported", + ), + pl.SQLContext({"tbl": pl.DataFrame({"a": [1, 2, 3], "b": [4, 3, 2]})}) as ctx, + ): ctx.execute( f""" SELECT * @@ -310,12 +313,19 @@ def test_non_equi_joins(constraint: str) -> None: def test_implicit_joins() -> None: # no support for this yet; ensure we catch it - with pytest.raises( - SQLInterfaceError, - match=r"not currently supported .* use explicit JOIN syntax instead", - ), pl.SQLContext( - {"tbl": pl.DataFrame({"a": [1, 2, 3], "b": [4, 3, 2], "c": ["x", "y", "z"]})} - ) as ctx: + with ( + pytest.raises( + SQLInterfaceError, + match=r"not currently supported .* use explicit JOIN syntax instead", + ), + pl.SQLContext( + { + "tbl": pl.DataFrame( + {"a": [1, 2, 3], "b": [4, 3, 2], "c": ["x", "y", "z"]} + ) + } + ) as ctx, + ): ctx.execute( """ SELECT t1.* diff --git a/py-polars/tests/unit/test_config.py b/py-polars/tests/unit/test_config.py index aadbd8de7079..cd0491b5435f 100644 --- a/py-polars/tests/unit/test_config.py +++ b/py-polars/tests/unit/test_config.py @@ -1,9 +1,8 @@ from __future__ import annotations import os -from collections.abc import Iterator from pathlib import Path -from typing import Any +from typing import TYPE_CHECKING, Any import pytest @@ -12,6 +11,9 @@ from polars._utils.unstable import issue_unstable_warning from polars.config import _POLARS_CFG_ENV_VARS +if TYPE_CHECKING: + from collections.abc import Iterator + @pytest.fixture(autouse=True) def _environ() -> Iterator[None]: diff --git a/py-polars/tests/unit/test_format.py b/py-polars/tests/unit/test_format.py index f118c63e9cf3..44c754e4884b 100644 --- a/py-polars/tests/unit/test_format.py +++ b/py-polars/tests/unit/test_format.py @@ -1,7 +1,6 @@ from __future__ import annotations import string -from collections.abc import Iterator from decimal import Decimal as D from typing import TYPE_CHECKING, Any @@ -11,6 +10,8 @@ from polars.exceptions import InvalidOperationError if TYPE_CHECKING: + from collections.abc import Iterator + from polars._typing import PolarsDataType @@ -291,8 +292,9 @@ def test_fmt_float_full() -> None: def test_fmt_list_12188() -> None: # set max_items to 1 < 4(size of failed list) to touch the testing branch. - with pl.Config(fmt_table_cell_list_len=1), pytest.raises( - InvalidOperationError, match="from `i64` to `u8` failed" + with ( + pl.Config(fmt_table_cell_list_len=1), + pytest.raises(InvalidOperationError, match="from `i64` to `u8` failed"), ): pl.DataFrame( { diff --git a/py-polars/tests/unit/test_selectors.py b/py-polars/tests/unit/test_selectors.py index a5d573d10379..bf44ff87bac5 100644 --- a/py-polars/tests/unit/test_selectors.py +++ b/py-polars/tests/unit/test_selectors.py @@ -1,26 +1,18 @@ -import sys from collections import OrderedDict from datetime import datetime from typing import Any +from zoneinfo import ZoneInfo import pytest import polars as pl import polars.selectors as cs from polars._typing import SelectorType -from polars.dependencies import _ZONEINFO_AVAILABLE from polars.exceptions import ColumnNotFoundError, InvalidOperationError from polars.selectors import expand_selector, is_selector from polars.testing import assert_frame_equal from tests.unit.conftest import INTEGER_DTYPES, TEMPORAL_DTYPES -if sys.version_info >= (3, 9): - from zoneinfo import ZoneInfo -elif _ZONEINFO_AVAILABLE: - # Import from submodule due to typing issue with backports.zoneinfo package: - # https://github.com/pganssle/zoneinfo/issues/125 - from backports.zoneinfo._zoneinfo import ZoneInfo - def assert_repr_equals(item: Any, expected: str) -> None: """Assert that the repr of an item matches the expected string.""" diff --git a/py-polars/tests/unit/utils/test_utils.py b/py-polars/tests/unit/utils/test_utils.py index 853593e62ae0..96730c91434b 100644 --- a/py-polars/tests/unit/utils/test_utils.py +++ b/py-polars/tests/unit/utils/test_utils.py @@ -1,6 +1,5 @@ from __future__ import annotations -from collections.abc import Sequence from datetime import date, datetime, time, timedelta from typing import TYPE_CHECKING, Any @@ -26,6 +25,7 @@ ) if TYPE_CHECKING: + from collections.abc import Sequence from zoneinfo import ZoneInfo from polars._typing import TimeUnit