Python Glossary Русский

all Python 3threadingfunction

threading.enumerate()

thread introspection

A list of all live Thread objects, including the main, daemon and dummy threads; threads not yet started or already finished are not in it.

Syntax

threading.enumerate()

The name clashes with the built-in enumerate(), and from threading import * shadows it: after that for i, x in enumerate(items) fails with TypeError — write threading.enumerate(). You get a snapshot copy: changing it is safe, but it may be stale by the time you use it. Handy when debugging why a program will not exit: look for non-daemon threads other than the main one.

Examples

import threading
stop = threading.Event()
t = threading.Thread(target=stop.wait, name='waiter')
print([th.name for th in threading.enumerate()])  # → ['MainThread']
t.start()
print(sorted(th.name for th in threading.enumerate()))  # → ['MainThread', 'waiter']
stop.set()
t.join()
from threading import *
try:
    for i, x in enumerate('ab'):
        pass
except TypeError as e:
    print(e)  # → enumerate() takes 0 positional arguments but 1 was given

See also

Open in the full glossarydocs.python.orgReport an inaccuracy