Skip to content

Instantly share code, notes, and snippets.

@rongpenl
Created May 29, 2023 04:25
Show Gist options
  • Save rongpenl/ea92b8db417e4decb6caf924d804ea51 to your computer and use it in GitHub Desktop.
Save rongpenl/ea92b8db417e4decb6caf924d804ea51 to your computer and use it in GitHub Desktop.
Cracking Intermediate Python Episode 1: Context Manager
from threading import Lock
import sqlite3
import requests
# thread lock example
lock = Lock()
with lock:
# Critical section of code
print("Critical section running")
# database connection example
with sqlite3.connect("database.db") as conn:
cursor = conn.cursor()
cursor.execute("SELECT * FROM table")
# requests session example
with requests.Session() as session:
response = session.get('http://example.com')
print(response.status_code)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment