PyCharm @overload Operator

时间:2017-03-03 15:21:45

标签: python python-3.x pycharm overloading typing

我正在尝试使用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?')))

1 个答案:

答案 0 :(得分: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: str) -> 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警告,所以可能没关系。