Why is there a need to explicitly delete the sys.exc_info() traceback?

前端 未结 2 1880
北恋
北恋 2020-12-31 07:01

I\'ve seen in different code bases and just read on PyMOTW (see the first Note here).

The explanation says that a cycle will be created in case the traceback is assi

2条回答
  •  温柔的废话
    2020-12-31 07:13

    The traceback contains references to all the active frames, which in turn contain references to all the local variables in those various frames -- those references are a big part of the very job of traceback and frame objects, so that's hardly surprising. So, if you add a reference back to the traceback (or fail to remove it promptly having temporarily added it), you inevitably form a big loop of references -- which interferes with garbage collection (and may stop it altogether if any of the objects in the loop belong to classes that overide __del__, the finalizer method).

    Especially in a long-running program, interfering with garbage collection is not the best of idea, because you'll be holding on to memory you don't really need (for longer than necessary, or indefinitely if you've essentially blocked garbage collection on such loops by having them include objects with finalizers).

    So, it's definitely best to get rid of tracebacks as soon as feasible, whether they come from exc_info or not!

提交回复
热议问题