accessing variable of the __main__ module
Alf P. Steinbach
alfps at start.no
Sat Mar 20 08:47:41 EDT 2010
* News123:
>
> 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?
I don't know if this is what you're after, because it's design level instead of
technical-Python level. But consider the knowledge distribution above. I see it
as like a doctor (main program) telling a nurse (mod.f) to please do something
for which the nurse would require some ImportantFact, which the good doctor
absent-mindedly forgets to tell the nurse. Trying to do as told the nurse
discovers that she needs the ImportantFact, and knowing that it might be
available in one of the doctor's files she breaks into his office, finds the PC
up and running with the doctor logged in, hurray!, and starts looking...
I think the doctor should just give the nurse the ImportantFact right away, not
be so absent-minded and unavailable for query later.
And I think that if the nurse isn't told the ImportantFact and discovers that
she needs it to do what she's told, then the proper thing to do is not to break
into the doctor's office and go browsing in his files to possibly find what she
needs. For example, she might instead raise an exception. Don't know how they do
that in hospitals, though.
Cheers & hth.,
- Alf
More information about the Python-list
mailing list