Skip to content

Commit

Permalink
Replace Union with | where future annotations imported
Browse files Browse the repository at this point in the history
  • Loading branch information
copalco committed Sep 6, 2023
1 parent 9222aab commit fd8b3be
Show file tree
Hide file tree
Showing 7 changed files with 22 additions and 30 deletions.
9 changes: 4 additions & 5 deletions falcon/errors.py
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,6 @@ def on_get(self, req, resp):
from datetime import datetime
from typing import Iterable
from typing import Optional
from typing import Union

import falcon.status_codes as status
from falcon.typing import NormalizedHeaders
Expand Down Expand Up @@ -175,8 +174,8 @@ class WebSocketServerError(WebSocketDisconnected):
pass


Kwargs = Union[str, int, None]
RetryAfter = Union[int, datetime, None]
Kwargs = str | int | None
RetryAfter = int | datetime | None


class HTTPBadRequest(HTTPError):
Expand Down Expand Up @@ -2648,7 +2647,7 @@ class MediaMalformedError(HTTPBadRequest):
base articles related to this error (default ``None``).
"""

def __init__(self, media_type: str, **kwargs: Union[RawHeaders, Kwargs]):
def __init__(self, media_type: str, **kwargs: RawHeaders | Kwargs):
super().__init__(
title='Invalid {0}'.format(media_type), description=None, **kwargs
)
Expand Down Expand Up @@ -2749,7 +2748,7 @@ class MultipartParseError(MediaMalformedError):

@deprecated_args(allowed_positional=0)
def __init__(
self, description: Optional[str] = None, **kwargs: Union[RawHeaders, Kwargs]
self, description: Optional[str] = None, **kwargs: RawHeaders | Kwargs
) -> None:
HTTPBadRequest.__init__(
self,
Expand Down
5 changes: 2 additions & 3 deletions falcon/hooks.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,6 @@
from typing import Dict
from typing import List
from typing import Tuple
from typing import Union

from falcon import asgi
from falcon.constants import COMBINED_METHODS
Expand All @@ -41,7 +40,7 @@

SynchronousResource = Callable[..., Any]
AsynchronousResource = Callable[..., Awaitable[Any]]
Resource = Union[SynchronousResource, AsynchronousResource]
Resource = SynchronousResource | AsynchronousResource


def before(
Expand Down Expand Up @@ -266,7 +265,7 @@ def _wrap_with_before(
action_args: Tuple[Any, ...],
action_kwargs: Dict[str, Any],
is_async: bool,
) -> Union[Callable[..., Awaitable[None]], Callable[..., None]]:
) -> Callable[..., Awaitable[None]] | Callable[..., None]:
"""Execute the given action function before a responder method.
Args:
Expand Down
5 changes: 2 additions & 3 deletions falcon/http_error.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,6 @@
from typing import MutableMapping
from typing import Optional
from typing import Type
from typing import Union
import xml.etree.ElementTree as et

from falcon.constants import MEDIA_JSON
Expand Down Expand Up @@ -157,8 +156,8 @@ def status_code(self) -> int:
return http_status_to_code(self.status)

def to_dict(
self, obj_type: Type[MutableMapping[str, Union[str, int, None, Link]]] = dict
) -> MutableMapping[str, Union[str, int, None, Link]]:
self, obj_type: Type[MutableMapping[str, str | int | None | Link]] = dict
) -> MutableMapping[str, str | int | None | Link]:
"""Return a basic dictionary representing the error.
This method can be useful when serializing the error to hash-like
Expand Down
13 changes: 5 additions & 8 deletions falcon/inspect.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,6 @@
from typing import Optional
from typing import Tuple
from typing import Type
from typing import Union

from falcon import app_helpers
from falcon.app import App
Expand Down Expand Up @@ -615,7 +614,7 @@ def visit_route_method(self, route_method: RouteMethodInfo) -> str:
return text

def _methods_to_string(
self, methods: Union[List[RouteMethodInfo], List[MiddlewareMethodInfo]]
self, methods: List[RouteMethodInfo] | List[MiddlewareMethodInfo]
) -> str:
"""Return a string from the list of methods."""
tab = self.tab + ' ' * 3
Expand Down Expand Up @@ -814,13 +813,11 @@ def _is_internal(obj: Any) -> bool:


def _filter_internal(
iterable: Union[
Iterable[RouteMethodInfo],
Iterable[ErrorHandlerInfo],
Iterable[MiddlewareMethodInfo],
],
iterable: Iterable[RouteMethodInfo]
| Iterable[ErrorHandlerInfo]
| Iterable[MiddlewareMethodInfo],
return_internal: bool,
) -> Union[Iterable[_Traversable], List[_Traversable]]:
) -> Iterable[_Traversable] | List[_Traversable]:
"""Filter the internal elements of an iterable."""
if return_internal:
return iterable
Expand Down
7 changes: 3 additions & 4 deletions falcon/middleware.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@
from typing import Any
from typing import Iterable
from typing import Optional
from typing import Union

from .request import Request
from .response import Response
Expand Down Expand Up @@ -45,9 +44,9 @@ class CORSMiddleware(object):

def __init__(
self,
allow_origins: Union[str, Iterable[str]] = '*',
expose_headers: Optional[Union[str, Iterable[str]]] = None,
allow_credentials: Optional[Union[str, Iterable[str]]] = None,
allow_origins: str | Iterable[str] = '*',
expose_headers: Optional[str | Iterable[str]] = None,
allow_credentials: Optional[str | Iterable[str]] = None,
):
if allow_origins == '*':
self.allow_origins = allow_origins
Expand Down
4 changes: 2 additions & 2 deletions falcon/stream.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,12 +17,12 @@
from __future__ import annotations

import io
from typing import BinaryIO, Callable, List, Optional, TypeVar, Union
from typing import BinaryIO, Callable, List, Optional, TypeVar

__all__ = ['BoundedStream']


Result = TypeVar('Result', bound=Union[bytes, List[bytes]])
Result = TypeVar('Result', bound=bytes | List[bytes])


class BoundedStream(io.IOBase):
Expand Down
9 changes: 4 additions & 5 deletions falcon/typing.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,15 +23,14 @@
from typing import Optional
from typing import Pattern
from typing import Tuple
from typing import Union


Link = Dict[str, str]


class Serializer:
def serialize(
self, media: MutableMapping[str, Union[str, int, None, Link]], content_type: str
self, media: MutableMapping[str, str | int | None | Link], content_type: str
) -> bytes:
raise NotImplementedError()

Expand All @@ -54,13 +53,13 @@ def _resolve(
ErrorSerializer = Callable[[Request, Response, BaseException], Any]

# Sinks
SinkPrefix = Union[str, Pattern]
SinkPrefix = str | Pattern

# TODO(vytas): Is it possible to specify a Callable or a Protocol that defines
# type hints for the two first parameters, but accepts any number of keyword
# arguments afterwords?
# class SinkCallable(Protocol):
# def __call__(sef, req: Request, resp: Response, <how to do?>): ...
NormalizedHeaders = Dict[str, str]
RawHeaders = Union[NormalizedHeaders, List[Tuple[str, str]]]
Status = Union[http.HTTPStatus, str, int]
RawHeaders = NormalizedHeaders | List[Tuple[str, str]]
Status = http.HTTPStatus | str | int

0 comments on commit fd8b3be

Please sign in to comment.