Skip to content

STY: pyupgrade to 3.9 #54044

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 5 commits into from
Jul 10, 2023
Merged
Show file tree
Hide file tree
Changes from 3 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
7 changes: 2 additions & 5 deletions .pre-commit-config.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ repos:
rev: 23.3.0
hooks:
- id: black
- repo: https://github.com/charliermarsh/ruff-pre-commit
- repo: https://github.com/astral-sh/ruff-pre-commit
rev: v0.0.270
hooks:
- id: ruff
Expand Down Expand Up @@ -94,7 +94,7 @@ repos:
rev: v3.4.0
hooks:
- id: pyupgrade
args: [--py38-plus]
args: [--py39-plus]
- repo: https://github.com/pre-commit/pygrep-hooks
rev: v1.10.0
hooks:
Expand Down Expand Up @@ -179,9 +179,6 @@ repos:
|np\.bool[^_8`]
|np\.object[^_8`]

# imports from collections.abc instead of `from collections import abc`
|from\ collections\.abc\ import

# Numpy
|from\ numpy\ import\ random
|from\ numpy\.random\ import
Expand Down
9 changes: 1 addition & 8 deletions doc/source/conf.py
Original file line number Diff line number Diff line change
Expand Up @@ -586,14 +586,7 @@ class AccessorCallableDocumenter(AccessorLevelDocumenter, MethodDocumenter):
priority = 0.5

def format_name(self):
if sys.version_info < (3, 9):
# NOTE pyupgrade will remove this when we run it with --py39-plus
# so don't remove the unnecessary `else` statement below
from pandas.util._str_methods import removesuffix

return removesuffix(MethodDocumenter.format_name(self), ".__call__")
else:
return MethodDocumenter.format_name(self).removesuffix(".__call__")
return MethodDocumenter.format_name(self).removesuffix(".__call__")


class PandasAutosummary(Autosummary):
Expand Down
9 changes: 7 additions & 2 deletions pandas/_config/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -56,11 +56,10 @@
)
import re
from typing import (
TYPE_CHECKING,
Any,
Callable,
Generator,
Generic,
Iterable,
NamedTuple,
cast,
)
Expand All @@ -72,6 +71,12 @@
)
from pandas.util._exceptions import find_stack_level

if TYPE_CHECKING:
from collections.abc import (
Generator,
Iterable,
)


class DeprecatedOption(NamedTuple):
key: str
Expand Down
5 changes: 4 additions & 1 deletion pandas/_config/localization.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,10 +10,13 @@
import platform
import re
import subprocess
from typing import Generator
from typing import TYPE_CHECKING

from pandas._config.config import options

if TYPE_CHECKING:
from collections.abc import Generator


@contextmanager
def set_locale(
Expand Down
5 changes: 3 additions & 2 deletions pandas/_testing/__init__.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
from __future__ import annotations

import collections
from collections import Counter
from datetime import datetime
from decimal import Decimal
import operator
Expand All @@ -12,8 +13,6 @@
TYPE_CHECKING,
Callable,
ContextManager,
Counter,
Iterable,
cast,
)

Expand Down Expand Up @@ -109,6 +108,8 @@
from pandas.core.construction import extract_array

if TYPE_CHECKING:
from collections.abc import Iterable

from pandas._typing import (
Dtype,
Frequency,
Expand Down
14 changes: 9 additions & 5 deletions pandas/_testing/_warnings.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,14 +7,18 @@
import re
import sys
from typing import (
Generator,
TYPE_CHECKING,
Literal,
Sequence,
Type,
cast,
)
import warnings

if TYPE_CHECKING:
from collections.abc import (
Generator,
Sequence,
)


@contextmanager
def assert_produces_warning(
Expand Down Expand Up @@ -91,7 +95,7 @@ class for all warnings. To raise multiple types of exceptions,
yield w
finally:
if expected_warning:
expected_warning = cast(Type[Warning], expected_warning)
expected_warning = cast(type[Warning], expected_warning)
_assert_caught_expected_warning(
caught_warnings=w,
expected_warning=expected_warning,
Expand Down Expand Up @@ -195,7 +199,7 @@ def _is_unexpected_warning(
"""Check if the actual warning issued is unexpected."""
if actual_warning and not expected_warning:
return True
expected_warning = cast(Type[Warning], expected_warning)
expected_warning = cast(type[Warning], expected_warning)
return bool(not issubclass(actual_warning.category, expected_warning))


Expand Down
3 changes: 2 additions & 1 deletion pandas/_testing/contexts.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,6 @@
IO,
TYPE_CHECKING,
Any,
Generator,
)
import uuid

Expand All @@ -20,6 +19,8 @@
from pandas.io.common import get_handle

if TYPE_CHECKING:
from collections.abc import Generator

from pandas._typing import (
BaseBuffer,
CompressionOptions,
Expand Down
41 changes: 20 additions & 21 deletions pandas/_typing.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,11 @@
from __future__ import annotations

from collections.abc import (
Hashable,
Iterator,
Mapping,
Sequence,
)
from datetime import (
datetime,
timedelta,
Expand All @@ -11,16 +17,9 @@
TYPE_CHECKING,
Any,
Callable,
Dict,
Hashable,
Iterator,
List,
Literal,
Mapping,
Optional,
Protocol,
Sequence,
Tuple,
Type as type_t,
TypeVar,
Union,
Expand Down Expand Up @@ -111,7 +110,7 @@
# Cannot use `Sequence` because a string is a sequence, and we don't want to
# accept that. Could refine if https://github.com/python/typing/issues/256 is
# resolved to differentiate between Sequence[str] and str
ListLike = Union[AnyArrayLike, List, range]
ListLike = Union[AnyArrayLike, list, range]

# scalars

Expand Down Expand Up @@ -146,10 +145,10 @@
Axis = Union[AxisInt, Literal["index", "columns", "rows"]]
IndexLabel = Union[Hashable, Sequence[Hashable]]
Level = Hashable
Shape = Tuple[int, ...]
Suffixes = Tuple[Optional[str], Optional[str]]
Shape = tuple[int, ...]
Suffixes = tuple[Optional[str], Optional[str]]
Ordered = Optional[bool]
JSONSerializable = Optional[Union[PythonScalar, List, Dict]]
JSONSerializable = Optional[Union[PythonScalar, list, dict]]
Frequency = Union[str, "BaseOffset"]
Axes = ListLike

Expand All @@ -166,15 +165,15 @@
Dtype = Union["ExtensionDtype", NpDtype]
AstypeArg = Union["ExtensionDtype", "npt.DTypeLike"]
# DtypeArg specifies all allowable dtypes in a functions its dtype argument
DtypeArg = Union[Dtype, Dict[Hashable, Dtype]]
DtypeArg = Union[Dtype, dict[Hashable, Dtype]]
DtypeObj = Union[np.dtype, "ExtensionDtype"]

# converters
ConvertersArg = Dict[Hashable, Callable[[Dtype], Dtype]]
ConvertersArg = dict[Hashable, Callable[[Dtype], Dtype]]

# parse_dates
ParseDatesArg = Union[
bool, List[Hashable], List[List[Hashable]], Dict[Hashable, List[Hashable]]
bool, list[Hashable], list[list[Hashable]], dict[Hashable, list[Hashable]]
]

# For functions like rename that convert one label to another
Expand All @@ -195,10 +194,10 @@

# types of `func` kwarg for DataFrame.aggregate and Series.aggregate
AggFuncTypeBase = Union[Callable, str]
AggFuncTypeDict = Dict[Hashable, Union[AggFuncTypeBase, List[AggFuncTypeBase]]]
AggFuncTypeDict = dict[Hashable, Union[AggFuncTypeBase, list[AggFuncTypeBase]]]
AggFuncType = Union[
AggFuncTypeBase,
List[AggFuncTypeBase],
list[AggFuncTypeBase],
AggFuncTypeDict,
]
AggObjType = Union[
Expand Down Expand Up @@ -286,18 +285,18 @@ def closed(self) -> bool:
FilePath = Union[str, "PathLike[str]"]

# for arbitrary kwargs passed during reading/writing files
StorageOptions = Optional[Dict[str, Any]]
StorageOptions = Optional[dict[str, Any]]


# compression keywords and compression
CompressionDict = Dict[str, Any]
CompressionDict = dict[str, Any]
CompressionOptions = Optional[
Union[Literal["infer", "gzip", "bz2", "zip", "xz", "zstd", "tar"], CompressionDict]
]

# types in DataFrameFormatter
FormattersType = Union[
List[Callable], Tuple[Callable, ...], Mapping[Union[str, int], Callable]
list[Callable], tuple[Callable, ...], Mapping[Union[str, int], Callable]
]
ColspaceType = Mapping[Hashable, Union[str, int]]
FloatFormatType = Union[str, Callable, "EngFormatter"]
Expand Down Expand Up @@ -347,9 +346,9 @@ def closed(self) -> bool:
# https://bugs.python.org/issue41810
# Using List[int] here rather than Sequence[int] to disallow tuples.
ScalarIndexer = Union[int, np.integer]
SequenceIndexer = Union[slice, List[int], np.ndarray]
SequenceIndexer = Union[slice, list[int], np.ndarray]
PositionalIndexer = Union[ScalarIndexer, SequenceIndexer]
PositionalIndexerTuple = Tuple[PositionalIndexer, PositionalIndexer]
PositionalIndexerTuple = tuple[PositionalIndexer, PositionalIndexer]
PositionalIndexer2D = Union[PositionalIndexer, PositionalIndexerTuple]
if TYPE_CHECKING:
TakeIndexer = Union[Sequence[int], Sequence[np.integer], npt.NDArray[np.integer]]
Expand Down
9 changes: 3 additions & 6 deletions pandas/_version.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,10 +16,7 @@
import re
import subprocess
import sys
from typing import (
Callable,
Dict,
)
from typing import Callable


def get_keywords():
Expand Down Expand Up @@ -57,8 +54,8 @@ class NotThisMethod(Exception):
"""Exception raised if a method is not valid for the current scenario."""


LONG_VERSION_PY: Dict[str, str] = {}
HANDLERS: Dict[str, Dict[str, Callable]] = {}
LONG_VERSION_PY: dict[str, str] = {}
HANDLERS: dict[str, dict[str, Callable]] = {}


def register_vcs_handler(vcs, method): # decorator
Expand Down
5 changes: 4 additions & 1 deletion pandas/compat/pickle_compat.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
import copy
import io
import pickle as pkl
from typing import Generator
from typing import TYPE_CHECKING

import numpy as np

Expand All @@ -22,6 +22,9 @@
)
from pandas.core.internals import BlockManager

if TYPE_CHECKING:
from collections.abc import Generator


def load_reduce(self):
stack = self.stack
Expand Down
9 changes: 7 additions & 2 deletions pandas/conftest.py
Original file line number Diff line number Diff line change
Expand Up @@ -32,9 +32,8 @@
import os
from pathlib import Path
from typing import (
TYPE_CHECKING,
Callable,
Hashable,
Iterator,
)

from dateutil.tz import (
Expand Down Expand Up @@ -73,6 +72,12 @@
MultiIndex,
)

if TYPE_CHECKING:
from collections.abc import (
Hashable,
Iterator,
)

try:
import pyarrow as pa
except ImportError:
Expand Down
Loading