Huh?!?!? What is it that I'm seeing here?

John Roth newsgroups at jhrothjr.com
Sun Sep 14 18:46:54 EDT 2003


"Don Bruder" <dakidd at sonic.net> wrote in message
news:Mj59b.21551$dk4.670845 at typhoon.sonic.net...

> I'm in the process of trying to convert a Python script/program or
> whatever the favored term is into C and/or C++, and of course, due to my
> unfamiliarity with Python, I'm hitting some stuff that looks to be
> idiomatic, without being able to locate a definition/description of the
> idiom. Most of what I'm messing with seems pretty straightforward - it's
> converting nicely into C++, and with my testing so far, appears to be
> performing properly (albeit somewhat inefficiently, since I haven't done
> any tweaking yet) but one particular construct has me stumped. It looks
> like this:
>
> if __name__ == '__main__':
>   run(argv[1:])
>
> This (or a markedly similar construct) sits all by its lonesome self at
> the bottom of several of the source files, apparently not part of any
> class or declaration. It seems to be *FAIRLY* common in the group of
> files that make up the program, which makes me think it may be some sort
> of "preprocessor directive" type thing, similar to a C construct that
> would conditionally compile in a "main()" routine if a given symbol
> is/isn't defined. In all cases where this construct appears, there's a
> corresponding "run()" method, which, confusingly, appears to be outside
> the scope of any lexical blocks that I can recognize, so I've got no
> contextual clue there...

What's confusing you is that Python executes the module when it's
first run (or imported.) That means that any code outside of a def
is executed directly, including those last two lines that have
you puzzled.

"__main__" is the name of the module that is executed from the
command line, regardless of what its name was on disk. What
that means is that the if statement will succeed if the module is
run directly from the command line, but will fail if it is imported
from some other module.

HTH

John Roth

>
> Thanks in advance...
>
> -- 
> Don Bruder -  dakidd at sonic.net <--- Preferred Email - unmunged,
SpamAssassinated
> Hate SPAM? See <http://www.spamassassin.org> for some seriously great
info.
> I will choose a path that's clear: I will choose Free Will! - N. Peart
> Fly trap info pages:
<http://www.sonic.net/~dakidd/Horses/FlyTrap/index.html>






More information about the Python-list mailing list