Search code examples
pythonpython-importpython-modulepythonpath

Import module from child folder to parent


So I looked at various similar problems asked here but so far nothing worked for me.

I have the following file architecture:

\folder
    __init__.py
    supClass.py
    script1.py
    \sub
        __init__.py
        script2.py

So in script2.py I try to import supClass. If I understood well what I read on related subjects, I have to specify that \folder is part of the PYTHONPATH.

So following examples I read, I ended up with this piece of code :

if __name__ == '__main__' and __package__ is None:
    from os import sys, path
    sys.path.append(path.dirname(path.dirname(path.abspath(__file__))))

from test_package import supClass

    a = supClass()
    a.print_sup()

But I get the following error :

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "C:\Python27\lib\site-packages\spyderlib\widgets\externalshell\sitecustomize.py", line 685, in runfile
    execfile(filename, namespace)
  File "C:\Python27\lib\site-packages\spyderlib\widgets\externalshell\sitecustomize.py", line 71, in execfile
    exec(compile(scripttext, filename, 'exec'), glob, loc)
  File "C:/Donnees/Programmes_Python/Developpement/Tests/test_package/sub/script.py", line 18, in <module>
    from test_package import supClass
ImportError: No module named test_package

I checked that \folder is now part of the PYTHONPATH by doing

import sys
print sys.path

in my console and it's ok. However, the __package__ variable stays set to None.

The error I get seems to say that my \folder is not a module. I don't see why, maybe I am confusing things between "package" and "module".

Anyway, if anyone has an idea, it'd be much appreciated!


Solution

  • The parent of \folder should be on PYTHONPATH. You can then do

    from folder import subClass 
    

    and

    from folder.sub import script2
    

    The reason the parent of folder should be on PYTHONPATH (and not folder itself), is because folder is your package, and to import folder Python needs to look in the directory containing folder.

    Note that executing scripts from sub-folders is problematic, but easy if you write a setup.py file. See my answer here stackoverflow.com/a/41201868/75103 for more info.