我想知道在python 3.6 中使用工厂方法的类型提示的正确方法。理想情况下,我想使用联合,但是我正在从自动生成的Protobuf模块中导入A,其中其中有大量不同的类别。在使用类型提示时处理这种情况的最佳方法是什么?
我目前有类似的东西:
from testing import test as t
def generate_class(class_type: str) -> # What should go here?
if class_type in t.__dict__:
return t.__dict__[class_type]
ex_msg = "{} not found in the module library".format(class_type)
raise KeyError(ex_msg)
我不确定下面的可运行代码与您的用例匹配,但是如果这样做,则可以通过使用TypeVar
来定义返回类型来处理这种情况。
TypeVar
在PEP 484中描述 - 键入其Generics
部分中的提示。
from typing import TypeVar, Text
#from testing import test as t
t = type('test', (object,), {'Text': Text, 'bytes': bytes})
LibraryType = TypeVar(t.__dict__)
def generate_class(class_type: str) -> LibraryType:
if class_type in t.__dict__:
return t.__dict__[class_type]
ex_msg = "{} not found in the module library".format(class_type)
raise KeyError(ex_msg)
print("generate_class('Text'):", generate_class('Text')) # -> generate_class('Text'): <class 'str'>
print("generate_class('bytes'):", generate_class('bytes')) # -> generate_class('bytes'): <class 'bytes'>
print("generate_class('foobar'):", generate_class('foobar')) # -> KeyError: 'foobar not found in the module library'