if __name__ == '__main__'
if __name__ == '__main__'
You may have encountered something like if __name__ == '__main__'. This if construct is used to execute the top-level code(i.e. at the first indent level) of a script ONLY IF it is being run directly(i.e. by double-clicking the .py file), and not if the module is being imported into another file. Let’s look at this in detail.
In other programming languages such as C++, there is a main() function (it has to named main, or else the code doesn't compile), declared explicitly by the user, from which the execution of a program begins. In Python, the main() function is composed of all the top-level code i.e. all statements written at indentation level 0. That’s it, you don’t have to declare the main() function, Python does it by itself.
The top-level code in a Python script gets executed as soon as it is run via command line (i.e. $ python myfile.py) or run directly by executing a .py file.
The __name__ dunder attribute of a module evaluates to the name of the module itself. However, if the module is being run directly by either of the two methods stated above, then the __name__ attribute is set to the string “__main__”. This enables the user to check if the script is being run directly (command line or execution of .py file) or it is being imported. The developer can place the functionality in this if clause ensuring that importing the module doesn't trigger the functionality. Only if the module is being executed will the functionality be triggered.
Below is a simple Python script that contains a function, a print statement, and the if construct. If the script is being run directly, the function is called with a sample value, and not if the script is being imported as a module.
# prime.py def primeOrNot(num): if num <= 1: print(str(num), "is not a prime number.") return False for factor in range(2, num): # if there exists any number greater than 2 that if num % factor == 0: # divides the given number evenly(with remainder 0, that is), print(str(num), "is not a prime number.") return False # then the given number is not prime print(str(num), "is a prime number.") return True print("Top-level code being executed...") if __name__ == '__main__': primeOrNot(23) # WHEN THE ABOVE SCRIPT IS RUN DIRECTLY VIA COMMAND LINE OR BY EXECUTING prime.py Top-level code being executed... 23 is a prime number. # WHEN THE ABOVE SCRIPT IS BEING IMPORTED AS A MODULE # One way of importing the module is by going to Run Menu in IDLE window of above script > Python Shell >>> import prime Top-level code being executed...