Python Forum

Full Version: if __name__=='__main__'
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
can some explain what is if __name__=='__main__' ? and how it is used in python programs ?

Regards,
albin2005
In the global namespace of a Python file, there is an implicit variable named __name__. Its value is a string of characters, the name of the current module. When the Python file is the main program as opposed to an imported module, the name of the current module is '__main__'. Thus the condition
if __name__ == '__main__':
    do_something()
could be translated in pseudo code as
if this file is the main program currently executed:
    do_something()
On the other hand, if this file is imported by another Python file, instead of being the main program, this part of the code won't be executed.
https://docs.python.org/3/faq/programmin...odule-name Wrote:How do I find the current module name?
A module can find out its own module name by looking at the predefined global variable __name__. If this has the value '__main__', the program is running as a script. Many modules that are usually used by importing them also provide a command-line interface or a self-test, and only execute this code after checking __name__:

def main():
    print('Running test...')
    ...

if __name__ == '__main__':
    main()

https://python-forum.io/thread-19700.html
Thank You for the reply

regards
albin2005 Smile