PyCharm @overload运算符

问题描述 投票:1回答:1

我正在尝试使用PyCharm中@overload库中的typing装饰器,但收到警告,但代码运行正常。我使用的操作员是否错误,还是PyCharm只是错误地发出警告?

我正在使用PyCharm Community 2016.3.2和Python 3.5.2。

from typing import Optional, List, overload


@overload
def hello_world(message: str) -> str:
    pass

# Warning: Redeclared 'hello_world' usage defined above without usage
def hello_world(message: str, second_message: Optional[str] = None) -> List[str]:
    if second_message is None:
        # Warning: Expected type 'List[str]', got 'str' instead
        return message
    else:
        return [
            message,
            second_message
        ]


def count_single_message(message: str) -> int:
    return len(message)


def count_multiple_message(messages: List[str]) -> int:
    total = 0
    for message in messages:
        total += len(message)

    return total


print(
    count_single_message(
        # Warning: Expected type 'List[str]', got 'str' instead
        hello_world('hello world')))
print(
    count_multiple_message(
        hello_world('hello world', 'how are you?')))
python python-3.x pycharm overloading typing
1个回答
0
投票

重载函数应至少具有2个重载签名和1个没有类型提示的实现。我认为这是各种类型检查器(特别是mypy)的要求。

此代码摆脱了两个Expected type 'List[str]', got 'str' instead警告,我没有Redeclared 'hello_world' usage警告。

@overload
def hello_world(message: str) -> str:
    ...

@overload
def hello_world(message: str, second_message: Optional[str] = None) -> List[str]:
    ...

def hello_world(message, second_message=None):
    if second_message is None:
        return message
    else:
        return [
            message,
            second_message
        ]

这是最近发布的Pycharm 2019.2.5,但我有相同的Expected type警告,所以可能没关系。

© www.soinside.com 2019 - 2024. All rights reserved.