Some New Features in Python 3.11

Pretty Printed
26 Oct 202214:15

Summary

TLDRThis video discusses new features in Python 3.11, including enhanced tracebacks for better error debugging, improvements in handling asynchronous tasks with task groups, and the introduction of exception groups for managing multiple exceptions simultaneously. The presenter demonstrates these updates with code examples, highlighting how Python 3.11 makes debugging and handling asynchronous processes more efficient. Additional features like performance improvements and updates to Python's typing module are briefly mentioned. Viewers are encouraged to explore these updates and share their thoughts on the usefulness of these new additions.

Takeaways

  • 😀 Python 3.11 introduces improved tracebacks, offering more precise error location details compared to Python 3.10.
  • 🔍 With Python 3.11, you can easily spot where a ZeroDivisionError occurs in a complex expression, saving debugging time.
  • 🚀 The new Task Groups in async programming allow asynchronous tasks to be grouped and executed immediately, unlike the old gather method which waits for task completion.
  • 🛠️ Task Groups don't require gathering results explicitly, making them ideal for cases where the result doesn't need to be returned.
  • 📊 If results from tasks are needed, using asyncio.gather is more straightforward, but Task Groups offer a simpler syntax for non-result-driven tasks.
  • 🔗 Python 3.11 introduces exception groups, allowing multiple exceptions to be raised and handled together, which is especially useful for asynchronous programming.
  • ⚡ With the new `accept*` syntax, multiple exceptions within a group can be handled, unlike the traditional method that stops after the first match.
  • 📝 Exception notes are a new feature that lets you attach additional information to exceptions, providing more context during debugging.
  • 💡 The script demonstrates how to use exception groups and notes by showing how to manage multiple failed URL requests with informative error handling.
  • ⏩ Python 3.11 includes performance improvements, making it faster globally without requiring changes to existing code, along with enhanced type hints.

Q & A

  • What is the main focus of the video?

    -The video covers new features introduced in Python 3.11, focusing on improved tracebacks, task groups, exception groups, and performance improvements.

  • How has the traceback feature improved in Python 3.11?

    -In Python 3.11, the traceback provides more precise information about where an error occurs, highlighting the exact part of the expression causing the issue, such as showing which variable is causing a zero division error.

  • What are task groups in Python 3.11, and how do they differ from using 'asyncio.gather'?

    -Task groups are introduced in Python 3.11 as a more efficient way to manage asynchronous tasks. Unlike 'asyncio.gather', task groups start tasks immediately without needing to create a list of tasks, and the 'async with' block does not return until all tasks are completed.

  • Can you get the results of tasks in a task group? How?

    -Yes, you can get the results of tasks in a task group by appending each task to a results list and later accessing the results using a list comprehension. This approach gives you similar functionality to 'asyncio.gather'.

  • What are exception groups, and when would you use them?

    -Exception groups allow multiple exceptions to be raised and handled at the same time, which is particularly useful in asynchronous programming where several tasks can fail for different reasons. They enable you to manage multiple exceptions in a single block.

  • How do 'accept *' blocks work in Python 3.11?

    -'Accept *' blocks in Python 3.11 allow multiple exception handling blocks to run for different types of errors within the same try-except statement. Each applicable exception is handled separately without exiting after the first match, unlike traditional except blocks.

  • What is the purpose of the 'add_note' method in Python 3.11?

    -The 'add_note' method allows developers to attach additional information to exceptions without needing to create custom exceptions. For example, you can add extra details like URLs or context-specific notes to the exception for debugging purposes.

  • What other features are included in Python 3.11 besides task groups and exception groups?

    -In addition to task groups and exception groups, Python 3.11 brings speed improvements, enhancements to the typing module, and other performance optimizations that benefit developers without requiring code changes.

  • Are there performance improvements in Python 3.11, and do they require code changes?

    -Yes, Python 3.11 includes speed improvements, but these enhancements do not require code changes. Developers can continue writing code as usual and benefit from the performance boost automatically.

  • Why might a developer choose to use task groups instead of 'asyncio.gather'?

    -A developer might choose task groups over 'asyncio.gather' because task groups start tasks immediately, simplifying code by removing the need for creating and appending tasks to a list. They are particularly useful when task results are not needed.

Outlines

00:00

🐍 Python 3.11: Enhanced Tracebacks

In this paragraph, the video introduces a new feature in Python 3.11: improved tracebacks. The speaker compares the error reporting between Python 3.10 and 3.11 by running a piece of code that divides numbers, triggering a zero division error. In Python 3.11, the traceback is more precise, highlighting the exact part of the expression causing the error. This new feature improves debugging efficiency by pinpointing where the issue occurs, saving developers time when identifying the cause of an error.

05:01

⚡ Running Asynchronous Tasks with Task Groups

This section discusses two methods for running asynchronous tasks in Python: the traditional `asyncio.gather` approach and the new `asyncio.TaskGroup` introduced in Python 3.11. The speaker walks through an example where tasks are executed concurrently. The `TaskGroup` method starts tasks immediately when added, eliminating the need for task lists or explicit `gather` calls. While `gather` makes it easier to return results, `TaskGroup` provides a cleaner way to run multiple tasks, especially when the results are not needed. This new method simplifies managing async operations in Python.

10:02

💥 Managing Multiple Exceptions with Exception Groups

In this part of the video, the speaker introduces Python 3.11's support for handling multiple exceptions with 'Exception Groups.' This feature is particularly useful in asynchronous programming, where many operations can fail for different reasons. The example demonstrates how to catch and handle multiple exceptions simultaneously using `ExceptionGroup`, as well as how the new `except*` syntax allows handling several exceptions in one try-except block. The speaker also introduces 'Exception Notes,' which lets developers add additional context to exceptions for better error diagnostics.

⚙️ Python 3.11 Performance Improvements and Other Features

The final part discusses general improvements in Python 3.11, including performance boosts that speed up code execution without requiring any special modifications by developers. While the speaker acknowledges that they couldn't demonstrate the performance gains due to the nature of their code, they mention that Python 3.11 will deliver noticeable performance increases. Additionally, the speaker briefly touches on improvements in the typing module, which makes using type hints easier and more powerful for developers. The video ends by encouraging viewers to share their opinions on Python 3.11's new features.

Mindmap

Keywords

💡Python 3.11

Python 3.11 is the latest version of the Python programming language at the time of the video's recording. This version introduces several new features and improvements, including better error tracebacks, enhanced support for asynchronous programming, and overall performance boosts. The speaker demonstrates these features to showcase the version's efficiency and debugging advantages.

💡Traceback

Traceback refers to the error output in Python that shows where an error occurred in the code, which helps in debugging. Python 3.11 offers more detailed tracebacks, indicating the exact location of errors, such as a division by zero, making it easier for programmers to identify and resolve issues without scanning all potential problem areas manually.

💡ZeroDivisionError

A ZeroDivisionError occurs in Python when a division operation has a divisor of zero, which is undefined in mathematics. In the video, this error is used to show how Python 3.11 provides more detailed tracebacks, pinpointing the specific location in an expression where the division by zero occurs, thus making debugging more efficient.

💡Asynchronous Programming

Asynchronous programming, or async, allows tasks to be run concurrently without waiting for each to finish before starting the next. The speaker discusses enhancements in Python 3.11, including the new 'TaskGroup' feature, which simplifies running and managing asynchronous tasks compared to the previous 'gather' approach. This is beneficial in scenarios where tasks need to be run independently, like multiple API requests or parallel computations.

💡TaskGroup

TaskGroup is a new class in Python 3.11 that enables the grouping of asynchronous tasks in a simpler and more organized way. Unlike traditional 'gather' methods, TaskGroup automatically initiates tasks and waits for all to complete without the need for a separate task list. This feature improves code readability and reduces setup requirements for asynchronous operations.

💡asyncio.gather

'asyncio.gather' is a method used in Python for managing multiple asynchronous tasks, running them concurrently, and waiting for all of them to complete. In the video, 'asyncio.gather' is contrasted with the new TaskGroup approach, with the former requiring a task list and the latter handling tasks more dynamically, thereby simplifying async management in Python 3.11.

💡Exception Groups

Exception groups allow handling multiple exceptions simultaneously within Python, which is particularly useful for asynchronous programming where various tasks might fail for different reasons. In Python 3.11, this feature enables programmers to group related exceptions together, making it easier to handle complex error scenarios by processing them all at once.

💡Exception Notes

Exception notes in Python 3.11 allow developers to add custom notes or messages to exceptions. This can provide extra context about the error, such as the URL that caused a failure. Exception notes help developers understand the specifics of an error without having to create custom exception classes, simplifying error handling.

💡Performance Improvements

Python 3.11 includes general performance improvements that make it faster than previous versions. These optimizations benefit Python programs without requiring any changes to the code, and though the speaker doesn't give specific metrics, they note that all Python scripts will see an automatic boost in speed, particularly in computation-heavy tasks.

💡Typing Module

The typing module in Python provides support for type hints, enabling developers to specify data types in code, which helps with readability and error detection. Python 3.11 introduces enhancements in the typing module, making it easier to define and work with types, which is especially beneficial for large codebases and team projects that require clear documentation and structure.

Highlights

Introduction to Python 3.11's new features, available now and recently released.

Improved tracebacks in Python 3.11, offering more precise error locations for better debugging.

Example of improved traceback: detecting exact zero division location in a complex expression.

Explanation of new async features: creating groups of asynchronous tasks more efficiently.

Introduction to the 'task group' feature in async IO, which simplifies task grouping and management.

Comparison between async IO gather and the new task group; task group eliminates the need to store tasks in a list.

Illustration of running async tasks using 'task group' for automatic task initiation and grouping.

Drawback of task groups: cannot retrieve results directly, unlike with async IO gather.

Solution for retrieving results when using task groups, by appending tasks to a results list.

Introduction to exception groups: managing multiple exceptions simultaneously, useful for async programming.

Demonstration of exception groups, using a URL loading function where multiple requests may fail.

Using 'accept star' to handle multiple exceptions in one block, which processes all applicable exceptions.

New feature: adding exception notes to exceptions for additional context, e.g., URL causing an error.

Overview of Python 3.11's general performance improvements, benefiting all Python code without additional setup.

Mention of new typing module enhancements in Python 3.11, which facilitate using type hints.

Transcripts

play00:00

hey everyone in today's video I want to

play00:02

go over some of the new features of

play00:03

python 3.11 that I found interesting

play00:05

it's available now it was released a

play00:07

couple of days ago at the time of

play00:09

recording this video so you'll be able

play00:10

to do everything that I'm showing in

play00:12

this video today

play00:14

the first feature has to do with

play00:16

improved tracebacks so here I have some

play00:20

code it basically just assigns the

play00:22

letters a to J to the numbers one

play00:24

through ten and then it divides all of

play00:26

these here just like you see and it

play00:28

prints out the result so let me go ahead

play00:30

and run this just so you can see what it

play00:32

looks like and it gives me a really

play00:34

small number now if I were to change

play00:36

this to have a zero somewhere let's say

play00:40

five and I change that to zero and I run

play00:43

this using python 3.10

play00:47

we see I get this error message right so

play00:49

it's telling me that there's a zero

play00:51

division error somewhere in this

play00:53

expression I'm dividing by zero but it's

play00:56

not clear where now with python 3.11 if

play01:00

I run this so python 3.11 is my default

play01:03

now so I still see the zero division

play01:05

error but it's giving me more precise

play01:07

information on where the error is

play01:09

occurring and we see it's happening

play01:11

after the D

play01:13

and before the E so the division there

play01:15

so I'm trying to divide by zero there so

play01:17

it's saying that e is zero so one two

play01:21

three four five and one two three four

play01:23

five yes so e is zero and that's the

play01:25

part that's failing if I change this

play01:27

back to five

play01:29

and I change let's say the 9 to 0 which

play01:31

means the I in this case will be zero

play01:34

and run it again we see now this little

play01:37

arrow is pointing to the division sign

play01:40

right before the I which means the I

play01:42

itself is zero this is going to save you

play01:45

time when you're debugging because it's

play01:47

going to show you exactly where

play01:49

something is occurring so you won't have

play01:51

to kind of look at everything in the

play01:52

area you'll have a better idea of where

play01:54

to start your investigation when you're

play01:57

debugging so I think this is a great

play01:58

addition to python 3.11 the next thing I

play02:02

want to talk about are different ways of

play02:05

creating groups of asynchronous tasks

play02:08

so right now I have this example of the

play02:12

old way of doing it or you know the the

play02:14

standard way of doing it here I'm

play02:18

here I have this async function which

play02:20

will basically print start and end and

play02:23

return finish along with some number

play02:26

that I pass in and it's just going to

play02:28

sleep for however many seconds I pass in

play02:30

so I want to run this multiple times in

play02:34

a group so the typical way you do this

play02:36

is with gather so you create a list of

play02:39

tasks so I have this task list and I

play02:42

just create a bunch of tasks from one to

play02:45

five well really one to four and they're

play02:47

calling this async function that I've

play02:49

defined up there and then I'm adding

play02:51

them to this task list so I have the

play02:52

list of tasks and then I await

play02:55

um this list of tasks by using gather so

play02:58

then gather will run all these tasks at

play03:00

the same time and it will wait for them

play03:02

all to finish and when it finishes then

play03:04

it Returns the results from the entire

play03:07

group of them so this is fine I've used

play03:10

this before of course you can change

play03:12

this user list comprehension but the

play03:13

idea is the same you just basically

play03:15

create a list of tasks and then you

play03:17

await those tasks using gather so now

play03:19

there's a new way of doing it and I'm

play03:22

going to copy this one and I'm going to

play03:24

modify it to support the new approach so

play03:27

I'm going to call this run with groups

play03:29

so let's change this to groups I can get

play03:32

rid of the tasks here because I no

play03:34

longer need a tasks list and what I want

play03:37

to do instead is I want to use async

play03:39

with

play03:40

and I want to call the class called

play03:45

task group inside of async IO

play03:49

so async with async IO and then I can

play03:52

assign this to a variable so let's call

play03:54

this TG for task group and then with

play03:57

this task group whenever I add a task to

play03:59

this group it will immediately start

play04:01

running and this async with block won't

play04:04

return until all the tasks in the group

play04:06

have finished running so let me go ahead

play04:08

and indent this let me show you how it

play04:10

works so the loop here looping over one

play04:13

to four

play04:15

still appears but instead of creating a

play04:17

task like this what I can do is I can

play04:20

say TG dot create task and then the rest

play04:23

of the API is similar so instead of

play04:26

using

play04:27

uh the standard great task from async IO

play04:30

I'm using the one from task group and

play04:33

then I'm creating a task and then I

play04:35

don't need to append it I don't need to

play04:37

append it to a list here if I'm not

play04:39

interested in the results and then I

play04:41

also don't need to run async gather

play04:44

anymore because like I said these will

play04:46

start executing right away so let me go

play04:48

ahead and run this

play04:51

so task groups so right now this is

play04:53

going to use the gather and we see it

play04:55

starts them all at the same time and

play04:57

then they slowly appear for the other

play04:59

ones because the first one takes one

play05:00

second and the last one takes four

play05:02

seconds right so now if I do this with

play05:04

group

play05:07

so whoops just like that and I run it we

play05:11

see it works just the same it starts

play05:14

them at the same time and it returns and

play05:16

I see I have this print results here

play05:18

because I didn't remove it but let me go

play05:20

ahead and just run that again

play05:22

we see start one two three four and then

play05:24

in one two three four and then it's done

play05:27

but I don't have the results for this so

play05:29

this is a little bit of a limitation

play05:32

um it depends on if you want the results

play05:34

from your tasks being run oftentimes you

play05:37

don't you just want to make sure that

play05:38

they run and don't fail but if you do

play05:40

want the results here's what you can do

play05:42

so you can do results equals an empty

play05:44

list

play05:45

and then you can append each task to the

play05:49

results so results a pin task

play05:55

and then outside I can print the results

play05:58

so print and then I'll use a list

play06:01

comprehension for this so task.results

play06:04

or actually results singular uh four

play06:07

tasks in results

play06:10

and you can call this tasks as well and

play06:12

now if I run this

play06:15

I see it still works the same but at the

play06:17

end I get the results from this so if

play06:20

you want the results I think async

play06:23

io.gather

play06:25

is a little bit more clear on how it

play06:27

works but if you don't care about the

play06:29

results then task group is definitely a

play06:31

lot better the last thing I want to talk

play06:33

about are exception groups and exception

play06:35

notes so before I get into that let me

play06:37

just show you this function that I have

play06:38

here I have this function called load

play06:40

URLs and I have a list of four URLs out

play06:43

of the four only one is valid what I'm

play06:46

going to do is I'm going to Loop over

play06:47

these four URLs and then I'm going to

play06:50

try to send a get request to them but

play06:52

because only one is valid only one

play06:54

should work but because I have an

play06:55

exception here it's going to fail on the

play06:58

first one because the first URL is

play07:00

invalid so let me just go ahead and run

play07:01

this exception groups and we see I

play07:04

immediately get an error so

play07:07

what I can do is I can use a new feature

play07:10

called exception groups and exception

play07:12

groups allow you to pass multiple

play07:14

exceptions at the same time so this is

play07:16

useful in cases in like async

play07:19

programming where you can have many

play07:21

things running and many things can fail

play07:23

for different reasons you can group all

play07:25

those exceptions together and deal with

play07:27

them as a group so this example that I'm

play07:30

showing isn't very realistic but I think

play07:32

it's clear to show you how exception

play07:34

groups work and the way that I'm going

play07:35

to do this is first I'm going to create

play07:37

a list that will hold a bunch of

play07:39

exceptions so exceptions equals an empty

play07:42

list and what I'm going to do here is

play07:45

inside of the exception block here

play07:46

instead of raising I'm going to append

play07:48

the exceptions to this exceptions list

play07:52

so exceptions dot append e and now when

play07:56

I run this

play07:57

we see it runs but uh all the exceptions

play08:01

were suppressed because I appended them

play08:03

to this list so now that I have a list

play08:05

of exceptions the way I can raise the

play08:07

entire group is by using exceptional

play08:09

groups so to do that

play08:12

outside of the loop here what I want to

play08:15

do is I want to raise exception group

play08:18

just like that you can give it a name so

play08:21

I can say request errors is the name

play08:24

and then you have to give it a list of

play08:26

exceptions

play08:29

so just save that and I'll run it again

play08:32

and now the results

play08:35

have multiple exceptions and if I go to

play08:38

the top we see exception group Trace

play08:40

back

play08:41

and then it just gives you information

play08:43

about the entire group so raise

play08:45

exception group request errors and then

play08:48

we see three sub exceptions because

play08:50

three out of the four

play08:52

URLs are in ballot so now how do you

play08:55

handle this in the exception blocks the

play08:58

way you do this is first let me put a

play09:00

try here is instead of using accept

play09:03

you're going to use accept star

play09:05

and the way that accepts star is

play09:07

different from accept is multiple except

play09:10

Stars can run in one try except block

play09:13

group so typically when you have try

play09:16

except when it hits the first except

play09:18

that applies only that one will run and

play09:21

the whole block exits after that but now

play09:23

with accept star multiple except Stars

play09:26

can run

play09:27

so let me go ahead and bring in the

play09:29

exceptions that

play09:32

could happen here so we have

play09:34

requests.exceptions dots uh invalids

play09:37

schema is one

play09:40

and what it does is it catches the

play09:42

entire group so it's going to create

play09:44

like a subgroup for you and it's going

play09:46

to group all of the invalid schemas into

play09:49

a sub exception group so that's why I'm

play09:50

calling the EG for exception group

play09:53

and I just want to print uh let's say

play09:56

prints uh invalid schema

play10:00

and then I'll do the same thing for the

play10:02

other two so

play10:03

um one is going to be missing schema

play10:08

and I just put missing schema here and

play10:10

then the last one is going to be

play10:13

connection error

play10:15

so connection

play10:16

error

play10:18

and then we can say

play10:20

connection error here

play10:22

so now when I run this let's see what

play10:24

happens

play10:27

we see invalid schema missing schema and

play10:30

connection error so those print

play10:32

statements all ran even though it

play10:35

matched multiple of them if I only had

play10:37

accept without the star then it would

play10:40

have stopped on the first one and then

play10:41

the other two wouldn't appear you

play10:43

wouldn't see them

play10:44

so now let me just show you the last

play10:46

thing that I wanted to talk about which

play10:48

are exception notes which are pretty

play10:49

simple so inside of exception you have

play10:52

the ability to add a note to each

play10:54

exception that you're dealing with so

play10:56

here e now has this method called at

play10:59

node so any exception and what you can

play11:02

do is you can add extra information onto

play11:04

the exception so typically what you

play11:06

would do is you would like create your

play11:07

own exceptions that support additional

play11:09

information but now you don't have to do

play11:11

that you can just use e dot add note and

play11:14

you can add any extra information you

play11:15

want so what I'll do is I'll add the URL

play11:17

here

play11:18

for the notes

play11:20

and inside of the print statement here

play11:23

what I'll do

play11:24

is I'll print out the note information

play11:27

and I'm going to use a list

play11:29

comprehension here because this is an

play11:31

exception group and I can have multiple

play11:32

exceptions in this example I only have

play11:34

one per group but I could have multiple

play11:37

exceptions per group so I'm going to

play11:38

Loop over them so four

play11:41

e n e g dot exceptions so each exception

play11:45

in the exception group and then here I

play11:48

want to take e and then Dunder notes and

play11:51

I just want the first note right so it

play11:54

puts all the notes here

play11:56

um in this Dunder notes and because I

play11:58

only have one node per exception I'm

play12:00

just getting the first one here and I

play12:02

can just copy this and paste it to the

play12:04

other ones

play12:07

and I can run it

play12:10

and now we see for the invalid schema we

play12:12

have HTTP SS which is invalid schema a

play12:17

missing schema so there's just nothing

play12:18

there for pretty printer.com and then

play12:20

connection error when I do pretty

play12:22

printed.coms with an s on the end it

play12:24

can't connect there and then for the

play12:26

other one that is correct nothing

play12:28

happens because there's no exception

play12:30

there so like I said this isn't really a

play12:32

realistic example but I do think it

play12:34

shows the case where you can have

play12:35

multiple exceptions in one thing and

play12:38

then you can handle all of those

play12:39

exceptions at the same time so there are

play12:41

some other features in Python 3.11 that

play12:43

I didn't cover like a big one has to do

play12:46

with speed improvements I couldn't think

play12:47

of a good way to demonstrate that

play12:49

because most of the code that I write is

play12:51

limited by input and output not

play12:54

necessarily like the speed of the code

play12:55

execution so the speed changes probably

play12:58

won't affect me but it is something

play13:00

that's going to

play13:02

um globally affect all Python scripts so

play13:05

you don't have to do anything different

play13:06

to benefit from the performance

play13:08

increases you just write your code as

play13:10

normal use Python 3.11 and there's going

play13:13

to be some speed increase you don't have

play13:15

to switch to something like Pi Pi to get

play13:17

an increase like you just use it like

play13:19

you are right now and you're going to

play13:20

benefit from increased performance and

play13:23

there are also a bunch of other things

play13:24

added to the typing module to make a

play13:27

writing typing it's a lot easier there

play13:30

are a few of them I don't want to cover

play13:31

them in this video but if you're using

play13:33

type hints in Python then you'll

play13:35

probably benefit from the new type hints

play13:37

and features around type pins that were

play13:39

added in Python 3.11 so check out the

play13:42

link in the description below it's going

play13:44

to talk about like the difference uh

play13:46

changes to Python 3.11 and in the

play13:48

comments below let me know which

play13:49

features you like which features you

play13:51

don't like

play13:52

um do you think these are good additions

play13:54

to python do you think they're not

play13:56

really necessary let me know in the

play13:58

comments so that's it for this video uh

play14:00

feel free to give me a like if you like

play14:02

this video and if you haven't subscribed

play14:03

to my channel already please subscribe

play14:04

so thank you for watching and I will

play14:06

talk to you next time

Rate This

5.0 / 5 (0 votes)

Связанные теги
Python 3.11new featurestraceback improvementsasync tasksexception handlingperformance boostdebuggingprogramming tipstype hintssoftware development
Вам нужно краткое изложение на английском?