๐๐ [3.15] thread-safe iterators
October 29, 2026
๐๐ [3.15] thread-safe iterators
day 13 of 15 days of Python 3.15
Hey there, ๐
How is your Python ๐ going?
In this email weโll talk about writing and using thread-safe iterators. ๐
See the future schedule here and links to the previous days: https://mathspp.com/python-315
Iterators are not thread-safe
Iterators are not thread-safe out of the box.
For example, generators will raise ValueError if you try to access them from one thread while another thread is running the generator already.
Python 3.15 provides the tools to work with this.
Serialising an iterator
Given an iterator, you can now create a thread-safe version of it with
import threading
it = ... # Non-thread-safe iterator
threadsafe_it = threading.serialize_iterator(it)Serialising all iterators from an iterator factory
If you have an โiterator factoryโ, like something from itertools or a generator, you can use @threading.synchronize_iterator to automatically serialise all the iterators produce.
E.g., hereโs how to write a thread-safe generator:
import threading
@threading.synchronize_iterator
def my_threadsafe_generator():
...The generator function my_threadsafe_generator will automatically produce thread-safe iterators.
Further reading
You can learn more about thread-safe iterators and the new 3.15 tools here: https://mathspp.com/blog/threadsafe-iterators
Tomorrow youโll learn about the new โabi3tโ, namely what it means and the silent impact itโll have on you and the community!
See the future schedule here and links to the previous days: https://mathspp.com/python-315
You received this email (at [subscriber]) because you got my free Python book โPydonโtsโ or one of my other books/cheatsheets (or because you signed up directly!).
Rodrigo ๐๐
ยฉ 2026 mathspp insider ๐๐
228 Park Ave S, #29976, New York, New York 10003, United States