0

I have a directory tree as follows:

main.py
dir1
  sub1.py
  sub2.py

In main.py:

import dir1.sub1

In dir1/sub1.py:

def f1() -> None:
    print("f1")


import dir1.sub2

dir1.sub2.f2()

In dir1/sub2.py:

import dir1.sub1


def f2() -> None:
    dir1.sub1.f1()
    print("f2")

When I run main.py, I get the following error message:

Traceback (most recent call last):
  File "...\main.py", line 1, in <module>
    import dir1.sub1
  File "...\dir1\sub1.py", line 7, in <module>
    dir1.sub2.f2()
  File "...\dir1\sub2.py", line 5, in f2
    dir1.sub1.f1()
AttributeError: module 'dir1' has no attribute 'sub1'. Did you mean: 'sub2'?

(Where the ... at the beginning of the file path is my working directory.)

If I change main.py to

import dir1.sub2

I get a slightly different error message:

Traceback (most recent call last):
  File "...\main.py", line 1, in <module>
    import dir1.sub2
  File "...\dir1\sub2.py", line 1, in <module>
    import dir1.sub1
  File "...\dir1\sub1.py", line 7, in <module>
    dir1.sub2.f2()
AttributeError: module 'dir1' has no attribute 'sub2'

If I move sub1.py and sub2.py to the same directory as main.py and re‐direct imports as necessary, I get the expected output of

f1
f2

Why does this happen, and how can I make it not happen?

1 Answers1

0

You need to use absolute import because Python 3 only supports that. In Python 2 your method will work. So for example if you have import dir1.sub2 change it to from dir1 import sub2. See here.

Note: I've tested it with your setup and it works.

Whispored2001
  • 411
  • 1
  • 5