summary refs log tree commit diff
path: root/pkgs/development/interpreters/python
diff options
context:
space:
mode:
Diffstat (limited to 'pkgs/development/interpreters/python')
-rw-r--r--pkgs/development/interpreters/python/catch_conflicts/catch_conflicts.py30
-rw-r--r--pkgs/development/interpreters/python/catch_conflicts/catch_conflicts_py2.py30
-rw-r--r--pkgs/development/interpreters/python/cpython/2.7/default.nix17
-rw-r--r--pkgs/development/interpreters/python/cpython/3.13/no-ldconfig.patch107
-rw-r--r--pkgs/development/interpreters/python/cpython/default.nix68
-rw-r--r--pkgs/development/interpreters/python/cpython/platform-triplet-detection.patch295
-rw-r--r--pkgs/development/interpreters/python/default.nix64
-rw-r--r--pkgs/development/interpreters/python/hooks/default.nix48
-rw-r--r--pkgs/development/interpreters/python/hooks/pypa-build-hook-test.nix32
-rw-r--r--pkgs/development/interpreters/python/hooks/pypa-build-hook.sh2
-rw-r--r--pkgs/development/interpreters/python/hooks/sphinx-hook.sh2
-rw-r--r--pkgs/development/interpreters/python/mk-python-derivation.nix13
-rw-r--r--pkgs/development/interpreters/python/passthrufun.nix10
-rw-r--r--pkgs/development/interpreters/python/python-packages-base.nix4
-rw-r--r--pkgs/development/interpreters/python/python2/mk-python-derivation.nix2
-rw-r--r--pkgs/development/interpreters/python/tests.nix11
-rw-r--r--pkgs/development/interpreters/python/wrap-python.nix2
17 files changed, 624 insertions, 113 deletions
diff --git a/pkgs/development/interpreters/python/catch_conflicts/catch_conflicts.py b/pkgs/development/interpreters/python/catch_conflicts/catch_conflicts.py
index bb82900c65a..d5c99e64751 100644
--- a/pkgs/development/interpreters/python/catch_conflicts/catch_conflicts.py
+++ b/pkgs/development/interpreters/python/catch_conflicts/catch_conflicts.py
@@ -1,30 +1,34 @@
-import pkg_resources
+from importlib.metadata import PathDistribution
+from pathlib import Path
 import collections
 import sys
 
+
 do_abort = False
 packages = collections.defaultdict(list)
 
-for f in sys.path:
-    for req in pkg_resources.find_distributions(f):
-        if req not in packages[req.project_name]:
-            # some exceptions inside buildPythonPackage
-            if req.project_name in ['setuptools', 'pip', 'wheel']:
-                continue
-            packages[req.project_name].append(req)
+
+for path in sys.path:
+    for dist_info in Path(path).glob("*.dist-info"):
+        dist = PathDistribution(dist_info)
+
+        packages[dist._normalized_name].append(
+            f"{dist._normalized_name} {dist.version} ({dist._path})"
+        )
 
 
 for name, duplicates in packages.items():
     if len(duplicates) > 1:
         do_abort = True
         print("Found duplicated packages in closure for dependency '{}': ".format(name))
-        for dup in duplicates:
-            print("  " + repr(dup))
+        for duplicate in duplicates:
+            print(f"\t{duplicate}")
 
 if do_abort:
     print("")
     print(
-        'Package duplicates found in closure, see above. Usually this '
-        'happens if two packages depend on different version '
-        'of the same dependency.')
+        "Package duplicates found in closure, see above. Usually this "
+        "happens if two packages depend on different version "
+        "of the same dependency."
+    )
     sys.exit(1)
diff --git a/pkgs/development/interpreters/python/catch_conflicts/catch_conflicts_py2.py b/pkgs/development/interpreters/python/catch_conflicts/catch_conflicts_py2.py
new file mode 100644
index 00000000000..bb82900c65a
--- /dev/null
+++ b/pkgs/development/interpreters/python/catch_conflicts/catch_conflicts_py2.py
@@ -0,0 +1,30 @@
+import pkg_resources
+import collections
+import sys
+
+do_abort = False
+packages = collections.defaultdict(list)
+
+for f in sys.path:
+    for req in pkg_resources.find_distributions(f):
+        if req not in packages[req.project_name]:
+            # some exceptions inside buildPythonPackage
+            if req.project_name in ['setuptools', 'pip', 'wheel']:
+                continue
+            packages[req.project_name].append(req)
+
+
+for name, duplicates in packages.items():
+    if len(duplicates) > 1:
+        do_abort = True
+        print("Found duplicated packages in closure for dependency '{}': ".format(name))
+        for dup in duplicates:
+            print("  " + repr(dup))
+
+if do_abort:
+    print("")
+    print(
+        'Package duplicates found in closure, see above. Usually this '
+        'happens if two packages depend on different version '
+        'of the same dependency.')
+    sys.exit(1)
diff --git a/pkgs/development/interpreters/python/cpython/2.7/default.nix b/pkgs/development/interpreters/python/cpython/2.7/default.nix
index 9cd806c0523..5cdd307e70f 100644
--- a/pkgs/development/interpreters/python/cpython/2.7/default.nix
+++ b/pkgs/development/interpreters/python/cpython/2.7/default.nix
@@ -56,11 +56,11 @@ assert lib.assertMsg (reproducibleBuild -> (!rebuildBytecode))
 
 let
   buildPackages = pkgsBuildHost;
-  inherit (passthru) pythonForBuild;
+  inherit (passthru) pythonOnBuildForHost;
 
-  pythonForBuildInterpreter = if stdenv.hostPlatform == stdenv.buildPlatform then
+  pythonOnBuildForHostInterpreter = if stdenv.hostPlatform == stdenv.buildPlatform then
     "$out/bin/python"
-  else pythonForBuild.interpreter;
+  else pythonOnBuildForHost.interpreter;
 
   passthru = passthruFun rec {
     inherit self sourceVersion packageOverrides;
@@ -133,6 +133,11 @@ let
 
     ] ++ lib.optionals (x11Support && stdenv.isDarwin) [
       ./use-correct-tcl-tk-on-darwin.patch
+
+    ] ++ lib.optionals stdenv.isDarwin [
+      # Fix darwin build https://bugs.python.org/issue34027
+      ../3.7/darwin-libutil.patch
+
     ] ++ lib.optionals stdenv.isLinux [
 
       # Disable the use of ldconfig in ctypes.util.find_library (since
@@ -297,9 +302,9 @@ in with passthru; stdenv.mkDerivation ({
         # We build 3 levels of optimized bytecode. Note the default level, without optimizations,
         # is not reproducible yet. https://bugs.python.org/issue29708
         # Not creating bytecode will result in a large performance loss however, so we do build it.
-        find $out -name "*.py" | ${pythonForBuildInterpreter} -m compileall -q -f -x "lib2to3" -i -
-        find $out -name "*.py" | ${pythonForBuildInterpreter} -O  -m compileall -q -f -x "lib2to3" -i -
-        find $out -name "*.py" | ${pythonForBuildInterpreter} -OO -m compileall -q -f -x "lib2to3" -i -
+        find $out -name "*.py" | ${pythonOnBuildForHostInterpreter} -m compileall -q -f -x "lib2to3" -i -
+        find $out -name "*.py" | ${pythonOnBuildForHostInterpreter} -O  -m compileall -q -f -x "lib2to3" -i -
+        find $out -name "*.py" | ${pythonOnBuildForHostInterpreter} -OO -m compileall -q -f -x "lib2to3" -i -
       '' + lib.optionalString stdenv.hostPlatform.isCygwin ''
         cp libpython2.7.dll.a $out/lib
       '';
diff --git a/pkgs/development/interpreters/python/cpython/3.13/no-ldconfig.patch b/pkgs/development/interpreters/python/cpython/3.13/no-ldconfig.patch
new file mode 100644
index 00000000000..ca6a76d0ffd
--- /dev/null
+++ b/pkgs/development/interpreters/python/cpython/3.13/no-ldconfig.patch
@@ -0,0 +1,107 @@
+From 5330b6af9f832af59aa5c61d9ef6971053a8e709 Mon Sep 17 00:00:00 2001
+From: Jonathan Ringer <jonringer117@gmail.com>
+Date: Mon, 9 Nov 2020 10:24:35 -0800
+Subject: [PATCH] CPython: Don't use ldconfig
+
+---
+ Lib/ctypes/util.py | 77 ++--------------------------------------------
+ 1 file changed, 2 insertions(+), 75 deletions(-)
+
+diff --git a/Lib/ctypes/util.py b/Lib/ctypes/util.py
+index 0c2510e161..7fb98af308 100644
+--- a/Lib/ctypes/util.py
++++ b/Lib/ctypes/util.py
+@@ -100,53 +100,7 @@ def _is_elf(filename):
+             return thefile.read(4) == elf_header
+ 
+     def _findLib_gcc(name):
+-        # Run GCC's linker with the -t (aka --trace) option and examine the
+-        # library name it prints out. The GCC command will fail because we
+-        # haven't supplied a proper program with main(), but that does not
+-        # matter.
+-        expr = os.fsencode(r'[^\(\)\s]*lib%s\.[^\(\)\s]*' % re.escape(name))
+-
+-        c_compiler = shutil.which('gcc')
+-        if not c_compiler:
+-            c_compiler = shutil.which('cc')
+-        if not c_compiler:
+-            # No C compiler available, give up
+-            return None
+-
+-        temp = tempfile.NamedTemporaryFile()
+-        try:
+-            args = [c_compiler, '-Wl,-t', '-o', temp.name, '-l' + name]
+-
+-            env = dict(os.environ)
+-            env['LC_ALL'] = 'C'
+-            env['LANG'] = 'C'
+-            try:
+-                proc = subprocess.Popen(args,
+-                                        stdout=subprocess.PIPE,
+-                                        stderr=subprocess.STDOUT,
+-                                        env=env)
+-            except OSError:  # E.g. bad executable
+-                return None
+-            with proc:
+-                trace = proc.stdout.read()
+-        finally:
+-            try:
+-                temp.close()
+-            except FileNotFoundError:
+-                # Raised if the file was already removed, which is the normal
+-                # behaviour of GCC if linking fails
+-                pass
+-        res = re.findall(expr, trace)
+-        if not res:
+-            return None
+-
+-        for file in res:
+-            # Check if the given file is an elf file: gcc can report
+-            # some files that are linker scripts and not actual
+-            # shared objects. See bpo-41976 for more details
+-            if not _is_elf(file):
+-                continue
+-            return os.fsdecode(file)
++        return None
+ 
+ 
+     if sys.platform == "sunos5":
+@@ -268,34 +222,7 @@ def find_library(name, is64 = False):
+     else:
+ 
+         def _findSoname_ldconfig(name):
+-            import struct
+-            if struct.calcsize('l') == 4:
+-                machine = os.uname().machine + '-32'
+-            else:
+-                machine = os.uname().machine + '-64'
+-            mach_map = {
+-                'x86_64-64': 'libc6,x86-64',
+-                'ppc64-64': 'libc6,64bit',
+-                'sparc64-64': 'libc6,64bit',
+-                's390x-64': 'libc6,64bit',
+-                'ia64-64': 'libc6,IA-64',
+-                }
+-            abi_type = mach_map.get(machine, 'libc6')
+-
+-            # XXX assuming GLIBC's ldconfig (with option -p)
+-            regex = r'\s+(lib%s\.[^\s]+)\s+\(%s'
+-            regex = os.fsencode(regex % (re.escape(name), abi_type))
+-            try:
+-                with subprocess.Popen(['/sbin/ldconfig', '-p'],
+-                                      stdin=subprocess.DEVNULL,
+-                                      stderr=subprocess.DEVNULL,
+-                                      stdout=subprocess.PIPE,
+-                                      env={'LC_ALL': 'C', 'LANG': 'C'}) as p:
+-                    res = re.search(regex, p.stdout.read())
+-                    if res:
+-                        return os.fsdecode(res.group(1))
+-            except OSError:
+-                pass
++            return None
+ 
+         def _findLib_ld(name):
+             # See issue #9998 for why this is needed
+-- 
+2.33.1
+
diff --git a/pkgs/development/interpreters/python/cpython/default.nix b/pkgs/development/interpreters/python/cpython/default.nix
index 6778dc460e0..8bc5c6c586d 100644
--- a/pkgs/development/interpreters/python/cpython/default.nix
+++ b/pkgs/development/interpreters/python/cpython/default.nix
@@ -58,6 +58,7 @@
 , reproducibleBuild ? false
 , pythonAttr ? "python${sourceVersion.major}${sourceVersion.minor}"
 , noldconfigPatch ? ./. + "/${sourceVersion.major}.${sourceVersion.minor}/no-ldconfig.patch"
+, testers
 } @ inputs:
 
 # Note: this package is used for bootstrapping fetchurl, and thus
@@ -91,7 +92,7 @@ let
   openssl' = if openssl != null then openssl_legacy else null;
 
   buildPackages = pkgsBuildHost;
-  inherit (passthru) pythonForBuild;
+  inherit (passthru) pythonOnBuildForHost;
 
   inherit (darwin.apple_sdk.frameworks) Cocoa;
 
@@ -126,7 +127,7 @@ let
     nukeReferences
   ] ++ optionals (stdenv.hostPlatform != stdenv.buildPlatform) [
     buildPackages.stdenv.cc
-    pythonForBuild
+    pythonOnBuildForHost
   ] ++ optionals (stdenv.cc.isClang && (!stdenv.hostPlatform.useAndroidPrebuilt or false) && (enableLTO || enableOptimizations)) [
     stdenv.cc.cc.libllvm.out
   ];
@@ -147,9 +148,9 @@ let
 
   hasDistutilsCxxPatch = !(stdenv.cc.isGNU or false);
 
-  pythonForBuildInterpreter = if stdenv.hostPlatform == stdenv.buildPlatform then
+  pythonOnBuildForHostInterpreter = if stdenv.hostPlatform == stdenv.buildPlatform then
     "$out/bin/python"
-  else pythonForBuild.interpreter;
+  else pythonOnBuildForHost.interpreter;
 
   src = fetchurl {
     url = with sourceVersion; "https://www.python.org/ftp/python/${major}.${minor}.${patch}/Python-${version}.tar.xz";
@@ -195,25 +196,22 @@ let
         if parsed.cpu.significantByte.name == "littleEndian" then "arm" else "armeb"
       else if isx86_32 then "i386"
       else parsed.cpu.name;
-    # Python doesn't distinguish musl and glibc and always prefixes with "gnu"
-    gnuAbiName = replaceStrings [ "musl" ] [ "gnu" ] parsed.abi.name;
-    pythonAbiName =
-      # python's build doesn't support every gnu<extension>, and doesn't
-      # differentiate between musl and glibc, so we list those supported in
-      # here:
+
+    pythonAbiName = let
+      # python's build doesn't match the nixpkgs abi in some cases.
       # https://github.com/python/cpython/blob/e488e300f5c01289c10906c2e53a8e43d6de32d8/configure.ac#L724
-      # Note: this is an approximation, as it doesn't take into account the CPU
-      # family, or the nixpkgs abi naming conventions.
-      if elem gnuAbiName [
-        "gnux32"
-        "gnueabihf"
-        "gnueabi"
-        "gnuabin32"
-        "gnuabi64"
-        "gnuspe"
-      ]
-      then gnuAbiName
-      else "gnu";
+      nixpkgsPythonAbiMappings = {
+        "gnuabielfv2" = "gnu";
+        "muslabielfv2" = "musl";
+      };
+      pythonAbi = nixpkgsPythonAbiMappings.${parsed.abi.name} or parsed.abi.name;
+    in
+      # Python <3.11 doesn't distinguish musl and glibc and always prefixes with "gnu"
+      if lib.versionOlder version "3.11" then
+        replaceStrings [ "musl" ] [ "gnu" ] pythonAbi
+      else
+        pythonAbi;
+
     multiarch =
       if isDarwin then "darwin"
       else if isWindows then ""
@@ -235,7 +233,7 @@ let
   '';
 
   execSuffix = stdenv.hostPlatform.extensions.executable;
-in with passthru; stdenv.mkDerivation {
+in with passthru; stdenv.mkDerivation (finalAttrs: {
   pname = "python3";
   inherit src version;
 
@@ -305,9 +303,12 @@ in with passthru; stdenv.mkDerivation {
     ./3.8/0001-On-all-posix-systems-not-just-Darwin-set-LDSHARED-if.patch
     # Use sysconfigdata to find headers. Fixes cross-compilation of extension modules.
     ./3.7/fix-finding-headers-when-cross-compiling.patch
-  ] ++ optionals stdenv.hostPlatform.isLoongArch64 [
+  ] ++ optionals (pythonOlder "3.12") [
     # https://github.com/python/cpython/issues/90656
     ./loongarch-support.patch
+  ] ++ optionals (pythonAtLeast "3.11" && pythonOlder "3.13") [
+    # backport fix for https://github.com/python/cpython/issues/95855
+    ./platform-triplet-detection.patch
   ] ++ optionals (stdenv.hostPlatform.isMinGW) (let
     # https://src.fedoraproject.org/rpms/mingw-python3
     mingw-patch = fetchgit {
@@ -326,7 +327,7 @@ in with passthru; stdenv.mkDerivation {
   '' + optionalString mimetypesSupport ''
     substituteInPlace Lib/mimetypes.py \
       --replace "@mime-types@" "${mailcap}"
-  '' + optionalString (x11Support && (tix != null)) ''
+  '' + optionalString (pythonOlder "3.13" && x11Support && (tix != null)) ''
     substituteInPlace "Lib/tkinter/tix.py" --replace "os.environ.get('TIX_LIBRARY')" "os.environ.get('TIX_LIBRARY') or '${tix}/lib'"
   '';
 
@@ -387,7 +388,7 @@ in with passthru; stdenv.mkDerivation {
     "ac_cv_file__dev_ptmx=${if stdenv.hostPlatform.isWindows then "no" else "yes"}"
     "ac_cv_file__dev_ptc=${if stdenv.hostPlatform.isWindows then "no" else "yes"}"
   ] ++ optionals (stdenv.hostPlatform != stdenv.buildPlatform && pythonAtLeast "3.11") [
-    "--with-build-python=${pythonForBuildInterpreter}"
+    "--with-build-python=${pythonOnBuildForHostInterpreter}"
   ] ++ optionals stdenv.hostPlatform.isLinux [
     # Never even try to use lchmod on linux,
     # don't rely on detecting glibc-isms.
@@ -510,9 +511,9 @@ in with passthru; stdenv.mkDerivation {
     # We build 3 levels of optimized bytecode. Note the default level, without optimizations,
     # is not reproducible yet. https://bugs.python.org/issue29708
     # Not creating bytecode will result in a large performance loss however, so we do build it.
-    find $out -name "*.py" | ${pythonForBuildInterpreter} -m compileall -q -f -x "lib2to3" -i -
-    find $out -name "*.py" | ${pythonForBuildInterpreter} -O  -m compileall -q -f -x "lib2to3" -i -
-    find $out -name "*.py" | ${pythonForBuildInterpreter} -OO -m compileall -q -f -x "lib2to3" -i -
+    find $out -name "*.py" | ${pythonOnBuildForHostInterpreter} -m compileall -q -f -x "lib2to3" -i -
+    find $out -name "*.py" | ${pythonOnBuildForHostInterpreter} -O  -m compileall -q -f -x "lib2to3" -i -
+    find $out -name "*.py" | ${pythonOnBuildForHostInterpreter} -OO -m compileall -q -f -x "lib2to3" -i -
     '' + ''
     # *strip* shebang from libpython gdb script - it should be dual-syntax and
     # interpretable by whatever python the gdb in question is using, which may
@@ -560,7 +561,7 @@ in with passthru; stdenv.mkDerivation {
     ++ lib.optionals (stdenv.hostPlatform != stdenv.buildPlatform) [
     # Ensure we don't have references to build-time packages.
     # These typically end up in shebangs.
-    pythonForBuild buildPackages.bash
+    pythonOnBuildForHost buildPackages.bash
   ];
 
   separateDebugInfo = true;
@@ -580,8 +581,10 @@ in with passthru; stdenv.mkDerivation {
         mv $out/share/doc/* $out/share/doc/python${pythonVersion}-${version}
       '';
 
-      nativeBuildInputs = with pkgsBuildBuild.python3.pkgs; [ sphinxHook python_docs_theme ];
+      nativeBuildInputs = with pkgsBuildBuild.python3.pkgs; [ sphinxHook python-docs-theme ];
     };
+
+    tests.pkg-config = testers.testMetaPkgConfig finalAttrs.finalPackage;
   };
 
   enableParallelBuilding = true;
@@ -607,8 +610,9 @@ in with passthru; stdenv.mkDerivation {
       high level dynamic data types.
     '';
     license = licenses.psfl;
+    pkgConfigModules = [ "python3" ];
     platforms = platforms.linux ++ platforms.darwin ++ platforms.windows;
     maintainers = with maintainers; [ fridh ];
     mainProgram = executable;
   };
-}
+})
diff --git a/pkgs/development/interpreters/python/cpython/platform-triplet-detection.patch b/pkgs/development/interpreters/python/cpython/platform-triplet-detection.patch
new file mode 100644
index 00000000000..ec76546f54e
--- /dev/null
+++ b/pkgs/development/interpreters/python/cpython/platform-triplet-detection.patch
@@ -0,0 +1,295 @@
+diff --git a/configure.ac b/configure.ac
+index ba768aea93..621ac166bd 100644
+--- a/configure.ac
++++ b/configure.ac
+@@ -936,125 +936,192 @@ cat > conftest.c <<EOF
+ #if defined(__ANDROID__)
+     # Android is not a multiarch system.
+ #elif defined(__linux__)
++# include <features.h>
++# if defined(__UCLIBC__)
++#  error uclibc not supported
++# elif defined(__dietlibc__)
++#  error dietlibc not supported
++# elif defined(__GLIBC__)
++#  define LIBC gnu
++#  define LIBC_X32 gnux32
++#  if defined(__ARM_PCS_VFP)
++#   define LIBC_ARM gnueabihf
++#  else
++#   define LIBC_ARM gnueabi
++#  endif
++#  if defined(__loongarch__)
++#   if defined(__loongarch_soft_float)
++#    define LIBC_LA gnusf
++#   elif defined(__loongarch_single_float)
++#    define LIBC_LA gnuf32
++#   elif defined(__loongarch_double_float)
++#    define LIBC_LA gnu
++#   else
++#    error unknown loongarch floating-point base abi
++#   endif
++#  endif
++#  if defined(_MIPS_SIM)
++#   if defined(__mips_hard_float)
++#    if _MIPS_SIM == _ABIO32
++#     define LIBC_MIPS gnu
++#    elif _MIPS_SIM == _ABIN32
++#     define LIBC_MIPS gnuabin32
++#    elif _MIPS_SIM == _ABI64
++#     define LIBC_MIPS gnuabi64
++#    else
++#     error unknown mips sim value
++#    endif
++#   else
++#    if _MIPS_SIM == _ABIO32
++#     define LIBC_MIPS gnusf
++#    elif _MIPS_SIM == _ABIN32
++#     define LIBC_MIPS gnuabin32sf
++#    elif _MIPS_SIM == _ABI64
++#     define LIBC_MIPS gnuabi64sf
++#    else
++#     error unknown mips sim value
++#    endif
++#   endif
++#  endif
++#  if defined(__SPE__)
++#   define LIBC_PPC gnuspe
++#  else
++#   define LIBC_PPC gnu
++#  endif
++# else
++#  include <stdarg.h>
++#  ifdef __DEFINED_va_list
++#   define LIBC musl
++#   define LIBC_X32 muslx32
++#   if defined(__ARM_PCS_VFP)
++#    define LIBC_ARM musleabihf
++#   else
++#    define LIBC_ARM musleabi
++#   endif
++#   if defined(__loongarch__)
++#    if defined(__loongarch_soft_float)
++#     define LIBC_LA muslsf
++#    elif defined(__loongarch_single_float)
++#     define LIBC_LA muslf32
++#    elif defined(__loongarch_double_float)
++#     define LIBC_LA musl
++#    else
++#     error unknown loongarch floating-point base abi
++#    endif
++#   endif
++#   if defined(_MIPS_SIM)
++#    if defined(__mips_hard_float)
++#     if _MIPS_SIM == _ABIO32
++#      define LIBC_MIPS musl
++#     elif _MIPS_SIM == _ABIN32
++#      define LIBC_MIPS musln32
++#     elif _MIPS_SIM == _ABI64
++#      define LIBC_MIPS musl
++#     else
++#      error unknown mips sim value
++#     endif
++#    else
++#     if _MIPS_SIM == _ABIO32
++#      define LIBC_MIPS muslsf
++#     elif _MIPS_SIM == _ABIN32
++#      define LIBC_MIPS musln32sf
++#     elif _MIPS_SIM == _ABI64
++#      define LIBC_MIPS muslsf
++#     else
++#      error unknown mips sim value
++#     endif
++#    endif
++#   endif
++#   if defined(_SOFT_FLOAT) || defined(__NO_FPRS__)
++#    define LIBC_PPC muslsf
++#   else
++#    define LIBC_PPC musl
++#   endif
++#  else
++#   error unknown libc
++#  endif
++# endif
+ # if defined(__x86_64__) && defined(__LP64__)
+-        x86_64-linux-gnu
++        x86_64-linux-LIBC
+ # elif defined(__x86_64__) && defined(__ILP32__)
+-        x86_64-linux-gnux32
++        x86_64-linux-LIBC_X32
+ # elif defined(__i386__)
+-        i386-linux-gnu
++        i386-linux-LIBC
+ # elif defined(__aarch64__) && defined(__AARCH64EL__)
+ #  if defined(__ILP32__)
+-        aarch64_ilp32-linux-gnu
++        aarch64_ilp32-linux-LIBC
+ #  else
+-        aarch64-linux-gnu
++        aarch64-linux-LIBC
+ #  endif
+ # elif defined(__aarch64__) && defined(__AARCH64EB__)
+ #  if defined(__ILP32__)
+-        aarch64_be_ilp32-linux-gnu
++        aarch64_be_ilp32-linux-LIBC
+ #  else
+-        aarch64_be-linux-gnu
++        aarch64_be-linux-LIBC
+ #  endif
+ # elif defined(__alpha__)
+-        alpha-linux-gnu
+-# elif defined(__ARM_EABI__) && defined(__ARM_PCS_VFP)
++        alpha-linux-LIBC
++# elif defined(__ARM_EABI__)
+ #  if defined(__ARMEL__)
+-        arm-linux-gnueabihf
++        arm-linux-LIBC_ARM
+ #  else
+-        armeb-linux-gnueabihf
+-#  endif
+-# elif defined(__ARM_EABI__) && !defined(__ARM_PCS_VFP)
+-#  if defined(__ARMEL__)
+-        arm-linux-gnueabi
+-#  else
+-        armeb-linux-gnueabi
++        armeb-linux-LIBC_ARM
+ #  endif
+ # elif defined(__hppa__)
+-        hppa-linux-gnu
++        hppa-linux-LIBC
+ # elif defined(__ia64__)
+-        ia64-linux-gnu
+-# elif defined(__loongarch__)
+-#  if defined(__loongarch_lp64)
+-#   if defined(__loongarch_soft_float)
+-        loongarch64-linux-gnusf
+-#   elif defined(__loongarch_single_float)
+-        loongarch64-linux-gnuf32
+-#   elif defined(__loongarch_double_float)
+-        loongarch64-linux-gnu
++        ia64-linux-LIBC
++# elif defined(__loongarch__) && defined(__loongarch_lp64)
++        loongarch64-linux-LIBC_LA
++# elif defined(__m68k__) && !defined(__mcoldfire__)
++        m68k-linux-LIBC
++# elif defined(__mips__)
++#  if defined(__mips_isa_rev) && (__mips_isa_rev >=6)
++#   if defined(_MIPSEL) && defined(__mips64)
++        mipsisa64r6el-linux-LIBC_MIPS
++#   elif defined(_MIPSEL)
++        mipsisa32r6el-linux-LIBC_MIPS
++#   elif defined(__mips64)
++        mipsisa64r6-linux-LIBC_MIPS
+ #   else
+-#    error unknown platform triplet
++        mipsisa32r6-linux-LIBC_MIPS
+ #   endif
+ #  else
+-#   error unknown platform triplet
+-#  endif
+-# elif defined(__m68k__) && !defined(__mcoldfire__)
+-        m68k-linux-gnu
+-# elif defined(__mips_hard_float) && defined(__mips_isa_rev) && (__mips_isa_rev >=6) && defined(_MIPSEL)
+-#  if _MIPS_SIM == _ABIO32
+-        mipsisa32r6el-linux-gnu
+-#  elif _MIPS_SIM == _ABIN32
+-        mipsisa64r6el-linux-gnuabin32
+-#  elif _MIPS_SIM == _ABI64
+-        mipsisa64r6el-linux-gnuabi64
+-#  else
+-#   error unknown platform triplet
+-#  endif
+-# elif defined(__mips_hard_float) && defined(__mips_isa_rev) && (__mips_isa_rev >=6)
+-#  if _MIPS_SIM == _ABIO32
+-        mipsisa32r6-linux-gnu
+-#  elif _MIPS_SIM == _ABIN32
+-        mipsisa64r6-linux-gnuabin32
+-#  elif _MIPS_SIM == _ABI64
+-        mipsisa64r6-linux-gnuabi64
+-#  else
+-#   error unknown platform triplet
+-#  endif
+-# elif defined(__mips_hard_float) && defined(_MIPSEL)
+-#  if _MIPS_SIM == _ABIO32
+-        mipsel-linux-gnu
+-#  elif _MIPS_SIM == _ABIN32
+-        mips64el-linux-gnuabin32
+-#  elif _MIPS_SIM == _ABI64
+-        mips64el-linux-gnuabi64
+-#  else
+-#   error unknown platform triplet
+-#  endif
+-# elif defined(__mips_hard_float)
+-#  if _MIPS_SIM == _ABIO32
+-        mips-linux-gnu
+-#  elif _MIPS_SIM == _ABIN32
+-        mips64-linux-gnuabin32
+-#  elif _MIPS_SIM == _ABI64
+-        mips64-linux-gnuabi64
+-#  else
+-#   error unknown platform triplet
++#   if defined(_MIPSEL) && defined(__mips64)
++        mips64el-linux-LIBC_MIPS
++#   elif defined(_MIPSEL)
++        mipsel-linux-LIBC_MIPS
++#   elif defined(__mips64)
++        mips64-linux-LIBC_MIPS
++#   else
++        mips-linux-LIBC_MIPS
++#   endif
+ #  endif
+ # elif defined(__or1k__)
+-        or1k-linux-gnu
+-# elif defined(__powerpc__) && defined(__SPE__)
+-        powerpc-linux-gnuspe
++        or1k-linux-LIBC
+ # elif defined(__powerpc64__)
+ #  if defined(__LITTLE_ENDIAN__)
+-        powerpc64le-linux-gnu
++        powerpc64le-linux-LIBC
+ #  else
+-        powerpc64-linux-gnu
++        powerpc64-linux-LIBC
+ #  endif
+ # elif defined(__powerpc__)
+-        powerpc-linux-gnu
++        powerpc-linux-LIBC_PPC
+ # elif defined(__s390x__)
+-        s390x-linux-gnu
++        s390x-linux-LIBC
+ # elif defined(__s390__)
+-        s390-linux-gnu
++        s390-linux-LIBC
+ # elif defined(__sh__) && defined(__LITTLE_ENDIAN__)
+-        sh4-linux-gnu
++        sh4-linux-LIBC
+ # elif defined(__sparc__) && defined(__arch64__)
+-        sparc64-linux-gnu
++        sparc64-linux-LIBC
+ # elif defined(__sparc__)
+-        sparc-linux-gnu
++        sparc-linux-LIBC
+ # elif defined(__riscv)
+ #  if __riscv_xlen == 32
+-        riscv32-linux-gnu
++        riscv32-linux-LIBC
+ #  elif __riscv_xlen == 64
+-        riscv64-linux-gnu
++        riscv64-linux-LIBC
+ #  else
+ #   error unknown platform triplet
+ #  endif
+@@ -1102,12 +1169,7 @@ cat > conftest.c <<EOF
+ EOF
+ 
+ if $CPP $CPPFLAGS conftest.c >conftest.out 2>/dev/null; then
+-  PLATFORM_TRIPLET=`grep -v '^#' conftest.out | grep -v '^ *$' | tr -d ' 	'`
+-  case "$build_os" in
+-  linux-musl*)
+-    PLATFORM_TRIPLET=`echo "$PLATFORM_TRIPLET" | sed 's/linux-gnu/linux-musl/'`
+-    ;;
+-  esac
++  PLATFORM_TRIPLET=`grep -v '^#' conftest.out | grep -v '^ *$' | grep -v typedef | tr -d ' 	'`
+   AC_MSG_RESULT([$PLATFORM_TRIPLET])
+ else
+   AC_MSG_RESULT([none])
diff --git a/pkgs/development/interpreters/python/default.nix b/pkgs/development/interpreters/python/default.nix
index 902015ecfb6..8f775699f48 100644
--- a/pkgs/development/interpreters/python/default.nix
+++ b/pkgs/development/interpreters/python/default.nix
@@ -20,20 +20,20 @@
       sourceVersion = {
         major = "3";
         minor = "10";
-        patch = "12";
+        patch = "13";
         suffix = "";
       };
-      hash = "sha256-r7dL8ZEw56R9EDEsj154TyTgUnmB6raOIFRs+4ZYMLg=";
+      hash = "sha256-XIiEhmhkDT4VKzW0U27xwjsspL0slX7x7LsFP1cd0/Y=";
     };
 
     python311 = {
       sourceVersion = {
         major = "3";
         minor = "11";
-        patch = "4";
+        patch = "6";
         suffix = "";
       };
-      hash = "sha256-Lw5AnfKrV6qfxMvd+5dq9E5OVb9vYZ7ua8XCKXJkp/Y=";
+      hash = "sha256-D6t4+n8TP084IQxiYNkNfA1ccZhEZBnOBX7HrC5vXzg=";
     };
   };
 
@@ -96,13 +96,25 @@ in {
       major = "3";
       minor = "12";
       patch = "0";
-      suffix = "rc3";
+      suffix = "";
     };
-    hash = "sha256-ljl+iR6YgCsdOZ3uPOrrm88KolZsinsczk0BlsJ3UGo=";
+    hash = "sha256-eVw09E30Wg6blxDIxxwVxnGHFSTNQSyhTe8hLozLFV0=";
     inherit (darwin) configd;
     inherit passthruFun;
   };
 
+  python313 = callPackage ./cpython {
+    self = __splicedPackages.python313;
+    sourceVersion = {
+      major = "3";
+      minor = "13";
+      patch = "0";
+      suffix = "a1";
+    };
+    hash = "sha256-8Cgb8izABBQ2HBT8kZcYPn6y6rtylla2lEIiT7tj7ss=";
+    inherit (darwin) configd;
+    inherit passthruFun;
+  };
   # Minimal versions of Python (built without optional dependencies)
   python3Minimal = (callPackage ./cpython ({
     self = __splicedPackages.python3Minimal;
@@ -127,7 +139,7 @@ in {
     enableOptimizations = false;
     enableLTO = false;
     mimetypesSupport = false;
-  } // sources.python310)).overrideAttrs(old: {
+  } // sources.python311)).overrideAttrs(old: {
     # TODO(@Artturin): Add this to the main cpython expr
     strictDeps = true;
     pname = "python3-minimal";
@@ -138,10 +150,10 @@ in {
     sourceVersion = {
       major = "7";
       minor = "3";
-      patch = "11";
+      patch = "12";
     };
 
-    hash = "sha256-ERevtmgx2k6m852NIIR4enRon9AineC+MB+e2bJVCTw=";
+    hash = "sha256-3WHYjaJ0ws4s7HdmfUo9+aZSvMUOJvkJkdTdCvZrzPQ=";
     pythonVersion = "2.7";
     db = db.override { dbmSupport = !stdenv.isDarwin; };
     python = __splicedPackages.pythonInterpreters.pypy27_prebuilt;
@@ -155,10 +167,10 @@ in {
     sourceVersion = {
       major = "7";
       minor = "3";
-      patch = "11";
+      patch = "12";
     };
 
-    hash = "sha256-sPMWb7Klqt/VzrnbXN1feSmg7MygK0omwNrgSS98qOo=";
+    hash = "sha256-56IEbH5sJfw4aru1Ey6Sp8wkkeOTVpmpRstdy7NCwqo=";
     pythonVersion = "3.9";
     db = db.override { dbmSupport = !stdenv.isDarwin; };
     python = __splicedPackages.pypy27;
@@ -167,28 +179,26 @@ in {
     inherit (darwin.apple_sdk.frameworks) Security;
   };
 
-  pypy38 = __splicedPackages.pypy39.override {
-    self = __splicedPackages.pythonInterpreters.pypy38;
-    pythonVersion = "3.8";
-    hash = "sha256-TWdpv8pzc06GZv1wUDt86wam4lkRDmFzMbs4mcpOYFg=";
+  pypy310 = __splicedPackages.pypy39.override {
+    self = __splicedPackages.pythonInterpreters.pypy310;
+    pythonVersion = "3.10";
+    hash = "sha256-huTk6sw2BGxhgvQwGHllN/4zpg4dKizGuOf5Gl3LPkI=";
   };
 
-  pypy37 = throw "pypy37 has been removed from nixpkgs since it is no longer supported upstream"; # Added 2023-01-04
-
   pypy27_prebuilt = callPackage ./pypy/prebuilt_2_7.nix {
     # Not included at top-level
     self = __splicedPackages.pythonInterpreters.pypy27_prebuilt;
     sourceVersion = {
       major = "7";
       minor = "3";
-      patch = "11";
+      patch = "12";
     };
 
     hash = {
-      aarch64-linux = "sha256-6pJNod7+kyXvdg4oiwT5hGFOQFWA9TIetqXI9Tm9QVo=";
-      x86_64-linux = "sha256-uo7ZWKkFwHNaTP/yh1wlCJlU3AIOCH2YKw/6W52jFs0=";
-      aarch64-darwin = "sha256-zFaWq0+TzTSBweSZC13t17pgrAYC+hiQ02iImmxb93E=";
-      x86_64-darwin = "sha256-Vt7unCJkD1aGw1udZP2xzjq9BEWD5AePCxccov0qGY4=";
+      aarch64-linux = "sha256-4E3LYoantHJOw/DlDTzBuoWDMB3RZYwG1/N1meQgHFk=";
+      x86_64-linux = "sha256-GmGiV0t5Rm9gYBDymZormVvZbNCF+Rp46909XCxA6B0=";
+      aarch64-darwin = "sha256-a3R6oHauhZfklgPF3sTKWTWhoKEy10BKVZvpaiYNm/c=";
+      x86_64-darwin = "sha256-bon/3RVTfOT/zjFFtl7lfC6clSiSvZW5NAEtLwCfUDs=";
     }.${stdenv.system};
     pythonVersion = "2.7";
     inherit passthruFun;
@@ -200,13 +210,13 @@ in {
     sourceVersion = {
       major = "7";
       minor = "3";
-      patch = "11";
+      patch = "12";
     };
     hash = {
-      aarch64-linux = "sha256-CRddxlLtiV2Y6a1j0haBK/PufjmNkAqb+espBrqDArk=";
-      x86_64-linux = "sha256-1QYXLKEQcSdBdddOnFgcMWZDLQF5sDZHDjuejSDq5YE=";
-      aarch64-darwin = "sha256-ka11APGjlTHb76CzRaPc/5J/+ZcWVOjS6e98WuMR9X4=";
-      x86_64-darwin = "sha256-0z9AsgcJmHJYWv1xhzV1ym6mOKJ9gjvGISOMWuglQu0=";
+      aarch64-linux = "sha256-6TJ/ue2vKtkZNdW4Vj7F/yQZO92xdcGsqvdywCWvGCQ=";
+      x86_64-linux = "sha256-hMiblm+rK1j0UaSC7jDKf+wzUENb0LlhRhXGHcbaI5A=";
+      aarch64-darwin = "sha256-DooaNGi5eQxzSsaY9bAMwD/BaJnMxs6HZGX6wLg5gOM=";
+      x86_64-darwin = "sha256-ZPAI/6BwxAfl70bIJWsuAU3nGW6l2Fg4WGElTnlZ9Os=";
     }.${stdenv.system};
     pythonVersion = "3.9";
     inherit passthruFun;
diff --git a/pkgs/development/interpreters/python/hooks/default.nix b/pkgs/development/interpreters/python/hooks/default.nix
index 700276e77af..0a4600b9d6c 100644
--- a/pkgs/development/interpreters/python/hooks/default.nix
+++ b/pkgs/development/interpreters/python/hooks/default.nix
@@ -1,8 +1,8 @@
 self: dontUse: with self;
 
 let
-  inherit (python) pythonForBuild;
-  pythonInterpreter = pythonForBuild.interpreter;
+  inherit (python) pythonOnBuildForHost;
+  pythonInterpreter = pythonOnBuildForHost.interpreter;
   pythonSitePackages = python.sitePackages;
   pythonCheckInterpreter = python.interpreter;
   setuppy = ../run_setup.py;
@@ -57,9 +57,21 @@ in {
   pypaBuildHook = callPackage ({ makePythonHook, build, wheel }:
     makePythonHook {
       name = "pypa-build-hook.sh";
-      propagatedBuildInputs = [ build wheel ];
+      propagatedBuildInputs = [ wheel ];
+      substitutions = {
+        inherit build;
+      };
+      # A test to ensure that this hook never propagates any of its dependencies
+      #   into the build environment.
+      # This prevents false positive alerts raised by catchConflictsHook.
+      # Such conflicts don't happen within the standard nixpkgs python package
+      #   set, but in downstream projects that build packages depending on other
+      #   versions of this hook's dependencies.
+      passthru.tests = import ./pypa-build-hook-tests.nix {
+        inherit pythonOnBuildForHost runCommand;
+      };
     } ./pypa-build-hook.sh) {
-      inherit (pythonForBuild.pkgs) build;
+      inherit (pythonOnBuildForHost.pkgs) build;
     };
 
   pipInstallHook = callPackage ({ makePythonHook, pip }:
@@ -79,7 +91,7 @@ in {
         inherit pythonInterpreter pythonSitePackages;
       };
     } ./pypa-install-hook.sh) {
-      inherit (pythonForBuild.pkgs) installer;
+      inherit (pythonOnBuildForHost.pkgs) installer;
     };
 
   pytestCheckHook = callPackage ({ makePythonHook, pytest }:
@@ -94,9 +106,16 @@ in {
   pythonCatchConflictsHook = callPackage ({ makePythonHook, setuptools }:
     makePythonHook {
       name = "python-catch-conflicts-hook";
-      substitutions = {
-        inherit pythonInterpreter pythonSitePackages setuptools;
-        catchConflicts=../catch_conflicts/catch_conflicts.py;
+      substitutions = let
+        useLegacyHook = lib.versionOlder python.version "3.10";
+      in {
+        inherit pythonInterpreter pythonSitePackages;
+        catchConflicts = if useLegacyHook then
+          ../catch_conflicts/catch_conflicts_py2.py
+        else
+          ../catch_conflicts/catch_conflicts.py;
+      } // lib.optionalAttrs useLegacyHook {
+        inherit setuptools;
       };
     } ./python-catch-conflicts-hook.sh) {};
 
@@ -171,16 +190,14 @@ in {
       };
     } ./setuptools-check-hook.sh) {};
 
-    setuptoolsRustBuildHook = callPackage ({ makePythonHook, setuptools-rust, rust }:
+    setuptoolsRustBuildHook = callPackage ({ makePythonHook, setuptools-rust }:
       makePythonHook {
         name = "setuptools-rust-setup-hook";
         propagatedBuildInputs = [ setuptools-rust ];
         substitutions = {
           pyLibDir = "${python}/lib/${python.libPrefix}";
-          cargoBuildTarget = rust.toRustTargetSpec stdenv.hostPlatform;
-          cargoLinkerVar = lib.toUpper (
-              builtins.replaceStrings ["-"] ["_"] (
-                rust.toRustTarget stdenv.hostPlatform));
+          cargoBuildTarget = stdenv.hostPlatform.rust.rustcTargetSpec;
+          cargoLinkerVar = stdenv.hostPlatform.rust.cargoEnvVarTarget;
           targetLinker = "${stdenv.cc}/bin/${stdenv.cc.targetPrefix}cc";
         };
       } ./setuptools-rust-hook.sh) {};
@@ -215,6 +232,9 @@ in {
   sphinxHook = callPackage ({ makePythonHook, installShellFiles }:
     makePythonHook {
       name = "python${python.pythonVersion}-sphinx-hook";
-      propagatedBuildInputs = [ pythonForBuild.pkgs.sphinx installShellFiles ];
+      propagatedBuildInputs = [ pythonOnBuildForHost.pkgs.sphinx installShellFiles ];
+      substitutions = {
+        sphinxBuild = "${pythonOnBuildForHost.pkgs.sphinx}/bin/sphinx-build";
+      };
     } ./sphinx-hook.sh) {};
 }
diff --git a/pkgs/development/interpreters/python/hooks/pypa-build-hook-test.nix b/pkgs/development/interpreters/python/hooks/pypa-build-hook-test.nix
new file mode 100644
index 00000000000..4153c21ca4f
--- /dev/null
+++ b/pkgs/development/interpreters/python/hooks/pypa-build-hook-test.nix
@@ -0,0 +1,32 @@
+{ pythonOnBuildForHost, runCommand }: {
+  dont-propagate-conflicting-deps = let
+    # customize a package so that its store paths differs
+    mkConflict = pkg: pkg.overrideAttrs { some_modification = true; };
+    # minimal pyproject.toml for the example project
+    pyprojectToml = builtins.toFile "pyproject.toml" ''
+      [project]
+      name = "my-project"
+      version = "1.0.0"
+    '';
+    # the source of the example project
+    projectSource = runCommand "my-project-source" {} ''
+      mkdir -p $out/src
+      cp ${pyprojectToml} $out/pyproject.toml
+      touch $out/src/__init__.py
+    '';
+    in
+    # this build must never triger conflicts
+    pythonOnBuildForHost.pkgs.buildPythonPackage {
+      pname = "dont-propagate-conflicting-deps";
+      version = "0.0.0";
+      src = projectSource;
+      format = "pyproject";
+      propagatedBuildInputs = [
+        # At least one dependency of `build` should be included here to
+        # keep the test meaningful
+        (mkConflict pythonOnBuildForHost.pkgs.tomli)
+        # setuptools is also needed to build the example project
+        pythonOnBuildForHost.pkgs.setuptools
+      ];
+    };
+}
diff --git a/pkgs/development/interpreters/python/hooks/pypa-build-hook.sh b/pkgs/development/interpreters/python/hooks/pypa-build-hook.sh
index 5d77613bf56..dd49d935bce 100644
--- a/pkgs/development/interpreters/python/hooks/pypa-build-hook.sh
+++ b/pkgs/development/interpreters/python/hooks/pypa-build-hook.sh
@@ -6,7 +6,7 @@ pypaBuildPhase() {
     runHook preBuild
 
     echo "Creating a wheel..."
-    pyproject-build --no-isolation --outdir dist/ --wheel $pypaBuildFlags
+    @build@/bin/pyproject-build --no-isolation --outdir dist/ --wheel $pypaBuildFlags
     echo "Finished creating a wheel..."
 
     runHook postBuild
diff --git a/pkgs/development/interpreters/python/hooks/sphinx-hook.sh b/pkgs/development/interpreters/python/hooks/sphinx-hook.sh
index ca67fa9beab..0307e83d947 100644
--- a/pkgs/development/interpreters/python/hooks/sphinx-hook.sh
+++ b/pkgs/development/interpreters/python/hooks/sphinx-hook.sh
@@ -38,7 +38,7 @@ buildSphinxPhase() {
 
     for __builder in "${__sphinxBuilders[@]}"; do
         echo "Executing sphinx-build with ${__builder} builder"
-        sphinx-build -M "${__builder}" "${__sphinxRoot}" ".sphinx/${__builder}" -v
+        @sphinxBuild@ -M "${__builder}" "${__sphinxRoot}" ".sphinx/${__builder}" -v
     done
 
     runHook postBuildSphinx
diff --git a/pkgs/development/interpreters/python/mk-python-derivation.nix b/pkgs/development/interpreters/python/mk-python-derivation.nix
index fbacf6bb233..c14c6bc096f 100644
--- a/pkgs/development/interpreters/python/mk-python-derivation.nix
+++ b/pkgs/development/interpreters/python/mk-python-derivation.nix
@@ -102,13 +102,14 @@
 
 , disabledTestPaths ? []
 
+# Allow passing in a custom stdenv to buildPython*
+, stdenv ? python.stdenv
+
 , ... } @ attrs:
 
 assert (pyproject != null) -> (format == null);
 
 let
-  inherit (python) stdenv;
-
   format' =
     if pyproject != null then
       if pyproject then
@@ -194,7 +195,7 @@ let
   # Keep extra attributes from `attrs`, e.g., `patchPhase', etc.
   self = toPythonModule (stdenv.mkDerivation ((builtins.removeAttrs attrs [
     "disabled" "checkPhase" "checkInputs" "nativeCheckInputs" "doCheck" "doInstallCheck" "dontWrapPythonPrograms" "catchConflicts" "pyproject" "format"
-    "disabledTestPaths" "outputs"
+    "disabledTestPaths" "outputs" "stdenv"
   ]) // {
 
     name = namePrefix + name_;
@@ -223,7 +224,7 @@ let
     ] ++ lib.optionals (format' == "pyproject") [(
       if isBootstrapPackage then
         pypaBuildHook.override {
-          inherit (python.pythonForBuild.pkgs.bootstrap) build;
+          inherit (python.pythonOnBuildForHost.pkgs.bootstrap) build;
           wheel = null;
         }
       else
@@ -235,7 +236,7 @@ let
     ] ++ lib.optionals (format' != "other") [(
       if isBootstrapInstallPackage then
         pypaInstallHook.override {
-          inherit (python.pythonForBuild.pkgs.bootstrap) installer;
+          inherit (python.pythonOnBuildForHost.pkgs.bootstrap) installer;
         }
       else
         pypaInstallHook
@@ -279,7 +280,7 @@ let
     '' + attrs.postFixup or "";
 
     # Python packages built through cross-compilation are always for the host platform.
-    disallowedReferences = lib.optionals (python.stdenv.hostPlatform != python.stdenv.buildPlatform) [ python.pythonForBuild ];
+    disallowedReferences = lib.optionals (python.stdenv.hostPlatform != python.stdenv.buildPlatform) [ python.pythonOnBuildForHost ];
 
     outputs = outputs ++ lib.optional withDistOutput "dist";
 
diff --git a/pkgs/development/interpreters/python/passthrufun.nix b/pkgs/development/interpreters/python/passthrufun.nix
index 867027e3841..b06433113b6 100644
--- a/pkgs/development/interpreters/python/passthrufun.nix
+++ b/pkgs/development/interpreters/python/passthrufun.nix
@@ -67,6 +67,8 @@
       overrides = packageOverrides;
       python = self;
     });
+  pythonOnBuildForHost_overridden =
+    pythonOnBuildForHost.override { inherit packageOverrides; self = pythonOnBuildForHost_overridden; };
 in rec {
     isPy27 = pythonVersion == "2.7";
     isPy37 = pythonVersion == "3.7";
@@ -89,9 +91,11 @@ in rec {
     pythonAtLeast = lib.versionAtLeast pythonVersion;
     pythonOlder = lib.versionOlder pythonVersion;
     inherit hasDistutilsCxxPatch;
-    # TODO: rename to pythonOnBuild
-    # Not done immediately because its likely used outside Nixpkgs.
-    pythonForBuild = pythonOnBuildForHost.override { inherit packageOverrides; self = pythonForBuild; };
+    # Remove after 24.11 is released.
+    pythonForBuild =
+      lib.warnIf (lib.isInOldestRelease 2311) "`pythonForBuild` (from `python*`) has been renamed to `pythonOnBuildForHost`"
+        pythonOnBuildForHost_overridden;
+    pythonOnBuildForHost = pythonOnBuildForHost_overridden;
 
     tests = callPackage ./tests.nix {
       python = self;
diff --git a/pkgs/development/interpreters/python/python-packages-base.nix b/pkgs/development/interpreters/python/python-packages-base.nix
index 91ca84b34b8..b5afaf34ce6 100644
--- a/pkgs/development/interpreters/python/python-packages-base.nix
+++ b/pkgs/development/interpreters/python/python-packages-base.nix
@@ -13,7 +13,7 @@ let
 
   # Derivations built with `buildPythonPackage` can already be overridden with `override`, `overrideAttrs`, and `overrideDerivation`.
   # This function introduces `overridePythonAttrs` and it overrides the call to `buildPythonPackage`.
-  makeOverridablePythonPackage = f: origArgs:
+  makeOverridablePythonPackage = f: lib.mirrorFunctionArgs f (origArgs:
     let
       args = lib.fix (lib.extends
         (_: previousAttrs: {
@@ -30,7 +30,7 @@ let
         overridePythonAttrs = newArgs: makeOverridablePythonPackage f (overrideWith newArgs);
         __functor = self: result;
       }
-      else result;
+      else result);
 
   mkPythonDerivation = if python.isPy3k then
     ./mk-python-derivation.nix
diff --git a/pkgs/development/interpreters/python/python2/mk-python-derivation.nix b/pkgs/development/interpreters/python/python2/mk-python-derivation.nix
index d42e4e85c10..1a6f9c784cf 100644
--- a/pkgs/development/interpreters/python/python2/mk-python-derivation.nix
+++ b/pkgs/development/interpreters/python/python2/mk-python-derivation.nix
@@ -224,7 +224,7 @@ let
     '' + attrs.postFixup or "";
 
     # Python packages built through cross-compilation are always for the host platform.
-    disallowedReferences = lib.optionals (python.stdenv.hostPlatform != python.stdenv.buildPlatform) [ python.pythonForBuild ];
+    disallowedReferences = lib.optionals (python.stdenv.hostPlatform != python.stdenv.buildPlatform) [ python.pythonOnBuildForHost ];
 
     outputs = outputs ++ lib.optional withDistOutput "dist";
 
diff --git a/pkgs/development/interpreters/python/tests.nix b/pkgs/development/interpreters/python/tests.nix
index d2bab1b0c8d..67670ceb654 100644
--- a/pkgs/development/interpreters/python/tests.nix
+++ b/pkgs/development/interpreters/python/tests.nix
@@ -8,7 +8,6 @@
 { stdenv
 , python
 , runCommand
-, substituteAll
 , lib
 , callPackage
 , pkgs
@@ -60,7 +59,7 @@ let
         is_nixenv = "True";
         is_virtualenv = "False";
       };
-    } // lib.optionalAttrs (python.isPy3k && (!python.isPyPy)) rec {
+    } // lib.optionalAttrs (python.isPy3k && (!python.isPyPy)) {
       # Venv built using plain Python
       # Python 2 does not support venv
       # TODO: PyPy executable name is incorrect, it should be pypy-c or pypy-3c instead of pypy and pypy3.
@@ -109,7 +108,7 @@ let
       cpython-gdb = callPackage ./tests/test_cpython_gdb {
         interpreter = python;
       };
-    } // lib.optionalAttrs (python.pythonAtLeast "3.7") rec {
+    } // lib.optionalAttrs (python.pythonAtLeast "3.7") {
       # Before the addition of NIX_PYTHONPREFIX mypy was broken with typed packages
       nix-pythonprefix-mypy = callPackage ./tests/test_nix_pythonprefix {
         interpreter = python;
@@ -126,7 +125,7 @@ let
     extension = self: super: {
       foobar = super.numpy;
     };
-  in {
+  in lib.optionalAttrs (python.isPy3k) ({
     test-packageOverrides = let
       myPython = let
         self = python.override {
@@ -150,7 +149,7 @@ let
         ];
       });
     in pkgs_.${python.pythonAttr}.pkgs.foo;
-  };
+  });
 
   condaTests = let
     requests = callPackage ({
@@ -178,7 +177,7 @@ let
       }
     ) {};
     pythonWithRequests = requests.pythonModule.withPackages (ps: [ requests ]);
-    in lib.optionalAttrs stdenv.isLinux
+    in lib.optionalAttrs (python.isPy3k && stdenv.isLinux)
     {
       condaExamplePackage = runCommand "import-requests" {} ''
         ${pythonWithRequests.interpreter} -c "import requests" > $out
diff --git a/pkgs/development/interpreters/python/wrap-python.nix b/pkgs/development/interpreters/python/wrap-python.nix
index c67a8e08851..8817d091a28 100644
--- a/pkgs/development/interpreters/python/wrap-python.nix
+++ b/pkgs/development/interpreters/python/wrap-python.nix
@@ -8,7 +8,7 @@ makePythonHook {
       propagatedBuildInputs = [ makeWrapper ];
       substitutions.sitePackages = python.sitePackages;
       substitutions.executable = python.interpreter;
-      substitutions.python = python.pythonForBuild;
+      substitutions.python = python.pythonOnBuildForHost;
       substitutions.pythonHost = python;
       substitutions.magicalSedExpression = let
         # Looks weird? Of course, it's between single quoted shell strings.