How Do You Use the Name-Main Idiom?
00:00 You now know what the name-main idiom is, how it works, and when to use it. In this lesson, you’ll see some of the best practices of how to incorporate it into your own scripts. Since it’s just a regular conditional statement, you can use the name-main idiom anywhere in your script, potentially even more than once.
00:20 But generally, you just have it one time at the very bottom of your file. This is because Python files are always executed from top to bottom, and you want to make sure that all of your functions and classes are defined before you attempt to use them in the name-main idiom block.
00:39
Next, keep the code under your name-main idiom to a minimum. Putting as few statements as possible in the name-main idiom block can improve code clarity and correctness. If you do have multiple lines under it, consider defining a global main()
function and calling that function from the name-main idiom block instead.
01:01
Here’s an example of what that would look like. We’ve got repeat.py
that accepts script arguments, and we have two lines of code inside of the name-main idiom block.
01:13
You can move them into a function called main()
,
01:24
And then you can call that main()
function inside of the name-main idiom code. Then to make sure that it still works, you can run python repeat.py
.
01:36 Does this still work? And it does.
01:44
There are many advantages of using a main()
function to store your script code. First, it helps make the code inside the name-main idiom clear and concise, which is better for people who don’t know what it’s used for yet. Also, you can put the main()
function anywhere in your file, like at the top, where it’s more likely to be read first.
02:04
It also makes it possible to import and call the main()
function from anywhere, like inside the Python console. And it moves variables out of the global scope of your script.
02:18
So, as you can see in this example, now the text
variable inside of the main()
function and the text
variable inside of the repeat()
function are in separate scopes, and this reduces the potential for bugs.
02:35
Also note that this main()
function is just a convention that’s used in the Python world. Just like the name-main idiom is a regular conditional statement, the main()
function is just a regular function.
02:47
It doesn’t mean anything special like it would if you were programming in Java or C. To summarize, how would you use the name-main idiom? You would include it it at the bottom of your script, and don’t put too many lines of code. If you would have multiple lines of code, consider using a separate main()
function instead to make it clearer and more concise.
03:13 Now you’ve learned how to use the name-main idiom. In the next and final lesson, you’ll get a summary of everything covered in this course as well as some additional resources.
Become a Member to join the conversation.