1
Current Location:
>
Python New Features
Python 3.9-3.11: From Dictionary Merging to Exception Groups, These New Features Make Coding More Efficient
2024-11-10 22:07:01   read:18

Hello, Python enthusiasts! Today, let's talk about the exciting new features in Python versions 3.9 to 3.11. These versions have brought many practical improvements, from syntax optimizations to performance enhancements, making our coding experience smoother. Let's see how these changes will affect our daily development work!

Dictionary Operations

Remember the cumbersome process of merging two dictionaries in the past? Python 3.9 brings us good news - the dictionary merge operator | and update operator |=. This small change can make our code more concise and elegant.

Let's look at an example:

dict1 = {'a': 1, 'b': 2}
dict2 = {'c': 3, 'd': 4}
merged = {**dict1, **dict2}


merged = dict1 | dict2


dict1 |= dict2

Doesn't it feel much cleaner? This syntactic sugar not only makes the code more readable but also improves efficiency. I personally find this improvement very practical, especially when dealing with configuration files or API responses.

Decorator Expressions

Python 3.9 also makes decorators more flexible. Now we can use any expression in decorators, opening new doors for metaprogramming.

For example:

@(lambda x: x)
def func(): 
    pass


@(logger if DEBUG else lambda f: f)
def some_function():
    pass

This flexibility allows us to dynamically choose decorators based on runtime conditions. Isn't that cool?

Type Hints

Starting from Python 3.9, we can finally use built-in collection types directly for type hinting, without needing to import from the typing module. This change makes type hinting more intuitive.

from typing import List, Dict

def process_items(items: List[int]) -> Dict[str, int]:
    pass


def process_items(items: list[int]) -> dict[str, int]:
    pass

Doesn't it look more natural? This change not only makes the code more readable but also reduces unnecessary imports. I think this is a big step towards a more concise and Pythonic direction.

Python 3.11 further enhances the type system, introducing variadic generics and the Self type. These new features allow us to express complex type relationships more precisely.

from typing import Generic, TypeVar

T = TypeVar('T')

class Stack(Generic[T]):
    def push(self, item: T) -> Self:
        ...

    def pop(self) -> T:
        ...

The Self type here makes type hinting for method chaining more accurate. How do you think these improvements will affect your code quality?

Performance Leap

When it comes to Python 3.11, we can't ignore its amazing performance boost. Official data shows that Python 3.11 is 10-60% faster than 3.10, with an average speed increase of 1.25 times. This is achieved through a series of low-level optimizations, including faster startup speed, more efficient memory management, and improved bytecode compilation.

What does this mean? It means our programs can run faster, especially for compute-intensive tasks. Imagine your data processing script suddenly becoming 25% faster - isn't that exciting?

Exception Handling Upgrade

Python 3.11 also brings us exception groups and the except* syntax, making handling multiple exceptions more elegant.

try:
    # Code that might raise multiple exceptions
except* (TypeError, ValueError) as exc_group:
    for exc in exc_group.exceptions:
        print(f"Caught {type(exc).__name__}: {exc}")

This new feature allows us to control the exception handling process more finely, especially when dealing with complex error scenarios. Can you think of scenarios where this feature would be particularly useful?

More Precise Debugging

Python 3.11 has also improved error tracing, now providing more precise error location information. This means we can locate and fix bugs faster.

def foo():
    x = 1
    y = 0
    return x / y  # This will raise a ZeroDivisionError

foo()

See that arrow pointing to the specific error location? This expression-level error localization makes the debugging process more efficient.

New Members in the Standard Library

Python 3.9 and 3.11 have also added new modules to the standard library. The zoneinfo module finally brings built-in time zone support to Python, while the tomllib module provides standard support for parsing TOML files.

The addition of these new modules makes us more adept at handling time-related operations and configuration files. Are you already considering how to apply these new tools in your projects?

Conclusion

From Python 3.9 to 3.11, we've seen progress in various aspects of the language: more concise syntax, a more powerful type system, significant performance improvements, more flexible error handling, and a better debugging experience. These improvements not only make our code more elegant and efficient but also lay a more solid foundation for Python's application in various fields.

So, which new feature do you like the most? How will they affect your programming practices? Feel free to share your thoughts in the comments!

Remember, keep your enthusiasm for learning, keep up with Python's development pace, and your programming journey will surely become broader. Let's embrace these exciting changes together and create better Python code!

>Related articles