[Python] Inconsistent behavior between Python function and VS Code debugger for scope lookup

Discussão em 'Python' iniciado por Stack, Dezembro 9, 2024.

  1. Stack

    Stack Membro Participativo

    For the following code (revised):

    # infile.py

    FILE1 = 'file1'
    FILE2 = 'file2'

    def getfile():
    # Note: I am doing the equivalent of this with VS Code debugger:
    # breakpoint()
    file = FILE1 if 'FILE1' in locals() else FILE2
    print(f'{file=}')

    if __name__ == '__main__':
    getfile()


    If I run this on Windows (using Python 3.12.7 or Python 3.13.0), here's what I see:

    PS> .\infile.py
    file='file2'


    If I run this in my VS Code debugger (v1.95.3, Python v2024.20.0, Pylance v2024.12.1, Python Debugger v2024.12.0), here's what I see:

    # Uncomment breakpoint at first line in above def getfile function
    # Start VS Code in debugging mode (F5)
    # VS Code stops at breakpoint
    # From VS Code Debug Console, execute following:
    file = FILE1 if 'FILE1' in locals() else FILE2

    print(f'{file=})

    # Output:
    file='file1'


    My expectation was the result shown in the VS Code debugger above. It sounds like I'm not quite understanding something with Python scoping. What am I missing?

    I'm also curious why I see a difference between what Python does and what the VS Code Python debugger shows. Am I doing something wrong, or is this a bug?

    Revised: If I do this with pdb, I see this:

    PS> .\infile
    > ...\infile.py(9)getfile()
    -> breakpoint()
    (Pdb) l
    4 FILE1 = 'file1'
    5 FILE2 = 'file2'
    6
    7
    8 def getfile():
    9 -> breakpoint()
    10 file = FILE1 if 'FILE1' in locals() else FILE2
    11 # file = FILE1 if 'FILE1' in globals() else FILE2
    12 print(f'{file=}')
    13
    14
    (Pdb) 'FILE1' in locals()
    False
    (Pdb) 'FILE1' in globals()
    True
    (Pdb)


    So, I think what I really want is to use globals() - is that right?

    Continue reading...

Compartilhe esta Página