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?

  • embed_me@programming.dev
    link
    fedilink
    arrow-up
    16
    ·
    24 days ago

    Sometimes I have the misfortune of working with python code written by someone else and I wonder how a language like this became anything more than a scripting language

    • bastion@feddit.nl
      link
      fedilink
      arrow-up
      3
      ·
      24 days ago

      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.

        • bastion@feddit.nl
          link
          fedilink
          arrow-up
          3
          ·
          edit-2
          24 days ago

          It simply swaps some things around to make things more confusing, then goes into an infinite loop (whether or not you import or execute it standalone). it’s no different than just including in the global scope:

          while True:
              pass
          

          I was kinda lazy with the fuckery, tbh. I could have gotten much more confusing, but don’t have too much time today. :-)

  • jjjalljs@ttrpg.network
    link
    fedilink
    arrow-up
    5
    ·
    24 days ago

    Call the function from the if block.

    Now your tests can more easily call it.

    I think at my last job we did argument parsing in the if block, and passed stuff into the main function.

  • onlinepersona@programming.dev
    link
    fedilink
    arrow-up
    2
    ·
    edit-2
    24 days ago

    Can someone explain to me how to compile a C library with “main” and a program with main? How does executing a program actually work? It has an executable flag, but what actually happens in the OS when it encounters a file with an executable file? How does it know to execute “main”? Is it possible to have a library that can be called and also executed like a program?

    Anti Commercial-AI license

    • namingthingsiseasy@programming.dev
      link
      fedilink
      arrow-up
      1
      ·
      24 days ago

      There are a lot of other helpful replies in this thread, so I won’t add much, but I did find this reference, which you could read if you have a lot of free time. But I particularly liked reading this summary:

      • _start calls the libc __libc_start_main;
      • __libc_start_main calls the executable __libc_csu_init (statically-linked part of the libc);
      • __libc_csu_init calls the executable constructors (and other initialisatios);
      • __libc_start_main calls the executable main();
      • __libc_start_main calls the executable exit().