better error messages

Easier troubleshooting with improved error messages

The biggest Python 3.10 improvements by far are all related improved error messages . I make typos all the time.

Error messages that help me quickly figure out what’s wrong are really important.

I’ve already grown accustom to the process of deciphering many of Python’s more cryptic error messages. So while improved error messages are great for me, this change is especially big for new Python learners .

When I teach an introduction to Python course, some of the most common errors I help folks debug are:

  • Missing colons at the end of a block of code

  • Missing indentation or incorrect indentation in a block of code

  • Misspelled variable names

  • Brackets and braces that were never closed

Python 3.10 makes all of these errors (and more) much clearer for Python learners.

New Python users often forget to put a : to begin their code blocks. In Python 3.9 users would see this cryptic error message:

$ python3.10 temp.py 70
  File "/home/trey/temp.py", line 4
    if temperature < 65
                       ^
SyntaxError: invalid syntax

Python 3.10 makes this much clearer:

$ python3.10 temp.py 70
  File "/home/trey/temp.py", line 4
    if temperature < 65
                       ^
SyntaxError: expected ':'

Indentation errors are clearer too (that after ‘if’ statement on line 4 is new):

$ python3.10 temp.py 70
  File "/home/trey/temp.py", line 5
    print("Too cold")
    ^
IndentationError: expected an indented block after 'if' statement on line 4

And incorrect variable and attribute names now show a suggestion:

$ python3.10 temp.py 70
Traceback (most recent call last):
  File "/home/trey/temp.py", line 4, in <module>
    if temparature < 65:
NameError: name 'temparature' is not defined. Did you mean: 'temperature'?

I’m really excited about that one because I make typos in variable names pretty much daily.

The error message shown for unclosed brackets, braces, and parentheses is also much more helpful.

Python used to show us the next line of code after an unclosed brace:

$ python3.9 temp.py 70
  File "/home/trey/temp.py", line 6
    elif temperature > 80:
    ^
SyntaxError: invalid syntax

Now it instead points to the opening brace that was left unclosed:

$ python3.10 temp.py 70
  File "/home/trey/temp.py", line 5
    print("Too cold"
         ^
SyntaxError: '(' was never closed

You can find more details on these improved error messages in the better error messages section of the “What’s new in Python 3.10” documentation.

While Python 3.10 does include other changes (read on if you’re interested), these improved error messages are the one 3.10 improvement that all Python users will notice.

Better Error Messages by Realpython