Concurrency & performance
asyncio, threading, multiprocessing, and profiling-friendly performance patterns.
How to Reduce Instance Memory with __slots__ in Python
Demonstrates that classes with __slots__ use less memory per instance than regular classes because they skip the instance __dict__.
class SlottedPoint:
__slots__ = ('x', 'y', 'z')
def __init__(self, x, y, z):
self.x = x
self.y = y
self.z = z
class RegularPoint:
def __init__(self, x, y, z):
self.x = x
self.y = y
self.z = z
if __name__ == "__main__":
regular = RegularPoint(1, 2, 3)…
How to Share Memory Between Processes in Python with multiprocessing.Value and Array
Share a numeric value and a list-like array across multiple Python processes using multiprocessing.Value and multiprocessing.Array, with each process modifying the same memory.
import multiprocessing
def worker(shared_value, shared_array, index):
shared_value.value += 10
shared_array[index] = shared_array[index] * 2
if __name__ == "__main__":
shared_value = multiprocessing.Value("i", 5)
shared_array = multiprocessing.Array("i", [1, 2, 3, 4, 5])
processes = []
for i…
How to Use Array Typecodes for Compact Numeric Storage in Python
This code demonstrates how to use the `array` module with typecodes to store integers, floats, and bytes in a memory-efficient way compared to standard Python lists.
from array import array
def demonstrate_array_types():
# Compact integer arrays
small_ints = array('i', [1, 2, 3, 4, 5])
unsigned_ints = array('I', [10, 20, 30])
# Floating point arrays
floats = array('f', [1.5, 2.5, 3.5])
doubles = array('d', [1.123456789, 2.987654321])
# Charac…
How to Use a Weakref Cache to Avoid Memory Leaks in Python
This code demonstrates building a value cache with weakref.WeakValueDictionary so objects can be garbage collected when no longer referenced, preventing memory leaks.
import weakref
import gc
class ExpensiveObject:
def __init__(self, name):
self.name = name
def __repr__(self):
return f"ExpensiveObject('{self.name}')"
class ObjectCache:
def __init__(self):
self._cache = weakref.WeakValueDictionary()
def get_or_create(self, name):
…
Profile Memory Usage with tracemalloc Snapshot Diff in Python
Use tracemalloc to take two memory snapshots, compute a diff, and print the top changes (size and count) by line number.
import tracemalloc
def profile_memory():
tracemalloc.start()
# Allocate some objects to track
data = [i * 2 for i in range(10000)]
text = "x" * 5000
nested = {"key": [1, 2, 3], "value": (4, 5)}
# Take first snapshot
snapshot1 = tracemalloc.take_snapshot()
# Free some mem…
Using a Python Generator Instead of a List to Save Memory
Compare a list approach with a generator to stream values lazily, avoiding memory-heavy storage of large sequences.
def fibonacci_generator(limit):
a, b = 0, 1
count = 0
while count < limit:
yield a
a, b = b, a + b
count += 1
def sum_first_n(generator, n):
total = 0
for i, value in enumerate(generator):
if i >= n:
break
total += value
return total
if __…
Browse by section
Each section groups closely related Python snippets.
Concurrency & performance — Python code examples
What you will find here
This page collects concurrency & performance snippets — short, copy-ready Python you can paste into our free online IDE and run without installing anything. Each sample includes a plain-English explanation and the full source code.
Samples vs tutorials and challenges
Samples are quick reference — one concept per page. For step-by-step teaching, use our Python tutorials. To test yourself, try quizzes or coding challenges. Clean up style with the Python formatter.