Python complex subpackage importing

2019-05-30 19:14发布

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.)

2条回答
等我变得足够好
2楼-- · 2019-05-30 19:25

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
查看更多
干净又极端
3楼-- · 2019-05-30 19:40

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  
查看更多
登录 后发表回答