Search code examples
python-3.xpython-importrelative-import

Relative import of module in parent directory


I want to be able to test a python class from a testscript located in a subfolder. My project structure is as follows:

importTest
    __init__.py
    testFolder
        testScript.py
    tobeimported.py

The content of tobeimported.py is:

class ToBeImported:
    def __init__(self):
        self.print('Created!')

the content of my testScript.py is:

from ...importTest import tobeimported

def runTest():
    item = tobeimported.ToBeImported()

if __name__ == '__main__':
    runTest()

When I run testScript.py, I get the error:

attempted relative import with no known parent package

But importTest should be known as a package right? Because it has the __init__.py file?

How else can I import my ToBeImported class in my testscript?

I'm running python 3.9.5


Solution

  • There are two problems here

    • there is no __init__.py file in testFolder so this is not a python package as far as python is concerned
    • the testScript.py is run directly from its folder. This makes python think that the top level package is testFolder so "no known parent package"

    You should add the init file then run the code from the parent folder of importTest as python -m importTest.testFolder.testScript