bidict/docs/inv-avoids-reference-cycles...

32 lines
1.2 KiB
PHP
Raw Normal View History

2017-12-17 18:58:57 +00:00
.. _inv-avoids-reference-cycles:
:attr:`~bidict.BidirectionalMapping.inv` Avoids Reference Cycles
----------------------------------------------------------------
2017-12-17 18:58:57 +00:00
A careful reader might notice the following...
>>> from bidict import bidict
>>> fwd = bidict(one=1)
>>> inv = fwd.inv
>>> inv.inv is fwd
True
...and become concerned that a bidict and its inverse create a reference cycle.
2018-01-17 00:43:39 +00:00
If this were true, in CPython this would mean that the memory for a bidict
2017-12-17 18:58:57 +00:00
could not be immediately reclaimed when you retained no more references to it,
2018-01-17 00:43:39 +00:00
but rather would have to wait for the next gargage collection to kick in
before it could be reclaimed.
2017-12-17 18:58:57 +00:00
However, under the hood bidict uses a :class:`weakref.ref`
2018-01-17 00:43:39 +00:00
to store the inverse reference in one direction,
avoiding the strong reference cycle.
2017-12-17 18:58:57 +00:00
As a result, when you no longer retain any references to a bidict you create,
2018-01-17 00:43:39 +00:00
you can be sure that its refcount in CPython drops to zero,
2017-12-17 18:58:57 +00:00
and that its memory will therefore be reclaimed immediately.
2018-01-17 00:43:39 +00:00
.. note::
In PyPy this is not an issue, as PyPy doesn't use reference counts.
The memory for unreferenced objects in PyPy is only reclaimed
when GC kicks in, which is unpredictable.