Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
293 views
in Technique[技术] by (71.8m points)

python - Relative importing modules from parent folder subfolder

Given a directory structure like this

/main/
/main/common/foo.py
/main/A/
/main/A/src/
/main/A/src/bar.py

How can I use Python's relative imports to import foo from bar? I've got a working solution by adding it to the path, but this is ugly. Is there a way to simply do with a single import in Python 2.7?

This is a more complex version of this question:

Importing modules from parent folder

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The correct relative import would be this:

from ...common import foo

However, relative imports are only meant to work within one package. If main is a package, then you can use relative imports here. If main is not a package, you cannot.

Thus, if you're running a script in /main/ and doing something like import A.src.bar, then that relative import will fail with "Attempted relative import beyond toplevel package". This is because the relative import is trying to import something outside of the toplevel package A.

However, if you're running a script in / and doing something like import main.A.src.bar, then that relative import will succeed because main is now a package. In that case, the following two would be equivalent:

from ...common import foo
from main.common import foo

To answer your comment: the meaning of the . doesn't change depending on where the script was run from, it changes depending on what the package structure is.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...