117

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?

Kev
  • 118,037
  • 53
  • 300
  • 385
TheGentleOne
  • 1,735
  • 2
  • 11
  • 7
  • 9
    In Python there's no "declare". There's the definition (which must be complete) or there's nothing. – S.Lott Sep 20 '10 at 18:35
  • 2
    You say, "it gives trouble". Can you elaborate on that? – Martin Del Vecchio Sep 20 '10 at 18:51
  • In case anyone is wondering: `Kerma is an acronym for "kinetic energy released per unit mass"` – anon Apr 09 '17 at 20:57
  • 2
    I know this is super old, but why has no one recommended putting the functions in a separate `.py` file and importing that? Is there some unintended consequences? – Kyle Apr 13 '17 at 20:01
  • 1
    @Kyle Importing just pastes the imported code before the current code at compile time, so it's the same as defining the functions in the current code before calling them xD – NoName May 01 '19 at 18:41
  • @NoName learn something new everyday! Thanks for the info. – Kyle May 02 '19 at 19:19
  • 1
    A vast oversight in python, it should read the file before executing so all functions are available, suggest they fix it fer pete's sake in 4x – gseattle Feb 12 '21 at 11:08
  • @NoName It is not the same from a coder's POV while editing. The script is easier to manage. – Melvin Calvin Sep 22 '21 at 18:17
  • @gseattle that would be fundamentally opposed to how Python works and is designed. Code runs in the order it is written, and a `def` *statement* is *code* that runs in order to *create a function object* and assign it to the function's name. Code at the top level *runs* whenever the file is either executed or imported, which is both a) why you don't need any specially named entry point; b) why it is possible for the `if __name__ == '__main__':` idiom to work. – Karl Knechtel Jun 29 '22 at 16:36
  • To be more clear, Python, almost great, is clumsy, just read the whole file in first, simple, instead of executing line-by-line like a batch file and then no need for placing operative code below functions or the clunky extra `if __name__ == '__main__':`. I like Python but frankly Perl was superior on this point. – gseattle Feb 19 '23 at 10:53

5 Answers5

190

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.

Muhammad Alkarouri
  • 23,884
  • 19
  • 66
  • 101
  • 5
    @Muhammad: while this is a viable approach, it surely isn't idiomatic in Python. Quite the opposite, you'll notice most `main` functions are usually placed at the end. – Eli Bendersky Sep 20 '10 at 18:28
  • 18
    @Eli Bendersky: I'd submit that the `if __name__ == '__main__':` switch is the common idiomatic part. – S.Lott Sep 20 '10 at 18:36
  • 2
    @Eli: the idiomatic part is the if clause at the end: no code at the top level of the module, then at the end invoke a main function if the module is __main__. – Ned Batchelder Sep 20 '10 at 18:36
  • @S.Lott and @Ned: of course, but note Muhammad's sentence after the code sample which specifically points to placing `main` above and calling it below. The `if __name__` part is tangential in that answer, or at least not given attention. – Eli Bendersky Sep 20 '10 at 18:38
  • 1
    @Eli: The idiomatic part is the `if ... __main__':`. I didn't say that the `main` should be placed above the rest of the code. I said the important part is calling `_\_main__` at the end, and it doesn't matter where you place its definition then. – Muhammad Alkarouri Sep 20 '10 at 18:42
  • 3
    With the if __name__ == '__main__': switch it becomes irrelevant how you order your functions. That's the right thing(TM) to do. – MKesper Dec 16 '16 at 09:07
  • I am confused about the usage. The code fails if I make the `Kerma()` to be an inner function. – Simon Z. Sep 06 '20 at 13:23
  • 1
    @SimonZ. you are supposed to do the definition of the function outside the definition of main – Melvin Calvin Sep 22 '21 at 18:22
21

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.

martineau
  • 119,623
  • 25
  • 170
  • 301
  • It's not that a dynamic language can't do that. Perl is a dynamic language and you can call a function before you define it. That's because it has a compile phase and an execute phase (though oddly, but usefully, you can arrange to execute code during the compile phase). This works: `doit(); sub doit { print("I'm doing it!\n"); }` – John Deighan Jul 29 '19 at 06:20
14

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.

Eli Bendersky
  • 263,248
  • 89
  • 350
  • 412
10

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

arye
  • 458
  • 3
  • 15
6

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.

Nijat Aliyev
  • 190
  • 3
  • 13
eumiro
  • 207,213
  • 34
  • 299
  • 261