By Arman Laalfam


2019-10-09 14:27:25 8 Comments

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'

2 comments

@Martijn Pieters 2019-10-09 14:35:52

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.

@CrazyKP 2019-10-09 14:36:00

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.

Related Questions

Sponsored Content

23 Answered Questions

[SOLVED] Does Python have a ternary conditional operator?

12 Answered Questions

[SOLVED] Calling a function of a module by using its name (a string)

  • 2008-08-06 03:36:08
  • ricree
  • 621185 View
  • 1538 Score
  • 12 Answer
  • Tags:   python object

62 Answered Questions

[SOLVED] Calling an external command in Python

10 Answered Questions

[SOLVED] Does Python have a string 'contains' substring method?

31 Answered Questions

[SOLVED] "Least Astonishment" and the Mutable Default Argument

28 Answered Questions

[SOLVED] Finding the index of an item given a list containing it in Python

  • 2008-10-07 01:39:38
  • Eugene M
  • 3455383 View
  • 2844 Score
  • 28 Answer
  • Tags:   python list indexing

16 Answered Questions

[SOLVED] What are metaclasses in Python?

18 Answered Questions

[SOLVED] Using global variables in a function

17 Answered Questions

[SOLVED] Are static class variables possible in Python?

9 Answered Questions

[SOLVED] Proper way to declare custom exceptions in modern Python?

Sponsored Content