News123 wrote:
Steven D'Aprano wrote:
<snip>
Now, in your case you escape that trap, because the import is inside a
function, so it doesn't occur until you call the function. But it is
still considered poor practice: it is best to avoid circular imports
unless you really, really need them.
The question is, why does module mod.py care what is happening in
main.py? It is better for mod.py to be self-contained, and not care about
main.py at all. If it needs A, let the caller pass A to it:
The reason is pure lazyness.
I would like to 'try' something quickly.
I have a module used by many different python programs.
In case the __main__ module contains a certain object I'd like to
extract information from this object if not not.
This is for debug, not for 'production'.
I'd prefer to change only one file and not many.
First, the practical response: yes, it'll work, and if this is really
for debug, it's fine. However, realize that many times "debug things"
make it into the wild.
Any time recursion of imports occurs, it's a sign of trouble. And doing
it right isn't usually much harder than studying the hazards of the
recursion.
In the particular case you're doing, I think there are at least three
better solutions:
1) Pass A as an argument to a function call, for example f(A).
2) Put A into a separate module that both main.py and mod.py import
3) Explicitly add A to mod.py's global space. mod.A = A written in
main.py, before calling the function mod.x().
HTH
DaveA
--
http://mail.python.org/mailman/listinfo/python-list