簡體   English   中英

在 __getitem__ 上使用 type.overload 和 PyCharm

[英]Using type.overload on __getitem__ with PyCharm

我試圖讓類型檢查在 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)

這是一個已知的錯誤,請投票給https://youtrack.jetbrains.com/issue/PY-39990 (在問題標題附近豎起大拇指)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM