As you build more complex Python apps, you will probably want to start splitting your code into separate files.
What Is the __main__ Function?
Importing and executing code from another file is common in even small scripts and apps built with Python. As your library of scripts increases, you may choose to import previously written code into new projects.
The __main__ function in Python is only executed when the script is called directly, allowing you to set different behavior based on how your code is being accessed.
The __name__ Variable
In Python, the __name__ variable is automatically set to the value of the current script’s name as Python is using it.
If the script is being executed directly by python, it will be called __main__ – a reserved name for the script that Python has called directly.
If the script has been imported into another script, the value of __name__ will be the name the script was given when it was imported.
Importing Python Scripts as Modules
Consider the following two files, stored in the same directory:
fruit.py
fruitList = ["apple", "banana", "orange", "pear"] # Create an ordered list of fruit print("__name__ is: ", __name__) # Print the name of this script as it is executed # If this script is executed directly, print the list of fruit if __name__ == '__main__': print(fruitList)
salad.py
import fruit # Import the fruit.py file - as it's in the same directory it can be imported using just its name reversed = list(reversed(fruit.fruitList)) # Reverse the list of fruit supplied by the fruit Python file print(reversed)
A list was reversed in salad.py – see our article on reversing lists on how this was done.
If you run the fruit.py file directly:
python3 fruit.py
You will see the following output:
__name__ is: __main__ ['apple', 'banana', 'orange', 'pear']
The first line of the output tells us that the file has been executed directly by Python as it is called __main__.
The second line of the output is the ordered list of fruit, executed as the if condition is met.
If, however, you execute the salad.py file instead:
python3 salad.py
You will get the output:
__name__ is: fruit ['pear', 'orange', 'banana', 'apple']
The first line of the output tells us that the fruit.py file was executed with the name fruit – as it was imported, it wasn’t executed directly!
Due to this, the list of fruit is never printed from fruit.py.
Instead, salad.py has read the fruit list from the imported fruit.py, reversed it, and printed it.
Conclusion
Pretty simple, but useful. You’ll see that the if statement is used to compare values above.