
TL;DR
When a module is imported into a script, the module's code is run when the script is run.
This is useful for unit testing
Like, most programming languages, python has special variables. A peculiar special variable in python is the __name__ variable.
When you have a script that can act as both a module and a script, you'd probably need this conditional statement.
One thing about python modules is that if imported, into a script all the code in that module is run when the script is run.
module.py
print("I am module.py")deffunc1():return"The first function was called"if__name__=="__main__":print(func1())# When this module (or script) is run this would be the outputIammodule.pyThefirstfunctionwascalled
script.py
importmoduleprint("I would be printed after'I am module.py'")# When this script is run, this would be the outputIammodule.pyIwouldbeprintedafter'I am module.py'# Note, func1 wasn't called
Now, let's assume we have a script with useful utility functions. We want to be able to test our script and also export it as a module. We would put our unit tests in the conditionalif __name__ == "__main__"
Try this out yourself. Investigate it. Then learn about unit testing in python. Thanks for reading.
Top comments(0)
For further actions, you may consider blocking this person and/orreporting abuse