yield conn is used in Python’s context manager pattern with the @contextmanager decorator. It’s a special way to manage resources (like database connections) automatically.
database.py:@contextmanager
def get_connection(self):
conn = None
try:
# Step 1: Create connection
credentials = get_secret(...)
conn = snowflake.connector.connect(...)
yield conn # Step 2: Pause here, give conn to the caller
# Step 4: Resume here after 'with' block ends
except Exception as e:
# Step 3: Handle errors
raise
finally:
# Step 5: Always clean up
if conn:
conn.close()
with db.get_connection() as conn:
cursor = conn.cursor()
cursor.execute("SELECT 1")
result = cursor.fetchone()
# Connection automatically closed here!
1. Enter 'with' block
↓
2. Execute code BEFORE yield (create connection)
↓
3. PAUSE at 'yield conn' → give conn to your code
↓
4. Execute YOUR code in the 'with' block
↓
5. Exit 'with' block
↓
6. Resume AFTER yield
↓
7. Execute 'finally' block (close connection)
yield?| Feature | With yield | Without yield |
|---|---|---|
| Auto-close connection | ✅ Yes | ❌ Manual |
| Exception safety | ✅ Closes even on error | ❌ May leak |
| Clean code | ✅ One line with | ❌ Need try-finally |
| Pythonic | ✅ Standard pattern | ❌ Verbose |
WITH yield (your current code):
with db.get_connection() as conn:
cursor = conn.cursor()
cursor.execute("SELECT 1")
# Auto-closed! ✅
WITHOUT yield:
conn = None
try:
conn = db.create_connection()
cursor = conn.cursor()
cursor.execute("SELECT 1")
finally:
if conn:
conn.close() # Must remember! ❌
Think of yield like a valet parking service:
with block)yield conn)with block)finally: conn.close())You don’t worry about parking – it’s automatic! 🚗
with db.get_connection() as conn:
cursor = conn.cursor()
cursor.execute("SELECT 1")
result = cursor.fetchone()
# ← Connection ALWAYS closed here, even if exception occurs
This guarantees:
That’s why yield is the best practice for managing database connections in Python! 🎯