Gestore di contesto asincrono in Python

Livello 5350 battiture

Questo crea un gestore di contesto asincrono usando __aenter__ e __aexit__. Usato con 'async with' per la gestione asincrona delle risorse.

Codice Python

# Importa asyncio per il supporto async/await
# Fornisce event loop e utilità async
1import asyncio
2
# class AsyncResource è un gestore di contesto asincrono
# Gestisce risorse che richiedono preparazione e pulizia asincrone
3class AsyncResource:
# __aenter__ è la versione async di __enter__
# Chiamato quando si entra nel blocco 'async with'
4 async def __aenter__(self):
# Stampa il messaggio di acquisizione
5 print("Acquiring resource")
# Simula un'operazione asincrona, come rete o file
6 await asyncio.sleep(0.1)
# Restituisce self per la variabile di 'as'
7 return self
8
# __aexit__ è la versione async di __exit__
# *args raccoglie le informazioni sull'eccezione, se presenti
9 async def __aexit__(self, *args):
# Stampa il messaggio di rilascio
10 print("Releasing resource")
# Simula una pulizia asincrona
11 await asyncio.sleep(0.1)
12
# use è un normale metodo async
# Chiamato mentre la risorsa è acquisita
13 async def use(self):
14 print("Using resource")
15
# main è una funzione async (coroutine)
# Punto di ingresso del codice async
16async def main():
# 'async with' chiama __aenter__ e __aexit__
# r è il valore restituito da __aenter__
17 async with AsyncResource() as r:
# Chiama use() mentre la risorsa è in uso
18 await r.use()
19
# asyncio.run() crea l'event loop ed esegue main
# Modo standard per eseguire codice async
20asyncio.run(main())

Output

Acquiring resource
Using resource
Releasing resource
Esercitati a digitare questo codice

Esercitati a digitare questo codice. I risultati non vengono registrati in classifica.

Simboli in questo codice

I simboli che digiti in questo codice Python e quante volte compaiono.

  • (× 13
  • )× 13
  • _× 8
  • :× 6
  • .× 6
  • "× 6
  • ,× 1
  • *× 1

Altri esempi Python di livello 5

← Pratica di digitazione Python