Quantcast
Channel: Planet Python
Viewing all articles
Browse latest Browse all 22874

Real Python: Python 3.11: Cool New Features for You to Try

$
0
0

Python 3.11 will be published on October 24, 2022. This latest version of Python is faster and more user-friendly. After seventeen months of development, it’s now ready for prime-time use.

As in every version, Python 3.11 comes with lots of improvements and changes. You can see a list of all of them in the documentation. Here, you’ll explore the coolest and most impactful new features.

In this tutorial, you’ll learn about new features and improvements like:

  • Better error messages with more informative tracebacks
  • Faster code execution due to considerable effort in the Faster CPython project
  • Task and exception groups that simplify working with asynchronous code
  • Several new typing features that improve Python’s static typing support
  • Native TOML support for working with configuration files

If you want to try any of the examples in this tutorial, then you’ll need to use Python 3.11. The Python 3 Installation & Setup Guide and How Can You Install a Pre-Release Version of Python? walk you through several options for adding a new version of Python to your system.

In addition to learning more about the new features coming to the language, you’ll also get some advice about what to consider before upgrading to the new version. Click the link below to download code examples demonstrating the new capabilities of Python 3.11:

Free Download:Click here to download free sample code that demonstrates some of the new features of Python 3.11.

More Informative Error Tracebacks

Python is often recognized as a good beginner programming language, with its readable syntax and powerful data structures. A challenge for all, but especially those new to Python, is how to interpret the traceback that’s displayed when Python encounters an error.

In Python 3.10, Python’s error messages were greatly improved. Similarly, one of Python 3.11’s most anticipated features will also boost your developer experience. Decorative annotations are added to the tracebacks and can help you more quickly interpret an error message.

To see a quick example of the enhanced traceback, add the following code to a file named inverse.py:

# inverse.pydefinverse(number):return1/numberprint(inverse(0))

You can use inverse() to calculate the multiplicative inverse of a number. There’s no multiplicative inverse of 0, so your code raises an error when you run it:

$ python inverse.py
Traceback (most recent call last):  File "/home/realpython/inverse.py", line 6, in <module>    print(inverse(0))          ^^^^^^^^^^  File "/home/realpython/inverse.py", line 4, in inverse    return 1 / number           ~~^~~~~~~~ZeroDivisionError: division by zero

Note the ^ and ~ symbols embedded within the traceback. They’re used to guide your attention to the code that’s causing the error. As usual with tracebacks, you should start at the bottom and work your way up. In this example, a ZeroDivisionError is caused by the division 1 / number. The actual culprit is calling inverse(0), as 0 has no inverse.

Getting this extra help in spotting mistakes is useful. However, the annotated tracebacks are even more powerful if your code is more complex. They may be able to convey information that you couldn’t get from the traceback by itself before.

To appreciate the power of the improved tracebacks, you’ll build a small parser of information about a few programmers. Assume you have a file named programmers.json with the following content:

[{"name":{"first":"Uncle Barry"}},{"name":{"first":"Ada","last":"Lovelace"},"birth":{"year":1815},"death":{"month":11,"day":27}},{"name":{"first":"Grace","last":"Hopper"},"birth":{"year":1906,"month":12,"day":9},"death":{"year":1992,"month":1,"day":1}},{"name":{"first":"Ole-Johan","last":"Dahl"},"birth":{"year":1931,"month":10,"day":12},"death":{"year":2002,"month":6,"day":29}},{"name":{"first":"Guido","last":"Van Rossum"},"birth":{"year":1956,"month":1,"day":31},"death":null}]

Note that the information about the programmers is quite inconsistent. While the information about Grace Hopper and Ole-Johan Dahl is complete, you’re missing Ada Lovelace’s day and month of birth as well as her year of death. Naturally, you only have birth information about Guido van Rossum. To top it off, you’ve only recorded Uncle Barry’s first name.

You’ll create a class that can wrap this information. Start by reading the information from the JSON file:

# programmers.pyimportjsonimportpathlibprogrammers=json.loads(pathlib.Path("programmers.json").read_text(encoding="utf-8"))

You use pathlib to read the JSON file and json to parse the information into a Python list of dictionaries.

Next, you’ll use a data class to encapsulate the information about each programmer:

# programmers.pyfromdataclassesimportdataclass# ...@dataclassclassPerson:name:strlife_span:tuple[int,int]@classmethoddeffrom_dict(cls,info):returncls(name=f"{info['name']['first']}{info['name']['last']}",life_span=(info["birth"]["year"],info["death"]["year"]),)

Each Person will have a name and a life_span attribute. Additionally, you add a convenience constructor that can initialize Person based on the information and structure in your JSON file.

Read the full article at https://realpython.com/python311-new-features/ »


[ Improve Your Python With 🐍 Python Tricks 💌 – Get a short & sweet Python Trick delivered to your inbox every couple of days. >> Click here to learn more and see examples ]


Viewing all articles
Browse latest Browse all 22874

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>