skip to Main Content

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


  1. 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.

    Login or Signup to reply.
  2. Python compiles the module and then executes it starting at the top. Looking at the disassembly with line numbers on the left

      1           0 LOAD_NAME                0 (hello)
                  2 CALL_FUNCTION            0
                  4 POP_TOP
    
      3           6 LOAD_CONST               0 (<code object hello at 0x7f3ee7adeef0, file "test.py", line 3>)
                  8 LOAD_CONST               1 ('hello')
                 10 MAKE_FUNCTION            0
                 12 STORE_NAME               0 (hello)
                 14 LOAD_CONST               2 (None)
                 16 RETURN_VALUE
    

    the already-compiled function <code object hello> isn’t stored to the global variable hello until line 3 (STORE_NAME 0 (hello)). That is after the LOAD_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.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search