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 · IntermediateSnippet

Generator Expressions for Memory Efficiency

Unlike list comprehensions, generator expressions use parentheses and yield items one by one. This is significantly more memory-efficient for large datasets.

snippet.py
python
1
2
3
4
5
6
7
import sys
large_list = [x for x in range(1000000)]
large_gen = (x for x in range(1000000))
print(sys.getsizeof(large_list)) # ~8MB
print(sys.getsizeof(large_gen)) # ~100 bytes
PerformanceData Types
Python · IntermediateSnippet

Unpacking with *args and **kwargs

*args allows a function to accept any number of positional arguments as a tuple, while **kwargs accepts arbitrary keyword arguments as a dictionary.

snippet.py
python
1
2
3
4
5
6
def versatile_func(required, *args, **kwargs):
print(f'Required: {required}')
print(f'Additional positional: {args}')
print(f'Keyword arguments: {kwargs}')
versatile_func('Main', 1, 2, mode='fast', debug=True)
FunctionsSyntax
Python · IntermediateSnippet

Property Decorators for Encapsulation

The @property decorator allows you to define methods that can be accessed like attributes, providing a clean way to implement validation and encapsulation in classes.

snippet.py
python
1
2
3
4
5
6
7
8
9
10
11
12
13
class Circle:
def __init__(self, radius):
self._radius = radius
@property
def radius(self):
return self._radius
@radius.setter
def radius(self, value):
if value < 0:
raise ValueError('Radius cannot be negative')
self._radius = value
OOPBest Practices
Python · IntermediateSnippet

Managing Resources with Context Managers

The 'with' statement simplifies exception handling by encapsulating standard clean-up tasks, like closing a file automatically after the block finishes.

snippet.py
python
1
2
3
4
5
6
try:
with open('data.txt', 'r') as file:
content = file.read()
except FileNotFoundError:
print('File not found')
# File is automatically closed here even if an error occurs
Error HandlingBest Practices
Python · IntermediateSnippet

List Comprehensions with Conditional Logic

List comprehensions provide a concise way to create lists. This intermediate pattern includes an 'if' condition to filter elements while applying a transformation.

snippet.py
python
1
2
3
numbers = [1, 2, 3, 4, 5, 6]
squared_evens = [x**2 for x in numbers if x % 2 == 0]
print(squared_evens) # Output: [4, 16, 36]
SyntaxBest Practices
Python · IntermediateSnippet

Function Decorators

Decorators allow you to wrap another function to extend its behavior without permanently modifying it. They are often used for logging, access control, or caching.

snippet.py
python
1
2
3
4
5
6
7
8
9
def log_call(func):
def wrapper(*args, **kwargs):
print(f"Calling {func.__name__}")
return func(*args, **kwargs)
return wrapper
@log_call
def greet(name):
return f"Hello, {name}"
FunctionsDesign Patterns
Python · IntermediateSnippet

Parallel Iteration with zip()

The zip() function takes multiple iterables and aggregates them into tuples. This is the most efficient way to iterate over multiple lists in parallel.

snippet.py
python
1
2
3
4
5
names = ["Alice", "Bob", "Charlie"]
scores = [85, 92, 78]
for name, score in zip(names, scores):
print(f"{name} scored {score}")
SyntaxPerformance
Python · IntermediateSnippet

Simplifying Classes with Dataclasses

The @dataclass decorator automatically generates common methods like __init__, __repr__, and __eq__ based on type hints, reducing boilerplate code in data-oriented classes.

snippet.py
python
1
2
3
4
5
6
7
8
9
10
from dataclasses import dataclass
@dataclass
class Product:
name: str
price: float
quantity: int = 0
def total_value(self) -> float:
return self.price * self.quantity
OOPData Types