Why does pycharm typing not recognize recursive type aliases
Answered
Well I'm defining a type alias:
from __future__ import annotations
from typing import TypeAlias
BaseTy = str | int | float | bool | None
GenericJsonTy: TypeAlias = dict[str, GenericJsonTy] | list[GenericJsonTy] | BaseTy
simple_value: GenericJsonTy = 123
complex_test: GenericJsonTy = {
"a": {"b": 1},
"c": ["hello", {"a": 3}],
"d": 5,
"e": None
}
class MyClass:
pass
m = MyClass()
illegal: GenericJsonTy = {
"a": m
}
However pycharm gives the error: “Unresolved reference 'GenericJsonTy' ”
I could use the old way: by placing `GenericJsonTy: TypeAlias = dict[str, “GenericJsonTy”] | list["GenericJsonTy"] | BaseTy
However now pycharm just sees it as “Any”.
this is with pycharm 2023.3.6. Running pythong 3.11.
This is correctly working as shown on mypy: https://mypy-play.net/?mypy=latest&python=3.12&gist=bddab61d386a8ab62315897e987252d9
Please sign in to leave a comment.
As Python 3.11 itself requires string annotations for recursive type aliases,
GenericJsonTyis referenced before being fully defined, causing the mentioned warningPython 3.12 should solve this issue with PEP 695, allowing recursive type aliases. Did you try using it?
Having the same issue with python 3.12
1. When hovering over
fields, PyCharm (2024.3.3) shows type oflist[str | dict[str, Any]].2. PyCharm doesn't warn that
{"x": “y”}is invalid.