+ 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 ?
4 ответов
+ 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()
+ 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
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.
0
Ok, thank you guys ! I think I get it but I have to practice that.