python 输入提示类型作为输入

python type hinting type as input

我想使用 python 类型提示并将参数定义为 datatype。最好的办法是只允许 strintfloatboolNone(但我猜这是 datatype,不是类型,我可以手动检查)。我该怎么做?


我有如下函数:

import typing

Savable = typing.Union[str, int, float, bool, None]
Datatype = type.Any # <- what should I use?

def save_variable_persistent(key: str, value: Savable, datatype: Datatype) -> bool:
    # save the variable in some way where I **have** to know the datatype, 
    # for reserving the space
    pass

def load_variable_persistent(key: str, datatype: Datatype):
    # load the value from some backend interface which **needs** to know the type
    pass

我不知道如何定义 Datatype 以仅允许类型。


我做了什么

想法 1(错误):使用 typing.Union[int, str, ...],但这没有意义,因为这将允许 int 和 str 的实例。这将使 datatypeSavable 相同,这是错误的。

思考2(错误):当我使用python并键入

>>> int
<class 'int'>

它说 intint-class (?) 的一个实例。所以我需要一个 typing. Union 允许 int-class 的实例加上 str-class 的实例等等(?)。但是 int-class 的实例是整数,所以是数字。 str class 的实例是字符串本身。另外,这意味着使用 typing. Union[int, str, ...] 所以我又回到等于 Savable

想法 3:在 python docs about typing at the section typing.Type 上它说,int 是一个 typing.Type。这意味着我应该使用 typing.Type 作为 Datatype。还有 type(int) == typing.Type returns True.

想法 4:使用 type(int) returns <class 'type'>。但是 typing.Type == type returns False.

3 和 4 让我觉得,typing.Typetype 都只是 classes,包含例如信息。 int 但不是 int 的 type/class。


那么,我应该使用什么? Datatype = typing.TypeDatatype = type 还是完全不同的东西?

您认为 typing.Type 是正确位置的直觉是正确的。这里的文档非常好,即使他们没有解释为什么 type!=typing.Type.

  • 如果您想允许任何类型,请使用 type(或等同于 TypeType[Any],即使 == 比较表明它们不同)。
  • 如果您想协变地允许任何一组固定类型,请使用 Type[Union[str, int, etc]]
  • 如果您想使用泛型,请使用 Type[T](例如 def foo(a: T, a_type: Type[T]))(如果您还不知道如何使用泛型,请查找 TypeVar)。