if __name__ == 'main': & passing an arg to a class object

John Machin sjmachin at lexicon.net
Sun Apr 29 08:13:20 EDT 2007


On Apr 29, 9:32 pm, Bart Willems <b.r.will... at gmail.com> wrote:
> gtb wrote:
> > appear at the end of many examples I see. Is this to cause a .class
> > file to be generated?
>
> This might be obvious, but no one else mentioned it: the Python
> interpreter cannot execute code that it hasn't compiled yet, which is
> why the "if __name__ ..." code is always at the end of the module - to
> guarantee that the entire file is scanned first.

I make no claims about the following code; it is merely presented for
examination :-)

8< --- namemain.py -----------
# code used both in import mode and script mode
def greet(whom):
    print "Hello, %s" % whom
if __name__ == "__main__":
    # code used only in script mode
    import sys, namemain
    tgt = sys.argv[1]
    greet(tgt)
    namemain.farewell(tgt)
else:
    # code used only in import mode
    def farewell(whom):
        print "Goodbye, %s" % whom
8<------------------------------------------------------





More information about the Python-list mailing list