accessing variable of the __main__ module

Jean-Michel Pichavant jeanmichel at sequans.com
Mon Mar 22 12:01:00 CET 2010


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



More information about the Python-list mailing list