Sam
Sam

Reputation: 2605

Import Python module from different folders

I see the question I am going to ask is a very trivial one and has been asked and consequently answered by many. I have looked through the solution provided for the problem, however I don't see the solution to work in my case.

I have the following directory hierarchy.

----a
-------__init__.py
--------------aa
------------------aa.py
------------------__init__.py
--------------bb
------------------bb.py
------------------__init__.py
-------a.py

I would like to do the following.

  1. To import bb.py and aa.py from the file a.py-- accomplished by using __init__.py in each folder directory
  2. TO import bb.py from aa.py (Doesn't work)
  3. TO import a.py from aa.py (Doesn't work)

By looking at many solutions I have placed the __init__.py file inside every folder directory.

I used:

import imp

foo = imp.load_source('module.name', 'path to the file') 

This worked, but since the path has to be hard-coded I am not sure if this will be a viable solution in my case

Currently I am doing the imports by adding the path to the sys directories. I'd like a solution that's more dynamic.

The folder hierarchy of my project goes deep to 6-7 levels sub-directories and I need a solution to import a module at level 1 from level 7.

I'll be glad if somebody could point out what I am missing.

Upvotes: 2

Views: 2091

Answers (1)

lesnik
lesnik

Reputation: 2757

What's the entry point of your application? If, for example, you start from command line the aa.py file, you are not lucky.

"Guido views running scripts within a package as an anti-pattern" (rejected PEP-3122)

The entry point of you package should be somewhere in the root of the package. In your case it's a file a.py. From out there you import some internal modules as usual:

# contents of a.py
from aa import a

Now about the imports from within your package.

Let's say there is one more file aa1.py in the same directory as aa.py. To import it from aa.py you can use relative import feature

# contents of aa.py
from . import aa1

Here . means "in the same directory".

Other examples:

# contents of aa.py
from .. import a  # here .. means "one level above"
from ..bb import bb  # this will import your bb.py module

Please note, that all that imports will fail if for example you run from command line directly aa.py!

UPDATE:

. and .. in above examples are NOT names of directories. This is python syntax to say "same level", "one level above", etc. If you need to import from 3 levels above you should write:

from .... import my_module

Upvotes: 1

Related Questions