I’ve been struggling with Python in VS Code because my functions weren’t being recognized.
I tried following a bunch of stuff in this Q&A:
No definition found for function – VSCode Python.
I also tried messing with the interpreter, the python settings, updating to Python 3.11, different environments and nothing worked.
Then I discovered when running this, it works totally fine.
def hello():
print("Hello World!")
hello()
But when running this, it gives an error that hello()
isn’t defined
hello()
def hello():
print("Hello World!")
It’s been a few years since I’ve done any coding with Python but this feels weird. I’m used to this logic in Powershell, but everywhere else I’m used to it not caring where it’s defined as long as it is defined properly.
Unless this is something related to it being a basic script file that doesn’t have a main()
function. It’s a script that I only plan to run from VS Code, so if I have to define my functions before invoking them I can do it that way. I just prefer to put my functions at the bottom because I’m usually writing them as I’m figuring things out and breaking things into smaller parts.
2
Answers
Python is interpreted from the top to the bottom, meaning that functions must be defined before they are called. This is true for all python scripts, not just ones run on VS Code.
Python compiles the module and then executes it starting at the top. Looking at the disassembly with line numbers on the left
the already-compiled function
<code object hello>
isn’t stored to the global variablehello
until line 3 (STORE_NAME 0 (hello)
). That is after theLOAD_NAME
on line 1 that causes the fail.The only rule is that the name "hello" must be resolved to a function object at the time of the call.