Search code examples
python-3.xpython-idle

Why does IDLE *sometimes* require a space after an int


The IDLE shell (ver 3.10.5) allows this statement (note the omitted space between 2 and in):

2in range(5)
True

But it complains about these:

if True:
    2in range(5)   
SyntaxError: invalid decimal literal

def always_true():
    2in range(5)    
SyntaxError: invalid decimal literal

Why is the first one allowed, but the others not?


Solution

  • In interactive python3.10.5 (on Windows 10), 2in range(5) always returns True. Why does IDLE run on python3.10.5 show a different result? IDLE does NOT compile or run the Python code you write. However, its Shell uses a subclass of code.InteractiveInterpreter and the latter compiles interactive input with codeop._maybe_compile. (code and codeop are builtin modules that most people never use directly.) _maybe_compile attempts to simulate the custom line-by-line behavior of interactive python mode. This workaround is tricky and perhaps impossible to do exactly, especially as the details of parsing change. I don't know yet how IDLE on 3.10.5 gets the 'invalid decimal literal' message as I have not yet reproduced it by directly calling compile().

    To say a bit more: In current interactive Python 3.10.5+ (the development version of the future 3.10.6 release, all uses of 2in range(5) emit "DeprecationWarning: invalid decimal literal" besides returning 'True'. In 3.11.0b3+ and 3.12.0a0, the message has changed to "SyntaxWarning:...". Somewhere from _maybe_compile to Shell, the warning is turned into an error. In 3.13 or maybe later, the warning will become an error for everyone.