By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
446,285 Members | 1,647 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 446,285 IT Pros & Developers. It's quick & easy.

A question about "Intra-package References"

ChrisWang
P: 9
Hi all,

I have a simple question about "Intra-package References"
There are two source files and __init__.py in package MyPkg shown below:

|-MyPkg
-__init__.py
-example.py
-test.py

example.py is like this:
Expand|Select|Wrap|Line Numbers
  1. a = 5
and test.py is like this:
Expand|Select|Wrap|Line Numbers
  1. from . import example
  2.  
  3. print example.a
While I executed test.py, python said "ValueError: Attempted relative import in non-package". Could anybody tell me what's wrong with the code. Thanks!
Dec 15 '08 #1
Share this Question
Share on Google+
3 Replies


bvdet
Expert Mod 2.5K+
P: 2,851
My limited understanding is that you cannot use relative imports in a top-level module. There does not appear to be anything wrong.

-BV
Dec 15 '08 #2

ChrisWang
P: 9
Thank you. I've got the answer why the error happened.

"Since the name of the main module is always "__main__", modules intended for use as the main module of a Python application should always use absolute imports."

So I made another main module with absolute imports, and also imports this test module. Everything is fine.

Thanks again for your help:)
Have a nice day!
Dec 16 '08 #3

bvdet
Expert Mod 2.5K+
P: 2,851
You are welcome, and thank you for the feedback ChrisWang.
Dec 16 '08 #4

Post your reply

Sign in to post your reply or Sign up for a free account.