What's New at Python 3.10 And Why You Should Know That ?

Hi, have you already learned Python 3.10? And what if you meet a project written on this version? How fast can you figure out this code? Most people know that Python 3.10 has been released, but some beginner developers do not even pay attention to the features of the new version, because they are now working on 3.8, for example, and 3.10 is unnecessary for them. Soon most of the code will be written on version 3.10 and without knowing the specifics, you simply will not be able to read someone else's code correctly. Let's get acquainted with some innovations.

Improvements in type checking

If you use type checking, you will be happy to hear that Python 3.10 includes many improvements in type checking, among them the type union operator, whose syntax is now cleaner.

# Function that accepts either `int` or `float`
# Old:
def func(value: Union[int, float]) -> Union[int, float]:
    return value

# New:
def func(value: int | float) -> int | float:
    return value

Population Count (popcount)

Starting with Python 3.10, to count the number of bits in the binary representation of an integer, you can call int.bit_count().

value = 42
print(bin(value))
# '0b101010'
print(value.bit_count())
# 3

Performance improvements

As with all recent Python releases, performance improvements will come with Python 3.10. The first is an optimization of the constructors str(), bytes(), and bytearray(), which should become about 30% faster (fragment adapted from the example in the Python bug tracker):

~ $ ./python3.10 -m pyperf timeit -q --compare-to=python "str()"
Mean +- std dev: [python] 81.9 ns +- 4.5 ns -> [python3.10] 60.0 ns +- 1.9 ns: 1.36x faster (-27%)
~ $ ./python3.10 -m pyperf timeit -q --compare-to=python "bytes()"
Mean +- std dev: [python] 85.1 ns +- 2.2 ns -> [python3.10] 60.2 ns +- 2.3 ns: 1.41x faster (-29%)
~ $ ./python3.10 -m pyperf timeit -q --compare-to=python "bytearray()"
Mean +- std dev: [python] 93.5 ns +- 2.1 ns -> [python3.10] 73.1 ns +- 1.8 ns: 1.28x faster (-22%)

Better error messages

SyntaxErrors

Yes, they added more accurate information in the syntax error message

SyntaxError: '{' was never closed
SyntaxError: invalid syntax. Perhaps you forgot a comma?
SyntaxError: did you forget parentheses around the comprehension target?
SyntaxError: ':' expected after dictionary key
SyntaxError: expected 'except' or 'finally' block
SyntaxError: cannot assign to attribute here. Maybe you meant '==' instead of '='?
SyntaxError: f-string: cannot use starred expression here

IndentationError

Now this exception has more context as to which block was expecting an indent, and where the operator is located.

def foo():
if some:
x = 2

IndentationError: expected an indented block after 'if' statement in line 2

AttributeError

Now it will prompt suggestions of similar attribute names in the object

collections.namedtoplo

AttributeError: module 'collections' has no attribute 'namedtoplo'. Did you mean: namedtuple?

NameError

it will also work by offering you a similar name from your code as AttributeError

Structural Pattern Matching(Match-Case)

Before version 3.10, we had to use the if ... elif operator. Python version 3.10 introduced the match-case operator, which has more features than a simple selection operator. Its syntax is as follows:

def foo(key):
   match key:
       case 'python':
          # do something with py
       case 'c++':
          # do something with cpp
       case _:
          # default

In fact, this is not all his opportunity. Let's look at some simple examples with the new operator

Structural patterns

For example, you need to check whether the analyzed object is a sequence (list or set):

case ['a', 'b']:
   pass

What to do if we don't know the length of the incoming list, but only the first two elements are known. The match operator allows you to select the remaining elements of the sequence in a variable.

match some_seq:
   case [2, 4, *others]: # The first two elements are known
       print("Yes", *others)
   case _:
       print("No")

If, however, the length of the sequence is known, and some elements may change, then they can also be set as variable:

match some_seq:
   case (1, two, three, 4):
       print("Yes", two, three)

Another unexpected feature of structural templates is that you can check their values. For example, so:

case (y, x) if x == y:
   print("number")
case (y, *other) if len(other) == 3:
   print(other)

Dictionaries as structural patterns

Dictionaries can also serve as structural patterns. Now you can compare dictionaries by keys:

match some_dict:
   case {"move": direction, "distance": km}:
       move(direction, km)
   case {"stop": duration}:
       sleep(duration)

Using OR in a match-case

If some cases are handled in a similar way, then we can combine them as a logical expression using the OR (|) operation. Moreover, the OR operation can be used with literals, sequences, and dictionaries. Below is the Python code where the template with OR is used.

match k:
   case 1 | 2:
       print("number")
   case (1, _) | (_, 2):
       print("sequence")

Conclusion

A complete list of all changes is described in the Python documentation on the website Docs Python
We looked at the most interesting and understandable changes for beginners. It should be understood that the Python 3.10 version is not stable yet and I would not recommend using it as the main interpreter for projects temporarily. You can install it for tests or training.

Why is it useful for all Python developers to know these innovations? Soon we will all be faced with a new style of writing code, new operators, features, and syntactic changes from Python 3.10. The best will be the one who will be able to understand the new code before everyone else, having a lot of practice on previous versions.

Put on Heart if you liked it and you learned something new!

You can also follow ME to receive notifications about new interesting articles.

FAQ

I am a beginner, how should I learn Python?

Look into the following series:

Can we cooperate with you?

If you have interesting projects and you need a python (web)developer, then you can contact me by mail or discord and LinkedIn for cooperation

Connect to me on


To beat depression, try to just quit #programming đŸ€Ș

— Vadim Kolobanov (@decodesperato) November 22, 2021

18