Question about import

dieter dieter at handshake.de
Fri Sep 11 08:29:12 CEST 2015


"Frank Millman" <frank at chagford.com> writes:
>...
> My project comprises a number of modules, split into packages. Modules
> frequently need to access the contents of other modules, in the same
> or in a different package. I am getting better at it, but I still
> occasionally bump my head against circular imports, and have to fiddle
> around until it settles down again. Not ideal, I know.

Ideally, you have only oneway dependencies between modules.
In most cases, cyclic dependencies can be removed by refactoring - yielding
a better architecture.

> ...
> The surprising thing is that, within aa.py, I just have to say 'import
> b', and I can access 'b.bb.bbbb', and the same applies to 'bb.py'.

As a side effect of importing "<package>.<module>" "<module>"
is bound in "<package>". Thus, after the first import
of "<package>.<module>", "<module>" can be accessed via "<package>"
after only importing "<package>".


> That makes me wonder if, in my project, I can import all modules
> inside 'start.py', and then just use 'import package_name' inside each
> module?

You could - but you should not as this make you vulnerable with
respect to the import order.

In a small project, this is likely no problem. However, when your
projects grow and reuse components intially developped for other
projects, this may become unfeasable.



More information about the Python-list mailing list