Skip to content

Commit

Permalink
add __future__ annotations
Browse files Browse the repository at this point in the history
  • Loading branch information
davidism committed Apr 20, 2023
1 parent cfa863c commit 44ffe6c
Show file tree
Hide file tree
Showing 19 changed files with 277 additions and 262 deletions.
1 change: 1 addition & 0 deletions CHANGES.rst
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,7 @@ Unreleased
:issue:`5051`
- The ``routes`` command shows each rule's ``subdomain`` or ``host`` when domain
matching is in use. :issue:`5004`
- Use postponed evaluation of annotations. :pr:`5071`


Version 2.2.4
Expand Down
110 changes: 54 additions & 56 deletions src/flask/app.py

Large diffs are not rendered by default.

56 changes: 29 additions & 27 deletions src/flask/blueprints.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
from __future__ import annotations

import os
import typing as t
from collections import defaultdict
Expand Down Expand Up @@ -38,8 +40,8 @@ class BlueprintSetupState:

def __init__(
self,
blueprint: "Blueprint",
app: "Flask",
blueprint: Blueprint,
app: Flask,
options: t.Any,
first_registration: bool,
) -> None:
Expand Down Expand Up @@ -85,8 +87,8 @@ def __init__(
def add_url_rule(
self,
rule: str,
endpoint: t.Optional[str] = None,
view_func: t.Optional[t.Callable] = None,
endpoint: str | None = None,
view_func: t.Callable | None = None,
**options: t.Any,
) -> None:
"""A helper method to register a rule (and optionally a view function)
Expand Down Expand Up @@ -173,14 +175,14 @@ def __init__(
self,
name: str,
import_name: str,
static_folder: t.Optional[t.Union[str, os.PathLike]] = None,
static_url_path: t.Optional[str] = None,
template_folder: t.Optional[t.Union[str, os.PathLike]] = None,
url_prefix: t.Optional[str] = None,
subdomain: t.Optional[str] = None,
url_defaults: t.Optional[dict] = None,
root_path: t.Optional[str] = None,
cli_group: t.Optional[str] = _sentinel, # type: ignore
static_folder: str | os.PathLike | None = None,
static_url_path: str | None = None,
template_folder: str | os.PathLike | None = None,
url_prefix: str | None = None,
subdomain: str | None = None,
url_defaults: dict | None = None,
root_path: str | None = None,
cli_group: str | None = _sentinel, # type: ignore
):
super().__init__(
import_name=import_name,
Expand All @@ -199,14 +201,14 @@ def __init__(
self.name = name
self.url_prefix = url_prefix
self.subdomain = subdomain
self.deferred_functions: t.List[DeferredSetupFunction] = []
self.deferred_functions: list[DeferredSetupFunction] = []

if url_defaults is None:
url_defaults = {}

self.url_values_defaults = url_defaults
self.cli_group = cli_group
self._blueprints: t.List[t.Tuple["Blueprint", dict]] = []
self._blueprints: list[tuple[Blueprint, dict]] = []

def _check_setup_finished(self, f_name: str) -> None:
if self._got_registered_once:
Expand Down Expand Up @@ -242,7 +244,7 @@ def wrapper(state: BlueprintSetupState) -> None:
self.record(update_wrapper(wrapper, func))

def make_setup_state(
self, app: "Flask", options: dict, first_registration: bool = False
self, app: Flask, options: dict, first_registration: bool = False
) -> BlueprintSetupState:
"""Creates an instance of :meth:`~flask.blueprints.BlueprintSetupState`
object that is later passed to the register callback functions.
Expand All @@ -251,7 +253,7 @@ def make_setup_state(
return BlueprintSetupState(self, app, options, first_registration)

@setupmethod
def register_blueprint(self, blueprint: "Blueprint", **options: t.Any) -> None:
def register_blueprint(self, blueprint: Blueprint, **options: t.Any) -> None:
"""Register a :class:`~flask.Blueprint` on this blueprint. Keyword
arguments passed to this method will override the defaults set
on the blueprint.
Expand All @@ -268,7 +270,7 @@ def register_blueprint(self, blueprint: "Blueprint", **options: t.Any) -> None:
raise ValueError("Cannot register a blueprint on itself")
self._blueprints.append((blueprint, options))

def register(self, app: "Flask", options: dict) -> None:
def register(self, app: Flask, options: dict) -> None:
"""Called by :meth:`Flask.register_blueprint` to register all
views and callbacks registered on the blueprint with the
application. Creates a :class:`.BlueprintSetupState` and calls
Expand Down Expand Up @@ -408,9 +410,9 @@ def extend(bp_dict, parent_dict):
def add_url_rule(
self,
rule: str,
endpoint: t.Optional[str] = None,
view_func: t.Optional[ft.RouteCallable] = None,
provide_automatic_options: t.Optional[bool] = None,
endpoint: str | None = None,
view_func: ft.RouteCallable | None = None,
provide_automatic_options: bool | None = None,
**options: t.Any,
) -> None:
"""Register a URL rule with the blueprint. See :meth:`.Flask.add_url_rule` for
Expand All @@ -437,7 +439,7 @@ def add_url_rule(

@setupmethod
def app_template_filter(
self, name: t.Optional[str] = None
self, name: str | None = None
) -> t.Callable[[T_template_filter], T_template_filter]:
"""Register a template filter, available in any template rendered by the
application. Equivalent to :meth:`.Flask.template_filter`.
Expand All @@ -454,7 +456,7 @@ def decorator(f: T_template_filter) -> T_template_filter:

@setupmethod
def add_app_template_filter(
self, f: ft.TemplateFilterCallable, name: t.Optional[str] = None
self, f: ft.TemplateFilterCallable, name: str | None = None
) -> None:
"""Register a template filter, available in any template rendered by the
application. Works like the :meth:`app_template_filter` decorator. Equivalent to
Expand All @@ -471,7 +473,7 @@ def register_template(state: BlueprintSetupState) -> None:

@setupmethod
def app_template_test(
self, name: t.Optional[str] = None
self, name: str | None = None
) -> t.Callable[[T_template_test], T_template_test]:
"""Register a template test, available in any template rendered by the
application. Equivalent to :meth:`.Flask.template_test`.
Expand All @@ -490,7 +492,7 @@ def decorator(f: T_template_test) -> T_template_test:

@setupmethod
def add_app_template_test(
self, f: ft.TemplateTestCallable, name: t.Optional[str] = None
self, f: ft.TemplateTestCallable, name: str | None = None
) -> None:
"""Register a template test, available in any template rendered by the
application. Works like the :meth:`app_template_test` decorator. Equivalent to
Expand All @@ -509,7 +511,7 @@ def register_template(state: BlueprintSetupState) -> None:

@setupmethod
def app_template_global(
self, name: t.Optional[str] = None
self, name: str | None = None
) -> t.Callable[[T_template_global], T_template_global]:
"""Register a template global, available in any template rendered by the
application. Equivalent to :meth:`.Flask.template_global`.
Expand All @@ -528,7 +530,7 @@ def decorator(f: T_template_global) -> T_template_global:

@setupmethod
def add_app_template_global(
self, f: ft.TemplateGlobalCallable, name: t.Optional[str] = None
self, f: ft.TemplateGlobalCallable, name: str | None = None
) -> None:
"""Register a template global, available in any template rendered by the
application. Works like the :meth:`app_template_global` decorator. Equivalent to
Expand Down Expand Up @@ -589,7 +591,7 @@ def app_context_processor(

@setupmethod
def app_errorhandler(
self, code: t.Union[t.Type[Exception], int]
self, code: type[Exception] | int
) -> t.Callable[[T_error_handler], T_error_handler]:
"""Like :meth:`errorhandler`, but for every request, not only those handled by
the blueprint. Equivalent to :meth:`.Flask.errorhandler`.
Expand Down
2 changes: 1 addition & 1 deletion src/flask/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -285,7 +285,7 @@ def __init__(
self.create_app = create_app
#: A dictionary with arbitrary data that can be associated with
#: this script info.
self.data: t.Dict[t.Any, t.Any] = {}
self.data: dict[t.Any, t.Any] = {}
self.set_debug_flag = set_debug_flag
self._loaded_app: Flask | None = None

Expand Down
14 changes: 8 additions & 6 deletions src/flask/config.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
from __future__ import annotations

import errno
import json
import os
Expand All @@ -10,7 +12,7 @@
class ConfigAttribute:
"""Makes an attribute forward to the config"""

def __init__(self, name: str, get_converter: t.Optional[t.Callable] = None) -> None:
def __init__(self, name: str, get_converter: t.Callable | None = None) -> None:
self.__name__ = name
self.get_converter = get_converter

Expand Down Expand Up @@ -70,7 +72,7 @@ class Config(dict):
:param defaults: an optional dictionary of default values
"""

def __init__(self, root_path: str, defaults: t.Optional[dict] = None) -> None:
def __init__(self, root_path: str, defaults: dict | None = None) -> None:
super().__init__(defaults or {})
self.root_path = root_path

Expand Down Expand Up @@ -191,7 +193,7 @@ def from_pyfile(self, filename: str, silent: bool = False) -> bool:
self.from_object(d)
return True

def from_object(self, obj: t.Union[object, str]) -> None:
def from_object(self, obj: object | str) -> None:
"""Updates the values from the given object. An object can be of one
of the following two types:
Expand Down Expand Up @@ -278,7 +280,7 @@ def from_file(
return self.from_mapping(obj)

def from_mapping(
self, mapping: t.Optional[t.Mapping[str, t.Any]] = None, **kwargs: t.Any
self, mapping: t.Mapping[str, t.Any] | None = None, **kwargs: t.Any
) -> bool:
"""Updates the config like :meth:`update` ignoring items with
non-upper keys.
Expand All @@ -287,7 +289,7 @@ def from_mapping(
.. versionadded:: 0.11
"""
mappings: t.Dict[str, t.Any] = {}
mappings: dict[str, t.Any] = {}
if mapping is not None:
mappings.update(mapping)
mappings.update(kwargs)
Expand All @@ -298,7 +300,7 @@ def from_mapping(

def get_namespace(
self, namespace: str, lowercase: bool = True, trim_namespace: bool = True
) -> t.Dict[str, t.Any]:
) -> dict[str, t.Any]:
"""Returns a dictionary containing a subset of configuration options
that match the specified namespace/prefix. Example usage::
Expand Down
44 changes: 23 additions & 21 deletions src/flask/ctx.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
from __future__ import annotations

import contextvars
import sys
import typing as t
Expand Down Expand Up @@ -60,7 +62,7 @@ def __delattr__(self, name: str) -> None:
except KeyError:
raise AttributeError(name) from None

def get(self, name: str, default: t.Optional[t.Any] = None) -> t.Any:
def get(self, name: str, default: t.Any | None = None) -> t.Any:
"""Get an attribute by name, or a default value. Like
:meth:`dict.get`.
Expand Down Expand Up @@ -233,18 +235,18 @@ class AppContext:
running CLI commands.
"""

def __init__(self, app: "Flask") -> None:
def __init__(self, app: Flask) -> None:
self.app = app
self.url_adapter = app.create_url_adapter(None)
self.g: _AppCtxGlobals = app.app_ctx_globals_class()
self._cv_tokens: t.List[contextvars.Token] = []
self._cv_tokens: list[contextvars.Token] = []

def push(self) -> None:
"""Binds the app context to the current context."""
self._cv_tokens.append(_cv_app.set(self))
appcontext_pushed.send(self.app, _async_wrapper=self.app.ensure_sync)

def pop(self, exc: t.Optional[BaseException] = _sentinel) -> None: # type: ignore
def pop(self, exc: BaseException | None = _sentinel) -> None: # type: ignore
"""Pops the app context."""
try:
if len(self._cv_tokens) == 1:
Expand All @@ -262,15 +264,15 @@ def pop(self, exc: t.Optional[BaseException] = _sentinel) -> None: # type: igno

appcontext_popped.send(self.app, _async_wrapper=self.app.ensure_sync)

def __enter__(self) -> "AppContext":
def __enter__(self) -> AppContext:
self.push()
return self

def __exit__(
self,
exc_type: t.Optional[type],
exc_value: t.Optional[BaseException],
tb: t.Optional[TracebackType],
exc_type: type | None,
exc_value: BaseException | None,
tb: TracebackType | None,
) -> None:
self.pop(exc_value)

Expand Down Expand Up @@ -299,10 +301,10 @@ class RequestContext:

def __init__(
self,
app: "Flask",
app: Flask,
environ: dict,
request: t.Optional["Request"] = None,
session: t.Optional["SessionMixin"] = None,
request: Request | None = None,
session: SessionMixin | None = None,
) -> None:
self.app = app
if request is None:
Expand All @@ -314,16 +316,16 @@ def __init__(
self.url_adapter = app.create_url_adapter(self.request)
except HTTPException as e:
self.request.routing_exception = e
self.flashes: t.Optional[t.List[t.Tuple[str, str]]] = None
self.session: t.Optional["SessionMixin"] = session
self.flashes: list[tuple[str, str]] | None = None
self.session: SessionMixin | None = session
# Functions that should be executed after the request on the response
# object. These will be called before the regular "after_request"
# functions.
self._after_request_functions: t.List[ft.AfterRequestCallable] = []
self._after_request_functions: list[ft.AfterRequestCallable] = []

self._cv_tokens: t.List[t.Tuple[contextvars.Token, t.Optional[AppContext]]] = []
self._cv_tokens: list[tuple[contextvars.Token, AppContext | None]] = []

def copy(self) -> "RequestContext":
def copy(self) -> RequestContext:
"""Creates a copy of this request context with the same request object.
This can be used to move a request context to a different greenlet.
Because the actual request object is the same this cannot be used to
Expand Down Expand Up @@ -382,7 +384,7 @@ def push(self) -> None:
if self.url_adapter is not None:
self.match_request()

def pop(self, exc: t.Optional[BaseException] = _sentinel) -> None: # type: ignore
def pop(self, exc: BaseException | None = _sentinel) -> None: # type: ignore
"""Pops the request context and unbinds it by doing that. This will
also trigger the execution of functions registered by the
:meth:`~flask.Flask.teardown_request` decorator.
Expand Down Expand Up @@ -419,15 +421,15 @@ def pop(self, exc: t.Optional[BaseException] = _sentinel) -> None: # type: igno
f"Popped wrong request context. ({ctx!r} instead of {self!r})"
)

def __enter__(self) -> "RequestContext":
def __enter__(self) -> RequestContext:
self.push()
return self

def __exit__(
self,
exc_type: t.Optional[type],
exc_value: t.Optional[BaseException],
tb: t.Optional[TracebackType],
exc_type: type | None,
exc_value: BaseException | None,
tb: TracebackType | None,
) -> None:
self.pop(exc_value)

Expand Down
2 changes: 2 additions & 0 deletions src/flask/debughelpers.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
from __future__ import annotations

import typing as t

from .app import Flask
Expand Down
Loading

0 comments on commit 44ffe6c

Please sign in to comment.