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?

asked May 28, 2017 at 13:19
3
  • 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. Commented May 28, 2017 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. Commented May 28, 2017 at 13:55
  • Correct aaa.ttt is not a module without __init__.py, see this answer: stackoverflow.com/questions/4092395/… Commented May 29, 2017 at 3:31

0

Know someone who can answer? Share a link to this question via email, Twitter, or Facebook.

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.