Skip to content

Commit

Permalink
Emit UserWarning when accessing Application items by str
Browse files Browse the repository at this point in the history
  • Loading branch information
cdce8p committed Aug 25, 2023
1 parent cf97e5b commit 4f7215d
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 1 deletion.
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

0 comments on commit 4f7215d

Please sign in to comment.