[Python-ideas] Improve import mechanism for circular imports

Paul Moore p.f.moore at gmail.com
Tue Apr 10 13:57:11 CEST 2012


On 10 April 2012 10:30, Victor Varvariuc <victor.varvariuc at gmail.com> wrote:
> There are circular imports in this example code.
> Currently, `root = sys.modules['tree.root']` hack in branch.py works.
> Wouldn't it be useful to create attribute `root` in `main` at the same time
> `sys.modules['tree.root']` is created when doing `from tree import root` in
> main?
> This would solve more complex cases with when circular imports are involved,
> without applying such hacks.

Why does "tree" even exist? Why not just have 2 top-level modules
"root" and "branch". ("It's only an example" isn't a good answer - it
isn't a good example if it doesn't demonstrate why "tree" is needed
for your real use case). Can you explain the purpose of "tree" in your
real code?

Also, having things happen at import time (as opposed to simply
defining classes, functions, etc) is not good form, precisely because
partially-imported modules are in an odd state, and problems like this
can easily arise if you don't know what you are doing.

Instead of giving a made-up example, if you describe what you are
trying to achieve, I'm fairly certain someone here (or more likely on
python-list) could show you a better way to do it, without needing
circular imports.

Paul.



More information about the Python-ideas mailing list