简体   繁体   English

在 __getitem__ 上使用 type.overload 和 PyCharm

[英]Using type.overload on __getitem__ with PyCharm

I'm trying to get type checking to work in PyCharm for the __getitem__ method.我试图让类型检查在 PyCharm 中为 __getitem__ 方法工作。 I tried to do this with the typing.overload decorator to specify a return type for different input strings.我尝试使用 typing.overload 装饰器来为不同的输入字符串指定返回类型。 This works correctly for 'normal' methods but not for __getitem__.这适用于“正常”方法,但不适用于 __getitem__。

When checking with mypy ( python3 -m mypy example.py ) the errors are detected correctly so the problem lies with the typechecker of PyCharm.使用 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"

Is there a way to fix this in PyCharm?有没有办法在 PyCharm 中解决这个问题? Or is there another way to write down the type hints so PyCharm understands it?还是有另一种方法来写下类型提示以便 PyCharm 理解它? I'm using Pycharm 2020.1.3 and python3.7 if that's important.如果这很重要,我正在使用 Pycharm 2020.1.3 和 python3.7。

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)这是一个已知的错误,请投票给https://youtrack.jetbrains.com/issue/PY-39990 (在问题标题附近竖起大拇指)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM