More Helpful and Precise Error Messages With Python 3.10

Real Python · Beginner ·📰 AI News & Updates ·4y ago

Key Takeaways

The video covers the new features in Python 3.10, specifically the improvements to error messages, including better indication of where the error occurred and more accurate error highlighting. It also touches on other features such as structural pattern matching, type hint improvements, and changes to the zip function.

Full Transcript

welcome to python 310 cool new features my name is chris and i will be your guide in this course you will learn all about the new features packed into the 310 release of python including better error messages structural pattern matching type hint improvements changes to zip and new multi-variable statistics methods python 310 was released on october 4th 2021 and was actively being worked on since may of 2020 the key features of this release are better error messages python aims to be both powerful and beginner friendly up until 3 10 a lot of the syntax error messages have been rather cryptic you might not notice them because you're used to them but if you ever stop to read their contents you might see how challenging it could be for a new coder not only are the messages themselves a little confusing but they often point to the line after the problem was triggered within most error messages there's a little pointer showing where on the line of code the error occurs in addition to improving indications of what line the error happens on 310 also adds more accurate error highlighting with these pointers the big new syntax structure in 310 is the pattern matching statement which introduces two new keywords match and case if you've come from another programming language that supports a switch statement you'll be familiar with the basics but python's implementation goes far deeper than that there's a whole bunch of type hint goodness in python 310. there are improvements to unions aliases and guards as well as better support for type hinting decorators there's also a new introspection call allowing you to get information about annotations used for type hinting at runtime the standard library zip method has a new parameter that makes it safer to use by raising an error if you attempt to zip things of unequal length and there are also three new functions in the statistics library covariance correlation and linear regression and finally there are a whole host of small improvements like default text encodings asynchronous iteration multiple context managers additions to the cis module giving info on the interpreter and dropped support for older ssl in the next lesson i'll show you all the new ways the compiler will tell you you're wrong and that's a good thing in the previous lesson i gave you an overview of the course in this lesson i'll be talking about the error message improvements introduced in python 310. 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 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 310 i'll start out first with a bunch of errors with dictionaries and comprehensions strictly speaking this first one isn't a comprehension but it's very similar it's an embedded generator statements like these must be wrapped in parenthesis to be legal in python 310 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 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 it does this for all the items in both strings and then these tuples are turned into key value pairs by the dictionary here is the exact same thing but using the dictionary comprehension instead with me so far okay let's cause a problem like with the embedded generator before parentheses are required this error isn't too helpful it says the syntax is invalid but not y and it points to the four keyword instead of the x y part that actually caused the problem now let's look at this in 310 that's much better isn't it how about some easy to make dictionary mistakes here i've missed the comma after february and the 310 version 310 is much more specific let's do something else this time instead of comma i'll miss the value altogether another very generic message which is far improved in 310. consider this small program in the top window where the month stick is missing its closing brackets let me run this in 3 9 good old invalid syntax and now in 310. 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 python39 in the top window and 310 in the bottom exception blocks can catch multiple exceptions through the use of parenthesis let me show you a working example and now here's what happens if you forget the parenthesis let's try that in 310 in 310 there's a highlight line showing you where the cause is and a nice clear message to go with the syntax error what about if you forget your accept clause that goes with the try block your usual vagueness here and in 310. much improved there are also improvements in other kinds of blocks as well missing colons go from invalid syntax to a specific indication of what you forgot 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 single equals instead of double you assign the value and that returns true because this problem was so common python decided to disallow assignment in condition blocks python eventually added the walrus operator to allow this but it is still a special operator regular value assignment can't happen in a condition clause here's an example of 3 9 syntax error and now the improvement in 310 it's a nice little hint there to go with it f strings are one of my favorite python features i can't imagine going back to the days of percent s or format although they are very powerful there are still some restrictions within an f string one of those restrictions is the use of the star operator if you haven't seen the star operator before it's used to expand a list in place let me start with a working example 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 that's great but you're not allowed to do that in an f string the improvement in 310 isn't a lot but it does explicitly make an indication of the problem not as drastic as some of the other improvements but still useful python's use of white space 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 three nine and a subtle improvement in 310 that indicates the block type that expected the indent some command line terminals now support suggestions when you make a typo now python's reple supports the same concept note that underneath this is all implemented in a method called pi air display and not all repels use this method for error management but for those that do you get the new feature let me import collections and in three nine i'll misspell named tuple i'm going to create a variable named fool and then access foo instead let's try these in 310. did i mean named tuple well yes indeed i did fool me once shame on you fool me twice don't be food again that's it for the errors next up python's answer to switch

Original Description

Python 3.10 is out! Each new version of Python brings a host of changes, and this version is no exception. This video covers the various updates to how error messages have been improved in Python 3.10. Click here for more info about the complete course: https://realpython.com/courses/cool-new-features-python-310/ In the complete course, you’ll learn about: - Debugging with more helpful and precise error messages - Using structural pattern matching to work with data structures - Adding more readable and more specific type hints - Checking the length of sequences when using zip() - Calculating multivariable statistics
Watch on YouTube ↗ (saves to browser)
Sign in to unlock AI tutor explanation · ⚡30

Playlist

Uploads from Real Python · Real Python · 0 of 60

← Previous Next →
1 A better Python REPL – bpython vs python interpreter
A better Python REPL – bpython vs python interpreter
Real Python
2 Introducing large-type.com – A Utility Website
Introducing large-type.com – A Utility Website
Real Python
3 Reading Hacker News Without Wasting Tons of Time
Reading Hacker News Without Wasting Tons of Time
Real Python
4 Forward References and Python 3 Type Hints
Forward References and Python 3 Type Hints
Real Python
5 Using Sublime Text as your Git Editor
Using Sublime Text as your Git Editor
Real Python
6 Python Code Linting and Auto-Complete for Sublime Text
Python Code Linting and Auto-Complete for Sublime Text
Real Python
7 Make your Python Code More Readable with Custom Exceptions
Make your Python Code More Readable with Custom Exceptions
Real Python
8 Write Better Tests with Sublime Text's Split Layout Feature
Write Better Tests with Sublime Text's Split Layout Feature
Real Python
9 How to Use Sublime Text from the Command Line
How to Use Sublime Text from the Command Line
Real Python
10 Rename Variables with Multiple Selection in Sublime Text
Rename Variables with Multiple Selection in Sublime Text
Real Python
11 Sublime Text Settings for Writing PEP 8 Python
Sublime Text Settings for Writing PEP 8 Python
Real Python
12 Write Cleaner Python with Sublime Text's Indent Guides
Write Cleaner Python with Sublime Text's Indent Guides
Real Python
13 Sublime Text Whitespace Settings for Python Development
Sublime Text Whitespace Settings for Python Development
Real Python
14 Function Argument Unpacking in Python
Function Argument Unpacking in Python
Real Python
15 Python Code Review: Debugging and Refactoring "Conway's Game of Life" +  Automated Tests
Python Code Review: Debugging and Refactoring "Conway's Game of Life" + Automated Tests
Real Python
16 Using "get()" to Return a Default Value from a Python Dict
Using "get()" to Return a Default Value from a Python Dict
Real Python
17 A Python Shorthand for Swapping Two Variables
A Python Shorthand for Swapping Two Variables
Real Python
18 Python Code Review: Refactoring a Web Scraper, PEP 8 Style Guide Compliance, requirements.txt
Python Code Review: Refactoring a Web Scraper, PEP 8 Style Guide Compliance, requirements.txt
Real Python
19 Click & Jump to Test Failures from the Command Line (iTerm2)
Click & Jump to Test Failures from the Command Line (iTerm2)
Real Python
20 Setting up Sublime Text for Python Developers
Setting up Sublime Text for Python Developers
Real Python
21 Sublime Text + Python Guide Overview
Sublime Text + Python Guide Overview
Real Python
22 Python Code Review: Adding Pytest Tests to an Existing Python Web Scraper
Python Code Review: Adding Pytest Tests to an Existing Python Web Scraper
Real Python
23 Type-Checking Python Programs With Type Hints and mypy
Type-Checking Python Programs With Type Hints and mypy
Real Python
24 A Shorthand for Merging Dictionaries in Python 3.5+
A Shorthand for Merging Dictionaries in Python 3.5+
Real Python
25 Python Code Review Flask Web Security Tutorial + Virtualenvs, requirements.txt
Python Code Review Flask Web Security Tutorial + Virtualenvs, requirements.txt
Real Python
26 My Python Code Looks Ugly and Confusing – Help!
My Python Code Looks Ugly and Confusing – Help!
Real Python
27 Setting Up a Programmer Portfolio/Developer Blog – How To Get Started
Setting Up a Programmer Portfolio/Developer Blog – How To Get Started
Real Python
28 Do I Need a GitHub/GitLab/Bitbucket Profile as a Developer?
Do I Need a GitHub/GitLab/Bitbucket Profile as a Developer?
Real Python
29 Programmer Portfolio – Example and Walkthrough
Programmer Portfolio – Example and Walkthrough
Real Python
30 How to Get Your 1st Speaking Gig at a Tech Conference
How to Get Your 1st Speaking Gig at a Tech Conference
Real Python
31 How to Build Your Public Speaking Skills as a Developer
How to Build Your Public Speaking Skills as a Developer
Real Python
32 The Object-oriented Version of "Spaghetti Code" is "Lasagna Code" ?!
The Object-oriented Version of "Spaghetti Code" is "Lasagna Code" ?!
Real Python
33 Setting up Sublime Text for Python Developers – Lesson #1
Setting up Sublime Text for Python Developers – Lesson #1
Real Python
34 Cool New Features in Python 3.6
Cool New Features in Python 3.6
Real Python
35 "is" vs "==" in Python – What's the Difference? (And When to Use Each)
"is" vs "==" in Python – What's the Difference? (And When to Use Each)
Real Python
36 Emulating switch/case Statements in Python with Dictionaries
Emulating switch/case Statements in Python with Dictionaries
Real Python
37 Python Function Argument Unpacking Tutorial (* and ** Operators)
Python Function Argument Unpacking Tutorial (* and ** Operators)
Real Python
38 What Code Should I Put On My GitHub/GitLab/BitBucket Profile?
What Code Should I Put On My GitHub/GitLab/BitBucket Profile?
Real Python
39 A Crazy Python Dictionary Expression ?!
A Crazy Python Dictionary Expression ?!
Real Python
40 String Conversion in Python: When to Use __repr__ vs __str__
String Conversion in Python: When to Use __repr__ vs __str__
Real Python
41 Method Types in Python OOP: @classmethod, @staticmethod, and Instance Methods
Method Types in Python OOP: @classmethod, @staticmethod, and Instance Methods
Real Python
42 Optional Arguments in Python With *args and **kwargs
Optional Arguments in Python With *args and **kwargs
Real Python
43 Python Context Managers and the "with" Statement (__enter__ & __exit__)
Python Context Managers and the "with" Statement (__enter__ & __exit__)
Real Python
44 Installing Python Packages with pip and virtualenv / venv
Installing Python Packages with pip and virtualenv / venv
Real Python
45 "For Each" Loops in Python with enumerate() and range()
"For Each" Loops in Python with enumerate() and range()
Real Python
46 Python Code Review: LibreOffice Automation and the Python Standard Library
Python Code Review: LibreOffice Automation and the Python Standard Library
Real Python
47 Managing Python Dependencies With Pip and Virtual Environments – Lesson #1
Managing Python Dependencies With Pip and Virtual Environments – Lesson #1
Real Python
48 Python Tutorial: List Comprehensions Step-By-Step
Python Tutorial: List Comprehensions Step-By-Step
Real Python
49 Leveraging Python's Implicit "return None" Statements
Leveraging Python's Implicit "return None" Statements
Real Python
50 What's the meaning of underscores (_ & __) in Python variable names?
What's the meaning of underscores (_ & __) in Python variable names?
Real Python
51 Python Data Structures: Sets, Frozensets, and Multisets (Bags)
Python Data Structures: Sets, Frozensets, and Multisets (Bags)
Real Python
52 Writing automated tests for Python command-line apps and scripts
Writing automated tests for Python command-line apps and scripts
Real Python
53 How to find great Python packages on PyPI, the Python Package Repository
How to find great Python packages on PyPI, the Python Package Repository
Real Python
54 Immutable vs Mutable Objects in Python
Immutable vs Mutable Objects in Python
Real Python
55 PyPI vs Warehouse, the Next-Generation Python Package Repository
PyPI vs Warehouse, the Next-Generation Python Package Repository
Real Python
56 pep8.org — The Prettiest Way to View the PEP 8 Python Style Guide
pep8.org — The Prettiest Way to View the PEP 8 Python Style Guide
Real Python
57 My Experience at PyCon 2017 in Portland
My Experience at PyCon 2017 in Portland
Real Python
58 Pylint Tutorial – How to Write Clean Python
Pylint Tutorial – How to Write Clean Python
Real Python
59 "Reverse a List in Python" Tutorial: Three Methods & How-to Demos
"Reverse a List in Python" Tutorial: Three Methods & How-to Demos
Real Python
60 Python Refactoring: "while True" Infinite Loops & The "input" Function
Python Refactoring: "while True" Infinite Loops & The "input" Function
Real Python

The video covers the new features in Python 3.10, including improvements to error messages, structural pattern matching, and type hint improvements. It provides examples of how these features work and how they can be used in practice.

Key Takeaways
  1. Update to Python 3.10 to take advantage of the new features
  2. Use the improved error messages to diagnose and fix syntax errors
  3. Use structural pattern matching to simplify code and improve readability
  4. Take advantage of type hint improvements to make code more maintainable and self-documenting
💡 The improved error messages in Python 3.10 can help developers diagnose and fix syntax errors more quickly and easily, making it easier to write and maintain high-quality code.

Related Reads

📰
Five Signals From the Frontier of AI Research
Explore the latest AI research signals from Frontier Labs, advancing real-world AI applications
Medium · AI
📰
AI Giants Are Handing Out Tons of Free Computing Power to Grab
Learn how AI giants are offering free computing power to startups and how to leverage this opportunity for your business, understanding the strategic motivations behind it.
Dev.to AI
📰
The Great AI Chip Recalibration: Why Record Profits and Massive Investments Aren't Calming Markets
Learn why AI chip stocks are experiencing a selloff despite record profits and massive investments, and what this means for the future of AI technology
Dev.to AI
📰
The Future of Artificial Intelligence in 2026: How AI Is Transforming Every Industry
Discover how AI is transforming every industry in 2026 and what it means for professionals and businesses
Medium · Startup
Up next
Anthropic's Sonnet 5 is quiet AI shrinkflation #AInews #Claude #Anthropic #Sonnet5 #LLM #AItools
__beginnerscode__
Watch →