如何在Python中正确使用类型提示?

How to properly use type hints in Python?

提问人:Boris Mirzakhanyan 提问时间:9/28/2023 最后编辑:Boris Mirzakhanyan 更新时间:9/28/2023 访问量:80

问:

我不知道如何在我的type_casting函数中正确使用类型提示。

def type_casting(var, _type):
    if _type not in (str, int, float, bool):
        return Exception

    return _type(var)

assert type_casting("55", int) == 55
assert type_casting(55, str) == "55"

如何在Python中正确使用类型提示?

我想做这样的事情:

T = int | float | str | bool
def type_casting(var: Any, _type: Type[T]) -> T:
python-3.x 转换 类型提示

评论

0赞 KonstantinosKokos 9/28/2023
不确定操作员是否分布过来,可能更理智|Type[...]Type[int] | Type[float], ...
0赞 Boris Mirzakhanyan 9/28/2023
是的,这不是一个可行的选项。我只是写了我想收到的大致内容。

答:

1赞 Noé Duruz 9/28/2023 #1

这似乎有点麻烦,但您可以让它处理一些重载。请注意,您必须从较窄的类型开始,否则永远无法访问它,并且 MyPy 会抱怨它。

from typing import TYPE_CHECKING, Any, overload

T = int | float | str | bool


@overload
def type_casting(var: Any, type_: type[bool]) -> bool:
    ...


@overload
def type_casting(var: Any, type_: type[int]) -> int:
    ...


@overload
def type_casting(var: Any, type_: type[float]) -> float:
    ...


@overload
def type_casting(var: Any, type_: type[str]) -> str:
    ...


def type_casting(var: Any, type_: type[T]) -> T:
    if type_ not in (str, int, float, bool):
        raise Exception

    return type_(var)


my_int = type_casting(55, int)
my_float = type_casting(55, float)
my_str = type_casting(55, str)
my_bool = type_casting(55, bool)

if TYPE_CHECKING:
    reveal_type(my_int)  # note: Revealed type is "builtins.int"
    reveal_type(my_float)  # note: Revealed type is "builtins.float"
    reveal_type(my_str)  # note: Revealed type is "builtins.str"
    reveal_type(my_bool)  # note: Revealed type is "builtins.bool"

assert type_casting("55", int) == 55
assert type_casting(55, str) == "55"
2赞 Yuri R 9/28/2023 #2

您可以使用 和AnyTypeVar

from typing import TypeVar, Type, Any

T = TypeVar('T', int, float, str, bool)

def type_casting(var: Any, _type: Type[T]) -> T:
    if _type not in (str, int, float, bool):
        raise ValueError(f"Unsupported type {_type}")

    return _type(var)

你可以在这里参考 TypeVar

评论

0赞 Noé Duruz 9/28/2023
这比我的解决方案优雅得多!