在Python中导入嵌套包时出现问题。

huangapple go评论108阅读模式
英文:

Problem importing nested package in Python

问题

在具有以下结构的项目基础上:

  1. .
  2. └── src/
  3. ├── main.py
  4. ├── PackageA/
  5. ├── __init__.py
  6. ├── logic.py
  7. ├── SubPackageA1/
  8. ├── __init__.py
  9. └── util.py
  10. └── SubPackageA2/
  11. ├── __init__.py
  12. └── otherUtil.py
  13. └── PackageB/
  14. ├── __init__.py
  15. └── helpers.py

helpers.py文件中,是否可以导入otherutil.py包?

到目前为止,我尝试的所有组合都失败了。

英文:

Based from a project with the following structure:

  1. .
  2. └── src/
  3. ├── main.py
  4. ├── PackageA/
  5. ├── __init__.py
  6. ├── logic.py
  7. ├── SubPackageA1/
  8. ├── __init__.py
  9. └── util.py
  10. └── SubPackageA2/
  11. ├── __init__.py
  12. └── otherUtil.py
  13. └── PackageB/
  14. ├── __init__.py
  15. └── helpers.py

Project structure

It would be possible to import in the file helpers.py the package otherutil.py?

All the combinations I tried until now fail.

答案1

得分: 0

如果您的程序是从main.py执行的,helpers.py中的导入应该像这样工作:

  1. from PackageA.SubPackageA2 import otherUtil

是的,我检查了它,main.py:

  1. from PackageB import helpers
  2. print(helpers.HELPERS_UTIL)

otherUtil.py:

  1. OTHER_UTIL = 'test'

helpers.py:

  1. from PackageA.SubPackageA2 import otherUtil
  2. HELPERS_UTIL = otherUtil.OTHER_UTIL
英文:

If your program is executed from main.py the import in helpers.py should work like this:

  1. from PackageA.SubPackageA2 import otherUtil

Yes, I checked it, main.py:

  1. from PackageB import helpers
  2. print(helpers.HELPERS_UTIL)

otherUtil.py:

  1. OTHER_UTIL = 'test'

helpers.py

  1. from PackageA.SubPackageA2 import otherUtil
  2. HELPERS_UTIL = otherUtil.OTHER_UTIL

huangapple
  • 本文由 发表于 2023年1月9日 01:28:40
  • 转载请务必保留本文链接:https://go.coder-hub.com/75049934.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定