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.

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

4 Comments

I edited it to include how I laid out the project, and what is in the source files. How does yours differ ?
Ah, it works with python 2 but not 3.. and I was running python 3. Since I do need to run py3, do you know what the solution might be?
For Py3, change the import to from . import b. That is compatible with Python 2.7.
Aah, there we go. Thank you so much, you saved my day!
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?

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.