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

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

Problem importing nested package in Python

问题

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

.
└── src/
    ├── main.py
    ├── PackageA/
    │   ├── __init__.py
    │   ├── logic.py
    │   ├── SubPackageA1/
    │   │   ├── __init__.py
    │   │   └── util.py
    │   └── SubPackageA2/
    │       ├── __init__.py
    │       └── otherUtil.py
    └── PackageB/
        ├── __init__.py
        └── helpers.py

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

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

英文:

Based from a project with the following structure:

.
└── src/
    ├── main.py
    ├── PackageA/
    │   ├── __init__.py
    │   ├── logic.py
    │   ├── SubPackageA1/
    │   │   ├── __init__.py
    │   │   └── util.py
    │   └── SubPackageA2/
    │       ├── __init__.py
    │       └── otherUtil.py
    └── PackageB/
        ├── __init__.py
        └── 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中的导入应该像这样工作:

from PackageA.SubPackageA2 import otherUtil

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

from PackageB import helpers

print(helpers.HELPERS_UTIL)

otherUtil.py:

OTHER_UTIL = 'test'

helpers.py:

from PackageA.SubPackageA2 import otherUtil

HELPERS_UTIL = otherUtil.OTHER_UTIL
英文:

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

from PackageA.SubPackageA2 import otherUtil

Yes, I checked it, main.py:

from PackageB import helpers

print(helpers.HELPERS_UTIL)

otherUtil.py:

OTHER_UTIL = 'test'

helpers.py

from PackageA.SubPackageA2 import otherUtil

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:

确定