A question about "Intra-package References"

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • ChrisWang
    New Member
    • Nov 2008
    • 9

    A question about "Intra-package References"

    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:
    Code:
    a = 5
    and test.py is like this:
    Code:
    from . import example
    
    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!
  • bvdet
    Recognized Expert Specialist
    • Oct 2006
    • 2851

    #2
    My limited understanding is that you cannot use relative imports in a top-level module. There does not appear to be anything wrong.

    -BV

    Comment

    • ChrisWang
      New Member
      • Nov 2008
      • 9

      #3
      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!

      Comment

      • bvdet
        Recognized Expert Specialist
        • Oct 2006
        • 2851

        #4
        You are welcome, and thank you for the feedback ChrisWang.

        Comment

        Working...