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
1.8k views
in Technique[技术] by (71.8m points)

python - How to resolve "ValueError: attempted relative import beyond top-level package"

I have the following problem with my project, help me please! Here is the structure of my package:

/pkg

/pkg/__init__.py
/pkg/sub1/__init__.py
/pkg/sub2/__init__.py

/pkg/sub1/foo1.py
/pkg/sub2/foo2.py

Here is implementation of foo1.py:

from ..sub2 import foo2

def f():
    print("Hello!")

When I run foo1 I get error: ValueError: attempted relative import beyond top-level package.

I can solve it doing the following adjustment:

import sys
import os
sys.path.append(os.path.abspath(os.path.pardir))

from sub2 import foo2
def f():
    print("Hello!")

But I wonder if there is a way to do it without importing sys and appending parent directory in it.

I heard that if I had .py file '/pkg/start.py' for example which called my foo1 module, then two dots would work. However, is there any way to call foo2 from foo1 directly?

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

It seems to me, that without adding pkg to my PATH it is impossible to import modules from sub2 in sub1. Here is explanation why:

Relative imports use a module's name attribute to determine that module's position in the package hierarchy. If the module's name does not contain any package information (e.g. it is set to 'main') then relative imports are resolved as if the module were a top level module, regardless of where the module is actually located on the file system.

Here is official python web site, where it is explained


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

...