Better Error Messages
00:10 Many different kinds of errors raised by the compiler have been improved. This includes better indication of where the error happened and better indication of what the error was and where on the line it took place.
00:24 In the top window, I’m going to show you Python 3.9, while in the bottom window, I’ll show you the new differences in 3.10. I’ll start out first with a bunch of errors with dictionaries and comprehensions.
00:55 In Python 3.10, the same error gives a better indication of where the problem lies within the statement, highlighting the entire generator expression. This next one is an actual comprehension. To better understand the problem, let’s first look at some working code.
This is a dictionary instantiated using the standard library’s
zip() function. Here,
zip() is taking the first item from the first string and combining it with the first item of the second string and creating a tuple.
This error isn’t too helpful. It says the syntax is invalid but not why, and it points to the
for keyword instead of the
x, y part that actually caused the problem. Now let’s look at this in 3.10.
invalid syntax. And now in 3.10. You see not only what went wrong, but exactly which opening bracket was mismatched. Now let’s look at improvements around exception blocks. Once again, I’m back to Python 3.9 in the top window and 3.10 in the bottom.
A lot of programming languages allow value assignment inside of a condition block. This makes for a tricky-to-find bug. If you accidentally use a single equals (
=) instead of a double (
==), you assign the value and that returns
True. Because this problem was so common, Python decided to disallow assignment in condition blocks.
06:47 Consider this list containing the months from quarter one, and then another from quarter two. You can combine these into the first half of the year list by expanding them with the star operator.
07:36 Python’s use of whitespace for coding blocks is the favorite complaint of non-Pythonistas. However you feel about it, the error message when you forget to do it has at least improved. Here’s 3.9.
07:59 And a subtle improvement in 3.10 that indicates the block type that expected the indent. Some command line terminals now support suggestions when you make a typo. Now, Python’s REPL supports the same concept.
Note that underneath, this is all implemented in a method called
PyErr_Display(), and not all REPLs use this method for error management. But for those that do, you get the new feature. Let me import
Become a Member to join the conversation.