pythonbeginner
Walrus Operator := Patterns
Use the walrus operator (:=) for concise assignment-in-expression patterns.
pythonPress ⌘/Ctrl + Shift + C to copy
# Filter and transform in one pass
data = [1, -2, 3, -4, 5, -6, 7]
positive_doubles = [
doubled
for x in data
if (doubled := x * 2) > 0
]
print(positive_doubles) # [2, 6, 10, 14]
# Read until EOF
import io
buffer = io.StringIO("line1\nline2\nline3\n")
while (line := buffer.readline()):
print(line.strip())
# Avoid repeated computation
import re
text = "Contact: alice@example.com"
if (match := re.search(r'[\w.]+@[\w.]+', text)):
print(f"Found email: {match.group()}")
# Complex list comprehension filtering
values = ["10", "abc", "20", "def", "30"]
numbers = [
n
for v in values
if (n := _try_int(v)) is not None
]
def _try_int(s):
try: return int(s)
except ValueError: return NoneUse Cases
- Concise filtering
- While-loop reads
- Regex matches
Tags
Related Snippets
Similar patterns you can reuse in the same workflow.
pythonbeginner
Dataclass with Validation
Python dataclass with __post_init__ field validation, type coercion, and descriptive error messages.
Best for: Data transfer objects
#dataclass#validation
pythonintermediate
Custom Context Manager
Context managers for resource management using both class-based and decorator approaches with error handling.
Best for: Database connection management
#context-manager#resource-management
pythonintermediate
Pytest Fixtures and Parametrize
Reusable pytest fixtures with scope control, parametrize for data-driven tests, and temporary resources.
Best for: Unit test setup
#pytest#testing
pythonintermediate
FastAPI Dependency Injection
Use FastAPI's dependency injection for database sessions, auth checks, and shared service logic.
Best for: Database session management
#fastapi#dependency-injection