Accessing one's main script's global from imported libraries
aleax at aleax.it
Tue Feb 25 19:31:56 CET 2003
Mike Meyer wrote:
> Alex Martelli <aleax at aleax.it> writes:
>> czrpb wrote:
>> > All:
>> > Say I have spam.py with the global taste.
>> > Say in spam.py I import eggs.
>> > Say I want eggs to access spam.py's taste global.
>> > How might I do this?
>> You shouldn't -- it sets up the worst possible kinds of
>> dependencies. But if you're really dead set on it:
>> taste = 23
>> import eggs
>> import __main__
>> print __main__.taste
> You can also just import spam instead of eggs. Mutual imports like
> that require a little care, but can work.
Assuming you mean "import spam from eggs" (I don't see how you
can import spam INSTEAD OF eggs -- spam.py presumably continues
with other statements after the "import eggs", in any case of
real interest), i.e. import spam instead of import __main__ --
this will not work in general when spam is run as the main
script. The problem is not visible in this code because as
"the global taste" I just put in a number. Consider instead:
taste = 
Now when you run "python spam.py" you will see  printed.
If you edited eggs.py to use spam instead of __main__, then
when you ran "python spam.py" it would print the empty list
 twice -- eggs.py would have imported spam.py again under
the new and different name 'spam', a distinct copy from the
one that is loading under the name '__main__'. Try it...
More information about the Python-list