1

I have a pretty complex package tree like the following within yet another package

A\
    B\
        a.py
        b.py
        c.py
    C\
        a.py
        b.py
        c.py

I want to be able to do import A and access all sub-packages and submodules like A.B.a.foo(). One way would be to have A/__init__.py import all of A's subpackages, but some of the subpackages also import other subpackages (e.g., A.C uses things from A.B, leading to an ImportError. What I'm looking for is a way to do from A import B as A.B, i.e., import subpackages but still have them be bound to the parent package. Is there a good way to do this?

(I'm not sure what title embodies this question, if someone has a better title then I'll change it.)

darkfeline
  • 9,404
  • 5
  • 31
  • 32
  • You have a circular import there, and this usually means that you have some design flaw in your package. If both `B` and `C` need each other, then they should be probably merged into a single package. – Bakuriu Jun 05 '13 at 05:36
  • @Bakuriu I don't think that's necessarily or universally true (although it's probably true more often than it's false). Sometimes I have two packages that are conceptually pretty distinct even if their implementations are a bit intermingled, requiring some co-dependence. It's not pretty, but in some cases it could be worse to merge everything together. edit: I realize you said "probably", not "definitely", but I still wanted to make the other argument. – cxrodgers Jun 05 '13 at 09:28

2 Answers2

0

Did you try:

In A.__init__:

import B
import C

In B.__init__:

import C, a, b, c

In C.__init__:

import B, a, b, c

I tried this with some test files and it seemed to work fine.

In [5]: import A

In [6]: A.
A.B  A.C  

In [6]: A.B.
A.B.C  A.B.a  A.B.b  A.B.c  
cxrodgers
  • 4,317
  • 2
  • 23
  • 29
0

You don't need to import anything in __init__.py (just make sure that each package has this file on Python <3.3).

If you need to use A.B.a.foo() function in a module then add the corresponding import in it:

from A.B.a import foo
jfs
  • 399,953
  • 195
  • 994
  • 1,670