improve typing for `app.errorhandler` decorator
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by Pascal Corpet · committed by pgjones · parent 5205cd4 · Browse files · 5 files·+38 added−13 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
5 files+38 added−13 removed
- other:+38 added−13 removed
Provenance
- Commit
6a4e7e9- Tree
f8e7698- Author
Pascal Corpet <pascal@bayesimpact.org>- Committer
pgjones <philip.graham.jones@googlemail.com>- Parent
5205cd4
5 files changed+38 added−13 removed
modified:src/flask/app.py+4 added-2 removed
59 unmodified lines60 from .templating import Environment61 from .typing import AfterRequestCallable62 from .typing import BeforeFirstRequestCallable63 from .typing import BeforeRequestCallable64-from .typing import ErrorHandlerCallable64 from .typing import ResponseReturnValue65 from .typing import TeardownCallable66 from .typing import TemplateContextProcessorCallable67 from .typing import TemplateFilterCallable8 unmodified lines76 import typing_extensions as te77 from .blueprints import Blueprint78 from .testing import FlaskClient79 from .testing import FlaskCliRunner80+ from .typing import ErrorHandlerCallable81 82 if sys.version_info >= (3, 8):83 iscoroutinefunction = inspect.iscoroutinefunction84 else:1182 unmodified lines1267 """1268 self.shell_context_processors.append(f)1269 return f1270 1271- def _find_error_handler(self, e: Exception) -> t.Optional[ErrorHandlerCallable]:1271+ def _find_error_handler(1272+ self, e: Exception1273+ ) -> t.Optional["ErrorHandlerCallable[Exception]"]:1274 """Return a registered error handler for an exception in this order:1275 blueprint handler for a specific code, app handler for a specific code,1276 blueprint handler for an exception class, app handler for an exception1277 class, or ``None`` if a suitable handler is not found.816 unmodified linesmodified:src/flask/blueprints.py+4 added-2 removed
6 unmodified lines7 from .scaffold import Scaffold8 from .typing import AfterRequestCallable9 from .typing import BeforeFirstRequestCallable10 from .typing import BeforeRequestCallable11-from .typing import ErrorHandlerCallable11 from .typing import TeardownCallable12 from .typing import TemplateContextProcessorCallable13 from .typing import TemplateFilterCallable14 from .typing import TemplateGlobalCallable2 unmodified lines17 from .typing import URLValuePreprocessorCallable18 19 if t.TYPE_CHECKING:20 from .app import Flask21+ from .typing import ErrorHandlerCallable22 23 DeferredSetupFunction = t.Callable[["BlueprintSetupState"], t.Callable]24 25 554 unmodified lines580 """Like :meth:`Flask.errorhandler` but for a blueprint. This581 handler is used for all requests, even if outside of the blueprint.582 """583 584- def decorator(f: ErrorHandlerCallable) -> ErrorHandlerCallable:584+ def decorator(585+ f: "ErrorHandlerCallable[Exception]",586+ ) -> "ErrorHandlerCallable[Exception]":587 self.record_once(lambda s: s.app.errorhandler(code)(f))588 return f589 590 return decorator16 unmodified linesmodified:src/flask/scaffold.py+19 added-8 removed
19 unmodified lines20 from .templating import _default_template_ctx_processor21 from .typing import AfterRequestCallable22 from .typing import AppOrBlueprintKey23 from .typing import BeforeRequestCallable24-from .typing import ErrorHandlerCallable24+from .typing import GenericException25 from .typing import TeardownCallable26 from .typing import TemplateContextProcessorCallable27 from .typing import URLDefaultCallable28 from .typing import URLValuePreprocessorCallable29 30 if t.TYPE_CHECKING:31 from .wrappers import Response32+ from .typing import ErrorHandlerCallable33 34 # a singleton sentinel value for parameter defaults35 _sentinel = object()36 107 unmodified lines144 #: This data structure is internal. It should not be modified145 #: directly and its format may change at any time.146 self.error_handler_spec: t.Dict[147 AppOrBlueprintKey,147- t.Dict[t.Optional[int], t.Dict[t.Type[Exception], ErrorHandlerCallable]],148+ t.Dict[149+ t.Optional[int],150+ t.Dict[t.Type[Exception], "ErrorHandlerCallable[Exception]"],151+ ],152 ] = defaultdict(lambda: defaultdict(dict))153 154 #: A data structure of functions to call at the beginning of155 #: each request, in the format ``{scope: [functions]}``. The490 unmodified lines646 return f647 648 @setupmethod649 def errorhandler(646- self, code_or_exception: t.Union[t.Type[Exception], int]647- ) -> t.Callable[[ErrorHandlerCallable], ErrorHandlerCallable]:650+ self, code_or_exception: t.Union[t.Type[GenericException], int]651+ ) -> t.Callable[652+ ["ErrorHandlerCallable[GenericException]"],653+ "ErrorHandlerCallable[GenericException]",654+ ]:655 """Register a function to handle errors by code or exception class.656 657 A decorator that is used to register a function given an658 error code. Example::21 unmodified lines680 :param code_or_exception: the code as integer for the handler, or681 an arbitrary exception682 """683 677- def decorator(f: ErrorHandlerCallable) -> ErrorHandlerCallable:684+ def decorator(685+ f: "ErrorHandlerCallable[GenericException]",686+ ) -> "ErrorHandlerCallable[GenericException]":687 self.register_error_handler(code_or_exception, f)688 return f689 690 return decorator691 692 @setupmethod693 def register_error_handler(694 self,686- code_or_exception: t.Union[t.Type[Exception], int],687- f: ErrorHandlerCallable,695+ code_or_exception: t.Union[t.Type[GenericException], int],696+ f: "ErrorHandlerCallable[GenericException]",697 ) -> None:698 """Alternative error attach function to the :meth:`errorhandler`699 decorator that is more straightforward to use for non decorator700 usage.15 unmodified lines716 " code. Use a subclass of HTTPException with that code"717 " instead."718 )719 711- self.error_handler_spec[None][code][exc_class] = f720+ self.error_handler_spec[None][code][exc_class] = t.cast(721+ "ErrorHandlerCallable[Exception]", f722+ )723 724 @staticmethod725 def _get_exc_class_and_code(726 exc_class_or_code: t.Union[t.Type[Exception], int]149 unmodified linesmodified:src/flask/typing.py+10 added-1 removed
31 unmodified lines32 t.Tuple[ResponseValue, StatusCode, HeadersValue],33 "WSGIApplication",34 ]35 36+GenericException = t.TypeVar("GenericException", bound=Exception, contravariant=True)37+38 AppOrBlueprintKey = t.Optional[str] # The App key is None, whereas blueprints are named39 AfterRequestCallable = t.Callable[["Response"], "Response"]40 BeforeFirstRequestCallable = t.Callable[[], None]41 BeforeRequestCallable = t.Callable[[], t.Optional[ResponseReturnValue]]40-ErrorHandlerCallable = t.Callable[[Exception], ResponseReturnValue]42 TeardownCallable = t.Callable[[t.Optional[BaseException]], None]43 TemplateContextProcessorCallable = t.Callable[[], t.Dict[str, t.Any]]44 TemplateFilterCallable = t.Callable[..., t.Any]45 TemplateGlobalCallable = t.Callable[..., t.Any]46 TemplateTestCallable = t.Callable[..., bool]47 URLDefaultCallable = t.Callable[[str, dict], None]48 URLValuePreprocessorCallable = t.Callable[[t.Optional[str], t.Optional[dict]], None]49+50+51+if t.TYPE_CHECKING:52+ import typing_extensions as te53+54+ class ErrorHandlerCallable(te.Protocol[GenericException]):55+ def __call__(self, error: GenericException) -> ResponseReturnValue:56+ ...modified:CHANGES.rst+1 added
9 unmodified lines10 decorators. :issue:`4104`11 - Fixed the issue where typing requires template global12 decorators to accept functions with no arguments. :issue:`4098`13 - Support View and MethodView instances with async handlers. :issue:`4112`14+- Enhance typing of ``app.errorhandler`` decorator. :issue:`4095`15 16 17 Version 2.0.118 -------------1154 unmodified lines