user200783
user200783

Reputation: 14348

Order of functions within a Python source file

In languages such as C and C++, it is common to define called functions above their callers, in order to avoid the need for forward declarations. For example:

void g() { ... }

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

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

In Python, if the

if __name__ == '__main__': 
    main() 

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

Is there any convention for the order of functions within a Python source file? Are called functions still generally written above callers, or vice-versa?

Upvotes: 11

Views: 9043

Answers (2)

user200783
user200783

Reputation: 14348

There is no convention (for example, there is nothing in PEP 8) regarding function order. Even modules within the standard library are inconsistent.

Upvotes: 2

too honest for this site
too honest for this site

Reputation: 12263

For statically typed languages, it is sufficient to look for its definition to determine the type of an object. However, if the definition appears after its usage, two passes would be required: 1) determine the types of such objects, 2) compile using the then-known type. If the definition was in another file, that would have to be parsed, too, before pass 2. This is circumventend by requiring an object/type to be declared (tell the compiler it exists and about its type) before its usage. That is sufficient to compile. The actual definition just reserves space for the object and is not required to generate the actual code (mostly) - that's what the declaration is for. (Remember: most such langauages allow to combine both where appropriate).

In Python, as a dynamically typed language, the object (value and type) a name references (!) can change anytime before its actual usage by the control flow, so it is useless to verify it before its actual usage.

Consider the following:

def f():
    g()

def g():
    pass

f()

That might look as if controverts the "define first" policy. But it actually does not, as g() will be only required when f() is actually executing. That is not before the last line (f()) is executed, at which point g() has very well been defined.

Upvotes: 8

Related Questions