Define functions on top or bottom of a script?

In Python, all functions must be defined before they are available. This leaves two options for writing a script:

  • Define the functions above:

    def f1():
        # something
    
    def f2():
        # something
    
    # Call f1
    f1()
    # Call f2
    f2()
    
  • Define the functions below:

    def main():
        # Call f1
        f1()
        # Call f2
        f2()
    
    def f1():
        # something
    
    def f2():
        # something
    
    # Call main() at the bottom, after all the functions have been defined.
    if __name__ == '__main__':
        main()
    

Starting with Fortran, I was used to define functions at the bottom, but I saw a lot of Python scripts where the definition at the top seems to be preferred.

Is one of these options more Pythonic / recommended than the other? If so, why?

(I do not ask for an “opinion”; I ask for a reasoned reason why one of them is preferable, or if both of them are considered equally valid.)

+4
source share

Source: https://habr.com/ru/post/1679386/


All Articles