我尝试使用PyCharm中typing
库中的@overload
装饰器,收到警告,但代码运行良好。是我使用了错误的运算符,还是PyCharm只是错误地发出了警告?
我使用的是PyCharm社区2016.3.2和Python3.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?')))
更新:关于这个问题已经提交了一个bug:https://youtrack.jetbrains.com/issue/PY-22971。
发布于 2020-04-06 22:53:47
重载函数应至少有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
]
这是PyCharm2019.2.5的更新版本,但我收到了相同的Expected type
警告,所以这可能无关紧要。
https://stackoverflow.com/questions/42582597
复制相似问题