Declare function at end of file in Python

PythonFunctionFormatting

Python Problem Overview


Is it possible to call a function without first fully defining it? When attempting this I get the error: "function_name is not defined". I am coming from a C++ background so this issue stumps me.

Declaring the function before works:

def Kerma():
        return "energy / mass"    

print Kerma()

However, attempting to call the function without first defining it gives trouble:

print Kerma()

def Kerma():
    return "energy / mass"

In C++, you can declare a function after the call once you place its header before it.

Am I missing something here?

Python Solutions


Solution 1 - Python

One way that is sort of idiomatic in Python is writing:

def main():
    print Kerma()

def Kerma():
    return "energy / mass"    

if __name__ == '__main__':
    main()

This allows you to write you code in the order you like as long as you keep calling the function main at the end.

Solution 2 - Python

When a Python module (.py file) is run, the top level statements in it are executed in the order they appear, from top to bottom (beginning to end). This means you can't reference something until you've defined it. For example the following will generate the error shown:

c = a + b  # -> NameError: name 'a' is not defined
a = 13
b = 17

Unlike with many other languages, def and class statements are executable in Python—not just declarative—so you can't reference either a or b until that happens and they're defined. This is why your first example has trouble—you're referencing the Kerma() function before its def statement has executed and body have been processed and the resulting function object bound to the function's name, so it's not defined at that point in the script.

Programs in languages like C++ are usually preprocessed before being run and during this compilation stage the entire program and any #include files it refers to are read and processed all at once. Unlike Python, this language features declarative statements which allow the name and calling sequence of functions (or static type of variables) to be declared (but not defined), before use so that when the compiler encounters their name it has enough information to check their usage, which primarily entails type checking and type conversions, none of which requires their actual contents or code bodies to have been defined yet.

Solution 3 - Python

This isn't possible in Python, but quite frankly you will soon find you don't need it at all. The Pythonic way to write code is to divide your program into modules that define classes and functions, and a single "main module" that imports all the others and runs.

For simple throw-away scripts get used to placing the "executable portion" at the end, or better yet, learn to use an interactive Python shell.

Solution 4 - Python

If you are willing to be like C++ and use everything inside a functions. you can call the first function from the bottom of the file, like this:

def main():
    print("I'm in main")
    #calling a although it is in the bottom
    a()

def b():
   print("I'm in b")

def a():
   print("I'm in a")
   b()

main()

That way python is first 'reading' the whole file and just then starting the execution

Solution 5 - Python

Python is a dynamic programming language and the interpreter always takes the state of the variables (functions,...) as they are at the moment of calling them. You could even redefine the functions in some if-blocks and call them each time differently. That's why you have to define them before calling them.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionTheGentleOneView Question on Stackoverflow
Solution 1 - PythonMuhammad AlkarouriView Answer on Stackoverflow
Solution 2 - PythonmartineauView Answer on Stackoverflow
Solution 3 - PythonEli BenderskyView Answer on Stackoverflow
Solution 4 - PythonaryeView Answer on Stackoverflow
Solution 5 - PythoneumiroView Answer on Stackoverflow