Skip to content

M-Taghizadeh/py310

Repository files navigation

python310

Getting Started

Structural-Pattern-Matching

match subject:
    case <pattern_1>:
        <action_1>
    case <pattern_2>:
        <action_2>
    case _:
        <action_wildcard>
def httperror(status):
    match status:
        case 400: 
            return "Bad request"
        case 401 | 403:
            return "Not allowed"
        case 404:
            return "Not found"
        case _:
            return "Somthing's wrong with the internet"

print(httperror(406))
# point is an (x, y) tuple
x = 9
y = 10
point = (x, y)
match point:
    case (0, 0):
        print("Origin")
    case (0, y):
        print(f"Y={y}")
    case (x, 0):
        print(f"X={x}")
    case (x, y):
        print(f"X={x}, Y={y}")
    case _:
        raise ValueError("Not a point")
from enum import Enum
class Color(Enum):
    RED = 0
    GREEN = 1
    BLUE = 2

color = Color.RED

match color:
    case Color.RED:
        print("I see red!")
    case Color.GREEN:
        print("Grass is green")
    case Color.BLUE:
        print("I'm feeling the blues :(")
    case _:
        print("Not Color")

Parenthesized-context-managers

  • what is context manager? for example : with in open files
with open('myfilename.txt') as f:
    pass
  • create multiple context manager in python310
class Log_Manager:
    def __enter__(self):
        print('Entering context manager')

    def __exit__(self, exc_type, exc_val, exc_tb):
        print('Exiting context manager')
class Test_Context_Manager:
    def __enter__(self):
        print('task1')

    def __exit__(self, exc_type, exc_val, exc_tb):
        print('task2')

our function:

def do_task():
    print("do task")
  • python3.9
with Log_Manager():
    do_task()
  • Parenthesized context managers
with (
    Log_Manager() as ctx1,
    Test_Context_Manager() as ctx2,
):
    do_task()

zip

  • what is zip : The zip() function returns a zip object, which is an iterator of tuples where the first item in each passed iterator is paired together, and then the second item in each passed iterator are paired together etc.

  • strict in python3.10

name = ("Mohammad", "Ali", "Reza")
family = ("Taghizadeh", "Mohammadi", "Rahimi",  "Felani", "Behamani")
fullname_tuple = zip(name, family, strict=True) # strict(yek dandeh) => ValueError: zip() argument 2 is longer than argument 1
print(list(fullname_tuple))
  • we can use zip() for list objects
name = ["Mohammad", "Ali", "Reza"]
family = ["Taghizadeh", "Mohammadi", "Rahimi",  "Felani"]
fullname_tuple = zip(name, family)
print(list(fullname_tuple))

Better-error-messages

SyntaxError

mydict = {9: 1, 18: 2, 19: 2, 27: 3, 28: 3, 29: 3, 36: 4, 37: 4,
some_other_code = foo()
output: SyntaxError: '{' was never closed 
print("hello world!" 
print("hello world!")
output: SyntaxError: '(' was never closed
try:
    x = 2
something = 3
number = "mohammad"
if name = "mohammad": 
    pass    

IndentationError

def task():
    if True:
    x = 2

AttributeErrors : errors suggestions

product = "car"
print(produc) 

output: NameError: name 'produc' is not defined. Did you mean: 'product'?

typing

  • Union Operator => python3.9 => |, |=
dict1 = {
    1: 'a',
    2: 'b', 
    3: 'c', 
    4: 'in both',
}
dict2 = {
    4: 'but different', 
    5: 'd', 
    6: 'e'
}

print(dict1 | dict2) 
dict1 |= dict2
print(dict1)
  • New Type Union Operator
def square(number: int | float):
    print(type(number))
    return number ** 2

# Instead of 
from typing import Union
def old_square(number: Union[int, float]):
    return number ** 2

print(square(2.2))
print(square(2))

Improved Modules

asyncio, argparse
base64,
contextlib,
dataclasses,
hashlib,
os,
pathlib, pprint,
statistics, socket, ssl, sqlite3,
threading, traceback, typing,
unittest,
xml

Optimizations

  • Constructors str(), bytes() and bytearray() are now faster (around 30–40% for small objects).

  • The runpy module now imports fewer modules. The python3 -m module-name command startup time is 1.4x faster in average. On Linux, python3 -I -m module-name imports 69 modules on Python 3.9, whereas it only imports 51 modules (-18) on Python 3.10.

About

In This repository explains the new features in Python 3.10

Topics

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages