Mypy:转换元组值

发布于 2025-01-15 08:28:34 字数 412 浏览 3 评论 0原文

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

小嗲 2025-01-22 08:28:34

使用 typing.cast 断言 parameters 的类型为 tuple[int|str,...]

parameters = tuple(map(int, typing.cast(tuple[int|str,...], parameters)))

您也可以考虑使用 type.overload 将签名分成两个更简单的签名。

from typing import overload, Literal

@overload
def my_function(key, parameters: tuple[int|str, ...]) ->  None:
    ...

@overload
def my_function(key, parameters: tuple[MyClass,...]) -> None:
    ...


def my_function(key, parameters):
    if key == "id":
       parameters = tuple(map(int, parameters))

Use typing.cast to assert that parameters has type tuple[int|str,...]:

parameters = tuple(map(int, typing.cast(tuple[int|str,...], parameters)))

You might also consider using typing.overload to separate the signature into two simpler signatures.

from typing import overload, Literal

@overload
def my_function(key, parameters: tuple[int|str, ...]) ->  None:
    ...

@overload
def my_function(key, parameters: tuple[MyClass,...]) -> None:
    ...


def my_function(key, parameters):
    if key == "id":
       parameters = tuple(map(int, parameters))
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文