Must define functions before they are called ?? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

Must define functions before they are called ??

At first I was agree with that statement, then I recently saw a piece of code where a function is called before its definition. here is The link @Github: https://github.com/hartleybrody/fb-messenger-bot/blob/master/app.py as you Can see The function send_message(...) is called within The function webhook(...) before its definition . is there something I missed ?

1st Jan 2017, 9:35 AM
R00T_L33
R00T_L33 - avatar
4 Answers
+ 2
The reason is the last if statement at the end of the file. the following code will work normally (I made this code public in the code playground): def foo():   bar()   print('foo') def bar():   print('bar')   if __name__ == '__main__':   foo()
1st Jan 2017, 10:18 AM
Mohamed
+ 1
OK, you need to know how the interpreter works (roughly): When the Python interpreter executes a file (through an import statement or a module execution), it first works it way through the whole file, executing the high-level statements and putting in its own memory where the functions are. So you can put a function call before its definition without any kind of trouble
2nd Jan 2017, 12:27 AM
Amaras A
Amaras A - avatar
0
Python usually execute the script line by line. However, if that "if statement" is present, then it means that is the starting point of the app (like main method in Java and C++). Since Python will start from that point, it will check all the file before starting, thus no throwing the error you asked about.
2nd Jan 2017, 5:49 AM
Mohamed
0
Ok, thank you guys ! I think I get it but I have to practice that.
2nd Jan 2017, 8:52 AM
R00T_L33
R00T_L33 - avatar