Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Shift+enter inserts extra indents

I have a Python source file with some dummy code:

a = 3
if a == 1:
    print("a = 1")
elif a == 2:
    print("a = 2")
else:
    print("Other")

When I submit the code to terminal with shift+enter, I get the following error. It looks like VS Code changed the indentation of my code. The same code ran just fine with shift+enter on my other computer. The error message is as below:

PS C:\Users\win32> & C:/Users/win32/AppData/Local/Programs/Python/Python313/python.exe
Python 3.13.0 (tags/v3.13.0:60403a5, Oct  7 2024, 09:38:07) [MSC v.1941 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> a = 3
>>> if a == 1:
...         print("a = 1")
...         elif a == 2:
...                     print("a = 2")
...                     else:
...                                 print("Other")
... 
  File "<python-input-1>", line 3
    elif a == 2:
    ^^^^
SyntaxError: invalid syntax

Any insights?

like image 971
PingPong Avatar asked Nov 17 '25 07:11

PingPong


1 Answers

This has to do with the indentation behavior change in the REPL from Python3.12 to Python3.13, so that's why it works on one of your computer but fails on another.

In the new Python3.13 REPL, if you type if a==1: followed by a newline, the REPL knows that an indentation is expected, and so it inserts one for you, but the text that the VSCode plugin pastes to the REPL for you also contains an indentation. That's where the double indentation comes from.

The answer by @Minxin Yu - MSFT has already included the corresponding bug report. Since it is marked as completed, upgrading VSCode Python plugin should solve the issue. If it doesn't, for now you may stick to Python3.12 as that answer indicates. Alternatively, as indicated in the official documentation link above, you may define the PYTHON_BASIC_REPL environment variable to recover the Python3.12 behavior. With that said, I cannot reproduce the behavior in the question using Shift+Enter with my VSCode, so I'm not entirely sure whether the environment variable works, but I can confirm that launching VSCode with that environment variable does put the REPL in the legacy mode.

like image 119
Weijun Zhou Avatar answered Nov 19 '25 21:11

Weijun Zhou