I have a Python project with the following structure:
├── main.py
├── pack1
│ ├── __init__.py
│ ├── mod1
│ │ ├── __init__.py
│ │ └── request.py
│ ├── mod1.py
│ └── mod2.py
The content of main.py is:
from pack1 import mod1
from pack1.mod1.request import Mod1Request
my_class = mod1.Mod1Class()
my_request = Mod1Request()
if __name__ == '__main__':
print(repr(my_request))
print(repr(my_class))
The content of request.py and mod1.py is:
# request.py
class Mod1Request(object):
pass
# mod1.py
class Mod1Class(object):
pass
When I run it, I get this error:
Traceback (most recent call last):
File "/Users/dohong/dev/import_traps/main.py", line 4, in <module>
my_class = mod1.Mod1Class()
AttributeError: module 'pack1.mod1' has no attribute 'Mod1Class'
I have both a mod1.py file and a mod1 directory in my pack1 package. How can I properly import the Mod1Class from mod1.py while also keeping the imports from the mod1 directory working?
importstatement overwrites the contents of themod1namespace. You can check whether this is true by printing the content of thedircommand. Take a look at The import system for details on how imports are managed.from pack1 import mod1 as newmod1, followed withmy_class = newmod1.Mod1Class().