From 2c0f8634f824800b339f0728d6dd25a4f7d3734f Mon Sep 17 00:00:00 2001 From: Inessa Pawson Date: Fri, 2 Dec 2022 20:36:18 +0000 Subject: [PATCH 001/202] Create development_ghcodespaces.rst and add the doc outline --- doc/source/dev/development_ghcodespaces.rst | 129 ++++++++++++++++++++ 1 file changed, 129 insertions(+) create mode 100644 doc/source/dev/development_ghcodespaces.rst diff --git a/doc/source/dev/development_ghcodespaces.rst b/doc/source/dev/development_ghcodespaces.rst new file mode 100644 index 000000000000..afd46ec2744e --- /dev/null +++ b/doc/source/dev/development_ghcodespaces.rst @@ -0,0 +1,129 @@ +.. _development_ghcodespaces: + + +Using GitHub Codespaces for NumPy development +============================================= + +This section of the documentation will guide you through: + +* using GitHub Codespaces for your NumPy development environment +* creating a personal fork of the NumPy repository on GitHub +* a quick tour of GitHub Codespaces and VSCode desktop application +* working on the NumPy documentation in GitHub Codespaces + +GitHub Codespaces +----------------- +`GitHub Codespaces`_ is + +TO DO + + +What is a codespace? +-------------------- +A codespace is a development environment that is hosted in the cloud. +Each codespace runs on a virtual machine hosted by GitHub. You can choose +the type of machine you want to use, depending on the resources you need. Various +types of machine are available, starting with a 2-core processor, 4 GB of RAM, +and 32 GB of storage. +You can connect to a codespace from your browser, from Visual Studio Code, from +the JetBrains Gateway application, or by using GitHub CLI. + + +Forking the NumPy repository +---------------------------- +The best way to work on NumPy as a contributor is by making a fork of the +repository first. + +#. Browse to the `NumPy repository on GitHub`_ and `create your own fork`_. +#. Browse to your fork. Your fork will have a URL like + https://github.com/inessapawson/NumPy, except with your GitHub username in place of ``inessapawson``. + + +Starting GitHub Codespaces +-------------------------- +TO DO + + +Quick workspace tour +-------------------- +You can develop code in a codespace using your choice of tool: + +* a command shell, via an SSH connection initiated using GitHub CLI. +* one of the JetBrains IDEs, via the JetBrains Gateway. +* the Visual Studio Code desktop application. +* a browser-based version of Visual Studio Code. + +In this quickstart, we will be using the VSCode desktop application as the editor. If you have not used it before, see the Getting started `VSCode docs`_ to familiarize yourself with this tool. + +Your workspace will look similar to the image below: + +TO DO + + +Development workflow with GitHub Codespaces +-------------------------------- +The :ref:`development-workflow` section of this documentation contains +information regarding the NumPy development workflow. Make sure to check this +before working on your contributions. + +TO DO + + +Rendering the NumPy documentation +--------------------------------- +You can find the detailed documentation on how the rendering of the documentation with +Sphinx works in the :ref:`howto-build-docs` section. + +The documentation is pre-built during your codespace initialization. So once +this task is completed, you have two main options to render the documentation +in GitHub Codespaces. + +Option 1: Using Liveserve +~~~~~~~~~~~~~~~~~~~~~~~~~ + +#. View the documentation in ``NumPy/doc/build/html``. You can start with + ``index.html`` and browse, or you can jump straight to the file you're + interested in. +#. To see the rendered version of a page, you can right-click on the ``.html`` + file and click on **Open with Live Serve**. Alternatively, you can open the + file in the editor and click on the **Go live** button on the status bar. + + .. image:: + :alt: + +#. A simple browser will open to the right-hand side of the editor. We recommend + closing it and click on the **Open in browser** button in the pop-up. +#. To stop the server click on the **Port: 5500** button on the status bar. + +Option 2: Using the rst extension +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +A quick and easy way to see live changes in a ``.rst`` file as you work on it +uses the rst extension with docutils. + +.. note:: This will generate a simple live preview of the document without the + ``html`` theme, and some backlinks might not be added correctly. But it is an + easy and lightweight way to get instant feedback on your work. + +#. Open any of the source documentation files located in ``doc/source`` in the + editor. +#. Open VSCode Command Palette with :kbd:`Cmd-Shift-P` in Mac or + :kbd:`Ctrl-Shift-P` in Linux and Windows. Start typing "restructured" + and choose either "Open preview" or "Open preview to the Side". + + .. image:: + :alt: + +#. As you work on the document, you will see a live rendering of it on the editor. + + .. image:: + :alt: + +To see the final output with the ``html`` theme, you need to +rebuild the docs with ``make html`` and use Live Serve as described in option 1. + + +FAQs and troubleshooting +------------------------- +TO DO + From 18bc0524849aabcce02716da104b963dedcaebff Mon Sep 17 00:00:00 2001 From: Inessa Pawson Date: Fri, 2 Dec 2022 23:42:40 -0500 Subject: [PATCH 002/202] Add reviewer feedback Co-authored-by: Craig Peters --- doc/source/dev/development_ghcodespaces.rst | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/doc/source/dev/development_ghcodespaces.rst b/doc/source/dev/development_ghcodespaces.rst index afd46ec2744e..87e6d2a95a0d 100644 --- a/doc/source/dev/development_ghcodespaces.rst +++ b/doc/source/dev/development_ghcodespaces.rst @@ -20,7 +20,7 @@ TO DO What is a codespace? -------------------- -A codespace is a development environment that is hosted in the cloud. +A codespace is an instance of Codespaces - and thus a development environment that is hosted in the cloud. Each codespace runs on a virtual machine hosted by GitHub. You can choose the type of machine you want to use, depending on the resources you need. Various types of machine are available, starting with a 2-core processor, 4 GB of RAM, From eebfe7eaf357cb336c69caaaa9baea1d26b4f4e5 Mon Sep 17 00:00:00 2001 From: Inessa Pawson Date: Fri, 2 Dec 2022 23:43:29 -0500 Subject: [PATCH 003/202] Add reviewer feedback Co-authored-by: Craig Peters --- doc/source/dev/development_ghcodespaces.rst | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/doc/source/dev/development_ghcodespaces.rst b/doc/source/dev/development_ghcodespaces.rst index 87e6d2a95a0d..f7f19a7b0548 100644 --- a/doc/source/dev/development_ghcodespaces.rst +++ b/doc/source/dev/development_ghcodespaces.rst @@ -13,7 +13,10 @@ This section of the documentation will guide you through: GitHub Codespaces ----------------- -`GitHub Codespaces`_ is +`GitHub Codespaces`_ is a service that provides cloud based development environments +so that you don't have to install anything on your local machine or worry about configuration. + +.. _https://github.com/features/codespaces TO DO From 928f0a246a00629df85d11de32b0d9a32106e415 Mon Sep 17 00:00:00 2001 From: Inessa Pawson Date: Fri, 2 Dec 2022 23:43:46 -0500 Subject: [PATCH 004/202] Add reviewer feedback Co-authored-by: Craig Peters --- doc/source/dev/development_ghcodespaces.rst | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/doc/source/dev/development_ghcodespaces.rst b/doc/source/dev/development_ghcodespaces.rst index f7f19a7b0548..389148e2cfb0 100644 --- a/doc/source/dev/development_ghcodespaces.rst +++ b/doc/source/dev/development_ghcodespaces.rst @@ -44,7 +44,10 @@ repository first. Starting GitHub Codespaces -------------------------- -TO DO +You can create a codespace from the green "Code" button on the repository home page, or click this |open| button + +.. |open| image:: https://github.com/codespaces/badge.svg +.. _open: https://github.com/codespaces/new?hide_repo_select=true&ref=main&repo=908607 Quick workspace tour From 68da466f99108086339fdc0d1c7ff0b08aba545b Mon Sep 17 00:00:00 2001 From: Inessa Pawson Date: Fri, 2 Dec 2022 23:44:00 -0500 Subject: [PATCH 005/202] Add reviewer feedback Co-authored-by: Craig Peters --- doc/source/dev/development_ghcodespaces.rst | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/doc/source/dev/development_ghcodespaces.rst b/doc/source/dev/development_ghcodespaces.rst index 389148e2cfb0..745c3a57bb05 100644 --- a/doc/source/dev/development_ghcodespaces.rst +++ b/doc/source/dev/development_ghcodespaces.rst @@ -54,7 +54,9 @@ Quick workspace tour -------------------- You can develop code in a codespace using your choice of tool: -* a command shell, via an SSH connection initiated using GitHub CLI. +* `a command shell, via an SSH connection initiated using GitHub CLI.`_ + +.. _https://docs.github.com/en/authentication/connecting-to-github-with-ssh * one of the JetBrains IDEs, via the JetBrains Gateway. * the Visual Studio Code desktop application. * a browser-based version of Visual Studio Code. From b873b15e867b9b0c8f65d466070d30125e8a65fd Mon Sep 17 00:00:00 2001 From: Inessa Pawson Date: Fri, 2 Dec 2022 23:44:22 -0500 Subject: [PATCH 006/202] Add reviewer feedback Co-authored-by: Craig Peters --- doc/source/dev/development_ghcodespaces.rst | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/doc/source/dev/development_ghcodespaces.rst b/doc/source/dev/development_ghcodespaces.rst index 745c3a57bb05..b9b202ce4487 100644 --- a/doc/source/dev/development_ghcodespaces.rst +++ b/doc/source/dev/development_ghcodespaces.rst @@ -57,7 +57,9 @@ You can develop code in a codespace using your choice of tool: * `a command shell, via an SSH connection initiated using GitHub CLI.`_ .. _https://docs.github.com/en/authentication/connecting-to-github-with-ssh -* one of the JetBrains IDEs, via the JetBrains Gateway. +* `one of the JetBrains IDEs, via the JetBrains Gateway.`_ + +.. _https://docs.github.com/en/codespaces/developing-in-codespaces/using-github-codespaces-in-your-jetbrains-ide * the Visual Studio Code desktop application. * a browser-based version of Visual Studio Code. From 11c3a70bffc9cea70bf82c6b21448f95f7d45712 Mon Sep 17 00:00:00 2001 From: Inessa Pawson Date: Fri, 2 Dec 2022 23:44:57 -0500 Subject: [PATCH 007/202] Add reviewer feedback Co-authored-by: Craig Peters --- doc/source/dev/development_ghcodespaces.rst | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/doc/source/dev/development_ghcodespaces.rst b/doc/source/dev/development_ghcodespaces.rst index b9b202ce4487..f99baa559c4f 100644 --- a/doc/source/dev/development_ghcodespaces.rst +++ b/doc/source/dev/development_ghcodespaces.rst @@ -60,7 +60,9 @@ You can develop code in a codespace using your choice of tool: * `one of the JetBrains IDEs, via the JetBrains Gateway.`_ .. _https://docs.github.com/en/codespaces/developing-in-codespaces/using-github-codespaces-in-your-jetbrains-ide -* the Visual Studio Code desktop application. +* `the Visual Studio Code desktop application.`_ + +.. _https://docs.github.com/en/codespaces/developing-in-codespaces/using-github-codespaces-in-visual-studio-code * a browser-based version of Visual Studio Code. In this quickstart, we will be using the VSCode desktop application as the editor. If you have not used it before, see the Getting started `VSCode docs`_ to familiarize yourself with this tool. From 256efb3f876915e37cf477350d26ab0bf0d73d90 Mon Sep 17 00:00:00 2001 From: Inessa Pawson Date: Fri, 2 Dec 2022 23:45:05 -0500 Subject: [PATCH 008/202] Update doc/source/dev/development_ghcodespaces.rst Co-authored-by: Craig Peters --- doc/source/dev/development_ghcodespaces.rst | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/doc/source/dev/development_ghcodespaces.rst b/doc/source/dev/development_ghcodespaces.rst index f99baa559c4f..722a0b4b136b 100644 --- a/doc/source/dev/development_ghcodespaces.rst +++ b/doc/source/dev/development_ghcodespaces.rst @@ -63,7 +63,9 @@ You can develop code in a codespace using your choice of tool: * `the Visual Studio Code desktop application.`_ .. _https://docs.github.com/en/codespaces/developing-in-codespaces/using-github-codespaces-in-visual-studio-code -* a browser-based version of Visual Studio Code. +* `a browser-based version of Visual Studio Code.`_ + +.. _https://docs.github.com/en/codespaces/developing-in-codespaces/developing-in-a-codespace In this quickstart, we will be using the VSCode desktop application as the editor. If you have not used it before, see the Getting started `VSCode docs`_ to familiarize yourself with this tool. From a7f66c1df2a159f0fdbf5d83d69b2781c99d36a7 Mon Sep 17 00:00:00 2001 From: Inessa Pawson Date: Sat, 3 Dec 2022 05:27:39 +0000 Subject: [PATCH 009/202] Clean up the formatting --- doc/source/dev/development_ghcodespaces.rst | 31 ++++++++------------- 1 file changed, 11 insertions(+), 20 deletions(-) diff --git a/doc/source/dev/development_ghcodespaces.rst b/doc/source/dev/development_ghcodespaces.rst index 722a0b4b136b..8f82e40829f7 100644 --- a/doc/source/dev/development_ghcodespaces.rst +++ b/doc/source/dev/development_ghcodespaces.rst @@ -13,16 +13,13 @@ This section of the documentation will guide you through: GitHub Codespaces ----------------- + `GitHub Codespaces`_ is a service that provides cloud based development environments so that you don't have to install anything on your local machine or worry about configuration. -.. _https://github.com/features/codespaces - -TO DO - - What is a codespace? -------------------- + A codespace is an instance of Codespaces - and thus a development environment that is hosted in the cloud. Each codespace runs on a virtual machine hosted by GitHub. You can choose the type of machine you want to use, depending on the resources you need. Various @@ -31,27 +28,26 @@ and 32 GB of storage. You can connect to a codespace from your browser, from Visual Studio Code, from the JetBrains Gateway application, or by using GitHub CLI. - Forking the NumPy repository ---------------------------- -The best way to work on NumPy as a contributor is by making a fork of the +The best way to work on the NumPy codebase as a contributor is by making a fork of the repository first. #. Browse to the `NumPy repository on GitHub`_ and `create your own fork`_. #. Browse to your fork. Your fork will have a URL like - https://github.com/inessapawson/NumPy, except with your GitHub username in place of ``inessapawson``. - - + https://github.com/inessapawson/numpy, except with your GitHub username in place of ``inessapawson``. + Starting GitHub Codespaces -------------------------- + You can create a codespace from the green "Code" button on the repository home page, or click this |open| button .. |open| image:: https://github.com/codespaces/badge.svg .. _open: https://github.com/codespaces/new?hide_repo_select=true&ref=main&repo=908607 - Quick workspace tour -------------------- + You can develop code in a codespace using your choice of tool: * `a command shell, via an SSH connection initiated using GitHub CLI.`_ @@ -71,20 +67,16 @@ In this quickstart, we will be using the VSCode desktop application as the edito Your workspace will look similar to the image below: -TO DO - - Development workflow with GitHub Codespaces --------------------------------- +------------------------------------------- + The :ref:`development-workflow` section of this documentation contains information regarding the NumPy development workflow. Make sure to check this -before working on your contributions. - -TO DO - +before you start working on your contributions. Rendering the NumPy documentation --------------------------------- + You can find the detailed documentation on how the rendering of the documentation with Sphinx works in the :ref:`howto-build-docs` section. @@ -136,7 +128,6 @@ uses the rst extension with docutils. To see the final output with the ``html`` theme, you need to rebuild the docs with ``make html`` and use Live Serve as described in option 1. - FAQs and troubleshooting ------------------------- TO DO From f44534282a274d767aa0dacd14e186e1241bc189 Mon Sep 17 00:00:00 2001 From: Inessa Pawson Date: Sat, 3 Dec 2022 05:52:01 +0000 Subject: [PATCH 010/202] Add links to the references --- doc/source/dev/development_ghcodespaces.rst | 18 ++++++++++-------- 1 file changed, 10 insertions(+), 8 deletions(-) diff --git a/doc/source/dev/development_ghcodespaces.rst b/doc/source/dev/development_ghcodespaces.rst index 8f82e40829f7..d751db5c8495 100644 --- a/doc/source/dev/development_ghcodespaces.rst +++ b/doc/source/dev/development_ghcodespaces.rst @@ -51,18 +51,10 @@ Quick workspace tour You can develop code in a codespace using your choice of tool: * `a command shell, via an SSH connection initiated using GitHub CLI.`_ - -.. _https://docs.github.com/en/authentication/connecting-to-github-with-ssh * `one of the JetBrains IDEs, via the JetBrains Gateway.`_ - -.. _https://docs.github.com/en/codespaces/developing-in-codespaces/using-github-codespaces-in-your-jetbrains-ide * `the Visual Studio Code desktop application.`_ - -.. _https://docs.github.com/en/codespaces/developing-in-codespaces/using-github-codespaces-in-visual-studio-code * `a browser-based version of Visual Studio Code.`_ -.. _https://docs.github.com/en/codespaces/developing-in-codespaces/developing-in-a-codespace - In this quickstart, we will be using the VSCode desktop application as the editor. If you have not used it before, see the Getting started `VSCode docs`_ to familiarize yourself with this tool. Your workspace will look similar to the image below: @@ -132,3 +124,13 @@ FAQs and troubleshooting ------------------------- TO DO +.. _GitHub Codespaces: https://github.com/features/codespaces +.. _NumPy repository on GitHub: https://github.com/NumPy/NumPy +.. _create your own fork: https://help.github.com/en/articles/fork-a-repo +.. _VSCode docs: https://code.visualstudio.com/docs/getstarted/tips-and-tricks +.. _command shell, via an SSH connection initiated using GitHub CLI: https://docs.github.com/en/authentication/connecting-to-github-with-ssh +.. _one of the JetBrains IDEs, via the JetBrains Gateway: https://docs.github.com/en/codespaces/developing-in-codespaces/using-github-codespaces-in-your-jetbrains-ide +.. _the Visual Studio Code desktop application: https://docs.github.com/en/codespaces/developing-in-codespaces/using-github-codespaces-in-visual-studio-code +.. _a browser-based version of Visual Studio Code: +https://docs.github.com/en/codespaces/developing-in-codespaces/developing-in-a-codespace + From 0577b75bc79521d57cbdc980cef50f19ad8fb244 Mon Sep 17 00:00:00 2001 From: Inessa Pawson Date: Sat, 3 Dec 2022 06:30:04 +0000 Subject: [PATCH 011/202] Add content to the FAQs and troubleshooting section --- doc/source/dev/development_ghcodespaces.rst | 14 ++++++++++++-- 1 file changed, 12 insertions(+), 2 deletions(-) diff --git a/doc/source/dev/development_ghcodespaces.rst b/doc/source/dev/development_ghcodespaces.rst index d751db5c8495..d1088d29a54c 100644 --- a/doc/source/dev/development_ghcodespaces.rst +++ b/doc/source/dev/development_ghcodespaces.rst @@ -122,7 +122,18 @@ rebuild the docs with ``make html`` and use Live Serve as described in option 1. FAQs and troubleshooting ------------------------- -TO DO + +**How long does my codespace stay active if I'm not using it?** +If you leave your codespace running without interaction, or if you exit your +codespace without explicitly stopping it, by default the codespace will timeout +after 30 minutes of inactivity. You can customize the duration of the timeout period +for new codespaces that you create. + +**Can I come back to a previous codespace?** +The lifecycle of a codespace begins when you create a codespace and ends +when you delete it. You can disconnect and reconnect to an active codespace without +affecting its running processes. You may stop and restart a codespace without losing +changes that you have made to your project. .. _GitHub Codespaces: https://github.com/features/codespaces .. _NumPy repository on GitHub: https://github.com/NumPy/NumPy @@ -133,4 +144,3 @@ TO DO .. _the Visual Studio Code desktop application: https://docs.github.com/en/codespaces/developing-in-codespaces/using-github-codespaces-in-visual-studio-code .. _a browser-based version of Visual Studio Code: https://docs.github.com/en/codespaces/developing-in-codespaces/developing-in-a-codespace - From a69d6a9bd8aaddc5b56e855f46f9503ebd5ca99d Mon Sep 17 00:00:00 2001 From: Inessa Pawson Date: Sat, 3 Dec 2022 16:20:28 +0000 Subject: [PATCH 012/202] Clean up the formatting --- doc/source/dev/development_ghcodespaces.rst | 17 +++++++++-------- 1 file changed, 9 insertions(+), 8 deletions(-) diff --git a/doc/source/dev/development_ghcodespaces.rst b/doc/source/dev/development_ghcodespaces.rst index d1088d29a54c..29308b69401d 100644 --- a/doc/source/dev/development_ghcodespaces.rst +++ b/doc/source/dev/development_ghcodespaces.rst @@ -42,7 +42,7 @@ Starting GitHub Codespaces You can create a codespace from the green "Code" button on the repository home page, or click this |open| button -.. |open| image:: https://github.com/codespaces/badge.svg +.. |open| image:: https://github.com/codespaces/badge.svg_ .. _open: https://github.com/codespaces/new?hide_repo_select=true&ref=main&repo=908607 Quick workspace tour @@ -50,12 +50,14 @@ Quick workspace tour You can develop code in a codespace using your choice of tool: -* `a command shell, via an SSH connection initiated using GitHub CLI.`_ -* `one of the JetBrains IDEs, via the JetBrains Gateway.`_ -* `the Visual Studio Code desktop application.`_ -* `a browser-based version of Visual Studio Code.`_ +* a command shell, via an SSH connection initiated using GitHub CLI._ +* one of the JetBrains IDEs, via the JetBrains Gateway._ +* the Visual Studio Code desktop application._ +* a browser-based version of Visual Studio Code._ -In this quickstart, we will be using the VSCode desktop application as the editor. If you have not used it before, see the Getting started `VSCode docs`_ to familiarize yourself with this tool. +In this quickstart, we will be using the VSCode desktop application as the editor. +If you have not used it before, see the Getting started `VSCode docs`_ to familiarize +yourself with this tool. Your workspace will look similar to the image below: @@ -142,5 +144,4 @@ changes that you have made to your project. .. _command shell, via an SSH connection initiated using GitHub CLI: https://docs.github.com/en/authentication/connecting-to-github-with-ssh .. _one of the JetBrains IDEs, via the JetBrains Gateway: https://docs.github.com/en/codespaces/developing-in-codespaces/using-github-codespaces-in-your-jetbrains-ide .. _the Visual Studio Code desktop application: https://docs.github.com/en/codespaces/developing-in-codespaces/using-github-codespaces-in-visual-studio-code -.. _a browser-based version of Visual Studio Code: -https://docs.github.com/en/codespaces/developing-in-codespaces/developing-in-a-codespace +.. _a browser-based version of Visual Studio Code: https://docs.github.com/en/codespaces/developing-in-codespaces/developing-in-a-codespace From f45ffe854bb2e3906d66e2e926cb770bfeddcd96 Mon Sep 17 00:00:00 2001 From: Inessa Pawson Date: Fri, 9 Dec 2022 17:35:59 +0000 Subject: [PATCH 013/202] Create 'ghcodespaces-imgs' folder and add image for the quickstart --- .../ghcodespaces-imgs/codespaces-codebutton.png | Bin 0 -> 8619 bytes 1 file changed, 0 insertions(+), 0 deletions(-) create mode 100644 doc/source/dev/ghcodespaces-imgs/codespaces-codebutton.png diff --git a/doc/source/dev/ghcodespaces-imgs/codespaces-codebutton.png b/doc/source/dev/ghcodespaces-imgs/codespaces-codebutton.png new file mode 100644 index 0000000000000000000000000000000000000000..da3e7e3bde2f9208ee252662fb99c9fe22e30c83 GIT binary patch literal 8619 zcmb7pWmH^IvTk={-AI5YK!D)x7BslKySqCChv4pRX`BE-I!Fi!8l2z+4Gsyx-R*T| z=FQA{@6Ww^tvXews=lhTYu8@KV%1b+vCxUp0RRA&yquHfO!pU>z^*-cMgZ4FtV)EMe{J1X>wy)Cr~4{qUd@Z%hS_L~RcPZ+;hcF6S;0 z0h;{%H0;@`vBY3yVg%%5BgENx{ZzszRz<+35Im0clV2L%Mn^F5m`cXh9*GJ2l`MwL?n>08k$?RAEhFIx&j5u;LJlnPYIzLO;^j zz{D33EJ}Yd9{L#{z?C?VZVfE*!#=H%2qtJMy@6N|#)`23#T=1)fq}THfR9|4xPE?` z8J}NTysl)Ae9@28#@+ET_k!<^Nb=IJt%kB@*imed(xUZMHs8Y&%ji>9n^9j8Hp#pl zmA+IP*IT_FLjlc_j2u+=Y#M4h9eu}`fIg7+GEl6FN?IySft=^}cL8{C2;^gY2q6^Z zBWJI9+ER`kPhl$KvrP$1T?|2Gqb}u$dB8@Wgr8lQfo;5#LfaytK|bRqeCFN{=G0X` zHHRdv0yT7gN|YPa{yFd}UMiLmN0ags({uU(u^Pz7Mj?7ig<9?}a=o!cKT;VtGEWS} zU$SRJpncf4jLdC-`!)y5!vZ->o#N$264f`uQA&Ej+ClK?z!kB34#FC326K9>Mcm;5 zY3$!rI8hPR9s@88T6u`W>-MRzHQyPd0;bVK&Am;6Z%b~puE399+c?C9302ub;x(dcBR6Yyq3z=RTXIP58ZX&O!lkRV6?s6_t#uj>U6+K&Q zT@XtGq+cSvHQx-KXhgFT*!`TTZ60KM=SmcK#{0wnIU%|Nkqo3{K1ft^T724aFs@;C zbygPNv0trSK$3d(ZaYvj2)JL`G1p6A84dTGm){3@KmUNlvX88j%wsu_;cNFsm`Kk! zd}RY|V<^zB`8Kt=bnm5&`OTxcDX;Ij=~woY6?Aym#L=$CI6;H4irU~^e_>=bK>ml?o6JFGj1 zuKltu5NEA3f?&x$s_VHP=ygsq^D%NT1vny14hI7&&Xj}vfhBCu2(==^15?o)&3vSS7!FiIvb6Y}gZDep z9j?cM^}W|>-l+zexu+T)q=ytZuKUru2IDRS&mDE_+q*UNq^@)~5m@qgfA$9cHCr2j zXrgH!`Nr}!A?Tf%k{iu6^mBxJ1j{!q3C`jKc(_}R8|q>Cvv04dQU_@kq3vrXO0+h3 zwm8{PKIj!5Nvw14Krb0I)=JKU<|f@jUPuF2mD2=kiuMZgiu@tIOY4|2I#{>G;X$k~ z0aIn8KB6P1H>DJ%zEW>uoPBPpz#=V{tD>*6pkiNSRN{rHlNQsj9Vww|KlipLr_AU0VJ6>O~ zgkxYb>_zOQy3?wY%_skmad`kU z!F*_q<2nH);UIxK;hAs=td>ld-LPKEwcaG&q@|;-<7;rkG|f{np!|CDg$>ZgqLIgje#8WRuJ5G7_MzZS-i))06PbA($Ew4M#fq)DW2zPB zszqmCkYaUti*>~>;_r0dU6{E)aO!Z^I@BEMY1XvYO3&`qjO%x{d~BBgsBfidd$u&& zmE~w?WoQ{Np5#Jkm+h)+?K29qJ8~|x?40bF0lqnQ!x7LDH1d`r6(;RVA|d@LgCldD zkdjbI>^>d)yVsk^tJ>ZF&xlu&H|)r0``)2!X0R!hSr$fe)7RHSJ7@j%`?C6%QYzU| z@)?fZ#1G-jtIbmvc_hoMBhE>N?LQrTWPOV7=&lUOFq1jS;)U{rL<0Q%hJ~*Dy#4k4 z$^)E_zwFd*lWw>FxNF1irk}S>8dopG?tpcmbf5)2oqL{sKlyoZ71(rOxBlm#l>E-{ z`s}{twgn9innL=7+=P~gb_)6cB1h3jg@kz{3tRqdY+MMKuMaa0v+j-#U-b+WXyi|% z)RXg-lb2Jhbg|R0ll~LV5f86{=fMx%l8=ej6LBMADq}Kn`C93WL|XEGlJ4LOFrRuo zXJw+SrrK3+l5Ar6VvZ?D=P|O&d1X;!NyGW(BSjX;SHa8R0%xP(rFzR)%guhBq#$BZ zreK@hy@4x}%WJn*Li&E1&e&>xyd6{$%deZzFo?N~gH9<;Y+901>dJ~rV zxViN1(fO3g(e2~86I1jsWJlz85^vX;)*F?cMznLs8}A!+Y~RFzq^(QXIAx6}gWr*+ zwhP<^sW^>|6+A9wEIs&bwVk(7LyhH=w$7hVGfr1D$&;4%O_3y+*zSz^V_tY@wjhs!Fi$MYvXo#_9C7u zBhiiXji1J3Y-~qd@+<{x*9($b*FAkkOUJ(FUi}QrzWMO`shPrByhkEE(vwi+k@7w| z&tlX<|727;IG&fipD>=Vg~i>lA$TYoDn8Vwkv-KgrK)(N$o|N`J8(*Vmu=1FsDIcR zIE}u6J`_j7jHG*LP~KQ=H?uiosWVq+UdyO|Hn%wB$ez)f?Q9}z{9bR)gv{8abH(8y z?xK)M3V)6{ocYR?V+C&2bC(#FsLPAuyx6i}<+<}a*|68p#TjeWz|dM#`%~iQTDPCm z2SY!{AGRJeFP@c>mcJG`%Gh^W#qZqnYSw*o;j+2>-Eo3gT6r4=2{5>d+OJ*RZgSlV z{{1+Gv=*|_6<;|0w!@uc*KC^dNb)ZDB;$Ye9OW-hd-L9Emd0zVg)@P zo#q!bx97K23a&)oo`)SpQWLhb&l;b$Y5m-v47}z`UVYZ$`{{?t%-Y*B& znO)5E^-)H`0f_+zQx`dV&U|SuOJ4-mZSGjRYqwiGT{}B8ecvA)E(Jsc&|WnkWealz zt6hA3IJ)~O{4-e?({KKsVSRFW;C_I;aIi3NSMNIGv1vbdp>cP+ZampL>dmK)7f&Ud z<>%I>x+mmx?%3@*PsjZU>hx%xc*deqfaH5w21@jJR*$v!8( zJiJ|dSYH~*NFKkf2&M{RdUASdU03{(9q{1y@Sp)p;B$N4WhTkZ4fJiq1Nbuuz3vJi zdDFJb#!nHm`zRRF_4Zr!-A0Hn2+j=-DQg8t^>7c<&DT&?bes4^sA7UD^M9&o#tTi4 zYFo#nx=KW>JU+J20aAzo*DQNSM?dFRpZs29Uh)DGZ>nEcYQ!9m!TZ!=^IRRmkEGv- zKF|#u1r#N8kp`|lVVE>0nLhWGeua4Th_lv{w^3FGFd<|x02xROKtV`A1c?Ai{w>P@ z830KC(1QSgXnO$izkE~>{O?FX&|l0yIZ|2_01a^lMUZb1=-=LJMM(da^$<3IxTd7M zJc4UldRSY#c-pyo!6h1F5DJK!oW3UjKtTJKfbtqN$B6hd_F8&gddfDJUp}JgjU4HKb(z1xK6-Q`vcWxe2nf`}p{<`Eawjdf2ja3J3_Wb8xY9 zaj_yiSUvq*yv%)BT|BA(8RY-Qk+Sx*^ssmHvUhc%_#4;U!u5@pFcsC`ME@TDyiRLh z`~PHe@%-1c5EEqoYhmYP<6!@HYy?#3uU1ga-q+emU&`JYQ8Ppi5q^H5f4KjDhW{k| zFQDFkfLvU!{u}vUmj4&2?P={H>FSKg=q2)>)%q9szm5L_3bFs4_c7Exvq zbRqVCFPR8>1jp6iRexzOrK*MCh#vdLU_l%i5cHQL2+eHcV^unWv&c({Yxx5A-$9hL zWM2$CeckWg>0SpKluO4J@rp^KWNN6rg4Mp_IjJ;oT=dr_QEqBR#&fo`oT$i~b;z%< z@9Tf{sgkp=R6$s*x=0V6XdrDgOsi$KkUl09Xh@Jfz-H_-{VRWTvpx65=J%-UcITOm zw|7c27n+Au2>5ekNCNU7f8dOkD%U%qn1ZvW{G)d41 z+gLZBZg5w7l)~Wrcg0^Qts2i-CA!DB#KxX^NOh${atzIRbIf@gdd$M)T_uqDeW2??rVQ_0hHtTrH3*}E94cyI{$`W!JesMXe?Me;l1%KO~wz|62ezN&+fvPs}`E09r~ zi3jg$Bt@=2AjzfqnmP+Sbo&}1x%49a>wBW&#TsHW1BSlHJd;kgsxF>dJ|xI( zRvzLpx3>f@E@VbxVPOeBW_Vd@!)Z|TY8d;5dx-3&9E+cwi+^atrx9@s*`fwf0of#S z^-+!A5j;AW?&oEO=1eefF8ntIH^TAn}=eNtqlKV0}+OVDG&b7ONaOdHlOZ zUPX)4=W9(5ifRjbSZ`9Wm5Q|4(r6gdz(Q1A6;?$bW-QFaL|+=-M$!<<1Cv&Tb@dKP z&~1b%4px~VX;iTxav|d}yN(83*|qNi_EKIrov|=>Jfutn+kdU-~T-8OIodv^aoi)F7#@V2}*7=m9>M2IkL4wB&*mqbSuH0MV>S@WG7# zl};^;!L(}aFjII1oo6aar7Nb(mSaK`Idmmx!p=_SjVEcH)>S%yUwyX}^>BDF+O;0vt$bLq>WW4QNcB9^de2)ILjm+o_DIH|a2=^n zR2V4hwnSFoSwz$GxkZwj#caX#5|~^m-vGcl6EyOaw@if zyMKSdJZt&YmQx4IcD7HVDMwLnFdv=TH>%FGD#}1 zVazvuu`o-P%~W5aW0?HjKaz@zHt4 znE%F5ztjT?N{WpQ_Dr_WGW+4tMfB;X%{0FfxI`uTET#_aNQ<=4Uk4d?eO5)XF}a-0^D z!}XF1u(WnLTsI^TYJWQ|4?YqGQ+9|?5I228`!3+Un*D0d=rU*3p4Rx~dMe1P!mS`z zSNEv4ehRI1$22S%*t*FLXI8aokR5k?M~8I+>0K8HV6o5B4_A3~NuAM4QQZhkyY1je zU(}b0e4Dwp+{W^w`G=?tm2E(dQ(+UCJgL9oWQwZYvIE1w>Ex5k2QxwP~2%Q#`P#Fv{-^4!}WMw%K{TqC=l zG#+=zDl*91#{~&~3dx66YnL9$@u+-(s^};cJ0u< z`F@n6)`m1bD#};0&=1y6@55DpFIBV4dL480p2vrU9q2L&uH-w9{G{~f^pm6dq-Z39rQu@SeCFV1^EB~2K4WJ^S~G_P)nNl>BweUjdmCDrW&gu+Ypio)v6Me` zu1bM9aPfpRwL_FS zcx55II6IiYYsp#U?W68|SjGNveU~lucWM=@EM<)eIjmQ7yyn~Pyz@S_ayXLtYEi`3 z77cH{3!q8-BLk{iHIo#YI^pn2VPR*L&1`8!Um{snP{$>* z(`WdG;yU5N9BWT9_*CKDVUcKn)mgLf{NN+(y&PyUCfFT%+&*jRxvYeDHQs&lQ*?g5 z=jDa9u!zL82bPpf%LVlb4YhokUm4N#P1=sfLSPU(mCC*0M~8egmi2|0FJJJ^R9Nxs z&j#a63Mnd;j8pp{^9_MGSzh_Hr>=A>{c+@_QhBlp{@3OT@uDYXyUh_((=oy{UdX5F zSMQ=iW@FTU=)gbMpXeOpAo`Q#kiDU1wciEb-jF(9g0Qr~)USN8=X~G~5znv#9vG!l~Dn!NLI+y9|5`1@x@hEIhbw;3AvG4yqw@a z(_z)jh+Tn|gqh zU0mbCSZ-isA%yDs&aN3!D-)kCITz2>p@dnxjL-cu0q=%8DKKi;T~=yQ=ycnr=h(kg zSBik1A~lTVYpncz*%EyQ#DMV6D+!R!;mr{&LyjAsC7Ol@|rXrj%Y@cDj zq1PzPBUSIK51TTI6Tw{|oiBNP zx#vkOtG+4W*J)pCb4*)`q!vtd{r=hXM5_Y{qWW@vTK$n(KYlKt#q*q8FobT6XqEr5 znR4!>ySGwS=21JEB_cK*+SSE4lwNB4o0?&PWRy&P#06DCHEg@AeV*W zqqxVFVC}}UN+_xs#CcHe$&Tfu`;48i;QH?f;Z6o~32KcA_zMimaa}OVNAY3y_5P-g zc&vK8&1wF$Z$ywORIqvu!)^#OvfGhW6oZ}x(U5K{33Fga2MdpCXSyk+bF?jN%^3MD zfzoWfuGTV-->?^FOq+OZjrq6_Y{Z0K7XOI4WL)s+C+)wv)AeY!SNv8Gk)$9(oIDLp zLDhW$!mnU6{%Ha^KOMNu7DZc5F&aGR+`kueYVW|Vit?IRFtoJMA9U0kP2ewc4fYbB zb(j1@l|zm_!HKM2Y#8gKRz^(@lt22Cp*@#6Qn5iq zTcCoU;4OhjLYwhC)YEBNlu6H%6kPzw=(1B(Tz-KjOSm!ILoysKUK>(9Y|`kSD_B+s z&OExl!BJhrheC$DMUP5Ro5x=B0PWXiW13zcR?gG^LK)+*5%$+|rH_kWEM+481l`eZ z7yjK;cs`=+EX|{v)%?r2#lbl@vw&)B-9sBLS4PBjdh6}W<15)t0 zO=V7b2iKwBv)s?OhOG&zA$|(cJb%X9N@fbx@7M$4Y=0$_)TAXdPp8Xl=0B5GTkscB zgbW#^^;85`<>g$SgZpxV>a|JAClIjK7Gu!3v zF>P=mZ{aDBeZ610z5H`3*oT{TQAw(%tdBYs8UfR9n~xS{yyG`4^km&61yg|zPX0*7 z!fu)_y_8Hg!N=!l&E{qo!BzM#wZkQXdzqaU%dwUW_ouN{cWPp7%Zxn+R_kKdZG% z!uYtKD@Eao922r4$o`V#X+OYY#IdRazgBlkZb{h>U`!F9rbS%sA-9V~}@Dn-FOjcl1l=FH4D zuo2pL_M;S}4Pr~s57pl0lh~_@oaK9}AFni#Cs05(LI!F!kX2yf$?)DFeS6(mEa;#O zBKr~u<+daU=`gCoF#E2?*NUkvt%-0>aJsqS$9sfzT*EE-1$n^geNverLqm+$3^usl z%lw#$UkO|ur_ifQ7%_~=fR-g>`u=$SGrJ)~@A`Y@_^u3rEI$LDh~ zs<&8+P(i!)#?>k7g%l-4WFu0bW*%;Z7E-`#F_Z*X&X>j{pThI=1x>Xeav^kdbQTA# zc2bXUm79k5v(c#&itXyUgH!mfLFZ(8n)H2wN(G8p* z>CtYWDaYRj2fH>0RN=pNO`O_4C9}#NF~O%g)JiSc#U`wyPirO?j(7z`E?4lZi2jUc zkTyJ!L0Dhk%^oI9d|Af9QG>!@D0lLmAlwwTl(e+Ctt~5~&u{VXHj>uYM$?BixwPn{ zsn)8&DJ|S(8r)u0WMOL_7rE1Ygd!pf?96OnIutqzo-7z_>@q^WX!X49d`)m{IkE3o z1WBB98M*P6=%HQ;h9YTf*Aq49+*e;-=1X3vcIN7~olzZGK&g?j-MnJ={lmlBuV2>F za3?B?W~Bg$h6sE69bRKOCPm}|e4wi Date: Fri, 9 Dec 2022 17:43:09 +0000 Subject: [PATCH 014/202] Clean up the formatting of some sections --- doc/source/dev/development_ghcodespaces.rst | 77 +++++---------------- 1 file changed, 17 insertions(+), 60 deletions(-) diff --git a/doc/source/dev/development_ghcodespaces.rst b/doc/source/dev/development_ghcodespaces.rst index 29308b69401d..b57b90a2174e 100644 --- a/doc/source/dev/development_ghcodespaces.rst +++ b/doc/source/dev/development_ghcodespaces.rst @@ -14,22 +14,24 @@ This section of the documentation will guide you through: GitHub Codespaces ----------------- -`GitHub Codespaces`_ is a service that provides cloud based development environments -so that you don't have to install anything on your local machine or worry about configuration. +`GitHub Codespaces`_ is a service that provides cloud based +development environments so that you don't have to install anything +on your local machine or worry about configuration. What is a codespace? -------------------- -A codespace is an instance of Codespaces - and thus a development environment that is hosted in the cloud. -Each codespace runs on a virtual machine hosted by GitHub. You can choose -the type of machine you want to use, depending on the resources you need. Various -types of machine are available, starting with a 2-core processor, 4 GB of RAM, -and 32 GB of storage. -You can connect to a codespace from your browser, from Visual Studio Code, from -the JetBrains Gateway application, or by using GitHub CLI. +A codespace is an instance of Codespaces - and thus a development +environment that is hosted in the cloud. Each codespace runs on a virtual +machine hosted by GitHub. You can choose the type of machine you want to use, +depending on the resources you need. Various types of machine are available, +starting with a 2-core processor, 4 GB of RAM, and 32 GB of storage. +You can connect to a codespace from your browser, from Visual Studio Code, +from the JetBrains Gateway application, or by using GitHub CLI. Forking the NumPy repository ---------------------------- + The best way to work on the NumPy codebase as a contributor is by making a fork of the repository first. @@ -37,15 +39,13 @@ repository first. #. Browse to your fork. Your fork will have a URL like https://github.com/inessapawson/numpy, except with your GitHub username in place of ``inessapawson``. -Starting GitHub Codespaces +Starting GitHub Codespaces - draft -------------------------- -You can create a codespace from the green "Code" button on the repository home page, or click this |open| button - -.. |open| image:: https://github.com/codespaces/badge.svg_ -.. _open: https://github.com/codespaces/new?hide_repo_select=true&ref=main&repo=908607 +You can create a codespace from the green "Code" button (image to be added) +on the repository home page, or click on this `open (image to be added)`_ button -Quick workspace tour +Quick workspace tour - draft -------------------- You can develop code in a codespace using your choice of tool: @@ -68,7 +68,7 @@ The :ref:`development-workflow` section of this documentation contains information regarding the NumPy development workflow. Make sure to check this before you start working on your contributions. -Rendering the NumPy documentation +Rendering the NumPy documentation - draft --------------------------------- You can find the detailed documentation on how the rendering of the documentation with @@ -78,50 +78,6 @@ The documentation is pre-built during your codespace initialization. So once this task is completed, you have two main options to render the documentation in GitHub Codespaces. -Option 1: Using Liveserve -~~~~~~~~~~~~~~~~~~~~~~~~~ - -#. View the documentation in ``NumPy/doc/build/html``. You can start with - ``index.html`` and browse, or you can jump straight to the file you're - interested in. -#. To see the rendered version of a page, you can right-click on the ``.html`` - file and click on **Open with Live Serve**. Alternatively, you can open the - file in the editor and click on the **Go live** button on the status bar. - - .. image:: - :alt: - -#. A simple browser will open to the right-hand side of the editor. We recommend - closing it and click on the **Open in browser** button in the pop-up. -#. To stop the server click on the **Port: 5500** button on the status bar. - -Option 2: Using the rst extension -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -A quick and easy way to see live changes in a ``.rst`` file as you work on it -uses the rst extension with docutils. - -.. note:: This will generate a simple live preview of the document without the - ``html`` theme, and some backlinks might not be added correctly. But it is an - easy and lightweight way to get instant feedback on your work. - -#. Open any of the source documentation files located in ``doc/source`` in the - editor. -#. Open VSCode Command Palette with :kbd:`Cmd-Shift-P` in Mac or - :kbd:`Ctrl-Shift-P` in Linux and Windows. Start typing "restructured" - and choose either "Open preview" or "Open preview to the Side". - - .. image:: - :alt: - -#. As you work on the document, you will see a live rendering of it on the editor. - - .. image:: - :alt: - -To see the final output with the ``html`` theme, you need to -rebuild the docs with ``make html`` and use Live Serve as described in option 1. - FAQs and troubleshooting ------------------------- @@ -140,6 +96,7 @@ changes that you have made to your project. .. _GitHub Codespaces: https://github.com/features/codespaces .. _NumPy repository on GitHub: https://github.com/NumPy/NumPy .. _create your own fork: https://help.github.com/en/articles/fork-a-repo +.. _open: https://github.com/codespaces/new?hide_repo_select=true&ref=main&repo=908607 .. _VSCode docs: https://code.visualstudio.com/docs/getstarted/tips-and-tricks .. _command shell, via an SSH connection initiated using GitHub CLI: https://docs.github.com/en/authentication/connecting-to-github-with-ssh .. _one of the JetBrains IDEs, via the JetBrains Gateway: https://docs.github.com/en/codespaces/developing-in-codespaces/using-github-codespaces-in-your-jetbrains-ide From 8fdefd5a0956cee53c78b568028ac900c047c06e Mon Sep 17 00:00:00 2001 From: Matthias Diener Date: Mon, 16 Sep 2024 12:20:57 -0500 Subject: [PATCH 015/202] DOC: document type promotion with Python types Closes #27325 --- doc/source/reference/arrays.promotion.rst | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) diff --git a/doc/source/reference/arrays.promotion.rst b/doc/source/reference/arrays.promotion.rst index 976d59acb054..df88dd20ec5b 100644 --- a/doc/source/reference/arrays.promotion.rst +++ b/doc/source/reference/arrays.promotion.rst @@ -201,6 +201,25 @@ This leads to what may appear as "exceptions" to the rules: In principle, some of these exceptions may make sense for other functions. Please raise an issue if you feel this is the case. +Notable behavior with Python builtin type classes +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +When combining Python's builtin scalar *types* (i.e., ``float``, ``int``, +or ``complex``, not scalar *values*), the promotion rules can appear +surprising: + + >>> np.result_type(7, np.array([1], np.float32)) + dtype('float32') # The scalar value '7' does not impact type promotion + >>> np.result_type(type(7), np.array([1], np.float32)) + dtype('float64') # The *type* of the scalar value '7' does impact promotion + # Similar situations happen with Python's float and complex types + +The reason for this behavior is that NumPy converts ``int`` to its default +integer type, and uses that type for promotion: + + >>> np.result_type(int) + dtype('int64') + Promotion of non-numerical datatypes ------------------------------------ From 904a6f5cd04cedc05472739f6bbdf7a32613baf9 Mon Sep 17 00:00:00 2001 From: Matthias Diener Date: Wed, 30 Oct 2024 13:02:27 -0500 Subject: [PATCH 016/202] add reference to Python type conversion --- doc/source/reference/arrays.dtypes.rst | 7 +++++-- doc/source/reference/arrays.promotion.rst | 2 ++ 2 files changed, 7 insertions(+), 2 deletions(-) diff --git a/doc/source/reference/arrays.dtypes.rst b/doc/source/reference/arrays.dtypes.rst index 8aa7170df065..4293fe279302 100644 --- a/doc/source/reference/arrays.dtypes.rst +++ b/doc/source/reference/arrays.dtypes.rst @@ -179,11 +179,14 @@ Generic types to an array of ``float64``, even though ``float32`` is a subdtype of ``np.floating``. +.. _dtype-constructing-from-python-types: Built-in Python types - Several python types are equivalent to a corresponding + Several Python types are equivalent to a corresponding array scalar when used to generate a :class:`dtype` object: + =================== =============== + Python type NumPy type =================== =============== :class:`int` :class:`int\_` :class:`bool` :class:`bool\_` @@ -274,7 +277,7 @@ Array-protocol type strings (see :ref:`arrays.interface`) .. admonition:: Note on string types For backward compatibility with existing code originally written to support - Python 2, ``S`` and ``a`` typestrings are zero-terminated bytes. + Python 2, ``S`` and ``a`` typestrings are zero-terminated bytes. For unicode strings, use ``U``, `numpy.str_`. For signed bytes that do not need zero-termination ``b`` or ``i1`` can be used. diff --git a/doc/source/reference/arrays.promotion.rst b/doc/source/reference/arrays.promotion.rst index 6432461c4473..d6d1311217be 100644 --- a/doc/source/reference/arrays.promotion.rst +++ b/doc/source/reference/arrays.promotion.rst @@ -220,6 +220,8 @@ integer type, and uses that type for promotion: >>> np.result_type(int) dtype('int64') +See also :ref:`dtype-constructing-from-python-types` for more details. + Promotion of non-numerical datatypes ------------------------------------ From 06c06a882b09a0f4df63d2cc6445d4e745a1b82d Mon Sep 17 00:00:00 2001 From: Matthias Diener Date: Wed, 30 Oct 2024 15:32:37 -0500 Subject: [PATCH 017/202] reword footnote --- doc/source/reference/arrays.promotion.rst | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/doc/source/reference/arrays.promotion.rst b/doc/source/reference/arrays.promotion.rst index d6d1311217be..11d19d72bccc 100644 --- a/doc/source/reference/arrays.promotion.rst +++ b/doc/source/reference/arrays.promotion.rst @@ -277,4 +277,4 @@ could drastically slow down evaluation. precision of NumPy scalars or 0-D arrays for promotion purposes. .. [#default-int] The default integer is marked as ``int64`` in the schema - but is ``int32`` on 32bit platforms. However, normal PCs are 64bit. + but is ``int32`` on 32bit platforms. However, most modern systems are 64bit. From e23bd3360efa19f6cba48f8bf54e25eef1ae65e5 Mon Sep 17 00:00:00 2001 From: Saransh Chopra Date: Wed, 2 Apr 2025 12:38:38 +0100 Subject: [PATCH 018/202] DOC: update array API standard version in compatibility page --- doc/source/reference/array_api.rst | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/doc/source/reference/array_api.rst b/doc/source/reference/array_api.rst index 69b51215e555..584f55a76fcd 100644 --- a/doc/source/reference/array_api.rst +++ b/doc/source/reference/array_api.rst @@ -5,12 +5,12 @@ Array API standard compatibility ******************************** NumPy's main namespace as well as the `numpy.fft` and `numpy.linalg` namespaces -are compatible [1]_ with the -`2022.12 version `__ +are compatible with the +`2023.12 version `__ of the Python array API standard. NumPy aims to implement support for the -`2023.12 version `__ +`2024.12 version `__ and future versions of the standard - assuming that those future versions can be upgraded to given NumPy's :ref:`backwards compatibility policy `. @@ -32,7 +32,8 @@ rather than anything NumPy-specific, the `array-api-strict NumPy 1.22.0 was the first version to include support for the array API standard, via a separate ``numpy.array_api`` submodule. This module was marked as experimental (it emitted a warning on import) and removed in - NumPy 2.0 because full support was included in the main namespace. + NumPy 2.0 because full support (2022.12 version [1]_) was included in the main namespace (with + 2023.12 version support in NumPy 2.1). :ref:`NEP 47 ` and :ref:`NEP 56 ` describe the motivation and scope for implementing the array API standard From 9f6a4d9f872643e85a8d2684875b31b2614a7aa1 Mon Sep 17 00:00:00 2001 From: Saransh Chopra Date: Wed, 2 Apr 2025 13:37:05 +0100 Subject: [PATCH 019/202] 2024.12 support is in progress --- doc/source/reference/array_api.rst | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/doc/source/reference/array_api.rst b/doc/source/reference/array_api.rst index 584f55a76fcd..2bc46a6d926c 100644 --- a/doc/source/reference/array_api.rst +++ b/doc/source/reference/array_api.rst @@ -11,8 +11,8 @@ of the Python array API standard. NumPy aims to implement support for the `2024.12 version `__ -and future versions of the standard - assuming that those future versions can be -upgraded to given NumPy's +(in progress) and future versions of the standard - assuming that those future +versions can be upgraded to given NumPy's :ref:`backwards compatibility policy `. For usage guidelines for downstream libraries and end users who want to write From e0793182120f5fe90ed89d20e41383bc0d952f5b Mon Sep 17 00:00:00 2001 From: Saransh Chopra Date: Wed, 2 Apr 2025 13:37:58 +0100 Subject: [PATCH 020/202] better formatting --- doc/source/reference/array_api.rst | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/doc/source/reference/array_api.rst b/doc/source/reference/array_api.rst index 2bc46a6d926c..135db1f948c3 100644 --- a/doc/source/reference/array_api.rst +++ b/doc/source/reference/array_api.rst @@ -32,8 +32,8 @@ rather than anything NumPy-specific, the `array-api-strict NumPy 1.22.0 was the first version to include support for the array API standard, via a separate ``numpy.array_api`` submodule. This module was marked as experimental (it emitted a warning on import) and removed in - NumPy 2.0 because full support (2022.12 version [1]_) was included in the main namespace (with - 2023.12 version support in NumPy 2.1). + NumPy 2.0 because full support (2022.12 version [1]_) was included in + the main namespace (with 2023.12 version support in NumPy 2.1). :ref:`NEP 47 ` and :ref:`NEP 56 ` describe the motivation and scope for implementing the array API standard From cbe2cab32569b49d97b5c334bc3c97fd3b9a03b8 Mon Sep 17 00:00:00 2001 From: Dimitri Papadopoulos <3234522+DimitriPapadopoulos@users.noreply.github.com> Date: Wed, 16 Apr 2025 08:45:11 +0200 Subject: [PATCH 021/202] STY: Apply ruff/refurb rule FURB113 Use `extend()` instead of repeatedly calling `append()` --- numpy/lib/_npyio_impl.py | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/numpy/lib/_npyio_impl.py b/numpy/lib/_npyio_impl.py index 24606f7dc8c0..2eab1f8e7101 100644 --- a/numpy/lib/_npyio_impl.py +++ b/numpy/lib/_npyio_impl.py @@ -1621,8 +1621,7 @@ def first_write(self, v): for row in X: row2 = [] for number in row: - row2.append(number.real) - row2.append(number.imag) + row2.extend((number.real, number.imag)) s = format % tuple(row2) + newline fh.write(s.replace('+-', '-')) else: From f47fcdd066679df2a5cab73200bcfc90b58a7ac1 Mon Sep 17 00:00:00 2001 From: Dimitri Papadopoulos <3234522+DimitriPapadopoulos@users.noreply.github.com> Date: Wed, 16 Apr 2025 08:51:01 +0200 Subject: [PATCH 022/202] STY: Apply ruff/refurb rule FURB116 Replace `bin` call with f-string --- numpy/_core/numeric.py | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/numpy/_core/numeric.py b/numpy/_core/numeric.py index 793eaa954258..54e50d7f7ea3 100644 --- a/numpy/_core/numeric.py +++ b/numpy/_core/numeric.py @@ -2091,7 +2091,7 @@ def err_if_insufficient(width, binwidth): return '0' * (width or 1) elif num > 0: - binary = bin(num)[2:] + binary = f'{num:b}' binwidth = len(binary) outwidth = (binwidth if width is None else builtins.max(binwidth, width)) @@ -2100,10 +2100,10 @@ def err_if_insufficient(width, binwidth): else: if width is None: - return '-' + bin(-num)[2:] + return f'-{-num:b}' else: - poswidth = len(bin(-num)[2:]) + poswidth = len(f'{-num:b}') # See gh-8679: remove extra digit # for numbers at boundaries. @@ -2111,7 +2111,7 @@ def err_if_insufficient(width, binwidth): poswidth -= 1 twocomp = 2**(poswidth + 1) + num - binary = bin(twocomp)[2:] + binary = f'{twocomp:b}' binwidth = len(binary) outwidth = builtins.max(binwidth, width) From fa9d6727aa0cdcbad84ea0eaf6cc1309ed1c4f8b Mon Sep 17 00:00:00 2001 From: Dimitri Papadopoulos <3234522+DimitriPapadopoulos@users.noreply.github.com> Date: Wed, 16 Apr 2025 08:54:26 +0200 Subject: [PATCH 023/202] STY: Apply ruff/refurb rule FURB145 Prefer `copy` method over slicing --- numpy/lib/_npyio_impl.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/numpy/lib/_npyio_impl.py b/numpy/lib/_npyio_impl.py index 2eab1f8e7101..e1d2c0bf5376 100644 --- a/numpy/lib/_npyio_impl.py +++ b/numpy/lib/_npyio_impl.py @@ -2384,7 +2384,7 @@ def encode_unicode_cols(row_tup): column_types[i] = np.bytes_ # Update string types to be the right length - sized_column_types = column_types[:] + sized_column_types = column_types.copy() for i, col_type in enumerate(column_types): if np.issubdtype(col_type, np.character): n_chars = max(len(row[i]) for row in data) From 3671a2201257be4f8852fb906333cc5d8839c21f Mon Sep 17 00:00:00 2001 From: Dimitri Papadopoulos <3234522+DimitriPapadopoulos@users.noreply.github.com> Date: Wed, 16 Apr 2025 08:55:40 +0200 Subject: [PATCH 024/202] STY: Apply ruff/refurb rule FURB148 `enumerate` index is unused, use `for x in y` instead --- numpy/_core/tests/test_scalarmath.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/numpy/_core/tests/test_scalarmath.py b/numpy/_core/tests/test_scalarmath.py index b00e80e79fd6..cee1389569a2 100644 --- a/numpy/_core/tests/test_scalarmath.py +++ b/numpy/_core/tests/test_scalarmath.py @@ -68,7 +68,7 @@ def test_type_add(self): (k, np.dtype(atype).char, l, np.dtype(btype).char)) def test_type_create(self): - for k, atype in enumerate(types): + for atype in types: a = np.array([1, 2, 3], atype) b = atype([1, 2, 3]) assert_equal(a, b) From 7d198644ee44b0acb7d9b591a06efa1bc64eb34c Mon Sep 17 00:00:00 2001 From: Dimitri Papadopoulos <3234522+DimitriPapadopoulos@users.noreply.github.com> Date: Wed, 16 Apr 2025 08:56:55 +0200 Subject: [PATCH 025/202] STY: Apply ruff/refurb rule FURB161 Use of `bin(...).count('1')` --- numpy/_core/tests/test_scalar_methods.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/numpy/_core/tests/test_scalar_methods.py b/numpy/_core/tests/test_scalar_methods.py index 96cec38acb5b..89e7270f9b6e 100644 --- a/numpy/_core/tests/test_scalar_methods.py +++ b/numpy/_core/tests/test_scalar_methods.py @@ -194,7 +194,7 @@ class TestBitCount: def test_small(self, itype): for a in range(max(np.iinfo(itype).min, 0), 128): msg = f"Smoke test for {itype}({a}).bit_count()" - assert itype(a).bit_count() == bin(a).count("1"), msg + assert itype(a).bit_count() == a.bit_count(), msg def test_bit_count(self): for exp in [10, 17, 63]: From 9d5711dbdad1cf17e3dbacaea9a432eb3731f4bc Mon Sep 17 00:00:00 2001 From: Dimitri Papadopoulos <3234522+DimitriPapadopoulos@users.noreply.github.com> Date: Wed, 16 Apr 2025 08:58:19 +0200 Subject: [PATCH 026/202] STY: Apply ruff/refurb rule FURB180 Use of `metaclass=abc.ABCMeta` to define abstract base class --- numpy/lib/mixins.pyi | 4 ++-- numpy/polynomial/_polybase.pyi | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/numpy/lib/mixins.pyi b/numpy/lib/mixins.pyi index d13d0fe81df4..c42f2e3d8ed4 100644 --- a/numpy/lib/mixins.pyi +++ b/numpy/lib/mixins.pyi @@ -1,4 +1,4 @@ -from abc import ABCMeta, abstractmethod +from abc import ABC, abstractmethod from typing import Literal as L, Any from numpy import ufunc @@ -12,7 +12,7 @@ __all__ = ["NDArrayOperatorsMixin"] # completely dependent on how `__array_ufunc__` is implemented. # As such, only little type safety can be provided here. -class NDArrayOperatorsMixin(metaclass=ABCMeta): +class NDArrayOperatorsMixin(ABC): @abstractmethod def __array_ufunc__( self, diff --git a/numpy/polynomial/_polybase.pyi b/numpy/polynomial/_polybase.pyi index c85a3822202a..7fe2724572ed 100644 --- a/numpy/polynomial/_polybase.pyi +++ b/numpy/polynomial/_polybase.pyi @@ -58,7 +58,7 @@ _Other = TypeVar("_Other", bound=ABCPolyBase) _AnyOther: TypeAlias = ABCPolyBase | _CoefLike_co | _SeriesLikeCoef_co _Hundred: TypeAlias = Literal[100] -class ABCPolyBase(Generic[_NameCo], metaclass=abc.ABCMeta): +class ABCPolyBase(Generic[_NameCo], abc.ABC): __hash__: ClassVar[None] # type: ignore[assignment] __array_ufunc__: ClassVar[None] From 54909f2355c3ee160055a9e42dff374f1a63f175 Mon Sep 17 00:00:00 2001 From: Dimitri Papadopoulos <3234522+DimitriPapadopoulos@users.noreply.github.com> Date: Wed, 16 Apr 2025 08:59:20 +0200 Subject: [PATCH 027/202] STY: Apply ruff/refurb rule FURB188 Prefer `str.removesuffix()` over conditionally replacing with slice. --- numpy/_build_utils/tempita/_tempita.py | 9 +++------ numpy/f2py/crackfortran.py | 3 +-- numpy/lib/_polynomial_impl.py | 3 +-- 3 files changed, 5 insertions(+), 10 deletions(-) diff --git a/numpy/_build_utils/tempita/_tempita.py b/numpy/_build_utils/tempita/_tempita.py index d3eada2d2638..d8ce41742f3a 100644 --- a/numpy/_build_utils/tempita/_tempita.py +++ b/numpy/_build_utils/tempita/_tempita.py @@ -841,8 +841,7 @@ def parse_cond(tokens, name, context): def parse_one_cond(tokens, name, context): (first, pos), tokens = tokens[0], tokens[1:] content = [] - if first.endswith(":"): - first = first[:-1] + first = first.removesuffix(":") if first.startswith("if "): part = ("if", pos, first[3:].lstrip(), content) elif first.startswith("elif "): @@ -870,8 +869,7 @@ def parse_for(tokens, name, context): context = ("for",) + context content = [] assert first.startswith("for "), first - if first.endswith(":"): - first = first[:-1] + first = first.removesuffix(":") first = first[3:].strip() match = in_re.search(first) if not match: @@ -932,8 +930,7 @@ def parse_def(tokens, name, context): tokens = tokens[1:] assert first.startswith("def ") first = first.split(None, 1)[1] - if first.endswith(":"): - first = first[:-1] + first = first.removesuffix(":") if "(" not in first: func_name = first sig = ((), None, None, {}) diff --git a/numpy/f2py/crackfortran.py b/numpy/f2py/crackfortran.py index 1e3c91a3fb1a..0ae8b5ce7610 100644 --- a/numpy/f2py/crackfortran.py +++ b/numpy/f2py/crackfortran.py @@ -1434,8 +1434,7 @@ def analyzeline(m, case, line): last_name = None for l in ll: l[0], l[1] = l[0].strip(), l[1].strip() - if l[0].startswith(','): - l[0] = l[0][1:] + l[0] = l[0].removeprefix(',') if l[0].startswith('('): outmess('analyzeline: implied-DO list "%s" is not supported. Skipping.\n' % l[0]) continue diff --git a/numpy/lib/_polynomial_impl.py b/numpy/lib/_polynomial_impl.py index 535e21af20a5..efb57a31c361 100644 --- a/numpy/lib/_polynomial_impl.py +++ b/numpy/lib/_polynomial_impl.py @@ -1290,8 +1290,7 @@ def __str__(self): def fmt_float(q): s = '%.4g' % q - if s.endswith('.0000'): - s = s[:-5] + s = s.removesuffix('.0000') return s for k, coeff in enumerate(coeffs): From 65d644c40c1ed65f0d3446229c69eb3ccc92681b Mon Sep 17 00:00:00 2001 From: Dimitri Papadopoulos <3234522+DimitriPapadopoulos@users.noreply.github.com> Date: Wed, 16 Apr 2025 17:22:30 +0200 Subject: [PATCH 028/202] MNT: Merge two lines for simplicity Co-authored-by: Joren Hammudoglu --- numpy/f2py/crackfortran.py | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/numpy/f2py/crackfortran.py b/numpy/f2py/crackfortran.py index 0ae8b5ce7610..93a8f2ab5a69 100644 --- a/numpy/f2py/crackfortran.py +++ b/numpy/f2py/crackfortran.py @@ -1433,8 +1433,7 @@ def analyzeline(m, case, line): vars = groupcache[groupcounter].get('vars', {}) last_name = None for l in ll: - l[0], l[1] = l[0].strip(), l[1].strip() - l[0] = l[0].removeprefix(',') + l[0], l[1] = l[0].strip().removeprefix(','), l[1].strip() if l[0].startswith('('): outmess('analyzeline: implied-DO list "%s" is not supported. Skipping.\n' % l[0]) continue From 74a2946c5834cef27b657fce7c46a7e258e4487d Mon Sep 17 00:00:00 2001 From: Dimitri Papadopoulos <3234522+DimitriPapadopoulos@users.noreply.github.com> Date: Wed, 16 Apr 2025 09:33:04 +0200 Subject: [PATCH 029/202] STY: Apply ruff/pyupgrade rule UP018 Unnecessary `bool` call (rewrite as a literal) Unnecessary `bytes` call (rewrite as a literal) Unnecessary `float` call (rewrite as a literal) Unnecessary `int` call (rewrite as a literal) Unnecessary `str` call (rewrite as a literal) --- numpy/_core/tests/test_api.py | 2 +- numpy/_core/tests/test_defchararray.py | 2 +- numpy/_core/tests/test_multiarray.py | 10 +++++----- numpy/_core/tests/test_print.py | 10 +++++----- numpy/_core/tests/test_regression.py | 2 +- numpy/lib/_format_impl.py | 2 +- numpy/polynomial/tests/test_classes.py | 2 +- 7 files changed, 15 insertions(+), 15 deletions(-) diff --git a/numpy/_core/tests/test_api.py b/numpy/_core/tests/test_api.py index 811116c9e095..f0200d59cafe 100644 --- a/numpy/_core/tests/test_api.py +++ b/numpy/_core/tests/test_api.py @@ -56,7 +56,7 @@ def test_array_array(): np.ones((), dtype=np.float64)) assert_equal(np.array("1.0").dtype, U3) assert_equal(np.array("1.0", dtype=str).dtype, U3) - assert_equal(np.array("1.0", dtype=U2), np.array(str("1."))) + assert_equal(np.array("1.0", dtype=U2), np.array("1.")) assert_equal(np.array("1", dtype=U5), np.ones((), dtype=U5)) builtins = getattr(__builtins__, '__dict__', __builtins__) diff --git a/numpy/_core/tests/test_defchararray.py b/numpy/_core/tests/test_defchararray.py index 6609be78d7ea..1f14ba6c9b53 100644 --- a/numpy/_core/tests/test_defchararray.py +++ b/numpy/_core/tests/test_defchararray.py @@ -379,7 +379,7 @@ def test_decode(self): def test_encode(self): B = self.B.encode('unicode_escape') - assert_(B[0][0] == str(' \\u03a3 ').encode('latin1')) + assert_(B[0][0] == ' \\u03a3 '.encode('latin1')) def test_expandtabs(self): T = self.A.expandtabs() diff --git a/numpy/_core/tests/test_multiarray.py b/numpy/_core/tests/test_multiarray.py index decbcb280c47..1cbb0d0fb50c 100644 --- a/numpy/_core/tests/test_multiarray.py +++ b/numpy/_core/tests/test_multiarray.py @@ -6123,10 +6123,10 @@ def test_field_names(self): assert_raises(IndexError, a['f1'].__setitem__, b'sf1', 1) assert_raises(IndexError, a['f1'].__getitem__, b'sf1') b = a.copy() - fn1 = str('f1') + fn1 = 'f1' b[fn1] = 1 assert_equal(b[fn1], 1) - fnn = str('not at all') + fnn = 'not at all' assert_raises(ValueError, b.__setitem__, fnn, 1) assert_raises(ValueError, b.__getitem__, fnn) b[0][fn1] = 2 @@ -6135,14 +6135,14 @@ def test_field_names(self): assert_raises(ValueError, b[0].__setitem__, fnn, 1) assert_raises(ValueError, b[0].__getitem__, fnn) # Subfield - fn3 = str('f3') - sfn1 = str('sf1') + fn3 = 'f3' + sfn1 = 'sf1' b[fn3][sfn1] = 1 assert_equal(b[fn3][sfn1], 1) assert_raises(ValueError, b[fn3].__setitem__, fnn, 1) assert_raises(ValueError, b[fn3].__getitem__, fnn) # multiple subfields - fn2 = str('f2') + fn2 = 'f2' b[fn2] = 3 assert_equal(b[['f1', 'f2']][0].tolist(), (2, 3)) diff --git a/numpy/_core/tests/test_print.py b/numpy/_core/tests/test_print.py index 43ded5539f48..ac5445ff3035 100644 --- a/numpy/_core/tests/test_print.py +++ b/numpy/_core/tests/test_print.py @@ -129,10 +129,10 @@ def test_float_type_print(tp): _test_redirected_print(float(x), tp, _REF[x]) if tp(1e16).itemsize > 4: - _test_redirected_print(float(1e16), tp) + _test_redirected_print(1e16, tp) else: ref = '1e+16' - _test_redirected_print(float(1e16), tp, ref) + _test_redirected_print(1e16, tp, ref) @pytest.mark.parametrize('tp', [np.complex64, np.cdouble, np.clongdouble]) @@ -191,12 +191,12 @@ def test_scalar_format(): class TestCommaDecimalPointLocale(CommaDecimalPointLocale): def test_locale_single(self): - assert_equal(str(np.float32(1.2)), str(float(1.2))) + assert_equal(str(np.float32(1.2)), str(1.2)) def test_locale_double(self): - assert_equal(str(np.double(1.2)), str(float(1.2))) + assert_equal(str(np.double(1.2)), str(1.2)) @pytest.mark.skipif(IS_MUSL, reason="test flaky on musllinux") def test_locale_longdouble(self): - assert_equal(str(np.longdouble('1.2')), str(float(1.2))) + assert_equal(str(np.longdouble('1.2')), str(1.2)) diff --git a/numpy/_core/tests/test_regression.py b/numpy/_core/tests/test_regression.py index 1aaf2b247828..84a16a18e19e 100644 --- a/numpy/_core/tests/test_regression.py +++ b/numpy/_core/tests/test_regression.py @@ -1804,7 +1804,7 @@ def test_object_array_nested(self): a = np.array(0, dtype=object) b = np.array(0, dtype=object) a[()] = b - assert_equal(int(a), int(0)) + assert_equal(int(a), int(0)) # noqa: UP018 assert_equal(float(a), float(0)) def test_object_array_self_copy(self): diff --git a/numpy/lib/_format_impl.py b/numpy/lib/_format_impl.py index 12ccb54db06c..a25d64ada252 100644 --- a/numpy/lib/_format_impl.py +++ b/numpy/lib/_format_impl.py @@ -1007,7 +1007,7 @@ def _read_bytes(fp, size, error_template="ran out of data"): Required as e.g. ZipExtFile in python 2.6 can return less data than requested. """ - data = bytes() + data = b"" while True: # io files (default in python3) return None or raise on # would-block, python2 file will truncate, probably nothing can be diff --git a/numpy/polynomial/tests/test_classes.py b/numpy/polynomial/tests/test_classes.py index a6dc7b9244e4..dbbbb2011535 100644 --- a/numpy/polynomial/tests/test_classes.py +++ b/numpy/polynomial/tests/test_classes.py @@ -323,7 +323,7 @@ def test_truediv(Poly): s = stype(5, 0) assert_poly_almost_equal(op.truediv(p2, s), p1) assert_raises(TypeError, op.truediv, s, p2) - for s in [(), [], {}, bool(), np.array([1])]: + for s in [(), [], {}, False, np.array([1])]: assert_raises(TypeError, op.truediv, p2, s) assert_raises(TypeError, op.truediv, s, p2) for ptype in classes: From b2b906a682cb8302890bd5d27d394d74549f9a48 Mon Sep 17 00:00:00 2001 From: Dimitri Papadopoulos <3234522+DimitriPapadopoulos@users.noreply.github.com> Date: Wed, 16 Apr 2025 09:38:46 +0200 Subject: [PATCH 030/202] STY: Apply ruff/pyupgrade rule UP030 Use implicit references for positional format fields --- numpy/conftest.py | 4 ++-- numpy/lib/tests/test_histograms.py | 10 +++++----- 2 files changed, 7 insertions(+), 7 deletions(-) diff --git a/numpy/conftest.py b/numpy/conftest.py index 0eb42d1103e4..9a09765ae3e5 100644 --- a/numpy/conftest.py +++ b/numpy/conftest.py @@ -133,13 +133,13 @@ def check_fpu_mode(request): new_mode = get_fpu_mode() if old_mode != new_mode: - raise AssertionError("FPU precision mode changed from {0:#x} to {1:#x}" + raise AssertionError("FPU precision mode changed from {:#x} to {:#x}" " during the test".format(old_mode, new_mode)) collect_result = _collect_results.get(request.node) if collect_result is not None: old_mode, new_mode = collect_result - raise AssertionError("FPU precision mode changed from {0:#x} to {1:#x}" + raise AssertionError("FPU precision mode changed from {:#x} to {:#x}" " when collecting the test".format(old_mode, new_mode)) diff --git a/numpy/lib/tests/test_histograms.py b/numpy/lib/tests/test_histograms.py index cf76a5a4ae3d..64f54f522201 100644 --- a/numpy/lib/tests/test_histograms.py +++ b/numpy/lib/tests/test_histograms.py @@ -462,8 +462,8 @@ def test_simple(self): x = np.concatenate((x1, x2)) for estimator, numbins in expectedResults.items(): a, b = np.histogram(x, estimator) - assert_equal(len(a), numbins, err_msg="For the {0} estimator " - "with datasize of {1}".format(estimator, testlen)) + assert_equal(len(a), numbins, err_msg="For the {} estimator " + "with datasize of {}".format(estimator, testlen)) def test_small(self): """ @@ -482,8 +482,8 @@ def test_small(self): testdat = np.arange(testlen).astype(float) for estimator, expbins in expectedResults.items(): a, b = np.histogram(testdat, estimator) - assert_equal(len(a), expbins, err_msg="For the {0} estimator " - "with datasize of {1}".format(estimator, testlen)) + assert_equal(len(a), expbins, err_msg="For the {} estimator " + "with datasize of {}".format(estimator, testlen)) def test_incorrect_methods(self): """ @@ -504,7 +504,7 @@ def test_novariance(self): for estimator, numbins in novar_resultdict.items(): a, b = np.histogram(novar_dataset, estimator) - assert_equal(len(a), numbins, err_msg="{0} estimator, " + assert_equal(len(a), numbins, err_msg="{} estimator, " "No Variance test".format(estimator)) def test_limited_variance(self): From ec39692684fb6fce69bd2703f23520127a43db03 Mon Sep 17 00:00:00 2001 From: Dimitri Papadopoulos <3234522+DimitriPapadopoulos@users.noreply.github.com> Date: Wed, 16 Apr 2025 09:40:26 +0200 Subject: [PATCH 031/202] STY: Apply ruff/pyuprade rule UP034 Avoid extraneous parentheses --- numpy/_core/tests/test_multiarray.py | 2 +- numpy/_core/tests/test_shape_base.py | 2 +- numpy/lib/recfunctions.py | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/numpy/_core/tests/test_multiarray.py b/numpy/_core/tests/test_multiarray.py index 1cbb0d0fb50c..93d52a1eed0d 100644 --- a/numpy/_core/tests/test_multiarray.py +++ b/numpy/_core/tests/test_multiarray.py @@ -5499,7 +5499,7 @@ def test_roundtrip_str(self, x): def test_roundtrip_repr(self, x): x = x.real.ravel() - s = "@".join((repr(x)[11:-1] for x in x)) + s = "@".join(repr(x)[11:-1] for x in x) y = np.fromstring(s, sep="@") assert_array_equal(x, y) diff --git a/numpy/_core/tests/test_shape_base.py b/numpy/_core/tests/test_shape_base.py index 5ead366526f4..3c4346af40d9 100644 --- a/numpy/_core/tests/test_shape_base.py +++ b/numpy/_core/tests/test_shape_base.py @@ -156,7 +156,7 @@ def test_generator(self): with pytest.raises(TypeError, match="arrays to stack must be"): hstack(np.arange(3) for _ in range(2)) with pytest.raises(TypeError, match="arrays to stack must be"): - hstack((x for x in np.ones((3, 2)))) + hstack(x for x in np.ones((3, 2))) def test_casting_and_dtype(self): a = np.array([1, 2, 3]) diff --git a/numpy/lib/recfunctions.py b/numpy/lib/recfunctions.py index c2ae17a6defe..4a3fc98de171 100644 --- a/numpy/lib/recfunctions.py +++ b/numpy/lib/recfunctions.py @@ -263,7 +263,7 @@ def get_fieldstructure(adtype, lastname=None, parents=None,): parents[name] = [] parents.update(get_fieldstructure(current, name, parents)) else: - lastparent = list((parents.get(lastname, []) or [])) + lastparent = list(parents.get(lastname, []) or []) if lastparent: lastparent.append(lastname) elif lastname: From 3253257c023eea6cff5a31e12cc84cee3fb4b335 Mon Sep 17 00:00:00 2001 From: Dimitri Papadopoulos <3234522+DimitriPapadopoulos@users.noreply.github.com> Date: Wed, 16 Apr 2025 09:45:04 +0200 Subject: [PATCH 032/202] STY: Apply ruff/pyupgrade rule UP035 Import from `collections.abc` instead: `Iterable` Import from `typing` instead: `NotRequired` `typing.Dict` is deprecated, use `dict` instead `typing.List` is deprecated, use `list` instead `typing.Set` is deprecated, use `set` instead `typing.Tuple` is deprecated, use `tuple` instead `typing.Type` is deprecated, use `type` instead --- numpy/__init__.pyi | 5 +---- numpy/_core/tests/test_multiarray.py | 10 ---------- numpy/_core/tests/test_scalar_methods.py | 6 +++--- numpy/f2py/f2py2e.pyi | 3 ++- numpy/lib/_array_utils_impl.pyi | 3 ++- numpy/ma/core.py | 5 ++--- numpy/polynomial/_polybase.py | 2 +- numpy/tests/test_public_api.py | 11 ++++++----- 8 files changed, 17 insertions(+), 28 deletions(-) diff --git a/numpy/__init__.pyi b/numpy/__init__.pyi index e881cab14bfa..0516e64c5716 100644 --- a/numpy/__init__.pyi +++ b/numpy/__init__.pyi @@ -1000,10 +1000,7 @@ _SortSide: TypeAlias = L["left", "right"] _ConvertibleToInt: TypeAlias = SupportsInt | SupportsIndex | _CharLike_co _ConvertibleToFloat: TypeAlias = SupportsFloat | SupportsIndex | _CharLike_co -if sys.version_info >= (3, 11): - _ConvertibleToComplex: TypeAlias = SupportsComplex | SupportsFloat | SupportsIndex | _CharLike_co -else: - _ConvertibleToComplex: TypeAlias = complex | SupportsComplex | SupportsFloat | SupportsIndex | _CharLike_co +_ConvertibleToComplex: TypeAlias = SupportsComplex | SupportsFloat | SupportsIndex | _CharLike_co _ConvertibleToTD64: TypeAlias = dt.timedelta | int | _CharLike_co | character | number | timedelta64 | np.bool | None _ConvertibleToDT64: TypeAlias = dt.date | int | _CharLike_co | character | number | datetime64 | np.bool | None diff --git a/numpy/_core/tests/test_multiarray.py b/numpy/_core/tests/test_multiarray.py index 93d52a1eed0d..b3a2486f89b8 100644 --- a/numpy/_core/tests/test_multiarray.py +++ b/numpy/_core/tests/test_multiarray.py @@ -8977,16 +8977,6 @@ def test_to_int_scalar(self): assert_equal(5, int_func(np.bytes_(b'5'))) assert_equal(6, int_func(np.str_('6'))) - # The delegation of int() to __trunc__ was deprecated in - # Python 3.11. - if sys.version_info < (3, 11): - class HasTrunc: - def __trunc__(self): - return 3 - assert_equal(3, int_func(np.array(HasTrunc()))) - with assert_warns(DeprecationWarning): - assert_equal(3, int_func(np.array([HasTrunc()]))) - class NotConvertible: def __int__(self): raise NotImplementedError diff --git a/numpy/_core/tests/test_scalar_methods.py b/numpy/_core/tests/test_scalar_methods.py index 96cec38acb5b..7f9a9271ab34 100644 --- a/numpy/_core/tests/test_scalar_methods.py +++ b/numpy/_core/tests/test_scalar_methods.py @@ -4,7 +4,7 @@ import fractions import platform import types -from typing import Any, Type +from typing import Any import pytest import numpy as np @@ -143,7 +143,7 @@ class TestClassGetItem: np.signedinteger, np.floating, ]) - def test_abc(self, cls: Type[np.number]) -> None: + def test_abc(self, cls: type[np.number]) -> None: alias = cls[Any] assert isinstance(alias, types.GenericAlias) assert alias.__origin__ is cls @@ -164,7 +164,7 @@ def test_abc_complexfloating_subscript_tuple(self, arg_len: int) -> None: np.complexfloating[arg_tup] @pytest.mark.parametrize("cls", [np.generic, np.flexible, np.character]) - def test_abc_non_numeric(self, cls: Type[np.generic]) -> None: + def test_abc_non_numeric(self, cls: type[np.generic]) -> None: with pytest.raises(TypeError): cls[Any] diff --git a/numpy/f2py/f2py2e.pyi b/numpy/f2py/f2py2e.pyi index f72568375f34..2e3d30de2b5c 100644 --- a/numpy/f2py/f2py2e.pyi +++ b/numpy/f2py/f2py2e.pyi @@ -4,7 +4,8 @@ from collections.abc import Hashable, Iterable, Mapping, MutableMapping, Sequenc from types import ModuleType from typing import Any, Final, TypedDict, type_check_only -from typing_extensions import NotRequired, TypeVar, override +from typing_extensions import TypeVar, override +from typing import NotRequired from .__version__ import version from .auxfuncs import _Bool diff --git a/numpy/lib/_array_utils_impl.pyi b/numpy/lib/_array_utils_impl.pyi index 11a2aafb8837..32dda28f34ed 100644 --- a/numpy/lib/_array_utils_impl.pyi +++ b/numpy/lib/_array_utils_impl.pyi @@ -1,4 +1,5 @@ -from typing import Any, Iterable +from typing import Any +from collections.abc import Iterable from numpy import generic from numpy.typing import NDArray diff --git a/numpy/ma/core.py b/numpy/ma/core.py index a2f25a82e42a..f73ff45cad02 100644 --- a/numpy/ma/core.py +++ b/numpy/ma/core.py @@ -27,7 +27,6 @@ import warnings import textwrap import re -from typing import Dict import numpy as np import numpy._core.umath as umath @@ -185,8 +184,8 @@ class MaskError(MAError): float_types_list = [np.half, np.single, np.double, np.longdouble, np.csingle, np.cdouble, np.clongdouble] -_minvals: Dict[type, int] = {} -_maxvals: Dict[type, int] = {} +_minvals: dict[type, int] = {} +_maxvals: dict[type, int] = {} for sctype in ntypes.sctypeDict.values(): scalar_dtype = np.dtype(sctype) diff --git a/numpy/polynomial/_polybase.py b/numpy/polynomial/_polybase.py index 5b2982e25c6a..c9585f5c6d2f 100644 --- a/numpy/polynomial/_polybase.py +++ b/numpy/polynomial/_polybase.py @@ -9,7 +9,7 @@ import os import abc import numbers -from typing import Callable +from collections.abc import Callable import numpy as np from . import polyutils as pu diff --git a/numpy/tests/test_public_api.py b/numpy/tests/test_public_api.py index d26b11f81327..1dccf2a8491d 100644 --- a/numpy/tests/test_public_api.py +++ b/numpy/tests/test_public_api.py @@ -563,20 +563,21 @@ def test_functions_single_location(): Test performs BFS search traversing NumPy's public API. It flags any function-like object that is accessible from more that one place. """ - from typing import Any, Callable, Dict, List, Set, Tuple + from typing import Any + from collections.abc import Callable from numpy._core._multiarray_umath import ( _ArrayFunctionDispatcher as dispatched_function ) - visited_modules: Set[types.ModuleType] = {np} - visited_functions: Set[Callable[..., Any]] = set() + visited_modules: set[types.ModuleType] = {np} + visited_functions: set[Callable[..., Any]] = set() # Functions often have `__name__` overridden, therefore we need # to keep track of locations where functions have been found. - functions_original_paths: Dict[Callable[..., Any], str] = {} + functions_original_paths: dict[Callable[..., Any], str] = {} # Here we aggregate functions with more than one location. # It must be empty for the test to pass. - duplicated_functions: List[Tuple] = [] + duplicated_functions: list[tuple] = [] modules_queue = [np] From a3776cd55cc55026cedec5dd12159d8b9d720796 Mon Sep 17 00:00:00 2001 From: Dimitri Papadopoulos Orfanos <3234522+DimitriPapadopoulos@users.noreply.github.com> Date: Thu, 17 Apr 2025 12:21:02 +0200 Subject: [PATCH 033/202] STY: Apply assorted ruff rules (RUF) (#28724) * STY: Apply ruff rules about white space and non-ascii chars Co-authored-by: Joren Hammudoglu * MNT: remove more non-breaking spaces from text files --------- Co-authored-by: Joren Hammudoglu --- benchmarks/benchmarks/bench_linalg.py | 2 +- doc/source/user/numpy-for-matlab-users.rst | 6 +++--- numpy/_core/include/numpy/ndarraytypes.h | 2 +- numpy/_core/tests/test_numeric.py | 2 +- numpy/f2py/_backends/_meson.py | 2 +- numpy/f2py/crackfortran.py | 2 -- numpy/lib/_index_tricks_impl.py | 2 +- numpy/lib/_iotools.py | 3 ++- numpy/ma/core.py | 4 ++-- tools/changelog.py | 4 ++-- 10 files changed, 14 insertions(+), 15 deletions(-) diff --git a/benchmarks/benchmarks/bench_linalg.py b/benchmarks/benchmarks/bench_linalg.py index 72bd16e4e9c5..b4fe6e58b3c7 100644 --- a/benchmarks/benchmarks/bench_linalg.py +++ b/benchmarks/benchmarks/bench_linalg.py @@ -202,7 +202,7 @@ def time_einsum_noncon_mul(self, dtype): def time_einsum_noncon_contig_contig(self, dtype): np.einsum("ji,i->", self.non_contiguous_dim2, self.non_contiguous_dim1_small, optimize=True) - # sum_of_products_contig_outstride0_one:non_contiguous arrays + # sum_of_products_contig_outstride0_one: non_contiguous arrays def time_einsum_noncon_contig_outstride0(self, dtype): np.einsum("i->", self.non_contiguous_dim1, optimize=True) diff --git a/doc/source/user/numpy-for-matlab-users.rst b/doc/source/user/numpy-for-matlab-users.rst index 44ffa2a3a9e1..a3ced19e23ad 100644 --- a/doc/source/user/numpy-for-matlab-users.rst +++ b/doc/source/user/numpy-for-matlab-users.rst @@ -574,12 +574,12 @@ Notes \ **Submatrix**: Assignment to a submatrix can be done with lists of indices using the ``ix_`` command. E.g., for 2D array ``a``, one might -do: ``ind=[1, 3]; a[np.ix_(ind, ind)] += 100``. +do: ``ind=[1, 3]; a[np.ix_(ind, ind)] += 100``. \ **HELP**: There is no direct equivalent of MATLAB's ``which`` command, but the commands :func:`help` will usually list the filename where the function is located. Python also has an ``inspect`` module (do -``import inspect``) which provides a ``getfile`` that often works. +``import inspect``) which provides a ``getfile`` that often works. \ **INDEXING**: MATLAB uses one based indexing, so the initial element of a sequence has index 1. Python uses zero based indexing, so the @@ -709,7 +709,7 @@ are only a handful of key differences between the two. - The ``array`` constructor **takes (nested) Python sequences as initializers**. As in, ``array([[1,2,3],[4,5,6]])``. - The ``matrix`` constructor additionally **takes a convenient - string initializer**. As in ``matrix("[1 2 3; 4 5 6]")``. + string initializer**. As in ``matrix("[1 2 3; 4 5 6]")``. There are pros and cons to using both: diff --git a/numpy/_core/include/numpy/ndarraytypes.h b/numpy/_core/include/numpy/ndarraytypes.h index 609252f1cf4d..baa42406ac88 100644 --- a/numpy/_core/include/numpy/ndarraytypes.h +++ b/numpy/_core/include/numpy/ndarraytypes.h @@ -1679,7 +1679,7 @@ PyArray_CLEARFLAGS(PyArrayObject *arr, int flags) /* * PyDataType_* FLAGS, FLACHK, REFCHK, HASFIELDS, HASSUBARRAY, UNSIZED, * SUBARRAY, NAMES, FIELDS, C_METADATA, and METADATA require version specific - * lookup and are defined in npy_2_compat.h. + * lookup and are defined in npy_2_compat.h. */ diff --git a/numpy/_core/tests/test_numeric.py b/numpy/_core/tests/test_numeric.py index f00c51112c25..6a35b82ed766 100644 --- a/numpy/_core/tests/test_numeric.py +++ b/numpy/_core/tests/test_numeric.py @@ -2061,7 +2061,7 @@ def _test_array_equal_parametrizations(): yield (e1, e1.copy(), False, True) yield (e1, e1.copy(), True, True) - # Non-nanable – those cannot hold nans + # Non-nanable - those cannot hold nans a12 = np.array([1, 2]) a12b = a12.copy() a123 = np.array([1, 2, 3]) diff --git a/numpy/f2py/_backends/_meson.py b/numpy/f2py/_backends/_meson.py index f303fa9a6c7e..b65b2def4d1f 100644 --- a/numpy/f2py/_backends/_meson.py +++ b/numpy/f2py/_backends/_meson.py @@ -126,7 +126,7 @@ def generate_meson_build(self): node() template = Template(self.meson_build_template()) meson_build = template.substitute(self.substitutions) - meson_build = re.sub(r",,", ",", meson_build) + meson_build = meson_build.replace(",,", ",") return meson_build diff --git a/numpy/f2py/crackfortran.py b/numpy/f2py/crackfortran.py index 509b6c4e20e7..f2f5198a77bc 100644 --- a/numpy/f2py/crackfortran.py +++ b/numpy/f2py/crackfortran.py @@ -1537,8 +1537,6 @@ def analyzeline(m, case, line): else: rl[l] = l groupcache[groupcounter]['use'][name]['map'] = rl - else: - pass else: print(m.groupdict()) outmess('analyzeline: Could not crack the use statement.\n') diff --git a/numpy/lib/_index_tricks_impl.py b/numpy/lib/_index_tricks_impl.py index 7939567ffb97..7041ad5d051d 100644 --- a/numpy/lib/_index_tricks_impl.py +++ b/numpy/lib/_index_tricks_impl.py @@ -165,7 +165,7 @@ def __getitem__(self, key): size.append(int(step)) else: size.append( - int(math.ceil((stop - start) / (step * 1.0)))) + math.ceil((stop - start) / step)) num_list += [start, stop, step] typ = _nx.result_type(*num_list) if self.sparse: diff --git a/numpy/lib/_iotools.py b/numpy/lib/_iotools.py index 7e0413667010..87e6a2ab23e9 100644 --- a/numpy/lib/_iotools.py +++ b/numpy/lib/_iotools.py @@ -6,6 +6,7 @@ import numpy as np import numpy._core.numeric as nx from numpy._utils import asbytes, asunicode +import itertools def _decode_line(line, encoding=None): @@ -180,7 +181,7 @@ def __init__(self, delimiter=None, comments='#', autostrip=True, elif hasattr(delimiter, '__iter__'): _handyman = self._variablewidth_splitter idx = np.cumsum([0] + list(delimiter)) - delimiter = [slice(i, j) for (i, j) in zip(idx[:-1], idx[1:])] + delimiter = [slice(i, j) for (i, j) in itertools.pairwise(idx)] # Delimiter is a single integer elif int(delimiter): (_handyman, delimiter) = ( diff --git a/numpy/ma/core.py b/numpy/ma/core.py index a2f25a82e42a..44d1d203aa7a 100644 --- a/numpy/ma/core.py +++ b/numpy/ma/core.py @@ -4697,7 +4697,7 @@ def count(self, axis=None, keepdims=np._NoValue): raise np.exceptions.AxisError(axis=axis, ndim=self.ndim) return 1 elif axis is None: - if kwargs.get('keepdims', False): + if kwargs.get('keepdims'): return np.array(self.size, dtype=np.intp, ndmin=self.ndim) return self.size @@ -4706,7 +4706,7 @@ def count(self, axis=None, keepdims=np._NoValue): for ax in axes: items *= self.shape[ax] - if kwargs.get('keepdims', False): + if kwargs.get('keepdims'): out_dims = list(self.shape) for a in axes: out_dims[a] = 1 diff --git a/tools/changelog.py b/tools/changelog.py index 723be088346e..de203e2f1de2 100755 --- a/tools/changelog.py +++ b/tools/changelog.py @@ -160,8 +160,8 @@ def backtick_repl(matchobj): if len(title) > 60: remainder = re.sub(r"\s.*$", "...", title[60:]) if len(remainder) > 20: - # just use the first 80 characters, with ellipses. - # note: this was previously bugged, + # just use the first 80 characters, with ellipses. + # note: this was previously bugged, # assigning to `remainder` rather than `title` title = title[:80] + "..." else: From 89f90ed7a02e8e433b27fe464c6b8c7d51e4a8d7 Mon Sep 17 00:00:00 2001 From: Dimitri Papadopoulos <3234522+DimitriPapadopoulos@users.noreply.github.com> Date: Thu, 17 Apr 2025 13:33:45 +0200 Subject: [PATCH 034/202] MNT: Apply ruff/pygrep-hooks rule PGH004 PGH004 Use specific rule codes when using `noqa` --- numpy/_core/multiarray.py | 2 +- numpy/_core/tests/test_multiarray.py | 14 +++++++------- numpy/_core/tests/test_regression.py | 16 ++++++++-------- numpy/exceptions.py | 2 +- numpy/lib/tests/test_function_base.py | 2 +- 5 files changed, 18 insertions(+), 18 deletions(-) diff --git a/numpy/_core/multiarray.py b/numpy/_core/multiarray.py index 088de1073e7e..8348522e8420 100644 --- a/numpy/_core/multiarray.py +++ b/numpy/_core/multiarray.py @@ -173,7 +173,7 @@ def empty_like( array([[ -2.00000715e+000, 1.48219694e-323, -2.00000572e+000], # uninitialized [ 4.38791518e-305, -2.00000715e+000, 4.17269252e-309]]) - """ # NOQA + """ return (prototype,) diff --git a/numpy/_core/tests/test_multiarray.py b/numpy/_core/tests/test_multiarray.py index decbcb280c47..0c256dc41a99 100644 --- a/numpy/_core/tests/test_multiarray.py +++ b/numpy/_core/tests/test_multiarray.py @@ -4444,44 +4444,44 @@ def _loads(self, obj): # version 0 pickles, using protocol=2 to pickle # version 0 doesn't have a version field def test_version0_int8(self): - s = b"\x80\x02cnumpy.core._internal\n_reconstruct\nq\x01cnumpy\nndarray\nq\x02K\x00\x85U\x01b\x87Rq\x03(K\x04\x85cnumpy\ndtype\nq\x04U\x02i1K\x00K\x01\x87Rq\x05(U\x01|NNJ\xff\xff\xff\xffJ\xff\xff\xff\xfftb\x89U\x04\x01\x02\x03\x04tb." # noqa + s = b"\x80\x02cnumpy.core._internal\n_reconstruct\nq\x01cnumpy\nndarray\nq\x02K\x00\x85U\x01b\x87Rq\x03(K\x04\x85cnumpy\ndtype\nq\x04U\x02i1K\x00K\x01\x87Rq\x05(U\x01|NNJ\xff\xff\xff\xffJ\xff\xff\xff\xfftb\x89U\x04\x01\x02\x03\x04tb." a = np.array([1, 2, 3, 4], dtype=np.int8) p = self._loads(s) assert_equal(a, p) def test_version0_float32(self): - s = b"\x80\x02cnumpy.core._internal\n_reconstruct\nq\x01cnumpy\nndarray\nq\x02K\x00\x85U\x01b\x87Rq\x03(K\x04\x85cnumpy\ndtype\nq\x04U\x02f4K\x00K\x01\x87Rq\x05(U\x01 Date: Thu, 17 Apr 2025 13:36:00 +0200 Subject: [PATCH 035/202] MNT: Enforce ruff/pygrep-hooks rules (PGH) --- ruff.toml | 1 + 1 file changed, 1 insertion(+) diff --git a/ruff.toml b/ruff.toml index ecc7b190f9da..378be76651eb 100644 --- a/ruff.toml +++ b/ruff.toml @@ -19,6 +19,7 @@ preview = true extend-select = [ "E", "W", + "PGH", ] ignore = [ "F", # TODO: enable Pyflakes rules From b34378f4713700e9722e600c2ca7c71b04256a00 Mon Sep 17 00:00:00 2001 From: jorenham Date: Thu, 17 Apr 2025 16:00:29 +0200 Subject: [PATCH 036/202] TYP: ``numpy.ma`` squiggly line cleanup --- numpy/ma/core.pyi | 20 ++++++++++---------- 1 file changed, 10 insertions(+), 10 deletions(-) diff --git a/numpy/ma/core.pyi b/numpy/ma/core.pyi index 44d808618316..bd0460d96547 100644 --- a/numpy/ma/core.pyi +++ b/numpy/ma/core.pyi @@ -1,5 +1,5 @@ # pyright: reportIncompatibleMethodOverride=false -# ruff: noqa: ANN001, ANN002, ANN003, ANN201, ANN202 ANN204 +# ruff: noqa: ANN001, ANN002, ANN003, ANN201, ANN202 ANN204, ANN401 from collections.abc import Sequence from typing import Any, Literal, SupportsIndex, TypeAlias, TypeVar, overload @@ -423,10 +423,10 @@ class MaskedArray(ndarray[_ShapeT_co, _DTypeT_co]): def compress(self, condition, axis=..., out=...): ... def __eq__(self, other): ... def __ne__(self, other): ... - def __ge__(self, other: ArrayLike, /) -> _MaskedArray[bool_]: ... - def __gt__(self, other: ArrayLike, /) -> _MaskedArray[bool_]: ... - def __le__(self, other: ArrayLike, /) -> _MaskedArray[bool_]: ... - def __lt__(self, other: ArrayLike, /) -> _MaskedArray[bool_]: ... + def __ge__(self, other: ArrayLike, /) -> _MaskedArray[bool_]: ... # type: ignore[override] + def __gt__(self, other: ArrayLike, /) -> _MaskedArray[bool_]: ... # type: ignore[override] + def __le__(self, other: ArrayLike, /) -> _MaskedArray[bool_]: ... # type: ignore[override] + def __lt__(self, other: ArrayLike, /) -> _MaskedArray[bool_]: ... # type: ignore[override] def __add__(self, other): ... def __radd__(self, other): ... def __sub__(self, other): ... @@ -564,7 +564,7 @@ class MaskedArray(ndarray[_ShapeT_co, _DTypeT_co]): ) -> _ArrayT: ... # - def sort( + def sort( # type: ignore[override] self, axis: SupportsIndex = -1, kind: _SortKind | None = None, @@ -748,8 +748,8 @@ class MaskedArray(ndarray[_ShapeT_co, _DTypeT_co]): def torecords(self) -> Incomplete: ... def tolist(self, fill_value: Incomplete | None = None) -> Incomplete: ... @deprecated("tostring() is deprecated. Use tobytes() instead.") - def tostring(self, /, fill_value: Incomplete | None = None, order: _OrderKACF = "C") -> bytes: ... # type: ignore[override] # pyright: ignore[reportIncompatibleMethodOverride] - def tobytes(self, /, fill_value: Incomplete | None = None, order: _OrderKACF = "C") -> bytes: ... # type: ignore[override] # pyright: ignore[reportIncompatibleMethodOverride] + def tostring(self, /, fill_value: Incomplete | None = None, order: _OrderKACF = "C") -> bytes: ... # type: ignore[override] + def tobytes(self, /, fill_value: Incomplete | None = None, order: _OrderKACF = "C") -> bytes: ... # type: ignore[override] def tofile(self, /, fid: Incomplete, sep: str = "", format: str = "%s") -> Incomplete: ... # @@ -1049,7 +1049,7 @@ minimum: _extrema_operation maximum: _extrema_operation @overload -def take( # type: ignore[overload-overlap] +def take( a: _ArrayLike[_ScalarT], indices: _IntLike_co, axis: None = None, @@ -1157,7 +1157,7 @@ def fromflex(fxarray): ... class _convert2ma: def __init__(self, /, funcname: str, np_ret: str, np_ma_ret: str, params: dict[str, Any] | None = None) -> None: ... - def __call__(self, /, *args: object, **params: object) -> Any: ... # noqa: ANN401 + def __call__(self, /, *args: object, **params: object) -> Any: ... def getdoc(self, /, np_ret: str, np_ma_ret: str) -> str | None: ... arange: _convert2ma From 8a2ae207ca546cd934fa923839150503ecb7bbd5 Mon Sep 17 00:00:00 2001 From: jorenham Date: Thu, 17 Apr 2025 16:35:33 +0200 Subject: [PATCH 037/202] TYP: some ``[arg]partition`` fixes --- numpy/__init__.pyi | 49 ++++++++++++++++++++++++++++--------- numpy/_core/fromnumeric.pyi | 36 +++++++++++++++++---------- 2 files changed, 60 insertions(+), 25 deletions(-) diff --git a/numpy/__init__.pyi b/numpy/__init__.pyi index 0516e64c5716..0870d1da5248 100644 --- a/numpy/__init__.pyi +++ b/numpy/__init__.pyi @@ -2290,14 +2290,47 @@ class ndarray(_ArrayOrScalarCommon, Generic[_ShapeT_co, _DTypeT_co]): where: _ArrayLikeBool_co = True, ) -> _ArrayT: ... + # + @overload + def partition( + self, + /, + kth: _ArrayLikeInt, + axis: SupportsIndex = -1, + kind: _PartitionKind = "introselect", + order: None = None, + ) -> None: ... + @overload + def partition( + self: NDArray[void], + /, + kth: _ArrayLikeInt, + axis: SupportsIndex = -1, + kind: _PartitionKind = "introselect", + order: str | Sequence[str] | None = None, + ) -> None: ... + + # + @overload def argpartition( self, - kth: _ArrayLikeInt_co, - axis: None | SupportsIndex = ..., - kind: _PartitionKind = ..., - order: None | str | Sequence[str] = ..., + /, + kth: _ArrayLikeInt, + axis: SupportsIndex | None = -1, + kind: _PartitionKind = "introselect", + order: None = None, + ) -> NDArray[intp]: ... + @overload + def argpartition( + self: NDArray[void], + /, + kth: _ArrayLikeInt, + axis: SupportsIndex | None = -1, + kind: _PartitionKind = "introselect", + order: str | Sequence[str] | None = None, ) -> NDArray[intp]: ... + # def diagonal( self, offset: SupportsIndex = ..., @@ -2317,14 +2350,6 @@ class ndarray(_ArrayOrScalarCommon, Generic[_ShapeT_co, _DTypeT_co]): # `nonzero()` is deprecated for 0d arrays/generics def nonzero(self) -> tuple[NDArray[intp], ...]: ... - def partition( - self, - kth: _ArrayLikeInt_co, - axis: SupportsIndex = ..., - kind: _PartitionKind = ..., - order: None | str | Sequence[str] = ..., - ) -> None: ... - # `put` is technically available to `generic`, # but is pointless as `generic`s are immutable def put(self, /, indices: _ArrayLikeInt_co, values: ArrayLike, mode: _ModeKind = "raise") -> None: ... diff --git a/numpy/_core/fromnumeric.pyi b/numpy/_core/fromnumeric.pyi index ecfa14d90ab8..138fe8809110 100644 --- a/numpy/_core/fromnumeric.pyi +++ b/numpy/_core/fromnumeric.pyi @@ -17,7 +17,6 @@ from typing_extensions import deprecated import numpy as np from numpy import ( - number, uint64, int_, int64, @@ -48,11 +47,11 @@ from numpy._typing import ( _ShapeLike, _ArrayLikeBool_co, _ArrayLikeUInt_co, + _ArrayLikeInt, _ArrayLikeInt_co, _ArrayLikeFloat_co, _ArrayLikeComplex_co, _ArrayLikeObject_co, - _ArrayLikeTD64_co, _IntLike_co, _BoolLike_co, _ComplexLike_co, @@ -323,31 +322,42 @@ def matrix_transpose(x: _ArrayLike[_ScalarT], /) -> NDArray[_ScalarT]: ... @overload def matrix_transpose(x: ArrayLike, /) -> NDArray[Any]: ... +# @overload def partition( a: _ArrayLike[_ScalarT], - kth: _ArrayLikeInt_co, - axis: SupportsIndex | None = ..., - kind: _PartitionKind = ..., - order: str | Sequence[str] | None = ..., + kth: _ArrayLikeInt, + axis: SupportsIndex | None = -1, + kind: _PartitionKind = "introselect", + order: None = None, ) -> NDArray[_ScalarT]: ... @overload +def partition( + a: _ArrayLike[np.void], + kth: _ArrayLikeInt, + axis: SupportsIndex | None = -1, + kind: _PartitionKind = "introselect", + order: str | Sequence[str] | None = None, +) -> NDArray[np.void]: ... +@overload def partition( a: ArrayLike, - kth: _ArrayLikeInt_co, - axis: SupportsIndex | None = ..., - kind: _PartitionKind = ..., - order: str | Sequence[str] | None = ..., + kth: _ArrayLikeInt, + axis: SupportsIndex | None = -1, + kind: _PartitionKind = "introselect", + order: str | Sequence[str] | None = None, ) -> NDArray[Any]: ... +# def argpartition( a: ArrayLike, - kth: _ArrayLikeInt_co, + kth: _ArrayLikeInt, axis: SupportsIndex | None = -1, - kind: _PartitionKind = ..., - order: str | Sequence[str] | None = ..., + kind: _PartitionKind = "introselect", + order: str | Sequence[str] | None = None, ) -> NDArray[intp]: ... +# @overload def sort( a: _ArrayLike[_ScalarT], From 9082f926db3c2f388d65b6c868efac920617f957 Mon Sep 17 00:00:00 2001 From: jorenham Date: Thu, 17 Apr 2025 16:36:06 +0200 Subject: [PATCH 038/202] TYP: some ``[arg]partition`` fixes in ``ma.MaskedArray`` --- numpy/ma/core.pyi | 31 ++++++++++++++++++++++++++++--- 1 file changed, 28 insertions(+), 3 deletions(-) diff --git a/numpy/ma/core.pyi b/numpy/ma/core.pyi index 44d808618316..6695a24064da 100644 --- a/numpy/ma/core.pyi +++ b/numpy/ma/core.pyi @@ -7,6 +7,7 @@ from typing import Any, Literal, SupportsIndex, TypeAlias, TypeVar, overload from _typeshed import Incomplete from typing_extensions import deprecated +import numpy as np from numpy import ( _ModeKind, _OrderKACF, @@ -681,19 +682,43 @@ class MaskedArray(ndarray[_ShapeT_co, _DTypeT_co]): ) -> _ArrayT: ... # + @overload def partition( self, + /, kth: _ArrayLikeInt, axis: SupportsIndex = -1, kind: _PartitionKind = "introselect", - order: str | Sequence[str] | None = None + order: None = None ) -> None: ... + @overload + def partition( + self: _MaskedArray[np.void], + /, + kth: _ArrayLikeInt, + axis: SupportsIndex = -1, + kind: _PartitionKind = "introselect", + order: str | Sequence[str] | None = None, + ) -> None: ... + + # + @overload def argpartition( self, + /, kth: _ArrayLikeInt, - axis: SupportsIndex = -1, + axis: SupportsIndex | None = -1, kind: _PartitionKind = "introselect", - order: str | Sequence[str] | None = None + order: None = None, + ) -> _MaskedArray[intp]: ... + @overload + def argpartition( + self: _MaskedArray[np.void], + /, + kth: _ArrayLikeInt, + axis: SupportsIndex | None = -1, + kind: _PartitionKind = "introselect", + order: str | Sequence[str] | None = None, ) -> _MaskedArray[intp]: ... # Keep in-sync with np.ma.take From 4a470ec5c3de4dac43441ff604fbb0bbac6407e9 Mon Sep 17 00:00:00 2001 From: jorenham Date: Thu, 17 Apr 2025 16:47:44 +0200 Subject: [PATCH 039/202] TYP: fix incorrect ``ma.MaskedArray.partition`` type-test --- numpy/typing/tests/data/reveal/ma.pyi | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/numpy/typing/tests/data/reveal/ma.pyi b/numpy/typing/tests/data/reveal/ma.pyi index c2ab12f58c85..63e0e7bf58c4 100644 --- a/numpy/typing/tests/data/reveal/ma.pyi +++ b/numpy/typing/tests/data/reveal/ma.pyi @@ -24,6 +24,7 @@ MAR_td64: MaskedNDArray[np.timedelta64] MAR_o: MaskedNDArray[np.object_] MAR_s: MaskedNDArray[np.str_] MAR_byte: MaskedNDArray[np.bytes_] +MAR_V: MaskedNDArray[np.void] MAR_subclass: MaskedNDArraySubclass @@ -163,7 +164,7 @@ assert_type(np.ma.take([1], [0]), MaskedNDArray[Any]) assert_type(np.ma.take(np.eye(2), 1, axis=0), MaskedNDArray[np.float64]) assert_type(MAR_f4.partition(1), None) -assert_type(MAR_f4.partition(1, axis=0, kind='introselect', order='K'), None) +assert_type(MAR_V.partition(1, axis=0, kind='introselect', order='K'), None) assert_type(MAR_f4.argpartition(1), MaskedNDArray[np.intp]) assert_type(MAR_1d.argpartition(1, axis=0, kind='introselect', order='K'), MaskedNDArray[np.intp]) From f18e893b6c499701708181285a278649151c6fb6 Mon Sep 17 00:00:00 2001 From: Marco Edward Gorelli Date: Thu, 17 Apr 2025 17:20:00 +0100 Subject: [PATCH 040/202] TYP: Type ``MaskedArray.filled`` and ``np.ma.filled`` (#28742) --- numpy/ma/core.pyi | 10 ++++++++-- numpy/typing/tests/data/reveal/ma.pyi | 10 ++++++++++ 2 files changed, 18 insertions(+), 2 deletions(-) diff --git a/numpy/ma/core.pyi b/numpy/ma/core.pyi index 44d808618316..d99421f3dd14 100644 --- a/numpy/ma/core.pyi +++ b/numpy/ma/core.pyi @@ -224,6 +224,7 @@ _DTypeT = TypeVar("_DTypeT", bound=dtype[Any]) _DTypeT_co = TypeVar("_DTypeT_co", bound=dtype[Any], covariant=True) _ArrayT = TypeVar("_ArrayT", bound=ndarray[Any, Any]) _ScalarT = TypeVar("_ScalarT", bound=generic) +_ScalarT_co = TypeVar("_ScalarT_co", bound=generic) # A subset of `MaskedArray` that can be parametrized w.r.t. `np.generic` _MaskedArray: TypeAlias = MaskedArray[_Shape, dtype[_ScalarT]] @@ -239,7 +240,12 @@ def minimum_fill_value(obj): ... def maximum_fill_value(obj): ... def set_fill_value(a, fill_value): ... def common_fill_value(a, b): ... -def filled(a, fill_value=...): ... +@overload +def filled(a: ndarray[_ShapeT_co, _DTypeT_co], fill_value: _ScalarLike_co | None = None) -> ndarray[_ShapeT_co, _DTypeT_co]: ... +@overload +def filled(a: _ArrayLike[_ScalarT_co], fill_value: _ScalarLike_co | None = None) -> NDArray[_ScalarT_co]: ... +@overload +def filled(a: ArrayLike, fill_value: _ScalarLike_co | None = None) -> NDArray[Any]: ... def getdata(a, subok=...): ... get_data = getdata @@ -418,7 +424,7 @@ class MaskedArray(ndarray[_ShapeT_co, _DTypeT_co]): def fill_value(self, value=...): ... get_fill_value: Any set_fill_value: Any - def filled(self, fill_value=...): ... + def filled(self, /, fill_value: _ScalarLike_co | None = None) -> ndarray[_ShapeT_co, _DTypeT_co]: ... def compressed(self): ... def compress(self, condition, axis=..., out=...): ... def __eq__(self, other): ... diff --git a/numpy/typing/tests/data/reveal/ma.pyi b/numpy/typing/tests/data/reveal/ma.pyi index c2ab12f58c85..e17c6659cec4 100644 --- a/numpy/typing/tests/data/reveal/ma.pyi +++ b/numpy/typing/tests/data/reveal/ma.pyi @@ -247,3 +247,13 @@ assert_type(np.ma.count(MAR_b, axis=(0,1)), NDArray[np.int_]) assert_type(np.ma.count(MAR_o, keepdims=True), NDArray[np.int_]) assert_type(np.ma.count(MAR_o, axis=None, keepdims=True), NDArray[np.int_]) assert_type(np.ma.count(MAR_o, None, True), NDArray[np.int_]) + +assert_type(MAR_f4.filled(float('nan')), NDArray[np.float32]) +assert_type(MAR_i8.filled(), NDArray[np.int64]) +assert_type(MAR_1d.filled(), np.ndarray[tuple[int], np.dtype[Any]]) + +assert_type(np.ma.filled(MAR_f4, float('nan')), NDArray[np.float32]) +assert_type(np.ma.filled([[1,2,3]]), NDArray[Any]) +# PyRight detects this one correctly, but mypy doesn't. +# https://github.com/numpy/numpy/pull/28742#discussion_r2048968375 +assert_type(np.ma.filled(MAR_1d), np.ndarray[tuple[int], np.dtype[Any]]) # type: ignore[assert-type] From a9cb2bbdbd31bdbaea4fda3a3087de8d1a5e68d0 Mon Sep 17 00:00:00 2001 From: jorenham Date: Thu, 17 Apr 2025 18:42:51 +0200 Subject: [PATCH 041/202] TYP: fix `count_nonzero` signature --- numpy/_core/numeric.pyi | 21 ++++++++++----------- numpy/typing/tests/data/reveal/numeric.pyi | 2 +- 2 files changed, 11 insertions(+), 12 deletions(-) diff --git a/numpy/_core/numeric.pyi b/numpy/_core/numeric.pyi index 0d7b9ea47798..17093fcd5d99 100644 --- a/numpy/_core/numeric.pyi +++ b/numpy/_core/numeric.pyi @@ -98,6 +98,7 @@ from numpy._typing import ( _ArrayLikeComplex_co, _ArrayLikeTD64_co, _ArrayLikeObject_co, + _NestedSequence, ) __all__ = [ @@ -413,21 +414,19 @@ def full_like( device: None | L["cpu"] = ..., ) -> NDArray[Any]: ... +# @overload -def count_nonzero( - a: ArrayLike, - axis: None = ..., - *, - keepdims: L[False] = ..., -) -> int: ... +def count_nonzero(a: ArrayLike, axis: None = None, *, keepdims: L[False] = False) -> int: ... +@overload +def count_nonzero(a: _ScalarLike_co, axis: _ShapeLike | None = None, *, keepdims: L[True]) -> np.intp: ... @overload def count_nonzero( - a: ArrayLike, - axis: _ShapeLike = ..., - *, - keepdims: bool = ..., -) -> Any: ... # TODO: np.intp or ndarray[np.intp] + a: NDArray[Any] | _NestedSequence[ArrayLike], axis: _ShapeLike | None = None, *, keepdims: L[True] +) -> NDArray[np.intp]: ... +@overload +def count_nonzero(a: ArrayLike, axis: _ShapeLike | None = None, *, keepdims: bool = False) -> Any: ... +# def isfortran(a: NDArray[Any] | generic) -> bool: ... def argwhere(a: ArrayLike) -> NDArray[intp]: ... diff --git a/numpy/typing/tests/data/reveal/numeric.pyi b/numpy/typing/tests/data/reveal/numeric.pyi index c9aede6d9126..34e20c986b69 100644 --- a/numpy/typing/tests/data/reveal/numeric.pyi +++ b/numpy/typing/tests/data/reveal/numeric.pyi @@ -28,7 +28,7 @@ C: SubClass assert_type(np.count_nonzero(i8), int) assert_type(np.count_nonzero(AR_i8), int) assert_type(np.count_nonzero(B), int) -assert_type(np.count_nonzero(AR_i8, keepdims=True), Any) +assert_type(np.count_nonzero(AR_i8, keepdims=True), npt.NDArray[np.intp]) assert_type(np.count_nonzero(AR_i8, axis=0), Any) assert_type(np.isfortran(i8), bool) From 8c6cabcb0bcc802b350b0218fd71cd3c10952828 Mon Sep 17 00:00:00 2001 From: Dimitri Papadopoulos <3234522+DimitriPapadopoulos@users.noreply.github.com> Date: Thu, 17 Apr 2025 13:45:16 +0200 Subject: [PATCH 042/202] STY: Apply ruff rule RUF015 Prefer `next(iter(...))` over single element slice --- numpy/_core/tests/_natype.py | 2 +- numpy/f2py/auxfuncs.py | 2 +- tools/wheels/check_license.py | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/numpy/_core/tests/_natype.py b/numpy/_core/tests/_natype.py index 4bbf06128532..e8c2bc2248c8 100644 --- a/numpy/_core/tests/_natype.py +++ b/numpy/_core/tests/_natype.py @@ -183,7 +183,7 @@ def __array_ufunc__(self, ufunc, method, *inputs, **kwargs): ) if result is NotImplemented: # For a NumPy ufunc that's not a binop, like np.logaddexp - index = [i for i, x in enumerate(inputs) if x is pd_NA][0] + index = next(i for i, x in enumerate(inputs) if x is pd_NA) result = np.broadcast_arrays(*inputs)[index] if result.ndim == 0: result = result.item() diff --git a/numpy/f2py/auxfuncs.py b/numpy/f2py/auxfuncs.py index 9fd4b41264fb..e52840690e90 100644 --- a/numpy/f2py/auxfuncs.py +++ b/numpy/f2py/auxfuncs.py @@ -416,7 +416,7 @@ def getdimension(var): dimpattern = r"\((.*?)\)" if 'attrspec' in var.keys(): if any('dimension' in s for s in var['attrspec']): - return [re.findall(dimpattern, v) for v in var['attrspec']][0] + return next(re.findall(dimpattern, v) for v in var['attrspec']) def isrequired(var): diff --git a/tools/wheels/check_license.py b/tools/wheels/check_license.py index 99db0744d9fb..3610558ce913 100644 --- a/tools/wheels/check_license.py +++ b/tools/wheels/check_license.py @@ -35,7 +35,7 @@ def main(): # LICENSE.txt is installed in the .dist-info directory, so find it there sitepkgs = pathlib.Path(mod.__file__).parent.parent - distinfo_path = list(sitepkgs.glob("numpy-*.dist-info"))[0] + distinfo_path = next(iter(sitepkgs.glob("numpy-*.dist-info"))) # Check license text license_txt = distinfo_path / "LICENSE.txt" From bcfd085d4c22ebfb5a36fbd54777bfa39e7907e8 Mon Sep 17 00:00:00 2001 From: Dimitri Papadopoulos <3234522+DimitriPapadopoulos@users.noreply.github.com> Date: Thu, 17 Apr 2025 13:47:00 +0200 Subject: [PATCH 043/202] STY: Apply ruff rule RUF021 Parenthesize `a and b` expressions when chaining `and` and `or` together, to make the precedence clear --- numpy/_core/arrayprint.py | 6 +++--- numpy/_core/tests/_natype.py | 2 +- numpy/f2py/_src_pyf.py | 2 +- numpy/f2py/crackfortran.py | 2 +- numpy/f2py/tests/test_array_from_pyobj.py | 2 +- numpy/lib/tests/test_io.py | 4 ++-- 6 files changed, 9 insertions(+), 9 deletions(-) diff --git a/numpy/_core/arrayprint.py b/numpy/_core/arrayprint.py index 36f465c9e6b6..14818c66f172 100644 --- a/numpy/_core/arrayprint.py +++ b/numpy/_core/arrayprint.py @@ -1594,9 +1594,9 @@ def _array_repr_implementation( # Add dtype and shape information if these cannot be inferred from # the array string. extras = [] - if (arr.size == 0 and arr.shape != (0,) - or current_options['legacy'] > 210 - and arr.size > current_options['threshold']): + if ((arr.size == 0 and arr.shape != (0,)) + or (current_options['legacy'] > 210 + and arr.size > current_options['threshold'])): extras.append(f"shape={arr.shape}") if not dtype_is_implied(arr.dtype) or arr.size == 0: extras.append(f"dtype={dtype_short_repr(arr.dtype)}") diff --git a/numpy/_core/tests/_natype.py b/numpy/_core/tests/_natype.py index e8c2bc2248c8..aa335ec540c2 100644 --- a/numpy/_core/tests/_natype.py +++ b/numpy/_core/tests/_natype.py @@ -15,7 +15,7 @@ def method(self, other): if ( other is pd_NA or isinstance(other, (str, bytes, numbers.Number, np.bool)) - or isinstance(other, np.ndarray) and not other.shape + or (isinstance(other, np.ndarray) and not other.shape) ): # Need the other.shape clause to handle NumPy scalars, # since we do a setitem on `out` below, which diff --git a/numpy/f2py/_src_pyf.py b/numpy/f2py/_src_pyf.py index ce116bf902d3..d5a759f84411 100644 --- a/numpy/f2py/_src_pyf.py +++ b/numpy/f2py/_src_pyf.py @@ -75,7 +75,7 @@ def parse_structure(astr): break start += 1 m = routine_end_re.search(astr, m.end()) - ind = end = m and m.end() - 1 or len(astr) + ind = end = (m and m.end() - 1) or len(astr) spanlist.append((start, end)) return spanlist diff --git a/numpy/f2py/crackfortran.py b/numpy/f2py/crackfortran.py index f2f5198a77bc..2ed96c189b40 100644 --- a/numpy/f2py/crackfortran.py +++ b/numpy/f2py/crackfortran.py @@ -417,7 +417,7 @@ def readfortrancode(ffile, dowithline=show, istop=1): beginpattern = beginpattern90 outmess('\tReading file %s (format:%s%s)\n' % (repr(currentfilename), sourcecodeform, - strictf77 and ',strict' or '')) + (strictf77 and ',strict') or '')) l = l.expandtabs().replace('\xa0', ' ') # Get rid of newline characters diff --git a/numpy/f2py/tests/test_array_from_pyobj.py b/numpy/f2py/tests/test_array_from_pyobj.py index 20be08cf8eb4..e317cbabe382 100644 --- a/numpy/f2py/tests/test_array_from_pyobj.py +++ b/numpy/f2py/tests/test_array_from_pyobj.py @@ -291,7 +291,7 @@ def __init__(self, typ, dims, intent, obj): else: self.pyarr = np.array( np.array(obj, dtype=typ.dtypechar).reshape(*dims), - order=self.intent.is_intent("c") and "C" or "F", + order=(self.intent.is_intent("c") and "C") or "F", ) assert self.pyarr.dtype == typ self.pyarr.setflags(write=self.arr.flags["WRITEABLE"]) diff --git a/numpy/lib/tests/test_io.py b/numpy/lib/tests/test_io.py index 6e279ce83350..58cf1a756ea6 100644 --- a/numpy/lib/tests/test_io.py +++ b/numpy/lib/tests/test_io.py @@ -1623,9 +1623,9 @@ def test_unused_converter(self): def test_invalid_converter(self): strip_rand = lambda x: float((b'r' in x.lower() and x.split()[-1]) or - (b'r' not in x.lower() and x.strip() or 0.0)) + ((b'r' not in x.lower() and x.strip()) or 0.0)) strip_per = lambda x: float((b'%' in x.lower() and x.split()[0]) or - (b'%' not in x.lower() and x.strip() or 0.0)) + ((b'%' not in x.lower() and x.strip()) or 0.0)) s = TextIO("D01N01,10/1/2003 ,1 %,R 75,400,600\r\n" "L24U05,12/5/2003, 2 %,1,300, 150.5\r\n" "D02N03,10/10/2004,R 1,,7,145.55") From cd03029496e49b31ed9af6e59cb8fbd9bf54aa09 Mon Sep 17 00:00:00 2001 From: Dimitri Papadopoulos <3234522+DimitriPapadopoulos@users.noreply.github.com> Date: Thu, 17 Apr 2025 13:47:42 +0200 Subject: [PATCH 044/202] STY: Apply ruff rule RUF023 `__slots__` is not sorted --- numpy/_core/_ufunc_config.py | 9 ++++++++- numpy/exceptions.py | 2 +- numpy/lib/_index_tricks_impl.py | 2 +- 3 files changed, 10 insertions(+), 3 deletions(-) diff --git a/numpy/_core/_ufunc_config.py b/numpy/_core/_ufunc_config.py index 4563f66cb52f..ec9fd77ecbd8 100644 --- a/numpy/_core/_ufunc_config.py +++ b/numpy/_core/_ufunc_config.py @@ -425,7 +425,14 @@ class errstate: """ __slots__ = ( - "_call", "_all", "_divide", "_over", "_under", "_invalid", "_token") + "_all", + "_call", + "_divide", + "_invalid", + "_over", + "_token", + "_under", + ) def __init__(self, *, call=_Unspecified, all=None, divide=None, over=None, under=None, invalid=None): diff --git a/numpy/exceptions.py b/numpy/exceptions.py index 998e8f07fd22..f1cc2bb83551 100644 --- a/numpy/exceptions.py +++ b/numpy/exceptions.py @@ -171,7 +171,7 @@ class AxisError(ValueError, IndexError): """ - __slots__ = ("axis", "ndim", "_msg") + __slots__ = ("_msg", "axis", "ndim") def __init__(self, axis, ndim=None, msg_prefix=None): if ndim is msg_prefix is None: diff --git a/numpy/lib/_index_tricks_impl.py b/numpy/lib/_index_tricks_impl.py index 7041ad5d051d..77aa1394fa0e 100644 --- a/numpy/lib/_index_tricks_impl.py +++ b/numpy/lib/_index_tricks_impl.py @@ -331,7 +331,7 @@ class AxisConcatenator: For detailed documentation on usage, see `r_`. """ - __slots__ = ('axis', 'matrix', 'trans1d', 'ndmin') + __slots__ = ('axis', 'matrix', 'ndmin', 'trans1d') # allow ma.mr_ to override this concatenate = staticmethod(_nx.concatenate) From fc4d84a63a345f7e4b15e412062fe6135438c778 Mon Sep 17 00:00:00 2001 From: Dimitri Papadopoulos <3234522+DimitriPapadopoulos@users.noreply.github.com> Date: Thu, 17 Apr 2025 13:49:01 +0200 Subject: [PATCH 045/202] STY: Apply ruff rule RUF027 Possible f-string without an `f` prefix --- numpy/polynomial/tests/test_printing.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/numpy/polynomial/tests/test_printing.py b/numpy/polynomial/tests/test_printing.py index 82802ba98305..b897770c9427 100644 --- a/numpy/polynomial/tests/test_printing.py +++ b/numpy/polynomial/tests/test_printing.py @@ -546,7 +546,7 @@ def test_switch_to_exp(self): def test_non_finite(self): p = poly.Polynomial([nan, inf]) assert str(p) == 'nan + inf x' - assert p._repr_latex_() == r'$x \mapsto \text{nan} + \text{inf}\,x$' + assert p._repr_latex_() == r'$x \mapsto \text{nan} + \text{inf}\,x$' # noqa: RUF027 with printoptions(nanstr='NAN', infstr='INF'): assert str(p) == 'NAN + INF x' assert p._repr_latex_() == \ From 84fc644fbf98d39542ecbe73210fa42709dde318 Mon Sep 17 00:00:00 2001 From: Dimitri Papadopoulos <3234522+DimitriPapadopoulos@users.noreply.github.com> Date: Thu, 17 Apr 2025 13:52:06 +0200 Subject: [PATCH 046/202] STY: Apply ruff rule RUF039 First argument to `re.compile()` is not raw bytes literal First argument to `re.match()` is not raw string First argument to `re.search()` is not raw string First argument to `re.split()` is not raw string First argument to `re.sub()` is not raw string --- numpy/_core/tests/test_cpu_features.py | 14 +++++++------- numpy/_core/tests/test_regression.py | 4 ++-- numpy/f2py/crackfortran.py | 2 +- numpy/lib/tests/test_io.py | 4 ++-- tools/c_coverage/c_coverage_report.py | 4 ++-- tools/changelog.py | 4 ++-- tools/refguide_check.py | 2 +- 7 files changed, 17 insertions(+), 17 deletions(-) diff --git a/numpy/_core/tests/test_cpu_features.py b/numpy/_core/tests/test_cpu_features.py index 0797bb8c772c..18fce21532ad 100644 --- a/numpy/_core/tests/test_cpu_features.py +++ b/numpy/_core/tests/test_cpu_features.py @@ -334,7 +334,7 @@ def test_impossible_feature_enable(self): is_linux = sys.platform.startswith('linux') is_cygwin = sys.platform.startswith('cygwin') machine = platform.machine() -is_x86 = re.match("^(amd64|x86|i386|i686)", machine, re.IGNORECASE) +is_x86 = re.match(r"^(amd64|x86|i386|i686)", machine, re.IGNORECASE) @pytest.mark.skipif( not (is_linux or is_cygwin) or not is_x86, reason="Only for Linux and x86" ) @@ -373,7 +373,7 @@ def load_flags(self): self.load_flags_cpuinfo("flags") -is_power = re.match("^(powerpc|ppc)64", machine, re.IGNORECASE) +is_power = re.match(r"^(powerpc|ppc)64", machine, re.IGNORECASE) @pytest.mark.skipif(not is_linux or not is_power, reason="Only for Linux and Power") class Test_POWER_Features(AbstractTest): features = ["VSX", "VSX2", "VSX3", "VSX4"] @@ -383,7 +383,7 @@ def load_flags(self): self.load_flags_auxv() -is_zarch = re.match("^(s390x)", machine, re.IGNORECASE) +is_zarch = re.match(r"^(s390x)", machine, re.IGNORECASE) @pytest.mark.skipif(not is_linux or not is_zarch, reason="Only for Linux and IBM Z") class Test_ZARCH_Features(AbstractTest): @@ -393,7 +393,7 @@ def load_flags(self): self.load_flags_auxv() -is_arm = re.match("^(arm|aarch64)", machine, re.IGNORECASE) +is_arm = re.match(r"^(arm|aarch64)", machine, re.IGNORECASE) @pytest.mark.skipif(not is_linux or not is_arm, reason="Only for Linux and ARM") class Test_ARM_Features(AbstractTest): features = [ @@ -409,10 +409,10 @@ def load_flags(self): arch = self.get_cpuinfo_item("CPU architecture") # in case of mounting virtual filesystem of aarch64 kernel without linux32 is_rootfs_v8 = ( - not re.match("^armv[0-9]+l$", machine) and + not re.match(r"^armv[0-9]+l$", machine) and (int('0' + next(iter(arch))) > 7 if arch else 0) ) - if re.match("^(aarch64|AARCH64)", machine) or is_rootfs_v8: + if re.match(r"^(aarch64|AARCH64)", machine) or is_rootfs_v8: self.features_map = { "NEON": "ASIMD", "HALF": "ASIMD", "VFPV4": "ASIMD" } @@ -425,7 +425,7 @@ def load_flags(self): } -is_loongarch = re.match("^(loongarch)", machine, re.IGNORECASE) +is_loongarch = re.match(r"^(loongarch)", machine, re.IGNORECASE) @pytest.mark.skipif(not is_linux or not is_loongarch, reason="Only for Linux and LoongArch") class Test_LOONGARCH_Features(AbstractTest): features = ["LSX"] diff --git a/numpy/_core/tests/test_regression.py b/numpy/_core/tests/test_regression.py index 84a16a18e19e..e5cc7003ca92 100644 --- a/numpy/_core/tests/test_regression.py +++ b/numpy/_core/tests/test_regression.py @@ -1902,10 +1902,10 @@ def test_pickle_string_overwrite(self): data = pickle.loads(blob) # Check that loads does not clobber interned strings - s = re.sub("a(.)", "\x01\\1", "a_") + s = re.sub(r"a(.)", "\x01\\1", "a_") assert_equal(s[0], "\x01") data[0] = 0x6a - s = re.sub("a(.)", "\x01\\1", "a_") + s = re.sub(r"a(.)", "\x01\\1", "a_") assert_equal(s[0], "\x01") def test_pickle_bytes_overwrite(self): diff --git a/numpy/f2py/crackfortran.py b/numpy/f2py/crackfortran.py index 2ed96c189b40..05c55bcd3822 100644 --- a/numpy/f2py/crackfortran.py +++ b/numpy/f2py/crackfortran.py @@ -1492,7 +1492,7 @@ def analyzeline(m, case, line): line = '//' + line cl = [] - [_, bn, ol] = re.split('/', line, maxsplit=2) + [_, bn, ol] = re.split('/', line, maxsplit=2) # noqa: RUF039 bn = bn.strip() if not bn: bn = '_BLNK_' diff --git a/numpy/lib/tests/test_io.py b/numpy/lib/tests/test_io.py index 58cf1a756ea6..cce86489e22f 100644 --- a/numpy/lib/tests/test_io.py +++ b/numpy/lib/tests/test_io.py @@ -1321,7 +1321,7 @@ def test_record_unicode(self, path_type): assert_array_equal(x, a) def test_compiled_bytes(self): - regexp = re.compile(b'(\\d)') + regexp = re.compile(br'(\d)') c = BytesIO(b'123') dt = [('num', np.float64)] a = np.array([1, 2, 3], dtype=dt) @@ -1329,7 +1329,7 @@ def test_compiled_bytes(self): assert_array_equal(x, a) def test_bad_dtype_not_structured(self): - regexp = re.compile(b'(\\d)') + regexp = re.compile(br'(\d)') c = BytesIO(b'123') with pytest.raises(TypeError, match='structured datatype'): np.fromregex(c, regexp, dtype=np.float64) diff --git a/tools/c_coverage/c_coverage_report.py b/tools/c_coverage/c_coverage_report.py index 956d1872229e..0d65bf3af075 100755 --- a/tools/c_coverage/c_coverage_report.py +++ b/tools/c_coverage/c_coverage_report.py @@ -123,13 +123,13 @@ def collect_stats(files, fd, pattern): current_file = None current_function = None for line in fd: - if re.match("f[lie]=.+", line): + if re.match(r"f[lie]=.+", line): path = line.split('=', 2)[1].strip() if os.path.exists(path) and re.search(pattern, path): current_file = files.get_file(path) else: current_file = None - elif re.match("fn=.+", line): + elif re.match(r"fn=.+", line): current_function = line.split('=', 2)[1].strip() elif current_file is not None: for regex in line_regexs: diff --git a/tools/changelog.py b/tools/changelog.py index de203e2f1de2..f1f42f9333d0 100755 --- a/tools/changelog.py +++ b/tools/changelog.py @@ -147,12 +147,12 @@ def backtick_repl(matchobj): # substitute any single backtick not adjacent to a backtick # for a double backtick title = re.sub( - "(?P
(?:^|(?<=[^`])))`(?P(?=[^`]|$))",
+            r"(?P
(?:^|(?<=[^`])))`(?P(?=[^`]|$))",
             r"\g
``\g",
             title
         )
         # add an escaped space if code block is not followed by a space
-        title = re.sub("``(.*?)``(.)", backtick_repl, title)
+        title = re.sub(r"``(.*?)``(.)", backtick_repl, title)
 
         # sanitize asterisks
         title = title.replace('*', '\\*')
diff --git a/tools/refguide_check.py b/tools/refguide_check.py
index dbe6d951926d..ea7e74918a88 100644
--- a/tools/refguide_check.py
+++ b/tools/refguide_check.py
@@ -524,7 +524,7 @@ def check_rest(module, names, dots=True):
                                 traceback.format_exc()))
                 continue
 
-        m = re.search("([\x00-\x09\x0b-\x1f])", text)
+        m = re.search("([\x00-\x09\x0b-\x1f])", text)  # noqa: RUF039
         if m:
             msg = ("Docstring contains a non-printable character %r! "
                    "Maybe forgot r\"\"\"?" % (m.group(1),))

From 4d81238f8ff17b6a5e4c1f36829438c88c718a54 Mon Sep 17 00:00:00 2001
From: Dimitri Papadopoulos
 <3234522+DimitriPapadopoulos@users.noreply.github.com>
Date: Thu, 17 Apr 2025 19:59:22 +0200
Subject: [PATCH 047/202] MNT: discard Python 2 leftover

---
 tools/refguide_check.py | 6 +-----
 1 file changed, 1 insertion(+), 5 deletions(-)

diff --git a/tools/refguide_check.py b/tools/refguide_check.py
index dbe6d951926d..e19d98db8bdd 100644
--- a/tools/refguide_check.py
+++ b/tools/refguide_check.py
@@ -489,11 +489,7 @@ def check_rest(module, names, dots=True):
         List of [(module_name, success_flag, output),...]
     """
 
-    try:
-        skip_types = (dict, str, unicode, float, int)
-    except NameError:
-        # python 3
-        skip_types = (dict, str, float, int)
+    skip_types = (dict, str, float, int)
 
     results = []
 

From 3deea5346853516922369911d90cf7029368d5ad Mon Sep 17 00:00:00 2001
From: Marco Edward Gorelli 
Date: Thu, 17 Apr 2025 19:16:25 +0100
Subject: [PATCH 048/202] TYP: Type ``MaskedArray.put``, ``np.ma.put``,
 ``np.ma.putmask`` (#28745)

---
 numpy/ma/core.pyi                     |  7 ++++---
 numpy/typing/tests/data/fail/ma.pyi   |  6 ++++++
 numpy/typing/tests/data/reveal/ma.pyi | 10 ++++++++++
 3 files changed, 20 insertions(+), 3 deletions(-)

diff --git a/numpy/ma/core.pyi b/numpy/ma/core.pyi
index d99421f3dd14..b56f15bd56d4 100644
--- a/numpy/ma/core.pyi
+++ b/numpy/ma/core.pyi
@@ -28,6 +28,7 @@ from numpy._typing import (
     ArrayLike,
     NDArray,
     _ArrayLike,
+    _ArrayLikeBool_co,
     _ArrayLikeInt,
     _ArrayLikeInt_co,
     _DTypeLikeBool,
@@ -473,7 +474,7 @@ class MaskedArray(ndarray[_ShapeT_co, _DTypeT_co]):
     def ravel(self, order=...): ...
     def reshape(self, *s, **kwargs): ...
     def resize(self, newshape, refcheck=..., order=...): ...
-    def put(self, indices, values, mode=...): ...
+    def put(self, indices: _ArrayLikeInt_co, values: ArrayLike, mode: _ModeKind = "raise") -> None: ...
     def ids(self) -> tuple[int, int]: ...
     def iscontiguous(self) -> bool: ...
     def all(self, axis=..., out=..., keepdims=...): ...
@@ -1133,8 +1134,8 @@ def concatenate(arrays, axis=...): ...
 def diag(v, k=...): ...
 def left_shift(a, n): ...
 def right_shift(a, n): ...
-def put(a, indices, values, mode=...): ...
-def putmask(a, mask, values): ...
+def put(a: NDArray[Any], indices: _ArrayLikeInt_co, values: ArrayLike, mode: _ModeKind = 'raise') -> None: ...
+def putmask(a: NDArray[Any], mask: _ArrayLikeBool_co, values: ArrayLike) -> None: ...
 def transpose(a, axes=...): ...
 def reshape(a, new_shape, order=...): ...
 def resize(x, new_shape): ...
diff --git a/numpy/typing/tests/data/fail/ma.pyi b/numpy/typing/tests/data/fail/ma.pyi
index df9628d26479..19a3e7128ac4 100644
--- a/numpy/typing/tests/data/fail/ma.pyi
+++ b/numpy/typing/tests/data/fail/ma.pyi
@@ -108,3 +108,9 @@ m < (lambda x: 'mango') # E: No overload variant
 m.count(axis=0.)  # E: No overload variant
 
 np.ma.count(m, axis=0.)  # E: No overload variant
+
+m.put(4, 999, mode='flip')  # E: No overload variant
+
+np.ma.put(m, 4, 999, mode='flip')  # E: No overload variant
+
+np.ma.put([1,1,3], 0, 999)  # E: No overload variant
diff --git a/numpy/typing/tests/data/reveal/ma.pyi b/numpy/typing/tests/data/reveal/ma.pyi
index e17c6659cec4..5027d2996cc0 100644
--- a/numpy/typing/tests/data/reveal/ma.pyi
+++ b/numpy/typing/tests/data/reveal/ma.pyi
@@ -248,6 +248,16 @@ assert_type(np.ma.count(MAR_o, keepdims=True), NDArray[np.int_])
 assert_type(np.ma.count(MAR_o, axis=None, keepdims=True), NDArray[np.int_])
 assert_type(np.ma.count(MAR_o, None, True), NDArray[np.int_])
 
+assert_type(MAR_f4.put([0,4,8], [10,20,30]), None)
+assert_type(MAR_f4.put(4, 999), None)
+assert_type(MAR_f4.put(4, 999, mode='clip'), None)
+
+assert_type(np.ma.put(MAR_f4, [0,4,8], [10,20,30]), None)
+assert_type(np.ma.put(MAR_f4, 4, 999), None)
+assert_type(np.ma.put(MAR_f4, 4, 999, mode='clip'), None)
+
+assert_type(np.ma.putmask(MAR_f4, [True, False], [0, 1]), None)
+
 assert_type(MAR_f4.filled(float('nan')), NDArray[np.float32])
 assert_type(MAR_i8.filled(), NDArray[np.int64])
 assert_type(MAR_1d.filled(), np.ndarray[tuple[int], np.dtype[Any]])

From 36d8febb4697761aa45a22fa87bed1de0f4d412c Mon Sep 17 00:00:00 2001
From: Dimitri Papadopoulos
 <3234522+DimitriPapadopoulos@users.noreply.github.com>
Date: Thu, 17 Apr 2025 20:13:58 +0200
Subject: [PATCH 049/202] MNT: Apply ruff/Pylint rule  PLW0129

Asserting on a non-empty string literal will always pass

This line had been modified by #28214 / b45b614 without any explanation.
I believe it's an error as the current assertion is a no-op. Change to
have the test actually test something.
---
 numpy/tests/test_configtool.py | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/numpy/tests/test_configtool.py b/numpy/tests/test_configtool.py
index a758ad7feb72..a26f911744b6 100644
--- a/numpy/tests/test_configtool.py
+++ b/numpy/tests/test_configtool.py
@@ -31,7 +31,7 @@ def test_configtool_version(self):
 
     def test_configtool_cflags(self):
         stdout = self.check_numpyconfig('--cflags')
-        assert f'-I{os.fspath(INCLUDE_DIR)}'
+        assert f'-I{os.fspath(INCLUDE_DIR)}' in stdout
 
     def test_configtool_pkgconfigdir(self):
         stdout = self.check_numpyconfig('--pkgconfigdir')

From 6ea3b91fef8c6748b2c0e98ac2be5371aaad2a18 Mon Sep 17 00:00:00 2001
From: Dimitri Papadopoulos
 <3234522+DimitriPapadopoulos@users.noreply.github.com>
Date: Thu, 17 Apr 2025 20:21:24 +0200
Subject: [PATCH 050/202] MNT: Apply ruff/Pylint rule  PLW0129

Asserting on a non-empty string literal will always pass

This line had been added by #25181 / 0f6e357 without any explanation.
I believe it's an error because the assertion is a no-op. So remove it.
---
 numpy/f2py/tests/test_f2py2e.py | 1 -
 1 file changed, 1 deletion(-)

diff --git a/numpy/f2py/tests/test_f2py2e.py b/numpy/f2py/tests/test_f2py2e.py
index c0f6cb05161f..936883ffc1fd 100644
--- a/numpy/f2py/tests/test_f2py2e.py
+++ b/numpy/f2py/tests/test_f2py2e.py
@@ -149,7 +149,6 @@ def test_gh22819_cli(capfd, gh22819_cli, monkeypatch):
         assert "blah-f2pywrappers.f" not in gen_paths
         assert "test_22819-f2pywrappers.f" in gen_paths
         assert "test_22819module.c" in gen_paths
-        assert "Ignoring blah"
 
 
 def test_gh22819_many_pyf(capfd, gh22819_cli, monkeypatch):

From 8babcb96a8b0a0e5bc5b133a56c3469d55ee1346 Mon Sep 17 00:00:00 2001
From: Dimitri Papadopoulos
 <3234522+DimitriPapadopoulos@users.noreply.github.com>
Date: Thu, 17 Apr 2025 20:41:46 +0200
Subject: [PATCH 051/202] MNT: Apply ruff/Pylint rule PLE0302

The special method `__getitem__` expects 2 parameters, 1 was given
---
 numpy/_core/tests/test_array_coercion.py | 6 +++---
 numpy/_core/tests/test_multiarray.py     | 2 +-
 2 files changed, 4 insertions(+), 4 deletions(-)

diff --git a/numpy/_core/tests/test_array_coercion.py b/numpy/_core/tests/test_array_coercion.py
index 9cdf3952bdf3..b0735c1c2cbe 100644
--- a/numpy/_core/tests/test_array_coercion.py
+++ b/numpy/_core/tests/test_array_coercion.py
@@ -46,7 +46,7 @@ class _SequenceLike:
         def __len__(self):
             raise TypeError
 
-        def __getitem__(self):
+        def __getitem__(self):  # noqa: PLE0302
             raise TypeError
 
     # Array-interface
@@ -636,7 +636,7 @@ def __len__(self):
                 obj[0][0] = 2  # replace with a different list.
                 raise ValueError("not actually a sequence!")
 
-            def __getitem__(self):
+            def __getitem__(self):  # noqa: PLE0302
                 pass
 
         # Runs into a corner case in the new code, the `array(2)` is cached
@@ -758,7 +758,7 @@ class BadSequence:
             def __len__(self):
                 raise error
 
-            def __getitem__(self):
+            def __getitem__(self):  # noqa: PLE0302
                 # must have getitem to be a Sequence
                 return 1
 
diff --git a/numpy/_core/tests/test_multiarray.py b/numpy/_core/tests/test_multiarray.py
index cf02d39eb085..199bf7769bc0 100644
--- a/numpy/_core/tests/test_multiarray.py
+++ b/numpy/_core/tests/test_multiarray.py
@@ -638,7 +638,7 @@ def test_stringlike_empty_list(self):
         b = np.array([b'done'])
 
         class bad_sequence:
-            def __getitem__(self): pass
+            def __getitem__(self): pass  # noqa: PLE0302
             def __len__(self): raise RuntimeError
 
         assert_raises(ValueError, operator.setitem, u, 0, [])

From 3fff7631118620d4d8c1ec2c5b059fa0176fc80d Mon Sep 17 00:00:00 2001
From: Dimitri Papadopoulos
 <3234522+DimitriPapadopoulos@users.noreply.github.com>
Date: Thu, 17 Apr 2025 20:43:21 +0200
Subject: [PATCH 052/202] MNT: Apply ruff/Pylint rule PLE0605

Invalid format for `__all__`, must be `tuple` or `list`
---
 numpy/fft/__init__.py    | 2 +-
 numpy/linalg/__init__.py | 2 +-
 numpy/ma/testutils.py    | 2 +-
 numpy/matlib.py          | 2 +-
 4 files changed, 4 insertions(+), 4 deletions(-)

diff --git a/numpy/fft/__init__.py b/numpy/fft/__init__.py
index 36bddd353966..aaea3ea2fe54 100644
--- a/numpy/fft/__init__.py
+++ b/numpy/fft/__init__.py
@@ -207,7 +207,7 @@
 from ._pocketfft import *
 from ._helper import *
 
-__all__ = _pocketfft.__all__.copy()
+__all__ = _pocketfft.__all__.copy()  # noqa: PLE0605
 __all__ += _helper.__all__
 
 from numpy._pytesttester import PytestTester
diff --git a/numpy/linalg/__init__.py b/numpy/linalg/__init__.py
index 274fd9085533..acb04d4e2136 100644
--- a/numpy/linalg/__init__.py
+++ b/numpy/linalg/__init__.py
@@ -88,7 +88,7 @@
 from . import _linalg
 from ._linalg import *
 
-__all__ = _linalg.__all__.copy()
+__all__ = _linalg.__all__.copy()  # noqa: PLE0605
 
 from numpy._pytesttester import PytestTester
 test = PytestTester(__name__)
diff --git a/numpy/ma/testutils.py b/numpy/ma/testutils.py
index c51256047c27..ce597b3d5e99 100644
--- a/numpy/ma/testutils.py
+++ b/numpy/ma/testutils.py
@@ -35,7 +35,7 @@
     'assert_raises'
     ]
 
-__all__ = __all__masked + __some__from_testing
+__all__ = __all__masked + __some__from_testing  # noqa: PLE0605
 
 
 def approx(a, b, fill_value=True, rtol=1e-5, atol=1e-8):
diff --git a/numpy/matlib.py b/numpy/matlib.py
index 7a99b82e0ef0..1c449ce8800f 100644
--- a/numpy/matlib.py
+++ b/numpy/matlib.py
@@ -18,7 +18,7 @@
 
 __version__ = np.__version__
 
-__all__ = np.__all__[:]  # copy numpy namespace
+__all__ = np.__all__[:]  # copy numpy namespace  # noqa: PLE0605
 __all__ += ['rand', 'randn', 'repmat']
 
 def empty(shape, dtype=None, order='C'):

From ee4fb00bddc84be3003a07ea113a36e6d73739e0 Mon Sep 17 00:00:00 2001
From: Dimitri Papadopoulos
 <3234522+DimitriPapadopoulos@users.noreply.github.com>
Date: Thu, 17 Apr 2025 20:44:13 +0200
Subject: [PATCH 053/202] MNT: Enforce ruff/Pylint Error rules (PLE)

---
 ruff.toml | 1 +
 1 file changed, 1 insertion(+)

diff --git a/ruff.toml b/ruff.toml
index 378be76651eb..4dab12cf0aee 100644
--- a/ruff.toml
+++ b/ruff.toml
@@ -20,6 +20,7 @@ extend-select = [
     "E",
     "W",
     "PGH",
+    "PLE",
 ]
 ignore = [
     "F",     # TODO: enable Pyflakes rules

From 65de73e814474eaa9a4f270e8061068837332c0c Mon Sep 17 00:00:00 2001
From: Dimitri Papadopoulos
 <3234522+DimitriPapadopoulos@users.noreply.github.com>
Date: Thu, 17 Apr 2025 21:16:55 +0200
Subject: [PATCH 054/202] MNT: Different solution for PLE0302

Co-authored-by: Joren Hammudoglu 
---
 numpy/_core/tests/test_array_coercion.py | 6 +++---
 numpy/_core/tests/test_multiarray.py     | 2 +-
 2 files changed, 4 insertions(+), 4 deletions(-)

diff --git a/numpy/_core/tests/test_array_coercion.py b/numpy/_core/tests/test_array_coercion.py
index b0735c1c2cbe..9301f3fd92c8 100644
--- a/numpy/_core/tests/test_array_coercion.py
+++ b/numpy/_core/tests/test_array_coercion.py
@@ -46,7 +46,7 @@ class _SequenceLike:
         def __len__(self):
             raise TypeError
 
-        def __getitem__(self):  # noqa: PLE0302
+        def __getitem__(self, _, /):
             raise TypeError
 
     # Array-interface
@@ -636,7 +636,7 @@ def __len__(self):
                 obj[0][0] = 2  # replace with a different list.
                 raise ValueError("not actually a sequence!")
 
-            def __getitem__(self):  # noqa: PLE0302
+            def __getitem__(self, _, /):
                 pass
 
         # Runs into a corner case in the new code, the `array(2)` is cached
@@ -758,7 +758,7 @@ class BadSequence:
             def __len__(self):
                 raise error
 
-            def __getitem__(self):  # noqa: PLE0302
+            def __getitem__(self, _, /):
                 # must have getitem to be a Sequence
                 return 1
 
diff --git a/numpy/_core/tests/test_multiarray.py b/numpy/_core/tests/test_multiarray.py
index 199bf7769bc0..214e30e4da2b 100644
--- a/numpy/_core/tests/test_multiarray.py
+++ b/numpy/_core/tests/test_multiarray.py
@@ -638,7 +638,7 @@ def test_stringlike_empty_list(self):
         b = np.array([b'done'])
 
         class bad_sequence:
-            def __getitem__(self): pass  # noqa: PLE0302
+            def __getitem__(self, _, /): pass
             def __len__(self): raise RuntimeError
 
         assert_raises(ValueError, operator.setitem, u, 0, [])

From 009beb292d6b17568de0b7d4d416ededae0185d0 Mon Sep 17 00:00:00 2001
From: Dimitri Papadopoulos
 <3234522+DimitriPapadopoulos@users.noreply.github.com>
Date: Thu, 17 Apr 2025 21:26:16 +0200
Subject: [PATCH 055/202] MNT: Different solution for PLE0605

Co-authored-by: Joren Hammudoglu 
---
 numpy/matlib.py | 4 ++--
 1 file changed, 2 insertions(+), 2 deletions(-)

diff --git a/numpy/matlib.py b/numpy/matlib.py
index 1c449ce8800f..4b11015046e8 100644
--- a/numpy/matlib.py
+++ b/numpy/matlib.py
@@ -18,8 +18,8 @@
 
 __version__ = np.__version__
 
-__all__ = np.__all__[:]  # copy numpy namespace  # noqa: PLE0605
-__all__ += ['rand', 'randn', 'repmat']
+__all__ = ['rand', 'randn', 'repmat']
+__all__ += np.__all__
 
 def empty(shape, dtype=None, order='C'):
     """Return a new matrix of given shape and type, without initializing entries.

From e71a2242ca005d7e660fbb4f6f898be19f278639 Mon Sep 17 00:00:00 2001
From: Dimitri Papadopoulos
 <3234522+DimitriPapadopoulos@users.noreply.github.com>
Date: Thu, 17 Apr 2025 22:14:05 +0200
Subject: [PATCH 056/202] STY: Apply ruff/pyupgrade rule UP032

Use f-string instead of `format` call
---
 numpy/__init__.py                             |  5 ++---
 numpy/_core/_exceptions.py                    | 21 +++++++------------
 numpy/_core/_internal.py                      |  8 +++----
 .../code_generators/generate_numpy_api.py     |  7 ++++---
 numpy/_core/einsumfunc.py                     |  4 ++--
 numpy/_core/fromnumeric.py                    |  3 +--
 numpy/_core/function_base.py                  |  5 ++---
 numpy/_core/getlimits.py                      |  4 ++--
 numpy/_core/shape_base.py                     | 15 +++++--------
 numpy/_core/tests/test_shape_base.py          |  5 ++---
 numpy/conftest.py                             |  9 ++++----
 numpy/f2py/__init__.py                        |  3 +--
 numpy/lib/__init__.py                         |  3 +--
 numpy/lib/_arraypad_impl.py                   |  4 ++--
 numpy/lib/_function_base_impl.py              |  2 +-
 numpy/lib/tests/test_histograms.py            | 12 +++++------
 numpy/random/tests/test_extending.py          |  3 +--
 numpy/tests/test_public_api.py                |  8 +++----
 numpy/tests/test_warnings.py                  |  8 +++----
 tools/swig/test/testFarray.py                 |  2 +-
 tools/wheels/check_license.py                 |  4 ++--
 21 files changed, 58 insertions(+), 77 deletions(-)

diff --git a/numpy/__init__.py b/numpy/__init__.py
index 67db9bcaf750..f1eb956c5b8c 100644
--- a/numpy/__init__.py
+++ b/numpy/__init__.py
@@ -410,8 +410,7 @@ def __getattr__(attr):
             import numpy.char as char
             return char.chararray
 
-        raise AttributeError("module {!r} has no attribute "
-                             "{!r}".format(__name__, attr))
+        raise AttributeError(f"module {__name__!r} has no attribute {attr!r}")
 
     def __dir__():
         public_symbols = (
@@ -485,7 +484,7 @@ def _mac_os_check():
                             "\nIf you compiled yourself, more information is available at:"
                             "\nhttps://numpy.org/devdocs/building/index.html"
                             "\nOtherwise report this to the vendor "
-                            "that provided NumPy.\n\n{}\n".format(error_message))
+                            f"that provided NumPy.\n\n{error_message}\n")
                         raise RuntimeError(msg)
                 del _wn
             del w
diff --git a/numpy/_core/_exceptions.py b/numpy/_core/_exceptions.py
index 3db1b9af8674..180e71946e6c 100644
--- a/numpy/_core/_exceptions.py
+++ b/numpy/_core/_exceptions.py
@@ -44,12 +44,9 @@ def __init__(self, ufunc, dtypes):
 
     def __str__(self):
         return (
-            "ufunc {!r} did not contain a loop with signature matching types "
-            "{!r} -> {!r}"
-        ).format(
-            self.ufunc.__name__,
-            _unpack_tuple(self.dtypes[:self.ufunc.nin]),
-            _unpack_tuple(self.dtypes[self.ufunc.nin:])
+            f"ufunc {self.ufunc.__name__!r} did not contain a loop with signature "
+            f"matching types {_unpack_tuple(self.dtypes[:self.ufunc.nin])!r} "
+            f"-> {_unpack_tuple(self.dtypes[self.ufunc.nin:])!r}"
         )
 
 
@@ -88,10 +85,8 @@ def __str__(self):
         # only show the number if more than one input exists
         i_str = f"{self.in_i} " if self.ufunc.nin != 1 else ""
         return (
-            "Cannot cast ufunc {!r} input {}from {!r} to {!r} with casting "
-            "rule {!r}"
-        ).format(
-            self.ufunc.__name__, i_str, self.from_, self.to, self.casting
+            f"Cannot cast ufunc {self.ufunc.__name__!r} input {i_str}from "
+            f"{self.from_!r} to {self.to!r} with casting rule {self.casting!r}"
         )
 
 
@@ -106,10 +101,8 @@ def __str__(self):
         # only show the number if more than one output exists
         i_str = f"{self.out_i} " if self.ufunc.nout != 1 else ""
         return (
-            "Cannot cast ufunc {!r} output {}from {!r} to {!r} with casting "
-            "rule {!r}"
-        ).format(
-            self.ufunc.__name__, i_str, self.from_, self.to, self.casting
+            f"Cannot cast ufunc {self.ufunc.__name__!r} output {i_str}from "
+            f"{self.from_!r} to {self.to!r} with casting rule {self.casting!r}"
         )
 
 
diff --git a/numpy/_core/_internal.py b/numpy/_core/_internal.py
index a10b812098e3..b24a2cc6117a 100644
--- a/numpy/_core/_internal.py
+++ b/numpy/_core/_internal.py
@@ -878,15 +878,15 @@ def array_ufunc_errmsg_formatter(dummy, ufunc, method, *inputs, **kwargs):
     args = inputs + kwargs.get('out', ())
     types_string = ', '.join(repr(type(arg).__name__) for arg in args)
     return ('operand type(s) all returned NotImplemented from '
-            '__array_ufunc__({!r}, {!r}, {}): {}'
-            .format(ufunc, method, args_string, types_string))
+            f'__array_ufunc__({ufunc!r}, {method!r}, {args_string}): {types_string}'
+            )
 
 
 def array_function_errmsg_formatter(public_api, types):
     """ Format the error message for when __array_ufunc__ gives up. """
     func_name = f'{public_api.__module__}.{public_api.__name__}'
-    return ("no implementation found for '{}' on types that implement "
-            '__array_function__: {}'.format(func_name, list(types)))
+    return (f"no implementation found for '{func_name}' on types that implement "
+            f'__array_function__: {list(types)}')
 
 
 def _ufunc_doc_signature_formatter(ufunc):
diff --git a/numpy/_core/code_generators/generate_numpy_api.py b/numpy/_core/code_generators/generate_numpy_api.py
index 43a1b83f4691..42be369ae2e6 100644
--- a/numpy/_core/code_generators/generate_numpy_api.py
+++ b/numpy/_core/code_generators/generate_numpy_api.py
@@ -267,10 +267,11 @@ def do_generate_api(targets, sources):
     if len(multiarray_api_dict) != len(multiarray_api_index):
         keys_dict = set(multiarray_api_dict.keys())
         keys_index = set(multiarray_api_index.keys())
+        keys_index_dict = keys_index - keys_dict
+        keys_dict_index = keys_dict - keys_index
         raise AssertionError(
-            "Multiarray API size mismatch - "
-            "index has extra keys {}, dict has extra keys {}"
-            .format(keys_index - keys_dict, keys_dict - keys_index)
+            f"Multiarray API size mismatch - index has extra keys {keys_index_dict}, "
+            f"dict has extra keys {keys_dict_index}"
         )
 
     extension_list = []
diff --git a/numpy/_core/einsumfunc.py b/numpy/_core/einsumfunc.py
index b3d16c603fd6..13ea54326a08 100644
--- a/numpy/_core/einsumfunc.py
+++ b/numpy/_core/einsumfunc.py
@@ -1013,8 +1013,8 @@ def einsum_path(*operands, optimize='greedy', einsum_call=False):
         # Explicit "einsum_path" is usually trusted, but we detect this kind of
         # mistake in order to prevent from returning an intermediate value.
         raise RuntimeError(
-            "Invalid einsum_path is specified: {} more operands has to be "
-            "contracted.".format(len(input_list) - 1))
+            f"Invalid einsum_path is specified: {len(input_list) - 1} more "
+            "operands has to be contracted.")
 
     if einsum_call_arg:
         return (operands, contraction_list)
diff --git a/numpy/_core/fromnumeric.py b/numpy/_core/fromnumeric.py
index 202bcde9e570..1b8b5198277a 100644
--- a/numpy/_core/fromnumeric.py
+++ b/numpy/_core/fromnumeric.py
@@ -565,8 +565,7 @@ def put(a, ind, v, mode='raise'):
     try:
         put = a.put
     except AttributeError as e:
-        raise TypeError("argument 1 must be numpy.ndarray, "
-                        "not {name}".format(name=type(a).__name__)) from e
+        raise TypeError(f"argument 1 must be numpy.ndarray, not {type(a)}") from e
 
     return put(ind, v, mode=mode)
 
diff --git a/numpy/_core/function_base.py b/numpy/_core/function_base.py
index cba071768ab7..f22aa6908c7b 100644
--- a/numpy/_core/function_base.py
+++ b/numpy/_core/function_base.py
@@ -473,9 +473,8 @@ def _needs_add_docstring(obj):
 def _add_docstring(obj, doc, warn_on_python):
     if warn_on_python and not _needs_add_docstring(obj):
         warnings.warn(
-            "add_newdoc was used on a pure-python object {}. "
-            "Prefer to attach it directly to the source."
-            .format(obj),
+            f"add_newdoc was used on a pure-python object {obj}. "
+            "Prefer to attach it directly to the source.",
             UserWarning,
             stacklevel=3)
     try:
diff --git a/numpy/_core/getlimits.py b/numpy/_core/getlimits.py
index c9f39ae25c5e..feec9139a26b 100644
--- a/numpy/_core/getlimits.py
+++ b/numpy/_core/getlimits.py
@@ -79,8 +79,8 @@ def smallest_subnormal(self):
         value = self._smallest_subnormal
         if self.ftype(0) == value:
             warnings.warn(
-                'The value of the smallest subnormal for {} type '
-                'is zero.'.format(self.ftype), UserWarning, stacklevel=2)
+                f'The value of the smallest subnormal for {self.ftype} type is zero.',
+                UserWarning, stacklevel=2)
 
         return self._float_to_float(value)
 
diff --git a/numpy/_core/shape_base.py b/numpy/_core/shape_base.py
index a36aa1a9e00b..62334695eb7b 100644
--- a/numpy/_core/shape_base.py
+++ b/numpy/_core/shape_base.py
@@ -594,11 +594,9 @@ def _block_check_depths_match(arrays, parent_index=[]):
         #  - horribly confusing behaviour that results when tuples are
         #    treated like ndarray
         raise TypeError(
-            '{} is a tuple. '
+            f'{_block_format_index(parent_index)} is a tuple. '
             'Only lists can be used to arrange blocks, and np.block does '
-            'not allow implicit conversion from tuple to ndarray.'.format(
-                _block_format_index(parent_index)
-            )
+            'not allow implicit conversion from tuple to ndarray.'
         )
     elif type(arrays) is list and len(arrays) > 0:
         idxs_ndims = (_block_check_depths_match(arr, parent_index + [i])
@@ -611,12 +609,9 @@ def _block_check_depths_match(arrays, parent_index=[]):
                 max_arr_ndim = ndim
             if len(index) != len(first_index):
                 raise ValueError(
-                    "List depths are mismatched. First element was at depth "
-                    "{}, but there is an element at depth {} ({})".format(
-                        len(first_index),
-                        len(index),
-                        _block_format_index(index)
-                    )
+                    "List depths are mismatched. First element was at "
+                    f"depth {len(first_index)}, but there is an element at "
+                    f"depth {len(index)} ({_block_format_index(index)})"
                 )
             # propagate our flag that indicates an empty list at the bottom
             if index[-1] is None:
diff --git a/numpy/_core/tests/test_shape_base.py b/numpy/_core/tests/test_shape_base.py
index 3c4346af40d9..58a36e8c022f 100644
--- a/numpy/_core/tests/test_shape_base.py
+++ b/numpy/_core/tests/test_shape_base.py
@@ -261,9 +261,8 @@ def test_exceptions(self):
             assert_raises_regex(
                 ValueError,
                 "all the input array dimensions except for the concatenation axis "
-                "must match exactly, but along dimension {}, the array at "
-                "index 0 has size 1 and the array at index 1 has size 2"
-                .format(i),
+                f"must match exactly, but along dimension {i}, the array at "
+                "index 0 has size 1 and the array at index 1 has size 2",
                 np.concatenate, (a, b), axis=axis[1])
             assert_raises(ValueError, np.concatenate, (a, b), axis=axis[2])
             a = np.moveaxis(a, -1, 0)
diff --git a/numpy/conftest.py b/numpy/conftest.py
index 9a09765ae3e5..9ae2b290ee71 100644
--- a/numpy/conftest.py
+++ b/numpy/conftest.py
@@ -133,15 +133,14 @@ def check_fpu_mode(request):
     new_mode = get_fpu_mode()
 
     if old_mode != new_mode:
-        raise AssertionError("FPU precision mode changed from {:#x} to {:#x}"
-                             " during the test".format(old_mode, new_mode))
+        raise AssertionError(f"FPU precision mode changed from {old_mode:#x} to "
+                             f"{new_mode:#x} during the test")
 
     collect_result = _collect_results.get(request.node)
     if collect_result is not None:
         old_mode, new_mode = collect_result
-        raise AssertionError("FPU precision mode changed from {:#x} to {:#x}"
-                             " when collecting the test".format(old_mode,
-                                                                new_mode))
+        raise AssertionError(f"FPU precision mode changed from {old_mode:#x} to "
+                             f"{new_mode:#x} when collecting the test")
 
 
 @pytest.fixture(autouse=True)
diff --git a/numpy/f2py/__init__.py b/numpy/f2py/__init__.py
index 8bf1d637ec0c..a7ce9f2b080b 100644
--- a/numpy/f2py/__init__.py
+++ b/numpy/f2py/__init__.py
@@ -79,8 +79,7 @@ def __getattr__(attr):
         return test
 
     else:
-        raise AttributeError("module {!r} has no attribute "
-                              "{!r}".format(__name__, attr))
+        raise AttributeError(f"module {__name__!r} has no attribute {attr!r}")
 
 
 def __dir__():
diff --git a/numpy/lib/__init__.py b/numpy/lib/__init__.py
index e3ba0cf9044c..82297f488264 100644
--- a/numpy/lib/__init__.py
+++ b/numpy/lib/__init__.py
@@ -91,5 +91,4 @@ def __getattr__(attr):
             name=None
         )
     else:
-        raise AttributeError("module {!r} has no attribute "
-                             "{!r}".format(__name__, attr))
+        raise AttributeError(f"module {__name__!r} has no attribute {attr!r}")
diff --git a/numpy/lib/_arraypad_impl.py b/numpy/lib/_arraypad_impl.py
index 93754d4c360e..3956875bf4f5 100644
--- a/numpy/lib/_arraypad_impl.py
+++ b/numpy/lib/_arraypad_impl.py
@@ -826,8 +826,8 @@ def pad(array, pad_width, mode='constant', **kwargs):
         for axis, width_pair in zip(axes, pad_width):
             if array.shape[axis] == 0 and any(width_pair):
                 raise ValueError(
-                    "can't extend empty axis {} using modes other than "
-                    "'constant' or 'empty'".format(axis)
+                    f"can't extend empty axis {axis} using modes other than "
+                    "'constant' or 'empty'"
                 )
         # passed, don't need to do anything more as _pad_simple already
         # returned the correct result
diff --git a/numpy/lib/_function_base_impl.py b/numpy/lib/_function_base_impl.py
index 4382958ae9fa..359d42e9c6c0 100644
--- a/numpy/lib/_function_base_impl.py
+++ b/numpy/lib/_function_base_impl.py
@@ -5436,7 +5436,7 @@ def delete(arr, obj, axis=None):
             if obj.shape != (N,):
                 raise ValueError('boolean array argument obj to delete '
                                  'must be one dimensional and match the axis '
-                                 'length of {}'.format(N))
+                                 f'length of {N}')
 
             # optimization, the other branch is slower
             keep = ~obj
diff --git a/numpy/lib/tests/test_histograms.py b/numpy/lib/tests/test_histograms.py
index 64f54f522201..49ec7c34456f 100644
--- a/numpy/lib/tests/test_histograms.py
+++ b/numpy/lib/tests/test_histograms.py
@@ -462,8 +462,8 @@ def test_simple(self):
             x = np.concatenate((x1, x2))
             for estimator, numbins in expectedResults.items():
                 a, b = np.histogram(x, estimator)
-                assert_equal(len(a), numbins, err_msg="For the {} estimator "
-                             "with datasize of {}".format(estimator, testlen))
+                assert_equal(len(a), numbins, err_msg=f"For the {estimator} estimator "
+                             f"with datasize of {testlen}")
 
     def test_small(self):
         """
@@ -482,8 +482,8 @@ def test_small(self):
             testdat = np.arange(testlen).astype(float)
             for estimator, expbins in expectedResults.items():
                 a, b = np.histogram(testdat, estimator)
-                assert_equal(len(a), expbins, err_msg="For the {} estimator "
-                             "with datasize of {}".format(estimator, testlen))
+                assert_equal(len(a), expbins, err_msg=f"For the {estimator} estimator "
+                             f"with datasize of {testlen}")
 
     def test_incorrect_methods(self):
         """
@@ -504,8 +504,8 @@ def test_novariance(self):
 
         for estimator, numbins in novar_resultdict.items():
             a, b = np.histogram(novar_dataset, estimator)
-            assert_equal(len(a), numbins, err_msg="{} estimator, "
-                         "No Variance test".format(estimator))
+            assert_equal(len(a), numbins,
+                         err_msg=f"{estimator} estimator, No Variance test")
 
     def test_limited_variance(self):
         """
diff --git a/numpy/random/tests/test_extending.py b/numpy/random/tests/test_extending.py
index d6ffea0b2dbf..608f58756289 100644
--- a/numpy/random/tests/test_extending.py
+++ b/numpy/random/tests/test_extending.py
@@ -94,8 +94,7 @@ def test_cython(tmp_path):
             if txt_to_find in line:
                 break
         else:
-            assert False, ("Could not find '{}' in C file, "
-                           "wrong pxd used".format(txt_to_find))
+            assert False, f"Could not find '{txt_to_find}' in C file, wrong pxd used"
     # import without adding the directory to sys.path
     suffix = sysconfig.get_config_var('EXT_SUFFIX')
 
diff --git a/numpy/tests/test_public_api.py b/numpy/tests/test_public_api.py
index 1dccf2a8491d..729af9751fa1 100644
--- a/numpy/tests/test_public_api.py
+++ b/numpy/tests/test_public_api.py
@@ -378,7 +378,7 @@ def find_unexpected_members(mod_name):
 
     if unexpected_members:
         raise AssertionError("Found unexpected object(s) that look like "
-                             "modules: {}".format(unexpected_members))
+                             f"modules: {unexpected_members}")
 
 
 def test_api_importable():
@@ -404,7 +404,7 @@ def check_importable(module_name):
 
     if module_names:
         raise AssertionError("Modules in the public API that cannot be "
-                             "imported: {}".format(module_names))
+                             f"imported: {module_names}")
 
     for module_name in PUBLIC_ALIASED_MODULES:
         try:
@@ -414,7 +414,7 @@ def check_importable(module_name):
 
     if module_names:
         raise AssertionError("Modules in the public API that were not "
-                             "found: {}".format(module_names))
+                             f"found: {module_names}")
 
     with warnings.catch_warnings(record=True) as w:
         warnings.filterwarnings('always', category=DeprecationWarning)
@@ -426,7 +426,7 @@ def check_importable(module_name):
     if module_names:
         raise AssertionError("Modules that are not really public but looked "
                              "public and can not be imported: "
-                             "{}".format(module_names))
+                             f"{module_names}")
 
 
 @pytest.mark.xfail(
diff --git a/numpy/tests/test_warnings.py b/numpy/tests/test_warnings.py
index 9304c1346cbf..4cb9669ff589 100644
--- a/numpy/tests/test_warnings.py
+++ b/numpy/tests/test_warnings.py
@@ -34,8 +34,8 @@ def visit_Call(self, node):
         if p.ls[-1] == 'simplefilter' or p.ls[-1] == 'filterwarnings':
             if node.args[0].value == "ignore":
                 raise AssertionError(
-                    "warnings should have an appropriate stacklevel; found in "
-                    "{} on line {}".format(self.__filename, node.lineno))
+                    "warnings should have an appropriate stacklevel; "
+                    f"found in {self.__filename} on line {node.lineno}")
 
         if p.ls[-1] == 'warn' and (
                 len(p.ls) == 1 or p.ls[-2] == 'warnings'):
@@ -51,8 +51,8 @@ def visit_Call(self, node):
             if "stacklevel" in args:
                 return
             raise AssertionError(
-                "warnings should have an appropriate stacklevel; found in "
-                "{} on line {}".format(self.__filename, node.lineno))
+                "warnings should have an appropriate stacklevel; "
+                f"found in {self.__filename} on line {node.lineno}")
 
 
 @pytest.mark.slow
diff --git a/tools/swig/test/testFarray.py b/tools/swig/test/testFarray.py
index b611cee9d748..de98a52016b1 100755
--- a/tools/swig/test/testFarray.py
+++ b/tools/swig/test/testFarray.py
@@ -15,7 +15,7 @@
 
 # Add the distutils-generated build directory to the python search path and then
 # import the extension module
-libDir = "lib.{}-{}.{}".format(get_platform(), *sys.version_info[:2])
+libDir = f"lib.{get_platform()}-{sys.version_info[0]}.{sys.version_info[1]}"
 sys.path.insert(0, os.path.join("build", libDir))
 import Farray
 
diff --git a/tools/wheels/check_license.py b/tools/wheels/check_license.py
index 3610558ce913..0a29bdf69fc0 100644
--- a/tools/wheels/check_license.py
+++ b/tools/wheels/check_license.py
@@ -45,8 +45,8 @@ def main():
     ok = check_text(text)
     if not ok:
         print(
-            "ERROR: License text {} does not contain expected "
-            "text fragments\n".format(license_txt)
+            f"ERROR: License text {license_txt} does not contain expected "
+            "text fragments\n"
         )
         print(text)
         sys.exit(1)

From 39240592ad8ca5298023bbcc4333f7a3ca3ea063 Mon Sep 17 00:00:00 2001
From: Dimitri Papadopoulos
 <3234522+DimitriPapadopoulos@users.noreply.github.com>
Date: Fri, 18 Apr 2025 11:14:45 +0200
Subject: [PATCH 057/202] STY: Use f-string instead of `format` call

Fix residual occurrences not caught by ruff rule UP032,
especially in *.pyx files.
---
 doc/neps/nep-0013-ufunc-overrides.rst         |  2 +-
 .../reference/random/bit_generators/index.rst |  2 +-
 numpy/f2py/_src_pyf.py                        |  6 +-
 numpy/f2py/f2py2e.py                          | 11 ++--
 numpy/random/_common.pyx                      | 62 +++++++++----------
 numpy/random/_generator.pyx                   |  6 +-
 numpy/random/_mt19937.pyx                     |  3 +-
 numpy/random/_pcg64.pyx                       |  6 +-
 numpy/random/_philox.pyx                      |  3 +-
 numpy/random/_sfc64.pyx                       |  3 +-
 numpy/random/bit_generator.pyx                |  2 +-
 numpy/random/mtrand.pyx                       |  7 +--
 12 files changed, 53 insertions(+), 60 deletions(-)

diff --git a/doc/neps/nep-0013-ufunc-overrides.rst b/doc/neps/nep-0013-ufunc-overrides.rst
index d69af6924940..eea7bfb91949 100644
--- a/doc/neps/nep-0013-ufunc-overrides.rst
+++ b/doc/neps/nep-0013-ufunc-overrides.rst
@@ -526,7 +526,7 @@ multiplication::
         def __init__(self, value):
             self.value = value
         def __repr__(self):
-            return "MyObject({!r})".format(self.value)
+            return f"MyObject({self.value!r})"
         def __mul__(self, other):
             return MyObject(1234)
         def __rmul__(self, other):
diff --git a/doc/source/reference/random/bit_generators/index.rst b/doc/source/reference/random/bit_generators/index.rst
index 00f9edb4af59..cb9650b07d85 100644
--- a/doc/source/reference/random/bit_generators/index.rst
+++ b/doc/source/reference/random/bit_generators/index.rst
@@ -91,7 +91,7 @@ user, which is up to you.
     # If the user did not provide a seed, it should return `None`.
     seed = get_user_seed()
     ss = SeedSequence(seed)
-    print('seed = {}'.format(ss.entropy))
+    print(f'seed = {ss.entropy}')
     bg = PCG64(ss)
 
 .. end_block
diff --git a/numpy/f2py/_src_pyf.py b/numpy/f2py/_src_pyf.py
index d5a759f84411..51ca6493bf91 100644
--- a/numpy/f2py/_src_pyf.py
+++ b/numpy/f2py/_src_pyf.py
@@ -169,8 +169,10 @@ def listrepl(mobj):
             elif num == numsubs:
                 rules[r] = rule
             else:
-                print("Mismatch in number of replacements (base <{}={}>) "
-                      "for <{}={}>. Ignoring.".format(base_rule, ','.join(rules[base_rule]), r, thelist))
+                rules_base_rule = ','.join(rules[base_rule])
+                print("Mismatch in number of replacements "
+                      f"(base <{base_rule}={rules_base_rule}>) "
+                      f"for <{r}={thelist}>. Ignoring.")
     if not rules:
         return substr
 
diff --git a/numpy/f2py/f2py2e.py b/numpy/f2py/f2py2e.py
index c0f801e06c7f..5fcc48ea5ce4 100644
--- a/numpy/f2py/f2py2e.py
+++ b/numpy/f2py/f2py2e.py
@@ -479,13 +479,14 @@ def run_main(comline_list):
                     isusedby[u] = []
                 isusedby[u].append(plist['name'])
     for plist in postlist:
-        if plist['block'] == 'python module' and '__user__' in plist['name']:
-            if plist['name'] in isusedby:
+        module_name = plist['name']
+        if plist['block'] == 'python module' and '__user__' in module_name:
+            if module_name in isusedby:
                 # if not quiet:
+                usedby = ','.join(f'"{s}"' for s in isusedby[module_name])
                 outmess(
-                    f'Skipping Makefile build for module "{plist["name"]}" '
-                    'which is used by {}\n'.format(
-                        ','.join(f'"{s}"' for s in isusedby[plist['name']])))
+                    f'Skipping Makefile build for module "{module_name}" '
+                    f'which is used by {usedby}\n')
     if 'signsfile' in options:
         if options['verbose'] > 1:
             outmess(
diff --git a/numpy/random/_common.pyx b/numpy/random/_common.pyx
index 8944b5f061db..f8420b3951cc 100644
--- a/numpy/random/_common.pyx
+++ b/numpy/random/_common.pyx
@@ -224,8 +224,7 @@ cdef np.ndarray int_to_array(object value, object name, object bits, object uint
         value = int(value)
         upper = int(2)**int(bits)
         if value < 0 or value >= upper:
-            raise ValueError('{name} must be positive and '
-                             'less than 2**{bits}.'.format(name=name, bits=bits))
+            raise ValueError(f'{name} must be positive and less than 2**{bits}.')
 
         out = np.empty(len, dtype=dtype)
         for i in range(len):
@@ -234,8 +233,7 @@ cdef np.ndarray int_to_array(object value, object name, object bits, object uint
     else:
         out = value.astype(dtype)
         if out.shape != (len,):
-            raise ValueError('{name} must have {len} elements when using '
-                             'array form'.format(name=name, len=len))
+            raise ValueError(f'{name} must have {len} elements when using array form')
     return out
 
 
@@ -283,7 +281,7 @@ cdef check_output(object out, object dtype, object size, bint require_c_array):
         )
     if out_array.dtype != dtype:
         raise TypeError('Supplied output array has the wrong type. '
-                        'Expected {0}, got {1}'.format(np.dtype(dtype), out_array.dtype))
+                        f'Expected {np.dtype(dtype)}, got {out_array.dtype}')
     if size is not None:
         try:
             tup_size = tuple(size)
@@ -386,43 +384,43 @@ cdef int _check_array_cons_bounded_0_1(np.ndarray val, object name) except -1:
 cdef int check_array_constraint(np.ndarray val, object name, constraint_type cons) except -1:
     if cons == CONS_NON_NEGATIVE:
         if np.any(np.logical_and(np.logical_not(np.isnan(val)), np.signbit(val))):
-            raise ValueError(name + " < 0")
+            raise ValueError(f"{name} < 0")
     elif cons == CONS_POSITIVE or cons == CONS_POSITIVE_NOT_NAN:
         if cons == CONS_POSITIVE_NOT_NAN and np.any(np.isnan(val)):
-            raise ValueError(name + " must not be NaN")
+            raise ValueError(f"{name} must not be NaN")
         elif np.any(np.less_equal(val, 0)):
-            raise ValueError(name + " <= 0")
+            raise ValueError(f"{name} <= 0")
     elif cons == CONS_BOUNDED_0_1:
         return _check_array_cons_bounded_0_1(val, name)
     elif cons == CONS_BOUNDED_GT_0_1:
         if not np.all(np.greater(val, 0)) or not np.all(np.less_equal(val, 1)):
-            raise ValueError("{0} <= 0, {0} > 1 or {0} contains NaNs".format(name))
+            raise ValueError(f"{name} <= 0, {name} > 1 or {name} contains NaNs")
     elif cons == CONS_BOUNDED_LT_0_1:
         if not np.all(np.greater_equal(val, 0)) or not np.all(np.less(val, 1)):
-            raise ValueError("{0} < 0, {0} >= 1 or {0} contains NaNs".format(name))
+            raise ValueError(f"{name} < 0, {name} >= 1 or {name} contains NaNs")
     elif cons == CONS_GT_1:
         if not np.all(np.greater(val, 1)):
-            raise ValueError("{0} <= 1 or {0} contains NaNs".format(name))
+            raise ValueError(f"{name} <= 1 or {name} contains NaNs")
     elif cons == CONS_GTE_1:
         if not np.all(np.greater_equal(val, 1)):
-            raise ValueError("{0} < 1 or {0} contains NaNs".format(name))
+            raise ValueError(f"{name} < 1 or {name} contains NaNs")
     elif cons == CONS_POISSON:
         if not np.all(np.less_equal(val, POISSON_LAM_MAX)):
-            raise ValueError("{0} value too large".format(name))
+            raise ValueError(f"{name} value too large")
         elif not np.all(np.greater_equal(val, 0.0)):
-            raise ValueError("{0} < 0 or {0} contains NaNs".format(name))
+            raise ValueError(f"{name} < 0 or {name} contains NaNs")
     elif cons == LEGACY_CONS_POISSON:
         if not np.all(np.less_equal(val, LEGACY_POISSON_LAM_MAX)):
-            raise ValueError("{0} value too large".format(name))
+            raise ValueError(f"{name} value too large")
         elif not np.all(np.greater_equal(val, 0.0)):
-            raise ValueError("{0} < 0 or {0} contains NaNs".format(name))
+            raise ValueError(f"{name} < 0 or {name} contains NaNs")
     elif cons == LEGACY_CONS_NON_NEGATIVE_INBOUNDS_LONG:
         # Note, we assume that array is integral:
         if not np.all(val >= 0):
-            raise ValueError(name + " < 0")
+            raise ValueError(f"{name} < 0")
         elif not np.all(val <= int(LONG_MAX)):
             raise ValueError(
-                    name + " is out of bounds for long, consider using "
+                    f"{name} is out of bounds for long, consider using "
                     "the new generator API for 64bit integers.")
 
     return 0
@@ -432,44 +430,44 @@ cdef int check_constraint(double val, object name, constraint_type cons) except
     cdef bint is_nan
     if cons == CONS_NON_NEGATIVE:
         if not isnan(val) and signbit(val):
-            raise ValueError(name + " < 0")
+            raise ValueError(f"{name} < 0")
     elif cons == CONS_POSITIVE or cons == CONS_POSITIVE_NOT_NAN:
         if cons == CONS_POSITIVE_NOT_NAN and isnan(val):
-            raise ValueError(name + " must not be NaN")
+            raise ValueError(f"{name} must not be NaN")
         elif val <= 0:
-            raise ValueError(name + " <= 0")
+            raise ValueError(f"{name} <= 0")
     elif cons == CONS_BOUNDED_0_1:
         if not (val >= 0) or not (val <= 1):
-            raise ValueError("{0} < 0, {0} > 1 or {0} is NaN".format(name))
+            raise ValueError(f"{name} < 0, {name} > 1 or {name} is NaN")
     elif cons == CONS_BOUNDED_GT_0_1:
         if not val >0 or not val <= 1:
-            raise ValueError("{0} <= 0, {0} > 1 or {0} contains NaNs".format(name))
+            raise ValueError(f"{name} <= 0, {name} > 1 or {name} contains NaNs")
     elif cons == CONS_BOUNDED_LT_0_1:
         if not (val >= 0) or not (val < 1):
-            raise ValueError("{0} < 0, {0} >= 1 or {0} is NaN".format(name))
+            raise ValueError(f"{name} < 0, {name} >= 1 or {name} is NaN")
     elif cons == CONS_GT_1:
         if not (val > 1):
-            raise ValueError("{0} <= 1 or {0} is NaN".format(name))
+            raise ValueError(f"{name} <= 1 or {name} is NaN")
     elif cons == CONS_GTE_1:
         if not (val >= 1):
-            raise ValueError("{0} < 1 or {0} is NaN".format(name))
+            raise ValueError(f"{name} < 1 or {name} is NaN")
     elif cons == CONS_POISSON:
         if not (val >= 0):
-            raise ValueError("{0} < 0 or {0} is NaN".format(name))
+            raise ValueError(f"{name} < 0 or {name} is NaN")
         elif not (val <= POISSON_LAM_MAX):
-            raise ValueError(name + " value too large")
+            raise ValueError(f"{name} value too large")
     elif cons == LEGACY_CONS_POISSON:
         if not (val >= 0):
-            raise ValueError("{0} < 0 or {0} is NaN".format(name))
+            raise ValueError(f"{name} < 0 or {name} is NaN")
         elif not (val <= LEGACY_POISSON_LAM_MAX):
-            raise ValueError(name + " value too large")
+            raise ValueError(f"{name} value too large")
     elif cons == LEGACY_CONS_NON_NEGATIVE_INBOUNDS_LONG:
         # Note: Assume value is integral (double of LONG_MAX should work out)
         if val < 0:
-            raise ValueError(name + " < 0")
+            raise ValueError(f"{name} < 0")
         elif val >  LONG_MAX:
             raise ValueError(
-                    name + " is out of bounds for long, consider using "
+                    f"{name} is out of bounds for long, consider using "
                     "the new generator API for 64bit integers.")
 
     return 0
diff --git a/numpy/random/_generator.pyx b/numpy/random/_generator.pyx
index c9c001dd2ec1..c067a0821563 100644
--- a/numpy/random/_generator.pyx
+++ b/numpy/random/_generator.pyx
@@ -207,12 +207,10 @@ cdef class Generator:
         self.lock = bit_generator.lock
 
     def __repr__(self):
-        return self.__str__() + ' at 0x{:X}'.format(id(self))
+        return f'{self} at 0x{id(self):X}'
 
     def __str__(self):
-        _str = self.__class__.__name__
-        _str += '(' + self.bit_generator.__class__.__name__ + ')'
-        return _str
+        return f'{self.__class__.__name__}({self.bit_generator.__class__.__name__})'
 
     # Pickling support:
     def __getstate__(self):
diff --git a/numpy/random/_mt19937.pyx b/numpy/random/_mt19937.pyx
index 826cb8441ef1..ed69c2aa6c58 100644
--- a/numpy/random/_mt19937.pyx
+++ b/numpy/random/_mt19937.pyx
@@ -284,8 +284,7 @@ cdef class MT19937(BitGenerator):
             raise TypeError('state must be a dict')
         bitgen = value.get('bit_generator', '')
         if bitgen != self.__class__.__name__:
-            raise ValueError('state must be for a {0} '
-                             'PRNG'.format(self.__class__.__name__))
+            raise ValueError(f'state must be for a {self.__class__.__name__} PRNG')
         key = value['state']['key']
         for i in range(624):
             self.rng_state.key[i] = key[i]
diff --git a/numpy/random/_pcg64.pyx b/numpy/random/_pcg64.pyx
index 250bf967bba2..e6e9b8e0ac3c 100644
--- a/numpy/random/_pcg64.pyx
+++ b/numpy/random/_pcg64.pyx
@@ -225,8 +225,7 @@ cdef class PCG64(BitGenerator):
             raise TypeError('state must be a dict')
         bitgen = value.get('bit_generator', '')
         if bitgen != self.__class__.__name__:
-            raise ValueError('state must be for a {0} '
-                             'RNG'.format(self.__class__.__name__))
+            raise ValueError(f'state must be for a {self.__class__.__name__} RNG')
         state_vec = np.empty(4, dtype=np.uint64)
         state_vec[0] = value['state']['state'] // 2 ** 64
         state_vec[1] = value['state']['state'] % 2 ** 64
@@ -460,8 +459,7 @@ cdef class PCG64DXSM(BitGenerator):
             raise TypeError('state must be a dict')
         bitgen = value.get('bit_generator', '')
         if bitgen != self.__class__.__name__:
-            raise ValueError('state must be for a {0} '
-                             'RNG'.format(self.__class__.__name__))
+            raise ValueError(f'state must be for a {self.__class__.__name__} RNG')
         state_vec = np.empty(4, dtype=np.uint64)
         state_vec[0] = value['state']['state'] // 2 ** 64
         state_vec[1] = value['state']['state'] % 2 ** 64
diff --git a/numpy/random/_philox.pyx b/numpy/random/_philox.pyx
index a046d9441fae..5faa281818fd 100644
--- a/numpy/random/_philox.pyx
+++ b/numpy/random/_philox.pyx
@@ -238,8 +238,7 @@ cdef class Philox(BitGenerator):
             raise TypeError('state must be a dict')
         bitgen = value.get('bit_generator', '')
         if bitgen != self.__class__.__name__:
-            raise ValueError('state must be for a {0} '
-                             'PRNG'.format(self.__class__.__name__))
+            raise ValueError(f'state must be for a {self.__class__.__name__} PRNG')
         for i in range(4):
             self.rng_state.ctr.v[i] =  value['state']['counter'][i]
             if i < 2:
diff --git a/numpy/random/_sfc64.pyx b/numpy/random/_sfc64.pyx
index 12b48059cef2..86136f0b42fb 100644
--- a/numpy/random/_sfc64.pyx
+++ b/numpy/random/_sfc64.pyx
@@ -135,8 +135,7 @@ cdef class SFC64(BitGenerator):
             raise TypeError('state must be a dict')
         bitgen = value.get('bit_generator', '')
         if bitgen != self.__class__.__name__:
-            raise ValueError('state must be for a {0} '
-                             'RNG'.format(self.__class__.__name__))
+            raise ValueError('state must be for a {self.__class__.__name__} RNG')
         state_vec = np.empty(4, dtype=np.uint64)
         state_vec[:] = value['state']['state']
         has_uint32 = value['has_uint32']
diff --git a/numpy/random/bit_generator.pyx b/numpy/random/bit_generator.pyx
index c999e6e32794..fbedb0fd5786 100644
--- a/numpy/random/bit_generator.pyx
+++ b/numpy/random/bit_generator.pyx
@@ -305,7 +305,7 @@ cdef class SeedSequence():
         elif not isinstance(entropy, (int, np.integer, list, tuple, range,
                                       np.ndarray)):
             raise TypeError('SeedSequence expects int or sequence of ints for '
-                            'entropy not {}'.format(entropy))
+                            f'entropy not {entropy}')
         self.entropy = entropy
         self.spawn_key = tuple(spawn_key)
         self.pool_size = pool_size
diff --git a/numpy/random/mtrand.pyx b/numpy/random/mtrand.pyx
index 5feb0413dc91..beaf96c06921 100644
--- a/numpy/random/mtrand.pyx
+++ b/numpy/random/mtrand.pyx
@@ -190,7 +190,7 @@ cdef class RandomState:
         self._initialize_bit_generator(bit_generator)
 
     def __repr__(self):
-        return self.__str__() + ' at 0x{:X}'.format(id(self))
+        return f'{self} at 0x{id(self):X}'
 
     def __str__(self):
         _str = self.__class__.__name__
@@ -1387,15 +1387,14 @@ cdef class RandomState:
         """
         if high is None:
             warnings.warn(("This function is deprecated. Please call "
-                           "randint(1, {low} + 1) instead".format(low=low)),
+                           f"randint(1, {low} + 1) instead"),
                           DeprecationWarning)
             high = low
             low = 1
 
         else:
             warnings.warn(("This function is deprecated. Please call "
-                           "randint({low}, {high} + 1) "
-                           "instead".format(low=low, high=high)),
+                           f"randint({low}, {high} + 1) instead"),
                           DeprecationWarning)
 
         return self.randint(low, int(high) + 1, size=size, dtype='l')

From fec856fc31b78e5d7391dc5fbcc430076fa667ac Mon Sep 17 00:00:00 2001
From: Dimitri Papadopoulos
 <3234522+DimitriPapadopoulos@users.noreply.github.com>
Date: Fri, 18 Apr 2025 11:23:26 +0200
Subject: [PATCH 058/202] STY: Apply ruff/flake8-pie rule PIE804

Unnecessary `dict` kwargs
---
 numpy/_core/tests/test_numeric.py | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/numpy/_core/tests/test_numeric.py b/numpy/_core/tests/test_numeric.py
index 6a35b82ed766..a05d49e74b52 100644
--- a/numpy/_core/tests/test_numeric.py
+++ b/numpy/_core/tests/test_numeric.py
@@ -4117,7 +4117,7 @@ def test_broadcast_error_kwargs(self):
         #gh-13455
         arrs = [np.empty((5, 6, 7))]
         mit = np.broadcast(*arrs)
-        mit2 = np.broadcast(*arrs, **{})
+        mit2 = np.broadcast(*arrs)
         assert_equal(mit.shape, mit2.shape)
         assert_equal(mit.ndim, mit2.ndim)
         assert_equal(mit.nd, mit2.nd)

From 5c47ca1da0e8b849fde4f40cb3e2c507fe77603b Mon Sep 17 00:00:00 2001
From: Dimitri Papadopoulos
 <3234522+DimitriPapadopoulos@users.noreply.github.com>
Date: Fri, 18 Apr 2025 11:25:53 +0200
Subject: [PATCH 059/202] MNT: Enforce ruff/flake8-pie rules (PIE)

---
 ruff.toml | 6 ++++--
 1 file changed, 4 insertions(+), 2 deletions(-)

diff --git a/ruff.toml b/ruff.toml
index 4dab12cf0aee..4e606c5c8593 100644
--- a/ruff.toml
+++ b/ruff.toml
@@ -17,20 +17,22 @@ extend-exclude = [
 [lint]
 preview = true
 extend-select = [
+    "PIE",
     "E",
     "W",
     "PGH",
     "PLE",
 ]
 ignore = [
-    "F",     # TODO: enable Pyflakes rules
+    "F",      # TODO: enable Pyflakes rules
+    "PIE790", # Unnecessary `pass` statement
     "E241",
     "E251",
     "E265",
     "E266",
     "E302",
     "E402",
-    "E501",  # TODO: Line too long
+    "E501",   # TODO: Line too long
     "E712",
     "E721",
     "E731",

From 3290ee6aae582c2aef991484f8ff66b3337c84c1 Mon Sep 17 00:00:00 2001
From: Dimitri Papadopoulos
 <3234522+DimitriPapadopoulos@users.noreply.github.com>
Date: Fri, 18 Apr 2025 11:26:37 +0200
Subject: [PATCH 060/202] MNT: Enforce ruff/Flynt rules (FLY)

---
 ruff.toml | 1 +
 1 file changed, 1 insertion(+)

diff --git a/ruff.toml b/ruff.toml
index 4e606c5c8593..40ddc0eccf14 100644
--- a/ruff.toml
+++ b/ruff.toml
@@ -18,6 +18,7 @@ extend-exclude = [
 preview = true
 extend-select = [
     "PIE",
+    "FLY",
     "E",
     "W",
     "PGH",

From c502e5e738194f848155013d3c23e24e38259274 Mon Sep 17 00:00:00 2001
From: Marco Edward Gorelli 
Date: Fri, 18 Apr 2025 14:53:52 +0100
Subject: [PATCH 061/202] TYP: Type ``MaskedArray.compressed`` and
 ``np.ma.compressed`` (#28766)

---
 numpy/ma/core.pyi                     | 11 +++++++----
 numpy/typing/tests/data/fail/ma.pyi   |  2 ++
 numpy/typing/tests/data/reveal/ma.pyi | 11 ++++++++---
 3 files changed, 17 insertions(+), 7 deletions(-)

diff --git a/numpy/ma/core.pyi b/numpy/ma/core.pyi
index e0aeec84c803..8461c54aa5f1 100644
--- a/numpy/ma/core.pyi
+++ b/numpy/ma/core.pyi
@@ -222,8 +222,8 @@ __all__ = [
 
 _ShapeT = TypeVar("_ShapeT", bound=tuple[int, ...])
 _ShapeT_co = TypeVar("_ShapeT_co", bound=tuple[int, ...], covariant=True)
-_DTypeT = TypeVar("_DTypeT", bound=dtype[Any])
-_DTypeT_co = TypeVar("_DTypeT_co", bound=dtype[Any], covariant=True)
+_DTypeT = TypeVar("_DTypeT", bound=dtype)
+_DTypeT_co = TypeVar("_DTypeT_co", bound=dtype, covariant=True)
 _ArrayT = TypeVar("_ArrayT", bound=ndarray[Any, Any])
 _ScalarT = TypeVar("_ScalarT", bound=generic)
 _ScalarT_co = TypeVar("_ScalarT_co", bound=generic)
@@ -427,7 +427,7 @@ class MaskedArray(ndarray[_ShapeT_co, _DTypeT_co]):
     get_fill_value: Any
     set_fill_value: Any
     def filled(self, /, fill_value: _ScalarLike_co | None = None) -> ndarray[_ShapeT_co, _DTypeT_co]: ...
-    def compressed(self): ...
+    def compressed(self) -> ndarray[tuple[int], _DTypeT_co]: ...
     def compress(self, condition, axis=..., out=...): ...
     def __eq__(self, other): ...
     def __ne__(self, other): ...
@@ -1154,7 +1154,10 @@ def sort(
     *,
     stable: Literal[False] | None = False,
 ) -> NDArray[Any]: ...
-def compressed(x): ...
+@overload
+def compressed(x: _ArrayLike[_ScalarT_co]) -> ndarray[tuple[int], dtype[_ScalarT_co]]: ...
+@overload
+def compressed(x: ArrayLike) -> ndarray[tuple[int], dtype]: ...
 def concatenate(arrays, axis=...): ...
 def diag(v, k=...): ...
 def left_shift(a, n): ...
diff --git a/numpy/typing/tests/data/fail/ma.pyi b/numpy/typing/tests/data/fail/ma.pyi
index 19a3e7128ac4..e0b7df5b6ab7 100644
--- a/numpy/typing/tests/data/fail/ma.pyi
+++ b/numpy/typing/tests/data/fail/ma.pyi
@@ -114,3 +114,5 @@ m.put(4, 999, mode='flip')  # E: No overload variant
 np.ma.put(m, 4, 999, mode='flip')  # E: No overload variant
 
 np.ma.put([1,1,3], 0, 999)  # E: No overload variant
+
+np.ma.compressed(lambda: 'compress me')  # E: No overload variant
diff --git a/numpy/typing/tests/data/reveal/ma.pyi b/numpy/typing/tests/data/reveal/ma.pyi
index c658d240db7c..0a2fe6d593ec 100644
--- a/numpy/typing/tests/data/reveal/ma.pyi
+++ b/numpy/typing/tests/data/reveal/ma.pyi
@@ -28,7 +28,7 @@ MAR_V: MaskedNDArray[np.void]
 
 MAR_subclass: MaskedNDArraySubclass
 
-MAR_1d: np.ma.MaskedArray[tuple[int], np.dtype[Any]]
+MAR_1d: np.ma.MaskedArray[tuple[int], np.dtype]
 
 b: np.bool
 f4: np.float32
@@ -249,6 +249,11 @@ assert_type(np.ma.count(MAR_o, keepdims=True), NDArray[np.int_])
 assert_type(np.ma.count(MAR_o, axis=None, keepdims=True), NDArray[np.int_])
 assert_type(np.ma.count(MAR_o, None, True), NDArray[np.int_])
 
+assert_type(MAR_f4.compressed(), np.ndarray[tuple[int], np.dtype[np.float32]])
+
+assert_type(np.ma.compressed(MAR_i8), np.ndarray[tuple[int], np.dtype[np.int64]])
+assert_type(np.ma.compressed([[1,2,3]]), np.ndarray[tuple[int], np.dtype])
+
 assert_type(MAR_f4.put([0,4,8], [10,20,30]), None)
 assert_type(MAR_f4.put(4, 999), None)
 assert_type(MAR_f4.put(4, 999, mode='clip'), None)
@@ -261,10 +266,10 @@ assert_type(np.ma.putmask(MAR_f4, [True, False], [0, 1]), None)
 
 assert_type(MAR_f4.filled(float('nan')), NDArray[np.float32])
 assert_type(MAR_i8.filled(), NDArray[np.int64])
-assert_type(MAR_1d.filled(), np.ndarray[tuple[int], np.dtype[Any]])
+assert_type(MAR_1d.filled(), np.ndarray[tuple[int], np.dtype])
 
 assert_type(np.ma.filled(MAR_f4, float('nan')), NDArray[np.float32])
 assert_type(np.ma.filled([[1,2,3]]), NDArray[Any])
 # PyRight detects this one correctly, but mypy doesn't.
 # https://github.com/numpy/numpy/pull/28742#discussion_r2048968375
-assert_type(np.ma.filled(MAR_1d), np.ndarray[tuple[int], np.dtype[Any]])  # type: ignore[assert-type]
+assert_type(np.ma.filled(MAR_1d), np.ndarray[tuple[int], np.dtype])  # type: ignore[assert-type]

From fb3d4c21970963bd093ebb7a89ed4a61ff93c982 Mon Sep 17 00:00:00 2001
From: Aditi Juneja <1509aditi@gmail.com>
Date: Fri, 18 Apr 2025 19:25:48 +0530
Subject: [PATCH 062/202] using flynt

---
 benchmarks/benchmarks/bench_ufunc.py          |   2 +-
 doc/neps/conf.py                              |   2 +-
 doc/source/conf.py                            |   7 +-
 numpy/__init__.py                             |   3 +-
 numpy/_core/_dtype.py                         |  12 +-
 numpy/_core/_internal.py                      |   5 +-
 numpy/_core/_machar.py                        |   2 +-
 numpy/_core/arrayprint.py                     |   4 +-
 numpy/_core/code_generators/genapi.py         |  30 ++-
 .../code_generators/generate_numpy_api.py     |   4 +-
 .../code_generators/generate_ufunc_api.py     |   4 +-
 numpy/_core/code_generators/generate_umath.py |   6 +-
 numpy/_core/einsumfunc.py                     |  26 ++-
 numpy/_core/function_base.py                  |   2 +-
 numpy/_core/getlimits.py                      |   4 +-
 numpy/_core/records.py                        |  18 +-
 numpy/_core/tests/test_array_interface.py     |  14 +-
 numpy/_core/tests/test_arrayprint.py          |   8 +-
 numpy/_core/tests/test_cpu_features.py        |  10 +-
 numpy/_core/tests/test_datetime.py            |  38 ++--
 numpy/_core/tests/test_defchararray.py        |   4 +-
 numpy/_core/tests/test_dtype.py               |   4 +-
 numpy/_core/tests/test_extint128.py           |   3 +-
 numpy/_core/tests/test_half.py                |   4 +-
 numpy/_core/tests/test_longdouble.py          |   6 +-
 numpy/_core/tests/test_machar.py              |   2 +-
 numpy/_core/tests/test_mem_overlap.py         |  16 +-
 numpy/_core/tests/test_multiarray.py          | 102 +++++------
 numpy/_core/tests/test_nditer.py              |  12 +-
 numpy/_core/tests/test_numeric.py             |  34 ++--
 numpy/_core/tests/test_numerictypes.py        |   3 +-
 numpy/_core/tests/test_print.py               |  22 +--
 numpy/_core/tests/test_regression.py          |   4 +-
 numpy/_core/tests/test_scalarmath.py          |  53 +++---
 numpy/_core/tests/test_simd.py                |   4 +-
 numpy/_core/tests/test_ufunc.py               |   5 +-
 numpy/_core/tests/test_umath.py               | 116 ++++++------
 numpy/_core/tests/test_unicode.py             |  30 +--
 numpy/_pytesttester.py                        |   4 +-
 numpy/ctypeslib/_ctypeslib.py                 |   9 +-
 numpy/f2py/__init__.py                        |   3 +-
 numpy/f2py/_src_pyf.py                        |   8 +-
 numpy/f2py/auxfuncs.py                        |  22 +--
 numpy/f2py/capi_maps.py                       |  82 ++++-----
 numpy/f2py/cb_rules.py                        |   7 +-
 numpy/f2py/cfuncs.py                          |  13 +-
 numpy/f2py/common_rules.py                    |  29 ++-
 numpy/f2py/crackfortran.py                    | 171 ++++++++----------
 numpy/f2py/diagnose.py                        |  11 +-
 numpy/f2py/f2py2e.py                          |  17 +-
 numpy/f2py/f90mod_rules.py                    |  56 +++---
 numpy/f2py/func2subr.py                       |  74 ++++----
 numpy/f2py/rules.py                           |  26 +--
 numpy/f2py/tests/test_array_from_pyobj.py     |   4 +-
 numpy/f2py/tests/util.py                      |   5 +-
 numpy/f2py/use_rules.py                       |  13 +-
 numpy/lib/__init__.py                         |   3 +-
 numpy/lib/_datasource.py                      |   2 +-
 numpy/lib/_format_impl.py                     |   2 +-
 numpy/lib/_function_base_impl.py              |   6 +-
 numpy/lib/_iotools.py                         |   4 +-
 numpy/lib/_npyio_impl.py                      |  12 +-
 numpy/lib/_polynomial_impl.py                 |  17 +-
 numpy/lib/_utils_impl.py                      |  24 ++-
 numpy/lib/_version.py                         |   2 +-
 numpy/lib/recfunctions.py                     |   9 +-
 numpy/lib/tests/test_function_base.py         |   2 +-
 numpy/lib/tests/test_io.py                    |  12 +-
 numpy/lib/tests/test_mixins.py                |   2 +-
 numpy/lib/tests/test_nanfunctions.py          |   2 +-
 numpy/lib/tests/test_stride_tricks.py         |   2 +-
 numpy/linalg/_linalg.py                       |   3 +-
 numpy/linalg/lapack_lite/make_lite.py         |  14 +-
 numpy/ma/core.py                              |  10 +-
 numpy/matrixlib/tests/test_defmatrix.py       |   2 +-
 numpy/random/tests/test_extending.py          |   3 +-
 numpy/testing/_private/extbuild.py            |   2 +-
 numpy/testing/_private/utils.py               |   3 +-
 numpy/tests/test_ctypeslib.py                 |   2 +-
 pavement.py                                   |   2 +-
 tools/check_installed_files.py                |   4 +-
 tools/ci/push_docs_to_repo.py                 |   6 +-
 tools/refguide_check.py                       |  10 +-
 83 files changed, 639 insertions(+), 702 deletions(-)

diff --git a/benchmarks/benchmarks/bench_ufunc.py b/benchmarks/benchmarks/bench_ufunc.py
index 3cade863b77b..926e04571402 100644
--- a/benchmarks/benchmarks/bench_ufunc.py
+++ b/benchmarks/benchmarks/bench_ufunc.py
@@ -37,7 +37,7 @@
 if len(missing_ufuncs) > 0:
     missing_ufunc_names = [f.__name__ for f in missing_ufuncs]
     raise NotImplementedError(
-        "Missing benchmarks for ufuncs %r" % missing_ufunc_names)
+        f"Missing benchmarks for ufuncs {missing_ufunc_names!r}")
 
 
 class ArrayFunctionDispatcher(Benchmark):
diff --git a/doc/neps/conf.py b/doc/neps/conf.py
index 2ac0765e9c18..343c32681c91 100644
--- a/doc/neps/conf.py
+++ b/doc/neps/conf.py
@@ -97,7 +97,7 @@
   "show_prev_next": False,
 }
 
-html_title = "%s" % (project)
+html_title = f"{project}"
 html_static_path = ['../source/_static']
 html_last_updated_fmt = '%b %d, %Y'
 
diff --git a/doc/source/conf.py b/doc/source/conf.py
index 2e78187431aa..c62d96c32069 100644
--- a/doc/source/conf.py
+++ b/doc/source/conf.py
@@ -127,7 +127,7 @@ class PyTypeObject(ctypes.Structure):
 version = re.sub(r'(\.dev\d+).*?$', r'\1', version)
 # The full version, including alpha/beta/rc tags.
 release = numpy.__version__
-print("%s %s" % (version, release))
+print(f"{version} {release}")
 
 # There are two options for replacing |today|: either, you set today to some
 # non-false value, then it is used:
@@ -271,7 +271,7 @@ def setup(app):
     "show_version_warning_banner": True,
 }
 
-html_title = "%s v%s Manual" % (project, version)
+html_title = f"{project} v{version} Manual"
 html_static_path = ['_static']
 html_last_updated_fmt = '%b %d, %Y'
 html_css_files = ["numpy.css"]
@@ -575,8 +575,7 @@ def linkcode_resolve(domain, info):
         linespec = ""
 
     if 'dev' in numpy.__version__:
-        return "https://github.com/numpy/numpy/blob/main/numpy/%s%s" % (
-           fn, linespec)
+        return f"https://github.com/numpy/numpy/blob/main/numpy/{fn}{linespec}"
     else:
         return "https://github.com/numpy/numpy/blob/v%s/numpy/%s%s" % (
            numpy.__version__, fn, linespec)
diff --git a/numpy/__init__.py b/numpy/__init__.py
index 67db9bcaf750..88384e969931 100644
--- a/numpy/__init__.py
+++ b/numpy/__init__.py
@@ -410,8 +410,7 @@ def __getattr__(attr):
             import numpy.char as char
             return char.chararray
 
-        raise AttributeError("module {!r} has no attribute "
-                             "{!r}".format(__name__, attr))
+        raise AttributeError(f"module {__name__!r} has no attribute {attr!r}")
 
     def __dir__():
         public_symbols = (
diff --git a/numpy/_core/_dtype.py b/numpy/_core/_dtype.py
index d8413ef2fe4f..d8308320f441 100644
--- a/numpy/_core/_dtype.py
+++ b/numpy/_core/_dtype.py
@@ -121,7 +121,7 @@ def _scalar_str(dtype, short):
 
     elif dtype.type == np.str_:
         if _isunsized(dtype):
-            return "'%sU'" % byteorder
+            return f"'{byteorder}U'"
         else:
             return "'%sU%d'" % (byteorder, dtype.itemsize / 4)
 
@@ -140,10 +140,10 @@ def _scalar_str(dtype, short):
             return "'V%d'" % dtype.itemsize
 
     elif dtype.type == np.datetime64:
-        return "'%sM8%s'" % (byteorder, _datetime_metadata_str(dtype))
+        return f"'{byteorder}M8{_datetime_metadata_str(dtype)}'"
 
     elif dtype.type == np.timedelta64:
-        return "'%sm8%s'" % (byteorder, _datetime_metadata_str(dtype))
+        return f"'{byteorder}m8{_datetime_metadata_str(dtype)}'"
 
     elif dtype.isbuiltin == 2:
         return dtype.type.__name__
@@ -217,17 +217,17 @@ def _struct_dict_str(dtype, includealignedflag):
     ret += fieldsep.join(repr(name) for name in names)
 
     # Second, the formats
-    ret += "], 'formats'%s[" % colon
+    ret += f"], 'formats'{colon}["
     ret += fieldsep.join(
         _construction_repr(fld_dtype, short=True) for fld_dtype in fld_dtypes)
 
     # Third, the offsets
-    ret += "], 'offsets'%s[" % colon
+    ret += f"], 'offsets'{colon}["
     ret += fieldsep.join("%d" % offset for offset in offsets)
 
     # Fourth, the titles
     if any(title is not None for title in titles):
-        ret += "], 'titles'%s[" % colon
+        ret += f"], 'titles'{colon}["
         ret += fieldsep.join(repr(title) for title in titles)
 
     # Fifth, the itemsize
diff --git a/numpy/_core/_internal.py b/numpy/_core/_internal.py
index a10b812098e3..d07e8614896b 100644
--- a/numpy/_core/_internal.py
+++ b/numpy/_core/_internal.py
@@ -183,8 +183,7 @@ def _commastring(astr):
             order2 = _convorder.get(order2, order2)
             if (order1 != order2):
                 raise ValueError(
-                    'inconsistent byte-order specification %s and %s' %
-                    (order1, order2))
+                    f'inconsistent byte-order specification {order1} and {order2}')
             order = order1
 
         if order in ('|', '=', _nbo):
@@ -742,7 +741,7 @@ def __dtype_from_pep3118(stream, is_subdtype):
                 f"Unrepresentable PEP 3118 data type {stream.next!r} ({desc})")
         else:
             raise ValueError(
-                "Unknown PEP 3118 data type specifier %r" % stream.s
+                f"Unknown PEP 3118 data type specifier {stream.s!r}"
             )
 
         #
diff --git a/numpy/_core/_machar.py b/numpy/_core/_machar.py
index 3ea5803f5010..e9d621b764c3 100644
--- a/numpy/_core/_machar.py
+++ b/numpy/_core/_machar.py
@@ -103,7 +103,7 @@ class MachAr:
 
     def __init__(self, float_conv=float, int_conv=int,
                  float_to_float=float,
-                 float_to_str=lambda v: '%24.16e' % v,
+                 float_to_str=lambda v: f'{v:24.16e}',
                  title='Python floating point number'):
         """
 
diff --git a/numpy/_core/arrayprint.py b/numpy/_core/arrayprint.py
index 14818c66f172..5ebc8d961a16 100644
--- a/numpy/_core/arrayprint.py
+++ b/numpy/_core/arrayprint.py
@@ -1552,14 +1552,14 @@ def dtype_short_repr(dtype):
         return str(dtype)
     elif issubclass(dtype.type, flexible):
         # handle these separately so they don't give garbage like str256
-        return "'%s'" % str(dtype)
+        return f"'{str(dtype)}'"
 
     typename = dtype.name
     if not dtype.isnative:
         # deal with cases like dtype('':
                 continue
             if s not in einsum_symbols:
-                raise ValueError("Character %s is not a valid symbol." % s)
+                raise ValueError(f"Character {s} is not a valid symbol.")
 
     else:
         tmp_operands = list(operands)
@@ -691,7 +691,7 @@ def _parse_einsum_input(operands):
             tmp_subscripts = subscripts.replace(",", "")
             for s in sorted(set(tmp_subscripts)):
                 if s not in (einsum_symbols):
-                    raise ValueError("Character %s is not a valid symbol." % s)
+                    raise ValueError(f"Character {s} is not a valid symbol.")
                 if tmp_subscripts.count(s) == 1:
                     output_subscript += s
             normal_inds = ''.join(sorted(set(output_subscript) -
@@ -709,7 +709,7 @@ def _parse_einsum_input(operands):
         output_subscript = ""
         for s in sorted(set(tmp_subscripts)):
             if s not in einsum_symbols:
-                raise ValueError("Character %s is not a valid symbol." % s)
+                raise ValueError(f"Character {s} is not a valid symbol.")
             if tmp_subscripts.count(s) == 1:
                 output_subscript += s
 
@@ -719,8 +719,7 @@ def _parse_einsum_input(operands):
             raise ValueError("Output character %s appeared more than once in "
                              "the output." % char)
         if char not in input_subscripts:
-            raise ValueError("Output character %s did not appear in the input"
-                             % char)
+            raise ValueError(f"Output character {char} did not appear in the input")
 
     # Make sure number operands is equivalent to the number of terms
     if len(input_subscripts.split(',')) != len(operands):
@@ -876,7 +875,7 @@ def einsum_path(*operands, optimize='greedy', einsum_call=False):
         path_type = path_type[0]
 
     else:
-        raise TypeError("Did not understand the path: %s" % str(path_type))
+        raise TypeError(f"Did not understand the path: {str(path_type)}")
 
     # Hidden option, only einsum should call this
     einsum_call_arg = einsum_call
@@ -1026,13 +1025,13 @@ def einsum_path(*operands, optimize='greedy', einsum_call=False):
     speedup = naive_cost / opt_cost
     max_i = max(size_list)
 
-    path_print = "  Complete contraction:  %s\n" % overall_contraction
-    path_print += "         Naive scaling:  %d\n" % len(indices)
+    path_print = f"  Complete contraction:  {overall_contraction}\n"
+    path_print += f"         Naive scaling:  {len(indices)}\n"
     path_print += "     Optimized scaling:  %d\n" % max(scale_list)
-    path_print += "      Naive FLOP count:  %.3e\n" % naive_cost
-    path_print += "  Optimized FLOP count:  %.3e\n" % opt_cost
-    path_print += "   Theoretical speedup:  %3.3f\n" % speedup
-    path_print += "  Largest intermediate:  %.3e elements\n" % max_i
+    path_print += f"      Naive FLOP count:  {naive_cost:.3e}\n"
+    path_print += f"  Optimized FLOP count:  {opt_cost:.3e}\n"
+    path_print += f"   Theoretical speedup:  {speedup:3.3f}\n"
+    path_print += f"  Largest intermediate:  {max_i:.3e} elements\n"
     path_print += "-" * 74 + "\n"
     path_print += "%6s %24s %40s\n" % header
     path_print += "-" * 74
@@ -1429,8 +1428,7 @@ def einsum(*operands, out=None, optimize=False, **kwargs):
     unknown_kwargs = [k for (k, v) in kwargs.items() if
                       k not in valid_einsum_kwargs]
     if len(unknown_kwargs):
-        raise TypeError("Did not understand the following kwargs: %s"
-                        % unknown_kwargs)
+        raise TypeError(f"Did not understand the following kwargs: {unknown_kwargs}")
 
     # Build the contraction list and operand
     operands, contraction_list = einsum_path(*operands, optimize=optimize,
diff --git a/numpy/_core/function_base.py b/numpy/_core/function_base.py
index cba071768ab7..a07ab210eae8 100644
--- a/numpy/_core/function_base.py
+++ b/numpy/_core/function_base.py
@@ -121,7 +121,7 @@ def linspace(start, stop, num=50, endpoint=True, retstep=False, dtype=None,
     num = operator.index(num)
     if num < 0:
         raise ValueError(
-            "Number of samples, %s, must be non-negative." % num
+            f"Number of samples, {num}, must be non-negative."
         )
     div = (num - 1) if endpoint else num
 
diff --git a/numpy/_core/getlimits.py b/numpy/_core/getlimits.py
index c9f39ae25c5e..eee8dfc081eb 100644
--- a/numpy/_core/getlimits.py
+++ b/numpy/_core/getlimits.py
@@ -522,7 +522,7 @@ def __new__(cls, dtype):
             dtypes.append(newdtype)
             dtype = newdtype
         if not issubclass(dtype, numeric.inexact):
-            raise ValueError("data type %r not inexact" % (dtype))
+            raise ValueError(f"data type {dtype!r} not inexact")
         obj = cls._finfo_cache.get(dtype)
         if obj is not None:
             return obj
@@ -703,7 +703,7 @@ def __init__(self, int_type):
         self.bits = self.dtype.itemsize * 8
         self.key = "%s%d" % (self.kind, self.bits)
         if self.kind not in 'iu':
-            raise ValueError("Invalid integer data type %r." % (self.kind,))
+            raise ValueError(f"Invalid integer data type {self.kind!r}.")
 
     @property
     def min(self):
diff --git a/numpy/_core/records.py b/numpy/_core/records.py
index bddda68ebe06..09ac92f9c1f1 100644
--- a/numpy/_core/records.py
+++ b/numpy/_core/records.py
@@ -153,7 +153,7 @@ def _setfieldnames(self, names, titles):
             elif isinstance(names, str):
                 names = names.split(',')
             else:
-                raise NameError("illegal input names %s" % repr(names))
+                raise NameError(f"illegal input names {repr(names)}")
 
             self._names = [n.strip() for n in names[:self._nfields]]
         else:
@@ -168,7 +168,7 @@ def _setfieldnames(self, names, titles):
         # check for redundant names
         _dup = find_duplicate(self._names)
         if _dup:
-            raise ValueError("Duplicate field names: %s" % _dup)
+            raise ValueError(f"Duplicate field names: {_dup}")
 
         if titles:
             self._titles = [n.strip() for n in titles[:self._nfields]]
@@ -234,12 +234,11 @@ def __getattribute__(self, attr):
                 return obj.view((self.__class__, obj.dtype))
             return obj
         else:
-            raise AttributeError("'record' object has no "
-                    "attribute '%s'" % attr)
+            raise AttributeError(f"'record' object has no attribute '{attr}'")
 
     def __setattr__(self, attr, val):
         if attr in ('setfield', 'getfield', 'dtype'):
-            raise AttributeError("Cannot set '%s' attribute" % attr)
+            raise AttributeError(f"Cannot set '{attr}' attribute")
         fielddict = nt.void.__getattribute__(self, 'dtype').fields
         res = fielddict.get(attr, None)
         if res:
@@ -248,8 +247,7 @@ def __setattr__(self, attr, val):
             if getattr(self, attr, None):
                 return nt.void.__setattr__(self, attr, val)
             else:
-                raise AttributeError("'record' object has no "
-                        "attribute '%s'" % attr)
+                raise AttributeError(f"'record' object has no attribute '{attr}'")
 
     def __getitem__(self, indx):
         obj = nt.void.__getitem__(self, indx)
@@ -428,7 +426,7 @@ def __getattribute__(self, attr):
         try:
             res = fielddict[attr][:2]
         except (TypeError, KeyError) as e:
-            raise AttributeError("recarray has no attribute %s" % attr) from e
+            raise AttributeError(f"recarray has no attribute {attr}") from e
         obj = self.getfield(*res)
 
         # At this point obj will always be a recarray, since (see
@@ -481,7 +479,7 @@ def __setattr__(self, attr, val):
             res = fielddict[attr][:2]
         except (TypeError, KeyError) as e:
             raise AttributeError(
-                "record array has no attribute %s" % attr
+                f"record array has no attribute {attr}"
             ) from e
         return self.setfield(val, *res)
 
@@ -531,7 +529,7 @@ def __repr__(self):
                 self, separator=', ', prefix=prefix, suffix=',')
         else:
             # show zero-length shape unless it is (0,)
-            lst = "[], shape=%s" % (repr(self.shape),)
+            lst = f"[], shape={repr(self.shape)}"
 
         lf = '\n' + ' ' * len(prefix)
         if _get_legacy_print_mode() <= 113:
diff --git a/numpy/_core/tests/test_array_interface.py b/numpy/_core/tests/test_array_interface.py
index ae719568a4b2..1917c8fecafe 100644
--- a/numpy/_core/tests/test_array_interface.py
+++ b/numpy/_core/tests/test_array_interface.py
@@ -167,9 +167,8 @@ def __array_struct__(self):
     # share the data
     stderr.write(' ---- share data via the array interface protocol ---- \n')
     arr = np.array(buf, copy=False)
-    stderr.write('arr.__array_interface___ = %s\n' % (
-                 str(arr.__array_interface__)))
-    stderr.write('arr.base = %s\n' % (str(arr.base)))
+    stderr.write(f'arr.__array_interface___ = {str(arr.__array_interface__)}\n')
+    stderr.write(f'arr.base = {str(arr.base)}\n')
     stderr.write(' ---- OK!\n\n')
 
     # release the source of the shared data. this will not release the data
@@ -188,7 +187,7 @@ def __array_struct__(self):
     # called then reading the values here may cause a SEGV and will be reported
     # as invalid reads by valgrind
     stderr.write(' ---- read shared data ---- \n')
-    stderr.write('arr = %s\n' % (str(arr)))
+    stderr.write(f'arr = {str(arr)}\n')
     stderr.write(' ---- OK!\n\n')
 
     # write to the shared buffer. If the shared data was prematurely deleted
@@ -196,15 +195,14 @@ def __array_struct__(self):
     stderr.write(' ---- modify shared data ---- \n')
     arr *= multiplier
     expected_value *= multiplier
-    stderr.write('arr.__array_interface___ = %s\n' % (
-                 str(arr.__array_interface__)))
-    stderr.write('arr.base = %s\n' % (str(arr.base)))
+    stderr.write(f'arr.__array_interface___ = {str(arr.__array_interface__)}\n')
+    stderr.write(f'arr.base = {str(arr.base)}\n')
     stderr.write(' ---- OK!\n\n')
 
     # read the data. If the shared data was prematurely deleted this
     # will may cause a SEGV and valgrind will report invalid reads
     stderr.write(' ---- read modified shared data ---- \n')
-    stderr.write('arr = %s\n' % (str(arr)))
+    stderr.write(f'arr = {str(arr)}\n')
     stderr.write(' ---- OK!\n\n')
 
     # check that we got the expected data. If the PyCapsule destructor we
diff --git a/numpy/_core/tests/test_arrayprint.py b/numpy/_core/tests/test_arrayprint.py
index 060e2679d681..c3889ed7991a 100644
--- a/numpy/_core/tests/test_arrayprint.py
+++ b/numpy/_core/tests/test_arrayprint.py
@@ -243,7 +243,7 @@ def _format_function(x):
                 "[. o O]")
         assert_(np.array2string(x, formatter={'int_kind': _format_function}) ==
                 "[. o O]")
-        assert_(np.array2string(x, formatter={'all': lambda x: "%.4f" % x}) ==
+        assert_(np.array2string(x, formatter={'all': lambda x: f"{x:.4f}"}) ==
                 "[0.0000 1.0000 2.0000]")
         assert_equal(np.array2string(x, formatter={'int': lambda x: hex(x)}),
                 x_hex)
@@ -251,9 +251,9 @@ def _format_function(x):
                 x_oct)
 
         x = np.arange(3.)
-        assert_(np.array2string(x, formatter={'float_kind': lambda x: "%.2f" % x}) ==
+        assert_(np.array2string(x, formatter={'float_kind': lambda x: f"{x:.2f}"}) ==
                 "[0.00 1.00 2.00]")
-        assert_(np.array2string(x, formatter={'float': lambda x: "%.2f" % x}) ==
+        assert_(np.array2string(x, formatter={'float': lambda x: f"{x:.2f}"}) ==
                 "[0.00 1.00 2.00]")
 
         s = np.array(['abc', 'def'])
@@ -663,7 +663,7 @@ def test_precision_zero(self):
                 ([100.], "100."), ([.2, -1, 122.51], "  0.,  -1., 123."),
                 ([0], "0"), ([-12], "-12"), ([complex(.3, -.7)], "0.-1.j")):
             x = np.array(values)
-            assert_equal(repr(x), "array([%s])" % string)
+            assert_equal(repr(x), f"array([{string}])")
 
     def test_formatter(self):
         x = np.arange(3)
diff --git a/numpy/_core/tests/test_cpu_features.py b/numpy/_core/tests/test_cpu_features.py
index 18fce21532ad..62b0eac5dda5 100644
--- a/numpy/_core/tests/test_cpu_features.py
+++ b/numpy/_core/tests/test_cpu_features.py
@@ -33,23 +33,23 @@ def assert_features_equal(actual, desired, fname):
 
     import textwrap
     error_report = textwrap.indent(
-"""
+f"""
 ###########################################
 ### Extra debugging information
 ###########################################
 -------------------------------------------
 --- NumPy Detections
 -------------------------------------------
-%s
+{detected}
 -------------------------------------------
 --- SYS / CPUINFO
 -------------------------------------------
-%s....
+{cpuinfo}....
 -------------------------------------------
 --- SYS / AUXV
 -------------------------------------------
-%s
-""" % (detected, cpuinfo, auxv), prefix='\r')
+{auxv}
+""", prefix='\r')
 
     raise AssertionError((
         "Failure Detection\n"
diff --git a/numpy/_core/tests/test_datetime.py b/numpy/_core/tests/test_datetime.py
index 1b4e2a411ce6..d2e4e5ec6cad 100644
--- a/numpy/_core/tests/test_datetime.py
+++ b/numpy/_core/tests/test_datetime.py
@@ -51,10 +51,10 @@ def test_datetime_dtype_creation(self):
                      'h', 'm', 's', 'ms', 'us',
                      'μs',  # alias for us
                      'ns', 'ps', 'fs', 'as']:
-            dt1 = np.dtype('M8[750%s]' % unit)
-            assert_(dt1 == np.dtype('datetime64[750%s]' % unit))
-            dt2 = np.dtype('m8[%s]' % unit)
-            assert_(dt2 == np.dtype('timedelta64[%s]' % unit))
+            dt1 = np.dtype(f'M8[750{unit}]')
+            assert_(dt1 == np.dtype(f'datetime64[750{unit}]'))
+            dt2 = np.dtype(f'm8[{unit}]')
+            assert_(dt2 == np.dtype(f'timedelta64[{unit}]'))
 
         # Generic units shouldn't add [] to the end
         assert_equal(str(np.dtype("M8")), "datetime64")
@@ -815,7 +815,7 @@ def test_datetime_array_str(self):
         a = np.array(['2011-03-16T13:55', '1920-01-01T03:12'], dtype='M')
         assert_equal(np.array2string(a, separator=', ',
                     formatter={'datetime': lambda x:
-                            "'%s'" % np.datetime_as_string(x, timezone='UTC')}),
+                            f"'{np.datetime_as_string(x, timezone='UTC')}'"}),
                      "['2011-03-16T13:55Z', '1920-01-01T03:12Z']")
 
         # Check that one NaT doesn't corrupt subsequent entries
@@ -943,7 +943,7 @@ def test_pyobject_roundtrip(self):
             b[8] = 'NaT'
 
             assert_equal(b.astype(object).astype(unit), b,
-                            "Error roundtripping unit %s" % unit)
+                            f"Error roundtripping unit {unit}")
         # With time units
         for unit in ['M8[as]', 'M8[16fs]', 'M8[ps]', 'M8[us]',
                      'M8[300as]', 'M8[20us]']:
@@ -959,7 +959,7 @@ def test_pyobject_roundtrip(self):
             b[8] = 'NaT'
 
             assert_equal(b.astype(object).astype(unit), b,
-                            "Error roundtripping unit %s" % unit)
+                            f"Error roundtripping unit {unit}")
 
     def test_month_truncation(self):
         # Make sure that months are truncating correctly
@@ -977,9 +977,9 @@ def test_month_truncation(self):
     def test_different_unit_comparison(self):
         # Check some years with date units
         for unit1 in ['Y', 'M', 'D']:
-            dt1 = np.dtype('M8[%s]' % unit1)
+            dt1 = np.dtype(f'M8[{unit1}]')
             for unit2 in ['Y', 'M', 'D']:
-                dt2 = np.dtype('M8[%s]' % unit2)
+                dt2 = np.dtype(f'M8[{unit2}]')
                 assert_equal(np.array('1945', dtype=dt1),
                              np.array('1945', dtype=dt2))
                 assert_equal(np.array('1970', dtype=dt1),
@@ -998,9 +998,9 @@ def test_different_unit_comparison(self):
                              np.datetime64('10000-01-01', unit2))
         # Check some datetimes with time units
         for unit1 in ['6h', 'h', 'm', 's', '10ms', 'ms', 'us']:
-            dt1 = np.dtype('M8[%s]' % unit1)
+            dt1 = np.dtype(f'M8[{unit1}]')
             for unit2 in ['h', 'm', 's', 'ms', 'us']:
-                dt2 = np.dtype('M8[%s]' % unit2)
+                dt2 = np.dtype(f'M8[{unit2}]')
                 assert_equal(np.array('1945-03-12T18', dtype=dt1),
                              np.array('1945-03-12T18', dtype=dt2))
                 assert_equal(np.array('1970-03-12T18', dtype=dt1),
@@ -1019,9 +1019,9 @@ def test_different_unit_comparison(self):
                              np.datetime64('10000-01-01T00', unit2))
         # Check some days with units that won't overflow
         for unit1 in ['D', '12h', 'h', 'm', 's', '4s', 'ms', 'us']:
-            dt1 = np.dtype('M8[%s]' % unit1)
+            dt1 = np.dtype(f'M8[{unit1}]')
             for unit2 in ['D', 'h', 'm', 's', 'ms', 'us']:
-                dt2 = np.dtype('M8[%s]' % unit2)
+                dt2 = np.dtype(f'M8[{unit2}]')
                 assert_(np.equal(np.array('1932-02-17', dtype='M').astype(dt1),
                      np.array('1932-02-17T00:00:00', dtype='M').astype(dt2),
                      casting='unsafe'))
@@ -1762,10 +1762,10 @@ def test_creation_overflow(self):
         timesteps = np.array([date], dtype='datetime64[s]')[0].astype(np.int64)
         for unit in ['ms', 'us', 'ns']:
             timesteps *= 1000
-            x = np.array([date], dtype='datetime64[%s]' % unit)
+            x = np.array([date], dtype=f'datetime64[{unit}]')
 
             assert_equal(timesteps, x[0].astype(np.int64),
-                         err_msg='Datetime conversion error for unit %s' % unit)
+                         err_msg=f'Datetime conversion error for unit {unit}')
 
         assert_equal(x[0].astype(np.int64), 322689600000000000)
 
@@ -2460,13 +2460,13 @@ def test_isnat(self):
         for unit in ['Y', 'M', 'W', 'D',
                      'h', 'm', 's', 'ms', 'us',
                      'ns', 'ps', 'fs', 'as']:
-            arr = np.array([123, -321, "NaT"], dtype='datetime64[{unit}]')
             assert_equal(np.isnat(arr), res)
-            arr = np.array([123, -321, "NaT"], dtype='timedelta64[{unit}]')
             assert_equal(np.isnat(arr), res)
 
     def test_isnat_error(self):
diff --git a/numpy/_core/tests/test_defchararray.py b/numpy/_core/tests/test_defchararray.py
index 1f14ba6c9b53..f88e1fce1c11 100644
--- a/numpy/_core/tests/test_defchararray.py
+++ b/numpy/_core/tests/test_defchararray.py
@@ -713,8 +713,8 @@ def test_mod(self):
         assert_array_equal(A2, (A % [[1, 2], [3, 4]]))
 
     def test_rmod(self):
-        assert_(("%s" % self.A) == str(self.A))
-        assert_(("%r" % self.A) == repr(self.A))
+        assert_(f"{self.A}" == str(self.A))
+        assert_(f"{self.A!r}" == repr(self.A))
 
         for ob in [42, object()]:
             with assert_raises_regex(
diff --git a/numpy/_core/tests/test_dtype.py b/numpy/_core/tests/test_dtype.py
index b20e36bb5a27..79be16fc2ff2 100644
--- a/numpy/_core/tests/test_dtype.py
+++ b/numpy/_core/tests/test_dtype.py
@@ -1399,10 +1399,10 @@ def test_structured_titles(self):
     @pytest.mark.parametrize('unit', ['', 'Y', 'M', 'W', 'D', 'h', 'm', 's',
                                       'ms', 'us', 'ns', 'ps', 'fs', 'as'])
     def test_datetime(self, base, unit):
-        dt = np.dtype('%s[%s]' % (base, unit) if unit else base)
+        dt = np.dtype(f'{base}[{unit}]' if unit else base)
         self.check_pickling(dt)
         if unit:
-            dt = np.dtype('%s[7%s]' % (base, unit))
+            dt = np.dtype(f'{base}[7{unit}]')
             self.check_pickling(dt)
 
     def test_metadata(self):
diff --git a/numpy/_core/tests/test_extint128.py b/numpy/_core/tests/test_extint128.py
index 619ddba20659..ba9aeeacdbac 100644
--- a/numpy/_core/tests/test_extint128.py
+++ b/numpy/_core/tests/test_extint128.py
@@ -58,8 +58,7 @@ def iterate():
         yield iterate()
     except Exception:
         import traceback
-        msg = "At: %r\n%s" % (repr(value[0]),
-                              traceback.format_exc())
+        msg = f"At: {repr(value[0])!r}\n{traceback.format_exc()}"
         raise AssertionError(msg)
 
 
diff --git a/numpy/_core/tests/test_half.py b/numpy/_core/tests/test_half.py
index 3887b5e93aef..98a1dab61bfc 100644
--- a/numpy/_core/tests/test_half.py
+++ b/numpy/_core/tests/test_half.py
@@ -11,10 +11,10 @@ def assert_raises_fpe(strmatch, callable, *args, **kwargs):
         callable(*args, **kwargs)
     except FloatingPointError as exc:
         assert_(str(exc).find(strmatch) >= 0,
-                "Did not raise floating point %s error" % strmatch)
+                f"Did not raise floating point {strmatch} error")
     else:
         assert_(False,
-                "Did not raise floating point %s error" % strmatch)
+                f"Did not raise floating point {strmatch} error")
 
 class TestHalf:
     def setup_method(self):
diff --git a/numpy/_core/tests/test_longdouble.py b/numpy/_core/tests/test_longdouble.py
index a394310cf60e..c09f2d824a1c 100644
--- a/numpy/_core/tests/test_longdouble.py
+++ b/numpy/_core/tests/test_longdouble.py
@@ -40,7 +40,7 @@ def test_scalar_extraction():
 def test_str_roundtrip():
     # We will only see eps in repr if within printing precision.
     o = 1 + LD_INFO.eps
-    assert_equal(np.longdouble(str(o)), o, "str was %s" % str(o))
+    assert_equal(np.longdouble(str(o)), o, f"str was {str(o)}")
 
 
 @pytest.mark.skipif(string_to_longdouble_inaccurate, reason="Need strtold_l")
@@ -86,7 +86,7 @@ def test_fromstring():
     s = (" " + str(o)) * 5
     a = np.array([o] * 5)
     assert_equal(np.fromstring(s, sep=" ", dtype=np.longdouble), a,
-                 err_msg="reading '%s'" % s)
+                 err_msg=f"reading '{s}'")
 
 
 def test_fromstring_complex():
@@ -274,7 +274,7 @@ def test_format():
                     reason="Need strtold_l")
 def test_percent():
     o = 1 + LD_INFO.eps
-    assert_("%.40g" % o != '1')
+    assert_(f"{o:.40g}" != '1')
 
 
 @pytest.mark.skipif(longdouble_longer_than_double,
diff --git a/numpy/_core/tests/test_machar.py b/numpy/_core/tests/test_machar.py
index c7f677075dca..18d7ed30e062 100644
--- a/numpy/_core/tests/test_machar.py
+++ b/numpy/_core/tests/test_machar.py
@@ -26,5 +26,5 @@ def test_underlow(self):
             try:
                 self._run_machar_highprec()
             except FloatingPointError as e:
-                msg = "Caught %s exception, should not have been raised." % e
+                msg = f"Caught {e} exception, should not have been raised."
                 raise AssertionError(msg)
diff --git a/numpy/_core/tests/test_mem_overlap.py b/numpy/_core/tests/test_mem_overlap.py
index 5158bd4aa926..0d80951a854a 100644
--- a/numpy/_core/tests/test_mem_overlap.py
+++ b/numpy/_core/tests/test_mem_overlap.py
@@ -63,7 +63,7 @@ def _check_assignment(srcidx, dstidx):
     arr[dstidx] = arr[srcidx]
 
     assert_(np.all(arr == cpy),
-            'assigning arr[%s] = arr[%s]' % (dstidx, srcidx))
+            f'assigning arr[{dstidx}] = arr[{srcidx}]')
 
 
 def test_overlapping_assignments():
@@ -168,13 +168,13 @@ def check_may_share_memory_exact(a, b):
     err_msg = ""
     if got != exact:
         err_msg = "    " + "\n    ".join([
-            "base_a - base_b = %r" % (a.__array_interface__['data'][0] - b.__array_interface__['data'][0],),
-            "shape_a = %r" % (a.shape,),
-            "shape_b = %r" % (b.shape,),
-            "strides_a = %r" % (a.strides,),
-            "strides_b = %r" % (b.strides,),
-            "size_a = %r" % (a.size,),
-            "size_b = %r" % (b.size,)
+            f"base_a - base_b = {a.__array_interface__['data'][0] - b.__array_interface__['data'][0]!r}",
+            f"shape_a = {a.shape!r}",
+            f"shape_b = {b.shape!r}",
+            f"strides_a = {a.strides!r}",
+            f"strides_b = {b.strides!r}",
+            f"size_a = {a.size!r}",
+            f"size_b = {b.size!r}"
         ])
 
     assert_equal(got, exact, err_msg=err_msg)
diff --git a/numpy/_core/tests/test_multiarray.py b/numpy/_core/tests/test_multiarray.py
index 214e30e4da2b..9cb9354bef9e 100644
--- a/numpy/_core/tests/test_multiarray.py
+++ b/numpy/_core/tests/test_multiarray.py
@@ -927,7 +927,7 @@ def test_from_string(self):
         nstr = ['123', '123']
         result = np.array([123, 123], dtype=int)
         for type in types:
-            msg = 'String conversion for %s' % type
+            msg = f'String conversion for {type}'
             assert_equal(np.array(nstr, dtype=type), result, err_msg=msg)
 
     def test_void(self):
@@ -2120,7 +2120,7 @@ def test_sort_unsigned(self, dtype):
         a = np.arange(101, dtype=dtype)
         b = a[::-1].copy()
         for kind in self.sort_kinds:
-            msg = "scalar sort, kind=%s" % kind
+            msg = f"scalar sort, kind={kind}"
             c = a.copy()
             c.sort(kind=kind)
             assert_equal(c, a, msg)
@@ -2135,7 +2135,7 @@ def test_sort_signed(self, dtype):
         a = np.arange(-50, 51, dtype=dtype)
         b = a[::-1].copy()
         for kind in self.sort_kinds:
-            msg = "scalar sort, kind=%s" % (kind)
+            msg = f"scalar sort, kind={kind}"
             c = a.copy()
             c.sort(kind=kind)
             assert_equal(c, a, msg)
@@ -2160,7 +2160,7 @@ def test_sort_complex(self, part, dtype):
         setattr(ai, part, 1)
         setattr(bi, part, 1)
         for kind in self.sort_kinds:
-            msg = "complex sort, %s part == 1, kind=%s" % (part, kind)
+            msg = f"complex sort, {part} part == 1, kind={kind}"
             c = ai.copy()
             c.sort(kind=kind)
             assert_equal(c, ai, msg)
@@ -2184,7 +2184,7 @@ def test_sort_string(self, dtype):
         a = np.array(['aaaaaaaa' + chr(i) for i in range(101)], dtype=dtype)
         b = a[::-1].copy()
         for kind in self.sort_kinds:
-            msg = "kind=%s" % kind
+            msg = f"kind={kind}"
             c = a.copy()
             c.sort(kind=kind)
             assert_equal(c, a, msg)
@@ -2198,7 +2198,7 @@ def test_sort_object(self):
         a[:] = list(range(101))
         b = a[::-1]
         for kind in ['q', 'h', 'm']:
-            msg = "kind=%s" % kind
+            msg = f"kind={kind}"
             c = a.copy()
             c.sort(kind=kind)
             assert_equal(c, a, msg)
@@ -2215,7 +2215,7 @@ def test_sort_structured(self, dt, step):
         a = np.array([(i, i) for i in range(101 * step)], dtype=dt)
         b = a[::-1]
         for kind in ['q', 'h', 'm']:
-            msg = "kind=%s" % kind
+            msg = f"kind={kind}"
             c = a.copy()[::step]
             indx = c.argsort(kind=kind)
             c.sort(kind=kind)
@@ -2233,7 +2233,7 @@ def test_sort_time(self, dtype):
         a = np.arange(0, 101, dtype=dtype)
         b = a[::-1]
         for kind in ['q', 'h', 'm']:
-            msg = "kind=%s" % kind
+            msg = f"kind={kind}"
             c = a.copy()
             c.sort(kind=kind)
             assert_equal(c, a, msg)
@@ -2276,7 +2276,7 @@ def __lt__(self, other):
 
         a = np.array([Boom()] * 100, dtype=object)
         for kind in self.sort_kinds:
-            msg = "kind=%s" % kind
+            msg = f"kind={kind}"
             c = a.copy()
             c.sort(kind=kind)
             assert_equal(c, a, msg)
@@ -2420,7 +2420,7 @@ def test_argsort(self):
             a = np.arange(101, dtype=dtype)
             b = a[::-1].copy()
             for kind in self.sort_kinds:
-                msg = "scalar argsort, kind=%s, dtype=%s" % (kind, dtype)
+                msg = f"scalar argsort, kind={kind}, dtype={dtype}"
                 assert_equal(a.copy().argsort(kind=kind), a, msg)
                 assert_equal(b.copy().argsort(kind=kind), b, msg)
 
@@ -2429,13 +2429,13 @@ def test_argsort(self):
         ai = a * 1j + 1
         bi = b * 1j + 1
         for kind in self.sort_kinds:
-            msg = "complex argsort, kind=%s" % kind
+            msg = f"complex argsort, kind={kind}"
             assert_equal(ai.copy().argsort(kind=kind), a, msg)
             assert_equal(bi.copy().argsort(kind=kind), b, msg)
         ai = a + 1j
         bi = b + 1j
         for kind in self.sort_kinds:
-            msg = "complex argsort, kind=%s" % kind
+            msg = f"complex argsort, kind={kind}"
             assert_equal(ai.copy().argsort(kind=kind), a, msg)
             assert_equal(bi.copy().argsort(kind=kind), b, msg)
 
@@ -2454,7 +2454,7 @@ def test_argsort(self):
         r = np.arange(101)
         rr = r[::-1]
         for kind in self.sort_kinds:
-            msg = "string argsort, kind=%s" % kind
+            msg = f"string argsort, kind={kind}"
             assert_equal(a.copy().argsort(kind=kind), r, msg)
             assert_equal(b.copy().argsort(kind=kind), rr, msg)
 
@@ -2465,7 +2465,7 @@ def test_argsort(self):
         r = np.arange(101)
         rr = r[::-1]
         for kind in self.sort_kinds:
-            msg = "unicode argsort, kind=%s" % kind
+            msg = f"unicode argsort, kind={kind}"
             assert_equal(a.copy().argsort(kind=kind), r, msg)
             assert_equal(b.copy().argsort(kind=kind), rr, msg)
 
@@ -2476,7 +2476,7 @@ def test_argsort(self):
         r = np.arange(101)
         rr = r[::-1]
         for kind in self.sort_kinds:
-            msg = "object argsort, kind=%s" % kind
+            msg = f"object argsort, kind={kind}"
             assert_equal(a.copy().argsort(kind=kind), r, msg)
             assert_equal(b.copy().argsort(kind=kind), rr, msg)
 
@@ -2487,7 +2487,7 @@ def test_argsort(self):
         r = np.arange(101)
         rr = r[::-1]
         for kind in self.sort_kinds:
-            msg = "structured array argsort, kind=%s" % kind
+            msg = f"structured array argsort, kind={kind}"
             assert_equal(a.copy().argsort(kind=kind), r, msg)
             assert_equal(b.copy().argsort(kind=kind), rr, msg)
 
@@ -2497,7 +2497,7 @@ def test_argsort(self):
         r = np.arange(101)
         rr = r[::-1]
         for kind in ['q', 'h', 'm']:
-            msg = "datetime64 argsort, kind=%s" % kind
+            msg = f"datetime64 argsort, kind={kind}"
             assert_equal(a.copy().argsort(kind=kind), r, msg)
             assert_equal(b.copy().argsort(kind=kind), rr, msg)
 
@@ -2507,7 +2507,7 @@ def test_argsort(self):
         r = np.arange(101)
         rr = r[::-1]
         for kind in ['q', 'h', 'm']:
-            msg = "timedelta64 argsort, kind=%s" % kind
+            msg = f"timedelta64 argsort, kind={kind}"
             assert_equal(a.copy().argsort(kind=kind), r, msg)
             assert_equal(b.copy().argsort(kind=kind), rr, msg)
 
@@ -2567,10 +2567,10 @@ def test_searchsorted_floats(self, a):
         # test for floats arrays containing nans. Explicitly test
         # half, single, and double precision floats to verify that
         # the NaN-handling is correct.
-        msg = "Test real (%s) searchsorted with nans, side='l'" % a.dtype
+        msg = f"Test real ({a.dtype}) searchsorted with nans, side='l'"
         b = a.searchsorted(a, side='left')
         assert_equal(b, np.arange(3), msg)
-        msg = "Test real (%s) searchsorted with nans, side='r'" % a.dtype
+        msg = f"Test real ({a.dtype}) searchsorted with nans, side='r'"
         b = a.searchsorted(a, side='right')
         assert_equal(b, np.arange(1, 4), msg)
         # check keyword arguments
@@ -3196,7 +3196,7 @@ def test_partition_fuzz(self):
                 kth = [0, idx, i, i + 1]
                 tgt = np.sort(d)[kth]
                 assert_array_equal(np.partition(d, kth)[kth], tgt,
-                                   err_msg="data: %r\n kth: %r" % (d, kth))
+                                   err_msg=f"data: {d!r}\n kth: {kth!r}")
 
     @pytest.mark.parametrize("kth_dtype", np.typecodes["AllInteger"])
     def test_argpartition_gh5524(self, kth_dtype):
@@ -4431,7 +4431,7 @@ def test_roundtrip(self):
             for a in DATA:
                 assert_equal(
                         a, pickle.loads(pickle.dumps(a, protocol=proto)),
-                        err_msg="%r" % a)
+                        err_msg=f"{a!r}")
             del a, DATA, carray
             break_cycles()
             # check for reference leaks (gh-12793)
@@ -4860,20 +4860,20 @@ def test_combinations(self, data):
                         "invalid value encountered in reduce")
             val = np.max(arr)
 
-        assert_equal(np.argmax(arr), pos, err_msg="%r" % arr)
-        assert_equal(arr[np.argmax(arr)], val, err_msg="%r" % arr)
+        assert_equal(np.argmax(arr), pos, err_msg=f"{arr!r}")
+        assert_equal(arr[np.argmax(arr)], val, err_msg=f"{arr!r}")
 
         # add padding to test SIMD loops
         rarr = np.repeat(arr, 129)
         rpos = pos * 129
-        assert_equal(np.argmax(rarr), rpos, err_msg="%r" % rarr)
-        assert_equal(rarr[np.argmax(rarr)], val, err_msg="%r" % rarr)
+        assert_equal(np.argmax(rarr), rpos, err_msg=f"{rarr!r}")
+        assert_equal(rarr[np.argmax(rarr)], val, err_msg=f"{rarr!r}")
 
         padd = np.repeat(np.min(arr), 513)
         rarr = np.concatenate((arr, padd))
         rpos = pos
-        assert_equal(np.argmax(rarr), rpos, err_msg="%r" % rarr)
-        assert_equal(rarr[np.argmax(rarr)], val, err_msg="%r" % rarr)
+        assert_equal(np.argmax(rarr), rpos, err_msg=f"{rarr!r}")
+        assert_equal(rarr[np.argmax(rarr)], val, err_msg=f"{rarr!r}")
 
     def test_maximum_signed_integers(self):
 
@@ -5002,20 +5002,20 @@ def test_combinations(self, data):
                        "invalid value encountered in reduce")
             min_val = np.min(arr)
 
-        assert_equal(np.argmin(arr), pos, err_msg="%r" % arr)
-        assert_equal(arr[np.argmin(arr)], min_val, err_msg="%r" % arr)
+        assert_equal(np.argmin(arr), pos, err_msg=f"{arr!r}")
+        assert_equal(arr[np.argmin(arr)], min_val, err_msg=f"{arr!r}")
 
         # add padding to test SIMD loops
         rarr = np.repeat(arr, 129)
         rpos = pos * 129
-        assert_equal(np.argmin(rarr), rpos, err_msg="%r" % rarr)
-        assert_equal(rarr[np.argmin(rarr)], min_val, err_msg="%r" % rarr)
+        assert_equal(np.argmin(rarr), rpos, err_msg=f"{rarr!r}")
+        assert_equal(rarr[np.argmin(rarr)], min_val, err_msg=f"{rarr!r}")
 
         padd = np.repeat(np.max(arr), 513)
         rarr = np.concatenate((arr, padd))
         rpos = pos
-        assert_equal(np.argmin(rarr), rpos, err_msg="%r" % rarr)
-        assert_equal(rarr[np.argmin(rarr)], min_val, err_msg="%r" % rarr)
+        assert_equal(np.argmin(rarr), rpos, err_msg=f"{rarr!r}")
+        assert_equal(rarr[np.argmin(rarr)], min_val, err_msg=f"{rarr!r}")
 
     def test_minimum_signed_integers(self):
 
@@ -7884,7 +7884,7 @@ def _check(self, spec, wanted):
         dt = np.dtype(wanted)
         actual = _dtype_from_pep3118(spec)
         assert_equal(actual, dt,
-                     err_msg="spec %r != dtype %r" % (spec, wanted))
+                     err_msg=f"spec {spec!r} != dtype {wanted!r}")
 
     def test_native_padding(self):
         align = np.dtype('i').alignment
@@ -8887,43 +8887,43 @@ class TestConversion:
     def test_array_scalar_relational_operation(self):
         # All integer
         for dt1 in np.typecodes['AllInteger']:
-            assert_(1 > np.array(0, dtype=dt1), "type %s failed" % (dt1,))
-            assert_(not 1 < np.array(0, dtype=dt1), "type %s failed" % (dt1,))
+            assert_(1 > np.array(0, dtype=dt1), f"type {dt1} failed")
+            assert_(not 1 < np.array(0, dtype=dt1), f"type {dt1} failed")
 
             for dt2 in np.typecodes['AllInteger']:
                 assert_(np.array(1, dtype=dt1) > np.array(0, dtype=dt2),
-                        "type %s and %s failed" % (dt1, dt2))
+                        f"type {dt1} and {dt2} failed")
                 assert_(not np.array(1, dtype=dt1) < np.array(0, dtype=dt2),
-                        "type %s and %s failed" % (dt1, dt2))
+                        f"type {dt1} and {dt2} failed")
 
         # Unsigned integers
         for dt1 in 'BHILQP':
-            assert_(-1 < np.array(1, dtype=dt1), "type %s failed" % (dt1,))
-            assert_(not -1 > np.array(1, dtype=dt1), "type %s failed" % (dt1,))
-            assert_(-1 != np.array(1, dtype=dt1), "type %s failed" % (dt1,))
+            assert_(-1 < np.array(1, dtype=dt1), f"type {dt1} failed")
+            assert_(not -1 > np.array(1, dtype=dt1), f"type {dt1} failed")
+            assert_(-1 != np.array(1, dtype=dt1), f"type {dt1} failed")
 
             # Unsigned vs signed
             for dt2 in 'bhilqp':
                 assert_(np.array(1, dtype=dt1) > np.array(-1, dtype=dt2),
-                        "type %s and %s failed" % (dt1, dt2))
+                        f"type {dt1} and {dt2} failed")
                 assert_(not np.array(1, dtype=dt1) < np.array(-1, dtype=dt2),
-                        "type %s and %s failed" % (dt1, dt2))
+                        f"type {dt1} and {dt2} failed")
                 assert_(np.array(1, dtype=dt1) != np.array(-1, dtype=dt2),
-                        "type %s and %s failed" % (dt1, dt2))
+                        f"type {dt1} and {dt2} failed")
 
         # Signed integers and floats
         for dt1 in 'bhlqp' + np.typecodes['Float']:
-            assert_(1 > np.array(-1, dtype=dt1), "type %s failed" % (dt1,))
-            assert_(not 1 < np.array(-1, dtype=dt1), "type %s failed" % (dt1,))
-            assert_(-1 == np.array(-1, dtype=dt1), "type %s failed" % (dt1,))
+            assert_(1 > np.array(-1, dtype=dt1), f"type {dt1} failed")
+            assert_(not 1 < np.array(-1, dtype=dt1), f"type {dt1} failed")
+            assert_(-1 == np.array(-1, dtype=dt1), f"type {dt1} failed")
 
             for dt2 in 'bhlqp' + np.typecodes['Float']:
                 assert_(np.array(1, dtype=dt1) > np.array(-1, dtype=dt2),
-                        "type %s and %s failed" % (dt1, dt2))
+                        f"type {dt1} and {dt2} failed")
                 assert_(not np.array(1, dtype=dt1) < np.array(-1, dtype=dt2),
-                        "type %s and %s failed" % (dt1, dt2))
+                        f"type {dt1} and {dt2} failed")
                 assert_(np.array(-1, dtype=dt1) == np.array(-1, dtype=dt2),
-                        "type %s and %s failed" % (dt1, dt2))
+                        f"type {dt1} and {dt2} failed")
 
     def test_to_bool_scalar(self):
         assert_equal(bool(np.array([False])), False)
diff --git a/numpy/_core/tests/test_nditer.py b/numpy/_core/tests/test_nditer.py
index 216682100e71..b8328f174e3f 100644
--- a/numpy/_core/tests/test_nditer.py
+++ b/numpy/_core/tests/test_nditer.py
@@ -675,10 +675,10 @@ def test_iter_broadcasting_errors():
         msg = str(e)
         # The message should contain the shape of the 3rd operand
         assert_(msg.find('(2,3)') >= 0,
-                'Message "%s" doesn\'t contain operand shape (2,3)' % msg)
+                f'Message "{msg}" doesn\'t contain operand shape (2,3)')
         # The message should contain the broadcast shape
         assert_(msg.find('(1,2,3)') >= 0,
-                'Message "%s" doesn\'t contain broadcast shape (1,2,3)' % msg)
+                f'Message "{msg}" doesn\'t contain broadcast shape (1,2,3)')
 
     try:
         nditer([arange(6).reshape(2, 3), arange(2)],
@@ -691,13 +691,13 @@ def test_iter_broadcasting_errors():
         msg = str(e)
         # The message should contain "shape->remappedshape" for each operand
         assert_(msg.find('(2,3)->(2,3)') >= 0,
-            'Message "%s" doesn\'t contain operand shape (2,3)->(2,3)' % msg)
+            f'Message "{msg}" doesn\'t contain operand shape (2,3)->(2,3)')
         assert_(msg.find('(2,)->(2,newaxis)') >= 0,
                 ('Message "%s" doesn\'t contain remapped operand shape'
                 '(2,)->(2,newaxis)') % msg)
         # The message should contain the itershape parameter
         assert_(msg.find('(4,3)') >= 0,
-                'Message "%s" doesn\'t contain itershape parameter (4,3)' % msg)
+                f'Message "{msg}" doesn\'t contain itershape parameter (4,3)')
 
     try:
         nditer([np.zeros((2, 1, 1)), np.zeros((2,))],
@@ -708,10 +708,10 @@ def test_iter_broadcasting_errors():
         msg = str(e)
         # The message should contain the shape of the bad operand
         assert_(msg.find('(2,1,1)') >= 0,
-            'Message "%s" doesn\'t contain operand shape (2,1,1)' % msg)
+            f'Message "{msg}" doesn\'t contain operand shape (2,1,1)')
         # The message should contain the broadcast shape
         assert_(msg.find('(2,1,2)') >= 0,
-                'Message "%s" doesn\'t contain the broadcast shape (2,1,2)' % msg)
+                f'Message "{msg}" doesn\'t contain the broadcast shape (2,1,2)')
 
 def test_iter_flags_errors():
     # Check that bad combinations of flags produce errors
diff --git a/numpy/_core/tests/test_numeric.py b/numpy/_core/tests/test_numeric.py
index 6a35b82ed766..eed2f7a02c7b 100644
--- a/numpy/_core/tests/test_numeric.py
+++ b/numpy/_core/tests/test_numeric.py
@@ -763,10 +763,10 @@ def test_all_any(self):
         for i in list(range(9, 6000, 507)) + [7764, 90021, -10]:
             d = np.array([False] * 100043, dtype=bool)
             d[i] = True
-            assert_(np.any(d), msg="%r" % i)
+            assert_(np.any(d), msg=f"{i!r}")
             e = np.array([True] * 100043, dtype=bool)
             e[i] = False
-            assert_(not np.all(e), msg="%r" % i)
+            assert_(not np.all(e), msg=f"{i!r}")
 
     def test_logical_not_abs(self):
         assert_array_equal(~self.t, self.f)
@@ -962,10 +962,10 @@ def assert_raises_fpe(self, fpeerr, flop, x, y):
         try:
             flop(x, y)
             assert_(False,
-                    "Type %s did not raise fpe error '%s'." % (ftype, fpeerr))
+                    f"Type {ftype} did not raise fpe error '{fpeerr}'.")
         except FloatingPointError as exc:
             assert_(str(exc).find(fpeerr) >= 0,
-                    "Type %s raised wrong fpe error '%s'." % (ftype, exc))
+                    f"Type {ftype} raised wrong fpe error '{exc}'.")
 
     def assert_op_raises_fpe(self, fpeerr, flop, sc1, sc2):
         # Check that fpe exception is raised.
@@ -1145,26 +1145,26 @@ def res_type(a, b):
         #           shouldn't narrow the float/complex type
         for a in [np.array([True, False]), np.array([-3, 12], dtype=np.int8)]:
             b = 1.234 * a
-            assert_equal(b.dtype, np.dtype('f8'), "array type %s" % a.dtype)
+            assert_equal(b.dtype, np.dtype('f8'), f"array type {a.dtype}")
             b = np.longdouble(1.234) * a
             assert_equal(b.dtype, np.dtype(np.longdouble),
-                         "array type %s" % a.dtype)
+                         f"array type {a.dtype}")
             b = np.float64(1.234) * a
-            assert_equal(b.dtype, np.dtype('f8'), "array type %s" % a.dtype)
+            assert_equal(b.dtype, np.dtype('f8'), f"array type {a.dtype}")
             b = np.float32(1.234) * a
-            assert_equal(b.dtype, np.dtype('f4'), "array type %s" % a.dtype)
+            assert_equal(b.dtype, np.dtype('f4'), f"array type {a.dtype}")
             b = np.float16(1.234) * a
-            assert_equal(b.dtype, np.dtype('f2'), "array type %s" % a.dtype)
+            assert_equal(b.dtype, np.dtype('f2'), f"array type {a.dtype}")
 
             b = 1.234j * a
-            assert_equal(b.dtype, np.dtype('c16'), "array type %s" % a.dtype)
+            assert_equal(b.dtype, np.dtype('c16'), f"array type {a.dtype}")
             b = np.clongdouble(1.234j) * a
             assert_equal(b.dtype, np.dtype(np.clongdouble),
-                         "array type %s" % a.dtype)
+                         f"array type {a.dtype}")
             b = np.complex128(1.234j) * a
-            assert_equal(b.dtype, np.dtype('c16'), "array type %s" % a.dtype)
+            assert_equal(b.dtype, np.dtype('c16'), f"array type {a.dtype}")
             b = np.complex64(1.234j) * a
-            assert_equal(b.dtype, np.dtype('c8'), "array type %s" % a.dtype)
+            assert_equal(b.dtype, np.dtype('c8'), f"array type {a.dtype}")
 
         # The following use-case is problematic, and to resolve its
         # tricky side-effects requires more changes.
@@ -1554,7 +1554,7 @@ def load_data(self, n, eindex):
         # Raise an exception at the desired index in the iterator.
         for e in range(n):
             if e == eindex:
-                raise NIterError('error at index %s' % eindex)
+                raise NIterError(f'error at index {eindex}')
             yield e
 
     @pytest.mark.parametrize("dtype", [int, object])
@@ -2915,10 +2915,10 @@ def teardown_method(self):
         np.seterr(**self.olderr)
 
     def tst_allclose(self, x, y):
-        assert_(np.allclose(x, y), "%s and %s not close" % (x, y))
+        assert_(np.allclose(x, y), f"{x} and {y} not close")
 
     def tst_not_allclose(self, x, y):
-        assert_(not np.allclose(x, y), "%s and %s shouldn't be close" % (x, y))
+        assert_(not np.allclose(x, y), f"{x} and {y} shouldn't be close")
 
     def test_ip_allclose(self):
         # Parametric test factory.
@@ -3077,7 +3077,7 @@ def test_nep50_isclose(self):
         assert not np.isclose(f32, 2, atol=0, rtol=np.float64(below_one / 2))
 
     def tst_all_isclose(self, x, y):
-        assert_(np.all(np.isclose(x, y)), "%s and %s not close" % (x, y))
+        assert_(np.all(np.isclose(x, y)), f"{x} and {y} not close")
 
     def tst_none_isclose(self, x, y):
         msg = "%s and %s shouldn't be close"
diff --git a/numpy/_core/tests/test_numerictypes.py b/numpy/_core/tests/test_numerictypes.py
index 6c7202639de4..ec35e30bd5cd 100644
--- a/numpy/_core/tests/test_numerictypes.py
+++ b/numpy/_core/tests/test_numerictypes.py
@@ -97,8 +97,7 @@ def normalize_descr(descr):
             l = normalize_descr(dtype)
             out.append((item[0], l))
         else:
-            raise ValueError("Expected a str or list and got %s" %
-                             (type(item)))
+            raise ValueError(f"Expected a str or list and got {type(item)}")
     return out
 
 
diff --git a/numpy/_core/tests/test_print.py b/numpy/_core/tests/test_print.py
index ac5445ff3035..856cfa6e0a34 100644
--- a/numpy/_core/tests/test_print.py
+++ b/numpy/_core/tests/test_print.py
@@ -23,15 +23,15 @@ def test_float_types(tp):
     """
     for x in [0, 1, -1, 1e20]:
         assert_equal(str(tp(x)), str(float(x)),
-                     err_msg='Failed str formatting for type %s' % tp)
+                     err_msg=f'Failed str formatting for type {tp}')
 
     if tp(1e16).itemsize > 4:
         assert_equal(str(tp(1e16)), str(float('1e16')),
-                     err_msg='Failed str formatting for type %s' % tp)
+                     err_msg=f'Failed str formatting for type {tp}')
     else:
         ref = '1e+16'
         assert_equal(str(tp(1e16)), ref,
-                     err_msg='Failed str formatting for type %s' % tp)
+                     err_msg=f'Failed str formatting for type {tp}')
 
 
 @pytest.mark.parametrize('tp', [np.float32, np.double, np.longdouble])
@@ -45,7 +45,7 @@ def test_nan_inf_float(tp):
     """
     for x in [np.inf, -np.inf, np.nan]:
         assert_equal(str(tp(x)), _REF[x],
-                     err_msg='Failed str formatting for type %s' % tp)
+                     err_msg=f'Failed str formatting for type {tp}')
 
 
 @pytest.mark.parametrize('tp', [np.complex64, np.cdouble, np.clongdouble])
@@ -59,19 +59,19 @@ def test_complex_types(tp):
     """
     for x in [0, 1, -1, 1e20]:
         assert_equal(str(tp(x)), str(complex(x)),
-                     err_msg='Failed str formatting for type %s' % tp)
+                     err_msg=f'Failed str formatting for type {tp}')
         assert_equal(str(tp(x * 1j)), str(complex(x * 1j)),
-                     err_msg='Failed str formatting for type %s' % tp)
+                     err_msg=f'Failed str formatting for type {tp}')
         assert_equal(str(tp(x + x * 1j)), str(complex(x + x * 1j)),
-                     err_msg='Failed str formatting for type %s' % tp)
+                     err_msg=f'Failed str formatting for type {tp}')
 
     if tp(1e16).itemsize > 8:
         assert_equal(str(tp(1e16)), str(complex(1e16)),
-                     err_msg='Failed str formatting for type %s' % tp)
+                     err_msg=f'Failed str formatting for type {tp}')
     else:
         ref = '(1e+16+0j)'
         assert_equal(str(tp(1e16)), ref,
-                     err_msg='Failed str formatting for type %s' % tp)
+                     err_msg=f'Failed str formatting for type {tp}')
 
 
 @pytest.mark.parametrize('dtype', [np.complex64, np.cdouble, np.clongdouble])
@@ -116,7 +116,7 @@ def _test_redirected_print(x, tp, ref=None):
         sys.stdout = stdout
 
     assert_equal(file.getvalue(), file_tp.getvalue(),
-                 err_msg='print failed for type%s' % tp)
+                 err_msg=f'print failed for type{tp}')
 
 
 @pytest.mark.parametrize('tp', [np.float32, np.double, np.longdouble])
@@ -177,7 +177,7 @@ def test_scalar_format():
     for (fmat, val, valtype) in tests:
         try:
             assert_equal(fmat.format(val), fmat.format(valtype(val)),
-                    "failed with val %s, type %s" % (val, valtype))
+                    f"failed with val {val}, type {valtype}")
         except ValueError as e:
             assert_(False,
                "format raised exception (fmt='%s', val=%s, type=%s, exc='%s')" %
diff --git a/numpy/_core/tests/test_regression.py b/numpy/_core/tests/test_regression.py
index 6ab7737b34b3..3d583eeef860 100644
--- a/numpy/_core/tests/test_regression.py
+++ b/numpy/_core/tests/test_regression.py
@@ -138,7 +138,7 @@ def test_unicode_swapping(self):
         # Ticket #79
         ulen = 1
         ucs_value = '\U0010FFFF'
-        ua = np.array([[[ucs_value * ulen] * 2] * 3] * 4, dtype='U%s' % ulen)
+        ua = np.array([[[ucs_value * ulen] * 2] * 3] * 4, dtype=f'U{ulen}')
         ua.view(ua.dtype.newbyteorder())  # Should succeed.
 
     def test_object_array_fill(self):
@@ -1524,7 +1524,7 @@ def test_ticket_1539(self):
                     if d != 0:
                         failures.append((x, y))
         if failures:
-            raise AssertionError("Failures: %r" % failures)
+            raise AssertionError(f"Failures: {failures!r}")
 
     def test_ticket_1538(self):
         x = np.finfo(np.float32)
diff --git a/numpy/_core/tests/test_scalarmath.py b/numpy/_core/tests/test_scalarmath.py
index cee1389569a2..e9cac03c7a9b 100644
--- a/numpy/_core/tests/test_scalarmath.py
+++ b/numpy/_core/tests/test_scalarmath.py
@@ -45,7 +45,7 @@ class TestTypes:
     def test_types(self):
         for atype in types:
             a = atype(1)
-            assert_(a == 1, "error with %r: got %r" % (atype, a))
+            assert_(a == 1, f"error with {atype!r}: got {a!r}")
 
     def test_type_add(self):
         # list of types
@@ -202,13 +202,13 @@ def test_small_types(self):
         for t in [np.int8, np.int16, np.float16]:
             a = t(3)
             b = a ** 4
-            assert_(b == 81, "error with %r: got %r" % (t, b))
+            assert_(b == 81, f"error with {t!r}: got {b!r}")
 
     def test_large_types(self):
         for t in [np.int32, np.int64, np.float32, np.float64, np.longdouble]:
             a = t(51)
             b = a ** 4
-            msg = "error with %r: got %r" % (t, b)
+            msg = f"error with {t!r}: got {b!r}"
             if np.issubdtype(t, np.integer):
                 assert_(b == 6765201, msg)
             else:
@@ -259,8 +259,7 @@ def test_mixed_types(self):
                 a = t1(3)
                 b = t2(2)
                 result = a**b
-                msg = ("error with %r and %r:"
-                       "got %r, expected %r") % (t1, t2, result, 9)
+                msg = f"error with {t1!r} and {t2!r}:got {result!r}, expected {9!r}"
                 if np.issubdtype(np.dtype(result), np.integer):
                     assert_(result == 9, msg)
                 else:
@@ -326,7 +325,7 @@ def test_float_modulus_exact(self):
 
         for op in [floordiv_and_mod, divmod]:
             for dt in np.typecodes['Float']:
-                msg = 'op: %s, dtype: %s' % (op.__name__, dt)
+                msg = f'op: {op.__name__}, dtype: {dt}'
                 fa = a.astype(dt)
                 fb = b.astype(dt)
                 # use list comprehension so a_ and b_ are scalars
@@ -358,9 +357,9 @@ def test_float_modulus_corner_cases(self):
             b = np.array(1.0, dtype=dt)
             a = np.nextafter(np.array(0.0, dtype=dt), -b)
             rem = operator.mod(a, b)
-            assert_(rem <= b, 'dt: %s' % dt)
+            assert_(rem <= b, f'dt: {dt}')
             rem = operator.mod(-a, -b)
-            assert_(rem >= -b, 'dt: %s' % dt)
+            assert_(rem >= -b, f'dt: {dt}')
 
         # Check nans, inf
         with suppress_warnings() as sup:
@@ -375,14 +374,14 @@ def test_float_modulus_corner_cases(self):
                 finf = np.array(np.inf, dtype=dt)
                 fnan = np.array(np.nan, dtype=dt)
                 rem = operator.mod(fone, fzer)
-                assert_(np.isnan(rem), 'dt: %s' % dt)
+                assert_(np.isnan(rem), f'dt: {dt}')
                 # MSVC 2008 returns NaN here, so disable the check.
                 #rem = operator.mod(fone, finf)
                 #assert_(rem == fone, 'dt: %s' % dt)
                 rem = operator.mod(fone, fnan)
-                assert_(np.isnan(rem), 'dt: %s' % dt)
+                assert_(np.isnan(rem), f'dt: {dt}')
                 rem = operator.mod(finf, fone)
-                assert_(np.isnan(rem), 'dt: %s' % dt)
+                assert_(np.isnan(rem), f'dt: {dt}')
                 for op in [floordiv_and_mod, divmod]:
                     div, mod = op(fone, fzer)
                     assert_(np.isinf(div)) and assert_(np.isnan(mod))
@@ -554,43 +553,43 @@ def test_int_from_longdouble(self):
     def test_numpy_scalar_relational_operators(self):
         # All integer
         for dt1 in np.typecodes['AllInteger']:
-            assert_(1 > np.array(0, dtype=dt1)[()], "type %s failed" % (dt1,))
-            assert_(not 1 < np.array(0, dtype=dt1)[()], "type %s failed" % (dt1,))
+            assert_(1 > np.array(0, dtype=dt1)[()], f"type {dt1} failed")
+            assert_(not 1 < np.array(0, dtype=dt1)[()], f"type {dt1} failed")
 
             for dt2 in np.typecodes['AllInteger']:
                 assert_(np.array(1, dtype=dt1)[()] > np.array(0, dtype=dt2)[()],
-                        "type %s and %s failed" % (dt1, dt2))
+                        f"type {dt1} and {dt2} failed")
                 assert_(not np.array(1, dtype=dt1)[()] < np.array(0, dtype=dt2)[()],
-                        "type %s and %s failed" % (dt1, dt2))
+                        f"type {dt1} and {dt2} failed")
 
         #Unsigned integers
         for dt1 in 'BHILQP':
-            assert_(-1 < np.array(1, dtype=dt1)[()], "type %s failed" % (dt1,))
-            assert_(not -1 > np.array(1, dtype=dt1)[()], "type %s failed" % (dt1,))
-            assert_(-1 != np.array(1, dtype=dt1)[()], "type %s failed" % (dt1,))
+            assert_(-1 < np.array(1, dtype=dt1)[()], f"type {dt1} failed")
+            assert_(not -1 > np.array(1, dtype=dt1)[()], f"type {dt1} failed")
+            assert_(-1 != np.array(1, dtype=dt1)[()], f"type {dt1} failed")
 
             #unsigned vs signed
             for dt2 in 'bhilqp':
                 assert_(np.array(1, dtype=dt1)[()] > np.array(-1, dtype=dt2)[()],
-                        "type %s and %s failed" % (dt1, dt2))
+                        f"type {dt1} and {dt2} failed")
                 assert_(not np.array(1, dtype=dt1)[()] < np.array(-1, dtype=dt2)[()],
-                        "type %s and %s failed" % (dt1, dt2))
+                        f"type {dt1} and {dt2} failed")
                 assert_(np.array(1, dtype=dt1)[()] != np.array(-1, dtype=dt2)[()],
-                        "type %s and %s failed" % (dt1, dt2))
+                        f"type {dt1} and {dt2} failed")
 
         #Signed integers and floats
         for dt1 in 'bhlqp' + np.typecodes['Float']:
-            assert_(1 > np.array(-1, dtype=dt1)[()], "type %s failed" % (dt1,))
-            assert_(not 1 < np.array(-1, dtype=dt1)[()], "type %s failed" % (dt1,))
-            assert_(-1 == np.array(-1, dtype=dt1)[()], "type %s failed" % (dt1,))
+            assert_(1 > np.array(-1, dtype=dt1)[()], f"type {dt1} failed")
+            assert_(not 1 < np.array(-1, dtype=dt1)[()], f"type {dt1} failed")
+            assert_(-1 == np.array(-1, dtype=dt1)[()], f"type {dt1} failed")
 
             for dt2 in 'bhlqp' + np.typecodes['Float']:
                 assert_(np.array(1, dtype=dt1)[()] > np.array(-1, dtype=dt2)[()],
-                        "type %s and %s failed" % (dt1, dt2))
+                        f"type {dt1} and {dt2} failed")
                 assert_(not np.array(1, dtype=dt1)[()] < np.array(-1, dtype=dt2)[()],
-                        "type %s and %s failed" % (dt1, dt2))
+                        f"type {dt1} and {dt2} failed")
                 assert_(np.array(-1, dtype=dt1)[()] == np.array(-1, dtype=dt2)[()],
-                        "type %s and %s failed" % (dt1, dt2))
+                        f"type {dt1} and {dt2} failed")
 
     def test_scalar_comparison_to_none(self):
         # Scalars should just return False and not give a warnings.
diff --git a/numpy/_core/tests/test_simd.py b/numpy/_core/tests/test_simd.py
index 94f92a45a86c..fdcab688963e 100644
--- a/numpy/_core/tests/test_simd.py
+++ b/numpy/_core/tests/test_simd.py
@@ -1104,8 +1104,8 @@ def test_operators_crosstest(self, intrin, data):
 
     def test_conversion_boolean(self):
         bsfx = "b" + self.sfx[1:]
-        to_boolean = getattr(self.npyv, "cvt_%s_%s" % (bsfx, self.sfx))
-        from_boolean = getattr(self.npyv, "cvt_%s_%s" % (self.sfx, bsfx))
+        to_boolean = getattr(self.npyv, f"cvt_{bsfx}_{self.sfx}")
+        from_boolean = getattr(self.npyv, f"cvt_{self.sfx}_{bsfx}")
 
         false_vb = to_boolean(self.setall(0))
         true_vb = self.cmpeq(self.setall(0), self.setall(0))
diff --git a/numpy/_core/tests/test_ufunc.py b/numpy/_core/tests/test_ufunc.py
index 737402315957..0dbef44300b1 100644
--- a/numpy/_core/tests/test_ufunc.py
+++ b/numpy/_core/tests/test_ufunc.py
@@ -1450,7 +1450,7 @@ def test_matrix_multiply_umath_empty(self):
     def compare_matrix_multiply_results(self, tp):
         d1 = np.array(np.random.rand(2, 3, 4), dtype=tp)
         d2 = np.array(np.random.rand(2, 3, 4), dtype=tp)
-        msg = "matrix multiply on type %s" % d1.dtype.name
+        msg = f"matrix multiply on type {d1.dtype.name}"
 
         def permute_n(n):
             if n == 1:
@@ -1496,8 +1496,7 @@ def broadcastable(s1, s2):
                                 umt.matrix_multiply(a1, a2),
                                 np.sum(a2[..., np.newaxis].swapaxes(-3, -1) *
                                        a1[..., np.newaxis, :], axis=-1),
-                                err_msg=msg + ' %s %s' % (str(a1.shape),
-                                                          str(a2.shape)))
+                                err_msg=msg + f' {str(a1.shape)} {str(a2.shape)}')
 
         assert_equal(ref, True, err_msg="reference check")
 
diff --git a/numpy/_core/tests/test_umath.py b/numpy/_core/tests/test_umath.py
index 370694bd44b4..c6708e14034e 100644
--- a/numpy/_core/tests/test_umath.py
+++ b/numpy/_core/tests/test_umath.py
@@ -693,11 +693,11 @@ def test_floor_division_corner_cases(self, dtype):
         with suppress_warnings() as sup:
             sup.filter(RuntimeWarning, "invalid value encountered in floor_divide")
             div = np.floor_divide(fnan, fone)
-            assert np.isnan(div), "div: %s" % div
+            assert np.isnan(div), f"div: {div}"
             div = np.floor_divide(fone, fnan)
-            assert np.isnan(div), "div: %s" % div
+            assert np.isnan(div), f"div: {div}"
             div = np.floor_divide(fnan, fzer)
-            assert np.isnan(div), "div: %s" % div
+            assert np.isnan(div), f"div: {div}"
         # verify 1.0//0.0 computations return inf
         with np.errstate(divide='ignore'):
             z = np.floor_divide(y, x)
@@ -751,7 +751,7 @@ def test_float_remainder_exact(self):
 
         for op in [floor_divide_and_remainder, np.divmod]:
             for dt in np.typecodes['Float']:
-                msg = 'op: %s, dtype: %s' % (op.__name__, dt)
+                msg = f'op: {op.__name__}, dtype: {dt}'
                 fa = a.astype(dt)
                 fb = b.astype(dt)
                 div, rem = op(fa, fb)
@@ -850,26 +850,26 @@ def test_float_divmod_corner_cases(self):
                 sup.filter(RuntimeWarning, "invalid value encountered in divmod")
                 sup.filter(RuntimeWarning, "divide by zero encountered in divmod")
                 div, rem = np.divmod(fone, fzer)
-                assert np.isinf(div), 'dt: %s, div: %s' % (dt, rem)
-                assert np.isnan(rem), 'dt: %s, rem: %s' % (dt, rem)
+                assert np.isinf(div), f'dt: {dt}, div: {rem}'
+                assert np.isnan(rem), f'dt: {dt}, rem: {rem}'
                 div, rem = np.divmod(fzer, fzer)
-                assert np.isnan(rem), 'dt: %s, rem: %s' % (dt, rem)
-                assert_(np.isnan(div)), 'dt: %s, rem: %s' % (dt, rem)
+                assert np.isnan(rem), f'dt: {dt}, rem: {rem}'
+                assert_(np.isnan(div)), f'dt: {dt}, rem: {rem}'
                 div, rem = np.divmod(finf, finf)
-                assert np.isnan(div), 'dt: %s, rem: %s' % (dt, rem)
-                assert np.isnan(rem), 'dt: %s, rem: %s' % (dt, rem)
+                assert np.isnan(div), f'dt: {dt}, rem: {rem}'
+                assert np.isnan(rem), f'dt: {dt}, rem: {rem}'
                 div, rem = np.divmod(finf, fzer)
-                assert np.isinf(div), 'dt: %s, rem: %s' % (dt, rem)
-                assert np.isnan(rem), 'dt: %s, rem: %s' % (dt, rem)
+                assert np.isinf(div), f'dt: {dt}, rem: {rem}'
+                assert np.isnan(rem), f'dt: {dt}, rem: {rem}'
                 div, rem = np.divmod(fnan, fone)
-                assert np.isnan(rem), "dt: %s, rem: %s" % (dt, rem)
-                assert np.isnan(div), "dt: %s, rem: %s" % (dt, rem)
+                assert np.isnan(rem), f"dt: {dt}, rem: {rem}"
+                assert np.isnan(div), f"dt: {dt}, rem: {rem}"
                 div, rem = np.divmod(fone, fnan)
-                assert np.isnan(rem), "dt: %s, rem: %s" % (dt, rem)
-                assert np.isnan(div), "dt: %s, rem: %s" % (dt, rem)
+                assert np.isnan(rem), f"dt: {dt}, rem: {rem}"
+                assert np.isnan(div), f"dt: {dt}, rem: {rem}"
                 div, rem = np.divmod(fnan, fzer)
-                assert np.isnan(rem), "dt: %s, rem: %s" % (dt, rem)
-                assert np.isnan(div), "dt: %s, rem: %s" % (dt, rem)
+                assert np.isnan(rem), f"dt: {dt}, rem: {rem}"
+                assert np.isnan(div), f"dt: {dt}, rem: {rem}"
 
     def test_float_remainder_corner_cases(self):
         # Check remainder magnitude.
@@ -880,9 +880,9 @@ def test_float_remainder_corner_cases(self):
             b = np.array(1.0, dtype=dt)
             a = np.nextafter(np.array(0.0, dtype=dt), -b)
             rem = np.remainder(a, b)
-            assert_(rem <= b, 'dt: %s' % dt)
+            assert_(rem <= b, f'dt: {dt}')
             rem = np.remainder(-a, -b)
-            assert_(rem >= -b, 'dt: %s' % dt)
+            assert_(rem >= -b, f'dt: {dt}')
 
         # Check nans, inf
         with suppress_warnings() as sup:
@@ -894,34 +894,34 @@ def test_float_remainder_corner_cases(self):
                 finf = np.array(np.inf, dtype=dt)
                 fnan = np.array(np.nan, dtype=dt)
                 rem = np.remainder(fone, fzer)
-                assert_(np.isnan(rem), 'dt: %s, rem: %s' % (dt, rem))
+                assert_(np.isnan(rem), f'dt: {dt}, rem: {rem}')
                 # MSVC 2008 returns NaN here, so disable the check.
                 #rem = np.remainder(fone, finf)
                 #assert_(rem == fone, 'dt: %s, rem: %s' % (dt, rem))
                 rem = np.remainder(finf, fone)
                 fmod = np.fmod(finf, fone)
-                assert_(np.isnan(fmod), 'dt: %s, fmod: %s' % (dt, fmod))
-                assert_(np.isnan(rem), 'dt: %s, rem: %s' % (dt, rem))
+                assert_(np.isnan(fmod), f'dt: {dt}, fmod: {fmod}')
+                assert_(np.isnan(rem), f'dt: {dt}, rem: {rem}')
                 rem = np.remainder(finf, finf)
                 fmod = np.fmod(finf, fone)
-                assert_(np.isnan(rem), 'dt: %s, rem: %s' % (dt, rem))
-                assert_(np.isnan(fmod), 'dt: %s, fmod: %s' % (dt, fmod))
+                assert_(np.isnan(rem), f'dt: {dt}, rem: {rem}')
+                assert_(np.isnan(fmod), f'dt: {dt}, fmod: {fmod}')
                 rem = np.remainder(finf, fzer)
                 fmod = np.fmod(finf, fzer)
-                assert_(np.isnan(rem), 'dt: %s, rem: %s' % (dt, rem))
-                assert_(np.isnan(fmod), 'dt: %s, fmod: %s' % (dt, fmod))
+                assert_(np.isnan(rem), f'dt: {dt}, rem: {rem}')
+                assert_(np.isnan(fmod), f'dt: {dt}, fmod: {fmod}')
                 rem = np.remainder(fone, fnan)
                 fmod = np.fmod(fone, fnan)
-                assert_(np.isnan(rem), 'dt: %s, rem: %s' % (dt, rem))
-                assert_(np.isnan(fmod), 'dt: %s, fmod: %s' % (dt, fmod))
+                assert_(np.isnan(rem), f'dt: {dt}, rem: {rem}')
+                assert_(np.isnan(fmod), f'dt: {dt}, fmod: {fmod}')
                 rem = np.remainder(fnan, fzer)
                 fmod = np.fmod(fnan, fzer)
-                assert_(np.isnan(rem), 'dt: %s, rem: %s' % (dt, rem))
-                assert_(np.isnan(fmod), 'dt: %s, fmod: %s' % (dt, rem))
+                assert_(np.isnan(rem), f'dt: {dt}, rem: {rem}')
+                assert_(np.isnan(fmod), f'dt: {dt}, fmod: {rem}')
                 rem = np.remainder(fnan, fone)
                 fmod = np.fmod(fnan, fone)
-                assert_(np.isnan(rem), 'dt: %s, rem: %s' % (dt, rem))
-                assert_(np.isnan(fmod), 'dt: %s, fmod: %s' % (dt, rem))
+                assert_(np.isnan(rem), f'dt: {dt}, rem: {rem}')
+                assert_(np.isnan(fmod), f'dt: {dt}, fmod: {rem}')
 
 
 class TestDivisionIntegerOverflowsAndDivideByZero:
@@ -1264,7 +1264,7 @@ def test_type_conversion(self):
         arg_type = '?bhilBHILefdgFDG'
         res_type = 'ddddddddddddgDDG'
         for dtin, dtout in zip(arg_type, res_type):
-            msg = "dtin: %s, dtout: %s" % (dtin, dtout)
+            msg = f"dtin: {dtin}, dtout: {dtout}"
             arg = np.ones(1, dtype=dtin)
             res = np.float_power(arg, arg)
             assert_(res.dtype.name == np.dtype(dtout).name, msg)
@@ -2195,13 +2195,13 @@ def test_reduce(self):
 def assert_hypot_isnan(x, y):
     with np.errstate(invalid='ignore'):
         assert_(np.isnan(ncu.hypot(x, y)),
-                "hypot(%s, %s) is %s, not nan" % (x, y, ncu.hypot(x, y)))
+                f"hypot({x}, {y}) is {ncu.hypot(x, y)}, not nan")
 
 
 def assert_hypot_isinf(x, y):
     with np.errstate(invalid='ignore'):
         assert_(np.isinf(ncu.hypot(x, y)),
-                "hypot(%s, %s) is %s, not inf" % (x, y, ncu.hypot(x, y)))
+                f"hypot({x}, {y}) is {ncu.hypot(x, y)}, not inf")
 
 
 class TestHypotSpecialValues:
@@ -2222,23 +2222,23 @@ def test_no_fpe(self):
 
 
 def assert_arctan2_isnan(x, y):
-    assert_(np.isnan(ncu.arctan2(x, y)), "arctan(%s, %s) is %s, not nan" % (x, y, ncu.arctan2(x, y)))
+    assert_(np.isnan(ncu.arctan2(x, y)), f"arctan({x}, {y}) is {ncu.arctan2(x, y)}, not nan")
 
 
 def assert_arctan2_ispinf(x, y):
-    assert_((np.isinf(ncu.arctan2(x, y)) and ncu.arctan2(x, y) > 0), "arctan(%s, %s) is %s, not +inf" % (x, y, ncu.arctan2(x, y)))
+    assert_((np.isinf(ncu.arctan2(x, y)) and ncu.arctan2(x, y) > 0), f"arctan({x}, {y}) is {ncu.arctan2(x, y)}, not +inf")
 
 
 def assert_arctan2_isninf(x, y):
-    assert_((np.isinf(ncu.arctan2(x, y)) and ncu.arctan2(x, y) < 0), "arctan(%s, %s) is %s, not -inf" % (x, y, ncu.arctan2(x, y)))
+    assert_((np.isinf(ncu.arctan2(x, y)) and ncu.arctan2(x, y) < 0), f"arctan({x}, {y}) is {ncu.arctan2(x, y)}, not -inf")
 
 
 def assert_arctan2_ispzero(x, y):
-    assert_((ncu.arctan2(x, y) == 0 and not np.signbit(ncu.arctan2(x, y))), "arctan(%s, %s) is %s, not +0" % (x, y, ncu.arctan2(x, y)))
+    assert_((ncu.arctan2(x, y) == 0 and not np.signbit(ncu.arctan2(x, y))), f"arctan({x}, {y}) is {ncu.arctan2(x, y)}, not +0")
 
 
 def assert_arctan2_isnzero(x, y):
-    assert_((ncu.arctan2(x, y) == 0 and np.signbit(ncu.arctan2(x, y))), "arctan(%s, %s) is %s, not -0" % (x, y, ncu.arctan2(x, y)))
+    assert_((ncu.arctan2(x, y) == 0 and np.signbit(ncu.arctan2(x, y))), f"arctan({x}, {y}) is {ncu.arctan2(x, y)}, not -0")
 
 
 class TestArctan2SpecialValues:
@@ -2727,7 +2727,7 @@ def test_values(self):
         for dt in self.bitwise_types:
             zeros = np.array([0], dtype=dt)
             ones = np.array([-1]).astype(dt)
-            msg = "dt = '%s'" % dt.char
+            msg = f"dt = '{dt.char}'"
 
             assert_equal(np.bitwise_not(zeros), ones, err_msg=msg)
             assert_equal(np.bitwise_not(ones), zeros, err_msg=msg)
@@ -2751,7 +2751,7 @@ def test_types(self):
         for dt in self.bitwise_types:
             zeros = np.array([0], dtype=dt)
             ones = np.array([-1]).astype(dt)
-            msg = "dt = '%s'" % dt.char
+            msg = f"dt = '{dt.char}'"
 
             assert_(np.bitwise_not(zeros).dtype == dt, msg)
             assert_(np.bitwise_or(zeros, zeros).dtype == dt, msg)
@@ -2770,7 +2770,7 @@ def test_reduction(self):
             zeros = np.array([0], dtype=dt)
             ones = np.array([-1]).astype(dt)
             for f in binary_funcs:
-                msg = "dt: '%s', f: '%s'" % (dt, f)
+                msg = f"dt: '{dt}', f: '{f}'"
                 assert_equal(f.reduce(zeros), zeros, err_msg=msg)
                 assert_equal(f.reduce(ones), ones, err_msg=msg)
 
@@ -2779,7 +2779,7 @@ def test_reduction(self):
             # No object array types
             empty = np.array([], dtype=dt)
             for f in binary_funcs:
-                msg = "dt: '%s', f: '%s'" % (dt, f)
+                msg = f"dt: '{dt}', f: '{f}'"
                 tgt = np.array(f.identity).astype(dt)
                 res = f.reduce(empty)
                 assert_equal(res, tgt, err_msg=msg)
@@ -2790,7 +2790,7 @@ def test_reduction(self):
         # function and is not the same as the type returned by the identity
         # method.
         for f in binary_funcs:
-            msg = "dt: '%s'" % (f,)
+            msg = f"dt: '{f}'"
             empty = np.array([], dtype=object)
             tgt = f.identity
             res = f.reduce(empty)
@@ -2798,7 +2798,7 @@ def test_reduction(self):
 
         # Non-empty object arrays do not use the identity
         for f in binary_funcs:
-            msg = "dt: '%s'" % (f,)
+            msg = f"dt: '{f}'"
             btype = np.array([True], dtype=object)
             assert_(type(f.reduce(btype)) is bool, msg)
 
@@ -2936,7 +2936,7 @@ def test_minmax_blocked(self):
                 for i in range(inp.size):
                     inp[:] = np.arange(inp.size, dtype=dt)
                     inp[i] = np.nan
-                    emsg = lambda: '%r\n%s' % (inp, msg)
+                    emsg = lambda: f'{inp!r}\n{msg}'
                     with suppress_warnings() as sup:
                         sup.filter(RuntimeWarning,
                                    "invalid value encountered in reduce")
@@ -4228,8 +4228,8 @@ def test_it(self):
                 x = .5
             fr = f(x)
             fz = f(complex(x))
-            assert_almost_equal(fz.real, fr, err_msg='real part %s' % f)
-            assert_almost_equal(fz.imag, 0., err_msg='imag part %s' % f)
+            assert_almost_equal(fz.real, fr, err_msg=f'real part {f}')
+            assert_almost_equal(fz.imag, 0., err_msg=f'imag part {f}')
 
     @pytest.mark.xfail(IS_WASM, reason="doesn't work")
     def test_precisions_consistent(self):
@@ -4238,8 +4238,8 @@ def test_precisions_consistent(self):
             fcf = f(np.csingle(z))
             fcd = f(np.cdouble(z))
             fcl = f(np.clongdouble(z))
-            assert_almost_equal(fcf, fcd, decimal=6, err_msg='fch-fcd %s' % f)
-            assert_almost_equal(fcl, fcd, decimal=15, err_msg='fch-fcl %s' % f)
+            assert_almost_equal(fcf, fcd, decimal=6, err_msg=f'fch-fcd {f}')
+            assert_almost_equal(fcl, fcd, decimal=15, err_msg=f'fch-fcl {f}')
 
     @pytest.mark.xfail(IS_WASM, reason="doesn't work")
     def test_branch_cuts(self):
@@ -4312,7 +4312,7 @@ def test_against_cmath(self):
                 b = cfunc(p)
                 assert_(
                     abs(a - b) < atol,
-                    "%s %s: %s; cmath: %s" % (fname, p, a, b)
+                    f"{fname} {p}: {a}; cmath: {b}"
                 )
 
     @pytest.mark.xfail(
@@ -4717,11 +4717,11 @@ def test_complex_nan_comparisons():
                 if np.isfinite(x) and np.isfinite(y):
                     continue
 
-                assert_equal(x < y, False, err_msg="%r < %r" % (x, y))
-                assert_equal(x > y, False, err_msg="%r > %r" % (x, y))
-                assert_equal(x <= y, False, err_msg="%r <= %r" % (x, y))
-                assert_equal(x >= y, False, err_msg="%r >= %r" % (x, y))
-                assert_equal(x == y, False, err_msg="%r == %r" % (x, y))
+                assert_equal(x < y, False, err_msg=f"{x!r} < {y!r}")
+                assert_equal(x > y, False, err_msg=f"{x!r} > {y!r}")
+                assert_equal(x <= y, False, err_msg=f"{x!r} <= {y!r}")
+                assert_equal(x >= y, False, err_msg=f"{x!r} >= {y!r}")
+                assert_equal(x == y, False, err_msg=f"{x!r} == {y!r}")
 
 
 def test_rint_big_int():
diff --git a/numpy/_core/tests/test_unicode.py b/numpy/_core/tests/test_unicode.py
index 07cec2d854ff..6ca0cd46d781 100644
--- a/numpy/_core/tests/test_unicode.py
+++ b/numpy/_core/tests/test_unicode.py
@@ -65,18 +65,18 @@ def content_check(self, ua, ua_scalar, nbytes):
 
     def test_zeros0D(self):
         # Check creation of 0-dimensional objects
-        ua = np.zeros((), dtype='U%s' % self.ulen)
+        ua = np.zeros((), dtype=f'U{self.ulen}')
         self.content_check(ua, ua[()], 4 * self.ulen)
 
     def test_zerosSD(self):
         # Check creation of single-dimensional objects
-        ua = np.zeros((2,), dtype='U%s' % self.ulen)
+        ua = np.zeros((2,), dtype=f'U{self.ulen}')
         self.content_check(ua, ua[0], 4 * self.ulen * 2)
         self.content_check(ua, ua[1], 4 * self.ulen * 2)
 
     def test_zerosMD(self):
         # Check creation of multi-dimensional objects
-        ua = np.zeros((2, 3, 4), dtype='U%s' % self.ulen)
+        ua = np.zeros((2, 3, 4), dtype=f'U{self.ulen}')
         self.content_check(ua, ua[0, 0, 0], 4 * self.ulen * 2 * 3 * 4)
         self.content_check(ua, ua[-1, -1, -1], 4 * self.ulen * 2 * 3 * 4)
 
@@ -122,18 +122,18 @@ def content_check(self, ua, ua_scalar, nbytes):
 
     def test_values0D(self):
         # Check creation of 0-dimensional objects with values
-        ua = np.array(self.ucs_value * self.ulen, dtype='U%s' % self.ulen)
+        ua = np.array(self.ucs_value * self.ulen, dtype=f'U{self.ulen}')
         self.content_check(ua, ua[()], 4 * self.ulen)
 
     def test_valuesSD(self):
         # Check creation of single-dimensional objects with values
-        ua = np.array([self.ucs_value * self.ulen] * 2, dtype='U%s' % self.ulen)
+        ua = np.array([self.ucs_value * self.ulen] * 2, dtype=f'U{self.ulen}')
         self.content_check(ua, ua[0], 4 * self.ulen * 2)
         self.content_check(ua, ua[1], 4 * self.ulen * 2)
 
     def test_valuesMD(self):
         # Check creation of multi-dimensional objects with values
-        ua = np.array([[[self.ucs_value * self.ulen] * 2] * 3] * 4, dtype='U%s' % self.ulen)
+        ua = np.array([[[self.ucs_value * self.ulen] * 2] * 3] * 4, dtype=f'U{self.ulen}')
         self.content_check(ua, ua[0, 0, 0], 4 * self.ulen * 2 * 3 * 4)
         self.content_check(ua, ua[-1, -1, -1], 4 * self.ulen * 2 * 3 * 4)
 
@@ -204,13 +204,13 @@ def content_check(self, ua, ua_scalar, nbytes):
 
     def test_values0D(self):
         # Check assignment of 0-dimensional objects with values
-        ua = np.zeros((), dtype='U%s' % self.ulen)
+        ua = np.zeros((), dtype=f'U{self.ulen}')
         ua[()] = self.ucs_value * self.ulen
         self.content_check(ua, ua[()], 4 * self.ulen)
 
     def test_valuesSD(self):
         # Check assignment of single-dimensional objects with values
-        ua = np.zeros((2,), dtype='U%s' % self.ulen)
+        ua = np.zeros((2,), dtype=f'U{self.ulen}')
         ua[0] = self.ucs_value * self.ulen
         self.content_check(ua, ua[0], 4 * self.ulen * 2)
         ua[1] = self.ucs_value * self.ulen
@@ -218,7 +218,7 @@ def test_valuesSD(self):
 
     def test_valuesMD(self):
         # Check assignment of multi-dimensional objects with values
-        ua = np.zeros((2, 3, 4), dtype='U%s' % self.ulen)
+        ua = np.zeros((2, 3, 4), dtype=f'U{self.ulen}')
         ua[0, 0, 0] = self.ucs_value * self.ulen
         self.content_check(ua, ua[0, 0, 0], 4 * self.ulen * 2 * 3 * 4)
         ua[-1, -1, -1] = self.ucs_value * self.ulen
@@ -270,7 +270,7 @@ class ByteorderValues:
 
     def test_values0D(self):
         # Check byteorder of 0-dimensional objects
-        ua = np.array(self.ucs_value * self.ulen, dtype='U%s' % self.ulen)
+        ua = np.array(self.ucs_value * self.ulen, dtype=f'U{self.ulen}')
         ua2 = ua.view(ua.dtype.newbyteorder())
         # This changes the interpretation of the data region (but not the
         #  actual data), therefore the returned scalars are not
@@ -282,7 +282,7 @@ def test_values0D(self):
 
     def test_valuesSD(self):
         # Check byteorder of single-dimensional objects
-        ua = np.array([self.ucs_value * self.ulen] * 2, dtype='U%s' % self.ulen)
+        ua = np.array([self.ucs_value * self.ulen] * 2, dtype=f'U{self.ulen}')
         ua2 = ua.view(ua.dtype.newbyteorder())
         assert_((ua != ua2).all())
         assert_(ua[-1] != ua2[-1])
@@ -293,7 +293,7 @@ def test_valuesSD(self):
     def test_valuesMD(self):
         # Check byteorder of multi-dimensional objects
         ua = np.array([[[self.ucs_value * self.ulen] * 2] * 3] * 4,
-                      dtype='U%s' % self.ulen)
+                      dtype=f'U{self.ulen}')
         ua2 = ua.view(ua.dtype.newbyteorder())
         assert_((ua != ua2).all())
         assert_(ua[-1, -1, -1] != ua2[-1, -1, -1])
@@ -304,7 +304,7 @@ def test_valuesMD(self):
     def test_values_cast(self):
         # Check byteorder of when casting the array for a strided and
         # contiguous array:
-        test1 = np.array([self.ucs_value * self.ulen] * 2, dtype='U%s' % self.ulen)
+        test1 = np.array([self.ucs_value * self.ulen] * 2, dtype=f'U{self.ulen}')
         test2 = np.repeat(test1, 2)[::2]
         for ua in (test1, test2):
             ua2 = ua.astype(dtype=ua.dtype.newbyteorder())
@@ -317,11 +317,11 @@ def test_values_cast(self):
     def test_values_updowncast(self):
         # Check byteorder of when casting the array to a longer and shorter
         # string length for strided and contiguous arrays
-        test1 = np.array([self.ucs_value * self.ulen] * 2, dtype='U%s' % self.ulen)
+        test1 = np.array([self.ucs_value * self.ulen] * 2, dtype=f'U{self.ulen}')
         test2 = np.repeat(test1, 2)[::2]
         for ua in (test1, test2):
             # Cast to a longer type with zero padding
-            longer_type = np.dtype('U%s' % (self.ulen + 1)).newbyteorder()
+            longer_type = np.dtype(f'U{self.ulen + 1}').newbyteorder()
             ua2 = ua.astype(dtype=longer_type)
             assert_((ua == ua2).all())
             assert_(ua[-1] == ua2[-1])
diff --git a/numpy/_pytesttester.py b/numpy/_pytesttester.py
index 031e5883b662..482c6eddbca0 100644
--- a/numpy/_pytesttester.py
+++ b/numpy/_pytesttester.py
@@ -37,7 +37,7 @@
 def _show_numpy_info():
     import numpy as np
 
-    print("NumPy version %s" % np.__version__)
+    print(f"NumPy version {np.__version__}")
     info = np.lib._utils_impl._opt_info()
     print("NumPy CPU features: ", (info if info else 'nothing enabled'))
 
@@ -182,7 +182,7 @@ def __call__(self, label='fast', verbose=1, extra_argv=None,
             pytest_args += ["-m", label]
 
         if durations >= 0:
-            pytest_args += ["--durations=%s" % durations]
+            pytest_args += [f"--durations={durations}"]
 
         if tests is None:
             tests = [self.module_name]
diff --git a/numpy/ctypeslib/_ctypeslib.py b/numpy/ctypeslib/_ctypeslib.py
index adccc05320f4..bd5632702d8c 100644
--- a/numpy/ctypeslib/_ctypeslib.py
+++ b/numpy/ctypeslib/_ctypeslib.py
@@ -189,17 +189,16 @@ def from_param(cls, obj):
             raise TypeError("argument must be an ndarray")
         if cls._dtype_ is not None \
                and obj.dtype != cls._dtype_:
-            raise TypeError("array must have data type %s" % cls._dtype_)
+            raise TypeError(f"array must have data type {cls._dtype_}")
         if cls._ndim_ is not None \
                and obj.ndim != cls._ndim_:
             raise TypeError("array must have %d dimension(s)" % cls._ndim_)
         if cls._shape_ is not None \
                and obj.shape != cls._shape_:
-            raise TypeError("array must have shape %s" % str(cls._shape_))
+            raise TypeError(f"array must have shape {str(cls._shape_)}")
         if cls._flags_ is not None \
                and ((obj.flags.num & cls._flags_) != cls._flags_):
-            raise TypeError("array must have flags %s" %
-                    _flags_fromnum(cls._flags_))
+            raise TypeError(f"array must have flags {_flags_fromnum(cls._flags_)}")
         return obj.ctypes
 
 
@@ -344,7 +343,7 @@ def ndpointer(dtype=None, ndim=None, shape=None, flags=None):
     else:
         base = _ndptr
 
-    klass = type("ndpointer_%s" % name, (base,),
+    klass = type(f"ndpointer_{name}", (base,),
                  {"_dtype_": dtype,
                   "_shape_": shape,
                   "_ndim_": ndim,
diff --git a/numpy/f2py/__init__.py b/numpy/f2py/__init__.py
index 8bf1d637ec0c..a7ce9f2b080b 100644
--- a/numpy/f2py/__init__.py
+++ b/numpy/f2py/__init__.py
@@ -79,8 +79,7 @@ def __getattr__(attr):
         return test
 
     else:
-        raise AttributeError("module {!r} has no attribute "
-                              "{!r}".format(__name__, attr))
+        raise AttributeError(f"module {__name__!r} has no attribute {attr!r}")
 
 
 def __dir__():
diff --git a/numpy/f2py/_src_pyf.py b/numpy/f2py/_src_pyf.py
index d5a759f84411..f7e40bca4777 100644
--- a/numpy/f2py/_src_pyf.py
+++ b/numpy/f2py/_src_pyf.py
@@ -117,7 +117,7 @@ def unique_key(adict):
     done = False
     n = 1
     while not done:
-        newkey = '__l%s' % (n)
+        newkey = f'__l{n}'
         if newkey in allkeys:
             n += 1
         else:
@@ -135,7 +135,7 @@ def expand_sub(substr, names):
     def listrepl(mobj):
         thelist = conv(mobj.group(1).replace(r'\,', '@comma@'))
         if template_name_re.match(thelist):
-            return "<%s>" % (thelist)
+            return f"<{thelist}>"
         name = None
         for key in lnames.keys():    # see if list is already in dictionary
             if lnames[key] == thelist:
@@ -143,7 +143,7 @@ def listrepl(mobj):
         if name is None:      # this list is not in the dictionary yet
             name = unique_key(lnames)
             lnames[name] = thelist
-        return "<%s>" % name
+        return f"<{name}>"
 
     # convert all lists to named templates
     # new names are constructed as needed
@@ -156,7 +156,7 @@ def listrepl(mobj):
         if r not in rules:
             thelist = lnames.get(r, names.get(r, None))
             if thelist is None:
-                raise ValueError('No replicates found for <%s>' % (r))
+                raise ValueError(f'No replicates found for <{r}>')
             if r not in names and not thelist.startswith('_'):
                 names[r] = thelist
             rule = [i.replace('@comma@', ',') for i in thelist.split(',')]
diff --git a/numpy/f2py/auxfuncs.py b/numpy/f2py/auxfuncs.py
index e52840690e90..1adc2d6228c4 100644
--- a/numpy/f2py/auxfuncs.py
+++ b/numpy/f2py/auxfuncs.py
@@ -607,7 +607,7 @@ def __init__(self, mess):
         self.mess = mess
 
     def __call__(self, var):
-        mess = '\n\n  var = %s\n  Message: %s\n' % (var, self.mess)
+        mess = f'\n\n  var = {var}\n  Message: {self.mess}\n'
         raise F2PYError(mess)
 
 
@@ -616,7 +616,7 @@ def l_and(*f):
     for i in range(len(f)):
         l1 = '%s,f%d=f[%d]' % (l1, i, i)
         l2.append('f%d(v)' % (i))
-    return eval('%s:%s' % (l1, ' and '.join(l2)))
+    return eval(f"{l1}:{' and '.join(l2)}")
 
 
 def l_or(*f):
@@ -624,7 +624,7 @@ def l_or(*f):
     for i in range(len(f)):
         l1 = '%s,f%d=f[%d]' % (l1, i, i)
         l2.append('f%d(v)' % (i))
-    return eval('%s:%s' % (l1, ' or '.join(l2)))
+    return eval(f"{l1}:{' or '.join(l2)}")
 
 
 def l_not(f):
@@ -644,8 +644,7 @@ def getfortranname(rout):
         if name == '':
             raise KeyError
         if not name:
-            errmess('Failed to use fortranname from %s\n' %
-                    (rout['f2pyenhancements']))
+            errmess(f"Failed to use fortranname from {rout['f2pyenhancements']}\n")
             raise KeyError
     except KeyError:
         name = rout['name']
@@ -677,8 +676,7 @@ def getmultilineblock(rout, blockname, comment=1, counter=0):
             else:
                 r = r[:-3]
         else:
-            errmess("%s multiline block should end with `'''`: %s\n"
-                    % (blockname, repr(r)))
+            errmess(f"{blockname} multiline block should end with `'''`: {repr(r)}\n")
     return r
 
 
@@ -781,7 +779,7 @@ def getrestdoc(rout):
 
 def gentitle(name):
     ln = (80 - len(name) - 6) // 2
-    return '/*%s %s %s*/' % (ln * '*', name, ln * '*')
+    return f"/*{ln * '*'} {name} {ln * '*'}*/"
 
 
 def flatlist(lst):
@@ -809,9 +807,9 @@ def replace(str, d, defaultsep=''):
         else:
             sep = defaultsep
         if isinstance(d[k], list):
-            str = str.replace('#%s#' % (k), sep.join(flatlist(d[k])))
+            str = str.replace(f'#{k}#', sep.join(flatlist(d[k])))
         else:
-            str = str.replace('#%s#' % (k), d[k])
+            str = str.replace(f'#{k}#', d[k])
     return str
 
 
@@ -891,7 +889,7 @@ def applyrules(rules, d, var={}):
                             i = res.get('supertext', '')
                         ret[k].append(replace(i, d))
         else:
-            errmess('applyrules: ignoring rule %s.\n' % repr(rules[k]))
+            errmess(f'applyrules: ignoring rule {repr(rules[k])}.\n')
         if isinstance(ret[k], list):
             if len(ret[k]) == 1:
                 ret[k] = ret[k][0]
@@ -983,7 +981,7 @@ def process_f2cmap_dict(f2cmap_all, new_map, c2py_map, verbose = False):
                     )
                 f2cmap_all[k][k1] = v1
                 if verbose:
-                    outmess('\tMapping "%s(kind=%s)" to "%s"\n' % (k, k1, v1))
+                    outmess(f'\tMapping "{k}(kind={k1})" to "{v1}\"\n')
                 f2cmap_mapped.append(v1)
             else:
                 if verbose:
diff --git a/numpy/f2py/capi_maps.py b/numpy/f2py/capi_maps.py
index a340abc1b85c..2fa11bce3374 100644
--- a/numpy/f2py/capi_maps.py
+++ b/numpy/f2py/capi_maps.py
@@ -158,7 +158,7 @@ def load_f2cmap_file(f2cmap_file):
         f2cmap_all, f2cmap_mapped = process_f2cmap_dict(f2cmap_all, d, c2py_map, True)
         outmess('Successfully applied user defined f2cmap changes\n')
     except Exception as msg:
-        errmess('Failed to apply user defined f2cmap changes: %s. Skipping.\n' % (msg))
+        errmess(f'Failed to apply user defined f2cmap changes: {msg}. Skipping.\n')
 
 
 cformat_map = {'double': '%g',
@@ -197,7 +197,7 @@ def getctype(var):
         if a in var['vars']:
             return getctype(var['vars'][a])
         else:
-            errmess('getctype: function %s has no return value?!\n' % a)
+            errmess(f'getctype: function {a} has no return value?!\n')
     elif issubroutine(var):
         return ctype
     elif ischaracter_or_characterarray(var):
@@ -231,7 +231,7 @@ def getctype(var):
                                    typespec, var['kindselector']['kind'], os.getcwd()))
     else:
         if not isexternal(var):
-            errmess('getctype: No C-type found in "%s", assuming void.\n' % var)
+            errmess(f'getctype: No C-type found in "{var}", assuming void.\n')
     return ctype
 
 
@@ -259,10 +259,10 @@ def getstrlength(var):
         if a in var['vars']:
             return getstrlength(var['vars'][a])
         else:
-            errmess('getstrlength: function %s has no return value?!\n' % a)
+            errmess(f'getstrlength: function {a} has no return value?!\n')
     if not isstring(var):
         errmess(
-            'getstrlength: expected a signature of a string but got: %s\n' % (repr(var)))
+            f'getstrlength: expected a signature of a string but got: {repr(var)}\n')
     len = '1'
     if 'charselector' in var:
         a = var['charselector']
@@ -331,7 +331,7 @@ def getarrdims(a, var, verbose=0):
                     ret['cbsetdims'], i, 0)
             elif verbose:
                 errmess(
-                    'getarrdims: If in call-back function: array argument %s must have bounded dimensions: got %s\n' % (repr(a), repr(d)))
+                    f'getarrdims: If in call-back function: array argument {repr(a)} must have bounded dimensions: got {repr(d)}\n')
         if ret['cbsetdims']:
             ret['cbsetdims'] = ret['cbsetdims'][:-1]
 #         if not isintent_c(var):
@@ -349,7 +349,7 @@ def getpydocsign(a, var):
         if af in var['vars']:
             return getpydocsign(af, var['vars'][af])
         else:
-            errmess('getctype: function %s has no return value?!\n' % af)
+            errmess(f'getctype: function {af} has no return value?!\n')
         return '', ''
     sig, sigout = a, a
     opt = ''
@@ -368,22 +368,21 @@ def getpydocsign(a, var):
 
     if hasinitvalue(var):
         init, showinit = getinit(a, var)
-        init = ', optional\\n    Default: %s' % showinit
+        init = f', optional\\n    Default: {showinit}'
     if isscalar(var):
         if isintent_inout(var):
             sig = '%s : %s rank-0 array(%s,\'%s\')%s' % (a, opt, c2py_map[ctype],
                                                          c2pycode_map[ctype], init)
         else:
-            sig = '%s : %s %s%s' % (a, opt, c2py_map[ctype], init)
-        sigout = '%s : %s' % (out_a, c2py_map[ctype])
+            sig = f'{a} : {opt} {c2py_map[ctype]}{init}'
+        sigout = f'{out_a} : {c2py_map[ctype]}'
     elif isstring(var):
         if isintent_inout(var):
             sig = '%s : %s rank-0 array(string(len=%s),\'c\')%s' % (
                 a, opt, getstrlength(var), init)
         else:
-            sig = '%s : %s string(len=%s)%s' % (
-                a, opt, getstrlength(var), init)
-        sigout = '%s : string(len=%s)' % (out_a, getstrlength(var))
+            sig = f'{a} : {opt} string(len={getstrlength(var)}){init}'
+        sigout = f'{out_a} : string(len={getstrlength(var)})'
     elif isarray(var):
         dim = var['dimension']
         rank = repr(len(dim))
@@ -402,25 +401,23 @@ def getpydocsign(a, var):
         if a in lcb_map and lcb_map[a] in lcb2_map and 'argname' in lcb2_map[lcb_map[a]]:
             ua = lcb2_map[lcb_map[a]]['argname']
             if not ua == a:
-                ua = ' => %s' % ua
+                ua = f' => {ua}'
             else:
                 ua = ''
-        sig = '%s : call-back function%s' % (a, ua)
+        sig = f'{a} : call-back function{ua}'
         sigout = sig
     else:
         errmess(
-            'getpydocsign: Could not resolve docsignature for "%s".\n' % a)
+            f'getpydocsign: Could not resolve docsignature for "{a}".\n')
     return sig, sigout
 
 
 def getarrdocsign(a, var):
     ctype = getctype(var)
     if isstring(var) and (not isarray(var)):
-        sig = '%s : rank-0 array(string(len=%s),\'c\')' % (a,
-                                                           getstrlength(var))
+        sig = f'{a} : rank-0 array(string(len={getstrlength(var)}),\'c\')'
     elif isscalar(var):
-        sig = '%s : rank-0 array(%s,\'%s\')' % (a, c2py_map[ctype],
-                                                c2pycode_map[ctype],)
+        sig = f'{a} : rank-0 array({c2py_map[ctype]},\'{c2pycode_map[ctype]}\')'
     elif isarray(var):
         dim = var['dimension']
         rank = repr(len(dim))
@@ -452,17 +449,16 @@ def getinit(a, var):
                     ret['init.r'], ret['init.i'] = str(v.real), str(v.imag)
             except Exception:
                 raise ValueError(
-                    'getinit: expected complex number `(r,i)\' but got `%s\' as initial value of %r.' % (init, a))
+                    f'getinit: expected complex number `(r,i)\' but got `{init}\' as initial value of {a!r}.')
             if isarray(var):
-                init = '(capi_c.r=%s,capi_c.i=%s,capi_c)' % (
-                    ret['init.r'], ret['init.i'])
+                init = f"(capi_c.r={ret['init.r']},capi_c.i={ret['init.i']},capi_c)"
         elif isstring(var):
             if not init:
                 init, showinit = '""', "''"
             if init[0] == "'":
                 init = '"%s"' % (init[1:-1].replace('"', '\\"'))
             if init[0] == '"':
-                showinit = "'%s'" % (init[1:-1])
+                showinit = f"'{init[1:-1]}'"
     return init, showinit
 
 
@@ -499,7 +495,7 @@ def sign2map(a, var):
     intent_flags = []
     for f, s in isintent_dict.items():
         if f(var):
-            intent_flags.append('F2PY_%s' % s)
+            intent_flags.append(f'F2PY_{s}')
     if intent_flags:
         # TODO: Evaluate intent_flags here.
         ret['intent'] = '|'.join(intent_flags)
@@ -555,29 +551,27 @@ def sign2map(a, var):
             if il[i](var):
                 rl.append(il[i + 1])
         if isstring(var):
-            rl.append('slen(%s)=%s' % (a, ret['length']))
+            rl.append(f"slen({a})={ret['length']}")
         if isarray(var):
             ddim = ','.join(
-                map(lambda x, y: '%s|%s' % (x, y), var['dimension'], dim))
-            rl.append('dims(%s)' % ddim)
+                map(lambda x, y: f'{x}|{y}', var['dimension'], dim))
+            rl.append(f'dims({ddim})')
         if isexternal(var):
-            ret['vardebuginfo'] = 'debug-capi:%s=>%s:%s' % (
-                a, ret['cbname'], ','.join(rl))
+            ret['vardebuginfo'] = f"debug-capi:{a}=>{ret['cbname']}:{','.join(rl)}"
         else:
             ret['vardebuginfo'] = 'debug-capi:%s %s=%s:%s' % (
                 ret['ctype'], a, ret['showinit'], ','.join(rl))
         if isscalar(var):
             if ret['ctype'] in cformat_map:
-                ret['vardebugshowvalue'] = 'debug-capi:%s=%s' % (
-                    a, cformat_map[ret['ctype']])
+                ret['vardebugshowvalue'] = f"debug-capi:{a}={cformat_map[ret['ctype']]}"
         if isstring(var):
             ret['vardebugshowvalue'] = 'debug-capi:slen(%s)=%%d %s=\\"%%s\\"' % (
                 a, a)
         if isexternal(var):
-            ret['vardebugshowvalue'] = 'debug-capi:%s=%%p' % (a)
+            ret['vardebugshowvalue'] = f'debug-capi:{a}=%p'
     if ret['ctype'] in cformat_map:
-        ret['varshowvalue'] = '#name#:%s=%s' % (a, cformat_map[ret['ctype']])
-        ret['showvalueformat'] = '%s' % (cformat_map[ret['ctype']])
+        ret['varshowvalue'] = f"#name#:{a}={cformat_map[ret['ctype']]}"
+        ret['showvalueformat'] = f"{cformat_map[ret['ctype']]}"
     if isstring(var):
         ret['varshowvalue'] = '#name#:slen(%s)=%%d %s=\\"%%s\\"' % (a, a)
     ret['pydocsign'], ret['pydocsignout'] = getpydocsign(a, var)
@@ -600,7 +594,7 @@ def routsign2map(rout):
            'name_lower': name.lower(),
            'NAME': name.upper(),
            'begintitle': gentitle(name),
-           'endtitle': gentitle('end of %s' % name),
+           'endtitle': gentitle(f'end of {name}'),
            'fortranname': fname,
            'FORTRANNAME': fname.upper(),
            'callstatement': getcallstatement(rout) or '',
@@ -706,7 +700,7 @@ def cb_sign2map(a, var, index=None):
         ret['atype'] = c2capi_map[ret['ctype']]
         ret['elsize'] = get_elsize(var)
     if ret['ctype'] in cformat_map:
-        ret['showvalueformat'] = '%s' % (cformat_map[ret['ctype']])
+        ret['showvalueformat'] = f"{cformat_map[ret['ctype']]}"
     if isarray(var):
         ret = dictappend(ret, getarrdims(a, var))
     ret['pydocsign'], ret['pydocsignout'] = getpydocsign(a, var)
@@ -721,25 +715,21 @@ def cb_routsign2map(rout, um):
     name,begintitle,endtitle,argname
     ctype,rctype,maxnofargs,nofoptargs,returncptr
     """
-    ret = {'name': 'cb_%s_in_%s' % (rout['name'], um),
+    ret = {'name': f"cb_{rout['name']}_in_{um}",
            'returncptr': ''}
     if isintent_callback(rout):
         if '_' in rout['name']:
             F_FUNC = 'F_FUNC_US'
         else:
             F_FUNC = 'F_FUNC'
-        ret['callbackname'] = '%s(%s,%s)' \
-                              % (F_FUNC,
-                                 rout['name'].lower(),
-                                 rout['name'].upper(),
-                                 )
+        ret['callbackname'] = f"{F_FUNC}({rout['name'].lower()},{rout['name'].upper()})"
         ret['static'] = 'extern'
     else:
         ret['callbackname'] = ret['name']
         ret['static'] = 'static'
     ret['argname'] = rout['name']
     ret['begintitle'] = gentitle(ret['name'])
-    ret['endtitle'] = gentitle('end of %s' % ret['name'])
+    ret['endtitle'] = gentitle(f"end of {ret['name']}")
     ret['ctype'] = getctype(rout)
     ret['rctype'] = 'void'
     if ret['ctype'] == 'string':
@@ -756,7 +746,7 @@ def cb_routsign2map(rout, um):
         else:
             ret['returncptr'] = 'return_value='
     if ret['ctype'] in cformat_map:
-        ret['showvalueformat'] = '%s' % (cformat_map[ret['ctype']])
+        ret['showvalueformat'] = f"{cformat_map[ret['ctype']]}"
     if isstringfunction(rout):
         ret['strlength'] = getstrlength(rout)
     if isfunction(rout):
@@ -806,7 +796,7 @@ def common_sign2map(a, var):  # obsolete
         ret['atype'] = c2capi_map[ret['ctype']]
         ret['elsize'] = get_elsize(var)
     if ret['ctype'] in cformat_map:
-        ret['showvalueformat'] = '%s' % (cformat_map[ret['ctype']])
+        ret['showvalueformat'] = f"{cformat_map[ret['ctype']]}"
     if isarray(var):
         ret = dictappend(ret, getarrdims(a, var))
     elif isstring(var):
diff --git a/numpy/f2py/cb_rules.py b/numpy/f2py/cb_rules.py
index f2dc77298c88..6fa655d39069 100644
--- a/numpy/f2py/cb_rules.py
+++ b/numpy/f2py/cb_rules.py
@@ -513,14 +513,13 @@ def buildcallbacks(m):
                 if b:
                     buildcallback(b, m['name'])
                 else:
-                    errmess('warning: empty body for %s\n' % (m['name']))
+                    errmess(f"warning: empty body for {m['name']}\n")
 
 
 def buildcallback(rout, um):
     from . import capi_maps
 
-    outmess('    Constructing call-back function "cb_%s_in_%s"\n' %
-            (rout['name'], um))
+    outmess(f"    Constructing call-back function \"cb_{rout['name']}_in_{um}\"\n")
     args, depargs = getargs(rout)
     capi_maps.depargs = depargs
     var = rout['vars']
@@ -639,6 +638,6 @@ def buildcallback(rout, um):
                                       'latexdocstr': ar['latexdocstr'],
                                       'argname': rd['argname']
                                       }
-    outmess('      %s\n' % (ar['docstrshort']))
+    outmess(f"      {ar['docstrshort']}\n")
     return
 ################## Build call-back function #############
diff --git a/numpy/f2py/cfuncs.py b/numpy/f2py/cfuncs.py
index 0b2b40fb65c6..e5e1328b33f7 100644
--- a/numpy/f2py/cfuncs.py
+++ b/numpy/f2py/cfuncs.py
@@ -1439,14 +1439,14 @@ def errmess(s: str) -> None:
 def buildcfuncs():
     from .capi_maps import c2capi_map
     for k in c2capi_map.keys():
-        m = 'pyarr_from_p_%s1' % k
+        m = f'pyarr_from_p_{k}1'
         cppmacros[
-            m] = '#define %s(v) (PyArray_SimpleNewFromData(0,NULL,%s,(char *)v))' % (m, c2capi_map[k])
+            m] = f'#define {m}(v) (PyArray_SimpleNewFromData(0,NULL,{c2capi_map[k]},(char *)v))'
     k = 'string'
-    m = 'pyarr_from_p_%s1' % k
+    m = f'pyarr_from_p_{k}1'
     # NPY_CHAR compatibility, NPY_STRING with itemsize 1
     cppmacros[
-        m] = '#define %s(v,dims) (PyArray_New(&PyArray_Type, 1, dims, NPY_STRING, NULL, v, 1, NPY_ARRAY_CARRAY, NULL))' % (m)
+        m] = f'#define {m}(v,dims) (PyArray_New(&PyArray_Type, 1, dims, NPY_STRING, NULL, v, 1, NPY_ARRAY_CARRAY, NULL))'
 
 
 ############ Auxiliary functions for sorting needs ###################
@@ -1478,7 +1478,7 @@ def append_needs(need, flag=1):
         elif need in commonhooks:
             n = 'commonhooks'
         else:
-            errmess('append_needs: unknown need %s\n' % (repr(need)))
+            errmess(f'append_needs: unknown need {repr(need)}\n')
             return
         if need in outneeds[n]:
             return
@@ -1514,8 +1514,7 @@ def append_needs(need, flag=1):
             tmp[n].append(need)
             return tmp
     else:
-        errmess('append_needs: expected list or string but got :%s\n' %
-                (repr(need)))
+        errmess(f'append_needs: expected list or string but got :{repr(need)}\n')
 
 
 def get_needs():
diff --git a/numpy/f2py/common_rules.py b/numpy/f2py/common_rules.py
index 64347b737454..4c8cef7ad832 100644
--- a/numpy/f2py/common_rules.py
+++ b/numpy/f2py/common_rules.py
@@ -45,19 +45,19 @@ def buildhooks(m):
     fwrap = ['']
 
     def fadd(line, s=fwrap):
-        s[0] = '%s\n      %s' % (s[0], line)
+        s[0] = f'{s[0]}\n      {line}'
     chooks = ['']
 
     def cadd(line, s=chooks):
-        s[0] = '%s\n%s' % (s[0], line)
+        s[0] = f'{s[0]}\n{line}'
     ihooks = ['']
 
     def iadd(line, s=ihooks):
-        s[0] = '%s\n%s' % (s[0], line)
+        s[0] = f'{s[0]}\n{line}'
     doc = ['']
 
     def dadd(line, s=doc):
-        s[0] = '%s\n%s' % (s[0], line)
+        s[0] = f'{s[0]}\n{line}'
     for (name, vnames, vars) in findcommonblocks(m):
         lower_name = name.lower()
         hnames, inames = [], []
@@ -72,17 +72,17 @@ def dadd(line, s=doc):
         else:
             outmess('\t\tConstructing COMMON block support for "%s"...\n\t\t  %s\n' % (
                 name, ','.join(inames)))
-        fadd('subroutine f2pyinit%s(setupfunc)' % name)
+        fadd(f'subroutine f2pyinit{name}(setupfunc)')
         for usename in getuseblocks(m):
             fadd(f'use {usename}')
         fadd('external setupfunc')
         for n in vnames:
             fadd(func2subr.var2fixfortran(vars, n))
         if name == '_BLNK_':
-            fadd('common %s' % (','.join(vnames)))
+            fadd(f"common {','.join(vnames)}")
         else:
-            fadd('common /%s/ %s' % (name, ','.join(vnames)))
-        fadd('call setupfunc(%s)' % (','.join(inames)))
+            fadd(f"common /{name}/ {','.join(vnames)}")
+        fadd(f"call setupfunc({','.join(inames)})")
         fadd('end\n')
         cadd('static FortranDataDef f2py_%s_def[] = {' % (name))
         idims = []
@@ -92,7 +92,7 @@ def dadd(line, s=doc):
             at = capi_maps.c2capi_map[ct]
             dm = capi_maps.getarrdims(n, vars[n])
             if dm['dims']:
-                idims.append('(%s)' % (dm['dims']))
+                idims.append(f"({dm['dims']})")
             else:
                 idims.append('')
             dms = dm['dims'].strip()
@@ -106,7 +106,7 @@ def dadd(line, s=doc):
         cadd('static void f2py_setup_%s(%s) {' % (name, inames1_tps))
         cadd('\tint i_f2py=0;')
         for n in inames1:
-            cadd('\tf2py_%s_def[i_f2py++].data = %s;' % (name, n))
+            cadd(f'\tf2py_{name}_def[i_f2py++].data = {n};')
         cadd('}')
         if '_' in lower_name:
             F_FUNC = 'F_FUNC_US'
@@ -119,10 +119,9 @@ def dadd(line, s=doc):
         cadd('\t%s(f2pyinit%s,F2PYINIT%s)(f2py_setup_%s);'
              % (F_FUNC, lower_name, name.upper(), name))
         cadd('}\n')
-        iadd('\ttmp = PyFortranObject_New(f2py_%s_def,f2py_init_%s);' % (name, name))
+        iadd(f'\ttmp = PyFortranObject_New(f2py_{name}_def,f2py_init_{name});')
         iadd('\tif (tmp == NULL) return NULL;')
-        iadd('\tif (F2PyDict_SetItemString(d, \"%s\", tmp) == -1) return NULL;'
-             % name)
+        iadd(f'\tif (F2PyDict_SetItemString(d, "{name}", tmp) == -1) return NULL;')
         iadd('\tPy_DECREF(tmp);')
         tname = name.replace('_', '\\_')
         dadd('\\subsection{Common block \\texttt{%s}}\n' % (tname))
@@ -134,10 +133,10 @@ def dadd(line, s=doc):
                 note = vars[n]['note']
                 if isinstance(note, list):
                     note = '\n'.join(note)
-                dadd('--- %s' % (note))
+                dadd(f'--- {note}')
         dadd('\\end{description}')
         ret['docs'].append(
-            '"\t/%s/ %s\\n"' % (name, ','.join(map(lambda v, d: v + d, inames, idims))))
+            f"\"\t/{name}/ {','.join(map(lambda v, d: v + d, inames, idims))}\\n\"")
     ret['commonhooks'] = chooks
     ret['initcommonhooks'] = ihooks
     ret['latexdoc'] = doc[0]
diff --git a/numpy/f2py/crackfortran.py b/numpy/f2py/crackfortran.py
index 17941aaa1182..ea590722c835 100644
--- a/numpy/f2py/crackfortran.py
+++ b/numpy/f2py/crackfortran.py
@@ -266,8 +266,7 @@ def outmess(line, flag=1):
 
 def rmbadname1(name):
     if name in badnames:
-        errmess('rmbadname1: Replacing "%s" with "%s".\n' %
-                (name, badnames[name]))
+        errmess(f'rmbadname1: Replacing "{name}" with "{badnames[name]}".\n')
         return badnames[name]
     return name
 
@@ -278,8 +277,7 @@ def rmbadname(names):
 
 def undo_rmbadname1(name):
     if name in invbadnames:
-        errmess('undo_rmbadname1: Replacing "%s" with "%s".\n'
-                % (name, invbadnames[name]))
+        errmess(f'undo_rmbadname1: Replacing "{name}" with "{invbadnames[name]}".\n')
         return invbadnames[name]
     return name
 
@@ -521,7 +519,7 @@ def readfortrancode(ffile, dowithline=show, istop=1):
             cont = (r is not None)
         else:
             raise ValueError(
-                "Flag sourcecodeform must be either 'fix' or 'free': %s" % repr(sourcecodeform))
+                f"Flag sourcecodeform must be either 'fix' or 'free': {repr(sourcecodeform)}")
         filepositiontext = 'Line #%d in %s:"%s"\n\t' % (
             fin.filelineno() - 1, currentfilename, l1)
         m = includeline.match(origfinalline)
@@ -793,14 +791,13 @@ def crackline(line, reset=0):
                     m2 = re_1.match(m1.group('before'))
                     a = _simplifyargs(m1.group('args'))
                     if m2:
-                        line = 'callfun %s(%s) result (%s)' % (
-                            name, a, m2.group('result'))
+                        line = f"callfun {name}({a}) result ({m2.group('result')})"
                     else:
-                        line = 'callfun %s(%s)' % (name, a)
+                        line = f'callfun {name}({a})'
                     m = callfunpattern[0].match(line)
                     if not m:
                         outmess(
-                            'crackline: could not resolve function call for line=%s.\n' % repr(line))
+                            f'crackline: could not resolve function call for line={repr(line)}.\n')
                         return
                     analyzeline(m, 'callfun', line)
                     return
@@ -922,7 +919,7 @@ def appenddecl(decl, decl2, force=1):
             pass
         elif k in ['intent', 'check', 'dimension', 'optional',
                    'required', 'depend']:
-            errmess('appenddecl: "%s" not implemented.\n' % k)
+            errmess(f'appenddecl: "{k}" not implemented.\n')
         else:
             raise Exception('appenddecl: Unknown variable definition key: ' +
                             str(k))
@@ -1014,7 +1011,7 @@ def analyzeline(m, case, line):
        and not skipemptyends and groupcounter < 1:
         newname = os.path.basename(currentfilename).split('.')[0]
         outmess(
-            'analyzeline: no group yet. Creating program group with name "%s".\n' % newname)
+            f'analyzeline: no group yet. Creating program group with name "{newname}".\n')
         gotnextfile = 0
         groupcounter = groupcounter + 1
         groupname[groupcounter] = 'program'
@@ -1275,7 +1272,7 @@ def analyzeline(m, case, line):
                                 groupcache[groupcounter]['args'].append(k)
                         else:
                             errmess(
-                                'analyzeline: intent(callback) %s is ignored\n' % (k))
+                                f'analyzeline: intent(callback) {k} is ignored\n')
                     else:
                         errmess('analyzeline: intent(callback) %s is already'
                                 ' in argument list\n' % (k))
@@ -1310,7 +1307,7 @@ def analyzeline(m, case, line):
                 k, initexpr = [x.strip() for x in e.split('=')]
             except Exception:
                 outmess(
-                    'analyzeline: could not extract name,expr in parameter statement "%s" of "%s"\n' % (e, ll))
+                    f'analyzeline: could not extract name,expr in parameter statement "{e}" of "{ll}\"\n')
                 continue
             params = get_parameters(edecl)
             k = rmbadname1(k)
@@ -1360,12 +1357,12 @@ def analyzeline(m, case, line):
                     r'\s*(?P.*?)\s*(\(\s*(?P[a-z-, ]+)\s*\)\s*|)\Z', e, re.I)
                 if not m1:
                     outmess(
-                        'analyzeline: could not extract info of implicit statement part "%s"\n' % (e))
+                        f'analyzeline: could not extract info of implicit statement part "{e}\"\n')
                     continue
                 m2 = typespattern4implicit.match(m1.group('this'))
                 if not m2:
                     outmess(
-                        'analyzeline: could not extract types pattern of implicit statement part "%s"\n' % (e))
+                        f'analyzeline: could not extract types pattern of implicit statement part "{e}\"\n')
                     continue
                 typespec, selector, attr, edecl = cracktypespec0(
                     m2.group('this'), m2.group('after'))
@@ -1384,13 +1381,13 @@ def analyzeline(m, case, line):
                             begc, endc = [x.strip() for x in r.split('-')]
                         except Exception:
                             outmess(
-                                'analyzeline: expected "-" instead of "%s" in range list of implicit statement\n' % r)
+                                f'analyzeline: expected "-" instead of "{r}" in range list of implicit statement\n')
                             continue
                     else:
                         begc = endc = r.strip()
                     if not len(begc) == len(endc) == 1:
                         outmess(
-                            'analyzeline: expected "-" instead of "%s" in range list of implicit statement (2)\n' % r)
+                            f'analyzeline: expected "-" instead of "{r}" in range list of implicit statement (2)\n')
                         continue
                     for o in range(ord(begc), ord(endc) + 1):
                         impl[chr(o)] = decl
@@ -1435,11 +1432,11 @@ def analyzeline(m, case, line):
         for l in ll:
             l[0], l[1] = l[0].strip().removeprefix(','), l[1].strip()
             if l[0].startswith('('):
-                outmess('analyzeline: implied-DO list "%s" is not supported. Skipping.\n' % l[0])
+                outmess(f'analyzeline: implied-DO list "{l[0]}" is not supported. Skipping.\n')
                 continue
             for idx, v in enumerate(rmbadname([x.strip() for x in markoutercomma(l[0]).split('@,@')])):
                 if v.startswith('('):
-                    outmess('analyzeline: implied-DO list "%s" is not supported. Skipping.\n' % v)
+                    outmess(f'analyzeline: implied-DO list "{v}" is not supported. Skipping.\n')
                     # XXX: subsequent init expressions may get wrong values.
                     # Ignoring since data statements are irrelevant for
                     # wrapping.
@@ -1450,7 +1447,7 @@ def analyzeline(m, case, line):
                     # integer dimension(3) :: mytab
                     # common /mycom/ mytab
                     # Since in any case it is initialized in the Fortran code
-                    outmess('Comment line in declaration "%s" is not supported. Skipping.\n' % l[1])
+                    outmess(f'Comment line in declaration "{l[1]}" is not supported. Skipping.\n')
                     continue
                 vars.setdefault(v, {})
                 vtype = vars[v].get('typespec')
@@ -1478,7 +1475,7 @@ def analyzeline(m, case, line):
                     new_val = f"(/{', '.join(matches)}/)" if vdim else matches[idx]
                 current_val = vars[v].get('=')
                 if current_val and (current_val != new_val):
-                    outmess('analyzeline: changing init expression of "%s" ("%s") to "%s"\n' % (v, current_val, new_val))
+                    outmess(f'analyzeline: changing init expression of "{v}" ("{current_val}") to "{new_val}\"\n')
                 vars[v]['='] = new_val
                 last_name = v
         groupcache[groupcounter]['vars'] = vars
@@ -1531,7 +1528,7 @@ def analyzeline(m, case, line):
                                 'use').strip()
                         else:
                             outmess(
-                                'analyzeline: Not local=>use pattern found in %s\n' % repr(l))
+                                f'analyzeline: Not local=>use pattern found in {repr(l)}\n')
                     else:
                         rl[l] = l
                     groupcache[groupcounter]['use'][name]['map'] = rl
@@ -1702,7 +1699,7 @@ def updatevars(typespec, selector, attrspec, entitydecl):
         m = namepattern.match(e)
         if not m:
             outmess(
-                'updatevars: no name pattern found for entity=%s. Skipping.\n' % (repr(e)))
+                f'updatevars: no name pattern found for entity={repr(e)}. Skipping.\n')
             continue
         ename = rmbadname1(m.group('name'))
         edecl = {}
@@ -1810,7 +1807,7 @@ def updatevars(typespec, selector, attrspec, entitydecl):
                         edecl['='] = d1['init']
 
                 if 'array' in d1:
-                    dm = 'dimension(%s)' % d1['array']
+                    dm = f"dimension({d1['array']})"
                     if 'attrspec' not in edecl or (not edecl['attrspec']):
                         edecl['attrspec'] = [dm]
                     else:
@@ -1844,7 +1841,7 @@ def cracktypespec(typespec, selector):
             kindselect = kindselector.match(selector)
             if not kindselect:
                 outmess(
-                    'cracktypespec: no kindselector pattern found for %s\n' % (repr(selector)))
+                    f'cracktypespec: no kindselector pattern found for {repr(selector)}\n')
                 return
             kindselect = kindselect.groupdict()
             kindselect['*'] = kindselect['kind2']
@@ -1858,7 +1855,7 @@ def cracktypespec(typespec, selector):
             charselect = charselector.match(selector)
             if not charselect:
                 outmess(
-                    'cracktypespec: no charselector pattern found for %s\n' % (repr(selector)))
+                    f'cracktypespec: no charselector pattern found for {repr(selector)}\n')
                 return
             charselect = charselect.groupdict()
             charselect['*'] = charselect['charlen']
@@ -1889,8 +1886,7 @@ def cracktypespec(typespec, selector):
                 outmess('cracktypespec: no typename found in %s\n' %
                         (repr(typespec + selector)))
         else:
-            outmess('cracktypespec: no selector used for %s\n' %
-                    (repr(selector)))
+            outmess(f'cracktypespec: no selector used for {repr(selector)}\n')
     return kindselect, charselect, typename
 ######
 
@@ -1963,7 +1959,7 @@ def setmesstext(block):
     global filepositiontext
 
     try:
-        filepositiontext = 'In: %s:%s\n' % (block['from'], block['name'])
+        filepositiontext = f"In: {block['from']}:{block['name']}\n"
     except Exception:
         pass
 
@@ -1997,7 +1993,7 @@ def get_useparameters(block, param_map=None):
             continue
         # XXX: apply mapping
         if mapping:
-            errmess('get_useparameters: mapping for %s not impl.\n' % (mapping))
+            errmess(f'get_useparameters: mapping for {mapping} not impl.\n')
         for k, v in list(params.items()):
             if k in param_map:
                 outmess('get_useparameters: overriding parameter %s with'
@@ -2017,7 +2013,7 @@ def postcrack2(block, tab='', param_map=None):
                for g in block]
         return ret
     setmesstext(block)
-    outmess('%sBlock: %s\n' % (tab, block['name']), 0)
+    outmess(f"{tab}Block: {block['name']}\n", 0)
 
     if param_map is None:
         param_map = get_useparameters(block)
@@ -2064,7 +2060,7 @@ def postcrack(block, args=None, tab=''):
         raise Exception('postcrack: Expected block dictionary instead of ' +
                         str(block))
     if 'name' in block and not block['name'] == 'unknown_interface':
-        outmess('%sBlock: %s\n' % (tab, block['name']), 0)
+        outmess(f"{tab}Block: {block['name']}\n", 0)
     block = analyzeargs(block)
     block = analyzecommon(block)
     block['vars'] = analyzevars(block)
@@ -2187,14 +2183,14 @@ def analyzecommon(block):
                 if n in block['vars']:
                     if 'attrspec' in block['vars'][n]:
                         block['vars'][n]['attrspec'].append(
-                            'dimension(%s)' % (','.join(dims)))
+                            f"dimension({','.join(dims)})")
                     else:
                         block['vars'][n]['attrspec'] = [
-                            'dimension(%s)' % (','.join(dims))]
+                            f"dimension({','.join(dims)})"]
                 else:
                     if dims:
                         block['vars'][n] = {
-                            'attrspec': ['dimension(%s)' % (','.join(dims))]}
+                            'attrspec': [f"dimension({','.join(dims)})"]}
                     else:
                         block['vars'][n] = {}
                 if n not in commonvars:
@@ -2202,7 +2198,7 @@ def analyzecommon(block):
             else:
                 n = e
                 errmess(
-                    'analyzecommon: failed to extract "[()]" from "%s" in common /%s/.\n' % (e, k))
+                    f'analyzecommon: failed to extract "[()]" from "{e}" in common /{k}/.\n')
             comvars.append(n)
         block['common'][k] = comvars
     if 'commonvars' not in block:
@@ -2266,7 +2262,7 @@ def buildimplicitrules(block):
             implicitrules = None
             if verbose > 1:
                 outmess(
-                    'buildimplicitrules: no implicit rules for routine %s.\n' % repr(block['name']))
+                    f"buildimplicitrules: no implicit rules for routine {repr(block['name'])}.\n")
         else:
             for k in list(block['implicit'].keys()):
                 if block['implicit'][k].get('typespec') not in ['static', 'automatic']:
@@ -2281,7 +2277,7 @@ def myeval(e, g=None, l=None):
     r = eval(e, g, l)
     if type(r) in [int, float]:
         return r
-    raise ValueError('r=%r' % (r))
+    raise ValueError(f'r={r!r}')
 
 
 getlincoef_re_1 = re.compile(r'\A\b\w+\b\Z', re.I)
@@ -2328,27 +2324,23 @@ def getlincoef(e, xset):  # e = a*x+b ; x in xset
             try:
                 m1 = re_1.match(e)
                 while m1:
-                    ee = '%s(%s)%s' % (
-                        m1.group('before'), 0, m1.group('after'))
+                    ee = f"{m1.group('before')}({0}){m1.group('after')}"
                     m1 = re_1.match(ee)
                 b = myeval(ee, {}, {})
                 m1 = re_1.match(e)
                 while m1:
-                    ee = '%s(%s)%s' % (
-                        m1.group('before'), 1, m1.group('after'))
+                    ee = f"{m1.group('before')}({1}){m1.group('after')}"
                     m1 = re_1.match(ee)
                 a = myeval(ee, {}, {}) - b
                 m1 = re_1.match(e)
                 while m1:
-                    ee = '%s(%s)%s' % (
-                        m1.group('before'), 0.5, m1.group('after'))
+                    ee = f"{m1.group('before')}({0.5}){m1.group('after')}"
                     m1 = re_1.match(ee)
                 c = myeval(ee, {}, {})
                 # computing another point to be sure that expression is linear
                 m1 = re_1.match(e)
                 while m1:
-                    ee = '%s(%s)%s' % (
-                        m1.group('before'), 1.5, m1.group('after'))
+                    ee = f"{m1.group('before')}({1.5}){m1.group('after')}"
                     m1 = re_1.match(ee)
                 c2 = myeval(ee, {}, {})
                 if (a * 0.5 + b == c and a * 1.5 + b == c2):
@@ -2378,7 +2370,7 @@ def _get_depend_dict(name, vars, deps):
                 if w not in words:
                     words.append(w)
     else:
-        outmess('_get_depend_dict: no dependence info for %s\n' % (repr(name)))
+        outmess(f'_get_depend_dict: no dependence info for {repr(name)}\n')
         words = []
     deps[name] = words
     return words
@@ -2941,7 +2933,7 @@ def compute_deps(v, deps):
                             vars[n] = setattrspec(vars[n], 'recursive')
                     else:
                         outmess(
-                            'analyzevars: prefix (%s) were not used\n' % repr(block['prefix']))
+                            f"analyzevars: prefix ({repr(block['prefix'])}) were not used\n")
     if block['block'] not in ['module', 'pythonmodule', 'python module', 'block data']:
         if 'commonvars' in block:
             neededvars = copy.copy(block['args'] + block['commonvars'])
@@ -3209,13 +3201,13 @@ def determineexprtype(expr, vars, rules={}):
     if m:
         if 'name' in m.groupdict() and m.group('name'):
             outmess(
-                'determineexprtype: selected kind types not supported (%s)\n' % repr(expr))
+                f'determineexprtype: selected kind types not supported ({repr(expr)})\n')
         return {'typespec': 'integer'}
     m = determineexprtype_re_3.match(expr)
     if m:
         if 'name' in m.groupdict() and m.group('name'):
             outmess(
-                'determineexprtype: selected kind types not supported (%s)\n' % repr(expr))
+                f'determineexprtype: selected kind types not supported ({repr(expr)})\n')
         return {'typespec': 'real'}
     for op in ['+', '-', '*', '/']:
         for e in [x.strip() for x in markoutercomma(expr, comma=op).split('@' + op + '@')]:
@@ -3238,7 +3230,7 @@ def determineexprtype(expr, vars, rules={}):
         return {'typespec': 'character', 'charselector': {'*': '*'}}
     if not t:
         outmess(
-            'determineexprtype: could not determine expressions (%s) type.\n' % (repr(expr)))
+            f'determineexprtype: could not determine expressions ({repr(expr)}) type.\n')
     return t
 
 ######
@@ -3274,7 +3266,7 @@ def crack2fortrangen(block, tab='\n', as_interface=False):
             if not isintent_callback(vars[a]):
                 argsl.append(a)
         if block['block'] == 'function' or argsl:
-            args = '(%s)' % ','.join(argsl)
+            args = f"({','.join(argsl)})"
     f2pyenhancements = ''
     if 'f2pyenhancements' in block:
         for k in list(block['f2pyenhancements'].keys()):
@@ -3297,7 +3289,7 @@ def crack2fortrangen(block, tab='\n', as_interface=False):
         name = ''
     result = ''
     if 'result' in block:
-        result = ' result (%s)' % block['result']
+        result = f" result ({block['result']})"
         if block['result'] not in argsl:
             argsl.append(block['result'])
     body = crack2fortrangen(block['body'], tab + tabchar, as_interface=as_interface)
@@ -3305,12 +3297,11 @@ def crack2fortrangen(block, tab='\n', as_interface=False):
         block, block['vars'], argsl, tab + tabchar, as_interface=as_interface)
     mess = ''
     if 'from' in block and not as_interface:
-        mess = '! in %s' % block['from']
+        mess = f"! in {block['from']}"
     if 'entry' in block:
         entry_stmts = ''
         for k, i in list(block['entry'].items()):
-            entry_stmts = '%s%sentry %s(%s)' \
-                          % (entry_stmts, tab + tabchar, k, ','.join(i))
+            entry_stmts = f"{entry_stmts}{tab + tabchar}entry {k}({','.join(i)})"
         body = body + entry_stmts
     if blocktype == 'block data' and name == '_BLOCK_DATA_':
         name = ''
@@ -3323,30 +3314,30 @@ def common2fortran(common, tab=''):
     ret = ''
     for k in list(common.keys()):
         if k == '_BLNK_':
-            ret = '%s%scommon %s' % (ret, tab, ','.join(common[k]))
+            ret = f"{ret}{tab}common {','.join(common[k])}"
         else:
-            ret = '%s%scommon /%s/ %s' % (ret, tab, k, ','.join(common[k]))
+            ret = f"{ret}{tab}common /{k}/ {','.join(common[k])}"
     return ret
 
 
 def use2fortran(use, tab=''):
     ret = ''
     for m in list(use.keys()):
-        ret = '%s%suse %s,' % (ret, tab, m)
+        ret = f'{ret}{tab}use {m},'
         if use[m] == {}:
             if ret and ret[-1] == ',':
                 ret = ret[:-1]
             continue
         if 'only' in use[m] and use[m]['only']:
-            ret = '%s only:' % (ret)
+            ret = f'{ret} only:'
         if 'map' in use[m] and use[m]['map']:
             c = ' '
             for k in list(use[m]['map'].keys()):
                 if k == use[m]['map'][k]:
-                    ret = '%s%s%s' % (ret, c, k)
+                    ret = f'{ret}{c}{k}'
                     c = ','
                 else:
-                    ret = '%s%s%s=>%s' % (ret, c, k, use[m]['map'][k])
+                    ret = f"{ret}{c}{k}=>{use[m]['map'][k]}"
                     c = ','
         if ret and ret[-1] == ',':
             ret = ret[:-1]
@@ -3358,7 +3349,7 @@ def true_intent_list(var):
     ret = []
     for intent in lst:
         try:
-            f = globals()['isintent_%s' % intent]
+            f = globals()[f'isintent_{intent}']
         except KeyError:
             pass
         else:
@@ -3381,7 +3372,7 @@ def vars2fortran(block, vars, args, tab='', as_interface=False):
                     nout.append(a)
             else:
                 errmess(
-                    'vars2fortran: Confused?!: "%s" is not defined in vars.\n' % a)
+                    f'vars2fortran: Confused?!: "{a}" is not defined in vars.\n')
     if 'varnames' in block:
         nout.extend(block['varnames'])
     if not as_interface:
@@ -3393,13 +3384,13 @@ def vars2fortran(block, vars, args, tab='', as_interface=False):
             for d in vars[a]['depend']:
                 if d in vars and 'depend' in vars[d] and a in vars[d]['depend']:
                     errmess(
-                        'vars2fortran: Warning: cross-dependence between variables "%s" and "%s"\n' % (a, d))
+                        f'vars2fortran: Warning: cross-dependence between variables "{a}" and "{d}\"\n')
         if 'externals' in block and a in block['externals']:
             if isintent_callback(vars[a]):
-                ret = '%s%sintent(callback) %s' % (ret, tab, a)
-            ret = '%s%sexternal %s' % (ret, tab, a)
+                ret = f'{ret}{tab}intent(callback) {a}'
+            ret = f'{ret}{tab}external {a}'
             if isoptional(vars[a]):
-                ret = '%s%soptional %s' % (ret, tab, a)
+                ret = f'{ret}{tab}optional {a}'
             if a in vars and 'typespec' not in vars[a]:
                 continue
             cont = 1
@@ -3411,7 +3402,7 @@ def vars2fortran(block, vars, args, tab='', as_interface=False):
                 continue
         if a not in vars:
             show(vars)
-            outmess('vars2fortran: No definition for argument "%s".\n' % a)
+            outmess(f'vars2fortran: No definition for argument "{a}".\n')
             continue
         if a == block['name']:
             if block['block'] != 'function' or block.get('result'):
@@ -3423,14 +3414,14 @@ def vars2fortran(block, vars, args, tab='', as_interface=False):
         if 'typespec' not in vars[a]:
             if 'attrspec' in vars[a] and 'external' in vars[a]['attrspec']:
                 if a in args:
-                    ret = '%s%sexternal %s' % (ret, tab, a)
+                    ret = f'{ret}{tab}external {a}'
                 continue
             show(vars[a])
-            outmess('vars2fortran: No typespec for argument "%s".\n' % a)
+            outmess(f'vars2fortran: No typespec for argument "{a}".\n')
             continue
         vardef = vars[a]['typespec']
         if vardef == 'type' and 'typename' in vars[a]:
-            vardef = '%s(%s)' % (vardef, vars[a]['typename'])
+            vardef = f"{vardef}({vars[a]['typename']})"
         selector = {}
         if 'kindselector' in vars[a]:
             selector = vars[a]['kindselector']
@@ -3438,18 +3429,18 @@ def vars2fortran(block, vars, args, tab='', as_interface=False):
             selector = vars[a]['charselector']
         if '*' in selector:
             if selector['*'] in ['*', ':']:
-                vardef = '%s*(%s)' % (vardef, selector['*'])
+                vardef = f"{vardef}*({selector['*']})"
             else:
-                vardef = '%s*%s' % (vardef, selector['*'])
+                vardef = f"{vardef}*{selector['*']}"
         else:
             if 'len' in selector:
-                vardef = '%s(len=%s' % (vardef, selector['len'])
+                vardef = f"{vardef}(len={selector['len']}"
                 if 'kind' in selector:
-                    vardef = '%s,kind=%s)' % (vardef, selector['kind'])
+                    vardef = f"{vardef},kind={selector['kind']})"
                 else:
-                    vardef = '%s)' % (vardef)
+                    vardef = f'{vardef})'
             elif 'kind' in selector:
-                vardef = '%s(kind=%s)' % (vardef, selector['kind'])
+                vardef = f"{vardef}(kind={selector['kind']})"
         c = ' '
         if 'attrspec' in vars[a]:
             attr = [l for l in vars[a]['attrspec']
@@ -3462,36 +3453,34 @@ def vars2fortran(block, vars, args, tab='', as_interface=False):
                 # intent(out) to resolve the conflict.
                 attr.remove('intent(out)')
             if attr:
-                vardef = '%s, %s' % (vardef, ','.join(attr))
+                vardef = f"{vardef}, {','.join(attr)}"
                 c = ','
         if 'dimension' in vars[a]:
-            vardef = '%s%sdimension(%s)' % (
-                vardef, c, ','.join(vars[a]['dimension']))
+            vardef = f"{vardef}{c}dimension({','.join(vars[a]['dimension'])})"
             c = ','
         if 'intent' in vars[a]:
             lst = true_intent_list(vars[a])
             if lst:
-                vardef = '%s%sintent(%s)' % (vardef, c, ','.join(lst))
+                vardef = f"{vardef}{c}intent({','.join(lst)})"
             c = ','
         if 'check' in vars[a]:
-            vardef = '%s%scheck(%s)' % (vardef, c, ','.join(vars[a]['check']))
+            vardef = f"{vardef}{c}check({','.join(vars[a]['check'])})"
             c = ','
         if 'depend' in vars[a]:
-            vardef = '%s%sdepend(%s)' % (
-                vardef, c, ','.join(vars[a]['depend']))
+            vardef = f"{vardef}{c}depend({','.join(vars[a]['depend'])})"
             c = ','
         if '=' in vars[a]:
             v = vars[a]['=']
             if vars[a]['typespec'] in ['complex', 'double complex']:
                 try:
                     v = eval(v)
-                    v = '(%s,%s)' % (v.real, v.imag)
+                    v = f'({v.real},{v.imag})'
                 except Exception:
                     pass
-            vardef = '%s :: %s=%s' % (vardef, a, v)
+            vardef = f'{vardef} :: {a}={v}'
         else:
-            vardef = '%s :: %s' % (vardef, a)
-        ret = '%s%s%s' % (ret, tab, vardef)
+            vardef = f'{vardef} :: {a}'
+        ret = f'{ret}{tab}{vardef}'
     return ret
 ######
 
@@ -3710,7 +3699,7 @@ def fix_usage(varname, value):
         elif l == '-m':
             f3 = 1
         elif l[0] == '-':
-            errmess('Unknown option %s\n' % repr(l))
+            errmess(f'Unknown option {repr(l)}\n')
         elif f2:
             f2 = 0
             pyffilename = l
@@ -3736,7 +3725,7 @@ def fix_usage(varname, value):
 
     postlist = crackfortran(files)
     if pyffilename:
-        outmess('Writing fortran code to file %s\n' % repr(pyffilename), 0)
+        outmess(f'Writing fortran code to file {repr(pyffilename)}\n', 0)
         pyf = crack2fortran(postlist)
         with open(pyffilename, 'w') as f:
             f.write(pyf)
diff --git a/numpy/f2py/diagnose.py b/numpy/f2py/diagnose.py
index cbc8cf4e50bc..cbcaa9eb2931 100644
--- a/numpy/f2py/diagnose.py
+++ b/numpy/f2py/diagnose.py
@@ -5,7 +5,7 @@
 
 
 def run_command(cmd):
-    print('Running %r:' % (cmd))
+    print(f'Running {cmd!r}:')
     os.system(cmd)
     print('------')
 
@@ -14,9 +14,9 @@ def run():
     _path = os.getcwd()
     os.chdir(tempfile.gettempdir())
     print('------')
-    print('os.name=%r' % (os.name))
+    print(f'os.name={os.name!r}')
     print('------')
-    print('sys.platform=%r' % (sys.platform))
+    print(f'sys.platform={sys.platform!r}')
     print('------')
     print('sys.version:')
     print(sys.version)
@@ -24,7 +24,7 @@ def run():
     print('sys.prefix:')
     print(sys.prefix)
     print('------')
-    print('sys.path=%r' % (':'.join(sys.path)))
+    print(f"sys.path={':'.join(sys.path)!r}")
     print('------')
 
     try:
@@ -54,8 +54,7 @@ def run():
 
     if has_newnumpy:
         try:
-            print('Found new numpy version %r in %s' %
-                  (numpy.__version__, numpy.__file__))
+            print(f'Found new numpy version {numpy.__version__!r} in {numpy.__file__}')
         except Exception as msg:
             print('error:', msg)
             print('------')
diff --git a/numpy/f2py/f2py2e.py b/numpy/f2py/f2py2e.py
index c0f801e06c7f..b5bb18d2ebac 100644
--- a/numpy/f2py/f2py2e.py
+++ b/numpy/f2py/f2py2e.py
@@ -267,7 +267,7 @@ def scaninputline(inputline):
         elif l == '--skip-empty-wrappers':
             emptygen = False
         elif l[0] == '-':
-            errmess('Unknown option %s\n' % repr(l))
+            errmess(f'Unknown option {repr(l)}\n')
             sys.exit()
         elif f2:
             f2 = 0
@@ -303,13 +303,13 @@ def scaninputline(inputline):
         sys.exit()
     if not os.path.isdir(buildpath):
         if not verbose:
-            outmess('Creating build directory %s\n' % (buildpath))
+            outmess(f'Creating build directory {buildpath}\n')
         os.mkdir(buildpath)
     if signsfile:
         signsfile = os.path.join(buildpath, signsfile)
     if signsfile and os.path.isfile(signsfile) and 'h-overwrite' not in options:
         errmess(
-            'Signature file "%s" exists!!! Use --overwrite-signature to overwrite.\n' % (signsfile))
+            f'Signature file "{signsfile}" exists!!! Use --overwrite-signature to overwrite.\n')
         sys.exit()
 
     options['emptygen'] = emptygen
@@ -351,7 +351,7 @@ def callcrackfortran(files, options):
     crackfortran.dolowercase = options['do-lower']
     postlist = crackfortran.crackfortran(files)
     if 'signsfile' in options:
-        outmess('Saving signatures to file "%s"\n' % (options['signsfile']))
+        outmess(f"Saving signatures to file \"{options['signsfile']}\"\n")
         pyf = crackfortran.crack2fortran(postlist)
         if options['signsfile'][-6:] == 'stdout':
             sys.stdout.write(pyf)
@@ -360,13 +360,13 @@ def callcrackfortran(files, options):
                 f.write(pyf)
     if options["coutput"] is None:
         for mod in postlist:
-            mod["coutput"] = "%smodule.c" % mod["name"]
+            mod["coutput"] = f"{mod['name']}module.c"
     else:
         for mod in postlist:
             mod["coutput"] = options["coutput"]
     if options["f2py_wrapper_output"] is None:
         for mod in postlist:
-            mod["f2py_wrapper_output"] = "%s-f2pywrappers.f" % mod["name"]
+            mod["f2py_wrapper_output"] = f"{mod['name']}-f2pywrappers.f"
     else:
         for mod in postlist:
             mod["f2py_wrapper_output"] = options["f2py_wrapper_output"]
@@ -490,8 +490,7 @@ def run_main(comline_list):
         if options['verbose'] > 1:
             outmess(
                 'Stopping. Edit the signature file and then run f2py on the signature file: ')
-            outmess('%s %s\n' %
-                    (os.path.basename(sys.argv[0]), options['signsfile']))
+            outmess(f"{os.path.basename(sys.argv[0])} {options['signsfile']}\n")
         return
     for plist in postlist:
         if plist['block'] != 'python module':
@@ -676,7 +675,7 @@ def run_compile():
                         nv = vmap[ov]
                     except KeyError:
                         if ov not in vmap.values():
-                            print('Unknown vendor: "%s"' % (s[len(v):]))
+                            print(f'Unknown vendor: "{s[len(v):]}"')
                     nv = ov
                 i = flib_flags.index(s)
                 flib_flags[i] = '--fcompiler=' + nv
diff --git a/numpy/f2py/f90mod_rules.py b/numpy/f2py/f90mod_rules.py
index 6070bde844d3..305611fa0521 100644
--- a/numpy/f2py/f90mod_rules.py
+++ b/numpy/f2py/f90mod_rules.py
@@ -90,11 +90,11 @@ def buildhooks(pymod):
     fhooks = ['']
 
     def fadd(line, s=fhooks):
-        s[0] = '%s\n      %s' % (s[0], line)
+        s[0] = f'{s[0]}\n      {line}'
     doc = ['']
 
     def dadd(line, s=doc):
-        s[0] = '%s\n%s' % (s[0], line)
+        s[0] = f'{s[0]}\n{line}'
 
     usenames = getuseblocks(pymod)
     for m in findf90modules(pymod):
@@ -112,8 +112,7 @@ def dadd(line, s=doc):
             if (n not in notvars and isvariable(var)) and (not l_or(isintent_hide, isprivate)(var)):
                 onlyvars.append(n)
                 mfargs.append(n)
-        outmess('\t\tConstructing F90 module support for "%s"...\n' %
-                (m['name']))
+        outmess(f"\t\tConstructing F90 module support for \"{m['name']}\"...\n")
         if len(onlyvars) == 0 and len(notvars) == 1 and m['name'] in notvars:
             outmess(f"\t\t\tSkipping {m['name']} since there are no public vars/func in this module...\n")
             continue
@@ -123,15 +122,15 @@ def dadd(line, s=doc):
             outmess(f"\t\t\tSkipping {m['name']} since it is in 'use' and contains a common block...\n")
             continue
         if onlyvars:
-            outmess('\t\t  Variables: %s\n' % (' '.join(onlyvars)))
+            outmess(f"\t\t  Variables: {' '.join(onlyvars)}\n")
         chooks = ['']
 
         def cadd(line, s=chooks):
-            s[0] = '%s\n%s' % (s[0], line)
+            s[0] = f'{s[0]}\n{line}'
         ihooks = ['']
 
         def iadd(line, s=ihooks):
-            s[0] = '%s\n%s' % (s[0], line)
+            s[0] = f'{s[0]}\n{line}'
 
         vrd = capi_maps.modsign2map(m)
         cadd('static FortranDataDef f2py_%s_def[] = {' % (m['name']))
@@ -163,29 +162,28 @@ def iadd(line, s=ihooks):
                 note = var['note']
                 if isinstance(note, list):
                     note = '\n'.join(note)
-                dadd('--- %s' % (note))
+                dadd(f'--- {note}')
             if isallocatable(var):
-                fargs.append('f2py_%s_getdims_%s' % (m['name'], n))
+                fargs.append(f"f2py_{m['name']}_getdims_{n}")
                 efargs.append(fargs[-1])
                 sargs.append(
-                    'void (*%s)(int*,npy_intp*,void(*)(char*,npy_intp*),int*)' % (n))
+                    f'void (*{n})(int*,npy_intp*,void(*)(char*,npy_intp*),int*)')
                 sargsp.append('void (*)(int*,npy_intp*,void(*)(char*,npy_intp*),int*)')
-                iadd('\tf2py_%s_def[i_f2py++].func = %s;' % (m['name'], n))
-                fadd('subroutine %s(r,s,f2pysetdata,flag)' % (fargs[-1]))
-                fadd('use %s, only: d => %s\n' %
-                     (m['name'], undo_rmbadname1(n)))
+                iadd(f"\tf2py_{m['name']}_def[i_f2py++].func = {n};")
+                fadd(f'subroutine {fargs[-1]}(r,s,f2pysetdata,flag)')
+                fadd(f"use {m['name']}, only: d => {undo_rmbadname1(n)}\n")
                 fadd('integer flag\n')
                 fhooks[0] = fhooks[0] + fgetdims1
                 dms = range(1, int(dm['rank']) + 1)
                 fadd(' allocate(d(%s))\n' %
                      (','.join(['s(%s)' % i for i in dms])))
                 fhooks[0] = fhooks[0] + use_fgetdims2
-                fadd('end subroutine %s' % (fargs[-1]))
+                fadd(f'end subroutine {fargs[-1]}')
             else:
                 fargs.append(n)
-                sargs.append('char *%s' % (n))
+                sargs.append(f'char *{n}')
                 sargsp.append('char*')
-                iadd('\tf2py_%s_def[i_f2py++].data = %s;' % (m['name'], n))
+                iadd(f"\tf2py_{m['name']}_def[i_f2py++].data = {n};")
         if onlyvars:
             dadd('\\end{description}')
         if hasbody(m):
@@ -194,17 +192,17 @@ def iadd(line, s=ihooks):
                     outmess("f90mod_rules.buildhooks:"
                             f" skipping {b['block']} {b['name']}\n")
                     continue
-                modobjs.append('%s()' % (b['name']))
+                modobjs.append(f"{b['name']}()")
                 b['modulename'] = m['name']
                 api, wrap = rules.buildapi(b)
                 if isfunction(b):
                     fhooks[0] = fhooks[0] + wrap
-                    fargs.append('f2pywrap_%s_%s' % (m['name'], b['name']))
+                    fargs.append(f"f2pywrap_{m['name']}_{b['name']}")
                     ifargs.append(func2subr.createfuncwrapper(b, signature=1))
                 else:
                     if wrap:
                         fhooks[0] = fhooks[0] + wrap
-                        fargs.append('f2pywrap_%s_%s' % (m['name'], b['name']))
+                        fargs.append(f"f2pywrap_{m['name']}_{b['name']}")
                         ifargs.append(
                             func2subr.createsubrwrapper(b, signature=1))
                     else:
@@ -219,10 +217,9 @@ def iadd(line, s=ihooks):
                       'f2py_rout_#modulename#_%s_%s,'
                       'doc_f2py_rout_#modulename#_%s_%s},')
                      % (b['name'], m['name'], b['name'], m['name'], b['name']))
-                sargs.append('char *%s' % (b['name']))
+                sargs.append(f"char *{b['name']}")
                 sargsp.append('char *')
-                iadd('\tf2py_%s_def[i_f2py++].data = %s;' %
-                     (m['name'], b['name']))
+                iadd(f"\tf2py_{m['name']}_def[i_f2py++].data = {b['name']};")
         cadd('\t{NULL}\n};\n')
         iadd('}')
         ihooks[0] = 'static void f2py_setup_%s(%s) {\n\tint i_f2py=0;%s' % (
@@ -241,26 +238,25 @@ def iadd(line, s=ihooks):
         ret['initf90modhooks'] = ['\tPyDict_SetItemString(d, "%s", PyFortranObject_New(f2py_%s_def,f2py_init_%s));' % (
             m['name'], m['name'], m['name'])] + ret['initf90modhooks']
         fadd('')
-        fadd('subroutine f2pyinit%s(f2pysetupfunc)' % (m['name']))
+        fadd(f"subroutine f2pyinit{m['name']}(f2pysetupfunc)")
         if mfargs:
             for a in undo_rmbadname(mfargs):
-                fadd('use %s, only : %s' % (m['name'], a))
+                fadd(f"use {m['name']}, only : {a}")
         if ifargs:
             fadd(' '.join(['interface'] + ifargs))
             fadd('end interface')
         fadd('external f2pysetupfunc')
         if efargs:
             for a in undo_rmbadname(efargs):
-                fadd('external %s' % (a))
-        fadd('call f2pysetupfunc(%s)' % (','.join(undo_rmbadname(fargs))))
-        fadd('end subroutine f2pyinit%s\n' % (m['name']))
+                fadd(f'external {a}')
+        fadd(f"call f2pysetupfunc({','.join(undo_rmbadname(fargs))})")
+        fadd(f"end subroutine f2pyinit{m['name']}\n")
 
         dadd('\n'.join(ret['latexdoc']).replace(
             r'\subsection{', r'\subsubsection{'))
 
         ret['latexdoc'] = []
-        ret['docs'].append('"\t%s --- %s"' % (m['name'],
-                                              ','.join(undo_rmbadname(modobjs))))
+        ret['docs'].append(f"\"\t{m['name']} --- {','.join(undo_rmbadname(modobjs))}\"")
 
     ret['routine_defs'] = ''
     ret['doc'] = []
diff --git a/numpy/f2py/func2subr.py b/numpy/f2py/func2subr.py
index 2d972180ee82..93598259991b 100644
--- a/numpy/f2py/func2subr.py
+++ b/numpy/f2py/func2subr.py
@@ -24,15 +24,15 @@ def var2fixfortran(vars, a, fa=None, f90mode=None):
         fa = a
     if a not in vars:
         show(vars)
-        outmess('var2fixfortran: No definition for argument "%s".\n' % a)
+        outmess(f'var2fixfortran: No definition for argument "{a}".\n')
         return ''
     if 'typespec' not in vars[a]:
         show(vars[a])
-        outmess('var2fixfortran: No typespec for argument "%s".\n' % a)
+        outmess(f'var2fixfortran: No typespec for argument "{a}".\n')
         return ''
     vardef = vars[a]['typespec']
     if vardef == 'type' and 'typename' in vars[a]:
-        vardef = '%s(%s)' % (vardef, vars[a]['typename'])
+        vardef = f"{vardef}({vars[a]['typename']})"
     selector = {}
     lk = ''
     if 'kindselector' in vars[a]:
@@ -44,27 +44,27 @@ def var2fixfortran(vars, a, fa=None, f90mode=None):
     if '*' in selector:
         if f90mode:
             if selector['*'] in ['*', ':', '(*)']:
-                vardef = '%s(len=*)' % (vardef)
+                vardef = f'{vardef}(len=*)'
             else:
-                vardef = '%s(%s=%s)' % (vardef, lk, selector['*'])
+                vardef = f"{vardef}({lk}={selector['*']})"
         else:
             if selector['*'] in ['*', ':']:
-                vardef = '%s*(%s)' % (vardef, selector['*'])
+                vardef = f"{vardef}*({selector['*']})"
             else:
-                vardef = '%s*%s' % (vardef, selector['*'])
+                vardef = f"{vardef}*{selector['*']}"
     else:
         if 'len' in selector:
-            vardef = '%s(len=%s' % (vardef, selector['len'])
+            vardef = f"{vardef}(len={selector['len']}"
             if 'kind' in selector:
-                vardef = '%s,kind=%s)' % (vardef, selector['kind'])
+                vardef = f"{vardef},kind={selector['kind']})"
             else:
-                vardef = '%s)' % (vardef)
+                vardef = f'{vardef})'
         elif 'kind' in selector:
-            vardef = '%s(kind=%s)' % (vardef, selector['kind'])
+            vardef = f"{vardef}(kind={selector['kind']})"
 
-    vardef = '%s %s' % (vardef, fa)
+    vardef = f'{vardef} {fa}'
     if 'dimension' in vars[a]:
-        vardef = '%s(%s)' % (vardef, ','.join(vars[a]['dimension']))
+        vardef = f"{vardef}({','.join(vars[a]['dimension'])})"
     return vardef
 
 def useiso_c_binding(rout):
@@ -84,9 +84,9 @@ def createfuncwrapper(rout, signature=0):
         v = rout['vars'][a]
         for i, d in enumerate(v.get('dimension', [])):
             if d == ':':
-                dn = 'f2py_%s_d%s' % (a, i)
+                dn = f'f2py_{a}_d{i}'
                 dv = {'typespec': 'integer', 'intent': ['hide']}
-                dv['='] = 'shape(%s, %s)' % (a, i)
+                dv['='] = f'shape({a}, {i})'
                 extra_args.append(dn)
                 vars[dn] = dv
                 v['dimension'][i] = dn
@@ -96,11 +96,11 @@ def createfuncwrapper(rout, signature=0):
     ret = ['']
 
     def add(line, ret=ret):
-        ret[0] = '%s\n      %s' % (ret[0], line)
+        ret[0] = f'{ret[0]}\n      {line}'
     name = rout['name']
     fortranname = getfortranname(rout)
     f90mode = ismoduleroutine(rout)
-    newname = '%sf2pywrap' % (name)
+    newname = f'{name}f2pywrap'
 
     if newname not in vars:
         vars[newname] = vars[name]
@@ -130,18 +130,17 @@ def add(line, ret=ret):
         sargs = sargs.replace(f"{name}, ", '')
         args = [arg for arg in args if arg != name]
         rout['args'] = args
-        add('subroutine f2pywrap_%s_%s (%s)' %
-            (rout['modulename'], name, sargs))
+        add(f"subroutine f2pywrap_{rout['modulename']}_{name} ({sargs})")
         if not signature:
-            add('use %s, only : %s' % (rout['modulename'], fortranname))
+            add(f"use {rout['modulename']}, only : {fortranname}")
         if useisoc:
             add('use iso_c_binding')
     else:
-        add('subroutine f2pywrap%s (%s)' % (name, sargs))
+        add(f'subroutine f2pywrap{name} ({sargs})')
         if useisoc:
             add('use iso_c_binding')
         if not need_interface:
-            add('external %s' % (fortranname))
+            add(f'external {fortranname}')
             rl = l_tmpl.replace('@@@NAME@@@', '') + ' ' + fortranname
 
     if need_interface:
@@ -153,7 +152,7 @@ def add(line, ret=ret):
     dumped_args = []
     for a in args:
         if isexternal(vars[a]):
-            add('external %s' % (a))
+            add(f'external {a}')
             dumped_args.append(a)
     for a in args:
         if a in dumped_args:
@@ -189,11 +188,11 @@ def add(line, ret=ret):
 
     if not signature:
         if islogicalfunction(rout):
-            add('%s = .not.(.not.%s(%s))' % (newname, fortranname, sargs))
+            add(f'{newname} = .not.(.not.{fortranname}({sargs}))')
         else:
-            add('%s = %s(%s)' % (newname, fortranname, sargs))
+            add(f'{newname} = {fortranname}({sargs})')
     if f90mode:
-        add('end subroutine f2pywrap_%s_%s' % (rout['modulename'], name))
+        add(f"end subroutine f2pywrap_{rout['modulename']}_{name}")
     else:
         add('end')
     return ret[0]
@@ -208,9 +207,9 @@ def createsubrwrapper(rout, signature=0):
         v = rout['vars'][a]
         for i, d in enumerate(v.get('dimension', [])):
             if d == ':':
-                dn = 'f2py_%s_d%s' % (a, i)
+                dn = f'f2py_{a}_d{i}'
                 dv = {'typespec': 'integer', 'intent': ['hide']}
-                dv['='] = 'shape(%s, %s)' % (a, i)
+                dv['='] = f'shape({a}, {i})'
                 extra_args.append(dn)
                 vars[dn] = dv
                 v['dimension'][i] = dn
@@ -220,7 +219,7 @@ def createsubrwrapper(rout, signature=0):
     ret = ['']
 
     def add(line, ret=ret):
-        ret[0] = '%s\n      %s' % (ret[0], line)
+        ret[0] = f'{ret[0]}\n      {line}'
     name = rout['name']
     fortranname = getfortranname(rout)
     f90mode = ismoduleroutine(rout)
@@ -230,18 +229,17 @@ def add(line, ret=ret):
     useisoc = useiso_c_binding(rout)
     sargs = ', '.join(args)
     if f90mode:
-        add('subroutine f2pywrap_%s_%s (%s)' %
-            (rout['modulename'], name, sargs))
+        add(f"subroutine f2pywrap_{rout['modulename']}_{name} ({sargs})")
         if useisoc:
             add('use iso_c_binding')
         if not signature:
-            add('use %s, only : %s' % (rout['modulename'], fortranname))
+            add(f"use {rout['modulename']}, only : {fortranname}")
     else:
-        add('subroutine f2pywrap%s (%s)' % (name, sargs))
+        add(f'subroutine f2pywrap{name} ({sargs})')
         if useisoc:
             add('use iso_c_binding')
         if not need_interface:
-            add('external %s' % (fortranname))
+            add(f'external {fortranname}')
 
     if need_interface:
         for line in rout['saved_interface'].split('\n'):
@@ -251,7 +249,7 @@ def add(line, ret=ret):
     dumped_args = []
     for a in args:
         if isexternal(vars[a]):
-            add('external %s' % (a))
+            add(f'external {a}')
             dumped_args.append(a)
     for a in args:
         if a in dumped_args:
@@ -279,9 +277,9 @@ def add(line, ret=ret):
     sargs = ', '.join([a for a in args if a not in extra_args])
 
     if not signature:
-        add('call %s(%s)' % (fortranname, sargs))
+        add(f'call {fortranname}({sargs})')
     if f90mode:
-        add('end subroutine f2pywrap_%s_%s' % (rout['modulename'], name))
+        add(f"end subroutine f2pywrap_{rout['modulename']}_{name}")
     else:
         add('end')
     return ret[0]
@@ -310,7 +308,7 @@ def assubr(rout):
                     flag = 0
                     break
             if flag:
-                fvar['intent'].append('out=%s' % (rname))
+                fvar['intent'].append(f'out={rname}')
         rout['args'][:] = [fname] + rout['args']
         return rout, createfuncwrapper(rout)
     if issubroutine_wrap(rout):
diff --git a/numpy/f2py/rules.py b/numpy/f2py/rules.py
index 6ce71608143f..9d967a080bf8 100644
--- a/numpy/f2py/rules.py
+++ b/numpy/f2py/rules.py
@@ -1251,7 +1251,7 @@ def buildmodule(m, um):
     """
     Return
     """
-    outmess('    Building module "%s"...\n' % (m['name']))
+    outmess(f"    Building module \"{m['name']}\"...\n")
     ret = {}
     mod_rules = defmod_rules[:]
     vrd = capi_maps.modsign2map(m)
@@ -1271,7 +1271,7 @@ def buildmodule(m, um):
 
         if not nb:
             print(
-                'buildmodule: Could not find the body of interfaced routine "%s". Skipping.\n' % (n), file=sys.stderr)
+                f'buildmodule: Could not find the body of interfaced routine "{n}". Skipping.\n', file=sys.stderr)
             continue
         nb_list = [nb]
         if 'entry' in nb:
@@ -1358,7 +1358,7 @@ def buildmodule(m, um):
             elif k in cfuncs.commonhooks:
                 c = cfuncs.commonhooks[k]
             else:
-                errmess('buildmodule: unknown need %s.\n' % (repr(k)))
+                errmess(f'buildmodule: unknown need {repr(k)}.\n')
                 continue
             code[n].append(c)
     mod_rules.append(code)
@@ -1372,7 +1372,7 @@ def buildmodule(m, um):
     ret['csrc'] = fn
     with open(fn, 'w') as f:
         f.write(ar['modulebody'].replace('\t', 2 * ' '))
-    outmess('    Wrote C/API module "%s" to file "%s"\n' % (m['name'], fn))
+    outmess(f"    Wrote C/API module \"{m['name']}\" to file \"{fn}\"\n")
 
     if options['dorestdoc']:
         fn = os.path.join(
@@ -1388,7 +1388,7 @@ def buildmodule(m, um):
         ret['ltx'] = fn
         with open(fn, 'w') as f:
             f.write(
-                '%% This file is auto-generated with f2py (version:%s)\n' % (f2py_version))
+                f'% This file is auto-generated with f2py (version:{f2py_version})\n')
             if 'shortlatex' not in options:
                 f.write(
                     '\\documentclass{article}\n\\usepackage{a4wide}\n\\begin{document}\n\\tableofcontents\n\n')
@@ -1403,7 +1403,7 @@ def buildmodule(m, um):
         with open(wn, 'w') as f:
             f.write('C     -*- fortran -*-\n')
             f.write(
-                'C     This file is autogenerated with f2py (version:%s)\n' % (f2py_version))
+                f'C     This file is autogenerated with f2py (version:{f2py_version})\n')
             f.write(
                 'C     It contains Fortran 77 wrappers to fortran functions.\n')
             lines = []
@@ -1420,15 +1420,15 @@ def buildmodule(m, um):
                     lines.append(l + '\n')
             lines = ''.join(lines).replace('\n     &\n', '\n')
             f.write(lines)
-        outmess('    Fortran 77 wrappers are saved to "%s"\n' % (wn))
+        outmess(f'    Fortran 77 wrappers are saved to "{wn}\"\n')
     if funcwrappers2:
         wn = os.path.join(
-            options['buildpath'], '%s-f2pywrappers2.f90' % (vrd['modulename']))
+            options['buildpath'], f"{vrd['modulename']}-f2pywrappers2.f90")
         ret['fsrc'] = wn
         with open(wn, 'w') as f:
             f.write('!     -*- f90 -*-\n')
             f.write(
-                '!     This file is autogenerated with f2py (version:%s)\n' % (f2py_version))
+                f'!     This file is autogenerated with f2py (version:{f2py_version})\n')
             f.write(
                 '!     It contains Fortran 90 wrappers to fortran functions.\n')
             lines = []
@@ -1447,7 +1447,7 @@ def buildmodule(m, um):
                     lines.append(l + '\n')
             lines = ''.join(lines).replace('\n     &\n', '\n')
             f.write(lines)
-        outmess('    Fortran 90 wrappers are saved to "%s"\n' % (wn))
+        outmess(f'    Fortran 90 wrappers are saved to "{wn}\"\n')
     return ret
 
 ################## Build C/API function #############
@@ -1467,7 +1467,7 @@ def buildapi(rout):
         outmess('            Constructing wrapper function "%s.%s"...\n' %
                 (rout['modulename'], rout['name']))
     else:
-        outmess('        Constructing wrapper function "%s"...\n' % (rout['name']))
+        outmess(f"        Constructing wrapper function \"{rout['name']}\"...\n")
     # Routine
     vrd = capi_maps.routsign2map(rout)
     rd = dictappend({}, vrd)
@@ -1569,9 +1569,9 @@ def buildapi(rout):
 
     ar = applyrules(routine_rules, rd)
     if ismoduleroutine(rout):
-        outmess('              %s\n' % (ar['docshort']))
+        outmess(f"              {ar['docshort']}\n")
     else:
-        outmess('          %s\n' % (ar['docshort']))
+        outmess(f"          {ar['docshort']}\n")
     return ar, wrap
 
 
diff --git a/numpy/f2py/tests/test_array_from_pyobj.py b/numpy/f2py/tests/test_array_from_pyobj.py
index e317cbabe382..e0e366fb94a2 100644
--- a/numpy/f2py/tests/test_array_from_pyobj.py
+++ b/numpy/f2py/tests/test_array_from_pyobj.py
@@ -82,10 +82,10 @@ def __getattr__(self, name):
         return self.__class__(self.intent_list + [name])
 
     def __str__(self):
-        return "intent(%s)" % (",".join(self.intent_list))
+        return f"intent({','.join(self.intent_list)})"
 
     def __repr__(self):
-        return "Intent(%r)" % (self.intent_list)
+        return f"Intent({self.intent_list!r})"
 
     def is_intent(self, *names):
         return all(name in self.intent_list for name in names)
diff --git a/numpy/f2py/tests/util.py b/numpy/f2py/tests/util.py
index 30d8772fd908..dbb7416b7765 100644
--- a/numpy/f2py/tests/util.py
+++ b/numpy/f2py/tests/util.py
@@ -212,7 +212,7 @@ def build_module(source_files, options=[], skip=[], only=[], module_name=None):
     f2py_sources = []
     for fn in source_files:
         if not os.path.isfile(fn):
-            raise RuntimeError("%s is not a file" % fn)
+            raise RuntimeError(f"{fn} is not a file")
         dst = os.path.join(d, os.path.basename(fn))
         shutil.copyfile(fn, dst)
         dst_sources.append(dst)
@@ -247,8 +247,7 @@ def build_module(source_files, options=[], skip=[], only=[], module_name=None):
                              stderr=subprocess.STDOUT)
         out, err = p.communicate()
         if p.returncode != 0:
-            raise RuntimeError("Running f2py failed: %s\n%s" %
-                               (cmd[4:], asunicode(out)))
+            raise RuntimeError(f"Running f2py failed: {cmd[4:]}\n{asunicode(out)}")
     finally:
         os.chdir(cwd)
 
diff --git a/numpy/f2py/use_rules.py b/numpy/f2py/use_rules.py
index 372dc5340fef..1a53b871a173 100644
--- a/numpy/f2py/use_rules.py
+++ b/numpy/f2py/use_rules.py
@@ -45,7 +45,7 @@
 def buildusevars(m, r):
     ret = {}
     outmess(
-        '\t\tBuilding use variable hooks for module "%s" (feature only for F90/F95)...\n' % (m['name']))
+        f"\t\tBuilding use variable hooks for module \"{m['name']}\" (feature only for F90/F95)...\n")
     varsmap = {}
     revmap = {}
     if 'map' in r:
@@ -62,11 +62,10 @@ def buildusevars(m, r):
                 if revmap[r['map'][v]] == v:
                     varsmap[v] = r['map'][v]
                 else:
-                    outmess('\t\t\tIgnoring map "%s=>%s". See above.\n' %
-                            (v, r['map'][v]))
+                    outmess(f"\t\t\tIgnoring map \"{v}=>{r['map'][v]}\". See above.\n")
             else:
                 outmess(
-                    '\t\t\tNo definition for variable "%s=>%s". Skipping.\n' % (v, r['map'][v]))
+                    f"\t\t\tNo definition for variable \"{v}=>{r['map'][v]}\". Skipping.\n")
     else:
         for v in m['vars'].keys():
             varsmap[v] = revmap.get(v, v)
@@ -85,9 +84,9 @@ def buildusevar(name, realname, vars, usemodulename):
            'usemodulename': usemodulename,
            'USEMODULENAME': usemodulename.upper(),
            'texname': name.replace('_', '\\_'),
-           'begintitle': gentitle('%s=>%s' % (name, realname)),
-           'endtitle': gentitle('end of %s=>%s' % (name, realname)),
-           'apiname': '#modulename#_use_%s_from_%s' % (realname, usemodulename)
+           'begintitle': gentitle(f'{name}=>{realname}'),
+           'endtitle': gentitle(f'end of {name}=>{realname}'),
+           'apiname': f'#modulename#_use_{realname}_from_{usemodulename}'
            }
     nummap = {0: 'Ro', 1: 'Ri', 2: 'Rii', 3: 'Riii', 4: 'Riv',
               5: 'Rv', 6: 'Rvi', 7: 'Rvii', 8: 'Rviii', 9: 'Rix'}
diff --git a/numpy/lib/__init__.py b/numpy/lib/__init__.py
index e3ba0cf9044c..82297f488264 100644
--- a/numpy/lib/__init__.py
+++ b/numpy/lib/__init__.py
@@ -91,5 +91,4 @@ def __getattr__(attr):
             name=None
         )
     else:
-        raise AttributeError("module {!r} has no attribute "
-                             "{!r}".format(__name__, attr))
+        raise AttributeError(f"module {__name__!r} has no attribute {attr!r}")
diff --git a/numpy/lib/_datasource.py b/numpy/lib/_datasource.py
index 37c2a73c4644..1babc722b036 100644
--- a/numpy/lib/_datasource.py
+++ b/numpy/lib/_datasource.py
@@ -57,7 +57,7 @@ def _check_mode(mode, encoding, newline):
     """
     if "t" in mode:
         if "b" in mode:
-            raise ValueError("Invalid mode: %r" % (mode,))
+            raise ValueError(f"Invalid mode: {mode!r}")
     else:
         if encoding is not None:
             raise ValueError("Argument 'encoding' not supported in binary mode")
diff --git a/numpy/lib/_format_impl.py b/numpy/lib/_format_impl.py
index a25d64ada252..6ef3f3cec023 100644
--- a/numpy/lib/_format_impl.py
+++ b/numpy/lib/_format_impl.py
@@ -460,7 +460,7 @@ def _write_array_header(fp, d, version=None):
     header = ["{"]
     for key, value in sorted(d.items()):
         # Need to use repr here, since we eval these when reading
-        header.append("'%s': %s, " % (key, repr(value)))
+        header.append(f"'{key}': {repr(value)}, ")
     header.append("}")
     header = "".join(header)
 
diff --git a/numpy/lib/_function_base_impl.py b/numpy/lib/_function_base_impl.py
index 4382958ae9fa..a44ee77a967c 100644
--- a/numpy/lib/_function_base_impl.py
+++ b/numpy/lib/_function_base_impl.py
@@ -2134,9 +2134,9 @@ def disp(mesg, device=None, linefeed=True):
     if device is None:
         device = sys.stdout
     if linefeed:
-        device.write('%s\n' % mesg)
+        device.write(f'{mesg}\n')
     else:
-        device.write('%s' % mesg)
+        device.write(f'{mesg}')
     device.flush()
     return
 
@@ -2458,7 +2458,7 @@ def __init__(self, pyfunc=np._NoValue, otypes=None, doc=None,
         if isinstance(otypes, str):
             for char in otypes:
                 if char not in typecodes['All']:
-                    raise ValueError("Invalid otype specified: %s" % (char,))
+                    raise ValueError(f"Invalid otype specified: {char}")
         elif iterable(otypes):
             otypes = [_get_vectorize_dtype(_nx.dtype(x)) for x in otypes]
         elif otypes is not None:
diff --git a/numpy/lib/_iotools.py b/numpy/lib/_iotools.py
index 87e6a2ab23e9..56ee65d38575 100644
--- a/numpy/lib/_iotools.py
+++ b/numpy/lib/_iotools.py
@@ -304,7 +304,7 @@ def __init__(self, excludelist=None, deletechars=None,
         elif case_sensitive.startswith('l'):
             self.case_converter = lambda x: x.lower()
         else:
-            msg = 'unrecognized case_sensitive value %s.' % case_sensitive
+            msg = f'unrecognized case_sensitive value {case_sensitive}.'
             raise ValueError(msg)
 
         self.replace_space = replace_space
@@ -698,7 +698,7 @@ def _strict_call(self, value):
                 if not self._status:
                     self._checked = False
                 return self.default
-            raise ValueError("Cannot convert string '%s'" % value)
+            raise ValueError(f"Cannot convert string '{value}'")
 
     def __call__(self, value):
         return self._callingfunction(value)
diff --git a/numpy/lib/_npyio_impl.py b/numpy/lib/_npyio_impl.py
index cde5335adbb4..0fff58f1601d 100644
--- a/numpy/lib/_npyio_impl.py
+++ b/numpy/lib/_npyio_impl.py
@@ -779,7 +779,7 @@ def _savez(file, args, kwds, compress, allow_pickle=True, pickle_kwargs=None):
         key = 'arr_%d' % i
         if key in namedict.keys():
             raise ValueError(
-                "Cannot use un-named variables and keyword %s" % key)
+                f"Cannot use un-named variables and keyword {key}")
         namedict[key] = val
 
     if compress:
@@ -1594,14 +1594,14 @@ def first_write(self, v):
         # list of formats.  E.g. '%10.5f\t%10d' or ('%10.5f', '$10d')
         if type(fmt) in (list, tuple):
             if len(fmt) != ncol:
-                raise AttributeError('fmt has wrong shape.  %s' % str(fmt))
+                raise AttributeError(f'fmt has wrong shape.  {str(fmt)}')
             format = delimiter.join(fmt)
         elif isinstance(fmt, str):
             n_fmt_chars = fmt.count('%')
-            error = ValueError('fmt has wrong number of %% formats:  %s' % fmt)
+            error = ValueError(f'fmt has wrong number of % formats:  {fmt}')
             if n_fmt_chars == 1:
                 if iscomplex_X:
-                    fmt = [' (%s+%sj)' % (fmt, fmt), ] * ncol
+                    fmt = [f' ({fmt}+{fmt}j)', ] * ncol
                 else:
                     fmt = [fmt, ] * ncol
                 format = delimiter.join(fmt)
@@ -1612,7 +1612,7 @@ def first_write(self, v):
             else:
                 format = fmt
         else:
-            raise ValueError('invalid fmt: %r' % (fmt,))
+            raise ValueError(f'invalid fmt: {fmt!r}')
 
         if len(header) > 0:
             header = header.replace('\n', '\n' + comments)
@@ -2027,7 +2027,7 @@ def genfromtxt(fname, dtype=float, comments='#', delimiter=None,
             first_line = ''
             first_values = []
             warnings.warn(
-                'genfromtxt: Empty input file: "%s"' % fname, stacklevel=2
+                f'genfromtxt: Empty input file: "{fname}"', stacklevel=2
             )
 
         # Should we take the first values as names ?
diff --git a/numpy/lib/_polynomial_impl.py b/numpy/lib/_polynomial_impl.py
index efb57a31c361..91cf7405a1cc 100644
--- a/numpy/lib/_polynomial_impl.py
+++ b/numpy/lib/_polynomial_impl.py
@@ -1275,7 +1275,7 @@ def __array__(self, t=None, copy=None):
     def __repr__(self):
         vals = repr(self.coeffs)
         vals = vals[6:-1]
-        return "poly1d(%s)" % vals
+        return f"poly1d({vals})"
 
     def __len__(self):
         return self.order
@@ -1289,7 +1289,7 @@ def __str__(self):
         N = len(coeffs) - 1
 
         def fmt_float(q):
-            s = '%.4g' % q
+            s = f'{q:.4g}'
             s = s.removesuffix('.0000')
             return s
 
@@ -1297,15 +1297,14 @@ def fmt_float(q):
             if not iscomplex(coeff):
                 coefstr = fmt_float(real(coeff))
             elif real(coeff) == 0:
-                coefstr = '%sj' % fmt_float(imag(coeff))
+                coefstr = f'{fmt_float(imag(coeff))}j'
             else:
-                coefstr = '(%s + %sj)' % (fmt_float(real(coeff)),
-                                          fmt_float(imag(coeff)))
+                coefstr = f'({fmt_float(real(coeff))} + {fmt_float(imag(coeff))}j)'
 
             power = (N - k)
             if power == 0:
                 if coefstr != '0':
-                    newstr = '%s' % (coefstr,)
+                    newstr = f'{coefstr}'
                 else:
                     if k == 0:
                         newstr = '0'
@@ -1317,7 +1316,7 @@ def fmt_float(q):
                 elif coefstr == 'b':
                     newstr = var
                 else:
-                    newstr = '%s %s' % (coefstr, var)
+                    newstr = f'{coefstr} {var}'
             else:
                 if coefstr == '0':
                     newstr = ''
@@ -1329,9 +1328,9 @@ def fmt_float(q):
             if k > 0:
                 if newstr != '':
                     if newstr.startswith('-'):
-                        thestr = "%s - %s" % (thestr, newstr[1:])
+                        thestr = f"{thestr} - {newstr[1:]}"
                     else:
-                        thestr = "%s + %s" % (thestr, newstr)
+                        thestr = f"{thestr} + {newstr}"
             else:
                 thestr = newstr
         return _raise_power(thestr)
diff --git a/numpy/lib/_utils_impl.py b/numpy/lib/_utils_impl.py
index 1d7714115414..ac10aec698d6 100644
--- a/numpy/lib/_utils_impl.py
+++ b/numpy/lib/_utils_impl.py
@@ -144,10 +144,9 @@ def __call__(self, func, *args, **kwargs):
         if old_name is None:
             old_name = func.__name__
         if new_name is None:
-            depdoc = "`%s` is deprecated!" % old_name
+            depdoc = f"`{old_name}` is deprecated!"
         else:
-            depdoc = "`%s` is deprecated, use `%s` instead!" % \
-                     (old_name, new_name)
+            depdoc = f"`{old_name}` is deprecated, use `{new_name}` instead!"
 
         if message is not None:
             depdoc += "\n" + message
@@ -394,21 +393,21 @@ def _info(obj, output=None):
     print("contiguous: ", bp(obj.flags.contiguous), file=output)
     print("fortran: ", obj.flags.fortran, file=output)
     print(
-        "data pointer: %s%s" % (hex(obj.ctypes._as_parameter_.value), extra),
+        f"data pointer: {hex(obj.ctypes._as_parameter_.value)}{extra}",
         file=output
         )
     print("byteorder: ", end=' ', file=output)
     if endian in ['|', '=']:
-        print("%s%s%s" % (tic, sys.byteorder, tic), file=output)
+        print(f"{tic}{sys.byteorder}{tic}", file=output)
         byteswap = False
     elif endian == '>':
-        print("%sbig%s" % (tic, tic), file=output)
+        print(f"{tic}big{tic}", file=output)
         byteswap = sys.byteorder != "big"
     else:
-        print("%slittle%s" % (tic, tic), file=output)
+        print(f"{tic}little{tic}", file=output)
         byteswap = sys.byteorder != "little"
     print("byteswap: ", bp(byteswap), file=output)
-    print("type: %s" % obj.dtype, file=output)
+    print(f"type: {obj.dtype}", file=output)
 
 
 @set_module('numpy')
@@ -502,20 +501,19 @@ def info(object=None, maxwidth=76, output=None, toplevel='numpy'):
             try:
                 obj = _namedict[namestr][object]
                 if id(obj) in objlist:
-                    print("\n     "
-                          "*** Repeat reference found in %s *** " % namestr,
+                    print(f"\n     *** Repeat reference found in {namestr} *** ",
                           file=output
                           )
                 else:
                     objlist.append(id(obj))
-                    print("     *** Found in %s ***" % namestr, file=output)
+                    print(f"     *** Found in {namestr} ***", file=output)
                     info(obj)
                     print("-" * maxwidth, file=output)
                 numfound += 1
             except KeyError:
                 pass
         if numfound == 0:
-            print("Help for %s not found." % object, file=output)
+            print(f"Help for {object} not found.", file=output)
         else:
             print("\n     "
                   "*** Total of %d references found. ***" % numfound,
@@ -568,7 +566,7 @@ def info(object=None, maxwidth=76, output=None, toplevel='numpy'):
                     methstr, other = pydoc.splitdoc(
                             inspect.getdoc(thisobj) or "None"
                             )
-                print("  %s  --  %s" % (meth, methstr), file=output)
+                print(f"  {meth}  --  {methstr}", file=output)
 
     elif hasattr(object, '__doc__'):
         print(inspect.getdoc(object), file=output)
diff --git a/numpy/lib/_version.py b/numpy/lib/_version.py
index 929f8a1c6685..dac2876b1e97 100644
--- a/numpy/lib/_version.py
+++ b/numpy/lib/_version.py
@@ -152,4 +152,4 @@ def __ge__(self, other):
         return self._compare(other) >= 0
 
     def __repr__(self):
-        return "NumpyVersion(%s)" % self.vstring
+        return f"NumpyVersion({self.vstring})"
diff --git a/numpy/lib/recfunctions.py b/numpy/lib/recfunctions.py
index 4a3fc98de171..19337cad1943 100644
--- a/numpy/lib/recfunctions.py
+++ b/numpy/lib/recfunctions.py
@@ -1386,8 +1386,7 @@ def stack_arrays(arrays, defaults=None, usemask=True, asrecarray=False,
                 if autoconvert:
                     newdescr[nameidx] = (fname, max(fdtype, cdtype))
                 elif fdtype != cdtype:
-                    raise TypeError("Incompatible type '%s' <> '%s'" %
-                                    (cdtype, fdtype))
+                    raise TypeError(f"Incompatible type '{cdtype}' <> '{fdtype}'")
     # Only one field: use concatenate
     if len(newdescr) == 1:
         output = ma.concatenate(seqarrays)
@@ -1544,12 +1543,12 @@ def join_by(key, r1, r2, jointype='inner', r1postfix='1', r2postfix='2',
     # Check the keys
     if len(set(key)) != len(key):
         dup = next(x for n, x in enumerate(key) if x in key[n + 1:])
-        raise ValueError("duplicate join key %r" % dup)
+        raise ValueError(f"duplicate join key {dup!r}")
     for name in key:
         if name not in r1.dtype.names:
-            raise ValueError('r1 does not have key field %r' % name)
+            raise ValueError(f'r1 does not have key field {name!r}')
         if name not in r2.dtype.names:
-            raise ValueError('r2 does not have key field %r' % name)
+            raise ValueError(f'r2 does not have key field {name!r}')
 
     # Make sure we work with ravelled arrays
     r1 = r1.ravel()
diff --git a/numpy/lib/tests/test_function_base.py b/numpy/lib/tests/test_function_base.py
index 2d07307d1be6..711b36f59671 100644
--- a/numpy/lib/tests/test_function_base.py
+++ b/numpy/lib/tests/test_function_base.py
@@ -945,7 +945,7 @@ def setup_method(self):
     def _check_inverse_of_slicing(self, indices):
         a_del = delete(self.a, indices)
         nd_a_del = delete(self.nd_a, indices, axis=1)
-        msg = 'Delete failed for obj: %r' % indices
+        msg = f'Delete failed for obj: {indices!r}'
         assert_array_equal(setxor1d(a_del, self.a[indices, ]), self.a,
                            err_msg=msg)
         xor = setxor1d(nd_a_del[0, :, 0], self.nd_a[0, indices, 0])
diff --git a/numpy/lib/tests/test_io.py b/numpy/lib/tests/test_io.py
index cce86489e22f..3276584779a7 100644
--- a/numpy/lib/tests/test_io.py
+++ b/numpy/lib/tests/test_io.py
@@ -314,7 +314,7 @@ def test_closing_fid(self):
                     try:
                         np.load(tmp)["data"]
                     except Exception as e:
-                        msg = "Failed to load data from a file: %s" % e
+                        msg = f"Failed to load data from a file: {e}"
                         raise AssertionError(msg)
                     finally:
                         if IS_PYPY:
@@ -907,13 +907,13 @@ def __index__(self):
         bogus_idx = 1.5
         assert_raises_regex(
             TypeError,
-            '^usecols must be.*%s' % type(bogus_idx).__name__,
+            f'^usecols must be.*{type(bogus_idx).__name__}',
             np.loadtxt, c, usecols=bogus_idx
             )
 
         assert_raises_regex(
             TypeError,
-            '^usecols must be.*%s' % type(bogus_idx).__name__,
+            f'^usecols must be.*{type(bogus_idx).__name__}',
             np.loadtxt, c, usecols=[0, bogus_idx, 0]
             )
 
@@ -1029,7 +1029,7 @@ def test_from_float_hex(self):
             c.seek(0)
             res = np.loadtxt(
                 c, dtype=dt, converters=float.fromhex, encoding="latin1")
-            assert_equal(res, tgt, err_msg="%s" % dt)
+            assert_equal(res, tgt, err_msg=f"{dt}")
 
     @pytest.mark.skipif(IS_PYPY and sys.implementation.version <= (7, 3, 8),
                         reason="PyPy bug in error formatting")
@@ -1412,7 +1412,7 @@ def test_skip_footer(self):
         data[-1] = "99,99"
         kwargs = {"delimiter": ",", "names": True, "skip_header": 5, "skip_footer": 10}
         test = np.genfromtxt(TextIO("\n".join(data)), **kwargs)
-        ctrl = np.array([("%f" % i, "%f" % i, "%f" % i) for i in range(41)],
+        ctrl = np.array([(f"{i:f}", f"{i:f}", f"{i:f}") for i in range(41)],
                         dtype=[(_, float) for _ in "ABC"])
         assert_equal(test, ctrl)
 
@@ -1997,7 +1997,7 @@ def test_inconsistent_dtype(self):
         data = ["1, 1, 1, 1, -1.1"] * 50
         mdata = TextIO("\n".join(data))
 
-        converters = {4: lambda x: "(%s)" % x.decode()}
+        converters = {4: lambda x: f"({x.decode()})"}
         kwargs = {"delimiter": ",", "converters": converters,
                       "dtype": [(_, int) for _ in 'abcde'], "encoding": "bytes"}
         assert_raises(ValueError, np.genfromtxt, mdata, **kwargs)
diff --git a/numpy/lib/tests/test_mixins.py b/numpy/lib/tests/test_mixins.py
index 70e3c31d3174..2ff4b49011f8 100644
--- a/numpy/lib/tests/test_mixins.py
+++ b/numpy/lib/tests/test_mixins.py
@@ -46,7 +46,7 @@ def __array_ufunc__(self, ufunc, method, *inputs, **kwargs):
             return type(self)(result)
 
     def __repr__(self):
-        return '%s(%r)' % (type(self).__name__, self.value)
+        return f'{type(self).__name__}({self.value!r})'
 
 
 def wrap_array_like(result):
diff --git a/numpy/lib/tests/test_nanfunctions.py b/numpy/lib/tests/test_nanfunctions.py
index b9c53ab36b63..918d855cd104 100644
--- a/numpy/lib/tests/test_nanfunctions.py
+++ b/numpy/lib/tests/test_nanfunctions.py
@@ -522,7 +522,7 @@ def test_dtype_from_input(self):
                 mat = np.eye(3, dtype=c)
                 tgt = rf(mat, axis=1).dtype.type
                 res = nf(mat, axis=1).dtype.type
-                assert_(res is tgt, "res %s, tgt %s" % (res, tgt))
+                assert_(res is tgt, f"res {res}, tgt {tgt}")
                 # scalar case
                 tgt = rf(mat, axis=None).dtype.type
                 res = nf(mat, axis=None).dtype.type
diff --git a/numpy/lib/tests/test_stride_tricks.py b/numpy/lib/tests/test_stride_tricks.py
index 017d46478b74..d82e9b801e27 100644
--- a/numpy/lib/tests/test_stride_tricks.py
+++ b/numpy/lib/tests/test_stride_tricks.py
@@ -219,7 +219,7 @@ def test_same_as_ufunc():
     ]
     for input_shapes, expected_shape in data:
         assert_same_as_ufunc(input_shapes[0], input_shapes[1],
-                             "Shapes: %s %s" % (input_shapes[0], input_shapes[1]))
+                             f"Shapes: {input_shapes[0]} {input_shapes[1]}")
         # Reverse the input shapes since broadcasting should be symmetric.
         assert_same_as_ufunc(input_shapes[1], input_shapes[0])
         # Try them transposed, too.
diff --git a/numpy/linalg/_linalg.py b/numpy/linalg/_linalg.py
index 8d15b3c9d8a2..1301f1cb7e9a 100644
--- a/numpy/linalg/_linalg.py
+++ b/numpy/linalg/_linalg.py
@@ -159,8 +159,7 @@ def _commonType(*arrays):
                 result_type = double
             elif rt is None:
                 # unsupported inexact scalar
-                raise TypeError("array type %s is unsupported in linalg" %
-                        (a.dtype.name,))
+                raise TypeError(f"array type {a.dtype.name} is unsupported in linalg")
         else:
             result_type = double
     if is_complex:
diff --git a/numpy/linalg/lapack_lite/make_lite.py b/numpy/linalg/lapack_lite/make_lite.py
index 872e2a096ff3..4de2b337328f 100755
--- a/numpy/linalg/lapack_lite/make_lite.py
+++ b/numpy/linalg/lapack_lite/make_lite.py
@@ -199,7 +199,7 @@ def allRoutinesByType(self, typename):
 def printRoutineNames(desc, routines):
     print(desc)
     for r in routines:
-        print('\t%s' % r.name)
+        print(f'\t{r.name}')
 
 def getLapackRoutines(wrapped_routines, ignores, lapack_dir):
     blas_src_dir = os.path.join(lapack_dir, 'BLAS', 'SRC')
@@ -250,7 +250,7 @@ def dumpRoutineNames(library, output_dir):
         with open(filename, 'w') as fo:
             for r in routines:
                 deps = r.dependencies()
-                fo.write('%s: %s\n' % (r.name, ' '.join(deps)))
+                fo.write(f"{r.name}: {' '.join(deps)}\n")
 
 def concatenateRoutines(routines, output_file):
     with open(output_file, 'w') as output_fo:
@@ -323,13 +323,13 @@ def create_name_header(output_dir):
 
         # Rename BLAS/LAPACK symbols
         for name in sorted(symbols):
-            f.write("#define %s_ BLAS_FUNC(%s)\n" % (name, name))
+            f.write(f"#define {name}_ BLAS_FUNC({name})\n")
 
         # Rename also symbols that f2c exports itself
         f.write("\n"
                 "/* Symbols exported by f2c.c */\n")
         for name in sorted(f2c_symbols):
-            f.write("#define %s numpy_lapack_lite_%s\n" % (name, name))
+            f.write(f"#define {name} numpy_lapack_lite_{name}\n")
 
 def main():
     if len(sys.argv) != 3:
@@ -352,9 +352,9 @@ def main():
     dumpRoutineNames(library, output_dir)
 
     for typename in types:
-        fortran_file = os.path.join(output_dir, 'f2c_%s.f' % typename)
+        fortran_file = os.path.join(output_dir, f'f2c_{typename}.f')
         c_file = fortran_file[:-2] + '.c'
-        print('creating %s ...' % c_file)
+        print(f'creating {c_file} ...')
         routines = library.allRoutinesByType(typename)
         concatenateRoutines(routines, fortran_file)
 
@@ -366,7 +366,7 @@ def main():
         try:
             runF2C(fortran_file, output_dir)
         except F2CError:
-            print('f2c failed on %s' % fortran_file)
+            print(f'f2c failed on {fortran_file}')
             break
         scrubF2CSource(c_file)
 
diff --git a/numpy/ma/core.py b/numpy/ma/core.py
index db2f9eadb9bd..3e291efa6032 100644
--- a/numpy/ma/core.py
+++ b/numpy/ma/core.py
@@ -120,7 +120,7 @@ def doc_note(initialdoc, note):
         return initialdoc
 
     notesplit = re.split(r'\n\s*?Notes\n\s*?-----', inspect.cleandoc(initialdoc))
-    notedoc = "\n\nNotes\n-----\n%s\n" % inspect.cleandoc(note)
+    notedoc = f"\n\nNotes\n-----\n{inspect.cleandoc(note)}\n"
 
     return ''.join(notesplit[:1] + [notedoc] + notesplit[1:])
 
@@ -1797,7 +1797,7 @@ def mask_or(m1, m2, copy=False, shrink=True):
         return _shrink_mask(m1) if shrink else m1
     (dtype1, dtype2) = (getattr(m1, 'dtype', None), getattr(m2, 'dtype', None))
     if dtype1 != dtype2:
-        raise ValueError("Incompatible dtypes '%s'<>'%s'" % (dtype1, dtype2))
+        raise ValueError(f"Incompatible dtypes '{dtype1}'<>'{dtype2}'")
     if dtype1.names is not None:
         # Allocate an output mask array with the properly broadcast shape.
         newmask = np.empty(np.broadcast(m1, m2).shape, dtype1)
@@ -7096,8 +7096,8 @@ def getdoc(self):
             getattr(np, self.__name__, None)
         signature = self.__name__ + get_object_signature(meth)
         if meth is not None:
-            doc = """    %s\n%s""" % (
-                signature, getattr(meth, '__doc__', None))
+            doc = f"""    {signature}
+{getattr(meth, '__doc__', None)}"""
             return doc
 
     def __call__(self, a, *args, **params):
@@ -8794,7 +8794,7 @@ def getdoc(self, np_ret, np_ma_ret):
             doc = self._replace_return_type(doc, np_ret, np_ma_ret)
             # Add the signature of the function at the beginning of the doc
             if sig:
-                sig = "%s%s\n" % (self._func.__name__, sig)
+                sig = f"{self._func.__name__}{sig}\n"
             doc = sig + doc
         return doc
 
diff --git a/numpy/matrixlib/tests/test_defmatrix.py b/numpy/matrixlib/tests/test_defmatrix.py
index 9c18299b8e5c..bfdbb9abf5b9 100644
--- a/numpy/matrixlib/tests/test_defmatrix.py
+++ b/numpy/matrixlib/tests/test_defmatrix.py
@@ -298,7 +298,7 @@ def test_instance_methods(self):
                 a.fill(1.0)
                 args = methodargs.get(attrib, ())
                 b = f(*args)
-                assert_(type(b) is matrix, "%s" % attrib)
+                assert_(type(b) is matrix, f"{attrib}")
         assert_(type(a.real) is matrix)
         assert_(type(a.imag) is matrix)
         c, d = matrix([0.0]).nonzero()
diff --git a/numpy/random/tests/test_extending.py b/numpy/random/tests/test_extending.py
index d6ffea0b2dbf..a24394e600a9 100644
--- a/numpy/random/tests/test_extending.py
+++ b/numpy/random/tests/test_extending.py
@@ -94,8 +94,7 @@ def test_cython(tmp_path):
             if txt_to_find in line:
                 break
         else:
-            assert False, ("Could not find '{}' in C file, "
-                           "wrong pxd used".format(txt_to_find))
+            assert False, (f"Could not find '{txt_to_find}' in C file, wrong pxd used")
     # import without adding the directory to sys.path
     suffix = sysconfig.get_config_var('EXT_SUFFIX')
 
diff --git a/numpy/testing/_private/extbuild.py b/numpy/testing/_private/extbuild.py
index f473b2d34ec4..af403bf7f8f4 100644
--- a/numpy/testing/_private/extbuild.py
+++ b/numpy/testing/_private/extbuild.py
@@ -134,7 +134,7 @@ def _make_methods(functions, modname):
     methods_table = []
     codes = []
     for funcname, flags, code in functions:
-        cfuncname = "%s_%s" % (modname, funcname)
+        cfuncname = f"{modname}_{funcname}"
         if 'METH_KEYWORDS' in flags:
             signature = '(PyObject *self, PyObject *args, PyObject *kwargs)'
         else:
diff --git a/numpy/testing/_private/utils.py b/numpy/testing/_private/utils.py
index ebbdb0a2a165..ba7c1c94e082 100644
--- a/numpy/testing/_private/utils.py
+++ b/numpy/testing/_private/utils.py
@@ -1879,8 +1879,7 @@ def nulp_diff(x, y, dtype=None):
     y[np.isnan(y)] = np.nan
 
     if not x.shape == y.shape:
-        raise ValueError("Arrays do not have the same shape: %s - %s" %
-                         (x.shape, y.shape))
+        raise ValueError(f"Arrays do not have the same shape: {x.shape} - {y.shape}")
 
     def _diff(rx, ry, vdt):
         diff = np.asarray(rx - ry, dtype=vdt)
diff --git a/numpy/tests/test_ctypeslib.py b/numpy/tests/test_ctypeslib.py
index ec5964375988..5a65f7d99eee 100644
--- a/numpy/tests/test_ctypeslib.py
+++ b/numpy/tests/test_ctypeslib.py
@@ -61,7 +61,7 @@ def test_basic2(self):
         # (including extension) does not work.
         try:
             so_ext = sysconfig.get_config_var('EXT_SUFFIX')
-            load_library('_multiarray_umath%s' % so_ext,
+            load_library(f'_multiarray_umath{so_ext}',
                          np._core._multiarray_umath.__file__)
         except ImportError as e:
             msg = ("ctypes is not available on this python: skipping the test"
diff --git a/pavement.py b/pavement.py
index a9bf7febd804..9b4e4fc81346 100644
--- a/pavement.py
+++ b/pavement.py
@@ -69,7 +69,7 @@ def _compute_hash(idirs, hashfunc):
         with open(fpath, 'rb') as fin:
             fhash = hashfunc(fin.read())
             checksums.append(
-                '%s  %s' % (fhash.hexdigest(), os.path.basename(fpath)))
+                f'{fhash.hexdigest()}  {os.path.basename(fpath)}')
     return checksums
 
 
diff --git a/tools/check_installed_files.py b/tools/check_installed_files.py
index 16b80caa5744..0783583cd928 100644
--- a/tools/check_installed_files.py
+++ b/tools/check_installed_files.py
@@ -55,7 +55,7 @@ def main(install_dir, tests_check):
         for test_file in numpy_test_files.keys():
             if test_file not in installed_test_files.keys():
                 raise Exception(
-                    "%s is not installed" % numpy_test_files[test_file]
+                    f"{numpy_test_files[test_file]} is not installed"
                 )
 
         print("----------- All the test files were installed --------------")
@@ -69,7 +69,7 @@ def main(install_dir, tests_check):
             if (tests_check == "--no-tests" and
                     "tests" in numpy_pyi_files[pyi_file]):
                 continue
-            raise Exception("%s is not installed" % numpy_pyi_files[pyi_file])
+            raise Exception(f"{numpy_pyi_files[pyi_file]} is not installed")
 
     print("----------- All the necessary .pyi files "
           "were installed --------------")
diff --git a/tools/ci/push_docs_to_repo.py b/tools/ci/push_docs_to_repo.py
index aa9663d4764c..4b31f8df492e 100755
--- a/tools/ci/push_docs_to_repo.py
+++ b/tools/ci/push_docs_to_repo.py
@@ -45,7 +45,7 @@ def run(cmd, stdout=True):
     try:
         subprocess.check_call(cmd, stdout=pipe, stderr=pipe)
     except subprocess.CalledProcessError:
-        print("\n! Error executing: `%s;` aborting" % ' '.join(cmd))
+        print(f"\n! Error executing: `{' '.join(cmd)};` aborting")
         sys.exit(1)
 
 
@@ -60,12 +60,12 @@ def run(cmd, stdout=True):
 run(['git', 'config', '--local', 'user.name', args.committer])
 run(['git', 'config', '--local', 'user.email', args.email])
 
-print('- committing new content: "%s"' % args.message)
+print(f'- committing new content: "{args.message}"')
 run(['cp', '-R', os.path.join(args.dir, '.'), '.'])
 run(['git', 'add', '.'], stdout=False)
 run(['git', 'commit', '--allow-empty', '-m', args.message], stdout=False)
 
-print('- uploading as %s <%s>' % (args.committer, args.email))
+print(f'- uploading as {args.committer} <{args.email}>')
 if args.force:
     run(['git', 'push', 'origin', 'main', '--force'])
 else:
diff --git a/tools/refguide_check.py b/tools/refguide_check.py
index 4b474e698c7a..87c760bf154b 100644
--- a/tools/refguide_check.py
+++ b/tools/refguide_check.py
@@ -359,7 +359,7 @@ def check_items(all_dict, names, deprecated, others, module_name, dots=True):
         return [(None, True, output)]
     else:
         if len(only_all) > 0:
-            output += "ERROR: objects in %s.__all__ but not in refguide::\n\n" % module_name  # noqa: E501
+            output += f"ERROR: objects in {module_name}.__all__ but not in refguide::\n\n"  # noqa: E501
             for name in sorted(only_all):
                 output += "    " + name + "\n"
 
@@ -367,7 +367,7 @@ def check_items(all_dict, names, deprecated, others, module_name, dots=True):
             output += "the function listing in __init__.py for this module\n"
 
         if len(only_ref) > 0:
-            output += "ERROR: objects in refguide but not in %s.__all__::\n\n" % module_name  # noqa: E501
+            output += f"ERROR: objects in refguide but not in {module_name}.__all__::\n\n"  # noqa: E501
             for name in sorted(only_ref):
                 output += "    " + name + "\n"
 
@@ -404,7 +404,7 @@ def validate_rst_syntax(text, name, dots=True):
     if text is None:
         if dots:
             output_dot('E')
-        return False, "ERROR: %s: no documentation" % (name,)
+        return False, f"ERROR: {name}: no documentation"
 
     ok_unknown_items = {
         'mod', 'doc', 'currentmodule', 'autosummary', 'data', 'attr',
@@ -503,7 +503,7 @@ def check_rest(module, names, dots=True):
         obj = getattr(module, name, None)
 
         if obj is None:
-            results.append((full_name, False, "%s has no docstring" % (full_name,)))
+            results.append((full_name, False, f"{full_name} has no docstring"))
             continue
         elif isinstance(obj, skip_types):
             continue
@@ -592,7 +592,7 @@ def main(argv):
             modules.append(module)
 
     if modules:
-        print("Running checks for %d modules:" % (len(modules),))
+        print(f"Running checks for {len(modules)} modules:")
         for module in modules:
             if dots:
                 sys.stderr.write(module.__name__ + ' ')

From 9843e151e45fa836753a8632a9fa01cb49588955 Mon Sep 17 00:00:00 2001
From: Krishna Bindumadhavan <31140965+f2013519@users.noreply.github.com>
Date: Fri, 18 Apr 2025 20:32:21 +0530
Subject: [PATCH 063/202] MAINT: Improve float16 and float32 printing (#28703)

* MAINT: Improve float16 and float32 printing

* Address review comments

* Add release note

* Add array printing legacy version 2.2 for backward compatibility

* Address remaining review comments

* Fix Typo
---
 doc/release/upcoming_changes/28703.change.rst |  3 ++
 numpy/_core/arrayprint.py                     | 18 +++++++--
 numpy/_core/src/multiarray/scalartypes.c.src  | 19 ++++++++-
 numpy/_core/tests/test_arrayprint.py          | 39 +++++++++++++++++++
 numpy/_core/tests/test_scalarprint.py         | 28 +++++++++++++
 5 files changed, 102 insertions(+), 5 deletions(-)
 create mode 100644 doc/release/upcoming_changes/28703.change.rst

diff --git a/doc/release/upcoming_changes/28703.change.rst b/doc/release/upcoming_changes/28703.change.rst
new file mode 100644
index 000000000000..87bb431951f9
--- /dev/null
+++ b/doc/release/upcoming_changes/28703.change.rst
@@ -0,0 +1,3 @@
+* Printing of ``np.float16`` and ``np.float32`` scalars and arrays have been improved by
+  adjusting the transition to scientific notation based on the floating point precision.
+  A new legacy ``np.printoptions`` mode ``'2.2'`` has been added for backwards compatibility.
diff --git a/numpy/_core/arrayprint.py b/numpy/_core/arrayprint.py
index 14818c66f172..af41bf9878b3 100644
--- a/numpy/_core/arrayprint.py
+++ b/numpy/_core/arrayprint.py
@@ -85,12 +85,14 @@ def _make_options_dict(precision=None, threshold=None, edgeitems=None,
         options['legacy'] = 125
     elif legacy == '2.1':
         options['legacy'] = 201
+    elif legacy == '2.2':
+        options['legacy'] = 202
     elif legacy is None:
         pass  # OK, do nothing.
     else:
         warnings.warn(
             "legacy printing option can currently only be '1.13', '1.21', "
-            "'1.25', '2.1, or `False`", stacklevel=3)
+            "'1.25', '2.1', '2.2' or `False`", stacklevel=3)
 
     if threshold is not None:
         # forbid the bad threshold arg suggested by stack overflow, gh-12351
@@ -219,6 +221,10 @@ def set_printoptions(precision=None, threshold=None, edgeitems=None,
         If set to ``'2.1'``, shape information is not given when arrays are
         summarized (i.e., multiple elements replaced with ``...``).
 
+        If set to ``'2.2'``, the transition to use scientific notation for
+        printing ``np.float16`` and ``np.float32`` types may happen later or
+        not at all for larger values.
+
         If set to `False`, disables legacy mode.
 
         Unrecognized strings will be ignored with a warning for forward
@@ -359,7 +365,8 @@ def get_printoptions():
     """
     opts = format_options.get().copy()
     opts['legacy'] = {
-        113: '1.13', 121: '1.21', 125: '1.25', sys.maxsize: False,
+        113: '1.13', 121: '1.21', 125: '1.25', 201: '2.1',
+        202: '2.2', sys.maxsize: False,
     }[opts['legacy']]
     return opts
 
@@ -993,8 +1000,13 @@ def fillFormat(self, data):
         if len(abs_non_zero) != 0:
             max_val = np.max(abs_non_zero)
             min_val = np.min(abs_non_zero)
+            if self._legacy <= 202:
+                exp_cutoff_max = 1.e8
+            else:
+                # consider data type while deciding the max cutoff for exp format
+                exp_cutoff_max = 10.**min(8, np.finfo(data.dtype).precision)
             with errstate(over='ignore'):  # division can overflow
-                if max_val >= 1.e8 or (not self.suppress_small and
+                if max_val >= exp_cutoff_max or (not self.suppress_small and
                         (min_val < 0.0001 or max_val / min_val > 1000.)):
                     self.exp_format = True
 
diff --git a/numpy/_core/src/multiarray/scalartypes.c.src b/numpy/_core/src/multiarray/scalartypes.c.src
index 39909c159683..1f683851f585 100644
--- a/numpy/_core/src/multiarray/scalartypes.c.src
+++ b/numpy/_core/src/multiarray/scalartypes.c.src
@@ -1306,6 +1306,7 @@ legacy_@name@_format@kind@(npy_@name@ val){
 
 /**begin repeat1
  * #name = float, double, longdouble#
+ * #max_positional = 1.e6L, 1.e16L, 1.e16L#
  * #Name = Float, Double, LongDouble#
  * #NAME = FLOAT, DOUBLE, LONGDOUBLE#
  * #n = f, , l#
@@ -1329,6 +1330,13 @@ static PyObject *
     if (legacy_print_mode <= 113) {
         return legacy_@name@_format@kind@(val);
     }
+    long double max_positional;
+    if (legacy_print_mode <= 202) {
+        max_positional = 1.e16L;
+    }
+    else {
+        max_positional = @max_positional@;
+    }
 
     int use_positional;
     if (npy_isnan(val) || val == 0) {
@@ -1336,7 +1344,7 @@ static PyObject *
     }
     else {
         npy_@name@ absval = val < 0 ? -val : val;
-        use_positional = absval < 1.e16L && absval >= 1.e-4L;
+        use_positional = absval < max_positional && absval >= 1.e-4L;
     }
 
     if (use_positional) {
@@ -1481,11 +1489,18 @@ halftype_@kind@(PyObject *self)
     if (legacy_print_mode <= 113) {
         return legacy_float_format@kind@(floatval);
     }
+    long double max_positional;
+    if (legacy_print_mode <= 202) {
+        max_positional = 1.e16L;
+    }
+    else {
+        max_positional = 1.e3L;
+    }
 
     absval = floatval < 0 ? -floatval : floatval;
 
     PyObject *string;
-    if (absval == 0 || (absval < 1.e16 && absval >= 1.e-4) ) {
+    if (absval == 0 || (absval < max_positional && absval >= 1.e-4) ) {
         string = format_half(val, 0, -1, 0, TrimMode_LeaveOneZero, -1, -1, -1);
     }
     else {
diff --git a/numpy/_core/tests/test_arrayprint.py b/numpy/_core/tests/test_arrayprint.py
index 060e2679d681..cfb2a13e6473 100644
--- a/numpy/_core/tests/test_arrayprint.py
+++ b/numpy/_core/tests/test_arrayprint.py
@@ -919,6 +919,45 @@ def test_floatmode(self):
         a = np.float64.fromhex('-1p-97')
         assert_equal(np.float64(np.array2string(a, floatmode='unique')), a)
 
+    test_cases_gh_28679 = [
+        (np.half([999, 999]), "[999. 999.]"),
+        (np.half([999, 1000]), "[9.99e+02 1.00e+03]"),
+        (np.single([999999, 999999]), "[999999. 999999.]"),
+        (np.single([999999, -1000000]), "[ 9.99999e+05 -1.00000e+06]"),
+        (
+            np.complex64([999999 + 999999j, 999999 + 999999j]),
+            "[999999.+999999.j 999999.+999999.j]"
+        ),
+        (
+            np.complex64([999999 + 999999j, 999999 + -1000000j]),
+            "[999999.+9.99999e+05j 999999.-1.00000e+06j]"
+        ),
+    ]
+
+    @pytest.mark.parametrize("input_array, expected_str", test_cases_gh_28679)
+    def test_gh_28679(self, input_array, expected_str):
+        # test cutoff to exponent notation for half, single, and complex64
+        assert_equal(str(input_array), expected_str)
+
+    test_cases_legacy_2_2 = [
+        (np.half([1.e3, 1.e4, 65504]), "[ 1000. 10000. 65504.]"),
+        (np.single([1.e6, 1.e7]), "[ 1000000. 10000000.]"),
+        (np.single([1.e7, 1.e8]), "[1.e+07 1.e+08]"),
+    ]
+
+    @pytest.mark.parametrize("input_array, expected_str", test_cases_legacy_2_2)
+    def test_legacy_2_2_mode(self, input_array, expected_str):
+        # test legacy cutoff to exponent notation for half and single
+        with np.printoptions(legacy='2.2'):
+            assert_equal(str(input_array), expected_str)
+
+    @pytest.mark.parametrize("legacy", ['1.13', '1.21', '1.25', '2.1', '2.2'])
+    def test_legacy_get_options(self, legacy):
+        # test legacy get options works okay
+        with np.printoptions(legacy=legacy):
+            p_opt = np.get_printoptions()
+            assert_equal(p_opt["legacy"], legacy)
+
     def test_legacy_mode_scalars(self):
         # in legacy mode, str of floats get truncated, and complex scalars
         # use * for non-finite imaginary part
diff --git a/numpy/_core/tests/test_scalarprint.py b/numpy/_core/tests/test_scalarprint.py
index 05aff950386d..16a9267e235c 100644
--- a/numpy/_core/tests/test_scalarprint.py
+++ b/numpy/_core/tests/test_scalarprint.py
@@ -48,6 +48,34 @@ def check(v):
         check(1e15)
         check(1e16)
 
+    test_cases_gh_28679 = [
+        (np.half, -0.000099, "-9.9e-05"),
+        (np.half, 0.0001, "0.0001"),
+        (np.half, 999, "999.0"),
+        (np.half, -1000, "-1e+03"),
+        (np.single, 0.000099, "9.9e-05"),
+        (np.single, -0.000100001, "-0.000100001"),
+        (np.single, 999999, "999999.0"),
+        (np.single, -1000000, "-1e+06")
+    ]
+
+    @pytest.mark.parametrize("dtype, input_val, expected_str", test_cases_gh_28679)
+    def test_gh_28679(self, dtype, input_val, expected_str):
+        # test cutoff to exponent notation for half and single
+        assert_equal(str(dtype(input_val)), expected_str)
+
+    test_cases_legacy_2_2 = [
+        (np.half(65504), "65500.0"),
+        (np.single(1.e15), "1000000000000000.0"),
+        (np.single(1.e16), "1e+16"),
+    ]
+
+    @pytest.mark.parametrize("input_val, expected_str", test_cases_legacy_2_2)
+    def test_legacy_2_2_mode(self, input_val, expected_str):
+        # test legacy cutoff to exponent notation for half and single
+        with np.printoptions(legacy='2.2'):
+            assert_equal(str(input_val), expected_str)
+
     def test_dragon4(self):
         # these tests are adapted from Ryan Juckett's dragon4 implementation,
         # see dragon4.c for details.

From 4233c813f5d652096297f66ad04fd03ee60810ce Mon Sep 17 00:00:00 2001
From: Dimitri Papadopoulos
 <3234522+DimitriPapadopoulos@users.noreply.github.com>
Date: Thu, 17 Apr 2025 21:43:48 +0200
Subject: [PATCH 064/202] STY: Apply ruff/Pylint rule PLW0108

Lambda may be unnecessary; consider inlining inner function
---
 numpy/_core/tests/test_arrayprint.py   | 4 ++--
 numpy/_core/tests/test_deprecations.py | 4 ++--
 numpy/_core/tests/test_multiarray.py   | 4 ++--
 numpy/f2py/tests/test_callback.py      | 2 +-
 numpy/lib/_function_base_impl.py       | 5 ++---
 numpy/lib/tests/test_function_base.py  | 2 +-
 numpy/testing/_private/utils.py        | 2 +-
 7 files changed, 11 insertions(+), 12 deletions(-)

diff --git a/numpy/_core/tests/test_arrayprint.py b/numpy/_core/tests/test_arrayprint.py
index cfb2a13e6473..e35d7307a86a 100644
--- a/numpy/_core/tests/test_arrayprint.py
+++ b/numpy/_core/tests/test_arrayprint.py
@@ -245,9 +245,9 @@ def _format_function(x):
                 "[. o O]")
         assert_(np.array2string(x, formatter={'all': lambda x: "%.4f" % x}) ==
                 "[0.0000 1.0000 2.0000]")
-        assert_equal(np.array2string(x, formatter={'int': lambda x: hex(x)}),
+        assert_equal(np.array2string(x, formatter={'int': hex}),
                 x_hex)
-        assert_equal(np.array2string(x, formatter={'int': lambda x: oct(x)}),
+        assert_equal(np.array2string(x, formatter={'int': oct}),
                 x_oct)
 
         x = np.arange(3.)
diff --git a/numpy/_core/tests/test_deprecations.py b/numpy/_core/tests/test_deprecations.py
index f8da36c2d887..693e4ca29663 100644
--- a/numpy/_core/tests/test_deprecations.py
+++ b/numpy/_core/tests/test_deprecations.py
@@ -220,7 +220,7 @@ class TestCtypesGetter(_DeprecationTestCase):
     )
     def test_deprecated(self, name: str) -> None:
         func = getattr(self.ctypes, name)
-        self.assert_deprecated(lambda: func())
+        self.assert_deprecated(func)
 
     @pytest.mark.parametrize(
         "name", ["data", "shape", "strides", "_as_parameter_"]
@@ -361,7 +361,7 @@ def test_lib_functions_deprecation_call(self):
         self.assert_deprecated(lambda: recfromtxt(data_gen(), **kwargs))
 
         self.assert_deprecated(lambda: disp("test"))
-        self.assert_deprecated(lambda: get_array_wrap())
+        self.assert_deprecated(get_array_wrap)
         self.assert_deprecated(lambda: maximum_sctype(int))
 
         self.assert_deprecated(lambda: in1d([1], [1]))
diff --git a/numpy/_core/tests/test_multiarray.py b/numpy/_core/tests/test_multiarray.py
index 214e30e4da2b..ddd631f51f18 100644
--- a/numpy/_core/tests/test_multiarray.py
+++ b/numpy/_core/tests/test_multiarray.py
@@ -3743,8 +3743,8 @@ def test_conjugate(self):
         assert_equal(ac, np.conjugate(a))
 
         a = np.array([1 - 1j, 1, 2.0, 'f'], object)
-        assert_raises(TypeError, lambda: a.conj())
-        assert_raises(TypeError, lambda: a.conjugate())
+        assert_raises(TypeError, a.conj)
+        assert_raises(TypeError, a.conjugate)
 
     def test_conjugate_out(self):
         # Minimal test for the out argument being passed on correctly
diff --git a/numpy/f2py/tests/test_callback.py b/numpy/f2py/tests/test_callback.py
index 9ce8654cd2c9..332c4cc0d79a 100644
--- a/numpy/f2py/tests/test_callback.py
+++ b/numpy/f2py/tests/test_callback.py
@@ -61,7 +61,7 @@ def check_function(self, name):
         assert r == 6
         r = t(lambda a: 5 + a, fun_extra_args=(7, ))
         assert r == 12
-        r = t(lambda a: math.degrees(a), fun_extra_args=(math.pi, ))
+        r = t(math.degrees, fun_extra_args=(math.pi, ))
         assert r == 180
         r = t(math.degrees, fun_extra_args=(math.pi, ))
         assert r == 180
diff --git a/numpy/lib/_function_base_impl.py b/numpy/lib/_function_base_impl.py
index 359d42e9c6c0..f14378daf58b 100644
--- a/numpy/lib/_function_base_impl.py
+++ b/numpy/lib/_function_base_impl.py
@@ -67,7 +67,7 @@
     # --- HYNDMAN and FAN METHODS
     # Discrete methods
     'inverted_cdf': {
-        'get_virtual_index': lambda n, quantiles: _inverted_cdf(n, quantiles),
+        'get_virtual_index': _inverted_cdf,
         'fix_gamma': None,  # should never be called
     },
     'averaged_inverted_cdf': {
@@ -79,8 +79,7 @@
             where=gamma == 0),
     },
     'closest_observation': {
-        'get_virtual_index': lambda n, quantiles: _closest_observation(n,
-                                                                    quantiles),
+        'get_virtual_index': _closest_observation,
         'fix_gamma': None,  # should never be called
     },
     # Continuous methods
diff --git a/numpy/lib/tests/test_function_base.py b/numpy/lib/tests/test_function_base.py
index 2d07307d1be6..f62b5dea807f 100644
--- a/numpy/lib/tests/test_function_base.py
+++ b/numpy/lib/tests/test_function_base.py
@@ -3057,7 +3057,7 @@ def test_non_finite_behavior_exact_x(self):
         assert_almost_equal(np.interp(x, xp, fp), [1, 2, np.nan, np.nan, 4])
 
     @pytest.fixture(params=[
-        lambda x: np.float64(x),
+        np.float64,
         lambda x: _make_complex(x, 0),
         lambda x: _make_complex(0, x),
         lambda x: _make_complex(x, np.multiply(x, -2))
diff --git a/numpy/testing/_private/utils.py b/numpy/testing/_private/utils.py
index ebbdb0a2a165..3d7589ce0887 100644
--- a/numpy/testing/_private/utils.py
+++ b/numpy/testing/_private/utils.py
@@ -1396,7 +1396,7 @@ def rundocs(filename=None, raise_on_error=True):
 
     msg = []
     if raise_on_error:
-        out = lambda s: msg.append(s)
+        out = msg.append
     else:
         out = None
 

From b60cd7ead10a9403c956991749cf32789365e98f Mon Sep 17 00:00:00 2001
From: Dimitri Papadopoulos
 <3234522+DimitriPapadopoulos@users.noreply.github.com>
Date: Thu, 17 Apr 2025 21:49:55 +0200
Subject: [PATCH 065/202] STY: Apply ruff/Pylint rule PLW1508

Invalid type for environment variable default; expected `str` or `None`
---
 doc/source/conf.py                | 2 +-
 numpy/typing/tests/test_typing.py | 2 +-
 2 files changed, 2 insertions(+), 2 deletions(-)

diff --git a/doc/source/conf.py b/doc/source/conf.py
index 2e78187431aa..5d7e291bd6f2 100644
--- a/doc/source/conf.py
+++ b/doc/source/conf.py
@@ -235,7 +235,7 @@ def setup(app):
 html_favicon = '_static/favicon/favicon.ico'
 
 # Set up the version switcher.  The versions.json is stored in the doc repo.
-if os.environ.get('CIRCLE_JOB', False) and \
+if os.environ.get('CIRCLE_JOB', None) and \
         os.environ.get('CIRCLE_BRANCH', '') != 'main':
     # For PR, name is set to its ref
     switcher_version = os.environ['CIRCLE_BRANCH']
diff --git a/numpy/typing/tests/test_typing.py b/numpy/typing/tests/test_typing.py
index 96101a1db6ab..ad61f637475b 100644
--- a/numpy/typing/tests/test_typing.py
+++ b/numpy/typing/tests/test_typing.py
@@ -84,7 +84,7 @@ def run_mypy() -> None:
     """
     if (
         os.path.isdir(CACHE_DIR)
-        and bool(os.environ.get("NUMPY_TYPING_TEST_CLEAR_CACHE", True))
+        and bool(os.environ.get("NUMPY_TYPING_TEST_CLEAR_CACHE", "True"))
     ):
         shutil.rmtree(CACHE_DIR)
 

From f89e30b6b58f08d21104fbac762bb94256687826 Mon Sep 17 00:00:00 2001
From: Dimitri Papadopoulos
 <3234522+DimitriPapadopoulos@users.noreply.github.com>
Date: Fri, 18 Apr 2025 08:36:56 +0200
Subject: [PATCH 066/202] MNT: Better solution for PLW1508

Co-authored-by: Joren Hammudoglu 
---
 doc/source/conf.py                | 3 +--
 numpy/typing/tests/test_typing.py | 2 +-
 2 files changed, 2 insertions(+), 3 deletions(-)

diff --git a/doc/source/conf.py b/doc/source/conf.py
index 5d7e291bd6f2..a13dd38db416 100644
--- a/doc/source/conf.py
+++ b/doc/source/conf.py
@@ -235,8 +235,7 @@ def setup(app):
 html_favicon = '_static/favicon/favicon.ico'
 
 # Set up the version switcher.  The versions.json is stored in the doc repo.
-if os.environ.get('CIRCLE_JOB', None) and \
-        os.environ.get('CIRCLE_BRANCH', '') != 'main':
+if os.environ.get('CIRCLE_JOB') and os.environ['CIRCLE_BRANCH'] != 'main':
     # For PR, name is set to its ref
     switcher_version = os.environ['CIRCLE_BRANCH']
 elif ".dev" in version:
diff --git a/numpy/typing/tests/test_typing.py b/numpy/typing/tests/test_typing.py
index ad61f637475b..f7cab5a7a9fb 100644
--- a/numpy/typing/tests/test_typing.py
+++ b/numpy/typing/tests/test_typing.py
@@ -84,7 +84,7 @@ def run_mypy() -> None:
     """
     if (
         os.path.isdir(CACHE_DIR)
-        and bool(os.environ.get("NUMPY_TYPING_TEST_CLEAR_CACHE", "True"))
+        and bool(os.environ.get("NUMPY_TYPING_TEST_CLEAR_CACHE", True))  # noqa: PLW1508
     ):
         shutil.rmtree(CACHE_DIR)
 

From 26cb46d7d1323509aef242cceb9cee096a97ee12 Mon Sep 17 00:00:00 2001
From: Dimitri Papadopoulos
 <3234522+DimitriPapadopoulos@users.noreply.github.com>
Date: Fri, 18 Apr 2025 16:33:11 +0200
Subject: [PATCH 067/202] MNT: Better solution for PLW0108

Co-authored-by: Joren Hammudoglu 
---
 numpy/lib/_function_base_impl.py | 4 ++--
 1 file changed, 2 insertions(+), 2 deletions(-)

diff --git a/numpy/lib/_function_base_impl.py b/numpy/lib/_function_base_impl.py
index f14378daf58b..bb4a5c7dff90 100644
--- a/numpy/lib/_function_base_impl.py
+++ b/numpy/lib/_function_base_impl.py
@@ -67,7 +67,7 @@
     # --- HYNDMAN and FAN METHODS
     # Discrete methods
     'inverted_cdf': {
-        'get_virtual_index': _inverted_cdf,
+        'get_virtual_index': lambda n, quantiles: _inverted_cdf(n, quantiles),  # noqa: PLW0108
         'fix_gamma': None,  # should never be called
     },
     'averaged_inverted_cdf': {
@@ -79,7 +79,7 @@
             where=gamma == 0),
     },
     'closest_observation': {
-        'get_virtual_index': _closest_observation,
+        'get_virtual_index': lambda n, quantiles: _closest_observation(n, quantiles),  # noqa: PLW0108
         'fix_gamma': None,  # should never be called
     },
     # Continuous methods

From 6e83c2634c4cb821dadf6a27b346c0ac11615e8a Mon Sep 17 00:00:00 2001
From: Dimitri Papadopoulos
 <3234522+DimitriPapadopoulos@users.noreply.github.com>
Date: Fri, 18 Apr 2025 18:36:57 +0200
Subject: [PATCH 068/202] MNT: Apply suggestion of reviewers

Keep the function call as is, because this is a C function.
---
 numpy/_core/tests/test_numeric.py | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/numpy/_core/tests/test_numeric.py b/numpy/_core/tests/test_numeric.py
index a05d49e74b52..143a0c446044 100644
--- a/numpy/_core/tests/test_numeric.py
+++ b/numpy/_core/tests/test_numeric.py
@@ -4117,7 +4117,7 @@ def test_broadcast_error_kwargs(self):
         #gh-13455
         arrs = [np.empty((5, 6, 7))]
         mit = np.broadcast(*arrs)
-        mit2 = np.broadcast(*arrs)
+        mit2 = np.broadcast(*arrs, **{})  # noqa: PIE804
         assert_equal(mit.shape, mit2.shape)
         assert_equal(mit.ndim, mit2.ndim)
         assert_equal(mit.nd, mit2.nd)

From 1fa958dbdf63fef3ddbdaa36fbb3f4b4b72d2be0 Mon Sep 17 00:00:00 2001
From: Sayed Adel 
Date: Fri, 18 Apr 2025 02:35:28 +0200
Subject: [PATCH 069/202] BUG: Fix AVX512_SPR dispatching for SVML
 half-precision operations

During the transition from distutils CPU dispatcher to Meson, `AVX512_SPR`
dispatching was inadvertently omitted for half-precision operations. SVML
half-precision operations were not dynamically dispatched and only benefited
from `AVX512_SKX`, which led to performance reduction on Intel SPR.

This patch fixes the issue above and also moves the half-precision operations
from `loops_umath_fp.dispatch.c.src` into a separate source file
`loops_half.dispatch.c.src`. This separation is beneficial since
`loops_umath_fp.dispatch.c.src` covers SVML single/double-precision operations as
well, which would generate objects for these operations for `AVX512_SPR`
without any performance benefits, leading to unnecessary increases in binary
size.
---
 numpy/_core/code_generators/generate_umath.py | 40 ++++----
 numpy/_core/meson.build                       |  5 +
 numpy/_core/src/umath/loops.h.src             |  3 +
 .../_core/src/umath/loops_half.dispatch.c.src | 93 +++++++++++++++++++
 .../src/umath/loops_umath_fp.dispatch.c.src   | 86 +----------------
 5 files changed, 122 insertions(+), 105 deletions(-)
 create mode 100644 numpy/_core/src/umath/loops_half.dispatch.c.src

diff --git a/numpy/_core/code_generators/generate_umath.py b/numpy/_core/code_generators/generate_umath.py
index 68e0463b5e8a..8084298c5618 100644
--- a/numpy/_core/code_generators/generate_umath.py
+++ b/numpy/_core/code_generators/generate_umath.py
@@ -776,7 +776,7 @@ def english_upper(s):
     Ufunc(1, 1, None,
           docstrings.get('numpy._core.umath.arccos'),
           None,
-          TD('efd', dispatch=[('loops_umath_fp', 'efd')]),
+          TD('efd', dispatch=[('loops_umath_fp', 'fd'), ('loops_half', 'e')]),
           TD(inexact, f='acos', astype={'e': 'f'}),
           TD(P, f='arccos'),
           ),
@@ -784,7 +784,7 @@ def english_upper(s):
     Ufunc(1, 1, None,
           docstrings.get('numpy._core.umath.arccosh'),
           None,
-          TD('efd', dispatch=[('loops_umath_fp', 'efd')]),
+          TD('efd', dispatch=[('loops_umath_fp', 'fd'), ('loops_half', 'e')]),
           TD(inexact, f='acosh', astype={'e': 'f'}),
           TD(P, f='arccosh'),
           ),
@@ -792,7 +792,7 @@ def english_upper(s):
     Ufunc(1, 1, None,
           docstrings.get('numpy._core.umath.arcsin'),
           None,
-          TD('efd', dispatch=[('loops_umath_fp', 'efd')]),
+          TD('efd', dispatch=[('loops_umath_fp', 'fd'), ('loops_half', 'e')]),
           TD(inexact, f='asin', astype={'e': 'f'}),
           TD(P, f='arcsin'),
           ),
@@ -800,7 +800,7 @@ def english_upper(s):
     Ufunc(1, 1, None,
           docstrings.get('numpy._core.umath.arcsinh'),
           None,
-          TD('efd', dispatch=[('loops_umath_fp', 'efd')]),
+          TD('efd', dispatch=[('loops_umath_fp', 'fd'), ('loops_half', 'e')]),
           TD(inexact, f='asinh', astype={'e': 'f'}),
           TD(P, f='arcsinh'),
           ),
@@ -808,7 +808,7 @@ def english_upper(s):
     Ufunc(1, 1, None,
           docstrings.get('numpy._core.umath.arctan'),
           None,
-          TD('efd', dispatch=[('loops_umath_fp', 'efd')]),
+          TD('efd', dispatch=[('loops_umath_fp', 'fd'), ('loops_half', 'e')]),
           TD(inexact, f='atan', astype={'e': 'f'}),
           TD(P, f='arctan'),
           ),
@@ -816,7 +816,7 @@ def english_upper(s):
     Ufunc(1, 1, None,
           docstrings.get('numpy._core.umath.arctanh'),
           None,
-          TD('efd', dispatch=[('loops_umath_fp', 'efd')]),
+          TD('efd', dispatch=[('loops_umath_fp', 'fd'), ('loops_half', 'e')]),
           TD(inexact, f='atanh', astype={'e': 'f'}),
           TD(P, f='arctanh'),
           ),
@@ -824,7 +824,7 @@ def english_upper(s):
     Ufunc(1, 1, None,
           docstrings.get('numpy._core.umath.cos'),
           None,
-          TD('e', dispatch=[('loops_umath_fp', 'e')]),
+          TD('e', dispatch=[('loops_half', 'e')]),
           TD('f', dispatch=[('loops_trigonometric', 'f')]),
           TD('d', dispatch=[('loops_trigonometric', 'd')]),
           TD('g' + cmplx, f='cos'),
@@ -834,7 +834,7 @@ def english_upper(s):
     Ufunc(1, 1, None,
           docstrings.get('numpy._core.umath.sin'),
           None,
-          TD('e', dispatch=[('loops_umath_fp', 'e')]),
+          TD('e', dispatch=[('loops_half', 'e')]),
           TD('f', dispatch=[('loops_trigonometric', 'f')]),
           TD('d', dispatch=[('loops_trigonometric', 'd')]),
           TD('g' + cmplx, f='sin'),
@@ -844,7 +844,7 @@ def english_upper(s):
     Ufunc(1, 1, None,
           docstrings.get('numpy._core.umath.tan'),
           None,
-          TD('efd', dispatch=[('loops_umath_fp', 'efd')]),
+          TD('efd', dispatch=[('loops_umath_fp', 'fd'), ('loops_half', 'e')]),
           TD(inexact, f='tan', astype={'e': 'f'}),
           TD(P, f='tan'),
           ),
@@ -852,7 +852,7 @@ def english_upper(s):
     Ufunc(1, 1, None,
           docstrings.get('numpy._core.umath.cosh'),
           None,
-          TD('efd', dispatch=[('loops_umath_fp', 'efd')]),
+          TD('efd', dispatch=[('loops_umath_fp', 'fd'), ('loops_half', 'e')]),
           TD(inexact, f='cosh', astype={'e': 'f'}),
           TD(P, f='cosh'),
           ),
@@ -860,7 +860,7 @@ def english_upper(s):
     Ufunc(1, 1, None,
           docstrings.get('numpy._core.umath.sinh'),
           None,
-          TD('efd', dispatch=[('loops_umath_fp', 'efd')]),
+          TD('efd', dispatch=[('loops_umath_fp', 'fd'), ('loops_half', 'e')]),
           TD(inexact, f='sinh', astype={'e': 'f'}),
           TD(P, f='sinh'),
           ),
@@ -868,7 +868,7 @@ def english_upper(s):
     Ufunc(1, 1, None,
           docstrings.get('numpy._core.umath.tanh'),
           None,
-          TD('e', dispatch=[('loops_umath_fp', 'e')]),
+          TD('e', dispatch=[('loops_half', 'e')]),
           TD('fd', dispatch=[('loops_hyperbolic', 'fd')]),
           TD(inexact, f='tanh', astype={'e': 'f'}),
           TD(P, f='tanh'),
@@ -877,7 +877,7 @@ def english_upper(s):
     Ufunc(1, 1, None,
           docstrings.get('numpy._core.umath.exp'),
           None,
-          TD('e', dispatch=[('loops_umath_fp', 'e')]),
+          TD('e', dispatch=[('loops_half', 'e')]),
           TD('fd', dispatch=[('loops_exponent_log', 'fd')]),
           TD('fdg' + cmplx, f='exp'),
           TD(P, f='exp'),
@@ -886,7 +886,7 @@ def english_upper(s):
     Ufunc(1, 1, None,
           docstrings.get('numpy._core.umath.exp2'),
           None,
-          TD('efd', dispatch=[('loops_umath_fp', 'efd')]),
+          TD('efd', dispatch=[('loops_umath_fp', 'fd'), ('loops_half', 'e')]),
           TD(inexact, f='exp2', astype={'e': 'f'}),
           TD(P, f='exp2'),
           ),
@@ -894,7 +894,7 @@ def english_upper(s):
     Ufunc(1, 1, None,
           docstrings.get('numpy._core.umath.expm1'),
           None,
-          TD('efd', dispatch=[('loops_umath_fp', 'efd')]),
+          TD('efd', dispatch=[('loops_umath_fp', 'fd'), ('loops_half', 'e')]),
           TD(inexact, f='expm1', astype={'e': 'f'}),
           TD(P, f='expm1'),
           ),
@@ -902,7 +902,7 @@ def english_upper(s):
     Ufunc(1, 1, None,
           docstrings.get('numpy._core.umath.log'),
           None,
-          TD('e', dispatch=[('loops_umath_fp', 'e')]),
+          TD('e', dispatch=[('loops_half', 'e')]),
           TD('fd', dispatch=[('loops_exponent_log', 'fd')]),
           TD('fdg' + cmplx, f='log'),
           TD(P, f='log'),
@@ -911,7 +911,7 @@ def english_upper(s):
     Ufunc(1, 1, None,
           docstrings.get('numpy._core.umath.log2'),
           None,
-          TD('efd', dispatch=[('loops_umath_fp', 'efd')]),
+          TD('efd', dispatch=[('loops_umath_fp', 'fd'), ('loops_half', 'e')]),
           TD(inexact, f='log2', astype={'e': 'f'}),
           TD(P, f='log2'),
           ),
@@ -919,7 +919,7 @@ def english_upper(s):
     Ufunc(1, 1, None,
           docstrings.get('numpy._core.umath.log10'),
           None,
-          TD('efd', dispatch=[('loops_umath_fp', 'efd')]),
+          TD('efd', dispatch=[('loops_umath_fp', 'fd'), ('loops_half', 'e')]),
           TD(inexact, f='log10', astype={'e': 'f'}),
           TD(P, f='log10'),
           ),
@@ -927,7 +927,7 @@ def english_upper(s):
     Ufunc(1, 1, None,
           docstrings.get('numpy._core.umath.log1p'),
           None,
-          TD('efd', dispatch=[('loops_umath_fp', 'efd')]),
+          TD('efd', dispatch=[('loops_umath_fp', 'fd'), ('loops_half', 'e')]),
           TD(inexact, f='log1p', astype={'e': 'f'}),
           TD(P, f='log1p'),
           ),
@@ -944,7 +944,7 @@ def english_upper(s):
     Ufunc(1, 1, None,
           docstrings.get('numpy._core.umath.cbrt'),
           None,
-          TD('efd', dispatch=[('loops_umath_fp', 'efd')]),
+          TD('efd', dispatch=[('loops_umath_fp', 'fd'), ('loops_half', 'e')]),
           TD(flts, f='cbrt', astype={'e': 'f'}),
           TD(P, f='cbrt'),
           ),
diff --git a/numpy/_core/meson.build b/numpy/_core/meson.build
index d1c78910b2a3..8569297edf43 100644
--- a/numpy/_core/meson.build
+++ b/numpy/_core/meson.build
@@ -1039,6 +1039,11 @@ foreach gen_mtargets : [
       LSX,
     ]
   ],
+  [
+    'loops_half.dispatch.h',
+    src_file.process('src/umath/loops_half.dispatch.c.src'),
+    [AVX512_SPR, AVX512_SKX]
+  ],
 ]
   mtargets = mod_features.multi_targets(
     gen_mtargets[0], umath_gen_headers + gen_mtargets[1],
diff --git a/numpy/_core/src/umath/loops.h.src b/numpy/_core/src/umath/loops.h.src
index f775bc22b8a8..3639345d2cd3 100644
--- a/numpy/_core/src/umath/loops.h.src
+++ b/numpy/_core/src/umath/loops.h.src
@@ -348,6 +348,9 @@ NPY_CPU_DISPATCH_DECLARE(NPY_NO_EXPORT void @TYPE@_@func@,
 /**end repeat1**/
 /**end repeat**/
 
+#ifndef NPY_DISABLE_OPTIMIZATION
+    #include "loops_half.dispatch.h"
+#endif
 /**begin repeat
  * #func = sin, cos, tan, exp, exp2, log, log2, log10, expm1, log1p, cbrt, arcsin, arccos, arctan, sinh, cosh, tanh, arcsinh, arccosh, arctanh#
  */
diff --git a/numpy/_core/src/umath/loops_half.dispatch.c.src b/numpy/_core/src/umath/loops_half.dispatch.c.src
new file mode 100644
index 000000000000..82f763e3d43c
--- /dev/null
+++ b/numpy/_core/src/umath/loops_half.dispatch.c.src
@@ -0,0 +1,93 @@
+#include "numpy/npy_math.h"
+#include "simd/simd.h"
+#include "loops_utils.h"
+#include "loops.h"
+#include "npy_svml.h"
+#include "fast_loop_macros.h"
+
+
+#define NPY__SVML_IS_ENABLED (NPY_SIMD && defined(NPY_HAVE_AVX512_SKX) && defined(NPY_CAN_LINK_SVML))
+
+#if NPY__SVML_IS_ENABLED && !defined(NPY_HAVE_AVX512_SPR)
+
+typedef __m256i npyvh_f16;
+#define npyv_cvt_f16_f32 _mm512_cvtph_ps
+#define npyv_cvt_f32_f16 _mm512_cvtps_ph
+#define npyvh_load_f16(PTR) _mm256_loadu_si256((const __m256i*)(PTR))
+#define npyvh_store_f16(PTR, data) _mm256_storeu_si256((__m256i*)PTR, data)
+NPY_FINLINE npyvh_f16 npyvh_load_till_f16(const npy_half *ptr, npy_uintp nlane, npy_half fill)
+{
+    assert(nlane > 0);
+    const __m256i vfill = _mm256_set1_epi16(fill);
+    const __mmask16 mask = (0x0001 << nlane) - 0x0001;
+    return _mm256_mask_loadu_epi16(vfill, mask, ptr);
+}
+NPY_FINLINE void npyvh_store_till_f16(npy_half *ptr, npy_uintp nlane, npyvh_f16 data)
+{
+    assert(nlane > 0);
+    const __mmask16 mask = (0x0001 << nlane) - 0x0001;
+    _mm256_mask_storeu_epi16(ptr, mask, data);
+}
+
+/**begin repeat
+ * #func = sin, cos, tan, exp, exp2, expm1, log, log2, log10, log1p, cbrt, asin, acos, atan, sinh, cosh, tanh, asinh, acosh, atanh#
+ * #default_val = 0, 0, 0, 0, 0, 0x3c00, 0x3c00, 0x3c00, 0x3c00, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0x3c00, 0#
+ */
+static void
+avx512_@func@_f16(const npy_half *src, npy_half *dst, npy_intp len)
+{
+    const int num_lanes = npyv_nlanes_f32;
+    npyvh_f16 x, out;
+    npyv_f32 x_ps, out_ps;
+    for (; len > 0; len -= num_lanes, src += num_lanes, dst += num_lanes) {
+        if (len >= num_lanes) {
+            x       = npyvh_load_f16(src);
+            x_ps    = npyv_cvt_f16_f32(x);
+            out_ps  = __svml_@func@f16(x_ps);
+            out     = npyv_cvt_f32_f16(out_ps, 0);
+            npyvh_store_f16(dst, out);
+        }
+        else {
+            x       = npyvh_load_till_f16(src, len, @default_val@);
+            x_ps    = npyv_cvt_f16_f32(x);
+            out_ps  = __svml_@func@f16(x_ps);
+            out     = npyv_cvt_f32_f16(out_ps, 0);
+            npyvh_store_till_f16(dst, len, out);
+        }
+    }
+    npyv_cleanup();
+}
+/**end repeat**/
+#endif // NPY__SVML_IS_ENABLED
+
+/**begin repeat
+ *  #func = sin, cos, tan, exp, exp2, expm1, log, log2, log10, log1p, cbrt, arcsin, arccos, arctan, sinh, cosh, tanh, arcsinh, arccosh, arctanh#
+ *  #intrin = sin, cos, tan, exp, exp2, expm1, log, log2, log10, log1p, cbrt, asin, acos, atan, sinh, cosh, tanh, asinh, acosh, atanh#
+ */
+NPY_NO_EXPORT void NPY_CPU_DISPATCH_CURFX(HALF_@func@)
+(char **args, npy_intp const *dimensions, npy_intp const *steps, void *NPY_UNUSED(data))
+{
+#if NPY__SVML_IS_ENABLED
+    const npy_half *src = (npy_half*)args[0];
+          npy_half *dst = (npy_half*)args[1];
+
+    const npy_intp len = dimensions[0];
+
+    if (!is_mem_overlap(src, steps[0], dst, steps[1], len) &&
+        (steps[0] == sizeof(npy_half)) &&
+        (steps[1] == sizeof(npy_half))) {
+    #ifdef NPY_HAVE_AVX512_SPR
+        __svml_@intrin@s32(src, dst, len);
+    #else
+        avx512_@intrin@_f16(src, dst, len);
+    #endif
+        return;
+    }
+#endif // NPY__SVML_IS_ENABLED
+    UNARY_LOOP {
+        const npy_float in1 = npy_half_to_float(*(npy_half *)ip1);
+        *((npy_half *)op1) = npy_float_to_half(npy_@intrin@f(in1));
+    }
+}
+/**end repeat**/
+
diff --git a/numpy/_core/src/umath/loops_umath_fp.dispatch.c.src b/numpy/_core/src/umath/loops_umath_fp.dispatch.c.src
index c79d872311b7..25edf44cf677 100644
--- a/numpy/_core/src/umath/loops_umath_fp.dispatch.c.src
+++ b/numpy/_core/src/umath/loops_umath_fp.dispatch.c.src
@@ -1,5 +1,5 @@
 /*@targets
- ** $maxopt baseline avx512_skx avx512_spr
+ ** $maxopt baseline avx512_skx
  */
 #include "numpy/npy_math.h"
 #include "simd/simd.h"
@@ -98,91 +98,7 @@ simd_@func@_@sfx@(const npyv_lanetype_@sfx@ *src1, npy_intp ssrc1,
 }
 /**end repeat1**/
 /**end repeat**/
-
-typedef __m256i npyvh_f16;
-#define npyv_cvt_f16_f32 _mm512_cvtph_ps
-#define npyv_cvt_f32_f16 _mm512_cvtps_ph
-#define npyvh_load_f16(PTR) _mm256_loadu_si256((const __m256i*)(PTR))
-#define npyvh_store_f16(PTR, data) _mm256_storeu_si256((__m256i*)PTR, data)
-NPY_FINLINE npyvh_f16 npyvh_load_till_f16(const npy_half *ptr, npy_uintp nlane, npy_half fill)
-{
-    assert(nlane > 0);
-    const __m256i vfill = _mm256_set1_epi16(fill);
-    const __mmask16 mask = (0x0001 << nlane) - 0x0001;
-    return _mm256_mask_loadu_epi16(vfill, mask, ptr);
-}
-NPY_FINLINE void npyvh_store_till_f16(npy_half *ptr, npy_uintp nlane, npyvh_f16 data)
-{
-    assert(nlane > 0);
-    const __mmask16 mask = (0x0001 << nlane) - 0x0001;
-    _mm256_mask_storeu_epi16(ptr, mask, data);
-}
-
-/**begin repeat
- * #func = sin, cos, tan, exp, exp2, expm1, log, log2, log10, log1p, cbrt, asin, acos, atan, sinh, cosh, tanh, asinh, acosh, atanh#
- * #default_val = 0, 0, 0, 0, 0, 0x3c00, 0x3c00, 0x3c00, 0x3c00, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0x3c00, 0#
- */
-static void
-avx512_@func@_f16(const npy_half *src, npy_half *dst, npy_intp len)
-{
-    const int num_lanes = npyv_nlanes_f32;
-    npyvh_f16 x, out;
-    npyv_f32 x_ps, out_ps;
-    for (; len > 0; len -= num_lanes, src += num_lanes, dst += num_lanes) {
-        if (len >= num_lanes) {
-            x       = npyvh_load_f16(src);
-            x_ps    = npyv_cvt_f16_f32(x);
-            out_ps  = __svml_@func@f16(x_ps);
-            out     = npyv_cvt_f32_f16(out_ps, 0);
-            npyvh_store_f16(dst, out);
-        }
-        else {
-            x       = npyvh_load_till_f16(src, len, @default_val@);
-            x_ps    = npyv_cvt_f16_f32(x);
-            out_ps  = __svml_@func@f16(x_ps);
-            out     = npyv_cvt_f32_f16(out_ps, 0);
-            npyvh_store_till_f16(dst, len, out);
-        }
-    }
-    npyv_cleanup();
-}
-/**end repeat**/
-#endif
-
-/**begin repeat
- *  #func = sin, cos, tan, exp, exp2, expm1, log, log2, log10, log1p, cbrt, arcsin, arccos, arctan, sinh, cosh, tanh, arcsinh, arccosh, arctanh#
- *  #intrin = sin, cos, tan, exp, exp2, expm1, log, log2, log10, log1p, cbrt, asin, acos, atan, sinh, cosh, tanh, asinh, acosh, atanh#
- */
-NPY_NO_EXPORT void NPY_CPU_DISPATCH_CURFX(HALF_@func@)
-(char **args, npy_intp const *dimensions, npy_intp const *steps, void *NPY_UNUSED(data))
-{
-#if defined(NPY_HAVE_AVX512_SPR) || defined(NPY_HAVE_AVX512_SKX)
-#if NPY_SIMD && defined(NPY_CAN_LINK_SVML)
-    const npy_half *src = (npy_half*)args[0];
-          npy_half *dst = (npy_half*)args[1];
-
-    const npy_intp len = dimensions[0];
-
-    if (!is_mem_overlap(src, steps[0], dst, steps[1], len) &&
-        (steps[0] == sizeof(npy_half)) &&
-        (steps[1] == sizeof(npy_half))) {
-#if defined(NPY_HAVE_AVX512_SPR)
-        __svml_@intrin@s32(src, dst, len);
-        return;
-#endif
-#if defined(NPY_HAVE_AVX512_SKX)
-        avx512_@intrin@_f16(src, dst, len);
-        return;
 #endif
-    }
-#endif // NPY_SIMD && NPY_CAN_LINK_SVML
-#endif // SPR or SKX
-    UNARY_LOOP {
-        const npy_float in1 = npy_half_to_float(*(npy_half *)ip1);
-        *((npy_half *)op1) = npy_float_to_half(npy_@intrin@f(in1));
-    }
-}
-/**end repeat**/
 
 /**begin repeat
  *  #TYPE = DOUBLE, FLOAT#

From aa4f974c2f9905ac05b395a35bf14ea4d0fb9499 Mon Sep 17 00:00:00 2001
From: Roy Smart 
Date: Fri, 18 Apr 2025 15:59:47 -0500
Subject: [PATCH 070/202] BUG: Re-enable overriding functions in the
 `np.strings` module. (#28741)

* Enable overriding the `mod`, `encode`, `decode`, `upper`, `lower`, `swapcase`, `capitalize`, `title`, `_join`, `_split`, `_rsplit`, `_splitlines`, and `translate` functions in the `np.strings` module.

* Added tests

* changelog entry

* linting

* oversight

* test fixes

* override more functions

* Simplify changelog
---
 doc/release/upcoming_changes/28741.change.rst |  1 +
 numpy/_core/strings.py                        | 80 ++++++++++++++++++-
 numpy/_core/tests/test_strings.py             | 68 ++++++++++++++++
 3 files changed, 148 insertions(+), 1 deletion(-)
 create mode 100644 doc/release/upcoming_changes/28741.change.rst

diff --git a/doc/release/upcoming_changes/28741.change.rst b/doc/release/upcoming_changes/28741.change.rst
new file mode 100644
index 000000000000..ca9531f490d8
--- /dev/null
+++ b/doc/release/upcoming_changes/28741.change.rst
@@ -0,0 +1 @@
+Re-enable overriding functions in the :mod:`numpy.strings` module.
diff --git a/numpy/_core/strings.py b/numpy/_core/strings.py
index 429d79656381..befd76d8ceed 100644
--- a/numpy/_core/strings.py
+++ b/numpy/_core/strings.py
@@ -4,13 +4,14 @@
 """
 
 import sys
+import functools
 import numpy as np
 from numpy import (
     equal, not_equal, less, less_equal, greater, greater_equal,
     add, multiply as _multiply_ufunc,
 )
 from numpy._core.multiarray import _vec_string
-from numpy._core.overrides import set_module
+from numpy._core.overrides import set_module, array_function_dispatch
 from numpy._core.umath import (
     isalpha,
     isdigit,
@@ -84,6 +85,9 @@ def _override___module__():
 
 MAX = np.iinfo(np.int64).max
 
+array_function_dispatch = functools.partial(
+    array_function_dispatch, module='numpy.strings')
+
 
 def _get_num_chars(a):
     """
@@ -130,7 +134,12 @@ def _clean_args(*args):
     return newargs
 
 
+def _multiply_dispatcher(a, i):
+    return (a,)
+
+
 @set_module("numpy.strings")
+@array_function_dispatch(_multiply_dispatcher)
 def multiply(a, i):
     """
     Return (a * i), that is string multiple concatenation,
@@ -194,7 +203,12 @@ def multiply(a, i):
     return _multiply_ufunc(a, i, out=out)
 
 
+def _mod_dispatcher(a, values):
+    return (a, values)
+
+
 @set_module("numpy.strings")
+@array_function_dispatch(_mod_dispatcher)
 def mod(a, values):
     """
     Return (a % i), that is pre-Python 2.6 string formatting
@@ -507,7 +521,12 @@ def endswith(a, suffix, start=0, end=None):
     return _endswith_ufunc(a, suffix, start, end)
 
 
+def _code_dispatcher(a, encoding=None, errors=None):
+    return (a,)
+
+
 @set_module("numpy.strings")
+@array_function_dispatch(_code_dispatcher)
 def decode(a, encoding=None, errors=None):
     r"""
     Calls :meth:`bytes.decode` element-wise.
@@ -556,6 +575,7 @@ def decode(a, encoding=None, errors=None):
 
 
 @set_module("numpy.strings")
+@array_function_dispatch(_code_dispatcher)
 def encode(a, encoding=None, errors=None):
     """
     Calls :meth:`str.encode` element-wise.
@@ -600,7 +620,12 @@ def encode(a, encoding=None, errors=None):
         np.bytes_(b''))
 
 
+def _expandtabs_dispatcher(a, tabsize=None):
+    return (a,)
+
+
 @set_module("numpy.strings")
+@array_function_dispatch(_expandtabs_dispatcher)
 def expandtabs(a, tabsize=8):
     """
     Return a copy of each string element where all tab characters are
@@ -652,7 +677,12 @@ def expandtabs(a, tabsize=8):
     return _expandtabs(a, tabsize, out=out)
 
 
+def _just_dispatcher(a, width, fillchar=None):
+    return (a,)
+
+
 @set_module("numpy.strings")
+@array_function_dispatch(_just_dispatcher)
 def center(a, width, fillchar=' '):
     """
     Return a copy of `a` with its elements centered in a string of
@@ -721,6 +751,7 @@ def center(a, width, fillchar=' '):
 
 
 @set_module("numpy.strings")
+@array_function_dispatch(_just_dispatcher)
 def ljust(a, width, fillchar=' '):
     """
     Return an array with the elements of `a` left-justified in a
@@ -785,6 +816,7 @@ def ljust(a, width, fillchar=' '):
 
 
 @set_module("numpy.strings")
+@array_function_dispatch(_just_dispatcher)
 def rjust(a, width, fillchar=' '):
     """
     Return an array with the elements of `a` right-justified in a
@@ -848,7 +880,12 @@ def rjust(a, width, fillchar=' '):
     return _rjust(a, width, fillchar, out=out)
 
 
+def _zfill_dispatcher(a, width):
+    return (a,)
+
+
 @set_module("numpy.strings")
+@array_function_dispatch(_zfill_dispatcher)
 def zfill(a, width):
     """
     Return the numeric string left-filled with zeros. A leading
@@ -1033,7 +1070,12 @@ def strip(a, chars=None):
     return _strip_chars(a, chars)
 
 
+def _unary_op_dispatcher(a):
+    return (a,)
+
+
 @set_module("numpy.strings")
+@array_function_dispatch(_unary_op_dispatcher)
 def upper(a):
     """
     Return an array with the elements converted to uppercase.
@@ -1071,6 +1113,7 @@ def upper(a):
 
 
 @set_module("numpy.strings")
+@array_function_dispatch(_unary_op_dispatcher)
 def lower(a):
     """
     Return an array with the elements converted to lowercase.
@@ -1108,6 +1151,7 @@ def lower(a):
 
 
 @set_module("numpy.strings")
+@array_function_dispatch(_unary_op_dispatcher)
 def swapcase(a):
     """
     Return element-wise a copy of the string with
@@ -1148,6 +1192,7 @@ def swapcase(a):
 
 
 @set_module("numpy.strings")
+@array_function_dispatch(_unary_op_dispatcher)
 def capitalize(a):
     """
     Return a copy of ``a`` with only the first character of each element
@@ -1188,6 +1233,7 @@ def capitalize(a):
 
 
 @set_module("numpy.strings")
+@array_function_dispatch(_unary_op_dispatcher)
 def title(a):
     """
     Return element-wise title cased version of string or unicode.
@@ -1229,7 +1275,12 @@ def title(a):
     return _vec_string(a_arr, a_arr.dtype, 'title')
 
 
+def _replace_dispatcher(a, old, new, count=None):
+    return (a,)
+
+
 @set_module("numpy.strings")
+@array_function_dispatch(_replace_dispatcher)
 def replace(a, old, new, count=-1):
     """
     For each element in ``a``, return a copy of the string with
@@ -1293,6 +1344,11 @@ def replace(a, old, new, count=-1):
     return _replace(arr, old, new, counts, out=out)
 
 
+def _join_dispatcher(sep, seq):
+    return (sep, seq)
+
+
+@array_function_dispatch(_join_dispatcher)
 def _join(sep, seq):
     """
     Return a string which is the concatenation of the strings in the
@@ -1329,6 +1385,11 @@ def _join(sep, seq):
         _vec_string(sep, np.object_, 'join', (seq,)), seq)
 
 
+def _split_dispatcher(a, sep=None, maxsplit=None):
+    return (a,)
+
+
+@array_function_dispatch(_split_dispatcher)
 def _split(a, sep=None, maxsplit=None):
     """
     For each element in `a`, return a list of the words in the
@@ -1373,6 +1434,7 @@ def _split(a, sep=None, maxsplit=None):
         a, np.object_, 'split', [sep] + _clean_args(maxsplit))
 
 
+@array_function_dispatch(_split_dispatcher)
 def _rsplit(a, sep=None, maxsplit=None):
     """
     For each element in `a`, return a list of the words in the
@@ -1418,6 +1480,11 @@ def _rsplit(a, sep=None, maxsplit=None):
         a, np.object_, 'rsplit', [sep] + _clean_args(maxsplit))
 
 
+def _splitlines_dispatcher(a, keepends=None):
+    return (a,)
+
+
+@array_function_dispatch(_splitlines_dispatcher)
 def _splitlines(a, keepends=None):
     """
     For each element in `a`, return a list of the lines in the
@@ -1455,7 +1522,12 @@ def _splitlines(a, keepends=None):
         a, np.object_, 'splitlines', _clean_args(keepends))
 
 
+def _partition_dispatcher(a, sep):
+    return (a,)
+
+
 @set_module("numpy.strings")
+@array_function_dispatch(_partition_dispatcher)
 def partition(a, sep):
     """
     Partition each element in ``a`` around ``sep``.
@@ -1524,6 +1596,7 @@ def partition(a, sep):
 
 
 @set_module("numpy.strings")
+@array_function_dispatch(_partition_dispatcher)
 def rpartition(a, sep):
     """
     Partition (split) each element around the right-most separator.
@@ -1592,7 +1665,12 @@ def rpartition(a, sep):
         a, sep, pos, out=(out["f0"], out["f1"], out["f2"]))
 
 
+def _translate_dispatcher(a, table, deletechars=None):
+    return (a,)
+
+
 @set_module("numpy.strings")
+@array_function_dispatch(_translate_dispatcher)
 def translate(a, table, deletechars=None):
     """
     For each element in `a`, return a copy of the string where all
diff --git a/numpy/_core/tests/test_strings.py b/numpy/_core/tests/test_strings.py
index d0355e9817a2..40d830c3d4a4 100644
--- a/numpy/_core/tests/test_strings.py
+++ b/numpy/_core/tests/test_strings.py
@@ -1367,3 +1367,71 @@ def test_replace_broadcasting(self, dt):
                                         dtype=dt))
         r3 = np.strings.replace(a, ["0", "0,0", "0,0,0"], "X")
         assert_array_equal(r3, np.array(["X,X,X", "X,0", "X"], dtype=dt))
+
+
+class TestOverride:
+    @classmethod
+    def setup_class(cls):
+        class Override:
+
+            def __array_function__(self, *args, **kwargs):
+                return "function"
+
+            def __array_ufunc__(self, *args, **kwargs):
+                return "ufunc"
+
+        cls.override = Override()
+
+    @pytest.mark.parametrize("func, kwargs", [
+        (np.strings.center, dict(width=10)),
+        (np.strings.capitalize, {}),
+        (np.strings.decode, {}),
+        (np.strings.encode, {}),
+        (np.strings.expandtabs, {}),
+        (np.strings.ljust, dict(width=10)),
+        (np.strings.lower, {}),
+        (np.strings.mod, dict(values=2)),
+        (np.strings.multiply, dict(i=2)),
+        (np.strings.partition, dict(sep="foo")),
+        (np.strings.rjust, dict(width=10)),
+        (np.strings.rpartition, dict(sep="foo")),
+        (np.strings.swapcase, {}),
+        (np.strings.title, {}),
+        (np.strings.translate, dict(table=None)),
+        (np.strings.upper, {}),
+        (np.strings.zfill, dict(width=10)),
+    ])
+    def test_override_function(self, func, kwargs):
+        assert func(self.override, **kwargs) == "function"
+
+    @pytest.mark.parametrize("func, args, kwargs", [
+        (np.strings.add, (None, ), {}),
+        (np.strings.lstrip, (), {}),
+        (np.strings.rstrip, (), {}),
+        (np.strings.strip, (), {}),
+        (np.strings.equal, (None, ), {}),
+        (np.strings.not_equal, (None, ), {}),
+        (np.strings.greater_equal, (None, ), {}),
+        (np.strings.less_equal, (None, ), {}),
+        (np.strings.greater, (None, ), {}),
+        (np.strings.less, (None, ), {}),
+        (np.strings.count, ("foo", ), {}),
+        (np.strings.endswith, ("foo", ), {}),
+        (np.strings.find, ("foo", ), {}),
+        (np.strings.index, ("foo", ), {}),
+        (np.strings.isalnum, (), {}),
+        (np.strings.isalpha, (), {}),
+        (np.strings.isdecimal, (), {}),
+        (np.strings.isdigit, (), {}),
+        (np.strings.islower, (), {}),
+        (np.strings.isnumeric, (), {}),
+        (np.strings.isspace, (), {}),
+        (np.strings.istitle, (), {}),
+        (np.strings.isupper, (), {}),
+        (np.strings.rfind, ("foo", ), {}),
+        (np.strings.rindex, ("foo", ), {}),
+        (np.strings.startswith, ("foo", ), {}),
+        (np.strings.str_len, (), {}),
+    ])
+    def test_override_ufunc(self, func, args, kwargs):
+        assert func(self.override, *args, **kwargs) == "ufunc"

From c6c6a37b6e523195b67991360f4b9ebddcd6006a Mon Sep 17 00:00:00 2001
From: Ihar Hrachyshka 
Date: Fri, 18 Apr 2025 16:24:58 -0400
Subject: [PATCH 071/202] ENH: Include offset in error message when fallocate()
 fails

When the error happens, it may be useful to know if it's the `fd` file
that got too large, or some other file did. Including the current fd
offset in the error message gives a hint which case it is.

Signed-off-by: Ihar Hrachyshka 
---
 numpy/_core/src/multiarray/convert.c | 7 +++++--
 1 file changed, 5 insertions(+), 2 deletions(-)

diff --git a/numpy/_core/src/multiarray/convert.c b/numpy/_core/src/multiarray/convert.c
index 555c187cd5a3..8e0177616955 100644
--- a/numpy/_core/src/multiarray/convert.c
+++ b/numpy/_core/src/multiarray/convert.c
@@ -44,6 +44,7 @@ npy_fallocate(npy_intp nbytes, FILE * fp)
      */
 #if defined(HAVE_FALLOCATE) && defined(__linux__)
     int r;
+    npy_intp offset;
     /* small files not worth the system call */
     if (nbytes < 16 * 1024 * 1024) {
         return 0;
@@ -60,7 +61,8 @@ npy_fallocate(npy_intp nbytes, FILE * fp)
      * the flag "1" (=FALLOC_FL_KEEP_SIZE) is needed for the case of files
      * opened in append mode (issue #8329)
      */
-    r = fallocate(fileno(fp), 1, npy_ftell(fp), nbytes);
+    offset = npy_ftell(fp);
+    r = fallocate(fileno(fp), 1, offset, nbytes);
     NPY_END_ALLOW_THREADS;
 
     /*
@@ -68,7 +70,8 @@ npy_fallocate(npy_intp nbytes, FILE * fp)
      */
     if (r == -1 && errno == ENOSPC) {
         PyErr_Format(PyExc_OSError, "Not enough free space to write "
-                     "%"NPY_INTP_FMT" bytes", nbytes);
+                     "%"NPY_INTP_FMT" bytes after offset %"NPY_INTP_FMT,
+                     nbytes, offset);
         return -1;
     }
 #endif

From 2c7b0e44fea60db1aacb4d2f2b009e51726b3774 Mon Sep 17 00:00:00 2001
From: Dimitri Papadopoulos Orfanos
 <3234522+DimitriPapadopoulos@users.noreply.github.com>
Date: Sat, 19 Apr 2025 14:05:29 +0200
Subject: [PATCH 072/202] MNT: Enforce ruff/pyupgrade rules (UP) (#28770)

---
 numpy/_core/tests/test_multiarray.py | 2 +-
 ruff.toml                            | 3 +++
 2 files changed, 4 insertions(+), 1 deletion(-)

diff --git a/numpy/_core/tests/test_multiarray.py b/numpy/_core/tests/test_multiarray.py
index 2301c034ba0b..c90329fa1e6f 100644
--- a/numpy/_core/tests/test_multiarray.py
+++ b/numpy/_core/tests/test_multiarray.py
@@ -9053,7 +9053,7 @@ def test_exotic(self):
         e = float('-Infinity')
         assert_equal(np.where(True, d, e).dtype, np.float32)
         # With NEP 50 adopted, the float will overflow here:
-        e = float(1e150)
+        e = 1e150
         with pytest.warns(RuntimeWarning, match="overflow"):
             res = np.where(True, d, e)
         assert res.dtype == np.float32
diff --git a/ruff.toml b/ruff.toml
index 4dab12cf0aee..25b6c13fa656 100644
--- a/ruff.toml
+++ b/ruff.toml
@@ -21,6 +21,7 @@ extend-select = [
     "W",
     "PGH",
     "PLE",
+    "UP",
 ]
 ignore = [
     "F",     # TODO: enable Pyflakes rules
@@ -35,6 +36,8 @@ ignore = [
     "E721",
     "E731",
     "E741",
+    "UP015", # Unnecessary mode argument
+    "UP031", # TODO: Use format specifiers instead of percent format
 ]
 
 [lint.per-file-ignores]

From 61527980324f30824aead36cfebf1c413a8ae473 Mon Sep 17 00:00:00 2001
From: Charles Harris 
Date: Sat, 19 Apr 2025 18:44:06 -0600
Subject: [PATCH 073/202] MAINT: Update main after Numpy 2.2.5 release

- Forward port 2.2.5-notes.rst
- Forward port 2.2.5-changelog.rst
- Update .mailmap
- Update release.rst

[skip azp] [skip cirrus] [skip actions]
---
 .mailmap                           |  1 +
 doc/changelog/2.2.5-changelog.rst  | 39 ++++++++++++++++++++++
 doc/source/release.rst             |  1 +
 doc/source/release/2.2.5-notes.rst | 53 ++++++++++++++++++++++++++++++
 4 files changed, 94 insertions(+)
 create mode 100644 doc/changelog/2.2.5-changelog.rst
 create mode 100644 doc/source/release/2.2.5-notes.rst

diff --git a/.mailmap b/.mailmap
index 1ae0bce7f11a..f33dfddb6492 100644
--- a/.mailmap
+++ b/.mailmap
@@ -152,6 +152,7 @@ Ashutosh Singh  <55102089+Ashutosh619-sudo@users.nor
 Auke Wiggers 
 Austin Ran <504977925@qq.com>
 Badhri Narayanan Krishnakumar 
+Baskar Gopinath 
 Bhavuk Kalra 
 Bhavuk Kalra  
 Bangcheng Yang 
diff --git a/doc/changelog/2.2.5-changelog.rst b/doc/changelog/2.2.5-changelog.rst
new file mode 100644
index 000000000000..409c243d148e
--- /dev/null
+++ b/doc/changelog/2.2.5-changelog.rst
@@ -0,0 +1,39 @@
+
+Contributors
+============
+
+A total of 7 people contributed to this release.  People with a "+" by their
+names contributed a patch for the first time.
+
+* Charles Harris
+* Joren Hammudoglu
+* Baskar Gopinath + 
+* Nathan Goldbaum
+* Nicholas Christensen +
+* Sayed Adel
+* karl +
+
+Pull requests merged
+====================
+
+A total of 19 pull requests were merged for this release.
+
+* `#28545 `__: MAINT: Prepare 2.2.x for further development
+* `#28582 `__: BUG: Fix return type of NpyIter_GetIterNext in Cython declarations
+* `#28583 `__: BUG: avoid deadlocks with C++ shared mutex in dispatch cache
+* `#28585 `__: TYP: fix typing errors in ``_core.strings``
+* `#28631 `__: MAINT, CI: Update Ubuntu to 22.04 in azure-pipelines
+* `#28632 `__: BUG: Set writeable flag for writeable dlpacks.
+* `#28633 `__: BUG: Fix crackfortran parsing error when a division occurs within...
+* `#28650 `__: TYP: fix ``ndarray.tolist()`` and ``.item()`` for unknown dtype
+* `#28654 `__: BUG: fix deepcopying StringDType arrays (#28643)
+* `#28661 `__: TYP: Accept objects that ``write()`` to ``str`` in ``savetxt``
+* `#28663 `__: CI: Replace QEMU armhf with native (32-bit compatibility mode)
+* `#28682 `__: SIMD: Resolve Highway QSort symbol linking error on aarch32/ASIMD
+* `#28683 `__: TYP: add missing ``"b1"`` literals for ``dtype[bool]``
+* `#28705 `__: TYP: Fix false rejection of ``NDArray[object_].__abs__()``
+* `#28706 `__: TYP: Fix inconsistent ``NDArray[float64].__[r]truediv__`` return...
+* `#28723 `__: TYP: fix string-like ``ndarray`` rich comparison operators
+* `#28758 `__: TYP: some ``[arg]partition`` fixes
+* `#28772 `__: TYP: fix incorrect ``random.Generator.integers`` return type
+* `#28774 `__: TYP: fix ``count_nonzero`` signature
diff --git a/doc/source/release.rst b/doc/source/release.rst
index 0a2e5f5b4098..675b91352772 100644
--- a/doc/source/release.rst
+++ b/doc/source/release.rst
@@ -6,6 +6,7 @@ Release notes
     :maxdepth: 2
 
     2.3.0 
+    2.2.5 
     2.2.4 
     2.2.3 
     2.2.2 
diff --git a/doc/source/release/2.2.5-notes.rst b/doc/source/release/2.2.5-notes.rst
new file mode 100644
index 000000000000..e1c3205b006d
--- /dev/null
+++ b/doc/source/release/2.2.5-notes.rst
@@ -0,0 +1,53 @@
+.. currentmodule:: numpy
+
+==========================
+NumPy 2.2.5 Release Notes
+==========================
+
+NumPy 2.2.5 is a patch release that fixes bugs found after the 2.2.4 release.
+It has a large number of typing fixes/improvements as well as the normal bug
+fixes and some CI maintenance.
+
+This release supports Python versions 3.10-3.13.
+
+
+Contributors
+============
+
+A total of 7 people contributed to this release.  People with a "+" by their
+names contributed a patch for the first time.
+
+* Charles Harris
+* Joren Hammudoglu
+* Baskar Gopinath + 
+* Nathan Goldbaum
+* Nicholas Christensen +
+* Sayed Adel
+* karl +
+
+
+Pull requests merged
+====================
+
+A total of 19 pull requests were merged for this release.
+
+* `#28545 `__: MAINT: Prepare 2.2.x for further development
+* `#28582 `__: BUG: Fix return type of NpyIter_GetIterNext in Cython declarations
+* `#28583 `__: BUG: avoid deadlocks with C++ shared mutex in dispatch cache
+* `#28585 `__: TYP: fix typing errors in ``_core.strings``
+* `#28631 `__: MAINT, CI: Update Ubuntu to 22.04 in azure-pipelines
+* `#28632 `__: BUG: Set writeable flag for writeable dlpacks.
+* `#28633 `__: BUG: Fix crackfortran parsing error when a division occurs within...
+* `#28650 `__: TYP: fix ``ndarray.tolist()`` and ``.item()`` for unknown dtype
+* `#28654 `__: BUG: fix deepcopying StringDType arrays (#28643)
+* `#28661 `__: TYP: Accept objects that ``write()`` to ``str`` in ``savetxt``
+* `#28663 `__: CI: Replace QEMU armhf with native (32-bit compatibility mode)
+* `#28682 `__: SIMD: Resolve Highway QSort symbol linking error on aarch32/ASIMD
+* `#28683 `__: TYP: add missing ``"b1"`` literals for ``dtype[bool]``
+* `#28705 `__: TYP: Fix false rejection of ``NDArray[object_].__abs__()``
+* `#28706 `__: TYP: Fix inconsistent ``NDArray[float64].__[r]truediv__`` return...
+* `#28723 `__: TYP: fix string-like ``ndarray`` rich comparison operators
+* `#28758 `__: TYP: some ``[arg]partition`` fixes
+* `#28772 `__: TYP: fix incorrect ``random.Generator.integers`` return type
+* `#28774 `__: TYP: fix ``count_nonzero`` signature
+

From 0852d103c1c30fde7f98254d94b063ff93db1f66 Mon Sep 17 00:00:00 2001
From: Sayed Adel 
Date: Mon, 21 Apr 2025 04:12:37 +0200
Subject: [PATCH 074/202] BUG: Re-enable GCC function-specific optimization
 attributes

This patch restores support for function-specific optimization attributes
that were disabled during the transition from distutils to Meson.
We now properly detect and enable the following GCC attributes:

- __attribute__((optimize("O3")))
- __attribute__((optimize("unroll-loops")))
- __attribute__((nonnull(1)))
---
 numpy/_core/meson.build | 26 +++++++++++++++++++-------
 1 file changed, 19 insertions(+), 7 deletions(-)

diff --git a/numpy/_core/meson.build b/numpy/_core/meson.build
index d1c78910b2a3..5257ff09c92b 100644
--- a/numpy/_core/meson.build
+++ b/numpy/_core/meson.build
@@ -343,14 +343,26 @@ endif
 optional_function_attributes = [
   ['optimize("unroll-loops")', 'OPTIMIZE_UNROLL_LOOPS'],
   ['optimize("O3")', 'OPTIMIZE_OPT_3'],
-  ['optimize("O2")', 'OPTIMIZE_OPT_2'],
-  ['optimize("nonnull (1)")', 'NONNULL'],
+  ['nonnull(1)', 'NONNULL'],
 ]
-#foreach attr: optional_function_attributes
-#  if cc.has_function_attribute(attr[0])
-#    cdata.set10('HAVE_ATTRIBUTE_' + attr[1], true)
-#  endif
-#endforeach
+if get_option('disable-optimization') == false
+  foreach attr: optional_function_attributes
+    test_code = '''
+      __attribute__((@0@)) void test_function(void *ptr) {
+        (void*)ptr;
+        return;
+      }
+      int main(void) {
+        int dummy = 0;
+        test_function(&dummy);
+        return 0;
+      }
+    '''.format(attr[0])
+    if cc.compiles(test_code, name: '__attribute__((' + attr[0] + '))', args: ['-Werror', '-Wattributes'])
+      cdata.set10('HAVE_ATTRIBUTE_' + attr[1], true)
+    endif
+  endforeach
+endif
 
 # Max possible optimization flags. We pass this flags to all our dispatch-able
 # (multi_targets) sources.

From c8036e972cdb53dc74c5a03824f1b017acd0a7ad Mon Sep 17 00:00:00 2001
From: mikeobr 
Date: Tue, 22 Apr 2025 03:28:47 -0400
Subject: [PATCH 075/202] ENH: Prevent nanmax/nanmin from copying  memmap
 arrays (#28731)

Fixed nanmax and nanmin to special case memmap ndarrays to use the fast path. Previously
the function would create copies which is problematic for large GB+ arrays.

Closes #28721

* TST: test that memmap arrays take fast path through nanmax/min

---------

Co-authored-by: Marten H. van Kerkwijk 
---
 numpy/lib/_nanfunctions_impl.py      |  4 ++--
 numpy/lib/tests/test_nanfunctions.py | 15 +++++++++++++++
 2 files changed, 17 insertions(+), 2 deletions(-)

diff --git a/numpy/lib/_nanfunctions_impl.py b/numpy/lib/_nanfunctions_impl.py
index 24cb7587f8ba..563a8574cd13 100644
--- a/numpy/lib/_nanfunctions_impl.py
+++ b/numpy/lib/_nanfunctions_impl.py
@@ -351,7 +351,7 @@ def nanmin(a, axis=None, out=None, keepdims=np._NoValue, initial=np._NoValue,
     if where is not np._NoValue:
         kwargs['where'] = where
 
-    if type(a) is np.ndarray and a.dtype != np.object_:
+    if (type(a) is np.ndarray or type(a) is np.memmap) and a.dtype != np.object_:
         # Fast, but not safe for subclasses of ndarray, or object arrays,
         # which do not implement isnan (gh-9009), or fmin correctly (gh-8975)
         res = np.fmin.reduce(a, axis=axis, out=out, **kwargs)
@@ -480,7 +480,7 @@ def nanmax(a, axis=None, out=None, keepdims=np._NoValue, initial=np._NoValue,
     if where is not np._NoValue:
         kwargs['where'] = where
 
-    if type(a) is np.ndarray and a.dtype != np.object_:
+    if (type(a) is np.ndarray or type(a) is np.memmap) and a.dtype != np.object_:
         # Fast, but not safe for subclasses of ndarray, or object arrays,
         # which do not implement isnan (gh-9009), or fmax correctly (gh-8975)
         res = np.fmax.reduce(a, axis=axis, out=out, **kwargs)
diff --git a/numpy/lib/tests/test_nanfunctions.py b/numpy/lib/tests/test_nanfunctions.py
index 918d855cd104..85ba8ff53d5a 100644
--- a/numpy/lib/tests/test_nanfunctions.py
+++ b/numpy/lib/tests/test_nanfunctions.py
@@ -1416,3 +1416,18 @@ def test__replace_nan():
         assert result_nan is not arr_nan
         assert_equal(result_nan, np.array([0, 1, 2]))
         assert np.isnan(arr_nan[-1])
+
+
+def test_memmap_takes_fast_route(tmpdir):
+    # We want memory mapped arrays to take the fast route through nanmax,
+    # which avoids creating a mask by using fmax.reduce (see gh-28721). So we
+    # check that on bad input, the error is from fmax (rather than maximum).
+    a = np.arange(10., dtype=float)
+    with open(tmpdir.join("data.bin"), "w+b") as fh:
+        fh.write(a.tobytes())
+        mm = np.memmap(fh, dtype=a.dtype, shape=a.shape)
+        with pytest.raises(ValueError, match="reduction operation fmax"):
+            np.nanmax(mm, out=np.zeros(2))
+        # For completeness, same for nanmin.
+        with pytest.raises(ValueError, match="reduction operation fmin"):
+            np.nanmin(mm, out=np.zeros(2))

From e68ac767ddcf30d5d1958d2e27451f7a5e9c5d4a Mon Sep 17 00:00:00 2001
From: Pieter Eendebak 
Date: Tue, 22 Apr 2025 10:32:46 +0200
Subject: [PATCH 076/202] ENH: Improve performance of np.count_nonzero for
 float arrays (#27523)

Special case `count_nonzero` for numerical built-in types on trivially iterable arrays.

---------

Co-authored-by: Sebastian Berg 
---
 benchmarks/benchmarks/bench_core.py         |  2 +-
 numpy/_core/src/multiarray/arraytypes.c.src | 36 +++++++++++++++++++++
 numpy/_core/src/multiarray/arraytypes.h.src |  3 ++
 numpy/_core/src/multiarray/item_selection.c | 13 ++++++--
 numpy/_core/tests/test_numeric.py           | 28 ++++++++++++++++
 5 files changed, 79 insertions(+), 3 deletions(-)

diff --git a/benchmarks/benchmarks/bench_core.py b/benchmarks/benchmarks/bench_core.py
index 0c71cda57b54..434407d62b8b 100644
--- a/benchmarks/benchmarks/bench_core.py
+++ b/benchmarks/benchmarks/bench_core.py
@@ -151,7 +151,7 @@ class CountNonzero(Benchmark):
     params = [
         [1, 2, 3],
         [100, 10000, 1000000],
-        [bool, np.int8, np.int16, np.int32, np.int64, str, object]
+        [bool, np.int8, np.int16, np.int32, np.int64, np.float32, np.float64, str, object]
     ]
 
     def setup(self, numaxes, size, dtype):
diff --git a/numpy/_core/src/multiarray/arraytypes.c.src b/numpy/_core/src/multiarray/arraytypes.c.src
index 8de16afd3412..f064d99475cc 100644
--- a/numpy/_core/src/multiarray/arraytypes.c.src
+++ b/numpy/_core/src/multiarray/arraytypes.c.src
@@ -2534,6 +2534,42 @@ static npy_bool
 }
 /**end repeat**/
 
+/**begin repeat
+ *
+ * #name = BOOL, BYTE, UBYTE, USHORT, SHORT, UINT, INT, ULONG, LONG, FLOAT, DOUBLE#
+ * #type = npy_bool, npy_byte, npy_byte, npy_uint16, npy_int16, npy_uint32, npy_int32, npy_uint64, npy_int64, npy_float, npy_double#
+ * #nonzero = _NONZERO*11#
+ */
+static npy_intp
+count_nonzero_trivial_@name@(npy_intp count, const char *data, npy_int stride)
+{
+    npy_intp nonzero_count = 0;
+    while (count--) {
+        @type@ *ptmp = (@type@ *)data;
+        nonzero_count += (npy_bool) @nonzero@(*ptmp);
+        data += stride;
+    }
+    return nonzero_count;
+}
+/**end repeat**/
+
+NPY_NO_EXPORT npy_intp
+count_nonzero_trivial_dispatcher(npy_intp count, const char* data, npy_intp stride, int dtype_num) { 
+    switch(dtype_num) {
+        /**begin repeat
+         *
+         * #dtypeID = NPY_BOOL, NPY_UINT8, NPY_INT8, NPY_UINT16, NPY_INT16, NPY_UINT32, NPY_INT32, NPY_UINT64, NPY_INT64, NPY_FLOAT32, NPY_FLOAT64#
+         * #name = BOOL, BYTE, UBYTE, USHORT, SHORT, UINT, INT, ULONG, LONG, FLOAT, DOUBLE#
+         */
+        case @dtypeID@:
+        {
+            return count_nonzero_trivial_@name@(count, data, stride);
+        }
+        /**end repeat**/
+    }
+    return -1;
+}
+
 /**begin repeat
  *
  * #fname = CFLOAT, CDOUBLE, CLONGDOUBLE#
diff --git a/numpy/_core/src/multiarray/arraytypes.h.src b/numpy/_core/src/multiarray/arraytypes.h.src
index 35764dc1b253..ac4100bb8e38 100644
--- a/numpy/_core/src/multiarray/arraytypes.h.src
+++ b/numpy/_core/src/multiarray/arraytypes.h.src
@@ -164,4 +164,7 @@ NPY_CPU_DISPATCH_DECLARE(NPY_NO_EXPORT int BOOL_argmax,
 #undef INT_not_size_named
 #undef LONGLONG_not_size_named
 
+NPY_NO_EXPORT npy_intp
+count_nonzero_trivial_dispatcher(npy_intp count, const char* data, npy_intp stride, int dtype_num);
+
 #endif  /* NUMPY_CORE_SRC_MULTIARRAY_ARRAYTYPES_H_ */
diff --git a/numpy/_core/src/multiarray/item_selection.c b/numpy/_core/src/multiarray/item_selection.c
index d71b737745af..feea67c79bb9 100644
--- a/numpy/_core/src/multiarray/item_selection.c
+++ b/numpy/_core/src/multiarray/item_selection.c
@@ -398,7 +398,7 @@ PyArray_PutTo(PyArrayObject *self, PyObject* values0, PyObject *indices0,
     }
     ni = PyArray_SIZE(indices);
     if ((ni > 0) && (PyArray_Size((PyObject *)self) == 0)) {
-        PyErr_SetString(PyExc_IndexError, 
+        PyErr_SetString(PyExc_IndexError,
                         "cannot replace elements of an empty array");
         goto fail;
     }
@@ -2629,7 +2629,7 @@ count_nonzero_u64(const char *data, npy_intp bstride, npy_uintp len)
     return count;
 }
 /*
- * Counts the number of True values in a raw boolean array. This
+ * Counts the number of non-zero values in a raw int array. This
  * is a low-overhead function which does no heap allocations.
  *
  * Returns -1 on error.
@@ -2739,6 +2739,15 @@ PyArray_CountNonzero(PyArrayObject *self)
             }
         }
         else {
+            /* Special low-overhead version specific to the float types (and some others) */
+            if (PyArray_ISNOTSWAPPED(self) && PyArray_ISALIGNED(self)) {
+                npy_intp dispatched_nonzero_count = count_nonzero_trivial_dispatcher(count,
+                                                        data, stride, dtype->type_num);
+                if (dispatched_nonzero_count >= 0) {
+                    return dispatched_nonzero_count;
+                }
+            }
+
             NPY_BEGIN_THREADS_THRESHOLDED(count);
             while (count--) {
                 if (nonzero(data, self)) {
diff --git a/numpy/_core/tests/test_numeric.py b/numpy/_core/tests/test_numeric.py
index eed2f7a02c7b..23502fdd7ec8 100644
--- a/numpy/_core/tests/test_numeric.py
+++ b/numpy/_core/tests/test_numeric.py
@@ -1956,6 +1956,34 @@ def __bool__(self):
         a = np.array([[ThrowsAfter(15)]] * 10)
         assert_raises(ValueError, np.nonzero, a)
 
+    def test_nonzero_byteorder(self):
+        values = [0., -0., 1, float('nan'), 0, 1,
+                  np.float16(0), np.float16(12.3)]
+        expected = [0, 0, 1, 1, 0, 1, 0, 1]
+
+        for value, expected in zip(values, expected):
+            A = np.array([value])
+            A_byteswapped = (A.view(A.dtype.newbyteorder()).byteswap()).copy()
+
+            assert np.count_nonzero(A) == expected
+            assert np.count_nonzero(A_byteswapped) == expected
+
+    def test_count_nonzero_non_aligned_array(self):
+        # gh-27523
+        b = np.zeros(64 + 1, dtype=np.int8)[1:]
+        b = b.view(int)
+        b[:] = np.arange(b.size)
+        b[::2] = 0
+        assert b.flags.aligned is False
+        assert np.count_nonzero(b) == b.size / 2
+
+        b = np.zeros(64 + 1, dtype=np.float16)[1:]
+        b = b.view(float)
+        b[:] = np.arange(b.size)
+        b[::2] = 0
+        assert b.flags.aligned is False
+        assert np.count_nonzero(b) == b.size / 2
+
 
 class TestIndex:
     def test_boolean(self):

From 461d1c0656b506740b68de5a8930451a6d74217e Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Fran=C3=A7ois=20Rozet?= 
Date: Tue, 22 Apr 2025 10:40:13 +0200
Subject: [PATCH 077/202] BUG: fix ``np.vectorize`` for object dtype (#28624)

With `dtype=object` results, the `asarray()` call previously lead to incorrect results when the inputs were scalars.  The new `out=...` provides a way to ensure the result is always an array.
(Unlike ufuncs `vectorize` always returns arrays also for 0-D results, which is maybe weird but not a change here.)

Closes #21274
---
 numpy/lib/_function_base_impl.py      | 10 +++-------
 numpy/lib/tests/test_function_base.py | 15 +++++++++++++++
 2 files changed, 18 insertions(+), 7 deletions(-)

diff --git a/numpy/lib/_function_base_impl.py b/numpy/lib/_function_base_impl.py
index 8b8156437728..33bc64511009 100644
--- a/numpy/lib/_function_base_impl.py
+++ b/numpy/lib/_function_base_impl.py
@@ -2549,7 +2549,6 @@ def _get_ufunc_and_otypes(self, func, args):
             # the subsequent call when the ufunc is evaluated.
             # Assumes that ufunc first evaluates the 0th elements in the input
             # arrays (the input values are not checked to ensure this)
-            args = [asarray(arg) for arg in args]
             if builtins.any(arg.size == 0 for arg in args):
                 raise ValueError('cannot call `vectorize` on size 0 inputs '
                                  'unless `otypes` is set')
@@ -2595,18 +2594,15 @@ def _vectorize_call(self, func, args):
         elif not args:
             res = func()
         else:
+            args = [asanyarray(a, dtype=object) for a in args]
             ufunc, otypes = self._get_ufunc_and_otypes(func=func, args=args)
-
-            # Convert args to object arrays first
-            inputs = [asanyarray(a, dtype=object) for a in args]
-
-            outputs = ufunc(*inputs)
+            outputs = ufunc(*args, out=...)
 
             if ufunc.nout == 1:
                 res = asanyarray(outputs, dtype=otypes[0])
             else:
                 res = tuple(asanyarray(x, dtype=t)
-                             for x, t in zip(outputs, otypes))
+                            for x, t in zip(outputs, otypes))
         return res
 
     def _vectorize_call_with_signature(self, func, args):
diff --git a/numpy/lib/tests/test_function_base.py b/numpy/lib/tests/test_function_base.py
index c35243f79d39..653a0f068372 100644
--- a/numpy/lib/tests/test_function_base.py
+++ b/numpy/lib/tests/test_function_base.py
@@ -1715,6 +1715,21 @@ def test_otypes(self):
         x = np.arange(5)
         assert_array_equal(f(x), x)
 
+    def test_otypes_object_28624(self):
+        # with object otype, the vectorized function should return y
+        # wrapped into an object array
+        y = np.arange(3)
+        f = vectorize(lambda x: y, otypes=[object])
+
+        assert f(None).item() is y
+        assert f([None]).item() is y
+
+        y = [1, 2, 3]
+        f = vectorize(lambda x: y, otypes=[object])
+
+        assert f(None).item() is y
+        assert f([None]).item() is y
+
     def test_parse_gufunc_signature(self):
         assert_equal(nfb._parse_gufunc_signature('(x)->()'), ([('x',)], [()]))
         assert_equal(nfb._parse_gufunc_signature('(x,y)->()'),

From 8df09df7365539a092c9f4534ef8b8295b679de6 Mon Sep 17 00:00:00 2001
From: Nathan Goldbaum 
Date: Tue, 22 Apr 2025 15:31:14 -0600
Subject: [PATCH 078/202] ENH: Support Python 3.14 (#28748)

* MNT: use CPython internal APIs to hotfix temporary elision on 3.14

This is based on a diff from Sam Gross, see
https://github.com/numpy/numpy/issues/28681#issuecomment-2810661401

* TST: use refcount deltas in tests that hardcode refcounts

* TST: one more refcount test change I don't understand

* TST: fix ResourceWarning

* CI: add 3.14 and 3.14t linux CI

* CI: try with setup-python instead of setup-uv

* CI: fix 3.14t-dev cython install

* Update numpy/_core/src/multiarray/temp_elide.c

Co-authored-by: Ross Barnowski 

* CI: drop linux 3.13t smoke test

* TST: move refcount check inside with block

* MNT: guard against a possible future PyPy 3.14

---------

Co-authored-by: Ross Barnowski 
---
 .github/workflows/linux.yml              |  9 ++---
 numpy/_core/src/multiarray/temp_elide.c  | 48 +++++++++++++++++++++++-
 numpy/_core/tests/test_dlpack.py         |  8 ++--
 numpy/_core/tests/test_dtype.py          |  3 +-
 numpy/_core/tests/test_indexing.py       |  6 ++-
 numpy/_core/tests/test_item_selection.py |  8 +++-
 numpy/_core/tests/test_multiarray.py     |  4 +-
 numpy/_core/tests/test_nditer.py         |  5 ++-
 numpy/_core/tests/test_regression.py     | 43 ++++++++++-----------
 numpy/_core/tests/test_umath.py          |  4 +-
 10 files changed, 93 insertions(+), 45 deletions(-)

diff --git a/.github/workflows/linux.yml b/.github/workflows/linux.yml
index 3198ac696476..ac269ff2a752 100644
--- a/.github/workflows/linux.yml
+++ b/.github/workflows/linux.yml
@@ -58,22 +58,19 @@ jobs:
       MESON_ARGS: "-Dallow-noblas=true -Dcpu-baseline=none -Dcpu-dispatch=none"
     strategy:
       matrix:
-        version: ["3.11", "3.12", "3.13", "3.13t"]
+        version: ["3.11", "3.12", "3.13", "3.14-dev", "3.14t-dev"]
     steps:
     - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2
       with:
         submodules: recursive
         fetch-tags: true
         persist-credentials: false
-    - uses: astral-sh/setup-uv@d4b2f3b6ecc6e67c4457f6d3e41ec42d3d0fcb86
+    - uses: actions/setup-python@8d9ed9ac5c53483de85588cdf95a591a75ab9f55 # v5.5.0
       with:
         python-version: ${{ matrix.version }}
-        enable-cache: false
-    - run:
-        uv pip install --python=${{ matrix.version }} pip
     # TODO: remove cython nightly install when cython does a release
     - name: Install nightly Cython
-      if: matrix.version == '3.13t'
+      if: matrix.version == '3.14t-dev'
       run: |
         pip install -i https://pypi.anaconda.org/scientific-python-nightly-wheels/simple cython
     - uses: ./.github/meson_actions
diff --git a/numpy/_core/src/multiarray/temp_elide.c b/numpy/_core/src/multiarray/temp_elide.c
index 662a2fa52b06..667ba2b443ef 100644
--- a/numpy/_core/src/multiarray/temp_elide.c
+++ b/numpy/_core/src/multiarray/temp_elide.c
@@ -62,6 +62,13 @@
 
 #include 
 
+#if PY_VERSION_HEX >= 0x030E00A7 && !defined(PYPY_VERSION)
+#define Py_BUILD_CORE
+#include "internal/pycore_frame.h"
+#include "internal/pycore_interpframe.h"
+#undef Py_BUILD_CORE
+#endif
+
 /* 1 prints elided operations, 2 prints stacktraces */
 #define NPY_ELIDE_DEBUG 0
 #define NPY_MAX_STACKSIZE 10
@@ -109,6 +116,41 @@ find_addr(void * addresses[], npy_intp naddr, void * addr)
     return 0;
 }
 
+static int
+check_unique_temporary(PyObject *lhs)
+{
+#if PY_VERSION_HEX >= 0x030E00A7 && !defined(PYPY_VERSION)
+    // In Python 3.14.0a7 and later, a reference count of one doesn't guarantee
+    // that an object is a unique temporary variable. We scan the top of the
+    // interpreter stack to check if the object exists as an "owned" reference
+    // in the temporary stack.
+    PyFrameObject *frame = PyEval_GetFrame();
+    if (frame == NULL) {
+        return 0;
+    }
+    _PyInterpreterFrame *f = frame->f_frame;
+    _PyStackRef *base = _PyFrame_Stackbase(f);
+    _PyStackRef *stackpointer = f->stackpointer;
+    int found_once = 0;
+    while (stackpointer > base) {
+        stackpointer--;
+        PyObject *obj = PyStackRef_AsPyObjectBorrow(*stackpointer);
+        if (obj == lhs) {
+            if (!found_once && PyStackRef_IsHeapSafe(*stackpointer)) {
+                found_once = 1;
+            }
+            else {
+                return 0;
+            }
+        }
+        return found_once;
+    }
+    return 0;
+#else
+    return 1;
+#endif
+}
+
 static int
 check_callers(int * cannot)
 {
@@ -295,7 +337,8 @@ can_elide_temp(PyObject *olhs, PyObject *orhs, int *cannot)
             !PyArray_CHKFLAGS(alhs, NPY_ARRAY_OWNDATA) ||
             !PyArray_ISWRITEABLE(alhs) ||
             PyArray_CHKFLAGS(alhs, NPY_ARRAY_WRITEBACKIFCOPY) ||
-            PyArray_NBYTES(alhs) < NPY_MIN_ELIDE_BYTES) {
+            PyArray_NBYTES(alhs) < NPY_MIN_ELIDE_BYTES ||
+            !check_unique_temporary(olhs)) {
         return 0;
     }
     if (PyArray_CheckExact(orhs) ||
@@ -372,7 +415,8 @@ can_elide_temp_unary(PyArrayObject * m1)
             !PyArray_ISNUMBER(m1) ||
             !PyArray_CHKFLAGS(m1, NPY_ARRAY_OWNDATA) ||
             !PyArray_ISWRITEABLE(m1) ||
-            PyArray_NBYTES(m1) < NPY_MIN_ELIDE_BYTES) {
+            PyArray_NBYTES(m1) < NPY_MIN_ELIDE_BYTES ||
+            !check_unique_temporary((PyObject *)m1)) {
         return 0;
     }
     if (check_callers(&cannot)) {
diff --git a/numpy/_core/tests/test_dlpack.py b/numpy/_core/tests/test_dlpack.py
index 41dd72429580..d273bd798ebb 100644
--- a/numpy/_core/tests/test_dlpack.py
+++ b/numpy/_core/tests/test_dlpack.py
@@ -22,9 +22,9 @@ class TestDLPack:
     def test_dunder_dlpack_refcount(self, max_version):
         x = np.arange(5)
         y = x.__dlpack__(max_version=max_version)
-        assert sys.getrefcount(x) == 3
+        startcount = sys.getrefcount(x)
         del y
-        assert sys.getrefcount(x) == 2
+        assert startcount - sys.getrefcount(x) == 1
 
     def test_dunder_dlpack_stream(self):
         x = np.arange(5)
@@ -58,9 +58,9 @@ def test_strides_not_multiple_of_itemsize(self):
     def test_from_dlpack_refcount(self, arr):
         arr = arr.copy()
         y = np.from_dlpack(arr)
-        assert sys.getrefcount(arr) == 3
+        startcount = sys.getrefcount(arr)
         del y
-        assert sys.getrefcount(arr) == 2
+        assert startcount - sys.getrefcount(arr) == 1
 
     @pytest.mark.parametrize("dtype", [
         np.bool,
diff --git a/numpy/_core/tests/test_dtype.py b/numpy/_core/tests/test_dtype.py
index 79be16fc2ff2..5d458729d278 100644
--- a/numpy/_core/tests/test_dtype.py
+++ b/numpy/_core/tests/test_dtype.py
@@ -1922,9 +1922,10 @@ class mytype:
         if HAS_REFCOUNT:
             # Create an array and test that memory gets cleaned up (gh-25949)
             o = object()
+            startcount = sys.getrefcount(o)
             a = np.array([o], dtype=dt)
             del a
-            assert sys.getrefcount(o) == 2
+            assert sys.getrefcount(o) == startcount
 
     def test_custom_structured_dtype_errors(self):
         class mytype:
diff --git a/numpy/_core/tests/test_indexing.py b/numpy/_core/tests/test_indexing.py
index e841b8e07237..c9508bb03bdc 100644
--- a/numpy/_core/tests/test_indexing.py
+++ b/numpy/_core/tests/test_indexing.py
@@ -1164,6 +1164,8 @@ def _compare_index_result(self, arr, index, mimic_get, no_copy):
         """Compare mimicked result to indexing result.
         """
         arr = arr.copy()
+        if HAS_REFCOUNT:
+            startcount = sys.getrefcount(arr)
         indexed_arr = arr[index]
         assert_array_equal(indexed_arr, mimic_get)
         # Check if we got a view, unless its a 0-sized or 0-d array.
@@ -1174,9 +1176,9 @@ def _compare_index_result(self, arr, index, mimic_get, no_copy):
             if HAS_REFCOUNT:
                 if no_copy:
                     # refcount increases by one:
-                    assert_equal(sys.getrefcount(arr), 3)
+                    assert_equal(sys.getrefcount(arr), startcount + 1)
                 else:
-                    assert_equal(sys.getrefcount(arr), 2)
+                    assert_equal(sys.getrefcount(arr), startcount)
 
         # Test non-broadcast setitem:
         b = arr.copy()
diff --git a/numpy/_core/tests/test_item_selection.py b/numpy/_core/tests/test_item_selection.py
index 8e5e7b1cb210..c63c11011e6f 100644
--- a/numpy/_core/tests/test_item_selection.py
+++ b/numpy/_core/tests/test_item_selection.py
@@ -50,19 +50,23 @@ def test_simple(self):
 
     def test_refcounting(self):
         objects = [object() for i in range(10)]
+        if HAS_REFCOUNT:
+            orig_rcs = [sys.getrefcount(o) for o in objects]
         for mode in ('raise', 'clip', 'wrap'):
             a = np.array(objects)
             b = np.array([2, 2, 4, 5, 3, 5])
             a.take(b, out=a[:6], mode=mode)
             del a
             if HAS_REFCOUNT:
-                assert_(all(sys.getrefcount(o) == 3 for o in objects))
+                assert_(all(sys.getrefcount(o) == rc + 1
+                            for o, rc in zip(objects, orig_rcs)))
             # not contiguous, example:
             a = np.array(objects * 2)[::2]
             a.take(b, out=a[:6], mode=mode)
             del a
             if HAS_REFCOUNT:
-                assert_(all(sys.getrefcount(o) == 3 for o in objects))
+                assert_(all(sys.getrefcount(o) == rc + 1
+                            for o, rc in zip(objects, orig_rcs)))
 
     def test_unicode_mode(self):
         d = np.arange(10)
diff --git a/numpy/_core/tests/test_multiarray.py b/numpy/_core/tests/test_multiarray.py
index c90329fa1e6f..e2987f6676d6 100644
--- a/numpy/_core/tests/test_multiarray.py
+++ b/numpy/_core/tests/test_multiarray.py
@@ -6791,10 +6791,12 @@ def test_dot_3args(self):
         v = np.random.random_sample((16, 32))
 
         r = np.empty((1024, 32))
+        if HAS_REFCOUNT:
+            orig_refcount = sys.getrefcount(r)
         for i in range(12):
             dot(f, v, r)
         if HAS_REFCOUNT:
-            assert_equal(sys.getrefcount(r), 2)
+            assert_equal(sys.getrefcount(r), orig_refcount)
         r2 = dot(f, v, out=None)
         assert_array_equal(r2, r)
         assert_(r is dot(f, v, out=r))
diff --git a/numpy/_core/tests/test_nditer.py b/numpy/_core/tests/test_nditer.py
index b8328f174e3f..5bf0a6b7b2f4 100644
--- a/numpy/_core/tests/test_nditer.py
+++ b/numpy/_core/tests/test_nditer.py
@@ -1125,8 +1125,9 @@ def test_iter_object_arrays_conversions():
             rc = sys.getrefcount(ob)
         for x in i:
             x[...] += 1
-    if HAS_REFCOUNT:
-        assert_(sys.getrefcount(ob) == rc - 1)
+        if HAS_REFCOUNT:
+            newrc = sys.getrefcount(ob)
+            assert_(newrc == rc - 1)
     assert_equal(a, np.arange(6) + 98172489)
 
 def test_iter_common_dtype():
diff --git a/numpy/_core/tests/test_regression.py b/numpy/_core/tests/test_regression.py
index 3d583eeef860..30d66bb3cbe2 100644
--- a/numpy/_core/tests/test_regression.py
+++ b/numpy/_core/tests/test_regression.py
@@ -1585,29 +1585,26 @@ def test_take_refcount(self):
     def test_fromfile_tofile_seeks(self):
         # On Python 3, tofile/fromfile used to get (#1610) the Python
         # file handle out of sync
-        f0 = tempfile.NamedTemporaryFile()
-        f = f0.file
-        f.write(np.arange(255, dtype='u1').tobytes())
-
-        f.seek(20)
-        ret = np.fromfile(f, count=4, dtype='u1')
-        assert_equal(ret, np.array([20, 21, 22, 23], dtype='u1'))
-        assert_equal(f.tell(), 24)
-
-        f.seek(40)
-        np.array([1, 2, 3], dtype='u1').tofile(f)
-        assert_equal(f.tell(), 43)
-
-        f.seek(40)
-        data = f.read(3)
-        assert_equal(data, b"\x01\x02\x03")
-
-        f.seek(80)
-        f.read(4)
-        data = np.fromfile(f, dtype='u1', count=4)
-        assert_equal(data, np.array([84, 85, 86, 87], dtype='u1'))
-
-        f.close()
+        with tempfile.NamedTemporaryFile() as f:
+            f.write(np.arange(255, dtype='u1').tobytes())
+
+            f.seek(20)
+            ret = np.fromfile(f, count=4, dtype='u1')
+            assert_equal(ret, np.array([20, 21, 22, 23], dtype='u1'))
+            assert_equal(f.tell(), 24)
+
+            f.seek(40)
+            np.array([1, 2, 3], dtype='u1').tofile(f)
+            assert_equal(f.tell(), 43)
+
+            f.seek(40)
+            data = f.read(3)
+            assert_equal(data, b"\x01\x02\x03")
+
+            f.seek(80)
+            f.read(4)
+            data = np.fromfile(f, dtype='u1', count=4)
+            assert_equal(data, np.array([84, 85, 86, 87], dtype='u1'))
 
     def test_complex_scalar_warning(self):
         for tp in [np.csingle, np.cdouble, np.clongdouble]:
diff --git a/numpy/_core/tests/test_umath.py b/numpy/_core/tests/test_umath.py
index c6708e14034e..0efa51bfd772 100644
--- a/numpy/_core/tests/test_umath.py
+++ b/numpy/_core/tests/test_umath.py
@@ -269,9 +269,9 @@ class ArrSubclass(np.ndarray):
             pass
 
         arr = np.arange(10).view(ArrSubclass)
-
+        orig_refcount = sys.getrefcount(arr)
         arr *= 1
-        assert sys.getrefcount(arr) == 2
+        assert sys.getrefcount(arr) == orig_refcount
 
 
 class TestComparisons:

From 9ead596ce4f8df0189f9ba3d54937e22e2785a5e Mon Sep 17 00:00:00 2001
From: Pieter Eendebak 
Date: Wed, 23 Apr 2025 09:55:22 +0200
Subject: [PATCH 079/202] ENH: Improve performance for np.result_type (#28710)

Improve performance of  np.result_type

* Use NPY_ALLOC_WORKSPACE in array_result_type
* Avoid increfs/decrefs in PyArray_ResultType
* Fast path for identical arguments to np.result_type
---
 numpy/_core/src/multiarray/convert_datatype.c |  7 +------
 numpy/_core/src/multiarray/multiarraymodule.c | 18 +++++++++++-------
 2 files changed, 12 insertions(+), 13 deletions(-)

diff --git a/numpy/_core/src/multiarray/convert_datatype.c b/numpy/_core/src/multiarray/convert_datatype.c
index 7de76ac63ed6..59b6298b5815 100644
--- a/numpy/_core/src/multiarray/convert_datatype.c
+++ b/numpy/_core/src/multiarray/convert_datatype.c
@@ -1597,13 +1597,12 @@ PyArray_ResultType(
         return NULL;
     }
 
-    PyArray_DTypeMeta **all_DTypes = (PyArray_DTypeMeta **)workspace;
+    PyArray_DTypeMeta **all_DTypes = (PyArray_DTypeMeta **)workspace; // borrowed references
     PyArray_Descr **all_descriptors = (PyArray_Descr **)(&all_DTypes[narrs+ndtypes]);
 
     /* Copy all dtypes into a single array defining non-value-based behaviour */
     for (npy_intp i=0; i < ndtypes; i++) {
         all_DTypes[i] = NPY_DTYPE(descrs[i]);
-        Py_INCREF(all_DTypes[i]);
         all_descriptors[i] = descrs[i];
     }
 
@@ -1628,14 +1627,10 @@ PyArray_ResultType(
             all_descriptors[i_all] = PyArray_DTYPE(arrs[i]);
             all_DTypes[i_all] = NPY_DTYPE(all_descriptors[i_all]);
         }
-        Py_INCREF(all_DTypes[i_all]);
     }
 
     PyArray_DTypeMeta *common_dtype = PyArray_PromoteDTypeSequence(
             narrs+ndtypes, all_DTypes);
-    for (npy_intp i=0; i < narrs+ndtypes; i++) {
-        Py_DECREF(all_DTypes[i]);
-    }
     if (common_dtype == NULL) {
         goto error;
     }
diff --git a/numpy/_core/src/multiarray/multiarraymodule.c b/numpy/_core/src/multiarray/multiarraymodule.c
index e74e14bf10c2..cddfad16a972 100644
--- a/numpy/_core/src/multiarray/multiarraymodule.c
+++ b/numpy/_core/src/multiarray/multiarraymodule.c
@@ -3583,24 +3583,28 @@ static PyObject *
 array_result_type(PyObject *NPY_UNUSED(dummy), PyObject *const *args, Py_ssize_t len)
 {
     npy_intp i, narr = 0, ndtypes = 0;
-    PyArrayObject **arr = NULL;
-    PyArray_Descr **dtypes = NULL;
     PyObject *ret = NULL;
 
     if (len == 0) {
         PyErr_SetString(PyExc_ValueError,
                         "at least one array or dtype is required");
-        goto finish;
+        return NULL;
     }
 
-    arr = PyArray_malloc(2 * len * sizeof(void *));
+    NPY_ALLOC_WORKSPACE(arr, PyArrayObject *, 2 * 3, 2 * len);
     if (arr == NULL) {
-        return PyErr_NoMemory();
+        return NULL;
     }
-    dtypes = (PyArray_Descr**)&arr[len];
+    PyArray_Descr **dtypes = (PyArray_Descr**)&arr[len];
+
+    PyObject *previous_obj = NULL;
 
     for (i = 0; i < len; ++i) {
         PyObject *obj = args[i];
+        if (obj == previous_obj) {
+            continue;
+        }
+
         if (PyArray_Check(obj)) {
             Py_INCREF(obj);
             arr[narr] = (PyArrayObject *)obj;
@@ -3636,7 +3640,7 @@ array_result_type(PyObject *NPY_UNUSED(dummy), PyObject *const *args, Py_ssize_t
     for (i = 0; i < ndtypes; ++i) {
         Py_DECREF(dtypes[i]);
     }
-    PyArray_free(arr);
+    npy_free_workspace(arr);
     return ret;
 }
 

From a26c1306b70223e2fc586c496e450efea4ec098f Mon Sep 17 00:00:00 2001
From: Sayed Adel 
Date: Sun, 6 Apr 2025 19:11:40 +0200
Subject: [PATCH 080/202] MAINT: Remove distutils CPU dispatcher compatibility
 code

  Since distutils is no longer enabled and NumPy now fully uses Meson for
  CPU dispatching, we can remove the compatibility layer between the two
  systems. This simplifies the codebase and removes unnecessary code paths
  that are no longer needed.
---
 meson_cpu/main_config.h.in                    |  42 ++++---
 numpy/_core/code_generators/generate_umath.py |   2 -
 numpy/_core/src/_simd/_simd.c                 |   9 +-
 numpy/_core/src/_simd/_simd.dispatch.c.src    |   1 -
 numpy/_core/src/_simd/_simd.h                 |   2 -
 numpy/_core/src/common/npy_cpu_dispatch.h     |  38 +-----
 .../src/common/npy_cpu_dispatch_distutils.h   | 116 ------------------
 .../src/multiarray/argfunc.dispatch.c.src     |   8 --
 numpy/_core/src/multiarray/arraytypes.c.src   |   4 +-
 numpy/_core/src/multiarray/arraytypes.h.src   |   4 +-
 numpy/_core/src/npysort/highway_qsort.hpp     |   8 +-
 numpy/_core/src/npysort/quicksort.cpp         |  36 +++---
 numpy/_core/src/npysort/selection.cpp         |  12 +-
 numpy/_core/src/npysort/x86_simd_qsort.hpp    |  12 +-
 numpy/_core/src/umath/_umath_tests.c.src      |   4 +-
 numpy/_core/src/umath/_umath_tests.dispatch.c |  10 +-
 numpy/_core/src/umath/loops.h.src             |  94 ++++----------
 .../src/umath/loops_arithm_fp.dispatch.c.src  |   7 --
 .../src/umath/loops_arithmetic.dispatch.c.src |   7 --
 .../src/umath/loops_autovec.dispatch.c.src    |   7 --
 .../src/umath/loops_comparison.dispatch.c.src |   7 --
 .../umath/loops_exponent_log.dispatch.c.src   |   5 -
 .../umath/loops_hyperbolic.dispatch.cpp.src   |   8 --
 .../src/umath/loops_minmax.dispatch.c.src     |   7 --
 .../src/umath/loops_modulo.dispatch.c.src     |   3 -
 .../src/umath/loops_umath_fp.dispatch.c.src   |   3 -
 .../src/umath/loops_unary.dispatch.c.src      |   8 --
 .../umath/loops_unary_complex.dispatch.c.src  |   7 --
 .../src/umath/loops_unary_fp.dispatch.c.src   |   7 --
 .../umath/loops_unary_fp_le.dispatch.c.src    |   7 --
 30 files changed, 81 insertions(+), 404 deletions(-)
 delete mode 100644 numpy/_core/src/common/npy_cpu_dispatch_distutils.h

diff --git a/meson_cpu/main_config.h.in b/meson_cpu/main_config.h.in
index 4de867d1f325..e1d6a870c075 100644
--- a/meson_cpu/main_config.h.in
+++ b/meson_cpu/main_config.h.in
@@ -11,8 +11,6 @@
  */
 #ifndef @P@_CPU_DISPATCHER_CONF_H_
 #define @P@_CPU_DISPATCHER_CONF_H_
-/// This definition is required to provide compatibility with NumPy distutils
-#define @P@_CPU_MESON_BUILD
 /**
  * @def @P@WITH_CPU_BASELINE
  * Enabled baseline features names as a single string where each is separated by a single space.
@@ -79,20 +77,12 @@
  * Defines the default behavior for the configurable macros derived from the configuration header
  * that is generated by the meson function `mod_features.multi_targets()`.
  *
- * Note: Providing fallback in case of optimization disabled is no longer needed for meson
- * since we always guarantee having configuration headers.
- *
- * However, it is still needed for compatibility with Numpy distutils.
+ * These macros are replaced by disapatch config headers once its included.
  */
-#ifndef @P@DISABLE_OPTIMIZATION
-    #define @P@MTARGETS_CONF_BASELINE(CB, ...) \
-         &&"Expected config header that generated by mod_features.multi_targets()";
-    #define @P@MTARGETS_CONF_DISPATCH(TEST_FEATURE_CB, CB, ...) \
-         &&"Expected config header that generated by mod_features.multi_targets()";
-#else
-    #define @P@MTARGETS_CONF_BASELINE(CB, ...) @P@_CPU_EXPAND(CB(__VA_ARGS__))
-    #define @P@MTARGETS_CONF_DISPATCH(CHK, CB, ...)
-#endif
+#define @P@MTARGETS_CONF_BASELINE(CB, ...) \
+     &&"Expected config header that generated by mod_features.multi_targets()";
+#define @P@MTARGETS_CONF_DISPATCH(TEST_FEATURE_CB, CB, ...) \
+     &&"Expected config header that generated by mod_features.multi_targets()";
 /**
  * @def @P@CPU_DISPATCH_CURFX(NAME)
  *
@@ -374,13 +364,33 @@
     #include 
 #endif
 
+#if (defined(@P@HAVE_VSX) || defined(@P@HAVE_VX)) && !defined(__cplusplus) && defined(bool)
+    /*
+     * "altivec.h" header contains the definitions(bool, vector, pixel),
+     * usually in c++ we undefine them after including the header.
+     * It's better anyway to take them off and use built-in types(__vector, __pixel, __bool) instead,
+     * since c99 supports bool variables which may lead to ambiguous errors.
+     */
+    // backup 'bool' before including 'npy_cpu_dispatch_config.h', since it may not defined as a compiler token.
+    #define NPY__CPU_DISPATCH_GUARD_BOOL
+    typedef bool npy__cpu_dispatch_guard_bool;
+#endif
 #ifdef @P@HAVE_VSX
     #include 
 #endif
-
 #ifdef @P@HAVE_VX
     #include 
 #endif
+#if (defined(@P@HAVE_VSX) || defined(@P@HAVE_VX))
+    #undef bool
+    #undef vector
+    #undef pixel
+    #ifdef NPY__CPU_DISPATCH_GUARD_BOOL
+        #define bool npy__cpu_dispatch_guard_bool
+        #undef NPY__CPU_DISPATCH_GUARD_BOOL
+    #endif
+#endif
+
 
 #ifdef @P@HAVE_NEON
     #include 
diff --git a/numpy/_core/code_generators/generate_umath.py b/numpy/_core/code_generators/generate_umath.py
index 9ba63778dde8..e9b7989afd28 100644
--- a/numpy/_core/code_generators/generate_umath.py
+++ b/numpy/_core/code_generators/generate_umath.py
@@ -1479,9 +1479,7 @@ def make_arrays(funcdict):
 
     for dname, funcs in dispdict.items():
         code2list.append(textwrap.dedent(f"""
-            #ifndef NPY_DISABLE_OPTIMIZATION
             #include "{dname}.dispatch.h"
-            #endif
         """))
         for (ufunc_name, func_idx, cfunc_name, inout) in funcs:
             code2list.append(textwrap.dedent(f"""\
diff --git a/numpy/_core/src/_simd/_simd.c b/numpy/_core/src/_simd/_simd.c
index c1881dd86f0a..2f0a5df6375c 100644
--- a/numpy/_core/src/_simd/_simd.c
+++ b/numpy/_core/src/_simd/_simd.c
@@ -85,13 +85,8 @@ PyMODINIT_FUNC PyInit__simd(void)
                 goto err;                                                      \
             }                                                                  \
         }
-    #ifdef NPY__CPU_MESON_BUILD
-        NPY_MTARGETS_CONF_DISPATCH(NPY_CPU_HAVE, ATTACH_MODULE, MAKE_MSVC_HAPPY)
-        NPY_MTARGETS_CONF_BASELINE(ATTACH_BASELINE_MODULE, MAKE_MSVC_HAPPY)
-    #else
-        NPY__CPU_DISPATCH_CALL(NPY_CPU_HAVE, ATTACH_MODULE, MAKE_MSVC_HAPPY)
-        NPY__CPU_DISPATCH_BASELINE_CALL(ATTACH_BASELINE_MODULE, MAKE_MSVC_HAPPY)
-    #endif
+    NPY_MTARGETS_CONF_DISPATCH(NPY_CPU_HAVE, ATTACH_MODULE, MAKE_MSVC_HAPPY)
+    NPY_MTARGETS_CONF_BASELINE(ATTACH_BASELINE_MODULE, MAKE_MSVC_HAPPY)
 
 #if Py_GIL_DISABLED
     // signal this module supports running with the GIL disabled
diff --git a/numpy/_core/src/_simd/_simd.dispatch.c.src b/numpy/_core/src/_simd/_simd.dispatch.c.src
index 2b47c84706f5..120fbfee3270 100644
--- a/numpy/_core/src/_simd/_simd.dispatch.c.src
+++ b/numpy/_core/src/_simd/_simd.dispatch.c.src
@@ -1,4 +1,3 @@
-/*@targets #simd_test*/
 #include "_simd.h"
 #include "_simd_inc.h"
 
diff --git a/numpy/_core/src/_simd/_simd.h b/numpy/_core/src/_simd/_simd.h
index f3b0a8ccdda9..82a4451cc3a2 100644
--- a/numpy/_core/src/_simd/_simd.h
+++ b/numpy/_core/src/_simd/_simd.h
@@ -18,10 +18,8 @@
 #include "npy_cpu_dispatch.h"
 #include "numpy/npy_cpu.h"
 
-#ifndef NPY_DISABLE_OPTIMIZATION
 // autogenerated, required for CPU dispatch macros
 #include "_simd.dispatch.h"
-#endif
 /**
  * Create a new module for each required optimization which contains all NPYV intrinsics,
  *
diff --git a/numpy/_core/src/common/npy_cpu_dispatch.h b/numpy/_core/src/common/npy_cpu_dispatch.h
index ddf6bd554492..49d29b8aa655 100644
--- a/numpy/_core/src/common/npy_cpu_dispatch.h
+++ b/numpy/_core/src/common/npy_cpu_dispatch.h
@@ -7,51 +7,19 @@
  * To get a better understanding of the mechanism behind it.
  */
 #include "npy_cpu_features.h" // NPY_CPU_HAVE
-#if (defined(__s390x__) || defined(__powerpc64__)) && !defined(__cplusplus) && defined(bool)
-    /*
-     * "altivec.h" header contains the definitions(bool, vector, pixel),
-     * usually in c++ we undefine them after including the header.
-     * It's better anyway to take them off and use built-in types(__vector, __pixel, __bool) instead,
-     * since c99 supports bool variables which may lead to ambiguous errors.
-     */
-    // backup 'bool' before including 'npy_cpu_dispatch_config.h', since it may not defined as a compiler token.
-    #define NPY__CPU_DISPATCH_GUARD_BOOL
-    typedef bool npy__cpu_dispatch_guard_bool;
-#endif
 /**
- * Including the main configuration header 'npy_cpu_dispatch_config.h'.
- * This header is generated by the 'ccompiler_opt' distutils module and the Meson build system.
+ *  This header genereated by the build system and contains:
  *
- * For the distutils-generated version, it contains:
- *   - Headers for platform-specific instruction sets.
- *   - Feature #definitions, e.g. NPY_HAVE_AVX2.
- *   - Helper macros that encapsulate enabled features through user-defined build options
- *     '--cpu-baseline' and '--cpu-dispatch'. These options are essential for implementing
- *     attributes like `__cpu_baseline__` and `__cpu_dispatch__` in the NumPy module.
- *
- * For the Meson-generated version, it contains:
  *   - Headers for platform-specific instruction sets.
  *   - Helper macros that encapsulate enabled features through user-defined build options
  *     '--cpu-baseline' and '--cpu-dispatch'. These options remain crucial for implementing
  *     attributes like `__cpu_baseline__` and `__cpu_dispatch__` in the NumPy module.
  *   - Additional helper macros necessary for runtime dispatching.
  *
- * Note: In the Meson build, features #definitions are conveyed via compiler arguments.
+ * Note: features #definitions are conveyed via compiler arguments.
  */
 #include "npy_cpu_dispatch_config.h"
-#ifndef NPY__CPU_MESON_BUILD
-    // Define helper macros necessary for runtime dispatching for distutils.
-    #include "npy_cpu_dispatch_distutils.h"
-#endif
-#if defined(NPY_HAVE_VSX) || defined(NPY_HAVE_VX)
-    #undef bool
-    #undef vector
-    #undef pixel
-    #ifdef NPY__CPU_DISPATCH_GUARD_BOOL
-        #define bool npy__cpu_dispatch_guard_bool
-        #undef NPY__CPU_DISPATCH_GUARD_BOOL
-    #endif
-#endif
+
 /**
  * Initialize the CPU dispatch tracer.
  *
diff --git a/numpy/_core/src/common/npy_cpu_dispatch_distutils.h b/numpy/_core/src/common/npy_cpu_dispatch_distutils.h
deleted file mode 100644
index 8db995412f4b..000000000000
--- a/numpy/_core/src/common/npy_cpu_dispatch_distutils.h
+++ /dev/null
@@ -1,116 +0,0 @@
-#ifndef NUMPY_CORE_SRC_COMMON_NPY_CPU_DISPATCH_DISTUTILS_H_
-#define NUMPY_CORE_SRC_COMMON_NPY_CPU_DISPATCH_DISTUTILS_H_
-#ifndef NUMPY_CORE_SRC_COMMON_NPY_CPU_DISPATCH_H_
-    #error "Not standalone header please use 'npy_cpu_dispatch.h'"
-#endif
-/**
- * This header should be removed after support for distutils is removed.
- * It provides helper macros required for CPU runtime dispatching,
- * which are already defined within `meson_cpu/main_config.h.in`.
- *
- * The following macros are explained within `meson_cpu/main_config.h.in`,
- * although there are some differences in their usage:
- *
- * - Dispatched targets must be defined at the top of each dispatch-able
- *   source file within an inline or multi-line comment block.
- *   For example: //@targets baseline SSE2 AVX2 AVX512_SKX
- *
- * - The generated configuration derived from each dispatch-able source
- *   file must be guarded with `#ifndef NPY_DISABLE_OPTIMIZATION`.
- *   For example:
- *   #ifndef NPY_DISABLE_OPTIMIZATION
- *      #include "arithmetic.dispatch.h"
- *   #endif
- */
-#include "npy_cpu_features.h" // NPY_CPU_HAVE
-#include "numpy/utils.h" // NPY_EXPAND, NPY_CAT
-
-#ifdef NPY__CPU_TARGET_CURRENT
-    // 'NPY__CPU_TARGET_CURRENT': only defined by the dispatch-able sources
-    #define NPY_CPU_DISPATCH_CURFX(NAME) NPY_CAT(NPY_CAT(NAME, _), NPY__CPU_TARGET_CURRENT)
-#else
-    #define NPY_CPU_DISPATCH_CURFX(NAME) NPY_EXPAND(NAME)
-#endif
-/**
- * Defining the default behavior for the configurable macros of dispatch-able sources,
- * 'NPY__CPU_DISPATCH_CALL(...)' and 'NPY__CPU_DISPATCH_BASELINE_CALL(...)'
- *
- * These macros are defined inside the generated config files that been derived from
- * the configuration statements of the dispatch-able sources.
- *
- * The generated config file takes the same name of the dispatch-able source with replacing
- * the extension to '.h' instead of '.c', and it should be treated as a header template.
- */
-#ifndef NPY_DISABLE_OPTIMIZATION
-    #define NPY__CPU_DISPATCH_BASELINE_CALL(CB, ...) \
-        &&"Expected config header of the dispatch-able source";
-    #define NPY__CPU_DISPATCH_CALL(CHK, CB, ...) \
-        &&"Expected config header of the dispatch-able source";
-#else
-    /**
-     * We assume by default that all configuration statements contains 'baseline' option however,
-     * if the dispatch-able source doesn't require it, then the dispatch-able source and following macros
-     * need to be guard it with '#ifndef NPY_DISABLE_OPTIMIZATION'
-     */
-    #define NPY__CPU_DISPATCH_BASELINE_CALL(CB, ...) \
-        NPY_EXPAND(CB(__VA_ARGS__))
-    #define NPY__CPU_DISPATCH_CALL(CHK, CB, ...)
-#endif // !NPY_DISABLE_OPTIMIZATION
-
-#define NPY_CPU_DISPATCH_DECLARE(...) \
-    NPY__CPU_DISPATCH_CALL(NPY_CPU_DISPATCH_DECLARE_CHK_, NPY_CPU_DISPATCH_DECLARE_CB_, __VA_ARGS__) \
-    NPY__CPU_DISPATCH_BASELINE_CALL(NPY_CPU_DISPATCH_DECLARE_BASE_CB_, __VA_ARGS__)
-// Preprocessor callbacks
-#define NPY_CPU_DISPATCH_DECLARE_CB_(DUMMY, TARGET_NAME, LEFT, ...) \
-    NPY_CAT(NPY_CAT(LEFT, _), TARGET_NAME) __VA_ARGS__;
-#define NPY_CPU_DISPATCH_DECLARE_BASE_CB_(LEFT, ...) \
-    LEFT __VA_ARGS__;
-// Dummy CPU runtime checking
-#define NPY_CPU_DISPATCH_DECLARE_CHK_(FEATURE)
-
-#define NPY_CPU_DISPATCH_DECLARE_XB(...) \
-    NPY__CPU_DISPATCH_CALL(NPY_CPU_DISPATCH_DECLARE_CHK_, NPY_CPU_DISPATCH_DECLARE_CB_, __VA_ARGS__)
-#define NPY_CPU_DISPATCH_CALL(...) \
-    NPY__CPU_DISPATCH_CALL(NPY_CPU_HAVE, NPY_CPU_DISPATCH_CALL_CB_, __VA_ARGS__) \
-    NPY__CPU_DISPATCH_BASELINE_CALL(NPY_CPU_DISPATCH_CALL_BASE_CB_, __VA_ARGS__)
-// Preprocessor callbacks
-#define NPY_CPU_DISPATCH_CALL_CB_(TESTED_FEATURES, TARGET_NAME, LEFT, ...) \
-    (TESTED_FEATURES) ? (NPY_CAT(NPY_CAT(LEFT, _), TARGET_NAME) __VA_ARGS__) :
-#define NPY_CPU_DISPATCH_CALL_BASE_CB_(LEFT, ...) \
-    (LEFT __VA_ARGS__)
-
-#define NPY_CPU_DISPATCH_CALL_XB(...) \
-    NPY__CPU_DISPATCH_CALL(NPY_CPU_HAVE, NPY_CPU_DISPATCH_CALL_XB_CB_, __VA_ARGS__) \
-    ((void) 0 /* discarded expression value */)
-#define NPY_CPU_DISPATCH_CALL_XB_CB_(TESTED_FEATURES, TARGET_NAME, LEFT, ...) \
-    (TESTED_FEATURES) ? (void) (NPY_CAT(NPY_CAT(LEFT, _), TARGET_NAME) __VA_ARGS__) :
-
-#define NPY_CPU_DISPATCH_CALL_ALL(...) \
-    (NPY__CPU_DISPATCH_CALL(NPY_CPU_HAVE, NPY_CPU_DISPATCH_CALL_ALL_CB_, __VA_ARGS__) \
-    NPY__CPU_DISPATCH_BASELINE_CALL(NPY_CPU_DISPATCH_CALL_ALL_BASE_CB_, __VA_ARGS__))
-// Preprocessor callbacks
-#define NPY_CPU_DISPATCH_CALL_ALL_CB_(TESTED_FEATURES, TARGET_NAME, LEFT, ...) \
-    ((TESTED_FEATURES) ? (NPY_CAT(NPY_CAT(LEFT, _), TARGET_NAME) __VA_ARGS__) : (void) 0),
-#define NPY_CPU_DISPATCH_CALL_ALL_BASE_CB_(LEFT, ...) \
-    ( LEFT __VA_ARGS__ )
-
-#define NPY_CPU_DISPATCH_INFO() \
-    { \
-        NPY__CPU_DISPATCH_CALL(NPY_CPU_HAVE, NPY_CPU_DISPATCH_INFO_HIGH_CB_, DUMMY) \
-        NPY__CPU_DISPATCH_BASELINE_CALL(NPY_CPU_DISPATCH_INFO_BASE_HIGH_CB_, DUMMY) \
-        "", \
-        NPY__CPU_DISPATCH_CALL(NPY_CPU_HAVE, NPY_CPU_DISPATCH_INFO_CB_, DUMMY) \
-        NPY__CPU_DISPATCH_BASELINE_CALL(NPY_CPU_DISPATCH_INFO_BASE_CB_, DUMMY) \
-        ""\
-    }
-#define NPY_CPU_DISPATCH_INFO_HIGH_CB_(TESTED_FEATURES, TARGET_NAME, ...) \
-    (TESTED_FEATURES) ? NPY_TOSTRING(TARGET_NAME) :
-#define NPY_CPU_DISPATCH_INFO_BASE_HIGH_CB_(...) \
-    (1) ? "baseline(" NPY_WITH_CPU_BASELINE ")" :
-// Preprocessor callbacks
-#define NPY_CPU_DISPATCH_INFO_CB_(TESTED_FEATURES, TARGET_NAME, ...) \
-    NPY_TOSTRING(TARGET_NAME) " "
-#define NPY_CPU_DISPATCH_INFO_BASE_CB_(...) \
-    "baseline(" NPY_WITH_CPU_BASELINE ")"
-
-#endif  // NUMPY_CORE_SRC_COMMON_NPY_CPU_DISPATCH_DISTUTILS_H_
diff --git a/numpy/_core/src/multiarray/argfunc.dispatch.c.src b/numpy/_core/src/multiarray/argfunc.dispatch.c.src
index d79be1df5034..79dc111d2438 100644
--- a/numpy/_core/src/multiarray/argfunc.dispatch.c.src
+++ b/numpy/_core/src/multiarray/argfunc.dispatch.c.src
@@ -1,12 +1,4 @@
 /* -*- c -*- */
-/*@targets
- ** $maxopt baseline
- ** sse2 sse42 xop avx2 avx512_skx
- ** vsx2
- ** neon asimd
- ** vx vxe
- **/
-
 #define NPY_NO_DEPRECATED_API NPY_API_VERSION
 
 #include "simd/simd.h"
diff --git a/numpy/_core/src/multiarray/arraytypes.c.src b/numpy/_core/src/multiarray/arraytypes.c.src
index f064d99475cc..9e5588f98a83 100644
--- a/numpy/_core/src/multiarray/arraytypes.c.src
+++ b/numpy/_core/src/multiarray/arraytypes.c.src
@@ -4337,9 +4337,7 @@ set_typeinfo(PyObject *dict)
     PyObject *cobj, *key;
 
     // SIMD runtime dispatching
-    #ifndef NPY_DISABLE_OPTIMIZATION
-        #include "argfunc.dispatch.h"
-    #endif
+    #include "argfunc.dispatch.h"
     /**begin repeat
      * #FROM = BYTE, UBYTE, SHORT, USHORT, INT, UINT,
      *         LONG, ULONG, LONGLONG, ULONGLONG,
diff --git a/numpy/_core/src/multiarray/arraytypes.h.src b/numpy/_core/src/multiarray/arraytypes.h.src
index ac4100bb8e38..a5613aa8dad6 100644
--- a/numpy/_core/src/multiarray/arraytypes.h.src
+++ b/numpy/_core/src/multiarray/arraytypes.h.src
@@ -45,9 +45,7 @@ NPY_NO_EXPORT int
 /**end repeat**/
 
 
-#ifndef NPY_DISABLE_OPTIMIZATION
-    #include "argfunc.dispatch.h"
-#endif
+#include "argfunc.dispatch.h"
 /**begin repeat
  * #TYPE = BYTE, UBYTE, SHORT, USHORT, INT, UINT,
  *         LONG, ULONG, LONGLONG, ULONGLONG,
diff --git a/numpy/_core/src/npysort/highway_qsort.hpp b/numpy/_core/src/npysort/highway_qsort.hpp
index b52e6da2b621..371f2c2fbe7d 100644
--- a/numpy/_core/src/npysort/highway_qsort.hpp
+++ b/numpy/_core/src/npysort/highway_qsort.hpp
@@ -5,14 +5,10 @@
 
 namespace np::highway::qsort_simd {
 
-#ifndef NPY_DISABLE_OPTIMIZATION
-    #include "highway_qsort.dispatch.h"
-#endif
+#include "highway_qsort.dispatch.h"
 NPY_CPU_DISPATCH_DECLARE(template  void QSort, (T *arr, npy_intp size))
 
-#ifndef NPY_DISABLE_OPTIMIZATION
-    #include "highway_qsort_16bit.dispatch.h"
-#endif
+#include "highway_qsort_16bit.dispatch.h"
 NPY_CPU_DISPATCH_DECLARE(template  void QSort, (T *arr, npy_intp size))
 
 } // np::highway::qsort_simd
diff --git a/numpy/_core/src/npysort/quicksort.cpp b/numpy/_core/src/npysort/quicksort.cpp
index 15e5668f599d..ddf4fce0c28b 100644
--- a/numpy/_core/src/npysort/quicksort.cpp
+++ b/numpy/_core/src/npysort/quicksort.cpp
@@ -80,26 +80,22 @@ inline bool quicksort_dispatch(T *start, npy_intp num)
     using TF = typename np::meta::FixedWidth::Type;
     void (*dispfunc)(TF*, intptr_t) = nullptr;
     if (sizeof(T) == sizeof(uint16_t)) {
-        #ifndef NPY_DISABLE_OPTIMIZATION
-            #if defined(NPY_CPU_AMD64) || defined(NPY_CPU_X86) // x86 32-bit and 64-bit
-                #include "x86_simd_qsort_16bit.dispatch.h"
-                NPY_CPU_DISPATCH_CALL_XB(dispfunc = np::qsort_simd::template QSort, );
-            #else
-                #include "highway_qsort_16bit.dispatch.h"
-                NPY_CPU_DISPATCH_CALL_XB(dispfunc = np::highway::qsort_simd::template QSort, );
-            #endif
-        #endif
+    #if defined(NPY_CPU_AMD64) || defined(NPY_CPU_X86) // x86 32-bit and 64-bit
+        #include "x86_simd_qsort_16bit.dispatch.h"
+        NPY_CPU_DISPATCH_CALL_XB(dispfunc = np::qsort_simd::template QSort, );
+    #else
+        #include "highway_qsort_16bit.dispatch.h"
+        NPY_CPU_DISPATCH_CALL_XB(dispfunc = np::highway::qsort_simd::template QSort, );
+    #endif
     }
     else if (sizeof(T) == sizeof(uint32_t) || sizeof(T) == sizeof(uint64_t)) {
-        #ifndef NPY_DISABLE_OPTIMIZATION
-            #if defined(NPY_CPU_AMD64) || defined(NPY_CPU_X86) // x86 32-bit and 64-bit
-                #include "x86_simd_qsort.dispatch.h"
-                NPY_CPU_DISPATCH_CALL_XB(dispfunc = np::qsort_simd::template QSort, );
-            #else
-                #include "highway_qsort.dispatch.h"
-                NPY_CPU_DISPATCH_CALL_XB(dispfunc = np::highway::qsort_simd::template QSort, );
-            #endif
-        #endif
+    #if defined(NPY_CPU_AMD64) || defined(NPY_CPU_X86) // x86 32-bit and 64-bit
+        #include "x86_simd_qsort.dispatch.h"
+        NPY_CPU_DISPATCH_CALL_XB(dispfunc = np::qsort_simd::template QSort, );
+    #else
+        #include "highway_qsort.dispatch.h"
+        NPY_CPU_DISPATCH_CALL_XB(dispfunc = np::highway::qsort_simd::template QSort, );
+    #endif
     }
     if (dispfunc) {
         (*dispfunc)(reinterpret_cast(start), static_cast(num));
@@ -116,9 +112,7 @@ inline bool aquicksort_dispatch(T *start, npy_intp* arg, npy_intp num)
 #if !defined(__CYGWIN__)
     using TF = typename np::meta::FixedWidth::Type;
     void (*dispfunc)(TF*, npy_intp*, npy_intp) = nullptr;
-    #ifndef NPY_DISABLE_OPTIMIZATION
-        #include "x86_simd_argsort.dispatch.h"
-    #endif
+    #include "x86_simd_argsort.dispatch.h"
     NPY_CPU_DISPATCH_CALL_XB(dispfunc = np::qsort_simd::template ArgQSort, );
     if (dispfunc) {
         (*dispfunc)(reinterpret_cast(start), arg, num);
diff --git a/numpy/_core/src/npysort/selection.cpp b/numpy/_core/src/npysort/selection.cpp
index 5106cab7757c..1a479178c9b5 100644
--- a/numpy/_core/src/npysort/selection.cpp
+++ b/numpy/_core/src/npysort/selection.cpp
@@ -44,15 +44,11 @@ inline bool quickselect_dispatch(T* v, npy_intp num, npy_intp kth)
         using TF = typename np::meta::FixedWidth::Type;
         void (*dispfunc)(TF*, npy_intp, npy_intp) = nullptr;
         if constexpr (sizeof(T) == sizeof(uint16_t)) {
-            #ifndef NPY_DISABLE_OPTIMIZATION
-                #include "x86_simd_qsort_16bit.dispatch.h"
-            #endif
+            #include "x86_simd_qsort_16bit.dispatch.h"
             NPY_CPU_DISPATCH_CALL_XB(dispfunc = np::qsort_simd::template QSelect, );
         }
         else if constexpr (sizeof(T) == sizeof(uint32_t) || sizeof(T) == sizeof(uint64_t)) {
-            #ifndef NPY_DISABLE_OPTIMIZATION
-                #include "x86_simd_qsort.dispatch.h"
-            #endif
+            #include "x86_simd_qsort.dispatch.h"
             NPY_CPU_DISPATCH_CALL_XB(dispfunc = np::qsort_simd::template QSelect, );
         }
         if (dispfunc) {
@@ -76,9 +72,7 @@ inline bool argquickselect_dispatch(T* v, npy_intp* arg, npy_intp num, npy_intp
         (std::is_integral_v || std::is_floating_point_v) &&
         (sizeof(T) == sizeof(uint32_t) || sizeof(T) == sizeof(uint64_t))) {
         using TF = typename np::meta::FixedWidth::Type;
-        #ifndef NPY_DISABLE_OPTIMIZATION
-            #include "x86_simd_argsort.dispatch.h"
-        #endif
+        #include "x86_simd_argsort.dispatch.h"
         void (*dispfunc)(TF*, npy_intp*, npy_intp, npy_intp) = nullptr;
         NPY_CPU_DISPATCH_CALL_XB(dispfunc = np::qsort_simd::template ArgQSelect, );
         if (dispfunc) {
diff --git a/numpy/_core/src/npysort/x86_simd_qsort.hpp b/numpy/_core/src/npysort/x86_simd_qsort.hpp
index 79ee48c91a55..e12385689deb 100644
--- a/numpy/_core/src/npysort/x86_simd_qsort.hpp
+++ b/numpy/_core/src/npysort/x86_simd_qsort.hpp
@@ -5,21 +5,15 @@
 
 namespace np { namespace qsort_simd {
 
-#ifndef NPY_DISABLE_OPTIMIZATION
-    #include "x86_simd_qsort.dispatch.h"
-#endif
+#include "x86_simd_qsort.dispatch.h"
 NPY_CPU_DISPATCH_DECLARE(template  void QSort, (T *arr, npy_intp size))
 NPY_CPU_DISPATCH_DECLARE(template  void QSelect, (T* arr, npy_intp num, npy_intp kth))
 
-#ifndef NPY_DISABLE_OPTIMIZATION
-    #include "x86_simd_argsort.dispatch.h"
-#endif
+#include "x86_simd_argsort.dispatch.h"
 NPY_CPU_DISPATCH_DECLARE(template  void ArgQSort, (T *arr, npy_intp* arg, npy_intp size))
 NPY_CPU_DISPATCH_DECLARE(template  void ArgQSelect, (T *arr, npy_intp* arg, npy_intp kth, npy_intp size))
 
-#ifndef NPY_DISABLE_OPTIMIZATION
-    #include "x86_simd_qsort_16bit.dispatch.h"
-#endif
+#include "x86_simd_qsort_16bit.dispatch.h"
 NPY_CPU_DISPATCH_DECLARE(template  void QSort, (T *arr, npy_intp size))
 NPY_CPU_DISPATCH_DECLARE(template  void QSelect, (T* arr, npy_intp num, npy_intp kth))
 
diff --git a/numpy/_core/src/umath/_umath_tests.c.src b/numpy/_core/src/umath/_umath_tests.c.src
index c1bcc3c8957e..9f2818d14526 100644
--- a/numpy/_core/src/umath/_umath_tests.c.src
+++ b/numpy/_core/src/umath/_umath_tests.c.src
@@ -682,9 +682,7 @@ fail:
 }
 
 // Testing the utilities of the CPU dispatcher
-#ifndef NPY_DISABLE_OPTIMIZATION
-    #include "_umath_tests.dispatch.h"
-#endif
+#include "_umath_tests.dispatch.h"
 NPY_CPU_DISPATCH_DECLARE(extern const char *_umath_tests_dispatch_var)
 NPY_CPU_DISPATCH_DECLARE(const char *_umath_tests_dispatch_func, (void))
 NPY_CPU_DISPATCH_DECLARE(void _umath_tests_dispatch_attach, (PyObject *list))
diff --git a/numpy/_core/src/umath/_umath_tests.dispatch.c b/numpy/_core/src/umath/_umath_tests.dispatch.c
index 70a4c6d825e3..e92356ac09f2 100644
--- a/numpy/_core/src/umath/_umath_tests.dispatch.c
+++ b/numpy/_core/src/umath/_umath_tests.dispatch.c
@@ -1,10 +1,5 @@
 /**
  * Testing the utilities of the CPU dispatcher
- *
- * @targets $werror baseline
- * SSE2 SSE41 AVX2
- * VSX VSX2 VSX3
- * NEON ASIMD ASIMDHP
  */
 #define PY_SSIZE_T_CLEAN
 #include 
@@ -12,10 +7,7 @@
 #include "npy_cpu_dispatch.h"
 #include "numpy/utils.h" // NPY_TOSTRING
 
-#ifndef NPY_DISABLE_OPTIMIZATION
-    #include "_umath_tests.dispatch.h"
-#endif
-
+#include "_umath_tests.dispatch.h"
 NPY_CPU_DISPATCH_DECLARE(const char *_umath_tests_dispatch_func, (void))
 NPY_CPU_DISPATCH_DECLARE(extern const char *_umath_tests_dispatch_var)
 NPY_CPU_DISPATCH_DECLARE(void _umath_tests_dispatch_attach, (PyObject *list))
diff --git a/numpy/_core/src/umath/loops.h.src b/numpy/_core/src/umath/loops.h.src
index 3639345d2cd3..4163f2e65c29 100644
--- a/numpy/_core/src/umath/loops.h.src
+++ b/numpy/_core/src/umath/loops.h.src
@@ -40,10 +40,8 @@ extern "C" {
 typedef struct PyArrayMethod_Context_tag PyArrayMethod_Context;
 typedef struct NpyAuxData_tag NpyAuxData;
 
-#ifndef NPY_DISABLE_OPTIMIZATION
-    #include "loops_comparison.dispatch.h"
-#endif
 
+#include "loops_comparison.dispatch.h"
 /**begin repeat
  * #kind = equal, not_equal, greater, greater_equal, less, less_equal#
  */
@@ -51,10 +49,8 @@ NPY_CPU_DISPATCH_DECLARE(NPY_NO_EXPORT void BOOL_@kind@,
     (char **args, npy_intp const *dimensions, npy_intp const *steps, void *NPY_UNUSED(func)))
 /**end repeat**/
 
-#ifndef NPY_DISABLE_OPTIMIZATION
-    #include "loops_logical.dispatch.h"
-#endif
 
+#include "loops_logical.dispatch.h"
 /**begin repeat
  * #kind = logical_and, logical_or, logical_not, absolute#
  */
@@ -73,9 +69,7 @@ BOOL_@kind@(char **args, npy_intp const *dimensions, npy_intp const *steps, void
 /**end repeat**/
 
 
-#ifndef NPY_DISABLE_OPTIMIZATION
-    #include "loops_autovec.dispatch.h"
-#endif
+#include "loops_autovec.dispatch.h"
 /**begin repeat
  * #kind = isnan, isinf, isfinite, floor, ceil, trunc#
  */
@@ -89,10 +83,7 @@ NPY_CPU_DISPATCH_DECLARE(NPY_NO_EXPORT void BOOL_@kind@,
  *****************************************************************************
  */
 
-#ifndef NPY_DISABLE_OPTIMIZATION
-    #include "loops_arithmetic.dispatch.h"
-#endif
-
+#include "loops_arithmetic.dispatch.h"
 /**begin repeat
  * #TYPE = UBYTE, USHORT, UINT, ULONG, ULONGLONG,
            BYTE,  SHORT,  INT,  LONG,  LONGLONG#
@@ -106,10 +97,7 @@ NPY_NO_EXPORT int
 /**end repeat3**/
 /**end repeat**/
 
-#ifndef NPY_DISABLE_OPTIMIZATION
-    #include "loops_modulo.dispatch.h"
-#endif
-
+#include "loops_modulo.dispatch.h"
 /**begin repeat
  * #TYPE = UBYTE, USHORT, UINT, ULONG, ULONGLONG,
            BYTE,  SHORT,  INT,  LONG,  LONGLONG#
@@ -122,10 +110,7 @@ NPY_CPU_DISPATCH_DECLARE(NPY_NO_EXPORT void @TYPE@_@kind@,
 /**end repeat1**/
 /**end repeat**/
 
-#ifndef NPY_DISABLE_OPTIMIZATION
-    #include "loops_comparison.dispatch.h"
-#endif
-
+#include "loops_comparison.dispatch.h"
 /**begin repeat
  * #TYPE = UBYTE, USHORT, UINT, ULONG, ULONGLONG,
            BYTE,  SHORT,  INT,  LONG,  LONGLONG#
@@ -139,9 +124,8 @@ NPY_CPU_DISPATCH_DECLARE(NPY_NO_EXPORT void @TYPE@_@kind@,
 /**end repeat**/
 
 
-#ifndef NPY_DISABLE_OPTIMIZATION
-    #include "loops_autovec.dispatch.h"
-#endif
+
+#include "loops_autovec.dispatch.h"
 /**begin repeat
  * #TYPE = UBYTE, USHORT, UINT, ULONG, ULONGLONG,
            BYTE,  SHORT,  INT,  LONG,  LONGLONG#
@@ -234,9 +218,7 @@ LONGLONG_qQ_bool_@kind@(char **args, npy_intp const *dimensions, npy_intp const
 /**end repeat**/
 
 
-#ifndef NPY_DISABLE_OPTIMIZATION
-    #include "loops_unary.dispatch.h"
-#endif
+#include "loops_unary.dispatch.h"
 /**begin repeat
  * #TYPE = UBYTE, USHORT, UINT, ULONG, ULONGLONG,
  *         BYTE,  SHORT,  INT,  LONG,  LONGLONG#
@@ -255,9 +237,7 @@ NPY_CPU_DISPATCH_DECLARE(NPY_NO_EXPORT void @TYPE@_@kind@,
  **                             FLOAT LOOPS                                 **
  *****************************************************************************
  */
-#ifndef NPY_DISABLE_OPTIMIZATION
-    #include "loops_unary_fp.dispatch.h"
-#endif
+#include "loops_unary_fp.dispatch.h"
 /**begin repeat
  *  #TYPE = FLOAT, DOUBLE#
  */
@@ -269,9 +249,7 @@ NPY_CPU_DISPATCH_DECLARE(NPY_NO_EXPORT void @TYPE@_@kind@,
 /**end repeat1**/
 /**end repeat**/
 
-#ifndef NPY_DISABLE_OPTIMIZATION
-    #include "loops_unary_fp_le.dispatch.h"
-#endif
+#include "loops_unary_fp_le.dispatch.h"
 /**begin repeat
  *  #TYPE = FLOAT, DOUBLE#
  */
@@ -283,9 +261,7 @@ NPY_CPU_DISPATCH_DECLARE(NPY_NO_EXPORT void @TYPE@_@kind@,
 /**end repeat1**/
 /**end repeat**/
 
-#ifndef NPY_DISABLE_OPTIMIZATION
-    #include "loops_unary.dispatch.h"
-#endif
+#include "loops_unary.dispatch.h"
 /**begin repeat
  *  #TYPE = FLOAT, DOUBLE, LONGDOUBLE#
  */
@@ -297,9 +273,7 @@ NPY_CPU_DISPATCH_DECLARE(NPY_NO_EXPORT void @TYPE@_@kind@,
 /**end repeat1**/
 /**end repeat**/
 
-#ifndef NPY_DISABLE_OPTIMIZATION
-    #include "loops_arithm_fp.dispatch.h"
-#endif
+#include "loops_arithm_fp.dispatch.h"
 /**begin repeat
  *  #TYPE = FLOAT, DOUBLE#
  */
@@ -316,9 +290,7 @@ NPY_NO_EXPORT int
 /**end repeat1**/
 /**end repeat**/
 
-#ifndef NPY_DISABLE_OPTIMIZATION
-    #include "loops_hyperbolic.dispatch.h"
-#endif
+#include "loops_hyperbolic.dispatch.h"
 /**begin repeat
  *  #TYPE = FLOAT, DOUBLE#
  */
@@ -331,10 +303,7 @@ NPY_CPU_DISPATCH_DECLARE(NPY_NO_EXPORT void @TYPE@_@func@,
 /**end repeat**/
 
 // SVML
-#ifndef NPY_DISABLE_OPTIMIZATION
-    #include "loops_umath_fp.dispatch.h"
-#endif
-
+#include "loops_umath_fp.dispatch.h"
 /**begin repeat
  *  #TYPE = FLOAT, DOUBLE#
  */
@@ -373,10 +342,7 @@ NPY_CPU_DISPATCH_DECLARE(NPY_NO_EXPORT void @TYPE@_@func@,
 /**end repeat1**/
 /**end repeat**/
 
-#ifndef NPY_DISABLE_OPTIMIZATION
-    #include "loops_trigonometric.dispatch.h"
-#endif
-
+#include "loops_trigonometric.dispatch.h"
 /**begin repeat
  *  #TYPE = FLOAT, DOUBLE#
  */
@@ -389,9 +355,7 @@ NPY_CPU_DISPATCH_DECLARE(NPY_NO_EXPORT void @TYPE@_@func@, (
 /**end repeat1**/
 /**end repeat**/
 
-#ifndef NPY_DISABLE_OPTIMIZATION
-    #include "loops_exponent_log.dispatch.h"
-#endif
+#include "loops_exponent_log.dispatch.h"
 /**begin repeat
  *  #TYPE = FLOAT, DOUBLE#
  */
@@ -404,9 +368,7 @@ NPY_CPU_DISPATCH_DECLARE(NPY_NO_EXPORT void @TYPE@_@kind@, (
 /**end repeat1**/
 /**end repeat**/
 
-#ifndef NPY_DISABLE_OPTIMIZATION
-    #include "loops_comparison.dispatch.h"
-#endif
+#include "loops_comparison.dispatch.h"
 /**begin repeat
  *  #TYPE = FLOAT, DOUBLE#
  */
@@ -553,9 +515,7 @@ NPY_NO_EXPORT void
 /**end repeat1**/
 /**end repeat**/
 
-#ifndef NPY_DISABLE_OPTIMIZATION
-    #include "loops_autovec.dispatch.h"
-#endif
+#include "loops_autovec.dispatch.h"
 /**begin repeat
  * #TYPE = HALF#
  */
@@ -571,9 +531,7 @@ NPY_CPU_DISPATCH_DECLARE(NPY_NO_EXPORT void @TYPE@_@kind@,
  **                           COMPLEX LOOPS                                 **
  *****************************************************************************
  */
-#ifndef NPY_DISABLE_OPTIMIZATION
-    #include "loops_arithm_fp.dispatch.h"
-#endif
+#include "loops_arithm_fp.dispatch.h"
 /**begin repeat
  * #TYPE = CFLOAT, CDOUBLE#
  */
@@ -585,9 +543,7 @@ NPY_CPU_DISPATCH_DECLARE(NPY_NO_EXPORT void @TYPE@_@kind@,
 /**end repeat1**/
 /**end repeat**/
 
-#ifndef NPY_DISABLE_OPTIMIZATION
-    #include "loops_unary_complex.dispatch.h"
-#endif
+#include "loops_unary_complex.dispatch.h"
 /**begin repeat
  * #TYPE = CFLOAT, CDOUBLE#
  */
@@ -808,9 +764,7 @@ TIMEDELTA_mm_qm_divmod(char **args, npy_intp const *dimensions, npy_intp const *
 /* #define TIMEDELTA_mm_d_floor_divide TIMEDELTA_mm_d_divide */
 
 
-#ifndef NPY_DISABLE_OPTIMIZATION
-    #include "loops_autovec.dispatch.h"
-#endif
+#include "loops_autovec.dispatch.h"
 /**begin repeat
  * #TYPE = TIMEDELTA, DATETIME#
  */
@@ -852,9 +806,7 @@ PyUFunc_OOO_O(char **args, npy_intp const *dimensions, npy_intp const *steps, vo
  *****************************************************************************
  */
 
-#ifndef NPY_DISABLE_OPTIMIZATION
-    #include "loops_minmax.dispatch.h"
-#endif
+#include "loops_minmax.dispatch.h"
 
 //---------- Integers ----------
 
diff --git a/numpy/_core/src/umath/loops_arithm_fp.dispatch.c.src b/numpy/_core/src/umath/loops_arithm_fp.dispatch.c.src
index 9defead3075d..94bc24811e1d 100644
--- a/numpy/_core/src/umath/loops_arithm_fp.dispatch.c.src
+++ b/numpy/_core/src/umath/loops_arithm_fp.dispatch.c.src
@@ -1,10 +1,3 @@
-/*@targets
- ** $maxopt baseline
- ** sse2 (avx2 fma3)
- ** neon asimd
- ** vsx2 vsx3
- ** vx vxe
- **/
 #define _UMATHMODULE
 #define _MULTIARRAYMODULE
 #define NPY_NO_DEPRECATED_API NPY_API_VERSION
diff --git a/numpy/_core/src/umath/loops_arithmetic.dispatch.c.src b/numpy/_core/src/umath/loops_arithmetic.dispatch.c.src
index d330c21695d5..c9efe5579e71 100644
--- a/numpy/_core/src/umath/loops_arithmetic.dispatch.c.src
+++ b/numpy/_core/src/umath/loops_arithmetic.dispatch.c.src
@@ -1,10 +1,3 @@
-/*@targets
- ** $maxopt baseline
- ** sse2 sse41 avx2 avx512f avx512_skx
- ** vsx2 vsx4
- ** neon
- ** vx
- **/
 #define _UMATHMODULE
 #define _MULTIARRAYMODULE
 #define NPY_NO_DEPRECATED_API NPY_API_VERSION
diff --git a/numpy/_core/src/umath/loops_autovec.dispatch.c.src b/numpy/_core/src/umath/loops_autovec.dispatch.c.src
index e93e851d6b7a..983fa1b5eb80 100644
--- a/numpy/_core/src/umath/loops_autovec.dispatch.c.src
+++ b/numpy/_core/src/umath/loops_autovec.dispatch.c.src
@@ -1,10 +1,3 @@
-/*@targets
- ** $maxopt $autovec baseline
- ** sse2 avx2
- ** neon
- ** vsx2
- ** vx
- **/
 #define _UMATHMODULE
 #define _MULTIARRAYMODULE
 #define NPY_NO_DEPRECATED_API NPY_API_VERSION
diff --git a/numpy/_core/src/umath/loops_comparison.dispatch.c.src b/numpy/_core/src/umath/loops_comparison.dispatch.c.src
index 7510808714a3..6450bed962b1 100644
--- a/numpy/_core/src/umath/loops_comparison.dispatch.c.src
+++ b/numpy/_core/src/umath/loops_comparison.dispatch.c.src
@@ -1,10 +1,3 @@
-/*@targets
- ** $maxopt baseline
- ** sse2 sse42 avx2 avx512f avx512_skx
- ** vsx2 vsx3
- ** neon
- ** vx vxe
- **/
 #define _UMATHMODULE
 #define _MULTIARRAYMODULE
 #define NPY_NO_DEPRECATED_API NPY_API_VERSION
diff --git a/numpy/_core/src/umath/loops_exponent_log.dispatch.c.src b/numpy/_core/src/umath/loops_exponent_log.dispatch.c.src
index 190ea6b8be72..316b612f1a02 100644
--- a/numpy/_core/src/umath/loops_exponent_log.dispatch.c.src
+++ b/numpy/_core/src/umath/loops_exponent_log.dispatch.c.src
@@ -1,8 +1,3 @@
-/*@targets
- ** $maxopt baseline
- ** (avx2 fma3) avx512f avx512_skx
- **/
-
 #define _UMATHMODULE
 #define _MULTIARRAYMODULE
 #define NPY_NO_DEPRECATED_API NPY_API_VERSION
diff --git a/numpy/_core/src/umath/loops_hyperbolic.dispatch.cpp.src b/numpy/_core/src/umath/loops_hyperbolic.dispatch.cpp.src
index e12a98864d96..8c66229942ee 100755
--- a/numpy/_core/src/umath/loops_hyperbolic.dispatch.cpp.src
+++ b/numpy/_core/src/umath/loops_hyperbolic.dispatch.cpp.src
@@ -1,11 +1,3 @@
-/*@targets
- ** $maxopt baseline
- ** (avx2 fma3) AVX512_SKX
- ** vsx2 vsx4
- ** neon_vfpv4
- ** vxe
- **/
-
 #include "numpy/npy_math.h"
 #include "simd/simd.h"
 #include "loops_utils.h"
diff --git a/numpy/_core/src/umath/loops_minmax.dispatch.c.src b/numpy/_core/src/umath/loops_minmax.dispatch.c.src
index a67e7d490f5b..c11f391f9159 100644
--- a/numpy/_core/src/umath/loops_minmax.dispatch.c.src
+++ b/numpy/_core/src/umath/loops_minmax.dispatch.c.src
@@ -1,10 +1,3 @@
-/*@targets
- ** $maxopt baseline
- ** neon asimd
- ** sse2 avx2 avx512_skx
- ** vsx2
- ** vx vxe
- **/
 #define _UMATHMODULE
 #define _MULTIARRAYMODULE
 #define NPY_NO_DEPRECATED_API NPY_API_VERSION
diff --git a/numpy/_core/src/umath/loops_modulo.dispatch.c.src b/numpy/_core/src/umath/loops_modulo.dispatch.c.src
index 25edffb1e2c1..032cc3344060 100644
--- a/numpy/_core/src/umath/loops_modulo.dispatch.c.src
+++ b/numpy/_core/src/umath/loops_modulo.dispatch.c.src
@@ -1,6 +1,3 @@
-/*@targets
- ** baseline vsx4
- **/
 #define _UMATHMODULE
 #define _MULTIARRAYMODULE
 #define NPY_NO_DEPRECATED_API NPY_API_VERSION
diff --git a/numpy/_core/src/umath/loops_umath_fp.dispatch.c.src b/numpy/_core/src/umath/loops_umath_fp.dispatch.c.src
index 25edf44cf677..1a6dbbb9cac3 100644
--- a/numpy/_core/src/umath/loops_umath_fp.dispatch.c.src
+++ b/numpy/_core/src/umath/loops_umath_fp.dispatch.c.src
@@ -1,6 +1,3 @@
-/*@targets
- ** $maxopt baseline avx512_skx
- */
 #include "numpy/npy_math.h"
 #include "simd/simd.h"
 #include "loops_utils.h"
diff --git a/numpy/_core/src/umath/loops_unary.dispatch.c.src b/numpy/_core/src/umath/loops_unary.dispatch.c.src
index 4c87c2279c3b..951aa5be5240 100644
--- a/numpy/_core/src/umath/loops_unary.dispatch.c.src
+++ b/numpy/_core/src/umath/loops_unary.dispatch.c.src
@@ -1,11 +1,3 @@
-/*@targets
- ** $maxopt baseline
- ** neon asimd
- ** sse2 avx2 avx512_skx
- ** vsx2
- ** vx vxe
- **/
-
 #define _UMATHMODULE
 #define _MULTIARRAYMODULE
 #define NPY_NO_DEPRECATED_API NPY_API_VERSION
diff --git a/numpy/_core/src/umath/loops_unary_complex.dispatch.c.src b/numpy/_core/src/umath/loops_unary_complex.dispatch.c.src
index ede46485313b..4b4457e6aada 100644
--- a/numpy/_core/src/umath/loops_unary_complex.dispatch.c.src
+++ b/numpy/_core/src/umath/loops_unary_complex.dispatch.c.src
@@ -1,10 +1,3 @@
-/*@targets
- ** $maxopt baseline
- ** sse2 (avx2 fma3) avx512f
- ** neon asimd
- ** vsx2 vsx3
- ** vx vxe
- **/
 #define _UMATHMODULE
 #define _MULTIARRAYMODULE
 #define NPY_NO_DEPRECATED_API NPY_API_VERSION
diff --git a/numpy/_core/src/umath/loops_unary_fp.dispatch.c.src b/numpy/_core/src/umath/loops_unary_fp.dispatch.c.src
index 6cce02cd37bc..85f74839eba7 100644
--- a/numpy/_core/src/umath/loops_unary_fp.dispatch.c.src
+++ b/numpy/_core/src/umath/loops_unary_fp.dispatch.c.src
@@ -1,10 +1,3 @@
-/*@targets
- ** $maxopt baseline
- ** sse2 sse41
- ** vsx2
- ** neon asimd
- ** vx vxe
- **/
 /**
  * Force use SSE only on x86, even if AVX2 or AVX512F are enabled
  * through the baseline, since scatter(AVX512F) and gather very costly
diff --git a/numpy/_core/src/umath/loops_unary_fp_le.dispatch.c.src b/numpy/_core/src/umath/loops_unary_fp_le.dispatch.c.src
index 9f7ed6c1dfc4..ca02bc85608e 100644
--- a/numpy/_core/src/umath/loops_unary_fp_le.dispatch.c.src
+++ b/numpy/_core/src/umath/loops_unary_fp_le.dispatch.c.src
@@ -1,10 +1,3 @@
-/*@targets
- ** $maxopt baseline
- ** sse2 sse41
- ** vsx2
- ** neon asimd
- **/
-
 /**
  * Force use SSE only on x86, even if AVX2 or AVX512F are enabled
  * through the baseline, since scatter(AVX512F) and gather very costly

From 1bc8764f132501a8ee4649696488acbe796fe50f Mon Sep 17 00:00:00 2001
From: Nathan Goldbaum 
Date: Wed, 23 Apr 2025 08:50:16 -0600
Subject: [PATCH 081/202] TST: skip test if spawning threads triggers a
 RuntimeError (#28798)

---
 numpy/testing/_private/utils.py | 5 +++++
 1 file changed, 5 insertions(+)

diff --git a/numpy/testing/_private/utils.py b/numpy/testing/_private/utils.py
index 9fb96796bac4..0074d77bce0c 100644
--- a/numpy/testing/_private/utils.py
+++ b/numpy/testing/_private/utils.py
@@ -2741,6 +2741,11 @@ def run_threaded(func, max_workers=8, pass_count=False,
                 futures = []
                 for arg in all_args:
                     futures.append(tpe.submit(*arg))
+            except RuntimeError as e:
+                import pytest
+                pytest.skip(f"Spawning {max_workers} threads failed with "
+                            f"error {e!r} (likely due to resource limits on the "
+                            "system running the tests)")
             finally:
                 if len(futures) < max_workers and pass_barrier:
                     barrier.abort()

From 628b99d990aef09a828c801113b6c56ab96392f6 Mon Sep 17 00:00:00 2001
From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com>
Date: Wed, 23 Apr 2025 17:07:32 +0000
Subject: [PATCH 082/202] MAINT: Bump github/codeql-action from 3.28.15 to
 3.28.16

Bumps [github/codeql-action](https://github.com/github/codeql-action) from 3.28.15 to 3.28.16.
- [Release notes](https://github.com/github/codeql-action/releases)
- [Changelog](https://github.com/github/codeql-action/blob/main/CHANGELOG.md)
- [Commits](https://github.com/github/codeql-action/compare/45775bd8235c68ba998cffa5171334d58593da47...28deaeda66b76a05916b6923827895f2b14ab387)

---
updated-dependencies:
- dependency-name: github/codeql-action
  dependency-version: 3.28.16
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] 
---
 .github/workflows/codeql.yml     | 6 +++---
 .github/workflows/scorecards.yml | 2 +-
 2 files changed, 4 insertions(+), 4 deletions(-)

diff --git a/.github/workflows/codeql.yml b/.github/workflows/codeql.yml
index e49b3e9e796f..68e75754346a 100644
--- a/.github/workflows/codeql.yml
+++ b/.github/workflows/codeql.yml
@@ -47,7 +47,7 @@ jobs:
 
       # Initializes the CodeQL tools for scanning.
       - name: Initialize CodeQL
-        uses: github/codeql-action/init@45775bd8235c68ba998cffa5171334d58593da47 # v3.28.15
+        uses: github/codeql-action/init@28deaeda66b76a05916b6923827895f2b14ab387 # v3.28.16
         with:
           languages: ${{ matrix.language }}
           # If you wish to specify custom queries, you can do so here or in a config file.
@@ -57,7 +57,7 @@ jobs:
       # Autobuild attempts to build any compiled languages  (C/C++, C#, or Java).
       # If this step fails, then you should remove it and run the build manually (see below)
       - name: Autobuild
-        uses: github/codeql-action/autobuild@45775bd8235c68ba998cffa5171334d58593da47 # v3.28.15
+        uses: github/codeql-action/autobuild@28deaeda66b76a05916b6923827895f2b14ab387 # v3.28.16
 
       # ℹ️ Command-line programs to run using the OS shell.
       # 📚 See https://docs.github.com/en/actions/using-workflows/workflow-syntax-for-github-actions#jobsjob_idstepsrun
@@ -70,6 +70,6 @@ jobs:
       #   ./location_of_script_within_repo/buildscript.sh
 
       - name: Perform CodeQL Analysis
-        uses: github/codeql-action/analyze@45775bd8235c68ba998cffa5171334d58593da47 # v3.28.15
+        uses: github/codeql-action/analyze@28deaeda66b76a05916b6923827895f2b14ab387 # v3.28.16
         with:
           category: "/language:${{matrix.language}}"
diff --git a/.github/workflows/scorecards.yml b/.github/workflows/scorecards.yml
index 50e338503763..c2b15262ea41 100644
--- a/.github/workflows/scorecards.yml
+++ b/.github/workflows/scorecards.yml
@@ -50,6 +50,6 @@ jobs:
 
       # Upload the results to GitHub's code scanning dashboard.
       - name: "Upload to code-scanning"
-        uses: github/codeql-action/upload-sarif@45775bd8235c68ba998cffa5171334d58593da47 # v2.1.27
+        uses: github/codeql-action/upload-sarif@28deaeda66b76a05916b6923827895f2b14ab387 # v2.1.27
         with:
           sarif_file: results.sarif

From 8362f533ca8aa703a093feeaaf5b5aead78c781e Mon Sep 17 00:00:00 2001
From: Marco Edward Gorelli 
Date: Wed, 23 Apr 2025 20:21:07 +0200
Subject: [PATCH 083/202] TYP: Type ``np.ma.allclose`` and ``np.ma.allequal``
 (#28793)

---
 numpy/ma/core.pyi                     | 7 +++++--
 numpy/typing/tests/data/fail/ma.pyi   | 6 ++++++
 numpy/typing/tests/data/reveal/ma.pyi | 7 +++++++
 3 files changed, 18 insertions(+), 2 deletions(-)

diff --git a/numpy/ma/core.pyi b/numpy/ma/core.pyi
index 8cd8fec97852..6ce080ada9fb 100644
--- a/numpy/ma/core.pyi
+++ b/numpy/ma/core.pyi
@@ -1184,8 +1184,11 @@ outerproduct = outer
 
 def correlate(a, v, mode=..., propagate_mask=...): ...
 def convolve(a, v, mode=..., propagate_mask=...): ...
-def allequal(a, b, fill_value=...): ...
-def allclose(a, b, masked_equal=..., rtol=..., atol=...): ...
+
+def allequal(a: ArrayLike, b: ArrayLike, fill_value: bool = True) -> bool: ...
+
+def allclose(a: ArrayLike, b: ArrayLike, masked_equal: bool = True, rtol: float = 1e-5, atol: float = 1e-8) -> bool: ...
+
 def asarray(a, dtype=..., order=...): ...
 def asanyarray(a, dtype=...): ...
 def fromflex(fxarray): ...
diff --git a/numpy/typing/tests/data/fail/ma.pyi b/numpy/typing/tests/data/fail/ma.pyi
index e0b7df5b6ab7..a4f2517fd4a6 100644
--- a/numpy/typing/tests/data/fail/ma.pyi
+++ b/numpy/typing/tests/data/fail/ma.pyi
@@ -116,3 +116,9 @@ np.ma.put(m, 4, 999, mode='flip')  # E: No overload variant
 np.ma.put([1,1,3], 0, 999)  # E: No overload variant
 
 np.ma.compressed(lambda: 'compress me')  # E: No overload variant
+
+np.ma.allequal(m, [1,2,3], fill_value=1.5)  # E: No overload variant
+
+np.ma.allclose(m, [1,2,3], masked_equal=4.5)  # E: No overload variant
+np.ma.allclose(m, [1,2,3], rtol='.4')  # E: No overload variant
+np.ma.allclose(m, [1,2,3], atol='.5')  # E: No overload variant
diff --git a/numpy/typing/tests/data/reveal/ma.pyi b/numpy/typing/tests/data/reveal/ma.pyi
index 0a2fe6d593ec..8c49d989c1ca 100644
--- a/numpy/typing/tests/data/reveal/ma.pyi
+++ b/numpy/typing/tests/data/reveal/ma.pyi
@@ -273,3 +273,10 @@ assert_type(np.ma.filled([[1,2,3]]), NDArray[Any])
 # PyRight detects this one correctly, but mypy doesn't.
 # https://github.com/numpy/numpy/pull/28742#discussion_r2048968375
 assert_type(np.ma.filled(MAR_1d), np.ndarray[tuple[int], np.dtype])  # type: ignore[assert-type]
+
+assert_type(np.ma.allequal(AR_f4, MAR_f4), bool)
+assert_type(np.ma.allequal(AR_f4, MAR_f4, fill_value=False), bool)
+
+assert_type(np.ma.allclose(AR_f4, MAR_f4), bool)
+assert_type(np.ma.allclose(AR_f4, MAR_f4, masked_equal=False), bool)
+assert_type(np.ma.allclose(AR_f4, MAR_f4, rtol=.4, atol=.3), bool)

From 8b8f8923ed4384389968eb3dd81f15515b2bf0c0 Mon Sep 17 00:00:00 2001
From: Nathan Goldbaum 
Date: Wed, 23 Apr 2025 11:51:54 -0600
Subject: [PATCH 084/202] BUG: fix heap buffer overflow in np.strings.find

---
 numpy/_core/src/umath/string_fastsearch.h | 12 ++----------
 numpy/_core/tests/test_strings.py         |  2 ++
 2 files changed, 4 insertions(+), 10 deletions(-)

diff --git a/numpy/_core/src/umath/string_fastsearch.h b/numpy/_core/src/umath/string_fastsearch.h
index 54092d8b293d..95d0ee4fb214 100644
--- a/numpy/_core/src/umath/string_fastsearch.h
+++ b/numpy/_core/src/umath/string_fastsearch.h
@@ -670,16 +670,8 @@ preprocess(CheckedIndexer needle, Py_ssize_t len_needle,
     assert(p->period + p->cut <= len_needle);
 
     // Compare parts of the needle to check for periodicity.
-    int cmp;
-    if (std::is_same::value) {
-        cmp = memcmp(needle.buffer,
-                needle.buffer + (p->period * sizeof(npy_ucs4)),
-                (size_t) p->cut);
-    }
-    else {
-        cmp = memcmp(needle.buffer, needle.buffer + p->period,
-                (size_t) p->cut);
-    }
+    int cmp = memcmp(needle.buffer, needle.buffer + p->period,
+                     (size_t) p->cut);
     p->is_periodic = (0 == cmp);
 
     // If periodic, gap is unused; otherwise, calculate period and gap.
diff --git a/numpy/_core/tests/test_strings.py b/numpy/_core/tests/test_strings.py
index 40d830c3d4a4..7960142162c5 100644
--- a/numpy/_core/tests/test_strings.py
+++ b/numpy/_core/tests/test_strings.py
@@ -381,6 +381,8 @@ def test_str_len(self, in_, out, dt):
          None, [3, -1]),
         ("Ae¢☃€ 😊" * 2, "😊", 0, None, 6),
         ("Ae¢☃€ 😊" * 2, "😊", 7, None, 13),
+        pytest.param("A" * (2 ** 17), r"[\w]+\Z", 0, None, -1,
+                     id=r"A*2**17-[\w]+\Z-0-None--1"),
     ])
     def test_find(self, a, sub, start, end, out, dt):
         if "😊" in a and dt == "S":

From f77bb1ef81f3d2092012ae83f41b2732321d3cfb Mon Sep 17 00:00:00 2001
From: jorenham 
Date: Thu, 24 Apr 2025 02:15:50 +0200
Subject: [PATCH 085/202] TYP: fix ``NDArray[floating] + float`` return type

---
 numpy/__init__.pyi                            | 52 +++++++++----------
 numpy/typing/tests/data/reveal/arithmetic.pyi | 23 +++++++-
 2 files changed, 48 insertions(+), 27 deletions(-)

diff --git a/numpy/__init__.pyi b/numpy/__init__.pyi
index 0870d1da5248..ff3fbf667228 100644
--- a/numpy/__init__.pyi
+++ b/numpy/__init__.pyi
@@ -2731,7 +2731,7 @@ class ndarray(_ArrayOrScalarCommon, Generic[_ShapeT_co, _DTypeT_co]):
     @overload
     def __mod__(self: NDArray[np.bool], other: _ArrayLike[_RealNumberT], /) -> NDArray[_RealNumberT]: ...  # type: ignore[overload-overlap]
     @overload
-    def __mod__(self: NDArray[floating[_64Bit]], other: _ArrayLikeFloat64_co, /) -> NDArray[float64]: ...
+    def __mod__(self: NDArray[float64], other: _ArrayLikeFloat64_co, /) -> NDArray[float64]: ...
     @overload
     def __mod__(self: _ArrayFloat64_co, other: _ArrayLike[floating[_64Bit]], /) -> NDArray[float64]: ...
     @overload
@@ -2756,7 +2756,7 @@ class ndarray(_ArrayOrScalarCommon, Generic[_ShapeT_co, _DTypeT_co]):
     @overload
     def __rmod__(self: NDArray[np.bool], other: _ArrayLike[_RealNumberT], /) -> NDArray[_RealNumberT]: ...  # type: ignore[overload-overlap]
     @overload
-    def __rmod__(self: NDArray[floating[_64Bit]], other: _ArrayLikeFloat64_co, /) -> NDArray[float64]: ...
+    def __rmod__(self: NDArray[float64], other: _ArrayLikeFloat64_co, /) -> NDArray[float64]: ...
     @overload
     def __rmod__(self: _ArrayFloat64_co, other: _ArrayLike[floating[_64Bit]], /) -> NDArray[float64]: ...
     @overload
@@ -2781,7 +2781,7 @@ class ndarray(_ArrayOrScalarCommon, Generic[_ShapeT_co, _DTypeT_co]):
     @overload
     def __divmod__(self: NDArray[np.bool], rhs: _ArrayLike[_RealNumberT], /) -> _2Tuple[NDArray[_RealNumberT]]: ...  # type: ignore[overload-overlap]
     @overload
-    def __divmod__(self: NDArray[floating[_64Bit]], rhs: _ArrayLikeFloat64_co, /) -> _2Tuple[NDArray[float64]]: ...
+    def __divmod__(self: NDArray[float64], rhs: _ArrayLikeFloat64_co, /) -> _2Tuple[NDArray[float64]]: ...
     @overload
     def __divmod__(self: _ArrayFloat64_co, rhs: _ArrayLike[floating[_64Bit]], /) -> _2Tuple[NDArray[float64]]: ...
     @overload
@@ -2802,7 +2802,7 @@ class ndarray(_ArrayOrScalarCommon, Generic[_ShapeT_co, _DTypeT_co]):
     @overload
     def __rdivmod__(self: NDArray[np.bool], lhs: _ArrayLike[_RealNumberT], /) -> _2Tuple[NDArray[_RealNumberT]]: ...  # type: ignore[overload-overlap]
     @overload
-    def __rdivmod__(self: NDArray[floating[_64Bit]], lhs: _ArrayLikeFloat64_co, /) -> _2Tuple[NDArray[float64]]: ...
+    def __rdivmod__(self: NDArray[float64], lhs: _ArrayLikeFloat64_co, /) -> _2Tuple[NDArray[float64]]: ...
     @overload
     def __rdivmod__(self: _ArrayFloat64_co, lhs: _ArrayLike[floating[_64Bit]], /) -> _2Tuple[NDArray[float64]]: ...
     @overload
@@ -2823,11 +2823,11 @@ class ndarray(_ArrayOrScalarCommon, Generic[_ShapeT_co, _DTypeT_co]):
     @overload
     def __add__(self: NDArray[np.bool], other: _ArrayLike[_NumberT], /) -> NDArray[_NumberT]: ...  # type: ignore[overload-overlap]
     @overload
-    def __add__(self: NDArray[floating[_64Bit]], other: _ArrayLikeFloat64_co, /) -> NDArray[float64]: ...
+    def __add__(self: NDArray[float64], other: _ArrayLikeFloat64_co, /) -> NDArray[float64]: ...
     @overload
     def __add__(self: _ArrayFloat64_co, other: _ArrayLike[floating[_64Bit]], /) -> NDArray[float64]: ...
     @overload
-    def __add__(self: NDArray[complexfloating[_64Bit]], other: _ArrayLikeComplex128_co, /) -> NDArray[complex128]: ...
+    def __add__(self: NDArray[complex128], other: _ArrayLikeComplex128_co, /) -> NDArray[complex128]: ...
     @overload
     def __add__(self: _ArrayComplex128_co, other: _ArrayLike[complexfloating[_64Bit]], /) -> NDArray[complex128]: ...
     @overload
@@ -2860,11 +2860,11 @@ class ndarray(_ArrayOrScalarCommon, Generic[_ShapeT_co, _DTypeT_co]):
     @overload
     def __radd__(self: NDArray[np.bool], other: _ArrayLike[_NumberT], /) -> NDArray[_NumberT]: ...  # type: ignore[overload-overlap]
     @overload
-    def __radd__(self: NDArray[floating[_64Bit]], other: _ArrayLikeFloat64_co, /) -> NDArray[float64]: ...
+    def __radd__(self: NDArray[float64], other: _ArrayLikeFloat64_co, /) -> NDArray[float64]: ...
     @overload
     def __radd__(self: _ArrayFloat64_co, other: _ArrayLike[floating[_64Bit]], /) -> NDArray[float64]: ...
     @overload
-    def __radd__(self: NDArray[complexfloating[_64Bit]], other: _ArrayLikeComplex128_co, /) -> NDArray[complex128]: ...
+    def __radd__(self: NDArray[complex128], other: _ArrayLikeComplex128_co, /) -> NDArray[complex128]: ...
     @overload
     def __radd__(self: _ArrayComplex128_co, other: _ArrayLike[complexfloating[_64Bit]], /) -> NDArray[complex128]: ...
     @overload
@@ -2897,11 +2897,11 @@ class ndarray(_ArrayOrScalarCommon, Generic[_ShapeT_co, _DTypeT_co]):
     @overload
     def __sub__(self: NDArray[np.bool], other: _ArrayLike[_NumberT], /) -> NDArray[_NumberT]: ...  # type: ignore[overload-overlap]
     @overload
-    def __sub__(self: NDArray[floating[_64Bit]], other: _ArrayLikeFloat64_co, /) -> NDArray[float64]: ...
+    def __sub__(self: NDArray[float64], other: _ArrayLikeFloat64_co, /) -> NDArray[float64]: ...
     @overload
     def __sub__(self: _ArrayFloat64_co, other: _ArrayLike[floating[_64Bit]], /) -> NDArray[float64]: ...
     @overload
-    def __sub__(self: NDArray[complexfloating[_64Bit]], other: _ArrayLikeComplex128_co, /) -> NDArray[complex128]: ...
+    def __sub__(self: NDArray[complex128], other: _ArrayLikeComplex128_co, /) -> NDArray[complex128]: ...
     @overload
     def __sub__(self: _ArrayComplex128_co, other: _ArrayLike[complexfloating[_64Bit]], /) -> NDArray[complex128]: ...
     @overload
@@ -2934,11 +2934,11 @@ class ndarray(_ArrayOrScalarCommon, Generic[_ShapeT_co, _DTypeT_co]):
     @overload
     def __rsub__(self: NDArray[np.bool], other: _ArrayLike[_NumberT], /) -> NDArray[_NumberT]: ...  # type: ignore[overload-overlap]
     @overload
-    def __rsub__(self: NDArray[floating[_64Bit]], other: _ArrayLikeFloat64_co, /) -> NDArray[float64]: ...
+    def __rsub__(self: NDArray[float64], other: _ArrayLikeFloat64_co, /) -> NDArray[float64]: ...
     @overload
     def __rsub__(self: _ArrayFloat64_co, other: _ArrayLike[floating[_64Bit]], /) -> NDArray[float64]: ...
     @overload
-    def __rsub__(self: NDArray[complexfloating[_64Bit]], other: _ArrayLikeComplex128_co, /) -> NDArray[complex128]: ...
+    def __rsub__(self: NDArray[complex128], other: _ArrayLikeComplex128_co, /) -> NDArray[complex128]: ...
     @overload
     def __rsub__(self: _ArrayComplex128_co, other: _ArrayLike[complexfloating[_64Bit]], /) -> NDArray[complex128]: ...
     @overload
@@ -2971,11 +2971,11 @@ class ndarray(_ArrayOrScalarCommon, Generic[_ShapeT_co, _DTypeT_co]):
     @overload
     def __mul__(self: NDArray[np.bool], other: _ArrayLike[_NumberT], /) -> NDArray[_NumberT]: ...  # type: ignore[overload-overlap]
     @overload
-    def __mul__(self: NDArray[floating[_64Bit]], other: _ArrayLikeFloat64_co, /) -> NDArray[float64]: ...
+    def __mul__(self: NDArray[float64], other: _ArrayLikeFloat64_co, /) -> NDArray[float64]: ...
     @overload
     def __mul__(self: _ArrayFloat64_co, other: _ArrayLike[floating[_64Bit]], /) -> NDArray[float64]: ...
     @overload
-    def __mul__(self: NDArray[complexfloating[_64Bit]], other: _ArrayLikeComplex128_co, /) -> NDArray[complex128]: ...
+    def __mul__(self: NDArray[complex128], other: _ArrayLikeComplex128_co, /) -> NDArray[complex128]: ...
     @overload
     def __mul__(self: _ArrayComplex128_co, other: _ArrayLike[complexfloating[_64Bit]], /) -> NDArray[complex128]: ...
     @overload
@@ -3006,11 +3006,11 @@ class ndarray(_ArrayOrScalarCommon, Generic[_ShapeT_co, _DTypeT_co]):
     @overload
     def __rmul__(self: NDArray[np.bool], other: _ArrayLike[_NumberT], /) -> NDArray[_NumberT]: ...  # type: ignore[overload-overlap]
     @overload
-    def __rmul__(self: NDArray[floating[_64Bit]], other: _ArrayLikeFloat64_co, /) -> NDArray[float64]: ...
+    def __rmul__(self: NDArray[float64], other: _ArrayLikeFloat64_co, /) -> NDArray[float64]: ...
     @overload
     def __rmul__(self: _ArrayFloat64_co, other: _ArrayLike[floating[_64Bit]], /) -> NDArray[float64]: ...
     @overload
-    def __rmul__(self: NDArray[complexfloating[_64Bit]], other: _ArrayLikeComplex128_co, /) -> NDArray[complex128]: ...
+    def __rmul__(self: NDArray[complex128], other: _ArrayLikeComplex128_co, /) -> NDArray[complex128]: ...
     @overload
     def __rmul__(self: _ArrayComplex128_co, other: _ArrayLike[complexfloating[_64Bit]], /) -> NDArray[complex128]: ...
     @overload
@@ -3033,11 +3033,11 @@ class ndarray(_ArrayOrScalarCommon, Generic[_ShapeT_co, _DTypeT_co]):
     def __rmul__(self: NDArray[Any], other: _ArrayLikeObject_co, /) -> Any: ...
 
     @overload
-    def __truediv__(self: _ArrayInt_co | NDArray[floating[_64Bit]], other: _ArrayLikeFloat64_co, /) -> NDArray[float64]: ...
+    def __truediv__(self: _ArrayInt_co | NDArray[float64], other: _ArrayLikeFloat64_co, /) -> NDArray[float64]: ...
     @overload
     def __truediv__(self: _ArrayFloat64_co, other: _ArrayLikeInt_co | _ArrayLike[floating[_64Bit]], /) -> NDArray[float64]: ...
     @overload
-    def __truediv__(self: NDArray[complexfloating[_64Bit]], other: _ArrayLikeComplex128_co, /) -> NDArray[complex128]: ...
+    def __truediv__(self: NDArray[complex128], other: _ArrayLikeComplex128_co, /) -> NDArray[complex128]: ...
     @overload
     def __truediv__(self: _ArrayComplex128_co, other: _ArrayLike[complexfloating[_64Bit]], /) -> NDArray[complex128]: ...
     @overload
@@ -3064,11 +3064,11 @@ class ndarray(_ArrayOrScalarCommon, Generic[_ShapeT_co, _DTypeT_co]):
     def __truediv__(self: NDArray[Any], other: _ArrayLikeObject_co, /) -> Any: ...
 
     @overload
-    def __rtruediv__(self: _ArrayInt_co | NDArray[floating[_64Bit]], other: _ArrayLikeFloat64_co, /) -> NDArray[float64]: ...
+    def __rtruediv__(self: _ArrayInt_co | NDArray[float64], other: _ArrayLikeFloat64_co, /) -> NDArray[float64]: ...
     @overload
     def __rtruediv__(self: _ArrayFloat64_co, other: _ArrayLikeInt_co | _ArrayLike[floating[_64Bit]], /) -> NDArray[float64]: ...
     @overload
-    def __rtruediv__(self: NDArray[complexfloating[_64Bit]], other: _ArrayLikeComplex128_co, /) -> NDArray[complex128]: ...
+    def __rtruediv__(self: NDArray[complex128], other: _ArrayLikeComplex128_co, /) -> NDArray[complex128]: ...
     @overload
     def __rtruediv__(self: _ArrayComplex128_co, other: _ArrayLike[complexfloating[_64Bit]], /) -> NDArray[complex128]: ...
     @overload
@@ -3101,7 +3101,7 @@ class ndarray(_ArrayOrScalarCommon, Generic[_ShapeT_co, _DTypeT_co]):
     @overload
     def __floordiv__(self: NDArray[np.bool], other: _ArrayLike[_RealNumberT], /) -> NDArray[_RealNumberT]: ...  # type: ignore[overload-overlap]
     @overload
-    def __floordiv__(self: NDArray[floating[_64Bit]], other: _ArrayLikeFloat64_co, /) -> NDArray[float64]: ...
+    def __floordiv__(self: NDArray[float64], other: _ArrayLikeFloat64_co, /) -> NDArray[float64]: ...
     @overload
     def __floordiv__(self: _ArrayFloat64_co, other: _ArrayLike[floating[_64Bit]], /) -> NDArray[float64]: ...
     @overload
@@ -3130,7 +3130,7 @@ class ndarray(_ArrayOrScalarCommon, Generic[_ShapeT_co, _DTypeT_co]):
     @overload
     def __rfloordiv__(self: NDArray[np.bool], other: _ArrayLike[_RealNumberT], /) -> NDArray[_RealNumberT]: ...  # type: ignore[overload-overlap]
     @overload
-    def __rfloordiv__(self: NDArray[floating[_64Bit]], other: _ArrayLikeFloat64_co, /) -> NDArray[float64]: ...
+    def __rfloordiv__(self: NDArray[float64], other: _ArrayLikeFloat64_co, /) -> NDArray[float64]: ...
     @overload
     def __rfloordiv__(self: _ArrayFloat64_co, other: _ArrayLike[floating[_64Bit]], /) -> NDArray[float64]: ...
     @overload
@@ -3157,11 +3157,11 @@ class ndarray(_ArrayOrScalarCommon, Generic[_ShapeT_co, _DTypeT_co]):
     @overload
     def __pow__(self: NDArray[np.bool], other: _ArrayLike[_NumberT], /) -> NDArray[_NumberT]: ...  # type: ignore[overload-overlap]
     @overload
-    def __pow__(self: NDArray[floating[_64Bit]], other: _ArrayLikeFloat64_co, /) -> NDArray[float64]: ...
+    def __pow__(self: NDArray[float64], other: _ArrayLikeFloat64_co, /) -> NDArray[float64]: ...
     @overload
     def __pow__(self: _ArrayFloat64_co, other: _ArrayLike[floating[_64Bit]], /) -> NDArray[float64]: ...
     @overload
-    def __pow__(self: NDArray[complexfloating[_64Bit]], other: _ArrayLikeComplex128_co, /) -> NDArray[complex128]: ...
+    def __pow__(self: NDArray[complex128], other: _ArrayLikeComplex128_co, /) -> NDArray[complex128]: ...
     @overload
     def __pow__(self: _ArrayComplex128_co, other: _ArrayLike[complexfloating[_64Bit]], /) -> NDArray[complex128]: ...
     @overload
@@ -3188,11 +3188,11 @@ class ndarray(_ArrayOrScalarCommon, Generic[_ShapeT_co, _DTypeT_co]):
     @overload
     def __rpow__(self: NDArray[np.bool], other: _ArrayLike[_NumberT], /) -> NDArray[_NumberT]: ...  # type: ignore[overload-overlap]
     @overload
-    def __rpow__(self: NDArray[floating[_64Bit]], other: _ArrayLikeFloat64_co, /) -> NDArray[float64]: ...
+    def __rpow__(self: NDArray[float64], other: _ArrayLikeFloat64_co, /) -> NDArray[float64]: ...
     @overload
     def __rpow__(self: _ArrayFloat64_co, other: _ArrayLike[floating[_64Bit]], /) -> NDArray[float64]: ...
     @overload
-    def __rpow__(self: NDArray[complexfloating[_64Bit]], other: _ArrayLikeComplex128_co, /) -> NDArray[complex128]: ...
+    def __rpow__(self: NDArray[complex128], other: _ArrayLikeComplex128_co, /) -> NDArray[complex128]: ...
     @overload
     def __rpow__(self: _ArrayComplex128_co, other: _ArrayLike[complexfloating[_64Bit]], /) -> NDArray[complex128]: ...
     @overload
diff --git a/numpy/typing/tests/data/reveal/arithmetic.pyi b/numpy/typing/tests/data/reveal/arithmetic.pyi
index d8624186767d..2a33e4fc9148 100644
--- a/numpy/typing/tests/data/reveal/arithmetic.pyi
+++ b/numpy/typing/tests/data/reveal/arithmetic.pyi
@@ -48,7 +48,8 @@ AR_c: npt.NDArray[np.complex128]
 AR_m: npt.NDArray[np.timedelta64]
 AR_M: npt.NDArray[np.datetime64]
 AR_O: npt.NDArray[np.object_]
-AR_number: npt.NDArray[np.number[Any]]
+AR_floating: npt.NDArray[np.floating]
+AR_number: npt.NDArray[np.number]
 AR_Any: npt.NDArray[Any]
 
 AR_LIKE_b: list[bool]
@@ -652,3 +653,23 @@ assert_type(AR_f + u4, npt.NDArray[np.float64])
 # Any
 
 assert_type(AR_Any + 2, npt.NDArray[Any])
+
+# regression tests for https://github.com/numpy/numpy/issues/28805
+
+assert_type(AR_floating + f, npt.NDArray[np.floating])
+assert_type(AR_floating - f, npt.NDArray[np.floating])
+assert_type(AR_floating * f, npt.NDArray[np.floating])
+assert_type(AR_floating ** f, npt.NDArray[np.floating])
+assert_type(AR_floating / f, npt.NDArray[np.floating])
+assert_type(AR_floating // f, npt.NDArray[np.floating])
+assert_type(AR_floating % f, npt.NDArray[np.floating])
+assert_type(divmod(AR_floating, f), tuple[npt.NDArray[np.floating], npt.NDArray[np.floating]])
+
+assert_type(f + AR_floating, npt.NDArray[np.floating])
+assert_type(f - AR_floating, npt.NDArray[np.floating])
+assert_type(f * AR_floating, npt.NDArray[np.floating])
+assert_type(f ** AR_floating, npt.NDArray[np.floating])
+assert_type(f / AR_floating, npt.NDArray[np.floating])
+assert_type(f // AR_floating, npt.NDArray[np.floating])
+assert_type(f % AR_floating, npt.NDArray[np.floating])
+assert_type(divmod(f, AR_floating), tuple[npt.NDArray[np.floating], npt.NDArray[np.floating]])

From c091f26cebd5ae65338765786ac6ceca615ed0e5 Mon Sep 17 00:00:00 2001
From: Matthew Goldsberry
 <108106975+MatthewGoldsberry@users.noreply.github.com>
Date: Thu, 24 Apr 2025 09:47:55 -0400
Subject: [PATCH 086/202] BUG: Fix ` __array__(None)` to preserve dtype
 (#28806)

This PR fixes a bug in the __array__ method where calling __array__(None) would return an array with the default dtype float64, regardless of the original array's dtype.
---
 numpy/_core/src/multiarray/methods.c |  2 +-
 numpy/_core/tests/test_multiarray.py | 10 ++++++++++
 2 files changed, 11 insertions(+), 1 deletion(-)

diff --git a/numpy/_core/src/multiarray/methods.c b/numpy/_core/src/multiarray/methods.c
index dd3a1469ecd1..baa680f3a74a 100644
--- a/numpy/_core/src/multiarray/methods.c
+++ b/numpy/_core/src/multiarray/methods.c
@@ -928,7 +928,7 @@ array_getarray(PyArrayObject *self, PyObject *args, PyObject *kwds)
     PyObject *ret;
 
     if (!PyArg_ParseTupleAndKeywords(args, kwds, "|O&$O&:__array__", kwlist,
-                                     PyArray_DescrConverter, &newtype,
+                                     PyArray_DescrConverter2, &newtype,
                                      PyArray_CopyConverter, ©)) {
         Py_XDECREF(newtype);
         return NULL;
diff --git a/numpy/_core/tests/test_multiarray.py b/numpy/_core/tests/test_multiarray.py
index e2987f6676d6..6d97124d66c0 100644
--- a/numpy/_core/tests/test_multiarray.py
+++ b/numpy/_core/tests/test_multiarray.py
@@ -10459,3 +10459,13 @@ def __init__(self, interface):
     # Now, using np.asanyarray on this dummy should trigger a ValueError (not segfault)
     with pytest.raises(ValueError, match="dimensions must be within"):
         np.asanyarray(dummy)
+
+@pytest.mark.parametrize("dtype", [np.float32, np.float64, np.uint32, np.complex128])
+def test_array_dunder_array_preserves_dtype_on_none(dtype):
+    """
+    Regression test for: https://github.com/numpy/numpy/issues/27407
+    Ensure that __array__(None) returns an array of the same dtype.
+    """
+    a = np.array([1], dtype=dtype)
+    b = a.__array__(None)
+    assert_array_equal(a, b, strict=True)

From c13bf96b920974d5c45d91c4a63e749ab6b68116 Mon Sep 17 00:00:00 2001
From: lvllvl <24905907+lvllvl@users.noreply.github.com>
Date: Thu, 24 Apr 2025 12:00:19 -0400
Subject: [PATCH 087/202] CI: change clang_TSAN to use docker image (#28808)

---
 .github/workflows/compiler_sanitizers.yml | 73 +++++++----------------
 1 file changed, 23 insertions(+), 50 deletions(-)

diff --git a/.github/workflows/compiler_sanitizers.yml b/.github/workflows/compiler_sanitizers.yml
index 9452289239bc..84eab228b397 100644
--- a/.github/workflows/compiler_sanitizers.yml
+++ b/.github/workflows/compiler_sanitizers.yml
@@ -76,54 +76,27 @@ jobs:
   clang_TSAN:
     # To enable this workflow on a fork, comment out:
     if: github.repository == 'numpy/numpy'
-    runs-on: macos-latest
+    runs-on: ubuntu-latest
+    container:
+        image: ghcr.io/nascheme/numpy-tsan:3.14t-dev
+        options: --shm-size=2g # increase memory for large matrix ops
+      
     steps:
-    - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2
-      with:
-        submodules: recursive
-        fetch-tags: true
-        persist-credentials: false
-    - name: Set up pyenv
-      run: |
-        git clone https://github.com/pyenv/pyenv.git "$HOME/.pyenv"
-        PYENV_ROOT="$HOME/.pyenv"
-        PYENV_BIN="$PYENV_ROOT/bin"
-        PYENV_SHIMS="$PYENV_ROOT/shims"
-        echo "$PYENV_BIN" >> $GITHUB_PATH
-        echo "$PYENV_SHIMS" >> $GITHUB_PATH
-        echo "PYENV_ROOT=$PYENV_ROOT" >> $GITHUB_ENV
-    - name: Check pyenv is working
-      run:
-        pyenv --version
-    - name: Set up LLVM
-      run: |
-        brew install llvm@19
-        LLVM_PREFIX=$(brew --prefix llvm@19)
-        echo CC="$LLVM_PREFIX/bin/clang" >> $GITHUB_ENV
-        echo CXX="$LLVM_PREFIX/bin/clang++" >> $GITHUB_ENV
-        echo LDFLAGS="-L$LLVM_PREFIX/lib" >> $GITHUB_ENV
-        echo CPPFLAGS="-I$LLVM_PREFIX/include" >> $GITHUB_ENV
-    - name: Build Python with thread sanitizer support
-      run: |
-        # free-threaded Python is much more likely to trigger races
-        CONFIGURE_OPTS="--with-thread-sanitizer" pyenv install 3.13t
-        pyenv global 3.13t
-    - name: Install dependencies
-      run: |
-        # TODO: remove when a released cython supports free-threaded python
-        pip install -i https://pypi.anaconda.org/scientific-python-nightly-wheels/simple cython
-        pip install -r requirements/build_requirements.txt
-        pip install -r requirements/ci_requirements.txt
-        pip install -r requirements/test_requirements.txt
-        # xdist captures stdout/stderr, but we want the TSAN output
-        pip uninstall -y pytest-xdist
-    - name: Build
-      run:
-        python -m spin build -j2 -- -Db_sanitize=thread
-    - name: Test
-      run: |
-        # These tests are slow, so only run tests in files that do "import threading" to make them count
-        TSAN_OPTIONS="allocator_may_return_null=1:suppressions=$GITHUB_WORKSPACE/tools/ci/tsan_suppressions.txt" \
-        python -m spin test \
-        `find numpy -name "test*.py" | xargs grep -l "import threading" | tr '\n' ' '` \
-        -- -v -s --timeout=600 --durations=10
+      - uses: actions/checkout@v4
+      - name: Trust working directory and initialize submodules
+        run: |
+          git config --global --add safe.directory /__w/numpy/numpy
+          git submodule update --init --recursive
+      - name: Uninstall pytest-xdist (conflicts with TSAN)
+        run: pip uninstall -y pytest-xdist
+
+      - name: Build NumPy with ThreadSanitizer
+        run: python -m spin build -j2 -- -Db_sanitize=thread
+
+      - name: Run tests under prebuilt TSAN container
+        run: |
+          export TSAN_OPTIONS="halt_on_error=0:allocator_may_return_null=1:suppressions=$GITHUB_WORKSPACE/tools/ci/tsan_suppressions.txt"
+          echo "TSAN_OPTIONS=$TSAN_OPTIONS"
+          python -m spin test \
+          `find numpy -name "test*.py" | xargs grep -l "import threading" | tr '\n' ' '` \
+           -- -v -s --timeout=600 --durations=10

From cf80df2879346133450368372a2e6e41c540ab1d Mon Sep 17 00:00:00 2001
From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com>
Date: Thu, 24 Apr 2025 17:13:40 +0000
Subject: [PATCH 088/202] MAINT: Bump actions/setup-python from 5.5.0 to 5.6.0

Bumps [actions/setup-python](https://github.com/actions/setup-python) from 5.5.0 to 5.6.0.
- [Release notes](https://github.com/actions/setup-python/releases)
- [Commits](https://github.com/actions/setup-python/compare/8d9ed9ac5c53483de85588cdf95a591a75ab9f55...a26af69be951a213d495a4c3e4e4022e16d87065)

---
updated-dependencies:
- dependency-name: actions/setup-python
  dependency-version: 5.6.0
  dependency-type: direct:production
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] 
---
 .github/workflows/linux.yml         | 18 +++++++++---------
 .github/workflows/linux_blas.yml    | 12 ++++++------
 .github/workflows/linux_simd.yml    | 12 ++++++------
 .github/workflows/mypy.yml          |  2 +-
 .github/workflows/mypy_primer.yml   |  2 +-
 .github/workflows/wheels.yml        |  4 ++--
 .github/workflows/windows.yml       |  2 +-
 .github/workflows/windows_arm64.yml |  2 +-
 8 files changed, 27 insertions(+), 27 deletions(-)

diff --git a/.github/workflows/linux.yml b/.github/workflows/linux.yml
index ac269ff2a752..db660c8190c0 100644
--- a/.github/workflows/linux.yml
+++ b/.github/workflows/linux.yml
@@ -38,7 +38,7 @@ jobs:
         submodules: recursive
         fetch-depth: 0
         persist-credentials: false
-    - uses: actions/setup-python@8d9ed9ac5c53483de85588cdf95a591a75ab9f55 # v5.5.0
+    - uses: actions/setup-python@a26af69be951a213d495a4c3e4e4022e16d87065 # v5.6.0
       with:
         python-version: '3.11'
     - name: Install linter requirements
@@ -65,7 +65,7 @@ jobs:
         submodules: recursive
         fetch-tags: true
         persist-credentials: false
-    - uses: actions/setup-python@8d9ed9ac5c53483de85588cdf95a591a75ab9f55 # v5.5.0
+    - uses: actions/setup-python@a26af69be951a213d495a4c3e4e4022e16d87065 # v5.6.0
       with:
         python-version: ${{ matrix.version }}
     # TODO: remove cython nightly install when cython does a release
@@ -85,7 +85,7 @@ jobs:
         submodules: recursive
         fetch-tags: true
         persist-credentials: false
-    - uses: actions/setup-python@8d9ed9ac5c53483de85588cdf95a591a75ab9f55 # v5.5.0
+    - uses: actions/setup-python@a26af69be951a213d495a4c3e4e4022e16d87065 # v5.6.0
       with:
         python-version: 'pypy3.11-v7.3.19'
     - name: Setup using scipy-openblas
@@ -134,7 +134,7 @@ jobs:
         submodules: recursive
         fetch-tags: true
         persist-credentials: false
-    - uses: actions/setup-python@8d9ed9ac5c53483de85588cdf95a591a75ab9f55 # v5.5.0
+    - uses: actions/setup-python@a26af69be951a213d495a4c3e4e4022e16d87065 # v5.6.0
       with:
         python-version: '3.11'
     - name: Install build and test dependencies from PyPI
@@ -174,7 +174,7 @@ jobs:
         fetch-tags: true
         persist-credentials: false
 
-    - uses: actions/setup-python@8d9ed9ac5c53483de85588cdf95a591a75ab9f55 # v5.5.0
+    - uses: actions/setup-python@a26af69be951a213d495a4c3e4e4022e16d87065 # v5.6.0
       with:
         python-version: '3.11'
 
@@ -251,7 +251,7 @@ jobs:
         submodules: recursive
         fetch-tags: true
         persist-credentials: false
-    - uses: actions/setup-python@8d9ed9ac5c53483de85588cdf95a591a75ab9f55 # v5.5.0
+    - uses: actions/setup-python@a26af69be951a213d495a4c3e4e4022e16d87065 # v5.6.0
       with:
         python-version: '3.11'
     - name: Install build and benchmarking dependencies
@@ -290,7 +290,7 @@ jobs:
         submodules: recursive
         fetch-tags: true
         persist-credentials: false
-    - uses: actions/setup-python@8d9ed9ac5c53483de85588cdf95a591a75ab9f55 # v5.5.0
+    - uses: actions/setup-python@a26af69be951a213d495a4c3e4e4022e16d87065 # v5.6.0
       with:
         python-version: '3.11'
     - name: Install gfortran and setup OpenBLAS (sdist build)
@@ -334,7 +334,7 @@ jobs:
         path: 'array-api-tests'
         persist-credentials: false
     - name: Set up Python
-      uses: actions/setup-python@8d9ed9ac5c53483de85588cdf95a591a75ab9f55 # v5.5.0
+      uses: actions/setup-python@a26af69be951a213d495a4c3e4e4022e16d87065 # v5.6.0
       with:
         python-version: '3.11'
     - name: Install build and test dependencies from PyPI
@@ -363,7 +363,7 @@ jobs:
         submodules: recursive
         fetch-tags: true
         persist-credentials: false
-    - uses: actions/setup-python@8d9ed9ac5c53483de85588cdf95a591a75ab9f55 # v5.5.0
+    - uses: actions/setup-python@a26af69be951a213d495a4c3e4e4022e16d87065 # v5.6.0
       with:
         python-version: '3.11'
     - name: Install build and test dependencies from PyPI
diff --git a/.github/workflows/linux_blas.yml b/.github/workflows/linux_blas.yml
index ef75a22caedf..54d217cc12fb 100644
--- a/.github/workflows/linux_blas.yml
+++ b/.github/workflows/linux_blas.yml
@@ -70,7 +70,7 @@ jobs:
         submodules: recursive
         fetch-tags: true
         persist-credentials: false
-    - uses: actions/setup-python@8d9ed9ac5c53483de85588cdf95a591a75ab9f55 # v5.5.0
+    - uses: actions/setup-python@a26af69be951a213d495a4c3e4e4022e16d87065 # v5.6.0
       with:
         python-version: '3.11'
 
@@ -199,7 +199,7 @@ jobs:
         submodules: recursive
         fetch-tags: true
         persist-credentials: false
-    - uses: actions/setup-python@8d9ed9ac5c53483de85588cdf95a591a75ab9f55 # v5.5.0
+    - uses: actions/setup-python@a26af69be951a213d495a4c3e4e4022e16d87065 # v5.6.0
       with:
         python-version: '3.11'
 
@@ -228,7 +228,7 @@ jobs:
         submodules: recursive
         fetch-tags: true
         persist-credentials: false
-    - uses: actions/setup-python@8d9ed9ac5c53483de85588cdf95a591a75ab9f55 # v5.5.0
+    - uses: actions/setup-python@a26af69be951a213d495a4c3e4e4022e16d87065 # v5.6.0
       with:
         python-version: '3.11'
 
@@ -290,7 +290,7 @@ jobs:
         submodules: recursive
         fetch-tags: true
         persist-credentials: false
-    - uses: actions/setup-python@8d9ed9ac5c53483de85588cdf95a591a75ab9f55 # v5.5.0
+    - uses: actions/setup-python@a26af69be951a213d495a4c3e4e4022e16d87065 # v5.6.0
       with:
         python-version: '3.11'
 
@@ -354,7 +354,7 @@ jobs:
         submodules: recursive
         fetch-tags: true
         persist-credentials: false
-    - uses: actions/setup-python@8d9ed9ac5c53483de85588cdf95a591a75ab9f55 # v5.5.0
+    - uses: actions/setup-python@a26af69be951a213d495a4c3e4e4022e16d87065 # v5.6.0
       with:
         python-version: '3.11'
 
@@ -391,7 +391,7 @@ jobs:
         submodules: recursive
         fetch-tags: true
         persist-credentials: false
-    - uses: actions/setup-python@8d9ed9ac5c53483de85588cdf95a591a75ab9f55 # v5.5.0
+    - uses: actions/setup-python@a26af69be951a213d495a4c3e4e4022e16d87065 # v5.6.0
       with:
         python-version: '3.11'
 
diff --git a/.github/workflows/linux_simd.yml b/.github/workflows/linux_simd.yml
index fddf3bb297e5..4cd87ab37dd4 100644
--- a/.github/workflows/linux_simd.yml
+++ b/.github/workflows/linux_simd.yml
@@ -63,7 +63,7 @@ jobs:
         submodules: recursive
         fetch-tags: true
         persist-credentials: false
-    - uses: actions/setup-python@8d9ed9ac5c53483de85588cdf95a591a75ab9f55 # v5.5.0
+    - uses: actions/setup-python@a26af69be951a213d495a4c3e4e4022e16d87065 # v5.6.0
       with:
         python-version: '3.11'
     - uses: ./.github/meson_actions
@@ -81,7 +81,7 @@ jobs:
         submodules: recursive
         fetch-tags: true
         persist-credentials: false
-    - uses: actions/setup-python@8d9ed9ac5c53483de85588cdf95a591a75ab9f55 # v5.5.0
+    - uses: actions/setup-python@a26af69be951a213d495a4c3e4e4022e16d87065 # v5.6.0
       with:
         python-version: '3.11'
 
@@ -127,7 +127,7 @@ jobs:
       with:
         submodules: recursive
         fetch-tags: true
-    - uses: actions/setup-python@8d9ed9ac5c53483de85588cdf95a591a75ab9f55 # v5.5.0
+    - uses: actions/setup-python@a26af69be951a213d495a4c3e4e4022e16d87065 # v5.6.0
       with:
         python-version: '3.11'
     - name: Install dependencies
@@ -181,7 +181,7 @@ jobs:
         submodules: recursive
         fetch-tags: true
         persist-credentials: false
-    - uses: actions/setup-python@8d9ed9ac5c53483de85588cdf95a591a75ab9f55 # v5.5.0
+    - uses: actions/setup-python@a26af69be951a213d495a4c3e4e4022e16d87065 # v5.6.0
       with:
         python-version: "${{ matrix.BUILD_PROP[2] }}"
     - uses: ./.github/meson_actions
@@ -196,7 +196,7 @@ jobs:
         submodules: recursive
         fetch-tags: true
         persist-credentials: false
-    - uses: actions/setup-python@8d9ed9ac5c53483de85588cdf95a591a75ab9f55 # v5.5.0
+    - uses: actions/setup-python@a26af69be951a213d495a4c3e4e4022e16d87065 # v5.6.0
       with:
         python-version: '3.11'
 
@@ -247,7 +247,7 @@ jobs:
         submodules: recursive
         fetch-tags: true
         persist-credentials: false
-    - uses: actions/setup-python@8d9ed9ac5c53483de85588cdf95a591a75ab9f55 # v5.5.0
+    - uses: actions/setup-python@a26af69be951a213d495a4c3e4e4022e16d87065 # v5.6.0
       with:
         python-version: '3.11'
 
diff --git a/.github/workflows/mypy.yml b/.github/workflows/mypy.yml
index 90e4870dd253..36e89504def7 100644
--- a/.github/workflows/mypy.yml
+++ b/.github/workflows/mypy.yml
@@ -56,7 +56,7 @@ jobs:
         fetch-tags: true
         persist-credentials: false
 
-    - uses: actions/setup-python@8d9ed9ac5c53483de85588cdf95a591a75ab9f55 # v5.5.0
+    - uses: actions/setup-python@a26af69be951a213d495a4c3e4e4022e16d87065 # v5.6.0
       with:
         python-version: ${{ matrix.os_python[1] }}
     - name: Install dependencies
diff --git a/.github/workflows/mypy_primer.yml b/.github/workflows/mypy_primer.yml
index 8b5ba74f4f9f..bfbf34fa7817 100644
--- a/.github/workflows/mypy_primer.yml
+++ b/.github/workflows/mypy_primer.yml
@@ -28,7 +28,7 @@ jobs:
         with:
           path: numpy_to_test
           fetch-depth: 0
-      - uses: actions/setup-python@8d9ed9ac5c53483de85588cdf95a591a75ab9f55 # v5.5.0
+      - uses: actions/setup-python@a26af69be951a213d495a4c3e4e4022e16d87065 # v5.6.0
         with:
           python-version: "3.12"
       - name: Install dependencies
diff --git a/.github/workflows/wheels.yml b/.github/workflows/wheels.yml
index 9875afc5f6e2..159ffc4f4131 100644
--- a/.github/workflows/wheels.yml
+++ b/.github/workflows/wheels.yml
@@ -134,7 +134,7 @@ jobs:
         if: runner.os == 'windows'
 
       # Used to push the built wheels
-      - uses: actions/setup-python@8d9ed9ac5c53483de85588cdf95a591a75ab9f55 # v5.5.0
+      - uses: actions/setup-python@a26af69be951a213d495a4c3e4e4022e16d87065 # v5.6.0
         with:
           python-version: "3.x"
 
@@ -235,7 +235,7 @@ jobs:
           submodules: true
           persist-credentials: false
       # Used to push the built wheels
-      - uses: actions/setup-python@8d9ed9ac5c53483de85588cdf95a591a75ab9f55 # v5.5.0
+      - uses: actions/setup-python@a26af69be951a213d495a4c3e4e4022e16d87065 # v5.6.0
         with:
           # Build sdist on lowest supported Python
           python-version: "3.11"
diff --git a/.github/workflows/windows.yml b/.github/workflows/windows.yml
index 1f897e1153e3..4356a18f1fd0 100644
--- a/.github/workflows/windows.yml
+++ b/.github/workflows/windows.yml
@@ -109,7 +109,7 @@ jobs:
           persist-credentials: false
 
       - name: Setup Python (32-bit)
-        uses: actions/setup-python@8d9ed9ac5c53483de85588cdf95a591a75ab9f55 # v5.5.0
+        uses: actions/setup-python@a26af69be951a213d495a4c3e4e4022e16d87065 # v5.6.0
         with:
           python-version: '3.11'
           architecture: 'x86'
diff --git a/.github/workflows/windows_arm64.yml b/.github/workflows/windows_arm64.yml
index 0f5ec8db193f..0a691bff9b21 100644
--- a/.github/workflows/windows_arm64.yml
+++ b/.github/workflows/windows_arm64.yml
@@ -28,7 +28,7 @@ jobs:
         persist-credentials: false
 
     - name: Setup Python
-      uses: actions/setup-python@8d9ed9ac5c53483de85588cdf95a591a75ab9f55 # v5.5.0
+      uses: actions/setup-python@a26af69be951a213d495a4c3e4e4022e16d87065 # v5.6.0
       with:
         python-version: ${{env.python_version}}
         architecture: x64

From e902685f9b26fccf3a8fe8b1d5b6c2d58ea6e74a Mon Sep 17 00:00:00 2001
From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com>
Date: Thu, 24 Apr 2025 17:13:42 +0000
Subject: [PATCH 089/202] MAINT: Bump astral-sh/setup-uv from 5.4.2 to 6.0.0

Bumps [astral-sh/setup-uv](https://github.com/astral-sh/setup-uv) from 5.4.2 to 6.0.0.
- [Release notes](https://github.com/astral-sh/setup-uv/releases)
- [Commits](https://github.com/astral-sh/setup-uv/compare/d4b2f3b6ecc6e67c4457f6d3e41ec42d3d0fcb86...c7f87aa956e4c323abf06d5dec078e358f6b4d04)

---
updated-dependencies:
- dependency-name: astral-sh/setup-uv
  dependency-version: 6.0.0
  dependency-type: direct:production
  update-type: version-update:semver-major
...

Signed-off-by: dependabot[bot] 
---
 .github/workflows/macos.yml   | 2 +-
 .github/workflows/windows.yml | 2 +-
 2 files changed, 2 insertions(+), 2 deletions(-)

diff --git a/.github/workflows/macos.yml b/.github/workflows/macos.yml
index c07735b55501..e0b980e00e13 100644
--- a/.github/workflows/macos.yml
+++ b/.github/workflows/macos.yml
@@ -124,7 +124,7 @@ jobs:
         fetch-tags: true
         persist-credentials: false
 
-    - uses: astral-sh/setup-uv@d4b2f3b6ecc6e67c4457f6d3e41ec42d3d0fcb86
+    - uses: astral-sh/setup-uv@c7f87aa956e4c323abf06d5dec078e358f6b4d04
       with:
         python-version: ${{ matrix.version }}
         enable-cache: false
diff --git a/.github/workflows/windows.yml b/.github/workflows/windows.yml
index 1f897e1153e3..d1bb1154909f 100644
--- a/.github/workflows/windows.yml
+++ b/.github/workflows/windows.yml
@@ -35,7 +35,7 @@ jobs:
         persist-credentials: false
 
     - name: Setup Python
-      uses: astral-sh/setup-uv@d4b2f3b6ecc6e67c4457f6d3e41ec42d3d0fcb86
+      uses: astral-sh/setup-uv@c7f87aa956e4c323abf06d5dec078e358f6b4d04
       with:
         python-version: ${{ matrix.compiler-pyversion[1] }}
         enable-cache: false

From bb6e11f7706ac65abfc94413349a52fd7b1f7d88 Mon Sep 17 00:00:00 2001
From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com>
Date: Thu, 24 Apr 2025 17:13:46 +0000
Subject: [PATCH 090/202] MAINT: Bump actions/download-artifact from 4.2.1 to
 4.3.0

Bumps [actions/download-artifact](https://github.com/actions/download-artifact) from 4.2.1 to 4.3.0.
- [Release notes](https://github.com/actions/download-artifact/releases)
- [Commits](https://github.com/actions/download-artifact/compare/95815c38cf2ff2164869cbab79da8d1f422bc89e...d3f86a106a0bac45b974a628896c90dbdf5c8093)

---
updated-dependencies:
- dependency-name: actions/download-artifact
  dependency-version: 4.3.0
  dependency-type: direct:production
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] 
---
 .github/workflows/emscripten.yml | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/.github/workflows/emscripten.yml b/.github/workflows/emscripten.yml
index 8b2935202a5a..a1b6e923b131 100644
--- a/.github/workflows/emscripten.yml
+++ b/.github/workflows/emscripten.yml
@@ -73,7 +73,7 @@ jobs:
       (github.event_name == 'schedule')
     steps:
       - name: Download wheel artifact(s)
-        uses: actions/download-artifact@95815c38cf2ff2164869cbab79da8d1f422bc89e  # v4.2.1
+        uses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093  # v4.3.0
         with:
           path: wheelhouse/
           merge-multiple: true

From 170da7af69fbf52cd8dc847ca471d6814b196109 Mon Sep 17 00:00:00 2001
From: Joren Hammudoglu 
Date: Thu, 24 Apr 2025 19:21:01 +0200
Subject: [PATCH 091/202] CI: activate ``uv`` environments

---
 .github/workflows/macos.yml   | 1 +
 .github/workflows/windows.yml | 1 +
 2 files changed, 2 insertions(+)

diff --git a/.github/workflows/macos.yml b/.github/workflows/macos.yml
index e0b980e00e13..7156e8f486f2 100644
--- a/.github/workflows/macos.yml
+++ b/.github/workflows/macos.yml
@@ -126,6 +126,7 @@ jobs:
 
     - uses: astral-sh/setup-uv@c7f87aa956e4c323abf06d5dec078e358f6b4d04
       with:
+        activate-environment: true
         python-version: ${{ matrix.version }}
         enable-cache: false
 
diff --git a/.github/workflows/windows.yml b/.github/workflows/windows.yml
index d1bb1154909f..6df3a215c933 100644
--- a/.github/workflows/windows.yml
+++ b/.github/workflows/windows.yml
@@ -37,6 +37,7 @@ jobs:
     - name: Setup Python
       uses: astral-sh/setup-uv@c7f87aa956e4c323abf06d5dec078e358f6b4d04
       with:
+        activate-environment: true
         python-version: ${{ matrix.compiler-pyversion[1] }}
         enable-cache: false
 

From ad0fb40638643d133a0df3c5cafbb49af301623f Mon Sep 17 00:00:00 2001
From: jorenham 
Date: Thu, 24 Apr 2025 19:47:22 +0200
Subject: [PATCH 092/202] TYP: ``None`` at the end of a union

---
 numpy/__init__.pyi                            | 185 ++++++-------
 numpy/_core/_asarray.pyi                      |   4 +-
 numpy/_core/_ufunc_config.pyi                 |  10 +-
 numpy/_core/arrayprint.pyi                    |  62 ++---
 numpy/_core/defchararray.pyi                  | 196 +++++++-------
 numpy/_core/einsumfunc.pyi                    |  24 +-
 numpy/_core/multiarray.pyi                    | 254 +++++++++---------
 numpy/_core/numeric.pyi                       |  72 ++---
 numpy/_pytesttester.pyi                       |   4 +-
 numpy/_typing/_ufunc.pyi                      |  88 +++---
 numpy/ctypeslib/_ctypeslib.pyi                |  22 +-
 numpy/exceptions.pyi                          |   6 +-
 numpy/fft/_pocketfft.pyi                      |  72 ++---
 numpy/lib/_array_utils_impl.pyi               |   6 +-
 numpy/lib/_arraypad_impl.pyi                  |   4 +-
 numpy/lib/_function_base_impl.pyi             |  90 +++----
 numpy/lib/_histograms_impl.pyi                |  12 +-
 numpy/lib/_polynomial_impl.pyi                |  32 +--
 numpy/lib/_shape_base_impl.pyi                |   8 +-
 numpy/lib/_stride_tricks_impl.pyi             |  16 +-
 numpy/lib/_twodim_base_impl.pyi               | 136 +++++-----
 numpy/linalg/_linalg.pyi                      |  32 +--
 numpy/matrixlib/defmatrix.pyi                 |   4 +-
 numpy/polynomial/_polybase.pyi                |  56 ++--
 numpy/polynomial/_polytypes.pyi               |  42 +--
 numpy/polynomial/chebyshev.pyi                |   6 +-
 numpy/polynomial/polyutils.pyi                |  40 +--
 numpy/random/_generator.pyi                   | 100 +++----
 numpy/random/_mt19937.pyi                     |   2 +-
 numpy/random/_pcg64.pyi                       |   4 +-
 numpy/random/_philox.pyi                      |   6 +-
 numpy/random/_sfc64.pyi                       |   2 +-
 numpy/random/mtrand.pyi                       | 162 +++++------
 numpy/typing/tests/data/pass/array_like.py    |   2 +-
 .../typing/tests/data/reveal/arrayterator.pyi |   2 +-
 numpy/typing/tests/data/reveal/dtype.pyi      |   4 +-
 .../tests/data/reveal/lib_function_base.pyi   |   6 +-
 numpy/typing/tests/data/reveal/npyio.pyi      |   4 +-
 numpy/typing/tests/data/reveal/random.pyi     |   2 +-
 numpy/typing/tests/data/reveal/testing.pyi    |   2 +-
 .../typing/tests/data/reveal/ufunc_config.pyi |   6 +-
 numpy/typing/tests/test_runtime.py            |   2 +-
 numpy/typing/tests/test_typing.py             |   2 +-
 43 files changed, 892 insertions(+), 899 deletions(-)

diff --git a/numpy/__init__.pyi b/numpy/__init__.pyi
index 0870d1da5248..75e67ddf12dd 100644
--- a/numpy/__init__.pyi
+++ b/numpy/__init__.pyi
@@ -1184,14 +1184,14 @@ class _DTypeMeta(type):
 
 @final
 class dtype(Generic[_ScalarT_co], metaclass=_DTypeMeta):
-    names: None | tuple[builtins.str, ...]
+    names: tuple[builtins.str, ...] | None
     def __hash__(self) -> int: ...
 
     # `None` results in the default dtype
     @overload
     def __new__(
         cls,
-        dtype: None | type[float64],
+        dtype: type[float64] | None,
         align: builtins.bool = ...,
         copy: builtins.bool = ...,
         metadata: dict[builtins.str, Any] = ...
@@ -1241,7 +1241,7 @@ class dtype(Generic[_ScalarT_co], metaclass=_DTypeMeta):
     @overload
     def __new__(
         cls,
-        dtype: None | type[float | float64 | int_ | np.bool],
+        dtype: type[float | float64 | int_ | np.bool] | None,
         align: builtins.bool = ...,
         copy: builtins.bool = ...,
         metadata: dict[str, Any] = ...,
@@ -1573,7 +1573,7 @@ class dtype(Generic[_ScalarT_co], metaclass=_DTypeMeta):
     @property
     def descr(self) -> list[tuple[LiteralString, LiteralString] | tuple[LiteralString, LiteralString, _Shape]]: ...
     @property
-    def fields(self,) -> None | MappingProxyType[LiteralString, tuple[dtype[Any], int] | tuple[dtype[Any], int, Any]]: ...
+    def fields(self,) -> MappingProxyType[LiteralString, tuple[dtype[Any], int] | tuple[dtype[Any], int, Any]] | None: ...
     @property
     def flags(self) -> int: ...
     @property
@@ -1589,7 +1589,7 @@ class dtype(Generic[_ScalarT_co], metaclass=_DTypeMeta):
     @property
     def kind(self) -> _DTypeKind: ...
     @property
-    def metadata(self) -> None | MappingProxyType[builtins.str, Any]: ...
+    def metadata(self) -> MappingProxyType[builtins.str, Any] | None: ...
     @property
     def name(self) -> LiteralString: ...
     @property
@@ -1599,7 +1599,7 @@ class dtype(Generic[_ScalarT_co], metaclass=_DTypeMeta):
     @property
     def ndim(self) -> int: ...
     @property
-    def subdtype(self) -> None | tuple[dtype[Any], _Shape]: ...
+    def subdtype(self) -> tuple[dtype[Any], _Shape] | None: ...
     def newbyteorder(self, new_order: _ByteOrder = ..., /) -> Self: ...
     @property
     def str(self) -> LiteralString: ...
@@ -1672,7 +1672,7 @@ class _ArrayOrScalarCommon:
     def __int__(self, /) -> int: ...
     def __float__(self, /) -> float: ...
     def __copy__(self) -> Self: ...
-    def __deepcopy__(self, memo: None | dict[int, Any], /) -> Self: ...
+    def __deepcopy__(self, memo: dict[int, Any] | None, /) -> Self: ...
 
     # TODO: How to deal with the non-commutative nature of `==` and `!=`?
     # xref numpy/numpy#17368
@@ -1686,7 +1686,7 @@ class _ArrayOrScalarCommon:
     def tofile(self, fid: StrOrBytesPath | _SupportsFileMethods, sep: str = ..., format: str = ...) -> None: ...
     # generics and 0d arrays return builtin scalars
     def tolist(self) -> Any: ...
-    def to_device(self, device: L["cpu"], /, *, stream: None | int | Any = ...) -> Self: ...
+    def to_device(self, device: L["cpu"], /, *, stream: int | Any | None = ...) -> Self: ...
 
     @property
     def __array_interface__(self) -> dict[str, Any]: ...
@@ -1708,11 +1708,11 @@ class _ArrayOrScalarCommon:
 
     def argsort(
         self,
-        axis: None | SupportsIndex = ...,
-        kind: None | _SortKind = ...,
-        order: None | str | Sequence[str] = ...,
+        axis: SupportsIndex | None = ...,
+        kind: _SortKind | None = ...,
+        order: str | Sequence[str] | None = ...,
         *,
-        stable: None | bool = ...,
+        stable: bool | None = ...,
     ) -> NDArray[Any]: ...
 
     @overload  # axis=None (default), out=None (default), keepdims=False (default)
@@ -2032,7 +2032,7 @@ class _ArrayOrScalarCommon:
 class ndarray(_ArrayOrScalarCommon, Generic[_ShapeT_co, _DTypeT_co]):
     __hash__: ClassVar[None]  # type: ignore[assignment]  # pyright: ignore[reportIncompatibleMethodOverride]
     @property
-    def base(self) -> None | NDArray[Any]: ...
+    def base(self) -> NDArray[Any] | None: ...
     @property
     def ndim(self) -> int: ...
     @property
@@ -2050,9 +2050,9 @@ class ndarray(_ArrayOrScalarCommon, Generic[_ShapeT_co, _DTypeT_co]):
         cls,
         shape: _ShapeLike,
         dtype: DTypeLike = ...,
-        buffer: None | _SupportsBuffer = ...,
+        buffer: _SupportsBuffer | None = ...,
         offset: SupportsIndex = ...,
-        strides: None | _ShapeLike = ...,
+        strides: _ShapeLike | None = ...,
         order: _OrderKACF = ...,
     ) -> Self: ...
 
@@ -2063,11 +2063,11 @@ class ndarray(_ArrayOrScalarCommon, Generic[_ShapeT_co, _DTypeT_co]):
 
     @overload
     def __array__(
-        self, dtype: None = ..., /, *, copy: None | bool = ...
+        self, dtype: None = ..., /, *, copy: bool | None = ...
     ) -> ndarray[_ShapeT_co, _DTypeT_co]: ...
     @overload
     def __array__(
-        self, dtype: _DTypeT, /, *, copy: None | bool = ...
+        self, dtype: _DTypeT, /, *, copy: bool | None = ...
     ) -> ndarray[_ShapeT_co, _DTypeT]: ...
 
     def __array_ufunc__(
@@ -2089,12 +2089,12 @@ class ndarray(_ArrayOrScalarCommon, Generic[_ShapeT_co, _DTypeT_co]):
     # NOTE: In practice any object is accepted by `obj`, but as `__array_finalize__`
     # is a pseudo-abstract method the type has been narrowed down in order to
     # grant subclasses a bit more flexibility
-    def __array_finalize__(self, obj: None | NDArray[Any], /) -> None: ...
+    def __array_finalize__(self, obj: NDArray[Any] | None, /) -> None: ...
 
     def __array_wrap__(
         self,
         array: ndarray[_ShapeT, _DTypeT],
-        context: None | tuple[ufunc, tuple[Any, ...], int] = ...,
+        context: tuple[ufunc, tuple[Any, ...], int] | None = ...,
         return_scalar: builtins.bool = ...,
         /,
     ) -> ndarray[_ShapeT, _DTypeT]: ...
@@ -2202,7 +2202,7 @@ class ndarray(_ArrayOrScalarCommon, Generic[_ShapeT_co, _DTypeT_co]):
 
     def squeeze(
         self,
-        axis: None | SupportsIndex | tuple[SupportsIndex, ...] = ...,
+        axis: SupportsIndex | tuple[SupportsIndex, ...] | None = ...,
     ) -> ndarray[_Shape, _DTypeT_co]: ...
 
     def swapaxes(
@@ -2212,7 +2212,7 @@ class ndarray(_ArrayOrScalarCommon, Generic[_ShapeT_co, _DTypeT_co]):
     ) -> ndarray[_Shape, _DTypeT_co]: ...
 
     @overload
-    def transpose(self, axes: None | _ShapeLike, /) -> Self: ...
+    def transpose(self, axes: _ShapeLike | None, /) -> Self: ...
     @overload
     def transpose(self, *axes: SupportsIndex) -> Self: ...
 
@@ -2228,7 +2228,7 @@ class ndarray(_ArrayOrScalarCommon, Generic[_ShapeT_co, _DTypeT_co]):
     @overload
     def all(
         self,
-        axis: None | int | tuple[int, ...] = None,
+        axis: int | tuple[int, ...] | None = None,
         out: None = None,
         keepdims: SupportsIndex = False,
         *,
@@ -2237,7 +2237,7 @@ class ndarray(_ArrayOrScalarCommon, Generic[_ShapeT_co, _DTypeT_co]):
     @overload
     def all(
         self,
-        axis: None | int | tuple[int, ...],
+        axis: int | tuple[int, ...] | None,
         out: _ArrayT,
         keepdims: SupportsIndex = False,
         *,
@@ -2246,7 +2246,7 @@ class ndarray(_ArrayOrScalarCommon, Generic[_ShapeT_co, _DTypeT_co]):
     @overload
     def all(
         self,
-        axis: None | int | tuple[int, ...] = None,
+        axis: int | tuple[int, ...] | None = None,
         *,
         out: _ArrayT,
         keepdims: SupportsIndex = False,
@@ -2265,7 +2265,7 @@ class ndarray(_ArrayOrScalarCommon, Generic[_ShapeT_co, _DTypeT_co]):
     @overload
     def any(
         self,
-        axis: None | int | tuple[int, ...] = None,
+        axis: int | tuple[int, ...] | None = None,
         out: None = None,
         keepdims: SupportsIndex = False,
         *,
@@ -2274,7 +2274,7 @@ class ndarray(_ArrayOrScalarCommon, Generic[_ShapeT_co, _DTypeT_co]):
     @overload
     def any(
         self,
-        axis: None | int | tuple[int, ...],
+        axis: int | tuple[int, ...] | None,
         out: _ArrayT,
         keepdims: SupportsIndex = False,
         *,
@@ -2283,7 +2283,7 @@ class ndarray(_ArrayOrScalarCommon, Generic[_ShapeT_co, _DTypeT_co]):
     @overload
     def any(
         self,
-        axis: None | int | tuple[int, ...] = None,
+        axis: int | tuple[int, ...] | None = None,
         *,
         out: _ArrayT,
         keepdims: SupportsIndex = False,
@@ -2359,23 +2359,23 @@ class ndarray(_ArrayOrScalarCommon, Generic[_ShapeT_co, _DTypeT_co]):
         self,  # >= 1D array
         v: _ScalarLike_co,  # 0D array-like
         side: _SortSide = ...,
-        sorter: None | _ArrayLikeInt_co = ...,
+        sorter: _ArrayLikeInt_co | None = ...,
     ) -> intp: ...
     @overload
     def searchsorted(
         self,  # >= 1D array
         v: ArrayLike,
         side: _SortSide = ...,
-        sorter: None | _ArrayLikeInt_co = ...,
+        sorter: _ArrayLikeInt_co | None = ...,
     ) -> NDArray[intp]: ...
 
     def sort(
         self,
         axis: SupportsIndex = ...,
-        kind: None | _SortKind = ...,
-        order: None | str | Sequence[str] = ...,
+        kind: _SortKind | None = ...,
+        order: str | Sequence[str] | None = ...,
         *,
-        stable: None | bool = ...,
+        stable: bool | None = ...,
     ) -> None: ...
 
     @overload
@@ -2401,7 +2401,7 @@ class ndarray(_ArrayOrScalarCommon, Generic[_ShapeT_co, _DTypeT_co]):
     def take(  # type: ignore[misc]
         self: NDArray[_ScalarT],
         indices: _IntLike_co,
-        axis: None | SupportsIndex = ...,
+        axis: SupportsIndex | None = ...,
         out: None = ...,
         mode: _ModeKind = ...,
     ) -> _ScalarT: ...
@@ -2409,7 +2409,7 @@ class ndarray(_ArrayOrScalarCommon, Generic[_ShapeT_co, _DTypeT_co]):
     def take(  # type: ignore[misc]
         self,
         indices: _ArrayLikeInt_co,
-        axis: None | SupportsIndex = ...,
+        axis: SupportsIndex | None = ...,
         out: None = ...,
         mode: _ModeKind = ...,
     ) -> ndarray[_Shape, _DTypeT_co]: ...
@@ -2417,7 +2417,7 @@ class ndarray(_ArrayOrScalarCommon, Generic[_ShapeT_co, _DTypeT_co]):
     def take(
         self,
         indices: _ArrayLikeInt_co,
-        axis: None | SupportsIndex = ...,
+        axis: SupportsIndex | None = ...,
         out: _ArrayT = ...,
         mode: _ModeKind = ...,
     ) -> _ArrayT: ...
@@ -2425,7 +2425,7 @@ class ndarray(_ArrayOrScalarCommon, Generic[_ShapeT_co, _DTypeT_co]):
     def repeat(
         self,
         repeats: _ArrayLikeInt_co,
-        axis: None | SupportsIndex = ...,
+        axis: SupportsIndex | None = ...,
     ) -> ndarray[_Shape, _DTypeT_co]: ...
 
     def flatten(self, /, order: _OrderKACF = "C") -> ndarray[tuple[int], _DTypeT_co]: ...
@@ -3665,7 +3665,7 @@ class generic(_ArrayOrScalarCommon, Generic[_ItemT_co]):
     def take(  # type: ignore[misc]
         self,
         indices: _IntLike_co,
-        axis: None | SupportsIndex = ...,
+        axis: SupportsIndex | None = ...,
         out: None = ...,
         mode: _ModeKind = ...,
     ) -> Self: ...
@@ -3673,7 +3673,7 @@ class generic(_ArrayOrScalarCommon, Generic[_ItemT_co]):
     def take(  # type: ignore[misc]
         self,
         indices: _ArrayLikeInt_co,
-        axis: None | SupportsIndex = ...,
+        axis: SupportsIndex | None = ...,
         out: None = ...,
         mode: _ModeKind = ...,
     ) -> NDArray[Self]: ...
@@ -3681,12 +3681,12 @@ class generic(_ArrayOrScalarCommon, Generic[_ItemT_co]):
     def take(
         self,
         indices: _ArrayLikeInt_co,
-        axis: None | SupportsIndex = ...,
+        axis: SupportsIndex | None = ...,
         out: _ArrayT = ...,
         mode: _ModeKind = ...,
     ) -> _ArrayT: ...
 
-    def repeat(self, repeats: _ArrayLikeInt_co, axis: None | SupportsIndex = ...) -> NDArray[Self]: ...
+    def repeat(self, repeats: _ArrayLikeInt_co, axis: SupportsIndex | None = ...) -> NDArray[Self]: ...
     def flatten(self, /, order: _OrderKACF = "C") -> ndarray[tuple[int], dtype[Self]]: ...
     def ravel(self, /, order: _OrderKACF = "C") -> ndarray[tuple[int], dtype[Self]]: ...
 
@@ -3773,8 +3773,8 @@ class generic(_ArrayOrScalarCommon, Generic[_ItemT_co]):
         copy: builtins.bool | None = None,
     ) -> ndarray[tuple[L[1], L[1], L[1], L[1], L[1], *tuple[L[1], ...]], dtype[Self]]: ...
 
-    def squeeze(self, axis: None | L[0] | tuple[()] = ...) -> Self: ...
-    def transpose(self, axes: None | tuple[()] = ..., /) -> Self: ...
+    def squeeze(self, axis: L[0] | tuple[()] | None = ...) -> Self: ...
+    def transpose(self, axes: tuple[()] | None = ..., /) -> Self: ...
 
     @overload
     def all(
@@ -4490,7 +4490,7 @@ class timedelta64(_IntegralMixin, generic[_TD64ItemT_co], Generic[_TD64ItemT_co]
     __rmul__ = __mul__
 
     @overload
-    def __mod__(self, x: timedelta64[None | L[0]], /) -> timedelta64[None]: ...
+    def __mod__(self, x: timedelta64[L[0] | None], /) -> timedelta64[None]: ...
     @overload
     def __mod__(self: timedelta64[None], x: timedelta64, /) -> timedelta64[None]: ...
     @overload
@@ -4508,7 +4508,7 @@ class timedelta64(_IntegralMixin, generic[_TD64ItemT_co], Generic[_TD64ItemT_co]
     @overload
     def __rmod__(self, x: timedelta64[None], /) -> timedelta64[None]: ...
     @overload
-    def __rmod__(self: timedelta64[None | L[0]], x: timedelta64, /) -> timedelta64[None]: ...
+    def __rmod__(self: timedelta64[L[0] | None], x: timedelta64, /) -> timedelta64[None]: ...
     @overload
     def __rmod__(self: timedelta64[int], x: timedelta64[int | dt.timedelta], /) -> timedelta64[int | None]: ...
     @overload
@@ -4522,7 +4522,7 @@ class timedelta64(_IntegralMixin, generic[_TD64ItemT_co], Generic[_TD64ItemT_co]
 
     # keep in sync with __mod__
     @overload
-    def __divmod__(self, x: timedelta64[None | L[0]], /) -> tuple[int64, timedelta64[None]]: ...
+    def __divmod__(self, x: timedelta64[L[0] | None], /) -> tuple[int64, timedelta64[None]]: ...
     @overload
     def __divmod__(self: timedelta64[None], x: timedelta64, /) -> tuple[int64, timedelta64[None]]: ...
     @overload
@@ -4540,7 +4540,7 @@ class timedelta64(_IntegralMixin, generic[_TD64ItemT_co], Generic[_TD64ItemT_co]
     @overload
     def __rdivmod__(self, x: timedelta64[None], /) -> tuple[int64, timedelta64[None]]: ...
     @overload
-    def __rdivmod__(self: timedelta64[None | L[0]], x: timedelta64, /) -> tuple[int64, timedelta64[None]]: ...
+    def __rdivmod__(self: timedelta64[L[0] | None], x: timedelta64, /) -> tuple[int64, timedelta64[None]]: ...
     @overload
     def __rdivmod__(self: timedelta64[int], x: timedelta64[int | dt.timedelta], /) -> tuple[int64, timedelta64[int | None]]: ...
     @overload
@@ -4793,7 +4793,7 @@ class ufunc:
     def identity(self) -> Any: ...
     # This is None for ufuncs and a string for gufuncs.
     @property
-    def signature(self) -> None | LiteralString: ...
+    def signature(self) -> LiteralString | None: ...
 
     def __call__(self, *args: Any, **kwargs: Any) -> Any: ...
     # The next four methods will always exist, but they will just
@@ -4935,18 +4935,18 @@ class errstate:
         self,
         *,
         call: _ErrCall = ...,
-        all: None | _ErrKind = ...,
-        divide: None | _ErrKind = ...,
-        over: None | _ErrKind = ...,
-        under: None | _ErrKind = ...,
-        invalid: None | _ErrKind = ...,
+        all: _ErrKind | None = ...,
+        divide: _ErrKind | None = ...,
+        over: _ErrKind | None = ...,
+        under: _ErrKind | None = ...,
+        invalid: _ErrKind | None = ...,
     ) -> None: ...
     def __enter__(self) -> None: ...
     def __exit__(
         self,
-        exc_type: None | type[BaseException],
-        exc_value: None | BaseException,
-        traceback: None | TracebackType,
+        exc_type: type[BaseException] | None,
+        exc_value: BaseException | None,
+        traceback: TracebackType | None,
         /,
     ) -> None: ...
     def __call__(self, func: _CallableT) -> _CallableT: ...
@@ -5045,21 +5045,21 @@ class nditer:
     def __new__(
         cls,
         op: ArrayLike | Sequence[ArrayLike | None],
-        flags: None | Sequence[_NDIterFlagsKind] = ...,
-        op_flags: None | Sequence[Sequence[_NDIterFlagsOp]] = ...,
+        flags: Sequence[_NDIterFlagsKind] | None = ...,
+        op_flags: Sequence[Sequence[_NDIterFlagsOp]] | None = ...,
         op_dtypes: DTypeLike | Sequence[DTypeLike] = ...,
         order: _OrderKACF = ...,
         casting: _CastingKind = ...,
-        op_axes: None | Sequence[Sequence[SupportsIndex]] = ...,
-        itershape: None | _ShapeLike = ...,
+        op_axes: Sequence[Sequence[SupportsIndex]] | None = ...,
+        itershape: _ShapeLike | None = ...,
         buffersize: SupportsIndex = ...,
     ) -> nditer: ...
     def __enter__(self) -> nditer: ...
     def __exit__(
         self,
-        exc_type: None | type[BaseException],
-        exc_value: None | BaseException,
-        traceback: None | TracebackType,
+        exc_type: type[BaseException] | None,
+        exc_value: BaseException | None,
+        traceback: TracebackType | None,
     ) -> None: ...
     def __iter__(self) -> nditer: ...
     def __next__(self) -> tuple[NDArray[Any], ...]: ...
@@ -5125,7 +5125,7 @@ class memmap(ndarray[_ShapeT_co, _DTypeT_co]):
         dtype: type[uint8] = ...,
         mode: _MemMapModeKind = ...,
         offset: int = ...,
-        shape: None | int | tuple[int, ...] = ...,
+        shape: int | tuple[int, ...] | None = ...,
         order: _OrderKACF = ...,
     ) -> memmap[Any, dtype[uint8]]: ...
     @overload
@@ -5135,7 +5135,7 @@ class memmap(ndarray[_ShapeT_co, _DTypeT_co]):
         dtype: _DTypeLike[_ScalarT],
         mode: _MemMapModeKind = ...,
         offset: int = ...,
-        shape: None | int | tuple[int, ...] = ...,
+        shape: int | tuple[int, ...] | None = ...,
         order: _OrderKACF = ...,
     ) -> memmap[Any, dtype[_ScalarT]]: ...
     @overload
@@ -5145,14 +5145,14 @@ class memmap(ndarray[_ShapeT_co, _DTypeT_co]):
         dtype: DTypeLike,
         mode: _MemMapModeKind = ...,
         offset: int = ...,
-        shape: None | int | tuple[int, ...] = ...,
+        shape: int | tuple[int, ...] | None = ...,
         order: _OrderKACF = ...,
     ) -> memmap[Any, dtype[Any]]: ...
     def __array_finalize__(self, obj: object) -> None: ...
     def __array_wrap__(
         self,
         array: memmap[_ShapeT_co, _DTypeT_co],
-        context: None | tuple[ufunc, tuple[Any, ...], int] = ...,
+        context: tuple[ufunc, tuple[Any, ...], int] | None = ...,
         return_scalar: builtins.bool = ...,
     ) -> Any: ...
     def flush(self) -> None: ...
@@ -5162,18 +5162,18 @@ class memmap(ndarray[_ShapeT_co, _DTypeT_co]):
 class vectorize:
     pyfunc: Callable[..., Any]
     cache: builtins.bool
-    signature: None | LiteralString
-    otypes: None | LiteralString
+    signature: LiteralString | None
+    otypes: LiteralString | None
     excluded: set[int | str]
-    __doc__: None | str
+    __doc__: str | None
     def __init__(
         self,
         pyfunc: Callable[..., Any],
-        otypes: None | str | Iterable[DTypeLike] = ...,
-        doc: None | str = ...,
-        excluded: None | Iterable[int | str] = ...,
+        otypes: str | Iterable[DTypeLike] | None = ...,
+        doc: str | None = ...,
+        excluded: Iterable[int | str] | None = ...,
         cache: builtins.bool = ...,
-        signature: None | str = ...,
+        signature: str | None = ...,
     ) -> None: ...
     def __call__(self, *args: Any, **kwargs: Any) -> Any: ...
 
@@ -5227,7 +5227,7 @@ class poly1d:
         self,
         c_or_r: ArrayLike,
         r: builtins.bool = ...,
-        variable: None | str = ...,
+        variable: str | None = ...,
     ) -> None: ...
     def __len__(self) -> int: ...
     def __neg__(self) -> poly1d: ...
@@ -5250,7 +5250,7 @@ class poly1d:
     def integ(
         self,
         m: SupportsInt | SupportsIndex = ...,
-        k: None | _ArrayLikeComplex_co | _ArrayLikeObject_co = ...,
+        k: _ArrayLikeComplex_co | _ArrayLikeObject_co | None = ...,
     ) -> poly1d: ...
 
 class matrix(ndarray[_2DShapeT_co, _DTypeT_co]):
@@ -5276,14 +5276,7 @@ class matrix(ndarray[_2DShapeT_co, _DTypeT_co]):
     @overload
     def __getitem__(
         self,
-        key: (
-            None
-            | slice
-            | EllipsisType
-            | SupportsIndex
-            | _ArrayLikeInt_co
-            | tuple[None | slice | EllipsisType | _ArrayLikeInt_co | SupportsIndex, ...]
-        ),
+        key: slice | EllipsisType | SupportsIndex | _ArrayLikeInt_co | tuple[slice | EllipsisType | _ArrayLikeInt_co | SupportsIndex | None, ...] | None,
         /,
     ) -> matrix[_2D, _DTypeT_co]: ...
     @overload
@@ -5302,86 +5295,86 @@ class matrix(ndarray[_2DShapeT_co, _DTypeT_co]):
     @overload
     def sum(self, axis: _ShapeLike, dtype: DTypeLike = ..., out: None = ...) -> matrix[_2D, Any]: ...
     @overload
-    def sum(self, axis: None | _ShapeLike = ..., dtype: DTypeLike = ..., out: _ArrayT = ...) -> _ArrayT: ...
+    def sum(self, axis: _ShapeLike | None = ..., dtype: DTypeLike = ..., out: _ArrayT = ...) -> _ArrayT: ...
 
     @overload
     def mean(self, axis: None = ..., dtype: DTypeLike = ..., out: None = ...) -> Any: ...
     @overload
     def mean(self, axis: _ShapeLike, dtype: DTypeLike = ..., out: None = ...) -> matrix[_2D, Any]: ...
     @overload
-    def mean(self, axis: None | _ShapeLike = ..., dtype: DTypeLike = ..., out: _ArrayT = ...) -> _ArrayT: ...
+    def mean(self, axis: _ShapeLike | None = ..., dtype: DTypeLike = ..., out: _ArrayT = ...) -> _ArrayT: ...
 
     @overload
     def std(self, axis: None = ..., dtype: DTypeLike = ..., out: None = ..., ddof: float = ...) -> Any: ...
     @overload
     def std(self, axis: _ShapeLike, dtype: DTypeLike = ..., out: None = ..., ddof: float = ...) -> matrix[_2D, Any]: ...
     @overload
-    def std(self, axis: None | _ShapeLike = ..., dtype: DTypeLike = ..., out: _ArrayT = ..., ddof: float = ...) -> _ArrayT: ...
+    def std(self, axis: _ShapeLike | None = ..., dtype: DTypeLike = ..., out: _ArrayT = ..., ddof: float = ...) -> _ArrayT: ...
 
     @overload
     def var(self, axis: None = ..., dtype: DTypeLike = ..., out: None = ..., ddof: float = ...) -> Any: ...
     @overload
     def var(self, axis: _ShapeLike, dtype: DTypeLike = ..., out: None = ..., ddof: float = ...) -> matrix[_2D, Any]: ...
     @overload
-    def var(self, axis: None | _ShapeLike = ..., dtype: DTypeLike = ..., out: _ArrayT = ..., ddof: float = ...) -> _ArrayT: ...
+    def var(self, axis: _ShapeLike | None = ..., dtype: DTypeLike = ..., out: _ArrayT = ..., ddof: float = ...) -> _ArrayT: ...
 
     @overload
     def prod(self, axis: None = ..., dtype: DTypeLike = ..., out: None = ...) -> Any: ...
     @overload
     def prod(self, axis: _ShapeLike, dtype: DTypeLike = ..., out: None = ...) -> matrix[_2D, Any]: ...
     @overload
-    def prod(self, axis: None | _ShapeLike = ..., dtype: DTypeLike = ..., out: _ArrayT = ...) -> _ArrayT: ...
+    def prod(self, axis: _ShapeLike | None = ..., dtype: DTypeLike = ..., out: _ArrayT = ...) -> _ArrayT: ...
 
     @overload
     def any(self, axis: None = ..., out: None = ...) -> np.bool: ...
     @overload
     def any(self, axis: _ShapeLike, out: None = ...) -> matrix[_2D, dtype[np.bool]]: ...
     @overload
-    def any(self, axis: None | _ShapeLike = ..., out: _ArrayT = ...) -> _ArrayT: ...
+    def any(self, axis: _ShapeLike | None = ..., out: _ArrayT = ...) -> _ArrayT: ...
 
     @overload
     def all(self, axis: None = ..., out: None = ...) -> np.bool: ...
     @overload
     def all(self, axis: _ShapeLike, out: None = ...) -> matrix[_2D, dtype[np.bool]]: ...
     @overload
-    def all(self, axis: None | _ShapeLike = ..., out: _ArrayT = ...) -> _ArrayT: ...
+    def all(self, axis: _ShapeLike | None = ..., out: _ArrayT = ...) -> _ArrayT: ...
 
     @overload
     def max(self: NDArray[_ScalarT], axis: None = ..., out: None = ...) -> _ScalarT: ...
     @overload
     def max(self, axis: _ShapeLike, out: None = ...) -> matrix[_2D, _DTypeT_co]: ...
     @overload
-    def max(self, axis: None | _ShapeLike = ..., out: _ArrayT = ...) -> _ArrayT: ...
+    def max(self, axis: _ShapeLike | None = ..., out: _ArrayT = ...) -> _ArrayT: ...
 
     @overload
     def min(self: NDArray[_ScalarT], axis: None = ..., out: None = ...) -> _ScalarT: ...
     @overload
     def min(self, axis: _ShapeLike, out: None = ...) -> matrix[_2D, _DTypeT_co]: ...
     @overload
-    def min(self, axis: None | _ShapeLike = ..., out: _ArrayT = ...) -> _ArrayT: ...
+    def min(self, axis: _ShapeLike | None = ..., out: _ArrayT = ...) -> _ArrayT: ...
 
     @overload
     def argmax(self: NDArray[_ScalarT], axis: None = ..., out: None = ...) -> intp: ...
     @overload
     def argmax(self, axis: _ShapeLike, out: None = ...) -> matrix[_2D, dtype[intp]]: ...
     @overload
-    def argmax(self, axis: None | _ShapeLike = ..., out: _ArrayT = ...) -> _ArrayT: ...
+    def argmax(self, axis: _ShapeLike | None = ..., out: _ArrayT = ...) -> _ArrayT: ...
 
     @overload
     def argmin(self: NDArray[_ScalarT], axis: None = ..., out: None = ...) -> intp: ...
     @overload
     def argmin(self, axis: _ShapeLike, out: None = ...) -> matrix[_2D, dtype[intp]]: ...
     @overload
-    def argmin(self, axis: None | _ShapeLike = ..., out: _ArrayT = ...) -> _ArrayT: ...
+    def argmin(self, axis: _ShapeLike | None = ..., out: _ArrayT = ...) -> _ArrayT: ...
 
     @overload
     def ptp(self: NDArray[_ScalarT], axis: None = ..., out: None = ...) -> _ScalarT: ...
     @overload
     def ptp(self, axis: _ShapeLike, out: None = ...) -> matrix[_2D, _DTypeT_co]: ...
     @overload
-    def ptp(self, axis: None | _ShapeLike = ..., out: _ArrayT = ...) -> _ArrayT: ...
+    def ptp(self, axis: _ShapeLike | None = ..., out: _ArrayT = ...) -> _ArrayT: ...
 
-    def squeeze(self, axis: None | _ShapeLike = ...) -> matrix[_2D, _DTypeT_co]: ...
+    def squeeze(self, axis: _ShapeLike | None = ...) -> matrix[_2D, _DTypeT_co]: ...
     def tolist(self: matrix[Any, dtype[generic[_T]]]) -> list[list[_T]]: ...  # pyright: ignore[reportIncompatibleMethodOverride]
     def ravel(self, /, order: _OrderKACF = "C") -> matrix[tuple[L[1], int], _DTypeT_co]: ...  # pyright: ignore[reportIncompatibleMethodOverride]
     def flatten(self, /, order: _OrderKACF = "C") -> matrix[tuple[L[1], int], _DTypeT_co]: ...  # pyright: ignore[reportIncompatibleMethodOverride]
diff --git a/numpy/_core/_asarray.pyi b/numpy/_core/_asarray.pyi
index f96101eea1ee..90e17c56c1a2 100644
--- a/numpy/_core/_asarray.pyi
+++ b/numpy/_core/_asarray.pyi
@@ -19,7 +19,7 @@ _RequirementsWithE: TypeAlias = _Requirements | _E
 def require(
     a: _ArrayT,
     dtype: None = ...,
-    requirements: None | _Requirements | Iterable[_Requirements] = ...,
+    requirements: _Requirements | Iterable[_Requirements] | None = ...,
     *,
     like: _SupportsArrayFunc = ...
 ) -> _ArrayT: ...
@@ -35,7 +35,7 @@ def require(
 def require(
     a: object,
     dtype: DTypeLike = ...,
-    requirements: None | _Requirements | Iterable[_Requirements] = ...,
+    requirements: _Requirements | Iterable[_Requirements] | None = ...,
     *,
     like: _SupportsArrayFunc = ...
 ) -> NDArray[Any]: ...
diff --git a/numpy/_core/_ufunc_config.pyi b/numpy/_core/_ufunc_config.pyi
index 3ec1f6208b86..86df9827d652 100644
--- a/numpy/_core/_ufunc_config.pyi
+++ b/numpy/_core/_ufunc_config.pyi
@@ -16,11 +16,11 @@ class _ErrDict(TypedDict):
     invalid: _ErrKind
 
 def seterr(
-    all: None | _ErrKind = ...,
-    divide: None | _ErrKind = ...,
-    over: None | _ErrKind = ...,
-    under: None | _ErrKind = ...,
-    invalid: None | _ErrKind = ...,
+    all: _ErrKind | None = ...,
+    divide: _ErrKind | None = ...,
+    over: _ErrKind | None = ...,
+    under: _ErrKind | None = ...,
+    invalid: _ErrKind | None = ...,
 ) -> _ErrDict: ...
 def geterr() -> _ErrDict: ...
 def setbufsize(size: int) -> int: ...
diff --git a/numpy/_core/arrayprint.pyi b/numpy/_core/arrayprint.pyi
index 1f8be64d5e7b..01a1c10d6b6d 100644
--- a/numpy/_core/arrayprint.pyi
+++ b/numpy/_core/arrayprint.pyi
@@ -69,14 +69,14 @@ class _FormatOptions(TypedDict):
 __docformat__: Final = "restructuredtext"  # undocumented
 
 def set_printoptions(
-    precision: None | SupportsIndex = ...,
-    threshold: None | int = ...,
-    edgeitems: None | int = ...,
-    linewidth: None | int = ...,
-    suppress: None | bool = ...,
-    nanstr: None | str = ...,
-    infstr: None | str = ...,
-    formatter: None | _FormatDict = ...,
+    precision: SupportsIndex | None = ...,
+    threshold: int | None = ...,
+    edgeitems: int | None = ...,
+    linewidth: int | None = ...,
+    suppress: bool | None = ...,
+    nanstr: str | None = ...,
+    infstr: str | None = ...,
+    formatter: _FormatDict | None = ...,
     sign: _Sign | None = None,
     floatmode: _FloatMode | None = None,
     *,
@@ -181,47 +181,47 @@ def array2string(
 
 def format_float_scientific(
     x: _FloatLike_co,
-    precision: None | int = ...,
+    precision: int | None = ...,
     unique: bool = ...,
     trim: _Trim = "k",
     sign: bool = ...,
-    pad_left: None | int = ...,
-    exp_digits: None | int = ...,
-    min_digits: None | int = ...,
+    pad_left: int | None = ...,
+    exp_digits: int | None = ...,
+    min_digits: int | None = ...,
 ) -> str: ...
 def format_float_positional(
     x: _FloatLike_co,
-    precision: None | int = ...,
+    precision: int | None = ...,
     unique: bool = ...,
     fractional: bool = ...,
     trim: _Trim = "k",
     sign: bool = ...,
-    pad_left: None | int = ...,
-    pad_right: None | int = ...,
-    min_digits: None | int = ...,
+    pad_left: int | None = ...,
+    pad_right: int | None = ...,
+    min_digits: int | None = ...,
 ) -> str: ...
 def array_repr(
     arr: NDArray[Any],
-    max_line_width: None | int = ...,
-    precision: None | SupportsIndex = ...,
-    suppress_small: None | bool = ...,
+    max_line_width: int | None = ...,
+    precision: SupportsIndex | None = ...,
+    suppress_small: bool | None = ...,
 ) -> str: ...
 def array_str(
     a: NDArray[Any],
-    max_line_width: None | int = ...,
-    precision: None | SupportsIndex = ...,
-    suppress_small: None | bool = ...,
+    max_line_width: int | None = ...,
+    precision: SupportsIndex | None = ...,
+    suppress_small: bool | None = ...,
 ) -> str: ...
 def printoptions(
-    precision: None | SupportsIndex = ...,
-    threshold: None | int = ...,
-    edgeitems: None | int = ...,
-    linewidth: None | int = ...,
-    suppress: None | bool = ...,
-    nanstr: None | str = ...,
-    infstr: None | str = ...,
-    formatter: None | _FormatDict = ...,
-    sign: None | _Sign = None,
+    precision: SupportsIndex | None = ...,
+    threshold: int | None = ...,
+    edgeitems: int | None = ...,
+    linewidth: int | None = ...,
+    suppress: bool | None = ...,
+    nanstr: str | None = ...,
+    infstr: str | None = ...,
+    formatter: _FormatDict | None = ...,
+    sign: _Sign | None = None,
     floatmode: _FloatMode | None = None,
     *,
     legacy: _Legacy | None = None,
diff --git a/numpy/_core/defchararray.pyi b/numpy/_core/defchararray.pyi
index de010c34d457..b34f13ef9641 100644
--- a/numpy/_core/defchararray.pyi
+++ b/numpy/_core/defchararray.pyi
@@ -233,26 +233,26 @@ class chararray(ndarray[_ShapeT_co, _CharDTypeT_co]):
         self: _CharArray[str_],
         sub: U_co,
         start: i_co = ...,
-        end: None | i_co = ...,
+        end: i_co | None = ...,
     ) -> NDArray[int_]: ...
     @overload
     def count(
         self: _CharArray[bytes_],
         sub: S_co,
         start: i_co = ...,
-        end: None | i_co = ...,
+        end: i_co | None = ...,
     ) -> NDArray[int_]: ...
 
     def decode(
         self: _CharArray[bytes_],
-        encoding: None | str = ...,
-        errors: None | str = ...,
+        encoding: str | None = ...,
+        errors: str | None = ...,
     ) -> _CharArray[str_]: ...
 
     def encode(
         self: _CharArray[str_],
-        encoding: None | str = ...,
-        errors: None | str = ...,
+        encoding: str | None = ...,
+        errors: str | None = ...,
     ) -> _CharArray[bytes_]: ...
 
     @overload
@@ -260,14 +260,14 @@ class chararray(ndarray[_ShapeT_co, _CharDTypeT_co]):
         self: _CharArray[str_],
         suffix: U_co,
         start: i_co = ...,
-        end: None | i_co = ...,
+        end: i_co | None = ...,
     ) -> NDArray[np.bool]: ...
     @overload
     def endswith(
         self: _CharArray[bytes_],
         suffix: S_co,
         start: i_co = ...,
-        end: None | i_co = ...,
+        end: i_co | None = ...,
     ) -> NDArray[np.bool]: ...
 
     def expandtabs(
@@ -280,14 +280,14 @@ class chararray(ndarray[_ShapeT_co, _CharDTypeT_co]):
         self: _CharArray[str_],
         sub: U_co,
         start: i_co = ...,
-        end: None | i_co = ...,
+        end: i_co | None = ...,
     ) -> NDArray[int_]: ...
     @overload
     def find(
         self: _CharArray[bytes_],
         sub: S_co,
         start: i_co = ...,
-        end: None | i_co = ...,
+        end: i_co | None = ...,
     ) -> NDArray[int_]: ...
 
     @overload
@@ -295,14 +295,14 @@ class chararray(ndarray[_ShapeT_co, _CharDTypeT_co]):
         self: _CharArray[str_],
         sub: U_co,
         start: i_co = ...,
-        end: None | i_co = ...,
+        end: i_co | None = ...,
     ) -> NDArray[int_]: ...
     @overload
     def index(
         self: _CharArray[bytes_],
         sub: S_co,
         start: i_co = ...,
-        end: None | i_co = ...,
+        end: i_co | None = ...,
     ) -> NDArray[int_]: ...
 
     @overload
@@ -332,12 +332,12 @@ class chararray(ndarray[_ShapeT_co, _CharDTypeT_co]):
     @overload
     def lstrip(
         self: _CharArray[str_],
-        chars: None | U_co = ...,
+        chars: U_co | None = ...,
     ) -> _CharArray[str_]: ...
     @overload
     def lstrip(
         self: _CharArray[bytes_],
-        chars: None | S_co = ...,
+        chars: S_co | None = ...,
     ) -> _CharArray[bytes_]: ...
 
     @overload
@@ -356,14 +356,14 @@ class chararray(ndarray[_ShapeT_co, _CharDTypeT_co]):
         self: _CharArray[str_],
         old: U_co,
         new: U_co,
-        count: None | i_co = ...,
+        count: i_co | None = ...,
     ) -> _CharArray[str_]: ...
     @overload
     def replace(
         self: _CharArray[bytes_],
         old: S_co,
         new: S_co,
-        count: None | i_co = ...,
+        count: i_co | None = ...,
     ) -> _CharArray[bytes_]: ...
 
     @overload
@@ -371,14 +371,14 @@ class chararray(ndarray[_ShapeT_co, _CharDTypeT_co]):
         self: _CharArray[str_],
         sub: U_co,
         start: i_co = ...,
-        end: None | i_co = ...,
+        end: i_co | None = ...,
     ) -> NDArray[int_]: ...
     @overload
     def rfind(
         self: _CharArray[bytes_],
         sub: S_co,
         start: i_co = ...,
-        end: None | i_co = ...,
+        end: i_co | None = ...,
     ) -> NDArray[int_]: ...
 
     @overload
@@ -386,14 +386,14 @@ class chararray(ndarray[_ShapeT_co, _CharDTypeT_co]):
         self: _CharArray[str_],
         sub: U_co,
         start: i_co = ...,
-        end: None | i_co = ...,
+        end: i_co | None = ...,
     ) -> NDArray[int_]: ...
     @overload
     def rindex(
         self: _CharArray[bytes_],
         sub: S_co,
         start: i_co = ...,
-        end: None | i_co = ...,
+        end: i_co | None = ...,
     ) -> NDArray[int_]: ...
 
     @overload
@@ -423,79 +423,79 @@ class chararray(ndarray[_ShapeT_co, _CharDTypeT_co]):
     @overload
     def rsplit(
         self: _CharArray[str_],
-        sep: None | U_co = ...,
-        maxsplit: None | i_co = ...,
+        sep: U_co | None = ...,
+        maxsplit: i_co | None = ...,
     ) -> NDArray[object_]: ...
     @overload
     def rsplit(
         self: _CharArray[bytes_],
-        sep: None | S_co = ...,
-        maxsplit: None | i_co = ...,
+        sep: S_co | None = ...,
+        maxsplit: i_co | None = ...,
     ) -> NDArray[object_]: ...
 
     @overload
     def rstrip(
         self: _CharArray[str_],
-        chars: None | U_co = ...,
+        chars: U_co | None = ...,
     ) -> _CharArray[str_]: ...
     @overload
     def rstrip(
         self: _CharArray[bytes_],
-        chars: None | S_co = ...,
+        chars: S_co | None = ...,
     ) -> _CharArray[bytes_]: ...
 
     @overload
     def split(
         self: _CharArray[str_],
-        sep: None | U_co = ...,
-        maxsplit: None | i_co = ...,
+        sep: U_co | None = ...,
+        maxsplit: i_co | None = ...,
     ) -> NDArray[object_]: ...
     @overload
     def split(
         self: _CharArray[bytes_],
-        sep: None | S_co = ...,
-        maxsplit: None | i_co = ...,
+        sep: S_co | None = ...,
+        maxsplit: i_co | None = ...,
     ) -> NDArray[object_]: ...
 
-    def splitlines(self, keepends: None | b_co = ...) -> NDArray[object_]: ...
+    def splitlines(self, keepends: b_co | None = ...) -> NDArray[object_]: ...
 
     @overload
     def startswith(
         self: _CharArray[str_],
         prefix: U_co,
         start: i_co = ...,
-        end: None | i_co = ...,
+        end: i_co | None = ...,
     ) -> NDArray[np.bool]: ...
     @overload
     def startswith(
         self: _CharArray[bytes_],
         prefix: S_co,
         start: i_co = ...,
-        end: None | i_co = ...,
+        end: i_co | None = ...,
     ) -> NDArray[np.bool]: ...
 
     @overload
     def strip(
         self: _CharArray[str_],
-        chars: None | U_co = ...,
+        chars: U_co | None = ...,
     ) -> _CharArray[str_]: ...
     @overload
     def strip(
         self: _CharArray[bytes_],
-        chars: None | S_co = ...,
+        chars: S_co | None = ...,
     ) -> _CharArray[bytes_]: ...
 
     @overload
     def translate(
         self: _CharArray[str_],
         table: U_co,
-        deletechars: None | U_co = ...,
+        deletechars: U_co | None = ...,
     ) -> _CharArray[str_]: ...
     @overload
     def translate(
         self: _CharArray[bytes_],
         table: S_co,
-        deletechars: None | S_co = ...,
+        deletechars: S_co | None = ...,
     ) -> _CharArray[bytes_]: ...
 
     def zfill(self, width: i_co) -> chararray[_Shape, _CharDTypeT_co]: ...
@@ -604,13 +604,13 @@ def center(a: T_co, width: i_co, fillchar: T_co = ...) -> _StringDTypeOrUnicodeA
 
 def decode(
     a: S_co,
-    encoding: None | str = ...,
-    errors: None | str = ...,
+    encoding: str | None = ...,
+    errors: str | None = ...,
 ) -> NDArray[str_]: ...
 def encode(
     a: U_co | T_co,
-    encoding: None | str = ...,
-    errors: None | str = ...,
+    encoding: str | None = ...,
+    errors: str | None = ...,
 ) -> NDArray[bytes_]: ...
 
 @overload
@@ -650,13 +650,13 @@ def lower(a: _StringDTypeSupportsArray) -> _StringDTypeArray: ...
 def lower(a: T_co) -> _StringDTypeOrUnicodeArray: ...
 
 @overload
-def lstrip(a: U_co, chars: None | U_co = ...) -> NDArray[str_]: ...
+def lstrip(a: U_co, chars: U_co | None = ...) -> NDArray[str_]: ...
 @overload
-def lstrip(a: S_co, chars: None | S_co = ...) -> NDArray[bytes_]: ...
+def lstrip(a: S_co, chars: S_co | None = ...) -> NDArray[bytes_]: ...
 @overload
-def lstrip(a: _StringDTypeSupportsArray, chars: None | _StringDTypeSupportsArray = ...) -> _StringDTypeArray: ...
+def lstrip(a: _StringDTypeSupportsArray, chars: _StringDTypeSupportsArray | None = ...) -> _StringDTypeArray: ...
 @overload
-def lstrip(a: T_co, chars: None | T_co = ...) -> _StringDTypeOrUnicodeArray: ...
+def lstrip(a: T_co, chars: T_co | None = ...) -> _StringDTypeOrUnicodeArray: ...
 
 @overload
 def partition(a: U_co, sep: U_co) -> NDArray[str_]: ...
@@ -672,14 +672,14 @@ def replace(
     a: U_co,
     old: U_co,
     new: U_co,
-    count: None | i_co = ...,
+    count: i_co | None = ...,
 ) -> NDArray[str_]: ...
 @overload
 def replace(
     a: S_co,
     old: S_co,
     new: S_co,
-    count: None | i_co = ...,
+    count: i_co | None = ...,
 ) -> NDArray[bytes_]: ...
 @overload
 def replace(
@@ -733,72 +733,72 @@ def rpartition(a: T_co, sep: T_co) -> _StringDTypeOrUnicodeArray: ...
 @overload
 def rsplit(
     a: U_co,
-    sep: None | U_co = ...,
-    maxsplit: None | i_co = ...,
+    sep: U_co | None = ...,
+    maxsplit: i_co | None = ...,
 ) -> NDArray[object_]: ...
 @overload
 def rsplit(
     a: S_co,
-    sep: None | S_co = ...,
-    maxsplit: None | i_co = ...,
+    sep: S_co | None = ...,
+    maxsplit: i_co | None = ...,
 ) -> NDArray[object_]: ...
 @overload
 def rsplit(
     a: _StringDTypeSupportsArray,
-    sep: None | _StringDTypeSupportsArray = ...,
-    maxsplit: None | i_co = ...,
+    sep: _StringDTypeSupportsArray | None = ...,
+    maxsplit: i_co | None = ...,
 ) -> NDArray[object_]: ...
 @overload
 def rsplit(
     a: T_co,
-    sep: None | T_co = ...,
-    maxsplit: None | i_co = ...,
+    sep: T_co | None = ...,
+    maxsplit: i_co | None = ...,
 ) -> NDArray[object_]: ...
 
 @overload
-def rstrip(a: U_co, chars: None | U_co = ...) -> NDArray[str_]: ...
+def rstrip(a: U_co, chars: U_co | None = ...) -> NDArray[str_]: ...
 @overload
-def rstrip(a: S_co, chars: None | S_co = ...) -> NDArray[bytes_]: ...
+def rstrip(a: S_co, chars: S_co | None = ...) -> NDArray[bytes_]: ...
 @overload
-def rstrip(a: _StringDTypeSupportsArray, chars: None | _StringDTypeSupportsArray = ...) -> _StringDTypeArray: ...
+def rstrip(a: _StringDTypeSupportsArray, chars: _StringDTypeSupportsArray | None = ...) -> _StringDTypeArray: ...
 @overload
-def rstrip(a: T_co, chars: None | T_co = ...) -> _StringDTypeOrUnicodeArray: ...
+def rstrip(a: T_co, chars: T_co | None = ...) -> _StringDTypeOrUnicodeArray: ...
 
 @overload
 def split(
     a: U_co,
-    sep: None | U_co = ...,
-    maxsplit: None | i_co = ...,
+    sep: U_co | None = ...,
+    maxsplit: i_co | None = ...,
 ) -> NDArray[object_]: ...
 @overload
 def split(
     a: S_co,
-    sep: None | S_co = ...,
-    maxsplit: None | i_co = ...,
+    sep: S_co | None = ...,
+    maxsplit: i_co | None = ...,
 ) -> NDArray[object_]: ...
 @overload
 def split(
     a: _StringDTypeSupportsArray,
-    sep: None | _StringDTypeSupportsArray = ...,
-    maxsplit: None | i_co = ...,
+    sep: _StringDTypeSupportsArray | None = ...,
+    maxsplit: i_co | None = ...,
 ) -> NDArray[object_]: ...
 @overload
 def split(
     a: T_co,
-    sep: None | T_co = ...,
-    maxsplit: None | i_co = ...,
+    sep: T_co | None = ...,
+    maxsplit: i_co | None = ...,
 ) -> NDArray[object_]: ...
 
-def splitlines(a: UST_co, keepends: None | b_co = ...) -> NDArray[np.object_]: ...
+def splitlines(a: UST_co, keepends: b_co | None = ...) -> NDArray[np.object_]: ...
 
 @overload
-def strip(a: U_co, chars: None | U_co = ...) -> NDArray[str_]: ...
+def strip(a: U_co, chars: U_co | None = ...) -> NDArray[str_]: ...
 @overload
-def strip(a: S_co, chars: None | S_co = ...) -> NDArray[bytes_]: ...
+def strip(a: S_co, chars: S_co | None = ...) -> NDArray[bytes_]: ...
 @overload
-def strip(a: _StringDTypeSupportsArray, chars: None | _StringDTypeSupportsArray = ...) -> _StringDTypeArray: ...
+def strip(a: _StringDTypeSupportsArray, chars: _StringDTypeSupportsArray | None = ...) -> _StringDTypeArray: ...
 @overload
-def strip(a: T_co, chars: None | T_co = ...) -> _StringDTypeOrUnicodeArray: ...
+def strip(a: T_co, chars: T_co | None = ...) -> _StringDTypeOrUnicodeArray: ...
 
 @overload
 def swapcase(a: U_co) -> NDArray[str_]: ...
@@ -822,25 +822,25 @@ def title(a: T_co) -> _StringDTypeOrUnicodeArray: ...
 def translate(
     a: U_co,
     table: str,
-    deletechars: None | str = ...,
+    deletechars: str | None = ...,
 ) -> NDArray[str_]: ...
 @overload
 def translate(
     a: S_co,
     table: str,
-    deletechars: None | str = ...,
+    deletechars: str | None = ...,
 ) -> NDArray[bytes_]: ...
 @overload
 def translate(
     a: _StringDTypeSupportsArray,
     table: str,
-    deletechars: None | str = ...,
+    deletechars: str | None = ...,
 ) -> _StringDTypeArray: ...
 @overload
 def translate(
     a: T_co,
     table: str,
-    deletechars: None | str = ...,
+    deletechars: str | None = ...,
 ) -> _StringDTypeOrUnicodeArray: ...
 
 @overload
@@ -867,14 +867,14 @@ def count(
     a: U_co,
     sub: U_co,
     start: i_co = ...,
-    end: None | i_co = ...,
+    end: i_co | None = ...,
 ) -> NDArray[int_]: ...
 @overload
 def count(
     a: S_co,
     sub: S_co,
     start: i_co = ...,
-    end: None | i_co = ...,
+    end: i_co | None = ...,
 ) -> NDArray[int_]: ...
 @overload
 def count(
@@ -889,14 +889,14 @@ def endswith(
     a: U_co,
     suffix: U_co,
     start: i_co = ...,
-    end: None | i_co = ...,
+    end: i_co | None = ...,
 ) -> NDArray[np.bool]: ...
 @overload
 def endswith(
     a: S_co,
     suffix: S_co,
     start: i_co = ...,
-    end: None | i_co = ...,
+    end: i_co | None = ...,
 ) -> NDArray[np.bool]: ...
 @overload
 def endswith(
@@ -911,14 +911,14 @@ def find(
     a: U_co,
     sub: U_co,
     start: i_co = ...,
-    end: None | i_co = ...,
+    end: i_co | None = ...,
 ) -> NDArray[int_]: ...
 @overload
 def find(
     a: S_co,
     sub: S_co,
     start: i_co = ...,
-    end: None | i_co = ...,
+    end: i_co | None = ...,
 ) -> NDArray[int_]: ...
 @overload
 def find(
@@ -933,14 +933,14 @@ def index(
     a: U_co,
     sub: U_co,
     start: i_co = ...,
-    end: None | i_co = ...,
+    end: i_co | None = ...,
 ) -> NDArray[int_]: ...
 @overload
 def index(
     a: S_co,
     sub: S_co,
     start: i_co = ...,
-    end: None | i_co = ...,
+    end: i_co | None = ...,
 ) -> NDArray[int_]: ...
 @overload
 def index(
@@ -965,14 +965,14 @@ def rfind(
     a: U_co,
     sub: U_co,
     start: i_co = ...,
-    end: None | i_co = ...,
+    end: i_co | None = ...,
 ) -> NDArray[int_]: ...
 @overload
 def rfind(
     a: S_co,
     sub: S_co,
     start: i_co = ...,
-    end: None | i_co = ...,
+    end: i_co | None = ...,
 ) -> NDArray[int_]: ...
 @overload
 def rfind(
@@ -987,14 +987,14 @@ def rindex(
     a: U_co,
     sub: U_co,
     start: i_co = ...,
-    end: None | i_co = ...,
+    end: i_co | None = ...,
 ) -> NDArray[int_]: ...
 @overload
 def rindex(
     a: S_co,
     sub: S_co,
     start: i_co = ...,
-    end: None | i_co = ...,
+    end: i_co | None = ...,
 ) -> NDArray[int_]: ...
 @overload
 def rindex(
@@ -1009,14 +1009,14 @@ def startswith(
     a: U_co,
     prefix: U_co,
     start: i_co = ...,
-    end: None | i_co = ...,
+    end: i_co | None = ...,
 ) -> NDArray[np.bool]: ...
 @overload
 def startswith(
     a: S_co,
     prefix: S_co,
     start: i_co = ...,
-    end: None | i_co = ...,
+    end: i_co | None = ...,
 ) -> NDArray[np.bool]: ...
 @overload
 def startswith(
@@ -1034,7 +1034,7 @@ def str_len(A: UST_co) -> NDArray[int_]: ...
 @overload
 def array(
     obj: U_co,
-    itemsize: None | int = ...,
+    itemsize: int | None = ...,
     copy: bool = ...,
     unicode: L[False] = ...,
     order: _OrderKACF = ...,
@@ -1042,7 +1042,7 @@ def array(
 @overload
 def array(
     obj: S_co,
-    itemsize: None | int = ...,
+    itemsize: int | None = ...,
     copy: bool = ...,
     unicode: L[False] = ...,
     order: _OrderKACF = ...,
@@ -1050,7 +1050,7 @@ def array(
 @overload
 def array(
     obj: object,
-    itemsize: None | int = ...,
+    itemsize: int | None = ...,
     copy: bool = ...,
     unicode: L[False] = ...,
     order: _OrderKACF = ...,
@@ -1058,7 +1058,7 @@ def array(
 @overload
 def array(
     obj: object,
-    itemsize: None | int = ...,
+    itemsize: int | None = ...,
     copy: bool = ...,
     unicode: L[True] = ...,
     order: _OrderKACF = ...,
@@ -1067,28 +1067,28 @@ def array(
 @overload
 def asarray(
     obj: U_co,
-    itemsize: None | int = ...,
+    itemsize: int | None = ...,
     unicode: L[False] = ...,
     order: _OrderKACF = ...,
 ) -> _CharArray[str_]: ...
 @overload
 def asarray(
     obj: S_co,
-    itemsize: None | int = ...,
+    itemsize: int | None = ...,
     unicode: L[False] = ...,
     order: _OrderKACF = ...,
 ) -> _CharArray[bytes_]: ...
 @overload
 def asarray(
     obj: object,
-    itemsize: None | int = ...,
+    itemsize: int | None = ...,
     unicode: L[False] = ...,
     order: _OrderKACF = ...,
 ) -> _CharArray[bytes_]: ...
 @overload
 def asarray(
     obj: object,
-    itemsize: None | int = ...,
+    itemsize: int | None = ...,
     unicode: L[True] = ...,
     order: _OrderKACF = ...,
 ) -> _CharArray[str_]: ...
diff --git a/numpy/_core/einsumfunc.pyi b/numpy/_core/einsumfunc.pyi
index a4648c9193c3..e45c865da3f1 100644
--- a/numpy/_core/einsumfunc.pyi
+++ b/numpy/_core/einsumfunc.pyi
@@ -43,7 +43,7 @@ def einsum(
     /,
     *operands: _ArrayLikeBool_co,
     out: None = ...,
-    dtype: None | _DTypeLikeBool = ...,
+    dtype: _DTypeLikeBool | None = ...,
     order: _OrderKACF = ...,
     casting: _CastingSafe = ...,
     optimize: _OptimizeKind = ...,
@@ -54,7 +54,7 @@ def einsum(
     /,
     *operands: _ArrayLikeUInt_co,
     out: None = ...,
-    dtype: None | _DTypeLikeUInt = ...,
+    dtype: _DTypeLikeUInt | None = ...,
     order: _OrderKACF = ...,
     casting: _CastingSafe = ...,
     optimize: _OptimizeKind = ...,
@@ -65,7 +65,7 @@ def einsum(
     /,
     *operands: _ArrayLikeInt_co,
     out: None = ...,
-    dtype: None | _DTypeLikeInt = ...,
+    dtype: _DTypeLikeInt | None = ...,
     order: _OrderKACF = ...,
     casting: _CastingSafe = ...,
     optimize: _OptimizeKind = ...,
@@ -76,7 +76,7 @@ def einsum(
     /,
     *operands: _ArrayLikeFloat_co,
     out: None = ...,
-    dtype: None | _DTypeLikeFloat = ...,
+    dtype: _DTypeLikeFloat | None = ...,
     order: _OrderKACF = ...,
     casting: _CastingSafe = ...,
     optimize: _OptimizeKind = ...,
@@ -87,7 +87,7 @@ def einsum(
     /,
     *operands: _ArrayLikeComplex_co,
     out: None = ...,
-    dtype: None | _DTypeLikeComplex = ...,
+    dtype: _DTypeLikeComplex | None = ...,
     order: _OrderKACF = ...,
     casting: _CastingSafe = ...,
     optimize: _OptimizeKind = ...,
@@ -98,7 +98,7 @@ def einsum(
     /,
     *operands: Any,
     casting: _CastingUnsafe,
-    dtype: None | _DTypeLikeComplex_co = ...,
+    dtype: _DTypeLikeComplex_co | None = ...,
     out: None = ...,
     order: _OrderKACF = ...,
     optimize: _OptimizeKind = ...,
@@ -109,7 +109,7 @@ def einsum(
     /,
     *operands: _ArrayLikeComplex_co,
     out: _ArrayT,
-    dtype: None | _DTypeLikeComplex_co = ...,
+    dtype: _DTypeLikeComplex_co | None = ...,
     order: _OrderKACF = ...,
     casting: _CastingSafe = ...,
     optimize: _OptimizeKind = ...,
@@ -121,7 +121,7 @@ def einsum(
     *operands: Any,
     out: _ArrayT,
     casting: _CastingUnsafe,
-    dtype: None | _DTypeLikeComplex_co = ...,
+    dtype: _DTypeLikeComplex_co | None = ...,
     order: _OrderKACF = ...,
     optimize: _OptimizeKind = ...,
 ) -> _ArrayT: ...
@@ -132,7 +132,7 @@ def einsum(
     /,
     *operands: _ArrayLikeObject_co,
     out: None = ...,
-    dtype: None | _DTypeLikeObject = ...,
+    dtype: _DTypeLikeObject | None = ...,
     order: _OrderKACF = ...,
     casting: _CastingSafe = ...,
     optimize: _OptimizeKind = ...,
@@ -143,7 +143,7 @@ def einsum(
     /,
     *operands: Any,
     casting: _CastingUnsafe,
-    dtype: None | _DTypeLikeObject = ...,
+    dtype: _DTypeLikeObject | None = ...,
     out: None = ...,
     order: _OrderKACF = ...,
     optimize: _OptimizeKind = ...,
@@ -154,7 +154,7 @@ def einsum(
     /,
     *operands: _ArrayLikeObject_co,
     out: _ArrayT,
-    dtype: None | _DTypeLikeObject = ...,
+    dtype: _DTypeLikeObject | None = ...,
     order: _OrderKACF = ...,
     casting: _CastingSafe = ...,
     optimize: _OptimizeKind = ...,
@@ -166,7 +166,7 @@ def einsum(
     *operands: Any,
     out: _ArrayT,
     casting: _CastingUnsafe,
-    dtype: None | _DTypeLikeObject = ...,
+    dtype: _DTypeLikeObject | None = ...,
     order: _OrderKACF = ...,
     optimize: _OptimizeKind = ...,
 ) -> _ArrayT: ...
diff --git a/numpy/_core/multiarray.pyi b/numpy/_core/multiarray.pyi
index a2ca8db7959a..a127b04c9e2e 100644
--- a/numpy/_core/multiarray.pyi
+++ b/numpy/_core/multiarray.pyi
@@ -241,8 +241,8 @@ class _SupportsArray(Protocol[_ArrayT_co]):
 
 @type_check_only
 class _KwargsEmpty(TypedDict, total=False):
-    device: None | L["cpu"]
-    like: None | _SupportsArrayFunc
+    device: L["cpu"] | None
+    like: _SupportsArrayFunc | None
 
 @type_check_only
 class _ConstructorEmpty(Protocol):
@@ -406,9 +406,9 @@ def empty_like(
     dtype: None = ...,
     order: _OrderKACF = ...,
     subok: bool = ...,
-    shape: None | _ShapeLike = ...,
+    shape: _ShapeLike | None = ...,
     *,
-    device: None | L["cpu"] = ...,
+    device: L["cpu"] | None = ...,
 ) -> _ArrayT: ...
 @overload
 def empty_like(
@@ -416,9 +416,9 @@ def empty_like(
     dtype: None = ...,
     order: _OrderKACF = ...,
     subok: bool = ...,
-    shape: None | _ShapeLike = ...,
+    shape: _ShapeLike | None = ...,
     *,
-    device: None | L["cpu"] = ...,
+    device: L["cpu"] | None = ...,
 ) -> NDArray[_ScalarT]: ...
 @overload
 def empty_like(
@@ -426,9 +426,9 @@ def empty_like(
     dtype: _DTypeLike[_ScalarT],
     order: _OrderKACF = ...,
     subok: bool = ...,
-    shape: None | _ShapeLike = ...,
+    shape: _ShapeLike | None = ...,
     *,
-    device: None | L["cpu"] = ...,
+    device: L["cpu"] | None = ...,
 ) -> NDArray[_ScalarT]: ...
 @overload
 def empty_like(
@@ -436,9 +436,9 @@ def empty_like(
     dtype: DTypeLike | None = ...,
     order: _OrderKACF = ...,
     subok: bool = ...,
-    shape: None | _ShapeLike = ...,
+    shape: _ShapeLike | None = ...,
     *,
-    device: None | L["cpu"] = ...,
+    device: L["cpu"] | None = ...,
 ) -> NDArray[Any]: ...
 
 @overload
@@ -446,55 +446,55 @@ def array(
     object: _ArrayT,
     dtype: None = ...,
     *,
-    copy: None | bool | _CopyMode = ...,
+    copy: bool | _CopyMode | None = ...,
     order: _OrderKACF = ...,
     subok: L[True],
     ndmin: int = ...,
-    like: None | _SupportsArrayFunc = ...,
+    like: _SupportsArrayFunc | None = ...,
 ) -> _ArrayT: ...
 @overload
 def array(
     object: _SupportsArray[_ArrayT],
     dtype: None = ...,
     *,
-    copy: None | bool | _CopyMode = ...,
+    copy: bool | _CopyMode | None = ...,
     order: _OrderKACF = ...,
     subok: L[True],
     ndmin: L[0] = ...,
-    like: None | _SupportsArrayFunc = ...,
+    like: _SupportsArrayFunc | None = ...,
 ) -> _ArrayT: ...
 @overload
 def array(
     object: _ArrayLike[_ScalarT],
     dtype: None = ...,
     *,
-    copy: None | bool | _CopyMode = ...,
+    copy: bool | _CopyMode | None = ...,
     order: _OrderKACF = ...,
     subok: bool = ...,
     ndmin: int = ...,
-    like: None | _SupportsArrayFunc = ...,
+    like: _SupportsArrayFunc | None = ...,
 ) -> NDArray[_ScalarT]: ...
 @overload
 def array(
     object: Any,
     dtype: _DTypeLike[_ScalarT],
     *,
-    copy: None | bool | _CopyMode = ...,
+    copy: bool | _CopyMode | None = ...,
     order: _OrderKACF = ...,
     subok: bool = ...,
     ndmin: int = ...,
-    like: None | _SupportsArrayFunc = ...,
+    like: _SupportsArrayFunc | None = ...,
 ) -> NDArray[_ScalarT]: ...
 @overload
 def array(
     object: Any,
     dtype: DTypeLike | None = ...,
     *,
-    copy: None | bool | _CopyMode = ...,
+    copy: bool | _CopyMode | None = ...,
     order: _OrderKACF = ...,
     subok: bool = ...,
     ndmin: int = ...,
-    like: None | _SupportsArrayFunc = ...,
+    like: _SupportsArrayFunc | None = ...,
 ) -> NDArray[Any]: ...
 
 @overload
@@ -530,42 +530,42 @@ def ravel_multi_index(
 def concatenate(  # type: ignore[misc]
     arrays: _ArrayLike[_ScalarT],
     /,
-    axis: None | SupportsIndex = ...,
+    axis: SupportsIndex | None = ...,
     out: None = ...,
     *,
     dtype: None = ...,
-    casting: None | _CastingKind = ...
+    casting: _CastingKind | None = ...
 ) -> NDArray[_ScalarT]: ...
 @overload
 @overload
 def concatenate(  # type: ignore[misc]
     arrays: SupportsLenAndGetItem[ArrayLike],
     /,
-    axis: None | SupportsIndex = ...,
+    axis: SupportsIndex | None = ...,
     out: None = ...,
     *,
     dtype: _DTypeLike[_ScalarT],
-    casting: None | _CastingKind = ...
+    casting: _CastingKind | None = ...
 ) -> NDArray[_ScalarT]: ...
 @overload
 def concatenate(  # type: ignore[misc]
     arrays: SupportsLenAndGetItem[ArrayLike],
     /,
-    axis: None | SupportsIndex = ...,
+    axis: SupportsIndex | None = ...,
     out: None = ...,
     *,
     dtype: DTypeLike | None = None,
-    casting: None | _CastingKind = ...
+    casting: _CastingKind | None = ...
 ) -> NDArray[Any]: ...
 @overload
 def concatenate(
     arrays: SupportsLenAndGetItem[ArrayLike],
     /,
-    axis: None | SupportsIndex = ...,
+    axis: SupportsIndex | None = ...,
     out: _ArrayT = ...,
     *,
     dtype: DTypeLike = ...,
-    casting: None | _CastingKind = ...
+    casting: _CastingKind | None = ...
 ) -> _ArrayT: ...
 
 def inner(
@@ -589,13 +589,13 @@ def where(
 
 def lexsort(
     keys: ArrayLike,
-    axis: None | SupportsIndex = ...,
+    axis: SupportsIndex | None = ...,
 ) -> Any: ...
 
 def can_cast(
     from_: ArrayLike | DTypeLike,
     to: DTypeLike,
-    casting: None | _CastingKind = ...,
+    casting: _CastingKind | None = ...,
 ) -> bool: ...
 
 def min_scalar_type(
@@ -631,15 +631,15 @@ def vdot(a: Any, b: _ArrayLikeObject_co, /) -> Any: ...
 def bincount(
     x: ArrayLike,
     /,
-    weights: None | ArrayLike = ...,
+    weights: ArrayLike | None = ...,
     minlength: SupportsIndex = ...,
 ) -> NDArray[intp]: ...
 
 def copyto(
     dst: NDArray[Any],
     src: ArrayLike,
-    casting: None | _CastingKind = ...,
-    where: None | _ArrayLikeBool_co = ...,
+    casting: _CastingKind | None = ...,
+    where: _ArrayLikeBool_co | None = ...,
 ) -> None: ...
 
 def putmask(
@@ -652,15 +652,15 @@ def putmask(
 def packbits(
     a: _ArrayLikeInt_co,
     /,
-    axis: None | SupportsIndex = ...,
+    axis: SupportsIndex | None = ...,
     bitorder: L["big", "little"] = ...,
 ) -> NDArray[uint8]: ...
 
 def unpackbits(
     a: _ArrayLike[uint8],
     /,
-    axis: None | SupportsIndex = ...,
-    count: None | SupportsIndex = ...,
+    axis: SupportsIndex | None = ...,
+    count: SupportsIndex | None = ...,
     bitorder: L["big", "little"] = ...,
 ) -> NDArray[uint8]: ...
 
@@ -668,14 +668,14 @@ def shares_memory(
     a: object,
     b: object,
     /,
-    max_work: None | int = ...,
+    max_work: int | None = ...,
 ) -> bool: ...
 
 def may_share_memory(
     a: object,
     b: object,
     /,
-    max_work: None | int = ...,
+    max_work: int | None = ...,
 ) -> bool: ...
 
 @overload
@@ -684,9 +684,9 @@ def asarray(
     dtype: None = ...,
     order: _OrderKACF = ...,
     *,
-    device: None | L["cpu"] = ...,
-    copy: None | bool = ...,
-    like: None | _SupportsArrayFunc = ...,
+    device: L["cpu"] | None = ...,
+    copy: bool | None = ...,
+    like: _SupportsArrayFunc | None = ...,
 ) -> NDArray[_ScalarT]: ...
 @overload
 def asarray(
@@ -694,9 +694,9 @@ def asarray(
     dtype: _DTypeLike[_ScalarT],
     order: _OrderKACF = ...,
     *,
-    device: None | L["cpu"] = ...,
-    copy: None | bool = ...,
-    like: None | _SupportsArrayFunc = ...,
+    device: L["cpu"] | None = ...,
+    copy: bool | None = ...,
+    like: _SupportsArrayFunc | None = ...,
 ) -> NDArray[_ScalarT]: ...
 @overload
 def asarray(
@@ -704,9 +704,9 @@ def asarray(
     dtype: DTypeLike | None = ...,
     order: _OrderKACF = ...,
     *,
-    device: None | L["cpu"] = ...,
-    copy: None | bool = ...,
-    like: None | _SupportsArrayFunc = ...,
+    device: L["cpu"] | None = ...,
+    copy: bool | None = ...,
+    like: _SupportsArrayFunc | None = ...,
 ) -> NDArray[Any]: ...
 
 @overload
@@ -715,9 +715,9 @@ def asanyarray(
     dtype: None = ...,
     order: _OrderKACF = ...,
     *,
-    device: None | L["cpu"] = ...,
-    copy: None | bool = ...,
-    like: None | _SupportsArrayFunc = ...,
+    device: L["cpu"] | None = ...,
+    copy: bool | None = ...,
+    like: _SupportsArrayFunc | None = ...,
 ) -> _ArrayT: ...
 @overload
 def asanyarray(
@@ -725,9 +725,9 @@ def asanyarray(
     dtype: None = ...,
     order: _OrderKACF = ...,
     *,
-    device: None | L["cpu"] = ...,
-    copy: None | bool = ...,
-    like: None | _SupportsArrayFunc = ...,
+    device: L["cpu"] | None = ...,
+    copy: bool | None = ...,
+    like: _SupportsArrayFunc | None = ...,
 ) -> NDArray[_ScalarT]: ...
 @overload
 def asanyarray(
@@ -735,9 +735,9 @@ def asanyarray(
     dtype: _DTypeLike[_ScalarT],
     order: _OrderKACF = ...,
     *,
-    device: None | L["cpu"] = ...,
-    copy: None | bool = ...,
-    like: None | _SupportsArrayFunc = ...,
+    device: L["cpu"] | None = ...,
+    copy: bool | None = ...,
+    like: _SupportsArrayFunc | None = ...,
 ) -> NDArray[_ScalarT]: ...
 @overload
 def asanyarray(
@@ -745,9 +745,9 @@ def asanyarray(
     dtype: DTypeLike | None = ...,
     order: _OrderKACF = ...,
     *,
-    device: None | L["cpu"] = ...,
-    copy: None | bool = ...,
-    like: None | _SupportsArrayFunc = ...,
+    device: L["cpu"] | None = ...,
+    copy: bool | None = ...,
+    like: _SupportsArrayFunc | None = ...,
 ) -> NDArray[Any]: ...
 
 @overload
@@ -755,21 +755,21 @@ def ascontiguousarray(
     a: _ArrayLike[_ScalarT],
     dtype: None = ...,
     *,
-    like: None | _SupportsArrayFunc = ...,
+    like: _SupportsArrayFunc | None = ...,
 ) -> NDArray[_ScalarT]: ...
 @overload
 def ascontiguousarray(
     a: Any,
     dtype: _DTypeLike[_ScalarT],
     *,
-    like: None | _SupportsArrayFunc = ...,
+    like: _SupportsArrayFunc | None = ...,
 ) -> NDArray[_ScalarT]: ...
 @overload
 def ascontiguousarray(
     a: Any,
     dtype: DTypeLike | None = ...,
     *,
-    like: None | _SupportsArrayFunc = ...,
+    like: _SupportsArrayFunc | None = ...,
 ) -> NDArray[Any]: ...
 
 @overload
@@ -777,21 +777,21 @@ def asfortranarray(
     a: _ArrayLike[_ScalarT],
     dtype: None = ...,
     *,
-    like: None | _SupportsArrayFunc = ...,
+    like: _SupportsArrayFunc | None = ...,
 ) -> NDArray[_ScalarT]: ...
 @overload
 def asfortranarray(
     a: Any,
     dtype: _DTypeLike[_ScalarT],
     *,
-    like: None | _SupportsArrayFunc = ...,
+    like: _SupportsArrayFunc | None = ...,
 ) -> NDArray[_ScalarT]: ...
 @overload
 def asfortranarray(
     a: Any,
     dtype: DTypeLike | None = ...,
     *,
-    like: None | _SupportsArrayFunc = ...,
+    like: _SupportsArrayFunc | None = ...,
 ) -> NDArray[Any]: ...
 
 def promote_types(__type1: DTypeLike, __type2: DTypeLike) -> dtype[Any]: ...
@@ -804,7 +804,7 @@ def fromstring(
     count: SupportsIndex = ...,
     *,
     sep: str,
-    like: None | _SupportsArrayFunc = ...,
+    like: _SupportsArrayFunc | None = ...,
 ) -> NDArray[float64]: ...
 @overload
 def fromstring(
@@ -813,7 +813,7 @@ def fromstring(
     count: SupportsIndex = ...,
     *,
     sep: str,
-    like: None | _SupportsArrayFunc = ...,
+    like: _SupportsArrayFunc | None = ...,
 ) -> NDArray[_ScalarT]: ...
 @overload
 def fromstring(
@@ -822,7 +822,7 @@ def fromstring(
     count: SupportsIndex = ...,
     *,
     sep: str,
-    like: None | _SupportsArrayFunc = ...,
+    like: _SupportsArrayFunc | None = ...,
 ) -> NDArray[Any]: ...
 
 @overload
@@ -895,7 +895,7 @@ def frompyfunc(
     nin: SupportsIndex,
     nout: SupportsIndex,
     *,
-    identity: None | object = ...,
+    identity: object | None = ...,
 ) -> ufunc: ...
 
 @overload
@@ -906,7 +906,7 @@ def fromfile(
     sep: str = ...,
     offset: SupportsIndex = ...,
     *,
-    like: None | _SupportsArrayFunc = ...,
+    like: _SupportsArrayFunc | None = ...,
 ) -> NDArray[float64]: ...
 @overload
 def fromfile(
@@ -916,7 +916,7 @@ def fromfile(
     sep: str = ...,
     offset: SupportsIndex = ...,
     *,
-    like: None | _SupportsArrayFunc = ...,
+    like: _SupportsArrayFunc | None = ...,
 ) -> NDArray[_ScalarT]: ...
 @overload
 def fromfile(
@@ -926,7 +926,7 @@ def fromfile(
     sep: str = ...,
     offset: SupportsIndex = ...,
     *,
-    like: None | _SupportsArrayFunc = ...,
+    like: _SupportsArrayFunc | None = ...,
 ) -> NDArray[Any]: ...
 
 @overload
@@ -935,7 +935,7 @@ def fromiter(
     dtype: _DTypeLike[_ScalarT],
     count: SupportsIndex = ...,
     *,
-    like: None | _SupportsArrayFunc = ...,
+    like: _SupportsArrayFunc | None = ...,
 ) -> NDArray[_ScalarT]: ...
 @overload
 def fromiter(
@@ -943,7 +943,7 @@ def fromiter(
     dtype: DTypeLike,
     count: SupportsIndex = ...,
     *,
-    like: None | _SupportsArrayFunc = ...,
+    like: _SupportsArrayFunc | None = ...,
 ) -> NDArray[Any]: ...
 
 @overload
@@ -953,7 +953,7 @@ def frombuffer(
     count: SupportsIndex = ...,
     offset: SupportsIndex = ...,
     *,
-    like: None | _SupportsArrayFunc = ...,
+    like: _SupportsArrayFunc | None = ...,
 ) -> NDArray[float64]: ...
 @overload
 def frombuffer(
@@ -962,7 +962,7 @@ def frombuffer(
     count: SupportsIndex = ...,
     offset: SupportsIndex = ...,
     *,
-    like: None | _SupportsArrayFunc = ...,
+    like: _SupportsArrayFunc | None = ...,
 ) -> NDArray[_ScalarT]: ...
 @overload
 def frombuffer(
@@ -971,7 +971,7 @@ def frombuffer(
     count: SupportsIndex = ...,
     offset: SupportsIndex = ...,
     *,
-    like: None | _SupportsArrayFunc = ...,
+    like: _SupportsArrayFunc | None = ...,
 ) -> NDArray[Any]: ...
 
 @overload
@@ -979,8 +979,8 @@ def arange(  # type: ignore[misc]
     stop: _IntLike_co,
     /, *,
     dtype: None = ...,
-    device: None | L["cpu"] = ...,
-    like: None | _SupportsArrayFunc = ...,
+    device: L["cpu"] | None = ...,
+    like: _SupportsArrayFunc | None = ...,
 ) -> _Array1D[signedinteger]: ...
 @overload
 def arange(  # type: ignore[misc]
@@ -989,16 +989,16 @@ def arange(  # type: ignore[misc]
     step: _IntLike_co = ...,
     dtype: None = ...,
     *,
-    device: None | L["cpu"] = ...,
-    like: None | _SupportsArrayFunc = ...,
+    device: L["cpu"] | None = ...,
+    like: _SupportsArrayFunc | None = ...,
 ) -> _Array1D[signedinteger]: ...
 @overload
 def arange(  # type: ignore[misc]
     stop: _FloatLike_co,
     /, *,
     dtype: None = ...,
-    device: None | L["cpu"] = ...,
-    like: None | _SupportsArrayFunc = ...,
+    device: L["cpu"] | None = ...,
+    like: _SupportsArrayFunc | None = ...,
 ) -> _Array1D[floating]: ...
 @overload
 def arange(  # type: ignore[misc]
@@ -1007,16 +1007,16 @@ def arange(  # type: ignore[misc]
     step: _FloatLike_co = ...,
     dtype: None = ...,
     *,
-    device: None | L["cpu"] = ...,
-    like: None | _SupportsArrayFunc = ...,
+    device: L["cpu"] | None = ...,
+    like: _SupportsArrayFunc | None = ...,
 ) -> _Array1D[floating]: ...
 @overload
 def arange(
     stop: _TD64Like_co,
     /, *,
     dtype: None = ...,
-    device: None | L["cpu"] = ...,
-    like: None | _SupportsArrayFunc = ...,
+    device: L["cpu"] | None = ...,
+    like: _SupportsArrayFunc | None = ...,
 ) -> _Array1D[timedelta64]: ...
 @overload
 def arange(
@@ -1025,8 +1025,8 @@ def arange(
     step: _TD64Like_co = ...,
     dtype: None = ...,
     *,
-    device: None | L["cpu"] = ...,
-    like: None | _SupportsArrayFunc = ...,
+    device: L["cpu"] | None = ...,
+    like: _SupportsArrayFunc | None = ...,
 ) -> _Array1D[timedelta64]: ...
 @overload
 def arange(  # both start and stop must always be specified for datetime64
@@ -1035,16 +1035,16 @@ def arange(  # both start and stop must always be specified for datetime64
     step: datetime64 = ...,
     dtype: None = ...,
     *,
-    device: None | L["cpu"] = ...,
-    like: None | _SupportsArrayFunc = ...,
+    device: L["cpu"] | None = ...,
+    like: _SupportsArrayFunc | None = ...,
 ) -> _Array1D[datetime64]: ...
 @overload
 def arange(
     stop: Any,
     /, *,
     dtype: _DTypeLike[_ScalarT],
-    device: None | L["cpu"] = ...,
-    like: None | _SupportsArrayFunc = ...,
+    device: L["cpu"] | None = ...,
+    like: _SupportsArrayFunc | None = ...,
 ) -> _Array1D[_ScalarT]: ...
 @overload
 def arange(
@@ -1053,16 +1053,16 @@ def arange(
     step: Any = ...,
     dtype: _DTypeLike[_ScalarT] = ...,
     *,
-    device: None | L["cpu"] = ...,
-    like: None | _SupportsArrayFunc = ...,
+    device: L["cpu"] | None = ...,
+    like: _SupportsArrayFunc | None = ...,
 ) -> _Array1D[_ScalarT]: ...
 @overload
 def arange(
     stop: Any, /,
     *,
     dtype: DTypeLike | None = ...,
-    device: None | L["cpu"] = ...,
-    like: None | _SupportsArrayFunc = ...,
+    device: L["cpu"] | None = ...,
+    like: _SupportsArrayFunc | None = ...,
 ) -> _Array1D[Any]: ...
 @overload
 def arange(
@@ -1071,8 +1071,8 @@ def arange(
     step: Any = ...,
     dtype: DTypeLike | None = ...,
     *,
-    device: None | L["cpu"] = ...,
-    like: None | _SupportsArrayFunc = ...,
+    device: L["cpu"] | None = ...,
+    like: _SupportsArrayFunc | None = ...,
 ) -> _Array1D[Any]: ...
 
 def datetime_data(
@@ -1087,8 +1087,8 @@ def busday_count(  # type: ignore[misc]
     begindates: _ScalarLike_co | dt.date,
     enddates: _ScalarLike_co | dt.date,
     weekmask: ArrayLike = ...,
-    holidays: None | ArrayLike | dt.date | _NestedSequence[dt.date] = ...,
-    busdaycal: None | busdaycalendar = ...,
+    holidays: ArrayLike | dt.date | _NestedSequence[dt.date] | None = ...,
+    busdaycal: busdaycalendar | None = ...,
     out: None = ...,
 ) -> int_: ...
 @overload
@@ -1096,8 +1096,8 @@ def busday_count(  # type: ignore[misc]
     begindates: ArrayLike | dt.date | _NestedSequence[dt.date],
     enddates: ArrayLike | dt.date | _NestedSequence[dt.date],
     weekmask: ArrayLike = ...,
-    holidays: None | ArrayLike | dt.date | _NestedSequence[dt.date] = ...,
-    busdaycal: None | busdaycalendar = ...,
+    holidays: ArrayLike | dt.date | _NestedSequence[dt.date] | None = ...,
+    busdaycal: busdaycalendar | None = ...,
     out: None = ...,
 ) -> NDArray[int_]: ...
 @overload
@@ -1105,8 +1105,8 @@ def busday_count(
     begindates: ArrayLike | dt.date | _NestedSequence[dt.date],
     enddates: ArrayLike | dt.date | _NestedSequence[dt.date],
     weekmask: ArrayLike = ...,
-    holidays: None | ArrayLike | dt.date | _NestedSequence[dt.date] = ...,
-    busdaycal: None | busdaycalendar = ...,
+    holidays: ArrayLike | dt.date | _NestedSequence[dt.date] | None = ...,
+    busdaycal: busdaycalendar | None = ...,
     out: _ArrayT = ...,
 ) -> _ArrayT: ...
 
@@ -1117,8 +1117,8 @@ def busday_offset(  # type: ignore[misc]
     offsets: _TD64Like_co | dt.timedelta,
     roll: L["raise"] = ...,
     weekmask: ArrayLike = ...,
-    holidays: None | ArrayLike | dt.date | _NestedSequence[dt.date] = ...,
-    busdaycal: None | busdaycalendar = ...,
+    holidays: ArrayLike | dt.date | _NestedSequence[dt.date] | None = ...,
+    busdaycal: busdaycalendar | None = ...,
     out: None = ...,
 ) -> datetime64: ...
 @overload
@@ -1127,8 +1127,8 @@ def busday_offset(  # type: ignore[misc]
     offsets: _ArrayLikeTD64_co | dt.timedelta | _NestedSequence[dt.timedelta],
     roll: L["raise"] = ...,
     weekmask: ArrayLike = ...,
-    holidays: None | ArrayLike | dt.date | _NestedSequence[dt.date] = ...,
-    busdaycal: None | busdaycalendar = ...,
+    holidays: ArrayLike | dt.date | _NestedSequence[dt.date] | None = ...,
+    busdaycal: busdaycalendar | None = ...,
     out: None = ...,
 ) -> NDArray[datetime64]: ...
 @overload
@@ -1137,8 +1137,8 @@ def busday_offset(  # type: ignore[misc]
     offsets: _ArrayLikeTD64_co | dt.timedelta | _NestedSequence[dt.timedelta],
     roll: L["raise"] = ...,
     weekmask: ArrayLike = ...,
-    holidays: None | ArrayLike | dt.date | _NestedSequence[dt.date] = ...,
-    busdaycal: None | busdaycalendar = ...,
+    holidays: ArrayLike | dt.date | _NestedSequence[dt.date] | None = ...,
+    busdaycal: busdaycalendar | None = ...,
     out: _ArrayT = ...,
 ) -> _ArrayT: ...
 @overload
@@ -1147,8 +1147,8 @@ def busday_offset(  # type: ignore[misc]
     offsets: _ScalarLike_co | dt.timedelta,
     roll: _RollKind,
     weekmask: ArrayLike = ...,
-    holidays: None | ArrayLike | dt.date | _NestedSequence[dt.date] = ...,
-    busdaycal: None | busdaycalendar = ...,
+    holidays: ArrayLike | dt.date | _NestedSequence[dt.date] | None = ...,
+    busdaycal: busdaycalendar | None = ...,
     out: None = ...,
 ) -> datetime64: ...
 @overload
@@ -1157,8 +1157,8 @@ def busday_offset(  # type: ignore[misc]
     offsets: ArrayLike | dt.timedelta | _NestedSequence[dt.timedelta],
     roll: _RollKind,
     weekmask: ArrayLike = ...,
-    holidays: None | ArrayLike | dt.date | _NestedSequence[dt.date] = ...,
-    busdaycal: None | busdaycalendar = ...,
+    holidays: ArrayLike | dt.date | _NestedSequence[dt.date] | None = ...,
+    busdaycal: busdaycalendar | None = ...,
     out: None = ...,
 ) -> NDArray[datetime64]: ...
 @overload
@@ -1167,8 +1167,8 @@ def busday_offset(
     offsets: ArrayLike | dt.timedelta | _NestedSequence[dt.timedelta],
     roll: _RollKind,
     weekmask: ArrayLike = ...,
-    holidays: None | ArrayLike | dt.date | _NestedSequence[dt.date] = ...,
-    busdaycal: None | busdaycalendar = ...,
+    holidays: ArrayLike | dt.date | _NestedSequence[dt.date] | None = ...,
+    busdaycal: busdaycalendar | None = ...,
     out: _ArrayT = ...,
 ) -> _ArrayT: ...
 
@@ -1176,38 +1176,38 @@ def busday_offset(
 def is_busday(  # type: ignore[misc]
     dates: _ScalarLike_co | dt.date,
     weekmask: ArrayLike = ...,
-    holidays: None | ArrayLike | dt.date | _NestedSequence[dt.date] = ...,
-    busdaycal: None | busdaycalendar = ...,
+    holidays: ArrayLike | dt.date | _NestedSequence[dt.date] | None = ...,
+    busdaycal: busdaycalendar | None = ...,
     out: None = ...,
 ) -> np.bool: ...
 @overload
 def is_busday(  # type: ignore[misc]
     dates: ArrayLike | _NestedSequence[dt.date],
     weekmask: ArrayLike = ...,
-    holidays: None | ArrayLike | dt.date | _NestedSequence[dt.date] = ...,
-    busdaycal: None | busdaycalendar = ...,
+    holidays: ArrayLike | dt.date | _NestedSequence[dt.date] | None = ...,
+    busdaycal: busdaycalendar | None = ...,
     out: None = ...,
 ) -> NDArray[np.bool]: ...
 @overload
 def is_busday(
     dates: ArrayLike | _NestedSequence[dt.date],
     weekmask: ArrayLike = ...,
-    holidays: None | ArrayLike | dt.date | _NestedSequence[dt.date] = ...,
-    busdaycal: None | busdaycalendar = ...,
+    holidays: ArrayLike | dt.date | _NestedSequence[dt.date] | None = ...,
+    busdaycal: busdaycalendar | None = ...,
     out: _ArrayT = ...,
 ) -> _ArrayT: ...
 
 @overload
 def datetime_as_string(  # type: ignore[misc]
     arr: datetime64 | dt.date,
-    unit: None | L["auto"] | _UnitKind = ...,
+    unit: L["auto"] | _UnitKind | None = ...,
     timezone: L["naive", "UTC", "local"] | dt.tzinfo = ...,
     casting: _CastingKind = ...,
 ) -> str_: ...
 @overload
 def datetime_as_string(
     arr: _ArrayLikeDT64_co | _NestedSequence[dt.date],
-    unit: None | L["auto"] | _UnitKind = ...,
+    unit: L["auto"] | _UnitKind | None = ...,
     timezone: L["naive", "UTC", "local"] | dt.tzinfo = ...,
     casting: _CastingKind = ...,
 ) -> NDArray[str_]: ...
@@ -1284,8 +1284,8 @@ class flagsobj:
 def nested_iters(
     op: ArrayLike | Sequence[ArrayLike],
     axes: Sequence[Sequence[SupportsIndex]],
-    flags: None | Sequence[_NDIterFlagsKind] = ...,
-    op_flags: None | Sequence[Sequence[_NDIterFlagsOp]] = ...,
+    flags: Sequence[_NDIterFlagsKind] | None = ...,
+    op_flags: Sequence[Sequence[_NDIterFlagsOp]] | None = ...,
     op_dtypes: DTypeLike | Sequence[DTypeLike] = ...,
     order: _OrderKACF = ...,
     casting: _CastingKind = ...,
diff --git a/numpy/_core/numeric.pyi b/numpy/_core/numeric.pyi
index 17093fcd5d99..0a0c70d80a50 100644
--- a/numpy/_core/numeric.pyi
+++ b/numpy/_core/numeric.pyi
@@ -192,7 +192,7 @@ def zeros_like(
     subok: L[True] = ...,
     shape: None = ...,
     *,
-    device: None | L["cpu"] = ...,
+    device: L["cpu"] | None = ...,
 ) -> _ArrayT: ...
 @overload
 def zeros_like(
@@ -200,9 +200,9 @@ def zeros_like(
     dtype: None = ...,
     order: _OrderKACF = ...,
     subok: bool = ...,
-    shape: None | _ShapeLike = ...,
+    shape: _ShapeLike | None = ...,
     *,
-    device: None | L["cpu"] = ...,
+    device: L["cpu"] | None = ...,
 ) -> NDArray[_ScalarT]: ...
 @overload
 def zeros_like(
@@ -210,9 +210,9 @@ def zeros_like(
     dtype: _DTypeLike[_ScalarT],
     order: _OrderKACF = ...,
     subok: bool = ...,
-    shape: None | _ShapeLike = ...,
+    shape: _ShapeLike | None = ...,
     *,
-    device: None | L["cpu"] = ...,
+    device: L["cpu"] | None = ...,
 ) -> NDArray[_ScalarT]: ...
 @overload
 def zeros_like(
@@ -220,9 +220,9 @@ def zeros_like(
     dtype: DTypeLike | None = ...,
     order: _OrderKACF = ...,
     subok: bool = ...,
-    shape: None | _ShapeLike = ...,
+    shape: _ShapeLike | None = ...,
     *,
-    device: None | L["cpu"] = ...,
+    device: L["cpu"] | None = ...,
 ) -> NDArray[Any]: ...
 
 ones: Final[_ConstructorEmpty]
@@ -235,7 +235,7 @@ def ones_like(
     subok: L[True] = ...,
     shape: None = ...,
     *,
-    device: None | L["cpu"] = ...,
+    device: L["cpu"] | None = ...,
 ) -> _ArrayT: ...
 @overload
 def ones_like(
@@ -243,9 +243,9 @@ def ones_like(
     dtype: None = ...,
     order: _OrderKACF = ...,
     subok: bool = ...,
-    shape: None | _ShapeLike = ...,
+    shape: _ShapeLike | None = ...,
     *,
-    device: None | L["cpu"] = ...,
+    device: L["cpu"] | None = ...,
 ) -> NDArray[_ScalarT]: ...
 @overload
 def ones_like(
@@ -253,9 +253,9 @@ def ones_like(
     dtype: _DTypeLike[_ScalarT],
     order: _OrderKACF = ...,
     subok: bool = ...,
-    shape: None | _ShapeLike = ...,
+    shape: _ShapeLike | None = ...,
     *,
-    device: None | L["cpu"] = ...,
+    device: L["cpu"] | None = ...,
 ) -> NDArray[_ScalarT]: ...
 @overload
 def ones_like(
@@ -263,9 +263,9 @@ def ones_like(
     dtype: DTypeLike | None = ...,
     order: _OrderKACF = ...,
     subok: bool = ...,
-    shape: None | _ShapeLike = ...,
+    shape: _ShapeLike | None = ...,
     *,
-    device: None | L["cpu"] = ...,
+    device: L["cpu"] | None = ...,
 ) -> NDArray[Any]: ...
 
 # TODO: Add overloads for bool, int, float, complex, str, bytes, and memoryview
@@ -298,7 +298,7 @@ def full(
 def full(
     shape: SupportsIndex,
     fill_value: Any,
-    dtype: None | DTypeLike = ...,
+    dtype: DTypeLike | None = ...,
     order: _OrderCF = ...,
     **kwargs: Unpack[_KwargsEmpty],
 ) -> _Array[tuple[int], Any]: ...
@@ -331,7 +331,7 @@ def full(
 def full(
     shape: _AnyShapeT,
     fill_value: Any,
-    dtype: None | DTypeLike = ...,
+    dtype: DTypeLike | None = ...,
     order: _OrderCF = ...,
     **kwargs: Unpack[_KwargsEmpty],
 ) -> _Array[_AnyShapeT, Any]: ...
@@ -364,7 +364,7 @@ def full(
 def full(
     shape: _ShapeLike,
     fill_value: Any,
-    dtype: None | DTypeLike = ...,
+    dtype: DTypeLike | None = ...,
     order: _OrderCF = ...,
     **kwargs: Unpack[_KwargsEmpty],
 ) -> NDArray[Any]: ...
@@ -378,7 +378,7 @@ def full_like(
     subok: L[True] = ...,
     shape: None = ...,
     *,
-    device: None | L["cpu"] = ...,
+    device: L["cpu"] | None = ...,
 ) -> _ArrayT: ...
 @overload
 def full_like(
@@ -387,9 +387,9 @@ def full_like(
     dtype: None = ...,
     order: _OrderKACF = ...,
     subok: bool = ...,
-    shape: None | _ShapeLike = ...,
+    shape: _ShapeLike | None = ...,
     *,
-    device: None | L["cpu"] = ...,
+    device: L["cpu"] | None = ...,
 ) -> NDArray[_ScalarT]: ...
 @overload
 def full_like(
@@ -398,9 +398,9 @@ def full_like(
     dtype: _DTypeLike[_ScalarT],
     order: _OrderKACF = ...,
     subok: bool = ...,
-    shape: None | _ShapeLike = ...,
+    shape: _ShapeLike | None = ...,
     *,
-    device: None | L["cpu"] = ...,
+    device: L["cpu"] | None = ...,
 ) -> NDArray[_ScalarT]: ...
 @overload
 def full_like(
@@ -409,9 +409,9 @@ def full_like(
     dtype: DTypeLike | None = ...,
     order: _OrderKACF = ...,
     subok: bool = ...,
-    shape: None | _ShapeLike = ...,
+    shape: _ShapeLike | None = ...,
     *,
-    device: None | L["cpu"] = ...,
+    device: L["cpu"] | None = ...,
 ) -> NDArray[Any]: ...
 
 #
@@ -639,13 +639,13 @@ def tensordot(
 def roll(
     a: _ArrayLike[_ScalarT],
     shift: _ShapeLike,
-    axis: None | _ShapeLike = ...,
+    axis: _ShapeLike | None = ...,
 ) -> NDArray[_ScalarT]: ...
 @overload
 def roll(
     a: ArrayLike,
     shift: _ShapeLike,
-    axis: None | _ShapeLike = ...,
+    axis: _ShapeLike | None = ...,
 ) -> NDArray[Any]: ...
 
 def rollaxis(
@@ -667,7 +667,7 @@ def cross(
     axisa: int = ...,
     axisb: int = ...,
     axisc: int = ...,
-    axis: None | int = ...,
+    axis: int | None = ...,
 ) -> NDArray[Any]: ...
 @overload
 def cross(
@@ -676,7 +676,7 @@ def cross(
     axisa: int = ...,
     axisb: int = ...,
     axisc: int = ...,
-    axis: None | int = ...,
+    axis: int | None = ...,
 ) -> NoReturn: ...
 @overload
 def cross(
@@ -685,7 +685,7 @@ def cross(
     axisa: int = ...,
     axisb: int = ...,
     axisc: int = ...,
-    axis: None | int = ...,
+    axis: int | None = ...,
 ) -> NDArray[unsignedinteger[Any]]: ...
 @overload
 def cross(
@@ -694,7 +694,7 @@ def cross(
     axisa: int = ...,
     axisb: int = ...,
     axisc: int = ...,
-    axis: None | int = ...,
+    axis: int | None = ...,
 ) -> NDArray[signedinteger[Any]]: ...
 @overload
 def cross(
@@ -703,7 +703,7 @@ def cross(
     axisa: int = ...,
     axisb: int = ...,
     axisc: int = ...,
-    axis: None | int = ...,
+    axis: int | None = ...,
 ) -> NDArray[floating[Any]]: ...
 @overload
 def cross(
@@ -712,7 +712,7 @@ def cross(
     axisa: int = ...,
     axisb: int = ...,
     axisc: int = ...,
-    axis: None | int = ...,
+    axis: int | None = ...,
 ) -> NDArray[complexfloating[Any, Any]]: ...
 @overload
 def cross(
@@ -721,7 +721,7 @@ def cross(
     axisa: int = ...,
     axisb: int = ...,
     axisc: int = ...,
-    axis: None | int = ...,
+    axis: int | None = ...,
 ) -> NDArray[object_]: ...
 
 @overload
@@ -788,7 +788,7 @@ def isscalar(element: object) -> TypeGuard[
     generic | bool | int | float | complex | str | bytes | memoryview
 ]: ...
 
-def binary_repr(num: SupportsIndex, width: None | int = ...) -> str: ...
+def binary_repr(num: SupportsIndex, width: int | None = ...) -> str: ...
 
 def base_repr(
     number: SupportsAbs[float],
@@ -854,7 +854,7 @@ def astype(
     /,
     *,
     copy: bool = ...,
-    device: None | L["cpu"] = ...,
+    device: L["cpu"] | None = ...,
 ) -> ndarray[_ShapeT, dtype[_ScalarT]]: ...
 @overload
 def astype(
@@ -863,5 +863,5 @@ def astype(
     /,
     *,
     copy: bool = ...,
-    device: None | L["cpu"] = ...,
+    device: L["cpu"] | None = ...,
 ) -> ndarray[_ShapeT, dtype[Any]]: ...
diff --git a/numpy/_pytesttester.pyi b/numpy/_pytesttester.pyi
index f5db633fcd56..a12abb1c1a10 100644
--- a/numpy/_pytesttester.pyi
+++ b/numpy/_pytesttester.pyi
@@ -10,9 +10,9 @@ class PytestTester:
         self,
         label: L["fast", "full"] = ...,
         verbose: int = ...,
-        extra_argv: None | Iterable[str] = ...,
+        extra_argv: Iterable[str] | None = ...,
         doctests: L[False] = ...,
         coverage: bool = ...,
         durations: int = ...,
-        tests: None | Iterable[str] = ...,
+        tests: Iterable[str] | None = ...,
     ) -> bool: ...
diff --git a/numpy/_typing/_ufunc.pyi b/numpy/_typing/_ufunc.pyi
index cadbe6ce3e60..766cde1ad420 100644
--- a/numpy/_typing/_ufunc.pyi
+++ b/numpy/_typing/_ufunc.pyi
@@ -105,38 +105,38 @@ class _UFunc_Nin1_Nout1(ufunc, Generic[_NameType, _NTypes, _IDType]):  # type: i
         __x1: _ScalarLike_co,
         out: None = ...,
         *,
-        where: None | _ArrayLikeBool_co = ...,
+        where: _ArrayLikeBool_co | None = ...,
         casting: _CastingKind = ...,
         order: _OrderKACF = ...,
         dtype: DTypeLike = ...,
         subok: bool = ...,
-        signature: str | _2Tuple[None | str] = ...,
+        signature: str | _2Tuple[str | None] = ...,
     ) -> Any: ...
     @overload
     def __call__(
         self,
         __x1: ArrayLike,
-        out: None | NDArray[Any] | tuple[NDArray[Any]] = ...,
+        out: NDArray[Any] | tuple[NDArray[Any]] | None = ...,
         *,
-        where: None | _ArrayLikeBool_co = ...,
+        where: _ArrayLikeBool_co | None = ...,
         casting: _CastingKind = ...,
         order: _OrderKACF = ...,
         dtype: DTypeLike = ...,
         subok: bool = ...,
-        signature: str | _2Tuple[None | str] = ...,
+        signature: str | _2Tuple[str | None] = ...,
     ) -> NDArray[Any]: ...
     @overload
     def __call__(
         self,
         __x1: _SupportsArrayUFunc,
-        out: None | NDArray[Any] | tuple[NDArray[Any]] = ...,
+        out: NDArray[Any] | tuple[NDArray[Any]] | None = ...,
         *,
-        where: None | _ArrayLikeBool_co = ...,
+        where: _ArrayLikeBool_co | None = ...,
         casting: _CastingKind = ...,
         order: _OrderKACF = ...,
         dtype: DTypeLike = ...,
         subok: bool = ...,
-        signature: str | _2Tuple[None | str] = ...,
+        signature: str | _2Tuple[str | None] = ...,
     ) -> Any: ...
 
     def at(
@@ -237,9 +237,9 @@ class _UFunc_Nin2_Nout1(ufunc, Generic[_NameType, _NTypes, _IDType]):  # type: i
     def reduce(
         self,
         array: ArrayLike,
-        axis: None | _ShapeLike = ...,
+        axis: _ShapeLike | None = ...,
         dtype: DTypeLike = ...,
-        out: None | NDArray[Any] = ...,
+        out: NDArray[Any] | None = ...,
         keepdims: bool = ...,
         initial: Any = ...,
         where: _ArrayLikeBool_co = ...,
@@ -250,7 +250,7 @@ class _UFunc_Nin2_Nout1(ufunc, Generic[_NameType, _NTypes, _IDType]):  # type: i
         array: ArrayLike,
         axis: SupportsIndex = ...,
         dtype: DTypeLike = ...,
-        out: None | NDArray[Any] = ...,
+        out: NDArray[Any] | None = ...,
     ) -> NDArray[Any]: ...
 
     def reduceat(
@@ -259,7 +259,7 @@ class _UFunc_Nin2_Nout1(ufunc, Generic[_NameType, _NTypes, _IDType]):  # type: i
         indices: _ArrayLikeInt_co,
         axis: SupportsIndex = ...,
         dtype: DTypeLike = ...,
-        out: None | NDArray[Any] = ...,
+        out: NDArray[Any] | None = ...,
     ) -> NDArray[Any]: ...
 
     @overload  # (scalar, scalar) -> scalar
@@ -344,42 +344,42 @@ class _UFunc_Nin1_Nout2(ufunc, Generic[_NameType, _NTypes, _IDType]):  # type: i
         __out1: None = ...,
         __out2: None = ...,
         *,
-        where: None | _ArrayLikeBool_co = ...,
+        where: _ArrayLikeBool_co | None = ...,
         casting: _CastingKind = ...,
         order: _OrderKACF = ...,
         dtype: DTypeLike = ...,
         subok: bool = ...,
-        signature: str | _3Tuple[None | str] = ...,
+        signature: str | _3Tuple[str | None] = ...,
     ) -> _2Tuple[Any]: ...
     @overload
     def __call__(
         self,
         __x1: ArrayLike,
-        __out1: None | NDArray[Any] = ...,
-        __out2: None | NDArray[Any] = ...,
+        __out1: NDArray[Any] | None = ...,
+        __out2: NDArray[Any] | None = ...,
         *,
         out: _2Tuple[NDArray[Any]] = ...,
-        where: None | _ArrayLikeBool_co = ...,
+        where: _ArrayLikeBool_co | None = ...,
         casting: _CastingKind = ...,
         order: _OrderKACF = ...,
         dtype: DTypeLike = ...,
         subok: bool = ...,
-        signature: str | _3Tuple[None | str] = ...,
+        signature: str | _3Tuple[str | None] = ...,
     ) -> _2Tuple[NDArray[Any]]: ...
     @overload
     def __call__(
         self,
         __x1: _SupportsArrayUFunc,
-        __out1: None | NDArray[Any] = ...,
-        __out2: None | NDArray[Any] = ...,
+        __out1: NDArray[Any] | None = ...,
+        __out2: NDArray[Any] | None = ...,
         *,
         out: _2Tuple[NDArray[Any]] = ...,
-        where: None | _ArrayLikeBool_co = ...,
+        where: _ArrayLikeBool_co | None = ...,
         casting: _CastingKind = ...,
         order: _OrderKACF = ...,
         dtype: DTypeLike = ...,
         subok: bool = ...,
-        signature: str | _3Tuple[None | str] = ...,
+        signature: str | _3Tuple[str | None] = ...,
     ) -> _2Tuple[Any]: ...
 
     def at(self, *args, **kwargs) -> NoReturn: ...
@@ -415,28 +415,28 @@ class _UFunc_Nin2_Nout2(ufunc, Generic[_NameType, _NTypes, _IDType]):  # type: i
         __out1: None = ...,
         __out2: None = ...,
         *,
-        where: None | _ArrayLikeBool_co = ...,
+        where: _ArrayLikeBool_co | None = ...,
         casting: _CastingKind = ...,
         order: _OrderKACF = ...,
         dtype: DTypeLike = ...,
         subok: bool = ...,
-        signature: str | _4Tuple[None | str] = ...,
+        signature: str | _4Tuple[str | None] = ...,
     ) -> _2Tuple[Any]: ...
     @overload
     def __call__(
         self,
         __x1: ArrayLike,
         __x2: ArrayLike,
-        __out1: None | NDArray[Any] = ...,
-        __out2: None | NDArray[Any] = ...,
+        __out1: NDArray[Any] | None = ...,
+        __out2: NDArray[Any] | None = ...,
         *,
         out: _2Tuple[NDArray[Any]] = ...,
-        where: None | _ArrayLikeBool_co = ...,
+        where: _ArrayLikeBool_co | None = ...,
         casting: _CastingKind = ...,
         order: _OrderKACF = ...,
         dtype: DTypeLike = ...,
         subok: bool = ...,
-        signature: str | _4Tuple[None | str] = ...,
+        signature: str | _4Tuple[str | None] = ...,
     ) -> _2Tuple[NDArray[Any]]: ...
 
     def at(self, *args, **kwargs) -> NoReturn: ...
@@ -476,7 +476,7 @@ class _GUFunc_Nin2_Nout1(ufunc, Generic[_NameType, _NTypes, _IDType, _Signature]
         order: _OrderKACF = ...,
         dtype: DTypeLike = ...,
         subok: bool = ...,
-        signature: str | _3Tuple[None | str] = ...,
+        signature: str | _3Tuple[str | None] = ...,
         axes: list[_2Tuple[SupportsIndex]] = ...,
     ) -> Any: ...
     @overload
@@ -490,7 +490,7 @@ class _GUFunc_Nin2_Nout1(ufunc, Generic[_NameType, _NTypes, _IDType, _Signature]
         order: _OrderKACF = ...,
         dtype: DTypeLike = ...,
         subok: bool = ...,
-        signature: str | _3Tuple[None | str] = ...,
+        signature: str | _3Tuple[str | None] = ...,
         axes: list[_2Tuple[SupportsIndex]] = ...,
     ) -> NDArray[Any]: ...
 
@@ -502,7 +502,7 @@ class _GUFunc_Nin2_Nout1(ufunc, Generic[_NameType, _NTypes, _IDType, _Signature]
 
 @type_check_only
 class _PyFunc_Kwargs_Nargs2(TypedDict, total=False):
-    where: None | _ArrayLikeBool_co
+    where: _ArrayLikeBool_co | None
     casting: _CastingKind
     order: _OrderKACF
     dtype: DTypeLike
@@ -511,7 +511,7 @@ class _PyFunc_Kwargs_Nargs2(TypedDict, total=False):
 
 @type_check_only
 class _PyFunc_Kwargs_Nargs3(TypedDict, total=False):
-    where: None | _ArrayLikeBool_co
+    where: _ArrayLikeBool_co | None
     casting: _CastingKind
     order: _OrderKACF
     dtype: DTypeLike
@@ -520,7 +520,7 @@ class _PyFunc_Kwargs_Nargs3(TypedDict, total=False):
 
 @type_check_only
 class _PyFunc_Kwargs_Nargs3P(TypedDict, total=False):
-    where: None | _ArrayLikeBool_co
+    where: _ArrayLikeBool_co | None
     casting: _CastingKind
     order: _OrderKACF
     dtype: DTypeLike
@@ -529,7 +529,7 @@ class _PyFunc_Kwargs_Nargs3P(TypedDict, total=False):
 
 @type_check_only
 class _PyFunc_Kwargs_Nargs4P(TypedDict, total=False):
-    where: None | _ArrayLikeBool_co
+    where: _ArrayLikeBool_co | None
     casting: _CastingKind
     order: _OrderKACF
     dtype: DTypeLike
@@ -580,7 +580,7 @@ class _PyFunc_Nin1_Nout1(ufunc, Generic[_ReturnType_co, _IDType]):  # type: igno
         self,
         x1: _SupportsArrayUFunc,
         /,
-        out: None | NDArray[Any] | tuple[NDArray[Any]] = ...,
+        out: NDArray[Any] | tuple[NDArray[Any]] | None = ...,
         **kwargs: Unpack[_PyFunc_Kwargs_Nargs2],
     ) -> Any: ...
 
@@ -638,7 +638,7 @@ class _PyFunc_Nin2_Nout1(ufunc, Generic[_ReturnType_co, _IDType]):  # type: igno
         x1: _SupportsArrayUFunc,
         x2: _SupportsArrayUFunc | ArrayLike,
         /,
-        out: None | NDArray[Any] | tuple[NDArray[Any]] = ...,
+        out: NDArray[Any] | tuple[NDArray[Any]] | None = ...,
         **kwargs: Unpack[_PyFunc_Kwargs_Nargs3],
     ) -> Any: ...
     @overload
@@ -647,7 +647,7 @@ class _PyFunc_Nin2_Nout1(ufunc, Generic[_ReturnType_co, _IDType]):  # type: igno
         x1: ArrayLike,
         x2: _SupportsArrayUFunc,
         /,
-        out: None | NDArray[Any] | tuple[NDArray[Any]] = ...,
+        out: NDArray[Any] | tuple[NDArray[Any]] | None = ...,
         **kwargs: Unpack[_PyFunc_Kwargs_Nargs3],
     ) -> Any: ...
 
@@ -657,7 +657,7 @@ class _PyFunc_Nin2_Nout1(ufunc, Generic[_ReturnType_co, _IDType]):  # type: igno
     def reduce(
         self,
         array: ArrayLike,
-        axis: None | _ShapeLike,
+        axis: _ShapeLike | None,
         dtype: DTypeLike,
         out: _ArrayT,
         /,
@@ -670,7 +670,7 @@ class _PyFunc_Nin2_Nout1(ufunc, Generic[_ReturnType_co, _IDType]):  # type: igno
         self,
         /,
         array: ArrayLike,
-        axis: None | _ShapeLike = ...,
+        axis: _ShapeLike | None = ...,
         dtype: DTypeLike = ...,
         *,
         out: _ArrayT | tuple[_ArrayT],
@@ -683,7 +683,7 @@ class _PyFunc_Nin2_Nout1(ufunc, Generic[_ReturnType_co, _IDType]):  # type: igno
         self,
         /,
         array: ArrayLike,
-        axis: None | _ShapeLike = ...,
+        axis: _ShapeLike | None = ...,
         dtype: DTypeLike = ...,
         out: None = ...,
         *,
@@ -696,7 +696,7 @@ class _PyFunc_Nin2_Nout1(ufunc, Generic[_ReturnType_co, _IDType]):  # type: igno
         self,
         /,
         array: ArrayLike,
-        axis: None | _ShapeLike = ...,
+        axis: _ShapeLike | None = ...,
         dtype: DTypeLike = ...,
         out: None = ...,
         keepdims: bool = ...,
@@ -743,7 +743,7 @@ class _PyFunc_Nin2_Nout1(ufunc, Generic[_ReturnType_co, _IDType]):  # type: igno
         indices: _ArrayLikeInt_co,
         axis: SupportsIndex = ...,
         dtype: DTypeLike = ...,
-        out: None | NDArray[Any] | tuple[NDArray[Any]] = ...,
+        out: NDArray[Any] | tuple[NDArray[Any]] | None = ...,
     ) -> Any: ...
 
     @overload
@@ -874,7 +874,7 @@ class _PyFunc_Nin3P_Nout1(ufunc, Generic[_ReturnType_co, _IDType, _NIn]):  # typ
         x3: _SupportsArrayUFunc | ArrayLike,
         /,
         *xs: _SupportsArrayUFunc | ArrayLike,
-        out: None | NDArray[Any] | tuple[NDArray[Any]] = ...,
+        out: NDArray[Any] | tuple[NDArray[Any]] | None = ...,
         **kwargs: Unpack[_PyFunc_Kwargs_Nargs4P],
     ) -> Any: ...
 
@@ -930,7 +930,7 @@ class _PyFunc_Nin1P_Nout2P(ufunc, Generic[_ReturnType_co, _IDType, _NIn, _NOut])
         x1: _SupportsArrayUFunc | ArrayLike,
         /,
         *xs: _SupportsArrayUFunc | ArrayLike,
-        out: None | _2PTuple[NDArray[Any]] = ...,
+        out: _2PTuple[NDArray[Any]] | None = ...,
         **kwargs: Unpack[_PyFunc_Kwargs_Nargs3P],
     ) -> Any: ...
 
diff --git a/numpy/ctypeslib/_ctypeslib.pyi b/numpy/ctypeslib/_ctypeslib.pyi
index b199d855acec..ebb0fbc4677a 100644
--- a/numpy/ctypeslib/_ctypeslib.pyi
+++ b/numpy/ctypeslib/_ctypeslib.pyi
@@ -70,7 +70,7 @@ __all__ = ["load_library", "ndpointer", "c_intp", "as_ctypes", "as_array", "as_c
 
 # TODO: Add a proper `_Shape` bound once we've got variadic typevars
 _DTypeT = TypeVar("_DTypeT", bound=dtype[Any])
-_DTypeOptionalT = TypeVar("_DTypeOptionalT", bound=None | dtype[Any])
+_DTypeOptionalT = TypeVar("_DTypeOptionalT", bound=dtype[Any] | None)
 _ScalarT = TypeVar("_ScalarT", bound=generic)
 
 _FlagsKind: TypeAlias = L[
@@ -88,8 +88,8 @@ class _ndptr(ctypes.c_void_p, Generic[_DTypeOptionalT]):
     # returned by `ndpointer`
     _dtype_: ClassVar[_DTypeOptionalT]
     _shape_: ClassVar[None]
-    _ndim_: ClassVar[None | int]
-    _flags_: ClassVar[None | list[_FlagsKind]]
+    _ndim_: ClassVar[int | None]
+    _flags_: ClassVar[list[_FlagsKind] | None]
 
     @overload
     @classmethod
@@ -112,8 +112,8 @@ c_intp = _c_intp
 def ndpointer(
     dtype: None = ...,
     ndim: int = ...,
-    shape: None | _ShapeLike = ...,
-    flags: None | _FlagsKind | Iterable[_FlagsKind] | int | flagsobj = ...,
+    shape: _ShapeLike | None = ...,
+    flags: _FlagsKind | Iterable[_FlagsKind] | int | flagsobj | None = ...,
 ) -> type[_ndptr[None]]: ...
 @overload
 def ndpointer(
@@ -121,7 +121,7 @@ def ndpointer(
     ndim: int = ...,
     *,
     shape: _ShapeLike,
-    flags: None | _FlagsKind | Iterable[_FlagsKind] | int | flagsobj = ...,
+    flags: _FlagsKind | Iterable[_FlagsKind] | int | flagsobj | None = ...,
 ) -> type[_concrete_ndptr[dtype[_ScalarT]]]: ...
 @overload
 def ndpointer(
@@ -129,21 +129,21 @@ def ndpointer(
     ndim: int = ...,
     *,
     shape: _ShapeLike,
-    flags: None | _FlagsKind | Iterable[_FlagsKind] | int | flagsobj = ...,
+    flags: _FlagsKind | Iterable[_FlagsKind] | int | flagsobj | None = ...,
 ) -> type[_concrete_ndptr[dtype[Any]]]: ...
 @overload
 def ndpointer(
     dtype: _DTypeLike[_ScalarT],
     ndim: int = ...,
     shape: None = ...,
-    flags: None | _FlagsKind | Iterable[_FlagsKind] | int | flagsobj = ...,
+    flags: _FlagsKind | Iterable[_FlagsKind] | int | flagsobj | None = ...,
 ) -> type[_ndptr[dtype[_ScalarT]]]: ...
 @overload
 def ndpointer(
     dtype: DTypeLike,
     ndim: int = ...,
     shape: None = ...,
-    flags: None | _FlagsKind | Iterable[_FlagsKind] | int | flagsobj = ...,
+    flags: _FlagsKind | Iterable[_FlagsKind] | int | flagsobj | None = ...,
 ) -> type[_ndptr[dtype[Any]]]: ...
 
 @overload
@@ -184,9 +184,9 @@ def as_ctypes_type(dtype: str) -> type[Any]: ...
 @overload
 def as_array(obj: ctypes._PointerLike, shape: Sequence[int]) -> NDArray[Any]: ...
 @overload
-def as_array(obj: _ArrayLike[_ScalarT], shape: None | _ShapeLike = ...) -> NDArray[_ScalarT]: ...
+def as_array(obj: _ArrayLike[_ScalarT], shape: _ShapeLike | None = ...) -> NDArray[_ScalarT]: ...
 @overload
-def as_array(obj: object, shape: None | _ShapeLike = ...) -> NDArray[Any]: ...
+def as_array(obj: object, shape: _ShapeLike | None = ...) -> NDArray[Any]: ...
 
 @overload
 def as_ctypes(obj: np.bool) -> ctypes.c_bool: ...
diff --git a/numpy/exceptions.pyi b/numpy/exceptions.pyi
index 7caa96c4673c..9ed50927d070 100644
--- a/numpy/exceptions.pyi
+++ b/numpy/exceptions.pyi
@@ -17,9 +17,9 @@ class TooHardError(RuntimeError): ...
 class DTypePromotionError(TypeError): ...
 
 class AxisError(ValueError, IndexError):
-    axis: None | int
-    ndim: None | int
+    axis: int | None
+    ndim: int | None
     @overload
     def __init__(self, axis: str, ndim: None = ..., msg_prefix: None = ...) -> None: ...
     @overload
-    def __init__(self, axis: int, ndim: int, msg_prefix: None | str = ...) -> None: ...
+    def __init__(self, axis: int, ndim: int, msg_prefix: str | None = ...) -> None: ...
diff --git a/numpy/fft/_pocketfft.pyi b/numpy/fft/_pocketfft.pyi
index 2fdfa816b5fb..4f5e5c944b4c 100644
--- a/numpy/fft/_pocketfft.pyi
+++ b/numpy/fft/_pocketfft.pyi
@@ -25,113 +25,113 @@ _NormKind: TypeAlias = L["backward", "ortho", "forward"] | None
 
 def fft(
     a: ArrayLike,
-    n: None | int = ...,
+    n: int | None = ...,
     axis: int = ...,
     norm: _NormKind = ...,
-    out: None | NDArray[complex128] = ...,
+    out: NDArray[complex128] | None = ...,
 ) -> NDArray[complex128]: ...
 
 def ifft(
     a: ArrayLike,
-    n: None | int = ...,
+    n: int | None = ...,
     axis: int = ...,
     norm: _NormKind = ...,
-    out: None | NDArray[complex128] = ...,
+    out: NDArray[complex128] | None = ...,
 ) -> NDArray[complex128]: ...
 
 def rfft(
     a: ArrayLike,
-    n: None | int = ...,
+    n: int | None = ...,
     axis: int = ...,
     norm: _NormKind = ...,
-    out: None | NDArray[complex128] = ...,
+    out: NDArray[complex128] | None = ...,
 ) -> NDArray[complex128]: ...
 
 def irfft(
     a: ArrayLike,
-    n: None | int = ...,
+    n: int | None = ...,
     axis: int = ...,
     norm: _NormKind = ...,
-    out: None | NDArray[float64] = ...,
+    out: NDArray[float64] | None = ...,
 ) -> NDArray[float64]: ...
 
 # Input array must be compatible with `np.conjugate`
 def hfft(
     a: _ArrayLikeNumber_co,
-    n: None | int = ...,
+    n: int | None = ...,
     axis: int = ...,
     norm: _NormKind = ...,
-    out: None | NDArray[float64] = ...,
+    out: NDArray[float64] | None = ...,
 ) -> NDArray[float64]: ...
 
 def ihfft(
     a: ArrayLike,
-    n: None | int = ...,
+    n: int | None = ...,
     axis: int = ...,
     norm: _NormKind = ...,
-    out: None | NDArray[complex128] = ...,
+    out: NDArray[complex128] | None = ...,
 ) -> NDArray[complex128]: ...
 
 def fftn(
     a: ArrayLike,
-    s: None | Sequence[int] = ...,
-    axes: None | Sequence[int] = ...,
+    s: Sequence[int] | None = ...,
+    axes: Sequence[int] | None = ...,
     norm: _NormKind = ...,
-    out: None | NDArray[complex128] = ...,
+    out: NDArray[complex128] | None = ...,
 ) -> NDArray[complex128]: ...
 
 def ifftn(
     a: ArrayLike,
-    s: None | Sequence[int] = ...,
-    axes: None | Sequence[int] = ...,
+    s: Sequence[int] | None = ...,
+    axes: Sequence[int] | None = ...,
     norm: _NormKind = ...,
-    out: None | NDArray[complex128] = ...,
+    out: NDArray[complex128] | None = ...,
 ) -> NDArray[complex128]: ...
 
 def rfftn(
     a: ArrayLike,
-    s: None | Sequence[int] = ...,
-    axes: None | Sequence[int] = ...,
+    s: Sequence[int] | None = ...,
+    axes: Sequence[int] | None = ...,
     norm: _NormKind = ...,
-    out: None | NDArray[complex128] = ...,
+    out: NDArray[complex128] | None = ...,
 ) -> NDArray[complex128]: ...
 
 def irfftn(
     a: ArrayLike,
-    s: None | Sequence[int] = ...,
-    axes: None | Sequence[int] = ...,
+    s: Sequence[int] | None = ...,
+    axes: Sequence[int] | None = ...,
     norm: _NormKind = ...,
-    out: None | NDArray[float64] = ...,
+    out: NDArray[float64] | None = ...,
 ) -> NDArray[float64]: ...
 
 def fft2(
     a: ArrayLike,
-    s: None | Sequence[int] = ...,
-    axes: None | Sequence[int] = ...,
+    s: Sequence[int] | None = ...,
+    axes: Sequence[int] | None = ...,
     norm: _NormKind = ...,
-    out: None | NDArray[complex128] = ...,
+    out: NDArray[complex128] | None = ...,
 ) -> NDArray[complex128]: ...
 
 def ifft2(
     a: ArrayLike,
-    s: None | Sequence[int] = ...,
-    axes: None | Sequence[int] = ...,
+    s: Sequence[int] | None = ...,
+    axes: Sequence[int] | None = ...,
     norm: _NormKind = ...,
-    out: None | NDArray[complex128] = ...,
+    out: NDArray[complex128] | None = ...,
 ) -> NDArray[complex128]: ...
 
 def rfft2(
     a: ArrayLike,
-    s: None | Sequence[int] = ...,
-    axes: None | Sequence[int] = ...,
+    s: Sequence[int] | None = ...,
+    axes: Sequence[int] | None = ...,
     norm: _NormKind = ...,
-    out: None | NDArray[complex128] = ...,
+    out: NDArray[complex128] | None = ...,
 ) -> NDArray[complex128]: ...
 
 def irfft2(
     a: ArrayLike,
-    s: None | Sequence[int] = ...,
-    axes: None | Sequence[int] = ...,
+    s: Sequence[int] | None = ...,
+    axes: Sequence[int] | None = ...,
     norm: _NormKind = ...,
-    out: None | NDArray[float64] = ...,
+    out: NDArray[float64] | None = ...,
 ) -> NDArray[float64]: ...
diff --git a/numpy/lib/_array_utils_impl.pyi b/numpy/lib/_array_utils_impl.pyi
index 32dda28f34ed..a70de058bf8e 100644
--- a/numpy/lib/_array_utils_impl.pyi
+++ b/numpy/lib/_array_utils_impl.pyi
@@ -15,12 +15,12 @@ def byte_bounds(a: generic | NDArray[Any]) -> tuple[int, int]: ...
 def normalize_axis_tuple(
     axis: int | Iterable[int],
     ndim: int = ...,
-    argname: None | str = ...,
-    allow_duplicate: None | bool = ...,
+    argname: str | None = ...,
+    allow_duplicate: bool | None = ...,
 ) -> tuple[int, int]: ...
 
 def normalize_axis_index(
     axis: int = ...,
     ndim: int = ...,
-    msg_prefix: None | str = ...,
+    msg_prefix: str | None = ...,
 ) -> int: ...
diff --git a/numpy/lib/_arraypad_impl.pyi b/numpy/lib/_arraypad_impl.pyi
index bb9b3e82c028..d82495c3d934 100644
--- a/numpy/lib/_arraypad_impl.pyi
+++ b/numpy/lib/_arraypad_impl.pyi
@@ -56,7 +56,7 @@ def pad(
     pad_width: _ArrayLikeInt,
     mode: _ModeKind = ...,
     *,
-    stat_length: None | _ArrayLikeInt = ...,
+    stat_length: _ArrayLikeInt | None = ...,
     constant_values: ArrayLike = ...,
     end_values: ArrayLike = ...,
     reflect_type: L["odd", "even"] = ...,
@@ -67,7 +67,7 @@ def pad(
     pad_width: _ArrayLikeInt,
     mode: _ModeKind = ...,
     *,
-    stat_length: None | _ArrayLikeInt = ...,
+    stat_length: _ArrayLikeInt | None = ...,
     constant_values: ArrayLike = ...,
     end_values: ArrayLike = ...,
     reflect_type: L["odd", "even"] = ...,
diff --git a/numpy/lib/_function_base_impl.pyi b/numpy/lib/_function_base_impl.pyi
index 88f27f9589b9..55010ad6e5fd 100644
--- a/numpy/lib/_function_base_impl.pyi
+++ b/numpy/lib/_function_base_impl.pyi
@@ -138,9 +138,9 @@ def flip(m: _ScalarT, axis: None = ...) -> _ScalarT: ...
 @overload
 def flip(m: _ScalarLike_co, axis: None = ...) -> Any: ...
 @overload
-def flip(m: _ArrayLike[_ScalarT], axis: None | _ShapeLike = ...) -> NDArray[_ScalarT]: ...
+def flip(m: _ArrayLike[_ScalarT], axis: _ShapeLike | None = ...) -> NDArray[_ScalarT]: ...
 @overload
-def flip(m: ArrayLike, axis: None | _ShapeLike = ...) -> NDArray[Any]: ...
+def flip(m: ArrayLike, axis: _ShapeLike | None = ...) -> NDArray[Any]: ...
 
 def iterable(y: object) -> TypeIs[Iterable[Any]]: ...
 
@@ -284,7 +284,7 @@ def copy(
 def gradient(
     f: ArrayLike,
     *varargs: ArrayLike,
-    axis: None | _ShapeLike = ...,
+    axis: _ShapeLike | None = ...,
     edge_order: L[1, 2] = ...,
 ) -> Any: ...
 
@@ -399,7 +399,7 @@ def angle(z: _ArrayLikeObject_co, deg: bool = ...) -> NDArray[object_]: ...
 @overload
 def unwrap(
     p: _ArrayLikeFloat_co,
-    discont: None | float = ...,
+    discont: float | None = ...,
     axis: int = ...,
     *,
     period: float = ...,
@@ -407,7 +407,7 @@ def unwrap(
 @overload
 def unwrap(
     p: _ArrayLikeObject_co,
-    discont: None | float = ...,
+    discont: float | None = ...,
     axis: int = ...,
     *,
     period: float = ...,
@@ -430,48 +430,48 @@ def place(arr: NDArray[Any], mask: ArrayLike, vals: Any) -> None: ...
 @overload
 def cov(
     m: _ArrayLikeFloat_co,
-    y: None | _ArrayLikeFloat_co = ...,
+    y: _ArrayLikeFloat_co | None = ...,
     rowvar: bool = ...,
     bias: bool = ...,
-    ddof: None | SupportsIndex | SupportsInt = ...,
-    fweights: None | ArrayLike = ...,
-    aweights: None | ArrayLike = ...,
+    ddof: SupportsIndex | SupportsInt | None = ...,
+    fweights: ArrayLike | None = ...,
+    aweights: ArrayLike | None = ...,
     *,
     dtype: None = ...,
 ) -> NDArray[floating[Any]]: ...
 @overload
 def cov(
     m: _ArrayLikeComplex_co,
-    y: None | _ArrayLikeComplex_co = ...,
+    y: _ArrayLikeComplex_co | None = ...,
     rowvar: bool = ...,
     bias: bool = ...,
-    ddof: None | SupportsIndex | SupportsInt = ...,
-    fweights: None | ArrayLike = ...,
-    aweights: None | ArrayLike = ...,
+    ddof: SupportsIndex | SupportsInt | None = ...,
+    fweights: ArrayLike | None = ...,
+    aweights: ArrayLike | None = ...,
     *,
     dtype: None = ...,
 ) -> NDArray[complexfloating[Any, Any]]: ...
 @overload
 def cov(
     m: _ArrayLikeComplex_co,
-    y: None | _ArrayLikeComplex_co = ...,
+    y: _ArrayLikeComplex_co | None = ...,
     rowvar: bool = ...,
     bias: bool = ...,
-    ddof: None | SupportsIndex | SupportsInt = ...,
-    fweights: None | ArrayLike = ...,
-    aweights: None | ArrayLike = ...,
+    ddof: SupportsIndex | SupportsInt | None = ...,
+    fweights: ArrayLike | None = ...,
+    aweights: ArrayLike | None = ...,
     *,
     dtype: _DTypeLike[_ScalarT],
 ) -> NDArray[_ScalarT]: ...
 @overload
 def cov(
     m: _ArrayLikeComplex_co,
-    y: None | _ArrayLikeComplex_co = ...,
+    y: _ArrayLikeComplex_co | None = ...,
     rowvar: bool = ...,
     bias: bool = ...,
-    ddof: None | SupportsIndex | SupportsInt = ...,
-    fweights: None | ArrayLike = ...,
-    aweights: None | ArrayLike = ...,
+    ddof: SupportsIndex | SupportsInt | None = ...,
+    fweights: ArrayLike | None = ...,
+    aweights: ArrayLike | None = ...,
     *,
     dtype: DTypeLike,
 ) -> NDArray[Any]: ...
@@ -577,7 +577,7 @@ def median(
 @overload
 def median(
     a: _ArrayLikeFloat_co | _ArrayLikeComplex_co | _ArrayLikeTD64_co | _ArrayLikeObject_co,
-    axis: None | _ShapeLike = ...,
+    axis: _ShapeLike | None = ...,
     out: None = ...,
     overwrite_input: bool = ...,
     keepdims: bool = ...,
@@ -585,7 +585,7 @@ def median(
 @overload
 def median(
     a: _ArrayLikeFloat_co | _ArrayLikeComplex_co | _ArrayLikeTD64_co | _ArrayLikeObject_co,
-    axis: None | _ShapeLike,
+    axis: _ShapeLike | None,
     out: _ArrayT,
     overwrite_input: bool = ...,
     keepdims: bool = ...,
@@ -593,7 +593,7 @@ def median(
 @overload
 def median(
     a: _ArrayLikeFloat_co | _ArrayLikeComplex_co | _ArrayLikeTD64_co | _ArrayLikeObject_co,
-    axis: None | _ShapeLike = ...,
+    axis: _ShapeLike | None = ...,
     *,
     out: _ArrayT,
     overwrite_input: bool = ...,
@@ -626,7 +626,7 @@ def percentile(
     method: _MethodKind = ...,
     keepdims: L[False] = ...,
     *,
-    weights: None | _ArrayLikeFloat_co = ...,
+    weights: _ArrayLikeFloat_co | None = ...,
 ) -> floating[Any]: ...
 @overload
 def percentile(
@@ -638,7 +638,7 @@ def percentile(
     method: _MethodKind = ...,
     keepdims: L[False] = ...,
     *,
-    weights: None | _ArrayLikeFloat_co = ...,
+    weights: _ArrayLikeFloat_co | None = ...,
 ) -> complexfloating[Any, Any]: ...
 @overload
 def percentile(
@@ -650,7 +650,7 @@ def percentile(
     method: _MethodKind = ...,
     keepdims: L[False] = ...,
     *,
-    weights: None | _ArrayLikeFloat_co = ...,
+    weights: _ArrayLikeFloat_co | None = ...,
 ) -> timedelta64: ...
 @overload
 def percentile(
@@ -662,7 +662,7 @@ def percentile(
     method: _MethodKind = ...,
     keepdims: L[False] = ...,
     *,
-    weights: None | _ArrayLikeFloat_co = ...,
+    weights: _ArrayLikeFloat_co | None = ...,
 ) -> datetime64: ...
 @overload
 def percentile(
@@ -674,7 +674,7 @@ def percentile(
     method: _MethodKind = ...,
     keepdims: L[False] = ...,
     *,
-    weights: None | _ArrayLikeFloat_co = ...,
+    weights: _ArrayLikeFloat_co | None = ...,
 ) -> Any: ...
 @overload
 def percentile(
@@ -686,7 +686,7 @@ def percentile(
     method: _MethodKind = ...,
     keepdims: L[False] = ...,
     *,
-    weights: None | _ArrayLikeFloat_co = ...,
+    weights: _ArrayLikeFloat_co | None = ...,
 ) -> NDArray[floating[Any]]: ...
 @overload
 def percentile(
@@ -698,7 +698,7 @@ def percentile(
     method: _MethodKind = ...,
     keepdims: L[False] = ...,
     *,
-    weights: None | _ArrayLikeFloat_co = ...,
+    weights: _ArrayLikeFloat_co | None = ...,
 ) -> NDArray[complexfloating[Any, Any]]: ...
 @overload
 def percentile(
@@ -710,7 +710,7 @@ def percentile(
     method: _MethodKind = ...,
     keepdims: L[False] = ...,
     *,
-    weights: None | _ArrayLikeFloat_co = ...,
+    weights: _ArrayLikeFloat_co | None = ...,
 ) -> NDArray[timedelta64]: ...
 @overload
 def percentile(
@@ -722,7 +722,7 @@ def percentile(
     method: _MethodKind = ...,
     keepdims: L[False] = ...,
     *,
-    weights: None | _ArrayLikeFloat_co = ...,
+    weights: _ArrayLikeFloat_co | None = ...,
 ) -> NDArray[datetime64]: ...
 @overload
 def percentile(
@@ -734,43 +734,43 @@ def percentile(
     method: _MethodKind = ...,
     keepdims: L[False] = ...,
     *,
-    weights: None | _ArrayLikeFloat_co = ...,
+    weights: _ArrayLikeFloat_co | None = ...,
 ) -> NDArray[object_]: ...
 @overload
 def percentile(
     a: _ArrayLikeComplex_co | _ArrayLikeTD64_co | _ArrayLikeDT64_co | _ArrayLikeObject_co,
     q: _ArrayLikeFloat_co,
-    axis: None | _ShapeLike = ...,
+    axis: _ShapeLike | None = ...,
     out: None = ...,
     overwrite_input: bool = ...,
     method: _MethodKind = ...,
     keepdims: bool = ...,
     *,
-    weights: None | _ArrayLikeFloat_co = ...,
+    weights: _ArrayLikeFloat_co | None = ...,
 ) -> Any: ...
 @overload
 def percentile(
     a: _ArrayLikeComplex_co | _ArrayLikeTD64_co | _ArrayLikeDT64_co | _ArrayLikeObject_co,
     q: _ArrayLikeFloat_co,
-    axis: None | _ShapeLike,
+    axis: _ShapeLike | None,
     out: _ArrayT,
     overwrite_input: bool = ...,
     method: _MethodKind = ...,
     keepdims: bool = ...,
     *,
-    weights: None | _ArrayLikeFloat_co = ...,
+    weights: _ArrayLikeFloat_co | None = ...,
 ) -> _ArrayT: ...
 @overload
 def percentile(
     a: _ArrayLikeComplex_co | _ArrayLikeTD64_co | _ArrayLikeDT64_co | _ArrayLikeObject_co,
     q: _ArrayLikeFloat_co,
-    axis: None | _ShapeLike = ...,
+    axis: _ShapeLike | None = ...,
     *,
     out: _ArrayT,
     overwrite_input: bool = ...,
     method: _MethodKind = ...,
     keepdims: bool = ...,
-    weights: None | _ArrayLikeFloat_co = ...,
+    weights: _ArrayLikeFloat_co | None = ...,
 ) -> _ArrayT: ...
 
 # NOTE: Not an alias, but they do have identical signatures
@@ -941,13 +941,13 @@ def meshgrid(
 def delete(
     arr: _ArrayLike[_ScalarT],
     obj: slice | _ArrayLikeInt_co,
-    axis: None | SupportsIndex = ...,
+    axis: SupportsIndex | None = ...,
 ) -> NDArray[_ScalarT]: ...
 @overload
 def delete(
     arr: ArrayLike,
     obj: slice | _ArrayLikeInt_co,
-    axis: None | SupportsIndex = ...,
+    axis: SupportsIndex | None = ...,
 ) -> NDArray[Any]: ...
 
 @overload
@@ -955,20 +955,20 @@ def insert(
     arr: _ArrayLike[_ScalarT],
     obj: slice | _ArrayLikeInt_co,
     values: ArrayLike,
-    axis: None | SupportsIndex = ...,
+    axis: SupportsIndex | None = ...,
 ) -> NDArray[_ScalarT]: ...
 @overload
 def insert(
     arr: ArrayLike,
     obj: slice | _ArrayLikeInt_co,
     values: ArrayLike,
-    axis: None | SupportsIndex = ...,
+    axis: SupportsIndex | None = ...,
 ) -> NDArray[Any]: ...
 
 def append(
     arr: ArrayLike,
     values: ArrayLike,
-    axis: None | SupportsIndex = ...,
+    axis: SupportsIndex | None = ...,
 ) -> NDArray[Any]: ...
 
 @overload
diff --git a/numpy/lib/_histograms_impl.pyi b/numpy/lib/_histograms_impl.pyi
index e18ab99035b4..e91bf2531366 100644
--- a/numpy/lib/_histograms_impl.pyi
+++ b/numpy/lib/_histograms_impl.pyi
@@ -27,22 +27,22 @@ _BinKind: TypeAlias = L[
 def histogram_bin_edges(
     a: ArrayLike,
     bins: _BinKind | SupportsIndex | ArrayLike = ...,
-    range: None | tuple[float, float] = ...,
-    weights: None | ArrayLike = ...,
+    range: tuple[float, float] | None = ...,
+    weights: ArrayLike | None = ...,
 ) -> NDArray[Any]: ...
 
 def histogram(
     a: ArrayLike,
     bins: _BinKind | SupportsIndex | ArrayLike = ...,
-    range: None | tuple[float, float] = ...,
+    range: tuple[float, float] | None = ...,
     density: bool = ...,
-    weights: None | ArrayLike = ...,
+    weights: ArrayLike | None = ...,
 ) -> tuple[NDArray[Any], NDArray[Any]]: ...
 
 def histogramdd(
     sample: ArrayLike,
     bins: SupportsIndex | ArrayLike = ...,
     range: Sequence[tuple[float, float]] = ...,
-    density: None | bool = ...,
-    weights: None | ArrayLike = ...,
+    density: bool | None = ...,
+    weights: ArrayLike | None = ...,
 ) -> tuple[NDArray[Any], tuple[NDArray[Any], ...]]: ...
diff --git a/numpy/lib/_polynomial_impl.pyi b/numpy/lib/_polynomial_impl.pyi
index 112ec33d2520..b93d579a195f 100644
--- a/numpy/lib/_polynomial_impl.pyi
+++ b/numpy/lib/_polynomial_impl.pyi
@@ -69,25 +69,25 @@ def roots(p: ArrayLike) -> NDArray[complexfloating[Any, Any]] | NDArray[floating
 def polyint(
     p: poly1d,
     m: SupportsInt | SupportsIndex = ...,
-    k: None | _ArrayLikeComplex_co | _ArrayLikeObject_co = ...,
+    k: _ArrayLikeComplex_co | _ArrayLikeObject_co | None = ...,
 ) -> poly1d: ...
 @overload
 def polyint(
     p: _ArrayLikeFloat_co,
     m: SupportsInt | SupportsIndex = ...,
-    k: None | _ArrayLikeFloat_co = ...,
+    k: _ArrayLikeFloat_co | None = ...,
 ) -> NDArray[floating[Any]]: ...
 @overload
 def polyint(
     p: _ArrayLikeComplex_co,
     m: SupportsInt | SupportsIndex = ...,
-    k: None | _ArrayLikeComplex_co = ...,
+    k: _ArrayLikeComplex_co | None = ...,
 ) -> NDArray[complexfloating[Any, Any]]: ...
 @overload
 def polyint(
     p: _ArrayLikeObject_co,
     m: SupportsInt | SupportsIndex = ...,
-    k: None | _ArrayLikeObject_co = ...,
+    k: _ArrayLikeObject_co | None = ...,
 ) -> NDArray[object_]: ...
 
 @overload
@@ -116,9 +116,9 @@ def polyfit(
     x: _ArrayLikeFloat_co,
     y: _ArrayLikeFloat_co,
     deg: SupportsIndex | SupportsInt,
-    rcond: None | float = ...,
+    rcond: float | None = ...,
     full: L[False] = ...,
-    w: None | _ArrayLikeFloat_co = ...,
+    w: _ArrayLikeFloat_co | None = ...,
     cov: L[False] = ...,
 ) -> NDArray[float64]: ...
 @overload
@@ -126,9 +126,9 @@ def polyfit(
     x: _ArrayLikeComplex_co,
     y: _ArrayLikeComplex_co,
     deg: SupportsIndex | SupportsInt,
-    rcond: None | float = ...,
+    rcond: float | None = ...,
     full: L[False] = ...,
-    w: None | _ArrayLikeFloat_co = ...,
+    w: _ArrayLikeFloat_co | None = ...,
     cov: L[False] = ...,
 ) -> NDArray[complex128]: ...
 @overload
@@ -136,9 +136,9 @@ def polyfit(
     x: _ArrayLikeFloat_co,
     y: _ArrayLikeFloat_co,
     deg: SupportsIndex | SupportsInt,
-    rcond: None | float = ...,
+    rcond: float | None = ...,
     full: L[False] = ...,
-    w: None | _ArrayLikeFloat_co = ...,
+    w: _ArrayLikeFloat_co | None = ...,
     cov: L[True, "unscaled"] = ...,
 ) -> _2Tup[NDArray[float64]]: ...
 @overload
@@ -146,9 +146,9 @@ def polyfit(
     x: _ArrayLikeComplex_co,
     y: _ArrayLikeComplex_co,
     deg: SupportsIndex | SupportsInt,
-    rcond: None | float = ...,
+    rcond: float | None = ...,
     full: L[False] = ...,
-    w: None | _ArrayLikeFloat_co = ...,
+    w: _ArrayLikeFloat_co | None = ...,
     cov: L[True, "unscaled"] = ...,
 ) -> _2Tup[NDArray[complex128]]: ...
 @overload
@@ -156,9 +156,9 @@ def polyfit(
     x: _ArrayLikeFloat_co,
     y: _ArrayLikeFloat_co,
     deg: SupportsIndex | SupportsInt,
-    rcond: None | float = ...,
+    rcond: float | None = ...,
     full: L[True] = ...,
-    w: None | _ArrayLikeFloat_co = ...,
+    w: _ArrayLikeFloat_co | None = ...,
     cov: bool | L["unscaled"] = ...,
 ) -> _5Tup[NDArray[float64]]: ...
 @overload
@@ -166,9 +166,9 @@ def polyfit(
     x: _ArrayLikeComplex_co,
     y: _ArrayLikeComplex_co,
     deg: SupportsIndex | SupportsInt,
-    rcond: None | float = ...,
+    rcond: float | None = ...,
     full: L[True] = ...,
-    w: None | _ArrayLikeFloat_co = ...,
+    w: _ArrayLikeFloat_co | None = ...,
     cov: bool | L["unscaled"] = ...,
 ) -> _5Tup[NDArray[complex128]]: ...
 
diff --git a/numpy/lib/_shape_base_impl.pyi b/numpy/lib/_shape_base_impl.pyi
index 79e9ca195d5e..ee3234fb45f4 100644
--- a/numpy/lib/_shape_base_impl.pyi
+++ b/numpy/lib/_shape_base_impl.pyi
@@ -55,7 +55,7 @@ class _ArrayWrap(Protocol):
     def __call__(
         self,
         array: NDArray[Any],
-        context: None | tuple[ufunc, tuple[Any, ...], int] = ...,
+        context: tuple[ufunc, tuple[Any, ...], int] | None = ...,
         return_scalar: bool = ...,
         /,
     ) -> Any: ...
@@ -70,14 +70,14 @@ class _SupportsArrayWrap(Protocol):
 def take_along_axis(
     arr: _ScalarT | NDArray[_ScalarT],
     indices: NDArray[integer[Any]],
-    axis: None | int,
+    axis: int | None,
 ) -> NDArray[_ScalarT]: ...
 
 def put_along_axis(
     arr: NDArray[_ScalarT],
     indices: NDArray[integer[Any]],
     values: ArrayLike,
-    axis: None | int,
+    axis: int | None,
 ) -> None: ...
 
 @overload
@@ -196,7 +196,7 @@ def dsplit(
 @overload
 def get_array_wrap(*args: _SupportsArrayWrap) -> _ArrayWrap: ...
 @overload
-def get_array_wrap(*args: object) -> None | _ArrayWrap: ...
+def get_array_wrap(*args: object) -> _ArrayWrap | None: ...
 
 @overload
 def kron(a: _ArrayLikeBool_co, b: _ArrayLikeBool_co) -> NDArray[np.bool]: ...  # type: ignore[misc]
diff --git a/numpy/lib/_stride_tricks_impl.pyi b/numpy/lib/_stride_tricks_impl.pyi
index 01ce196bba2c..de2400a9ee98 100644
--- a/numpy/lib/_stride_tricks_impl.pyi
+++ b/numpy/lib/_stride_tricks_impl.pyi
@@ -16,26 +16,26 @@ _ScalarT = TypeVar("_ScalarT", bound=generic)
 
 class DummyArray:
     __array_interface__: dict[str, Any]
-    base: None | NDArray[Any]
+    base: NDArray[Any] | None
     def __init__(
         self,
         interface: dict[str, Any],
-        base: None | NDArray[Any] = ...,
+        base: NDArray[Any] | None = ...,
     ) -> None: ...
 
 @overload
 def as_strided(
     x: _ArrayLike[_ScalarT],
-    shape: None | Iterable[int] = ...,
-    strides: None | Iterable[int] = ...,
+    shape: Iterable[int] | None = ...,
+    strides: Iterable[int] | None = ...,
     subok: bool = ...,
     writeable: bool = ...,
 ) -> NDArray[_ScalarT]: ...
 @overload
 def as_strided(
     x: ArrayLike,
-    shape: None | Iterable[int] = ...,
-    strides: None | Iterable[int] = ...,
+    shape: Iterable[int] | None = ...,
+    strides: Iterable[int] | None = ...,
     subok: bool = ...,
     writeable: bool = ...,
 ) -> NDArray[Any]: ...
@@ -44,7 +44,7 @@ def as_strided(
 def sliding_window_view(
     x: _ArrayLike[_ScalarT],
     window_shape: int | Iterable[int],
-    axis: None | SupportsIndex = ...,
+    axis: SupportsIndex | None = ...,
     *,
     subok: bool = ...,
     writeable: bool = ...,
@@ -53,7 +53,7 @@ def sliding_window_view(
 def sliding_window_view(
     x: ArrayLike,
     window_shape: int | Iterable[int],
-    axis: None | SupportsIndex = ...,
+    axis: SupportsIndex | None = ...,
     *,
     subok: bool = ...,
     writeable: bool = ...,
diff --git a/numpy/lib/_twodim_base_impl.pyi b/numpy/lib/_twodim_base_impl.pyi
index 2115c4576e9e..9867f59f9409 100644
--- a/numpy/lib/_twodim_base_impl.pyi
+++ b/numpy/lib/_twodim_base_impl.pyi
@@ -91,46 +91,46 @@ def flipud(m: ArrayLike) -> NDArray[Any]: ...
 @overload
 def eye(
     N: int,
-    M: None | int = ...,
+    M: int | None = ...,
     k: int = ...,
     dtype: None = ...,
     order: _OrderCF = ...,
     *,
-    device: None | L["cpu"] = ...,
-    like: None | _SupportsArrayFunc = ...,
+    device: L["cpu"] | None = ...,
+    like: _SupportsArrayFunc | None = ...,
 ) -> NDArray[float64]: ...
 @overload
 def eye(
     N: int,
-    M: None | int,
+    M: int | None,
     k: int,
     dtype: _DTypeLike[_ScalarT],
     order: _OrderCF = ...,
     *,
-    device: None | L["cpu"] = ...,
-    like: None | _SupportsArrayFunc = ...,
+    device: L["cpu"] | None = ...,
+    like: _SupportsArrayFunc | None = ...,
 ) -> NDArray[_ScalarT]: ...
 @overload
 def eye(
     N: int,
-    M: None | int = ...,
+    M: int | None = ...,
     k: int = ...,
     *,
     dtype: _DTypeLike[_ScalarT],
     order: _OrderCF = ...,
-    device: None | L["cpu"] = ...,
-    like: None | _SupportsArrayFunc = ...,
+    device: L["cpu"] | None = ...,
+    like: _SupportsArrayFunc | None = ...,
 ) -> NDArray[_ScalarT]: ...
 @overload
 def eye(
     N: int,
-    M: None | int = ...,
+    M: int | None = ...,
     k: int = ...,
     dtype: DTypeLike = ...,
     order: _OrderCF = ...,
     *,
-    device: None | L["cpu"] = ...,
-    like: None | _SupportsArrayFunc = ...,
+    device: L["cpu"] | None = ...,
+    like: _SupportsArrayFunc | None = ...,
 ) -> NDArray[Any]: ...
 
 @overload
@@ -146,38 +146,38 @@ def diagflat(v: ArrayLike, k: int = ...) -> NDArray[Any]: ...
 @overload
 def tri(
     N: int,
-    M: None | int = ...,
+    M: int | None = ...,
     k: int = ...,
     dtype: None = ...,
     *,
-    like: None | _SupportsArrayFunc = ...
+    like: _SupportsArrayFunc | None = ...
 ) -> NDArray[float64]: ...
 @overload
 def tri(
     N: int,
-    M: None | int,
+    M: int | None,
     k: int,
     dtype: _DTypeLike[_ScalarT],
     *,
-    like: None | _SupportsArrayFunc = ...
+    like: _SupportsArrayFunc | None = ...
 ) -> NDArray[_ScalarT]: ...
 @overload
 def tri(
     N: int,
-    M: None | int = ...,
+    M: int | None = ...,
     k: int = ...,
     *,
     dtype: _DTypeLike[_ScalarT],
-    like: None | _SupportsArrayFunc = ...
+    like: _SupportsArrayFunc | None = ...
 ) -> NDArray[_ScalarT]: ...
 @overload
 def tri(
     N: int,
-    M: None | int = ...,
+    M: int | None = ...,
     k: int = ...,
     dtype: DTypeLike = ...,
     *,
-    like: None | _SupportsArrayFunc = ...
+    like: _SupportsArrayFunc | None = ...
 ) -> NDArray[Any]: ...
 
 @overload
@@ -193,25 +193,25 @@ def triu(m: ArrayLike, k: int = 0) -> NDArray[Any]: ...
 @overload
 def vander(  # type: ignore[misc]
     x: _ArrayLikeInt_co,
-    N: None | int = ...,
+    N: int | None = ...,
     increasing: bool = ...,
 ) -> NDArray[signedinteger[Any]]: ...
 @overload
 def vander(  # type: ignore[misc]
     x: _ArrayLikeFloat_co,
-    N: None | int = ...,
+    N: int | None = ...,
     increasing: bool = ...,
 ) -> NDArray[floating[Any]]: ...
 @overload
 def vander(
     x: _ArrayLikeComplex_co,
-    N: None | int = ...,
+    N: int | None = ...,
     increasing: bool = ...,
 ) -> NDArray[complexfloating[Any, Any]]: ...
 @overload
 def vander(
     x: _ArrayLikeObject_co,
-    N: None | int = ...,
+    N: int | None = ...,
     increasing: bool = ...,
 ) -> NDArray[object_]: ...
 
@@ -220,9 +220,9 @@ def histogram2d(
     x: _ArrayLike1D[_ComplexFloatingT],
     y: _ArrayLike1D[_ComplexFloatingT | _Float_co],
     bins: int | Sequence[int] = ...,
-    range: None | _ArrayLike2DFloat_co = ...,
-    density: None | bool = ...,
-    weights: None | _ArrayLike1DFloat_co = ...,
+    range: _ArrayLike2DFloat_co | None = ...,
+    density: bool | None = ...,
+    weights: _ArrayLike1DFloat_co | None = ...,
 ) -> tuple[
     NDArray[float64],
     NDArray[_ComplexFloatingT],
@@ -233,9 +233,9 @@ def histogram2d(
     x: _ArrayLike1D[_ComplexFloatingT | _Float_co],
     y: _ArrayLike1D[_ComplexFloatingT],
     bins: int | Sequence[int] = ...,
-    range: None | _ArrayLike2DFloat_co = ...,
-    density: None | bool = ...,
-    weights: None | _ArrayLike1DFloat_co = ...,
+    range: _ArrayLike2DFloat_co | None = ...,
+    density: bool | None = ...,
+    weights: _ArrayLike1DFloat_co | None = ...,
 ) -> tuple[
     NDArray[float64],
     NDArray[_ComplexFloatingT],
@@ -246,9 +246,9 @@ def histogram2d(
     x: _ArrayLike1D[_InexactT],
     y: _ArrayLike1D[_InexactT | _Int_co],
     bins: int | Sequence[int] = ...,
-    range: None | _ArrayLike2DFloat_co = ...,
-    density: None | bool = ...,
-    weights: None | _ArrayLike1DFloat_co = ...,
+    range: _ArrayLike2DFloat_co | None = ...,
+    density: bool | None = ...,
+    weights: _ArrayLike1DFloat_co | None = ...,
 ) -> tuple[
     NDArray[float64],
     NDArray[_InexactT],
@@ -259,9 +259,9 @@ def histogram2d(
     x: _ArrayLike1D[_InexactT | _Int_co],
     y: _ArrayLike1D[_InexactT],
     bins: int | Sequence[int] = ...,
-    range: None | _ArrayLike2DFloat_co = ...,
-    density: None | bool = ...,
-    weights: None | _ArrayLike1DFloat_co = ...,
+    range: _ArrayLike2DFloat_co | None = ...,
+    density: bool | None = ...,
+    weights: _ArrayLike1DFloat_co | None = ...,
 ) -> tuple[
     NDArray[float64],
     NDArray[_InexactT],
@@ -272,9 +272,9 @@ def histogram2d(
     x: _ArrayLike1DInt_co | Sequence[float | int],
     y: _ArrayLike1DInt_co | Sequence[float | int],
     bins: int | Sequence[int] = ...,
-    range: None | _ArrayLike2DFloat_co = ...,
-    density: None | bool = ...,
-    weights: None | _ArrayLike1DFloat_co = ...,
+    range: _ArrayLike2DFloat_co | None = ...,
+    density: bool | None = ...,
+    weights: _ArrayLike1DFloat_co | None = ...,
 ) -> tuple[
     NDArray[float64],
     NDArray[float64],
@@ -285,9 +285,9 @@ def histogram2d(
     x: Sequence[complex | float | int],
     y: Sequence[complex | float | int],
     bins: int | Sequence[int] = ...,
-    range: None | _ArrayLike2DFloat_co = ...,
-    density: None | bool = ...,
-    weights: None | _ArrayLike1DFloat_co = ...,
+    range: _ArrayLike2DFloat_co | None = ...,
+    density: bool | None = ...,
+    weights: _ArrayLike1DFloat_co | None = ...,
 ) -> tuple[
     NDArray[float64],
     NDArray[complex128 | float64],
@@ -298,9 +298,9 @@ def histogram2d(
     x: _ArrayLike1DNumber_co,
     y: _ArrayLike1DNumber_co,
     bins: _ArrayLike1D[_NumberCoT] | Sequence[_ArrayLike1D[_NumberCoT]],
-    range: None | _ArrayLike2DFloat_co = ...,
-    density: None | bool = ...,
-    weights: None | _ArrayLike1DFloat_co = ...,
+    range: _ArrayLike2DFloat_co | None = ...,
+    density: bool | None = ...,
+    weights: _ArrayLike1DFloat_co | None = ...,
 ) -> tuple[
     NDArray[float64],
     NDArray[_NumberCoT],
@@ -311,9 +311,9 @@ def histogram2d(
     x: _ArrayLike1D[_InexactT],
     y: _ArrayLike1D[_InexactT],
     bins: Sequence[_ArrayLike1D[_NumberCoT] | int],
-    range: None | _ArrayLike2DFloat_co = ...,
-    density: None | bool = ...,
-    weights: None | _ArrayLike1DFloat_co = ...,
+    range: _ArrayLike2DFloat_co | None = ...,
+    density: bool | None = ...,
+    weights: _ArrayLike1DFloat_co | None = ...,
 ) -> tuple[
     NDArray[float64],
     NDArray[_NumberCoT | _InexactT],
@@ -324,9 +324,9 @@ def histogram2d(
     x: _ArrayLike1DInt_co | Sequence[float | int],
     y: _ArrayLike1DInt_co | Sequence[float | int],
     bins: Sequence[_ArrayLike1D[_NumberCoT] | int],
-    range: None | _ArrayLike2DFloat_co = ...,
-    density: None | bool = ...,
-    weights: None | _ArrayLike1DFloat_co = ...,
+    range: _ArrayLike2DFloat_co | None = ...,
+    density: bool | None = ...,
+    weights: _ArrayLike1DFloat_co | None = ...,
 ) -> tuple[
     NDArray[float64],
     NDArray[_NumberCoT | float64],
@@ -337,9 +337,9 @@ def histogram2d(
     x: Sequence[complex | float | int],
     y: Sequence[complex | float | int],
     bins: Sequence[_ArrayLike1D[_NumberCoT] | int],
-    range: None | _ArrayLike2DFloat_co = ...,
-    density: None | bool = ...,
-    weights: None | _ArrayLike1DFloat_co = ...,
+    range: _ArrayLike2DFloat_co | None = ...,
+    density: bool | None = ...,
+    weights: _ArrayLike1DFloat_co | None = ...,
 ) -> tuple[
     NDArray[float64],
     NDArray[_NumberCoT | complex128 | float64],
@@ -350,9 +350,9 @@ def histogram2d(
     x: _ArrayLike1DNumber_co,
     y: _ArrayLike1DNumber_co,
     bins: Sequence[Sequence[bool]],
-    range: None | _ArrayLike2DFloat_co = ...,
-    density: None | bool = ...,
-    weights: None | _ArrayLike1DFloat_co = ...,
+    range: _ArrayLike2DFloat_co | None = ...,
+    density: bool | None = ...,
+    weights: _ArrayLike1DFloat_co | None = ...,
 ) -> tuple[
     NDArray[float64],
     NDArray[np.bool],
@@ -363,9 +363,9 @@ def histogram2d(
     x: _ArrayLike1DNumber_co,
     y: _ArrayLike1DNumber_co,
     bins: Sequence[Sequence[int | bool]],
-    range: None | _ArrayLike2DFloat_co = ...,
-    density: None | bool = ...,
-    weights: None | _ArrayLike1DFloat_co = ...,
+    range: _ArrayLike2DFloat_co | None = ...,
+    density: bool | None = ...,
+    weights: _ArrayLike1DFloat_co | None = ...,
 ) -> tuple[
     NDArray[float64],
     NDArray[np.int_ | np.bool],
@@ -376,9 +376,9 @@ def histogram2d(
     x: _ArrayLike1DNumber_co,
     y: _ArrayLike1DNumber_co,
     bins: Sequence[Sequence[float | int | bool]],
-    range: None | _ArrayLike2DFloat_co = ...,
-    density: None | bool = ...,
-    weights: None | _ArrayLike1DFloat_co = ...,
+    range: _ArrayLike2DFloat_co | None = ...,
+    density: bool | None = ...,
+    weights: _ArrayLike1DFloat_co | None = ...,
 ) -> tuple[
     NDArray[float64],
     NDArray[np.float64 | np.int_ | np.bool],
@@ -389,9 +389,9 @@ def histogram2d(
     x: _ArrayLike1DNumber_co,
     y: _ArrayLike1DNumber_co,
     bins: Sequence[Sequence[complex | float | int | bool]],
-    range: None | _ArrayLike2DFloat_co = ...,
-    density: None | bool = ...,
-    weights: None | _ArrayLike1DFloat_co = ...,
+    range: _ArrayLike2DFloat_co | None = ...,
+    density: bool | None = ...,
+    weights: _ArrayLike1DFloat_co | None = ...,
 ) -> tuple[
     NDArray[float64],
     NDArray[np.complex128 | np.float64 | np.int_ | np.bool],
@@ -417,7 +417,7 @@ def mask_indices(
 def tril_indices(
     n: int,
     k: int = ...,
-    m: None | int = ...,
+    m: int | None = ...,
 ) -> tuple[NDArray[int_], NDArray[int_]]: ...
 
 def tril_indices_from(
@@ -428,7 +428,7 @@ def tril_indices_from(
 def triu_indices(
     n: int,
     k: int = ...,
-    m: None | int = ...,
+    m: int | None = ...,
 ) -> tuple[NDArray[int_], NDArray[int_]]: ...
 
 def triu_indices_from(
diff --git a/numpy/linalg/_linalg.pyi b/numpy/linalg/_linalg.pyi
index 1f5d91889c3f..0f0de668b9a9 100644
--- a/numpy/linalg/_linalg.pyi
+++ b/numpy/linalg/_linalg.pyi
@@ -105,19 +105,19 @@ class SVDResult(NamedTuple):
 def tensorsolve(
     a: _ArrayLikeInt_co,
     b: _ArrayLikeInt_co,
-    axes: None | Iterable[int] = ...,
+    axes: Iterable[int] | None = ...,
 ) -> NDArray[float64]: ...
 @overload
 def tensorsolve(
     a: _ArrayLikeFloat_co,
     b: _ArrayLikeFloat_co,
-    axes: None | Iterable[int] = ...,
+    axes: Iterable[int] | None = ...,
 ) -> NDArray[floating[Any]]: ...
 @overload
 def tensorsolve(
     a: _ArrayLikeComplex_co,
     b: _ArrayLikeComplex_co,
-    axes: None | Iterable[int] = ...,
+    axes: Iterable[int] | None = ...,
 ) -> NDArray[complexfloating[Any, Any]]: ...
 
 @overload
@@ -286,15 +286,15 @@ def svdvals(
 
 # TODO: Returns a scalar for 2D arrays and
 # a `(x.ndim - 2)`` dimensionl array otherwise
-def cond(x: _ArrayLikeComplex_co, p: None | float | L["fro", "nuc"] = ...) -> Any: ...
+def cond(x: _ArrayLikeComplex_co, p: float | L["fro", "nuc"] | None = ...) -> Any: ...
 
 # TODO: Returns `int` for <2D arrays and `intp` otherwise
 def matrix_rank(
     A: _ArrayLikeComplex_co,
-    tol: None | _ArrayLikeFloat_co = ...,
+    tol: _ArrayLikeFloat_co | None = ...,
     hermitian: bool = ...,
     *,
-    rtol: None | _ArrayLikeFloat_co = ...,
+    rtol: _ArrayLikeFloat_co | None = ...,
 ) -> Any: ...
 
 @overload
@@ -325,21 +325,21 @@ def slogdet(a: _ArrayLikeComplex_co) -> SlogdetResult: ...
 def det(a: _ArrayLikeComplex_co) -> Any: ...
 
 @overload
-def lstsq(a: _ArrayLikeInt_co, b: _ArrayLikeInt_co, rcond: None | float = ...) -> tuple[
+def lstsq(a: _ArrayLikeInt_co, b: _ArrayLikeInt_co, rcond: float | None = ...) -> tuple[
     NDArray[float64],
     NDArray[float64],
     int32,
     NDArray[float64],
 ]: ...
 @overload
-def lstsq(a: _ArrayLikeFloat_co, b: _ArrayLikeFloat_co, rcond: None | float = ...) -> tuple[
+def lstsq(a: _ArrayLikeFloat_co, b: _ArrayLikeFloat_co, rcond: float | None = ...) -> tuple[
     NDArray[floating[Any]],
     NDArray[floating[Any]],
     int32,
     NDArray[floating[Any]],
 ]: ...
 @overload
-def lstsq(a: _ArrayLikeComplex_co, b: _ArrayLikeComplex_co, rcond: None | float = ...) -> tuple[
+def lstsq(a: _ArrayLikeComplex_co, b: _ArrayLikeComplex_co, rcond: float | None = ...) -> tuple[
     NDArray[complexfloating[Any, Any]],
     NDArray[floating[Any]],
     int32,
@@ -349,14 +349,14 @@ def lstsq(a: _ArrayLikeComplex_co, b: _ArrayLikeComplex_co, rcond: None | float
 @overload
 def norm(
     x: ArrayLike,
-    ord: None | float | L["fro", "nuc"] = ...,
+    ord: float | L["fro", "nuc"] | None = ...,
     axis: None = ...,
     keepdims: bool = ...,
 ) -> floating[Any]: ...
 @overload
 def norm(
     x: ArrayLike,
-    ord: None | float | L["fro", "nuc"] = ...,
+    ord: float | L["fro", "nuc"] | None = ...,
     axis: SupportsInt | SupportsIndex | tuple[int, ...] = ...,
     keepdims: bool = ...,
 ) -> Any: ...
@@ -366,7 +366,7 @@ def matrix_norm(
     x: ArrayLike,
     /,
     *,
-    ord: None | float | L["fro", "nuc"] = ...,
+    ord: float | L["fro", "nuc"] | None = ...,
     keepdims: bool = ...,
 ) -> floating[Any]: ...
 @overload
@@ -374,7 +374,7 @@ def matrix_norm(
     x: ArrayLike,
     /,
     *,
-    ord: None | float | L["fro", "nuc"] = ...,
+    ord: float | L["fro", "nuc"] | None = ...,
     keepdims: bool = ...,
 ) -> Any: ...
 
@@ -384,7 +384,7 @@ def vector_norm(
     /,
     *,
     axis: None = ...,
-    ord: None | float = ...,
+    ord: float | None = ...,
     keepdims: bool = ...,
 ) -> floating[Any]: ...
 @overload
@@ -393,7 +393,7 @@ def vector_norm(
     /,
     *,
     axis: SupportsInt | SupportsIndex | tuple[int, ...] = ...,
-    ord: None | float = ...,
+    ord: float | None = ...,
     keepdims: bool = ...,
 ) -> Any: ...
 
@@ -401,7 +401,7 @@ def vector_norm(
 def multi_dot(
     arrays: Iterable[_ArrayLikeComplex_co | _ArrayLikeObject_co | _ArrayLikeTD64_co],
     *,
-    out: None | NDArray[Any] = ...,
+    out: NDArray[Any] | None = ...,
 ) -> Any: ...
 
 def diagonal(
diff --git a/numpy/matrixlib/defmatrix.pyi b/numpy/matrixlib/defmatrix.pyi
index a6095cc1155a..ee8f83746998 100644
--- a/numpy/matrixlib/defmatrix.pyi
+++ b/numpy/matrixlib/defmatrix.pyi
@@ -8,8 +8,8 @@ __all__ = ["asmatrix", "bmat", "matrix"]
 
 def bmat(
     obj: str | Sequence[ArrayLike] | NDArray[Any],
-    ldict: None | Mapping[str, Any] = ...,
-    gdict: None | Mapping[str, Any] = ...,
+    ldict: Mapping[str, Any] | None = ...,
+    gdict: Mapping[str, Any] | None = ...,
 ) -> matrix[tuple[int, int], Any]: ...
 
 def asmatrix(
diff --git a/numpy/polynomial/_polybase.pyi b/numpy/polynomial/_polybase.pyi
index 7fe2724572ed..edbe4c8db980 100644
--- a/numpy/polynomial/_polybase.pyi
+++ b/numpy/polynomial/_polybase.pyi
@@ -80,8 +80,8 @@ class ABCPolyBase(Generic[_NameCo], abc.ABC):
         self,
         /,
         coef: _SeriesLikeCoef_co,
-        domain: None | _SeriesLikeCoef_co = ...,
-        window: None | _SeriesLikeCoef_co = ...,
+        domain: _SeriesLikeCoef_co | None = ...,
+        window: _SeriesLikeCoef_co | None = ...,
         symbol: str = ...,
     ) -> None: ...
 
@@ -162,27 +162,27 @@ class ABCPolyBase(Generic[_NameCo], abc.ABC):
     @overload
     def convert(
         self,
-        domain: None | _SeriesLikeCoef_co,
+        domain: _SeriesLikeCoef_co | None,
         kind: type[_Other],
         /,
-        window: None | _SeriesLikeCoef_co = ...,
+        window: _SeriesLikeCoef_co | None = ...,
     ) -> _Other: ...
     @overload
     def convert(
         self,
         /,
-        domain: None | _SeriesLikeCoef_co = ...,
+        domain: _SeriesLikeCoef_co | None = ...,
         *,
         kind: type[_Other],
-        window: None | _SeriesLikeCoef_co = ...,
+        window: _SeriesLikeCoef_co | None = ...,
     ) -> _Other: ...
     @overload
     def convert(
         self: _Self,
         /,
-        domain: None | _SeriesLikeCoef_co = ...,
-        kind: None | type[_Self] = ...,
-        window: None | _SeriesLikeCoef_co = ...,
+        domain: _SeriesLikeCoef_co | None = ...,
+        kind: type[_Self] | None = ...,
+        window: _SeriesLikeCoef_co | None = ...,
     ) -> _Self: ...
 
     def mapparms(self, /) -> _Tuple2[Any]: ...
@@ -191,7 +191,7 @@ class ABCPolyBase(Generic[_NameCo], abc.ABC):
         self: _Self, /,
         m: SupportsIndex = ...,
         k: _CoefLike_co | _SeriesLikeCoef_co = ...,
-        lbnd: None | _CoefLike_co = ...,
+        lbnd: _CoefLike_co | None = ...,
     ) -> _Self: ...
 
     def deriv(self: _Self, /, m: SupportsIndex = ...) -> _Self: ...
@@ -201,7 +201,7 @@ class ABCPolyBase(Generic[_NameCo], abc.ABC):
     def linspace(
         self, /,
         n: SupportsIndex = ...,
-        domain: None | _SeriesLikeCoef_co = ...,
+        domain: _SeriesLikeCoef_co | None = ...,
     ) -> _Tuple2[_Series[np.float64 | np.complex128]]: ...
 
     @overload
@@ -211,11 +211,11 @@ class ABCPolyBase(Generic[_NameCo], abc.ABC):
         x: _SeriesLikeCoef_co,
         y: _SeriesLikeCoef_co,
         deg: int | _SeriesLikeInt_co,
-        domain: None | _SeriesLikeCoef_co = ...,
+        domain: _SeriesLikeCoef_co | None = ...,
         rcond: _FloatLike_co = ...,
         full: Literal[False] = ...,
-        w: None | _SeriesLikeCoef_co = ...,
-        window: None | _SeriesLikeCoef_co = ...,
+        w: _SeriesLikeCoef_co | None = ...,
+        window: _SeriesLikeCoef_co | None = ...,
         symbol: str = ...,
     ) -> _Self: ...
     @overload
@@ -225,12 +225,12 @@ class ABCPolyBase(Generic[_NameCo], abc.ABC):
         x: _SeriesLikeCoef_co,
         y: _SeriesLikeCoef_co,
         deg: int | _SeriesLikeInt_co,
-        domain: None | _SeriesLikeCoef_co = ...,
+        domain: _SeriesLikeCoef_co | None = ...,
         rcond: _FloatLike_co = ...,
         *,
         full: Literal[True],
-        w: None | _SeriesLikeCoef_co = ...,
-        window: None | _SeriesLikeCoef_co = ...,
+        w: _SeriesLikeCoef_co | None = ...,
+        window: _SeriesLikeCoef_co | None = ...,
         symbol: str = ...,
     ) -> tuple[_Self, Sequence[np.inexact[Any] | np.int32]]: ...
     @overload
@@ -240,11 +240,11 @@ class ABCPolyBase(Generic[_NameCo], abc.ABC):
         x: _SeriesLikeCoef_co,
         y: _SeriesLikeCoef_co,
         deg: int | _SeriesLikeInt_co,
-        domain: None | _SeriesLikeCoef_co,
+        domain: _SeriesLikeCoef_co | None,
         rcond: _FloatLike_co,
         full: Literal[True], /,
-        w: None | _SeriesLikeCoef_co = ...,
-        window: None | _SeriesLikeCoef_co = ...,
+        w: _SeriesLikeCoef_co | None = ...,
+        window: _SeriesLikeCoef_co | None = ...,
         symbol: str = ...,
     ) -> tuple[_Self, Sequence[np.inexact[Any] | np.int32]]: ...
 
@@ -252,16 +252,16 @@ class ABCPolyBase(Generic[_NameCo], abc.ABC):
     def fromroots(
         cls: type[_Self], /,
         roots: _ArrayLikeCoef_co,
-        domain: None | _SeriesLikeCoef_co = ...,
-        window: None | _SeriesLikeCoef_co = ...,
+        domain: _SeriesLikeCoef_co | None = ...,
+        window: _SeriesLikeCoef_co | None = ...,
         symbol: str = ...,
     ) -> _Self: ...
 
     @classmethod
     def identity(
         cls: type[_Self], /,
-        domain: None | _SeriesLikeCoef_co = ...,
-        window: None | _SeriesLikeCoef_co = ...,
+        domain: _SeriesLikeCoef_co | None = ...,
+        window: _SeriesLikeCoef_co | None = ...,
         symbol: str = ...,
     ) -> _Self: ...
 
@@ -269,8 +269,8 @@ class ABCPolyBase(Generic[_NameCo], abc.ABC):
     def basis(
         cls: type[_Self], /,
         deg: _AnyInt,
-        domain: None | _SeriesLikeCoef_co = ...,
-        window: None | _SeriesLikeCoef_co = ...,
+        domain: _SeriesLikeCoef_co | None = ...,
+        window: _SeriesLikeCoef_co | None = ...,
         symbol: str = ...,
     ) -> _Self: ...
 
@@ -278,8 +278,8 @@ class ABCPolyBase(Generic[_NameCo], abc.ABC):
     def cast(
         cls: type[_Self], /,
         series: ABCPolyBase,
-        domain: None | _SeriesLikeCoef_co = ...,
-        window: None | _SeriesLikeCoef_co = ...,
+        domain: _SeriesLikeCoef_co | None = ...,
+        window: _SeriesLikeCoef_co | None = ...,
     ) -> _Self: ...
 
     @classmethod
diff --git a/numpy/polynomial/_polytypes.pyi b/numpy/polynomial/_polytypes.pyi
index 276c67f34124..3074bb840cc0 100644
--- a/numpy/polynomial/_polytypes.pyi
+++ b/numpy/polynomial/_polytypes.pyi
@@ -215,7 +215,7 @@ class _FuncPow(_Named[_Name_co], Protocol[_Name_co]):
         /,
         c: _SeriesLikeFloat_co,
         pow: _IntLike_co,
-        maxpower: None | _IntLike_co = ...,
+        maxpower: _IntLike_co | None = ...,
     ) -> _FloatSeries: ...
     @overload
     def __call__(
@@ -223,7 +223,7 @@ class _FuncPow(_Named[_Name_co], Protocol[_Name_co]):
         /,
         c: _SeriesLikeComplex_co,
         pow: _IntLike_co,
-        maxpower: None | _IntLike_co = ...,
+        maxpower: _IntLike_co | None = ...,
     ) -> _ComplexSeries: ...
     @overload
     def __call__(
@@ -231,7 +231,7 @@ class _FuncPow(_Named[_Name_co], Protocol[_Name_co]):
         /,
         c: _SeriesLikeCoef_co,
         pow: _IntLike_co,
-        maxpower: None | _IntLike_co = ...,
+        maxpower: _IntLike_co | None = ...,
     ) -> _ObjectSeries: ...
 
 @type_check_only
@@ -727,9 +727,9 @@ class _FuncFit(_Named[_Name_co], Protocol[_Name_co]):
         x: _SeriesLikeFloat_co,
         y: _ArrayLikeFloat_co,
         deg: int | _SeriesLikeInt_co,
-        rcond: None | float = ...,
+        rcond: float | None = ...,
         full: Literal[False] = ...,
-        w: None | _SeriesLikeFloat_co = ...,
+        w: _SeriesLikeFloat_co | None = ...,
     ) -> _FloatArray: ...
     @overload
     def __call__(
@@ -737,10 +737,10 @@ class _FuncFit(_Named[_Name_co], Protocol[_Name_co]):
         x: _SeriesLikeFloat_co,
         y: _ArrayLikeFloat_co,
         deg: int | _SeriesLikeInt_co,
-        rcond: None | float,
+        rcond: float | None,
         full: Literal[True],
         /,
-        w: None | _SeriesLikeFloat_co = ...,
+        w: _SeriesLikeFloat_co | None = ...,
     ) -> tuple[_FloatArray, _FullFitResult]: ...
     @overload
     def __call__(
@@ -749,10 +749,10 @@ class _FuncFit(_Named[_Name_co], Protocol[_Name_co]):
         x: _SeriesLikeFloat_co,
         y: _ArrayLikeFloat_co,
         deg: int | _SeriesLikeInt_co,
-        rcond: None | float = ...,
+        rcond: float | None = ...,
         *,
         full: Literal[True],
-        w: None | _SeriesLikeFloat_co = ...,
+        w: _SeriesLikeFloat_co | None = ...,
     ) -> tuple[_FloatArray, _FullFitResult]: ...
 
     @overload
@@ -762,9 +762,9 @@ class _FuncFit(_Named[_Name_co], Protocol[_Name_co]):
         x: _SeriesLikeComplex_co,
         y: _ArrayLikeComplex_co,
         deg: int | _SeriesLikeInt_co,
-        rcond: None | float = ...,
+        rcond: float | None = ...,
         full: Literal[False] = ...,
-        w: None | _SeriesLikeFloat_co = ...,
+        w: _SeriesLikeFloat_co | None = ...,
     ) -> _ComplexArray: ...
     @overload
     def __call__(
@@ -772,10 +772,10 @@ class _FuncFit(_Named[_Name_co], Protocol[_Name_co]):
         x: _SeriesLikeComplex_co,
         y: _ArrayLikeComplex_co,
         deg: int | _SeriesLikeInt_co,
-        rcond: None | float,
+        rcond: float | None,
         full: Literal[True],
         /,
-        w: None | _SeriesLikeFloat_co = ...,
+        w: _SeriesLikeFloat_co | None = ...,
     ) -> tuple[_ComplexArray, _FullFitResult]: ...
     @overload
     def __call__(
@@ -784,10 +784,10 @@ class _FuncFit(_Named[_Name_co], Protocol[_Name_co]):
         x: _SeriesLikeComplex_co,
         y: _ArrayLikeComplex_co,
         deg: int | _SeriesLikeInt_co,
-        rcond: None | float = ...,
+        rcond: float | None = ...,
         *,
         full: Literal[True],
-        w: None | _SeriesLikeFloat_co = ...,
+        w: _SeriesLikeFloat_co | None = ...,
     ) -> tuple[_ComplexArray, _FullFitResult]: ...
 
     @overload
@@ -797,9 +797,9 @@ class _FuncFit(_Named[_Name_co], Protocol[_Name_co]):
         x: _SeriesLikeComplex_co,
         y: _ArrayLikeCoef_co,
         deg: int | _SeriesLikeInt_co,
-        rcond: None | float = ...,
+        rcond: float | None = ...,
         full: Literal[False] = ...,
-        w: None | _SeriesLikeFloat_co = ...,
+        w: _SeriesLikeFloat_co | None = ...,
     ) -> _ObjectArray: ...
     @overload
     def __call__(
@@ -807,10 +807,10 @@ class _FuncFit(_Named[_Name_co], Protocol[_Name_co]):
         x: _SeriesLikeComplex_co,
         y: _ArrayLikeCoef_co,
         deg: int | _SeriesLikeInt_co,
-        rcond: None | float,
+        rcond: float | None,
         full: Literal[True],
         /,
-        w: None | _SeriesLikeFloat_co = ...,
+        w: _SeriesLikeFloat_co | None = ...,
     ) -> tuple[_ObjectArray, _FullFitResult]: ...
     @overload
     def __call__(
@@ -819,10 +819,10 @@ class _FuncFit(_Named[_Name_co], Protocol[_Name_co]):
         x: _SeriesLikeComplex_co,
         y: _ArrayLikeCoef_co,
         deg: int | _SeriesLikeInt_co,
-        rcond: None | float = ...,
+        rcond: float | None = ...,
         *,
         full: Literal[True],
-        w: None | _SeriesLikeFloat_co = ...,
+        w: _SeriesLikeFloat_co | None = ...,
     ) -> tuple[_ObjectArray, _FullFitResult]: ...
 
 @type_check_only
diff --git a/numpy/polynomial/chebyshev.pyi b/numpy/polynomial/chebyshev.pyi
index 8eeb7cb86dca..ea00ca04884a 100644
--- a/numpy/polynomial/chebyshev.pyi
+++ b/numpy/polynomial/chebyshev.pyi
@@ -160,7 +160,7 @@ class Chebyshev(ABCPolyBase[L["T"]]):
         /,
         func: Callable[[npt.NDArray[np.float64]], _CoefSeries],
         deg: _IntLike_co,
-        domain: None | _SeriesLikeCoef_co = ...,
+        domain: _SeriesLikeCoef_co | None = ...,
         args: tuple[()] = ...,
     ) -> _Self: ...
     @overload
@@ -173,7 +173,7 @@ class Chebyshev(ABCPolyBase[L["T"]]):
             _CoefSeries,
         ],
         deg: _IntLike_co,
-        domain: None | _SeriesLikeCoef_co = ...,
+        domain: _SeriesLikeCoef_co | None = ...,
         *,
         args: Iterable[Any],
     ) -> _Self: ...
@@ -186,7 +186,7 @@ class Chebyshev(ABCPolyBase[L["T"]]):
             _CoefSeries,
         ],
         deg: _IntLike_co,
-        domain: None | _SeriesLikeCoef_co,
+        domain: _SeriesLikeCoef_co | None,
         args: Iterable[Any],
         /,
     ) -> _Self: ...
diff --git a/numpy/polynomial/polyutils.pyi b/numpy/polynomial/polyutils.pyi
index befc437d137a..08607fcf94ba 100644
--- a/numpy/polynomial/polyutils.pyi
+++ b/numpy/polynomial/polyutils.pyi
@@ -275,7 +275,7 @@ def mapdomain(
 def _nth_slice(
     i: SupportsIndex,
     ndim: SupportsIndex,
-) -> tuple[None | slice, ...]: ...
+) -> tuple[slice | None, ...]: ...
 
 _vander_nd: _FuncVanderND[Literal["_vander_nd"]]
 _vander_nd_flat: _FuncVanderND[Literal["_vander_nd_flat"]]
@@ -344,28 +344,28 @@ def _pow(  # type: ignore[overload-overlap]
     mul_f: _AnyMulF,
     c: _SeriesLikeFloat_co,
     pow: _AnyInt,
-    maxpower: None | _AnyInt = ...,
+    maxpower: _AnyInt | None = ...,
 ) -> _FloatSeries: ...
 @overload
 def _pow(
     mul_f: _AnyMulF,
     c: _SeriesLikeComplex_co,
     pow: _AnyInt,
-    maxpower: None | _AnyInt = ...,
+    maxpower: _AnyInt | None = ...,
 ) -> _ComplexSeries: ...
 @overload
 def _pow(
     mul_f: _AnyMulF,
     c: _SeriesLikeCoef_co,
     pow: _AnyInt,
-    maxpower: None | _AnyInt = ...,
+    maxpower: _AnyInt | None = ...,
 ) -> _ObjectSeries: ...
 @overload
 def _pow(
     mul_f: _AnyMulF,
     c: _SeriesLikeCoef_co,
     pow: _AnyInt,
-    maxpower: None | _AnyInt = ...,
+    maxpower: _AnyInt | None = ...,
 ) -> _CoefSeries: ...
 
 # keep in sync with `_polytypes._FuncFit`
@@ -375,10 +375,10 @@ def _fit(  # type: ignore[overload-overlap]
     x: _SeriesLikeFloat_co,
     y: _ArrayLikeFloat_co,
     deg: _SeriesLikeInt_co,
-    domain: None | _SeriesLikeFloat_co = ...,
-    rcond: None | _FloatLike_co = ...,
+    domain: _SeriesLikeFloat_co | None = ...,
+    rcond: _FloatLike_co | None = ...,
     full: Literal[False] = ...,
-    w: None | _SeriesLikeFloat_co = ...,
+    w: _SeriesLikeFloat_co | None = ...,
 ) -> _FloatArray: ...
 @overload
 def _fit(
@@ -386,10 +386,10 @@ def _fit(
     x: _SeriesLikeComplex_co,
     y: _ArrayLikeComplex_co,
     deg: _SeriesLikeInt_co,
-    domain: None | _SeriesLikeComplex_co = ...,
-    rcond: None | _FloatLike_co = ...,
+    domain: _SeriesLikeComplex_co | None = ...,
+    rcond: _FloatLike_co | None = ...,
     full: Literal[False] = ...,
-    w: None | _SeriesLikeComplex_co = ...,
+    w: _SeriesLikeComplex_co | None = ...,
 ) -> _ComplexArray: ...
 @overload
 def _fit(
@@ -397,10 +397,10 @@ def _fit(
     x: _SeriesLikeCoef_co,
     y: _ArrayLikeCoef_co,
     deg: _SeriesLikeInt_co,
-    domain: None | _SeriesLikeCoef_co = ...,
-    rcond: None | _FloatLike_co = ...,
+    domain: _SeriesLikeCoef_co | None = ...,
+    rcond: _FloatLike_co | None = ...,
     full: Literal[False] = ...,
-    w: None | _SeriesLikeCoef_co = ...,
+    w: _SeriesLikeCoef_co | None = ...,
 ) -> _CoefArray: ...
 @overload
 def _fit(
@@ -408,11 +408,11 @@ def _fit(
     x: _SeriesLikeCoef_co,
     y: _SeriesLikeCoef_co,
     deg: _SeriesLikeInt_co,
-    domain: None | _SeriesLikeCoef_co,
-    rcond: None | _FloatLike_co,
+    domain: _SeriesLikeCoef_co | None,
+    rcond: _FloatLike_co | None,
     full: Literal[True],
     /,
-    w: None | _SeriesLikeCoef_co = ...,
+    w: _SeriesLikeCoef_co | None = ...,
 ) -> tuple[_CoefSeries, Sequence[np.inexact[Any] | np.int32]]: ...
 @overload
 def _fit(
@@ -420,11 +420,11 @@ def _fit(
     x: _SeriesLikeCoef_co,
     y: _SeriesLikeCoef_co,
     deg: _SeriesLikeInt_co,
-    domain: None | _SeriesLikeCoef_co = ...,
-    rcond: None | _FloatLike_co = ...,
+    domain: _SeriesLikeCoef_co | None = ...,
+    rcond: _FloatLike_co | None = ...,
     *,
     full: Literal[True],
-    w: None | _SeriesLikeCoef_co = ...,
+    w: _SeriesLikeCoef_co | None = ...,
 ) -> tuple[_CoefSeries, Sequence[np.inexact[Any] | np.int32]]: ...
 
 def _as_int(x: SupportsIndex, desc: str) -> int: ...
diff --git a/numpy/random/_generator.pyi b/numpy/random/_generator.pyi
index 7ed4a959625f..dc78a76eda70 100644
--- a/numpy/random/_generator.pyi
+++ b/numpy/random/_generator.pyi
@@ -88,14 +88,14 @@ class Generator:
         self,
         size: _ShapeLike = ...,
         dtype: _DTypeLikeFloat32 = ...,
-        out: None | NDArray[float32] = ...,
+        out: NDArray[float32] | None = ...,
     ) -> NDArray[float32]: ...
     @overload
     def standard_normal(  # type: ignore[misc]
         self,
         size: _ShapeLike = ...,
         dtype: _DTypeLikeFloat64 = ...,
-        out: None | NDArray[float64] = ...,
+        out: NDArray[float64] | None = ...,
     ) -> NDArray[float64]: ...
     @overload
     def permutation(self, x: int, axis: int = ...) -> NDArray[int64]: ...
@@ -126,7 +126,7 @@ class Generator:
         size: _ShapeLike = ...,
         *,
         method: Literal["zig", "inv"] = ...,
-        out: None | NDArray[float64] = ...,
+        out: NDArray[float64] | None = ...,
     ) -> NDArray[float64]: ...
     @overload
     def standard_exponential(
@@ -134,7 +134,7 @@ class Generator:
         size: _ShapeLike = ...,
         dtype: _DTypeLikeFloat32 = ...,
         method: Literal["zig", "inv"] = ...,
-        out: None | NDArray[float32] = ...,
+        out: NDArray[float32] | None = ...,
     ) -> NDArray[float32]: ...
     @overload
     def standard_exponential(
@@ -142,7 +142,7 @@ class Generator:
         size: _ShapeLike = ...,
         dtype: _DTypeLikeFloat64 = ...,
         method: Literal["zig", "inv"] = ...,
-        out: None | NDArray[float64] = ...,
+        out: NDArray[float64] | None = ...,
     ) -> NDArray[float64]: ...
     @overload
     def random(  # type: ignore[misc]
@@ -162,21 +162,21 @@ class Generator:
         self,
         size: _ShapeLike = ...,
         *,
-        out: None | NDArray[float64] = ...,
+        out: NDArray[float64] | None = ...,
     ) -> NDArray[float64]: ...
     @overload
     def random(
         self,
         size: _ShapeLike = ...,
         dtype: _DTypeLikeFloat32 = ...,
-        out: None | NDArray[float32] = ...,
+        out: NDArray[float32] | None = ...,
     ) -> NDArray[float32]: ...
     @overload
     def random(
         self,
         size: _ShapeLike = ...,
         dtype: _DTypeLikeFloat64 = ...,
-        out: None | NDArray[float64] = ...,
+        out: NDArray[float64] | None = ...,
     ) -> NDArray[float64]: ...
     @overload
     def beta(
@@ -190,12 +190,12 @@ class Generator:
         self,
         a: _ArrayLikeFloat_co,
         b: _ArrayLikeFloat_co,
-        size: None | _ShapeLike = ...
+        size: _ShapeLike | None = ...
     ) -> NDArray[float64]: ...
     @overload
     def exponential(self, scale: _FloatLike_co = ..., size: None = ...) -> float: ...  # type: ignore[misc]
     @overload
-    def exponential(self, scale: _ArrayLikeFloat_co = ..., size: None | _ShapeLike = ...) -> NDArray[float64]: ...
+    def exponential(self, scale: _ArrayLikeFloat_co = ..., size: _ShapeLike | None = ...) -> NDArray[float64]: ...
 
     #
     @overload
@@ -483,7 +483,7 @@ class Generator:
         a: int,
         size: None = ...,
         replace: bool = ...,
-        p: None | _ArrayLikeFloat_co = ...,
+        p: _ArrayLikeFloat_co | None = ...,
         axis: int = ...,
         shuffle: bool = ...,
     ) -> int: ...
@@ -493,7 +493,7 @@ class Generator:
         a: int,
         size: _ShapeLike = ...,
         replace: bool = ...,
-        p: None | _ArrayLikeFloat_co = ...,
+        p: _ArrayLikeFloat_co | None = ...,
         axis: int = ...,
         shuffle: bool = ...,
     ) -> NDArray[int64]: ...
@@ -503,7 +503,7 @@ class Generator:
         a: ArrayLike,
         size: None = ...,
         replace: bool = ...,
-        p: None | _ArrayLikeFloat_co = ...,
+        p: _ArrayLikeFloat_co | None = ...,
         axis: int = ...,
         shuffle: bool = ...,
     ) -> Any: ...
@@ -513,7 +513,7 @@ class Generator:
         a: ArrayLike,
         size: _ShapeLike = ...,
         replace: bool = ...,
-        p: None | _ArrayLikeFloat_co = ...,
+        p: _ArrayLikeFloat_co | None = ...,
         axis: int = ...,
         shuffle: bool = ...,
     ) -> NDArray[Any]: ...
@@ -529,7 +529,7 @@ class Generator:
         self,
         low: _ArrayLikeFloat_co = ...,
         high: _ArrayLikeFloat_co = ...,
-        size: None | _ShapeLike = ...,
+        size: _ShapeLike | None = ...,
     ) -> NDArray[float64]: ...
     @overload
     def normal(
@@ -543,7 +543,7 @@ class Generator:
         self,
         loc: _ArrayLikeFloat_co = ...,
         scale: _ArrayLikeFloat_co = ...,
-        size: None | _ShapeLike = ...,
+        size: _ShapeLike | None = ...,
     ) -> NDArray[float64]: ...
     @overload
     def standard_gamma(  # type: ignore[misc]
@@ -557,7 +557,7 @@ class Generator:
     def standard_gamma(
         self,
         shape: _ArrayLikeFloat_co,
-        size: None | _ShapeLike = ...,
+        size: _ShapeLike | None = ...,
     ) -> NDArray[float64]: ...
     @overload
     def standard_gamma(
@@ -570,17 +570,17 @@ class Generator:
     def standard_gamma(
         self,
         shape: _ArrayLikeFloat_co,
-        size: None | _ShapeLike = ...,
+        size: _ShapeLike | None = ...,
         dtype: _DTypeLikeFloat32 = ...,
-        out: None | NDArray[float32] = ...,
+        out: NDArray[float32] | None = ...,
     ) -> NDArray[float32]: ...
     @overload
     def standard_gamma(
         self,
         shape: _ArrayLikeFloat_co,
-        size: None | _ShapeLike = ...,
+        size: _ShapeLike | None = ...,
         dtype: _DTypeLikeFloat64 = ...,
-        out: None | NDArray[float64] = ...,
+        out: NDArray[float64] | None = ...,
     ) -> NDArray[float64]: ...
     @overload
     def gamma(
@@ -591,7 +591,7 @@ class Generator:
         self,
         shape: _ArrayLikeFloat_co,
         scale: _ArrayLikeFloat_co = ...,
-        size: None | _ShapeLike = ...,
+        size: _ShapeLike | None = ...,
     ) -> NDArray[float64]: ...
     @overload
     def f(
@@ -602,7 +602,7 @@ class Generator:
         self,
         dfnum: _ArrayLikeFloat_co,
         dfden: _ArrayLikeFloat_co,
-        size: None | _ShapeLike = ...
+        size: _ShapeLike | None = ...
     ) -> NDArray[float64]: ...
     @overload
     def noncentral_f(
@@ -617,13 +617,13 @@ class Generator:
         dfnum: _ArrayLikeFloat_co,
         dfden: _ArrayLikeFloat_co,
         nonc: _ArrayLikeFloat_co,
-        size: None | _ShapeLike = ...,
+        size: _ShapeLike | None = ...,
     ) -> NDArray[float64]: ...
     @overload
     def chisquare(self, df: _FloatLike_co, size: None = ...) -> float: ...  # type: ignore[misc]
     @overload
     def chisquare(
-        self, df: _ArrayLikeFloat_co, size: None | _ShapeLike = ...
+        self, df: _ArrayLikeFloat_co, size: _ShapeLike | None = ...
     ) -> NDArray[float64]: ...
     @overload
     def noncentral_chisquare(
@@ -634,7 +634,7 @@ class Generator:
         self,
         df: _ArrayLikeFloat_co,
         nonc: _ArrayLikeFloat_co,
-        size: None | _ShapeLike = ...
+        size: _ShapeLike | None = ...
     ) -> NDArray[float64]: ...
     @overload
     def standard_t(self, df: _FloatLike_co, size: None = ...) -> float: ...  # type: ignore[misc]
@@ -655,25 +655,25 @@ class Generator:
         self,
         mu: _ArrayLikeFloat_co,
         kappa: _ArrayLikeFloat_co,
-        size: None | _ShapeLike = ...
+        size: _ShapeLike | None = ...
     ) -> NDArray[float64]: ...
     @overload
     def pareto(self, a: _FloatLike_co, size: None = ...) -> float: ...  # type: ignore[misc]
     @overload
     def pareto(
-        self, a: _ArrayLikeFloat_co, size: None | _ShapeLike = ...
+        self, a: _ArrayLikeFloat_co, size: _ShapeLike | None = ...
     ) -> NDArray[float64]: ...
     @overload
     def weibull(self, a: _FloatLike_co, size: None = ...) -> float: ...  # type: ignore[misc]
     @overload
     def weibull(
-        self, a: _ArrayLikeFloat_co, size: None | _ShapeLike = ...
+        self, a: _ArrayLikeFloat_co, size: _ShapeLike | None = ...
     ) -> NDArray[float64]: ...
     @overload
     def power(self, a: _FloatLike_co, size: None = ...) -> float: ...  # type: ignore[misc]
     @overload
     def power(
-        self, a: _ArrayLikeFloat_co, size: None | _ShapeLike = ...
+        self, a: _ArrayLikeFloat_co, size: _ShapeLike | None = ...
     ) -> NDArray[float64]: ...
     @overload
     def standard_cauchy(self, size: None = ...) -> float: ...  # type: ignore[misc]
@@ -691,7 +691,7 @@ class Generator:
         self,
         loc: _ArrayLikeFloat_co = ...,
         scale: _ArrayLikeFloat_co = ...,
-        size: None | _ShapeLike = ...,
+        size: _ShapeLike | None = ...,
     ) -> NDArray[float64]: ...
     @overload
     def gumbel(
@@ -705,7 +705,7 @@ class Generator:
         self,
         loc: _ArrayLikeFloat_co = ...,
         scale: _ArrayLikeFloat_co = ...,
-        size: None | _ShapeLike = ...,
+        size: _ShapeLike | None = ...,
     ) -> NDArray[float64]: ...
     @overload
     def logistic(
@@ -719,7 +719,7 @@ class Generator:
         self,
         loc: _ArrayLikeFloat_co = ...,
         scale: _ArrayLikeFloat_co = ...,
-        size: None | _ShapeLike = ...,
+        size: _ShapeLike | None = ...,
     ) -> NDArray[float64]: ...
     @overload
     def lognormal(
@@ -733,13 +733,13 @@ class Generator:
         self,
         mean: _ArrayLikeFloat_co = ...,
         sigma: _ArrayLikeFloat_co = ...,
-        size: None | _ShapeLike = ...,
+        size: _ShapeLike | None = ...,
     ) -> NDArray[float64]: ...
     @overload
     def rayleigh(self, scale: _FloatLike_co = ..., size: None = ...) -> float: ...  # type: ignore[misc]
     @overload
     def rayleigh(
-        self, scale: _ArrayLikeFloat_co = ..., size: None | _ShapeLike = ...
+        self, scale: _ArrayLikeFloat_co = ..., size: _ShapeLike | None = ...
     ) -> NDArray[float64]: ...
     @overload
     def wald(
@@ -750,7 +750,7 @@ class Generator:
         self,
         mean: _ArrayLikeFloat_co,
         scale: _ArrayLikeFloat_co,
-        size: None | _ShapeLike = ...
+        size: _ShapeLike | None = ...
     ) -> NDArray[float64]: ...
     @overload
     def triangular(
@@ -766,13 +766,13 @@ class Generator:
         left: _ArrayLikeFloat_co,
         mode: _ArrayLikeFloat_co,
         right: _ArrayLikeFloat_co,
-        size: None | _ShapeLike = ...,
+        size: _ShapeLike | None = ...,
     ) -> NDArray[float64]: ...
     @overload
     def binomial(self, n: int, p: _FloatLike_co, size: None = ...) -> int: ...  # type: ignore[misc]
     @overload
     def binomial(
-        self, n: _ArrayLikeInt_co, p: _ArrayLikeFloat_co, size: None | _ShapeLike = ...
+        self, n: _ArrayLikeInt_co, p: _ArrayLikeFloat_co, size: _ShapeLike | None = ...
     ) -> NDArray[int64]: ...
     @overload
     def negative_binomial(
@@ -783,25 +783,25 @@ class Generator:
         self,
         n: _ArrayLikeFloat_co,
         p: _ArrayLikeFloat_co,
-        size: None | _ShapeLike = ...
+        size: _ShapeLike | None = ...
     ) -> NDArray[int64]: ...
     @overload
     def poisson(self, lam: _FloatLike_co = ..., size: None = ...) -> int: ...  # type: ignore[misc]
     @overload
     def poisson(
-        self, lam: _ArrayLikeFloat_co = ..., size: None | _ShapeLike = ...
+        self, lam: _ArrayLikeFloat_co = ..., size: _ShapeLike | None = ...
     ) -> NDArray[int64]: ...
     @overload
     def zipf(self, a: _FloatLike_co, size: None = ...) -> int: ...  # type: ignore[misc]
     @overload
     def zipf(
-        self, a: _ArrayLikeFloat_co, size: None | _ShapeLike = ...
+        self, a: _ArrayLikeFloat_co, size: _ShapeLike | None = ...
     ) -> NDArray[int64]: ...
     @overload
     def geometric(self, p: _FloatLike_co, size: None = ...) -> int: ...  # type: ignore[misc]
     @overload
     def geometric(
-        self, p: _ArrayLikeFloat_co, size: None | _ShapeLike = ...
+        self, p: _ArrayLikeFloat_co, size: _ShapeLike | None = ...
     ) -> NDArray[int64]: ...
     @overload
     def hypergeometric(
@@ -813,19 +813,19 @@ class Generator:
         ngood: _ArrayLikeInt_co,
         nbad: _ArrayLikeInt_co,
         nsample: _ArrayLikeInt_co,
-        size: None | _ShapeLike = ...,
+        size: _ShapeLike | None = ...,
     ) -> NDArray[int64]: ...
     @overload
     def logseries(self, p: _FloatLike_co, size: None = ...) -> int: ...  # type: ignore[misc]
     @overload
     def logseries(
-        self, p: _ArrayLikeFloat_co, size: None | _ShapeLike = ...
+        self, p: _ArrayLikeFloat_co, size: _ShapeLike | None = ...
     ) -> NDArray[int64]: ...
     def multivariate_normal(
         self,
         mean: _ArrayLikeFloat_co,
         cov: _ArrayLikeFloat_co,
-        size: None | _ShapeLike = ...,
+        size: _ShapeLike | None = ...,
         check_valid: Literal["warn", "raise", "ignore"] = ...,
         tol: float = ...,
         *,
@@ -834,23 +834,23 @@ class Generator:
     def multinomial(
         self, n: _ArrayLikeInt_co,
             pvals: _ArrayLikeFloat_co,
-            size: None | _ShapeLike = ...
+            size: _ShapeLike | None = ...
     ) -> NDArray[int64]: ...
     def multivariate_hypergeometric(
         self,
         colors: _ArrayLikeInt_co,
         nsample: int,
-        size: None | _ShapeLike = ...,
+        size: _ShapeLike | None = ...,
         method: Literal["marginals", "count"] = ...,
     ) -> NDArray[int64]: ...
     def dirichlet(
-        self, alpha: _ArrayLikeFloat_co, size: None | _ShapeLike = ...
+        self, alpha: _ArrayLikeFloat_co, size: _ShapeLike | None = ...
     ) -> NDArray[float64]: ...
     def permuted(
-        self, x: ArrayLike, *, axis: None | int = ..., out: None | NDArray[Any] = ...
+        self, x: ArrayLike, *, axis: int | None = ..., out: NDArray[Any] | None = ...
     ) -> NDArray[Any]: ...
     def shuffle(self, x: ArrayLike, axis: int = ...) -> None: ...
 
 def default_rng(
-    seed: None | _ArrayLikeInt_co | SeedSequence | BitGenerator | Generator | RandomState = ...
+    seed: _ArrayLikeInt_co | SeedSequence | BitGenerator | Generator | RandomState | None = ...
 ) -> Generator: ...
diff --git a/numpy/random/_mt19937.pyi b/numpy/random/_mt19937.pyi
index 430dd8041f50..a65843154063 100644
--- a/numpy/random/_mt19937.pyi
+++ b/numpy/random/_mt19937.pyi
@@ -16,7 +16,7 @@ class _MT19937State(TypedDict):
     state: _MT19937Internal
 
 class MT19937(BitGenerator):
-    def __init__(self, seed: None | _ArrayLikeInt_co | SeedSequence = ...) -> None: ...
+    def __init__(self, seed: _ArrayLikeInt_co | SeedSequence | None = ...) -> None: ...
     def _legacy_seeding(self, seed: _ArrayLikeInt_co) -> None: ...
     def jumped(self, jumps: int = ...) -> MT19937: ...
     @property
diff --git a/numpy/random/_pcg64.pyi b/numpy/random/_pcg64.pyi
index 15bb0525c9a5..a3a6260fabfd 100644
--- a/numpy/random/_pcg64.pyi
+++ b/numpy/random/_pcg64.pyi
@@ -16,7 +16,7 @@ class _PCG64State(TypedDict):
     uinteger: int
 
 class PCG64(BitGenerator):
-    def __init__(self, seed: None | _ArrayLikeInt_co | SeedSequence = ...) -> None: ...
+    def __init__(self, seed: _ArrayLikeInt_co | SeedSequence | None = ...) -> None: ...
     def jumped(self, jumps: int = ...) -> PCG64: ...
     @property
     def state(
@@ -30,7 +30,7 @@ class PCG64(BitGenerator):
     def advance(self, delta: int) -> PCG64: ...
 
 class PCG64DXSM(BitGenerator):
-    def __init__(self, seed: None | _ArrayLikeInt_co | SeedSequence = ...) -> None: ...
+    def __init__(self, seed: _ArrayLikeInt_co | SeedSequence | None = ...) -> None: ...
     def jumped(self, jumps: int = ...) -> PCG64DXSM: ...
     @property
     def state(
diff --git a/numpy/random/_philox.pyi b/numpy/random/_philox.pyi
index 7206ae9702c0..1305a797b09a 100644
--- a/numpy/random/_philox.pyi
+++ b/numpy/random/_philox.pyi
@@ -22,9 +22,9 @@ class _PhiloxState(TypedDict):
 class Philox(BitGenerator):
     def __init__(
         self,
-        seed: None | _ArrayLikeInt_co | SeedSequence = ...,
-        counter: None | _ArrayLikeInt_co = ...,
-        key: None | _ArrayLikeInt_co = ...,
+        seed: _ArrayLikeInt_co | SeedSequence | None = ...,
+        counter: _ArrayLikeInt_co | None = ...,
+        key: _ArrayLikeInt_co | None = ...,
     ) -> None: ...
     @property
     def state(
diff --git a/numpy/random/_sfc64.pyi b/numpy/random/_sfc64.pyi
index baaae7c668fb..2f98ff9f1dda 100644
--- a/numpy/random/_sfc64.pyi
+++ b/numpy/random/_sfc64.pyi
@@ -16,7 +16,7 @@ class _SFC64State(TypedDict):
     uinteger: int
 
 class SFC64(BitGenerator):
-    def __init__(self, seed: None | _ArrayLikeInt_co | SeedSequence = ...) -> None: ...
+    def __init__(self, seed: _ArrayLikeInt_co | SeedSequence | None = ...) -> None: ...
     @property
     def state(
         self,
diff --git a/numpy/random/mtrand.pyi b/numpy/random/mtrand.pyi
index b92b292ef524..0062fa3ce657 100644
--- a/numpy/random/mtrand.pyi
+++ b/numpy/random/mtrand.pyi
@@ -44,13 +44,13 @@ from numpy._typing import (
 
 class RandomState:
     _bit_generator: BitGenerator
-    def __init__(self, seed: None | _ArrayLikeInt_co | BitGenerator = ...) -> None: ...
+    def __init__(self, seed: _ArrayLikeInt_co | BitGenerator | None = ...) -> None: ...
     def __repr__(self) -> str: ...
     def __str__(self) -> str: ...
     def __getstate__(self) -> dict[str, Any]: ...
     def __setstate__(self, state: dict[str, Any]) -> None: ...
     def __reduce__(self) -> tuple[Callable[[BitGenerator], RandomState], tuple[BitGenerator], dict[str, Any]]: ...  # noqa: E501
-    def seed(self, seed: None | _ArrayLikeFloat_co = ...) -> None: ...
+    def seed(self, seed: _ArrayLikeFloat_co | None = ...) -> None: ...
     @overload
     def get_state(self, legacy: Literal[False] = ...) -> dict[str, Any]: ...
     @overload
@@ -75,13 +75,13 @@ class RandomState:
         self,
         a: _ArrayLikeFloat_co,
         b: _ArrayLikeFloat_co,
-        size: None | _ShapeLike = ...
+        size: _ShapeLike | None = ...
     ) -> NDArray[float64]: ...
     @overload
     def exponential(self, scale: float = ..., size: None = ...) -> float: ...  # type: ignore[misc]
     @overload
     def exponential(
-        self, scale: _ArrayLikeFloat_co = ..., size: None | _ShapeLike = ...
+        self, scale: _ArrayLikeFloat_co = ..., size: _ShapeLike | None = ...
     ) -> NDArray[float64]: ...
     @overload
     def standard_exponential(self, size: None = ...) -> float: ...  # type: ignore[misc]
@@ -96,14 +96,14 @@ class RandomState:
     def randint(  # type: ignore[misc]
         self,
         low: int,
-        high: None | int = ...,
+        high: int | None = ...,
         size: None = ...,
     ) -> int: ...
     @overload
     def randint(  # type: ignore[misc]
         self,
         low: int,
-        high: None | int = ...,
+        high: int | None = ...,
         size: None = ...,
         dtype: type[bool] = ...,
     ) -> bool: ...
@@ -111,7 +111,7 @@ class RandomState:
     def randint(  # type: ignore[misc]
         self,
         low: int,
-        high: None | int = ...,
+        high: int | None = ...,
         size: None = ...,
         dtype: type[np.bool] = ...,
     ) -> np.bool: ...
@@ -119,7 +119,7 @@ class RandomState:
     def randint(  # type: ignore[misc]
         self,
         low: int,
-        high: None | int = ...,
+        high: int | None = ...,
         size: None = ...,
         dtype: type[int] = ...,
     ) -> int: ...
@@ -127,7 +127,7 @@ class RandomState:
     def randint(  # type: ignore[misc]
         self,
         low: int,
-        high: None | int = ...,
+        high: int | None = ...,
         size: None = ...,
         dtype: dtype[uint8] | type[uint8] | _UInt8Codes | _SupportsDType[dtype[uint8]] = ...,  # noqa: E501
     ) -> uint8: ...
@@ -135,7 +135,7 @@ class RandomState:
     def randint(  # type: ignore[misc]
         self,
         low: int,
-        high: None | int = ...,
+        high: int | None = ...,
         size: None = ...,
         dtype: dtype[uint16] | type[uint16] | _UInt16Codes | _SupportsDType[dtype[uint16]] = ...,  # noqa: E501
     ) -> uint16: ...
@@ -143,7 +143,7 @@ class RandomState:
     def randint(  # type: ignore[misc]
         self,
         low: int,
-        high: None | int = ...,
+        high: int | None = ...,
         size: None = ...,
         dtype: dtype[uint32] | type[uint32] | _UInt32Codes | _SupportsDType[dtype[uint32]] = ...,  # noqa: E501
     ) -> uint32: ...
@@ -151,7 +151,7 @@ class RandomState:
     def randint(  # type: ignore[misc]
         self,
         low: int,
-        high: None | int = ...,
+        high: int | None = ...,
         size: None = ...,
         dtype: dtype[uint] | type[uint] | _UIntCodes | _SupportsDType[dtype[uint]] = ...,  # noqa: E501
     ) -> uint: ...
@@ -159,7 +159,7 @@ class RandomState:
     def randint(  # type: ignore[misc]
         self,
         low: int,
-        high: None | int = ...,
+        high: int | None = ...,
         size: None = ...,
         dtype: dtype[ulong] | type[ulong] | _ULongCodes | _SupportsDType[dtype[ulong]] = ...,  # noqa: E501
     ) -> ulong: ...
@@ -167,7 +167,7 @@ class RandomState:
     def randint(  # type: ignore[misc]
         self,
         low: int,
-        high: None | int = ...,
+        high: int | None = ...,
         size: None = ...,
         dtype: dtype[uint64] | type[uint64] | _UInt64Codes | _SupportsDType[dtype[uint64]] = ...,  # noqa: E501
     ) -> uint64: ...
@@ -175,7 +175,7 @@ class RandomState:
     def randint(  # type: ignore[misc]
         self,
         low: int,
-        high: None | int = ...,
+        high: int | None = ...,
         size: None = ...,
         dtype: dtype[int8] | type[int8] | _Int8Codes | _SupportsDType[dtype[int8]] = ...,  # noqa: E501
     ) -> int8: ...
@@ -183,7 +183,7 @@ class RandomState:
     def randint(  # type: ignore[misc]
         self,
         low: int,
-        high: None | int = ...,
+        high: int | None = ...,
         size: None = ...,
         dtype: dtype[int16] | type[int16] | _Int16Codes | _SupportsDType[dtype[int16]] = ...,  # noqa: E501
     ) -> int16: ...
@@ -191,7 +191,7 @@ class RandomState:
     def randint(  # type: ignore[misc]
         self,
         low: int,
-        high: None | int = ...,
+        high: int | None = ...,
         size: None = ...,
         dtype: dtype[int32] | type[int32] | _Int32Codes | _SupportsDType[dtype[int32]] = ...,  # noqa: E501
     ) -> int32: ...
@@ -199,7 +199,7 @@ class RandomState:
     def randint(  # type: ignore[misc]
         self,
         low: int,
-        high: None | int = ...,
+        high: int | None = ...,
         size: None = ...,
         dtype: dtype[int_] | type[int_] | _IntCodes | _SupportsDType[dtype[int_]] = ...,  # noqa: E501
     ) -> int_: ...
@@ -207,7 +207,7 @@ class RandomState:
     def randint(  # type: ignore[misc]
         self,
         low: int,
-        high: None | int = ...,
+        high: int | None = ...,
         size: None = ...,
         dtype: dtype[long] | type[long] | _LongCodes | _SupportsDType[dtype[long]] = ...,  # noqa: E501
     ) -> long: ...
@@ -215,7 +215,7 @@ class RandomState:
     def randint(  # type: ignore[misc]
         self,
         low: int,
-        high: None | int = ...,
+        high: int | None = ...,
         size: None = ...,
         dtype: dtype[int64] | type[int64] | _Int64Codes | _SupportsDType[dtype[int64]] = ...,  # noqa: E501
     ) -> int64: ...
@@ -223,95 +223,95 @@ class RandomState:
     def randint(  # type: ignore[misc]
         self,
         low: _ArrayLikeInt_co,
-        high: None | _ArrayLikeInt_co = ...,
-        size: None | _ShapeLike = ...,
+        high: _ArrayLikeInt_co | None = ...,
+        size: _ShapeLike | None = ...,
     ) -> NDArray[long]: ...
     @overload
     def randint(  # type: ignore[misc]
         self,
         low: _ArrayLikeInt_co,
-        high: None | _ArrayLikeInt_co = ...,
-        size: None | _ShapeLike = ...,
+        high: _ArrayLikeInt_co | None = ...,
+        size: _ShapeLike | None = ...,
         dtype: _DTypeLikeBool = ...,
     ) -> NDArray[np.bool]: ...
     @overload
     def randint(  # type: ignore[misc]
         self,
         low: _ArrayLikeInt_co,
-        high: None | _ArrayLikeInt_co = ...,
-        size: None | _ShapeLike = ...,
+        high: _ArrayLikeInt_co | None = ...,
+        size: _ShapeLike | None = ...,
         dtype: dtype[int8] | type[int8] | _Int8Codes | _SupportsDType[dtype[int8]] = ...,  # noqa: E501
     ) -> NDArray[int8]: ...
     @overload
     def randint(  # type: ignore[misc]
         self,
         low: _ArrayLikeInt_co,
-        high: None | _ArrayLikeInt_co = ...,
-        size: None | _ShapeLike = ...,
+        high: _ArrayLikeInt_co | None = ...,
+        size: _ShapeLike | None = ...,
         dtype: dtype[int16] | type[int16] | _Int16Codes | _SupportsDType[dtype[int16]] = ...,  # noqa: E501
     ) -> NDArray[int16]: ...
     @overload
     def randint(  # type: ignore[misc]
         self,
         low: _ArrayLikeInt_co,
-        high: None | _ArrayLikeInt_co = ...,
-        size: None | _ShapeLike = ...,
+        high: _ArrayLikeInt_co | None = ...,
+        size: _ShapeLike | None = ...,
         dtype: dtype[int32] | type[int32] | _Int32Codes | _SupportsDType[dtype[int32]] = ...,  # noqa: E501
     ) -> NDArray[int32]: ...
     @overload
     def randint(  # type: ignore[misc]
         self,
         low: _ArrayLikeInt_co,
-        high: None | _ArrayLikeInt_co = ...,
-        size: None | _ShapeLike = ...,
-        dtype: None | dtype[int64] | type[int64] | _Int64Codes | _SupportsDType[dtype[int64]] = ...,  # noqa: E501
+        high: _ArrayLikeInt_co | None = ...,
+        size: _ShapeLike | None = ...,
+        dtype: dtype[int64] | type[int64] | _Int64Codes | _SupportsDType[dtype[int64]] | None = ...,  # noqa: E501
     ) -> NDArray[int64]: ...
     @overload
     def randint(  # type: ignore[misc]
         self,
         low: _ArrayLikeInt_co,
-        high: None | _ArrayLikeInt_co = ...,
-        size: None | _ShapeLike = ...,
+        high: _ArrayLikeInt_co | None = ...,
+        size: _ShapeLike | None = ...,
         dtype: dtype[uint8] | type[uint8] | _UInt8Codes | _SupportsDType[dtype[uint8]] = ...,  # noqa: E501
     ) -> NDArray[uint8]: ...
     @overload
     def randint(  # type: ignore[misc]
         self,
         low: _ArrayLikeInt_co,
-        high: None | _ArrayLikeInt_co = ...,
-        size: None | _ShapeLike = ...,
+        high: _ArrayLikeInt_co | None = ...,
+        size: _ShapeLike | None = ...,
         dtype: dtype[uint16] | type[uint16] | _UInt16Codes | _SupportsDType[dtype[uint16]] = ...,  # noqa: E501
     ) -> NDArray[uint16]: ...
     @overload
     def randint(  # type: ignore[misc]
         self,
         low: _ArrayLikeInt_co,
-        high: None | _ArrayLikeInt_co = ...,
-        size: None | _ShapeLike = ...,
+        high: _ArrayLikeInt_co | None = ...,
+        size: _ShapeLike | None = ...,
         dtype: dtype[uint32] | type[uint32] | _UInt32Codes | _SupportsDType[dtype[uint32]] = ...,  # noqa: E501
     ) -> NDArray[uint32]: ...
     @overload
     def randint(  # type: ignore[misc]
         self,
         low: _ArrayLikeInt_co,
-        high: None | _ArrayLikeInt_co = ...,
-        size: None | _ShapeLike = ...,
+        high: _ArrayLikeInt_co | None = ...,
+        size: _ShapeLike | None = ...,
         dtype: dtype[uint64] | type[uint64] | _UInt64Codes | _SupportsDType[dtype[uint64]] = ...,  # noqa: E501
     ) -> NDArray[uint64]: ...
     @overload
     def randint(  # type: ignore[misc]
         self,
         low: _ArrayLikeInt_co,
-        high: None | _ArrayLikeInt_co = ...,
-        size: None | _ShapeLike = ...,
+        high: _ArrayLikeInt_co | None = ...,
+        size: _ShapeLike | None = ...,
         dtype: dtype[long] | type[int] | type[long] | _LongCodes | _SupportsDType[dtype[long]] = ...,  # noqa: E501
     ) -> NDArray[long]: ...
     @overload
     def randint(  # type: ignore[misc]
         self,
         low: _ArrayLikeInt_co,
-        high: None | _ArrayLikeInt_co = ...,
-        size: None | _ShapeLike = ...,
+        high: _ArrayLikeInt_co | None = ...,
+        size: _ShapeLike | None = ...,
         dtype: dtype[ulong] | type[ulong] | _ULongCodes | _SupportsDType[dtype[ulong]] = ...,  # noqa: E501
     ) -> NDArray[ulong]: ...
     def bytes(self, length: int) -> builtins.bytes: ...
@@ -321,7 +321,7 @@ class RandomState:
         a: int,
         size: None = ...,
         replace: bool = ...,
-        p: None | _ArrayLikeFloat_co = ...,
+        p: _ArrayLikeFloat_co | None = ...,
     ) -> int: ...
     @overload
     def choice(
@@ -329,7 +329,7 @@ class RandomState:
         a: int,
         size: _ShapeLike = ...,
         replace: bool = ...,
-        p: None | _ArrayLikeFloat_co = ...,
+        p: _ArrayLikeFloat_co | None = ...,
     ) -> NDArray[long]: ...
     @overload
     def choice(
@@ -337,7 +337,7 @@ class RandomState:
         a: ArrayLike,
         size: None = ...,
         replace: bool = ...,
-        p: None | _ArrayLikeFloat_co = ...,
+        p: _ArrayLikeFloat_co | None = ...,
     ) -> Any: ...
     @overload
     def choice(
@@ -345,7 +345,7 @@ class RandomState:
         a: ArrayLike,
         size: _ShapeLike = ...,
         replace: bool = ...,
-        p: None | _ArrayLikeFloat_co = ...,
+        p: _ArrayLikeFloat_co | None = ...,
     ) -> NDArray[Any]: ...
     @overload
     def uniform(
@@ -356,7 +356,7 @@ class RandomState:
         self,
         low: _ArrayLikeFloat_co = ...,
         high: _ArrayLikeFloat_co = ...,
-        size: None | _ShapeLike = ...,
+        size: _ShapeLike | None = ...,
     ) -> NDArray[float64]: ...
     @overload
     def rand(self) -> float: ...
@@ -368,14 +368,14 @@ class RandomState:
     def randn(self, *args: int) -> NDArray[float64]: ...
     @overload
     def random_integers(
-        self, low: int, high: None | int = ..., size: None = ...
+        self, low: int, high: int | None = ..., size: None = ...
     ) -> int: ...  # type: ignore[misc]
     @overload
     def random_integers(
         self,
         low: _ArrayLikeInt_co,
-        high: None | _ArrayLikeInt_co = ...,
-        size: None | _ShapeLike = ...,
+        high: _ArrayLikeInt_co | None = ...,
+        size: _ShapeLike | None = ...,
     ) -> NDArray[long]: ...
     @overload
     def standard_normal(self, size: None = ...) -> float: ...  # type: ignore[misc]
@@ -392,7 +392,7 @@ class RandomState:
         self,
         loc: _ArrayLikeFloat_co = ...,
         scale: _ArrayLikeFloat_co = ...,
-        size: None | _ShapeLike = ...,
+        size: _ShapeLike | None = ...,
     ) -> NDArray[float64]: ...
     @overload
     def standard_gamma(  # type: ignore[misc]
@@ -404,7 +404,7 @@ class RandomState:
     def standard_gamma(
         self,
         shape: _ArrayLikeFloat_co,
-        size: None | _ShapeLike = ...,
+        size: _ShapeLike | None = ...,
     ) -> NDArray[float64]: ...
     @overload
     def gamma(self, shape: float, scale: float = ..., size: None = ...) -> float: ...  # type: ignore[misc]
@@ -413,7 +413,7 @@ class RandomState:
         self,
         shape: _ArrayLikeFloat_co,
         scale: _ArrayLikeFloat_co = ...,
-        size: None | _ShapeLike = ...,
+        size: _ShapeLike | None = ...,
     ) -> NDArray[float64]: ...
     @overload
     def f(self, dfnum: float, dfden: float, size: None = ...) -> float: ...  # type: ignore[misc]
@@ -422,7 +422,7 @@ class RandomState:
         self,
         dfnum: _ArrayLikeFloat_co,
         dfden: _ArrayLikeFloat_co,
-        size: None | _ShapeLike = ...
+        size: _ShapeLike | None = ...
     ) -> NDArray[float64]: ...
     @overload
     def noncentral_f(
@@ -434,13 +434,13 @@ class RandomState:
         dfnum: _ArrayLikeFloat_co,
         dfden: _ArrayLikeFloat_co,
         nonc: _ArrayLikeFloat_co,
-        size: None | _ShapeLike = ...,
+        size: _ShapeLike | None = ...,
     ) -> NDArray[float64]: ...
     @overload
     def chisquare(self, df: float, size: None = ...) -> float: ...  # type: ignore[misc]
     @overload
     def chisquare(
-        self, df: _ArrayLikeFloat_co, size: None | _ShapeLike = ...
+        self, df: _ArrayLikeFloat_co, size: _ShapeLike | None = ...
     ) -> NDArray[float64]: ...
     @overload
     def noncentral_chisquare(
@@ -451,7 +451,7 @@ class RandomState:
         self,
         df: _ArrayLikeFloat_co,
         nonc: _ArrayLikeFloat_co,
-        size: None | _ShapeLike = ...
+        size: _ShapeLike | None = ...
     ) -> NDArray[float64]: ...
     @overload
     def standard_t(self, df: float, size: None = ...) -> float: ...  # type: ignore[misc]
@@ -470,25 +470,25 @@ class RandomState:
         self,
         mu: _ArrayLikeFloat_co,
         kappa: _ArrayLikeFloat_co,
-        size: None | _ShapeLike = ...
+        size: _ShapeLike | None = ...
     ) -> NDArray[float64]: ...
     @overload
     def pareto(self, a: float, size: None = ...) -> float: ...  # type: ignore[misc]
     @overload
     def pareto(
-        self, a: _ArrayLikeFloat_co, size: None | _ShapeLike = ...
+        self, a: _ArrayLikeFloat_co, size: _ShapeLike | None = ...
     ) -> NDArray[float64]: ...
     @overload
     def weibull(self, a: float, size: None = ...) -> float: ...  # type: ignore[misc]
     @overload
     def weibull(
-        self, a: _ArrayLikeFloat_co, size: None | _ShapeLike = ...
+        self, a: _ArrayLikeFloat_co, size: _ShapeLike | None = ...
     ) -> NDArray[float64]: ...
     @overload
     def power(self, a: float, size: None = ...) -> float: ...  # type: ignore[misc]
     @overload
     def power(
-        self, a: _ArrayLikeFloat_co, size: None | _ShapeLike = ...
+        self, a: _ArrayLikeFloat_co, size: _ShapeLike | None = ...
     ) -> NDArray[float64]: ...
     @overload
     def standard_cauchy(self, size: None = ...) -> float: ...  # type: ignore[misc]
@@ -503,7 +503,7 @@ class RandomState:
         self,
         loc: _ArrayLikeFloat_co = ...,
         scale: _ArrayLikeFloat_co = ...,
-        size: None | _ShapeLike = ...,
+        size: _ShapeLike | None = ...,
     ) -> NDArray[float64]: ...
     @overload
     def gumbel(
@@ -514,7 +514,7 @@ class RandomState:
         self,
         loc: _ArrayLikeFloat_co = ...,
         scale: _ArrayLikeFloat_co = ...,
-        size: None | _ShapeLike = ...,
+        size: _ShapeLike | None = ...,
     ) -> NDArray[float64]: ...
     @overload
     def logistic(
@@ -525,7 +525,7 @@ class RandomState:
         self,
         loc: _ArrayLikeFloat_co = ...,
         scale: _ArrayLikeFloat_co = ...,
-        size: None | _ShapeLike = ...,
+        size: _ShapeLike | None = ...,
     ) -> NDArray[float64]: ...
     @overload
     def lognormal(
@@ -536,13 +536,13 @@ class RandomState:
         self,
         mean: _ArrayLikeFloat_co = ...,
         sigma: _ArrayLikeFloat_co = ...,
-        size: None | _ShapeLike = ...,
+        size: _ShapeLike | None = ...,
     ) -> NDArray[float64]: ...
     @overload
     def rayleigh(self, scale: float = ..., size: None = ...) -> float: ...  # type: ignore[misc]
     @overload
     def rayleigh(
-        self, scale: _ArrayLikeFloat_co = ..., size: None | _ShapeLike = ...
+        self, scale: _ArrayLikeFloat_co = ..., size: _ShapeLike | None = ...
     ) -> NDArray[float64]: ...
     @overload
     def wald(self, mean: float, scale: float, size: None = ...) -> float: ...  # type: ignore[misc]
@@ -551,7 +551,7 @@ class RandomState:
         self,
         mean: _ArrayLikeFloat_co,
         scale: _ArrayLikeFloat_co,
-        size: None | _ShapeLike = ...
+        size: _ShapeLike | None = ...
     ) -> NDArray[float64]: ...
     @overload
     def triangular(
@@ -563,7 +563,7 @@ class RandomState:
         left: _ArrayLikeFloat_co,
         mode: _ArrayLikeFloat_co,
         right: _ArrayLikeFloat_co,
-        size: None | _ShapeLike = ...,
+        size: _ShapeLike | None = ...,
     ) -> NDArray[float64]: ...
     @overload
     def binomial(
@@ -571,7 +571,7 @@ class RandomState:
     ) -> int: ...  # type: ignore[misc]
     @overload
     def binomial(
-        self, n: _ArrayLikeInt_co, p: _ArrayLikeFloat_co, size: None | _ShapeLike = ...
+        self, n: _ArrayLikeInt_co, p: _ArrayLikeFloat_co, size: _ShapeLike | None = ...
     ) -> NDArray[long]: ...
     @overload
     def negative_binomial(
@@ -582,7 +582,7 @@ class RandomState:
         self,
         n: _ArrayLikeFloat_co,
         p: _ArrayLikeFloat_co,
-        size: None | _ShapeLike = ...
+        size: _ShapeLike | None = ...
     ) -> NDArray[long]: ...
     @overload
     def poisson(
@@ -590,19 +590,19 @@ class RandomState:
     ) -> int: ...  # type: ignore[misc]
     @overload
     def poisson(
-        self, lam: _ArrayLikeFloat_co = ..., size: None | _ShapeLike = ...
+        self, lam: _ArrayLikeFloat_co = ..., size: _ShapeLike | None = ...
     ) -> NDArray[long]: ...
     @overload
     def zipf(self, a: float, size: None = ...) -> int: ...  # type: ignore[misc]
     @overload
     def zipf(
-        self, a: _ArrayLikeFloat_co, size: None | _ShapeLike = ...
+        self, a: _ArrayLikeFloat_co, size: _ShapeLike | None = ...
     ) -> NDArray[long]: ...
     @overload
     def geometric(self, p: float, size: None = ...) -> int: ...  # type: ignore[misc]
     @overload
     def geometric(
-        self, p: _ArrayLikeFloat_co, size: None | _ShapeLike = ...
+        self, p: _ArrayLikeFloat_co, size: _ShapeLike | None = ...
     ) -> NDArray[long]: ...
     @overload
     def hypergeometric(
@@ -614,29 +614,29 @@ class RandomState:
         ngood: _ArrayLikeInt_co,
         nbad: _ArrayLikeInt_co,
         nsample: _ArrayLikeInt_co,
-        size: None | _ShapeLike = ...,
+        size: _ShapeLike | None = ...,
     ) -> NDArray[long]: ...
     @overload
     def logseries(self, p: float, size: None = ...) -> int: ...  # type: ignore[misc]
     @overload
     def logseries(
-        self, p: _ArrayLikeFloat_co, size: None | _ShapeLike = ...
+        self, p: _ArrayLikeFloat_co, size: _ShapeLike | None = ...
     ) -> NDArray[long]: ...
     def multivariate_normal(
         self,
         mean: _ArrayLikeFloat_co,
         cov: _ArrayLikeFloat_co,
-        size: None | _ShapeLike = ...,
+        size: _ShapeLike | None = ...,
         check_valid: Literal["warn", "raise", "ignore"] = ...,
         tol: float = ...,
     ) -> NDArray[float64]: ...
     def multinomial(
         self, n: _ArrayLikeInt_co,
         pvals: _ArrayLikeFloat_co,
-        size: None | _ShapeLike = ...
+        size: _ShapeLike | None = ...
     ) -> NDArray[long]: ...
     def dirichlet(
-        self, alpha: _ArrayLikeFloat_co, size: None | _ShapeLike = ...
+        self, alpha: _ArrayLikeFloat_co, size: _ShapeLike | None = ...
     ) -> NDArray[float64]: ...
     def shuffle(self, x: ArrayLike) -> None: ...
     @overload
diff --git a/numpy/typing/tests/data/pass/array_like.py b/numpy/typing/tests/data/pass/array_like.py
index 730eb46d1c92..fe0f9558ca12 100644
--- a/numpy/typing/tests/data/pass/array_like.py
+++ b/numpy/typing/tests/data/pass/array_like.py
@@ -23,7 +23,7 @@
 
 class A:
     def __array__(
-        self, dtype: None | np.dtype[Any] = None
+        self, dtype: np.dtype[Any] | None = None
     ) -> NDArray[np.float64]:
         return np.array([1.0, 2.0, 3.0])
 
diff --git a/numpy/typing/tests/data/reveal/arrayterator.pyi b/numpy/typing/tests/data/reveal/arrayterator.pyi
index 0e6e38a86eda..4484cf785139 100644
--- a/numpy/typing/tests/data/reveal/arrayterator.pyi
+++ b/numpy/typing/tests/data/reveal/arrayterator.pyi
@@ -8,7 +8,7 @@ AR_i8: npt.NDArray[np.int64]
 ar_iter = np.lib.Arrayterator(AR_i8)
 
 assert_type(ar_iter.var, npt.NDArray[np.int64])
-assert_type(ar_iter.buf_size, None | int)
+assert_type(ar_iter.buf_size, int | None)
 assert_type(ar_iter.start, list[int])
 assert_type(ar_iter.stop, list[int])
 assert_type(ar_iter.step, list[int])
diff --git a/numpy/typing/tests/data/reveal/dtype.pyi b/numpy/typing/tests/data/reveal/dtype.pyi
index 4a47d1e23221..f7581a305503 100644
--- a/numpy/typing/tests/data/reveal/dtype.pyi
+++ b/numpy/typing/tests/data/reveal/dtype.pyi
@@ -108,11 +108,11 @@ assert_type(np.dtype("|T"), StringDType)
 
 # Methods and attributes
 assert_type(dtype_U.base, np.dtype[Any])
-assert_type(dtype_U.subdtype, None | tuple[np.dtype[Any], tuple[int, ...]])
+assert_type(dtype_U.subdtype, tuple[np.dtype[Any], tuple[int, ...]] | None)
 assert_type(dtype_U.newbyteorder(), np.dtype[np.str_])
 assert_type(dtype_U.type, type[np.str_])
 assert_type(dtype_U.name, LiteralString)
-assert_type(dtype_U.names, None | tuple[str, ...])
+assert_type(dtype_U.names, tuple[str, ...] | None)
 
 assert_type(dtype_U * 0, np.dtype[np.str_])
 assert_type(dtype_U * 1, np.dtype[np.str_])
diff --git a/numpy/typing/tests/data/reveal/lib_function_base.pyi b/numpy/typing/tests/data/reveal/lib_function_base.pyi
index 9f3e01ddc740..4b76f891f23d 100644
--- a/numpy/typing/tests/data/reveal/lib_function_base.pyi
+++ b/numpy/typing/tests/data/reveal/lib_function_base.pyi
@@ -35,10 +35,10 @@ def func(
 
 assert_type(vectorized_func.pyfunc, Callable[..., Any])
 assert_type(vectorized_func.cache, bool)
-assert_type(vectorized_func.signature, None | str)
-assert_type(vectorized_func.otypes, None | str)
+assert_type(vectorized_func.signature, str | None)
+assert_type(vectorized_func.otypes, str | None)
 assert_type(vectorized_func.excluded, set[int | str])
-assert_type(vectorized_func.__doc__, None | str)
+assert_type(vectorized_func.__doc__, str | None)
 assert_type(vectorized_func([1]), Any)
 assert_type(np.vectorize(int), np.vectorize)
 assert_type(
diff --git a/numpy/typing/tests/data/reveal/npyio.pyi b/numpy/typing/tests/data/reveal/npyio.pyi
index 5ab1ed749a08..40da72c8544e 100644
--- a/numpy/typing/tests/data/reveal/npyio.pyi
+++ b/numpy/typing/tests/data/reveal/npyio.pyi
@@ -29,10 +29,10 @@ bytes_writer: BytesWriter
 bytes_reader: BytesReader
 
 assert_type(npz_file.zip, zipfile.ZipFile)
-assert_type(npz_file.fid, None | IO[str])
+assert_type(npz_file.fid, IO[str] | None)
 assert_type(npz_file.files, list[str])
 assert_type(npz_file.allow_pickle, bool)
-assert_type(npz_file.pickle_kwargs, None | Mapping[str, Any])
+assert_type(npz_file.pickle_kwargs, Mapping[str, Any] | None)
 assert_type(npz_file.f, BagObj[np.lib.npyio.NpzFile])
 assert_type(npz_file["test"], npt.NDArray[Any])
 assert_type(len(npz_file), int)
diff --git a/numpy/typing/tests/data/reveal/random.pyi b/numpy/typing/tests/data/reveal/random.pyi
index dc2d71e81dcb..e188eb02893f 100644
--- a/numpy/typing/tests/data/reveal/random.pyi
+++ b/numpy/typing/tests/data/reveal/random.pyi
@@ -72,7 +72,7 @@ assert_type(sfc64_raw_arr, npt.NDArray[np.uint64])
 assert_type(sfc64.lock, threading.Lock)
 
 assert_type(seed_seq.pool, npt.NDArray[np.uint32])
-assert_type(seed_seq.entropy, None | int | Sequence[int])
+assert_type(seed_seq.entropy, int | Sequence[int] | None)
 assert_type(seed_seq.spawn(1), list[np.random.SeedSequence])
 assert_type(seed_seq.generate_state(8, "uint32"), npt.NDArray[np.uint32 | np.uint64])
 assert_type(seed_seq.generate_state(8, "uint64"), npt.NDArray[np.uint32 | np.uint64])
diff --git a/numpy/typing/tests/data/reveal/testing.pyi b/numpy/typing/tests/data/reveal/testing.pyi
index edadd15bcc12..e0eae7f42ecc 100644
--- a/numpy/typing/tests/data/reveal/testing.pyi
+++ b/numpy/typing/tests/data/reveal/testing.pyi
@@ -76,7 +76,7 @@ assert_type(np.testing.assert_(2, msg=lambda: "test"), None)
 if sys.platform == "win32" or sys.platform == "cygwin":
     assert_type(np.testing.memusage(), int)
 elif sys.platform == "linux":
-    assert_type(np.testing.memusage(), None | int)
+    assert_type(np.testing.memusage(), int | None)
 
 assert_type(np.testing.jiffies(), int)
 
diff --git a/numpy/typing/tests/data/reveal/ufunc_config.pyi b/numpy/typing/tests/data/reveal/ufunc_config.pyi
index 4d0fc56911f9..748507530aa1 100644
--- a/numpy/typing/tests/data/reveal/ufunc_config.pyi
+++ b/numpy/typing/tests/data/reveal/ufunc_config.pyi
@@ -22,9 +22,9 @@ assert_type(np.geterr(), np._core._ufunc_config._ErrDict)
 assert_type(np.setbufsize(4096), int)
 assert_type(np.getbufsize(), int)
 
-assert_type(np.seterrcall(func), Callable[[str, int], Any] | None | SupportsWrite[str])
-assert_type(np.seterrcall(Write()), Callable[[str, int], Any] | None | SupportsWrite[str])
-assert_type(np.geterrcall(), Callable[[str, int], Any] | None | SupportsWrite[str])
+assert_type(np.seterrcall(func), Callable[[str, int], Any] | SupportsWrite[str] | None)
+assert_type(np.seterrcall(Write()), Callable[[str, int], Any] | SupportsWrite[str] | None)
+assert_type(np.geterrcall(), Callable[[str, int], Any] | SupportsWrite[str] | None)
 
 assert_type(np.errstate(call=func, all="call"), np.errstate)
 assert_type(np.errstate(call=Write(), divide="log", over="log"), np.errstate)
diff --git a/numpy/typing/tests/test_runtime.py b/numpy/typing/tests/test_runtime.py
index c32c5db3266a..a249472d5b3f 100644
--- a/numpy/typing/tests/test_runtime.py
+++ b/numpy/typing/tests/test_runtime.py
@@ -20,7 +20,7 @@
 class TypeTup(NamedTuple):
     typ: type
     args: tuple[type, ...]
-    origin: None | type
+    origin: type | None
 
 
 NDArrayTup = TypeTup(npt.NDArray, npt.NDArray.__args__, np.ndarray)
diff --git a/numpy/typing/tests/test_typing.py b/numpy/typing/tests/test_typing.py
index f7cab5a7a9fb..c1e708c876e5 100644
--- a/numpy/typing/tests/test_typing.py
+++ b/numpy/typing/tests/test_typing.py
@@ -195,7 +195,7 @@ def _test_fail(
     path: str,
     expression: str,
     error: str,
-    expected_error: None | str,
+    expected_error: str | None,
     lineno: int,
 ) -> None:
     if expected_error is None:

From fb55d0bb69c6c43d698a793aad0fa881c13b76a8 Mon Sep 17 00:00:00 2001
From: jorenham 
Date: Thu, 24 Apr 2025 19:14:26 +0200
Subject: [PATCH 093/202] TYP: simplify redundant unions of builtin scalar
 types

---
 numpy/_core/fromnumeric.pyi              |  2 +-
 numpy/_core/numeric.pyi                  |  4 +---
 numpy/lib/_twodim_base_impl.pyi          | 22 +++++++++++-----------
 numpy/typing/tests/data/reveal/dtype.pyi |  6 +++---
 4 files changed, 16 insertions(+), 18 deletions(-)

diff --git a/numpy/_core/fromnumeric.pyi b/numpy/_core/fromnumeric.pyi
index 138fe8809110..b16994085308 100644
--- a/numpy/_core/fromnumeric.pyi
+++ b/numpy/_core/fromnumeric.pyi
@@ -122,7 +122,7 @@ class _SupportsShape(Protocol[_ShapeT_co]):
 _T = TypeVar("_T")
 _PyArray: TypeAlias = list[_T] | tuple[_T, ...]
 # `int` also covers `bool`
-_PyScalar: TypeAlias = float | complex | bytes | str
+_PyScalar: TypeAlias = complex | bytes | str
 
 @overload
 def take(
diff --git a/numpy/_core/numeric.pyi b/numpy/_core/numeric.pyi
index 0a0c70d80a50..b9fddcef5b6c 100644
--- a/numpy/_core/numeric.pyi
+++ b/numpy/_core/numeric.pyi
@@ -784,9 +784,7 @@ def fromfunction(
     **kwargs: Any,
 ) -> _T: ...
 
-def isscalar(element: object) -> TypeGuard[
-    generic | bool | int | float | complex | str | bytes | memoryview
-]: ...
+def isscalar(element: object) -> TypeGuard[generic | complex | str | bytes | memoryview]: ...
 
 def binary_repr(num: SupportsIndex, width: int | None = ...) -> str: ...
 
diff --git a/numpy/lib/_twodim_base_impl.pyi b/numpy/lib/_twodim_base_impl.pyi
index 9867f59f9409..b9a199c76616 100644
--- a/numpy/lib/_twodim_base_impl.pyi
+++ b/numpy/lib/_twodim_base_impl.pyi
@@ -269,8 +269,8 @@ def histogram2d(
 ]: ...
 @overload
 def histogram2d(
-    x: _ArrayLike1DInt_co | Sequence[float | int],
-    y: _ArrayLike1DInt_co | Sequence[float | int],
+    x: _ArrayLike1DInt_co | Sequence[float],
+    y: _ArrayLike1DInt_co | Sequence[float],
     bins: int | Sequence[int] = ...,
     range: _ArrayLike2DFloat_co | None = ...,
     density: bool | None = ...,
@@ -282,8 +282,8 @@ def histogram2d(
 ]: ...
 @overload
 def histogram2d(
-    x: Sequence[complex | float | int],
-    y: Sequence[complex | float | int],
+    x: Sequence[complex],
+    y: Sequence[complex],
     bins: int | Sequence[int] = ...,
     range: _ArrayLike2DFloat_co | None = ...,
     density: bool | None = ...,
@@ -321,8 +321,8 @@ def histogram2d(
 ]: ...
 @overload
 def histogram2d(
-    x: _ArrayLike1DInt_co | Sequence[float | int],
-    y: _ArrayLike1DInt_co | Sequence[float | int],
+    x: _ArrayLike1DInt_co | Sequence[float],
+    y: _ArrayLike1DInt_co | Sequence[float],
     bins: Sequence[_ArrayLike1D[_NumberCoT] | int],
     range: _ArrayLike2DFloat_co | None = ...,
     density: bool | None = ...,
@@ -334,8 +334,8 @@ def histogram2d(
 ]: ...
 @overload
 def histogram2d(
-    x: Sequence[complex | float | int],
-    y: Sequence[complex | float | int],
+    x: Sequence[complex],
+    y: Sequence[complex],
     bins: Sequence[_ArrayLike1D[_NumberCoT] | int],
     range: _ArrayLike2DFloat_co | None = ...,
     density: bool | None = ...,
@@ -362,7 +362,7 @@ def histogram2d(
 def histogram2d(
     x: _ArrayLike1DNumber_co,
     y: _ArrayLike1DNumber_co,
-    bins: Sequence[Sequence[int | bool]],
+    bins: Sequence[Sequence[int]],
     range: _ArrayLike2DFloat_co | None = ...,
     density: bool | None = ...,
     weights: _ArrayLike1DFloat_co | None = ...,
@@ -375,7 +375,7 @@ def histogram2d(
 def histogram2d(
     x: _ArrayLike1DNumber_co,
     y: _ArrayLike1DNumber_co,
-    bins: Sequence[Sequence[float | int | bool]],
+    bins: Sequence[Sequence[float]],
     range: _ArrayLike2DFloat_co | None = ...,
     density: bool | None = ...,
     weights: _ArrayLike1DFloat_co | None = ...,
@@ -388,7 +388,7 @@ def histogram2d(
 def histogram2d(
     x: _ArrayLike1DNumber_co,
     y: _ArrayLike1DNumber_co,
-    bins: Sequence[Sequence[complex | float | int | bool]],
+    bins: Sequence[Sequence[complex]],
     range: _ArrayLike2DFloat_co | None = ...,
     density: bool | None = ...,
     weights: _ArrayLike1DFloat_co | None = ...,
diff --git a/numpy/typing/tests/data/reveal/dtype.pyi b/numpy/typing/tests/data/reveal/dtype.pyi
index f7581a305503..50a7be4b2547 100644
--- a/numpy/typing/tests/data/reveal/dtype.pyi
+++ b/numpy/typing/tests/data/reveal/dtype.pyi
@@ -14,9 +14,9 @@ dtype_U: np.dtype[np.str_]
 dtype_V: np.dtype[np.void]
 dtype_i8: np.dtype[np.int64]
 
-py_int_co: type[int | bool]
-py_float_co: type[float | int | bool]
-py_complex_co: type[complex | float | int | bool]
+py_int_co: type[int]
+py_float_co: type[float]
+py_complex_co: type[complex]
 py_object: type[_PyObjectLike]
 py_character: type[str | bytes]
 py_flexible: type[str | bytes | memoryview]

From a0b54f6163b922c9367d2dca5432b2209be1de47 Mon Sep 17 00:00:00 2001
From: jorenham 
Date: Thu, 24 Apr 2025 03:39:35 +0200
Subject: [PATCH 094/202] TYP: replace ``_Self`` type parameters with
 ``typing.Self``

---
 numpy/polynomial/_polybase.pyi  | 136 ++++++++++++++------------------
 numpy/polynomial/_polytypes.pyi |  23 +++---
 numpy/polynomial/chebyshev.pyi  |  31 +++-----
 3 files changed, 80 insertions(+), 110 deletions(-)

diff --git a/numpy/polynomial/_polybase.pyi b/numpy/polynomial/_polybase.pyi
index edbe4c8db980..7923faf2c256 100644
--- a/numpy/polynomial/_polybase.pyi
+++ b/numpy/polynomial/_polybase.pyi
@@ -2,49 +2,28 @@ import abc
 import decimal
 import numbers
 from collections.abc import Iterator, Mapping, Sequence
-from typing import (
-    Any,
-    ClassVar,
-    Final,
-    Generic,
-    Literal,
-    LiteralString,
-    SupportsIndex,
-    TypeAlias,
-    TypeGuard,
-    overload,
-)
+from typing import Any, ClassVar, Final, Generic, Literal, LiteralString, Self, SupportsIndex, TypeAlias, overload
+
+from typing_extensions import TypeIs, TypeVar
 
 import numpy as np
 import numpy.typing as npt
-from numpy._typing import (
-    _FloatLike_co,
-    _NumberLike_co,
-
-    _ArrayLikeFloat_co,
-    _ArrayLikeComplex_co,
-)
+from numpy._typing import _ArrayLikeComplex_co, _ArrayLikeFloat_co, _FloatLike_co, _NumberLike_co
 
 from ._polytypes import (
     _AnyInt,
-    _CoefLike_co,
-
     _Array2,
-    _Tuple2,
-
-    _Series,
+    _ArrayLikeCoef_co,
+    _ArrayLikeCoefObject_co,
+    _CoefLike_co,
     _CoefSeries,
-
-    _SeriesLikeInt_co,
+    _Series,
     _SeriesLikeCoef_co,
-
-    _ArrayLikeCoefObject_co,
-    _ArrayLikeCoef_co,
+    _SeriesLikeInt_co,
+    _Tuple2,
 )
 
-from typing_extensions import TypeVar
-
-__all__: Final[Sequence[str]] = ("ABCPolyBase",)
+__all__ = ["ABCPolyBase"]
 
 _NameCo = TypeVar(
     "_NameCo",
@@ -52,14 +31,13 @@ _NameCo = TypeVar(
     covariant=True,
     default=LiteralString | None
 )
-_Self = TypeVar("_Self")
 _Other = TypeVar("_Other", bound=ABCPolyBase)
 
 _AnyOther: TypeAlias = ABCPolyBase | _CoefLike_co | _SeriesLikeCoef_co
 _Hundred: TypeAlias = Literal[100]
 
 class ABCPolyBase(Generic[_NameCo], abc.ABC):
-    __hash__: ClassVar[None]  # type: ignore[assignment]
+    __hash__: ClassVar[None]  # type: ignore[assignment]  # pyright: ignore[reportIncompatibleMethodOverride]
     __array_ufunc__: ClassVar[None]
 
     maxpower: ClassVar[_Hundred]
@@ -123,23 +101,23 @@ class ABCPolyBase(Generic[_NameCo], abc.ABC):
     def __format__(self, fmt_str: str, /) -> str: ...
     def __eq__(self, x: object, /) -> bool: ...
     def __ne__(self, x: object, /) -> bool: ...
-    def __neg__(self: _Self, /) -> _Self: ...
-    def __pos__(self: _Self, /) -> _Self: ...
-    def __add__(self: _Self, x: _AnyOther, /) -> _Self: ...
-    def __sub__(self: _Self, x: _AnyOther, /) -> _Self: ...
-    def __mul__(self: _Self, x: _AnyOther, /) -> _Self: ...
-    def __truediv__(self: _Self, x: _AnyOther, /) -> _Self: ...
-    def __floordiv__(self: _Self, x: _AnyOther, /) -> _Self: ...
-    def __mod__(self: _Self, x: _AnyOther, /) -> _Self: ...
-    def __divmod__(self: _Self, x: _AnyOther, /) -> _Tuple2[_Self]: ...
-    def __pow__(self: _Self, x: _AnyOther, /) -> _Self: ...
-    def __radd__(self: _Self, x: _AnyOther, /) -> _Self: ...
-    def __rsub__(self: _Self, x: _AnyOther, /) -> _Self: ...
-    def __rmul__(self: _Self, x: _AnyOther, /) -> _Self: ...
-    def __rtruediv__(self: _Self, x: _AnyOther, /) -> _Self: ...
-    def __rfloordiv__(self: _Self, x: _AnyOther, /) -> _Self: ...
-    def __rmod__(self: _Self, x: _AnyOther, /) -> _Self: ...
-    def __rdivmod__(self: _Self, x: _AnyOther, /) -> _Tuple2[_Self]: ...
+    def __neg__(self, /) -> Self: ...
+    def __pos__(self, /) -> Self: ...
+    def __add__(self, x: _AnyOther, /) -> Self: ...
+    def __sub__(self, x: _AnyOther, /) -> Self: ...
+    def __mul__(self, x: _AnyOther, /) -> Self: ...
+    def __truediv__(self, x: _AnyOther, /) -> Self: ...
+    def __floordiv__(self, x: _AnyOther, /) -> Self: ...
+    def __mod__(self, x: _AnyOther, /) -> Self: ...
+    def __divmod__(self, x: _AnyOther, /) -> _Tuple2[Self]: ...
+    def __pow__(self, x: _AnyOther, /) -> Self: ...
+    def __radd__(self, x: _AnyOther, /) -> Self: ...
+    def __rsub__(self, x: _AnyOther, /) -> Self: ...
+    def __rmul__(self, x: _AnyOther, /) -> Self: ...
+    def __rtruediv__(self, x: _AnyOther, /) -> Self: ...
+    def __rfloordiv__(self, x: _AnyOther, /) -> Self: ...
+    def __rmod__(self, x: _AnyOther, /) -> Self: ...
+    def __rdivmod__(self, x: _AnyOther, /) -> _Tuple2[Self]: ...
     def __len__(self, /) -> int: ...
     def __iter__(self, /) -> Iterator[np.inexact[Any] | object]: ...
     def __getstate__(self, /) -> dict[str, Any]: ...
@@ -149,22 +127,22 @@ class ABCPolyBase(Generic[_NameCo], abc.ABC):
     def has_samedomain(self, /, other: ABCPolyBase) -> bool: ...
     def has_samewindow(self, /, other: ABCPolyBase) -> bool: ...
     @overload
-    def has_sametype(self: _Self, /, other: ABCPolyBase) -> TypeGuard[_Self]: ...
+    def has_sametype(self, /, other: ABCPolyBase) -> TypeIs[Self]: ...
     @overload
     def has_sametype(self, /, other: object) -> Literal[False]: ...
 
-    def copy(self: _Self, /) -> _Self: ...
+    def copy(self, /) -> Self: ...
     def degree(self, /) -> int: ...
-    def cutdeg(self: _Self, /) -> _Self: ...
-    def trim(self: _Self, /, tol: _FloatLike_co = ...) -> _Self: ...
-    def truncate(self: _Self, /, size: _AnyInt) -> _Self: ...
+    def cutdeg(self, /) -> Self: ...
+    def trim(self, /, tol: _FloatLike_co = ...) -> Self: ...
+    def truncate(self, /, size: _AnyInt) -> Self: ...
 
     @overload
     def convert(
         self,
+        /,
         domain: _SeriesLikeCoef_co | None,
         kind: type[_Other],
-        /,
         window: _SeriesLikeCoef_co | None = ...,
     ) -> _Other: ...
     @overload
@@ -178,28 +156,30 @@ class ABCPolyBase(Generic[_NameCo], abc.ABC):
     ) -> _Other: ...
     @overload
     def convert(
-        self: _Self,
+        self,
         /,
         domain: _SeriesLikeCoef_co | None = ...,
-        kind: type[_Self] | None = ...,
+        kind: None = None,
         window: _SeriesLikeCoef_co | None = ...,
-    ) -> _Self: ...
+    ) -> Self: ...
 
     def mapparms(self, /) -> _Tuple2[Any]: ...
 
     def integ(
-        self: _Self, /,
+        self,
+        /,
         m: SupportsIndex = ...,
         k: _CoefLike_co | _SeriesLikeCoef_co = ...,
         lbnd: _CoefLike_co | None = ...,
-    ) -> _Self: ...
+    ) -> Self: ...
 
-    def deriv(self: _Self, /, m: SupportsIndex = ...) -> _Self: ...
+    def deriv(self, /, m: SupportsIndex = ...) -> Self: ...
 
     def roots(self, /) -> _CoefSeries: ...
 
     def linspace(
-        self, /,
+        self,
+        /,
         n: SupportsIndex = ...,
         domain: _SeriesLikeCoef_co | None = ...,
     ) -> _Tuple2[_Series[np.float64 | np.complex128]]: ...
@@ -207,7 +187,7 @@ class ABCPolyBase(Generic[_NameCo], abc.ABC):
     @overload
     @classmethod
     def fit(
-        cls: type[_Self], /,
+        cls,
         x: _SeriesLikeCoef_co,
         y: _SeriesLikeCoef_co,
         deg: int | _SeriesLikeInt_co,
@@ -217,11 +197,11 @@ class ABCPolyBase(Generic[_NameCo], abc.ABC):
         w: _SeriesLikeCoef_co | None = ...,
         window: _SeriesLikeCoef_co | None = ...,
         symbol: str = ...,
-    ) -> _Self: ...
+    ) -> Self: ...
     @overload
     @classmethod
     def fit(
-        cls: type[_Self], /,
+        cls,
         x: _SeriesLikeCoef_co,
         y: _SeriesLikeCoef_co,
         deg: int | _SeriesLikeInt_co,
@@ -232,11 +212,11 @@ class ABCPolyBase(Generic[_NameCo], abc.ABC):
         w: _SeriesLikeCoef_co | None = ...,
         window: _SeriesLikeCoef_co | None = ...,
         symbol: str = ...,
-    ) -> tuple[_Self, Sequence[np.inexact[Any] | np.int32]]: ...
+    ) -> tuple[Self, Sequence[np.inexact[Any] | np.int32]]: ...
     @overload
     @classmethod
     def fit(
-        cls: type[_Self],
+        cls,
         x: _SeriesLikeCoef_co,
         y: _SeriesLikeCoef_co,
         deg: int | _SeriesLikeInt_co,
@@ -246,41 +226,41 @@ class ABCPolyBase(Generic[_NameCo], abc.ABC):
         w: _SeriesLikeCoef_co | None = ...,
         window: _SeriesLikeCoef_co | None = ...,
         symbol: str = ...,
-    ) -> tuple[_Self, Sequence[np.inexact[Any] | np.int32]]: ...
+    ) -> tuple[Self, Sequence[np.inexact[Any] | np.int32]]: ...
 
     @classmethod
     def fromroots(
-        cls: type[_Self], /,
+        cls,
         roots: _ArrayLikeCoef_co,
         domain: _SeriesLikeCoef_co | None = ...,
         window: _SeriesLikeCoef_co | None = ...,
         symbol: str = ...,
-    ) -> _Self: ...
+    ) -> Self: ...
 
     @classmethod
     def identity(
-        cls: type[_Self], /,
+        cls,
         domain: _SeriesLikeCoef_co | None = ...,
         window: _SeriesLikeCoef_co | None = ...,
         symbol: str = ...,
-    ) -> _Self: ...
+    ) -> Self: ...
 
     @classmethod
     def basis(
-        cls: type[_Self], /,
+        cls,
         deg: _AnyInt,
         domain: _SeriesLikeCoef_co | None = ...,
         window: _SeriesLikeCoef_co | None = ...,
         symbol: str = ...,
-    ) -> _Self: ...
+    ) -> Self: ...
 
     @classmethod
     def cast(
-        cls: type[_Self], /,
+        cls,
         series: ABCPolyBase,
         domain: _SeriesLikeCoef_co | None = ...,
         window: _SeriesLikeCoef_co | None = ...,
-    ) -> _Self: ...
+    ) -> Self: ...
 
     @classmethod
     def _str_term_unicode(cls, /, i: str, arg_str: str) -> str: ...
diff --git a/numpy/polynomial/_polytypes.pyi b/numpy/polynomial/_polytypes.pyi
index 3074bb840cc0..0aaa8b78ae2b 100644
--- a/numpy/polynomial/_polytypes.pyi
+++ b/numpy/polynomial/_polytypes.pyi
@@ -1,3 +1,5 @@
+# ruff: noqa: PYI046, PYI047
+
 from collections.abc import Callable, Sequence
 from typing import (
     Any,
@@ -5,6 +7,7 @@ from typing import (
     LiteralString,
     NoReturn,
     Protocol,
+    Self,
     SupportsIndex,
     SupportsInt,
     TypeAlias,
@@ -23,7 +26,6 @@ from numpy._typing import (
     _ArrayLikeObject_co,
     _NestedSequence,
     _SupportsArray,
-
     # scalar-likes
     _IntLike_co,
     _FloatLike_co,
@@ -33,7 +35,6 @@ from numpy._typing import (
 
 _T = TypeVar("_T")
 _T_contra = TypeVar("_T_contra", contravariant=True)
-_Self = TypeVar("_Self")
 _ScalarT = TypeVar("_ScalarT", bound=np.number[Any] | np.bool | np.object_)
 
 # compatible with e.g. int, float, complex, Decimal, Fraction, and ABCPolyBase
@@ -42,17 +43,17 @@ class _SupportsCoefOps(Protocol[_T_contra]):
     def __eq__(self, x: object, /) -> bool: ...
     def __ne__(self, x: object, /) -> bool: ...
 
-    def __neg__(self: _Self, /) -> _Self: ...
-    def __pos__(self: _Self, /) -> _Self: ...
+    def __neg__(self, /) -> Self: ...
+    def __pos__(self, /) -> Self: ...
 
-    def __add__(self: _Self, x: _T_contra, /) -> _Self: ...
-    def __sub__(self: _Self, x: _T_contra, /) -> _Self: ...
-    def __mul__(self: _Self, x: _T_contra, /) -> _Self: ...
-    def __pow__(self: _Self, x: _T_contra, /) -> _Self | float: ...
+    def __add__(self, x: _T_contra, /) -> Self: ...
+    def __sub__(self, x: _T_contra, /) -> Self: ...
+    def __mul__(self, x: _T_contra, /) -> Self: ...
+    def __pow__(self, x: _T_contra, /) -> Self | float: ...
 
-    def __radd__(self: _Self, x: _T_contra, /) -> _Self: ...
-    def __rsub__(self: _Self, x: _T_contra, /) -> _Self: ...
-    def __rmul__(self: _Self, x: _T_contra, /) -> _Self: ...
+    def __radd__(self, x: _T_contra, /) -> Self: ...
+    def __rsub__(self, x: _T_contra, /) -> Self: ...
+    def __rmul__(self, x: _T_contra, /) -> Self: ...
 
 _Series: TypeAlias = np.ndarray[tuple[int], np.dtype[_ScalarT]]
 
diff --git a/numpy/polynomial/chebyshev.pyi b/numpy/polynomial/chebyshev.pyi
index ea00ca04884a..f2dc5d8fc470 100644
--- a/numpy/polynomial/chebyshev.pyi
+++ b/numpy/polynomial/chebyshev.pyi
@@ -1,12 +1,6 @@
 from collections.abc import Callable, Iterable
-from typing import (
-    Any,
-    Concatenate,
-    Final,
-    Literal as L,
-    TypeVar,
-    overload,
-)
+from typing import Any, Concatenate, Final, Self, TypeVar, overload
+from typing import Literal as L
 
 import numpy as np
 import numpy.typing as npt
@@ -14,9 +8,7 @@ from numpy._typing import _IntLike_co
 
 from ._polybase import ABCPolyBase
 from ._polytypes import (
-    _SeriesLikeCoef_co,
     _Array1,
-    _Series,
     _Array2,
     _CoefSeries,
     _FuncBinOp,
@@ -40,6 +32,8 @@ from ._polytypes import (
     _FuncVander2D,
     _FuncVander3D,
     _FuncWeight,
+    _Series,
+    _SeriesLikeCoef_co,
 )
 from .polyutils import trimcoef as chebtrim
 
@@ -150,24 +144,20 @@ def chebinterpolate(
     args: Iterable[Any],
 ) -> npt.NDArray[_RT]: ...
 
-_Self = TypeVar("_Self", bound=object)
-
 class Chebyshev(ABCPolyBase[L["T"]]):
     @overload
     @classmethod
     def interpolate(
-        cls: type[_Self],
-        /,
+        cls,
         func: Callable[[npt.NDArray[np.float64]], _CoefSeries],
         deg: _IntLike_co,
         domain: _SeriesLikeCoef_co | None = ...,
         args: tuple[()] = ...,
-    ) -> _Self: ...
+    ) -> Self: ...
     @overload
     @classmethod
     def interpolate(
-        cls: type[_Self],
-        /,
+        cls,
         func: Callable[
             Concatenate[npt.NDArray[np.float64], ...],
             _CoefSeries,
@@ -176,11 +166,11 @@ class Chebyshev(ABCPolyBase[L["T"]]):
         domain: _SeriesLikeCoef_co | None = ...,
         *,
         args: Iterable[Any],
-    ) -> _Self: ...
+    ) -> Self: ...
     @overload
     @classmethod
     def interpolate(
-        cls: type[_Self],
+        cls,
         func: Callable[
             Concatenate[npt.NDArray[np.float64], ...],
             _CoefSeries,
@@ -188,5 +178,4 @@ class Chebyshev(ABCPolyBase[L["T"]]):
         deg: _IntLike_co,
         domain: _SeriesLikeCoef_co | None,
         args: Iterable[Any],
-        /,
-    ) -> _Self: ...
+    ) -> Self: ...

From 12016be173200af63c5d0e5c9e5e82ff6353d131 Mon Sep 17 00:00:00 2001
From: jorenham 
Date: Thu, 24 Apr 2025 02:49:10 +0200
Subject: [PATCH 095/202] TYP: write ``dtype[Any]`` as ``dtype``

---
 numpy/__init__.pyi                            | 39 +++++++++----------
 numpy/_core/_dtype.pyi                        | 36 ++++++++---------
 numpy/_core/_exceptions.pyi                   | 38 ++++++------------
 numpy/_core/_machar.pyi                       | 38 ++++++------------
 numpy/_core/fromnumeric.pyi                   | 10 ++---
 numpy/_core/multiarray.pyi                    | 14 +++----
 numpy/_core/numeric.pyi                       |  8 ++--
 numpy/_core/numerictypes.pyi                  |  9 +----
 numpy/_core/records.pyi                       |  2 +-
 numpy/_typing/_dtype_like.py                  |  2 +-
 numpy/ctypeslib/_ctypeslib.pyi                |  8 ++--
 numpy/lib/_arrayterator_impl.pyi              |  4 +-
 numpy/lib/_index_tricks_impl.pyi              |  4 +-
 numpy/lib/_iotools.pyi                        |  2 +-
 numpy/lib/_user_array_impl.pyi                |  6 +--
 numpy/lib/recfunctions.pyi                    | 22 +++++------
 numpy/ma/mrecords.pyi                         |  2 +-
 numpy/typing/tests/data/pass/array_like.py    |  6 +--
 numpy/typing/tests/data/pass/recfunctions.py  |  2 +-
 .../tests/data/reveal/array_constructors.pyi  |  8 ++--
 numpy/typing/tests/data/reveal/ctypeslib.pyi  |  4 +-
 numpy/typing/tests/data/reveal/dtype.pyi      | 16 ++++----
 .../typing/tests/data/reveal/fromnumeric.pyi  | 10 ++---
 numpy/typing/tests/data/reveal/memmap.pyi     |  2 +-
 numpy/typing/tests/data/reveal/multiarray.pyi | 14 +++----
 .../tests/data/reveal/ndarray_conversion.pyi  |  2 +-
 numpy/typing/tests/data/reveal/nditer.pyi     |  2 +-
 numpy/typing/tests/data/reveal/rec.pyi        | 14 +++----
 28 files changed, 140 insertions(+), 184 deletions(-)

diff --git a/numpy/__init__.pyi b/numpy/__init__.pyi
index 500647feb2ad..c2bef3a54d35 100644
--- a/numpy/__init__.pyi
+++ b/numpy/__init__.pyi
@@ -782,7 +782,6 @@ _AnyShapeT = TypeVar(
     tuple[int, int, int, int, int, int, int, int],  # 8-d
     tuple[int, ...],  # N-d
 )
-_AnyNBitInexact = TypeVar("_AnyNBitInexact", _NBitHalf, _NBitSingle, _NBitDouble, _NBitLongDouble)
 _AnyTD64Item = TypeVar("_AnyTD64Item", dt.timedelta, int, None, dt.timedelta | int | None)
 _AnyDT64Arg = TypeVar("_AnyDT64Arg", dt.datetime, dt.date, None)
 _AnyDT64Item = TypeVar("_AnyDT64Item", dt.datetime, dt.date, int, None, dt.date, int | None)
@@ -799,8 +798,8 @@ _ImagT_co = TypeVar("_ImagT_co", covariant=True)
 
 _CallableT = TypeVar("_CallableT", bound=Callable[..., object])
 
-_DTypeT = TypeVar("_DTypeT", bound=dtype[Any])
-_DTypeT_co = TypeVar("_DTypeT_co", bound=dtype[Any], covariant=True)
+_DTypeT = TypeVar("_DTypeT", bound=dtype)
+_DTypeT_co = TypeVar("_DTypeT_co", bound=dtype, covariant=True)
 _FlexDTypeT = TypeVar("_FlexDTypeT", bound=dtype[flexible])
 
 _ArrayT = TypeVar("_ArrayT", bound=NDArray[Any])
@@ -1512,7 +1511,7 @@ class dtype(Generic[_ScalarT_co], metaclass=_DTypeMeta):
         align: builtins.bool = ...,
         copy: builtins.bool = ...,
         metadata: dict[builtins.str, Any] = ...,
-    ) -> dtype[Any]: ...
+    ) -> dtype: ...
 
     # Catch-all overload for object-likes
     # NOTE: `object_ | Any` is *not* equivalent to `Any` -- it describes some
@@ -1533,7 +1532,7 @@ class dtype(Generic[_ScalarT_co], metaclass=_DTypeMeta):
     @overload
     def __getitem__(self: dtype[void], key: list[builtins.str], /) -> dtype[void]: ...
     @overload
-    def __getitem__(self: dtype[void], key: builtins.str | SupportsIndex, /) -> dtype[Any]: ...
+    def __getitem__(self: dtype[void], key: builtins.str | SupportsIndex, /) -> dtype: ...
 
     # NOTE: In the future 1-based multiplications will also yield `flexible` dtypes
     @overload
@@ -1544,12 +1543,12 @@ class dtype(Generic[_ScalarT_co], metaclass=_DTypeMeta):
     def __mul__(self, value: SupportsIndex, /) -> dtype[void]: ...
 
     # NOTE: `__rmul__` seems to be broken when used in combination with
-    # literals as of mypy 0.902. Set the return-type to `dtype[Any]` for
+    # literals as of mypy 0.902. Set the return-type to `dtype` for
     # now for non-flexible dtypes.
     @overload
     def __rmul__(self: _FlexDTypeT, value: SupportsIndex, /) -> _FlexDTypeT: ...
     @overload
-    def __rmul__(self, value: SupportsIndex, /) -> dtype[Any]: ...
+    def __rmul__(self, value: SupportsIndex, /) -> dtype: ...
 
     def __gt__(self, other: DTypeLike, /) -> builtins.bool: ...
     def __ge__(self, other: DTypeLike, /) -> builtins.bool: ...
@@ -1565,7 +1564,7 @@ class dtype(Generic[_ScalarT_co], metaclass=_DTypeMeta):
     @property
     def alignment(self) -> int: ...
     @property
-    def base(self) -> dtype[Any]: ...
+    def base(self) -> dtype: ...
     @property
     def byteorder(self) -> _ByteOrderChar: ...
     @property
@@ -1573,7 +1572,7 @@ class dtype(Generic[_ScalarT_co], metaclass=_DTypeMeta):
     @property
     def descr(self) -> list[tuple[LiteralString, LiteralString] | tuple[LiteralString, LiteralString, _Shape]]: ...
     @property
-    def fields(self,) -> MappingProxyType[LiteralString, tuple[dtype[Any], int] | tuple[dtype[Any], int, Any]] | None: ...
+    def fields(self,) -> MappingProxyType[LiteralString, tuple[dtype, int] | tuple[dtype, int, Any]] | None: ...
     @property
     def flags(self) -> int: ...
     @property
@@ -1599,7 +1598,7 @@ class dtype(Generic[_ScalarT_co], metaclass=_DTypeMeta):
     @property
     def ndim(self) -> int: ...
     @property
-    def subdtype(self) -> tuple[dtype[Any], _Shape] | None: ...
+    def subdtype(self) -> tuple[dtype, _Shape] | None: ...
     def newbyteorder(self, new_order: _ByteOrder = ..., /) -> Self: ...
     @property
     def str(self) -> LiteralString: ...
@@ -2106,7 +2105,7 @@ class ndarray(_ArrayOrScalarCommon, Generic[_ShapeT_co, _DTypeT_co]):
     @overload
     def __getitem__(self, key: _ToIndices, /) -> ndarray[_Shape, _DTypeT_co]: ...
     @overload
-    def __getitem__(self: NDArray[void], key: str, /) -> ndarray[_ShapeT_co, np.dtype[Any]]: ...
+    def __getitem__(self: NDArray[void], key: str, /) -> ndarray[_ShapeT_co, np.dtype]: ...
     @overload
     def __getitem__(self: NDArray[void], key: list[str], /) -> ndarray[_ShapeT_co, _dtype[void]]: ...
 
@@ -2530,7 +2529,7 @@ class ndarray(_ArrayOrScalarCommon, Generic[_ShapeT_co, _DTypeT_co]):
         casting: _CastingKind = ...,
         subok: builtins.bool = ...,
         copy: builtins.bool | _CopyMode = ...,
-    ) -> ndarray[_ShapeT_co, dtype[Any]]: ...
+    ) -> ndarray[_ShapeT_co, dtype]: ...
 
     #
     @overload  # ()
@@ -2544,7 +2543,7 @@ class ndarray(_ArrayOrScalarCommon, Generic[_ShapeT_co, _DTypeT_co]):
     @overload  # (_: T)
     def view(self, /, dtype: type[_ArrayT]) -> _ArrayT: ...
     @overload  # (dtype: ?)
-    def view(self, /, dtype: DTypeLike) -> ndarray[_ShapeT_co, dtype[Any]]: ...
+    def view(self, /, dtype: DTypeLike) -> ndarray[_ShapeT_co, dtype]: ...
     @overload  # (dtype: ?, type: type[T])
     def view(self, /, dtype: DTypeLike, type: type[_ArrayT]) -> _ArrayT: ...
 
@@ -4812,12 +4811,12 @@ class ufunc:
     def resolve_dtypes(
         self,
         /,
-        dtypes: tuple[dtype[Any] | type | None, ...],
+        dtypes: tuple[dtype | type | None, ...],
         *,
-        signature: tuple[dtype[Any] | None, ...] | None = None,
+        signature: tuple[dtype | None, ...] | None = None,
         casting: _CastingKind | None = None,
         reduction: builtins.bool = False,
-    ) -> tuple[dtype[Any], ...]: ...
+    ) -> tuple[dtype, ...]: ...
 
 # Parameters: `__name__`, `ntypes` and `identity`
 absolute: _UFunc_Nin1_Nout1[L['absolute'], L[20], None]
@@ -5079,7 +5078,7 @@ class nditer:
     def remove_multi_index(self) -> None: ...
     def reset(self) -> None: ...
     @property
-    def dtypes(self) -> tuple[dtype[Any], ...]: ...
+    def dtypes(self) -> tuple[dtype, ...]: ...
     @property
     def finished(self) -> builtins.bool: ...
     @property
@@ -5147,7 +5146,7 @@ class memmap(ndarray[_ShapeT_co, _DTypeT_co]):
         offset: int = ...,
         shape: int | tuple[int, ...] | None = ...,
         order: _OrderKACF = ...,
-    ) -> memmap[Any, dtype[Any]]: ...
+    ) -> memmap[Any, dtype]: ...
     def __array_finalize__(self, obj: object) -> None: ...
     def __array_wrap__(
         self,
@@ -5212,7 +5211,7 @@ class poly1d:
     __hash__: ClassVar[None]  # type: ignore[assignment]  # pyright: ignore[reportIncompatibleMethodOverride]
 
     @overload
-    def __array__(self, /, t: None = None, copy: builtins.bool | None = None) -> ndarray[tuple[int], dtype[Any]]: ...
+    def __array__(self, /, t: None = None, copy: builtins.bool | None = None) -> ndarray[tuple[int], dtype]: ...
     @overload
     def __array__(self, /, t: _DTypeT, copy: builtins.bool | None = None) -> ndarray[tuple[int], _DTypeT]: ...
 
@@ -5280,7 +5279,7 @@ class matrix(ndarray[_2DShapeT_co, _DTypeT_co]):
         /,
     ) -> matrix[_2D, _DTypeT_co]: ...
     @overload
-    def __getitem__(self: NDArray[void], key: str, /) -> matrix[_2D, dtype[Any]]: ...
+    def __getitem__(self: NDArray[void], key: str, /) -> matrix[_2D, dtype]: ...
     @overload
     def __getitem__(self: NDArray[void], key: list[str], /) -> matrix[_2DShapeT_co, dtype[void]]: ...
 
diff --git a/numpy/_core/_dtype.pyi b/numpy/_core/_dtype.pyi
index c3e966e3f517..6cdd77b22e07 100644
--- a/numpy/_core/_dtype.pyi
+++ b/numpy/_core/_dtype.pyi
@@ -1,4 +1,4 @@
-from typing import Any, Final, TypeAlias, TypedDict, overload, type_check_only
+from typing import Final, TypeAlias, TypedDict, overload, type_check_only
 from typing import Literal as L
 
 from typing_extensions import ReadOnly, TypeVar
@@ -30,29 +30,29 @@ class _KindToStemType(TypedDict):
 _kind_to_stem: Final[_KindToStemType] = ...
 
 #
-def _kind_name(dtype: np.dtype[Any]) -> _Name: ...
-def __str__(dtype: np.dtype[Any]) -> str: ...
-def __repr__(dtype: np.dtype[Any]) -> str: ...
+def _kind_name(dtype: np.dtype) -> _Name: ...
+def __str__(dtype: np.dtype) -> str: ...
+def __repr__(dtype: np.dtype) -> str: ...
 
 #
-def _isunsized(dtype: np.dtype[Any]) -> bool: ...
-def _is_packed(dtype: np.dtype[Any]) -> bool: ...
-def _name_includes_bit_suffix(dtype: np.dtype[Any]) -> bool: ...
+def _isunsized(dtype: np.dtype) -> bool: ...
+def _is_packed(dtype: np.dtype) -> bool: ...
+def _name_includes_bit_suffix(dtype: np.dtype) -> bool: ...
 
 #
-def _construction_repr(dtype: np.dtype[Any], include_align: bool = False, short: bool = False) -> str: ...
-def _scalar_str(dtype: np.dtype[Any], short: bool) -> str: ...
-def _byte_order_str(dtype: np.dtype[Any]) -> str: ...
-def _datetime_metadata_str(dtype: np.dtype[Any]) -> str: ...
-def _struct_dict_str(dtype: np.dtype[Any], includealignedflag: bool) -> str: ...
-def _struct_list_str(dtype: np.dtype[Any]) -> str: ...
-def _struct_str(dtype: np.dtype[Any], include_align: bool) -> str: ...
-def _subarray_str(dtype: np.dtype[Any]) -> str: ...
-def _name_get(dtype: np.dtype[Any]) -> str: ...
+def _construction_repr(dtype: np.dtype, include_align: bool = False, short: bool = False) -> str: ...
+def _scalar_str(dtype: np.dtype, short: bool) -> str: ...
+def _byte_order_str(dtype: np.dtype) -> str: ...
+def _datetime_metadata_str(dtype: np.dtype) -> str: ...
+def _struct_dict_str(dtype: np.dtype, includealignedflag: bool) -> str: ...
+def _struct_list_str(dtype: np.dtype) -> str: ...
+def _struct_str(dtype: np.dtype, include_align: bool) -> str: ...
+def _subarray_str(dtype: np.dtype) -> str: ...
+def _name_get(dtype: np.dtype) -> str: ...
 
 #
 @overload
-def _unpack_field(dtype: np.dtype[Any], offset: int, title: _T) -> tuple[np.dtype[Any], int, _T]: ...
+def _unpack_field(dtype: np.dtype, offset: int, title: _T) -> tuple[np.dtype, int, _T]: ...
 @overload
-def _unpack_field(dtype: np.dtype[Any], offset: int, title: None = None) -> tuple[np.dtype[Any], int, None]: ...
+def _unpack_field(dtype: np.dtype, offset: int, title: None = None) -> tuple[np.dtype, int, None]: ...
 def _aligned_offset(offset: int, alignment: int) -> int: ...
diff --git a/numpy/_core/_exceptions.pyi b/numpy/_core/_exceptions.pyi
index 0c9addd79dc6..02637a17b6a8 100644
--- a/numpy/_core/_exceptions.pyi
+++ b/numpy/_core/_exceptions.pyi
@@ -18,47 +18,31 @@ class UFuncTypeError(TypeError):
     def __init__(self, /, ufunc: np.ufunc) -> None: ...
 
 class _UFuncNoLoopError(UFuncTypeError):
-    dtypes: tuple[np.dtype[Any], ...]
-    def __init__(self, /, ufunc: np.ufunc, dtypes: Iterable[np.dtype[Any]]) -> None: ...
+    dtypes: tuple[np.dtype, ...]
+    def __init__(self, /, ufunc: np.ufunc, dtypes: Iterable[np.dtype]) -> None: ...
 
 class _UFuncBinaryResolutionError(_UFuncNoLoopError):
-    dtypes: tuple[np.dtype[Any], np.dtype[Any]]
-    def __init__(self, /, ufunc: np.ufunc, dtypes: Iterable[np.dtype[Any]]) -> None: ...
+    dtypes: tuple[np.dtype, np.dtype]
+    def __init__(self, /, ufunc: np.ufunc, dtypes: Iterable[np.dtype]) -> None: ...
 
 class _UFuncCastingError(UFuncTypeError):
     casting: Final[_CastingKind]
-    from_: Final[np.dtype[Any]]
-    to: Final[np.dtype[Any]]
-    def __init__(self, /, ufunc: np.ufunc, casting: _CastingKind, from_: np.dtype[Any], to: np.dtype[Any]) -> None: ...
+    from_: Final[np.dtype]
+    to: Final[np.dtype]
+    def __init__(self, /, ufunc: np.ufunc, casting: _CastingKind, from_: np.dtype, to: np.dtype) -> None: ...
 
 class _UFuncInputCastingError(_UFuncCastingError):
     in_i: Final[int]
-    def __init__(
-        self,
-        /,
-        ufunc: np.ufunc,
-        casting: _CastingKind,
-        from_: np.dtype[Any],
-        to: np.dtype[Any],
-        i: int,
-    ) -> None: ...
+    def __init__(self, /, ufunc: np.ufunc, casting: _CastingKind, from_: np.dtype, to: np.dtype, i: int) -> None: ...
 
 class _UFuncOutputCastingError(_UFuncCastingError):
     out_i: Final[int]
-    def __init__(
-        self,
-        /,
-        ufunc: np.ufunc,
-        casting: _CastingKind,
-        from_: np.dtype[Any],
-        to: np.dtype[Any],
-        i: int,
-    ) -> None: ...
+    def __init__(self, /, ufunc: np.ufunc, casting: _CastingKind, from_: np.dtype, to: np.dtype, i: int) -> None: ...
 
 class _ArrayMemoryError(MemoryError):
     shape: tuple[int, ...]
-    dtype: np.dtype[Any]
-    def __init__(self, /, shape: tuple[int, ...], dtype: np.dtype[Any]) -> None: ...
+    dtype: np.dtype
+    def __init__(self, /, shape: tuple[int, ...], dtype: np.dtype) -> None: ...
     @property
     def _total_size(self) -> int: ...
     @staticmethod
diff --git a/numpy/_core/_machar.pyi b/numpy/_core/_machar.pyi
index 0c9addd79dc6..02637a17b6a8 100644
--- a/numpy/_core/_machar.pyi
+++ b/numpy/_core/_machar.pyi
@@ -18,47 +18,31 @@ class UFuncTypeError(TypeError):
     def __init__(self, /, ufunc: np.ufunc) -> None: ...
 
 class _UFuncNoLoopError(UFuncTypeError):
-    dtypes: tuple[np.dtype[Any], ...]
-    def __init__(self, /, ufunc: np.ufunc, dtypes: Iterable[np.dtype[Any]]) -> None: ...
+    dtypes: tuple[np.dtype, ...]
+    def __init__(self, /, ufunc: np.ufunc, dtypes: Iterable[np.dtype]) -> None: ...
 
 class _UFuncBinaryResolutionError(_UFuncNoLoopError):
-    dtypes: tuple[np.dtype[Any], np.dtype[Any]]
-    def __init__(self, /, ufunc: np.ufunc, dtypes: Iterable[np.dtype[Any]]) -> None: ...
+    dtypes: tuple[np.dtype, np.dtype]
+    def __init__(self, /, ufunc: np.ufunc, dtypes: Iterable[np.dtype]) -> None: ...
 
 class _UFuncCastingError(UFuncTypeError):
     casting: Final[_CastingKind]
-    from_: Final[np.dtype[Any]]
-    to: Final[np.dtype[Any]]
-    def __init__(self, /, ufunc: np.ufunc, casting: _CastingKind, from_: np.dtype[Any], to: np.dtype[Any]) -> None: ...
+    from_: Final[np.dtype]
+    to: Final[np.dtype]
+    def __init__(self, /, ufunc: np.ufunc, casting: _CastingKind, from_: np.dtype, to: np.dtype) -> None: ...
 
 class _UFuncInputCastingError(_UFuncCastingError):
     in_i: Final[int]
-    def __init__(
-        self,
-        /,
-        ufunc: np.ufunc,
-        casting: _CastingKind,
-        from_: np.dtype[Any],
-        to: np.dtype[Any],
-        i: int,
-    ) -> None: ...
+    def __init__(self, /, ufunc: np.ufunc, casting: _CastingKind, from_: np.dtype, to: np.dtype, i: int) -> None: ...
 
 class _UFuncOutputCastingError(_UFuncCastingError):
     out_i: Final[int]
-    def __init__(
-        self,
-        /,
-        ufunc: np.ufunc,
-        casting: _CastingKind,
-        from_: np.dtype[Any],
-        to: np.dtype[Any],
-        i: int,
-    ) -> None: ...
+    def __init__(self, /, ufunc: np.ufunc, casting: _CastingKind, from_: np.dtype, to: np.dtype, i: int) -> None: ...
 
 class _ArrayMemoryError(MemoryError):
     shape: tuple[int, ...]
-    dtype: np.dtype[Any]
-    def __init__(self, /, shape: tuple[int, ...], dtype: np.dtype[Any]) -> None: ...
+    dtype: np.dtype
+    def __init__(self, /, shape: tuple[int, ...], dtype: np.dtype) -> None: ...
     @property
     def _total_size(self) -> int: ...
     @staticmethod
diff --git a/numpy/_core/fromnumeric.pyi b/numpy/_core/fromnumeric.pyi
index 138fe8809110..13fb027759b3 100644
--- a/numpy/_core/fromnumeric.pyi
+++ b/numpy/_core/fromnumeric.pyi
@@ -209,7 +209,7 @@ def reshape(
     order: _OrderACF = "C",
     *,
     copy: bool | None = None,
-) -> np.ndarray[tuple[int], np.dtype[Any]]: ...
+) -> np.ndarray[tuple[int], np.dtype]: ...
 @overload
 def reshape(  # shape: (int, ...) @ _AnyShapeT
     a: ArrayLike,
@@ -218,7 +218,7 @@ def reshape(  # shape: (int, ...) @ _AnyShapeT
     order: _OrderACF = "C",
     *,
     copy: bool | None = None,
-) -> np.ndarray[_AnyShapeT, np.dtype[Any]]: ...
+) -> np.ndarray[_AnyShapeT, np.dtype]: ...
 @overload  # shape: Sequence[index]
 def reshape(
     a: ArrayLike,
@@ -475,9 +475,9 @@ def resize(a: _ArrayLike[_ScalarT], new_shape: _AnyShapeT) -> np.ndarray[_AnySha
 @overload
 def resize(a: _ArrayLike[_ScalarT], new_shape: _ShapeLike) -> NDArray[_ScalarT]: ...
 @overload
-def resize(a: ArrayLike, new_shape: SupportsIndex | tuple[SupportsIndex]) -> np.ndarray[tuple[int], np.dtype[Any]]: ...
+def resize(a: ArrayLike, new_shape: SupportsIndex | tuple[SupportsIndex]) -> np.ndarray[tuple[int], np.dtype]: ...
 @overload
-def resize(a: ArrayLike, new_shape: _AnyShapeT) -> np.ndarray[_AnyShapeT, np.dtype[Any]]: ...
+def resize(a: ArrayLike, new_shape: _AnyShapeT) -> np.ndarray[_AnyShapeT, np.dtype]: ...
 @overload
 def resize(a: ArrayLike, new_shape: _ShapeLike) -> NDArray[Any]: ...
 
@@ -561,7 +561,7 @@ def ravel(
     order: _OrderKACF = "C",
 ) -> _Array1D[np.complex128 | np.float64 | np.int_ | np.bool]: ...
 @overload
-def ravel(a: ArrayLike, order: _OrderKACF = "C") -> np.ndarray[tuple[int], np.dtype[Any]]: ...
+def ravel(a: ArrayLike, order: _OrderKACF = "C") -> np.ndarray[tuple[int], np.dtype]: ...
 
 def nonzero(a: _ArrayLike[Any]) -> tuple[NDArray[intp], ...]: ...
 
diff --git a/numpy/_core/multiarray.pyi b/numpy/_core/multiarray.pyi
index a127b04c9e2e..7ca9b4ba783e 100644
--- a/numpy/_core/multiarray.pyi
+++ b/numpy/_core/multiarray.pyi
@@ -194,7 +194,7 @@ __all__ = [
 ]
 
 _ScalarT = TypeVar("_ScalarT", bound=generic)
-_DTypeT = TypeVar("_DTypeT", bound=np.dtype[Any])
+_DTypeT = TypeVar("_DTypeT", bound=np.dtype)
 _ArrayT = TypeVar("_ArrayT", bound=ndarray[Any, Any])
 _ArrayT_co = TypeVar(
     "_ArrayT_co",
@@ -384,7 +384,7 @@ def get_handler_name(a: NDArray[Any] = ..., /) -> str | None: ...
 def get_handler_version(a: NDArray[Any] = ..., /) -> int | None: ...
 def format_longfloat(x: np.longdouble, precision: int) -> str: ...
 def scalar(dtype: _DTypeT, object: bytes | object = ...) -> ndarray[tuple[()], _DTypeT]: ...
-def set_typeDict(dict_: dict[str, np.dtype[Any]], /) -> None: ...
+def set_typeDict(dict_: dict[str, np.dtype], /) -> None: ...
 typeinfo: Final[dict[str, np.dtype[np.generic]]]
 
 ALLOW_THREADS: Final[int]  # 0 or 1 (system-specific)
@@ -598,13 +598,9 @@ def can_cast(
     casting: _CastingKind | None = ...,
 ) -> bool: ...
 
-def min_scalar_type(
-    a: ArrayLike, /,
-) -> dtype[Any]: ...
+def min_scalar_type(a: ArrayLike, /) -> dtype: ...
 
-def result_type(
-    *arrays_and_dtypes: ArrayLike | DTypeLike,
-) -> dtype[Any]: ...
+def result_type(*arrays_and_dtypes: ArrayLike | DTypeLike) -> dtype: ...
 
 @overload
 def dot(a: ArrayLike, b: ArrayLike, out: None = ...) -> Any: ...
@@ -794,7 +790,7 @@ def asfortranarray(
     like: _SupportsArrayFunc | None = ...,
 ) -> NDArray[Any]: ...
 
-def promote_types(__type1: DTypeLike, __type2: DTypeLike) -> dtype[Any]: ...
+def promote_types(__type1: DTypeLike, __type2: DTypeLike) -> dtype: ...
 
 # `sep` is a de facto mandatory argument, as its default value is deprecated
 @overload
diff --git a/numpy/_core/numeric.pyi b/numpy/_core/numeric.pyi
index 0a0c70d80a50..251f1bdb3601 100644
--- a/numpy/_core/numeric.pyi
+++ b/numpy/_core/numeric.pyi
@@ -178,7 +178,7 @@ __all__ = [
 
 _T = TypeVar("_T")
 _ScalarT = TypeVar("_ScalarT", bound=generic)
-_DTypeT = TypeVar("_DTypeT", bound=np.dtype[Any])
+_DTypeT = TypeVar("_DTypeT", bound=np.dtype)
 _ArrayT = TypeVar("_ArrayT", bound=np.ndarray[Any, Any])
 _ShapeT = TypeVar("_ShapeT", bound=tuple[int, ...])
 
@@ -849,7 +849,7 @@ def array_equiv(a1: ArrayLike, a2: ArrayLike) -> bool: ...
 
 @overload
 def astype(
-    x: ndarray[_ShapeT, dtype[Any]],
+    x: ndarray[_ShapeT, dtype],
     dtype: _DTypeLike[_ScalarT],
     /,
     *,
@@ -858,10 +858,10 @@ def astype(
 ) -> ndarray[_ShapeT, dtype[_ScalarT]]: ...
 @overload
 def astype(
-    x: ndarray[_ShapeT, dtype[Any]],
+    x: ndarray[_ShapeT, dtype],
     dtype: DTypeLike,
     /,
     *,
     copy: bool = ...,
     device: L["cpu"] | None = ...,
-) -> ndarray[_ShapeT, dtype[Any]]: ...
+) -> ndarray[_ShapeT, dtype]: ...
diff --git a/numpy/_core/numerictypes.pyi b/numpy/_core/numerictypes.pyi
index ace5913f0f84..3f06991adf8f 100644
--- a/numpy/_core/numerictypes.pyi
+++ b/numpy/_core/numerictypes.pyi
@@ -1,10 +1,5 @@
 import builtins
-from typing import (
-    Any,
-    Literal as L,
-    TypedDict,
-    type_check_only,
-)
+from typing import Literal as L, TypedDict, type_check_only
 
 import numpy as np
 from numpy import (
@@ -177,7 +172,7 @@ class _TypeCodes(TypedDict):
     Datetime: L['Mm']
     All: L['?bhilqnpBHILQNPefdgFDGSUVOMm']
 
-def isdtype(dtype: dtype[Any] | type[Any], kind: DTypeLike | tuple[DTypeLike, ...]) -> builtins.bool: ...
+def isdtype(dtype: dtype | type, kind: DTypeLike | tuple[DTypeLike, ...]) -> builtins.bool: ...
 
 def issubdtype(arg1: DTypeLike, arg2: DTypeLike) -> builtins.bool: ...
 
diff --git a/numpy/_core/records.pyi b/numpy/_core/records.pyi
index 3542a0817154..b1725bcdf237 100644
--- a/numpy/_core/records.pyi
+++ b/numpy/_core/records.pyi
@@ -23,7 +23,7 @@ __all__ = [
 
 _T = TypeVar("_T")
 _ScalarT = TypeVar("_ScalarT", bound=np.generic)
-_DTypeT_co = TypeVar("_DTypeT_co", bound=np.dtype[Any], covariant=True)
+_DTypeT_co = TypeVar("_DTypeT_co", bound=np.dtype, covariant=True)
 _ShapeT_co = TypeVar("_ShapeT_co", bound=tuple[int, ...], covariant=True)
 
 _RecArray: TypeAlias = recarray[Any, np.dtype[_ScalarT]]
diff --git a/numpy/_typing/_dtype_like.py b/numpy/_typing/_dtype_like.py
index 2120c57fbaec..cd5be8e11864 100644
--- a/numpy/_typing/_dtype_like.py
+++ b/numpy/_typing/_dtype_like.py
@@ -26,7 +26,7 @@
 )
 
 _ScalarT = TypeVar("_ScalarT", bound=np.generic)
-_DTypeT_co = TypeVar("_DTypeT_co", covariant=True, bound=np.dtype[Any])
+_DTypeT_co = TypeVar("_DTypeT_co", bound=np.dtype, covariant=True)
 
 _DTypeLikeNested: TypeAlias = Any  # TODO: wait for support for recursive types
 
diff --git a/numpy/ctypeslib/_ctypeslib.pyi b/numpy/ctypeslib/_ctypeslib.pyi
index ebb0fbc4677a..3fe1f7927961 100644
--- a/numpy/ctypeslib/_ctypeslib.pyi
+++ b/numpy/ctypeslib/_ctypeslib.pyi
@@ -69,8 +69,8 @@ from numpy._typing import (
 __all__ = ["load_library", "ndpointer", "c_intp", "as_ctypes", "as_array", "as_ctypes_type"]
 
 # TODO: Add a proper `_Shape` bound once we've got variadic typevars
-_DTypeT = TypeVar("_DTypeT", bound=dtype[Any])
-_DTypeOptionalT = TypeVar("_DTypeOptionalT", bound=dtype[Any] | None)
+_DTypeT = TypeVar("_DTypeT", bound=dtype)
+_DTypeOptionalT = TypeVar("_DTypeOptionalT", bound=dtype | None)
 _ScalarT = TypeVar("_ScalarT", bound=generic)
 
 _FlagsKind: TypeAlias = L[
@@ -130,7 +130,7 @@ def ndpointer(
     *,
     shape: _ShapeLike,
     flags: _FlagsKind | Iterable[_FlagsKind] | int | flagsobj | None = ...,
-) -> type[_concrete_ndptr[dtype[Any]]]: ...
+) -> type[_concrete_ndptr[dtype]]: ...
 @overload
 def ndpointer(
     dtype: _DTypeLike[_ScalarT],
@@ -144,7 +144,7 @@ def ndpointer(
     ndim: int = ...,
     shape: None = ...,
     flags: _FlagsKind | Iterable[_FlagsKind] | int | flagsobj | None = ...,
-) -> type[_ndptr[dtype[Any]]]: ...
+) -> type[_ndptr[dtype]]: ...
 
 @overload
 def as_ctypes_type(dtype: _BoolCodes | _DTypeLike[np.bool] | type[ctypes.c_bool]) -> type[ctypes.c_bool]: ...
diff --git a/numpy/lib/_arrayterator_impl.pyi b/numpy/lib/_arrayterator_impl.pyi
index b0884e61e024..060ff37d5c66 100644
--- a/numpy/lib/_arrayterator_impl.pyi
+++ b/numpy/lib/_arrayterator_impl.pyi
@@ -11,8 +11,8 @@ import numpy as np
 __all__ = ["Arrayterator"]
 
 _ShapeT_co = TypeVar("_ShapeT_co", bound=tuple[int, ...], covariant=True)
-_DTypeT = TypeVar("_DTypeT", bound=np.dtype[Any])
-_DTypeT_co = TypeVar("_DTypeT_co", bound=np.dtype[Any], covariant=True)
+_DTypeT = TypeVar("_DTypeT", bound=np.dtype)
+_DTypeT_co = TypeVar("_DTypeT_co", bound=np.dtype, covariant=True)
 _ScalarT = TypeVar("_ScalarT", bound=np.generic)
 
 _AnyIndex: TypeAlias = EllipsisType | int | slice | tuple[EllipsisType | int | slice, ...]
diff --git a/numpy/lib/_index_tricks_impl.pyi b/numpy/lib/_index_tricks_impl.pyi
index a8d88f18071f..ef6e42200deb 100644
--- a/numpy/lib/_index_tricks_impl.pyi
+++ b/numpy/lib/_index_tricks_impl.pyi
@@ -39,7 +39,7 @@ __all__ = [  # noqa: RUF022
 _T = TypeVar("_T")
 _TupleT = TypeVar("_TupleT", bound=tuple[Any, ...])
 _ArrayT = TypeVar("_ArrayT", bound=NDArray[Any])
-_DTypeT = TypeVar("_DTypeT", bound=np.dtype[Any])
+_DTypeT = TypeVar("_DTypeT", bound=np.dtype)
 _ScalarT = TypeVar("_ScalarT", bound=np.generic)
 _ScalarT_co = TypeVar("_ScalarT_co", bound=np.generic, covariant=True)
 _BoolT_co = TypeVar("_BoolT_co", bound=bool, default=bool, covariant=True)
@@ -116,7 +116,7 @@ class OGridClass(nd_grid[L[True]]):
 class AxisConcatenator(Generic[_AxisT_co, _MatrixT_co, _NDMinT_co, _Trans1DT_co]):
     __slots__ = "axis", "matrix", "ndmin", "trans1d"
 
-    makemat: ClassVar[type[np.matrix[tuple[int, int], np.dtype[Any]]]]
+    makemat: ClassVar[type[np.matrix[tuple[int, int], np.dtype]]]
 
     axis: _AxisT_co
     matrix: _MatrixT_co
diff --git a/numpy/lib/_iotools.pyi b/numpy/lib/_iotools.pyi
index b155542acf38..28349000aeba 100644
--- a/numpy/lib/_iotools.pyi
+++ b/numpy/lib/_iotools.pyi
@@ -95,7 +95,7 @@ def str2bool(value: Literal["true", "True", "TRUE"]) -> Literal[True]: ...
 
 #
 def has_nested_fields(ndtype: np.dtype[np.void]) -> bool: ...
-def flatten_dtype(ndtype: np.dtype[np.void], flatten_base: bool = False) -> type[np.dtype[Any]]: ...
+def flatten_dtype(ndtype: np.dtype[np.void], flatten_base: bool = False) -> type[np.dtype]: ...
 def easy_dtype(
     ndtype: npt.DTypeLike,
     names: Iterable[str] | None = None,
diff --git a/numpy/lib/_user_array_impl.pyi b/numpy/lib/_user_array_impl.pyi
index d0a322c53e42..5d08dbdb40c7 100644
--- a/numpy/lib/_user_array_impl.pyi
+++ b/numpy/lib/_user_array_impl.pyi
@@ -13,8 +13,8 @@ from numpy._typing import _ArrayLike, _ArrayLikeBool_co, _ArrayLikeInt_co, _DTyp
 _ScalarT = TypeVar("_ScalarT", bound=np.generic)
 _ShapeT = TypeVar("_ShapeT", bound=tuple[int, ...])
 _ShapeT_co = TypeVar("_ShapeT_co", bound=tuple[int, ...], default=Any, covariant=True)
-_DTypeT = TypeVar("_DTypeT", bound=np.dtype[Any])
-_DTypeT_co = TypeVar("_DTypeT_co", bound=np.dtype[Any], default=np.dtype[Any], covariant=True)
+_DTypeT = TypeVar("_DTypeT", bound=np.dtype)
+_DTypeT_co = TypeVar("_DTypeT_co", bound=np.dtype, default=np.dtype, covariant=True)
 
 _BoolArrayT = TypeVar("_BoolArrayT", bound=container[Any, np.dtype[np.bool]])
 _IntegralArrayT = TypeVar("_IntegralArrayT", bound=container[Any, np.dtype[np.bool | np.integer | np.object_]])
@@ -95,7 +95,7 @@ class container(Generic[_ShapeT_co, _DTypeT_co]):
     @overload
     def __getitem__(self: container[Any, np.dtype[np.void]], key: list[str], /) -> container[_ShapeT_co, np.dtype[np.void]]: ...
     @overload
-    def __getitem__(self: container[Any, np.dtype[np.void]], key: str, /) -> container[_ShapeT_co, np.dtype[Any]]: ...
+    def __getitem__(self: container[Any, np.dtype[np.void]], key: str, /) -> container[_ShapeT_co, np.dtype]: ...
 
     # keep in sync with np.ndarray
     @overload
diff --git a/numpy/lib/recfunctions.pyi b/numpy/lib/recfunctions.pyi
index 442530e9cd39..a80086b75d85 100644
--- a/numpy/lib/recfunctions.pyi
+++ b/numpy/lib/recfunctions.pyi
@@ -36,7 +36,7 @@ __all__ = [
 _T = TypeVar("_T")
 _ShapeT = TypeVar("_ShapeT", bound=tuple[int, ...])
 _ScalarT = TypeVar("_ScalarT", bound=np.generic)
-_DTypeT = TypeVar("_DTypeT", bound=np.dtype[Any])
+_DTypeT = TypeVar("_DTypeT", bound=np.dtype)
 _ArrayT = TypeVar("_ArrayT", bound=npt.NDArray[Any])
 _VoidArrayT = TypeVar("_VoidArrayT", bound=npt.NDArray[np.void])
 _NonVoidDTypeT = TypeVar("_NonVoidDTypeT", bound=_NonVoidDType)
@@ -62,7 +62,7 @@ def get_names_flat(adtype: np.dtype[np.void]) -> tuple[str, ...]: ...
 @overload
 def flatten_descr(ndtype: _NonVoidDTypeT) -> tuple[tuple[Literal[""], _NonVoidDTypeT]]: ...
 @overload
-def flatten_descr(ndtype: np.dtype[np.void]) -> tuple[tuple[str, np.dtype[Any]]]: ...
+def flatten_descr(ndtype: np.dtype[np.void]) -> tuple[tuple[str, np.dtype]]: ...
 
 #
 def get_fieldstructure(
@@ -74,7 +74,7 @@ def get_fieldstructure(
 #
 @overload
 def merge_arrays(
-    seqarrays: Sequence[np.ndarray[_ShapeT, np.dtype[Any]]] | np.ndarray[_ShapeT, np.dtype[Any]],
+    seqarrays: Sequence[np.ndarray[_ShapeT, np.dtype]] | np.ndarray[_ShapeT, np.dtype],
     fill_value: float = -1,
     flatten: bool = False,
     usemask: bool = False,
@@ -141,7 +141,7 @@ def append_fields(
     base: np.ndarray[_ShapeT, np.dtype[np.void]],
     names: _OneOrMany[str],
     data: _OneOrMany[npt.NDArray[Any]],
-    dtypes: _BuiltinSequence[np.dtype[Any]] | None,
+    dtypes: _BuiltinSequence[np.dtype] | None,
     fill_value: int,
     usemask: Literal[False],
     asrecarray: Literal[False] = False,
@@ -151,7 +151,7 @@ def append_fields(
     base: np.ndarray[_ShapeT, np.dtype[np.void]],
     names: _OneOrMany[str],
     data: _OneOrMany[npt.NDArray[Any]],
-    dtypes: _BuiltinSequence[np.dtype[Any]] | None = None,
+    dtypes: _BuiltinSequence[np.dtype] | None = None,
     fill_value: int = -1,
     *,
     usemask: Literal[False],
@@ -162,7 +162,7 @@ def append_fields(
     base: np.ndarray[_ShapeT, np.dtype[np.void]],
     names: _OneOrMany[str],
     data: _OneOrMany[npt.NDArray[Any]],
-    dtypes: _BuiltinSequence[np.dtype[Any]] | None,
+    dtypes: _BuiltinSequence[np.dtype] | None,
     fill_value: int,
     usemask: Literal[False],
     asrecarray: Literal[True],
@@ -172,7 +172,7 @@ def append_fields(
     base: np.ndarray[_ShapeT, np.dtype[np.void]],
     names: _OneOrMany[str],
     data: _OneOrMany[npt.NDArray[Any]],
-    dtypes: _BuiltinSequence[np.dtype[Any]] | None = None,
+    dtypes: _BuiltinSequence[np.dtype] | None = None,
     fill_value: int = -1,
     *,
     usemask: Literal[False],
@@ -183,7 +183,7 @@ def append_fields(
     base: np.ndarray[_ShapeT, np.dtype[np.void]],
     names: _OneOrMany[str],
     data: _OneOrMany[npt.NDArray[Any]],
-    dtypes: _BuiltinSequence[np.dtype[Any]] | None = None,
+    dtypes: _BuiltinSequence[np.dtype] | None = None,
     fill_value: int = -1,
     usemask: Literal[True] = True,
     asrecarray: Literal[False] = False,
@@ -193,7 +193,7 @@ def append_fields(
     base: np.ndarray[_ShapeT, np.dtype[np.void]],
     names: _OneOrMany[str],
     data: _OneOrMany[npt.NDArray[Any]],
-    dtypes: _BuiltinSequence[np.dtype[Any]] | None,
+    dtypes: _BuiltinSequence[np.dtype] | None,
     fill_value: int,
     usemask: Literal[True],
     asrecarray: Literal[True],
@@ -203,7 +203,7 @@ def append_fields(
     base: np.ndarray[_ShapeT, np.dtype[np.void]],
     names: _OneOrMany[str],
     data: _OneOrMany[npt.NDArray[Any]],
-    dtypes: _BuiltinSequence[np.dtype[Any]] | None = None,
+    dtypes: _BuiltinSequence[np.dtype] | None = None,
     fill_value: int = -1,
     usemask: Literal[True] = True,
     *,
@@ -221,7 +221,7 @@ def rec_append_fields(
     base: np.ndarray[_ShapeT, np.dtype[np.void]],
     names: _OneOrMany[str],
     data: _OneOrMany[npt.NDArray[Any]],
-    dtypes: _BuiltinSequence[np.dtype[Any]] | None = None,
+    dtypes: _BuiltinSequence[np.dtype] | None = None,
 ) -> np.ma.MaskedArray[_ShapeT, np.dtype[np.void]]: ...
 
 # TODO(jorenham): Stop passing `void` directly once structured dtypes are implemented,
diff --git a/numpy/ma/mrecords.pyi b/numpy/ma/mrecords.pyi
index 019ecc6faed7..6e608c8cbca1 100644
--- a/numpy/ma/mrecords.pyi
+++ b/numpy/ma/mrecords.pyi
@@ -13,7 +13,7 @@ __all__ = [
 ]
 
 _ShapeT_co = TypeVar("_ShapeT_co", covariant=True, bound=tuple[int, ...])
-_DTypeT_co = TypeVar("_DTypeT_co", bound=dtype[Any], covariant=True)
+_DTypeT_co = TypeVar("_DTypeT_co", bound=dtype, covariant=True)
 
 class MaskedRecords(MaskedArray[_ShapeT_co, _DTypeT_co]):
     def __new__(
diff --git a/numpy/typing/tests/data/pass/array_like.py b/numpy/typing/tests/data/pass/array_like.py
index fe0f9558ca12..264ec55da053 100644
--- a/numpy/typing/tests/data/pass/array_like.py
+++ b/numpy/typing/tests/data/pass/array_like.py
@@ -1,6 +1,6 @@
 from __future__ import annotations
 
-from typing import Any, TYPE_CHECKING
+from typing import TYPE_CHECKING
 
 import numpy as np
 
@@ -22,9 +22,7 @@
 
 
 class A:
-    def __array__(
-        self, dtype: np.dtype[Any] | None = None
-    ) -> NDArray[np.float64]:
+    def __array__(self, dtype: np.dtype | None = None) -> NDArray[np.float64]:
         return np.array([1.0, 2.0, 3.0])
 
 
diff --git a/numpy/typing/tests/data/pass/recfunctions.py b/numpy/typing/tests/data/pass/recfunctions.py
index 576277c24868..d6290a23680e 100644
--- a/numpy/typing/tests/data/pass/recfunctions.py
+++ b/numpy/typing/tests/data/pass/recfunctions.py
@@ -37,7 +37,7 @@ def test_get_names_flat() -> None:
 
 def test_flatten_descr() -> None:
     ndtype = np.dtype([("a", " None:
diff --git a/numpy/typing/tests/data/reveal/array_constructors.pyi b/numpy/typing/tests/data/reveal/array_constructors.pyi
index 4dfad431421f..c4099088a547 100644
--- a/numpy/typing/tests/data/reveal/array_constructors.pyi
+++ b/numpy/typing/tests/data/reveal/array_constructors.pyi
@@ -117,8 +117,8 @@ assert_type(np.arange(0, np.timedelta64(10)), np.ndarray[tuple[int], np.dtype[np
 assert_type(np.arange(np.datetime64("0"), np.datetime64("10")), np.ndarray[tuple[int], np.dtype[np.datetime64]])
 assert_type(np.arange(10, dtype=np.float64), np.ndarray[tuple[int], np.dtype[np.float64]])
 assert_type(np.arange(0, 10, step=2, dtype=np.int16), np.ndarray[tuple[int], np.dtype[np.int16]])
-assert_type(np.arange(10, dtype=int), np.ndarray[tuple[int], np.dtype[Any]])
-assert_type(np.arange(0, 10, dtype="f8"), np.ndarray[tuple[int], np.dtype[Any]])
+assert_type(np.arange(10, dtype=int), np.ndarray[tuple[int], np.dtype])
+assert_type(np.arange(0, 10, dtype="f8"), np.ndarray[tuple[int], np.dtype])
 
 assert_type(np.require(A), npt.NDArray[np.float64])
 assert_type(np.require(B), SubClass[np.float64])
@@ -191,9 +191,9 @@ assert_type(np.full(_shape_2d, i8), np.ndarray[tuple[int, int], np.dtype[np.int6
 assert_type(np.full(_shape_like, i8), npt.NDArray[np.int64])
 assert_type(np.full(_shape_like, 42), npt.NDArray[Any])
 assert_type(np.full(_size, i8, dtype=np.float64), np.ndarray[tuple[int], np.dtype[np.float64]])
-assert_type(np.full(_size, i8, dtype=float), np.ndarray[tuple[int], np.dtype[Any]])
+assert_type(np.full(_size, i8, dtype=float), np.ndarray[tuple[int], np.dtype])
 assert_type(np.full(_shape_like, 42, dtype=float), npt.NDArray[Any])
-assert_type(np.full(_shape_0d, i8, dtype=object), np.ndarray[tuple[()], np.dtype[Any]])
+assert_type(np.full(_shape_0d, i8, dtype=object), np.ndarray[tuple[()], np.dtype])
 
 assert_type(np.indices([1, 2, 3]), npt.NDArray[np.int_])
 assert_type(np.indices([1, 2, 3], sparse=True), tuple[npt.NDArray[np.int_], ...])
diff --git a/numpy/typing/tests/data/reveal/ctypeslib.pyi b/numpy/typing/tests/data/reveal/ctypeslib.pyi
index 10ef143d4655..dee2760d74e9 100644
--- a/numpy/typing/tests/data/reveal/ctypeslib.pyi
+++ b/numpy/typing/tests/data/reveal/ctypeslib.pyi
@@ -28,10 +28,10 @@ assert_type(np.ctypeslib.c_intp(), ctypeslib.c_intp)
 
 assert_type(np.ctypeslib.ndpointer(), type[ctypeslib._ndptr[None]])
 assert_type(np.ctypeslib.ndpointer(dtype=np.float64), type[ctypeslib._ndptr[np.dtype[np.float64]]])
-assert_type(np.ctypeslib.ndpointer(dtype=float), type[ctypeslib._ndptr[np.dtype[Any]]])
+assert_type(np.ctypeslib.ndpointer(dtype=float), type[ctypeslib._ndptr[np.dtype]])
 assert_type(np.ctypeslib.ndpointer(shape=(10, 3)), type[ctypeslib._ndptr[None]])
 assert_type(np.ctypeslib.ndpointer(np.int64, shape=(10, 3)), type[ctypeslib._concrete_ndptr[np.dtype[np.int64]]])
-assert_type(np.ctypeslib.ndpointer(int, shape=(1,)), type[np.ctypeslib._concrete_ndptr[np.dtype[Any]]])
+assert_type(np.ctypeslib.ndpointer(int, shape=(1,)), type[np.ctypeslib._concrete_ndptr[np.dtype]])
 
 assert_type(np.ctypeslib.as_ctypes_type(np.bool), type[ct.c_bool])
 assert_type(np.ctypeslib.as_ctypes_type(np.ubyte), type[ct.c_ubyte])
diff --git a/numpy/typing/tests/data/reveal/dtype.pyi b/numpy/typing/tests/data/reveal/dtype.pyi
index f7581a305503..04c1a7090b95 100644
--- a/numpy/typing/tests/data/reveal/dtype.pyi
+++ b/numpy/typing/tests/data/reveal/dtype.pyi
@@ -95,7 +95,7 @@ assert_type(np.dtype(np.dtype(np.float64)), np.dtype[np.float64])
 assert_type(np.dtype(dt_inexact), np.dtype[np.inexact[Any]])
 
 # Parameterized dtypes
-assert_type(np.dtype("S8"), np.dtype[Any])
+assert_type(np.dtype("S8"), np.dtype)
 
 # Void
 assert_type(np.dtype(("U", 10)), np.dtype[np.void])
@@ -107,8 +107,8 @@ assert_type(np.dtype("=T"), StringDType)
 assert_type(np.dtype("|T"), StringDType)
 
 # Methods and attributes
-assert_type(dtype_U.base, np.dtype[Any])
-assert_type(dtype_U.subdtype, tuple[np.dtype[Any], tuple[int, ...]] | None)
+assert_type(dtype_U.base, np.dtype)
+assert_type(dtype_U.subdtype, tuple[np.dtype, tuple[int, ...]] | None)
 assert_type(dtype_U.newbyteorder(), np.dtype[np.str_])
 assert_type(dtype_U.type, type[np.str_])
 assert_type(dtype_U.name, LiteralString)
@@ -126,11 +126,11 @@ assert_type(0 * dtype_U, np.dtype[np.str_])
 assert_type(1 * dtype_U, np.dtype[np.str_])
 assert_type(2 * dtype_U, np.dtype[np.str_])
 
-assert_type(0 * dtype_i8, np.dtype[Any])
-assert_type(1 * dtype_i8, np.dtype[Any])
-assert_type(2 * dtype_i8, np.dtype[Any])
+assert_type(0 * dtype_i8, np.dtype)
+assert_type(1 * dtype_i8, np.dtype)
+assert_type(2 * dtype_i8, np.dtype)
 
-assert_type(dtype_V["f0"], np.dtype[Any])
-assert_type(dtype_V[0], np.dtype[Any])
+assert_type(dtype_V["f0"], np.dtype)
+assert_type(dtype_V[0], np.dtype)
 assert_type(dtype_V[["f0", "f1"]], np.dtype[np.void])
 assert_type(dtype_V[["f0"]], np.dtype[np.void])
diff --git a/numpy/typing/tests/data/reveal/fromnumeric.pyi b/numpy/typing/tests/data/reveal/fromnumeric.pyi
index 48682a179c6b..71d06e4b76e4 100644
--- a/numpy/typing/tests/data/reveal/fromnumeric.pyi
+++ b/numpy/typing/tests/data/reveal/fromnumeric.pyi
@@ -16,9 +16,9 @@ AR_i8: npt.NDArray[np.int64]
 AR_O: npt.NDArray[np.object_]
 AR_subclass: NDArraySubclass
 AR_m: npt.NDArray[np.timedelta64]
-AR_0d: np.ndarray[tuple[()], np.dtype[Any]]
-AR_1d: np.ndarray[tuple[int], np.dtype[Any]]
-AR_nd: np.ndarray[tuple[int, ...], np.dtype[Any]]
+AR_0d: np.ndarray[tuple[()], np.dtype]
+AR_1d: np.ndarray[tuple[int], np.dtype]
+AR_nd: np.ndarray[tuple[int, ...], np.dtype]
 
 b: np.bool
 f4: np.float32
@@ -37,7 +37,7 @@ assert_type(np.take(AR_f4, [0], out=AR_subclass), NDArraySubclass)
 
 assert_type(np.reshape(b, 1), np.ndarray[tuple[int], np.dtype[np.bool]])
 assert_type(np.reshape(f4, 1), np.ndarray[tuple[int], np.dtype[np.float32]])
-assert_type(np.reshape(f, 1), np.ndarray[tuple[int], np.dtype[Any]])
+assert_type(np.reshape(f, 1), np.ndarray[tuple[int], np.dtype])
 assert_type(np.reshape(AR_b, 1), np.ndarray[tuple[int], np.dtype[np.bool]])
 assert_type(np.reshape(AR_f4, 1), np.ndarray[tuple[int], np.dtype[np.float32]])
 
@@ -102,7 +102,7 @@ assert_type(np.searchsorted(AR_f4[0], [0]), npt.NDArray[np.intp])
 
 assert_type(np.resize(b, (5, 5)), np.ndarray[tuple[int, int], np.dtype[np.bool]])
 assert_type(np.resize(f4, (5, 5)), np.ndarray[tuple[int, int], np.dtype[np.float32]])
-assert_type(np.resize(f, (5, 5)), np.ndarray[tuple[int, int], np.dtype[Any]])
+assert_type(np.resize(f, (5, 5)), np.ndarray[tuple[int, int], np.dtype])
 assert_type(np.resize(AR_b, (5, 5)), np.ndarray[tuple[int, int], np.dtype[np.bool]])
 assert_type(np.resize(AR_f4, (5, 5)), np.ndarray[tuple[int, int], np.dtype[np.float32]])
 
diff --git a/numpy/typing/tests/data/reveal/memmap.pyi b/numpy/typing/tests/data/reveal/memmap.pyi
index 6ee2853a64ab..f3e20ed2d5e7 100644
--- a/numpy/typing/tests/data/reveal/memmap.pyi
+++ b/numpy/typing/tests/data/reveal/memmap.pyi
@@ -14,6 +14,6 @@ assert_type(memmap_obj.flush(), None)
 assert_type(np.memmap("file.txt", offset=5), np.memmap[Any, np.dtype[np.uint8]])
 assert_type(np.memmap(b"file.txt", dtype=np.float64, shape=(10, 3)), np.memmap[Any, np.dtype[np.float64]])
 with open("file.txt", "rb") as f:
-    assert_type(np.memmap(f, dtype=float, order="K"), np.memmap[Any, np.dtype[Any]])
+    assert_type(np.memmap(f, dtype=float, order="K"), np.memmap[Any, np.dtype])
 
 assert_type(memmap_obj.__array_finalize__(object()), None)
diff --git a/numpy/typing/tests/data/reveal/multiarray.pyi b/numpy/typing/tests/data/reveal/multiarray.pyi
index dd55b061002b..ec5d8aa525c6 100644
--- a/numpy/typing/tests/data/reveal/multiarray.pyi
+++ b/numpy/typing/tests/data/reveal/multiarray.pyi
@@ -72,12 +72,12 @@ assert_type(np.can_cast(np.dtype("i8"), int), bool)
 assert_type(np.can_cast(AR_f8, "f8"), bool)
 assert_type(np.can_cast(AR_f8, np.complex128, casting="unsafe"), bool)
 
-assert_type(np.min_scalar_type([1]), np.dtype[Any])
-assert_type(np.min_scalar_type(AR_f8), np.dtype[Any])
+assert_type(np.min_scalar_type([1]), np.dtype)
+assert_type(np.min_scalar_type(AR_f8), np.dtype)
 
-assert_type(np.result_type(int, [1]), np.dtype[Any])
-assert_type(np.result_type(AR_f8, AR_u1), np.dtype[Any])
-assert_type(np.result_type(AR_f8, np.complex128), np.dtype[Any])
+assert_type(np.result_type(int, [1]), np.dtype)
+assert_type(np.result_type(AR_f8, AR_u1), np.dtype)
+assert_type(np.result_type(AR_f8, np.complex128), np.dtype)
 
 assert_type(np.dot(AR_LIKE_f, AR_i8), Any)
 assert_type(np.dot(AR_u1, 1), Any)
@@ -105,8 +105,8 @@ assert_type(np.shares_memory(AR_f8, AR_f8, max_work=1), bool)
 assert_type(np.may_share_memory(1, 2), bool)
 assert_type(np.may_share_memory(AR_f8, AR_f8, max_work=1), bool)
 
-assert_type(np.promote_types(np.int32, np.int64), np.dtype[Any])
-assert_type(np.promote_types("f4", float), np.dtype[Any])
+assert_type(np.promote_types(np.int32, np.int64), np.dtype)
+assert_type(np.promote_types("f4", float), np.dtype)
 
 assert_type(np.frompyfunc(func11, n1, n1).nin, Literal[1])
 assert_type(np.frompyfunc(func11, n1, n1).nout, Literal[1])
diff --git a/numpy/typing/tests/data/reveal/ndarray_conversion.pyi b/numpy/typing/tests/data/reveal/ndarray_conversion.pyi
index 2331c26871fe..cd40b74e2e56 100644
--- a/numpy/typing/tests/data/reveal/ndarray_conversion.pyi
+++ b/numpy/typing/tests/data/reveal/ndarray_conversion.pyi
@@ -60,7 +60,7 @@ assert_type(np.astype(i4_2d, np.uint16), np.ndarray[tuple[int, int], np.dtype[np
 assert_type(f8_3d.astype(np.int16), np.ndarray[tuple[int, int, int], np.dtype[np.int16]])
 assert_type(np.astype(f8_3d, np.int16), np.ndarray[tuple[int, int, int], np.dtype[np.int16]])
 assert_type(i4_2d.astype(uncertain_dtype), np.ndarray[tuple[int, int], np.dtype[np.generic[Any]]])
-assert_type(np.astype(i4_2d, uncertain_dtype), np.ndarray[tuple[int, int], np.dtype[Any]])
+assert_type(np.astype(i4_2d, uncertain_dtype), np.ndarray[tuple[int, int], np.dtype])
 
 # byteswap
 assert_type(i0_nd.byteswap(), npt.NDArray[np.int_])
diff --git a/numpy/typing/tests/data/reveal/nditer.pyi b/numpy/typing/tests/data/reveal/nditer.pyi
index 4d7d6f39d087..8965f3c03e6d 100644
--- a/numpy/typing/tests/data/reveal/nditer.pyi
+++ b/numpy/typing/tests/data/reveal/nditer.pyi
@@ -10,7 +10,7 @@ assert_type(np.nditer([0, 1], op_flags=[["readonly", "readonly"]]), np.nditer)
 assert_type(np.nditer([0, 1], op_dtypes=np.int_), np.nditer)
 assert_type(np.nditer([0, 1], order="C", casting="no"), np.nditer)
 
-assert_type(nditer_obj.dtypes, tuple[np.dtype[Any], ...])
+assert_type(nditer_obj.dtypes, tuple[np.dtype, ...])
 assert_type(nditer_obj.finished, bool)
 assert_type(nditer_obj.has_delayed_bufalloc, bool)
 assert_type(nditer_obj.has_index, bool)
diff --git a/numpy/typing/tests/data/reveal/rec.pyi b/numpy/typing/tests/data/reveal/rec.pyi
index 52f404400e02..f55fcd272eae 100644
--- a/numpy/typing/tests/data/reveal/rec.pyi
+++ b/numpy/typing/tests/data/reveal/rec.pyi
@@ -50,13 +50,13 @@ assert_type(
         dtype=[("f8", np.float64), ("i8", np.int64)],
         strides=(5, 5),
     ),
-    np.recarray[Any, np.dtype[Any]],
+    np.recarray[Any, np.dtype],
 )
 
-assert_type(np.rec.fromarrays(AR_LIST), np.recarray[Any, np.dtype[Any]])
+assert_type(np.rec.fromarrays(AR_LIST), np.recarray[Any, np.dtype])
 assert_type(
     np.rec.fromarrays(AR_LIST, dtype=np.int64),
-    np.recarray[Any, np.dtype[Any]],
+    np.recarray[Any, np.dtype],
 )
 assert_type(
     np.rec.fromarrays(
@@ -109,7 +109,7 @@ assert_type(
 assert_type(np.rec.fromfile(
     "test_file.txt",
     dtype=[("i8", np.int64), ("f8", np.float64)],
-), np.recarray[Any, np.dtype[Any]])
+), np.recarray[Any, np.dtype])
 
 assert_type(
     np.rec.fromfile(
@@ -124,7 +124,7 @@ assert_type(np.rec.array(AR_i8), np.recarray[Any, np.dtype[np.int64]])
 
 assert_type(
     np.rec.array([(1, 1.5)], dtype=[("i8", np.int64), ("f8", np.float64)]),
-    np.recarray[Any, np.dtype[Any]],
+    np.recarray[Any, np.dtype],
 )
 
 assert_type(
@@ -142,7 +142,7 @@ assert_type(
         dtype=np.float64,
         shape=(10, 3),
     ),
-    np.recarray[Any, np.dtype[Any]],
+    np.recarray[Any, np.dtype],
 )
 
 assert_type(
@@ -157,7 +157,7 @@ assert_type(
 
 assert_type(
     np.rec.array(file_obj, dtype=np.float64),
-    np.recarray[Any, np.dtype[Any]],
+    np.recarray[Any, np.dtype],
 )
 
 assert_type(

From 2594b05d692aa7c7549043ad0c2410710731b1f5 Mon Sep 17 00:00:00 2001
From: jorenham 
Date: Thu, 24 Apr 2025 02:51:33 +0200
Subject: [PATCH 096/202] DOC: replace ``dtype[Any]`` in
 ``ndarray.__class_getitem__`` with ``dtype[uint8]``

---
 numpy/_core/_add_newdocs.py | 4 ++--
 1 file changed, 2 insertions(+), 2 deletions(-)

diff --git a/numpy/_core/_add_newdocs.py b/numpy/_core/_add_newdocs.py
index 90b3d91d9578..9f452931fcf1 100644
--- a/numpy/_core/_add_newdocs.py
+++ b/numpy/_core/_add_newdocs.py
@@ -3027,8 +3027,8 @@
     >>> from typing import Any
     >>> import numpy as np
 
-    >>> np.ndarray[Any, np.dtype[Any]]
-    numpy.ndarray[typing.Any, numpy.dtype[typing.Any]]
+    >>> np.ndarray[Any, np.dtype[np.uint8]]
+    numpy.ndarray[typing.Any, numpy.dtype[numpy.uint8]]
 
     See Also
     --------

From f5ab6682b35c53eb793078ee31f58495ba0ee4cb Mon Sep 17 00:00:00 2001
From: jorenham 
Date: Thu, 24 Apr 2025 03:51:49 +0200
Subject: [PATCH 097/202] TYP: revert the ``type[Any]`` simplification to
 prevent a mypy false-positive from being reported in the numpy compat code of
 ``xarray``

---
 numpy/_core/numerictypes.pyi | 4 ++--
 1 file changed, 2 insertions(+), 2 deletions(-)

diff --git a/numpy/_core/numerictypes.pyi b/numpy/_core/numerictypes.pyi
index 3f06991adf8f..f04d11303ad5 100644
--- a/numpy/_core/numerictypes.pyi
+++ b/numpy/_core/numerictypes.pyi
@@ -1,5 +1,5 @@
 import builtins
-from typing import Literal as L, TypedDict, type_check_only
+from typing import Any, Literal as L, TypedDict, type_check_only
 
 import numpy as np
 from numpy import (
@@ -172,7 +172,7 @@ class _TypeCodes(TypedDict):
     Datetime: L['Mm']
     All: L['?bhilqnpBHILQNPefdgFDGSUVOMm']
 
-def isdtype(dtype: dtype | type, kind: DTypeLike | tuple[DTypeLike, ...]) -> builtins.bool: ...
+def isdtype(dtype: dtype | type[Any], kind: DTypeLike | tuple[DTypeLike, ...]) -> builtins.bool: ...
 
 def issubdtype(arg1: DTypeLike, arg2: DTypeLike) -> builtins.bool: ...
 

From 3d4e1bb16bea444adcd7095b8f60e1f777760e81 Mon Sep 17 00:00:00 2001
From: jorenham 
Date: Thu, 24 Apr 2025 04:14:43 +0200
Subject: [PATCH 098/202] TYP: remove unnecessary scalar-type ``Any`` type-args

---
 numpy/__init__.pyi                            | 214 +++++++++---------
 numpy/_core/_type_aliases.pyi                 |   8 +-
 numpy/_core/einsumfunc.pyi                    |   2 +-
 numpy/_core/fromnumeric.pyi                   |  22 +-
 numpy/_core/multiarray.pyi                    |   8 +-
 numpy/_core/numeric.pyi                       |  40 ++--
 numpy/_typing/_callable.pyi                   |  16 +-
 numpy/lib/_function_base_impl.pyi             |  54 ++---
 numpy/lib/_polynomial_impl.pyi                |  40 ++--
 numpy/lib/_scimath_impl.pyi                   |  36 +--
 numpy/lib/_shape_base_impl.pyi                |  12 +-
 numpy/lib/_twodim_base_impl.pyi               |   6 +-
 numpy/lib/_ufunclike_impl.pyi                 |   4 +-
 numpy/linalg/_linalg.pyi                      |  76 +++----
 numpy/polynomial/_polybase.pyi                |  10 +-
 numpy/polynomial/_polytypes.pyi               |  46 ++--
 numpy/polynomial/chebyshev.pyi                |   4 +-
 numpy/polynomial/polyutils.pyi                |  54 ++---
 numpy/typing/tests/data/reveal/arithmetic.pyi |  82 +++----
 .../tests/data/reveal/array_constructors.pyi  |  26 +--
 numpy/typing/tests/data/reveal/arraypad.pyi   |   2 +-
 numpy/typing/tests/data/reveal/arrayprint.pyi |   4 +-
 .../typing/tests/data/reveal/bitwise_ops.pyi  |  50 ++--
 numpy/typing/tests/data/reveal/dtype.pyi      |   8 +-
 numpy/typing/tests/data/reveal/emath.pyi      |  36 +--
 numpy/typing/tests/data/reveal/fft.pyi        |   8 +-
 .../typing/tests/data/reveal/fromnumeric.pyi  |  40 ++--
 numpy/typing/tests/data/reveal/getlimits.pyi  |   2 +-
 .../tests/data/reveal/lib_function_base.pyi   |  66 +++---
 .../tests/data/reveal/lib_polynomial.pyi      |  56 ++---
 numpy/typing/tests/data/reveal/linalg.pyi     |  82 +++----
 numpy/typing/tests/data/reveal/multiarray.pyi |   6 +-
 .../tests/data/reveal/ndarray_conversion.pyi  |   2 +-
 numpy/typing/tests/data/reveal/numeric.pyi    |  66 +++---
 .../tests/data/reveal/polynomial_polybase.pyi |  24 +-
 .../data/reveal/polynomial_polyutils.pyi      |  32 +--
 .../tests/data/reveal/polynomial_series.pyi   |  72 +++---
 numpy/typing/tests/data/reveal/shape_base.pyi |   4 +-
 numpy/typing/tests/data/reveal/testing.pyi    |   4 +-
 .../typing/tests/data/reveal/twodim_base.pyi  |  12 +-
 numpy/typing/tests/data/reveal/ufunclike.pyi  |   8 +-
 41 files changed, 669 insertions(+), 675 deletions(-)

diff --git a/numpy/__init__.pyi b/numpy/__init__.pyi
index c2bef3a54d35..5c16b91b7772 100644
--- a/numpy/__init__.pyi
+++ b/numpy/__init__.pyi
@@ -804,9 +804,9 @@ _FlexDTypeT = TypeVar("_FlexDTypeT", bound=dtype[flexible])
 
 _ArrayT = TypeVar("_ArrayT", bound=NDArray[Any])
 _ArrayT_co = TypeVar("_ArrayT_co", bound=NDArray[Any], covariant=True)
-_IntegralArrayT = TypeVar("_IntegralArrayT", bound=NDArray[integer[Any] | np.bool | object_])
-_RealArrayT = TypeVar("_RealArrayT", bound=NDArray[floating[Any] | integer[Any] | timedelta64 | np.bool | object_])
-_NumericArrayT = TypeVar("_NumericArrayT", bound=NDArray[number[Any] | timedelta64 | object_])
+_IntegralArrayT = TypeVar("_IntegralArrayT", bound=NDArray[integer | np.bool | object_])
+_RealArrayT = TypeVar("_RealArrayT", bound=NDArray[floating | integer | timedelta64 | np.bool | object_])
+_NumericArrayT = TypeVar("_NumericArrayT", bound=NDArray[number | timedelta64 | object_])
 
 _ShapeT = TypeVar("_ShapeT", bound=_Shape)
 _ShapeT_co = TypeVar("_ShapeT_co", bound=_Shape, covariant=True)
@@ -816,11 +816,11 @@ _1NShapeT = TypeVar("_1NShapeT", bound=tuple[L[1], *tuple[L[1], ...]])  # (1,) |
 
 _ScalarT = TypeVar("_ScalarT", bound=generic)
 _ScalarT_co = TypeVar("_ScalarT_co", bound=generic, default=Any, covariant=True)
-_NumberT = TypeVar("_NumberT", bound=number[Any])
+_NumberT = TypeVar("_NumberT", bound=number)
 _RealNumberT = TypeVar("_RealNumberT", bound=floating | integer)
-_FloatingT_co = TypeVar("_FloatingT_co", bound=floating[Any], default=floating[Any], covariant=True)
+_FloatingT_co = TypeVar("_FloatingT_co", bound=floating, default=floating, covariant=True)
 _IntegerT = TypeVar("_IntegerT", bound=integer)
-_IntegerT_co = TypeVar("_IntegerT_co", bound=integer[Any], default=integer[Any], covariant=True)
+_IntegerT_co = TypeVar("_IntegerT_co", bound=integer, default=integer, covariant=True)
 
 _NBit = TypeVar("_NBit", bound=NBitBase, default=Any)
 _NBit1 = TypeVar("_NBit1", bound=NBitBase, default=Any)
@@ -829,8 +829,8 @@ _NBit2 = TypeVar("_NBit2", bound=NBitBase, default=_NBit1)
 _ItemT_co = TypeVar("_ItemT_co", default=Any, covariant=True)
 _BoolItemT = TypeVar("_BoolItemT", bound=builtins.bool)
 _BoolItemT_co = TypeVar("_BoolItemT_co", bound=builtins.bool, default=builtins.bool, covariant=True)
-_NumberItemT_co = TypeVar("_NumberItemT_co", bound=int | float | complex, default=int | float | complex, covariant=True)
-_InexactItemT_co = TypeVar("_InexactItemT_co", bound=float | complex, default=float | complex, covariant=True)
+_NumberItemT_co = TypeVar("_NumberItemT_co", bound=complex, default=int | float | complex, covariant=True)
+_InexactItemT_co = TypeVar("_InexactItemT_co", bound=complex, default=float | complex, covariant=True)
 _FlexibleItemT_co = TypeVar(
     "_FlexibleItemT_co",
     bound=_CharLike_co | tuple[Any, ...],
@@ -1429,7 +1429,7 @@ class dtype(Generic[_ScalarT_co], metaclass=_DTypeMeta):
         align: builtins.bool = ...,
         copy: builtins.bool = ...,
         metadata: dict[builtins.str, Any] = ...,
-    ) -> dtype[unsignedinteger[Any]]: ...
+    ) -> dtype[unsignedinteger]: ...
     @overload
     def __new__(
         cls,
@@ -1437,7 +1437,7 @@ class dtype(Generic[_ScalarT_co], metaclass=_DTypeMeta):
         align: builtins.bool = ...,
         copy: builtins.bool = ...,
         metadata: dict[builtins.str, Any] = ...,
-    ) -> dtype[signedinteger[Any]]: ...
+    ) -> dtype[signedinteger]: ...
     @overload
     def __new__(
         cls,
@@ -1445,7 +1445,7 @@ class dtype(Generic[_ScalarT_co], metaclass=_DTypeMeta):
         align: builtins.bool = ...,
         copy: builtins.bool = ...,
         metadata: dict[builtins.str, Any] = ...,
-    ) -> dtype[integer[Any]]: ...
+    ) -> dtype[integer]: ...
     @overload
     def __new__(
         cls,
@@ -1453,7 +1453,7 @@ class dtype(Generic[_ScalarT_co], metaclass=_DTypeMeta):
         align: builtins.bool = ...,
         copy: builtins.bool = ...,
         metadata: dict[builtins.str, Any] = ...,
-    ) -> dtype[floating[Any]]: ...
+    ) -> dtype[floating]: ...
     @overload
     def __new__(
         cls,
@@ -1461,7 +1461,7 @@ class dtype(Generic[_ScalarT_co], metaclass=_DTypeMeta):
         align: builtins.bool = ...,
         copy: builtins.bool = ...,
         metadata: dict[builtins.str, Any] = ...,
-    ) -> dtype[complexfloating[Any, Any]]: ...
+    ) -> dtype[complexfloating]: ...
     @overload
     def __new__(
         cls,
@@ -1469,7 +1469,7 @@ class dtype(Generic[_ScalarT_co], metaclass=_DTypeMeta):
         align: builtins.bool = ...,
         copy: builtins.bool = ...,
         metadata: dict[builtins.str, Any] = ...,
-    ) -> dtype[inexact[Any]]: ...
+    ) -> dtype[inexact]: ...
     @overload
     def __new__(
         cls,
@@ -1477,7 +1477,7 @@ class dtype(Generic[_ScalarT_co], metaclass=_DTypeMeta):
         align: builtins.bool = ...,
         copy: builtins.bool = ...,
         metadata: dict[builtins.str, Any] = ...,
-    ) -> dtype[number[Any]]: ...
+    ) -> dtype[number]: ...
     @overload
     def __new__(
         cls,
@@ -1621,7 +1621,7 @@ class flatiter(Generic[_ArrayT_co]):
     @overload
     def __getitem__(
         self: flatiter[NDArray[_ScalarT]],
-        key: int | integer[Any] | tuple[int | integer[Any]],
+        key: int | integer | tuple[int | integer],
     ) -> _ScalarT: ...
     @overload
     def __getitem__(
@@ -2707,15 +2707,15 @@ class ndarray(_ArrayOrScalarCommon, Generic[_ShapeT_co, _DTypeT_co]):
     @overload
     def __rmatmul__(self: _ArrayComplex128_co, other: _ArrayLike[complexfloating[_64Bit]], /) -> NDArray[complex128]: ...
     @overload
-    def __rmatmul__(self: _ArrayUInt_co, other: _ArrayLikeUInt_co, /) -> NDArray[unsignedinteger[Any]]: ...  # type: ignore[overload-overlap]
+    def __rmatmul__(self: _ArrayUInt_co, other: _ArrayLikeUInt_co, /) -> NDArray[unsignedinteger]: ...  # type: ignore[overload-overlap]
     @overload
-    def __rmatmul__(self: _ArrayInt_co, other: _ArrayLikeInt_co, /) -> NDArray[signedinteger[Any]]: ...  # type: ignore[overload-overlap]
+    def __rmatmul__(self: _ArrayInt_co, other: _ArrayLikeInt_co, /) -> NDArray[signedinteger]: ...  # type: ignore[overload-overlap]
     @overload
-    def __rmatmul__(self: _ArrayFloat_co, other: _ArrayLikeFloat_co, /) -> NDArray[floating[Any]]: ...  # type: ignore[overload-overlap]
+    def __rmatmul__(self: _ArrayFloat_co, other: _ArrayLikeFloat_co, /) -> NDArray[floating]: ...  # type: ignore[overload-overlap]
     @overload
-    def __rmatmul__(self: _ArrayComplex_co, other: _ArrayLikeComplex_co, /) -> NDArray[complexfloating[Any, Any]]: ...
+    def __rmatmul__(self: _ArrayComplex_co, other: _ArrayLikeComplex_co, /) -> NDArray[complexfloating]: ...
     @overload
-    def __rmatmul__(self: NDArray[number], other: _ArrayLikeNumber_co, /) -> NDArray[number[Any]]: ...
+    def __rmatmul__(self: NDArray[number], other: _ArrayLikeNumber_co, /) -> NDArray[number]: ...
     @overload
     def __rmatmul__(self: NDArray[object_], other: Any, /) -> Any: ...
     @overload
@@ -3212,9 +3212,9 @@ class ndarray(_ArrayOrScalarCommon, Generic[_ShapeT_co, _DTypeT_co]):
     @overload
     def __lshift__(self: NDArray[np.bool], other: _ArrayLikeBool_co, /) -> NDArray[int8]: ...  # type: ignore[misc]
     @overload
-    def __lshift__(self: _ArrayUInt_co, other: _ArrayLikeUInt_co, /) -> NDArray[unsignedinteger[Any]]: ...  # type: ignore[misc]
+    def __lshift__(self: _ArrayUInt_co, other: _ArrayLikeUInt_co, /) -> NDArray[unsignedinteger]: ...  # type: ignore[misc]
     @overload
-    def __lshift__(self: _ArrayInt_co, other: _ArrayLikeInt_co, /) -> NDArray[signedinteger[Any]]: ...
+    def __lshift__(self: _ArrayInt_co, other: _ArrayLikeInt_co, /) -> NDArray[signedinteger]: ...
     @overload
     def __lshift__(self: NDArray[object_], other: Any, /) -> Any: ...
     @overload
@@ -3223,9 +3223,9 @@ class ndarray(_ArrayOrScalarCommon, Generic[_ShapeT_co, _DTypeT_co]):
     @overload
     def __rlshift__(self: NDArray[np.bool], other: _ArrayLikeBool_co, /) -> NDArray[int8]: ...  # type: ignore[misc]
     @overload
-    def __rlshift__(self: _ArrayUInt_co, other: _ArrayLikeUInt_co, /) -> NDArray[unsignedinteger[Any]]: ...  # type: ignore[misc]
+    def __rlshift__(self: _ArrayUInt_co, other: _ArrayLikeUInt_co, /) -> NDArray[unsignedinteger]: ...  # type: ignore[misc]
     @overload
-    def __rlshift__(self: _ArrayInt_co, other: _ArrayLikeInt_co, /) -> NDArray[signedinteger[Any]]: ...
+    def __rlshift__(self: _ArrayInt_co, other: _ArrayLikeInt_co, /) -> NDArray[signedinteger]: ...
     @overload
     def __rlshift__(self: NDArray[object_], other: Any, /) -> Any: ...
     @overload
@@ -3234,9 +3234,9 @@ class ndarray(_ArrayOrScalarCommon, Generic[_ShapeT_co, _DTypeT_co]):
     @overload
     def __rshift__(self: NDArray[np.bool], other: _ArrayLikeBool_co, /) -> NDArray[int8]: ...  # type: ignore[misc]
     @overload
-    def __rshift__(self: _ArrayUInt_co, other: _ArrayLikeUInt_co, /) -> NDArray[unsignedinteger[Any]]: ...  # type: ignore[misc]
+    def __rshift__(self: _ArrayUInt_co, other: _ArrayLikeUInt_co, /) -> NDArray[unsignedinteger]: ...  # type: ignore[misc]
     @overload
-    def __rshift__(self: _ArrayInt_co, other: _ArrayLikeInt_co, /) -> NDArray[signedinteger[Any]]: ...
+    def __rshift__(self: _ArrayInt_co, other: _ArrayLikeInt_co, /) -> NDArray[signedinteger]: ...
     @overload
     def __rshift__(self: NDArray[object_], other: Any, /) -> Any: ...
     @overload
@@ -3245,9 +3245,9 @@ class ndarray(_ArrayOrScalarCommon, Generic[_ShapeT_co, _DTypeT_co]):
     @overload
     def __rrshift__(self: NDArray[np.bool], other: _ArrayLikeBool_co, /) -> NDArray[int8]: ...  # type: ignore[misc]
     @overload
-    def __rrshift__(self: _ArrayUInt_co, other: _ArrayLikeUInt_co, /) -> NDArray[unsignedinteger[Any]]: ...  # type: ignore[misc]
+    def __rrshift__(self: _ArrayUInt_co, other: _ArrayLikeUInt_co, /) -> NDArray[unsignedinteger]: ...  # type: ignore[misc]
     @overload
-    def __rrshift__(self: _ArrayInt_co, other: _ArrayLikeInt_co, /) -> NDArray[signedinteger[Any]]: ...
+    def __rrshift__(self: _ArrayInt_co, other: _ArrayLikeInt_co, /) -> NDArray[signedinteger]: ...
     @overload
     def __rrshift__(self: NDArray[object_], other: Any, /) -> Any: ...
     @overload
@@ -3256,9 +3256,9 @@ class ndarray(_ArrayOrScalarCommon, Generic[_ShapeT_co, _DTypeT_co]):
     @overload
     def __and__(self: NDArray[np.bool], other: _ArrayLikeBool_co, /) -> NDArray[np.bool]: ...  # type: ignore[misc]
     @overload
-    def __and__(self: _ArrayUInt_co, other: _ArrayLikeUInt_co, /) -> NDArray[unsignedinteger[Any]]: ...  # type: ignore[misc]
+    def __and__(self: _ArrayUInt_co, other: _ArrayLikeUInt_co, /) -> NDArray[unsignedinteger]: ...  # type: ignore[misc]
     @overload
-    def __and__(self: _ArrayInt_co, other: _ArrayLikeInt_co, /) -> NDArray[signedinteger[Any]]: ...
+    def __and__(self: _ArrayInt_co, other: _ArrayLikeInt_co, /) -> NDArray[signedinteger]: ...
     @overload
     def __and__(self: NDArray[object_], other: Any, /) -> Any: ...
     @overload
@@ -3267,9 +3267,9 @@ class ndarray(_ArrayOrScalarCommon, Generic[_ShapeT_co, _DTypeT_co]):
     @overload
     def __rand__(self: NDArray[np.bool], other: _ArrayLikeBool_co, /) -> NDArray[np.bool]: ...  # type: ignore[misc]
     @overload
-    def __rand__(self: _ArrayUInt_co, other: _ArrayLikeUInt_co, /) -> NDArray[unsignedinteger[Any]]: ...  # type: ignore[misc]
+    def __rand__(self: _ArrayUInt_co, other: _ArrayLikeUInt_co, /) -> NDArray[unsignedinteger]: ...  # type: ignore[misc]
     @overload
-    def __rand__(self: _ArrayInt_co, other: _ArrayLikeInt_co, /) -> NDArray[signedinteger[Any]]: ...
+    def __rand__(self: _ArrayInt_co, other: _ArrayLikeInt_co, /) -> NDArray[signedinteger]: ...
     @overload
     def __rand__(self: NDArray[object_], other: Any, /) -> Any: ...
     @overload
@@ -3278,9 +3278,9 @@ class ndarray(_ArrayOrScalarCommon, Generic[_ShapeT_co, _DTypeT_co]):
     @overload
     def __xor__(self: NDArray[np.bool], other: _ArrayLikeBool_co, /) -> NDArray[np.bool]: ...  # type: ignore[misc]
     @overload
-    def __xor__(self: _ArrayUInt_co, other: _ArrayLikeUInt_co, /) -> NDArray[unsignedinteger[Any]]: ...  # type: ignore[misc]
+    def __xor__(self: _ArrayUInt_co, other: _ArrayLikeUInt_co, /) -> NDArray[unsignedinteger]: ...  # type: ignore[misc]
     @overload
-    def __xor__(self: _ArrayInt_co, other: _ArrayLikeInt_co, /) -> NDArray[signedinteger[Any]]: ...
+    def __xor__(self: _ArrayInt_co, other: _ArrayLikeInt_co, /) -> NDArray[signedinteger]: ...
     @overload
     def __xor__(self: NDArray[object_], other: Any, /) -> Any: ...
     @overload
@@ -3289,9 +3289,9 @@ class ndarray(_ArrayOrScalarCommon, Generic[_ShapeT_co, _DTypeT_co]):
     @overload
     def __rxor__(self: NDArray[np.bool], other: _ArrayLikeBool_co, /) -> NDArray[np.bool]: ...  # type: ignore[misc]
     @overload
-    def __rxor__(self: _ArrayUInt_co, other: _ArrayLikeUInt_co, /) -> NDArray[unsignedinteger[Any]]: ...  # type: ignore[misc]
+    def __rxor__(self: _ArrayUInt_co, other: _ArrayLikeUInt_co, /) -> NDArray[unsignedinteger]: ...  # type: ignore[misc]
     @overload
-    def __rxor__(self: _ArrayInt_co, other: _ArrayLikeInt_co, /) -> NDArray[signedinteger[Any]]: ...
+    def __rxor__(self: _ArrayInt_co, other: _ArrayLikeInt_co, /) -> NDArray[signedinteger]: ...
     @overload
     def __rxor__(self: NDArray[object_], other: Any, /) -> Any: ...
     @overload
@@ -3300,9 +3300,9 @@ class ndarray(_ArrayOrScalarCommon, Generic[_ShapeT_co, _DTypeT_co]):
     @overload
     def __or__(self: NDArray[np.bool], other: _ArrayLikeBool_co, /) -> NDArray[np.bool]: ...  # type: ignore[misc]
     @overload
-    def __or__(self: _ArrayUInt_co, other: _ArrayLikeUInt_co, /) -> NDArray[unsignedinteger[Any]]: ...  # type: ignore[misc]
+    def __or__(self: _ArrayUInt_co, other: _ArrayLikeUInt_co, /) -> NDArray[unsignedinteger]: ...  # type: ignore[misc]
     @overload
-    def __or__(self: _ArrayInt_co, other: _ArrayLikeInt_co, /) -> NDArray[signedinteger[Any]]: ...
+    def __or__(self: _ArrayInt_co, other: _ArrayLikeInt_co, /) -> NDArray[signedinteger]: ...
     @overload
     def __or__(self: NDArray[object_], other: Any, /) -> Any: ...
     @overload
@@ -3311,9 +3311,9 @@ class ndarray(_ArrayOrScalarCommon, Generic[_ShapeT_co, _DTypeT_co]):
     @overload
     def __ror__(self: NDArray[np.bool], other: _ArrayLikeBool_co, /) -> NDArray[np.bool]: ...  # type: ignore[misc]
     @overload
-    def __ror__(self: _ArrayUInt_co, other: _ArrayLikeUInt_co, /) -> NDArray[unsignedinteger[Any]]: ...  # type: ignore[misc]
+    def __ror__(self: _ArrayUInt_co, other: _ArrayLikeUInt_co, /) -> NDArray[unsignedinteger]: ...  # type: ignore[misc]
     @overload
-    def __ror__(self: _ArrayInt_co, other: _ArrayLikeInt_co, /) -> NDArray[signedinteger[Any]]: ...
+    def __ror__(self: _ArrayInt_co, other: _ArrayLikeInt_co, /) -> NDArray[signedinteger]: ...
     @overload
     def __ror__(self: NDArray[object_], other: Any, /) -> Any: ...
     @overload
@@ -3331,20 +3331,20 @@ class ndarray(_ArrayOrScalarCommon, Generic[_ShapeT_co, _DTypeT_co]):
     def __iadd__(self: NDArray[np.bool], other: _ArrayLikeBool_co, /) -> ndarray[_ShapeT_co, _DTypeT_co]: ...
     @overload
     def __iadd__(
-        self: NDArray[unsignedinteger[Any]],
+        self: NDArray[unsignedinteger],
         other: _ArrayLikeUInt_co | _IntLike_co,
         /,
     ) -> ndarray[_ShapeT_co, _DTypeT_co]: ...
     @overload
-    def __iadd__(self: NDArray[signedinteger[Any]], other: _ArrayLikeInt_co, /) -> ndarray[_ShapeT_co, _DTypeT_co]: ...
+    def __iadd__(self: NDArray[signedinteger], other: _ArrayLikeInt_co, /) -> ndarray[_ShapeT_co, _DTypeT_co]: ...
     @overload
     def __iadd__(self: NDArray[float64], other: _ArrayLikeFloat_co, /) -> ndarray[_ShapeT_co, _DTypeT_co]: ...
     @overload
-    def __iadd__(self: NDArray[floating[Any]], other: _ArrayLikeFloat_co, /) -> ndarray[_ShapeT_co, _DTypeT_co]: ...
+    def __iadd__(self: NDArray[floating], other: _ArrayLikeFloat_co, /) -> ndarray[_ShapeT_co, _DTypeT_co]: ...
     @overload
     def __iadd__(self: NDArray[complex128], other: _ArrayLikeComplex_co, /) -> ndarray[_ShapeT_co, _DTypeT_co]: ...
     @overload
-    def __iadd__(self: NDArray[complexfloating[Any]], other: _ArrayLikeComplex_co, /) -> ndarray[_ShapeT_co, _DTypeT_co]: ...
+    def __iadd__(self: NDArray[complexfloating], other: _ArrayLikeComplex_co, /) -> ndarray[_ShapeT_co, _DTypeT_co]: ...
     @overload
     def __iadd__(self: NDArray[timedelta64], other: _ArrayLikeTD64_co, /) -> ndarray[_ShapeT_co, _DTypeT_co]: ...
     @overload
@@ -3354,20 +3354,20 @@ class ndarray(_ArrayOrScalarCommon, Generic[_ShapeT_co, _DTypeT_co]):
 
     @overload
     def __isub__(
-        self: NDArray[unsignedinteger[Any]],
+        self: NDArray[unsignedinteger],
         other: _ArrayLikeUInt_co | _IntLike_co,
         /,
     ) -> ndarray[_ShapeT_co, _DTypeT_co]: ...
     @overload
-    def __isub__(self: NDArray[signedinteger[Any]], other: _ArrayLikeInt_co, /) -> ndarray[_ShapeT_co, _DTypeT_co]: ...
+    def __isub__(self: NDArray[signedinteger], other: _ArrayLikeInt_co, /) -> ndarray[_ShapeT_co, _DTypeT_co]: ...
     @overload
     def __isub__(self: NDArray[float64], other: _ArrayLikeFloat_co, /) -> ndarray[_ShapeT_co, _DTypeT_co]: ...
     @overload
-    def __isub__(self: NDArray[floating[Any]], other: _ArrayLikeFloat_co, /) -> ndarray[_ShapeT_co, _DTypeT_co]: ...
+    def __isub__(self: NDArray[floating], other: _ArrayLikeFloat_co, /) -> ndarray[_ShapeT_co, _DTypeT_co]: ...
     @overload
     def __isub__(self: NDArray[complex128], other: _ArrayLikeComplex_co, /) -> ndarray[_ShapeT_co, _DTypeT_co]: ...
     @overload
-    def __isub__(self: NDArray[complexfloating[Any]], other: _ArrayLikeComplex_co, /) -> ndarray[_ShapeT_co, _DTypeT_co]: ...
+    def __isub__(self: NDArray[complexfloating], other: _ArrayLikeComplex_co, /) -> ndarray[_ShapeT_co, _DTypeT_co]: ...
     @overload
     def __isub__(self: NDArray[timedelta64], other: _ArrayLikeTD64_co, /) -> ndarray[_ShapeT_co, _DTypeT_co]: ...
     @overload
@@ -3379,20 +3379,20 @@ class ndarray(_ArrayOrScalarCommon, Generic[_ShapeT_co, _DTypeT_co]):
     def __imul__(self: NDArray[np.bool], other: _ArrayLikeBool_co, /) -> ndarray[_ShapeT_co, _DTypeT_co]: ...
     @overload
     def __imul__(
-        self: NDArray[unsignedinteger[Any]],
+        self: NDArray[unsignedinteger],
         other: _ArrayLikeUInt_co | _IntLike_co,
         /,
     ) -> ndarray[_ShapeT_co, _DTypeT_co]: ...
     @overload
-    def __imul__(self: NDArray[signedinteger[Any]], other: _ArrayLikeInt_co, /) -> ndarray[_ShapeT_co, _DTypeT_co]: ...
+    def __imul__(self: NDArray[signedinteger], other: _ArrayLikeInt_co, /) -> ndarray[_ShapeT_co, _DTypeT_co]: ...
     @overload
     def __imul__(self: NDArray[float64], other: _ArrayLikeFloat_co, /) -> ndarray[_ShapeT_co, _DTypeT_co]: ...
     @overload
-    def __imul__(self: NDArray[floating[Any]], other: _ArrayLikeFloat_co, /) -> ndarray[_ShapeT_co, _DTypeT_co]: ...
+    def __imul__(self: NDArray[floating], other: _ArrayLikeFloat_co, /) -> ndarray[_ShapeT_co, _DTypeT_co]: ...
     @overload
     def __imul__(self: NDArray[complex128], other: _ArrayLikeComplex_co, /) -> ndarray[_ShapeT_co, _DTypeT_co]: ...
     @overload
-    def __imul__(self: NDArray[complexfloating[Any]], other: _ArrayLikeComplex_co, /) -> ndarray[_ShapeT_co, _DTypeT_co]: ...
+    def __imul__(self: NDArray[complexfloating], other: _ArrayLikeComplex_co, /) -> ndarray[_ShapeT_co, _DTypeT_co]: ...
     @overload
     def __imul__(self: NDArray[timedelta64], other: _ArrayLikeFloat_co, /) -> ndarray[_ShapeT_co, _DTypeT_co]: ...
     @overload
@@ -3401,12 +3401,12 @@ class ndarray(_ArrayOrScalarCommon, Generic[_ShapeT_co, _DTypeT_co]):
     @overload
     def __itruediv__(self: NDArray[float64], other: _ArrayLikeFloat_co, /) -> ndarray[_ShapeT_co, _DTypeT_co]: ...
     @overload
-    def __itruediv__(self: NDArray[floating[Any]], other: _ArrayLikeFloat_co, /) -> ndarray[_ShapeT_co, _DTypeT_co]: ...
+    def __itruediv__(self: NDArray[floating], other: _ArrayLikeFloat_co, /) -> ndarray[_ShapeT_co, _DTypeT_co]: ...
     @overload
     def __itruediv__(self: NDArray[complex128], other: _ArrayLikeComplex_co, /) -> ndarray[_ShapeT_co, _DTypeT_co]: ...
     @overload
     def __itruediv__(
-        self: NDArray[complexfloating[Any]],
+        self: NDArray[complexfloating],
         other: _ArrayLikeComplex_co,
         /,
     ) -> ndarray[_ShapeT_co, _DTypeT_co]: ...
@@ -3417,21 +3417,21 @@ class ndarray(_ArrayOrScalarCommon, Generic[_ShapeT_co, _DTypeT_co]):
 
     @overload
     def __ifloordiv__(
-        self: NDArray[unsignedinteger[Any]],
+        self: NDArray[unsignedinteger],
         other: _ArrayLikeUInt_co | _IntLike_co,
         /,
     ) -> ndarray[_ShapeT_co, _DTypeT_co]: ...
     @overload
-    def __ifloordiv__(self: NDArray[signedinteger[Any]], other: _ArrayLikeInt_co, /) -> ndarray[_ShapeT_co, _DTypeT_co]: ...
+    def __ifloordiv__(self: NDArray[signedinteger], other: _ArrayLikeInt_co, /) -> ndarray[_ShapeT_co, _DTypeT_co]: ...
     @overload
     def __ifloordiv__(self: NDArray[float64], other: _ArrayLikeFloat_co, /) -> ndarray[_ShapeT_co, _DTypeT_co]: ...
     @overload
-    def __ifloordiv__(self: NDArray[floating[Any]], other: _ArrayLikeFloat_co, /) -> ndarray[_ShapeT_co, _DTypeT_co]: ...
+    def __ifloordiv__(self: NDArray[floating], other: _ArrayLikeFloat_co, /) -> ndarray[_ShapeT_co, _DTypeT_co]: ...
     @overload
     def __ifloordiv__(self: NDArray[complex128], other: _ArrayLikeComplex_co, /) -> ndarray[_ShapeT_co, _DTypeT_co]: ...
     @overload
     def __ifloordiv__(
-        self: NDArray[complexfloating[Any]],
+        self: NDArray[complexfloating],
         other: _ArrayLikeComplex_co,
         /,
     ) -> ndarray[_ShapeT_co, _DTypeT_co]: ...
@@ -3442,35 +3442,35 @@ class ndarray(_ArrayOrScalarCommon, Generic[_ShapeT_co, _DTypeT_co]):
 
     @overload
     def __ipow__(
-        self: NDArray[unsignedinteger[Any]],
+        self: NDArray[unsignedinteger],
         other: _ArrayLikeUInt_co | _IntLike_co,
         /,
     ) -> ndarray[_ShapeT_co, _DTypeT_co]: ...
     @overload
-    def __ipow__(self: NDArray[signedinteger[Any]], other: _ArrayLikeInt_co, /) -> ndarray[_ShapeT_co, _DTypeT_co]: ...
+    def __ipow__(self: NDArray[signedinteger], other: _ArrayLikeInt_co, /) -> ndarray[_ShapeT_co, _DTypeT_co]: ...
     @overload
     def __ipow__(self: NDArray[float64], other: _ArrayLikeFloat_co, /) -> ndarray[_ShapeT_co, _DTypeT_co]: ...
     @overload
-    def __ipow__(self: NDArray[floating[Any]], other: _ArrayLikeFloat_co, /) -> ndarray[_ShapeT_co, _DTypeT_co]: ...
+    def __ipow__(self: NDArray[floating], other: _ArrayLikeFloat_co, /) -> ndarray[_ShapeT_co, _DTypeT_co]: ...
     @overload
     def __ipow__(self: NDArray[complex128], other: _ArrayLikeComplex_co, /) -> ndarray[_ShapeT_co, _DTypeT_co]: ...
     @overload
-    def __ipow__(self: NDArray[complexfloating[Any]], other: _ArrayLikeComplex_co, /) -> ndarray[_ShapeT_co, _DTypeT_co]: ...
+    def __ipow__(self: NDArray[complexfloating], other: _ArrayLikeComplex_co, /) -> ndarray[_ShapeT_co, _DTypeT_co]: ...
     @overload
     def __ipow__(self: NDArray[object_], other: Any, /) -> ndarray[_ShapeT_co, _DTypeT_co]: ...
 
     @overload
     def __imod__(
-        self: NDArray[unsignedinteger[Any]],
+        self: NDArray[unsignedinteger],
         other: _ArrayLikeUInt_co | _IntLike_co,
         /,
     ) -> ndarray[_ShapeT_co, _DTypeT_co]: ...
     @overload
-    def __imod__(self: NDArray[signedinteger[Any]], other: _ArrayLikeInt_co, /) -> ndarray[_ShapeT_co, _DTypeT_co]: ...
+    def __imod__(self: NDArray[signedinteger], other: _ArrayLikeInt_co, /) -> ndarray[_ShapeT_co, _DTypeT_co]: ...
     @overload
     def __imod__(self: NDArray[float64], other: _ArrayLikeFloat_co, /) -> ndarray[_ShapeT_co, _DTypeT_co]: ...
     @overload
-    def __imod__(self: NDArray[floating[Any]], other: _ArrayLikeFloat_co, /) -> ndarray[_ShapeT_co, _DTypeT_co]: ...
+    def __imod__(self: NDArray[floating], other: _ArrayLikeFloat_co, /) -> ndarray[_ShapeT_co, _DTypeT_co]: ...
     @overload
     def __imod__(
         self: NDArray[timedelta64],
@@ -3482,23 +3482,23 @@ class ndarray(_ArrayOrScalarCommon, Generic[_ShapeT_co, _DTypeT_co]):
 
     @overload
     def __ilshift__(
-        self: NDArray[unsignedinteger[Any]],
+        self: NDArray[unsignedinteger],
         other: _ArrayLikeUInt_co | _IntLike_co,
         /,
     ) -> ndarray[_ShapeT_co, _DTypeT_co]: ...
     @overload
-    def __ilshift__(self: NDArray[signedinteger[Any]], other: _ArrayLikeInt_co, /) -> ndarray[_ShapeT_co, _DTypeT_co]: ...
+    def __ilshift__(self: NDArray[signedinteger], other: _ArrayLikeInt_co, /) -> ndarray[_ShapeT_co, _DTypeT_co]: ...
     @overload
     def __ilshift__(self: NDArray[object_], other: Any, /) -> ndarray[_ShapeT_co, _DTypeT_co]: ...
 
     @overload
     def __irshift__(
-        self: NDArray[unsignedinteger[Any]],
+        self: NDArray[unsignedinteger],
         other: _ArrayLikeUInt_co | _IntLike_co,
         /,
     ) -> ndarray[_ShapeT_co, _DTypeT_co]: ...
     @overload
-    def __irshift__(self: NDArray[signedinteger[Any]], other: _ArrayLikeInt_co, /) -> ndarray[_ShapeT_co, _DTypeT_co]: ...
+    def __irshift__(self: NDArray[signedinteger], other: _ArrayLikeInt_co, /) -> ndarray[_ShapeT_co, _DTypeT_co]: ...
     @overload
     def __irshift__(self: NDArray[object_], other: Any, /) -> ndarray[_ShapeT_co, _DTypeT_co]: ...
 
@@ -3506,12 +3506,12 @@ class ndarray(_ArrayOrScalarCommon, Generic[_ShapeT_co, _DTypeT_co]):
     def __iand__(self: NDArray[np.bool], other: _ArrayLikeBool_co, /) -> ndarray[_ShapeT_co, _DTypeT_co]: ...
     @overload
     def __iand__(
-        self: NDArray[unsignedinteger[Any]],
+        self: NDArray[unsignedinteger],
         other: _ArrayLikeUInt_co | _IntLike_co,
         /,
     ) -> ndarray[_ShapeT_co, _DTypeT_co]: ...
     @overload
-    def __iand__(self: NDArray[signedinteger[Any]], other: _ArrayLikeInt_co, /) -> ndarray[_ShapeT_co, _DTypeT_co]: ...
+    def __iand__(self: NDArray[signedinteger], other: _ArrayLikeInt_co, /) -> ndarray[_ShapeT_co, _DTypeT_co]: ...
     @overload
     def __iand__(self: NDArray[object_], other: Any, /) -> ndarray[_ShapeT_co, _DTypeT_co]: ...
 
@@ -3519,12 +3519,12 @@ class ndarray(_ArrayOrScalarCommon, Generic[_ShapeT_co, _DTypeT_co]):
     def __ixor__(self: NDArray[np.bool], other: _ArrayLikeBool_co, /) -> ndarray[_ShapeT_co, _DTypeT_co]: ...
     @overload
     def __ixor__(
-        self: NDArray[unsignedinteger[Any]],
+        self: NDArray[unsignedinteger],
         other: _ArrayLikeUInt_co | _IntLike_co,
         /,
     ) -> ndarray[_ShapeT_co, _DTypeT_co]: ...
     @overload
-    def __ixor__(self: NDArray[signedinteger[Any]], other: _ArrayLikeInt_co, /) -> ndarray[_ShapeT_co, _DTypeT_co]: ...
+    def __ixor__(self: NDArray[signedinteger], other: _ArrayLikeInt_co, /) -> ndarray[_ShapeT_co, _DTypeT_co]: ...
     @overload
     def __ixor__(self: NDArray[object_], other: Any, /) -> ndarray[_ShapeT_co, _DTypeT_co]: ...
 
@@ -3532,34 +3532,34 @@ class ndarray(_ArrayOrScalarCommon, Generic[_ShapeT_co, _DTypeT_co]):
     def __ior__(self: NDArray[np.bool], other: _ArrayLikeBool_co, /) -> ndarray[_ShapeT_co, _DTypeT_co]: ...
     @overload
     def __ior__(
-        self: NDArray[unsignedinteger[Any]],
+        self: NDArray[unsignedinteger],
         other: _ArrayLikeUInt_co | _IntLike_co,
         /,
     ) -> ndarray[_ShapeT_co, _DTypeT_co]: ...
     @overload
-    def __ior__(self: NDArray[signedinteger[Any]], other: _ArrayLikeInt_co, /) -> ndarray[_ShapeT_co, _DTypeT_co]: ...
+    def __ior__(self: NDArray[signedinteger], other: _ArrayLikeInt_co, /) -> ndarray[_ShapeT_co, _DTypeT_co]: ...
     @overload
     def __ior__(self: NDArray[object_], other: Any, /) -> ndarray[_ShapeT_co, _DTypeT_co]: ...
 
     @overload
     def __imatmul__(self: NDArray[np.bool], other: _ArrayLikeBool_co, /) -> ndarray[_ShapeT_co, _DTypeT_co]: ...
     @overload
-    def __imatmul__(self: NDArray[unsignedinteger[Any]], other: _ArrayLikeUInt_co, /) -> ndarray[_ShapeT_co, _DTypeT_co]: ...
+    def __imatmul__(self: NDArray[unsignedinteger], other: _ArrayLikeUInt_co, /) -> ndarray[_ShapeT_co, _DTypeT_co]: ...
     @overload
-    def __imatmul__(self: NDArray[signedinteger[Any]], other: _ArrayLikeInt_co, /) -> ndarray[_ShapeT_co, _DTypeT_co]: ...
+    def __imatmul__(self: NDArray[signedinteger], other: _ArrayLikeInt_co, /) -> ndarray[_ShapeT_co, _DTypeT_co]: ...
     @overload
     def __imatmul__(self: NDArray[float64], other: _ArrayLikeFloat_co, /) -> ndarray[_ShapeT_co, _DTypeT_co]: ...
     @overload
-    def __imatmul__(self: NDArray[floating[Any]], other: _ArrayLikeFloat_co, /) -> ndarray[_ShapeT_co, _DTypeT_co]: ...
+    def __imatmul__(self: NDArray[floating], other: _ArrayLikeFloat_co, /) -> ndarray[_ShapeT_co, _DTypeT_co]: ...
     @overload
     def __imatmul__(self: NDArray[complex128], other: _ArrayLikeComplex_co, /) -> ndarray[_ShapeT_co, _DTypeT_co]: ...
     @overload
-    def __imatmul__(self: NDArray[complexfloating[Any]], other: _ArrayLikeComplex_co, /) -> ndarray[_ShapeT_co, _DTypeT_co]: ...
+    def __imatmul__(self: NDArray[complexfloating], other: _ArrayLikeComplex_co, /) -> ndarray[_ShapeT_co, _DTypeT_co]: ...
     @overload
     def __imatmul__(self: NDArray[object_], other: Any, /) -> ndarray[_ShapeT_co, _DTypeT_co]: ...
 
     def __dlpack__(
-        self: NDArray[number[Any]],
+        self: NDArray[number],
         /,
         *,
         stream: int | Any | None = None,
@@ -3981,7 +3981,7 @@ bool_ = bool
 # NOTE: Because mypy has some long-standing bugs related to `__new__`, `object_` can't
 # be made generic.
 @final
-class object_(_RealMixin, generic[Any]):
+class object_(_RealMixin, generic):
     @overload
     def __new__(cls, nothing_to_see_here: None = None, /) -> None: ...  # type: ignore[misc]
     @overload
@@ -4013,19 +4013,19 @@ class integer(_IntegralMixin, _RoundMixin, number[_NBit, int]):
 
     __truediv__: _IntTrueDiv[_NBit]
     __rtruediv__: _IntTrueDiv[_NBit]
-    def __mod__(self, value: _IntLike_co, /) -> integer[Any]: ...
-    def __rmod__(self, value: _IntLike_co, /) -> integer[Any]: ...
+    def __mod__(self, value: _IntLike_co, /) -> integer: ...
+    def __rmod__(self, value: _IntLike_co, /) -> integer: ...
     # Ensure that objects annotated as `integer` support bit-wise operations
-    def __lshift__(self, other: _IntLike_co, /) -> integer[Any]: ...
-    def __rlshift__(self, other: _IntLike_co, /) -> integer[Any]: ...
-    def __rshift__(self, other: _IntLike_co, /) -> integer[Any]: ...
-    def __rrshift__(self, other: _IntLike_co, /) -> integer[Any]: ...
-    def __and__(self, other: _IntLike_co, /) -> integer[Any]: ...
-    def __rand__(self, other: _IntLike_co, /) -> integer[Any]: ...
-    def __or__(self, other: _IntLike_co, /) -> integer[Any]: ...
-    def __ror__(self, other: _IntLike_co, /) -> integer[Any]: ...
-    def __xor__(self, other: _IntLike_co, /) -> integer[Any]: ...
-    def __rxor__(self, other: _IntLike_co, /) -> integer[Any]: ...
+    def __lshift__(self, other: _IntLike_co, /) -> integer: ...
+    def __rlshift__(self, other: _IntLike_co, /) -> integer: ...
+    def __rshift__(self, other: _IntLike_co, /) -> integer: ...
+    def __rrshift__(self, other: _IntLike_co, /) -> integer: ...
+    def __and__(self, other: _IntLike_co, /) -> integer: ...
+    def __rand__(self, other: _IntLike_co, /) -> integer: ...
+    def __or__(self, other: _IntLike_co, /) -> integer: ...
+    def __ror__(self, other: _IntLike_co, /) -> integer: ...
+    def __xor__(self, other: _IntLike_co, /) -> integer: ...
+    def __rxor__(self, other: _IntLike_co, /) -> integer: ...
 
 class signedinteger(integer[_NBit1]):
     def __init__(self, value: _ConvertibleToInt = ..., /) -> None: ...
@@ -4481,11 +4481,11 @@ class timedelta64(_IntegralMixin, generic[_TD64ItemT_co], Generic[_TD64ItemT_co]
     __radd__ = __add__
 
     @overload
-    def __mul__(self: timedelta64[_AnyTD64Item], x: int | np.integer[Any] | np.bool, /) -> timedelta64[_AnyTD64Item]: ...
+    def __mul__(self: timedelta64[_AnyTD64Item], x: int | np.integer | np.bool, /) -> timedelta64[_AnyTD64Item]: ...
     @overload
-    def __mul__(self: timedelta64[_AnyTD64Item], x: float | np.floating[Any], /) -> timedelta64[_AnyTD64Item | None]: ...
+    def __mul__(self: timedelta64[_AnyTD64Item], x: float | np.floating, /) -> timedelta64[_AnyTD64Item | None]: ...
     @overload
-    def __mul__(self, x: float | np.floating[Any] | np.integer[Any] | np.bool, /) -> timedelta64: ...
+    def __mul__(self, x: float | np.floating | np.integer | np.bool, /) -> timedelta64: ...
     __rmul__ = __mul__
 
     @overload
@@ -4638,7 +4638,7 @@ class datetime64(_RealMixin, generic[_DT64ItemT_co], Generic[_DT64ItemT_co]):
     def __init__(self, value: bytes | str | dt.date | None, format: _TimeUnitSpec = ..., /) -> None: ...
 
     @overload
-    def __add__(self: datetime64[_AnyDT64Item], x: int | integer[Any] | np.bool, /) -> datetime64[_AnyDT64Item]: ...
+    def __add__(self: datetime64[_AnyDT64Item], x: int | integer | np.bool, /) -> datetime64[_AnyDT64Item]: ...
     @overload
     def __add__(self: datetime64[None], x: _TD64Like_co, /) -> datetime64[None]: ...
     @overload
@@ -4656,7 +4656,7 @@ class datetime64(_RealMixin, generic[_DT64ItemT_co], Generic[_DT64ItemT_co]):
     __radd__ = __add__
 
     @overload
-    def __sub__(self: datetime64[_AnyDT64Item], x: int | integer[Any] | np.bool, /) -> datetime64[_AnyDT64Item]: ...
+    def __sub__(self: datetime64[_AnyDT64Item], x: int | integer | np.bool, /) -> datetime64[_AnyDT64Item]: ...
     @overload
     def __sub__(self: datetime64[_AnyDate], x: _AnyDate, /) -> dt.timedelta: ...
     @overload
@@ -4689,7 +4689,7 @@ class datetime64(_RealMixin, generic[_DT64ItemT_co], Generic[_DT64ItemT_co]):
     def __sub__(self, x: datetime64, /) -> timedelta64: ...
 
     @overload
-    def __rsub__(self: datetime64[_AnyDT64Item], x: int | integer[Any] | np.bool, /) -> datetime64[_AnyDT64Item]: ...
+    def __rsub__(self: datetime64[_AnyDT64Item], x: int | integer | np.bool, /) -> datetime64[_AnyDT64Item]: ...
     @overload
     def __rsub__(self: datetime64[_AnyDate], x: _AnyDate, /) -> dt.timedelta: ...
     @overload
@@ -5008,17 +5008,11 @@ class finfo(Generic[_FloatingT_co]):
     @property
     def tiny(self) -> _FloatingT_co: ...
     @overload
-    def __new__(
-        cls, dtype: inexact[_NBit1] | _DTypeLike[inexact[_NBit1]]
-    ) -> finfo[floating[_NBit1]]: ...
+    def __new__(cls, dtype: inexact[_NBit1] | _DTypeLike[inexact[_NBit1]]) -> finfo[floating[_NBit1]]: ...
     @overload
-    def __new__(
-        cls, dtype: complex | float | type[complex] | type[float]
-    ) -> finfo[float64]: ...
+    def __new__(cls, dtype: complex | type[complex]) -> finfo[float64]: ...
     @overload
-    def __new__(
-        cls, dtype: str
-    ) -> finfo[floating[Any]]: ...
+    def __new__(cls, dtype: str) -> finfo[floating]: ...
 
 class iinfo(Generic[_IntegerT_co]):
     dtype: Final[dtype[_IntegerT_co]]
@@ -5400,4 +5394,4 @@ def from_dlpack(
     *,
     device: L["cpu"] | None = None,
     copy: builtins.bool | None = None,
-) -> NDArray[number[Any] | np.bool]: ...
+) -> NDArray[number | np.bool]: ...
diff --git a/numpy/_core/_type_aliases.pyi b/numpy/_core/_type_aliases.pyi
index f92958a67d55..683cc0ab273a 100644
--- a/numpy/_core/_type_aliases.pyi
+++ b/numpy/_core/_type_aliases.pyi
@@ -87,10 +87,10 @@ _extra_aliases: Final[_ExtraAliasesType]
 
 @type_check_only
 class _SCTypes(TypedDict):
-    int: Collection[type[np.signedinteger[Any]]]
-    uint: Collection[type[np.unsignedinteger[Any]]]
-    float: Collection[type[np.floating[Any]]]
-    complex: Collection[type[np.complexfloating[Any, Any]]]
+    int: Collection[type[np.signedinteger]]
+    uint: Collection[type[np.unsignedinteger]]
+    float: Collection[type[np.floating]]
+    complex: Collection[type[np.complexfloating]]
     others: Collection[type[np.flexible | np.bool | np.object_]]
 
 sctypes: Final[_SCTypes]
diff --git a/numpy/_core/einsumfunc.pyi b/numpy/_core/einsumfunc.pyi
index e45c865da3f1..a9c11b0b21a9 100644
--- a/numpy/_core/einsumfunc.pyi
+++ b/numpy/_core/einsumfunc.pyi
@@ -24,7 +24,7 @@ __all__ = ["einsum", "einsum_path"]
 
 _ArrayT = TypeVar(
     "_ArrayT",
-    bound=NDArray[np.bool | number[Any]],
+    bound=NDArray[np.bool | number],
 )
 
 _OptimizeKind: TypeAlias = bool | Literal["greedy", "optimal"] | Sequence[Any] | None
diff --git a/numpy/_core/fromnumeric.pyi b/numpy/_core/fromnumeric.pyi
index 13fb027759b3..b6b8499096f0 100644
--- a/numpy/_core/fromnumeric.pyi
+++ b/numpy/_core/fromnumeric.pyi
@@ -107,7 +107,7 @@ __all__ = [
 ]
 
 _ScalarT = TypeVar("_ScalarT", bound=generic)
-_NumberOrObjectT = TypeVar("_NumberOrObjectT", bound=np.number[Any] | np.object_)
+_NumberOrObjectT = TypeVar("_NumberOrObjectT", bound=np.number | np.object_)
 _ArrayT = TypeVar("_ArrayT", bound=np.ndarray[Any, Any])
 _ShapeT = TypeVar("_ShapeT", bound=tuple[int, ...])
 _ShapeT_co = TypeVar("_ShapeT_co", bound=tuple[int, ...], covariant=True)
@@ -1134,7 +1134,7 @@ def prod(
     keepdims: Literal[False] = ...,
     initial: _NumberLike_co = ...,
     where: _ArrayLikeBool_co = ...,
-) -> floating[Any]: ...
+) -> floating: ...
 @overload
 def prod(
     a: _ArrayLikeComplex_co,
@@ -1144,7 +1144,7 @@ def prod(
     keepdims: Literal[False] = ...,
     initial: _NumberLike_co = ...,
     where: _ArrayLikeBool_co = ...,
-) -> complexfloating[Any, Any]: ...
+) -> complexfloating: ...
 @overload
 def prod(
     a: _ArrayLikeComplex_co | _ArrayLikeObject_co,
@@ -1235,14 +1235,14 @@ def cumprod(
     axis: SupportsIndex | None = ...,
     dtype: None = ...,
     out: None = ...,
-) -> NDArray[floating[Any]]: ...
+) -> NDArray[floating]: ...
 @overload
 def cumprod(
     a: _ArrayLikeComplex_co,
     axis: SupportsIndex | None = ...,
     dtype: None = ...,
     out: None = ...,
-) -> NDArray[complexfloating[Any, Any]]: ...
+) -> NDArray[complexfloating]: ...
 @overload
 def cumprod(
     a: _ArrayLikeObject_co,
@@ -1327,7 +1327,7 @@ def cumulative_prod(
     dtype: None = ...,
     out: None = ...,
     include_initial: bool = ...,
-) -> NDArray[floating[Any]]: ...
+) -> NDArray[floating]: ...
 @overload
 def cumulative_prod(
     x: _ArrayLikeComplex_co,
@@ -1337,7 +1337,7 @@ def cumulative_prod(
     dtype: None = ...,
     out: None = ...,
     include_initial: bool = ...,
-) -> NDArray[complexfloating[Any, Any]]: ...
+) -> NDArray[complexfloating]: ...
 @overload
 def cumulative_prod(
     x: _ArrayLikeObject_co,
@@ -1442,7 +1442,7 @@ def mean(
     keepdims: Literal[False] | _NoValueType = ...,
     *,
     where: _ArrayLikeBool_co | _NoValueType = ...,
-) -> floating[Any]: ...
+) -> floating: ...
 @overload
 def mean(
     a: _ArrayLikeComplex_co,
@@ -1452,7 +1452,7 @@ def mean(
     keepdims: Literal[False] | _NoValueType = ...,
     *,
     where: _ArrayLikeBool_co | _NoValueType = ...,
-) -> complexfloating[Any]: ...
+) -> complexfloating: ...
 @overload
 def mean(
     a: _ArrayLike[np.timedelta64],
@@ -1556,7 +1556,7 @@ def std(
     where: _ArrayLikeBool_co | _NoValueType = ...,
     mean: _ArrayLikeComplex_co | _NoValueType = ...,
     correction: float | _NoValueType = ...,
-) -> floating[Any]: ...
+) -> floating: ...
 @overload
 def std(
     a: _ArrayLikeComplex_co | _ArrayLikeObject_co,
@@ -1648,7 +1648,7 @@ def var(
     where: _ArrayLikeBool_co | _NoValueType = ...,
     mean: _ArrayLikeComplex_co | _NoValueType = ...,
     correction: float | _NoValueType = ...,
-) -> floating[Any]: ...
+) -> floating: ...
 @overload
 def var(
     a: _ArrayLikeComplex_co | _ArrayLikeObject_co,
diff --git a/numpy/_core/multiarray.pyi b/numpy/_core/multiarray.pyi
index 7ca9b4ba783e..be918f2214d8 100644
--- a/numpy/_core/multiarray.pyi
+++ b/numpy/_core/multiarray.pyi
@@ -610,13 +610,13 @@ def dot(a: ArrayLike, b: ArrayLike, out: _ArrayT) -> _ArrayT: ...
 @overload
 def vdot(a: _ArrayLikeBool_co, b: _ArrayLikeBool_co, /) -> np.bool: ...  # type: ignore[misc]
 @overload
-def vdot(a: _ArrayLikeUInt_co, b: _ArrayLikeUInt_co, /) -> unsignedinteger[Any]: ...  # type: ignore[misc]
+def vdot(a: _ArrayLikeUInt_co, b: _ArrayLikeUInt_co, /) -> unsignedinteger: ...  # type: ignore[misc]
 @overload
-def vdot(a: _ArrayLikeInt_co, b: _ArrayLikeInt_co, /) -> signedinteger[Any]: ...  # type: ignore[misc]
+def vdot(a: _ArrayLikeInt_co, b: _ArrayLikeInt_co, /) -> signedinteger: ...  # type: ignore[misc]
 @overload
-def vdot(a: _ArrayLikeFloat_co, b: _ArrayLikeFloat_co, /) -> floating[Any]: ...  # type: ignore[misc]
+def vdot(a: _ArrayLikeFloat_co, b: _ArrayLikeFloat_co, /) -> floating: ...  # type: ignore[misc]
 @overload
-def vdot(a: _ArrayLikeComplex_co, b: _ArrayLikeComplex_co, /) -> complexfloating[Any, Any]: ...  # type: ignore[misc]
+def vdot(a: _ArrayLikeComplex_co, b: _ArrayLikeComplex_co, /) -> complexfloating: ...  # type: ignore[misc]
 @overload
 def vdot(a: _ArrayLikeTD64_co, b: _ArrayLikeTD64_co, /) -> timedelta64: ...
 @overload
diff --git a/numpy/_core/numeric.pyi b/numpy/_core/numeric.pyi
index 251f1bdb3601..6636801128bb 100644
--- a/numpy/_core/numeric.pyi
+++ b/numpy/_core/numeric.pyi
@@ -450,25 +450,25 @@ def correlate(
     a: _ArrayLikeUInt_co,
     v: _ArrayLikeUInt_co,
     mode: _CorrelateMode = ...,
-) -> NDArray[unsignedinteger[Any]]: ...
+) -> NDArray[unsignedinteger]: ...
 @overload
 def correlate(
     a: _ArrayLikeInt_co,
     v: _ArrayLikeInt_co,
     mode: _CorrelateMode = ...,
-) -> NDArray[signedinteger[Any]]: ...
+) -> NDArray[signedinteger]: ...
 @overload
 def correlate(
     a: _ArrayLikeFloat_co,
     v: _ArrayLikeFloat_co,
     mode: _CorrelateMode = ...,
-) -> NDArray[floating[Any]]: ...
+) -> NDArray[floating]: ...
 @overload
 def correlate(
     a: _ArrayLikeComplex_co,
     v: _ArrayLikeComplex_co,
     mode: _CorrelateMode = ...,
-) -> NDArray[complexfloating[Any, Any]]: ...
+) -> NDArray[complexfloating]: ...
 @overload
 def correlate(
     a: _ArrayLikeTD64_co,
@@ -499,25 +499,25 @@ def convolve(
     a: _ArrayLikeUInt_co,
     v: _ArrayLikeUInt_co,
     mode: _CorrelateMode = ...,
-) -> NDArray[unsignedinteger[Any]]: ...
+) -> NDArray[unsignedinteger]: ...
 @overload
 def convolve(
     a: _ArrayLikeInt_co,
     v: _ArrayLikeInt_co,
     mode: _CorrelateMode = ...,
-) -> NDArray[signedinteger[Any]]: ...
+) -> NDArray[signedinteger]: ...
 @overload
 def convolve(
     a: _ArrayLikeFloat_co,
     v: _ArrayLikeFloat_co,
     mode: _CorrelateMode = ...,
-) -> NDArray[floating[Any]]: ...
+) -> NDArray[floating]: ...
 @overload
 def convolve(
     a: _ArrayLikeComplex_co,
     v: _ArrayLikeComplex_co,
     mode: _CorrelateMode = ...,
-) -> NDArray[complexfloating[Any, Any]]: ...
+) -> NDArray[complexfloating]: ...
 @overload
 def convolve(
     a: _ArrayLikeTD64_co,
@@ -548,25 +548,25 @@ def outer(
     a: _ArrayLikeUInt_co,
     b: _ArrayLikeUInt_co,
     out: None = ...,
-) -> NDArray[unsignedinteger[Any]]: ...
+) -> NDArray[unsignedinteger]: ...
 @overload
 def outer(
     a: _ArrayLikeInt_co,
     b: _ArrayLikeInt_co,
     out: None = ...,
-) -> NDArray[signedinteger[Any]]: ...
+) -> NDArray[signedinteger]: ...
 @overload
 def outer(
     a: _ArrayLikeFloat_co,
     b: _ArrayLikeFloat_co,
     out: None = ...,
-) -> NDArray[floating[Any]]: ...
+) -> NDArray[floating]: ...
 @overload
 def outer(
     a: _ArrayLikeComplex_co,
     b: _ArrayLikeComplex_co,
     out: None = ...,
-) -> NDArray[complexfloating[Any, Any]]: ...
+) -> NDArray[complexfloating]: ...
 @overload
 def outer(
     a: _ArrayLikeTD64_co,
@@ -603,25 +603,25 @@ def tensordot(
     a: _ArrayLikeUInt_co,
     b: _ArrayLikeUInt_co,
     axes: int | tuple[_ShapeLike, _ShapeLike] = ...,
-) -> NDArray[unsignedinteger[Any]]: ...
+) -> NDArray[unsignedinteger]: ...
 @overload
 def tensordot(
     a: _ArrayLikeInt_co,
     b: _ArrayLikeInt_co,
     axes: int | tuple[_ShapeLike, _ShapeLike] = ...,
-) -> NDArray[signedinteger[Any]]: ...
+) -> NDArray[signedinteger]: ...
 @overload
 def tensordot(
     a: _ArrayLikeFloat_co,
     b: _ArrayLikeFloat_co,
     axes: int | tuple[_ShapeLike, _ShapeLike] = ...,
-) -> NDArray[floating[Any]]: ...
+) -> NDArray[floating]: ...
 @overload
 def tensordot(
     a: _ArrayLikeComplex_co,
     b: _ArrayLikeComplex_co,
     axes: int | tuple[_ShapeLike, _ShapeLike] = ...,
-) -> NDArray[complexfloating[Any, Any]]: ...
+) -> NDArray[complexfloating]: ...
 @overload
 def tensordot(
     a: _ArrayLikeTD64_co,
@@ -686,7 +686,7 @@ def cross(
     axisb: int = ...,
     axisc: int = ...,
     axis: int | None = ...,
-) -> NDArray[unsignedinteger[Any]]: ...
+) -> NDArray[unsignedinteger]: ...
 @overload
 def cross(
     a: _ArrayLikeInt_co,
@@ -695,7 +695,7 @@ def cross(
     axisb: int = ...,
     axisc: int = ...,
     axis: int | None = ...,
-) -> NDArray[signedinteger[Any]]: ...
+) -> NDArray[signedinteger]: ...
 @overload
 def cross(
     a: _ArrayLikeFloat_co,
@@ -704,7 +704,7 @@ def cross(
     axisb: int = ...,
     axisc: int = ...,
     axis: int | None = ...,
-) -> NDArray[floating[Any]]: ...
+) -> NDArray[floating]: ...
 @overload
 def cross(
     a: _ArrayLikeComplex_co,
@@ -713,7 +713,7 @@ def cross(
     axisb: int = ...,
     axisc: int = ...,
     axis: int | None = ...,
-) -> NDArray[complexfloating[Any, Any]]: ...
+) -> NDArray[complexfloating]: ...
 @overload
 def cross(
     a: _ArrayLikeObject_co,
diff --git a/numpy/_typing/_callable.pyi b/numpy/_typing/_callable.pyi
index 75af1ae8efba..dd7ae6fb1131 100644
--- a/numpy/_typing/_callable.pyi
+++ b/numpy/_typing/_callable.pyi
@@ -53,10 +53,10 @@ _2Tuple: TypeAlias = tuple[_T1, _T1]
 _NBit1 = TypeVar("_NBit1", bound=NBitBase)
 _NBit2 = TypeVar("_NBit2", bound=NBitBase)
 
-_IntType = TypeVar("_IntType", bound=integer[Any])
-_FloatType = TypeVar("_FloatType", bound=floating[Any])
-_NumberType = TypeVar("_NumberType", bound=number[Any])
-_NumberType_co = TypeVar("_NumberType_co", covariant=True, bound=number[Any])
+_IntType = TypeVar("_IntType", bound=integer)
+_FloatType = TypeVar("_FloatType", bound=floating)
+_NumberType = TypeVar("_NumberType", bound=number)
+_NumberType_co = TypeVar("_NumberType_co", covariant=True, bound=number)
 _GenericType_co = TypeVar("_GenericType_co", covariant=True, bound=generic)
 
 @type_check_only
@@ -166,9 +166,9 @@ class _UnsignedIntBitOp(Protocol[_NBit1]):
     @overload
     def __call__(self, other: bool, /) -> unsignedinteger[_NBit1]: ...
     @overload
-    def __call__(self, other: int, /) -> signedinteger[Any]: ...
+    def __call__(self, other: int, /) -> signedinteger: ...
     @overload
-    def __call__(self, other: signedinteger[Any], /) -> signedinteger[Any]: ...
+    def __call__(self, other: signedinteger, /) -> signedinteger: ...
     @overload
     def __call__(
         self, other: unsignedinteger[_NBit2], /
@@ -179,7 +179,7 @@ class _UnsignedIntMod(Protocol[_NBit1]):
     @overload
     def __call__(self, other: bool, /) -> unsignedinteger[_NBit1]: ...
     @overload
-    def __call__(self, other: int | signedinteger[Any], /) -> Any: ...
+    def __call__(self, other: int | signedinteger, /) -> Any: ...
     @overload
     def __call__(self, other: float, /) -> floating[_NBit1] | float64: ...
     @overload
@@ -192,7 +192,7 @@ class _UnsignedIntDivMod(Protocol[_NBit1]):
     @overload
     def __call__(self, other: bool, /) -> _2Tuple[signedinteger[_NBit1]]: ...
     @overload
-    def __call__(self, other: int | signedinteger[Any], /) -> _2Tuple[Any]: ...
+    def __call__(self, other: int | signedinteger, /) -> _2Tuple[Any]: ...
     @overload
     def __call__(self, other: float, /) -> _2Tuple[floating[_NBit1]] | _2Tuple[float64]: ...
     @overload
diff --git a/numpy/lib/_function_base_impl.pyi b/numpy/lib/_function_base_impl.pyi
index 55010ad6e5fd..0f9ddd92b8fc 100644
--- a/numpy/lib/_function_base_impl.pyi
+++ b/numpy/lib/_function_base_impl.pyi
@@ -388,11 +388,11 @@ def interp(
 ) -> NDArray[complex128 | float64] | complex128 | float64: ...
 
 @overload
-def angle(z: _ComplexLike_co, deg: bool = ...) -> floating[Any]: ...
+def angle(z: _ComplexLike_co, deg: bool = ...) -> floating: ...
 @overload
 def angle(z: object_, deg: bool = ...) -> Any: ...
 @overload
-def angle(z: _ArrayLikeComplex_co, deg: bool = ...) -> NDArray[floating[Any]]: ...
+def angle(z: _ArrayLikeComplex_co, deg: bool = ...) -> NDArray[floating]: ...
 @overload
 def angle(z: _ArrayLikeObject_co, deg: bool = ...) -> NDArray[object_]: ...
 
@@ -403,7 +403,7 @@ def unwrap(
     axis: int = ...,
     *,
     period: float = ...,
-) -> NDArray[floating[Any]]: ...
+) -> NDArray[floating]: ...
 @overload
 def unwrap(
     p: _ArrayLikeObject_co,
@@ -413,7 +413,7 @@ def unwrap(
     period: float = ...,
 ) -> NDArray[object_]: ...
 
-def sort_complex(a: ArrayLike) -> NDArray[complexfloating[Any, Any]]: ...
+def sort_complex(a: ArrayLike) -> NDArray[complexfloating]: ...
 
 def trim_zeros(
     filt: _TrimZerosSequence[_T],
@@ -438,7 +438,7 @@ def cov(
     aweights: ArrayLike | None = ...,
     *,
     dtype: None = ...,
-) -> NDArray[floating[Any]]: ...
+) -> NDArray[floating]: ...
 @overload
 def cov(
     m: _ArrayLikeComplex_co,
@@ -450,7 +450,7 @@ def cov(
     aweights: ArrayLike | None = ...,
     *,
     dtype: None = ...,
-) -> NDArray[complexfloating[Any, Any]]: ...
+) -> NDArray[complexfloating]: ...
 @overload
 def cov(
     m: _ArrayLikeComplex_co,
@@ -518,29 +518,29 @@ def corrcoef(
     dtype: DTypeLike | None = None,
 ) -> NDArray[Any]: ...
 
-def blackman(M: _FloatLike_co) -> NDArray[floating[Any]]: ...
+def blackman(M: _FloatLike_co) -> NDArray[floating]: ...
 
-def bartlett(M: _FloatLike_co) -> NDArray[floating[Any]]: ...
+def bartlett(M: _FloatLike_co) -> NDArray[floating]: ...
 
-def hanning(M: _FloatLike_co) -> NDArray[floating[Any]]: ...
+def hanning(M: _FloatLike_co) -> NDArray[floating]: ...
 
-def hamming(M: _FloatLike_co) -> NDArray[floating[Any]]: ...
+def hamming(M: _FloatLike_co) -> NDArray[floating]: ...
 
-def i0(x: _ArrayLikeFloat_co) -> NDArray[floating[Any]]: ...
+def i0(x: _ArrayLikeFloat_co) -> NDArray[floating]: ...
 
 def kaiser(
     M: _FloatLike_co,
     beta: _FloatLike_co,
-) -> NDArray[floating[Any]]: ...
+) -> NDArray[floating]: ...
 
 @overload
-def sinc(x: _FloatLike_co) -> floating[Any]: ...
+def sinc(x: _FloatLike_co) -> floating: ...
 @overload
-def sinc(x: _ComplexLike_co) -> complexfloating[Any, Any]: ...
+def sinc(x: _ComplexLike_co) -> complexfloating: ...
 @overload
-def sinc(x: _ArrayLikeFloat_co) -> NDArray[floating[Any]]: ...
+def sinc(x: _ArrayLikeFloat_co) -> NDArray[floating]: ...
 @overload
-def sinc(x: _ArrayLikeComplex_co) -> NDArray[complexfloating[Any, Any]]: ...
+def sinc(x: _ArrayLikeComplex_co) -> NDArray[complexfloating]: ...
 
 @overload
 def median(
@@ -549,7 +549,7 @@ def median(
     out: None = ...,
     overwrite_input: bool = ...,
     keepdims: L[False] = ...,
-) -> floating[Any]: ...
+) -> floating: ...
 @overload
 def median(
     a: _ArrayLikeComplex_co,
@@ -557,7 +557,7 @@ def median(
     out: None = ...,
     overwrite_input: bool = ...,
     keepdims: L[False] = ...,
-) -> complexfloating[Any, Any]: ...
+) -> complexfloating: ...
 @overload
 def median(
     a: _ArrayLikeTD64_co,
@@ -627,7 +627,7 @@ def percentile(
     keepdims: L[False] = ...,
     *,
     weights: _ArrayLikeFloat_co | None = ...,
-) -> floating[Any]: ...
+) -> floating: ...
 @overload
 def percentile(
     a: _ArrayLikeComplex_co,
@@ -639,7 +639,7 @@ def percentile(
     keepdims: L[False] = ...,
     *,
     weights: _ArrayLikeFloat_co | None = ...,
-) -> complexfloating[Any, Any]: ...
+) -> complexfloating: ...
 @overload
 def percentile(
     a: _ArrayLikeTD64_co,
@@ -687,7 +687,7 @@ def percentile(
     keepdims: L[False] = ...,
     *,
     weights: _ArrayLikeFloat_co | None = ...,
-) -> NDArray[floating[Any]]: ...
+) -> NDArray[floating]: ...
 @overload
 def percentile(
     a: _ArrayLikeComplex_co,
@@ -699,7 +699,7 @@ def percentile(
     keepdims: L[False] = ...,
     *,
     weights: _ArrayLikeFloat_co | None = ...,
-) -> NDArray[complexfloating[Any, Any]]: ...
+) -> NDArray[complexfloating]: ...
 @overload
 def percentile(
     a: _ArrayLikeTD64_co,
@@ -779,7 +779,7 @@ quantile = percentile
 
 _ScalarT_fm = TypeVar(
     "_ScalarT_fm",
-    bound=floating[Any] | complexfloating[Any, Any] | timedelta64,
+    bound=floating | complexfloating | timedelta64,
 )
 
 class _SupportsRMulFloat(Protocol[_T_co]):
@@ -801,8 +801,8 @@ def trapezoid(
 ) -> complex128: ...
 @overload
 def trapezoid(
-    y: _ArrayLike[bool_ | integer[Any]],
-    x: _ArrayLike[bool_ | integer[Any]] | None = ...,
+    y: _ArrayLike[bool_ | integer],
+    x: _ArrayLike[bool_ | integer] | None = ...,
     dx: float = ...,
     axis: SupportsIndex = ...,
 ) -> float64 | NDArray[float64]: ...
@@ -834,8 +834,8 @@ def trapezoid(
     dx: float = ...,
     axis: SupportsIndex = ...,
 ) -> (
-    floating[Any] | complexfloating[Any, Any] | timedelta64
-    | NDArray[floating[Any] | complexfloating[Any, Any] | timedelta64 | object_]
+    floating | complexfloating | timedelta64
+    | NDArray[floating | complexfloating | timedelta64 | object_]
 ): ...
 
 @deprecated("Use 'trapezoid' instead")
diff --git a/numpy/lib/_polynomial_impl.pyi b/numpy/lib/_polynomial_impl.pyi
index b93d579a195f..b40f4b78ddf5 100644
--- a/numpy/lib/_polynomial_impl.pyi
+++ b/numpy/lib/_polynomial_impl.pyi
@@ -59,11 +59,11 @@ __all__ = [
     "polyfit",
 ]
 
-def poly(seq_of_zeros: ArrayLike) -> NDArray[floating[Any]]: ...
+def poly(seq_of_zeros: ArrayLike) -> NDArray[floating]: ...
 
 # Returns either a float or complex array depending on the input values.
 # See `np.linalg.eigvals`.
-def roots(p: ArrayLike) -> NDArray[complexfloating[Any, Any]] | NDArray[floating[Any]]: ...
+def roots(p: ArrayLike) -> NDArray[complexfloating] | NDArray[floating]: ...
 
 @overload
 def polyint(
@@ -76,13 +76,13 @@ def polyint(
     p: _ArrayLikeFloat_co,
     m: SupportsInt | SupportsIndex = ...,
     k: _ArrayLikeFloat_co | None = ...,
-) -> NDArray[floating[Any]]: ...
+) -> NDArray[floating]: ...
 @overload
 def polyint(
     p: _ArrayLikeComplex_co,
     m: SupportsInt | SupportsIndex = ...,
     k: _ArrayLikeComplex_co | None = ...,
-) -> NDArray[complexfloating[Any, Any]]: ...
+) -> NDArray[complexfloating]: ...
 @overload
 def polyint(
     p: _ArrayLikeObject_co,
@@ -99,12 +99,12 @@ def polyder(
 def polyder(
     p: _ArrayLikeFloat_co,
     m: SupportsInt | SupportsIndex = ...,
-) -> NDArray[floating[Any]]: ...
+) -> NDArray[floating]: ...
 @overload
 def polyder(
     p: _ArrayLikeComplex_co,
     m: SupportsInt | SupportsIndex = ...,
-) -> NDArray[complexfloating[Any, Any]]: ...
+) -> NDArray[complexfloating]: ...
 @overload
 def polyder(
     p: _ArrayLikeObject_co,
@@ -181,22 +181,22 @@ def polyval(
 def polyval(
     p: _ArrayLikeUInt_co,
     x: _ArrayLikeUInt_co,
-) -> NDArray[unsignedinteger[Any]]: ...
+) -> NDArray[unsignedinteger]: ...
 @overload
 def polyval(
     p: _ArrayLikeInt_co,
     x: _ArrayLikeInt_co,
-) -> NDArray[signedinteger[Any]]: ...
+) -> NDArray[signedinteger]: ...
 @overload
 def polyval(
     p: _ArrayLikeFloat_co,
     x: _ArrayLikeFloat_co,
-) -> NDArray[floating[Any]]: ...
+) -> NDArray[floating]: ...
 @overload
 def polyval(
     p: _ArrayLikeComplex_co,
     x: _ArrayLikeComplex_co,
-) -> NDArray[complexfloating[Any, Any]]: ...
+) -> NDArray[complexfloating]: ...
 @overload
 def polyval(
     p: _ArrayLikeObject_co,
@@ -222,22 +222,22 @@ def polyadd(
 def polyadd(
     a1: _ArrayLikeUInt_co,
     a2: _ArrayLikeUInt_co,
-) -> NDArray[unsignedinteger[Any]]: ...
+) -> NDArray[unsignedinteger]: ...
 @overload
 def polyadd(
     a1: _ArrayLikeInt_co,
     a2: _ArrayLikeInt_co,
-) -> NDArray[signedinteger[Any]]: ...
+) -> NDArray[signedinteger]: ...
 @overload
 def polyadd(
     a1: _ArrayLikeFloat_co,
     a2: _ArrayLikeFloat_co,
-) -> NDArray[floating[Any]]: ...
+) -> NDArray[floating]: ...
 @overload
 def polyadd(
     a1: _ArrayLikeComplex_co,
     a2: _ArrayLikeComplex_co,
-) -> NDArray[complexfloating[Any, Any]]: ...
+) -> NDArray[complexfloating]: ...
 @overload
 def polyadd(
     a1: _ArrayLikeObject_co,
@@ -263,22 +263,22 @@ def polysub(
 def polysub(
     a1: _ArrayLikeUInt_co,
     a2: _ArrayLikeUInt_co,
-) -> NDArray[unsignedinteger[Any]]: ...
+) -> NDArray[unsignedinteger]: ...
 @overload
 def polysub(
     a1: _ArrayLikeInt_co,
     a2: _ArrayLikeInt_co,
-) -> NDArray[signedinteger[Any]]: ...
+) -> NDArray[signedinteger]: ...
 @overload
 def polysub(
     a1: _ArrayLikeFloat_co,
     a2: _ArrayLikeFloat_co,
-) -> NDArray[floating[Any]]: ...
+) -> NDArray[floating]: ...
 @overload
 def polysub(
     a1: _ArrayLikeComplex_co,
     a2: _ArrayLikeComplex_co,
-) -> NDArray[complexfloating[Any, Any]]: ...
+) -> NDArray[complexfloating]: ...
 @overload
 def polysub(
     a1: _ArrayLikeObject_co,
@@ -302,12 +302,12 @@ def polydiv(
 def polydiv(
     u: _ArrayLikeFloat_co,
     v: _ArrayLikeFloat_co,
-) -> _2Tup[NDArray[floating[Any]]]: ...
+) -> _2Tup[NDArray[floating]]: ...
 @overload
 def polydiv(
     u: _ArrayLikeComplex_co,
     v: _ArrayLikeComplex_co,
-) -> _2Tup[NDArray[complexfloating[Any, Any]]]: ...
+) -> _2Tup[NDArray[complexfloating]]: ...
 @overload
 def polydiv(
     u: _ArrayLikeObject_co,
diff --git a/numpy/lib/_scimath_impl.pyi b/numpy/lib/_scimath_impl.pyi
index 43b7110b2923..a47a4f932d21 100644
--- a/numpy/lib/_scimath_impl.pyi
+++ b/numpy/lib/_scimath_impl.pyi
@@ -15,80 +15,80 @@ __all__ = ["sqrt", "log", "log2", "logn", "log10", "power", "arccos", "arcsin",
 @overload
 def sqrt(x: _FloatLike_co) -> Any: ...
 @overload
-def sqrt(x: _ComplexLike_co) -> complexfloating[Any, Any]: ...
+def sqrt(x: _ComplexLike_co) -> complexfloating: ...
 @overload
 def sqrt(x: _ArrayLikeFloat_co) -> NDArray[Any]: ...
 @overload
-def sqrt(x: _ArrayLikeComplex_co) -> NDArray[complexfloating[Any, Any]]: ...
+def sqrt(x: _ArrayLikeComplex_co) -> NDArray[complexfloating]: ...
 
 @overload
 def log(x: _FloatLike_co) -> Any: ...
 @overload
-def log(x: _ComplexLike_co) -> complexfloating[Any, Any]: ...
+def log(x: _ComplexLike_co) -> complexfloating: ...
 @overload
 def log(x: _ArrayLikeFloat_co) -> NDArray[Any]: ...
 @overload
-def log(x: _ArrayLikeComplex_co) -> NDArray[complexfloating[Any, Any]]: ...
+def log(x: _ArrayLikeComplex_co) -> NDArray[complexfloating]: ...
 
 @overload
 def log10(x: _FloatLike_co) -> Any: ...
 @overload
-def log10(x: _ComplexLike_co) -> complexfloating[Any, Any]: ...
+def log10(x: _ComplexLike_co) -> complexfloating: ...
 @overload
 def log10(x: _ArrayLikeFloat_co) -> NDArray[Any]: ...
 @overload
-def log10(x: _ArrayLikeComplex_co) -> NDArray[complexfloating[Any, Any]]: ...
+def log10(x: _ArrayLikeComplex_co) -> NDArray[complexfloating]: ...
 
 @overload
 def log2(x: _FloatLike_co) -> Any: ...
 @overload
-def log2(x: _ComplexLike_co) -> complexfloating[Any, Any]: ...
+def log2(x: _ComplexLike_co) -> complexfloating: ...
 @overload
 def log2(x: _ArrayLikeFloat_co) -> NDArray[Any]: ...
 @overload
-def log2(x: _ArrayLikeComplex_co) -> NDArray[complexfloating[Any, Any]]: ...
+def log2(x: _ArrayLikeComplex_co) -> NDArray[complexfloating]: ...
 
 @overload
 def logn(n: _FloatLike_co, x: _FloatLike_co) -> Any: ...
 @overload
-def logn(n: _ComplexLike_co, x: _ComplexLike_co) -> complexfloating[Any, Any]: ...
+def logn(n: _ComplexLike_co, x: _ComplexLike_co) -> complexfloating: ...
 @overload
 def logn(n: _ArrayLikeFloat_co, x: _ArrayLikeFloat_co) -> NDArray[Any]: ...
 @overload
-def logn(n: _ArrayLikeComplex_co, x: _ArrayLikeComplex_co) -> NDArray[complexfloating[Any, Any]]: ...
+def logn(n: _ArrayLikeComplex_co, x: _ArrayLikeComplex_co) -> NDArray[complexfloating]: ...
 
 @overload
 def power(x: _FloatLike_co, p: _FloatLike_co) -> Any: ...
 @overload
-def power(x: _ComplexLike_co, p: _ComplexLike_co) -> complexfloating[Any, Any]: ...
+def power(x: _ComplexLike_co, p: _ComplexLike_co) -> complexfloating: ...
 @overload
 def power(x: _ArrayLikeFloat_co, p: _ArrayLikeFloat_co) -> NDArray[Any]: ...
 @overload
-def power(x: _ArrayLikeComplex_co, p: _ArrayLikeComplex_co) -> NDArray[complexfloating[Any, Any]]: ...
+def power(x: _ArrayLikeComplex_co, p: _ArrayLikeComplex_co) -> NDArray[complexfloating]: ...
 
 @overload
 def arccos(x: _FloatLike_co) -> Any: ...
 @overload
-def arccos(x: _ComplexLike_co) -> complexfloating[Any, Any]: ...
+def arccos(x: _ComplexLike_co) -> complexfloating: ...
 @overload
 def arccos(x: _ArrayLikeFloat_co) -> NDArray[Any]: ...
 @overload
-def arccos(x: _ArrayLikeComplex_co) -> NDArray[complexfloating[Any, Any]]: ...
+def arccos(x: _ArrayLikeComplex_co) -> NDArray[complexfloating]: ...
 
 @overload
 def arcsin(x: _FloatLike_co) -> Any: ...
 @overload
-def arcsin(x: _ComplexLike_co) -> complexfloating[Any, Any]: ...
+def arcsin(x: _ComplexLike_co) -> complexfloating: ...
 @overload
 def arcsin(x: _ArrayLikeFloat_co) -> NDArray[Any]: ...
 @overload
-def arcsin(x: _ArrayLikeComplex_co) -> NDArray[complexfloating[Any, Any]]: ...
+def arcsin(x: _ArrayLikeComplex_co) -> NDArray[complexfloating]: ...
 
 @overload
 def arctanh(x: _FloatLike_co) -> Any: ...
 @overload
-def arctanh(x: _ComplexLike_co) -> complexfloating[Any, Any]: ...
+def arctanh(x: _ComplexLike_co) -> complexfloating: ...
 @overload
 def arctanh(x: _ArrayLikeFloat_co) -> NDArray[Any]: ...
 @overload
-def arctanh(x: _ArrayLikeComplex_co) -> NDArray[complexfloating[Any, Any]]: ...
+def arctanh(x: _ArrayLikeComplex_co) -> NDArray[complexfloating]: ...
diff --git a/numpy/lib/_shape_base_impl.pyi b/numpy/lib/_shape_base_impl.pyi
index ee3234fb45f4..09d67cc3a062 100644
--- a/numpy/lib/_shape_base_impl.pyi
+++ b/numpy/lib/_shape_base_impl.pyi
@@ -69,13 +69,13 @@ class _SupportsArrayWrap(Protocol):
 
 def take_along_axis(
     arr: _ScalarT | NDArray[_ScalarT],
-    indices: NDArray[integer[Any]],
+    indices: NDArray[integer],
     axis: int | None,
 ) -> NDArray[_ScalarT]: ...
 
 def put_along_axis(
     arr: NDArray[_ScalarT],
-    indices: NDArray[integer[Any]],
+    indices: NDArray[integer],
     values: ArrayLike,
     axis: int | None,
 ) -> None: ...
@@ -201,13 +201,13 @@ def get_array_wrap(*args: object) -> _ArrayWrap | None: ...
 @overload
 def kron(a: _ArrayLikeBool_co, b: _ArrayLikeBool_co) -> NDArray[np.bool]: ...  # type: ignore[misc]
 @overload
-def kron(a: _ArrayLikeUInt_co, b: _ArrayLikeUInt_co) -> NDArray[unsignedinteger[Any]]: ...  # type: ignore[misc]
+def kron(a: _ArrayLikeUInt_co, b: _ArrayLikeUInt_co) -> NDArray[unsignedinteger]: ...  # type: ignore[misc]
 @overload
-def kron(a: _ArrayLikeInt_co, b: _ArrayLikeInt_co) -> NDArray[signedinteger[Any]]: ...  # type: ignore[misc]
+def kron(a: _ArrayLikeInt_co, b: _ArrayLikeInt_co) -> NDArray[signedinteger]: ...  # type: ignore[misc]
 @overload
-def kron(a: _ArrayLikeFloat_co, b: _ArrayLikeFloat_co) -> NDArray[floating[Any]]: ...  # type: ignore[misc]
+def kron(a: _ArrayLikeFloat_co, b: _ArrayLikeFloat_co) -> NDArray[floating]: ...  # type: ignore[misc]
 @overload
-def kron(a: _ArrayLikeComplex_co, b: _ArrayLikeComplex_co) -> NDArray[complexfloating[Any, Any]]: ...
+def kron(a: _ArrayLikeComplex_co, b: _ArrayLikeComplex_co) -> NDArray[complexfloating]: ...
 @overload
 def kron(a: _ArrayLikeObject_co, b: Any) -> NDArray[object_]: ...
 @overload
diff --git a/numpy/lib/_twodim_base_impl.pyi b/numpy/lib/_twodim_base_impl.pyi
index 9867f59f9409..204bf2a2ecea 100644
--- a/numpy/lib/_twodim_base_impl.pyi
+++ b/numpy/lib/_twodim_base_impl.pyi
@@ -195,19 +195,19 @@ def vander(  # type: ignore[misc]
     x: _ArrayLikeInt_co,
     N: int | None = ...,
     increasing: bool = ...,
-) -> NDArray[signedinteger[Any]]: ...
+) -> NDArray[signedinteger]: ...
 @overload
 def vander(  # type: ignore[misc]
     x: _ArrayLikeFloat_co,
     N: int | None = ...,
     increasing: bool = ...,
-) -> NDArray[floating[Any]]: ...
+) -> NDArray[floating]: ...
 @overload
 def vander(
     x: _ArrayLikeComplex_co,
     N: int | None = ...,
     increasing: bool = ...,
-) -> NDArray[complexfloating[Any, Any]]: ...
+) -> NDArray[complexfloating]: ...
 @overload
 def vander(
     x: _ArrayLikeObject_co,
diff --git a/numpy/lib/_ufunclike_impl.pyi b/numpy/lib/_ufunclike_impl.pyi
index ea2b775a01ec..947532aa07a3 100644
--- a/numpy/lib/_ufunclike_impl.pyi
+++ b/numpy/lib/_ufunclike_impl.pyi
@@ -17,12 +17,12 @@ _ArrayT = TypeVar("_ArrayT", bound=NDArray[Any])
 def fix(  # type: ignore[misc]
     x: _FloatLike_co,
     out: None = ...,
-) -> floating[Any]: ...
+) -> floating: ...
 @overload
 def fix(
     x: _ArrayLikeFloat_co,
     out: None = ...,
-) -> NDArray[floating[Any]]: ...
+) -> NDArray[floating]: ...
 @overload
 def fix(
     x: _ArrayLikeObject_co,
diff --git a/numpy/linalg/_linalg.pyi b/numpy/linalg/_linalg.pyi
index 0f0de668b9a9..5c4cdd73d9c1 100644
--- a/numpy/linalg/_linalg.pyi
+++ b/numpy/linalg/_linalg.pyi
@@ -112,13 +112,13 @@ def tensorsolve(
     a: _ArrayLikeFloat_co,
     b: _ArrayLikeFloat_co,
     axes: Iterable[int] | None = ...,
-) -> NDArray[floating[Any]]: ...
+) -> NDArray[floating]: ...
 @overload
 def tensorsolve(
     a: _ArrayLikeComplex_co,
     b: _ArrayLikeComplex_co,
     axes: Iterable[int] | None = ...,
-) -> NDArray[complexfloating[Any, Any]]: ...
+) -> NDArray[complexfloating]: ...
 
 @overload
 def solve(
@@ -129,12 +129,12 @@ def solve(
 def solve(
     a: _ArrayLikeFloat_co,
     b: _ArrayLikeFloat_co,
-) -> NDArray[floating[Any]]: ...
+) -> NDArray[floating]: ...
 @overload
 def solve(
     a: _ArrayLikeComplex_co,
     b: _ArrayLikeComplex_co,
-) -> NDArray[complexfloating[Any, Any]]: ...
+) -> NDArray[complexfloating]: ...
 
 @overload
 def tensorinv(
@@ -145,19 +145,19 @@ def tensorinv(
 def tensorinv(
     a: _ArrayLikeFloat_co,
     ind: int = ...,
-) -> NDArray[floating[Any]]: ...
+) -> NDArray[floating]: ...
 @overload
 def tensorinv(
     a: _ArrayLikeComplex_co,
     ind: int = ...,
-) -> NDArray[complexfloating[Any, Any]]: ...
+) -> NDArray[complexfloating]: ...
 
 @overload
 def inv(a: _ArrayLikeInt_co) -> NDArray[float64]: ...
 @overload
-def inv(a: _ArrayLikeFloat_co) -> NDArray[floating[Any]]: ...
+def inv(a: _ArrayLikeFloat_co) -> NDArray[floating]: ...
 @overload
-def inv(a: _ArrayLikeComplex_co) -> NDArray[complexfloating[Any, Any]]: ...
+def inv(a: _ArrayLikeComplex_co) -> NDArray[complexfloating]: ...
 
 # TODO: The supported input and output dtypes are dependent on the value of `n`.
 # For example: `n < 0` always casts integer types to float64
@@ -169,25 +169,25 @@ def matrix_power(
 @overload
 def cholesky(a: _ArrayLikeInt_co, /, *, upper: bool = False) -> NDArray[float64]: ...
 @overload
-def cholesky(a: _ArrayLikeFloat_co, /, *, upper: bool = False) -> NDArray[floating[Any]]: ...
+def cholesky(a: _ArrayLikeFloat_co, /, *, upper: bool = False) -> NDArray[floating]: ...
 @overload
-def cholesky(a: _ArrayLikeComplex_co, /, *, upper: bool = False) -> NDArray[complexfloating[Any, Any]]: ...
+def cholesky(a: _ArrayLikeComplex_co, /, *, upper: bool = False) -> NDArray[complexfloating]: ...
 
 @overload
 def outer(x1: _ArrayLike[Never], x2: _ArrayLike[Never]) -> NDArray[Any]: ...
 @overload
 def outer(x1: _ArrayLikeBool_co, x2: _ArrayLikeBool_co) -> NDArray[np.bool]: ...
 @overload
-def outer(x1: _ArrayLikeUInt_co, x2: _ArrayLikeUInt_co) -> NDArray[unsignedinteger[Any]]: ...
+def outer(x1: _ArrayLikeUInt_co, x2: _ArrayLikeUInt_co) -> NDArray[unsignedinteger]: ...
 @overload
-def outer(x1: _ArrayLikeInt_co, x2: _ArrayLikeInt_co) -> NDArray[signedinteger[Any]]: ...
+def outer(x1: _ArrayLikeInt_co, x2: _ArrayLikeInt_co) -> NDArray[signedinteger]: ...
 @overload
-def outer(x1: _ArrayLikeFloat_co, x2: _ArrayLikeFloat_co) -> NDArray[floating[Any]]: ...
+def outer(x1: _ArrayLikeFloat_co, x2: _ArrayLikeFloat_co) -> NDArray[floating]: ...
 @overload
 def outer(
     x1: _ArrayLikeComplex_co,
     x2: _ArrayLikeComplex_co,
-) -> NDArray[complexfloating[Any, Any]]: ...
+) -> NDArray[complexfloating]: ...
 @overload
 def outer(
     x1: _ArrayLikeTD64_co,
@@ -212,14 +212,14 @@ def qr(a: _ArrayLikeComplex_co, mode: _ModeKind = ...) -> QRResult: ...
 @overload
 def eigvals(a: _ArrayLikeInt_co) -> NDArray[float64] | NDArray[complex128]: ...
 @overload
-def eigvals(a: _ArrayLikeFloat_co) -> NDArray[floating[Any]] | NDArray[complexfloating[Any, Any]]: ...
+def eigvals(a: _ArrayLikeFloat_co) -> NDArray[floating] | NDArray[complexfloating]: ...
 @overload
-def eigvals(a: _ArrayLikeComplex_co) -> NDArray[complexfloating[Any, Any]]: ...
+def eigvals(a: _ArrayLikeComplex_co) -> NDArray[complexfloating]: ...
 
 @overload
 def eigvalsh(a: _ArrayLikeInt_co, UPLO: L["L", "U", "l", "u"] = ...) -> NDArray[float64]: ...
 @overload
-def eigvalsh(a: _ArrayLikeComplex_co, UPLO: L["L", "U", "l", "u"] = ...) -> NDArray[floating[Any]]: ...
+def eigvalsh(a: _ArrayLikeComplex_co, UPLO: L["L", "U", "l", "u"] = ...) -> NDArray[floating]: ...
 
 @overload
 def eig(a: _ArrayLikeInt_co) -> EigResult: ...
@@ -278,11 +278,11 @@ def svd(
     full_matrices: bool = ...,
     compute_uv: L[False] = ...,
     hermitian: bool = ...,
-) -> NDArray[floating[Any]]: ...
+) -> NDArray[floating]: ...
 
 def svdvals(
     x: _ArrayLikeInt_co | _ArrayLikeFloat_co | _ArrayLikeComplex_co
-) -> NDArray[floating[Any]]: ...
+) -> NDArray[floating]: ...
 
 # TODO: Returns a scalar for 2D arrays and
 # a `(x.ndim - 2)`` dimensionl array otherwise
@@ -308,13 +308,13 @@ def pinv(
     a: _ArrayLikeFloat_co,
     rcond: _ArrayLikeFloat_co = ...,
     hermitian: bool = ...,
-) -> NDArray[floating[Any]]: ...
+) -> NDArray[floating]: ...
 @overload
 def pinv(
     a: _ArrayLikeComplex_co,
     rcond: _ArrayLikeFloat_co = ...,
     hermitian: bool = ...,
-) -> NDArray[complexfloating[Any, Any]]: ...
+) -> NDArray[complexfloating]: ...
 
 # TODO: Returns a 2-tuple of scalars for 2D arrays and
 # a 2-tuple of `(a.ndim - 2)`` dimensionl arrays otherwise
@@ -333,17 +333,17 @@ def lstsq(a: _ArrayLikeInt_co, b: _ArrayLikeInt_co, rcond: float | None = ...) -
 ]: ...
 @overload
 def lstsq(a: _ArrayLikeFloat_co, b: _ArrayLikeFloat_co, rcond: float | None = ...) -> tuple[
-    NDArray[floating[Any]],
-    NDArray[floating[Any]],
+    NDArray[floating],
+    NDArray[floating],
     int32,
-    NDArray[floating[Any]],
+    NDArray[floating],
 ]: ...
 @overload
 def lstsq(a: _ArrayLikeComplex_co, b: _ArrayLikeComplex_co, rcond: float | None = ...) -> tuple[
-    NDArray[complexfloating[Any, Any]],
-    NDArray[floating[Any]],
+    NDArray[complexfloating],
+    NDArray[floating],
     int32,
-    NDArray[floating[Any]],
+    NDArray[floating],
 ]: ...
 
 @overload
@@ -352,7 +352,7 @@ def norm(
     ord: float | L["fro", "nuc"] | None = ...,
     axis: None = ...,
     keepdims: bool = ...,
-) -> floating[Any]: ...
+) -> floating: ...
 @overload
 def norm(
     x: ArrayLike,
@@ -368,7 +368,7 @@ def matrix_norm(
     *,
     ord: float | L["fro", "nuc"] | None = ...,
     keepdims: bool = ...,
-) -> floating[Any]: ...
+) -> floating: ...
 @overload
 def matrix_norm(
     x: ArrayLike,
@@ -386,7 +386,7 @@ def vector_norm(
     axis: None = ...,
     ord: float | None = ...,
     keepdims: bool = ...,
-) -> floating[Any]: ...
+) -> floating: ...
 @overload
 def vector_norm(
     x: ArrayLike,
@@ -426,7 +426,7 @@ def cross(
     /,
     *,
     axis: int = ...,
-) -> NDArray[unsignedinteger[Any]]: ...
+) -> NDArray[unsignedinteger]: ...
 @overload
 def cross(
     x1: _ArrayLikeInt_co,
@@ -434,7 +434,7 @@ def cross(
     /,
     *,
     axis: int = ...,
-) -> NDArray[signedinteger[Any]]: ...
+) -> NDArray[signedinteger]: ...
 @overload
 def cross(
     x1: _ArrayLikeFloat_co,
@@ -442,7 +442,7 @@ def cross(
     /,
     *,
     axis: int = ...,
-) -> NDArray[floating[Any]]: ...
+) -> NDArray[floating]: ...
 @overload
 def cross(
     x1: _ArrayLikeComplex_co,
@@ -450,25 +450,25 @@ def cross(
     /,
     *,
     axis: int = ...,
-) -> NDArray[complexfloating[Any, Any]]: ...
+) -> NDArray[complexfloating]: ...
 
 @overload
 def matmul(
     x1: _ArrayLikeInt_co,
     x2: _ArrayLikeInt_co,
-) -> NDArray[signedinteger[Any]]: ...
+) -> NDArray[signedinteger]: ...
 @overload
 def matmul(
     x1: _ArrayLikeUInt_co,
     x2: _ArrayLikeUInt_co,
-) -> NDArray[unsignedinteger[Any]]: ...
+) -> NDArray[unsignedinteger]: ...
 @overload
 def matmul(
     x1: _ArrayLikeFloat_co,
     x2: _ArrayLikeFloat_co,
-) -> NDArray[floating[Any]]: ...
+) -> NDArray[floating]: ...
 @overload
 def matmul(
     x1: _ArrayLikeComplex_co,
     x2: _ArrayLikeComplex_co,
-) -> NDArray[complexfloating[Any, Any]]: ...
+) -> NDArray[complexfloating]: ...
diff --git a/numpy/polynomial/_polybase.pyi b/numpy/polynomial/_polybase.pyi
index 7923faf2c256..d36e6b64ca20 100644
--- a/numpy/polynomial/_polybase.pyi
+++ b/numpy/polynomial/_polybase.pyi
@@ -47,8 +47,8 @@ class ABCPolyBase(Generic[_NameCo], abc.ABC):
 
     basis_name: _NameCo
     coef: _CoefSeries
-    domain: _Array2[np.inexact[Any] | np.object_]
-    window: _Array2[np.inexact[Any] | np.object_]
+    domain: _Array2[np.inexact | np.object_]
+    window: _Array2[np.inexact | np.object_]
 
     _symbol: LiteralString
     @property
@@ -119,7 +119,7 @@ class ABCPolyBase(Generic[_NameCo], abc.ABC):
     def __rmod__(self, x: _AnyOther, /) -> Self: ...
     def __rdivmod__(self, x: _AnyOther, /) -> _Tuple2[Self]: ...
     def __len__(self, /) -> int: ...
-    def __iter__(self, /) -> Iterator[np.inexact[Any] | object]: ...
+    def __iter__(self, /) -> Iterator[np.inexact | object]: ...
     def __getstate__(self, /) -> dict[str, Any]: ...
     def __setstate__(self, dict: dict[str, Any], /) -> None: ...
 
@@ -212,7 +212,7 @@ class ABCPolyBase(Generic[_NameCo], abc.ABC):
         w: _SeriesLikeCoef_co | None = ...,
         window: _SeriesLikeCoef_co | None = ...,
         symbol: str = ...,
-    ) -> tuple[Self, Sequence[np.inexact[Any] | np.int32]]: ...
+    ) -> tuple[Self, Sequence[np.inexact | np.int32]]: ...
     @overload
     @classmethod
     def fit(
@@ -226,7 +226,7 @@ class ABCPolyBase(Generic[_NameCo], abc.ABC):
         w: _SeriesLikeCoef_co | None = ...,
         window: _SeriesLikeCoef_co | None = ...,
         symbol: str = ...,
-    ) -> tuple[Self, Sequence[np.inexact[Any] | np.int32]]: ...
+    ) -> tuple[Self, Sequence[np.inexact | np.int32]]: ...
 
     @classmethod
     def fromroots(
diff --git a/numpy/polynomial/_polytypes.pyi b/numpy/polynomial/_polytypes.pyi
index 0aaa8b78ae2b..de2d36142497 100644
--- a/numpy/polynomial/_polytypes.pyi
+++ b/numpy/polynomial/_polytypes.pyi
@@ -35,7 +35,7 @@ from numpy._typing import (
 
 _T = TypeVar("_T")
 _T_contra = TypeVar("_T_contra", contravariant=True)
-_ScalarT = TypeVar("_ScalarT", bound=np.number[Any] | np.bool | np.object_)
+_ScalarT = TypeVar("_ScalarT", bound=np.number | np.bool | np.object_)
 
 # compatible with e.g. int, float, complex, Decimal, Fraction, and ABCPolyBase
 @type_check_only
@@ -57,15 +57,15 @@ class _SupportsCoefOps(Protocol[_T_contra]):
 
 _Series: TypeAlias = np.ndarray[tuple[int], np.dtype[_ScalarT]]
 
-_FloatSeries: TypeAlias = _Series[np.floating[Any]]
-_ComplexSeries: TypeAlias = _Series[np.complexfloating[Any, Any]]
+_FloatSeries: TypeAlias = _Series[np.floating]
+_ComplexSeries: TypeAlias = _Series[np.complexfloating]
 _ObjectSeries: TypeAlias = _Series[np.object_]
-_CoefSeries: TypeAlias = _Series[np.inexact[Any] | np.object_]
+_CoefSeries: TypeAlias = _Series[np.inexact | np.object_]
 
-_FloatArray: TypeAlias = npt.NDArray[np.floating[Any]]
-_ComplexArray: TypeAlias = npt.NDArray[np.complexfloating[Any, Any]]
+_FloatArray: TypeAlias = npt.NDArray[np.floating]
+_ComplexArray: TypeAlias = npt.NDArray[np.complexfloating]
 _ObjectArray: TypeAlias = npt.NDArray[np.object_]
-_CoefArray: TypeAlias = npt.NDArray[np.inexact[Any] | np.object_]
+_CoefArray: TypeAlias = npt.NDArray[np.inexact | np.object_]
 
 _Tuple2: TypeAlias = tuple[_T, _T]
 _Array1: TypeAlias = np.ndarray[tuple[Literal[1]], np.dtype[_ScalarT]]
@@ -82,15 +82,15 @@ _SeriesLikeBool_co: TypeAlias = (
     | Sequence[bool | np.bool]
 )
 _SeriesLikeInt_co: TypeAlias = (
-    _SupportsArray[np.dtype[np.integer[Any] | np.bool]]
+    _SupportsArray[np.dtype[np.integer | np.bool]]
     | Sequence[_IntLike_co]
 )
 _SeriesLikeFloat_co: TypeAlias = (
-    _SupportsArray[np.dtype[np.floating[Any] | np.integer[Any] | np.bool]]
+    _SupportsArray[np.dtype[np.floating | np.integer | np.bool]]
     | Sequence[_FloatLike_co]
 )
 _SeriesLikeComplex_co: TypeAlias = (
-    _SupportsArray[np.dtype[np.inexact[Any] | np.integer[Any] | np.bool]]
+    _SupportsArray[np.dtype[np.inexact | np.integer | np.bool]]
     | Sequence[_ComplexLike_co]
 )
 _SeriesLikeObject_co: TypeAlias = (
@@ -98,7 +98,7 @@ _SeriesLikeObject_co: TypeAlias = (
     | Sequence[_CoefObjectLike_co]
 )
 _SeriesLikeCoef_co: TypeAlias = (
-    _SupportsArray[np.dtype[np.number[Any] | np.bool | np.object_]]
+    _SupportsArray[np.dtype[np.number | np.bool | np.object_]]
     | Sequence[_CoefLike_co]
 )
 
@@ -108,7 +108,7 @@ _ArrayLikeCoefObject_co: TypeAlias = (
     | _NestedSequence[_SeriesLikeObject_co]
 )
 _ArrayLikeCoef_co: TypeAlias = (
-    npt.NDArray[np.number[Any] | np.bool | np.object_]
+    npt.NDArray[np.number | np.bool | np.object_]
     | _ArrayLikeNumber_co
     | _ArrayLikeCoefObject_co
 )
@@ -310,7 +310,7 @@ class _FuncValFromRoots(_Named[_Name_co], Protocol[_Name_co]):
         x: _FloatLike_co,
         r: _FloatLike_co,
         tensor: bool = ...,
-    ) -> np.floating[Any]: ...
+    ) -> np.floating: ...
     @overload
     def __call__(
         self,
@@ -318,7 +318,7 @@ class _FuncValFromRoots(_Named[_Name_co], Protocol[_Name_co]):
         x: _NumberLike_co,
         r: _NumberLike_co,
         tensor: bool = ...,
-    ) -> np.complexfloating[Any, Any]: ...
+    ) -> np.complexfloating: ...
     @overload
     def __call__(
         self,
@@ -361,7 +361,7 @@ class _FuncVal(_Named[_Name_co], Protocol[_Name_co]):
         x: _FloatLike_co,
         c: _SeriesLikeFloat_co,
         tensor: bool = ...,
-    ) -> np.floating[Any]: ...
+    ) -> np.floating: ...
     @overload
     def __call__(
         self,
@@ -369,7 +369,7 @@ class _FuncVal(_Named[_Name_co], Protocol[_Name_co]):
         x: _NumberLike_co,
         c: _SeriesLikeComplex_co,
         tensor: bool = ...,
-    ) -> np.complexfloating[Any, Any]: ...
+    ) -> np.complexfloating: ...
     @overload
     def __call__(
         self,
@@ -412,7 +412,7 @@ class _FuncVal2D(_Named[_Name_co], Protocol[_Name_co]):
         x: _FloatLike_co,
         y: _FloatLike_co,
         c: _SeriesLikeFloat_co,
-    ) -> np.floating[Any]: ...
+    ) -> np.floating: ...
     @overload
     def __call__(
         self,
@@ -420,7 +420,7 @@ class _FuncVal2D(_Named[_Name_co], Protocol[_Name_co]):
         x: _NumberLike_co,
         y: _NumberLike_co,
         c: _SeriesLikeComplex_co,
-    ) -> np.complexfloating[Any, Any]: ...
+    ) -> np.complexfloating: ...
     @overload
     def __call__(
         self,
@@ -464,7 +464,7 @@ class _FuncVal3D(_Named[_Name_co], Protocol[_Name_co]):
         y: _FloatLike_co,
         z: _FloatLike_co,
         c: _SeriesLikeFloat_co
-    ) -> np.floating[Any]: ...
+    ) -> np.floating: ...
     @overload
     def __call__(
         self,
@@ -473,7 +473,7 @@ class _FuncVal3D(_Named[_Name_co], Protocol[_Name_co]):
         y: _NumberLike_co,
         z: _NumberLike_co,
         c: _SeriesLikeComplex_co,
-    ) -> np.complexfloating[Any, Any]: ...
+    ) -> np.complexfloating: ...
     @overload
     def __call__(
         self,
@@ -525,7 +525,7 @@ class _FuncValND(_Named[_Name_co], Protocol[_Name_co]):
         c: _SeriesLikeFloat_co,
         /,
         *args: _FloatLike_co,
-    ) -> np.floating[Any]: ...
+    ) -> np.floating: ...
     @overload
     def __call__(
         self,
@@ -533,7 +533,7 @@ class _FuncValND(_Named[_Name_co], Protocol[_Name_co]):
         c: _SeriesLikeComplex_co,
         /,
         *args: _NumberLike_co,
-    ) -> np.complexfloating[Any, Any]: ...
+    ) -> np.complexfloating: ...
     @overload
     def __call__(
         self,
@@ -717,7 +717,7 @@ class _FuncVanderND(_Named[_Name_co], Protocol[_Name_co]):
         degrees: Sequence[SupportsIndex],
     ) -> _CoefArray: ...
 
-_FullFitResult: TypeAlias = Sequence[np.inexact[Any] | np.int32]
+_FullFitResult: TypeAlias = Sequence[np.inexact | np.int32]
 
 @type_check_only
 class _FuncFit(_Named[_Name_co], Protocol[_Name_co]):
diff --git a/numpy/polynomial/chebyshev.pyi b/numpy/polynomial/chebyshev.pyi
index f2dc5d8fc470..ec342df0f9d1 100644
--- a/numpy/polynomial/chebyshev.pyi
+++ b/numpy/polynomial/chebyshev.pyi
@@ -74,7 +74,7 @@ __all__ = [
     "chebinterpolate",
 ]
 
-_NumberOrObjectT = TypeVar("_NumberOrObjectT", bound=np.number[Any] | np.object_)
+_NumberOrObjectT = TypeVar("_NumberOrObjectT", bound=np.number | np.object_)
 def _cseries_to_zseries(c: npt.NDArray[_NumberOrObjectT]) -> _Series[_NumberOrObjectT]: ...
 def _zseries_to_cseries(zs: npt.NDArray[_NumberOrObjectT]) -> _Series[_NumberOrObjectT]: ...
 def _zseries_mul(
@@ -124,7 +124,7 @@ chebpts1: _FuncPts[L["chebpts1"]]
 chebpts2: _FuncPts[L["chebpts2"]]
 
 # keep in sync with `Chebyshev.interpolate`
-_RT = TypeVar("_RT", bound=np.number[Any] | np.bool | np.object_)
+_RT = TypeVar("_RT", bound=np.number | np.bool | np.object_)
 @overload
 def chebinterpolate(
     func: np.ufunc,
diff --git a/numpy/polynomial/polyutils.pyi b/numpy/polynomial/polyutils.pyi
index 08607fcf94ba..57657808fcaf 100644
--- a/numpy/polynomial/polyutils.pyi
+++ b/numpy/polynomial/polyutils.pyi
@@ -73,7 +73,7 @@ _AnyVanderF: TypeAlias = Callable[
 
 @overload
 def as_series(
-    alist: npt.NDArray[np.integer[Any]] | _FloatArray,
+    alist: npt.NDArray[np.integer] | _FloatArray,
     trim: bool = ...,
 ) -> list[_FloatSeries]: ...
 @overload
@@ -88,7 +88,7 @@ def as_series(
 ) -> list[_ObjectSeries]: ...
 @overload
 def as_series(  # type: ignore[overload-overlap]
-    alist: Iterable[_FloatArray | npt.NDArray[np.integer[Any]]],
+    alist: Iterable[_FloatArray | npt.NDArray[np.integer]],
     trim: bool = ...,
 ) -> list[_FloatSeries]: ...
 @overload
@@ -122,7 +122,7 @@ def trimseq(seq: _T_seq) -> _T_seq: ...
 
 @overload
 def trimcoef(  # type: ignore[overload-overlap]
-    c: npt.NDArray[np.integer[Any]] | _FloatArray,
+    c: npt.NDArray[np.integer] | _FloatArray,
     tol: _FloatLike_co = ...,
 ) -> _FloatSeries: ...
 @overload
@@ -153,7 +153,7 @@ def trimcoef(
 
 @overload
 def getdomain(  # type: ignore[overload-overlap]
-    x: _FloatArray | npt.NDArray[np.integer[Any]],
+    x: _FloatArray | npt.NDArray[np.integer],
 ) -> _Array2[np.float64]: ...
 @overload
 def getdomain(
@@ -178,18 +178,18 @@ def getdomain(
 
 @overload
 def mapparms(  # type: ignore[overload-overlap]
-    old: npt.NDArray[np.floating[Any] | np.integer[Any]],
-    new: npt.NDArray[np.floating[Any] | np.integer[Any]],
-) -> _Tuple2[np.floating[Any]]: ...
+    old: npt.NDArray[np.floating | np.integer],
+    new: npt.NDArray[np.floating | np.integer],
+) -> _Tuple2[np.floating]: ...
 @overload
 def mapparms(
-    old: npt.NDArray[np.number[Any]],
-    new: npt.NDArray[np.number[Any]],
-) -> _Tuple2[np.complexfloating[Any, Any]]: ...
+    old: npt.NDArray[np.number],
+    new: npt.NDArray[np.number],
+) -> _Tuple2[np.complexfloating]: ...
 @overload
 def mapparms(
-    old: npt.NDArray[np.object_ | np.number[Any]],
-    new: npt.NDArray[np.object_ | np.number[Any]],
+    old: npt.NDArray[np.object_ | np.number],
+    new: npt.NDArray[np.object_ | np.number],
 ) -> _Tuple2[object]: ...
 @overload
 def mapparms(  # type: ignore[overload-overlap]
@@ -205,12 +205,12 @@ def mapparms(
 def mapparms(
     old: _SeriesLikeFloat_co,
     new: _SeriesLikeFloat_co,
-) -> _Tuple2[np.floating[Any]]: ...
+) -> _Tuple2[np.floating]: ...
 @overload
 def mapparms(
     old: _SeriesLikeComplex_co,
     new: _SeriesLikeComplex_co,
-) -> _Tuple2[np.complexfloating[Any, Any]]: ...
+) -> _Tuple2[np.complexfloating]: ...
 @overload
 def mapparms(
     old: _SeriesLikeCoef_co,
@@ -222,30 +222,30 @@ def mapdomain(  # type: ignore[overload-overlap]
     x: _FloatLike_co,
     old: _SeriesLikeFloat_co,
     new: _SeriesLikeFloat_co,
-) -> np.floating[Any]: ...
+) -> np.floating: ...
 @overload
 def mapdomain(
     x: _NumberLike_co,
     old: _SeriesLikeComplex_co,
     new: _SeriesLikeComplex_co,
-) -> np.complexfloating[Any, Any]: ...
+) -> np.complexfloating: ...
 @overload
 def mapdomain(  # type: ignore[overload-overlap]
-    x: npt.NDArray[np.floating[Any] | np.integer[Any]],
-    old: npt.NDArray[np.floating[Any] | np.integer[Any]],
-    new: npt.NDArray[np.floating[Any] | np.integer[Any]],
+    x: npt.NDArray[np.floating | np.integer],
+    old: npt.NDArray[np.floating | np.integer],
+    new: npt.NDArray[np.floating | np.integer],
 ) -> _FloatSeries: ...
 @overload
 def mapdomain(
-    x: npt.NDArray[np.number[Any]],
-    old: npt.NDArray[np.number[Any]],
-    new: npt.NDArray[np.number[Any]],
+    x: npt.NDArray[np.number],
+    old: npt.NDArray[np.number],
+    new: npt.NDArray[np.number],
 ) -> _ComplexSeries: ...
 @overload
 def mapdomain(
-    x: npt.NDArray[np.object_ | np.number[Any]],
-    old: npt.NDArray[np.object_ | np.number[Any]],
-    new: npt.NDArray[np.object_ | np.number[Any]],
+    x: npt.NDArray[np.object_ | np.number],
+    old: npt.NDArray[np.object_ | np.number],
+    new: npt.NDArray[np.object_ | np.number],
 ) -> _ObjectSeries: ...
 @overload
 def mapdomain(  # type: ignore[overload-overlap]
@@ -413,7 +413,7 @@ def _fit(
     full: Literal[True],
     /,
     w: _SeriesLikeCoef_co | None = ...,
-) -> tuple[_CoefSeries, Sequence[np.inexact[Any] | np.int32]]: ...
+) -> tuple[_CoefSeries, Sequence[np.inexact | np.int32]]: ...
 @overload
 def _fit(
     vander_f: _AnyVanderF,
@@ -425,7 +425,7 @@ def _fit(
     *,
     full: Literal[True],
     w: _SeriesLikeCoef_co | None = ...,
-) -> tuple[_CoefSeries, Sequence[np.inexact[Any] | np.int32]]: ...
+) -> tuple[_CoefSeries, Sequence[np.inexact | np.int32]]: ...
 
 def _as_int(x: SupportsIndex, desc: str) -> int: ...
 def format_float(x: _FloatLike_co, parens: bool = ...) -> str: ...
diff --git a/numpy/typing/tests/data/reveal/arithmetic.pyi b/numpy/typing/tests/data/reveal/arithmetic.pyi
index 2a33e4fc9148..b48226b75637 100644
--- a/numpy/typing/tests/data/reveal/arithmetic.pyi
+++ b/numpy/typing/tests/data/reveal/arithmetic.pyi
@@ -64,53 +64,53 @@ AR_LIKE_O: list[np.object_]
 
 # Array subtraction
 
-assert_type(AR_number - AR_number, npt.NDArray[np.number[Any]])
+assert_type(AR_number - AR_number, npt.NDArray[np.number])
 
 assert_type(AR_b - AR_LIKE_u, npt.NDArray[np.uint32])
-assert_type(AR_b - AR_LIKE_i, npt.NDArray[np.signedinteger[Any]])
-assert_type(AR_b - AR_LIKE_f, npt.NDArray[np.floating[Any]])
-assert_type(AR_b - AR_LIKE_c, npt.NDArray[np.complexfloating[Any, Any]])
+assert_type(AR_b - AR_LIKE_i, npt.NDArray[np.signedinteger])
+assert_type(AR_b - AR_LIKE_f, npt.NDArray[np.floating])
+assert_type(AR_b - AR_LIKE_c, npt.NDArray[np.complexfloating])
 assert_type(AR_b - AR_LIKE_m, npt.NDArray[np.timedelta64])
 assert_type(AR_b - AR_LIKE_O, Any)
 
 assert_type(AR_LIKE_u - AR_b, npt.NDArray[np.uint32])
-assert_type(AR_LIKE_i - AR_b, npt.NDArray[np.signedinteger[Any]])
-assert_type(AR_LIKE_f - AR_b, npt.NDArray[np.floating[Any]])
-assert_type(AR_LIKE_c - AR_b, npt.NDArray[np.complexfloating[Any, Any]])
+assert_type(AR_LIKE_i - AR_b, npt.NDArray[np.signedinteger])
+assert_type(AR_LIKE_f - AR_b, npt.NDArray[np.floating])
+assert_type(AR_LIKE_c - AR_b, npt.NDArray[np.complexfloating])
 assert_type(AR_LIKE_m - AR_b, npt.NDArray[np.timedelta64])
 assert_type(AR_LIKE_M - AR_b, npt.NDArray[np.datetime64])
 assert_type(AR_LIKE_O - AR_b, Any)
 
 assert_type(AR_u - AR_LIKE_b, npt.NDArray[np.uint32])
-assert_type(AR_u - AR_LIKE_u, npt.NDArray[np.unsignedinteger[Any]])
-assert_type(AR_u - AR_LIKE_i, npt.NDArray[np.signedinteger[Any]])
-assert_type(AR_u - AR_LIKE_f, npt.NDArray[np.floating[Any]])
-assert_type(AR_u - AR_LIKE_c, npt.NDArray[np.complexfloating[Any, Any]])
+assert_type(AR_u - AR_LIKE_u, npt.NDArray[np.unsignedinteger])
+assert_type(AR_u - AR_LIKE_i, npt.NDArray[np.signedinteger])
+assert_type(AR_u - AR_LIKE_f, npt.NDArray[np.floating])
+assert_type(AR_u - AR_LIKE_c, npt.NDArray[np.complexfloating])
 assert_type(AR_u - AR_LIKE_m, npt.NDArray[np.timedelta64])
 assert_type(AR_u - AR_LIKE_O, Any)
 
 assert_type(AR_LIKE_b - AR_u, npt.NDArray[np.uint32])
-assert_type(AR_LIKE_u - AR_u, npt.NDArray[np.unsignedinteger[Any]])
-assert_type(AR_LIKE_i - AR_u, npt.NDArray[np.signedinteger[Any]])
-assert_type(AR_LIKE_f - AR_u, npt.NDArray[np.floating[Any]])
-assert_type(AR_LIKE_c - AR_u, npt.NDArray[np.complexfloating[Any, Any]])
+assert_type(AR_LIKE_u - AR_u, npt.NDArray[np.unsignedinteger])
+assert_type(AR_LIKE_i - AR_u, npt.NDArray[np.signedinteger])
+assert_type(AR_LIKE_f - AR_u, npt.NDArray[np.floating])
+assert_type(AR_LIKE_c - AR_u, npt.NDArray[np.complexfloating])
 assert_type(AR_LIKE_m - AR_u, npt.NDArray[np.timedelta64])
 assert_type(AR_LIKE_M - AR_u, npt.NDArray[np.datetime64])
 assert_type(AR_LIKE_O - AR_u, Any)
 
 assert_type(AR_i - AR_LIKE_b, npt.NDArray[np.int64])
-assert_type(AR_i - AR_LIKE_u, npt.NDArray[np.signedinteger[Any]])
-assert_type(AR_i - AR_LIKE_i, npt.NDArray[np.signedinteger[Any]])
-assert_type(AR_i - AR_LIKE_f, npt.NDArray[np.floating[Any]])
-assert_type(AR_i - AR_LIKE_c, npt.NDArray[np.complexfloating[Any, Any]])
+assert_type(AR_i - AR_LIKE_u, npt.NDArray[np.signedinteger])
+assert_type(AR_i - AR_LIKE_i, npt.NDArray[np.signedinteger])
+assert_type(AR_i - AR_LIKE_f, npt.NDArray[np.floating])
+assert_type(AR_i - AR_LIKE_c, npt.NDArray[np.complexfloating])
 assert_type(AR_i - AR_LIKE_m, npt.NDArray[np.timedelta64])
 assert_type(AR_i - AR_LIKE_O, Any)
 
 assert_type(AR_LIKE_b - AR_i, npt.NDArray[np.int64])
-assert_type(AR_LIKE_u - AR_i, npt.NDArray[np.signedinteger[Any]])
-assert_type(AR_LIKE_i - AR_i, npt.NDArray[np.signedinteger[Any]])
-assert_type(AR_LIKE_f - AR_i, npt.NDArray[np.floating[Any]])
-assert_type(AR_LIKE_c - AR_i, npt.NDArray[np.complexfloating[Any, Any]])
+assert_type(AR_LIKE_u - AR_i, npt.NDArray[np.signedinteger])
+assert_type(AR_LIKE_i - AR_i, npt.NDArray[np.signedinteger])
+assert_type(AR_LIKE_f - AR_i, npt.NDArray[np.floating])
+assert_type(AR_LIKE_c - AR_i, npt.NDArray[np.complexfloating])
 assert_type(AR_LIKE_m - AR_i, npt.NDArray[np.timedelta64])
 assert_type(AR_LIKE_M - AR_i, npt.NDArray[np.datetime64])
 assert_type(AR_LIKE_O - AR_i, Any)
@@ -119,14 +119,14 @@ assert_type(AR_f - AR_LIKE_b, npt.NDArray[np.float64])
 assert_type(AR_f - AR_LIKE_u, npt.NDArray[np.float64])
 assert_type(AR_f - AR_LIKE_i, npt.NDArray[np.float64])
 assert_type(AR_f - AR_LIKE_f, npt.NDArray[np.float64])
-assert_type(AR_f - AR_LIKE_c, npt.NDArray[np.complexfloating[Any, Any]])
+assert_type(AR_f - AR_LIKE_c, npt.NDArray[np.complexfloating])
 assert_type(AR_f - AR_LIKE_O, Any)
 
 assert_type(AR_LIKE_b - AR_f, npt.NDArray[np.float64])
 assert_type(AR_LIKE_u - AR_f, npt.NDArray[np.float64])
 assert_type(AR_LIKE_i - AR_f, npt.NDArray[np.float64])
 assert_type(AR_LIKE_f - AR_f, npt.NDArray[np.float64])
-assert_type(AR_LIKE_c - AR_f, npt.NDArray[np.complexfloating[Any, Any]])
+assert_type(AR_LIKE_c - AR_f, npt.NDArray[np.complexfloating])
 assert_type(AR_LIKE_O - AR_f, Any)
 
 assert_type(AR_c - AR_LIKE_b, npt.NDArray[np.complex128])
@@ -274,39 +274,39 @@ assert_type(AR_LIKE_O / AR_O, Any)
 
 assert_type(AR_b // AR_LIKE_b, npt.NDArray[np.int8])
 assert_type(AR_b // AR_LIKE_u, npt.NDArray[np.uint32])
-assert_type(AR_b // AR_LIKE_i, npt.NDArray[np.signedinteger[Any]])
-assert_type(AR_b // AR_LIKE_f, npt.NDArray[np.floating[Any]])
+assert_type(AR_b // AR_LIKE_i, npt.NDArray[np.signedinteger])
+assert_type(AR_b // AR_LIKE_f, npt.NDArray[np.floating])
 assert_type(AR_b // AR_LIKE_O, Any)
 
 assert_type(AR_LIKE_b // AR_b, npt.NDArray[np.int8])
 assert_type(AR_LIKE_u // AR_b, npt.NDArray[np.uint32])
-assert_type(AR_LIKE_i // AR_b, npt.NDArray[np.signedinteger[Any]])
-assert_type(AR_LIKE_f // AR_b, npt.NDArray[np.floating[Any]])
+assert_type(AR_LIKE_i // AR_b, npt.NDArray[np.signedinteger])
+assert_type(AR_LIKE_f // AR_b, npt.NDArray[np.floating])
 assert_type(AR_LIKE_O // AR_b, Any)
 
 assert_type(AR_u // AR_LIKE_b, npt.NDArray[np.uint32])
-assert_type(AR_u // AR_LIKE_u, npt.NDArray[np.unsignedinteger[Any]])
-assert_type(AR_u // AR_LIKE_i, npt.NDArray[np.signedinteger[Any]])
-assert_type(AR_u // AR_LIKE_f, npt.NDArray[np.floating[Any]])
+assert_type(AR_u // AR_LIKE_u, npt.NDArray[np.unsignedinteger])
+assert_type(AR_u // AR_LIKE_i, npt.NDArray[np.signedinteger])
+assert_type(AR_u // AR_LIKE_f, npt.NDArray[np.floating])
 assert_type(AR_u // AR_LIKE_O, Any)
 
 assert_type(AR_LIKE_b // AR_u, npt.NDArray[np.uint32])
-assert_type(AR_LIKE_u // AR_u, npt.NDArray[np.unsignedinteger[Any]])
-assert_type(AR_LIKE_i // AR_u, npt.NDArray[np.signedinteger[Any]])
-assert_type(AR_LIKE_f // AR_u, npt.NDArray[np.floating[Any]])
+assert_type(AR_LIKE_u // AR_u, npt.NDArray[np.unsignedinteger])
+assert_type(AR_LIKE_i // AR_u, npt.NDArray[np.signedinteger])
+assert_type(AR_LIKE_f // AR_u, npt.NDArray[np.floating])
 assert_type(AR_LIKE_m // AR_u, npt.NDArray[np.timedelta64])
 assert_type(AR_LIKE_O // AR_u, Any)
 
 assert_type(AR_i // AR_LIKE_b, npt.NDArray[np.int64])
-assert_type(AR_i // AR_LIKE_u, npt.NDArray[np.signedinteger[Any]])
-assert_type(AR_i // AR_LIKE_i, npt.NDArray[np.signedinteger[Any]])
-assert_type(AR_i // AR_LIKE_f, npt.NDArray[np.floating[Any]])
+assert_type(AR_i // AR_LIKE_u, npt.NDArray[np.signedinteger])
+assert_type(AR_i // AR_LIKE_i, npt.NDArray[np.signedinteger])
+assert_type(AR_i // AR_LIKE_f, npt.NDArray[np.floating])
 assert_type(AR_i // AR_LIKE_O, Any)
 
 assert_type(AR_LIKE_b // AR_i, npt.NDArray[np.int64])
-assert_type(AR_LIKE_u // AR_i, npt.NDArray[np.signedinteger[Any]])
-assert_type(AR_LIKE_i // AR_i, npt.NDArray[np.signedinteger[Any]])
-assert_type(AR_LIKE_f // AR_i, npt.NDArray[np.floating[Any]])
+assert_type(AR_LIKE_u // AR_i, npt.NDArray[np.signedinteger])
+assert_type(AR_LIKE_i // AR_i, npt.NDArray[np.signedinteger])
+assert_type(AR_LIKE_f // AR_i, npt.NDArray[np.floating])
 assert_type(AR_LIKE_m // AR_i, npt.NDArray[np.timedelta64])
 assert_type(AR_LIKE_O // AR_i, Any)
 
diff --git a/numpy/typing/tests/data/reveal/array_constructors.pyi b/numpy/typing/tests/data/reveal/array_constructors.pyi
index c4099088a547..07610d982751 100644
--- a/numpy/typing/tests/data/reveal/array_constructors.pyi
+++ b/numpy/typing/tests/data/reveal/array_constructors.pyi
@@ -107,11 +107,11 @@ assert_type(np.frombuffer(A), npt.NDArray[np.float64])
 assert_type(np.frombuffer(A, dtype=np.int64), npt.NDArray[np.int64])
 assert_type(np.frombuffer(A, dtype="c16"), npt.NDArray[Any])
 
-assert_type(np.arange(False, True), np.ndarray[tuple[int], np.dtype[np.signedinteger[Any]]])
-assert_type(np.arange(10), np.ndarray[tuple[int], np.dtype[np.signedinteger[Any]]])
-assert_type(np.arange(0, 10, step=2), np.ndarray[tuple[int], np.dtype[np.signedinteger[Any]]])
-assert_type(np.arange(10.0), np.ndarray[tuple[int], np.dtype[np.floating[Any]]])
-assert_type(np.arange(start=0, stop=10.0), np.ndarray[tuple[int], np.dtype[np.floating[Any]]])
+assert_type(np.arange(False, True), np.ndarray[tuple[int], np.dtype[np.signedinteger]])
+assert_type(np.arange(10), np.ndarray[tuple[int], np.dtype[np.signedinteger]])
+assert_type(np.arange(0, 10, step=2), np.ndarray[tuple[int], np.dtype[np.signedinteger]])
+assert_type(np.arange(10.0), np.ndarray[tuple[int], np.dtype[np.floating]])
+assert_type(np.arange(start=0, stop=10.0), np.ndarray[tuple[int], np.dtype[np.floating]])
 assert_type(np.arange(np.timedelta64(0)), np.ndarray[tuple[int], np.dtype[np.timedelta64]])
 assert_type(np.arange(0, np.timedelta64(10)), np.ndarray[tuple[int], np.dtype[np.timedelta64]])
 assert_type(np.arange(np.datetime64("0"), np.datetime64("10")), np.ndarray[tuple[int], np.dtype[np.datetime64]])
@@ -132,22 +132,22 @@ assert_type(np.require(B, requirements="W"), SubClass[np.float64])
 assert_type(np.require(B, requirements="A"), SubClass[np.float64])
 assert_type(np.require(C), npt.NDArray[Any])
 
-assert_type(np.linspace(0, 10), npt.NDArray[np.floating[Any]])
-assert_type(np.linspace(0, 10j), npt.NDArray[np.complexfloating[Any, Any]])
+assert_type(np.linspace(0, 10), npt.NDArray[np.floating])
+assert_type(np.linspace(0, 10j), npt.NDArray[np.complexfloating])
 assert_type(np.linspace(0, 10, dtype=np.int64), npt.NDArray[np.int64])
 assert_type(np.linspace(0, 10, dtype=int), npt.NDArray[Any])
-assert_type(np.linspace(0, 10, retstep=True), tuple[npt.NDArray[np.floating[Any]], np.floating[Any]])
-assert_type(np.linspace(0j, 10, retstep=True), tuple[npt.NDArray[np.complexfloating[Any, Any]], np.complexfloating[Any, Any]])
+assert_type(np.linspace(0, 10, retstep=True), tuple[npt.NDArray[np.floating], np.floating])
+assert_type(np.linspace(0j, 10, retstep=True), tuple[npt.NDArray[np.complexfloating], np.complexfloating])
 assert_type(np.linspace(0, 10, retstep=True, dtype=np.int64), tuple[npt.NDArray[np.int64], np.int64])
 assert_type(np.linspace(0j, 10, retstep=True, dtype=int), tuple[npt.NDArray[Any], Any])
 
-assert_type(np.logspace(0, 10), npt.NDArray[np.floating[Any]])
-assert_type(np.logspace(0, 10j), npt.NDArray[np.complexfloating[Any, Any]])
+assert_type(np.logspace(0, 10), npt.NDArray[np.floating])
+assert_type(np.logspace(0, 10j), npt.NDArray[np.complexfloating])
 assert_type(np.logspace(0, 10, dtype=np.int64), npt.NDArray[np.int64])
 assert_type(np.logspace(0, 10, dtype=int), npt.NDArray[Any])
 
-assert_type(np.geomspace(0, 10), npt.NDArray[np.floating[Any]])
-assert_type(np.geomspace(0, 10j), npt.NDArray[np.complexfloating[Any, Any]])
+assert_type(np.geomspace(0, 10), npt.NDArray[np.floating])
+assert_type(np.geomspace(0, 10j), npt.NDArray[np.complexfloating])
 assert_type(np.geomspace(0, 10, dtype=np.int64), npt.NDArray[np.int64])
 assert_type(np.geomspace(0, 10, dtype=int), npt.NDArray[Any])
 
diff --git a/numpy/typing/tests/data/reveal/arraypad.pyi b/numpy/typing/tests/data/reveal/arraypad.pyi
index 377a85408fda..c5a443d93fe3 100644
--- a/numpy/typing/tests/data/reveal/arraypad.pyi
+++ b/numpy/typing/tests/data/reveal/arraypad.pyi
@@ -5,7 +5,7 @@ import numpy as np
 import numpy.typing as npt
 
 def mode_func(
-    ar: npt.NDArray[np.number[Any]],
+    ar: npt.NDArray[np.number],
     width: tuple[int, int],
     iaxis: SupportsIndex,
     kwargs: Mapping[str, Any],
diff --git a/numpy/typing/tests/data/reveal/arrayprint.pyi b/numpy/typing/tests/data/reveal/arrayprint.pyi
index 3c40f8680884..3b339edced32 100644
--- a/numpy/typing/tests/data/reveal/arrayprint.pyi
+++ b/numpy/typing/tests/data/reveal/arrayprint.pyi
@@ -7,8 +7,8 @@ import numpy.typing as npt
 from numpy._core.arrayprint import _FormatOptions
 
 AR: npt.NDArray[np.int64]
-func_float: Callable[[np.floating[Any]], str]
-func_int: Callable[[np.integer[Any]], str]
+func_float: Callable[[np.floating], str]
+func_int: Callable[[np.integer], str]
 
 assert_type(np.get_printoptions(), _FormatOptions)
 assert_type(
diff --git a/numpy/typing/tests/data/reveal/bitwise_ops.pyi b/numpy/typing/tests/data/reveal/bitwise_ops.pyi
index ba3847b95d8d..6c6b56197546 100644
--- a/numpy/typing/tests/data/reveal/bitwise_ops.pyi
+++ b/numpy/typing/tests/data/reveal/bitwise_ops.pyi
@@ -32,11 +32,11 @@ assert_type(i8 | i8, np.int64)
 assert_type(i8 ^ i8, np.int64)
 assert_type(i8 & i8, np.int64)
 
-assert_type(i8 << AR, npt.NDArray[np.signedinteger[Any]])
-assert_type(i8 >> AR, npt.NDArray[np.signedinteger[Any]])
-assert_type(i8 | AR, npt.NDArray[np.signedinteger[Any]])
-assert_type(i8 ^ AR, npt.NDArray[np.signedinteger[Any]])
-assert_type(i8 & AR, npt.NDArray[np.signedinteger[Any]])
+assert_type(i8 << AR, npt.NDArray[np.signedinteger])
+assert_type(i8 >> AR, npt.NDArray[np.signedinteger])
+assert_type(i8 | AR, npt.NDArray[np.signedinteger])
+assert_type(i8 ^ AR, npt.NDArray[np.signedinteger])
+assert_type(i8 & AR, npt.NDArray[np.signedinteger])
 
 assert_type(i4 << i4, np.int32)
 assert_type(i4 >> i4, np.int32)
@@ -68,11 +68,11 @@ assert_type(u8 | u8, np.uint64)
 assert_type(u8 ^ u8, np.uint64)
 assert_type(u8 & u8, np.uint64)
 
-assert_type(u8 << AR, npt.NDArray[np.signedinteger[Any]])
-assert_type(u8 >> AR, npt.NDArray[np.signedinteger[Any]])
-assert_type(u8 | AR, npt.NDArray[np.signedinteger[Any]])
-assert_type(u8 ^ AR, npt.NDArray[np.signedinteger[Any]])
-assert_type(u8 & AR, npt.NDArray[np.signedinteger[Any]])
+assert_type(u8 << AR, npt.NDArray[np.signedinteger])
+assert_type(u8 >> AR, npt.NDArray[np.signedinteger])
+assert_type(u8 | AR, npt.NDArray[np.signedinteger])
+assert_type(u8 ^ AR, npt.NDArray[np.signedinteger])
+assert_type(u8 & AR, npt.NDArray[np.signedinteger])
 
 assert_type(u4 << u4, np.uint32)
 assert_type(u4 >> u4, np.uint32)
@@ -80,17 +80,17 @@ assert_type(u4 | u4, np.uint32)
 assert_type(u4 ^ u4, np.uint32)
 assert_type(u4 & u4, np.uint32)
 
-assert_type(u4 << i4, np.signedinteger[Any])
-assert_type(u4 >> i4, np.signedinteger[Any])
-assert_type(u4 | i4, np.signedinteger[Any])
-assert_type(u4 ^ i4, np.signedinteger[Any])
-assert_type(u4 & i4, np.signedinteger[Any])
+assert_type(u4 << i4, np.signedinteger)
+assert_type(u4 >> i4, np.signedinteger)
+assert_type(u4 | i4, np.signedinteger)
+assert_type(u4 ^ i4, np.signedinteger)
+assert_type(u4 & i4, np.signedinteger)
 
-assert_type(u4 << i, np.signedinteger[Any])
-assert_type(u4 >> i, np.signedinteger[Any])
-assert_type(u4 | i, np.signedinteger[Any])
-assert_type(u4 ^ i, np.signedinteger[Any])
-assert_type(u4 & i, np.signedinteger[Any])
+assert_type(u4 << i, np.signedinteger)
+assert_type(u4 >> i, np.signedinteger)
+assert_type(u4 | i, np.signedinteger)
+assert_type(u4 ^ i, np.signedinteger)
+assert_type(u4 & i, np.signedinteger)
 
 assert_type(u8 << b_, np.uint64)
 assert_type(u8 >> b_, np.uint64)
@@ -110,11 +110,11 @@ assert_type(b_ | b_, np.bool)
 assert_type(b_ ^ b_, np.bool)
 assert_type(b_ & b_, np.bool)
 
-assert_type(b_ << AR, npt.NDArray[np.signedinteger[Any]])
-assert_type(b_ >> AR, npt.NDArray[np.signedinteger[Any]])
-assert_type(b_ | AR, npt.NDArray[np.signedinteger[Any]])
-assert_type(b_ ^ AR, npt.NDArray[np.signedinteger[Any]])
-assert_type(b_ & AR, npt.NDArray[np.signedinteger[Any]])
+assert_type(b_ << AR, npt.NDArray[np.signedinteger])
+assert_type(b_ >> AR, npt.NDArray[np.signedinteger])
+assert_type(b_ | AR, npt.NDArray[np.signedinteger])
+assert_type(b_ ^ AR, npt.NDArray[np.signedinteger])
+assert_type(b_ & AR, npt.NDArray[np.signedinteger])
 
 assert_type(b_ << b, np.int8)
 assert_type(b_ >> b, np.int8)
diff --git a/numpy/typing/tests/data/reveal/dtype.pyi b/numpy/typing/tests/data/reveal/dtype.pyi
index 04c1a7090b95..6533aca20d9b 100644
--- a/numpy/typing/tests/data/reveal/dtype.pyi
+++ b/numpy/typing/tests/data/reveal/dtype.pyi
@@ -30,7 +30,7 @@ cs_number: Literal["=L", "i", "c16"]
 cs_flex: Literal[">V", "S"]
 cs_generic: Literal["H", "U", "h", "|M8[Y]", "?"]
 
-dt_inexact: np.dtype[np.inexact[Any]]
+dt_inexact: np.dtype[np.inexact]
 dt_string: StringDType
 
 assert_type(np.dtype(np.float64), np.dtype[np.float64])
@@ -74,8 +74,8 @@ assert_type(np.dtype("u1"), np.dtype[np.uint8])
 assert_type(np.dtype("l"), np.dtype[np.long])
 assert_type(np.dtype("longlong"), np.dtype[np.longlong])
 assert_type(np.dtype(">g"), np.dtype[np.longdouble])
-assert_type(np.dtype(cs_integer), np.dtype[np.integer[Any]])
-assert_type(np.dtype(cs_number), np.dtype[np.number[Any]])
+assert_type(np.dtype(cs_integer), np.dtype[np.integer])
+assert_type(np.dtype(cs_number), np.dtype[np.number])
 assert_type(np.dtype(cs_flex), np.dtype[np.flexible])
 assert_type(np.dtype(cs_generic), np.dtype[np.generic])
 
@@ -92,7 +92,7 @@ assert_type(np.dtype(None), np.dtype[np.float64])
 
 # Dypes of dtypes
 assert_type(np.dtype(np.dtype(np.float64)), np.dtype[np.float64])
-assert_type(np.dtype(dt_inexact), np.dtype[np.inexact[Any]])
+assert_type(np.dtype(dt_inexact), np.dtype[np.inexact])
 
 # Parameterized dtypes
 assert_type(np.dtype("S8"), np.dtype)
diff --git a/numpy/typing/tests/data/reveal/emath.pyi b/numpy/typing/tests/data/reveal/emath.pyi
index e8f173e85dea..1d7bff893e73 100644
--- a/numpy/typing/tests/data/reveal/emath.pyi
+++ b/numpy/typing/tests/data/reveal/emath.pyi
@@ -10,45 +10,45 @@ c16: np.complex128
 
 assert_type(np.emath.sqrt(f8), Any)
 assert_type(np.emath.sqrt(AR_f8), npt.NDArray[Any])
-assert_type(np.emath.sqrt(c16), np.complexfloating[Any, Any])
-assert_type(np.emath.sqrt(AR_c16), npt.NDArray[np.complexfloating[Any, Any]])
+assert_type(np.emath.sqrt(c16), np.complexfloating)
+assert_type(np.emath.sqrt(AR_c16), npt.NDArray[np.complexfloating])
 
 assert_type(np.emath.log(f8), Any)
 assert_type(np.emath.log(AR_f8), npt.NDArray[Any])
-assert_type(np.emath.log(c16), np.complexfloating[Any, Any])
-assert_type(np.emath.log(AR_c16), npt.NDArray[np.complexfloating[Any, Any]])
+assert_type(np.emath.log(c16), np.complexfloating)
+assert_type(np.emath.log(AR_c16), npt.NDArray[np.complexfloating])
 
 assert_type(np.emath.log10(f8), Any)
 assert_type(np.emath.log10(AR_f8), npt.NDArray[Any])
-assert_type(np.emath.log10(c16), np.complexfloating[Any, Any])
-assert_type(np.emath.log10(AR_c16), npt.NDArray[np.complexfloating[Any, Any]])
+assert_type(np.emath.log10(c16), np.complexfloating)
+assert_type(np.emath.log10(AR_c16), npt.NDArray[np.complexfloating])
 
 assert_type(np.emath.log2(f8), Any)
 assert_type(np.emath.log2(AR_f8), npt.NDArray[Any])
-assert_type(np.emath.log2(c16), np.complexfloating[Any, Any])
-assert_type(np.emath.log2(AR_c16), npt.NDArray[np.complexfloating[Any, Any]])
+assert_type(np.emath.log2(c16), np.complexfloating)
+assert_type(np.emath.log2(AR_c16), npt.NDArray[np.complexfloating])
 
 assert_type(np.emath.logn(f8, 2), Any)
 assert_type(np.emath.logn(AR_f8, 4), npt.NDArray[Any])
-assert_type(np.emath.logn(f8, 1j), np.complexfloating[Any, Any])
-assert_type(np.emath.logn(AR_c16, 1.5), npt.NDArray[np.complexfloating[Any, Any]])
+assert_type(np.emath.logn(f8, 1j), np.complexfloating)
+assert_type(np.emath.logn(AR_c16, 1.5), npt.NDArray[np.complexfloating])
 
 assert_type(np.emath.power(f8, 2), Any)
 assert_type(np.emath.power(AR_f8, 4), npt.NDArray[Any])
-assert_type(np.emath.power(f8, 2j), np.complexfloating[Any, Any])
-assert_type(np.emath.power(AR_c16, 1.5), npt.NDArray[np.complexfloating[Any, Any]])
+assert_type(np.emath.power(f8, 2j), np.complexfloating)
+assert_type(np.emath.power(AR_c16, 1.5), npt.NDArray[np.complexfloating])
 
 assert_type(np.emath.arccos(f8), Any)
 assert_type(np.emath.arccos(AR_f8), npt.NDArray[Any])
-assert_type(np.emath.arccos(c16), np.complexfloating[Any, Any])
-assert_type(np.emath.arccos(AR_c16), npt.NDArray[np.complexfloating[Any, Any]])
+assert_type(np.emath.arccos(c16), np.complexfloating)
+assert_type(np.emath.arccos(AR_c16), npt.NDArray[np.complexfloating])
 
 assert_type(np.emath.arcsin(f8), Any)
 assert_type(np.emath.arcsin(AR_f8), npt.NDArray[Any])
-assert_type(np.emath.arcsin(c16), np.complexfloating[Any, Any])
-assert_type(np.emath.arcsin(AR_c16), npt.NDArray[np.complexfloating[Any, Any]])
+assert_type(np.emath.arcsin(c16), np.complexfloating)
+assert_type(np.emath.arcsin(AR_c16), npt.NDArray[np.complexfloating])
 
 assert_type(np.emath.arctanh(f8), Any)
 assert_type(np.emath.arctanh(AR_f8), npt.NDArray[Any])
-assert_type(np.emath.arctanh(c16), np.complexfloating[Any, Any])
-assert_type(np.emath.arctanh(AR_c16), npt.NDArray[np.complexfloating[Any, Any]])
+assert_type(np.emath.arctanh(c16), np.complexfloating)
+assert_type(np.emath.arctanh(AR_c16), npt.NDArray[np.complexfloating])
diff --git a/numpy/typing/tests/data/reveal/fft.pyi b/numpy/typing/tests/data/reveal/fft.pyi
index 147326e620d1..dacd2b89777c 100644
--- a/numpy/typing/tests/data/reveal/fft.pyi
+++ b/numpy/typing/tests/data/reveal/fft.pyi
@@ -13,11 +13,11 @@ assert_type(np.fft.fftshift(AR_LIKE_f8, axes=0), npt.NDArray[Any])
 assert_type(np.fft.ifftshift(AR_f8), npt.NDArray[np.float64])
 assert_type(np.fft.ifftshift(AR_LIKE_f8, axes=0), npt.NDArray[Any])
 
-assert_type(np.fft.fftfreq(5, AR_f8), npt.NDArray[np.floating[Any]])
-assert_type(np.fft.fftfreq(np.int64(), AR_c16), npt.NDArray[np.complexfloating[Any, Any]])
+assert_type(np.fft.fftfreq(5, AR_f8), npt.NDArray[np.floating])
+assert_type(np.fft.fftfreq(np.int64(), AR_c16), npt.NDArray[np.complexfloating])
 
-assert_type(np.fft.fftfreq(5, AR_f8), npt.NDArray[np.floating[Any]])
-assert_type(np.fft.fftfreq(np.int64(), AR_c16), npt.NDArray[np.complexfloating[Any, Any]])
+assert_type(np.fft.fftfreq(5, AR_f8), npt.NDArray[np.floating])
+assert_type(np.fft.fftfreq(np.int64(), AR_c16), npt.NDArray[np.complexfloating])
 
 assert_type(np.fft.fft(AR_f8), npt.NDArray[np.complex128])
 assert_type(np.fft.ifft(AR_f8, axis=1), npt.NDArray[np.complex128])
diff --git a/numpy/typing/tests/data/reveal/fromnumeric.pyi b/numpy/typing/tests/data/reveal/fromnumeric.pyi
index 71d06e4b76e4..ee761a2762b7 100644
--- a/numpy/typing/tests/data/reveal/fromnumeric.pyi
+++ b/numpy/typing/tests/data/reveal/fromnumeric.pyi
@@ -247,8 +247,8 @@ assert_type(np.amin(AR_f4, out=AR_subclass), NDArraySubclass)
 assert_type(np.prod(AR_b), np.int_)
 assert_type(np.prod(AR_u8), np.uint64)
 assert_type(np.prod(AR_i8), np.int64)
-assert_type(np.prod(AR_f4), np.floating[Any])
-assert_type(np.prod(AR_c16), np.complexfloating[Any, Any])
+assert_type(np.prod(AR_f4), np.floating)
+assert_type(np.prod(AR_c16), np.complexfloating)
 assert_type(np.prod(AR_O), Any)
 assert_type(np.prod(AR_f4, axis=0), Any)
 assert_type(np.prod(AR_f4, keepdims=True), Any)
@@ -259,10 +259,10 @@ assert_type(np.prod(AR_f4, out=AR_subclass), NDArraySubclass)
 assert_type(np.cumprod(AR_b), npt.NDArray[np.int_])
 assert_type(np.cumprod(AR_u8), npt.NDArray[np.uint64])
 assert_type(np.cumprod(AR_i8), npt.NDArray[np.int64])
-assert_type(np.cumprod(AR_f4), npt.NDArray[np.floating[Any]])
-assert_type(np.cumprod(AR_c16), npt.NDArray[np.complexfloating[Any, Any]])
+assert_type(np.cumprod(AR_f4), npt.NDArray[np.floating])
+assert_type(np.cumprod(AR_c16), npt.NDArray[np.complexfloating])
 assert_type(np.cumprod(AR_O), npt.NDArray[np.object_])
-assert_type(np.cumprod(AR_f4, axis=0), npt.NDArray[np.floating[Any]])
+assert_type(np.cumprod(AR_f4, axis=0), npt.NDArray[np.floating])
 assert_type(np.cumprod(AR_f4, dtype=np.float64), npt.NDArray[np.float64])
 assert_type(np.cumprod(AR_f4, dtype=float), npt.NDArray[Any])
 assert_type(np.cumprod(AR_f4, out=AR_subclass), NDArraySubclass)
@@ -270,10 +270,10 @@ assert_type(np.cumprod(AR_f4, out=AR_subclass), NDArraySubclass)
 assert_type(np.cumulative_prod(AR_b), npt.NDArray[np.int_])
 assert_type(np.cumulative_prod(AR_u8), npt.NDArray[np.uint64])
 assert_type(np.cumulative_prod(AR_i8), npt.NDArray[np.int64])
-assert_type(np.cumulative_prod(AR_f4), npt.NDArray[np.floating[Any]])
-assert_type(np.cumulative_prod(AR_c16), npt.NDArray[np.complexfloating[Any, Any]])
+assert_type(np.cumulative_prod(AR_f4), npt.NDArray[np.floating])
+assert_type(np.cumulative_prod(AR_c16), npt.NDArray[np.complexfloating])
 assert_type(np.cumulative_prod(AR_O), npt.NDArray[np.object_])
-assert_type(np.cumulative_prod(AR_f4, axis=0), npt.NDArray[np.floating[Any]])
+assert_type(np.cumulative_prod(AR_f4, axis=0), npt.NDArray[np.floating])
 assert_type(np.cumulative_prod(AR_f4, dtype=np.float64), npt.NDArray[np.float64])
 assert_type(np.cumulative_prod(AR_f4, dtype=float), npt.NDArray[Any])
 assert_type(np.cumulative_prod(AR_f4, out=AR_subclass), NDArraySubclass)
@@ -300,11 +300,11 @@ assert_type(np.around(AR_f4), npt.NDArray[np.float32])
 assert_type(np.around([1.5]), npt.NDArray[Any])
 assert_type(np.around(AR_f4, out=AR_subclass), NDArraySubclass)
 
-assert_type(np.mean(AR_b), np.floating[Any])
-assert_type(np.mean(AR_i8), np.floating[Any])
-assert_type(np.mean(AR_f4), np.floating[Any])
+assert_type(np.mean(AR_b), np.floating)
+assert_type(np.mean(AR_i8), np.floating)
+assert_type(np.mean(AR_f4), np.floating)
 assert_type(np.mean(AR_m), np.timedelta64)
-assert_type(np.mean(AR_c16), np.complexfloating[Any, Any])
+assert_type(np.mean(AR_c16), np.complexfloating)
 assert_type(np.mean(AR_O), Any)
 assert_type(np.mean(AR_f4, axis=0), Any)
 assert_type(np.mean(AR_f4, keepdims=True), Any)
@@ -318,10 +318,10 @@ assert_type(np.mean(AR_f4, None, np.float64, keepdims=False), np.float64)
 assert_type(np.mean(AR_f4, dtype=np.float64, keepdims=True), np.float64 | npt.NDArray[np.float64])
 assert_type(np.mean(AR_f4, None, np.float64, keepdims=True), np.float64 | npt.NDArray[np.float64])
 
-assert_type(np.std(AR_b), np.floating[Any])
-assert_type(np.std(AR_i8), np.floating[Any])
-assert_type(np.std(AR_f4), np.floating[Any])
-assert_type(np.std(AR_c16), np.floating[Any])
+assert_type(np.std(AR_b), np.floating)
+assert_type(np.std(AR_i8), np.floating)
+assert_type(np.std(AR_f4), np.floating)
+assert_type(np.std(AR_c16), np.floating)
 assert_type(np.std(AR_O), Any)
 assert_type(np.std(AR_f4, axis=0), Any)
 assert_type(np.std(AR_f4, keepdims=True), Any)
@@ -329,10 +329,10 @@ assert_type(np.std(AR_f4, dtype=float), Any)
 assert_type(np.std(AR_f4, dtype=np.float64), np.float64)
 assert_type(np.std(AR_f4, out=AR_subclass), NDArraySubclass)
 
-assert_type(np.var(AR_b), np.floating[Any])
-assert_type(np.var(AR_i8), np.floating[Any])
-assert_type(np.var(AR_f4), np.floating[Any])
-assert_type(np.var(AR_c16), np.floating[Any])
+assert_type(np.var(AR_b), np.floating)
+assert_type(np.var(AR_i8), np.floating)
+assert_type(np.var(AR_f4), np.floating)
+assert_type(np.var(AR_c16), np.floating)
 assert_type(np.var(AR_O), Any)
 assert_type(np.var(AR_f4, axis=0), Any)
 assert_type(np.var(AR_f4, keepdims=True), Any)
diff --git a/numpy/typing/tests/data/reveal/getlimits.pyi b/numpy/typing/tests/data/reveal/getlimits.pyi
index 314a93d83342..825daba43064 100644
--- a/numpy/typing/tests/data/reveal/getlimits.pyi
+++ b/numpy/typing/tests/data/reveal/getlimits.pyi
@@ -17,7 +17,7 @@ iinfo_i8: np.iinfo[np.int64]
 assert_type(np.finfo(f), np.finfo[np.float64])
 assert_type(np.finfo(f8), np.finfo[np.floating[_64Bit]])
 assert_type(np.finfo(c8), np.finfo[np.float32])
-assert_type(np.finfo('f2'), np.finfo[np.floating[Any]])
+assert_type(np.finfo('f2'), np.finfo[np.floating])
 
 assert_type(finfo_f8.dtype, np.dtype[np.float64])
 assert_type(finfo_f8.bits, int)
diff --git a/numpy/typing/tests/data/reveal/lib_function_base.pyi b/numpy/typing/tests/data/reveal/lib_function_base.pyi
index 4b76f891f23d..bb54d6913b34 100644
--- a/numpy/typing/tests/data/reveal/lib_function_base.pyi
+++ b/numpy/typing/tests/data/reveal/lib_function_base.pyi
@@ -57,11 +57,11 @@ assert_type(np.flip(AR_LIKE_f8, axis=0), npt.NDArray[Any])
 assert_type(np.iterable(1), bool)
 assert_type(np.iterable([1]), bool)
 
-assert_type(np.average(AR_f8), np.floating[Any])
-assert_type(np.average(AR_f8, weights=AR_c16), np.complexfloating[Any, Any])
+assert_type(np.average(AR_f8), np.floating)
+assert_type(np.average(AR_f8, weights=AR_c16), np.complexfloating)
 assert_type(np.average(AR_O), Any)
-assert_type(np.average(AR_f8, returned=True), tuple[np.floating[Any], np.floating[Any]])
-assert_type(np.average(AR_f8, weights=AR_c16, returned=True), tuple[np.complexfloating[Any, Any], np.complexfloating[Any, Any]])
+assert_type(np.average(AR_f8, returned=True), tuple[np.floating, np.floating])
+assert_type(np.average(AR_f8, weights=AR_c16, returned=True), tuple[np.complexfloating, np.complexfloating])
 assert_type(np.average(AR_O, returned=True), tuple[Any, Any])
 assert_type(np.average(AR_f8, axis=0), Any)
 assert_type(np.average(AR_f8, axis=0, returned=True), tuple[Any, Any])
@@ -101,15 +101,15 @@ assert_type(np.interp([1], [1], [1]), npt.NDArray[np.float64])
 assert_type(np.interp([1], [1], AR_c16), npt.NDArray[np.complex128])
 assert_type(np.interp([1], [1], [1j]), npt.NDArray[np.complex128])  # pyright correctly infers `NDArray[complex128 | float64]`
 
-assert_type(np.angle(f8), np.floating[Any])
-assert_type(np.angle(AR_f8), npt.NDArray[np.floating[Any]])
-assert_type(np.angle(AR_c16, deg=True), npt.NDArray[np.floating[Any]])
+assert_type(np.angle(f8), np.floating)
+assert_type(np.angle(AR_f8), npt.NDArray[np.floating])
+assert_type(np.angle(AR_c16, deg=True), npt.NDArray[np.floating])
 assert_type(np.angle(AR_O), npt.NDArray[np.object_])
 
-assert_type(np.unwrap(AR_f8), npt.NDArray[np.floating[Any]])
+assert_type(np.unwrap(AR_f8), npt.NDArray[np.floating])
 assert_type(np.unwrap(AR_O), npt.NDArray[np.object_])
 
-assert_type(np.sort_complex(AR_f8), npt.NDArray[np.complexfloating[Any, Any]])
+assert_type(np.sort_complex(AR_f8), npt.NDArray[np.complexfloating])
 
 assert_type(np.trim_zeros(AR_f8), npt.NDArray[np.float64])
 assert_type(np.trim_zeros(AR_LIKE_f8), list[float])
@@ -119,43 +119,43 @@ assert_type(np.extract(AR_i8, AR_LIKE_f8), npt.NDArray[Any])
 
 assert_type(np.place(AR_f8, mask=AR_i8, vals=5.0), None)
 
-assert_type(np.cov(AR_f8, bias=True), npt.NDArray[np.floating[Any]])
-assert_type(np.cov(AR_f8, AR_c16, ddof=1), npt.NDArray[np.complexfloating[Any, Any]])
+assert_type(np.cov(AR_f8, bias=True), npt.NDArray[np.floating])
+assert_type(np.cov(AR_f8, AR_c16, ddof=1), npt.NDArray[np.complexfloating])
 assert_type(np.cov(AR_f8, aweights=AR_f8, dtype=np.float32), npt.NDArray[np.float32])
 assert_type(np.cov(AR_f8, fweights=AR_f8, dtype=float), npt.NDArray[Any])
 
-assert_type(np.corrcoef(AR_f8, rowvar=True), npt.NDArray[np.floating[Any]])
-assert_type(np.corrcoef(AR_f8, AR_c16), npt.NDArray[np.complexfloating[Any, Any]])
+assert_type(np.corrcoef(AR_f8, rowvar=True), npt.NDArray[np.floating])
+assert_type(np.corrcoef(AR_f8, AR_c16), npt.NDArray[np.complexfloating])
 assert_type(np.corrcoef(AR_f8, dtype=np.float32), npt.NDArray[np.float32])
 assert_type(np.corrcoef(AR_f8, dtype=float), npt.NDArray[Any])
 
-assert_type(np.blackman(5), npt.NDArray[np.floating[Any]])
-assert_type(np.bartlett(6), npt.NDArray[np.floating[Any]])
-assert_type(np.hanning(4.5), npt.NDArray[np.floating[Any]])
-assert_type(np.hamming(0), npt.NDArray[np.floating[Any]])
-assert_type(np.i0(AR_i8), npt.NDArray[np.floating[Any]])
-assert_type(np.kaiser(4, 5.9), npt.NDArray[np.floating[Any]])
+assert_type(np.blackman(5), npt.NDArray[np.floating])
+assert_type(np.bartlett(6), npt.NDArray[np.floating])
+assert_type(np.hanning(4.5), npt.NDArray[np.floating])
+assert_type(np.hamming(0), npt.NDArray[np.floating])
+assert_type(np.i0(AR_i8), npt.NDArray[np.floating])
+assert_type(np.kaiser(4, 5.9), npt.NDArray[np.floating])
 
-assert_type(np.sinc(1.0), np.floating[Any])
-assert_type(np.sinc(1j), np.complexfloating[Any, Any])
-assert_type(np.sinc(AR_f8), npt.NDArray[np.floating[Any]])
-assert_type(np.sinc(AR_c16), npt.NDArray[np.complexfloating[Any, Any]])
+assert_type(np.sinc(1.0), np.floating)
+assert_type(np.sinc(1j), np.complexfloating)
+assert_type(np.sinc(AR_f8), npt.NDArray[np.floating])
+assert_type(np.sinc(AR_c16), npt.NDArray[np.complexfloating])
 
-assert_type(np.median(AR_f8, keepdims=False), np.floating[Any])
-assert_type(np.median(AR_c16, overwrite_input=True), np.complexfloating[Any, Any])
+assert_type(np.median(AR_f8, keepdims=False), np.floating)
+assert_type(np.median(AR_c16, overwrite_input=True), np.complexfloating)
 assert_type(np.median(AR_m), np.timedelta64)
 assert_type(np.median(AR_O), Any)
 assert_type(np.median(AR_f8, keepdims=True), Any)
 assert_type(np.median(AR_c16, axis=0), Any)
 assert_type(np.median(AR_LIKE_f8, out=AR_c16), npt.NDArray[np.complex128])
 
-assert_type(np.percentile(AR_f8, 50), np.floating[Any])
-assert_type(np.percentile(AR_c16, 50), np.complexfloating[Any, Any])
+assert_type(np.percentile(AR_f8, 50), np.floating)
+assert_type(np.percentile(AR_c16, 50), np.complexfloating)
 assert_type(np.percentile(AR_m, 50), np.timedelta64)
 assert_type(np.percentile(AR_M, 50, overwrite_input=True), np.datetime64)
 assert_type(np.percentile(AR_O, 50), Any)
-assert_type(np.percentile(AR_f8, [50]), npt.NDArray[np.floating[Any]])
-assert_type(np.percentile(AR_c16, [50]), npt.NDArray[np.complexfloating[Any, Any]])
+assert_type(np.percentile(AR_f8, [50]), npt.NDArray[np.floating])
+assert_type(np.percentile(AR_c16, [50]), npt.NDArray[np.complexfloating])
 assert_type(np.percentile(AR_m, [50]), npt.NDArray[np.timedelta64])
 assert_type(np.percentile(AR_M, [50], method="nearest"), npt.NDArray[np.datetime64])
 assert_type(np.percentile(AR_O, [50]), npt.NDArray[np.object_])
@@ -163,13 +163,13 @@ assert_type(np.percentile(AR_f8, [50], keepdims=True), Any)
 assert_type(np.percentile(AR_f8, [50], axis=[1]), Any)
 assert_type(np.percentile(AR_f8, [50], out=AR_c16), npt.NDArray[np.complex128])
 
-assert_type(np.quantile(AR_f8, 0.5), np.floating[Any])
-assert_type(np.quantile(AR_c16, 0.5), np.complexfloating[Any, Any])
+assert_type(np.quantile(AR_f8, 0.5), np.floating)
+assert_type(np.quantile(AR_c16, 0.5), np.complexfloating)
 assert_type(np.quantile(AR_m, 0.5), np.timedelta64)
 assert_type(np.quantile(AR_M, 0.5, overwrite_input=True), np.datetime64)
 assert_type(np.quantile(AR_O, 0.5), Any)
-assert_type(np.quantile(AR_f8, [0.5]), npt.NDArray[np.floating[Any]])
-assert_type(np.quantile(AR_c16, [0.5]), npt.NDArray[np.complexfloating[Any, Any]])
+assert_type(np.quantile(AR_f8, [0.5]), npt.NDArray[np.floating])
+assert_type(np.quantile(AR_c16, [0.5]), npt.NDArray[np.complexfloating])
 assert_type(np.quantile(AR_m, [0.5]), npt.NDArray[np.timedelta64])
 assert_type(np.quantile(AR_M, [0.5], method="nearest"), npt.NDArray[np.datetime64])
 assert_type(np.quantile(AR_O, [0.5]), npt.NDArray[np.object_])
diff --git a/numpy/typing/tests/data/reveal/lib_polynomial.pyi b/numpy/typing/tests/data/reveal/lib_polynomial.pyi
index 390a72d56d12..8b0a9f3d22e7 100644
--- a/numpy/typing/tests/data/reveal/lib_polynomial.pyi
+++ b/numpy/typing/tests/data/reveal/lib_polynomial.pyi
@@ -49,18 +49,18 @@ assert_type(iter(poly_obj), Iterator[Any])
 assert_type(poly_obj.deriv(), np.poly1d)
 assert_type(poly_obj.integ(), np.poly1d)
 
-assert_type(np.poly(poly_obj), npt.NDArray[np.floating[Any]])
-assert_type(np.poly(AR_f8), npt.NDArray[np.floating[Any]])
-assert_type(np.poly(AR_c16), npt.NDArray[np.floating[Any]])
+assert_type(np.poly(poly_obj), npt.NDArray[np.floating])
+assert_type(np.poly(AR_f8), npt.NDArray[np.floating])
+assert_type(np.poly(AR_c16), npt.NDArray[np.floating])
 
 assert_type(np.polyint(poly_obj), np.poly1d)
-assert_type(np.polyint(AR_f8), npt.NDArray[np.floating[Any]])
-assert_type(np.polyint(AR_f8, k=AR_c16), npt.NDArray[np.complexfloating[Any, Any]])
+assert_type(np.polyint(AR_f8), npt.NDArray[np.floating])
+assert_type(np.polyint(AR_f8, k=AR_c16), npt.NDArray[np.complexfloating])
 assert_type(np.polyint(AR_O, m=2), npt.NDArray[np.object_])
 
 assert_type(np.polyder(poly_obj), np.poly1d)
-assert_type(np.polyder(AR_f8), npt.NDArray[np.floating[Any]])
-assert_type(np.polyder(AR_c16), npt.NDArray[np.complexfloating[Any, Any]])
+assert_type(np.polyder(AR_f8), npt.NDArray[np.floating])
+assert_type(np.polyder(AR_c16), npt.NDArray[np.complexfloating])
 assert_type(np.polyder(AR_O, m=2), npt.NDArray[np.object_])
 
 assert_type(np.polyfit(AR_f8, AR_f8, 2), npt.NDArray[np.float64])
@@ -101,44 +101,44 @@ assert_type(
 )
 
 assert_type(np.polyval(AR_b, AR_b), npt.NDArray[np.int64])
-assert_type(np.polyval(AR_u4, AR_b), npt.NDArray[np.unsignedinteger[Any]])
-assert_type(np.polyval(AR_i8, AR_i8), npt.NDArray[np.signedinteger[Any]])
-assert_type(np.polyval(AR_f8, AR_i8), npt.NDArray[np.floating[Any]])
-assert_type(np.polyval(AR_i8, AR_c16), npt.NDArray[np.complexfloating[Any, Any]])
+assert_type(np.polyval(AR_u4, AR_b), npt.NDArray[np.unsignedinteger])
+assert_type(np.polyval(AR_i8, AR_i8), npt.NDArray[np.signedinteger])
+assert_type(np.polyval(AR_f8, AR_i8), npt.NDArray[np.floating])
+assert_type(np.polyval(AR_i8, AR_c16), npt.NDArray[np.complexfloating])
 assert_type(np.polyval(AR_O, AR_O), npt.NDArray[np.object_])
 
 assert_type(np.polyadd(poly_obj, AR_i8), np.poly1d)
 assert_type(np.polyadd(AR_f8, poly_obj), np.poly1d)
 assert_type(np.polyadd(AR_b, AR_b), npt.NDArray[np.bool])
-assert_type(np.polyadd(AR_u4, AR_b), npt.NDArray[np.unsignedinteger[Any]])
-assert_type(np.polyadd(AR_i8, AR_i8), npt.NDArray[np.signedinteger[Any]])
-assert_type(np.polyadd(AR_f8, AR_i8), npt.NDArray[np.floating[Any]])
-assert_type(np.polyadd(AR_i8, AR_c16), npt.NDArray[np.complexfloating[Any, Any]])
+assert_type(np.polyadd(AR_u4, AR_b), npt.NDArray[np.unsignedinteger])
+assert_type(np.polyadd(AR_i8, AR_i8), npt.NDArray[np.signedinteger])
+assert_type(np.polyadd(AR_f8, AR_i8), npt.NDArray[np.floating])
+assert_type(np.polyadd(AR_i8, AR_c16), npt.NDArray[np.complexfloating])
 assert_type(np.polyadd(AR_O, AR_O), npt.NDArray[np.object_])
 
 assert_type(np.polysub(poly_obj, AR_i8), np.poly1d)
 assert_type(np.polysub(AR_f8, poly_obj), np.poly1d)
 assert_type(np.polysub(AR_b, AR_b), NoReturn)
-assert_type(np.polysub(AR_u4, AR_b), npt.NDArray[np.unsignedinteger[Any]])
-assert_type(np.polysub(AR_i8, AR_i8), npt.NDArray[np.signedinteger[Any]])
-assert_type(np.polysub(AR_f8, AR_i8), npt.NDArray[np.floating[Any]])
-assert_type(np.polysub(AR_i8, AR_c16), npt.NDArray[np.complexfloating[Any, Any]])
+assert_type(np.polysub(AR_u4, AR_b), npt.NDArray[np.unsignedinteger])
+assert_type(np.polysub(AR_i8, AR_i8), npt.NDArray[np.signedinteger])
+assert_type(np.polysub(AR_f8, AR_i8), npt.NDArray[np.floating])
+assert_type(np.polysub(AR_i8, AR_c16), npt.NDArray[np.complexfloating])
 assert_type(np.polysub(AR_O, AR_O), npt.NDArray[np.object_])
 
 assert_type(np.polymul(poly_obj, AR_i8), np.poly1d)
 assert_type(np.polymul(AR_f8, poly_obj), np.poly1d)
 assert_type(np.polymul(AR_b, AR_b), npt.NDArray[np.bool])
-assert_type(np.polymul(AR_u4, AR_b), npt.NDArray[np.unsignedinteger[Any]])
-assert_type(np.polymul(AR_i8, AR_i8), npt.NDArray[np.signedinteger[Any]])
-assert_type(np.polymul(AR_f8, AR_i8), npt.NDArray[np.floating[Any]])
-assert_type(np.polymul(AR_i8, AR_c16), npt.NDArray[np.complexfloating[Any, Any]])
+assert_type(np.polymul(AR_u4, AR_b), npt.NDArray[np.unsignedinteger])
+assert_type(np.polymul(AR_i8, AR_i8), npt.NDArray[np.signedinteger])
+assert_type(np.polymul(AR_f8, AR_i8), npt.NDArray[np.floating])
+assert_type(np.polymul(AR_i8, AR_c16), npt.NDArray[np.complexfloating])
 assert_type(np.polymul(AR_O, AR_O), npt.NDArray[np.object_])
 
 assert_type(np.polydiv(poly_obj, AR_i8), tuple[np.poly1d, np.poly1d])
 assert_type(np.polydiv(AR_f8, poly_obj), tuple[np.poly1d, np.poly1d])
-assert_type(np.polydiv(AR_b, AR_b), tuple[npt.NDArray[np.floating[Any]], npt.NDArray[np.floating[Any]]])
-assert_type(np.polydiv(AR_u4, AR_b), tuple[npt.NDArray[np.floating[Any]], npt.NDArray[np.floating[Any]]])
-assert_type(np.polydiv(AR_i8, AR_i8), tuple[npt.NDArray[np.floating[Any]], npt.NDArray[np.floating[Any]]])
-assert_type(np.polydiv(AR_f8, AR_i8), tuple[npt.NDArray[np.floating[Any]], npt.NDArray[np.floating[Any]]])
-assert_type(np.polydiv(AR_i8, AR_c16), tuple[npt.NDArray[np.complexfloating[Any, Any]], npt.NDArray[np.complexfloating[Any, Any]]])
+assert_type(np.polydiv(AR_b, AR_b), tuple[npt.NDArray[np.floating], npt.NDArray[np.floating]])
+assert_type(np.polydiv(AR_u4, AR_b), tuple[npt.NDArray[np.floating], npt.NDArray[np.floating]])
+assert_type(np.polydiv(AR_i8, AR_i8), tuple[npt.NDArray[np.floating], npt.NDArray[np.floating]])
+assert_type(np.polydiv(AR_f8, AR_i8), tuple[npt.NDArray[np.floating], npt.NDArray[np.floating]])
+assert_type(np.polydiv(AR_i8, AR_c16), tuple[npt.NDArray[np.complexfloating], npt.NDArray[np.complexfloating]])
 assert_type(np.polydiv(AR_O, AR_O), tuple[npt.NDArray[Any], npt.NDArray[Any]])
diff --git a/numpy/typing/tests/data/reveal/linalg.pyi b/numpy/typing/tests/data/reveal/linalg.pyi
index 52a6b8f4b180..417fb0d8c558 100644
--- a/numpy/typing/tests/data/reveal/linalg.pyi
+++ b/numpy/typing/tests/data/reveal/linalg.pyi
@@ -19,20 +19,20 @@ AR_S: npt.NDArray[np.str_]
 AR_b: npt.NDArray[np.bool]
 
 assert_type(np.linalg.tensorsolve(AR_i8, AR_i8), npt.NDArray[np.float64])
-assert_type(np.linalg.tensorsolve(AR_i8, AR_f8), npt.NDArray[np.floating[Any]])
-assert_type(np.linalg.tensorsolve(AR_c16, AR_f8), npt.NDArray[np.complexfloating[Any, Any]])
+assert_type(np.linalg.tensorsolve(AR_i8, AR_f8), npt.NDArray[np.floating])
+assert_type(np.linalg.tensorsolve(AR_c16, AR_f8), npt.NDArray[np.complexfloating])
 
 assert_type(np.linalg.solve(AR_i8, AR_i8), npt.NDArray[np.float64])
-assert_type(np.linalg.solve(AR_i8, AR_f8), npt.NDArray[np.floating[Any]])
-assert_type(np.linalg.solve(AR_c16, AR_f8), npt.NDArray[np.complexfloating[Any, Any]])
+assert_type(np.linalg.solve(AR_i8, AR_f8), npt.NDArray[np.floating])
+assert_type(np.linalg.solve(AR_c16, AR_f8), npt.NDArray[np.complexfloating])
 
 assert_type(np.linalg.tensorinv(AR_i8), npt.NDArray[np.float64])
-assert_type(np.linalg.tensorinv(AR_f8), npt.NDArray[np.floating[Any]])
-assert_type(np.linalg.tensorinv(AR_c16), npt.NDArray[np.complexfloating[Any, Any]])
+assert_type(np.linalg.tensorinv(AR_f8), npt.NDArray[np.floating])
+assert_type(np.linalg.tensorinv(AR_c16), npt.NDArray[np.complexfloating])
 
 assert_type(np.linalg.inv(AR_i8), npt.NDArray[np.float64])
-assert_type(np.linalg.inv(AR_f8), npt.NDArray[np.floating[Any]])
-assert_type(np.linalg.inv(AR_c16), npt.NDArray[np.complexfloating[Any, Any]])
+assert_type(np.linalg.inv(AR_f8), npt.NDArray[np.floating])
+assert_type(np.linalg.inv(AR_c16), npt.NDArray[np.complexfloating])
 
 assert_type(np.linalg.matrix_power(AR_i8, -1), npt.NDArray[Any])
 assert_type(np.linalg.matrix_power(AR_f8, 0), npt.NDArray[Any])
@@ -40,12 +40,12 @@ assert_type(np.linalg.matrix_power(AR_c16, 1), npt.NDArray[Any])
 assert_type(np.linalg.matrix_power(AR_O, 2), npt.NDArray[Any])
 
 assert_type(np.linalg.cholesky(AR_i8), npt.NDArray[np.float64])
-assert_type(np.linalg.cholesky(AR_f8), npt.NDArray[np.floating[Any]])
-assert_type(np.linalg.cholesky(AR_c16), npt.NDArray[np.complexfloating[Any, Any]])
+assert_type(np.linalg.cholesky(AR_f8), npt.NDArray[np.floating])
+assert_type(np.linalg.cholesky(AR_c16), npt.NDArray[np.complexfloating])
 
-assert_type(np.linalg.outer(AR_i8, AR_i8), npt.NDArray[np.signedinteger[Any]])
-assert_type(np.linalg.outer(AR_f8, AR_f8), npt.NDArray[np.floating[Any]])
-assert_type(np.linalg.outer(AR_c16, AR_c16), npt.NDArray[np.complexfloating[Any, Any]])
+assert_type(np.linalg.outer(AR_i8, AR_i8), npt.NDArray[np.signedinteger])
+assert_type(np.linalg.outer(AR_f8, AR_f8), npt.NDArray[np.floating])
+assert_type(np.linalg.outer(AR_c16, AR_c16), npt.NDArray[np.complexfloating])
 assert_type(np.linalg.outer(AR_b, AR_b), npt.NDArray[np.bool])
 assert_type(np.linalg.outer(AR_O, AR_O), npt.NDArray[np.object_])
 assert_type(np.linalg.outer(AR_i8, AR_m), npt.NDArray[np.timedelta64])
@@ -55,12 +55,12 @@ assert_type(np.linalg.qr(AR_f8), QRResult)
 assert_type(np.linalg.qr(AR_c16), QRResult)
 
 assert_type(np.linalg.eigvals(AR_i8), npt.NDArray[np.float64] | npt.NDArray[np.complex128])
-assert_type(np.linalg.eigvals(AR_f8), npt.NDArray[np.floating[Any]] | npt.NDArray[np.complexfloating[Any, Any]])
-assert_type(np.linalg.eigvals(AR_c16), npt.NDArray[np.complexfloating[Any, Any]])
+assert_type(np.linalg.eigvals(AR_f8), npt.NDArray[np.floating] | npt.NDArray[np.complexfloating])
+assert_type(np.linalg.eigvals(AR_c16), npt.NDArray[np.complexfloating])
 
 assert_type(np.linalg.eigvalsh(AR_i8), npt.NDArray[np.float64])
-assert_type(np.linalg.eigvalsh(AR_f8), npt.NDArray[np.floating[Any]])
-assert_type(np.linalg.eigvalsh(AR_c16), npt.NDArray[np.floating[Any]])
+assert_type(np.linalg.eigvalsh(AR_f8), npt.NDArray[np.floating])
+assert_type(np.linalg.eigvalsh(AR_c16), npt.NDArray[np.floating])
 
 assert_type(np.linalg.eig(AR_i8), EigResult)
 assert_type(np.linalg.eig(AR_f8), EigResult)
@@ -74,8 +74,8 @@ assert_type(np.linalg.svd(AR_i8), SVDResult)
 assert_type(np.linalg.svd(AR_f8), SVDResult)
 assert_type(np.linalg.svd(AR_c16), SVDResult)
 assert_type(np.linalg.svd(AR_i8, compute_uv=False), npt.NDArray[np.float64])
-assert_type(np.linalg.svd(AR_f8, compute_uv=False), npt.NDArray[np.floating[Any]])
-assert_type(np.linalg.svd(AR_c16, compute_uv=False), npt.NDArray[np.floating[Any]])
+assert_type(np.linalg.svd(AR_f8, compute_uv=False), npt.NDArray[np.floating])
+assert_type(np.linalg.svd(AR_c16, compute_uv=False), npt.NDArray[np.floating])
 
 assert_type(np.linalg.cond(AR_i8), Any)
 assert_type(np.linalg.cond(AR_f8), Any)
@@ -86,8 +86,8 @@ assert_type(np.linalg.matrix_rank(AR_f8), Any)
 assert_type(np.linalg.matrix_rank(AR_c16), Any)
 
 assert_type(np.linalg.pinv(AR_i8), npt.NDArray[np.float64])
-assert_type(np.linalg.pinv(AR_f8), npt.NDArray[np.floating[Any]])
-assert_type(np.linalg.pinv(AR_c16), npt.NDArray[np.complexfloating[Any, Any]])
+assert_type(np.linalg.pinv(AR_f8), npt.NDArray[np.floating])
+assert_type(np.linalg.pinv(AR_c16), npt.NDArray[np.complexfloating])
 
 assert_type(np.linalg.slogdet(AR_i8), SlogdetResult)
 assert_type(np.linalg.slogdet(AR_f8), SlogdetResult)
@@ -98,24 +98,24 @@ assert_type(np.linalg.det(AR_f8), Any)
 assert_type(np.linalg.det(AR_c16), Any)
 
 assert_type(np.linalg.lstsq(AR_i8, AR_i8), tuple[npt.NDArray[np.float64], npt.NDArray[np.float64], np.int32, npt.NDArray[np.float64]])
-assert_type(np.linalg.lstsq(AR_i8, AR_f8), tuple[npt.NDArray[np.floating[Any]], npt.NDArray[np.floating[Any]], np.int32, npt.NDArray[np.floating[Any]]])
-assert_type(np.linalg.lstsq(AR_f8, AR_c16), tuple[npt.NDArray[np.complexfloating[Any, Any]], npt.NDArray[np.floating[Any]], np.int32, npt.NDArray[np.floating[Any]]])
+assert_type(np.linalg.lstsq(AR_i8, AR_f8), tuple[npt.NDArray[np.floating], npt.NDArray[np.floating], np.int32, npt.NDArray[np.floating]])
+assert_type(np.linalg.lstsq(AR_f8, AR_c16), tuple[npt.NDArray[np.complexfloating], npt.NDArray[np.floating], np.int32, npt.NDArray[np.floating]])
 
-assert_type(np.linalg.norm(AR_i8), np.floating[Any])
-assert_type(np.linalg.norm(AR_f8), np.floating[Any])
-assert_type(np.linalg.norm(AR_c16), np.floating[Any])
-assert_type(np.linalg.norm(AR_S), np.floating[Any])
+assert_type(np.linalg.norm(AR_i8), np.floating)
+assert_type(np.linalg.norm(AR_f8), np.floating)
+assert_type(np.linalg.norm(AR_c16), np.floating)
+assert_type(np.linalg.norm(AR_S), np.floating)
 assert_type(np.linalg.norm(AR_f8, axis=0), Any)
 
-assert_type(np.linalg.matrix_norm(AR_i8), np.floating[Any])
-assert_type(np.linalg.matrix_norm(AR_f8), np.floating[Any])
-assert_type(np.linalg.matrix_norm(AR_c16), np.floating[Any])
-assert_type(np.linalg.matrix_norm(AR_S), np.floating[Any])
+assert_type(np.linalg.matrix_norm(AR_i8), np.floating)
+assert_type(np.linalg.matrix_norm(AR_f8), np.floating)
+assert_type(np.linalg.matrix_norm(AR_c16), np.floating)
+assert_type(np.linalg.matrix_norm(AR_S), np.floating)
 
-assert_type(np.linalg.vector_norm(AR_i8), np.floating[Any])
-assert_type(np.linalg.vector_norm(AR_f8), np.floating[Any])
-assert_type(np.linalg.vector_norm(AR_c16), np.floating[Any])
-assert_type(np.linalg.vector_norm(AR_S), np.floating[Any])
+assert_type(np.linalg.vector_norm(AR_i8), np.floating)
+assert_type(np.linalg.vector_norm(AR_f8), np.floating)
+assert_type(np.linalg.vector_norm(AR_c16), np.floating)
+assert_type(np.linalg.vector_norm(AR_S), np.floating)
 
 assert_type(np.linalg.multi_dot([AR_i8, AR_i8]), Any)
 assert_type(np.linalg.multi_dot([AR_i8, AR_f8]), Any)
@@ -123,10 +123,10 @@ assert_type(np.linalg.multi_dot([AR_f8, AR_c16]), Any)
 assert_type(np.linalg.multi_dot([AR_O, AR_O]), Any)
 assert_type(np.linalg.multi_dot([AR_m, AR_m]), Any)
 
-assert_type(np.linalg.cross(AR_i8, AR_i8), npt.NDArray[np.signedinteger[Any]])
-assert_type(np.linalg.cross(AR_f8, AR_f8), npt.NDArray[np.floating[Any]])
-assert_type(np.linalg.cross(AR_c16, AR_c16), npt.NDArray[np.complexfloating[Any, Any]])
+assert_type(np.linalg.cross(AR_i8, AR_i8), npt.NDArray[np.signedinteger])
+assert_type(np.linalg.cross(AR_f8, AR_f8), npt.NDArray[np.floating])
+assert_type(np.linalg.cross(AR_c16, AR_c16), npt.NDArray[np.complexfloating])
 
-assert_type(np.linalg.matmul(AR_i8, AR_i8), npt.NDArray[np.signedinteger[Any]])
-assert_type(np.linalg.matmul(AR_f8, AR_f8), npt.NDArray[np.floating[Any]])
-assert_type(np.linalg.matmul(AR_c16, AR_c16), npt.NDArray[np.complexfloating[Any, Any]])
+assert_type(np.linalg.matmul(AR_i8, AR_i8), npt.NDArray[np.signedinteger])
+assert_type(np.linalg.matmul(AR_f8, AR_f8), npt.NDArray[np.floating])
+assert_type(np.linalg.matmul(AR_c16, AR_c16), npt.NDArray[np.complexfloating])
diff --git a/numpy/typing/tests/data/reveal/multiarray.pyi b/numpy/typing/tests/data/reveal/multiarray.pyi
index ec5d8aa525c6..e73d6028c718 100644
--- a/numpy/typing/tests/data/reveal/multiarray.pyi
+++ b/numpy/typing/tests/data/reveal/multiarray.pyi
@@ -84,9 +84,9 @@ assert_type(np.dot(AR_u1, 1), Any)
 assert_type(np.dot(1.5j, 1), Any)
 assert_type(np.dot(AR_u1, 1, out=AR_f8), npt.NDArray[np.float64])
 
-assert_type(np.vdot(AR_LIKE_f, AR_i8), np.floating[Any])
-assert_type(np.vdot(AR_u1, 1), np.signedinteger[Any])
-assert_type(np.vdot(1.5j, 1), np.complexfloating[Any, Any])
+assert_type(np.vdot(AR_LIKE_f, AR_i8), np.floating)
+assert_type(np.vdot(AR_u1, 1), np.signedinteger)
+assert_type(np.vdot(1.5j, 1), np.complexfloating)
 
 assert_type(np.bincount(AR_i8), npt.NDArray[np.intp])
 
diff --git a/numpy/typing/tests/data/reveal/ndarray_conversion.pyi b/numpy/typing/tests/data/reveal/ndarray_conversion.pyi
index cd40b74e2e56..bbd42573a774 100644
--- a/numpy/typing/tests/data/reveal/ndarray_conversion.pyi
+++ b/numpy/typing/tests/data/reveal/ndarray_conversion.pyi
@@ -59,7 +59,7 @@ assert_type(i4_2d.astype(np.uint16), np.ndarray[tuple[int, int], np.dtype[np.uin
 assert_type(np.astype(i4_2d, np.uint16), np.ndarray[tuple[int, int], np.dtype[np.uint16]])
 assert_type(f8_3d.astype(np.int16), np.ndarray[tuple[int, int, int], np.dtype[np.int16]])
 assert_type(np.astype(f8_3d, np.int16), np.ndarray[tuple[int, int, int], np.dtype[np.int16]])
-assert_type(i4_2d.astype(uncertain_dtype), np.ndarray[tuple[int, int], np.dtype[np.generic[Any]]])
+assert_type(i4_2d.astype(uncertain_dtype), np.ndarray[tuple[int, int], np.dtype[np.generic]])
 assert_type(np.astype(i4_2d, uncertain_dtype), np.ndarray[tuple[int, int], np.dtype])
 
 # byteswap
diff --git a/numpy/typing/tests/data/reveal/numeric.pyi b/numpy/typing/tests/data/reveal/numeric.pyi
index 34e20c986b69..bd94f4e7eede 100644
--- a/numpy/typing/tests/data/reveal/numeric.pyi
+++ b/numpy/typing/tests/data/reveal/numeric.pyi
@@ -40,47 +40,47 @@ assert_type(np.argwhere(AR_i8), npt.NDArray[np.intp])
 assert_type(np.flatnonzero(i8), npt.NDArray[np.intp])
 assert_type(np.flatnonzero(AR_i8), npt.NDArray[np.intp])
 
-assert_type(np.correlate(B, AR_i8, mode="valid"), npt.NDArray[np.signedinteger[Any]])
-assert_type(np.correlate(AR_i8, AR_i8, mode="same"), npt.NDArray[np.signedinteger[Any]])
+assert_type(np.correlate(B, AR_i8, mode="valid"), npt.NDArray[np.signedinteger])
+assert_type(np.correlate(AR_i8, AR_i8, mode="same"), npt.NDArray[np.signedinteger])
 assert_type(np.correlate(AR_b, AR_b), npt.NDArray[np.bool])
-assert_type(np.correlate(AR_b, AR_u8), npt.NDArray[np.unsignedinteger[Any]])
-assert_type(np.correlate(AR_i8, AR_b), npt.NDArray[np.signedinteger[Any]])
-assert_type(np.correlate(AR_i8, AR_f8), npt.NDArray[np.floating[Any]])
-assert_type(np.correlate(AR_i8, AR_c16), npt.NDArray[np.complexfloating[Any, Any]])
+assert_type(np.correlate(AR_b, AR_u8), npt.NDArray[np.unsignedinteger])
+assert_type(np.correlate(AR_i8, AR_b), npt.NDArray[np.signedinteger])
+assert_type(np.correlate(AR_i8, AR_f8), npt.NDArray[np.floating])
+assert_type(np.correlate(AR_i8, AR_c16), npt.NDArray[np.complexfloating])
 assert_type(np.correlate(AR_i8, AR_m), npt.NDArray[np.timedelta64])
 assert_type(np.correlate(AR_O, AR_O), npt.NDArray[np.object_])
 
-assert_type(np.convolve(B, AR_i8, mode="valid"), npt.NDArray[np.signedinteger[Any]])
-assert_type(np.convolve(AR_i8, AR_i8, mode="same"), npt.NDArray[np.signedinteger[Any]])
+assert_type(np.convolve(B, AR_i8, mode="valid"), npt.NDArray[np.signedinteger])
+assert_type(np.convolve(AR_i8, AR_i8, mode="same"), npt.NDArray[np.signedinteger])
 assert_type(np.convolve(AR_b, AR_b), npt.NDArray[np.bool])
-assert_type(np.convolve(AR_b, AR_u8), npt.NDArray[np.unsignedinteger[Any]])
-assert_type(np.convolve(AR_i8, AR_b), npt.NDArray[np.signedinteger[Any]])
-assert_type(np.convolve(AR_i8, AR_f8), npt.NDArray[np.floating[Any]])
-assert_type(np.convolve(AR_i8, AR_c16), npt.NDArray[np.complexfloating[Any, Any]])
+assert_type(np.convolve(AR_b, AR_u8), npt.NDArray[np.unsignedinteger])
+assert_type(np.convolve(AR_i8, AR_b), npt.NDArray[np.signedinteger])
+assert_type(np.convolve(AR_i8, AR_f8), npt.NDArray[np.floating])
+assert_type(np.convolve(AR_i8, AR_c16), npt.NDArray[np.complexfloating])
 assert_type(np.convolve(AR_i8, AR_m), npt.NDArray[np.timedelta64])
 assert_type(np.convolve(AR_O, AR_O), npt.NDArray[np.object_])
 
-assert_type(np.outer(i8, AR_i8), npt.NDArray[np.signedinteger[Any]])
-assert_type(np.outer(B, AR_i8), npt.NDArray[np.signedinteger[Any]])
-assert_type(np.outer(AR_i8, AR_i8), npt.NDArray[np.signedinteger[Any]])
+assert_type(np.outer(i8, AR_i8), npt.NDArray[np.signedinteger])
+assert_type(np.outer(B, AR_i8), npt.NDArray[np.signedinteger])
+assert_type(np.outer(AR_i8, AR_i8), npt.NDArray[np.signedinteger])
 assert_type(np.outer(AR_i8, AR_i8, out=C), SubClass)
 assert_type(np.outer(AR_b, AR_b), npt.NDArray[np.bool])
-assert_type(np.outer(AR_b, AR_u8), npt.NDArray[np.unsignedinteger[Any]])
-assert_type(np.outer(AR_i8, AR_b), npt.NDArray[np.signedinteger[Any]])
-assert_type(np.convolve(AR_i8, AR_f8), npt.NDArray[np.floating[Any]])
-assert_type(np.outer(AR_i8, AR_c16), npt.NDArray[np.complexfloating[Any, Any]])
+assert_type(np.outer(AR_b, AR_u8), npt.NDArray[np.unsignedinteger])
+assert_type(np.outer(AR_i8, AR_b), npt.NDArray[np.signedinteger])
+assert_type(np.convolve(AR_i8, AR_f8), npt.NDArray[np.floating])
+assert_type(np.outer(AR_i8, AR_c16), npt.NDArray[np.complexfloating])
 assert_type(np.outer(AR_i8, AR_m), npt.NDArray[np.timedelta64])
 assert_type(np.outer(AR_O, AR_O), npt.NDArray[np.object_])
 
-assert_type(np.tensordot(B, AR_i8), npt.NDArray[np.signedinteger[Any]])
-assert_type(np.tensordot(AR_i8, AR_i8), npt.NDArray[np.signedinteger[Any]])
-assert_type(np.tensordot(AR_i8, AR_i8, axes=0), npt.NDArray[np.signedinteger[Any]])
-assert_type(np.tensordot(AR_i8, AR_i8, axes=(0, 1)), npt.NDArray[np.signedinteger[Any]])
+assert_type(np.tensordot(B, AR_i8), npt.NDArray[np.signedinteger])
+assert_type(np.tensordot(AR_i8, AR_i8), npt.NDArray[np.signedinteger])
+assert_type(np.tensordot(AR_i8, AR_i8, axes=0), npt.NDArray[np.signedinteger])
+assert_type(np.tensordot(AR_i8, AR_i8, axes=(0, 1)), npt.NDArray[np.signedinteger])
 assert_type(np.tensordot(AR_b, AR_b), npt.NDArray[np.bool])
-assert_type(np.tensordot(AR_b, AR_u8), npt.NDArray[np.unsignedinteger[Any]])
-assert_type(np.tensordot(AR_i8, AR_b), npt.NDArray[np.signedinteger[Any]])
-assert_type(np.tensordot(AR_i8, AR_f8), npt.NDArray[np.floating[Any]])
-assert_type(np.tensordot(AR_i8, AR_c16), npt.NDArray[np.complexfloating[Any, Any]])
+assert_type(np.tensordot(AR_b, AR_u8), npt.NDArray[np.unsignedinteger])
+assert_type(np.tensordot(AR_i8, AR_b), npt.NDArray[np.signedinteger])
+assert_type(np.tensordot(AR_i8, AR_f8), npt.NDArray[np.floating])
+assert_type(np.tensordot(AR_i8, AR_c16), npt.NDArray[np.complexfloating])
 assert_type(np.tensordot(AR_i8, AR_m), npt.NDArray[np.timedelta64])
 assert_type(np.tensordot(AR_O, AR_O), npt.NDArray[np.object_])
 
@@ -97,12 +97,12 @@ assert_type(np.rollaxis(AR_i8, 0, 1), npt.NDArray[np.int64])
 assert_type(np.moveaxis(AR_i8, 0, 1), npt.NDArray[np.int64])
 assert_type(np.moveaxis(AR_i8, (0, 1), (1, 2)), npt.NDArray[np.int64])
 
-assert_type(np.cross(B, AR_i8), npt.NDArray[np.signedinteger[Any]])
-assert_type(np.cross(AR_i8, AR_i8), npt.NDArray[np.signedinteger[Any]])
-assert_type(np.cross(AR_b, AR_u8), npt.NDArray[np.unsignedinteger[Any]])
-assert_type(np.cross(AR_i8, AR_b), npt.NDArray[np.signedinteger[Any]])
-assert_type(np.cross(AR_i8, AR_f8), npt.NDArray[np.floating[Any]])
-assert_type(np.cross(AR_i8, AR_c16), npt.NDArray[np.complexfloating[Any, Any]])
+assert_type(np.cross(B, AR_i8), npt.NDArray[np.signedinteger])
+assert_type(np.cross(AR_i8, AR_i8), npt.NDArray[np.signedinteger])
+assert_type(np.cross(AR_b, AR_u8), npt.NDArray[np.unsignedinteger])
+assert_type(np.cross(AR_i8, AR_b), npt.NDArray[np.signedinteger])
+assert_type(np.cross(AR_i8, AR_f8), npt.NDArray[np.floating])
+assert_type(np.cross(AR_i8, AR_c16), npt.NDArray[np.complexfloating])
 assert_type(np.cross(AR_O, AR_O), npt.NDArray[np.object_])
 
 assert_type(np.indices([0, 1, 2]), npt.NDArray[np.int_])
diff --git a/numpy/typing/tests/data/reveal/polynomial_polybase.pyi b/numpy/typing/tests/data/reveal/polynomial_polybase.pyi
index c060011eea9c..bb927035e40c 100644
--- a/numpy/typing/tests/data/reveal/polynomial_polybase.pyi
+++ b/numpy/typing/tests/data/reveal/polynomial_polybase.pyi
@@ -8,19 +8,19 @@ import numpy as np
 import numpy.polynomial as npp
 import numpy.typing as npt
 
-_Ar_x: TypeAlias = npt.NDArray[np.inexact[Any] | np.object_]
-_Ar_f: TypeAlias = npt.NDArray[np.floating[Any]]
-_Ar_c: TypeAlias = npt.NDArray[np.complexfloating[Any, Any]]
+_Ar_x: TypeAlias = npt.NDArray[np.inexact | np.object_]
+_Ar_f: TypeAlias = npt.NDArray[np.floating]
+_Ar_c: TypeAlias = npt.NDArray[np.complexfloating]
 _Ar_O: TypeAlias = npt.NDArray[np.object_]
 
-_Ar_x_n: TypeAlias = np.ndarray[tuple[int], np.dtype[np.inexact[Any] | np.object_]]
-_Ar_f_n: TypeAlias = np.ndarray[tuple[int], np.dtype[np.floating[Any]]]
-_Ar_c_n: TypeAlias = np.ndarray[tuple[int], np.dtype[np.complexfloating[Any, Any]]]
+_Ar_x_n: TypeAlias = np.ndarray[tuple[int], np.dtype[np.inexact | np.object_]]
+_Ar_f_n: TypeAlias = np.ndarray[tuple[int], np.dtype[np.floating]]
+_Ar_c_n: TypeAlias = np.ndarray[tuple[int], np.dtype[np.complexfloating]]
 _Ar_O_n: TypeAlias = np.ndarray[tuple[int], np.dtype[np.object_]]
 
-_Ar_x_2: TypeAlias = np.ndarray[tuple[L[2]], np.dtype[np.inexact[Any] | np.object_]]
-_Ar_f_2: TypeAlias = np.ndarray[tuple[L[2]], np.dtype[np.floating[Any]]]
-_Ar_c_2: TypeAlias = np.ndarray[tuple[L[2]], np.dtype[np.complexfloating[Any, Any]]]
+_Ar_x_2: TypeAlias = np.ndarray[tuple[L[2]], np.dtype[np.inexact | np.object_]]
+_Ar_f_2: TypeAlias = np.ndarray[tuple[L[2]], np.dtype[np.floating]]
+_Ar_c_2: TypeAlias = np.ndarray[tuple[L[2]], np.dtype[np.complexfloating]]
 _Ar_O_2: TypeAlias = np.ndarray[tuple[L[2]], np.dtype[np.object_]]
 
 _ScalarT = TypeVar("_ScalarT", bound=np.generic)
@@ -42,7 +42,7 @@ AR_f_co: npt.NDArray[np.float64] | npt.NDArray[np.int_]
 AR_c: npt.NDArray[np.complex128]
 AR_c_co: npt.NDArray[np.complex128] | npt.NDArray[np.float64] | npt.NDArray[np.int_]
 AR_O: npt.NDArray[np.object_]
-AR_O_co: npt.NDArray[np.object_ | np.number[Any]]
+AR_O_co: npt.NDArray[np.object_ | np.number]
 
 SQ_i: Sequence[int]
 SQ_f: Sequence[float]
@@ -160,7 +160,7 @@ assert_type(PS_poly.fit(AR_c_co, SQ_c, SQ_i), npp.Polynomial)
 assert_type(PS_lag.fit(SQ_c, SQ_c, SQ_i, full=False), npp.Laguerre)
 assert_type(
     PS_herme.fit(SQ_c, AR_c_co, SC_i_co, full=True),
-    tuple[npp.HermiteE, Sequence[np.inexact[Any] | np.int32]],
+    tuple[npp.HermiteE, Sequence[np.inexact | np.int32]],
 )
 
 # custom operations
@@ -173,7 +173,7 @@ assert_type(repr(PS_all), str)
 assert_type(format(PS_all), str)
 
 assert_type(len(PS_all), int)
-assert_type(next(iter(PS_all)), np.inexact[Any] | object)
+assert_type(next(iter(PS_all)), np.inexact | object)
 
 assert_type(PS_all(SC_f_co), np.float64 | np.complex128)
 assert_type(PS_all(SC_c_co), np.complex128)
diff --git a/numpy/typing/tests/data/reveal/polynomial_polyutils.pyi b/numpy/typing/tests/data/reveal/polynomial_polyutils.pyi
index 69d675533a6c..45522e72102f 100644
--- a/numpy/typing/tests/data/reveal/polynomial_polyutils.pyi
+++ b/numpy/typing/tests/data/reveal/polynomial_polyutils.pyi
@@ -9,8 +9,8 @@ import numpy.polynomial.polyutils as pu
 import numpy.typing as npt
 from numpy.polynomial._polytypes import _Tuple2
 
-_ArrFloat1D: TypeAlias = np.ndarray[tuple[int], np.dtype[np.floating[Any]]]
-_ArrComplex1D: TypeAlias = np.ndarray[tuple[int], np.dtype[np.complexfloating[Any, Any]]]
+_ArrFloat1D: TypeAlias = np.ndarray[tuple[int], np.dtype[np.floating]]
+_ArrComplex1D: TypeAlias = np.ndarray[tuple[int], np.dtype[np.complexfloating]]
 _ArrObject1D: TypeAlias = np.ndarray[tuple[int], np.dtype[np.object_]]
 
 _ArrFloat1D_2: TypeAlias = np.ndarray[tuple[L[2]], np.dtype[np.float64]]
@@ -156,31 +156,31 @@ assert_type(pu.mapparms(seq_num_complex, seq_num_complex), _Tuple2[complex])
 assert_type(pu.mapparms(seq_num_complex, seq_num_object), _Tuple2[object])
 assert_type(pu.mapparms(seq_num_object, seq_num_object), _Tuple2[object])
 
-assert_type(pu.mapparms(seq_sct_int, seq_sct_int), _Tuple2[np.floating[Any]])
-assert_type(pu.mapparms(seq_sct_int, seq_sct_float), _Tuple2[np.floating[Any]])
+assert_type(pu.mapparms(seq_sct_int, seq_sct_int), _Tuple2[np.floating])
+assert_type(pu.mapparms(seq_sct_int, seq_sct_float), _Tuple2[np.floating])
 assert_type(pu.mapparms(seq_sct_float, seq_sct_float), _Tuple2[float])
 assert_type(pu.mapparms(seq_sct_float, seq_sct_complex), _Tuple2[complex])
 assert_type(pu.mapparms(seq_sct_complex, seq_sct_complex), _Tuple2[complex])
 assert_type(pu.mapparms(seq_sct_complex, seq_sct_object), _Tuple2[object])
 assert_type(pu.mapparms(seq_sct_object, seq_sct_object), _Tuple2[object])
 
-assert_type(pu.mapparms(arr_int, arr_int), _Tuple2[np.floating[Any]])
-assert_type(pu.mapparms(arr_int, arr_float), _Tuple2[np.floating[Any]])
-assert_type(pu.mapparms(arr_float, arr_float), _Tuple2[np.floating[Any]])
-assert_type(pu.mapparms(arr_float, arr_complex), _Tuple2[np.complexfloating[Any, Any]])
-assert_type(pu.mapparms(arr_complex, arr_complex), _Tuple2[np.complexfloating[Any, Any]])
+assert_type(pu.mapparms(arr_int, arr_int), _Tuple2[np.floating])
+assert_type(pu.mapparms(arr_int, arr_float), _Tuple2[np.floating])
+assert_type(pu.mapparms(arr_float, arr_float), _Tuple2[np.floating])
+assert_type(pu.mapparms(arr_float, arr_complex), _Tuple2[np.complexfloating])
+assert_type(pu.mapparms(arr_complex, arr_complex), _Tuple2[np.complexfloating])
 assert_type(pu.mapparms(arr_complex, arr_object), _Tuple2[object])
 assert_type(pu.mapparms(arr_object, arr_object), _Tuple2[object])
 
 # mapdomain
 
-assert_type(pu.mapdomain(num_int, seq_num_int, seq_num_int), np.floating[Any])
-assert_type(pu.mapdomain(num_int, seq_num_int, seq_num_float), np.floating[Any])
-assert_type(pu.mapdomain(num_int, seq_num_float, seq_num_float), np.floating[Any])
-assert_type(pu.mapdomain(num_float, seq_num_float, seq_num_float), np.floating[Any])
-assert_type(pu.mapdomain(num_float, seq_num_float, seq_num_complex), np.complexfloating[Any, Any])
-assert_type(pu.mapdomain(num_float, seq_num_complex, seq_num_complex), np.complexfloating[Any, Any])
-assert_type(pu.mapdomain(num_complex, seq_num_complex, seq_num_complex), np.complexfloating[Any, Any])
+assert_type(pu.mapdomain(num_int, seq_num_int, seq_num_int), np.floating)
+assert_type(pu.mapdomain(num_int, seq_num_int, seq_num_float), np.floating)
+assert_type(pu.mapdomain(num_int, seq_num_float, seq_num_float), np.floating)
+assert_type(pu.mapdomain(num_float, seq_num_float, seq_num_float), np.floating)
+assert_type(pu.mapdomain(num_float, seq_num_float, seq_num_complex), np.complexfloating)
+assert_type(pu.mapdomain(num_float, seq_num_complex, seq_num_complex), np.complexfloating)
+assert_type(pu.mapdomain(num_complex, seq_num_complex, seq_num_complex), np.complexfloating)
 assert_type(pu.mapdomain(num_complex, seq_num_complex, seq_num_object), object)
 assert_type(pu.mapdomain(num_complex, seq_num_object, seq_num_object), object)
 assert_type(pu.mapdomain(num_object, seq_num_object, seq_num_object), object)
diff --git a/numpy/typing/tests/data/reveal/polynomial_series.pyi b/numpy/typing/tests/data/reveal/polynomial_series.pyi
index 6bc7eb0d9afb..93f0799c818d 100644
--- a/numpy/typing/tests/data/reveal/polynomial_series.pyi
+++ b/numpy/typing/tests/data/reveal/polynomial_series.pyi
@@ -5,9 +5,9 @@ import numpy as np
 import numpy.polynomial as npp
 import numpy.typing as npt
 
-_ArrFloat1D: TypeAlias = np.ndarray[tuple[int], np.dtype[np.floating[Any]]]
+_ArrFloat1D: TypeAlias = np.ndarray[tuple[int], np.dtype[np.floating]]
 _ArrFloat1D64: TypeAlias = np.ndarray[tuple[int], np.dtype[np.float64]]
-_ArrComplex1D: TypeAlias = np.ndarray[tuple[int], np.dtype[np.complexfloating[Any, Any]]]
+_ArrComplex1D: TypeAlias = np.ndarray[tuple[int], np.dtype[np.complexfloating]]
 _ArrComplex1D128: TypeAlias = np.ndarray[tuple[int], np.dtype[np.complex128]]
 _ArrObject1D: TypeAlias = np.ndarray[tuple[int], np.dtype[np.object_]]
 
@@ -49,70 +49,70 @@ assert_type(npp.polynomial.polypow(AR_c16, 2), _ArrComplex1D)
 assert_type(npp.polynomial.polypow(AR_O, 2), _ArrObject1D)
 
 # assert_type(npp.polynomial.polyder(PS_poly), npt.NDArray[np.object_])
-assert_type(npp.polynomial.polyder(AR_f8), npt.NDArray[np.floating[Any]])
-assert_type(npp.polynomial.polyder(AR_c16), npt.NDArray[np.complexfloating[Any, Any]])
+assert_type(npp.polynomial.polyder(AR_f8), npt.NDArray[np.floating])
+assert_type(npp.polynomial.polyder(AR_c16), npt.NDArray[np.complexfloating])
 assert_type(npp.polynomial.polyder(AR_O, m=2), npt.NDArray[np.object_])
 
 # assert_type(npp.polynomial.polyint(PS_poly), npt.NDArray[np.object_])
-assert_type(npp.polynomial.polyint(AR_f8), npt.NDArray[np.floating[Any]])
-assert_type(npp.polynomial.polyint(AR_f8, k=AR_c16), npt.NDArray[np.complexfloating[Any, Any]])
+assert_type(npp.polynomial.polyint(AR_f8), npt.NDArray[np.floating])
+assert_type(npp.polynomial.polyint(AR_f8, k=AR_c16), npt.NDArray[np.complexfloating])
 assert_type(npp.polynomial.polyint(AR_O, m=2), npt.NDArray[np.object_])
 
-assert_type(npp.polynomial.polyval(AR_b, AR_b), npt.NDArray[np.floating[Any]])
-assert_type(npp.polynomial.polyval(AR_u4, AR_b), npt.NDArray[np.floating[Any]])
-assert_type(npp.polynomial.polyval(AR_i8, AR_i8), npt.NDArray[np.floating[Any]])
-assert_type(npp.polynomial.polyval(AR_f8, AR_i8), npt.NDArray[np.floating[Any]])
-assert_type(npp.polynomial.polyval(AR_i8, AR_c16), npt.NDArray[np.complexfloating[Any, Any]])
+assert_type(npp.polynomial.polyval(AR_b, AR_b), npt.NDArray[np.floating])
+assert_type(npp.polynomial.polyval(AR_u4, AR_b), npt.NDArray[np.floating])
+assert_type(npp.polynomial.polyval(AR_i8, AR_i8), npt.NDArray[np.floating])
+assert_type(npp.polynomial.polyval(AR_f8, AR_i8), npt.NDArray[np.floating])
+assert_type(npp.polynomial.polyval(AR_i8, AR_c16), npt.NDArray[np.complexfloating])
 assert_type(npp.polynomial.polyval(AR_O, AR_O), npt.NDArray[np.object_])
 
-assert_type(npp.polynomial.polyval2d(AR_b, AR_b, AR_b), npt.NDArray[np.floating[Any]])
-assert_type(npp.polynomial.polyval2d(AR_u4, AR_u4, AR_b), npt.NDArray[np.floating[Any]])
-assert_type(npp.polynomial.polyval2d(AR_i8, AR_i8, AR_i8), npt.NDArray[np.floating[Any]])
-assert_type(npp.polynomial.polyval2d(AR_f8, AR_f8, AR_i8), npt.NDArray[np.floating[Any]])
-assert_type(npp.polynomial.polyval2d(AR_i8, AR_i8, AR_c16), npt.NDArray[np.complexfloating[Any, Any]])
+assert_type(npp.polynomial.polyval2d(AR_b, AR_b, AR_b), npt.NDArray[np.floating])
+assert_type(npp.polynomial.polyval2d(AR_u4, AR_u4, AR_b), npt.NDArray[np.floating])
+assert_type(npp.polynomial.polyval2d(AR_i8, AR_i8, AR_i8), npt.NDArray[np.floating])
+assert_type(npp.polynomial.polyval2d(AR_f8, AR_f8, AR_i8), npt.NDArray[np.floating])
+assert_type(npp.polynomial.polyval2d(AR_i8, AR_i8, AR_c16), npt.NDArray[np.complexfloating])
 assert_type(npp.polynomial.polyval2d(AR_O, AR_O, AR_O), npt.NDArray[np.object_])
 
-assert_type(npp.polynomial.polyval3d(AR_b, AR_b, AR_b, AR_b), npt.NDArray[np.floating[Any]])
-assert_type(npp.polynomial.polyval3d(AR_u4, AR_u4, AR_u4, AR_b), npt.NDArray[np.floating[Any]])
-assert_type(npp.polynomial.polyval3d(AR_i8, AR_i8, AR_i8, AR_i8), npt.NDArray[np.floating[Any]])
-assert_type(npp.polynomial.polyval3d(AR_f8, AR_f8, AR_f8, AR_i8), npt.NDArray[np.floating[Any]])
-assert_type(npp.polynomial.polyval3d(AR_i8, AR_i8, AR_i8, AR_c16), npt.NDArray[np.complexfloating[Any, Any]])
+assert_type(npp.polynomial.polyval3d(AR_b, AR_b, AR_b, AR_b), npt.NDArray[np.floating])
+assert_type(npp.polynomial.polyval3d(AR_u4, AR_u4, AR_u4, AR_b), npt.NDArray[np.floating])
+assert_type(npp.polynomial.polyval3d(AR_i8, AR_i8, AR_i8, AR_i8), npt.NDArray[np.floating])
+assert_type(npp.polynomial.polyval3d(AR_f8, AR_f8, AR_f8, AR_i8), npt.NDArray[np.floating])
+assert_type(npp.polynomial.polyval3d(AR_i8, AR_i8, AR_i8, AR_c16), npt.NDArray[np.complexfloating])
 assert_type(npp.polynomial.polyval3d(AR_O, AR_O, AR_O, AR_O), npt.NDArray[np.object_])
 
-assert_type(npp.polynomial.polyvalfromroots(AR_b, AR_b), npt.NDArray[np.floating[Any]])
-assert_type(npp.polynomial.polyvalfromroots(AR_u4, AR_b), npt.NDArray[np.floating[Any]])
-assert_type(npp.polynomial.polyvalfromroots(AR_i8, AR_i8), npt.NDArray[np.floating[Any]])
-assert_type(npp.polynomial.polyvalfromroots(AR_f8, AR_i8), npt.NDArray[np.floating[Any]])
-assert_type(npp.polynomial.polyvalfromroots(AR_i8, AR_c16), npt.NDArray[np.complexfloating[Any, Any]])
+assert_type(npp.polynomial.polyvalfromroots(AR_b, AR_b), npt.NDArray[np.floating])
+assert_type(npp.polynomial.polyvalfromroots(AR_u4, AR_b), npt.NDArray[np.floating])
+assert_type(npp.polynomial.polyvalfromroots(AR_i8, AR_i8), npt.NDArray[np.floating])
+assert_type(npp.polynomial.polyvalfromroots(AR_f8, AR_i8), npt.NDArray[np.floating])
+assert_type(npp.polynomial.polyvalfromroots(AR_i8, AR_c16), npt.NDArray[np.complexfloating])
 assert_type(npp.polynomial.polyvalfromroots(AR_O, AR_O), npt.NDArray[np.object_])
 
-assert_type(npp.polynomial.polyvander(AR_f8, 3), npt.NDArray[np.floating[Any]])
-assert_type(npp.polynomial.polyvander(AR_c16, 3), npt.NDArray[np.complexfloating[Any, Any]])
+assert_type(npp.polynomial.polyvander(AR_f8, 3), npt.NDArray[np.floating])
+assert_type(npp.polynomial.polyvander(AR_c16, 3), npt.NDArray[np.complexfloating])
 assert_type(npp.polynomial.polyvander(AR_O, 3), npt.NDArray[np.object_])
 
-assert_type(npp.polynomial.polyvander2d(AR_f8, AR_f8, [4, 2]), npt.NDArray[np.floating[Any]])
-assert_type(npp.polynomial.polyvander2d(AR_c16, AR_c16, [4, 2]), npt.NDArray[np.complexfloating[Any, Any]])
+assert_type(npp.polynomial.polyvander2d(AR_f8, AR_f8, [4, 2]), npt.NDArray[np.floating])
+assert_type(npp.polynomial.polyvander2d(AR_c16, AR_c16, [4, 2]), npt.NDArray[np.complexfloating])
 assert_type(npp.polynomial.polyvander2d(AR_O, AR_O, [4, 2]), npt.NDArray[np.object_])
 
-assert_type(npp.polynomial.polyvander3d(AR_f8, AR_f8, AR_f8, [4, 3, 2]), npt.NDArray[np.floating[Any]])
-assert_type(npp.polynomial.polyvander3d(AR_c16, AR_c16, AR_c16, [4, 3, 2]), npt.NDArray[np.complexfloating[Any, Any]])
+assert_type(npp.polynomial.polyvander3d(AR_f8, AR_f8, AR_f8, [4, 3, 2]), npt.NDArray[np.floating])
+assert_type(npp.polynomial.polyvander3d(AR_c16, AR_c16, AR_c16, [4, 3, 2]), npt.NDArray[np.complexfloating])
 assert_type(npp.polynomial.polyvander3d(AR_O, AR_O, AR_O, [4, 3, 2]), npt.NDArray[np.object_])
 
 assert_type(
     npp.polynomial.polyfit(AR_f8, AR_f8, 2),
-    npt.NDArray[np.floating[Any]],
+    npt.NDArray[np.floating],
 )
 assert_type(
     npp.polynomial.polyfit(AR_f8, AR_i8, 1, full=True),
-    tuple[npt.NDArray[np.floating[Any]], Sequence[np.inexact[Any] | np.int32]],
+    tuple[npt.NDArray[np.floating], Sequence[np.inexact | np.int32]],
 )
 assert_type(
     npp.polynomial.polyfit(AR_c16, AR_f8, 2),
-    npt.NDArray[np.complexfloating[Any, Any]],
+    npt.NDArray[np.complexfloating],
 )
 assert_type(
     npp.polynomial.polyfit(AR_f8, AR_c16, 1, full=True)[0],
-    npt.NDArray[np.complexfloating[Any, Any]],
+    npt.NDArray[np.complexfloating],
 )
 
 assert_type(npp.chebyshev.chebgauss(2), tuple[_ArrFloat1D64, _ArrFloat1D64])
diff --git a/numpy/typing/tests/data/reveal/shape_base.pyi b/numpy/typing/tests/data/reveal/shape_base.pyi
index 55503dfc07e1..e409a53bcef9 100644
--- a/numpy/typing/tests/data/reveal/shape_base.pyi
+++ b/numpy/typing/tests/data/reveal/shape_base.pyi
@@ -42,8 +42,8 @@ assert_type(np.dsplit(AR_i8, [3, 5, 6, 10]), list[npt.NDArray[np.int64]])
 assert_type(np.dsplit(AR_LIKE_f8, [3, 5, 6, 10]), list[npt.NDArray[Any]])
 
 assert_type(np.kron(AR_b, AR_b), npt.NDArray[np.bool])
-assert_type(np.kron(AR_b, AR_i8), npt.NDArray[np.signedinteger[Any]])
-assert_type(np.kron(AR_f8, AR_f8), npt.NDArray[np.floating[Any]])
+assert_type(np.kron(AR_b, AR_i8), npt.NDArray[np.signedinteger])
+assert_type(np.kron(AR_f8, AR_f8), npt.NDArray[np.floating])
 
 assert_type(np.tile(AR_i8, 5), npt.NDArray[np.int64])
 assert_type(np.tile(AR_LIKE_f8, [2, 2]), npt.NDArray[Any])
diff --git a/numpy/typing/tests/data/reveal/testing.pyi b/numpy/typing/tests/data/reveal/testing.pyi
index e0eae7f42ecc..d70bc971c15f 100644
--- a/numpy/typing/tests/data/reveal/testing.pyi
+++ b/numpy/typing/tests/data/reveal/testing.pyi
@@ -21,8 +21,8 @@ FT = TypeVar("FT", bound=Callable[..., Any])
 def func() -> int: ...
 
 def func2(
-    x: npt.NDArray[np.number[Any]],
-    y: npt.NDArray[np.number[Any]],
+    x: npt.NDArray[np.number],
+    y: npt.NDArray[np.number],
 ) -> npt.NDArray[np.bool]: ...
 
 assert_type(np.testing.KnownFailureException(), np.testing.KnownFailureException)
diff --git a/numpy/typing/tests/data/reveal/twodim_base.pyi b/numpy/typing/tests/data/reveal/twodim_base.pyi
index df5e258e7896..7e9563a38611 100644
--- a/numpy/typing/tests/data/reveal/twodim_base.pyi
+++ b/numpy/typing/tests/data/reveal/twodim_base.pyi
@@ -7,7 +7,7 @@ _ScalarT = TypeVar("_ScalarT", bound=np.generic)
 
 def func1(ar: npt.NDArray[_ScalarT], a: int) -> npt.NDArray[_ScalarT]: ...
 
-def func2(ar: npt.NDArray[np.number[Any]], a: str) -> npt.NDArray[np.float64]: ...
+def func2(ar: npt.NDArray[np.number], a: str) -> npt.NDArray[np.float64]: ...
 
 AR_b: npt.NDArray[np.bool]
 AR_u: npt.NDArray[np.uint64]
@@ -45,11 +45,11 @@ assert_type(np.tril(AR_LIKE_b, k=0), npt.NDArray[Any])
 assert_type(np.triu(AR_b), npt.NDArray[np.bool])
 assert_type(np.triu(AR_LIKE_b, k=0), npt.NDArray[Any])
 
-assert_type(np.vander(AR_b), npt.NDArray[np.signedinteger[Any]])
-assert_type(np.vander(AR_u), npt.NDArray[np.signedinteger[Any]])
-assert_type(np.vander(AR_i, N=2), npt.NDArray[np.signedinteger[Any]])
-assert_type(np.vander(AR_f, increasing=True), npt.NDArray[np.floating[Any]])
-assert_type(np.vander(AR_c), npt.NDArray[np.complexfloating[Any, Any]])
+assert_type(np.vander(AR_b), npt.NDArray[np.signedinteger])
+assert_type(np.vander(AR_u), npt.NDArray[np.signedinteger])
+assert_type(np.vander(AR_i, N=2), npt.NDArray[np.signedinteger])
+assert_type(np.vander(AR_f, increasing=True), npt.NDArray[np.floating])
+assert_type(np.vander(AR_c), npt.NDArray[np.complexfloating])
 assert_type(np.vander(AR_O), npt.NDArray[np.object_])
 
 assert_type(
diff --git a/numpy/typing/tests/data/reveal/ufunclike.pyi b/numpy/typing/tests/data/reveal/ufunclike.pyi
index 8dc4c8b1dbfd..a0ede60e0158 100644
--- a/numpy/typing/tests/data/reveal/ufunclike.pyi
+++ b/numpy/typing/tests/data/reveal/ufunclike.pyi
@@ -11,10 +11,10 @@ AR_LIKE_O: list[np.object_]
 
 AR_U: npt.NDArray[np.str_]
 
-assert_type(np.fix(AR_LIKE_b), npt.NDArray[np.floating[Any]])
-assert_type(np.fix(AR_LIKE_u), npt.NDArray[np.floating[Any]])
-assert_type(np.fix(AR_LIKE_i), npt.NDArray[np.floating[Any]])
-assert_type(np.fix(AR_LIKE_f), npt.NDArray[np.floating[Any]])
+assert_type(np.fix(AR_LIKE_b), npt.NDArray[np.floating])
+assert_type(np.fix(AR_LIKE_u), npt.NDArray[np.floating])
+assert_type(np.fix(AR_LIKE_i), npt.NDArray[np.floating])
+assert_type(np.fix(AR_LIKE_f), npt.NDArray[np.floating])
 assert_type(np.fix(AR_LIKE_O), npt.NDArray[np.object_])
 assert_type(np.fix(AR_LIKE_f, out=AR_U), npt.NDArray[np.str_])
 

From 625a1b149b27d5d5f2dbab61814612a31469b0b3 Mon Sep 17 00:00:00 2001
From: Hin-Tak Leung 
Date: Sat, 26 Apr 2025 16:22:44 +0100
Subject: [PATCH 099/202] ENH: Provide Windows 11 ARM64 wheels (#22530)

This is mostly adapting and duplicating how the 32-bit no-OpenBLAS
wheels are built, to make ARM64 wheels.

The mamba-org/setup-micromamba github action reports "win_arm64" as
unsupported for installation of anaconda-client at the moment.

Beyond that, a number of tests need to be skipped. They are in
three categories:
    - Meson outside of the msdevshell github action does not seems
      to be able to find the MSVC linker. (Possibly missing some PATH env)
    - No "checks" modules in win-arm64 (yet)
    - Mingw GNU objdump does not understand arm64 dll format (yet) to
      to generate import libraries.

closes #22530
---
 .github/workflows/wheels.yml                  | 11 +++++++++
 .github/workflows/windows.yml                 | 22 ++++++++++++------
 numpy/_core/tests/test_array_interface.py     |  4 ++++
 numpy/_core/tests/test_cython.py              |  4 ++++
 numpy/_core/tests/test_limited_api.py         |  2 ++
 numpy/_core/tests/test_mem_policy.py          |  3 +++
 numpy/distutils/mingw32ccompiler.py           | 23 +++++++++++++++++++
 .../distutils/tests/test_mingw32ccompiler.py  |  2 ++
 numpy/random/tests/test_extending.py          |  1 +
 pyproject.toml                                |  5 ++++
 tools/wheels/cibw_before_build.sh             |  3 +++
 11 files changed, 73 insertions(+), 7 deletions(-)

diff --git a/.github/workflows/wheels.yml b/.github/workflows/wheels.yml
index 159ffc4f4131..1da2c46ebe94 100644
--- a/.github/workflows/wheels.yml
+++ b/.github/workflows/wheels.yml
@@ -91,11 +91,15 @@ jobs:
           - [macos-14, macosx_arm64, accelerate]  # always use accelerate
           - [windows-2019, win_amd64, ""]
           - [windows-2019, win32, ""]
+          - [windows-11-arm, win_arm64, ""]
         python: ["cp311", "cp312", "cp313", "cp313t", "pp311"]
         exclude:
           # Don't build PyPy 32-bit windows
           - buildplat: [windows-2019, win32, ""]
             python: "pp311"
+          # Don't build PyPy arm64 windows
+          - buildplat: [windows-11-arm, win_arm64, ""]
+            python: "pp311"
           # No PyPy on musllinux images
           - buildplat: [ ubuntu-22.04, musllinux_x86_64, "" ]
             python: "pp311"
@@ -121,6 +125,12 @@ jobs:
         with:
           architecture: 'x86'
 
+      - name: Setup MSVC arm64
+        if: ${{ matrix.buildplat[1] == 'win_arm64' }}
+        uses: bus1/cabuild/action/msdevshell@e22aba57d6e74891d059d66501b6b5aed8123c4d  # v1
+        with:
+          architecture: 'arm64'
+
       - name: pkg-config-for-win
         run: |
           choco install -y --no-progress --stoponfirstfailure --checksum 6004DF17818F5A6DBF19CB335CC92702 pkgconfiglite
@@ -181,6 +191,7 @@ jobs:
           path: ./wheelhouse/*.whl
 
       - uses: mamba-org/setup-micromamba@0dea6379afdaffa5d528b3d1dabc45da37f443fc
+        if: ${{ matrix.buildplat[1] != 'win_arm64' }} # unsupported platform at the moment
         with:
           # for installation of anaconda-client, required for upload to
           # anaconda.org
diff --git a/.github/workflows/windows.yml b/.github/workflows/windows.yml
index 985d7d9c6d6a..d5242a22024e 100644
--- a/.github/workflows/windows.yml
+++ b/.github/workflows/windows.yml
@@ -96,9 +96,17 @@ jobs:
       run: |
         spin test -- --timeout=600 --durations=10
 
-  msvc_32bit_python_no_openblas:
-    name: MSVC, 32-bit Python, no BLAS
-    runs-on: windows-2019
+  msvc_python_no_openblas:
+    name: MSVC, ${{ matrix.architecture }} Python , no BLAS
+    runs-on: ${{ matrix.os }}
+    strategy:
+      fail-fast: false
+      matrix:
+        include:
+          - os: windows-2019
+            architecture: x86
+          - os: windows-11-arm
+            architecture: arm64
     # To enable this job on a fork, comment out:
     if: github.repository == 'numpy/numpy'
     steps:
@@ -109,16 +117,16 @@ jobs:
           fetch-tags: true
           persist-credentials: false
 
-      - name: Setup Python (32-bit)
+      - name: Setup Python
         uses: actions/setup-python@a26af69be951a213d495a4c3e4e4022e16d87065 # v5.6.0
         with:
           python-version: '3.11'
-          architecture: 'x86'
+          architecture: ${{ matrix.architecture }}
 
-      - name: Setup MSVC (32-bit)
+      - name: Setup MSVC
         uses: bus1/cabuild/action/msdevshell@e22aba57d6e74891d059d66501b6b5aed8123c4d  # v1
         with:
-          architecture: 'x86'
+          architecture: ${{ matrix.architecture }}
 
       - name: Build and install
         run: |
diff --git a/numpy/_core/tests/test_array_interface.py b/numpy/_core/tests/test_array_interface.py
index 1917c8fecafe..a044c883bb26 100644
--- a/numpy/_core/tests/test_array_interface.py
+++ b/numpy/_core/tests/test_array_interface.py
@@ -2,6 +2,8 @@
 import pytest
 import numpy as np
 from numpy.testing import extbuild, IS_WASM, IS_EDITABLE
+import sysconfig
+
 
 
 @pytest.fixture
@@ -123,6 +125,8 @@ def get_module(tmp_path):
         pass
 
     # if it does not exist, build and load it
+    if sysconfig.get_platform() == "win-arm64":
+        pytest.skip("Meson unable to find MSVC linker on win-arm64")
     return extbuild.build_and_import_extension('array_interface_testing',
                                                functions,
                                                prologue=prologue,
diff --git a/numpy/_core/tests/test_cython.py b/numpy/_core/tests/test_cython.py
index 81ddc63258c2..fda70b9ac79c 100644
--- a/numpy/_core/tests/test_cython.py
+++ b/numpy/_core/tests/test_cython.py
@@ -3,6 +3,7 @@
 import subprocess
 import sys
 import pytest
+import sysconfig
 
 import numpy as np
 from numpy.testing import assert_array_equal, IS_WASM, IS_EDITABLE
@@ -53,6 +54,8 @@ def install_temp(tmpdir_factory):
         subprocess.check_call(["meson", "--version"])
     except FileNotFoundError:
         pytest.skip("No usable 'meson' found")
+    if sysconfig.get_platform() == "win-arm64":
+        pytest.skip("Meson unable to find MSVC linker on win-arm64")
     if sys.platform == "win32":
         subprocess.check_call(["meson", "setup",
                                "--buildtype=release",
@@ -341,6 +344,7 @@ def test_npystring_allocators_other_dtype(install_temp):
     assert checks.npystring_allocators_other_types(arr1, arr2) == 0
 
 
+@pytest.mark.skipif(sysconfig.get_platform() == 'win-arm64', reason='no checks module on win-arm64')
 def test_npy_uintp_type_enum():
     import checks
     assert checks.check_npy_uintp_type_enum()
diff --git a/numpy/_core/tests/test_limited_api.py b/numpy/_core/tests/test_limited_api.py
index 51bed1d77561..58f2b5ce050d 100644
--- a/numpy/_core/tests/test_limited_api.py
+++ b/numpy/_core/tests/test_limited_api.py
@@ -52,6 +52,8 @@ def install_temp(tmpdir_factory):
         subprocess.check_call(["meson", "--version"])
     except FileNotFoundError:
         pytest.skip("No usable 'meson' found")
+    if sysconfig.get_platform() == "win-arm64":
+        pytest.skip("Meson unable to find MSVC linker on win-arm64")
     if sys.platform == "win32":
         subprocess.check_call(["meson", "setup",
                                "--werror",
diff --git a/numpy/_core/tests/test_mem_policy.py b/numpy/_core/tests/test_mem_policy.py
index 9846f89c404c..8d09a9ded659 100644
--- a/numpy/_core/tests/test_mem_policy.py
+++ b/numpy/_core/tests/test_mem_policy.py
@@ -3,6 +3,7 @@
 import os
 import sys
 import threading
+import sysconfig
 
 import pytest
 
@@ -220,6 +221,8 @@ def get_module(tmp_path):
     except ImportError:
         pass
     # if it does not exist, build and load it
+    if sysconfig.get_platform() == "win-arm64":
+        pytest.skip("Meson unable to find MSVC linker on win-arm64")
     return extbuild.build_and_import_extension('mem_policy',
                                                functions,
                                                prologue=prologue,
diff --git a/numpy/distutils/mingw32ccompiler.py b/numpy/distutils/mingw32ccompiler.py
index 2599a9e9a807..944ba2d03b33 100644
--- a/numpy/distutils/mingw32ccompiler.py
+++ b/numpy/distutils/mingw32ccompiler.py
@@ -262,6 +262,7 @@ def generate_def(dll, dfile):
 def find_dll(dll_name):
 
     arch = {'AMD64' : 'amd64',
+            'ARM64' : 'arm64',
             'Intel' : 'x86'}[get_build_architecture()]
 
     def _find_dll_in_winsxs(dll_name):
@@ -351,6 +352,8 @@ def build_import_library():
     arch = get_build_architecture()
     if arch == 'AMD64':
         return _build_import_library_amd64()
+    if arch == 'ARM64':
+        return _build_import_library_arm64()
     elif arch == 'Intel':
         return _build_import_library_x86()
     else:
@@ -412,6 +415,26 @@ def _build_import_library_amd64():
     cmd = ['dlltool', '-d', def_file, '-l', out_file]
     subprocess.check_call(cmd)
 
+def _build_import_library_arm64():
+    out_exists, out_file = _check_for_import_lib()
+    if out_exists:
+        log.debug('Skip building import library: "%s" exists', out_file)
+        return
+
+    # get the runtime dll for which we are building import library
+    dll_file = find_python_dll()
+    log.info('Building import library (arch=ARM64): "%s" (from %s)' %
+             (out_file, dll_file))
+
+    # generate symbol list from this library
+    def_name = "python%d%d.def" % tuple(sys.version_info[:2])
+    def_file = os.path.join(sys.prefix, 'libs', def_name)
+    generate_def(dll_file, def_file)
+
+    # generate import library from this symbol list
+    cmd = ['dlltool', '-d', def_file, '-l', out_file]
+    subprocess.check_call(cmd)
+
 def _build_import_library_x86():
     """ Build the import libraries for Mingw32-gcc on Windows
     """
diff --git a/numpy/distutils/tests/test_mingw32ccompiler.py b/numpy/distutils/tests/test_mingw32ccompiler.py
index 19b19450fc8c..c4eac7b72de1 100644
--- a/numpy/distutils/tests/test_mingw32ccompiler.py
+++ b/numpy/distutils/tests/test_mingw32ccompiler.py
@@ -3,6 +3,7 @@
 import sys
 import pytest
 import os
+import sysconfig
 
 from numpy.distutils import mingw32ccompiler
 
@@ -10,6 +11,7 @@
 @pytest.mark.skipif(sys.platform != 'win32', reason='win32 only test')
 @pytest.mark.skipif(not os.path.exists(os.path.join(sys.prefix, 'libs')),
                     reason="test requires mingw library layout")
+@pytest.mark.skipif(sysconfig.get_platform() == 'win-arm64', reason='mingw GNU objdump does not understand arm64 binary format yet')
 def test_build_import():
     '''Test the mingw32ccompiler.build_import_library, which builds a
     `python.a` from the MSVC `python.lib`
diff --git a/numpy/random/tests/test_extending.py b/numpy/random/tests/test_extending.py
index 608f58756289..86cbefcbf2ed 100644
--- a/numpy/random/tests/test_extending.py
+++ b/numpy/random/tests/test_extending.py
@@ -54,6 +54,7 @@
 )
 @pytest.mark.skipif(IS_WASM, reason="Can't start subprocess")
 @pytest.mark.skipif(cython is None, reason="requires cython")
+@pytest.mark.skipif(sysconfig.get_platform() == 'win-arm64', reason='meson not working on win-arm64')
 @pytest.mark.slow
 def test_cython(tmp_path):
     import glob
diff --git a/pyproject.toml b/pyproject.toml
index eb7015acc347..b62d71cbba73 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -188,6 +188,11 @@ select = "*-win32"
 config-settings = "setup-args=--vsenv setup-args=-Dallow-noblas=true build-dir=build"
 repair-wheel-command = ""
 
+[[tool.cibuildwheel.overrides]]
+select = "*-win_arm64"
+config-settings = "setup-args=--vsenv setup-args=-Dallow-noblas=true build-dir=build"
+repair-wheel-command = ""
+
 [[tool.cibuildwheel.overrides]]
 select = "*pyodide*"
 before-test = "pip install -r {project}/requirements/emscripten_test_requirements.txt"
diff --git a/tools/wheels/cibw_before_build.sh b/tools/wheels/cibw_before_build.sh
index e2f464d32a2a..c8d119b1b39f 100644
--- a/tools/wheels/cibw_before_build.sh
+++ b/tools/wheels/cibw_before_build.sh
@@ -22,6 +22,9 @@ fi
 if [[ $(python -c"import sys; print(sys.maxsize)") < $(python -c"import sys; print(2**33)") ]]; then
     echo "No BLAS used for 32-bit wheels"
     export INSTALL_OPENBLAS=false
+elif [[ $(python -c"import sysconfig; print(sysconfig.get_platform())") == "win-arm64" ]]; then
+    echo "No BLAS used for ARM64 wheels"
+    export INSTALL_OPENBLAS=false
 elif [ -z $INSTALL_OPENBLAS ]; then
     # the macos_arm64 build might not set this variable
     export INSTALL_OPENBLAS=true

From b6d83ef49e0a2d5d74b62153b4af3e211f2d68a0 Mon Sep 17 00:00:00 2001
From: Hin-Tak Leung 
Date: Sat, 26 Apr 2025 17:03:02 +0100
Subject: [PATCH 100/202] MAINT: Removing extra blank line mistakenly added
 earlier.

---
 numpy/_core/tests/test_array_interface.py | 1 -
 1 file changed, 1 deletion(-)

diff --git a/numpy/_core/tests/test_array_interface.py b/numpy/_core/tests/test_array_interface.py
index a044c883bb26..ed56f7e79daf 100644
--- a/numpy/_core/tests/test_array_interface.py
+++ b/numpy/_core/tests/test_array_interface.py
@@ -5,7 +5,6 @@
 import sysconfig
 
 
-
 @pytest.fixture
 def get_module(tmp_path):
     """ Some codes to generate data and manage temporary buffers use when

From d054ef304ce96cd29fbed85a4b89eb150e0cb0b9 Mon Sep 17 00:00:00 2001
From: Hin-Tak Leung 
Date: Sat, 26 Apr 2025 17:11:39 +0100
Subject: [PATCH 101/202] MAINT: Better / more uniform Meson related skip
 message

---
 numpy/random/tests/test_extending.py | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/numpy/random/tests/test_extending.py b/numpy/random/tests/test_extending.py
index 86cbefcbf2ed..dad9b10449d6 100644
--- a/numpy/random/tests/test_extending.py
+++ b/numpy/random/tests/test_extending.py
@@ -54,7 +54,7 @@
 )
 @pytest.mark.skipif(IS_WASM, reason="Can't start subprocess")
 @pytest.mark.skipif(cython is None, reason="requires cython")
-@pytest.mark.skipif(sysconfig.get_platform() == 'win-arm64', reason='meson not working on win-arm64')
+@pytest.mark.skipif(sysconfig.get_platform() == 'win-arm64', reason='Meson unable to find MSVC linker on win-arm64')
 @pytest.mark.slow
 def test_cython(tmp_path):
     import glob

From fb50a1227dd005004d8f838f07ba60f25c4da3a6 Mon Sep 17 00:00:00 2001
From: Marco Edward Gorelli 
Date: Sat, 26 Apr 2025 18:56:44 +0200
Subject: [PATCH 102/202] TYP: Fix type annotations for ``np.ma.nomask`` and
 ``np.ma.MaskType`` (#28831)

---
 numpy/ma/core.pyi                     | 4 ++--
 numpy/typing/tests/data/reveal/ma.pyi | 6 +++++-
 2 files changed, 7 insertions(+), 3 deletions(-)

diff --git a/numpy/ma/core.pyi b/numpy/ma/core.pyi
index 6ce080ada9fb..555a722c3b7a 100644
--- a/numpy/ma/core.pyi
+++ b/numpy/ma/core.pyi
@@ -230,8 +230,8 @@ _ScalarT_co = TypeVar("_ScalarT_co", bound=generic)
 # A subset of `MaskedArray` that can be parametrized w.r.t. `np.generic`
 _MaskedArray: TypeAlias = MaskedArray[_Shape, dtype[_ScalarT]]
 
-MaskType = bool
-nomask: bool
+MaskType = bool_
+nomask: bool_[Literal[False]]
 
 class MaskedArrayFutureWarning(FutureWarning): ...
 class MAError(Exception): ...
diff --git a/numpy/typing/tests/data/reveal/ma.pyi b/numpy/typing/tests/data/reveal/ma.pyi
index 8c49d989c1ca..4a40a8d536a2 100644
--- a/numpy/typing/tests/data/reveal/ma.pyi
+++ b/numpy/typing/tests/data/reveal/ma.pyi
@@ -1,5 +1,5 @@
 from datetime import datetime, timedelta
-from typing import Any, TypeAlias, TypeVar, assert_type
+from typing import Any, Literal, TypeAlias, TypeVar, assert_type
 
 import numpy as np
 from numpy import dtype, generic
@@ -280,3 +280,7 @@ assert_type(np.ma.allequal(AR_f4, MAR_f4, fill_value=False), bool)
 assert_type(np.ma.allclose(AR_f4, MAR_f4), bool)
 assert_type(np.ma.allclose(AR_f4, MAR_f4, masked_equal=False), bool)
 assert_type(np.ma.allclose(AR_f4, MAR_f4, rtol=.4, atol=.3), bool)
+
+assert_type(np.ma.nomask, np.bool[Literal[False]])
+# https://github.com/python/mypy/issues/18974
+assert_type(np.ma.MaskType, type[np.bool])  # type: ignore[assert-type]

From 1d261ff4466f67bbb9da10f31cd15b56fa12ef58 Mon Sep 17 00:00:00 2001
From: Sayed Adel 
Date: Sat, 26 Apr 2025 19:29:36 +0300
Subject: [PATCH 103/202] Update vendor-meson to fix module_feature conflicts
 arguments bug

Fix incorrect handling of the compiler arguments 'conflicts' that
was causing failures when detecting asmid instructions at compile time on
aarch32 platforms.
---
 vendored-meson/meson | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/vendored-meson/meson b/vendored-meson/meson
index 0d93515fb826..7300f5fd4c1c 160000
--- a/vendored-meson/meson
+++ b/vendored-meson/meson
@@ -1 +1 @@
-Subproject commit 0d93515fb826440d19707eee47fd92655fe2f166
+Subproject commit 7300f5fd4c1c8b0406faeec4cc631f11f1ea324c

From f70238009766e1f4755d915f015b1bb5337f4c67 Mon Sep 17 00:00:00 2001
From: Marco Edward Gorelli 
Date: Sat, 26 Apr 2025 20:00:52 +0200
Subject: [PATCH 104/202] TYP: Type ``np.ma.is_mask`` (#28833)

---
 numpy/ma/core.pyi                     |  8 ++++++--
 numpy/typing/tests/data/reveal/ma.pyi | 10 ++++++++++
 2 files changed, 16 insertions(+), 2 deletions(-)

diff --git a/numpy/ma/core.pyi b/numpy/ma/core.pyi
index 555a722c3b7a..0ec6e826d2f3 100644
--- a/numpy/ma/core.pyi
+++ b/numpy/ma/core.pyi
@@ -5,7 +5,7 @@ from collections.abc import Sequence
 from typing import Any, Literal, SupportsIndex, TypeAlias, TypeVar, overload
 
 from _typeshed import Incomplete
-from typing_extensions import deprecated
+from typing_extensions import TypeIs, deprecated
 
 import numpy as np
 from numpy import (
@@ -341,7 +341,11 @@ def getmask(a): ...
 get_mask = getmask
 
 def getmaskarray(arr): ...
-def is_mask(m): ...
+
+# It's sufficient for `m` to have dtype with type: `type[np.bool_]`,
+# which isn't necessarily a ndarray. Please open an issue if this causes issues.
+def is_mask(m: object) -> TypeIs[NDArray[bool_]]: ...
+
 def make_mask(m, copy=..., shrink=..., dtype=...): ...
 def make_mask_none(newshape, dtype=...): ...
 def mask_or(m1, m2, copy=..., shrink=...): ...
diff --git a/numpy/typing/tests/data/reveal/ma.pyi b/numpy/typing/tests/data/reveal/ma.pyi
index 4a40a8d536a2..e552b3a99897 100644
--- a/numpy/typing/tests/data/reveal/ma.pyi
+++ b/numpy/typing/tests/data/reveal/ma.pyi
@@ -10,6 +10,7 @@ MaskedNDArray: TypeAlias = np.ma.MaskedArray[_Shape, dtype[_ScalarT_co]]
 
 class MaskedNDArraySubclass(MaskedNDArray[np.complex128]): ...
 
+AR_b: NDArray[np.bool]
 AR_f4: NDArray[np.float32]
 AR_dt64: NDArray[np.datetime64]
 AR_td64: NDArray[np.timedelta64]
@@ -281,6 +282,15 @@ assert_type(np.ma.allclose(AR_f4, MAR_f4), bool)
 assert_type(np.ma.allclose(AR_f4, MAR_f4, masked_equal=False), bool)
 assert_type(np.ma.allclose(AR_f4, MAR_f4, rtol=.4, atol=.3), bool)
 
+assert_type(np.ma.is_mask(MAR_1d), bool)
+assert_type(np.ma.is_mask(AR_b), bool)
+
+def func(x: object) -> None:
+    if np.ma.is_mask(x):
+        assert_type(x, NDArray[np.bool])
+    else:
+        assert_type(x, object)
+
 assert_type(np.ma.nomask, np.bool[Literal[False]])
 # https://github.com/python/mypy/issues/18974
 assert_type(np.ma.MaskType, type[np.bool])  # type: ignore[assert-type]

From 1923b383077b29d2c3a9d78681e752b95ce5e9f7 Mon Sep 17 00:00:00 2001
From: Marco Edward Gorelli 
Date: Sun, 27 Apr 2025 00:24:02 +0100
Subject: [PATCH 105/202] TYP: Type ``np.ma.getmask`` (#28832)

---
 numpy/ma/core.pyi                     | 9 ++++++++-
 numpy/typing/tests/data/reveal/ma.pyi | 9 +++++++++
 2 files changed, 17 insertions(+), 1 deletion(-)

diff --git a/numpy/ma/core.pyi b/numpy/ma/core.pyi
index 0ec6e826d2f3..71652e047905 100644
--- a/numpy/ma/core.pyi
+++ b/numpy/ma/core.pyi
@@ -337,7 +337,14 @@ fmod: _DomainedBinaryOperation
 mod: _DomainedBinaryOperation
 
 def make_mask_descr(ndtype): ...
-def getmask(a): ...
+
+@overload
+def getmask(a: _ScalarLike_co) -> bool_: ...
+@overload
+def getmask(a: MaskedArray[_ShapeT_co, Any]) -> np.ndarray[_ShapeT_co, dtype[bool_]] | bool_: ...
+@overload
+def getmask(a: ArrayLike) -> NDArray[bool_] | bool_: ...
+
 get_mask = getmask
 
 def getmaskarray(arr): ...
diff --git a/numpy/typing/tests/data/reveal/ma.pyi b/numpy/typing/tests/data/reveal/ma.pyi
index e552b3a99897..5c1b04a03718 100644
--- a/numpy/typing/tests/data/reveal/ma.pyi
+++ b/numpy/typing/tests/data/reveal/ma.pyi
@@ -30,6 +30,7 @@ MAR_V: MaskedNDArray[np.void]
 MAR_subclass: MaskedNDArraySubclass
 
 MAR_1d: np.ma.MaskedArray[tuple[int], np.dtype]
+MAR_2d_f4: np.ma.MaskedArray[tuple[int, int], np.dtype[np.float32]]
 
 b: np.bool
 f4: np.float32
@@ -282,6 +283,14 @@ assert_type(np.ma.allclose(AR_f4, MAR_f4), bool)
 assert_type(np.ma.allclose(AR_f4, MAR_f4, masked_equal=False), bool)
 assert_type(np.ma.allclose(AR_f4, MAR_f4, rtol=.4, atol=.3), bool)
 
+assert_type(np.ma.getmask(MAR_f4), NDArray[np.bool] | np.bool)
+# PyRight detects this one correctly, but mypy doesn't:
+# `Revealed type is "Union[numpy.ndarray[Any, Any], numpy.bool[Any]]"`
+assert_type(np.ma.getmask(MAR_1d), np.ndarray[tuple[int], np.dtype[np.bool]] | np.bool)  # type: ignore[assert-type]
+assert_type(np.ma.getmask(MAR_2d_f4), np.ndarray[tuple[int, int], np.dtype[np.bool]] | np.bool)
+assert_type(np.ma.getmask([1,2]), NDArray[np.bool] | np.bool)
+assert_type(np.ma.getmask(np.int64(1)), np.bool)
+
 assert_type(np.ma.is_mask(MAR_1d), bool)
 assert_type(np.ma.is_mask(AR_b), bool)
 

From 48793d506ff8dac9d9440e64bfe27415ee57258f Mon Sep 17 00:00:00 2001
From: Dimitri Papadopoulos
 <3234522+DimitriPapadopoulos@users.noreply.github.com>
Date: Sat, 19 Apr 2025 10:49:11 +0200
Subject: [PATCH 106/202] MNT: Document ignored ruff rules

---
 ruff.toml | 24 ++++++++++++------------
 1 file changed, 12 insertions(+), 12 deletions(-)

diff --git a/ruff.toml b/ruff.toml
index 56ac820ce23d..d01ff1b5dd21 100644
--- a/ruff.toml
+++ b/ruff.toml
@@ -28,19 +28,19 @@ extend-select = [
 ignore = [
     "F",      # TODO: enable Pyflakes rules
     "PIE790", # Unnecessary `pass` statement
-    "E241",
-    "E251",
-    "E265",
-    "E266",
-    "E302",
-    "E402",
+    "E241",   # Multiple spaces after comma
+    "E251",   # Unexpected spaces around keyword / parameter equals
+    "E265",   # Block comment should start with `# `
+    "E266",   # Too many leading `#` before block comment
+    "E302",   # TODO: Expected 2 blank lines, found 1
+    "E402",   # Module level import not at top of file
     "E501",   # TODO: Line too long
-    "E712",
-    "E721",
-    "E731",
-    "E741",
-    "UP015", # Unnecessary mode argument
-    "UP031", # TODO: Use format specifiers instead of percent format
+    "E712",   # Avoid equality comparisons to `True` or `False`
+    "E721",   # TODO: Use `is` and `is not` for type comparisons, or `isinstance()` for isinstance check
+    "E731",   # Do not assign a `lambda` expression, use a `def`
+    "E741",   # Ambiguous variable name
+    "UP015",  # Unnecessary mode argument
+    "UP031",  # TODO: Use format specifiers instead of percent format
 ]
 
 [lint.per-file-ignores]

From 45be942c22301158328fdbee4fbae73914c71794 Mon Sep 17 00:00:00 2001
From: Dimitri Papadopoulos
 <3234522+DimitriPapadopoulos@users.noreply.github.com>
Date: Sat, 19 Apr 2025 11:20:05 +0200
Subject: [PATCH 107/202] STY: Partially apply ruff/pycodestyle rule E241

Multiple spaces after comma

Do not apply this rule to tabular data, tables must remain aligned.
---
 benchmarks/benchmarks/bench_ufunc.py         |  2 +-
 benchmarks/benchmarks/common.py              |  4 +--
 numpy/_core/overrides.py                     |  2 +-
 numpy/_core/tests/test_arrayprint.py         |  2 +-
 numpy/_core/tests/test_indexing.py           |  4 +--
 numpy/_core/tests/test_regression.py         |  4 +--
 numpy/_core/tests/test_scalarmath.py         |  4 +--
 numpy/lib/tests/test_function_base.py        | 36 ++++++++++----------
 numpy/linalg/lapack_lite/clapack_scrub.py    | 16 ++++-----
 numpy/linalg/tests/test_regression.py        | 10 +++---
 numpy/ma/tests/test_extras.py                |  6 ++--
 numpy/matrixlib/tests/test_defmatrix.py      |  4 +--
 numpy/random/tests/test_generator_mt19937.py |  2 +-
 numpy/testing/_private/utils.py              |  2 +-
 numpy/tests/test_scripts.py                  |  2 +-
 tools/ci/push_docs_to_repo.py                |  2 +-
 16 files changed, 51 insertions(+), 51 deletions(-)

diff --git a/benchmarks/benchmarks/bench_ufunc.py b/benchmarks/benchmarks/bench_ufunc.py
index 926e04571402..ad1c2d3fad9f 100644
--- a/benchmarks/benchmarks/bench_ufunc.py
+++ b/benchmarks/benchmarks/bench_ufunc.py
@@ -432,7 +432,7 @@ def time_divide_scalar2_inplace(self, dtype):
 
 
 class CustomComparison(Benchmark):
-    params = (np.int8,  np.int16,  np.int32,  np.int64, np.uint8, np.uint16,
+    params = (np.int8, np.int16, np.int32, np.int64, np.uint8, np.uint16,
               np.uint32, np.uint64, np.float32, np.float64, np.bool)
     param_names = ['dtype']
 
diff --git a/benchmarks/benchmarks/common.py b/benchmarks/benchmarks/common.py
index bee012d4ab26..064255e185eb 100644
--- a/benchmarks/benchmarks/common.py
+++ b/benchmarks/benchmarks/common.py
@@ -20,14 +20,14 @@
 TYPES1 = [
     'int16', 'float16',
     'int32', 'float32',
-    'int64', 'float64',  'complex64',
+    'int64', 'float64', 'complex64',
     'complex128',
 ]
 
 DLPACK_TYPES = [
     'int16', 'float16',
     'int32', 'float32',
-    'int64', 'float64',  'complex64',
+    'int64', 'float64', 'complex64',
     'complex128', 'bool',
 ]
 
diff --git a/numpy/_core/overrides.py b/numpy/_core/overrides.py
index cb466408cd39..c73d8eb4c1c5 100644
--- a/numpy/_core/overrides.py
+++ b/numpy/_core/overrides.py
@@ -5,7 +5,7 @@
 from .._utils import set_module
 from .._utils._inspect import getargspec
 from numpy._core._multiarray_umath import (
-    add_docstring,  _get_implementing_args, _ArrayFunctionDispatcher)
+    add_docstring, _get_implementing_args, _ArrayFunctionDispatcher)
 
 
 ARRAY_FUNCTIONS = set()
diff --git a/numpy/_core/tests/test_arrayprint.py b/numpy/_core/tests/test_arrayprint.py
index 4b9da0ebb7c6..d31f29271e93 100644
--- a/numpy/_core/tests/test_arrayprint.py
+++ b/numpy/_core/tests/test_arrayprint.py
@@ -320,7 +320,7 @@ def test_structure_format_float(self):
         assert_equal(np.array2string(array_scalar), "(1., 2.12345679, 3.)")
 
     def test_unstructured_void_repr(self):
-        a = np.array([27, 91, 50, 75,  7, 65, 10,  8,
+        a = np.array([27, 91, 50, 75,   7, 65, 10,    8,
                       27, 91, 51, 49, 109, 82, 101, 100], dtype='u1').view('V8')
         assert_equal(repr(a[0]),
             r"np.void(b'\x1B\x5B\x32\x4B\x07\x41\x0A\x08')")
diff --git a/numpy/_core/tests/test_indexing.py b/numpy/_core/tests/test_indexing.py
index c9508bb03bdc..410a68b7efb4 100644
--- a/numpy/_core/tests/test_indexing.py
+++ b/numpy/_core/tests/test_indexing.py
@@ -219,7 +219,7 @@ def test_boolean_shape_mismatch(self):
     def test_boolean_indexing_onedim(self):
         # Indexing a 2-dimensional array with
         # boolean array of length one
-        a = np.array([[0.,  0.,  0.]])
+        a = np.array([[0., 0., 0.]])
         b = np.array([True], dtype=bool)
         assert_equal(a[b], a)
         # boolean assignment
@@ -643,7 +643,7 @@ def test_prepend_not_one(self):
         a = np.zeros(5)
 
         # Too large and not only ones.
-        assert_raises(ValueError, assign, a, s_[...],  np.ones((2, 1)))
+        assert_raises(ValueError, assign, a, s_[...], np.ones((2, 1)))
         assert_raises(ValueError, assign, a, s_[[1, 2, 3],], np.ones((2, 1)))
         assert_raises(ValueError, assign, a, s_[[[1], [2]],], np.ones((2, 2, 1)))
 
diff --git a/numpy/_core/tests/test_regression.py b/numpy/_core/tests/test_regression.py
index 30d66bb3cbe2..b8b539946909 100644
--- a/numpy/_core/tests/test_regression.py
+++ b/numpy/_core/tests/test_regression.py
@@ -171,7 +171,7 @@ def test_endian_where(self):
         net[2] = 0.605202
         max_net = net.max()
         test = np.where(net <= 0., max_net, net)
-        correct = np.array([0.60520202,  0.00458849,  0.60520202])
+        correct = np.array([0.60520202, 0.00458849, 0.60520202])
         assert_array_almost_equal(test, correct)
 
     def test_endian_recarray(self):
@@ -2046,7 +2046,7 @@ def test_unique_stable(self):
         # get consistent results
         v = np.array(([0] * 5 + [1] * 6 + [2] * 6) * 4)
         res = np.unique(v, return_index=True)
-        tgt = (np.array([0, 1, 2]), np.array([0,  5, 11]))
+        tgt = (np.array([0, 1, 2]), np.array([0, 5, 11]))
         assert_equal(res, tgt)
 
     def test_unicode_alloc_dealloc_match(self):
diff --git a/numpy/_core/tests/test_scalarmath.py b/numpy/_core/tests/test_scalarmath.py
index e9cac03c7a9b..1842f5edd08b 100644
--- a/numpy/_core/tests/test_scalarmath.py
+++ b/numpy/_core/tests/test_scalarmath.py
@@ -171,11 +171,11 @@ def test_blocked(self):
 
                 inp2[...] += np.arange(inp2.size, dtype=dt) + 1
                 assert_almost_equal(np.square(inp2),
-                                    np.multiply(inp2, inp2),  err_msg=msg)
+                                    np.multiply(inp2, inp2), err_msg=msg)
                 # skip true divide for ints
                 if dt != np.int32:
                     assert_almost_equal(np.reciprocal(inp2),
-                                        np.divide(1, inp2),  err_msg=msg)
+                                        np.divide(1, inp2), err_msg=msg)
 
                 inp1[...] = np.ones_like(inp1)
                 np.add(inp1, 2, out=out)
diff --git a/numpy/lib/tests/test_function_base.py b/numpy/lib/tests/test_function_base.py
index 653a0f068372..782068eac206 100644
--- a/numpy/lib/tests/test_function_base.py
+++ b/numpy/lib/tests/test_function_base.py
@@ -2413,7 +2413,7 @@ class TestCorrCoef:
 
     def test_non_array(self):
         assert_almost_equal(np.corrcoef([0, 1, 0], [1, 0, 1]),
-                            [[1., -1.], [-1.,  1.]])
+                            [[1., -1.], [-1., 1.]])
 
     def test_simple(self):
         tgt1 = corrcoef(self.A)
@@ -3401,10 +3401,10 @@ def test_scalar_q(self):
         x = np.arange(12).reshape(3, 4)
         assert_equal(np.percentile(x, 50), 5.5)
         assert_(np.isscalar(np.percentile(x, 50)))
-        r0 = np.array([4.,  5.,  6.,  7.])
+        r0 = np.array([4., 5., 6., 7.])
         assert_equal(np.percentile(x, 50, axis=0), r0)
         assert_equal(np.percentile(x, 50, axis=0).shape, r0.shape)
-        r1 = np.array([1.5,  5.5,  9.5])
+        r1 = np.array([1.5, 5.5, 9.5])
         assert_almost_equal(np.percentile(x, 50, axis=1), r1)
         assert_equal(np.percentile(x, 50, axis=1).shape, r1.shape)
 
@@ -3422,11 +3422,11 @@ def test_scalar_q(self):
         x = np.arange(12).reshape(3, 4)
         assert_equal(np.percentile(x, 50, method='lower'), 5.)
         assert_(np.isscalar(np.percentile(x, 50)))
-        r0 = np.array([4.,  5.,  6.,  7.])
+        r0 = np.array([4., 5., 6., 7.])
         c0 = np.percentile(x, 50, method='lower', axis=0)
         assert_equal(c0, r0)
         assert_equal(c0.shape, r0.shape)
-        r1 = np.array([1.,  5.,  9.])
+        r1 = np.array([1., 5., 9.])
         c1 = np.percentile(x, 50, method='lower', axis=1)
         assert_almost_equal(c1, r1)
         assert_equal(c1.shape, r1.shape)
@@ -3496,18 +3496,18 @@ def test_percentile_out(self, percentile, with_weights):
             percentile(x, (25, 50), axis=0, out=out, weights=weights), r0
         )
         assert_equal(out, r0)
-        r1 = np.array([[0.75,  4.75,  8.75], [1.5,  5.5,  9.5]])
+        r1 = np.array([[0.75, 4.75, 8.75], [1.5, 5.5, 9.5]])
         out = np.empty((2, 3))
         assert_equal(np.percentile(x, (25, 50), axis=1, out=out), r1)
         assert_equal(out, r1)
 
         # q.dim > 1, int
-        r0 = np.array([[0,  1,  2, 3], [4, 5, 6, 7]])
+        r0 = np.array([[0, 1, 2, 3], [4, 5, 6, 7]])
         out = np.empty((2, 4), dtype=x.dtype)
         c = np.percentile(x, (25, 50), method='lower', axis=0, out=out)
         assert_equal(c, r0)
         assert_equal(out, r0)
-        r1 = np.array([[0,  4,  8], [1,  5,  9]])
+        r1 = np.array([[0, 4, 8], [1, 5, 9]])
         out = np.empty((2, 3), dtype=x.dtype)
         c = np.percentile(x, (25, 50), method='lower', axis=1, out=out)
         assert_equal(c, r1)
@@ -3583,7 +3583,7 @@ def test_extended_axis(self):
 
         d = np.arange(3 * 5 * 7 * 11).reshape((3, 5, 7, 11))
         np.random.shuffle(d.ravel())
-        assert_equal(np.percentile(d, 25,  axis=(0, 1, 2))[0],
+        assert_equal(np.percentile(d, 25, axis=(0, 1, 2))[0],
                      np.percentile(d[:, :, :, 0].flatten(), 25))
         assert_equal(np.percentile(d, [10, 90], axis=(0, 1, 3))[:, 1],
                      np.percentile(d[:, :, 1, :].flatten(), [10, 90]))
@@ -3888,7 +3888,7 @@ def test_q_zero_one(self, method):
         # gh-24710
         arr = [10, 11, 12]
         quantile = np.quantile(arr, q = [0, 1], method=method)
-        assert_equal(quantile,  np.array([10, 12]))
+        assert_equal(quantile, np.array([10, 12]))
 
     @pytest.mark.parametrize("method", quantile_methods)
     def test_quantile_monotonic(self, method):
@@ -4217,7 +4217,7 @@ def test_basic(self):
         assert_equal(np.median(a0), 1)
         assert_allclose(np.median(a1), 0.5)
         assert_allclose(np.median(a2), 2.5)
-        assert_allclose(np.median(a2, axis=0), [1.5,  2.5,  3.5])
+        assert_allclose(np.median(a2, axis=0), [1.5, 2.5, 3.5])
         assert_equal(np.median(a2, axis=1), [1, 4])
         assert_allclose(np.median(a2, axis=None), 2.5)
 
@@ -4244,8 +4244,8 @@ def test_axis_keyword(self):
                 np.median(a, axis=ax)
             assert_array_equal(a, orig)
 
-        assert_allclose(np.median(a3, axis=0), [3,  4])
-        assert_allclose(np.median(a3.T, axis=1), [3,  4])
+        assert_allclose(np.median(a3, axis=0), [3, 4])
+        assert_allclose(np.median(a3.T, axis=1), [3, 4])
         assert_allclose(np.median(a3), 3.5)
         assert_allclose(np.median(a3, axis=None), 3.5)
         assert_allclose(np.median(a3.T), 3.5)
@@ -4261,16 +4261,16 @@ def test_overwrite_keyword(self):
         assert_allclose(np.median(a0.copy(), overwrite_input=True), 1)
         assert_allclose(np.median(a1.copy(), overwrite_input=True), 0.5)
         assert_allclose(np.median(a2.copy(), overwrite_input=True), 2.5)
-        assert_allclose(np.median(a2.copy(), overwrite_input=True, axis=0),
-                        [1.5,  2.5,  3.5])
+        assert_allclose(
+            np.median(a2.copy(), overwrite_input=True, axis=0), [1.5, 2.5, 3.5])
         assert_allclose(
             np.median(a2.copy(), overwrite_input=True, axis=1), [1, 4])
         assert_allclose(
             np.median(a2.copy(), overwrite_input=True, axis=None), 2.5)
         assert_allclose(
-            np.median(a3.copy(), overwrite_input=True, axis=0), [3,  4])
-        assert_allclose(np.median(a3.T.copy(), overwrite_input=True, axis=1),
-                        [3,  4])
+            np.median(a3.copy(), overwrite_input=True, axis=0), [3, 4])
+        assert_allclose(
+            np.median(a3.T.copy(), overwrite_input=True, axis=1), [3, 4])
 
         a4 = np.arange(3 * 4 * 5, dtype=np.float32).reshape((3, 4, 5))
         np.random.shuffle(a4.ravel())
diff --git a/numpy/linalg/lapack_lite/clapack_scrub.py b/numpy/linalg/lapack_lite/clapack_scrub.py
index 65231aed7998..1d903bd6409d 100644
--- a/numpy/linalg/lapack_lite/clapack_scrub.py
+++ b/numpy/linalg/lapack_lite/clapack_scrub.py
@@ -79,19 +79,19 @@ def endArgs(self, text):
     keep_ftnlen = (Str('ilaenv_') | Str('iparmq_') | Str('s_rnge')) + Str('(')
 
     lexicon = Lexicon([
-        (iofunctions,                           TEXT),
-        (keep_ftnlen,                           beginArgs),
+        (iofunctions,                                        TEXT),
+        (keep_ftnlen,                                        beginArgs),
         State('args', [
             (Str(')'),   endArgs),
             (Str('('),   beginArgs),
             (AnyChar,    TEXT),
         ]),
-        (cS + Re(r'[1-9][0-9]*L'),                IGNORE),
-        (cS + Str('ftnlen') + Opt(S + len_),          IGNORE),
-        (cS + sep_seq(['(', 'ftnlen', ')'], S) + S + digits,      IGNORE),
-        (Bol + Str('ftnlen ') + len_ + Str(';\n'),    IGNORE),
-        (cS + len_,                               TEXT),
-        (AnyChar,                               TEXT),
+        (cS + Re(r'[1-9][0-9]*L'),                           IGNORE),
+        (cS + Str('ftnlen') + Opt(S + len_),                 IGNORE),
+        (cS + sep_seq(['(', 'ftnlen', ')'], S) + S + digits, IGNORE),
+        (Bol + Str('ftnlen ') + len_ + Str(';\n'),           IGNORE),
+        (cS + len_,                                          TEXT),
+        (AnyChar,                                            TEXT),
     ])
 
 def scrubFtnlen(source):
diff --git a/numpy/linalg/tests/test_regression.py b/numpy/linalg/tests/test_regression.py
index 3949b0b9e66f..e8159fd570bf 100644
--- a/numpy/linalg/tests/test_regression.py
+++ b/numpy/linalg/tests/test_regression.py
@@ -40,9 +40,9 @@ def test_eigh_build(self):
         # Ticket 662.
         rvals = [68.60568999, 89.57756725, 106.67185574]
 
-        cov = array([[77.70273908,   3.51489954,  15.64602427],
-                     [3.51489954,  88.97013878, -1.07431931],
-                     [15.64602427, -1.07431931,  98.18223512]])
+        cov = array([[77.70273908,  3.51489954, 15.64602427],
+                     [ 3.51489954, 88.97013878, -1.07431931],
+                     [15.64602427, -1.07431931, 98.18223512]])
 
         vals, vecs = linalg.eigh(cov)
         assert_array_almost_equal(vals, rvals)
@@ -64,8 +64,8 @@ def test_norm_vector_badarg(self):
 
     def test_lapack_endian(self):
         # For bug #1482
-        a = array([[5.7998084, -2.1825367],
-                   [-2.1825367,   9.85910595]], dtype='>f8')
+        a = array([[ 5.7998084, -2.1825367],
+                   [-2.1825367,  9.85910595]], dtype='>f8')
         b = array(a, dtype='
Date: Sat, 19 Apr 2025 11:35:02 +0200
Subject: [PATCH 108/202] STY: Partially apply ruff/pycodestyle rule E251

Unexpected spaces around keyword / parameter equals

For now, do not modify large and consistent code blocks that use spaces on
purpose, mostly when the default values are arrays.
---
 benchmarks/benchmarks/bench_ufunc.py          |  2 +-
 numpy/_core/code_generators/generate_umath.py |  2 +-
 numpy/_core/tests/test_ufunc.py               |  2 +-
 numpy/_core/tests/test_umath_accuracy.py      |  2 +-
 numpy/f2py/auxfuncs.py                        |  2 +-
 numpy/f2py/tests/test_array_from_pyobj.py     |  2 +-
 numpy/f2py/tests/test_regression.py           |  2 +-
 numpy/lib/tests/test_function_base.py         | 12 ++++++------
 numpy/lib/tests/test_histograms.py            |  2 +-
 numpy/ma/extras.pyi                           |  8 ++++----
 numpy/ma/tests/test_core.py                   |  4 ++--
 tools/download-wheels.py                      |  2 +-
 tools/swig/test/setup.py                      | 16 ++++++++--------
 13 files changed, 29 insertions(+), 29 deletions(-)

diff --git a/benchmarks/benchmarks/bench_ufunc.py b/benchmarks/benchmarks/bench_ufunc.py
index ad1c2d3fad9f..4d9f3c9c8f61 100644
--- a/benchmarks/benchmarks/bench_ufunc.py
+++ b/benchmarks/benchmarks/bench_ufunc.py
@@ -342,7 +342,7 @@ def time_ufunc_small_array(self, ufuncname):
         self.f(self.array_5)
 
     def time_ufunc_small_array_inplace(self, ufuncname):
-        self.f(self.array_5, out = self.array_5)
+        self.f(self.array_5, out=self.array_5)
 
     def time_ufunc_small_int_array(self, ufuncname):
         self.f(self.array_int_3)
diff --git a/numpy/_core/code_generators/generate_umath.py b/numpy/_core/code_generators/generate_umath.py
index e9b7989afd28..b80a0a52ba36 100644
--- a/numpy/_core/code_generators/generate_umath.py
+++ b/numpy/_core/code_generators/generate_umath.py
@@ -1570,7 +1570,7 @@ def make_ufuncs(funcdict):
                 typenum=f"NPY_{english_upper(chartoname[c])}",
                 count=uf.nin + uf.nout,
                 name=name,
-                funcname = f"{english_upper(chartoname[c])}_{name}_indexed",
+                funcname=f"{english_upper(chartoname[c])}_{name}_indexed",
             ))
 
         mlist.append(r"""PyDict_SetItemString(dictionary, "%s", f);""" % name)
diff --git a/numpy/_core/tests/test_ufunc.py b/numpy/_core/tests/test_ufunc.py
index 0dbef44300b1..26844fabd437 100644
--- a/numpy/_core/tests/test_ufunc.py
+++ b/numpy/_core/tests/test_ufunc.py
@@ -2104,7 +2104,7 @@ def __rmul__(self, other):
     def test_array_wrap_array_priority(self):
         class ArrayPriorityBase(np.ndarray):
             @classmethod
-            def __array_wrap__(cls, array, context=None, return_scalar = False):
+            def __array_wrap__(cls, array, context=None, return_scalar=False):
                 return cls
 
         class ArrayPriorityMinus0(ArrayPriorityBase):
diff --git a/numpy/_core/tests/test_umath_accuracy.py b/numpy/_core/tests/test_umath_accuracy.py
index 0d3c99bf7d54..a0e0cbccc596 100644
--- a/numpy/_core/tests/test_umath_accuracy.py
+++ b/numpy/_core/tests/test_umath_accuracy.py
@@ -75,7 +75,7 @@ def test_validate_transcendentals(self):
                         assert_array_max_ulp(npfunc(inval), outval, maxulperr)
 
     @pytest.mark.skipif(IS_AVX512FP16,
-            reason = "SVML FP16 have slightly higher ULP errors")
+            reason="SVML FP16 have slightly higher ULP errors")
     @pytest.mark.parametrize("ufunc", UNARY_OBJECT_UFUNCS)
     def test_validate_fp16_transcendentals(self, ufunc):
         with np.errstate(all='ignore'):
diff --git a/numpy/f2py/auxfuncs.py b/numpy/f2py/auxfuncs.py
index 1adc2d6228c4..3c1b4500793b 100644
--- a/numpy/f2py/auxfuncs.py
+++ b/numpy/f2py/auxfuncs.py
@@ -923,7 +923,7 @@ def getuseblocks(pymod):
                 all_uses.extend([x for x in modblock.get("use").keys() if "__" not in x])
     return all_uses
 
-def process_f2cmap_dict(f2cmap_all, new_map, c2py_map, verbose = False):
+def process_f2cmap_dict(f2cmap_all, new_map, c2py_map, verbose=False):
     """
     Update the Fortran-to-C type mapping dictionary with new mappings and
     return a list of successfully mapped C types.
diff --git a/numpy/f2py/tests/test_array_from_pyobj.py b/numpy/f2py/tests/test_array_from_pyobj.py
index e0e366fb94a2..9bdd91f47638 100644
--- a/numpy/f2py/tests/test_array_from_pyobj.py
+++ b/numpy/f2py/tests/test_array_from_pyobj.py
@@ -33,7 +33,7 @@ def setup_module():
         src = [
             get_testdir() / "wrapmodule.c",
         ]
-        wrap = util.build_meson(src, module_name = "test_array_from_pyobj_ext")
+        wrap = util.build_meson(src, module_name="test_array_from_pyobj_ext")
 
 
 def flags_info(arr):
diff --git a/numpy/f2py/tests/test_regression.py b/numpy/f2py/tests/test_regression.py
index 7917d2fb6b7b..bf994ffa07a5 100644
--- a/numpy/f2py/tests/test_regression.py
+++ b/numpy/f2py/tests/test_regression.py
@@ -53,7 +53,7 @@ def ubound(xl, xh):
             return xh - xl + 1
         rval = self.module.foo(is_=xlow, ie_=xhigh,
                         arr=xvec[:ubound(xlow, xhigh)])
-        expval = np.arange(11, dtype = np.float32)
+        expval = np.arange(11, dtype=np.float32)
         assert np.allclose(rval, expval)
 
 
diff --git a/numpy/lib/tests/test_function_base.py b/numpy/lib/tests/test_function_base.py
index 782068eac206..97fec7071ad5 100644
--- a/numpy/lib/tests/test_function_base.py
+++ b/numpy/lib/tests/test_function_base.py
@@ -1962,7 +1962,7 @@ def f(x):
 
     def test_bad_input(self):
         with assert_raises(TypeError):
-            A = np.vectorize(pyfunc = 3)
+            A = np.vectorize(pyfunc=3)
 
     def test_no_keywords(self):
         with assert_raises(TypeError):
@@ -3887,7 +3887,7 @@ def test_quantile_preserve_int_type(self, dtype):
     def test_q_zero_one(self, method):
         # gh-24710
         arr = [10, 11, 12]
-        quantile = np.quantile(arr, q = [0, 1], method=method)
+        quantile = np.quantile(arr, q=[0, 1], method=method)
         assert_equal(quantile, np.array([10, 12]))
 
     @pytest.mark.parametrize("method", quantile_methods)
@@ -4163,10 +4163,10 @@ class TestLerp:
                                    min_value=0, max_value=1),
                       t1=st.floats(allow_nan=False, allow_infinity=False,
                                    min_value=0, max_value=1),
-                      a = st.floats(allow_nan=False, allow_infinity=False,
-                                    min_value=-1e300, max_value=1e300),
-                      b = st.floats(allow_nan=False, allow_infinity=False,
-                                    min_value=-1e300, max_value=1e300))
+                      a=st.floats(allow_nan=False, allow_infinity=False,
+                                  min_value=-1e300, max_value=1e300),
+                      b=st.floats(allow_nan=False, allow_infinity=False,
+                                  min_value=-1e300, max_value=1e300))
     def test_linear_interpolation_formula_monotonic(self, t0, t1, a, b):
         l0 = nfb._lerp(a, b, t0)
         l1 = nfb._lerp(a, b, t1)
diff --git a/numpy/lib/tests/test_histograms.py b/numpy/lib/tests/test_histograms.py
index 49ec7c34456f..bfb0248ebdcf 100644
--- a/numpy/lib/tests/test_histograms.py
+++ b/numpy/lib/tests/test_histograms.py
@@ -588,7 +588,7 @@ def test_simple_range(self):
             x3 = np.linspace(-100, -50, testlen)
             x = np.hstack((x1, x2, x3))
             for estimator, numbins in expectedResults.items():
-                a, b = np.histogram(x, estimator, range = (-20, 20))
+                a, b = np.histogram(x, estimator, range=(-20, 20))
                 msg = f"For the {estimator} estimator"
                 msg += f" with datasize of {testlen}"
                 assert_equal(len(a), numbins, err_msg=msg)
diff --git a/numpy/ma/extras.pyi b/numpy/ma/extras.pyi
index ba76f3517526..c3f9fcde4a0a 100644
--- a/numpy/ma/extras.pyi
+++ b/numpy/ma/extras.pyi
@@ -56,7 +56,7 @@ __all__ = [
 ]
 
 def count_masked(arr, axis=...): ...
-def masked_all(shape, dtype = ...): ...
+def masked_all(shape, dtype=...): ...
 def masked_all_like(arr): ...
 
 class _fromnxfunction:
@@ -96,8 +96,8 @@ def compress_nd(x, axis=...): ...
 def compress_rowcols(x, axis=...): ...
 def compress_rows(a): ...
 def compress_cols(a): ...
-def mask_rows(a, axis = ...): ...
-def mask_cols(a, axis = ...): ...
+def mask_rows(a, axis=...): ...
+def mask_cols(a, axis=...): ...
 def ediff1d(arr, to_end=..., to_begin=...): ...
 def unique(ar1, return_index=..., return_inverse=...): ...
 def intersect1d(ar1, ar2, assume_unique=...): ...
@@ -107,7 +107,7 @@ def isin(element, test_elements, assume_unique=..., invert=...): ...
 def union1d(ar1, ar2): ...
 def setdiff1d(ar1, ar2, assume_unique=...): ...
 def cov(x, y=..., rowvar=..., bias=..., allow_masked=..., ddof=...): ...
-def corrcoef(x, y=..., rowvar=..., bias = ..., allow_masked=..., ddof = ...): ...
+def corrcoef(x, y=..., rowvar=..., bias=..., allow_masked=..., ddof=...): ...
 
 class MAxisConcatenator(AxisConcatenator):
     @staticmethod
diff --git a/numpy/ma/tests/test_core.py b/numpy/ma/tests/test_core.py
index 280d94bc0fe8..f660123f394d 100644
--- a/numpy/ma/tests/test_core.py
+++ b/numpy/ma/tests/test_core.py
@@ -997,8 +997,8 @@ def test_mvoid_multidim_print(self):
         assert_(str(t_2d[0]) == "([[1, --], [--, 4]], 1.0)")
         assert_(repr(t_2d[0]) == "([[1, --], [--, 4]], 1.0)")
 
-        t_ne = masked_array(data=[(1, (1, 1))],
-                            mask=[(True, (True, False))],
+        t_ne = masked_array(data = [(1, (1, 1))],
+                            mask = [(True, (True, False))],
                             dtype = [('a', '/release/installers]")
     parser.add_argument(
         "-t", "--test",
-        action = 'store_true',
+        action='store_true',
         help="only list available wheels, do not download")
 
     args = parser.parse_args()
diff --git a/tools/swig/test/setup.py b/tools/swig/test/setup.py
index bc310043d82e..c925f358ec7b 100755
--- a/tools/swig/test/setup.py
+++ b/tools/swig/test/setup.py
@@ -46,16 +46,16 @@
                     )
 
 _Fortran = Extension("_Fortran",
-                    ["Fortran_wrap.cxx",
-                     "Fortran.cxx"],
-                    include_dirs = [numpy_include],
-                    )
+                     ["Fortran_wrap.cxx",
+                      "Fortran.cxx"],
+                     include_dirs = [numpy_include],
+                     )
 
 _Flat = Extension("_Flat",
-                    ["Flat_wrap.cxx",
-                     "Flat.cxx"],
-                    include_dirs = [numpy_include],
-                    )
+                  ["Flat_wrap.cxx",
+                   "Flat.cxx"],
+                  include_dirs = [numpy_include],
+                  )
 
 # NumyTypemapTests setup
 setup(name = "NumpyTypemapTests",

From 9d2bb785bf30145a42f201028eb452055c25528a Mon Sep 17 00:00:00 2001
From: Dimitri Papadopoulos
 <3234522+DimitriPapadopoulos@users.noreply.github.com>
Date: Sat, 19 Apr 2025 12:06:18 +0200
Subject: [PATCH 109/202] STY: Partially apply ruff/pycodestyle rule E265

Block comment should start with `# `

For now, keep commented out code as is.
---
 numpy/_core/code_generators/generate_umath.py | 22 ++++++------
 numpy/_core/records.py                        |  2 +-
 numpy/_core/tests/test_dtype.py               |  2 +-
 numpy/_core/tests/test_einsum.py              |  6 ++--
 numpy/_core/tests/test_indexing.py            |  2 +-
 numpy/_core/tests/test_multiarray.py          |  4 +--
 numpy/_core/tests/test_nditer.py              |  2 +-
 numpy/_core/tests/test_numeric.py             |  2 +-
 numpy/_core/tests/test_records.py             | 12 +++----
 numpy/_core/tests/test_regression.py          | 12 +++----
 numpy/_core/tests/test_scalarmath.py          |  6 ++--
 numpy/_core/tests/test_scalarprint.py         |  2 +-
 numpy/_core/tests/test_shape_base.py          |  4 +--
 numpy/_core/tests/test_umath.py               |  6 ++--
 numpy/_core/tests/test_umath_complex.py       |  4 +--
 numpy/conftest.py                             |  2 +-
 numpy/lib/_function_base_impl.py              |  4 +--
 numpy/lib/tests/test_format.py                |  6 ++--
 numpy/lib/tests/test_function_base.py         |  4 +--
 numpy/lib/tests/test_index_tricks.py          |  2 +-
 numpy/lib/tests/test_io.py                    |  2 +-
 numpy/linalg/tests/test_linalg.py             |  2 +-
 numpy/ma/core.py                              |  2 +-
 numpy/ma/tests/test_extras.py                 |  2 +-
 numpy/ma/tests/test_mrecords.py               |  4 +--
 numpy/ma/tests/test_old_ma.py                 |  2 +-
 numpy/polynomial/tests/test_chebyshev.py      | 34 +++++++++----------
 numpy/polynomial/tests/test_hermite.py        | 26 +++++++-------
 numpy/polynomial/tests/test_hermite_e.py      | 26 +++++++-------
 numpy/polynomial/tests/test_laguerre.py       | 26 +++++++-------
 numpy/polynomial/tests/test_legendre.py       | 26 +++++++-------
 numpy/polynomial/tests/test_polynomial.py     | 30 ++++++++--------
 numpy/testing/_private/utils.py               |  2 +-
 tools/swig/test/testSuperTensor.py            |  4 +--
 34 files changed, 147 insertions(+), 147 deletions(-)

diff --git a/numpy/_core/code_generators/generate_umath.py b/numpy/_core/code_generators/generate_umath.py
index b80a0a52ba36..35b5ad92ac82 100644
--- a/numpy/_core/code_generators/generate_umath.py
+++ b/numpy/_core/code_generators/generate_umath.py
@@ -259,16 +259,16 @@ def english_upper(s):
     return uppered
 
 
-#each entry in defdict is a Ufunc object.
+# each entry in defdict is a Ufunc object.
 
-#name: [string of chars for which it is defined,
-#       string of characters using func interface,
-#       tuple of strings giving funcs for data,
-#       (in, out), or (instr, outstr) giving the signature as character codes,
-#       identity,
-#       docstring,
-#       output specification (optional)
-#       ]
+# name: [string of chars for which it is defined,
+#        string of characters using func interface,
+#        tuple of strings giving funcs for data,
+#        (in, out), or (instr, outstr) giving the signature as character codes,
+#        identity,
+#        docstring,
+#        output specification (optional)
+#        ]
 
 chartoname = {
     '?': 'bool',
@@ -396,7 +396,7 @@ def english_upper(s):
           TD(O, f='PyNumber_Multiply'),
           indexed=intfltcmplx
           ),
-#'true_divide' : aliased to divide in umathmodule.c:initumath
+# 'true_divide' : aliased to divide in umathmodule.c:initumath
 'floor_divide':
     Ufunc(2, 1, None,  # One is only a unit to the right, not the left
           docstrings.get('numpy._core.umath.floor_divide'),
@@ -1382,7 +1382,7 @@ def indent(st, spaces):
     }
 }
 
-#for each name
+# for each name
 # 1) create functions, data, and signature
 # 2) fill in functions and data in InitOperators
 # 3) add function.
diff --git a/numpy/_core/records.py b/numpy/_core/records.py
index 09ac92f9c1f1..3e2d48d5f267 100644
--- a/numpy/_core/records.py
+++ b/numpy/_core/records.py
@@ -228,7 +228,7 @@ def __getattribute__(self, attr):
             try:
                 dt = obj.dtype
             except AttributeError:
-                #happens if field is Object type
+                # happens if field is Object type
                 return obj
             if dt.names is not None:
                 return obj.view((self.__class__, obj.dtype))
diff --git a/numpy/_core/tests/test_dtype.py b/numpy/_core/tests/test_dtype.py
index 5d458729d278..68698fc229fb 100644
--- a/numpy/_core/tests/test_dtype.py
+++ b/numpy/_core/tests/test_dtype.py
@@ -742,7 +742,7 @@ def test_shape_invalid(self):
         assert_raises(ValueError, np.dtype, [('a', 'f4', (-1, -1))])
 
     def test_alignment(self):
-        #Check that subarrays are aligned
+        # Check that subarrays are aligned
         t1 = np.dtype('(1,)i4', align=True)
         t2 = np.dtype('2i4', align=True)
         assert_equal(t1.alignment, t2.alignment)
diff --git a/numpy/_core/tests/test_einsum.py b/numpy/_core/tests/test_einsum.py
index 5aa75b5a6b97..649e05c4476d 100644
--- a/numpy/_core/tests/test_einsum.py
+++ b/numpy/_core/tests/test_einsum.py
@@ -1240,7 +1240,7 @@ def test_path_type_input(self):
         assert_almost_equal(noopt, opt)
 
     def test_path_type_input_internal_trace(self):
-        #gh-20962
+        # gh-20962
         path_test = self.build_operands('cab,cdd->ab')
         exp_path = ['einsum_path', (1,), (0, 1)]
 
@@ -1266,7 +1266,7 @@ def test_path_type_input_invalid(self):
             RuntimeError, np.einsum_path, *path_test, optimize=exp_path)
 
     def test_spaces(self):
-        #gh-10794
+        # gh-10794
         arr = np.array([[1]])
         for sp in itertools.product(['', ' '], repeat=4):
             # no error for any spacing
@@ -1279,7 +1279,7 @@ def test_overlap():
     # sanity check
     c = np.einsum('ij,jk->ik', a, b)
     assert_equal(c, d)
-    #gh-10080, out overlaps one of the operands
+    # gh-10080, out overlaps one of the operands
     c = np.einsum('ij,jk->ik', a, b, out=b)
     assert_equal(c, d)
 
diff --git a/numpy/_core/tests/test_indexing.py b/numpy/_core/tests/test_indexing.py
index 410a68b7efb4..b65533bbc5ef 100644
--- a/numpy/_core/tests/test_indexing.py
+++ b/numpy/_core/tests/test_indexing.py
@@ -492,7 +492,7 @@ def test_unaligned(self):
         x = x.view(np.dtype("S8"))
         x[...] = np.array("b" * 8, dtype="S")
         b = np.arange(d.size)
-        #trivial
+        # trivial
         assert_equal(d[b], d)
         d[b] = x
         # nontrivial
diff --git a/numpy/_core/tests/test_multiarray.py b/numpy/_core/tests/test_multiarray.py
index 6d97124d66c0..e8abf1aef01a 100644
--- a/numpy/_core/tests/test_multiarray.py
+++ b/numpy/_core/tests/test_multiarray.py
@@ -2295,11 +2295,11 @@ def test_void_sort(self):
             arr[::-1].sort()
 
     def test_sort_raises(self):
-        #gh-9404
+        # gh-9404
         arr = np.array([0, datetime.now(), 1], dtype=object)
         for kind in self.sort_kinds:
             assert_raises(TypeError, arr.sort, kind=kind)
-        #gh-3879
+        # gh-3879
 
         class Raiser:
             def raises_anything(*args, **kwargs):
diff --git a/numpy/_core/tests/test_nditer.py b/numpy/_core/tests/test_nditer.py
index 5bf0a6b7b2f4..9f60b67ba5b1 100644
--- a/numpy/_core/tests/test_nditer.py
+++ b/numpy/_core/tests/test_nditer.py
@@ -1113,7 +1113,7 @@ def test_iter_object_arrays_conversions():
             x[...] += 1
     assert_equal(a, np.arange(6) + 1)
 
-    #Non-contiguous value array
+    # Non-contiguous value array
     a = np.zeros((6,), dtype=[('p', 'i1'), ('a', 'i4')])
     a = a['a']
     a[:] = np.arange(6) + 98172488
diff --git a/numpy/_core/tests/test_numeric.py b/numpy/_core/tests/test_numeric.py
index d821c14c3bad..21dae72168de 100644
--- a/numpy/_core/tests/test_numeric.py
+++ b/numpy/_core/tests/test_numeric.py
@@ -4142,7 +4142,7 @@ def test_number_of_arguments(self):
                 assert_equal(mit.numiter, j)
 
     def test_broadcast_error_kwargs(self):
-        #gh-13455
+        # gh-13455
         arrs = [np.empty((5, 6, 7))]
         mit = np.broadcast(*arrs)
         mit2 = np.broadcast(*arrs, **{})  # noqa: PIE804
diff --git a/numpy/_core/tests/test_records.py b/numpy/_core/tests/test_records.py
index e8a757dc3d42..9e30887942ae 100644
--- a/numpy/_core/tests/test_records.py
+++ b/numpy/_core/tests/test_records.py
@@ -185,31 +185,31 @@ def test_recarray_views(self):
                      dtype=[('foo', int), ('bar', 'S4')])
         b = np.array([1, 2, 3, 4, 5], dtype=np.int64)
 
-        #check that np.rec.array gives right dtypes
+        # check that np.rec.array gives right dtypes
         assert_equal(np.rec.array(a).dtype.type, np.record)
         assert_equal(type(np.rec.array(a)), np.recarray)
         assert_equal(np.rec.array(b).dtype.type, np.int64)
         assert_equal(type(np.rec.array(b)), np.recarray)
 
-        #check that viewing as recarray does the same
+        # check that viewing as recarray does the same
         assert_equal(a.view(np.recarray).dtype.type, np.record)
         assert_equal(type(a.view(np.recarray)), np.recarray)
         assert_equal(b.view(np.recarray).dtype.type, np.int64)
         assert_equal(type(b.view(np.recarray)), np.recarray)
 
-        #check that view to non-structured dtype preserves type=np.recarray
+        # check that view to non-structured dtype preserves type=np.recarray
         r = np.rec.array(np.ones(4, dtype="f4,i4"))
         rv = r.view('f8').view('f4,i4')
         assert_equal(type(rv), np.recarray)
         assert_equal(rv.dtype.type, np.record)
 
-        #check that getitem also preserves np.recarray and np.record
+        # check that getitem also preserves np.recarray and np.record
         r = np.rec.array(np.ones(4, dtype=[('a', 'i4'), ('b', 'i4'),
                                            ('c', 'i4,i4')]))
         assert_equal(r['c'].dtype.type, np.record)
         assert_equal(type(r['c']), np.recarray)
 
-        #and that it preserves subclasses (gh-6949)
+        # and that it preserves subclasses (gh-6949)
         class C(np.recarray):
             pass
 
@@ -233,7 +233,7 @@ class C(np.recarray):
         assert_equal(r.view('V8').dtype.type, np.void)
         assert_equal(r.view(('i8', 'i4,i4')).dtype.type, np.int64)
 
-        #check that we can undo the view
+        # check that we can undo the view
         arrs = [np.ones(4, dtype='f4,i4'), np.ones(4, dtype='f8')]
         for arr in arrs:
             rec = np.rec.array(arr)
diff --git a/numpy/_core/tests/test_regression.py b/numpy/_core/tests/test_regression.py
index b8b539946909..8aca446b3920 100644
--- a/numpy/_core/tests/test_regression.py
+++ b/numpy/_core/tests/test_regression.py
@@ -1243,18 +1243,18 @@ def test_void_scalar_with_titles(self):
         assert_(arr[0][1] == 4)
 
     def test_void_scalar_constructor(self):
-        #Issue #1550
+        # Issue #1550
 
-        #Create test string data, construct void scalar from data and assert
-        #that void scalar contains original data.
+        # Create test string data, construct void scalar from data and assert
+        # that void scalar contains original data.
         test_string = np.array("test")
         test_string_void_scalar = np._core.multiarray.scalar(
             np.dtype(("V", test_string.dtype.itemsize)), test_string.tobytes())
 
         assert_(test_string_void_scalar.view(test_string.dtype) == test_string)
 
-        #Create record scalar, construct from data and assert that
-        #reconstructed scalar is correct.
+        # Create record scalar, construct from data and assert that
+        # reconstructed scalar is correct.
         test_record = np.ones((), "i,i")
         test_record_void_scalar = np._core.multiarray.scalar(
             test_record.dtype, test_record.tobytes())
@@ -2456,7 +2456,7 @@ def __len__(self):
 
     @pytest.mark.skipif(sys.maxsize < 2 ** 31 + 1, reason='overflows 32-bit python')
     def test_to_ctypes(self):
-        #gh-14214
+        # gh-14214
         arr = np.zeros((2 ** 31 + 1,), 'b')
         assert arr.size * arr.itemsize > 2 ** 31
         c_arr = np.ctypeslib.as_ctypes(arr)
diff --git a/numpy/_core/tests/test_scalarmath.py b/numpy/_core/tests/test_scalarmath.py
index 1842f5edd08b..0b086df21c60 100644
--- a/numpy/_core/tests/test_scalarmath.py
+++ b/numpy/_core/tests/test_scalarmath.py
@@ -562,13 +562,13 @@ def test_numpy_scalar_relational_operators(self):
                 assert_(not np.array(1, dtype=dt1)[()] < np.array(0, dtype=dt2)[()],
                         f"type {dt1} and {dt2} failed")
 
-        #Unsigned integers
+        # Unsigned integers
         for dt1 in 'BHILQP':
             assert_(-1 < np.array(1, dtype=dt1)[()], f"type {dt1} failed")
             assert_(not -1 > np.array(1, dtype=dt1)[()], f"type {dt1} failed")
             assert_(-1 != np.array(1, dtype=dt1)[()], f"type {dt1} failed")
 
-            #unsigned vs signed
+            # unsigned vs signed
             for dt2 in 'bhilqp':
                 assert_(np.array(1, dtype=dt1)[()] > np.array(-1, dtype=dt2)[()],
                         f"type {dt1} and {dt2} failed")
@@ -577,7 +577,7 @@ def test_numpy_scalar_relational_operators(self):
                 assert_(np.array(1, dtype=dt1)[()] != np.array(-1, dtype=dt2)[()],
                         f"type {dt1} and {dt2} failed")
 
-        #Signed integers and floats
+        # Signed integers and floats
         for dt1 in 'bhlqp' + np.typecodes['Float']:
             assert_(1 > np.array(-1, dtype=dt1)[()], f"type {dt1} failed")
             assert_(not 1 < np.array(-1, dtype=dt1)[()], f"type {dt1} failed")
diff --git a/numpy/_core/tests/test_scalarprint.py b/numpy/_core/tests/test_scalarprint.py
index 16a9267e235c..298eb232eafb 100644
--- a/numpy/_core/tests/test_scalarprint.py
+++ b/numpy/_core/tests/test_scalarprint.py
@@ -303,7 +303,7 @@ def test_dragon4_positional_interface_overflow(self, tp, pad_val):
 
         fpos = np.format_float_positional
 
-        #gh-28068
+        # gh-28068
         with pytest.raises(RuntimeError,
                            match="Float formatting result too large"):
             fpos(tp('1.047'), unique=False, precision=pad_val)
diff --git a/numpy/_core/tests/test_shape_base.py b/numpy/_core/tests/test_shape_base.py
index 58a36e8c022f..9e4ef3a8e6e9 100644
--- a/numpy/_core/tests/test_shape_base.py
+++ b/numpy/_core/tests/test_shape_base.py
@@ -477,13 +477,13 @@ def test_stack():
     with pytest.raises(TypeError, match="arrays to stack must be"):
         stack(x for x in range(3))
 
-    #casting and dtype test
+    # casting and dtype test
     a = np.array([1, 2, 3])
     b = np.array([2.5, 3.5, 4.5])
     res = np.stack((a, b), axis=1, casting="unsafe", dtype=np.int64)
     expected_res = np.array([[1, 2], [2, 3], [3, 4]])
     assert_array_equal(res, expected_res)
-    #casting and dtype with TypeError
+    # casting and dtype with TypeError
     with assert_raises(TypeError):
         stack((a, b), dtype=np.int64, axis=1, casting="safe")
 
diff --git a/numpy/_core/tests/test_umath.py b/numpy/_core/tests/test_umath.py
index 0efa51bfd772..22ad1b8ac302 100644
--- a/numpy/_core/tests/test_umath.py
+++ b/numpy/_core/tests/test_umath.py
@@ -1167,14 +1167,14 @@ def assert_complex_equal(x, y):
             assert_array_equal(x.real, y.real)
             assert_array_equal(x.imag, y.imag)
 
-        #Complex powers with positive real part will not generate a warning
+        # Complex powers with positive real part will not generate a warning
         assert_complex_equal(np.power(zero, 1 + 4j), zero)
         assert_complex_equal(np.power(zero, 2 - 3j), zero)
-        #Testing zero values when real part is greater than zero
+        # Testing zero values when real part is greater than zero
         assert_complex_equal(np.power(zero, 1 + 1j), zero)
         assert_complex_equal(np.power(zero, 1 + 0j), zero)
         assert_complex_equal(np.power(zero, 1 - 1j), zero)
-        #Complex powers will negative real part or 0 (provided imaginary
+        # Complex powers will negative real part or 0 (provided imaginary
         # part is not zero) will generate a NAN and hence a RUNTIME warning
         with pytest.warns(expected_warning=RuntimeWarning) as r:
             assert_complex_equal(np.power(zero, -1 + 1j), cnan)
diff --git a/numpy/_core/tests/test_umath_complex.py b/numpy/_core/tests/test_umath_complex.py
index 81c1447c4cbb..eb221f15f327 100644
--- a/numpy/_core/tests/test_umath_complex.py
+++ b/numpy/_core/tests/test_umath_complex.py
@@ -16,7 +16,7 @@
 # At least on Windows the results of many complex functions are not conforming
 # to the C99 standard. See ticket 1574.
 # Ditto for Solaris (ticket 1642) and OS X on PowerPC.
-#FIXME: this will probably change when we require full C99 compatibility
+# FIXME: this will probably change when we require full C99 compatibility
 with np.errstate(all='ignore'):
     functions_seem_flaky = ((np.exp(complex(np.inf, 0)).imag != 0)
                             or (np.log(complex(ncu.NZERO, 0)).imag != np.pi))
@@ -333,7 +333,7 @@ def test_special_values(self):
         def _check_ninf_nan(dummy):
             msgform = "csqrt(-inf, nan) is (%f, %f), expected (nan, +-inf)"
             z = np.sqrt(np.array(complex(-np.inf, np.nan)))
-            #Fixme: ugly workaround for isinf bug.
+            # FIXME: ugly workaround for isinf bug.
             with np.errstate(invalid='ignore'):
                 if not (np.isnan(z.real) and np.isinf(z.imag)):
                     raise AssertionError(msgform % (z.real, z.imag))
diff --git a/numpy/conftest.py b/numpy/conftest.py
index 9ae2b290ee71..84d856e55684 100644
--- a/numpy/conftest.py
+++ b/numpy/conftest.py
@@ -102,7 +102,7 @@ def pytest_terminal_summary(terminalreporter, exitstatus, config):
         tr.line("code that re-enables the GIL should do so in a subprocess.")
         pytest.exit("GIL re-enabled during tests", returncode=1)
 
-#FIXME when yield tests are gone.
+# FIXME when yield tests are gone.
 @pytest.hookimpl()
 def pytest_itemcollected(item):
     """
diff --git a/numpy/lib/_function_base_impl.py b/numpy/lib/_function_base_impl.py
index 33bc64511009..e44b27a68adb 100644
--- a/numpy/lib/_function_base_impl.py
+++ b/numpy/lib/_function_base_impl.py
@@ -2434,8 +2434,8 @@ def __init__(self, pyfunc=np._NoValue, otypes=None, doc=None,
                  excluded=None, cache=False, signature=None):
 
         if (pyfunc != np._NoValue) and (not callable(pyfunc)):
-            #Splitting the error message to keep
-            #the length below 79 characters.
+            # Splitting the error message to keep
+            # the length below 79 characters.
             part1 = "When used as a decorator, "
             part2 = "only accepts keyword arguments."
             raise TypeError(part1 + part2)
diff --git a/numpy/lib/tests/test_format.py b/numpy/lib/tests/test_format.py
index dd6f4fc9c765..cf076ac01eb5 100644
--- a/numpy/lib/tests/test_format.py
+++ b/numpy/lib/tests/test_format.py
@@ -396,7 +396,7 @@
 ]
 
 
-#BytesIO that reads a random number of bytes at a time
+# BytesIO that reads a random number of bytes at a time
 class BytesIOSRandomSize(BytesIO):
     def read(self, size=None):
         import random
@@ -423,7 +423,7 @@ def roundtrip_randsize(arr):
 def roundtrip_truncated(arr):
     f = BytesIO()
     format.write_array(f, arr)
-    #BytesIO is one byte short
+    # BytesIO is one byte short
     f2 = BytesIO(f.getvalue()[0:-1])
     arr2 = format.read_array(f2)
     return arr2
@@ -456,7 +456,7 @@ def test_file_truncated(tmp_path):
         if arr.dtype != object:
             with open(path, 'wb') as f:
                 format.write_array(f, arr)
-            #truncate the file by one byte
+            # truncate the file by one byte
             with open(path, 'rb+') as f:
                 f.seek(-1, os.SEEK_END)
                 f.truncate()
diff --git a/numpy/lib/tests/test_function_base.py b/numpy/lib/tests/test_function_base.py
index 97fec7071ad5..7329287721c4 100644
--- a/numpy/lib/tests/test_function_base.py
+++ b/numpy/lib/tests/test_function_base.py
@@ -1915,7 +1915,7 @@ class subclass(np.ndarray):
         assert_equal(r, m * v)
 
     def test_name(self):
-        #See gh-23021
+        # gh-23021
         @np.vectorize
         def f2(a, b):
             return a + b
@@ -3857,7 +3857,7 @@ def test_fraction(self):
         assert_equal(np.quantile(x, Fraction(1, 2)), Fraction(7, 2))
 
     def test_complex(self):
-        #See gh-22652
+        # gh-22652
         arr_c = np.array([0.5 + 3.0j, 2.1 + 0.5j, 1.6 + 2.3j], dtype='G')
         assert_raises(TypeError, np.quantile, arr_c, 0.5)
         arr_c = np.array([0.5 + 3.0j, 2.1 + 0.5j, 1.6 + 2.3j], dtype='D')
diff --git a/numpy/lib/tests/test_index_tricks.py b/numpy/lib/tests/test_index_tricks.py
index bf249100d17b..d17bd9e6259b 100644
--- a/numpy/lib/tests/test_index_tricks.py
+++ b/numpy/lib/tests/test_index_tricks.py
@@ -151,7 +151,7 @@ def test_clipmodes(self):
             ValueError, np.ravel_multi_index, [5, 1, -1, 2], (4, 3, 7, 12))
 
     def test_writeability(self):
-        # See gh-7269
+        # gh-7269
         x, y = np.unravel_index([1, 2, 3], (4, 5))
         assert_(x.flags.writeable)
         assert_(y.flags.writeable)
diff --git a/numpy/lib/tests/test_io.py b/numpy/lib/tests/test_io.py
index 3276584779a7..6939e5ceffac 100644
--- a/numpy/lib/tests/test_io.py
+++ b/numpy/lib/tests/test_io.py
@@ -2359,7 +2359,7 @@ def test_recfromcsv(self):
         assert_(isinstance(test, np.recarray))
         assert_equal(test, control)
 
-        #gh-10394
+        # gh-10394
         data = TextIO('color\n"red"\n"blue"')
         test = recfromcsv(data, converters={0: lambda x: x.strip('\"')})
         control = np.array([('red',), ('blue',)], dtype=[('color', (str, 4))])
diff --git a/numpy/linalg/tests/test_linalg.py b/numpy/linalg/tests/test_linalg.py
index 1a79629814e9..b47bb180a486 100644
--- a/numpy/linalg/tests/test_linalg.py
+++ b/numpy/linalg/tests/test_linalg.py
@@ -1034,7 +1034,7 @@ class TestMatrixPower:
     rshft_all = [rshft_0, rshft_1, rshft_2, rshft_3]
     noninv = array([[1, 0], [0, 0]])
     stacked = np.block([[[rshft_0]]] * 2)
-    #FIXME the 'e' dtype might work in future
+    # FIXME the 'e' dtype might work in future
     dtnoinv = [object, np.dtype('e'), np.dtype('g'), np.dtype('G')]
 
     def test_large_power(self, dt):
diff --git a/numpy/ma/core.py b/numpy/ma/core.py
index 3e291efa6032..add0ad9770d7 100644
--- a/numpy/ma/core.py
+++ b/numpy/ma/core.py
@@ -5183,7 +5183,7 @@ def trace(self, offset=0, axis1=0, axis2=1, dtype=None, out=None):
         """
         (this docstring should be overwritten)
         """
-        #!!!: implement out + test!
+        # !!!: implement out + test!
         m = self._mask
         if m is nomask:
             result = super().trace(offset=offset, axis1=axis1, axis2=axis2,
diff --git a/numpy/ma/tests/test_extras.py b/numpy/ma/tests/test_extras.py
index c2aa0c29a556..d4eeec59723e 100644
--- a/numpy/ma/tests/test_extras.py
+++ b/numpy/ma/tests/test_extras.py
@@ -1717,7 +1717,7 @@ def test_isin(self):
         c = isin(a, b)
         assert_(isinstance(c, MaskedArray))
         assert_array_equal(c, ec)
-        #compare results of np.isin to ma.isin
+        # compare results of np.isin to ma.isin
         d = np.isin(a, b[~b.mask]) & ~a.mask
         assert_array_equal(c, d)
 
diff --git a/numpy/ma/tests/test_mrecords.py b/numpy/ma/tests/test_mrecords.py
index ff463fc4d912..b73d32796772 100644
--- a/numpy/ma/tests/test_mrecords.py
+++ b/numpy/ma/tests/test_mrecords.py
@@ -411,14 +411,14 @@ def test_fromarrays(self):
     def test_fromrecords(self):
         # Test construction from records.
         (mrec, nrec, ddtype) = self.data
-        #......
+        # ......
         palist = [(1, 'abc', 3.7000002861022949, 0),
                   (2, 'xy', 6.6999998092651367, 1),
                   (0, ' ', 0.40000000596046448, 0)]
         pa = recfromrecords(palist, names='c1, c2, c3, c4')
         mpa = fromrecords(palist, names='c1, c2, c3, c4')
         assert_equal_records(pa, mpa)
-        #.....
+        # .....
         _mrec = fromrecords(nrec)
         assert_equal(_mrec.dtype, mrec.dtype)
         for field in _mrec.dtype.names:
diff --git a/numpy/ma/tests/test_old_ma.py b/numpy/ma/tests/test_old_ma.py
index 958601047109..e21dd39768e1 100644
--- a/numpy/ma/tests/test_old_ma.py
+++ b/numpy/ma/tests/test_old_ma.py
@@ -651,7 +651,7 @@ def test_testToPython(self):
 
     def test_testScalarArithmetic(self):
         xm = array(0, mask=1)
-        #TODO FIXME: Find out what the following raises a warning in r8247
+        # TODO FIXME: Find out what the following raises a warning in r8247
         with np.errstate(divide='ignore'):
             assert_((1 / array(0)).mask)
         assert_((1 + xm).mask)
diff --git a/numpy/polynomial/tests/test_chebyshev.py b/numpy/polynomial/tests/test_chebyshev.py
index 9d892a1f61d5..7733ded90412 100644
--- a/numpy/polynomial/tests/test_chebyshev.py
+++ b/numpy/polynomial/tests/test_chebyshev.py
@@ -133,10 +133,10 @@ class TestEvaluation:
     y = polyval(x, [1., 2., 3.])
 
     def test_chebval(self):
-        #check empty input
+        # check empty input
         assert_equal(cheb.chebval([], [1]).size, 0)
 
-        #check normal input)
+        # check normal input)
         x = np.linspace(-1, 1)
         y = [polyval(x, c) for c in Tlist]
         for i in range(10):
@@ -145,7 +145,7 @@ def test_chebval(self):
             res = cheb.chebval(x, [0] * i + [1])
             assert_almost_equal(res, tgt, err_msg=msg)
 
-        #check that shape is preserved
+        # check that shape is preserved
         for i in range(3):
             dims = [2] * i
             x = np.zeros(dims)
@@ -157,15 +157,15 @@ def test_chebval2d(self):
         x1, x2, x3 = self.x
         y1, y2, y3 = self.y
 
-        #test exceptions
+        # test exceptions
         assert_raises(ValueError, cheb.chebval2d, x1, x2[:2], self.c2d)
 
-        #test values
+        # test values
         tgt = y1 * y2
         res = cheb.chebval2d(x1, x2, self.c2d)
         assert_almost_equal(res, tgt)
 
-        #test shape
+        # test shape
         z = np.ones((2, 3))
         res = cheb.chebval2d(z, z, self.c2d)
         assert_(res.shape == (2, 3))
@@ -174,15 +174,15 @@ def test_chebval3d(self):
         x1, x2, x3 = self.x
         y1, y2, y3 = self.y
 
-        #test exceptions
+        # test exceptions
         assert_raises(ValueError, cheb.chebval3d, x1, x2, x3[:2], self.c3d)
 
-        #test values
+        # test values
         tgt = y1 * y2 * y3
         res = cheb.chebval3d(x1, x2, x3, self.c3d)
         assert_almost_equal(res, tgt)
 
-        #test shape
+        # test shape
         z = np.ones((2, 3))
         res = cheb.chebval3d(z, z, z, self.c3d)
         assert_(res.shape == (2, 3))
@@ -191,12 +191,12 @@ def test_chebgrid2d(self):
         x1, x2, x3 = self.x
         y1, y2, y3 = self.y
 
-        #test values
+        # test values
         tgt = np.einsum('i,j->ij', y1, y2)
         res = cheb.chebgrid2d(x1, x2, self.c2d)
         assert_almost_equal(res, tgt)
 
-        #test shape
+        # test shape
         z = np.ones((2, 3))
         res = cheb.chebgrid2d(z, z, self.c2d)
         assert_(res.shape == (2, 3) * 2)
@@ -205,12 +205,12 @@ def test_chebgrid3d(self):
         x1, x2, x3 = self.x
         y1, y2, y3 = self.y
 
-        #test values
+        # test values
         tgt = np.einsum('i,j,k->ijk', y1, y2, y3)
         res = cheb.chebgrid3d(x1, x2, x3, self.c3d)
         assert_almost_equal(res, tgt)
 
-        #test shape
+        # test shape
         z = np.ones((2, 3))
         res = cheb.chebgrid3d(z, z, z, self.c3d)
         assert_(res.shape == (2, 3) * 3)
@@ -590,11 +590,11 @@ def test_weight(self):
         assert_almost_equal(res, tgt)
 
     def test_chebpts1(self):
-        #test exceptions
+        # test exceptions
         assert_raises(ValueError, cheb.chebpts1, 1.5)
         assert_raises(ValueError, cheb.chebpts1, 0)
 
-        #test points
+        # test points
         tgt = [0]
         assert_almost_equal(cheb.chebpts1(1), tgt)
         tgt = [-0.70710678118654746, 0.70710678118654746]
@@ -605,11 +605,11 @@ def test_chebpts1(self):
         assert_almost_equal(cheb.chebpts1(4), tgt)
 
     def test_chebpts2(self):
-        #test exceptions
+        # test exceptions
         assert_raises(ValueError, cheb.chebpts2, 1.5)
         assert_raises(ValueError, cheb.chebpts2, 1)
 
-        #test points
+        # test points
         tgt = [-1, 1]
         assert_almost_equal(cheb.chebpts2(2), tgt)
         tgt = [-1, 0, 1]
diff --git a/numpy/polynomial/tests/test_hermite.py b/numpy/polynomial/tests/test_hermite.py
index 3e2b7c0032c6..2f17091137b9 100644
--- a/numpy/polynomial/tests/test_hermite.py
+++ b/numpy/polynomial/tests/test_hermite.py
@@ -120,10 +120,10 @@ class TestEvaluation:
     y = polyval(x, [1., 2., 3.])
 
     def test_hermval(self):
-        #check empty input
+        # check empty input
         assert_equal(herm.hermval([], [1]).size, 0)
 
-        #check normal input)
+        # check normal input)
         x = np.linspace(-1, 1)
         y = [polyval(x, c) for c in Hlist]
         for i in range(10):
@@ -132,7 +132,7 @@ def test_hermval(self):
             res = herm.hermval(x, [0] * i + [1])
             assert_almost_equal(res, tgt, err_msg=msg)
 
-        #check that shape is preserved
+        # check that shape is preserved
         for i in range(3):
             dims = [2] * i
             x = np.zeros(dims)
@@ -144,15 +144,15 @@ def test_hermval2d(self):
         x1, x2, x3 = self.x
         y1, y2, y3 = self.y
 
-        #test exceptions
+        # test exceptions
         assert_raises(ValueError, herm.hermval2d, x1, x2[:2], self.c2d)
 
-        #test values
+        # test values
         tgt = y1 * y2
         res = herm.hermval2d(x1, x2, self.c2d)
         assert_almost_equal(res, tgt)
 
-        #test shape
+        # test shape
         z = np.ones((2, 3))
         res = herm.hermval2d(z, z, self.c2d)
         assert_(res.shape == (2, 3))
@@ -161,15 +161,15 @@ def test_hermval3d(self):
         x1, x2, x3 = self.x
         y1, y2, y3 = self.y
 
-        #test exceptions
+        # test exceptions
         assert_raises(ValueError, herm.hermval3d, x1, x2, x3[:2], self.c3d)
 
-        #test values
+        # test values
         tgt = y1 * y2 * y3
         res = herm.hermval3d(x1, x2, x3, self.c3d)
         assert_almost_equal(res, tgt)
 
-        #test shape
+        # test shape
         z = np.ones((2, 3))
         res = herm.hermval3d(z, z, z, self.c3d)
         assert_(res.shape == (2, 3))
@@ -178,12 +178,12 @@ def test_hermgrid2d(self):
         x1, x2, x3 = self.x
         y1, y2, y3 = self.y
 
-        #test values
+        # test values
         tgt = np.einsum('i,j->ij', y1, y2)
         res = herm.hermgrid2d(x1, x2, self.c2d)
         assert_almost_equal(res, tgt)
 
-        #test shape
+        # test shape
         z = np.ones((2, 3))
         res = herm.hermgrid2d(z, z, self.c2d)
         assert_(res.shape == (2, 3) * 2)
@@ -192,12 +192,12 @@ def test_hermgrid3d(self):
         x1, x2, x3 = self.x
         y1, y2, y3 = self.y
 
-        #test values
+        # test values
         tgt = np.einsum('i,j,k->ijk', y1, y2, y3)
         res = herm.hermgrid3d(x1, x2, x3, self.c3d)
         assert_almost_equal(res, tgt)
 
-        #test shape
+        # test shape
         z = np.ones((2, 3))
         res = herm.hermgrid3d(z, z, z, self.c3d)
         assert_(res.shape == (2, 3) * 3)
diff --git a/numpy/polynomial/tests/test_hermite_e.py b/numpy/polynomial/tests/test_hermite_e.py
index bd567d513027..ce55e2098b97 100644
--- a/numpy/polynomial/tests/test_hermite_e.py
+++ b/numpy/polynomial/tests/test_hermite_e.py
@@ -120,10 +120,10 @@ class TestEvaluation:
     y = polyval(x, [1., 2., 3.])
 
     def test_hermeval(self):
-        #check empty input
+        # check empty input
         assert_equal(herme.hermeval([], [1]).size, 0)
 
-        #check normal input)
+        # check normal input)
         x = np.linspace(-1, 1)
         y = [polyval(x, c) for c in Helist]
         for i in range(10):
@@ -132,7 +132,7 @@ def test_hermeval(self):
             res = herme.hermeval(x, [0] * i + [1])
             assert_almost_equal(res, tgt, err_msg=msg)
 
-        #check that shape is preserved
+        # check that shape is preserved
         for i in range(3):
             dims = [2] * i
             x = np.zeros(dims)
@@ -144,15 +144,15 @@ def test_hermeval2d(self):
         x1, x2, x3 = self.x
         y1, y2, y3 = self.y
 
-        #test exceptions
+        # test exceptions
         assert_raises(ValueError, herme.hermeval2d, x1, x2[:2], self.c2d)
 
-        #test values
+        # test values
         tgt = y1 * y2
         res = herme.hermeval2d(x1, x2, self.c2d)
         assert_almost_equal(res, tgt)
 
-        #test shape
+        # test shape
         z = np.ones((2, 3))
         res = herme.hermeval2d(z, z, self.c2d)
         assert_(res.shape == (2, 3))
@@ -161,15 +161,15 @@ def test_hermeval3d(self):
         x1, x2, x3 = self.x
         y1, y2, y3 = self.y
 
-        #test exceptions
+        # test exceptions
         assert_raises(ValueError, herme.hermeval3d, x1, x2, x3[:2], self.c3d)
 
-        #test values
+        # test values
         tgt = y1 * y2 * y3
         res = herme.hermeval3d(x1, x2, x3, self.c3d)
         assert_almost_equal(res, tgt)
 
-        #test shape
+        # test shape
         z = np.ones((2, 3))
         res = herme.hermeval3d(z, z, z, self.c3d)
         assert_(res.shape == (2, 3))
@@ -178,12 +178,12 @@ def test_hermegrid2d(self):
         x1, x2, x3 = self.x
         y1, y2, y3 = self.y
 
-        #test values
+        # test values
         tgt = np.einsum('i,j->ij', y1, y2)
         res = herme.hermegrid2d(x1, x2, self.c2d)
         assert_almost_equal(res, tgt)
 
-        #test shape
+        # test shape
         z = np.ones((2, 3))
         res = herme.hermegrid2d(z, z, self.c2d)
         assert_(res.shape == (2, 3) * 2)
@@ -192,12 +192,12 @@ def test_hermegrid3d(self):
         x1, x2, x3 = self.x
         y1, y2, y3 = self.y
 
-        #test values
+        # test values
         tgt = np.einsum('i,j,k->ijk', y1, y2, y3)
         res = herme.hermegrid3d(x1, x2, x3, self.c3d)
         assert_almost_equal(res, tgt)
 
-        #test shape
+        # test shape
         z = np.ones((2, 3))
         res = herme.hermegrid3d(z, z, z, self.c3d)
         assert_(res.shape == (2, 3) * 3)
diff --git a/numpy/polynomial/tests/test_laguerre.py b/numpy/polynomial/tests/test_laguerre.py
index f19c4d2fc2aa..1dd1977de684 100644
--- a/numpy/polynomial/tests/test_laguerre.py
+++ b/numpy/polynomial/tests/test_laguerre.py
@@ -117,10 +117,10 @@ class TestEvaluation:
     y = polyval(x, [1., 2., 3.])
 
     def test_lagval(self):
-        #check empty input
+        # check empty input
         assert_equal(lag.lagval([], [1]).size, 0)
 
-        #check normal input)
+        # check normal input)
         x = np.linspace(-1, 1)
         y = [polyval(x, c) for c in Llist]
         for i in range(7):
@@ -129,7 +129,7 @@ def test_lagval(self):
             res = lag.lagval(x, [0] * i + [1])
             assert_almost_equal(res, tgt, err_msg=msg)
 
-        #check that shape is preserved
+        # check that shape is preserved
         for i in range(3):
             dims = [2] * i
             x = np.zeros(dims)
@@ -141,15 +141,15 @@ def test_lagval2d(self):
         x1, x2, x3 = self.x
         y1, y2, y3 = self.y
 
-        #test exceptions
+        # test exceptions
         assert_raises(ValueError, lag.lagval2d, x1, x2[:2], self.c2d)
 
-        #test values
+        # test values
         tgt = y1 * y2
         res = lag.lagval2d(x1, x2, self.c2d)
         assert_almost_equal(res, tgt)
 
-        #test shape
+        # test shape
         z = np.ones((2, 3))
         res = lag.lagval2d(z, z, self.c2d)
         assert_(res.shape == (2, 3))
@@ -158,15 +158,15 @@ def test_lagval3d(self):
         x1, x2, x3 = self.x
         y1, y2, y3 = self.y
 
-        #test exceptions
+        # test exceptions
         assert_raises(ValueError, lag.lagval3d, x1, x2, x3[:2], self.c3d)
 
-        #test values
+        # test values
         tgt = y1 * y2 * y3
         res = lag.lagval3d(x1, x2, x3, self.c3d)
         assert_almost_equal(res, tgt)
 
-        #test shape
+        # test shape
         z = np.ones((2, 3))
         res = lag.lagval3d(z, z, z, self.c3d)
         assert_(res.shape == (2, 3))
@@ -175,12 +175,12 @@ def test_laggrid2d(self):
         x1, x2, x3 = self.x
         y1, y2, y3 = self.y
 
-        #test values
+        # test values
         tgt = np.einsum('i,j->ij', y1, y2)
         res = lag.laggrid2d(x1, x2, self.c2d)
         assert_almost_equal(res, tgt)
 
-        #test shape
+        # test shape
         z = np.ones((2, 3))
         res = lag.laggrid2d(z, z, self.c2d)
         assert_(res.shape == (2, 3) * 2)
@@ -189,12 +189,12 @@ def test_laggrid3d(self):
         x1, x2, x3 = self.x
         y1, y2, y3 = self.y
 
-        #test values
+        # test values
         tgt = np.einsum('i,j,k->ijk', y1, y2, y3)
         res = lag.laggrid3d(x1, x2, x3, self.c3d)
         assert_almost_equal(res, tgt)
 
-        #test shape
+        # test shape
         z = np.ones((2, 3))
         res = lag.laggrid3d(z, z, z, self.c3d)
         assert_(res.shape == (2, 3) * 3)
diff --git a/numpy/polynomial/tests/test_legendre.py b/numpy/polynomial/tests/test_legendre.py
index 80b428e31dcc..ee23b4a2527f 100644
--- a/numpy/polynomial/tests/test_legendre.py
+++ b/numpy/polynomial/tests/test_legendre.py
@@ -121,10 +121,10 @@ class TestEvaluation:
     y = polyval(x, [1., 2., 3.])
 
     def test_legval(self):
-        #check empty input
+        # check empty input
         assert_equal(leg.legval([], [1]).size, 0)
 
-        #check normal input)
+        # check normal input)
         x = np.linspace(-1, 1)
         y = [polyval(x, c) for c in Llist]
         for i in range(10):
@@ -133,7 +133,7 @@ def test_legval(self):
             res = leg.legval(x, [0] * i + [1])
             assert_almost_equal(res, tgt, err_msg=msg)
 
-        #check that shape is preserved
+        # check that shape is preserved
         for i in range(3):
             dims = [2] * i
             x = np.zeros(dims)
@@ -145,15 +145,15 @@ def test_legval2d(self):
         x1, x2, x3 = self.x
         y1, y2, y3 = self.y
 
-        #test exceptions
+        # test exceptions
         assert_raises(ValueError, leg.legval2d, x1, x2[:2], self.c2d)
 
-        #test values
+        # test values
         tgt = y1 * y2
         res = leg.legval2d(x1, x2, self.c2d)
         assert_almost_equal(res, tgt)
 
-        #test shape
+        # test shape
         z = np.ones((2, 3))
         res = leg.legval2d(z, z, self.c2d)
         assert_(res.shape == (2, 3))
@@ -162,15 +162,15 @@ def test_legval3d(self):
         x1, x2, x3 = self.x
         y1, y2, y3 = self.y
 
-        #test exceptions
+        # test exceptions
         assert_raises(ValueError, leg.legval3d, x1, x2, x3[:2], self.c3d)
 
-        #test values
+        # test values
         tgt = y1 * y2 * y3
         res = leg.legval3d(x1, x2, x3, self.c3d)
         assert_almost_equal(res, tgt)
 
-        #test shape
+        # test shape
         z = np.ones((2, 3))
         res = leg.legval3d(z, z, z, self.c3d)
         assert_(res.shape == (2, 3))
@@ -179,12 +179,12 @@ def test_leggrid2d(self):
         x1, x2, x3 = self.x
         y1, y2, y3 = self.y
 
-        #test values
+        # test values
         tgt = np.einsum('i,j->ij', y1, y2)
         res = leg.leggrid2d(x1, x2, self.c2d)
         assert_almost_equal(res, tgt)
 
-        #test shape
+        # test shape
         z = np.ones((2, 3))
         res = leg.leggrid2d(z, z, self.c2d)
         assert_(res.shape == (2, 3) * 2)
@@ -193,12 +193,12 @@ def test_leggrid3d(self):
         x1, x2, x3 = self.x
         y1, y2, y3 = self.y
 
-        #test values
+        # test values
         tgt = np.einsum('i,j,k->ijk', y1, y2, y3)
         res = leg.leggrid3d(x1, x2, x3, self.c3d)
         assert_almost_equal(res, tgt)
 
-        #test shape
+        # test shape
         z = np.ones((2, 3))
         res = leg.leggrid3d(z, z, z, self.c3d)
         assert_(res.shape == (2, 3) * 3)
diff --git a/numpy/polynomial/tests/test_polynomial.py b/numpy/polynomial/tests/test_polynomial.py
index 177bd0893ec9..e7c4fdfe8996 100644
--- a/numpy/polynomial/tests/test_polynomial.py
+++ b/numpy/polynomial/tests/test_polynomial.py
@@ -155,10 +155,10 @@ class TestEvaluation:
     y = poly.polyval(x, [1., 2., 3.])
 
     def test_polyval(self):
-        #check empty input
+        # check empty input
         assert_equal(poly.polyval([], [1]).size, 0)
 
-        #check normal input)
+        # check normal input)
         x = np.linspace(-1, 1)
         y = [x**i for i in range(5)]
         for i in range(5):
@@ -169,7 +169,7 @@ def test_polyval(self):
         res = poly.polyval(x, [0, -1, 0, 1])
         assert_almost_equal(res, tgt)
 
-        #check that shape is preserved
+        # check that shape is preserved
         for i in range(3):
             dims = [2] * i
             x = np.zeros(dims)
@@ -177,13 +177,13 @@ def test_polyval(self):
             assert_equal(poly.polyval(x, [1, 0]).shape, dims)
             assert_equal(poly.polyval(x, [1, 0, 0]).shape, dims)
 
-        #check masked arrays are processed correctly
+        # check masked arrays are processed correctly
         mask = [False, True, False]
         mx = np.ma.array([1, 2, 3], mask=mask)
         res = np.polyval([7, 5, 3], mx)
         assert_array_equal(res.mask, mask)
 
-        #check subtypes of ndarray are preserved
+        # check subtypes of ndarray are preserved
         class C(np.ndarray):
             pass
 
@@ -258,16 +258,16 @@ def test_polyval2d(self):
         x1, x2, x3 = self.x
         y1, y2, y3 = self.y
 
-        #test exceptions
+        # test exceptions
         assert_raises_regex(ValueError, 'incompatible',
                             poly.polyval2d, x1, x2[:2], self.c2d)
 
-        #test values
+        # test values
         tgt = y1 * y2
         res = poly.polyval2d(x1, x2, self.c2d)
         assert_almost_equal(res, tgt)
 
-        #test shape
+        # test shape
         z = np.ones((2, 3))
         res = poly.polyval2d(z, z, self.c2d)
         assert_(res.shape == (2, 3))
@@ -276,16 +276,16 @@ def test_polyval3d(self):
         x1, x2, x3 = self.x
         y1, y2, y3 = self.y
 
-        #test exceptions
+        # test exceptions
         assert_raises_regex(ValueError, 'incompatible',
                       poly.polyval3d, x1, x2, x3[:2], self.c3d)
 
-        #test values
+        # test values
         tgt = y1 * y2 * y3
         res = poly.polyval3d(x1, x2, x3, self.c3d)
         assert_almost_equal(res, tgt)
 
-        #test shape
+        # test shape
         z = np.ones((2, 3))
         res = poly.polyval3d(z, z, z, self.c3d)
         assert_(res.shape == (2, 3))
@@ -294,12 +294,12 @@ def test_polygrid2d(self):
         x1, x2, x3 = self.x
         y1, y2, y3 = self.y
 
-        #test values
+        # test values
         tgt = np.einsum('i,j->ij', y1, y2)
         res = poly.polygrid2d(x1, x2, self.c2d)
         assert_almost_equal(res, tgt)
 
-        #test shape
+        # test shape
         z = np.ones((2, 3))
         res = poly.polygrid2d(z, z, self.c2d)
         assert_(res.shape == (2, 3) * 2)
@@ -308,12 +308,12 @@ def test_polygrid3d(self):
         x1, x2, x3 = self.x
         y1, y2, y3 = self.y
 
-        #test values
+        # test values
         tgt = np.einsum('i,j,k->ijk', y1, y2, y3)
         res = poly.polygrid3d(x1, x2, x3, self.c3d)
         assert_almost_equal(res, tgt)
 
-        #test shape
+        # test shape
         z = np.ones((2, 3))
         res = poly.polygrid3d(z, z, z, self.c3d)
         assert_(res.shape == (2, 3) * 3)
diff --git a/numpy/testing/_private/utils.py b/numpy/testing/_private/utils.py
index 4bc10e2f58f6..5cbb5130dc1f 100644
--- a/numpy/testing/_private/utils.py
+++ b/numpy/testing/_private/utils.py
@@ -136,7 +136,7 @@ def GetPerformanceAttributes(object, counter, instance=None,
         # you should copy this function, but keep the counter open, and call
         # CollectQueryData() each time you need to know.
         # See http://msdn.microsoft.com/library/en-us/dnperfmo/html/perfmonpt2.asp
-        #(dead link)
+        # (dead link)
         # My older explanation for this was that the "AddCounter" process
         # forced the CPU to 100%, but the above makes more sense :)
         import win32pdh
diff --git a/tools/swig/test/testSuperTensor.py b/tools/swig/test/testSuperTensor.py
index 11cbc76f2642..5f185884641e 100644
--- a/tools/swig/test/testSuperTensor.py
+++ b/tools/swig/test/testSuperTensor.py
@@ -29,8 +29,8 @@ def testNorm(self):
         norm = SuperTensor.__dict__[self.typeStr + "Norm"]
         supertensor = np.arange(2 * 2 * 2 * 2,
                                 dtype=self.typeCode).reshape((2, 2, 2, 2))
-        #Note: cludge to get an answer of the same type as supertensor.
-        #Answer is simply sqrt(sum(supertensor*supertensor)/16)
+        # Note: cludge to get an answer of the same type as supertensor.
+        # Answer is simply sqrt(sum(supertensor*supertensor)/16)
         answer = np.array([np.sqrt(np.sum(supertensor.astype('d') * supertensor) / 16.)], dtype=self.typeCode)[0]  # noqa: E501
         self.assertAlmostEqual(norm(supertensor), answer, 6)
 

From 5cc13b0896dc0c615b402b17bffb264ddaaba851 Mon Sep 17 00:00:00 2001
From: Dimitri Papadopoulos
 <3234522+DimitriPapadopoulos@users.noreply.github.com>
Date: Sat, 19 Apr 2025 12:09:32 +0200
Subject: [PATCH 110/202] STY: Partially apply ruff:pycodestyle rule E266

Too many leading `#` before block comment

For now, do not modify titles.
---
 numpy/_core/tests/test_api.py | 4 ++--
 numpy/ctypeslib/_ctypeslib.py | 4 ++--
 2 files changed, 4 insertions(+), 4 deletions(-)

diff --git a/numpy/_core/tests/test_api.py b/numpy/_core/tests/test_api.py
index f0200d59cafe..8d7c617898e6 100644
--- a/numpy/_core/tests/test_api.py
+++ b/numpy/_core/tests/test_api.py
@@ -82,8 +82,8 @@ def test_array_array():
                  dtype=[('f0', int), ('f1', float), ('f2', str)])
     o = type("o", (object,),
              {"__array_struct__": a.__array_struct__})
-    ## wasn't what I expected... is np.array(o) supposed to equal a ?
-    ## instead we get a array([...], dtype=">V18")
+    # wasn't what I expected... is np.array(o) supposed to equal a ?
+    # instead we get a array([...], dtype=">V18")
     assert_equal(bytes(np.array(o).data), bytes(a.data))
 
     # test array
diff --git a/numpy/ctypeslib/_ctypeslib.py b/numpy/ctypeslib/_ctypeslib.py
index bd5632702d8c..40b9e58b5912 100644
--- a/numpy/ctypeslib/_ctypeslib.py
+++ b/numpy/ctypeslib/_ctypeslib.py
@@ -158,9 +158,9 @@ def load_library(libname, loader_path):
                 try:
                     return ctypes.cdll[libpath]
                 except OSError:
-                    ## defective lib file
+                    # defective lib file
                     raise
-        ## if no successful return in the libname_ext loop:
+        # if no successful return in the libname_ext loop:
         raise OSError("no file with expected extension")
 
 

From 493facec3b86e7b8b1a96b923a4a5245c79c5d6c Mon Sep 17 00:00:00 2001
From: Dimitri Papadopoulos
 <3234522+DimitriPapadopoulos@users.noreply.github.com>
Date: Tue, 22 Apr 2025 10:17:43 +0200
Subject: [PATCH 111/202] STY: Take into account reviewer's comments

Co-authored-by: Joren Hammudoglu 
---
 doc/source/f2py/code/setup_example.py  | 18 +++++-----
 numpy/_core/tests/test_arrayprint.py   |  2 +-
 numpy/_core/tests/test_cpu_features.py |  2 +-
 numpy/_core/tests/test_datetime.py     |  2 +-
 numpy/_core/tests/test_einsum.py       |  2 +-
 numpy/_core/tests/test_multiarray.py   |  3 +-
 numpy/lib/tests/test_format.py         |  2 +-
 numpy/ma/tests/test_core.py            | 46 +++++++++++++-------------
 8 files changed, 38 insertions(+), 39 deletions(-)

diff --git a/doc/source/f2py/code/setup_example.py b/doc/source/f2py/code/setup_example.py
index 654c448a4b75..ef79ad1ecfb6 100644
--- a/doc/source/f2py/code/setup_example.py
+++ b/doc/source/f2py/code/setup_example.py
@@ -1,16 +1,16 @@
 from numpy.distutils.core import Extension
 
-ext1 = Extension(name = 'scalar',
-                 sources = ['scalar.f'])
-ext2 = Extension(name = 'fib2',
-                 sources = ['fib2.pyf', 'fib1.f'])
+ext1 = Extension(name='scalar',
+                 sources=['scalar.f'])
+ext2 = Extension(name='fib2',
+                 sources=['fib2.pyf', 'fib1.f'])
 
 if __name__ == "__main__":
     from numpy.distutils.core import setup
-    setup(name = 'f2py_example',
-          description = "F2PY Users Guide examples",
-          author = "Pearu Peterson",
-          author_email = "pearu@cens.ioc.ee",
-          ext_modules = [ext1, ext2]
+    setup(name='f2py_example',
+          description="F2PY Users Guide examples",
+          author="Pearu Peterson",
+          author_email="pearu@cens.ioc.ee",
+          ext_modules=[ext1, ext2]
           )
 # End of setup_example.py
diff --git a/numpy/_core/tests/test_arrayprint.py b/numpy/_core/tests/test_arrayprint.py
index d31f29271e93..c15034f56ee2 100644
--- a/numpy/_core/tests/test_arrayprint.py
+++ b/numpy/_core/tests/test_arrayprint.py
@@ -320,7 +320,7 @@ def test_structure_format_float(self):
         assert_equal(np.array2string(array_scalar), "(1., 2.12345679, 3.)")
 
     def test_unstructured_void_repr(self):
-        a = np.array([27, 91, 50, 75,   7, 65, 10,    8,
+        a = np.array([27, 91, 50, 75,   7, 65,  10,   8,
                       27, 91, 51, 49, 109, 82, 101, 100], dtype='u1').view('V8')
         assert_equal(repr(a[0]),
             r"np.void(b'\x1B\x5B\x32\x4B\x07\x41\x0A\x08')")
diff --git a/numpy/_core/tests/test_cpu_features.py b/numpy/_core/tests/test_cpu_features.py
index 62b0eac5dda5..f4bd02ab55e5 100644
--- a/numpy/_core/tests/test_cpu_features.py
+++ b/numpy/_core/tests/test_cpu_features.py
@@ -117,7 +117,7 @@ def load_flags_auxv(self):
 
 @pytest.mark.skipif(
     sys.platform == 'emscripten',
-    reason= (
+    reason=(
         "The subprocess module is not available on WASM platforms and"
         " therefore this test class cannot be properly executed."
     ),
diff --git a/numpy/_core/tests/test_datetime.py b/numpy/_core/tests/test_datetime.py
index d2e4e5ec6cad..8d48e8a6630a 100644
--- a/numpy/_core/tests/test_datetime.py
+++ b/numpy/_core/tests/test_datetime.py
@@ -2492,7 +2492,7 @@ def test_isfinite_isinf_isnan_units(self, unit, dstr):
         '''check isfinite, isinf, isnan for all units of M, m dtypes
         '''
         arr_val = [123, -321, "NaT"]
-        arr = np.array(arr_val,  dtype= dstr % unit)
+        arr = np.array(arr_val, dtype=(dstr % unit))
         pos = np.array([True, True, False])
         neg = np.array([False, False, True])
         false = np.array([False, False, False])
diff --git a/numpy/_core/tests/test_einsum.py b/numpy/_core/tests/test_einsum.py
index 649e05c4476d..f3fd137b7c5c 100644
--- a/numpy/_core/tests/test_einsum.py
+++ b/numpy/_core/tests/test_einsum.py
@@ -764,7 +764,7 @@ def __mul__(self, other):
                 return 42
 
         objMult = np.array([Mult()])
-        objNULL = np.ndarray(buffer = b'\0' * np.intp(0).itemsize, shape=1, dtype=object)
+        objNULL = np.ndarray(buffer=b'\0' * np.intp(0).itemsize, shape=1, dtype=object)
 
         with pytest.raises(TypeError):
             np.einsum("i,j", [1], objNULL)
diff --git a/numpy/_core/tests/test_multiarray.py b/numpy/_core/tests/test_multiarray.py
index e8abf1aef01a..0a62cb6945f0 100644
--- a/numpy/_core/tests/test_multiarray.py
+++ b/numpy/_core/tests/test_multiarray.py
@@ -9427,8 +9427,7 @@ def _make_readonly(x):
         np.array([1, 2, 3]),
         np.array([['one', 'two'], ['three', 'four']]),
         np.array((1, 2), dtype='i4,i4'),
-        np.zeros((2,), dtype=
-            np.dtype({
+        np.zeros((2,), dtype=np.dtype({
                 "formats": ['
Date: Thu, 24 Apr 2025 11:31:17 +0200
Subject: [PATCH 112/202] STY: More taking into account reviewer's comments

Unwrap the array arbitrarily split over two lines, as it fits the new
default line-length limit of 88 characters.

Co-authored-by: Joren Hammudoglu 
---
 numpy/_core/tests/test_arrayprint.py | 4 ++--
 1 file changed, 2 insertions(+), 2 deletions(-)

diff --git a/numpy/_core/tests/test_arrayprint.py b/numpy/_core/tests/test_arrayprint.py
index c15034f56ee2..09ed71f342a2 100644
--- a/numpy/_core/tests/test_arrayprint.py
+++ b/numpy/_core/tests/test_arrayprint.py
@@ -320,8 +320,8 @@ def test_structure_format_float(self):
         assert_equal(np.array2string(array_scalar), "(1., 2.12345679, 3.)")
 
     def test_unstructured_void_repr(self):
-        a = np.array([27, 91, 50, 75,   7, 65,  10,   8,
-                      27, 91, 51, 49, 109, 82, 101, 100], dtype='u1').view('V8')
+        a = np.array([27, 91, 50, 75, 7, 65, 10, 8, 27, 91, 51, 49, 109, 82, 101, 100],
+                      dtype='u1').view('V8')
         assert_equal(repr(a[0]),
             r"np.void(b'\x1B\x5B\x32\x4B\x07\x41\x0A\x08')")
         assert_equal(str(a[0]), r"b'\x1B\x5B\x32\x4B\x07\x41\x0A\x08'")

From 4961a1414bba2222016f29a03dcf75e6034a13f7 Mon Sep 17 00:00:00 2001
From: Sayed Adel 
Date: Sun, 27 Apr 2025 19:08:46 +0300
Subject: [PATCH 113/202] BUG: Fix Clang warning in loops_half.dispatch.c.src
 (#28841)

Fix macro expansion warning [-Wexpansion-to-defined] by removing 'defined'
usage in the NPY__SVML_IS_ENABLED macro expansion.
---
 numpy/_core/src/umath/loops_half.dispatch.c.src | 6 +++++-
 1 file changed, 5 insertions(+), 1 deletion(-)

diff --git a/numpy/_core/src/umath/loops_half.dispatch.c.src b/numpy/_core/src/umath/loops_half.dispatch.c.src
index 82f763e3d43c..a81a64ed0294 100644
--- a/numpy/_core/src/umath/loops_half.dispatch.c.src
+++ b/numpy/_core/src/umath/loops_half.dispatch.c.src
@@ -6,7 +6,11 @@
 #include "fast_loop_macros.h"
 
 
-#define NPY__SVML_IS_ENABLED (NPY_SIMD && defined(NPY_HAVE_AVX512_SKX) && defined(NPY_CAN_LINK_SVML))
+#if NPY_SIMD && defined(NPY_HAVE_AVX512_SKX) && defined(NPY_CAN_LINK_SVML)
+  #define NPY__SVML_IS_ENABLED 1
+#else
+  #define NPY__SVML_IS_ENABLED 0
+#endif
 
 #if NPY__SVML_IS_ENABLED && !defined(NPY_HAVE_AVX512_SPR)
 

From 2ddc86163e6b194edb975629bdfc60bd5af40c0f Mon Sep 17 00:00:00 2001
From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com>
Date: Mon, 28 Apr 2025 18:37:48 +0000
Subject: [PATCH 114/202] MAINT: Bump pypa/cibuildwheel from 2.23.2 to 2.23.3

Bumps [pypa/cibuildwheel](https://github.com/pypa/cibuildwheel) from 2.23.2 to 2.23.3.
- [Release notes](https://github.com/pypa/cibuildwheel/releases)
- [Changelog](https://github.com/pypa/cibuildwheel/blob/main/docs/changelog.md)
- [Commits](https://github.com/pypa/cibuildwheel/compare/d04cacbc9866d432033b1d09142936e6a0e2121a...faf86a6ed7efa889faf6996aa23820831055001a)

---
updated-dependencies:
- dependency-name: pypa/cibuildwheel
  dependency-version: 2.23.3
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] 
---
 .github/workflows/emscripten.yml | 2 +-
 .github/workflows/wheels.yml     | 2 +-
 2 files changed, 2 insertions(+), 2 deletions(-)

diff --git a/.github/workflows/emscripten.yml b/.github/workflows/emscripten.yml
index a1b6e923b131..fea77068e128 100644
--- a/.github/workflows/emscripten.yml
+++ b/.github/workflows/emscripten.yml
@@ -49,7 +49,7 @@ jobs:
           fetch-tags: true
           persist-credentials: false
 
-      - uses: pypa/cibuildwheel@d04cacbc9866d432033b1d09142936e6a0e2121a  # 2.23.2
+      - uses: pypa/cibuildwheel@faf86a6ed7efa889faf6996aa23820831055001a  # 2.23.3
         env:
           CIBW_PLATFORM: pyodide
 
diff --git a/.github/workflows/wheels.yml b/.github/workflows/wheels.yml
index 159ffc4f4131..1107b3caf6f7 100644
--- a/.github/workflows/wheels.yml
+++ b/.github/workflows/wheels.yml
@@ -171,7 +171,7 @@ jobs:
           echo "CIBW_BUILD_FRONTEND=pip; args: --no-build-isolation" >> "$GITHUB_ENV"
 
       - name: Build wheels
-        uses: pypa/cibuildwheel@d04cacbc9866d432033b1d09142936e6a0e2121a  # v2.23.2
+        uses: pypa/cibuildwheel@faf86a6ed7efa889faf6996aa23820831055001a  # v2.23.3
         env:
           CIBW_BUILD: ${{ matrix.python }}-${{ matrix.buildplat[1] }}
 

From 92b815507ffa73301bfe913e574bb5c44479d692 Mon Sep 17 00:00:00 2001
From: jorenham 
Date: Mon, 28 Apr 2025 21:47:20 +0200
Subject: [PATCH 115/202] TYP: add missing ``mod`` params to ``__[r]pow__``

---
 numpy/__init__.pyi | 113 ++++++++++++++++++++++++++-------------------
 numpy/ma/core.pyi  |   4 +-
 2 files changed, 67 insertions(+), 50 deletions(-)

diff --git a/numpy/__init__.pyi b/numpy/__init__.pyi
index 5c16b91b7772..cde24cc9ac97 100644
--- a/numpy/__init__.pyi
+++ b/numpy/__init__.pyi
@@ -3148,66 +3148,70 @@ class ndarray(_ArrayOrScalarCommon, Generic[_ShapeT_co, _DTypeT_co]):
     def __rfloordiv__(self: NDArray[Any], other: _ArrayLikeObject_co, /) -> Any: ...
 
     @overload
-    def __pow__(self: NDArray[_NumberT], other: int | np.bool, /) -> ndarray[_ShapeT_co, dtype[_NumberT]]: ...
+    def __pow__(self: NDArray[_NumberT], other: int | np.bool, mod: None = None, /) -> ndarray[_ShapeT_co, dtype[_NumberT]]: ...
     @overload
-    def __pow__(self: NDArray[_NumberT], other: _ArrayLikeBool_co, /) -> NDArray[_NumberT]: ...  # type: ignore[overload-overlap]
+    def __pow__(self: NDArray[_NumberT], other: _ArrayLikeBool_co, mod: None = None, /) -> NDArray[_NumberT]: ...  # type: ignore[overload-overlap]
     @overload
-    def __pow__(self: NDArray[np.bool], other: _ArrayLikeBool_co, /) -> NDArray[int8]: ...  # type: ignore[overload-overlap]
+    def __pow__(self: NDArray[np.bool], other: _ArrayLikeBool_co, mod: None = None, /) -> NDArray[int8]: ...  # type: ignore[overload-overlap]
     @overload
-    def __pow__(self: NDArray[np.bool], other: _ArrayLike[_NumberT], /) -> NDArray[_NumberT]: ...  # type: ignore[overload-overlap]
+    def __pow__(self: NDArray[np.bool], other: _ArrayLike[_NumberT], mod: None = None, /) -> NDArray[_NumberT]: ...  # type: ignore[overload-overlap]
     @overload
-    def __pow__(self: NDArray[float64], other: _ArrayLikeFloat64_co, /) -> NDArray[float64]: ...
+    def __pow__(self: NDArray[float64], other: _ArrayLikeFloat64_co, mod: None = None, /) -> NDArray[float64]: ...
     @overload
-    def __pow__(self: _ArrayFloat64_co, other: _ArrayLike[floating[_64Bit]], /) -> NDArray[float64]: ...
+    def __pow__(self: _ArrayFloat64_co, other: _ArrayLike[floating[_64Bit]], mod: None = None, /) -> NDArray[float64]: ...
     @overload
-    def __pow__(self: NDArray[complex128], other: _ArrayLikeComplex128_co, /) -> NDArray[complex128]: ...
+    def __pow__(self: NDArray[complex128], other: _ArrayLikeComplex128_co, mod: None = None, /) -> NDArray[complex128]: ...
     @overload
-    def __pow__(self: _ArrayComplex128_co, other: _ArrayLike[complexfloating[_64Bit]], /) -> NDArray[complex128]: ...
+    def __pow__(
+        self: _ArrayComplex128_co, other: _ArrayLike[complexfloating[_64Bit]], mod: None = None, /
+    ) -> NDArray[complex128]: ...
     @overload
-    def __pow__(self: _ArrayUInt_co, other: _ArrayLikeUInt_co, /) -> NDArray[unsignedinteger]: ...  # type: ignore[overload-overlap]
+    def __pow__(self: _ArrayUInt_co, other: _ArrayLikeUInt_co, mod: None = None, /) -> NDArray[unsignedinteger]: ...  # type: ignore[overload-overlap]
     @overload
-    def __pow__(self: _ArrayInt_co, other: _ArrayLikeInt_co, /) -> NDArray[signedinteger]: ...  # type: ignore[overload-overlap]
+    def __pow__(self: _ArrayInt_co, other: _ArrayLikeInt_co, mod: None = None, /) -> NDArray[signedinteger]: ...  # type: ignore[overload-overlap]
     @overload
-    def __pow__(self: _ArrayFloat_co, other: _ArrayLikeFloat_co, /) -> NDArray[floating]: ...  # type: ignore[overload-overlap]
+    def __pow__(self: _ArrayFloat_co, other: _ArrayLikeFloat_co, mod: None = None, /) -> NDArray[floating]: ...  # type: ignore[overload-overlap]
     @overload
-    def __pow__(self: _ArrayComplex_co, other: _ArrayLikeComplex_co, /) -> NDArray[complexfloating]: ...
+    def __pow__(self: _ArrayComplex_co, other: _ArrayLikeComplex_co, mod: None = None, /) -> NDArray[complexfloating]: ...
     @overload
-    def __pow__(self: NDArray[number], other: _ArrayLikeNumber_co, /) -> NDArray[number]: ...
+    def __pow__(self: NDArray[number], other: _ArrayLikeNumber_co, mod: None = None, /) -> NDArray[number]: ...
     @overload
-    def __pow__(self: NDArray[object_], other: Any, /) -> Any: ...
+    def __pow__(self: NDArray[object_], other: Any, mod: None = None, /) -> Any: ...
     @overload
-    def __pow__(self: NDArray[Any], other: _ArrayLikeObject_co, /) -> Any: ...
+    def __pow__(self: NDArray[Any], other: _ArrayLikeObject_co, mod: None = None, /) -> Any: ...
 
     @overload
-    def __rpow__(self: NDArray[_NumberT], other: int | np.bool, /) -> ndarray[_ShapeT_co, dtype[_NumberT]]: ...
+    def __rpow__(self: NDArray[_NumberT], other: int | np.bool, mod: None = None, /) -> ndarray[_ShapeT_co, dtype[_NumberT]]: ...
     @overload
-    def __rpow__(self: NDArray[_NumberT], other: _ArrayLikeBool_co, /) -> NDArray[_NumberT]: ...  # type: ignore[overload-overlap]
+    def __rpow__(self: NDArray[_NumberT], other: _ArrayLikeBool_co, mod: None = None, /) -> NDArray[_NumberT]: ...  # type: ignore[overload-overlap]
     @overload
-    def __rpow__(self: NDArray[np.bool], other: _ArrayLikeBool_co, /) -> NDArray[int8]: ...  # type: ignore[overload-overlap]
+    def __rpow__(self: NDArray[np.bool], other: _ArrayLikeBool_co, mod: None = None, /) -> NDArray[int8]: ...  # type: ignore[overload-overlap]
     @overload
-    def __rpow__(self: NDArray[np.bool], other: _ArrayLike[_NumberT], /) -> NDArray[_NumberT]: ...  # type: ignore[overload-overlap]
+    def __rpow__(self: NDArray[np.bool], other: _ArrayLike[_NumberT], mod: None = None, /) -> NDArray[_NumberT]: ...  # type: ignore[overload-overlap]
     @overload
-    def __rpow__(self: NDArray[float64], other: _ArrayLikeFloat64_co, /) -> NDArray[float64]: ...
+    def __rpow__(self: NDArray[float64], other: _ArrayLikeFloat64_co, mod: None = None, /) -> NDArray[float64]: ...
     @overload
-    def __rpow__(self: _ArrayFloat64_co, other: _ArrayLike[floating[_64Bit]], /) -> NDArray[float64]: ...
+    def __rpow__(self: _ArrayFloat64_co, other: _ArrayLike[floating[_64Bit]], mod: None = None, /) -> NDArray[float64]: ...
     @overload
-    def __rpow__(self: NDArray[complex128], other: _ArrayLikeComplex128_co, /) -> NDArray[complex128]: ...
+    def __rpow__(self: NDArray[complex128], other: _ArrayLikeComplex128_co, mod: None = None, /) -> NDArray[complex128]: ...
     @overload
-    def __rpow__(self: _ArrayComplex128_co, other: _ArrayLike[complexfloating[_64Bit]], /) -> NDArray[complex128]: ...
+    def __rpow__(
+        self: _ArrayComplex128_co, other: _ArrayLike[complexfloating[_64Bit]], mod: None = None, /
+    ) -> NDArray[complex128]: ...
     @overload
-    def __rpow__(self: _ArrayUInt_co, other: _ArrayLikeUInt_co, /) -> NDArray[unsignedinteger]: ...  # type: ignore[overload-overlap]
+    def __rpow__(self: _ArrayUInt_co, other: _ArrayLikeUInt_co, mod: None = None, /) -> NDArray[unsignedinteger]: ...  # type: ignore[overload-overlap]
     @overload
-    def __rpow__(self: _ArrayInt_co, other: _ArrayLikeInt_co, /) -> NDArray[signedinteger]: ...  # type: ignore[overload-overlap]
+    def __rpow__(self: _ArrayInt_co, other: _ArrayLikeInt_co, mod: None = None, /) -> NDArray[signedinteger]: ...  # type: ignore[overload-overlap]
     @overload
-    def __rpow__(self: _ArrayFloat_co, other: _ArrayLikeFloat_co, /) -> NDArray[floating]: ...  # type: ignore[overload-overlap]
+    def __rpow__(self: _ArrayFloat_co, other: _ArrayLikeFloat_co, mod: None = None, /) -> NDArray[floating]: ...  # type: ignore[overload-overlap]
     @overload
-    def __rpow__(self: _ArrayComplex_co, other: _ArrayLikeComplex_co, /) -> NDArray[complexfloating]: ...
+    def __rpow__(self: _ArrayComplex_co, other: _ArrayLikeComplex_co, mod: None = None, /) -> NDArray[complexfloating]: ...
     @overload
-    def __rpow__(self: NDArray[number], other: _ArrayLikeNumber_co, /) -> NDArray[number]: ...
+    def __rpow__(self: NDArray[number], other: _ArrayLikeNumber_co, mod: None = None, /) -> NDArray[number]: ...
     @overload
-    def __rpow__(self: NDArray[object_], other: Any, /) -> Any: ...
+    def __rpow__(self: NDArray[object_], other: Any, mod: None = None, /) -> Any: ...
     @overload
-    def __rpow__(self: NDArray[Any], other: _ArrayLikeObject_co, /) -> Any: ...
+    def __rpow__(self: NDArray[Any], other: _ArrayLikeObject_co, mod: None = None, /) -> Any: ...
 
     @overload
     def __lshift__(self: NDArray[np.bool], other: _ArrayLikeBool_co, /) -> NDArray[int8]: ...  # type: ignore[misc]
@@ -4247,21 +4251,25 @@ class float64(floating[_64Bit], float):  # type: ignore[misc]
     def __rfloordiv__(self, other: complex, /) -> float64 | complex128: ...
 
     @overload
-    def __pow__(self, other: _Float64_co, /) -> float64: ...
+    def __pow__(self, other: _Float64_co, mod: None = None, /) -> float64: ...
     @overload
-    def __pow__(self, other: complexfloating[_64Bit, _64Bit], /) -> complex128: ...
+    def __pow__(self, other: complexfloating[_64Bit, _64Bit], mod: None = None, /) -> complex128: ...
     @overload
-    def __pow__(self, other: complexfloating[_NBit1, _NBit2], /) -> complexfloating[_NBit1 | _64Bit, _NBit2 | _64Bit]: ...
+    def __pow__(
+        self, other: complexfloating[_NBit1, _NBit2], mod: None = None, /
+    ) -> complexfloating[_NBit1 | _64Bit, _NBit2 | _64Bit]: ...
     @overload
-    def __pow__(self, other: complex, /) -> float64 | complex128: ...
+    def __pow__(self, other: complex, mod: None = None, /) -> float64 | complex128: ...
     @overload
-    def __rpow__(self, other: _Float64_co, /) -> float64: ...
+    def __rpow__(self, other: _Float64_co, mod: None = None, /) -> float64: ...
     @overload
-    def __rpow__(self, other: complexfloating[_64Bit, _64Bit], /) -> complex128: ...
+    def __rpow__(self, other: complexfloating[_64Bit, _64Bit], mod: None = None, /) -> complex128: ...
     @overload
-    def __rpow__(self, other: complexfloating[_NBit1, _NBit2], /) -> complexfloating[_NBit1 | _64Bit, _NBit2 | _64Bit]: ...
+    def __rpow__(
+        self, other: complexfloating[_NBit1, _NBit2], mod: None = None, /
+    ) -> complexfloating[_NBit1 | _64Bit, _NBit2 | _64Bit]: ...
     @overload
-    def __rpow__(self, other: complex, /) -> float64 | complex128: ...
+    def __rpow__(self, other: complex, mod: None = None, /) -> float64 | complex128: ...
 
     def __mod__(self, other: _Float64_co, /) -> float64: ...  # type: ignore[override]
     def __rmod__(self, other: _Float64_co, /) -> float64: ...  # type: ignore[override]
@@ -4351,17 +4359,23 @@ class complexfloating(inexact[_NBit1, complex], Generic[_NBit1, _NBit2]):
     def __rtruediv__(self, other: number[_NBit], /) -> complexfloating[_NBit1, _NBit2] | complexfloating[_NBit, _NBit]: ...
 
     @overload
-    def __pow__(self, other: _Complex64_co, /) -> complexfloating[_NBit1, _NBit2]: ...
+    def __pow__(self, other: _Complex64_co, mod: None = None, /) -> complexfloating[_NBit1, _NBit2]: ...
     @overload
-    def __pow__(self, other: complex | float64 | complex128, /) -> complexfloating[_NBit1, _NBit2] | complex128: ...
+    def __pow__(
+        self, other: complex | float64 | complex128, mod: None = None, /
+    ) -> complexfloating[_NBit1, _NBit2] | complex128: ...
     @overload
-    def __pow__(self, other: number[_NBit], /) -> complexfloating[_NBit1, _NBit2] | complexfloating[_NBit, _NBit]: ...
+    def __pow__(
+        self, other: number[_NBit], mod: None = None, /
+    ) -> complexfloating[_NBit1, _NBit2] | complexfloating[_NBit, _NBit]: ...
     @overload
-    def __rpow__(self, other: _Complex64_co, /) -> complexfloating[_NBit1, _NBit2]: ...
+    def __rpow__(self, other: _Complex64_co, mod: None = None, /) -> complexfloating[_NBit1, _NBit2]: ...
     @overload
-    def __rpow__(self, other: complex, /) -> complexfloating[_NBit1, _NBit2] | complex128: ...
+    def __rpow__(self, other: complex, mod: None = None, /) -> complexfloating[_NBit1, _NBit2] | complex128: ...
     @overload
-    def __rpow__(self, other: number[_NBit], /) -> complexfloating[_NBit1, _NBit2] | complexfloating[_NBit, _NBit]: ...
+    def __rpow__(
+        self, other: number[_NBit], mod: None = None, /
+    ) -> complexfloating[_NBit1, _NBit2] | complexfloating[_NBit, _NBit]: ...
 
 complex64: TypeAlias = complexfloating[_32Bit, _32Bit]
 
@@ -4417,10 +4431,12 @@ class complex128(complexfloating[_64Bit, _64Bit], complex):  # type: ignore[misc
     def __rtruediv__(self, other: _Complex128_co, /) -> complex128: ...
 
     @overload
-    def __pow__(self, other: _Complex128_co, /) -> complex128: ...
+    def __pow__(self, other: _Complex128_co, mod: None = None, /) -> complex128: ...
     @overload
-    def __pow__(self, other: complexfloating[_NBit1, _NBit2], /) -> complexfloating[_NBit1 | _64Bit, _NBit2 | _64Bit]: ...
-    def __rpow__(self, other: _Complex128_co, /) -> complex128: ...
+    def __pow__(
+        self, other: complexfloating[_NBit1, _NBit2], mod: None = None, /
+    ) -> complexfloating[_NBit1 | _64Bit, _NBit2 | _64Bit]: ...
+    def __rpow__(self, other: _Complex128_co, mod: None = None, /) -> complex128: ...
 
 csingle: TypeAlias = complexfloating[_NBitSingle, _NBitSingle]
 cdouble: TypeAlias = complexfloating[_NBitDouble, _NBitDouble]
@@ -5280,7 +5296,8 @@ class matrix(ndarray[_2DShapeT_co, _DTypeT_co]):
     def __mul__(self, other: ArrayLike, /) -> matrix[_2D, Any]: ...
     def __rmul__(self, other: ArrayLike, /) -> matrix[_2D, Any]: ...
     def __imul__(self, other: ArrayLike, /) -> matrix[_2DShapeT_co, _DTypeT_co]: ...
-    def __pow__(self, other: ArrayLike, /) -> matrix[_2D, Any]: ...
+    def __pow__(self, other: ArrayLike, mod: None = None, /) -> matrix[_2D, Any]: ...
+    def __rpow__(self, other: ArrayLike, mod: None = None, /) -> matrix[_2D, Any]: ...
     def __ipow__(self, other: ArrayLike, /) -> matrix[_2DShapeT_co, _DTypeT_co]: ...
 
     @overload
diff --git a/numpy/ma/core.pyi b/numpy/ma/core.pyi
index 71652e047905..06456637f5fc 100644
--- a/numpy/ma/core.pyi
+++ b/numpy/ma/core.pyi
@@ -457,8 +457,8 @@ class MaskedArray(ndarray[_ShapeT_co, _DTypeT_co]):
     def __rtruediv__(self, other): ...
     def __floordiv__(self, other): ...
     def __rfloordiv__(self, other): ...
-    def __pow__(self, other): ...
-    def __rpow__(self, other): ...
+    def __pow__(self, other, mod: None = None, /): ...
+    def __rpow__(self, other, mod: None = None, /): ...
     def __iadd__(self, other): ...
     def __isub__(self, other): ...
     def __imul__(self, other): ...

From 251272cee4d0bcca826151deb48bbda451de0a9c Mon Sep 17 00:00:00 2001
From: jorenham 
Date: Mon, 28 Apr 2025 22:17:55 +0200
Subject: [PATCH 116/202] TYP: generic ``StringDType``

---
 numpy/dtypes.pyi | 45 +++++++++++++++++++++++++++++----------------
 1 file changed, 29 insertions(+), 16 deletions(-)

diff --git a/numpy/dtypes.pyi b/numpy/dtypes.pyi
index fad612380359..98829745e067 100644
--- a/numpy/dtypes.pyi
+++ b/numpy/dtypes.pyi
@@ -1,6 +1,5 @@
 # ruff: noqa: ANN401
-from types import MemberDescriptorType
-from typing import Any, ClassVar, Generic, LiteralString, NoReturn, Self, TypeAlias, final, type_check_only
+from typing import Any, Generic, LiteralString, Never, NoReturn, Self, TypeAlias, final, overload, type_check_only
 from typing import Literal as L
 
 from typing_extensions import TypeVar
@@ -568,40 +567,54 @@ class TimeDelta64DType(  # type: ignore[misc]
         "m8[as]",
     ]: ...
 
+_NaObjectT_co = TypeVar("_NaObjectT_co", default=Never, covariant=True)
+
 @final
 class StringDType(  # type: ignore[misc]
     _TypeCodes[L["T"], L["T"], L[2056]],
     _NativeOrder,
     _NBit[L[8], L[16]],
-    # TODO: Replace the (invalid) `str` with the scalar type, once implemented
-    np.dtype[str],  # type: ignore[type-var]  # pyright: ignore[reportGeneralTypeIssues,reportInvalidTypeArguments]
+    # TODO(jorenham): change once we have a string scalar type:
+    # https://github.com/numpy/numpy/pull/28196
+    np.dtype[str],  # type: ignore[type-var]  # pyright: ignore[reportGeneralTypeIssues, reportInvalidTypeArguments]
+    Generic[_NaObjectT_co],
 ):
+    @property
+    def na_object(self) -> _NaObjectT_co: ...
     @property
     def coerce(self) -> L[True]: ...
-    na_object: ClassVar[MemberDescriptorType]  # does not get instantiated
 
     #
-    def __new__(cls, /) -> StringDType: ...
-    def __getitem__(self, key: Any, /) -> NoReturn: ...
-    @property
-    def base(self) -> StringDType: ...
+    @overload
+    def __new__(cls, /, *, coerce: bool = True) -> Self: ...
+    @overload
+    def __new__(cls, /, *, na_object: _NaObjectT_co, coerce: bool = True) -> Self: ...
+
+    #
+    def __getitem__(self, key: Never, /) -> NoReturn: ...  # type: ignore[override]  # pyright: ignore[reportIncompatibleMethodOverride]
     @property
     def fields(self) -> None: ...
     @property
-    def hasobject(self) -> L[True]: ...
+    def base(self) -> Self: ...
     @property
-    def isalignedstruct(self) -> L[False]: ...
+    def ndim(self) -> L[0]: ...
     @property
-    def isnative(self) -> L[True]: ...
+    def shape(self) -> tuple[()]: ...
+
+    #
     @property
     def name(self) -> L["StringDType64", "StringDType128"]: ...
     @property
-    def ndim(self) -> L[0]: ...
+    def subdtype(self) -> None: ...
     @property
-    def shape(self) -> tuple[()]: ...
+    def type(self) -> type[str]: ...
     @property
     def str(self) -> L["|T8", "|T16"]: ...
+
+    #
     @property
-    def subdtype(self) -> None: ...
+    def hasobject(self) -> L[True]: ...
     @property
-    def type(self) -> type[str]: ...  # type: ignore[valid-type]
+    def isalignedstruct(self) -> L[False]: ...
+    @property
+    def isnative(self) -> L[True]: ...

From 467117e044e1afbfb06952825a3e4e768188aa01 Mon Sep 17 00:00:00 2001
From: jorenham 
Date: Mon, 28 Apr 2025 22:36:57 +0200
Subject: [PATCH 117/202] DOC: add release note for #28856

---
 doc/release/upcoming_changes/28856.improvement.rst | 5 +++++
 1 file changed, 5 insertions(+)
 create mode 100644 doc/release/upcoming_changes/28856.improvement.rst

diff --git a/doc/release/upcoming_changes/28856.improvement.rst b/doc/release/upcoming_changes/28856.improvement.rst
new file mode 100644
index 000000000000..83911035f097
--- /dev/null
+++ b/doc/release/upcoming_changes/28856.improvement.rst
@@ -0,0 +1,5 @@
+* ``np.dtypes.StringDType`` is now a
+  `generic type `_ which
+  accepts a type argument for ``na_object`` that defaults to ``typing.Never``.
+  For example, ``StringDType(na_object=None)`` returns a ``StringDType[None]``,
+  and ``StringDType()`` returns a ``StringDType[typing.Never]``.

From 58a7a9ed49db4b3e1bf96dfadcae463745e14728 Mon Sep 17 00:00:00 2001
From: jorenham 
Date: Mon, 28 Apr 2025 22:50:33 +0200
Subject: [PATCH 118/202] TYP: implicit ``linalg`` private submodule re-exports

ported from numpy/numtype#380
---
 numpy/linalg/__init__.pyi | 91 ++++++++++++++++++++-------------------
 1 file changed, 47 insertions(+), 44 deletions(-)

diff --git a/numpy/linalg/__init__.pyi b/numpy/linalg/__init__.pyi
index 119ca0d0683d..16c8048c1a11 100644
--- a/numpy/linalg/__init__.pyi
+++ b/numpy/linalg/__init__.pyi
@@ -1,70 +1,73 @@
-from numpy._core.fromnumeric import matrix_transpose
-from numpy._core.numeric import tensordot, vecdot
-
+from . import _linalg as _linalg
+from . import _umath_linalg as _umath_linalg
+from . import linalg as linalg
 from ._linalg import (
-    matrix_power,
-    solve,
-    tensorsolve,
-    tensorinv,
-    inv,
     cholesky,
-    outer,
-    eigvals,
-    eigvalsh,
-    pinv,
-    slogdet,
+    cond,
+    cross,
     det,
-    svd,
-    svdvals,
+    diagonal,
     eig,
     eigh,
+    eigvals,
+    eigvalsh,
+    inv,
     lstsq,
-    norm,
+    matmul,
     matrix_norm,
-    vector_norm,
-    qr,
-    cond,
+    matrix_power,
     matrix_rank,
+    matrix_transpose,
     multi_dot,
-    matmul,
+    norm,
+    outer,
+    pinv,
+    qr,
+    slogdet,
+    solve,
+    svd,
+    svdvals,
+    tensordot,
+    tensorinv,
+    tensorsolve,
     trace,
-    diagonal,
-    cross,
+    vecdot,
+    vector_norm,
 )
 
 __all__ = [
-    "matrix_power",
-    "solve",
-    "tensorsolve",
-    "tensorinv",
-    "inv",
+    "LinAlgError",
     "cholesky",
-    "eigvals",
-    "eigvalsh",
-    "pinv",
-    "slogdet",
+    "cond",
+    "cross",
     "det",
-    "svd",
-    "svdvals",
+    "diagonal",
     "eig",
     "eigh",
+    "eigvals",
+    "eigvalsh",
+    "inv",
     "lstsq",
-    "norm",
-    "qr",
-    "cond",
+    "matmul",
+    "matrix_norm",
+    "matrix_power",
     "matrix_rank",
-    "LinAlgError",
+    "matrix_transpose",
     "multi_dot",
-    "trace",
-    "diagonal",
-    "cross",
+    "norm",
     "outer",
+    "pinv",
+    "qr",
+    "slogdet",
+    "solve",
+    "svd",
+    "svdvals",
     "tensordot",
-    "matmul",
-    "matrix_transpose",
-    "matrix_norm",
-    "vector_norm",
+    "tensorinv",
+    "tensorsolve",
+    "trace",
     "vecdot",
+    "vector_norm",
 ]
 
 class LinAlgError(ValueError): ...

From edde6b632a5c213607d325fc234da3556585fd5c Mon Sep 17 00:00:00 2001
From: jorenham 
Date: Mon, 28 Apr 2025 23:32:51 +0200
Subject: [PATCH 119/202] TYP: fix the ``set_module`` signature

---
 numpy/_utils/__init__.pyi | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/numpy/_utils/__init__.pyi b/numpy/_utils/__init__.pyi
index 4e8eca9e9a11..f3472df9a554 100644
--- a/numpy/_utils/__init__.pyi
+++ b/numpy/_utils/__init__.pyi
@@ -20,7 +20,7 @@ class _HasModule(Protocol):
 @overload
 def set_module(module: None) -> IdentityFunction: ...
 @overload
-def set_module(module: _HasModuleT) -> _HasModuleT: ...
+def set_module(module: str) -> Callable[[_HasModuleT], _HasModuleT]: ...
 
 #
 def _rename_parameter(

From 71f146db602f44a67cd16b44f00a2afd2bd779ef Mon Sep 17 00:00:00 2001
From: Dimitri Papadopoulos
 <3234522+DimitriPapadopoulos@users.noreply.github.com>
Date: Tue, 29 Apr 2025 09:09:32 +0200
Subject: [PATCH 120/202] =?UTF-8?q?DOC:=20http://=20=E2=86=92=20https://?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit

Update a few links in the process.
---
 doc/source/building/index.rst                 |  2 +-
 doc/source/building/introspecting_a_build.rst |  2 +-
 doc/source/f2py/f2py.getting-started.rst      |  2 +-
 doc/source/f2py/windows/index.rst             |  2 +-
 doc/source/user/basics.dispatch.rst           |  4 ++--
 doc/source/user/c-info.python-as-glue.rst     |  2 +-
 doc/source/user/numpy-for-matlab-users.rst    |  2 +-
 numpy/distutils/system_info.py                | 14 +++++++-------
 8 files changed, 15 insertions(+), 15 deletions(-)

diff --git a/doc/source/building/index.rst b/doc/source/building/index.rst
index 3a9709f1ebc1..d7baeaee9324 100644
--- a/doc/source/building/index.rst
+++ b/doc/source/building/index.rst
@@ -52,7 +52,7 @@ your system.
     * BLAS and LAPACK libraries. `OpenBLAS `__
       is the NumPy default; other variants include Apple Accelerate,
       `MKL `__,
-      `ATLAS `__ and
+      `ATLAS `__ and
       `Netlib `__ (or "Reference")
       BLAS and LAPACK.
 
diff --git a/doc/source/building/introspecting_a_build.rst b/doc/source/building/introspecting_a_build.rst
index f23628bf3ffd..268365f595bf 100644
--- a/doc/source/building/introspecting_a_build.rst
+++ b/doc/source/building/introspecting_a_build.rst
@@ -19,4 +19,4 @@ These things are all available after the configure stage of the build (i.e.,
 information, rather than running the build and reading the full build log.
 
 For more details on this topic, see the
-`SciPy doc page on build introspection `__.
+`SciPy doc page on build introspection `__.
diff --git a/doc/source/f2py/f2py.getting-started.rst b/doc/source/f2py/f2py.getting-started.rst
index dd1349979a39..e5746c49e94d 100644
--- a/doc/source/f2py/f2py.getting-started.rst
+++ b/doc/source/f2py/f2py.getting-started.rst
@@ -308,4 +308,4 @@ the previous case::
   >>> print(fib3.fib(8))
   [  0.   1.   1.   2.   3.   5.   8.  13.]
 
-.. _`system dependencies panel`: http://scipy.github.io/devdocs/building/index.html#system-level-dependencies
+.. _`system dependencies panel`: https://scipy.github.io/devdocs/building/index.html#system-level-dependencies
diff --git a/doc/source/f2py/windows/index.rst b/doc/source/f2py/windows/index.rst
index 797dfc2b4179..ea0af7505ce7 100644
--- a/doc/source/f2py/windows/index.rst
+++ b/doc/source/f2py/windows/index.rst
@@ -217,4 +217,4 @@ path using a hash. This needs to be added to the ``PATH`` variable.
 .. _are outdated: https://github.com/conda-forge/conda-forge.github.io/issues/1044
 .. _now deprecated: https://github.com/numpy/numpy/pull/20875
 .. _LLVM Flang: https://releases.llvm.org/11.0.0/tools/flang/docs/ReleaseNotes.html
-.. _SciPy's documentation: http://scipy.github.io/devdocs/building/index.html#system-level-dependencies
+.. _SciPy's documentation: https://scipy.github.io/devdocs/building/index.html#system-level-dependencies
diff --git a/doc/source/user/basics.dispatch.rst b/doc/source/user/basics.dispatch.rst
index 1505c9285ea8..ae53995a3917 100644
--- a/doc/source/user/basics.dispatch.rst
+++ b/doc/source/user/basics.dispatch.rst
@@ -7,8 +7,8 @@ Writing custom array containers
 Numpy's dispatch mechanism, introduced in numpy version v1.16 is the
 recommended approach for writing custom N-dimensional array containers that are
 compatible with the numpy API and provide custom implementations of numpy
-functionality. Applications include `dask `_ arrays, an
-N-dimensional array distributed across multiple nodes, and `cupy
+functionality. Applications include `dask `_
+arrays, an N-dimensional array distributed across multiple nodes, and `cupy
 `_ arrays, an N-dimensional array on
 a GPU.
 
diff --git a/doc/source/user/c-info.python-as-glue.rst b/doc/source/user/c-info.python-as-glue.rst
index d791341ac560..c699760fdebd 100644
--- a/doc/source/user/c-info.python-as-glue.rst
+++ b/doc/source/user/c-info.python-as-glue.rst
@@ -144,7 +144,7 @@ written C-code.
 Cython
 ======
 
-`Cython `_ is a compiler for a Python dialect that adds
+`Cython `_ is a compiler for a Python dialect that adds
 (optional) static typing for speed, and allows mixing C or C++ code
 into your modules. It produces C or C++ extensions that can be compiled
 and imported in Python code.
diff --git a/doc/source/user/numpy-for-matlab-users.rst b/doc/source/user/numpy-for-matlab-users.rst
index a3ced19e23ad..370a1f7ab435 100644
--- a/doc/source/user/numpy-for-matlab-users.rst
+++ b/doc/source/user/numpy-for-matlab-users.rst
@@ -810,7 +810,7 @@ Links
 =====
 
 Another somewhat outdated MATLAB/NumPy cross-reference can be found at
-http://mathesaurus.sf.net/
+https://mathesaurus.sourceforge.net/
 
 An extensive list of tools for scientific work with Python can be
 found in the `topical software page `__.
diff --git a/numpy/distutils/system_info.py b/numpy/distutils/system_info.py
index e428b47f08d4..4702742e4589 100644
--- a/numpy/distutils/system_info.py
+++ b/numpy/distutils/system_info.py
@@ -604,7 +604,7 @@ class AliasedOptionError(DistutilsError):
 
 class AtlasNotFoundError(NotFoundError):
     """
-    Atlas (http://github.com/math-atlas/math-atlas) libraries not found.
+    Atlas (https://github.com/math-atlas/math-atlas) libraries not found.
     Directories to search for the libraries can be specified in the
     numpy/distutils/site.cfg file (section [atlas]) or by setting
     the ATLAS environment variable."""
@@ -612,14 +612,14 @@ class AtlasNotFoundError(NotFoundError):
 
 class FlameNotFoundError(NotFoundError):
     """
-    FLAME (http://www.cs.utexas.edu/~flame/web/) libraries not found.
+    FLAME (https://shpc.oden.utexas.edu/libFLAME.html) libraries not found.
     Directories to search for the libraries can be specified in the
     numpy/distutils/site.cfg file (section [flame])."""
 
 
 class LapackNotFoundError(NotFoundError):
     """
-    Lapack (http://www.netlib.org/lapack/) libraries not found.
+    Lapack (https://www.netlib.org/lapack/) libraries not found.
     Directories to search for the libraries can be specified in the
     numpy/distutils/site.cfg file (section [lapack]) or by setting
     the LAPACK environment variable."""
@@ -627,7 +627,7 @@ class LapackNotFoundError(NotFoundError):
 
 class LapackSrcNotFoundError(LapackNotFoundError):
     """
-    Lapack (http://www.netlib.org/lapack/) sources not found.
+    Lapack (https://www.netlib.org/lapack/) sources not found.
     Directories to search for the sources can be specified in the
     numpy/distutils/site.cfg file (section [lapack_src]) or by setting
     the LAPACK_SRC environment variable."""
@@ -649,7 +649,7 @@ class BlasOptNotFoundError(NotFoundError):
 
 class BlasNotFoundError(NotFoundError):
     """
-    Blas (http://www.netlib.org/blas/) libraries not found.
+    Blas (https://www.netlib.org/blas/) libraries not found.
     Directories to search for the libraries can be specified in the
     numpy/distutils/site.cfg file (section [blas]) or by setting
     the BLAS environment variable."""
@@ -663,7 +663,7 @@ class BlasILP64NotFoundError(NotFoundError):
 
 class BlasSrcNotFoundError(BlasNotFoundError):
     """
-    Blas (http://www.netlib.org/blas/) sources not found.
+    Blas (https://www.netlib.org/blas/) sources not found.
     Directories to search for the sources can be specified in the
     numpy/distutils/site.cfg file (section [blas_src]) or by setting
     the BLAS_SRC environment variable."""
@@ -671,7 +671,7 @@ class BlasSrcNotFoundError(BlasNotFoundError):
 
 class FFTWNotFoundError(NotFoundError):
     """
-    FFTW (http://www.fftw.org/) libraries not found.
+    FFTW (https://www.fftw.org/) libraries not found.
     Directories to search for the libraries can be specified in the
     numpy/distutils/site.cfg file (section [fftw]) or by setting
     the FFTW environment variable."""

From db8ff5cda8da14bb720e80cd749f30a8de2afa9a Mon Sep 17 00:00:00 2001
From: Ralf Gommers 
Date: Tue, 29 Apr 2025 08:13:45 +0200
Subject: [PATCH 121/202] BLD: update vendored Meson: v1.6.1 and iOS support
 [wheel build]

These are PRs 18 and 19 from https://github.com/numpy/meson
---
 vendored-meson/meson | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/vendored-meson/meson b/vendored-meson/meson
index 7300f5fd4c1c..23ec306e6510 160000
--- a/vendored-meson/meson
+++ b/vendored-meson/meson
@@ -1 +1 @@
-Subproject commit 7300f5fd4c1c8b0406faeec4cc631f11f1ea324c
+Subproject commit 23ec306e65107f5ad39a03709799dc90ea678a54

From 9642714c7328bca8434c8895968f9d814b576788 Mon Sep 17 00:00:00 2001
From: Nathan Goldbaum 
Date: Tue, 29 Apr 2025 08:33:12 -0600
Subject: [PATCH 122/202] BUG: set the array_owned flag on the StringDType
 singleton

---
 numpy/_core/src/multiarray/stringdtype/dtype.c | 9 ++++++---
 1 file changed, 6 insertions(+), 3 deletions(-)

diff --git a/numpy/_core/src/multiarray/stringdtype/dtype.c b/numpy/_core/src/multiarray/stringdtype/dtype.c
index 41dfa7c21ca1..167ab86f5dc4 100644
--- a/numpy/_core/src/multiarray/stringdtype/dtype.c
+++ b/numpy/_core/src/multiarray/stringdtype/dtype.c
@@ -850,14 +850,17 @@ init_string_dtype(void)
         return -1;
     }
 
-    PyArray_Descr *singleton =
-            NPY_DT_CALL_default_descr(&PyArray_StringDType);
+    PyArray_StringDTypeObject *singleton =
+            (PyArray_StringDTypeObject *)NPY_DT_CALL_default_descr(&PyArray_StringDType);
 
     if (singleton == NULL) {
         return -1;
     }
 
-    PyArray_StringDType.singleton = singleton;
+    // never associate the singleton with an array
+    singleton->array_owned = 1;
+
+    PyArray_StringDType.singleton = (PyArray_Descr *)singleton;
     PyArray_StringDType.type_num = NPY_VSTRING;
 
     for (int i = 0; PyArray_StringDType_casts[i] != NULL; i++) {

From aed1f5b2b1c931e345bdda08ff03ce8f3720e2c3 Mon Sep 17 00:00:00 2001
From: Nathan Goldbaum 
Date: Tue, 29 Apr 2025 08:33:35 -0600
Subject: [PATCH 123/202] ENH: acquire the allocator lock when setting the
 array_owned flag

---
 numpy/_core/src/multiarray/stringdtype/dtype.c | 5 +++++
 1 file changed, 5 insertions(+)

diff --git a/numpy/_core/src/multiarray/stringdtype/dtype.c b/numpy/_core/src/multiarray/stringdtype/dtype.c
index 167ab86f5dc4..a06e7a1ed1b6 100644
--- a/numpy/_core/src/multiarray/stringdtype/dtype.c
+++ b/numpy/_core/src/multiarray/stringdtype/dtype.c
@@ -633,11 +633,16 @@ PyArray_Descr *
 stringdtype_finalize_descr(PyArray_Descr *dtype)
 {
     PyArray_StringDTypeObject *sdtype = (PyArray_StringDTypeObject *)dtype;
+    // acquire the allocator lock in case the descriptor we want to finalize
+    // is shared between threads, see gh-28813
+    npy_string_allocator *allocator = NpyString_acquire_allocator(sdtype);
     if (sdtype->array_owned == 0) {
         sdtype->array_owned = 1;
+        NpyString_release_allocator(allocator);
         Py_INCREF(dtype);
         return dtype;
     }
+    NpyString_release_allocator(allocator);
     PyArray_StringDTypeObject *ret = (PyArray_StringDTypeObject *)new_stringdtype_instance(
             sdtype->na_object, sdtype->coerce);
     ret->array_owned = 1;

From d692fbccd98cb880812b32936e5f94fcfe55053f Mon Sep 17 00:00:00 2001
From: Krishna Bindumadhavan <31140965+f2013519@users.noreply.github.com>
Date: Tue, 29 Apr 2025 21:59:05 +0530
Subject: [PATCH 124/202] ENH: Improve Floating Point Cast Performance on ARM
 (#28769)

* WIP,Prototype: Use Neon SIMD to improve half->float cast performance
[ci skip] [skip ci]

* Support Neon SIMD float32->float16 cast and update scalar path to use hardware cast

* Add missing header

* Relax VECTOR_ARITHMETIC check and add comment on need for SIMD routines

* Enable hardware cast on x86 when F16C is available

* Relax fp exceptions in Clang to enable vectorization for cast

* Ignore fp exceptions only for float casts

* Fix build

* Attempt to fix test failure on ARM64 native

* Work around gcc bug for double->half casts

* Add release note
---
 .../upcoming_changes/28769.performance.rst    |  8 +++
 .../multiarray/lowlevel_strided_loops.c.src   | 71 +++++++++++++++----
 2 files changed, 66 insertions(+), 13 deletions(-)
 create mode 100644 doc/release/upcoming_changes/28769.performance.rst

diff --git a/doc/release/upcoming_changes/28769.performance.rst b/doc/release/upcoming_changes/28769.performance.rst
new file mode 100644
index 000000000000..7fb8f02282f6
--- /dev/null
+++ b/doc/release/upcoming_changes/28769.performance.rst
@@ -0,0 +1,8 @@
+Performance improvements for ``np.float16`` casts
+--------------------------------------------------
+Earlier, floating point casts to and from ``np.float16`` types
+were emulated in software on all platforms.
+
+Now, on ARM devices that support Neon float16 intrinsics (such as
+recent Apple Silicon), the native float16 path is used to achieve
+the best performance.
diff --git a/numpy/_core/src/multiarray/lowlevel_strided_loops.c.src b/numpy/_core/src/multiarray/lowlevel_strided_loops.c.src
index 1299e55b4258..01ffd225274f 100644
--- a/numpy/_core/src/multiarray/lowlevel_strided_loops.c.src
+++ b/numpy/_core/src/multiarray/lowlevel_strided_loops.c.src
@@ -708,6 +708,16 @@ NPY_NO_EXPORT PyArrayMethod_StridedLoop *
 
 /************* STRIDED CASTING SPECIALIZED FUNCTIONS *************/
 
+#if defined(NPY_HAVE_NEON_FP16)
+    #define EMULATED_FP16 0
+    #define NATIVE_FP16 1
+    typedef _Float16 _npy_half;
+#else
+    #define EMULATED_FP16 1
+    #define NATIVE_FP16 0
+    typedef npy_half _npy_half;
+#endif
+
 /**begin repeat
  *
  * #NAME1 = BOOL,
@@ -723,15 +733,16 @@ NPY_NO_EXPORT PyArrayMethod_StridedLoop *
  * #type1 = npy_bool,
  *          npy_ubyte, npy_ushort, npy_uint, npy_ulong, npy_ulonglong,
  *          npy_byte, npy_short, npy_int, npy_long, npy_longlong,
- *          npy_half, npy_float, npy_double, npy_longdouble,
+ *          _npy_half, npy_float, npy_double, npy_longdouble,
  *          npy_cfloat, npy_cdouble, npy_clongdouble#
  * #rtype1 = npy_bool,
  *           npy_ubyte, npy_ushort, npy_uint, npy_ulong, npy_ulonglong,
  *           npy_byte, npy_short, npy_int, npy_long, npy_longlong,
- *           npy_half, npy_float, npy_double, npy_longdouble,
+ *           _npy_half, npy_float, npy_double, npy_longdouble,
  *           npy_float, npy_double, npy_longdouble#
  * #is_bool1 = 1, 0*17#
- * #is_half1 = 0*11, 1, 0*6#
+ * #is_emu_half1 = 0*11, EMULATED_FP16, 0*6#
+ * #is_native_half1 = 0*11, NATIVE_FP16, 0*6#
  * #is_float1 = 0*12, 1, 0, 0, 1, 0, 0#
  * #is_double1 = 0*13, 1, 0, 0, 1, 0#
  * #is_complex1 = 0*15, 1*3#
@@ -752,15 +763,16 @@ NPY_NO_EXPORT PyArrayMethod_StridedLoop *
  * #type2 = npy_bool,
  *          npy_ubyte, npy_ushort, npy_uint, npy_ulong, npy_ulonglong,
  *          npy_byte, npy_short, npy_int, npy_long, npy_longlong,
- *          npy_half, npy_float, npy_double, npy_longdouble,
+ *          _npy_half, npy_float, npy_double, npy_longdouble,
  *          npy_cfloat, npy_cdouble, npy_clongdouble#
  * #rtype2 = npy_bool,
  *          npy_ubyte, npy_ushort, npy_uint, npy_ulong, npy_ulonglong,
  *          npy_byte, npy_short, npy_int, npy_long, npy_longlong,
- *          npy_half, npy_float, npy_double, npy_longdouble,
+ *          _npy_half, npy_float, npy_double, npy_longdouble,
  *          npy_float, npy_double, npy_longdouble#
  * #is_bool2 = 1, 0*17#
- * #is_half2 = 0*11, 1, 0*6#
+ * #is_emu_half2 = 0*11, EMULATED_FP16, 0*6#
+ * #is_native_half2 = 0*11, NATIVE_FP16, 0*6#
  * #is_float2 = 0*12, 1, 0, 0, 1, 0, 0#
  * #is_double2 = 0*13, 1, 0, 0, 1, 0#
  * #is_complex2 = 0*15, 1*3#
@@ -774,8 +786,8 @@ NPY_NO_EXPORT PyArrayMethod_StridedLoop *
 
 #if !(NPY_USE_UNALIGNED_ACCESS && !@aligned@)
 
-/* For half types, don't use actual double/float types in conversion */
-#if @is_half1@ || @is_half2@
+/* For emulated half types, don't use actual double/float types in conversion */
+#if @is_emu_half1@ || @is_emu_half2@
 
 #  if @is_float1@
 #    define _TYPE1 npy_uint32
@@ -801,13 +813,13 @@ NPY_NO_EXPORT PyArrayMethod_StridedLoop *
 #endif
 
 /* Determine an appropriate casting conversion function */
-#if @is_half1@
+#if @is_emu_half1@
 
 #  if @is_float2@
 #    define _CONVERT_FN(x) npy_halfbits_to_floatbits(x)
 #  elif @is_double2@
 #    define _CONVERT_FN(x) npy_halfbits_to_doublebits(x)
-#  elif @is_half2@
+#  elif @is_emu_half2@
 #    define _CONVERT_FN(x) (x)
 #  elif @is_bool2@
 #    define _CONVERT_FN(x) ((npy_bool)!npy_half_iszero(x))
@@ -815,13 +827,13 @@ NPY_NO_EXPORT PyArrayMethod_StridedLoop *
 #    define _CONVERT_FN(x) ((_TYPE2)npy_half_to_float(x))
 #  endif
 
-#elif @is_half2@
+#elif @is_emu_half2@
 
 #  if @is_float1@
 #    define _CONVERT_FN(x) npy_floatbits_to_halfbits(x)
 #  elif @is_double1@
 #    define _CONVERT_FN(x) npy_doublebits_to_halfbits(x)
-#  elif @is_half1@
+#  elif @is_emu_half1@
 #    define _CONVERT_FN(x) (x)
 #  elif @is_bool1@
 #    define _CONVERT_FN(x) npy_float_to_half((float)(x!=0))
@@ -839,7 +851,29 @@ NPY_NO_EXPORT PyArrayMethod_StridedLoop *
 
 #endif
 
-static NPY_GCC_OPT_3 int
+// Enable auto-vectorization for floating point casts with clang
+#if @is_native_half1@ || @is_float1@ || @is_double1@
+    #if @is_native_half2@ || @is_float2@ || @is_double2@
+        #if defined(__clang__) && !defined(__EMSCRIPTEN__)
+            #if __clang_major__ >= 12
+                _Pragma("clang fp exceptions(ignore)")
+            #endif
+        #endif
+    #endif
+#endif
+
+// Work around GCC bug for double->half casts. For SVE and
+// OPT_LEVEL > 1, it implements this as double->single->half
+// which is incorrect as it introduces double rounding with
+// narrowing casts.
+#if (@is_double1@ && @is_native_half2@) && \
+    defined(NPY_HAVE_SVE) && defined(__GNUC__)
+    #define GCC_CAST_OPT_LEVEL __attribute__((optimize("O1")))
+#else
+    #define GCC_CAST_OPT_LEVEL NPY_GCC_OPT_3
+#endif
+
+static GCC_CAST_OPT_LEVEL int
 @prefix@_cast_@name1@_to_@name2@(
         PyArrayMethod_Context *context, char *const *args,
         const npy_intp *dimensions, const npy_intp *strides,
@@ -933,6 +967,17 @@ static NPY_GCC_OPT_3 int
     return 0;
 }
 
+#if @is_native_half1@ || @is_float1@ || @is_double1@
+    #if @is_native_half2@ || @is_float2@ || @is_double2@
+        #if defined(__clang__) && !defined(__EMSCRIPTEN__)
+            #if __clang_major__ >= 12
+                _Pragma("clang fp exceptions(strict)")
+            #endif
+        #endif
+    #endif
+#endif
+
+#undef GCC_CAST_OPT_LEVEL
 #undef _CONVERT_FN
 #undef _TYPE2
 #undef _TYPE1

From 9938ab5f10e3298e989aec63051983db0e48904b Mon Sep 17 00:00:00 2001
From: Joren Hammudoglu 
Date: Tue, 29 Apr 2025 19:07:30 +0200
Subject: [PATCH 125/202] TYP: Apply suggestions from code review

Co-authored-by: Nathan Goldbaum 
---
 numpy/dtypes.pyi | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/numpy/dtypes.pyi b/numpy/dtypes.pyi
index 98829745e067..07f889406353 100644
--- a/numpy/dtypes.pyi
+++ b/numpy/dtypes.pyi
@@ -575,7 +575,7 @@ class StringDType(  # type: ignore[misc]
     _NativeOrder,
     _NBit[L[8], L[16]],
     # TODO(jorenham): change once we have a string scalar type:
-    # https://github.com/numpy/numpy/pull/28196
+    # https://github.com/numpy/numpy/issues/28165
     np.dtype[str],  # type: ignore[type-var]  # pyright: ignore[reportGeneralTypeIssues, reportInvalidTypeArguments]
     Generic[_NaObjectT_co],
 ):

From c4dc63e487547a910eb61928412c44cc0ee70a62 Mon Sep 17 00:00:00 2001
From: Dimitri Papadopoulos Orfanos
 <3234522+DimitriPapadopoulos@users.noreply.github.com>
Date: Tue, 29 Apr 2025 21:04:37 +0200
Subject: [PATCH 126/202] DOC: keep URL short by using sf.net

Co-authored-by: Joren Hammudoglu 
---
 doc/source/user/numpy-for-matlab-users.rst | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/doc/source/user/numpy-for-matlab-users.rst b/doc/source/user/numpy-for-matlab-users.rst
index 370a1f7ab435..0dfe49e386b9 100644
--- a/doc/source/user/numpy-for-matlab-users.rst
+++ b/doc/source/user/numpy-for-matlab-users.rst
@@ -810,7 +810,7 @@ Links
 =====
 
 Another somewhat outdated MATLAB/NumPy cross-reference can be found at
-https://mathesaurus.sourceforge.net/
+https://mathesaurus.sf.net/ 
 
 An extensive list of tools for scientific work with Python can be
 found in the `topical software page `__.

From abe7a2f25856b1292ea55ae1e7620d93dc80c38f Mon Sep 17 00:00:00 2001
From: Dimitri Papadopoulos
 <3234522+DimitriPapadopoulos@users.noreply.github.com>
Date: Tue, 29 Apr 2025 22:12:48 +0200
Subject: [PATCH 127/202] DOC: Revert changes to `numpy/distutils`

---
 doc/source/user/numpy-for-matlab-users.rst |  2 +-
 numpy/distutils/system_info.py             | 14 +++++++-------
 2 files changed, 8 insertions(+), 8 deletions(-)

diff --git a/doc/source/user/numpy-for-matlab-users.rst b/doc/source/user/numpy-for-matlab-users.rst
index 0dfe49e386b9..8c7914ea8dec 100644
--- a/doc/source/user/numpy-for-matlab-users.rst
+++ b/doc/source/user/numpy-for-matlab-users.rst
@@ -810,7 +810,7 @@ Links
 =====
 
 Another somewhat outdated MATLAB/NumPy cross-reference can be found at
-https://mathesaurus.sf.net/ 
+https://mathesaurus.sf.net/
 
 An extensive list of tools for scientific work with Python can be
 found in the `topical software page `__.
diff --git a/numpy/distutils/system_info.py b/numpy/distutils/system_info.py
index 4702742e4589..e428b47f08d4 100644
--- a/numpy/distutils/system_info.py
+++ b/numpy/distutils/system_info.py
@@ -604,7 +604,7 @@ class AliasedOptionError(DistutilsError):
 
 class AtlasNotFoundError(NotFoundError):
     """
-    Atlas (https://github.com/math-atlas/math-atlas) libraries not found.
+    Atlas (http://github.com/math-atlas/math-atlas) libraries not found.
     Directories to search for the libraries can be specified in the
     numpy/distutils/site.cfg file (section [atlas]) or by setting
     the ATLAS environment variable."""
@@ -612,14 +612,14 @@ class AtlasNotFoundError(NotFoundError):
 
 class FlameNotFoundError(NotFoundError):
     """
-    FLAME (https://shpc.oden.utexas.edu/libFLAME.html) libraries not found.
+    FLAME (http://www.cs.utexas.edu/~flame/web/) libraries not found.
     Directories to search for the libraries can be specified in the
     numpy/distutils/site.cfg file (section [flame])."""
 
 
 class LapackNotFoundError(NotFoundError):
     """
-    Lapack (https://www.netlib.org/lapack/) libraries not found.
+    Lapack (http://www.netlib.org/lapack/) libraries not found.
     Directories to search for the libraries can be specified in the
     numpy/distutils/site.cfg file (section [lapack]) or by setting
     the LAPACK environment variable."""
@@ -627,7 +627,7 @@ class LapackNotFoundError(NotFoundError):
 
 class LapackSrcNotFoundError(LapackNotFoundError):
     """
-    Lapack (https://www.netlib.org/lapack/) sources not found.
+    Lapack (http://www.netlib.org/lapack/) sources not found.
     Directories to search for the sources can be specified in the
     numpy/distutils/site.cfg file (section [lapack_src]) or by setting
     the LAPACK_SRC environment variable."""
@@ -649,7 +649,7 @@ class BlasOptNotFoundError(NotFoundError):
 
 class BlasNotFoundError(NotFoundError):
     """
-    Blas (https://www.netlib.org/blas/) libraries not found.
+    Blas (http://www.netlib.org/blas/) libraries not found.
     Directories to search for the libraries can be specified in the
     numpy/distutils/site.cfg file (section [blas]) or by setting
     the BLAS environment variable."""
@@ -663,7 +663,7 @@ class BlasILP64NotFoundError(NotFoundError):
 
 class BlasSrcNotFoundError(BlasNotFoundError):
     """
-    Blas (https://www.netlib.org/blas/) sources not found.
+    Blas (http://www.netlib.org/blas/) sources not found.
     Directories to search for the sources can be specified in the
     numpy/distutils/site.cfg file (section [blas_src]) or by setting
     the BLAS_SRC environment variable."""
@@ -671,7 +671,7 @@ class BlasSrcNotFoundError(BlasNotFoundError):
 
 class FFTWNotFoundError(NotFoundError):
     """
-    FFTW (https://www.fftw.org/) libraries not found.
+    FFTW (http://www.fftw.org/) libraries not found.
     Directories to search for the libraries can be specified in the
     numpy/distutils/site.cfg file (section [fftw]) or by setting
     the FFTW environment variable."""

From 20a4635d22de266906dff2b617f5df678e436fe7 Mon Sep 17 00:00:00 2001
From: Marco Edward Gorelli 
Date: Tue, 29 Apr 2025 21:52:57 +0100
Subject: [PATCH 128/202] TYP: Use _Array1D alias in ``numpy.ma.core.pyi``
 (#28847)

---
 numpy/ma/core.pyi | 7 ++++---
 1 file changed, 4 insertions(+), 3 deletions(-)

diff --git a/numpy/ma/core.pyi b/numpy/ma/core.pyi
index 71652e047905..1a94e04ff3d4 100644
--- a/numpy/ma/core.pyi
+++ b/numpy/ma/core.pyi
@@ -226,9 +226,10 @@ _DTypeT = TypeVar("_DTypeT", bound=dtype)
 _DTypeT_co = TypeVar("_DTypeT_co", bound=dtype, covariant=True)
 _ArrayT = TypeVar("_ArrayT", bound=ndarray[Any, Any])
 _ScalarT = TypeVar("_ScalarT", bound=generic)
-_ScalarT_co = TypeVar("_ScalarT_co", bound=generic)
+_ScalarT_co = TypeVar("_ScalarT_co", bound=generic, covariant=True)
 # A subset of `MaskedArray` that can be parametrized w.r.t. `np.generic`
 _MaskedArray: TypeAlias = MaskedArray[_Shape, dtype[_ScalarT]]
+_Array1D: TypeAlias = np.ndarray[tuple[int], np.dtype[_ScalarT]]
 
 MaskType = bool_
 nomask: bool_[Literal[False]]
@@ -1166,9 +1167,9 @@ def sort(
     stable: Literal[False] | None = False,
 ) -> NDArray[Any]: ...
 @overload
-def compressed(x: _ArrayLike[_ScalarT_co]) -> ndarray[tuple[int], dtype[_ScalarT_co]]: ...
+def compressed(x: _ArrayLike[_ScalarT_co]) -> _Array1D[_ScalarT_co]: ...
 @overload
-def compressed(x: ArrayLike) -> ndarray[tuple[int], dtype]: ...
+def compressed(x: ArrayLike) -> _Array1D[Any]: ...
 def concatenate(arrays, axis=...): ...
 def diag(v, k=...): ...
 def left_shift(a, n): ...

From 01fc7407f6fd99de3cb807f95bedced25117b6cb Mon Sep 17 00:00:00 2001
From: Marco Edward Gorelli 
Date: Tue, 29 Apr 2025 21:57:59 +0100
Subject: [PATCH 129/202] TYP: Type ``MaskedArray.ravel`` (#28848)

---
 numpy/ma/core.pyi                     | 2 +-
 numpy/typing/tests/data/reveal/ma.pyi | 3 +++
 2 files changed, 4 insertions(+), 1 deletion(-)

diff --git a/numpy/ma/core.pyi b/numpy/ma/core.pyi
index 1a94e04ff3d4..35fd6f223de1 100644
--- a/numpy/ma/core.pyi
+++ b/numpy/ma/core.pyi
@@ -484,7 +484,7 @@ class MaskedArray(ndarray[_ShapeT_co, _DTypeT_co]):
     @overload
     def count(self, axis: _ShapeLike | None, keepdims: Literal[True]) -> NDArray[int_]: ...
 
-    def ravel(self, order=...): ...
+    def ravel(self, order: _OrderKACF = "C") -> MaskedArray[tuple[int], _DTypeT_co]: ...
     def reshape(self, *s, **kwargs): ...
     def resize(self, newshape, refcheck=..., order=...): ...
     def put(self, indices: _ArrayLikeInt_co, values: ArrayLike, mode: _ModeKind = "raise") -> None: ...
diff --git a/numpy/typing/tests/data/reveal/ma.pyi b/numpy/typing/tests/data/reveal/ma.pyi
index 5c1b04a03718..f7c99357cb41 100644
--- a/numpy/typing/tests/data/reveal/ma.pyi
+++ b/numpy/typing/tests/data/reveal/ma.pyi
@@ -283,6 +283,9 @@ assert_type(np.ma.allclose(AR_f4, MAR_f4), bool)
 assert_type(np.ma.allclose(AR_f4, MAR_f4, masked_equal=False), bool)
 assert_type(np.ma.allclose(AR_f4, MAR_f4, rtol=.4, atol=.3), bool)
 
+assert_type(MAR_2d_f4.ravel(), np.ma.MaskedArray[tuple[int], np.dtype[np.float32]])
+assert_type(MAR_1d.ravel(order='A'), np.ma.MaskedArray[tuple[int], np.dtype[Any]])
+
 assert_type(np.ma.getmask(MAR_f4), NDArray[np.bool] | np.bool)
 # PyRight detects this one correctly, but mypy doesn't:
 # `Revealed type is "Union[numpy.ndarray[Any, Any], numpy.bool[Any]]"`

From 9af251c7f92ff87aef65f070b5735db7617620b2 Mon Sep 17 00:00:00 2001
From: Marco Edward Gorelli 
Date: Tue, 29 Apr 2025 22:27:45 +0100
Subject: [PATCH 130/202] TYP: Type ``MaskedArray.repeat``, improve overloads
 for ``NDArray.repeat``, ``generic.repeat``, and ``np.repeat`` (#28849)

---
 numpy/__init__.pyi                              | 11 +++++++++--
 numpy/_core/fromnumeric.pyi                     | 16 ++++++++++++++--
 numpy/ma/core.pyi                               | 15 ++++++++++++++-
 numpy/typing/tests/data/reveal/fromnumeric.pyi  | 12 +++++++-----
 numpy/typing/tests/data/reveal/ma.pyi           |  5 +++++
 numpy/typing/tests/data/reveal/ndarray_misc.pyi |  9 ++++++---
 6 files changed, 55 insertions(+), 13 deletions(-)

diff --git a/numpy/__init__.pyi b/numpy/__init__.pyi
index 5c16b91b7772..d39bb02279fb 100644
--- a/numpy/__init__.pyi
+++ b/numpy/__init__.pyi
@@ -2421,10 +2421,17 @@ class ndarray(_ArrayOrScalarCommon, Generic[_ShapeT_co, _DTypeT_co]):
         mode: _ModeKind = ...,
     ) -> _ArrayT: ...
 
+    @overload
     def repeat(
         self,
         repeats: _ArrayLikeInt_co,
-        axis: SupportsIndex | None = ...,
+        axis: None = None,
+    ) -> ndarray[tuple[int], _DTypeT_co]: ...
+    @overload
+    def repeat(
+        self,
+        repeats: _ArrayLikeInt_co,
+        axis: SupportsIndex,
     ) -> ndarray[_Shape, _DTypeT_co]: ...
 
     def flatten(self, /, order: _OrderKACF = "C") -> ndarray[tuple[int], _DTypeT_co]: ...
@@ -3685,7 +3692,7 @@ class generic(_ArrayOrScalarCommon, Generic[_ItemT_co]):
         mode: _ModeKind = ...,
     ) -> _ArrayT: ...
 
-    def repeat(self, repeats: _ArrayLikeInt_co, axis: SupportsIndex | None = ...) -> NDArray[Self]: ...
+    def repeat(self, repeats: _ArrayLikeInt_co, axis: SupportsIndex | None = None) -> ndarray[tuple[int], dtype[Self]]: ...
     def flatten(self, /, order: _OrderKACF = "C") -> ndarray[tuple[int], dtype[Self]]: ...
     def ravel(self, /, order: _OrderKACF = "C") -> ndarray[tuple[int], dtype[Self]]: ...
 
diff --git a/numpy/_core/fromnumeric.pyi b/numpy/_core/fromnumeric.pyi
index 9e30a84165b4..f974dc33a027 100644
--- a/numpy/_core/fromnumeric.pyi
+++ b/numpy/_core/fromnumeric.pyi
@@ -277,13 +277,25 @@ def choose(
 def repeat(
     a: _ArrayLike[_ScalarT],
     repeats: _ArrayLikeInt_co,
-    axis: SupportsIndex | None = ...,
+    axis: None = None,
+) -> np.ndarray[tuple[int], np.dtype[_ScalarT]]: ...
+@overload
+def repeat(
+    a: _ArrayLike[_ScalarT],
+    repeats: _ArrayLikeInt_co,
+    axis: SupportsIndex,
 ) -> NDArray[_ScalarT]: ...
 @overload
 def repeat(
     a: ArrayLike,
     repeats: _ArrayLikeInt_co,
-    axis: SupportsIndex | None = ...,
+    axis: None = None,
+) -> np.ndarray[tuple[int], np.dtype[Any]]: ...
+@overload
+def repeat(
+    a: ArrayLike,
+    repeats: _ArrayLikeInt_co,
+    axis: SupportsIndex,
 ) -> NDArray[Any]: ...
 
 def put(
diff --git a/numpy/ma/core.pyi b/numpy/ma/core.pyi
index 35fd6f223de1..9e755e5901da 100644
--- a/numpy/ma/core.pyi
+++ b/numpy/ma/core.pyi
@@ -778,7 +778,20 @@ class MaskedArray(ndarray[_ShapeT_co, _DTypeT_co]):
     copy: Any
     diagonal: Any
     flatten: Any
-    repeat: Any
+
+    @overload
+    def repeat(
+        self,
+        repeats: _ArrayLikeInt_co,
+        axis: None = None,
+    ) -> MaskedArray[tuple[int], _DTypeT_co]: ...
+    @overload
+    def repeat(
+        self,
+        repeats: _ArrayLikeInt_co,
+        axis: SupportsIndex,
+    ) -> MaskedArray[_Shape, _DTypeT_co]: ...
+
     squeeze: Any
     swapaxes: Any
     T: Any
diff --git a/numpy/typing/tests/data/reveal/fromnumeric.pyi b/numpy/typing/tests/data/reveal/fromnumeric.pyi
index ee761a2762b7..0827b27a056b 100644
--- a/numpy/typing/tests/data/reveal/fromnumeric.pyi
+++ b/numpy/typing/tests/data/reveal/fromnumeric.pyi
@@ -46,11 +46,13 @@ assert_type(np.choose([1], [True, True]), npt.NDArray[Any])
 assert_type(np.choose([1], AR_b), npt.NDArray[np.bool])
 assert_type(np.choose([1], AR_b, out=AR_f4), npt.NDArray[np.float32])
 
-assert_type(np.repeat(b, 1), npt.NDArray[np.bool])
-assert_type(np.repeat(f4, 1), npt.NDArray[np.float32])
-assert_type(np.repeat(f, 1), npt.NDArray[Any])
-assert_type(np.repeat(AR_b, 1), npt.NDArray[np.bool])
-assert_type(np.repeat(AR_f4, 1), npt.NDArray[np.float32])
+assert_type(np.repeat(b, 1), np.ndarray[tuple[int], np.dtype[np.bool]])
+assert_type(np.repeat(b, 1, axis=0), npt.NDArray[np.bool])
+assert_type(np.repeat(f4, 1), np.ndarray[tuple[int], np.dtype[np.float32]])
+assert_type(np.repeat(f, 1), np.ndarray[tuple[int], np.dtype[Any]])
+assert_type(np.repeat(AR_b, 1), np.ndarray[tuple[int], np.dtype[np.bool]])
+assert_type(np.repeat(AR_f4, 1), np.ndarray[tuple[int], np.dtype[np.float32]])
+assert_type(np.repeat(AR_f4, 1, axis=0), npt.NDArray[np.float32])
 
 # TODO: array_bdd tests for np.put()
 
diff --git a/numpy/typing/tests/data/reveal/ma.pyi b/numpy/typing/tests/data/reveal/ma.pyi
index f7c99357cb41..eb5b4508d954 100644
--- a/numpy/typing/tests/data/reveal/ma.pyi
+++ b/numpy/typing/tests/data/reveal/ma.pyi
@@ -276,6 +276,11 @@ assert_type(np.ma.filled([[1,2,3]]), NDArray[Any])
 # https://github.com/numpy/numpy/pull/28742#discussion_r2048968375
 assert_type(np.ma.filled(MAR_1d), np.ndarray[tuple[int], np.dtype])  # type: ignore[assert-type]
 
+assert_type(MAR_b.repeat(3), np.ma.MaskedArray[tuple[int], np.dtype[np.bool]])
+assert_type(MAR_2d_f4.repeat(MAR_i8), np.ma.MaskedArray[tuple[int], np.dtype[np.float32]])
+assert_type(MAR_2d_f4.repeat(MAR_i8, axis=None), np.ma.MaskedArray[tuple[int], np.dtype[np.float32]])
+assert_type(MAR_2d_f4.repeat(MAR_i8, axis=0), MaskedNDArray[np.float32])
+
 assert_type(np.ma.allequal(AR_f4, MAR_f4), bool)
 assert_type(np.ma.allequal(AR_f4, MAR_f4, fill_value=False), bool)
 
diff --git a/numpy/typing/tests/data/reveal/ndarray_misc.pyi b/numpy/typing/tests/data/reveal/ndarray_misc.pyi
index 2016fb5c7971..682f9db50220 100644
--- a/numpy/typing/tests/data/reveal/ndarray_misc.pyi
+++ b/numpy/typing/tests/data/reveal/ndarray_misc.pyi
@@ -126,9 +126,12 @@ assert_type(f8.round(), np.float64)
 assert_type(AR_f8.round(), npt.NDArray[np.float64])
 assert_type(AR_f8.round(out=B), SubClass)
 
-assert_type(f8.repeat(1), npt.NDArray[np.float64])
-assert_type(AR_f8.repeat(1), npt.NDArray[np.float64])
-assert_type(B.repeat(1), npt.NDArray[np.object_])
+assert_type(f8.repeat(1), np.ndarray[tuple[int], np.dtype[np.float64]])
+assert_type(f8.repeat(1, axis=0), np.ndarray[tuple[int], np.dtype[np.float64]])
+assert_type(AR_f8.repeat(1), np.ndarray[tuple[int], np.dtype[np.float64]])
+assert_type(AR_f8.repeat(1, axis=0), npt.NDArray[np.float64])
+assert_type(B.repeat(1), np.ndarray[tuple[int], np.dtype[np.object_]])
+assert_type(B.repeat(1, axis=0), npt.NDArray[np.object_])
 
 assert_type(f8.std(), Any)
 assert_type(AR_f8.std(), Any)

From 470c458aacda6ecd5207c7442cbe720833194c60 Mon Sep 17 00:00:00 2001
From: Marco Edward Gorelli 
Date: Wed, 30 Apr 2025 01:09:08 +0100
Subject: [PATCH 131/202] TYP: Improve consistency of (masked) array typing
 aliases (#28863)

---
 numpy/_typing/_add_docstring.py       |   2 +-
 numpy/_typing/_array_like.py          |   2 +-
 numpy/typing/tests/data/reveal/ma.pyi | 206 +++++++++++++-------------
 3 files changed, 105 insertions(+), 105 deletions(-)

diff --git a/numpy/_typing/_add_docstring.py b/numpy/_typing/_add_docstring.py
index 493e775ebae2..da415f1b94c6 100644
--- a/numpy/_typing/_add_docstring.py
+++ b/numpy/_typing/_add_docstring.py
@@ -137,7 +137,7 @@ def _parse_docstrings() -> str:
         >>> import numpy.typing as npt
 
         >>> print(npt.NDArray)
-        numpy.ndarray[tuple[int, ...], numpy.dtype[+_ScalarT_co]]
+        numpy.ndarray[tuple[int, ...], numpy.dtype[~_ScalarT]]
 
         >>> print(npt.NDArray[np.float64])
         numpy.ndarray[tuple[int, ...], numpy.dtype[numpy.float64]]
diff --git a/numpy/_typing/_array_like.py b/numpy/_typing/_array_like.py
index 56388db1155e..b4c291639d6a 100644
--- a/numpy/_typing/_array_like.py
+++ b/numpy/_typing/_array_like.py
@@ -23,7 +23,7 @@
 _DTypeT = TypeVar("_DTypeT", bound=dtype[Any])
 _DTypeT_co = TypeVar("_DTypeT_co", covariant=True, bound=dtype[Any])
 
-NDArray: TypeAlias = np.ndarray[_Shape, dtype[_ScalarT_co]]
+NDArray: TypeAlias = np.ndarray[_Shape, dtype[_ScalarT]]
 
 # The `_SupportsArray` protocol only cares about the default dtype
 # (i.e. `dtype=None` or no `dtype` parameter at all) of the to-be returned
diff --git a/numpy/typing/tests/data/reveal/ma.pyi b/numpy/typing/tests/data/reveal/ma.pyi
index eb5b4508d954..5274deed90a1 100644
--- a/numpy/typing/tests/data/reveal/ma.pyi
+++ b/numpy/typing/tests/data/reveal/ma.pyi
@@ -5,10 +5,10 @@ import numpy as np
 from numpy import dtype, generic
 from numpy._typing import NDArray, _Shape
 
-_ScalarT_co = TypeVar("_ScalarT_co", bound=generic, covariant=True)
-MaskedNDArray: TypeAlias = np.ma.MaskedArray[_Shape, dtype[_ScalarT_co]]
+_ScalarT = TypeVar("_ScalarT", bound=generic)
+MaskedArray: TypeAlias = np.ma.MaskedArray[_Shape, dtype[_ScalarT]]
 
-class MaskedNDArraySubclass(MaskedNDArray[np.complex128]): ...
+class MaskedArraySubclass(MaskedArray[np.complex128]): ...
 
 AR_b: NDArray[np.bool]
 AR_f4: NDArray[np.float32]
@@ -16,18 +16,18 @@ AR_dt64: NDArray[np.datetime64]
 AR_td64: NDArray[np.timedelta64]
 AR_o: NDArray[np.timedelta64]
 
-MAR_b: MaskedNDArray[np.bool]
-MAR_f4: MaskedNDArray[np.float32]
-MAR_f8: MaskedNDArray[np.float64]
-MAR_i8: MaskedNDArray[np.int64]
-MAR_dt64: MaskedNDArray[np.datetime64]
-MAR_td64: MaskedNDArray[np.timedelta64]
-MAR_o: MaskedNDArray[np.object_]
-MAR_s: MaskedNDArray[np.str_]
-MAR_byte: MaskedNDArray[np.bytes_]
-MAR_V: MaskedNDArray[np.void]
+MAR_b: MaskedArray[np.bool]
+MAR_f4: MaskedArray[np.float32]
+MAR_f8: MaskedArray[np.float64]
+MAR_i8: MaskedArray[np.int64]
+MAR_dt64: MaskedArray[np.datetime64]
+MAR_td64: MaskedArray[np.timedelta64]
+MAR_o: MaskedArray[np.object_]
+MAR_s: MaskedArray[np.str_]
+MAR_byte: MaskedArray[np.bytes_]
+MAR_V: MaskedArray[np.void]
 
-MAR_subclass: MaskedNDArraySubclass
+MAR_subclass: MaskedArraySubclass
 
 MAR_1d: np.ma.MaskedArray[tuple[int], np.dtype]
 MAR_2d_f4: np.ma.MaskedArray[tuple[int, int], np.dtype[np.float32]]
@@ -49,9 +49,9 @@ assert_type(np.ma.min(MAR_b, axis=0), Any)
 assert_type(np.ma.min(MAR_f4, axis=0), Any)
 assert_type(np.ma.min(MAR_b, keepdims=True), Any)
 assert_type(np.ma.min(MAR_f4, keepdims=True), Any)
-assert_type(np.ma.min(MAR_f4, out=MAR_subclass), MaskedNDArraySubclass)
-assert_type(np.ma.min(MAR_f4, 0, MAR_subclass), MaskedNDArraySubclass)
-assert_type(np.ma.min(MAR_f4, None, MAR_subclass), MaskedNDArraySubclass)
+assert_type(np.ma.min(MAR_f4, out=MAR_subclass), MaskedArraySubclass)
+assert_type(np.ma.min(MAR_f4, 0, MAR_subclass), MaskedArraySubclass)
+assert_type(np.ma.min(MAR_f4, None, MAR_subclass), MaskedArraySubclass)
 
 assert_type(MAR_b.min(), np.bool)
 assert_type(MAR_f4.min(), np.float32)
@@ -59,9 +59,9 @@ assert_type(MAR_b.min(axis=0), Any)
 assert_type(MAR_f4.min(axis=0), Any)
 assert_type(MAR_b.min(keepdims=True), Any)
 assert_type(MAR_f4.min(keepdims=True), Any)
-assert_type(MAR_f4.min(out=MAR_subclass), MaskedNDArraySubclass)
-assert_type(MAR_f4.min(0, MAR_subclass), MaskedNDArraySubclass)
-assert_type(MAR_f4.min(None, MAR_subclass), MaskedNDArraySubclass)
+assert_type(MAR_f4.min(out=MAR_subclass), MaskedArraySubclass)
+assert_type(MAR_f4.min(0, MAR_subclass), MaskedArraySubclass)
+assert_type(MAR_f4.min(None, MAR_subclass), MaskedArraySubclass)
 
 assert_type(np.ma.max(MAR_b), np.bool)
 assert_type(np.ma.max(MAR_f4), np.float32)
@@ -69,9 +69,9 @@ assert_type(np.ma.max(MAR_b, axis=0), Any)
 assert_type(np.ma.max(MAR_f4, axis=0), Any)
 assert_type(np.ma.max(MAR_b, keepdims=True), Any)
 assert_type(np.ma.max(MAR_f4, keepdims=True), Any)
-assert_type(np.ma.max(MAR_f4, out=MAR_subclass), MaskedNDArraySubclass)
-assert_type(np.ma.max(MAR_f4, 0, MAR_subclass), MaskedNDArraySubclass)
-assert_type(np.ma.max(MAR_f4, None, MAR_subclass), MaskedNDArraySubclass)
+assert_type(np.ma.max(MAR_f4, out=MAR_subclass), MaskedArraySubclass)
+assert_type(np.ma.max(MAR_f4, 0, MAR_subclass), MaskedArraySubclass)
+assert_type(np.ma.max(MAR_f4, None, MAR_subclass), MaskedArraySubclass)
 
 assert_type(MAR_b.max(), np.bool)
 assert_type(MAR_f4.max(), np.float32)
@@ -79,9 +79,9 @@ assert_type(MAR_b.max(axis=0), Any)
 assert_type(MAR_f4.max(axis=0), Any)
 assert_type(MAR_b.max(keepdims=True), Any)
 assert_type(MAR_f4.max(keepdims=True), Any)
-assert_type(MAR_f4.max(out=MAR_subclass), MaskedNDArraySubclass)
-assert_type(MAR_f4.max(0, MAR_subclass), MaskedNDArraySubclass)
-assert_type(MAR_f4.max(None, MAR_subclass), MaskedNDArraySubclass)
+assert_type(MAR_f4.max(out=MAR_subclass), MaskedArraySubclass)
+assert_type(MAR_f4.max(0, MAR_subclass), MaskedArraySubclass)
+assert_type(MAR_f4.max(None, MAR_subclass), MaskedArraySubclass)
 
 assert_type(np.ma.ptp(MAR_b), np.bool)
 assert_type(np.ma.ptp(MAR_f4), np.float32)
@@ -89,9 +89,9 @@ assert_type(np.ma.ptp(MAR_b, axis=0), Any)
 assert_type(np.ma.ptp(MAR_f4, axis=0), Any)
 assert_type(np.ma.ptp(MAR_b, keepdims=True), Any)
 assert_type(np.ma.ptp(MAR_f4, keepdims=True), Any)
-assert_type(np.ma.ptp(MAR_f4, out=MAR_subclass), MaskedNDArraySubclass)
-assert_type(np.ma.ptp(MAR_f4, 0, MAR_subclass), MaskedNDArraySubclass)
-assert_type(np.ma.ptp(MAR_f4, None, MAR_subclass), MaskedNDArraySubclass)
+assert_type(np.ma.ptp(MAR_f4, out=MAR_subclass), MaskedArraySubclass)
+assert_type(np.ma.ptp(MAR_f4, 0, MAR_subclass), MaskedArraySubclass)
+assert_type(np.ma.ptp(MAR_f4, None, MAR_subclass), MaskedArraySubclass)
 
 assert_type(MAR_b.ptp(), np.bool)
 assert_type(MAR_f4.ptp(), np.float32)
@@ -99,9 +99,9 @@ assert_type(MAR_b.ptp(axis=0), Any)
 assert_type(MAR_f4.ptp(axis=0), Any)
 assert_type(MAR_b.ptp(keepdims=True), Any)
 assert_type(MAR_f4.ptp(keepdims=True), Any)
-assert_type(MAR_f4.ptp(out=MAR_subclass), MaskedNDArraySubclass)
-assert_type(MAR_f4.ptp(0, MAR_subclass), MaskedNDArraySubclass)
-assert_type(MAR_f4.ptp(None, MAR_subclass), MaskedNDArraySubclass)
+assert_type(MAR_f4.ptp(out=MAR_subclass), MaskedArraySubclass)
+assert_type(MAR_f4.ptp(0, MAR_subclass), MaskedArraySubclass)
+assert_type(MAR_f4.ptp(None, MAR_subclass), MaskedArraySubclass)
 
 assert_type(MAR_b.argmin(), np.intp)
 assert_type(MAR_f4.argmin(), np.intp)
@@ -109,8 +109,8 @@ assert_type(MAR_f4.argmax(fill_value=6.28318, keepdims=False), np.intp)
 assert_type(MAR_b.argmin(axis=0), Any)
 assert_type(MAR_f4.argmin(axis=0), Any)
 assert_type(MAR_b.argmin(keepdims=True), Any)
-assert_type(MAR_f4.argmin(out=MAR_subclass), MaskedNDArraySubclass)
-assert_type(MAR_f4.argmin(None, None, out=MAR_subclass), MaskedNDArraySubclass)
+assert_type(MAR_f4.argmin(out=MAR_subclass), MaskedArraySubclass)
+assert_type(MAR_f4.argmin(None, None, out=MAR_subclass), MaskedArraySubclass)
 
 assert_type(np.ma.argmin(MAR_b), np.intp)
 assert_type(np.ma.argmin(MAR_f4), np.intp)
@@ -118,8 +118,8 @@ assert_type(np.ma.argmin(MAR_f4, fill_value=6.28318, keepdims=False), np.intp)
 assert_type(np.ma.argmin(MAR_b, axis=0), Any)
 assert_type(np.ma.argmin(MAR_f4, axis=0), Any)
 assert_type(np.ma.argmin(MAR_b, keepdims=True), Any)
-assert_type(np.ma.argmin(MAR_f4, out=MAR_subclass), MaskedNDArraySubclass)
-assert_type(np.ma.argmin(MAR_f4, None, None, out=MAR_subclass), MaskedNDArraySubclass)
+assert_type(np.ma.argmin(MAR_f4, out=MAR_subclass), MaskedArraySubclass)
+assert_type(np.ma.argmin(MAR_f4, None, None, out=MAR_subclass), MaskedArraySubclass)
 
 assert_type(MAR_b.argmax(), np.intp)
 assert_type(MAR_f4.argmax(), np.intp)
@@ -127,8 +127,8 @@ assert_type(MAR_f4.argmax(fill_value=6.28318, keepdims=False), np.intp)
 assert_type(MAR_b.argmax(axis=0), Any)
 assert_type(MAR_f4.argmax(axis=0), Any)
 assert_type(MAR_b.argmax(keepdims=True), Any)
-assert_type(MAR_f4.argmax(out=MAR_subclass), MaskedNDArraySubclass)
-assert_type(MAR_f4.argmax(None, None, out=MAR_subclass), MaskedNDArraySubclass)
+assert_type(MAR_f4.argmax(out=MAR_subclass), MaskedArraySubclass)
+assert_type(MAR_f4.argmax(None, None, out=MAR_subclass), MaskedArraySubclass)
 
 assert_type(np.ma.argmax(MAR_b), np.intp)
 assert_type(np.ma.argmax(MAR_f4), np.intp)
@@ -136,40 +136,40 @@ assert_type(np.ma.argmax(MAR_f4, fill_value=6.28318, keepdims=False), np.intp)
 assert_type(np.ma.argmax(MAR_b, axis=0), Any)
 assert_type(np.ma.argmax(MAR_f4, axis=0), Any)
 assert_type(np.ma.argmax(MAR_b, keepdims=True), Any)
-assert_type(np.ma.argmax(MAR_f4, out=MAR_subclass), MaskedNDArraySubclass)
-assert_type(np.ma.argmax(MAR_f4, None, None, out=MAR_subclass), MaskedNDArraySubclass)
+assert_type(np.ma.argmax(MAR_f4, out=MAR_subclass), MaskedArraySubclass)
+assert_type(np.ma.argmax(MAR_f4, None, None, out=MAR_subclass), MaskedArraySubclass)
 
 assert_type(MAR_f4.sort(), None)
 assert_type(MAR_f4.sort(axis=0, kind='quicksort', order='K', endwith=False, fill_value=42., stable=False), None)
 
-assert_type(np.ma.sort(MAR_f4), MaskedNDArray[np.float32])
-assert_type(np.ma.sort(MAR_subclass), MaskedNDArraySubclass)
+assert_type(np.ma.sort(MAR_f4), MaskedArray[np.float32])
+assert_type(np.ma.sort(MAR_subclass), MaskedArraySubclass)
 assert_type(np.ma.sort([[0, 1], [2, 3]]), NDArray[Any])
 assert_type(np.ma.sort(AR_f4), NDArray[np.float32])
 
 assert_type(MAR_f8.take(0), np.float64)
 assert_type(MAR_1d.take(0), Any)
-assert_type(MAR_f8.take([0]), MaskedNDArray[np.float64])
-assert_type(MAR_f8.take(0, out=MAR_subclass), MaskedNDArraySubclass)
-assert_type(MAR_f8.take([0], out=MAR_subclass), MaskedNDArraySubclass)
+assert_type(MAR_f8.take([0]), MaskedArray[np.float64])
+assert_type(MAR_f8.take(0, out=MAR_subclass), MaskedArraySubclass)
+assert_type(MAR_f8.take([0], out=MAR_subclass), MaskedArraySubclass)
 
 assert_type(np.ma.take(f, 0), Any)
 assert_type(np.ma.take(f4, 0), np.float32)
 assert_type(np.ma.take(MAR_f8, 0), np.float64)
 assert_type(np.ma.take(AR_f4, 0), np.float32)
 assert_type(np.ma.take(MAR_1d, 0), Any)
-assert_type(np.ma.take(MAR_f8, [0]), MaskedNDArray[np.float64])
-assert_type(np.ma.take(AR_f4, [0]), MaskedNDArray[np.float32])
-assert_type(np.ma.take(MAR_f8, 0, out=MAR_subclass), MaskedNDArraySubclass)
-assert_type(np.ma.take(MAR_f8, [0], out=MAR_subclass), MaskedNDArraySubclass)
-assert_type(np.ma.take([1], [0]), MaskedNDArray[Any])
-assert_type(np.ma.take(np.eye(2), 1, axis=0), MaskedNDArray[np.float64])
+assert_type(np.ma.take(MAR_f8, [0]), MaskedArray[np.float64])
+assert_type(np.ma.take(AR_f4, [0]), MaskedArray[np.float32])
+assert_type(np.ma.take(MAR_f8, 0, out=MAR_subclass), MaskedArraySubclass)
+assert_type(np.ma.take(MAR_f8, [0], out=MAR_subclass), MaskedArraySubclass)
+assert_type(np.ma.take([1], [0]), MaskedArray[Any])
+assert_type(np.ma.take(np.eye(2), 1, axis=0), MaskedArray[np.float64])
 
 assert_type(MAR_f4.partition(1), None)
 assert_type(MAR_V.partition(1, axis=0, kind='introselect', order='K'), None)
 
-assert_type(MAR_f4.argpartition(1), MaskedNDArray[np.intp])
-assert_type(MAR_1d.argpartition(1, axis=0, kind='introselect', order='K'), MaskedNDArray[np.intp])
+assert_type(MAR_f4.argpartition(1), MaskedArray[np.intp])
+assert_type(MAR_1d.argpartition(1, axis=0, kind='introselect', order='K'), MaskedArray[np.intp])
 
 assert_type(np.ma.ndim(f4), int)
 assert_type(np.ma.ndim(MAR_b), int)
@@ -185,55 +185,55 @@ assert_type(MAR_f4.ids(), tuple[int, int])
 
 assert_type(MAR_f4.iscontiguous(), bool)
 
-assert_type(MAR_f4 >= 3, MaskedNDArray[np.bool])
-assert_type(MAR_i8 >= AR_td64, MaskedNDArray[np.bool])
-assert_type(MAR_b >= AR_td64, MaskedNDArray[np.bool])
-assert_type(MAR_td64 >= AR_td64, MaskedNDArray[np.bool])
-assert_type(MAR_dt64 >= AR_dt64, MaskedNDArray[np.bool])
-assert_type(MAR_o >= AR_o, MaskedNDArray[np.bool])
-assert_type(MAR_1d >= 0, MaskedNDArray[np.bool])
-assert_type(MAR_s >= MAR_s, MaskedNDArray[np.bool])
-assert_type(MAR_byte >= MAR_byte, MaskedNDArray[np.bool])
-
-assert_type(MAR_f4 > 3, MaskedNDArray[np.bool])
-assert_type(MAR_i8 > AR_td64, MaskedNDArray[np.bool])
-assert_type(MAR_b > AR_td64, MaskedNDArray[np.bool])
-assert_type(MAR_td64 > AR_td64, MaskedNDArray[np.bool])
-assert_type(MAR_dt64 > AR_dt64, MaskedNDArray[np.bool])
-assert_type(MAR_o > AR_o, MaskedNDArray[np.bool])
-assert_type(MAR_1d > 0, MaskedNDArray[np.bool])
-assert_type(MAR_s > MAR_s, MaskedNDArray[np.bool])
-assert_type(MAR_byte > MAR_byte, MaskedNDArray[np.bool])
-
-assert_type(MAR_f4 <= 3, MaskedNDArray[np.bool])
-assert_type(MAR_i8 <= AR_td64, MaskedNDArray[np.bool])
-assert_type(MAR_b <= AR_td64, MaskedNDArray[np.bool])
-assert_type(MAR_td64 <= AR_td64, MaskedNDArray[np.bool])
-assert_type(MAR_dt64 <= AR_dt64, MaskedNDArray[np.bool])
-assert_type(MAR_o <= AR_o, MaskedNDArray[np.bool])
-assert_type(MAR_1d <= 0, MaskedNDArray[np.bool])
-assert_type(MAR_s <= MAR_s, MaskedNDArray[np.bool])
-assert_type(MAR_byte <= MAR_byte, MaskedNDArray[np.bool])
-
-assert_type(MAR_f4 < 3, MaskedNDArray[np.bool])
-assert_type(MAR_i8 < AR_td64, MaskedNDArray[np.bool])
-assert_type(MAR_b < AR_td64, MaskedNDArray[np.bool])
-assert_type(MAR_td64 < AR_td64, MaskedNDArray[np.bool])
-assert_type(MAR_dt64 < AR_dt64, MaskedNDArray[np.bool])
-assert_type(MAR_o < AR_o, MaskedNDArray[np.bool])
-assert_type(MAR_1d < 0, MaskedNDArray[np.bool])
-assert_type(MAR_s < MAR_s, MaskedNDArray[np.bool])
-assert_type(MAR_byte < MAR_byte, MaskedNDArray[np.bool])
-
-assert_type(MAR_f4 <= 3, MaskedNDArray[np.bool])
-assert_type(MAR_i8 <= AR_td64, MaskedNDArray[np.bool])
-assert_type(MAR_b <= AR_td64, MaskedNDArray[np.bool])
-assert_type(MAR_td64 <= AR_td64, MaskedNDArray[np.bool])
-assert_type(MAR_dt64 <= AR_dt64, MaskedNDArray[np.bool])
-assert_type(MAR_o <= AR_o, MaskedNDArray[np.bool])
-assert_type(MAR_1d <= 0, MaskedNDArray[np.bool])
-assert_type(MAR_s <= MAR_s, MaskedNDArray[np.bool])
-assert_type(MAR_byte <= MAR_byte, MaskedNDArray[np.bool])
+assert_type(MAR_f4 >= 3, MaskedArray[np.bool])
+assert_type(MAR_i8 >= AR_td64, MaskedArray[np.bool])
+assert_type(MAR_b >= AR_td64, MaskedArray[np.bool])
+assert_type(MAR_td64 >= AR_td64, MaskedArray[np.bool])
+assert_type(MAR_dt64 >= AR_dt64, MaskedArray[np.bool])
+assert_type(MAR_o >= AR_o, MaskedArray[np.bool])
+assert_type(MAR_1d >= 0, MaskedArray[np.bool])
+assert_type(MAR_s >= MAR_s, MaskedArray[np.bool])
+assert_type(MAR_byte >= MAR_byte, MaskedArray[np.bool])
+
+assert_type(MAR_f4 > 3, MaskedArray[np.bool])
+assert_type(MAR_i8 > AR_td64, MaskedArray[np.bool])
+assert_type(MAR_b > AR_td64, MaskedArray[np.bool])
+assert_type(MAR_td64 > AR_td64, MaskedArray[np.bool])
+assert_type(MAR_dt64 > AR_dt64, MaskedArray[np.bool])
+assert_type(MAR_o > AR_o, MaskedArray[np.bool])
+assert_type(MAR_1d > 0, MaskedArray[np.bool])
+assert_type(MAR_s > MAR_s, MaskedArray[np.bool])
+assert_type(MAR_byte > MAR_byte, MaskedArray[np.bool])
+
+assert_type(MAR_f4 <= 3, MaskedArray[np.bool])
+assert_type(MAR_i8 <= AR_td64, MaskedArray[np.bool])
+assert_type(MAR_b <= AR_td64, MaskedArray[np.bool])
+assert_type(MAR_td64 <= AR_td64, MaskedArray[np.bool])
+assert_type(MAR_dt64 <= AR_dt64, MaskedArray[np.bool])
+assert_type(MAR_o <= AR_o, MaskedArray[np.bool])
+assert_type(MAR_1d <= 0, MaskedArray[np.bool])
+assert_type(MAR_s <= MAR_s, MaskedArray[np.bool])
+assert_type(MAR_byte <= MAR_byte, MaskedArray[np.bool])
+
+assert_type(MAR_f4 < 3, MaskedArray[np.bool])
+assert_type(MAR_i8 < AR_td64, MaskedArray[np.bool])
+assert_type(MAR_b < AR_td64, MaskedArray[np.bool])
+assert_type(MAR_td64 < AR_td64, MaskedArray[np.bool])
+assert_type(MAR_dt64 < AR_dt64, MaskedArray[np.bool])
+assert_type(MAR_o < AR_o, MaskedArray[np.bool])
+assert_type(MAR_1d < 0, MaskedArray[np.bool])
+assert_type(MAR_s < MAR_s, MaskedArray[np.bool])
+assert_type(MAR_byte < MAR_byte, MaskedArray[np.bool])
+
+assert_type(MAR_f4 <= 3, MaskedArray[np.bool])
+assert_type(MAR_i8 <= AR_td64, MaskedArray[np.bool])
+assert_type(MAR_b <= AR_td64, MaskedArray[np.bool])
+assert_type(MAR_td64 <= AR_td64, MaskedArray[np.bool])
+assert_type(MAR_dt64 <= AR_dt64, MaskedArray[np.bool])
+assert_type(MAR_o <= AR_o, MaskedArray[np.bool])
+assert_type(MAR_1d <= 0, MaskedArray[np.bool])
+assert_type(MAR_s <= MAR_s, MaskedArray[np.bool])
+assert_type(MAR_byte <= MAR_byte, MaskedArray[np.bool])
 
 assert_type(MAR_byte.count(), int)
 assert_type(MAR_f4.count(axis=None), int)
@@ -279,7 +279,7 @@ assert_type(np.ma.filled(MAR_1d), np.ndarray[tuple[int], np.dtype])  # type: ign
 assert_type(MAR_b.repeat(3), np.ma.MaskedArray[tuple[int], np.dtype[np.bool]])
 assert_type(MAR_2d_f4.repeat(MAR_i8), np.ma.MaskedArray[tuple[int], np.dtype[np.float32]])
 assert_type(MAR_2d_f4.repeat(MAR_i8, axis=None), np.ma.MaskedArray[tuple[int], np.dtype[np.float32]])
-assert_type(MAR_2d_f4.repeat(MAR_i8, axis=0), MaskedNDArray[np.float32])
+assert_type(MAR_2d_f4.repeat(MAR_i8, axis=0), MaskedArray[np.float32])
 
 assert_type(np.ma.allequal(AR_f4, MAR_f4), bool)
 assert_type(np.ma.allequal(AR_f4, MAR_f4, fill_value=False), bool)

From 57fdd8ea19e0801a0b7301cc65721262ecec9105 Mon Sep 17 00:00:00 2001
From: Marco Edward Gorelli 
Date: Wed, 30 Apr 2025 17:15:21 +0100
Subject: [PATCH 132/202] TYP: Type ``MaskedArray.swapaxes`` (#28850)

---
 numpy/ma/core.pyi                     | 9 ++++++++-
 numpy/typing/tests/data/fail/ma.pyi   | 2 ++
 numpy/typing/tests/data/reveal/ma.pyi | 3 +++
 3 files changed, 13 insertions(+), 1 deletion(-)

diff --git a/numpy/ma/core.pyi b/numpy/ma/core.pyi
index 9e755e5901da..73b2a803304c 100644
--- a/numpy/ma/core.pyi
+++ b/numpy/ma/core.pyi
@@ -793,7 +793,14 @@ class MaskedArray(ndarray[_ShapeT_co, _DTypeT_co]):
     ) -> MaskedArray[_Shape, _DTypeT_co]: ...
 
     squeeze: Any
-    swapaxes: Any
+
+    def swapaxes(
+        self,
+        axis1: SupportsIndex,
+        axis2: SupportsIndex,
+        /
+    ) -> MaskedArray[_Shape, _DTypeT_co]: ...
+
     T: Any
     transpose: Any
 
diff --git a/numpy/typing/tests/data/fail/ma.pyi b/numpy/typing/tests/data/fail/ma.pyi
index a4f2517fd4a6..d79008b60d25 100644
--- a/numpy/typing/tests/data/fail/ma.pyi
+++ b/numpy/typing/tests/data/fail/ma.pyi
@@ -122,3 +122,5 @@ np.ma.allequal(m, [1,2,3], fill_value=1.5)  # E: No overload variant
 np.ma.allclose(m, [1,2,3], masked_equal=4.5)  # E: No overload variant
 np.ma.allclose(m, [1,2,3], rtol='.4')  # E: No overload variant
 np.ma.allclose(m, [1,2,3], atol='.5')  # E: No overload variant
+
+m.swapaxes(axis1=1, axis2=0)  # E: No overload variant
diff --git a/numpy/typing/tests/data/reveal/ma.pyi b/numpy/typing/tests/data/reveal/ma.pyi
index 5274deed90a1..d59a0a709707 100644
--- a/numpy/typing/tests/data/reveal/ma.pyi
+++ b/numpy/typing/tests/data/reveal/ma.pyi
@@ -308,6 +308,9 @@ def func(x: object) -> None:
     else:
         assert_type(x, object)
 
+assert_type(MAR_b.swapaxes(0, 1), MaskedArray[np.bool])
+assert_type(MAR_2d_f4.swapaxes(1, 0), MaskedArray[np.float32])
+
 assert_type(np.ma.nomask, np.bool[Literal[False]])
 # https://github.com/python/mypy/issues/18974
 assert_type(np.ma.MaskType, type[np.bool])  # type: ignore[assert-type]

From 41241603ac40b2dab3e236800ee112279c661c75 Mon Sep 17 00:00:00 2001
From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com>
Date: Wed, 30 Apr 2025 17:50:15 +0000
Subject: [PATCH 133/202] MAINT: Bump astral-sh/setup-uv from 6.0.0 to 6.0.1

Bumps [astral-sh/setup-uv](https://github.com/astral-sh/setup-uv) from 6.0.0 to 6.0.1.
- [Release notes](https://github.com/astral-sh/setup-uv/releases)
- [Commits](https://github.com/astral-sh/setup-uv/compare/c7f87aa956e4c323abf06d5dec078e358f6b4d04...6b9c6063abd6010835644d4c2e1bef4cf5cd0fca)

---
updated-dependencies:
- dependency-name: astral-sh/setup-uv
  dependency-version: 6.0.1
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] 
---
 .github/workflows/macos.yml   | 2 +-
 .github/workflows/windows.yml | 2 +-
 2 files changed, 2 insertions(+), 2 deletions(-)

diff --git a/.github/workflows/macos.yml b/.github/workflows/macos.yml
index 7156e8f486f2..82de69009aac 100644
--- a/.github/workflows/macos.yml
+++ b/.github/workflows/macos.yml
@@ -124,7 +124,7 @@ jobs:
         fetch-tags: true
         persist-credentials: false
 
-    - uses: astral-sh/setup-uv@c7f87aa956e4c323abf06d5dec078e358f6b4d04
+    - uses: astral-sh/setup-uv@6b9c6063abd6010835644d4c2e1bef4cf5cd0fca
       with:
         activate-environment: true
         python-version: ${{ matrix.version }}
diff --git a/.github/workflows/windows.yml b/.github/workflows/windows.yml
index 985d7d9c6d6a..098c29f52893 100644
--- a/.github/workflows/windows.yml
+++ b/.github/workflows/windows.yml
@@ -35,7 +35,7 @@ jobs:
         persist-credentials: false
 
     - name: Setup Python
-      uses: astral-sh/setup-uv@c7f87aa956e4c323abf06d5dec078e358f6b4d04
+      uses: astral-sh/setup-uv@6b9c6063abd6010835644d4c2e1bef4cf5cd0fca
       with:
         activate-environment: true
         python-version: ${{ matrix.compiler-pyversion[1] }}

From 180a7a452c04d81557e1170ef9fceb2777f9cffe Mon Sep 17 00:00:00 2001
From: Dimitri Papadopoulos
 <3234522+DimitriPapadopoulos@users.noreply.github.com>
Date: Thu, 1 May 2025 10:17:53 +0200
Subject: [PATCH 134/202] MNT: retire old script for SVN repositories

Back in 2009, this script was used to determine active SVN committers
of NumPy, SciPy, and SciKits.
---
 tools/commitstats.py | 38 --------------------------------------
 1 file changed, 38 deletions(-)
 delete mode 100644 tools/commitstats.py

diff --git a/tools/commitstats.py b/tools/commitstats.py
deleted file mode 100644
index 5aee433025b4..000000000000
--- a/tools/commitstats.py
+++ /dev/null
@@ -1,38 +0,0 @@
-# Run svn log -l 
-
-import re
-import numpy as np
-import os
-
-names = re.compile(r'r\d+\s\|\s(.*)\s\|\s200')
-
-def get_count(filename, repo):
-    mystr = open(filename).read()
-    result = names.findall(mystr)
-    u = np.unique(result)
-    count = [(x, result.count(x), repo) for x in u]
-    return count
-
-
-command = 'svn log -l 2300 > output.txt'
-os.chdir('..')
-os.system(command)
-
-count = get_count('output.txt', 'NumPy')
-
-
-os.chdir('../scipy')
-os.system(command)
-
-count.extend(get_count('output.txt', 'SciPy'))
-
-os.chdir('../scikits')
-os.system(command)
-count.extend(get_count('output.txt', 'SciKits'))
-count.sort()
-
-
-print("** SciPy and NumPy **")
-print("=====================")
-for val in count:
-    print(val)

From e09450fc5f6e6aa04d317bb2f71c2b44efd25eb6 Mon Sep 17 00:00:00 2001
From: Dimitri Papadopoulos
 <3234522+DimitriPapadopoulos@users.noreply.github.com>
Date: Thu, 1 May 2025 10:34:10 +0200
Subject: [PATCH 135/202] MNT: retire script superseded by ruff rule W605

The script would detect deprecated invalid escape sequences, just like
ruff rule W605 which is now enabled:
https://docs.astral.sh/ruff/rules/invalid-escape-sequence/
---
 tools/find_deprecated_escaped_characters.py | 62 ---------------------
 1 file changed, 62 deletions(-)
 delete mode 100644 tools/find_deprecated_escaped_characters.py

diff --git a/tools/find_deprecated_escaped_characters.py b/tools/find_deprecated_escaped_characters.py
deleted file mode 100644
index d7225b8e85f6..000000000000
--- a/tools/find_deprecated_escaped_characters.py
+++ /dev/null
@@ -1,62 +0,0 @@
-#!/usr/bin/env python3
-r"""
-Look for escape sequences deprecated in Python 3.6.
-
-Python 3.6 deprecates a number of non-escape sequences starting with '\' that
-were accepted before. For instance, '\(' was previously accepted but must now
-be written as '\\(' or r'\('.
-
-"""
-
-
-def main(root):
-    """Find deprecated escape sequences.
-
-    Checks for deprecated escape sequences in ``*.py files``. If `root` is a
-    file, that file is checked, if `root` is a directory all ``*.py`` files
-    found in a recursive descent are checked.
-
-    If a deprecated escape sequence is found, the file and line where found is
-    printed. Note that for multiline strings the line where the string ends is
-    printed and the error(s) are somewhere in the body of the string.
-
-    Parameters
-    ----------
-    root : str
-        File or directory to check.
-    Returns
-    -------
-    None
-
-    """
-    import ast
-    import tokenize
-    import warnings
-    from pathlib import Path
-
-    count = 0
-    base = Path(root)
-    paths = base.rglob("*.py") if base.is_dir() else [base]
-    for path in paths:
-        # use tokenize to auto-detect encoding on systems where no
-        # default encoding is defined (e.g. LANG='C')
-        with tokenize.open(str(path)) as f:
-            with warnings.catch_warnings(record=True) as w:
-                warnings.simplefilter('always')
-                tree = ast.parse(f.read())
-            if w:
-                print("file: ", str(path))
-                for e in w:
-                    print('line: ', e.lineno, ': ', e.message)
-                print()
-                count += len(w)
-    print("Errors Found", count)
-
-
-if __name__ == "__main__":
-    from argparse import ArgumentParser
-
-    parser = ArgumentParser(description="Find deprecated escaped characters")
-    parser.add_argument('root', help='directory or file to be checked')
-    args = parser.parse_args()
-    main(args.root)

From 4a3cbc4f6644bcb0f510d56c33382329004507c5 Mon Sep 17 00:00:00 2001
From: Dimitri Papadopoulos
 <3234522+DimitriPapadopoulos@users.noreply.github.com>
Date: Thu, 1 May 2025 11:47:34 +0200
Subject: [PATCH 136/202] MNT: discard unused function using os.system()

---
 numpy/f2py/diagnose.py | 6 ------
 1 file changed, 6 deletions(-)

diff --git a/numpy/f2py/diagnose.py b/numpy/f2py/diagnose.py
index cbcaa9eb2931..7eb1697cc787 100644
--- a/numpy/f2py/diagnose.py
+++ b/numpy/f2py/diagnose.py
@@ -4,12 +4,6 @@
 import tempfile
 
 
-def run_command(cmd):
-    print(f'Running {cmd!r}:')
-    os.system(cmd)
-    print('------')
-
-
 def run():
     _path = os.getcwd()
     os.chdir(tempfile.gettempdir())

From 91e9b4200ad101d81e65cf2e0389b863ca3ed754 Mon Sep 17 00:00:00 2001
From: Dimitri Papadopoulos
 <3234522+DimitriPapadopoulos@users.noreply.github.com>
Date: Thu, 1 May 2025 10:51:11 +0200
Subject: [PATCH 137/202] DOC: consistent and updated LICENSE files for wheels

* Add an empty line to LICENSE_osx.txt for consistency.
* Change URLs from http:// to https://, now verbatim copy of latest GPLv3:
  https://www.gnu.org/licenses/gpl-3.0.txt
---
 tools/wheels/LICENSE_linux.txt | 10 +++++-----
 tools/wheels/LICENSE_osx.txt   | 11 ++++++-----
 tools/wheels/LICENSE_win32.txt | 10 +++++-----
 3 files changed, 16 insertions(+), 15 deletions(-)

diff --git a/tools/wheels/LICENSE_linux.txt b/tools/wheels/LICENSE_linux.txt
index 021b4b0289e7..9e2d9053b8a7 100644
--- a/tools/wheels/LICENSE_linux.txt
+++ b/tools/wheels/LICENSE_linux.txt
@@ -133,7 +133,7 @@ GCC RUNTIME LIBRARY EXCEPTION
 
 Version 3.1, 31 March 2009
 
-Copyright (C) 2009 Free Software Foundation, Inc. 
+Copyright (C) 2009 Free Software Foundation, Inc. 
 
 Everyone is permitted to copy and distribute verbatim copies of this
 license document, but changing it is not allowed.
@@ -207,7 +207,7 @@ requirements of the license of GCC.
                     GNU GENERAL PUBLIC LICENSE
                        Version 3, 29 June 2007
 
- Copyright (C) 2007 Free Software Foundation, Inc. 
+ Copyright (C) 2007 Free Software Foundation, Inc. 
  Everyone is permitted to copy and distribute verbatim copies
  of this license document, but changing it is not allowed.
 
@@ -851,7 +851,7 @@ the "copyright" line and a pointer to where the full notice is found.
     GNU General Public License for more details.
 
     You should have received a copy of the GNU General Public License
-    along with this program.  If not, see .
+    along with this program.  If not, see .
 
 Also add information on how to contact you by electronic and paper mail.
 
@@ -870,14 +870,14 @@ might be different; for a GUI interface, you would use an "about box".
   You should also get your employer (if you work as a programmer) or school,
 if any, to sign a "copyright disclaimer" for the program, if necessary.
 For more information on this, and how to apply and follow the GNU GPL, see
-.
+.
 
   The GNU General Public License does not permit incorporating your program
 into proprietary programs.  If your program is a subroutine library, you
 may consider it more useful to permit linking proprietary applications with
 the library.  If this is what you want to do, use the GNU Lesser General
 Public License instead of this License.  But first, please read
-.
+.
 
 Name: libquadmath
 Files: numpy.libs/libquadmath*.so
diff --git a/tools/wheels/LICENSE_osx.txt b/tools/wheels/LICENSE_osx.txt
index 81889131cfa7..7ef2e381874e 100644
--- a/tools/wheels/LICENSE_osx.txt
+++ b/tools/wheels/LICENSE_osx.txt
@@ -3,6 +3,7 @@
 
 This binary distribution of NumPy also bundles the following software:
 
+
 Name: OpenBLAS
 Files: numpy/.dylibs/libscipy_openblas*.so
 Description: bundled as a dynamically linked library
@@ -132,7 +133,7 @@ GCC RUNTIME LIBRARY EXCEPTION
 
 Version 3.1, 31 March 2009
 
-Copyright (C) 2009 Free Software Foundation, Inc. 
+Copyright (C) 2009 Free Software Foundation, Inc. 
 
 Everyone is permitted to copy and distribute verbatim copies of this
 license document, but changing it is not allowed.
@@ -206,7 +207,7 @@ requirements of the license of GCC.
                     GNU GENERAL PUBLIC LICENSE
                        Version 3, 29 June 2007
 
- Copyright (C) 2007 Free Software Foundation, Inc. 
+ Copyright (C) 2007 Free Software Foundation, Inc. 
  Everyone is permitted to copy and distribute verbatim copies
  of this license document, but changing it is not allowed.
 
@@ -850,7 +851,7 @@ the "copyright" line and a pointer to where the full notice is found.
     GNU General Public License for more details.
 
     You should have received a copy of the GNU General Public License
-    along with this program.  If not, see .
+    along with this program.  If not, see .
 
 Also add information on how to contact you by electronic and paper mail.
 
@@ -869,14 +870,14 @@ might be different; for a GUI interface, you would use an "about box".
   You should also get your employer (if you work as a programmer) or school,
 if any, to sign a "copyright disclaimer" for the program, if necessary.
 For more information on this, and how to apply and follow the GNU GPL, see
-.
+.
 
   The GNU General Public License does not permit incorporating your program
 into proprietary programs.  If your program is a subroutine library, you
 may consider it more useful to permit linking proprietary applications with
 the library.  If this is what you want to do, use the GNU Lesser General
 Public License instead of this License.  But first, please read
-.
+.
 
 Name: libquadmath
 Files: numpy/.dylibs/libquadmath*.so
diff --git a/tools/wheels/LICENSE_win32.txt b/tools/wheels/LICENSE_win32.txt
index a2ccce66fbe5..c8277e7710a2 100644
--- a/tools/wheels/LICENSE_win32.txt
+++ b/tools/wheels/LICENSE_win32.txt
@@ -133,7 +133,7 @@ GCC RUNTIME LIBRARY EXCEPTION
 
 Version 3.1, 31 March 2009
 
-Copyright (C) 2009 Free Software Foundation, Inc. 
+Copyright (C) 2009 Free Software Foundation, Inc. 
 
 Everyone is permitted to copy and distribute verbatim copies of this
 license document, but changing it is not allowed.
@@ -207,7 +207,7 @@ requirements of the license of GCC.
                     GNU GENERAL PUBLIC LICENSE
                        Version 3, 29 June 2007
 
- Copyright (C) 2007 Free Software Foundation, Inc. 
+ Copyright (C) 2007 Free Software Foundation, Inc. 
  Everyone is permitted to copy and distribute verbatim copies
  of this license document, but changing it is not allowed.
 
@@ -851,7 +851,7 @@ the "copyright" line and a pointer to where the full notice is found.
     GNU General Public License for more details.
 
     You should have received a copy of the GNU General Public License
-    along with this program.  If not, see .
+    along with this program.  If not, see .
 
 Also add information on how to contact you by electronic and paper mail.
 
@@ -870,12 +870,12 @@ might be different; for a GUI interface, you would use an "about box".
   You should also get your employer (if you work as a programmer) or school,
 if any, to sign a "copyright disclaimer" for the program, if necessary.
 For more information on this, and how to apply and follow the GNU GPL, see
-.
+.
 
   The GNU General Public License does not permit incorporating your program
 into proprietary programs.  If your program is a subroutine library, you
 may consider it more useful to permit linking proprietary applications with
 the library.  If this is what you want to do, use the GNU Lesser General
 Public License instead of this License.  But first, please read
-.
+.
 

From 3c9060ccf83a81d42b8ecbf4d38922e51f19a294 Mon Sep 17 00:00:00 2001
From: Ralf Gommers 
Date: Thu, 1 May 2025 12:30:00 +0200
Subject: [PATCH 138/202] DOC: update content of cross compilation build docs

[docs only]
---
 doc/source/building/cross_compilation.rst | 17 +++++++++++++----
 1 file changed, 13 insertions(+), 4 deletions(-)

diff --git a/doc/source/building/cross_compilation.rst b/doc/source/building/cross_compilation.rst
index 0a2e3a5af42a..f03b620ff031 100644
--- a/doc/source/building/cross_compilation.rst
+++ b/doc/source/building/cross_compilation.rst
@@ -2,10 +2,10 @@ Cross compilation
 =================
 
 Cross compilation is a complex topic, we only add some hopefully helpful hints
-here (for now). As of May 2023, cross-compilation based on ``crossenv`` is
-known to work, as used (for example) in conda-forge. Cross-compilation without
-``crossenv`` requires some manual overrides. You instruct these overrides by
-passing options to ``meson setup`` via `meson-python`_.
+here (for now). As of May 2025, cross-compilation with a Meson cross file as
+well as cross-compilation based on ``crossenv`` are known to work. Conda-forge
+uses the latter method. Cross-compilation without ``crossenv`` requires passing
+build options to ``meson setup`` via `meson-python`_.
 
 .. _meson-python: https://meson-python.readthedocs.io/en/latest/how-to-guides/meson-args.html
 
@@ -33,9 +33,18 @@ your *cross file*:
     [properties]
     longdouble_format = 'IEEE_DOUBLE_LE'
 
+For an example of a cross file needed to cross-compile NumPy, see
+`numpy#288861 `__.
+Putting that together, invoking a cross build with such a cross file, looks like:
+
+.. code:: bash
+
+   $ python -m build --wheel -Csetup-args="--cross-file=aarch64-myos-cross-file.txt"
+
 For more details and the current status around cross compilation, see:
 
 - The state of cross compilation in Python:
   `pypackaging-native key issue page `__
+- The `set of NumPy issues with the "Cross compilation" label `__
 - Tracking issue for SciPy cross-compilation needs and issues:
   `scipy#14812 `__

From 8e4143556c462c37b8cd372215abe3794f1a8c00 Mon Sep 17 00:00:00 2001
From: Dimitri Papadopoulos
 <3234522+DimitriPapadopoulos@users.noreply.github.com>
Date: Thu, 1 May 2025 12:49:39 +0200
Subject: [PATCH 139/202] STY: Apply ruff/refurb rule FURB110

Replace ternary `if` expression with `or` operator
---
 benchmarks/benchmarks/__init__.py             | 2 +-
 numpy/_core/code_generators/generate_umath.py | 2 +-
 numpy/_core/strings.py                        | 4 ++--
 numpy/_pytesttester.py                        | 2 +-
 numpy/f2py/tests/util.py                      | 2 +-
 numpy/testing/_private/extbuild.py            | 6 +++---
 6 files changed, 9 insertions(+), 9 deletions(-)

diff --git a/benchmarks/benchmarks/__init__.py b/benchmarks/benchmarks/__init__.py
index 6aa85c22f614..8372be467005 100644
--- a/benchmarks/benchmarks/__init__.py
+++ b/benchmarks/benchmarks/__init__.py
@@ -5,7 +5,7 @@
 def show_cpu_features():
     from numpy.lib._utils_impl import _opt_info
     info = _opt_info()
-    info = "NumPy CPU features: " + (info if info else 'nothing enabled')
+    info = "NumPy CPU features: " + (info or 'nothing enabled')
     # ASV wrapping stdout & stderr, so we assume having a tty here
     if 'SHELL' in os.environ and sys.platform != 'win32':
         # to avoid the red color that imposed by ASV
diff --git a/numpy/_core/code_generators/generate_umath.py b/numpy/_core/code_generators/generate_umath.py
index 35b5ad92ac82..fbda9393b5a5 100644
--- a/numpy/_core/code_generators/generate_umath.py
+++ b/numpy/_core/code_generators/generate_umath.py
@@ -1403,7 +1403,7 @@ def make_arrays(funcdict):
         sub = 0
 
         for k, t in enumerate(uf.type_descriptions):
-            cfunc_alias = t.cfunc_alias if t.cfunc_alias else name
+            cfunc_alias = t.cfunc_alias or name
             cfunc_fname = None
             if t.func_data is FullTypeDescr:
                 tname = english_upper(chartoname[t.type])
diff --git a/numpy/_core/strings.py b/numpy/_core/strings.py
index befd76d8ceed..cd6d1ec439f1 100644
--- a/numpy/_core/strings.py
+++ b/numpy/_core/strings.py
@@ -1332,8 +1332,8 @@ def replace(a, old, new, count=-1):
         return _replace(arr, old, new, count)
 
     a_dt = arr.dtype
-    old = old.astype(old_dtype if old_dtype else a_dt, copy=False)
-    new = new.astype(new_dtype if new_dtype else a_dt, copy=False)
+    old = old.astype(old_dtype or a_dt, copy=False)
+    new = new.astype(new_dtype or a_dt, copy=False)
     max_int64 = np.iinfo(np.int64).max
     counts = _count_ufunc(arr, old, 0, max_int64)
     counts = np.where(count < 0, counts, np.minimum(counts, count))
diff --git a/numpy/_pytesttester.py b/numpy/_pytesttester.py
index 482c6eddbca0..f41d54f36bec 100644
--- a/numpy/_pytesttester.py
+++ b/numpy/_pytesttester.py
@@ -39,7 +39,7 @@ def _show_numpy_info():
 
     print(f"NumPy version {np.__version__}")
     info = np.lib._utils_impl._opt_info()
-    print("NumPy CPU features: ", (info if info else 'nothing enabled'))
+    print("NumPy CPU features: ", (info or 'nothing enabled'))
 
 
 class PytestTester:
diff --git a/numpy/f2py/tests/util.py b/numpy/f2py/tests/util.py
index dbb7416b7765..ab2a1b6f8710 100644
--- a/numpy/f2py/tests/util.py
+++ b/numpy/f2py/tests/util.py
@@ -384,7 +384,7 @@ def setup_method(self):
         if self.module is not None:
             return
 
-        codes = self.sources if self.sources else []
+        codes = self.sources or []
         if self.code:
             codes.append(self.suffix)
 
diff --git a/numpy/testing/_private/extbuild.py b/numpy/testing/_private/extbuild.py
index af403bf7f8f4..f81184e9af1e 100644
--- a/numpy/testing/_private/extbuild.py
+++ b/numpy/testing/_private/extbuild.py
@@ -104,9 +104,9 @@ def compile_extension_module(
     dirname = builddir / name
     dirname.mkdir(exist_ok=True)
     cfile = _convert_str_to_file(source_string, dirname)
-    include_dirs = include_dirs if include_dirs else []
-    libraries = libraries if libraries else []
-    library_dirs = library_dirs if library_dirs else []
+    include_dirs = include_dirs or []
+    libraries = libraries or []
+    library_dirs = library_dirs or []
 
     return _c_compile(
         cfile, outputfilename=dirname / modname,

From a53b45f66255ee378a29d3a255a1de52fb1af522 Mon Sep 17 00:00:00 2001
From: Dimitri Papadopoulos
 <3234522+DimitriPapadopoulos@users.noreply.github.com>
Date: Thu, 1 May 2025 13:00:07 +0200
Subject: [PATCH 140/202] STY: Apply ruff/refurb rule FURB113

Use `extend()` instead of repeatedly calling `append()`
---
 numpy/_core/code_generators/generate_umath.py | 18 +++++++++---------
 numpy/lib/tests/test_arraysetops.py           |  8 ++------
 numpy/random/tests/test_direct.py             |  3 +--
 3 files changed, 12 insertions(+), 17 deletions(-)

diff --git a/numpy/_core/code_generators/generate_umath.py b/numpy/_core/code_generators/generate_umath.py
index fbda9393b5a5..eb5751df590f 100644
--- a/numpy/_core/code_generators/generate_umath.py
+++ b/numpy/_core/code_generators/generate_umath.py
@@ -1466,13 +1466,11 @@ def make_arrays(funcdict):
             funcnames = ', '.join(funclist)
             signames = ', '.join(siglist)
             datanames = ', '.join(datalist)
-            code1list.append(
-                "static PyUFuncGenericFunction %s_functions[] = {%s};"
-                % (name, funcnames))
-            code1list.append("static void * %s_data[] = {%s};"
-                            % (name, datanames))
-            code1list.append("static const char %s_signatures[] = {%s};"
-                            % (name, signames))
+            code1list.extend((
+                f"static PyUFuncGenericFunction {name}_functions[] = {{{funcnames}}};",
+                f"static void * {name}_data[] = {{{datanames}}};",
+                f"static const char {name}_signatures[] = {{{signames}}};",
+            ))
             uf.empty = False
         else:
             uf.empty = True
@@ -1573,8 +1571,10 @@ def make_ufuncs(funcdict):
                 funcname=f"{english_upper(chartoname[c])}_{name}_indexed",
             ))
 
-        mlist.append(r"""PyDict_SetItemString(dictionary, "%s", f);""" % name)
-        mlist.append(r"""Py_DECREF(f);""")
+        mlist.extend((
+            f'PyDict_SetItemString(dictionary, "{name}", f);',
+            "Py_DECREF(f);",
+        ))
         code3list.append('\n'.join(mlist))
     return '\n'.join(code3list)
 
diff --git a/numpy/lib/tests/test_arraysetops.py b/numpy/lib/tests/test_arraysetops.py
index 788a4cecdb44..b4c4b39aac83 100644
--- a/numpy/lib/tests/test_arraysetops.py
+++ b/numpy/lib/tests/test_arraysetops.py
@@ -688,8 +688,7 @@ def get_types(self):
         types = []
         types.extend(np.typecodes['AllInteger'])
         types.extend(np.typecodes['AllFloat'])
-        types.append('datetime64[D]')
-        types.append('timedelta64[D]')
+        types.extend(('datetime64[D]', 'timedelta64[D]'))
         return types
 
     def test_unique_1d(self):
@@ -871,10 +870,7 @@ def test_unique_axis(self):
         types = []
         types.extend(np.typecodes['AllInteger'])
         types.extend(np.typecodes['AllFloat'])
-        types.append('datetime64[D]')
-        types.append('timedelta64[D]')
-        types.append([('a', int), ('b', int)])
-        types.append([('a', int), ('b', float)])
+        types.extend(('datetime64[D]', 'timedelta64[D]', [('a', int), ('b', int)], [('a', int), ('b', float)]))
 
         for dtype in types:
             self._run_axis_tests(dtype)
diff --git a/numpy/random/tests/test_direct.py b/numpy/random/tests/test_direct.py
index c8a83f3bc40b..23da9714ddb8 100644
--- a/numpy/random/tests/test_direct.py
+++ b/numpy/random/tests/test_direct.py
@@ -123,8 +123,7 @@ def gauss_from_uint(x, n, bits):
             loc += 2
 
         f = np.sqrt(-2.0 * np.log(r2) / r2)
-        gauss.append(f * x2)
-        gauss.append(f * x1)
+        gauss.extend((f * x2, f * x1))
 
     return gauss[:n]
 

From f61fb70e35b3f27d26a76b9beaee65f395ceaf96 Mon Sep 17 00:00:00 2001
From: Dimitri Papadopoulos
 <3234522+DimitriPapadopoulos@users.noreply.github.com>
Date: Thu, 1 May 2025 12:47:56 +0200
Subject: [PATCH 141/202] STY: Apply ruff/refurb rule FURB116

Replace `hex` call with f-string
---
 numpy/_build_utils/tempita/_tempita.py | 6 +-----
 1 file changed, 1 insertion(+), 5 deletions(-)

diff --git a/numpy/_build_utils/tempita/_tempita.py b/numpy/_build_utils/tempita/_tempita.py
index d8ce41742f3a..446658fc15f8 100644
--- a/numpy/_build_utils/tempita/_tempita.py
+++ b/numpy/_build_utils/tempita/_tempita.py
@@ -175,11 +175,7 @@ def from_filename(
     from_filename = classmethod(from_filename)
 
     def __repr__(self):
-        return "<%s %s name=%r>" % (
-            self.__class__.__name__,
-            hex(id(self))[2:],
-            self.name,
-        )
+        return f"<{self.__class__.__name__} {id(self):x} name={self.name!r}>"
 
     def substitute(self, *args, **kw):
         if args:

From f1b77fae7d74e609d7c25adc814c41df3cea5679 Mon Sep 17 00:00:00 2001
From: Dimitri Papadopoulos
 <3234522+DimitriPapadopoulos@users.noreply.github.com>
Date: Thu, 1 May 2025 13:02:00 +0200
Subject: [PATCH 142/202] STY: Apply ruff/refurb rule FURB140

Use `itertools.starmap` instead of the generator
---
 benchmarks/benchmarks/bench_ufunc.py      | 4 ++--
 doc/source/reference/simd/gen_features.py | 3 ++-
 numpy/_core/code_generators/genapi.py     | 3 ++-
 numpy/_core/tests/test_cython.py          | 4 ++--
 numpy/_core/tests/test_mem_overlap.py     | 9 ++++-----
 numpy/_core/tests/test_scalarmath.py      | 4 ++--
 numpy/_core/tests/test_simd.py            | 8 ++++----
 numpy/_core/tests/test_strings.py         | 7 ++++---
 numpy/_core/tests/test_umath.py           | 4 ++--
 numpy/lib/_arrayterator_impl.py           | 6 +++---
 numpy/lib/_function_base_impl.py          | 3 ++-
 numpy/lib/_iotools.py                     | 2 +-
 numpy/lib/tests/test_arrayterator.py      | 3 ++-
 numpy/ma/extras.py                        | 5 ++---
 14 files changed, 34 insertions(+), 31 deletions(-)

diff --git a/benchmarks/benchmarks/bench_ufunc.py b/benchmarks/benchmarks/bench_ufunc.py
index 4d9f3c9c8f61..810555fec73b 100644
--- a/benchmarks/benchmarks/bench_ufunc.py
+++ b/benchmarks/benchmarks/bench_ufunc.py
@@ -61,7 +61,7 @@ def setup(self, ufuncname):
             self.args.append(arg)
 
     def time_afdn_types(self, ufuncname):
-        [self.afdn(*arg) for arg in self.args]
+        list(itertools.starmap(self.afdn, self.args))
 
 
 class Broadcast(Benchmark):
@@ -108,7 +108,7 @@ def setup(self, ufuncname):
             self.args.append(arg)
 
     def time_ufunc_types(self, ufuncname):
-        [self.ufn(*arg) for arg in self.args]
+        list(itertools.starmap(self.ufn, self.args))
 
 
 class MethodsV0(Benchmark):
diff --git a/doc/source/reference/simd/gen_features.py b/doc/source/reference/simd/gen_features.py
index 47b35dbfc397..2d8a2e49cd2f 100644
--- a/doc/source/reference/simd/gen_features.py
+++ b/doc/source/reference/simd/gen_features.py
@@ -2,6 +2,7 @@
 Generate CPU features tables from CCompilerOpt
 """
 from os import path
+from itertools import starmap
 from numpy.distutils.ccompiler_opt import CCompilerOpt
 
 class FakeCCompilerOpt(CCompilerOpt):
@@ -122,7 +123,7 @@ def gen_rst_table(self, field_names, rows, tab_size=4):
         cformat = ' '.join('{:<%d}' % i for i in cls_len)
         border = cformat.format(*['=' * i for i in cls_len])
 
-        rows = [cformat.format(*row) for row in rows]
+        rows = list(starmap(cformat.format, rows))
         # header
         rows = [border, cformat.format(*field_names), border] + rows
         # footer
diff --git a/numpy/_core/code_generators/genapi.py b/numpy/_core/code_generators/genapi.py
index 9b51904a2d7d..3045149b3405 100644
--- a/numpy/_core/code_generators/genapi.py
+++ b/numpy/_core/code_generators/genapi.py
@@ -15,6 +15,7 @@
 import textwrap
 
 from os.path import join
+from itertools import starmap
 
 
 def get_processor():
@@ -152,7 +153,7 @@ def _format_arg(self, typename, name):
             return typename + ' ' + name
 
     def __str__(self):
-        argstr = ', '.join([self._format_arg(*a) for a in self.args])
+        argstr = ', '.join(list(starmap(self._format_arg, self.args)))
         if self.doc:
             doccomment = f'/* {self.doc} */\n'
         else:
diff --git a/numpy/_core/tests/test_cython.py b/numpy/_core/tests/test_cython.py
index 81ddc63258c2..3fd45582c5eb 100644
--- a/numpy/_core/tests/test_cython.py
+++ b/numpy/_core/tests/test_cython.py
@@ -3,6 +3,7 @@
 import subprocess
 import sys
 import pytest
+from itertools import starmap
 
 import numpy as np
 from numpy.testing import assert_array_equal, IS_WASM, IS_EDITABLE
@@ -278,8 +279,7 @@ def test_npyiter_api(install_temp):
         x is y for x, y in zip(checks.get_npyiter_operands(it), it.operands)
     )
     assert all(
-        np.allclose(x, y)
-        for x, y in zip(checks.get_npyiter_itviews(it), it.itviews)
+        starmap(np.allclose, zip(checks.get_npyiter_itviews(it), it.itviews))
     )
 
 
diff --git a/numpy/_core/tests/test_mem_overlap.py b/numpy/_core/tests/test_mem_overlap.py
index 0d80951a854a..9317d87358f3 100644
--- a/numpy/_core/tests/test_mem_overlap.py
+++ b/numpy/_core/tests/test_mem_overlap.py
@@ -281,7 +281,7 @@ def random_slice_fixed_size(n, step, size):
         steps = tuple(rng.randint(1, 11, dtype=np.intp)
                       if rng.randint(0, 5, dtype=np.intp) == 0 else 1
                       for j in range(x.ndim))
-        s1 = tuple(random_slice(p, s) for p, s in zip(x.shape, steps))
+        s1 = tuple(itertools.starmap(random_slice, zip(x.shape, steps)))
 
         t1 = np.arange(x.ndim)
         rng.shuffle(t1)
@@ -301,8 +301,7 @@ def random_slice_fixed_size(n, step, size):
             steps2 = tuple(rng.randint(1, max(2, p // (1 + pa)))
                            if rng.randint(0, 5) == 0 else 1
                            for p, s, pa in zip(x.shape, s1, a.shape))
-            s2 = tuple(random_slice_fixed_size(p, s, pa)
-                       for p, s, pa in zip(x.shape, steps2, a.shape))
+            s2 = tuple(itertools.starmap(random_slice_fixed_size, zip(x.shape, steps2, a.shape)))
         elif same_steps:
             steps2 = steps
         else:
@@ -311,7 +310,7 @@ def random_slice_fixed_size(n, step, size):
                            for j in range(x.ndim))
 
         if not equal_size:
-            s2 = tuple(random_slice(p, s) for p, s in zip(x.shape, steps2))
+            s2 = tuple(itertools.starmap(random_slice, zip(x.shape, steps2)))
 
         a = a.transpose(t1)
         b = x[s2].transpose(t2)
@@ -442,7 +441,7 @@ def random_slice(n, step):
                       for j in range(x.ndim))
         t1 = np.arange(x.ndim)
         rng.shuffle(t1)
-        s1 = tuple(random_slice(p, s) for p, s in zip(x.shape, steps))
+        s1 = tuple(itertools.starmap(random_slice, zip(x.shape, steps)))
         a = x[s1].transpose(t1)
 
         assert_(not internal_overlap(a))
diff --git a/numpy/_core/tests/test_scalarmath.py b/numpy/_core/tests/test_scalarmath.py
index 0b086df21c60..ad671c94c78b 100644
--- a/numpy/_core/tests/test_scalarmath.py
+++ b/numpy/_core/tests/test_scalarmath.py
@@ -314,7 +314,7 @@ def test_float_modulus_exact(self):
         dividend = nlst + [0] + plst
         divisor = nlst + plst
         arg = list(itertools.product(dividend, divisor))
-        tgt = [divmod(*t) for t in arg]
+        tgt = list(itertools.starmap(divmod, arg))
 
         a, b = np.array(arg, dtype=int).T
         # convert exact integer results from Python to float so that
@@ -329,7 +329,7 @@ def test_float_modulus_exact(self):
                 fa = a.astype(dt)
                 fb = b.astype(dt)
                 # use list comprehension so a_ and b_ are scalars
-                div, rem = zip(*[op(a_, b_) for a_, b_ in zip(fa, fb)])
+                div, rem = zip(*list(itertools.starmap(op, zip(fa, fb))))
                 assert_equal(div, tgtdiv, err_msg=msg)
                 assert_equal(rem, tgtrem, err_msg=msg)
 
diff --git a/numpy/_core/tests/test_simd.py b/numpy/_core/tests/test_simd.py
index fdcab688963e..385b2cc6c0bf 100644
--- a/numpy/_core/tests/test_simd.py
+++ b/numpy/_core/tests/test_simd.py
@@ -302,11 +302,11 @@ def test_math_max_min(self):
         data_b = self._data(self.nlanes)
         vdata_a, vdata_b = self.load(data_a), self.load(data_b)
 
-        data_max = [max(a, b) for a, b in zip(data_a, data_b)]
+        data_max = list(itertools.starmap(max, zip(data_a, data_b)))
         simd_max = self.max(vdata_a, vdata_b)
         assert simd_max == data_max
 
-        data_min = [min(a, b) for a, b in zip(data_a, data_b)]
+        data_min = list(itertools.starmap(min, zip(data_a, data_b)))
         simd_min = self.min(vdata_a, vdata_b)
         assert simd_min == data_min
 
@@ -613,7 +613,7 @@ def to_bool(vector):
             vdata_a = self.setall(case_operand1)
             vdata_b = self.setall(case_operand2)
             vcmp = to_bool(intrin(vdata_a, vdata_b))
-            data_cmp = [py_comp(a, b) for a, b in zip(data_a, data_b)]
+            data_cmp = list(itertools.starmap(py_comp, zip(data_a, data_b)))
             assert vcmp == data_cmp
 
     @pytest.mark.parametrize("intrin", ["any", "all"])
@@ -1036,7 +1036,7 @@ def test_operators_comparison(self, func, intrin):
         def to_bool(vector):
             return [lane == mask_true for lane in vector]
 
-        data_cmp = [func(a, b) for a, b in zip(data_a, data_b)]
+        data_cmp = list(itertools.starmap(func, zip(data_a, data_b)))
         cmp = to_bool(intrin(vdata_a, vdata_b))
         assert cmp == data_cmp
 
diff --git a/numpy/_core/tests/test_strings.py b/numpy/_core/tests/test_strings.py
index 7960142162c5..7ea94eafa7da 100644
--- a/numpy/_core/tests/test_strings.py
+++ b/numpy/_core/tests/test_strings.py
@@ -1,9 +1,10 @@
 import sys
+import operator
+from itertools import starmap
+
 import pytest
 
-import operator
 import numpy as np
-
 from numpy.testing import assert_array_equal, assert_raises, IS_PYPY
 from numpy.testing._private.utils import requires_memory
 
@@ -65,7 +66,7 @@ def test_string_comparisons(op, ufunc, sym, dtypes, aligned):
     np.random.shuffle(arr2)
     arr[0] = arr2[0]  # make sure one matches
 
-    expected = [op(d1, d2) for d1, d2 in zip(arr.tolist(), arr2.tolist())]
+    expected = list(starmap(op, zip(arr.tolist(), arr2.tolist())))
     assert_array_equal(op(arr, arr2), expected)
     assert_array_equal(ufunc(arr, arr2), expected)
     assert_array_equal(
diff --git a/numpy/_core/tests/test_umath.py b/numpy/_core/tests/test_umath.py
index 22ad1b8ac302..0078c2a9d54b 100644
--- a/numpy/_core/tests/test_umath.py
+++ b/numpy/_core/tests/test_umath.py
@@ -508,7 +508,7 @@ def test_division_int_boundary(self, dtype, ex_val):
             ac = a.copy()
             ac //= b
             div_ab = a // b
-        div_lst = [c_div(x, y) for x, y in zip(a_lst, b_lst)]
+        div_lst = list(itertools.starmap(c_div, zip(a_lst, b_lst)))
 
         msg = "Integer arrays floor division check (//)"
         assert all(div_ab == div_lst), msg
@@ -740,7 +740,7 @@ def test_float_remainder_exact(self):
         dividend = nlst + [0] + plst
         divisor = nlst + plst
         arg = list(itertools.product(dividend, divisor))
-        tgt = [divmod(*t) for t in arg]
+        tgt = list(itertools.starmap(divmod, arg))
 
         a, b = np.array(arg, dtype=int).T
         # convert exact integer results from Python to float so that
diff --git a/numpy/lib/_arrayterator_impl.py b/numpy/lib/_arrayterator_impl.py
index 5bb1630a9300..9aa7bcc0690c 100644
--- a/numpy/lib/_arrayterator_impl.py
+++ b/numpy/lib/_arrayterator_impl.py
@@ -9,6 +9,7 @@
 """
 from operator import mul
 from functools import reduce
+from itertools import starmap
 
 __all__ = ['Arrayterator']
 
@@ -133,8 +134,7 @@ def __array__(self, dtype=None, copy=None):
         Return corresponding data.
 
         """
-        slice_ = tuple(slice(*t) for t in zip(
-                self.start, self.stop, self.step))
+        slice_ = tuple(starmap(slice, zip(self.start, self.stop, self.step)))
         return self.var[slice_]
 
     @property
@@ -210,7 +210,7 @@ def __iter__(self):
                 count = count // self.shape[i]
 
             # yield a block
-            slice_ = tuple(slice(*t) for t in zip(start, stop, step))
+            slice_ = tuple(starmap(slice, zip(start, stop, step)))
             yield self.var[slice_]
 
             # Update start position, taking care of overflow to
diff --git a/numpy/lib/_function_base_impl.py b/numpy/lib/_function_base_impl.py
index e44b27a68adb..b5bf32398339 100644
--- a/numpy/lib/_function_base_impl.py
+++ b/numpy/lib/_function_base_impl.py
@@ -4,6 +4,7 @@
 import re
 import sys
 import warnings
+from itertools import starmap
 
 import numpy as np
 import numpy._core.numeric as _nx
@@ -1971,7 +1972,7 @@ def trim_zeros(filt, trim='fb', axis=None):
         sl = slice(start[0], stop[0])
     elif axis is None:
         # trim all axes
-        sl = tuple(slice(*x) for x in zip(start, stop))
+        sl = tuple(starmap(slice, zip(start, stop)))
     else:
         # only trim single axis
         axis = normalize_axis_index(axis, filt_.ndim)
diff --git a/numpy/lib/_iotools.py b/numpy/lib/_iotools.py
index 56ee65d38575..5a2372ef75f7 100644
--- a/numpy/lib/_iotools.py
+++ b/numpy/lib/_iotools.py
@@ -181,7 +181,7 @@ def __init__(self, delimiter=None, comments='#', autostrip=True,
         elif hasattr(delimiter, '__iter__'):
             _handyman = self._variablewidth_splitter
             idx = np.cumsum([0] + list(delimiter))
-            delimiter = [slice(i, j) for (i, j) in itertools.pairwise(idx)]
+            delimiter = list(itertools.starmap(slice, itertools.pairwise(idx)))
         # Delimiter is a single integer
         elif int(delimiter):
             (_handyman, delimiter) = (
diff --git a/numpy/lib/tests/test_arrayterator.py b/numpy/lib/tests/test_arrayterator.py
index e64d1d1e3ece..675cc513ab54 100644
--- a/numpy/lib/tests/test_arrayterator.py
+++ b/numpy/lib/tests/test_arrayterator.py
@@ -1,5 +1,6 @@
 from operator import mul
 from functools import reduce
+from itertools import starmap
 
 import numpy as np
 from numpy.random import randint
@@ -31,7 +32,7 @@ def test():
     start = [randint(dim) for dim in shape]
     stop = [randint(dim) + 1 for dim in shape]
     step = [randint(dim) + 1 for dim in shape]
-    slice_ = tuple(slice(*t) for t in zip(start, stop, step))
+    slice_ = tuple(starmap(slice, zip(start, stop, step)))
     c = b[slice_]
     d = a[slice_]
 
diff --git a/numpy/ma/extras.py b/numpy/ma/extras.py
index 22151b95e27d..ef1b6904ae39 100644
--- a/numpy/ma/extras.py
+++ b/numpy/ma/extras.py
@@ -2183,13 +2183,12 @@ def _ezclump(mask):
             return [slice(0, mask.size)]
 
         r = [slice(0, idx[0])]
-        r.extend((slice(left, right)
-                  for left, right in zip(idx[1:-1:2], idx[2::2])))
+        r.extend(itertools.starmap(slice, zip(idx[1:-1:2], idx[2::2])))
     else:
         if len(idx) == 0:
             return []
 
-        r = [slice(left, right) for left, right in zip(idx[:-1:2], idx[1::2])]
+        r = list(itertools.starmap(slice, zip(idx[:-1:2], idx[1::2])))
 
     if mask[-1]:
         r.append(slice(idx[-1], mask.size))

From 73374eb69c0323e5ccaaa58a5defe01c6142c11d Mon Sep 17 00:00:00 2001
From: Dimitri Papadopoulos
 <3234522+DimitriPapadopoulos@users.noreply.github.com>
Date: Thu, 1 May 2025 12:38:49 +0200
Subject: [PATCH 143/202] STY: Enforce more ruff rules

---
 ruff.toml | 5 +++++
 1 file changed, 5 insertions(+)

diff --git a/ruff.toml b/ruff.toml
index d01ff1b5dd21..c01b5cf30991 100644
--- a/ruff.toml
+++ b/ruff.toml
@@ -17,7 +17,11 @@ extend-exclude = [
 [lint]
 preview = true
 extend-select = [
+    "C4",
+    "LOG",
+    "G",
     "PIE",
+    "TID",
     "FLY",
     "E",
     "W",
@@ -27,6 +31,7 @@ extend-select = [
 ]
 ignore = [
     "F",      # TODO: enable Pyflakes rules
+    "C408",   # Unnecessary `dict()` call (rewrite as a literal)
     "PIE790", # Unnecessary `pass` statement
     "E241",   # Multiple spaces after comma
     "E251",   # Unexpected spaces around keyword / parameter equals

From d1b5dcc6640d4af6e610788136161098da8e7e17 Mon Sep 17 00:00:00 2001
From: Dimitri Papadopoulos
 <3234522+DimitriPapadopoulos@users.noreply.github.com>
Date: Thu, 1 May 2025 12:40:41 +0200
Subject: [PATCH 144/202] STY: Apply ruff/flake8-tidy-imports rule TID252

Prefer absolute imports over relative imports from parent modules
---
 numpy/_core/_exceptions.py      | 2 +-
 numpy/_core/_internal.py        | 2 +-
 numpy/_core/_machar.py          | 2 +-
 numpy/_core/_ufunc_config.py    | 2 +-
 numpy/_core/defchararray.py     | 2 +-
 numpy/_core/fromnumeric.py      | 2 +-
 numpy/_core/getlimits.py        | 2 +-
 numpy/_core/memmap.py           | 2 +-
 numpy/_core/numeric.py          | 2 +-
 numpy/_core/numerictypes.py     | 2 +-
 numpy/_core/overrides.py        | 4 ++--
 numpy/_core/records.py          | 2 +-
 numpy/_typing/_nbit_base.py     | 2 +-
 numpy/_typing/_ufunc.py         | 2 +-
 numpy/compat/__init__.py        | 4 ++--
 numpy/lib/_datasource.py        | 2 +-
 numpy/lib/_index_tricks_impl.py | 2 +-
 numpy/lib/_polynomial_impl.py   | 2 +-
 numpy/lib/_type_check_impl.py   | 2 +-
 numpy/matrixlib/defmatrix.py    | 2 +-
 20 files changed, 22 insertions(+), 22 deletions(-)

diff --git a/numpy/_core/_exceptions.py b/numpy/_core/_exceptions.py
index 180e71946e6c..aaa41648a1d2 100644
--- a/numpy/_core/_exceptions.py
+++ b/numpy/_core/_exceptions.py
@@ -5,7 +5,7 @@
 By putting the formatting in `__str__`, we also avoid paying the cost for
 users who silence the exceptions.
 """
-from .._utils import set_module
+from numpy._utils import set_module
 
 def _unpack_tuple(tup):
     if len(tup) == 1:
diff --git a/numpy/_core/_internal.py b/numpy/_core/_internal.py
index ed31afde6fa8..915510b220d0 100644
--- a/numpy/_core/_internal.py
+++ b/numpy/_core/_internal.py
@@ -10,7 +10,7 @@
 import sys
 import warnings
 
-from ..exceptions import DTypePromotionError
+from numpy.exceptions import DTypePromotionError
 from .multiarray import dtype, array, ndarray, promote_types, StringDType
 from numpy import _NoValue
 try:
diff --git a/numpy/_core/_machar.py b/numpy/_core/_machar.py
index e9d621b764c3..84d1f82a89ab 100644
--- a/numpy/_core/_machar.py
+++ b/numpy/_core/_machar.py
@@ -9,7 +9,7 @@
 
 from .fromnumeric import any
 from ._ufunc_config import errstate
-from .._utils import set_module
+from numpy._utils import set_module
 
 # Need to speed this up...especially for longdouble
 
diff --git a/numpy/_core/_ufunc_config.py b/numpy/_core/_ufunc_config.py
index ec9fd77ecbd8..edb533ea3c2b 100644
--- a/numpy/_core/_ufunc_config.py
+++ b/numpy/_core/_ufunc_config.py
@@ -8,7 +8,7 @@
 import contextvars
 import functools
 
-from .._utils import set_module
+from numpy._utils import set_module
 from .umath import _make_extobj, _get_extobj_dict, _extobj_contextvar
 
 __all__ = [
diff --git a/numpy/_core/defchararray.py b/numpy/_core/defchararray.py
index cde1c3a7f291..d782e6131337 100644
--- a/numpy/_core/defchararray.py
+++ b/numpy/_core/defchararray.py
@@ -18,7 +18,7 @@
 import functools
 
 import numpy as np
-from .._utils import set_module
+from numpy._utils import set_module
 from .numerictypes import bytes_, str_, character
 from .numeric import ndarray, array as narray, asarray as asnarray
 from numpy._core.multiarray import compare_chararrays
diff --git a/numpy/_core/fromnumeric.py b/numpy/_core/fromnumeric.py
index 1b8b5198277a..bc00877612d6 100644
--- a/numpy/_core/fromnumeric.py
+++ b/numpy/_core/fromnumeric.py
@@ -6,7 +6,7 @@
 import warnings
 
 import numpy as np
-from .._utils import set_module
+from numpy._utils import set_module
 from . import multiarray as mu
 from . import overrides
 from . import umath as um
diff --git a/numpy/_core/getlimits.py b/numpy/_core/getlimits.py
index f33a1254467d..2dc6d1e7fad2 100644
--- a/numpy/_core/getlimits.py
+++ b/numpy/_core/getlimits.py
@@ -6,7 +6,7 @@
 import types
 import warnings
 
-from .._utils import set_module
+from numpy._utils import set_module
 from ._machar import MachAr
 from . import numeric
 from . import numerictypes as ntypes
diff --git a/numpy/_core/memmap.py b/numpy/_core/memmap.py
index cf95687962af..561ac38a4d58 100644
--- a/numpy/_core/memmap.py
+++ b/numpy/_core/memmap.py
@@ -1,7 +1,7 @@
 from contextlib import nullcontext
 import operator
 import numpy as np
-from .._utils import set_module
+from numpy._utils import set_module
 from .numeric import uint8, ndarray, dtype
 
 __all__ = ['memmap']
diff --git a/numpy/_core/numeric.py b/numpy/_core/numeric.py
index da82391b4b8a..7adeaeddda54 100644
--- a/numpy/_core/numeric.py
+++ b/numpy/_core/numeric.py
@@ -26,7 +26,7 @@
 from .overrides import finalize_array_function_like, set_module
 from .umath import (multiply, invert, sin, PINF, NAN)
 from . import numerictypes
-from ..exceptions import AxisError
+from numpy.exceptions import AxisError
 from ._ufunc_config import errstate
 
 bitwise_not = invert
diff --git a/numpy/_core/numerictypes.py b/numpy/_core/numerictypes.py
index 029390ab0a5a..cb8d3c11a23f 100644
--- a/numpy/_core/numerictypes.py
+++ b/numpy/_core/numerictypes.py
@@ -84,7 +84,7 @@
         ndarray, dtype, datetime_data, datetime_as_string,
         busday_offset, busday_count, is_busday, busdaycalendar
         )
-from .._utils import set_module
+from numpy._utils import set_module
 
 # we add more at the bottom
 __all__ = [
diff --git a/numpy/_core/overrides.py b/numpy/_core/overrides.py
index c73d8eb4c1c5..aed83d17b836 100644
--- a/numpy/_core/overrides.py
+++ b/numpy/_core/overrides.py
@@ -2,8 +2,8 @@
 import collections
 import functools
 
-from .._utils import set_module
-from .._utils._inspect import getargspec
+from numpy._utils import set_module
+from numpy._utils._inspect import getargspec
 from numpy._core._multiarray_umath import (
     add_docstring, _get_implementing_args, _ArrayFunctionDispatcher)
 
diff --git a/numpy/_core/records.py b/numpy/_core/records.py
index 3e2d48d5f267..6d0331984bc7 100644
--- a/numpy/_core/records.py
+++ b/numpy/_core/records.py
@@ -6,7 +6,7 @@
 from collections import Counter
 from contextlib import nullcontext
 
-from .._utils import set_module
+from numpy._utils import set_module
 from . import numeric as sb
 from . import numerictypes as nt
 from .arrayprint import _get_legacy_print_mode
diff --git a/numpy/_typing/_nbit_base.py b/numpy/_typing/_nbit_base.py
index 4f764757c4ea..bf16c436c6da 100644
--- a/numpy/_typing/_nbit_base.py
+++ b/numpy/_typing/_nbit_base.py
@@ -1,5 +1,5 @@
 """A module with the precisions of generic `~numpy.number` types."""
-from .._utils import set_module
+from numpy._utils import set_module
 from typing import final
 
 
diff --git a/numpy/_typing/_ufunc.py b/numpy/_typing/_ufunc.py
index d0573c8f5463..db52a1fdb318 100644
--- a/numpy/_typing/_ufunc.py
+++ b/numpy/_typing/_ufunc.py
@@ -1,4 +1,4 @@
-from .. import ufunc
+from numpy import ufunc
 
 _UFunc_Nin1_Nout1 = ufunc
 _UFunc_Nin2_Nout1 = ufunc
diff --git a/numpy/compat/__init__.py b/numpy/compat/__init__.py
index 729265aa9c27..8f926c4bd568 100644
--- a/numpy/compat/__init__.py
+++ b/numpy/compat/__init__.py
@@ -13,8 +13,8 @@
 
 import warnings
 
-from .._utils import _inspect
-from .._utils._inspect import getargspec, formatargspec
+from numpy._utils import _inspect
+from numpy._utils._inspect import getargspec, formatargspec
 from . import py3k
 from .py3k import *
 
diff --git a/numpy/lib/_datasource.py b/numpy/lib/_datasource.py
index 1babc722b036..5dafb0ee3843 100644
--- a/numpy/lib/_datasource.py
+++ b/numpy/lib/_datasource.py
@@ -36,7 +36,7 @@
 """
 import os
 
-from .._utils import set_module
+from numpy._utils import set_module
 
 
 _open = open
diff --git a/numpy/lib/_index_tricks_impl.py b/numpy/lib/_index_tricks_impl.py
index 77aa1394fa0e..7fe0539fa86d 100644
--- a/numpy/lib/_index_tricks_impl.py
+++ b/numpy/lib/_index_tricks_impl.py
@@ -4,7 +4,7 @@
 import warnings
 
 import numpy as np
-from .._utils import set_module
+from numpy._utils import set_module
 import numpy._core.numeric as _nx
 from numpy._core.numeric import ScalarType, array
 from numpy._core.numerictypes import issubdtype
diff --git a/numpy/lib/_polynomial_impl.py b/numpy/lib/_polynomial_impl.py
index 91cf7405a1cc..a1d21c624c57 100644
--- a/numpy/lib/_polynomial_impl.py
+++ b/numpy/lib/_polynomial_impl.py
@@ -10,7 +10,7 @@
 import re
 import warnings
 
-from .._utils import set_module
+from numpy._utils import set_module
 import numpy._core.numeric as NX
 
 from numpy._core import (isscalar, abs, finfo, atleast_1d, hstack, dot, array,
diff --git a/numpy/lib/_type_check_impl.py b/numpy/lib/_type_check_impl.py
index 7b0c245335a4..671f27adc0d7 100644
--- a/numpy/lib/_type_check_impl.py
+++ b/numpy/lib/_type_check_impl.py
@@ -8,7 +8,7 @@
            'typename', 'mintypecode',
            'common_type']
 
-from .._utils import set_module
+from numpy._utils import set_module
 import numpy._core.numeric as _nx
 from numpy._core.numeric import asarray, asanyarray, isnan, zeros
 from numpy._core import overrides, getlimits
diff --git a/numpy/matrixlib/defmatrix.py b/numpy/matrixlib/defmatrix.py
index 5c9f9616b814..09f10fa3be6d 100644
--- a/numpy/matrixlib/defmatrix.py
+++ b/numpy/matrixlib/defmatrix.py
@@ -4,7 +4,7 @@
 import warnings
 import ast
 
-from .._utils import set_module
+from numpy._utils import set_module
 import numpy._core.numeric as N
 from numpy._core.numeric import concatenate, isscalar
 # While not in __all__, matrix_power used to be defined here, so we import

From 99e52b1ad1e329f097566fd0d5d9940bbc867341 Mon Sep 17 00:00:00 2001
From: Dimitri Papadopoulos Orfanos
 <3234522+DimitriPapadopoulos@users.noreply.github.com>
Date: Thu, 1 May 2025 16:07:55 +0200
Subject: [PATCH 145/202] DOC: numpy.i will not be included as part of SWIG
 (#28874)

https://github.com/swig/swig/issues/361#issuecomment-100635225
---
 tools/swig/README | 4 +---
 1 file changed, 1 insertion(+), 3 deletions(-)

diff --git a/tools/swig/README b/tools/swig/README
index c539c597f8c6..876d6a698034 100644
--- a/tools/swig/README
+++ b/tools/swig/README
@@ -3,9 +3,7 @@ Notes for the numpy/tools/swig directory
 
 This set of files is for developing and testing file numpy.i, which is
 intended to be a set of typemaps for helping SWIG interface between C
-and C++ code that uses C arrays and the python module NumPy.  It is
-ultimately hoped that numpy.i will be included as part of the SWIG
-distribution.
+and C++ code that uses C arrays and the python module NumPy.
 
 Documentation
 -------------

From 75a25670ac53ffac2c32ce29ec40ca2add29b75b Mon Sep 17 00:00:00 2001
From: Dimitri Papadopoulos
 <3234522+DimitriPapadopoulos@users.noreply.github.com>
Date: Thu, 1 May 2025 16:53:40 +0200
Subject: [PATCH 146/202] Revert "STY: Apply ruff/refurb rule FURB113"

This reverts commit a53b45f66255ee378a29d3a255a1de52fb1af522.
---
 numpy/_core/code_generators/generate_umath.py | 18 +++++++++---------
 numpy/lib/tests/test_arraysetops.py           |  8 ++++++--
 numpy/random/tests/test_direct.py             |  3 ++-
 3 files changed, 17 insertions(+), 12 deletions(-)

diff --git a/numpy/_core/code_generators/generate_umath.py b/numpy/_core/code_generators/generate_umath.py
index eb5751df590f..fbda9393b5a5 100644
--- a/numpy/_core/code_generators/generate_umath.py
+++ b/numpy/_core/code_generators/generate_umath.py
@@ -1466,11 +1466,13 @@ def make_arrays(funcdict):
             funcnames = ', '.join(funclist)
             signames = ', '.join(siglist)
             datanames = ', '.join(datalist)
-            code1list.extend((
-                f"static PyUFuncGenericFunction {name}_functions[] = {{{funcnames}}};",
-                f"static void * {name}_data[] = {{{datanames}}};",
-                f"static const char {name}_signatures[] = {{{signames}}};",
-            ))
+            code1list.append(
+                "static PyUFuncGenericFunction %s_functions[] = {%s};"
+                % (name, funcnames))
+            code1list.append("static void * %s_data[] = {%s};"
+                            % (name, datanames))
+            code1list.append("static const char %s_signatures[] = {%s};"
+                            % (name, signames))
             uf.empty = False
         else:
             uf.empty = True
@@ -1571,10 +1573,8 @@ def make_ufuncs(funcdict):
                 funcname=f"{english_upper(chartoname[c])}_{name}_indexed",
             ))
 
-        mlist.extend((
-            f'PyDict_SetItemString(dictionary, "{name}", f);',
-            "Py_DECREF(f);",
-        ))
+        mlist.append(r"""PyDict_SetItemString(dictionary, "%s", f);""" % name)
+        mlist.append(r"""Py_DECREF(f);""")
         code3list.append('\n'.join(mlist))
     return '\n'.join(code3list)
 
diff --git a/numpy/lib/tests/test_arraysetops.py b/numpy/lib/tests/test_arraysetops.py
index b4c4b39aac83..788a4cecdb44 100644
--- a/numpy/lib/tests/test_arraysetops.py
+++ b/numpy/lib/tests/test_arraysetops.py
@@ -688,7 +688,8 @@ def get_types(self):
         types = []
         types.extend(np.typecodes['AllInteger'])
         types.extend(np.typecodes['AllFloat'])
-        types.extend(('datetime64[D]', 'timedelta64[D]'))
+        types.append('datetime64[D]')
+        types.append('timedelta64[D]')
         return types
 
     def test_unique_1d(self):
@@ -870,7 +871,10 @@ def test_unique_axis(self):
         types = []
         types.extend(np.typecodes['AllInteger'])
         types.extend(np.typecodes['AllFloat'])
-        types.extend(('datetime64[D]', 'timedelta64[D]', [('a', int), ('b', int)], [('a', int), ('b', float)]))
+        types.append('datetime64[D]')
+        types.append('timedelta64[D]')
+        types.append([('a', int), ('b', int)])
+        types.append([('a', int), ('b', float)])
 
         for dtype in types:
             self._run_axis_tests(dtype)
diff --git a/numpy/random/tests/test_direct.py b/numpy/random/tests/test_direct.py
index 23da9714ddb8..c8a83f3bc40b 100644
--- a/numpy/random/tests/test_direct.py
+++ b/numpy/random/tests/test_direct.py
@@ -123,7 +123,8 @@ def gauss_from_uint(x, n, bits):
             loc += 2
 
         f = np.sqrt(-2.0 * np.log(r2) / r2)
-        gauss.extend((f * x2, f * x1))
+        gauss.append(f * x2)
+        gauss.append(f * x1)
 
     return gauss[:n]
 

From c60143927c4eb6c1be9bb18c8b0b8f7ffd3e24df Mon Sep 17 00:00:00 2001
From: Dimitri Papadopoulos
 <3234522+DimitriPapadopoulos@users.noreply.github.com>
Date: Thu, 1 May 2025 16:55:32 +0200
Subject: [PATCH 147/202] STY:  add missing blank line

---
 doc/source/reference/simd/gen_features.py | 1 +
 1 file changed, 1 insertion(+)

diff --git a/doc/source/reference/simd/gen_features.py b/doc/source/reference/simd/gen_features.py
index 2d8a2e49cd2f..95af997fd2d0 100644
--- a/doc/source/reference/simd/gen_features.py
+++ b/doc/source/reference/simd/gen_features.py
@@ -3,6 +3,7 @@
 """
 from os import path
 from itertools import starmap
+
 from numpy.distutils.ccompiler_opt import CCompilerOpt
 
 class FakeCCompilerOpt(CCompilerOpt):

From 175287618e93e37b479695526df5fab558adf94c Mon Sep 17 00:00:00 2001
From: Marco Edward Gorelli 
Date: Thu, 1 May 2025 16:04:59 +0100
Subject: [PATCH 148/202] TYP: Type ``MaskedArray.nonzero`` (#28845)

---
 numpy/ma/core.pyi                     | 2 +-
 numpy/typing/tests/data/reveal/ma.pyi | 4 ++++
 2 files changed, 5 insertions(+), 1 deletion(-)

diff --git a/numpy/ma/core.pyi b/numpy/ma/core.pyi
index 73b2a803304c..4bf2924ef566 100644
--- a/numpy/ma/core.pyi
+++ b/numpy/ma/core.pyi
@@ -492,7 +492,7 @@ class MaskedArray(ndarray[_ShapeT_co, _DTypeT_co]):
     def iscontiguous(self) -> bool: ...
     def all(self, axis=..., out=..., keepdims=...): ...
     def any(self, axis=..., out=..., keepdims=...): ...
-    def nonzero(self): ...
+    def nonzero(self) -> tuple[_Array1D[intp], *tuple[_Array1D[intp], ...]]: ...
     def trace(self, offset=..., axis1=..., axis2=..., dtype=..., out=...): ...
     def dot(self, b, out=..., strict=...): ...
     def sum(self, axis=..., dtype=..., out=..., keepdims=...): ...
diff --git a/numpy/typing/tests/data/reveal/ma.pyi b/numpy/typing/tests/data/reveal/ma.pyi
index d59a0a709707..86c097b96a4c 100644
--- a/numpy/typing/tests/data/reveal/ma.pyi
+++ b/numpy/typing/tests/data/reveal/ma.pyi
@@ -7,6 +7,7 @@ from numpy._typing import NDArray, _Shape
 
 _ScalarT = TypeVar("_ScalarT", bound=generic)
 MaskedArray: TypeAlias = np.ma.MaskedArray[_Shape, dtype[_ScalarT]]
+_Array1D: TypeAlias = np.ndarray[tuple[int], np.dtype[_ScalarT]]
 
 class MaskedArraySubclass(MaskedArray[np.complex128]): ...
 
@@ -314,3 +315,6 @@ assert_type(MAR_2d_f4.swapaxes(1, 0), MaskedArray[np.float32])
 assert_type(np.ma.nomask, np.bool[Literal[False]])
 # https://github.com/python/mypy/issues/18974
 assert_type(np.ma.MaskType, type[np.bool])  # type: ignore[assert-type]
+
+assert_type(MAR_2d_f4.nonzero(), tuple[_Array1D[np.intp], *tuple[_Array1D[np.intp], ...]])
+assert_type(MAR_2d_f4.nonzero()[0], _Array1D[np.intp])

From 42205e09851a7b047f209f6c5d610189d5ba523b Mon Sep 17 00:00:00 2001
From: Marco Edward Gorelli 
Date: Thu, 1 May 2025 16:10:04 +0100
Subject: [PATCH 149/202] TYP: Type ``MaskedArray.{imag, real, baseclass, mT}``
 (#28868)

---
 numpy/ma/core.pyi                     | 22 +++++++++++-----------
 numpy/typing/tests/data/reveal/ma.pyi |  8 ++++++++
 2 files changed, 19 insertions(+), 11 deletions(-)

diff --git a/numpy/ma/core.pyi b/numpy/ma/core.pyi
index 4bf2924ef566..006386a03296 100644
--- a/numpy/ma/core.pyi
+++ b/numpy/ma/core.pyi
@@ -2,13 +2,14 @@
 # ruff: noqa: ANN001, ANN002, ANN003, ANN201, ANN202 ANN204, ANN401
 
 from collections.abc import Sequence
-from typing import Any, Literal, SupportsIndex, TypeAlias, TypeVar, overload
+from typing import Any, Literal, Self, SupportsIndex, TypeAlias, TypeVar, overload
 
 from _typeshed import Incomplete
 from typing_extensions import TypeIs, deprecated
 
 import numpy as np
 from numpy import (
+    _HasDTypeWithRealAndImag,
     _ModeKind,
     _OrderKACF,
     _PartitionKind,
@@ -401,10 +402,6 @@ class MaskedArray(ndarray[_ShapeT_co, _DTypeT_co]):
     def __getitem__(self, indx): ...
     def __setitem__(self, indx, value): ...
     @property
-    def dtype(self) -> _DTypeT_co: ...
-    @dtype.setter
-    def dtype(self: MaskedArray[Any, _DTypeT], dtype: _DTypeT, /) -> None: ...
-    @property
     def shape(self) -> _ShapeT_co: ...
     @shape.setter
     def shape(self: MaskedArray[_ShapeT, Any], shape: _ShapeT, /) -> None: ...
@@ -426,7 +423,7 @@ class MaskedArray(ndarray[_ShapeT_co, _DTypeT_co]):
     def sharedmask(self): ...
     def shrink_mask(self): ...
     @property
-    def baseclass(self): ...
+    def baseclass(self) -> type[NDArray[Any]]: ...
     data: Any
     @property
     def flat(self): ...
@@ -468,10 +465,10 @@ class MaskedArray(ndarray[_ShapeT_co, _DTypeT_co]):
     def __itruediv__(self, other): ...
     def __ipow__(self, other): ...
     @property  # type: ignore[misc]
-    def imag(self): ...
+    def imag(self: _HasDTypeWithRealAndImag[object, _ScalarT], /) -> MaskedArray[_ShapeT_co, dtype[_ScalarT]]: ...
     get_imag: Any
     @property  # type: ignore[misc]
-    def real(self): ...
+    def real(self: _HasDTypeWithRealAndImag[_ScalarT, object], /) -> MaskedArray[_ShapeT_co, dtype[_ScalarT]]: ...
     get_real: Any
 
     # keep in sync with `np.ma.count`
@@ -804,9 +801,6 @@ class MaskedArray(ndarray[_ShapeT_co, _DTypeT_co]):
     T: Any
     transpose: Any
 
-    @property  # type: ignore[misc]
-    def mT(self): ...
-
     #
     def toflex(self) -> Incomplete: ...
     def torecords(self) -> Incomplete: ...
@@ -820,6 +814,12 @@ class MaskedArray(ndarray[_ShapeT_co, _DTypeT_co]):
     def __reduce__(self): ...
     def __deepcopy__(self, memo=...): ...
 
+    # Keep `dtype` at the bottom to avoid name conflicts with `np.dtype`
+    @property
+    def dtype(self) -> _DTypeT_co: ...
+    @dtype.setter
+    def dtype(self: MaskedArray[Any, _DTypeT], dtype: _DTypeT, /) -> None: ...
+
 class mvoid(MaskedArray[_ShapeT_co, _DTypeT_co]):
     def __new__(
         self,  # pyright: ignore[reportSelfClsParameterName]
diff --git a/numpy/typing/tests/data/reveal/ma.pyi b/numpy/typing/tests/data/reveal/ma.pyi
index 86c097b96a4c..79bfe7f86744 100644
--- a/numpy/typing/tests/data/reveal/ma.pyi
+++ b/numpy/typing/tests/data/reveal/ma.pyi
@@ -17,6 +17,7 @@ AR_dt64: NDArray[np.datetime64]
 AR_td64: NDArray[np.timedelta64]
 AR_o: NDArray[np.timedelta64]
 
+MAR_c16: MaskedArray[np.complex128]
 MAR_b: MaskedArray[np.bool]
 MAR_f4: MaskedArray[np.float32]
 MAR_f8: MaskedArray[np.float64]
@@ -309,6 +310,13 @@ def func(x: object) -> None:
     else:
         assert_type(x, object)
 
+assert_type(MAR_2d_f4.mT, np.ma.MaskedArray[tuple[int, int], np.dtype[np.float32]])
+
+assert_type(MAR_c16.real, MaskedArray[np.float64])
+assert_type(MAR_c16.imag, MaskedArray[np.float64])
+
+assert_type(MAR_2d_f4.baseclass, type[NDArray[Any]])
+
 assert_type(MAR_b.swapaxes(0, 1), MaskedArray[np.bool])
 assert_type(MAR_2d_f4.swapaxes(1, 0), MaskedArray[np.float32])
 

From 7e1bc0838a16ee9d031ca870149c748e01df4bd2 Mon Sep 17 00:00:00 2001
From: Dimitri Papadopoulos
 <3234522+DimitriPapadopoulos@users.noreply.github.com>
Date: Thu, 1 May 2025 17:28:52 +0200
Subject: [PATCH 150/202] MNT: address warnign in SWIG tests
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit

Array2.cxx:163:25: warning: ‘*’ in boolean context, suggest ‘&&’ instead [-Wint-in-bool-context]
  163 |   if (_ownData && _nrows*_ncols && _buffer)
      |                   ~~~~~~^~~~~~~
---
 tools/swig/test/Array2.cxx | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/tools/swig/test/Array2.cxx b/tools/swig/test/Array2.cxx
index 2da61f728569..11b523523617 100644
--- a/tools/swig/test/Array2.cxx
+++ b/tools/swig/test/Array2.cxx
@@ -160,7 +160,7 @@ void Array2::allocateRows()
 
 void Array2::deallocateMemory()
 {
-  if (_ownData && _nrows*_ncols && _buffer)
+  if (_ownData && _nrows && _ncols && _buffer)
   {
     delete [] _rows;
     delete [] _buffer;

From a7a79f3f6b9fa1fb6c6c5c3415e9551af1a10106 Mon Sep 17 00:00:00 2001
From: Dimitri Papadopoulos
 <3234522+DimitriPapadopoulos@users.noreply.github.com>
Date: Thu, 1 May 2025 17:44:38 +0200
Subject: [PATCH 151/202] Revert "STY: Apply ruff/refurb rule FURB140"

This reverts commit f1b77fae7d74e609d7c25adc814c41df3cea5679.
---
 benchmarks/benchmarks/bench_ufunc.py      | 4 ++--
 doc/source/reference/simd/gen_features.py | 3 +--
 numpy/_core/code_generators/genapi.py     | 3 +--
 numpy/_core/tests/test_cython.py          | 4 ++--
 numpy/_core/tests/test_mem_overlap.py     | 9 +++++----
 numpy/_core/tests/test_scalarmath.py      | 4 ++--
 numpy/_core/tests/test_simd.py            | 8 ++++----
 numpy/_core/tests/test_strings.py         | 7 +++----
 numpy/_core/tests/test_umath.py           | 4 ++--
 numpy/lib/_arrayterator_impl.py           | 6 +++---
 numpy/lib/_function_base_impl.py          | 3 +--
 numpy/lib/_iotools.py                     | 2 +-
 numpy/lib/tests/test_arrayterator.py      | 3 +--
 numpy/ma/extras.py                        | 5 +++--
 14 files changed, 31 insertions(+), 34 deletions(-)

diff --git a/benchmarks/benchmarks/bench_ufunc.py b/benchmarks/benchmarks/bench_ufunc.py
index 810555fec73b..4d9f3c9c8f61 100644
--- a/benchmarks/benchmarks/bench_ufunc.py
+++ b/benchmarks/benchmarks/bench_ufunc.py
@@ -61,7 +61,7 @@ def setup(self, ufuncname):
             self.args.append(arg)
 
     def time_afdn_types(self, ufuncname):
-        list(itertools.starmap(self.afdn, self.args))
+        [self.afdn(*arg) for arg in self.args]
 
 
 class Broadcast(Benchmark):
@@ -108,7 +108,7 @@ def setup(self, ufuncname):
             self.args.append(arg)
 
     def time_ufunc_types(self, ufuncname):
-        list(itertools.starmap(self.ufn, self.args))
+        [self.ufn(*arg) for arg in self.args]
 
 
 class MethodsV0(Benchmark):
diff --git a/doc/source/reference/simd/gen_features.py b/doc/source/reference/simd/gen_features.py
index 95af997fd2d0..eb516e3ff2ac 100644
--- a/doc/source/reference/simd/gen_features.py
+++ b/doc/source/reference/simd/gen_features.py
@@ -2,7 +2,6 @@
 Generate CPU features tables from CCompilerOpt
 """
 from os import path
-from itertools import starmap
 
 from numpy.distutils.ccompiler_opt import CCompilerOpt
 
@@ -124,7 +123,7 @@ def gen_rst_table(self, field_names, rows, tab_size=4):
         cformat = ' '.join('{:<%d}' % i for i in cls_len)
         border = cformat.format(*['=' * i for i in cls_len])
 
-        rows = list(starmap(cformat.format, rows))
+        rows = [cformat.format(*row) for row in rows]
         # header
         rows = [border, cformat.format(*field_names), border] + rows
         # footer
diff --git a/numpy/_core/code_generators/genapi.py b/numpy/_core/code_generators/genapi.py
index 3045149b3405..9b51904a2d7d 100644
--- a/numpy/_core/code_generators/genapi.py
+++ b/numpy/_core/code_generators/genapi.py
@@ -15,7 +15,6 @@
 import textwrap
 
 from os.path import join
-from itertools import starmap
 
 
 def get_processor():
@@ -153,7 +152,7 @@ def _format_arg(self, typename, name):
             return typename + ' ' + name
 
     def __str__(self):
-        argstr = ', '.join(list(starmap(self._format_arg, self.args)))
+        argstr = ', '.join([self._format_arg(*a) for a in self.args])
         if self.doc:
             doccomment = f'/* {self.doc} */\n'
         else:
diff --git a/numpy/_core/tests/test_cython.py b/numpy/_core/tests/test_cython.py
index 3fd45582c5eb..81ddc63258c2 100644
--- a/numpy/_core/tests/test_cython.py
+++ b/numpy/_core/tests/test_cython.py
@@ -3,7 +3,6 @@
 import subprocess
 import sys
 import pytest
-from itertools import starmap
 
 import numpy as np
 from numpy.testing import assert_array_equal, IS_WASM, IS_EDITABLE
@@ -279,7 +278,8 @@ def test_npyiter_api(install_temp):
         x is y for x, y in zip(checks.get_npyiter_operands(it), it.operands)
     )
     assert all(
-        starmap(np.allclose, zip(checks.get_npyiter_itviews(it), it.itviews))
+        np.allclose(x, y)
+        for x, y in zip(checks.get_npyiter_itviews(it), it.itviews)
     )
 
 
diff --git a/numpy/_core/tests/test_mem_overlap.py b/numpy/_core/tests/test_mem_overlap.py
index 9317d87358f3..0d80951a854a 100644
--- a/numpy/_core/tests/test_mem_overlap.py
+++ b/numpy/_core/tests/test_mem_overlap.py
@@ -281,7 +281,7 @@ def random_slice_fixed_size(n, step, size):
         steps = tuple(rng.randint(1, 11, dtype=np.intp)
                       if rng.randint(0, 5, dtype=np.intp) == 0 else 1
                       for j in range(x.ndim))
-        s1 = tuple(itertools.starmap(random_slice, zip(x.shape, steps)))
+        s1 = tuple(random_slice(p, s) for p, s in zip(x.shape, steps))
 
         t1 = np.arange(x.ndim)
         rng.shuffle(t1)
@@ -301,7 +301,8 @@ def random_slice_fixed_size(n, step, size):
             steps2 = tuple(rng.randint(1, max(2, p // (1 + pa)))
                            if rng.randint(0, 5) == 0 else 1
                            for p, s, pa in zip(x.shape, s1, a.shape))
-            s2 = tuple(itertools.starmap(random_slice_fixed_size, zip(x.shape, steps2, a.shape)))
+            s2 = tuple(random_slice_fixed_size(p, s, pa)
+                       for p, s, pa in zip(x.shape, steps2, a.shape))
         elif same_steps:
             steps2 = steps
         else:
@@ -310,7 +311,7 @@ def random_slice_fixed_size(n, step, size):
                            for j in range(x.ndim))
 
         if not equal_size:
-            s2 = tuple(itertools.starmap(random_slice, zip(x.shape, steps2)))
+            s2 = tuple(random_slice(p, s) for p, s in zip(x.shape, steps2))
 
         a = a.transpose(t1)
         b = x[s2].transpose(t2)
@@ -441,7 +442,7 @@ def random_slice(n, step):
                       for j in range(x.ndim))
         t1 = np.arange(x.ndim)
         rng.shuffle(t1)
-        s1 = tuple(itertools.starmap(random_slice, zip(x.shape, steps)))
+        s1 = tuple(random_slice(p, s) for p, s in zip(x.shape, steps))
         a = x[s1].transpose(t1)
 
         assert_(not internal_overlap(a))
diff --git a/numpy/_core/tests/test_scalarmath.py b/numpy/_core/tests/test_scalarmath.py
index ad671c94c78b..0b086df21c60 100644
--- a/numpy/_core/tests/test_scalarmath.py
+++ b/numpy/_core/tests/test_scalarmath.py
@@ -314,7 +314,7 @@ def test_float_modulus_exact(self):
         dividend = nlst + [0] + plst
         divisor = nlst + plst
         arg = list(itertools.product(dividend, divisor))
-        tgt = list(itertools.starmap(divmod, arg))
+        tgt = [divmod(*t) for t in arg]
 
         a, b = np.array(arg, dtype=int).T
         # convert exact integer results from Python to float so that
@@ -329,7 +329,7 @@ def test_float_modulus_exact(self):
                 fa = a.astype(dt)
                 fb = b.astype(dt)
                 # use list comprehension so a_ and b_ are scalars
-                div, rem = zip(*list(itertools.starmap(op, zip(fa, fb))))
+                div, rem = zip(*[op(a_, b_) for a_, b_ in zip(fa, fb)])
                 assert_equal(div, tgtdiv, err_msg=msg)
                 assert_equal(rem, tgtrem, err_msg=msg)
 
diff --git a/numpy/_core/tests/test_simd.py b/numpy/_core/tests/test_simd.py
index 385b2cc6c0bf..fdcab688963e 100644
--- a/numpy/_core/tests/test_simd.py
+++ b/numpy/_core/tests/test_simd.py
@@ -302,11 +302,11 @@ def test_math_max_min(self):
         data_b = self._data(self.nlanes)
         vdata_a, vdata_b = self.load(data_a), self.load(data_b)
 
-        data_max = list(itertools.starmap(max, zip(data_a, data_b)))
+        data_max = [max(a, b) for a, b in zip(data_a, data_b)]
         simd_max = self.max(vdata_a, vdata_b)
         assert simd_max == data_max
 
-        data_min = list(itertools.starmap(min, zip(data_a, data_b)))
+        data_min = [min(a, b) for a, b in zip(data_a, data_b)]
         simd_min = self.min(vdata_a, vdata_b)
         assert simd_min == data_min
 
@@ -613,7 +613,7 @@ def to_bool(vector):
             vdata_a = self.setall(case_operand1)
             vdata_b = self.setall(case_operand2)
             vcmp = to_bool(intrin(vdata_a, vdata_b))
-            data_cmp = list(itertools.starmap(py_comp, zip(data_a, data_b)))
+            data_cmp = [py_comp(a, b) for a, b in zip(data_a, data_b)]
             assert vcmp == data_cmp
 
     @pytest.mark.parametrize("intrin", ["any", "all"])
@@ -1036,7 +1036,7 @@ def test_operators_comparison(self, func, intrin):
         def to_bool(vector):
             return [lane == mask_true for lane in vector]
 
-        data_cmp = list(itertools.starmap(func, zip(data_a, data_b)))
+        data_cmp = [func(a, b) for a, b in zip(data_a, data_b)]
         cmp = to_bool(intrin(vdata_a, vdata_b))
         assert cmp == data_cmp
 
diff --git a/numpy/_core/tests/test_strings.py b/numpy/_core/tests/test_strings.py
index 7ea94eafa7da..7960142162c5 100644
--- a/numpy/_core/tests/test_strings.py
+++ b/numpy/_core/tests/test_strings.py
@@ -1,10 +1,9 @@
 import sys
-import operator
-from itertools import starmap
-
 import pytest
 
+import operator
 import numpy as np
+
 from numpy.testing import assert_array_equal, assert_raises, IS_PYPY
 from numpy.testing._private.utils import requires_memory
 
@@ -66,7 +65,7 @@ def test_string_comparisons(op, ufunc, sym, dtypes, aligned):
     np.random.shuffle(arr2)
     arr[0] = arr2[0]  # make sure one matches
 
-    expected = list(starmap(op, zip(arr.tolist(), arr2.tolist())))
+    expected = [op(d1, d2) for d1, d2 in zip(arr.tolist(), arr2.tolist())]
     assert_array_equal(op(arr, arr2), expected)
     assert_array_equal(ufunc(arr, arr2), expected)
     assert_array_equal(
diff --git a/numpy/_core/tests/test_umath.py b/numpy/_core/tests/test_umath.py
index 0078c2a9d54b..22ad1b8ac302 100644
--- a/numpy/_core/tests/test_umath.py
+++ b/numpy/_core/tests/test_umath.py
@@ -508,7 +508,7 @@ def test_division_int_boundary(self, dtype, ex_val):
             ac = a.copy()
             ac //= b
             div_ab = a // b
-        div_lst = list(itertools.starmap(c_div, zip(a_lst, b_lst)))
+        div_lst = [c_div(x, y) for x, y in zip(a_lst, b_lst)]
 
         msg = "Integer arrays floor division check (//)"
         assert all(div_ab == div_lst), msg
@@ -740,7 +740,7 @@ def test_float_remainder_exact(self):
         dividend = nlst + [0] + plst
         divisor = nlst + plst
         arg = list(itertools.product(dividend, divisor))
-        tgt = list(itertools.starmap(divmod, arg))
+        tgt = [divmod(*t) for t in arg]
 
         a, b = np.array(arg, dtype=int).T
         # convert exact integer results from Python to float so that
diff --git a/numpy/lib/_arrayterator_impl.py b/numpy/lib/_arrayterator_impl.py
index 9aa7bcc0690c..5bb1630a9300 100644
--- a/numpy/lib/_arrayterator_impl.py
+++ b/numpy/lib/_arrayterator_impl.py
@@ -9,7 +9,6 @@
 """
 from operator import mul
 from functools import reduce
-from itertools import starmap
 
 __all__ = ['Arrayterator']
 
@@ -134,7 +133,8 @@ def __array__(self, dtype=None, copy=None):
         Return corresponding data.
 
         """
-        slice_ = tuple(starmap(slice, zip(self.start, self.stop, self.step)))
+        slice_ = tuple(slice(*t) for t in zip(
+                self.start, self.stop, self.step))
         return self.var[slice_]
 
     @property
@@ -210,7 +210,7 @@ def __iter__(self):
                 count = count // self.shape[i]
 
             # yield a block
-            slice_ = tuple(starmap(slice, zip(start, stop, step)))
+            slice_ = tuple(slice(*t) for t in zip(start, stop, step))
             yield self.var[slice_]
 
             # Update start position, taking care of overflow to
diff --git a/numpy/lib/_function_base_impl.py b/numpy/lib/_function_base_impl.py
index b5bf32398339..e44b27a68adb 100644
--- a/numpy/lib/_function_base_impl.py
+++ b/numpy/lib/_function_base_impl.py
@@ -4,7 +4,6 @@
 import re
 import sys
 import warnings
-from itertools import starmap
 
 import numpy as np
 import numpy._core.numeric as _nx
@@ -1972,7 +1971,7 @@ def trim_zeros(filt, trim='fb', axis=None):
         sl = slice(start[0], stop[0])
     elif axis is None:
         # trim all axes
-        sl = tuple(starmap(slice, zip(start, stop)))
+        sl = tuple(slice(*x) for x in zip(start, stop))
     else:
         # only trim single axis
         axis = normalize_axis_index(axis, filt_.ndim)
diff --git a/numpy/lib/_iotools.py b/numpy/lib/_iotools.py
index 5a2372ef75f7..56ee65d38575 100644
--- a/numpy/lib/_iotools.py
+++ b/numpy/lib/_iotools.py
@@ -181,7 +181,7 @@ def __init__(self, delimiter=None, comments='#', autostrip=True,
         elif hasattr(delimiter, '__iter__'):
             _handyman = self._variablewidth_splitter
             idx = np.cumsum([0] + list(delimiter))
-            delimiter = list(itertools.starmap(slice, itertools.pairwise(idx)))
+            delimiter = [slice(i, j) for (i, j) in itertools.pairwise(idx)]
         # Delimiter is a single integer
         elif int(delimiter):
             (_handyman, delimiter) = (
diff --git a/numpy/lib/tests/test_arrayterator.py b/numpy/lib/tests/test_arrayterator.py
index 675cc513ab54..e64d1d1e3ece 100644
--- a/numpy/lib/tests/test_arrayterator.py
+++ b/numpy/lib/tests/test_arrayterator.py
@@ -1,6 +1,5 @@
 from operator import mul
 from functools import reduce
-from itertools import starmap
 
 import numpy as np
 from numpy.random import randint
@@ -32,7 +31,7 @@ def test():
     start = [randint(dim) for dim in shape]
     stop = [randint(dim) + 1 for dim in shape]
     step = [randint(dim) + 1 for dim in shape]
-    slice_ = tuple(starmap(slice, zip(start, stop, step)))
+    slice_ = tuple(slice(*t) for t in zip(start, stop, step))
     c = b[slice_]
     d = a[slice_]
 
diff --git a/numpy/ma/extras.py b/numpy/ma/extras.py
index ef1b6904ae39..22151b95e27d 100644
--- a/numpy/ma/extras.py
+++ b/numpy/ma/extras.py
@@ -2183,12 +2183,13 @@ def _ezclump(mask):
             return [slice(0, mask.size)]
 
         r = [slice(0, idx[0])]
-        r.extend(itertools.starmap(slice, zip(idx[1:-1:2], idx[2::2])))
+        r.extend((slice(left, right)
+                  for left, right in zip(idx[1:-1:2], idx[2::2])))
     else:
         if len(idx) == 0:
             return []
 
-        r = list(itertools.starmap(slice, zip(idx[:-1:2], idx[1::2])))
+        r = [slice(left, right) for left, right in zip(idx[:-1:2], idx[1::2])]
 
     if mask[-1]:
         r.append(slice(idx[-1], mask.size))

From d69a9e5b1e31642a930d944b7895dbc94ffd133a Mon Sep 17 00:00:00 2001
From: jorenham 
Date: Thu, 1 May 2025 20:29:05 +0200
Subject: [PATCH 152/202] DEP: deprecate ``numpy.typing.NBitBase``

---
 numpy/_typing/__init__.py    |  2 +-
 numpy/_typing/_nbit_base.py  |  7 ++++++-
 numpy/_typing/_nbit_base.pyi | 40 ++++++++++++++++++++++++++++++++++++
 numpy/typing/__init__.py     | 37 +++++++++++++++++++++++++++------
 4 files changed, 78 insertions(+), 8 deletions(-)
 create mode 100644 numpy/_typing/_nbit_base.pyi

diff --git a/numpy/_typing/__init__.py b/numpy/_typing/__init__.py
index 92cdcec84900..097e59390691 100644
--- a/numpy/_typing/__init__.py
+++ b/numpy/_typing/__init__.py
@@ -6,7 +6,7 @@
     _NestedSequence as _NestedSequence,
 )
 from ._nbit_base import (
-    NBitBase as NBitBase,
+    NBitBase as NBitBase,  # pyright: ignore[reportDeprecated]
     _8Bit as _8Bit,
     _16Bit as _16Bit,
     _32Bit as _32Bit,
diff --git a/numpy/_typing/_nbit_base.py b/numpy/_typing/_nbit_base.py
index bf16c436c6da..df2fb64e4040 100644
--- a/numpy/_typing/_nbit_base.py
+++ b/numpy/_typing/_nbit_base.py
@@ -9,13 +9,17 @@ class NBitBase:
     """
     A type representing `numpy.number` precision during static type checking.
 
-    Used exclusively for the purpose static type checking, `NBitBase`
+    Used exclusively for the purpose of static type checking, `NBitBase`
     represents the base of a hierarchical set of subclasses.
     Each subsequent subclass is herein used for representing a lower level
     of precision, *e.g.* ``64Bit > 32Bit > 16Bit``.
 
     .. versionadded:: 1.20
 
+    .. deprecated:: 2.3
+        Use ``@typing.overload`` or a ``TypeVar`` with a scalar-type as upper
+        bound, instead.
+
     Examples
     --------
     Below is a typical usage example: `NBitBase` is herein used for annotating
@@ -48,6 +52,7 @@ class NBitBase:
         ...     # note:     out: numpy.floating[numpy.typing._64Bit*]
 
     """
+    # Deprecated in NumPy 2.3, 2025-05-01
 
     def __init_subclass__(cls) -> None:
         allowed_names = {
diff --git a/numpy/_typing/_nbit_base.pyi b/numpy/_typing/_nbit_base.pyi
new file mode 100644
index 000000000000..ccf8f5ceac45
--- /dev/null
+++ b/numpy/_typing/_nbit_base.pyi
@@ -0,0 +1,40 @@
+# pyright: reportDeprecated=false
+# pyright: reportGeneralTypeIssues=false
+# mypy: disable-error-code=misc
+
+from typing import final
+
+from typing_extensions import deprecated
+
+# Deprecated in NumPy 2.3, 2025-05-01
+@deprecated(
+    "`NBitBase` is deprecated and will be removed from numpy.typing in the "
+    "future. Use `@typing.overload` or a `TypeVar` with a scalar-type as upper "
+    "bound, instead. (deprecated in NumPy 2.3)",
+)
+@final
+class NBitBase: ...
+
+@final
+class _256Bit(NBitBase): ...
+
+@final
+class _128Bit(_256Bit): ...
+
+@final
+class _96Bit(_128Bit): ...
+
+@final
+class _80Bit(_96Bit): ...
+
+@final
+class _64Bit(_80Bit): ...
+
+@final
+class _32Bit(_64Bit): ...
+
+@final
+class _16Bit(_32Bit): ...
+
+@final
+class _8Bit(_16Bit): ...
diff --git a/numpy/typing/__init__.py b/numpy/typing/__init__.py
index 8a4a974a9928..2c75c348667e 100644
--- a/numpy/typing/__init__.py
+++ b/numpy/typing/__init__.py
@@ -155,15 +155,40 @@
 # NOTE: The API section will be appended with additional entries
 # further down in this file
 
-from numpy._typing import (
-    ArrayLike,
-    DTypeLike,
-    NBitBase,
-    NDArray,
-)
+# pyright: reportDeprecated=false
+
+from numpy._typing import ArrayLike, DTypeLike, NBitBase, NDArray
 
 __all__ = ["ArrayLike", "DTypeLike", "NBitBase", "NDArray"]
 
+
+__DIR = __all__ + [k for k in globals() if k.startswith("__") and k.endswith("__")]
+__DIR_SET = frozenset(__DIR)
+
+
+def __dir__() -> list[str]:
+    return __DIR
+
+def __getattr__(name: str):
+    if name == "NBitBase":
+        import warnings
+
+        # Deprecated in NumPy 2.3, 2025-05-01
+        warnings.warn(
+            "`NBitBase` is deprecated and will be removed from numpy.typing in the "
+            "future. Use `@typing.overload` or a `TypeVar` with a scalar-type as upper "
+            "bound, instead. (deprecated in NumPy 2.3)",
+            DeprecationWarning,
+            stacklevel=2,
+        )
+        return NBitBase
+
+    if name in __DIR_SET:
+        return globals()[name]
+
+    raise AttributeError(f"module {__name__!r} has no attribute {name!r}")
+
+
 if __doc__ is not None:
     from numpy._typing._add_docstring import _docstrings
     __doc__ += _docstrings

From 72fcaa926f84cd9015af010bebf25efc2fbcef54 Mon Sep 17 00:00:00 2001
From: jorenham 
Date: Thu, 1 May 2025 20:53:14 +0200
Subject: [PATCH 153/202] DOC: add release note for the
 ``numpy.typing.NBitBase`` deprecation

---
 .../upcoming_changes/28884.deprecation.rst    | 28 +++++++++++++++++++
 1 file changed, 28 insertions(+)
 create mode 100644 doc/release/upcoming_changes/28884.deprecation.rst

diff --git a/doc/release/upcoming_changes/28884.deprecation.rst b/doc/release/upcoming_changes/28884.deprecation.rst
new file mode 100644
index 000000000000..c1be55fb0dd3
--- /dev/null
+++ b/doc/release/upcoming_changes/28884.deprecation.rst
@@ -0,0 +1,28 @@
+``numpy.typing.NBitBase`` deprecation
+-------------------------------------
+The ``numpy.typing.NBitBase`` type has been deprecated and will be removed in a future version.
+
+This type was previously intended to be used as a generic upper bound for type-parameters, for example:
+
+.. code-block:: python
+
+    import numpy as np
+    import numpy.typing as npt
+
+    def f[NT: npt.NBitBase](x: np.complexfloating[NT]) -> np.floating[NT]: ...
+
+But in NumPy 2.2.0, ``float64`` and ``complex128`` were changed to concrete subtypes, causing static type-checkers to reject ``x: np.float64 = f(np.complex128(42j))``.
+
+So instead, the better approach is to use ``typing.overload``:
+
+.. code-block:: python
+
+    import numpy as np
+    from typing import overload
+
+    @overload
+    def f(x: np.complex64) -> np.float32: ...
+    @overload
+    def f(x: np.complex128) -> np.float64: ...
+    @overload
+    def f(x: np.clongdouble) -> np.longdouble: ...

From dfb77e7615a09dec6d2dcef6c5e63c6844cad800 Mon Sep 17 00:00:00 2001
From: Warrick Ball 
Date: Fri, 2 May 2025 12:25:20 +0100
Subject: [PATCH 154/202] DOC: math mode x to \times in docstring for
 numpy.linalg.multi_dot

---
 numpy/linalg/_linalg.py | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/numpy/linalg/_linalg.py b/numpy/linalg/_linalg.py
index 1301f1cb7e9a..f2d7e14fdf28 100644
--- a/numpy/linalg/_linalg.py
+++ b/numpy/linalg/_linalg.py
@@ -2903,7 +2903,7 @@ def cost(A, B):
             return A.shape[0] * A.shape[1] * B.shape[1]
 
     Assume we have three matrices
-    :math:`A_{10x100}, B_{100x5}, C_{5x50}`.
+    :math:`A_{10 \times 100}, B_{100 \times 5}, C_{5 \times 50}`.
 
     The costs for the two different parenthesizations are as follows::
 

From aa7c4f5d59ee2b478eae9c7fa8759d59a8365c2d Mon Sep 17 00:00:00 2001
From: Nathan Goldbaum 
Date: Fri, 2 May 2025 08:42:22 -0600
Subject: [PATCH 155/202] MAINT: from_dlpack thread safety fixes (#28883)

Fixes #28881

Moves the global variables defined in from_dlpack to the npy_static_pydata struct and initializes them during module init.
---
 numpy/_core/src/multiarray/dlpack.c          | 31 +++-----------------
 numpy/_core/src/multiarray/npy_static_data.c | 16 ++++++++++
 numpy/_core/src/multiarray/npy_static_data.h |  7 +++++
 3 files changed, 27 insertions(+), 27 deletions(-)

diff --git a/numpy/_core/src/multiarray/dlpack.c b/numpy/_core/src/multiarray/dlpack.c
index 4bea7f9fc1ab..ac37a04c30c6 100644
--- a/numpy/_core/src/multiarray/dlpack.c
+++ b/numpy/_core/src/multiarray/dlpack.c
@@ -504,36 +504,12 @@ from_dlpack(PyObject *NPY_UNUSED(self),
         return NULL;
     }
 
-    /* Prepare the arguments to call objects __dlpack__() method */
-    static PyObject *call_kwnames = NULL;
-    static PyObject *dl_cpu_device_tuple = NULL;
-    static PyObject *max_version = NULL;
-
-    if (call_kwnames == NULL) {
-        call_kwnames = Py_BuildValue("(sss)", "dl_device", "copy", "max_version");
-        if (call_kwnames == NULL) {
-            return NULL;
-        }
-    }
-    if (dl_cpu_device_tuple == NULL) {
-        dl_cpu_device_tuple = Py_BuildValue("(i,i)", 1, 0);
-        if (dl_cpu_device_tuple == NULL) {
-            return NULL;
-        }
-    }
-    if (max_version == NULL) {
-        max_version = Py_BuildValue("(i,i)", 1, 0);
-        if (max_version == NULL) {
-            return NULL;
-        }
-    }
-
     /* 
      * Prepare arguments for the full call. We always forward copy and pass
      * our max_version. `device` is always passed as `None`, but if the user
      * provided a device, we will replace it with the "cpu": (1, 0).
      */
-    PyObject *call_args[] = {obj, Py_None, copy, max_version};
+    PyObject *call_args[] = {obj, Py_None, copy, npy_static_pydata.dl_max_version};
     Py_ssize_t nargsf = 1 | PY_VECTORCALL_ARGUMENTS_OFFSET;
 
     /* If device is passed it must be "cpu" and replace it with (1, 0) */
@@ -544,12 +520,13 @@ from_dlpack(PyObject *NPY_UNUSED(self),
             return NULL;
         }
         assert(device_request == NPY_DEVICE_CPU);
-        call_args[1] = dl_cpu_device_tuple;
+        call_args[1] = npy_static_pydata.dl_cpu_device_tuple;
     }
 
 
     PyObject *capsule = PyObject_VectorcallMethod(
-            npy_interned_str.__dlpack__, call_args, nargsf, call_kwnames);
+            npy_interned_str.__dlpack__, call_args, nargsf,
+            npy_static_pydata.dl_call_kwnames);
     if (capsule == NULL) {
         /*
          * TODO: This path should be deprecated in NumPy 2.1.  Once deprecated
diff --git a/numpy/_core/src/multiarray/npy_static_data.c b/numpy/_core/src/multiarray/npy_static_data.c
index 2cc6ea72c26e..62e1fd3c1b15 100644
--- a/numpy/_core/src/multiarray/npy_static_data.c
+++ b/numpy/_core/src/multiarray/npy_static_data.c
@@ -184,6 +184,22 @@ initialize_static_globals(void)
         return -1;
     }
 
+    npy_static_pydata.dl_call_kwnames =
+            Py_BuildValue("(sss)", "dl_device", "copy", "max_version");
+    if (npy_static_pydata.dl_call_kwnames == NULL) {
+        return -1;
+    }
+
+    npy_static_pydata.dl_cpu_device_tuple = Py_BuildValue("(i,i)", 1, 0);
+    if (npy_static_pydata.dl_cpu_device_tuple == NULL) {
+        return -1;
+    }
+
+    npy_static_pydata.dl_max_version = Py_BuildValue("(i,i)", 1, 0);
+    if (npy_static_pydata.dl_max_version == NULL) {
+        return -1;
+    }
+
     /*
      * Initialize contents of npy_static_cdata struct
      *
diff --git a/numpy/_core/src/multiarray/npy_static_data.h b/numpy/_core/src/multiarray/npy_static_data.h
index d6ee4a8dc54d..287dc80e4c1f 100644
--- a/numpy/_core/src/multiarray/npy_static_data.h
+++ b/numpy/_core/src/multiarray/npy_static_data.h
@@ -138,6 +138,13 @@ typedef struct npy_static_pydata_struct {
     PyObject *GenericToVoidMethod;
     PyObject *ObjectToGenericMethod;
     PyObject *GenericToObjectMethod;
+
+    /*
+     * Used in from_dlpack
+     */
+    PyObject *dl_call_kwnames;
+    PyObject *dl_cpu_device_tuple;
+    PyObject *dl_max_version;
 } npy_static_pydata_struct;
 
 

From c9e66d0e36f0a47c3066ac3c57b112a6804cb711 Mon Sep 17 00:00:00 2001
From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com>
Date: Fri, 2 May 2025 18:02:23 +0000
Subject: [PATCH 156/202] MAINT: Bump github/codeql-action from 3.28.16 to
 3.28.17

Bumps [github/codeql-action](https://github.com/github/codeql-action) from 3.28.16 to 3.28.17.
- [Release notes](https://github.com/github/codeql-action/releases)
- [Changelog](https://github.com/github/codeql-action/blob/main/CHANGELOG.md)
- [Commits](https://github.com/github/codeql-action/compare/28deaeda66b76a05916b6923827895f2b14ab387...60168efe1c415ce0f5521ea06d5c2062adbeed1b)

---
updated-dependencies:
- dependency-name: github/codeql-action
  dependency-version: 3.28.17
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] 
---
 .github/workflows/codeql.yml     | 6 +++---
 .github/workflows/scorecards.yml | 2 +-
 2 files changed, 4 insertions(+), 4 deletions(-)

diff --git a/.github/workflows/codeql.yml b/.github/workflows/codeql.yml
index 68e75754346a..68ef1e811e88 100644
--- a/.github/workflows/codeql.yml
+++ b/.github/workflows/codeql.yml
@@ -47,7 +47,7 @@ jobs:
 
       # Initializes the CodeQL tools for scanning.
       - name: Initialize CodeQL
-        uses: github/codeql-action/init@28deaeda66b76a05916b6923827895f2b14ab387 # v3.28.16
+        uses: github/codeql-action/init@60168efe1c415ce0f5521ea06d5c2062adbeed1b # v3.28.17
         with:
           languages: ${{ matrix.language }}
           # If you wish to specify custom queries, you can do so here or in a config file.
@@ -57,7 +57,7 @@ jobs:
       # Autobuild attempts to build any compiled languages  (C/C++, C#, or Java).
       # If this step fails, then you should remove it and run the build manually (see below)
       - name: Autobuild
-        uses: github/codeql-action/autobuild@28deaeda66b76a05916b6923827895f2b14ab387 # v3.28.16
+        uses: github/codeql-action/autobuild@60168efe1c415ce0f5521ea06d5c2062adbeed1b # v3.28.17
 
       # ℹ️ Command-line programs to run using the OS shell.
       # 📚 See https://docs.github.com/en/actions/using-workflows/workflow-syntax-for-github-actions#jobsjob_idstepsrun
@@ -70,6 +70,6 @@ jobs:
       #   ./location_of_script_within_repo/buildscript.sh
 
       - name: Perform CodeQL Analysis
-        uses: github/codeql-action/analyze@28deaeda66b76a05916b6923827895f2b14ab387 # v3.28.16
+        uses: github/codeql-action/analyze@60168efe1c415ce0f5521ea06d5c2062adbeed1b # v3.28.17
         with:
           category: "/language:${{matrix.language}}"
diff --git a/.github/workflows/scorecards.yml b/.github/workflows/scorecards.yml
index c2b15262ea41..360261b6a186 100644
--- a/.github/workflows/scorecards.yml
+++ b/.github/workflows/scorecards.yml
@@ -50,6 +50,6 @@ jobs:
 
       # Upload the results to GitHub's code scanning dashboard.
       - name: "Upload to code-scanning"
-        uses: github/codeql-action/upload-sarif@28deaeda66b76a05916b6923827895f2b14ab387 # v2.1.27
+        uses: github/codeql-action/upload-sarif@60168efe1c415ce0f5521ea06d5c2062adbeed1b # v2.1.27
         with:
           sarif_file: results.sarif

From cd0756a354a526d2382d35f7ff93c43787bcf948 Mon Sep 17 00:00:00 2001
From: Marco Edward Gorelli 
Date: Sat, 3 May 2025 10:10:50 +0100
Subject: [PATCH 157/202] TYP: Type ``MaskedArray.all`` and ``MaskedArray.any``
 (#28880)

---
 numpy/ma/core.pyi                     | 93 ++++++++++++++++++++++++++-
 numpy/typing/tests/data/fail/ma.pyi   |  8 +++
 numpy/typing/tests/data/reveal/ma.pyi | 22 +++++++
 3 files changed, 121 insertions(+), 2 deletions(-)

diff --git a/numpy/ma/core.pyi b/numpy/ma/core.pyi
index 71a05d05a940..f3fc825124e1 100644
--- a/numpy/ma/core.pyi
+++ b/numpy/ma/core.pyi
@@ -487,8 +487,97 @@ class MaskedArray(ndarray[_ShapeT_co, _DTypeT_co]):
     def put(self, indices: _ArrayLikeInt_co, values: ArrayLike, mode: _ModeKind = "raise") -> None: ...
     def ids(self) -> tuple[int, int]: ...
     def iscontiguous(self) -> bool: ...
-    def all(self, axis=..., out=..., keepdims=...): ...
-    def any(self, axis=..., out=..., keepdims=...): ...
+
+    @overload
+    def all(
+        self,
+        axis: None = None,
+        out: None = None,
+        keepdims: Literal[False] | _NoValueType = ...,
+    ) -> bool_: ...
+    @overload
+    def all(
+        self,
+        axis: _ShapeLike | None = None,
+        out: None = None,
+        *,
+        keepdims: Literal[True],
+    ) -> _MaskedArray[bool_]: ...
+    @overload
+    def all(
+        self,
+        axis: _ShapeLike | None,
+        out: None,
+        keepdims: Literal[True],
+    ) -> _MaskedArray[bool_]: ...
+    @overload
+    def all(
+        self,
+        axis: _ShapeLike | None = None,
+        out: None = None,
+        keepdims: bool | _NoValueType = ...,
+    ) -> bool_ | _MaskedArray[bool_]: ...
+    @overload
+    def all(
+        self,
+        axis: _ShapeLike | None = None,
+        *,
+        out: _ArrayT,
+        keepdims: bool | _NoValueType = ...,
+    ) -> _ArrayT: ...
+    @overload
+    def all(
+        self,
+        axis: _ShapeLike | None,
+        out: _ArrayT,
+        keepdims: bool | _NoValueType = ...,
+    ) -> _ArrayT: ...
+
+    @overload
+    def any(
+        self,
+        axis: None = None,
+        out: None = None,
+        keepdims: Literal[False] | _NoValueType = ...,
+    ) -> bool_: ...
+    @overload
+    def any(
+        self,
+        axis: _ShapeLike | None = None,
+        out: None = None,
+        *,
+        keepdims: Literal[True],
+    ) -> _MaskedArray[bool_]: ...
+    @overload
+    def any(
+        self,
+        axis: _ShapeLike | None,
+        out: None,
+        keepdims: Literal[True],
+    ) -> _MaskedArray[bool_]: ...
+    @overload
+    def any(
+        self,
+        axis: _ShapeLike | None = None,
+        out: None = None,
+        keepdims: bool | _NoValueType = ...,
+    ) -> bool_ | _MaskedArray[bool_]: ...
+    @overload
+    def any(
+        self,
+        axis: _ShapeLike | None = None,
+        *,
+        out: _ArrayT,
+        keepdims: bool | _NoValueType = ...,
+    ) -> _ArrayT: ...
+    @overload
+    def any(
+        self,
+        axis: _ShapeLike | None,
+        out: _ArrayT,
+        keepdims: bool | _NoValueType = ...,
+    ) -> _ArrayT: ...
+
     def nonzero(self) -> tuple[_Array1D[intp], *tuple[_Array1D[intp], ...]]: ...
     def trace(self, offset=..., axis1=..., axis2=..., dtype=..., out=...): ...
     def dot(self, b, out=..., strict=...): ...
diff --git a/numpy/typing/tests/data/fail/ma.pyi b/numpy/typing/tests/data/fail/ma.pyi
index d79008b60d25..78f98e918c43 100644
--- a/numpy/typing/tests/data/fail/ma.pyi
+++ b/numpy/typing/tests/data/fail/ma.pyi
@@ -63,6 +63,14 @@ np.ma.argmax(m, keepdims=1.0)  # E: No overload variant
 np.ma.argmax(m, out=1.0)  # E: No overload variant
 np.ma.argmax(m, fill_value=lambda x: 27)  # E: No overload variant
 
+m.all(axis=1.0)  # E: No overload variant
+m.all(keepdims=1.0)  # E: No overload variant
+m.all(out=1.0)  # E: No overload variant
+
+m.any(axis=1.0)  # E: No overload variant
+m.any(keepdims=1.0)  # E: No overload variant
+m.any(out=1.0)  # E: No overload variant
+
 m.sort(axis=(0,1))  # E: No overload variant
 m.sort(axis=None)  # E: No overload variant
 m.sort(kind='cabbage')  # E: No overload variant
diff --git a/numpy/typing/tests/data/reveal/ma.pyi b/numpy/typing/tests/data/reveal/ma.pyi
index 79bfe7f86744..39245fddf780 100644
--- a/numpy/typing/tests/data/reveal/ma.pyi
+++ b/numpy/typing/tests/data/reveal/ma.pyi
@@ -141,6 +141,28 @@ assert_type(np.ma.argmax(MAR_b, keepdims=True), Any)
 assert_type(np.ma.argmax(MAR_f4, out=MAR_subclass), MaskedArraySubclass)
 assert_type(np.ma.argmax(MAR_f4, None, None, out=MAR_subclass), MaskedArraySubclass)
 
+assert_type(MAR_b.all(), np.bool)
+assert_type(MAR_f4.all(), np.bool)
+assert_type(MAR_f4.all(keepdims=False), np.bool)
+assert_type(MAR_b.all(axis=0), np.bool | MaskedArray[np.bool])
+assert_type(MAR_b.all(axis=0, keepdims=True), MaskedArray[np.bool])
+assert_type(MAR_b.all(0, None, True), MaskedArray[np.bool])
+assert_type(MAR_f4.all(axis=0), np.bool | MaskedArray[np.bool])
+assert_type(MAR_b.all(keepdims=True), MaskedArray[np.bool])
+assert_type(MAR_f4.all(out=MAR_subclass), MaskedArraySubclass)
+assert_type(MAR_f4.all(None, out=MAR_subclass), MaskedArraySubclass)
+
+assert_type(MAR_b.any(), np.bool)
+assert_type(MAR_f4.any(), np.bool)
+assert_type(MAR_f4.any(keepdims=False), np.bool)
+assert_type(MAR_b.any(axis=0), np.bool | MaskedArray[np.bool])
+assert_type(MAR_b.any(axis=0, keepdims=True), MaskedArray[np.bool])
+assert_type(MAR_b.any(0, None, True), MaskedArray[np.bool])
+assert_type(MAR_f4.any(axis=0), np.bool | MaskedArray[np.bool])
+assert_type(MAR_b.any(keepdims=True), MaskedArray[np.bool])
+assert_type(MAR_f4.any(out=MAR_subclass), MaskedArraySubclass)
+assert_type(MAR_f4.any(None, out=MAR_subclass), MaskedArraySubclass)
+
 assert_type(MAR_f4.sort(), None)
 assert_type(MAR_f4.sort(axis=0, kind='quicksort', order='K', endwith=False, fill_value=42., stable=False), None)
 

From 09489205b68b6187dc3e36324d13607fc3c6dcb1 Mon Sep 17 00:00:00 2001
From: jorenham 
Date: Sat, 3 May 2025 13:39:18 +0200
Subject: [PATCH 158/202] TYP: remove non-existent extended-precision scalar
 types

ported from numpy/numtype#209
---
 numpy/__init__.pyi                            | 16 ++----------
 numpy/_core/numerictypes.pyi                  | 23 +----------------
 numpy/_typing/__init__.py                     |  2 --
 numpy/_typing/_extended_precision.py          | 15 +----------
 numpy/_typing/_nbit_base.py                   | 25 ++++++-------------
 numpy/typing/mypy_plugin.py                   | 11 +-------
 .../tests/data/misc/extended_precision.pyi    | 13 +---------
 numpy/typing/tests/test_typing.py             | 16 +++---------
 8 files changed, 17 insertions(+), 104 deletions(-)

diff --git a/numpy/__init__.pyi b/numpy/__init__.pyi
index 5f176e519a24..b309c355d164 100644
--- a/numpy/__init__.pyi
+++ b/numpy/__init__.pyi
@@ -57,10 +57,8 @@ from numpy._typing import (
     NBitBase,
     # NOTE: Do not remove the extended precision bit-types even if seemingly unused;
     # they're used by the mypy plugin
-    _256Bit,
     _128Bit,
     _96Bit,
-    _80Bit,
     _64Bit,
     _32Bit,
     _16Bit,
@@ -160,21 +158,12 @@ from numpy._typing._callable import (
     _ComparisonOpGE,
 )
 
-# NOTE: Numpy's mypy plugin is used for removing the types unavailable
-# to the specific platform
+# NOTE: Numpy's mypy plugin is used for removing the types unavailable to the specific platform
 from numpy._typing._extended_precision import (
-    uint128,
-    uint256,
-    int128,
-    int256,
-    float80,
     float96,
     float128,
-    float256,
-    complex160,
     complex192,
     complex256,
-    complex512,
 )
 
 from numpy._array_api_info import __array_namespace_info__
@@ -698,8 +687,7 @@ __all__ = [  # noqa: RUF022
     "uint8", "ubyte", "int16", "short", "uint16", "ushort", "int32", "intc", "uint32",
     "uintc", "int64", "long", "uint64", "ulong", "longlong", "ulonglong", "intp",
     "uintp", "double", "cdouble", "single", "csingle", "half", "bool_", "int_", "uint",
-    "uint128", "uint256", "int128", "int256", "float80", "float96", "float128",
-    "float256", "complex160", "complex192", "complex256", "complex512",
+    "float96", "float128", "complex192", "complex256",
     "array2string", "array_str", "array_repr", "set_printoptions", "get_printoptions",
     "printoptions", "format_float_positional", "format_float_scientific", "require",
     "seterr", "geterr", "setbufsize", "getbufsize", "seterrcall", "geterrcall",
diff --git a/numpy/_core/numerictypes.pyi b/numpy/_core/numerictypes.pyi
index f04d11303ad5..3b6b0c63713a 100644
--- a/numpy/_core/numerictypes.pyi
+++ b/numpy/_core/numerictypes.pyi
@@ -68,20 +68,7 @@ from .multiarray import (
 )
 
 from numpy._typing import DTypeLike
-from numpy._typing._extended_precision import (
-    uint128,
-    uint256,
-    int128,
-    int256,
-    float80,
-    float96,
-    float128,
-    float256,
-    complex160,
-    complex192,
-    complex256,
-    complex512,
-)
+from numpy._typing._extended_precision import float96, float128, complex192, complex256
 
 __all__ = [
     "ScalarType",
@@ -146,18 +133,10 @@ __all__ = [
     "bool_",
     "int_",
     "uint",
-    "uint128",
-    "uint256",
-    "int128",
-    "int256",
-    "float80",
     "float96",
     "float128",
-    "float256",
-    "complex160",
     "complex192",
     "complex256",
-    "complex512",
 ]
 
 @type_check_only
diff --git a/numpy/_typing/__init__.py b/numpy/_typing/__init__.py
index 92cdcec84900..ad271748c747 100644
--- a/numpy/_typing/__init__.py
+++ b/numpy/_typing/__init__.py
@@ -11,10 +11,8 @@
     _16Bit as _16Bit,
     _32Bit as _32Bit,
     _64Bit as _64Bit,
-    _80Bit as _80Bit,
     _96Bit as _96Bit,
     _128Bit as _128Bit,
-    _256Bit as _256Bit,
 )
 from ._nbit import (
     _NBitByte as _NBitByte,
diff --git a/numpy/_typing/_extended_precision.py b/numpy/_typing/_extended_precision.py
index 7246b47d0ee1..73a1847ccbeb 100644
--- a/numpy/_typing/_extended_precision.py
+++ b/numpy/_typing/_extended_precision.py
@@ -6,22 +6,9 @@
 """
 
 import numpy as np
-from . import (
-    _80Bit,
-    _96Bit,
-    _128Bit,
-    _256Bit,
-)
+from . import _96Bit, _128Bit
 
-uint128 = np.unsignedinteger[_128Bit]
-uint256 = np.unsignedinteger[_256Bit]
-int128 = np.signedinteger[_128Bit]
-int256 = np.signedinteger[_256Bit]
-float80 = np.floating[_80Bit]
 float96 = np.floating[_96Bit]
 float128 = np.floating[_128Bit]
-float256 = np.floating[_256Bit]
-complex160 = np.complexfloating[_80Bit, _80Bit]
 complex192 = np.complexfloating[_96Bit, _96Bit]
 complex256 = np.complexfloating[_128Bit, _128Bit]
-complex512 = np.complexfloating[_256Bit, _256Bit]
diff --git a/numpy/_typing/_nbit_base.py b/numpy/_typing/_nbit_base.py
index bf16c436c6da..0380cfd2b2de 100644
--- a/numpy/_typing/_nbit_base.py
+++ b/numpy/_typing/_nbit_base.py
@@ -51,8 +51,7 @@ class NBitBase:
 
     def __init_subclass__(cls) -> None:
         allowed_names = {
-            "NBitBase", "_256Bit", "_128Bit", "_96Bit", "_80Bit",
-            "_64Bit", "_32Bit", "_16Bit", "_8Bit",
+            "NBitBase", "_128Bit", "_96Bit", "_64Bit", "_32Bit", "_16Bit", "_8Bit"
         }
         if cls.__name__ not in allowed_names:
             raise TypeError('cannot inherit from final class "NBitBase"')
@@ -61,40 +60,30 @@ def __init_subclass__(cls) -> None:
 @final
 @set_module("numpy._typing")
 # Silence errors about subclassing a `@final`-decorated class
-class _256Bit(NBitBase):  # type: ignore[misc]
+class _128Bit(NBitBase):  # type: ignore[misc]  # pyright: ignore[reportGeneralTypeIssues]
     pass
 
 @final
 @set_module("numpy._typing")
-class _128Bit(_256Bit):  # type: ignore[misc]
+class _96Bit(_128Bit):  # type: ignore[misc]  # pyright: ignore[reportGeneralTypeIssues]
     pass
 
 @final
 @set_module("numpy._typing")
-class _96Bit(_128Bit):  # type: ignore[misc]
+class _64Bit(_96Bit):  # type: ignore[misc]  # pyright: ignore[reportGeneralTypeIssues]
     pass
 
 @final
 @set_module("numpy._typing")
-class _80Bit(_96Bit):  # type: ignore[misc]
+class _32Bit(_64Bit):  # type: ignore[misc]  # pyright: ignore[reportGeneralTypeIssues]
     pass
 
 @final
 @set_module("numpy._typing")
-class _64Bit(_80Bit):  # type: ignore[misc]
+class _16Bit(_32Bit):  # type: ignore[misc]  # pyright: ignore[reportGeneralTypeIssues]
     pass
 
 @final
 @set_module("numpy._typing")
-class _32Bit(_64Bit):  # type: ignore[misc]
-    pass
-
-@final
-@set_module("numpy._typing")
-class _16Bit(_32Bit):  # type: ignore[misc]
-    pass
-
-@final
-@set_module("numpy._typing")
-class _8Bit(_16Bit):  # type: ignore[misc]
+class _8Bit(_16Bit):  # type: ignore[misc]  # pyright: ignore[reportGeneralTypeIssues]
     pass
diff --git a/numpy/typing/mypy_plugin.py b/numpy/typing/mypy_plugin.py
index 81ccf0b64fc1..5c01f261bb79 100644
--- a/numpy/typing/mypy_plugin.py
+++ b/numpy/typing/mypy_plugin.py
@@ -65,18 +65,10 @@ def _get_precision_dict() -> dict[str, str]:
 
 def _get_extended_precision_list() -> list[str]:
     extended_names = [
-        "uint128",
-        "uint256",
-        "int128",
-        "int256",
-        "float80",
         "float96",
         "float128",
-        "float256",
-        "complex160",
         "complex192",
         "complex256",
-        "complex512",
     ]
     return [i for i in extended_names if hasattr(np, i)]
 
@@ -169,8 +161,7 @@ def get_additional_deps(
             """Handle all import-based overrides.
 
             * Import platform-specific extended-precision `numpy.number`
-              subclasses (*e.g.* `numpy.float96`, `numpy.float128` and
-              `numpy.complex256`).
+              subclasses (*e.g.* `numpy.float96` and `numpy.float128`).
             * Import the appropriate `ctypes` equivalent to `numpy.intp`.
 
             """
diff --git a/numpy/typing/tests/data/misc/extended_precision.pyi b/numpy/typing/tests/data/misc/extended_precision.pyi
index 02dfcec6a8e2..84b5f516bdde 100644
--- a/numpy/typing/tests/data/misc/extended_precision.pyi
+++ b/numpy/typing/tests/data/misc/extended_precision.pyi
@@ -1,20 +1,9 @@
 import numpy as np
-from numpy._typing import _80Bit, _96Bit, _128Bit, _256Bit
+from numpy._typing import _96Bit, _128Bit
 
 from typing import assert_type
 
-assert_type(np.uint128(), np.unsignedinteger[_128Bit])
-assert_type(np.uint256(), np.unsignedinteger[_256Bit])
-
-assert_type(np.int128(), np.signedinteger[_128Bit])
-assert_type(np.int256(), np.signedinteger[_256Bit])
-
-assert_type(np.float80(), np.floating[_80Bit])
 assert_type(np.float96(), np.floating[_96Bit])
 assert_type(np.float128(), np.floating[_128Bit])
-assert_type(np.float256(), np.floating[_256Bit])
-
-assert_type(np.complex160(), np.complexfloating[_80Bit, _80Bit])
 assert_type(np.complex192(), np.complexfloating[_96Bit, _96Bit])
 assert_type(np.complex256(), np.complexfloating[_128Bit, _128Bit])
-assert_type(np.complex512(), np.complexfloating[_256Bit, _256Bit])
diff --git a/numpy/typing/tests/test_typing.py b/numpy/typing/tests/test_typing.py
index c1e708c876e5..068b27a7709f 100644
--- a/numpy/typing/tests/test_typing.py
+++ b/numpy/typing/tests/test_typing.py
@@ -249,18 +249,10 @@ def test_code_runs(path: str) -> None:
 
 
 LINENO_MAPPING = {
-    6: "uint128",
-    7: "uint256",
-    9: "int128",
-    10: "int256",
-    12: "float80",
-    13: "float96",
-    14: "float128",
-    15: "float256",
-    17: "complex160",
-    18: "complex192",
-    19: "complex256",
-    20: "complex512",
+    6: "float96",
+    7: "float128",
+    8: "complex192",
+    9: "complex256",
 }
 
 

From 111154abf7ce734fbb57bbe970938a5f4b44f487 Mon Sep 17 00:00:00 2001
From: Marco Edward Gorelli 
Date: Sat, 3 May 2025 12:45:08 +0100
Subject: [PATCH 159/202] TYP: Type
 ``MaskedArray.{__setmask__,mask,harden_mask,soften_mask,hardmask,unshare_mask,sharedmask,shrink_mask}``
 (#28867)

---
 numpy/ma/core.py                      |  3 ++-
 numpy/ma/core.pyi                     | 18 +++++++++---------
 numpy/typing/tests/data/fail/ma.pyi   |  2 ++
 numpy/typing/tests/data/pass/ma.py    |  6 +++++-
 numpy/typing/tests/data/reveal/ma.pyi | 14 ++++++++++++++
 5 files changed, 32 insertions(+), 11 deletions(-)

diff --git a/numpy/ma/core.py b/numpy/ma/core.py
index add0ad9770d7..bbd64bd76007 100644
--- a/numpy/ma/core.py
+++ b/numpy/ma/core.py
@@ -3737,7 +3737,8 @@ def shrink_mask(self):
 
         Returns
         -------
-        None
+        result : MaskedArray
+            A :class:`~ma.MaskedArray` object.
 
         Examples
         --------
diff --git a/numpy/ma/core.pyi b/numpy/ma/core.pyi
index f3fc825124e1..dc2a472a18d3 100644
--- a/numpy/ma/core.pyi
+++ b/numpy/ma/core.pyi
@@ -405,23 +405,23 @@ class MaskedArray(ndarray[_ShapeT_co, _DTypeT_co]):
     def shape(self) -> _ShapeT_co: ...
     @shape.setter
     def shape(self: MaskedArray[_ShapeT, Any], shape: _ShapeT, /) -> None: ...
-    def __setmask__(self, mask, copy=...): ...
+    def __setmask__(self, mask: _ArrayLikeBool_co, copy: bool = False) -> None: ...
     @property
-    def mask(self): ...
+    def mask(self) -> NDArray[MaskType] | MaskType: ...
     @mask.setter
-    def mask(self, value): ...
+    def mask(self, value: _ArrayLikeBool_co, /) -> None: ...
     @property
     def recordmask(self): ...
     @recordmask.setter
     def recordmask(self, mask): ...
-    def harden_mask(self): ...
-    def soften_mask(self): ...
+    def harden_mask(self) -> Self: ...
+    def soften_mask(self) -> Self: ...
     @property
-    def hardmask(self): ...
-    def unshare_mask(self): ...
+    def hardmask(self) -> bool: ...
+    def unshare_mask(self) -> Self: ...
     @property
-    def sharedmask(self): ...
-    def shrink_mask(self): ...
+    def sharedmask(self) -> bool: ...
+    def shrink_mask(self) -> Self: ...
     @property
     def baseclass(self) -> type[NDArray[Any]]: ...
     data: Any
diff --git a/numpy/typing/tests/data/fail/ma.pyi b/numpy/typing/tests/data/fail/ma.pyi
index 78f98e918c43..e93be464de10 100644
--- a/numpy/typing/tests/data/fail/ma.pyi
+++ b/numpy/typing/tests/data/fail/ma.pyi
@@ -131,4 +131,6 @@ np.ma.allclose(m, [1,2,3], masked_equal=4.5)  # E: No overload variant
 np.ma.allclose(m, [1,2,3], rtol='.4')  # E: No overload variant
 np.ma.allclose(m, [1,2,3], atol='.5')  # E: No overload variant
 
+m.__setmask__('mask')  # E: No overload variant
+
 m.swapaxes(axis1=1, axis2=0)  # E: No overload variant
diff --git a/numpy/typing/tests/data/pass/ma.py b/numpy/typing/tests/data/pass/ma.py
index 7a4e9909e334..abd1a0103005 100644
--- a/numpy/typing/tests/data/pass/ma.py
+++ b/numpy/typing/tests/data/pass/ma.py
@@ -2,7 +2,11 @@
 
 import numpy as np
 import numpy.ma
+import numpy.typing as npt
 
-
+ar_b: npt.NDArray[np.bool] = np.array([True, False, True])
 m: np.ma.MaskedArray[Any, np.dtype[np.float64]] = np.ma.masked_array([1.5, 2, 3], mask=[True, False, True])
 
+m.mask = ar_b
+m.mask = np.False_
+
diff --git a/numpy/typing/tests/data/reveal/ma.pyi b/numpy/typing/tests/data/reveal/ma.pyi
index 39245fddf780..8c22a4ea5e44 100644
--- a/numpy/typing/tests/data/reveal/ma.pyi
+++ b/numpy/typing/tests/data/reveal/ma.pyi
@@ -289,6 +289,7 @@ assert_type(np.ma.put(MAR_f4, 4, 999), None)
 assert_type(np.ma.put(MAR_f4, 4, 999, mode='clip'), None)
 
 assert_type(np.ma.putmask(MAR_f4, [True, False], [0, 1]), None)
+assert_type(np.ma.putmask(MAR_f4, np.False_, [0, 1]), None)
 
 assert_type(MAR_f4.filled(float('nan')), NDArray[np.float32])
 assert_type(MAR_i8.filled(), NDArray[np.int64])
@@ -346,5 +347,18 @@ assert_type(np.ma.nomask, np.bool[Literal[False]])
 # https://github.com/python/mypy/issues/18974
 assert_type(np.ma.MaskType, type[np.bool])  # type: ignore[assert-type]
 
+assert_type(MAR_1d.__setmask__([True, False]), None)
+assert_type(MAR_1d.__setmask__(np.False_), None)
+
+assert_type(MAR_2d_f4.harden_mask(), np.ma.MaskedArray[tuple[int, int], np.dtype[np.float32]])
+assert_type(MAR_i8.harden_mask(), MaskedArray[np.int64])
+assert_type(MAR_2d_f4.soften_mask(), np.ma.MaskedArray[tuple[int, int], np.dtype[np.float32]])
+assert_type(MAR_i8.soften_mask(), MaskedArray[np.int64])
+assert_type(MAR_f4.unshare_mask(), MaskedArray[np.float32])
+assert_type(MAR_b.shrink_mask(), MaskedArray[np.bool_])
+
+assert_type(MAR_i8.hardmask, bool)
+assert_type(MAR_i8.sharedmask, bool)
+
 assert_type(MAR_2d_f4.nonzero(), tuple[_Array1D[np.intp], *tuple[_Array1D[np.intp], ...]])
 assert_type(MAR_2d_f4.nonzero()[0], _Array1D[np.intp])

From 682e95457d66e230aef27d5dfd83addfd52db1c5 Mon Sep 17 00:00:00 2001
From: Ralf Gommers 
Date: Mon, 5 May 2025 12:39:30 +0200
Subject: [PATCH 160/202] BLD: update vendored Meson to include iOS fix

This is PR 21 from https://github.com/numpy/meson
---
 vendored-meson/meson | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/vendored-meson/meson b/vendored-meson/meson
index 23ec306e6510..f754c4258805 160000
--- a/vendored-meson/meson
+++ b/vendored-meson/meson
@@ -1 +1 @@
-Subproject commit 23ec306e65107f5ad39a03709799dc90ea678a54
+Subproject commit f754c4258805056ed7be09830d96af45215d341b

From 01f5c86f298d863e0bd555e923ac77cf1446d50e Mon Sep 17 00:00:00 2001
From: Marco Gorelli <33491632+MarcoGorelli@users.noreply.github.com>
Date: Mon, 5 May 2025 16:42:20 +0100
Subject: [PATCH 161/202] TYP: Test ``MaskedArray.transpose`` and
 ``MaskedArray.T``, remove unnecessary annotations

---
 numpy/ma/core.pyi                     | 3 ---
 numpy/typing/tests/data/reveal/ma.pyi | 7 +++++++
 2 files changed, 7 insertions(+), 3 deletions(-)

diff --git a/numpy/ma/core.pyi b/numpy/ma/core.pyi
index dc2a472a18d3..055f25fe0557 100644
--- a/numpy/ma/core.pyi
+++ b/numpy/ma/core.pyi
@@ -887,9 +887,6 @@ class MaskedArray(ndarray[_ShapeT_co, _DTypeT_co]):
         /
     ) -> MaskedArray[_Shape, _DTypeT_co]: ...
 
-    T: Any
-    transpose: Any
-
     #
     def toflex(self) -> Incomplete: ...
     def torecords(self) -> Incomplete: ...
diff --git a/numpy/typing/tests/data/reveal/ma.pyi b/numpy/typing/tests/data/reveal/ma.pyi
index 8c22a4ea5e44..e80426efc03e 100644
--- a/numpy/typing/tests/data/reveal/ma.pyi
+++ b/numpy/typing/tests/data/reveal/ma.pyi
@@ -360,5 +360,12 @@ assert_type(MAR_b.shrink_mask(), MaskedArray[np.bool_])
 assert_type(MAR_i8.hardmask, bool)
 assert_type(MAR_i8.sharedmask, bool)
 
+assert_type(MAR_b.transpose(), MaskedArray[np.bool])
+assert_type(MAR_2d_f4.transpose(), np.ma.MaskedArray[tuple[int, int], np.dtype[np.float32]])
+assert_type(MAR_2d_f4.transpose(1, 0), np.ma.MaskedArray[tuple[int, int], np.dtype[np.float32]])
+assert_type(MAR_2d_f4.transpose((1, 0)), np.ma.MaskedArray[tuple[int, int], np.dtype[np.float32]])
+assert_type(MAR_b.T, MaskedArray[np.bool])
+assert_type(MAR_2d_f4.T, np.ma.MaskedArray[tuple[int, int], np.dtype[np.float32]])
+
 assert_type(MAR_2d_f4.nonzero(), tuple[_Array1D[np.intp], *tuple[_Array1D[np.intp], ...]])
 assert_type(MAR_2d_f4.nonzero()[0], _Array1D[np.intp])

From 4ce6579e8865884e95e50766f6ac395559affc0a Mon Sep 17 00:00:00 2001
From: Marco Gorelli <33491632+MarcoGorelli@users.noreply.github.com>
Date: Tue, 6 May 2025 09:07:10 +0100
Subject: [PATCH 162/202] TYP: Fix non-existent ``CanIndex`` annotation in
 ``ndarray.setfield``

---
 numpy/__init__.pyi                          | 2 +-
 numpy/typing/tests/data/fail/array_like.pyi | 2 ++
 2 files changed, 3 insertions(+), 1 deletion(-)

diff --git a/numpy/__init__.pyi b/numpy/__init__.pyi
index b309c355d164..540cf188a967 100644
--- a/numpy/__init__.pyi
+++ b/numpy/__init__.pyi
@@ -2542,7 +2542,7 @@ class ndarray(_ArrayOrScalarCommon, Generic[_ShapeT_co, _DTypeT_co]):
     @overload  # (dtype: ?, type: type[T])
     def view(self, /, dtype: DTypeLike, type: type[_ArrayT]) -> _ArrayT: ...
 
-    def setfield(self, /, val: ArrayLike, dtype: DTypeLike, offset: CanIndex = 0) -> None: ...
+    def setfield(self, /, val: ArrayLike, dtype: DTypeLike, offset: SupportsIndex = 0) -> None: ...
     @overload
     def getfield(self, dtype: _DTypeLike[_ScalarT], offset: SupportsIndex = 0) -> NDArray[_ScalarT]: ...
     @overload
diff --git a/numpy/typing/tests/data/fail/array_like.pyi b/numpy/typing/tests/data/fail/array_like.pyi
index 53f0c1ec85e9..6b6c16dd6e70 100644
--- a/numpy/typing/tests/data/fail/array_like.pyi
+++ b/numpy/typing/tests/data/fail/array_like.pyi
@@ -11,3 +11,5 @@ scalar = np.int64(1)
 scalar.__array__(dtype=np.float64)  # E: No overload variant
 array = np.array([1])
 array.__array__(dtype=np.float64)  # E: No overload variant
+
+array.setfield(np.eye(1), np.int32, (0, 1))  # E: No overload variant

From 3077b211f501d3fb0035efa788fa2b967eb878d3 Mon Sep 17 00:00:00 2001
From: jorenham 
Date: Tue, 6 May 2025 15:53:51 +0200
Subject: [PATCH 163/202] TYP: add a ``float64`` overload to ``np.*space``

---
 numpy/_core/function_base.pyi                 | 48 +++++++++++++++++++
 .../tests/data/reveal/array_constructors.pyi  |  8 ++--
 2 files changed, 52 insertions(+), 4 deletions(-)

diff --git a/numpy/_core/function_base.pyi b/numpy/_core/function_base.pyi
index 3d0a80c23e6a..d019803abc6a 100644
--- a/numpy/_core/function_base.pyi
+++ b/numpy/_core/function_base.pyi
@@ -1,11 +1,13 @@
 from typing import (
     Literal as L,
+    TypeAlias,
     overload,
     Any,
     SupportsIndex,
     TypeVar,
 )
 
+import numpy as np
 from numpy import floating, complexfloating, generic
 from numpy._typing import (
     NDArray,
@@ -14,11 +16,26 @@ from numpy._typing import (
     _ArrayLikeFloat_co,
     _ArrayLikeComplex_co,
 )
+from numpy._typing._array_like import _DualArrayLike
 
 __all__ = ["logspace", "linspace", "geomspace"]
 
 _ScalarT = TypeVar("_ScalarT", bound=generic)
 
+_ToArrayFloat64: TypeAlias = _DualArrayLike[np.dtype[np.float64 | np.integer | np.bool], float]
+
+@overload
+def linspace(
+    start: _ToArrayFloat64,
+    stop: _ToArrayFloat64,
+    num: SupportsIndex = ...,
+    endpoint: bool = ...,
+    retstep: L[False] = ...,
+    dtype: None = ...,
+    axis: SupportsIndex = ...,
+    *,
+    device: L["cpu"] | None = ...,
+) -> NDArray[np.float64]: ...
 @overload
 def linspace(
     start: _ArrayLikeFloat_co,
@@ -80,6 +97,18 @@ def linspace(
     device: L["cpu"] | None = ...,
 ) -> NDArray[Any]: ...
 @overload
+def linspace(
+    start: _ToArrayFloat64,
+    stop: _ToArrayFloat64,
+    num: SupportsIndex = ...,
+    endpoint: bool = ...,
+    *,
+    retstep: L[True],
+    dtype: None = ...,
+    axis: SupportsIndex = ...,
+    device: L["cpu"] | None = ...,
+) -> tuple[NDArray[np.float64], np.float64]: ...
+@overload
 def linspace(
     start: _ArrayLikeFloat_co,
     stop: _ArrayLikeFloat_co,
@@ -128,6 +157,16 @@ def linspace(
     device: L["cpu"] | None = ...,
 ) -> tuple[NDArray[Any], Any]: ...
 
+@overload
+def logspace(
+    start: _ToArrayFloat64,
+    stop: _ToArrayFloat64,
+    num: SupportsIndex = ...,
+    endpoint: bool = ...,
+    base: _ToArrayFloat64 = ...,
+    dtype: None = ...,
+    axis: SupportsIndex = ...,
+) -> NDArray[np.float64]: ...
 @overload
 def logspace(
     start: _ArrayLikeFloat_co,
@@ -180,6 +219,15 @@ def logspace(
     axis: SupportsIndex = ...,
 ) -> NDArray[Any]: ...
 
+@overload
+def geomspace(
+    start: _ToArrayFloat64,
+    stop: _ToArrayFloat64,
+    num: SupportsIndex = ...,
+    endpoint: bool = ...,
+    dtype: None = ...,
+    axis: SupportsIndex = ...,
+) -> NDArray[np.float64]: ...
 @overload
 def geomspace(
     start: _ArrayLikeFloat_co,
diff --git a/numpy/typing/tests/data/reveal/array_constructors.pyi b/numpy/typing/tests/data/reveal/array_constructors.pyi
index 07610d982751..2f32579c0816 100644
--- a/numpy/typing/tests/data/reveal/array_constructors.pyi
+++ b/numpy/typing/tests/data/reveal/array_constructors.pyi
@@ -132,21 +132,21 @@ assert_type(np.require(B, requirements="W"), SubClass[np.float64])
 assert_type(np.require(B, requirements="A"), SubClass[np.float64])
 assert_type(np.require(C), npt.NDArray[Any])
 
-assert_type(np.linspace(0, 10), npt.NDArray[np.floating])
+assert_type(np.linspace(0, 10), npt.NDArray[np.float64])
 assert_type(np.linspace(0, 10j), npt.NDArray[np.complexfloating])
 assert_type(np.linspace(0, 10, dtype=np.int64), npt.NDArray[np.int64])
 assert_type(np.linspace(0, 10, dtype=int), npt.NDArray[Any])
-assert_type(np.linspace(0, 10, retstep=True), tuple[npt.NDArray[np.floating], np.floating])
+assert_type(np.linspace(0, 10, retstep=True), tuple[npt.NDArray[np.float64], np.float64])
 assert_type(np.linspace(0j, 10, retstep=True), tuple[npt.NDArray[np.complexfloating], np.complexfloating])
 assert_type(np.linspace(0, 10, retstep=True, dtype=np.int64), tuple[npt.NDArray[np.int64], np.int64])
 assert_type(np.linspace(0j, 10, retstep=True, dtype=int), tuple[npt.NDArray[Any], Any])
 
-assert_type(np.logspace(0, 10), npt.NDArray[np.floating])
+assert_type(np.logspace(0, 10), npt.NDArray[np.float64])
 assert_type(np.logspace(0, 10j), npt.NDArray[np.complexfloating])
 assert_type(np.logspace(0, 10, dtype=np.int64), npt.NDArray[np.int64])
 assert_type(np.logspace(0, 10, dtype=int), npt.NDArray[Any])
 
-assert_type(np.geomspace(0, 10), npt.NDArray[np.floating])
+assert_type(np.geomspace(0, 10), npt.NDArray[np.float64])
 assert_type(np.geomspace(0, 10j), npt.NDArray[np.complexfloating])
 assert_type(np.geomspace(0, 10, dtype=np.int64), npt.NDArray[np.int64])
 assert_type(np.geomspace(0, 10, dtype=int), npt.NDArray[Any])

From 980758d22cbbba55e73b8939e50eda61e41ea7d5 Mon Sep 17 00:00:00 2001
From: jorenham 
Date: Tue, 6 May 2025 15:57:56 +0200
Subject: [PATCH 164/202] TYP: fill in the function param defaults in
 ``_core.function_base``

---
 numpy/_core/function_base.pyi | 202 +++++++++++++++++-----------------
 1 file changed, 101 insertions(+), 101 deletions(-)

diff --git a/numpy/_core/function_base.pyi b/numpy/_core/function_base.pyi
index d019803abc6a..34af79177f97 100644
--- a/numpy/_core/function_base.pyi
+++ b/numpy/_core/function_base.pyi
@@ -28,37 +28,37 @@ _ToArrayFloat64: TypeAlias = _DualArrayLike[np.dtype[np.float64 | np.integer | n
 def linspace(
     start: _ToArrayFloat64,
     stop: _ToArrayFloat64,
-    num: SupportsIndex = ...,
-    endpoint: bool = ...,
-    retstep: L[False] = ...,
-    dtype: None = ...,
-    axis: SupportsIndex = ...,
+    num: SupportsIndex = 50,
+    endpoint: bool = True,
+    retstep: L[False] = False,
+    dtype: None = None,
+    axis: SupportsIndex = 0,
     *,
-    device: L["cpu"] | None = ...,
+    device: L["cpu"] | None = None,
 ) -> NDArray[np.float64]: ...
 @overload
 def linspace(
     start: _ArrayLikeFloat_co,
     stop: _ArrayLikeFloat_co,
-    num: SupportsIndex = ...,
-    endpoint: bool = ...,
-    retstep: L[False] = ...,
-    dtype: None = ...,
-    axis: SupportsIndex = ...,
+    num: SupportsIndex = 50,
+    endpoint: bool = True,
+    retstep: L[False] = False,
+    dtype: None = None,
+    axis: SupportsIndex = 0,
     *,
-    device: L["cpu"] | None = ...,
+    device: L["cpu"] | None = None,
 ) -> NDArray[floating]: ...
 @overload
 def linspace(
     start: _ArrayLikeComplex_co,
     stop: _ArrayLikeComplex_co,
-    num: SupportsIndex = ...,
-    endpoint: bool = ...,
-    retstep: L[False] = ...,
-    dtype: None = ...,
-    axis: SupportsIndex = ...,
+    num: SupportsIndex = 50,
+    endpoint: bool = True,
+    retstep: L[False] = False,
+    dtype: None = None,
+    axis: SupportsIndex = 0,
     *,
-    device: L["cpu"] | None = ...,
+    device: L["cpu"] | None = None,
 ) -> NDArray[complexfloating]: ...
 @overload
 def linspace(
@@ -68,124 +68,124 @@ def linspace(
     endpoint: bool,
     retstep: L[False],
     dtype: _DTypeLike[_ScalarT],
-    axis: SupportsIndex = ...,
+    axis: SupportsIndex = 0,
     *,
-    device: L["cpu"] | None = ...,
+    device: L["cpu"] | None = None,
 ) -> NDArray[_ScalarT]: ...
 @overload
 def linspace(
     start: _ArrayLikeComplex_co,
     stop: _ArrayLikeComplex_co,
-    num: SupportsIndex = ...,
-    endpoint: bool = ...,
-    retstep: L[False] = ...,
+    num: SupportsIndex = 50,
+    endpoint: bool = True,
+    retstep: L[False] = False,
     *,
     dtype: _DTypeLike[_ScalarT],
-    axis: SupportsIndex = ...,
-    device: L["cpu"] | None = ...,
+    axis: SupportsIndex = 0,
+    device: L["cpu"] | None = None,
 ) -> NDArray[_ScalarT]: ...
 @overload
 def linspace(
     start: _ArrayLikeComplex_co,
     stop: _ArrayLikeComplex_co,
-    num: SupportsIndex = ...,
-    endpoint: bool = ...,
-    retstep: L[False] = ...,
-    dtype: DTypeLike = ...,
-    axis: SupportsIndex = ...,
+    num: SupportsIndex = 50,
+    endpoint: bool = True,
+    retstep: L[False] = False,
+    dtype: DTypeLike | None = None,
+    axis: SupportsIndex = 0,
     *,
-    device: L["cpu"] | None = ...,
+    device: L["cpu"] | None = None,
 ) -> NDArray[Any]: ...
 @overload
 def linspace(
     start: _ToArrayFloat64,
     stop: _ToArrayFloat64,
-    num: SupportsIndex = ...,
-    endpoint: bool = ...,
+    num: SupportsIndex = 50,
+    endpoint: bool = True,
     *,
     retstep: L[True],
-    dtype: None = ...,
-    axis: SupportsIndex = ...,
-    device: L["cpu"] | None = ...,
+    dtype: None = None,
+    axis: SupportsIndex = 0,
+    device: L["cpu"] | None = None,
 ) -> tuple[NDArray[np.float64], np.float64]: ...
 @overload
 def linspace(
     start: _ArrayLikeFloat_co,
     stop: _ArrayLikeFloat_co,
-    num: SupportsIndex = ...,
-    endpoint: bool = ...,
+    num: SupportsIndex = 50,
+    endpoint: bool = True,
     *,
     retstep: L[True],
-    dtype: None = ...,
-    axis: SupportsIndex = ...,
-    device: L["cpu"] | None = ...,
+    dtype: None = None,
+    axis: SupportsIndex = 0,
+    device: L["cpu"] | None = None,
 ) -> tuple[NDArray[floating], floating]: ...
 @overload
 def linspace(
     start: _ArrayLikeComplex_co,
     stop: _ArrayLikeComplex_co,
-    num: SupportsIndex = ...,
-    endpoint: bool = ...,
+    num: SupportsIndex = 50,
+    endpoint: bool = True,
     *,
     retstep: L[True],
-    dtype: None = ...,
-    axis: SupportsIndex = ...,
-    device: L["cpu"] | None = ...,
+    dtype: None = None,
+    axis: SupportsIndex = 0,
+    device: L["cpu"] | None = None,
 ) -> tuple[NDArray[complexfloating], complexfloating]: ...
 @overload
 def linspace(
     start: _ArrayLikeComplex_co,
     stop: _ArrayLikeComplex_co,
-    num: SupportsIndex = ...,
-    endpoint: bool = ...,
+    num: SupportsIndex = 50,
+    endpoint: bool = True,
     *,
     retstep: L[True],
     dtype: _DTypeLike[_ScalarT],
-    axis: SupportsIndex = ...,
-    device: L["cpu"] | None = ...,
+    axis: SupportsIndex = 0,
+    device: L["cpu"] | None = None,
 ) -> tuple[NDArray[_ScalarT], _ScalarT]: ...
 @overload
 def linspace(
     start: _ArrayLikeComplex_co,
     stop: _ArrayLikeComplex_co,
-    num: SupportsIndex = ...,
-    endpoint: bool = ...,
+    num: SupportsIndex = 50,
+    endpoint: bool = True,
     *,
     retstep: L[True],
-    dtype: DTypeLike = ...,
-    axis: SupportsIndex = ...,
-    device: L["cpu"] | None = ...,
+    dtype: DTypeLike | None = None,
+    axis: SupportsIndex = 0,
+    device: L["cpu"] | None = None,
 ) -> tuple[NDArray[Any], Any]: ...
 
 @overload
 def logspace(
     start: _ToArrayFloat64,
     stop: _ToArrayFloat64,
-    num: SupportsIndex = ...,
-    endpoint: bool = ...,
-    base: _ToArrayFloat64 = ...,
-    dtype: None = ...,
-    axis: SupportsIndex = ...,
+    num: SupportsIndex = 50,
+    endpoint: bool = True,
+    base: _ToArrayFloat64 = 10.0,
+    dtype: None = None,
+    axis: SupportsIndex = 0,
 ) -> NDArray[np.float64]: ...
 @overload
 def logspace(
     start: _ArrayLikeFloat_co,
     stop: _ArrayLikeFloat_co,
-    num: SupportsIndex = ...,
-    endpoint: bool = ...,
-    base: _ArrayLikeFloat_co = ...,
-    dtype: None = ...,
-    axis: SupportsIndex = ...,
+    num: SupportsIndex = 50,
+    endpoint: bool = True,
+    base: _ArrayLikeFloat_co = 10.0,
+    dtype: None = None,
+    axis: SupportsIndex = 0,
 ) -> NDArray[floating]: ...
 @overload
 def logspace(
     start: _ArrayLikeComplex_co,
     stop: _ArrayLikeComplex_co,
-    num: SupportsIndex = ...,
-    endpoint: bool = ...,
-    base: _ArrayLikeComplex_co = ...,
-    dtype: None = ...,
-    axis: SupportsIndex = ...,
+    num: SupportsIndex = 50,
+    endpoint: bool = True,
+    base: _ArrayLikeComplex_co = 10.0,
+    dtype: None = None,
+    axis: SupportsIndex = 0,
 ) -> NDArray[complexfloating]: ...
 @overload
 def logspace(
@@ -195,56 +195,56 @@ def logspace(
     endpoint: bool,
     base: _ArrayLikeComplex_co,
     dtype: _DTypeLike[_ScalarT],
-    axis: SupportsIndex = ...,
+    axis: SupportsIndex = 0,
 ) -> NDArray[_ScalarT]: ...
 @overload
 def logspace(
     start: _ArrayLikeComplex_co,
     stop: _ArrayLikeComplex_co,
-    num: SupportsIndex = ...,
-    endpoint: bool = ...,
-    base: _ArrayLikeComplex_co = ...,
+    num: SupportsIndex = 50,
+    endpoint: bool = True,
+    base: _ArrayLikeComplex_co = 10.0,
     *,
     dtype: _DTypeLike[_ScalarT],
-    axis: SupportsIndex = ...,
+    axis: SupportsIndex = 0,
 ) -> NDArray[_ScalarT]: ...
 @overload
 def logspace(
     start: _ArrayLikeComplex_co,
     stop: _ArrayLikeComplex_co,
-    num: SupportsIndex = ...,
-    endpoint: bool = ...,
-    base: _ArrayLikeComplex_co = ...,
-    dtype: DTypeLike = ...,
-    axis: SupportsIndex = ...,
+    num: SupportsIndex = 50,
+    endpoint: bool = True,
+    base: _ArrayLikeComplex_co = 10.0,
+    dtype: DTypeLike | None = None,
+    axis: SupportsIndex = 0,
 ) -> NDArray[Any]: ...
 
 @overload
 def geomspace(
     start: _ToArrayFloat64,
     stop: _ToArrayFloat64,
-    num: SupportsIndex = ...,
-    endpoint: bool = ...,
-    dtype: None = ...,
-    axis: SupportsIndex = ...,
+    num: SupportsIndex = 50,
+    endpoint: bool = True,
+    dtype: None = None,
+    axis: SupportsIndex = 0,
 ) -> NDArray[np.float64]: ...
 @overload
 def geomspace(
     start: _ArrayLikeFloat_co,
     stop: _ArrayLikeFloat_co,
-    num: SupportsIndex = ...,
-    endpoint: bool = ...,
-    dtype: None = ...,
-    axis: SupportsIndex = ...,
+    num: SupportsIndex = 50,
+    endpoint: bool = True,
+    dtype: None = None,
+    axis: SupportsIndex = 0,
 ) -> NDArray[floating]: ...
 @overload
 def geomspace(
     start: _ArrayLikeComplex_co,
     stop: _ArrayLikeComplex_co,
-    num: SupportsIndex = ...,
-    endpoint: bool = ...,
-    dtype: None = ...,
-    axis: SupportsIndex = ...,
+    num: SupportsIndex = 50,
+    endpoint: bool = True,
+    dtype: None = None,
+    axis: SupportsIndex = 0,
 ) -> NDArray[complexfloating]: ...
 @overload
 def geomspace(
@@ -253,31 +253,31 @@ def geomspace(
     num: SupportsIndex,
     endpoint: bool,
     dtype: _DTypeLike[_ScalarT],
-    axis: SupportsIndex = ...,
+    axis: SupportsIndex = 0,
 ) -> NDArray[_ScalarT]: ...
 @overload
 def geomspace(
     start: _ArrayLikeComplex_co,
     stop: _ArrayLikeComplex_co,
-    num: SupportsIndex = ...,
-    endpoint: bool = ...,
+    num: SupportsIndex = 50,
+    endpoint: bool = True,
     *,
     dtype: _DTypeLike[_ScalarT],
-    axis: SupportsIndex = ...,
+    axis: SupportsIndex = 0,
 ) -> NDArray[_ScalarT]: ...
 @overload
 def geomspace(
     start: _ArrayLikeComplex_co,
     stop: _ArrayLikeComplex_co,
-    num: SupportsIndex = ...,
-    endpoint: bool = ...,
-    dtype: DTypeLike = ...,
-    axis: SupportsIndex = ...,
+    num: SupportsIndex = 50,
+    endpoint: bool = True,
+    dtype: DTypeLike | None = None,
+    axis: SupportsIndex = 0,
 ) -> NDArray[Any]: ...
 
 def add_newdoc(
     place: str,
     obj: str,
     doc: str | tuple[str, str] | list[tuple[str, str]],
-    warn_on_python: bool = ...,
+    warn_on_python: bool = True,
 ) -> None: ...

From 34a0181bde5b88f005b8f5b557c7857f5823a599 Mon Sep 17 00:00:00 2001
From: jorenham 
Date: Tue, 6 May 2025 16:01:19 +0200
Subject: [PATCH 165/202] TYP: use ``Incomplete`` when appropriate in
 ``_core.function_base``

---
 numpy/_core/function_base.pyi | 10 +++++-----
 1 file changed, 5 insertions(+), 5 deletions(-)

diff --git a/numpy/_core/function_base.pyi b/numpy/_core/function_base.pyi
index 34af79177f97..3ba22cb167e0 100644
--- a/numpy/_core/function_base.pyi
+++ b/numpy/_core/function_base.pyi
@@ -1,8 +1,8 @@
+from _typeshed import Incomplete
 from typing import (
     Literal as L,
     TypeAlias,
     overload,
-    Any,
     SupportsIndex,
     TypeVar,
 )
@@ -95,7 +95,7 @@ def linspace(
     axis: SupportsIndex = 0,
     *,
     device: L["cpu"] | None = None,
-) -> NDArray[Any]: ...
+) -> NDArray[Incomplete]: ...
 @overload
 def linspace(
     start: _ToArrayFloat64,
@@ -155,7 +155,7 @@ def linspace(
     dtype: DTypeLike | None = None,
     axis: SupportsIndex = 0,
     device: L["cpu"] | None = None,
-) -> tuple[NDArray[Any], Any]: ...
+) -> tuple[NDArray[Incomplete], Incomplete]: ...
 
 @overload
 def logspace(
@@ -217,7 +217,7 @@ def logspace(
     base: _ArrayLikeComplex_co = 10.0,
     dtype: DTypeLike | None = None,
     axis: SupportsIndex = 0,
-) -> NDArray[Any]: ...
+) -> NDArray[Incomplete]: ...
 
 @overload
 def geomspace(
@@ -273,7 +273,7 @@ def geomspace(
     endpoint: bool = True,
     dtype: DTypeLike | None = None,
     axis: SupportsIndex = 0,
-) -> NDArray[Any]: ...
+) -> NDArray[Incomplete]: ...
 
 def add_newdoc(
     place: str,

From ce588ef107d9f9850d67f679197f52f698107c87 Mon Sep 17 00:00:00 2001
From: jorenham 
Date: Tue, 6 May 2025 16:04:20 +0200
Subject: [PATCH 166/202] TYP: prefer ``np._`` over ``from numpy import _`` in
 ``_core.function_base``

---
 numpy/_core/function_base.pyi | 19 +++++++++----------
 1 file changed, 9 insertions(+), 10 deletions(-)

diff --git a/numpy/_core/function_base.pyi b/numpy/_core/function_base.pyi
index 3ba22cb167e0..0b416aca3a99 100644
--- a/numpy/_core/function_base.pyi
+++ b/numpy/_core/function_base.pyi
@@ -8,7 +8,6 @@ from typing import (
 )
 
 import numpy as np
-from numpy import floating, complexfloating, generic
 from numpy._typing import (
     NDArray,
     DTypeLike,
@@ -20,7 +19,7 @@ from numpy._typing._array_like import _DualArrayLike
 
 __all__ = ["logspace", "linspace", "geomspace"]
 
-_ScalarT = TypeVar("_ScalarT", bound=generic)
+_ScalarT = TypeVar("_ScalarT", bound=np.generic)
 
 _ToArrayFloat64: TypeAlias = _DualArrayLike[np.dtype[np.float64 | np.integer | np.bool], float]
 
@@ -47,7 +46,7 @@ def linspace(
     axis: SupportsIndex = 0,
     *,
     device: L["cpu"] | None = None,
-) -> NDArray[floating]: ...
+) -> NDArray[np.floating]: ...
 @overload
 def linspace(
     start: _ArrayLikeComplex_co,
@@ -59,7 +58,7 @@ def linspace(
     axis: SupportsIndex = 0,
     *,
     device: L["cpu"] | None = None,
-) -> NDArray[complexfloating]: ...
+) -> NDArray[np.complexfloating]: ...
 @overload
 def linspace(
     start: _ArrayLikeComplex_co,
@@ -119,7 +118,7 @@ def linspace(
     dtype: None = None,
     axis: SupportsIndex = 0,
     device: L["cpu"] | None = None,
-) -> tuple[NDArray[floating], floating]: ...
+) -> tuple[NDArray[np.floating], np.floating]: ...
 @overload
 def linspace(
     start: _ArrayLikeComplex_co,
@@ -131,7 +130,7 @@ def linspace(
     dtype: None = None,
     axis: SupportsIndex = 0,
     device: L["cpu"] | None = None,
-) -> tuple[NDArray[complexfloating], complexfloating]: ...
+) -> tuple[NDArray[np.complexfloating], np.complexfloating]: ...
 @overload
 def linspace(
     start: _ArrayLikeComplex_co,
@@ -176,7 +175,7 @@ def logspace(
     base: _ArrayLikeFloat_co = 10.0,
     dtype: None = None,
     axis: SupportsIndex = 0,
-) -> NDArray[floating]: ...
+) -> NDArray[np.floating]: ...
 @overload
 def logspace(
     start: _ArrayLikeComplex_co,
@@ -186,7 +185,7 @@ def logspace(
     base: _ArrayLikeComplex_co = 10.0,
     dtype: None = None,
     axis: SupportsIndex = 0,
-) -> NDArray[complexfloating]: ...
+) -> NDArray[np.complexfloating]: ...
 @overload
 def logspace(
     start: _ArrayLikeComplex_co,
@@ -236,7 +235,7 @@ def geomspace(
     endpoint: bool = True,
     dtype: None = None,
     axis: SupportsIndex = 0,
-) -> NDArray[floating]: ...
+) -> NDArray[np.floating]: ...
 @overload
 def geomspace(
     start: _ArrayLikeComplex_co,
@@ -245,7 +244,7 @@ def geomspace(
     endpoint: bool = True,
     dtype: None = None,
     axis: SupportsIndex = 0,
-) -> NDArray[complexfloating]: ...
+) -> NDArray[np.complexfloating]: ...
 @overload
 def geomspace(
     start: _ArrayLikeComplex_co,

From 1b0d920d11b78117940f6284677bc1a0f428be52 Mon Sep 17 00:00:00 2001
From: jorenham 
Date: Tue, 6 May 2025 16:06:15 +0200
Subject: [PATCH 167/202] STY: appease ruff in the ``_core.function_base``
 stubs

---
 numpy/_core/function_base.pyi | 20 +++++---------------
 1 file changed, 5 insertions(+), 15 deletions(-)

diff --git a/numpy/_core/function_base.pyi b/numpy/_core/function_base.pyi
index 0b416aca3a99..5348ebfb40c3 100644
--- a/numpy/_core/function_base.pyi
+++ b/numpy/_core/function_base.pyi
@@ -1,23 +1,13 @@
+from typing import Literal as L
+from typing import SupportsIndex, TypeAlias, TypeVar, overload
+
 from _typeshed import Incomplete
-from typing import (
-    Literal as L,
-    TypeAlias,
-    overload,
-    SupportsIndex,
-    TypeVar,
-)
 
 import numpy as np
-from numpy._typing import (
-    NDArray,
-    DTypeLike,
-    _DTypeLike,
-    _ArrayLikeFloat_co,
-    _ArrayLikeComplex_co,
-)
+from numpy._typing import DTypeLike, NDArray, _ArrayLikeComplex_co, _ArrayLikeFloat_co, _DTypeLike
 from numpy._typing._array_like import _DualArrayLike
 
-__all__ = ["logspace", "linspace", "geomspace"]
+__all__ = ["geomspace", "linspace", "logspace"]
 
 _ScalarT = TypeVar("_ScalarT", bound=np.generic)
 

From 83a4e6a77720802f1d2476cf0d376f4b04725fc7 Mon Sep 17 00:00:00 2001
From: Ilhan Polat 
Date: Tue, 6 May 2025 22:14:08 +0200
Subject: [PATCH 168/202] MAINT: Avoid dereferencing/strict aliasing warnings
 during complex casts in `npy_math.h` for C++ runs (#28892)

* MAINT: Avoid type-punning complex casts in npy_math.h

* MAINT: Add missing typecast in npy_cimagl
---
 numpy/_core/include/numpy/npy_math.h | 12 ++++++------
 1 file changed, 6 insertions(+), 6 deletions(-)

diff --git a/numpy/_core/include/numpy/npy_math.h b/numpy/_core/include/numpy/npy_math.h
index d11df12b7ceb..abc784bc686c 100644
--- a/numpy/_core/include/numpy/npy_math.h
+++ b/numpy/_core/include/numpy/npy_math.h
@@ -363,7 +363,7 @@ NPY_INPLACE npy_longdouble npy_heavisidel(npy_longdouble x, npy_longdouble h0);
 static inline double npy_creal(const npy_cdouble z)
 {
 #if defined(__cplusplus)
-    return ((double *) &z)[0];
+    return z._Val[0];
 #else
     return creal(z);
 #endif
@@ -377,7 +377,7 @@ static inline void npy_csetreal(npy_cdouble *z, const double r)
 static inline double npy_cimag(const npy_cdouble z)
 {
 #if defined(__cplusplus)
-    return ((double *) &z)[1];
+    return z._Val[1];
 #else
     return cimag(z);
 #endif
@@ -391,7 +391,7 @@ static inline void npy_csetimag(npy_cdouble *z, const double i)
 static inline float npy_crealf(const npy_cfloat z)
 {
 #if defined(__cplusplus)
-    return ((float *) &z)[0];
+    return z._Val[0];
 #else
     return crealf(z);
 #endif
@@ -405,7 +405,7 @@ static inline void npy_csetrealf(npy_cfloat *z, const float r)
 static inline float npy_cimagf(const npy_cfloat z)
 {
 #if defined(__cplusplus)
-    return ((float *) &z)[1];
+    return z._Val[1];
 #else
     return cimagf(z);
 #endif
@@ -419,7 +419,7 @@ static inline void npy_csetimagf(npy_cfloat *z, const float i)
 static inline npy_longdouble npy_creall(const npy_clongdouble z)
 {
 #if defined(__cplusplus)
-    return ((longdouble_t *) &z)[0];
+    return (npy_longdouble)z._Val[0];
 #else
     return creall(z);
 #endif
@@ -433,7 +433,7 @@ static inline void npy_csetreall(npy_clongdouble *z, const longdouble_t r)
 static inline npy_longdouble npy_cimagl(const npy_clongdouble z)
 {
 #if defined(__cplusplus)
-    return ((longdouble_t *) &z)[1];
+    return (npy_longdouble)z._Val[1];
 #else
     return cimagl(z);
 #endif

From de784cd6ee53ffddf07e0b3f89bf22bda9fd92fb Mon Sep 17 00:00:00 2001
From: Peter Hawkins 
Date: Tue, 6 May 2025 16:15:10 -0400
Subject: [PATCH 169/202] BUG: Fix missing check for PyErr_Occurred() in
 _pyarray_correlate. (#28898)

When running the scipy 1.15 test suite test
signal/tests/test_signaltools.py::test_lfilter_bad_object, with Python
built in debug mode, we see the following error:

```
Fatal Python error: _Py_CheckSlotResult: Slot * of type float succeeded with an exception set
```

`None` ends up as the first argument to `dot`, and this triggers an
error from PyFloat_Multiply. Once an error has occurred, we must avoid
calling multiply again, since it asserts that PyErr_Occurred() is false
if the output is a non-error, which will fail if an error was set at
entry.
---
 numpy/_core/src/multiarray/multiarraymodule.c | 10 ++++++++--
 1 file changed, 8 insertions(+), 2 deletions(-)

diff --git a/numpy/_core/src/multiarray/multiarraymodule.c b/numpy/_core/src/multiarray/multiarraymodule.c
index cddfad16a972..a53dd0960ed0 100644
--- a/numpy/_core/src/multiarray/multiarraymodule.c
+++ b/numpy/_core/src/multiarray/multiarraymodule.c
@@ -1205,6 +1205,7 @@ _pyarray_correlate(PyArrayObject *ap1, PyArrayObject *ap2, int typenum,
         goto clean_ret;
     }
 
+    int needs_pyapi = PyDataType_FLAGCHK(PyArray_DESCR(ret), NPY_NEEDS_PYAPI);
     NPY_BEGIN_THREADS_DESCR(PyArray_DESCR(ret));
     is1 = PyArray_STRIDES(ap1)[0];
     is2 = PyArray_STRIDES(ap2)[0];
@@ -1215,6 +1216,9 @@ _pyarray_correlate(PyArrayObject *ap1, PyArrayObject *ap2, int typenum,
     n = n - n_left;
     for (i = 0; i < n_left; i++) {
         dot(ip1, is1, ip2, is2, op, n, ret);
+        if (needs_pyapi && PyErr_Occurred()) {
+            goto done;
+        }
         n++;
         ip2 -= is2;
         op += os;
@@ -1226,19 +1230,21 @@ _pyarray_correlate(PyArrayObject *ap1, PyArrayObject *ap2, int typenum,
         op += os * (n1 - n2 + 1);
     }
     else {
-        for (i = 0; i < (n1 - n2 + 1); i++) {
+        for (i = 0; i < (n1 - n2 + 1) && (!needs_pyapi || !PyErr_Occurred());
+             i++) {
             dot(ip1, is1, ip2, is2, op, n, ret);
             ip1 += is1;
             op += os;
         }
     }
-    for (i = 0; i < n_right; i++) {
+    for (i = 0; i < n_right && (!needs_pyapi || !PyErr_Occurred()); i++) {
         n--;
         dot(ip1, is1, ip2, is2, op, n, ret);
         ip1 += is1;
         op += os;
     }
 
+done:
     NPY_END_THREADS_DESCR(PyArray_DESCR(ret));
     if (PyErr_Occurred()) {
         goto clean_ret;

From 949554c276e7641d9dd360d5eed8aa1518eb0e71 Mon Sep 17 00:00:00 2001
From: Chevali2004 <93073405+Chevali2004@users.noreply.github.com>
Date: Wed, 7 May 2025 20:08:51 +0200
Subject: [PATCH 170/202] BUG: Use unrotated companion matrix in
 polynomial.polyroots. (#28821)

* BUG: Fix #27881 inconsistent behavior between numpy.roots and numpy.polynomial.polynomial.polyroots

Both functions use numpy.linalg.eigvals, but while roots gives in argument the polynomial's companion matrix unchanged, polyroots rotates it. Though in theory this rotation shouldn't change anything, in terms of numerical calcuations, eigvals gives significantly different results. This commit removes the rotation as an easy fix to the inconsistency.

This strange behavior by eigvals is however a bug. I did some research on it, which you can find on the issue.

* BUG: Fix #27881 Adding tests for numpy.roots and numpy.polynomial.polynomial.polyroots

The following tests provide a minimum precision expected by the functions. In the case of my change, they allow my change but not the previous version. You'll find that the difference of precision between the two versions vary according to the root values but in all cases, this change either increases precision or maintains the previous result.

* BUG: Fix #27881 Adding tests for numpy.roots and numpy.polynomial.polynomial.polyroots

Fixing tests

* BUG: Fix #27881 Adding tests for numpy.roots and numpy.polynomial.polynomial.polyroots

Fixing tests. It seems that the way numpy.roots creates it's matrice companion augments the numerical error compared to the polycompanion function, which is why I had to reduce the expected precision.

* Reverting change from commit 6703b91a22f7f0d1e98f565efcb659d8369b4952 in matlib.pyi
---
 numpy/lib/tests/test_polynomial.py        | 12 ++++++++++++
 numpy/polynomial/polynomial.py            |  3 +--
 numpy/polynomial/tests/test_polynomial.py | 11 +++++++++++
 3 files changed, 24 insertions(+), 2 deletions(-)

diff --git a/numpy/lib/tests/test_polynomial.py b/numpy/lib/tests/test_polynomial.py
index 0a91b941526e..bf432348cb36 100644
--- a/numpy/lib/tests/test_polynomial.py
+++ b/numpy/lib/tests/test_polynomial.py
@@ -1,4 +1,5 @@
 import numpy as np
+import numpy.polynomial.polynomial as poly
 from numpy.testing import (
     assert_, assert_equal, assert_array_equal, assert_almost_equal,
     assert_array_almost_equal, assert_raises, assert_allclose
@@ -121,6 +122,17 @@ def test_poly(self):
     def test_roots(self):
         assert_array_equal(np.roots([1, 0, 0]), [0, 0])
 
+        # Testing for larger root values
+        for i in np.logspace(10, 25, num = 1000, base = 10):
+            tgt = np.array([-1, 1, i])
+            res = np.sort(np.roots(poly.polyfromroots(tgt)[::-1]))
+            assert_almost_equal(res, tgt, 14 - int(np.log10(i)))    # Adapting the expected precision according to the root value, to take into account numerical calculation error
+
+        for i in np.logspace(10, 25, num = 1000, base = 10):
+            tgt = np.array([-1, 1.01, i])
+            res = np.sort(np.roots(poly.polyfromroots(tgt)[::-1]))
+            assert_almost_equal(res, tgt, 14 - int(np.log10(i)))    # Adapting the expected precision according to the root value, to take into account numerical calculation error
+
     def test_str_leading_zeros(self):
         p = np.poly1d([4, 3, 2, 1])
         p[3] = 0
diff --git a/numpy/polynomial/polynomial.py b/numpy/polynomial/polynomial.py
index dada4544dc63..32b53b757a1c 100644
--- a/numpy/polynomial/polynomial.py
+++ b/numpy/polynomial/polynomial.py
@@ -1535,8 +1535,7 @@ def polyroots(c):
     if len(c) == 2:
         return np.array([-c[0] / c[1]])
 
-    # rotated companion matrix reduces error
-    m = polycompanion(c)[::-1, ::-1]
+    m = polycompanion(c)
     r = la.eigvals(m)
     r.sort()
     return r
diff --git a/numpy/polynomial/tests/test_polynomial.py b/numpy/polynomial/tests/test_polynomial.py
index e7c4fdfe8996..84ccc45fc4e4 100644
--- a/numpy/polynomial/tests/test_polynomial.py
+++ b/numpy/polynomial/tests/test_polynomial.py
@@ -543,6 +543,17 @@ def test_polyroots(self):
             res = poly.polyroots(poly.polyfromroots(tgt))
             assert_almost_equal(trim(res), trim(tgt))
 
+        # Testing for larger root values
+        for i in np.logspace(10, 25, num = 1000, base = 10):
+            tgt = np.array([-1, 1, i])
+            res = poly.polyroots(poly.polyfromroots(tgt))
+            assert_almost_equal(res, tgt, 15 - int(np.log10(i)))    # Adapting the expected precision according to the root value, to take into account numerical calculation error
+
+        for i in np.logspace(10, 25, num = 1000, base = 10):
+            tgt = np.array([-1, 1.01, i])
+            res = poly.polyroots(poly.polyfromroots(tgt))
+            assert_almost_equal(res, tgt, 14 - int(np.log10(i)))    # Adapting the expected precision according to the root value, to take into account numerical calculation error
+
     def test_polyfit(self):
         def f(x):
             return x * (x - 1) * (x - 2)

From 7d0d61f50d2a38d6da8bcb2b22cadde7b58bf6b9 Mon Sep 17 00:00:00 2001
From: Marco Gorelli <33491632+MarcoGorelli@users.noreply.github.com>
Date: Thu, 8 May 2025 15:17:16 +0100
Subject: [PATCH 171/202] MAINT: Remove outdated ``MaskedArray.__div__`` and
 ``MaskedArray.__idiv__``

---
 numpy/ma/core.py  | 28 ----------------------------
 numpy/ma/core.pyi |  2 --
 2 files changed, 30 deletions(-)

diff --git a/numpy/ma/core.py b/numpy/ma/core.py
index bbd64bd76007..a4084c7dc938 100644
--- a/numpy/ma/core.py
+++ b/numpy/ma/core.py
@@ -4358,15 +4358,6 @@ def __rmul__(self, other):
         # we get here from `other * self`.
         return multiply(other, self)
 
-    def __div__(self, other):
-        """
-        Divide other into self, and return a new masked array.
-
-        """
-        if self._delegate_binop(other):
-            return NotImplemented
-        return divide(self, other)
-
     def __truediv__(self, other):
         """
         Divide other into self, and return a new masked array.
@@ -4467,25 +4458,6 @@ def __imul__(self, other):
         self._data.__imul__(other_data)
         return self
 
-    def __idiv__(self, other):
-        """
-        Divide self by other in-place.
-
-        """
-        other_data = getdata(other)
-        dom_mask = _DomainSafeDivide().__call__(self._data, other_data)
-        other_mask = getmask(other)
-        new_mask = mask_or(other_mask, dom_mask)
-        # The following 4 lines control the domain filling
-        if dom_mask.any():
-            (_, fval) = ufunc_fills[np.divide]
-            other_data = np.where(
-                    dom_mask, other_data.dtype.type(fval), other_data)
-        self._mask |= new_mask
-        other_data = np.where(self._mask, other_data.dtype.type(1), other_data)
-        self._data.__idiv__(other_data)
-        return self
-
     def __ifloordiv__(self, other):
         """
         Floor divide self by other in-place.
diff --git a/numpy/ma/core.pyi b/numpy/ma/core.pyi
index 055f25fe0557..9641e7f63671 100644
--- a/numpy/ma/core.pyi
+++ b/numpy/ma/core.pyi
@@ -450,7 +450,6 @@ class MaskedArray(ndarray[_ShapeT_co, _DTypeT_co]):
     def __rsub__(self, other): ...
     def __mul__(self, other): ...
     def __rmul__(self, other): ...
-    def __div__(self, other): ...
     def __truediv__(self, other): ...
     def __rtruediv__(self, other): ...
     def __floordiv__(self, other): ...
@@ -460,7 +459,6 @@ class MaskedArray(ndarray[_ShapeT_co, _DTypeT_co]):
     def __iadd__(self, other): ...
     def __isub__(self, other): ...
     def __imul__(self, other): ...
-    def __idiv__(self, other): ...
     def __ifloordiv__(self, other): ...
     def __itruediv__(self, other): ...
     def __ipow__(self, other): ...

From f95a7fdd113477cde1873808e0277f395cb24a0b Mon Sep 17 00:00:00 2001
From: jorenham 
Date: Thu, 8 May 2025 16:45:15 +0200
Subject: [PATCH 172/202] MAINT: remove py2 ``__div__`` remnants from
 ``poly1d``

---
 numpy/__init__.pyi            | 2 --
 numpy/lib/_polynomial_impl.py | 8 ++------
 2 files changed, 2 insertions(+), 8 deletions(-)

diff --git a/numpy/__init__.pyi b/numpy/__init__.pyi
index 540cf188a967..5502d6e0755a 100644
--- a/numpy/__init__.pyi
+++ b/numpy/__init__.pyi
@@ -5243,9 +5243,7 @@ class poly1d:
     def __pow__(self, val: _FloatLike_co, /) -> poly1d: ...  # Integral floats are accepted
     def __sub__(self, other: ArrayLike, /) -> poly1d: ...
     def __rsub__(self, other: ArrayLike, /) -> poly1d: ...
-    def __div__(self, other: ArrayLike, /) -> poly1d: ...
     def __truediv__(self, other: ArrayLike, /) -> poly1d: ...
-    def __rdiv__(self, other: ArrayLike, /) -> poly1d: ...
     def __rtruediv__(self, other: ArrayLike, /) -> poly1d: ...
     def __getitem__(self, val: int, /) -> Any: ...
     def __setitem__(self, key: int, val: Any, /) -> None: ...
diff --git a/numpy/lib/_polynomial_impl.py b/numpy/lib/_polynomial_impl.py
index a1d21c624c57..f8a31ac4fe13 100644
--- a/numpy/lib/_polynomial_impl.py
+++ b/numpy/lib/_polynomial_impl.py
@@ -1382,24 +1382,20 @@ def __rsub__(self, other):
         other = poly1d(other)
         return poly1d(polysub(other.coeffs, self.coeffs))
 
-    def __div__(self, other):
+    def __truediv__(self, other):
         if isscalar(other):
             return poly1d(self.coeffs / other)
         else:
             other = poly1d(other)
             return polydiv(self, other)
 
-    __truediv__ = __div__
-
-    def __rdiv__(self, other):
+    def __rtruediv__(self, other):
         if isscalar(other):
             return poly1d(other / self.coeffs)
         else:
             other = poly1d(other)
             return polydiv(other, self)
 
-    __rtruediv__ = __rdiv__
-
     def __eq__(self, other):
         if not isinstance(other, poly1d):
             return NotImplemented

From 822f1e18347356b319012cc51795e25bb4fe6d20 Mon Sep 17 00:00:00 2001
From: jorenham 
Date: Thu, 8 May 2025 16:47:32 +0200
Subject: [PATCH 173/202] MAINT: remove ``ABCPolyBase.__rdiv__``

---
 numpy/polynomial/_polybase.py | 4 ----
 1 file changed, 4 deletions(-)

diff --git a/numpy/polynomial/_polybase.py b/numpy/polynomial/_polybase.py
index c9585f5c6d2f..f454a131c31d 100644
--- a/numpy/polynomial/_polybase.py
+++ b/numpy/polynomial/_polybase.py
@@ -611,10 +611,6 @@ def __rmul__(self, other):
             return NotImplemented
         return self.__class__(coef, self.domain, self.window, self.symbol)
 
-    def __rdiv__(self, other):
-        # set to __floordiv__ /.
-        return self.__rfloordiv__(other)
-
     def __rtruediv__(self, other):
         # An instance of ABCPolyBase is not considered a
         # Number.

From 44e35f0dee878e26dbf963f3b8ea279529e5438f Mon Sep 17 00:00:00 2001
From: jorenham 
Date: Thu, 8 May 2025 16:54:57 +0200
Subject: [PATCH 174/202] MAINT: remove py2 ``__div__`` remnants from the tests

---
 numpy/_core/tests/test_function_base.py | 4 ++--
 numpy/_core/tests/test_multiarray.py    | 5 ++---
 numpy/ma/tests/test_core.py             | 4 +---
 3 files changed, 5 insertions(+), 8 deletions(-)

diff --git a/numpy/_core/tests/test_function_base.py b/numpy/_core/tests/test_function_base.py
index 8350777565ba..d7a1124d6c3d 100644
--- a/numpy/_core/tests/test_function_base.py
+++ b/numpy/_core/tests/test_function_base.py
@@ -39,10 +39,10 @@ def __mul__(self, x):
         return PhysicalQuantity(float(x) * float(self))
     __rmul__ = __mul__
 
-    def __div__(self, x):
+    def __truediv__(self, x):
         return PhysicalQuantity(float(self) / float(x))
 
-    def __rdiv__(self, x):
+    def __rtruediv__(self, x):
         return PhysicalQuantity(float(x) / float(self))
 
 
diff --git a/numpy/_core/tests/test_multiarray.py b/numpy/_core/tests/test_multiarray.py
index 0a62cb6945f0..0e92dfc4140b 100644
--- a/numpy/_core/tests/test_multiarray.py
+++ b/numpy/_core/tests/test_multiarray.py
@@ -4170,8 +4170,8 @@ def __init__(self, num=None):
             def __mul__(self, other):
                 raise AssertionError('__mul__ should not be called')
 
-            def __div__(self, other):
-                raise AssertionError('__div__ should not be called')
+            def __truediv__(self, other):
+                raise AssertionError('__truediv__ should not be called')
 
             def __pow__(self, exp):
                 return SomeClass(num=self.num ** exp)
@@ -9260,7 +9260,6 @@ def _all(self, other):
         __sub__ = __rsub__ = _all
         __mul__ = __rmul__ = _all
         __pow__ = __rpow__ = _all
-        __div__ = __rdiv__ = _all
         __mod__ = __rmod__ = _all
         __truediv__ = __rtruediv__ = _all
         __floordiv__ = __rfloordiv__ = _all
diff --git a/numpy/ma/tests/test_core.py b/numpy/ma/tests/test_core.py
index 64404d4dad8c..b3d42c363335 100644
--- a/numpy/ma/tests/test_core.py
+++ b/numpy/ma/tests/test_core.py
@@ -2589,11 +2589,9 @@ def __mul__(self, other):
             def __rmul__(self, other):
                 return "Me2rmul"
 
-            def __rdiv__(self, other):
+            def __rtruediv__(self, other):
                 return "Me2rdiv"
 
-            __rtruediv__ = __rdiv__
-
         me_too = MyClass2()
         assert_(a.__mul__(me_too) is NotImplemented)
         assert_(all(multiply.outer(a, me_too) == "Me2rmul"))

From 789370ae262e1369a64b66d3454a20207f6c3ea2 Mon Sep 17 00:00:00 2001
From: jorenham 
Date: Thu, 8 May 2025 17:04:23 +0200
Subject: [PATCH 175/202] MAINT: remove py2 ``__div__`` methods from
 ``lib.user_array.container``

---
 numpy/lib/_user_array_impl.py  | 10 ----------
 numpy/lib/_user_array_impl.pyi |  5 -----
 numpy/lib/mixins.py            |  1 -
 3 files changed, 16 deletions(-)

diff --git a/numpy/lib/_user_array_impl.py b/numpy/lib/_user_array_impl.py
index 9bea5a457cb0..fce4e4261453 100644
--- a/numpy/lib/_user_array_impl.py
+++ b/numpy/lib/_user_array_impl.py
@@ -88,16 +88,6 @@ def __imul__(self, other):
         multiply(self.array, other, self.array)
         return self
 
-    def __div__(self, other):
-        return self._rc(divide(self.array, asarray(other)))
-
-    def __rdiv__(self, other):
-        return self._rc(divide(asarray(other), self.array))
-
-    def __idiv__(self, other):
-        divide(self.array, other, self.array)
-        return self
-
     def __mod__(self, other):
         return self._rc(remainder(self.array, other))
 
diff --git a/numpy/lib/_user_array_impl.pyi b/numpy/lib/_user_array_impl.pyi
index 5d08dbdb40c7..13da406c99f5 100644
--- a/numpy/lib/_user_array_impl.pyi
+++ b/numpy/lib/_user_array_impl.pyi
@@ -137,11 +137,6 @@ class container(Generic[_ShapeT_co, _DTypeT_co]):
     def __rmul__(self, other: npt.ArrayLike, /) -> Incomplete: ...
     def __imul__(self, other: npt.ArrayLike, /) -> Self: ...
 
-    #
-    def __div__(self, other: npt.ArrayLike, /) -> Incomplete: ...
-    def __rdiv__(self, other: npt.ArrayLike, /) -> Incomplete: ...
-    def __idiv__(self, other: npt.ArrayLike, /) -> Self: ...
-
     #
     def __mod__(self, other: npt.ArrayLike, /) -> Incomplete: ...
     def __rmod__(self, other: npt.ArrayLike, /) -> Incomplete: ...
diff --git a/numpy/lib/mixins.py b/numpy/lib/mixins.py
index f06d54a98b65..831bb34cfb55 100644
--- a/numpy/lib/mixins.py
+++ b/numpy/lib/mixins.py
@@ -155,7 +155,6 @@ class that simply wraps a NumPy array and ensures that the result of any
     __mul__, __rmul__, __imul__ = _numeric_methods(um.multiply, 'mul')
     __matmul__, __rmatmul__, __imatmul__ = _numeric_methods(
         um.matmul, 'matmul')
-    # Python 3 does not use __div__, __rdiv__, or __idiv__
     __truediv__, __rtruediv__, __itruediv__ = _numeric_methods(
         um.true_divide, 'truediv')
     __floordiv__, __rfloordiv__, __ifloordiv__ = _numeric_methods(

From d3722a2d0b913a1174461fb1f635ca5d2091ea92 Mon Sep 17 00:00:00 2001
From: Marco Gorelli <33491632+MarcoGorelli@users.noreply.github.com>
Date: Thu, 8 May 2025 16:50:02 +0100
Subject: [PATCH 176/202] clean up docs pages

---
 doc/source/reference/maskedarray.baseclass.rst | 2 --
 1 file changed, 2 deletions(-)

diff --git a/doc/source/reference/maskedarray.baseclass.rst b/doc/source/reference/maskedarray.baseclass.rst
index bf223fbed6e9..398abd4eda63 100644
--- a/doc/source/reference/maskedarray.baseclass.rst
+++ b/doc/source/reference/maskedarray.baseclass.rst
@@ -264,7 +264,6 @@ Arithmetic:
    MaskedArray.__rsub__
    MaskedArray.__mul__
    MaskedArray.__rmul__
-   MaskedArray.__div__
    MaskedArray.__truediv__
    MaskedArray.__rtruediv__
    MaskedArray.__floordiv__
@@ -296,7 +295,6 @@ Arithmetic, in-place:
    MaskedArray.__iadd__
    MaskedArray.__isub__
    MaskedArray.__imul__
-   MaskedArray.__idiv__
    MaskedArray.__itruediv__
    MaskedArray.__ifloordiv__
    MaskedArray.__imod__

From f3540cd33d1df1183ed627cbd47c60bdcf273800 Mon Sep 17 00:00:00 2001
From: jorenham 
Date: Thu, 8 May 2025 18:29:35 +0200
Subject: [PATCH 177/202] MAINT: remove references to 256-bits extended
 precision types

---
 numpy/__init__.cython-30.pxd           |  5 -----
 numpy/__init__.pxd                     |  5 -----
 numpy/_core/include/numpy/npy_common.h | 28 --------------------------
 numpy/_core/numerictypes.py            | 14 ++++++-------
 4 files changed, 6 insertions(+), 46 deletions(-)

diff --git a/numpy/__init__.cython-30.pxd b/numpy/__init__.cython-30.pxd
index 216d9382ab4c..0ef442e5152d 100644
--- a/numpy/__init__.cython-30.pxd
+++ b/numpy/__init__.cython-30.pxd
@@ -129,27 +129,22 @@ cdef extern from "numpy/arrayobject.h":
         NPY_INT32
         NPY_INT64
         NPY_INT128
-        NPY_INT256
         NPY_UINT8
         NPY_UINT16
         NPY_UINT32
         NPY_UINT64
         NPY_UINT128
-        NPY_UINT256
         NPY_FLOAT16
         NPY_FLOAT32
         NPY_FLOAT64
         NPY_FLOAT80
         NPY_FLOAT96
         NPY_FLOAT128
-        NPY_FLOAT256
-        NPY_COMPLEX32
         NPY_COMPLEX64
         NPY_COMPLEX128
         NPY_COMPLEX160
         NPY_COMPLEX192
         NPY_COMPLEX256
-        NPY_COMPLEX512
 
         NPY_INTP
         NPY_UINTP
diff --git a/numpy/__init__.pxd b/numpy/__init__.pxd
index 11fdbec01e8b..28b572c39c4c 100644
--- a/numpy/__init__.pxd
+++ b/numpy/__init__.pxd
@@ -138,27 +138,22 @@ cdef extern from "numpy/arrayobject.h":
         NPY_INT32
         NPY_INT64
         NPY_INT128
-        NPY_INT256
         NPY_UINT8
         NPY_UINT16
         NPY_UINT32
         NPY_UINT64
         NPY_UINT128
-        NPY_UINT256
         NPY_FLOAT16
         NPY_FLOAT32
         NPY_FLOAT64
         NPY_FLOAT80
         NPY_FLOAT96
         NPY_FLOAT128
-        NPY_FLOAT256
-        NPY_COMPLEX32
         NPY_COMPLEX64
         NPY_COMPLEX128
         NPY_COMPLEX160
         NPY_COMPLEX192
         NPY_COMPLEX256
-        NPY_COMPLEX512
 
         NPY_INTP
         NPY_UINTP
diff --git a/numpy/_core/include/numpy/npy_common.h b/numpy/_core/include/numpy/npy_common.h
index 79ad8ad78cb2..fe1ca69daa23 100644
--- a/numpy/_core/include/numpy/npy_common.h
+++ b/numpy/_core/include/numpy/npy_common.h
@@ -410,9 +410,6 @@ typedef longdouble_t _Complex npy_clongdouble;
 #define NPY_MAX_INT128 NPY_LONGLONG_SUFFIX(85070591730234615865843651857942052864)
 #define NPY_MIN_INT128 (-NPY_MAX_INT128 - NPY_LONGLONG_SUFFIX(1))
 #define NPY_MAX_UINT128 NPY_ULONGLONG_SUFFIX(170141183460469231731687303715884105728)
-#define NPY_MAX_INT256 NPY_LONGLONG_SUFFIX(57896044618658097711785492504343953926634992332820282019728792003956564819967)
-#define NPY_MIN_INT256 (-NPY_MAX_INT256 - NPY_LONGLONG_SUFFIX(1))
-#define NPY_MAX_UINT256 NPY_ULONGLONG_SUFFIX(115792089237316195423570985008687907853269984665640564039457584007913129639935)
 #define NPY_MIN_DATETIME NPY_MIN_INT64
 #define NPY_MAX_DATETIME NPY_MAX_INT64
 #define NPY_MIN_TIMEDELTA NPY_MIN_INT64
@@ -611,20 +608,6 @@ typedef longdouble_t _Complex npy_clongdouble;
 #  define NPY_MAX_LONGLONG NPY_MAX_INT128
 #  define NPY_MIN_LONGLONG NPY_MIN_INT128
 #  define NPY_MAX_ULONGLONG NPY_MAX_UINT128
-#elif NPY_BITSOF_LONGLONG == 256
-#  define NPY_INT256 NPY_LONGLONG
-#  define NPY_UINT256 NPY_ULONGLONG
-        typedef npy_longlong npy_int256;
-        typedef npy_ulonglong npy_uint256;
-#  define PyInt256ScalarObject PyLongLongScalarObject
-#  define PyInt256ArrType_Type PyLongLongArrType_Type
-#  define PyUInt256ScalarObject PyULongLongScalarObject
-#  define PyUInt256ArrType_Type PyULongLongArrType_Type
-#define NPY_INT256_FMT NPY_LONGLONG_FMT
-#define NPY_UINT256_FMT NPY_ULONGLONG_FMT
-#  define NPY_MAX_LONGLONG NPY_MAX_INT256
-#  define NPY_MIN_LONGLONG NPY_MIN_INT256
-#  define NPY_MAX_ULONGLONG NPY_MAX_UINT256
 #endif
 
 #if NPY_BITSOF_INT == 8
@@ -1046,17 +1029,6 @@ typedef npy_half npy_float16;
 #define NPY_FLOAT128_FMT NPY_LONGDOUBLE_FMT
 #define NPY_COMPLEX256_FMT NPY_CLONGDOUBLE_FMT
 #endif
-#elif NPY_BITSOF_LONGDOUBLE == 256
-#define NPY_FLOAT256 NPY_LONGDOUBLE
-#define NPY_COMPLEX512 NPY_CLONGDOUBLE
-        typedef npy_longdouble npy_float256;
-        typedef npy_clongdouble npy_complex512;
-#    define PyFloat256ScalarObject PyLongDoubleScalarObject
-#    define PyComplex512ScalarObject PyCLongDoubleScalarObject
-#    define PyFloat256ArrType_Type PyLongDoubleArrType_Type
-#    define PyComplex512ArrType_Type PyCLongDoubleArrType_Type
-#define NPY_FLOAT256_FMT NPY_LONGDOUBLE_FMT
-#define NPY_COMPLEX512_FMT NPY_CLONGDOUBLE_FMT
 #endif
 
 /* datetime typedefs */
diff --git a/numpy/_core/numerictypes.py b/numpy/_core/numerictypes.py
index cb8d3c11a23f..774e57927743 100644
--- a/numpy/_core/numerictypes.py
+++ b/numpy/_core/numerictypes.py
@@ -14,8 +14,8 @@
 
     int8 int16 int32 int64 int128
     uint8 uint16 uint32 uint64 uint128
-    float16 float32 float64 float96 float128 float256
-    complex32 complex64 complex128 complex192 complex256 complex512
+    float16 float32 float64 float96 float128
+    complex64 complex128 complex192 complex256
     datetime64 timedelta64
 
     c-based names
@@ -113,12 +113,10 @@
 generic = allTypes['generic']
 
 genericTypeRank = ['bool', 'int8', 'uint8', 'int16', 'uint16',
-                   'int32', 'uint32', 'int64', 'uint64', 'int128',
-                   'uint128', 'float16',
-                   'float32', 'float64', 'float80', 'float96', 'float128',
-                   'float256',
-                   'complex32', 'complex64', 'complex128', 'complex160',
-                   'complex192', 'complex256', 'complex512', 'object']
+                   'int32', 'uint32', 'int64', 'uint64', 'int128', 'uint128',
+                   'float16', 'float32', 'float64', 'float96', 'float128',
+                   'complex64', 'complex128', 'complex192', 'complex256',
+                   'object']
 
 @set_module('numpy')
 def maximum_sctype(t):

From ce6c8e6fc2ad9273aec07432e61f03fb9d09ea9f Mon Sep 17 00:00:00 2001
From: jorenham 
Date: Thu, 8 May 2025 19:23:47 +0200
Subject: [PATCH 178/202] MAINT: remove references to ``int128`` and
 ``uint128``

---
 numpy/__init__.cython-30.pxd                  | 10 ---
 numpy/__init__.pxd                            | 10 ---
 numpy/_core/include/numpy/npy_common.h        | 65 -------------------
 numpy/_core/numerictypes.py                   |  6 +-
 numpy/_core/src/multiarray/conversion_utils.c | 10 ---
 5 files changed, 3 insertions(+), 98 deletions(-)

diff --git a/numpy/__init__.cython-30.pxd b/numpy/__init__.cython-30.pxd
index 0ef442e5152d..86c91cf617a5 100644
--- a/numpy/__init__.cython-30.pxd
+++ b/numpy/__init__.cython-30.pxd
@@ -51,15 +51,11 @@ cdef extern from "numpy/arrayobject.h":
     ctypedef signed short       npy_int16
     ctypedef signed int         npy_int32
     ctypedef signed long long   npy_int64
-    ctypedef signed long long   npy_int96
-    ctypedef signed long long   npy_int128
 
     ctypedef unsigned char      npy_uint8
     ctypedef unsigned short     npy_uint16
     ctypedef unsigned int       npy_uint32
     ctypedef unsigned long long npy_uint64
-    ctypedef unsigned long long npy_uint96
-    ctypedef unsigned long long npy_uint128
 
     ctypedef float        npy_float32
     ctypedef double       npy_float64
@@ -128,12 +124,10 @@ cdef extern from "numpy/arrayobject.h":
         NPY_INT16
         NPY_INT32
         NPY_INT64
-        NPY_INT128
         NPY_UINT8
         NPY_UINT16
         NPY_UINT32
         NPY_UINT64
-        NPY_UINT128
         NPY_FLOAT16
         NPY_FLOAT32
         NPY_FLOAT64
@@ -750,15 +744,11 @@ ctypedef npy_int8       int8_t
 ctypedef npy_int16      int16_t
 ctypedef npy_int32      int32_t
 ctypedef npy_int64      int64_t
-#ctypedef npy_int96      int96_t
-#ctypedef npy_int128     int128_t
 
 ctypedef npy_uint8      uint8_t
 ctypedef npy_uint16     uint16_t
 ctypedef npy_uint32     uint32_t
 ctypedef npy_uint64     uint64_t
-#ctypedef npy_uint96     uint96_t
-#ctypedef npy_uint128    uint128_t
 
 ctypedef npy_float32    float32_t
 ctypedef npy_float64    float64_t
diff --git a/numpy/__init__.pxd b/numpy/__init__.pxd
index 28b572c39c4c..eb0764126116 100644
--- a/numpy/__init__.pxd
+++ b/numpy/__init__.pxd
@@ -60,15 +60,11 @@ cdef extern from "numpy/arrayobject.h":
     ctypedef signed short       npy_int16
     ctypedef signed int         npy_int32
     ctypedef signed long long   npy_int64
-    ctypedef signed long long   npy_int96
-    ctypedef signed long long   npy_int128
 
     ctypedef unsigned char      npy_uint8
     ctypedef unsigned short     npy_uint16
     ctypedef unsigned int       npy_uint32
     ctypedef unsigned long long npy_uint64
-    ctypedef unsigned long long npy_uint96
-    ctypedef unsigned long long npy_uint128
 
     ctypedef float        npy_float32
     ctypedef double       npy_float64
@@ -137,12 +133,10 @@ cdef extern from "numpy/arrayobject.h":
         NPY_INT16
         NPY_INT32
         NPY_INT64
-        NPY_INT128
         NPY_UINT8
         NPY_UINT16
         NPY_UINT32
         NPY_UINT64
-        NPY_UINT128
         NPY_FLOAT16
         NPY_FLOAT32
         NPY_FLOAT64
@@ -665,15 +659,11 @@ ctypedef npy_int8       int8_t
 ctypedef npy_int16      int16_t
 ctypedef npy_int32      int32_t
 ctypedef npy_int64      int64_t
-#ctypedef npy_int96      int96_t
-#ctypedef npy_int128     int128_t
 
 ctypedef npy_uint8      uint8_t
 ctypedef npy_uint16     uint16_t
 ctypedef npy_uint32     uint32_t
 ctypedef npy_uint64     uint64_t
-#ctypedef npy_uint96     uint96_t
-#ctypedef npy_uint128    uint128_t
 
 ctypedef npy_float32    float32_t
 ctypedef npy_float64    float64_t
diff --git a/numpy/_core/include/numpy/npy_common.h b/numpy/_core/include/numpy/npy_common.h
index fe1ca69daa23..e2556a07a3ef 100644
--- a/numpy/_core/include/numpy/npy_common.h
+++ b/numpy/_core/include/numpy/npy_common.h
@@ -512,17 +512,6 @@ typedef longdouble_t _Complex npy_clongdouble;
 #define NPY_UINT64_FMT NPY_ULONG_FMT
 #define MyPyLong_FromInt64 PyLong_FromLong
 #define MyPyLong_AsInt64 PyLong_AsLong
-#elif NPY_BITSOF_LONG == 128
-#define NPY_INT128 NPY_LONG
-#define NPY_UINT128 NPY_ULONG
-        typedef long npy_int128;
-        typedef unsigned long npy_uint128;
-#define PyInt128ScalarObject PyLongScalarObject
-#define PyInt128ArrType_Type PyLongArrType_Type
-#define PyUInt128ScalarObject PyULongScalarObject
-#define PyUInt128ArrType_Type PyULongArrType_Type
-#define NPY_INT128_FMT NPY_LONG_FMT
-#define NPY_UINT128_FMT NPY_ULONG_FMT
 #endif
 
 #if NPY_BITSOF_LONGLONG == 8
@@ -592,22 +581,6 @@ typedef longdouble_t _Complex npy_clongdouble;
 #  define NPY_MAX_LONGLONG NPY_MAX_INT64
 #  define NPY_MIN_LONGLONG NPY_MIN_INT64
 #  define NPY_MAX_ULONGLONG NPY_MAX_UINT64
-#elif NPY_BITSOF_LONGLONG == 128
-#  ifndef NPY_INT128
-#    define NPY_INT128 NPY_LONGLONG
-#    define NPY_UINT128 NPY_ULONGLONG
-        typedef npy_longlong npy_int128;
-        typedef npy_ulonglong npy_uint128;
-#    define PyInt128ScalarObject PyLongLongScalarObject
-#    define PyInt128ArrType_Type PyLongLongArrType_Type
-#    define PyUInt128ScalarObject PyULongLongScalarObject
-#    define PyUInt128ArrType_Type PyULongLongArrType_Type
-#define NPY_INT128_FMT NPY_LONGLONG_FMT
-#define NPY_UINT128_FMT NPY_ULONGLONG_FMT
-#  endif
-#  define NPY_MAX_LONGLONG NPY_MAX_INT128
-#  define NPY_MIN_LONGLONG NPY_MIN_INT128
-#  define NPY_MAX_ULONGLONG NPY_MAX_UINT128
 #endif
 
 #if NPY_BITSOF_INT == 8
@@ -665,19 +638,6 @@ typedef longdouble_t _Complex npy_clongdouble;
 #    define MyPyLong_FromInt64 PyLong_FromLong
 #    define MyPyLong_AsInt64 PyLong_AsLong
 #endif
-#elif NPY_BITSOF_INT == 128
-#ifndef NPY_INT128
-#define NPY_INT128 NPY_INT
-#define NPY_UINT128 NPY_UINT
-        typedef int npy_int128;
-        typedef unsigned int npy_uint128;
-#    define PyInt128ScalarObject PyIntScalarObject
-#    define PyInt128ArrType_Type PyIntArrType_Type
-#    define PyUInt128ScalarObject PyUIntScalarObject
-#    define PyUInt128ArrType_Type PyUIntArrType_Type
-#define NPY_INT128_FMT NPY_INT_FMT
-#define NPY_UINT128_FMT NPY_UINT_FMT
-#endif
 #endif
 
 #if NPY_BITSOF_SHORT == 8
@@ -735,19 +695,6 @@ typedef longdouble_t _Complex npy_clongdouble;
 #    define MyPyLong_FromInt64 PyLong_FromLong
 #    define MyPyLong_AsInt64 PyLong_AsLong
 #endif
-#elif NPY_BITSOF_SHORT == 128
-#ifndef NPY_INT128
-#define NPY_INT128 NPY_SHORT
-#define NPY_UINT128 NPY_USHORT
-        typedef short npy_int128;
-        typedef unsigned short npy_uint128;
-#    define PyInt128ScalarObject PyShortScalarObject
-#    define PyInt128ArrType_Type PyShortArrType_Type
-#    define PyUInt128ScalarObject PyUShortScalarObject
-#    define PyUInt128ArrType_Type PyUShortArrType_Type
-#define NPY_INT128_FMT NPY_SHORT_FMT
-#define NPY_UINT128_FMT NPY_USHORT_FMT
-#endif
 #endif
 
 
@@ -807,18 +754,6 @@ typedef longdouble_t _Complex npy_clongdouble;
 #    define MyPyLong_AsInt64 PyLong_AsLong
 #endif
 #elif NPY_BITSOF_CHAR == 128
-#ifndef NPY_INT128
-#define NPY_INT128 NPY_BYTE
-#define NPY_UINT128 NPY_UBYTE
-        typedef signed char npy_int128;
-        typedef unsigned char npy_uint128;
-#    define PyInt128ScalarObject PyByteScalarObject
-#    define PyInt128ArrType_Type PyByteArrType_Type
-#    define PyUInt128ScalarObject PyUByteScalarObject
-#    define PyUInt128ArrType_Type PyUByteArrType_Type
-#define NPY_INT128_FMT NPY_BYTE_FMT
-#define NPY_UINT128_FMT NPY_UBYTE_FMT
-#endif
 #endif
 
 
diff --git a/numpy/_core/numerictypes.py b/numpy/_core/numerictypes.py
index 774e57927743..ef95137a628d 100644
--- a/numpy/_core/numerictypes.py
+++ b/numpy/_core/numerictypes.py
@@ -12,8 +12,8 @@
 
     Bit-width names
 
-    int8 int16 int32 int64 int128
-    uint8 uint16 uint32 uint64 uint128
+    int8 int16 int32 int64
+    uint8 uint16 uint32 uint64
     float16 float32 float64 float96 float128
     complex64 complex128 complex192 complex256
     datetime64 timedelta64
@@ -113,7 +113,7 @@
 generic = allTypes['generic']
 
 genericTypeRank = ['bool', 'int8', 'uint8', 'int16', 'uint16',
-                   'int32', 'uint32', 'int64', 'uint64', 'int128', 'uint128',
+                   'int32', 'uint32', 'int64', 'uint64',
                    'float16', 'float32', 'float64', 'float96', 'float128',
                    'complex64', 'complex128', 'complex192', 'complex256',
                    'object']
diff --git a/numpy/_core/src/multiarray/conversion_utils.c b/numpy/_core/src/multiarray/conversion_utils.c
index 867854324453..777a71c20423 100644
--- a/numpy/_core/src/multiarray/conversion_utils.c
+++ b/numpy/_core/src/multiarray/conversion_utils.c
@@ -1215,11 +1215,6 @@ PyArray_TypestrConvert(int itemsize, int gentype)
                 case 8:
                     newtype = NPY_INT64;
                     break;
-#ifdef NPY_INT128
-                case 16:
-                    newtype = NPY_INT128;
-                    break;
-#endif
             }
             break;
 
@@ -1237,11 +1232,6 @@ PyArray_TypestrConvert(int itemsize, int gentype)
                 case 8:
                     newtype = NPY_UINT64;
                     break;
-#ifdef NPY_INT128
-                case 16:
-                    newtype = NPY_UINT128;
-                    break;
-#endif
             }
             break;
 

From a5f915876d49387b1e8cafd6d58883f3a802822b Mon Sep 17 00:00:00 2001
From: Nathan Goldbaum 
Date: Thu, 8 May 2025 08:26:13 -0600
Subject: [PATCH 179/202] MNT: add support for 3.14.0b1

---
 numpy/_core/src/multiarray/temp_elide.c | 39 ++++---------------------
 pytest.ini                              |  3 ++
 2 files changed, 8 insertions(+), 34 deletions(-)

diff --git a/numpy/_core/src/multiarray/temp_elide.c b/numpy/_core/src/multiarray/temp_elide.c
index 667ba2b443ef..9236476c4213 100644
--- a/numpy/_core/src/multiarray/temp_elide.c
+++ b/numpy/_core/src/multiarray/temp_elide.c
@@ -62,13 +62,6 @@
 
 #include 
 
-#if PY_VERSION_HEX >= 0x030E00A7 && !defined(PYPY_VERSION)
-#define Py_BUILD_CORE
-#include "internal/pycore_frame.h"
-#include "internal/pycore_interpframe.h"
-#undef Py_BUILD_CORE
-#endif
-
 /* 1 prints elided operations, 2 prints stacktraces */
 #define NPY_ELIDE_DEBUG 0
 #define NPY_MAX_STACKSIZE 10
@@ -119,33 +112,11 @@ find_addr(void * addresses[], npy_intp naddr, void * addr)
 static int
 check_unique_temporary(PyObject *lhs)
 {
-#if PY_VERSION_HEX >= 0x030E00A7 && !defined(PYPY_VERSION)
-    // In Python 3.14.0a7 and later, a reference count of one doesn't guarantee
-    // that an object is a unique temporary variable. We scan the top of the
-    // interpreter stack to check if the object exists as an "owned" reference
-    // in the temporary stack.
-    PyFrameObject *frame = PyEval_GetFrame();
-    if (frame == NULL) {
-        return 0;
-    }
-    _PyInterpreterFrame *f = frame->f_frame;
-    _PyStackRef *base = _PyFrame_Stackbase(f);
-    _PyStackRef *stackpointer = f->stackpointer;
-    int found_once = 0;
-    while (stackpointer > base) {
-        stackpointer--;
-        PyObject *obj = PyStackRef_AsPyObjectBorrow(*stackpointer);
-        if (obj == lhs) {
-            if (!found_once && PyStackRef_IsHeapSafe(*stackpointer)) {
-                found_once = 1;
-            }
-            else {
-                return 0;
-            }
-        }
-        return found_once;
-    }
-    return 0;
+#if PY_VERSION_HEX == 0x030E00A7 && !defined(PYPY_VERSION)
+#error "NumPy is broken on CPython 3.14.0a7, please update to a newer version"
+#elif PY_VERSION_HEX >= 0x030E00B1 && !defined(PYPY_VERSION)
+    // see https://github.com/python/cpython/issues/133164
+    return PyUnstable_Object_IsUniqueReferencedTemporary(lhs);
 #else
     return 1;
 #endif
diff --git a/pytest.ini b/pytest.ini
index a0db548381f2..132af0bb78ab 100644
--- a/pytest.ini
+++ b/pytest.ini
@@ -27,3 +27,6 @@ filterwarnings =
     ignore:\n\n  `numpy.distutils`:DeprecationWarning
 # Ignore DeprecationWarning from typing.mypy_plugin
     ignore:`numpy.typing.mypy_plugin` is deprecated:DeprecationWarning
+# Ignore DeprecationWarning from struct module
+# see https://github.com/numpy/numpy/issues/28926
+    ignore:Due to \'_pack_\', the
\ No newline at end of file

From 1245ec71d48e35278a205eff4e1ba636560d615a Mon Sep 17 00:00:00 2001
From: jorenham 
Date: Fri, 9 May 2025 03:16:36 +0200
Subject: [PATCH 180/202] TYP: specific mypy error codes for the "fail"
 type-tests

---
 numpy/typing/tests/data/fail/arithmetic.pyi   | 140 ++++-----
 .../tests/data/fail/array_constructors.pyi    |  40 +--
 numpy/typing/tests/data/fail/array_like.pyi   |  12 +-
 numpy/typing/tests/data/fail/array_pad.pyi    |   2 +-
 numpy/typing/tests/data/fail/arrayprint.pyi   |  12 +-
 numpy/typing/tests/data/fail/arrayterator.pyi |  16 +-
 numpy/typing/tests/data/fail/bitwise_ops.pyi  |  16 +-
 numpy/typing/tests/data/fail/char.pyi         | 122 ++++----
 numpy/typing/tests/data/fail/chararray.pyi    | 112 +++----
 numpy/typing/tests/data/fail/comparisons.pyi  |  28 +-
 numpy/typing/tests/data/fail/constants.pyi    |   2 +-
 numpy/typing/tests/data/fail/datasource.pyi   |  14 +-
 numpy/typing/tests/data/fail/dtype.pyi        |   6 +-
 numpy/typing/tests/data/fail/einsumfunc.pyi   |   8 +-
 numpy/typing/tests/data/fail/flatiter.pyi     |  16 +-
 numpy/typing/tests/data/fail/fromnumeric.pyi  | 284 ++++++++----------
 numpy/typing/tests/data/fail/histograms.pyi   |   8 +-
 numpy/typing/tests/data/fail/index_tricks.pyi |  18 +-
 .../tests/data/fail/lib_function_base.pyi     |  90 +++---
 .../typing/tests/data/fail/lib_polynomial.pyi |  28 +-
 numpy/typing/tests/data/fail/lib_utils.pyi    |   2 +-
 numpy/typing/tests/data/fail/lib_version.pyi  |   4 +-
 numpy/typing/tests/data/fail/linalg.pyi       |  46 +--
 numpy/typing/tests/data/fail/ma.pyi           | 199 ++++++------
 numpy/typing/tests/data/fail/memmap.pyi       |   4 +-
 numpy/typing/tests/data/fail/modules.pyi      |  18 +-
 numpy/typing/tests/data/fail/multiarray.pyi   |  44 +--
 numpy/typing/tests/data/fail/ndarray.pyi      |   2 +-
 numpy/typing/tests/data/fail/ndarray_misc.pyi |  36 +--
 numpy/typing/tests/data/fail/nditer.pyi       |  10 +-
 .../tests/data/fail/nested_sequence.pyi       |  10 +-
 numpy/typing/tests/data/fail/npyio.pyi        |  15 +-
 numpy/typing/tests/data/fail/numerictypes.pyi |   4 +-
 numpy/typing/tests/data/fail/random.pyi       |  88 +++---
 numpy/typing/tests/data/fail/rec.pyi          |  16 +-
 numpy/typing/tests/data/fail/scalars.pyi      | 105 ++++---
 numpy/typing/tests/data/fail/shape.pyi        |   2 +-
 numpy/typing/tests/data/fail/shape_base.pyi   |   2 +-
 .../typing/tests/data/fail/stride_tricks.pyi  |   6 +-
 numpy/typing/tests/data/fail/strings.pyi      |  99 +++---
 numpy/typing/tests/data/fail/testing.pyi      |  34 +--
 numpy/typing/tests/data/fail/twodim_base.pyi  |  24 +-
 numpy/typing/tests/data/fail/type_check.pyi   |  12 +-
 numpy/typing/tests/data/fail/ufunc_config.pyi |  10 +-
 numpy/typing/tests/data/fail/ufunclike.pyi    |  22 +-
 numpy/typing/tests/data/fail/ufuncs.pyi       |  16 +-
 .../tests/data/fail/warnings_and_errors.pyi   |   6 +-
 47 files changed, 884 insertions(+), 926 deletions(-)

diff --git a/numpy/typing/tests/data/fail/arithmetic.pyi b/numpy/typing/tests/data/fail/arithmetic.pyi
index 3d250c493cfb..7cc49b93ba2f 100644
--- a/numpy/typing/tests/data/fail/arithmetic.pyi
+++ b/numpy/typing/tests/data/fail/arithmetic.pyi
@@ -28,96 +28,96 @@ AR_LIKE_M: list[np.datetime64]
 # Array subtraction
 
 # NOTE: mypys `NoReturn` errors are, unfortunately, not that great
-_1 = AR_b - AR_LIKE_b  # E: Need type annotation
-_2 = AR_LIKE_b - AR_b  # E: Need type annotation
-AR_i - bytes()  # E: No overload variant
+_1 = AR_b - AR_LIKE_b  # type: ignore[var-annotated]
+_2 = AR_LIKE_b - AR_b  # type: ignore[var-annotated]
+AR_i - bytes()  # type: ignore[operator]
 
-AR_f - AR_LIKE_m  # E: Unsupported operand types
-AR_f - AR_LIKE_M  # E: Unsupported operand types
-AR_c - AR_LIKE_m  # E: Unsupported operand types
-AR_c - AR_LIKE_M  # E: Unsupported operand types
+AR_f - AR_LIKE_m  # type: ignore[operator]
+AR_f - AR_LIKE_M  # type: ignore[operator]
+AR_c - AR_LIKE_m  # type: ignore[operator]
+AR_c - AR_LIKE_M  # type: ignore[operator]
 
-AR_m - AR_LIKE_f  # E: Unsupported operand types
-AR_M - AR_LIKE_f  # E: Unsupported operand types
-AR_m - AR_LIKE_c  # E: Unsupported operand types
-AR_M - AR_LIKE_c  # E: Unsupported operand types
+AR_m - AR_LIKE_f  # type: ignore[operator]
+AR_M - AR_LIKE_f  # type: ignore[operator]
+AR_m - AR_LIKE_c  # type: ignore[operator]
+AR_M - AR_LIKE_c  # type: ignore[operator]
 
-AR_m - AR_LIKE_M  # E: Unsupported operand types
-AR_LIKE_m - AR_M  # E: Unsupported operand types
+AR_m - AR_LIKE_M  # type: ignore[operator]
+AR_LIKE_m - AR_M  # type: ignore[operator]
 
 # array floor division
 
-AR_M // AR_LIKE_b  # E: Unsupported operand types
-AR_M // AR_LIKE_u  # E: Unsupported operand types
-AR_M // AR_LIKE_i  # E: Unsupported operand types
-AR_M // AR_LIKE_f  # E: Unsupported operand types
-AR_M // AR_LIKE_c  # E: Unsupported operand types
-AR_M // AR_LIKE_m  # E: Unsupported operand types
-AR_M // AR_LIKE_M  # E: Unsupported operand types
-
-AR_b // AR_LIKE_M  # E: Unsupported operand types
-AR_u // AR_LIKE_M  # E: Unsupported operand types
-AR_i // AR_LIKE_M  # E: Unsupported operand types
-AR_f // AR_LIKE_M  # E: Unsupported operand types
-AR_c // AR_LIKE_M  # E: Unsupported operand types
-AR_m // AR_LIKE_M  # E: Unsupported operand types
-AR_M // AR_LIKE_M  # E: Unsupported operand types
-
-_3 = AR_m // AR_LIKE_b  # E: Need type annotation
-AR_m // AR_LIKE_c  # E: Unsupported operand types
-
-AR_b // AR_LIKE_m  # E: Unsupported operand types
-AR_u // AR_LIKE_m  # E: Unsupported operand types
-AR_i // AR_LIKE_m  # E: Unsupported operand types
-AR_f // AR_LIKE_m  # E: Unsupported operand types
-AR_c // AR_LIKE_m  # E: Unsupported operand types
+AR_M // AR_LIKE_b  # type: ignore[operator]
+AR_M // AR_LIKE_u  # type: ignore[operator]
+AR_M // AR_LIKE_i  # type: ignore[operator]
+AR_M // AR_LIKE_f  # type: ignore[operator]
+AR_M // AR_LIKE_c  # type: ignore[operator]
+AR_M // AR_LIKE_m  # type: ignore[operator]
+AR_M // AR_LIKE_M  # type: ignore[operator]
+
+AR_b // AR_LIKE_M  # type: ignore[operator]
+AR_u // AR_LIKE_M  # type: ignore[operator]
+AR_i // AR_LIKE_M  # type: ignore[operator]
+AR_f // AR_LIKE_M  # type: ignore[operator]
+AR_c // AR_LIKE_M  # type: ignore[operator]
+AR_m // AR_LIKE_M  # type: ignore[operator]
+AR_M // AR_LIKE_M  # type: ignore[operator]
+
+_3 = AR_m // AR_LIKE_b  # type: ignore[var-annotated]
+AR_m // AR_LIKE_c  # type: ignore[operator]
+
+AR_b // AR_LIKE_m  # type: ignore[operator]
+AR_u // AR_LIKE_m  # type: ignore[operator]
+AR_i // AR_LIKE_m  # type: ignore[operator]
+AR_f // AR_LIKE_m  # type: ignore[operator]
+AR_c // AR_LIKE_m  # type: ignore[operator]
 
 # Array multiplication
 
-AR_b *= AR_LIKE_u  # E: incompatible type
-AR_b *= AR_LIKE_i  # E: incompatible type
-AR_b *= AR_LIKE_f  # E: incompatible type
-AR_b *= AR_LIKE_c  # E: incompatible type
-AR_b *= AR_LIKE_m  # E: incompatible type
+AR_b *= AR_LIKE_u  # type: ignore[arg-type]
+AR_b *= AR_LIKE_i  # type: ignore[arg-type]
+AR_b *= AR_LIKE_f  # type: ignore[arg-type]
+AR_b *= AR_LIKE_c  # type: ignore[arg-type]
+AR_b *= AR_LIKE_m  # type: ignore[arg-type]
 
-AR_u *= AR_LIKE_i  # E: incompatible type
-AR_u *= AR_LIKE_f  # E: incompatible type
-AR_u *= AR_LIKE_c  # E: incompatible type
-AR_u *= AR_LIKE_m  # E: incompatible type
+AR_u *= AR_LIKE_i  # type: ignore[arg-type]
+AR_u *= AR_LIKE_f  # type: ignore[arg-type]
+AR_u *= AR_LIKE_c  # type: ignore[arg-type]
+AR_u *= AR_LIKE_m  # type: ignore[arg-type]
 
-AR_i *= AR_LIKE_f  # E: incompatible type
-AR_i *= AR_LIKE_c  # E: incompatible type
-AR_i *= AR_LIKE_m  # E: incompatible type
+AR_i *= AR_LIKE_f  # type: ignore[arg-type]
+AR_i *= AR_LIKE_c  # type: ignore[arg-type]
+AR_i *= AR_LIKE_m  # type: ignore[arg-type]
 
-AR_f *= AR_LIKE_c  # E: incompatible type
-AR_f *= AR_LIKE_m  # E: incompatible type
+AR_f *= AR_LIKE_c  # type: ignore[arg-type]
+AR_f *= AR_LIKE_m  # type: ignore[arg-type]
 
 # Array power
 
-AR_b **= AR_LIKE_b  # E: Invalid self argument
-AR_b **= AR_LIKE_u  # E: Invalid self argument
-AR_b **= AR_LIKE_i  # E: Invalid self argument
-AR_b **= AR_LIKE_f  # E: Invalid self argument
-AR_b **= AR_LIKE_c  # E: Invalid self argument
+AR_b **= AR_LIKE_b  # type: ignore[misc]
+AR_b **= AR_LIKE_u  # type: ignore[misc]
+AR_b **= AR_LIKE_i  # type: ignore[misc]
+AR_b **= AR_LIKE_f  # type: ignore[misc]
+AR_b **= AR_LIKE_c  # type: ignore[misc]
 
-AR_u **= AR_LIKE_i  # E: incompatible type
-AR_u **= AR_LIKE_f  # E: incompatible type
-AR_u **= AR_LIKE_c  # E: incompatible type
+AR_u **= AR_LIKE_i  # type: ignore[arg-type]
+AR_u **= AR_LIKE_f  # type: ignore[arg-type]
+AR_u **= AR_LIKE_c  # type: ignore[arg-type]
 
-AR_i **= AR_LIKE_f  # E: incompatible type
-AR_i **= AR_LIKE_c  # E: incompatible type
+AR_i **= AR_LIKE_f  # type: ignore[arg-type]
+AR_i **= AR_LIKE_c  # type: ignore[arg-type]
 
-AR_f **= AR_LIKE_c  # E: incompatible type
+AR_f **= AR_LIKE_c  # type: ignore[arg-type]
 
 # Scalars
 
-b_ - b_  # E: No overload variant
+b_ - b_  # type: ignore[call-overload]
 
-dt + dt  # E: Unsupported operand types
-td - dt  # E: Unsupported operand types
-td % 1  # E: Unsupported operand types
-td / dt  # E: No overload
-td % dt  # E: Unsupported operand types
+dt + dt  # type: ignore[operator]
+td - dt  # type: ignore[operator]
+td % 1  # type: ignore[operator]
+td / dt  # type: ignore[operator]
+td % dt  # type: ignore[operator]
 
--b_  # E: Unsupported operand type
-+b_  # E: Unsupported operand type
+-b_  # type: ignore[operator]
++b_  # type: ignore[operator]
diff --git a/numpy/typing/tests/data/fail/array_constructors.pyi b/numpy/typing/tests/data/fail/array_constructors.pyi
index 27eefe3c918d..cadc2ae595e7 100644
--- a/numpy/typing/tests/data/fail/array_constructors.pyi
+++ b/numpy/typing/tests/data/fail/array_constructors.pyi
@@ -4,31 +4,31 @@ import numpy.typing as npt
 a: npt.NDArray[np.float64]
 generator = (i for i in range(10))
 
-np.require(a, requirements=1)  # E: No overload variant
-np.require(a, requirements="TEST")  # E: incompatible type
+np.require(a, requirements=1)  # type: ignore[call-overload]
+np.require(a, requirements="TEST")  # type: ignore[arg-type]
 
-np.zeros("test")  # E: incompatible type
-np.zeros()  # E: require at least one argument
+np.zeros("test")  # type: ignore[arg-type]
+np.zeros()  # type: ignore[call-overload]
 
-np.ones("test")  # E: incompatible type
-np.ones()  # E: require at least one argument
+np.ones("test")  # type: ignore[arg-type]
+np.ones()  # type: ignore[call-overload]
 
-np.array(0, float, True)  # E: No overload variant
+np.array(0, float, True)  # type: ignore[call-overload]
 
-np.linspace(None, 'bob')  # E: No overload variant
-np.linspace(0, 2, num=10.0)  # E: No overload variant
-np.linspace(0, 2, endpoint='True')  # E: No overload variant
-np.linspace(0, 2, retstep=b'False')  # E: No overload variant
-np.linspace(0, 2, dtype=0)  # E: No overload variant
-np.linspace(0, 2, axis=None)  # E: No overload variant
+np.linspace(None, 'bob')  # type: ignore[call-overload]
+np.linspace(0, 2, num=10.0)  # type: ignore[call-overload]
+np.linspace(0, 2, endpoint='True')  # type: ignore[call-overload]
+np.linspace(0, 2, retstep=b'False')  # type: ignore[call-overload]
+np.linspace(0, 2, dtype=0)  # type: ignore[call-overload]
+np.linspace(0, 2, axis=None)  # type: ignore[call-overload]
 
-np.logspace(None, 'bob')  # E: No overload variant
-np.logspace(0, 2, base=None)  # E: No overload variant
+np.logspace(None, 'bob')  # type: ignore[call-overload]
+np.logspace(0, 2, base=None)  # type: ignore[call-overload]
 
-np.geomspace(None, 'bob')  # E: No overload variant
+np.geomspace(None, 'bob')  # type: ignore[call-overload]
 
-np.stack(generator)  # E: No overload variant
-np.hstack({1, 2})  # E: No overload variant
-np.vstack(1)  # E: No overload variant
+np.stack(generator)  # type: ignore[call-overload]
+np.hstack({1, 2})  # type: ignore[call-overload]
+np.vstack(1)  # type: ignore[call-overload]
 
-np.array([1], like=1)  # E: No overload variant
+np.array([1], like=1)  # type: ignore[call-overload]
diff --git a/numpy/typing/tests/data/fail/array_like.pyi b/numpy/typing/tests/data/fail/array_like.pyi
index 6b6c16dd6e70..4e37354e8eba 100644
--- a/numpy/typing/tests/data/fail/array_like.pyi
+++ b/numpy/typing/tests/data/fail/array_like.pyi
@@ -3,13 +3,13 @@ from numpy._typing import ArrayLike
 
 class A: ...
 
-x1: ArrayLike = (i for i in range(10))  # E: Incompatible types in assignment
-x2: ArrayLike = A()  # E: Incompatible types in assignment
-x3: ArrayLike = {1: "foo", 2: "bar"}  # E: Incompatible types in assignment
+x1: ArrayLike = (i for i in range(10))  # type: ignore[assignment]
+x2: ArrayLike = A()  # type: ignore[assignment]
+x3: ArrayLike = {1: "foo", 2: "bar"}  # type: ignore[assignment]
 
 scalar = np.int64(1)
-scalar.__array__(dtype=np.float64)  # E: No overload variant
+scalar.__array__(dtype=np.float64)  # type: ignore[call-overload]
 array = np.array([1])
-array.__array__(dtype=np.float64)  # E: No overload variant
+array.__array__(dtype=np.float64)  # type: ignore[call-overload]
 
-array.setfield(np.eye(1), np.int32, (0, 1))  # E: No overload variant
+array.setfield(np.eye(1), np.int32, (0, 1))  # type: ignore[arg-type]
diff --git a/numpy/typing/tests/data/fail/array_pad.pyi b/numpy/typing/tests/data/fail/array_pad.pyi
index 2be51a87181d..42e61c8d70d6 100644
--- a/numpy/typing/tests/data/fail/array_pad.pyi
+++ b/numpy/typing/tests/data/fail/array_pad.pyi
@@ -3,4 +3,4 @@ import numpy.typing as npt
 
 AR_i8: npt.NDArray[np.int64]
 
-np.pad(AR_i8, 2, mode="bob")  # E: No overload variant
+np.pad(AR_i8, 2, mode="bob")  # type: ignore[call-overload]
diff --git a/numpy/typing/tests/data/fail/arrayprint.pyi b/numpy/typing/tests/data/fail/arrayprint.pyi
index 486c11e79868..224a4105b8a6 100644
--- a/numpy/typing/tests/data/fail/arrayprint.pyi
+++ b/numpy/typing/tests/data/fail/arrayprint.pyi
@@ -8,9 +8,9 @@ AR: npt.NDArray[np.float64]
 func1: Callable[[Any], str]
 func2: Callable[[np.integer], str]
 
-np.array2string(AR, style=None)  # E: No overload variant
-np.array2string(AR, legacy="1.14")  # E: No overload variant
-np.array2string(AR, sign="*")  # E: No overload variant
-np.array2string(AR, floatmode="default")  # E: No overload variant
-np.array2string(AR, formatter={"A": func1})  # E: No overload variant
-np.array2string(AR, formatter={"float": func2})  # E: No overload variant
+np.array2string(AR, style=None)  # type: ignore[call-overload]
+np.array2string(AR, legacy="1.14")  # type: ignore[call-overload]
+np.array2string(AR, sign="*")  # type: ignore[call-overload]
+np.array2string(AR, floatmode="default")  # type: ignore[call-overload]
+np.array2string(AR, formatter={"A": func1})  # type: ignore[call-overload]
+np.array2string(AR, formatter={"float": func2})  # type: ignore[call-overload]
diff --git a/numpy/typing/tests/data/fail/arrayterator.pyi b/numpy/typing/tests/data/fail/arrayterator.pyi
index 00280b3a6a2c..8d2295a5859f 100644
--- a/numpy/typing/tests/data/fail/arrayterator.pyi
+++ b/numpy/typing/tests/data/fail/arrayterator.pyi
@@ -4,11 +4,11 @@ import numpy.typing as npt
 AR_i8: npt.NDArray[np.int64]
 ar_iter = np.lib.Arrayterator(AR_i8)
 
-np.lib.Arrayterator(np.int64())  # E: incompatible type
-ar_iter.shape = (10, 5)  # E: is read-only
-ar_iter[None]  # E: Invalid index type
-ar_iter[None, 1]  # E: Invalid index type
-ar_iter[np.intp()]  # E: Invalid index type
-ar_iter[np.intp(), ...]  # E: Invalid index type
-ar_iter[AR_i8]  # E: Invalid index type
-ar_iter[AR_i8, :]  # E: Invalid index type
+np.lib.Arrayterator(np.int64())  # type: ignore[arg-type]
+ar_iter.shape = (10, 5)  # type: ignore[misc]
+ar_iter[None]  # type: ignore[index]
+ar_iter[None, 1]  # type: ignore[index]
+ar_iter[np.intp()]  # type: ignore[index]
+ar_iter[np.intp(), ...]  # type: ignore[index]
+ar_iter[AR_i8]  # type: ignore[index]
+ar_iter[AR_i8, :]  # type: ignore[index]
diff --git a/numpy/typing/tests/data/fail/bitwise_ops.pyi b/numpy/typing/tests/data/fail/bitwise_ops.pyi
index 13b47c485b41..3538ec7d64c7 100644
--- a/numpy/typing/tests/data/fail/bitwise_ops.pyi
+++ b/numpy/typing/tests/data/fail/bitwise_ops.pyi
@@ -8,14 +8,10 @@ i = int()
 
 f8 = np.float64()
 
-b_ >> f8  # E: No overload variant
-i8 << f8  # E: No overload variant
-i | f8  # E: Unsupported operand types
-i8 ^ f8  # E: No overload variant
-u8 & f8  # E: No overload variant
-~f8  # E: Unsupported operand type
+b_ >> f8  # type: ignore[call-overload]
+i8 << f8  # type: ignore[call-overload]
+i | f8  # type: ignore[operator]
+i8 ^ f8  # type: ignore[call-overload]
+u8 & f8  # type: ignore[call-overload]
+~f8  # type: ignore[operator]
 # TODO: Certain mixes like i4 << u8 go to float and thus should fail
-
-# mypys' error message for `NoReturn` is unfortunately pretty bad
-# TODO: Re-enable this once we add support for numerical precision for `number`s
-# a = u8 | 0  # E: Need type annotation
diff --git a/numpy/typing/tests/data/fail/char.pyi b/numpy/typing/tests/data/fail/char.pyi
index 542a273baef5..62c4475c29be 100644
--- a/numpy/typing/tests/data/fail/char.pyi
+++ b/numpy/typing/tests/data/fail/char.pyi
@@ -4,66 +4,62 @@ import numpy.typing as npt
 AR_U: npt.NDArray[np.str_]
 AR_S: npt.NDArray[np.bytes_]
 
-np.char.equal(AR_U, AR_S)  # E: incompatible type
-
-np.char.not_equal(AR_U, AR_S)  # E: incompatible type
-
-np.char.greater_equal(AR_U, AR_S)  # E: incompatible type
-
-np.char.less_equal(AR_U, AR_S)  # E: incompatible type
-
-np.char.greater(AR_U, AR_S)  # E: incompatible type
-
-np.char.less(AR_U, AR_S)  # E: incompatible type
-
-np.char.encode(AR_S)  # E: incompatible type
-np.char.decode(AR_U)  # E: incompatible type
-
-np.char.join(AR_U, b"_")  # E: incompatible type
-np.char.join(AR_S, "_")  # E: incompatible type
-
-np.char.ljust(AR_U, 5, fillchar=b"a")  # E: incompatible type
-np.char.ljust(AR_S, 5, fillchar="a")  # E: incompatible type
-np.char.rjust(AR_U, 5, fillchar=b"a")  # E: incompatible type
-np.char.rjust(AR_S, 5, fillchar="a")  # E: incompatible type
-
-np.char.lstrip(AR_U, chars=b"a")  # E: incompatible type
-np.char.lstrip(AR_S, chars="a")  # E: incompatible type
-np.char.strip(AR_U, chars=b"a")  # E: incompatible type
-np.char.strip(AR_S, chars="a")  # E: incompatible type
-np.char.rstrip(AR_U, chars=b"a")  # E: incompatible type
-np.char.rstrip(AR_S, chars="a")  # E: incompatible type
-
-np.char.partition(AR_U, b"a")  # E: incompatible type
-np.char.partition(AR_S, "a")  # E: incompatible type
-np.char.rpartition(AR_U, b"a")  # E: incompatible type
-np.char.rpartition(AR_S, "a")  # E: incompatible type
-
-np.char.replace(AR_U, b"_", b"-")  # E: incompatible type
-np.char.replace(AR_S, "_", "-")  # E: incompatible type
-
-np.char.split(AR_U, b"_")  # E: incompatible type
-np.char.split(AR_S, "_")  # E: incompatible type
-np.char.rsplit(AR_U, b"_")  # E: incompatible type
-np.char.rsplit(AR_S, "_")  # E: incompatible type
-
-np.char.count(AR_U, b"a", start=[1, 2, 3])  # E: incompatible type
-np.char.count(AR_S, "a", end=9)  # E: incompatible type
-
-np.char.endswith(AR_U, b"a", start=[1, 2, 3])  # E: incompatible type
-np.char.endswith(AR_S, "a", end=9)  # E: incompatible type
-np.char.startswith(AR_U, b"a", start=[1, 2, 3])  # E: incompatible type
-np.char.startswith(AR_S, "a", end=9)  # E: incompatible type
-
-np.char.find(AR_U, b"a", start=[1, 2, 3])  # E: incompatible type
-np.char.find(AR_S, "a", end=9)  # E: incompatible type
-np.char.rfind(AR_U, b"a", start=[1, 2, 3])  # E: incompatible type
-np.char.rfind(AR_S, "a", end=9)  # E: incompatible type
-
-np.char.index(AR_U, b"a", start=[1, 2, 3])  # E: incompatible type
-np.char.index(AR_S, "a", end=9)  # E: incompatible type
-np.char.rindex(AR_U, b"a", start=[1, 2, 3])  # E: incompatible type
-np.char.rindex(AR_S, "a", end=9)  # E: incompatible type
-
-np.char.isdecimal(AR_S)  # E: incompatible type
-np.char.isnumeric(AR_S)  # E: incompatible type
+np.char.equal(AR_U, AR_S)  # type: ignore[arg-type]
+np.char.not_equal(AR_U, AR_S)  # type: ignore[arg-type]
+
+np.char.greater_equal(AR_U, AR_S)  # type: ignore[arg-type]
+np.char.less_equal(AR_U, AR_S)  # type: ignore[arg-type]
+np.char.greater(AR_U, AR_S)  # type: ignore[arg-type]
+np.char.less(AR_U, AR_S)  # type: ignore[arg-type]
+
+np.char.encode(AR_S)  # type: ignore[arg-type]
+np.char.decode(AR_U)  # type: ignore[arg-type]
+
+np.char.join(AR_U, b"_")  # type: ignore[arg-type]
+np.char.join(AR_S, "_")  # type: ignore[arg-type]
+
+np.char.ljust(AR_U, 5, fillchar=b"a")  # type: ignore[arg-type]
+np.char.ljust(AR_S, 5, fillchar="a")  # type: ignore[arg-type]
+np.char.rjust(AR_U, 5, fillchar=b"a")  # type: ignore[arg-type]
+np.char.rjust(AR_S, 5, fillchar="a")  # type: ignore[arg-type]
+
+np.char.lstrip(AR_U, chars=b"a")  # type: ignore[arg-type]
+np.char.lstrip(AR_S, chars="a")  # type: ignore[arg-type]
+np.char.strip(AR_U, chars=b"a")  # type: ignore[arg-type]
+np.char.strip(AR_S, chars="a")  # type: ignore[arg-type]
+np.char.rstrip(AR_U, chars=b"a")  # type: ignore[arg-type]
+np.char.rstrip(AR_S, chars="a")  # type: ignore[arg-type]
+
+np.char.partition(AR_U, b"a")  # type: ignore[arg-type]
+np.char.partition(AR_S, "a")  # type: ignore[arg-type]
+np.char.rpartition(AR_U, b"a")  # type: ignore[arg-type]
+np.char.rpartition(AR_S, "a")  # type: ignore[arg-type]
+
+np.char.replace(AR_U, b"_", b"-")  # type: ignore[arg-type]
+np.char.replace(AR_S, "_", "-")  # type: ignore[arg-type]
+
+np.char.split(AR_U, b"_")  # type: ignore[arg-type]
+np.char.split(AR_S, "_")  # type: ignore[arg-type]
+np.char.rsplit(AR_U, b"_")  # type: ignore[arg-type]
+np.char.rsplit(AR_S, "_")  # type: ignore[arg-type]
+
+np.char.count(AR_U, b"a", start=[1, 2, 3])  # type: ignore[arg-type]
+np.char.count(AR_S, "a", end=9)  # type: ignore[arg-type]
+
+np.char.endswith(AR_U, b"a", start=[1, 2, 3])  # type: ignore[arg-type]
+np.char.endswith(AR_S, "a", end=9)  # type: ignore[arg-type]
+np.char.startswith(AR_U, b"a", start=[1, 2, 3])  # type: ignore[arg-type]
+np.char.startswith(AR_S, "a", end=9)  # type: ignore[arg-type]
+
+np.char.find(AR_U, b"a", start=[1, 2, 3])  # type: ignore[arg-type]
+np.char.find(AR_S, "a", end=9)  # type: ignore[arg-type]
+np.char.rfind(AR_U, b"a", start=[1, 2, 3])  # type: ignore[arg-type]
+np.char.rfind(AR_S, "a", end=9)  # type: ignore[arg-type]
+
+np.char.index(AR_U, b"a", start=[1, 2, 3])  # type: ignore[arg-type]
+np.char.index(AR_S, "a", end=9)  # type: ignore[arg-type]
+np.char.rindex(AR_U, b"a", start=[1, 2, 3])  # type: ignore[arg-type]
+np.char.rindex(AR_S, "a", end=9)  # type: ignore[arg-type]
+
+np.char.isdecimal(AR_S)  # type: ignore[arg-type]
+np.char.isnumeric(AR_S)  # type: ignore[arg-type]
diff --git a/numpy/typing/tests/data/fail/chararray.pyi b/numpy/typing/tests/data/fail/chararray.pyi
index e484b644e4b8..54b147e0e6c0 100644
--- a/numpy/typing/tests/data/fail/chararray.pyi
+++ b/numpy/typing/tests/data/fail/chararray.pyi
@@ -3,59 +3,59 @@ import numpy as np
 AR_U: np.char.chararray[tuple[int, ...], np.dtype[np.str_]]
 AR_S: np.char.chararray[tuple[int, ...], np.dtype[np.bytes_]]
 
-AR_S.encode()  # E: Invalid self argument
-AR_U.decode()  # E: Invalid self argument
-
-AR_U.join(b"_")  # E: incompatible type
-AR_S.join("_")  # E: incompatible type
-
-AR_U.ljust(5, fillchar=b"a")  # E: incompatible type
-AR_S.ljust(5, fillchar="a")  # E: incompatible type
-AR_U.rjust(5, fillchar=b"a")  # E: incompatible type
-AR_S.rjust(5, fillchar="a")  # E: incompatible type
-
-AR_U.lstrip(chars=b"a")  # E: incompatible type
-AR_S.lstrip(chars="a")  # E: incompatible type
-AR_U.strip(chars=b"a")  # E: incompatible type
-AR_S.strip(chars="a")  # E: incompatible type
-AR_U.rstrip(chars=b"a")  # E: incompatible type
-AR_S.rstrip(chars="a")  # E: incompatible type
-
-AR_U.partition(b"a")  # E: incompatible type
-AR_S.partition("a")  # E: incompatible type
-AR_U.rpartition(b"a")  # E: incompatible type
-AR_S.rpartition("a")  # E: incompatible type
-
-AR_U.replace(b"_", b"-")  # E: incompatible type
-AR_S.replace("_", "-")  # E: incompatible type
-
-AR_U.split(b"_")  # E: incompatible type
-AR_S.split("_")  # E: incompatible type
-AR_S.split(1)  # E: incompatible type
-AR_U.rsplit(b"_")  # E: incompatible type
-AR_S.rsplit("_")  # E: incompatible type
-
-AR_U.count(b"a", start=[1, 2, 3])  # E: incompatible type
-AR_S.count("a", end=9)  # E: incompatible type
-
-AR_U.endswith(b"a", start=[1, 2, 3])  # E: incompatible type
-AR_S.endswith("a", end=9)  # E: incompatible type
-AR_U.startswith(b"a", start=[1, 2, 3])  # E: incompatible type
-AR_S.startswith("a", end=9)  # E: incompatible type
-
-AR_U.find(b"a", start=[1, 2, 3])  # E: incompatible type
-AR_S.find("a", end=9)  # E: incompatible type
-AR_U.rfind(b"a", start=[1, 2, 3])  # E: incompatible type
-AR_S.rfind("a", end=9)  # E: incompatible type
-
-AR_U.index(b"a", start=[1, 2, 3])  # E: incompatible type
-AR_S.index("a", end=9)  # E: incompatible type
-AR_U.rindex(b"a", start=[1, 2, 3])  # E: incompatible type
-AR_S.rindex("a", end=9)  # E: incompatible type
-
-AR_U == AR_S  # E: Unsupported operand types
-AR_U != AR_S  # E: Unsupported operand types
-AR_U >= AR_S  # E: Unsupported operand types
-AR_U <= AR_S  # E: Unsupported operand types
-AR_U > AR_S  # E: Unsupported operand types
-AR_U < AR_S  # E: Unsupported operand types
+AR_S.encode()  # type: ignore[misc]
+AR_U.decode()  # type: ignore[misc]
+
+AR_U.join(b"_")  # type: ignore[arg-type]
+AR_S.join("_")  # type: ignore[arg-type]
+
+AR_U.ljust(5, fillchar=b"a")  # type: ignore[arg-type]
+AR_S.ljust(5, fillchar="a")  # type: ignore[arg-type]
+AR_U.rjust(5, fillchar=b"a")  # type: ignore[arg-type]
+AR_S.rjust(5, fillchar="a")  # type: ignore[arg-type]
+
+AR_U.lstrip(chars=b"a")  # type: ignore[arg-type]
+AR_S.lstrip(chars="a")  # type: ignore[arg-type]
+AR_U.strip(chars=b"a")  # type: ignore[arg-type]
+AR_S.strip(chars="a")  # type: ignore[arg-type]
+AR_U.rstrip(chars=b"a")  # type: ignore[arg-type]
+AR_S.rstrip(chars="a")  # type: ignore[arg-type]
+
+AR_U.partition(b"a")  # type: ignore[arg-type]
+AR_S.partition("a")  # type: ignore[arg-type]
+AR_U.rpartition(b"a")  # type: ignore[arg-type]
+AR_S.rpartition("a")  # type: ignore[arg-type]
+
+AR_U.replace(b"_", b"-")  # type: ignore[arg-type]
+AR_S.replace("_", "-")  # type: ignore[arg-type]
+
+AR_U.split(b"_")  # type: ignore[arg-type]
+AR_S.split("_")  # type: ignore[arg-type]
+AR_S.split(1)  # type: ignore[arg-type]
+AR_U.rsplit(b"_")  # type: ignore[arg-type]
+AR_S.rsplit("_")  # type: ignore[arg-type]
+
+AR_U.count(b"a", start=[1, 2, 3])  # type: ignore[arg-type]
+AR_S.count("a", end=9)  # type: ignore[arg-type]
+
+AR_U.endswith(b"a", start=[1, 2, 3])  # type: ignore[arg-type]
+AR_S.endswith("a", end=9)  # type: ignore[arg-type]
+AR_U.startswith(b"a", start=[1, 2, 3])  # type: ignore[arg-type]
+AR_S.startswith("a", end=9)  # type: ignore[arg-type]
+
+AR_U.find(b"a", start=[1, 2, 3])  # type: ignore[arg-type]
+AR_S.find("a", end=9)  # type: ignore[arg-type]
+AR_U.rfind(b"a", start=[1, 2, 3])  # type: ignore[arg-type]
+AR_S.rfind("a", end=9)  # type: ignore[arg-type]
+
+AR_U.index(b"a", start=[1, 2, 3])  # type: ignore[arg-type]
+AR_S.index("a", end=9)  # type: ignore[arg-type]
+AR_U.rindex(b"a", start=[1, 2, 3])  # type: ignore[arg-type]
+AR_S.rindex("a", end=9)  # type: ignore[arg-type]
+
+AR_U == AR_S  # type: ignore[operator]
+AR_U != AR_S  # type: ignore[operator]
+AR_U >= AR_S  # type: ignore[operator]
+AR_U <= AR_S  # type: ignore[operator]
+AR_U > AR_S  # type: ignore[operator]
+AR_U < AR_S  # type: ignore[operator]
diff --git a/numpy/typing/tests/data/fail/comparisons.pyi b/numpy/typing/tests/data/fail/comparisons.pyi
index 1ae8149082b6..3c8a94bff240 100644
--- a/numpy/typing/tests/data/fail/comparisons.pyi
+++ b/numpy/typing/tests/data/fail/comparisons.pyi
@@ -7,21 +7,21 @@ AR_c: npt.NDArray[np.complex128]
 AR_m: npt.NDArray[np.timedelta64]
 AR_M: npt.NDArray[np.datetime64]
 
-AR_f > AR_m  # E: Unsupported operand types
-AR_c > AR_m  # E: Unsupported operand types
+AR_f > AR_m  # type: ignore[operator]
+AR_c > AR_m  # type: ignore[operator]
 
-AR_m > AR_f  # E: Unsupported operand types
-AR_m > AR_c  # E: Unsupported operand types
+AR_m > AR_f  # type: ignore[operator]
+AR_m > AR_c  # type: ignore[operator]
 
-AR_i > AR_M  # E: Unsupported operand types
-AR_f > AR_M  # E: Unsupported operand types
-AR_m > AR_M  # E: Unsupported operand types
+AR_i > AR_M  # type: ignore[operator]
+AR_f > AR_M  # type: ignore[operator]
+AR_m > AR_M  # type: ignore[operator]
 
-AR_M > AR_i  # E: Unsupported operand types
-AR_M > AR_f  # E: Unsupported operand types
-AR_M > AR_m  # E: Unsupported operand types
+AR_M > AR_i  # type: ignore[operator]
+AR_M > AR_f  # type: ignore[operator]
+AR_M > AR_m  # type: ignore[operator]
 
-AR_i > str()  # E: No overload variant
-AR_i > bytes()  # E: No overload variant
-str() > AR_M  # E: Unsupported operand types
-bytes() > AR_M  # E: Unsupported operand types
+AR_i > str()  # type: ignore[operator]
+AR_i > bytes()  # type: ignore[operator]
+str() > AR_M  # type: ignore[operator]
+bytes() > AR_M  # type: ignore[operator]
diff --git a/numpy/typing/tests/data/fail/constants.pyi b/numpy/typing/tests/data/fail/constants.pyi
index b5d6d27eae46..10717f664e0a 100644
--- a/numpy/typing/tests/data/fail/constants.pyi
+++ b/numpy/typing/tests/data/fail/constants.pyi
@@ -1,3 +1,3 @@
 import numpy as np
 
-np.little_endian = np.little_endian  # E: Cannot assign to final
+np.little_endian = np.little_endian  # type: ignore[misc]
diff --git a/numpy/typing/tests/data/fail/datasource.pyi b/numpy/typing/tests/data/fail/datasource.pyi
index 44f4fa27307a..267b672baea7 100644
--- a/numpy/typing/tests/data/fail/datasource.pyi
+++ b/numpy/typing/tests/data/fail/datasource.pyi
@@ -4,12 +4,12 @@ import numpy as np
 path: Path
 d1: np.lib.npyio.DataSource
 
-d1.abspath(path)  # E: incompatible type
-d1.abspath(b"...")  # E: incompatible type
+d1.abspath(path)  # type: ignore[arg-type]
+d1.abspath(b"...")  # type: ignore[arg-type]
 
-d1.exists(path)  # E: incompatible type
-d1.exists(b"...")  # E: incompatible type
+d1.exists(path)  # type: ignore[arg-type]
+d1.exists(b"...")  # type: ignore[arg-type]
 
-d1.open(path, "r")  # E: incompatible type
-d1.open(b"...", encoding="utf8")  # E: incompatible type
-d1.open(None, newline="/n")  # E: incompatible type
+d1.open(path, "r")  # type: ignore[arg-type]
+d1.open(b"...", encoding="utf8")  # type: ignore[arg-type]
+d1.open(None, newline="/n")  # type: ignore[arg-type]
diff --git a/numpy/typing/tests/data/fail/dtype.pyi b/numpy/typing/tests/data/fail/dtype.pyi
index a1af3cd8d86b..64a7c3f775e1 100644
--- a/numpy/typing/tests/data/fail/dtype.pyi
+++ b/numpy/typing/tests/data/fail/dtype.pyi
@@ -6,10 +6,10 @@ class Test1:
 class Test2:
     dtype = float
 
-np.dtype(Test1())  # E: No overload variant of "dtype" matches
-np.dtype(Test2())  # E: incompatible type
+np.dtype(Test1())  # type: ignore[call-overload]
+np.dtype(Test2())  # type: ignore[arg-type]
 
-np.dtype(  # E: No overload variant of "dtype" matches
+np.dtype(  # type: ignore[call-overload]
     {
         "field1": (float, 1),
         "field2": (int, 3),
diff --git a/numpy/typing/tests/data/fail/einsumfunc.pyi b/numpy/typing/tests/data/fail/einsumfunc.pyi
index bae422ac14ac..982ad986297f 100644
--- a/numpy/typing/tests/data/fail/einsumfunc.pyi
+++ b/numpy/typing/tests/data/fail/einsumfunc.pyi
@@ -6,7 +6,7 @@ AR_f: npt.NDArray[np.float64]
 AR_m: npt.NDArray[np.timedelta64]
 AR_U: npt.NDArray[np.str_]
 
-np.einsum("i,i->i", AR_i, AR_m)  # E: incompatible type
-np.einsum("i,i->i", AR_f, AR_f, dtype=np.int32)  # E: incompatible type
-np.einsum("i,i->i", AR_i, AR_i, out=AR_U)  # E: Value of type variable "_ArrayT" of "einsum" cannot be
-np.einsum("i,i->i", AR_i, AR_i, out=AR_U, casting="unsafe")  # E: No overload variant
+np.einsum("i,i->i", AR_i, AR_m)  # type: ignore[arg-type]
+np.einsum("i,i->i", AR_f, AR_f, dtype=np.int32)  # type: ignore[arg-type]
+np.einsum("i,i->i", AR_i, AR_i, out=AR_U)  # type: ignore[type-var]
+np.einsum("i,i->i", AR_i, AR_i, out=AR_U, casting="unsafe")  # type: ignore[call-overload]
diff --git a/numpy/typing/tests/data/fail/flatiter.pyi b/numpy/typing/tests/data/fail/flatiter.pyi
index c2689f44c35b..06e23fed9e3f 100644
--- a/numpy/typing/tests/data/fail/flatiter.pyi
+++ b/numpy/typing/tests/data/fail/flatiter.pyi
@@ -1,5 +1,3 @@
-from typing import Any
-
 import numpy as np
 import numpy._typing as npt
 
@@ -9,14 +7,14 @@ class Index:
 a: np.flatiter[npt.NDArray[np.float64]]
 supports_array: npt._SupportsArray[np.dtype[np.float64]]
 
-a.base = Any  # E: Property "base" defined in "flatiter" is read-only
-a.coords = Any  # E: Property "coords" defined in "flatiter" is read-only
-a.index = Any  # E: Property "index" defined in "flatiter" is read-only
-a.copy(order='C')  # E: Unexpected keyword argument
+a.base = object()  # type: ignore[assignment, misc]
+a.coords = object()  # type: ignore[assignment, misc]
+a.index = object()  # type: ignore[assignment, misc]
+a.copy(order='C')  # type: ignore[call-arg]
 
 # NOTE: Contrary to `ndarray.__getitem__` its counterpart in `flatiter`
 # does not accept objects with the `__array__` or `__index__` protocols;
 # boolean indexing is just plain broken (gh-17175)
-a[np.bool()]  # E: No overload variant of "__getitem__"
-a[Index()]  # E: No overload variant of "__getitem__"
-a[supports_array]  # E: No overload variant of "__getitem__"
+a[np.bool()]  # type: ignore[index]
+a[Index()]  # type: ignore[call-overload]
+a[supports_array]  # type: ignore[index]
diff --git a/numpy/typing/tests/data/fail/fromnumeric.pyi b/numpy/typing/tests/data/fail/fromnumeric.pyi
index fb666986a7e0..afab58f9a71f 100644
--- a/numpy/typing/tests/data/fail/fromnumeric.pyi
+++ b/numpy/typing/tests/data/fail/fromnumeric.pyi
@@ -10,156 +10,136 @@ AR_M: npt.NDArray[np.datetime64]
 
 a = np.bool(True)
 
-np.take(a, None)  # E: No overload variant
-np.take(a, axis=1.0)  # E: No overload variant
-np.take(A, out=1)  # E: No overload variant
-np.take(A, mode="bob")  # E: No overload variant
-
-np.reshape(a, None)  # E: No overload variant
-np.reshape(A, 1, order="bob")  # E: No overload variant
-
-np.choose(a, None)  # E: No overload variant
-np.choose(a, out=1.0)  # E: No overload variant
-np.choose(A, mode="bob")  # E: No overload variant
-
-np.repeat(a, None)  # E: No overload variant
-np.repeat(A, 1, axis=1.0)  # E: No overload variant
-
-np.swapaxes(A, None, 1)  # E: No overload variant
-np.swapaxes(A, 1, [0])  # E: No overload variant
-
-np.transpose(A, axes=1.0)  # E: No overload variant
-
-np.partition(a, None)  # E: No overload variant
-np.partition(  # E: No overload variant
-    a, 0, axis="bob"
-)
-np.partition(  # E: No overload variant
-    A, 0, kind="bob"
-)
-np.partition(
-    A, 0, order=range(5)  # E: Argument "order" to "partition" has incompatible type
-)
-
-np.argpartition(
-    a, None  # E: incompatible type
-)
-np.argpartition(
-    a, 0, axis="bob"  # E: incompatible type
-)
-np.argpartition(
-    A, 0, kind="bob"  # E: incompatible type
-)
-np.argpartition(
-    A, 0, order=range(5)  # E: Argument "order" to "argpartition" has incompatible type
-)
-
-np.sort(A, axis="bob")  # E: No overload variant
-np.sort(A, kind="bob")  # E: No overload variant
-np.sort(A, order=range(5))  # E: Argument "order" to "sort" has incompatible type
-
-np.argsort(A, axis="bob")  # E: Argument "axis" to "argsort" has incompatible type
-np.argsort(A, kind="bob")  # E: Argument "kind" to "argsort" has incompatible type
-np.argsort(A, order=range(5))  # E: Argument "order" to "argsort" has incompatible type
-
-np.argmax(A, axis="bob")  # E: No overload variant of "argmax" matches argument type
-np.argmax(A, kind="bob")  # E: No overload variant of "argmax" matches argument type
-
-np.argmin(A, axis="bob")  # E: No overload variant of "argmin" matches argument type
-np.argmin(A, kind="bob")  # E: No overload variant of "argmin" matches argument type
-
-np.searchsorted(  # E: No overload variant of "searchsorted" matches argument type
-    A[0], 0, side="bob"
-)
-np.searchsorted(  # E: No overload variant of "searchsorted" matches argument type
-    A[0], 0, sorter=1.0
-)
-
-np.resize(A, 1.0)  # E: No overload variant
-
-np.squeeze(A, 1.0)  # E: No overload variant of "squeeze" matches argument type
-
-np.diagonal(A, offset=None)  # E: No overload variant
-np.diagonal(A, axis1="bob")  # E: No overload variant
-np.diagonal(A, axis2=[])  # E: No overload variant
-
-np.trace(A, offset=None)  # E: No overload variant
-np.trace(A, axis1="bob")  # E: No overload variant
-np.trace(A, axis2=[])  # E: No overload variant
-
-np.ravel(a, order="bob")  # E: No overload variant
-
-np.nonzero(0)  # E: No overload variant
-
-np.compress(  # E: No overload variant
-    [True], A, axis=1.0
-)
-
-np.clip(a, 1, 2, out=1)  # E: No overload variant of "clip" matches argument type
-
-np.sum(a, axis=1.0)  # E: No overload variant
-np.sum(a, keepdims=1.0)  # E: No overload variant
-np.sum(a, initial=[1])  # E: No overload variant
-
-np.all(a, axis=1.0)  # E: No overload variant
-np.all(a, keepdims=1.0)  # E: No overload variant
-np.all(a, out=1.0)  # E: No overload variant
-
-np.any(a, axis=1.0)  # E: No overload variant
-np.any(a, keepdims=1.0)  # E: No overload variant
-np.any(a, out=1.0)  # E: No overload variant
-
-np.cumsum(a, axis=1.0)  # E: No overload variant
-np.cumsum(a, dtype=1.0)  # E: No overload variant
-np.cumsum(a, out=1.0)  # E: No overload variant
-
-np.ptp(a, axis=1.0)  # E: No overload variant
-np.ptp(a, keepdims=1.0)  # E: No overload variant
-np.ptp(a, out=1.0)  # E: No overload variant
-
-np.amax(a, axis=1.0)  # E: No overload variant
-np.amax(a, keepdims=1.0)  # E: No overload variant
-np.amax(a, out=1.0)  # E: No overload variant
-np.amax(a, initial=[1.0])  # E: No overload variant
-np.amax(a, where=[1.0])  # E: incompatible type
-
-np.amin(a, axis=1.0)  # E: No overload variant
-np.amin(a, keepdims=1.0)  # E: No overload variant
-np.amin(a, out=1.0)  # E: No overload variant
-np.amin(a, initial=[1.0])  # E: No overload variant
-np.amin(a, where=[1.0])  # E: incompatible type
-
-np.prod(a, axis=1.0)  # E: No overload variant
-np.prod(a, out=False)  # E: No overload variant
-np.prod(a, keepdims=1.0)  # E: No overload variant
-np.prod(a, initial=int)  # E: No overload variant
-np.prod(a, where=1.0)  # E: No overload variant
-np.prod(AR_U)  # E: incompatible type
-
-np.cumprod(a, axis=1.0)  # E: No overload variant
-np.cumprod(a, out=False)  # E: No overload variant
-np.cumprod(AR_U)  # E: incompatible type
-
-np.size(a, axis=1.0)  # E: Argument "axis" to "size" has incompatible type
-
-np.around(a, decimals=1.0)  # E: No overload variant
-np.around(a, out=type)  # E: No overload variant
-np.around(AR_U)  # E: incompatible type
-
-np.mean(a, axis=1.0)  # E: No overload variant
-np.mean(a, out=False)  # E: No overload variant
-np.mean(a, keepdims=1.0)  # E: No overload variant
-np.mean(AR_U)  # E: incompatible type
-np.mean(AR_M)  # E: incompatible type
-
-np.std(a, axis=1.0)  # E: No overload variant
-np.std(a, out=False)  # E: No overload variant
-np.std(a, ddof='test')  # E: No overload variant
-np.std(a, keepdims=1.0)  # E: No overload variant
-np.std(AR_U)  # E: incompatible type
+np.take(a, None)  # type: ignore[call-overload]
+np.take(a, axis=1.0)  # type: ignore[call-overload]
+np.take(A, out=1)  # type: ignore[call-overload]
+np.take(A, mode="bob")  # type: ignore[call-overload]
 
-np.var(a, axis=1.0)  # E: No overload variant
-np.var(a, out=False)  # E: No overload variant
-np.var(a, ddof='test')  # E: No overload variant
-np.var(a, keepdims=1.0)  # E: No overload variant
-np.var(AR_U)  # E: incompatible type
+np.reshape(a, None)  # type: ignore[call-overload]
+np.reshape(A, 1, order="bob")  # type: ignore[call-overload]
+
+np.choose(a, None)  # type: ignore[call-overload]
+np.choose(a, out=1.0)  # type: ignore[call-overload]
+np.choose(A, mode="bob")  # type: ignore[call-overload]
+
+np.repeat(a, None)  # type: ignore[call-overload]
+np.repeat(A, 1, axis=1.0)  # type: ignore[call-overload]
+
+np.swapaxes(A, None, 1)  # type: ignore[call-overload]
+np.swapaxes(A, 1, [0])  # type: ignore[call-overload]
+
+np.transpose(A, axes=1.0)  # type: ignore[call-overload]
+
+np.partition(a, None)  # type: ignore[call-overload]
+np.partition(a, 0, axis="bob") # type: ignore[call-overload]
+np.partition(A, 0, kind="bob")  # type: ignore[call-overload]
+np.partition(A, 0, order=range(5))  # type: ignore[arg-type]
+
+np.argpartition(a, None)  # type: ignore[arg-type]
+np.argpartition(a, 0, axis="bob")  # type: ignore[arg-type]
+np.argpartition(A, 0, kind="bob") # type: ignore[arg-type]
+np.argpartition(A, 0, order=range(5))  # type: ignore[arg-type]
+
+np.sort(A, axis="bob")  # type: ignore[call-overload]
+np.sort(A, kind="bob")  # type: ignore[call-overload]
+np.sort(A, order=range(5)) # type: ignore[arg-type]
+
+np.argsort(A, axis="bob")  # type: ignore[arg-type]
+np.argsort(A, kind="bob")  # type: ignore[arg-type]
+np.argsort(A, order=range(5))  # type: ignore[arg-type]
+
+np.argmax(A, axis="bob")  # type: ignore[call-overload]
+np.argmax(A, kind="bob")  # type: ignore[call-overload]
+
+np.argmin(A, axis="bob")  # type: ignore[call-overload]
+np.argmin(A, kind="bob")  # type: ignore[call-overload]
+
+np.searchsorted(A[0], 0, side="bob")  # type: ignore[call-overload]
+np.searchsorted(A[0], 0, sorter=1.0)  # type: ignore[call-overload]
+
+np.resize(A, 1.0)  # type: ignore[call-overload]
+
+np.squeeze(A, 1.0)  # type: ignore[call-overload]
+
+np.diagonal(A, offset=None)  # type: ignore[call-overload]
+np.diagonal(A, axis1="bob")  # type: ignore[call-overload]
+np.diagonal(A, axis2=[])  # type: ignore[call-overload]
+
+np.trace(A, offset=None)  # type: ignore[call-overload]
+np.trace(A, axis1="bob")  # type: ignore[call-overload]
+np.trace(A, axis2=[])  # type: ignore[call-overload]
+
+np.ravel(a, order="bob")  # type: ignore[call-overload]
+
+np.nonzero(0)  # type: ignore[arg-type]
+
+np.compress([True], A, axis=1.0)  # type: ignore[call-overload]
+
+np.clip(a, 1, 2, out=1)  # type: ignore[call-overload]
+
+np.sum(a, axis=1.0)  # type: ignore[call-overload]
+np.sum(a, keepdims=1.0)  # type: ignore[call-overload]
+np.sum(a, initial=[1])  # type: ignore[call-overload]
+
+np.all(a, axis=1.0)  # type: ignore[call-overload]
+np.all(a, keepdims=1.0)  # type: ignore[call-overload]
+np.all(a, out=1.0)  # type: ignore[call-overload]
+
+np.any(a, axis=1.0)  # type: ignore[call-overload]
+np.any(a, keepdims=1.0)  # type: ignore[call-overload]
+np.any(a, out=1.0)  # type: ignore[call-overload]
+
+np.cumsum(a, axis=1.0)  # type: ignore[call-overload]
+np.cumsum(a, dtype=1.0)  # type: ignore[call-overload]
+np.cumsum(a, out=1.0)  # type: ignore[call-overload]
+
+np.ptp(a, axis=1.0)  # type: ignore[call-overload]
+np.ptp(a, keepdims=1.0)  # type: ignore[call-overload]
+np.ptp(a, out=1.0)  # type: ignore[call-overload]
+
+np.amax(a, axis=1.0)  # type: ignore[call-overload]
+np.amax(a, keepdims=1.0)  # type: ignore[call-overload]
+np.amax(a, out=1.0)  # type: ignore[call-overload]
+np.amax(a, initial=[1.0])  # type: ignore[call-overload]
+np.amax(a, where=[1.0])  # type: ignore[arg-type]
+
+np.amin(a, axis=1.0)  # type: ignore[call-overload]
+np.amin(a, keepdims=1.0)  # type: ignore[call-overload]
+np.amin(a, out=1.0)  # type: ignore[call-overload]
+np.amin(a, initial=[1.0])  # type: ignore[call-overload]
+np.amin(a, where=[1.0])  # type: ignore[arg-type]
+
+np.prod(a, axis=1.0)  # type: ignore[call-overload]
+np.prod(a, out=False)  # type: ignore[call-overload]
+np.prod(a, keepdims=1.0)  # type: ignore[call-overload]
+np.prod(a, initial=int)  # type: ignore[call-overload]
+np.prod(a, where=1.0)  # type: ignore[call-overload]
+np.prod(AR_U)  # type: ignore[arg-type]
+
+np.cumprod(a, axis=1.0)  # type: ignore[call-overload]
+np.cumprod(a, out=False)  # type: ignore[call-overload]
+np.cumprod(AR_U)  # type: ignore[arg-type]
+
+np.size(a, axis=1.0)  # type: ignore[arg-type]
+
+np.around(a, decimals=1.0)  # type: ignore[call-overload]
+np.around(a, out=type)  # type: ignore[call-overload]
+np.around(AR_U)  # type: ignore[arg-type]
+
+np.mean(a, axis=1.0)  # type: ignore[call-overload]
+np.mean(a, out=False)  # type: ignore[call-overload]
+np.mean(a, keepdims=1.0)  # type: ignore[call-overload]
+np.mean(AR_U)  # type: ignore[arg-type]
+np.mean(AR_M)  # type: ignore[arg-type]
+
+np.std(a, axis=1.0)  # type: ignore[call-overload]
+np.std(a, out=False)  # type: ignore[call-overload]
+np.std(a, ddof='test')  # type: ignore[call-overload]
+np.std(a, keepdims=1.0)  # type: ignore[call-overload]
+np.std(AR_U)  # type: ignore[arg-type]
+
+np.var(a, axis=1.0)  # type: ignore[call-overload]
+np.var(a, out=False)  # type: ignore[call-overload]
+np.var(a, ddof='test')  # type: ignore[call-overload]
+np.var(a, keepdims=1.0)  # type: ignore[call-overload]
+np.var(AR_U)  # type: ignore[arg-type]
diff --git a/numpy/typing/tests/data/fail/histograms.pyi b/numpy/typing/tests/data/fail/histograms.pyi
index 22499d39175a..5f7892719eb4 100644
--- a/numpy/typing/tests/data/fail/histograms.pyi
+++ b/numpy/typing/tests/data/fail/histograms.pyi
@@ -4,9 +4,9 @@ import numpy.typing as npt
 AR_i8: npt.NDArray[np.int64]
 AR_f8: npt.NDArray[np.float64]
 
-np.histogram_bin_edges(AR_i8, range=(0, 1, 2))  # E: incompatible type
+np.histogram_bin_edges(AR_i8, range=(0, 1, 2))  # type: ignore[arg-type]
 
-np.histogram(AR_i8, range=(0, 1, 2))  # E: incompatible type
+np.histogram(AR_i8, range=(0, 1, 2))  # type: ignore[arg-type]
 
-np.histogramdd(AR_i8, range=(0, 1))  # E: incompatible type
-np.histogramdd(AR_i8, range=[(0, 1, 2)])  # E: incompatible type
+np.histogramdd(AR_i8, range=(0, 1))  # type: ignore[arg-type]
+np.histogramdd(AR_i8, range=[(0, 1, 2)])  # type: ignore[list-item]
diff --git a/numpy/typing/tests/data/fail/index_tricks.pyi b/numpy/typing/tests/data/fail/index_tricks.pyi
index 22f6f4a61e8e..8b7b1ae2b5bf 100644
--- a/numpy/typing/tests/data/fail/index_tricks.pyi
+++ b/numpy/typing/tests/data/fail/index_tricks.pyi
@@ -3,12 +3,12 @@ import numpy as np
 AR_LIKE_i: list[int]
 AR_LIKE_f: list[float]
 
-np.ndindex([1, 2, 3])  # E: No overload variant
-np.unravel_index(AR_LIKE_f, (1, 2, 3))  # E: incompatible type
-np.ravel_multi_index(AR_LIKE_i, (1, 2, 3), mode="bob")  # E: No overload variant
-np.mgrid[1]  # E: Invalid index type
-np.mgrid[...]  # E: Invalid index type
-np.ogrid[1]  # E: Invalid index type
-np.ogrid[...]  # E: Invalid index type
-np.fill_diagonal(AR_LIKE_f, 2)  # E: incompatible type
-np.diag_indices(1.0)  # E: incompatible type
+np.ndindex([1, 2, 3])  # type: ignore[call-overload]
+np.unravel_index(AR_LIKE_f, (1, 2, 3))  # type: ignore[arg-type]
+np.ravel_multi_index(AR_LIKE_i, (1, 2, 3), mode="bob")  # type: ignore[call-overload]
+np.mgrid[1]  # type: ignore[index]
+np.mgrid[...]  # type: ignore[index]
+np.ogrid[1]  # type: ignore[index]
+np.ogrid[...]  # type: ignore[index]
+np.fill_diagonal(AR_LIKE_f, 2)  # type: ignore[arg-type]
+np.diag_indices(1.0)  # type: ignore[arg-type]
diff --git a/numpy/typing/tests/data/fail/lib_function_base.pyi b/numpy/typing/tests/data/fail/lib_function_base.pyi
index de4e56b07ba1..f0bf6347691d 100644
--- a/numpy/typing/tests/data/fail/lib_function_base.pyi
+++ b/numpy/typing/tests/data/fail/lib_function_base.pyi
@@ -13,50 +13,50 @@ AR_b_list: list[npt.NDArray[np.bool]]
 def fn_none_i(a: None, /) -> npt.NDArray[Any]: ...
 def fn_ar_i(a: npt.NDArray[np.float64], posarg: int, /) -> npt.NDArray[Any]: ...
 
-np.average(AR_m)  # E: incompatible type
-np.select(1, [AR_f8])  # E: incompatible type
-np.angle(AR_m)  # E: incompatible type
-np.unwrap(AR_m)  # E: incompatible type
-np.unwrap(AR_c16)  # E: incompatible type
-np.trim_zeros(1)  # E: incompatible type
-np.place(1, [True], 1.5)  # E: incompatible type
-np.vectorize(1)  # E: incompatible type
-np.place(AR_f8, slice(None), 5)  # E: incompatible type
-
-np.piecewise(AR_f8, True, [fn_ar_i], 42)  # E: No overload variants
+np.average(AR_m)  # type: ignore[arg-type]
+np.select(1, [AR_f8])  # type: ignore[arg-type]
+np.angle(AR_m)  # type: ignore[arg-type]
+np.unwrap(AR_m)  # type: ignore[arg-type]
+np.unwrap(AR_c16)  # type: ignore[arg-type]
+np.trim_zeros(1)  # type: ignore[arg-type]
+np.place(1, [True], 1.5)  # type: ignore[arg-type]
+np.vectorize(1)  # type: ignore[arg-type]
+np.place(AR_f8, slice(None), 5)  # type: ignore[arg-type]
+
+np.piecewise(AR_f8, True, [fn_ar_i], 42)  # type: ignore[call-overload]
 # TODO: enable these once mypy actually supports ParamSpec (released in 2021)
 # NOTE: pyright correctly reports errors for these (`reportCallIssue`)
-# np.piecewise(AR_f8, AR_b_list, [fn_none_i])  # E: No overload variants
-# np.piecewise(AR_f8, AR_b_list, [fn_ar_i])  # E: No overload variant
-# np.piecewise(AR_f8, AR_b_list, [fn_ar_i], 3.14)  # E: No overload variant
-# np.piecewise(AR_f8, AR_b_list, [fn_ar_i], 42, None)  # E: No overload variant
-# np.piecewise(AR_f8, AR_b_list, [fn_ar_i], 42, _=None)  # E: No overload variant
-
-np.interp(AR_f8, AR_c16, AR_f8)  # E: incompatible type
-np.interp(AR_c16, AR_f8, AR_f8)  # E: incompatible type
-np.interp(AR_f8, AR_f8, AR_f8, period=AR_c16)  # E: No overload variant
-np.interp(AR_f8, AR_f8, AR_O)  # E: incompatible type
-
-np.cov(AR_m)  # E: incompatible type
-np.cov(AR_O)  # E: incompatible type
-np.corrcoef(AR_m)  # E: incompatible type
-np.corrcoef(AR_O)  # E: incompatible type
-np.corrcoef(AR_f8, bias=True)  # E: No overload variant
-np.corrcoef(AR_f8, ddof=2)  # E: No overload variant
-np.blackman(1j)  # E: incompatible type
-np.bartlett(1j)  # E: incompatible type
-np.hanning(1j)  # E: incompatible type
-np.hamming(1j)  # E: incompatible type
-np.hamming(AR_c16)  # E: incompatible type
-np.kaiser(1j, 1)  # E: incompatible type
-np.sinc(AR_O)  # E: incompatible type
-np.median(AR_M)  # E: incompatible type
-
-np.percentile(AR_f8, 50j)  # E: No overload variant
-np.percentile(AR_f8, 50, interpolation="bob")  # E: No overload variant
-np.quantile(AR_f8, 0.5j)  # E: No overload variant
-np.quantile(AR_f8, 0.5, interpolation="bob")  # E: No overload variant
-np.meshgrid(AR_f8, AR_f8, indexing="bob")  # E: incompatible type
-np.delete(AR_f8, AR_f8)  # E: incompatible type
-np.insert(AR_f8, AR_f8, 1.5)  # E: incompatible type
-np.digitize(AR_f8, 1j)  # E: No overload variant
+# np.piecewise(AR_f8, AR_b_list, [fn_none_i])  # type: ignore[call-overload]s
+# np.piecewise(AR_f8, AR_b_list, [fn_ar_i])  # type: ignore[call-overload]
+# np.piecewise(AR_f8, AR_b_list, [fn_ar_i], 3.14)  # type: ignore[call-overload]
+# np.piecewise(AR_f8, AR_b_list, [fn_ar_i], 42, None)  # type: ignore[call-overload]
+# np.piecewise(AR_f8, AR_b_list, [fn_ar_i], 42, _=None)  # type: ignore[call-overload]
+
+np.interp(AR_f8, AR_c16, AR_f8)  # type: ignore[arg-type]
+np.interp(AR_c16, AR_f8, AR_f8)  # type: ignore[arg-type]
+np.interp(AR_f8, AR_f8, AR_f8, period=AR_c16)  # type: ignore[call-overload]
+np.interp(AR_f8, AR_f8, AR_O)  # type: ignore[arg-type]
+
+np.cov(AR_m)  # type: ignore[arg-type]
+np.cov(AR_O)  # type: ignore[arg-type]
+np.corrcoef(AR_m)  # type: ignore[arg-type]
+np.corrcoef(AR_O)  # type: ignore[arg-type]
+np.corrcoef(AR_f8, bias=True)  # type: ignore[call-overload]
+np.corrcoef(AR_f8, ddof=2)  # type: ignore[call-overload]
+np.blackman(1j)  # type: ignore[arg-type]
+np.bartlett(1j)  # type: ignore[arg-type]
+np.hanning(1j)  # type: ignore[arg-type]
+np.hamming(1j)  # type: ignore[arg-type]
+np.hamming(AR_c16)  # type: ignore[arg-type]
+np.kaiser(1j, 1)  # type: ignore[arg-type]
+np.sinc(AR_O)  # type: ignore[arg-type]
+np.median(AR_M)  # type: ignore[arg-type]
+
+np.percentile(AR_f8, 50j)  # type: ignore[call-overload]
+np.percentile(AR_f8, 50, interpolation="bob")  # type: ignore[call-overload]
+np.quantile(AR_f8, 0.5j)  # type: ignore[call-overload]
+np.quantile(AR_f8, 0.5, interpolation="bob")  # type: ignore[call-overload]
+np.meshgrid(AR_f8, AR_f8, indexing="bob")  # type: ignore[call-overload]
+np.delete(AR_f8, AR_f8)  # type: ignore[arg-type]
+np.insert(AR_f8, AR_f8, 1.5)  # type: ignore[arg-type]
+np.digitize(AR_f8, 1j)  # type: ignore[call-overload]
diff --git a/numpy/typing/tests/data/fail/lib_polynomial.pyi b/numpy/typing/tests/data/fail/lib_polynomial.pyi
index e51b6b58e307..727eb7f4b2b1 100644
--- a/numpy/typing/tests/data/fail/lib_polynomial.pyi
+++ b/numpy/typing/tests/data/fail/lib_polynomial.pyi
@@ -8,22 +8,22 @@ AR_U: npt.NDArray[np.str_]
 
 poly_obj: np.poly1d
 
-np.polymul(AR_f8, AR_U)  # E: incompatible type
-np.polydiv(AR_f8, AR_U)  # E: incompatible type
+np.polymul(AR_f8, AR_U)  # type: ignore[arg-type]
+np.polydiv(AR_f8, AR_U)  # type: ignore[arg-type]
 
-5**poly_obj  # E: No overload variant
+5**poly_obj  # type: ignore[operator]
 
-np.polyint(AR_U)  # E: incompatible type
-np.polyint(AR_f8, m=1j)  # E: No overload variant
+np.polyint(AR_U)  # type: ignore[arg-type]
+np.polyint(AR_f8, m=1j)  # type: ignore[call-overload]
 
-np.polyder(AR_U)  # E: incompatible type
-np.polyder(AR_f8, m=1j)  # E: No overload variant
+np.polyder(AR_U)  # type: ignore[arg-type]
+np.polyder(AR_f8, m=1j)  # type: ignore[call-overload]
 
-np.polyfit(AR_O, AR_f8, 1)  # E: incompatible type
-np.polyfit(AR_f8, AR_f8, 1, rcond=1j)  # E: No overload variant
-np.polyfit(AR_f8, AR_f8, 1, w=AR_c16)  # E: incompatible type
-np.polyfit(AR_f8, AR_f8, 1, cov="bob")  # E: No overload variant
+np.polyfit(AR_O, AR_f8, 1)  # type: ignore[arg-type]
+np.polyfit(AR_f8, AR_f8, 1, rcond=1j)  # type: ignore[call-overload]
+np.polyfit(AR_f8, AR_f8, 1, w=AR_c16)  # type: ignore[arg-type]
+np.polyfit(AR_f8, AR_f8, 1, cov="bob")  # type: ignore[call-overload]
 
-np.polyval(AR_f8, AR_U)  # E: incompatible type
-np.polyadd(AR_f8, AR_U)  # E: incompatible type
-np.polysub(AR_f8, AR_U)  # E: incompatible type
+np.polyval(AR_f8, AR_U)  # type: ignore[arg-type]
+np.polyadd(AR_f8, AR_U)  # type: ignore[arg-type]
+np.polysub(AR_f8, AR_U)  # type: ignore[arg-type]
diff --git a/numpy/typing/tests/data/fail/lib_utils.pyi b/numpy/typing/tests/data/fail/lib_utils.pyi
index 8b8482eeff6d..25af32b43297 100644
--- a/numpy/typing/tests/data/fail/lib_utils.pyi
+++ b/numpy/typing/tests/data/fail/lib_utils.pyi
@@ -1,3 +1,3 @@
 import numpy.lib.array_utils as array_utils
 
-array_utils.byte_bounds(1)  # E: incompatible type
+array_utils.byte_bounds(1)  # type: ignore[arg-type]
diff --git a/numpy/typing/tests/data/fail/lib_version.pyi b/numpy/typing/tests/data/fail/lib_version.pyi
index 2758cfe40438..62011a848cc1 100644
--- a/numpy/typing/tests/data/fail/lib_version.pyi
+++ b/numpy/typing/tests/data/fail/lib_version.pyi
@@ -2,5 +2,5 @@ from numpy.lib import NumpyVersion
 
 version: NumpyVersion
 
-NumpyVersion(b"1.8.0")  # E: incompatible type
-version >= b"1.8.0"  # E: Unsupported operand types
+NumpyVersion(b"1.8.0")  # type: ignore[arg-type]
+version >= b"1.8.0"  # type: ignore[operator]
diff --git a/numpy/typing/tests/data/fail/linalg.pyi b/numpy/typing/tests/data/fail/linalg.pyi
index da9390328bd7..c4695ee671cd 100644
--- a/numpy/typing/tests/data/fail/linalg.pyi
+++ b/numpy/typing/tests/data/fail/linalg.pyi
@@ -5,44 +5,44 @@ AR_f8: npt.NDArray[np.float64]
 AR_O: npt.NDArray[np.object_]
 AR_M: npt.NDArray[np.datetime64]
 
-np.linalg.tensorsolve(AR_O, AR_O)  # E: incompatible type
+np.linalg.tensorsolve(AR_O, AR_O)  # type: ignore[arg-type]
 
-np.linalg.solve(AR_O, AR_O)  # E: incompatible type
+np.linalg.solve(AR_O, AR_O)  # type: ignore[arg-type]
 
-np.linalg.tensorinv(AR_O)  # E: incompatible type
+np.linalg.tensorinv(AR_O)  # type: ignore[arg-type]
 
-np.linalg.inv(AR_O)  # E: incompatible type
+np.linalg.inv(AR_O)  # type: ignore[arg-type]
 
-np.linalg.matrix_power(AR_M, 5)  # E: incompatible type
+np.linalg.matrix_power(AR_M, 5)  # type: ignore[arg-type]
 
-np.linalg.cholesky(AR_O)  # E: incompatible type
+np.linalg.cholesky(AR_O)  # type: ignore[arg-type]
 
-np.linalg.qr(AR_O)  # E: incompatible type
-np.linalg.qr(AR_f8, mode="bob")  # E: No overload variant
+np.linalg.qr(AR_O)  # type: ignore[arg-type]
+np.linalg.qr(AR_f8, mode="bob")  # type: ignore[call-overload]
 
-np.linalg.eigvals(AR_O)  # E: incompatible type
+np.linalg.eigvals(AR_O)  # type: ignore[arg-type]
 
-np.linalg.eigvalsh(AR_O)  # E: incompatible type
-np.linalg.eigvalsh(AR_O, UPLO="bob")  # E: No overload variant
+np.linalg.eigvalsh(AR_O)  # type: ignore[arg-type]
+np.linalg.eigvalsh(AR_O, UPLO="bob")  # type: ignore[call-overload]
 
-np.linalg.eig(AR_O)  # E: incompatible type
+np.linalg.eig(AR_O)  # type: ignore[arg-type]
 
-np.linalg.eigh(AR_O)  # E: incompatible type
-np.linalg.eigh(AR_O, UPLO="bob")  # E: No overload variant
+np.linalg.eigh(AR_O)  # type: ignore[arg-type]
+np.linalg.eigh(AR_O, UPLO="bob")  # type: ignore[call-overload]
 
-np.linalg.svd(AR_O)  # E: incompatible type
+np.linalg.svd(AR_O)  # type: ignore[arg-type]
 
-np.linalg.cond(AR_O)  # E: incompatible type
-np.linalg.cond(AR_f8, p="bob")  # E: incompatible type
+np.linalg.cond(AR_O)  # type: ignore[arg-type]
+np.linalg.cond(AR_f8, p="bob")  # type: ignore[arg-type]
 
-np.linalg.matrix_rank(AR_O)  # E: incompatible type
+np.linalg.matrix_rank(AR_O)  # type: ignore[arg-type]
 
-np.linalg.pinv(AR_O)  # E: incompatible type
+np.linalg.pinv(AR_O)  # type: ignore[arg-type]
 
-np.linalg.slogdet(AR_O)  # E: incompatible type
+np.linalg.slogdet(AR_O)  # type: ignore[arg-type]
 
-np.linalg.det(AR_O)  # E: incompatible type
+np.linalg.det(AR_O)  # type: ignore[arg-type]
 
-np.linalg.norm(AR_f8, ord="bob")  # E: No overload variant
+np.linalg.norm(AR_f8, ord="bob")  # type: ignore[call-overload]
 
-np.linalg.multi_dot([AR_M])  # E: incompatible type
+np.linalg.multi_dot([AR_M])  # type: ignore[list-item]
diff --git a/numpy/typing/tests/data/fail/ma.pyi b/numpy/typing/tests/data/fail/ma.pyi
index e93be464de10..2ea53a2956c5 100644
--- a/numpy/typing/tests/data/fail/ma.pyi
+++ b/numpy/typing/tests/data/fail/ma.pyi
@@ -8,129 +8,126 @@ m: np.ma.MaskedArray[tuple[int], np.dtype[np.float64]]
 
 AR_b: npt.NDArray[np.bool]
 
-m.shape = (3, 1)  # E: Incompatible types in assignment
-m.dtype = np.bool  # E: Incompatible types in assignment
-
-np.ma.min(m, axis=1.0)  # E: No overload variant
-np.ma.min(m, keepdims=1.0)  # E: No overload variant
-np.ma.min(m, out=1.0)  # E: No overload variant
-np.ma.min(m, fill_value=lambda x: 27)  # E: No overload variant
-
-m.min(axis=1.0)  # E: No overload variant
-m.min(keepdims=1.0)  # E: No overload variant
-m.min(out=1.0)  # E: No overload variant
-m.min(fill_value=lambda x: 27)  # E: No overload variant
+m.shape = (3, 1)  # type: ignore[assignment]
+m.dtype = np.bool  # type: ignore[assignment]
+
+np.ma.min(m, axis=1.0)  # type: ignore[call-overload]
+np.ma.min(m, keepdims=1.0)  # type: ignore[call-overload]
+np.ma.min(m, out=1.0)  # type: ignore[call-overload]
+np.ma.min(m, fill_value=lambda x: 27)  # type: ignore[call-overload]
+
+m.min(axis=1.0)  # type: ignore[call-overload]
+m.min(keepdims=1.0)  # type: ignore[call-overload]
+m.min(out=1.0)  # type: ignore[call-overload]
+m.min(fill_value=lambda x: 27)  # type: ignore[call-overload]
+
+np.ma.max(m, axis=1.0)  # type: ignore[call-overload]
+np.ma.max(m, keepdims=1.0)  # type: ignore[call-overload]
+np.ma.max(m, out=1.0)  # type: ignore[call-overload]
+np.ma.max(m, fill_value=lambda x: 27)  # type: ignore[call-overload]
+
+m.max(axis=1.0)  # type: ignore[call-overload]
+m.max(keepdims=1.0)  # type: ignore[call-overload]
+m.max(out=1.0)  # type: ignore[call-overload]
+m.max(fill_value=lambda x: 27)  # type: ignore[call-overload]
 
-np.ma.max(m, axis=1.0)  # E: No overload variant
-np.ma.max(m, keepdims=1.0)  # E: No overload variant
-np.ma.max(m, out=1.0)  # E: No overload variant
-np.ma.max(m, fill_value=lambda x: 27)  # E: No overload variant
+np.ma.ptp(m, axis=1.0)  # type: ignore[call-overload]
+np.ma.ptp(m, keepdims=1.0)  # type: ignore[call-overload]
+np.ma.ptp(m, out=1.0)  # type: ignore[call-overload]
+np.ma.ptp(m, fill_value=lambda x: 27)  # type: ignore[call-overload]
 
-m.max(axis=1.0)  # E: No overload variant
-m.max(keepdims=1.0)  # E: No overload variant
-m.max(out=1.0)  # E: No overload variant
-m.max(fill_value=lambda x: 27)  # E: No overload variant
+m.ptp(axis=1.0)  # type: ignore[call-overload]
+m.ptp(keepdims=1.0)  # type: ignore[call-overload]
+m.ptp(out=1.0)  # type: ignore[call-overload]
+m.ptp(fill_value=lambda x: 27)  # type: ignore[call-overload]
 
-np.ma.ptp(m, axis=1.0)  # E: No overload variant
-np.ma.ptp(m, keepdims=1.0)  # E: No overload variant
-np.ma.ptp(m, out=1.0)  # E: No overload variant
-np.ma.ptp(m, fill_value=lambda x: 27)  # E: No overload variant
+m.argmin(axis=1.0)  # type: ignore[call-overload]
+m.argmin(keepdims=1.0)  # type: ignore[call-overload]
+m.argmin(out=1.0)  # type: ignore[call-overload]
+m.argmin(fill_value=lambda x: 27)  # type: ignore[call-overload]
 
-m.ptp(axis=1.0)  # E: No overload variant
-m.ptp(keepdims=1.0)  # E: No overload variant
-m.ptp(out=1.0)  # E: No overload variant
-m.ptp(fill_value=lambda x: 27)  # E: No overload variant
+np.ma.argmin(m, axis=1.0)  # type: ignore[call-overload]
+np.ma.argmin(m, axis=(1,))  # type: ignore[call-overload]
+np.ma.argmin(m, keepdims=1.0)  # type: ignore[call-overload]
+np.ma.argmin(m, out=1.0)  # type: ignore[call-overload]
+np.ma.argmin(m, fill_value=lambda x: 27)  # type: ignore[call-overload]
 
-m.argmin(axis=1.0)  # E: No overload variant
-m.argmin(keepdims=1.0)  # E: No overload variant
-m.argmin(out=1.0)  # E: No overload variant
-m.argmin(fill_value=lambda x: 27)  # E: No overload variant
+m.argmax(axis=1.0)  # type: ignore[call-overload]
+m.argmax(keepdims=1.0)  # type: ignore[call-overload]
+m.argmax(out=1.0)  # type: ignore[call-overload]
+m.argmax(fill_value=lambda x: 27)  # type: ignore[call-overload]
 
-np.ma.argmin(m, axis=1.0)  # E: No overload variant
-np.ma.argmin(m, axis=(1,))  # E: No overload variant
-np.ma.argmin(m, keepdims=1.0)  # E: No overload variant
-np.ma.argmin(m, out=1.0)  # E: No overload variant
-np.ma.argmin(m, fill_value=lambda x: 27)  # E: No overload variant
+np.ma.argmax(m, axis=1.0)  # type: ignore[call-overload]
+np.ma.argmax(m, axis=(0,))  # type: ignore[call-overload]
+np.ma.argmax(m, keepdims=1.0)  # type: ignore[call-overload]
+np.ma.argmax(m, out=1.0)  # type: ignore[call-overload]
+np.ma.argmax(m, fill_value=lambda x: 27)  # type: ignore[call-overload]
 
-m.argmax(axis=1.0)  # E: No overload variant
-m.argmax(keepdims=1.0)  # E: No overload variant
-m.argmax(out=1.0)  # E: No overload variant
-m.argmax(fill_value=lambda x: 27)  # E: No overload variant
+m.all(axis=1.0)  # type: ignore[call-overload]
+m.all(keepdims=1.0)  # type: ignore[call-overload]
+m.all(out=1.0)  # type: ignore[call-overload]
 
-np.ma.argmax(m, axis=1.0)  # E: No overload variant
-np.ma.argmax(m, axis=(0,))  # E: No overload variant
-np.ma.argmax(m, keepdims=1.0)  # E: No overload variant
-np.ma.argmax(m, out=1.0)  # E: No overload variant
-np.ma.argmax(m, fill_value=lambda x: 27)  # E: No overload variant
+m.any(axis=1.0)  # type: ignore[call-overload]
+m.any(keepdims=1.0)  # type: ignore[call-overload]
+m.any(out=1.0)  # type: ignore[call-overload]
 
-m.all(axis=1.0)  # E: No overload variant
-m.all(keepdims=1.0)  # E: No overload variant
-m.all(out=1.0)  # E: No overload variant
+m.sort(axis=(0,1))  # type: ignore[arg-type]
+m.sort(axis=None)  # type: ignore[arg-type]
+m.sort(kind='cabbage')  # type: ignore[arg-type]
+m.sort(order=lambda: 'cabbage')  # type: ignore[arg-type]
+m.sort(endwith='cabbage')  # type: ignore[arg-type]
+m.sort(fill_value=lambda: 'cabbage')  # type: ignore[arg-type]
+m.sort(stable='cabbage')  # type: ignore[arg-type]
+m.sort(stable=True)  # type: ignore[arg-type]
 
-m.any(axis=1.0)  # E: No overload variant
-m.any(keepdims=1.0)  # E: No overload variant
-m.any(out=1.0)  # E: No overload variant
+m.take(axis=1.0)  # type: ignore[call-overload]
+m.take(out=1)  # type: ignore[call-overload]
+m.take(mode="bob")  # type: ignore[call-overload]
 
-m.sort(axis=(0,1))  # E: No overload variant
-m.sort(axis=None)  # E: No overload variant
-m.sort(kind='cabbage')  # E: No overload variant
-m.sort(order=lambda: 'cabbage')  # E: No overload variant
-m.sort(endwith='cabbage')  # E: No overload variant
-m.sort(fill_value=lambda: 'cabbage')  # E: No overload variant
-m.sort(stable='cabbage')  # E: No overload variant
-m.sort(stable=True)  # E: No overload variant
+np.ma.take(None)  # type: ignore[call-overload]
+np.ma.take(axis=1.0)  # type: ignore[call-overload]
+np.ma.take(out=1)  # type: ignore[call-overload]
+np.ma.take(mode="bob")  # type: ignore[call-overload]
 
-m.take(axis=1.0)  # E: No overload variant
-m.take(out=1)  # E: No overload variant
-m.take(mode="bob")  # E: No overload variant
+m.partition(['cabbage'])  # type: ignore[arg-type]
+m.partition(axis=(0,1))  # type: ignore[arg-type, call-arg]
+m.partition(kind='cabbage')  # type: ignore[arg-type, call-arg]
+m.partition(order=lambda: 'cabbage')  # type: ignore[arg-type, call-arg]
+m.partition(AR_b)  # type: ignore[arg-type]
 
-np.ma.take(None)  # E: No overload variant
-np.ma.take(axis=1.0)  # E: No overload variant
-np.ma.take(out=1)  # E: No overload variant
-np.ma.take(mode="bob")  # E: No overload variant
+m.argpartition(['cabbage'])  # type: ignore[arg-type]
+m.argpartition(axis=(0,1))  # type: ignore[arg-type, call-arg]
+m.argpartition(kind='cabbage')  # type: ignore[arg-type, call-arg]
+m.argpartition(order=lambda: 'cabbage')  # type: ignore[arg-type, call-arg]
+m.argpartition(AR_b)  # type: ignore[arg-type]
 
-m.partition(['cabbage'])  # E: No overload variant
-m.partition(axis=(0,1))  # E: No overload variant
-m.partition(kind='cabbage')  # E: No overload variant
-m.partition(order=lambda: 'cabbage')  # E: No overload variant
-m.partition(AR_b)  # E: No overload variant
+np.ma.ndim(lambda: 'lambda')  # type: ignore[arg-type]
 
-m.argpartition(['cabbage'])  # E: No overload variant
-m.argpartition(axis=(0,1))  # E: No overload variant
-m.argpartition(kind='cabbage')  # E: No overload variant
-m.argpartition(order=lambda: 'cabbage')  # E: No overload variant
-m.argpartition(AR_b)  # E: No overload variant
+np.ma.size(AR_b, axis='0')  # type: ignore[arg-type]
 
-np.ma.ndim(lambda: 'lambda')  # E: No overload variant
+m >= (lambda x: 'mango') # type: ignore[operator]
+m > (lambda x: 'mango') # type: ignore[operator]
+m <= (lambda x: 'mango') # type: ignore[operator]
+m < (lambda x: 'mango') # type: ignore[operator]
 
-np.ma.size(AR_b, axis='0')  # E: No overload variant
+m.count(axis=0.)  # type: ignore[call-overload]
+
+np.ma.count(m, axis=0.)  # type: ignore[call-overload]
 
-m >= (lambda x: 'mango') # E: No overload variant
+m.put(4, 999, mode='flip')  # type: ignore[arg-type]
 
-m > (lambda x: 'mango') # E: No overload variant
+np.ma.put(m, 4, 999, mode='flip')  # type: ignore[arg-type]
 
-m <= (lambda x: 'mango') # E: No overload variant
+np.ma.put([1,1,3], 0, 999)  # type: ignore[arg-type]
 
-m < (lambda x: 'mango') # E: No overload variant
+np.ma.compressed(lambda: 'compress me')  # type: ignore[call-overload]
 
-m.count(axis=0.)  # E: No overload variant
+np.ma.allequal(m, [1,2,3], fill_value=1.5)  # type: ignore[arg-type]
 
-np.ma.count(m, axis=0.)  # E: No overload variant
+np.ma.allclose(m, [1,2,3], masked_equal=4.5)  # type: ignore[arg-type]
+np.ma.allclose(m, [1,2,3], rtol='.4')  # type: ignore[arg-type]
+np.ma.allclose(m, [1,2,3], atol='.5')  # type: ignore[arg-type]
 
-m.put(4, 999, mode='flip')  # E: No overload variant
+m.__setmask__('mask')  # type: ignore[arg-type]
 
-np.ma.put(m, 4, 999, mode='flip')  # E: No overload variant
-
-np.ma.put([1,1,3], 0, 999)  # E: No overload variant
-
-np.ma.compressed(lambda: 'compress me')  # E: No overload variant
-
-np.ma.allequal(m, [1,2,3], fill_value=1.5)  # E: No overload variant
-
-np.ma.allclose(m, [1,2,3], masked_equal=4.5)  # E: No overload variant
-np.ma.allclose(m, [1,2,3], rtol='.4')  # E: No overload variant
-np.ma.allclose(m, [1,2,3], atol='.5')  # E: No overload variant
-
-m.__setmask__('mask')  # E: No overload variant
-
-m.swapaxes(axis1=1, axis2=0)  # E: No overload variant
+m.swapaxes(axis1=1, axis2=0)  # type: ignore[call-arg]
diff --git a/numpy/typing/tests/data/fail/memmap.pyi b/numpy/typing/tests/data/fail/memmap.pyi
index 434870b60e41..3a4fc7df0689 100644
--- a/numpy/typing/tests/data/fail/memmap.pyi
+++ b/numpy/typing/tests/data/fail/memmap.pyi
@@ -1,5 +1,5 @@
 import numpy as np
 
 with open("file.txt", "r") as f:
-    np.memmap(f)  # E: No overload variant
-np.memmap("test.txt", shape=[10, 5])  # E: No overload variant
+    np.memmap(f)  # type: ignore[call-overload]
+np.memmap("test.txt", shape=[10, 5])  # type: ignore[call-overload]
diff --git a/numpy/typing/tests/data/fail/modules.pyi b/numpy/typing/tests/data/fail/modules.pyi
index 541be15b24ae..c12a182807d3 100644
--- a/numpy/typing/tests/data/fail/modules.pyi
+++ b/numpy/typing/tests/data/fail/modules.pyi
@@ -1,17 +1,17 @@
 import numpy as np
 
-np.testing.bob  # E: Module has no attribute
-np.bob  # E: Module has no attribute
+np.testing.bob  # type: ignore[attr-defined]
+np.bob  # type: ignore[attr-defined]
 
 # Stdlib modules in the namespace by accident
-np.warnings  # E: Module has no attribute
-np.sys  # E: Module has no attribute
-np.os  # E: Module "numpy" does not explicitly export
-np.math  # E: Module has no attribute
+np.warnings  # type: ignore[attr-defined]
+np.sys  # type: ignore[attr-defined]
+np.os  # type: ignore[attr-defined]
+np.math  # type: ignore[attr-defined]
 
 # Public sub-modules that are not imported to their parent module by default;
 # e.g. one must first execute `import numpy.lib.recfunctions`
-np.lib.recfunctions  # E: Module has no attribute
+np.lib.recfunctions  # type: ignore[attr-defined]
 
-np.__deprecated_attrs__  # E: Module has no attribute
-np.__expired_functions__  # E: Module has no attribute
+np.__deprecated_attrs__  # type: ignore[attr-defined]
+np.__expired_functions__  # type: ignore[attr-defined]
diff --git a/numpy/typing/tests/data/fail/multiarray.pyi b/numpy/typing/tests/data/fail/multiarray.pyi
index 7734f670d16b..1f9ef6894bad 100644
--- a/numpy/typing/tests/data/fail/multiarray.pyi
+++ b/numpy/typing/tests/data/fail/multiarray.pyi
@@ -15,38 +15,38 @@ AR_LIKE_f: list[float]
 
 def func(a: int) -> None: ...
 
-np.where(AR_b, 1)  # E: No overload variant
+np.where(AR_b, 1)  # type: ignore[call-overload]
 
-np.can_cast(AR_f8, 1)  # E: incompatible type
+np.can_cast(AR_f8, 1)  # type: ignore[arg-type]
 
-np.vdot(AR_M, AR_M)  # E: incompatible type
+np.vdot(AR_M, AR_M)  # type: ignore[arg-type]
 
-np.copyto(AR_LIKE_f, AR_f8)  # E: incompatible type
+np.copyto(AR_LIKE_f, AR_f8)  # type: ignore[arg-type]
 
-np.putmask(AR_LIKE_f, [True, True, False], 1.5)  # E: incompatible type
+np.putmask(AR_LIKE_f, [True, True, False], 1.5)  # type: ignore[arg-type]
 
-np.packbits(AR_f8)  # E: incompatible type
-np.packbits(AR_u1, bitorder=">")  # E: incompatible type
+np.packbits(AR_f8)  # type: ignore[arg-type]
+np.packbits(AR_u1, bitorder=">")  # type: ignore[arg-type]
 
-np.unpackbits(AR_i8)  # E: incompatible type
-np.unpackbits(AR_u1, bitorder=">")  # E: incompatible type
+np.unpackbits(AR_i8)  # type: ignore[arg-type]
+np.unpackbits(AR_u1, bitorder=">")  # type: ignore[arg-type]
 
-np.shares_memory(1, 1, max_work=i8)  # E: incompatible type
-np.may_share_memory(1, 1, max_work=i8)  # E: incompatible type
+np.shares_memory(1, 1, max_work=i8)  # type: ignore[arg-type]
+np.may_share_memory(1, 1, max_work=i8)  # type: ignore[arg-type]
 
-np.arange(stop=10)  # E: No overload variant
+np.arange(stop=10)  # type: ignore[call-overload]
 
-np.datetime_data(int)  # E: incompatible type
+np.datetime_data(int)  # type: ignore[arg-type]
 
-np.busday_offset("2012", 10)  # E: No overload variant
+np.busday_offset("2012", 10)  # type: ignore[call-overload]
 
-np.datetime_as_string("2012")  # E: No overload variant
+np.datetime_as_string("2012")  # type: ignore[call-overload]
 
-np.char.compare_chararrays("a", b"a", "==", False)  # E: No overload variant
+np.char.compare_chararrays("a", b"a", "==", False)  # type: ignore[call-overload]
 
-np.nested_iters([AR_i8, AR_i8])  # E: Missing positional argument
-np.nested_iters([AR_i8, AR_i8], 0)  # E: incompatible type
-np.nested_iters([AR_i8, AR_i8], [0])  # E: incompatible type
-np.nested_iters([AR_i8, AR_i8], [[0], [1]], flags=["test"])  # E: incompatible type
-np.nested_iters([AR_i8, AR_i8], [[0], [1]], op_flags=[["test"]])  # E: incompatible type
-np.nested_iters([AR_i8, AR_i8], [[0], [1]], buffersize=1.0)  # E: incompatible type
+np.nested_iters([AR_i8, AR_i8])  # type: ignore[call-arg]
+np.nested_iters([AR_i8, AR_i8], 0)  # type: ignore[arg-type]
+np.nested_iters([AR_i8, AR_i8], [0])  # type: ignore[list-item]
+np.nested_iters([AR_i8, AR_i8], [[0], [1]], flags=["test"])  # type: ignore[list-item]
+np.nested_iters([AR_i8, AR_i8], [[0], [1]], op_flags=[["test"]])  # type: ignore[list-item]
+np.nested_iters([AR_i8, AR_i8], [[0], [1]], buffersize=1.0)  # type: ignore[arg-type]
diff --git a/numpy/typing/tests/data/fail/ndarray.pyi b/numpy/typing/tests/data/fail/ndarray.pyi
index 5ecae02e6178..2aeec0883e3f 100644
--- a/numpy/typing/tests/data/fail/ndarray.pyi
+++ b/numpy/typing/tests/data/fail/ndarray.pyi
@@ -8,4 +8,4 @@ import numpy as np
 #
 # for more context.
 float_array = np.array([1.0])
-float_array.dtype = np.bool  # E: Property "dtype" defined in "ndarray" is read-only
+float_array.dtype = np.bool  # type: ignore[assignment, misc]
diff --git a/numpy/typing/tests/data/fail/ndarray_misc.pyi b/numpy/typing/tests/data/fail/ndarray_misc.pyi
index 489aefca7ffc..93e1bce8fecb 100644
--- a/numpy/typing/tests/data/fail/ndarray_misc.pyi
+++ b/numpy/typing/tests/data/fail/ndarray_misc.pyi
@@ -16,21 +16,21 @@ AR_b: npt.NDArray[np.bool]
 
 ctypes_obj = AR_f8.ctypes
 
-f8.argpartition(0)  # E: has no attribute
-f8.diagonal()  # E: has no attribute
-f8.dot(1)  # E: has no attribute
-f8.nonzero()  # E: has no attribute
-f8.partition(0)  # E: has no attribute
-f8.put(0, 2)  # E: has no attribute
-f8.setfield(2, np.float64)  # E: has no attribute
-f8.sort()  # E: has no attribute
-f8.trace()  # E: has no attribute
-
-AR_M.__complex__()  # E: Invalid self argument
-AR_b.__index__()  # E: Invalid self argument
-
-AR_f8[1.5]  # E: No overload variant
-AR_f8["field_a"]  # E: No overload variant
-AR_f8[["field_a", "field_b"]]  # E: Invalid index type
-
-AR_f8.__array_finalize__(object())  # E: incompatible type
+f8.argpartition(0)  # type: ignore[attr-defined]
+f8.diagonal()  # type: ignore[attr-defined]
+f8.dot(1)  # type: ignore[attr-defined]
+f8.nonzero()  # type: ignore[attr-defined]
+f8.partition(0)  # type: ignore[attr-defined]
+f8.put(0, 2)  # type: ignore[attr-defined]
+f8.setfield(2, np.float64)  # type: ignore[attr-defined]
+f8.sort()  # type: ignore[attr-defined]
+f8.trace()  # type: ignore[attr-defined]
+
+AR_M.__complex__()  # type: ignore[misc]
+AR_b.__index__()  # type: ignore[misc]
+
+AR_f8[1.5]  # type: ignore[call-overload]
+AR_f8["field_a"]  # type: ignore[call-overload]
+AR_f8[["field_a", "field_b"]]  # type: ignore[index]
+
+AR_f8.__array_finalize__(object())  # type: ignore[arg-type]
diff --git a/numpy/typing/tests/data/fail/nditer.pyi b/numpy/typing/tests/data/fail/nditer.pyi
index 1e8e37ee5fe0..cb64061e45fe 100644
--- a/numpy/typing/tests/data/fail/nditer.pyi
+++ b/numpy/typing/tests/data/fail/nditer.pyi
@@ -1,8 +1,8 @@
 import numpy as np
 
-class Test(np.nditer): ...  # E: Cannot inherit from final class
+class Test(np.nditer): ...  # type: ignore[misc]
 
-np.nditer([0, 1], flags=["test"])  # E: incompatible type
-np.nditer([0, 1], op_flags=[["test"]])  # E: incompatible type
-np.nditer([0, 1], itershape=(1.0,))  # E: incompatible type
-np.nditer([0, 1], buffersize=1.0)  # E: incompatible type
+np.nditer([0, 1], flags=["test"])  # type: ignore[list-item]
+np.nditer([0, 1], op_flags=[["test"]])  # type: ignore[list-item]
+np.nditer([0, 1], itershape=(1.0,))  # type: ignore[arg-type]
+np.nditer([0, 1], buffersize=1.0)  # type: ignore[arg-type]
diff --git a/numpy/typing/tests/data/fail/nested_sequence.pyi b/numpy/typing/tests/data/fail/nested_sequence.pyi
index 02c7beb6785d..a28d3df3c749 100644
--- a/numpy/typing/tests/data/fail/nested_sequence.pyi
+++ b/numpy/typing/tests/data/fail/nested_sequence.pyi
@@ -9,8 +9,8 @@ e: str
 
 def func(a: _NestedSequence[int]) -> None: ...
 
-reveal_type(func(a))  # E: incompatible type
-reveal_type(func(b))  # E: incompatible type
-reveal_type(func(c))  # E: incompatible type
-reveal_type(func(d))  # E: incompatible type
-reveal_type(func(e))  # E: incompatible type
+reveal_type(func(a))  # type: ignore[arg-type, misc]
+reveal_type(func(b))  # type: ignore[arg-type, misc]
+reveal_type(func(c))  # type: ignore[arg-type, misc]
+reveal_type(func(d))  # type: ignore[arg-type, misc]
+reveal_type(func(e))  # type: ignore[arg-type, misc]
diff --git a/numpy/typing/tests/data/fail/npyio.pyi b/numpy/typing/tests/data/fail/npyio.pyi
index 6ba6a6be1797..e204566a5877 100644
--- a/numpy/typing/tests/data/fail/npyio.pyi
+++ b/numpy/typing/tests/data/fail/npyio.pyi
@@ -10,16 +10,15 @@ pathlib_path: pathlib.Path
 str_file: IO[str]
 AR_i8: npt.NDArray[np.int64]
 
-np.load(str_file)  # E: incompatible type
+np.load(str_file)  # type: ignore[arg-type]
 
-np.save(bytes_path, AR_i8)  # E: No overload variant
-# https://github.com/python/mypy/issues/16111
-# np.save(str_path, AR_i8, fix_imports=True)  # W: deprecated
+np.save(bytes_path, AR_i8)  # type: ignore[call-overload]
+np.save(str_path, AR_i8, fix_imports=True)  # type: ignore[deprecated]  # pyright: ignore[reportDeprecated]
 
-np.savez(bytes_path, AR_i8)  # E: incompatible type
+np.savez(bytes_path, AR_i8)  # type: ignore[arg-type]
 
-np.savez_compressed(bytes_path, AR_i8)  # E: incompatible type
+np.savez_compressed(bytes_path, AR_i8)  # type: ignore[arg-type]
 
-np.loadtxt(bytes_path)  # E: incompatible type
+np.loadtxt(bytes_path)  # type: ignore[arg-type]
 
-np.fromregex(bytes_path, ".", np.int64)  # E: No overload variant
+np.fromregex(bytes_path, ".", np.int64)  # type: ignore[call-overload]
diff --git a/numpy/typing/tests/data/fail/numerictypes.pyi b/numpy/typing/tests/data/fail/numerictypes.pyi
index 29a3cf30dd95..a1fd47a6f479 100644
--- a/numpy/typing/tests/data/fail/numerictypes.pyi
+++ b/numpy/typing/tests/data/fail/numerictypes.pyi
@@ -1,5 +1,5 @@
 import numpy as np
 
-np.isdtype(1, np.int64)  # E: incompatible type
+np.isdtype(1, np.int64)  # type: ignore[arg-type]
 
-np.issubdtype(1, np.int64)  # E: incompatible type
+np.issubdtype(1, np.int64)  # type: ignore[arg-type]
diff --git a/numpy/typing/tests/data/fail/random.pyi b/numpy/typing/tests/data/fail/random.pyi
index aa1eae4424e2..1abf4b77653c 100644
--- a/numpy/typing/tests/data/fail/random.pyi
+++ b/numpy/typing/tests/data/fail/random.pyi
@@ -8,55 +8,55 @@ SEED_SEED_SEQ: np.random.SeedSequence = np.random.SeedSequence(0)
 SEED_STR: str = "String seeding not allowed"
 
 # default rng
-np.random.default_rng(SEED_FLOAT)  # E: incompatible type
-np.random.default_rng(SEED_ARR_FLOAT)  # E: incompatible type
-np.random.default_rng(SEED_ARRLIKE_FLOAT)  # E: incompatible type
-np.random.default_rng(SEED_STR)  # E: incompatible type
+np.random.default_rng(SEED_FLOAT)  # type: ignore[arg-type]
+np.random.default_rng(SEED_ARR_FLOAT)  # type: ignore[arg-type]
+np.random.default_rng(SEED_ARRLIKE_FLOAT)  # type: ignore[arg-type]
+np.random.default_rng(SEED_STR)  # type: ignore[arg-type]
 
 # Seed Sequence
-np.random.SeedSequence(SEED_FLOAT)  # E: incompatible type
-np.random.SeedSequence(SEED_ARR_FLOAT)  # E: incompatible type
-np.random.SeedSequence(SEED_ARRLIKE_FLOAT)  # E: incompatible type
-np.random.SeedSequence(SEED_SEED_SEQ)  # E: incompatible type
-np.random.SeedSequence(SEED_STR)  # E: incompatible type
+np.random.SeedSequence(SEED_FLOAT)  # type: ignore[arg-type]
+np.random.SeedSequence(SEED_ARR_FLOAT)  # type: ignore[arg-type]
+np.random.SeedSequence(SEED_ARRLIKE_FLOAT)  # type: ignore[arg-type]
+np.random.SeedSequence(SEED_SEED_SEQ)  # type: ignore[arg-type]
+np.random.SeedSequence(SEED_STR)  # type: ignore[arg-type]
 
 seed_seq: np.random.bit_generator.SeedSequence = np.random.SeedSequence()
-seed_seq.spawn(11.5)  # E: incompatible type
-seed_seq.generate_state(3.14)  # E: incompatible type
-seed_seq.generate_state(3, np.uint8)  # E: incompatible type
-seed_seq.generate_state(3, "uint8")  # E: incompatible type
-seed_seq.generate_state(3, "u1")  # E: incompatible type
-seed_seq.generate_state(3, np.uint16)  # E: incompatible type
-seed_seq.generate_state(3, "uint16")  # E: incompatible type
-seed_seq.generate_state(3, "u2")  # E: incompatible type
-seed_seq.generate_state(3, np.int32)  # E: incompatible type
-seed_seq.generate_state(3, "int32")  # E: incompatible type
-seed_seq.generate_state(3, "i4")  # E: incompatible type
+seed_seq.spawn(11.5)  # type: ignore[arg-type]
+seed_seq.generate_state(3.14)  # type: ignore[arg-type]
+seed_seq.generate_state(3, np.uint8)  # type: ignore[arg-type]
+seed_seq.generate_state(3, "uint8")  # type: ignore[arg-type]
+seed_seq.generate_state(3, "u1")  # type: ignore[arg-type]
+seed_seq.generate_state(3, np.uint16)  # type: ignore[arg-type]
+seed_seq.generate_state(3, "uint16")  # type: ignore[arg-type]
+seed_seq.generate_state(3, "u2")  # type: ignore[arg-type]
+seed_seq.generate_state(3, np.int32)  # type: ignore[arg-type]
+seed_seq.generate_state(3, "int32")  # type: ignore[arg-type]
+seed_seq.generate_state(3, "i4")  # type: ignore[arg-type]
 
 # Bit Generators
-np.random.MT19937(SEED_FLOAT)  # E: incompatible type
-np.random.MT19937(SEED_ARR_FLOAT)  # E: incompatible type
-np.random.MT19937(SEED_ARRLIKE_FLOAT)  # E: incompatible type
-np.random.MT19937(SEED_STR)  # E: incompatible type
-
-np.random.PCG64(SEED_FLOAT)  # E: incompatible type
-np.random.PCG64(SEED_ARR_FLOAT)  # E: incompatible type
-np.random.PCG64(SEED_ARRLIKE_FLOAT)  # E: incompatible type
-np.random.PCG64(SEED_STR)  # E: incompatible type
-
-np.random.Philox(SEED_FLOAT)  # E: incompatible type
-np.random.Philox(SEED_ARR_FLOAT)  # E: incompatible type
-np.random.Philox(SEED_ARRLIKE_FLOAT)  # E: incompatible type
-np.random.Philox(SEED_STR)  # E: incompatible type
-
-np.random.SFC64(SEED_FLOAT)  # E: incompatible type
-np.random.SFC64(SEED_ARR_FLOAT)  # E: incompatible type
-np.random.SFC64(SEED_ARRLIKE_FLOAT)  # E: incompatible type
-np.random.SFC64(SEED_STR)  # E: incompatible type
+np.random.MT19937(SEED_FLOAT)  # type: ignore[arg-type]
+np.random.MT19937(SEED_ARR_FLOAT)  # type: ignore[arg-type]
+np.random.MT19937(SEED_ARRLIKE_FLOAT)  # type: ignore[arg-type]
+np.random.MT19937(SEED_STR)  # type: ignore[arg-type]
+
+np.random.PCG64(SEED_FLOAT)  # type: ignore[arg-type]
+np.random.PCG64(SEED_ARR_FLOAT)  # type: ignore[arg-type]
+np.random.PCG64(SEED_ARRLIKE_FLOAT)  # type: ignore[arg-type]
+np.random.PCG64(SEED_STR)  # type: ignore[arg-type]
+
+np.random.Philox(SEED_FLOAT)  # type: ignore[arg-type]
+np.random.Philox(SEED_ARR_FLOAT)  # type: ignore[arg-type]
+np.random.Philox(SEED_ARRLIKE_FLOAT)  # type: ignore[arg-type]
+np.random.Philox(SEED_STR)  # type: ignore[arg-type]
+
+np.random.SFC64(SEED_FLOAT)  # type: ignore[arg-type]
+np.random.SFC64(SEED_ARR_FLOAT)  # type: ignore[arg-type]
+np.random.SFC64(SEED_ARRLIKE_FLOAT)  # type: ignore[arg-type]
+np.random.SFC64(SEED_STR)  # type: ignore[arg-type]
 
 # Generator
-np.random.Generator(None)  # E: incompatible type
-np.random.Generator(12333283902830213)  # E: incompatible type
-np.random.Generator("OxFEEDF00D")  # E: incompatible type
-np.random.Generator([123, 234])  # E: incompatible type
-np.random.Generator(np.array([123, 234], dtype="u4"))  # E: incompatible type
+np.random.Generator(None)  # type: ignore[arg-type]
+np.random.Generator(12333283902830213)  # type: ignore[arg-type]
+np.random.Generator("OxFEEDF00D")  # type: ignore[arg-type]
+np.random.Generator([123, 234])  # type: ignore[arg-type]
+np.random.Generator(np.array([123, 234], dtype="u4"))  # type: ignore[arg-type]
diff --git a/numpy/typing/tests/data/fail/rec.pyi b/numpy/typing/tests/data/fail/rec.pyi
index a57f1ba27d74..c9d43dd2ff1f 100644
--- a/numpy/typing/tests/data/fail/rec.pyi
+++ b/numpy/typing/tests/data/fail/rec.pyi
@@ -3,15 +3,15 @@ import numpy.typing as npt
 
 AR_i8: npt.NDArray[np.int64]
 
-np.rec.fromarrays(1)  # E: No overload variant
-np.rec.fromarrays([1, 2, 3], dtype=[("f8", "f8")], formats=["f8", "f8"])  # E: No overload variant
+np.rec.fromarrays(1)  # type: ignore[call-overload]
+np.rec.fromarrays([1, 2, 3], dtype=[("f8", "f8")], formats=["f8", "f8"])  # type: ignore[call-overload]
 
-np.rec.fromrecords(AR_i8)  # E: incompatible type
-np.rec.fromrecords([(1.5,)], dtype=[("f8", "f8")], formats=["f8", "f8"])  # E: No overload variant
+np.rec.fromrecords(AR_i8)  # type: ignore[arg-type]
+np.rec.fromrecords([(1.5,)], dtype=[("f8", "f8")], formats=["f8", "f8"])  # type: ignore[call-overload]
 
-np.rec.fromstring("string", dtype=[("f8", "f8")])  # E: No overload variant
-np.rec.fromstring(b"bytes")  # E: No overload variant
-np.rec.fromstring(b"(1.5,)", dtype=[("f8", "f8")], formats=["f8", "f8"])  # E: No overload variant
+np.rec.fromstring("string", dtype=[("f8", "f8")])  # type: ignore[call-overload]
+np.rec.fromstring(b"bytes")  # type: ignore[call-overload]
+np.rec.fromstring(b"(1.5,)", dtype=[("f8", "f8")], formats=["f8", "f8"])  # type: ignore[call-overload]
 
 with open("test", "r") as f:
-    np.rec.fromfile(f, dtype=[("f8", "f8")])  # E: No overload variant
+    np.rec.fromfile(f, dtype=[("f8", "f8")])  # type: ignore[call-overload]
diff --git a/numpy/typing/tests/data/fail/scalars.pyi b/numpy/typing/tests/data/fail/scalars.pyi
index adbb7570797d..bfbe9125e529 100644
--- a/numpy/typing/tests/data/fail/scalars.pyi
+++ b/numpy/typing/tests/data/fail/scalars.pyi
@@ -7,7 +7,7 @@ c8: np.complex64
 
 # Construction
 
-np.float32(3j)  # E: incompatible type
+np.float32(3j)  # type: ignore[arg-type]
 
 # Technically the following examples are valid NumPy code. But they
 # are not considered a best practice, and people who wish to use the
@@ -25,64 +25,63 @@ np.float32(3j)  # E: incompatible type
 # https://github.com/numpy/numpy-stubs/issues/41
 #
 # for more context.
-np.float32([1.0, 0.0, 0.0])  # E: incompatible type
-np.complex64([])  # E: incompatible type
+np.float32([1.0, 0.0, 0.0])  # type: ignore[arg-type]
+np.complex64([])  # type: ignore[call-overload]
 
 # TODO: protocols (can't check for non-existent protocols w/ __getattr__)
 
-np.datetime64(0)  # E: No overload variant
+np.datetime64(0)  # type: ignore[call-overload]
 
 class A:
-    def __float__(self):
-        return 1.0
-
-np.int8(A())  # E: incompatible type
-np.int16(A())  # E: incompatible type
-np.int32(A())  # E: incompatible type
-np.int64(A())  # E: incompatible type
-np.uint8(A())  # E: incompatible type
-np.uint16(A())  # E: incompatible type
-np.uint32(A())  # E: incompatible type
-np.uint64(A())  # E: incompatible type
-
-np.void("test")  # E: No overload variant
-np.void("test", dtype=None)  # E: No overload variant
-
-np.generic(1)  # E: Cannot instantiate abstract class
-np.number(1)  # E: Cannot instantiate abstract class
-np.integer(1)  # E: Cannot instantiate abstract class
-np.inexact(1)  # E: Cannot instantiate abstract class
-np.character("test")  # E: Cannot instantiate abstract class
-np.flexible(b"test")  # E: Cannot instantiate abstract class
-
-np.float64(value=0.0)  # E: Unexpected keyword argument
-np.int64(value=0)  # E: Unexpected keyword argument
-np.uint64(value=0)  # E: Unexpected keyword argument
-np.complex128(value=0.0j)  # E: No overload variant
-np.str_(value='bob')  # E: No overload variant
-np.bytes_(value=b'test')  # E: No overload variant
-np.void(value=b'test')  # E: No overload variant
-np.bool(value=True)  # E: Unexpected keyword argument
-np.datetime64(value="2019")  # E: No overload variant
-np.timedelta64(value=0)  # E: Unexpected keyword argument
-
-np.bytes_(b"hello", encoding='utf-8')  # E: No overload variant
-np.str_("hello", encoding='utf-8')  # E: No overload variant
-
-f8.item(1)  # E: incompatible type
-f8.item((0, 1))  # E: incompatible type
-f8.squeeze(axis=1)  # E: incompatible type
-f8.squeeze(axis=(0, 1))  # E: incompatible type
-f8.transpose(1)  # E: incompatible type
+    def __float__(self) -> float: ...
+
+np.int8(A())  # type: ignore[arg-type]
+np.int16(A())  # type: ignore[arg-type]
+np.int32(A())  # type: ignore[arg-type]
+np.int64(A())  # type: ignore[arg-type]
+np.uint8(A())  # type: ignore[arg-type]
+np.uint16(A())  # type: ignore[arg-type]
+np.uint32(A())  # type: ignore[arg-type]
+np.uint64(A())  # type: ignore[arg-type]
+
+np.void("test")  # type: ignore[call-overload]
+np.void("test", dtype=None)  # type: ignore[call-overload]
+
+np.generic(1)  # type: ignore[abstract]
+np.number(1)  # type: ignore[abstract]
+np.integer(1)  # type: ignore[abstract]
+np.inexact(1)  # type: ignore[abstract]
+np.character("test")  # type: ignore[abstract]
+np.flexible(b"test")  # type: ignore[abstract]
+
+np.float64(value=0.0)  # type: ignore[call-arg]
+np.int64(value=0)  # type: ignore[call-arg]
+np.uint64(value=0)  # type: ignore[call-arg]
+np.complex128(value=0.0j)  # type: ignore[call-overload]
+np.str_(value='bob')  # type: ignore[call-overload]
+np.bytes_(value=b'test')  # type: ignore[call-overload]
+np.void(value=b'test')  # type: ignore[call-overload]
+np.bool(value=True)  # type: ignore[call-overload]
+np.datetime64(value="2019")  # type: ignore[call-overload]
+np.timedelta64(value=0)  # type: ignore[call-overload]
+
+np.bytes_(b"hello", encoding='utf-8')  # type: ignore[call-overload]
+np.str_("hello", encoding='utf-8')  # type: ignore[call-overload]
+
+f8.item(1)  # type: ignore[call-overload]
+f8.item((0, 1))  # type: ignore[arg-type]
+f8.squeeze(axis=1)  # type: ignore[arg-type]
+f8.squeeze(axis=(0, 1))  # type: ignore[arg-type]
+f8.transpose(1)  # type: ignore[arg-type]
 
 def func(a: np.float32) -> None: ...
 
-func(f2)  # E: incompatible type
-func(f8)  # E: incompatible type
+func(f2)  # type: ignore[arg-type]
+func(f8)  # type: ignore[arg-type]
 
-c8.__getnewargs__()  # E: Invalid self argument
-f2.__getnewargs__()  # E: Invalid self argument
-f2.hex()  # E: Invalid self argument
-np.float16.fromhex("0x0.0p+0")  # E: Invalid self argument
-f2.__trunc__()  # E: Invalid self argument
-f2.__getformat__("float")  # E: Invalid self argument
+c8.__getnewargs__()  # type: ignore[attr-defined]
+f2.__getnewargs__()  # type: ignore[attr-defined]
+f2.hex()  # type: ignore[attr-defined]
+np.float16.fromhex("0x0.0p+0")  # type: ignore[attr-defined]
+f2.__trunc__()  # type: ignore[attr-defined]
+f2.__getformat__("float")  # type: ignore[attr-defined]
diff --git a/numpy/typing/tests/data/fail/shape.pyi b/numpy/typing/tests/data/fail/shape.pyi
index f540eef1871e..fea055583073 100644
--- a/numpy/typing/tests/data/fail/shape.pyi
+++ b/numpy/typing/tests/data/fail/shape.pyi
@@ -3,4 +3,4 @@ import numpy as np
 
 # test bounds of _ShapeT_co
 
-np.ndarray[tuple[str, str], Any]  # E: Value of type variable
+np.ndarray[tuple[str, str], Any]  # type: ignore[type-var]
diff --git a/numpy/typing/tests/data/fail/shape_base.pyi b/numpy/typing/tests/data/fail/shape_base.pyi
index e709741b7935..652b24ba311e 100644
--- a/numpy/typing/tests/data/fail/shape_base.pyi
+++ b/numpy/typing/tests/data/fail/shape_base.pyi
@@ -5,4 +5,4 @@ class DTypeLike:
 
 dtype_like: DTypeLike
 
-np.expand_dims(dtype_like, (5, 10))  # E: No overload variant
+np.expand_dims(dtype_like, (5, 10))  # type: ignore[call-overload]
diff --git a/numpy/typing/tests/data/fail/stride_tricks.pyi b/numpy/typing/tests/data/fail/stride_tricks.pyi
index f2bfba7432a8..7f9a26b96924 100644
--- a/numpy/typing/tests/data/fail/stride_tricks.pyi
+++ b/numpy/typing/tests/data/fail/stride_tricks.pyi
@@ -3,7 +3,7 @@ import numpy.typing as npt
 
 AR_f8: npt.NDArray[np.float64]
 
-np.lib.stride_tricks.as_strided(AR_f8, shape=8)  # E: No overload variant
-np.lib.stride_tricks.as_strided(AR_f8, strides=8)  # E: No overload variant
+np.lib.stride_tricks.as_strided(AR_f8, shape=8)  # type: ignore[call-overload]
+np.lib.stride_tricks.as_strided(AR_f8, strides=8)  # type: ignore[call-overload]
 
-np.lib.stride_tricks.sliding_window_view(AR_f8, axis=(1,))  # E: No overload variant
+np.lib.stride_tricks.sliding_window_view(AR_f8, axis=(1,))  # type: ignore[call-overload]
diff --git a/numpy/typing/tests/data/fail/strings.pyi b/numpy/typing/tests/data/fail/strings.pyi
index ac27c8d6ae64..328a521ae679 100644
--- a/numpy/typing/tests/data/fail/strings.pyi
+++ b/numpy/typing/tests/data/fail/strings.pyi
@@ -4,56 +4,49 @@ import numpy.typing as npt
 AR_U: npt.NDArray[np.str_]
 AR_S: npt.NDArray[np.bytes_]
 
-np.strings.equal(AR_U, AR_S)  # E: incompatible type
-
-np.strings.not_equal(AR_U, AR_S)  # E: incompatible type
-
-np.strings.greater_equal(AR_U, AR_S)  # E: incompatible type
-
-np.strings.less_equal(AR_U, AR_S)  # E: incompatible type
-
-np.strings.greater(AR_U, AR_S)  # E: incompatible type
-
-np.strings.less(AR_U, AR_S)  # E: incompatible type
-
-np.strings.encode(AR_S)  # E: incompatible type
-np.strings.decode(AR_U)  # E: incompatible type
-
-np.strings.join(AR_U, b"_")  # E: incompatible type
-np.strings.join(AR_S, "_")  # E: incompatible type
-
-np.strings.lstrip(AR_U, b"a")  # E: incompatible type
-np.strings.lstrip(AR_S, "a")  # E: incompatible type
-np.strings.strip(AR_U, b"a")  # E: incompatible type
-np.strings.strip(AR_S, "a")  # E: incompatible type
-np.strings.rstrip(AR_U, b"a")  # E: incompatible type
-np.strings.rstrip(AR_S, "a")  # E: incompatible type
-
-np.strings.partition(AR_U, b"a")  # E: incompatible type
-np.strings.partition(AR_S, "a")  # E: incompatible type
-np.strings.rpartition(AR_U, b"a")  # E: incompatible type
-np.strings.rpartition(AR_S, "a")  # E: incompatible type
-
-np.strings.count(AR_U, b"a", [1, 2, 3], [1, 2, 3])  # E: incompatible type
-np.strings.count(AR_S, "a", 0, 9)  # E: incompatible type
-
-np.strings.endswith(AR_U, b"a", [1, 2, 3], [1, 2, 3])  # E: incompatible type
-np.strings.endswith(AR_S, "a", 0, 9)  # E: incompatible type
-np.strings.startswith(AR_U, b"a", [1, 2, 3], [1, 2, 3])  # E: incompatible type
-np.strings.startswith(AR_S, "a", 0, 9)  # E: incompatible type
-
-np.strings.find(AR_U, b"a", [1, 2, 3], [1, 2, 3])  # E: incompatible type
-np.strings.find(AR_S, "a", 0, 9)  # E: incompatible type
-np.strings.rfind(AR_U, b"a", [1, 2, 3], [1, 2, 3])  # E: incompatible type
-np.strings.rfind(AR_S, "a", 0, 9)  # E: incompatible type
-
-np.strings.index(AR_U, b"a", start=[1, 2, 3])  # E: incompatible type
-np.strings.index(AR_S, "a", end=9)  # E: incompatible type
-np.strings.rindex(AR_U, b"a", start=[1, 2, 3])  # E: incompatible type
-np.strings.rindex(AR_S, "a", end=9)  # E: incompatible type
-
-np.strings.isdecimal(AR_S)  # E: incompatible type
-np.strings.isnumeric(AR_S)  # E: incompatible type
-
-np.strings.replace(AR_U, b"_", b"-", 10)  # E: incompatible type
-np.strings.replace(AR_S, "_", "-", 1)  # E: incompatible type
+np.strings.equal(AR_U, AR_S)  # type: ignore[arg-type]
+np.strings.not_equal(AR_U, AR_S)  # type: ignore[arg-type]
+
+np.strings.greater_equal(AR_U, AR_S)  # type: ignore[arg-type]
+np.strings.less_equal(AR_U, AR_S)  # type: ignore[arg-type]
+np.strings.greater(AR_U, AR_S)  # type: ignore[arg-type]
+np.strings.less(AR_U, AR_S)  # type: ignore[arg-type]
+
+np.strings.encode(AR_S)  # type: ignore[arg-type]
+np.strings.decode(AR_U)  # type: ignore[arg-type]
+
+np.strings.lstrip(AR_U, b"a")  # type: ignore[arg-type]
+np.strings.lstrip(AR_S, "a")  # type: ignore[arg-type]
+np.strings.strip(AR_U, b"a")  # type: ignore[arg-type]
+np.strings.strip(AR_S, "a")  # type: ignore[arg-type]
+np.strings.rstrip(AR_U, b"a")  # type: ignore[arg-type]
+np.strings.rstrip(AR_S, "a")  # type: ignore[arg-type]
+
+np.strings.partition(AR_U, b"a")  # type: ignore[arg-type]
+np.strings.partition(AR_S, "a")  # type: ignore[arg-type]
+np.strings.rpartition(AR_U, b"a")  # type: ignore[arg-type]
+np.strings.rpartition(AR_S, "a")  # type: ignore[arg-type]
+
+np.strings.count(AR_U, b"a", [1, 2, 3], [1, 2, 3])  # type: ignore[arg-type]
+np.strings.count(AR_S, "a", 0, 9)  # type: ignore[arg-type]
+
+np.strings.endswith(AR_U, b"a", [1, 2, 3], [1, 2, 3])  # type: ignore[arg-type]
+np.strings.endswith(AR_S, "a", 0, 9)  # type: ignore[arg-type]
+np.strings.startswith(AR_U, b"a", [1, 2, 3], [1, 2, 3])  # type: ignore[arg-type]
+np.strings.startswith(AR_S, "a", 0, 9)  # type: ignore[arg-type]
+
+np.strings.find(AR_U, b"a", [1, 2, 3], [1, 2, 3])  # type: ignore[arg-type]
+np.strings.find(AR_S, "a", 0, 9)  # type: ignore[arg-type]
+np.strings.rfind(AR_U, b"a", [1, 2, 3], [1, 2, 3])  # type: ignore[arg-type]
+np.strings.rfind(AR_S, "a", 0, 9)  # type: ignore[arg-type]
+
+np.strings.index(AR_U, b"a", start=[1, 2, 3])  # type: ignore[arg-type]
+np.strings.index(AR_S, "a", end=9)  # type: ignore[arg-type]
+np.strings.rindex(AR_U, b"a", start=[1, 2, 3])  # type: ignore[arg-type]
+np.strings.rindex(AR_S, "a", end=9)  # type: ignore[arg-type]
+
+np.strings.isdecimal(AR_S)  # type: ignore[arg-type]
+np.strings.isnumeric(AR_S)  # type: ignore[arg-type]
+
+np.strings.replace(AR_U, b"_", b"-", 10)  # type: ignore[arg-type]
+np.strings.replace(AR_S, "_", "-", 1)  # type: ignore[arg-type]
diff --git a/numpy/typing/tests/data/fail/testing.pyi b/numpy/typing/tests/data/fail/testing.pyi
index f7eaa7d20836..517062c4c952 100644
--- a/numpy/typing/tests/data/fail/testing.pyi
+++ b/numpy/typing/tests/data/fail/testing.pyi
@@ -5,24 +5,24 @@ AR_U: npt.NDArray[np.str_]
 
 def func(x: object) -> bool: ...
 
-np.testing.assert_(True, msg=1)  # E: incompatible type
-np.testing.build_err_msg(1, "test")  # E: incompatible type
-np.testing.assert_almost_equal(AR_U, AR_U)  # E: incompatible type
-np.testing.assert_approx_equal([1, 2, 3], [1, 2, 3])  # E: incompatible type
-np.testing.assert_array_almost_equal(AR_U, AR_U)  # E: incompatible type
-np.testing.assert_array_less(AR_U, AR_U)  # E: incompatible type
-np.testing.assert_string_equal(b"a", b"a")  # E: incompatible type
+np.testing.assert_(True, msg=1)  # type: ignore[arg-type]
+np.testing.build_err_msg(1, "test")  # type: ignore[arg-type]
+np.testing.assert_almost_equal(AR_U, AR_U)  # type: ignore[arg-type]
+np.testing.assert_approx_equal([1, 2, 3], [1, 2, 3])  # type: ignore[arg-type]
+np.testing.assert_array_almost_equal(AR_U, AR_U)  # type: ignore[arg-type]
+np.testing.assert_array_less(AR_U, AR_U)  # type: ignore[arg-type]
+np.testing.assert_string_equal(b"a", b"a")  # type: ignore[arg-type]
 
-np.testing.assert_raises(expected_exception=TypeError, callable=func)  # E: No overload variant
-np.testing.assert_raises_regex(expected_exception=TypeError, expected_regex="T", callable=func)  # E: No overload variant
+np.testing.assert_raises(expected_exception=TypeError, callable=func)  # type: ignore[call-overload]
+np.testing.assert_raises_regex(expected_exception=TypeError, expected_regex="T", callable=func)  # type: ignore[call-overload]
 
-np.testing.assert_allclose(AR_U, AR_U)  # E: incompatible type
-np.testing.assert_array_almost_equal_nulp(AR_U, AR_U)  # E: incompatible type
-np.testing.assert_array_max_ulp(AR_U, AR_U)  # E: incompatible type
+np.testing.assert_allclose(AR_U, AR_U)  # type: ignore[arg-type]
+np.testing.assert_array_almost_equal_nulp(AR_U, AR_U)  # type: ignore[arg-type]
+np.testing.assert_array_max_ulp(AR_U, AR_U)  # type: ignore[arg-type]
 
-np.testing.assert_warns(RuntimeWarning, func)  # E: No overload variant
-np.testing.assert_no_warnings(func=func)  # E: No overload variant
-np.testing.assert_no_warnings(func)  # E: Too many arguments
-np.testing.assert_no_warnings(func, y=None)  # E: No overload variant
+np.testing.assert_warns(RuntimeWarning, func)  # type: ignore[call-overload]
+np.testing.assert_no_warnings(func=func)  # type: ignore[call-overload]
+np.testing.assert_no_warnings(func)  # type: ignore[call-overload]
+np.testing.assert_no_warnings(func, y=None)  # type: ignore[call-overload]
 
-np.testing.assert_no_gc_cycles(func=func)  # E: No overload variant
+np.testing.assert_no_gc_cycles(func=func)  # type: ignore[call-overload]
diff --git a/numpy/typing/tests/data/fail/twodim_base.pyi b/numpy/typing/tests/data/fail/twodim_base.pyi
index 98a36e39e566..d0f2b7ad8322 100644
--- a/numpy/typing/tests/data/fail/twodim_base.pyi
+++ b/numpy/typing/tests/data/fail/twodim_base.pyi
@@ -12,21 +12,21 @@ AR_m: npt.NDArray[np.timedelta64]
 
 AR_LIKE_b: list[bool]
 
-np.eye(10, M=20.0)  # E: No overload variant
-np.eye(10, k=2.5, dtype=int)  # E: No overload variant
+np.eye(10, M=20.0)  # type: ignore[call-overload]
+np.eye(10, k=2.5, dtype=int)  # type: ignore[call-overload]
 
-np.diag(AR_b, k=0.5)  # E: No overload variant
-np.diagflat(AR_b, k=0.5)  # E: No overload variant
+np.diag(AR_b, k=0.5)  # type: ignore[call-overload]
+np.diagflat(AR_b, k=0.5)  # type: ignore[call-overload]
 
-np.tri(10, M=20.0)  # E: No overload variant
-np.tri(10, k=2.5, dtype=int)  # E: No overload variant
+np.tri(10, M=20.0)  # type: ignore[call-overload]
+np.tri(10, k=2.5, dtype=int)  # type: ignore[call-overload]
 
-np.tril(AR_b, k=0.5)  # E: No overload variant
-np.triu(AR_b, k=0.5)  # E: No overload variant
+np.tril(AR_b, k=0.5)  # type: ignore[call-overload]
+np.triu(AR_b, k=0.5)  # type: ignore[call-overload]
 
-np.vander(AR_m)  # E: incompatible type
+np.vander(AR_m)  # type: ignore[arg-type]
 
-np.histogram2d(AR_m)  # E: No overload variant
+np.histogram2d(AR_m)  # type: ignore[call-overload]
 
-np.mask_indices(10, func1)  # E: incompatible type
-np.mask_indices(10, func2, 10.5)  # E: incompatible type
+np.mask_indices(10, func1)  # type: ignore[arg-type]
+np.mask_indices(10, func2, 10.5)  # type: ignore[arg-type]
diff --git a/numpy/typing/tests/data/fail/type_check.pyi b/numpy/typing/tests/data/fail/type_check.pyi
index 95f52bfbd260..94b6ee425af5 100644
--- a/numpy/typing/tests/data/fail/type_check.pyi
+++ b/numpy/typing/tests/data/fail/type_check.pyi
@@ -3,11 +3,11 @@ import numpy.typing as npt
 
 DTYPE_i8: np.dtype[np.int64]
 
-np.mintypecode(DTYPE_i8)  # E: incompatible type
-np.iscomplexobj(DTYPE_i8)  # E: incompatible type
-np.isrealobj(DTYPE_i8)  # E: incompatible type
+np.mintypecode(DTYPE_i8)  # type: ignore[arg-type]
+np.iscomplexobj(DTYPE_i8)  # type: ignore[arg-type]
+np.isrealobj(DTYPE_i8)  # type: ignore[arg-type]
 
-np.typename(DTYPE_i8)  # E: No overload variant
-np.typename("invalid")  # E: No overload variant
+np.typename(DTYPE_i8)  # type: ignore[call-overload]
+np.typename("invalid")  # type: ignore[call-overload]
 
-np.common_type(np.timedelta64())  # E: incompatible type
+np.common_type(np.timedelta64())  # type: ignore[arg-type]
diff --git a/numpy/typing/tests/data/fail/ufunc_config.pyi b/numpy/typing/tests/data/fail/ufunc_config.pyi
index b080804b0fcf..c67b6a3acf98 100644
--- a/numpy/typing/tests/data/fail/ufunc_config.pyi
+++ b/numpy/typing/tests/data/fail/ufunc_config.pyi
@@ -14,8 +14,8 @@ class Write2:
 class Write3:
     def write(self, *, a: str) -> None: ...
 
-np.seterrcall(func1)  # E: Argument 1 to "seterrcall" has incompatible type
-np.seterrcall(func2)  # E: Argument 1 to "seterrcall" has incompatible type
-np.seterrcall(Write1())  # E: Argument 1 to "seterrcall" has incompatible type
-np.seterrcall(Write2())  # E: Argument 1 to "seterrcall" has incompatible type
-np.seterrcall(Write3())  # E: Argument 1 to "seterrcall" has incompatible type
+np.seterrcall(func1)  # type: ignore[arg-type]
+np.seterrcall(func2)  # type: ignore[arg-type]
+np.seterrcall(Write1())  # type: ignore[arg-type]
+np.seterrcall(Write2())  # type: ignore[arg-type]
+np.seterrcall(Write3())  # type: ignore[arg-type]
diff --git a/numpy/typing/tests/data/fail/ufunclike.pyi b/numpy/typing/tests/data/fail/ufunclike.pyi
index be5e6a1530c2..e556e409ebbc 100644
--- a/numpy/typing/tests/data/fail/ufunclike.pyi
+++ b/numpy/typing/tests/data/fail/ufunclike.pyi
@@ -6,16 +6,16 @@ AR_m: npt.NDArray[np.timedelta64]
 AR_M: npt.NDArray[np.datetime64]
 AR_O: npt.NDArray[np.object_]
 
-np.fix(AR_c)  # E: incompatible type
-np.fix(AR_m)  # E: incompatible type
-np.fix(AR_M)  # E: incompatible type
+np.fix(AR_c)  # type: ignore[arg-type]
+np.fix(AR_m)  # type: ignore[arg-type]
+np.fix(AR_M)  # type: ignore[arg-type]
 
-np.isposinf(AR_c)  # E: incompatible type
-np.isposinf(AR_m)  # E: incompatible type
-np.isposinf(AR_M)  # E: incompatible type
-np.isposinf(AR_O)  # E: incompatible type
+np.isposinf(AR_c)  # type: ignore[arg-type]
+np.isposinf(AR_m)  # type: ignore[arg-type]
+np.isposinf(AR_M)  # type: ignore[arg-type]
+np.isposinf(AR_O)  # type: ignore[arg-type]
 
-np.isneginf(AR_c)  # E: incompatible type
-np.isneginf(AR_m)  # E: incompatible type
-np.isneginf(AR_M)  # E: incompatible type
-np.isneginf(AR_O)  # E: incompatible type
+np.isneginf(AR_c)  # type: ignore[arg-type]
+np.isneginf(AR_m)  # type: ignore[arg-type]
+np.isneginf(AR_M)  # type: ignore[arg-type]
+np.isneginf(AR_O)  # type: ignore[arg-type]
diff --git a/numpy/typing/tests/data/fail/ufuncs.pyi b/numpy/typing/tests/data/fail/ufuncs.pyi
index bbab0dfe3fc2..1b1628d7da44 100644
--- a/numpy/typing/tests/data/fail/ufuncs.pyi
+++ b/numpy/typing/tests/data/fail/ufuncs.pyi
@@ -3,15 +3,15 @@ import numpy.typing as npt
 
 AR_f8: npt.NDArray[np.float64]
 
-np.sin.nin + "foo"  # E: Unsupported operand types
-np.sin(1, foo="bar")  # E: No overload variant
+np.sin.nin + "foo"  # type: ignore[operator]
+np.sin(1, foo="bar")  # type: ignore[call-overload]
 
-np.abs(None)  # E: No overload variant
+np.abs(None)  # type: ignore[call-overload]
 
-np.add(1, 1, 1)  # E: No overload variant
-np.add(1, 1, axis=0)  # E: No overload variant
+np.add(1, 1, 1)  # type: ignore[call-overload]
+np.add(1, 1, axis=0)  # type: ignore[call-overload]
 
-np.matmul(AR_f8, AR_f8, where=True)  # E: No overload variant
+np.matmul(AR_f8, AR_f8, where=True)  # type: ignore[call-overload]
 
-np.frexp(AR_f8, out=None)  # E: No overload variant
-np.frexp(AR_f8, out=AR_f8)  # E: No overload variant
+np.frexp(AR_f8, out=None)  # type: ignore[call-overload]
+np.frexp(AR_f8, out=AR_f8)  # type: ignore[call-overload]
diff --git a/numpy/typing/tests/data/fail/warnings_and_errors.pyi b/numpy/typing/tests/data/fail/warnings_and_errors.pyi
index fae96d6bf016..8ba34f6dfa3e 100644
--- a/numpy/typing/tests/data/fail/warnings_and_errors.pyi
+++ b/numpy/typing/tests/data/fail/warnings_and_errors.pyi
@@ -1,5 +1,5 @@
 import numpy.exceptions as ex
 
-ex.AxisError(1.0)  # E: No overload variant
-ex.AxisError(1, ndim=2.0)  # E: No overload variant
-ex.AxisError(2, msg_prefix=404)  # E: No overload variant
+ex.AxisError(1.0)  # type: ignore[call-overload]
+ex.AxisError(1, ndim=2.0)  # type: ignore[call-overload]
+ex.AxisError(2, msg_prefix=404)  # type: ignore[call-overload]

From a3e02e5bee7ca2d35b088291d5ef2cb2f380a7b5 Mon Sep 17 00:00:00 2001
From: jorenham 
Date: Fri, 9 May 2025 03:17:55 +0200
Subject: [PATCH 181/202] TYP: have mypy complain about unused ``# type:
 ignore`` comments

---
 numpy/typing/tests/data/mypy.ini | 8 +++++---
 1 file changed, 5 insertions(+), 3 deletions(-)

diff --git a/numpy/typing/tests/data/mypy.ini b/numpy/typing/tests/data/mypy.ini
index 52a8b76df67f..46e7f712ddb6 100644
--- a/numpy/typing/tests/data/mypy.ini
+++ b/numpy/typing/tests/data/mypy.ini
@@ -1,8 +1,10 @@
 [mypy]
 plugins = numpy.typing.mypy_plugin
-show_absolute_path = True
+enable_error_code = deprecated, ignore-without-code, truthy-bool
+strict_bytes = True
+warn_unused_ignores = True
 implicit_reexport = False
-pretty = True
 disallow_any_unimported = True
 disallow_any_generics = True
-strict_bytes = True
+show_absolute_path = True
+pretty = True

From 90298db7a2be49b469d379f89f053ce079296beb Mon Sep 17 00:00:00 2001
From: jorenham 
Date: Fri, 9 May 2025 03:19:20 +0200
Subject: [PATCH 182/202] TST: improved mypy type-test runners

---
 numpy/typing/tests/test_typing.py | 188 +++++++++++++-----------------
 1 file changed, 84 insertions(+), 104 deletions(-)

diff --git a/numpy/typing/tests/test_typing.py b/numpy/typing/tests/test_typing.py
index 068b27a7709f..22070ac69c6d 100644
--- a/numpy/typing/tests/test_typing.py
+++ b/numpy/typing/tests/test_typing.py
@@ -4,11 +4,11 @@
 import os
 import re
 import shutil
+import textwrap
 from collections import defaultdict
 from typing import TYPE_CHECKING
 
 import pytest
-from numpy.typing.mypy_plugin import _EXTENDED_PRECISION_LIST
 
 
 # Only trigger a full `mypy` run if this environment variable is set
@@ -99,9 +99,9 @@ def run_mypy() -> None:
             directory,
         ])
         if stderr:
-            pytest.fail(f"Unexpected mypy standard error\n\n{stderr}")
+            pytest.fail(f"Unexpected mypy standard error\n\n{stderr}", False)
         elif exit_code not in {0, 1}:
-            pytest.fail(f"Unexpected mypy exit code: {exit_code}\n\n{stdout}")
+            pytest.fail(f"Unexpected mypy exit code: {exit_code}\n\n{stdout}", False)
 
         str_concat = ""
         filename: str | None = None
@@ -118,98 +118,55 @@ def run_mypy() -> None:
                 filename = None
 
 
-def get_test_cases(directory: str) -> Iterator[ParameterSet]:
-    for root, _, files in os.walk(directory):
-        for fname in files:
-            short_fname, ext = os.path.splitext(fname)
-            if ext in (".pyi", ".py"):
+def get_test_cases(*directories: str) -> Iterator[ParameterSet]:
+    for directory in directories:
+        for root, _, files in os.walk(directory):
+            for fname in files:
+                short_fname, ext = os.path.splitext(fname)
+                if ext not in (".pyi", ".py"):
+                    continue
+
                 fullpath = os.path.join(root, fname)
                 yield pytest.param(fullpath, id=short_fname)
 
 
-@pytest.mark.slow
-@pytest.mark.skipif(NO_MYPY, reason="Mypy is not installed")
-@pytest.mark.parametrize("path", get_test_cases(PASS_DIR))
-def test_success(path) -> None:
-    # Alias `OUTPUT_MYPY` so that it appears in the local namespace
-    output_mypy = OUTPUT_MYPY
-    if path in output_mypy:
-        msg = "Unexpected mypy output\n\n"
-        msg += "\n".join(_strip_filename(v)[1] for v in output_mypy[path])
-        raise AssertionError(msg)
-
-
-@pytest.mark.slow
-@pytest.mark.skipif(NO_MYPY, reason="Mypy is not installed")
-@pytest.mark.parametrize("path", get_test_cases(FAIL_DIR))
-def test_fail(path: str) -> None:
-    __tracebackhide__ = True
-
-    with open(path) as fin:
-        lines = fin.readlines()
-
-    errors = defaultdict(lambda: "")
-
-    output_mypy = OUTPUT_MYPY
-    assert path in output_mypy
-
-    for error_line in output_mypy[path]:
-        lineno, error_line = _strip_filename(error_line)
-        errors[lineno] += f'{error_line}\n'
-
-    for i, line in enumerate(lines):
-        lineno = i + 1
-        if (
-            line.startswith('#')
-            or (" E:" not in line and lineno not in errors)
-        ):
-            continue
+_FAIL_INDENT = " " * 4
+_FAIL_SEP = "\n" + "_" * 79 +  "\n\n"
 
-        target_line = lines[lineno - 1]
-        if "# E:" in target_line:
-            expression, _, marker = target_line.partition("  # E: ")
-            error = errors[lineno].strip()
-            expected_error = marker.strip()
-            _test_fail(path, expression, error, expected_error, lineno)
-        else:
-            pytest.fail(
-                f"Unexpected mypy output at line {lineno}\n\n{errors[lineno]}"
-            )
+_FAIL_MSG_REVEAL = """{}:{} - reveal mismatch:
 
+{}"""
 
-_FAIL_MSG1 = """Extra error at line {}
+_FAIL_MSG_MISC = """{}:{} - error mismatch:
 
 Expression: {}
-Extra error: {!r}
+Expected error: {}
+Observed error: {}
 """
 
-_FAIL_MSG2 = """Error mismatch at line {}
 
-Expression: {}
-Expected error: {}
-Observed error: {!r}
-"""
+@pytest.mark.slow
+@pytest.mark.skipif(NO_MYPY, reason="Mypy is not installed")
+@pytest.mark.parametrize("path", get_test_cases(PASS_DIR, FAIL_DIR))
+def test_pass(path) -> None:
+    # Alias `OUTPUT_MYPY` so that it appears in the local namespace
+    output_mypy = OUTPUT_MYPY
 
+    if path not in output_mypy:
+        return
 
-def _test_fail(
-    path: str,
-    expression: str,
-    error: str,
-    expected_error: str | None,
-    lineno: int,
-) -> None:
-    if expected_error is None:
-        raise AssertionError(_FAIL_MSG1.format(lineno, expression, error))
-    elif expected_error not in error:
-        raise AssertionError(_FAIL_MSG2.format(
-            lineno, expression, expected_error, error
-        ))
+    relpath = os.path.relpath(path)
 
+    # collect any reported errors, and clean up the output
+    messages = []
+    for message in output_mypy[path]:
+        lineno, content = _strip_filename(message)
+        content = content.removeprefix("error:").lstrip()
+        messages.append(f"{relpath}:{lineno} - {content}")
 
-_REVEAL_MSG = """Reveal mismatch at line {}
+    if messages:
+        pytest.fail("\n".join(messages), pytrace=False)
 
-{}
-"""
 
 
 @pytest.mark.slow
@@ -225,27 +182,19 @@ def test_reveal(path: str) -> None:
     if path not in output_mypy:
         return
 
-    for error_line in output_mypy[path]:
-        lineno, error_line = _strip_filename(error_line)
-        raise AssertionError(_REVEAL_MSG.format(lineno, error_line))
-
+    relpath = os.path.relpath(path)
 
-@pytest.mark.slow
-@pytest.mark.skipif(NO_MYPY, reason="Mypy is not installed")
-@pytest.mark.parametrize("path", get_test_cases(PASS_DIR))
-def test_code_runs(path: str) -> None:
-    """Validate that the code in `path` properly during runtime."""
-    path_without_extension, _ = os.path.splitext(path)
-    dirname, filename = path.split(os.sep)[-2:]
-
-    spec = importlib.util.spec_from_file_location(
-        f"{dirname}.{filename}", path
-    )
-    assert spec is not None
-    assert spec.loader is not None
+    # collect any reported errors, and clean up the output
+    failures = []
+    for error_line in output_mypy[path]:
+        lineno, error_msg = _strip_filename(error_line)
+        error_msg = textwrap.indent(error_msg, _FAIL_INDENT)
+        reason = _FAIL_MSG_REVEAL.format(relpath, lineno, error_msg)
+        failures.append(reason)
 
-    test_module = importlib.util.module_from_spec(spec)
-    spec.loader.exec_module(test_module)
+    if failures:
+        reasons = _FAIL_SEP.join(failures)
+        pytest.fail(reasons, pytrace=False)
 
 
 LINENO_MAPPING = {
@@ -259,20 +208,51 @@ def test_code_runs(path: str) -> None:
 @pytest.mark.slow
 @pytest.mark.skipif(NO_MYPY, reason="Mypy is not installed")
 def test_extended_precision() -> None:
+    from numpy.typing.mypy_plugin import _EXTENDED_PRECISION_LIST
+
     path = os.path.join(MISC_DIR, "extended_precision.pyi")
     output_mypy = OUTPUT_MYPY
     assert path in output_mypy
 
+    expected_msg = 'Expression is of type "Any"'
+
     with open(path) as f:
         expression_list = f.readlines()
 
+    failures = []
     for _msg in output_mypy[path]:
-        lineno, msg = _strip_filename(_msg)
-        expression = expression_list[lineno - 1].rstrip("\n")
+        lineno, error_msg = _strip_filename(_msg)
+        expr = expression_list[lineno - 1].rstrip("\n")
 
         if LINENO_MAPPING[lineno] in _EXTENDED_PRECISION_LIST:
-            raise AssertionError(_REVEAL_MSG.format(lineno, msg))
-        elif "error" not in msg:
-            _test_fail(
-                path, expression, msg, 'Expression is of type "Any"', lineno
-            )
+            raise AssertionError(_FAIL_MSG_REVEAL.format(lineno, error_msg))
+        if "error" in error_msg or expected_msg not in error_msg:
+            continue
+
+        if "\n" in error_msg:
+            error_msg = "\n" + textwrap.indent(error_msg, _FAIL_INDENT)
+        relpath = os.path.relpath(path)
+        failure = _FAIL_MSG_MISC.format(relpath, lineno, expr, expected_msg, error_msg)
+        failures.append(failure)
+
+    if failures:
+        reasons = _FAIL_SEP.join(failures)
+        pytest.fail(reasons, pytrace=False)
+
+
+@pytest.mark.slow
+@pytest.mark.skipif(NO_MYPY, reason="Mypy is not installed")
+@pytest.mark.parametrize("path", get_test_cases(PASS_DIR))
+def test_code_runs(path: str) -> None:
+    """Validate that the code in `path` properly during runtime."""
+    path_without_extension, _ = os.path.splitext(path)
+    dirname, filename = path.split(os.sep)[-2:]
+
+    spec = importlib.util.spec_from_file_location(
+        f"{dirname}.{filename}", path
+    )
+    assert spec is not None
+    assert spec.loader is not None
+
+    test_module = importlib.util.module_from_spec(spec)
+    spec.loader.exec_module(test_module)

From 103ebb8c4b4dfcab64600867b9eebfff73919a05 Mon Sep 17 00:00:00 2001
From: jorenham 
Date: Fri, 9 May 2025 03:20:16 +0200
Subject: [PATCH 183/202] TYP: silence mypy deprecation warnings in the
 type-tests

---
 numpy/typing/tests/data/pass/ndarray_misc.py         | 8 ++++----
 numpy/typing/tests/data/reveal/nbit_base_example.pyi | 4 ++--
 2 files changed, 6 insertions(+), 6 deletions(-)

diff --git a/numpy/typing/tests/data/pass/ndarray_misc.py b/numpy/typing/tests/data/pass/ndarray_misc.py
index df95f3af9740..d995961f0962 100644
--- a/numpy/typing/tests/data/pass/ndarray_misc.py
+++ b/numpy/typing/tests/data/pass/ndarray_misc.py
@@ -188,10 +188,10 @@ class SubClass(npt.NDArray[np.float64]): ...
 # deprecated
 
 with np.testing.assert_warns(DeprecationWarning):
-    ctypes_obj.get_data()  # pyright: ignore[reportDeprecated]
+    ctypes_obj.get_data()  # type: ignore[deprecated]  # pyright: ignore[reportDeprecated]
 with np.testing.assert_warns(DeprecationWarning):
-    ctypes_obj.get_shape()  # pyright: ignore[reportDeprecated]
+    ctypes_obj.get_shape()  # type: ignore[deprecated]  # pyright: ignore[reportDeprecated]
 with np.testing.assert_warns(DeprecationWarning):
-    ctypes_obj.get_strides()  # pyright: ignore[reportDeprecated]
+    ctypes_obj.get_strides()  # type: ignore[deprecated]  # pyright: ignore[reportDeprecated]
 with np.testing.assert_warns(DeprecationWarning):
-    ctypes_obj.get_as_parameter()  # pyright: ignore[reportDeprecated]
+    ctypes_obj.get_as_parameter()  # type: ignore[deprecated]  # pyright: ignore[reportDeprecated]
diff --git a/numpy/typing/tests/data/reveal/nbit_base_example.pyi b/numpy/typing/tests/data/reveal/nbit_base_example.pyi
index 0629ead5e918..33229660b6f8 100644
--- a/numpy/typing/tests/data/reveal/nbit_base_example.pyi
+++ b/numpy/typing/tests/data/reveal/nbit_base_example.pyi
@@ -4,8 +4,8 @@ import numpy as np
 import numpy.typing as npt
 from numpy._typing import _32Bit, _64Bit
 
-T1 = TypeVar("T1", bound=npt.NBitBase)
-T2 = TypeVar("T2", bound=npt.NBitBase)
+T1 = TypeVar("T1", bound=npt.NBitBase)  # type: ignore[deprecated]  # pyright: ignore[reportDeprecated]
+T2 = TypeVar("T2", bound=npt.NBitBase)  # type: ignore[deprecated]  # pyright: ignore[reportDeprecated]
 
 def add(a: np.floating[T1], b: np.integer[T2]) -> np.floating[T1 | T2]:
     return a + b

From 6dcdda7e34bf3c8312890c2b66b2a8da81eb1f19 Mon Sep 17 00:00:00 2001
From: jorenham 
Date: Fri, 9 May 2025 03:57:24 +0200
Subject: [PATCH 184/202] TST: fix linter errors

---
 numpy/typing/tests/test_typing.py | 3 +--
 1 file changed, 1 insertion(+), 2 deletions(-)

diff --git a/numpy/typing/tests/test_typing.py b/numpy/typing/tests/test_typing.py
index 22070ac69c6d..2d8c48cb3fb2 100644
--- a/numpy/typing/tests/test_typing.py
+++ b/numpy/typing/tests/test_typing.py
@@ -131,7 +131,7 @@ def get_test_cases(*directories: str) -> Iterator[ParameterSet]:
 
 
 _FAIL_INDENT = " " * 4
-_FAIL_SEP = "\n" + "_" * 79 +  "\n\n"
+_FAIL_SEP = "\n" + "_" * 79 + "\n\n"
 
 _FAIL_MSG_REVEAL = """{}:{} - reveal mismatch:
 
@@ -168,7 +168,6 @@ def test_pass(path) -> None:
         pytest.fail("\n".join(messages), pytrace=False)
 
 
-
 @pytest.mark.slow
 @pytest.mark.skipif(NO_MYPY, reason="Mypy is not installed")
 @pytest.mark.parametrize("path", get_test_cases(REVEAL_DIR))

From 1598eb873667c6cb63ffd428ac4a8a3388fd3586 Mon Sep 17 00:00:00 2001
From: Pieter Eendebak 
Date: Fri, 9 May 2025 10:32:34 +0200
Subject: [PATCH 185/202] MAINT: Enable ruff E251

---
 numpy/lib/tests/test_polynomial.py        |  4 ++--
 numpy/polynomial/tests/test_polynomial.py |  4 ++--
 ruff.toml                                 |  1 -
 tools/refguide_check.py                   |  2 +-
 tools/swig/test/setup.py                  | 24 +++++++++++------------
 5 files changed, 17 insertions(+), 18 deletions(-)

diff --git a/numpy/lib/tests/test_polynomial.py b/numpy/lib/tests/test_polynomial.py
index bf432348cb36..a4961b580d08 100644
--- a/numpy/lib/tests/test_polynomial.py
+++ b/numpy/lib/tests/test_polynomial.py
@@ -123,12 +123,12 @@ def test_roots(self):
         assert_array_equal(np.roots([1, 0, 0]), [0, 0])
 
         # Testing for larger root values
-        for i in np.logspace(10, 25, num = 1000, base = 10):
+        for i in np.logspace(10, 25, num=1000, base=10):
             tgt = np.array([-1, 1, i])
             res = np.sort(np.roots(poly.polyfromroots(tgt)[::-1]))
             assert_almost_equal(res, tgt, 14 - int(np.log10(i)))    # Adapting the expected precision according to the root value, to take into account numerical calculation error
 
-        for i in np.logspace(10, 25, num = 1000, base = 10):
+        for i in np.logspace(10, 25, num=1000, base=10):
             tgt = np.array([-1, 1.01, i])
             res = np.sort(np.roots(poly.polyfromroots(tgt)[::-1]))
             assert_almost_equal(res, tgt, 14 - int(np.log10(i)))    # Adapting the expected precision according to the root value, to take into account numerical calculation error
diff --git a/numpy/polynomial/tests/test_polynomial.py b/numpy/polynomial/tests/test_polynomial.py
index 84ccc45fc4e4..3cbc09157946 100644
--- a/numpy/polynomial/tests/test_polynomial.py
+++ b/numpy/polynomial/tests/test_polynomial.py
@@ -544,12 +544,12 @@ def test_polyroots(self):
             assert_almost_equal(trim(res), trim(tgt))
 
         # Testing for larger root values
-        for i in np.logspace(10, 25, num = 1000, base = 10):
+        for i in np.logspace(10, 25, num=1000, base=10):
             tgt = np.array([-1, 1, i])
             res = poly.polyroots(poly.polyfromroots(tgt))
             assert_almost_equal(res, tgt, 15 - int(np.log10(i)))    # Adapting the expected precision according to the root value, to take into account numerical calculation error
 
-        for i in np.logspace(10, 25, num = 1000, base = 10):
+        for i in np.logspace(10, 25, num=1000, base=10):
             tgt = np.array([-1, 1.01, i])
             res = poly.polyroots(poly.polyfromroots(tgt))
             assert_almost_equal(res, tgt, 14 - int(np.log10(i)))    # Adapting the expected precision according to the root value, to take into account numerical calculation error
diff --git a/ruff.toml b/ruff.toml
index c01b5cf30991..4224a478d863 100644
--- a/ruff.toml
+++ b/ruff.toml
@@ -34,7 +34,6 @@ ignore = [
     "C408",   # Unnecessary `dict()` call (rewrite as a literal)
     "PIE790", # Unnecessary `pass` statement
     "E241",   # Multiple spaces after comma
-    "E251",   # Unexpected spaces around keyword / parameter equals
     "E265",   # Block comment should start with `# `
     "E266",   # Too many leading `#` before block comment
     "E302",   # TODO: Expected 2 blank lines, found 1
diff --git a/tools/refguide_check.py b/tools/refguide_check.py
index 87c760bf154b..3895f7818101 100644
--- a/tools/refguide_check.py
+++ b/tools/refguide_check.py
@@ -423,7 +423,7 @@ def resolve(name, is_label=False):
 
     docutils.core.publish_doctree(
         text, token,
-        settings_overrides = {'halt_level': 5,
+        settings_overrides={'halt_level': 5,
                                   'traceback': True,
                                   'default_reference_context': 'title-reference',
                                   'default_role': 'emphasis',
diff --git a/tools/swig/test/setup.py b/tools/swig/test/setup.py
index c925f358ec7b..ec21ca415c8b 100755
--- a/tools/swig/test/setup.py
+++ b/tools/swig/test/setup.py
@@ -14,55 +14,55 @@
                     "Array1.cxx",
                     "Array2.cxx",
                     "ArrayZ.cxx"],
-                   include_dirs = [numpy_include],
+                   include_dirs=[numpy_include],
                    )
 
 # Farray extension module
 _Farray = Extension("_Farray",
                     ["Farray_wrap.cxx",
                      "Farray.cxx"],
-                    include_dirs = [numpy_include],
+                    include_dirs=[numpy_include],
                     )
 
 # _Vector extension module
 _Vector = Extension("_Vector",
                     ["Vector_wrap.cxx",
                      "Vector.cxx"],
-                    include_dirs = [numpy_include],
+                    include_dirs=[numpy_include],
                     )
 
 # _Matrix extension module
 _Matrix = Extension("_Matrix",
                     ["Matrix_wrap.cxx",
                      "Matrix.cxx"],
-                    include_dirs = [numpy_include],
+                    include_dirs=[numpy_include],
                     )
 
 # _Tensor extension module
 _Tensor = Extension("_Tensor",
                     ["Tensor_wrap.cxx",
                      "Tensor.cxx"],
-                    include_dirs = [numpy_include],
+                    include_dirs=[numpy_include],
                     )
 
 _Fortran = Extension("_Fortran",
                      ["Fortran_wrap.cxx",
                       "Fortran.cxx"],
-                     include_dirs = [numpy_include],
+                     include_dirs=[numpy_include],
                      )
 
 _Flat = Extension("_Flat",
                   ["Flat_wrap.cxx",
                    "Flat.cxx"],
-                  include_dirs = [numpy_include],
+                  include_dirs=[numpy_include],
                   )
 
 # NumyTypemapTests setup
-setup(name = "NumpyTypemapTests",
-      description = "Functions that work on arrays",
-      author = "Bill Spotz",
-      py_modules = ["Array", "Farray", "Vector", "Matrix", "Tensor",
+setup(name="NumpyTypemapTests",
+      description="Functions that work on arrays",
+      author="Bill Spotz",
+      py_modules=["Array", "Farray", "Vector", "Matrix", "Tensor",
                      "Fortran", "Flat"],
-      ext_modules = [_Array, _Farray, _Vector, _Matrix, _Tensor,
+      ext_modules=[_Array, _Farray, _Vector, _Matrix, _Tensor,
                      _Fortran, _Flat]
       )

From e23096e1e9a9b4b9498b3eb42be3154e0916444e Mon Sep 17 00:00:00 2001
From: Pieter Eendebak 
Date: Fri, 9 May 2025 16:13:41 +0200
Subject: [PATCH 186/202] alignment

---
 tools/refguide_check.py  | 18 +++++++++---------
 tools/swig/test/setup.py |  2 +-
 2 files changed, 10 insertions(+), 10 deletions(-)

diff --git a/tools/refguide_check.py b/tools/refguide_check.py
index 3895f7818101..41cf3ddfefa5 100644
--- a/tools/refguide_check.py
+++ b/tools/refguide_check.py
@@ -424,15 +424,15 @@ def resolve(name, is_label=False):
     docutils.core.publish_doctree(
         text, token,
         settings_overrides={'halt_level': 5,
-                                  'traceback': True,
-                                  'default_reference_context': 'title-reference',
-                                  'default_role': 'emphasis',
-                                  'link_base': '',
-                                  'resolve_name': resolve,
-                                  'stylesheet_path': '',
-                                  'raw_enabled': 0,
-                                  'file_insertion_enabled': 0,
-                                  'warning_stream': error_stream})
+                            'traceback': True,
+                            'default_reference_context': 'title-reference',
+                            'default_role': 'emphasis',
+                            'link_base': '',
+                            'resolve_name': resolve,
+                            'stylesheet_path': '',
+                            'raw_enabled': 0,
+                            'file_insertion_enabled': 0,
+                            'warning_stream': error_stream})
 
     # Print errors, disregarding unimportant ones
     error_msg = error_stream.getvalue()
diff --git a/tools/swig/test/setup.py b/tools/swig/test/setup.py
index ec21ca415c8b..f792b03a0933 100755
--- a/tools/swig/test/setup.py
+++ b/tools/swig/test/setup.py
@@ -62,7 +62,7 @@
       description="Functions that work on arrays",
       author="Bill Spotz",
       py_modules=["Array", "Farray", "Vector", "Matrix", "Tensor",
-                     "Fortran", "Flat"],
+                  "Fortran", "Flat"],
       ext_modules=[_Array, _Farray, _Vector, _Matrix, _Tensor,
                      _Fortran, _Flat]
       )

From 7e478567658e806deacb87dccaaf8a9d22e384e5 Mon Sep 17 00:00:00 2001
From: Nathan Goldbaum 
Date: Fri, 9 May 2025 09:02:50 -0600
Subject: [PATCH 187/202] CI: fix TSAN ci using a different docker image

---
 .github/workflows/compiler_sanitizers.yml | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/.github/workflows/compiler_sanitizers.yml b/.github/workflows/compiler_sanitizers.yml
index 84eab228b397..810f311afb08 100644
--- a/.github/workflows/compiler_sanitizers.yml
+++ b/.github/workflows/compiler_sanitizers.yml
@@ -78,7 +78,7 @@ jobs:
     if: github.repository == 'numpy/numpy'
     runs-on: ubuntu-latest
     container:
-        image: ghcr.io/nascheme/numpy-tsan:3.14t-dev
+        image: ghcr.io/nascheme/numpy-tsan:3.14t
         options: --shm-size=2g # increase memory for large matrix ops
       
     steps:

From 81277b31ea4a10ff2c6ccff240d67509768aa2d0 Mon Sep 17 00:00:00 2001
From: Nathan Goldbaum 
Date: Fri, 9 May 2025 10:50:31 -0600
Subject: [PATCH 188/202] MNT: clean up free-threaded CI configuration [wheel
 build]

---
 .github/workflows/compiler_sanitizers.yml | 6 ++----
 .github/workflows/linux.yml               | 5 -----
 .github/workflows/macos.yml               | 8 +-------
 .github/workflows/wheels.yml              | 6 ------
 .github/workflows/windows.yml             | 8 +-------
 tools/ci/cirrus_wheels.yml                | 7 +------
 tools/wheels/cibw_before_build.sh         | 9 ---------
 tools/wheels/cibw_test_command.sh         | 5 -----
 8 files changed, 5 insertions(+), 49 deletions(-)

diff --git a/.github/workflows/compiler_sanitizers.yml b/.github/workflows/compiler_sanitizers.yml
index 810f311afb08..0581f7fc591b 100644
--- a/.github/workflows/compiler_sanitizers.yml
+++ b/.github/workflows/compiler_sanitizers.yml
@@ -53,12 +53,10 @@ jobs:
         echo CPPFLAGS="-I$LLVM_PREFIX/include" >> $GITHUB_ENV
     - name: Build Python with address sanitizer
       run: |
-        CONFIGURE_OPTS="--with-address-sanitizer" pyenv install 3.13t
-        pyenv global 3.13t
+        CONFIGURE_OPTS="--with-address-sanitizer" pyenv install 3.14t
+        pyenv global 3.14t
     - name: Install dependencies
       run: |
-        # TODO: remove when a released cython supports free-threaded python
-        pip install -i https://pypi.anaconda.org/scientific-python-nightly-wheels/simple cython
         pip install -r requirements/build_requirements.txt
         pip install -r requirements/ci_requirements.txt
         pip install -r requirements/test_requirements.txt
diff --git a/.github/workflows/linux.yml b/.github/workflows/linux.yml
index db660c8190c0..4e57e7621543 100644
--- a/.github/workflows/linux.yml
+++ b/.github/workflows/linux.yml
@@ -68,11 +68,6 @@ jobs:
     - uses: actions/setup-python@a26af69be951a213d495a4c3e4e4022e16d87065 # v5.6.0
       with:
         python-version: ${{ matrix.version }}
-    # TODO: remove cython nightly install when cython does a release
-    - name: Install nightly Cython
-      if: matrix.version == '3.14t-dev'
-      run: |
-        pip install -i https://pypi.anaconda.org/scientific-python-nightly-wheels/simple cython
     - uses: ./.github/meson_actions
 
   pypy:
diff --git a/.github/workflows/macos.yml b/.github/workflows/macos.yml
index 82de69009aac..16862d715876 100644
--- a/.github/workflows/macos.yml
+++ b/.github/workflows/macos.yml
@@ -115,7 +115,7 @@ jobs:
         build_runner:
           - [ macos-13, "macos_x86_64" ]
           - [ macos-14, "macos_arm64" ]
-        version: ["3.11", "3.13t"]
+        version: ["3.11", "3.14t"]
 
     steps:
     - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2
@@ -138,12 +138,6 @@ jobs:
       with:
         xcode-version: '14.3'
 
-    # TODO: remove cython nightly install when cython does a release
-    - name: Install nightly Cython
-      if: matrix.version == '3.13t'
-      run: |
-        pip install -i https://pypi.anaconda.org/scientific-python-nightly-wheels/simple cython
-
     - name: Install dependencies
       run: |
         pip install -r requirements/build_requirements.txt
diff --git a/.github/workflows/wheels.yml b/.github/workflows/wheels.yml
index 3f7295ff787b..e96021775f3c 100644
--- a/.github/workflows/wheels.yml
+++ b/.github/workflows/wheels.yml
@@ -174,12 +174,6 @@ jobs:
             echo "CIBW_ENVIRONMENT_MACOS=$CIBW PKG_CONFIG_PATH=$PKG_CONFIG_PATH DYLD_LIBRARY_PATH=$DYLD" >> "$GITHUB_ENV"
           fi
 
-      - name: Set up free-threaded build
-        if: matrix.python == 'cp313t'
-        shell: bash -el {0}
-        run: |
-          echo "CIBW_BUILD_FRONTEND=pip; args: --no-build-isolation" >> "$GITHUB_ENV"
-
       - name: Build wheels
         uses: pypa/cibuildwheel@faf86a6ed7efa889faf6996aa23820831055001a  # v2.23.3
         env:
diff --git a/.github/workflows/windows.yml b/.github/workflows/windows.yml
index 80b4a961e3e1..72d23e27b897 100644
--- a/.github/workflows/windows.yml
+++ b/.github/workflows/windows.yml
@@ -24,7 +24,7 @@ jobs:
       matrix:
         compiler-pyversion:
           - ["MSVC", "3.11"]
-          - ["Clang-cl", "3.13t"]
+          - ["Clang-cl", "3.14t"]
 
     steps:
     - name: Checkout
@@ -44,12 +44,6 @@ jobs:
     - run:
         uv pip install --python=${{ matrix.version }} pip
 
-    # TODO: remove cython nightly install when cython does a release
-    - name: Install nightly Cython
-      if: matrix.compiler-pyversion[1] == '3.13t'
-      run: |
-        pip install -i https://pypi.anaconda.org/scientific-python-nightly-wheels/simple cython
-
     - name: Install build dependencies from PyPI
       run: |
         pip install -r requirements/build_requirements.txt
diff --git a/tools/ci/cirrus_wheels.yml b/tools/ci/cirrus_wheels.yml
index e8395faab35a..b531e953daee 100644
--- a/tools/ci/cirrus_wheels.yml
+++ b/tools/ci/cirrus_wheels.yml
@@ -15,12 +15,7 @@ macosx_arm64_task:
 
   matrix:
     - env:
-        CIBW_BUILD: cp311-* cp312*
-    - env:
-        CIBW_BUILD: cp313-*
-    - env:
-        CIBW_BUILD: cp313t-*
-        CIBW_BUILD_FRONTEND: "pip; args: --no-build-isolation"
+        CIBW_BUILD: cp311-* cp312* cp313*
   env:
     PATH: /usr/local/lib:/usr/local/include:$PATH
     CIBW_ARCHS: arm64
diff --git a/tools/wheels/cibw_before_build.sh b/tools/wheels/cibw_before_build.sh
index c8d119b1b39f..3e1d4498fe7c 100644
--- a/tools/wheels/cibw_before_build.sh
+++ b/tools/wheels/cibw_before_build.sh
@@ -55,12 +55,3 @@ if [[ $RUNNER_OS == "Windows" ]]; then
     # delvewheel is the equivalent of delocate/auditwheel for windows.
     python -m pip install delvewheel wheel
 fi
-
-# TODO: delete along with enabling build isolation by unsetting
-# CIBW_BUILD_FRONTEND when numpy is buildable under free-threaded
-# python with a released version of cython
-FREE_THREADED_BUILD="$(python -c"import sysconfig; print(bool(sysconfig.get_config_var('Py_GIL_DISABLED')))")"
-if [[ $FREE_THREADED_BUILD == "True" ]]; then
-    python -m pip install meson-python ninja
-    python -m pip install -i https://pypi.anaconda.org/scientific-python-nightly-wheels/simple cython
-fi
diff --git a/tools/wheels/cibw_test_command.sh b/tools/wheels/cibw_test_command.sh
index 73d1049325e4..60e90ef5beb6 100644
--- a/tools/wheels/cibw_test_command.sh
+++ b/tools/wheels/cibw_test_command.sh
@@ -30,11 +30,6 @@ export NPY_AVAILABLE_MEM="4 GB"
 
 FREE_THREADED_BUILD="$(python -c"import sysconfig; print(bool(sysconfig.get_config_var('Py_GIL_DISABLED')))")"
 if [[ $FREE_THREADED_BUILD == "True" ]]; then
-    # TODO: delete when numpy is buildable under free-threaded python
-    # with a released version of cython
-    python -m pip uninstall -y cython
-    python -m pip install -i https://pypi.anaconda.org/scientific-python-nightly-wheels/simple cython
-
     # Manually check that importing NumPy does not re-enable the GIL.
     # In principle the tests should catch this but it seems harmless to leave it
     # here as a final sanity check before uploading broken wheels

From 50c1b6474933f578af9cd25ebfc65e9de4f3e1e6 Mon Sep 17 00:00:00 2001
From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com>
Date: Fri, 9 May 2025 17:23:46 +0000
Subject: [PATCH 189/202] MAINT: Bump actions/dependency-review-action from
 4.6.0 to 4.7.0

Bumps [actions/dependency-review-action](https://github.com/actions/dependency-review-action) from 4.6.0 to 4.7.0.
- [Release notes](https://github.com/actions/dependency-review-action/releases)
- [Commits](https://github.com/actions/dependency-review-action/compare/ce3cf9537a52e8119d91fd484ab5b8a807627bf8...38ecb5b593bf0eb19e335c03f97670f792489a8b)

---
updated-dependencies:
- dependency-name: actions/dependency-review-action
  dependency-version: 4.7.0
  dependency-type: direct:production
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] 
---
 .github/workflows/dependency-review.yml | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/.github/workflows/dependency-review.yml b/.github/workflows/dependency-review.yml
index 11ab6e4c67cd..af26de3aee9d 100644
--- a/.github/workflows/dependency-review.yml
+++ b/.github/workflows/dependency-review.yml
@@ -19,6 +19,6 @@ jobs:
         with:
           persist-credentials: false
       - name: 'Dependency Review'
-        uses: actions/dependency-review-action@ce3cf9537a52e8119d91fd484ab5b8a807627bf8 # v4.6.0
+        uses: actions/dependency-review-action@38ecb5b593bf0eb19e335c03f97670f792489a8b # v4.7.0
         with:
           allow-ghsas: GHSA-cx63-2mw6-8hw5

From 5b00a4d86134b9c190dccd519ba500af776f2ab0 Mon Sep 17 00:00:00 2001
From: Nathan Goldbaum 
Date: Fri, 9 May 2025 11:25:33 -0600
Subject: [PATCH 190/202] MNT: rename constants that might clash with system
 headers [wheel build]

---
 numpy/random/src/mt19937/mt19937-jump.c | 38 ++++++++++++-------------
 numpy/random/src/mt19937/mt19937.c      | 12 ++++----
 numpy/random/src/mt19937/mt19937.h      |  4 +--
 3 files changed, 27 insertions(+), 27 deletions(-)

diff --git a/numpy/random/src/mt19937/mt19937-jump.c b/numpy/random/src/mt19937/mt19937-jump.c
index 1a83a4c2e23b..14ca818ad218 100644
--- a/numpy/random/src/mt19937/mt19937-jump.c
+++ b/numpy/random/src/mt19937/mt19937-jump.c
@@ -13,7 +13,7 @@ unsigned long get_coef(unsigned long *pf, unsigned int deg) {
 void copy_state(mt19937_state *target_state, mt19937_state *state) {
   int i;
 
-  for (i = 0; i < N; i++)
+  for (i = 0; i < _MT19937_N; i++)
     target_state->key[i] = state->key[i];
 
   target_state->pos = state->pos;
@@ -26,17 +26,17 @@ void gen_next(mt19937_state *state) {
   static unsigned long mag02[2] = {0x0ul, MATRIX_A};
 
   num = state->pos;
-  if (num < N - M) {
+  if (num < _MT19937_N - _MT19937_M) {
     y = (state->key[num] & UPPER_MASK) | (state->key[num + 1] & LOWER_MASK);
-    state->key[num] = state->key[num + M] ^ (y >> 1) ^ mag02[y % 2];
+    state->key[num] = state->key[num + _MT19937_M] ^ (y >> 1) ^ mag02[y % 2];
     state->pos++;
-  } else if (num < N - 1) {
+  } else if (num < _MT19937_N - 1) {
     y = (state->key[num] & UPPER_MASK) | (state->key[num + 1] & LOWER_MASK);
-    state->key[num] = state->key[num + (M - N)] ^ (y >> 1) ^ mag02[y % 2];
+    state->key[num] = state->key[num + (_MT19937_M - _MT19937_N)] ^ (y >> 1) ^ mag02[y % 2];
     state->pos++;
-  } else if (num == N - 1) {
-    y = (state->key[N - 1] & UPPER_MASK) | (state->key[0] & LOWER_MASK);
-    state->key[N - 1] = state->key[M - 1] ^ (y >> 1) ^ mag02[y % 2];
+  } else if (num == _MT19937_N - 1) {
+    y = (state->key[_MT19937_N - 1] & UPPER_MASK) | (state->key[0] & LOWER_MASK);
+    state->key[_MT19937_N - 1] = state->key[_MT19937_M - 1] ^ (y >> 1) ^ mag02[y % 2];
     state->pos = 0;
   }
 }
@@ -45,19 +45,19 @@ void add_state(mt19937_state *state1, mt19937_state *state2) {
   int i, pt1 = state1->pos, pt2 = state2->pos;
 
   if (pt2 - pt1 >= 0) {
-    for (i = 0; i < N - pt2; i++)
+    for (i = 0; i < _MT19937_N - pt2; i++)
       state1->key[i + pt1] ^= state2->key[i + pt2];
-    for (; i < N - pt1; i++)
-      state1->key[i + pt1] ^= state2->key[i + (pt2 - N)];
-    for (; i < N; i++)
-      state1->key[i + (pt1 - N)] ^= state2->key[i + (pt2 - N)];
+    for (; i < _MT19937_N - pt1; i++)
+      state1->key[i + pt1] ^= state2->key[i + (pt2 - _MT19937_N)];
+    for (; i < _MT19937_N; i++)
+      state1->key[i + (pt1 - _MT19937_N)] ^= state2->key[i + (pt2 - _MT19937_N)];
   } else {
-    for (i = 0; i < N - pt1; i++)
+    for (i = 0; i < _MT19937_N - pt1; i++)
       state1->key[i + pt1] ^= state2->key[i + pt2];
-    for (; i < N - pt2; i++)
-      state1->key[i + (pt1 - N)] ^= state2->key[i + pt2];
-    for (; i < N; i++)
-      state1->key[i + (pt1 - N)] ^= state2->key[i + (pt2 - N)];
+    for (; i < _MT19937_N - pt2; i++)
+      state1->key[i + (pt1 - _MT19937_N)] ^= state2->key[i + pt2];
+    for (; i < _MT19937_N; i++)
+      state1->key[i + (pt1 - _MT19937_N)] ^= state2->key[i + (pt2 - _MT19937_N)];
   }
 }
 
@@ -104,7 +104,7 @@ void mt19937_jump_state(mt19937_state *state) {
     pf[i] = poly_coef[i];
   }
 
-  if (state->pos >= N) {
+  if (state->pos >= _MT19937_N) {
     state->pos = 0;
   }
 
diff --git a/numpy/random/src/mt19937/mt19937.c b/numpy/random/src/mt19937/mt19937.c
index bec518af8059..d52442858dbe 100644
--- a/numpy/random/src/mt19937/mt19937.c
+++ b/numpy/random/src/mt19937/mt19937.c
@@ -83,16 +83,16 @@ void mt19937_gen(mt19937_state *state) {
   uint32_t y;
   int i;
 
-  for (i = 0; i < N - M; i++) {
+  for (i = 0; i < _MT19937_N - _MT19937_M; i++) {
     y = (state->key[i] & UPPER_MASK) | (state->key[i + 1] & LOWER_MASK);
-    state->key[i] = state->key[i + M] ^ (y >> 1) ^ (-(y & 1) & MATRIX_A);
+    state->key[i] = state->key[i + _MT19937_M] ^ (y >> 1) ^ (-(y & 1) & MATRIX_A);
   }
-  for (; i < N - 1; i++) {
+  for (; i < _MT19937_N - 1; i++) {
     y = (state->key[i] & UPPER_MASK) | (state->key[i + 1] & LOWER_MASK);
-    state->key[i] = state->key[i + (M - N)] ^ (y >> 1) ^ (-(y & 1) & MATRIX_A);
+    state->key[i] = state->key[i + (_MT19937_M - _MT19937_N)] ^ (y >> 1) ^ (-(y & 1) & MATRIX_A);
   }
-  y = (state->key[N - 1] & UPPER_MASK) | (state->key[0] & LOWER_MASK);
-  state->key[N - 1] = state->key[M - 1] ^ (y >> 1) ^ (-(y & 1) & MATRIX_A);
+  y = (state->key[_MT19937_N - 1] & UPPER_MASK) | (state->key[0] & LOWER_MASK);
+  state->key[_MT19937_N - 1] = state->key[_MT19937_M - 1] ^ (y >> 1) ^ (-(y & 1) & MATRIX_A);
 
   state->pos = 0;
 }
diff --git a/numpy/random/src/mt19937/mt19937.h b/numpy/random/src/mt19937/mt19937.h
index 83129336a953..d84dc57fb301 100644
--- a/numpy/random/src/mt19937/mt19937.h
+++ b/numpy/random/src/mt19937/mt19937.h
@@ -8,8 +8,8 @@
 
 #define RK_STATE_LEN 624
 
-#define N 624
-#define M 397
+#define _MT19937_N 624
+#define _MT19937_M 397
 #define MATRIX_A 0x9908b0dfUL
 #define UPPER_MASK 0x80000000UL
 #define LOWER_MASK 0x7fffffffUL

From 828cfbea392ea4ae5af4dea7a72c384c57e0a92b Mon Sep 17 00:00:00 2001
From: Maanas Arora 
Date: Wed, 7 May 2025 22:54:39 -0400
Subject: [PATCH 191/202] BUG: dtype.str uses string conversion defined on
 dtype for new-style dtypes

---
 numpy/_core/src/multiarray/descriptor.c | 4 ++++
 1 file changed, 4 insertions(+)

diff --git a/numpy/_core/src/multiarray/descriptor.c b/numpy/_core/src/multiarray/descriptor.c
index 5f7558635594..5708e5c6ecb7 100644
--- a/numpy/_core/src/multiarray/descriptor.c
+++ b/numpy/_core/src/multiarray/descriptor.c
@@ -2116,6 +2116,10 @@ arraydescr_subdescr_get(PyArray_Descr *self, void *NPY_UNUSED(ignored))
 NPY_NO_EXPORT PyObject *
 arraydescr_protocol_typestr_get(PyArray_Descr *self, void *NPY_UNUSED(ignored))
 {
+    if (!PyDataType_ISLEGACY(NPY_DTYPE(self))) {
+        return (PyObject *) Py_TYPE(self)->tp_str((PyObject *)self);
+    }
+
     char basic_ = self->kind;
     char endian = self->byteorder;
     int size = self->elsize;

From 364ae00fcaec92ff6c689a2eb45a25d61bf07520 Mon Sep 17 00:00:00 2001
From: Maanas Arora 
Date: Thu, 8 May 2025 16:01:27 -0400
Subject: [PATCH 192/202] TST: Add tests for custom dtype .str

---
 numpy/_core/tests/test_custom_dtypes.py | 3 +++
 numpy/_core/tests/test_dtype.py         | 4 ++++
 2 files changed, 7 insertions(+)

diff --git a/numpy/_core/tests/test_custom_dtypes.py b/numpy/_core/tests/test_custom_dtypes.py
index 0eccf11abff4..ee3a02b612bf 100644
--- a/numpy/_core/tests/test_custom_dtypes.py
+++ b/numpy/_core/tests/test_custom_dtypes.py
@@ -47,6 +47,9 @@ def test_repr(self):
         # Check the repr, mainly to cover the code paths:
         assert repr(SF(scaling=1.)) == "_ScaledFloatTestDType(scaling=1.0)"
 
+    def test_dtype_str(self):
+        assert SF(1.).str == "_ScaledFloatTestDType(scaling=1.0)"
+
     def test_dtype_name(self):
         assert SF(1.).name == "_ScaledFloatTestDType64"
 
diff --git a/numpy/_core/tests/test_dtype.py b/numpy/_core/tests/test_dtype.py
index 68698fc229fb..e248eac1fa53 100644
--- a/numpy/_core/tests/test_dtype.py
+++ b/numpy/_core/tests/test_dtype.py
@@ -1174,6 +1174,10 @@ def test_void_subclass_fields(self):
         assert_equal(str(dt), "(numpy.record, [('a', '
Date: Fri, 9 May 2025 22:06:18 +0900
Subject: [PATCH 193/202] TST: Prevent import error when tests are not included
 in the wheel

It is possible to build numpy without test directories using install
tags. For example, passing the tags such as

install-args=--tags=runtime,python-runtime,devel

would exclude the test directories. However, even when the test
directories are excluded, numpy.testing is included in the wheel and one
of the file in numpy.testing tries to import the file from the test
directory, which causes an error.
---
 numpy/_core/tests/_natype.py          | 8 ++++++++
 numpy/_core/tests/test_stringdtype.py | 3 +--
 numpy/conftest.py                     | 4 ++--
 numpy/testing/_private/utils.py       | 9 ---------
 4 files changed, 11 insertions(+), 13 deletions(-)

diff --git a/numpy/_core/tests/_natype.py b/numpy/_core/tests/_natype.py
index aa335ec540c2..ae241c391c07 100644
--- a/numpy/_core/tests/_natype.py
+++ b/numpy/_core/tests/_natype.py
@@ -194,3 +194,11 @@ def __array_ufunc__(self, ufunc, method, *inputs, **kwargs):
 
 
 pd_NA = NAType()
+
+
+def get_stringdtype_dtype(na_object, coerce=True):
+    # explicit is check for pd_NA because != with pd_NA returns pd_NA
+    if na_object is pd_NA or na_object != "unset":
+        return np.dtypes.StringDType(na_object=na_object, coerce=coerce)
+    else:
+        return np.dtypes.StringDType(coerce=coerce)
diff --git a/numpy/_core/tests/test_stringdtype.py b/numpy/_core/tests/test_stringdtype.py
index 7ed7f975b04b..66b642cbd73a 100644
--- a/numpy/_core/tests/test_stringdtype.py
+++ b/numpy/_core/tests/test_stringdtype.py
@@ -9,9 +9,8 @@
 import pytest
 
 from numpy.dtypes import StringDType
-from numpy._core.tests._natype import pd_NA
+from numpy._core.tests._natype import pd_NA, get_stringdtype_dtype as get_dtype
 from numpy.testing import assert_array_equal, IS_PYPY
-from numpy.testing._private.utils import get_stringdtype_dtype as get_dtype
 
 
 @pytest.fixture
diff --git a/numpy/conftest.py b/numpy/conftest.py
index 84d856e55684..f323320d9f47 100644
--- a/numpy/conftest.py
+++ b/numpy/conftest.py
@@ -14,8 +14,8 @@
 import numpy as np
 
 from numpy._core._multiarray_tests import get_fpu_mode
-from numpy._core.tests._natype import pd_NA
-from numpy.testing._private.utils import NOGIL_BUILD, get_stringdtype_dtype
+from numpy._core.tests._natype import pd_NA, get_stringdtype_dtype
+from numpy.testing._private.utils import NOGIL_BUILD
 
 try:
     from scipy_doctest.conftest import dt_config
diff --git a/numpy/testing/_private/utils.py b/numpy/testing/_private/utils.py
index 5cbb5130dc1f..0cfd50cb2124 100644
--- a/numpy/testing/_private/utils.py
+++ b/numpy/testing/_private/utils.py
@@ -27,7 +27,6 @@
      intp, float32, empty, arange, array_repr, ndarray, isnat, array)
 from numpy import isfinite, isnan, isinf
 import numpy.linalg._umath_linalg
-from numpy._core.tests._natype import pd_NA
 
 from io import StringIO
 
@@ -2751,11 +2750,3 @@ def run_threaded(func, max_workers=8, pass_count=False,
                     barrier.abort()
             for f in futures:
                 f.result()
-
-
-def get_stringdtype_dtype(na_object, coerce=True):
-    # explicit is check for pd_NA because != with pd_NA returns pd_NA
-    if na_object is pd_NA or na_object != "unset":
-        return np.dtypes.StringDType(na_object=na_object, coerce=coerce)
-    else:
-        return np.dtypes.StringDType(coerce=coerce)

From ae8b43d6647d0a8f6bf2490f5ecfdfaab4e548e4 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Mateusz=20Sok=C3=B3=C5=82?= 
Date: Tue, 1 Apr 2025 13:17:04 +0000
Subject: [PATCH 194/202] ENH: Updgrade Array API version to 2024.12

---
 .github/workflows/linux.yml                   |  2 +-
 numpy/__init__.py                             |  2 +-
 numpy/__init__.pyi                            |  4 +--
 .../_core/src/multiarray/array_api_standard.c |  3 ++-
 numpy/_core/src/multiarray/multiarraymodule.c | 10 ++++---
 numpy/_core/tests/test_regression.py          |  8 +++---
 tools/ci/array-api-xfails.txt                 | 27 +++++++++++++++++++
 7 files changed, 45 insertions(+), 11 deletions(-)

diff --git a/.github/workflows/linux.yml b/.github/workflows/linux.yml
index 4e57e7621543..dc9ef34db71d 100644
--- a/.github/workflows/linux.yml
+++ b/.github/workflows/linux.yml
@@ -324,7 +324,7 @@ jobs:
       uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2
       with:
         repository: data-apis/array-api-tests
-        ref: '827edd804bcace9d64176b8115138d29ae3e8dec'  # Latest commit as of 2024-07-30
+        ref: 'c48410f96fc58e02eea844e6b7f6cc01680f77ce'  # Latest commit as of 2025-04-01
         submodules: 'true'
         path: 'array-api-tests'
         persist-credentials: false
diff --git a/numpy/__init__.py b/numpy/__init__.py
index f1eb956c5b8c..508fc0d8970b 100644
--- a/numpy/__init__.py
+++ b/numpy/__init__.py
@@ -289,7 +289,7 @@
     # import with `from numpy import *`.
     __future_scalars__ = {"str", "bytes", "object"}
 
-    __array_api_version__ = "2023.12"
+    __array_api_version__ = "2024.12"
 
     from ._array_api_info import __array_namespace_info__
 
diff --git a/numpy/__init__.pyi b/numpy/__init__.pyi
index 5502d6e0755a..551921889bf5 100644
--- a/numpy/__init__.pyi
+++ b/numpy/__init__.pyi
@@ -965,7 +965,7 @@ _DTypeNum: TypeAlias = L[
 ]
 _DTypeBuiltinKind: TypeAlias = L[0, 1, 2]
 
-_ArrayAPIVersion: TypeAlias = L["2021.12", "2022.12", "2023.12"]
+_ArrayAPIVersion: TypeAlias = L["2021.12", "2022.12", "2023.12", "2024.12"]
 
 _CastingKind: TypeAlias = L["no", "equiv", "safe", "same_kind", "unsafe"]
 
@@ -1153,7 +1153,7 @@ __NUMPY_SETUP__: Final[L[False]] = False
 __numpy_submodules__: Final[set[LiteralString]] = ...
 __former_attrs__: Final[_FormerAttrsDict] = ...
 __future_scalars__: Final[set[L["bytes", "str", "object"]]] = ...
-__array_api_version__: Final[L["2023.12"]] = "2023.12"
+__array_api_version__: Final[L["2024.12"]] = "2024.12"
 test: Final[PytestTester] = ...
 
 @type_check_only
diff --git a/numpy/_core/src/multiarray/array_api_standard.c b/numpy/_core/src/multiarray/array_api_standard.c
index 76612cff36fb..317fd8a69bb4 100644
--- a/numpy/_core/src/multiarray/array_api_standard.c
+++ b/numpy/_core/src/multiarray/array_api_standard.c
@@ -60,7 +60,8 @@ array_array_namespace(PyObject *NPY_UNUSED(self), PyObject *args, PyObject *kwds
             return NULL;
         } else if (PyUnicode_CompareWithASCIIString(array_api_version, "2021.12") != 0 &&
             PyUnicode_CompareWithASCIIString(array_api_version, "2022.12") != 0 &&
-            PyUnicode_CompareWithASCIIString(array_api_version, "2023.12") != 0)
+            PyUnicode_CompareWithASCIIString(array_api_version, "2023.12") != 0 &&
+            PyUnicode_CompareWithASCIIString(array_api_version, "2024.12") != 0)
         {
             PyErr_Format(PyExc_ValueError,
                 "Version \"%U\" of the Array API Standard is not supported.",
diff --git a/numpy/_core/src/multiarray/multiarraymodule.c b/numpy/_core/src/multiarray/multiarraymodule.c
index a53dd0960ed0..8ba38b555edb 100644
--- a/numpy/_core/src/multiarray/multiarraymodule.c
+++ b/numpy/_core/src/multiarray/multiarraymodule.c
@@ -2280,14 +2280,18 @@ array_count_nonzero(PyObject *NPY_UNUSED(self), PyObject *const *args, Py_ssize_
         return NULL;
     }
 
-    count =  PyArray_CountNonzero(array);
-
+    count = PyArray_CountNonzero(array);
     Py_DECREF(array);
 
     if (count == -1) {
         return NULL;
     }
-    return PyLong_FromSsize_t(count);
+
+    PyArray_Descr *descr = PyArray_DescrFromType(NPY_INTP);
+    if (descr == NULL) {
+        return NULL;
+    }
+    return PyArray_Scalar(&count, descr, NULL);
 }
 
 static PyObject *
diff --git a/numpy/_core/tests/test_regression.py b/numpy/_core/tests/test_regression.py
index 8aca446b3920..63899899c8e8 100644
--- a/numpy/_core/tests/test_regression.py
+++ b/numpy/_core/tests/test_regression.py
@@ -2570,21 +2570,23 @@ def test__array_namespace__(self):
         assert xp is np
         xp = arr.__array_namespace__(api_version="2023.12")
         assert xp is np
+        xp = arr.__array_namespace__(api_version="2024.12")
+        assert xp is np
         xp = arr.__array_namespace__(api_version=None)
         assert xp is np
 
         with pytest.raises(
             ValueError,
-            match="Version \"2024.12\" of the Array API Standard "
+            match="Version \"2025.12\" of the Array API Standard "
                   "is not supported."
         ):
-            arr.__array_namespace__(api_version="2024.12")
+            arr.__array_namespace__(api_version="2025.12")
 
         with pytest.raises(
             ValueError,
             match="Only None and strings are allowed as the Array API version"
         ):
-            arr.__array_namespace__(api_version=2023)
+            arr.__array_namespace__(api_version=2024)
 
     def test_isin_refcnt_bug(self):
         # gh-25295
diff --git a/tools/ci/array-api-xfails.txt b/tools/ci/array-api-xfails.txt
index c81b61c5740e..98c3895ced06 100644
--- a/tools/ci/array-api-xfails.txt
+++ b/tools/ci/array-api-xfails.txt
@@ -21,3 +21,30 @@ array_api_tests/test_signatures.py::test_func_signature[vecdot]
 
 # input is cast to min/max's dtype if they're different
 array_api_tests/test_operators_and_elementwise_functions.py::test_clip
+
+# missing 'dtype' keyword argument
+array_api_tests/test_signatures.py::test_extension_func_signature[fft.fftfreq]
+array_api_tests/test_signatures.py::test_extension_func_signature[fft.rfftfreq]
+
+# fails on np.repeat(np.array([]), np.array([])) test case
+array_api_tests/test_manipulation_functions.py::test_repeat
+
+# NumPy matches Python behavior and it returns NaN and -1 in these cases
+array_api_tests/test_special_cases.py::test_binary[floor_divide(x1_i is +infinity and isfinite(x2_i) and x2_i > 0) -> +infinity]
+array_api_tests/test_special_cases.py::test_binary[floor_divide(x1_i is +infinity and isfinite(x2_i) and x2_i < 0) -> -infinity]
+array_api_tests/test_special_cases.py::test_binary[floor_divide(x1_i is -infinity and isfinite(x2_i) and x2_i > 0) -> -infinity]
+array_api_tests/test_special_cases.py::test_binary[floor_divide(x1_i is -infinity and isfinite(x2_i) and x2_i < 0) -> +infinity]
+array_api_tests/test_special_cases.py::test_binary[__floordiv__(x1_i is +infinity and isfinite(x2_i) and x2_i > 0) -> +infinity]
+array_api_tests/test_special_cases.py::test_binary[__floordiv__(x1_i is +infinity and isfinite(x2_i) and x2_i < 0) -> -infinity]
+array_api_tests/test_special_cases.py::test_binary[__floordiv__(x1_i is -infinity and isfinite(x2_i) and x2_i > 0) -> -infinity]
+array_api_tests/test_special_cases.py::test_binary[__floordiv__(x1_i is -infinity and isfinite(x2_i) and x2_i < 0) -> +infinity]
+array_api_tests/test_special_cases.py::test_binary[floor_divide(isfinite(x1_i) and x1_i > 0 and x2_i is -infinity) -> -0]
+array_api_tests/test_special_cases.py::test_binary[floor_divide(isfinite(x1_i) and x1_i < 0 and x2_i is +infinity) -> -0]
+array_api_tests/test_special_cases.py::test_binary[__floordiv__(isfinite(x1_i) and x1_i > 0 and x2_i is -infinity) -> -0]
+array_api_tests/test_special_cases.py::test_binary[__floordiv__(isfinite(x1_i) and x1_i < 0 and x2_i is +infinity) -> -0]
+array_api_tests/test_special_cases.py::test_iop[__ifloordiv__(x1_i is +infinity and isfinite(x2_i) and x2_i > 0) -> +infinity]
+array_api_tests/test_special_cases.py::test_iop[__ifloordiv__(x1_i is +infinity and isfinite(x2_i) and x2_i < 0) -> -infinity]
+array_api_tests/test_special_cases.py::test_iop[__ifloordiv__(x1_i is -infinity and isfinite(x2_i) and x2_i > 0) -> -infinity]
+array_api_tests/test_special_cases.py::test_iop[__ifloordiv__(x1_i is -infinity and isfinite(x2_i) and x2_i < 0) -> +infinity]
+array_api_tests/test_special_cases.py::test_iop[__ifloordiv__(isfinite(x1_i) and x1_i > 0 and x2_i is -infinity) -> -0]
+array_api_tests/test_special_cases.py::test_iop[__ifloordiv__(isfinite(x1_i) and x1_i < 0 and x2_i is +infinity) -> -0]

From cd000d5109e31bfa15c6dcb48cd8f3fcdbbca94c Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Mateusz=20Sok=C3=B3=C5=82?= 
Date: Wed, 2 Apr 2025 10:30:32 +0000
Subject: [PATCH 195/202] Add a release note

---
 doc/release/upcoming_changes/28615.change.rst | 2 ++
 1 file changed, 2 insertions(+)
 create mode 100644 doc/release/upcoming_changes/28615.change.rst

diff --git a/doc/release/upcoming_changes/28615.change.rst b/doc/release/upcoming_changes/28615.change.rst
new file mode 100644
index 000000000000..0983a905f9e7
--- /dev/null
+++ b/doc/release/upcoming_changes/28615.change.rst
@@ -0,0 +1,2 @@
+* NumPy's ``__array_api_version__`` was upgraded from ``2023.12`` to ``2024.12``.
+* `numpy.count_nonzero` for ``axis=None`` now returns a scalar instead of a Python integer.

From 26f33928649ba667e2221ff8f0c090220858d13a Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Mateusz=20Sok=C3=B3=C5=82?= 
Date: Wed, 2 Apr 2025 20:13:10 +0000
Subject: [PATCH 196/202] Refine `count_nonzero` typing stub

---
 numpy/_core/numeric.pyi                    | 2 +-
 numpy/typing/tests/data/reveal/numeric.pyi | 6 +++---
 2 files changed, 4 insertions(+), 4 deletions(-)

diff --git a/numpy/_core/numeric.pyi b/numpy/_core/numeric.pyi
index d60639b97687..416c4eec8785 100644
--- a/numpy/_core/numeric.pyi
+++ b/numpy/_core/numeric.pyi
@@ -416,7 +416,7 @@ def full_like(
 
 #
 @overload
-def count_nonzero(a: ArrayLike, axis: None = None, *, keepdims: L[False] = False) -> int: ...
+def count_nonzero(a: ArrayLike, axis: None = None, *, keepdims: L[False] = False) -> np.intp: ...
 @overload
 def count_nonzero(a: _ScalarLike_co, axis: _ShapeLike | None = None, *, keepdims: L[True]) -> np.intp: ...
 @overload
diff --git a/numpy/typing/tests/data/reveal/numeric.pyi b/numpy/typing/tests/data/reveal/numeric.pyi
index bd94f4e7eede..7c1ea8958e3b 100644
--- a/numpy/typing/tests/data/reveal/numeric.pyi
+++ b/numpy/typing/tests/data/reveal/numeric.pyi
@@ -25,9 +25,9 @@ AR_O: npt.NDArray[np.object_]
 B: list[int]
 C: SubClass
 
-assert_type(np.count_nonzero(i8), int)
-assert_type(np.count_nonzero(AR_i8), int)
-assert_type(np.count_nonzero(B), int)
+assert_type(np.count_nonzero(i8), np.intp)
+assert_type(np.count_nonzero(AR_i8), np.intp)
+assert_type(np.count_nonzero(B), np.intp)
 assert_type(np.count_nonzero(AR_i8, keepdims=True), npt.NDArray[np.intp])
 assert_type(np.count_nonzero(AR_i8, axis=0), Any)
 

From 78d3a5bbad5ed58e86aaea8fe89472799b9c6f8a Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Mateusz=20Sok=C3=B3=C5=82?= 
Date: Tue, 22 Apr 2025 17:18:40 +0000
Subject: [PATCH 197/202] Tweak release note

---
 doc/release/upcoming_changes/28615.change.rst | 3 ++-
 1 file changed, 2 insertions(+), 1 deletion(-)

diff --git a/doc/release/upcoming_changes/28615.change.rst b/doc/release/upcoming_changes/28615.change.rst
index 0983a905f9e7..5e7b10a8e82e 100644
--- a/doc/release/upcoming_changes/28615.change.rst
+++ b/doc/release/upcoming_changes/28615.change.rst
@@ -1,2 +1,3 @@
 * NumPy's ``__array_api_version__`` was upgraded from ``2023.12`` to ``2024.12``.
-* `numpy.count_nonzero` for ``axis=None`` now returns a scalar instead of a Python integer.
+* `numpy.count_nonzero` for ``axis=None`` (default) now returns a NumPy scalar
+  instead of a Python integer.

From ff92ba826eb9bfc613bc61d71ca552f9e99bd412 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Mateusz=20Sok=C3=B3=C5=82?= 
Date: Wed, 23 Apr 2025 20:32:58 +0000
Subject: [PATCH 198/202] MAINT: Add default value for `axis` parameter in
 `numpy.take_along_axis`

---
 doc/release/upcoming_changes/28615.change.rst |  2 ++
 numpy/lib/_shape_base_impl.py                 | 15 +++++++++------
 numpy/lib/_shape_base_impl.pyi                |  2 +-
 3 files changed, 12 insertions(+), 7 deletions(-)

diff --git a/doc/release/upcoming_changes/28615.change.rst b/doc/release/upcoming_changes/28615.change.rst
index 5e7b10a8e82e..58b751e40704 100644
--- a/doc/release/upcoming_changes/28615.change.rst
+++ b/doc/release/upcoming_changes/28615.change.rst
@@ -1,3 +1,5 @@
 * NumPy's ``__array_api_version__`` was upgraded from ``2023.12`` to ``2024.12``.
 * `numpy.count_nonzero` for ``axis=None`` (default) now returns a NumPy scalar
   instead of a Python integer.
+* The parameter ``axis`` in `numpy.take_along_axis` function has now a default
+  value of ``-1``.
diff --git a/numpy/lib/_shape_base_impl.py b/numpy/lib/_shape_base_impl.py
index fe5dc38efe38..f9b41f77943c 100644
--- a/numpy/lib/_shape_base_impl.py
+++ b/numpy/lib/_shape_base_impl.py
@@ -50,12 +50,12 @@ def _make_along_axis_idx(arr_shape, indices, axis):
     return tuple(fancy_index)
 
 
-def _take_along_axis_dispatcher(arr, indices, axis):
+def _take_along_axis_dispatcher(arr, indices, axis=None):
     return (arr, indices)
 
 
 @array_function_dispatch(_take_along_axis_dispatcher)
-def take_along_axis(arr, indices, axis):
+def take_along_axis(arr, indices, axis=-1):
     """
     Take values from the input array by matching 1d index and data slices.
 
@@ -71,14 +71,17 @@ def take_along_axis(arr, indices, axis):
     arr : ndarray (Ni..., M, Nk...)
         Source array
     indices : ndarray (Ni..., J, Nk...)
-        Indices to take along each 1d slice of `arr`. This must match the
-        dimension of arr, but dimensions Ni and Nj only need to broadcast
-        against `arr`.
-    axis : int
+        Indices to take along each 1d slice of ``arr``. This must match the
+        dimension of ``arr``, but dimensions Ni and Nj only need to broadcast
+        against ``arr``.
+    axis : int or None, optional
         The axis to take 1d slices along. If axis is None, the input array is
         treated as if it had first been flattened to 1d, for consistency with
         `sort` and `argsort`.
 
+        .. versionchanged:: 2.3
+            The default value is now ``-1``.
+
     Returns
     -------
     out: ndarray (Ni..., J, Nk...)
diff --git a/numpy/lib/_shape_base_impl.pyi b/numpy/lib/_shape_base_impl.pyi
index 09d67cc3a062..15cbef7e4773 100644
--- a/numpy/lib/_shape_base_impl.pyi
+++ b/numpy/lib/_shape_base_impl.pyi
@@ -70,7 +70,7 @@ class _SupportsArrayWrap(Protocol):
 def take_along_axis(
     arr: _ScalarT | NDArray[_ScalarT],
     indices: NDArray[integer],
-    axis: int | None,
+    axis: int | None = ...,
 ) -> NDArray[_ScalarT]: ...
 
 def put_along_axis(

From e3d860d51fb6b24bb836bafd6bffc17a5e4b5a84 Mon Sep 17 00:00:00 2001
From: Saransh Chopra 
Date: Sat, 10 May 2025 21:26:20 +0100
Subject: [PATCH 199/202] 2024.12 is now supported

---
 doc/source/reference/array_api.rst | 10 ++++------
 1 file changed, 4 insertions(+), 6 deletions(-)

diff --git a/doc/source/reference/array_api.rst b/doc/source/reference/array_api.rst
index 135db1f948c3..d876f6e6b1d4 100644
--- a/doc/source/reference/array_api.rst
+++ b/doc/source/reference/array_api.rst
@@ -6,13 +6,11 @@ Array API standard compatibility
 
 NumPy's main namespace as well as the `numpy.fft` and `numpy.linalg` namespaces
 are compatible with the
-`2023.12 version `__
+`2024.12 version `__
 of the Python array API standard.
 
-NumPy aims to implement support for the
-`2024.12 version `__
-(in progress) and future versions of the standard - assuming that those future
-versions can be upgraded to given NumPy's
+NumPy aims to implement support for the future versions of the standard
+- assuming that those future versions can be upgraded to given NumPy's
 :ref:`backwards compatibility policy `.
 
 For usage guidelines for downstream libraries and end users who want to write
@@ -33,7 +31,7 @@ rather than anything NumPy-specific, the `array-api-strict
     standard, via a separate ``numpy.array_api`` submodule. This module was
     marked as experimental (it emitted a warning on import) and removed in
     NumPy 2.0 because full support (2022.12 version [1]_) was included in
-    the main namespace (with 2023.12 version support in NumPy 2.1).
+    the main namespace.
     :ref:`NEP 47 ` and
     :ref:`NEP 56 `
     describe the motivation and scope for implementing the array API standard

From 888a58ec25e8a43474b9adc78fd280325c031764 Mon Sep 17 00:00:00 2001
From: Saransh Chopra 
Date: Sun, 11 May 2025 11:48:30 +0100
Subject: [PATCH 200/202] specify NumPy version

---
 doc/source/reference/array_api.rst | 4 ++--
 1 file changed, 2 insertions(+), 2 deletions(-)

diff --git a/doc/source/reference/array_api.rst b/doc/source/reference/array_api.rst
index d876f6e6b1d4..66a607f12286 100644
--- a/doc/source/reference/array_api.rst
+++ b/doc/source/reference/array_api.rst
@@ -4,8 +4,8 @@
 Array API standard compatibility
 ********************************
 
-NumPy's main namespace as well as the `numpy.fft` and `numpy.linalg` namespaces
-are compatible with the
+The NumPy 2.3.0 main namespace as well as the `numpy.fft` and `numpy.linalg`
+namespaces are compatible with the
 `2024.12 version `__
 of the Python array API standard.
 

From 25387ef82cd0754481c4a272d849b5ded20e9015 Mon Sep 17 00:00:00 2001
From: Charles Harris 
Date: Sun, 11 May 2025 11:10:27 -0600
Subject: [PATCH 201/202] DOC: Fix titles in development_ghcodespaces.rst

[skip azp] [skip cirrus] [skip actions]
---
 doc/source/dev/development_ghcodespaces.rst | 64 ++++++++++-----------
 doc/source/dev/index.rst                    |  1 +
 2 files changed, 33 insertions(+), 32 deletions(-)

diff --git a/doc/source/dev/development_ghcodespaces.rst b/doc/source/dev/development_ghcodespaces.rst
index b57b90a2174e..b6c8f0d5f0f4 100644
--- a/doc/source/dev/development_ghcodespaces.rst
+++ b/doc/source/dev/development_ghcodespaces.rst
@@ -21,31 +21,31 @@ on your local machine or worry about configuration.
 What is a codespace?
 --------------------
 
-A codespace is an instance of Codespaces - and thus a development 
-environment that is hosted in the cloud. Each codespace runs on a virtual 
-machine hosted by GitHub. You can choose the type of machine you want to use, 
-depending on the resources you need. Various types of machine are available, 
-starting with a 2-core processor, 4 GB of RAM, and 32 GB of storage.
-You can connect to a codespace from your browser, from Visual Studio Code, 
-from the JetBrains Gateway application, or by using GitHub CLI.
+A codespace is an instance of Codespaces - and thus a development environment
+that is hosted in the cloud. Each codespace runs on a virtual machine hosted by
+GitHub. You can choose the type of machine you want to use, depending on the
+resources you need. Various types of machine are available, starting with a
+2-core processor, 4 GB of RAM, and 32 GB of storage.  You can connect to a
+codespace from your browser, from Visual Studio Code, from the JetBrains
+Gateway application, or by using GitHub CLI.
 
 Forking the NumPy repository
 ----------------------------
 
-The best way to work on the NumPy codebase as a contributor is by making a fork of the 
-repository first.
+The best way to work on the NumPy codebase as a contributor is by making a fork
+of the repository first.
 
 #. Browse to the `NumPy repository on GitHub`_ and `create your own fork`_.
 #. Browse to your fork. Your fork will have a URL like 
    https://github.com/inessapawson/numpy, except with your GitHub username in place of ``inessapawson``.
      
-Starting GitHub Codespaces - draft
+Starting GitHub Codespaces
 --------------------------
 
-You can create a codespace from the green "Code" button (image to be added)
-on the repository home page, or click on this `open (image to be added)`_ button
+You can create a codespace from the green "<> Code" button on the repository
+home page and choose "Codespaces", or click this link `open`_.
 
-Quick workspace tour - draft
+Quick workspace tour
 --------------------
 
 You can develop code in a codespace using your choice of tool:
@@ -55,43 +55,43 @@ You can develop code in a codespace using your choice of tool:
 * the Visual Studio Code desktop application._
 * a browser-based version of Visual Studio Code._
 
-In this quickstart, we will be using the VSCode desktop application as the editor. 
-If you have not used it before, see the Getting started `VSCode docs`_ to familiarize
-yourself with this tool.
+In this quickstart, we will be using the VSCode desktop application as the
+editor.  If you have not used it before, see the Getting started `VSCode docs`_
+to familiarize yourself with this tool.
 
 Your workspace will look similar to the image below:
 
 Development workflow with GitHub Codespaces
 -------------------------------------------
 
-The  :ref:`development-workflow` section of this documentation contains 
-information regarding the NumPy development workflow. Make sure to check this 
+The  :ref:`development-workflow` section of this documentation contains
+information regarding the NumPy development workflow. Make sure to check this
 before you start working on your contributions.
 
-Rendering the NumPy documentation - draft
+Rendering the NumPy documentation
 ---------------------------------
 
-You can find the detailed documentation on how the rendering of the documentation with 
-Sphinx works in the :ref:`howto-build-docs` section.
+You can find the detailed documentation on how the rendering of the
+documentation with Sphinx works in the :ref:`howto-build-docs` section.
 
-The documentation is pre-built during your codespace initialization. So once 
-this task is completed, you have two main options to render the documentation 
+The documentation is pre-built during your codespace initialization. So once
+this task is completed, you have two main options to render the documentation
 in GitHub Codespaces.
 
 FAQs and troubleshooting
--------------------------
+------------------------
 
 **How long does my codespace stay active if I'm not using it?**
-If you leave your codespace running without interaction, or if you exit your 
-codespace without explicitly stopping it, by default the codespace will timeout 
-after 30 minutes of inactivity. You can customize the duration of the timeout period 
-for new codespaces that you create.
+If you leave your codespace running without interaction, or if you exit your
+codespace without explicitly stopping it, by default the codespace will timeout
+after 30 minutes of inactivity. You can customize the duration of the timeout
+period for new codespaces that you create.
 
 **Can I come back to a previous codespace?**
-The lifecycle of a codespace begins when you create a codespace and ends 
-when you delete it. You can disconnect and reconnect to an active codespace without 
-affecting its running processes. You may stop and restart a codespace without losing 
-changes that you have made to your project.
+The lifecycle of a codespace begins when you create a codespace and ends when
+you delete it. You can disconnect and reconnect to an active codespace without
+affecting its running processes. You may stop and restart a codespace without
+losing changes that you have made to your project.
 
 .. _GitHub Codespaces: https://github.com/features/codespaces
 .. _NumPy repository on GitHub: https://github.com/NumPy/NumPy
diff --git a/doc/source/dev/index.rst b/doc/source/dev/index.rst
index dfa84a1f6331..2664ee745579 100644
--- a/doc/source/dev/index.rst
+++ b/doc/source/dev/index.rst
@@ -256,6 +256,7 @@ The rest of the story
    howto_build_docs
    development_workflow
    development_advanced_debugging
+   development_ghcodespaces
    reviewer_guidelines
    ../benchmarking
    NumPy C style guide 

From 49f31e738c319ae2da952406cae1d062554a90dd Mon Sep 17 00:00:00 2001
From: Pieter Eendebak 
Date: Mon, 12 May 2025 10:22:18 +0200
Subject: [PATCH 202/202] MAINT: Gradually introduce linting with ruff E501

---
 .spin/cmds.py                              |  3 ++-
 doc/source/conf.py                         |  3 ++-
 doc/source/reference/random/performance.py |  3 ++-
 numpy/ctypeslib/_ctypeslib.py              |  2 +-
 numpy/exceptions.py                        |  2 +-
 numpy/fft/_pocketfft.py                    |  3 +--
 numpy/fft/tests/test_helper.py             |  2 +-
 numpy/testing/_private/extbuild.py         |  3 ++-
 ruff.toml                                  | 17 ++++++++++++++++-
 9 files changed, 28 insertions(+), 10 deletions(-)

diff --git a/.spin/cmds.py b/.spin/cmds.py
index f9c7658fbf17..be4364b3b40a 100644
--- a/.spin/cmds.py
+++ b/.spin/cmds.py
@@ -615,7 +615,8 @@ def notes(version_override):
     )
 
     try:
-        test_notes = _get_numpy_tools(pathlib.Path('ci', 'test_all_newsfragments_used.py'))
+        cmd = pathlib.Path('ci', 'test_all_newsfragments_used.py')
+        test_notes = _get_numpy_tools(cmd)
     except ModuleNotFoundError as e:
         raise click.ClickException(
             f"{e.msg}. Install the missing packages to use this command."
diff --git a/doc/source/conf.py b/doc/source/conf.py
index f437cbb6e83e..3c80fd6a4dfd 100644
--- a/doc/source/conf.py
+++ b/doc/source/conf.py
@@ -20,7 +20,8 @@ def replace_scalar_type_names():
     """ Rename numpy types to use the canonical names to make sphinx behave """
     import ctypes
 
-    Py_ssize_t = ctypes.c_int64 if ctypes.sizeof(ctypes.c_void_p) == 8 else ctypes.c_int32
+    sizeof_void_p = ctypes.sizeof(ctypes.c_void_p)
+    Py_ssize_t = ctypes.c_int64 if sizeof_void_p == 8 else ctypes.c_int32
 
     class PyObject(ctypes.Structure):
         pass
diff --git a/doc/source/reference/random/performance.py b/doc/source/reference/random/performance.py
index b419f3f61100..5ae39e7d330b 100644
--- a/doc/source/reference/random/performance.py
+++ b/doc/source/reference/random/performance.py
@@ -74,7 +74,8 @@
 print(rel.to_csv(float_format='%0d'))
 
 # Cross-platform table
-rows = ['32-bit Unsigned Ints', '64-bit Unsigned Ints', 'Uniforms', 'Normals', 'Exponentials']
+rows = ['32-bit Unsigned Ints', '64-bit Unsigned Ints', 'Uniforms',
+        'Normals', 'Exponentials']
 xplat = rel.reindex(rows, axis=0)
 xplat = 100 * (xplat / xplat.MT19937.values[:, None])
 overall = np.exp(np.log(xplat).mean(0))
diff --git a/numpy/ctypeslib/_ctypeslib.py b/numpy/ctypeslib/_ctypeslib.py
index 40b9e58b5912..a711d83833da 100644
--- a/numpy/ctypeslib/_ctypeslib.py
+++ b/numpy/ctypeslib/_ctypeslib.py
@@ -409,7 +409,7 @@ def _ctype_from_dtype_structured(dtype):
         # ctypes doesn't care about field order
         field_data = sorted(field_data, key=lambda f: f[0])
 
-        if len(field_data) > 1 and all(offset == 0 for offset, name, ctype in field_data):
+        if len(field_data) > 1 and all(offset == 0 for offset, _, _ in field_data):
             # union, if multiple fields all at address 0
             size = 0
             _fields_ = []
diff --git a/numpy/exceptions.py b/numpy/exceptions.py
index 082027841520..0e8688ae9eba 100644
--- a/numpy/exceptions.py
+++ b/numpy/exceptions.py
@@ -243,5 +243,5 @@ class DTypePromotionError(TypeError):
     DTypePromotionError: field names `('field1', 'field2')` and `('field1',)`
     mismatch.
 
-    """
+    """  # noqa: E501
     pass
diff --git a/numpy/fft/_pocketfft.py b/numpy/fft/_pocketfft.py
index 8abb7e862dbf..72f43a5a5675 100644
--- a/numpy/fft/_pocketfft.py
+++ b/numpy/fft/_pocketfft.py
@@ -198,8 +198,7 @@ def fft(a, n=None, axis=-1, norm=None, out=None):
     >>> t = np.arange(256)
     >>> sp = np.fft.fft(np.sin(t))
     >>> freq = np.fft.fftfreq(t.shape[-1])
-    >>> plt.plot(freq, sp.real, freq, sp.imag)
-    [, ]
+    >>> _ = plt.plot(freq, sp.real, freq, sp.imag)
     >>> plt.show()
 
     """
diff --git a/numpy/fft/tests/test_helper.py b/numpy/fft/tests/test_helper.py
index 0255e053c3a6..987c0e748d5b 100644
--- a/numpy/fft/tests/test_helper.py
+++ b/numpy/fft/tests/test_helper.py
@@ -84,7 +84,7 @@ def test_uneven_dims(self):
         assert_array_almost_equal(fft.ifftshift(shift_dim_both), freqs)
 
     def test_equal_to_original(self):
-        """ Test that the new (>=v1.15) implementation (see #10073) is equal to the original (<=v1.14) """
+        """ Test the new (>=v1.15) and old implementations are equal (see #10073) """
         from numpy._core import asarray, concatenate, arange, take
 
         def original_fftshift(x, axes=None):
diff --git a/numpy/testing/_private/extbuild.py b/numpy/testing/_private/extbuild.py
index f81184e9af1e..2a724b73cfc3 100644
--- a/numpy/testing/_private/extbuild.py
+++ b/numpy/testing/_private/extbuild.py
@@ -233,7 +233,8 @@ def build(cfile, outputfilename, compile_extra, link_extra,
                               cwd=build_dir,
                               )
     else:
-        subprocess.check_call(["meson", "setup", "--vsenv", "..", f'--native-file={os.fspath(native_file_name)}'],
+        subprocess.check_call(["meson", "setup", "--vsenv",
+                               "..", f'--native-file={os.fspath(native_file_name)}'],
                               cwd=build_dir
                               )
 
diff --git a/ruff.toml b/ruff.toml
index 4224a478d863..035a8e70d825 100644
--- a/ruff.toml
+++ b/ruff.toml
@@ -14,6 +14,8 @@ extend-exclude = [
     "numpy/_core/src/common/pythoncapi-compat",
 ]
 
+line-length = 88
+
 [lint]
 preview = true
 extend-select = [
@@ -38,7 +40,6 @@ ignore = [
     "E266",   # Too many leading `#` before block comment
     "E302",   # TODO: Expected 2 blank lines, found 1
     "E402",   # Module level import not at top of file
-    "E501",   # TODO: Line too long
     "E712",   # Avoid equality comparisons to `True` or `False`
     "E721",   # TODO: Use `is` and `is not` for type comparisons, or `isinstance()` for isinstance check
     "E731",   # Do not assign a `lambda` expression, use a `def`
@@ -49,3 +50,17 @@ ignore = [
 
 [lint.per-file-ignores]
 "test*.py" = ["E201", "E714"]
+"benchmarks/*py" = ["E501"]
+"numpy/_build_utils/*py" = ["E501"]
+"numpy/__init__.py" = ["E501"]
+"numpy/_core/**" = ["E501"]
+"numpy/core/**" = ["E501"]
+"numpy/_typing/*py" = ["E501"]
+"numpy/lib/*py" = ["E501"]
+"numpy/linalg/*py" = ["E501"]
+"numpy/ma/*py" = ["E501"]
+"numpy/polynomial/*py" = ["E501"]
+"numpy/tests/*py" = ["E501"]
+"numpy/random/*py" = ["E501"]
+"numpy*pyi" = ["E501"]
+"numpy/f2py/*py" = ["E501"]