1

I am trying to import python files which have been developed. Initially, when all files were in the same directory then I there was no problems with them. However, I decided to split projects to dedicated directories. After that, I am unable to import files anymore.

My file structure is similar to the following:

dirFoo\
    mainFoo1.py
dirFoo\
    mainFoo2.py
dirFooCommon\
    commonFoo.py
    commonFoo2.py

Initially, I was trying to change the import path of my mainFoo1.py and do: from dirFooCommon import commonFoo. However, that approach gave me the following error: ModuleNotFoundError: No module named 'common'.

Apart from that, I tried to use imp.load_source which seems that is working. Unfortunately, this is generating so additional problems. For example what if some of the commonFoo.py libraries must include others? In this case, each of them needs to use an absolute project path, which will be a problem when I will try to use common libraries in any other place.

Do you have an idea what should I do to include my common libraries to my main projects?

  • Look into [packages](https://docs.python.org/3/reference/import.html#packages). – martineau Oct 31 '19 at 16:30
  • Consider using \_\_init\_\_.py files to convert your Python files into modules and your directories into packages. https://stackoverflow.com/a/4116384/6014095 – Kronosfear Oct 31 '19 at 16:32
  • @Kronosfear I heard that in python > 3.3 you don't need doing __init__.py anymore. Also, I tried that and I have the following error: ModuleNotFoundError: No module named 'dirFooCommon' – Mateusz Paczyński Oct 31 '19 at 17:55

1 Answers1

0

You can use this folder structure that will allow you to call each package and module properly.

dirFoo\  <=== This is a package know 
    __init__.py 
    mainFoo1.py
dirFoo2\  <==== Change the name or you will have namespace issue
    __init__.py
    mainFoo2.py
dirFooCommon\ <=== This is a package know 
    __init__.py
    commonFoo.py
    commonFoo2.py

So in mainFoo1.pyyou can call commonFoo.pylike this

import sys
sys.path.append("/path/to/dirFooCommon")

from dirFooCommon import commonFoo

To replace sys.path.appendyou can also add the folder in your PYTHONPATH.

Florian Bernard
  • 2,561
  • 1
  • 9
  • 22