6 great new Python features you don’t want to miss

Python has added a number of powerful new features over the last few versions. Don’t miss out on what they have to offer

6 great new Python features you don’t want to miss
Thinkstock

Any programming language that fails to add new functionality over time has stopped being a technology with a future and become a technology of the past. Python 3 continues to move forward with the addition of significant new features, though it’s difficult to keep up with them when you’re preoccupied with the nitty-gritty of your development work.

Here are six of the newest features in the last few versions of Python 3 that not only deserve your attention, but probably a place in your software projects.

F-strings

The Zen of Python states that there should be one obvious way to do things. String formatting in Python deviates greatly from this rule, because there is a slew of ways to do it. But the “f-string” format, unveiled in Python 3.6, is both the fastest and among the most convenient. Nevertheless, many Python programmers, who learned string formatting on earlier versions of Python, don’t take advantage of them. 

To use an f-string, just place the variable you want to include in the string in curly braces, and decorate the string with an f prefix:

filename = "file.jpg"
f_name_str = f"Your file is {filename}"

The result:

Your file is file.jpg

Most any valid Python expression can be placed in the curly brackets. You can decorate expressions therein with Python’s internal expression formatting language. And you can use triple quotes for multi-line f-strings.

These advantages make f-strings a convenient first choice for string formatting, since they cover the vast majority of use cases elegantly. About the only time you would not want to use f-strings is when you need to pass arbitrary formatting parameters via the .format command.

Another benefit: f-strings render far faster than the format command or the % string-rendering operator. In most cases f-strings are nearly twice as fast as format, slightly faster than %, and an order of magnitude faster than the Template formatting object.

Python 3.8 added a new plus to f-strings: internal debugging. Add an equal sign to the end of an f-string expression and you’ll see additional data when the string is rendered:

filename = "file.jpg"
f_name_str = f"Your file is {filename=}"

The result: 

Your file is filename='file.jpg'

Async

Asynchronous programming, or async for short, lets you queue up multiple tasks that need to wait on outside events, like network requests or disk I/O, and switch efficiently between them. Async is a way to give some jobs the efficiency of multithreading, but with far less operational overhead. Async operations take up much less memory and switch far faster than threads.

Python introduced the asyncio library in version 3.4 and the async/await keywords in version 3.5, and the language has been steadily adding and improving how async works ever since.

If you’re not already using async in your code, it’s worth exploring. After all, any program that spends time waiting for disk or network operations would benefit from asynchronous code. The one caveat: Async can be tricky to learn at first, because it requires thinking differently about your code.

Data classes

Python 3.7 introduced data classes, which provide a way to write classes that store many data elements without using lots of boilerplate constructor or initializer code. For example: 

from dataclasses import dataclass

@dataclass
class Student:
    name: str
    student_id: int
    gpa: float

This code automatically generates the __init__ function to assign name, student_id, and gpa to their respective variables in the class instance. It also generates comparison operators for the class. The resulting class is a class just like any other; the only difference is how it is defined.

If you create classes that are mainly containers for many named data elements with some methods attached to them, data classes can spare you the hassle of writing the nitty-gritty initialization details for each class.

Assignment expressions (the “walrus operator”)

Here is a common construction:

my_val = func_result()
if my_val == 1:
    do_something_else()

The assignment expression syntax, or “walrus operator” as it is also known, lets you condense the assignment of a variable in the local scope to a single line.

if (my_val:=func_result()) == 1:
    do_something_else()
# my_val continues to be a valid value 

Because this syntax is valid only in Python 3.8 and higher, you should use it only in new projects that are guaranteed to use these later versions of Python. But it is a handy way to reduce a bit of boilerplate that pops up often in Python code.

The breakpoint() function

Most Python developers use features in their Python IDE for debugging, such as manually inserting breakpoints in code. The breakpoint() function, new as of Python 3.7, lets you insert a breakpoint into code manually — for instance, in a code path that is triggered only by certain conditions. This makes it easier to create interactive debugging behaviors. With breakpoint(), you can even trigger a custom debugging function rather than the default pdb, if you have something else you’d rather use.

Type hinting advancements

For the longest time, Python had no explicit way to specify types for variables or function parameters. Now, type hinting and the typing module are supported directly by the Python interpreter.

Type hints in Python aren’t enforced at runtime. But when combined with linting tools, type hints shake out a great many bugs that might otherwise blow up only in production due to Python’s dynamism. Solo and team developers alike can benefit from this. What’s more, type hints can be added gradually to a codebase as needed. For instance, you might make use of type hints first around interfaces used between teams, then around internal interfaces.

In the future, we may see more aggressive use of third-party projects like mypyc to achieve runtime speed-ups for Python through type hints. Some performance gains are possible right now, if only in a limited way. But there are still plenty of other immediate benefits for using typing that are about programmer productivity (Python’s mainstay) rather than raw performance.

Copyright © 2020 IDG Communications, Inc.

How to choose a low-code development platform