Why does pycharm typing not recognize recursive type aliases

已回答

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

0

As Python 3.11 itself requires string annotations for recursive type aliases, GenericJsonTy is referenced before being fully defined, causing the mentioned warning

Python 3.12 should solve this issue with PEP 695, allowing recursive type aliases. Did you try using it?

from __future__ import annotations

from typing import TypeAlias

type BaseTy = str | int | float | bool | None
type GenericJsonTy = dict[str, GenericJsonTy] | list[GenericJsonTy] | BaseTy

simple_value: GenericJsonTy = 123

complex_test: GenericJsonTy = {
    "a": {"b": 1},
    "c": ["hello", {"a": 3}],
    "d": 5,
    "e": None
}
0

Having the same issue with python 3.12

type Fields = list[str | dict[str, Fields]]

fields: Fields = [
    "id",
    {"stuff": {"x": "y"}},
]

 

1. When hovering over fields, PyCharm (2024.3.3) shows type of list[str | dict[str, Any]].

2. PyCharm doesn't warn that {"x": “y”} is invalid.

0

请先登录再写评论。