你如何为 Python 中的类型起别名?

How do you alias a type in Python?

在某些(主要是函数式)语言中,您可以这样做:

type row = list(datum)

type row = [datum]

这样我们就可以构建这样的东西:

type row = [datum]
type table = [row]
type database = [table]

Python有没有办法做到这一点?您可以使用 类 来完成它,但是 Python 有很多功能方面,所以我想知道是否可以用更简单的方法来完成它。

从 Python 3.5 开始,您可以使用 typing 模块。

引用文档, 类型别名是通过将类型分配给别名来定义的:

Vector = List[float]

要了解有关 Python 中强制类型的更多信息,您可能需要熟悉 PEP:PEP483 and PEP484

Python 历史上使用的是鸭子类型而不是强类型,并且在 3.5 版本之前没有内置的强制类型方式。

@Lukasz 接受的答案是我们大部分时间所需要的。但是对于您需要别名本身是不同类型的情况,您可能需要使用 typing.NewType ,如此处所述:https://docs.python.org/3/library/typing.html#newtype

from typing import List, NewType

Vector = NewType("Vector", List[float])

一个特殊的用例是如果您正在使用 injector 库并且您需要注入别名的新类型而不是原始类型。

from typing import NewType

from injector import inject, Injector, Module, provider

AliasRawType = str
AliasNewType = NewType("AliasNewType", str)


class MyModule(Module):
    @provider
    def provide_raw_type(self) -> str:
        return "This is the raw type"

    @provider
    def provide_alias_raw_type(self) -> AliasRawType:
        return AliasRawType("This is the AliasRawType")

    @provider
    def provide_alias_new_type(self) -> AliasNewType:
        return AliasNewType("This is the AliasNewType")


class Test1:
    @inject
    def __init__(self, raw_type: str):  # Would be injected with MyModule.provide_raw_type() which is str. Expected.
        self.data = raw_type


class Test2:
    @inject
    def __init__(self, alias_raw_type: AliasRawType):  # Would be injected with MyModule.provide_raw_type() which is str and not MyModule.provide_alias_raw_type() which is just a direct alias to str. Unexpected.
        self.data = alias_raw_type


class Test3:
    @inject
    def __init__(self, alias_new_type: AliasNewType): # Would be injected with MyModule.provide_alias_new_type() which is a distinct alias to str. Expected.
        self.data = alias_new_type


injector = Injector([MyModule()])
print(injector.get(Test1).data, "-> Test1 injected with str")
print(injector.get(Test2).data, "-> Test2 injected with AliasRawType")
print(injector.get(Test3).data, "-> Test3 injected with AliasNewType")

输出:

This is the raw type -> Test1 injected with str
This is the raw type -> Test2 injected with AliasRawType
This is the AliasNewType -> Test3 injected with AliasNewType

因此,要在使用 injector 库时正确注入正确的提供程序,您需要 NewType 别名。

自 Python 3.10 起,TypeAlias 注释在 typing 模块中可用。

用于显式表示赋值完成生成类型别名。例如:

Point: TypeAlias = tuple[float, float]
Triangle: TypeAlias = tuple[Point, Point, Point]

您可以在介绍它的 PEP 613 上阅读有关 TypeAlias 注释的更多信息。