1

I have the following folder structure:

├── aaa
│   ├── __init__.py
│   ├── ttt
│   │   ├── aaa.py
│   │   └── __init__.py
│   └── ttt.py
├── __init__.py
├── t.py
└── ttt.py

The main script t.py:

import sys
sys.path = ['.']
import ttt
import aaa.ttt
import aaa.ttt.aaa

print(ttt.get_name())
print(aaa.ttt.get_name2())
print(aaa.ttt.aaa.get_name3())

The imported scripts:

./ttt.py

def get_name():
    return "ttt"

./aaa/ttt.py

def get_name2():
    return "aaa/ttt"

./aaa/ttt/aaa/ttt.py

def get_name3():
    return "aaa/ttt/aaa"

Now running the main script:

$ python -B t.py 
ttt
Traceback (most recent call last):
  File "t.py", line 10, in <module>
    print(aaa.ttt.get_name2())
AttributeError: module 'aaa.ttt' has no attribute 'get_name2'

What is the problem here? I am using Python 3.6.1.

Edit

As commented by @AChampion, a problem is that I have aaa/ttt.py and aaa/ttt/__init__.py. However, if I remove the latter I get a ModuleNotFoundError on import aaa.ttt.aaa:

$ python -B t.py 
Traceback (most recent call last):
  File "t.py", line 7, in <module>
    import aaa.ttt.aaa
ModuleNotFoundError: No module named 'aaa.ttt.aaa'; 'aaa.ttt' is not a package

Does this mean that if you have a package aaa.bbb in Python, then you cannot have any modules in package aaa named bbb? This smells bad design, so I guess I must be missing something here?

Håkon Hægland
  • 39,012
  • 21
  • 81
  • 174
  • 2
    `import aaa.ttt` is ambiguous, does this mean `aaa/ttt/__init__.py` or `aaa/ttt.py`, the former is tried first. So `aaa/ttt.py` is never imported. – AChampion May 28 '17 at 13:27
  • @AChampion Yes that seems like the case, but I am not allowed to remove the `aaa/ttt/__init__.py`. Then I get a `ModuleNotFoundError` for `import aaa.ttt.aaa`. See my updated question. – Håkon Hægland May 28 '17 at 13:55
  • Correct `aaa.ttt` is not a module without `__init__.py`, see this answer: https://stackoverflow.com/questions/4092395/python-import-precedence-packages-or-modules – AChampion May 29 '17 at 03:31

0 Answers0