[Chicago] __name__ == "__main__"

Kumar McMillan kumar.mcmillan at gmail.com
Fri Oct 26 18:06:30 CEST 2007


On 10/26/07, Michael Tobis <mtobis at gmail.com> wrote:
> Hi, Ian! Thanks for trying.
>
> Unfortunately, I still don't actually see how main() is better than
> just putting what you have in main() inline under the __name__
> conditional...

my opinion is that it's easier to test, that's all.  If you are trying
to functionally test your main code, I don't think there is a way
without creating a main function.  For example :

from mymodule import main
def test_mymodule_command():
    try:
        main(['--some-option=foo'])
    except SystemExit, e:
        assert e.code == 0
    # now you can do the post-mortem

K

>
> mt
>
> On 10/26/07, Ian Bicking <ianb at colorstudy.com> wrote:
> > Michael Tobis wrote:
> > > I agree with everything Kumar says. It could be prettier, but it's
> > > extremely useful to put the
> > > __name__ == "__main__" around code in your file that doesn't define
> > > objects or functions.
> > >
> > > Now that it's come up, though. what I never quite understood was the
> > > extra level of indirection that many people including Guido favor.
> > >
> > > ###
> > > def invoke_lots_of_stuff():
> > >    print "I represent a lot of very clever objects and functions"
> > >
> > > def main():
> > >    invoke_lots_of_stuff()
> > >
> > > if __name__ == "__main__":
> > >    main()
> > > ###
> > >
> > > What's the purpose of the extra layer provided by the main() function?
> > >
> > > Also, yeah, there's a little bit of a Python activity in Chicago...
> > > (Miss y'all; looking forward to seeing you again in March.)
> >
> > Usually main() handles the command-line interface, which specifically
> > parses a list of strings, and maybe calls sys.exit.
> > invoke_lots_of_stuff would generally have a Python interface, taking
> > keyword arguments and stuff that isn't a string.  So when you import the
> > code and use it from Python, you'd just use invoke_lots_of_stuff() and
> > not main().
> >
> >
> > --
> > Ian Bicking : ianb at colorstudy.com : http://blog.ianbicking.org
> > _______________________________________________
> > Chicago mailing list
> > Chicago at python.org
> > http://mail.python.org/mailman/listinfo/chicago
> >
> _______________________________________________
> Chicago mailing list
> Chicago at python.org
> http://mail.python.org/mailman/listinfo/chicago
>


More information about the Chicago mailing list