繁体   English   中英

类型提示工厂方法的返回值?

[英]type hint for return value of a factory method?

我想知道在Python 3.6+中为Factory方法执行类型提示的正确方法。 理想情况下,我想使用union,但是我从一个自动生成的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来定义返回类型来处理这种情况。

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'

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM