When to use weak references in Python?

前端 未结 3 1942
迷失自我
迷失自我 2021-01-30 10:56

Can anyone explain usage of weak references?

The documentation doesn\'t explain it precisely, it just says that the GC can destroy the object linked to via a weak refere

3条回答
  •  广开言路
    2021-01-30 11:35

    The typical use for weak references is if A has a reference to B and B has a reference to A. Without a proper cycle-detecting garbage collector, those two objects would never get GC'd even if there are no references to either from the "outside". However if one of the references is "weak", the objects will get properly GC'd.

    However, Python does have a cycle-detecting garbage collector (since 2.0!), so that doesn't count :)

    Another use for weak references is for caches. It's mentioned in the weakref documentation:

    A primary use for weak references is to implement caches or mappings holding large objects, where it’s desired that a large object not be kept alive solely because it appears in a cache or mapping.

    If the GC decides to destroy one of those objects, and you need it, you can just recalculate / refetch the data.

提交回复
热议问题