如何在 Python 中为类型添加别名?

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

在某些(主要是函数式)语言中,您可以执行以下操作:

type row = list(datum)

type row = [datum]

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

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

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

python alias type-hinting python-typing
4个回答
157
投票

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

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

Vector = List[float]

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

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


46
投票

自 Python 3.10 起,typing 模块中提供了

TypeAlias
注释。

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

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

您可以在介绍它的

PEP 613
上阅读有关 TypeAlias 注释的更多信息。


27
投票

@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
别名。


3
投票

Python 3.12(尚未发布最终版本)包含PEP 695:类型参数语法的实现,它提供了使用

type
语句声明类型别名的新方法(类似于TypeScript)。

type Point = tuple[float, float]

类型别名也可以是通用的。

type Point[T] = tuple[T, T]
© www.soinside.com 2019 - 2024. All rights reserved.