Python:如何使用相对导入导入包root [英] Python: How to import package root with relative imports
问题描述
我在python包的顶级__init__.py中定义了大量名称。我想使用 relative 导入来导入此命名空间,因为我不一定知道运行时的包名称(它甚至可能用作其他包的子包)。例如,请使用以下包:
I have a large number of names defined in the top-level __init__.py of a python package. I would like to use a relative import to import this namespace because I do not necessarily know the package name at runtime (it might even be used as a sub-package of some other package). For example, take the following package:
my_package/
__init__.py
a = 1
b = 2
...
my_module.py
from . import ??? as my_package
print(my_package.a)
如何修复my_module中的import语句这样print语句可以正常工作吗?我也宁愿避免。 import a,b,...
;我只想将整个包命名空间作为一个变量导入。
How shall I fix the import statement in my_module such that the print statement works correctly? I would also rather avoid from . import a, b, ...
; I just want the entire package namespace imported as one variable.
我试过。将__init__导入为my_package
,但在这种情况下, my_package
作为方法包装器导入,而不是模块。我也试过 my_module = __import __(__ package __)
,这只适用于my_package不是子包的情况。
I have tried from . import __init__ as my_package
, but in this case my_package
is imported as a method-wrapper, not a module. I have also tried my_module = __import__(__package__)
, which works only in the case that my_package is not a sub-package.
似乎应该有一个简单的答案..
It seems like there should be a simple answer to this..
推荐答案
你可以使用 __ package __
以了解包名称,并 importlib.import_module
;这适用于子包。
You can use __package__
to know the package name, and importlib.import_module
; This works for sub-packages.
import importlib
pkg = importlib.import_module(__package__)
print(pkg.a)
这篇关于Python:如何使用相对导入导入包root的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!