Skip to content

Commit

Permalink
Improve imports to avoid them inside functions
Browse files Browse the repository at this point in the history
  • Loading branch information
CaselIT committed Sep 9, 2023
1 parent 01dbfb9 commit 08a7eca
Show file tree
Hide file tree
Showing 10 changed files with 69 additions and 61 deletions.
2 changes: 1 addition & 1 deletion falcon/asgi_spec.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,9 +11,9 @@
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from __future__ import annotations

"""Constants, etc. defined by the ASGI specification."""
from __future__ import annotations


class EventType:
Expand Down
10 changes: 6 additions & 4 deletions falcon/errors.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,6 @@
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from __future__ import annotations

"""HTTP error classes and other Falcon-specific errors.
Expand All @@ -34,19 +33,22 @@ def on_get(self, req, resp):
# -- snip --
"""
from __future__ import annotations

from datetime import datetime
from typing import Iterable
from typing import Optional
from typing import TYPE_CHECKING
from typing import Union

from falcon.http_error import HTTPError
import falcon.status_codes as status
from falcon.typing import NormalizedHeaders
from falcon.typing import RawHeaders
from falcon.util.deprecation import deprecated_args
from falcon.util.misc import dt_to_http

from .http_error import HTTPError
if TYPE_CHECKING:
from falcon.typing import NormalizedHeaders
from falcon.typing import RawHeaders


__all__ = (
Expand Down
17 changes: 11 additions & 6 deletions falcon/hooks.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,15 +25,16 @@
from typing import Dict
from typing import List
from typing import Tuple
from typing import TYPE_CHECKING
from typing import Union

from falcon import asgi
from falcon.constants import COMBINED_METHODS
from falcon.request import Request
from falcon.response import Response
from falcon.util.misc import get_argnames
from falcon.util.sync import _wrap_non_coroutine_unsafe

if TYPE_CHECKING:
import falcon as wsgi
from falcon import asgi

_DECORABLE_METHOD_NAME = re.compile(
r'^on_({})(_\w+)?$'.format('|'.join(method.lower() for method in COMBINED_METHODS))
Expand Down Expand Up @@ -246,8 +247,8 @@ async def do_after(
@wraps(responder)
def do_after(
self: Resource,
req: Request,
resp: Response,
req: wsgi.Request,
resp: wsgi.Response,
*args: Any,
**kwargs: Any,
) -> None:
Expand Down Expand Up @@ -312,7 +313,11 @@ async def do_before(

@wraps(responder)
def do_before(
self: Resource, req: Request, resp: Response, *args: Any, **kwargs: Any
self: Resource,
req: wsgi.Request,
resp: wsgi.Response,
*args: Any,
**kwargs: Any,
) -> None:
if args:
_merge_responder_args(args, kwargs, extra_argnames)
Expand Down
23 changes: 15 additions & 8 deletions falcon/http_error.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,24 +11,29 @@
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""HTTPError exception class."""
from __future__ import annotations

"""HTTPError exception class."""
from collections import OrderedDict
from typing import MutableMapping
from typing import Optional
from typing import Type
from typing import TYPE_CHECKING
from typing import Union
import xml.etree.ElementTree as et

from falcon.constants import MEDIA_JSON
from falcon.typing import Link
from falcon.typing import RawHeaders
from falcon.typing import Serializer
from falcon.typing import Status
from falcon.util import code_to_http_status, http_status_to_code, uri
from falcon.util import code_to_http_status
from falcon.util import http_status_to_code
from falcon.util import uri
from falcon.util.deprecation import deprecated_args

if TYPE_CHECKING:
from falcon.typing import Link
from falcon.typing import RawHeaders
from falcon.typing import Serializer
from falcon.typing import Status


class HTTPError(Exception):
"""Represents a generic HTTP error.
Expand Down Expand Up @@ -205,7 +210,6 @@ def to_json(self, handler: Optional[Serializer] = None) -> bytes:
obj = self.to_dict(OrderedDict)
if handler is None:
handler = _DEFAULT_JSON_HANDLER
assert handler
return handler.serialize(obj, MEDIA_JSON)

def to_xml(self) -> bytes:
Expand Down Expand Up @@ -239,4 +243,7 @@ def to_xml(self) -> bytes:

# NOTE: initialized in falcon.media.json, that is always imported since Request/Response
# are imported by falcon init.
_DEFAULT_JSON_HANDLER = None
if TYPE_CHECKING:
_DEFAULT_JSON_HANDLER: Serializer
else:
_DEFAULT_JSON_HANDLER = None
9 changes: 6 additions & 3 deletions falcon/http_status.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,16 +11,19 @@
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""HTTPStatus exception class."""
from __future__ import annotations

"""HTTPStatus exception class."""
from typing import Optional
from typing import TYPE_CHECKING

from falcon.typing import RawHeaders
from falcon.typing import Status
from falcon.util import http_status_to_code
from falcon.util.deprecation import AttributeRemovedError

if TYPE_CHECKING:
from falcon.typing import RawHeaders
from falcon.typing import Status


class HTTPStatus(Exception):
"""Represents a generic HTTP status.
Expand Down
7 changes: 5 additions & 2 deletions falcon/redirects.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,14 +11,17 @@
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""HTTPStatus specializations for 3xx redirects."""
from __future__ import annotations

"""HTTPStatus specializations for 3xx redirects."""
from typing import Optional
from typing import TYPE_CHECKING

import falcon
from falcon.http_status import HTTPStatus
from falcon.typing import NormalizedHeaders

if TYPE_CHECKING:
from falcon.typing import NormalizedHeaders


class HTTPMovedPermanently(HTTPStatus):
Expand Down
10 changes: 4 additions & 6 deletions falcon/request.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,8 @@
# limitations under the License.

"""Request class."""
from __future__ import annotations

from collections import UserDict
from datetime import datetime
from io import BytesIO
Expand All @@ -26,6 +28,8 @@

# TODO: remove import in falcon 4
from falcon.forwarded import Forwarded # NOQA
from falcon.media import Handlers
from falcon.media.json import _DEFAULT_JSON_HANDLER
from falcon.stream import BoundedStream
from falcon.util import structures
from falcon.util.misc import isascii
Expand Down Expand Up @@ -1887,10 +1891,6 @@ def get_param_as_json(self, name, required=False, store=None, default=None):
MEDIA_JSON, MEDIA_JSON, raise_not_found=False
)
if handler is None:
from falcon.media.json import (
_DEFAULT_JSON_HANDLER,
) # import here to avoid circular imports

handler = _DEFAULT_JSON_HANDLER

try:
Expand Down Expand Up @@ -2104,8 +2104,6 @@ class RequestOptions:
)

def __init__(self):
from falcon.media.handlers import Handlers

self.keep_blank_qs_values = True
self.auto_parse_form_urlencoded = False
self.auto_parse_qs_csv = False
Expand Down
28 changes: 10 additions & 18 deletions falcon/response.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,21 +13,24 @@
# limitations under the License.

"""Response class."""
from __future__ import annotations

import functools
import mimetypes
from typing import Optional
from typing import TYPE_CHECKING

from falcon.constants import _DEFAULT_STATIC_MEDIA_TYPES
from falcon.constants import _UNSET
from falcon.constants import DEFAULT_MEDIA_TYPE
from falcon.errors import HeaderNotSupported
from falcon.media import Handlers
from falcon.response_helpers import format_content_disposition
from falcon.response_helpers import format_etag_header
from falcon.response_helpers import format_header_value_list
from falcon.response_helpers import format_range
from falcon.response_helpers import header_property
from falcon.response_helpers import is_ascii_encodable
from falcon.typing import MediaHandlers
from falcon.util import dt_to_http
from falcon.util import http_cookies
from falcon.util import http_status_to_code
Expand All @@ -37,6 +40,8 @@
from falcon.util.uri import encode_check_escaped as uri_encode
from falcon.util.uri import encode_value_check_escaped as uri_encode_value

if TYPE_CHECKING:
from falcon.typing import MediaHandlers

GMT_TIMEZONE = TimezoneGMT()

Expand Down Expand Up @@ -198,9 +203,6 @@ def __init__(self, options=None):
self._media_rendered = _UNSET

self.context = self.context_type()
from falcon.errors import HeaderNotSupported

self._header_not_supported = HeaderNotSupported

@property
def status_code(self) -> int:
Expand Down Expand Up @@ -634,9 +636,7 @@ def get_header(self, name, default=None):
name = name.lower()

if name == 'set-cookie':
raise self._header_not_supported(
'Getting Set-Cookie is not currently supported.'
)
raise HeaderNotSupported('Getting Set-Cookie is not currently supported.')

return self._headers.get(name, default)

Expand Down Expand Up @@ -672,9 +672,7 @@ def set_header(self, name, value):
name = name.lower()

if name == 'set-cookie':
raise self._header_not_supported(
'This method cannot be used to set cookies'
)
raise HeaderNotSupported('This method cannot be used to set cookies')

self._headers[name] = value

Expand Down Expand Up @@ -708,9 +706,7 @@ def delete_header(self, name):
name = name.lower()

if name == 'set-cookie':
raise self._header_not_supported(
'This method cannot be used to remove cookies'
)
raise HeaderNotSupported('This method cannot be used to remove ookies')

Check warning on line 709 in falcon/response.py

View check run for this annotation

Codecov / codecov/patch

falcon/response.py#L709

Added line #L709 was not covered by tests

self._headers.pop(name, None)

Expand Down Expand Up @@ -804,9 +800,7 @@ def set_headers(self, headers):

name = name.lower()
if name == 'set-cookie':
raise self._header_not_supported(
'This method cannot be used to set cookies'
)
raise HeaderNotSupported('This method cannot be used to set cookies')

_headers[name] = value

Expand Down Expand Up @@ -1259,8 +1253,6 @@ class ResponseOptions:
def __init__(self):
self.secure_cookies_by_default = True
self.default_media_type = DEFAULT_MEDIA_TYPE
from falcon.media import Handlers

self.media_handlers = Handlers()

if not mimetypes.inited:
Expand Down
14 changes: 7 additions & 7 deletions falcon/typing.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,9 +11,9 @@
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Shorthand definitions for more complex types."""
from __future__ import annotations

"""Shorthand definitions for more complex types."""
import http
from typing import Any
from typing import Callable
Expand All @@ -23,8 +23,12 @@
from typing import Optional
from typing import Pattern
from typing import Tuple
from typing import TYPE_CHECKING
from typing import Union

if TYPE_CHECKING:
from falcon.request import Request
from falcon.response import Response

Link = Dict[str, str]

Expand All @@ -43,15 +47,11 @@ def _resolve(
raise NotImplementedError()


from falcon.request import Request # noqa: E402
from falcon.response import Response # noqa: E402


# Error handlers
ErrorHandler = Callable[[Request, Response, BaseException, dict], Any]
ErrorHandler = Callable[['Request', 'Response', BaseException, dict], Any]

# Error serializers
ErrorSerializer = Callable[[Request, Response, BaseException], Any]
ErrorSerializer = Callable[['Request', 'Response', BaseException], Any]

# Sinks
SinkPrefix = Union[str, Pattern]
Expand Down
Loading

0 comments on commit 08a7eca

Please sign in to comment.