On Fri, Mar 24, 2017 at 6:51 AM, Rafael Knuth <rafael.kn...@gmail.com> wrote: > Thank you so much for your help. > I have a question: When creating an instance of GroceryListMaker, you are > using: > > if __name__ == "__main__": > > What is that specifically for? > I tested your code and both worked, with and without > if __name__ == "__main__": > > a) > > if __name__ == "__main__": > my_shopping_list = GroceryListMaker() > my_shopping_list.make_shopping_list() > my_shopping_list.display_shopping_list() > > b) > > my_shopping_list = GroceryListMaker() > my_shopping_list.make_shopping_list() > my_shopping_list.display_shopping_list() > > Can you explain?
Alan in his post pretty much said it all. I do this to cover files that I may want to reuse, that is, import classes, functions, etc. from them in future programs without running the initializer code after the if statement. The main reason that I am doing this construction almost all of the time now, however, is that I have been striving to write unit tests for my code. When I run a test suite I don't want the "if __name__ ..." code to run in the files I am testing. However, in one of my unit test files I will similarly have: if __name__ == '__main__': unittest.main() which will run the tests when the test file is run directly. See https://docs.python.org/3/library/unittest.html for the Python 3 docs on the unittest module. _______________________________________________ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor