Re: How to tell if in a script...

Guido.van.Rossum@cwi.nl
Thu, 29 Jul 1993 08:57:03 +0200

Lance Ellinghouse:

> Is there a way to tell from inside a module if you are in an import
> statement or loading from a script?

One trick that works:

running_as_script = 0
xxx = [] # create a unique object
import __main__ # the toplevel script being run
try:
if __main__.xxx is xxx:
running_as_script = 1
except AttributeError:
pass

Note the use of 'is' for the comparison, this compares object
identities instead of values.

Essentially the same code can be used for testing whether you have
been imported before (and hence are now being reloaded), by moving the
assignment to xxx after the try..except block (and changing the name
of the Boolean to something more meaningful, like impoerted_before).