Python Glossary Русский

Python 3.4+tracebackfunction

traceback.clear_frames()

frames and stack

Clears the local variables of every frame in a traceback so that a saved exception no longer keeps the data of the failed functions in memory.

Syntax

traceback.clear_frames(tb)

A caught exception holds its frames through __traceback__, and the frames hold all their local variables: store e in a list of errors and a huge array from the failed function is never freed. clear_frames(tb) calls frame.clear() on every frame; a frame that is still executing (the current one, say) is silently skipped. The traceback still prints as before — file names and line numbers stay, only the variables go.

Examples

import traceback
def load():
    data = list(range(100_000))
    raise ValueError('сбой')
try:
    load()
except ValueError as e:
    err = e
frame = err.__traceback__.tb_next.tb_frame
print(len(frame.f_locals))  # → 1
traceback.clear_frames(err.__traceback__)
print(len(frame.f_locals))  # → 0
print(len(traceback.extract_tb(err.__traceback__)))  # → 2

See also

Open in the full glossarydocs.python.orgReport an inaccuracy