An idea to make it clearer where main processing starts

I often find it tricky to work out where the actual processing starts in a Python program. It’s not impossible, of course but it means wading through, potentially, dozens of functions before encountering the main processing.

I’ve been writing programs professionally and non-professionally for around fifty years and I’ve encountered all standards of coding using many different languages.

One of my favourite languages is The REXX Language.

REXX (like Python) relies heavily on functions (and subroutines). And the way the interpreter handles subroutines is thus:

  1. Consult function table
  2. Have I encountered this function before?
  3. If yes, branch to function
  4. If no, add function to table and branch to function

Thus, in the interests of efficiency, one should code the first called function as the last function in the code and, therefore, the function table will be built very early on in processing.

Would it be possible for Python to use a similar method?

If this was employed then coders and code maintainers would be able to see instantly where the main processing begins.

I, personally, would find this very useful and I wonder what other people think.

It doesn’t matter where the function is declared. It may be declared in another library. You only need to find the first function call starting from the top.

It is always recommended to check if the script is the main module being run, so the module can also be used as a library:

if __name__ == "__main__":
    ...
1 Like

I’m having a hard time understanding how your idea would work or how it would help.

Is the idea that the “function table” (not a concept that currently exists in Python) records the functions in order, so that you can see which was the first to be called?

You can do something similar in Python today in a running program by printing the stack trace (traceback.print_stack()), which will show you the first user function to be called, at least on the main thread.

Knowing which function was the first to be called in the program might not be particularly interesting; I suspect it will be some function in site.py or the import system.

It sounds like you are suggesting a coding convention for people to adopt for their projects. Many people already write their main Python file this way, though some people like to have the main function first rather than last.

2 Likes

In my REXX programming, I always put the main code at the top, and functions below that. But these days, I always try to have the entry point at the bottom of the code (either a main() function or the equivalent), to ensure that functions are defined before they’re used. It’s a good policy to follow and is reasonably easy to maintain in Python too.