You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
C API: Implement Py_MIN(), Py_MAX() and Py_ABS() macros using typeof() #157495
Currently, arguments of Py_MIN(), Py_MAX() and Py_ABS() macros are evaluated twice. It's inefficient. We can do better using typeof(). I propose adding a typeof() implementation for these macros.
The current implement (without typeof) is used for C++.
Statement expressions are not allowed in C++. My PR adds explicit tests on Py_MIN() and Py_MAX() in test_cppext: so the macros are tested in C++ with different compiler flags, with and without the limited C API.
typeof() cannot be used on MSVC neither because statement expression is a GNU extension which is only supported by GCC and clang (not by MSVC).
The argument may be evaluated more than once. Consequently, do not pass an expression with side-effects directly to this macro.
min=Py_MIN(var, expensive_func()) should be replaced with result=expensive_func(); min=Py_MIN(var, result) for example.
Since my proposal change is only available on some compilers (GCC and clang, not on MSVC), Python code base should continue to follow the documentation advices.
I didn't check the 221 calls to these macros (git grep -E '(Py_MIN|Py_MAX|Py_ABS)\('|wc -l).
Activity
serhiy-storchaka commentedon Sep 14, 2026
How would it work in C++?
vstinner commentedon Sep 14, 2026
The current implement (without typeof) is used for C++.
Statement expressions are not allowed in C++. My PR adds explicit tests on Py_MIN() and Py_MAX() in test_cppext: so the macros are tested in C++ with different compiler flags, with and without the limited C API.
typeof() cannot be used on MSVC neither because statement expression is a GNU extension which is only supported by GCC and clang (not by MSVC).
skirpichev commentedon Sep 15, 2026
Does it matter for default builds, when optimizations turned on?
vstinner commentedon Sep 15, 2026
The documentation of Py_MIN(), Py_MAX() and Py_ABS() macros says:
min=Py_MIN(var, expensive_func())should be replaced withresult=expensive_func(); min=Py_MIN(var, result)for example.Since my proposal change is only available on some compilers (GCC and clang, not on MSVC), Python code base should continue to follow the documentation advices.
I didn't check the 221 calls to these macros (
git grep -E '(Py_MIN|Py_MAX|Py_ABS)\('|wc -l).pythongh-157495: Avoid Py_MIN()/Py_MAX() side effects
vstinner commentedon Sep 15, 2026
Ok, I checked Py_MIN/MAX/ABS calls in the Python code base and I found a few calls which are inefficient. I wrote this PR gh-157591 to fix them.
gh-157495: Implement Py_MIN/MAX/ABS using typeof() (#157496)
gh-157495: Avoid Py_MIN()/Py_MAX() side effects (#157591)