New features in Python3.8

Tech Geek
4 min readOct 25, 2019
Python3.8

From a powerful new assignment syntax to under-the-hood overhauls, Python 3.8 steps toward a more modern Python codebase. This article provided a summary of the awesome Python 3.8 features.

Install python3.8 in ubuntu:

sudo add-apt-repository ppa:deadsnakes/ppa
sudo apt-get update
sudo apt-get install python3.8
  1. New syntax warnings:

The Python interpreter now throws a SyntaxWarning in some cases when a comma is missed before tuple or list. So when you accidentally do this:

data = [
(a, b, c)
(d, e, f)
]

Instead of showing TypeError: ‘tuple’ object is not callable which doesn’t really tell you what’s wrong, a helpful warning will be shown pointing out that you probably missed a comma. Pretty helpful while debugging!

<stdin>:2: SyntaxWarning: ‘tuple’ object is not callable; perhaps you missed a comma?

2. reversed() now works with dict:

Since Python 3.7, dictionaries preserve the order of insertion of keys. The reversed() built-in can now be used to access the dictionary in the reverse order of insertion — just like OrderedDict.

>>> my_dict = dict(a=1, b=2)
>>> list(reversed(my_dict))
[‘b’, ‘a’]
>>> list(reversed(my_dict.items()))
[(‘b’, 2), (‘a’, 1)]

3. f-strings support = for self-documenting expressions and debugging Ease:

Added an = specifier to f-strings. An f-string such as f’{expr=}’ will expand to the text of the expression, an equal sign, then the representation of the evaluated expression. For example:

>>> user = ‘eric_idle’
>>> member_since = date(1975, 7, 31)
>>> f’{user=} {member_since=}’
“user=’eric_idle’ member_since=datetime.date(1975, 7, 31)”

The usual f-string format specifiers allow more control over how the result of the expression is displayed:

>>> delta = date.today() — member_since
>>> f’{user=!s} {delta.days=:,d}’
‘user=eric_idle delta.days=16,075’

The = specifier will display the whole expression so that calculations can be shown:

>>> print(f’{theta=} {cos(radians(theta))=:.3f}’)
theta=30 cos(radians(theta))=0.866

4. Assignment Expressions :=

It is also known as walrus operator due to its resemblance to the eyes and tusks of a walrus.

There is new syntax := that assigns values to variables as part of a larger expression.

In this example, the assignment expression helps avoid calling len() twice:

if (n := len(a)) > 10:
print(f”List is too long ({n} elements, expected <= 10)”)

A similar benefit arises during regular expression matching where match objects are needed twice, once to test whether a match occurred and another to extract a subgroup:

discount = 0.0
if (mo := re.search(r’(\d+)% discount’, advertisement)):
discount = float(mo.group(1)) / 100.0

The operator is also useful with while-loops that compute a value to test loop termination and then need that same value again in the body of the loop:

# Loop over fixed length blocks
while (block := f.read(256)) != ‘’:
process(block)

Another motivating use case arises in list comprehensions where a value computed in a filtering condition is also needed in the expression body:

[clean_name.title() for name in names
if (clean_name := normalize(‘NFC’, name)) in allowed_names]

Try to limit use of the walrus operator to clean cases that reduce complexity and improve readability.

5. Positional-only parameters (/)

If you want to call a function in Python that accepts parameters then you can pass the arguments by position or by keyword.
But what if we want to restrict the callers of our API to only call our function by passing in parameters by position? What if our parameter names do not make sense to the external world (for whatever reason) OR we might be planning to rename the parameters in the future AND we want to make our API backward compatible? The positional-only parameter functionality “/” solves it.

Let’s understand it with an example:

def add(a, b, c, d=None, /):
x = a+b+c
if d is not None:
x = x+d
return x

The function “add” accepts three mandatory parameters: a,b and c, and an optional parameter d. The last parameter “/” indicates that the parameters of the function must be specified positionally. As a result, we cannot call the function by passing in parameters by keyword.

Subsequently, add(1,2,3) and add(1,2,3,4) are valid calls.
add(a=1,b=2,c=3) or add(1,2,3,d=4) are all invalid calls.

The result of the “/” parameter indicates that the function accepts positional-only parameters and thus the arguments must be mapped to the parameters based solely on their order.

Summary:

The upcoming release of Python adds some great new features to the language and significantly improves the performance with fundamental speed-up fixes.

Read more about all the new features of python3.8: https://docs.python.org/3/whatsnew/3.8.html

--

--

Tech Geek

I’m a software developer from India, currently working with blockchain.