Skip to content
  • Categories
  • Recent
  • Tags
  • Popular
  • World
  • Users
  • Groups
Skins
  • Light
  • Brite
  • Cerulean
  • Cosmo
  • Flatly
  • Journal
  • Litera
  • Lumen
  • Lux
  • Materia
  • Minty
  • Morph
  • Pulse
  • Sandstone
  • Simplex
  • Sketchy
  • Spacelab
  • United
  • Yeti
  • Zephyr
  • Dark
  • Cyborg
  • Darkly
  • Quartz
  • Slate
  • Solar
  • Superhero
  • Vapor

  • Default (No Skin)
  • No Skin
Collapse
Brand Logo

agnos.is Forums

  1. Home
  2. Programmer Humor
  3. Python needs an actual default function

Python needs an actual default function

Scheduled Pinned Locked Moved Programmer Humor
programmerhumor
159 Posts 89 Posters 1 Views
  • Oldest to Newest
  • Newest to Oldest
  • Most Votes
Reply
  • Reply as topic
Log in to reply
This topic has been deleted. Only users with topic management privileges can see it.
  • sheridan@lemmy.worldS [email protected]

    Could someone explain this please? I'm still a noob.

    hiddenlayer555@lemmy.mlH This user is from outside of this forum
    hiddenlayer555@lemmy.mlH This user is from outside of this forum
    [email protected]
    wrote on last edited by [email protected]
    #9

    Basically, when you compile a program written in Rust or C/C++ (the first and second panels respectively), the compiler needs to know what's supposed to be executed first when the program is run directly (i.e. when you click on the executable), which in these languages, is denoted by a special function called main(). Executable files can also contain functions and data structures that can be called by other programs, and when they are, you wouldn't want to run an entire complex and resource intensive program if another program only needs to call a single function from it. In that case, the other program will call the function it wants but not main, so only that function executes and not the entire program.

    However, Python is a scripting language that's interpreted. So every Python source file is executable provided you have the Python runtime. Python also doesn't have native support for main functions in the same way Rust and C/C++ does, and it will execute every line of code as it reads the source file. This is why a single line Python file that just calls print is valid, it doesn't need to be wrapped in a main function to execute. However, what if your Python file is both meant to be executed directly and provides functions that other Python files can call? If you just put the main routine in the root of the file, it would be executed every time another program tries to import the file in order to call functions from it, since the import causes the file to be interpreted and executed in its entirety. You can still just have a main function in your file, but since Python doesn't natively support it, your main function won't do anything if you run the file directly because as far as Python is concerned, there is no executable code at the root of the file and you haven't called any functions.

    The workaround is to have a single if statement at the root of the file that looks like this:

    if __name__ == '__main__':
        main()
    

    It checks a special variable called __name__. If the Python file is directly executed, __name__ will have the value of the string '__main__', which satisfies the if statement so main() is called. If another Python file imports it, the value of __name__ will be the name of that file, so main() isn't called. It's clunky and not that efficient, but, 1, it works, and 2, if you cared about efficiency, you wouldn't be writing it in Python.

    S D 2 Replies Last reply
    15
    • hiddenlayer555@lemmy.mlH [email protected]

      Also, do y'all call main() in the if block or do you just put the code you want to run in the if block?

      match@pawb.socialM This user is from outside of this forum
      match@pawb.socialM This user is from outside of this forum
      [email protected]
      wrote on last edited by
      #10

      "pythonic"

      1 Reply Last reply
      5
      • arschflugkoerper@feddit.orgA [email protected]

        What kind of psychopath would put the code in the if block.

        N This user is from outside of this forum
        N This user is from outside of this forum
        [email protected]
        wrote on last edited by
        #11

        I definitely do for quick scripts, but I try to break this habit. The biggest advantage of def main() is that variables are local and not accessible to other functions defined in the same script, which can sometimes help catch bugs or typos.

        1 Reply Last reply
        2
        • hiddenlayer555@lemmy.mlH [email protected]

          Looks at all the Python scripts in my bin folder that I wrote.

          A This user is from outside of this forum
          A This user is from outside of this forum
          [email protected]
          wrote on last edited by
          #12

          custom bin folders are a realm no God dares to tread

          subarctictundra@lemmy.mlS 1 Reply Last reply
          4
          • hiddenlayer555@lemmy.mlH [email protected]

            Also, do y'all call main() in the if block or do you just put the code you want to run in the if block?

            J This user is from outside of this forum
            J This user is from outside of this forum
            [email protected]
            wrote on last edited by
            #13

            Its called runpy.run_script

            1 Reply Last reply
            1
            • arschflugkoerper@feddit.orgA [email protected]

              What kind of psychopath would put the code in the if block.

              eager_eagle@lemmy.worldE This user is from outside of this forum
              eager_eagle@lemmy.worldE This user is from outside of this forum
              [email protected]
              wrote on last edited by [email protected]
              #14

              I work in an academic / research environment. Depending who wrote it, even seeing a __name__ == "__main__" is a bit of a rare thing...

              H S B 3 Replies Last reply
              6
              • hiddenlayer555@lemmy.mlH [email protected]

                Also, do y'all call main() in the if block or do you just put the code you want to run in the if block?

                eager_eagle@lemmy.worldE This user is from outside of this forum
                eager_eagle@lemmy.worldE This user is from outside of this forum
                [email protected]
                wrote on last edited by
                #15

                The if block is still in the global scope, so writing the code in it is a great way to find yourself scratching your head with a weird bug 30 minutes later.

                B 1 Reply Last reply
                11
                • hiddenlayer555@lemmy.mlH [email protected]

                  Looks at all the Python scripts in my bin folder that I wrote.

                  30p87@feddit.org3 This user is from outside of this forum
                  30p87@feddit.org3 This user is from outside of this forum
                  [email protected]
                  wrote on last edited by [email protected]
                  #16

                  Never heard of

                  def main():
                      pass
                  
                  if __name__ == '__main__':
                      main()
                  

                  ?

                  hiddenlayer555@lemmy.mlH grrgyle@slrpnk.netG firelizzard@programming.devF 3 Replies Last reply
                  15
                  • 30p87@feddit.org3 [email protected]

                    Never heard of

                    def main():
                        pass
                    
                    if __name__ == '__main__':
                        main()
                    

                    ?

                    hiddenlayer555@lemmy.mlH This user is from outside of this forum
                    hiddenlayer555@lemmy.mlH This user is from outside of this forum
                    [email protected]
                    wrote on last edited by [email protected]
                    #17

                    Heard of it, was too lazy to do it that way.

                    To be fair I now do it that way, but not when I was learning Python.

                    1 Reply Last reply
                    0
                    • hiddenlayer555@lemmy.mlH [email protected]

                      Also, do y'all call main() in the if block or do you just put the code you want to run in the if block?

                      Q This user is from outside of this forum
                      Q This user is from outside of this forum
                      [email protected]
                      wrote on last edited by
                      #18

                      Nothing prevents you from putting a call to “main()” in the global scope

                      static_rocket@lemmy.worldS J 2 Replies Last reply
                      3
                      • A [email protected]

                        custom bin folders are a realm no God dares to tread

                        subarctictundra@lemmy.mlS This user is from outside of this forum
                        subarctictundra@lemmy.mlS This user is from outside of this forum
                        [email protected]
                        wrote on last edited by [email protected]
                        #19

                        I can and I do

                        *trollface*

                        1 Reply Last reply
                        0
                        • 30p87@feddit.org3 [email protected]

                          Never heard of

                          def main():
                              pass
                          
                          if __name__ == '__main__':
                              main()
                          

                          ?

                          grrgyle@slrpnk.netG This user is from outside of this forum
                          grrgyle@slrpnk.netG This user is from outside of this forum
                          [email protected]
                          wrote on last edited by
                          #20

                          I remember how weird this looked the first time I saw it and while I may now understand it, it still looks jank af

                          B A F 3 Replies Last reply
                          7
                          • hiddenlayer555@lemmy.mlH [email protected]

                            Basically, when you compile a program written in Rust or C/C++ (the first and second panels respectively), the compiler needs to know what's supposed to be executed first when the program is run directly (i.e. when you click on the executable), which in these languages, is denoted by a special function called main(). Executable files can also contain functions and data structures that can be called by other programs, and when they are, you wouldn't want to run an entire complex and resource intensive program if another program only needs to call a single function from it. In that case, the other program will call the function it wants but not main, so only that function executes and not the entire program.

                            However, Python is a scripting language that's interpreted. So every Python source file is executable provided you have the Python runtime. Python also doesn't have native support for main functions in the same way Rust and C/C++ does, and it will execute every line of code as it reads the source file. This is why a single line Python file that just calls print is valid, it doesn't need to be wrapped in a main function to execute. However, what if your Python file is both meant to be executed directly and provides functions that other Python files can call? If you just put the main routine in the root of the file, it would be executed every time another program tries to import the file in order to call functions from it, since the import causes the file to be interpreted and executed in its entirety. You can still just have a main function in your file, but since Python doesn't natively support it, your main function won't do anything if you run the file directly because as far as Python is concerned, there is no executable code at the root of the file and you haven't called any functions.

                            The workaround is to have a single if statement at the root of the file that looks like this:

                            if __name__ == '__main__':
                                main()
                            

                            It checks a special variable called __name__. If the Python file is directly executed, __name__ will have the value of the string '__main__', which satisfies the if statement so main() is called. If another Python file imports it, the value of __name__ will be the name of that file, so main() isn't called. It's clunky and not that efficient, but, 1, it works, and 2, if you cared about efficiency, you wouldn't be writing it in Python.

                            S This user is from outside of this forum
                            S This user is from outside of this forum
                            [email protected]
                            wrote on last edited by
                            #21

                            thats why i name my modules main.py

                            1 Reply Last reply
                            5
                            • D [email protected]

                              checks username

                              So it's you they're always talking about

                              kamenlady@lemmy.worldK This user is from outside of this forum
                              kamenlady@lemmy.worldK This user is from outside of this forum
                              [email protected]
                              wrote on last edited by
                              #22

                              It is, it's the other Barry.

                              1 Reply Last reply
                              0
                              • eager_eagle@lemmy.worldE [email protected]

                                I work in an academic / research environment. Depending who wrote it, even seeing a __name__ == "__main__" is a bit of a rare thing...

                                H This user is from outside of this forum
                                H This user is from outside of this forum
                                [email protected]
                                wrote on last edited by
                                #23

                                Do you also have nothing but love for those 50+ cell Jupyter notebooks that don't use a single function and have everything in the global scope?

                                eager_eagle@lemmy.worldE 1 Reply Last reply
                                2
                                • H [email protected]

                                  Do you also have nothing but love for those 50+ cell Jupyter notebooks that don't use a single function and have everything in the global scope?

                                  eager_eagle@lemmy.worldE This user is from outside of this forum
                                  eager_eagle@lemmy.worldE This user is from outside of this forum
                                  [email protected]
                                  wrote on last edited by
                                  #24

                                  the best thing is when not even the author knows the correct order of running the cells; because of course it isn't top-to-bottom.

                                  H 1 Reply Last reply
                                  3
                                  • eager_eagle@lemmy.worldE [email protected]

                                    I work in an academic / research environment. Depending who wrote it, even seeing a __name__ == "__main__" is a bit of a rare thing...

                                    S This user is from outside of this forum
                                    S This user is from outside of this forum
                                    [email protected]
                                    wrote on last edited by
                                    #25

                                    Academic code is absolutely horrific.

                                    Fortunately, it is possible to translate it for practical applications.

                                    A 1 Reply Last reply
                                    5
                                    • eager_eagle@lemmy.worldE [email protected]

                                      the best thing is when not even the author knows the correct order of running the cells; because of course it isn't top-to-bottom.

                                      H This user is from outside of this forum
                                      H This user is from outside of this forum
                                      [email protected]
                                      wrote on last edited by
                                      #26

                                      Yeah, and also zero dependency management, so you are free to figure out what combination of Python, Tensorflow and Keras will make it not throw random exceptions.

                                      And don't forget the number one rule: you must use all the graphing libraries, all the time.

                                      1 Reply Last reply
                                      3
                                      • arschflugkoerper@feddit.orgA [email protected]

                                        What kind of psychopath would put the code in the if block.

                                        L This user is from outside of this forum
                                        L This user is from outside of this forum
                                        [email protected]
                                        wrote on last edited by [email protected]
                                        #27

                                        If the file is just a class I usually put example usage with some default arguments in that block by itself. There is no reason for a "main" function. It's a nice obvious block that doesn't run when someone imports the class but if they're looking at the class there is a really obvious place to see the class usage. No confusion about what "main()" is meant to do.

                                        if __name__ == '__main__':
                                            # MyClass example Usage
                                            my_object = MyClass()
                                            my_object.my_method()
                                        
                                        1 Reply Last reply
                                        1
                                        • S [email protected]

                                          Academic code is absolutely horrific.

                                          Fortunately, it is possible to translate it for practical applications.

                                          A This user is from outside of this forum
                                          A This user is from outside of this forum
                                          [email protected]
                                          wrote on last edited by
                                          #28

                                          As someone in academia who writes code, I can confirm.

                                          1 Reply Last reply
                                          4
                                          Reply
                                          • Reply as topic
                                          Log in to reply
                                          • Oldest to Newest
                                          • Newest to Oldest
                                          • Most Votes


                                          • Login

                                          • Login or register to search.
                                          • First post
                                            Last post
                                          0
                                          • Categories
                                          • Recent
                                          • Tags
                                          • Popular
                                          • World
                                          • Users
                                          • Groups