How to abort module evaluation?
Dave Angel
davea at ieee.org
Tue May 12 17:56:17 EDT 2009
mrstevegross wrote:
> I have a python script that is pretty simple: when executed, it
> imports a bunch of stuff and then runs some logic. When *imported*, it
> defines some variables and exits. Here's what it looks like:
>
> === foo.py ===
> if __name__ != '__main__':
> x = 1
> exit_somehow
>
> import bar
> do_some_stuff...
> === EOF ===
>
> There's a problem, though. On line 3, I wrote "exit_somehow".
> Actually, I have no idea how to do that part. Is there some way I can
> get python to abandon processing the rest of the script at that point?
> I know goto doesn't exist, so that's not an option... sys.exit() won't
> work, because that will abort the entire python interpreter, rather
> than just the evaluation of the module.
>
> Thanks,
> --Steve
>
>
use "else" :
=== foo.py ===
if __name__ != '__main__':
x = 1
else:
import bar
do_some_stuff...
=== EOF ===
This is rather unconventional usage, however. In fact, Mike missed the
!= in your comparison, perhaps because the other way is so common. The
usual idiom is:
import some stuff
define some globals, like x=1
def some functions, classes etc.
if __name__ == "__main__":
maybe import some extra stuff
do_some_stuff
In this case, no else is needed,
Notice also that in your case, the x=1 doesn't take effect when you use
it as a script, but only when it's being imported. Usually, this is a
mistake.
More information about the Python-list
mailing list