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

craigrs84
  • 3,048
  • 1
  • 27
  • 34
  • 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. – Games Brainiac Nov 21 '15 at 07: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 – craigrs84 Dec 13 '15 at 03:00
  • correction, i ended up using from . import example which seems to be directly equivalent to what you provided in your comment. – craigrs84 Dec 13 '15 at 03:21

1 Answers1

2

run.py

import app

app/init.py

from .example.app import a # or b or ...
Thomas Anderson
  • 74
  • 1
  • 1
  • 9