Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Emit UserWarning when accessing Application items by str #7553

Draft
wants to merge 1 commit into
base: master
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
14 changes: 14 additions & 0 deletions aiohttp/web_app.py
Expand Up @@ -150,6 +150,13 @@ def __getitem__(self, key: str) -> Any:
...

def __getitem__(self, key: Union[str, AppKey[_T]]) -> Any:
if not isinstance(key, AppKey):
warnings.warn(
"It is recommended to use web.AppKey instances for keys.\n"
+ "https://docs.aiohttp.org/en/stable/web_advanced.html"
+ "#application-s-config",
stacklevel=2,
)
return self._state[key]

def _check_frozen(self) -> None:
Expand Down Expand Up @@ -200,6 +207,13 @@ def get(self, key: str, default: Any = ...) -> Any:
...

def get(self, key: Union[str, AppKey[_T]], default: Any = None) -> Any:
if not isinstance(key, AppKey):
warnings.warn(
"It is recommended to use web.AppKey instances for keys.\n"
+ "https://docs.aiohttp.org/en/stable/web_advanced.html"
+ "#application-s-config",
stacklevel=2,
)
return self._state.get(key, default)

########
Expand Down
14 changes: 13 additions & 1 deletion tests/test_web_app.py
Expand Up @@ -147,10 +147,22 @@ def test_app_str_keys() -> None:
with pytest.warns(
UserWarning, match=r"web_advanced\.html#application-s-config"
) as checker:
# Warning for __setitem__
app["key"] = "value"
# Check that the error is emitted at the call site (stacklevel=2)
assert checker[0].filename == __file__
assert app["key"] == "value"
with pytest.warns(
UserWarning, match=r"web_advanced\.html#application-s-config"
) as checker:
# Warning for __getitem__
assert app["key"] == "value"
assert checker[0].filename == __file__
with pytest.warns(
UserWarning, match=r"web_advanced\.html#application-s-config"
) as checker:
# Warning for get
assert app.get("key") == "value"
assert checker[0].filename == __file__


def test_app_get() -> None:
Expand Down