Issue With Relative Imports In Python
Question: 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?


Answer: 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](http://stackoverflow.com/questions/744373/circular-or-cyclic-imports-
in-python) issue. This is a design question. You need to review your code and
rethink how to link modules.

