I'm trying to get type checking to work in PyCharm for the __getitem__ method. I tried to do this with the typing.overload decorator to specify a return type for different input strings. This works correctly for 'normal' methods but not for __getitem__.
When checking with mypy ( python3 -m mypy example.py
) the errors are detected correctly so the problem lies with the typechecker of PyCharm.
example.py:33: error: "List[Any]" has no attribute "split"
example.py:34: error: "str" has no attribute "append"
example.py:37: error: "List[Any]" has no attribute "split"
example.py:38: error: "str" has no attribute "append"
Is there a way to fix this in PyCharm? Or is there another way to write down the type hints so PyCharm understands it? I'm using Pycharm 2020.1.3 and python3.7 if that's important.
Here's the code example:
from typing import overload, List
from typing_extensions import Literal
class MyClass:
@overload
def __getitem__(self, item: Literal['str']) -> str: ...
@overload
def __getitem__(self, item: Literal['list']) -> List: ...
def __getitem__(self, item):
if item == 'str':
return ''
if item == 'list':
return []
@overload
def f(self, item: Literal['str']) -> str: ...
@overload
def f(self, item: Literal['list']) -> List: ...
def f(self, item):
if item == 'str':
return ''
if item == 'list':
return []
c = MyClass()
c['str'].split()
c['list'].split() # Should be detected as incorrect.
c['str'].append(None) # Should be detected as incorrect.
c['list'].append(None)
c.f('str').split()
c.f('list').split() # This is detected as incorrect.
c.f('str').append(None) # This is detected as incorrect.
c.f('list').append(None)
It is a known bug, please vote for https://youtrack.jetbrains.com/issue/PY-39990 (thumbs up near the issue title)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.