Accessing one's main script's global from imported libraries

Alex Martelli aleax at
Tue Feb 25 19:31:56 CET 2003

Mike Meyer wrote:

> Alex Martelli <aleax at> writes:
>> czrpb wrote:
>> > All:
>> > Say I have with the global taste.
>> > Say in I import eggs.
>> > Say I want eggs to access'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 -- 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 = []
import eggs
print taste
import __main__

Now when you run "python" you will see [23] printed.
If you edited to use spam instead of __main__, then
when you ran "python" it would print the empty list
[] twice -- would have imported 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 mailing list