Python Forum
if __name__=='__main__' - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: if __name__=='__main__' (/thread-34848.html)



if __name__=='__main__' - albin2005 - Sep-07-2021

can some explain what is if __name__=='__main__' ? and how it is used in python programs ?

Regards,
albin2005


RE: if __name__=='__main__' - Gribouillis - Sep-07-2021

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.


RE: if __name__=='__main__' - Yoriz - Sep-07-2021

https://docs.python.org/3/faq/programming.html#how-do-i-find-the-current-module-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


RE: if __name__=='__main__' - albin2005 - Sep-07-2021

Thank You for the reply

regards
albin2005 Smile