why a main() function?

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • beliavsky@aol.com

    #1

    why a main() function?

    I think I read a suggestion somewhere to wrap the code where a Python
    script starts in a main() function, so one has

    def main():
    print "hi"

    main()

    instead of

    print "hi"

    What are the advantages of doing this?

  • insyte@gmail.com

    #2
    Re: why a main() function?


    beliavsky@aol.c om wrote:
    I think I read a suggestion somewhere to wrap the code where a Python
    script starts in a main() function, so one has
    >
    def main():
    print "hi"
    >
    main()
    >
    instead of
    >
    print "hi"
    >
    What are the advantages of doing this?

    I'm sure there are other reasons, but for me the most important is that
    you can import your code into the interpreter and poke at it from there
    without executing the script. Also, of course, you can re-use your
    code as a module in another program.

    -Ben

    Comment

    • Calvin Spealman

      #3
      Re: why a main() function?

      On 18 Sep 2006 12:40:00 -0700, beliavsky@aol.c om <beliavsky@aol. comwrote:
      I think I read a suggestion somewhere to wrap the code where a Python
      script starts in a main() function, so one has
      >
      def main():
      print "hi"
      >
      main()
      >
      instead of
      >
      print "hi"
      >
      What are the advantages of doing this?
      It is useful both importating scripts without running them, for
      debugging or reusing parts of them later, and also for adding small
      test scripts to modules to allow them to be run for testing purposes.

      Comment

      • Benjamin Niemann

        #4
        Re: why a main() function?

        beliavsky@aol.c om wrote:
        I think I read a suggestion somewhere to wrap the code where a Python
        script starts in a main() function, so one has
        >
        def main():
        print "hi"
        >
        main()
        >
        instead of
        >
        print "hi"
        >
        What are the advantages of doing this?
        Refine this to:

        def main():
        print "hi"

        if __name__ == "__main__":
        main()

        The advantage of the 'if __name__ ..' statement is that you can import the
        script without running the 'main' code, e.g. from your unittest module.

        Wrapping the main code in a function allows you to call this function from
        your unittests and test it like any other function.

        Additionally I do usually add an 'argv' argument to main() which I use
        instead of sys.argv, so I can easily test it with different arguments.

        --
        Benjamin Niemann
        Email: pink at odahoda dot de
        WWW: http://pink.odahoda.de/

        Comment

        • Steve Holden

          #5
          Re: why a main() function?

          beliavsky@aol.c om wrote:
          I think I read a suggestion somewhere to wrap the code where a Python
          script starts in a main() function, so one has
          >
          def main():
          print "hi"
          >
          main()
          >
          instead of
          >
          print "hi"
          >
          What are the advantages of doing this?
          >
          Guido van Rossum himself can tell you:



          regards
          Steve
          --
          Steve Holden +44 150 684 7255 +1 800 494 3119
          Holden Web LLC/Ltd http://www.holdenweb.com
          Skype: holdenweb http://holdenweb.blogspot.com
          Recent Ramblings http://del.icio.us/steve.holden

          Comment

          • bearophileHUGS@lycos.com

            #6
            Re: why a main() function?

            Others have already told you the most important things.

            There is another secondary advantage: the code inside a function runs
            faster (something related is true for C programs too). Usually this
            isn't important, but for certain programs they can go 20%+ faster.

            Bye,
            bearophile

            Comment

            • Ben Finney

              #7
              Re: why a main() function?

              Steve Holden <steve@holdenwe b.comwrites:
              beliavsky@aol.c om wrote:
              I think I read a suggestion somewhere to wrap the code where a
              Python script starts in a main() function
              [...]
              What are the advantages of doing this?
              Guido van Rossum himself can tell you:
              http://www.artima.com/forums/flat.js...06&thread=4829
              I read that one a while ago, and now have this in most of my programs:

              def __main__(argv=N one):
              """ Perform the main function of this program """
              from sys import argv as sys_argv
              if argv is None:
              argv = sys_argv

              # preparation, e.g. set up environment

              exit_code = None
              try:
              do_the_main_thi ng(argv) # or whatever the main step is
              except SystemError, e:
              exit_code = e.code

              return exit_code

              if __name__ == '__main__':
              import sys
              exit_code = __main__(sys.ar gv)
              sys.exit(exit_c ode)

              This allows me to import my program as a module, and treat the main
              routine as a function (argv as input, exit_code as output), while the
              code itself can do sys.exit() without needing to know that it's
              wrapped up in a function.

              It also encourages me to write code inside do_the_main_thi ng() that
              gets its environment parameterised as input, instead of specifying
              sys.argv and the like. This makes the code much easier to unit test.

              The name __main__ was chosen because I saw hints some time ago that
              Python 3000 might automate some of these semantics for a function with
              that name. True or false?

              --
              \ "Crime is contagious ... if the government becomes a |
              `\ lawbreaker, it breeds contempt for the law." -- Justice Louis |
              _o__) Brandeis |
              Ben Finney

              Comment

              • Dan Sommers

                #8
                [OT] Re: why a main() function?

                On 18 Sep 2006 14:38:12 -0700,
                bearophileHUGS@ lycos.com wrote:
                ... There is another secondary advantage: the code inside a function
                runs faster (something related is true for C programs too). Usually
                ^^^^^^^^^^^^^^^ ^^^^^^^^^^^^^^^ ^^^^^^^^^^^^^^
                this isn't important, but for certain programs they can go 20%+
                faster.
                Okay, I give up.

                AFAIK, All C code must be inside a function, unless you count the
                expressions in initializers.

                So aside from certain CPU/MMU/OS/cache/etc. quirks, why would C code
                inside a function run faster than C code outside a function? Compiler
                optimizations because of const and restrict keywords don't count.

                And what other C code *isn't* inside a function?

                Regards,
                Dan

                --
                Dan Sommers
                <http://www.tombstoneze ro.net/dan/>
                "I wish people would die in alphabetical order." -- My wife, the genealogist

                Comment

                • billie

                  #9
                  Re: why a main() function?

                  Another advantage is that you can catch all the unhandled exceptions of
                  the entire program (it they occurs) by doing something like this:

                  def another_call():
                  raise SomeUnexpectedE xception # it will be catched in '__main__'

                  def call():
                  another_call()

                  def run():
                  call()

                  in __name__ == '__main__':
                  try:
                  run()
                  except:
                  # do cleanup
                  # log exit message
                  # exit

                  Comment

                  • Diez B. Roggisch

                    #10
                    Re: why a main() function?

                    bearophileHUGS@ lycos.com wrote:
                    Others have already told you the most important things.
                    >
                    There is another secondary advantage: the code inside a function runs
                    faster (something related is true for C programs too). Usually this
                    isn't important, but for certain programs they can go 20%+ faster.
                    I totally fail to see why that should be the case - for python as well as
                    for C.

                    So - can you explain that a bit more, or provide resources to read up on it?

                    Diez

                    Comment

                    • Simon Brunning

                      #11
                      Re: why a main() function?

                      On 9/19/06, Diez B. Roggisch <deets@nospam.w eb.dewrote:
                      I totally fail to see why that should be the case - for python as well as
                      for C.
                      If you put your code into a main() function, all the names that it
                      binds are in the function's local scope, whereas if the code is in the
                      module's top level, the names are bound to the module's global scope.
                      Access to locals is somewhat faster than access to globals.

                      --
                      Cheers,
                      Simon B,
                      simon@brunningo nline.net,

                      Comment

                      • Fredrik Lundh

                        #12
                        Re: why a main() function?

                        "Diez B. Roggisch" wrote:
                        >There is another secondary advantage: the code inside a function runs
                        >faster (something related is true for C programs too). Usually this
                        >isn't important, but for certain programs they can go 20%+ faster.
                        >
                        I totally fail to see why that should be the case - for python as well as
                        for C.
                        >
                        So - can you explain that a bit more, or provide resources to read up on it?
                        Python stores local variables in an indexed array, but globals in a dictionary.
                        Looking things up by index is faster than looking them up by name.

                        Not sure what the C thing is; C doesn't really support putting *code* outside
                        functions. Maybe he was thinking about static vs. auto variables ?

                        </F>



                        Comment

                        • Peter Otten

                          #13
                          Re: why a main() function?

                          Diez B. Roggisch wrote:
                          bearophileHUGS@ lycos.com wrote:
                          >
                          >Others have already told you the most important things.
                          >>
                          >There is another secondary advantage: the code inside a function runs
                          >faster (something related is true for C programs too). Usually this
                          >isn't important, but for certain programs they can go 20%+ faster.
                          >
                          I totally fail to see why that should be the case - for python as well as
                          for C.
                          >
                          So - can you explain that a bit more, or provide resources to read up on
                          it?
                          A trivial example (for Python):

                          $ cat main.py
                          def main():
                          x = 42
                          for i in xrange(1000000) :
                          x; x; x; x; x; x; x; x; x; x
                          x; x; x; x; x; x; x; x; x; x
                          x; x; x; x; x; x; x; x; x; x

                          main()
                          $ time python main.py

                          real 0m0.874s
                          user 0m0.864s
                          sys 0m0.009s
                          $ cat nomain.py
                          x = 42
                          for i in xrange(1000000) :
                          x; x; x; x; x; x; x; x; x; x
                          x; x; x; x; x; x; x; x; x; x
                          x; x; x; x; x; x; x; x; x; x
                          $ time python nomain.py

                          real 0m2.154s
                          user 0m2.145s
                          sys 0m0.009s
                          $

                          Now let's verify that global variables are responsible for the extra time:

                          $ cat main_global.py
                          def main():
                          global i, x
                          x = 42
                          for i in xrange(1000000) :
                          x; x; x; x; x; x; x; x; x; x
                          x; x; x; x; x; x; x; x; x; x
                          x; x; x; x; x; x; x; x; x; x

                          main()
                          $ time python main_global.py

                          real 0m2.002s
                          user 0m1.995s
                          sys 0m0.007s


                          Peter

                          Comment

                          • Diez B. Roggisch

                            #14
                            Re: why a main() function?

                            Fredrik Lundh wrote:
                            "Diez B. Roggisch" wrote:
                            >
                            >>There is another secondary advantage: the code inside a function runs
                            >>faster (something related is true for C programs too). Usually this
                            >>isn't important, but for certain programs they can go 20%+ faster.
                            >>
                            >I totally fail to see why that should be the case - for python as well as
                            >for C.
                            >>
                            >So - can you explain that a bit more, or provide resources to read up on
                            >it?
                            >
                            Python stores local variables in an indexed array, but globals in a
                            dictionary. Looking things up by index is faster than looking them up by
                            name.
                            Interesting. How is the index computed? I would have assumed that locals()
                            is somehow used, which is a dicht.

                            I can imagine enumerating left-hand-side names and trying to replace their
                            occurence with the index, falling back to the name if that is not
                            possible/the index isn't found. Does that come close?

                            Diez

                            Comment

                            • Paul Rubin

                              #15
                              Re: why a main() function?

                              "Diez B. Roggisch" <deets@nospam.w eb.dewrites:
                              Python stores local variables in an indexed array, but globals in a
                              dictionary. Looking things up by index is faster than looking them up by
                              name.
                              >
                              Interesting. How is the index computed? I would have assumed that locals()
                              is somehow used, which is a dicht.
                              They're static indexes assigned at compile time.

                              Comment

                              Working...