[英]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 有很多功能方面,所以我想知道是否可以用更简单的方法来做。
来自@Lukasz 的公认答案是我们大部分时间都需要的。 但是对于您需要别名单独成为不同类型的情况,您可能需要使用typing.NewType
,如此处所述: https : typing.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是动态类型的。 尽管ŁukaszR.的回答对于类型提示目的是正确的(反过来可以用于静态分析和整理),但严格来说,您无需执行任何操作即可完成此工作。 只需像这样构造您的列表并将它们分配给变量:
foo_table = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
bar_table = ...
foo_database = [foo_table, bar_table, ...]
类型提示确实有用,因为它们可以帮助记录代码的行为方式,并且可以在静态和运行时对其进行检查。 但是,如果不方便,没有任何强迫您这样做的事情。
比如row = lambda datum: list(datum)
呢? 那里没有实类型自省支持,但是考虑到Python对鸭子类型的喜爱,这是一种非常简单的“别名”类型方法。 而且功能正常! 金田
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.