From: Dave Angel on
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

From: Jean-Michel Pichavant on
News123 wrote:
> Hi,
>
>
> I wondered about the best way, that a module's function could determine
> the existance and value of variables in the __main__ module.
>
>
> What I came up with is:
> ########### main.py ##########
> import mod
> A = 4
> if __name__ == "__main__": mod.f()
> ########### mod.py ##########
> def f():
> try:
> from __main__ import A
> except ImportError as e:
> A = "does not exist"
> print "__main__.A" ,A
>
> Is there anything better / more pythonic?
>
> Thanks in advance and bye
>
>
> N
>
The 'was I imported from that module' is usually some sign of bad
design. I can't detail more wihtout further detail of what you're trying
to achieve. Bud since what you have is working, I would'nt bother more
than that cause no matter what you try, it will be ugly :o).

JM