When writing scripts for personal use, I am used to doing this:
def do_something():
# Do something.
if __name__ == '__main__':
do_something()
Or, we can also do this:
def do_something():
# Do something.
do_something() # No if __name__ thingy.
I know the first form is useful when differentiating between importing the script as a module or calling it directly, but otherwise for scripts that will only be executed (and never imported), is there any reason to prefer one over the other?
There are two types of functions in python: User-Defined Functions - these types of functions are defined by the user to perform any specific task. Built-in Functions - these types of functions are pre-defined in python.
Types Of Python FunctionsPython Built-in Functions. Python Recursion Functions. Python Lambda Functions. Python User-defined Functions.
One – one function (Injective function) Many – one function. Onto – function (Surjective Function)
In Python, the role of the main function is to act as the starting point of execution for any software program. The execution of the program starts only when the main function is defined in Python because the program executes only when it runs directly, and if it is imported as a module, then it will not run.
Even if the script is only meant to be executed, it might sometimes be useful to import it anyway -- in an interactive shell, by documentation generation tools, in unit tests or to perform timings. So routinely using the more general form will never hurt.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With