Search code examples
pythonimportparentsys

Cannot get an absolute import to work with python 3.7.0


I have a root folder called dumdum which contains an init and a folder called foo. Within foo are an ini and two modules, foo1 and foo6.

dumdum/

       __init__
       foo/

              __init__
              foo1
              foo6

I want foo6 to work when called on its own and when a main module in the root folder dumdum calls it, so I have been trying to work out how to get foo6 to work in all cases, i.e. I want foo6 to work on its own and when it is not the main file. I run foo6 from an IDE. Foo6 calls foo1, but when I do that I get an error :

ModuleNotFoundError no folder named 'foo'

As foo is the parent folder for both foo1 and foo6 I can't understand why this is happening.

foo1.py:

def printy(msg):
    print(msg)


def printing_mystr(mystr):
    printy(mystr)
    
if __name__ == "__main__":
    print(__name__)
    printing_mystr(r"I am a string in foo_1")

foo6.py

import sys, pathlib
import os

if __name__ == "__main__":
    # if foo is the root folder
    print(os.getcwd())
    print(str(pathlib.Path(__file__).parent))
    sys.path.append(str(pathlib.Path(__file__).parent))
    #for i in sys.path:
        #print(i)
    
    from foo.foo1 import printy, printing_mystr


if __name__ == "__main__":
    print(__name__)
    printing_mystr("Oh I am a string passed into foo_1")

when I run:

import sys

for i in sys.path:
    print(i)

I get:

    C:\Users\priper\AppData\Local\Programs\Python\Python37\python37.zip
C:\Users\priper\AppData\Local\Programs\Python\Python37\DLLs
C:\Users\priper\AppData\Local\Programs\Python\Python37\Lib
C:\Users\priper\AppData\Local\Programs\Python\Python37
C:\Users\priper\AppData\Local\Programs\Python\Python37\Lib\site-packages

    C:\Users\priper\AppData\Local\Programs\Python\Python37\lib\site-packages\win32
C:\Users\priper\AppData\Local\Programs\Python\Python37\lib\site-packages\win32\lib
C:\Users\priper\AppData\Local\Programs\Python\Python37\lib\site-packages\Pythonwin
C:\Windows\Microsoft.NET\Framework64\v4.0.30319\
C:\Users\priper\Desktop\dumdum\foo

Traceback

ModuleNotFoundError no module named 'foo' in foo6.py...Line 12


Solution

  • When importing modules without any further path information you need to have the path directly beneath the module location as a member of sys.path. In your case, add C:\Users\priper\Desktop\dumdum to sys.path.

    If you start the python program inside the folder dumdum\foo\foo6, then os.getcwd() would give you dumdum\foo\foo6. Therefore, your import from foo.foo1 import printy, printing_mystr won't work. Even adding pathlib.Path(__file__).parent is not enough, because this is dumdum\foo and not \dumdum as it should be.