Back to: Python Programming
if __name__ == ‘__main__’: (pronounciation of “__” is dunder – double underscore)
This script can be imported OR run standalone.
Functions and classes in this module can be reused without the main block of code executing. This allows us to use the functionality of a program without using the main body of code.
In order to follow along with this example we will be creating two scripts, then importing one into the other in order to share functions coded in the first script.
DELETE main.py for this exercise (we’ll create it again at the end of this module).
CREATE two new scripts: File –> New –> Python File –> script1.py (repeat for script2.py). In PyCharm you should now see two tabs at the top of the IDE:

We need to add new Run configurations for script1 and script2.
In script1.py go to the Run menu –> Edit Configurations… –> click the “+” symbol –> select Python –> select a new script path –> select script1.py –> Apply –> OK
(Repeat for script2.py) In the drop down menu (top right) we can select which Run Configuration we would like. For now, select script1.
Script1.py
(Change the active script in the top right dropdown to script1):
def favorite_food(food):
print(f"Your favorite food is {food}")
def main():
print("This is script1")
favorite_food("pizza")
print("Goodbye!")
if __name__ == '__main__':
main()
This script is running “standalone” and outputs:
This is script1
Your favorite food is pizza
Goodbye!
Script2.py
(Change the active script in the top right dropdown to script2)
Now we are going to Import all of the functions from script1 so we can reuse its functions:
from script1 import *
def favorite_drink(drink):
print(f"Your favorite drink is {drink}")
def main():
print("This is script2")
favorite_food("sushi")
favorite_drink("coffee")
print('Goodbye!')
if __name__ == '__main__':
main()
Using if __name__ == ‘__main__’ is good practice because it makes your code more modular, helps readability, leaves no global variables and avoids unintended execution.
DON”T FORGET to remake your main.py file again.