python - 工厂方法返回值的类型提示?
问题描述
我想知道在 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)
解决方案
我不确定下面的可运行代码是否与您的用例匹配,但如果匹配,则可以通过使用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'
推荐阅读
- sql - “自联接”时如何从SQL中的多个表中选择*?
- apache-kafka - KStreams 加入计算
- swift5 - Xcode12.5 - 在这种情况下,“FileManager”对于类型查找不明确
- ssl - 通配符 SSL 证书不适用于子域的某些子目录
- python - 如何在 MongoDB 中获取最近插入的文档及其所有字段?
- c# - 为什么实体框架没有映射我订单中的客户实体?
- php - 从 Explode 字符串数组中获取要比较的值
- python - 如何仅向授权用户添加评论?
- apex - 在 SOQL 中,我如何获得组数的平均值?
- alpine.js - AlpineJS:如何将 x-for 变量传递给 x-data 函数