Home > Enterprise >  How to solve "attempted relative import with no known parent package" error in python
How to solve "attempted relative import with no known parent package" error in python

Time:12-28

I tried to import File from file.py in file2.py, but I got the error ImportError: attempted relative import with no known parent package

This is my filesystem:

-- projects
    -- project1
        -- folder1
            -- foo
                -- file.py
                -- fileInterface.py
            -- bar 
                -- file2.py
                -- file2Interface.py

And my code:

-- foo/file.py

from fileInterface import FileInterface
class File(FileInterface):
    def __init__(self):
        ...

    def func(self):
        ...

-- bar/file2.py

from file2Interface import File2Interface
from ..foo.file import File
class File2(File2Interface):
    def __init__(self):
        ...

    def func2(self):
        f = new File()
        f.func()
        ...

I also tried these ways from other stackoverflow posts:

  • Adding __init__.py to folder1, foo, bar
  • Adding setup.py to project1 (with pymodules and packages)
  • Running the file with python3 -m file2.py
  • Running the file with python3 folder1/bar/file2.py

But, they didn't work

Thanks in advance!

CodePudding user response:

import sys
sys.path.append("../foo")
import file

In this option, we add a folder to the module search area, which allows you to import your files.

This is useful when it is unwise to change the structure of the project, for example, to call tests from the test folder, but in general it is correct to assemble the project so that you do not have to use such hacks.

  • Related