You should put this in all your Python scripts | if __name__ == '__main__': ...

mCoding · Beginner ·📄 Research Papers Explained ·4y ago

Key Takeaways

The video discusses the importance of using the if __name__ == '__main__' idiom in Python scripts, highlighting its benefits in signaling that a file is a script, improving readability, and preventing unintended behavior when importing modules. The speaker also emphasizes the value of extracting the main code into a separate function to avoid global variables and facilitate testing and reuse.

Full Transcript

hello and welcome I'm James Murphy from M coding and today we're going to be talking about the deaf main if name main idiom in Python and why you should be using it in all of your scripts first off not every file is a script by a script I mean a file that you intend to run not a library so something like this that just defines a function that you're supposed to import in another file is not going to benefit from this idiom most languages like C plus plus or Java have a kind of boilerplate setup that you need to write even to write the most basic function Java is notorious for having its public static void mainstream args as one of the first things that a programmer sees before learning to use it but in Python it's seemingly a lot simpler all you need to do is say print hello world but what I hope to convince you of by the end of this video is that you should really prefer this deaf main if name main idiom over just writing things out in a line okay really quickly if you're not familiar what is this name variable if you run the script from your terminal or elsewhere you'll see that the name variable turns out to be this double underscore main double underscore but if you import the file you see something different in this case we see the double underscore name is if name main package.import me to print name the difference in Behavior allows you to check whether the file is being run as a script or not if you see done domain then it's being run as a script and if it's anything else then it's being imported you could just stop there and put all of the statements that you want to execute when this is run as a script into this if block but I say you should go one step further and Define it as a main function okay so you can check whether or not your code is being run as a script or being imported but why why would you want to do this is it just a way to flex on programmers that don't know the idiom or is there a reason for actually doing this well yes of course there are reasons for doing it let's go over them the first and most important reason actually has nothing to do with the language itself and everything to do with how people use it yes you can use if name main to check whether or not your code is being run versus imported but this isn't what it signals to the person reading your code if name main is used to signal that this file is a script and you can run it if I look at a file and I don't see if name main I assume that I cannot or should not try to run it it makes me think it's supposed to be a library or that it's only meant to be imported nothing about the Python language actually enforces this but compare it to using an underscore as a variable name if you see an underscore in someone's code they're basically saying I'm not going to use this variable Nothing Stops them from using it but if they do use it they're kind of breaking an unspoken rule in the python community underscore means I'm not going to use this variable and if they main means this is a script don't keep your reader guessing if this is supposed to be an entry point to your program just make it explicit many editors like pycharm use this as a signal you can see the file on the left has this green arrow which says run hello but there's no green arrow on the right that's because pycharm knows the signal if they main means this is something that I want to run no if name main means this is probably a library you're not meant to just run it but why should you extract main out into a function instead of just leaving the contents in the if block here's a script that just defines some function and then uses it to compute something even if I put this code inside a nameguard everything that I do here is still in the global scope in particular this variable I is a global variable even if I didn't really mean it to be that suppose I Define a function to compute some value and then later on I use it here I'm just trying to add up some evaluations of this function based off of this list but I have accidentally made a typo I use the variable I here but the name of the loop variable was n when I run the code instead of getting an error for my typo I silently get the wrong value this is one of the worst kind of errors that you can have and this is all just within the same file imagine if this happened in a different file if in another file or at the console I do an import Star of the bad script I now have a global variable I that I didn't know about so if it was this file that defined the compute Val function this file now has a global variable I and it's even harder than in the last example to find this typo also in the case where you didn't have an if name main at all just importing the script will actually run it that basically means that it's impossible to test your code without side effects also note that there are plenty of cases where importing your code happens automatically this script explicitly Imports the useful class from the bad script and then writes it to a pickle file it's clear here that we're importing the bad script because we explicitly wrote it but in this script there's no mention of the bad script all we're doing is unpickling some object we don't even know where it came from and yet when we run this code we see that we did in fact import the bad script and run all of the code that was in its body this is because pickle.load automatically imported the bad script in order to get the definition of the useful class in the pickle case it was just a little bit annoying to have that extra stuff printed out but in this case we're doing some multi-processing the goal is to compute the values of this useful function over some list of inputs multi-processing pool is going to start up a bunch of different python processes that all automatically import this file but without an if name main you can see how this starts to get into trouble just importing the file starts up new processes which then import the file and so on so you pretty much can't use multi-processing in this case look what happens and I can't even kill it with Ctrl C I have to kill the terminal putting this code in an ifnay main prevents the rampant process spawning but again without putting this in a separate function this is now going to give me a global variable named p all you have to do to avoid this headache is just use the idiom it's not that much typing and in fact you could probably just set up your Editor to have it there automatically when you make a new file or just have a template to paste it when you type Main one final less used reason for making a main function is that this allows you to have an entry point to your program that you can use from other scripts so I don't have to run this from the command line I could import this from another file and then call the main function as if I was running it from the command line without starting a new process in this case you can have your main taken whatever arguments as an optional parameter all right that's all I've got on the deaf main if name main idiom let me know if you found any other reasons to use it also let me know if you're a holdout what your reasons are for not using it as usual thanks to my patrons and to my donors for supporting me if you like the video don't forget to subscribe and hit the like button see you next time

Original Description

Python's favorite unexplained incantation! Do you know def main if __name__ == '__main__'? In this video I explain why your Python scripts should use this idiom. It's not strictly necessary, but you will be a better Python coder if you follow established conventions that improve the readability of your code. ― mCoding with James Murphy (https://mcoding.io) Source code: https://github.com/mCodingLLC/VideosSampleCode StackOverflow on the topic: https://stackoverflow.com/questions/419163/what-does-if-name-main-do Python docs: https://docs.python.org/3/reference/toplevel_components.html#complete-python-programs SUPPORT ME ⭐ --------------------------------------------------- Patreon: https://patreon.com/mCoding Paypal: https://www.paypal.com/donate/?hosted_button_id=VJY5SLZ8BJHEE Other donations: https://mcoding.io/donate Top patrons and donors: Jameson, John M, Laura M, Pieter G, Vahnekie, Sigmanificient BE ACTIVE IN MY COMMUNITY 😄 --------------------------------------------------- Discord: https://discord.gg/Ye9yJtZQuN Github: https://github.com/mCodingLLC/ Reddit: https://www.reddit.com/r/mCoding/ Facebook: https://www.facebook.com/james.mcoding CHAPTERS --------------------------------------------------- 0:00 Intro 0:58 Dunder name 1:47 Why if name main 3:36 Why def main 4:59 Pickle example 5:42 Multiprocessing example 6:42 Main function entry point 7:07 Outro
Watch on YouTube ↗ (saves to browser)
Sign in to unlock AI tutor explanation · ⚡30

Playlist

Uploads from mCoding · mCoding · 41 of 60

1 Goodbye, List! Type hinting standard collections - New in Python 3.9
Goodbye, List! Type hinting standard collections - New in Python 3.9
mCoding
2 Python's comma equals ,= operator?
Python's comma equals ,= operator?
mCoding
3 Finding Primes in Python with the Sieve of Eratosthenes
Finding Primes in Python with the Sieve of Eratosthenes
mCoding
4 Find the First Missing Positive Int | Hard Interview Question on LeetCode
Find the First Missing Positive Int | Hard Interview Question on LeetCode
mCoding
5 JSON Tutorial Python | Basic Python Recipes
JSON Tutorial Python | Basic Python Recipes
mCoding
6 Simulating Brownian Motion in Python
Simulating Brownian Motion in Python
mCoding
7 The Single Most Useful Decorator in Python
The Single Most Useful Decorator in Python
mCoding
8 The Fastest Way to Loop in Python - An Unfortunate Truth
The Fastest Way to Loop in Python - An Unfortunate Truth
mCoding
9 Numpy Array Broadcasting In Python Explained
Numpy Array Broadcasting In Python Explained
mCoding
10 Brownian Motion Single Path Zoom
Brownian Motion Single Path Zoom
mCoding
11 Brownian Motion Fractal Zoom
Brownian Motion Fractal Zoom
mCoding
12 Magic Methods - Making Python builtins work with your classes
Magic Methods - Making Python builtins work with your classes
mCoding
13 50 Million Primes In 5 Seconds - Segmented Sieve of Eratosthenes
50 Million Primes In 5 Seconds - Segmented Sieve of Eratosthenes
mCoding
14 The Hottest New Feature Coming In Python 3.10 - Structural Pattern Matching / Match Statement
The Hottest New Feature Coming In Python 3.10 - Structural Pattern Matching / Match Statement
mCoding
15 How Fast is Python's Sort? Performance Testing
How Fast is Python's Sort? Performance Testing
mCoding
16 C++ First Missing Int, faster than 100%!
C++ First Missing Int, faster than 100%!
mCoding
17 [April Fools 2021] Python 4.0! New old print, mandatory static typing, StackOverflow integration
[April Fools 2021] Python 4.0! New old print, mandatory static typing, StackOverflow integration
mCoding
18 Python dataclasses will save you HOURS, also featuring attrs
Python dataclasses will save you HOURS, also featuring attrs
mCoding
19 C++ Sudoku Solver in 7 minutes using Recursive Backtracking
C++ Sudoku Solver in 7 minutes using Recursive Backtracking
mCoding
20 Every PROOF you've seen that .999... = 1 is WRONG
Every PROOF you've seen that .999... = 1 is WRONG
mCoding
21 Python's sharpest corner is ... plus equals? (+=)
Python's sharpest corner is ... plus equals? (+=)
mCoding
22 Binary Search - A Different Perspective | Python Algorithms
Binary Search - A Different Perspective | Python Algorithms
mCoding
23 The Best Way to Check for Optional Arguments in Python
The Best Way to Check for Optional Arguments in Python
mCoding
24 Local and Global Variable Lookup Weirdness in Python
Local and Global Variable Lookup Weirdness in Python
mCoding
25 Efficient Exponentiation
Efficient Exponentiation
mCoding
26 How To Install Python for Data Science
How To Install Python for Data Science
mCoding
27 0.1 + 0.2 is NOT 0.3 in Most Programming Languages
0.1 + 0.2 is NOT 0.3 in Most Programming Languages
mCoding
28 Python 3.10's new type hinting features
Python 3.10's new type hinting features
mCoding
29 Python 3.10's Quality of Life improvements
Python 3.10's Quality of Life improvements
mCoding
30 Introducing mZips! Python Zip and Zip Longest
Introducing mZips! Python Zip and Zip Longest
mCoding
31 Match statement tips
Match statement tips
mCoding
32 Using except: is a HUGE mistake
Using except: is a HUGE mistake
mCoding
33 Python + YouTube API | Automating descriptions
Python + YouTube API | Automating descriptions
mCoding
34 Anaphones, phonetic anagrams
Anaphones, phonetic anagrams
mCoding
35 Cracking passwords using ONLY response times | Secure Python
Cracking passwords using ONLY response times | Secure Python
mCoding
36 Python f-strings can do more than you thought. f'{val=}', f'{val!r}', f'{dt:%Y-%m-%d}'
Python f-strings can do more than you thought. f'{val=}', f'{val!r}', f'{dt:%Y-%m-%d}'
mCoding
37 Diagnose slow Python code. (Feat. async/await)
Diagnose slow Python code. (Feat. async/await)
mCoding
38 Python MD5 implementation
Python MD5 implementation
mCoding
39 Salting, peppering, and hashing passwords
Salting, peppering, and hashing passwords
mCoding
40 x to bool conversion in Python, C++, and C
x to bool conversion in Python, C++, and C
mCoding
You should put this in all your Python scripts | if __name__ == '__main__': ...
You should put this in all your Python scripts | if __name__ == '__main__': ...
mCoding
42 Find the Skyline Problem with C++ Solution Explained
Find the Skyline Problem with C++ Solution Explained
mCoding
43 The ONLY C keyword with no C++ equivalent
The ONLY C keyword with no C++ equivalent
mCoding
44 Should you use "not not x" instead of "bool(x)" in Python? (NO!)
Should you use "not not x" instead of "bool(x)" in Python? (NO!)
mCoding
45 Multiple Assignments in Python
Multiple Assignments in Python
mCoding
46 Why I don't like Python's chained comparisons
Why I don't like Python's chained comparisons
mCoding
47 Automated Testing in Python with pytest, tox, and GitHub Actions
Automated Testing in Python with pytest, tox, and GitHub Actions
mCoding
48 You can pip install directly from GitHub
You can pip install directly from GitHub
mCoding
49 __new__ vs __init__ in Python
__new__ vs __init__ in Python
mCoding
50 Metaclasses in Python
Metaclasses in Python
mCoding
51 The easy way to keep your repos tidy.
The easy way to keep your repos tidy.
mCoding
52 Which Python @dataclass is best? Feat. Pydantic, NamedTuple, attrs...
Which Python @dataclass is best? Feat. Pydantic, NamedTuple, attrs...
mCoding
53 Python __slots__ and object layout explained
Python __slots__ and object layout explained
mCoding
54 C++ cache locality and branch predictability
C++ cache locality and branch predictability
mCoding
55 Avoiding import loops in Python
Avoiding import loops in Python
mCoding
56 25 nooby Python habits you need to ditch
25 nooby Python habits you need to ditch
mCoding
57 Python staticmethod and classmethod
Python staticmethod and classmethod
mCoding
58 Building a Python app with Anvil to email me if my website goes down (includes paid features)
Building a Python app with Anvil to email me if my website goes down (includes paid features)
mCoding
59 31 nooby C++ habits you need to ditch
31 nooby C++ habits you need to ditch
mCoding
60 Interviewing the creator of C++, Bjarne Stroustrup
Interviewing the creator of C++, Bjarne Stroustrup
mCoding

Use the if __name__ == '__main__' idiom in Python scripts to improve readability and prevent unintended behavior. Extract the main code into a separate function to avoid global variables and facilitate testing and reuse.

Key Takeaways
  1. Use the if __name__ == '__main__' idiom in Python scripts
  2. Extract the main code into a separate function
  3. Avoid using global variables
  4. Test and reuse code safely
💡 The if __name__ == '__main__' idiom is not just a convention, but a way to signal that a file is a script and improve readability, while also preventing unintended behavior when importing modules.

Related Reads

📰
Follow-up: The ArxivLens Protocol: Transforming Research Nois
Learn how to apply the ArxivLens Protocol to create dynamic grant-allocation pools that rebalance based on citation-impact signals, transforming research noise into actionable insights
Dev.to AI
📰
On July 1, 2026, arXiv will spin out from Cornell University, its home for the past 25 years, to become an independent nonprofit organization. Major funding support from Simons Foundation and Schmidt Sciences. Ditching the red for their website. [N]
arXiv is becoming an independent nonprofit organization after 25 years at Cornell University, backed by major funding, which will impact the future of research and academia
Reddit r/MachineLearning
📰
CS-NRRM™ Official Publications: Paper 1 and Paper 2 Are Now Available
Learn about the CS-NRRM's official publications on a 12-year longitudinal human observation archive and its significance in research and development
Medium · Data Science
📰
Found a potential mistake in an ICLR 2026 blogpost [D]
Verify a potential mistake in an ICLR 2026 blog post and learn how to effectively report errors in academic publications
Reddit r/MachineLearning

Chapters (8)

Intro
0:58 Dunder name
1:47 Why if name main
3:36 Why def main
4:59 Pickle example
5:42 Multiprocessing example
6:42 Main function entry point
7:07 Outro
Up next
How to get started With Drug Discovery using BioAI: Computational Biology ( 4K UHD Med Masterclass )
Sudarshan's Multiverse
Watch →