"Python threading.Thread daemon=True: A Quick Guide"
"python threading.Thread daemon=True creates a background thread that dies when the main program exits. Here's the exact code and the gotchas that bite everyone."
Passing daemon=True to threading.Thread creates a background thread the interpreter won't wait for — when your main thread finishes, the python threading.Thread daemon=True worker is killed instantly. Use it for housekeeping like logging and monitoring, never for work that must complete, and set it before start() . Last updated: 2026-10-05 Minimal working example import threading import time def heartbeat(): while True: # runs forever... print("♥ alive", flush=True) time.sleep(1) t = threading.Thread(target=heartbeat, daemon=True) t.start() time.sleep(3) print("main done — daemon dies here") Output: ♥ alive ♥ alive ♥ alive main done — daemon dies here The heartbeat loop never exits on its own — but the process terminates anyway, because the only remaining thread is daemonic. Remove daemon=True and this program would run forever: the interpreter waits for every non-daemon thread before exiting. That contrast is the entire concept. python threading.Thread daemon=True: three ways to set it 1. The daemon=True keyword argument — the modern way. Pass it in the constructor, exactly as in the example above. This is what you should write in all new code: t = threading.Thread(target=heartbeat, daemon=True) 2. The daemon property — set before start() . Equivalent, useful when the flag is decided after construction: t = threading.Thread(target=heartbeat) t.daemon = True # must happen before t.start() t.start() Set it *after* start() and you get RuntimeError: cannot set daemon status of active thread . The flag is locked the moment the thread begins. 3. setDaemon(True) — legacy. Still works, but it's the old Java-style setter from Python 2 days. You'll see it in Stack Overflow answers from 2014; don't write it in new code. Three rules that complete the picture:…