Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
if __name__=='__main__'
#1
can some explain what is if __name__=='__main__' ? and how it is used in python programs ?

Regards,
albin2005
Reply
#2
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.
Reply
#3
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
Reply
#4
Thank You for the reply

regards
albin2005 Smile
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  __name__ and __main__ in functions Mark17 3 726 Oct-12-2023, 01:55 AM
Last Post: deanhystad
  question about if __name__=="__main__" aaander 6 1,347 Nov-13-2022, 09:06 PM
Last Post: deanhystad
  Questions about __name__ SheeppOSU 3 2,277 Jul-11-2019, 12:51 PM
Last Post: DeaD_EyE
  ModuleNotFoundError: No module named '__main__.vtt'; '__main__' is not a package MM2018 26 16,828 Oct-12-2018, 05:40 AM
Last Post: MM2018
  Why do we use __main__ when we can call a function directly? Dave7Swift 5 3,847 Jun-04-2018, 05:01 AM
Last Post: Dave7Swift
  Problem with __main__ sylas 2 2,764 Mar-30-2018, 07:51 PM
Last Post: snippsat
  [split] can't find '__main__' module Blue Dog 1 9,471 Oct-18-2016, 12:23 AM
Last Post: micseydel

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020