Gunther
Gunther

Reputation: 2645

Directory setup for python modules

I'm looking to create a python module with the following imports. However, I'm not sure how to go about structuring the files / directories to get the desired effect?

import one
from one import two
from one.two import three
from one.two.three import four

Obviously these imports wont exist in the same file like they are shown above, but I'm looking to have the flexibility to import in this way.

Upvotes: 1

Views: 90

Answers (3)

Kamyar Ghasemlou
Kamyar Ghasemlou

Reputation: 859

i hope this would help, for any module directory

__init__.py

file is needed, you may leave it empty but it is needed. for any other file create .py version of it, for example: import one.example would need an example.py file inside "one" directory. hope this is what you were looking for:

|__ one
     |
     |__ __init__.py
     |
     |__two
         |
         |__ __init__.py
         |
         |__three
              |
              |__ __init__.py
              |
              |__four
                  |
                  |__ __init__.py

Upvotes: 0

jeanluc
jeanluc

Reputation: 1708

What you have to do is set up your directory tree with regular folders first. So you would have folder three in folder two in folder one. Then in each folder place an empty python file called

__init__.py 

which will tell python to treat this as a package folder. It should then work the way you want it to.

Read more here: https://docs.python.org/3/tutorial/modules.html#packages

Upvotes: 0

suhailvs
suhailvs

Reputation: 21680

main/
    one/
        __init__.py
        two/
            __init__.py
            three.py

inside three.py create a function four, something like:

def four():
    print ('this is four')

Now add path of main directory to the PYTHON_PATH

Note: you need empty __init__.py files in every folder, so that python track those folders.

Upvotes: 1

Related Questions