Why PyINCREF on _PyFalseStruct and _PyTrueStruct?

Ian Kelly ian.g.kelly at gmail.com
Wed Apr 8 11:24:46 EDT 2015


On Wed, Apr 8, 2015 at 9:07 AM, Shiyao Ma <i at introo.me> wrote:
> Hi.
>
> While reading the rich_compare of PyLongObject, I noticed this line:
>
> https://hg.python.org/cpython/file/a49737bd6086/Objects/longobject.c#l2785
>
> It increments the ob_ref of the builtin True/False object.
>
> Initializing the ob_ref of True/False to one so that they won't be
> garbage collected if fair enough. Why do we increment it?
>
> I don't see the reason behind it, since these two objects should
> always stay in the memory and never participate the garbage collecting
> system.

The ref count is incremented because the caller will decrement it when
it's done with the reference. The ref counter doesn't do any check to
see what the object is before freeing it; it just frees it if the
count hits 0. I believe that for objects like True/False, CPython
avoids getting a 0 ref count by adding one increment at creation that
will never be decremented. If it were possible to hit a decrement
without a corresponding increment though, then the count could reach 0
and the object would be freed anyway.



More information about the Python-list mailing list