[Tutor] I don't get it

Danny Yoo dyoo@hkn.eecs.berkeley.edu
Fri, 20 Sep 2002 10:48:16 -0700 (PDT)


On Fri, 20 Sep 2002, Erik Price wrote:

> > On Friday 20 September 2002 05:15, Erik Price wrote:
> >> On Friday, September 20, 2002, at 01:35 AM, Danny Yoo wrote:
> >>> However, I think your programs are also very monolithic.  My opinion
> >>> is that your programming will become better if you define more
> >>> utility functions.
> >>
> >> if __name__ == '__main__':
> >>
> >> Was really a lightbulb-turner-onner for me.
> >>
> >
> > Indeed.  It leads to unit testing and testing is not possible if you
> > have all of your code in one, big jumble.  I find that forcing myself
> > to write tests also forces me to design my code better.
>
> I have heard of unit-testing.  But I'm not sure exactly what it is.  My
> best guess is that it's when you provide sample data in the "if __name__
> == '__main__' " block so that you can execute this class individually to
> make sure it works.
>
> But I don't know the methodology of unit testing.


Dive into Python has an awesome chapter on showing what Unit Testing is:

    http://diveintopython.org/roman_divein.html




> (OT question: Does anyone know, is the Java version of "if __name__ ==
> '__main__' " a simple matter of using the main() method?)

Yes, it's the same... well, except that the Java version's main static
method is explicitely named, so that we can actually call it from other
places if we wanted to.


In Python, on the other hand, we'd need to add a layer of indirection for
the exact same effect.  That is, instead of:

###
if __name__ == '__main__':
    print "hello, this is a test"
###


we can yank out the body of the main into a separate function:

###
def _main():
    print "hello, this is a test"


if __name__ == '__main__':
    _main()
###


This would be closer to a Java/C style main function.

Good luck!