The order of functions in the Python source file

In languages ​​like C and C ++, you can usually define callable functions above your callers to avoid the need for forward declarations. For instance:

void g() { ... } void f() { g(); ... } int main() { f(); ... } 

In Python, if

 if __name__ == '__main__': main() 

idiom is used at the end of the source file, forward declarations are not needed, and the order of the functions does not matter.

Is there any convention for ordering functions in a Python source file? Called functions, which are usually written higher than callers, or vice versa?

Edit:. The answer is that there is no agreement (for example, in PEP 8 there is nothing) regarding the order of functions. Even the modules in the standard library are incompatible.

+5
source share
1 answer

For statically typed languages, just find its definition to determine the type of object. However, if the definition appears after its use, two passes will be required: 1) determine the types of such objects, 2) compile using the then-known type. If the definition was in another file, it would also need to be analyzed before passing 2. This is bypassed by requiring an object / type declaration (telling the compiler and its type) before using it. This is enough to compile. The actual definition simply reserves space for the object and it is not necessary to generate the actual code (basically) - for what the declaration is intended. (Remember: most of these langauages ​​allow you to combine them where necessary).

In Python, as a dynamically typed language, an object (value and type) of name references (!) Can change at any time before its actual use by the control flow, so it is useless to check it before its actual use.

Consider the following:

 def f(): g() def g(): pass f() 

It may look as if it contradicts the “define the first” policy. But in fact, this is not so, since g() will be required only when f() actually executed. This is not before the last line ( f() ) is executed, at which point g() very well defined.

+3
source

All Articles