From 4de56711f57e3c85f36b52b10231ad9538bc9a1d Mon Sep 17 00:00:00 2001
From: nrnhines <michael.hines@yale.edu>
Date: Mon, 24 Mar 2025 08:42:14 -0400
Subject: [PATCH] release/8.2 can use Python 3.13 (#3352)

At starting point, jelic/8.2-py313 #3319 had only two CI failures.

Almost the entirety of this PR is to get 8.2 to pass CI.
In addition it supports Python3.13.
Bug fixes adopted from the master are
#3239 Launching nrniv -python with Python 3.13.0 does not allow use of gui.
#3259 On h.quit() terminal settings are same as when neuron.hoc was imported.
#3243 save stdin terminal settings on import hoc and restore on h.quit()
#3276 Python 3.13.1 broke [s for s in sl] where sl is a SectionList. Manual partial cherry-pick.

Other PR attempts at fixing CI failures that can be closed when this PR is merged, are #3329 #3325 #3319 #3317

Many of the CI fixes are backports from #3028 #3040 #3303 #3105 #3278

bldnrnmacpkgcmake.sh was updated. It isolates a change (avoid breaking CI) with -DNRN_MAC_PKG=ON
---------

Co-authored-by: Goran Jelic-Cizmek <goran.jelic-cizmek@epfl.ch>
---
 .circleci/config.yml                          |  6 ++-
 .github/workflows/coverage.yml                |  4 +-
 .github/workflows/neuron-ci.yml               | 13 +++---
 .readthedocs.yml                              | 27 ++++++++++--
 azure-pipelines.yml                           | 17 ++++++-
 bldnrnmacpkgcmake.sh                          | 25 +++++++----
 ci/azure-win-installer-upload.yml             |  2 +-
 ci/win_build_cmake.sh                         |  9 ++--
 ci/win_download_deps.cmd                      |  3 +-
 ci/win_install_deps.cmd                       | 27 +++++-------
 ci/win_test_installer.cmd                     | 20 +++++++--
 ci/win_test_installer_wo_rxd.cmd              |  5 +--
 docs/changelog.md                             |  5 +++
 docs/conda_environment.yml                    |  2 +-
 docs/conf.py                                  | 40 ++++++++++++-----
 docs/docs_requirements.txt                    |  5 ++-
 docs/domains/hocdomain.py                     |  1 -
 docs/index.rst                                |  2 +-
 docs/install/install_instructions.md          |  2 +-
 docs/install/mac_pkg.md                       |  2 +-
 docs/parse_rst.py                             |  1 -
 nrn_requirements.txt                          |  4 +-
 packaging/python/build_requirements.txt       |  2 +-
 packaging/python/build_wheels.bash            | 11 ++---
 .../python/oldest_numpy_requirements.txt      |  8 ++++
 packaging/python/test_requirements.txt        |  2 +
 packaging/python/test_wheels.sh               | 21 ++++++---
 setup.py                                      | 23 ++++++++--
 share/lib/python/neuron/__init__.py           | 11 +++++
 share/lib/python/neuron/doc.py                |  2 -
 share/lib/python/neuron/gui.py                | 38 ++++++++++------
 .../neuron/rxd/geometry3d/FullJoinMorph.py    |  2 -
 .../rxd/geometry3d/GeneralizedVoxelization.py |  5 ++-
 .../python/neuron/rxd/geometry3d/surfaces.pyx |  4 +-
 share/lib/python/neuron/rxd/gui.py            |  3 ++
 share/lib/python/neuron/rxd/node.py           |  6 +--
 share/lib/python/neuron/rxd/region.py         |  1 -
 share/lib/python/neuron/rxd/rxd.py            | 17 +++----
 share/lib/python/neuron/rxd/section1d.py      |  2 +-
 share/lib/python/neuron/rxd/species.py        | 17 ++++---
 .../rxdtests/tests/3d/circadian_rhythm.py     |  1 +
 share/lib/python/neuron/rxdtests/tests/hh.py  |  1 +
 .../python/neuron/rxdtests/tests/hh_cvode.py  |  1 +
 .../python/neuron/rxdtests/tests/hh_param.py  |  1 +
 .../neuron/rxdtests/tests/hh_param_cvode.py   |  1 +
 share/lib/python/neuron/tests/test_all.py     |  2 -
 share/lib/python/neuron/tests/test_neuron.py  |  5 +--
 share/lib/python/neuron/tests/test_rxd.py     |  3 +-
 share/lib/python/neuron/tests/test_vector.py  |  5 +--
 src/nrniv/glinerec.cpp                        |  1 -
 src/nrnpython/CMakeLists.txt                  |  3 ++
 src/nrnpython/inithoc.cpp                     | 44 +++++++++++++++++--
 src/nrnpython/nrnpy_hoc.cpp                   |  5 ++-
 src/nrnpython/nrnpython.cpp                   |  7 +++
 src/oc/fileio.cpp                             |  2 +-
 src/oc/hoc.cpp                                | 14 +++---
 src/oc/redef.h                                |  1 -
 test/cover/checkresult.py                     |  1 +
 test/cover/test_netcvode.py                   |  1 +
 test/gjtests/test_par_gj.py                   |  4 --
 test/parallel_tests/test_bas.py               |  1 -
 test/pynrn/test_fast_imem.py                  |  1 -
 test/pynrn/test_hoc_po.py                     |  1 +
 test/pynrn/test_nrnste.py                     |  1 -
 test/pynrn/test_partrans.py                   |  2 +-
 test/pynrn/test_template_err.py               |  1 -
 test/rxd/3d/test_soma_outlines.py             |  2 +-
 test/rxd/conftest.py                          |  6 ++-
 68 files changed, 341 insertions(+), 174 deletions(-)
 create mode 100644 packaging/python/oldest_numpy_requirements.txt
 create mode 100644 packaging/python/test_requirements.txt

diff --git a/.circleci/config.yml b/.circleci/config.yml
index 2064f017a5..b20deacb03 100644
--- a/.circleci/config.yml
+++ b/.circleci/config.yml
@@ -31,7 +31,7 @@ jobs:
                 -e NRN_RELEASE_UPLOAD \
                 -e NEURON_WHEEL_VERSION \
                 -e NRN_BUILD_FOR_UPLOAD=1 \
-                'neuronsimulator/neuron_wheel:latest-gcc9-aarch64' \
+                'neuronsimulator/neuron_wheel:latest-aarch64' \
                 packaging/python/build_wheels.bash linux << parameters.NRN_PYTHON_VERSION >> coreneuron
 
       - store_artifacts:
@@ -54,6 +54,8 @@ jobs:
               39) pyenv_py_ver="3.9.1" ;;
               310) pyenv_py_ver="3.10.1" ;;
               311) pyenv_py_ver="3.11.0" ;;
+              312) pyenv_py_ver="3.12.0" ;;
+              313) pyenv_py_ver="3.13.1" ;;
               *) echo "Error: pyenv python version not specified!" && exit 1;;
             esac
 
@@ -110,5 +112,5 @@ workflows:
       - manylinux2014-aarch64:
           matrix:
             parameters:
-              NRN_PYTHON_VERSION: ["37", "38", "39", "310", "311"]
+              NRN_PYTHON_VERSION: ["37", "38", "39", "310", "311", "312", "313"]
               NRN_NIGHTLY_UPLOAD: ["true"]
diff --git a/.github/workflows/coverage.yml b/.github/workflows/coverage.yml
index 50d42052a4..c03bb9bbab 100644
--- a/.github/workflows/coverage.yml
+++ b/.github/workflows/coverage.yml
@@ -20,8 +20,8 @@ on:
 #      - 'docs/**'
 
 env:
-  PY_MIN_VERSION: '3.7'
-  PY_MAX_VERSION: '3.11'
+  PY_MIN_VERSION: '3.9'
+  PY_MAX_VERSION: '3.12'
 
 jobs:
   coverage:
diff --git a/.github/workflows/neuron-ci.yml b/.github/workflows/neuron-ci.yml
index d31a1ac24d..b77cec2cfd 100644
--- a/.github/workflows/neuron-ci.yml
+++ b/.github/workflows/neuron-ci.yml
@@ -23,7 +23,7 @@ env:
   BUILD_TYPE: Release
   DESIRED_CMAKE_VERSION: 3.15.0
   PY_MIN_VERSION: '3.7'
-  PY_MAX_VERSION: '3.11'
+  PY_MAX_VERSION: '3.13'
 
 jobs:
   ci:
@@ -40,12 +40,12 @@ jobs:
       BUILD_TYPE: Release
       DESIRED_CMAKE_VERSION: 3.15.0
       PY_MIN_VERSION: ${{ matrix.config.python_min_version || '3.8' }}
-      PY_MAX_VERSION: ${{ matrix.config.python_max_version || '3.11' }}
+      PY_MAX_VERSION: ${{ matrix.config.python_max_version || '3.12' }}
       MUSIC_INSTALL_DIR: /opt/MUSIC
 
     strategy:
       matrix:
-        os: [ macOS-12, ubuntu-20.04]
+        os: [ macOS-13, ubuntu-20.04]
         config:
           - { matrix_eval : "CC=gcc-9 CXX=g++-9",   build_mode: "setuptools"}
           - { matrix_eval : "CC=gcc-8 CXX=g++-8",   build_mode: "cmake", music: ON}
@@ -120,6 +120,7 @@ jobs:
       - uses: actions/checkout@v4
         with:
           fetch-depth: 2
+          submodules: recursive
 
       - name: Set up Python@${{ env.PY_MIN_VERSION }}
         if: ${{matrix.config.python_dynamic == 'ON'}}
@@ -148,7 +149,7 @@ jobs:
         run: |
           python3 -m venv music-venv
           source music-venv/bin/activate
-          python3 -m pip install mpi4py "cython<3" "numpy<2"
+          python3 -m pip install mpi4py cython numpy
           sudo mkdir -p $MUSIC_INSTALL_DIR
           sudo chown -R $USER $MUSIC_INSTALL_DIR
           # Stable build: https://github.com/INCF/MUSIC/archive/refs/heads/switch-to-MPI-C-interface.zip  @ f33b66ea9348888eed1761738ab48c23ffc8a0d0
@@ -156,7 +157,7 @@ jobs:
           unzip MUSIC.zip && mv MUSIC-* MUSIC && cd MUSIC
           ./autogen.sh
           # workaround for MUSIC on MacOS 12
-          if [[ "${{matrix.os}}" == "macOS-12" ]]; then
+          if [[ "${{matrix.os}}" == "macOS-13" ]]; then
             MPI_CXXFLAGS="-g" MPI_CFLAGS="-g" MPI_LDFLAGS="-g" CC=mpicc CXX=mpicxx ./configure --with-python-sys-prefix --prefix=$MUSIC_INSTALL_DIR --disable-anysource
           else
             ./configure --with-python-sys-prefix --prefix=$MUSIC_INSTALL_DIR --disable-anysource
@@ -354,7 +355,7 @@ jobs:
           fi;
 
           if [ "$BUILD_MODE" == "setuptools" ]; then
-            neuron_wheel=wheelhouse/NEURON*.whl;
+            neuron_wheel=wheelhouse/*.whl;
             # test with virtual environment
             ${nrn_enable_sanitizer_preload} ./packaging/python/test_wheels.sh $PYTHON $neuron_wheel
             # test with global installation
diff --git a/.readthedocs.yml b/.readthedocs.yml
index dc4223186f..3b4186235a 100644
--- a/.readthedocs.yml
+++ b/.readthedocs.yml
@@ -1,9 +1,30 @@
 version: 2
 
+sphinx:
+  configuration: docs/conf.py
+
 build:
   os: "ubuntu-22.04"
   tools:
-    python: "mambaforge-22.9"
+    python: "3.12"
+  apt_packages:
+    - build-essential
+    - libx11-dev
+    - libxcomposite-dev
+    - libmpich-dev
+    - ffmpeg
+    - doxygen
+    - pandoc
+    - cmake
+    - bison
+    - flex
+    - libfl-dev
+    - libreadline-dev
+
+submodules:
+  recursive: true
 
-conda:
-  environment: docs/conda_environment.yml
+python:
+  install:
+    - requirements: nrn_requirements.txt
+    - requirements: docs/docs_requirements.txt
diff --git a/azure-pipelines.yml b/azure-pipelines.yml
index 64383067da..9e637ee90d 100644
--- a/azure-pipelines.yml
+++ b/azure-pipelines.yml
@@ -46,7 +46,13 @@ stages:
             python.version: '3.11'
           Python312:
             python.version: '3.12'
+          Python313:
+            python.version: '3.13'
+
       steps:
+      - script: |
+          git submodule update --init --recursive
+        displayName: Init submodules
 
       # Secure files documentation:
       #   https://docs.microsoft.com/en-us/azure/devops/pipelines/library/secure-files?view=azure-devops
@@ -71,7 +77,7 @@ stages:
             -e NRN_RELEASE_UPLOAD \
             -e NEURON_WHEEL_VERSION \
             -e NRN_BUILD_FOR_UPLOAD=1 \
-            'neuronsimulator/neuron_wheel:latest-gcc9-x86_64' \
+            'neuronsimulator/neuron_wheel:latest-x86_64' \
             packaging/python/build_wheels.bash linux $(python.version) coreneuron
         displayName: 'Building ManyLinux Wheel'
 
@@ -86,7 +92,7 @@ stages:
     - job: 'MacOSWheels'
       timeoutInMinutes: 40
       pool:
-        vmImage: 'macOS-12'
+        vmImage: 'macOS-13'
       strategy:
         matrix:
           Python37:
@@ -113,8 +119,15 @@ stages:
             python.version: '3.12'
             python.org.version: '3.12.2'
             python.installer.name: 'macos11.pkg'
+          Python313:
+            python.version: '3.13'
+            python.org.version: '3.13.1'
+            python.installer.name: 'macos11.pkg'
 
       steps:
+      - script: |
+          git submodule update --init --recursive
+        displayName: Init submodules
 
       - script: |
           installer=python-$(python.org.version)-$(python.installer.name)
diff --git a/bldnrnmacpkgcmake.sh b/bldnrnmacpkgcmake.sh
index 12ccd1588f..15ff3ba3cf 100644
--- a/bldnrnmacpkgcmake.sh
+++ b/bldnrnmacpkgcmake.sh
@@ -1,7 +1,7 @@
 #!/usr/bin/env bash
 set -ex
 
-default_pythons="python3.8 python3.9 python3.10 python3.11 python3.12"
+default_pythons="python3.9 python3.10 python3.11 python3.12 python3.13"
 # distribution built with
 # bash bldnrnmacpkgcmake.sh
 # without args, default are the pythons above.
@@ -13,13 +13,21 @@ if test "$rx3doptlevel" = "" ; then
   rx3doptlevel=2
 fi
 
+# Now obsolete...
 # python3.8 needs to be universal and macosx-10.9. So we built our own
 # from python.org python3.8.18 sources. Unfortunately, I cannot get pip
 # to work (OpenSSH issues), so I installed python.org Python3.8.10 installer
 # (which would have been fine by itself except it is macosx-11)
 # and copied relevant site-packages from that into the python3.8.18
 # installation site-packages.
-export PATH=$HOME/soft/python3.8/bin:$PATH
+# export PATH=$HOME/soft/python3.8/bin:$PATH
+
+# As of Python-3.13.0, we configure to link universal2 static readline
+# (and ncurses) into libnrniv.dylib.
+# The packages were downloade and the universal libraries were built with
+# nrn/packaging/python/build_static_readline_osx.bash
+READLINE_LIST="/opt/nrnwheel/readline;/opt/nrnwheel/ncurses"
+
 # In the top level source dir?# 
 if test -f nrnversion.sh ; then
   NRN_SRC=`pwd`
@@ -30,10 +38,6 @@ fi
 # All pythons must have the same macos version and that will become
 # the MACOSX_DEPLOYMENT_TARGET
 
-# On my machine, to build nrn-x.x.x-macosx-10.9-universal2-py-38-39-310-311.pkg
-# I built my own versions of 3.8 in $HOME/soft/python3.8, and
-export PATH=$HOME/soft/python3.8/bin:$PATH
-
 CPU=`uname -m`
 
 universal="yes" # changes to "no" if any python not universal
@@ -43,10 +47,13 @@ if test "$args" = "" ; then
   args="$default_pythons"
 fi
 
-
 # sysconfig.get_platform() looks like, e.g. "macosx-12.2-arm64" or
 # "macosx-11-universal2". I.e. encodes MACOSX_DEPLOYMENT_TARGET and archs.
 # Demand all pythons we are building against have same platform.
+# Python 3.13 is 10.13. The substantive aspect of
+# the following fragment (exit 1 if not all the same platform), has been
+# commented out.
+
 mac_platform=""
 for i in $args ; do
   last_py=$i
@@ -57,7 +64,7 @@ for i in $args ; do
   fi
   if test "$mac_platform" != "$mplat" ; then
     echo "$i platform \"$mplat\" differs from previous python \"$mac_platform\"."
-    exit 1
+#    exit 1
   fi
 done
 
@@ -117,6 +124,8 @@ cmake .. -G Ninja -DCMAKE_INSTALL_PREFIX=$NRN_INSTALL \
   -DIV_ENABLE_X11_DYNAMIC=ON \
   -DNRN_ENABLE_CORENEURON=OFF \
   -DNRN_RX3D_OPT_LEVEL=$rx3doptlevel \
+  -DLINK_AGAINST_PYTHON=ON \
+  -DNRN_MAC_PKG=ON \
   $archs_cmake \
   -DCMAKE_PREFIX_PATH=/usr/X11 \
   -DCMAKE_C_COMPILER=cc -DCMAKE_CXX_COMPILER=c++
diff --git a/ci/azure-win-installer-upload.yml b/ci/azure-win-installer-upload.yml
index c75bd701a3..f07739c7bd 100644
--- a/ci/azure-win-installer-upload.yml
+++ b/ci/azure-win-installer-upload.yml
@@ -7,7 +7,7 @@ steps:
 
   - task: UsePythonVersion@0
     inputs:
-      versionSpec: '3.7'
+      versionSpec: '3.9'
     displayName: "Use System Python"
 
   - task: BatchScript@1
diff --git a/ci/win_build_cmake.sh b/ci/win_build_cmake.sh
index 116f30a175..8a8beaddbd 100755
--- a/ci/win_build_cmake.sh
+++ b/ci/win_build_cmake.sh
@@ -9,8 +9,9 @@ export MINGW_CHOST=x86_64-w64-mingw32
 export MSYSTEM_PREFIX=/mingw64
 export PATH=/mingw64/bin:$PATH
 
-# have compatible cython3
-python3 -m pip install "cython<3"
+
+# have compatible cython and setuptools
+python3 -m pip install "cython<=3" setuptools
 
 # if BUILD_SOURCESDIRECTORY not available, use te root of the repo
 if [ -z "$BUILD_SOURCESDIRECTORY" ]; then
@@ -29,9 +30,9 @@ cd $BUILD_SOURCESDIRECTORY/build
 	-DNRN_ENABLE_PYTHON=ON  \
 	-DNRN_ENABLE_RX3D=ON  \
 	-DNRN_RX3D_OPT_LEVEL=2 \
-	-DPYTHON_EXECUTABLE=/c/Python37/python.exe \
+	-DPYTHON_EXECUTABLE=/c/Python312/python.exe \
 	-DNRN_ENABLE_PYTHON_DYNAMIC=ON  \
-	-DNRN_PYTHON_DYNAMIC='c:/Python37/python.exe;c:/Python38/python.exe;c:/Python39/python.exe;c:/Python310/python.exe;c:/Python311/python.exe;c:/Python312/python.exe'  \
+	-DNRN_PYTHON_DYNAMIC='c:/Python39/python.exe;c:/Python310/python.exe;c:/Python311/python.exe;c:/Python312/python.exe;c:/Python313/python.exe'  \
 	-DCMAKE_INSTALL_PREFIX='/c/nrn-install' \
 	-DMPI_CXX_LIB_NAMES:STRING=msmpi \
 	-DMPI_C_LIB_NAMES:STRING=msmpi \
diff --git a/ci/win_download_deps.cmd b/ci/win_download_deps.cmd
index 95f2588528..c66a0b510f 100644
--- a/ci/win_download_deps.cmd
+++ b/ci/win_download_deps.cmd
@@ -3,12 +3,11 @@
 :: download all installers
 
 :: python
-pwsh -command Invoke-WebRequest -MaximumRetryCount 4 -OutFile python-3.7.exe https://www.python.org/ftp/python/3.7.7/python-3.7.7-amd64.exe || goto :error
-pwsh -command Invoke-WebRequest -MaximumRetryCount 4 -OutFile python-3.8.exe https://www.python.org/ftp/python/3.8.2/python-3.8.2-amd64.exe || goto :error
 pwsh -command Invoke-WebRequest -MaximumRetryCount 4 -OutFile python-3.9.exe https://www.python.org/ftp/python/3.9.0/python-3.9.0-amd64.exe || goto :error
 pwsh -command Invoke-WebRequest -MaximumRetryCount 4 -OutFile python-3.10.exe https://www.python.org/ftp/python/3.10.0/python-3.10.0-amd64.exe || goto :error
 pwsh -command Invoke-WebRequest -MaximumRetryCount 4 -OutFile python-3.11.exe https://www.python.org/ftp/python/3.11.1/python-3.11.1-amd64.exe || goto :error
 pwsh -command Invoke-WebRequest -MaximumRetryCount 4 -OutFile python-3.12.exe https://www.python.org/ftp/python/3.12.1/python-3.12.1-amd64.exe || goto :error
+pwsh -command Invoke-WebRequest -MaximumRetryCount 4 -OutFile python-3.13.exe https://www.python.org/ftp/python/3.13.1/python-3.13.1-amd64.exe || goto :error
 
 :: mpi
 pwsh -command Invoke-WebRequest -MaximumRetryCount 4 -OutFile msmpisetup.exe https://download.microsoft.com/download/a/5/2/a5207ca5-1203-491a-8fb8-906fd68ae623/msmpisetup.exe || goto :error
diff --git a/ci/win_install_deps.cmd b/ci/win_install_deps.cmd
index 88954242de..04a360662d 100644
--- a/ci/win_install_deps.cmd
+++ b/ci/win_install_deps.cmd
@@ -3,37 +3,32 @@
 :: install all dependencies
 
 :: install python
-python-3.7.exe /passive Include_pip=1 Include_test=0 PrependPath=1 DefaultJustForMeTargetDir=C:\Python37 || goto :error
-python-3.8.exe /passive Include_pip=1 Include_test=0 PrependPath=1 DefaultJustForMeTargetDir=C:\Python38 || goto :error
 python-3.9.exe /passive Include_pip=1 Include_test=0 PrependPath=1 DefaultJustForMeTargetDir=C:\Python39 || goto :error
 python-3.10.exe /passive Include_pip=1 Include_test=0 PrependPath=1 DefaultJustForMeTargetDir=C:\Python310 || goto :error
 python-3.11.exe /passive Include_pip=1 Include_test=0 PrependPath=1 DefaultJustForMeTargetDir=C:\Python311 || goto :error
 python-3.12.exe /passive Include_pip=1 Include_test=0 PrependPath=1 DefaultJustForMeTargetDir=C:\Python312 || goto :error
+python-3.13.exe /passive Include_pip=1 Include_test=0 PrependPath=1 DefaultJustForMeTargetDir=C:\Python313 || goto :error
 
 :: fix msvcc version for all python3
-pwsh -command "(Get-Content C:\Python37\Lib\distutils\cygwinccompiler.py) -replace 'elif msc_ver == ''1600'':', 'elif msc_ver == ''1900'':' | Out-File C:\Python37\Lib\distutils\cygwinccompiler.py"
-pwsh -command "(Get-Content C:\Python38\Lib\distutils\cygwinccompiler.py) -replace 'elif msc_ver == ''1600'':', 'elif msc_ver == ''1916'':' | Out-File C:\Python38\Lib\distutils\cygwinccompiler.py"
 pwsh -command "(Get-Content C:\Python39\Lib\distutils\cygwinccompiler.py) -replace 'elif msc_ver == ''1600'':', 'elif msc_ver == ''1927'':' | Out-File C:\Python39\Lib\distutils\cygwinccompiler.py"
 pwsh -command "(Get-Content C:\Python310\Lib\distutils\cygwinccompiler.py) -replace 'elif msc_ver == ''1600'':', 'elif msc_ver == ''1929'':' | Out-File C:\Python310\Lib\distutils\cygwinccompiler.py"
 pwsh -command "(Get-Content C:\Python311\Lib\distutils\cygwinccompiler.py) -replace 'elif msc_ver == ''1600'':', 'elif msc_ver == ''1934'':' | Out-File C:\Python311\Lib\distutils\cygwinccompiler.py"
 
 
 :: fix msvc runtime library for all python
-pwsh -command "(Get-Content C:\Python37\Lib\distutils\cygwinccompiler.py) -replace 'msvcr100', 'msvcrt' | Out-File C:\Python37\Lib\distutils\cygwinccompiler.py"
-pwsh -command "(Get-Content C:\Python38\Lib\distutils\cygwinccompiler.py) -replace 'msvcr100', 'msvcrt' | Out-File C:\Python38\Lib\distutils\cygwinccompiler.py"
 pwsh -command "(Get-Content C:\Python39\Lib\distutils\cygwinccompiler.py) -replace 'msvcr100', 'msvcrt' | Out-File C:\Python39\Lib\distutils\cygwinccompiler.py"
 pwsh -command "(Get-Content C:\Python310\Lib\distutils\cygwinccompiler.py) -replace 'msvcr100', 'msvcrt' | Out-File C:\Python310\Lib\distutils\cygwinccompiler.py"
 pwsh -command "(Get-Content C:\Python311\Lib\distutils\cygwinccompiler.py) -replace 'msvcr100', 'msvcrt' | Out-File C:\Python311\Lib\distutils\cygwinccompiler.py"
 
 :: install numpy
-C:\Python37\python.exe -m pip install numpy==1.14.6 "cython < 3" || goto :error
-C:\Python38\python.exe -m pip install  numpy==1.17.5 "cython < 3" || goto :error
-C:\Python39\python.exe -m pip install  numpy==1.19.3 "cython < 3" || goto :error
-C:\Python310\python.exe -m pip install numpy==1.21.3 "cython < 3" || goto :error
-C:\Python311\python.exe -m pip install numpy==1.23.5 "cython < 3" || goto :error
-C:\Python312\python.exe -m pip install numpy==1.26.3 "cython < 3" || goto :error
+C:\Python39\python.exe -m pip install  numpy==1.19.3 "cython<3" || goto :error
+C:\Python310\python.exe -m pip install numpy==1.21.3 "cython<3" || goto :error
+C:\Python311\python.exe -m pip install numpy==1.23.5 "cython<3" || goto :error
+C:\Python312\python.exe -m pip install numpy==1.26.3 "cython<3" || goto :error
+C:\Python313\python.exe -m pip install numpy cython || goto :error
 :: setuptools 70.2 leads to an error
 C:\Python312\python.exe -m pip install setuptools==70.1.1 || goto :error
+C:\Python313\python.exe -m pip install setuptools==70.1.1 || goto :error
 
 :: install nsis
 nsis-3.05-setup.exe /S || goto :error
@@ -67,11 +62,11 @@ base-devel ^
 mingw-w64-x86_64-cmake ^
 mingw-w64-x86_64-ncurses ^
 mingw-w64-x86_64-readline ^
-mingw-w64-x86_64-python3 ^
+mingw-w64-x86_64-python ^
 mingw64/mingw-w64-x86_64-cython ^
-mingw-w64-x86_64-python3-setuptools ^
-mingw-w64-x86_64-python3-packaging ^
-mingw-w64-x86_64-python3-pip ^
+mingw-w64-x86_64-python-setuptools ^
+mingw-w64-x86_64-python-packaging ^
+mingw-w64-x86_64-python-pip ^
 mingw64/mingw-w64-x86_64-dlfcn ^
 mingw-w64-x86_64-toolchain || goto :error
 
diff --git a/ci/win_test_installer.cmd b/ci/win_test_installer.cmd
index e26dd2b139..9c8f11e210 100644
--- a/ci/win_test_installer.cmd
+++ b/ci/win_test_installer.cmd
@@ -17,14 +17,28 @@ echo %NEURONHOME%
 if not exist association.hoc.out (start /wait /REALTIME %cd%\ci\association.hoc)
 
 :: test all pythons
-C:\Python37\python -c "import neuron; neuron.test(); quit()" || set "errorfound=y"
-C:\Python38\python -c "import neuron; neuron.test(); quit()" || set "errorfound=y"
 C:\Python39\python -c "import neuron; neuron.test(); quit()" || set "errorfound=y"
 C:\Python310\python -c "import neuron; neuron.test(); quit()" || set "errorfound=y"
 C:\Python311\python -c "import neuron; neuron.test(); quit()" || set "errorfound=y"
 C:\Python312\python -c "import neuron; neuron.test(); quit()" || set "errorfound=y"
+C:\Python313\python -c "import neuron; neuron.test(); quit()" || set "errorfound=y"
+
+:: install oldest supported numpy
+C:\Python39\python.exe -m pip install -r packaging/python/oldest_numpy_requirements.txt || goto :error
+C:\Python310\python.exe -m pip install -r packaging/python/oldest_numpy_requirements.txt || goto :error
+C:\Python311\python.exe -m pip install -r packaging/python/oldest_numpy_requirements.txt || goto :error
+C:\Python312\python.exe -m pip install -r packaging/python/oldest_numpy_requirements.txt || goto :error
+C:\Python313\python.exe -m pip install -r packaging/python/oldest_numpy_requirements.txt || goto :error
+
+:: test all pythons again
+C:\Python39\python -c "import neuron; neuron.test(); quit()" || set "errorfound=y"
+C:\Python310\python -c "import neuron; neuron.test(); quit()" || set "errorfound=y"
+C:\Python311\python -c "import neuron; neuron.test(); quit()" || set "errorfound=y"
+C:\Python312\python -c "import neuron; neuron.test(); quit()" || set "errorfound=y"
+C:\Python313\python -c "import neuron; neuron.test(); quit()" || set "errorfound=y"
+
 :: install numpy dependency
-python -m pip install "numpy<2"
+python -m pip install numpy
 :: run also using whatever is system python
 python --version
 python -c "import neuron; neuron.test(); quit()" || set "errorfound=y"
diff --git a/ci/win_test_installer_wo_rxd.cmd b/ci/win_test_installer_wo_rxd.cmd
index 369bfa39cf..d6682ee967 100644
--- a/ci/win_test_installer_wo_rxd.cmd
+++ b/ci/win_test_installer_wo_rxd.cmd
@@ -20,15 +20,14 @@ echo %NEURONHOME%
 if not exist association.hoc.out (start /wait /REALTIME %cd%\ci\association.hoc)
 
 :: test all pythons
-C:\Python37\python -c "import neuron; neuron.test(); quit()" || set "errorfound=y"
-C:\Python38\python -c "import neuron; neuron.test(); quit()" || set "errorfound=y"
 C:\Python39\python -c "import neuron; neuron.test(); quit()" || set "errorfound=y"
 C:\Python310\python -c "import neuron; neuron.test(); quit()" || set "errorfound=y"
 C:\Python311\python -c "import neuron; neuron.test(); quit()" || set "errorfound=y"
 C:\Python312\python -c "import neuron; neuron.test(); quit()" || set "errorfound=y"
+C:\Python313\python -c "import neuron; neuron.test(); quit()" || set "errorfound=y"
 
 :: install numpy dependency
-python -m pip install "numpy<2"
+python -m pip install -r packaging/python/oldest_numpy_requirements.txt
 :: run also using whatever is system python
 python --version
 python -c "import neuron; neuron.test(); quit()" || set "errorfound=y"
diff --git a/docs/changelog.md b/docs/changelog.md
index 803c8cb372..a1363e5f61 100644
--- a/docs/changelog.md
+++ b/docs/changelog.md
@@ -1,5 +1,10 @@
 # NEURON 8.2
 
+## 8.2.7
+_Release Date_ : 01-02-2025
+
+This release allows use of Python 3.13
+
 ## 8.2.6
 _Release Date_ : 24-07-2024
 
diff --git a/docs/conda_environment.yml b/docs/conda_environment.yml
index 3c794969e7..6637782481 100644
--- a/docs/conda_environment.yml
+++ b/docs/conda_environment.yml
@@ -9,7 +9,7 @@ dependencies:
   - cmake
   - xorg-libxcomposite
   - ffmpeg
-  - cython<3
+  - cython
   - pandoc
   - pip
   - pip:
diff --git a/docs/conf.py b/docs/conf.py
index c9e1f5c8ae..9c5713aaeb 100644
--- a/docs/conf.py
+++ b/docs/conf.py
@@ -10,9 +10,11 @@
 # add these directories to sys.path here. If the directory is relative to the
 # documentation root, use os.path.abspath to make it absolute, like shown here.
 #
+import glob
 import os
 import sys
 import subprocess
+from pathlib import Path
 
 # Make translators & domains available for include
 sys.path.insert(0, os.path.abspath("./translators"))
@@ -40,6 +42,7 @@
     "sphinx.ext.mathjax",
     "nbsphinx",
     "sphinx_design",
+    "sphinx_inline_tabs",
 ]
 
 source_suffix = {
@@ -112,17 +115,32 @@ def setup(app):
 
     rtd_ver = PKGVER.parse(os.environ.get("READTHEDOCS_VERSION"))
 
-    # Install neuron accordingly (nightly for master, otherwise incoming version)
-    # Note that neuron wheel must be published a priori.
-    subprocess.run(
-        "pip install neuron{}".format(
-            "=={}".format(rtd_ver.base_version)
-            if isinstance(rtd_ver, PKGVER.Version)
-            else "-nightly"
-        ),
-        shell=True,
-        check=True,
-    )
+    # see:
+    # https://docs.readthedocs.com/platform/stable/reference/environment-variables.html#envvar-READTHEDOCS_VERSION_TYPE
+    if os.environ.get("READTHEDOCS_VERSION_TYPE") == "external":
+        # Build and install NEURON from source
+        subprocess.run(
+            "cd .. && python setup.py build_ext bdist_wheel",
+            shell=True,
+            check=True,
+        )
+        subprocess.run(
+            f"pip install {glob.glob('../dist/*.whl')[0]}",
+            shell=True,
+            check=True,
+        )
+    else:
+        # Install neuron accordingly (nightly for master, otherwise incoming version)
+        # Note that neuron wheel must be published a priori.
+        subprocess.run(
+            "pip install neuron{}".format(
+                f"=={rtd_ver.base_version}"
+                if isinstance(rtd_ver, PKGVER.Version)
+                else "-nightly"
+            ),
+            shell=True,
+            check=True,
+        )
 
     # Execute & convert notebooks + doxygen
     subprocess.run("cd .. && python setup.py docs", check=True, shell=True)
diff --git a/docs/docs_requirements.txt b/docs/docs_requirements.txt
index a8a10b7fdd..3b25c76883 100644
--- a/docs/docs_requirements.txt
+++ b/docs/docs_requirements.txt
@@ -4,8 +4,7 @@ jupyter
 nbconvert
 recommonmark
 matplotlib
-# bokeh 3 seems to break docs notebooks
-bokeh<3
+bokeh>=3
 # do not check import of next line
 ipython
 plotnine
@@ -14,5 +13,7 @@ plotly
 nbsphinx
 jinja2
 sphinx-design
+sphinx-inline-tabs
 packaging==21.3
 tenacity<8.4
+anywidget
diff --git a/docs/domains/hocdomain.py b/docs/domains/hocdomain.py
index 73ae11df5d..6a2d575e2c 100644
--- a/docs/domains/hocdomain.py
+++ b/docs/domains/hocdomain.py
@@ -1617,7 +1617,6 @@ def resolve_any_xref(
         multiple_matches = len(matches) > 1
 
         for name, obj in matches:
-
             if multiple_matches and obj.aliased:
                 # Skip duplicated matches
                 continue
diff --git a/docs/index.rst b/docs/index.rst
index 0df1324839..ed83cc14bb 100644
--- a/docs/index.rst
+++ b/docs/index.rst
@@ -88,7 +88,7 @@ Installation
 
          pip3 install neuron
 
-      Alternatively, you can use the `PKG installer <https://github.com/neuronsimulator/nrn/releases/download/8.2.6/nrn-8.2.6-macosx-10.9-universal2-py-38-39-310-311-312.pkg>`_.
+      Alternatively, you can use the `PKG installer <https://github.com/neuronsimulator/nrn/releases/download/8.2.6/nrn-8.2.6-macosx-10.9-universal2-py-38-39-310-311-312-313.pkg>`_.
 
       For troubleshooting, see the `detailed installation instructions <install/install_instructions.html>`_.
 
diff --git a/docs/install/install_instructions.md b/docs/install/install_instructions.md
index 5a952ba735..070579e64c 100644
--- a/docs/install/install_instructions.md
+++ b/docs/install/install_instructions.md
@@ -205,7 +205,7 @@ In order to build NEURON from source, the following packages must be available:
 The following packages are optional (see build options):
 
 - Python >=3.7 (for Python interface)
-- Cython < 3 (for RXD)
+- Cython (for RXD)
 - MPI (for parallel)
 - X11 (Linux) or XQuartz (MacOS) (for GUI)
 
diff --git a/docs/install/mac_pkg.md b/docs/install/mac_pkg.md
index 8a36dc03b7..38145da1c7 100644
--- a/docs/install/mac_pkg.md
+++ b/docs/install/mac_pkg.md
@@ -55,7 +55,7 @@ cmake .. -DCMAKE_INSTALL_PREFIX=$NRN_INSTALL \
 
 The default variables above will be
 ```
-pythons="python3.9;python3.10;python3.11;python3.12"
+pythons="python3.9;python3.10;python3.11;python3.12;python3.13"
 archs_cmake='-DCMAKE_OSX_ARCHITECTURES=arm64;x86_64'
 ```
 
diff --git a/docs/parse_rst.py b/docs/parse_rst.py
index 8753626ada..0322302eb2 100644
--- a/docs/parse_rst.py
+++ b/docs/parse_rst.py
@@ -10,7 +10,6 @@
 
 
 class ParseRst(object):
-
     help_dictionary = {}
 
     def __init__(self, rst_path, out_file):
diff --git a/nrn_requirements.txt b/nrn_requirements.txt
index c4ce7d3ae0..3aacefa65b 100644
--- a/nrn_requirements.txt
+++ b/nrn_requirements.txt
@@ -5,9 +5,9 @@ matplotlib
 # bokeh 3 seems to break docs notebooks
 bokeh<3
 ipython
-cython<3
+cython
 packaging
 pytest
 pytest-cov
 mpi4py
-numpy<2
+numpy
diff --git a/packaging/python/build_requirements.txt b/packaging/python/build_requirements.txt
index dcbd639f9c..ba9dcfb0e8 100644
--- a/packaging/python/build_requirements.txt
+++ b/packaging/python/build_requirements.txt
@@ -1,2 +1,2 @@
-cython<3
+cython
 packaging
diff --git a/packaging/python/build_wheels.bash b/packaging/python/build_wheels.bash
index dfa9e90f9d..d09525d16f 100755
--- a/packaging/python/build_wheels.bash
+++ b/packaging/python/build_wheels.bash
@@ -52,15 +52,16 @@ pip_numpy_install() {
       36) numpy_ver="numpy==1.12.1" ;;
       37) numpy_ver="numpy==1.14.6" ;;
       38) numpy_ver="numpy==1.17.5" ;;
-      39) numpy_ver="numpy==1.19.3" ;;
-      310) numpy_ver="numpy==1.21.3" ;;
-      311) numpy_ver="numpy==1.23.5" ;;
-      312) numpy_ver="numpy==1.26.0" ;;
+      39) numpy_ver="numpy>=2" ;;
+      310) numpy_ver="numpy>=2" ;;
+      311) numpy_ver="numpy>=2" ;;
+      312) numpy_ver="numpy>=2" ;;
+      313) numpy_ver="numpy>=2" ;;
       *) echo "Error: numpy version not specified for this python!" && exit 1;;
     esac
 
     # older version for apple m1 as building from source fails
-    if [[ `uname -m` == 'arm64' ]] && [[ $py_ver != 311 ]] && [[ $py_ver != 312 ]]; then
+    if [[ `uname -m` == 'arm64' ]] && [[ $py_ver -le 311 ]] ; then
       numpy_ver="numpy==1.21.3"
     fi
 
diff --git a/packaging/python/oldest_numpy_requirements.txt b/packaging/python/oldest_numpy_requirements.txt
new file mode 100644
index 0000000000..53f064c633
--- /dev/null
+++ b/packaging/python/oldest_numpy_requirements.txt
@@ -0,0 +1,8 @@
+numpy==1.14.6;python_version=='3.7'
+numpy==1.17.5;python_version=='3.8'
+numpy==1.20.3;python_version=='3.9' and platform_machine!='arm64'
+numpy==1.21.6;python_version=='3.9' and platform_machine=='arm64'
+numpy==1.21.6;python_version=='3.10'
+numpy==1.23.5;python_version=='3.11'
+numpy==1.26.4;python_version=='3.12'
+numpy>=2;python_version=='3.13'
diff --git a/packaging/python/test_requirements.txt b/packaging/python/test_requirements.txt
new file mode 100644
index 0000000000..6dbabce060
--- /dev/null
+++ b/packaging/python/test_requirements.txt
@@ -0,0 +1,2 @@
+pytest
+setuptools;python_version>='3.12' # From 3.12, no longer installed by default
diff --git a/packaging/python/test_wheels.sh b/packaging/python/test_wheels.sh
index e7c6ca5dc7..e64c2d2e33 100755
--- a/packaging/python/test_wheels.sh
+++ b/packaging/python/test_wheels.sh
@@ -274,6 +274,12 @@ test_wheel () {
 }
 
 
+test_wheel_basic_python () {
+    echo "=========== BASIC PYTHON TESTS ==========="
+    $python_exe -c "import neuron; neuron.test(); neuron.test_rxd()"
+}
+
+
 echo "== Testing $python_wheel using $python_exe ($python_ver) =="
 
 
@@ -297,10 +303,8 @@ $python_exe -m pip install --upgrade pip
 $python_exe -m pip install --upgrade setuptools
 
 
-# install numpy, pytest and neuron
-# we install setuptools because since python 3.12 it is no more installed
-# by default
-$python_exe -m pip install "numpy<2" pytest setuptools
+# install test requirements
+$python_exe -m pip install -r packaging/python/test_requirements.txt
 $python_exe -m pip install $python_wheel
 $python_exe -m pip show neuron \
     || $python_exe -m pip show neuron-nightly \
@@ -332,9 +336,14 @@ if [[ "$has_gpu_support" == "true" ]]; then
 fi
 
 
-# run tests
-test_wheel $(which python)
+# run tests with latest NumPy
+echo " == Running tests with latest NumPy == "
+test_wheel
 
+# run basic python tests with oldest supported NumPy
+echo " == Running basic python tests with oldest supported NumPy == "
+$python_exe -m pip install -r packaging/python/oldest_numpy_requirements.txt
+test_wheel_basic_python
 
 # cleanup
 if [[ "$use_venv" != "false" ]]; then
diff --git a/setup.py b/setup.py
index 0ca138e607..29baef9277 100644
--- a/setup.py
+++ b/setup.py
@@ -1,4 +1,5 @@
 import os
+import platform
 import re
 import shutil
 import subprocess
@@ -80,6 +81,11 @@ class Components:
     without_nrnpython = True
     sys.argv.remove("--without-nrnpython")
 
+mac_pkg = False
+if "--mac_pkg" in sys.argv:
+    mac_pkg = True
+    sys.argv.remove("--mac_pkg")
+
 # Main source of the version. Dont rename, used by Cmake
 try:
     # github actions somehow fails with check_output and python3
@@ -211,7 +217,6 @@ def run(self, *args, **kw):
         the CMake building, sets the extension build environment and collects files.
         """
         for ext in self.extensions:
-
             if isinstance(ext, CMakeAugmentedExtension):
                 if ext.cmake_done:
                     continue
@@ -410,7 +415,7 @@ def setup_package():
     NRN_COLLECT_DIRS = ["bin", "lib", "include", "share"]
 
     docs_require = []  # sphinx, themes, etc
-    maybe_rxd_reqs = ["numpy<2", "Cython<3"] if Components.RX3D else []
+    maybe_rxd_reqs = ["numpy", "Cython"] if Components.RX3D else []
     maybe_docs = docs_require if "docs" in sys.argv else []
     maybe_test_runner = ["pytest-runner"] if "test" in sys.argv else []
 
@@ -433,13 +438,16 @@ def setup_package():
             if sys.platform != "win32"
             else str(sys.version_info[0]) + str(sys.version_info[1])
         )
+        if mac_pkg:
+            nrn_python_lib = "nrnpython{}".format(
+                str(sys.version_info[0]) + str(sys.version_info[1])
+            )
         ext_common_libraries.append(nrn_python_lib)
 
     extension_common_params = defaultdict(
         list,
         library_dirs=[os.path.join(cmake_build_dir, "lib")],
         libraries=ext_common_libraries,
-        language="c++",
     )
 
     logging.info("Extension common compile flags %s" % str(extension_common_params))
@@ -500,6 +508,7 @@ def setup_package():
                 "neuronmusic",
                 ["src/neuronmusic/neuronmusic.pyx"],
                 include_dirs=["src/nrnpython", "src/nrnmusic"],
+                language="c++",
                 **extension_common_params,
             )
         ]
@@ -522,6 +531,9 @@ def setup_package():
             )
         )
 
+        if platform.system() == "Darwin":
+            rxd_params["extra_link_args"] += ["-headerpad_max_install_names"]
+
         logging.info("RX3D compile flags %s" % str(rxd_params))
 
         extensions += [
@@ -574,7 +586,7 @@ def setup_package():
         ],
         cmdclass=dict(build_ext=CMakeAugmentedBuilder, docs=Docs),
         install_requires=[
-            "numpy>=1.9.3,<2",
+            "numpy>=1.9.3",
             "packaging",
             "find_libpython",
             "setuptools",
@@ -614,6 +626,9 @@ def fmt(version):
         explicit_target = tuple(
             int(x) for x in os.environ["MACOSX_DEPLOYMENT_TARGET"].split(".")
         )
+    else:
+        # default deployment target
+        explicit_target = (10, 9)
 
     # Match Python OSX framework
     py_osx_framework = extract_macosx_min_system_version(sys.executable)
diff --git a/share/lib/python/neuron/__init__.py b/share/lib/python/neuron/__init__.py
index 823fbec2d2..5f69b03816 100644
--- a/share/lib/python/neuron/__init__.py
+++ b/share/lib/python/neuron/__init__.py
@@ -1751,3 +1751,14 @@ def _mview_html_tree(hlist, inside_mechanisms_in_use=0):
 if _get_ipython() is not None:
     html_formatter = _get_ipython().display_formatter.formatters["text/html"]
     html_formatter.for_type(hoc.HocObject, _hocobj_html)
+
+# in case Bokeh is installed, register a serialization function for hoc.Vector
+try:
+    from bokeh.core.serialization import Serializer
+
+    Serializer.register(
+        type(h.Vector),
+        lambda obj, serializer: [serializer.encode(item) for item in obj],
+    )
+except ImportError:
+    pass
diff --git a/share/lib/python/neuron/doc.py b/share/lib/python/neuron/doc.py
index 6b95673e2c..61cc9cc7c9 100644
--- a/share/lib/python/neuron/doc.py
+++ b/share/lib/python/neuron/doc.py
@@ -207,7 +207,6 @@ def get_docstring(objtype, symbol):
         f.close()
 
     if (objtype, symbol) == ("", ""):
-
         return doc_h
 
     # are we asking for help on a class, e.g. h.Vector
@@ -229,7 +228,6 @@ def get_docstring(objtype, symbol):
     if full_name in _help_dict:
         return _get_from_help_dict(full_name)
     else:
-
         return default_member_doc_template % (
             objtype,
             symbol,
diff --git a/share/lib/python/neuron/gui.py b/share/lib/python/neuron/gui.py
index 3314aa0d52..c049d6d638 100644
--- a/share/lib/python/neuron/gui.py
+++ b/share/lib/python/neuron/gui.py
@@ -7,11 +7,11 @@
 Note that python threads are not used if nrniv is launched instead of Python
 """
 
-
 from neuron import h
-
+from contextlib import contextmanager
 import threading
 import time
+import atexit
 
 # recursive, especially in case stop/start pairs called from doNotify code.
 _lock = threading.RLock()
@@ -29,9 +29,10 @@ def process_events():
     _lock.acquire()
     try:
         h.doNotify()
-    except:
-        print("Exception in gui thread")
-    _lock.release()
+    except Exception as e:
+        print(f"Exception in gui thread: {e}")
+    finally:
+        _lock.release()
 
 
 class Timer:
@@ -67,31 +68,40 @@ def end(self):
 
 class LoopTimer(threading.Thread):
     """
-    a Timer that calls f every interval
+    A Timer that calls a function at regular intervals.
     """
 
     def __init__(self, interval, fun):
-        """
-        @param interval: time in seconds between call to fun()
-        @param fun: the function to call on timer update
-        """
         self.started = False
         self.interval = interval
         self.fun = fun
-        threading.Thread.__init__(self)
-        self.setDaemon(True)
+        self._running = threading.Event()
+        threading.Thread.__init__(self, daemon=True)
 
     def run(self):
         h.nrniv_bind_thread(threading.current_thread().ident)
         self.started = True
-        while True:
+        self._running.set()
+        while self._running.is_set():
             self.fun()
             time.sleep(self.interval)
 
+    def stop(self):
+        """Stop the timer thread and wait for it to terminate."""
+        self._running.clear()
+        self.join()
+
 
-if h.nrnversion(9) == "2":  #  launched with python (instead of nrniv)
+if h.nrnversion(9) == "2":  # Launched with Python (instead of nrniv)
     timer = LoopTimer(0.1, process_events)
     timer.start()
+
+    def cleanup():
+        if timer.started:
+            timer.stop()
+
+    atexit.register(cleanup)
+
     while not timer.started:
         time.sleep(0.001)
 
diff --git a/share/lib/python/neuron/rxd/geometry3d/FullJoinMorph.py b/share/lib/python/neuron/rxd/geometry3d/FullJoinMorph.py
index 34553b1fa2..158748cf12 100644
--- a/share/lib/python/neuron/rxd/geometry3d/FullJoinMorph.py
+++ b/share/lib/python/neuron/rxd/geometry3d/FullJoinMorph.py
@@ -22,7 +22,6 @@
 
 
 def find_parent_seg(join, sdict, objects):
-
     if not join:
         return None
     elif join[0] not in objects:
@@ -65,7 +64,6 @@ def sort_spheres_last(item):
 
 
 def fullmorph(source, dx, soma_step=100, mesh_grid=None, relevant_pts=None):
-
     """Input: object source; arguments to pass to ctng
     Output: all voxels with SA and volume associated, categorized by segment"""
     source = list(source)
diff --git a/share/lib/python/neuron/rxd/geometry3d/GeneralizedVoxelization.py b/share/lib/python/neuron/rxd/geometry3d/GeneralizedVoxelization.py
index 37b358024f..83b87a8e6e 100644
--- a/share/lib/python/neuron/rxd/geometry3d/GeneralizedVoxelization.py
+++ b/share/lib/python/neuron/rxd/geometry3d/GeneralizedVoxelization.py
@@ -52,7 +52,7 @@ def verts_in(f, voxel, surf, g):
     verts = get_verts(voxel, g)
     ins = 0
     distlist = []
-    for (x, y, z) in verts:
+    for x, y, z in verts:
         if (
             g["xlo"] <= x <= g["xhi"]
             and g["ylo"] <= y <= g["yhi"]
@@ -173,7 +173,8 @@ def find_endpoints(f, surf, include_ga, row, guesses, g):
 
 def voxelize(grid, Object, corners=None, include_ga=False):
     """return a list of all voxels (i,j,k) that contain part of the object
-    Other returned elements: set of surface voxels, possibly_missed for error handling"""
+    Other returned elements: set of surface voxels, possibly_missed for error handling
+    """
     # include_ga is whether to include grid-adjacent voxels in the surface, even if entirely within the surface
 
     yes_voxels = set()
diff --git a/share/lib/python/neuron/rxd/geometry3d/surfaces.pyx b/share/lib/python/neuron/rxd/geometry3d/surfaces.pyx
index 141adf7899..bf3aac2eb1 100644
--- a/share/lib/python/neuron/rxd/geometry3d/surfaces.pyx
+++ b/share/lib/python/neuron/rxd/geometry3d/surfaces.pyx
@@ -1,13 +1,11 @@
 import os
 import numpy
-import graphicsPrimitives
-import neuron
-import numpy
 cimport numpy
 import itertools
 import bisect
 cimport cython
 
+from neuron.rxd.geometry3d import graphicsPrimitives
 
 """
 The surfaces module
diff --git a/share/lib/python/neuron/rxd/gui.py b/share/lib/python/neuron/rxd/gui.py
index 6616006abe..b96e39e287 100644
--- a/share/lib/python/neuron/rxd/gui.py
+++ b/share/lib/python/neuron/rxd/gui.py
@@ -1204,6 +1204,7 @@ def map(self):
 
 _the_species_editor = _SpeciesEditor()
 
+
 # this is a way of faking the Singleton pattern
 def SpeciesEditor():
     if not _the_species_editor.is_mapped:
@@ -1249,6 +1250,7 @@ def map(self):
 
 _the_species_pane = _SpeciesPane()
 
+
 # this is a way of faking the Singleton pattern
 def SpeciesPane():
     _the_species_pane = _SpeciesPane()
@@ -1700,6 +1702,7 @@ def map(self):
 
 _the_reaction_pane = _ReactionPane()
 
+
 # this is a way of faking the Singleton pattern
 def ReactionPane():
     if not _the_reaction_pane.is_mapped:
diff --git a/share/lib/python/neuron/rxd/node.py b/share/lib/python/neuron/rxd/node.py
index 60e09b4d76..23360ccabe 100644
--- a/share/lib/python/neuron/rxd/node.py
+++ b/share/lib/python/neuron/rxd/node.py
@@ -71,7 +71,7 @@ def _remove(start, stop):
 
     # remove _node_flux
     newflux = {"index": [], "type": [], "source": [], "scale": [], "region": []}
-    for (i, idx) in enumerate(_node_fluxes["index"]):
+    for i, idx in enumerate(_node_fluxes["index"]):
         if idx not in dels:
             for key in _node_fluxes:
                 newflux[key].append(_node_fluxes[key][i])
@@ -79,7 +79,7 @@ def _remove(start, stop):
     _has_node_fluxes = _node_fluxes["index"] != []
 
     # remove _node_flux
-    for (i, idx) in enumerate(_node_fluxes["index"]):
+    for i, idx in enumerate(_node_fluxes["index"]):
         if idx in dels:
             for lst in _node_fluxes.values():
                 del lst[i]
@@ -108,7 +108,7 @@ def _replace(old_offset, old_nseg, new_offset, new_nseg):
     _states = numpy.delete(_states, list(range(start, stop)))
 
     # update _node_flux index
-    for (i, idx) in enumerate(_node_fluxes["index"]):
+    for i, idx in enumerate(_node_fluxes["index"]):
         if idx in dels:
             j = int(((idx + 0.5) / new_nseg) * old_nseg)
             _node_fluxes["index"][i] = j
diff --git a/share/lib/python/neuron/rxd/region.py b/share/lib/python/neuron/rxd/region.py
index 5791c68130..317e3f6aa2 100644
--- a/share/lib/python/neuron/rxd/region.py
+++ b/share/lib/python/neuron/rxd/region.py
@@ -447,7 +447,6 @@ def _parse_tortuosity(self, value, is_permeability=False):
         return parsed_value, ecs_permeability
 
     def _parse_volume_fraction(self, volume_fraction):
-
         if numpy.isscalar(volume_fraction):
             alpha = float(volume_fraction)
             alpha = alpha
diff --git a/share/lib/python/neuron/rxd/rxd.py b/share/lib/python/neuron/rxd/rxd.py
index 698381dfe5..2464780c24 100644
--- a/share/lib/python/neuron/rxd/rxd.py
+++ b/share/lib/python/neuron/rxd/rxd.py
@@ -65,7 +65,7 @@
 setup_solver.argtypes = [
     ndpointer(ctypes.c_double),
     ctypes.c_int,
-    numpy.ctypeslib.ndpointer(numpy.int_, flags="contiguous"),
+    numpy.ctypeslib.ndpointer(ctypes.c_long, flags="contiguous"),
     ctypes.c_int,
 ]
 
@@ -608,7 +608,6 @@ def _update_node_data(force=False, newspecies=False):
         or _structure_change_count.value != last_structure_change_cnt
         or force
     ):
-
         last_diam_change_cnt = _diam_change_count.value
         last_structure_change_cnt = _structure_change_count.value
         # if not species._has_3d:
@@ -655,17 +654,15 @@ def _matrix_to_rxd_sparse(m):
     return (
         n,
         len(nonzero_i),
-        numpy.ascontiguousarray(nonzero_i, dtype=numpy.int_),
-        numpy.ascontiguousarray(nonzero_j, dtype=numpy.int_),
+        numpy.ascontiguousarray(nonzero_i, dtype=ctypes.c_long),
+        numpy.ascontiguousarray(nonzero_j, dtype=ctypes.c_long),
         nonzero_values,
     )
 
 
 # TODO: make sure this does the right thing when the diffusion constant changes between two neighboring nodes
 def _setup_matrices():
-
     with initializer._init_lock:
-
         # update _node_fluxes in C
         _include_flux()
 
@@ -674,7 +671,7 @@ def _setup_matrices():
         n = len(_node_get_states())
 
         volumes = node._get_data()[0]
-        zero_volume_indices = (numpy.where(volumes == 0)[0]).astype(numpy.int_)
+        zero_volume_indices = (numpy.where(volumes == 0)[0]).astype(ctypes.c_long)
         if species._has_1d:
             # TODO: initialization is slow. track down why
 
@@ -1462,7 +1459,7 @@ def localize_index(creg, rate):
                             continue
                         fxn_string += "\n\trate = %s;" % rate_str
                         summed_mults = collections.defaultdict(lambda: 0)
-                        for (mult, sp) in zip(r._mult, r._sources + r._dests):
+                        for mult, sp in zip(r._mult, r._sources + r._dests):
                             summed_mults[creg._species_ids.get(sp()._id)] += mult
                         for idx in sorted([k for k in summed_mults if k is not None]):
                             operator = "+=" if species_ids_used[idx][region_id] else "="
@@ -1871,7 +1868,7 @@ def _init():
     _setup_matrices()
     # if species._has_1d and species._1d_submatrix_n():
     # volumes = node._get_data()[0]
-    # zero_volume_indices = (numpy.where(volumes == 0)[0]).astype(numpy.int_)
+    # zero_volume_indices = (numpy.where(volumes == 0)[0]).astype(ctypes.c_long)
     # setup_solver(_node_get_states(), len(_node_get_states()), zero_volume_indices, len(zero_volume_indices), h._ref_t, h._ref_dt)
     clear_rates()
     _setup_memb_currents()
@@ -2007,7 +2004,7 @@ def _windows_remove_dlls():
             kernel32.FreeLibrary.argtypes = [ctypes.c_void_p]
         else:
             kernel32 = ctypes.windll.kernel32
-    for (dll_ptr, filepath) in zip(_windows_dll, _windows_dll_files):
+    for dll_ptr, filepath in zip(_windows_dll, _windows_dll_files):
         dll = dll_ptr()
         if dll:
             handle = dll._handle
diff --git a/share/lib/python/neuron/rxd/section1d.py b/share/lib/python/neuron/rxd/section1d.py
index 09746f0a9e..5c9b9a1440 100644
--- a/share/lib/python/neuron/rxd/section1d.py
+++ b/share/lib/python/neuron/rxd/section1d.py
@@ -67,7 +67,7 @@ def remove(self, rxdsec):
 
 def add_values(mat, i, js, vals):
     mat_i = mat[i]
-    for (j, val) in zip(js, vals):
+    for j, val in zip(js, vals):
         if val == 0:
             continue
         if j in mat_i:
diff --git a/share/lib/python/neuron/rxd/species.py b/share/lib/python/neuron/rxd/species.py
index 93fcba63ad..245223df68 100644
--- a/share/lib/python/neuron/rxd/species.py
+++ b/share/lib/python/neuron/rxd/species.py
@@ -60,12 +60,12 @@
     ctypes.c_int,
     ctypes.py_object,
     ctypes.c_long,
-    numpy.ctypeslib.ndpointer(dtype=int),
-    numpy.ctypeslib.ndpointer(dtype=int),
+    numpy.ctypeslib.ndpointer(dtype=ctypes.c_long),
+    numpy.ctypeslib.ndpointer(dtype=ctypes.c_long),
     ctypes.c_long,
-    numpy.ctypeslib.ndpointer(dtype=int),
+    numpy.ctypeslib.ndpointer(dtype=ctypes.c_long),
     ctypes.c_long,
-    numpy.ctypeslib.ndpointer(dtype=int),
+    numpy.ctypeslib.ndpointer(dtype=ctypes.c_long),
     ctypes.c_long,
     numpy.ctypeslib.ndpointer(dtype=float),
     ctypes.c_double,
@@ -842,7 +842,7 @@ def line_defs(self, nodes, direction, nodes_length):
 
         # sort list for parallelization
         line_defs.sort(key=lambda x: x[1], reverse=True)
-        line_defs = numpy.asarray(line_defs, dtype=int)
+        line_defs = numpy.asarray(line_defs, dtype=ctypes.c_long)
         line_defs = line_defs.reshape(2 * len(line_defs))
         return line_defs
 
@@ -862,7 +862,7 @@ def ordered_nodes(self, p_line_defs, direction, neighbors):
 
     def create_neighbors_array(self, nodes, nodes_length):
         self._isalive()
-        my_array = numpy.zeros((nodes_length, 3), dtype=int)
+        my_array = numpy.zeros((nodes_length, 3), dtype=ctypes.c_long)
         for n in nodes:
             for i, ele in enumerate(n.neighbors[::2]):
                 my_array[n._index, i] = ele if ele is not None else -1
@@ -1507,7 +1507,6 @@ def _import_concentration(self):
                     self._states[i] = getattr(seg, stateo)
 
     def _semi_compile(self, reg, instruction):
-
         self._isalive()
         if self._species:
             sp = _defined_species[self._species][self._region]()
@@ -1523,7 +1522,6 @@ def _semi_compile(self, reg, instruction):
 
     @property
     def d(self):
-
         self._isalive()
         return self._d
 
@@ -2283,7 +2281,8 @@ def _import_concentration(self, init=True):
     def nodes(self):
         """A NodeList of all the nodes corresponding to the species.
 
-        This can then be further restricted using the callable property of NodeList objects."""
+        This can then be further restricted using the callable property of NodeList objects.
+        """
 
         from . import rxd
 
diff --git a/share/lib/python/neuron/rxdtests/tests/3d/circadian_rhythm.py b/share/lib/python/neuron/rxdtests/tests/3d/circadian_rhythm.py
index 8c9aa12ecc..811da1b913 100644
--- a/share/lib/python/neuron/rxdtests/tests/3d/circadian_rhythm.py
+++ b/share/lib/python/neuron/rxdtests/tests/3d/circadian_rhythm.py
@@ -11,6 +11,7 @@
 hour = 60 * minute
 h.dt = 1 * minute
 
+
 # def run_sim():
 def declare_parameters(**kwargs):
     """enables clean declaration of parameters in top namespace"""
diff --git a/share/lib/python/neuron/rxdtests/tests/hh.py b/share/lib/python/neuron/rxdtests/tests/hh.py
index 70f76a68dd..0736410653 100644
--- a/share/lib/python/neuron/rxdtests/tests/hh.py
+++ b/share/lib/python/neuron/rxdtests/tests/hh.py
@@ -61,6 +61,7 @@
 # extracellular
 ecs = rxd.Extracellular(-100, -100, -100, 100, 100, 100, dx=100)
 
+
 # Who?
 def init(ics, ecs):
     return lambda nd: ecs if isinstance(nd, rxd.node.NodeExtracellular) else ics
diff --git a/share/lib/python/neuron/rxdtests/tests/hh_cvode.py b/share/lib/python/neuron/rxdtests/tests/hh_cvode.py
index bf272bece6..86b23a8495 100644
--- a/share/lib/python/neuron/rxdtests/tests/hh_cvode.py
+++ b/share/lib/python/neuron/rxdtests/tests/hh_cvode.py
@@ -61,6 +61,7 @@
 # extracellular
 ecs = rxd.Extracellular(-100, -100, -100, 100, 100, 100, dx=100)
 
+
 # Who?
 def init(ics, ecs):
     return lambda nd: ecs if isinstance(nd, rxd.node.NodeExtracellular) else ics
diff --git a/share/lib/python/neuron/rxdtests/tests/hh_param.py b/share/lib/python/neuron/rxdtests/tests/hh_param.py
index 11c1f784da..5ea22df5bb 100644
--- a/share/lib/python/neuron/rxdtests/tests/hh_param.py
+++ b/share/lib/python/neuron/rxdtests/tests/hh_param.py
@@ -61,6 +61,7 @@
 # extracellular
 ecs = rxd.Extracellular(-100, -100, -100, 100, 100, 100, dx=33)
 
+
 # Who?
 def init(ics, ecs):
     return lambda nd: ecs if isinstance(nd, rxd.node.NodeExtracellular) else ics
diff --git a/share/lib/python/neuron/rxdtests/tests/hh_param_cvode.py b/share/lib/python/neuron/rxdtests/tests/hh_param_cvode.py
index f9f11f95fa..254cef35ff 100644
--- a/share/lib/python/neuron/rxdtests/tests/hh_param_cvode.py
+++ b/share/lib/python/neuron/rxdtests/tests/hh_param_cvode.py
@@ -61,6 +61,7 @@
 # extracellular
 ecs = rxd.Extracellular(-100, -100, -100, 100, 100, 100, dx=33)
 
+
 # Who?
 def init(ics, ecs):
     return lambda nd: ecs if isinstance(nd, rxd.node.NodeExtracellular) else ics
diff --git a/share/lib/python/neuron/tests/test_all.py b/share/lib/python/neuron/tests/test_all.py
index 3726bc9ff8..7af6d620e0 100644
--- a/share/lib/python/neuron/tests/test_all.py
+++ b/share/lib/python/neuron/tests/test_all.py
@@ -13,7 +13,6 @@
 
 
 def suite():
-
     suite = unittest.TestSuite()
     suite.addTest(test_vector.suite())
     suite.addTest(test_neuron.suite())
@@ -22,7 +21,6 @@ def suite():
 
 
 if __name__ == "__main__":
-
     # unittest.main()
     runner = unittest.TextTestRunner(verbosity=2)
     runner.run(suite())
diff --git a/share/lib/python/neuron/tests/test_neuron.py b/share/lib/python/neuron/tests/test_neuron.py
index f706dc2f4a..5392acf9cf 100644
--- a/share/lib/python/neuron/tests/test_neuron.py
+++ b/share/lib/python/neuron/tests/test_neuron.py
@@ -277,13 +277,10 @@ def basicRxD3D():
 
 
 def suite():
-
-    suite = unittest.makeSuite(NeuronTestCase, "test")
-    return suite
+    return unittest.defaultTestLoader.loadTestsFromTestCase(NeuronTestCase)
 
 
 if __name__ == "__main__":
-
     # unittest.main()
     runner = unittest.TextTestRunner(verbosity=2)
     runner.run(suite())
diff --git a/share/lib/python/neuron/tests/test_rxd.py b/share/lib/python/neuron/tests/test_rxd.py
index 964bd53738..db85696c90 100644
--- a/share/lib/python/neuron/tests/test_rxd.py
+++ b/share/lib/python/neuron/tests/test_rxd.py
@@ -798,8 +798,7 @@ def test_ecs_diffusion_variable_step_fine(self):
 
 
 def suite():
-    suite = unittest.makeSuite(RxDTestCase, "test")
-    return suite
+    return unittest.defaultTestLoader.loadTestsFromTestCase(RxDTestCase)
 
 
 def test():
diff --git a/share/lib/python/neuron/tests/test_vector.py b/share/lib/python/neuron/tests/test_vector.py
index efd5c672af..69166c9dcb 100644
--- a/share/lib/python/neuron/tests/test_vector.py
+++ b/share/lib/python/neuron/tests/test_vector.py
@@ -103,13 +103,10 @@ def testNumpyInteraction(self):
 
 
 def suite():
-
-    suite = unittest.makeSuite(VectorTestCase, "test")
-    return suite
+    return unittest.defaultTestLoader.loadTestsFromTestCase(VectorTestCase)
 
 
 if __name__ == "__main__":
-
     # unittest.main()
     runner = unittest.TextTestRunner(verbosity=2)
     runner.run(suite())
diff --git a/src/nrniv/glinerec.cpp b/src/nrniv/glinerec.cpp
index 7b48b68e1b..d41ad96a49 100644
--- a/src/nrniv/glinerec.cpp
+++ b/src/nrniv/glinerec.cpp
@@ -10,7 +10,6 @@
 
 #include "hocparse.h"
 #include "code.h"
-#undef begin
 #undef add
 
 #include <OS/list.h>
diff --git a/src/nrnpython/CMakeLists.txt b/src/nrnpython/CMakeLists.txt
index 395c9e7d65..3286acabfb 100644
--- a/src/nrnpython/CMakeLists.txt
+++ b/src/nrnpython/CMakeLists.txt
@@ -198,6 +198,9 @@ if(NRN_ENABLE_MODULE_INSTALL)
   if(NRN_ENABLE_MUSIC)
     list(APPEND NRN_SETUP_PY_BUILD_OPTIONS "--enable-music")
   endif()
+  if(NRN_MAC_PKG)
+    list(APPEND NRN_SETUP_PY_BUILD_OPTIONS "--mac_pkg")
+  endif()
   list(APPEND NRN_SETUP_PY_BUILD_OPTIONS "--build-lib=${NRN_PYTHON_BUILD_LIB}")
 
   # Prepare build_ext options for setup.py build
diff --git a/src/nrnpython/inithoc.cpp b/src/nrnpython/inithoc.cpp
index 5744c7c88e..27f96329a9 100644
--- a/src/nrnpython/inithoc.cpp
+++ b/src/nrnpython/inithoc.cpp
@@ -215,6 +215,33 @@ static int have_opt(const char* arg) {
     return 0;
 }
 
+#if defined(__linux__) || defined(DARWIN)
+
+/* we do this because thread sanitizer does not allow system calls.
+   In particular
+      system("stty sane")
+   returns an error code of 139
+*/
+
+#include <iostream>
+#include <termios.h>
+#include <unistd.h>
+
+static struct termios original_termios;
+
+static void save_original_terminal_settings() {
+    if (tcgetattr(STDIN_FILENO, &original_termios) == -1 && isatty(STDIN_FILENO)) {
+        std::cerr << "Error getting original terminal attributes\n";
+    }
+}
+
+static void restore_original_terminal_settings() {
+    if (tcsetattr(STDIN_FILENO, TCSANOW, &original_termios) == -1 && isatty(STDIN_FILENO)) {
+        std::cerr << "Error restoring terminal attributes\n";
+    }
+}
+#endif  // __linux__
+
 void nrnpython_finalize() {
 #if USE_PTHREAD
     pthread_t now = pthread_self();
@@ -222,11 +249,18 @@ void nrnpython_finalize() {
 #else
     {
 #endif
+        // Call python_gui_cleanup() if defined in Python
+        PyRun_SimpleString(
+            "try:\n"
+            "    gui.cleanup()\n"
+            "except NameError:\n"
+            "    pass\n");
+
+        // Finalize Python
         Py_Finalize();
     }
-#if linux
-    if (system("stty sane > /dev/null 2>&1")) {
-    }  // 'if' to avoid ignoring return value warning
+#if defined(__linux__) || defined(DARWIN)
+    restore_original_terminal_settings();
 #endif
 }
 
@@ -239,6 +273,10 @@ extern "C" PyObject* PyInit_hoc() {
     main_thread_ = pthread_self();
 #endif
 
+#if defined(__linux__) || defined(DARWIN)
+    save_original_terminal_settings();
+#endif  // __linux__
+
     if (nrn_global_argv) {  // ivocmain was already called so already loaded
         return nrnpy_hoc();
     }
diff --git a/src/nrnpython/nrnpy_hoc.cpp b/src/nrnpython/nrnpy_hoc.cpp
index 2d225e7df6..c8988ce1ec 100644
--- a/src/nrnpython/nrnpy_hoc.cpp
+++ b/src/nrnpython/nrnpy_hoc.cpp
@@ -1596,13 +1596,16 @@ PyObject* nrnpy_forall(PyObject* self, PyObject* args) {
 static PyObject* hocobj_iter(PyObject* self) {
     //	printf("hocobj_iter %p\n", self);
     PyHocObject* po = (PyHocObject*) self;
-    if (po->type_ == PyHoc::HocObject) {
+    if (po->type_ == PyHoc::HocObject || po->type_ == PyHoc::HocSectionListIterator) {
         if (po->ho_->ctemplate == hoc_vec_template_) {
             return PySeqIter_New(self);
         } else if (po->ho_->ctemplate == hoc_list_template_) {
             return PySeqIter_New(self);
         } else if (po->ho_->ctemplate == hoc_sectionlist_template_) {
             // need a clone of self so nested loops do not share iteritem_
+            // The HocSectionListIter arm of the outer 'if' became necessary
+            // at Python-3.13.1 upon which the following body is executed
+            // twice. See https://github.com/python/cpython/issues/127682
             PyObject* po2 = nrnpy_ho2po(po->ho_);
             PyHocObject* pho2 = (PyHocObject*) po2;
             pho2->type_ = PyHoc::HocSectionListIterator;
diff --git a/src/nrnpython/nrnpython.cpp b/src/nrnpython/nrnpython.cpp
index b774623aa5..b09a77c07d 100644
--- a/src/nrnpython/nrnpython.cpp
+++ b/src/nrnpython/nrnpython.cpp
@@ -210,6 +210,13 @@ extern "C" int nrnpython_start(int b) {
         // del g
         // Also, NEURONMainMenu/File/Quit did not work. The solution to both
         // seems to be to just avoid gui threads if MINGW and launched nrniv
+
+        // Beginning with Python 3.13.0 it seems that the readline
+        // module has not been loaded yet. Since PyInit_readline sets
+        // PyOS_ReadlineFunctionPointer = call_readline; without checking,
+        // we need to import here.
+        PyRun_SimpleString("import readline as nrn_readline");
+
         PyOS_ReadlineFunctionPointer = nrnpython_getline;
 
         // Is there a -c "command" or file.py arg.
diff --git a/src/oc/fileio.cpp b/src/oc/fileio.cpp
index 609a2abbde..185f44db06 100644
--- a/src/oc/fileio.cpp
+++ b/src/oc/fileio.cpp
@@ -16,7 +16,7 @@
 #include "nrnfilewrap.h"
 
 
-extern jmp_buf begin;
+extern jmp_buf begin_;
 extern char* neuron_home;
 
 NrnFILEWrap* frin;
diff --git a/src/oc/hoc.cpp b/src/oc/hoc.cpp
index 467dde99ef..5f5fad2875 100644
--- a/src/oc/hoc.cpp
+++ b/src/oc/hoc.cpp
@@ -190,7 +190,7 @@ int lineno;
 #include <signal.h>
 #include <setjmp.h>
 static int control_jmpbuf = 0; /* don't change jmp_buf if being controlled */
-jmp_buf begin;
+jmp_buf begin_;
 static int hoc_oc_jmpbuf;
 static jmp_buf hoc_oc_begin;
 int intset; /* safer interrupt handling */
@@ -695,7 +695,7 @@ extern void hoc_newobj1_err();
  *  hoc_newobj1_err needs handle to know how much to unwrap the newobj1 stack.
  **/
 void* nrn_get_hoc_jmp() {
-    void* jmp = hoc_oc_jmpbuf ? (void*) hoc_oc_begin : (void*) begin;
+    void* jmp = hoc_oc_jmpbuf ? (void*) hoc_oc_begin : (void*) begin_;
     return jmp;
 }
 
@@ -748,7 +748,7 @@ void hoc_execerror_mes(const char* s, const char* t, int prnt) { /* recover from
         longjmp(hoc_oc_begin, 1);
     }
     hoc_newobj1_err();
-    longjmp(begin, 1);
+    longjmp(begin_, 1);
 }
 
 extern "C" void hoc_execerror(const char* s, const char* t) /* recover from run-time error */
@@ -928,7 +928,7 @@ void hoc_main1_init(const char* pname, const char** envp) {
         }
     }
     progname = pname;
-    if (setjmp(begin)) {
+    if (setjmp(begin_)) {
         nrn_exit(1);
     }
 
@@ -1007,7 +1007,7 @@ int hoc_main1(int argc, const char** argv, const char** envp) /* hoc6 */
 	controlled = control_jmpbuf;
 	if (!controlled) {
 		control_jmpbuf = 1;
-		if (setjmp(begin)) {
+		if (setjmp(begin_)) {
 			control_jmpbuf = 0;
 			return 1;
 		}
@@ -1385,7 +1385,7 @@ static int hoc_run1(void) /* execute until EOF */
     if (!controlled) {
         set_signals();
         control_jmpbuf = 1;
-        if (setjmp(begin)) {
+        if (setjmp(begin_)) {
             fin = sav_fin;
             if (!nrn_fw_eq(fin, stdin)) {
                 return EXIT_FAILURE;
@@ -1430,7 +1430,7 @@ static int hoc_run1(void) /* execute until EOF */
    Where do we go in case of an hoc_execerror. We have to go to the beginning
    of hoc. But just maybe that is here. However hoc_oc may be called
    recursively. Or it may be called from the original hoc_run. Or it may be
-   There is therefore a notion of the controlling routine for the jmp_buf begin.
+   There is therefore a notion of the controlling routine for the jmp_buf begin_.
    We only do a setjmp and set the signals
    when there is no other controlling routine.
 */
diff --git a/src/oc/redef.h b/src/oc/redef.h
index 0891ecef01..c680501511 100644
--- a/src/oc/redef.h
+++ b/src/oc/redef.h
@@ -29,7 +29,6 @@
 #define argassign          hoc_argassign
 #define assign             hoc_assign
 #define assstr             hoc_assstr
-#define begin              hoc_begin
 #define bltin              hoc_bltin
 #define call               hoc_call
 #define call_ob_proc       hoc_call_ob_proc
diff --git a/test/cover/checkresult.py b/test/cover/checkresult.py
index b73c1948cd..66da19c5b5 100644
--- a/test/cover/checkresult.py
+++ b/test/cover/checkresult.py
@@ -42,6 +42,7 @@ def __call__(self, key, value, tol=0.0):
             if type(value) == type(h.Vector):  # actually hoc.HocObject
                 # Convert to list to keep the `equal` method below simple
                 value = list(value)
+
             # Hand-rolled comparison that uses `tol` for arithmetic values
             # buried inside lists of lists.
             def equal(a, b):
diff --git a/test/cover/test_netcvode.py b/test/cover/test_netcvode.py
index dbe3273130..105340cc5c 100644
--- a/test/cover/test_netcvode.py
+++ b/test/cover/test_netcvode.py
@@ -12,6 +12,7 @@
 cv = h.CVode()
 pc = h.ParallelContext()
 
+
 # remove address info from cv.debug_event output
 def debug_event_filter(s):
     s = re.sub(r"cvode_0x[0-9abcdef]* ", "cvode_0x... ", s)
diff --git a/test/gjtests/test_par_gj.py b/test/gjtests/test_par_gj.py
index d70c321333..59e89f7549 100644
--- a/test/gjtests/test_par_gj.py
+++ b/test/gjtests/test_par_gj.py
@@ -61,9 +61,7 @@ def mkcells(pc, ngids):
     assert nranks <= ngids
 
     for gid in range(ngids):
-
         if gid % nranks == myrank:
-
             cell = MyCell()
             nc = h.NetCon(cell.soma(0.5)._ref_v, None, sec=cell.soma)
             pc.set_gid2node(gid, myrank)
@@ -101,7 +99,6 @@ def mkgjs(pc, ngids):
 
     ggid = 2e6  ## gap junction id range is intended to not overlap with gid range
     for gid in range(0, ngids, 2):
-
         # source gid: all even gids
         src = gid
         # destination gid: all odd gids
@@ -128,7 +125,6 @@ def mkgjs(pc, ngids):
 
 
 def main():
-
     parser = argparse.ArgumentParser(description="Parallel transfer test.")
     parser.add_argument(
         "--sparse-partrans",
diff --git a/test/parallel_tests/test_bas.py b/test/parallel_tests/test_bas.py
index 6c2d38bdaf..4c5cf4de3b 100644
--- a/test/parallel_tests/test_bas.py
+++ b/test/parallel_tests/test_bas.py
@@ -335,7 +335,6 @@ def compare_dicts(dict1, dict2):
 
 
 def test_bas():
-
     # h.execute1(...) does not call mpi_abort on failure
     assert h.execute1("1/0") == 0
     assert h.execute1("2/0", 0) == 0  # no error message printed
diff --git a/test/pynrn/test_fast_imem.py b/test/pynrn/test_fast_imem.py
index 564737cc02..8f6bbe763a 100644
--- a/test/pynrn/test_fast_imem.py
+++ b/test/pynrn/test_fast_imem.py
@@ -256,7 +256,6 @@ def print_fast_imem():
 
 
 def test_fastimem_corenrn():
-
     if not coreneuron_available():
         return
 
diff --git a/test/pynrn/test_hoc_po.py b/test/pynrn/test_hoc_po.py
index abb1f6b8b9..5d7dfadc85 100644
--- a/test/pynrn/test_hoc_po.py
+++ b/test/pynrn/test_hoc_po.py
@@ -164,6 +164,7 @@ def test_2():
 
 # BBSaveState for mixed (hoc and python cells) Ring.
 
+
 # some helpers copied from ../parallel_tests/test_bas.py
 def subprocess_run(cmd):
     subprocess.run(cmd, shell=True).check_returncode()
diff --git a/test/pynrn/test_nrnste.py b/test/pynrn/test_nrnste.py
index d5bf746ab8..bfdf533ed5 100644
--- a/test/pynrn/test_nrnste.py
+++ b/test/pynrn/test_nrnste.py
@@ -51,7 +51,6 @@ def model():
 
 
 def test_ste():
-
     m1 = model()
     # one state ste with two self transitions
     var = m1["s"](0.5)._ref_v
diff --git a/test/pynrn/test_partrans.py b/test/pynrn/test_partrans.py
index 8ee420565d..f0a6bd6662 100644
--- a/test/pynrn/test_partrans.py
+++ b/test/pynrn/test_partrans.py
@@ -59,6 +59,7 @@ def expect_error(callable, args, sec=None):
 ks.gmax(0)
 ks.erev(0)
 
+
 # Cell with enough nonsense stuff to exercise transfer possibilities.
 class Cell:
     def __init__(self):
@@ -186,7 +187,6 @@ def check_values():
 
 
 def test_partrans():
-
     # no transfer targets or sources.
     mkmodel(4)
     run()
diff --git a/test/pynrn/test_template_err.py b/test/pynrn/test_template_err.py
index 61a2951670..4ed7c0aafb 100644
--- a/test/pynrn/test_template_err.py
+++ b/test/pynrn/test_template_err.py
@@ -3,7 +3,6 @@
 
 
 def test_template_err():
-
     h(
         """
 begintemplate TestTemplateErr1
diff --git a/test/rxd/3d/test_soma_outlines.py b/test/rxd/3d/test_soma_outlines.py
index a35082022f..89607849d0 100644
--- a/test/rxd/3d/test_soma_outlines.py
+++ b/test/rxd/3d/test_soma_outlines.py
@@ -32,7 +32,7 @@ def __init__(self, shift=(0, 0, 0)):
                     for i in range(sec.n3d())
                 ]
                 sec.pt3dclear()
-                for (x, y, z, diam) in pts:
+                for x, y, z, diam in pts:
                     sec.pt3dadd(x + sx, y + sy, z + sz, diam)
 
     yield (h, rxd, data, save_path, Cell)
diff --git a/test/rxd/conftest.py b/test/rxd/conftest.py
index 77d315f98d..79760b06df 100644
--- a/test/rxd/conftest.py
+++ b/test/rxd/conftest.py
@@ -1,7 +1,9 @@
+import ctypes
+import gc
 import os.path as osp
+
 import numpy
 import pytest
-import gc
 
 from .testutils import collect_data
 
@@ -77,7 +79,7 @@ def neuron_nosave_instance(neuron_import):
     rxd.rxd.rxd_include_node_flux1D(0, None, None, None)
     rxd.species._has_1d = False
     rxd.species._has_3d = False
-    rxd.rxd._zero_volume_indices = numpy.ndarray(0, dtype=numpy.int_)
+    rxd.rxd._zero_volume_indices = numpy.ndarray(0, dtype=ctypes.c_long)
     rxd.set_solve_type(dimension=1)
 
 
