What’s new in Python 3.11

Mando
3 min readDec 12, 2022

General 2 minute overview for soft reader:

  • Will give more information on error and point out where is your error
  • On TypedDict -> added Required and not required annotation to point out need of that item
  • Self annotation is more simple on classes
  • LiteralString annotaion
  • More fast then before using adaptive
  • More good syntax on asnyc task
  • Toml is now added in standard library

Wow, those are interesting right!

Let’s deep dive into each of them

  1. More information on error:
class Person:
def __init__(self):
self.salary: float = None
self.age: int = None
self.name: str = None

def set_name(self, name:str):
self.name = name

def set_age(self, age:int):
self.age = age

def set_salary(self, salary:float):
self.salary = salary

def multiply(self):
print(self.salary / self.name)


if __name__ == '__main__':
person = Person()
person.set_name(name='Sam')
person.set_age(age=18)
person.set_salary(salary=100000)
person.multiply()
#
# OUTPUT: Traceback (most recent call last):
File "/mnt/hdd/personal/testing_python3-11/main.py", line 25, in <module>
person.multiply()
File "/mnt/hdd/personal/testing_python3-11/main.py", line 17, in multiply
print(self.salary / self.name)
~~~~~~~~~~~~^~~~~~~~~~~
TypeError: unsupported operand type(s) for /: 'int' and 'str'

As you can see its pointing out with ^ where is the problem

2. Required and Not required annotation on

from typing import TypedDict
from typing_extensions import Required, NotRequired


class Movie(TypedDict):
title: Required[str]
year: NotRequired[int]


if __name__ == '__main__':
m1: Movie = {"title": "Black Panther"}
print(m1.items())

#
#OUTPUT:
dict_items([('title', 'Black Panther')])

3. Self annotation is more simple on classes

from typing_extensions import Self


class MyLock:
def __init__(self, name):
self.name = name

def __enter__(self) -> Self:
print(self.lock())
return self

def lock(self):
return f'{self.name} is locked'


if __name__ == '__main__':
m1 = MyLock(name='Sam')
m1.__enter__()
#
#OUTPUT:
Sam is locked

4. Literal String annotation using (LiteralString)

from typing_extensions import Self, LiteralString


class MyLock:
def __init__(self, name):
self.name: LiteralString = name

def __enter__(self) -> Self:
print(self.lock())
return self

def lock(self):
return f'{self.name} is locked'


if __name__ == '__main__':
m1 = MyLock(name='Sam')
m1.__enter__()

#
#OUTPUT:
Sam is locked

5. More fast then before using adaptive as True

import dis


def to_the_moon(value):
return [x for x in range(value)]


if __name__ == '__main__':
dis.dis(to_the_moon, adaptive=True)
print(to_the_moon(10))
#OUTPUT
4 0 RESUME 0

5 2 LOAD_CONST 1 (<code object <listcomp> at 0x7fe021c8b290, file "/mnt/hdd/personal/testing_python3-11/adaptive.py", line 5>)
4 MAKE_FUNCTION 0
6 LOAD_GLOBAL 1 (NULL + range)
18 LOAD_FAST 0 (value)
20 PRECALL 1
24 CALL 1
34 GET_ITER
36 PRECALL 0
40 CALL 0
50 RETURN_VALUE

Disassembly of <code object <listcomp> at 0x7fe021c8b290, file "/mnt/hdd/personal/testing_python3-11/adaptive.py", line 5>:
5 0 RESUME 0
2 BUILD_LIST 0
4 LOAD_FAST 0 (.0)
>> 6 FOR_ITER 4 (to 16)
8 STORE_FAST 1 (x)
10 LOAD_FAST 1 (x)
12 LIST_APPEND 2
14 JUMP_BACKWARD 5 (to 6)
>> 16 RETURN_VALUE
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

6. More good syntax on asnyc task

import asyncio
import aiohttp
from typing import List


async def one_url(session, url):
print(f"Getting response from: {url}")
async with session.get(url) as response:
text = await response.text()
print(f"Got response from url: {url}: {text}")


async def all_urls(session, urls):
tasks = [asyncio.create_task(one_url(session, url)) for url in urls]
await asyncio.gather(*tasks)


async def main(urls:List):
async with aiohttp.ClientSession() as session:
await all_urls(session, urls)


if __name__ == '__main__':

asyncio.run(main(urls=[
"https://duckduckgo.com/",
'https://www.google.co.in/'
]))
#OUTPUT: you will get html code on console

7. Added toml into standard library

import tomllib

if __name__ == '__main__':
with open('map.toml', 'rb') as toml:
url_data = tomllib.load(toml)
print(url_data)
#OUTPUT
{'URL': {'google_url': 'https://www.google.co.in/', 'duckduckgo_url': 'https://duckduckgo.com/'}}
['URL']
google_url = 'https://www.google.co.in/'
duckduckgo_url = 'https://duckduckgo.com/'

Thanks for reading 📖.

--

--

Mando
Mando

Written by Mando

Research Machine Learning Engineer

No responses yet