gpt4 book ai didi

python - 类型错误 : 'ABCMeta' object is not subscriptable on Callable

转载 作者:行者123 更新时间:2023-12-04 13:09:22 27 4
gpt4 key购买 nike

我对 python 3.8 和 mypy 协同工作的方式有疑问。考虑这个代码:

from collections.abc import Callable

def feeder(get_next_item: Callable[[], str]) -> str:
return get_next_item()
虽然 mypy 批准此代码,但使用 python 3.8 运行它会产生错误
Traceback (most recent call last):
File "mypytest.py", line 3, in <module>
def feeder(get_next_item: Callable[[], str]) -> str:
TypeError: 'ABCMeta' object is not subscriptable
所以,让我们试试别的:
from collections.abc import Callable
def feeder(get_next_item: Callable) -> str:
return get_next_item()
此时python3.8会运行正常,但是mypy会说
mypytest.py:4: error: Returning Any from function declared to return "str"
除了在返回时使用 #type: ignore 之外,有没有办法摆脱这个陷阱?
提前致谢

最佳答案

谢谢XtianP。只是为了记录,这段代码对我来说效果很好

from typing import Callable

def feeder(get_next_item: Callable[[], str]) -> str:
return get_next_item()

print( feeder(lambda : 'Hi man') )

关于python - 类型错误 : 'ABCMeta' object is not subscriptable on Callable,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67295757/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com