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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With