Python 3.10

L&L S4S1

2.7  - 03/07/2010

3.7  - 27/06/2018

3.8  - 14/10/2019
3.9  - 05/10/2020

3.10 - 04/10/2021

10m  Review python 3.8, 3.9

20m  Python 3.10 & Demo

15m    Q&A

  • (1) f-strings support '='
  • (2) ...
  • (3) ...
  • (4) Detailed Warning
  • (5) Performance Opt
  • (6) ...

Pyhon 3.8

(1) f-strings support '='

name1 = "Shiniya"
name2 = "Dahmane"
name3 = "Qiang"
print(f"name1={name1}")
print(f"{name2=}")
print(f"{name3=}")
name1 = "Shiniya"
name2 = "Dahmane"
name3 = "Qiang"
print(name1)
print(name2)
print('name3=',name3)

Classic Pyhon 3

Shiniya
Dahmane
name3=Qiang

Output:

name1=Shiniya
name2=Dahmane
name3=Qiang

Pyhon 3.8

(4) Detailed Warning:

== v.s. is

>>> version = "3.8"
>>> version == "3.8"
True
>>> version is "3.8"
<>:1: SyntaxWarning: "is" with a literal. Did you mean "=="?
<ipython-input-29-fb0be97c5f9d>:1: SyntaxWarning: "is" with a literal. Did you mean "=="?
  version is "3.8"
Out[29]: False
>>> version = "3.5"
>>> version == "3.5"
True​
>>> version is "3.5"
False

 

 

Classic Pyhon 3

Classic Pyhon 3

test = [
('a','b'),
('c','d')
]

 

TypeError: 'tuple' object is not callable

 
test = [
('a','b'),
('c','d')
]

 

SyntaxWarning: 'tuple' object is not callable; perhaps you missed a comma?
 

(4) Detailed Warning:

comma

Pyhon 3.8

Pyhon 3.8

(5) Performance Opt:

Faster

import collections
from timeit import timeit

P = collections.namedtuple(
  "P", 
  "name team"
) 
qiang = P("Qiang","LSE")
timeit(
  "qiang.team",  
  globals=globals(),
)
 

Classic Pyhon 3

0.07939400000032037
0.05426930000066932
161528168
181719232

Classic Pyhon 3

import sys

sys.getsizeof(
  list(
    range(20191014)
  )
)

 

(5) Performance Opt:

Memory

Pyhon 3.8

(6) Others

  • Import math and statistics

    • math.prod((2, 2, 2))

    • math.isqrt(9)

    • math.dist(point_1, point_2)

    • statistics.fmean()

  • Multiprocessing - memory share

  • Importlib.metadata

  • (1) Dictionary Merge & Update Operators
  • (2) removeprefix() & removesuffix() string methods
  • (3) Builtin Generic Types
  • (4) ...

Pyhon 3.9

(1) Dictionary Merge & Update Operators

a_dict = { x: '1', y: '2', z: '3' }

b_dict = { i: '4', j: '5' }

 

c_dict = a_dict | b_dict
print(c_dict)

a_dict = { x: '1', y: '2', z: '3' }

b_dict = { i: '4', j: '5' }

 

c_dict = {**a_dict, **b_dict}

print(c_dict)

Classic Pyhon 3

(1) Dictionary Merge & Update Operators

a_dict = { 'x': '1', 'y': '2', 'z': '3' }


b_dict = { 'i': '4', 'j': '5' }


a_dict |= b_dict


print(a_dict)

(2) removeprefix() & removesuffix() string methods

a_str = "Elena thought Filipa hated dogs".removeprefix("Elena thought ")
print(a_str)

b_str = "Dario likes cats ?".removesuffix("?")
print(b_str)

(3) Builtin Generic Types

from typing import (
    List,
    Dict,
)

def this_is_a_func( var_a: List ) -> Dict:
    return final_dict

Python 3.10

  • (1) Precise line numbers for debugging
  • (2) Allow writing union types as X | Y
  • (3) Add Optional Length-Checking To zip
  • (4) Structural Pattern Matching

(1) Precise line numbers for debugging

Pyhon 3.10

my_list = ["Hi", "Levis"
print(my_list)

 

Classic Pyhon 3

(2) Allow writing union types as X | Y

Pyhon 3.10

from typing import Union
def old_typing(para: Union[int, float]) -> Union[int, float]:
    return para*2

print(old_typing(0.3))

Classic Pyhon 3

def new_typing(para: int | float) -> int | float:
    return para*2

print(new_typing(0.3))

(3) Add Optional Length-Checking To zip

Pyhon 3.10

names = ["Filipa", "Victor", "TAHAR", "GUILLAUME", "Howard"]
roles = ["DS", "DEVOPS", "MLE", "DE"]
list(zip(names, roles))

 

Classic Pyhon 3

names = ["Filipa", "Victor", "TAHAR", "GUILLAUME", "Howard"]
roles = ["DS", "DEVOPS", "MLE", "DE"]
list(zip(names, roles, strict=True))

 

(4) Structural Pattern Matching

Pyhon 3.10

match subject:    
    case con1:        
        do  
    case con2:        
        do    
    case con3:        
        do    
    case _:        
        do
if
    do 
elif
    do 
elif
    do 

...

else
    do 

Classic Pyhon 3

(4) Structural Pattern Matching

Pyhon 3.10

def test(n):
    match n:
           case 0 | 1:
            return 1
        case _:
            return n*3
           
test(5)
def test(n):
    if n == 0 or n == 1:
        return 1
    else:
        return n*3

test(5) 

Classic Pyhon 3

(4) Structural Pattern Matching

Pyhon 3.10

roles = ("DS", "MLE", "DEVOPS")
#roles = ("DS", "MLE", "DEVOPS", "DE")

match roles:
    case filipa, saeed, victor:
        print(f"{filipa=},{saeed=},{victor=},")
    case filipa, saeed, victor, vicente:
        print(f"{filipa=},{saeed=},{victor=}, and {vicente=}")

 

(4) Structural Pattern Matching

def normalise_biz(biz_logic):
"""Normalise biz logic to (region, (con1, con2, con3, conx))."""
    match colour:
        case (con1, con2, con3):
            region = "EU"
            conx = ""
        case (con1, con2, con3, conx):
            region = "Global"
        case (region, (con1, con2, con3)):
            conx = "Frida"
        case (region, (con1, con2, con3, conx)):
            pass
        case _:
            raise ValueError("Unknown biz logic.")
    return (region, (con1, con2, con3, conx))



print(normalise_biz(("Caravaggio", "Dali", "Da Vinchy")))                      
print(normalise_biz(("Caravaggio", "Dali", "Zheng", "Frida")))                  
print(normalise_biz(("Mexico", ("Caravaggio", "Dali", "Zheng"))))       
print(normalise_biz(("Global", ("Caravaggio", "Dali", "Zheng", "Frida")))) 

 

Q&A

Python 3.10

By Qiang MENG

Python 3.10

  • 45