Skip to content

Commit cb86c29

Browse files
committed
pyupgrade: 3.9
Signed-off-by: Guillaume Andreu Sabater <[email protected]>
1 parent 92050ca commit cb86c29

File tree

103 files changed

+637
-819
lines changed

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

103 files changed

+637
-819
lines changed

.pre-commit-config.yaml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -41,7 +41,7 @@ repos:
4141
rev: v3.19.1
4242
hooks:
4343
- id: pyupgrade
44-
args: [--py38-plus, --keep-runtime-typing]
44+
args: [--py39-plus, --keep-runtime-typing]
4545

4646
- repo: https://github.com/pycqa/pylint
4747
rev: v3.2.7

docs/source/dataframe_models.md

Lines changed: 2 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -339,10 +339,8 @@ to python 3.6.
339339
✅ Good:
340340

341341
```{code-cell} python
342-
try:
343-
from typing import Annotated # python 3.9+
344-
except ImportError:
345-
from typing_extensions import Annotated
342+
from typing import Annotated
343+
346344
347345
class Schema(pa.DataFrameModel):
348346
col: Series[Annotated[pd.DatetimeTZDtype, "ns", "est"]]

docs/source/dtype_validation.md

Lines changed: 3 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -112,10 +112,8 @@ express this same type with the class-based API, we need to use an
112112
{py:class}`~typing.Annotated` type:
113113

114114
```{code-cell} python
115-
try:
116-
from typing import Annotated # python 3.9+
117-
except ImportError:
118-
from typing_extensions import Annotated
115+
from typing import Annotated
116+
119117
120118
class DateTimeModel(pa.DataFrameModel):
121119
dt: Series[Annotated[pd.DatetimeTZDtype, "ns", "UTC"]]
@@ -266,10 +264,7 @@ And when using class-based API, you must specify actual types (string aliases
266264
are not supported):
267265

268266
```{code-cell} python
269-
try:
270-
from typing import Annotated # python 3.9+
271-
except ImportError:
272-
from typing_extensions import Annotated
267+
from typing import Annotated
273268
274269
275270
class PyarrowModel(pa.DataFrameModel):

docs/source/polars.md

Lines changed: 2 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -484,10 +484,8 @@ schema = pa.DataFrameSchema(
484484
:::{tab-item} DataFrameModel (Annotated)
485485

486486
```{testcode} polars
487-
try:
488-
from typing import Annotated # python 3.9+
489-
except ImportError:
490-
from typing_extensions import Annotated
487+
from typing import Annotated
488+
491489
492490
class ModelWithAnnotated(pa.DataFrameModel):
493491
list_col: Annotated[pl.List, pl.Int64()]

noxfile.py

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,6 @@
1010
import shutil
1111
import sys
1212
import tempfile
13-
from typing import Dict, List
1413

1514
try:
1615
import tomllib
@@ -116,7 +115,7 @@ def _build_requires() -> Dict[str, Dict[str, str]]:
116115
return requires
117116

118117

119-
REQUIRES: Dict[str, Dict[str, str]] = _build_requires()
118+
REQUIRES: dict[str, dict[str, str]] = _build_requires()
120119

121120
CONDA_ARGS = [
122121
"--channel=conda-forge",

pandera/api/base/checks.py

Lines changed: 11 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -5,16 +5,13 @@
55
from typing import (
66
Any,
77
Callable,
8-
Dict,
9-
Iterable,
108
NamedTuple,
119
Optional,
12-
Tuple,
13-
Type,
1410
TypeVar,
1511
Union,
1612
no_type_check,
1713
)
14+
from collections.abc import Iterable
1815

1916
import pandas as pd
2017
from pandera.api.function_dispatch import Dispatcher
@@ -36,8 +33,8 @@ class CheckResult(NamedTuple):
3633
pd.core.groupby.generic.DataFrameGroupBy,
3734
]
3835

39-
SeriesCheckObj = Union[pd.Series, Dict[str, pd.Series]]
40-
DataFrameCheckObj = Union[pd.DataFrame, Dict[str, pd.DataFrame]]
36+
SeriesCheckObj = Union[pd.Series, dict[str, pd.Series]]
37+
DataFrameCheckObj = Union[pd.DataFrame, dict[str, pd.DataFrame]]
4138

4239

4340
_T = TypeVar("_T", bound="BaseCheck")
@@ -46,15 +43,15 @@ class CheckResult(NamedTuple):
4643
class MetaCheck(type): # pragma: no cover
4744
"""Check metaclass."""
4845

49-
BACKEND_REGISTRY: Dict[Tuple[Type, Type], Type[BaseCheckBackend]] = (
46+
BACKEND_REGISTRY: dict[tuple[type, type], type[BaseCheckBackend]] = (
5047
{}
5148
) # noqa
5249
"""Registry of check backends implemented for specific data objects."""
5350

54-
CHECK_FUNCTION_REGISTRY: Dict[str, Dispatcher] = {} # noqa
51+
CHECK_FUNCTION_REGISTRY: dict[str, Dispatcher] = {} # noqa
5552
"""Built-in check function registry."""
5653

57-
REGISTERED_CUSTOM_CHECKS: Dict[str, Callable] = {} # noqa
54+
REGISTERED_CUSTOM_CHECKS: dict[str, Callable] = {} # noqa
5855
"""User-defined custom checks."""
5956

6057
def __getattr__(cls, name: str) -> Any:
@@ -85,7 +82,7 @@ def __dir__(cls) -> Iterable[str]:
8582
# see https://mypy.readthedocs.io/en/stable/metaclasses.html#gotchas-and-limitations-of-metaclass-support
8683
# pylint: enable=line-too-long
8784
@no_type_check
88-
def __contains__(cls: Type[_T], item: Union[_T, str]) -> bool:
85+
def __contains__(cls: type[_T], item: Union[_T, str]) -> bool:
8986
"""Allow lookups for registered checks."""
9087
if isinstance(item, cls):
9188
name = item.name
@@ -102,7 +99,7 @@ def __init__(
10299
self,
103100
name: Optional[str] = None,
104101
error: Optional[str] = None,
105-
statistics: Optional[Dict[str, Any]] = None,
102+
statistics: Optional[dict[str, Any]] = None,
106103
):
107104
self.name = name
108105
self.error = error
@@ -136,7 +133,7 @@ def from_builtin_check_name(
136133
name: str,
137134
init_kwargs,
138135
error: Union[str, Callable],
139-
statistics: Optional[Dict[str, Any]] = None,
136+
statistics: Optional[dict[str, Any]] = None,
140137
**check_kwargs,
141138
):
142139
"""Create a Check object from a built-in check's name."""
@@ -156,13 +153,13 @@ def from_builtin_check_name(
156153
)
157154

158155
@classmethod
159-
def register_backend(cls, type_: Type, backend: Type[BaseCheckBackend]):
156+
def register_backend(cls, type_: type, backend: type[BaseCheckBackend]):
160157
"""Register a backend for the specified type."""
161158
if (cls, type_) not in cls.BACKEND_REGISTRY:
162159
cls.BACKEND_REGISTRY[(cls, type_)] = backend
163160

164161
@classmethod
165-
def get_backend(cls, check_obj: Any) -> Type[BaseCheckBackend]:
162+
def get_backend(cls, check_obj: Any) -> type[BaseCheckBackend]:
166163
"""Get the backend associated with the type of ``check_obj`` ."""
167164

168165
check_obj_cls = type(check_obj)

pandera/api/base/error_handler.py

Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22

33
from collections import defaultdict
44
from enum import Enum
5-
from typing import Any, Dict, List, Union
5+
from typing import Any, Union
66

77
from pandera.api.checks import Check
88
from pandera.config import ValidationDepth, get_config_context
@@ -28,8 +28,8 @@ def __init__(self, lazy: bool = True) -> None:
2828
Defaults to True.
2929
"""
3030
self._lazy = lazy
31-
self._collected_errors: List[Dict[str, Any]] = []
32-
self._schema_errors: List[SchemaError] = []
31+
self._collected_errors: list[dict[str, Any]] = []
32+
self._schema_errors: list[SchemaError] = []
3333
self._summarized_errors = defaultdict(lambda: defaultdict(list)) # type: ignore
3434

3535
@property
@@ -86,7 +86,7 @@ def collect_error(
8686

8787
def collect_errors(
8888
self,
89-
schema_errors: List[SchemaError],
89+
schema_errors: list[SchemaError],
9090
original_exc: Union[BaseException, None] = None,
9191
):
9292
"""Collect schema errors from a SchemaErrors exception.
@@ -104,19 +104,19 @@ def collect_errors(
104104
)
105105

106106
@property
107-
def collected_errors(self) -> List[Dict[str, Any]]:
107+
def collected_errors(self) -> list[dict[str, Any]]:
108108
"""Retrieve error objects collected during lazy validation."""
109109
return self._collected_errors
110110

111111
@collected_errors.setter
112-
def collected_errors(self, value: List[Dict[str, Any]]):
112+
def collected_errors(self, value: list[dict[str, Any]]):
113113
"""Set the list of collected errors."""
114114
if not isinstance(value, list):
115115
raise ValueError("collected_errors must be a list")
116116
self._collected_errors = value
117117

118118
@property
119-
def schema_errors(self) -> List[SchemaError]:
119+
def schema_errors(self) -> list[SchemaError]:
120120
"""Retrieve SchemaError objects collected during lazy validation."""
121121
return self._schema_errors
122122

pandera/api/base/model.py

Lines changed: 14 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -1,17 +1,8 @@
11
"""Base classes for model api."""
22

33
import os
4-
from typing import (
5-
Any,
6-
Dict,
7-
List,
8-
Mapping,
9-
Optional,
10-
Tuple,
11-
Type,
12-
TypeVar,
13-
Union,
14-
)
4+
from typing import Any, Optional, TypeVar, Union
5+
from collections.abc import Mapping
156

167
from pandera.api.base.model_components import BaseFieldInfo
178
from pandera.api.base.model_config import BaseModelConfig
@@ -34,24 +25,24 @@ def __str__(cls):
3425
class BaseModel(metaclass=MetaModel):
3526
"""Base class for a Data Object Model."""
3627

37-
Config: Type[BaseModelConfig] = BaseModelConfig
38-
__extras__: Optional[Dict[str, Any]] = None
28+
Config: type[BaseModelConfig] = BaseModelConfig
29+
__extras__: Optional[dict[str, Any]] = None
3930
__schema__: Optional[Any] = None
40-
__config__: Optional[Type[BaseModelConfig]] = None
31+
__config__: Optional[type[BaseModelConfig]] = None
4132

4233
#: Key according to `FieldInfo.name`
43-
__fields__: Mapping[str, Tuple[AnnotationInfo, BaseFieldInfo]] = {}
44-
__checks__: Dict[str, List[Check]] = {}
45-
__root_checks__: List[Check] = []
34+
__fields__: Mapping[str, tuple[AnnotationInfo, BaseFieldInfo]] = {}
35+
__checks__: dict[str, list[Check]] = {}
36+
__root_checks__: list[Check] = []
4637

4738
# This is syntantic sugar that delegates to the validate method
4839
def __new__(cls, *args, **kwargs) -> Any:
4940
raise NotImplementedError
5041

5142
def __class_getitem__(
52-
cls: Type[TBaseModel],
53-
params: Union[Type[Any], Tuple[Type[Any], ...]],
54-
) -> Type[TBaseModel]:
43+
cls: type[TBaseModel],
44+
params: Union[type[Any], tuple[type[Any], ...]],
45+
) -> type[TBaseModel]:
5546
"""
5647
Parameterize the class's generic arguments with the specified types.
5748
@@ -71,7 +62,7 @@ def to_yaml(cls, stream: Optional[os.PathLike] = None):
7162

7263
@classmethod
7364
def validate(
74-
cls: Type[TBaseModel],
65+
cls: type[TBaseModel],
7566
check_obj: Any,
7667
head: Optional[int] = None,
7768
tail: Optional[int] = None,
@@ -84,12 +75,12 @@ def validate(
8475
raise NotImplementedError
8576

8677
@classmethod
87-
def strategy(cls: Type[TBaseModel], *, size: Optional[int] = None):
78+
def strategy(cls: type[TBaseModel], *, size: Optional[int] = None):
8879
"""Create a data synthesis strategy."""
8980
raise NotImplementedError
9081

9182
@classmethod
92-
def example(cls: Type[TBaseModel], *, size: Optional[int] = None) -> Any:
83+
def example(cls: type[TBaseModel], *, size: Optional[int] = None) -> Any:
9384
"""Generate an example of this data model specification."""
9485
raise NotImplementedError
9586

pandera/api/base/model_components.py

Lines changed: 10 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -3,30 +3,27 @@
33
from typing import (
44
Any,
55
Callable,
6-
Dict,
7-
Iterable,
8-
List,
96
Optional,
10-
Type,
117
Union,
128
cast,
139
)
10+
from collections.abc import Iterable
1411

1512
from pandera.api.checks import Check
1613
from pandera.api.parsers import Parser
1714

18-
CheckArg = Union[Check, List[Check]]
19-
ParserArg = Union[Parser, List[Parser]]
15+
CheckArg = Union[Check, list[Check]]
16+
ParserArg = Union[Parser, list[Parser]]
2017
AnyCallable = Callable[..., Any]
2118

2219

23-
def to_checklist(checks: Optional[CheckArg]) -> List[Check]:
20+
def to_checklist(checks: Optional[CheckArg]) -> list[Check]:
2421
"""Convert value to list of checks."""
2522
checks = checks or []
2623
return [checks] if isinstance(checks, Check) else checks
2724

2825

29-
def to_parserlist(parsers: Optional[ParserArg]) -> List[Parser]:
26+
def to_parserlist(parsers: Optional[ParserArg]) -> list[Parser]:
3027
parsers = parsers or []
3128
return [parsers] if isinstance(parsers, Parser) else parsers
3229

@@ -64,7 +61,7 @@ def __init__(
6461
regex: bool = False,
6562
alias: Any = None,
6663
check_name: Optional[bool] = None,
67-
dtype_kwargs: Optional[Dict[str, Any]] = None,
64+
dtype_kwargs: Optional[dict[str, Any]] = None,
6865
title: Optional[str] = None,
6966
description: Optional[str] = None,
7067
default: Optional[Any] = None,
@@ -92,10 +89,10 @@ def name(self) -> str:
9289
return self.alias
9390
return self.original_name
9491

95-
def __set_name__(self, owner: Type, name: str) -> None:
92+
def __set_name__(self, owner: type, name: str) -> None:
9693
self.original_name = name
9794

98-
def __get__(self, instance: Any, owner: Type) -> str:
95+
def __get__(self, instance: Any, owner: type) -> str:
9996
return self.name
10097

10198
def __str__(self):
@@ -128,7 +125,7 @@ def __init__(self, check_fn: AnyCallable, **check_kwargs: Any):
128125
self.check_fn = check_fn
129126
self.check_kwargs = check_kwargs
130127

131-
def to_check(self, model_cls: Type) -> Check:
128+
def to_check(self, model_cls: type) -> Check:
132129
"""Create a Check from metadata."""
133130
name = self.check_kwargs.pop("name", None)
134131
if not name:
@@ -149,7 +146,7 @@ def __init__(self, parser_fn: AnyCallable, **parser_kwargs: Any) -> None:
149146
self.parser_fn = parser_fn
150147
self.parser_kwargs = parser_kwargs
151148

152-
def to_parser(self, model_cls: Type) -> Parser:
149+
def to_parser(self, model_cls: type) -> Parser:
153150
"""Create a Parser from metadata."""
154151
name = self.parser_kwargs.pop("name", None)
155152
if not name:

0 commit comments

Comments
 (0)