gpt4 book ai didi

python - 仅从具有 `importlib` 的 Python 模块导入特定类

转载 作者:行者123 更新时间:2023-12-04 17:07:55 27 4
gpt4 key购买 nike

如何使用 Python 模块的路径仅导入特定类?
我需要使用文件路径从 Python 文件导入特定的类。我无法控制该文件及其完全在我的包之外。
文件.py:

class Wanted(metaclass=MyMeta):
...

class Unwanted(metaclass=MyMeta):
...
元类实现在这里不相关。但是,我会指出它是我的包裹的一部分,我可以完全控制它。
导入示例:
spec = importlib.util.spec_from_file_location(name='Wanted', location="path_to_module/mudule.py")
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)
这有效,并且 Wanted是进口的。问题是 Unwanted也是进口的。实际上,只要给 name 任何字符串值(包括一个空字符串),都是 WantedUnwanted从模块导入。
这与之前的示例具有相同的效果,其中 WantedUnwanted是进口的:
importlib.util.spec_from_file_location(name='random string', location="path_to_module/mudule.py")
我不是在寻找使用 importlib 的特定解决方案;任何合理的方式都可以。我要指出的是,我不需要在导入类时使用它,我只需要导入,我的元类会处理其余的。

最佳答案

如果我没记错的话,name 参数只是用来命名您要导入的模块。但是,更重要的是,当您导入任何模块时,您正在执行整个文件,这意味着在您的情况下这两个类都将被创建。你写了没有关系from file import Wanted , import file或使用任何其他形式的导入语句。

A Python program is constructed from code blocks. A block is a piece of Python program text that is executed as a unit. The following are blocks: a module, a function body, and a class definition.


来源: https://docs.python.org/3/reference/executionmodel.html#structure-of-a-program

关于python - 仅从具有 `importlib` 的 Python 模块导入特定类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70147659/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com