0 day streak
Code library

Code worth reading.

Hand-picked snippets across TypeScript, Python, Rust, Go, and more — each one comes with a line-by-line breakdown so you can read it like the people who wrote it.

3495 snippets · 10 languages
▶ Start learning
Python · ExpertSnippet

Descriptor Protocol for Type Safety

Descriptors are classes that define any of the methods __get__, __set__, or __delete__. They are used to implement custom logic for attribute access. In this snippet, __set_name__ automatically captures the attribute name, and __set__ enforces that the value assigned to 'age' is always an integer.

snippet.py
python
1
2
3
4
5
6
7
8
9
10
11
class IntegerField:
def __set_name__(self, owner, name):
self.name = name
def __set__(self, instance, value):
if not isinstance(value, int):
raise ValueError(f'{self.name} must be an integer')
instance.__dict__[self.name] = value
class User:
age = IntegerField()
OOPBest Practices
Python · ExpertSnippet

Zero-Copy Slicing with memoryview

The memoryview object allows Python code to access the internal data of an object that supports the buffer protocol (like bytearray) without copying. Slicing a memoryview returns a new memoryview that shares the same underlying buffer, enabling extremely efficient memory manipulation for large datasets.

snippet.py
python
1
2
3
4
5
6
data = bytearray(b'X' * 100_000_000)
mv = memoryview(data)
chunk = mv[1000:2000]
# No data is copied here
chunk[0] = ord('Y')
print(data[1000]) # Outputs: 89 ('Y')
PerformanceData Types
Python · ExpertSnippet

Metaclasses for Singleton Enforcement

Metaclasses are the 'classes of classes'. By overriding the __call__ method of a metaclass, you can control the instantiation process of its classes. In this example, the metaclass ensures that only one instance of the Database class ever exists by storing and reusing it in a private dictionary.

snippet.py
python
1
2
3
4
5
6
7
8
9
class Singleton(type):
_instances = {}
def __call__(cls, *args, **kwargs):
if cls not in cls._instances:
cls._instances[cls] = super().__call__(*args, **kwargs)
return cls._instances[cls]
class Database(metaclass=Singleton):
pass
OOPDesign Patterns
Python · ExpertSnippet

Advanced Pattern Matching with Guards

Structural Pattern Matching (introduced in Python 3.10) allows for expressive data deconstruction. Using 'guards' (the 'if' clause after a pattern) enables adding conditional logic directly into the matching process, allowing for more granular control over complex dictionary or object structures.

snippet.py
python
1
2
3
4
5
6
7
8
def process_data(payload):
match payload:
case {"type": "user", "id": int(uid)} if uid > 1000:
return f"Admin logic for {uid}"
case {"type": "user", "id": int(uid)}:
return f"User logic for {uid}"
case _:
raise ValueError("Unknown format")
SyntaxControl Flow
Python · ExpertSnippet

Async Iteration with Context Managers

This demonstrates combining asynchronous context managers (__aenter__/__aexit__) with asynchronous iterators (__aiter__). It allows for safe resource management in concurrent environments while processing streams of data asynchronously using 'async with' and 'async for'.

snippet.py
python
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
import asyncio
class AsyncBuffer:
async def __aenter__(self):
print('Opening...')
return self
async def __aexit__(self, *args):
print('Closing...')
async def __aiter__(self):
for i in range(3):
await asyncio.sleep(0.1)
yield i
async def main():
async with AsyncBuffer() as buf:
async for item in buf:
print(item)
Async & ConcurrencyControl Flow
Python · ExpertSnippet

Scoped State with Context Variables

Context variables (contextvars) allow data to persist within a specific execution flow. Unlike thread-local storage, they are aware of async tasks, making them ideal for storing request IDs or transaction state in web servers.

snippet.py
python
1
2
3
4
5
6
7
8
9
10
11
12
13
import contextvars
import asyncio
client_id = contextvars.ContextVar("client_id")
async def log_operation(msg):
print(f"[Client {client_id.get()}] {msg}")
async def handle_request(cid):
client_id.set(cid)
await log_operation("Starting process")
asyncio.run(asyncio.gather(handle_request(1), handle_request(2)))
Async & ConcurrencyBest Practices
Python · ExpertSnippet

Intercepting Imports with Meta Path Finders

The Python import system can be customized by adding finders to sys.meta_path. This allows you to intercept every import attempt, enabling advanced patterns like hot-reloading, remote module loading, or automated instrumentation for security audits.

snippet.py
python
1
2
3
4
5
6
7
8
9
import sys
from importlib.abc import MetaPathFinder
class DebugFinder(MetaPathFinder):
def find_spec(self, fullname, path, target=None):
print(f"Attempting to import: {fullname}")
return None
sys.meta_path.insert(0, DebugFinder())
SyntaxDesign Patterns
Python · ExpertSnippet

Structural Subtyping with Protocols

Protocols (PEP 544) enable static duck typing. Unlike standard inheritance, a class is considered a subtype of a Protocol if it simply implements the required methods, without needing to explicitly inherit from the Protocol class.

snippet.py
python
1
2
3
4
5
6
7
8
9
10
11
12
13
from typing import Protocol, runtime_checkable
@runtime_checkable
class Drawable(Protocol):
def draw(self) -> str: ...
class Circle:
def draw(self) -> str: return "Circle drawn"
def render(obj: Drawable):
if isinstance(obj, Drawable):
return obj.draw()
return "Not drawable"
OOPBest Practices