Skip to content

Commit 6948511

Browse files
style: Introduce no-optional pre-commit hook (#295)
To replace `Optional[T]` type annotations in code base to `Union[T, None]`.
1 parent 9d54e79 commit 6948511

File tree

12 files changed

+39
-42
lines changed

12 files changed

+39
-42
lines changed

.pre-commit-config.yaml

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,12 @@ repos:
1212
language_version: *python_version
1313
stages: ["commit-msg"]
1414

15+
- repo: "https://github.com/Kludex/no-optional"
16+
rev: "0.4.0"
17+
hooks:
18+
- id: "no_optional"
19+
name: "Format code (no-optional)"
20+
1521
- repo: "https://github.com/PyCQA/isort"
1622
rev: "5.10.1"
1723
hooks:
@@ -84,7 +90,7 @@ repos:
8490
- repo: "https://github.com/asottile/yesqa"
8591
rev: "v1.4.0"
8692
hooks:
87-
- id: yesqa
93+
- id: "yesqa"
8894
name: "Lint code (yesqa)"
8995
additional_dependencies: *flake8_additional_dependencies
9096
exclude: ^docs/.*$

examples/petstore/src/petstore/data.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
from typing import Optional
1+
from typing import Union
22

33
import attr
44

@@ -8,7 +8,7 @@
88
@attr.dataclass(frozen=True, slots=True)
99
class NewPet:
1010
name: str
11-
tag: Optional[str]
11+
tag: Union[str, None]
1212

1313
def to_pet(self, pet_id: int) -> "Pet":
1414
return Pet(id=pet_id, name=self.name, tag=self.tag)

src/rororo/aio.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@
99
"""
1010

1111
from contextlib import contextmanager
12-
from typing import Iterator, Optional, Union
12+
from typing import Iterator, Union
1313
from urllib.parse import urlparse
1414

1515
from aiohttp import web
@@ -121,7 +121,7 @@ def is_xhr_request(request: web.Request) -> bool:
121121
122122
:param request: Request instance.
123123
"""
124-
value: Optional[str] = request.headers.get("X-Requested-With")
124+
value: Union[str, None] = request.headers.get("X-Requested-With")
125125
return value == "XMLHttpRequest"
126126

127127

@@ -140,7 +140,7 @@ async def connect_redis(url=None):
140140
"""
141141
parts = urlparse(url)
142142

143-
db: Optional[Union[str, int]] = parts.path[1:] or None
143+
db: Union[str, int, None] = parts.path[1:] or None
144144
if db:
145145
db = int(db)
146146

src/rororo/logger.py

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

1010
import logging
1111
import sys
12-
from typing import Any, Optional, Union
12+
from typing import Any, Union
1313

1414
from rororo.annotations import DictStrAny
1515

@@ -81,7 +81,7 @@ def default_logging_dict(*loggers: str, **kwargs: Any) -> DictStrAny:
8181

8282
def update_sentry_logging(
8383
logging_dict: DictStrAny,
84-
sentry_dsn: Optional[str],
84+
sentry_dsn: Union[str, None],
8585
*loggers: str,
8686
level: Union[str, int, None] = None,
8787
**kwargs: Any,

src/rororo/openapi/core_data.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
from typing import cast, Optional, Union
1+
from typing import cast, Union
22

33
from aiohttp import hdrs, web
44
from aiohttp.payload import IOBasePayload, Payload
@@ -19,7 +19,7 @@
1919

2020
def find_core_operation(
2121
request: web.Request, handler: Handler
22-
) -> Optional[Operation]:
22+
) -> Union[Operation, None]:
2323
mapping = getattr(handler, HANDLER_OPENAPI_MAPPING_KEY, None)
2424
if not mapping:
2525
return None
@@ -69,7 +69,7 @@ async def to_core_openapi_request(request: web.Request) -> OpenAPIRequest:
6969
Afterwards opeanpi-core request can be used for validation request data
7070
against spec.
7171
"""
72-
body: Optional[Union[bytes, str]] = None
72+
body: Union[bytes, str, None] = None
7373
if request.body_exists and request.can_read_body:
7474
raw_body = await request.read()
7575

@@ -100,7 +100,7 @@ def to_core_openapi_response(response: web.StreamResponse) -> OpenAPIResponse:
100100

101101
def to_core_openapi_response_data(
102102
response: web.StreamResponse,
103-
) -> Optional[bytes]:
103+
) -> Union[bytes, None]:
104104
if isinstance(response, web.Response):
105105
body = response.body
106106
if not body:

src/rororo/openapi/core_validators.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
from collections import deque
22
from functools import partial
3-
from typing import Any, cast, Dict, Iterator, List, Optional, Tuple, Union
3+
from typing import Any, cast, Dict, Iterator, List, Tuple, Union
44

55
import pyrsistent
66
from email_validator import EmailNotValidError, validate_email
@@ -71,7 +71,7 @@ class ArrayUnmarshaller(CoreArrayUnmarshaller):
7171
arrays: https://github.com/p1c2u/openapi-core/issues/251
7272
"""
7373

74-
def __call__(self, value: Any = NoValue) -> Optional[List[Any]]:
74+
def __call__(self, value: Any = NoValue) -> Union[List[Any], None]:
7575
if value is None and self.schema.nullable:
7676
return None
7777
return cast(List[Any], super().__call__(value))
@@ -108,7 +108,7 @@ class ObjectUnmarshaller(CoreObjectUnmarshaller):
108108
objects: https://github.com/p1c2u/openapi-core/issues/232
109109
"""
110110

111-
def __call__(self, value: Any = NoValue) -> Optional[Dict[Any, Any]]:
111+
def __call__(self, value: Any = NoValue) -> Union[Dict[Any, Any], None]:
112112
if value is None and self.schema.nullable:
113113
return None
114114
return cast(Dict[Any, Any], super().__call__(value))

src/rororo/openapi/exceptions.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22
import re
33
from contextlib import contextmanager
44
from contextvars import ContextVar
5-
from typing import Any, Dict, Iterator, List, Optional, Tuple, Union
5+
from typing import Any, Dict, Iterator, List, Tuple, Union
66

77
import attr
88
from jsonschema.exceptions import ValidationError as JsonSchemaValidationError
@@ -385,7 +385,7 @@ def get_parameter_error_details(
385385
loc: List[PathItem],
386386
err: OpenAPIParameterError,
387387
) -> ValidationErrorItem:
388-
parameter_name: Optional[str] = getattr(err, "name", None)
388+
parameter_name: Union[str, None] = getattr(err, "name", None)
389389
if parameter_name is None:
390390
return get_common_error_details(loc, err)
391391

src/rororo/openapi/openapi.py

Lines changed: 2 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -4,17 +4,7 @@
44
import warnings
55
from functools import lru_cache, partial
66
from pathlib import Path
7-
from typing import (
8-
Callable,
9-
cast,
10-
Deque,
11-
Dict,
12-
List,
13-
Optional,
14-
overload,
15-
Tuple,
16-
Union,
17-
)
7+
from typing import Callable, cast, Deque, Dict, List, overload, Tuple, Union
188

199
import attr
2010
import yaml
@@ -344,7 +334,7 @@ def fix_spec_operations(spec: Spec, schema: DictStrAny) -> Spec:
344334
as unsecured. With missed operation security - use global security schema
345335
if it is defined.
346336
"""
347-
mapping: Dict[str, Optional[SecurityDict]] = {}
337+
mapping: Dict[str, Union[SecurityDict, None]] = {}
348338

349339
for path_data in schema["paths"].values():
350340
for maybe_operation_data in path_data.values():

src/rororo/openapi/security.py

Lines changed: 7 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
from typing import cast, List, Optional, Union
1+
from typing import cast, List, Union
22

33
from aiohttp import BasicAuth, hdrs
44
from openapi_core.schema.operations.models import Operation
@@ -29,13 +29,15 @@ def basic_auth_factory(value: str) -> BasicAuth:
2929
return BasicAuth.decode(f"Basic {value}")
3030

3131

32-
def get_jwt_security_data(request: OpenAPIRequest) -> Optional[str]:
32+
def get_jwt_security_data(request: OpenAPIRequest) -> Union[str, None]:
3333
"""Get JWT bearer security data.
3434
3535
At a moment, openapi-core attempts to decode JWT header using same rules
3636
as for basic auth, which might return unexpected results.
3737
"""
38-
header: Optional[str] = request.parameters.header.get(AUTHORIZATION_HEADER)
38+
header: Union[str, None] = request.parameters.header.get(
39+
AUTHORIZATION_HEADER
40+
)
3941

4042
# Header does not exist
4143
if header is None:
@@ -54,7 +56,7 @@ def get_jwt_security_data(request: OpenAPIRequest) -> Optional[str]:
5456

5557
def get_security_data(
5658
validator: RequestValidator, request: OpenAPIRequest, scheme_name: str
57-
) -> Optional[Union[BasicAuth, str]]:
59+
) -> Union[BasicAuth, str, None]:
5860
"""Get security data from request.
5961
6062
Currently supported getting API Key & HTTP security data. OAuth & OpenID
@@ -83,7 +85,7 @@ def get_security_list(
8385

8486
def get_security_scheme(
8587
validator: RequestValidator, scheme_name: str
86-
) -> Optional[SecurityScheme]:
88+
) -> Union[SecurityScheme, None]:
8789
return validator.spec.components.security_schemes.get(scheme_name)
8890

8991

src/rororo/openapi/utils.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
from typing import Any, cast, Optional, Union
1+
from typing import Any, cast, Union
22

33
from aiohttp import web
44
from aiohttp.helpers import ChainMapProxy
@@ -18,7 +18,7 @@
1818
from rororo.openapi.exceptions import ConfigurationError, ContextError
1919

2020

21-
def add_prefix(path: str, prefix: Optional[str]) -> str:
21+
def add_prefix(path: str, prefix: Union[str, None]) -> str:
2222
if prefix:
2323
if prefix[-1] == "/":
2424
prefix = prefix[:-1]

0 commit comments

Comments
 (0)