Python Glossary Русский

Python 3.8+threadingterm

threading.ExceptHookArgs

errors in threads

The type of the argument passed to threading.excepthook: a sequence with the fields exc_type, exc_value, exc_traceback and thread.

Syntax

def hook(args): args.exc_type, args.exc_value, args.exc_traceback, args.thread

You never need to create one — the object arrives in your hook. exc_value, exc_traceback and thread may be None, so check them before use. Do not keep args.exc_value or args.thread after the hook returns: that creates a reference cycle or resurrects a thread being finalized — copy what you need (the thread name, the error text). It is a struct sequence rather than a namedtuple: there is no _fields, and the constructor takes a single four-item sequence.

Examples

import threading
seen = []
def hook(args):
    seen.append(type(args) is threading.ExceptHookArgs)
    seen.append((args.exc_type.__name__, str(args.exc_value), args.thread.name))
threading.excepthook = hook
def job():
    raise ValueError('bad data')
t = threading.Thread(target=job, name='worker')
t.start()
t.join()
print(seen)  # → [True, ('ValueError', 'bad data', 'worker')]
import threading
args = threading.ExceptHookArgs((KeyError, KeyError('x'), None, None))
print(args.exc_type.__name__, args.thread)  # → KeyError None
print(len(args))  # → 4

See also

Open in the full glossarydocs.python.orgReport an inaccuracy