首页 > 解决方案 > 工厂方法返回值的类型提示?

问题描述

我想知道在 Python 3.6+ 中为工厂方法执行类型提示的正确方法。理想情况下,我想使用一个联合但是我从一个自动生成的 Protobuf 模块中导入一个,其中包含大量不同的类。在使用类型提示的同时处理这种情况的最佳方法是什么。

我目前有类似的东西:

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)

标签: pythonpython-3.6

解决方案


我不确定下面的可运行代码是否与您的用例匹配,但如果匹配,则可以通过使用TypeVar定义返回类型来处理这种情况。

TypeVarPEP 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'

推荐阅读