python - 如何在 Python 3.7 中构建相对导入?
问题描述
我发现自己处于导入错误的境地,我以为我已经过去了。我在 Windows 10 上的 VSCode 中运行 Python 3.7.4。事不宜迟。这是我的文件夹和文件结构,从文件夹 crypto_code 开始:
/crypto_code:
__init__.py (blank)
/crypto_driver:
__init__.py (blank)
crypto_balances.py
/crypto_exchg:
__init__.py (blank)
exchg_lens.py
bittrex_lens.py
coinbase_lens.py
文件 coinbase_lens.py 的顶部:
import exchg_lens
文件顶部crypto_balances.py:
import sys
sys.path.append('..')
from crypto_exchg import coinbase_lens
运行 coinbase_lens 作为主要导入 exchg_lens 没有错误。
运行 crypto_balances.py 似乎可以识别路径/结构,但会抛出“ModuleNotFoundError”:没有名为“exchg_lens”的模块。
任何帮助将不胜感激。提前致谢。
解决方案
这也是我觉得很麻烦的一个问题。我有一个有效的设置,避免弄乱它。然而,这是一个很好的做法(对我来说)所以......
作为起始位置,我建议放弃import sys
and sys.path.append
。这些是掩盖问题的技巧。如果您使用 linter(我使用的是 flake8),那么它会抱怨sys.path.append
出现在之前imports
,值得尊重 linter 不喜欢的东西。
我认为开始的问题是,您是在编写模块还是程序。重组您的文件夹以提供明确的区别。
/
program.py
/crypto
__init__.py (empty)
/driver
__init__.py (empty)
crypto_balances.py
/exchg
__init__.py (empty)
coinbase_lens.py
exchg_lens.py
/test
__init__.py (empty)
test_coinbase_lens.py
程序.py
from crypto.driver import crypto_balances
from crypto.exchg import coinbase_lens, exchg_lens
加密余额.py
from ..exchg import coinbase_lens
print('crypto_balances')
coinbase_lens.py
from . import exchg_lens
print('coinbase_lens')
exchg_lens.py
print('exchg_lens')
从 / 文件夹运行时会产生
python .\program.py
exchg_lens
coinbase_lens
crypto_balances
当然,您应该有一个测试框架来在您的模块上运行测试。测试文件有以下内容。Pytest 成功找到(并运行)以下测试。
from crypto.exchg import coinbase_lens
def test():
assert True
稍后......您可以查看包__init__.py
并添加导入并__all__
在那里允许命名空间管理。很容易稍后添加。
编辑添加
感觉就像我错过了一个值得包括的有用点。\crypto\__init__.py
并且program.py
可以进行更改以允许您管理模块的名称空间在程序中的显示方式。
__init__.py
变成
from crypto.driver import crypto_balances
from crypto.exchg import coinbase_lens, exchg_lens
__all__ = [
"crypto_balances",
"coinbase_lens", "exchg_lens"
]
program.py 现在是...
from crypto import crypto_balances
from crypto import coinbase_lens, exchg_lens