1

I'm running into an issue with how to properly declare imports for some modules that I've written.

Suppose the follow directory structure:

main_dir/
 __init__.py
 module_A
    sub_dir/
     __init__.py
     module_B
     module_C

So that modules B and C are both in the same subdirectory relative to module A.

Module B imports C. Module A sometimes imports B.

So, in Module B, using import module_C works fines.

And in Module A, using import sub_dir.module_C works fine.

However, in Module A, using import sub_dir.module_B causes an ImportError no module named 'module_C' because B imports C.

I'm assuming that I could change B to import sub_dir.module_C but I don't want to do that because then it will break when I start directly in B rather than import B from A.

What's the correct way(s) to handle this sort of issue?

user3351605
  • 1,271
  • 3
  • 19
  • 30

1 Answers1

1

This should be your app structure of files.

app/
├── __init__.py
├── module_a.py
└── subdir
    ├── __init__.py
    ├── module_b.py
    └── module_c.py

module_a.py

from subdir import module_b, module_c

Then, you will have access to all modules from module_a.

If you import module_b in module_c or module_c in module_b you will have an cyclic import issue. This is a design question. You need to review your code and rethink how to link modules.

Community
  • 1
  • 1
Mauro Baraldi
  • 6,346
  • 2
  • 32
  • 43
  • 1
    I was hoping there would be an alternative to restructuring the modules, as the current structure fits well with the my mental construct of how they are related to each other and the way I use them. Unfortunately, that particular model does not seem to fit well with Python's expectations, so I shall have to adjust my own practices rather than fight a losing battle with the language. Thanks for your help. – user3351605 Mar 30 '15 at 13:48
  • I don't know which framework you're using to build your application, but this doc [building large apps with Flask](https://github.com/mitsuhiko/flask/wiki/Large-app-how-to) could help you with other issues like this. ;-) – Mauro Baraldi Mar 30 '15 at 14:10