Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python - ImportError: attempted relative import with no known parent package

Tags:

I have a trouble with imports in my project.

My directories structure is the following:

base_directory
  - examples
  - src
    - folder_1
      - __init__.py
      - file.py
    - folder_2
      - __init__.py
      - class1.py
      - class2.py
      - class3.py
      - class4.py

In file.py I'm trying: from ..folder2.class1 import Class1 then, I get the error:

ImportError: attempted relative import with no known parent package

In folder2/__init__.py I did what I saw on a tutorial for making packages in Python:

from class1 import Class1

my_class_1 = Class1()

So far, anything has worked. What should I do? I use Python 3.7.5

Thanks.

like image 251
Francisco Avatar asked Jun 23 '20 17:06

Francisco


1 Answers

In your example, folder_1 and folder_2 are two separate and unique packages. There are no relative imports between them. Put them in a single outer package to get it to work

base_directory
  - examples
  - src
      - mypackage
        - __init__.py
        - folder_1
          - __init__.py
          - file.py
                print("imported", __file__)
                from ..folder_2.class1 import Class1
                print("file.py found", Class1)
        - folder_2   
          - __init__.py
          - class1.py
                print("imported", __file__)
                class Class1:
                def __init__(self):
                    print("Created Class1 instance")
          - class2.py
          - class3.py 
          - class4.py
      - test.py
            import myproject.folder_1.file

Running test.py script

~/tmp/base_directory/src$ python test.py
imported /home/td/tmp/base_directory/src/myproject/folder_1/file.py
imported /home/td/tmp/base_directory/src/myproject/folder_2/class1.py
file.py found <class 'myproject.folder_2.class1.Class1'>

But there is a workaround where modules can be called using the "-m" option. But his only works if myproject is in the python path. It works here because I'm in the parent of myproject when I call it.

~/tmp/base_directory/src$ python -m myproject.folder_1.file
imported /home/td/tmp/base_directory/src/myproject/folder_1/file.py
imported /home/td/tmp/base_directory/src/myproject/folder_2/class1.py
file.py found <class 'myproject.folder_2.class1.Class1'>
like image 77
tdelaney Avatar answered Sep 19 '22 11:09

tdelaney