Python


What's new in Python 3.8 and 3.9


Author: Marcel Baltruschat (@GitHub)
Date: 04.02.2021

Content

  • Dictionary Merge Operator
  • Assignment Expressions
  • New String Methods to Remove Prefixes and Suffixes
  • f-strings support = for self-documenting expressions and debugging
  • Positional-only parameters


In [1]:
d1 = {'x': 1, 'y': 2}
d2 = {'y': 3, 'z': 0}
In [2]:
# Before
{**d1, **d2}
Out[2]:
{'x': 1, 'y': 3, 'z': 0}
In [3]:
# Now
d1 | d2
Out[3]:
{'x': 1, 'y': 3, 'z': 0}
In [4]:
# Important: The last item "wins"
In [5]:
a = [1, 2, 3, 4, 5, 6]
In [6]:
# Before
n = len(a)
if n > 5:
    print(f'List with {n} elements is too long!')
List with 6 elements is too long!
In [7]:
# Now
if (n := len(a)) > 5:
    print(f'List with {n} elements is too long!')
List with 6 elements is too long!
In [8]:
import os
In [9]:
s1 = 'myfile.txt'
In [10]:
# Before
s1.split('.')[0]                  # Problem with multiple dots in filename
s1[:-4]                           # Problem if you don't know the length
''.join(s1.split('.')[:-1])       # Complicated
os.path.splitext('myfile.txt')[0] # Needs import
Out[10]:
'myfile'
In [11]:
# Now
s1.removesuffix('.txt')  # You need to know the fileending
Out[11]:
'myfile'
In [12]:
s2 = 'www.czodrowskilab.org'
s2.removeprefix('www.')
Out[12]:
'czodrowskilab.org'
In [13]:
from datetime import date
from math import cos, pi
In [14]:
user = 'John Doe'
In [15]:
# Before
f'user={user}'
Out[15]:
'user=John Doe'
In [16]:
# Now
f'{user=}'
Out[16]:
"user='John Doe'"
In [17]:
f'{user=!s}'
Out[17]:
'user=John Doe'


In [18]:
# Before
a = cos(2**6 + pi)
f'{a:.3f}'
Out[18]:
'-0.392'
In [19]:
# Now
f'{cos(2**6 + pi)=:.3f}'
Out[19]:
'cos(2**6 + pi)=-0.392'
In [20]:
def f(a, /, b, *, c):
    # a has to be positional
    # b can be positional or a keyword argument
    # c has to be a keyword argument
    print(a, b, c)
In [21]:
# Valid calls
f(1, 2, c=3)
f(1, b=2, c=3)
1 2 3
1 2 3
In [22]:
# Invalid calls
f(1, 2, 3)
f(a=1, b=2, c=3)
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-22-a83ad21307fb> in <module>
      1 # Invalid calls
----> 2 f(1, 2, 3)
      3 f(a=1, b=2, c=3)

TypeError: f() takes 2 positional arguments but 3 were given