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

python - 'Attempted relative import in non-package' although packages with __init__.py in one directory

I have a module named extended.py which contains the following line:

from .basic import BasicModule

and the file basic.py resides in the same directory as does __init__.py. However, when I try to run it as:

python extended.py

I get the error:

ValueError: Attempted relative import in non-package

Also adding the line:

from __future__ import absolute_import

does not solve the problem. Maybe I am too tired to see the obvious - but I don't see the problem here.

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

Relative imports only work for packages, but when you importing in extended.py you are running a top-level module instead.

The current directory may hold a __init__.py file but that doesn't make exended.py part of a package yet.

For something to be considered a package, you need to import the directory name instead. The following would work:

main.py

packagename
    __init__.py
    basic.py
    extended.py

then in main.py put:

import packagename.extended

and only then is extended part of a package and do relative imports work.

The relative import now has something to be relative to, the packagename parent.


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

Just Browsing Browsing

[2] html - How to create even cell spacing within a

1.4m articles

1.4m replys

5 comments

57.0k users

...