Duplicate of:
What doesif __name__== "__main__"
do?
Consider this code:
if __name__ == '__main__':
import pdb
pdb.run("interact()\n")
What does the following line mean?
if(__name__=='__main__')
I fainted.
We can use an if __name__ == "__main__" block to allow or prevent parts of code from being run when the modules are imported. When the Python interpreter reads a file, the __name__ variable is set as __main__ if the module being run, or as the module's name if it is imported.
if __name__ == “main”: is used to execute some code only if the file was run directly, and not imported.
__name__ is a built-in variable which evaluates to the name of the current module. Thus it can be used to check whether the current script is being run on its own or being imported somewhere else by combining it with if statement, as shown below.
__main__ — Top-level code environment. In Python, the special name __main__ is used for two important constructs: the name of the top-level environment of the program, which can be checked using the __name__ == '__main__' expression; and. the __main__.py file in Python packages.
__name__
is a variable automatically set in an executing python program. If you import
your module from another program, __name__
will be set to the name of the module. If you run your program directly, __name__
will be set to __main__
.
Therefore, if you want some things to happen only if you're running your program from the command line and not when imported (eg. unit tests for a library), you can use the
if __name__ == "__main__":
# will run only if module directly run
print "I am being run directly"
else:
# will run only if module imported
print "I am being imported"
trick. It's a common Python idiom.
This will be true if this module is being run as a standalone program. That way, something can act either as a module imported by another program, or a standalone program, but only execute the code in the if
statement if executed as a program.
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