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

问题描述 投票:0回答:2

我不知道如何在 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 python-3.x casting type-hinting
2个回答
0
投票

这看起来有点麻烦,但是你可以让它在一些重载的情况下工作。请注意,您必须从较窄的类型开始,否则永远无法到达并且 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"

0
投票

您可以使用

Any
TypeVar

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

© www.soinside.com 2019 - 2024. All rights reserved.