Átomo
8Wi
Fundamentos · Python

with

Abrir na tabela

Definição

Gerenciador de contexto: abre um recurso e garante que ele é fechado, mesmo com erro.

Exemplos

1. Ficheiro
with open("config.json") as f:
    config = json.load(f)
2. Conexão com banco
with engine.begin() as conn:
    conn.execute(text("DELETE FROM stg_sales"))
    conn.execute(text("INSERT INTO stg_sales SELECT * FROM landing_sales"))
3. Criar um gerenciador de contexto
from contextlib import contextmanager
import time

@contextmanager
def timer(label):
    start = time.perf_counter()
    yield
    print(f"{label}: {time.perf_counter() - start:.1f}s")

with timer("load sales"):
    load_sales()

No mesmo grupo