Recipe 1.1 · Python
Open Late, Close Early
The Python listings are conversions of the book's C# code to Python 3.12. Each file's header says what it needs to run. The explanations were written for the C# version, so some names in the text refer to .NET.
- Problem
- The way it's often written
- The improved recipe
- How it works
- Variations and pitfalls
- On .NET Framework
Problem
Connections are pooled, but only if you give them back. A connection that is opened in a constructor, stored in a field, or closed only on the happy path will eventually exhaust the pool. The symptom is a timeout message about the pool reaching its maximum size, usually under load and usually at the worst time.
The way it's often written
Anti-pattern: shown so you can recognize it. Don't copy this one.
If ExecuteScalar throws, Close() never runs and the connection stays out of the pool until the garbage collector finalizes it. The field also makes the class unsafe to share across threads, and the connection string lookup is buried in a field initializer where nothing can test or replace it.
Requirements: Python 3.12+. Install: pip install pyodbc · Needs at run time: SQL Server + Microsoft ODBC Driver 18 for SQL Server. The module loads without them; calling the code does not work without them.
"""Shared connection closed only on success
Source: ImproveCode, Chapter 1, Recipe 1.1 "Open Late, Close Early"
Section: The way it's often written
Book page: 17 -- original C# listing
Converted from C# to Python.
ANTI-PATTERN: kept deliberately faithful to the C# 'not to copy' example; do not use.
SqlConnection -> pyodbc connection; ConfigurationManager.AppSettings -> os.environ.
pyodbc connects on creation, so the "shared field" is a connection created once per instance.
"""
import os
import pyodbc
# Not to copy: a shared connection closed only on success.
class CustomerData:
def __init__(self) -> None:
self.conn_str = os.environ["ConnStr"]
self.conn: pyodbc.Connection | None = None
def count_active(self) -> int:
self.conn = pyodbc.connect(self.conn_str)
cmd = self.conn.cursor()
cmd.execute("SELECT COUNT(*) FROM Customer WHERE IsActive = 1")
count = int(cmd.fetchone()[0])
self.conn.close() # never reached if execute() raises
return count
The improved recipe
Requirements: Python 3.12+. Install: pip install aioodbc · Needs at run time: SQL Server + Microsoft ODBC Driver 18 for SQL Server. The module loads without them; calling the code does not work without them.
"""Connection factory that opens late and closes early
Source: ImproveCode, Chapter 1, Recipe 1.1 "Open Late, Close Early"
Section: The improved recipe
Book page: 17-18 -- original C# listing
Converted from C# to Python.
Microsoft.Data.SqlClient -> aioodbc (async pyodbc); IDbConnectionFactory -> typing.Protocol;
"await using" -> "async with"; CancellationToken -> asyncio task cancellation.
"""
from typing import Protocol
import aioodbc
class DbConnectionFactory(Protocol):
async def open(self) -> aioodbc.Connection: ...
class SqlConnectionFactory:
def __init__(self, connection_string: str) -> None:
if not connection_string or not connection_string.strip():
raise ValueError("connection_string must not be empty")
self._connection_string = connection_string
async def open(self) -> aioodbc.Connection:
# aioodbc.connect only returns an opened connection; if the open
# fails nothing is left behind to dispose.
return await aioodbc.connect(dsn=self._connection_string)
class CustomerStats:
def __init__(self, db: DbConnectionFactory) -> None:
self._db = db
async def count_active(self) -> int:
sql = "SELECT COUNT(*) FROM dbo.Customer WHERE IsActive = 1;"
async with await self._db.open() as connection:
async with connection.cursor() as command:
await command.execute(sql)
row = await command.fetchone()
return int(row[0])
How it works
The factory owns one thing: the connection string. It hands out a new, open connection each time, and the caller owns that connection for the length of one unit of work. await using guarantees DisposeAsync runs whether the method returns or throws, and disposing a pooled connection returns it to the pool. It does not close the physical connection to the server, so opening and disposing per call is cheap.
If OpenAsync fails, the factory disposes the half-built connection before rethrowing, so a failed login never leaks a connection object either.
Register the factory once at startup. In ASP.NET Core it is a singleton because it holds no per-request state:
The interface is there so a test can hand in a factory that points at a local test database. Chapter 6 covers getting the connection string itself out of source control.
Requirements: Python 3.12+. Install: pip install fastapi
"""Register the connection factory once at startup
Source: ImproveCode, Chapter 1, Recipe 1.1 "Open Late, Close Early"
Section: How it works
Book page: 19 -- original C# listing
Converted from C# to Python.
Program.cs DI registration -> FastAPI app state + dependency; GetConnectionString -> os.environ.
SqlConnectionFactory is the class from p017_r1_1_async_connection_factory_count.py (minimal stand-in here).
"""
import os
from fastapi import FastAPI, Request
class SqlConnectionFactory: # stand-in; see the improved recipe file
def __init__(self, connection_string: str) -> None:
self._connection_string = connection_string
def create_app() -> FastAPI:
# Usage snippet: Program.cs
cs = os.environ.get("CONNECTIONSTRINGS__APPDB")
if cs is None:
raise RuntimeError("Missing AppDb.")
app = FastAPI()
app.state.db = SqlConnectionFactory(cs) # singleton
return app
def get_db(request: Request) -> SqlConnectionFactory:
"""FastAPI dependency: Depends(get_db) returns the singleton factory."""
return request.app.state.db
Variations and pitfalls
- Do not cache the connection. Not in a static field, not in a singleton service, not in
HttpContext.Items. Pooling already does the caching, and it does it safely. - Pool size. The default maximum is 100 connections per distinct connection string. If you hit it, the fix is almost always a leak or long-running work inside an open connection, not a bigger
Max Pool Size. - One connection string. Every variation of the string (a different
Application Name, a user ID built per request) creates a separate pool. Keep the string constant. - Encryption defaults. Starting with version 4 of
Microsoft.Data.SqlClient,Encryptdefaults totrue. Against a development server with a self-signed certificate you will see a certificate error. Fix the certificate, or setTrustServerCertificate=Truefor local development only.
On .NET Framework
The same pattern works on .NET Framework 4.6.2 and later with the Microsoft.Data.SqlClient package. On C# 7.3 you write using (var connection = ...) blocks instead of await using declarations, and you call Open() or OpenAsync() the same way.