Python Forum
Why do we use __main__ when we can call a function directly?
Thread Rating:
  • 2 Vote(s) - 3.5 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Why do we use __main__ when we can call a function directly?
#2
People use __name__ to determine if the script is being imported or not. If it's equal to "__main__" then it's not an import. The idea being, you want to run your main method if and only if you're not being imported.

Java knows to call your main method. Python has no such similarity. When you run or import a script, the contents are executed. So it's up to the script to determine whether it should run its main function or not, rather than being built into the language.
Reply


Messages In This Thread
RE: Why do we use __main__ when we can call a function directly? - by micseydel - Jun-03-2018, 08:09 PM

Possibly Related Threads…
Thread Author Replies Views Last Post
  __name__ and __main__ in functions Mark17 3 822 Oct-12-2023, 01:55 AM
Last Post: deanhystad
  How do I call sys.argv list inside a function, from the CLI? billykid999 3 852 May-02-2023, 08:40 AM
Last Post: Gribouillis
  Import XML file directly into Excel spreadsheet demdej 0 895 Jan-24-2023, 02:48 PM
Last Post: demdej
  question about if __name__=="__main__" aaander 6 1,466 Nov-13-2022, 09:06 PM
Last Post: deanhystad
  if __name__=='__main__' albin2005 3 2,199 Sep-07-2021, 09:21 AM
Last Post: albin2005
  how to call an object in another function in Maya bstout 0 2,124 Apr-05-2021, 07:12 PM
Last Post: bstout
  In this function y initially has no value, but a call to foo() gives no error. Why? Pedroski55 8 3,598 Dec-19-2020, 07:30 AM
Last Post: ndc85430
  Struggling for the past hour to define function and call it back godlyredwall 2 2,280 Oct-29-2020, 02:45 PM
Last Post: deanhystad
  list call problem in generator function using iteration and recursive calls postta 1 1,986 Oct-24-2020, 09:33 PM
Last Post: bowlofred
  function call at defined system time? Holon 5 3,298 Oct-06-2020, 03:58 PM
Last Post: snippsat

Forum Jump:

User Panel Messages

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