Использование type.overload в __getitem__ с PyCharm - PullRequest
0 голосов
/ 11 июля 2020

Я пытаюсь заставить работать проверку типов в PyCharm для метода __getitem__. Я попытался сделать это с помощью декоратора typing.overload, чтобы указать тип возвращаемого значения для разных входных строк. Это правильно работает для «обычных» методов, но не для __getitem __.

При проверке с помощью mypy (python3 -m mypy example.py) ошибки обнаруживаются правильно, поэтому проблема заключается в проверке типов 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"

Есть ли способ исправить это в PyCharm? Или есть другой способ записать подсказки типа, чтобы PyCharm их понимал? Я использую Pycharm 2020.1.3 и python3 .7, если это важно.

Вот пример кода:

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)

1 Ответ

0 голосов
/ 13 июля 2020

Это известная ошибка, проголосуйте за https://youtrack.jetbrains.com/issue/PY-39990 (большой палец вверх рядом с названием проблемы)

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...