0

My directory structure is like this:

app/
-sub1/
  -sub1_1/
  -sub1_2/
  -sub1_3/
-sub2
 -class1.py
-app.py

I am running a flask app which is trying to execute app.py from the app folder. I want to import the classes from files inside sub1 in class files inside sub2.

I want to do this without setting sys.path

Update: I have _ init _.py in all folder levels

1 Answers1

0

If you're running app.py, the app directory is your module root, you could just use

from sub2 import class1

There is also relative imports:

from ..sub2 import class

for modules located in sub2/sub2_N it'll be from ...sub2.

Note: relative imports won't work in Python 2.6 and 2.7 (2.5- do not have this) unless you add this line to the top of file:

from __future__ import absolute_imports
bakatrouble
  • 1,746
  • 13
  • 19
  • 1
    This is wrong. You need `from sub1.sub1_1 import class1` instead. With your code you trying to import the _module_ `class1` from the package `sub2` not the class `class1`. – Christian Dean Jun 29 '17 at 23:33
  • @ChristianDean How should I do the import of class1 inside sub1.sub1_1 in a file inside sub2 – Sriram Sitharaman Jun 29 '17 at 23:35
  • @Sriram You would need to do from `.sub1 import * `... but you need to have an `__init__.py` file inside `sub1` or else it won't be considered a valid submodule. – cs95 Jun 29 '17 at 23:38
  • the `__init__.py` doesn't need to have anything it in, it just needs to be there. – Coolq B Jun 29 '17 at 23:39
  • @CoolqB Actually, in Python 3 you are no longer required to create an `__init__.py` file for Python to recognize a folder as a package. OTHO, you may want to add one anyway for Python 2 compatibility. – Christian Dean Jun 29 '17 at 23:40