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.
  • 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.

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

    Really helpful explanation, thanks.

    1 Reply Last reply
    0
    • F [email protected]

      Python has a bunch of magic variables, like __name__. This one contains the name of the module you're currently in (usually based on the file name), so if your file is called foo.py, it will have the value foo.

      But that's only if your module is being imported by another module. If it's executed directly (e.g. python foo.py), it will instead have a __name__ of __main__. This is often used to add a standalone CLI section to modules - e.g. the module usually only defines functions that can be imported, but when executed it runs an example of those functions.

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

      Really helpful explanation, thanks.

      1 Reply Last reply
      0
      • slacktoid@lemmy.mlS [email protected]

        I call main() in the if

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

        I always use

        if "__main__" == main:
            __main__()
        

        ..and earlier in the code:

        def __main__():
            while True:
                pass
        main = "__main__"
        

        This helps to prevent people from arbitrarily running my code as a library or executable when I don't went them to.

        owsei@programming.devO slacktoid@lemmy.mlS 2 Replies Last reply
        1
        • B [email protected]

          I always use

          if "__main__" == main:
              __main__()
          

          ..and earlier in the code:

          def __main__():
              while True:
                  pass
          main = "__main__"
          

          This helps to prevent people from arbitrarily running my code as a library or executable when I don't went them to.

          owsei@programming.devO This user is from outside of this forum
          owsei@programming.devO This user is from outside of this forum
          [email protected]
          wrote on last edited by
          #68

          soulless stare

          1 Reply Last reply
          5
          • 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...

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

            python isn't the only language to do "execute everything imported from a particular file and all top level statements get run". both node and c# (but with restrictions on where top level statements can be) can do that type of thing, I'm sure there's more.

            python conventions are unique because they attempt to make their entrypoint also importable itself without side effects. almost no one needs to do that, and I imagine the convention leaked out from the few people that did since it doesn't hurt either.

            for instance in node this is the equivalent, even though I've never seen someone try before:

            if (path.resolve(url.fileURLToPath(import.meta.url)).includes(path.resolve(process.argv[1])))
            {
              // main things
            }
            
            1 Reply Last reply
            1
            • S [email protected]

              Sounds like a skill issue on your end

              embed_me@programming.devE This user is from outside of this forum
              embed_me@programming.devE This user is from outside of this forum
              [email protected]
              wrote on last edited by
              #70

              Agreed. I program mainly in C so its easier for me to make sense of bad C code than bad python code which just makes me cry

              J 1 Reply Last reply
              3
              • M [email protected]

                It really doesn't. It's a scripting language, functions are there but at it's core it runs a script. The issue is that it was so easy to start with that people started doing everything in it, even though it sucks for anything past complex scripts

                It is the excel of databases.

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

                Excel recently added the ability to run python code lol

                1 Reply Last reply
                3
                • D [email protected]

                  Since Java 21, this has been shortened significantly. https://www.baeldung.com/java-21-unnamed-class-instance-main

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

                  Only took 27 years to make the Java "Hello, world!" kinda sane.

                  1 Reply Last reply
                  3
                  • M [email protected]

                    It really doesn't. It's a scripting language, functions are there but at it's core it runs a script. The issue is that it was so easy to start with that people started doing everything in it, even though it sucks for anything past complex scripts

                    It is the excel of databases.

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

                    What's the difference between a "scripting" language and a "real" one?

                    M M jackbydev@programming.devJ J 4 Replies Last reply
                    6
                    • F [email protected]

                      What's the difference between a "scripting" language and a "real" one?

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

                      I didn't say it wasn't real, it's just a scripting structure and not object oriented, so it doesn't make sense for it to start by looking for a "main" object

                      F M 2 Replies Last reply
                      1
                      • M [email protected]

                        I didn't say it wasn't real, it's just a scripting structure and not object oriented, so it doesn't make sense for it to start by looking for a "main" object

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

                        What would make it "object oriented"?

                        M 1 Reply Last reply
                        0
                        • F [email protected]

                          What would make it "object oriented"?

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

                          You know what, I take that back:
                          https://docs.python.org/3.13/faq/general.html#what-is-python

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

                            Not having tons of code in one if statement, but in a function.

                            ironkrill@lemmy.caI This user is from outside of this forum
                            ironkrill@lemmy.caI This user is from outside of this forum
                            [email protected]
                            wrote on last edited by
                            #77

                            And scope. Variables declared in the if can be read everywhere, variables declared in the function are limited to that function.

                            1 Reply Last reply
                            4
                            • P [email protected]

                              How do you feel about other peoples Go code?

                              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
                              #78

                              Go code is always an abomination.

                              addie@feddit.ukA 1 Reply Last reply
                              3
                              • M [email protected]

                                I didn't say it wasn't real, it's just a scripting structure and not object oriented, so it doesn't make sense for it to start by looking for a "main" object

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

                                not object oriented

                                I don't think we have a name for what you are trying to say here.

                                (And yeah, "object oriented" isn't it.)

                                A 1 Reply Last reply
                                6
                                • F [email protected]

                                  What's the difference between a "scripting" language and a "real" one?

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

                                  It's a scripting language. What means that the computer runs it line by line, without needing to get the entire project first.

                                  F 1 Reply Last reply
                                  1
                                  • M [email protected]

                                    It's a scripting language. What means that the computer runs it line by line, without needing to get the entire project first.

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

                                    That is not how Python works. There are very few languages that work by executing line-by-line anymore. Unix shell scripts are one of the few holdouts. JavaScript also does it to a certain extent; the browser starts executing line-by-line while a compiler step works in the background. Once the compiler is done, it starts execution of the compiled form right where the line-by-line execution left off. It helps JavaScript be more responsive since it doesn't have to wait for the compiler to finish.

                                    M F 2 Replies Last reply
                                    4
                                    • B [email protected]

                                      I always use

                                      if "__main__" == main:
                                          __main__()
                                      

                                      ..and earlier in the code:

                                      def __main__():
                                          while True:
                                              pass
                                      main = "__main__"
                                      

                                      This helps to prevent people from arbitrarily running my code as a library or executable when I don't went them to.

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

                                      Can you elaborate on this blood magic?

                                      B 1 Reply Last reply
                                      1
                                      • M [email protected]

                                        not object oriented

                                        I don't think we have a name for what you are trying to say here.

                                        (And yeah, "object oriented" isn't it.)

                                        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
                                        #83

                                        procedural programming is more akin to that, but python has far to many oop concepts to be considered procedural imo

                                        F 1 Reply Last reply
                                        0
                                        • F [email protected]

                                          That is not how Python works. There are very few languages that work by executing line-by-line anymore. Unix shell scripts are one of the few holdouts. JavaScript also does it to a certain extent; the browser starts executing line-by-line while a compiler step works in the background. Once the compiler is done, it starts execution of the compiled form right where the line-by-line execution left off. It helps JavaScript be more responsive since it doesn't have to wait for the compiler to finish.

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

                                          Python still has the -i option, and it still runs the same language as the files interface.

                                          F 1 Reply Last reply
                                          0
                                          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