Resource mentioned in this lesson: What Does if __name__ == "__main__" Do in Python?
Creating a Fixed Entry Point
00:00
In this lesson, we will create a fixed entry point for our application. Many programming languages have typically a fixed entry point into their programs, which is usually the main() function.
00:12 This is the function that gets triggered every time a program runs. Now, Python technically doesn’t have this functionality, but you can simulate it anyway to ensure a consistent starting point for your applications.
00:27 In Python, there is a very typical construct, which is to check a special built-in variable
00:34
called __name__, check to make sure it has a specific value, which is the string __main__.
00:44
And if this is the case, we call a main() function, which we define earlier in the script, which contains the entire code logic. This short code snippet is then typically placed at the bottom of your file after the main() function is declared.
01:01
And it is called only if this special condition, this __name__ variable equal to this __main__ string holds. This is only true if your script is executed directly, not if your script is imported by another file. So by adding this construct to the bottom of your script, let’s have a look at it in action.
01:23 In our quote generator file,
01:26
most of the logic is in a function called main(). And right at the bottom, we have if __name__ == the string "__main__", then we run the main() function.
01:42 If you were to import this script in another file, that function would not run. And that ensures that not only do we have a consistent entry point into our application, it is only triggered when our file, our program is executed directly.
01:58
If you want to find out more about this construct, this if __name__ == "__main__" construct, there is an entire tutorial available on the Real Python website.
02:09 And that is our final topic for this course. All that is left is to summarize what you’ve learned.
Become a Member to join the conversation.
