如何"type"随机包return

How to "type" random package return

我正在构建一个 API 以允许在我正在处理的应用程序中使用插件。我正在使用 importlib.import_module 导入插件。显然我不知道要提前导入哪些模块。有没有办法在我用于导入的方法中将 return 类型识别为通用模块?

def import_plugin(plugin_name: str) -> <Some generic module type>:
    # conditional tests here...
    return importlib.import_module("plugins.{}".format(plugin_name))

Python 使用 duck typing,所以我建议假设它是一个模块,如果不是,则让用户处理它。如果你真的想获得类型,请使用 types.ModuleType 作为 khelwood said.

模块的类型由 types 模块中的 types.ModuleType 给出。

import types
type(types) is types.ModuleType
# => True