Python 3.11 won't be officially released until sometime in October this year, but I'm already getting excited. The changelog of new features is promising, with the most recent alpha release implementing PEP 654 and PEP 673.

PEP 654: Exception groups

Typically, when functions raise an exception, the first appropriate except block that is encountered is the code block that gets executed. However, PEP 654 introduces the use of except* to trigger multiple blocks! Even cooler, the new ExceptionGroup class allows multiple exceptions to be raised simultaneously!

Control flow via exceptions just got a whole lot more interesting.

PEP 673: The Self Type

Annotations became standard with Python 3, but not all edge cases were resolved before the initial Python 3 release. For example, type checkers currently throw errors if subclasses call a mix of inherited and new methods that return the self. This is demonstrated in the snippet below:

class Parent:
    def parent_method(self) -> Parent:
        # misc code here
        return self


class Child(Parent):
    def child_method(self) -> Child:
        # misc code here
        return self


Child().parent_method().child_method()  # error!

Here, a Child instance calls an inherited parent method, which the type checker expects to return a Parent (but a Child is actually returned). Then, when this returned Child instance attempts to call a child method, the checker falsely believes that the child method doesn't exist because Parent does not define one. Oops!

Previous workarounds involved the creation of a new type – TParent = TypeVar("TParent", bound="Parent") – to annotate any location where self was returned. Unfortunately, that solution was both verbose and unintuitive.

PEP 673 simplifies all this with the introduction of Self:

class Parent:
    def parent_method(self) -> Self:
        # misc code here
        return self


class Child(Parent):
    def child_method(self) -> Self:
        # misc code here
        return self


Child().parent_method().child_method()  # no error!

Can't wait to see what else comes out with Python 3.11. Get hyped!