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):
self.data = raw_type
class Test2:
@inject
def __init__(self, alias_raw_type: AliasRawType):
self.data = alias_raw_type
class Test3:
@inject
def __init__(self, alias_new_type: AliasNewType):
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
别名。
ID = int
这样行吗? - Charlie Parker