if __name__ == "__main__":
# Code inside of here will only run if the python script was launched directly
# This code will not run if imported as a module
# If the python interpreter is running that module (the source file)
# as the main program, it sets the special __name__ variable to have
# a value “__main__”. If this file is being imported from another
# module, __name__ will be set to the module’s name.
if __name__=='__main__':
# do something
# Suppose this is foo.py.
print("before import")
import math
print("before functionA")
def functionA():
print("Function A")
print("before functionB")
def functionB():
print("Function B {}".format(math.sqrt(100)))
print("before __name__ guard")
if __name__ == '__main__':
functionA()
functionB()
print("after __name__ guard")
basically, (__name__ == '__main__') ==True
confirms file is NOT a/part of a module and may continue execution
# Suppose this is foo.py.
print("before import")
import math
print("before function_a")
def function_a():
print("Function A")
print("before function_b")
def function_b():
print("Function B {}".format(math.sqrt(100)))
print("before __name__ guard")
if __name__ == '__main__':
function_a()
function_b()
print("after __name__ guard")
# Suppose this is foo.py.
print("before import")
import math
print("before functionA")
def functionA():
print("Function A")
print("before functionB")
def functionB():
print("Function B {}".format(math.sqrt(100)))
print("before __name__ guard")
if __name__ == '__main__':
functionA()
functionB()
print("after __name__ guard")
<class '__main__.CoolClass'>
if __name__ == "__main__"
// Every Python module has it’s __name__ defined
// and if this is ‘__main__’,
// it implies that the module is being run
// standalone by the user and we can do corresponding
// appropriate actions.
// If you import this script as a module
// in another script,
// the __name__ is set to the name
// of the script/module.
// Python files can act as either reusable modules,
// or as standalone programs.
// if __name__ == “main”: is used to execute some
// code only if the file was run directly,
// and not imported.