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
Dictionary Merge Operator¶
https://docs.python.org/3/whatsnew/3.9.html#dictionary-merge-update-operators
In [1]:
d1 = {'x': 1, 'y': 2}
d2 = {'y': 3, 'z': 0}
In [2]:
# Before
{**d1, **d2}
Out[2]:
In [3]:
# Now
d1 | d2
Out[3]:
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!')
In [7]:
# Now
if (n := len(a)) > 5:
print(f'List with {n} elements is too long!')
New String Methods to Remove Prefixes and Suffixes¶
https://docs.python.org/3/whatsnew/3.9.html#new-string-methods-to-remove-prefixes-and-suffixes
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]:
In [11]:
# Now
s1.removesuffix('.txt') # You need to know the fileending
Out[11]:
In [12]:
s2 = 'www.czodrowskilab.org'
s2.removeprefix('www.')
Out[12]:
f-strings support = for self-documenting expressions and debugging¶
In [13]:
from datetime import date
from math import cos, pi
In [14]:
user = 'John Doe'
In [15]:
# Before
f'user={user}'
Out[15]:
In [16]:
# Now
f'{user=}'
Out[16]:
In [17]:
f'{user=!s}'
Out[17]:
In [18]:
# Before
a = cos(2**6 + pi)
f'{a:.3f}'
Out[18]:
In [19]:
# Now
f'{cos(2**6 + pi)=:.3f}'
Out[19]:
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)
In [22]:
# Invalid calls
f(1, 2, 3)
f(a=1, b=2, c=3)