Skip to content
Advertisement

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:UserspriperAppDataLocalProgramsPythonPython37python37.zip
C:UserspriperAppDataLocalProgramsPythonPython37DLLs
C:UserspriperAppDataLocalProgramsPythonPython37Lib
C:UserspriperAppDataLocalProgramsPythonPython37
C:UserspriperAppDataLocalProgramsPythonPython37Libsite-packages

    C:UserspriperAppDataLocalProgramsPythonPython37libsite-packageswin32
C:UserspriperAppDataLocalProgramsPythonPython37libsite-packageswin32lib
C:UserspriperAppDataLocalProgramsPythonPython37libsite-packagesPythonwin
C:WindowsMicrosoft.NETFramework64v4.0.30319
C:UserspriperDesktopdumdumfoo

Traceback

ModuleNotFoundError no module named ‘foo’ in foo6.py…Line 12

Advertisement

Answer

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:UserspriperDesktopdumdum to sys.path.

If you start the python program inside the folder dumdumfoofoo6, then os.getcwd() would give you dumdumfoofoo6. 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 dumdumfoo and not dumdum as it should be.

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement