PyCharm's inspector doesn't use recursive type hinting

Answered

I'm currently using PyCharm on a project with type hinting (with Python 3.5+ syntax) and while using the json library I stumbled upon the need of a "recursive type hint", that is an hint which can hint at itself.

One of the easiest example would be a type as follow:

Recursive_int_list: type = List[Union[int, Recursive_int_list]]

Of course, that isn't valid Python syntax. But using the string syntax for type hinting forward reference (and if I understood this syntax properly), it is normally possible to do what I'd like - as shown below:

Recursive_int_list: type = List[Union[int, 'Recursive_int_list']]

However, if I try to do this in PyCharm, it seems the code inspector have trouble understanding what it means. the following simple code snippet shows the problem:

Recursive_int_list: type = List[Union[int, 'Recursive_int_list']]
myvar: Recursive_int_list = ['abc']

When I hover over myvar, the annotation box states "myvar: List[int] = ['abc']", without any error, which is quite a problem because, first, it lost a part the type hint (the 'Recursive_int_list' part, keeping only the int part) but even worse, it seems it totally set the inspector off as a string was accepted where an int or a list was wanted.

 

0
2 comments

I believe it's related to the following feature request https://youtrack.jetbrains.com/issue/PY-42947, please vote and feel free to leave comments.

0
Avatar
Permanently deleted user

It seems like it indeed, the problem is exactly the same I encountered while treating recursive dictionaries and list.

Thanks for the redirection, I'll vote for it.

0

Please sign in to leave a comment.