Project:Python/Strict aliasing

From Gentoo Wiki
Jump to:navigation Jump to:search

The Python 2 API had a design bug that caused some of the extensions to not comply with strict aliasing rules. For this reason, many extensions need to be explicitly built with -fno-strict-aliasing when built for Python 2.

When to use it?

To determine whether an extension needs -fno-strict-aliasing, build it with optimization and warnings enabled (-O2 -Wstrict-aliasing or just -O2 -Wall). If you get warnings similar to the following:

CODE Example compiler output
pyalsa/alsaseq.c:3393:3: warning: dereferencing type-punned pointer will break strict-aliasing rules [-Wstrict-aliasing]
   Py_INCREF(&ConstantType);
   ^

then you should add -fno-strict-aliasing to the build. However, usually this applies to Python 2 only (unless the extension code itself is broken).

How to add it?

The following snippet can be used to force -fno-strict-aliasing for Python 2-based implementations.

CODE Enabling -fno-strict-aliasing for Python 2
python_compile() {
    # include CXXFLAGS if C++ code is used
    python_is_python3 || local -x CFLAGS="${CFLAGS} -fno-strict-aliasing"
    distutils-r1_python_compile
}

Further reading

The strict aliasing issue is described in detail in PEP-3123. It explains the issue, its implications and the API changes introduced in Python 3 to solve it.