Skip to content

Commit 9947b29

Browse files
committed
mypy - use Optional & Union for python <3.10 compatibility
1 parent 8cff225 commit 9947b29

File tree

14 files changed

+57
-61
lines changed

14 files changed

+57
-61
lines changed

aiopenapi3/_types.py

Lines changed: 2 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,6 @@
11
from . import v20, v30, v31
22

3-
from typing import (
4-
TYPE_CHECKING,
5-
Dict,
6-
List,
7-
Sequence,
8-
Tuple,
9-
Union,
10-
TypeAlias,
11-
Type,
12-
)
3+
from typing import TYPE_CHECKING, Dict, List, Sequence, Tuple, Union, TypeAlias, Type, Optional
134

145
import yaml
156

@@ -23,7 +14,7 @@
2314
RequestFileParameter = Tuple[str, FileTypes]
2415
RequestFilesParameter = Sequence[RequestFileParameter]
2516

26-
JSON: TypeAlias = dict[str, "JSON"] | list["JSON"] | str | int | float | bool | None
17+
JSON: TypeAlias = Optional[Union[dict[str, "JSON"], list["JSON"], str, int, float, bool]]
2718
"""
2819
Define a JSON type
2920
https://github.com/python/typing/issues/182#issuecomment-1320974824

aiopenapi3/base.py

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -394,8 +394,8 @@ def _get_identity(self, prefix="XLS", name=None):
394394

395395
def set_type(
396396
self,
397-
names: List[str] | None = None,
398-
discriminators: Sequence[DiscriminatorBase] | None = None,
397+
names: Optional[List[str]] = None,
398+
discriminators: Optional[Sequence[DiscriminatorBase]] = None,
399399
extra: Optional["SchemaBase"] = None,
400400
) -> Type[BaseModel]:
401401
from .model import Model
@@ -417,8 +417,8 @@ def set_type(
417417

418418
def get_type(
419419
self,
420-
names: List[str] | None = None,
421-
discriminators: Sequence[DiscriminatorBase] | None = None,
420+
names: Optional[List[str]] = None,
421+
discriminators: Optional[Sequence[DiscriminatorBase]] = None,
422422
extra: Optional["SchemaBase"] = None,
423423
fwdref: bool = False,
424424
) -> Union[Type[BaseModel], ForwardRef]:
@@ -462,7 +462,7 @@ def model(self, data: "JSON") -> Union[BaseModel, List[BaseModel]]:
462462

463463

464464
class OperationBase:
465-
# parameters: Optional[List[ParameterBase | ReferenceBase]]
465+
# parameters: Optional[List[Union[ParameterBase, ReferenceBase]]]
466466
parameters: List[Any]
467467

468468
def _validate_path_parameters(self, pi_: "PathItemBase", path_: str, loc: Tuple[Any, str]):

aiopenapi3/cli.py

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,6 @@
1212
import tracemalloc
1313
import linecache
1414
import logging
15-
from typing import Callable
1615

1716
import jmespath
1817
import yaml
@@ -34,8 +33,11 @@
3433
from .loader import ChainLoader, RedirectLoader, WebLoader
3534
import aiopenapi3.loader
3635

36+
from .log import init
3737

38-
log: Callable[[...], None] | None = None
38+
init()
39+
40+
# log: Callable[..., None] | None = None
3941

4042

4143
def loader_prepare(args, session_factory):
@@ -62,7 +64,7 @@ def plugins_load(baseurl, plugins: List[str]) -> List[aiopenapi3.plugin.Plugin]:
6264
raise ValueError("importlib")
6365
if (module := importlib.util.module_from_spec(spec)) is None:
6466
raise ValueError("importlib")
65-
assert spec and module
67+
assert spec and spec.loader and module
6668
spec.loader.exec_module(module)
6769
for c in clsp:
6870
plugin = getattr(module, c)

aiopenapi3/loader.py

Lines changed: 8 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22
import json
33
import logging
44
import typing
5-
5+
from typing import Optional
66
import yaml
77
import httpx
88
import yarl
@@ -112,7 +112,7 @@ def __init__(self, yload: "YAMLLoaderType" = YAML12Loader):
112112
self.yload = yload
113113

114114
@abc.abstractmethod
115-
def load(self, plugins: Plugins, url: yarl.URL, codec: str | None = None):
115+
def load(self, plugins: Plugins, url: yarl.URL, codec: Optional[str] = None):
116116
"""
117117
load and decode description document
118118
@@ -124,7 +124,7 @@ def load(self, plugins: Plugins, url: yarl.URL, codec: str | None = None):
124124
raise NotImplementedError("load")
125125

126126
@classmethod
127-
def decode(cls, data: bytes, codec: str | None) -> str:
127+
def decode(cls, data: bytes, codec: Optional[str]) -> str:
128128
"""
129129
decode bytes to ascii or utf-8
130130
@@ -196,7 +196,7 @@ class NullLoader(Loader):
196196
Loader does not load anything
197197
"""
198198

199-
def load(self, plugins: Plugins, url: yarl.URL, codec: str | None = None):
199+
def load(self, plugins: Plugins, url: yarl.URL, codec: Optional[str] = None):
200200
raise NotImplementedError("load")
201201

202202

@@ -211,7 +211,7 @@ def __init__(self, baseurl: yarl.URL, session_factory=httpx.Client, yload: "YAML
211211
self.baseurl: yarl.URL = baseurl
212212
self.session_factory = session_factory
213213

214-
def load(self, plugins: Plugins, url: yarl.URL, codec: str | None = None) -> "JSON":
214+
def load(self, plugins: Plugins, url: yarl.URL, codec: Optional[str] = None) -> "JSON":
215215
url = self.baseurl.join(url)
216216
with self.session_factory() as session:
217217
data = session.get(str(url))
@@ -239,7 +239,7 @@ def __init__(self, base: Path, yload: "YAMLLoaderType" = YAML12Loader):
239239
assert isinstance(base, Path)
240240
self.base = base
241241

242-
def load(self, plugins: Plugins, url: yarl.URL, codec: str | None = None):
242+
def load(self, plugins: Plugins, url: yarl.URL, codec: Optional[str] = None):
243243
assert isinstance(url, yarl.URL)
244244
assert plugins
245245
file = Path(url.path)
@@ -262,7 +262,7 @@ class RedirectLoader(FileSystemLoader):
262262
everything but the "name" is stripped of the url
263263
"""
264264

265-
def load(self, plugins: "Plugins", url: yarl.URL, codec: str | None = None):
265+
def load(self, plugins: "Plugins", url: yarl.URL, codec: Optional[str] = None):
266266
return super().load(plugins, yarl.URL(url.name), codec)
267267

268268

@@ -280,7 +280,7 @@ def __init__(self, *loaders, yload: "YAMLLoaderType" = YAML12Loader):
280280
Loader.__init__(self, yload)
281281
self.loaders = loaders
282282

283-
def load(self, plugins: "Plugins", url: yarl.URL, codec: str | None = None):
283+
def load(self, plugins: "Plugins", url: yarl.URL, codec: Optional[str] = None):
284284
log.debug(f"load {url}")
285285
errors = []
286286
for i in self.loaders:

aiopenapi3/log.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,14 @@
11
import sys
22
import logging.config
33
import os
4-
from typing import List, Dict, Any
4+
from typing import List, Dict, Any, Optional
55

66
if sys.version_info >= (3, 9):
77
from pathlib import Path
88
else:
99
from pathlib3x import Path
1010

11-
handlers: List[str] | None = None
11+
handlers: Optional[List[str]] = None
1212

1313

1414
def init(force: bool = False) -> None:

aiopenapi3/model.py

Lines changed: 5 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,3 @@
1-
from __future__ import annotations
2-
31
import collections
42
import dataclasses
53
import logging
@@ -114,9 +112,9 @@ class Model: # (BaseModel):
114112
def from_schema(
115113
cls,
116114
schema: "SchemaType",
117-
schemanames: List[str] | None = None,
118-
discriminators: List["DiscriminatorType"] | None = None,
119-
extra: "SchemaType" | None = None,
115+
schemanames: Optional[List[str]] = None,
116+
discriminators: Optional[List["DiscriminatorType"]] = None,
117+
extra: Optional["SchemaType"] = None,
120118
) -> Type[BaseModel]:
121119
if schemanames is None:
122120
schemanames = []
@@ -322,7 +320,7 @@ def configof(schema: "SchemaType"):
322320

323321
@staticmethod
324322
def typeof(
325-
schema: Optional[Union["SchemaType", "ReferenceType"]], _type: str | None = None, fwdref: bool = False
323+
schema: Optional[Union["SchemaType", "ReferenceType"]], _type: Optional[str] = None, fwdref: bool = False
326324
) -> Type:
327325
if schema is None:
328326
return BaseModel
@@ -517,7 +515,7 @@ def is_type(schema: "SchemaType", type_) -> bool:
517515
return isinstance(schema.type, str) and schema.type == type_ or Model.or_type(schema, type_, l=None)
518516

519517
@staticmethod
520-
def or_type(schema: "SchemaType", type_: str, l: int | None = 2) -> bool:
518+
def or_type(schema: "SchemaType", type_: str, l: Optional[int] = 2) -> bool:
521519
return isinstance((t := schema.type), list) and (l is None or len(t) == l) and type_ in t
522520

523521
@staticmethod

aiopenapi3/openapi.py

Lines changed: 13 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -87,8 +87,8 @@ def load_sync(
8787
cls,
8888
url,
8989
session_factory: Callable[..., httpx.Client] = httpx.Client,
90-
loader: Loader | None = None,
91-
plugins: List[Plugin] | None = None,
90+
loader: Optional[Loader] = None,
91+
plugins: Optional[List[Plugin]] = None,
9292
use_operation_tags: bool = False,
9393
) -> "OpenAPI":
9494
"""
@@ -110,8 +110,8 @@ async def load_async(
110110
cls,
111111
url: str,
112112
session_factory: Callable[..., httpx.AsyncClient] = httpx.AsyncClient,
113-
loader: Loader | None = None,
114-
plugins: List[Plugin] | None = None,
113+
loader: Optional[Loader] = None,
114+
plugins: Optional[List[Plugin]] = None,
115115
use_operation_tags: bool = False,
116116
) -> "OpenAPI":
117117
"""
@@ -139,8 +139,8 @@ def load_file(
139139
url: str,
140140
path: Union[str, pathlib.Path, yarl.URL],
141141
session_factory: Callable[..., Union[httpx.AsyncClient, httpx.Client]] = httpx.AsyncClient,
142-
loader: Loader | None = None,
143-
plugins: List[Plugin] | None = None,
142+
loader: Optional[Loader] = None,
143+
plugins: Optional[List[Plugin]] = None,
144144
use_operation_tags: bool = False,
145145
) -> "OpenAPI":
146146
"""
@@ -166,8 +166,8 @@ def loads(
166166
url: str,
167167
data: str,
168168
session_factory: Callable[..., Union[httpx.AsyncClient, httpx.Client]] = httpx.AsyncClient,
169-
loader: Loader | None = None,
170-
plugins: List[Plugin] | None = None,
169+
loader: Optional[Loader] = None,
170+
plugins: Optional[List[Plugin]] = None,
171171
use_operation_tags: bool = False,
172172
) -> "OpenAPI":
173173
"""
@@ -213,8 +213,8 @@ def __init__(
213213
url: str,
214214
document: "JSON",
215215
session_factory: Callable[..., Union[httpx.Client, httpx.AsyncClient]] = httpx.AsyncClient,
216-
loader: Loader | None = None,
217-
plugins: List[Plugin] | None = None,
216+
loader: Optional[Loader] = None,
217+
plugins: Optional[List[Plugin]] = None,
218218
use_operation_tags: bool = True,
219219
) -> None:
220220
"""
@@ -233,7 +233,7 @@ def __init__(
233233

234234
self._session_factory: Callable[..., Union[httpx.Client, httpx.AsyncClient]] = session_factory
235235

236-
self.loader: Loader | None = loader
236+
self.loader: Optional[Loader] = loader
237237
"""
238238
Loader - loading referenced documents
239239
"""
@@ -722,7 +722,7 @@ def __copy__(self) -> "OpenAPI":
722722
api.loader = self.loader
723723
return api
724724

725-
def clone(self, baseurl: yarl.URL | None = None) -> "OpenAPI":
725+
def clone(self, baseurl: Optional[yarl.URL] = None) -> "OpenAPI":
726726
"""
727727
shallwo copy the api object
728728
optional set a base url
@@ -735,7 +735,7 @@ def clone(self, baseurl: yarl.URL | None = None) -> "OpenAPI":
735735
return api
736736

737737
@staticmethod
738-
def cache_load(path: pathlib.Path, plugins: List[Plugin] | None = None, session_factory=None) -> "OpenAPI":
738+
def cache_load(path: pathlib.Path, plugins: Optional[List[Plugin]] = None, session_factory=None) -> "OpenAPI":
739739
"""
740740
read a pickle api object from path and init the schema types
741741

aiopenapi3/plugin.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -49,9 +49,9 @@ class Init(Plugin):
4949
class Context:
5050
initialized: Optional["OpenAPI"] = None
5151
"""available in :func:`~aiopenapi3.plugin.Init.initialized`"""
52-
schemas: Dict[str, "SchemaBase"] | None = None
52+
schemas: Optional[Dict[str, "SchemaBase"]] = None
5353
"""available in :func:`~aiopenapi3.plugin.Init.schemas`"""
54-
paths: Dict[str, "PathItemBase"] | None = None
54+
paths: Optional[Dict[str, "PathItemBase"]] = None
5555
"""available in :func:`~aiopenapi3.plugin.Init.paths`"""
5656

5757
def schemas(self, ctx: "Init.Context") -> "Init.Context": # pragma: no cover
@@ -197,7 +197,7 @@ def __init__(self, plugins: List[Plugin]):
197197
self._message = self._get_domain("message", plugins)
198198

199199
def _get_domain(self, name: str, plugins: List[Plugin]) -> "Domain":
200-
domain: Type[Plugin] | None
200+
domain: Optional[Type[Plugin]]
201201
if (domain := self._domains.get(name)) is None:
202202
raise ValueError(name) # noqa
203203

aiopenapi3/request.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@
1010

1111
from aiopenapi3.errors import ContentLengthExceededError
1212

13+
1314
try:
1415
from contextlib import aclosing
1516
except: # <= Python 3.10
@@ -48,7 +49,7 @@ async def aclosing(thing):
4849

4950

5051
class RequestParameter:
51-
def __init__(self, url: yarl.URL | str):
52+
def __init__(self, url: Union[yarl.URL, str]):
5253
self.url: str = str(url)
5354
self.auth: Optional["AuthTypes"] = None
5455
self.cookies: Dict[str, str] = {}

aiopenapi3/v20/glue.py

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -283,7 +283,9 @@ def _process_stream(self, result: httpx.Response) -> Tuple[Dict[str, str], Optio
283283
headers = self._process__headers(result, result.headers, expected_response)
284284
return headers, expected_response.schema_
285285

286-
def _process_request(self, result: httpx.Response) -> Tuple[Dict[str, str], pydantic.BaseModel | str | None]:
286+
def _process_request(
287+
self, result: httpx.Response
288+
) -> Tuple[Dict[str, str], Optional[Union[pydantic.BaseModel, str]]]:
287289
rheaders = dict()
288290
# spec enforces these are strings
289291
status_code = str(result.status_code)

0 commit comments

Comments
 (0)