在某些(主要是函数式)语言中,您可以执行以下操作:
type row = list(datum)
或
type row = [datum]
这样我们就可以构建这样的东西:
type row = [datum]
type table = [row]
type database = [table]
有没有办法在Python中做到这一点?您可以使用类来完成此操作,但 Python 有相当多的功能方面,所以我想知道是否可以用更简单的方法来完成。
@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.12(尚未发布最终版本)包含PEP 695:类型参数语法的实现,它提供了使用
type
语句声明类型别名的新方法(类似于TypeScript)。
type Point = tuple[float, float]
类型别名也可以是通用的。
type Point[T] = tuple[T, T]