首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >PyCharm @重载运算符

PyCharm @重载运算符
EN

Stack Overflow用户
提问于 2017-03-03 23:21:45
回答 1查看 631关注 0票数 2

我尝试使用PyCharm中typing库中的@overload装饰器,收到警告,但代码运行良好。是我使用了错误的运算符,还是PyCharm只是错误地发出了警告?

我使用的是PyCharm社区2016.3.2和Python3.5.2。

代码语言:javascript
运行
复制
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?')))

更新:关于这个问题已经提交了一个bug:https://youtrack.jetbrains.com/issue/PY-22971

EN

回答 1

Stack Overflow用户

发布于 2020-04-06 22:53:47

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

这段代码去掉了两个Expected type 'List[str]', got 'str' instead警告,我没有Redeclared 'hello_world' usage警告。

代码语言:javascript
运行
复制
@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
        ]

这是PyCharm2019.2.5的更新版本,但我收到了相同的Expected type警告,所以这可能无关紧要。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/42582597

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档