Mypy:转换元组值
def my_function(key, parameters: tuple[int | str, ...] | tuple[MyClass, ...]) -> None
if key == "id":
parameters = tuple(map(int, parameters))
最后一行提出了
Argument 1 to "map" has incompatible type "Type[int]"; expected "Callable[[Union[MyClass, int, str]], int]"mypy(error)
如何使这项工作有效?我如何告诉 mypy 我知道我的元组是由 int 和 str 组成的,但不是由 MyClass 组成?
def my_function(key, parameters: tuple[int | str, ...] | tuple[MyClass, ...]) -> None
if key == "id":
parameters = tuple(map(int, parameters))
The last line raises
Argument 1 to "map" has incompatible type "Type[int]"; expected "Callable[[Union[MyClass, int, str]], int]"mypy(error)
How do I make this work? How do I tell mypy that I know that my tuple is made of int and str but not MyClass?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
使用
typing.cast
断言parameters
的类型为tuple[int|str,...]
:您也可以考虑使用
type.overload
将签名分成两个更简单的签名。Use
typing.cast
to assert thatparameters
has typetuple[int|str,...]
:You might also consider using
typing.overload
to separate the signature into two simpler signatures.