From 832cabc62a7ef325d51017b814fe4468d9423018 Mon Sep 17 00:00:00 2001 From: Vytautas Liuolia Date: Fri, 5 Apr 2024 18:18:44 +0200 Subject: [PATCH 1/2] chore(typing): add more descriptive typing to `Context` --- falcon/util/structures.py | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) diff --git a/falcon/util/structures.py b/falcon/util/structures.py index fc7ba2a88..340b46d16 100644 --- a/falcon/util/structures.py +++ b/falcon/util/structures.py @@ -37,6 +37,7 @@ from typing import KeysView from typing import Optional from typing import Tuple +from typing import TYPE_CHECKING from typing import ValuesView @@ -141,6 +142,25 @@ class Context: True """ + # NOTE(vytas): Define synthetic attr access methods (under TYPE_CHECKING) + # merely to let mypy know this is a namespace object. + if TYPE_CHECKING: + + def __getattr__(self, name: str) -> Any: + try: + return self.__dict__[name] + except KeyError: + raise AttributeError(name) from None + + def __setattr__(self, name: str, value: Any) -> None: + self.__dict__[name] = value + + def __delattr__(self, name: str) -> None: + try: + del self.__dict__[name] + except KeyError: + raise AttributeError(name) from None + def __contains__(self, key: str) -> bool: return self.__dict__.__contains__(key) From 4c4709f6533f39da550b165da8fc529358a847be Mon Sep 17 00:00:00 2001 From: Vytautas Liuolia Date: Fri, 5 Apr 2024 19:05:55 +0200 Subject: [PATCH 2/2] chore(typing): define only stubs when under `TYPE_CHECKING` --- falcon/util/structures.py | 12 +++--------- 1 file changed, 3 insertions(+), 9 deletions(-) diff --git a/falcon/util/structures.py b/falcon/util/structures.py index 340b46d16..5a9e51176 100644 --- a/falcon/util/structures.py +++ b/falcon/util/structures.py @@ -147,19 +147,13 @@ class Context: if TYPE_CHECKING: def __getattr__(self, name: str) -> Any: - try: - return self.__dict__[name] - except KeyError: - raise AttributeError(name) from None + ... def __setattr__(self, name: str, value: Any) -> None: - self.__dict__[name] = value + ... def __delattr__(self, name: str) -> None: - try: - del self.__dict__[name] - except KeyError: - raise AttributeError(name) from None + ... def __contains__(self, key: str) -> bool: return self.__dict__.__contains__(key)