[Python-Dev] Py_DECREF causes spurious gcc warning

Tim Peters tim.one at comcast.net
Sat Dec 20 14:35:34 EST 2003

[Zack Weinberg]
>>> It does, however, lead to a different problem:
>>>   if (condition)
>>>     Py_DECREF (foo);
>>>   else               // oops, syntax error here

[Martin v. Löwis]
>> How so? This expands to
>> if(condition)
>>   if(cond2)action1;
>>   else action2;
>> else

> No, it expands to
>  if(condition)
>   if(cond2) action1;
>   else action2;;
>  else
> -- note the extra semicolon, which provokes a syntax error.

Zack, which version of Python are you using?  The current definition of
Py_DECREF doesn't end with a semicolon:

#define Py_DECREF(op)                               \
        if (_Py_DEC_REFTOTAL  _Py_REF_DEBUG_COMMA   \
            --(op)->ob_refcnt != 0)                 \
		    _Py_CHECK_REFCNT(op)                \
        else                                        \
                _Py_Dealloc((PyObject *)(op))

The expansion of _Py_CHECK_REFCNT(op) always ends with a semicolon (and may
be nothing but a semicolon, depending on build type), but that's internal to
the stuff Py_DECREF generates, and the leading underscore in
_Py_CHECK_REFCNT's name makes it off-limits (by convention) for direct use
by user-written code (_Py_CHECK_REFCNT is internal to Python's
implementation, and Python internals guarantee to use it correctly).

The expansion of Py_DECREF's else branch never ends with a semicolon, and
Martin's explanation is correct.

Same deal with Py_INCREF, Py_XINCREF, and Py_XDECREF.

As a pragmatic matter, it's very unusual to need to do

    if (whatever)

The functionality is common enough when "whatever" is "op != NULL", but
accomplishing "decref if not NULL" is Py_XDECREF's purpose -- there's no
need to code your own if-block in that case, and it's bad style (because
non-idiomatic) to do so.

More information about the Python-Dev mailing list