1

So, I am having the following structure in my python package:

./main.py
__init__.py
./mymods/
    __init__.py
    a.py
    b.py

my module a.py imports module b:

import b

Now, I want to import module a from main but when I do I get the following:

import mymods.a

ImportError: No module named 'b'

I googled but I couldn't find a solution to this particular problem. Any good samaritan who knows how to do this?

p.s. I would prefer not to have to import the module b explicitly from main, if that is possible.

Noxet
  • 236
  • 4
  • 16

2 Answers2

2

You need to make mymods into a package. This can be done simply by creating an empty __init__.py file in the directory.

➜ tree
.
├── main.py
└── mymods
    ├── __init__.py
    ├── a.py
    └── b.py

1 directory, 4 files
➜ cat main.py
import mymods.a

print 'printing from main'
➜ cat mymods/a.py
from . import b

print 'printing from a'

➜ cat mymods/b.py
print 'printing from b

➜ python main.py
printing from b
printing from a
printing from main

For Python 3, change the import b to from . import b.

Christian Witts
  • 11,375
  • 1
  • 33
  • 46
0

Basically you have to add empty __init__.py file into each folder within your py project.

See more on What is __init__.py for?

Community
  • 1
  • 1
Andriy Ivaneyko
  • 20,639
  • 6
  • 60
  • 82