2

How can I define a prototype of a function? I called my function above of its definition. but it did not work. python interpreter cannot recognize my function.

For example:

my_function()
...
def my_function():
    print("Do something...")
Unresolved reference 'my_function'
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
  • 4
    You can't. Why do you think you need to? – Martijn Pieters Oct 09 '19 at 14:28
  • 3
    *Unresolved reference* is not a Python exception. What's the actual error output you see? Your code would either throw a `NameError: name 'my_function' is not defined` exception (when this is in the global scope of a module) or `UnboundLocalError: local variable 'my_function' referenced before assignment` if this is in a function scope. – Martijn Pieters Oct 09 '19 at 14:31

2 Answers2

3

You can't. Within the same scope, code is executed in the order it is defined.

In Python, a function definition is an executable statement, part of the normal flow of execution, resulting in the name being bound to the function object. Next, names are resolved (looked up) at runtime (only the scope of names is determined at compile time).

This means that if you define my_function within a module or function scope, and want to use it in the same scope, then you have to put the definition before the place you use it, the same way you need to assign a value to a variable name before you can use the variable name. Function names are just variables, really.

You can always reference functions in other scopes, provided those are executed after the referenced function has been defined. This is fine:

def foo():
    bar()

def bar():
    print("Do something...")

foo()

because foo() is not executed until after bar() has been defined.

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
1

Only after main() function,

#!/usr/local/bin/python

def main ():
  my_function()

def my_function():
  print("Do something...")

if __name__ == "__main__":
  main ()

def statements are really executable statements and not declarations, Order is important here.

Stidgeon
  • 2,673
  • 8
  • 20
  • 28
Purushoth.Kesav
  • 615
  • 7
  • 16