0

I'm just learning python, coming from a C# & Java background, and I'm pretty confused by the import system. Just trying to run a simple test for learning purposes, but getting an error AttributeError: module 'app' has no attribute 'example'

See code below, can someone explain why the error is thrown? I only seem to encounter this issue when there's a package inside a package, as seen in the instance of package "example" contained inside package "app"

run.py

import app

app/__init__.py

import app.example

app/example/__init__.py

import app.example.a

app/example/a.py

import app.example.b
print("TESTING: " + str(app.example.b)) #error is thrown on this line

app/example/b.py

print("LOADED B")

Error Thrown:

"C:\Program Files\Python 3.5\npwc-services\Scripts\python.exe" C:/Users/xxxxxxxx/PycharmProjects/untitled1/run.py
Traceback (most recent call last):
LOADED B
  File "C:/Users/xxxxxxxx/PycharmProjects/untitled1/run.py", line 1, in <module>
    import app
  File "C:\Users\xxxxxxxx\PycharmProjects\untitled1\app\__init__.py", line 1, in <module>
    import app.example
  File "C:\Users\xxxxxxxx\PycharmProjects\untitled1\app\example\__init__.py", line 1, in <module>
    import app.example.a
  File "C:\Users\xxxxxxxx\PycharmProjects\untitled1\app\example\a.py", line 2, in <module>
    print("TESTING: " + str(app.example.b))
AttributeError: module 'app' has no attribute 'example'

Process finished with exit code 1

Directory Structure:

enter image description here

3
  • 1
    Try import .example in app/__init__.py, and follow this with other modules and packages as well. You want relative, not absolute imports inside a package. Commented Nov 21, 2015 at 7:00
  • Thanks I didn't know relative imports were possible till you mentioned it, but the exact syntax you provided didn't work for me with Python 3. I had to do something like this instead: from .example.app import a Commented Dec 13, 2015 at 3:00
  • correction, i ended up using from . import example which seems to be directly equivalent to what you provided in your comment. Commented Dec 13, 2015 at 3:21

1 Answer 1

2

run.py

import app

app/init.py

from .example.app import a # or b or ...
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.