When you load a Python module, by default all the code in that module will be interpreted by the Python interpreter.
This means that if your module has a ‘main’ function — some function that you use as an entry point to your program — by default it will run, and this is often not what you want to happen.
mymodule.py:
def greet():
print("Hello")
def main():
greet()
main()
myprogram.py:
import mymodule as mm
# Nothing else here!
output:
Hello
Conditionally Running ‘Main’
To fix this, we can add some code that will ensure your main function will run only when the module file is run directly.
There is a variable called __name__ which will contain the text __main__ only if the file is run directly from the terminal. Otherwise it will contain the name of the module.
mymodule.py:
def greet():
print("Hello")
def main():
greet()
if __name__ == "__main__":
main()
Note that there is nothing special about the name “main” for a function. It’s just a good name to call the starting point of your program.
Now, main() will only run if mymodule.py is run as a standalone program from the terminal. If it’s loaded as a module, main() will not run.
Leave a Reply