{ "_id": "7fd7a89707530ea4", "_schema_version": "1.0", "_cleaned_at": "2026-02-12T07:46:51.362973+00:00", "repo": "psf/requests", "repo_url": "https://github.com/psf/requests", "license_name": "Apache License 2.0", "license_spdx": "Apache-2.0", "pr_number": 7191, "title": "Update maintainers in the AUTHORS.rst", "body": "Updated the maintainers list with our rotations in the last year. This will align with the published metadata in #7012 once it's merged.", "author": "user_dbf2a999bd6d", "created_at": "2026-01-30T22:52:33+00:00", "merged_at": "2026-01-31T02:12:41+00:00", "base_branch": "main", "head_branch": "update-maintainers", "additions": 7, "deletions": 7, "changed_files": 1, "files": [ { "filename": "AUTHORS.rst", "status": "modified", "additions": 7, "deletions": 7, "changes": 14, "patch": "@@ -1,17 +1,17 @@\n Requests was lovingly created by [NAME_REDACTED]\n \n-Keepers of the Crystals\n-```````````````````````\n+Requests Maintainers\n+````````````````````\n \n+- [NAME_REDACTED] <[EMAIL_REDACTED]> [CONTRIBUTOR_REDACTED]\n - [NAME_REDACTED] [CONTRIBUTOR_REDACTED]\n-- [NAME_REDACTED] [CONTRIBUTOR_REDACTED]\n \n-Previous Keepers of Crystals\n-````````````````````````````\n+Previous Maintainers\n+````````````````````\n+\n - [NAME_REDACTED] <[EMAIL_REDACTED]> [CONTRIBUTOR_REDACTED], reluctant Keeper of the Master Crystal.\n - [NAME_REDACTED] <[EMAIL_REDACTED]> [CONTRIBUTOR_REDACTED]\n-- [NAME_REDACTED] <[EMAIL_REDACTED]> [CONTRIBUTOR_REDACTED]\n-\n+- [NAME_REDACTED] [CONTRIBUTOR_REDACTED]\n \n Patches and Suggestions\n ```````````````````````" } ], "reviews": [ { "id": 3731002085, "user": "user_0fa58b6f3572", "state": "CHANGES_REQUESTED", "body": null, "submitted_at": "2026-01-30T23:47:34+00:00" }, { "id": 3731009362, "user": "user_dbf2a999bd6d", "state": "COMMENTED", "body": null, "submitted_at": "2026-01-30T23:49:04+00:00" }, { "id": 3731208005, "user": "user_0fa58b6f3572", "state": "APPROVED", "body": null, "submitted_at": "2026-01-31T00:52:44+00:00" }, { "id": 3731209056, "user": "user_0fa58b6f3572", "state": "COMMENTED", "body": null, "submitted_at": "2026-01-31T00:53:25+00:00" }, { "id": 3731210868, "user": "user_dbf2a999bd6d", "state": "COMMENTED", "body": null, "submitted_at": "2026-01-31T00:55:11+00:00" } ], "review_comments": [ { "id": 2748444433, "user": "user_0fa58b6f3572", "body": "```suggestion\n- [NAME_EMAIL_REDACTED] [CONTRIBUTOR_REDACTED]\n```", "path": "AUTHORS.rst", "line": null, "side": "RIGHT", "created_at": "2026-01-30T23:47:28+00:00" }, { "id": 2748449786, "user": "user_dbf2a999bd6d", "body": "I completely missed that 😅 Apologies.", "path": "AUTHORS.rst", "line": null, "side": "RIGHT", "created_at": "2026-01-30T23:49:04+00:00" }, { "id": 2748609530, "user": "user_0fa58b6f3572", "body": "Maybe we should rename \"Keepers of the Crystals\" too at some point", "path": "AUTHORS.rst", "line": null, "side": "RIGHT", "created_at": "2026-01-31T00:53:25+00:00" }, { "id": 2748611665, "user": "user_dbf2a999bd6d", "body": "Yep, I'm onboard with that. We can just swap it to maintainers and former.", "path": "AUTHORS.rst", "line": null, "side": "RIGHT", "created_at": "2026-01-31T00:55:11+00:00" } ], "meta": { "languages": [ "rst" ], "touches_tests": false, "review_state_summary": { "CHANGES_REQUESTED": 1, "COMMENTED": 3, "APPROVED": 1 }, "meaningful_comment_count": 4, "has_approval": true, "has_changes_requested": true, "total_review_comments": 4 } } { "_id": "1060d9a975ea74ca", "_schema_version": "1.0", "_cleaned_at": "2026-02-12T07:46:51.378696+00:00", "repo": "psf/requests", "repo_url": "https://github.com/psf/requests", "license_name": "Apache License 2.0", "license_spdx": "Apache-2.0", "pr_number": 7012, "title": "Migrate build system to PEP 517", "body": "This PR follows up on the original [announcement ](https://github.com/psf/requests/releases/tag/v2.32.0) of migrating Requests to a PEP 517 compliant backend in 2.33.0. This PR proposes moving to ~~hatchling which has wide adoption, but there's an argument for staying on setuptools~~ setuptools after reviewing our current needs. I'd be curious to hear from other maintainers on if there's a strong preference in either direction based on other projects.\n\n[USER_REDACTED] or [USER_REDACTED] may have input from migrating urllib3 as well. Presumably users with urllib3 2.x are already capable of building with this setup in their environment.", "author": "user_dbf2a999bd6d", "created_at": "2025-08-17T16:29:40+00:00", "merged_at": "2026-01-31T02:25:56+00:00", "base_branch": "main", "head_branch": "hatchling", "additions": 79, "deletions": 111, "changed_files": 3, "files": [ { "filename": "pyproject.toml", "status": "modified", "additions": 75, "deletions": 1, "changes": 76, "patch": "@@ -1,3 +1,76 @@\n+[build-system]\n+requires = [\"setuptools>=61.0\"]\n+build-backend = \"setuptools.build_meta\"\n+\n+[project]\n+name = \"requests\"\n+description = \"Python HTTP for Humans.\"\n+readme = \"README.md\"\n+license = {text = \"Apache-2.0\"}\n+authors = [\n+ { name = \"[NAME_REDACTED]\", email = \"[EMAIL_REDACTED]\" },\n+]\n+maintainers = [\n+ {name = \"[NAME_REDACTED]\", email=\"[EMAIL_REDACTED]\"},\n+ {name = \"[NAME_REDACTED]\", email=\"[EMAIL_REDACTED]\"}\n+]\n+requires-python = \">=3.9\"\n+dependencies = [\n+ \"charset_normalizer>=2,<4\",\n+ \"idna>=2.5,<4\",\n+ \"urllib3>=1.21.1,<3\",\n+ \"certifi>=2017.4.17\"\n+]\n+dynamic = [\"version\"]\n+\n+classifiers = [\n+ \"[NAME_REDACTED] :: 5 - Production/Stable\",\n+ \"Environment :: [NAME_REDACTED]\",\n+ \"[NAME_REDACTED] :: Developers\",\n+ \"License :: OSI Approved :: [NAME_REDACTED]\",\n+ \"[NAME_REDACTED] :: English\",\n+ \"[NAME_REDACTED] :: OS Independent\",\n+ \"[NAME_REDACTED] :: Python\",\n+ \"[NAME_REDACTED] :: Python :: 3\",\n+ \"[NAME_REDACTED] :: Python :: 3.9\",\n+ \"[NAME_REDACTED] :: Python :: 3.10\",\n+ \"[NAME_REDACTED] :: Python :: 3.11\",\n+ \"[NAME_REDACTED] :: Python :: 3.12\",\n+ \"[NAME_REDACTED] :: Python :: 3.13\",\n+ \"[NAME_REDACTED] :: Python :: 3.14\",\n+ \"[NAME_REDACTED] :: Python :: 3 :: Only\",\n+ \"[NAME_REDACTED] :: Python :: Implementation :: CPython\",\n+ \"[NAME_REDACTED] :: Python :: Implementation :: PyPy\",\n+ \"Topic :: Internet :: WWW/HTTP\",\n+ \"Topic :: [NAME_REDACTED] :: Libraries\"\n+]\n+\n+[project.urls]\n+Documentation = \"https://requests.readthedocs.io\"\n+Source = \"https://github.com/psf/requests\"\n+\n+[project.optional-dependencies]\n+security = []\n+socks = [\"PySocks>=1.5.6, !=1.5.7\"]\n+use_chardet_on_py3 = [\"chardet>=3.0.2,<6\"]\n+test = [\n+ \"pytest-httpbin==2.1.0\",\n+ \"pytest-cov\",\n+ \"pytest-mock\",\n+ \"pytest-xdist\",\n+ \"PySocks>=1.5.6, !=1.5.7\",\n+ \"pytest>=3\"\n+]\n+\n+[tool.setuptools]\n+license-files = [\"LICENSE\", \"NOTICE\"]\n+\n+[tool.setuptools.dynamic]\n+version = {attr = \"requests.__version__.__version__\"}\n+\n+[tool.setuptools.packages.find]\n+where = [\"src\"]\n+\n [tool.ruff]\n target-version = \"py310\"\n src = [\"src/requests\", \"tests\"]\n@@ -12,7 +85,8 @@ select = [\n \"UP\", # pyupgrade\n \"T10\", # flake8-debugger (replaces debug-statements hook)\n ]\n-ignore = [\"E203\", \"E501\", \"UP038\", \"UP031\"]\n+# UP036: Remove once Python 3.10 is the minimum supported version\n+ignore = [\"E203\", \"E501\", \"UP038\", \"UP031\", \"UP036\"]\n per-file-ignores = {\"src/requests/__init__.py\" = [\"E402\", \"F401\"], \"src/requests/compat.py\" = [\"E402\", \"F401\"], \"tests/compat.py\" = [\"F401\"]}\n \n [tool.ruff.lint.isort]" }, { "filename": "setup.cfg", "status": "removed", "additions": 0, "deletions": 10, "changes": 10, "patch": "@@ -1,10 +0,0 @@\n-[metadata]\n-license_file = LICENSE\n-provides-extra =\n- socks\n- use_chardet_on_py3\n-requires-dist =\n- certifi>=2017.4.17\n- charset_normalizer>=2,<4\n- idna>=2.5,<4\n- urllib3>=1.21.1,<3" }, { "filename": "setup.py", "status": "modified", "additions": 4, "deletions": 100, "changes": 104, "patch": "@@ -1,105 +1,9 @@\n-#!/usr/bin/env python\n-import os\n import sys\n-from codecs import open\n \n-from setuptools import setup\n-\n-CURRENT_PYTHON = sys.version_info[:2]\n-REQUIRED_PYTHON = (3, 9)\n-\n-if CURRENT_PYTHON < REQUIRED_PYTHON:\n- sys.stderr.write(\n- \"\"\"\n-==========================\n-[NAME_REDACTED] version\n-==========================\n-This version of Requests requires at least Python {}.{}, but\n-you're trying to install it on Python {}.{}. To resolve this,\n-consider upgrading to a supported Python version.\n-\n-If you can't upgrade your Python version, you'll need to\n-pin to an older version of Requests (<2.32.0).\n-\"\"\".format(*(REQUIRED_PYTHON + CURRENT_PYTHON))\n- )\n+if sys.version_info < (3, 9):\n+ sys.stderr.write(\"Requests requires Python 3.9 or later.\\n\")\n sys.exit(1)\n \n+from setuptools import setup\n \n-# 'setup.py publish' shortcut.\n-if sys.argv[-1] == \"publish\":\n- os.system(\"python setup.py sdist bdist_wheel\")\n- os.system(\"twine upload dist/*\")\n- sys.exit()\n-\n-requires = [\n- \"charset_normalizer>=2,<4\",\n- \"idna>=2.5,<4\",\n- \"urllib3>=1.21.1,<3\",\n- \"certifi>=2017.4.17\",\n-]\n-test_requirements = [\n- \"pytest-httpbin==2.1.0\",\n- \"pytest-cov\",\n- \"pytest-mock\",\n- \"pytest-xdist\",\n- \"PySocks>=1.5.6, !=1.5.7\",\n- \"pytest>=3\",\n-]\n-\n-about = {}\n-here = os.path.abspath(os.path.dirname(__file__))\n-with open(os.path.join(here, \"src\", \"requests\", \"__version__.py\"), \"r\", \"utf-8\") as f:\n- exec(f.read(), about)\n-\n-with open(\"README.md\", \"r\", \"utf-8\") as f:\n- readme = f.read()\n-\n-setup(\n- name=about[\"__title__\"],\n- version=about[\"__version__\"],\n- description=about[\"__description__\"],\n- long_description=readme,\n- long_description_content_type=\"text/markdown\",\n- author=about[\"__author__\"],\n- author_email=about[\"__author_email__\"],\n- url=about[\"__url__\"],\n- packages=[\"requests\"],\n- package_data={\"\": [\"LICENSE\", \"NOTICE\"]},\n- package_dir={\"\": \"src\"},\n- include_package_data=True,\n- python_requires=\">=3.9\",\n- install_requires=requires,\n- license=about[\"__license__\"],\n- zip_safe=False,\n- classifiers=[\n- \"[NAME_REDACTED] :: 5 - Production/Stable\",\n- \"Environment :: [NAME_REDACTED]\",\n- \"[NAME_REDACTED] :: Developers\",\n- \"License :: OSI Approved :: [NAME_REDACTED]\",\n- \"[NAME_REDACTED] :: English\",\n- \"[NAME_REDACTED] :: OS Independent\",\n- \"[NAME_REDACTED] :: Python\",\n- \"[NAME_REDACTED] :: Python :: 3\",\n- \"[NAME_REDACTED] :: Python :: 3.9\",\n- \"[NAME_REDACTED] :: Python :: 3.10\",\n- \"[NAME_REDACTED] :: Python :: 3.11\",\n- \"[NAME_REDACTED] :: Python :: 3.12\",\n- \"[NAME_REDACTED] :: Python :: 3.13\",\n- \"[NAME_REDACTED] :: Python :: 3.14\",\n- \"[NAME_REDACTED] :: Python :: 3 :: Only\",\n- \"[NAME_REDACTED] :: Python :: Implementation :: CPython\",\n- \"[NAME_REDACTED] :: Python :: Implementation :: PyPy\",\n- \"Topic :: Internet :: WWW/HTTP\",\n- \"Topic :: [NAME_REDACTED] :: Libraries\",\n- ],\n- tests_require=test_requirements,\n- extras_require={\n- \"security\": [],\n- \"socks\": [\"PySocks>=1.5.6, !=1.5.7\"],\n- \"use_chardet_on_py3\": [\"chardet>=3.0.2,<6\"],\n- },\n- project_urls={\n- \"Documentation\": \"https://requests.readthedocs.io\",\n- \"Source\": \"https://github.com/psf/requests\",\n- },\n-)\n+setup()" } ], "reviews": [ { "id": 3730413647, "user": "user_0fa58b6f3572", "state": "APPROVED", "body": null, "submitted_at": "2026-01-30T21:08:43+00:00" }, { "id": 3730866462, "user": "user_dbf2a999bd6d", "state": "COMMENTED", "body": null, "submitted_at": "2026-01-30T23:08:15+00:00" }, { "id": 3731211174, "user": "user_0fa58b6f3572", "state": "COMMENTED", "body": null, "submitted_at": "2026-01-31T00:55:33+00:00" } ], "review_comments": [ { "id": 2748329758, "user": "user_dbf2a999bd6d", "body": "I'll note here that we left the text identifier instead of using [PEP 639](https://peps.python.org/pep-0639/) intentionally. While it is marked for deprecation in Feb 2027, the minimum supported version (setuptools 77) is still quite recent and I'm not comfortable bringing the floor up that high yet. We'll evaluate how this initial migration goes and address that later.", "path": "pyproject.toml", "line": 9, "side": "RIGHT", "created_at": "2026-01-30T23:08:16+00:00" }, { "id": 2748611996, "user": "user_0fa58b6f3572", "body": "It wouldn't be a day ending in y if something in [NAME_REDACTED] wasn't being deprecated with hard to find warning messages, that's for sure. ;)", "path": "pyproject.toml", "line": 9, "side": "RIGHT", "created_at": "2026-01-31T00:55:33+00:00" } ], "meta": { "languages": [ "cfg", "py", "toml" ], "touches_tests": false, "review_state_summary": { "APPROVED": 1, "COMMENTED": 2 }, "meaningful_comment_count": 2, "has_approval": true, "has_changes_requested": false, "total_review_comments": 2 } } { "_id": "04a3ac8f90ef3153", "_schema_version": "1.0", "_cleaned_at": "2026-02-12T07:46:51.378696+00:00", "repo": "psf/requests", "repo_url": "https://github.com/psf/requests", "license_name": "Apache License 2.0", "license_spdx": "Apache-2.0", "pr_number": 6963, "title": "fix CVE 2024 47081: manual url parsing leads to netloc credentials leak", "body": "https://seclists.org/fulldisclosure/2025/Jun/2\n\nHonestly I have no idea why this lib used `netloc` + manual parsing instead of `hostname` as I can see references to `hostname` as early as from [the python 2.6 docs](https://docs.python.org/2.6/library/urlparse.html).", "author": "user_50fe2a4bfbbf", "created_at": "2025-06-04T10:59:08+00:00", "merged_at": "2025-06-05T14:55:33+00:00", "base_branch": "main", "head_branch": "aw/fix-CVE-2024-47081", "additions": 20, "deletions": 8, "changed_files": 2, "files": [ { "filename": "src/requests/utils.py", "status": "modified", "additions": 1, "deletions": 8, "changes": 9, "patch": "@@ -219,14 +219,7 @@ def get_netrc_auth(url, raise_errors=False):\n netrc_path = None\n \n for f in netrc_locations:\n- try:\n- loc = os.path.expanduser(f)\n- except KeyError:\n- # os.path.expanduser can fail when $HOME is undefined and\n- # getpwuid fails. See https://bugs.python.org/issue20164 &\n- # https://github.com/psf/requests/issues/1846\n- return\n-\n+ loc = os.path.expanduser(f)\n if os.path.exists(loc):\n netrc_path = loc\n break" }, { "filename": "tests/test_utils.py", "status": "modified", "additions": 19, "deletions": 0, "changes": 19, "patch": "@@ -23,6 +23,7 @@\n get_encoding_from_headers,\n get_encodings_from_content,\n get_environ_proxies,\n+ get_netrc_auth,\n guess_filename,\n guess_json_utf,\n is_ipv4_address,\n@@ -152,6 +153,24 @@ def test_super_len_with_no_matches(self):\n assert super_len(object()) == 0\n \n \n+class TestGetNetrcAuth:\n+ def test_works(self, tmp_path, monkeypatch):\n+ netrc_path = tmp_path / \".netrc\"\n+ monkeypatch.setenv(\"NETRC\", str(netrc_path))\n+ with open(netrc_path, \"w\") as f:\n+ f.write(\"machine example.com login aaaa password bbbb\\n\")\n+ auth = get_netrc_auth(\"http://example.com/thing\")\n+ assert auth == (\"aaaa\", \"bbbb\")\n+\n+ def test_not_vulnerable_to_bad_url_parsing(self, tmp_path, monkeypatch):\n+ netrc_path = tmp_path / \".netrc\"\n+ monkeypatch.setenv(\"NETRC\", str(netrc_path))\n+ with open(netrc_path, \"w\") as f:\n+ f.write(\"machine example.com login aaaa password bbbb\\n\")\n+ auth = get_netrc_auth(\"http://example.com:[USER_REDACTED].com/'\")\n+ assert auth is None\n+\n+\n class TestToKeyValList:\n [USER_REDACTED].mark.parametrize(\n \"value, expected\"," } ], "reviews": [ { "id": 2899123279, "user": "user_b94daa584f46", "state": "COMMENTED", "body": "About the test, I created another test for the same issue in a [different PR](https://github.com/psf/requests/pull/6962/). So at this point, the issue is fixed and it could be nice to have a test for this case, I'm okay to close my PR if this test is good enough, or keep it if maintainers are okay to have two tests for this case.", "submitted_at": "2025-06-05T07:17:48+00:00" }, { "id": 2900241034, "user": "user_0fa58b6f3572", "state": "APPROVED", "body": null, "submitted_at": "2025-06-05T13:00:47+00:00" } ], "review_comments": [ { "id": 2128118428, "user": "user_b94daa584f46", "body": "This is fixed now in main: https://github.com/psf/requests/commit/96ba401c1296ab1dda74a2365ef36d88f7d144ef", "path": "src/requests/utils.py", "line": null, "side": "RIGHT", "created_at": "2025-06-05T07:12:17+00:00" } ], "meta": { "languages": [ "py" ], "touches_tests": true, "review_state_summary": { "COMMENTED": 1, "APPROVED": 1 }, "meaningful_comment_count": 1, "has_approval": true, "has_changes_requested": false, "total_review_comments": 1 } } { "_id": "0c69e1dbe0a5b84e", "_schema_version": "1.0", "_cleaned_at": "2026-02-12T07:46:51.378696+00:00", "repo": "psf/requests", "repo_url": "https://github.com/psf/requests", "license_name": "Apache License 2.0", "license_spdx": "Apache-2.0", "pr_number": 6951, "title": "docs: fix dead links to kenreitz.org", "body": "I noticed a few dead links. Looking back through the [wayback machine](https://web.archive.org/web/20220203091232/https://kenreitz.org/essays/2012/06/14/the-future-of-python-http), I was able to find the new location of these articles.", "author": "user_4759e575a3d3", "created_at": "2025-05-21T16:11:00+00:00", "merged_at": "2025-06-01T18:07:18+00:00", "base_branch": "main", "head_branch": "patch-1", "additions": 13, "deletions": 18, "changed_files": 3, "files": [ { "filename": "docs/conf.py", "status": "modified", "additions": 1, "deletions": 1, "changes": 2, "patch": "@@ -58,7 +58,7 @@\n \n # General information about the project.\n project = u\"Requests\"\n-copyright = u'MMXVIX. A [NAME_REDACTED] Project'\n+copyright = u'MMXVIX. A [NAME_REDACTED]'\n author = u\"[NAME_REDACTED]\"\n \n # The version info for the project you're documenting, acts as replacement for" }, { "filename": "docs/dev/contributing.rst", "status": "modified", "additions": 9, "deletions": 11, "changes": 20, "patch": "@@ -22,19 +22,17 @@ The guide is split into sections based on the type of contribution you're\n thinking of making, with a section that covers general guidelines for all\n contributors.\n \n-[NAME_REDACTED]\n-----------\n+Code of Conduct\n+---------------\n \n- **Be cordial or be on your way**. *—[NAME_REDACTED]*\n+The Python community is made up of members from around the globe with a diverse\n+set of skills, personalities, and experiences. It is through these differences\n+that our community experiences great successes and continued growth. When you're\n+working with members of the community, follow the\n+`[NAME_REDACTED] Code of Conduct`_ to help steer your interactions\n+and keep Python a positive, successful, and growing community.\n \n-Requests has one very important rule governing all forms of contribution,\n-including reporting bugs or requesting features. This golden rule is\n-\"`be cordial or be on your way`_\".\n-\n-**All contributions are welcome**, as long as\n-everyone involved is treated with respect.\n-\n-.. _be cordial or be on your way: https://kenreitz.org/essays/2013/01/27/be-cordial-or-be-on-your-way\n+.. _Python [NAME_REDACTED] of Conduct: https://policies.python.org/python.org/code-of-conduct/\n \n .. _early-feedback:" }, { "filename": "docs/user/advanced.rst", "status": "modified", "additions": 3, "deletions": 6, "changes": 9, "patch": "@@ -969,11 +969,9 @@ Requests will automatically parse these link headers and make them easily consum\n [NAME_REDACTED]\n ------------------\n \n-As of v1.0.0, Requests has moved to a modular internal design. Part of the\n-reason this was done was to implement [NAME_REDACTED], originally\n-`described here`_. [NAME_REDACTED] provide a mechanism to define interaction\n-methods for an HTTP service. In particular, they allow you to apply per-service\n-configuration.\n+As of v1.0.0, Requests has moved to a modular internal design using Transport\n+Adapters. These objects provide a mechanism to define interaction methods for an\n+HTTP service. In particular, they allow you to apply per-service configuration.\n \n Requests ships with a single [NAME_REDACTED], the :class:`HTTPAdapter\n `. This adapter provides the default Requests\n@@ -1053,7 +1051,6 @@ backoff, within a Requests :class:`Session ` using the\n )\n s.mount('https://', HTTPAdapter(max_retries=retries))\n \n-.. _`described here`: https://kenreitz.org/essays/2012/06/14/the-future-of-python-http\n .. _`urllib3`: https://github.com/urllib3/urllib3\n .. _`urllib3.util.Retry`: https://urllib3.readthedocs.io/en/stable/reference/urllib3.util.html#urllib3.util.Retry" } ], "reviews": [ { "id": 2858933976, "user": "user_dbf2a999bd6d", "state": "COMMENTED", "body": "At this point I'd prefer we just remove these links. We get PRs every few years whenever the domain changes.", "submitted_at": "2025-05-30T20:21:09+00:00" }, { "id": 2885730837, "user": "user_0fa58b6f3572", "state": "APPROVED", "body": null, "submitted_at": "2025-06-01T14:53:49+00:00" }, { "id": 2885894125, "user": "user_dbf2a999bd6d", "state": "APPROVED", "body": null, "submitted_at": "2025-06-01T18:06:54+00:00" } ], "review_comments": [ { "id": 2101041830, "user": "user_dbf2a999bd6d", "body": "```suggestion\ncopyright = u'MMXVIX. A [NAME_REDACTED]'\n```", "path": "docs/conf.py", "line": null, "side": "RIGHT", "created_at": "2025-05-21T19:45:04+00:00" } ], "meta": { "languages": [ "py", "rst" ], "touches_tests": false, "review_state_summary": { "COMMENTED": 1, "APPROVED": 2 }, "meaningful_comment_count": 1, "has_approval": true, "has_changes_requested": false, "total_review_comments": 1 } } { "_id": "03198075bb0d5124", "_schema_version": "1.0", "_cleaned_at": "2026-02-12T07:46:51.378696+00:00", "repo": "psf/requests", "repo_url": "https://github.com/psf/requests", "license_name": "Apache License 2.0", "license_spdx": "Apache-2.0", "pr_number": 6876, "title": "Add netrc file search information to authentication documentation", "body": "Added paragraph (copied from `quickstart.rst`) with information where Requests search for `.netrc` file.\n\nIt should make it easier to find this information when somebody reads regular documentation (as opposite to quickstart documentation).", "author": "user_bce9f40bbd56", "created_at": "2025-01-27T20:57:34+00:00", "merged_at": "2025-06-08T17:47:56+00:00", "base_branch": "main", "head_branch": "main", "additions": 11, "deletions": 0, "changed_files": 2, "files": [ { "filename": "docs/user/authentication.rst", "status": "modified", "additions": 10, "deletions": 0, "changes": 10, "patch": "@@ -44,6 +44,16 @@ set with `headers=`.\n If credentials for the hostname are found, the request is sent with HTTP [NAME_REDACTED].\n \n+Requests will search for the netrc file at `~/.netrc`, `~/_netrc`, or at the path\n+specified by the `NETRC` environment variable. `~` denotes the user's home\n+directory, which is `$HOME` on Unix based systems and `%USERPROFILE%` on Windows.\n+\n+Usage of netrc file can be disabled by setting `trust_env` to `False` in the\n+Requests session::\n+\n+ >>> s = requests.Session()\n+ >>> s.trust_env = False\n+ >>> s.get('https://httpbin.org/basic-auth/user/pass')\n \n [NAME_REDACTED]\n ---------------------" }, { "filename": "docs/user/quickstart.rst", "status": "modified", "additions": 1, "deletions": 0, "changes": 1, "patch": "@@ -222,6 +222,7 @@ Note: Custom headers are given less precedence than more specific sources of inf\n are specified in ``.netrc``, which in turn will be overridden by the ``auth=``\n parameter. Requests will search for the netrc file at `~/.netrc`, `~/_netrc`,\n or at the path specified by the `NETRC` environment variable.\n+ Check details in :ref:`netrc authentication `.\n * Authorization headers will be removed if you get redirected off-host.\n * Proxy-Authorization headers will be overridden by [NAME_REDACTED] the URL.\n * Content-Length headers will be overridden when we can determine the length of the content." } ], "reviews": [ { "id": 2576791060, "user": "user_0fa58b6f3572", "state": "CHANGES_REQUESTED", "body": null, "submitted_at": "2025-01-27T23:56:26+00:00" }, { "id": 2579164936, "user": "user_bce9f40bbd56", "state": "COMMENTED", "body": null, "submitted_at": "2025-01-28T18:56:49+00:00" }, { "id": 2588345952, "user": "user_0fa58b6f3572", "state": "COMMENTED", "body": null, "submitted_at": "2025-02-01T14:24:13+00:00" }, { "id": 2588413785, "user": "user_bce9f40bbd56", "state": "COMMENTED", "body": null, "submitted_at": "2025-02-01T21:39:19+00:00" }, { "id": 2908591702, "user": "user_0fa58b6f3572", "state": "APPROVED", "body": null, "submitted_at": "2025-06-08T17:47:49+00:00" } ], "review_comments": [ { "id": 1931340274, "user": "user_0fa58b6f3572", "body": "This doesn't list the Windows paths or how to disable this altogether.", "path": "docs/user/authentication.rst", "line": 47, "side": "RIGHT", "created_at": "2025-01-27T23:56:20+00:00" }, { "id": 1932704347, "user": "user_bce9f40bbd56", "body": "[USER_REDACTED] please check updated commit.", "path": "docs/user/authentication.rst", "line": 47, "side": "RIGHT", "created_at": "2025-01-28T18:56:49+00:00" }, { "id": 1938283997, "user": "user_0fa58b6f3572", "body": "This is not at all what I meant.\n\n`trust_env=False` is the Requests mechanism for overriding this behaviour.\n\nThis may also work, but telling folks to use `/dev/null` I believe causes pathological behaviour on some versions of Python today.", "path": "docs/user/authentication.rst", "line": null, "side": "RIGHT", "created_at": "2025-02-01T14:24:12+00:00" }, { "id": 1938350825, "user": "user_bce9f40bbd56", "body": "I'm coming from Linux world where `/dev/null` is very respected thing 😄 \n\nI pushed new commit - I hope it looks better now.", "path": "docs/user/authentication.rst", "line": null, "side": "RIGHT", "created_at": "2025-02-01T21:39:18+00:00" } ], "meta": { "languages": [ "rst" ], "touches_tests": false, "review_state_summary": { "CHANGES_REQUESTED": 1, "COMMENTED": 3, "APPROVED": 1 }, "meaningful_comment_count": 4, "has_approval": true, "has_changes_requested": true, "total_review_comments": 4 } } { "_id": "c9a211c62ed85a9f", "_schema_version": "1.0", "_cleaned_at": "2026-02-12T07:46:51.378696+00:00", "repo": "psf/requests", "repo_url": "https://github.com/psf/requests", "license_name": "Apache License 2.0", "license_spdx": "Apache-2.0", "pr_number": 6802, "title": "start testing on 3.13rc", "body": null, "author": "user_43e0ee7d352e", "created_at": "2024-09-18T14:05:21+00:00", "merged_at": "2024-09-19T11:19:03+00:00", "base_branch": "main", "head_branch": "3.13", "additions": 6, "deletions": 4, "changed_files": 4, "files": [ { "filename": ".github/workflows/run-tests.yml", "status": "modified", "additions": 2, "deletions": 1, "changes": 3, "patch": "@@ -12,7 +12,7 @@ jobs:\n strategy:\n fail-fast: false\n matrix:\n- python-version: [\"3.8\", \"3.9\", \"3.10\", \"3.11\", \"3.12\", \"pypy-3.9\", \"pypy-3.10\"]\n+ python-version: [\"3.8\", \"3.9\", \"3.10\", \"3.11\", \"3.12\", \"3.13\", \"pypy-3.9\", \"pypy-3.10\"]\n os: [ubuntu-22.04, macOS-latest, windows-latest]\n # Python 3.8 and 3.9 do not run on macOS-latest which\n # is now using arm64 hardware.\n@@ -31,6 +31,7 @@ jobs:\n with:\n python-version: ${{ matrix.python-version }}\n cache: 'pip'\n+ allow-prereleases: true\n - name: Install dependencies\n run: |\n make" }, { "filename": "requirements-dev.txt", "status": "modified", "additions": 1, "deletions": 1, "changes": 2, "patch": "@@ -1,7 +1,7 @@\n -e .[socks]\n pytest>=2.8.0,<9\n pytest-cov\n-pytest-httpbin==2.0.0\n+pytest-httpbin==2.1.0\n httpbin~=0.10.0\n trustme\n wheel" }, { "filename": "setup.py", "status": "modified", "additions": 2, "deletions": 1, "changes": 3, "patch": "@@ -40,7 +40,7 @@\n \"certifi>=2017.4.17\",\n ]\n test_requirements = [\n- \"pytest-httpbin==2.0.0\",\n+ \"pytest-httpbin==2.1.0\",\n \"pytest-cov\",\n \"pytest-mock\",\n \"pytest-xdist\",\n@@ -87,6 +87,7 @@\n \"[NAME_REDACTED] :: Python :: 3.10\",\n \"[NAME_REDACTED] :: Python :: 3.11\",\n \"[NAME_REDACTED] :: Python :: 3.12\",\n+ \"[NAME_REDACTED] :: Python :: 3.13\",\n \"[NAME_REDACTED] :: Python :: 3 :: Only\",\n \"[NAME_REDACTED] :: Python :: Implementation :: CPython\",\n \"[NAME_REDACTED] :: Python :: Implementation :: PyPy\"," }, { "filename": "tox.ini", "status": "modified", "additions": 1, "deletions": 1, "changes": 2, "patch": "@@ -1,5 +1,5 @@\n [tox]\n-envlist = py{38,39,310,311,312}-{default, use_chardet_on_py3}\n+envlist = py{38,39,310,311,312,313}-{default, use_chardet_on_py3}\n \n [testenv]\n deps = -rrequirements-dev.txt" } ], "reviews": [ { "id": 2313094592, "user": "user_43e0ee7d352e", "state": "COMMENTED", "body": null, "submitted_at": "2024-09-18T15:36:17+00:00" }, { "id": 2313094844, "user": "user_43e0ee7d352e", "state": "COMMENTED", "body": null, "submitted_at": "2024-09-18T15:36:24+00:00" }, { "id": 2313379055, "user": "user_dbf2a999bd6d", "state": "COMMENTED", "body": null, "submitted_at": "2024-09-18T17:50:26+00:00" }, { "id": 2313421466, "user": "user_43e0ee7d352e", "state": "COMMENTED", "body": null, "submitted_at": "2024-09-18T18:11:52+00:00" }, { "id": 2313481566, "user": "user_dbf2a999bd6d", "state": "CHANGES_REQUESTED", "body": "I think we're also missing an update for the [`tox`](https://github.com/psf/requests/blob/f12ccbef6d6b95564da8d22e280d28c39d53f0e9/tox.ini#L2) file.", "submitted_at": "2024-09-18T18:35:34+00:00" }, { "id": 2313495230, "user": "user_dbf2a999bd6d", "state": "APPROVED", "body": null, "submitted_at": "2024-09-18T18:41:09+00:00" }, { "id": 2315230566, "user": "user_0fa58b6f3572", "state": "APPROVED", "body": null, "submitted_at": "2024-09-19T11:18:58+00:00" } ], "review_comments": [ { "id": 1765295100, "user": "user_43e0ee7d352e", "body": "```suggestion\npytest-httpbin==2.1.0\n```", "path": "requirements-dev.txt", "line": null, "side": "RIGHT", "created_at": "2024-09-18T15:36:17+00:00" }, { "id": 1765295244, "user": "user_43e0ee7d352e", "body": "```suggestion\n \"pytest-httpbin==2.1.0\",\n```", "path": "setup.py", "line": null, "side": "RIGHT", "created_at": "2024-09-18T15:36:24+00:00" }, { "id": 1765474720, "user": "user_dbf2a999bd6d", "body": "Do we still need this or can it be removed now that `pytest-httpbin` is fully released?", "path": ".github/workflows/run-tests.yml", "line": 34, "side": "RIGHT", "created_at": "2024-09-18T17:50:26+00:00" }, { "id": 1765499793, "user": "user_43e0ee7d352e", "body": "This is needed for 3.13rc. it doesn't effect pip installs", "path": ".github/workflows/run-tests.yml", "line": 34, "side": "RIGHT", "created_at": "2024-09-18T18:11:52+00:00" } ], "meta": { "languages": [ "ini", "py", "txt", "yml" ], "touches_tests": false, "review_state_summary": { "COMMENTED": 4, "CHANGES_REQUESTED": 1, "APPROVED": 2 }, "meaningful_comment_count": 4, "has_approval": true, "has_changes_requested": true, "total_review_comments": 4 } } { "_id": "02ef1a7c4086687a", "_schema_version": "1.0", "_cleaned_at": "2026-02-12T07:46:51.378696+00:00", "repo": "psf/requests", "repo_url": "https://github.com/psf/requests", "license_name": "Apache License 2.0", "license_spdx": "Apache-2.0", "pr_number": 6767, "title": "Revert caching a default SSLContext", "body": "This PR reverts the changes from #6667 to the previous behavior. Due to the number of edge cases and concurrency issues we've encountered with this change, we've decided the benefit doesn't currently outweigh the pain to existing infrastructure. We've iterated on a few tries to keep this functionality in place, but are still receiving reports of novel issues with this behavior.\n\nWe may be able to revisit this in a later version of Requests but we'll need a much more comprehensive test plan.", "author": "user_dbf2a999bd6d", "created_at": "2024-07-18T18:00:33+00:00", "merged_at": "2025-06-13T16:42:08+00:00", "base_branch": "main", "head_branch": "remove_cached_sslcontext", "additions": 16, "deletions": 39, "changed_files": 1, "files": [ { "filename": "src/requests/adapters.py", "status": "modified", "additions": 16, "deletions": 39, "changes": 55, "patch": "@@ -27,7 +27,6 @@\n from urllib3.util import Timeout as TimeoutSauce\n from urllib3.util import parse_url\n from urllib3.util.retry import Retry\n-from urllib3.util.ssl_ import create_urllib3_context\n \n from .auth import _basic_auth_str\n from .compat import basestring, urlparse\n@@ -74,19 +73,6 @@ def SOCKSProxyManager(*args, **kwargs):\n DEFAULT_POOL_TIMEOUT = None\n \n \n-try:\n- import ssl # noqa: F401\n-\n- _preloaded_ssl_context = create_urllib3_context()\n- _preloaded_ssl_context.load_verify_locations(\n- extract_zipped_paths(DEFAULT_CA_BUNDLE_PATH)\n- )\n-except ImportError:\n- # Bypass default SSLContext creation when Python\n- # interpreter isn't built with the ssl module.\n- _preloaded_ssl_context = None\n-\n-\n def _urllib3_request_context(\n request: \"PreparedRequest\",\n verify: \"bool | str | None\",\n@@ -99,19 +85,9 @@ def _urllib3_request_context(\n scheme = parsed_request_url.scheme.lower()\n port = parsed_request_url.port\n \n- # Determine if we have and should use our default SSLContext\n- # to optimize performance on standard requests.\n- poolmanager_kwargs = getattr(poolmanager, \"connection_pool_kw\", {})\n- has_poolmanager_ssl_context = poolmanager_kwargs.get(\"ssl_context\")\n- should_use_default_ssl_context = (\n- _preloaded_ssl_context is not None and not has_poolmanager_ssl_context\n- )\n-\n cert_reqs = \"CERT_REQUIRED\"\n if verify is False:\n cert_reqs = \"CERT_NONE\"\n- elif verify is True and should_use_default_ssl_context:\n- pool_kwargs[\"ssl_context\"] = _preloaded_ssl_context\n elif isinstance(verify, str):\n if not os.path.isdir(verify):\n pool_kwargs[\"ca_certs\"] = verify\n@@ -314,26 +290,27 @@ def cert_verify(self, conn, url, verify, cert):\n :param cert: The SSL certificate to verify.\n \"\"\"\n if url.lower().startswith(\"https\") and verify:\n- conn.cert_reqs = \"CERT_REQUIRED\"\n+ cert_loc = None\n \n- # Only load the CA certificates if 'verify' is a string indicating the CA bundle to use.\n- # Otherwise, if verify is a boolean, we don't load anything since\n- # the connection will be using a context with the default certificates already loaded,\n- # and this avoids a call to the slow load_verify_locations()\n+ # Allow self-specified cert location.\n if verify is not True:\n- # `verify` must be a str with a path then\n cert_loc = verify\n \n- if not os.path.exists(cert_loc):\n- raise OSError(\n- f\"Could not find a suitable TLS CA certificate bundle, \"\n- f\"invalid path: {cert_loc}\"\n- )\n+ if not cert_loc:\n+ cert_loc = extract_zipped_paths(DEFAULT_CA_BUNDLE_PATH)\n \n- if not os.path.isdir(cert_loc):\n- conn.ca_certs = cert_loc\n- else:\n- conn.ca_cert_dir = cert_loc\n+ if not cert_loc or not os.path.exists(cert_loc):\n+ raise OSError(\n+ f\"Could not find a suitable TLS CA certificate bundle, \"\n+ f\"invalid path: {cert_loc}\"\n+ )\n+\n+ conn.cert_reqs = \"CERT_REQUIRED\"\n+\n+ if not os.path.isdir(cert_loc):\n+ conn.ca_certs = cert_loc\n+ else:\n+ conn.ca_cert_dir = cert_loc\n else:\n conn.cert_reqs = \"CERT_NONE\"\n conn.ca_certs = None" } ], "reviews": [ { "id": 2186534311, "user": "user_dbf2a999bd6d", "state": "COMMENTED", "body": null, "submitted_at": "2024-07-18T18:02:54+00:00" }, { "id": 2887963612, "user": "user_0fa58b6f3572", "state": "APPROVED", "body": null, "submitted_at": "2025-06-02T11:30:11+00:00" } ], "review_comments": [ { "id": 1683276287, "user": "user_dbf2a999bd6d", "body": "This is one piece I left in place from #6667. We were unilaterally considering any `verify` string to be `ca_certs` instead of detecting if it was a directory. That seems like a miss from #6655 unless I'm missing something?", "path": "src/requests/adapters.py", "line": 92, "side": "RIGHT", "created_at": "2024-07-18T18:02:54+00:00" } ], "meta": { "languages": [ "py" ], "touches_tests": false, "review_state_summary": { "COMMENTED": 1, "APPROVED": 1 }, "meaningful_comment_count": 1, "has_approval": true, "has_changes_requested": false, "total_review_comments": 1 } } { "_id": "d3dbe5decf31f69c", "_schema_version": "1.0", "_cleaned_at": "2026-02-12T07:46:51.378696+00:00", "repo": "psf/requests", "repo_url": "https://github.com/psf/requests", "license_name": "Apache License 2.0", "license_spdx": "Apache-2.0", "pr_number": 6757, "title": "Test on urllib3 1.26.x", "body": "First step to address #6734. We'll enable testing on urllib3 1.26.x which was lost when we moved the pin to support 2.x. These will fail for now until the underlying issue is addressed, but this is to ensure we're catching any future breakages.", "author": "user_dbf2a999bd6d", "created_at": "2024-07-02T01:11:04+00:00", "merged_at": "2024-07-30T01:44:14+00:00", "base_branch": "main", "head_branch": "urllib-1.x-tests", "additions": 60, "deletions": 18, "changed_files": 4, "files": [ { "filename": ".github/workflows/run-tests.yml", "status": "modified", "additions": 20, "deletions": 0, "changes": 20, "patch": "@@ -57,3 +57,23 @@ jobs:\n - name: Run tests\n run: |\n make ci\n+\n+ urllib3:\n+ name: 'urllib3 1.x'\n+ runs-on: 'ubuntu-latest'\n+ strategy:\n+ fail-fast: true\n+\n+ steps:\n+ - uses: actions/checkout@8ade135a41bc03ea155e62e844d188df1ea18608\n+ - name: 'Set up Python 3.8'\n+ uses: actions/setup-python@82c7e631bb3cdc910f68e0081d67478d79c6982d\n+ with:\n+ python-version: '3.8'\n+ - name: Install dependencies\n+ run: |\n+ make\n+ python -m pip install \"urllib3<2\"\n+ - name: Run tests\n+ run: |\n+ make ci" }, { "filename": "src/requests/compat.py", "status": "modified", "additions": 12, "deletions": 0, "changes": 12, "patch": "@@ -10,6 +10,18 @@\n import importlib\n import sys\n \n+# -------\n+# urllib3\n+# -------\n+from urllib3 import __version__ as urllib3_version\n+\n+# Detect which major version of urllib3 is being used.\n+try:\n+ is_urllib3_1 = int(urllib3_version.split(\".\")[0]) == 1\n+except (TypeError, AttributeError):\n+ # If we can't discern a version, prefer old functionality.\n+ is_urllib3_1 = True\n+\n # -------------------\n # [NAME_REDACTED]\n # -------------------" }, { "filename": "src/requests/utils.py", "status": "modified", "additions": 4, "deletions": 1, "changes": 5, "patch": "@@ -38,6 +38,7 @@\n getproxies,\n getproxies_environment,\n integer_types,\n+ is_urllib3_1,\n )\n from .compat import parse_http_list as _parse_list_header\n from .compat import (\n@@ -136,7 +137,9 @@ def super_len(o):\n total_length = None\n current_position = 0\n \n- if isinstance(o, str):\n+ if not is_urllib3_1 and isinstance(o, str):\n+ # urllib3 2.x+ treats all strings as utf-8 instead\n+ # of latin-1 (iso-8859-1) like http.client.\n o = o.encode(\"utf-8\")\n \n if hasattr(o, \"__len__\"):" }, { "filename": "tests/test_requests.py", "status": "modified", "additions": 24, "deletions": 17, "changes": 41, "patch": "@@ -25,6 +25,7 @@\n builtin_str,\n cookielib,\n getproxies,\n+ is_urllib3_1,\n urlparse,\n )\n from requests.cookies import cookiejar_from_dict, morsel_to_cookie\n@@ -1810,23 +1811,6 @@ def test_autoset_header_values_are_native(self, httpbin):\n \n assert p.headers[\"Content-Length\"] == length\n \n- def test_content_length_for_bytes_data(self, httpbin):\n- data = \"This is a string containing multi-byte UTF-8 ☃️\"\n- encoded_data = data.encode(\"utf-8\")\n- length = str(len(encoded_data))\n- req = requests.Request(\"POST\", httpbin(\"post\"), data=encoded_data)\n- p = req.prepare()\n-\n- assert p.headers[\"Content-Length\"] == length\n-\n- def test_content_length_for_string_data_counts_bytes(self, httpbin):\n- data = \"This is a string containing multi-byte UTF-8 ☃️\"\n- length = str(len(data.encode(\"utf-8\")))\n- req = requests.Request(\"POST\", httpbin(\"post\"), data=data)\n- p = req.prepare()\n-\n- assert p.headers[\"Content-Length\"] == length\n-\n def test_nonhttp_schemes_dont_check_URLs(self):\n test_urls = (\n \"data:image/gif;base64,R0lGODlhAQABAHAAACH5BAUAAAAALAAAAAABAAEAAAICRAEAOw==\",\n@@ -2966,6 +2950,29 @@ def response_handler(sock):\n assert client_cert is not None\n \n \n+def test_content_length_for_bytes_data(httpbin):\n+ data = \"This is a string containing multi-byte UTF-8 ☃️\"\n+ encoded_data = data.encode(\"utf-8\")\n+ length = str(len(encoded_data))\n+ req = requests.Request(\"POST\", httpbin(\"post\"), data=encoded_data)\n+ p = req.prepare()\n+\n+ assert p.headers[\"Content-Length\"] == length\n+\n+\n+[USER_REDACTED].mark.skipif(\n+ is_urllib3_1,\n+ reason=\"urllib3 2.x encodes all strings to utf-8, urllib3 1.x uses latin-1\",\n+)\n+def test_content_length_for_string_data_counts_bytes(httpbin):\n+ data = \"This is a string containing multi-byte UTF-8 ☃️\"\n+ length = str(len(data.encode(\"utf-8\")))\n+ req = requests.Request(\"POST\", httpbin(\"post\"), data=data)\n+ p = req.prepare()\n+\n+ assert p.headers[\"Content-Length\"] == length\n+\n+\n def test_json_decode_errors_are_serializable_deserializable():\n json_decode_error = requests.exceptions.JSONDecodeError(\n \"Extra data\"," } ], "reviews": [ { "id": 2152480764, "user": "user_b08fb5f52ea1", "state": "APPROVED", "body": "LGTM! Thanks for testing urllib3 :)", "submitted_at": "2024-07-02T01:16:19+00:00" }, { "id": 2153790038, "user": "user_0fa58b6f3572", "state": "APPROVED", "body": null, "submitted_at": "2024-07-02T13:20:47+00:00" }, { "id": 2186404336, "user": "user_b08fb5f52ea1", "state": "COMMENTED", "body": null, "submitted_at": "2024-07-18T16:49:44+00:00" }, { "id": 2186420534, "user": "user_dbf2a999bd6d", "state": "COMMENTED", "body": null, "submitted_at": "2024-07-18T16:58:58+00:00" }, { "id": 2205199013, "user": "user_dbf2a999bd6d", "state": "COMMENTED", "body": null, "submitted_at": "2024-07-29T14:49:41+00:00" }, { "id": 2206392532, "user": "user_0fa58b6f3572", "state": "APPROVED", "body": null, "submitted_at": "2024-07-30T01:16:53+00:00" } ], "review_comments": [ { "id": 1683193453, "user": "user_b08fb5f52ea1", "body": "I believe this is a string, not an integer. Also, should do a >= check instead of equals.", "path": "src/requests/compat.py", "line": null, "side": "RIGHT", "created_at": "2024-07-18T16:49:44+00:00" }, { "id": 1683204168, "user": "user_dbf2a999bd6d", "body": "Good catch on the `int`. For the equivalence, I don't know if `>=` is what we want if this is specifically scoping the 2.x major version. In the same way I wouldn't want an `is_py3` to include Python 4.x. We could do something like `is_gt_urllib3_1` but that seems like it may be premature forwards-compatibility?\n\nRight now our dependencies are scoped at `urllib3<3` and if we add this check to any other behaviors, I'd rather they stay scoped to the major version. That will let tests fail if we major version again and we can make an informed decision at that point when adding support. Otherwise, we may unintentionally carry forward behaviors that are subtly wrong.\n\nI can see similar risks with both sides, so not a hill I'm going to die on, but that was my initial thought process.", "path": "src/requests/compat.py", "line": null, "side": "RIGHT", "created_at": "2024-07-18T16:58:58+00:00" }, { "id": 1695374605, "user": "user_dbf2a999bd6d", "body": "I've changed the check from checking for urllib3 2.x to check for 1.x. That leaves us open to forward compatibility without the confusing behavior with `is_urllib3_2` including newer major versions.", "path": "src/requests/compat.py", "line": null, "side": "RIGHT", "created_at": "2024-07-29T14:49:41+00:00" } ], "meta": { "languages": [ "py", "yml" ], "touches_tests": true, "review_state_summary": { "APPROVED": 3, "COMMENTED": 3 }, "meaningful_comment_count": 3, "has_approval": true, "has_changes_requested": false, "total_review_comments": 3 } } { "_id": "c209700120bc5bb8", "_schema_version": "1.0", "_cleaned_at": "2026-02-12T07:46:51.378696+00:00", "repo": "psf/requests", "repo_url": "https://github.com/psf/requests", "license_name": "Apache License 2.0", "license_spdx": "Apache-2.0", "pr_number": 6724, "title": "Don't create default SSLContext if ssl module isn't present", "body": "This PR is to address a [recent regression in Emscripten support for urllib3](https://github.com/urllib3/urllib3/actions/runs/9253144050/job/25452248794). We began unilaterally creating an SSLContext without consideration for Python versions built without an ssl module. This is handled in urllib3 but missed in our usage of `create_urllib3_context`.\n\nThis PR expands on the fix in #6716 by [NAME_REDACTED] presence of the `ssl` module before creating and setting the default SSLContext.", "author": "user_dbf2a999bd6d", "created_at": "2024-05-28T19:34:27+00:00", "merged_at": "2024-05-29T15:23:40+00:00", "base_branch": "main", "head_branch": "ssl_optimization", "additions": 19, "deletions": 5, "changed_files": 1, "files": [ { "filename": "src/requests/adapters.py", "status": "modified", "additions": 19, "deletions": 5, "changes": 24, "patch": "@@ -73,10 +73,18 @@ def SOCKSProxyManager(*args, **kwargs):\n DEFAULT_RETRIES = 0\n DEFAULT_POOL_TIMEOUT = None\n \n-_preloaded_ssl_context = create_urllib3_context()\n-_preloaded_ssl_context.load_verify_locations(\n- extract_zipped_paths(DEFAULT_CA_BUNDLE_PATH)\n-)\n+\n+try:\n+ import ssl # noqa: F401\n+\n+ _preloaded_ssl_context = create_urllib3_context()\n+ _preloaded_ssl_context.load_verify_locations(\n+ extract_zipped_paths(DEFAULT_CA_BUNDLE_PATH)\n+ )\n+except ImportError:\n+ # Bypass default SSLContext creation when Python\n+ # interpreter isn't built with the ssl module.\n+ _preloaded_ssl_context = None\n \n \n def _urllib3_request_context(\n@@ -90,13 +98,19 @@ def _urllib3_request_context(\n parsed_request_url = urlparse(request.url)\n scheme = parsed_request_url.scheme.lower()\n port = parsed_request_url.port\n+\n+ # Determine if we have and should use our default SSLContext\n+ # to optimize performance on standard requests.\n poolmanager_kwargs = getattr(poolmanager, \"connection_pool_kw\", {})\n has_poolmanager_ssl_context = poolmanager_kwargs.get(\"ssl_context\")\n+ should_use_default_ssl_context = (\n+ _preloaded_ssl_context is not None and not has_poolmanager_ssl_context\n+ )\n \n cert_reqs = \"CERT_REQUIRED\"\n if verify is False:\n cert_reqs = \"CERT_NONE\"\n- elif verify is True and not has_poolmanager_ssl_context:\n+ elif verify is True and should_use_default_ssl_context:\n pool_kwargs[\"ssl_context\"] = _preloaded_ssl_context\n elif isinstance(verify, str):\n if not os.path.isdir(verify):" } ], "reviews": [ { "id": 2083791089, "user": "user_0fa58b6f3572", "state": "COMMENTED", "body": null, "submitted_at": "2024-05-28T21:17:07+00:00" }, { "id": 2083948577, "user": "user_dbf2a999bd6d", "state": "COMMENTED", "body": null, "submitted_at": "2024-05-28T22:28:51+00:00" }, { "id": 2084021685, "user": "user_0fa58b6f3572", "state": "COMMENTED", "body": null, "submitted_at": "2024-05-28T23:58:30+00:00" }, { "id": 2084021778, "user": "user_0fa58b6f3572", "state": "APPROVED", "body": null, "submitted_at": "2024-05-28T23:58:37+00:00" }, { "id": 2084022830, "user": "user_dbf2a999bd6d", "state": "COMMENTED", "body": null, "submitted_at": "2024-05-29T00:00:07+00:00" }, { "id": 2085603226, "user": "user_0fa58b6f3572", "state": "APPROVED", "body": null, "submitted_at": "2024-05-29T14:32:43+00:00" }, { "id": 2085739900, "user": "user_dbf2a999bd6d", "state": "COMMENTED", "body": null, "submitted_at": "2024-05-29T15:23:20+00:00" }, { "id": 2411765982, "user": "user_adf270769e63", "state": "COMMENTED", "body": "Rerun have timestamp", "submitted_at": "2024-11-03T01:40:09+00:00" } ], "review_comments": [ { "id": 1617854876, "user": "user_0fa58b6f3572", "body": "Missed this earlier but do we need any logic for verify=True without a condition here?", "path": "src/requests/adapters.py", "line": 113, "side": "RIGHT", "created_at": "2024-05-28T20:27:08+00:00" }, { "id": 1617955993, "user": "user_dbf2a999bd6d", "body": "Are you asking about the behavior if `verify is True` but `should_use_default_ssl_context` is False? This was a no-op prior to #6655 which fellback to letting the SSLContext be created when fetching the connection from the pool. [`_ssl_wrap_socket_and_match_hostname`](https://github.com/urllib3/urllib3/blob/b07a669bd970d69847801148286b726f0570b625/src/urllib3/connection.py#L755-L765) handles this for us, so I don't know if there's any additional concern from our previous behavior unless I'm missing part of the question.", "path": "src/requests/adapters.py", "line": 113, "side": "RIGHT", "created_at": "2024-05-28T22:28:51+00:00" }, { "id": 1618008653, "user": "user_0fa58b6f3572", "body": "Makes sense. I've a terrible headache so just looking at the branches and concerned about missing something is all.", "path": "src/requests/adapters.py", "line": 113, "side": "RIGHT", "created_at": "2024-05-28T23:58:29+00:00" }, { "id": 1618009506, "user": "user_dbf2a999bd6d", "body": "Nope, that's a good call out. I'll give it one more look before merging but I think we're ok for that case.", "path": "src/requests/adapters.py", "line": 113, "side": "RIGHT", "created_at": "2024-05-29T00:00:07+00:00" }, { "id": 1619000165, "user": "user_0fa58b6f3572", "body": "Oh, looking again, not on a phone, and without a migraine, I see the `cert_reqs = \"CERT_REQUIRED\"` line on L110 that I clearly wrote, and which is what I was thinking we may want to be concerned about. So, I'm not nearly as worried.", "path": "src/requests/adapters.py", "line": 113, "side": "RIGHT", "created_at": "2024-05-29T14:31:10+00:00" }, { "id": 1619003075, "user": "user_0fa58b6f3572", "body": "Looking at this again with something of a performance mindset, do we want to cache somehow lookups to `isdir`? I'm not sure this hurts us at all, but just thinking about things that could slow us down in certain cases now. (Not for this pull request, just putting it out there)", "path": "src/requests/adapters.py", "line": 116, "side": "RIGHT", "created_at": "2024-05-29T14:32:37+00:00" }, { "id": 1619084935, "user": "user_dbf2a999bd6d", "body": "That seems like a reasonable optimization, I guess we'd need to check how much time we're actually spending on the dir check. I assume we'll get feedback if we have cases where this is a bottleneck.", "path": "src/requests/adapters.py", "line": 116, "side": "RIGHT", "created_at": "2024-05-29T15:23:20+00:00" } ], "meta": { "languages": [ "py" ], "touches_tests": false, "review_state_summary": { "COMMENTED": 6, "APPROVED": 2 }, "meaningful_comment_count": 7, "has_approval": true, "has_changes_requested": false, "total_review_comments": 7 } } { "_id": "c603a7094897e516", "_schema_version": "1.0", "_cleaned_at": "2026-02-12T07:46:51.378696+00:00", "repo": "psf/requests", "repo_url": "https://github.com/psf/requests", "license_name": "Apache License 2.0", "license_spdx": "Apache-2.0", "pr_number": 6716, "title": "Allow for overriding of specific pool key params", "body": "This re-enables the use case of providing a custom SSLContext via a [NAME_REDACTED] as broken in #6655 and reported in #6715\n\nCloses #6715", "author": "user_0fa58b6f3572", "created_at": "2024-05-22T11:53:49+00:00", "merged_at": "2024-05-24T21:37:06+00:00", "base_branch": "main", "head_branch": "bug/6715", "additions": 81, "deletions": 10, "changed_files": 2, "files": [ { "filename": "HISTORY.md", "status": "modified", "additions": 7, "deletions": 0, "changes": 7, "patch": "@@ -6,6 +6,13 @@ dev\n \n - \\[Short description of non-trivial change.\\]\n \n+2.32.3 (2024-05-24)\n+-------------------\n+\n+**Bugfixes**\n+- Fix bug breaking the ability to specify custom SSLContexts in sub-classes of\n+ HTTPAdapter. (#6716)\n+\n 2.32.2 (2024-05-21)\n -------------------" }, { "filename": "src/requests/adapters.py", "status": "modified", "additions": 74, "deletions": 10, "changes": 84, "patch": "@@ -83,16 +83,20 @@ def _urllib3_request_context(\n request: \"PreparedRequest\",\n verify: \"bool | str | None\",\n client_cert: \"typing.Tuple[str, str] | str | None\",\n+ poolmanager: \"PoolManager\",\n ) -> \"(typing.Dict[str, typing.Any], typing.Dict[str, typing.Any])\":\n host_params = {}\n pool_kwargs = {}\n parsed_request_url = urlparse(request.url)\n scheme = parsed_request_url.scheme.lower()\n port = parsed_request_url.port\n+ poolmanager_kwargs = getattr(poolmanager, \"connection_pool_kw\", {})\n+ has_poolmanager_ssl_context = poolmanager_kwargs.get(\"ssl_context\")\n+\n cert_reqs = \"CERT_REQUIRED\"\n if verify is False:\n cert_reqs = \"CERT_NONE\"\n- elif verify is True:\n+ elif verify is True and not has_poolmanager_ssl_context:\n pool_kwargs[\"ssl_context\"] = _preloaded_ssl_context\n elif isinstance(verify, str):\n if not os.path.isdir(verify):\n@@ -375,23 +379,83 @@ def build_response(self, req, resp):\n \n return response\n \n+ def build_connection_pool_key_attributes(self, request, verify, cert=None):\n+ \"\"\"Build the PoolKey attributes used by urllib3 to return a connection.\n+\n+ This looks at the PreparedRequest, the user-specified verify value,\n+ and the value of the cert parameter to determine what PoolKey values\n+ to use to select a connection from a given urllib3 [NAME_REDACTED].\n+\n+ The SSL related pool key arguments are not consistently set. As of\n+ this writing, use the following to determine what keys may be in that\n+ dictionary:\n+\n+ * If ``verify`` is ``True``, ``\"ssl_context\"`` will be set and will be the\n+ default Requests SSL Context\n+ * If ``verify`` is ``False``, ``\"ssl_context\"`` will not be set but\n+ ``\"cert_reqs\"`` will be set\n+ * If ``verify`` is a string, (i.e., it is a user-specified trust bundle)\n+ ``\"ca_certs\"`` will be set if the string is not a directory recognized\n+ by :py:func:`os.path.isdir`, otherwise ``\"ca_certs_dir\"`` will be\n+ set.\n+ * If ``\"cert\"`` is specified, ``\"cert_file\"`` will always be set. If\n+ ``\"cert\"`` is a tuple with a second item, ``\"key_file\"`` will also\n+ be present\n+\n+ To override these settings, one may subclass this class, call this\n+ method and use the above logic to change parameters as desired. For\n+ example, if one wishes to use a custom :py:class:`ssl.SSLContext` one\n+ must both set ``\"ssl_context\"`` and based on what else they require,\n+ alter the other keys to ensure the desired behaviour.\n+\n+ :param request:\n+ The PreparedReqest being sent over the connection.\n+ :type request:\n+ :class:`~requests.models.PreparedRequest`\n+ :param verify:\n+ Either a boolean, in which case it controls whether\n+ we verify the server's TLS certificate, or a string, in which case it\n+ must be a path to a CA bundle to use.\n+ :param cert:\n+ (optional) Any user-provided SSL certificate for client\n+ authentication (a.k.a., mTLS). This may be a string (i.e., just\n+ the path to a file which holds both certificate and key) or a\n+ tuple of length 2 with the certificate file path and key file\n+ path.\n+ :returns:\n+ A tuple of two dictionaries. The first is the \"host parameters\"\n+ portion of the [NAME_REDACTED] including scheme, hostname, and port. The\n+ second is a dictionary of SSLContext related parameters.\n+ \"\"\"\n+ return _urllib3_request_context(request, verify, cert, self.poolmanager)\n+\n def get_connection_with_tls_context(self, request, verify, proxies=None, cert=None):\n \"\"\"Returns a urllib3 connection for the given request and TLS settings.\n This should not be called from user code, and is only exposed for use\n when subclassing the :class:`HTTPAdapter `.\n \n- :param request: The :class:`PreparedRequest ` object\n- to be sent over the connection.\n- :param verify: Either a boolean, in which case it controls whether\n- we verify the server's TLS certificate, or a string, in which case it\n- must be a path to a CA bundle to use.\n- :param proxies: (optional) The proxies dictionary to apply to the request.\n- :param cert: (optional) Any user-provided SSL certificate to be trusted.\n- :rtype: urllib3.ConnectionPool\n+ :param request:\n+ The :class:`PreparedRequest ` object to be sent\n+ over the connection.\n+ :param verify:\n+ Either a boolean, in which case it controls whether we verify the\n+ server's TLS certificate, or a string, in which case it must be a\n+ path to a CA bundle to use.\n+ :param proxies:\n+ (optional) The proxies dictionary to apply to the request.\n+ :param cert:\n+ (optional) Any user-provided SSL certificate to be used for client\n+ authentication (a.k.a., mTLS).\n+ :rtype:\n+ urllib3.ConnectionPool\n \"\"\"\n proxy = select_proxy(request.url, proxies)\n try:\n- host_params, pool_kwargs = _urllib3_request_context(request, verify, cert)\n+ host_params, pool_kwargs = self.build_connection_pool_key_attributes(\n+ request,\n+ verify,\n+ cert,\n+ )\n except ValueError as e:\n raise InvalidURL(e, request=request)\n if proxy:" } ], "reviews": [ { "id": 2071195950, "user": "user_dbf2a999bd6d", "state": "COMMENTED", "body": "If [USER_REDACTED], [USER_REDACTED] and/or [USER_REDACTED] are willing to give this patch a try, it would be nice to make sure we're not missing any other requirements.\n\nOtherwise this seems straight forward to me, just a couple minor comments to add a date and the current PR reference.", "submitted_at": "2024-05-22T13:28:44+00:00" }, { "id": 2072332359, "user": "user_dbf2a999bd6d", "state": "APPROVED", "body": "I think this looks good to go. We've received some early indication is solves this class of problems from what's been raised. I'll plan to cut a release with this tomorrow AM in the US.", "submitted_at": "2024-05-22T20:46:01+00:00" }, { "id": 2342569167, "user": "user_e6d1de3927d6", "state": "APPROVED", "body": null, "submitted_at": "2024-10-02T10:28:12+00:00" } ], "review_comments": [ { "id": 1609951561, "user": "user_dbf2a999bd6d", "body": "```suggestion\n2.32.3 (2024-05-23)\n```", "path": "HISTORY.md", "line": null, "side": "RIGHT", "created_at": "2024-05-22T13:25:02+00:00" }, { "id": 1609952141, "user": "user_dbf2a999bd6d", "body": "```suggestion\n HTTPAdapter. (#6716)\n```", "path": "HISTORY.md", "line": null, "side": "RIGHT", "created_at": "2024-05-22T13:25:22+00:00" } ], "meta": { "languages": [ "md", "py" ], "touches_tests": false, "review_state_summary": { "COMMENTED": 1, "APPROVED": 2 }, "meaningful_comment_count": 2, "has_approval": true, "has_changes_requested": false, "total_review_comments": 2 } } { "_id": "e2b38a834355bced", "_schema_version": "1.0", "_cleaned_at": "2026-02-12T07:46:51.378696+00:00", "repo": "psf/requests", "repo_url": "https://github.com/psf/requests", "license_name": "Apache License 2.0", "license_spdx": "Apache-2.0", "pr_number": 6710, "title": "Move _get_connection to get_connection_with_tls_context", "body": "This PR is meant to provide a new publicly supported api `get_connection_with_tls_context` to better facilitate custom adapters with our recent fix for CVE-2024-35195.\n\nAs described [here](https://github.com/psf/requests/issues/6707#issuecomment-2122490651), we will be deprecating the existing `get_connection` API, and custom adapters will need to migrate their existing `get_connection` implementations to use `get_connection_with_tls_context`. Below is a very simple implementation that will get projects relying on a custom `get_connection` implementation unblocked.\n\nHowever, we _strongly_ recommend maintainers evaluate if their custom `get_connection` is subject to the same issues as the CVE above and make appropriate changes as needed.\n\n**Minimum new code to work as a pass-through**\nThis will be backwards compatible between versions of Requests.\n```python\ndef get_connection_with_tls_context(self, request, verify, proxies=None, cert=None):\n return self.get_connection(request.url, proxies)\n```", "author": "user_dbf2a999bd6d", "created_at": "2024-05-21T15:58:50+00:00", "merged_at": "2024-05-21T16:41:18+00:00", "base_branch": "main", "head_branch": "api_rename", "additions": 31, "deletions": 6, "changed_files": 1, "files": [ { "filename": "src/requests/adapters.py", "status": "modified", "additions": 31, "deletions": 6, "changes": 37, "patch": "@@ -9,6 +9,7 @@\n import os.path\n import socket # noqa: F401\n import typing\n+import warnings\n \n from urllib3.exceptions import ClosedPoolError, ConnectTimeoutError\n from urllib3.exceptions import HTTPError as _HTTPError\n@@ -374,10 +375,20 @@ def build_response(self, req, resp):\n \n return response\n \n- def _get_connection(self, request, verify, proxies=None, cert=None):\n- # Replace the existing get_connection without breaking things and\n- # ensure that TLS settings are considered when we interact with\n- # urllib3 HTTP Pools\n+ def get_connection_with_tls_context(self, request, verify, proxies=None, cert=None):\n+ \"\"\"Returns a urllib3 connection for the given request and TLS settings.\n+ This should not be called from user code, and is only exposed for use\n+ when subclassing the :class:`HTTPAdapter `.\n+\n+ :param request: The :class:`PreparedRequest ` object\n+ to be sent over the connection.\n+ :param verify: Either a boolean, in which case it controls whether\n+ we verify the server's TLS certificate, or a string, in which case it\n+ must be a path to a CA bundle to use.\n+ :param proxies: (optional) The proxies dictionary to apply to the request.\n+ :param cert: (optional) Any user-provided SSL certificate to be trusted.\n+ :rtype: urllib3.ConnectionPool\n+ \"\"\"\n proxy = select_proxy(request.url, proxies)\n try:\n host_params, pool_kwargs = _urllib3_request_context(request, verify, cert)\n@@ -404,14 +415,26 @@ def _get_connection(self, request, verify, proxies=None, cert=None):\n return conn\n \n def get_connection(self, url, proxies=None):\n- \"\"\"Returns a urllib3 connection for the given URL. This should not be\n+ \"\"\"DEPRECATED: Users should move to `get_connection_with_tls_context`\n+ for all subclasses of HTTPAdapter using Requests>=2.32.2.\n+\n+ Returns a urllib3 connection for the given URL. This should not be\n called from user code, and is only exposed for use when subclassing the\n :class:`HTTPAdapter `.\n \n :param url: The URL to connect to.\n :param proxies: (optional) A Requests-style dictionary of proxies used on this request.\n :rtype: urllib3.ConnectionPool\n \"\"\"\n+ warnings.warn(\n+ (\n+ \"`get_connection` has been deprecated in favor of \"\n+ \"`get_connection_with_tls_context`. Custom HTTPAdapter subclasses \"\n+ \"will need to migrate for Requests>=2.32.2. Please see \"\n+ \"https://github.com/psf/requests/pull/6710 for more details.\"\n+ ),\n+ DeprecationWarning,\n+ )\n proxy = select_proxy(url, proxies)\n \n if proxy:\n@@ -529,7 +552,9 @@ def send(\n \"\"\"\n \n try:\n- conn = self._get_connection(request, verify, proxies=proxies, cert=cert)\n+ conn = self.get_connection_with_tls_context(\n+ request, verify, proxies=proxies, cert=cert\n+ )\n except LocationValueError as e:\n raise InvalidURL(e, request=request)" } ], "reviews": [ { "id": 2069075746, "user": "user_b08fb5f52ea1", "state": "APPROVED", "body": "Looks good, only had one suggestion that might require a new test.", "submitted_at": "2024-05-21T16:13:58+00:00" }, { "id": 2069085116, "user": "user_dbf2a999bd6d", "state": "COMMENTED", "body": null, "submitted_at": "2024-05-21T16:17:36+00:00" }, { "id": 2069109177, "user": "user_dbf2a999bd6d", "state": "COMMENTED", "body": null, "submitted_at": "2024-05-21T16:29:48+00:00" } ], "review_comments": [ { "id": 1608603801, "user": "user_b08fb5f52ea1", "body": "If this method is deprecated shall we start emitting `DeprecationWarning`?", "path": "src/requests/adapters.py", "line": 418, "side": "RIGHT", "created_at": "2024-05-21T16:12:52+00:00" }, { "id": 1608609666, "user": "user_dbf2a999bd6d", "body": "I thought about that but it's not reachable in any of our code anymore and if someone is using a custom implementation it won't have the warning.\n\nHappy to be wrong if I'm missing something but it seems like it will just be dead code on arrival.", "path": "src/requests/adapters.py", "line": 418, "side": "RIGHT", "created_at": "2024-05-21T16:17:36+00:00" }, { "id": 1608624860, "user": "user_dbf2a999bd6d", "body": "I guess it's better to be safe, this should be addressed in 92075b330a30b9883f466a43d3f7566ab849f91b.", "path": "src/requests/adapters.py", "line": 418, "side": "RIGHT", "created_at": "2024-05-21T16:29:48+00:00" } ], "meta": { "languages": [ "py" ], "touches_tests": false, "review_state_summary": { "APPROVED": 1, "COMMENTED": 2 }, "meaningful_comment_count": 3, "has_approval": true, "has_changes_requested": false, "total_review_comments": 3 } } { "_id": "7505d25d2dba74e6", "_schema_version": "1.0", "_cleaned_at": "2026-02-12T07:46:51.378696+00:00", "repo": "psf/requests", "repo_url": "https://github.com/psf/requests", "license_name": "Apache License 2.0", "license_spdx": "Apache-2.0", "pr_number": 6702, "title": "Allow optional char detection dependencies in post-packaging", "body": "This PR is a proposal to relax our requirement to have a character detection library present with all installations of Requests. While we cannot remove our reliance on `charset_normalizer` or `chardet`, there are use cases where Requests is repackaged in applications or other tools that do not need our character detection behavior. These changes will enable them to remove those dependencies from their installation.\n\nThe current use case for this shift is to allow `pip` to remove these dependencies entirely. That should slim the package ~2MB in 24.1.0 and avoid the overhead of importing the unneeded dependency.", "author": "user_dbf2a999bd6d", "created_at": "2024-05-14T22:25:35+00:00", "merged_at": "2024-05-15T00:15:19+00:00", "base_branch": "main", "head_branch": "no_char_detection", "additions": 60, "deletions": 23, "changed_files": 5, "files": [ { "filename": ".github/workflows/run-tests.yml", "status": "modified", "additions": 20, "deletions": 0, "changes": 20, "patch": "@@ -37,3 +37,23 @@ jobs:\n - name: Run tests\n run: |\n make ci\n+\n+ no_chardet:\n+ name: \"[NAME_REDACTED]\"\n+ runs-on: ubuntu-latest\n+ strategy:\n+ fail-fast: true\n+\n+ steps:\n+ - uses: actions/checkout@8ade135a41bc03ea155e62e844d188df1ea18608\n+ - name: 'Set up Python 3.8'\n+ uses: actions/setup-python@82c7e631bb3cdc910f68e0081d67478d79c6982d\n+ with:\n+ python-version: '3.8'\n+ - name: Install dependencies\n+ run: |\n+ make\n+ python -m pip uninstall -y \"charset_normalizer\" \"chardet\"\n+ - name: Run tests\n+ run: |\n+ make ci" }, { "filename": "src/requests/__init__.py", "status": "modified", "additions": 5, "deletions": 1, "changes": 6, "patch": "@@ -83,7 +83,11 @@ def check_compatibility(urllib3_version, chardet_version, charset_normalizer_ver\n # charset_normalizer >= 2.0.0 < 4.0.0\n assert (2, 0, 0) <= (major, minor, patch) < (4, 0, 0)\n else:\n- raise Exception(\"You need either charset_normalizer or chardet installed\")\n+ warnings.warn(\n+ \"Unable to find acceptable character detection dependency \"\n+ \"(chardet or charset_normalizer).\",\n+ RequestsDependencyWarning,\n+ )\n \n \n def _check_cryptography(cryptography_version):" }, { "filename": "src/requests/compat.py", "status": "modified", "additions": 20, "deletions": 5, "changes": 25, "patch": "@@ -7,13 +7,28 @@\n compatibility until the next major version.\n \"\"\"\n \n-try:\n- import chardet\n-except ImportError:\n- import charset_normalizer as chardet\n-\n+import importlib\n import sys\n \n+# -------------------\n+# [NAME_REDACTED]\n+# -------------------\n+\n+\n+def _resolve_char_detection():\n+ \"\"\"Find supported character detection libraries.\"\"\"\n+ chardet = None\n+ for lib in (\"chardet\", \"charset_normalizer\"):\n+ if chardet is None:\n+ try:\n+ chardet = importlib.import_module(lib)\n+ except ImportError:\n+ pass\n+ return chardet\n+\n+\n+chardet = _resolve_char_detection()\n+\n # -------\n # Pythons\n # -------" }, { "filename": "src/requests/models.py", "status": "modified", "additions": 6, "deletions": 1, "changes": 7, "patch": "@@ -789,7 +789,12 @@ def next(self):\n [USER_REDACTED]\n def apparent_encoding(self):\n \"\"\"The apparent encoding, provided by [NAME_REDACTED]_normalizer or chardet libraries.\"\"\"\n- return chardet.detect(self.content)[\"encoding\"]\n+ if chardet is not None:\n+ return chardet.detect(self.content)[\"encoding\"]\n+ else:\n+ # If no character detection library is available, we'll fall back\n+ # to a standard Python utf-8 str.\n+ return \"utf-8\"\n \n def iter_content(self, chunk_size=1, decode_unicode=False):\n \"\"\"Iterates over the response data. When stream=True is set on the" }, { "filename": "src/requests/packages.py", "status": "modified", "additions": 9, "deletions": 16, "changes": 25, "patch": "@@ -1,13 +1,6 @@\n import sys\n \n-try:\n- import chardet\n-except ImportError:\n- import warnings\n-\n- import charset_normalizer as chardet\n-\n- warnings.filterwarnings(\"ignore\", \"Trying to detect\", module=\"charset_normalizer\")\n+from .compat import chardet\n \n # This code exists for backwards compatibility reasons.\n # I don't like it either. Just look the other way. :)\n@@ -20,11 +13,11 @@\n if mod == package or mod.startswith(f\"{package}.\"):\n sys.modules[f\"requests.packages.{mod}\"] = sys.modules[mod]\n \n-target = chardet.__name__\n-for mod in list(sys.modules):\n- if mod == target or mod.startswith(f\"{target}.\"):\n- imported_mod = sys.modules[mod]\n- sys.modules[f\"requests.packages.{mod}\"] = imported_mod\n- mod = mod.replace(target, \"chardet\")\n- sys.modules[f\"requests.packages.{mod}\"] = imported_mod\n-# Kinda cool, though, right?\n+if chardet is not None:\n+ target = chardet.__name__\n+ for mod in list(sys.modules):\n+ if mod == target or mod.startswith(f\"{target}.\"):\n+ imported_mod = sys.modules[mod]\n+ sys.modules[f\"requests.packages.{mod}\"] = imported_mod\n+ mod = mod.replace(target, \"chardet\")\n+ sys.modules[f\"requests.packages.{mod}\"] = imported_mod" } ], "reviews": [ { "id": 2056669581, "user": "user_0fa58b6f3572", "state": "APPROVED", "body": null, "submitted_at": "2024-05-15T00:15:13+00:00" }, { "id": 2070448164, "user": "user_2f8f1a139e37", "state": "COMMENTED", "body": null, "submitted_at": "2024-05-22T08:08:55+00:00" } ], "review_comments": [ { "id": 1609492798, "user": "user_2f8f1a139e37", "body": "While this keeps the logic of the earlier code, I think that the library which is required on should be tried first. https://github.com/psf/requests/pull/6714 addresses this.", "path": "src/requests/compat.py", "line": 21, "side": "RIGHT", "created_at": "2024-05-22T08:08:55+00:00" } ], "meta": { "languages": [ "py", "yml" ], "touches_tests": false, "review_state_summary": { "APPROVED": 1, "COMMENTED": 1 }, "meaningful_comment_count": 1, "has_approval": true, "has_changes_requested": false, "total_review_comments": 1 } } { "_id": "2c32ef2bbaccc4eb", "_schema_version": "1.0", "_cleaned_at": "2026-02-12T07:46:51.378696+00:00", "repo": "psf/requests", "repo_url": "https://github.com/psf/requests", "license_name": "Apache License 2.0", "license_spdx": "Apache-2.0", "pr_number": 6667, "title": "Avoid reloading root certificates to improve concurrent performance", "body": "## Reproducing the problem\n\nLet's consider the following script. It runs a bunch of concurrent requests against a URL, both with certificate verification enabled and disabled, and outputs the time it takes to do it in both cases.\n\n```py\nfrom time import time\nfrom threading import Thread\nimport requests\nimport urllib3\n\nurllib3.disable_warnings()\n\ndef do_request(verify):\n requests.get('https://example.com', verify=verify)\n\ndef measure(verify):\n threads = [Thread(target=do_request, args=(verify,)) for _ in range(30)]\n\n start = time()\n for t in threads: t.start()\n for t in threads: t.join()\n end = time()\n\n print(end - start)\n\nmeasure(verify=True)\nmeasure(verify=False)\n```\n\nWhat's the time difference between the two? It turns out it is highly dependent on your local configuration. On my local machine, with a relatively modern config (Python 3.12 + OpenSSL 3.0.2), the times are `~1.2s` for `verify=True` and `~0.5s` for `verify=False`.\n\nIt's a >100% difference, but we initially blamed it on cert verification taking some time. However, we observed even larger differences (>500%) in some environments, and decided to find out what was going on.\n\n## Problem description\n\nOur main use case for requests is running lots of requests concurrently, and we spent some time bisecting this oddity to see if there was room for a performance optimization.\n\nThe issue is a bit more clear if you profile the concurrent executions. When verifying certs, these are the top 3 function calls by [NAME_REDACTED]:\n\n```\nncalls tottime percall cumtime percall filename:lineno(function)\n30/1 0.681 0.023 0.002 0.002 {method 'load_verify_locations' of '_ssl._SSLContext' objects}\n30/1 0.181 0.006 0.002 0.002 {method 'connect' of '_socket.socket' objects}\n60/2 0.180 0.003 1.323 0.662 {method 'read' of '_ssl._SSLSocket' objects}\n```\n\nConversely, this is how the top 3 looks like without cert verification:\n\n```\nncalls tottime percall cumtime percall filename:lineno(function)\n30/1 0.233 0.008 0.001 0.001 {method 'do_handshake' of '_ssl._SSLSocket' objects}\n30/1 0.106 0.004 0.002 0.002 {method 'connect' of '_socket.socket' objects}\n60/2 0.063 0.001 0.505 0.253 {method 'read' of '_ssl._SSLSocket' objects}\n```\n\nIn the first case, a full 0.68 seconds are spent in the `load_verify_locations()` function of the `ssl` module, which configures a `SSLContext` object to use a set of CA certificates for validation. Inside it, there is a C FFI call to OpenSSL's `SSL_CTX_load_verify_locations()` which [is known](https://github.com/[USER_REDACTED]n/cpython/issues/95031) to be [quite slow](https://github.com/[USER_REDACTED]nssl/openssl/issues/16871). This happens once per request (hence the `30` on the left).\n\nWe believe that, in some cases, there is even some blocking going on, either because each FFI call locks up the GIL or because of some thread safety mechanisms in OpenSSL itself. We also think that this is more or less pronounced depending on internal changes between OpenSSL's versions, hence the variability between environments.\n\nWhen cert validation isn't needed, these calls are skipped which speeds up concurrent performance dramatically.\n\n## Submitted solution\n\nIt isn't possible to skip loading root CA certificates entirely, but it isn't necessary to do it on every request. More specifically, a call to `load_verify_locations()` happens when:\n\n- A new `urllib3.connectionpool.HTTPSConnectionPool` is created.\n\n- On connection, by urllib3's `ssl_wrap_socket()`, when the connection's `ca_certs` or `ca_cert_dir` attributes are set (see [the relevant code](https://github.com/urllib3/urllib3/blob/9929d3c4e03b71ba485148a8390cd9411981f40f/src/urllib3/util/ssl_.py#L438)).\n\nThe first case doesn't need to be addressed anymore after the latest addition of `_get_connection()`. Since it now passes down `pool_kwargs`, this allows urllib3 to use a cached pool with the same settings every time, instead of creating one per request.\n\nThe second one is addressed in this PR. If a verified connection is requested, `_urllib3_request_context()` already makes it so that a connection pool using a `SSLContext` with all relevant certificates loaded is always used. Hence, there is no need to trigger a call to `load_verify_locations()` again.\n\nYou can test against https://invalid.badssl.com to check that `verify=True` and `verify=False` still behave as expected and are now equally fast.\n\nI'd like to mention that there have been a few changes in Requests since I started drafting this, and I'm not sure that setting `conn.ca_certs` or `conn.ca_certs = cert_loc` in `cert_verify()` is even still needed, since I think that the logic could be moved to `_urllib3_request_context()` and benefit from using a cached context in those cases too.", "author": "user_14f21d37ae53", "created_at": "2024-03-20T11:51:17+00:00", "merged_at": "2024-05-15T20:07:26+00:00", "base_branch": "main", "head_branch": "main", "additions": 28, "deletions": 18, "changed_files": 1, "files": [ { "filename": "src/requests/adapters.py", "status": "modified", "additions": 28, "deletions": 18, "changes": 46, "patch": "@@ -26,6 +26,7 @@\n from urllib3.util import Timeout as TimeoutSauce\n from urllib3.util import parse_url\n from urllib3.util.retry import Retry\n+from urllib3.util.ssl_ import create_urllib3_context\n \n from .auth import _basic_auth_str\n from .compat import basestring, urlparse\n@@ -71,6 +72,11 @@ def SOCKSProxyManager(*args, **kwargs):\n DEFAULT_RETRIES = 0\n DEFAULT_POOL_TIMEOUT = None\n \n+_preloaded_ssl_context = create_urllib3_context()\n+_preloaded_ssl_context.load_verify_locations(\n+ extract_zipped_paths(DEFAULT_CA_BUNDLE_PATH)\n+)\n+\n \n def _urllib3_request_context(\n request: \"PreparedRequest\",\n@@ -85,8 +91,13 @@ def _urllib3_request_context(\n cert_reqs = \"CERT_REQUIRED\"\n if verify is False:\n cert_reqs = \"CERT_NONE\"\n- if isinstance(verify, str):\n- pool_kwargs[\"ca_certs\"] = verify\n+ elif verify is True:\n+ pool_kwargs[\"ssl_context\"] = _preloaded_ssl_context\n+ elif isinstance(verify, str):\n+ if not os.path.isdir(verify):\n+ pool_kwargs[\"ca_certs\"] = verify\n+ else:\n+ pool_kwargs[\"ca_cert_dir\"] = verify\n pool_kwargs[\"cert_reqs\"] = cert_reqs\n if client_cert is not None:\n if isinstance(client_cert, tuple) and len(client_cert) == 2:\n@@ -284,27 +295,26 @@ def cert_verify(self, conn, url, verify, cert):\n :param cert: The SSL certificate to verify.\n \"\"\"\n if url.lower().startswith(\"https\") and verify:\n- cert_loc = None\n+ conn.cert_reqs = \"CERT_REQUIRED\"\n \n- # Allow self-specified cert location.\n+ # Only load the CA certificates if 'verify' is a string indicating the CA bundle to use.\n+ # Otherwise, if verify is a boolean, we don't load anything since\n+ # the connection will be using a context with the default certificates already loaded,\n+ # and this avoids a call to the slow load_verify_locations()\n if verify is not True:\n+ # `verify` must be a str with a path then\n cert_loc = verify\n \n- if not cert_loc:\n- cert_loc = extract_zipped_paths(DEFAULT_CA_BUNDLE_PATH)\n-\n- if not cert_loc or not os.path.exists(cert_loc):\n- raise OSError(\n- f\"Could not find a suitable TLS CA certificate bundle, \"\n- f\"invalid path: {cert_loc}\"\n- )\n+ if not os.path.exists(cert_loc):\n+ raise OSError(\n+ f\"Could not find a suitable TLS CA certificate bundle, \"\n+ f\"invalid path: {cert_loc}\"\n+ )\n \n- conn.cert_reqs = \"CERT_REQUIRED\"\n-\n- if not os.path.isdir(cert_loc):\n- conn.ca_certs = cert_loc\n- else:\n- conn.ca_cert_dir = cert_loc\n+ if not os.path.isdir(cert_loc):\n+ conn.ca_certs = cert_loc\n+ else:\n+ conn.ca_cert_dir = cert_loc\n else:\n conn.cert_reqs = \"CERT_NONE\"\n conn.ca_certs = None" } ], "reviews": [ { "id": 1950596425, "user": "user_0fa58b6f3572", "state": "CHANGES_REQUESTED", "body": null, "submitted_at": "2024-03-21T01:46:24+00:00" }, { "id": 1951613196, "user": "user_14f21d37ae53", "state": "COMMENTED", "body": null, "submitted_at": "2024-03-21T10:14:37+00:00" }, { "id": 2052657681, "user": "user_0fa58b6f3572", "state": "APPROVED", "body": "Just want a second set of eyes from [USER_REDACTED] or [USER_REDACTED]", "submitted_at": "2024-05-13T13:10:49+00:00" }, { "id": 2058899428, "user": "user_dbf2a999bd6d", "state": "APPROVED", "body": "Cool, this seems reasonable to me. I was curious if we'd be better off doing this per-Adapter instance instead of globally but it seems like that may not be a concern with Christian's response.", "submitted_at": "2024-05-15T20:01:59+00:00" }, { "id": 2397673664, "user": "user_adf270769e63", "state": "COMMENTED", "body": "Run nodes debug merge", "submitted_at": "2024-10-28T00:08:02+00:00" } ], "review_comments": [ { "id": 1533138744, "user": "user_0fa58b6f3572", "body": "This is actually critical behavior you're removing", "path": "src/requests/adapters.py", "line": 294, "side": "LEFT", "created_at": "2024-03-21T01:45:42+00:00" }, { "id": 1533587993, "user": "user_14f21d37ae53", "body": "Thanks for the catch, I had to adapt the patch quite a bit from what we're using right now and that inconsistency slipped by.\n\nI pushed a change to explicitly use `DEFAULT_CA_BUNDLE_PATH` when `verify=True`. This is done by creating a module-level `SSLContext` with that bundle already loaded, and instructing the connection pool to use that context when no custom bundle is specified. Since the server's cert is verified using the CA certificates loaded in the `SSLContext` used in the request, this should work.\n\nAgain, the goal is to avoid setting `ca_certs` or `ca_cert_dir` in the most common use case as it triggers another (in this case redundant) call to `load_verify_locations()` by urllib3:\n\n```py\nif ca_certs or ca_cert_dir or ca_cert_data:\n try:\n context.load_verify_locations(ca_certs, ca_cert_dir, ca_cert_data)\n```\n\nSince `DEFAULT_CA_BUNDLE_PATH` is sugar for `certifi.where()`, which in turn always returns the path to a single bundle file, I decided to skip checking for `os.path.isdir()` because it should always be False. If you're not comfortable with this please let me know and I'll change it.\n\nI also changed `_urllib3_request_context()` slightly to handle the case where `verify` is a path to a dir instead to a single file, as we should set `ca_cert_dir` instead of `ca_certs` in that case. I believe this is now fully redundant with the corresponding logic in `cert_verify()`.\n\nI tried to write corresponding tests to verify that the `SSLContext`s used in different scenarios have the correct certificates loaded, but I couldn't find a way to access such low-level information about a request in the exposed classes. If it's possible, please give me a few pointers and I'll be glad to expand the test suite.", "path": "src/requests/adapters.py", "line": 294, "side": "LEFT", "created_at": "2024-03-21T10:14:37+00:00" } ], "meta": { "languages": [ "py" ], "touches_tests": false, "review_state_summary": { "CHANGES_REQUESTED": 1, "COMMENTED": 2, "APPROVED": 2 }, "meaningful_comment_count": 2, "has_approval": true, "has_changes_requested": true, "total_review_comments": 2 } } { "_id": "6706636b7f88e108", "_schema_version": "1.0", "_cleaned_at": "2026-02-12T07:46:51.378696+00:00", "repo": "psf/requests", "repo_url": "https://github.com/psf/requests", "license_name": "Apache License 2.0", "license_spdx": "Apache-2.0", "pr_number": 6655, "title": "Use TLS settings in selecting connection pool", "body": "Previously, if someone made a request with `verify=False` then made a request where they expected verification to be enabled to the same host, they would potentially reuse a connection where TLS had not been verified.\n\nThis fixes that issue.", "author": "user_0fa58b6f3572", "created_at": "2024-03-03T13:05:10+00:00", "merged_at": "2024-03-11T11:21:59+00:00", "base_branch": "main", "head_branch": "fix-tls-floppy", "additions": 65, "deletions": 2, "changed_files": 3, "files": [ { "filename": "src/requests/adapters.py", "status": "modified", "additions": 57, "deletions": 1, "changes": 58, "patch": "@@ -8,6 +8,7 @@\n \n import os.path\n import socket # noqa: F401\n+import typing\n \n from urllib3.exceptions import ClosedPoolError, ConnectTimeoutError\n from urllib3.exceptions import HTTPError as _HTTPError\n@@ -61,12 +62,38 @@ def SOCKSProxyManager(*args, **kwargs):\n raise InvalidSchema(\"Missing dependencies for SOCKS support.\")\n \n \n+if typing.TYPE_CHECKING:\n+ from .models import PreparedRequest\n+\n+\n DEFAULT_POOLBLOCK = False\n DEFAULT_POOLSIZE = 10\n DEFAULT_RETRIES = 0\n DEFAULT_POOL_TIMEOUT = None\n \n \n+def _urllib3_request_context(\n+ request: \"PreparedRequest\", verify: \"bool | str | None\"\n+) -> \"(typing.Dict[str, typing.Any], typing.Dict[str, typing.Any])\":\n+ host_params = {}\n+ pool_kwargs = {}\n+ parsed_request_url = urlparse(request.url)\n+ scheme = parsed_request_url.scheme.lower()\n+ port = parsed_request_url.port\n+ cert_reqs = \"CERT_REQUIRED\"\n+ if verify is False:\n+ cert_reqs = \"CERT_NONE\"\n+ if isinstance(verify, str):\n+ pool_kwargs[\"ca_certs\"] = verify\n+ pool_kwargs[\"cert_reqs\"] = cert_reqs\n+ host_params = {\n+ \"scheme\": scheme,\n+ \"host\": parsed_request_url.hostname,\n+ \"port\": port,\n+ }\n+ return host_params, pool_kwargs\n+\n+\n class BaseAdapter:\n \"\"\"The Base Transport Adapter\"\"\"\n \n@@ -327,6 +354,35 @@ def build_response(self, req, resp):\n \n return response\n \n+ def _get_connection(self, request, verify, proxies=None):\n+ # Replace the existing get_connection without breaking things and\n+ # ensure that TLS settings are considered when we interact with\n+ # urllib3 HTTP Pools\n+ proxy = select_proxy(request.url, proxies)\n+ try:\n+ host_params, pool_kwargs = _urllib3_request_context(request, verify)\n+ except ValueError as e:\n+ raise InvalidURL(e, request=request)\n+ if proxy:\n+ proxy = prepend_scheme_if_needed(proxy, \"http\")\n+ proxy_url = parse_url(proxy)\n+ if not proxy_url.host:\n+ raise InvalidProxyURL(\n+ \"Please check proxy URL. It is malformed \"\n+ \"and could be missing the host.\"\n+ )\n+ proxy_manager = self.proxy_manager_for(proxy)\n+ conn = proxy_manager.connection_from_host(\n+ **host_params, pool_kwargs=pool_kwargs\n+ )\n+ else:\n+ # Only scheme should be lower case\n+ conn = self.poolmanager.connection_from_host(\n+ **host_params, pool_kwargs=pool_kwargs\n+ )\n+\n+ return conn\n+\n def get_connection(self, url, proxies=None):\n \"\"\"Returns a urllib3 connection for the given URL. This should not be\n called from user code, and is only exposed for use when subclassing the\n@@ -453,7 +509,7 @@ def send(\n \"\"\"\n \n try:\n- conn = self.get_connection(request.url, proxies)\n+ conn = self._get_connection(request, verify, proxies)\n except LocationValueError as e:\n raise InvalidURL(e, request=request)" }, { "filename": "tests/test_requests.py", "status": "modified", "additions": 7, "deletions": 0, "changes": 7, "patch": "@@ -2828,6 +2828,13 @@ def test_status_code_425(self):\n assert r5 == 425\n assert r6 == 425\n \n+ def test_different_connection_pool_for_tls_settings(self):\n+ s = requests.Session()\n+ r1 = s.get(\"https://invalid.badssl.com\", verify=False)\n+ assert r1.status_code == 421\n+ with pytest.raises(requests.exceptions.SSLError):\n+ s.get(\"https://invalid.badssl.com\")\n+\n \n def test_json_decode_errors_are_serializable_deserializable():\n json_decode_error = requests.exceptions.JSONDecodeError(" }, { "filename": "tox.ini", "status": "modified", "additions": 1, "deletions": 1, "changes": 2, "patch": "@@ -7,7 +7,7 @@ extras =\n security\n socks\n commands =\n- pytest tests\n+ pytest {posargs:tests}\n \n [testenv:default]" } ], "reviews": [ { "id": 1920906731, "user": "user_dbf2a999bd6d", "state": "COMMENTED", "body": null, "submitted_at": "2024-03-10T16:33:49+00:00" }, { "id": 1926588901, "user": "user_0fa58b6f3572", "state": "COMMENTED", "body": null, "submitted_at": "2024-03-10T17:11:39+00:00" }, { "id": 1926589195, "user": "user_0fa58b6f3572", "state": "COMMENTED", "body": null, "submitted_at": "2024-03-10T17:12:49+00:00" }, { "id": 1926592022, "user": "user_dbf2a999bd6d", "state": "APPROVED", "body": ":shipit:", "submitted_at": "2024-03-10T17:18:05+00:00" }, { "id": 1927570372, "user": "user_0fa58b6f3572", "state": "COMMENTED", "body": null, "submitted_at": "2024-03-11T11:21:54+00:00" }, { "id": 2342567877, "user": "user_e6d1de3927d6", "state": "COMMENTED", "body": "Thank you", "submitted_at": "2024-10-02T10:27:22+00:00" } ], "review_comments": [ { "id": 1515206804, "user": "user_dbf2a999bd6d", "body": "Not against this, but I think this is the first time we're introducing typing into Requests. I'm curious if we want to start that or push it into typeshed since this will be precedent for future inline typing?", "path": "src/requests/adapters.py", "line": 66, "side": "RIGHT", "created_at": "2024-03-06T21:56:23+00:00" }, { "id": 1518892861, "user": "user_dbf2a999bd6d", "body": "There may not be a better way to test this but I don't know if we have other tests that require contacting a live site with TLS disabled. That may have some durability issues and means we're going to take the first response we get back. Probably minor, but figured I'd call it out.", "path": "tests/test_requests.py", "line": 2836, "side": "RIGHT", "created_at": "2024-03-10T16:33:36+00:00" }, { "id": 1518900181, "user": "user_0fa58b6f3572", "body": "This is for a private method (that I fully anticipate people abusing) but we're not advertising things are typed and so it's not something I'm concerned with.", "path": "src/requests/adapters.py", "line": 66, "side": "RIGHT", "created_at": "2024-03-10T17:11:39+00:00" }, { "id": 1518900465, "user": "user_0fa58b6f3572", "body": "There are many alternatives here, but those are all significantly more effort and this shows the behaviour is fixed before and after handily. I'm sure Linux folks will get pissed but I'm not as bothered about finding time later to do this a different way after we have fixed this", "path": "tests/test_requests.py", "line": 2836, "side": "RIGHT", "created_at": "2024-03-10T17:12:49+00:00" }, { "id": 1519559679, "user": "user_0fa58b6f3572", "body": "I'll try to prioritize better (offline) tests soon", "path": "tests/test_requests.py", "line": 2836, "side": "RIGHT", "created_at": "2024-03-11T11:21:54+00:00" } ], "meta": { "languages": [ "ini", "py" ], "touches_tests": true, "review_state_summary": { "COMMENTED": 5, "APPROVED": 1 }, "meaningful_comment_count": 5, "has_approval": true, "has_changes_requested": false, "total_review_comments": 5 } } { "_id": "72d526f7862e2149", "_schema_version": "1.0", "_cleaned_at": "2026-02-12T07:46:51.393484+00:00", "repo": "psf/requests", "repo_url": "https://github.com/psf/requests", "license_name": "Apache License 2.0", "license_spdx": "Apache-2.0", "pr_number": 6644, "title": "Trim excess leading path separators", "body": "A URL with excess leading / (path-separator)s would cause urllib3 to attempt to reparse the request-uri as a full URI with a host and port. This bypasses that logic in ConnectionPool.urlopen by [NAME_REDACTED] /s with just a single /.\n\nCloses #6643", "author": "user_0fa58b6f3572", "created_at": "2024-02-22T01:11:15+00:00", "merged_at": "2024-02-23T00:49:42+00:00", "base_branch": "main", "head_branch": "bug/6643", "additions": 11, "deletions": 0, "changed_files": 2, "files": [ { "filename": "src/requests/adapters.py", "status": "modified", "additions": 3, "deletions": 0, "changes": 3, "patch": "@@ -390,6 +390,9 @@ def request_url(self, request, proxies):\n using_socks_proxy = proxy_scheme.startswith(\"socks\")\n \n url = request.path_url\n+ if url.startswith(\"//\"): # Don't confuse urllib3\n+ url = f\"/{url.lstrip('/')}\"\n+\n if is_proxied_http_request and not using_socks_proxy:\n url = urldefragauth(request.url)" }, { "filename": "tests/test_adapters.py", "status": "added", "additions": 8, "deletions": 0, "changes": 8, "patch": "@@ -0,0 +1,8 @@\n+import requests.adapters\n+\n+\n+def test_request_url_trims_leading_path_separators():\n+ \"\"\"See also https://github.com/psf/requests/issues/6643.\"\"\"\n+ a = requests.adapters.HTTPAdapter()\n+ p = requests.Request(method=\"GET\", url=\"http://127.0.0.1:10000//v:h\").prepare()\n+ assert \"/v:h\" == a.request_url(p, {})" } ], "reviews": [ { "id": 1894724059, "user": "user_0fa58b6f3572", "state": "COMMENTED", "body": null, "submitted_at": "2024-02-22T01:55:27+00:00" }, { "id": 1894741153, "user": "user_0fa58b6f3572", "state": "COMMENTED", "body": null, "submitted_at": "2024-02-22T02:18:04+00:00" }, { "id": 1894743966, "user": "user_0fa58b6f3572", "state": "COMMENTED", "body": null, "submitted_at": "2024-02-22T02:21:43+00:00" }, { "id": 1894751684, "user": "user_0fa58b6f3572", "state": "COMMENTED", "body": null, "submitted_at": "2024-02-22T02:32:04+00:00" }, { "id": 1895756007, "user": "user_0fa58b6f3572", "state": "COMMENTED", "body": null, "submitted_at": "2024-02-22T12:39:14+00:00" }, { "id": 1896264588, "user": "user_dbf2a999bd6d", "state": "COMMENTED", "body": null, "submitted_at": "2024-02-22T16:10:48+00:00" }, { "id": 1896266764, "user": "user_dbf2a999bd6d", "state": "APPROVED", "body": null, "submitted_at": "2024-02-22T16:11:44+00:00" }, { "id": 1896601426, "user": "user_0fa58b6f3572", "state": "COMMENTED", "body": null, "submitted_at": "2024-02-22T18:22:38+00:00" }, { "id": 1896817321, "user": "user_dbf2a999bd6d", "state": "COMMENTED", "body": null, "submitted_at": "2024-02-22T19:44:36+00:00" }, { "id": 1897227706, "user": "user_0fa58b6f3572", "state": "COMMENTED", "body": null, "submitted_at": "2024-02-23T00:49:39+00:00" } ], "review_comments": [ { "id": 1498520667, "user": "user_0fa58b6f3572", "body": "```suggestion\nimport requests.adapters\n```", "path": "tests/test_adapters.py", "line": null, "side": "RIGHT", "created_at": "2024-02-22T01:55:22+00:00" }, { "id": 1498532708, "user": "user_0fa58b6f3572", "body": "```suggestion\n a = requests.adapters.HTTPAdapter()\n```", "path": "tests/test_adapters.py", "line": null, "side": "RIGHT", "created_at": "2024-02-22T02:17:57+00:00" }, { "id": 1498534695, "user": "user_0fa58b6f3572", "body": "```suggestion\n assert \"/v:h\" == a.request_url(\"http://127.0.0.1:10000//v:h\", {})\n```", "path": "tests/test_adapters.py", "line": null, "side": "RIGHT", "created_at": "2024-02-22T02:21:39+00:00" }, { "id": 1498539954, "user": "user_0fa58b6f3572", "body": "```suggestion\n p = requests.Request(method=\"GET\", url=\"http://127.0.0.1:10000//v:h\").prepare()\n assert \"/v:h\" == a.request_url(p, {})\n```", "path": "tests/test_adapters.py", "line": null, "side": "RIGHT", "created_at": "2024-02-22T02:31:51+00:00" }, { "id": 1499181040, "user": "user_0fa58b6f3572", "body": "As mentioned on https://github.com/urllib3/urllib3/issues/3352 this could also be\n\n```python\nurl = f\"/{request.path_url.lstrip('/')}\"\n```\n\nI could benchmark these but I don't particularly care what the implementation is. I just threw this together to show that it can be fixed", "path": "src/requests/adapters.py", "line": null, "side": "RIGHT", "created_at": "2024-02-22T12:39:14+00:00" }, { "id": 1499501563, "user": "user_dbf2a999bd6d", "body": "It looks like the f-string (Python 3.9-3.12 tested) is ~4x faster but we're talking on the scale of nanoseconds so it's basically moot. I'd vote the f-string for readability, but don't have a strong opinion.", "path": "src/requests/adapters.py", "line": null, "side": "RIGHT", "created_at": "2024-02-22T16:10:48+00:00" }, { "id": 1499711431, "user": "user_0fa58b6f3572", "body": "Yeah, I'm also happy to shove this into a branch too like \n\n```python\nif path.startswith('//'):\n```\n\nTo make it clearer that we only care about the separator being repeated. What I want is clarity in the reader as to why we're doing this. My old school brain things the regexp is clearer and the f-string looks sus but that's just my opinion and I'm not holding it closely", "path": "src/requests/adapters.py", "line": null, "side": "RIGHT", "created_at": "2024-02-22T18:22:38+00:00" }, { "id": 1499848845, "user": "user_dbf2a999bd6d", "body": "Yeah, branching seems fine to me too.", "path": "src/requests/adapters.py", "line": null, "side": "RIGHT", "created_at": "2024-02-22T19:44:35+00:00" }, { "id": 1500110895, "user": "user_0fa58b6f3572", "body": "Did both (f string and branch)", "path": "src/requests/adapters.py", "line": null, "side": "RIGHT", "created_at": "2024-02-23T00:49:38+00:00" } ], "meta": { "languages": [ "py" ], "touches_tests": true, "review_state_summary": { "COMMENTED": 9, "APPROVED": 1 }, "meaningful_comment_count": 9, "has_approval": true, "has_changes_requested": false, "total_review_comments": 9 } } { "_id": "e33a38a85cecae58", "_schema_version": "1.0", "_cleaned_at": "2026-02-12T07:46:51.393484+00:00", "repo": "psf/requests", "repo_url": "https://github.com/psf/requests", "license_name": "Apache License 2.0", "license_spdx": "Apache-2.0", "pr_number": 6600, "title": "Add note on connection timeout being larger than specified. Fix #5773", "body": "[As requested](https://github.com/psf/requests/issues/5773#issuecomment-799787382), here's my take on a PR to improve documentation. I've tried to incorporate the [suggestions made by [USER_REDACTED] at a previous PR](https://github.com/psf/requests/pull/5776#discussion_r596043195), by [NAME_REDACTED] \"IPv4+IPv6\" particular case to a more general (and correct) \"multiple IPs\" scenario.\n\nIf approved, this PR will also fix #5760, and supersede PRs #5776 and #6597", "author": "user_5b66c2b56f87", "created_at": "2023-12-13T13:19:43+00:00", "merged_at": "2023-12-16T13:30:18+00:00", "base_branch": "main", "head_branch": "MestreLion-connection-timeout-note", "additions": 14, "deletions": 0, "changed_files": 1, "files": [ { "filename": "docs/user/advanced.rst", "status": "modified", "additions": 14, "deletions": 0, "changes": 14, "patch": "@@ -1122,4 +1122,18 @@ coffee.\n \n r = requests.get('https://github.com', timeout=None)\n \n+.. note:: The connect timeout applies to each connection attempt to an IP address.\n+ If multiple addresses exist for a domain name, the underlying ``urllib3`` will\n+ try each address sequentially until one successfully connects.\n+ This may lead to an effective total connection timeout *multiple* times longer\n+ than the specified time, e.g. an unresponsive server having both IPv4 and IPv6\n+ addresses will have its perceived timeout *doubled*, so take that into account\n+ when setting the connection timeout.\n+.. note:: Neither the connect nor read timeouts are `wall clock`_. This means\n+ that if you start a request, and look at the time, and then look at\n+ the time when the request finishes or times out, the real-world time\n+ may be greater than what you specified.\n+\n+\n+.. _`wall clock`: https://wiki.php.net/rfc/max_execution_wall_time\n .. _`connect()`: https://linux.die.net/man/2/connect" } ], "reviews": [ { "id": 1785178531, "user": "user_0fa58b6f3572", "state": "COMMENTED", "body": null, "submitted_at": "2023-12-16T13:26:09+00:00" }, { "id": 1785178796, "user": "user_0fa58b6f3572", "state": "COMMENTED", "body": null, "submitted_at": "2023-12-16T13:29:17+00:00" }, { "id": 1785178884, "user": "user_0fa58b6f3572", "state": "APPROVED", "body": null, "submitted_at": "2023-12-16T13:30:11+00:00" } ], "review_comments": [ { "id": 1428809820, "user": "user_0fa58b6f3572", "body": "This should be indented. It should all be indented to match the start of \"The\" on the previous line\n\n```suggestion\n If multiple addresses exist for a domain name, the underlying ``urllib3`` will\n try each address sequentially until one successfully connects.\n This may lead to an effective total connection timeout *multiple* times longer\n than the specified time, e.g. an unresponsive server having both IPv4 and IPv6\n addresses will have its perceived timeout *doubled*, so take that into account\n when setting the connection timeout.\n```", "path": "docs/user/advanced.rst", "line": null, "side": "RIGHT", "created_at": "2023-12-16T13:26:09+00:00" }, { "id": 1428810474, "user": "user_0fa58b6f3572", "body": "I would also suggest we add:\n\n```suggestion\n.. note:: Neither the connect nor read timeouts are `wall clock`_. This means\n that if you start a request, and look at the time, and then look at\n the time when the request finishes or times out, the real-world time\n may be greater than what you specified.\n\n.. _`wall clock`: https://wiki.php.net/rfc/max_execution_wall_time\n```", "path": "docs/user/advanced.rst", "line": 1136, "side": "RIGHT", "created_at": "2023-12-16T13:29:17+00:00" } ], "meta": { "languages": [ "rst" ], "touches_tests": false, "review_state_summary": { "COMMENTED": 2, "APPROVED": 1 }, "meaningful_comment_count": 2, "has_approval": true, "has_changes_requested": false, "total_review_comments": 2 } } { "_id": "5819f52704ede042", "_schema_version": "1.0", "_cleaned_at": "2026-02-12T07:46:51.394523+00:00", "repo": "psf/requests", "repo_url": "https://github.com/psf/requests", "license_name": "Apache License 2.0", "license_spdx": "Apache-2.0", "pr_number": 6589, "title": "Enhance `super_len` to count encoded bytes for str", "body": "This is a possible fix for issue #6586.\n\nI am not at all confident that this is an appropriate change for Requests. All of the unit tests pass locally for me (specifically `make ci`).", "author": "user_3f1e3970e9ae", "created_at": "2023-11-28T18:21:03+00:00", "merged_at": "2024-02-23T00:53:25+00:00", "base_branch": "main", "head_branch": "super_len_str_utf-8", "additions": 20, "deletions": 0, "changed_files": 2, "files": [ { "filename": "src/requests/utils.py", "status": "modified", "additions": 3, "deletions": 0, "changes": 3, "patch": "@@ -134,6 +134,9 @@ def super_len(o):\n total_length = None\n current_position = 0\n \n+ if isinstance(o, str):\n+ o = o.encode(\"utf-8\")\n+\n if hasattr(o, \"__len__\"):\n total_length = len(o)" }, { "filename": "tests/test_requests.py", "status": "modified", "additions": 17, "deletions": 0, "changes": 17, "patch": "@@ -1808,6 +1808,23 @@ def test_autoset_header_values_are_native(self, httpbin):\n \n assert p.headers[\"Content-Length\"] == length\n \n+ def test_content_length_for_bytes_data(self, httpbin):\n+ data = \"This is a string containing multi-byte UTF-8 ☃️\"\n+ encoded_data = data.encode(\"utf-8\")\n+ length = str(len(encoded_data))\n+ req = requests.Request(\"POST\", httpbin(\"post\"), data=encoded_data)\n+ p = req.prepare()\n+\n+ assert p.headers[\"Content-Length\"] == length\n+\n+ def test_content_length_for_string_data_counts_bytes(self, httpbin):\n+ data = \"This is a string containing multi-byte UTF-8 ☃️\"\n+ length = str(len(data.encode(\"utf-8\")))\n+ req = requests.Request(\"POST\", httpbin(\"post\"), data=data)\n+ p = req.prepare()\n+\n+ assert p.headers[\"Content-Length\"] == length\n+\n def test_nonhttp_schemes_dont_check_URLs(self):\n test_urls = (\n \"data:image/gif;base64,R0lGODlhAQABAHAAACH5BAUAAAAALAAAAAABAAEAAAICRAEAOw==\"," } ], "reviews": [ { "id": 1755293955, "user": "user_0fa58b6f3572", "state": "CHANGES_REQUESTED", "body": null, "submitted_at": "2023-11-29T13:38:48+00:00" }, { "id": 1755335199, "user": "user_3f1e3970e9ae", "state": "COMMENTED", "body": null, "submitted_at": "2023-11-29T13:57:59+00:00" }, { "id": 1755377661, "user": "user_0fa58b6f3572", "state": "COMMENTED", "body": null, "submitted_at": "2023-11-29T14:16:41+00:00" }, { "id": 1896890206, "user": "user_dbf2a999bd6d", "state": "APPROVED", "body": "I'll leave any final comments and merging to [USER_REDACTED] but this looks reasonable to me. Thanks [USER_REDACTED]!", "submitted_at": "2024-02-22T20:30:04+00:00" }, { "id": 1897230775, "user": "user_0fa58b6f3572", "state": "APPROVED", "body": null, "submitted_at": "2024-02-23T00:53:03+00:00" } ], "review_comments": [ { "id": 1409296382, "user": "user_0fa58b6f3572", "body": "More simply this can be an if without changing the following conditions and just set `o = o.encode(...)` in the block then let the rest of the logic work. As it will hit another condition which will get it's length", "path": "src/requests/utils.py", "line": 137, "side": "RIGHT", "created_at": "2023-11-29T13:38:39+00:00" }, { "id": 1409321632, "user": "user_3f1e3970e9ae", "body": "Sounds fine to me. My usual workflow would be to rewrite my commit and do a force push to my branch (in my fork). Is this ok or would you prefer a separate commit for the change?", "path": "src/requests/utils.py", "line": 137, "side": "RIGHT", "created_at": "2023-11-29T13:57:59+00:00" }, { "id": 1409347860, "user": "user_0fa58b6f3572", "body": "That's my workflow as well. Feel free to do that", "path": "src/requests/utils.py", "line": 137, "side": "RIGHT", "created_at": "2023-11-29T14:16:40+00:00" } ], "meta": { "languages": [ "py" ], "touches_tests": true, "review_state_summary": { "CHANGES_REQUESTED": 1, "COMMENTED": 2, "APPROVED": 2 }, "meaningful_comment_count": 3, "has_approval": true, "has_changes_requested": true, "total_review_comments": 3 } } { "_id": "5fcd4a7ce90c08e4", "_schema_version": "1.0", "_cleaned_at": "2026-02-12T07:46:51.396174+00:00", "repo": "psf/requests", "repo_url": "https://github.com/psf/requests", "license_name": "Apache License 2.0", "license_spdx": "Apache-2.0", "pr_number": 6583, "title": "Fix broken links in docs", "body": "Hi,\n\nI noticed a broken link to rfc2988 in the [timeout section of the docs](https://requests.readthedocs.io/en/latest/user/advanced/#timeouts) and thought I would fix it.\n\nWhile doing that, I thought I would run the sphinx `linkcheck` builder to check for other broken links and fix them.\n\nThere were a few, some where I've 'fixed'/updated the link are hopefully uncontroversial. \n\nSome are more controversial - removing sections written by [NAME_REDACTED] requests that now have dead links, removing talks with dead links to slides, removing people's now dead GitHub account links. I wasn't sure what the right thing to do here was, but I went with my intuition, and kept commits pretty discrete so I can drop/amend them if the maintainers want me to do something different. If some are controversial enough to slow down the PR, I can always pull out the uncontroversial ones into their own PR for faster merging.", "author": "user_623591bfa86c", "created_at": "2023-11-24T11:23:44+00:00", "merged_at": "2024-02-23T11:30:46+00:00", "base_branch": "main", "head_branch": "fix-broken-links", "additions": 5, "deletions": 8, "changed_files": 4, "files": [ { "filename": "AUTHORS.rst", "status": "modified", "additions": 1, "deletions": 1, "changes": 2, "patch": "@@ -8,7 +8,7 @@ Keepers of the [NAME_REDACTED] of Crystals\n ````````````````````````````\n-- [NAME_REDACTED] <[EMAIL_REDACTED]> [CONTRIBUTOR_REDACTED], reluctant Keeper of the Master Crystal.\n+- [NAME_REDACTED] <[EMAIL_REDACTED]> [CONTRIBUTOR_REDACTED], reluctant Keeper of the Master Crystal.\n - [NAME_REDACTED] <[EMAIL_REDACTED]> [CONTRIBUTOR_REDACTED]\n - [NAME_REDACTED] <[EMAIL_REDACTED]> [CONTRIBUTOR_REDACTED]" }, { "filename": "HISTORY.md", "status": "modified", "additions": 1, "deletions": 1, "changes": 2, "patch": "@@ -14,7 +14,7 @@ dev\n forwarding of `Proxy-Authorization` headers to destination servers when\n following HTTPS redirects.\n \n- When proxies are defined with user info (https://user:pass@proxy:8080), Requests\n+ When proxies are defined with user info (`https://user:pass@proxy:8080`), Requests\n will construct a `Proxy-Authorization` header that is attached to the request to\n authenticate with the proxy." }, { "filename": "docs/user/advanced.rst", "status": "modified", "additions": 3, "deletions": 3, "changes": 6, "patch": "@@ -291,7 +291,7 @@ versions of Requests.\n For the sake of security we recommend upgrading certifi frequently!\n \n .. _HTTP persistent connection: https://en.wikipedia.org/wiki/HTTP_persistent_connection\n-.. _connection pooling: https://urllib3.readthedocs.io/en/latest/reference/index.html#module-urllib3.connectionpool\n+.. _connection pooling: https://urllib3.readthedocs.io/en/latest/reference/urllib3.connectionpool.html\n .. _certifi: https://certifiio.readthedocs.io/\n .. _Mozilla trust store: https://hg.mozilla.org/mozilla-central/raw-file/tip/security/nss/lib/ckfw/builtins/certdata.txt\n \n@@ -948,7 +948,7 @@ [NAME_REDACTED] HTTP APIs feature Link headers. They make APIs more self describing and\n discoverable.\n \n-GitHub uses these for `pagination `_\n+GitHub uses these for `pagination `_\n in their API, for example::\n \n >>> url = 'https://api.github.com/users/kennethreitz/repos?page=1&per_page=10'\n@@ -1099,7 +1099,7 @@ The **connect** timeout is the number of seconds Requests will wait for your\n client to establish a connection to a remote machine (corresponding to the\n `connect()`_) call on the socket. It's a good practice to set connect timeouts\n to slightly larger than a multiple of 3, which is the default `TCP packet\n-retransmission window `_.\n+retransmission window `_.\n \n Once your client has connected to the server and sent the HTTP request, the\n **read** timeout is the number of seconds the client will wait for the server" }, { "filename": "docs/user/quickstart.rst", "status": "modified", "additions": 0, "deletions": 3, "changes": 3, "patch": "@@ -568,6 +568,3 @@ All exceptions that Requests explicitly raises inherit from\n -----------------------\n \n Ready for more? Check out the :ref:`advanced ` section.\n-\n-\n-If you're on the job market, consider taking `this programming quiz `_. A substantial donation will be made to this project, if you find a job through this platform." } ], "reviews": [ { "id": 1747785992, "user": "user_623591bfa86c", "state": "COMMENTED", "body": null, "submitted_at": "2023-11-24T11:25:12+00:00" }, { "id": 1747989322, "user": "user_0fa58b6f3572", "state": "COMMENTED", "body": null, "submitted_at": "2023-11-24T13:52:52+00:00" }, { "id": 1747992792, "user": "user_0fa58b6f3572", "state": "COMMENTED", "body": null, "submitted_at": "2023-11-24T13:55:17+00:00" }, { "id": 1748201605, "user": "user_623591bfa86c", "state": "COMMENTED", "body": null, "submitted_at": "2023-11-24T16:31:47+00:00" }, { "id": 1748203081, "user": "user_623591bfa86c", "state": "COMMENTED", "body": null, "submitted_at": "2023-11-24T16:33:18+00:00" }, { "id": 1844811166, "user": "user_ab2c821ca104", "state": "APPROVED", "body": "That's great! Thank you, [USER_REDACTED]!\nI believe these changes are ready to be merged.", "submitted_at": "2024-01-25T22:47:48+00:00" }, { "id": 1844844142, "user": "user_ab2c821ca104", "state": "COMMENTED", "body": null, "submitted_at": "2024-01-25T23:10:48+00:00" }, { "id": 1845312906, "user": "user_623591bfa86c", "state": "COMMENTED", "body": null, "submitted_at": "2024-01-26T09:02:30+00:00" }, { "id": 1897910085, "user": "user_0fa58b6f3572", "state": "APPROVED", "body": null, "submitted_at": "2024-02-23T11:30:30+00:00" } ], "review_comments": [ { "id": 1404248901, "user": "user_623591bfa86c", "body": "I believe this is a similar app by [NAME_REDACTED], but it's python 2.5 (long deprecated), and doesn't work on the most recent version of iOS anyway.\n\nI was tempted to just delete the whole 'Python for iOS' section here, but I thought I would see what a maintainer thought before deleting the whole section.", "path": "docs/community/out-there.rst", "line": null, "side": "RIGHT", "created_at": "2023-11-24T11:25:11+00:00" }, { "id": 1404377720, "user": "user_0fa58b6f3572", "body": "This is actually an easy one to fix: https://issackelly.github.com/Consuming-Web-APIs-with-Python-Talk/slides/slides.html is from the very old GitHub pages and they switched the domain from `github.com` to `github.io`", "path": "docs/community/out-there.rst", "line": null, "side": "LEFT", "created_at": "2023-11-24T13:52:52+00:00" }, { "id": 1404379931, "user": "user_0fa58b6f3572", "body": "I'd rather not remove these. I don't think there's value in removing these links to folks even if they've deleted their account.", "path": "AUTHORS.rst", "line": null, "side": "LEFT", "created_at": "2023-11-24T13:55:17+00:00" }, { "id": 1404515378, "user": "user_623591bfa86c", "body": "ah, can't believe I didn't think of that 🤦 Thanks for finding it!\n\nI've updated the commit to 'fix' it to the correct link rather than removing the line.", "path": "docs/community/out-there.rst", "line": null, "side": "LEFT", "created_at": "2023-11-24T16:31:47+00:00" }, { "id": 1404516420, "user": "user_623591bfa86c", "body": "Fair enough - I've removed all cases like this from the relevant commit.\n\nI've left in the case where the GitHub user has changed, but let me know if you want me to remove that too.", "path": "AUTHORS.rst", "line": null, "side": "LEFT", "created_at": "2023-11-24T16:33:18+00:00" }, { "id": 1467061330, "user": "user_ab2c821ca104", "body": "> It's a good practice to set connect timeouts to slightly larger than a multiple of 3, which is the default [TCP packet retransmission window](https://datatracker.ietf.org/doc/html/rfc2988).\n\nDespite the fact I already approved this PR, there's still a room for improvement.\n[RFC 2988](https://datatracker.ietf.org/doc/html/rfc2988) was obsoleted by [RFC 6298](https://datatracker.ietf.org/doc/html/rfc6298), so this link might be updated even further, but it would require additional changes since newer RFC makes the whole statement not correct due to [this change](https://datatracker.ietf.org/doc/html/rfc6298#section-7).\nSo this might be handled in an additional PR.", "path": "docs/user/advanced.rst", "line": 1102, "side": "RIGHT", "created_at": "2024-01-25T23:10:48+00:00" }, { "id": 1467381716, "user": "user_623591bfa86c", "body": "Thanks - seems like a sensible comment, agree it makes sense for an additional PR.", "path": "docs/user/advanced.rst", "line": 1102, "side": "RIGHT", "created_at": "2024-01-26T09:02:30+00:00" } ], "meta": { "languages": [ "md", "rst" ], "touches_tests": false, "review_state_summary": { "COMMENTED": 7, "APPROVED": 2 }, "meaningful_comment_count": 7, "has_approval": true, "has_changes_requested": false, "total_review_comments": 7 } } { "_id": "d074ad4096637c58", "_schema_version": "1.0", "_cleaned_at": "2026-02-12T07:46:51.397675+00:00", "repo": "psf/requests", "repo_url": "https://github.com/psf/requests", "license_name": "Apache License 2.0", "license_spdx": "Apache-2.0", "pr_number": 6527, "title": "Autoclose specific issue templates", "body": "We spend a fair amount of time closing issues because people don't read the template closely or understand what they're being told. Let's take advantage of being able to auto-label an issue based on the template and then trigger a workflow to auto-magically close the issue with a message and lock the issue.", "author": "user_0fa58b6f3572", "created_at": "2023-09-13T14:36:49+00:00", "merged_at": "2023-10-11T16:29:20+00:00", "base_branch": "main", "head_branch": "update-templates", "additions": 39, "deletions": 0, "changed_files": 3, "files": [ { "filename": ".github/ISSUE_TEMPLATE/Custom.md", "status": "modified", "additions": 3, "deletions": 0, "changes": 3, "patch": "@@ -1,6 +1,9 @@\n ---\n name: Request for Help\n about: Guidance on using Requests.\n+labels:\n+- \"Question/Not a bug\"\n+- \"actions/autoclose-qa\"\n \n ---" }, { "filename": ".github/ISSUE_TEMPLATE/Feature_request.md", "status": "modified", "additions": 3, "deletions": 0, "changes": 3, "patch": "@@ -1,6 +1,9 @@\n ---\n name: Feature request\n about: Suggest an idea for this project\n+labels:\n+- \"[NAME_REDACTED]\"\n+- \"actions/autoclose-feat\"\n \n ---" }, { "filename": ".github/workflows/close-issues.yml", "status": "added", "additions": 33, "deletions": 0, "changes": 33, "patch": "@@ -0,0 +1,33 @@\n+name: '[NAME_REDACTED]'\n+\n+on:\n+ issues:\n+ types:\n+ - labeled\n+\n+permissions:\n+ issues: write\n+\n+jobs:\n+ close_qa:\n+ if: github.event.label.name == 'actions/autoclose-qa'\n+ runs-on: ubuntu-latest\n+ steps:\n+ - env:\n+ ISSUE_URL: ${{ github.event.issue.html_url }}\n+ run: |\n+ gh issue close $ISSUE_URL \\\n+ --comment \"As described in the template, we won't be able to answer questions on this issue tracker. Please use [Stack Overflow](https://stackoverflow.com/)\" \\\n+ --reason completed\n+ gh issue lock $ISSUE_URL --reason off_topic\n+ close_feature_request:\n+ if: github.event.label.name == 'actions/autoclose-feat'\n+ runs-on: ubuntu-latest\n+ steps:\n+ - env:\n+ ISSUE_URL: ${{ github.event.issue.html_url }}\n+ run: |\n+ gh issue close $ISSUE_URL \\\n+ --comment \"As described in the template, Requests is not accepting feature requests\" \\\n+ --reason \"not planned\"\n+ gh issue lock $ISSUE_URL --reason off_topic" } ], "reviews": [ { "id": 1631822927, "user": "user_dbf2a999bd6d", "state": "COMMENTED", "body": "Two minor comments, otherwise looks good.", "submitted_at": "2023-09-19T16:22:59+00:00" }, { "id": 1641078032, "user": "user_0fa58b6f3572", "state": "COMMENTED", "body": null, "submitted_at": "2023-09-24T15:19:47+00:00" }, { "id": 1671225473, "user": "user_0fa58b6f3572", "state": "COMMENTED", "body": null, "submitted_at": "2023-10-11T13:20:51+00:00" }, { "id": 1671831769, "user": "user_dbf2a999bd6d", "state": "APPROVED", "body": null, "submitted_at": "2023-10-11T16:28:10+00:00" } ], "review_comments": [ { "id": 1329187398, "user": "user_dbf2a999bd6d", "body": "I'm not familiar, what is `MY_TOKEN` in this case? Should this be `GITHUB_TOKEN` or were you planning on adding a separate token specifically for this workflow?", "path": ".github/workflows/close-issues.yml", "line": null, "side": "RIGHT", "created_at": "2023-09-18T19:29:12+00:00" }, { "id": 1329188753, "user": "user_dbf2a999bd6d", "body": "nit on phrasing.\n```suggestion\n --comment \"As described in the template, we won't be able to answer questions on this issue tracker. Please use [Stack Overflow](https://stackoverflow.com/)\" \\\n```", "path": ".github/workflows/close-issues.yml", "line": null, "side": "RIGHT", "created_at": "2023-09-18T19:30:51+00:00" }, { "id": 1335203087, "user": "user_0fa58b6f3572", "body": "Ah yeah, I based this heavily off the actions docs and didn't look terribly closely at this. I don't think it's necessary honestly", "path": ".github/workflows/close-issues.yml", "line": null, "side": "RIGHT", "created_at": "2023-09-24T15:19:47+00:00" }, { "id": 1355002832, "user": "user_0fa58b6f3572", "body": "Removed those", "path": ".github/workflows/close-issues.yml", "line": null, "side": "RIGHT", "created_at": "2023-10-11T13:20:51+00:00" } ], "meta": { "languages": [ "md", "yml" ], "touches_tests": false, "review_state_summary": { "COMMENTED": 3, "APPROVED": 1 }, "meaningful_comment_count": 4, "has_approval": true, "has_changes_requested": false, "total_review_comments": 4 } } { "_id": "a02a94c08dd90291", "_schema_version": "1.0", "_cleaned_at": "2026-02-12T07:46:51.398677+00:00", "repo": "psf/requests", "repo_url": "https://github.com/psf/requests", "license_name": "Apache License 2.0", "license_spdx": "Apache-2.0", "pr_number": 6436, "title": "v2.30.0", "body": "2.30.0 (2023-05-03)\n-------------------\n\n**Dependencies**\n- ⚠️ Added support for urllib3 2.0. ⚠️\n\n This may contain minor breaking changes so we advise careful testing and\n reviewing https://urllib3.readthedocs.io/en/latest/v2-migration-guide.html\n prior to upgrading.\n\n Users who wish to stay on urllib3 1.x can pin to `urllib3<2`.", "author": "user_dbf2a999bd6d", "created_at": "2023-05-03T15:27:01+00:00", "merged_at": "2023-05-03T15:39:44+00:00", "base_branch": "main", "head_branch": "v2.30.0", "additions": 19, "deletions": 7, "changed_files": 4, "files": [ { "filename": "HISTORY.md", "status": "modified", "additions": 12, "deletions": 0, "changes": 12, "patch": "@@ -6,6 +6,18 @@ dev\n \n - \\[Short description of non-trivial change.\\]\n \n+2.30.0 (2023-05-03)\n+-------------------\n+\n+**Dependencies**\n+- ⚠️ Added support for urllib3 2.0. ⚠️\n+\n+ This may contain minor breaking changes so we advise careful testing and\n+ reviewing https://urllib3.readthedocs.io/en/latest/v2-migration-guide.html\n+ prior to upgrading.\n+\n+ Users who wish to stay on urllib3 1.x can pin to `urllib3<2`.\n+\n 2.29.0 (2023-04-26)\n -------------------" }, { "filename": "requests/__init__.py", "status": "modified", "additions": 4, "deletions": 4, "changes": 8, "patch": "@@ -66,10 +66,10 @@ def check_compatibility(urllib3_version, chardet_version, charset_normalizer_ver\n # Check urllib3 for compatibility.\n major, minor, patch = urllib3_version # noqa: F811\n major, minor, patch = int(major), int(minor), int(patch)\n- # urllib3 >= 1.21.1, <= 1.26\n- assert major == 1\n- assert minor >= 21\n- assert minor <= 26\n+ # urllib3 >= 1.21.1\n+ assert major >= 1\n+ if major == 1:\n+ assert minor >= 21\n \n # Check charset_normalizer for compatibility.\n if chardet_version:" }, { "filename": "requests/__version__.py", "status": "modified", "additions": 2, "deletions": 2, "changes": 4, "patch": "@@ -5,8 +5,8 @@\n __title__ = \"requests\"\n __description__ = \"Python HTTP for Humans.\"\n __url__ = \"https://requests.readthedocs.io\"\n-__version__ = \"2.29.0\"\n-__build__ = 0x022900\n+__version__ = \"2.30.0\"\n+__build__ = 0x023000\n __author__ = \"[NAME_REDACTED]\"\n __author_email__ = \"[EMAIL_REDACTED]\"\n __license__ = \"Apache 2.0\"" }, { "filename": "setup.py", "status": "modified", "additions": 1, "deletions": 1, "changes": 2, "patch": "@@ -61,7 +61,7 @@ def run_tests(self):\n requires = [\n \"charset_normalizer>=2,<4\",\n \"idna>=2.5,<4\",\n- \"urllib3>=1.21.1,<1.27\",\n+ \"urllib3>=1.21.1,<3\",\n \"certifi>=2017.4.17\",\n ]\n test_requirements = [" } ], "reviews": [ { "id": 1411163825, "user": "user_c900b4a480af", "state": "APPROVED", "body": null, "submitted_at": "2023-05-03T15:29:03+00:00" }, { "id": 1411186494, "user": "user_b08fb5f52ea1", "state": "APPROVED", "body": ":shipit:", "submitted_at": "2023-05-03T15:37:29+00:00" } ], "review_comments": [ { "id": 1183862162, "user": "user_b08fb5f52ea1", "body": "<3", "path": "setup.py", "line": 64, "side": "RIGHT", "created_at": "2023-05-03T15:37:22+00:00" } ], "meta": { "languages": [ "md", "py" ], "touches_tests": false, "review_state_summary": { "APPROVED": 2 }, "meaningful_comment_count": 0, "has_approval": true, "has_changes_requested": false, "total_review_comments": 1 } } { "_id": "1012b6cf9c4f1a0d", "_schema_version": "1.0", "_cleaned_at": "2026-02-12T07:46:51.399447+00:00", "repo": "psf/requests", "repo_url": "https://github.com/psf/requests", "license_name": "Apache License 2.0", "license_spdx": "Apache-2.0", "pr_number": 6329, "title": "v2.28.2", "body": "2.28.2 (2023-01-12)\n-------------------\n\n**Dependencies**\n\n- Requests now supports charset\\_normalizer 3.x. (#6261)\n\n**Bugfixes**\n\n- Updated MissingSchema exception to suggest https scheme rather than http. (#6188)", "author": "user_dbf2a999bd6d", "created_at": "2023-01-11T22:39:35+00:00", "merged_at": "2023-01-12T16:16:12+00:00", "base_branch": "main", "head_branch": "v2.28.2", "additions": 14, "deletions": 3, "changed_files": 2, "files": [ { "filename": "HISTORY.md", "status": "modified", "additions": 11, "deletions": 0, "changes": 11, "patch": "@@ -7,6 +7,17 @@ dev\n - \\[Short description of non-trivial change.\\]\n \n \n+2.28.2 (2023-01-12)\n+-------------------\n+\n+**Dependencies**\n+\n+- Requests now supports charset\\_normalizer 3.x. (#6261)\n+\n+**Bugfixes**\n+\n+- [NAME_REDACTED] exception to suggest https scheme rather than http. (#6188)\n+\n 2.28.1 (2022-06-29)\n -------------------" }, { "filename": "requests/__version__.py", "status": "modified", "additions": 3, "deletions": 3, "changes": 6, "patch": "@@ -5,10 +5,10 @@\n __title__ = \"requests\"\n __description__ = \"Python HTTP for Humans.\"\n __url__ = \"https://requests.readthedocs.io\"\n-__version__ = \"2.28.1\"\n-__build__ = 0x022801\n+__version__ = \"2.28.2\"\n+__build__ = 0x022802\n __author__ = \"[NAME_REDACTED]\"\n __author_email__ = \"[EMAIL_REDACTED]\"\n __license__ = \"Apache 2.0\"\n-__copyright__ = \"Copyright 2022 [NAME_REDACTED]\"\n+__copyright__ = \"[NAME_REDACTED]\"\n __cake__ = \"\\u2728 \\U0001f370 \\u2728\"" } ], "reviews": [ { "id": 1244716604, "user": "user_b08fb5f52ea1", "state": "APPROVED", "body": "LGTM", "submitted_at": "2023-01-11T22:40:56+00:00" } ], "review_comments": [ { "id": 1067529571, "user": "user_b08fb5f52ea1", "body": "🥳", "path": "requests/__version__.py", "line": 13, "side": "LEFT", "created_at": "2023-01-11T22:40:47+00:00" } ], "meta": { "languages": [ "md", "py" ], "touches_tests": false, "review_state_summary": { "APPROVED": 1 }, "meaningful_comment_count": 0, "has_approval": true, "has_changes_requested": false, "total_review_comments": 1 } } { "_id": "7b178dbd0cc52ce5", "_schema_version": "1.0", "_cleaned_at": "2026-02-12T07:46:51.399447+00:00", "repo": "psf/requests", "repo_url": "https://github.com/psf/requests", "license_name": "Apache License 2.0", "license_spdx": "Apache-2.0", "pr_number": 6157, "title": "Add GitHub action to automate linting", "body": "This was intended to be a follow up to #6095 but got lost in the shuffle post PyCon. It's currently failing on a single line change that's addressed in #6154. Once that's merged this should be ready to merge and ensure we don't introduce any future inconsistencies.", "author": "user_dbf2a999bd6d", "created_at": "2022-06-08T04:19:31+00:00", "merged_at": "2022-06-08T19:11:11+00:00", "base_branch": "main", "head_branch": "lint", "additions": 16, "deletions": 0, "changed_files": 1, "files": [ { "filename": ".github/workflows/lint.yml", "status": "added", "additions": 16, "deletions": 0, "changes": 16, "patch": "@@ -0,0 +1,16 @@\n+name: Lint code\n+\n+on:\n+ push:\n+ pull_request:\n+\n+jobs:\n+ lint:\n+ runs-on: ubuntu-20.04\n+\n+ steps:\n+ - uses: actions/checkout@v3\n+ - name: Set up Python\n+ uses: actions/setup-python@v3\n+ - name: Run pre-commit\n+ uses: pre-commit/action@v3.0.0" } ], "reviews": [ { "id": 1000278482, "user": "user_b08fb5f52ea1", "state": "APPROVED", "body": "Looks good, one thought so you won't need to modify config in the future.", "submitted_at": "2022-06-08T18:55:00+00:00" }, { "id": 1000286602, "user": "user_dbf2a999bd6d", "state": "COMMENTED", "body": null, "submitted_at": "2022-06-08T18:59:51+00:00" } ], "review_comments": [ { "id": 892750749, "user": "user_b08fb5f52ea1", "body": "Thoughts on following pre-commit's example config and use setup-python without specifying a Python version?", "path": ".github/workflows/lint.yml", "line": null, "side": "RIGHT", "created_at": "2022-06-08T18:54:28+00:00" }, { "id": 892756299, "user": "user_dbf2a999bd6d", "body": "Fine by me, I'd brought this over from other projects but we can switch to `actions/setup-python@v3` per their Readme.", "path": ".github/workflows/lint.yml", "line": null, "side": "RIGHT", "created_at": "2022-06-08T18:59:51+00:00" } ], "meta": { "languages": [ "yml" ], "touches_tests": false, "review_state_summary": { "APPROVED": 1, "COMMENTED": 1 }, "meaningful_comment_count": 2, "has_approval": true, "has_changes_requested": false, "total_review_comments": 2 } } { "_id": "beb64c49747145b5", "_schema_version": "1.0", "_cleaned_at": "2026-02-12T07:46:51.401488+00:00", "repo": "psf/requests", "repo_url": "https://github.com/psf/requests", "license_name": "Apache License 2.0", "license_spdx": "Apache-2.0", "pr_number": 6156, "title": "v2.28.0", "body": "2.28.0 (2022-06-09)\n-------------------\n\n**Deprecations**\n\n- ⚠️ Requests has officially dropped support for Python 2.7. ⚠️ (#6091)\n- Requests has officially dropped support for Python 3.6 (including pypy3). (#6091)\n\n**Improvements**\n\n- Wrap JSON parsing issues in Request's JSONDecodeError for payloads without\n an encoding to make `json()` API consistent. (#6097)\n- Parse header components consistently, raising an InvalidHeader error in\n all invalid cases. (#6154)\n- Added provisional 3.11 support with current beta build. (#6155)\n- Requests got a makeover and we decided to paint it black. (#6095)\n\n**Bugfixes**\n\n- Fixed bug where setting `CURL_CA_BUNDLE` to an empty string would disable\n cert verification. All Requests 2.x versions before 2.28.0 are affected. (#6074)\n- Fixed urllib3 exception leak, wrapping `urllib3.exceptions.SSLError` with\n `requests.exceptions.SSLError` for `content` and `iter_content`. (#6057)\n- Fixed issue where invalid Windows registry entires caused proxy resolution\n to raise an exception rather than ignoring the entry. (#6149)\n- Fixed issue where entire payload could be included in the error message for\n JSONDecodeError. (#6079", "author": "user_dbf2a999bd6d", "created_at": "2022-06-08T04:10:18+00:00", "merged_at": "2022-06-09T14:42:10+00:00", "base_branch": "main", "head_branch": "v2.28.0", "additions": 26, "deletions": 7, "changed_files": 2, "files": [ { "filename": "HISTORY.md", "status": "modified", "additions": 24, "deletions": 5, "changes": 29, "patch": "@@ -6,15 +6,34 @@ dev\n \n - \\[Short description of non-trivial change.\\]\n \n-**Bugfixes**\n \n-- Fixed urllib3 exception leak, wrapping `urllib3.exceptions.SSLError` with\n- `requests.exceptions.SSLError` for `content` and `iter_content`.\n+2.28.0 (2022-06-09)\n+-------------------\n \n **Deprecations**\n \n-- ⚠️ Requests has officially dropped support for Python 2.7. ⚠️\n-- Requests has officially dropped support for Python 3.6 (including pypy3).\n+- ⚠️ Requests has officially dropped support for Python 2.7. ⚠️ (#6091)\n+- Requests has officially dropped support for Python 3.6 (including pypy3.6). (#6091)\n+\n+**Improvements**\n+\n+- [NAME_REDACTED] parsing issues in Request's JSONDecodeError for payloads without\n+ an encoding to make `json()` API consistent. (#6097)\n+- Parse header components consistently, raising an InvalidHeader error in\n+ all invalid cases. (#6154)\n+- Added provisional 3.11 support with current beta build. (#6155)\n+- Requests got a makeover and we decided to paint it black. (#6095)\n+\n+**Bugfixes**\n+\n+- Fixed bug where setting `CURL_CA_BUNDLE` to an empty string would disable\n+ cert verification. All Requests 2.x versions before 2.28.0 are affected. (#6074)\n+- Fixed urllib3 exception leak, wrapping `urllib3.exceptions.SSLError` with\n+ `requests.exceptions.SSLError` for `content` and `iter_content`. (#6057)\n+- Fixed issue where invalid Windows registry entires caused proxy resolution\n+ to raise an exception rather than ignoring the entry. (#6149)\n+- Fixed issue where entire payload could be included in the error message for\n+ JSONDecodeError. (#6036)\n \n 2.27.1 (2022-01-05)\n -------------------" }, { "filename": "requests/__version__.py", "status": "modified", "additions": 2, "deletions": 2, "changes": 4, "patch": "@@ -5,8 +5,8 @@\n __title__ = \"requests\"\n __description__ = \"Python HTTP for Humans.\"\n __url__ = \"https://requests.readthedocs.io\"\n-__version__ = \"2.27.1\"\n-__build__ = 0x022701\n+__version__ = \"2.28.0\"\n+__build__ = 0x022800\n __author__ = \"[NAME_REDACTED]\"\n __author_email__ = \"[EMAIL_REDACTED]\"\n __license__ = \"Apache 2.0\"" } ], "reviews": [ { "id": 1000626864, "user": "user_b08fb5f52ea1", "state": "APPROVED", "body": "So much awesome in this release!!! :shipit::rocket::sparkles::tada:", "submitted_at": "2022-06-09T01:51:44+00:00" }, { "id": 1000643445, "user": "user_dbf2a999bd6d", "state": "COMMENTED", "body": null, "submitted_at": "2022-06-09T02:27:03+00:00" }, { "id": 1000643696, "user": "user_dbf2a999bd6d", "state": "COMMENTED", "body": null, "submitted_at": "2022-06-09T02:27:33+00:00" } ], "review_comments": [ { "id": 893001188, "user": "user_b08fb5f52ea1", "body": "Thoughts on moving these to the top under a section \"Breaking Changes\" or \"Removals\"?", "path": "HISTORY.md", "line": null, "side": "RIGHT", "created_at": "2022-06-09T01:51:10+00:00" }, { "id": 893001255, "user": "user_b08fb5f52ea1", "body": "Remember to update this if you don't release today.", "path": "HISTORY.md", "line": null, "side": "RIGHT", "created_at": "2022-06-09T01:51:21+00:00" }, { "id": 893014397, "user": "user_dbf2a999bd6d", "body": "Yeah, that sounds fine. We've historically had deprecations at the bottom but I'm fine moving them up for visibility.", "path": "HISTORY.md", "line": null, "side": "RIGHT", "created_at": "2022-06-09T02:27:03+00:00" }, { "id": 893014600, "user": "user_dbf2a999bd6d", "body": "Yep, I'll move it to tomorrow. No ones getting paged tonight 😁", "path": "HISTORY.md", "line": null, "side": "RIGHT", "created_at": "2022-06-09T02:27:33+00:00" } ], "meta": { "languages": [ "md", "py" ], "touches_tests": false, "review_state_summary": { "APPROVED": 1, "COMMENTED": 2 }, "meaningful_comment_count": 4, "has_approval": true, "has_changes_requested": false, "total_review_comments": 4 } } { "_id": "0923dcfc060cf3ae", "_schema_version": "1.0", "_cleaned_at": "2026-02-12T07:46:51.403890+00:00", "repo": "psf/requests", "repo_url": "https://github.com/psf/requests", "license_name": "Apache License 2.0", "license_spdx": "Apache-2.0", "pr_number": 6091, "title": "Remove support for Python 2.7, 3.6 and Pypy3.6", "body": "This PR is a proposal to officially remove support for Python 2.7 as discussed in #6023. The next minor release (Requests 2.28.0) will no longer provide support for any of the end of life Python runtimes. Users are encouraged to upgrade to Python 3.8 or later. If you're unable to do so, we'd recommend pinning to `requests<2.28`.\n\nThis will be the first of a few PRs that will be doing some general code clean up now that we're moving to a Python 3-only code base. I'll post the others as drafts shortly.", "author": "user_dbf2a999bd6d", "created_at": "2022-03-23T00:27:13+00:00", "merged_at": "2022-03-25T16:50:34+00:00", "base_branch": "main", "head_branch": "halve_it", "additions": 141, "deletions": 180, "changed_files": 19, "files": [ { "filename": ".github/workflows/run-tests.yml", "status": "modified", "additions": 2, "deletions": 5, "changes": 7, "patch": "@@ -9,14 +9,11 @@ jobs:\n strategy:\n fail-fast: false\n matrix:\n- python-version: [\"2.7\", \"3.6\", \"3.7\", \"3.8\", \"3.9\", \"3.10\"]\n+ python-version: [\"3.7\", \"3.8\", \"3.9\", \"3.10\"]\n os: [ubuntu-18.04, macOS-latest, windows-latest]\n include:\n- # pypy3 on Mac OS currently fails trying to compile\n+ # pypy-3.7 on Mac OS currently fails trying to compile\n # brotlipy. Moving pypy3 to only test linux.\n- - python-version: pypy3\n- os: ubuntu-latest\n- experimental: false\n - python-version: pypy-3.7\n os: ubuntu-latest\n experimental: false" }, { "filename": "HISTORY.md", "status": "modified", "additions": 5, "deletions": 0, "changes": 5, "patch": "@@ -11,6 +11,11 @@ dev\n - Fixed urllib3 exception leak, wrapping `urllib3.exceptions.SSLError` with\n `requests.exceptions.SSLError` for `content` and `iter_content`.\n \n+**Deprecations**\n+\n+- ⚠️ Requests has officially dropped support for Python 2.7. ⚠️\n+- Requests has officially dropped support for Python 3.6 (including pypy3).\n+\n 2.27.1 (2022-01-05)\n -------------------" }, { "filename": "README.md", "status": "modified", "additions": 1, "deletions": 1, "changes": 2, "patch": "@@ -33,7 +33,7 @@ Requests is available on PyPI:\n $ python -m pip install requests\n ```\n \n-Requests officially supports Python 2.7 & 3.6+.\n+Requests officially supports Python 3.7+.\n \n ## [NAME_REDACTED] & Best–Practices" }, { "filename": "docs/community/faq.rst", "status": "modified", "additions": 6, "deletions": 9, "changes": 15, "patch": "@@ -55,16 +55,16 @@ [NAME_REDACTED] gave an excellent summary on\n Python 3 Support?\n -----------------\n \n-Yes! Requests officially supports Python 2.7 & 3.6+ and PyPy.\n+Yes! Requests officially supports Python 3.7+ and PyPy.\n \n Python 2 Support?\n -----------------\n \n-Yes! We understand that we have a large user base with varying needs. Through\n-**at least** Requests 2.27.x, we will be providing continued support for Python\n-2.7. However, this support is likely to end some time in 2022.\n+No! As of Requests 2.28.0, Requests no longer supports Python 2.7. Users who\n+have been unable to migrate should pin to `requests<2.28`. Full information\n+can be found in `psf/requests#6023 `_.\n \n-It is *highly* recommended users migrate to Python 3.7+ now since Python\n+It is *highly* recommended users migrate to Python 3.8+ now since Python\n 2.7 is no longer receiving bug fixes or security updates as of January 1, 2020.\n \n What are \"hostname doesn't match\" errors?\n@@ -83,10 +83,7 @@ when servers are using `[NAME_REDACTED]`_. When such servers are hosting\n more than one SSL site they need to be able to return the appropriate\n certificate based on the hostname the client is connecting to.\n \n-Python3 and Python 2.7.9+ include native support for SNI in their SSL modules.\n-For information on using SNI with Requests on Python < 2.7.9 refer to this\n-`Stack Overflow answer`_.\n+Python 3 already includes native support for SNI in their SSL modules.\n \n .. _`Server-Name-Indication`: https://en.wikipedia.org/wiki/Server_Name_Indication\n .. _`virtual hosting`: https://en.wikipedia.org/wiki/Virtual_hosting\n-.. _`Stack Overflow answer`: https://stackoverflow.com/questions/18578439/using-requests-with-tls-doesnt-give-sni-support/18579484#18579484" }, { "filename": "docs/index.rst", "status": "modified", "additions": 1, "deletions": 1, "changes": 2, "patch": "@@ -72,7 +72,7 @@ Requests is ready for today's web.\n - [NAME_REDACTED]\n - ``.netrc`` Support\n \n-Requests officially supports Python 2.7 & 3.6+, and runs great on PyPy.\n+Requests officially supports Python 3.7+, and runs great on PyPy.\n \n \n The User Guide" }, { "filename": "requests/_internal_utils.py", "status": "modified", "additions": 2, "deletions": 5, "changes": 7, "patch": "@@ -8,7 +8,7 @@\n which depend on extremely few external helpers (such as compat)\n \"\"\"\n \n-from .compat import is_py2, builtin_str, str\n+from .compat import builtin_str\n \n \n def to_native_string(string, encoding='ascii'):\n@@ -19,10 +19,7 @@ def to_native_string(string, encoding='ascii'):\n if isinstance(string, builtin_str):\n out = string\n else:\n- if is_py2:\n- out = string.encode(encoding)\n- else:\n- out = string.decode(encoding)\n+ out = string.decode(encoding)\n \n return out" }, { "filename": "requests/adapters.py", "status": "modified", "additions": 1, "deletions": 6, "changes": 7, "patch": "@@ -477,12 +477,7 @@ def send(self, request, stream=False, timeout=None, verify=True, cert=None, prox\n low_conn.send(b'0\\r\\n\\r\\n')\n \n # Receive the response from the server\n- try:\n- # For Python 2.7, use buffering of HTTP responses\n- r = low_conn.getresponse(buffering=True)\n- except TypeError:\n- # For compatibility with Python 3.3+\n- r = low_conn.getresponse()\n+ r = low_conn.getresponse()\n \n resp = HTTPResponse.from_httplib(\n r," }, { "filename": "requests/compat.py", "status": "modified", "additions": 26, "deletions": 44, "changes": 70, "patch": "@@ -4,8 +4,9 @@\n requests.compat\n ~~~~~~~~~~~~~~~\n \n-This module handles import compatibility issues between Python 2 and\n-Python 3.\n+This module previously handled import compatibility issues\n+between Python 2 and Python 3. It remains for backwards\n+compatibility until the next major version.\n \"\"\"\n \n try:\n@@ -28,54 +29,35 @@\n #: Python 3.x?\n is_py3 = (_ver[0] == 3)\n \n+# json/simplejson module import resolution\n has_simplejson = False\n try:\n import simplejson as json\n has_simplejson = True\n except ImportError:\n import json\n \n+if has_simplejson:\n+ from simplejson import JSONDecodeError\n+else:\n+ from json import JSONDecodeError\n+\n # ---------\n-# Specifics\n+# [NAME_REDACTED]\n # ---------\n-\n-if is_py2:\n- from urllib import (\n- quote, unquote, quote_plus, unquote_plus, urlencode, getproxies,\n- proxy_bypass, proxy_bypass_environment, getproxies_environment)\n- from urlparse import urlparse, urlunparse, urljoin, urlsplit, urldefrag\n- from urllib2 import parse_http_list\n- import cookielib\n- from Cookie import Morsel\n- from StringIO import StringIO\n- # [NAME_REDACTED] for backwards compatibility.\n- from collections import Callable, Mapping, MutableMapping, OrderedDict\n-\n- builtin_str = str\n- bytes = str\n- str = unicode\n- basestring = basestring\n- numeric_types = (int, long, float)\n- integer_types = (int, long)\n- JSONDecodeError = ValueError\n-\n-elif is_py3:\n- from urllib.parse import urlparse, urlunparse, urljoin, urlsplit, urlencode, quote, unquote, quote_plus, unquote_plus, urldefrag\n- from urllib.request import parse_http_list, getproxies, proxy_bypass, proxy_bypass_environment, getproxies_environment\n- from http import cookiejar as cookielib\n- from http.cookies import Morsel\n- from io import StringIO\n- # [NAME_REDACTED] for backwards compatibility.\n- from collections import OrderedDict\n- from collections.abc import Callable, Mapping, MutableMapping\n- if has_simplejson:\n- from simplejson import JSONDecodeError\n- else:\n- from json import JSONDecodeError\n-\n- builtin_str = str\n- str = str\n- bytes = bytes\n- basestring = (str, bytes)\n- numeric_types = (int, float)\n- integer_types = (int,)\n+from urllib.parse import urlparse, urlunparse, urljoin, urlsplit, urlencode, quote, unquote, quote_plus, unquote_plus, urldefrag\n+from urllib.request import parse_http_list, getproxies, proxy_bypass, proxy_bypass_environment, getproxies_environment\n+from http import cookiejar as cookielib\n+from http.cookies import Morsel\n+from io import StringIO\n+\n+# [NAME_REDACTED] for backwards compatibility.\n+from collections import OrderedDict\n+from collections.abc import Callable, Mapping, MutableMapping\n+\n+builtin_str = str\n+str = str\n+bytes = bytes\n+basestring = (str, bytes)\n+numeric_types = (int, float)\n+integer_types = (int,)" }, { "filename": "requests/help.py", "status": "modified", "additions": 2, "deletions": 2, "changes": 4, "patch": "@@ -36,8 +36,8 @@ def _implementation():\n \"\"\"Return a dict with the Python implementation and version.\n \n Provide both the name and the version of the Python implementation\n- currently running. For example, on CPython 2.7.5 it will return\n- {'name': 'CPython', 'version': '2.7.5'}.\n+ currently running. For example, on CPython 3.10.3 it will return\n+ {'name': 'CPython', 'version': '3.10.3'}.\n \n This function works best on CPython and PyPy: in particular, it probably\n doesn't work for Jython or IronPython. Future investigation should be done" }, { "filename": "requests/models.py", "status": "modified", "additions": 4, "deletions": 20, "changes": 24, "patch": "@@ -8,7 +8,6 @@\n \"\"\"\n \n import datetime\n-import sys\n \n # Import encoding now, to avoid implicit import later.\n # Implicit import within threads may cause LookupError when standard library is in a ZIP,\n@@ -45,8 +44,8 @@\n iter_slices, guess_json_utf, super_len, check_header_validity)\n from .compat import (\n Callable, Mapping,\n- cookielib, urlunparse, urlsplit, urlencode, str, bytes,\n- is_py2, chardet, builtin_str, basestring, JSONDecodeError)\n+ cookielib, urlunparse, urlsplit, urlencode,\n+ chardet, builtin_str, basestring, JSONDecodeError)\n from .compat import json as complexjson\n from .status_codes import codes\n \n@@ -373,7 +372,7 @@ def prepare_url(self, url, params):\n if isinstance(url, bytes):\n url = url.decode('utf8')\n else:\n- url = unicode(url) if is_py2 else str(url)\n+ url = str(url)\n \n # Remove leading whitespaces from url\n url = url.lstrip()\n@@ -424,18 +423,6 @@ def prepare_url(self, url, params):\n if not path:\n path = '/'\n \n- if is_py2:\n- if isinstance(scheme, str):\n- scheme = scheme.encode('utf-8')\n- if isinstance(netloc, str):\n- netloc = netloc.encode('utf-8')\n- if isinstance(path, str):\n- path = path.encode('utf-8')\n- if isinstance(query, str):\n- query = query.encode('utf-8')\n- if isinstance(fragment, str):\n- fragment = fragment.encode('utf-8')\n-\n if isinstance(params, (str, bytes)):\n params = to_native_string(params)\n \n@@ -919,10 +906,7 @@ def json(self, **kwargs):\n except JSONDecodeError as e:\n # Catch JSON-related errors and raise as requests.JSONDecodeError\n # This aliases json.JSONDecodeError and simplejson.JSONDecodeError\n- if is_py2: # e is a ValueError\n- raise RequestsJSONDecodeError(e.message)\n- else:\n- raise RequestsJSONDecodeError(e.msg, e.doc, e.pos)\n+ raise RequestsJSONDecodeError(e.msg, e.doc, e.pos)\n \n [USER_REDACTED]\n def links(self):" }, { "filename": "requests/sessions.py", "status": "modified", "additions": 3, "deletions": 7, "changes": 10, "patch": "@@ -14,7 +14,7 @@\n from collections import OrderedDict\n \n from .auth import _basic_auth_str\n-from .compat import cookielib, is_py3, urljoin, urlparse, Mapping\n+from .compat import cookielib, urljoin, urlparse, Mapping\n from .cookies import (\n cookiejar_from_dict, extract_cookies_to_jar, RequestsCookieJar, merge_cookies)\n from .models import Request, PreparedRequest, DEFAULT_REDIRECT_LIMIT\n@@ -39,10 +39,7 @@\n \n # Preferred clock, based on which one is more accurate on a given system.\n if sys.platform == 'win32':\n- try: # Python 3.4+\n- preferred_clock = time.perf_counter\n- except AttributeError: # Earlier than Python 3.\n- preferred_clock = time.clock\n+ preferred_clock = time.perf_counter\n else:\n preferred_clock = time.time\n \n@@ -111,8 +108,7 @@ def get_redirect_target(self, resp):\n # It is more likely to get UTF8 header rather than latin1.\n # This causes incorrect handling of UTF8 encoded location headers.\n # To solve this, we re-encode the location in latin1.\n- if is_py3:\n- location = location.encode('latin1')\n+ location = location.encode('latin1')\n return to_native_string(location, 'utf8')\n return None" }, { "filename": "requests/utils.py", "status": "modified", "additions": 3, "deletions": 7, "changes": 10, "patch": "@@ -30,7 +30,7 @@\n from .compat import parse_http_list as _parse_list_header\n from .compat import (\n quote, urlparse, bytes, str, unquote, getproxies,\n- proxy_bypass, urlunparse, basestring, integer_types, is_py3,\n+ proxy_bypass, urlunparse, basestring, integer_types,\n proxy_bypass_environment, getproxies_environment, Mapping)\n from .cookies import cookiejar_from_dict\n from .structures import CaseInsensitiveDict\n@@ -54,10 +54,7 @@\n \n def proxy_bypass_registry(host):\n try:\n- if is_py3:\n- import winreg\n- else:\n- import _winreg as winreg\n+ import winreg\n except ImportError:\n return False\n \n@@ -281,12 +278,11 @@ def extract_zipped_paths(path):\n [USER_REDACTED].contextmanager\n def atomic_open(filename):\n \"\"\"Write a file to the disk in an atomic fashion\"\"\"\n- replacer = os.rename if sys.version_info[0] == 2 else os.replace\n tmp_descriptor, tmp_name = tempfile.mkstemp(dir=os.path.dirname(filename))\n try:\n with os.fdopen(tmp_descriptor, 'wb') as tmp_handler:\n yield tmp_handler\n- replacer(tmp_name, filename)\n+ os.replace(tmp_name, filename)\n except BaseException:\n os.remove(tmp_name)\n raise" }, { "filename": "setup.cfg", "status": "modified", "additions": 8, "deletions": 3, "changes": 11, "patch": "@@ -1,5 +1,10 @@\n-[bdist_wheel]\n-universal = 1\n-\n [metadata]\n license_file = LICENSE\n+provides-extra =\n+ socks\n+ use_chardet_on_py3\n+requires-dist =\n+ certifi>=2017.4.17\n+ charset_normalizer~=2.0.0\n+ idna>=2.5,<4\n+ urllib3>=1.21.1,<1.27" }, { "filename": "setup.py", "status": "modified", "additions": 30, "deletions": 17, "changes": 47, "patch": "@@ -1,5 +1,4 @@\n #!/usr/bin/env python\n-# Learn more: https://github.com/[USER_REDACTED]nethreitz/setup.py\n import os\n import sys\n \n@@ -8,7 +7,27 @@\n from setuptools import setup\n from setuptools.command.test import test as TestCommand\n \n-here = os.path.abspath(os.path.dirname(__file__))\n+\n+CURRENT_PYTHON = sys.version_info[:2]\n+REQUIRED_PYTHON = (3, 7)\n+\n+if CURRENT_PYTHON < REQUIRED_PYTHON:\n+ sys.stderr.write(\n+ \"\"\"\n+==========================\n+[NAME_REDACTED] version\n+==========================\n+This version of Requests requires at least Python {}.{}, but\n+you're trying to install it on Python {}.{}. To resolve this,\n+consider upgrading to a supported Python version.\n+\n+If you can't upgrade your Python version, you'll need to\n+pin to an older version of Requests (<2.28).\n+\"\"\".format(\n+ *(REQUIRED_PYTHON + CURRENT_PYTHON)\n+ )\n+ )\n+ sys.exit(1)\n \n class PyTest(TestCommand):\n user_options = [('pytest-args=', 'a', \"Arguments to pass into py.test\")]\n@@ -38,27 +57,23 @@ def run_tests(self):\n os.system('twine upload dist/*')\n sys.exit()\n \n-packages = ['requests']\n-\n requires = [\n- 'charset_normalizer~=2.0.0; python_version >= \"3\"',\n- 'chardet>=3.0.2,<5; python_version < \"3\"',\n- 'idna>=2.5,<3; python_version < \"3\"',\n- 'idna>=2.5,<4; python_version >= \"3\"',\n+ 'charset_normalizer~=2.0.0',\n+ 'idna>=2.5,<4',\n 'urllib3>=1.21.1,<1.27',\n- 'certifi>=2017.4.17'\n-\n+ 'certifi>=2017.4.17',\n ]\n test_requirements = [\n 'pytest-httpbin==0.0.7',\n 'pytest-cov',\n 'pytest-mock',\n 'pytest-xdist',\n 'PySocks>=1.5.6, !=1.5.7',\n- 'pytest>=3'\n+ 'pytest>=3',\n ]\n \n about = {}\n+here = os.path.abspath(os.path.dirname(__file__))\n with open(os.path.join(here, 'requests', '__version__.py'), 'r', 'utf-8') as f:\n exec(f.read(), about)\n \n@@ -74,11 +89,11 @@ def run_tests(self):\n author=about['__author__'],\n author_email=about['__author_email__'],\n url=about['__url__'],\n- packages=packages,\n+ packages=['requests'],\n package_data={'': ['LICENSE', 'NOTICE']},\n package_dir={'requests': 'requests'},\n include_package_data=True,\n- python_requires=\">=2.7, !=3.0.*, !=3.1.*, !=3.2.*, !=3.3.*, !=3.4.*, !=3.5.*\",\n+ python_requires=\">=3.7, <4\",\n install_requires=requires,\n license=about['__license__'],\n zip_safe=False,\n@@ -90,14 +105,13 @@ def run_tests(self):\n '[NAME_REDACTED] :: English',\n '[NAME_REDACTED] :: OS Independent',\n '[NAME_REDACTED] :: Python',\n- '[NAME_REDACTED] :: Python :: 2',\n- '[NAME_REDACTED] :: Python :: 2.7',\n '[NAME_REDACTED] :: Python :: 3',\n- '[NAME_REDACTED] :: Python :: 3.6',\n '[NAME_REDACTED] :: Python :: 3.7',\n '[NAME_REDACTED] :: Python :: 3.8',\n '[NAME_REDACTED] :: Python :: 3.9',\n '[NAME_REDACTED] :: Python :: 3.10',\n+ '[NAME_REDACTED] :: Python :: 3.11',\n+ '[NAME_REDACTED] :: Python :: 3 :: Only',\n '[NAME_REDACTED] :: Python :: Implementation :: CPython',\n '[NAME_REDACTED] :: Python :: Implementation :: PyPy',\n 'Topic :: Internet :: WWW/HTTP',\n@@ -108,7 +122,6 @@ def run_tests(self):\n extras_require={\n 'security': [],\n 'socks': ['PySocks>=1.5.6, !=1.5.7'],\n- 'socks:sys_platform == \"win32\" and python_version == \"2.7\"': ['win_inet_pton'],\n 'use_chardet_on_py3': ['chardet>=3.0.2,<5']\n },\n project_urls={" }, { "filename": "tests/compat.py", "status": "modified", "additions": 12, "deletions": 9, "changes": 21, "patch": "@@ -1,7 +1,5 @@\n # -*- coding: utf-8 -*-\n-\n-from requests.compat import is_py3\n-\n+import warnings\n \n try:\n import StringIO\n@@ -13,9 +11,14 @@\n except ImportError:\n cStringIO = None\n \n-if is_py3:\n- def u(s):\n- return s\n-else:\n- def u(s):\n- return s.decode('unicode-escape')\n+\n+def u(s):\n+ warnings.warn(\n+ (\n+ \"This helper function is no longer relevant in Python 3. \"\n+ \"Usage of this alias should be discontinued as it will be \"\n+ \"removed in a future release of Requests.\"\n+ ),\n+ DeprecationWarning,\n+ )\n+ return s" }, { "filename": "tests/test_requests.py", "status": "modified", "additions": 32, "deletions": 36, "changes": 68, "patch": "@@ -2,7 +2,6 @@\n \n \"\"\"Tests for Requests.\"\"\"\n \n-from __future__ import division\n import json\n import os\n import pickle\n@@ -18,7 +17,7 @@\n from requests.adapters import HTTPAdapter\n from requests.auth import HTTPDigestAuth, _basic_auth_str\n from requests.compat import (\n- Morsel, cookielib, getproxies, str, urlparse,\n+ Morsel, cookielib, getproxies, urlparse,\n builtin_str)\n from requests.cookies import (\n cookiejar_from_dict, morsel_to_cookie)\n@@ -47,9 +46,9 @@\n from requests.sessions import SessionRedirectMixin\n from requests.models import urlencode\n from requests.hooks import default_hooks\n-from requests.compat import JSONDecodeError, is_py3, MutableMapping\n+from requests.compat import JSONDecodeError, MutableMapping\n \n-from .compat import StringIO, u\n+from .compat import StringIO\n from .utils import override_environ\n from urllib3.util import Timeout as Urllib3Timeout\n \n@@ -519,7 +518,7 @@ def test_BASICAUTH_TUPLE_HTTP_200_OK_GET(self, httpbin):\n [USER_REDACTED].mark.parametrize(\n 'username, password', (\n ('user', 'pass'),\n- (u'имя'.encode('utf-8'), u'пароль'.encode('utf-8')),\n+ ('имя'.encode('utf-8'), 'пароль'.encode('utf-8')),\n (42, 42),\n (None, None),\n ))\n@@ -843,8 +842,6 @@ def test_conflicting_post_params(self, httpbin):\n with open('requirements-dev.txt') as f:\n with pytest.raises(ValueError):\n requests.post(url, data='[{\"some\": \"data\"}]', files={'some': f})\n- with pytest.raises(ValueError):\n- requests.post(url, data=u('[{\"some\": \"data\"}]'), files={'some': f})\n \n def test_request_ok_set(self, httpbin):\n r = requests.get(httpbin('status', '404'))\n@@ -989,8 +986,8 @@ def test_different_encodings_dont_break_post(self, httpbin):\n \n [USER_REDACTED].mark.parametrize(\n 'data', (\n- {'stuff': u('ëlïxr')},\n- {'stuff': u('ëlïxr').encode('utf-8')},\n+ {'stuff': 'ëlïxr'},\n+ {'stuff': 'ëlïxr'.encode('utf-8')},\n {'stuff': 'elixr'},\n {'stuff': 'elixr'.encode('utf-8')},\n ))\n@@ -1013,13 +1010,13 @@ def test_unicode_multipart_post_fieldnames(self, httpbin):\n def test_unicode_method_name(self, httpbin):\n files = {'file': open(__file__, 'rb')}\n r = requests.request(\n- method=u('POST'), url=httpbin('post'), files=files)\n+ method='POST', url=httpbin('post'), files=files)\n assert r.status_code == 200\n \n def test_unicode_method_name_with_request_object(self, httpbin):\n files = {'file': open(__file__, 'rb')}\n s = requests.Session()\n- req = requests.Request(u('POST'), httpbin('post'), files=files)\n+ req = requests.Request('POST', httpbin('post'), files=files)\n prep = s.prepare_request(req)\n assert isinstance(prep.method, builtin_str)\n assert prep.method == 'POST'\n@@ -1029,7 +1026,7 @@ def test_unicode_method_name_with_request_object(self, httpbin):\n \n def test_non_prepared_request_error(self):\n s = requests.Session()\n- req = requests.Request(u('POST'), '/')\n+ req = requests.Request('POST', '/')\n \n with pytest.raises(ValueError) as e:\n s.send(req)\n@@ -1336,8 +1333,8 @@ def test_response_decode_unicode(self):\n def test_response_reason_unicode(self):\n # check for unicode HTTP status\n r = requests.Response()\n- r.url = u'unicode URL'\n- r.reason = u'Komponenttia ei löydy'.encode('utf-8')\n+ r.url = 'unicode URL'\n+ r.reason = 'Komponenttia ei löydy'.encode('utf-8')\n r.status_code = 404\n r.encoding = None\n assert not r.ok # old behaviour - crashes here\n@@ -1346,7 +1343,7 @@ def test_response_reason_unicode_fallback(self):\n # check raise_status falls back to ISO-8859-1\n r = requests.Response()\n r.url = 'some url'\n- reason = u'Komponenttia ei löydy'\n+ reason = 'Komponenttia ei löydy'\n r.reason = reason.encode('latin-1')\n r.status_code = 500\n r.encoding = None\n@@ -1593,7 +1590,7 @@ def test_long_authinfo_in_url(self):\n assert r.url == url\n \n def test_header_keys_are_native(self, httpbin):\n- headers = {u('unicode'): 'blah', 'byte'.encode('ascii'): 'blah'}\n+ headers = {'unicode': 'blah', 'byte'.encode('ascii'): 'blah'}\n r = requests.Request('GET', httpbin('get'), headers=headers)\n p = r.prepare()\n \n@@ -1605,7 +1602,7 @@ def test_header_keys_are_native(self, httpbin):\n def test_header_validation(self, httpbin):\n \"\"\"Ensure prepare_headers regex isn't flagging valid header contents.\"\"\"\n headers_ok = {'foo': 'bar baz qux',\n- 'bar': u'fbbq'.encode('utf8'),\n+ 'bar': 'fbbq'.encode('utf8'),\n 'baz': '',\n 'qux': '1'}\n r = requests.get(httpbin('get'), headers=headers_ok)\n@@ -1885,7 +1882,7 @@ def test_redirect_with_wrong_gzipped_header(self, httpbin):\n [USER_REDACTED].mark.parametrize(\n 'username, password, auth_str', (\n ('test', 'test', 'Basic dGVzdDp0ZXN0'),\n- (u'имя'.encode('utf-8'), u'пароль'.encode('utf-8'), 'Basic 0LjQvNGPOtC/0LDRgNC+0LvRjA=='),\n+ ('имя'.encode('utf-8'), 'пароль'.encode('utf-8'), 'Basic 0LjQvNGPOtC/0LDRgNC+0LvRjA=='),\n ))\n def test_basic_auth_str_is_always_native(self, username, password, auth_str):\n s = _basic_auth_str(username, password)\n@@ -2469,7 +2466,7 @@ def test_data_argument_accepts_tuples(data):\n },\n {\n 'method': 'GET',\n- 'url': u('http://www.example.com/üniçø∂é')\n+ 'url': 'http://www.example.com/üniçø∂é'\n },\n ))\n def test_prepared_copy(kwargs):\n@@ -2507,39 +2504,39 @@ class TestPreparingURLs(object):\n 'url,expected',\n (\n ('http://google.com', 'http://google.com/'),\n- (u'http://ジェーピーニック.jp', u'http://xn--hckqz9bzb1cyrb.jp/'),\n- (u'http://xn--n3h.net/', u'http://xn--n3h.net/'),\n+ ('http://ジェーピーニック.jp', 'http://xn--hckqz9bzb1cyrb.jp/'),\n+ ('http://xn--n3h.net/', 'http://xn--n3h.net/'),\n (\n- u'http://ジェーピーニック.jp'.encode('utf-8'),\n- u'http://xn--hckqz9bzb1cyrb.jp/'\n+ 'http://ジェーピーニック.jp'.encode('utf-8'),\n+ 'http://xn--hckqz9bzb1cyrb.jp/'\n ),\n (\n- u'http://straße.de/straße',\n- u'http://xn--strae-oqa.de/stra%C3%9Fe'\n+ 'http://straße.de/straße',\n+ 'http://xn--strae-oqa.de/stra%C3%9Fe'\n ),\n (\n- u'http://straße.de/straße'.encode('utf-8'),\n- u'http://xn--strae-oqa.de/stra%C3%9Fe'\n+ 'http://straße.de/straße'.encode('utf-8'),\n+ 'http://xn--strae-oqa.de/stra%C3%9Fe'\n ),\n (\n- u'http://Königsgäßchen.de/straße',\n- u'http://xn--knigsgchen-b4a3dun.de/stra%C3%9Fe'\n+ 'http://Königsgäßchen.de/straße',\n+ 'http://xn--knigsgchen-b4a3dun.de/stra%C3%9Fe'\n ),\n (\n- u'http://Königsgäßchen.de/straße'.encode('utf-8'),\n- u'http://xn--knigsgchen-b4a3dun.de/stra%C3%9Fe'\n+ 'http://Königsgäßchen.de/straße'.encode('utf-8'),\n+ 'http://xn--knigsgchen-b4a3dun.de/stra%C3%9Fe'\n ),\n (\n b'http://xn--n3h.net/',\n- u'http://xn--n3h.net/'\n+ 'http://xn--n3h.net/'\n ),\n (\n b'http://[1200:0000:ab00:1234:0000:2552:7777:1313]:12345/',\n- u'http://[1200:0000:ab00:1234:0000:2552:7777:1313]:12345/'\n+ 'http://[1200:0000:ab00:1234:0000:2552:7777:1313]:12345/'\n ),\n (\n- u'http://[1200:0000:ab00:1234:0000:2552:7777:1313]:12345/',\n- u'http://[1200:0000:ab00:1234:0000:2552:7777:1313]:12345/'\n+ 'http://[1200:0000:ab00:1234:0000:2552:7777:1313]:12345/',\n+ 'http://[1200:0000:ab00:1234:0000:2552:7777:1313]:12345/'\n )\n )\n )\n@@ -2664,7 +2661,6 @@ def test_json_decode_compatibility(self, httpbin):\n assert isinstance(excinfo.value, JSONDecodeError)\n assert r.text not in str(excinfo.value)\n \n- [USER_REDACTED].mark.skipif(not is_py3, reason=\"doc attribute is only present on py3\")\n def test_json_decode_persists_doc_attr(self, httpbin):\n r = requests.get(httpbin('bytes/20'))\n with pytest.raises(requests.exceptions.JSONDecodeError) as excinfo:" }, { "filename": "tests/test_utils.py", "status": "modified", "additions": 1, "deletions": 4, "changes": 5, "patch": "@@ -749,10 +749,7 @@ def test_should_bypass_proxies_win_registry(url, expected, override,\n \"\"\"\n if override is None:\n override = '192.168.*;127.0.0.1;localhost.localdomain;172.16.1.1'\n- if compat.is_py3:\n- import winreg\n- else:\n- import _winreg as winreg\n+ import winreg\n \n class RegHandle:\n def Close(self):" }, { "filename": "tests/testserver/server.py", "status": "modified", "additions": 1, "deletions": 3, "changes": 4, "patch": "@@ -78,9 +78,7 @@ def run(self):\n def _create_socket_and_bind(self):\n sock = socket.socket()\n sock.bind((self.host, self.port))\n- # NB: when Python 2.7 is no longer supported, the argument\n- # can be removed to use a default backlog size\n- sock.listen(5)\n+ sock.listen()\n return sock\n \n def _close_server_sock_ignore_errors(self):" }, { "filename": "tox.ini", "status": "modified", "additions": 1, "deletions": 1, "changes": 2, "patch": "@@ -1,5 +1,5 @@\n [tox]\n-envlist = py{27,36,37,38,39}-{default,use_chardet_on_py3}\n+envlist = py{37,38,39,310}-{default, use_chardet_on_py3}\n \n [testenv]\n deps = -rrequirements-dev.txt" } ], "reviews": [ { "id": 918984892, "user": "user_b08fb5f52ea1", "state": "COMMENTED", "body": null, "submitted_at": "2022-03-23T15:32:31+00:00" }, { "id": 918988014, "user": "user_b08fb5f52ea1", "state": "COMMENTED", "body": null, "submitted_at": "2022-03-23T15:34:32+00:00" }, { "id": 918989347, "user": "user_b08fb5f52ea1", "state": "COMMENTED", "body": "This is so exciting! Here's a handful of comments/questions:", "submitted_at": "2022-03-23T15:36:26+00:00" }, { "id": 919001880, "user": "user_dbf2a999bd6d", "state": "COMMENTED", "body": null, "submitted_at": "2022-03-23T15:41:49+00:00" }, { "id": 919004165, "user": "user_dbf2a999bd6d", "state": "COMMENTED", "body": null, "submitted_at": "2022-03-23T15:42:39+00:00" }, { "id": 919004456, "user": "user_dbf2a999bd6d", "state": "COMMENTED", "body": null, "submitted_at": "2022-03-23T15:42:44+00:00" }, { "id": 919026338, "user": "user_eef3c6ba6f45", "state": "COMMENTED", "body": null, "submitted_at": "2022-03-23T15:56:05+00:00" }, { "id": 919039661, "user": "user_dbf2a999bd6d", "state": "COMMENTED", "body": null, "submitted_at": "2022-03-23T16:04:19+00:00" }, { "id": 919042580, "user": "user_eef3c6ba6f45", "state": "COMMENTED", "body": "A few other bits to clean up:\n\n`tox.ini`: add `310`, remove `27` and `36`\n\nSeveral files: clean up `use_chardet_on_py3`\n\n`requests/utils.py`: `replacer = os.rename if sys.version_info[0] == 2 else os.replace`\n\n`tests/testserver/server.py`:\n\n```python\n # NB: when Python 2.7 is no longer supported, the argument\n # can be removed to use a default backlog size\n sock.listen(5)\n```", "submitted_at": "2022-03-23T16:07:43+00:00" }, { "id": 919046135, "user": "user_eef3c6ba6f45", "state": "COMMENTED", "body": null, "submitted_at": "2022-03-23T16:08:56+00:00" }, { "id": 920617581, "user": "user_b08fb5f52ea1", "state": "COMMENTED", "body": null, "submitted_at": "2022-03-24T17:20:47+00:00" }, { "id": 920630599, "user": "user_dbf2a999bd6d", "state": "COMMENTED", "body": null, "submitted_at": "2022-03-24T17:31:20+00:00" }, { "id": 920706904, "user": "user_b08fb5f52ea1", "state": "COMMENTED", "body": null, "submitted_at": "2022-03-24T18:32:48+00:00" }, { "id": 920815330, "user": "user_dbf2a999bd6d", "state": "COMMENTED", "body": null, "submitted_at": "2022-03-24T20:03:49+00:00" }, { "id": 920838365, "user": "user_1b087c94a628", "state": "COMMENTED", "body": null, "submitted_at": "2022-03-24T20:18:55+00:00" }, { "id": 920839825, "user": "user_dbf2a999bd6d", "state": "COMMENTED", "body": null, "submitted_at": "2022-03-24T20:19:50+00:00" }, { "id": 921524787, "user": "user_b08fb5f52ea1", "state": "APPROVED", "body": "LGTM! :shipit:", "submitted_at": "2022-03-25T11:34:51+00:00" } ], "review_comments": [ { "id": 833410951, "user": "user_b08fb5f52ea1", "body": "Since we're now Python 3.7+ I wonder if we can start using `time.perf_counter` everywhere? Might need to do more research into why Windows was given only perf_counter/clock instead of `time.time()`", "path": "requests/sessions.py", "line": 41, "side": "RIGHT", "created_at": "2022-03-23T15:32:31+00:00" }, { "id": 833413598, "user": "user_b08fb5f52ea1", "body": "[Finally free...](https://pypi.org/project/win-inet-pton) :smiling_face_with_tear:", "path": "setup.py", "line": 111, "side": "LEFT", "created_at": "2022-03-23T15:34:32+00:00" }, { "id": 833414757, "user": "user_b08fb5f52ea1", "body": "Should we go through and remove all uses of `u(...)` in the tests to simplify them?", "path": "tests/compat.py", "line": 15, "side": "RIGHT", "created_at": "2022-03-23T15:35:27+00:00" }, { "id": 833415192, "user": "user_b08fb5f52ea1", "body": "Do we need `u'...'`?", "path": "tests/test_requests.py", "line": null, "side": "RIGHT", "created_at": "2022-03-23T15:35:47+00:00" }, { "id": 833421896, "user": "user_dbf2a999bd6d", "body": "No we don't, I have a separate linting PR that removes these lines entirely since they're redundant. I can move that into this one.", "path": "tests/test_requests.py", "line": null, "side": "RIGHT", "created_at": "2022-03-23T15:41:49+00:00" }, { "id": 833422816, "user": "user_dbf2a999bd6d", "body": "I left the definition in case it's in use externally, but yes, it should be removed from all of our tests. I'll do a second pass if I missed some.", "path": "tests/compat.py", "line": 15, "side": "RIGHT", "created_at": "2022-03-23T15:42:39+00:00" }, { "id": 833422938, "user": "user_dbf2a999bd6d", "body": "It was a performance issue for Windows where the clock wasn't granular enough for CI to pass on Appveyor (#3988). I can take a look at standardizing everything onto perf_counter but that's probably a separate deep dive.", "path": "requests/sessions.py", "line": 41, "side": "RIGHT", "created_at": "2022-03-23T15:42:44+00:00" }, { "id": 833439166, "user": "user_eef3c6ba6f45", "body": "`pyupgrade **/*.py --py37-plus` will deal with a bunch of `u''`s and other stuff.", "path": "tests/test_requests.py", "line": null, "side": "RIGHT", "created_at": "2022-03-23T15:56:05+00:00" }, { "id": 833449625, "user": "user_dbf2a999bd6d", "body": "Yep, that's what's in the linting commit currently. Unfortunately, it just makes the two declarations identical so it will still require manual removal in one of the PRs.", "path": "tests/test_requests.py", "line": null, "side": "RIGHT", "created_at": "2022-03-23T16:04:19+00:00" }, { "id": 833451757, "user": "user_eef3c6ba6f45", "body": "```suggestion\n```", "path": "setup.py", "line": null, "side": "RIGHT", "created_at": "2022-03-23T16:06:26+00:00" }, { "id": 833454405, "user": "user_eef3c6ba6f45", "body": "Perhaps add a deprecation warning for any external use?", "path": "tests/compat.py", "line": 15, "side": "RIGHT", "created_at": "2022-03-23T16:08:55+00:00" }, { "id": 834551612, "user": "user_b08fb5f52ea1", "body": "We discussed this in the urllib3 Discord with [USER_REDACTED] and [USER_REDACTED] and figured out that this series of steps isn't always going to solve the problem because pip *also* dropped Python versions over time.\n\nThere were a few solutions proposed:\n- Keep the current message\n- Always recommend installing pip<21 (last version that supported Python 2 and 3.5)\n- Recommend installing [pip-with-requires-python](https://pypi.org/project/pip-with-requires-python)\n- Not give a recommendation on *how* to upgrade pip and setuptools?\n\nI also raised the point of recommending users upgrade pip/setuptools would likely break OS installations.", "path": "setup.py", "line": null, "side": "RIGHT", "created_at": "2022-03-24T17:20:47+00:00" }, { "id": 834561046, "user": "user_dbf2a999bd6d", "body": "I think `pip-with-requires-python` is likely the safest option. Alternatively, we'd vend the requires values from the package in our setup.py and compose the install message from those values as [USER_REDACTED] suggested. That avoids any risk for Python 3.4 users who still comprise a significant number of downloads.", "path": "setup.py", "line": null, "side": "RIGHT", "created_at": "2022-03-24T17:31:20+00:00" }, { "id": 834612265, "user": "user_b08fb5f52ea1", "body": "[USER_REDACTED] Noted that new Python versions come with a \"good\" pip version out of the box. Maybe our strategy should be to instruct the user to either pin to <2.28 or upgrade to at least Python 3.7 (since they'll need that version to install Requests anyways) and then we don't need to mention pip/setuptools at all.", "path": "setup.py", "line": null, "side": "RIGHT", "created_at": "2022-03-24T18:32:48+00:00" }, { "id": 834679845, "user": "user_dbf2a999bd6d", "body": "I went ahead and [ripped out the whole of touching pip versions](https://github.com/psf/requests/pull/6091/commits/febcd5199c278d99232124e22b3ab2d912b7cc16) after further discussion. If users want to upgrade their pip, that's something they can manage, otherwise the simplest option is to upgrade their Python version which will provide this automatically.\n\nOther users are free to pin to older supported versions as discussed in the original deprecation announcement.", "path": "setup.py", "line": null, "side": "RIGHT", "created_at": "2022-03-24T20:03:49+00:00" }, { "id": 834692016, "user": "user_1b087c94a628", "body": "```suggestion\npin to an older version of Requests (<2.28).\n```\n\nLet's just go all the way here. :P", "path": "setup.py", "line": null, "side": "RIGHT", "created_at": "2022-03-24T20:18:55+00:00" }, { "id": 834692955, "user": "user_dbf2a999bd6d", "body": "Fair enough :D", "path": "setup.py", "line": null, "side": "RIGHT", "created_at": "2022-03-24T20:19:50+00:00" } ], "meta": { "languages": [ "cfg", "ini", "md", "py", "rst", "yml" ], "touches_tests": true, "review_state_summary": { "COMMENTED": 16, "APPROVED": 1 }, "meaningful_comment_count": 17, "has_approval": true, "has_changes_requested": false, "total_review_comments": 17 } } { "_id": "23d5b79be8cb64d9", "_schema_version": "1.0", "_cleaned_at": "2026-02-12T07:46:51.418732+00:00", "repo": "psf/requests", "repo_url": "https://github.com/psf/requests", "license_name": "Apache License 2.0", "license_spdx": "Apache-2.0", "pr_number": 6036, "title": "Limit size of payload in JSONDecodeError", "body": "2.27 introduced a change in behavior where now the exception raised by [NAME_REDACTED] json contains the full body of the invalid response. This gets included it's string representation. This can cause problems when the response is very large. This PR tries to limit the size of the response that we store this way, to what might be around the reported error position. But we could also just return to first n bytes or remove the response altogether and let users fetch it, if needed from the error.response object.", "author": "user_b0902490d1eb", "created_at": "2022-01-07T01:02:24+00:00", "merged_at": "2022-01-13T15:42:49+00:00", "base_branch": "main", "head_branch": "json-err-size", "additions": 23, "deletions": 3, "changed_files": 2, "files": [ { "filename": "requests/exceptions.py", "status": "modified", "additions": 10, "deletions": 0, "changes": 10, "patch": "@@ -34,6 +34,16 @@ class InvalidJSONError(RequestException):\n class JSONDecodeError(InvalidJSONError, CompatJSONDecodeError):\n \"\"\"Couldn't decode the text into json\"\"\"\n \n+ def __init__(self, *args, **kwargs):\n+ \"\"\"\n+ Construct the JSONDecodeError instance first with all\n+ args. Then use it's args to construct the IOError so that\n+ the json specific args aren't used as IOError specific args\n+ and the error message from JSONDecodeError is preserved.\n+ \"\"\"\n+ CompatJSONDecodeError.__init__(self, *args)\n+ InvalidJSONError.__init__(self, *self.args, **kwargs)\n+\n \n class HTTPError(RequestException):\n \"\"\"An HTTP error occurred.\"\"\"" }, { "filename": "tests/test_requests.py", "status": "modified", "additions": 13, "deletions": 3, "changes": 16, "patch": "@@ -23,14 +23,14 @@\n cookiejar_from_dict, morsel_to_cookie)\n from requests.exceptions import (\n ConnectionError, ConnectTimeout, InvalidSchema, InvalidURL,\n- MissingSchema, ReadTimeout, Timeout, RetryError, TooManyRedirects,\n+ MissingSchema, ReadTimeout, Timeout, RetryError, RequestException, TooManyRedirects,\n ProxyError, InvalidHeader, UnrewindableBodyError, SSLError, InvalidProxyURL, InvalidJSONError)\n from requests.models import PreparedRequest\n from requests.structures import CaseInsensitiveDict\n from requests.sessions import SessionRedirectMixin\n from requests.models import urlencode\n from requests.hooks import default_hooks\n-from requests.compat import MutableMapping\n+from requests.compat import JSONDecodeError, is_py3, MutableMapping\n \n from .compat import StringIO, u\n from .utils import override_environ\n@@ -2585,5 +2585,15 @@ def test_post_json_nan(self, httpbin):\n \n def test_json_decode_compatibility(self, httpbin):\n r = requests.get(httpbin('bytes/20'))\n- with pytest.raises(requests.exceptions.JSONDecodeError):\n+ with pytest.raises(requests.exceptions.JSONDecodeError) as excinfo:\n r.json()\n+ assert isinstance(excinfo.value, RequestException)\n+ assert isinstance(excinfo.value, JSONDecodeError)\n+ assert r.text not in str(excinfo.value)\n+\n+ [USER_REDACTED].mark.skipif(not is_py3, reason=\"doc attribute is only present on py3\")\n+ def test_json_decode_persists_doc_attr(self, httpbin):\n+ r = requests.get(httpbin('bytes/20'))\n+ with pytest.raises(requests.exceptions.JSONDecodeError) as excinfo:\n+ r.json()\n+ assert excinfo.value.doc == r.text" } ], "reviews": [ { "id": 846975072, "user": "user_dbf2a999bd6d", "state": "APPROVED", "body": null, "submitted_at": "2022-01-07T20:35:47+00:00" }, { "id": 847161295, "user": "user_0fa58b6f3572", "state": "DISMISSED", "body": "Are there any tests we can add to verify this doesn't revert back to containing the entirety of `doc` in the `__repr__`? It's also unclear how this prevents that from happening on a visual inspection", "submitted_at": "2022-01-08T14:45:02+00:00" }, { "id": 848391205, "user": "user_dbf2a999bd6d", "state": "CHANGES_REQUESTED", "body": "Left a few small notes but I think we're close to wrapping this up if [USER_REDACTED] doesn't have more concerns.", "submitted_at": "2022-01-10T22:03:27+00:00" }, { "id": 848467202, "user": "user_b0902490d1eb", "state": "COMMENTED", "body": null, "submitted_at": "2022-01-10T23:41:25+00:00" }, { "id": 848469442, "user": "user_b0902490d1eb", "state": "COMMENTED", "body": null, "submitted_at": "2022-01-10T23:45:42+00:00" }, { "id": 848469866, "user": "user_b0902490d1eb", "state": "COMMENTED", "body": null, "submitted_at": "2022-01-10T23:46:37+00:00" }, { "id": 848470624, "user": "user_dbf2a999bd6d", "state": "COMMENTED", "body": null, "submitted_at": "2022-01-10T23:48:06+00:00" }, { "id": 848503102, "user": "user_b0902490d1eb", "state": "COMMENTED", "body": null, "submitted_at": "2022-01-11T00:58:11+00:00" }, { "id": 849413018, "user": "user_dbf2a999bd6d", "state": "CHANGES_REQUESTED", "body": "Great, thanks for the updates [USER_REDACTED]! I think there were a couple more things we discussed in the last review I left comments on. Let me know if you have any questions.", "submitted_at": "2022-01-11T16:23:16+00:00" }, { "id": 849461725, "user": "user_b0902490d1eb", "state": "COMMENTED", "body": null, "submitted_at": "2022-01-11T16:43:54+00:00" }, { "id": 849486491, "user": "user_dbf2a999bd6d", "state": "APPROVED", "body": "Looks good to me, thanks [USER_REDACTED]!", "submitted_at": "2022-01-11T17:03:32+00:00" }, { "id": 851870728, "user": "user_b08fb5f52ea1", "state": "APPROVED", "body": "Seems good to me.", "submitted_at": "2022-01-13T15:29:35+00:00" }, { "id": 851874069, "user": "user_0fa58b6f3572", "state": "COMMENTED", "body": "I'm still not convinced this is maintainable or correct but I also understand that it's probably a tonne of work to get compatibility on python 2 and 3 that isn't a scary nightmare", "submitted_at": "2022-01-13T15:31:56+00:00" } ], "review_comments": [ { "id": 780674790, "user": "user_0fa58b6f3572", "body": "Can we add comments here explaining why:\n\n1. We're using super old Python 2.5 methods of calling parent `__init__` methods\n2. We're calling the `__init__`s in this particular order - presuming the order matters\n3. This fixes the issue of `.doc` ending up in the message/default `__repr__`", "path": "requests/exceptions.py", "line": 45, "side": "RIGHT", "created_at": "2022-01-08T14:42:14+00:00" }, { "id": 780674982, "user": "user_0fa58b6f3572", "body": "Can we add an empty line prior to the `__init__` here? That's already the style of this sub-module if not the entirety of `requests`", "path": "requests/exceptions.py", "line": 37, "side": "RIGHT", "created_at": "2022-01-08T14:44:32+00:00" }, { "id": 781581198, "user": "user_dbf2a999bd6d", "body": "nit; This might be phrased \"[...] the error message from JSONDecodeError is preserved.\"\n\nAlso note the missing period in the current sentence.", "path": "requests/exceptions.py", "line": null, "side": "RIGHT", "created_at": "2022-01-10T21:47:23+00:00" }, { "id": 781592203, "user": "user_dbf2a999bd6d", "body": "Do we need to use `.value` in these assertions? Just `excinfo` should be sufficient and that's how the typical user will probably interact with them.", "path": "tests/test_requests.py", "line": 2590, "side": "RIGHT", "created_at": "2022-01-10T21:57:30+00:00" }, { "id": 781595242, "user": "user_dbf2a999bd6d", "body": "Also somewhat of a nit. It may be better to just make this its own test with a `[USER_REDACTED].skipIf(not is_py3)` at the top.\n\ne.g.\n\n```python\n[USER_REDACTED].skipIf(not is_py3)\ndef test_json_decode_persists_doc_attr(self, httpbin):\n r = requests.get(httpbin('bytes/20'))\n with pytest.raises(requests.exceptions.JSONDecodeError) as e:\n r.json()\n assert e.doc == r.text\n```", "path": "tests/test_requests.py", "line": null, "side": "RIGHT", "created_at": "2022-01-10T22:00:15+00:00" }, { "id": 781656546, "user": "user_b0902490d1eb", "body": "don't we want to test that the py2 object is also what we expect? Or if we don't can i can make it py3 only?", "path": "tests/test_requests.py", "line": null, "side": "RIGHT", "created_at": "2022-01-10T23:41:24+00:00" }, { "id": 781658238, "user": "user_b0902490d1eb", "body": "excinfo is a pytest thing that wraps the actual exception, i think we have to look at value to get the original object", "path": "tests/test_requests.py", "line": 2590, "side": "RIGHT", "created_at": "2022-01-10T23:45:42+00:00" }, { "id": 781658559, "user": "user_b0902490d1eb", "body": "updated", "path": "requests/exceptions.py", "line": null, "side": "RIGHT", "created_at": "2022-01-10T23:46:37+00:00" }, { "id": 781659079, "user": "user_dbf2a999bd6d", "body": "The original test doesn't assert anything about Python 2 either. So we don't lose anything with this change. I suppose we could assert doc _isn't_ on the Python 2 exception but I'm not sure how meaningful that is.\n\nEdit: to be clear I'm proposing two tests. The one you have and moving the Python 3 specifics to its own test.", "path": "tests/test_requests.py", "line": null, "side": "RIGHT", "created_at": "2022-01-10T23:48:06+00:00" }, { "id": 781684776, "user": "user_b0902490d1eb", "body": "ok, i think i updated it with what you had in mind.", "path": "tests/test_requests.py", "line": null, "side": "RIGHT", "created_at": "2022-01-11T00:58:10+00:00" }, { "id": 782303428, "user": "user_dbf2a999bd6d", "body": "I think the last sentence still needs a period at the end.", "path": "requests/exceptions.py", "line": null, "side": "RIGHT", "created_at": "2022-01-11T16:11:57+00:00" }, { "id": 782304038, "user": "user_dbf2a999bd6d", "body": "We probably don't need to reassert this since it's already handled in the test above.", "path": "tests/test_requests.py", "line": null, "side": "RIGHT", "created_at": "2022-01-11T16:12:37+00:00" }, { "id": 782312495, "user": "user_dbf2a999bd6d", "body": "nit; since we're only using this once we can probably just use r.text in the final assertion as shown in the original proposal.", "path": "tests/test_requests.py", "line": null, "side": "RIGHT", "created_at": "2022-01-11T16:21:42+00:00" }, { "id": 782337397, "user": "user_b0902490d1eb", "body": "I liked having both in the same test, assures us that we are testing with the right string. but i'll take it out.", "path": "tests/test_requests.py", "line": null, "side": "RIGHT", "created_at": "2022-01-11T16:43:54+00:00" } ], "meta": { "languages": [ "py" ], "touches_tests": true, "review_state_summary": { "APPROVED": 3, "DISMISSED": 1, "CHANGES_REQUESTED": 2, "COMMENTED": 7 }, "meaningful_comment_count": 13, "has_approval": true, "has_changes_requested": true, "total_review_comments": 14 } } { "_id": "9733163dfd7a365e", "_schema_version": "1.0", "_cleaned_at": "2026-02-12T07:46:51.424293+00:00", "repo": "psf/requests", "repo_url": "https://github.com/psf/requests", "license_name": "Apache License 2.0", "license_spdx": "Apache-2.0", "pr_number": 5924, "title": "Refactor rebuild_proxies to separate resolution and auth handling", "body": "This is a proposal for handling #5888 that's come out of discussion in an alternative PR (#5893). Given that we've stalled out on progress there for a few weeks, this PR is to help drive a conclusion. The approach taken here is to mitigate the incorrect behavior of stripping `Proxy-Authorization` headers off all requests sent with `Session.send`. This will not address the performance concerns from #5891 as that's a more significant problem without a clear answer.\n\nThe goal of driving this separately from #5891 is that one is an unintended breakage in basic behavior of the library and the second is an unfortunate performance regression. I'd like to address the former more quickly if possible instead of letting the problem fester.", "author": "user_dbf2a999bd6d", "created_at": "2021-09-02T06:01:26+00:00", "merged_at": "2021-11-24T19:21:01+00:00", "base_branch": "main", "head_branch": "proxy_auth", "additions": 45, "deletions": 18, "changed_files": 3, "files": [ { "filename": "requests/sessions.py", "status": "modified", "additions": 7, "deletions": 17, "changes": 24, "patch": "@@ -29,7 +29,7 @@\n \n from .utils import (\n requote_uri, get_environ_proxies, get_netrc_auth, should_bypass_proxies,\n- get_auth_from_url, rewind_body\n+ get_auth_from_url, rewind_body, resolve_proxies\n )\n \n from .status_codes import codes\n@@ -269,7 +269,6 @@ def rebuild_auth(self, prepared_request, response):\n if new_auth is not None:\n prepared_request.prepare_auth(new_auth)\n \n-\n def rebuild_proxies(self, prepared_request, proxies):\n \"\"\"This method re-evaluates the proxy configuration by [NAME_REDACTED] If we are redirected to a URL covered by\n@@ -282,21 +281,9 @@ def rebuild_proxies(self, prepared_request, proxies):\n \n :rtype: dict\n \"\"\"\n- proxies = proxies if proxies is not None else {}\n headers = prepared_request.headers\n- url = prepared_request.url\n- scheme = urlparse(url).scheme\n- new_proxies = proxies.copy()\n- no_proxy = proxies.get('no_proxy')\n-\n- bypass_proxy = should_bypass_proxies(url, no_proxy=no_proxy)\n- if self.trust_env and not bypass_proxy:\n- environ_proxies = get_environ_proxies(url, no_proxy=no_proxy)\n-\n- proxy = environ_proxies.get(scheme, environ_proxies.get('all'))\n-\n- if proxy:\n- new_proxies.setdefault(scheme, proxy)\n+ scheme = urlparse(prepared_request.url).scheme\n+ new_proxies = resolve_proxies(prepared_request, proxies, self.trust_env)\n \n if 'Proxy-Authorization' in headers:\n del headers['Proxy-Authorization']\n@@ -633,7 +620,10 @@ def send(self, request, **kwargs):\n kwargs.setdefault('stream', self.stream)\n kwargs.setdefault('verify', self.verify)\n kwargs.setdefault('cert', self.cert)\n- kwargs.setdefault('proxies', self.rebuild_proxies(request, self.proxies))\n+ if 'proxies' not in kwargs:\n+ kwargs['proxies'] = resolve_proxies(\n+ request, self.proxies, self.trust_env\n+ )\n \n # It's possible that users might accidentally send a Request object.\n # Guard against that specific failure case." }, { "filename": "requests/utils.py", "status": "modified", "additions": 28, "deletions": 0, "changes": 28, "patch": "@@ -830,6 +830,34 @@ def select_proxy(url, proxies):\n return proxy\n \n \n+def resolve_proxies(request, proxies, trust_env=True):\n+ \"\"\"This method takes proxy information from a request and configuration\n+ input to resolve a mapping of target proxies. This will consider settings\n+ such a NO_PROXY to strip proxy configurations.\n+\n+ :param request: Request or PreparedRequest\n+ :param proxies: A dictionary of schemes or schemes and hosts to proxy URLs\n+ :param trust_env: Boolean declaring whether to trust environment configs\n+\n+ :rtype: dict\n+ \"\"\"\n+ proxies = proxies if proxies is not None else {}\n+ url = request.url\n+ scheme = urlparse(url).scheme\n+ no_proxy = proxies.get('no_proxy')\n+ new_proxies = proxies.copy()\n+\n+ bypass_proxy = should_bypass_proxies(url, no_proxy=no_proxy)\n+ if trust_env and not bypass_proxy:\n+ environ_proxies = get_environ_proxies(url, no_proxy=no_proxy)\n+\n+ proxy = environ_proxies.get(scheme, environ_proxies.get('all'))\n+\n+ if proxy:\n+ new_proxies.setdefault(scheme, proxy)\n+ return new_proxies\n+\n+\n def default_user_agent(name=\"python-requests\"):\n \"\"\"\n Return a string representing the default user agent." }, { "filename": "tests/test_requests.py", "status": "modified", "additions": 10, "deletions": 1, "changes": 11, "patch": "@@ -590,6 +590,15 @@ def test_respect_proxy_env_on_request(self, httpbin):\n session = requests.Session()\n session.request(method='GET', url=httpbin())\n \n+ def test_proxy_authorization_preserved_on_request(self, httpbin):\n+ proxy_auth_value = \"Bearer XXX\"\n+ session = requests.Session()\n+ session.headers.update({\"Proxy-Authorization\": proxy_auth_value})\n+ resp = session.request(method='GET', url=httpbin('get'))\n+ sent_headers = resp.json().get('headers', {})\n+\n+ assert sent_headers.get(\"Proxy-Authorization\") == proxy_auth_value\n+\n def test_basicauth_with_netrc(self, httpbin):\n auth = ('user', 'pass')\n wrong_auth = ('wronguser', 'wrongpass')\n@@ -2575,4 +2584,4 @@ def test_post_json_nan(self, httpbin):\n def test_json_decode_compatibility(self, httpbin):\n r = requests.get(httpbin('bytes/20'))\n with pytest.raises(requests.exceptions.JSONDecodeError):\n- r.json()\n\\ No newline at end of file\n+ r.json()" } ], "reviews": [ { "id": 745305500, "user": "user_8e4c67791fa1", "state": "COMMENTED", "body": "Hey [USER_REDACTED], thanks for this!\nI added a few comments following up on our discussions.", "submitted_at": "2021-09-02T17:04:31+00:00" }, { "id": 745325581, "user": "user_dbf2a999bd6d", "state": "COMMENTED", "body": null, "submitted_at": "2021-09-02T17:13:41+00:00" }, { "id": 745326796, "user": "user_dbf2a999bd6d", "state": "COMMENTED", "body": null, "submitted_at": "2021-09-02T17:14:52+00:00" }, { "id": 745327920, "user": "user_dbf2a999bd6d", "state": "COMMENTED", "body": null, "submitted_at": "2021-09-02T17:16:02+00:00" }, { "id": 746610261, "user": "user_c3e2f6665894", "state": "CHANGES_REQUESTED", "body": "[](https://github.com/psf/requests/pull/5924/files)", "submitted_at": "2021-09-05T03:46:43+00:00" }, { "id": 748630378, "user": "user_7d82597c3e08", "state": "COMMENTED", "body": null, "submitted_at": "2021-09-08T04:23:38+00:00" }, { "id": 748630480, "user": "user_7d82597c3e08", "state": "APPROVED", "body": null, "submitted_at": "2021-09-08T04:23:52+00:00" }, { "id": 815299898, "user": "user_0fa58b6f3572", "state": "APPROVED", "body": null, "submitted_at": "2021-11-24T19:17:39+00:00" } ], "review_comments": [ { "id": 701262009, "user": "user_8e4c67791fa1", "body": "This change should actually fix the performance regression in most cases (`Session.request` - which I assume is the most common flow - always sets `proxies` on `kwargs`).", "path": "requests/sessions.py", "line": 623, "side": "RIGHT", "created_at": "2021-09-02T16:52:25+00:00" }, { "id": 701265200, "user": "user_8e4c67791fa1", "body": "So now we're:\n1. No longer stripping the proxy-auth header. Sounds right to me.\n2. No longer setting the proxy-auth header at all. Is this the desired behavior? What if someone uses a proxy and passes the username + password in the url? (though I'm not sure if that flow is supported or not)", "path": "requests/sessions.py", "line": 624, "side": "RIGHT", "created_at": "2021-09-02T16:56:54+00:00" }, { "id": 701266063, "user": "user_8e4c67791fa1", "body": "Didn't we want to unify 850 and 851 so we don't call `should_bypass_proxies` if `trust_env` is `False`?", "path": "requests/utils.py", "line": 850, "side": "RIGHT", "created_at": "2021-09-02T16:58:04+00:00" }, { "id": 701276964, "user": "user_dbf2a999bd6d", "body": "For 2.) we were never doing that before this change and I don't think that was an intended byproduct. We should still support our normal proxy auth flows that were available prior to #5681.", "path": "requests/sessions.py", "line": 624, "side": "RIGHT", "created_at": "2021-09-02T17:13:41+00:00" }, { "id": 701277868, "user": "user_dbf2a999bd6d", "body": "We do, I was going to have [USER_REDACTED] rebase their change onto whatever we merge so they can still have a commit in the repo.", "path": "requests/utils.py", "line": 850, "side": "RIGHT", "created_at": "2021-09-02T17:14:52+00:00" }, { "id": 701278739, "user": "user_dbf2a999bd6d", "body": "Yep, I think `proxies` will be the escape hatch when performance is a concern here :)", "path": "requests/sessions.py", "line": 623, "side": "RIGHT", "created_at": "2021-09-02T17:16:02+00:00" }, { "id": 704014493, "user": "user_7d82597c3e08", "body": "Sounds good to me.", "path": "requests/utils.py", "line": 850, "side": "RIGHT", "created_at": "2021-09-08T04:23:38+00:00" } ], "meta": { "languages": [ "py" ], "touches_tests": true, "review_state_summary": { "COMMENTED": 5, "CHANGES_REQUESTED": 1, "APPROVED": 2 }, "meaningful_comment_count": 7, "has_approval": true, "has_changes_requested": true, "total_review_comments": 7 } } { "_id": "911de196efb6a478", "_schema_version": "1.0", "_cleaned_at": "2026-02-12T07:46:51.426293+00:00", "repo": "psf/requests", "repo_url": "https://github.com/psf/requests", "license_name": "Apache License 2.0", "license_spdx": "Apache-2.0", "pr_number": 5917, "title": "Move from urlparse to parse_url for prepending schemes", "body": "This addresses the base problem raised in #5855 with the `urlparse` changes in Python 3.9 and potential issues in future 3.7/3.8 releases. We've avoided changing other uses of `urlparse` for now due to issues with `parse_url`'s strict validation requirements when performing parsing.", "author": "user_dbf2a999bd6d", "created_at": "2021-08-27T19:10:24+00:00", "merged_at": "2021-12-29T13:31:40+00:00", "base_branch": "main", "head_branch": "proxy_scheme_unknown_fix", "additions": 16, "deletions": 6, "changed_files": 2, "files": [ { "filename": "requests/utils.py", "status": "modified", "additions": 15, "deletions": 6, "changes": 21, "patch": "@@ -21,6 +21,7 @@\n import zipfile\n from collections import OrderedDict\n from urllib3.util import make_headers\n+from urllib3.util import parse_url\n \n from .__version__ import __version__\n from . import certs\n@@ -963,15 +964,23 @@ def prepend_scheme_if_needed(url, new_scheme):\n \n :rtype: str\n \"\"\"\n- scheme, netloc, path, params, query, fragment = urlparse(url, new_scheme)\n-\n- # urlparse is a finicky beast, and sometimes decides that there isn't a\n- # netloc present. Assume that it's being over-cautious, and switch netloc\n- # and path if urlparse decided there was no netloc.\n+ parsed = parse_url(url)\n+ scheme, auth, host, port, path, query, fragment = parsed\n+\n+ # A defect in urlparse determines that there isn't a netloc present in some\n+ # urls. We previously assumed parsing was overly cautious, and swapped the\n+ # netloc and path. Due to a lack of tests on the original defect, this is\n+ # maintained with parse_url for backwards compatibility.\n+ netloc = parsed.netloc\n if not netloc:\n netloc, path = path, netloc\n \n- return urlunparse((scheme, netloc, path, params, query, fragment))\n+ if scheme is None:\n+ scheme = new_scheme\n+ if path is None:\n+ path = ''\n+\n+ return urlunparse((scheme, netloc, path, '', query, fragment))\n \n \n def get_auth_from_url(url):" }, { "filename": "tests/test_utils.py", "status": "modified", "additions": 1, "deletions": 0, "changes": 1, "patch": "@@ -601,6 +601,7 @@ def test_parse_header_links(value, expected):\n 'value, expected', (\n ('example.com/path', 'http://example.com/path'),\n ('//example.com/path', 'http://example.com/path'),\n+ ('example.com:80', 'http://example.com:80'),\n ))\n def test_prepend_scheme_if_needed(value, expected):\n assert prepend_scheme_if_needed(value, 'http') == expected" } ], "reviews": [ { "id": 822219138, "user": "user_b08fb5f52ea1", "state": "COMMENTED", "body": null, "submitted_at": "2021-12-03T03:18:15+00:00" }, { "id": 824690204, "user": "user_dbf2a999bd6d", "state": "COMMENTED", "body": null, "submitted_at": "2021-12-07T01:46:39+00:00" }, { "id": 841177404, "user": "user_dbf2a999bd6d", "state": "COMMENTED", "body": null, "submitted_at": "2021-12-29T04:13:20+00:00" }, { "id": 841407199, "user": "user_0fa58b6f3572", "state": "APPROVED", "body": null, "submitted_at": "2021-12-29T13:31:34+00:00" } ], "review_comments": [ { "id": 761620552, "user": "user_b08fb5f52ea1", "body": "Uhhh, what? This doesn't make any sense to me, is this something that's only needed for `urlparse`?", "path": "requests/utils.py", "line": 974, "side": "RIGHT", "created_at": "2021-12-03T03:18:15+00:00" }, { "id": 763565145, "user": "user_dbf2a999bd6d", "body": "Yeah, this is only a quirk for `urlparse`. I'd thought I repro'd with `parse_url` initially, but I'm unable to now.\n\nI'll reword the whole comment for clarity. I'm not confident the test suite covers all of the initial issue though. I think I'm still in favor of leaving the swap in place as a fallback for anything we're missing.", "path": "requests/utils.py", "line": 974, "side": "RIGHT", "created_at": "2021-12-07T01:46:39+00:00" }, { "id": 776146587, "user": "user_dbf2a999bd6d", "body": "[USER_REDACTED] I've reworded things to be a bit clearer.", "path": "requests/utils.py", "line": 974, "side": "RIGHT", "created_at": "2021-12-29T04:13:20+00:00" } ], "meta": { "languages": [ "py" ], "touches_tests": true, "review_state_summary": { "COMMENTED": 3, "APPROVED": 1 }, "meaningful_comment_count": 3, "has_approval": true, "has_changes_requested": false, "total_review_comments": 3 } } { "_id": "152a7d907f1549be", "_schema_version": "1.0", "_cleaned_at": "2026-02-12T07:46:51.427292+00:00", "repo": "psf/requests", "repo_url": "https://github.com/psf/requests", "license_name": "Apache License 2.0", "license_spdx": "Apache-2.0", "pr_number": 5909, "title": "Add thread locker workflow", "body": null, "author": "user_0fa58b6f3572", "created_at": "2021-08-25T00:23:19+00:00", "merged_at": "2021-08-25T18:21:36+00:00", "base_branch": "main", "head_branch": "lock-threads", "additions": 15, "deletions": 0, "changed_files": 1, "files": [ { "filename": ".github/workflows/lock-issues.yml", "status": "added", "additions": 15, "deletions": 0, "changes": 15, "patch": "@@ -0,0 +1,15 @@\n+name: '[NAME_REDACTED]'\n+\n+on:\n+ schedule:\n+ - cron: '0 0 * * *'\n+\n+permissions:\n+ issues: write\n+ pull-requests: write\n+\n+jobs:\n+ action:\n+ runs-on: ubuntu-latest\n+ steps:\n+ - uses: dessant/lock-threads@v2" } ], "reviews": [ { "id": 737824574, "user": "user_dbf2a999bd6d", "state": "CHANGES_REQUESTED", "body": "Just a minor fix needed and then I think this looks good. Thanks, [USER_REDACTED]!", "submitted_at": "2021-08-25T01:49:19+00:00" }, { "id": 737827383, "user": "user_dbf2a999bd6d", "state": "COMMENTED", "body": null, "submitted_at": "2021-08-25T01:55:27+00:00" }, { "id": 738521818, "user": "user_dbf2a999bd6d", "state": "APPROVED", "body": "🚀", "submitted_at": "2021-08-25T15:40:31+00:00" }, { "id": 738694200, "user": "user_0fa58b6f3572", "state": "COMMENTED", "body": null, "submitted_at": "2021-08-25T18:24:30+00:00" } ], "review_comments": [ { "id": 695330209, "user": "user_dbf2a999bd6d", "body": "It looks like this got clipped during copy. `me`->`name`", "path": ".github/workflows/lock-issues.yml", "line": null, "side": "RIGHT", "created_at": "2021-08-25T01:48:29+00:00" }, { "id": 695332737, "user": "user_dbf2a999bd6d", "body": "Actually one more thought while we're here. It looks like some other projects have [shortened the window](https://github.com/pyca/pyopenssl/blob/main/.github/workflows/lock.yml#L13-L14) from 365 days to 90. That may be more reasonable to prevent unrelated pings resetting such a long timer.", "path": ".github/workflows/lock-issues.yml", "line": 15, "side": "RIGHT", "created_at": "2021-08-25T01:55:27+00:00" }, { "id": 696008774, "user": "user_0fa58b6f3572", "body": "Oh, I missed this. Hold on. #5911", "path": ".github/workflows/lock-issues.yml", "line": 15, "side": "RIGHT", "created_at": "2021-08-25T18:24:30+00:00" } ], "meta": { "languages": [ "yml" ], "touches_tests": false, "review_state_summary": { "CHANGES_REQUESTED": 1, "COMMENTED": 2, "APPROVED": 1 }, "meaningful_comment_count": 3, "has_approval": true, "has_changes_requested": true, "total_review_comments": 3 } } { "_id": "61e193af1c56f5a7", "_schema_version": "1.0", "_cleaned_at": "2026-02-12T07:46:51.434626+00:00", "repo": "psf/requests", "repo_url": "https://github.com/psf/requests", "license_name": "Apache License 2.0", "license_spdx": "Apache-2.0", "pr_number": 5856, "title": "Fix inconsistent exception type in response.json() method", "body": "## Summary\nFixes the inconsistency of errors thrown in the `response.json()` method in `models.py`, while preserving backwards compatibility. \n\n### What we used to have\nDepending on whether or not `simplejson` was installed in the user's library, and whether the user was running Python 3+ versus Python 2, a different exception would get thrown when there was an issue with decoding response text as JSON. If `simplejson` was installed, `simplejson.JSONDecodeError` would get thrown. If not, `json.JSONDecodeError` would get thrown for Python 3+ users, and `ValueError` for Python 2 users. Thus, depending on the scenario, users would find themselves having to catch either `simplejson.JSONDecodeError`, `json.JSONDecodeError`, or `ValueError` in the case of the `response.json()` method failing. This inconsistency is not ideal.\n\n### What we have now\nThere is now one error class in `exceptions.py` that will represent all errors that can be thrown or caught in the `response.json()` method: `requests.JSONDecodeError`. All `simplejson` functionality was replaced with `json` functionality, but the new error type aliases both `json.JSONDecodeError` and `simplejson.JSONDecodeError`. If `simplejson` is not installed, its `JSONDecodError` is replaced with a plain `Exception` when aliased. If the user is running Python 3+, `json.JSONDecodeError` is aliased, but if the user is running Python 2, that is replaced with `ValueError` when aliased, as the `JSONDecodeError` was not previously a part of the `json` library. Now, all five error types, `json.JSONDecodeError`, `simplejson.JSONDecodeError`, `ValueError`, and `requests.JSONDecodeError` and its parent class `requests.RequestException`, will be caught from the `requests.JSONDecodeError` that will be raised.\n\nFixes #5794\n[USER_REDACTED]", "author": "user_a7b578c0e355", "created_at": "2021-07-03T21:08:32+00:00", "merged_at": "2021-07-26T15:56:44+00:00", "base_branch": "master", "head_branch": "json-opt-2", "additions": 47, "deletions": 18, "changed_files": 7, "files": [ { "filename": "HISTORY.md", "status": "modified", "additions": 6, "deletions": 1, "changes": 7, "patch": "@@ -4,7 +4,12 @@ Release History\n dev\n ---\n \n-- \\[Short description of non-trivial change.\\]\n+- \\[Short description of non-trivial change.\\]\n+\n+- Added a `requests.exceptions.JSONDecodeError` to decrease inconsistencies\n+ in the library. This gets raised in the `response.json()` method, and is\n+ backwards compatible as it inherits from previously thrown exceptions.\n+ Can be caught from `requests.exceptions.RequestException` as well.\n \n 2.26.0 (2021-07-13)\n -------------------" }, { "filename": "docs/user/quickstart.rst", "status": "modified", "additions": 3, "deletions": 3, "changes": 6, "patch": "@@ -153,9 +153,9 @@ There's also a builtin JSON decoder, in case you're dealing with JSON data::\n \n In case the JSON decoding fails, ``r.json()`` raises an exception. For example, if\n the response gets a 204 ([NAME_REDACTED]), or if the response contains invalid JSON,\n-attempting ``r.json()`` raises ``simplejson.JSONDecodeError`` if simplejson is\n-installed or raises ``ValueError: No JSON object could be decoded`` on Python 2 or\n-``json.JSONDecodeError`` on Python 3.\n+attempting ``r.json()`` raises ``requests.exceptions.JSONDecodeError``. This wrapper exception\n+provides interoperability for multiple exceptions that may be thrown by different\n+python versions and json serialization libraries.\n \n It should be noted that the success of the call to ``r.json()`` does **not**\n indicate the success of the response. Some servers may return a JSON object in a" }, { "filename": "requests/__init__.py", "status": "modified", "additions": 1, "deletions": 1, "changes": 2, "patch": "@@ -139,7 +139,7 @@ def _check_cryptography(cryptography_version):\n from .exceptions import (\n RequestException, Timeout, URLRequired,\n TooManyRedirects, HTTPError, ConnectionError,\n- FileModeWarning, ConnectTimeout, ReadTimeout\n+ FileModeWarning, ConnectTimeout, ReadTimeout, JSONDecodeError\n )\n \n # Set default logging handler to avoid \"No handler found\" warnings." }, { "filename": "requests/compat.py", "status": "modified", "additions": 7, "deletions": 1, "changes": 8, "patch": "@@ -28,8 +28,10 @@\n #: Python 3.x?\n is_py3 = (_ver[0] == 3)\n \n+has_simplejson = False\n try:\n import simplejson as json\n+ has_simplejson = True\n except ImportError:\n import json\n \n@@ -49,13 +51,13 @@\n # [NAME_REDACTED] for backwards compatibility.\n from collections import Callable, Mapping, MutableMapping, OrderedDict\n \n-\n builtin_str = str\n bytes = str\n str = unicode\n basestring = basestring\n numeric_types = (int, long, float)\n integer_types = (int, long)\n+ JSONDecodeError = ValueError\n \n elif is_py3:\n from urllib.parse import urlparse, urlunparse, urljoin, urlsplit, urlencode, quote, unquote, quote_plus, unquote_plus, urldefrag\n@@ -66,6 +68,10 @@\n # [NAME_REDACTED] for backwards compatibility.\n from collections import OrderedDict\n from collections.abc import Callable, Mapping, MutableMapping\n+ if has_simplejson:\n+ from simplejson import JSONDecodeError\n+ else:\n+ from json import JSONDecodeError\n \n builtin_str = str\n str = str" }, { "filename": "requests/exceptions.py", "status": "modified", "additions": 6, "deletions": 0, "changes": 6, "patch": "@@ -8,6 +8,8 @@\n \"\"\"\n from urllib3.exceptions import HTTPError as BaseHTTPError\n \n+from .compat import JSONDecodeError as CompatJSONDecodeError\n+\n \n class RequestException(IOError):\n \"\"\"There was an ambiguous exception that occurred while handling your\n@@ -29,6 +31,10 @@ class InvalidJSONError(RequestException):\n \"\"\"A JSON error occurred.\"\"\"\n \n \n+class JSONDecodeError(InvalidJSONError, CompatJSONDecodeError):\n+ \"\"\"Couldn't decode the text into json\"\"\"\n+\n+\n class HTTPError(RequestException):\n \"\"\"An HTTP error occurred.\"\"\"" }, { "filename": "requests/models.py", "status": "modified", "additions": 18, "deletions": 11, "changes": 29, "patch": "@@ -29,7 +29,9 @@\n from .cookies import cookiejar_from_dict, get_cookie_header, _copy_cookie_jar\n from .exceptions import (\n HTTPError, MissingSchema, InvalidURL, ChunkedEncodingError,\n- ContentDecodingError, ConnectionError, StreamConsumedError, InvalidJSONError)\n+ ContentDecodingError, ConnectionError, StreamConsumedError,\n+ InvalidJSONError)\n+from .exceptions import JSONDecodeError as RequestsJSONDecodeError\n from ._internal_utils import to_native_string, unicode_is_ascii\n from .utils import (\n guess_filename, get_auth_from_url, requote_uri,\n@@ -38,7 +40,7 @@\n from .compat import (\n Callable, Mapping,\n cookielib, urlunparse, urlsplit, urlencode, str, bytes,\n- is_py2, chardet, builtin_str, basestring)\n+ is_py2, chardet, builtin_str, basestring, JSONDecodeError)\n from .compat import json as complexjson\n from .status_codes import codes\n \n@@ -468,9 +470,9 @@ def prepare_body(self, data, files, json=None):\n content_type = 'application/json'\n \n try:\n- body = complexjson.dumps(json, allow_nan=False)\n+ body = complexjson.dumps(json, allow_nan=False)\n except ValueError as ve:\n- raise InvalidJSONError(ve, request=self)\n+ raise InvalidJSONError(ve, request=self)\n \n if not isinstance(body, bytes):\n body = body.encode('utf-8')\n@@ -882,12 +884,8 @@ def json(self, **kwargs):\n r\"\"\"Returns the json-encoded content of a response, if any.\n \n :param \\*\\*kwargs: Optional arguments that ``json.loads`` takes.\n- :raises simplejson.JSONDecodeError: If the response body does not\n- contain valid json and simplejson is installed.\n- :raises json.JSONDecodeError: If the response body does not contain\n- valid json and simplejson is not installed on Python 3.\n- :raises ValueError: If the response body does not contain valid\n- json and simplejson is not installed on Python 2. \n+ :raises requests.exceptions.JSONDecodeError: If the response body does not\n+ contain valid json.\n \"\"\"\n \n if not self.encoding and self.content and len(self.content) > 3:\n@@ -907,7 +905,16 @@ def json(self, **kwargs):\n # and the server didn't bother to tell us what codec *was*\n # used.\n pass\n- return complexjson.loads(self.text, **kwargs)\n+\n+ try:\n+ return complexjson.loads(self.text, **kwargs)\n+ except JSONDecodeError as e:\n+ # Catch JSON-related errors and raise as requests.JSONDecodeError\n+ # This aliases json.JSONDecodeError and simplejson.JSONDecodeError\n+ if is_py2: # e is a ValueError\n+ raise RequestsJSONDecodeError(e.message)\n+ else:\n+ raise RequestsJSONDecodeError(e.msg, e.doc, e.pos)\n \n [USER_REDACTED]\n def links(self):" }, { "filename": "tests/test_requests.py", "status": "modified", "additions": 6, "deletions": 1, "changes": 7, "patch": "@@ -2570,4 +2570,9 @@ def test_parameters_for_nonstandard_schemes(self, input, params, expected):\n def test_post_json_nan(self, httpbin):\n data = {\"foo\": float(\"nan\")}\n with pytest.raises(requests.exceptions.InvalidJSONError):\n- r = requests.post(httpbin('post'), json=data)\n\\ No newline at end of file\n+ r = requests.post(httpbin('post'), json=data)\n+\n+ def test_json_decode_compatibility(self, httpbin):\n+ r = requests.get(httpbin('bytes/20'))\n+ with pytest.raises(requests.exceptions.JSONDecodeError):\n+ r.json()\n\\ No newline at end of file" } ], "reviews": [ { "id": 699315720, "user": "user_0fa58b6f3572", "state": "COMMENTED", "body": null, "submitted_at": "2021-07-05T16:19:59+00:00" }, { "id": 699316144, "user": "user_0fa58b6f3572", "state": "COMMENTED", "body": null, "submitted_at": "2021-07-05T16:20:44+00:00" }, { "id": 699316298, "user": "user_0fa58b6f3572", "state": "COMMENTED", "body": null, "submitted_at": "2021-07-05T16:21:02+00:00" }, { "id": 699316479, "user": "user_0fa58b6f3572", "state": "COMMENTED", "body": null, "submitted_at": "2021-07-05T16:21:22+00:00" }, { "id": 699316559, "user": "user_0fa58b6f3572", "state": "COMMENTED", "body": null, "submitted_at": "2021-07-05T16:21:31+00:00" }, { "id": 699316628, "user": "user_0fa58b6f3572", "state": "COMMENTED", "body": null, "submitted_at": "2021-07-05T16:21:38+00:00" }, { "id": 699316758, "user": "user_0fa58b6f3572", "state": "COMMENTED", "body": null, "submitted_at": "2021-07-05T16:21:53+00:00" }, { "id": 699316823, "user": "user_0fa58b6f3572", "state": "COMMENTED", "body": null, "submitted_at": "2021-07-05T16:22:00+00:00" }, { "id": 699316875, "user": "user_0fa58b6f3572", "state": "COMMENTED", "body": null, "submitted_at": "2021-07-05T16:22:07+00:00" }, { "id": 699317046, "user": "user_0fa58b6f3572", "state": "COMMENTED", "body": null, "submitted_at": "2021-07-05T16:22:29+00:00" }, { "id": 699317076, "user": "user_0fa58b6f3572", "state": "COMMENTED", "body": null, "submitted_at": "2021-07-05T16:22:33+00:00" }, { "id": 699317173, "user": "user_0fa58b6f3572", "state": "COMMENTED", "body": null, "submitted_at": "2021-07-05T16:22:44+00:00" }, { "id": 699317498, "user": "user_0fa58b6f3572", "state": "COMMENTED", "body": null, "submitted_at": "2021-07-05T16:23:21+00:00" }, { "id": 699318082, "user": "user_0fa58b6f3572", "state": "COMMENTED", "body": null, "submitted_at": "2021-07-05T16:24:32+00:00" }, { "id": 699318141, "user": "user_0fa58b6f3572", "state": "COMMENTED", "body": null, "submitted_at": "2021-07-05T16:24:39+00:00" }, { "id": 699318192, "user": "user_0fa58b6f3572", "state": "COMMENTED", "body": null, "submitted_at": "2021-07-05T16:24:44+00:00" }, { "id": 699318680, "user": "user_0fa58b6f3572", "state": "COMMENTED", "body": null, "submitted_at": "2021-07-05T16:25:43+00:00" }, { "id": 699320121, "user": "user_a7b578c0e355", "state": "COMMENTED", "body": null, "submitted_at": "2021-07-05T16:28:31+00:00" }, { "id": 699322273, "user": "user_a7b578c0e355", "state": "COMMENTED", "body": null, "submitted_at": "2021-07-05T16:32:45+00:00" }, { "id": 699327859, "user": "user_0fa58b6f3572", "state": "COMMENTED", "body": null, "submitted_at": "2021-07-05T16:44:57+00:00" }, { "id": 700469010, "user": "user_0fa58b6f3572", "state": "COMMENTED", "body": null, "submitted_at": "2021-07-07T00:02:39+00:00" }, { "id": 700469936, "user": "user_0fa58b6f3572", "state": "APPROVED", "body": null, "submitted_at": "2021-07-07T00:05:18+00:00" }, { "id": 703242572, "user": "user_dbf2a999bd6d", "state": "CHANGES_REQUESTED", "body": null, "submitted_at": "2021-07-09T17:25:28+00:00" }, { "id": 703257872, "user": "user_dbf2a999bd6d", "state": "COMMENTED", "body": null, "submitted_at": "2021-07-09T17:26:43+00:00" }, { "id": 703278537, "user": "user_dbf2a999bd6d", "state": "COMMENTED", "body": null, "submitted_at": "2021-07-09T17:56:48+00:00" }, { "id": 704227741, "user": "user_a7b578c0e355", "state": "COMMENTED", "body": null, "submitted_at": "2021-07-12T15:07:16+00:00" }, { "id": 705748435, "user": "user_0fa58b6f3572", "state": "COMMENTED", "body": null, "submitted_at": "2021-07-14T00:25:16+00:00" }, { "id": 706822735, "user": "user_0fa58b6f3572", "state": "CHANGES_REQUESTED", "body": null, "submitted_at": "2021-07-15T00:31:01+00:00" }, { "id": 708264387, "user": "user_0fa58b6f3572", "state": "APPROVED", "body": null, "submitted_at": "2021-07-16T11:18:20+00:00" }, { "id": 706441683, "user": "user_dbf2a999bd6d", "state": "COMMENTED", "body": "Thanks for the updates, [USER_REDACTED]. I added a couple of comments for discussion. I'm not convinced they're necessarily the right direction, but it does feel like the simplejson/json problems are potentially being spread more places than needed.\n\nLet me know what you think, thanks!", "submitted_at": "2021-07-16T18:22:12+00:00" }, { "id": 710735484, "user": "user_a7b578c0e355", "state": "COMMENTED", "body": null, "submitted_at": "2021-07-20T15:40:55+00:00" }, { "id": 710910737, "user": "user_dbf2a999bd6d", "state": "COMMENTED", "body": null, "submitted_at": "2021-07-20T17:53:18+00:00" }, { "id": 710943013, "user": "user_a7b578c0e355", "state": "COMMENTED", "body": null, "submitted_at": "2021-07-20T18:30:36+00:00" }, { "id": 713331292, "user": "user_a7b578c0e355", "state": "COMMENTED", "body": null, "submitted_at": "2021-07-23T00:36:29+00:00" }, { "id": 713360941, "user": "user_dbf2a999bd6d", "state": "COMMENTED", "body": null, "submitted_at": "2021-07-23T02:30:46+00:00" }, { "id": 713744325, "user": "user_a7b578c0e355", "state": "COMMENTED", "body": null, "submitted_at": "2021-07-23T13:47:08+00:00" }, { "id": 714234668, "user": "user_0fa58b6f3572", "state": "APPROVED", "body": null, "submitted_at": "2021-07-24T13:31:10+00:00" }, { "id": 714254560, "user": "user_dbf2a999bd6d", "state": "APPROVED", "body": "Cool, I think this looks like we’re ready now. Thanks for seeing this through, [USER_REDACTED].\n\nFor merging, I’m not sure if we want to put this on a 2.27.x branch while we wait for the next release, or if we merge now knowing we won’t do another patch release for 2.26.x. Any thoughts [USER_REDACTED]?", "submitted_at": "2021-07-24T19:05:56+00:00" } ], "review_comments": [ { "id": 664037480, "user": "user_0fa58b6f3572", "body": "This is backwards incompatible and needs to be reverted", "path": "requests/compat.py", "line": null, "side": "LEFT", "created_at": "2021-07-05T16:19:59+00:00" }, { "id": 664037858, "user": "user_0fa58b6f3572", "body": "I forgot we had this exception, where do we use it? Should we sub-class this in `JSONDecodeError` as well?", "path": "requests/exceptions.py", "line": null, "side": "RIGHT", "created_at": "2021-07-05T16:20:44+00:00" }, { "id": 664037984, "user": "user_0fa58b6f3572", "body": "Why did you change this?", "path": "requests/models.py", "line": null, "side": "RIGHT", "created_at": "2021-07-05T16:21:01+00:00" }, { "id": 664038143, "user": "user_0fa58b6f3572", "body": "Please revert this. It's tangential to the change", "path": "requests/models.py", "line": null, "side": "RIGHT", "created_at": "2021-07-05T16:21:22+00:00" }, { "id": 664038217, "user": "user_0fa58b6f3572", "body": "Please revert this as well", "path": "requests/models.py", "line": null, "side": "RIGHT", "created_at": "2021-07-05T16:21:31+00:00" }, { "id": 664038264, "user": "user_0fa58b6f3572", "body": "Please revert this", "path": "requests/models.py", "line": null, "side": "RIGHT", "created_at": "2021-07-05T16:21:38+00:00" }, { "id": 664038389, "user": "user_0fa58b6f3572", "body": "Please revert this", "path": "requests/models.py", "line": null, "side": "RIGHT", "created_at": "2021-07-05T16:21:52+00:00" }, { "id": 664038455, "user": "user_0fa58b6f3572", "body": "Please revert this", "path": "requests/models.py", "line": null, "side": "RIGHT", "created_at": "2021-07-05T16:22:00+00:00" }, { "id": 664038511, "user": "user_0fa58b6f3572", "body": "Please revert this", "path": "requests/models.py", "line": null, "side": "RIGHT", "created_at": "2021-07-05T16:22:07+00:00" }, { "id": 664038661, "user": "user_0fa58b6f3572", "body": "Please revert this", "path": "requests/models.py", "line": null, "side": "RIGHT", "created_at": "2021-07-05T16:22:28+00:00" }, { "id": 664038684, "user": "user_0fa58b6f3572", "body": "Please revert this", "path": "requests/models.py", "line": null, "side": "RIGHT", "created_at": "2021-07-05T16:22:33+00:00" }, { "id": 664038757, "user": "user_0fa58b6f3572", "body": "Please revert this", "path": "requests/models.py", "line": null, "side": "RIGHT", "created_at": "2021-07-05T16:22:44+00:00" }, { "id": 664039064, "user": "user_0fa58b6f3572", "body": "Please document this as `requests.exceptions.JSONDecodeError`. Eventually I desperately want to stop importing every exception class into `requests/__init__.py`", "path": "requests/models.py", "line": null, "side": "RIGHT", "created_at": "2021-07-05T16:23:21+00:00" }, { "id": 664039537, "user": "user_0fa58b6f3572", "body": "We should probably preserve the original exception instance in this as well and proxy attributes down to it. That way folks can find the original exception. I'm not certain `simplejson` and `json` have the same exception attributes with the same meaning", "path": "requests/models.py", "line": null, "side": "RIGHT", "created_at": "2021-07-05T16:24:32+00:00" }, { "id": 664039589, "user": "user_0fa58b6f3572", "body": "Please revert this", "path": "requests/models.py", "line": null, "side": "RIGHT", "created_at": "2021-07-05T16:24:39+00:00" }, { "id": 664039631, "user": "user_0fa58b6f3572", "body": "Please revert this", "path": "requests/models.py", "line": null, "side": "RIGHT", "created_at": "2021-07-05T16:24:44+00:00" }, { "id": 664040057, "user": "user_0fa58b6f3572", "body": "We must be clear that this is _new_ in the next version of Requests (add it to our changelog too) and that it is backwards compatible as it inherits from the exceptions raised previously", "path": "docs/user/quickstart.rst", "line": null, "side": "RIGHT", "created_at": "2021-07-05T16:25:43+00:00" }, { "id": 664041283, "user": "user_a7b578c0e355", "body": "Do you want me to add it to the changelog now or do you like to do that?", "path": "docs/user/quickstart.rst", "line": null, "side": "RIGHT", "created_at": "2021-07-05T16:28:30+00:00" }, { "id": 664043187, "user": "user_a7b578c0e355", "body": "I added this exception to sub-class both `JSONDecodeError`s", "path": "requests/exceptions.py", "line": null, "side": "RIGHT", "created_at": "2021-07-05T16:32:45+00:00" }, { "id": 664047954, "user": "user_0fa58b6f3572", "body": "Please add it to the changelog now", "path": "docs/user/quickstart.rst", "line": null, "side": "RIGHT", "created_at": "2021-07-05T16:44:57+00:00" }, { "id": 664949709, "user": "user_0fa58b6f3572", "body": "I'm talking about the `InvalidJSONError` exception here (the line I commented on)", "path": "requests/exceptions.py", "line": null, "side": "RIGHT", "created_at": "2021-07-07T00:02:39+00:00" }, { "id": 667093966, "user": "user_dbf2a999bd6d", "body": "We probably don't want to add all the information in the last sentence as it will become stale quickly. Let's simplfy it to something closer to:\n\n> This wrapper exception provides interoperability for multiple exceptions that may be thrown by [NAME_REDACTED] json serialization libraries.", "path": "docs/user/quickstart.rst", "line": null, "side": "RIGHT", "created_at": "2021-07-09T17:04:51+00:00" }, { "id": 667094313, "user": "user_dbf2a999bd6d", "body": "These spacing changes aren't really related to the current PR, can we remove them.", "path": "requests/compat.py", "line": null, "side": "RIGHT", "created_at": "2021-07-09T17:05:30+00:00" }, { "id": 667095839, "user": "user_dbf2a999bd6d", "body": "Our custom exceptions in Requests should ideally fall under a catch-all parent exception, `RequestException`. That allows users to catch everything thrown by Requests.", "path": "requests/exceptions.py", "line": null, "side": "RIGHT", "created_at": "2021-07-09T17:08:32+00:00" }, { "id": 667096117, "user": "user_dbf2a999bd6d", "body": "I think we're still waiting on a response here, [USER_REDACTED].", "path": "requests/exceptions.py", "line": null, "side": "RIGHT", "created_at": "2021-07-09T17:09:04+00:00" }, { "id": 667104578, "user": "user_dbf2a999bd6d", "body": "I'm not sure I'm following how this will work in the Python 2 `json` case. Where is `ValueError` being handled?", "path": "requests/models.py", "line": null, "side": "RIGHT", "created_at": "2021-07-09T17:24:48+00:00" }, { "id": 667105634, "user": "user_dbf2a999bd6d", "body": "https://github.com/psf/requests/pull/5856/checks?check_run_id=3031103164 Yeah, this is broken. We need to be able to handle this a different way.", "path": "requests/models.py", "line": null, "side": "RIGHT", "created_at": "2021-07-09T17:26:43+00:00" }, { "id": 667121799, "user": "user_dbf2a999bd6d", "body": "I see your last comment was made outside of this thread, [USER_REDACTED]. To clarify, while `json.JSONDecodeError` does inherit from `ValueError`, it's not going to work in this case. The exception doesn't exist in Python 2, so we fall over with an attribute error when handling the exception. You'll need to take another approach to handle this.", "path": "requests/models.py", "line": null, "side": "RIGHT", "created_at": "2021-07-09T17:56:48+00:00" }, { "id": 668015646, "user": "user_a7b578c0e355", "body": "Yes, I can subclass that in `JSONDecodeError` as well.", "path": "requests/exceptions.py", "line": null, "side": "RIGHT", "created_at": "2021-07-12T15:07:16+00:00" }, { "id": 669195075, "user": "user_0fa58b6f3572", "body": "Giving the user 0 useful information is unacceptable. Why can't we use `e.message` there?\n\n```py\nPython 2.7.18 (default, May 19 2021, 00:00:00)\n[GCC 11.1.1 20210428 ([NAME_REDACTED] 11.1.1-1)] on linux2\nType \"help\", \"copyright\", \"credits\" or \"license\" for more information.\n>>> import json\n>>> try:\n... json.loads(\"foo\")\n... except ValueError as ve:\n... pass\n...\n>>> dir(ve)\n['__class__', '__delattr__', '__dict__', '__doc__', '__format__', '__getattribute__', '__getitem__', '__getslice__', '__hash__', '__init__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__setstate__', '__sizeof__', '__str__', '__subclasshook__', '__unicode__', 'args', 'message']\n>>> ve.message\n'No JSON object could be decoded'\n>>> ve.args\n('No JSON object could be decoded',)\n>>>\n```", "path": "requests/models.py", "line": null, "side": "RIGHT", "created_at": "2021-07-14T00:25:15+00:00" }, { "id": 669741494, "user": "user_dbf2a999bd6d", "body": "It doesn't look like we use this anywhere except to declare the exceptions. We're already setting either dependency to be imported under the `json` namespace. Can we not just do `from json import JSONDecodeError` under the py3 section and have it automatically resolve? Perhaps adding a short comment above the import saying it's using simplejson or json depending on what was resolved?", "path": "requests/compat.py", "line": 31, "side": "RIGHT", "created_at": "2021-07-14T15:49:47+00:00" }, { "id": 670040646, "user": "user_0fa58b6f3572", "body": "Why did you remove this?", "path": "HISTORY.md", "line": null, "side": "LEFT", "created_at": "2021-07-15T00:29:52+00:00" }, { "id": 670040807, "user": "user_0fa58b6f3572", "body": "2.26.0 was released. This can not be added to those notes as this was not released with 2.26.0 please move it above the `2.26.0 (2021-07-13)` line.", "path": "HISTORY.md", "line": null, "side": "RIGHT", "created_at": "2021-07-15T00:30:22+00:00" }, { "id": 670040920, "user": "user_0fa58b6f3572", "body": "These changes in this file are unrelated and should be in a separate PR", "path": "docs/api.rst", "line": null, "side": "RIGHT", "created_at": "2021-07-15T00:30:45+00:00" }, { "id": 671444604, "user": "user_dbf2a999bd6d", "body": "We have logic for which simplejson/json exceptions we're using spread across a few places now. Is there a compelling reason not to simply import JSONDecodeError from compat since it's already been resolved and supplying it as a single parent class?", "path": "requests/exceptions.py", "line": null, "side": "RIGHT", "created_at": "2021-07-16T18:18:17+00:00" }, { "id": 673240914, "user": "user_a7b578c0e355", "body": "[USER_REDACTED] We want to know which properties the `JSONDecodeError` has, since it may have different properties depending on compatibility. That requires an extra check on import.", "path": "requests/exceptions.py", "line": null, "side": "RIGHT", "created_at": "2021-07-20T15:40:55+00:00" }, { "id": 673356731, "user": "user_dbf2a999bd6d", "body": "[USER_REDACTED] I'm not sure I'm following, could you clarify which properties you're referring to? We have 3 parent classes that we'd ever use in our environment, `json.JSONDecodeError`, `simplejson.JSONDecodeError`, and `ValueError`. Only one of those can be relevant in a given execution of Requests.\n\nWhat I was asking about was if we did:\n\n```python\nfrom .compat import JSONDecodeError as CompatJSONDecodeError\n\n[...]\n\nclass JSONDecodeError(InvalidJSONError, CompatJSONDecodeError):\n```\n\nWe've already resolved these values once in compat, so I wanted to know why we're doing it again here.", "path": "requests/exceptions.py", "line": null, "side": "RIGHT", "created_at": "2021-07-20T17:53:17+00:00" }, { "id": 673381345, "user": "user_a7b578c0e355", "body": "[USER_REDACTED] For Python 3, in the `compat.py` file itself, reference to the `json` package directly, whether aliased as `json` or actually the `json` package itself, would always look for the `json` package rather than whatever was aliased as it. So, just in the `compat.py` file itself, I used the check. From all other scripts that have `from .compat import json`, however, it works as expected.", "path": "requests/exceptions.py", "line": null, "side": "RIGHT", "created_at": "2021-07-20T18:30:36+00:00" }, { "id": 675244754, "user": "user_a7b578c0e355", "body": "Did you have any more questions about the code?", "path": "requests/exceptions.py", "line": null, "side": "RIGHT", "created_at": "2021-07-23T00:36:28+00:00" }, { "id": 675272659, "user": "user_dbf2a999bd6d", "body": "Hey [USER_REDACTED], I think there may still be some confusion. If you open the _Files changed_ tab, you should be able to see the full context of this thread. I've written out the [full diff](https://github.com/nateprewitt/requests/commit/665cf30861fb356d84103808e240d6940e8ff3d6) from the suggestion above to minimize ambiguity. You should find this passes the test suite without issue, so please let me know if there were other concerns you had.\n\nWhile we're here it would also be good to add a test exercising this change. Something to the effect of the example below should be sufficient:\n\n```\ndef test_json_decode_compatibility(self, httpbin):\n r = requests.get(httpbin('bytes/20'))\n with pytest.raises(requests.exceptions.JSONDecodeError):\n r.json()\n```\n\nThis won't cover simplejson in our general test suite, but I've done a one off run to ensure that's working.", "path": "requests/exceptions.py", "line": null, "side": "RIGHT", "created_at": "2021-07-23T02:30:46+00:00" }, { "id": 675577985, "user": "user_a7b578c0e355", "body": "Thank you, that makes total sense. I made those changes and I'm running workflows right now.", "path": "requests/exceptions.py", "line": null, "side": "RIGHT", "created_at": "2021-07-23T13:47:07+00:00" } ], "meta": { "languages": [ "md", "py", "rst" ], "touches_tests": true, "review_state_summary": { "COMMENTED": 32, "APPROVED": 4, "CHANGES_REQUESTED": 2 }, "meaningful_comment_count": 41, "has_approval": true, "has_changes_requested": true, "total_review_comments": 41 } } { "_id": "5cc48cdb15c7f0f0", "_schema_version": "1.0", "_cleaned_at": "2026-02-12T07:46:51.434626+00:00", "repo": "psf/requests", "repo_url": "https://github.com/psf/requests", "license_name": "Apache License 2.0", "license_spdx": "Apache-2.0", "pr_number": 5810, "title": "Throw value error when serializing JSON object with NaN value", "body": "I am attempting to fix #5767 with this PR. Feedback is really appreciated.", "author": "user_a39686a32f90", "created_at": "2021-05-04T10:37:03+00:00", "merged_at": "2021-05-06T18:18:58+00:00", "base_branch": "master", "head_branch": "nan-json-serialize", "additions": 17, "deletions": 3, "changed_files": 3, "files": [ { "filename": "requests/exceptions.py", "status": "modified", "additions": 4, "deletions": 0, "changes": 4, "patch": "@@ -25,6 +25,10 @@ def __init__(self, *args, **kwargs):\n super(RequestException, self).__init__(*args, **kwargs)\n \n \n+class InvalidJSONError(RequestException):\n+ \"\"\"A JSON error occurred.\"\"\"\n+\n+\n class HTTPError(RequestException):\n \"\"\"An HTTP error occurred.\"\"\"" }, { "filename": "requests/models.py", "status": "modified", "additions": 7, "deletions": 2, "changes": 9, "patch": "@@ -29,7 +29,7 @@\n from .cookies import cookiejar_from_dict, get_cookie_header, _copy_cookie_jar\n from .exceptions import (\n HTTPError, MissingSchema, InvalidURL, ChunkedEncodingError,\n- ContentDecodingError, ConnectionError, StreamConsumedError)\n+ ContentDecodingError, ConnectionError, StreamConsumedError, InvalidJSONError)\n from ._internal_utils import to_native_string, unicode_is_ascii\n from .utils import (\n guess_filename, get_auth_from_url, requote_uri,\n@@ -466,7 +466,12 @@ def prepare_body(self, data, files, json=None):\n # urllib3 requires a bytes-like body. Python 2's json.dumps\n # provides this natively, but Python 3 gives a Unicode string.\n content_type = 'application/json'\n- body = complexjson.dumps(json)\n+\n+ try:\n+ body = complexjson.dumps(json, allow_nan=False)\n+ except ValueError as ve:\n+ raise InvalidJSONError(ve, request=self)\n+\n if not isinstance(body, bytes):\n body = body.encode('utf-8')" }, { "filename": "tests/test_requests.py", "status": "modified", "additions": 6, "deletions": 1, "changes": 7, "patch": "@@ -24,7 +24,7 @@\n from requests.exceptions import (\n ConnectionError, ConnectTimeout, InvalidSchema, InvalidURL,\n MissingSchema, ReadTimeout, Timeout, RetryError, TooManyRedirects,\n- ProxyError, InvalidHeader, UnrewindableBodyError, SSLError, InvalidProxyURL)\n+ ProxyError, InvalidHeader, UnrewindableBodyError, SSLError, InvalidProxyURL, InvalidJSONError)\n from requests.models import PreparedRequest\n from requests.structures import CaseInsensitiveDict\n from requests.sessions import SessionRedirectMixin\n@@ -2566,3 +2566,8 @@ def test_parameters_for_nonstandard_schemes(self, input, params, expected):\n r = requests.Request('GET', url=input, params=params)\n p = r.prepare()\n assert p.url == expected\n+\n+ def test_post_json_nan(self, httpbin):\n+ data = {\"foo\": float(\"nan\")}\n+ with pytest.raises(requests.exceptions.InvalidJSONError):\n+ r = requests.post(httpbin('post'), json=data)\n\\ No newline at end of file" } ], "reviews": [ { "id": 651217570, "user": "user_0fa58b6f3572", "state": "CHANGES_REQUESTED", "body": "I don't believe a `request()` method will throw a ValueError ever and so this constitutes a backwards incompatible change. We should create a new exception, however, that inherits from `RequestsException` to cover this case and do something like\n\n```py\ntry:\n body = complexjson.dumps(json, allow_nan=False)\nexcept ValueError as ve:\n raise InvalidJSONError(json, original_exc=ve)\n```", "submitted_at": "2021-05-04T13:11:16+00:00" }, { "id": 651301885, "user": "user_a39686a32f90", "state": "COMMENTED", "body": null, "submitted_at": "2021-05-04T14:26:23+00:00" }, { "id": 653755925, "user": "user_0fa58b6f3572", "state": "COMMENTED", "body": null, "submitted_at": "2021-05-06T18:14:57+00:00" }, { "id": 653759134, "user": "user_0fa58b6f3572", "state": "APPROVED", "body": null, "submitted_at": "2021-05-06T18:18:52+00:00" } ], "review_comments": [ { "id": 625828753, "user": "user_a39686a32f90", "body": "[USER_REDACTED] is this okay? Couldn't do it the exact way you specified, but `request` contains the JSON info.", "path": "requests/models.py", "line": 473, "side": "RIGHT", "created_at": "2021-05-04T14:26:23+00:00" }, { "id": 627659767, "user": "user_0fa58b6f3572", "body": "I have an instinct of \"No\" but that's because people do not read the docs and sometimes pass open files and such _in addition to_ the `json=` keyword and keeping a reference to those might not be _the best_ but that's a \"The user has shot themselves in the foot\" situation only for high traffic (lots of requests doing the wrong thing explicitly that has undefined behaviour), poorly designed software (because it's potentially not releasing/decref'ing the exception which doesn't decref the request which doesn't decref the file obj).\n\ntl;dr - This should be fine", "path": "requests/models.py", "line": 473, "side": "RIGHT", "created_at": "2021-05-06T18:14:57+00:00" } ], "meta": { "languages": [ "py" ], "touches_tests": true, "review_state_summary": { "CHANGES_REQUESTED": 1, "COMMENTED": 2, "APPROVED": 1 }, "meaningful_comment_count": 2, "has_approval": true, "has_changes_requested": true, "total_review_comments": 2 } } { "_id": "6ab222745b98ca21", "_schema_version": "1.0", "_cleaned_at": "2026-02-12T07:46:51.447075+00:00", "repo": "psf/requests", "repo_url": "https://github.com/psf/requests", "license_name": "Apache License 2.0", "license_spdx": "Apache-2.0", "pr_number": 5797, "title": "Switch LGPL'd chardet for MIT licensed charset_normalizer", "body": "At least for Python 3 -- charset_normalizer doesn't support Python2, so for that chardet is still used -- this means the \"have chardet\" path is also still tested.\n\nAlthough using the (non-vendored) chardet library is fine for requests itself, but using a LGPL dependency the story is a lot less clear for downstream projects, particularly ones that might like to bundle requests (and thus chardet) in to a single binary -- think something similar to what docker-compose is doing. By [NAME_REDACTED] it is no longer clear if the resulting artefact must also be LGPL'd.\n\nBy [NAME_REDACTED] for one under MIT we remove all license ambiguity.\n\nAs an \"escape hatch\" I have made the code so that it will use chardet first if it is installed, but we no longer depend upon it directly, although there is a new extra added, `requests[lgpl]`. This should minimize the impact to users, and give them an escape hatch if charset_normalizer turns out to be not as good. (In my non-exhaustive tests it detects the same encoding as chartdet in every case I threw at it)\n\nI've read https://github.com/psf/requests/pull/4115, https://github.com/psf/requests/issues/3389, and https://github.com/chardet/chardet/issues/36#issuecomment-768281452 so I'm aware of the history, but I hope that the approach in this PR will allow this to be merged, as right now, the [NAME_REDACTED] doesn't allow projects to depend upon LGPL'd code (this is something I'm trying to get changed, but it is a _very_ slow process)", "author": "user_ec9356a049f3", "created_at": "2021-04-22T08:25:50+00:00", "merged_at": "2021-07-06T23:55:02+00:00", "base_branch": "master", "head_branch": "charset_normalizer", "additions": 119, "deletions": 27, "changed_files": 10, "files": [ { "filename": ".gitignore", "status": "modified", "additions": 6, "deletions": 0, "changes": 6, "patch": "@@ -23,6 +23,12 @@ env/\n \n .workon\n \n+# in case you work with IntelliJ/PyCharm\n+.idea\n+*.iml\n+.python-version\n+\n+\n t.py\n \n t2.py" }, { "filename": "HISTORY.md", "status": "modified", "additions": 16, "deletions": 1, "changes": 17, "patch": "@@ -6,6 +6,22 @@ dev\n \n - \\[Short description of non-trivial change.\\]\n \n+**Dependencies**\n+\n+- Instead of `chardet`, use the MIT-licensed `charset_normalizer` for Python3\n+ to remove license ambiguity for projects bundling requests. If `chardet`\n+ is already installed on your machine it will be used instead of `charset_normalizer`\n+ to keep backwards compatibility.\n+\n+ You can also install `chardet` while installing requests by\n+ specifying `[use_chardet_on_py3]` extra as follows:\n+\n+ ```shell\n+ pip install \"requests[use_chardet_on_py3]\"\n+ ```\n+\n+ Python2 still depends upon the `chardet` module.\n+\n 2.25.1 (2020-12-16)\n -------------------\n \n@@ -1707,4 +1723,3 @@ This is not a backwards compatible change.\n \n - Frustration\n - Conception\n-" }, { "filename": "docs/user/advanced.rst", "status": "modified", "additions": 16, "deletions": 4, "changes": 20, "patch": "@@ -697,10 +697,22 @@ [NAME_REDACTED] you receive a response, Requests makes a guess at the encoding to\n use for decoding the response when you access the :attr:`Response.text\n ` attribute. Requests will first check for an\n-encoding in the HTTP header, and if none is present, will use `chardet\n-`_ to attempt to guess the encoding.\n-\n-The only time Requests will not do this is if no explicit charset\n+encoding in the HTTP header, and if none is present, will use\n+`charset_normalizer `_\n+or `chardet `_ to attempt to\n+guess the encoding.\n+\n+If ``chardet`` is installed, ``requests`` uses it, however for python3\n+``chardet`` is no longer a mandatory dependency. The ``chardet``\n+library is an LGPL-licenced dependency and some users of requests\n+cannot depend on mandatory LGPL-licensed dependencies.\n+\n+When you install ``request`` without specifying ``[use_chardet_on_py3]]`` extra,\n+and ``chardet`` is not already installed, ``requests`` uses ``charset-normalizer``\n+(MIT-licensed) to guess the encoding. For Python 2, ``requests`` uses only\n+``chardet`` and is a mandatory dependency there.\n+\n+The only time Requests will not guess the encoding is if no explicit charset\n is present in the HTTP headers **and** the ``Content-Type``\n header contains ``text``. In this situation, `RFC 2616\n `_ specifies" }, { "filename": "requests/__init__.py", "status": "modified", "additions": 26, "deletions": 11, "changes": 37, "patch": "@@ -41,12 +41,20 @@\n \"\"\"\n \n import urllib3\n-import chardet\n import warnings\n from .exceptions import RequestsDependencyWarning\n \n+try:\n+ from charset_normalizer import __version__ as charset_normalizer_version\n+except ImportError:\n+ charset_normalizer_version = None\n \n-def check_compatibility(urllib3_version, chardet_version):\n+try:\n+ from chardet import __version__ as chardet_version\n+except ImportError:\n+ chardet_version = None\n+\n+def check_compatibility(urllib3_version, chardet_version, charset_normalizer_version):\n urllib3_version = urllib3_version.split('.')\n assert urllib3_version != ['dev'] # Verify urllib3 isn't installed from git.\n \n@@ -62,12 +70,19 @@ def check_compatibility(urllib3_version, chardet_version):\n assert minor >= 21\n assert minor <= 26\n \n- # Check chardet for compatibility.\n- major, minor, patch = chardet_version.split('.')[:3]\n- major, minor, patch = int(major), int(minor), int(patch)\n- # chardet >= 3.0.2, < 5.0.0\n- assert (3, 0, 2) <= (major, minor, patch) < (5, 0, 0)\n-\n+ # Check charset_normalizer for compatibility.\n+ if chardet_version:\n+ major, minor, patch = chardet_version.split('.')[:3]\n+ major, minor, patch = int(major), int(minor), int(patch)\n+ # chardet_version >= 3.0.2, < 5.0.0\n+ assert (3, 0, 2) <= (major, minor, patch) < (5, 0, 0)\n+ elif charset_normalizer_version:\n+ major, minor, patch = charset_normalizer_version.split('.')[:3]\n+ major, minor, patch = int(major), int(minor), int(patch)\n+ # charset_normalizer >= 2.0.0 < 3.0.0\n+ assert (2, 0, 0) <= (major, minor, patch) < (3, 0, 0)\n+ else:\n+ raise Exception(\"You need either charset_normalizer or chardet installed\")\n \n def _check_cryptography(cryptography_version):\n # cryptography < 1.3.4\n@@ -82,10 +97,10 @@ def _check_cryptography(cryptography_version):\n \n # Check imported dependencies for compatibility.\n try:\n- check_compatibility(urllib3.__version__, chardet.__version__)\n+ check_compatibility(urllib3.__version__, chardet_version, charset_normalizer_version)\n except (AssertionError, ValueError):\n- warnings.warn(\"urllib3 ({}) or chardet ({}) doesn't match a supported \"\n- \"version!\".format(urllib3.__version__, chardet.__version__),\n+ warnings.warn(\"urllib3 ({}) or chardet ({})/charset_normalizer ({}) doesn't match a supported \"\n+ \"version!\".format(urllib3.__version__, chardet_version, charset_normalizer_version),\n RequestsDependencyWarning)\n \n # Attempt to enable urllib3's fallback for SNI support" }, { "filename": "requests/compat.py", "status": "modified", "additions": 4, "deletions": 1, "changes": 5, "patch": "@@ -8,7 +8,10 @@\n Python 3.\n \"\"\"\n \n-import chardet\n+try:\n+ import chardet\n+except ImportError:\n+ import charset_normalizer as chardet\n \n import sys" }, { "filename": "requests/help.py", "status": "modified", "additions": 18, "deletions": 2, "changes": 20, "patch": "@@ -8,10 +8,19 @@\n \n import idna\n import urllib3\n-import chardet\n \n from . import __version__ as requests_version\n \n+try:\n+ import charset_normalizer\n+except ImportError:\n+ charset_normalizer = None\n+\n+try:\n+ import chardet\n+except ImportError:\n+ chardet = None\n+\n try:\n from urllib3.contrib import pyopenssl\n except ImportError:\n@@ -71,7 +80,12 @@ def info():\n \n implementation_info = _implementation()\n urllib3_info = {'version': urllib3.__version__}\n- chardet_info = {'version': chardet.__version__}\n+ charset_normalizer_info = {'version': None}\n+ chardet_info = {'version': None}\n+ if charset_normalizer:\n+ charset_normalizer_info = {'version': charset_normalizer.__version__}\n+ if chardet:\n+ chardet_info = {'version': chardet.__version__}\n \n pyopenssl_info = {\n 'version': None,\n@@ -99,9 +113,11 @@ def info():\n 'implementation': implementation_info,\n 'system_ssl': system_ssl_info,\n 'using_pyopenssl': pyopenssl is not None,\n+ 'using_charset_normalizer': chardet is None,\n 'pyOpenSSL': pyopenssl_info,\n 'urllib3': urllib3_info,\n 'chardet': chardet_info,\n+ 'charset_normalizer': charset_normalizer_info,\n 'cryptography': cryptography_info,\n 'idna': idna_info,\n 'requests': {" }, { "filename": "requests/models.py", "status": "modified", "additions": 3, "deletions": 3, "changes": 6, "patch": "@@ -731,7 +731,7 @@ def next(self):\n \n [USER_REDACTED]\n def apparent_encoding(self):\n- \"\"\"The apparent encoding, provided by [NAME_REDACTED]\"\"\"\n+ \"\"\"The apparent encoding, provided by [NAME_REDACTED]_normalizer or chardet libraries.\"\"\"\n return chardet.detect(self.content)['encoding']\n \n def iter_content(self, chunk_size=1, decode_unicode=False):\n@@ -845,7 +845,7 @@ def text(self):\n \"\"\"Content of the response, in unicode.\n \n If Response.encoding is None, encoding will be guessed using\n- ``chardet``.\n+ ``charset_normalizer`` or ``chardet``.\n \n The encoding of the response content is determined based solely on HTTP\n headers, following RFC 2616 to the letter. If you can take advantage of\n@@ -893,7 +893,7 @@ def json(self, **kwargs):\n if not self.encoding and self.content and len(self.content) > 3:\n # No encoding set. JSON RFC 4627 section 3 states we should expect\n # UTF-8, -16 or -32. Detect which one to use; If the detection or\n- # decoding fails, fall back to `self.text` (using chardet to make\n+ # decoding fails, fall back to `self.text` (using charset_normalizer to make\n # a best guess).\n encoding = guess_json_utf(self.content)\n if encoding is not None:" }, { "filename": "requests/packages.py", "status": "modified", "additions": 13, "deletions": 1, "changes": 14, "patch": "@@ -1,14 +1,26 @@\n import sys\n \n+try:\n+ import chardet\n+except ImportError:\n+ import charset_normalizer as chardet\n+ import warnings\n+\n+ warnings.filterwarnings('ignore', 'Trying to detect', module='charset_normalizer')\n+\n # This code exists for backwards compatibility reasons.\n # I don't like it either. Just look the other way. :)\n \n-for package in ('urllib3', 'idna', 'chardet'):\n+for package in ('urllib3', 'idna'):\n locals()[package] = __import__(package)\n # This traversal is apparently necessary such that the identities are\n # preserved (requests.packages.urllib3.* is urllib3.*)\n for mod in list(sys.modules):\n if mod == package or mod.startswith(package + '.'):\n sys.modules['requests.packages.' + mod] = sys.modules[mod]\n \n+target = chardet.__name__\n+for mod in list(sys.modules):\n+ if mod == target or mod.startswith(target + '.'):\n+ sys.modules['requests.packages.' + target.replace(target, 'chardet')] = sys.modules[mod]\n # Kinda cool, though, right?" }, { "filename": "setup.py", "status": "modified", "additions": 3, "deletions": 1, "changes": 4, "patch": "@@ -41,7 +41,8 @@ def run_tests(self):\n packages = ['requests']\n \n requires = [\n- 'chardet>=3.0.2,<5',\n+ 'charset_normalizer~=2.0.0; python_version >= \"3\"',\n+ 'chardet>=3.0.2,<5; python_version < \"3\"',\n 'idna>=2.5,<3',\n 'urllib3>=1.21.1,<1.27',\n 'certifi>=2017.4.17'\n@@ -103,6 +104,7 @@ def run_tests(self):\n 'security': ['pyOpenSSL >= 0.14', 'cryptography>=1.3.4'],\n 'socks': ['PySocks>=1.5.6, !=1.5.7'],\n 'socks:sys_platform == \"win32\" and python_version == \"2.7\"': ['win_inet_pton'],\n+ 'use_chardet_on_py3': ['chardet>=3.0.2,<5']\n },\n project_urls={\n 'Documentation': 'https://requests.readthedocs.io'," }, { "filename": "tox.ini", "status": "modified", "additions": 14, "deletions": 3, "changes": 17, "patch": "@@ -1,7 +1,18 @@\n [tox]\n-envlist = py27,py35,py36,py37,py38\n+envlist = py{27,35,36,37,38}-{default,use_chardet_on_py3}\n \n [testenv]\n-\n+deps = -rrequirements-dev.txt\n+extras =\n+ security\n+ socks\n commands =\n- python setup.py test\n+ pytest tests\n+\n+[testenv:default]\n+\n+[testenv:use_chardet_on_py3]\n+extras =\n+ security\n+ socks\n+ use_chardet_on_py3" } ], "reviews": [ { "id": 665901224, "user": "user_93734560a289", "state": "COMMENTED", "body": null, "submitted_at": "2021-05-21T21:16:35+00:00" }, { "id": 665903771, "user": "user_93734560a289", "state": "COMMENTED", "body": null, "submitted_at": "2021-05-21T21:17:59+00:00" }, { "id": 670838338, "user": "user_0fa58b6f3572", "state": "COMMENTED", "body": null, "submitted_at": "2021-05-28T00:15:43+00:00" }, { "id": 670904890, "user": "user_61c1656236f3", "state": "CHANGES_REQUESTED", "body": null, "submitted_at": "2021-05-28T03:54:21+00:00" }, { "id": 670961724, "user": "user_93734560a289", "state": "COMMENTED", "body": null, "submitted_at": "2021-05-28T06:16:50+00:00" }, { "id": 670964516, "user": "user_93734560a289", "state": "COMMENTED", "body": null, "submitted_at": "2021-05-28T06:21:54+00:00" }, { "id": 670964844, "user": "user_93734560a289", "state": "COMMENTED", "body": null, "submitted_at": "2021-05-28T06:22:26+00:00" }, { "id": 670965143, "user": "user_61c1656236f3", "state": "COMMENTED", "body": null, "submitted_at": "2021-05-28T06:22:55+00:00" }, { "id": 670965624, "user": "user_61c1656236f3", "state": "COMMENTED", "body": null, "submitted_at": "2021-05-28T06:23:44+00:00" }, { "id": 670972836, "user": "user_93734560a289", "state": "COMMENTED", "body": null, "submitted_at": "2021-05-28T06:36:15+00:00" }, { "id": 671047494, "user": "user_61c1656236f3", "state": "COMMENTED", "body": null, "submitted_at": "2021-05-28T08:16:23+00:00" }, { "id": 671055273, "user": "user_93734560a289", "state": "COMMENTED", "body": null, "submitted_at": "2021-05-28T08:25:32+00:00" }, { "id": 671112180, "user": "user_61c1656236f3", "state": "APPROVED", "body": null, "submitted_at": "2021-05-28T09:30:08+00:00" }, { "id": 671150670, "user": "user_0b8532a5e533", "state": "COMMENTED", "body": null, "submitted_at": "2021-05-28T10:16:18+00:00" }, { "id": 671160068, "user": "user_0b8532a5e533", "state": "APPROVED", "body": null, "submitted_at": "2021-05-28T10:28:52+00:00" }, { "id": 671256550, "user": "user_116b15be3ae2", "state": "COMMENTED", "body": null, "submitted_at": "2021-05-28T12:43:25+00:00" }, { "id": 671370415, "user": "user_116b15be3ae2", "state": "COMMENTED", "body": null, "submitted_at": "2021-05-28T14:36:49+00:00" }, { "id": 671777379, "user": "user_116b15be3ae2", "state": "APPROVED", "body": null, "submitted_at": "2021-05-29T22:32:43+00:00" }, { "id": 671777511, "user": "user_61c1656236f3", "state": "COMMENTED", "body": null, "submitted_at": "2021-05-29T22:35:37+00:00" }, { "id": 671793108, "user": "user_93734560a289", "state": "COMMENTED", "body": null, "submitted_at": "2021-05-30T05:44:23+00:00" }, { "id": 671793122, "user": "user_93734560a289", "state": "COMMENTED", "body": null, "submitted_at": "2021-05-30T05:44:41+00:00" }, { "id": 699286030, "user": "user_0fa58b6f3572", "state": "APPROVED", "body": null, "submitted_at": "2021-07-05T15:32:08+00:00" }, { "id": 699287362, "user": "user_b08fb5f52ea1", "state": "COMMENTED", "body": "This PR looks good, thank you for all the work and patience. I have one concern with the recent release of v2.0.0:", "submitted_at": "2021-07-05T15:35:57+00:00" }, { "id": 699289157, "user": "user_0fa58b6f3572", "state": "COMMENTED", "body": null, "submitted_at": "2021-07-05T15:36:53+00:00" }, { "id": 699290240, "user": "user_b08fb5f52ea1", "state": "COMMENTED", "body": null, "submitted_at": "2021-07-05T15:38:30+00:00" }, { "id": 699290535, "user": "user_b08fb5f52ea1", "state": "APPROVED", "body": null, "submitted_at": "2021-07-05T15:38:57+00:00" }, { "id": 700437644, "user": "user_dbf2a999bd6d", "state": "APPROVED", "body": "Looks like we're set on the testing infra fixes. I'll leave final merge to [USER_REDACTED], but I think this looks alright.", "submitted_at": "2021-07-06T22:44:46+00:00" } ], "review_comments": [ { "id": 637236978, "user": "user_93734560a289", "body": "```suggestion\n 'charset_normalizer~=1.4.0,<2; python_version >= \"3\"',\n```", "path": "setup.py", "line": null, "side": "RIGHT", "created_at": "2021-05-21T21:16:35+00:00" }, { "id": 637237986, "user": "user_93734560a289", "body": "```suggestion\n 'charset_normalizer~=1.4.0; python_version >= \"3\"',\n```", "path": "setup.py", "line": null, "side": "RIGHT", "created_at": "2021-05-21T21:17:59+00:00" }, { "id": 641068555, "user": "user_0fa58b6f3572", "body": "This seems somewhat disingenuous. For one thing, it's not the _only_ way to get `lgpl` dependencies. For another, it really exists to just force `chardet` to be installed on py3 so should be named something more like `use_chardet_on_py3`", "path": "setup.py", "line": null, "side": "RIGHT", "created_at": "2021-05-28T00:15:43+00:00" }, { "id": 641229125, "user": "user_61c1656236f3", "body": "Maybe precise that if chardet is installed, it will still be used as it could confuse users.", "path": "HISTORY.md", "line": 24, "side": "RIGHT", "created_at": "2021-05-28T03:41:55+00:00" }, { "id": 641230534, "user": "user_61c1656236f3", "body": "Maybe change the min to `(1, 4, 0)`.", "path": "requests/__init__.py", "line": null, "side": "RIGHT", "created_at": "2021-05-28T03:43:16+00:00" }, { "id": 641240625, "user": "user_61c1656236f3", "body": "I would add a bit of explanation there. \n\n- What happens if chardet is installed\n- Keep both lib name as python 2 is keeping chardet by default", "path": "docs/user/advanced.rst", "line": null, "side": "RIGHT", "created_at": "2021-05-28T03:53:23+00:00" }, { "id": 641295078, "user": "user_93734560a289", "body": "Done", "path": "setup.py", "line": null, "side": "RIGHT", "created_at": "2021-05-28T06:16:50+00:00" }, { "id": 641297212, "user": "user_93734560a289", "body": "Added.", "path": "HISTORY.md", "line": 24, "side": "RIGHT", "created_at": "2021-05-28T06:21:54+00:00" }, { "id": 641297465, "user": "user_93734560a289", "body": "Changed to 1.4.1 to account for logging fix just added by [USER_REDACTED]", "path": "requests/__init__.py", "line": null, "side": "RIGHT", "created_at": "2021-05-28T06:22:26+00:00" }, { "id": 641297716, "user": "user_61c1656236f3", "body": "Thanks!", "path": "HISTORY.md", "line": 24, "side": "RIGHT", "created_at": "2021-05-28T06:22:54+00:00" }, { "id": 641298081, "user": "user_61c1656236f3", "body": ":+1:", "path": "requests/__init__.py", "line": null, "side": "RIGHT", "created_at": "2021-05-28T06:23:44+00:00" }, { "id": 641303661, "user": "user_93734560a289", "body": "Updated.", "path": "docs/user/advanced.rst", "line": null, "side": "RIGHT", "created_at": "2021-05-28T06:36:15+00:00" }, { "id": 641360133, "user": "user_61c1656236f3", "body": "[USER_REDACTED] Missed the replacement there `use_chardet_on_py3`", "path": "tox.ini", "line": null, "side": "RIGHT", "created_at": "2021-05-28T08:16:23+00:00" }, { "id": 641366129, "user": "user_93734560a289", "body": "Fixed. Thanks!", "path": "tox.ini", "line": null, "side": "RIGHT", "created_at": "2021-05-28T08:25:32+00:00" }, { "id": 641438297, "user": "user_0b8532a5e533", "body": "```suggestion\n # charset_normalizer >= 1.4.1, < 2.0.0\n```", "path": "requests/__init__.py", "line": null, "side": "RIGHT", "created_at": "2021-05-28T10:16:17+00:00" }, { "id": 641516746, "user": "user_116b15be3ae2", "body": "```suggestion\n- Instead of `chardet`, use the MIT-licensed `charset_normalizer` for Python3\n to remove license ambiguity for projects bundling requests. If `chardet`\n is already installed on your machine it will be used instead of `charset_normalizer`\n to keep backwards compatibility.\n\n You can also install `chardet` while installing requests by\n specifying `[use_chardet_on_py3]` extra as follows:\n\n ```shell\n pip install \"requests[use_chardet_on_py3]\"\n ```\n```", "path": "HISTORY.md", "line": null, "side": "RIGHT", "created_at": "2021-05-28T12:40:09+00:00" }, { "id": 641517560, "user": "user_116b15be3ae2", "body": "```suggestion\nand ``chardet`` is not already installed, ``requests`` uses ``charset-normalizer``\n```", "path": "docs/user/advanced.rst", "line": null, "side": "RIGHT", "created_at": "2021-05-28T12:41:22+00:00" }, { "id": 641600649, "user": "user_116b15be3ae2", "body": "Something went wrong with that suggestion .. the ending triple quotes disappeared somehow, try this\n\n```suggestion\n ```shell\n pip install \"requests[use_chardet_on_py3]\"\n ```\n```", "path": "HISTORY.md", "line": null, "side": "RIGHT", "created_at": "2021-05-28T14:36:49+00:00" }, { "id": 641991272, "user": "user_61c1656236f3", "body": "[USER_REDACTED] missed a « lgpl » here. It is the last one.", "path": "tox.ini", "line": null, "side": "RIGHT", "created_at": "2021-05-29T22:35:36+00:00" }, { "id": 642023066, "user": "user_93734560a289", "body": "Too much reliance on Ci (which is not running because of workflow awaiting approval :)", "path": "tox.ini", "line": null, "side": "RIGHT", "created_at": "2021-05-30T05:44:22+00:00" }, { "id": 642023099, "user": "user_93734560a289", "body": "This time I actually run it before last fixup locally.", "path": "tox.ini", "line": null, "side": "RIGHT", "created_at": "2021-05-30T05:44:41+00:00" }, { "id": 664014262, "user": "user_b08fb5f52ea1", "body": "If charset_normalizer v2.0.0 is out do we need to update this to be >2?", "path": "requests/__init__.py", "line": null, "side": "RIGHT", "created_at": "2021-07-05T15:34:07+00:00" }, { "id": 664014844, "user": "user_b08fb5f52ea1", "body": "Do we need to update this with v2.0.0?", "path": "setup.py", "line": null, "side": "RIGHT", "created_at": "2021-07-05T15:35:12+00:00" }, { "id": 664015764, "user": "user_0fa58b6f3572", "body": "We haven't tested v2. I'd rather get something imperfect out than something perfect. Today's literally the only time I've had to review anything", "path": "setup.py", "line": null, "side": "RIGHT", "created_at": "2021-07-05T15:36:53+00:00" }, { "id": 664016609, "user": "user_b08fb5f52ea1", "body": "Makes sense, I/we can handle the upgrade in a follow-up PR.", "path": "setup.py", "line": null, "side": "RIGHT", "created_at": "2021-07-05T15:38:30+00:00" } ], "meta": { "languages": [ "ini", "md", "py", "rst" ], "touches_tests": false, "review_state_summary": { "COMMENTED": 20, "CHANGES_REQUESTED": 1, "APPROVED": 6 }, "meaningful_comment_count": 20, "has_approval": true, "has_changes_requested": true, "total_review_comments": 25 } } { "_id": "a061ddc01b452dd2", "_schema_version": "1.0", "_cleaned_at": "2026-02-12T07:46:51.449105+00:00", "repo": "psf/requests", "repo_url": "https://github.com/psf/requests", "license_name": "Apache License 2.0", "license_spdx": "Apache-2.0", "pr_number": 5783, "title": "Add support for brotli decoding", "body": "When the `brotli` or `brotlicffi` packages are installed, `urllib3.util.make_headers()` inserts ',br' in the Accept-Encoding header and decodes br from the answers.", "author": "user_9307f64f5cd5", "created_at": "2021-03-29T18:53:59+00:00", "merged_at": "2021-07-07T13:16:28+00:00", "base_branch": "master", "head_branch": "brotli_decoding", "additions": 15, "deletions": 1, "changed_files": 4, "files": [ { "filename": "HISTORY.md", "status": "modified", "additions": 2, "deletions": 0, "changes": 2, "patch": "@@ -5,6 +5,8 @@ dev\n ---\n \n - \\[Short description of non-trivial change.\\]\n+- [NAME_REDACTED] compression, if either the `brotli` or `brotlicffi` package\n+ is installed.\n \n 2.25.1 (2020-12-16)\n -------------------" }, { "filename": "docs/community/faq.rst", "status": "modified", "additions": 3, "deletions": 0, "changes": 3, "patch": "@@ -11,6 +11,9 @@ [NAME_REDACTED]?\n Requests automatically decompresses gzip-encoded responses, and does\n its best to decode response content to unicode when possible.\n \n+When either the `brotli `_ or `brotlicffi `_\n+package is installed, requests also decodes Brotli-encoded responses.\n+\n You can get direct access to the raw response (and even the socket),\n if needed as well." }, { "filename": "docs/user/quickstart.rst", "status": "modified", "additions": 3, "deletions": 0, "changes": 3, "patch": "@@ -128,6 +128,9 @@ You can also access the response body as bytes, for non-text requests::\n \n The ``gzip`` and ``deflate`` transfer-encodings are automatically decoded for you.\n \n+The ``br`` transfer-encoding is automatically decoded for you if a Brotli library\n+like `brotli `_ or `brotlicffi `_ is installed.\n+\n For example, to create an image from binary data returned by a request, you can\n use the following code::" }, { "filename": "requests/utils.py", "status": "modified", "additions": 7, "deletions": 1, "changes": 8, "patch": "@@ -20,6 +20,7 @@\n import warnings\n import zipfile\n from collections import OrderedDict\n+from urllib3.util import make_headers\n \n from .__version__ import __version__\n from . import certs\n@@ -41,6 +42,11 @@\n \n DEFAULT_PORTS = {'http': 80, 'https': 443}\n \n+# Ensure that ', ' is used to preserve previous delimiter behavior.\n+DEFAULT_ACCEPT_ENCODING = \", \".join(\n+ re.split(r\",\\s*\", make_headers(accept_encoding=True)[\"accept-encoding\"])\n+)\n+\n \n if sys.platform == 'win32':\n # provide a proxy_bypass version on Windows without DNS lookups\n@@ -820,7 +826,7 @@ def default_headers():\n \"\"\"\n return CaseInsensitiveDict({\n 'User-Agent': default_user_agent(),\n- 'Accept-Encoding': ', '.join(('gzip', 'deflate')),\n+ 'Accept-Encoding': DEFAULT_ACCEPT_ENCODING,\n 'Accept': '*/*',\n 'Connection': 'keep-alive',\n })" } ], "reviews": [ { "id": 648821963, "user": "user_b08fb5f52ea1", "state": "CHANGES_REQUESTED", "body": "This looks mostly good, few comments for you. Also can we add a test for this?", "submitted_at": "2021-05-20T20:57:47+00:00" }, { "id": 665228283, "user": "user_9307f64f5cd5", "state": "COMMENTED", "body": null, "submitted_at": "2021-05-21T08:41:32+00:00" }, { "id": 665232055, "user": "user_9307f64f5cd5", "state": "COMMENTED", "body": null, "submitted_at": "2021-05-21T08:45:36+00:00" }, { "id": 700981392, "user": "user_b08fb5f52ea1", "state": "APPROVED", "body": "I'm now happy with my changes but I'd like another reviewer to take a quick peek now that I'm the author [NAME_REDACTED] diff. cc [USER_REDACTED] [USER_REDACTED]", "submitted_at": "2021-07-07T13:06:57+00:00" }, { "id": 700992139, "user": "user_0fa58b6f3572", "state": "APPROVED", "body": null, "submitted_at": "2021-07-07T13:16:22+00:00" } ], "review_comments": [ { "id": 623550350, "user": "user_b08fb5f52ea1", "body": "Can we link to the individual packages here?", "path": "docs/community/faq.rst", "line": null, "side": "RIGHT", "created_at": "2021-04-30T02:51:17+00:00" }, { "id": 623550420, "user": "user_b08fb5f52ea1", "body": "nit: Brotli is a proper name so should be capitalized here and in the changelog", "path": "docs/community/faq.rst", "line": null, "side": "RIGHT", "created_at": "2021-04-30T02:51:33+00:00" }, { "id": 636462152, "user": "user_b08fb5f52ea1", "body": "Should we generate this header once and store the result so it doesn't need to be called every time? The value is determined by [NAME_REDACTED] changing often.", "path": "requests/utils.py", "line": null, "side": "RIGHT", "created_at": "2021-05-20T20:52:06+00:00" }, { "id": 636744118, "user": "user_9307f64f5cd5", "body": "I have capitalized Brotli-decompression on both places.", "path": "docs/community/faq.rst", "line": null, "side": "RIGHT", "created_at": "2021-05-21T08:41:31+00:00" }, { "id": 636746931, "user": "user_9307f64f5cd5", "body": "This optimization makes sense. I kindly ask you to implement it in the way, you think fits best.", "path": "requests/utils.py", "line": null, "side": "RIGHT", "created_at": "2021-05-21T08:45:36+00:00" } ], "meta": { "languages": [ "md", "py", "rst" ], "touches_tests": false, "review_state_summary": { "CHANGES_REQUESTED": 1, "COMMENTED": 2, "APPROVED": 2 }, "meaningful_comment_count": 5, "has_approval": true, "has_changes_requested": true, "total_review_comments": 5 } } { "_id": "6c4526377405ea6c", "_schema_version": "1.0", "_cleaned_at": "2026-02-12T07:46:51.452326+00:00", "repo": "psf/requests", "repo_url": "https://github.com/psf/requests", "license_name": "Apache License 2.0", "license_spdx": "Apache-2.0", "pr_number": 5777, "title": "quickstart.rst: r.json() can raise JSONDecodeError on Py3", "body": "% `python2 -c \"import requests ; requests.get('https://github.com').json()\"`\n% `python3 -c \"import requests ; requests.get('https://github.com').json()\"`\n\nPython | Simplejson is installed | Simplejson is NOT installed\n--- | --- | ---\nPython 2 | simplejson.JSONDecodeError | ValueError\nPython 3 | simplejson.JSONDecodeError | json.JSONDecodeError", "author": "user_bf0bce4a5e56", "created_at": "2021-03-18T09:06:28+00:00", "merged_at": "2021-03-18T14:36:35+00:00", "base_branch": "master", "head_branch": "patch-1", "additions": 9, "deletions": 2, "changed_files": 2, "files": [ { "filename": "docs/user/quickstart.rst", "status": "modified", "additions": 3, "deletions": 1, "changes": 4, "patch": "@@ -150,7 +150,9 @@ There's also a builtin JSON decoder, in case you're dealing with JSON data::\n \n In case the JSON decoding fails, ``r.json()`` raises an exception. For example, if\n the response gets a 204 ([NAME_REDACTED]), or if the response contains invalid JSON,\n-attempting ``r.json()`` raises ``ValueError: No JSON object could be decoded``.\n+attempting ``r.json()`` raises ``simplejson.JSONDecodeError`` if simplejson is\n+installed or raises ``ValueError: No JSON object could be decoded`` on Python 2 or\n+``json.JSONDecodeError`` on Python 3.\n \n It should be noted that the success of the call to ``r.json()`` does **not**\n indicate the success of the response. Some servers may return a JSON object in a" }, { "filename": "requests/models.py", "status": "modified", "additions": 6, "deletions": 1, "changes": 7, "patch": "@@ -877,7 +877,12 @@ def json(self, **kwargs):\n r\"\"\"Returns the json-encoded content of a response, if any.\n \n :param \\*\\*kwargs: Optional arguments that ``json.loads`` takes.\n- :raises ValueError: If the response body does not contain valid json.\n+ :raises simplejson.JSONDecodeError: If the response body does not\n+ contain valid json and simplejson is installed.\n+ :raises json.JSONDecodeError: If the response body does not contain\n+ valid json and simplejson is not installed on Python 3.\n+ :raises ValueError: If the response body does not contain valid\n+ json and simplejson is not installed on Python 2. \n \"\"\"\n \n if not self.encoding and self.content and len(self.content) > 3:" } ], "reviews": [ { "id": 615246092, "user": "user_0fa58b6f3572", "state": "COMMENTED", "body": null, "submitted_at": "2021-03-18T11:14:33+00:00" }, { "id": 615256568, "user": "user_bf0bce4a5e56", "state": "COMMENTED", "body": null, "submitted_at": "2021-03-18T11:19:48+00:00" }, { "id": 615466954, "user": "user_0fa58b6f3572", "state": "APPROVED", "body": null, "submitted_at": "2021-03-18T14:36:31+00:00" } ], "review_comments": [ { "id": 596760730, "user": "user_0fa58b6f3572", "body": "Does `simplejson` raise a `ValueError` on Py2?", "path": "docs/user/quickstart.rst", "line": null, "side": "RIGHT", "created_at": "2021-03-18T11:14:33+00:00" }, { "id": 596763999, "user": "user_bf0bce4a5e56", "body": "Yes. Good catch. Thanks.", "path": "docs/user/quickstart.rst", "line": null, "side": "RIGHT", "created_at": "2021-03-18T11:19:48+00:00" } ], "meta": { "languages": [ "py", "rst" ], "touches_tests": false, "review_state_summary": { "COMMENTED": 2, "APPROVED": 1 }, "meaningful_comment_count": 2, "has_approval": true, "has_changes_requested": false, "total_review_comments": 2 } } { "_id": "044c49b6189df9ad", "_schema_version": "1.0", "_cleaned_at": "2026-02-12T07:46:51.452326+00:00", "repo": "psf/requests", "repo_url": "https://github.com/psf/requests", "license_name": "Apache License 2.0", "license_spdx": "Apache-2.0", "pr_number": 5707, "title": "Avoid zip extract racing condition by [NAME_REDACTED]+write instead extract", "body": "Extract also creates the folder hierarchy, however we do not need that,\nthe file itself being extracted to a temporary folder is good enough.\nInstead we read the content of the zip and then write it. The write is\nnot locked but it's OK to update the same file multiple times given the\nupdate operation will not alter the content of the file. By [NAME_REDACTED] hierarchy (default via extract) we no longer can run into the\nproblem of two parallel extracts both trying to create the folder\nhierarchy without exists ok flag, and one must fail.\n\nResolves #5223.\n\nSigned-off-by: Bernát Gábor <[EMAIL_REDACTED]>", "author": "user_f6bd397772c3", "created_at": "2020-12-24T19:20:04+00:00", "merged_at": "2021-07-07T00:14:52+00:00", "base_branch": "master", "head_branch": "5223", "additions": 18, "deletions": 3, "changed_files": 1, "files": [ { "filename": "requests/utils.py", "status": "modified", "additions": 18, "deletions": 3, "changes": 21, "patch": "@@ -256,13 +256,28 @@ def extract_zipped_paths(path):\n \n # we have a valid zip archive and a valid member of that archive\n tmp = tempfile.gettempdir()\n- extracted_path = os.path.join(tmp, *member.split('/'))\n+ extracted_path = os.path.join(tmp, member.split('/')[-1])\n if not os.path.exists(extracted_path):\n- extracted_path = zip_file.extract(member, path=tmp)\n-\n+ # use read + write to avoid the creating nested folders, we only want the file, avoids mkdir racing condition\n+ with atomic_open(extracted_path) as file_handler:\n+ file_handler.write(zip_file.read(member))\n return extracted_path\n \n \n+[USER_REDACTED].contextmanager\n+def atomic_open(filename):\n+ \"\"\"Write a file to the disk in an atomic fashion\"\"\"\n+ replacer = os.rename if sys.version_info[0] == 2 else os.replace\n+ tmp_descriptor, tmp_name = tempfile.mkstemp(dir=os.path.dirname(filename))\n+ try:\n+ with os.fdopen(tmp_descriptor, 'wb') as tmp_handler:\n+ yield tmp_handler\n+ replacer(tmp_name, filename)\n+ except BaseException:\n+ os.remove(tmp_name)\n+ raise\n+\n+\n def from_key_val_list(value):\n \"\"\"Take an object and test to see if it can be represented as a\n dictionary. Unless it can not be represented as such, return an" } ], "reviews": [ { "id": 558723323, "user": "user_f6bd397772c3", "state": "COMMENTED", "body": null, "submitted_at": "2020-12-24T23:18:20+00:00" }, { "id": 700473285, "user": "user_0fa58b6f3572", "state": "APPROVED", "body": null, "submitted_at": "2021-07-07T00:14:46+00:00" } ], "review_comments": [ { "id": 548761782, "user": "user_f6bd397772c3", "body": "Just to handle a further race condition that can happen between opening and writing the file.", "path": "requests/utils.py", "line": 268, "side": "RIGHT", "created_at": "2020-12-24T23:18:20+00:00" } ], "meta": { "languages": [ "py" ], "touches_tests": false, "review_state_summary": { "COMMENTED": 1, "APPROVED": 1 }, "meaningful_comment_count": 1, "has_approval": true, "has_changes_requested": false, "total_review_comments": 1 } } { "_id": "2e27bc990a24dd9e", "_schema_version": "1.0", "_cleaned_at": "2026-02-12T07:46:51.452326+00:00", "repo": "psf/requests", "repo_url": "https://github.com/psf/requests", "license_name": "Apache License 2.0", "license_spdx": "Apache-2.0", "pr_number": 5681, "title": "5677: Rebuild proxies on Session#send", "body": "- Adds some test cases to highlight the issue, some of those seem excessive, I would like suggestions on how to combine them.\n- Rebuilds the proxy configuration on `send`, making it behave like `requests.Session#request` that already did that.", "author": "user_e3e9f7e88b44", "created_at": "2020-12-08T17:39:44+00:00", "merged_at": "2021-01-24T22:59:47+00:00", "base_branch": "master", "head_branch": "5677", "additions": 40, "deletions": 1, "changed_files": 2, "files": [ { "filename": "requests/sessions.py", "status": "modified", "additions": 1, "deletions": 1, "changes": 2, "patch": "@@ -633,7 +633,7 @@ def send(self, request, **kwargs):\n kwargs.setdefault('stream', self.stream)\n kwargs.setdefault('verify', self.verify)\n kwargs.setdefault('cert', self.cert)\n- kwargs.setdefault('proxies', self.proxies)\n+ kwargs.setdefault('proxies', self.rebuild_proxies(request, self.proxies))\n \n # It's possible that users might accidentally send a Request object.\n # Guard against that specific failure case." }, { "filename": "tests/test_requests.py", "status": "modified", "additions": 39, "deletions": 0, "changes": 39, "patch": "@@ -40,6 +40,9 @@\n # listening on that port)\n TARPIT = 'http://10.255.255.1'\n \n+# This is to avoid waiting the timeout of using TARPIT\n+INVALID_PROXY='http://localhost:1'\n+\n try:\n from ssl import SSLContext\n del SSLContext\n@@ -551,6 +554,42 @@ def test_proxy_error_on_bad_url(self, httpbin, httpbin_secure):\n with pytest.raises(InvalidProxyURL):\n requests.get(httpbin(), proxies={'http': 'http:///example.com:8080'})\n \n+ def test_respect_proxy_env_on_send_self_prepared_request(self, httpbin):\n+ with override_environ(http_proxy=INVALID_PROXY):\n+ with pytest.raises(ProxyError):\n+ session = requests.Session()\n+ request = requests.Request('GET', httpbin())\n+ session.send(request.prepare())\n+\n+ def test_respect_proxy_env_on_send_session_prepared_request(self, httpbin):\n+ with override_environ(http_proxy=INVALID_PROXY):\n+ with pytest.raises(ProxyError):\n+ session = requests.Session()\n+ request = requests.Request('GET', httpbin())\n+ prepared = session.prepare_request(request)\n+ session.send(prepared)\n+\n+ def test_respect_proxy_env_on_send_with_redirects(self, httpbin):\n+ with override_environ(http_proxy=INVALID_PROXY):\n+ with pytest.raises(ProxyError):\n+ session = requests.Session()\n+ url = httpbin('redirect/1')\n+ print(url)\n+ request = requests.Request('GET', url)\n+ session.send(request.prepare())\n+\n+ def test_respect_proxy_env_on_get(self, httpbin):\n+ with override_environ(http_proxy=INVALID_PROXY):\n+ with pytest.raises(ProxyError):\n+ session = requests.Session()\n+ session.get(httpbin())\n+\n+ def test_respect_proxy_env_on_request(self, httpbin):\n+ with override_environ(http_proxy=INVALID_PROXY):\n+ with pytest.raises(ProxyError):\n+ session = requests.Session()\n+ session.request(method='GET', url=httpbin())\n+\n def test_basicauth_with_netrc(self, httpbin):\n auth = ('user', 'pass')\n wrong_auth = ('wronguser', 'wrongpass')" } ], "reviews": [ { "id": 549552538, "user": "user_0fa58b6f3572", "state": "COMMENTED", "body": null, "submitted_at": "2020-12-10T19:56:30+00:00" }, { "id": 549691778, "user": "user_e3e9f7e88b44", "state": "COMMENTED", "body": null, "submitted_at": "2020-12-10T23:25:08+00:00" }, { "id": 574960999, "user": "user_e3e9f7e88b44", "state": "COMMENTED", "body": null, "submitted_at": "2021-01-24T19:25:43+00:00" }, { "id": 575000055, "user": "user_0fa58b6f3572", "state": "APPROVED", "body": null, "submitted_at": "2021-01-24T22:59:37+00:00" } ], "review_comments": [ { "id": 540455485, "user": "user_0fa58b6f3572", "body": "I'm 99% certain this isn't actually correct. This does work regardless of whether it's used or not. We should do:\n\n```py\nif kwargs['proxies']:\n kwargs['proxies'] = self.rebuild_proxies(request, kwargs['proxies'])\n```\n\nAfter this line though", "path": "requests/sessions.py", "line": 636, "side": "RIGHT", "created_at": "2020-12-10T19:56:30+00:00" }, { "id": 540575159, "user": "user_e3e9f7e88b44", "body": "What do you mean by \"this\"?\n\nThe problem or the proposed solution?\n\nFor the problem, I've added a fell test cases, which when I remove this line change those were not passing.\n\nAs for the solution.\n\nShould the `proxies` parameter be overwritten by [NAME_REDACTED]?\n\nIf we `rebuild_proxies` there, it will load the environment variables, instead of using what is being passed on the arguments, my solution intentionally considers the arguments as the highest priority.", "path": "requests/sessions.py", "line": 636, "side": "RIGHT", "created_at": "2020-12-10T23:25:07+00:00" }, { "id": 563337600, "user": "user_e3e9f7e88b44", "body": "[USER_REDACTED] \n\nDoes my answer help you understand the problem in any way?\n\nI'm facing this problem in production and the tests do show the inconsistent use of proxy environment variables by `requests.session`.", "path": "requests/sessions.py", "line": 636, "side": "RIGHT", "created_at": "2021-01-24T19:25:43+00:00" }, { "id": 563398766, "user": "user_0fa58b6f3572", "body": "I don't recall 😆 but your logic makes sense.", "path": "requests/sessions.py", "line": 636, "side": "RIGHT", "created_at": "2021-01-24T22:59:34+00:00" } ], "meta": { "languages": [ "py" ], "touches_tests": true, "review_state_summary": { "COMMENTED": 3, "APPROVED": 1 }, "meaningful_comment_count": 4, "has_approval": true, "has_changes_requested": false, "total_review_comments": 4 } } { "_id": "cd11201283f49160", "_schema_version": "1.0", "_cleaned_at": "2026-02-12T07:46:51.468723+00:00", "repo": "psf/requests", "repo_url": "https://github.com/psf/requests", "license_name": "Apache License 2.0", "license_spdx": "Apache-2.0", "pr_number": 5652, "title": "Move CI to [NAME_REDACTED]", "body": "Moving us to GH Actions since our Travis configs are in relative disarray and we haven't been running Mac/Windows builds for years at this point.\n\n### Other changes in this PR:\n\n**Pipenv**\nPipenv has caused a lot of friction with users trying to submit PR updates that need dependency changes, so this removes it. I've readded a `requirements-dev.txt` to store dev dependencies.\n\n**Removal of pytest-xdist**\n`pytest-xdist` causes threading issues on macOS for some versions of Python [StackOverflow issue](https://stackoverflow.com/questions/50168647/multiprocessing-causes-python-to-crash-and-gives-an-error-may-have-been-in-progr/52230415). The performance gain on tests is negligible, so I've removed it for config simplicity. If there's strong demand, we could attempt the bash updates or split out the macOS test command in the action definition.\n\n**[NAME_REDACTED] 3.9**\nAdding 3.9 to tests so we can update our trove classifiers before releasing 2.25.", "author": "user_dbf2a999bd6d", "created_at": "2020-11-10T22:27:27+00:00", "merged_at": "2020-11-11T18:29:14+00:00", "base_branch": "master", "head_branch": "github_actions", "additions": 48, "deletions": 1118, "changed_files": 10, "files": [ { "filename": ".github/workflows/run-tests.yml", "status": "added", "additions": 31, "deletions": 0, "changes": 31, "patch": "@@ -0,0 +1,31 @@\n+name: Tests\n+\n+on: [push, pull_request]\n+\n+jobs:\n+ build:\n+ runs-on: ${{ matrix.os }}\n+\n+ strategy:\n+ fail-fast: false\n+ matrix:\n+ python-version: [2.7, 3.5, 3.6, 3.7, 3.8, 3.9]\n+ os: [ubuntu-latest, macOS-latest, windows-latest]\n+ include:\n+ # pypy3 on Mac OS currently fails trying to compile\n+ # brotlipy. Moving pypy3 to only test linux.\n+ - python-version: pypy3\n+ os: ubuntu-latest\n+\n+ steps:\n+ - uses: actions/checkout@v2\n+ - name: Set up Python ${{ matrix.python-version }}\n+ uses: actions/setup-python@v2\n+ with:\n+ python-version: ${{ matrix.python-version }}\n+ - name: Install dependencies\n+ run: |\n+ make\n+ - name: Run tests\n+ run: |\n+ make ci" }, { "filename": ".travis.yml", "status": "removed", "additions": 0, "deletions": 26, "changes": 26, "patch": "@@ -1,26 +0,0 @@\n-language: python\n-# command to install dependencies\n-install: \"make\"\n-# command to run tests\n-script:\n- - make test-readme\n- - make ci\n-cache: pip\n-jobs:\n- include:\n- - stage: test\n- python: '2.7'\n- - stage: test\n- python: '3.5'\n- - stage: test\n- python: '3.6'\n- - stage: test\n- python: '3.7' \n- - stage: test\n- python: 'pypy3'\n- dist: xenial\n- - stage: test\n- python: '3.8'\n- - stage: coverage\n- python: '3.6'\n- script: codecov" }, { "filename": "MANIFEST.in", "status": "modified", "additions": 1, "deletions": 1, "changes": 2, "patch": "@@ -1,2 +1,2 @@\n-include README.md LICENSE NOTICE HISTORY.md pytest.ini requirements.txt [NAME_REDACTED]\n+include README.md LICENSE NOTICE HISTORY.md pytest.ini requirements-dev.txt\n recursive-include tests *.py" }, { "filename": "Makefile", "status": "modified", "additions": 7, "deletions": 7, "changes": 14, "patch": "@@ -1,21 +1,21 @@\n .PHONY: docs\n init:\n-\tpip install pipenv --upgrade\n-\tpipenv install --dev\n+\tpip install -e .[socks]\n+\tpip install -r requirements-dev.txt\n test:\n \t# This runs all of the tests, on both Python 2 and Python 3.\n \tdetox\n ci:\n-\tpipenv run py.test -n 8 --boxed --junitxml=report.xml\n+\tpytest tests --junitxml=report.xml\n \n test-readme:\n-\t[USER_REDACTED] run python setup.py check --restructuredtext --strict && ([ $$? -eq 0 ] && echo \"README.rst and HISTORY.rst ok\") || echo \"Invalid markup in README.rst or HISTORY.rst!\"\n+\tpython setup.py check --restructuredtext --strict && ([ $$? -eq 0 ] && echo \"README.rst and HISTORY.rst ok\") || echo \"Invalid markup in README.rst or HISTORY.rst!\"\n \n flake8:\n-\tpipenv run flake8 --ignore=E501,F401,E128,E402,E731,F821 requests\n+\tflake8 --ignore=E501,F401,E128,E402,E731,F821 requests\n \n coverage:\n-\tpipenv run py.test --cov-config .coveragerc --verbose --cov-report term --cov-report xml --cov=requests tests\n+\tpytest --cov-config .coveragerc --verbose --cov-report term --cov-report xml --cov=requests tests\n \n publish:\n \tpip install 'twine>=1.5.0'\n@@ -25,4 +25,4 @@ publish:\n \n docs:\n \tcd docs && make html\n-\t[USER_REDACTED] \"\\033[95m\\n\\nBuild successful! View the docs homepage at docs/_build/html/index.html.\\n\\033[0m\"\n\\ No newline at end of file\n+\t[USER_REDACTED] \"\\033[95m\\n\\nBuild successful! View the docs homepage at docs/_build/html/index.html.\\n\\033[0m\"" }, { "filename": "Pipfile", "status": "removed", "additions": 0, "deletions": 25, "changes": 25, "patch": "@@ -1,25 +0,0 @@\n-[[source]]\n-url = \"https://pypi.org/simple/\"\n-verify_ssl = true\n-name = \"pypi\"\n-\n-[dev-packages]\n-alabaster = \"*\"\n-codecov = \"*\"\n-docutils = \"*\"\n-detox = \"*\"\n-\"flake8\" = \"*\"\n-httpbin = \">=0.7.0\"\n-more-itertools = \"<6.0\"\n-pysocks = \"*\"\n-pytest = \">=2.8.0,<=3.10.1\"\n-pytest-httpbin = \">=0.0.7,<1.0\"\n-pytest-mock = \"*\"\n-pytest-cov = \"*\"\n-pytest-xdist = \"<=1.25\"\n-readme-renderer = \"*\"\n-sphinx = \"<=1.5.5\"\n-tox = \"*\"\n-\n-[packages]\n-\"requests\" = {path = \".\", editable = true, extras = [\"socks\"]}" }, { "filename": "Pipfile.lock", "status": "removed", "additions": 0, "deletions": 765, "changes": 765, "patch": "@@ -1,765 +0,0 @@\n-{\n- \"_meta\": {\n- \"hash\": {\n- \"sha256\": \"9c8d31d74dee008bc23d846267f23665288b0b1bee2525baca681d1061726701\"\n- },\n- \"pipfile-spec\": 6,\n- \"requires\": {},\n- \"sources\": [\n- {\n- \"name\": \"pypi\",\n- \"url\": \"https://pypi.org/simple/\",\n- \"verify_ssl\": true\n- }\n- ]\n- },\n- \"default\": {\n- \"certifi\": {\n- \"hashes\": [\n- \"sha256:017c25db2a153ce562900032d5bc68e9f191e44e9a0f762f373977de9df1fbb3\",\n- \"sha256:25b64c7da4cd7479594d035c08c2d809eb4aab3a26e5a990ea98cc450c320f1f\"\n- ],\n- \"version\": \"==2019.11.28\"\n- },\n- \"chardet\": {\n- \"hashes\": [\n- \"sha256:84ab92ed1c4d4f16916e05906b6b75a6c0fb5db821cc65e70cbd64a3e2a5eaae\",\n- \"sha256:fc323ffcaeaed0e0a02bf4d117757b98aed530d9ed4531e3e15460124c106691\"\n- ],\n- \"version\": \"==3.0.4\"\n- },\n- \"idna\": {\n- \"hashes\": [\n- \"sha256:7588d1c14ae4c77d74036e8c22ff447b26d0fde8f007354fd48a7814db15b7cb\",\n- \"sha256:a068a21ceac8a4d63dbfd964670474107f541babbd2250d61922f029858365fa\"\n- ],\n- \"version\": \"==2.9\"\n- },\n- \"pysocks\": {\n- \"hashes\": [\n- \"sha256:08e69f092cc6dbe92a0fdd16eeb9b9ffbc13cadfe5ca4c7bd92ffb078b293299\",\n- \"sha256:2725bd0a9925919b9b51739eea5f9e2bae91e83288108a9ad338b2e3a4435ee5\",\n- \"sha256:3f8804571ebe159c380ac6de37643bb4685970655d3bba243530d6558b799aa0\"\n- ],\n- \"version\": \"==1.7.1\"\n- },\n- \"requests\": {\n- \"editable\": true,\n- \"extras\": [\n- \"socks\"\n- ],\n- \"path\": \".\"\n- },\n- \"urllib3\": {\n- \"hashes\": [\n- \"sha256:2f3db8b19923a873b3e5256dc9c2dedfa883e33d87c690d9c7913e1f40673cdc\",\n- \"sha256:87716c2d2a7121198ebcb7ce7cccf6ce5e9ba539041cfbaeecfb641dc0bf6acc\"\n- ],\n- \"version\": \"==1.25.8\"\n- }\n- },\n- \"develop\": {\n- \"alabaster\": {\n- \"hashes\": [\n- \"sha256:446438bdcca0e05bd45ea2de1668c1d9b032e1a9154c2c259092d77031ddd359\",\n- \"sha256:a661d72d58e6ea8a57f7a86e37d86716863ee5e92788398526d58b26a4e4dc02\"\n- ],\n- \"index\": \"pypi\",\n- \"version\": \"==0.7.12\"\n- },\n- \"apipkg\": {\n- \"hashes\": [\n- \"sha256:37228cda29411948b422fae072f57e31d3396d2ee1c9783775980ee9c9990af6\",\n- \"sha256:58587dd4dc3daefad0487f6d9ae32b4542b185e1c36db6993290e7c41ca2b47c\"\n- ],\n- \"version\": \"==1.5\"\n- },\n- \"appdirs\": {\n- \"hashes\": [\n- \"sha256:9e5896d1372858f8dd3344faf4e5014d21849c756c8d5701f78f8a103b372d92\",\n- \"sha256:d8b24664561d0d34ddfaec54636d502d7cea6e29c3eaf68f3df6180863e2166e\"\n- ],\n- \"version\": \"==1.4.3\"\n- },\n- \"atomicwrites\": {\n- \"hashes\": [\n- \"sha256:03472c30eb2c5d1ba9227e4c2ca66ab8287fbfbbda3888aa93dc2e28fc6811b4\",\n- \"sha256:75a9445bac02d8d058d5e1fe689654ba5a6556a1dfd8ce6ec55a0ed79866cfa6\"\n- ],\n- \"version\": \"==1.3.0\"\n- },\n- \"attrs\": {\n- \"hashes\": [\n- \"sha256:08a96c641c3a74e44eb59afb61a24f2cb9f4d7188748e76ba4bb5edfa3cb7d1c\",\n- \"sha256:f7b7ce16570fe9965acd6d30101a28f62fb4a7f9e926b3bbc9b61f8b04247e72\"\n- ],\n- \"version\": \"==19.3.0\"\n- },\n- \"babel\": {\n- \"hashes\": [\n- \"sha256:1aac2ae2d0d8ea368fa90906567f5c08463d98ade155c0c4bfedd6a0f7160e38\",\n- \"sha256:d670ea0b10f8b723672d3a6abeb87b565b244da220d76b4dba1b66269ec152d4\"\n- ],\n- \"version\": \"==2.8.0\"\n- },\n- \"bleach\": {\n- \"hashes\": [\n- \"sha256:cc8da25076a1fe56c3ac63671e2194458e0c4d9c7becfd52ca251650d517903c\",\n- \"sha256:e78e426105ac07026ba098f04de8abe9b6e3e98b5befbf89b51a5ef0a4292b03\"\n- ],\n- \"version\": \"==3.1.4\"\n- },\n- \"blinker\": {\n- \"hashes\": [\n- \"sha256:471aee25f3992bd325afa3772f1063dbdbbca947a041b8b89466dc00d606f8b6\"\n- ],\n- \"version\": \"==1.4\"\n- },\n- \"brotlipy\": {\n- \"hashes\": [\n- \"sha256:07194f4768eb62a4f4ea76b6d0df6ade185e24ebd85877c351daa0a069f1111a\",\n- \"sha256:091b299bf36dd6ef7a06570dbc98c0f80a504a56c5b797f31934d2ad01ae7d17\",\n- \"sha256:09ec3e125d16749b31c74f021aba809541b3564e5359f8c265cbae442810b41a\",\n- \"sha256:0be698678a114addcf87a4b9496c552c68a2c99bf93cf8e08f5738b392e82057\",\n- \"sha256:0fa6088a9a87645d43d7e21e32b4a6bf8f7c3939015a50158c10972aa7f425b7\",\n- \"sha256:1379347337dc3d20b2d61456d44ccce13e0625db2611c368023b4194d5e2477f\",\n- \"sha256:1ea4e578241504b58f2456a6c69952c88866c794648bdc74baee74839da61d44\",\n- \"sha256:2699945a0a992c04fc7dc7fa2f1d0575a2c8b4b769f2874a08e8eae46bef36ae\",\n- \"sha256:2a80319ae13ea8dd60ecdc4f5ccf6da3ae64787765923256b62c598c5bba4121\",\n- \"sha256:2e5c64522364a9ebcdf47c5744a5ddeb3f934742d31e61ebfbbc095460b47162\",\n- \"sha256:36def0b859beaf21910157b4c33eb3b06d8ce459c942102f16988cca6ea164df\",\n- \"sha256:3a3e56ced8b15fbbd363380344f70f3b438e0fd1fcf27b7526b6172ea950e867\",\n- \"sha256:3c1d5e2cf945a46975bdb11a19257fa057b67591eb232f393d260e7246d9e571\",\n- \"sha256:4e4638b49835d567d447a2cfacec109f9a777f219f071312268b351b6839436d\",\n- \"sha256:50ca336374131cfad20612f26cc43c637ac0bfd2be3361495e99270883b52962\",\n- \"sha256:5de6f7d010b7558f72f4b061a07395c5c3fd57f0285c5af7f126a677b976a868\",\n- \"sha256:637847560d671657f993313ecc6c6c6666a936b7a925779fd044065c7bc035b9\",\n- \"sha256:653faef61241bf8bf99d73ca7ec4baa63401ba7b2a2aa88958394869379d67c7\",\n- \"sha256:786afc8c9bd67de8d31f46e408a3386331e126829114e4db034f91eacb05396d\",\n- \"sha256:79aaf217072840f3e9a3b641cccc51f7fc23037496bd71e26211856b93f4b4cb\",\n- \"sha256:7e31f7adcc5851ca06134705fcf3478210da45d35ad75ec181e1ce9ce345bb38\",\n- \"sha256:8b39abc3256c978f575df5cd7893153277216474f303e26f0e43ba3d3969ef96\",\n- \"sha256:9448227b0df082e574c45c983fa5cd4bda7bfb11ea6b59def0940c1647be0c3c\",\n- \"sha256:96bc59ff9b5b5552843dc67999486a220e07a0522dddd3935da05dc194fa485c\",\n- \"sha256:a07647886e24e2fb2d68ca8bf3ada398eb56fd8eac46c733d4d95c64d17f743b\",\n- \"sha256:af65d2699cb9f13b26ec3ba09e75e80d31ff422c03675fcb36ee4dabe588fdc2\",\n- \"sha256:b4c98b0d2c9c7020a524ca5bbff42027db1004c6571f8bc7b747f2b843128e7a\",\n- \"sha256:c6cc0036b1304dd0073eec416cb2f6b9e37ac8296afd9e481cac3b1f07f9db25\",\n- \"sha256:d2c1c724c4ac375feb2110f1af98ecdc0e5a8ea79d068efb5891f621a5b235cb\",\n- \"sha256:dc6c5ee0df9732a44d08edab32f8a616b769cc5a4155a12d2d010d248eb3fb07\",\n- \"sha256:fd1d1c64214af5d90014d82cee5d8141b13d44c92ada7a0c0ec0679c6f15a471\"\n- ],\n- \"version\": \"==0.7.0\"\n- },\n- \"certifi\": {\n- \"hashes\": [\n- \"sha256:017c25db2a153ce562900032d5bc68e9f191e44e9a0f762f373977de9df1fbb3\",\n- \"sha256:25b64c7da4cd7479594d035c08c2d809eb4aab3a26e5a990ea98cc450c320f1f\"\n- ],\n- \"version\": \"==2019.11.28\"\n- },\n- \"cffi\": {\n- \"hashes\": [\n- \"sha256:001bf3242a1bb04d985d63e138230802c6c8d4db3668fb545fb5005ddf5bb5ff\",\n- \"sha256:00789914be39dffba161cfc5be31b55775de5ba2235fe49aa28c148236c4e06b\",\n- \"sha256:028a579fc9aed3af38f4892bdcc7390508adabc30c6af4a6e4f611b0c680e6ac\",\n- \"sha256:14491a910663bf9f13ddf2bc8f60562d6bc5315c1f09c704937ef17293fb85b0\",\n- \"sha256:1cae98a7054b5c9391eb3249b86e0e99ab1e02bb0cc0575da191aedadbdf4384\",\n- \"sha256:2089ed025da3919d2e75a4d963d008330c96751127dd6f73c8dc0c65041b4c26\",\n- \"sha256:2d384f4a127a15ba701207f7639d94106693b6cd64173d6c8988e2c25f3ac2b6\",\n- \"sha256:337d448e5a725bba2d8293c48d9353fc68d0e9e4088d62a9571def317797522b\",\n- \"sha256:399aed636c7d3749bbed55bc907c3288cb43c65c4389964ad5ff849b6370603e\",\n- \"sha256:3b911c2dbd4f423b4c4fcca138cadde747abdb20d196c4a48708b8a2d32b16dd\",\n- \"sha256:3d311bcc4a41408cf5854f06ef2c5cab88f9fded37a3b95936c9879c1640d4c2\",\n- \"sha256:62ae9af2d069ea2698bf536dcfe1e4eed9090211dbaafeeedf5cb6c41b352f66\",\n- \"sha256:66e41db66b47d0d8672d8ed2708ba91b2f2524ece3dee48b5dfb36be8c2f21dc\",\n- \"sha256:675686925a9fb403edba0114db74e741d8181683dcf216be697d208857e04ca8\",\n- \"sha256:7e63cbcf2429a8dbfe48dcc2322d5f2220b77b2e17b7ba023d6166d84655da55\",\n- \"sha256:8a6c688fefb4e1cd56feb6c511984a6c4f7ec7d2a1ff31a10254f3c817054ae4\",\n- \"sha256:8c0ffc886aea5df6a1762d0019e9cb05f825d0eec1f520c51be9d198701daee5\",\n- \"sha256:95cd16d3dee553f882540c1ffe331d085c9e629499ceadfbda4d4fde635f4b7d\",\n- \"sha256:99f748a7e71ff382613b4e1acc0ac83bf7ad167fb3802e35e90d9763daba4d78\",\n- \"sha256:b8c78301cefcf5fd914aad35d3c04c2b21ce8629b5e4f4e45ae6812e461910fa\",\n- \"sha256:c420917b188a5582a56d8b93bdd8e0f6eca08c84ff623a4c16e809152cd35793\",\n- \"sha256:c43866529f2f06fe0edc6246eb4faa34f03fe88b64a0a9a942561c8e22f4b71f\",\n- \"sha256:cab50b8c2250b46fe738c77dbd25ce017d5e6fb35d3407606e7a4180656a5a6a\",\n- \"sha256:cef128cb4d5e0b3493f058f10ce32365972c554572ff821e175dbc6f8ff6924f\",\n- \"sha256:cf16e3cf6c0a5fdd9bc10c21687e19d29ad1fe863372b5543deaec1039581a30\",\n- \"sha256:e56c744aa6ff427a607763346e4170629caf7e48ead6921745986db3692f987f\",\n- \"sha256:e577934fc5f8779c554639376beeaa5657d54349096ef24abe8c74c5d9c117c3\",\n- \"sha256:f2b0fa0c01d8a0c7483afd9f31d7ecf2d71760ca24499c8697aeb5ca37dc090c\"\n- ],\n- \"version\": \"==1.14.0\"\n- },\n- \"chardet\": {\n- \"hashes\": [\n- \"sha256:84ab92ed1c4d4f16916e05906b6b75a6c0fb5db821cc65e70cbd64a3e2a5eaae\",\n- \"sha256:fc323ffcaeaed0e0a02bf4d117757b98aed530d9ed4531e3e15460124c106691\"\n- ],\n- \"version\": \"==3.0.4\"\n- },\n- \"click\": {\n- \"hashes\": [\n- \"sha256:8a18b4ea89d8820c5d0c7da8a64b2c324b4dabb695804dbfea19b9be9d88c0cc\",\n- \"sha256:e345d143d80bf5ee7534056164e5e112ea5e22716bbb1ce727941f4c8b471b9a\"\n- ],\n- \"version\": \"==7.1.1\"\n- },\n- \"codecov\": {\n- \"hashes\": [\n- \"sha256:09fb045eb044a619cd2b9dacd7789ae8e322cb7f18196378579fd8d883e6b665\",\n- \"sha256:aeeefa3a03cac8a78e4f988e935b51a4689bb1f17f20d4e827807ee11135f845\"\n- ],\n- \"index\": \"pypi\",\n- \"version\": \"==2.0.22\"\n- },\n- \"configparser\": {\n- \"hashes\": [\n- \"sha256:254c1d9c79f60c45dfde850850883d5aaa7f19a23f13561243a050d5a7c3fe4c\",\n- \"sha256:c7d282687a5308319bf3d2e7706e575c635b0a470342641c93bea0ea3b5331df\"\n- ],\n- \"markers\": \"python_version < '3.2'\",\n- \"version\": \"==4.0.2\"\n- },\n- \"contextlib2\": {\n- \"hashes\": [\n- \"sha256:01f490098c18b19d2bd5bb5dc445b2054d2fa97f09a4280ba2c5f3c394c8162e\",\n- \"sha256:3355078a159fbb44ee60ea80abd0d87b80b78c248643b49aa6d94673b413609b\"\n- ],\n- \"markers\": \"python_version < '3.2'\",\n- \"version\": \"==0.6.0.post1\"\n- },\n- \"coverage\": {\n- \"hashes\": [\n- \"sha256:03f630aba2b9b0d69871c2e8d23a69b7fe94a1e2f5f10df5049c0df99db639a0\",\n- \"sha256:046a1a742e66d065d16fb564a26c2a15867f17695e7f3d358d7b1ad8a61bca30\",\n- \"sha256:0a907199566269e1cfa304325cc3b45c72ae341fbb3253ddde19fa820ded7a8b\",\n- \"sha256:165a48268bfb5a77e2d9dbb80de7ea917332a79c7adb747bd005b3a07ff8caf0\",\n- \"sha256:1b60a95fc995649464e0cd48cecc8288bac5f4198f21d04b8229dc4097d76823\",\n- \"sha256:1f66cf263ec77af5b8fe14ef14c5e46e2eb4a795ac495ad7c03adc72ae43fafe\",\n- \"sha256:2e08c32cbede4a29e2a701822291ae2bc9b5220a971bba9d1e7615312efd3037\",\n- \"sha256:3844c3dab800ca8536f75ae89f3cf566848a3eb2af4d9f7b1103b4f4f7a5dad6\",\n- \"sha256:408ce64078398b2ee2ec08199ea3fcf382828d2f8a19c5a5ba2946fe5ddc6c31\",\n- \"sha256:443be7602c790960b9514567917af538cac7807a7c0c0727c4d2bbd4014920fd\",\n- \"sha256:4482f69e0701139d0f2c44f3c395d1d1d37abd81bfafbf9b6efbe2542679d892\",\n- \"sha256:4a8a259bf990044351baf69d3b23e575699dd60b18460c71e81dc565f5819ac1\",\n- \"sha256:513e6526e0082c59a984448f4104c9bf346c2da9961779ede1fc458e8e8a1f78\",\n- \"sha256:5f587dfd83cb669933186661a351ad6fc7166273bc3e3a1531ec5c783d997aac\",\n- \"sha256:62061e87071497951155cbccee487980524d7abea647a1b2a6eb6b9647df9006\",\n- \"sha256:641e329e7f2c01531c45c687efcec8aeca2a78a4ff26d49184dce3d53fc35014\",\n- \"sha256:65a7e00c00472cd0f59ae09d2fb8a8aaae7f4a0cf54b2b74f3138d9f9ceb9cb2\",\n- \"sha256:6ad6ca45e9e92c05295f638e78cd42bfaaf8ee07878c9ed73e93190b26c125f7\",\n- \"sha256:73aa6e86034dad9f00f4bbf5a666a889d17d79db73bc5af04abd6c20a014d9c8\",\n- \"sha256:7c9762f80a25d8d0e4ab3cb1af5d9dffbddb3ee5d21c43e3474c84bf5ff941f7\",\n- \"sha256:85596aa5d9aac1bf39fe39d9fa1051b0f00823982a1de5766e35d495b4a36ca9\",\n- \"sha256:86a0ea78fd851b313b2e712266f663e13b6bc78c2fb260b079e8b67d970474b1\",\n- \"sha256:8a620767b8209f3446197c0e29ba895d75a1e272a36af0786ec70fe7834e4307\",\n- \"sha256:922fb9ef2c67c3ab20e22948dcfd783397e4c043a5c5fa5ff5e9df5529074b0a\",\n- \"sha256:9fad78c13e71546a76c2f8789623eec8e499f8d2d799f4b4547162ce0a4df435\",\n- \"sha256:a37c6233b28e5bc340054cf6170e7090a4e85069513320275a4dc929144dccf0\",\n- \"sha256:c3fc325ce4cbf902d05a80daa47b645d07e796a80682c1c5800d6ac5045193e5\",\n- \"sha256:cda33311cb9fb9323958a69499a667bd728a39a7aa4718d7622597a44c4f1441\",\n- \"sha256:db1d4e38c9b15be1521722e946ee24f6db95b189d1447fa9ff18dd16ba89f732\",\n- \"sha256:eda55e6e9ea258f5e4add23bcf33dc53b2c319e70806e180aecbff8d90ea24de\",\n- \"sha256:f372cdbb240e09ee855735b9d85e7f50730dcfb6296b74b95a3e5dea0615c4c1\"\n- ],\n- \"version\": \"==5.0.4\"\n- },\n- \"decorator\": {\n- \"hashes\": [\n- \"sha256:41fa54c2a0cc4ba648be4fd43cff00aedf5b9465c9bf18d64325bc225f08f760\",\n- \"sha256:e3a62f0520172440ca0dcc823749319382e377f37f140a0b99ef45fecb84bfe7\"\n- ],\n- \"version\": \"==4.4.2\"\n- },\n- \"detox\": {\n- \"hashes\": [\n- \"sha256:e650f95f0c7f5858578014b3b193e5dac76c89285c1bbe4bae598fd641bf9cd3\",\n- \"sha256:fcad009e2d20ce61176dc826a2c1562bd712fe53953ca603b455171cf819080f\"\n- ],\n- \"index\": \"pypi\",\n- \"version\": \"==0.19\"\n- },\n- \"distlib\": {\n- \"hashes\": [\n- \"sha256:2e166e231a26b36d6dfe35a48c4464346620f8645ed0ace01ee31822b288de21\"\n- ],\n- \"version\": \"==0.3.0\"\n- },\n- \"dnspython\": {\n- \"hashes\": [\n- \"sha256:36c5e8e38d4369a08b6780b7f27d790a292b2b08eea01607865bf0936c558e01\",\n- \"sha256:f69c21288a962f4da86e56c4905b49d11aba7938d3d740e80d9e366ee4f1632d\"\n- ],\n- \"version\": \"==1.16.0\"\n- },\n- \"docutils\": {\n- \"hashes\": [\n- \"sha256:0c5b78adfbf7762415433f5515cd5c9e762339e23369dbe8000d84a4bf4ab3af\",\n- \"sha256:c2de3a60e9e7d07be26b7f2b00ca0309c207e06c100f9cc2a94931fc75a478fc\"\n- ],\n- \"index\": \"pypi\",\n- \"version\": \"==0.16\"\n- },\n- \"entrypoints\": {\n- \"hashes\": [\n- \"sha256:589f874b313739ad35be6e0cd7efde2a4e9b6fea91edcc34e58ecbb8dbe56d19\",\n- \"sha256:c70dd71abe5a8c85e55e12c19bd91ccfeec11a6e99044204511f9ed547d48451\"\n- ],\n- \"version\": \"==0.3\"\n- },\n- \"enum34\": {\n- \"hashes\": [\n- \"sha256:a98a201d6de3f2ab3db284e70a33b0f896fbf35f8086594e8c9e74b909058d53\",\n- \"sha256:c3858660960c984d6ab0ebad691265180da2b43f07e061c0f8dca9ef3cffd328\",\n- \"sha256:cce6a7477ed816bd2542d03d53db9f0db935dd013b70f336a95c73979289f248\"\n- ],\n- \"markers\": \"python_version == '2.7' or python_version == '3.3'\",\n- \"version\": \"==1.1.10\"\n- },\n- \"eventlet\": {\n- \"hashes\": [\n- \"sha256:658b1cd80937adc1a4860de2841e0528f64e2ca672885c4e00fc0e2217bde6b1\",\n- \"sha256:6c9c625af48424c4680d89314dbe45a76cc990cf002489f9469ff214b044ffc1\"\n- ],\n- \"version\": \"==0.25.1\"\n- },\n- \"execnet\": {\n- \"hashes\": [\n- \"sha256:cacb9df31c9680ec5f95553976c4da484d407e85e41c83cb812aa014f0eddc50\",\n- \"sha256:d4efd397930c46415f62f8a31388d6be4f27a91d7550eb79bc64a756e0056547\"\n- ],\n- \"version\": \"==1.7.1\"\n- },\n- \"filelock\": {\n- \"hashes\": [\n- \"sha256:18d82244ee114f543149c66a6e0c14e9c4f8a1044b5cdaadd0f82159d6a6ff59\",\n- \"sha256:929b7d63ec5b7d6b71b0fa5ac14e030b3f70b75747cef1b10da9b879fef15836\"\n- ],\n- \"version\": \"==3.0.12\"\n- },\n- \"flake8\": {\n- \"hashes\": [\n- \"sha256:45681a117ecc81e870cbf1262835ae4af5e7a8b08e40b944a8a6e6b895914cfb\",\n- \"sha256:49356e766643ad15072a789a20915d3c91dc89fd313ccd71802303fd67e4deca\"\n- ],\n- \"index\": \"pypi\",\n- \"version\": \"==3.7.9\"\n- },\n- \"flask\": {\n- \"hashes\": [\n- \"sha256:4efa1ae2d7c9865af48986de8aeb8504bf32c7f3d6fdc9353d34b21f4b127060\",\n- \"sha256:8a4fdd8936eba2512e9c85df320a37e694c93945b33ef33c89946a340a238557\"\n- ],\n- \"version\": \"==1.1.2\"\n- },\n- \"funcsigs\": {\n- \"hashes\": [\n- \"sha256:330cc27ccbf7f1e992e69fef78261dc7c6569012cf397db8d3de0234e6c937ca\",\n- \"sha256:a7bb0f2cf3a3fd1ab2732cb49eba4252c2af4240442415b4abce3b87022a8f50\"\n- ],\n- \"markers\": \"python_version < '3.0'\",\n- \"version\": \"==1.0.2\"\n- },\n- \"functools32\": {\n- \"hashes\": [\n- \"sha256:89d824aa6c358c421a234d7f9ee0bd75933a67c29588ce50aaa3acdf4d403fa0\",\n- \"sha256:f6253dfbe0538ad2e387bd8fdfd9293c925d63553f5813c4e587745416501e6d\"\n- ],\n- \"markers\": \"python_version < '3.2'\",\n- \"version\": \"==3.2.3.post2\"\n- },\n- \"greenlet\": {\n- \"hashes\": [\n- \"sha256:000546ad01e6389e98626c1367be58efa613fa82a1be98b0c6fc24b563acc6d0\",\n- \"sha256:0d48200bc50cbf498716712129eef819b1729339e34c3ae71656964dac907c28\",\n- \"sha256:23d12eacffa9d0f290c0fe0c4e81ba6d5f3a5b7ac3c30a5eaf0126bf4deda5c8\",\n- \"sha256:37c9ba82bd82eb6a23c2e5acc03055c0e45697253b2393c9a50cef76a3985304\",\n- \"sha256:51155342eb4d6058a0ffcd98a798fe6ba21195517da97e15fca3db12ab201e6e\",\n- \"sha256:51503524dd6f152ab4ad1fbd168fc6c30b5795e8c70be4410a64940b3abb55c0\",\n- \"sha256:7457d685158522df483196b16ec648b28f8e847861adb01a55d41134e7734122\",\n- \"sha256:8041e2de00e745c0e05a502d6e6db310db7faa7c979b3a5877123548a4c0b214\",\n- \"sha256:81fcd96a275209ef117e9ec91f75c731fa18dcfd9ffaa1c0adbdaa3616a86043\",\n- \"sha256:853da4f9563d982e4121fed8c92eea1a4594a2299037b3034c3c898cb8e933d6\",\n- \"sha256:8b4572c334593d449113f9dc8d19b93b7b271bdbe90ba7509eb178923327b625\",\n- \"sha256:9416443e219356e3c31f1f918a91badf2e37acf297e2fa13d24d1cc2380f8fbc\",\n- \"sha256:9854f612e1b59ec66804931df5add3b2d5ef0067748ea29dc60f0efdcda9a638\",\n- \"sha256:99a26afdb82ea83a265137a398f570402aa1f2b5dfb4ac3300c026931817b163\",\n- \"sha256:a19bf883b3384957e4a4a13e6bd1ae3d85ae87f4beb5957e35b0be287f12f4e4\",\n- \"sha256:a9f145660588187ff835c55a7d2ddf6abfc570c2651c276d3d4be8a2766db490\",\n- \"sha256:ac57fcdcfb0b73bb3203b58a14501abb7e5ff9ea5e2edfa06bb03035f0cff248\",\n- \"sha256:bcb530089ff24f6458a81ac3fa699e8c00194208a724b644ecc68422e1111939\",\n- \"sha256:beeabe25c3b704f7d56b573f7d2ff88fc99f0138e43480cecdfcaa3b87fe4f87\",\n- \"sha256:d634a7ea1fc3380ff96f9e44d8d22f38418c1c381d5fac680b272d7d90883720\",\n- \"sha256:d97b0661e1aead761f0ded3b769044bb00ed5d33e1ec865e891a8b128bf7c656\",\n- \"sha256:e538b8dae561080b542b0f5af64d47ef859f22517f7eca617bb314e0e03fd7ef\"\n- ],\n- \"version\": \"==0.4.15\"\n- },\n- \"httpbin\": {\n- \"hashes\": [\n- \"sha256:7a04b5904c80b7aa04dd0a6af6520d68ce17a5db175e66a64b971f8e93d73a26\",\n- \"sha256:cbb37790c91575f4f15757f42ad41d9f729eb227d5edbe89e4ec175486db8dfa\"\n- ],\n- \"index\": \"pypi\",\n- \"version\": \"==0.7.0\"\n- },\n- \"idna\": {\n- \"hashes\": [\n- \"sha256:7588d1c14ae4c77d74036e8c22ff447b26d0fde8f007354fd48a7814db15b7cb\",\n- \"sha256:a068a21ceac8a4d63dbfd964670474107f541babbd2250d61922f029858365fa\"\n- ],\n- \"version\": \"==2.9\"\n- },\n- \"imagesize\": {\n- \"hashes\": [\n- \"sha256:6965f19a6a2039c7d48bca7dba2473069ff854c36ae6f19d2cde309d998228a1\",\n- \"sha256:b1f6b5a4eab1f73479a50fb79fcf729514a900c341d8503d62a62dbc4127a2b1\"\n- ],\n- \"version\": \"==1.2.0\"\n- },\n- \"importlib-metadata\": {\n- \"hashes\": [\n- \"sha256:2a688cbaa90e0cc587f1df48bdc97a6eadccdcd9c35fb3f976a09e3b5016d90f\",\n- \"sha256:34513a8a0c4962bc66d35b359558fd8a5e10cd472d37aec5f66858addef32c1e\"\n- ],\n- \"markers\": \"python_version < '3.8'\",\n- \"version\": \"==1.6.0\"\n- },\n- \"importlib-resources\": {\n- \"hashes\": [\n- \"sha256:4019b6a9082d8ada9def02bece4a76b131518866790d58fdda0b5f8c603b36c2\",\n- \"sha256:dd98ceeef3f5ad2ef4cc287b8586da4ebad15877f351e9688987ad663a0a29b8\"\n- ],\n- \"markers\": \"python_version < '3.7'\",\n- \"version\": \"==1.4.0\"\n- },\n- \"itsdangerous\": {\n- \"hashes\": [\n- \"sha256:321b033d07f2a4136d3ec762eac9f16a10ccd60f53c0c91af90217ace7ba1f19\",\n- \"sha256:b12271b2047cb23eeb98c8b5622e2e5c5e9abd9784a153e9d8ef9cb4dd09d749\"\n- ],\n- \"version\": \"==1.1.0\"\n- },\n- \"jinja2\": {\n- \"hashes\": [\n- \"sha256:93187ffbc7808079673ef52771baa950426fd664d3aad1d0fa3e95644360e250\",\n- \"sha256:b0eaf100007721b5c16c1fc1eecb87409464edc10469ddc9a22a27a99123be49\"\n- ],\n- \"version\": \"==2.11.1\"\n- },\n- \"markupsafe\": {\n- \"hashes\": [\n- \"sha256:00bc623926325b26bb9605ae9eae8a215691f33cae5df11ca5424f06f2d1f473\",\n- \"sha256:09027a7803a62ca78792ad89403b1b7a73a01c8cb65909cd876f7fcebd79b161\",\n- \"sha256:09c4b7f37d6c648cb13f9230d847adf22f8171b1ccc4d5682398e77f40309235\",\n- \"sha256:1027c282dad077d0bae18be6794e6b6b8c91d58ed8a8d89a89d59693b9131db5\",\n- \"sha256:13d3144e1e340870b25e7b10b98d779608c02016d5184cfb9927a9f10c689f42\",\n- \"sha256:24982cc2533820871eba85ba648cd53d8623687ff11cbb805be4ff7b4c971aff\",\n- \"sha256:29872e92839765e546828bb7754a68c418d927cd064fd4708fab9fe9c8bb116b\",\n- \"sha256:43a55c2930bbc139570ac2452adf3d70cdbb3cfe5912c71cdce1c2c6bbd9c5d1\",\n- \"sha256:46c99d2de99945ec5cb54f23c8cd5689f6d7177305ebff350a58ce5f8de1669e\",\n- \"sha256:500d4957e52ddc3351cabf489e79c91c17f6e0899158447047588650b5e69183\",\n- \"sha256:535f6fc4d397c1563d08b88e485c3496cf5784e927af890fb3c3aac7f933ec66\",\n- \"sha256:596510de112c685489095da617b5bcbbac7dd6384aeebeda4df6025d0256a81b\",\n- \"sha256:62fe6c95e3ec8a7fad637b7f3d372c15ec1caa01ab47926cfdf7a75b40e0eac1\",\n- \"sha256:6788b695d50a51edb699cb55e35487e430fa21f1ed838122d722e0ff0ac5ba15\",\n- \"sha256:6dd73240d2af64df90aa7c4e7481e23825ea70af4b4922f8ede5b9e35f78a3b1\",\n- \"sha256:717ba8fe3ae9cc0006d7c451f0bb265ee07739daf76355d06366154ee68d221e\",\n- \"sha256:79855e1c5b8da654cf486b830bd42c06e8780cea587384cf6545b7d9ac013a0b\",\n- \"sha256:7c1699dfe0cf8ff607dbdcc1e9b9af1755371f92a68f706051cc8c37d447c905\",\n- \"sha256:88e5fcfb52ee7b911e8bb6d6aa2fd21fbecc674eadd44118a9cc3863f938e735\",\n- \"sha256:8defac2f2ccd6805ebf65f5eeb132adcf2ab57aa11fdf4c0dd5169a004710e7d\",\n- \"sha256:98c7086708b163d425c67c7a91bad6e466bb99d797aa64f965e9d25c12111a5e\",\n- \"sha256:9add70b36c5666a2ed02b43b335fe19002ee5235efd4b8a89bfcf9005bebac0d\",\n- \"sha256:9bf40443012702a1d2070043cb6291650a0841ece432556f784f004937f0f32c\",\n- \"sha256:ade5e387d2ad0d7ebf59146cc00c8044acbd863725f887353a10df825fc8ae21\",\n- \"sha256:b00c1de48212e4cc9603895652c5c410df699856a2853135b3967591e4beebc2\",\n- \"sha256:b1282f8c00509d99fef04d8ba936b156d419be841854fe901d8ae224c59f0be5\",\n- \"sha256:b2051432115498d3562c084a49bba65d97cf251f5a331c64a12ee7e04dacc51b\",\n- \"sha256:ba59edeaa2fc6114428f1637ffff42da1e311e29382d81b339c1817d37ec93c6\",\n- \"sha256:c8716a48d94b06bb3b2524c2b77e055fb313aeb4ea620c8dd03a105574ba704f\",\n- \"sha256:cd5df75523866410809ca100dc9681e301e3c27567cf498077e8551b6d20e42f\",\n- \"sha256:cdb132fc825c38e1aeec2c8aa9338310d29d337bebbd7baa06889d09a60a1fa2\",\n- \"sha256:e249096428b3ae81b08327a63a485ad0878de3fb939049038579ac0ef61e17e7\",\n- \"sha256:e8313f01ba26fbbe36c7be1966a7b7424942f670f38e666995b88d012765b9be\"\n- ],\n- \"version\": \"==1.1.1\"\n- },\n- \"mccabe\": {\n- \"hashes\": [\n- \"sha256:ab8a6258860da4b6677da4bd2fe5dc2c659cff31b3ee4f7f5d64e79735b80d42\",\n- \"sha256:dd8d182285a0fe56bace7f45b5e7d1a6ebcbf524e8f3bd87eb0f125271b8831f\"\n- ],\n- \"version\": \"==0.6.1\"\n- },\n- \"mock\": {\n- \"hashes\": [\n- \"sha256:83657d894c90d5681d62155c82bda9c1187827525880eda8ff5df4ec813437c3\",\n- \"sha256:d157e52d4e5b938c550f39eb2fd15610db062441a9c2747d3dbfa9298211d0f8\"\n- ],\n- \"markers\": \"python_version < '3.0'\",\n- \"version\": \"==3.0.5\"\n- },\n- \"monotonic\": {\n- \"hashes\": [\n- \"sha256:23953d55076df038541e648a53676fb24980f7a1be290cdda21300b3bc21dfb0\",\n- \"sha256:552a91f381532e33cbd07c6a2655a21908088962bb8fa7239ecbcc6ad1140cc7\"\n- ],\n- \"version\": \"==1.5\"\n- },\n- \"more-itertools\": {\n- \"hashes\": [\n- \"sha256:38a936c0a6d98a38bcc2d03fdaaedaba9f412879461dd2ceff8d37564d6522e4\",\n- \"sha256:c0a5785b1109a6bd7fac76d6837fd1feca158e54e521ccd2ae8bfe393cc9d4fc\",\n- \"sha256:fe7a7cae1ccb57d33952113ff4fa1bc5f879963600ed74918f1236e212ee50b9\"\n- ],\n- \"index\": \"pypi\",\n- \"version\": \"==5.0.0\"\n- },\n- \"pathlib2\": {\n- \"hashes\": [\n- \"sha256:0ec8205a157c80d7acc301c0b18fbd5d44fe655968f5d947b6ecef5290fc35db\",\n- \"sha256:6cd9a47b597b37cc57de1c05e56fb1a1c9cc9fab04fe78c29acd090418529868\"\n- ],\n- \"markers\": \"python_version < '3.6'\",\n- \"version\": \"==2.3.5\"\n- },\n- \"pluggy\": {\n- \"hashes\": [\n- \"sha256:15b2acde666561e1298d71b523007ed7364de07029219b604cf808bfa1c765b0\",\n- \"sha256:966c145cd83c96502c3c3868f50408687b38434af77734af1e9ca461a4081d2d\"\n- ],\n- \"version\": \"==0.13.1\"\n- },\n- \"py\": {\n- \"hashes\": [\n- \"sha256:5e27081401262157467ad6e7f851b7aa402c5852dbcb3dae06768434de5752aa\",\n- \"sha256:c20fdd83a5dbc0af9efd622bee9a5564e278f6380fffcacc43ba6f43db2813b0\"\n- ],\n- \"version\": \"==1.8.1\"\n- },\n- \"pycodestyle\": {\n- \"hashes\": [\n- \"sha256:95a2219d12372f05704562a14ec30bc76b05a5b297b21a5dfe3f6fac3491ae56\",\n- \"sha256:e40a936c9a450ad81df37f549d676d127b1b66000a6c500caa2b085bc0ca976c\"\n- ],\n- \"version\": \"==2.5.0\"\n- },\n- \"pycparser\": {\n- \"hashes\": [\n- \"sha256:2d475327684562c3a96cc71adf7dc8c4f0565175cf86b6d7a404ff4c771f15f0\",\n- \"sha256:7582ad22678f0fcd81102833f60ef8d0e57288b6b5fb00323d101be910e35705\"\n- ],\n- \"version\": \"==2.20\"\n- },\n- \"pyflakes\": {\n- \"hashes\": [\n- \"sha256:17dbeb2e3f4d772725c777fabc446d5634d1038f234e77343108ce445ea69ce0\",\n- \"sha256:d976835886f8c5b31d47970ed689944a0262b5f3afa00a5a7b4dc81e5449f8a2\"\n- ],\n- \"version\": \"==2.1.1\"\n- },\n- \"pygments\": {\n- \"hashes\": [\n- \"sha256:2a3fe295e54a20164a9df49c75fa58526d3be48e14aceba6d6b1e8ac0bfd6f1b\",\n- \"sha256:98c8aa5a9f778fcd1026a17361ddaf7330d1b7c62ae97c3bb0ae73e0b9b6b0fe\"\n- ],\n- \"version\": \"==2.5.2\"\n- },\n- \"pysocks\": {\n- \"hashes\": [\n- \"sha256:08e69f092cc6dbe92a0fdd16eeb9b9ffbc13cadfe5ca4c7bd92ffb078b293299\",\n- \"sha256:2725bd0a9925919b9b51739eea5f9e2bae91e83288108a9ad338b2e3a4435ee5\",\n- \"sha256:3f8804571ebe159c380ac6de37643bb4685970655d3bba243530d6558b799aa0\"\n- ],\n- \"version\": \"==1.7.1\"\n- },\n- \"pytest\": {\n- \"hashes\": [\n- \"sha256:3f193df1cfe1d1609d4c583838bea3d532b18d6160fd3f55c9447fdca30848ec\",\n- \"sha256:e246cf173c01169b9617fc07264b7b1316e78d7a650055235d6d897bc80d9660\"\n- ],\n- \"index\": \"pypi\",\n- \"version\": \"==3.10.1\"\n- },\n- \"pytest-cov\": {\n- \"hashes\": [\n- \"sha256:cc6742d8bac45070217169f5f72ceee1e0e55b0221f54bcf24845972d3a47f2b\",\n- \"sha256:cdbdef4f870408ebdbfeb44e63e07eb18bb4619fae852f6e760645fa36172626\"\n- ],\n- \"index\": \"pypi\",\n- \"version\": \"==2.8.1\"\n- },\n- \"pytest-forked\": {\n- \"hashes\": [\n- \"sha256:1805699ed9c9e60cb7a8179b8d4fa2b8898098e82d229b0825d8095f0f261100\",\n- \"sha256:1ae25dba8ee2e56fb47311c9638f9e58552691da87e82d25b0ce0e4bf52b7d87\"\n- ],\n- \"version\": \"==1.1.3\"\n- },\n- \"pytest-httpbin\": {\n- \"hashes\": [\n- \"sha256:8cd57e27418a7d7d205fcc9802eea246ed06170e3065abfa76c6d9b40553592c\",\n- \"sha256:d3919c5df0b644454129c0066a8ae62db40ac54bacb4cfd89d8cfa58615a4b42\"\n- ],\n- \"index\": \"pypi\",\n- \"version\": \"==0.3.0\"\n- },\n- \"pytest-mock\": {\n- \"hashes\": [\n- \"sha256:b35eb281e93aafed138db25c8772b95d3756108b601947f89af503f8c629413f\",\n- \"sha256:cb67402d87d5f53c579263d37971a164743dc33c159dfb4fb4a86f37c5552307\"\n- ],\n- \"index\": \"pypi\",\n- \"version\": \"==2.0.0\"\n- },\n- \"pytest-xdist\": {\n- \"hashes\": [\n- \"sha256:96f893094c89fddeaff3f4783f4807f7aeb138be1a0d87a8805057b6af1201b5\",\n- \"sha256:aab1402f2b063df48bf044b042707610f8fcc4c49d0eb9c10e79e30b3f26074f\"\n- ],\n- \"index\": \"pypi\",\n- \"version\": \"==1.25.0\"\n- },\n- \"pytz\": {\n- \"hashes\": [\n- \"sha256:1c557d7d0e871de1f5ccd5833f60fb2550652da6be2693c1e02300743d21500d\",\n- \"sha256:b02c06db6cf09c12dd25137e563b31700d3b80fcc4ad23abb7a315f2789819be\"\n- ],\n- \"version\": \"==2019.3\"\n- },\n- \"raven\": {\n- \"extras\": [\n- \"flask\"\n- ],\n- \"hashes\": [\n- \"sha256:3fa6de6efa2493a7c827472e984ce9b020797d0da16f1db67197bcc23c8fae54\",\n- \"sha256:44a13f87670836e153951af9a3c80405d36b43097db869a36e92809673692ce4\"\n- ],\n- \"version\": \"==6.10.0\"\n- },\n- \"readme-renderer\": {\n- \"hashes\": [\n- \"sha256:1b6d8dd1673a0b293766b4106af766b6eff3654605f9c4f239e65de6076bc222\",\n- \"sha256:e67d64242f0174a63c3b727801a2fff4c1f38ebe5d71d95ff7ece081945a6cd4\"\n- ],\n- \"index\": \"pypi\",\n- \"version\": \"==25.0\"\n- },\n- \"requests\": {\n- \"editable\": true,\n- \"extras\": [\n- \"socks\"\n- ],\n- \"path\": \".\"\n- },\n- \"scandir\": {\n- \"hashes\": [\n- \"sha256:2586c94e907d99617887daed6c1d102b5ca28f1085f90446554abf1faf73123e\",\n- \"sha256:2ae41f43797ca0c11591c0c35f2f5875fa99f8797cb1a1fd440497ec0ae4b022\",\n- \"sha256:2b8e3888b11abb2217a32af0766bc06b65cc4a928d8727828ee68af5a967fa6f\",\n- \"sha256:2c712840c2e2ee8dfaf36034080108d30060d759c7b73a01a52251cc8989f11f\",\n- \"sha256:4d4631f6062e658e9007ab3149a9b914f3548cb38bfb021c64f39a025ce578ae\",\n- \"sha256:67f15b6f83e6507fdc6fca22fedf6ef8b334b399ca27c6b568cbfaa82a364173\",\n- \"sha256:7d2d7a06a252764061a020407b997dd036f7bd6a175a5ba2b345f0a357f0b3f4\",\n- \"sha256:8c5922863e44ffc00c5c693190648daa6d15e7c1207ed02d6f46a8dcc2869d32\",\n- \"sha256:92c85ac42f41ffdc35b6da57ed991575bdbe69db895507af88b9f499b701c188\",\n- \"sha256:b24086f2375c4a094a6b51e78b4cf7ca16c721dcee2eddd7aa6494b42d6d519d\",\n- \"sha256:cb925555f43060a1745d0a321cca94bcea927c50114b623d73179189a4e100ac\"\n- ],\n- \"markers\": \"python_version < '3.5'\",\n- \"version\": \"==1.10.0\"\n- },\n- \"singledispatch\": {\n- \"hashes\": [\n- \"sha256:5b06af87df13818d14f08a028e42f566640aef80805c3b50c5056b086e3c2b9c\",\n- \"sha256:833b46966687b3de7f438c761ac475213e53b306740f1abfaa86e1d1aae56aa8\"\n- ],\n- \"markers\": \"python_version < '3.4'\",\n- \"version\": \"==3.4.0.3\"\n- },\n- \"six\": {\n- \"hashes\": [\n- \"sha256:236bdbdce46e6e6a3d61a337c0f8b763ca1e8717c03b369e87a7ec7ce1319c0a\",\n- \"sha256:8f3cd2e254d8f793e7f3d6d9df77b92252b52637291d0f0da013c76ea2724b6c\"\n- ],\n- \"version\": \"==1.14.0\"\n- },\n- \"snowballstemmer\": {\n- \"hashes\": [\n- \"sha256:209f257d7533fdb3cb73bdbd24f436239ca3b2fa67d56f6ff88e86be08cc5ef0\",\n- \"sha256:df3bac3df4c2c01363f3dd2cfa78cce2840a79b9f1c2d2de9ce8d31683992f52\"\n- ],\n- \"version\": \"==2.0.0\"\n- },\n- \"sphinx\": {\n- \"hashes\": [\n- \"sha256:11f271e7a9398385ed730e90f0bb41dc3815294bdcd395b46ed2d033bc2e7d87\",\n- \"sha256:4064ea6c56feeb268838cb8fbbee507d0c3d5d92fa63a7df935a916b52c9e2f5\"\n- ],\n- \"index\": \"pypi\",\n- \"version\": \"==1.5.5\"\n- },\n- \"toml\": {\n- \"hashes\": [\n- \"sha256:229f81c57791a41d65e399fc06bf0848bab550a9dfd5ed66df18ce5f05e73d5c\",\n- \"sha256:235682dd292d5899d361a811df37e04a8828a5b1da3115886b73cf81ebc9100e\"\n- ],\n- \"version\": \"==0.10.0\"\n- },\n- \"tox\": {\n- \"hashes\": [\n- \"sha256:2a8d8a63660563e41e64e3b5b677e81ce1ffa5e2a93c2c565d3768c287445800\",\n- \"sha256:edfca7809925f49bdc110d0a2d9966bbf35a0c25637216d9586e7a5c5de17bfb\"\n- ],\n- \"index\": \"pypi\",\n- \"version\": \"==3.6.1\"\n- },\n- \"typing\": {\n- \"hashes\": [\n- \"sha256:91dfe6f3f706ee8cc32d38edbbf304e9b7583fb37108fef38229617f8b3eba23\",\n- \"sha256:c8cabb5ab8945cd2f54917be357d134db9cc1eb039e59d1606dc1e60cb1d9d36\",\n- \"sha256:f38d83c5a7a7086543a0f649564d661859c5146a85775ab90c0d2f93ffaa9714\"\n- ],\n- \"markers\": \"python_version < '3.5'\",\n- \"version\": \"==3.7.4.1\"\n- },\n- \"urllib3\": {\n- \"hashes\": [\n- \"sha256:2f3db8b19923a873b3e5256dc9c2dedfa883e33d87c690d9c7913e1f40673cdc\",\n- \"sha256:87716c2d2a7121198ebcb7ce7cccf6ce5e9ba539041cfbaeecfb641dc0bf6acc\"\n- ],\n- \"version\": \"==1.25.8\"\n- },\n- \"virtualenv\": {\n- \"hashes\": [\n- \"sha256:4e399f48c6b71228bf79f5febd27e3bbb753d9d5905776a86667bc61ab628a25\",\n- \"sha256:9e81279f4a9d16d1c0654a127c2c86e5bca2073585341691882c1e66e31ef8a5\"\n- ],\n- \"version\": \"==20.0.15\"\n- },\n- \"webencodings\": {\n- \"hashes\": [\n- \"sha256:a0af1213f3c2226497a97e2b3aa01a7e4bee4f403f95be16fc9acd2947514a78\",\n- \"sha256:b36a1c245f2d304965eb4e0a82848379241dc04b865afcc4aab16748587e1923\"\n- ],\n- \"version\": \"==0.5.1\"\n- },\n- \"werkzeug\": {\n- \"hashes\": [\n- \"sha256:2de2a5db0baeae7b2d2664949077c2ac63fbd16d98da0ff71837f7d1dea3fd43\",\n- \"sha256:6c80b1e5ad3665290ea39320b91e1be1e0d5f60652b964a3070216de83d2e47c\"\n- ],\n- \"version\": \"==1.0.1\"\n- },\n- \"zipp\": {\n- \"hashes\": [\n- \"sha256:c70410551488251b0fee67b460fb9a536af8d6f9f008ad10ac51f615b6a521b1\",\n- \"sha256:e0d9e63797e483a30d27e09fffd308c59a700d365ec34e93cc100844168bf921\"\n- ],\n- \"markers\": \"python_version < '3.8'\",\n- \"version\": \"==1.2.0\"\n- }\n- }\n-}" }, { "filename": "_appveyor/install.ps1", "status": "removed", "additions": 0, "deletions": 229, "changes": 229, "patch": "@@ -1,229 +0,0 @@\n-# Sample script to install Python and pip under Windows\n-# Authors: [NAME_REDACTED], [NAME_REDACTED], [NAME_REDACTED], and [NAME_REDACTED]\n-# License: CC0 1.0 Universal: http://creativecommons.org/publicdomain/zero/1.0/\n-\n-$MINICONDA_URL = \"http://repo.continuum.io/miniconda/\"\n-$BASE_URL = \"https://www.python.org/ftp/python/\"\n-$GET_PIP_URL = \"https://bootstrap.pypa.io/get-pip.py\"\n-$GET_PIP_PATH = \"C:\\get-pip.py\"\n-\n-$PYTHON_PRERELEASE_REGEX = @\"\n-(?x)\n-(?\\d+)\n-\\.\n-(?\\d+)\n-\\.\n-(?\\d+)\n-(?[a-z]{1,2}\\d+)\n-\"@\n-\n-\n-function Download ($filename, $url) {\n- $webclient = [NAME_REDACTED]\n-\n- $basedir = $pwd.Path + \"\\\"\n- $filepath = $basedir + $filename\n- if (Test-Path $filename) {\n- Write-Host \"Reusing\" $filepath\n- return $filepath\n- }\n-\n- # Download and retry up to 3 times in case of network transient errors.\n- Write-Host \"Downloading\" $filename \"from\" $url\n- $retry_attempts = 2\n- for ($i = 0; $i -lt $retry_attempts; $i++) {\n- try {\n- $webclient.DownloadFile($url, $filepath)\n- break\n- }\n- Catch [Exception]{\n- Start-Sleep 1\n- }\n- }\n- if (Test-Path $filepath) {\n- Write-Host \"File saved at\" $filepath\n- } else {\n- # Retry once to get the error message if any at the last try\n- $webclient.DownloadFile($url, $filepath)\n- }\n- return $filepath\n-}\n-\n-\n-function ParsePythonVersion ($python_version) {\n- if ($python_version -match $PYTHON_PRERELEASE_REGEX) {\n- return ([int]$matches.major, [int]$matches.minor, [int]$matches.micro,\n- $matches.prerelease)\n- }\n- $version_obj = [version]$python_version\n- return ($version_obj.major, $version_obj.minor, $version_obj.build, \"\")\n-}\n-\n-\n-function DownloadPython ($python_version, $platform_suffix) {\n- $major, $minor, $micro, $prerelease = ParsePythonVersion $python_version\n-\n- if (($major -le 2 -and $micro -eq 0) `\n- -or ($major -eq 3 -and $minor -le 2 -and $micro -eq 0) `\n- ) {\n- $dir = \"$major.$minor\"\n- $python_version = \"$major.$minor$prerelease\"\n- } else {\n- $dir = \"$major.$minor.$micro\"\n- }\n-\n- if ($prerelease) {\n- if (($major -le 2) `\n- -or ($major -eq 3 -and $minor -eq 1) `\n- -or ($major -eq 3 -and $minor -eq 2) `\n- -or ($major -eq 3 -and $minor -eq 3) `\n- ) {\n- $dir = \"$dir/prev\"\n- }\n- }\n-\n- if (($major -le 2) -or ($major -le 3 -and $minor -le 4)) {\n- $ext = \"msi\"\n- if ($platform_suffix) {\n- $platform_suffix = \".$platform_suffix\"\n- }\n- } else {\n- $ext = \"exe\"\n- if ($platform_suffix) {\n- $platform_suffix = \"-$platform_suffix\"\n- }\n- }\n-\n- $filename = \"python-$python_version$platform_suffix.$ext\"\n- $url = \"$BASE_URL$dir/$filename\"\n- $filepath = Download $filename $url\n- return $filepath\n-}\n-\n-\n-function InstallPython ($python_version, $architecture, $python_home) {\n- Write-Host \"[NAME_REDACTED]\" $python_version \"for\" $architecture \"bit architecture to\" $python_home\n- if (Test-Path $python_home) {\n- Write-Host $python_home \"already exists, skipping.\"\n- return $false\n- }\n- if ($architecture -eq \"32\") {\n- $platform_suffix = \"\"\n- } else {\n- $platform_suffix = \"amd64\"\n- }\n- $installer_path = DownloadPython $python_version $platform_suffix\n- $installer_ext = [System.IO.Path]::GetExtension($installer_path)\n- Write-Host \"Installing $installer_path to $python_home\"\n- $install_log = $python_home + \".log\"\n- if ($installer_ext -eq '.msi') {\n- InstallPythonMSI $installer_path $python_home $install_log\n- } else {\n- InstallPythonEXE $installer_path $python_home $install_log\n- }\n- if (Test-Path $python_home) {\n- Write-Host \"Python $python_version ($architecture) installation complete\"\n- } else {\n- Write-Host \"Failed to install Python in $python_home\"\n- Get-Content -Path $install_log\n- Exit 1\n- }\n-}\n-\n-\n-function InstallPythonEXE ($exepath, $python_home, $install_log) {\n- $install_args = \"/quiet InstallAllUsers=1 TargetDir=$python_home\"\n- RunCommand $exepath $install_args\n-}\n-\n-\n-function InstallPythonMSI ($msipath, $python_home, $install_log) {\n- $install_args = \"/qn /log $install_log /i $msipath TARGETDIR=$python_home\"\n- $uninstall_args = \"/qn /x $msipath\"\n- RunCommand \"msiexec.exe\" $install_args\n- if (-not(Test-Path $python_home)) {\n- Write-Host \"Python seems to be installed else-where, reinstalling.\"\n- RunCommand \"msiexec.exe\" $uninstall_args\n- RunCommand \"msiexec.exe\" $install_args\n- }\n-}\n-\n-function RunCommand ($command, $command_args) {\n- Write-Host $command $command_args\n- Start-Process -FilePath $command -ArgumentList $command_args -Wait -Passthru\n-}\n-\n-\n-function InstallPip ($python_home) {\n- $pip_path = $python_home + \"\\Scripts\\pip.exe\"\n- $python_path = $python_home + \"\\python.exe\"\n- if (-not(Test-Path $pip_path)) {\n- Write-Host \"Installing pip...\"\n- $webclient = [NAME_REDACTED]\n- $webclient.DownloadFile($GET_PIP_URL, $GET_PIP_PATH)\n- Write-Host \"Executing:\" $python_path $GET_PIP_PATH\n- & $python_path $GET_PIP_PATH\n- } else {\n- Write-Host \"pip already installed.\"\n- }\n-}\n-\n-\n-function DownloadMiniconda ($python_version, $platform_suffix) {\n- if ($python_version -eq \"3.4\") {\n- $filename = \"Miniconda3-3.5.5-Windows-\" + $platform_suffix + \".exe\"\n- } else {\n- $filename = \"Miniconda-3.5.5-Windows-\" + $platform_suffix + \".exe\"\n- }\n- $url = $MINICONDA_URL + $filename\n- $filepath = Download $filename $url\n- return $filepath\n-}\n-\n-\n-function InstallMiniconda ($python_version, $architecture, $python_home) {\n- Write-Host \"[NAME_REDACTED]\" $python_version \"for\" $architecture \"bit architecture to\" $python_home\n- if (Test-Path $python_home) {\n- Write-Host $python_home \"already exists, skipping.\"\n- return $false\n- }\n- if ($architecture -eq \"32\") {\n- $platform_suffix = \"x86\"\n- } else {\n- $platform_suffix = \"x86_64\"\n- }\n- $filepath = DownloadMiniconda $python_version $platform_suffix\n- Write-Host \"Installing\" $filepath \"to\" $python_home\n- $install_log = $python_home + \".log\"\n- $args = \"/S /D=$python_home\"\n- Write-Host $filepath $args\n- Start-Process -FilePath $filepath -ArgumentList $args -Wait -Passthru\n- if (Test-Path $python_home) {\n- Write-Host \"Python $python_version ($architecture) installation complete\"\n- } else {\n- Write-Host \"Failed to install Python in $python_home\"\n- Get-Content -Path $install_log\n- Exit 1\n- }\n-}\n-\n-\n-function InstallMinicondaPip ($python_home) {\n- $pip_path = $python_home + \"\\Scripts\\pip.exe\"\n- $conda_path = $python_home + \"\\Scripts\\conda.exe\"\n- if (-not(Test-Path $pip_path)) {\n- Write-Host \"Installing pip...\"\n- $args = \"install --yes pip\"\n- Write-Host $conda_path $args\n- Start-Process -FilePath \"$conda_path\" -ArgumentList $args -Wait -Passthru\n- } else {\n- Write-Host \"pip already installed.\"\n- }\n-}\n-\n-function main () {\n- InstallPython $env:PYTHON_VERSION $env:PYTHON_ARCH $env:PYTHON\n- InstallPip $env:PYTHON\n-}\n-\n-main" }, { "filename": "appveyor.yml", "status": "removed", "additions": 0, "deletions": 62, "changes": 62, "patch": "@@ -1,62 +0,0 @@\n-# AppVeyor.yml from https://github.com/ogrisel/python-appveyor-demo\n-# License: CC0 1.0 Universal: https://creativecommons.org/publicdomain/zero/1.0/\n-\n-build: off\n-\n-environment:\n- matrix:\n- - PYTHON: \"C:\\\\Python27-x64\"\n- PYTHON_VERSION: \"2.7.x\"\n- PYTHON_ARCH: \"64\"\n- TOXENV: \"py27\"\n-\n- - PYTHON: \"C:\\\\Python34-x64\"\n- PYTHON_VERSION: \"3.4.x\"\n- PYTHON_ARCH: \"64\"\n- TOXENV: \"py34\"\n-\n- - PYTHON: \"C:\\\\Python35-x64\"\n- PYTHON_VERSION: \"3.5.x\"\n- PYTHON_ARCH: \"64\"\n- TOXENV: \"py35\"\n-\n- - PYTHON: \"C:\\\\Python36-x64\"\n- PYTHON_VERSION: \"3.6.x\"\n- PYTHON_ARCH: \"64\"\n- TOXENV: \"py36\"\n-\n- - PYTHON: \"C:\\\\Python37-x64\"\n- PYTHON_VERSION: \"3.7.x\"\n- PYTHON_ARCH: \"64\"\n- TOXENV: \"py37\"\n-\n- - PYTHON: \"C:\\\\Python38-x64\"\n- PYTHON_VERSION: \"3.8.x\"\n- PYTHON_ARCH: \"64\"\n- TOXENV: \"py38\"\n-\n-install:\n- # [NAME_REDACTED] (from the official .msi of https://www.python.org/) and pip when\n- # not already installed.\n- - ps: if (-not(Test-Path($env:PYTHON))) { & _appveyor\\install.ps1 }\n-\n- # Prepend newly installed Python to the PATH of this build (this cannot be\n- # done from inside the powershell script as it would require to restart\n- # the parent CMD process).\n- - \"SET PATH=%PYTHON%;%PYTHON%\\\\Scripts;%PATH%\"\n-\n- # Check that we have the expected version and architecture for Python\n- - \"python --version\"\n- - \"python -c \\\"import struct; print(struct.calcsize('P') * 8)\\\"\"\n-\n- # Upgrade to the latest version of pip to avoid it displaying warnings\n- # about it being out of date.\n- - \"python -m pip install --upgrade pip wheel\"\n- - \"C:\\\\MinGW\\\\bin\\\\mingw32-make\"\n- - \"pipenv install -e .[socks] --skip-lock\"\n-\n-test_script:\n- - \"C:\\\\MinGW\\\\bin\\\\mingw32-make coverage\"\n-\n-on_success:\n- - \"pipenv run codecov -f coverage.xml\"" }, { "filename": "requirements-dev.txt", "status": "added", "additions": 6, "deletions": 0, "changes": 6, "patch": "@@ -0,0 +1,6 @@\n+pytest>=2.8.0,<=3.10.1\n+pytest-cov\n+pytest-httpbin<1.0\n+pytest-mock==2.0.0\n+httpbin==0.7.0\n+wheel" }, { "filename": "tests/test_requests.py", "status": "modified", "additions": 3, "deletions": 3, "changes": 6, "patch": "@@ -668,7 +668,7 @@ def test_POSTBIN_GET_POST_FILES(self, httpbin):\n post1 = requests.post(url, data={'some': 'data'})\n assert post1.status_code == 200\n \n- with open('Pipfile') as f:\n+ with open('requirements-dev.txt') as f:\n post2 = requests.post(url, files={'some': f})\n assert post2.status_code == 200\n \n@@ -736,7 +736,7 @@ def test_POSTBIN_GET_POST_FILES_WITH_DATA(self, httpbin):\n post1 = requests.post(url, data={'some': 'data'})\n assert post1.status_code == 200\n \n- with open('Pipfile') as f:\n+ with open('requirements-dev.txt') as f:\n post2 = requests.post(url, data={'some': 'data'}, files={'some': f})\n assert post2.status_code == 200\n \n@@ -773,7 +773,7 @@ def __len__(self):\n \n def test_conflicting_post_params(self, httpbin):\n url = httpbin('post')\n- with open('Pipfile') as f:\n+ with open('requirements-dev.txt') as f:\n with pytest.raises(ValueError):\n requests.post(url, data='[{\"some\": \"data\"}]', files={'some': f})\n with pytest.raises(ValueError):" } ], "reviews": [ { "id": 527710359, "user": "user_0fa58b6f3572", "state": "COMMENTED", "body": null, "submitted_at": "2020-11-11T00:17:46+00:00" }, { "id": 527772501, "user": "user_dbf2a999bd6d", "state": "COMMENTED", "body": null, "submitted_at": "2020-11-11T01:10:24+00:00" }, { "id": 528426254, "user": "user_0fa58b6f3572", "state": "APPROVED", "body": null, "submitted_at": "2020-11-11T18:21:54+00:00" }, { "id": 528427437, "user": "user_b08fb5f52ea1", "state": "APPROVED", "body": "Woo, excited to see the Pipfile go, that means we don't have to maintain our own dependencies on the urllib3 downstream tests!", "submitted_at": "2020-11-11T18:23:35+00:00" } ], "review_comments": [ { "id": 520956859, "user": "user_0fa58b6f3572", "body": "Since we're (rightfully) dropping pipenv, should we get rid of the rest of its cruft (Pipenv, Pipenv.lock)?", "path": "Makefile", "line": 9, "side": "RIGHT", "created_at": "2020-11-11T00:17:46+00:00" }, { "id": 520981915, "user": "user_dbf2a999bd6d", "body": "~I'd been thinking we'd do that in the next minor release. Pipenv has \\~1M downloads a month, but I have no idea if anyone even uses the [NAME_REDACTED]. I'm not tied to waiting if you or Seth feel strongly.~\nI tested pipenv when we remove the Pipfile and it actually degrades pretty gracefully. Let's just remove it now.", "path": "Makefile", "line": 9, "side": "RIGHT", "created_at": "2020-11-11T01:10:24+00:00" } ], "meta": { "languages": [ "in", "lock", "ps1", "py", "txt", "yml" ], "touches_tests": true, "review_state_summary": { "COMMENTED": 2, "APPROVED": 2 }, "meaningful_comment_count": 2, "has_approval": true, "has_changes_requested": false, "total_review_comments": 2 } } { "_id": "c27c3f1ff87afc08", "_schema_version": "1.0", "_cleaned_at": "2026-02-12T07:46:51.472836+00:00", "repo": "psf/requests", "repo_url": "https://github.com/psf/requests", "license_name": "Apache License 2.0", "license_spdx": "Apache-2.0", "pr_number": 5643, "title": "Respect the NETRC environment variable", "body": "Resurecting https://github.com/psf/requests/pull/4339 with incorporated review/feedback\n\nFixes https://github.com/psf/requests/issues/4318", "author": "user_42c44b61b198", "created_at": "2020-10-30T17:20:32+00:00", "merged_at": "2020-11-01T16:52:02+00:00", "base_branch": "master", "head_branch": "netrc", "additions": 10, "deletions": 3, "changed_files": 2, "files": [ { "filename": "docs/user/quickstart.rst", "status": "modified", "additions": 2, "deletions": 1, "changes": 3, "patch": "@@ -213,7 +213,8 @@ Note: Custom headers are given less precedence than more specific sources of inf\n \n * Authorization headers set with `headers=` will be overridden if credentials\n are specified in ``.netrc``, which in turn will be overridden by the ``auth=``\n- parameter.\n+ parameter. Requests will search for the netrc file at `~/.netrc`, `~/_netrc`,\n+ or at the path specified by the `NETRC` environment variable.\n * Authorization headers will be removed if you get redirected off-host.\n * Proxy-Authorization headers will be overridden by [NAME_REDACTED] the URL.\n * Content-Length headers will be overridden when we can determine the length of the content." }, { "filename": "requests/utils.py", "status": "modified", "additions": 8, "deletions": 2, "changes": 10, "patch": "@@ -169,14 +169,20 @@ def super_len(o):\n def get_netrc_auth(url, raise_errors=False):\n \"\"\"Returns the Requests tuple auth for a given url from netrc.\"\"\"\n \n+ netrc_file = os.environ.get('NETRC')\n+ if netrc_file is not None:\n+ netrc_locations = (netrc_file,)\n+ else:\n+ netrc_locations = ('~/{}'.format(f) for f in NETRC_FILES)\n+\n try:\n from netrc import netrc, NetrcParseError\n \n netrc_path = None\n \n- for f in NETRC_FILES:\n+ for f in netrc_locations:\n try:\n- loc = os.path.expanduser('~/{}'.format(f))\n+ loc = os.path.expanduser(f)\n except KeyError:\n # os.path.expanduser can fail when $HOME is undefined and\n # getpwuid fails. See https://bugs.python.org/issue20164 &" } ], "reviews": [ { "id": 520925065, "user": "user_0fa58b6f3572", "state": "COMMENTED", "body": null, "submitted_at": "2020-10-30T18:16:11+00:00" }, { "id": 520939299, "user": "user_42c44b61b198", "state": "COMMENTED", "body": null, "submitted_at": "2020-10-30T18:37:49+00:00" }, { "id": 520951868, "user": "user_42c44b61b198", "state": "COMMENTED", "body": null, "submitted_at": "2020-10-30T18:57:26+00:00" }, { "id": 520952577, "user": "user_42c44b61b198", "state": "COMMENTED", "body": null, "submitted_at": "2020-10-30T18:58:35+00:00" }, { "id": 521148615, "user": "user_0fa58b6f3572", "state": "COMMENTED", "body": null, "submitted_at": "2020-10-31T15:46:27+00:00" }, { "id": 521148634, "user": "user_0fa58b6f3572", "state": "DISMISSED", "body": null, "submitted_at": "2020-10-31T15:46:49+00:00" }, { "id": 521189533, "user": "user_dbf2a999bd6d", "state": "COMMENTED", "body": "Yeah, I think I'm fine with adding support. Left a quick question about the current implementation.", "submitted_at": "2020-11-01T03:30:40+00:00" }, { "id": 521189789, "user": "user_dbf2a999bd6d", "state": "COMMENTED", "body": null, "submitted_at": "2020-11-01T03:37:52+00:00" }, { "id": 521189969, "user": "user_42c44b61b198", "state": "COMMENTED", "body": null, "submitted_at": "2020-11-01T03:43:20+00:00" }, { "id": 521190054, "user": "user_42c44b61b198", "state": "COMMENTED", "body": null, "submitted_at": "2020-11-01T03:46:02+00:00" }, { "id": 521190344, "user": "user_dbf2a999bd6d", "state": "COMMENTED", "body": null, "submitted_at": "2020-11-01T03:54:57+00:00" }, { "id": 521190468, "user": "user_42c44b61b198", "state": "COMMENTED", "body": null, "submitted_at": "2020-11-01T03:58:09+00:00" }, { "id": 521190637, "user": "user_42c44b61b198", "state": "COMMENTED", "body": null, "submitted_at": "2020-11-01T04:02:31+00:00" }, { "id": 521238976, "user": "user_0fa58b6f3572", "state": "APPROVED", "body": null, "submitted_at": "2020-11-01T16:20:31+00:00" }, { "id": 521241413, "user": "user_dbf2a999bd6d", "state": "APPROVED", "body": "Great, this looks good to me. Thanks [USER_REDACTED]!", "submitted_at": "2020-11-01T16:51:50+00:00" } ], "review_comments": [ { "id": 515293992, "user": "user_0fa58b6f3572", "body": "Why are you duplicating `.eggs` here? And `.tox` below?", "path": ".gitignore", "line": null, "side": "RIGHT", "created_at": "2020-10-30T18:16:10+00:00" }, { "id": 515304726, "user": "user_42c44b61b198", "body": "ah jeez, let me fix that...", "path": ".gitignore", "line": null, "side": "RIGHT", "created_at": "2020-10-30T18:37:49+00:00" }, { "id": 515314229, "user": "user_42c44b61b198", "body": "hrm, I amended the commit and force-pushed on my fork, but this change is still showing up...", "path": ".gitignore", "line": null, "side": "RIGHT", "created_at": "2020-10-30T18:57:26+00:00" }, { "id": 515314732, "user": "user_42c44b61b198", "body": "ok here goes.", "path": ".gitignore", "line": null, "side": "RIGHT", "created_at": "2020-10-30T18:58:35+00:00" }, { "id": 515509645, "user": "user_0fa58b6f3572", "body": "GitHub does that to avoid confusing folks with \"I left feedback here! They force-pushed and now it's disappeared!\"", "path": ".gitignore", "line": null, "side": "RIGHT", "created_at": "2020-10-31T15:46:27+00:00" }, { "id": 515570061, "user": "user_dbf2a999bd6d", "body": "This doesn't look quite right. Are all `NETRC` paths relative to the users home directory? I think we only want this formatting for the `NETRC_FILES`.", "path": "requests/utils.py", "line": null, "side": "RIGHT", "created_at": "2020-11-01T03:29:19+00:00" }, { "id": 515570584, "user": "user_dbf2a999bd6d", "body": "Actually, it looks like the last PR has [similar feedback](https://github.com/psf/requests/pull/4339#discussion_r144723124). If we can get that or something similar incorporated, I think we're set.", "path": "requests/utils.py", "line": null, "side": "RIGHT", "created_at": "2020-11-01T03:37:52+00:00" }, { "id": 515570915, "user": "user_42c44b61b198", "body": "very true... how's this then?", "path": "requests/utils.py", "line": null, "side": "RIGHT", "created_at": "2020-11-01T03:43:20+00:00" }, { "id": 515571119, "user": "user_42c44b61b198", "body": "I can also do it exactly as suggested in previous PR... let me know", "path": "requests/utils.py", "line": null, "side": "RIGHT", "created_at": "2020-11-01T03:46:02+00:00" }, { "id": 515571702, "user": "user_dbf2a999bd6d", "body": "I'm a little hesitant to mutate this directly with how long it's been around. Let's keep the formatting inside `get_netrc_auth` if possible.", "path": "requests/utils.py", "line": null, "side": "RIGHT", "created_at": "2020-11-01T03:54:57+00:00" }, { "id": 515571919, "user": "user_42c44b61b198", "body": "ah makes total sense, wouldn't have thought of that... changing then!", "path": "requests/utils.py", "line": null, "side": "RIGHT", "created_at": "2020-11-01T03:58:09+00:00" }, { "id": 515572244, "user": "user_42c44b61b198", "body": "done.", "path": "requests/utils.py", "line": null, "side": "RIGHT", "created_at": "2020-11-01T04:02:31+00:00" } ], "meta": { "languages": [ "py", "rst" ], "touches_tests": false, "review_state_summary": { "COMMENTED": 12, "DISMISSED": 1, "APPROVED": 2 }, "meaningful_comment_count": 11, "has_approval": true, "has_changes_requested": false, "total_review_comments": 12 } } { "_id": "0316b7cdad910c52", "_schema_version": "1.0", "_cleaned_at": "2026-02-12T07:46:51.472836+00:00", "repo": "psf/requests", "repo_url": "https://github.com/psf/requests", "license_name": "Apache License 2.0", "license_spdx": "Apache-2.0", "pr_number": 5611, "title": "Create codeql-analysis.yml", "body": null, "author": "user_0fa58b6f3572", "created_at": "2020-10-01T14:19:41+00:00", "merged_at": "2020-10-02T22:10:53+00:00", "base_branch": "master", "head_branch": "add-codescanning", "additions": 66, "deletions": 0, "changed_files": 1, "files": [ { "filename": ".github/workflows/codeql-analysis.yml", "status": "added", "additions": 66, "deletions": 0, "changes": 66, "patch": "@@ -0,0 +1,66 @@\n+# For most projects, this workflow file will not need changing; you simply need\n+# to commit it to your repository.\n+#\n+# You may wish to alter this file to override the set of languages analyzed,\n+# or to provide custom queries or build logic.\n+name: \"CodeQL\"\n+\n+on:\n+ push:\n+ branches: [master]\n+ pull_request:\n+ # The branches below must be a subset of the branches above\n+ branches: [master]\n+ schedule:\n+ - cron: '0 23 * * 0'\n+\n+jobs:\n+ analyze:\n+ name: Analyze\n+ runs-on: ubuntu-latest\n+\n+ strategy:\n+ fail-fast: false\n+\n+\n+ steps:\n+ - name: Checkout repository\n+ uses: actions/checkout@v2\n+ with:\n+ # We must fetch at least the immediate parents so that if this is\n+ # a pull request then we can checkout the head.\n+ fetch-depth: 2\n+\n+ # If this run was triggered by a pull request event, then checkout\n+ # the head of the pull request instead of the merge commit.\n+ - run: git checkout HEAD^2\n+ if: ${{ github.event_name == 'pull_request' }}\n+\n+ # Initializes the CodeQL tools for scanning.\n+ - name: [NAME_REDACTED]\n+ uses: github/codeql-action/init@v1\n+ with:\n+ languages: \"python\"\n+ # If you wish to specify custom queries, you can do so here or in a config file.\n+ # By default, queries listed here will override any specified in a config file. \n+ # Prefix the list here with \"+\" to use these queries and those in the config file.\n+ # queries: ./path/to/local/query, your-org/your-repo/queries@main\n+\n+ # Autobuild attempts to build any compiled languages (C/C++, C#, or Java).\n+ # If this step fails, then you should remove it and run the build manually (see below)\n+ - name: Autobuild\n+ uses: github/codeql-action/autobuild@v1\n+\n+ # ℹ️ Command-line programs to run using the OS shell.\n+ # 📚 https://git.io/JvXDl\n+\n+ # ✏️ If the Autobuild fails above, remove it and uncomment the following three lines\n+ # and modify them (or add more) to build your code if your project\n+ # uses a compiled language\n+\n+ #- run: |\n+ # make bootstrap\n+ # make release\n+\n+ - name: [NAME_REDACTED]\n+ uses: github/codeql-action/analyze@v1" } ], "reviews": [ { "id": 500492666, "user": "user_b08fb5f52ea1", "state": "CHANGES_REQUESTED", "body": "Interesting service! Some of the comments in the yml are a little much, up to you if you want to prune them down a bit.\n\nAlso, if this makes security vulnerabilities public have we tried running it locally and fixed issues before making this automated?", "submitted_at": "2020-10-01T15:55:50+00:00" }, { "id": 501379200, "user": "user_0fa58b6f3572", "state": "COMMENTED", "body": null, "submitted_at": "2020-10-02T19:03:00+00:00" }, { "id": 501381530, "user": "user_0fa58b6f3572", "state": "COMMENTED", "body": null, "submitted_at": "2020-10-02T19:06:45+00:00" }, { "id": 501381619, "user": "user_0fa58b6f3572", "state": "COMMENTED", "body": null, "submitted_at": "2020-10-02T19:06:54+00:00" }, { "id": 501385321, "user": "user_dbf2a999bd6d", "state": "COMMENTED", "body": null, "submitted_at": "2020-10-02T19:13:05+00:00" }, { "id": 501398380, "user": "user_0fa58b6f3572", "state": "COMMENTED", "body": null, "submitted_at": "2020-10-02T19:35:44+00:00" }, { "id": 501418075, "user": "user_b08fb5f52ea1", "state": "APPROVED", "body": "LGTM", "submitted_at": "2020-10-02T20:10:30+00:00" }, { "id": 501449244, "user": "user_dbf2a999bd6d", "state": "APPROVED", "body": null, "submitted_at": "2020-10-02T21:09:06+00:00" } ], "review_comments": [ { "id": 498351730, "user": "user_b08fb5f52ea1", "body": "Can we hard-code `python` here and not use the matrix feature?", "path": ".github/workflows/codeql-analysis.yml", "line": null, "side": "RIGHT", "created_at": "2020-10-01T15:54:18+00:00" }, { "id": 498352098, "user": "user_b08fb5f52ea1", "body": "Is there value in checking the v3 branch if it's likely not going to be released?", "path": ".github/workflows/codeql-analysis.yml", "line": null, "side": "RIGHT", "created_at": "2020-10-01T15:54:52+00:00" }, { "id": 499000189, "user": "user_0fa58b6f3572", "body": "Better question: Is there value in keeping it around if it's not going to be released?", "path": ".github/workflows/codeql-analysis.yml", "line": null, "side": "RIGHT", "created_at": "2020-10-02T19:03:00+00:00" }, { "id": 499001826, "user": "user_0fa58b6f3572", "body": "Done", "path": ".github/workflows/codeql-analysis.yml", "line": null, "side": "RIGHT", "created_at": "2020-10-02T19:06:44+00:00" }, { "id": 499001880, "user": "user_0fa58b6f3572", "body": "Removed it in the second commit as well", "path": ".github/workflows/codeql-analysis.yml", "line": null, "side": "RIGHT", "created_at": "2020-10-02T19:06:53+00:00" }, { "id": 499004453, "user": "user_dbf2a999bd6d", "body": "I think there's a lot of valuable work on the proposed/3.0.0 branch that *could* be released at some point. I was keeping it up to date until we had some of the crazier commit history changes in 2018. I think we can get it back in sync but it's going to take a pretty tedious merge. Alternatively, we could hand pick the relevant feature commits, but that's also a big time investment.\n\nThat said, I don't think there's any value in checking the current proposal branch here.", "path": ".github/workflows/codeql-analysis.yml", "line": null, "side": "RIGHT", "created_at": "2020-10-02T19:13:05+00:00" }, { "id": 499014113, "user": "user_0fa58b6f3572", "body": "Frankly, I think there's a lot of internal refactoring that could make a 3.0 easier to release and maintain long-term. It's something I've thought about for over a year", "path": ".github/workflows/codeql-analysis.yml", "line": null, "side": "RIGHT", "created_at": "2020-10-02T19:35:44+00:00" } ], "meta": { "languages": [ "yml" ], "touches_tests": false, "review_state_summary": { "CHANGES_REQUESTED": 1, "COMMENTED": 5, "APPROVED": 2 }, "meaningful_comment_count": 6, "has_approval": true, "has_changes_requested": true, "total_review_comments": 7 } } { "_id": "c4db515bbb83d1e7", "_schema_version": "1.0", "_cleaned_at": "2026-02-12T07:46:51.472836+00:00", "repo": "psf/requests", "repo_url": "https://github.com/psf/requests", "license_name": "Apache License 2.0", "license_spdx": "Apache-2.0", "pr_number": 5443, "title": "Don't use pyOpenSSL unless no SNI is detected", "body": "This is part 1 on removing `requests[security]` extra, for now we can still support SNI-less installations of Python but instead of unconditional monkey-patching we only patch if we detect either no `ssl` module or no `SNI` support.\n\nRelated: https://github.com/psf/requests/issues/5267\ncc [USER_REDACTED] \n\nAn additional thought I had was if we wanted to warn users about the complete removal of `requests[security]` I don't think there's a way to detect if you were installed via `requests pyopenssl` or `requests[security]` beyond registering a name on PyPI like `requests-security-extra`, trying to import it, and if we do then we know we were installed via `requests[security]` so throw a deprecation warning? Otherwise our \"end-goal\" could be to have `requests[security]` be empty?", "author": "user_b08fb5f52ea1", "created_at": "2020-04-30T13:57:50+00:00", "merged_at": "2020-05-01T23:33:52+00:00", "base_branch": "master", "head_branch": "remove-pyopenssl-default", "additions": 21, "deletions": 8, "changed_files": 2, "files": [ { "filename": "HISTORY.md", "status": "modified", "additions": 7, "deletions": 2, "changes": 9, "patch": "@@ -4,9 +4,14 @@ Release History\n dev\n ---\n \n-**Bugfixes**\n+**Improvements**\n+\n+- pyOpenSSL TLS implementation is now only used if Python\n+ either doesn't have an `ssl` module or doesn't support\n+ SNI. Previously pyOpenSSL was unconditionally used if available.\n+ This applies even if pyOpenSSL is installed via the\n+ `requests[security]` extra (#5443)\n \n-- \\[Short description of non-trivial change.\\]\n \n 2.23.0 (2020-02-19)\n -------------------" }, { "filename": "requests/__init__.py", "status": "modified", "additions": 14, "deletions": 6, "changes": 20, "patch": "@@ -90,14 +90,22 @@ def _check_cryptography(cryptography_version):\n \"version!\".format(urllib3.__version__, chardet.__version__),\n RequestsDependencyWarning)\n \n-# Attempt to enable urllib3's SNI support, if possible\n+# Attempt to enable urllib3's fallback for SNI support\n+# if the standard library doesn't support SNI or the\n+# 'ssl' library isn't available.\n try:\n- from urllib3.contrib import pyopenssl\n- pyopenssl.inject_into_urllib3()\n+ try:\n+ import ssl\n+ except ImportError:\n+ ssl = None\n+\n+ if not getattr(ssl, \"HAS_SNI\", False):\n+ from urllib3.contrib import pyopenssl\n+ pyopenssl.inject_into_urllib3()\n \n- # Check cryptography version\n- from cryptography import __version__ as cryptography_version\n- _check_cryptography(cryptography_version)\n+ # Check cryptography version\n+ from cryptography import __version__ as cryptography_version\n+ _check_cryptography(cryptography_version)\n except ImportError:\n pass" } ], "reviews": [ { "id": 404117261, "user": "user_0fa58b6f3572", "state": "DISMISSED", "body": "One question but otherwise LGTM", "submitted_at": "2020-05-01T11:17:02+00:00" }, { "id": 404146423, "user": "user_b08fb5f52ea1", "state": "COMMENTED", "body": null, "submitted_at": "2020-05-01T12:59:03+00:00" }, { "id": 404436373, "user": "user_dbf2a999bd6d", "state": "DISMISSED", "body": "Ok cool, it sounds like we’ve got agreement this is a decent compromise to at least get us moving in the right direction.", "submitted_at": "2020-05-01T22:46:57+00:00" }, { "id": 404446873, "user": "user_dbf2a999bd6d", "state": "APPROVED", "body": "Perfect 👌", "submitted_at": "2020-05-01T23:31:08+00:00" } ], "review_comments": [ { "id": 418504348, "user": "user_0fa58b6f3572", "body": "GitHub is rendering this oddly. Is this a tab or some kind of mixed white space?", "path": "requests/__init__.py", "line": 106, "side": "RIGHT", "created_at": "2020-05-01T11:16:49+00:00" }, { "id": 418530448, "user": "user_b08fb5f52ea1", "body": "That is a strange render but as far as I can tell they're all spaces.", "path": "requests/__init__.py", "line": 106, "side": "RIGHT", "created_at": "2020-05-01T12:59:03+00:00" } ], "meta": { "languages": [ "md", "py" ], "touches_tests": false, "review_state_summary": { "DISMISSED": 2, "COMMENTED": 1, "APPROVED": 1 }, "meaningful_comment_count": 2, "has_approval": true, "has_changes_requested": false, "total_review_comments": 2 } } { "_id": "960fc2339f0488a2", "_schema_version": "1.0", "_cleaned_at": "2026-02-12T07:46:51.479306+00:00", "repo": "psf/requests", "repo_url": "https://github.com/psf/requests", "license_name": "Apache License 2.0", "license_spdx": "Apache-2.0", "pr_number": 5437, "title": "docs: make danger of verify=False clearer", "body": "This PR makes the danger of setting `verify=False` clearer to users of requests. In many cases, users may set this to `False` when running into problems locally with self-signed certificates, but not realize the risk they are opening themselves up to.\n\nAs an example of how the dangers of not verifying TLS (SSL) certificates is communicated, see Go's `InsecureSkipVerify` docs: https://golang.org/pkg/crypto/tls/\n\n```\n // InsecureSkipVerify controls whether a client verifies the\n // server's certificate chain and host name.\n // If InsecureSkipVerify is true, TLS accepts any certificate\n // presented by [NAME_REDACTED] host name in that certificate.\n // In this mode, TLS is susceptible to man-in-the-middle attacks.\n // This should be used only for testing.\n```\n\nHappy to take feedback on the wording / doc-style - this is my first PR to requests but I care a lot about 'safe defaults' in OSS!", "author": "user_5a14ee944efb", "created_at": "2020-04-25T19:07:50+00:00", "merged_at": "2020-08-17T02:31:06+00:00", "base_branch": "master", "head_branch": "elithrar/improve-verify-docs", "additions": 19, "deletions": 1, "changed_files": 2, "files": [ { "filename": "docs/user/advanced.rst", "status": "modified", "additions": 6, "deletions": 0, "changes": 6, "patch": "@@ -243,6 +243,12 @@ Requests can also ignore verifying the SSL certificate if you set ``verify`` to\n >>> requests.get('https://kennethreitz.org', verify=False)\n \n \n+Note that when ``verify`` is set to ``False``, requests will accept any TLS\n+certificate presented by [NAME_REDACTED], and will ignore hostname mismatches\n+and/or expired certificates, which will make your application vulnerable to\n+man-in-the-middle (MitM) attacks. Setting verify to ``False`` may be useful\n+during local development or testing.\n+\n By default, ``verify`` is set to True. Option ``verify`` only applies to host certs.\n \n [NAME_REDACTED]" }, { "filename": "requests/sessions.py", "status": "modified", "additions": 13, "deletions": 1, "changes": 14, "patch": "@@ -387,6 +387,13 @@ def __init__(self):\n self.stream = False\n \n #: SSL Verification default.\n+ #: Defaults to `True`, requiring requests to verify the TLS certificate at the\n+ #: remote end.\n+ #: If verify is set to `False`, requests will accept any TLS certificate\n+ #: presented by [NAME_REDACTED], and will ignore hostname mismatches and/or\n+ #: expired certificates, which will make your application vulnerable to\n+ #: man-in-the-middle (MitM) attacks.\n+ #: Only set this to `False` for testing.\n self.verify = True\n \n #: SSL client certificate default, if String, path to ssl client\n@@ -495,7 +502,12 @@ def request(self, method, url,\n content. Defaults to ``False``.\n :param verify: (optional) Either a boolean, in which case it controls whether we verify\n the server's TLS certificate, or a string, in which case it must be a path\n- to a CA bundle to use. Defaults to ``True``.\n+ to a CA bundle to use. Defaults to ``True``. When set to\n+ ``False``, requests will accept any TLS certificate presented by\n+ the server, and will ignore hostname mismatches and/or expired\n+ certificates, which will make your application vulnerable to\n+ man-in-the-middle (MitM) attacks. Setting verify to ``False`` \n+ may be useful during local development or testing.\n :param cert: (optional) if String, path to ssl client cert file (.pem).\n If Tuple, ('cert', 'key') pair.\n :rtype: requests.Response" } ], "reviews": [ { "id": 400498245, "user": "user_0fa58b6f3572", "state": "COMMENTED", "body": null, "submitted_at": "2020-04-26T12:23:28+00:00" }, { "id": 400524274, "user": "user_5a14ee944efb", "state": "COMMENTED", "body": null, "submitted_at": "2020-04-26T16:44:34+00:00" }, { "id": 400539825, "user": "user_0fa58b6f3572", "state": "COMMENTED", "body": null, "submitted_at": "2020-04-26T19:22:15+00:00" }, { "id": 400540986, "user": "user_5a14ee944efb", "state": "COMMENTED", "body": null, "submitted_at": "2020-04-26T19:35:29+00:00" }, { "id": 400542509, "user": "user_0fa58b6f3572", "state": "COMMENTED", "body": null, "submitted_at": "2020-04-26T19:52:09+00:00" }, { "id": 400555921, "user": "user_5a14ee944efb", "state": "COMMENTED", "body": null, "submitted_at": "2020-04-26T22:24:27+00:00" }, { "id": 425759845, "user": "user_95967246daba", "state": "APPROVED", "body": null, "submitted_at": "2020-06-06T18:33:55+00:00" }, { "id": 468129687, "user": "user_b08fb5f52ea1", "state": "APPROVED", "body": "LGTM, thank you for this change.", "submitted_at": "2020-08-17T02:17:30+00:00" } ], "review_comments": [ { "id": 415298042, "user": "user_0fa58b6f3572", "body": "There are (rarely) good cases for setting this to False. I'd remove this line as it's likely to cause a fire-storm for the already overtaxed maintainers of this project", "path": "requests/sessions.py", "line": 396, "side": "RIGHT", "created_at": "2020-04-26T12:23:27+00:00" }, { "id": 415350484, "user": "user_5a14ee944efb", "body": "I would agree! The reason that I mentioned this was to get ahead of questions about \"why is this configurable in the first place?\" - which is a reasonable question for someone to ask about an option like this. I'm not sure I grok the 'firestorm' part, though.\n\nHappy to elide if there's strong feelings about it, but \"when would I set this to False\" is a fair question for a newcomer to ask.", "path": "requests/sessions.py", "line": 396, "side": "RIGHT", "created_at": "2020-04-26T16:44:34+00:00" }, { "id": 415381330, "user": "user_0fa58b6f3572", "body": "There are people who jump on things like this as soon as they find it and then they post about it in places to get attention and trigger a pile-on. The project has had issues like this in the past (for example, when it kept it's own certificate bundle copy from Mozilla instead of keeping that in certifi) and so given how sensitive people can be around this particular flag and topic, I'd rather leave this as an uncontroversial item. I think the \"Only\" in this will be controversial enough that people will get spitting mad and try to rile others up as well", "path": "requests/sessions.py", "line": 396, "side": "RIGHT", "created_at": "2020-04-26T19:22:15+00:00" }, { "id": 415383631, "user": "user_5a14ee944efb", "body": "That’s unfortunate, and hopefully we can point folks to prior art in other libraries/PLs. I have seen pile-ons the other way - e.g where the defaults are _unsafe_. But I digress.\n\nTo make sure I understand your ask concretely: you want me to remove the “Only set this...” sentence from the comment (only) - ?", "path": "requests/sessions.py", "line": 396, "side": "RIGHT", "created_at": "2020-04-26T19:35:29+00:00" }, { "id": 415386893, "user": "user_0fa58b6f3572", "body": "Or phrase it as `\"You might consider settings to False during local development or testing.\"` as I think that's the idea you're conveying", "path": "requests/sessions.py", "line": 396, "side": "RIGHT", "created_at": "2020-04-26T19:52:09+00:00" }, { "id": 415414945, "user": "user_5a14ee944efb", "body": "Done.", "path": "requests/sessions.py", "line": 396, "side": "RIGHT", "created_at": "2020-04-26T22:24:27+00:00" } ], "meta": { "languages": [ "py", "rst" ], "touches_tests": false, "review_state_summary": { "COMMENTED": 6, "APPROVED": 2 }, "meaningful_comment_count": 5, "has_approval": true, "has_changes_requested": false, "total_review_comments": 6 } } { "_id": "d495e23b93f43316", "_schema_version": "1.0", "_cleaned_at": "2026-02-12T07:46:51.481317+00:00", "repo": "psf/requests", "repo_url": "https://github.com/psf/requests", "license_name": "Apache License 2.0", "license_spdx": "Apache-2.0", "pr_number": 5391, "title": "Send only one Host header in chunked request", "body": "Send only one Host header when specifying a custom Host header in a chunked request.\n\nBefore this fix, the default Host header was sent along with the custom Host header.\n\nCloses #5274", "author": "user_dfe95ac7a79b", "created_at": "2020-03-17T22:01:53+00:00", "merged_at": "2021-11-29T15:58:32+00:00", "base_branch": "main", "head_branch": "fix-5274", "additions": 52, "deletions": 1, "changed_files": 3, "files": [ { "filename": "AUTHORS.rst", "status": "modified", "additions": 1, "deletions": 0, "changes": 1, "patch": "@@ -191,3 +191,4 @@ Patches and Suggestions\n - \"[NAME_REDACTED]\" <[EMAIL_REDACTED]> ([CONTRIBUTOR_REDACTED])\n - [NAME_REDACTED] ([CONTRIBUTOR_REDACTED])\n - Sylvain Marié ([CONTRIBUTOR_REDACTED])\n+- [NAME_REDACTED] ([CONTRIBUTOR_REDACTED])" }, { "filename": "requests/adapters.py", "status": "modified", "additions": 3, "deletions": 1, "changes": 4, "patch": "@@ -458,9 +458,11 @@ def send(self, request, stream=False, timeout=None, verify=True, cert=None, prox\n low_conn = conn._get_conn(timeout=DEFAULT_POOL_TIMEOUT)\n \n try:\n+ skip_host = 'Host' in request.headers\n low_conn.putrequest(request.method,\n url,\n- skip_accept_encoding=True)\n+ skip_accept_encoding=True,\n+ skip_host=skip_host)\n \n for header, value in request.headers.items():\n low_conn.putheader(header, value)" }, { "filename": "tests/test_lowlevel.py", "status": "modified", "additions": 48, "deletions": 0, "changes": 48, "patch": "@@ -9,6 +9,18 @@\n from .utils import override_environ\n \n \n+def echo_response_handler(sock):\n+ \"\"\"Simple handler that will take request and echo it back to requester.\"\"\"\n+ request_content = consume_socket_content(sock, timeout=0.5)\n+\n+ text_200 = (\n+ b'HTTP/1.1 200 OK\\r\\n'\n+ b'Content-Length: %d\\r\\n\\r\\n'\n+ b'%s'\n+ ) % (len(request_content), request_content)\n+ sock.send(text_200)\n+\n+\n def test_chunked_upload():\n \"\"\"can safely send generators\"\"\"\n close_server = threading.Event()\n@@ -46,6 +58,42 @@ def incomplete_chunked_response_handler(sock):\n close_server.set() # release server block\n \n \n+def test_chunked_upload_uses_only_specified_host_header():\n+ \"\"\"Ensure we use only the specified Host header for chunked requests.\"\"\"\n+ close_server = threading.Event()\n+ server = Server(echo_response_handler, wait_to_close_event=close_server)\n+\n+ data = iter([b'a', b'b', b'c'])\n+ custom_host = 'sample-host'\n+\n+ with server as (host, port):\n+ url = 'http://{}:{}/'.format(host, port)\n+ r = requests.post(url, data=data, headers={'Host': custom_host}, stream=True)\n+ close_server.set() # release server block\n+\n+ expected_header = b'Host: %s\\r\\n' % custom_host.encode('utf-8')\n+ assert expected_header in r.content\n+ assert r.content.count(b'Host: ') == 1\n+\n+\n+def test_chunked_upload_doesnt_skip_host_header():\n+ \"\"\"Ensure we don't omit all Host headers with chunked requests.\"\"\"\n+ close_server = threading.Event()\n+ server = Server(echo_response_handler, wait_to_close_event=close_server)\n+\n+ data = iter([b'a', b'b', b'c'])\n+\n+ with server as (host, port):\n+ expected_host = '{}:{}'.format(host, port)\n+ url = 'http://{}:{}/'.format(host, port)\n+ r = requests.post(url, data=data, stream=True)\n+ close_server.set() # release server block\n+\n+ expected_header = b'Host: %s\\r\\n' % expected_host.encode('utf-8')\n+ assert expected_header in r.content\n+ assert r.content.count(b'Host: ') == 1\n+\n+\n def test_conflicting_content_lengths():\n \"\"\"Ensure we correctly throw an InvalidHeader error if multiple\n conflicting Content-Length headers are returned." } ], "reviews": [ { "id": 425760898, "user": "user_95967246daba", "state": "DISMISSED", "body": null, "submitted_at": "2020-06-06T18:53:59+00:00" }, { "id": 530605943, "user": "user_95967246daba", "state": "COMMENTED", "body": null, "submitted_at": "2020-11-14T21:30:07+00:00" }, { "id": 530606142, "user": "user_95967246daba", "state": "APPROVED", "body": null, "submitted_at": "2020-11-14T21:33:16+00:00" }, { "id": 744799683, "user": "user_dbf2a999bd6d", "state": "APPROVED", "body": "Thanks for digging in a finding a simple solution here, [USER_REDACTED]! This seems like a straight forward win that alleviates the risks of other patches we've had for #5274. Apologies this has been sitting so long.\n\nI've added some minor test refactoring to make these easier to expand later and rebased your changes onto our `main` branch. I think this should be set!", "submitted_at": "2021-09-02T08:57:14+00:00" } ], "review_comments": [ { "id": 523465475, "user": "user_95967246daba", "body": "That's good, this appears to be the same way that the same situation is handled in the urllib3 code itself: https://github.com/urllib3/urllib3/blob/74d6be1ab66cef44c0f479c24b0fc1756a8fe4e9/src/urllib3/connection.py#L243-L246", "path": "requests/adapters.py", "line": null, "side": "RIGHT", "created_at": "2020-11-14T21:30:07+00:00" } ], "meta": { "languages": [ "py", "rst" ], "touches_tests": true, "review_state_summary": { "DISMISSED": 1, "COMMENTED": 1, "APPROVED": 2 }, "meaningful_comment_count": 1, "has_approval": true, "has_changes_requested": false, "total_review_comments": 1 } } { "_id": "4b9c14f4c1584e54", "_schema_version": "1.0", "_cleaned_at": "2026-02-12T07:46:51.483319+00:00", "repo": "psf/requests", "repo_url": "https://github.com/psf/requests", "license_name": "Apache License 2.0", "license_spdx": "Apache-2.0", "pr_number": 5336, "title": "Remove explicit unicode literal in README.md and doc", "body": "As the end of python 2 has come, I open this PR in order to get rid of the explicit unicode literal in the README file and the documentation.\nI know that this could be against the PEP 414 https://www.python.org/dev/peps/pep-0414/ but it should be harmless for the project.", "author": "user_f9f268d1dfdc", "created_at": "2020-02-13T21:44:12+00:00", "merged_at": "2020-03-25T19:44:52+00:00", "base_branch": "master", "head_branch": "master", "additions": 17, "deletions": 17, "changed_files": 4, "files": [ { "filename": "README.md", "status": "modified", "additions": 2, "deletions": 2, "changes": 4, "patch": "@@ -38,9 +38,9 @@ by [NAME_REDACTED] & is protected by The <\n >>> r.encoding\n 'utf-8'\n >>> r.text\n-u'{\"type\":\"User\"...'\n+'{\"type\":\"User\"...'\n >>> r.json()\n-{u'disk_usage': 368627, u'private_gists': 484, ...}\n+{'disk_usage': 368627, 'private_gists': 484, ...}\n ```" }, { "filename": "docs/index.rst", "status": "modified", "additions": 2, "deletions": 2, "changes": 4, "patch": "@@ -35,9 +35,9 @@ Release v\\ |version|. (:ref:`Installation `)\n >>> r.encoding\n 'utf-8'\n >>> r.text\n- u'{\"type\":\"User\"...'\n+ '{\"type\":\"User\"...'\n >>> r.json()\n- {u'private_gists': 419, u'total_private_repos': 77, ...}\n+ {'private_gists': 419, 'total_private_repos': 77, ...}\n \n See `similar code, sans Requests `_." }, { "filename": "docs/user/advanced.rst", "status": "modified", "additions": 11, "deletions": 11, "changes": 22, "patch": "@@ -698,12 +698,12 @@ So, GitHub returns JSON. That's great, we can use the :meth:`r.json\n >>> commit_data = r.json()\n \n >>> print(commit_data.keys())\n- [u'committer', u'author', u'url', u'tree', u'sha', u'parents', u'message']\n+ ['committer', 'author', 'url', 'tree', 'sha', 'parents', 'message']\n \n- >>> print(commit_data[u'committer'])\n- {u'date': u'2012-05-10T11:10:50-07:00', u'email': u'[EMAIL_REDACTED]', u'name': u'[NAME_REDACTED]'}\n+ >>> print(commit_data['committer'])\n+ {'date': '2012-05-10T11:10:50-07:00', 'email': '[EMAIL_REDACTED]', 'name': '[NAME_REDACTED]'}\n \n- >>> print(commit_data[u'message'])\n+ >>> print(commit_data['message'])\n makin' history\n \n So far, so simple. Well, let's investigate the GitHub API a little bit. Now,\n@@ -746,34 +746,34 @@ this issue already exists, we will use it as an example. Let's start by getting\n \n >>> issue = json.loads(r.text)\n \n- >>> print(issue[u'title'])\n+ >>> print(issue['title'])\n Feature any http verb in docs\n \n- >>> print(issue[u'comments'])\n+ >>> print(issue['comments'])\n 3\n \n Cool, we have three comments. Let's take a look at the last of them.\n \n ::\n \n- >>> r = requests.get(r.url + u'/comments')\n+ >>> r = requests.get(r.url + '/comments')\n >>> r.status_code\n 200\n \n >>> comments = r.json()\n \n >>> print(comments[0].keys())\n- [u'body', u'url', u'created_at', u'updated_at', u'user', u'id']\n+ ['body', 'url', 'created_at', 'updated_at', 'user', 'id']\n \n- >>> print(comments[2][u'body'])\n+ >>> print(comments[2]['body'])\n Probably in the \"advanced\" section\n \n Well, that seems like a silly place. Let's post a comment telling the poster\n that he's silly. Who is the poster, anyway?\n \n ::\n \n- >>> print(comments[2][u'user'][u'login'])\n+ >>> print(comments[2]['user']['login'])\n kennethreitz\n \n OK, so let's tell this Kenneth guy that we think this example should go in the\n@@ -803,7 +803,7 @@ the very common [NAME_REDACTED].\n 201\n \n >>> content = r.json()\n- >>> print(content[u'body'])\n+ >>> print(content['body'])\n Sounds great! I'll get right on it.\n \n Brilliant. Oh, wait, no! I meant to add that it would take me a while, because" }, { "filename": "docs/user/quickstart.rst", "status": "modified", "additions": 2, "deletions": 2, "changes": 4, "patch": "@@ -93,7 +93,7 @@ again::\n \n >>> r = requests.get('https://api.github.com/events')\n >>> r.text\n- u'[{\"repository\":{\"open_issues\":0,\"url\":\"https://github.com/...\n+ '[{\"repository\":{\"open_issues\":0,\"url\":\"https://github.com/...\n \n Requests will automatically decode content from the server. Most unicode\n charsets are seamlessly decoded.\n@@ -148,7 +148,7 @@ There's also a builtin JSON decoder, in case you're dealing with JSON data::\n \n >>> r = requests.get('https://api.github.com/events')\n >>> r.json()\n- [{u'repository': {u'open_issues': 0, u'url': 'https://github.com/...\n+ [{'repository': {'open_issues': 0, 'url': 'https://github.com/...\n \n In case the JSON decoding fails, ``r.json()`` raises an exception. For example, if\n the response gets a 204 ([NAME_REDACTED]), or if the response contains invalid JSON," } ], "reviews": [ { "id": 359421730, "user": "user_278727a2e287", "state": "DISMISSED", "body": null, "submitted_at": "2020-02-16T18:49:54+00:00" }, { "id": 360118718, "user": "user_dbf2a999bd6d", "state": "DISMISSED", "body": "This looks good to me, would you mind squashing and rebasing onto master?", "submitted_at": "2020-02-18T07:35:29+00:00" }, { "id": 363112908, "user": "user_0fa58b6f3572", "state": "COMMENTED", "body": null, "submitted_at": "2020-02-23T18:16:25+00:00" }, { "id": 363225969, "user": "user_f9f268d1dfdc", "state": "COMMENTED", "body": null, "submitted_at": "2020-02-24T08:39:09+00:00" }, { "id": 369016947, "user": "user_f9f268d1dfdc", "state": "COMMENTED", "body": null, "submitted_at": "2020-03-04T18:26:59+00:00" }, { "id": 371095490, "user": "user_0279b4b0e7d3", "state": "APPROVED", "body": null, "submitted_at": "2020-03-09T11:41:48+00:00" }, { "id": 381479817, "user": "user_dbf2a999bd6d", "state": "APPROVED", "body": "Thanks [USER_REDACTED]!", "submitted_at": "2020-03-25T19:44:03+00:00" } ], "review_comments": [ { "id": 383026460, "user": "user_0fa58b6f3572", "body": "Missed one here", "path": "docs/user/quickstart.rst", "line": null, "side": "RIGHT", "created_at": "2020-02-23T18:16:24+00:00" }, { "id": 383132683, "user": "user_f9f268d1dfdc", "body": "Thanks! I'll fix it as soon as possible.", "path": "docs/user/quickstart.rst", "line": null, "side": "RIGHT", "created_at": "2020-02-24T08:39:09+00:00" }, { "id": 387851529, "user": "user_f9f268d1dfdc", "body": "Fixed!", "path": "docs/user/quickstart.rst", "line": null, "side": "RIGHT", "created_at": "2020-03-04T18:26:58+00:00" } ], "meta": { "languages": [ "md", "rst" ], "touches_tests": false, "review_state_summary": { "DISMISSED": 2, "COMMENTED": 3, "APPROVED": 2 }, "meaningful_comment_count": 2, "has_approval": true, "has_changes_requested": false, "total_review_comments": 3 } } { "_id": "3e97453ae8c53f51", "_schema_version": "1.0", "_cleaned_at": "2026-02-12T07:46:51.485315+00:00", "repo": "psf/requests", "repo_url": "https://github.com/psf/requests", "license_name": "Apache License 2.0", "license_spdx": "Apache-2.0", "pr_number": 5208, "title": "Part II: The Principle of Polarity", "body": "Love & Hated appear orthogonal, yet are extracted from the same substance & essences. The opposite of Love is not Hatred — but Apathy.\n\n> Everything is dual; Everything has poles; Everything has its pair of opposites; Like and unlike are the same; Opposites are identical in nature, but different in degree; Extremes meet; All truths, are but half-truths; All paradoxes may be reconciled.\n\n[As above, so below](https://www.kennethreitz.org/as-above-so-below).\n\n☤", "author": "user_36df932e8b7a", "created_at": "2019-09-23T18:27:34+00:00", "merged_at": "2019-09-23T20:08:41+00:00", "base_branch": "master", "head_branch": "partII", "additions": 15, "deletions": 20, "changed_files": 6, "files": [ { "filename": "AUTHORS.rst", "status": "modified", "additions": 2, "deletions": 4, "changes": 6, "patch": "@@ -1,16 +1,14 @@\n-Requests is written and maintained by [NAME_REDACTED]\n-various contributors:\n+Requests was lovingly created by [NAME_REDACTED] the Crystals\n ```````````````````````\n \n-- [NAME_REDACTED] <[EMAIL_REDACTED]> [CONTRIBUTOR_REDACTED], Keeper of the Master Crystal.\n - [NAME_REDACTED] <[EMAIL_REDACTED]> [CONTRIBUTOR_REDACTED]\n - [NAME_REDACTED] <[EMAIL_REDACTED]> [CONTRIBUTOR_REDACTED]\n \n Previous Keepers of Crystals\n ````````````````````````````\n-\n+- [NAME_REDACTED] <[EMAIL_REDACTED]> [CONTRIBUTOR_REDACTED], reluctant Keeper of the Master Crystal.\n - [NAME_REDACTED] <[EMAIL_REDACTED]> [CONTRIBUTOR_REDACTED]" }, { "filename": "README.md", "status": "modified", "additions": 12, "deletions": 16, "changes": 28, "patch": "@@ -1,9 +1,10 @@\n \n \n \n- \n+\n
\n-    \n+    \n+    \n     
\n

\n Python 3.7.4 (default, Sep 7 2019, 18:27:02)\n@@ -12,15 +13,11 @@\n >>> r.json()[\"description\"]\n 'A simple, yet elegant HTTP library. Handcrafted, with ♥, for the Python community.'\n
\n- \n-\n- \n+\n

\n-This software has been designed for you, with much joy, \n-by [NAME_REDACTED] & is secured by The [NAME_REDACTED]. \n+This software has been designed for you, with much joy,\n+by [NAME_REDACTED] & is protected by The [NAME_REDACTED].\n

\n-

 

\n-\n
\n \n
\n@@ -71,14 +68,14 @@ Requests is ready for the demands of building robust and reliable HTTP–speak a\n \n
\n          + [NAME_REDACTED] and URLs       + Keep-Alive & [NAME_REDACTED]\n-         + Sessions with [NAME_REDACTED]     + Browser-style SSL Verification \n-         + Basic & [NAME_REDACTED]        + Familiar `dict`–like Cookies   \n-         + [NAME_REDACTED] of Content   + [NAME_REDACTED]     \n+         + Sessions with [NAME_REDACTED]     + Browser-style SSL Verification\n+         + Basic & [NAME_REDACTED]        + Familiar `dict`–like Cookies\n+         + [NAME_REDACTED] of Content   + [NAME_REDACTED]\n          + [NAME_REDACTED]         + [NAME_REDACTED]*\n-         + [NAME_REDACTED]              + SOCKS [NAME_REDACTED]            \n+         + [NAME_REDACTED]              + SOCKS [NAME_REDACTED]\n          + [NAME_REDACTED]                  + [NAME_REDACTED]\n-         + Automatic honoring of `.netrc`       + Chunked HTTP Requests          \n-              \n+         + Automatic honoring of `.netrc`       + Chunked HTTP Requests\n+\n                             &, of course, rock–solid stability!\n 
\n \n@@ -127,4 +124,3 @@ Requests officially supports Python 2.7 & 3.4–3.8.\n

\n \n

\n-" }, { "filename": "ext/LICENSE", "status": "added", "additions": 1, "deletions": 0, "changes": 1, "patch": "@@ -0,0 +1 @@\n+Copyright 2019 [NAME_REDACTED] reserved." }, { "filename": "ext/deepmind-kr.jpg", "status": "removed", "additions": 0, "deletions": 0, "changes": 0, "patch": null }, { "filename": "ext/flourish.jpg", "status": "removed", "additions": 0, "deletions": 0, "changes": 0, "patch": null }, { "filename": "ext/flower-of-life.jpg", "status": "modified", "additions": 0, "deletions": 0, "changes": 0, "patch": null } ], "reviews": [ { "id": 291974410, "user": "user_c71bba18f1eb", "state": "APPROVED", "body": null, "submitted_at": "2019-09-23T18:35:47+00:00" }, { "id": 291976846, "user": "user_36df932e8b7a", "state": "COMMENTED", "body": null, "submitted_at": "2019-09-23T18:39:59+00:00" } ], "review_comments": [ { "id": 327269074, "user": "user_36df932e8b7a", "body": "**Note**: this is for the images contained within the `ext` folder, which includes a [tattoo upon my arm](https://images.squarespace-cdn.com/content/v1/533ad9bde4b098d084a846b1/1469928300857-S9WKXBO0CCRX0RL4PJYX/ke17ZwdGBToddI8pDm48kKLHmMs23ZxPgeOu8Yrs55d7gQa3H78H3Y0txjaiv_0fDoOvxcdMmMKkDsyUqMSsMWxHk725yiiHCCLfrh8O1z4YTzHvnKhyp6Da-NYroOW3ZGjoBKy3azqku80C789l0iyqMbMesKd95J-X4EagrgXXATmnXitsEasKvdtVty7KcIpiUOmkkpuOP9PWkdpi9w/L1000129-Edit.jpg?format=1500w) — I had the tattoo before I made it the Requests logo :)", "path": "ext/LICENSE", "line": 1, "side": "RIGHT", "created_at": "2019-09-23T18:39:59+00:00" } ], "meta": { "languages": [ "jpg", "md", "rst" ], "touches_tests": false, "review_state_summary": { "APPROVED": 1, "COMMENTED": 1 }, "meaningful_comment_count": 1, "has_approval": true, "has_changes_requested": false, "total_review_comments": 1 } } { "_id": "a3716fe2faa7fd3c", "_schema_version": "1.0", "_cleaned_at": "2026-02-12T07:46:51.487316+00:00", "repo": "psf/requests", "repo_url": "https://github.com/psf/requests", "license_name": "Apache License 2.0", "license_spdx": "Apache-2.0", "pr_number": 4987, "title": "[fix] fix failing doctests in requests/*", "body": "## Why this PR\nRunning the command:\n`\n$ py.test --doctest-module requests\n`\ngives failing doctests. This PR aims to fix these failing doctests.\n\n[NAME_REDACTED]: https://github.com/[USER_REDACTED]nethreitz/requests/issues/4986\n\n## How to test\n`\n$ py.test --doctest-module requests\n`\nAll the 11 doctests should pass.", "author": "user_f9f268d1dfdc", "created_at": "2019-02-17T18:47:44+00:00", "merged_at": "2019-08-20T04:25:51+00:00", "base_branch": "master", "head_branch": "master", "additions": 18, "deletions": 9, "changed_files": 8, "files": [ { "filename": "AUTHORS.rst", "status": "modified", "additions": 2, "deletions": 0, "changes": 2, "patch": "@@ -189,5 +189,7 @@ Patches and Suggestions\n - [NAME_REDACTED] ([CONTRIBUTOR_REDACTED])\n - [NAME_REDACTED] ([CONTRIBUTOR_REDACTED])\n - [NAME_REDACTED] ([CONTRIBUTOR_REDACTED])\n+- \"[NAME_REDACTED]\" <[EMAIL_REDACTED]> ([CONTRIBUTOR_REDACTED])\n+- [NAME_REDACTED] ([CONTRIBUTOR_REDACTED])\n - [NAME_REDACTED] ([CONTRIBUTOR_REDACTED])\n - [NAME_REDACTED] <[EMAIL_REDACTED]> ([CONTRIBUTOR_REDACTED])" }, { "filename": "pytest.ini", "status": "modified", "additions": 2, "deletions": 1, "changes": 3, "patch": "@@ -1,2 +1,3 @@\n [pytest]\n-addopts = -p no:warnings\n\\ No newline at end of file\n+addopts = -p no:warnings --doctest-modules\n+doctest_optionflags= NORMALIZE_WHITESPACE ELLIPSIS\n\\ No newline at end of file" }, { "filename": "requests/__init__.py", "status": "modified", "additions": 5, "deletions": 5, "changes": 10, "patch": "@@ -9,14 +9,14 @@\n Requests HTTP Library\n ~~~~~~~~~~~~~~~~~~~~~\n \n-Requests is an HTTP library, written in Python, for human beings. Basic GET\n-usage:\n+Requests is an HTTP library, written in Python, for human beings.\n+Basic GET usage:\n \n >>> import requests\n >>> r = requests.get('https://www.python.org')\n >>> r.status_code\n 200\n- >>> 'Python is a programming language' in r.content\n+ >>> b'Python is a programming language' in r.content\n True\n \n ... or POST:\n@@ -27,8 +27,8 @@\n {\n ...\n \"form\": {\n- \"key2\": \"value2\",\n- \"key1\": \"value1\"\n+ \"key1\": \"value1\",\n+ \"key2\": \"value2\"\n },\n ...\n }" }, { "filename": "requests/api.py", "status": "modified", "additions": 1, "deletions": 0, "changes": 1, "patch": "@@ -50,6 +50,7 @@ def request(method, url, **kwargs):\n \n >>> import requests\n >>> req = requests.request('GET', 'https://httpbin.org/get')\n+ >>> req\n \n \"\"\"" }, { "filename": "requests/models.py", "status": "modified", "additions": 1, "deletions": 0, "changes": 1, "patch": "@@ -280,6 +280,7 @@ class PreparedRequest(RequestEncodingMixin, RequestHooksMixin):\n >>> import requests\n >>> req = requests.Request('GET', 'https://httpbin.org/get')\n >>> r = req.prepare()\n+ >>> r\n \n \n >>> s = requests.Session()" }, { "filename": "requests/sessions.py", "status": "modified", "additions": 1, "deletions": 1, "changes": 2, "patch": "@@ -354,7 +354,7 @@ class Session(SessionRedirectMixin):\n Or as a context manager::\n \n >>> with requests.Session() as s:\n- >>> s.get('https://httpbin.org/get')\n+ ... s.get('https://httpbin.org/get')\n \n \"\"\"" }, { "filename": "requests/status_codes.py", "status": "modified", "additions": 1, "deletions": 1, "changes": 2, "patch": "@@ -4,7 +4,7 @@\n The ``codes`` object defines a mapping from common names for HTTP statuses\n to their numerical codes, accessible either as attributes or as dictionary\n items.\n-\n+>>> import requests\n >>> requests.codes['temporary_redirect']\n 307\n >>> requests.codes.teapot" }, { "filename": "requests/utils.py", "status": "modified", "additions": 5, "deletions": 1, "changes": 6, "patch": "@@ -267,6 +267,8 @@ def from_key_val_list(value):\n >>> from_key_val_list([('key', 'val')])\n OrderedDict([('key', 'val')])\n >>> from_key_val_list('string')\n+ Traceback (most recent call last):\n+ ...\n ValueError: cannot encode objects that are not 2-tuples\n >>> from_key_val_list({'key': 'val'})\n OrderedDict([('key', 'val')])\n@@ -293,7 +295,9 @@ def to_key_val_list(value):\n >>> to_key_val_list({'key': 'val'})\n [('key', 'val')]\n >>> to_key_val_list('string')\n- ValueError: cannot encode objects that are not 2-tuples.\n+ Traceback (most recent call last):\n+ ...\n+ ValueError: cannot encode objects that are not 2-tuples\n \n :rtype: list\n \"\"\"" } ], "reviews": [ { "id": 204579935, "user": "user_378b41443422", "state": "APPROVED", "body": null, "submitted_at": "2019-02-17T21:00:20+00:00" }, { "id": 212580668, "user": "user_378b41443422", "state": "DISMISSED", "body": null, "submitted_at": "2019-03-09T22:57:01+00:00" }, { "id": 237178192, "user": "user_ba9b4e1a5bdb", "state": "COMMENTED", "body": null, "submitted_at": "2019-05-14T11:19:54+00:00" }, { "id": 237790724, "user": "user_f9f268d1dfdc", "state": "COMMENTED", "body": null, "submitted_at": "2019-05-15T12:35:57+00:00" }, { "id": 239240546, "user": "user_f9f268d1dfdc", "state": "COMMENTED", "body": null, "submitted_at": "2019-05-19T14:27:42+00:00" } ], "review_comments": [ { "id": 283747119, "user": "user_ba9b4e1a5bdb", "body": "Hi, I would suggest to do so: \n```\n >>> print(r.text)\n ... # doctest: +ELLIPSIS\n ... # doctest: +NORMALIZE_WHITESPACE\n {\n ...\n \"form\": {\n \"key2\": \"value2\",\n \"key1\": \"value1\"\n },\n ...\n }\n```\nSo we change the test minimally.", "path": "requests/__init__.py", "line": null, "side": "RIGHT", "created_at": "2019-05-14T11:18:48+00:00" }, { "id": 284231760, "user": "user_f9f268d1dfdc", "body": "Thanks. I did not know that I could use this syntax. I'm going to change it according to your suggestion.", "path": "requests/__init__.py", "line": null, "side": "RIGHT", "created_at": "2019-05-15T12:35:56+00:00" }, { "id": 285383435, "user": "user_f9f268d1dfdc", "body": "I added NORMALIZE_WHITESPACE and ELLIPSIS to the pytest.ini file and removed from the doctest in order to use them in pytest configuration.", "path": "requests/__init__.py", "line": null, "side": "RIGHT", "created_at": "2019-05-19T14:27:41+00:00" } ], "meta": { "languages": [ "ini", "py", "rst" ], "touches_tests": false, "review_state_summary": { "APPROVED": 1, "DISMISSED": 1, "COMMENTED": 3 }, "meaningful_comment_count": 3, "has_approval": true, "has_changes_requested": false, "total_review_comments": 3 } } { "_id": "eb058106b657e3d4", "_schema_version": "1.0", "_cleaned_at": "2026-02-12T07:46:51.488548+00:00", "repo": "psf/requests", "repo_url": "https://github.com/psf/requests", "license_name": "Apache License 2.0", "license_spdx": "Apache-2.0", "pr_number": 4915, "title": "Normalize percent-encoded bytes before comparison", "body": "urllib3 replaced it's URL parser with `rfc3986` for more compliant parsing (urllib3/urllib3#1487). We've also got an effort underway to run downstream tests before releases (urllib3/urllib3#1508) and during that process we've discovered that requests requires percent-encoded bytes to keep their casing.\n\nAdding this to the unit tests would allow either version of pre- and post-rfc3986 urllib3 to pass requests unit tests. I don't know if the `Request.url` attribute needs to maintain it's casing in this situation or not, if it does this is not the solution. Just putting this together as a potential solution.", "author": "user_b08fb5f52ea1", "created_at": "2018-12-23T21:54:59+00:00", "merged_at": "2019-01-21T13:58:33+00:00", "base_branch": "master", "head_branch": "patch-1", "additions": 13, "deletions": 4, "changed_files": 4, "files": [ { "filename": ".travis.yml", "status": "modified", "additions": 1, "deletions": 1, "changes": 2, "patch": "@@ -38,5 +38,5 @@ jobs:\n dist: xenial\n sudo: true \n - stage: coverage\n- python: 3.6\n+ python: '3.6'\n script: codecov" }, { "filename": "Makefile", "status": "modified", "additions": 1, "deletions": 1, "changes": 2, "patch": "@@ -1,7 +1,7 @@\n .PHONY: docs\n init:\n \tpip install pipenv --upgrade\n-\tpipenv install --dev --skip-lock\n+\tpipenv install --dev\n test:\n \t# This runs all of the tests, on both Python 2 and Python 3.\n \tdetox" }, { "filename": "Pipfile", "status": "modified", "additions": 1, "deletions": 1, "changes": 2, "patch": "@@ -4,7 +4,7 @@ verify_ssl = true\n name = \"pypi\"\n \n [dev-packages]\n-pytest = \">=2.8.0\"\n+pytest = \">=2.8.0,<4.1\"\n codecov = \"*\"\n pytest-httpbin = \">=0.0.7\"\n pytest-mock = \"*\"" }, { "filename": "tests/test_requests.py", "status": "modified", "additions": 10, "deletions": 1, "changes": 11, "patch": "@@ -9,6 +9,7 @@\n import collections\n import contextlib\n import warnings\n+import re\n \n import io\n import requests\n@@ -2418,9 +2419,17 @@ class TestPreparingURLs(object):\n )\n )\n def test_preparing_url(self, url, expected):\n+\n+ def normalize_percent_encode(x):\n+ # Helper function that normalizes equivalent \n+ # percent-encoded bytes before comparisons\n+ for c in re.findall(r'%[a-fA-F0-9]{2}', x):\n+ x = x.replace(c, c.upper())\n+ return x\n+ \n r = requests.Request('GET', url=url)\n p = r.prepare()\n- assert p.url == expected\n+ assert normalize_percent_encode(p.url) == expected\n \n [USER_REDACTED].mark.parametrize(\n 'url'," } ], "reviews": [ { "id": 187704190, "user": "user_0fa58b6f3572", "state": "DISMISSED", "body": "pchars don't have case-sensitivity as the RFC describes them so I see no issue with this fix for our tests.", "submitted_at": "2018-12-24T14:36:20+00:00" }, { "id": 194610821, "user": "user_0fa58b6f3572", "state": "APPROVED", "body": null, "submitted_at": "2019-01-21T13:58:16+00:00" } ], "review_comments": [ { "id": 249458508, "user": "user_0fa58b6f3572", "body": "This is odd", "path": ".travis.yml", "line": 41, "side": "RIGHT", "created_at": "2019-01-21T13:56:36+00:00" } ], "meta": { "languages": [ "py", "yml" ], "touches_tests": true, "review_state_summary": { "DISMISSED": 1, "APPROVED": 1 }, "meaningful_comment_count": 1, "has_approval": true, "has_changes_requested": false, "total_review_comments": 1 } } { "_id": "70fc79acb3da8199", "_schema_version": "1.0", "_cleaned_at": "2026-02-12T07:46:51.490896+00:00", "repo": "psf/requests", "repo_url": "https://github.com/psf/requests", "license_name": "Apache License 2.0", "license_spdx": "Apache-2.0", "pr_number": 4835, "title": "v2.20.0", "body": "2.20.0 (2018-10-??)\n-------------------\n**Bugfixes**\n\n- Content-Type header parsing is now case-insensitive (e.g.\n charset=utf8 v Charset=utf8).\n- Fixed exception leak where certain redirect urls would raise\n uncaught urllib3 exceptions.\n- Requests removes Authorization headers from requests redirected\n from https to http on the same hostname. (CVE-2018-18074)\n- `should_bypass_proxies` now handles URIs without hostnames, e.g. files.\n\n**Dependencies**\n- We now support urllib3 v1.24.\n\n**Deprecations**\n- Requests has officially stopped support for Python 2.6.", "author": "user_dbf2a999bd6d", "created_at": "2018-10-17T15:55:17+00:00", "merged_at": "2018-10-18T15:44:50+00:00", "base_branch": "master", "head_branch": "2.20.0", "additions": 88, "deletions": 102, "changed_files": 20, "files": [ { "filename": "AUTHORS.rst", "status": "modified", "additions": 1, "deletions": 1, "changes": 2, "patch": "@@ -125,7 +125,7 @@ Patches and Suggestions\n - [NAME_REDACTED] <[EMAIL_REDACTED]> ([CONTRIBUTOR_REDACTED])\n - [NAME_REDACTED] <[EMAIL_REDACTED]> ([CONTRIBUTOR_REDACTED])\n - [NAME_REDACTED] <[EMAIL_REDACTED]> ([CONTRIBUTOR_REDACTED])\n-- [NAME_REDACTED] <[EMAIL_REDACTED]> ([CONTRIBUTOR_REDACTED])\n+- [NAME_REDACTED] <[EMAIL_REDACTED]> ([CONTRIBUTOR_REDACTED])\n - Łukasz Langa <[EMAIL_REDACTED]>\n - [NAME_REDACTED] <[EMAIL_REDACTED]>\n - [NAME_REDACTED] ([CONTRIBUTOR_REDACTED])" }, { "filename": "HISTORY.md", "status": "modified", "additions": 18, "deletions": 1, "changes": 19, "patch": "@@ -6,12 +6,29 @@ dev\n \n **Bugfixes**\n \n+- \\[Short description of non-trivial change.\\]\n+\n+2.20.0 (2018-10-18)\n+-------------------\n+\n+**Bugfixes**\n+\n - Content-Type header parsing is now case-insensitive (e.g.\n charset=utf8 v Charset=utf8).\n - Fixed exception leak where certain redirect urls would raise\n uncaught urllib3 exceptions.\n+- Requests removes Authorization header from requests redirected\n+ from https to http on the same hostname. (CVE-2018-18074)\n+- `should_bypass_proxies` now handles URIs without hostnames (e.g.\n+ files).\n \n-- \\[Short description of non-trivial change.\\]\n+**Dependencies**\n+\n+- Requests now supports urllib3 v1.24.\n+\n+**Deprecations**\n+\n+- Requests has officially stopped support for Python 2.6.\n \n 2.19.1 (2018-06-14)\n -------------------" }, { "filename": "requests/__init__.py", "status": "modified", "additions": 5, "deletions": 10, "changes": 15, "patch": "@@ -57,10 +57,10 @@ def check_compatibility(urllib3_version, chardet_version):\n # Check urllib3 for compatibility.\n major, minor, patch = urllib3_version # noqa: F811\n major, minor, patch = int(major), int(minor), int(patch)\n- # urllib3 >= 1.21.1, <= 1.23\n+ # urllib3 >= 1.21.1, <= 1.24\n assert major == 1\n assert minor >= 21\n- assert minor <= 23\n+ assert minor <= 24\n \n # Check chardet for compatibility.\n major, minor, patch = chardet_version.split('.')[:3]\n@@ -79,14 +79,14 @@ def _check_cryptography(cryptography_version):\n return\n \n if cryptography_version < [1, 3, 4]:\n- warning = 'Old version of cryptography ({0}) may cause slowdown.'.format(cryptography_version)\n+ warning = 'Old version of cryptography ({}) may cause slowdown.'.format(cryptography_version)\n warnings.warn(warning, RequestsDependencyWarning)\n \n # Check imported dependencies for compatibility.\n try:\n check_compatibility(urllib3.__version__, chardet.__version__)\n except (AssertionError, ValueError):\n- warnings.warn(\"urllib3 ({0}) or chardet ({1}) doesn't match a supported \"\n+ warnings.warn(\"urllib3 ({}) or chardet ({}) doesn't match a supported \"\n \"version!\".format(urllib3.__version__, chardet.__version__),\n RequestsDependencyWarning)\n \n@@ -123,12 +123,7 @@ def _check_cryptography(cryptography_version):\n \n # Set default logging handler to avoid \"No handler found\" warnings.\n import logging\n-try: # Python 2.7+\n- from logging import NullHandler\n-except ImportError:\n- class NullHandler(logging.Handler):\n- def emit(self, record):\n- pass\n+from logging import NullHandler\n \n logging.getLogger(__name__).addHandler(NullHandler())" }, { "filename": "requests/__version__.py", "status": "modified", "additions": 2, "deletions": 2, "changes": 4, "patch": "@@ -5,8 +5,8 @@\n __title__ = 'requests'\n __description__ = 'Python HTTP for Humans.'\n __url__ = 'http://python-requests.org'\n-__version__ = '2.19.1'\n-__build__ = 0x021901\n+__version__ = '2.20.0'\n+__build__ = 0x022000\n __author__ = '[NAME_REDACTED]'\n __author_email__ = '[EMAIL_REDACTED]'\n __license__ = 'Apache 2.0'" }, { "filename": "requests/adapters.py", "status": "modified", "additions": 7, "deletions": 9, "changes": 16, "patch": "@@ -129,8 +129,7 @@ def __init__(self, pool_connections=DEFAULT_POOLSIZE,\n self.init_poolmanager(pool_connections, pool_maxsize, block=pool_block)\n \n def __getstate__(self):\n- return dict((attr, getattr(self, attr, None)) for attr in\n- self.__attrs__)\n+ return {attr: getattr(self, attr, None) for attr in self.__attrs__}\n \n def __setstate__(self, state):\n # Can't handle by adding 'proxy_manager' to self.__attrs__ because\n@@ -226,7 +225,7 @@ def cert_verify(self, conn, url, verify, cert):\n \n if not cert_loc or not os.path.exists(cert_loc):\n raise IOError(\"Could not find a suitable TLS CA certificate bundle, \"\n- \"invalid path: {0}\".format(cert_loc))\n+ \"invalid path: {}\".format(cert_loc))\n \n conn.cert_reqs = 'CERT_REQUIRED'\n \n@@ -248,10 +247,10 @@ def cert_verify(self, conn, url, verify, cert):\n conn.key_file = None\n if conn.cert_file and not os.path.exists(conn.cert_file):\n raise IOError(\"Could not find the TLS certificate file, \"\n- \"invalid path: {0}\".format(conn.cert_file))\n+ \"invalid path: {}\".format(conn.cert_file))\n if conn.key_file and not os.path.exists(conn.key_file):\n raise IOError(\"Could not find the TLS key file, \"\n- \"invalid path: {0}\".format(conn.key_file))\n+ \"invalid path: {}\".format(conn.key_file))\n \n def build_response(self, req, resp):\n \"\"\"Builds a :class:`Response ` object from a urllib3\n@@ -426,7 +425,7 @@ def send(self, request, stream=False, timeout=None, verify=True, cert=None, prox\n timeout = TimeoutSauce(connect=connect, read=read)\n except ValueError as e:\n # this may raise a string formatting error.\n- err = (\"Invalid timeout {0}. Pass a (connect, read) \"\n+ err = (\"Invalid timeout {}. Pass a (connect, read) \"\n \"timeout tuple, or a single float to set \"\n \"both timeouts to the same value\".format(timeout))\n raise ValueError(err)\n@@ -476,11 +475,10 @@ def send(self, request, stream=False, timeout=None, verify=True, cert=None, prox\n \n # Receive the response from the server\n try:\n- # For Python 2.7+ versions, use buffering of HTTP\n- # responses\n+ # For Python 2.7, use buffering of HTTP responses\n r = low_conn.getresponse(buffering=True)\n except TypeError:\n- # For compatibility with Python 2.6 versions and back\n+ # For compatibility with Python 3.3+\n r = low_conn.getresponse()\n \n resp = HTTPResponse.from_httplib(" }, { "filename": "requests/auth.py", "status": "modified", "additions": 2, "deletions": 2, "changes": 4, "patch": "@@ -38,7 +38,7 @@ def _basic_auth_str(username, password):\n if not isinstance(username, basestring):\n warnings.warn(\n \"Non-string usernames will no longer be supported in Requests \"\n- \"3.0.0. Please convert the object you've passed in ({0!r}) to \"\n+ \"3.0.0. Please convert the object you've passed in ({!r}) to \"\n \"a string or bytes object in the near future to avoid \"\n \"problems.\".format(username),\n category=DeprecationWarning,\n@@ -48,7 +48,7 @@ def _basic_auth_str(username, password):\n if not isinstance(password, basestring):\n warnings.warn(\n \"Non-string passwords will no longer be supported in Requests \"\n- \"3.0.0. Please convert the object you've passed in ({0!r}) to \"\n+ \"3.0.0. Please convert the object you've passed in ({!r}) to \"\n \"a string or bytes object in the near future to avoid \"\n \"problems.\".format(password),\n category=DeprecationWarning," }, { "filename": "requests/compat.py", "status": "modified", "additions": 1, "deletions": 2, "changes": 3, "patch": "@@ -43,9 +43,8 @@\n import cookielib\n from Cookie import Morsel\n from StringIO import StringIO\n- from collections import Callable, Mapping, MutableMapping\n+ from collections import Callable, Mapping, MutableMapping, OrderedDict\n \n- from urllib3.packages.ordered_dict import OrderedDict\n \n builtin_str = str\n bytes = str" }, { "filename": "requests/cookies.py", "status": "modified", "additions": 15, "deletions": 14, "changes": 29, "patch": "@@ -444,20 +444,21 @@ def create_cookie(name, value, **kwargs):\n By default, the pair of `name` and `value` will be set for the domain ''\n and sent on every request (this is sometimes called a \"supercookie\").\n \"\"\"\n- result = dict(\n- version=0,\n- name=name,\n- value=value,\n- port=None,\n- domain='',\n- path='/',\n- secure=False,\n- expires=None,\n- discard=True,\n- comment=None,\n- comment_url=None,\n- rest={'HttpOnly': None},\n- rfc2109=False,)\n+ result = {\n+ 'version': 0,\n+ 'name': name,\n+ 'value': value,\n+ 'port': None,\n+ 'domain': '',\n+ 'path': '/',\n+ 'secure': False,\n+ 'expires': None,\n+ 'discard': True,\n+ 'comment': None,\n+ 'comment_url': None,\n+ 'rest': {'HttpOnly': None},\n+ 'rfc2109': False,\n+ }\n \n badargs = set(kwargs) - set(result)\n if badargs:" }, { "filename": "requests/help.py", "status": "modified", "additions": 1, "deletions": 2, "changes": 3, "patch": "@@ -89,8 +89,7 @@ def info():\n 'version': getattr(idna, '__version__', ''),\n }\n \n- # OPENSSL_VERSION_NUMBER doesn't exist in the Python 2.6 ssl module.\n- system_ssl = getattr(ssl, 'OPENSSL_VERSION_NUMBER', None)\n+ system_ssl = ssl.OPENSSL_VERSION_NUMBER\n system_ssl_info = {\n 'version': '%x' % system_ssl if system_ssl is not None else ''\n }" }, { "filename": "requests/hooks.py", "status": "modified", "additions": 2, "deletions": 2, "changes": 4, "patch": "@@ -15,14 +15,14 @@\n \n \n def default_hooks():\n- return dict((event, []) for event in HOOKS)\n+ return {event: [] for event in HOOKS}\n \n # TODO: response is the only one\n \n \n def dispatch_hook(key, hooks, hook_data, **kwargs):\n \"\"\"Dispatches a hook dictionary on a given piece of data.\"\"\"\n- hooks = hooks or dict()\n+ hooks = hooks or {}\n hooks = hooks.get(key)\n if hooks:\n if hasattr(hooks, '__call__'):" }, { "filename": "requests/models.py", "status": "modified", "additions": 1, "deletions": 4, "changes": 5, "patch": "@@ -652,10 +652,7 @@ def __getstate__(self):\n if not self._content_consumed:\n self.content\n \n- return dict(\n- (attr, getattr(self, attr, None))\n- for attr in self.__attrs__\n- )\n+ return {attr: getattr(self, attr, None) for attr in self.__attrs__}\n \n def __setstate__(self, state):\n for name, value in state.items():" }, { "filename": "requests/sessions.py", "status": "modified", "additions": 1, "deletions": 1, "changes": 2, "patch": "@@ -738,7 +738,7 @@ def mount(self, prefix, adapter):\n self.adapters[key] = self.adapters.pop(key)\n \n def __getstate__(self):\n- state = dict((attr, getattr(self, attr, None)) for attr in self.__attrs__)\n+ state = {attr: getattr(self, attr, None) for attr in self.__attrs__}\n return state\n \n def __setstate__(self, state):" }, { "filename": "requests/utils.py", "status": "modified", "additions": 3, "deletions": 8, "changes": 11, "patch": "@@ -173,7 +173,7 @@ def get_netrc_auth(url, raise_errors=False):\n \n for f in NETRC_FILES:\n try:\n- loc = os.path.expanduser('~/{0}'.format(f))\n+ loc = os.path.expanduser('~/{}'.format(f))\n except KeyError:\n # os.path.expanduser can fail when $HOME is undefined and\n # getpwuid fails. See https://bugs.python.org/issue20164 &\n@@ -729,21 +729,16 @@ def should_bypass_proxies(url, no_proxy):\n else:\n host_with_port = parsed.hostname\n if parsed.port:\n- host_with_port += ':{0}'.format(parsed.port)\n+ host_with_port += ':{}'.format(parsed.port)\n \n for host in no_proxy:\n if parsed.hostname.endswith(host) or host_with_port.endswith(host):\n # The URL does match something in no_proxy, so we don't want\n # to apply the proxies on this URL.\n return True\n \n- # If the system proxy settings indicate that this URL should be bypassed,\n- # don't proxy.\n- # The proxy_bypass function is incredibly buggy on OS X in early versions\n- # of Python 2.6, so allow this call to fail. Only catch the specific\n- # exceptions we've seen, though: this call failing in other ways can reveal\n- # legitimate problems.\n with set_environ('no_proxy', no_proxy_arg):\n+ # parsed.hostname can be `None` in cases such as a file URI.\n try:\n bypass = proxy_bypass(parsed.hostname)\n except (TypeError, socket.gaierror):" }, { "filename": "setup.py", "status": "modified", "additions": 4, "deletions": 10, "changes": 14, "patch": "@@ -39,18 +39,12 @@ def run_tests(self):\n os.system('twine upload dist/*')\n sys.exit()\n \n-# pyOpenSSL version 18.0.0 dropped support for Python 2.6\n-if sys.version_info < (2, 7):\n- PYOPENSSL_VERSION = 'pyOpenSSL >= 0.14, < 18.0.0'\n-else:\n- PYOPENSSL_VERSION = 'pyOpenSSL >= 0.14'\n-\n packages = ['requests']\n \n requires = [\n 'chardet>=3.0.2,<3.1.0',\n 'idna>=2.5,<2.8',\n- 'urllib3>=1.21.1,<1.24',\n+ 'urllib3>=1.21.1,<1.25',\n 'certifi>=2017.4.17'\n \n ]\n@@ -85,7 +79,7 @@ def run_tests(self):\n package_data={'': ['LICENSE', 'NOTICE'], 'requests': ['*.pem']},\n package_dir={'requests': 'requests'},\n include_package_data=True,\n- python_requires=\">=2.6, !=3.0.*, !=3.1.*, !=3.2.*, !=3.3.*\",\n+ python_requires=\">=2.7, !=3.0.*, !=3.1.*, !=3.2.*, !=3.3.*\",\n install_requires=requires,\n license=about['__license__'],\n zip_safe=False,\n@@ -108,8 +102,8 @@ def run_tests(self):\n cmdclass={'test': PyTest},\n tests_require=test_requirements,\n extras_require={\n- 'security': [PYOPENSSL_VERSION, 'cryptography>=1.3.4', 'idna>=2.0.0'],\n+ 'security': ['pyOpenSSL >= 0.14', 'cryptography>=1.3.4', 'idna>=2.0.0'],\n 'socks': ['PySocks>=1.5.6, !=1.5.7'],\n- 'socks:sys_platform == \"win32\" and (python_version == \"2.7\" or python_version == \"2.6\")': ['win_inet_pton'],\n+ 'socks:sys_platform == \"win32\" and python_version == \"2.7\"': ['win_inet_pton'],\n },\n )" }, { "filename": "tests/test_help.py", "status": "modified", "additions": 0, "deletions": 9, "changes": 9, "patch": "@@ -7,15 +7,6 @@\n from requests.help import info\n \n \n-[USER_REDACTED].mark.skipif(sys.version_info[:2] != (2,6), reason=\"Only run on Python 2.6\")\n-def test_system_ssl_py26():\n- \"\"\"OPENSSL_VERSION_NUMBER isn't provided in Python 2.6, verify we don't\n- blow up in this case.\n- \"\"\"\n- assert info()['system_ssl'] == {'version': ''}\n-\n-\n-[USER_REDACTED].mark.skipif(sys.version_info < (2,7), reason=\"Only run on Python 2.7+\")\n def test_system_ssl():\n \"\"\"Verify we're actually setting system_ssl when it should be available.\"\"\"\n assert info()['system_ssl']['version'] != ''" }, { "filename": "tests/test_lowlevel.py", "status": "modified", "additions": 14, "deletions": 14, "changes": 28, "patch": "@@ -16,7 +16,7 @@ def test_chunked_upload():\n data = iter([b'a', b'b', b'c'])\n \n with server as (host, port):\n- url = 'http://{0}:{1}/'.format(host, port)\n+ url = 'http://{}:{}/'.format(host, port)\n r = requests.post(url, data=data, stream=True)\n close_server.set() # release server block\n \n@@ -77,7 +77,7 @@ def digest_response_handler(sock):\n server = Server(digest_response_handler, wait_to_close_event=close_server)\n \n with server as (host, port):\n- url = 'http://{0}:{1}/'.format(host, port)\n+ url = 'http://{}:{}/'.format(host, port)\n r = requests.get(url, auth=auth)\n # Verify server succeeded in authenticating.\n assert r.status_code == 200\n@@ -127,7 +127,7 @@ def digest_failed_response_handler(sock):\n server = Server(digest_failed_response_handler, wait_to_close_event=close_server)\n \n with server as (host, port):\n- url = 'http://{0}:{1}/'.format(host, port)\n+ url = 'http://{}:{}/'.format(host, port)\n r = requests.get(url, auth=auth)\n # Verify server didn't authenticate us.\n assert r.status_code == 401\n@@ -164,7 +164,7 @@ def digest_response_handler(sock):\n server = Server(digest_response_handler, wait_to_close_event=close_server)\n \n with server as (host, port):\n- url = 'http://{0}:{1}/'.format(host, port)\n+ url = 'http://{}:{}/'.format(host, port)\n r = requests.get(url, auth=auth)\n # Verify server didn't receive auth from us.\n assert r.status_code == 200\n@@ -181,17 +181,17 @@ def digest_response_handler(sock):\n _proxy_combos = []\n for prefix, schemes in _schemes_by_var_prefix:\n for scheme in schemes:\n- _proxy_combos.append((\"{0}_proxy\".format(prefix), scheme))\n+ _proxy_combos.append((\"{}_proxy\".format(prefix), scheme))\n \n _proxy_combos += [(var.upper(), scheme) for var, scheme in _proxy_combos]\n \n \n [USER_REDACTED].mark.parametrize(\"var,scheme\", _proxy_combos)\n def test_use_proxy_from_environment(httpbin, var, scheme):\n- url = \"{0}://httpbin.org\".format(scheme)\n+ url = \"{}://httpbin.org\".format(scheme)\n fake_proxy = Server() # do nothing with the requests; just close the socket\n with fake_proxy as (host, port):\n- proxy_url = \"socks5://{0}:{1}\".format(host, port)\n+ proxy_url = \"socks5://{}:{}\".format(host, port)\n kwargs = {var: proxy_url}\n with override_environ(**kwargs):\n # fake proxy's lack of response will cause a ConnectionError\n@@ -212,7 +212,7 @@ def test_redirect_rfc1808_to_non_ascii_location():\n \n def redirect_resp_handler(sock):\n consume_socket_content(sock, timeout=0.5)\n- location = u'//{0}:{1}/{2}'.format(host, port, path)\n+ location = u'//{}:{}/{}'.format(host, port, path)\n sock.send(\n b'HTTP/1.1 301 Moved Permanently\\r\\n'\n b'Content-Length: 0\\r\\n'\n@@ -226,13 +226,13 @@ def redirect_resp_handler(sock):\n server = Server(redirect_resp_handler, wait_to_close_event=close_server)\n \n with server as (host, port):\n- url = u'http://{0}:{1}'.format(host, port)\n+ url = u'http://{}:{}'.format(host, port)\n r = requests.get(url=url, allow_redirects=True)\n assert r.status_code == 200\n assert len(r.history) == 1\n assert r.history[0].status_code == 301\n assert redirect_request[0].startswith(b'GET /' + expected_path + b' HTTP/1.1')\n- assert r.url == u'{0}/{1}'.format(url, expected_path.decode('ascii'))\n+ assert r.url == u'{}/{}'.format(url, expected_path.decode('ascii'))\n \n close_server.set()\n \n@@ -250,7 +250,7 @@ def response_handler(sock):\n server = Server(response_handler, wait_to_close_event=close_server)\n \n with server as (host, port):\n- url = 'http://{0}:{1}/path/to/thing/#view=edit&token=hunter2'.format(host, port)\n+ url = 'http://{}:{}/path/to/thing/#view=edit&token=hunter2'.format(host, port)\n r = requests.get(url)\n raw_request = r.content\n \n@@ -293,7 +293,7 @@ def response_handler(sock):\n server = Server(response_handler, wait_to_close_event=close_server)\n \n with server as (host, port):\n- url = 'http://{0}:{1}/path/to/thing/#view=edit&token=hunter2'.format(host, port)\n+ url = 'http://{}:{}/path/to/thing/#view=edit&token=hunter2'.format(host, port)\n r = requests.get(url)\n raw_request = r.content\n \n@@ -302,8 +302,8 @@ def response_handler(sock):\n assert r.history[0].request.url == url\n \n # Verify we haven't overwritten the location with our previous fragment.\n- assert r.history[1].request.url == 'http://{0}:{1}/get#relevant-section'.format(host, port)\n+ assert r.history[1].request.url == 'http://{}:{}/get#relevant-section'.format(host, port)\n # Verify previous fragment is used and not the original.\n- assert r.url == 'http://{0}:{1}/final-url/#relevant-section'.format(host, port)\n+ assert r.url == 'http://{}:{}/final-url/#relevant-section'.format(host, port)\n \n close_server.set()" }, { "filename": "tests/test_requests.py", "status": "modified", "additions": 6, "deletions": 6, "changes": 12, "patch": "@@ -158,7 +158,7 @@ def test_mixed_case_scheme_acceptable(self, httpbin, scheme):\n url = scheme + parts.netloc + parts.path\n r = requests.Request('GET', url)\n r = s.send(r.prepare())\n- assert r.status_code == 200, 'failed for scheme {0}'.format(scheme)\n+ assert r.status_code == 200, 'failed for scheme {}'.format(scheme)\n \n def test_HTTP_200_OK_GET_ALTERNATIVE(self, httpbin):\n r = requests.Request('GET', httpbin('get'))\n@@ -816,17 +816,17 @@ def test_invalid_ca_certificate_path(self, httpbin_secure):\n INVALID_PATH = '/garbage'\n with pytest.raises(IOError) as e:\n requests.get(httpbin_secure(), verify=INVALID_PATH)\n- assert str(e.value) == 'Could not find a suitable TLS CA certificate bundle, invalid path: {0}'.format(INVALID_PATH)\n+ assert str(e.value) == 'Could not find a suitable TLS CA certificate bundle, invalid path: {}'.format(INVALID_PATH)\n \n def test_invalid_ssl_certificate_files(self, httpbin_secure):\n INVALID_PATH = '/garbage'\n with pytest.raises(IOError) as e:\n requests.get(httpbin_secure(), cert=INVALID_PATH)\n- assert str(e.value) == 'Could not find the TLS certificate file, invalid path: {0}'.format(INVALID_PATH)\n+ assert str(e.value) == 'Could not find the TLS certificate file, invalid path: {}'.format(INVALID_PATH)\n \n with pytest.raises(IOError) as e:\n requests.get(httpbin_secure(), cert=('.', INVALID_PATH))\n- assert str(e.value) == 'Could not find the TLS key file, invalid path: {0}'.format(INVALID_PATH)\n+ assert str(e.value) == 'Could not find the TLS key file, invalid path: {}'.format(INVALID_PATH)\n \n def test_http_with_certificate(self, httpbin):\n r = requests.get(httpbin(), cert='.')\n@@ -864,7 +864,7 @@ def test_certificate_failure(self, httpbin_secure):\n \n def test_urlencoded_get_query_multivalued_param(self, httpbin):\n \n- r = requests.get(httpbin('get'), params=dict(test=['foo', 'baz']))\n+ r = requests.get(httpbin('get'), params={'test': ['foo', 'baz']})\n assert r.status_code == 200\n assert r.url == httpbin('get?test=foo&test=baz')\n \n@@ -1458,7 +1458,7 @@ def test_params_are_merged_case_sensitive(self, httpbin):\n assert r.json()['args'] == {'foo': 'bar', 'FOO': 'bar'}\n \n def test_long_authinfo_in_url(self):\n- url = 'http://{0}:{1}@{2}:9000/path?query#frag'.format(\n+ url = 'http://{}:{}@{}:9000/path?query#frag'.format(\n 'E8A3BE87-9E3F-4620-8858-95478E385B5B',\n 'EA770032-DA4D-4D84-8CE9-29C6D910BF1E',\n 'exactly-------------sixty-----------three------------characters'," }, { "filename": "tests/test_testserver.py", "status": "modified", "additions": 3, "deletions": 3, "changes": 6, "patch": "@@ -50,7 +50,7 @@ def test_text_response(self):\n )\n \n with server as (host, port):\n- r = requests.get('http://{0}:{1}'.format(host, port))\n+ r = requests.get('http://{}:{}'.format(host, port))\n \n assert r.status_code == 200\n assert r.text == u'roflol'\n@@ -59,7 +59,7 @@ def test_text_response(self):\n def test_basic_response(self):\n \"\"\"the basic response server returns an empty http response\"\"\"\n with Server.basic_response_server() as (host, port):\n- r = requests.get('http://{0}:{1}'.format(host, port))\n+ r = requests.get('http://{}:{}'.format(host, port))\n assert r.status_code == 200\n assert r.text == u''\n assert r.headers['Content-Length'] == '0'\n@@ -83,7 +83,7 @@ def test_multiple_requests(self):\n server = Server.basic_response_server(requests_to_handle=requests_to_handle)\n \n with server as (host, port):\n- server_url = 'http://{0}:{1}'.format(host, port)\n+ server_url = 'http://{}:{}'.format(host, port)\n for _ in range(requests_to_handle):\n r = requests.get(server_url)\n assert r.status_code == 200" }, { "filename": "tests/test_utils.py", "status": "modified", "additions": 1, "deletions": 1, "changes": 2, "patch": "@@ -665,7 +665,7 @@ def test_add_dict_to_cookiejar(cookiejar):\n cookiedict = {'test': 'cookies',\n 'good': 'cookies'}\n cj = add_dict_to_cookiejar(cookiejar, cookiedict)\n- cookies = dict((cookie.name, cookie.value) for cookie in cj)\n+ cookies = {cookie.name: cookie.value for cookie in cj}\n assert cookiedict == cookies" }, { "filename": "tox.ini", "status": "modified", "additions": 1, "deletions": 1, "changes": 2, "patch": "@@ -1,5 +1,5 @@\n [tox]\n-envlist = py26,py27,py34,py35,py36\n+envlist = py27,py34,py35,py36\n \n [testenv]" } ], "reviews": [ { "id": 165709363, "user": "user_dbf2a999bd6d", "state": "COMMENTED", "body": null, "submitted_at": "2018-10-17T15:56:29+00:00" }, { "id": 165739089, "user": "user_b08fb5f52ea1", "state": "DISMISSED", "body": null, "submitted_at": "2018-10-17T17:04:04+00:00" } ], "review_comments": [ { "id": 225992828, "user": "user_dbf2a999bd6d", "body": "We'll need to update the date here before merging.", "path": "HISTORY.md", "line": null, "side": "RIGHT", "created_at": "2018-10-17T15:56:29+00:00" } ], "meta": { "languages": [ "ini", "md", "py", "rst" ], "touches_tests": true, "review_state_summary": { "COMMENTED": 1, "DISMISSED": 1 }, "meaningful_comment_count": 1, "has_approval": false, "has_changes_requested": false, "total_review_comments": 1 } } { "_id": "46982b049c80f2a2", "_schema_version": "1.0", "_cleaned_at": "2026-02-12T07:46:51.502128+00:00", "repo": "psf/requests", "repo_url": "https://github.com/psf/requests", "license_name": "Apache License 2.0", "license_spdx": "Apache-2.0", "pr_number": 4805, "title": "Prefer https:// for URLs throughout project", "body": null, "author": "user_278727a2e287", "created_at": "2018-09-23T20:56:44+00:00", "merged_at": "2018-10-01T00:27:24+00:00", "base_branch": "master", "head_branch": "https", "additions": 90, "deletions": 90, "changed_files": 20, "files": [ { "filename": "HISTORY.md", "status": "modified", "additions": 1, "deletions": 1, "changes": 2, "patch": "@@ -646,7 +646,7 @@ documentation](http://docs.python-requests.org/en/latest/community/release-proce\n **Bugfixes**\n \n - Revert changes to our vendored certificate bundle. For more context\n- see (\\#2455, \\#2456, and )\n+ see (\\#2455, \\#2456, and )\n \n 2.5.2 (2015-02-23)\n ------------------" }, { "filename": "LICENSE", "status": "modified", "additions": 1, "deletions": 1, "changes": 2, "patch": "@@ -4,7 +4,7 @@ Copyright 2018 [NAME_REDACTED] not use this file except in compliance with the License.\n You may obtain a copy of the License at\n \n- http://www.apache.org/licenses/LICENSE-2.0\n+ https://www.apache.org/licenses/LICENSE-2.0\n \n Unless required by [NAME_REDACTED] to in writing, software\n distributed under the License is distributed on an \"AS IS\" BASIS," }, { "filename": "_appveyor/install.ps1", "status": "modified", "additions": 1, "deletions": 1, "changes": 2, "patch": "@@ -226,4 +226,4 @@ function main () {\n InstallPip $env:PYTHON\n }\n \n-main\n\\ No newline at end of file\n+main" }, { "filename": "appveyor.yml", "status": "modified", "additions": 2, "deletions": 2, "changes": 4, "patch": "@@ -1,5 +1,5 @@\n # AppVeyor.yml from https://github.com/ogrisel/python-appveyor-demo\n-# License: CC0 1.0 Universal: http://creativecommons.org/publicdomain/zero/1.0/\n+# License: CC0 1.0 Universal: https://creativecommons.org/publicdomain/zero/1.0/\n \n build: off\n \n@@ -31,7 +31,7 @@ environment:\n TOXENV: \"py37\"\n \n install:\n- # [NAME_REDACTED] (from the official .msi of http://python.org) and pip when\n+ # [NAME_REDACTED] (from the official .msi of https://www.python.org/) and pip when\n # not already installed.\n - ps: if (-not(Test-Path($env:PYTHON))) { & _appveyor\\install.ps1 }" }, { "filename": "docs/_templates/sidebarintro.html", "status": "modified", "additions": 6, "deletions": 6, "changes": 12, "patch": "@@ -25,17 +25,17 @@

[NAME_REDACTED]

\n allowtransparency=\"true\" frameborder=\"0\" scrolling=\"0\" width=\"200\" height=\"20\">

\n \n

Follow [USER_REDACTED]

\n-

[NAME_REDACTED].

\n+

[NAME_REDACTED].

\n

[NAME_REDACTED]

\n \n-

More [NAME_REDACTED] projects:

\n+

More [NAME_REDACTED] projects:

\n
    \n-
  • Requests-HTML
  • \n+
  • Requests-HTML
  • \n
  • howtopython.org
  • \n
  • pipenv
  • \n-
  • pep8.org
  • \n-
  • httpbin.org
  • \n-
  • The Python Guide
  • \n+
  • pep8.org
  • \n+
  • httpbin.org
  • \n+
  • The Python Guide
  • \n
  • Maya: Datetimes for Humans
  • \n
  • Records: SQL for Humans
  • \n
  • Legit: Git for Humans
  • " }, { "filename": "docs/_templates/sidebarlogo.html", "status": "modified", "additions": 6, "deletions": 6, "changes": 12, "patch": "@@ -20,7 +20,7 @@\n

    [NAME_REDACTED]

    \n

    Receive updates on new releases and upcoming projects.

    \n \n-

    [NAME_REDACTED].

    \n+

    [NAME_REDACTED].

    \n \n
    \n \n@@ -34,14 +34,14 @@

    [NAME_REDACTED]

    \n \n

    [NAME_REDACTED]

    \n \n-

    More [NAME_REDACTED] projects:

    \n+

    More [NAME_REDACTED] projects:

    \n
      \n-
    • Requests-HTML
    • \n+
    • Requests-HTML
    • \n
    • howtopython.org
    • \n
    • pipenv
    • \n-
    • pep8.org
    • \n-
    • httpbin.org
    • \n-
    • The Python Guide
    • \n+
    • pep8.org
    • \n+
    • httpbin.org
    • \n+
    • The Python Guide
    • \n
    • Maya: Datetimes for Humans
    • \n
    • Records: SQL for Humans
    • \n
    • Legit: Git for Humans
    • " }, { "filename": "docs/api.rst", "status": "modified", "additions": 5, "deletions": 5, "changes": 10, "patch": "@@ -139,7 +139,7 @@ API Changes\n s = requests.Session() # formerly, session took parameters\n s.auth = auth\n s.headers.update(headers)\n- r = s.get('http://httpbin.org/headers')\n+ r = s.get('https://httpbin.org/headers')\n \n * All request hooks have been removed except 'response'.\n \n@@ -185,7 +185,7 @@ API Changes\n requests_log.setLevel(logging.DEBUG)\n requests_log.propagate = True\n \n- requests.get('http://httpbin.org/headers')\n+ requests.get('https://httpbin.org/headers')\n \n \n \n@@ -197,8 +197,8 @@ license from the ISC_ license to the `Apache 2.0`_ license. The Apache 2.0\n license ensures that contributions to Requests are also covered by [NAME_REDACTED]\n 2.0 license.\n \n-.. _ISC: http://opensource.org/licenses/ISC\n-.. _Apache 2.0: http://opensource.org/licenses/Apache-2.0\n+.. _ISC: https://opensource.org/licenses/ISC\n+.. _Apache 2.0: https://opensource.org/licenses/Apache-2.0\n \n \n Migrating to 2.x\n@@ -213,7 +213,7 @@ For more details on the changes in this release including new APIs, links\n to the relevant GitHub issues and some of the bug fixes, read Cory's blog_\n on the subject.\n \n-.. _blog: http://lukasa.co.uk/2013/09/Requests_20/\n+.. _blog: https://lukasa.co.uk/2013/09/Requests_20/\n \n \n API Changes" }, { "filename": "docs/community/out-there.rst", "status": "modified", "additions": 5, "deletions": 5, "changes": 10, "patch": "@@ -15,10 +15,10 @@ To give it a try, simply::\n \n Articles & Talks\n ================\n-- `Python for the Web `_ teaches how to use Python to interact with the web, using Requests.\n-- `[NAME_REDACTED] of Requests `_\n-- `My 'Python for Humans' talk `_ ( `audio `_ )\n+- `Python for the Web `_ teaches how to use Python to interact with the web, using Requests.\n+- `[NAME_REDACTED] of Requests `_\n+- `My 'Python for Humans' talk `_ ( `audio `_ )\n - `[NAME_REDACTED] '[NAME_REDACTED] APIs' talk `_\n-- `Blog post about Requests via Yum `_\n-- `Russian blog post introducing Requests `_\n+- `Blog post about Requests via Yum `_\n+- `Russian blog post introducing Requests `_\n - `Sending JSON in Requests `_" }, { "filename": "docs/dev/contributing.rst", "status": "modified", "additions": 1, "deletions": 1, "changes": 2, "patch": "@@ -157,7 +157,7 @@ model methods (e.g. ``__repr__``) are typically the exception to this rule.\n \n Thanks for helping to make the world a better place!\n \n-.. _PEP 8: http://pep8.org\n+.. _PEP 8: https://pep8.org/\n .. _line continuations: https://www.python.org/dev/peps/pep-0008/#indentation\n \n Documentation Contributions" }, { "filename": "docs/dev/philosophy.rst", "status": "modified", "additions": 2, "deletions": 2, "changes": 4, "patch": "@@ -9,7 +9,7 @@ Requests is an open but opinionated library, created by [NAME_REDACTED]\n [NAME_REDACTED]\n ~~~~~~~~~~~~~~~~\n \n-`[NAME_REDACTED] `_ is the BDFL. He has final say in any decision related to the Requests project. Kenneth is responsible for the direction and form of the library, as well as its presentation. In addition to making decisions based on technical merit, he is responsible for making decisions based on the development philosophy of Requests.\n+`[NAME_REDACTED] `_ is the BDFL. He has final say in any decision related to the Requests project. Kenneth is responsible for the direction and form of the library, as well as its presentation. In addition to making decisions based on technical merit, he is responsible for making decisions based on the development philosophy of Requests.\n \n `[NAME_REDACTED] `_ and `[NAME_REDACTED] `_ are the core contributors. They are responsible for triaging bug reports, reviewing pull requests and ensuring that Kenneth is kept up to speed with developments around the library. The day-to-day managing of the project is done by [NAME_REDACTED] are responsible for making judgements about whether or not a feature request is likely to be accepted by Kenneth. Their word is, in some ways, more final than Kenneth's.\n \n@@ -26,7 +26,7 @@ [NAME_REDACTED] many years, the open source community has been plagued with version number dystonia. Numbers vary so greatly from project to project, they are practically meaningless.\n \n-Requests uses `[NAME_REDACTED] `_. This specification seeks to put an end to this madness with a small set of practical guidelines for you and your colleagues to use in your next project.\n+Requests uses `[NAME_REDACTED] `_. This specification seeks to put an end to this madness with a small set of practical guidelines for you and your colleagues to use in your next project.\n \n [NAME_REDACTED]?\n ~~~~~~~~~~~~~~~~~" }, { "filename": "docs/user/advanced.rst", "status": "modified", "additions": 21, "deletions": 21, "changes": 42, "patch": "@@ -25,8 +25,8 @@ Let's persist some cookies across requests::\n \n s = requests.Session()\n \n- s.get('http://httpbin.org/cookies/set/sessioncookie/123456789')\n- r = s.get('http://httpbin.org/cookies')\n+ s.get('https://httpbin.org/cookies/set/sessioncookie/123456789')\n+ r = s.get('https://httpbin.org/cookies')\n \n print(r.text)\n # '{\"cookies\": {\"sessioncookie\": \"123456789\"}}'\n@@ -40,7 +40,7 @@ is done by [NAME_REDACTED] properties on a Session object::\n s.headers.update({'x-test': 'true'})\n \n # both 'x-test' and 'x-test2' are sent\n- s.get('http://httpbin.org/headers', headers={'x-test2': 'true'})\n+ s.get('https://httpbin.org/headers', headers={'x-test2': 'true'})\n \n \n Any dictionaries that you pass to a request method will be merged with the\n@@ -53,11 +53,11 @@ with the first request, but not the second::\n \n s = requests.Session()\n \n- r = s.get('http://httpbin.org/cookies', cookies={'from-my': 'browser'})\n+ r = s.get('https://httpbin.org/cookies', cookies={'from-my': 'browser'})\n print(r.text)\n # '{\"cookies\": {\"from-my\": \"browser\"}}'\n \n- r = s.get('http://httpbin.org/cookies')\n+ r = s.get('https://httpbin.org/cookies')\n print(r.text)\n # '{\"cookies\": {}}'\n \n@@ -69,7 +69,7 @@ If you want to manually add cookies to your session, use the\n Sessions can also be used as context managers::\n \n with requests.Session() as s:\n- s.get('http://httpbin.org/cookies/set/sessioncookie/123456789')\n+ s.get('https://httpbin.org/cookies/set/sessioncookie/123456789')\n \n This will make sure the session is closed as soon as the ``with`` block is\n exited, even if unhandled exceptions occurred.\n@@ -97,7 +97,7 @@ The ``Response`` object contains all of the information returned by [NAME_REDACTED] a\n also contains the ``Request`` object you created originally. Here is a simple\n request to get some very important information from Wikipedia's servers::\n \n- >>> r = requests.get('http://en.wikipedia.org/wiki/Monty_Python')\n+ >>> r = requests.get('https://en.wikipedia.org/wiki/Monty_Python')\n \n If we want to access the headers the server sent back to us, we do this::\n \n@@ -323,7 +323,7 @@ inefficiency with connections. If you find yourself partially reading request\n bodies (or not reading them at all) while using ``stream=True``, you should\n make the request within a ``with`` statement to ensure it's always closed::\n \n- with requests.get('http://httpbin.org/get', stream=True) as r:\n+ with requests.get('https://httpbin.org/get', stream=True) as r:\n # Do things with the response here.\n \n .. _keep-alive:\n@@ -393,7 +393,7 @@ upload image files to an HTML form with a multiple file field 'images'::\n \n To do that, just set files to a list of tuples of ``(form_field_name, file_info)``::\n \n- >>> url = 'http://httpbin.org/post'\n+ >>> url = 'https://httpbin.org/post'\n >>> multiple_files = [\n ('images', ('foo.png', open('foo.png', 'rb'), 'image/png')),\n ('images', ('bar.png', open('bar.png', 'rb'), 'image/png'))]\n@@ -455,13 +455,13 @@ anything, nothing else is affected.\n \n Let's print some request method arguments at runtime::\n \n- >>> requests.get('http://httpbin.org', hooks={'response': print_url})\n- http://httpbin.org\n+ >>> requests.get('https://httpbin.org/', hooks={'response': print_url})\n+ https://httpbin.org/\n \n \n You can add multiple hooks to a single request. Let's call two hooks at once::\n \n- >>> r = requests.get('http://httpbin.org', hooks={'response': [print_url, record_hook]})\n+ >>> r = requests.get('https://httpbin.org/', hooks={'response': [print_url, record_hook]})\n >>> r.hook_called\n True\n \n@@ -470,8 +470,8 @@ be called on every request made to the session. For example::\n \n >>> s = requests.Session()\n >>> s.hooks['response'].append(print_url)\n- >>> s.get('http://httpbin.org')\n- http://httpbin.org\n+ >>> s.get('https://httpbin.org/')\n+ https://httpbin.org/\n \n \n A ``Session`` can have multiple hooks, which will be called in the order\n@@ -529,7 +529,7 @@ set ``stream`` to ``True`` and iterate over the response with\n import json\n import requests\n \n- r = requests.get('http://httpbin.org/stream/20', stream=True)\n+ r = requests.get('https://httpbin.org/stream/20', stream=True)\n \n for line in r.iter_lines():\n \n@@ -543,7 +543,7 @@ When using `decode_unicode=True` with\n :meth:`Response.iter_content() `, you'll want\n to provide a fallback encoding in the event the server doesn't provide one::\n \n- r = requests.get('http://httpbin.org/stream/20', stream=True)\n+ r = requests.get('https://httpbin.org/stream/20', stream=True)\n \n if r.encoding is None:\n r.encoding = 'utf-8'\n@@ -657,7 +657,7 @@ encoding in the HTTP header, and if none is present, will use `chardet\n The only time Requests will not do this is if no explicit charset\n is present in the HTTP headers **and** the ``Content-Type``\n header contains ``text``. In this situation, `RFC 2616\n-`_ specifies\n+`_ specifies\n that the default charset must be ``ISO-8859-1``. Requests follows the\n specification in this case. If you require a different encoding, you can\n manually set the :attr:`Response.encoding `\n@@ -921,7 +921,7 @@ it should apply to.\n ::\n \n >>> s = requests.Session()\n- >>> s.mount('http://www.github.com', MyAdapter())\n+ >>> s.mount('https://github.com/', MyAdapter())\n \n The mount call registers a specific instance of a [NAME_REDACTED] to a\n prefix. Once mounted, any HTTP request made using that session whose URL starts\n@@ -959,7 +959,7 @@ library to use SSLv3::\n num_pools=connections, maxsize=maxsize,\n block=block, ssl_version=ssl.PROTOCOL_SSLv3)\n \n-.. _`described here`: http://www.kennethreitz.org/essays/the-future-of-python-http\n+.. _`described here`: https://www.kennethreitz.org/essays/the-future-of-python-http\n .. _`urllib3`: https://github.com/shazow/urllib3\n \n .. _blocking-or-nonblocking:\n@@ -1003,7 +1003,7 @@ The **connect** timeout is the number of seconds Requests will wait for your\n client to establish a connection to a remote machine (corresponding to the\n `connect()`_) call on the socket. It's a good practice to set connect timeouts\n to slightly larger than a multiple of 3, which is the default `TCP packet\n-retransmission window `_.\n+retransmission window `_.\n \n Once your client has connected to the server and sent the HTTP request, the\n **read** timeout is the number of seconds the client will wait for the server\n@@ -1028,4 +1028,4 @@ coffee.\n \n r = requests.get('https://github.com', timeout=None)\n \n-.. _`connect()`: http://linux.die.net/man/2/connect\n+.. _`connect()`: https://linux.die.net/man/2/connect" }, { "filename": "docs/user/authentication.rst", "status": "modified", "additions": 3, "deletions": 3, "changes": 6, "patch": "@@ -53,7 +53,7 @@ Another very popular form of HTTP Authentication is [NAME_REDACTED],\n and Requests supports this out of the box as well::\n \n >>> from requests.auth import HTTPDigestAuth\n- >>> url = 'http://httpbin.org/digest-auth/auth/user/pass'\n+ >>> url = 'https://httpbin.org/digest-auth/auth/user/pass'\n >>> requests.get(url, auth=HTTPDigestAuth('user', 'pass'))\n \n \n@@ -122,7 +122,7 @@ To do so, subclass :class:`AuthBase ` and implement the\n ... # Implement my authentication\n ... return r\n ...\n- >>> url = 'http://httpbin.org/get'\n+ >>> url = 'https://httpbin.org/get'\n >>> requests.get(url, auth=MyAuth())\n \n \n@@ -134,7 +134,7 @@ authentication will additionally add hooks to provide further functionality.\n Further examples can be found under the `Requests organization`_ and in the\n ``auth.py`` file.\n \n-.. _OAuth: http://oauth.net/\n+.. _OAuth: https://oauth.net/\n .. _requests_oauthlib: https://github.com/requests/requests-oauthlib\n .. _requests-oauthlib OAuth2 documentation: https://requests-oauthlib.readthedocs.io/en/latest/oauth2_workflow.html\n .. _Web [NAME_REDACTED]: https://requests-oauthlib.readthedocs.io/en/latest/oauth2_workflow.html#web-application-flow" }, { "filename": "docs/user/install.rst", "status": "modified", "additions": 1, "deletions": 1, "changes": 2, "patch": "@@ -18,7 +18,7 @@ To install Requests, simply run this simple command in your terminal of choice::\n $ pipenv install requests\n \n If you don't have `pipenv `_ installed (tisk tisk!), head over to the Pipenv website for installation instructions. Or, if you prefer to just use pip and don't have it installed,\n-`this Python installation guide `_\n+`this Python installation guide `_\n can guide you through the process.\n \n Get the [NAME_REDACTED]" }, { "filename": "docs/user/intro.rst", "status": "modified", "additions": 2, "deletions": 2, "changes": 4, "patch": "@@ -37,8 +37,8 @@ closed-source software.\n \n Requests is released under terms of `Apache2 License`_.\n \n-.. _`GPL Licensed`: http://www.opensource.org/licenses/gpl-license.php\n-.. _`Apache2 License`: http://opensource.org/licenses/Apache-2.0\n+.. _`GPL Licensed`: https://opensource.org/licenses/gpl-license.php\n+.. _`Apache2 License`: https://opensource.org/licenses/Apache-2.0\n \n \n [NAME_REDACTED]" }, { "filename": "docs/user/quickstart.rst", "status": "modified", "additions": 25, "deletions": 25, "changes": 50, "patch": "@@ -39,15 +39,15 @@ get all the information we need from this object.\n Requests' simple API means that all forms of HTTP request are as obvious. For\n example, this is how you make an HTTP POST request::\n \n- >>> r = requests.post('http://httpbin.org/post', data = {'key':'value'})\n+ >>> r = requests.post('https://httpbin.org/post', data = {'key':'value'})\n \n Nice, right? What about the other HTTP request types: PUT, DELETE, HEAD and\n OPTIONS? These are all just as simple::\n \n- >>> r = requests.put('http://httpbin.org/put', data = {'key':'value'})\n- >>> r = requests.delete('http://httpbin.org/delete')\n- >>> r = requests.head('http://httpbin.org/get')\n- >>> r = requests.options('http://httpbin.org/get')\n+ >>> r = requests.put('https://httpbin.org/put', data = {'key':'value'})\n+ >>> r = requests.delete('https://httpbin.org/delete')\n+ >>> r = requests.head('https://httpbin.org/get')\n+ >>> r = requests.options('https://httpbin.org/get')\n \n That's all well and good, but it's also only the start of what Requests can\n do.\n@@ -65,12 +65,12 @@ using the ``params`` keyword argument. As an example, if you wanted to pass\n following code::\n \n >>> payload = {'key1': 'value1', 'key2': 'value2'}\n- >>> r = requests.get('http://httpbin.org/get', params=payload)\n+ >>> r = requests.get('https://httpbin.org/get', params=payload)\n \n You can see that the URL has been correctly encoded by [NAME_REDACTED]::\n \n >>> print(r.url)\n- http://httpbin.org/get?key2=value2&key1=value1\n+ https://httpbin.org/get?key2=value2&key1=value1\n \n Note that any dictionary key whose value is ``None`` will not be added to the\n URL's query string.\n@@ -79,9 +79,9 @@ You can also pass a list of items as a value::\n \n >>> payload = {'key1': 'value1', 'key2': ['value2', 'value3']}\n \n- >>> r = requests.get('http://httpbin.org/get', params=payload)\n+ >>> r = requests.get('https://httpbin.org/get', params=payload)\n >>> print(r.url)\n- http://httpbin.org/get?key1=value1&key2=value2&key2=value3\n+ https://httpbin.org/get?key1=value1&key2=value2&key2=value3\n \n [NAME_REDACTED]\n ----------------\n@@ -233,7 +233,7 @@ dictionary of data will automatically be form-encoded when the request is made::\n \n >>> payload = {'key1': 'value1', 'key2': 'value2'}\n \n- >>> r = requests.post(\"http://httpbin.org/post\", data=payload)\n+ >>> r = requests.post(\"https://httpbin.org/post\", data=payload)\n >>> print(r.text)\n {\n ...\n@@ -250,9 +250,9 @@ as values. This is particularly useful when the form has multiple elements that\n use the same key::\n \n >>> payload_tuples = [('key1', 'value1'), ('key1', 'value2')]\n- >>> r1 = requests.post('http://httpbin.org/post', data=payload_tuples)\n+ >>> r1 = requests.post('https://httpbin.org/post', data=payload_tuples)\n >>> payload_dict = {'key1': ['value1', 'value2']}\n- >>> r2 = requests.post('http://httpbin.org/post', data=payload_dict)\n+ >>> r2 = requests.post('https://httpbin.org/post', data=payload_dict)\n >>> print(r1.text)\n {\n ...\n@@ -296,7 +296,7 @@ POST a [NAME_REDACTED] makes it simple to upload Multipart-encoded files::\n \n- >>> url = 'http://httpbin.org/post'\n+ >>> url = 'https://httpbin.org/post'\n >>> files = {'file': open('report.xls', 'rb')}\n \n >>> r = requests.post(url, files=files)\n@@ -311,7 +311,7 @@ Requests makes it simple to upload Multipart-encoded files::\n \n You can set the filename, content_type and headers explicitly::\n \n- >>> url = 'http://httpbin.org/post'\n+ >>> url = 'https://httpbin.org/post'\n >>> files = {'file': ('report.xls', open('report.xls', 'rb'), 'application/vnd.ms-excel', {'Expires': '0'})}\n \n >>> r = requests.post(url, files=files)\n@@ -326,7 +326,7 @@ You can set the filename, content_type and headers explicitly::\n \n If you want, you can send strings to be received as files::\n \n- >>> url = 'http://httpbin.org/post'\n+ >>> url = 'https://httpbin.org/post'\n >>> files = {'file': ('report.csv', 'some,data,to,send\\nanother,row,to,send\\n')}\n \n >>> r = requests.post(url, files=files)\n@@ -360,7 +360,7 @@ [NAME_REDACTED]\n \n We can check the response status code::\n \n- >>> r = requests.get('http://httpbin.org/get')\n+ >>> r = requests.get('https://httpbin.org/get')\n >>> r.status_code\n 200\n \n@@ -374,7 +374,7 @@ If we made a bad request (a 4XX client error or 5XX server error response), we\n can raise it with\n :meth:`Response.raise_for_status() `::\n \n- >>> bad_r = requests.get('http://httpbin.org/status/404')\n+ >>> bad_r = requests.get('https://httpbin.org/status/404')\n >>> bad_r.status_code\n 404\n \n@@ -410,7 +410,7 @@ We can view the server's response headers using a Python dictionary::\n }\n \n The dictionary is special, though: it's made just for HTTP headers. According to\n-`RFC 7230 `_, HTTP Header names\n+`RFC 7230 `_, HTTP Header names\n are case-insensitive.\n \n So, we can access the headers using any capitalization we want::\n@@ -424,7 +424,7 @@ So, we can access the headers using any capitalization we want::\n It is also special in that the server could have sent the same header multiple\n times with different values, but requests combines them so they can be\n represented in the dictionary within a single mapping, as per\n-`RFC 7230 `_:\n+`RFC 7230 `_:\n \n A recipient MAY combine multiple header fields with the same field name\n into one \"field-name: field-value\" pair, without changing the semantics\n@@ -445,7 +445,7 @@ If a response contains some Cookies, you can quickly access them::\n To send your own cookies to the server, you can use the ``cookies``\n parameter::\n \n- >>> url = 'http://httpbin.org/cookies'\n+ >>> url = 'https://httpbin.org/cookies'\n >>> cookies = dict(cookies_are='working')\n \n >>> r = requests.get(url, cookies=cookies)\n@@ -460,7 +460,7 @@ also be passed in to requests::\n >>> jar = requests.cookies.RequestsCookieJar()\n >>> jar.set('tasty_cookie', 'yum', domain='httpbin.org', path='/cookies')\n >>> jar.set('gross_cookie', 'blech', domain='httpbin.org', path='/elsewhere')\n- >>> url = 'http://httpbin.org/cookies'\n+ >>> url = 'https://httpbin.org/cookies'\n >>> r = requests.get(url, cookies=jar)\n >>> r.text\n '{\"cookies\": {\"tasty_cookie\": \"yum\"}}'\n@@ -481,7 +481,7 @@ response.\n \n For example, GitHub redirects all HTTP requests to HTTPS::\n \n- >>> r = requests.get('http://github.com')\n+ >>> r = requests.get('https://github.com/')\n \n >>> r.url\n 'https://github.com/'\n@@ -496,7 +496,7 @@ For example, GitHub redirects all HTTP requests to HTTPS::\n If you're using GET, OPTIONS, POST, PUT, PATCH or DELETE, you can disable\n redirection handling with the ``allow_redirects`` parameter::\n \n- >>> r = requests.get('http://github.com', allow_redirects=False)\n+ >>> r = requests.get('https://github.com/', allow_redirects=False)\n \n >>> r.status_code\n 301\n@@ -506,7 +506,7 @@ redirection handling with the ``allow_redirects`` parameter::\n \n If you're using HEAD, you can enable redirection as well::\n \n- >>> r = requests.head('http://github.com', allow_redirects=True)\n+ >>> r = requests.head('https://github.com/', allow_redirects=True)\n \n >>> r.url\n 'https://github.com/'\n@@ -523,7 +523,7 @@ seconds with the ``timeout`` parameter. Nearly all production code should use\n this parameter in nearly all requests. Failure to do so can cause your program\n to hang indefinitely::\n \n- >>> requests.get('http://github.com', timeout=0.001)\n+ >>> requests.get('https://github.com/', timeout=0.001)\n Traceback (most recent call last):\n File \"\", line 1, in \n requests.exceptions.Timeout: HTTPConnectionPool(host='github.com', port=80): Request timed out. (timeout=0.001)" }, { "filename": "requests/__init__.py", "status": "modified", "additions": 1, "deletions": 1, "changes": 2, "patch": "@@ -22,7 +22,7 @@\n ... or POST:\n \n >>> payload = dict(key1='value1', key2='value2')\n- >>> r = requests.post('http://httpbin.org/post', data=payload)\n+ >>> r = requests.post('https://httpbin.org/post', data=payload)\n >>> print(r.text)\n {\n ..." }, { "filename": "requests/api.py", "status": "modified", "additions": 1, "deletions": 1, "changes": 2, "patch": "@@ -49,7 +49,7 @@ def request(method, url, **kwargs):\n Usage::\n \n >>> import requests\n- >>> req = requests.request('GET', 'http://httpbin.org/get')\n+ >>> req = requests.request('GET', 'https://httpbin.org/get')\n \n \"\"\"" }, { "filename": "requests/models.py", "status": "modified", "additions": 2, "deletions": 2, "changes": 4, "patch": "@@ -218,7 +218,7 @@ class Request(RequestHooksMixin):\n Usage::\n \n >>> import requests\n- >>> req = requests.Request('GET', 'http://httpbin.org/get')\n+ >>> req = requests.Request('GET', 'https://httpbin.org/get')\n >>> req.prepare()\n \n \"\"\"\n@@ -278,7 +278,7 @@ class PreparedRequest(RequestEncodingMixin, RequestHooksMixin):\n Usage::\n \n >>> import requests\n- >>> req = requests.Request('GET', 'http://httpbin.org/get')\n+ >>> req = requests.Request('GET', 'https://httpbin.org/get')\n >>> r = req.prepare()\n " }, { "filename": "requests/sessions.py", "status": "modified", "additions": 3, "deletions": 3, "changes": 6, "patch": "@@ -311,7 +311,7 @@ def rebuild_method(self, prepared_request, response):\n \"\"\"\n method = prepared_request.method\n \n- # http://tools.ietf.org/html/rfc7231#section-6.4.4\n+ # https://tools.ietf.org/html/rfc7231#section-6.4.4\n if response.status_code == codes.see_other and method != 'HEAD':\n method = 'GET'\n \n@@ -337,13 +337,13 @@ class Session(SessionRedirectMixin):\n \n >>> import requests\n >>> s = requests.Session()\n- >>> s.get('http://httpbin.org/get')\n+ >>> s.get('https://httpbin.org/get')\n \n \n Or as a context manager::\n \n >>> with requests.Session() as s:\n- >>> s.get('http://httpbin.org/get')\n+ >>> s.get('https://httpbin.org/get')\n \n \"\"\"" }, { "filename": "requests/utils.py", "status": "modified", "additions": 1, "deletions": 1, "changes": 2, "patch": "@@ -176,7 +176,7 @@ def get_netrc_auth(url, raise_errors=False):\n loc = os.path.expanduser('~/{0}'.format(f))\n except KeyError:\n # os.path.expanduser can fail when $HOME is undefined and\n- # getpwuid fails. See http://bugs.python.org/issue20164 &\n+ # getpwuid fails. See https://bugs.python.org/issue20164 &\n # https://github.com/requests/requests/issues/1846\n return" } ], "reviews": [ { "id": 160126772, "user": "user_dbf2a999bd6d", "state": "CHANGES_REQUESTED", "body": "Looks like a couple examples may be broken. I left comments on the two I had a concern about. Once those are addressed and we get this rebased onto master, I think this is set for merge.", "submitted_at": "2018-09-30T20:13:22+00:00" }, { "id": 160134594, "user": "user_dbf2a999bd6d", "state": "APPROVED", "body": "Cool, I think this looks good. Thanks [USER_REDACTED]! ✨", "submitted_at": "2018-10-01T00:22:36+00:00" } ], "review_comments": [ { "id": 221471744, "user": "user_dbf2a999bd6d", "body": "Why was this removed?", "path": "docs/user/advanced.rst", "line": 28, "side": "LEFT", "created_at": "2018-09-30T20:08:36+00:00" }, { "id": 221471753, "user": "user_dbf2a999bd6d", "body": "Same question here.", "path": "docs/user/advanced.rst", "line": 72, "side": "LEFT", "created_at": "2018-09-30T20:08:56+00:00" } ], "meta": { "languages": [ "html", "md", "ps1", "py", "rst", "yml" ], "touches_tests": false, "review_state_summary": { "CHANGES_REQUESTED": 1, "APPROVED": 1 }, "meaningful_comment_count": 2, "has_approval": true, "has_changes_requested": true, "total_review_comments": 2 } } { "_id": "07dd6f4d43d35451", "_schema_version": "1.0", "_cleaned_at": "2026-02-12T07:46:51.504127+00:00", "repo": "psf/requests", "repo_url": "https://github.com/psf/requests", "license_name": "Apache License 2.0", "license_spdx": "Apache-2.0", "pr_number": 4766, "title": "Fix several ResourceWarnings in test_requests.py", "body": "Hello,\n\nI do not know if you are interested in fixing `ResourceWarning`s in tests, but I will take my chance :)\nThere was 10 unclosed files in `test_requests.py`.", "author": "user_3fa56c93af17", "created_at": "2018-08-13T19:11:49+00:00", "merged_at": "2022-05-11T01:04:18+00:00", "base_branch": "main", "head_branch": "fix-resource-warnings", "additions": 44, "deletions": 38, "changed_files": 1, "files": [ { "filename": "tests/test_requests.py", "status": "modified", "additions": 44, "deletions": 38, "changes": 82, "patch": "@@ -1022,12 +1022,13 @@ def test_form_encoded_post_query_multivalued_element(self, httpbin):\n assert prep.body == \"test=foo&test=baz\"\n \n def test_different_encodings_dont_break_post(self, httpbin):\n- r = requests.post(\n- httpbin(\"post\"),\n- data={\"stuff\": json.dumps({\"a\": 123})},\n- params={\"blah\": \"asdf1234\"},\n- files={\"file\": (\"test_requests.py\", open(__file__, \"rb\"))},\n- )\n+ with open(__file__, \"rb\") as f:\n+ r = requests.post(\n+ httpbin(\"post\"),\n+ data={\"stuff\": json.dumps({\"a\": 123})},\n+ params={\"blah\": \"asdf1234\"},\n+ files={\"file\": (\"test_requests.py\", f)},\n+ )\n assert r.status_code == 200\n \n [USER_REDACTED].mark.parametrize(\n@@ -1040,35 +1041,44 @@ def test_different_encodings_dont_break_post(self, httpbin):\n ),\n )\n def test_unicode_multipart_post(self, httpbin, data):\n- r = requests.post(\n- httpbin(\"post\"),\n- data=data,\n- files={\"file\": (\"test_requests.py\", open(__file__, \"rb\"))},\n- )\n+ with open(__file__, \"rb\") as f:\n+ r = requests.post(\n+ httpbin(\"post\"),\n+ data=data,\n+ files={\"file\": (\"test_requests.py\", f)},\n+ )\n assert r.status_code == 200\n \n def test_unicode_multipart_post_fieldnames(self, httpbin):\n filename = os.path.splitext(__file__)[0] + \".py\"\n- r = requests.Request(\n- method=\"POST\",\n- url=httpbin(\"post\"),\n- data={b\"stuff\": \"elixr\"},\n- files={\"file\": (\"test_requests.py\", open(filename, \"rb\"))},\n- )\n- prep = r.prepare()\n+ with open(filename, \"rb\") as f:\n+ r = requests.Request(\n+ method=\"POST\",\n+ url=httpbin(\"post\"),\n+ data={b\"stuff\": \"elixr\"},\n+ files={\"file\": (\"test_requests.py\", f)},\n+ )\n+ prep = r.prepare()\n+\n assert b'name=\"stuff\"' in prep.body\n assert b\"name=\\\"b'stuff'\\\"\" not in prep.body\n \n def test_unicode_method_name(self, httpbin):\n- files = {\"file\": open(__file__, \"rb\")}\n- r = requests.request(method=\"POST\", url=httpbin(\"post\"), files=files)\n+ with open(__file__, \"rb\") as f:\n+ files = {\"file\": f}\n+ r = requests.request(\n+ method=\"POST\",\n+ url=httpbin(\"post\"),\n+ files=files,\n+ )\n assert r.status_code == 200\n \n def test_unicode_method_name_with_request_object(self, httpbin):\n- files = {\"file\": open(__file__, \"rb\")}\n s = requests.Session()\n- req = requests.Request(\"POST\", httpbin(\"post\"), files=files)\n- prep = s.prepare_request(req)\n+ with open(__file__, \"rb\") as f:\n+ files = {\"file\": f}\n+ req = requests.Request(\"POST\", httpbin(\"post\"), files=files)\n+ prep = s.prepare_request(req)\n assert isinstance(prep.method, builtin_str)\n assert prep.method == \"POST\"\n \n@@ -1084,18 +1094,14 @@ def test_non_prepared_request_error(self):\n assert str(e.value) == \"You can only send PreparedRequests.\"\n \n def test_custom_content_type(self, httpbin):\n- r = requests.post(\n- httpbin(\"post\"),\n- data={\"stuff\": json.dumps({\"a\": 123})},\n- files={\n- \"file1\": (\"test_requests.py\", open(__file__, \"rb\")),\n- \"file2\": (\n- \"test_requests\",\n- open(__file__, \"rb\"),\n- \"text/py-content-type\",\n- ),\n- },\n- )\n+ with open(__file__, \"rb\") as f1:\n+ with open(__file__, \"rb\") as f2:\n+ data={\"stuff\": json.dumps({\"a\": 123})}\n+ files = {\n+ \"file1\": (\"test_requests.py\", f1),\n+ \"file2\": (\"test_requests\", f2, \"text/py-content-type\"),\n+ }\n+ r = requests.post(httpbin(\"post\"), data=data, files=files)\n assert r.status_code == 200\n assert b\"text/py-content-type\" in r.request.body\n \n@@ -1484,9 +1490,9 @@ def test_prepared_request_is_pickleable(self, httpbin):\n assert resp.status_code == 200\n \n def test_prepared_request_with_file_is_pickleable(self, httpbin):\n- files = {\"file\": open(__file__, \"rb\")}\n- r = requests.Request(\"POST\", httpbin(\"post\"), files=files)\n- p = r.prepare()\n+ with open(__file__, \"rb\") as f:\n+ r = requests.Request(\"POST\", httpbin(\"post\"), files={\"file\": f})\n+ p = r.prepare()\n \n # [NAME_REDACTED] can be pickled and unpickled\n r = pickle.loads(pickle.dumps(p))" } ], "reviews": [ { "id": 154914864, "user": "user_d37df7c0baa1", "state": "DISMISSED", "body": null, "submitted_at": "2018-09-13T03:07:13+00:00" }, { "id": 145869956, "user": "user_dbf2a999bd6d", "state": "CHANGES_REQUESTED", "body": "Hi [USER_REDACTED], thanks for looking into this. I don't have an issue adding the context handlers, but we should probably avoid dumping all of the logic inside of them.\n\nIf we want to encourage best practices, let's make sure anything not relevant to the file handler stays at its original indentation. Once that's done, if you can rebase onto master, I think I'm happy with this.", "submitted_at": "2018-09-30T20:31:20+00:00" }, { "id": 968559173, "user": "user_dbf2a999bd6d", "state": "APPROVED", "body": "Hi [USER_REDACTED], I've rebased your change onto the top of our main branch and resolved some conflicts. This seems like a reasonable fix still and I think we're happy with its current state. Thanks again for the contribution!", "submitted_at": "2022-05-11T01:03:37+00:00" } ], "review_comments": [ { "id": 209787773, "user": "user_dbf2a999bd6d", "body": "Let’s pull the `assert` out to the same indentation level as `with`.", "path": "tests/test_requests.py", "line": null, "side": "RIGHT", "created_at": "2018-08-13T23:14:55+00:00" }, { "id": 209787806, "user": "user_dbf2a999bd6d", "body": "Same here.", "path": "tests/test_requests.py", "line": null, "side": "RIGHT", "created_at": "2018-08-13T23:15:10+00:00" }, { "id": 221472175, "user": "user_dbf2a999bd6d", "body": "Let's just pass this directly to the `files` parameter.", "path": "tests/test_requests.py", "line": null, "side": "RIGHT", "created_at": "2018-09-30T20:23:42+00:00" }, { "id": 221472191, "user": "user_dbf2a999bd6d", "body": "We can unindent this to align with `with`.", "path": "tests/test_requests.py", "line": null, "side": "RIGHT", "created_at": "2018-09-30T20:24:12+00:00" }, { "id": 221472224, "user": "user_dbf2a999bd6d", "body": "These asserts can be done at the same indentation as the `with` block.", "path": "tests/test_requests.py", "line": null, "side": "RIGHT", "created_at": "2018-09-30T20:25:23+00:00" } ], "meta": { "languages": [ "py" ], "touches_tests": true, "review_state_summary": { "DISMISSED": 1, "CHANGES_REQUESTED": 1, "APPROVED": 1 }, "meaningful_comment_count": 5, "has_approval": true, "has_changes_requested": true, "total_review_comments": 5 } } { "_id": "ab6e05f17a242ca4", "_schema_version": "1.0", "_cleaned_at": "2026-02-12T07:46:51.504585+00:00", "repo": "psf/requests", "repo_url": "https://github.com/psf/requests", "license_name": "Apache License 2.0", "license_spdx": "Apache-2.0", "pr_number": 4739, "title": "Document that params and data can be list of tuples everywhere", "body": "Fix a few inconsistencies in the doc found while working on [MechanicalSoup](https://github.com/[USER_REDACTED]nicalSoup/MechanicalSoup/pull/219).", "author": "user_bf117c3b02cb", "created_at": "2018-07-13T09:49:48+00:00", "merged_at": "2018-07-17T22:16:03+00:00", "base_branch": "master", "head_branch": "doc-list-of-tuples", "additions": 26, "deletions": 13, "changed_files": 3, "files": [ { "filename": "requests/api.py", "status": "modified", "additions": 12, "deletions": 6, "changes": 18, "patch": "@@ -18,8 +18,10 @@ def request(method, url, **kwargs):\n \n :param method: method for the new :class:`Request` object.\n :param url: URL for the new :class:`Request` object.\n- :param params: (optional) Dictionary or bytes to be sent in the query string for the :class:`Request`.\n- :param data: (optional) Dictionary or list of tuples ``[(key, value)]`` (will be form-encoded), bytes, or file-like object to send in the body of the :class:`Request`.\n+ :param params: (optional) Dictionary, list of tuples or bytes to send\n+ in the body of the :class:`Request`.\n+ :param data: (optional) Dictionary, list of tuples, bytes, or file-like\n+ object to send in the body of the :class:`Request`.\n :param json: (optional) A JSON serializable Python object to send in the body of the :class:`Request`.\n :param headers: (optional) Dictionary of HTTP Headers to send with the :class:`Request`.\n :param cookies: (optional) Dict or CookieJar object to send with the :class:`Request`.\n@@ -62,7 +64,8 @@ def get(url, params=None, **kwargs):\n r\"\"\"Sends a GET request.\n \n :param url: URL for the new :class:`Request` object.\n- :param params: (optional) Dictionary or bytes to be sent in the query string for the :class:`Request`.\n+ :param params: (optional) Dictionary, list of tuples or bytes to send\n+ in the body of the :class:`Request`.\n :param \\*\\*kwargs: Optional arguments that ``request`` takes.\n :return: :class:`Response ` object\n :rtype: requests.Response\n@@ -102,7 +105,8 @@ def post(url, data=None, json=None, **kwargs):\n r\"\"\"Sends a POST request.\n \n :param url: URL for the new :class:`Request` object.\n- :param data: (optional) Dictionary (will be form-encoded), bytes, or file-like object to send in the body of the :class:`Request`.\n+ :param data: (optional) Dictionary, list of tuples, bytes, or file-like\n+ object to send in the body of the :class:`Request`.\n :param json: (optional) json data to send in the body of the :class:`Request`.\n :param \\*\\*kwargs: Optional arguments that ``request`` takes.\n :return: :class:`Response ` object\n@@ -116,7 +120,8 @@ def put(url, data=None, **kwargs):\n r\"\"\"Sends a PUT request.\n \n :param url: URL for the new :class:`Request` object.\n- :param data: (optional) Dictionary (will be form-encoded), bytes, or file-like object to send in the body of the :class:`Request`.\n+ :param data: (optional) Dictionary, list of tuples, bytes, or file-like\n+ object to send in the body of the :class:`Request`.\n :param json: (optional) json data to send in the body of the :class:`Request`.\n :param \\*\\*kwargs: Optional arguments that ``request`` takes.\n :return: :class:`Response ` object\n@@ -130,7 +135,8 @@ def patch(url, data=None, **kwargs):\n r\"\"\"Sends a PATCH request.\n \n :param url: URL for the new :class:`Request` object.\n- :param data: (optional) Dictionary (will be form-encoded), bytes, or file-like object to send in the body of the :class:`Request`.\n+ :param data: (optional) Dictionary, list of tuples, bytes, or file-like\n+ object to send in the body of the :class:`Request`.\n :param json: (optional) json data to send in the body of the :class:`Request`.\n :param \\*\\*kwargs: Optional arguments that ``request`` takes.\n :return: :class:`Response ` object" }, { "filename": "requests/models.py", "status": "modified", "additions": 6, "deletions": 2, "changes": 8, "patch": "@@ -204,9 +204,13 @@ class Request(RequestHooksMixin):\n :param url: URL to send.\n :param headers: dictionary of headers to send.\n :param files: dictionary of {filename: fileobject} files to multipart upload.\n- :param data: the body to attach to the request. If a dictionary is provided, form-encoding will take place.\n+ :param data: the body to attach to the request. If a dictionary or\n+ list of tuples ``[(key, value)]`` is provided, form-encoding will\n+ take place.\n :param json: json for the body to attach to the request (if files or data is not specified).\n- :param params: dictionary of URL parameters to append to the URL.\n+ :param params: URL parameters to append to the URL. If a dictionary or\n+ list of tuples ``[(key, value)]`` is provided, form-encoding will\n+ take place.\n :param auth: Auth handler or (user, pass) tuple.\n :param cookies: dictionary or CookieJar of cookies to attach to this request.\n :param hooks: dictionary of callback hooks, for internal usage." }, { "filename": "requests/sessions.py", "status": "modified", "additions": 8, "deletions": 5, "changes": 13, "patch": "@@ -453,8 +453,8 @@ def request(self, method, url,\n :param url: URL for the new :class:`Request` object.\n :param params: (optional) Dictionary or bytes to be sent in the query\n string for the :class:`Request`.\n- :param data: (optional) Dictionary, bytes, or file-like object to send\n- in the body of the :class:`Request`.\n+ :param data: (optional) Dictionary, list of tuples, bytes, or file-like\n+ object to send in the body of the :class:`Request`.\n :param json: (optional) json to send in the body of the\n :class:`Request`.\n :param headers: (optional) Dictionary of HTTP Headers to send with the\n@@ -550,7 +550,8 @@ def post(self, url, data=None, json=None, **kwargs):\n r\"\"\"Sends a POST request. Returns :class:`Response` object.\n \n :param url: URL for the new :class:`Request` object.\n- :param data: (optional) Dictionary, bytes, or file-like object to send in the body of the :class:`Request`.\n+ :param data: (optional) Dictionary, list of tuples, bytes, or file-like\n+ object to send in the body of the :class:`Request`.\n :param json: (optional) json to send in the body of the :class:`Request`.\n :param \\*\\*kwargs: Optional arguments that ``request`` takes.\n :rtype: requests.Response\n@@ -562,7 +563,8 @@ def put(self, url, data=None, **kwargs):\n r\"\"\"Sends a PUT request. Returns :class:`Response` object.\n \n :param url: URL for the new :class:`Request` object.\n- :param data: (optional) Dictionary, bytes, or file-like object to send in the body of the :class:`Request`.\n+ :param data: (optional) Dictionary, list of tuples, bytes, or file-like\n+ object to send in the body of the :class:`Request`.\n :param \\*\\*kwargs: Optional arguments that ``request`` takes.\n :rtype: requests.Response\n \"\"\"\n@@ -573,7 +575,8 @@ def patch(self, url, data=None, **kwargs):\n r\"\"\"Sends a PATCH request. Returns :class:`Response` object.\n \n :param url: URL for the new :class:`Request` object.\n- :param data: (optional) Dictionary, bytes, or file-like object to send in the body of the :class:`Request`.\n+ :param data: (optional) Dictionary, list of tuples, bytes, or file-like\n+ object to send in the body of the :class:`Request`.\n :param \\*\\*kwargs: Optional arguments that ``request`` takes.\n :rtype: requests.Response\n \"\"\"" } ], "reviews": [ { "id": 137231447, "user": "user_dbf2a999bd6d", "state": "CHANGES_REQUESTED", "body": "Hi [USER_REDACTED], thanks for submitting this PR! I think we can make the change on the base `request` method to be consistent between `data` and `params`.\n\nAs for the others, it feels unnecessarily redundant for a smaller edge case. The tuple list is a alternative encapsulation of the dictionary concept that is allowing us to use the same key multiple times, and we have documentation around this in the main docs if needed.", "submitted_at": "2018-07-14T07:22:41+00:00" }, { "id": 137278463, "user": "user_bf117c3b02cb", "state": "COMMENTED", "body": null, "submitted_at": "2018-07-15T21:11:07+00:00" }, { "id": 137278550, "user": "user_dbf2a999bd6d", "state": "COMMENTED", "body": null, "submitted_at": "2018-07-15T21:14:55+00:00" }, { "id": 137279073, "user": "user_bf117c3b02cb", "state": "COMMENTED", "body": null, "submitted_at": "2018-07-15T21:36:27+00:00" }, { "id": 137865783, "user": "user_dbf2a999bd6d", "state": "COMMENTED", "body": null, "submitted_at": "2018-07-17T14:47:15+00:00" }, { "id": 137869418, "user": "user_bf117c3b02cb", "state": "COMMENTED", "body": null, "submitted_at": "2018-07-17T14:53:58+00:00" }, { "id": 138042156, "user": "user_dbf2a999bd6d", "state": "APPROVED", "body": "Ok, I think I’m happy with this. Thanks [USER_REDACTED]!", "submitted_at": "2018-07-17T22:15:36+00:00" } ], "review_comments": [ { "id": 202508571, "user": "user_dbf2a999bd6d", "body": "This can probably be two lines instead of three, following the line length of the other entries.", "path": "requests/api.py", "line": null, "side": "RIGHT", "created_at": "2018-07-14T07:15:43+00:00" }, { "id": 202554674, "user": "user_bf117c3b02cb", "body": "To use 2 lines, one needs to cut the ` ``literal`` ` block, and I've seen some RST processor yield incorrect results in this case so I preferred avoiding this cut. I can change it if you prefer.", "path": "requests/api.py", "line": null, "side": "RIGHT", "created_at": "2018-07-15T21:11:07+00:00" }, { "id": 202554782, "user": "user_dbf2a999bd6d", "body": "I don’t think we need to cut the literal block. This line is almost identical to the one below it which only occupies a single line.", "path": "requests/api.py", "line": null, "side": "RIGHT", "created_at": "2018-07-15T21:14:55+00:00" }, { "id": 202555362, "user": "user_bf117c3b02cb", "body": "Indeed: my text editor wraps at 72 characters so it was cutting in the middle of the literal block. I make lines a bit longer, but in most cases it doesn't change the number of lines. Other docstrings fit on one line because they're e.g. 171 characters long.", "path": "requests/api.py", "line": null, "side": "RIGHT", "created_at": "2018-07-15T21:36:27+00:00" }, { "id": 203052167, "user": "user_dbf2a999bd6d", "body": "[USER_REDACTED] yes, so if we split it across two lines it will be < 100 characters per line which is consistent with this projects typical line length.", "path": "requests/api.py", "line": null, "side": "RIGHT", "created_at": "2018-07-17T14:47:15+00:00" }, { "id": 203054972, "user": "user_bf117c3b02cb", "body": "I'm a new contributor so I can't talk about the established practices, but the doc says \"Line-length can exceed 79 characters, to 100, when convenient.\", so I understand that I can make an exception to the 79 characters when I have a good reason (\"when convenient\"). I don't see the benefit of making an exception here.", "path": "requests/api.py", "line": null, "side": "RIGHT", "created_at": "2018-07-17T14:53:58+00:00" } ], "meta": { "languages": [ "py" ], "touches_tests": false, "review_state_summary": { "CHANGES_REQUESTED": 1, "COMMENTED": 5, "APPROVED": 1 }, "meaningful_comment_count": 6, "has_approval": true, "has_changes_requested": true, "total_review_comments": 6 } } { "_id": "a937d91ad1e5539b", "_schema_version": "1.0", "_cleaned_at": "2026-02-12T07:46:51.504585+00:00", "repo": "psf/requests", "repo_url": "https://github.com/psf/requests", "license_name": "Apache License 2.0", "license_spdx": "Apache-2.0", "pr_number": 4718, "title": "[NAME_REDACTED] header whenever root URL changes", "body": "Previously the header was stripped only if the hostname changed, but in\nan https -> http redirect that can leak the credentials on the wire\n(#4716). Based on with RFC 7235 section 2.2, the header is now stripped\nif the \"canonical root URL\" (scheme+authority) has changed.\n\nCloses #4716.", "author": "user_44c1846fca70", "created_at": "2018-06-28T14:48:34+00:00", "merged_at": "2018-09-14T12:08:05+00:00", "base_branch": "master", "head_branch": "fix-4716", "additions": 44, "deletions": 11, "changed_files": 2, "files": [ { "filename": "requests/sessions.py", "status": "modified", "additions": 18, "deletions": 6, "changes": 24, "patch": "@@ -115,6 +115,22 @@ def get_redirect_target(self, resp):\n return to_native_string(location, 'utf8')\n return None\n \n+ def should_strip_auth(self, old_url, new_url):\n+ \"\"\"Decide whether Authorization header should be removed when redirecting\"\"\"\n+ old_parsed = urlparse(old_url)\n+ new_parsed = urlparse(new_url)\n+ if old_parsed.hostname != new_parsed.hostname:\n+ return True\n+ # Special case: allow http -> https redirect when using the standard\n+ # ports. This isn't specified by RFC 7235, but is kept to avoid\n+ # breaking backwards compatibility with older versions of requests\n+ # that allowed any redirects on the same host.\n+ if (old_parsed.scheme == 'http' and old_parsed.port in (80, None)\n+ and new_parsed.scheme == 'https' and new_parsed.port in (443, None)):\n+ return False\n+ # Standard case: root URI must match\n+ return old_parsed.port != new_parsed.port or old_parsed.scheme != new_parsed.scheme\n+\n def resolve_redirects(self, resp, req, stream=False, timeout=None,\n verify=True, cert=None, proxies=None, yield_requests=False, **adapter_kwargs):\n \"\"\"Receives a Response. Returns a generator of Responses or Requests.\"\"\"\n@@ -236,14 +252,10 @@ def rebuild_auth(self, prepared_request, response):\n headers = prepared_request.headers\n url = prepared_request.url\n \n- if 'Authorization' in headers:\n+ if 'Authorization' in headers and self.should_strip_auth(response.request.url, url):\n # If we get redirected to a new host, we should strip out any\n # authentication headers.\n- original_parsed = urlparse(response.request.url)\n- redirect_parsed = urlparse(url)\n-\n- if (original_parsed.hostname != redirect_parsed.hostname):\n- del headers['Authorization']\n+ del headers['Authorization']\n \n # .netrc might have more auth for us on our new host.\n new_auth = get_netrc_auth(url) if self.trust_env else None" }, { "filename": "tests/test_requests.py", "status": "modified", "additions": 26, "deletions": 5, "changes": 31, "patch": "@@ -1573,15 +1573,15 @@ def test_nonhttp_schemes_dont_check_URLs(self):\n preq = req.prepare()\n assert test_url == preq.url\n \n- [USER_REDACTED].mark.xfail(raises=ConnectionError)\n- def test_auth_is_stripped_on_redirect_off_host(self, httpbin):\n+ def test_auth_is_stripped_on_http_downgrade(self, httpbin, httpbin_secure, httpbin_ca_bundle):\n r = requests.get(\n- httpbin('redirect-to'),\n- params={'url': 'http://www.google.co.uk'},\n+ httpbin_secure('redirect-to'),\n+ params={'url': httpbin('get')},\n auth=('user', 'pass'),\n+ verify=httpbin_ca_bundle\n )\n assert r.history[0].request.headers['Authorization']\n- assert not r.request.headers.get('Authorization', '')\n+ assert 'Authorization' not in r.request.headers\n \n def test_auth_is_retained_for_redirect_on_host(self, httpbin):\n r = requests.get(httpbin('redirect/1'), auth=('user', 'pass'))\n@@ -1590,6 +1590,27 @@ def test_auth_is_retained_for_redirect_on_host(self, httpbin):\n \n assert h1 == h2\n \n+ def test_should_strip_auth_host_change(self):\n+ s = requests.Session()\n+ assert s.should_strip_auth('http://example.com/foo', 'http://another.example.com/')\n+\n+ def test_should_strip_auth_http_downgrade(self):\n+ s = requests.Session()\n+ assert s.should_strip_auth('https://example.com/foo', 'http://example.com/bar')\n+\n+ def test_should_strip_auth_https_upgrade(self):\n+ s = requests.Session()\n+ assert not s.should_strip_auth('http://example.com/foo', 'https://example.com/bar')\n+ assert not s.should_strip_auth('http://example.com:80/foo', 'https://example.com/bar')\n+ assert not s.should_strip_auth('http://example.com/foo', 'https://example.com:443/bar')\n+ # Non-standard ports should trigger stripping\n+ assert s.should_strip_auth('http://example.com:8080/foo', 'https://example.com/bar')\n+ assert s.should_strip_auth('http://example.com/foo', 'https://example.com:8443/bar')\n+\n+ def test_should_strip_auth_port_change(self):\n+ s = requests.Session()\n+ assert s.should_strip_auth('http://example.com:1234/foo', 'https://example.com:4321/bar')\n+\n def test_manual_redirect_with_partial_body_read(self, httpbin):\n s = requests.Session()\n r1 = s.get(httpbin('redirect/2'), allow_redirects=False, stream=True)" } ], "reviews": [ { "id": 132958228, "user": "user_dbf2a999bd6d", "state": "CHANGES_REQUESTED", "body": "Hi [USER_REDACTED], thanks for contributing to Requests! I agree that this behavior does seem wrong and we ideally shouldn’t be sending credentials across the wire in clear view. I took a quick look but was surprisingly unable to find this discussed before. While I’m inclined to merge this, there’s likely some concern about breaking users relying on us not doing the right thing here. I’d like [USER_REDACTED] to weigh in with his thoughts before we move forward.\n\nIn the meantime, I’ve left a couple minor notes on some of the changes.", "submitted_at": "2018-06-28T18:09:25+00:00" }, { "id": 132962603, "user": "user_44c1846fca70", "state": "COMMENTED", "body": null, "submitted_at": "2018-06-28T18:20:04+00:00" }, { "id": 132962746, "user": "user_44c1846fca70", "state": "COMMENTED", "body": null, "submitted_at": "2018-06-28T18:20:29+00:00" }, { "id": 133309157, "user": "user_0fa58b6f3572", "state": "COMMENTED", "body": null, "submitted_at": "2018-06-29T17:17:46+00:00" }, { "id": 133309445, "user": "user_0fa58b6f3572", "state": "COMMENTED", "body": null, "submitted_at": "2018-06-29T17:18:40+00:00" }, { "id": 133321938, "user": "user_44c1846fca70", "state": "COMMENTED", "body": null, "submitted_at": "2018-06-29T17:56:36+00:00" }, { "id": 133714429, "user": "user_dbf2a999bd6d", "state": "COMMENTED", "body": null, "submitted_at": "2018-07-02T17:32:30+00:00" }, { "id": 133724794, "user": "user_44c1846fca70", "state": "COMMENTED", "body": null, "submitted_at": "2018-07-02T18:05:53+00:00" }, { "id": 133891499, "user": "user_44c1846fca70", "state": "COMMENTED", "body": null, "submitted_at": "2018-07-03T08:17:26+00:00" }, { "id": 145456031, "user": "user_dbf2a999bd6d", "state": "COMMENTED", "body": null, "submitted_at": "2018-08-11T20:08:26+00:00" }, { "id": 145549612, "user": "user_44c1846fca70", "state": "COMMENTED", "body": null, "submitted_at": "2018-08-13T08:06:28+00:00" }, { "id": 145655521, "user": "user_b08fb5f52ea1", "state": "COMMENTED", "body": null, "submitted_at": "2018-08-13T13:37:14+00:00" }, { "id": 145662416, "user": "user_44c1846fca70", "state": "COMMENTED", "body": null, "submitted_at": "2018-08-13T13:52:38+00:00" }, { "id": 145672168, "user": "user_b08fb5f52ea1", "state": "COMMENTED", "body": null, "submitted_at": "2018-08-13T14:13:54+00:00" }, { "id": 145716413, "user": "user_44c1846fca70", "state": "COMMENTED", "body": null, "submitted_at": "2018-08-13T15:47:14+00:00" }, { "id": 145722861, "user": "user_b08fb5f52ea1", "state": "COMMENTED", "body": null, "submitted_at": "2018-08-13T16:01:37+00:00" }, { "id": 145725559, "user": "user_dbf2a999bd6d", "state": "COMMENTED", "body": null, "submitted_at": "2018-08-13T16:07:36+00:00" }, { "id": 146021745, "user": "user_44c1846fca70", "state": "COMMENTED", "body": null, "submitted_at": "2018-08-14T11:32:58+00:00" }, { "id": 148875561, "user": "user_44c1846fca70", "state": "COMMENTED", "body": null, "submitted_at": "2018-08-23T11:58:23+00:00" }, { "id": 152489974, "user": "user_b08fb5f52ea1", "state": "DISMISSED", "body": null, "submitted_at": "2018-09-05T13:20:04+00:00" }, { "id": 152555114, "user": "user_dbf2a999bd6d", "state": "DISMISSED", "body": "Ok, I think this is set to go. Thanks for driving this, [USER_REDACTED]!", "submitted_at": "2018-09-05T15:28:14+00:00" }, { "id": 152578619, "user": "user_dbf2a999bd6d", "state": "DISMISSED", "body": null, "submitted_at": "2018-09-05T16:19:16+00:00" }, { "id": 155466028, "user": "user_dbf2a999bd6d", "state": "APPROVED", "body": "Ok, this still looks good. Thanks again for driving this [USER_REDACTED]!", "submitted_at": "2018-09-14T12:07:27+00:00" } ], "review_comments": [ { "id": 198934960, "user": "user_dbf2a999bd6d", "body": "We may want to do the explicit check on scheme, hostname, and port here. Otherwise a url with credentials that’s redirected without credentials may have the Authorization header unnecessarily stripped.", "path": "requests/sessions.py", "line": null, "side": "RIGHT", "created_at": "2018-06-28T18:08:00+00:00" }, { "id": 198935315, "user": "user_dbf2a999bd6d", "body": "We should be explicit here and validate that `Authorization` is not in the request headers rather than checking if the value is falsey.", "path": "tests/test_requests.py", "line": null, "side": "RIGHT", "created_at": "2018-06-28T18:09:13+00:00" }, { "id": 198938488, "user": "user_44c1846fca70", "body": "Fair enough, I hadn't spotted that the username and password are still present in response.request.url.", "path": "requests/sessions.py", "line": null, "side": "RIGHT", "created_at": "2018-06-28T18:20:04+00:00" }, { "id": 198938605, "user": "user_44c1846fca70", "body": "I was just copying the test above it, but I agree that would be an improvement. Will fix it tomorrow.", "path": "tests/test_requests.py", "line": null, "side": "RIGHT", "created_at": "2018-06-28T18:20:29+00:00" }, { "id": 199226219, "user": "user_0fa58b6f3572", "body": "`r.json()['headers']` should also be a way to verify that it wasn't *sent*", "path": "tests/test_requests.py", "line": null, "side": "RIGHT", "created_at": "2018-06-29T17:17:46+00:00" }, { "id": 199226444, "user": "user_0fa58b6f3572", "body": "I think this might need to be a bit different. I think if someone sent credentials over `HTTP` and we're being redirected to the same domain but it's `HTTPS` we should allow that. That's a secure upgrade. The opposite should not be allowed.", "path": "requests/sessions.py", "line": null, "side": "RIGHT", "created_at": "2018-06-29T17:18:39+00:00" }, { "id": 199236189, "user": "user_44c1846fca70", "body": "I did it this way based on RFC 7235:\n\n> A protection space is defined by [NAME_REDACTED] (the scheme\n and authority components of the effective request URI; see Section\n 5.5 of [RFC7230]) of the server being accessed, in combination with\n the realm value if present.\n\n...\n\n> The protection space determines the domain over which credentials can\n be automatically applied. If a prior request has been authorized,\n the user agent MAY reuse the same credentials for all other requests\n within that protection space for a period of time determined by [NAME_REDACTED], parameters, and/or user preferences (such as a\n configurable inactivity timeout).\n\nWhile it's not explicit, the implication is that a user agent may not automatically reuse the credentials outside the protection space, and a change from http -> https is a change in protection space.", "path": "requests/sessions.py", "line": null, "side": "RIGHT", "created_at": "2018-06-29T17:56:36+00:00" }, { "id": 199569417, "user": "user_dbf2a999bd6d", "body": "[USER_REDACTED], just to be clear, the spec you’re referencing is specifically about the realm attribute, which is different that what we’re doing here.\n\nIf we look at browsers for reference here, upgrade redirects maintain Authorization headers. Breaking this will make a common pattern pretty painful for most users.", "path": "requests/sessions.py", "line": null, "side": "RIGHT", "created_at": "2018-07-02T17:32:30+00:00" }, { "id": 199577864, "user": "user_44c1846fca70", "body": "Strange, I thought I'd tested the http -> https case with Firefox and Chromium and neither had sent the Authorization header. I'll take a closer look at my test when I'm in the office tomorrow.\n\nJust to check that I'm testing the same thing that you're referring to: my test is a localhost Apache server listening on http and https. On http it is set up to require basic auth, and on some path it is set up to send a 302 redirect to somewhere on https. I point the browser at the http port, I get a WWW-Authenticate challenge and I type in username+password, I then get redirected to https and the browser either does or doesn't automatically send the same credentials immediately without another WWW-Authenticate challenge?", "path": "requests/sessions.py", "line": null, "side": "RIGHT", "created_at": "2018-07-02T18:05:53+00:00" }, { "id": 199720262, "user": "user_44c1846fca70", "body": "I've redone my test, using `openssl s_server` to see the request headers that the browser sends to the https port after the redirect. Firefox definitely isn't preserving the Authorization header across the redirect. Let me know if you'd like more details to reproduce the test (httpd.conf etc) using Docker.", "path": "requests/sessions.py", "line": null, "side": "RIGHT", "created_at": "2018-07-03T08:17:26+00:00" }, { "id": 209436425, "user": "user_dbf2a999bd6d", "body": "Hi [USER_REDACTED], it looks like Firefox does adhere to this rule. I'm a bit worried that adding the stripping from HTTP->HTTPS is going to be breaking for some people. I think for this patch, we should focus on removing the immediate security risk, and then we can add a todo for Requests3 to make this more in line with how browsers are behaving.", "path": "requests/sessions.py", "line": null, "side": "RIGHT", "created_at": "2018-08-11T20:08:26+00:00" }, { "id": 209521493, "user": "user_44c1846fca70", "body": "Thanks for reminding me about this PR. Okay, I can add an exception to allow http -> https redirects, with a comment to explain why.\n\nHow do you want to handle port changes? For example, `http://example.com` -> `https://example.com` is one thing (which implicitly changes the port from 80 to 443), but what about `http://example.com:8080` -> `https://example.com:12345` or `http://example.com` -> `http://example.com:12345`? That last one seems like a security risk since a non-root user could listen on an arbitrary port.\n\nI bring up the port changes because the unit test necessarily runs httpbin on non-standard ports and so there is no way to test redirects with implicit port numbers.", "path": "requests/sessions.py", "line": null, "side": "RIGHT", "created_at": "2018-08-13T08:06:28+00:00" }, { "id": 209611050, "user": "user_b08fb5f52ea1", "body": "Any change in a URLs origin should probably result in stripping of security headers. Origin for `http/https` URLs is scheme, hostname, and port. The only cases we should keep headers on a cross-origin redirect IMO are `http://example.com:80 -> https://example.com:443` and `http://example.com:1234 -> https://example.com:1234`. Thoughts?", "path": "requests/sessions.py", "line": null, "side": "RIGHT", "created_at": "2018-08-13T13:37:14+00:00" }, { "id": 209616586, "user": "user_44c1846fca70", "body": "I think that matches the logic I started implementing (with the exception that it will only allow upgrade from 80->443 when both are implicit):\n```python\nhttps_upgrade = original_parsed.scheme == 'http' and redirect_parsed.scheme == 'https'\nif (original_parsed.hostname != redirect_parsed.hostname\n or original_parsed.port != redirect_parsed.port\n or (original_parsed.scheme != redirect_parsed.scheme and not https_upgrade)):\n```\nDoes that look reasonable?\n\nThe catch is that it's not really possible to test with httpbin, because we don't get to pick the port numbers that httpbin runs on. One option would be to move this logic into its own function (that just takes two URLs and decides whether to strip) and unit test that function separately from the end-to-end test through httpbin. The existing end-to-end tests should be sufficient to check that the actual stripping is done correctly.", "path": "requests/sessions.py", "line": null, "side": "RIGHT", "created_at": "2018-08-13T13:52:38+00:00" }, { "id": 209624235, "user": "user_b08fb5f52ea1", "body": "Question because I don't know the behavior of the URL parser, if you parse `http://example.com` and `http://example.com:80` do you get a different value of `redirect_parsed.port`, is it `None` on implicit?", "path": "requests/sessions.py", "line": null, "side": "RIGHT", "created_at": "2018-08-13T14:13:53+00:00" }, { "id": 209660749, "user": "user_44c1846fca70", "body": "Yes\n```python\n>>> print(urllib.parse.urlparse('http://example.com/').port)\nNone\n>>> print(urllib.parse.urlparse('http://example.com:80/').port)\n80\n```", "path": "requests/sessions.py", "line": null, "side": "RIGHT", "created_at": "2018-08-13T15:47:14+00:00" }, { "id": 209665887, "user": "user_b08fb5f52ea1", "body": "So we'd have to account for that in our comparison above as we want `http://example.com:80` -> `https://example.com` to work the same as `http://example.com` -> `https://example.com`.", "path": "requests/sessions.py", "line": null, "side": "RIGHT", "created_at": "2018-08-13T16:01:37+00:00" }, { "id": 209668067, "user": "user_dbf2a999bd6d", "body": "At this point there’s enough complexity in this implementation we should probably move it into it’s own check function.\n\nI think Seth’s assessment is right here. We want to check the following:\n\n1. The hostnames match.\n2. The schemes match...\n * Except in the case of http->https\n * If scheme change is http->https, origin port may be 80 or None and destination port may be 443 or None.\n3. Ports match, except in above scenario.\n4. Same scheme and hostname but varied port results in stripped auth.", "path": "requests/sessions.py", "line": null, "side": "RIGHT", "created_at": "2018-08-13T16:07:36+00:00" }, { "id": 209917194, "user": "user_44c1846fca70", "body": "Sounds sensible to me. I've implemented that in the latest push.\n\nI've left the logic in a public method of SessionRedirectMixin, because that gives the user the option to override it in a subclass, but let me know if I should move it to utils.", "path": "requests/sessions.py", "line": null, "side": "RIGHT", "created_at": "2018-08-14T11:32:58+00:00" }, { "id": 212280641, "user": "user_44c1846fca70", "body": "Ping? I think I've addressed the comments so far.", "path": "requests/sessions.py", "line": null, "side": "RIGHT", "created_at": "2018-08-23T11:58:23+00:00" } ], "meta": { "languages": [ "py" ], "touches_tests": true, "review_state_summary": { "CHANGES_REQUESTED": 1, "COMMENTED": 18, "DISMISSED": 3, "APPROVED": 1 }, "meaningful_comment_count": 20, "has_approval": true, "has_changes_requested": true, "total_review_comments": 20 } } { "_id": "193bcf7452369471", "_schema_version": "1.0", "_cleaned_at": "2026-02-12T07:46:51.504585+00:00", "repo": "psf/requests", "repo_url": "https://github.com/psf/requests", "license_name": "Apache License 2.0", "license_spdx": "Apache-2.0", "pr_number": 4717, "title": "Add official Python 3.7 support", "body": "Python 3.7 was just released [1]. This is a small change to\nenable support in requests.\n\n[1] https://docs.python.org/3.7/whatsnew/3.7.html\n\nSigned-off-by: [NAME_EMAIL_REDACTED]", "author": "user_ce33bf3d5b61", "created_at": "2018-06-28T06:32:11+00:00", "merged_at": "2018-07-24T14:44:38+00:00", "base_branch": "master", "head_branch": "py37", "additions": 30, "deletions": 11, "changed_files": 3, "files": [ { "filename": ".travis.yml", "status": "modified", "additions": 24, "deletions": 11, "changes": 35, "patch": "@@ -1,14 +1,5 @@\n sudo: false\n language: python\n-python:\n- # - \"2.6\"\n- - \"2.7\"\n- - \"3.4\"\n- - \"3.5\"\n- - \"3.6\"\n- - \"3.7-dev\"\n- # - \"pypy\" -- appears to hang\n- # - \"pypy3\"\n # command to install dependencies\n install: \"make\"\n # command to run tests\n@@ -21,9 +12,31 @@ jobs:\n include:\n - stage: test\n script:\n- - |\n- if [[ \"$TRAVIS_PYTHON_VERSION\" != \"2.6\" ]] ; then make test-readme; fi\n+ - make test-readme\n - make ci\n+ python: '2.7'\n+ - stage: test\n+ script:\n+ - make test-readme\n+ - make ci\n+ python: '3.4'\n+ - stage: test\n+ script:\n+ - make test-readme\n+ - make ci\n+ python: '3.5'\n+ - stage: test\n+ script:\n+ - make test-readme\n+ - make ci\n+ python: '3.6'\n+ - stage: test\n+ script:\n+ - make test-readme\n+ - make ci\n+ python: '3.7'\n+ dist: xenial\n+ sudo: true \n - stage: coverage\n python: 3.6\n script: codecov" }, { "filename": "appveyor.yml", "status": "modified", "additions": 5, "deletions": 0, "changes": 5, "patch": "@@ -25,6 +25,11 @@ environment:\n PYTHON_ARCH: \"64\"\n TOXENV: \"py36\"\n \n+ - PYTHON: \"C:\\\\Python37-x64\"\n+ PYTHON_VERSION: \"3.7.x\"\n+ PYTHON_ARCH: \"64\"\n+ TOXENV: \"py37\"\n+\n install:\n # [NAME_REDACTED] (from the official .msi of http://python.org) and pip when\n # not already installed." }, { "filename": "setup.py", "status": "modified", "additions": 1, "deletions": 0, "changes": 1, "patch": "@@ -95,6 +95,7 @@ def run_tests(self):\n '[NAME_REDACTED] :: Python :: 3.4',\n '[NAME_REDACTED] :: Python :: 3.5',\n '[NAME_REDACTED] :: Python :: 3.6',\n+ '[NAME_REDACTED] :: Python :: 3.7',\n '[NAME_REDACTED] :: Python :: Implementation :: CPython',\n '[NAME_REDACTED] :: Python :: Implementation :: PyPy'\n )," } ], "reviews": [ { "id": 139138443, "user": "user_0fa58b6f3572", "state": "DISMISSED", "body": null, "submitted_at": "2018-07-20T17:07:50+00:00" }, { "id": 139142511, "user": "user_278727a2e287", "state": "COMMENTED", "body": null, "submitted_at": "2018-07-20T17:22:09+00:00" }, { "id": 139143575, "user": "user_dbf2a999bd6d", "state": "COMMENTED", "body": null, "submitted_at": "2018-07-20T17:25:31+00:00" }, { "id": 139495497, "user": "user_0fa58b6f3572", "state": "COMMENTED", "body": null, "submitted_at": "2018-07-23T14:21:17+00:00" }, { "id": 139495868, "user": "user_0fa58b6f3572", "state": "COMMENTED", "body": null, "submitted_at": "2018-07-23T14:22:02+00:00" }, { "id": 139926086, "user": "user_dbf2a999bd6d", "state": "APPROVED", "body": "Alright, I think this looks good to go. Thanks for seeing this all the way through, [USER_REDACTED]!", "submitted_at": "2018-07-24T14:44:05+00:00" } ], "review_comments": [ { "id": 204113227, "user": "user_278727a2e287", "body": "This could drop the `|` and fit on one line", "path": ".travis.yml", "line": null, "side": "RIGHT", "created_at": "2018-07-20T17:20:25+00:00" }, { "id": 204113248, "user": "user_278727a2e287", "body": "Same.", "path": ".travis.yml", "line": null, "side": "RIGHT", "created_at": "2018-07-20T17:20:30+00:00" }, { "id": 204113487, "user": "user_278727a2e287", "body": "Same.", "path": ".travis.yml", "line": null, "side": "RIGHT", "created_at": "2018-07-20T17:21:24+00:00" }, { "id": 204113526, "user": "user_278727a2e287", "body": "Same.", "path": ".travis.yml", "line": null, "side": "RIGHT", "created_at": "2018-07-20T17:21:30+00:00" }, { "id": 204113619, "user": "user_278727a2e287", "body": "Same.", "path": ".travis.yml", "line": null, "side": "RIGHT", "created_at": "2018-07-20T17:21:45+00:00" }, { "id": 204114188, "user": "user_dbf2a999bd6d", "body": "Why do we need sudo here and does this conflict with the sudo: False declaration above?", "path": ".travis.yml", "line": null, "side": "RIGHT", "created_at": "2018-07-20T17:23:55+00:00" }, { "id": 204114432, "user": "user_dbf2a999bd6d", "body": "Could we get a quick explanation of the benefits/trade offs of moving from the matrix approach to this new setup?", "path": ".travis.yml", "line": 3, "side": "LEFT", "created_at": "2018-07-20T17:24:49+00:00" }, { "id": 204419234, "user": "user_0fa58b6f3572", "body": "No, it does not. This is the only way to use xenial on Travis is to use sudo on this job alone. And xenial is the only target that has true Python 3.7. So it's not ideal (because enabling sudo is *slow*) but it's the best we have right now", "path": ".travis.yml", "line": null, "side": "RIGHT", "created_at": "2018-07-23T14:21:17+00:00" }, { "id": 204419562, "user": "user_0fa58b6f3572", "body": "You mean moving from the old configuration to the more explicit matrix definition? Other than greater flexibility?", "path": ".travis.yml", "line": 3, "side": "LEFT", "created_at": "2018-07-23T14:22:02+00:00" } ], "meta": { "languages": [ "py", "yml" ], "touches_tests": false, "review_state_summary": { "DISMISSED": 1, "COMMENTED": 4, "APPROVED": 1 }, "meaningful_comment_count": 5, "has_approval": true, "has_changes_requested": false, "total_review_comments": 9 } } { "_id": "c83dd4e2b987bd5f", "_schema_version": "1.0", "_cleaned_at": "2026-02-12T07:46:51.512748+00:00", "repo": "psf/requests", "repo_url": "https://github.com/psf/requests", "license_name": "Apache License 2.0", "license_spdx": "Apache-2.0", "pr_number": 4701, "title": "Documentation and tests for form-encoded multivalued elements as lists", "body": null, "author": "user_ce471cb70cc6", "created_at": "2018-06-20T19:26:18+00:00", "merged_at": "2018-07-20T16:56:28+00:00", "base_branch": "master", "head_branch": "4700-multivalued-list-form-encoded", "additions": 19, "deletions": 6, "changed_files": 3, "files": [ { "filename": "AUTHORS.rst", "status": "modified", "additions": 1, "deletions": 0, "changes": 1, "patch": "@@ -188,3 +188,4 @@ Patches and Suggestions\n - [NAME_REDACTED] ([CONTRIBUTOR_REDACTED])\n - [NAME_REDACTED] ([CONTRIBUTOR_REDACTED])\n - [NAME_REDACTED] ([CONTRIBUTOR_REDACTED])\n+- [NAME_REDACTED] ([CONTRIBUTOR_REDACTED])" }, { "filename": "docs/user/quickstart.rst", "status": "modified", "additions": 12, "deletions": 6, "changes": 18, "patch": "@@ -244,12 +244,16 @@ dictionary of data will automatically be form-encoded when the request is made::\n ...\n }\n \n-You can also pass a list of tuples to the ``data`` argument. This is particularly\n-useful when the form has multiple elements that use the same key::\n-\n- >>> payload = (('key1', 'value1'), ('key1', 'value2'))\n- >>> r = requests.post('http://httpbin.org/post', data=payload)\n- >>> print(r.text)\n+The ``data`` argument can also have multiple values for each key. This can be\n+done by making ``data`` either a list of tuples or a dictionary with lists\n+as values. This is particularly useful when the form has multiple elements that\n+use the same key::\n+\n+ >>> payload_tuples = [('key1', 'value1'), ('key1', 'value2')]\n+ >>> r1 = requests.post('http://httpbin.org/post', data=payload_tuples)\n+ >>> payload_dict = {'key1': ['value1', 'value2']}\n+ >>> r2 = requests.post('http://httpbin.org/post', data=payload_dict)\n+ >>> print(r1.text)\n {\n ...\n \"form\": {\n@@ -260,6 +264,8 @@ useful when the form has multiple elements that use the same key::\n },\n ...\n }\n+ >>> r1.text == r2.text\n+ True\n \n There are times that you may want to send data that is not form-encoded. If\n you pass in a ``string`` instead of a ``dict``, that data will be posted directly." }, { "filename": "tests/test_requests.py", "status": "modified", "additions": 6, "deletions": 0, "changes": 6, "patch": "@@ -868,6 +868,12 @@ def test_urlencoded_get_query_multivalued_param(self, httpbin):\n assert r.status_code == 200\n assert r.url == httpbin('get?test=foo&test=baz')\n \n+ def test_form_encoded_post_query_multivalued_element(self, httpbin):\n+ r = requests.Request(method='POST', url=httpbin('post'),\n+ data=dict(test=['foo', 'baz']))\n+ prep = r.prepare()\n+ assert prep.body == 'test=foo&test=baz'\n+\n def test_different_encodings_dont_break_post(self, httpbin):\n r = requests.post(httpbin('post'),\n data={'stuff': json.dumps({'a': 123})}," } ], "reviews": [ { "id": 130651646, "user": "user_dbf2a999bd6d", "state": "CHANGES_REQUESTED", "body": "Hi [USER_REDACTED], thanks for contributing to Requests! I actually didn't know this would work, so thanks for teaching me something new.\n\nI left a quick comment about consolidating this with the current tuple example. Let me know what you think about that and we can work forward from there.", "submitted_at": "2018-06-21T02:51:04+00:00" }, { "id": 133326989, "user": "user_ce471cb70cc6", "state": "COMMENTED", "body": null, "submitted_at": "2018-06-29T18:11:33+00:00" }, { "id": 134459823, "user": "user_dbf2a999bd6d", "state": "DISMISSED", "body": null, "submitted_at": "2018-07-04T19:29:04+00:00" }, { "id": 139134767, "user": "user_dbf2a999bd6d", "state": "APPROVED", "body": "I think this looks good, thanks [USER_REDACTED]!", "submitted_at": "2018-07-20T16:56:17+00:00" } ], "review_comments": [ { "id": 196997499, "user": "user_dbf2a999bd6d", "body": "It may be better to roll this into the example above. They are both performing the same action, just with different syntactic sugar.", "path": "docs/user/quickstart.rst", "line": null, "side": "RIGHT", "created_at": "2018-06-21T02:49:52+00:00" }, { "id": 199240167, "user": "user_ce471cb70cc6", "body": "I rolled the examples into one in c61f36e. Does that look like what you were thinking about?", "path": "docs/user/quickstart.rst", "line": null, "side": "RIGHT", "created_at": "2018-06-29T18:11:33+00:00" } ], "meta": { "languages": [ "py", "rst" ], "touches_tests": true, "review_state_summary": { "CHANGES_REQUESTED": 1, "COMMENTED": 1, "DISMISSED": 1, "APPROVED": 1 }, "meaningful_comment_count": 2, "has_approval": true, "has_changes_requested": true, "total_review_comments": 2 } } { "_id": "e2105328d38b3cbd", "_schema_version": "1.0", "_cleaned_at": "2026-02-12T07:46:51.513781+00:00", "repo": "psf/requests", "repo_url": "https://github.com/psf/requests", "license_name": "Apache License 2.0", "license_spdx": "Apache-2.0", "pr_number": 4501, "title": "Separate collections from collections.abc", "body": "In Python 3.7, there is a warning that the abstract bases in collections.abc will no longer be accessible through the regular collections module in Python 3.8. This patch future-proofs requests.\n\nI wasn't able to run the test suite locally, so this needs a thorough test going forward.", "author": "user_3f2a938a80b3", "created_at": "2018-02-05T04:19:41+00:00", "merged_at": "2018-06-12T05:15:01+00:00", "base_branch": "master", "head_branch": "master", "additions": 17, "deletions": 19, "changed_files": 7, "files": [ { "filename": "requests/compat.py", "status": "modified", "additions": 2, "deletions": 0, "changes": 2, "patch": "@@ -43,6 +43,7 @@\n import cookielib\n from Cookie import Morsel\n from StringIO import StringIO\n+ from collections import Callable, Mapping, MutableMapping\n \n from urllib3.packages.ordered_dict import OrderedDict\n \n@@ -60,6 +61,7 @@\n from http.cookies import Morsel\n from io import StringIO\n from collections import OrderedDict\n+ from collections.abc import Callable, Mapping, MutableMapping\n \n builtin_str = str\n str = str" }, { "filename": "requests/cookies.py", "status": "modified", "additions": 2, "deletions": 3, "changes": 5, "patch": "@@ -12,10 +12,9 @@\n import copy\n import time\n import calendar\n-import collections\n \n from ._internal_utils import to_native_string\n-from .compat import cookielib, urlparse, urlunparse, Morsel\n+from .compat import cookielib, urlparse, urlunparse, Morsel, MutableMapping\n \n try:\n import threading\n@@ -169,7 +168,7 @@ class CookieConflictError(RuntimeError):\n \"\"\"\n \n \n-class RequestsCookieJar(cookielib.CookieJar, collections.MutableMapping):\n+class RequestsCookieJar(cookielib.CookieJar, MutableMapping):\n \"\"\"Compatibility class; is a cookielib.CookieJar, but exposes a dict\n interface." }, { "filename": "requests/models.py", "status": "modified", "additions": 4, "deletions": 4, "changes": 8, "patch": "@@ -7,7 +7,6 @@\n This module contains the primary objects that power Requests.\n \"\"\"\n \n-import collections\n import datetime\n import sys\n \n@@ -37,6 +36,7 @@\n stream_decode_response_unicode, to_key_val_list, parse_header_links,\n iter_slices, guess_json_utf, super_len, check_header_validity)\n from .compat import (\n+ Callable, Mapping,\n cookielib, urlunparse, urlsplit, urlencode, str, bytes,\n is_py2, chardet, builtin_str, basestring)\n from .compat import json as complexjson\n@@ -174,10 +174,10 @@ def register_hook(self, event, hook):\n if event not in self.hooks:\n raise ValueError('Unsupported event specified, with event name \"%s\"' % (event))\n \n- if isinstance(hook, collections.Callable):\n+ if isinstance(hook, Callable):\n self.hooks[event].append(hook)\n elif hasattr(hook, '__iter__'):\n- self.hooks[event].extend(h for h in hook if isinstance(h, collections.Callable))\n+ self.hooks[event].extend(h for h in hook if isinstance(h, Callable))\n \n def deregister_hook(self, event, hook):\n \"\"\"Deregister a previously registered hook.\n@@ -461,7 +461,7 @@ def prepare_body(self, data, files, json=None):\n \n is_stream = all([\n hasattr(data, '__iter__'),\n- not isinstance(data, (basestring, list, tuple, collections.Mapping))\n+ not isinstance(data, (basestring, list, tuple, Mapping))\n ])\n \n try:" }, { "filename": "requests/sessions.py", "status": "modified", "additions": 1, "deletions": 2, "changes": 3, "patch": "@@ -10,11 +10,10 @@\n import os\n import sys\n import time\n-from collections import Mapping\n from datetime import timedelta\n \n from .auth import _basic_auth_str\n-from .compat import cookielib, is_py3, OrderedDict, urljoin, urlparse\n+from .compat import cookielib, is_py3, OrderedDict, urljoin, urlparse, Mapping\n from .cookies import (\n cookiejar_from_dict, extract_cookies_to_jar, RequestsCookieJar, merge_cookies)\n from .models import Request, PreparedRequest, DEFAULT_REDIRECT_LIMIT" }, { "filename": "requests/structures.py", "status": "modified", "additions": 4, "deletions": 6, "changes": 10, "patch": "@@ -7,16 +7,14 @@\n Data structures that power Requests.\n \"\"\"\n \n-import collections\n+from .compat import OrderedDict, Mapping, MutableMapping\n \n-from .compat import OrderedDict\n \n-\n-class CaseInsensitiveDict(collections.MutableMapping):\n+class CaseInsensitiveDict(MutableMapping):\n \"\"\"A case-insensitive ``dict``-like object.\n \n Implements all methods and operations of\n- ``collections.MutableMapping`` as well as dict's ``copy``. Also\n+ ``MutableMapping`` as well as dict's ``copy``. Also\n provides ``lower_items``.\n \n All keys are expected to be strings. The structure remembers the\n@@ -71,7 +69,7 @@ def lower_items(self):\n )\n \n def __eq__(self, other):\n- if isinstance(other, collections.Mapping):\n+ if isinstance(other, Mapping):\n other = CaseInsensitiveDict(other)\n else:\n return NotImplemented" }, { "filename": "requests/utils.py", "status": "modified", "additions": 2, "deletions": 3, "changes": 5, "patch": "@@ -9,7 +9,6 @@\n \"\"\"\n \n import codecs\n-import collections\n import contextlib\n import io\n import os\n@@ -29,7 +28,7 @@\n from .compat import (\n quote, urlparse, bytes, str, OrderedDict, unquote, getproxies,\n proxy_bypass, urlunparse, basestring, integer_types, is_py3,\n- proxy_bypass_environment, getproxies_environment)\n+ proxy_bypass_environment, getproxies_environment, Mapping)\n from .cookies import cookiejar_from_dict\n from .structures import CaseInsensitiveDict\n from .exceptions import (\n@@ -301,7 +300,7 @@ def to_key_val_list(value):\n if isinstance(value, (str, bytes, bool, int)):\n raise ValueError('cannot encode objects that are not 2-tuples')\n \n- if isinstance(value, collections.Mapping):\n+ if isinstance(value, Mapping):\n value = value.items()\n \n return list(value)" }, { "filename": "tests/test_requests.py", "status": "modified", "additions": 2, "deletions": 1, "changes": 3, "patch": "@@ -29,6 +29,7 @@\n from requests.sessions import SessionRedirectMixin\n from requests.models import urlencode\n from requests.hooks import default_hooks\n+from requests.compat import MutableMapping\n \n from .compat import StringIO, u\n from .utils import override_environ\n@@ -726,7 +727,7 @@ def test_POSTBIN_GET_POST_FILES_WITH_DATA(self, httpbin):\n requests.post(url, files=['bad file data'])\n \n def test_post_with_custom_mapping(self, httpbin):\n- class CustomMapping(collections.MutableMapping):\n+ class CustomMapping(MutableMapping):\n def __init__(self, *args, **kwargs):\n self.data = dict(*args, **kwargs)" } ], "reviews": [ { "id": 93899681, "user": "user_dbf2a999bd6d", "state": "APPROVED", "body": "Hi [USER_REDACTED], thanks for contributing to Requests! This looks like it will resolve #4494 by [NAME_REDACTED] for Python 3.7. I'd like another maintainer to approve this PR before merging, but I believe this looks good from my end.", "submitted_at": "2018-02-05T07:19:13+00:00" }, { "id": 94698322, "user": "user_0fa58b6f3572", "state": "DISMISSED", "body": null, "submitted_at": "2018-02-07T13:01:19+00:00" }, { "id": 94748211, "user": "user_dbf2a999bd6d", "state": "COMMENTED", "body": null, "submitted_at": "2018-02-07T15:24:32+00:00" }, { "id": 95700740, "user": "user_3f2a938a80b3", "state": "COMMENTED", "body": null, "submitted_at": "2018-02-12T07:06:03+00:00" } ], "review_comments": [ { "id": 166609518, "user": "user_0fa58b6f3572", "body": "[USER_REDACTED] on which versions of Python 3 will this actually succeed on? It was my impression that `collections.abc` was introduced in 3.6 or 3.7.", "path": "requests/compat.py", "line": 64, "side": "RIGHT", "created_at": "2018-02-07T13:00:58+00:00" }, { "id": 166651224, "user": "user_dbf2a999bd6d", "body": "[USER_REDACTED] I'd tested it back to 3.4 without issue, so I think this should work.", "path": "requests/compat.py", "line": 64, "side": "RIGHT", "created_at": "2018-02-07T15:24:32+00:00" }, { "id": 167477993, "user": "user_3f2a938a80b3", "body": "This works back to Python 3.3.", "path": "requests/compat.py", "line": 64, "side": "RIGHT", "created_at": "2018-02-12T07:06:03+00:00" } ], "meta": { "languages": [ "py" ], "touches_tests": true, "review_state_summary": { "APPROVED": 1, "DISMISSED": 1, "COMMENTED": 2 }, "meaningful_comment_count": 3, "has_approval": true, "has_changes_requested": false, "total_review_comments": 3 } } { "_id": "386f736ba9ffc5a0", "_schema_version": "1.0", "_cleaned_at": "2026-02-12T07:46:51.514783+00:00", "repo": "psf/requests", "repo_url": "https://github.com/psf/requests", "license_name": "Apache License 2.0", "license_spdx": "Apache-2.0", "pr_number": 4497, "title": "Clarify docs that Requests always uses certs from certifi", "body": "Since commit 0d7de6430eef0cf09f9662746daf0c28d83f144e, certifi is always used for certificates. Certify became a hard dependency of the package in 628633143d5b8590b1dbdf5371fe81fb8250dffd.\n\nNow update the docs to clarify that Request will always use certificates from certifi.", "author": "user_278727a2e287", "created_at": "2018-02-03T00:01:39+00:00", "merged_at": "2018-02-16T01:56:01+00:00", "base_branch": "master", "head_branch": "docs-certfi", "additions": 8, "deletions": 9, "changed_files": 1, "files": [ { "filename": "docs/user/advanced.rst", "status": "modified", "additions": 8, "deletions": 9, "changes": 17, "patch": "@@ -274,15 +274,14 @@ If you specify a wrong path or an invalid cert, you'll get a SSLError::\n CA Certificates\n ---------------\n \n-By default, Requests bundles a set of root CAs that it trusts, sourced from the\n-`Mozilla trust store`_. However, these are only updated once for each Requests\n-version. This means that if you pin a Requests version your certificates can\n-become extremely out of date.\n-\n-[NAME_REDACTED] version 2.4.0 onwards, Requests will attempt to use certificates\n-from `certifi`_ if it is present on the system. This allows for users to update\n-their trusted certificates without having to change the code that runs on their\n-system.\n+Requests uses certificates from the package `certifi`_. This allows for users\n+to update their trusted certificates without changing the version of Requests.\n+\n+Before version 2.16, Requests bundled a set of root CAs that it trusted,\n+sourced from the `Mozilla trust store`_. The certificates were only updated\n+once for each Requests version. When ``certifi`` was not installed, this led to\n+extremely out-of-date certificate bundles when using significantly older\n+versions of Requests.\n \n For the sake of security we recommend upgrading certifi frequently!" } ], "reviews": [ { "id": 93898195, "user": "user_dbf2a999bd6d", "state": "DISMISSED", "body": "If you feel like it, we could probably remove \"Starting with version 2.4.0, certifi became an optional dependency and Requests would attempt to use its certificates if it was present. Since version 2.16, certifi is a mandatory dependency.\" but I think this looks good. Thanks [USER_REDACTED]!", "submitted_at": "2018-02-05T07:08:21+00:00" }, { "id": 94695306, "user": "user_0fa58b6f3572", "state": "CHANGES_REQUESTED", "body": null, "submitted_at": "2018-02-07T12:49:53+00:00" }, { "id": 94738841, "user": "user_278727a2e287", "state": "COMMENTED", "body": null, "submitted_at": "2018-02-07T15:01:15+00:00" }, { "id": 96485450, "user": "user_0fa58b6f3572", "state": "COMMENTED", "body": null, "submitted_at": "2018-02-14T12:52:42+00:00" }, { "id": 96501367, "user": "user_278727a2e287", "state": "COMMENTED", "body": null, "submitted_at": "2018-02-14T13:48:32+00:00" }, { "id": 96995293, "user": "user_0fa58b6f3572", "state": "APPROVED", "body": null, "submitted_at": "2018-02-15T20:30:51+00:00" }, { "id": 97067255, "user": "user_dbf2a999bd6d", "state": "APPROVED", "body": "Alright, I think this looks good. Thanks [USER_REDACTED]!", "submitted_at": "2018-02-16T01:55:53+00:00" } ], "review_comments": [ { "id": 166607012, "user": "user_0fa58b6f3572", "body": "They would be out of date if and only if users didn't separately install certifi. This is a blanket statement that is plainly untrue.", "path": "docs/user/advanced.rst", "line": null, "side": "RIGHT", "created_at": "2018-02-07T12:49:48+00:00" }, { "id": 166643502, "user": "user_278727a2e287", "body": "This is why I included \"could\". It is true under some conditions, but not others.\n\nHow would you like to see it altered?\n\nWhat about?\n\n> This meant that the certificates of a pinned version of Requests could become extremely out of date if certi was not installed.\n\nOr should the sentence be removed entirely? Any other suggestions?", "path": "docs/user/advanced.rst", "line": null, "side": "RIGHT", "created_at": "2018-02-07T15:01:15+00:00" }, { "id": 168164414, "user": "user_0fa58b6f3572", "body": "I think the `could` is too subtle. What about:\n\n```\nWhen `certifi` was not installed, this led to extremely out-of-date certificate bundles when using significantly older versions of Requests.\n```", "path": "docs/user/advanced.rst", "line": null, "side": "RIGHT", "created_at": "2018-02-14T12:52:42+00:00" }, { "id": 168178111, "user": "user_278727a2e287", "body": "Sounds good and works for me. I've changed the wording as suggested in the latest revision of the PR.", "path": "docs/user/advanced.rst", "line": null, "side": "RIGHT", "created_at": "2018-02-14T13:48:32+00:00" } ], "meta": { "languages": [ "rst" ], "touches_tests": false, "review_state_summary": { "DISMISSED": 1, "CHANGES_REQUESTED": 1, "COMMENTED": 3, "APPROVED": 2 }, "meaningful_comment_count": 4, "has_approval": true, "has_changes_requested": true, "total_review_comments": 4 } } { "_id": "8510490e1871b843", "_schema_version": "1.0", "_cleaned_at": "2026-02-12T07:46:51.516778+00:00", "repo": "psf/requests", "repo_url": "https://github.com/psf/requests", "license_name": "Apache License 2.0", "license_spdx": "Apache-2.0", "pr_number": 4452, "title": "append previous url fragment on redirect", "body": "This PR should address #4443 by [NAME_REDACTED] fragment to subsequent redirects, unless a new fragment is provided in the Location header. This behaviour should bring us into compliance with [RFC 7230 § 7.1.2](https://tools.ietf.org/html/rfc7231#section-7.1.2). I also wrote a test to confirm we don't send fragment information to new servers, our underlying implementation strips that.\n\nOne outstanding question I do have though is about chained redirects. \n\n-----\n\nLet's say we make a request (`http://url#alice`) and get a 302 response (`http://new_url#bob`). We would leave `#bob` as the fragment for the second request. When we request `http://new_url#bob`, we get back another 301 to `http://final_url/`. Do we append `alice` or `bob` at this point? \n\nI went with the assumption that the \"original\" request is the first one in the chain. I could see an argument that all requests are stateless though, and that the `new_url#bob` is the only originating request in scope for the second redirect.", "author": "user_dbf2a999bd6d", "created_at": "2018-01-07T21:28:31+00:00", "merged_at": "2018-01-21T18:41:47+00:00", "base_branch": "master", "head_branch": "append_fragment_on_redirect", "additions": 86, "deletions": 1, "changed_files": 3, "files": [ { "filename": "requests/sessions.py", "status": "modified", "additions": 6, "deletions": 1, "changes": 7, "patch": "@@ -123,6 +123,7 @@ def resolve_redirects(self, resp, req, stream=False, timeout=None,\n hist = [] # keep track of history\n \n url = self.get_redirect_target(resp)\n+ previous_fragment = urlparse(req.url).fragment\n while url:\n prepared_request = req.copy()\n \n@@ -147,8 +148,12 @@ def resolve_redirects(self, resp, req, stream=False, timeout=None,\n parsed_rurl = urlparse(resp.url)\n url = '%s:%s' % (to_native_string(parsed_rurl.scheme), url)\n \n- # The scheme should be lower case...\n+ # Normalize url case and attach previous fragment if needed (RFC 7231 7.1.2)\n parsed = urlparse(url)\n+ if parsed.fragment == '' and previous_fragment:\n+ parsed = parsed._replace(fragment=previous_fragment)\n+ elif parsed.fragment:\n+ previous_fragment = parsed.fragment\n url = parsed.geturl()\n \n # Facilitate relative 'location' headers, as allowed by RFC 7231." }, { "filename": "tests/test_lowlevel.py", "status": "modified", "additions": 72, "deletions": 0, "changes": 72, "patch": "@@ -235,3 +235,75 @@ def redirect_resp_handler(sock):\n assert r.url == u'{0}/{1}'.format(url, expected_path.decode('ascii'))\n \n close_server.set()\n+\n+def test_fragment_not_sent_with_request():\n+ \"\"\"Verify that the fragment portion of a URI isn't sent to the server.\"\"\"\n+ def response_handler(sock):\n+ req = consume_socket_content(sock, timeout=0.5)\n+ sock.send(\n+ b'HTTP/1.1 200 OK\\r\\n'\n+ b'Content-Length: '+bytes(len(req))+b'\\r\\n'\n+ b'\\r\\n'+req\n+ )\n+\n+ close_server = threading.Event()\n+ server = Server(response_handler, wait_to_close_event=close_server)\n+\n+ with server as (host, port):\n+ url = 'http://{0}:{1}/path/to/thing/#view=edit&token=hunter2'.format(host, port)\n+ r = requests.get(url)\n+ raw_request = r.content\n+\n+ assert r.status_code == 200\n+ headers, body = raw_request.split(b'\\r\\n\\r\\n', 1)\n+ status_line, headers = headers.split(b'\\r\\n', 1)\n+\n+ assert status_line == b'GET /path/to/thing/ HTTP/1.1'\n+ for frag in (b'view', b'edit', b'token', b'hunter2'):\n+ assert frag not in headers\n+ assert frag not in body\n+\n+ close_server.set()\n+\n+def test_fragment_update_on_redirect():\n+ \"\"\"Verify we only append previous fragment if one doesn't exist on new\n+ location. If a new fragment is encounterd in a Location header, it should\n+ be added to all subsequent requests.\n+ \"\"\"\n+\n+ def response_handler(sock):\n+ consume_socket_content(sock, timeout=0.5)\n+ sock.send(\n+ b'HTTP/1.1 302 FOUND\\r\\n'\n+ b'Content-Length: 0\\r\\n'\n+ b'Location: /get#relevant-section\\r\\n\\r\\n'\n+ )\n+ consume_socket_content(sock, timeout=0.5)\n+ sock.send(\n+ b'HTTP/1.1 302 FOUND\\r\\n'\n+ b'Content-Length: 0\\r\\n'\n+ b'Location: /final-url/\\r\\n\\r\\n'\n+ )\n+ consume_socket_content(sock, timeout=0.5)\n+ sock.send(\n+ b'HTTP/1.1 200 OK\\r\\n\\r\\n'\n+ )\n+\n+ close_server = threading.Event()\n+ server = Server(response_handler, wait_to_close_event=close_server)\n+\n+ with server as (host, port):\n+ url = 'http://{0}:{1}/path/to/thing/#view=edit&token=hunter2'.format(host, port)\n+ r = requests.get(url)\n+ raw_request = r.content\n+\n+ assert r.status_code == 200\n+ assert len(r.history) == 2\n+ assert r.history[0].request.url == url\n+\n+ # Verify we haven't overwritten the location with our previous fragment.\n+ assert r.history[1].request.url == 'http://{0}:{1}/get#relevant-section'.format(host, port)\n+ # Verify previous fragment is used and not the original.\n+ assert r.url == 'http://{0}:{1}/final-url/#relevant-section'.format(host, port)\n+\n+ close_server.set()" }, { "filename": "tests/test_requests.py", "status": "modified", "additions": 8, "deletions": 0, "changes": 8, "patch": "@@ -294,6 +294,14 @@ def test_transfer_enc_removal_on_redirect(self, httpbin):\n for header in purged_headers:\n assert header not in next_resp.request.headers\n \n+ def test_fragment_maintained_on_redirect(self, httpbin):\n+ fragment = \"#view=edit&token=hunter2\"\n+ r = requests.get(httpbin('redirect-to?url=get')+fragment)\n+\n+ assert len(r.history) > 0\n+ assert r.history[0].request.url == httpbin('redirect-to?url=get')+fragment\n+ assert r.url == httpbin('get')+fragment\n+\n def test_HTTP_200_OK_GET_WITH_PARAMS(self, httpbin):\n heads = {'User-agent': 'Mozilla/5.0'}" } ], "reviews": [ { "id": 87116124, "user": "user_0fa58b6f3572", "state": "COMMENTED", "body": null, "submitted_at": "2018-01-08T00:50:30+00:00" }, { "id": 87116502, "user": "user_dbf2a999bd6d", "state": "COMMENTED", "body": null, "submitted_at": "2018-01-08T01:03:32+00:00" }, { "id": 87116614, "user": "user_0fa58b6f3572", "state": "COMMENTED", "body": null, "submitted_at": "2018-01-08T01:06:51+00:00" }, { "id": 87117419, "user": "user_dbf2a999bd6d", "state": "COMMENTED", "body": null, "submitted_at": "2018-01-08T01:31:51+00:00" }, { "id": 87512619, "user": "user_0fa58b6f3572", "state": "COMMENTED", "body": null, "submitted_at": "2018-01-09T13:16:10+00:00" }, { "id": 87512795, "user": "user_0fa58b6f3572", "state": "COMMENTED", "body": null, "submitted_at": "2018-01-09T13:16:56+00:00" }, { "id": 87931167, "user": "user_dbf2a999bd6d", "state": "COMMENTED", "body": null, "submitted_at": "2018-01-10T18:18:01+00:00" }, { "id": 87963594, "user": "user_0fa58b6f3572", "state": "COMMENTED", "body": null, "submitted_at": "2018-01-10T20:03:55+00:00" }, { "id": 90332385, "user": "user_0fa58b6f3572", "state": "DISMISSED", "body": "Once you rebase this, [USER_REDACTED] it should be good to merge. 🎉", "submitted_at": "2018-01-21T13:40:25+00:00" } ], "review_comments": [ { "id": 160065925, "user": "user_0fa58b6f3572", "body": "I'm confused how this import is working right now. Maybe it's too late for me to be reviewing code?", "path": "tests/testserver.py", "line": null, "side": "RIGHT", "created_at": "2018-01-08T00:50:30+00:00" }, { "id": 160066266, "user": "user_dbf2a999bd6d", "body": "😬 this is me running `git add tests` and not paying attention to garbage in the directory. Disregard this file.", "path": "tests/testserver.py", "line": null, "side": "RIGHT", "created_at": "2018-01-08T01:03:32+00:00" }, { "id": 160066357, "user": "user_0fa58b6f3572", "body": "I await your force-push to remove it 😄", "path": "tests/testserver.py", "line": null, "side": "RIGHT", "created_at": "2018-01-08T01:06:51+00:00" }, { "id": 160067034, "user": "user_dbf2a999bd6d", "body": "Ok, we should be updated now.", "path": "tests/testserver.py", "line": null, "side": "RIGHT", "created_at": "2018-01-08T01:31:51+00:00" }, { "id": 160403161, "user": "user_0fa58b6f3572", "body": "Can we do `parsed._replace(fragment='previous_fragment')`?", "path": "requests/sessions.py", "line": null, "side": "RIGHT", "created_at": "2018-01-09T13:16:10+00:00" }, { "id": 160403297, "user": "user_0fa58b6f3572", "body": "My concern is that `url` might end with `#` which should be equivalent to `parsed.fragment == ''`. What do we do there?", "path": "requests/sessions.py", "line": null, "side": "RIGHT", "created_at": "2018-01-09T13:16:56+00:00" }, { "id": 160757996, "user": "user_dbf2a999bd6d", "body": "Yep, this is definitely a gap. It looks like `geturl()` will also strip empty fragments from redirect urls which probably isn’t the behavior we want.\n\nI’m a little leery of using private methods, but given that `_replace` has been stable for a decade it’s probably safe. I’m wondering given the trailing hash issue if it may be easier to append the fragment option (`’’`, `#`, `#fragment`) after we call `geturl`. I’ll try to come up with something tonight.", "path": "requests/sessions.py", "line": null, "side": "RIGHT", "created_at": "2018-01-10T18:18:01+00:00" }, { "id": 160785012, "user": "user_0fa58b6f3572", "body": "`_replace` is actually part of `namedtuple` which `ParseResult` inherits from. If we wanted to, we could switch wholesale to github.com/hyper/rfc3986 which has a proper public API for this but that is definitely more work than this.", "path": "requests/sessions.py", "line": null, "side": "RIGHT", "created_at": "2018-01-10T20:03:55+00:00" } ], "meta": { "languages": [ "py" ], "touches_tests": true, "review_state_summary": { "COMMENTED": 8, "DISMISSED": 1 }, "meaningful_comment_count": 8, "has_approval": false, "has_changes_requested": false, "total_review_comments": 8 } } { "_id": "78b7b1e6a342c82a", "_schema_version": "1.0", "_cleaned_at": "2026-02-12T07:46:51.517779+00:00", "repo": "django/django", "repo_url": "https://github.com/django/django", "license_name": "BSD 3-Clause \"New\" or \"Revised\" License", "license_spdx": "BSD-3-Clause", "pr_number": 20657, "title": "Refs #36644 -- Documented no pk ordering in first()/last() after empty order_by().", "body": "#### Trac ticket number\nticket-36644\n\n#### Branch description\nAlthough I still think we can regard this as a bugfix, on second thought I think it deserves just a little documentation to clarify.\n\n#### AI [NAME_REDACTED] (REQUIRED)\n\n- [x] **No AI tools were used** in preparing this PR.\n- [ ] **If AI tools were used**, I have disclosed which ones, and fully reviewed and verified their output.\n\n#### Checklist\n- [x] This PR follows the [contribution guidelines](https://docs.djangoproject.com/en/stable/internals/contributing/writing-code/submitting-patches/).\n- [x] This PR **does not** disclose a security vulnerability (see [vulnerability reporting](https://docs.djangoproject.com/en/stable/internals/security/)).\n- [x] This PR targets the `main` branch. \n- [x] The commit message is written in past tense, mentions the ticket number, and ends with a period.\n- [ ] I have checked the \"Has patch\" ticket flag in the Trac system.\n- [ ] I have added or updated relevant tests.\n- [ ] I have added or updated relevant docs, including release notes if applicable.\n- [ ] I have attached screenshots in both light and dark modes for any UI changes.", "author": "user_3a67c55598c5", "created_at": "2026-02-09T20:17:12+00:00", "merged_at": "2026-02-09T21:19:14+00:00", "base_branch": "main", "head_branch": "jtw/update-first-last-docs", "additions": 13, "deletions": 2, "changed_files": 2, "files": [ { "filename": "docs/ref/models/querysets.txt", "status": "modified", "additions": 9, "deletions": 2, "changes": 11, "patch": "@@ -2774,8 +2774,9 @@ the direction is changed.\n *Asynchronous version*: ``afirst()``\n \n Returns the first object matched by [NAME_REDACTED], or ``None`` if there\n-is no matching object. If the ``QuerySet`` has no ordering defined, then the\n-queryset is automatically ordered by [NAME_REDACTED] can affect\n+is no matching object. If the ``QuerySet`` has no ordering defined (and has not\n+had ordering forcibly cleared by calling :meth:`order_by` with no arguments),\n+then the queryset is automatically ordered by [NAME_REDACTED] can affect\n aggregation results as described in :ref:`aggregation-ordering-interaction`.\n \n Example::\n@@ -2790,6 +2791,12 @@ equivalent to the above example::\n except IndexError:\n p = None\n \n+.. versionchanged:: 6.1\n+\n+ ``first()`` and :meth:`last` no longer order by [NAME_REDACTED]\n+ ordering has been forcibly cleared by calling :meth:`order_by` with no\n+ arguments.\n+\n ``last()``\n ~~~~~~~~~~" }, { "filename": "docs/releases/6.1.txt", "status": "modified", "additions": 4, "deletions": 0, "changes": 4, "patch": "@@ -422,6 +422,10 @@ Miscellaneous\n ``null``, to match the behavior of :lookup:`exact=None ` on key\n transforms. Previously, it was interpreted as an :lookup:`isnull` lookup.\n \n+* :meth:`~.QuerySet.first` and :meth:`~.QuerySet.last` no longer order by the\n+ primary key when a ``QuerySet``'s ordering has been forcibly cleared by\n+ calling :meth:`~.QuerySet.order_by` with no arguments.\n+\n .. _deprecated-features-6.1:\n \n Features deprecated in 6.1" } ], "reviews": [ { "id": 3775136871, "user": "user_057de2f3b132", "state": "APPROVED", "body": null, "submitted_at": "2026-02-09T20:25:05+00:00" } ], "review_comments": [ { "id": 2784348743, "user": "user_057de2f3b132", "body": "This reads a bit better to me like this:\n\n```suggestion\nis no matching object. If the ``QuerySet`` has no ordering defined (and has not\nhad ordering forcibly cleared by calling :meth:`order_by` with no arguments),\n```", "path": "docs/ref/models/querysets.txt", "line": null, "side": "RIGHT", "created_at": "2026-02-09T20:23:29+00:00" }, { "id": 2784352784, "user": "user_057de2f3b132", "body": "I think this reads a bit better like this:\n\n```suggestion\n ``first()`` and :meth:`last` no longer order by [NAME_REDACTED]\n ordering has been forcibly cleared by calling :meth:`order_by` with no\n arguments.\n```", "path": "docs/ref/models/querysets.txt", "line": null, "side": "RIGHT", "created_at": "2026-02-09T20:24:22+00:00" } ], "meta": { "languages": [ "txt" ], "touches_tests": false, "review_state_summary": { "APPROVED": 1 }, "meaningful_comment_count": 2, "has_approval": true, "has_changes_requested": false, "total_review_comments": 2 } } { "_id": "c9b792d8b463f88c", "_schema_version": "1.0", "_cleaned_at": "2026-02-12T07:46:51.519778+00:00", "repo": "django/django", "repo_url": "https://github.com/django/django", "license_name": "BSD 3-Clause \"New\" or \"Revised\" License", "license_spdx": "BSD-3-Clause", "pr_number": 20656, "title": "Clarified optional nature of [NAME_REDACTED].", "body": "It's not clear that CLAs are needed to ensure contributors are assenting to our license (the \"inbound=outbound\" agreement), but we can keep them around for contributors who would like to (or are required by [NAME_REDACTED]) to submit one, without investing additional resources in checking every single contribution.\n\nSee https://forum.djangoproject.com/t/cla-vs-dco-for-django-contributors/42399 and recent board minutes.\n\n#### AI [NAME_REDACTED] (REQUIRED)\n\n- [x] **No AI tools were used** in preparing this PR.\n- [ ] **If AI tools were used**, I have disclosed which ones, and fully reviewed and verified their output.\n\n#### TODO\nUpdate flatpages on the website:\n- [x] https://www.djangoproject.com/foundation/cla/faq/\n- [x] https://www.djangoproject.com/foundation/cla/", "author": "user_3a67c55598c5", "created_at": "2026-02-09T15:31:52+00:00", "merged_at": "2026-02-10T14:58:39+00:00", "base_branch": "main", "head_branch": "jtw/cla", "additions": 8, "deletions": 8, "changed_files": 2, "files": [ { "filename": "docs/internals/contributing/new-contributors.txt", "status": "modified", "additions": 2, "deletions": 2, "changes": 4, "patch": "@@ -69,8 +69,8 @@ Sign the [NAME_REDACTED]\n --------------------------------------\n \n The code that you write belongs to you or your employer. If your contribution\n-is more than one or two lines of code, you need to sign the `CLA`_. See the\n-`[NAME_REDACTED] FAQ`_ for a more thorough explanation.\n+is more than one or two lines of code, you have the option to sign the `CLA`_.\n+See the `[NAME_REDACTED] FAQ`_ for a more thorough explanation.\n \n .. _CLA: https://www.djangoproject.com/foundation/cla/\n .. _Contributor License Agreement FAQ: https://www.djangoproject.com/foundation/cla/faq/" }, { "filename": "docs/internals/contributing/writing-code/submitting-patches.txt", "status": "modified", "additions": 6, "deletions": 6, "changes": 12, "patch": "@@ -59,11 +59,10 @@ and time availability), claim it by [NAME_REDACTED]:\n * Finally click the \"Submit changes\" button at the bottom to save.\n \n .. note::\n- The Django software foundation requests that anyone contributing more than\n- a :ref:`trivial change `, to Django sign and submit a\n- `[NAME_REDACTED]`_, this ensures that the Django Software\n- Foundation has clear license to all contributions allowing for a clear\n- license for all users.\n+ If your change is not :ref:`trivial `, you have the option\n+ to sign and submit a `[NAME_REDACTED]`_ clarifying the status\n+ of your contribution. This ensures that the [NAME_REDACTED] has\n+ clear license to your contribution.\n \n .. _Login using your GitHub account: https://code.djangoproject.com/github/login\n .. _Create an account: https://www.djangoproject.com/accounts/register/\n@@ -508,7 +507,8 @@ All tickets\n * Is the pull request a single squashed commit with a message that follows our\n :ref:`commit message format `?\n * Are you the patch author and a new contributor? Please add yourself to the\n- :source:`AUTHORS` file and submit a `[NAME_REDACTED]`_.\n+ :source:`AUTHORS` file. At your option, submit a\n+ `[NAME_REDACTED]`_.\n * Does this have an accepted ticket on Trac? All contributions require a ticket\n unless the :ref:`change is considered trivial `." } ], "reviews": [ { "id": 3774663809, "user": "user_00dac951cdbf", "state": "APPROVED", "body": "LGTM overall! added some small suggestions. Thanks! 🌟", "submitted_at": "2026-02-09T18:15:49+00:00" } ], "review_comments": [ { "id": 2783929224, "user": "user_00dac951cdbf", "body": "Should we be more lenient and say:\n\n```suggestion\n If your change is not :ref:`trivial `, you have the option to\n```", "path": "docs/internals/contributing/writing-code/submitting-patches.txt", "line": null, "side": "RIGHT", "created_at": "2026-02-09T18:14:47+00:00" }, { "id": 2783932384, "user": "user_00dac951cdbf", "body": "Same here?", "path": "docs/internals/contributing/new-contributors.txt", "line": null, "side": "RIGHT", "created_at": "2026-02-09T18:15:31+00:00" } ], "meta": { "languages": [ "txt" ], "touches_tests": false, "review_state_summary": { "APPROVED": 1 }, "meaningful_comment_count": 2, "has_approval": true, "has_changes_requested": false, "total_review_comments": 2 } } { "_id": "43d1fad023feadab", "_schema_version": "1.0", "_cleaned_at": "2026-02-12T07:46:51.522778+00:00", "repo": "django/django", "repo_url": "https://github.com/django/django", "license_name": "BSD 3-Clause \"New\" or \"Revised\" License", "license_spdx": "BSD-3-Clause", "pr_number": 20636, "title": "Refs #33579 -- Added extra tests for NotUpdated exception.", "body": "#### Trac ticket number\n\n\n\nticket-33579\n\n#### Branch description\nWhen `NotUpdated` was added in ab148c02cedbac492f29930dcd5346e1af052635, these additional tests that have equivalents for the `DoesNotExist` and `MultipleObjectsReturned` exceptions were missed.\n\n#### AI [NAME_REDACTED] (REQUIRED)\n\n- [x] **No AI tools were used** in preparing this PR.\n- [ ] **If AI tools were used**, I have disclosed which ones, and fully reviewed and verified their output.\n\n#### Checklist\n- [x] This PR follows the [contribution guidelines](https://docs.djangoproject.com/en/stable/internals/contributing/writing-code/submitting-patches/).\n- [x] This PR **does not** disclose a security vulnerability (see [vulnerability reporting](https://docs.djangoproject.com/en/stable/internals/security/)).\n- [x] This PR targets the `main` branch. \n- [x] The commit message is written in past tense, mentions the ticket number, and ends with a period.\n- [ ] I have checked the \"Has patch\" ticket flag in the Trac system.\n- [x] I have added or updated relevant tests.\n- [ ] I have added or updated relevant docs, including release notes if applicable.\n- [ ] I have attached screenshots in both light and dark modes for any UI changes.", "author": "user_194c2ef4033e", "created_at": "2026-02-03T10:19:03+00:00", "merged_at": "2026-02-05T14:18:55+00:00", "base_branch": "main", "head_branch": "ngnpope/ticket-33579", "additions": 15, "deletions": 3, "changed_files": 3, "files": [ { "filename": "tests/model_inheritance/tests.py", "status": "modified", "additions": 6, "deletions": 0, "changes": 6, "patch": "@@ -449,6 +449,12 @@ def test_inherited_multiple_objects_returned_exception(self):\n with self.assertRaises(Place.MultipleObjectsReturned):\n Restaurant.objects.get()\n \n+ def test_inherited_not_updated_exception(self):\n+ # NotUpdated is also inherited.\n+ obj = Restaurant(id=999)\n+ with self.assertRaises(Place.NotUpdated):\n+ obj.save(update_fields={\"name\"})\n+\n def test_related_objects_for_inherited_models(self):\n # Related objects work just as they normally do.\n s1 = Supplier.objects.create(name=\"[NAME_REDACTED]\", address=\"123 [NAME_REDACTED]\")" }, { "filename": "tests/proxy_models/tests.py", "status": "modified", "additions": 5, "deletions": 3, "changes": 8, "patch": "@@ -2,7 +2,7 @@\n from django.contrib.auth.models import User as AuthUser\n from django.contrib.contenttypes.models import ContentType\n from django.core import checks, management\n-from django.db import DEFAULT_DB_ALIAS, models\n+from django.db import DEFAULT_DB_ALIAS, models, transaction\n from django.db.models import signals\n from django.test import TestCase, override_settings\n from django.test.utils import isolate_apps\n@@ -104,8 +104,8 @@ def test_correct_type_proxy_of_proxy(self):\n \n def test_proxy_included_in_ancestors(self):\n \"\"\"\n- Proxy models are included in the ancestors for a model's DoesNotExist\n- and MultipleObjectsReturned\n+ Proxy models are included in the ancestors for a model's DoesNotExist,\n+ MultipleObjectsReturned, and NotUpdated\n \"\"\"\n Person.objects.create(name=\"[NAME_REDACTED]\")\n MyPerson.objects.create(name=\"Bazza del Frob\")\n@@ -118,6 +118,8 @@ def test_proxy_included_in_ancestors(self):\n MyPersonProxy.objects.get(id__lt=max_id + 1)\n with self.assertRaises(Person.DoesNotExist):\n StatusPerson.objects.get(name=\"Zathras\")\n+ with self.assertRaises(Person.NotUpdated), transaction.atomic():\n+ StatusPerson(id=999).save(update_fields={\"name\"})\n \n StatusPerson.objects.create(name=\"[NAME_REDACTED].\")\n StatusPerson.objects.create(name=\"[NAME_REDACTED].\")" }, { "filename": "tests/queryset_pickle/tests.py", "status": "modified", "additions": 4, "deletions": 0, "changes": 4, "patch": "@@ -70,6 +70,10 @@ def test_multipleobjectsreturned_class(self):\n klass = Event.MultipleObjectsReturned\n self.assertIs(pickle.loads(pickle.dumps(klass)), klass)\n \n+ def test_not_updated_class(self):\n+ klass = Event.NotUpdated\n+ self.assertIs(pickle.loads(pickle.dumps(klass)), klass)\n+\n def test_forward_relatedobjectdoesnotexist_class(self):\n # ForwardManyToOneDescriptor\n klass = Event.group.RelatedObjectDoesNotExist" } ], "reviews": [ { "id": 3744401904, "user": "user_194c2ef4033e", "state": "COMMENTED", "body": null, "submitted_at": "2026-02-03T10:21:12+00:00" }, { "id": 3744430123, "user": "user_081d78d226d7", "state": "COMMENTED", "body": null, "submitted_at": "2026-02-03T10:26:15+00:00" }, { "id": 3744508723, "user": "user_194c2ef4033e", "state": "COMMENTED", "body": null, "submitted_at": "2026-02-03T10:40:55+00:00" }, { "id": 3744520811, "user": "user_081d78d226d7", "state": "COMMENTED", "body": null, "submitted_at": "2026-02-03T10:42:56+00:00" }, { "id": 3744586202, "user": "user_194c2ef4033e", "state": "COMMENTED", "body": null, "submitted_at": "2026-02-03T10:57:29+00:00" }, { "id": 3746154002, "user": "user_cdda8932ec17", "state": "COMMENTED", "body": null, "submitted_at": "2026-02-03T16:05:44+00:00" }, { "id": 3757416620, "user": "user_3a67c55598c5", "state": "APPROVED", "body": null, "submitted_at": "2026-02-05T14:18:32+00:00" }, { "id": 3780801722, "user": "user_657e90e5ae46", "state": "COMMENTED", "body": null, "submitted_at": "2026-02-10T18:31:55+00:00" }, { "id": 3781971113, "user": "user_194c2ef4033e", "state": "COMMENTED", "body": null, "submitted_at": "2026-02-10T22:30:40+00:00" } ], "review_comments": [ { "id": 2758332665, "user": "user_194c2ef4033e", "body": "Curiously this works for `update_fields`, but not for `force_update` which gets overridden somehow as part of the MTI handling. Either that's a bug, or it needs to be documented... 🤔", "path": "tests/model_inheritance/tests.py", "line": 456, "side": "RIGHT", "created_at": "2026-02-03T10:20:46+00:00" }, { "id": 2758333882, "user": "user_194c2ef4033e", "body": "Ditto.", "path": "tests/proxy_models/tests.py", "line": 122, "side": "RIGHT", "created_at": "2026-02-03T10:20:56+00:00" }, { "id": 2758354395, "user": "user_081d78d226d7", "body": "What exactly do you mean? What doesn't work?", "path": "tests/model_inheritance/tests.py", "line": 456, "side": "RIGHT", "created_at": "2026-02-03T10:25:17+00:00" }, { "id": 2758422846, "user": "user_194c2ef4033e", "body": "Sorry - Using `obj.save(force_update=True)` doesn't raise `NotUpdated` where we are using multi-table inheritance because the parent(s) is inserted first and that overrides the `force_insert` flag on the child:\n\nhttps://github.com/[USER_REDACTED]ngo/django/blob/24a14860ced5c456522d69c16afd2c631cc0456f/django/db/models/base.py#L980-L995\n\nThis means that `_save_table()` here is called with both `force_insert` and `force_update` set to `True`, but we don't do any further validation from this point onward. As `force_insert` is `True`, all handling of `force_update` is then ignored in `_save_table()` as we don't take the branch that handles that.\n\nWhen using `update_fields`, however, that is passed through to `_save_parents()` which then calls `_save_table()` and handles it properly.\n\nI suspect the fix would be to pass `force_update` through `_save_parents()`, but I haven't looked at that yet.", "path": "tests/model_inheritance/tests.py", "line": 456, "side": "RIGHT", "created_at": "2026-02-03T10:40:55+00:00" }, { "id": 2758433090, "user": "user_081d78d226d7", "body": "That seems like a legitimate bug, if that's the case. But oh dear, that's gonna break people's code :grimacing:", "path": "tests/model_inheritance/tests.py", "line": 456, "side": "RIGHT", "created_at": "2026-02-03T10:42:56+00:00" }, { "id": 2758491470, "user": "user_194c2ef4033e", "body": "It might be possible to fix - we'd need to raise a deprecation warning first for a number of releases. Anyway - will try to write that up as another ticket later.", "path": "tests/model_inheritance/tests.py", "line": 456, "side": "RIGHT", "created_at": "2026-02-03T10:57:29+00:00" }, { "id": 2759834869, "user": "user_cdda8932ec17", "body": "That's a nice catch but I suspect the intersections of users that\n\n1. Are creating model instances pointing at primary keys they expect to exist\n2. Are making use of MTI\n3. Are passing `force_update=True`\n\nIs pretty small which might explain why this slipped under the radar for so long (the ORM has been silently doing inserts in this case for a long time)\n\nIf we are going to address this issue we should also test interactions with `force_insert: tuple[type[Model]]` and `force_update=True` as I assume it's not a well covered area either.", "path": "tests/model_inheritance/tests.py", "line": 456, "side": "RIGHT", "created_at": "2026-02-03T16:05:44+00:00" }, { "id": 2789583220, "user": "user_657e90e5ae46", "body": "This causes the next operation to fail on databases that don't support savepoints:\n```\n======================================================================\nERROR: test_proxy_included_in_ancestors (proxy_models.tests.ProxyModelTests.test_proxy_included_in_ancestors)\nProxy models are included in the ancestors for a model's DoesNotExist,\n----------------------------------------------------------------------\nTraceback (most recent call last):\n File \"/usr/lib/python3.12/unittest/case.py\", line 58, in testPartExecutor\n yield\n File \"/usr/lib/python3.12/unittest/case.py\", line 634, in run\n self._callTestMethod(testMethod)\n ^^^^^^^^^^^^^^^^^\n File \"/usr/lib/python3.12/unittest/case.py\", line 589, in _callTestMethod\n if method() is not None:\n ^^^^^^^^^^^^^^^^^\n File \"/home/runner/work/django-snowflake/django-snowflake/django_repo/tests/proxy_models/tests.py\", line 124, in test_proxy_included_in_ancestors\n StatusPerson.objects.create(name=\"[NAME_REDACTED].\")\n ^^^^^^^^^^^^^^^^^\n File \"/home/runner/work/django-snowflake/django-snowflake/django_repo/django/db/models/manager.py\", line 87, in manager_method\n return getattr(self.get_queryset(), name)(*args, **kwargs)\n ^^^^^^^^^^^^^^^^^\n File \"/home/runner/work/django-snowflake/django-snowflake/django_repo/django/db/models/query.py\", line 690, in create\n obj.save(force_insert=True, using=self.db)\n ^^^^^^^^^^^^^^^^^\n File \"/home/runner/work/django-snowflake/django-snowflake/django_repo/django/db/models/base.py\", line 896, in save\n self.save_base(\n File \"/home/runner/work/django-snowflake/django-snowflake/django_repo/django/db/models/base.py\", line 985, in save_base\n parent_inserted = self._save_parents(\n ^^^^^^^^^^^^^^^^^\n File \"/home/runner/work/django-snowflake/django-snowflake/django_repo/django/db/models/base.py\", line 1038, in _save_parents\n updated = self._save_table(\n ^^^^^^^^^^^^^^^^^\n File \"/home/runner/work/django-snowflake/django-snowflake/django_repo/django/db/models/base.py\", line 1191, in _save_table\n results = self._do_insert(\n ^^^^^^^^^^^^^^^^^\n File \"/home/runner/work/django-snowflake/django-snowflake/django_repo/django/db/models/base.py\", line 1243, in _do_insert\n return manager._insert(\n ^^^^^^^^^^^^^^^^^\n File \"/home/runner/work/django-snowflake/django-snowflake/django_repo/django/db/models/manager.py\", line 87, in manager_method\n return getattr(self.get_queryset(), name)(*args, **kwargs)\n ^^^^^^^^^^^^^^^^^\n File \"/home/runner/work/django-snowflake/django-snowflake/django_repo/django/db/models/query.py\", line 2013, in _insert\n return query.get_compiler(using=using).execute_sql(returning_fields)\n ^^^^^^^^^^^^^^^^^\n File \"/home/runner/work/django-snowflake/django-snowflake/django_repo/django/db/models/sql/compiler.py\", line 1939, in execute_sql\n cursor.execute(sql, params)\n ^^^^^^^^^^^^^^^^^\n File \"/home/runner/work/django-snowflake/django-snowflake/django_repo/django/db/backends/utils.py\", line 79, in execute\n return self._execute_with_wrappers(\n ^^^^^^^^^^^^^^^^^\n File \"/home/runner/work/django-snowflake/django-snowflake/django_repo/django/db/backends/utils.py\", line 92, in _execute_with_wrappers\n return executor(sql, params, many, context)\n ^^^^^^^^^^^^^^^^^\n File \"/home/runner/work/django-snowflake/django-snowflake/django_repo/django/db/backends/utils.py\", line 99, in _execute\n self.db.validate_no_broken_transaction()\n ^^^^^^^^^^^^^^^^^\n File \"/home/runner/work/django-snowflake/django-snowflake/django_repo/django/db/backends/base/base.py\", line 521, in validate_no_broken_transaction\n raise TransactionManagementError(\n ^^^^^^^^^^^^^^^^^\ndjango.db.transaction.TransactionManagementError: An error occurred in the current transaction. You can't execute queries until the end of the 'atomic' block.\n```\nPossible solutions:\n- Skip this block if `DatabaseFeatures.uses_savepoints=False`.\n- Move this block to a separate test.", "path": "tests/proxy_models/tests.py", "line": 122, "side": "RIGHT", "created_at": "2026-02-10T18:31:55+00:00" }, { "id": 2790603115, "user": "user_194c2ef4033e", "body": "The whole test was a bit overloaded, so I split each thing being tested into separate tests: https://github.com/[USER_REDACTED]ngo/django/pull/20669", "path": "tests/proxy_models/tests.py", "line": 122, "side": "RIGHT", "created_at": "2026-02-10T22:30:39+00:00" } ], "meta": { "languages": [ "py" ], "touches_tests": true, "review_state_summary": { "COMMENTED": 8, "APPROVED": 1 }, "meaningful_comment_count": 8, "has_approval": true, "has_changes_requested": false, "total_review_comments": 9 } } { "_id": "14833de8c3bb015a", "_schema_version": "1.0", "_cleaned_at": "2026-02-12T07:46:51.525778+00:00", "repo": "django/django", "repo_url": "https://github.com/django/django", "license_name": "BSD 3-Clause \"New\" or \"Revised\" License", "license_spdx": "BSD-3-Clause", "pr_number": 20634, "title": "Fixed #34352 -- Unified terms in Signals docs.", "body": "#### Trac ticket number\n\n\n\nticket-34352\n\n#### Branch description\nremoved callback from the signals document for consistency & to avoid confusion\n\n#### AI [NAME_REDACTED] (REQUIRED)\n\n- [x] **No AI tools were used** in preparing this PR.\n- [ ] **If AI tools were used**, I have disclosed which ones, and fully reviewed and verified their output.\n\n#### Checklist\n- [x] This PR follows the [contribution guidelines](https://docs.djangoproject.com/en/stable/internals/contributing/writing-code/submitting-patches/).\n- [x] This PR **does not** disclose a security vulnerability (see [vulnerability reporting](https://docs.djangoproject.com/en/stable/internals/security/)).\n- [x] This PR targets the `main` branch. \n- [x] The commit message is written in past tense, mentions the ticket number, and ends with a period.\n- [x] I have checked the \"Has patch\" ticket flag in the Trac system.\n- [ ] I have added or updated relevant tests.\n- [x] I have added or updated relevant docs, including release notes if applicable.\n- [ ] I have attached screenshots in both light and dark modes for any UI changes.", "author": "user_de355a7b8f22", "created_at": "2026-02-03T08:20:37+00:00", "merged_at": "2026-02-10T20:31:59+00:00", "base_branch": "main", "head_branch": "ticket_34352", "additions": 15, "deletions": 15, "changed_files": 1, "files": [ { "filename": "docs/topics/signals.txt", "status": "modified", "additions": 15, "deletions": 15, "changes": 30, "patch": "@@ -18,15 +18,15 @@ changes::\n from django.core.signals import setting_changed\n \n \n- def my_callback(sender, **kwargs):\n+ def my_receiver(sender, **kwargs):\n print(\"Setting changed!\")\n \n \n class MyAppConfig(AppConfig):\n ...\n \n def ready(self):\n- setting_changed.connect(my_callback)\n+ setting_changed.connect(my_receiver)\n \n Django's :doc:`built-in signals ` let user code get notified of\n certain actions.\n@@ -58,7 +58,7 @@ the order they were registered.\n :param sender: Specifies a particular sender to receive signals from. See\n :ref:`connecting-to-specific-signals` for more information.\n \n- :param weak: Django stores signal handlers as weak references by\n+ :param weak: Django stores signal receivers as weak references by\n default. Thus, if your receiver is a local function, it may be\n garbage collected. To prevent this, pass ``weak=False`` when you call\n the signal's ``connect()`` method.\n@@ -79,19 +79,19 @@ Receiver functions\n First, we need to define a receiver function. A receiver can be any Python\n function or method::\n \n- def my_callback(sender, **kwargs):\n+ def my_receiver(sender, **kwargs):\n print(\"Request finished!\")\n \n Notice that the function takes a ``sender`` argument, along with wildcard\n-keyword arguments (``**kwargs``); all signal handlers must take these\n+keyword arguments (``**kwargs``); all signal receivers must take these\n arguments.\n \n We'll look at senders :ref:`a bit later `, but\n right now look at the ``**kwargs`` argument. All signals send keyword\n arguments, and may change those keyword arguments at any time. In the case of\n :data:`~django.core.signals.request_finished`, it's documented as sending no\n arguments, which means we might be tempted to write our signal handling as\n-``my_callback(sender)``.\n+``my_receiver(sender)``.\n \n This would be wrong -- in fact, Django will throw an error if you do so. That's\n because at any point arguments could get added to the signal and your receiver\n@@ -100,7 +100,7 @@ must be able to handle those new arguments.\n Receivers may also be asynchronous functions, with the same signature but\n declared using ``async def``::\n \n- async def my_callback(sender, **kwargs):\n+ async def my_receiver(sender, **kwargs):\n await asyncio.sleep(5)\n print(\"Request finished!\")\n \n@@ -118,7 +118,7 @@ manual connect route::\n \n from django.core.signals import request_finished\n \n- request_finished.connect(my_callback)\n+ request_finished.connect(my_receiver)\n \n Alternatively, you can use a :func:`receiver` decorator:\n \n@@ -135,24 +135,24 @@ Here's how you connect with the decorator::\n \n \n [USER_REDACTED](request_finished)\n- def my_callback(sender, **kwargs):\n+ def my_receiver(sender, **kwargs):\n print(\"Request finished!\")\n \n-Now, our ``my_callback`` function will be called each time a request finishes.\n+Now, our ``my_receiver`` function will be called each time a request finishes.\n \n .. admonition:: Where should this code live?\n \n Strictly speaking, signal handling and registration code can live anywhere\n you like, although it's recommended to avoid the application's root module\n and its ``models`` module to minimize side-effects of importing code.\n \n- In practice, signal handlers are usually defined in a ``signals``\n+ In practice, signal receivers are usually defined in a ``signals``\n submodule of the application they relate to. Signal receivers are\n connected in the :meth:`~django.apps.AppConfig.ready` method of your\n application :ref:`configuration class `. If\n you're using the :func:`receiver` decorator, import the ``signals``\n submodule inside :meth:`~django.apps.AppConfig.ready`, this will implicitly\n- connect signal handlers::\n+ connect signal receivers::\n \n from django.apps import AppConfig\n from django.core.signals import request_finished\n@@ -162,11 +162,11 @@ Now, our ``my_callback`` function will be called each time a request finishes.\n ...\n \n def ready(self):\n- # Implicitly connect signal handlers decorated with [USER_REDACTED].\n+ # Implicitly connect signal receivers decorated with [USER_REDACTED].\n from . import signals\n \n # Explicitly connect a signal handler.\n- request_finished.connect(signals.my_callback)\n+ request_finished.connect(signals.my_receiver)\n \n .. note::\n \n@@ -228,7 +228,7 @@ bound to the signal once for each unique ``dispatch_uid`` value::\n \n from django.core.signals import request_finished\n \n- request_finished.connect(my_callback, dispatch_uid=\"my_unique_identifier\")\n+ request_finished.connect(my_receiver, dispatch_uid=\"my_unique_identifier\")\n \n .. _defining-and-sending-signals:" } ], "reviews": [ { "id": 3758065387, "user": "user_3a67c55598c5", "state": "COMMENTED", "body": null, "submitted_at": "2026-02-05T16:13:55+00:00" }, { "id": 3781413724, "user": "user_3a67c55598c5", "state": "APPROVED", "body": "👍", "submitted_at": "2026-02-10T20:29:46+00:00" } ], "review_comments": [ { "id": 2769972672, "user": "user_3a67c55598c5", "body": "I would make a single exception here and continue to use \"callback\", as otherwise, we're explaining the term X by [NAME_REDACTED] By using a synonym, there's a chance a user can rely on some prior knowledge or gain new knowledge.\n\nAnother possibility is to use both, e.g. \"The receiver (callback) function that will ...\"", "path": "docs/topics/signals.txt", "line": null, "side": "RIGHT", "created_at": "2026-02-05T16:10:45+00:00" } ], "meta": { "languages": [ "txt" ], "touches_tests": false, "review_state_summary": { "COMMENTED": 1, "APPROVED": 1 }, "meaningful_comment_count": 1, "has_approval": true, "has_changes_requested": false, "total_review_comments": 1 } } { "_id": "7e0ad94f091976fe", "_schema_version": "1.0", "_cleaned_at": "2026-02-12T07:46:51.526779+00:00", "repo": "django/django", "repo_url": "https://github.com/django/django", "license_name": "BSD 3-Clause \"New\" or \"Revised\" License", "license_spdx": "BSD-3-Clause", "pr_number": 20628, "title": "Fixed #36890 -- [NAME_REDACTED](distinct=True) on SQLite with the default delimiter.", "body": "#### Trac ticket number\n\n\n\nticket-36890\n\n#### Branch description\nCurrently, the generic StringAgg function raises an error on SQLite when distinct=True\n\nThis change enables support for distinct aggregation on SQLite by [NAME_REDACTED] in the generated SQL when it matches the default comma.\n\n#### AI [NAME_REDACTED] (REQUIRED)\n\n- [ ] **No AI tools were used** in preparing this PR.\n- [X] **If AI tools were used**, I have disclosed which ones, and fully reviewed and verified their output.\n\nI used [NAME_REDACTED] to assist with writing tests.\n\n#### Checklist\n- [X] This PR follows the [contribution guidelines](https://docs.djangoproject.com/en/stable/internals/contributing/writing-code/submitting-patches/).\n- [X] This PR **does not** disclose a security vulnerability (see [vulnerability reporting](https://docs.djangoproject.com/en/stable/internals/security/)).\n- [X] This PR targets the `main` branch. \n- [X] The commit message is written in past tense, mentions the ticket number, and ends with a period.\n- [x] I have checked the \"Has patch\" ticket flag in the Trac system.\n- [X] I have added or updated relevant tests.\n- [ ] I have added or updated relevant docs, including release notes if applicable.\n- [ ] I have attached screenshots in both light and dark modes for any UI changes.", "author": "user_95f516637e24", "created_at": "2026-02-02T08:23:43+00:00", "merged_at": "2026-02-10T21:47:45+00:00", "base_branch": "main", "head_branch": "ticket-36890", "additions": 41, "deletions": 2, "changed_files": 4, "files": [ { "filename": "django/db/models/aggregates.py", "status": "modified", "additions": 18, "deletions": 0, "changes": 18, "patch": "@@ -369,6 +369,24 @@ def as_mysql(self, compiler, connection, **extra_context):\n return sql, (*params, *delimiter_params)\n \n def as_sqlite(self, compiler, connection, **extra_context):\n+ if (\n+ self.distinct\n+ and isinstance(self.delimiter.value, Value)\n+ and self.delimiter.value.value == \",\"\n+ ):\n+ clone = self.copy()\n+ source_expressions = clone.get_source_expressions()\n+ clone.set_source_expressions(\n+ source_expressions[:1] + source_expressions[2:]\n+ )\n+\n+ return clone.as_sql(\n+ compiler,\n+ connection,\n+ function=\"GROUP_CONCAT\",\n+ **extra_context,\n+ )\n+\n if connection.get_database_version() < (3, 44):\n return self.as_sql(\n compiler," }, { "filename": "docs/ref/models/querysets.txt", "status": "modified", "additions": 8, "deletions": 1, "changes": 9, "patch": "@@ -4175,7 +4175,14 @@ by [NAME_REDACTED]\n .. attribute:: delimiter\n \n A ``Value`` or expression representing the string that should separate\n- each of the values. For example, ``Value(\",\")``.\n+ each of the values. For example, ``Value(\",\")``. (On SQLite, the\n+ literal delimiter ``Value(\",\")`` is the only delimiter compatible with\n+ ``distinct=True``.)\n+\n+ .. versionchanged:: 6.1\n+\n+ Support for using ``distinct=True`` with a delimiter of\n+ ``Value(\",\")`` on SQLite was added.\n \n Query-related tools\n ===================" }, { "filename": "docs/releases/6.1.txt", "status": "modified", "additions": 3, "deletions": 0, "changes": 3, "patch": "@@ -284,6 +284,9 @@ Models\n * The :data:`~django.db.models.signals.m2m_changed` signal now receives a\n ``raw`` argument.\n \n+* :class:`~django.db.models.StringAgg` now supports ``distinct=True`` on SQLite\n+ when using the default delimiter ``Value(\",\")`` only.\n+\n Pagination\n ~~~~~~~~~~" }, { "filename": "tests/aggregation/tests.py", "status": "modified", "additions": 12, "deletions": 1, "changes": 13, "patch": "@@ -3,6 +3,7 @@\n import re\n from decimal import Decimal\n from itertools import chain\n+from unittest import skipUnless\n \n from django.core.exceptions import FieldError\n from django.db import NotSupportedError, connection\n@@ -579,6 +580,16 @@ def test_distinct_on_stringagg(self):\n )\n self.assertCountEqual(books[\"ratings\"].split(\",\"), [\"3\", \"4\", \"4.5\", \"5\"])\n \n+ [USER_REDACTED](connection.vendor == \"sqlite\", \"Special default case for SQLite.\")\n+ def test_distinct_on_stringagg_sqlite_special_case(self):\n+ \"\"\"\n+ Value(\",\") is the only delimiter usable on SQLite with distinct=True.\n+ \"\"\"\n+ books = Book.objects.aggregate(\n+ ratings=StringAgg(Cast(F(\"rating\"), CharField()), Value(\",\"), distinct=True)\n+ )\n+ self.assertCountEqual(books[\"ratings\"].split(\",\"), [\"3.0\", \"4.0\", \"4.5\", \"5.0\"])\n+\n [USER_REDACTED](\"supports_aggregate_distinct_multiple_argument\")\n def test_raises_error_on_multiple_argument_distinct(self):\n message = (\n@@ -589,7 +600,7 @@ def test_raises_error_on_multiple_argument_distinct(self):\n Book.objects.aggregate(\n ratings=StringAgg(\n Cast(F(\"rating\"), CharField()),\n- Value(\",\"),\n+ Value(\";\"),\n distinct=True,\n )\n )" } ], "reviews": [ { "id": 3740360959, "user": "user_cdda8932ec17", "state": "COMMENTED", "body": null, "submitted_at": "2026-02-02T15:56:43+00:00" }, { "id": 3775494074, "user": "user_3a67c55598c5", "state": "COMMENTED", "body": null, "submitted_at": "2026-02-09T21:35:18+00:00" }, { "id": 3775592950, "user": "user_3a67c55598c5", "state": "APPROVED", "body": "Thanks 👍", "submitted_at": "2026-02-09T21:54:28+00:00" }, { "id": 3775608120, "user": "user_3a67c55598c5", "state": "COMMENTED", "body": null, "submitted_at": "2026-02-09T21:58:51+00:00" } ], "review_comments": [ { "id": 2755046559, "user": "user_cdda8932ec17", "body": "This lacks `order_by` and `filter`", "path": "django/db/models/aggregates.py", "line": null, "side": "RIGHT", "created_at": "2026-02-02T15:55:32+00:00" }, { "id": 2755051293, "user": "user_cdda8932ec17", "body": "```suggestion\n if (\n self.distinct\n and isinstance(self.delimiter.value, Value)\n and self.delimiter.value.value == \",\"\n ):\n return ...\n```", "path": "django/db/models/aggregates.py", "line": null, "side": "RIGHT", "created_at": "2026-02-02T15:56:28+00:00" }, { "id": 2784636581, "user": "user_3a67c55598c5", "body": "It's too bad we can't provide a better hint for SQLite users in this case, but I don't know what we can do about it without departing from our existing patterns.", "path": "tests/aggregation/tests.py", "line": 603, "side": "RIGHT", "created_at": "2026-02-09T21:35:18+00:00" }, { "id": 2784723845, "user": "user_3a67c55598c5", "body": "Simon's prior feedback for you was to avoid asserting over the exact stringified values, but once I realized that we _don't_ want this test to run on all databases (what about other databases besides SQLite where supports_aggregate_distinct_multiple_argument is also False, but the default delimiter trick may not work), I realized we were only testing a SQLite specific case.\n\nGiven that, I shuffled this test location and made it as parallel as possible to the prior one.", "path": "tests/aggregation/tests.py", "line": 591, "side": "RIGHT", "created_at": "2026-02-09T21:58:51+00:00" } ], "meta": { "languages": [ "py", "txt" ], "touches_tests": true, "review_state_summary": { "COMMENTED": 3, "APPROVED": 1 }, "meaningful_comment_count": 4, "has_approval": true, "has_changes_requested": false, "total_review_comments": 4 } } { "_id": "de327d05ef61056e", "_schema_version": "1.0", "_cleaned_at": "2026-02-12T07:46:51.527778+00:00", "repo": "django/django", "repo_url": "https://github.com/django/django", "license_name": "BSD 3-Clause \"New\" or \"Revised\" License", "license_spdx": "BSD-3-Clause", "pr_number": 20614, "title": "Fixed #36893 -- Serialized elidable kwarg for RunSQL and RunPython operations.", "body": "#### Trac ticket number\n\n\n\nticket-36893\n\n#### Branch description\n\nFixed an issue where `elidable=True` was not being serialized for Run-SQL and Run-Python operations which caused these operations to lose their elidable status when written to a migration file (e.g., during squashing), reverting to the default `False`.\n\n-Updated deconstruct() for both Run-SQL and Run-Python to correctly include 'elidable' keyword when set to 'True' \n-[NAME_REDACTED] are test_run_sql_elidable , test_run_python_elidable and test_operations.py\n\n#### AI [NAME_REDACTED] (REQUIRED)\n\n- [ ] **No AI tools were used** in preparing this PR.\n- [x] **If AI tools were used**, I have disclosed which ones, and fully reviewed and verified their output.\nAssistance provided by [NAME_REDACTED] I used the agent to understand the issue, implement the fix, and add regression tests.\n#### Checklist\n- [x] This PR follows the [contribution guidelines](https://docs.djangoproject.com/en/stable/internals/contributing/writing-code/submitting-patches/).\n- [x] This PR **does not** disclose a security vulnerability (see [vulnerability reporting](https://docs.djangoproject.com/en/stable/internals/security/)).\n- [x] This PR targets the `main` branch. \n- [x] The commit message is written in past tense, mentions the ticket number, and ends with a period.\n- [x] I have checked the \"Has patch\" ticket flag in the Trac system.\n- [ ] I have added or updated relevant tests.\n- [ ] I have added or updated relevant docs, including release notes if applicable.\n- [ ] I have attached screenshots in both light and dark modes for any UI changes.", "author": "user_ff4c0b4e0209", "created_at": "2026-01-30T05:32:49+00:00", "merged_at": "2026-02-03T02:05:44+00:00", "base_branch": "main", "head_branch": "ticket_36893_fix_elidable_serialization", "additions": 12, "deletions": 0, "changed_files": 2, "files": [ { "filename": "django/db/migrations/operations/special.py", "status": "modified", "additions": 4, "deletions": 0, "changes": 4, "patch": "@@ -93,6 +93,8 @@ def deconstruct(self):\n kwargs[\"state_operations\"] = self.state_operations\n if self.hints:\n kwargs[\"hints\"] = self.hints\n+ if self.elidable:\n+ kwargs[\"elidable\"] = self.elidable\n return (self.__class__.__qualname__, [], kwargs)\n \n [USER_REDACTED]\n@@ -173,6 +175,8 @@ def deconstruct(self):\n kwargs[\"atomic\"] = self.atomic\n if self.hints:\n kwargs[\"hints\"] = self.hints\n+ if self.elidable:\n+ kwargs[\"elidable\"] = self.elidable\n return (self.__class__.__qualname__, [], kwargs)\n \n [USER_REDACTED]" }, { "filename": "tests/migrations/test_operations.py", "status": "modified", "additions": 8, "deletions": 0, "changes": 8, "patch": "@@ -5536,6 +5536,10 @@ def test_run_sql(self):\n elidable_operation = migrations.RunSQL(\"SELECT 1 FROM void;\", elidable=True)\n self.assertEqual(elidable_operation.reduce(operation, []), [operation])\n \n+ # Test elidable deconstruction\n+ definition = elidable_operation.deconstruct()\n+ self.assertIs(definition[2][\"elidable\"], True)\n+\n def test_run_sql_params(self):\n \"\"\"\n #23426 - RunSQL should accept parameters.\n@@ -5789,6 +5793,10 @@ def create_shetlandponies(models, schema_editor):\n elidable_operation = migrations.RunPython(inner_method, elidable=True)\n self.assertEqual(elidable_operation.reduce(operation, []), [operation])\n \n+ # Test elidable deconstruction\n+ definition = elidable_operation.deconstruct()\n+ self.assertIs(definition[2][\"elidable\"], True)\n+\n def test_run_python_invalid_reverse_code(self):\n msg = \"RunPython must be supplied with callable arguments\"\n with self.assertRaisesMessage(ValueError, msg):" } ], "reviews": [ { "id": 3726671276, "user": "user_bc02c4664e11", "state": "COMMENTED", "body": null, "submitted_at": "2026-01-30T06:51:36+00:00" }, { "id": 3726710585, "user": "user_ff4c0b4e0209", "state": "COMMENTED", "body": null, "submitted_at": "2026-01-30T07:01:14+00:00" }, { "id": 3728783340, "user": "user_3a67c55598c5", "state": "COMMENTED", "body": "Thanks [USER_REDACTED] and [USER_REDACTED] for the review.\n\nVery nearly there, one small cleanup suggestion. And please update the PR title to match the commit. Thanks.", "submitted_at": "2026-01-30T14:51:56+00:00" }, { "id": 3741227562, "user": "user_3a67c55598c5", "state": "APPROVED", "body": "Thanks 👍", "submitted_at": "2026-02-02T18:33:32+00:00" } ], "review_comments": [ { "id": 2744906431, "user": "user_bc02c4664e11", "body": "Probs don't need an explicit test for just `elidable` param.\nIs there already a test somewhere that checks _all_ serialized params for RunSQL? I'd probs ensure we have one that does that, and include elidable as part of its check.", "path": "tests/migrations/test_operations.py", "line": null, "side": "RIGHT", "created_at": "2026-01-30T06:51:36+00:00" }, { "id": 2744939359, "user": "user_ff4c0b4e0209", "body": "Thanks for the feedback! I've updated the PR to remove the separate test case. I found that test_run_sqland and test_run_python\nwere already creating elidable operations for reduction testing, so I added assertions there to verify they also deconstruct correctly with the elidable keyword.", "path": "tests/migrations/test_operations.py", "line": null, "side": "RIGHT", "created_at": "2026-01-30T07:01:14+00:00" }, { "id": 2746658035, "user": "user_3a67c55598c5", "body": "Similar change here.", "path": "tests/migrations/test_operations.py", "line": null, "side": "RIGHT", "created_at": "2026-01-30T14:50:22+00:00" }, { "id": 2746661936, "user": "user_3a67c55598c5", "body": "One assertion for this is fine, also please use `assertIs` for first-party values:\n```suggestion\n self.assertIs(definition[2][\"elidable\"], True)\n```", "path": "tests/migrations/test_operations.py", "line": null, "side": "RIGHT", "created_at": "2026-01-30T14:51:21+00:00" } ], "meta": { "languages": [ "py" ], "touches_tests": true, "review_state_summary": { "COMMENTED": 3, "APPROVED": 1 }, "meaningful_comment_count": 4, "has_approval": true, "has_changes_requested": false, "total_review_comments": 4 } } { "_id": "51fcd4d9cc3a5a06", "_schema_version": "1.0", "_cleaned_at": "2026-02-12T07:46:51.529432+00:00", "repo": "django/django", "repo_url": "https://github.com/django/django", "license_name": "BSD 3-Clause \"New\" or \"Revised\" License", "license_spdx": "BSD-3-Clause", "pr_number": 20610, "title": "Fixed spell checks in GH docs workflow.", "body": "#### Branch description\nThe spelling check job was passing even with spelling errors because\nthe system spell checker (`aspell`) was not installed on the [NAME_REDACTED] runner. While `sphinxcontrib.spelling` and `PyEnchant` were\ninstalled via pip, they require a system-level spell checker backend\nto function.\n\nOnce installed, these errors were reported:\n\n```\nWARNING: internals/security.txt:50: : Spell check: runnable: Include a runnable proof of concept.\nWARNING: ref/contrib/postgres/search.txt:292: : Spell check: lexeme: an untrusted source. The content of each lexeme is escaped so that any.\nWARNING: ref/contrib/postgres/search.txt:295: : Spell check: lexemes: You can combine lexemes with other lexemes using the .\nWARNING: ref/contrib/postgres/search.txt:295: : Spell check: lexemes: You can combine lexemes with other lexemes using the .\nWARNING: ref/contrib/postgres/search.txt:314: : Spell check: Lexeme: Lexeme objects also support term weighting and prefixes:.\nWARNING: ref/models/database-functions.txt:1897: : Spell check: ai: 23ai/26ai (23.9) or later..\nWARNING: ref/models/database-functions.txt:1897: : Spell check: ai: 23ai/26ai (23.9) or later..\nWARNING: ref/models/expressions.txt:439: : Spell check: positionally: can be supplied positionally or only by keyword. For.\nWARNING: ref/models/fields.txt:1339: : Spell check: ai: PostgreSQL < 18 only supports persisted columns. Oracle < 23ai/26ai (23.7).\nWARNING: ref/models/fields.txt:1339: : Spell check: ai: PostgreSQL < 18 only supports persisted columns. Oracle < 23ai/26ai (23.7).\nWARNING: ref/models/fields.txt:1344: : Spell check: ai: s was added on Oracle 23ai/26ai.\nWARNING: ref/models/fields.txt:1344: : Spell check: ai: s was added on Oracle 23ai/26ai.\nWARNING: releases/4.2.21.txt:24: : Spell check: unclosed: exception if it encounters an unusually large number of unclosed opening tags..\nWARNING: releases/5.1.9.txt:24: : Spell check: unclosed: exception if it encounters an unusually large number of unclosed opening tags..\nWARNING: releases/5.2.1.txt:24: : Spell check: unclosed: exception if it encounters an unusually large number of unclosed opening tags..\nWARNING: releases/6.1.txt:244: : Spell check: mistyped: suggestions for mistyped subcommand names and argument choices..\nWARNING: releases/6.1.txt:281: : Spell check: ai: Oracle 23ai/26ai (23.7+)..\nWARNING: releases/6.1.txt:281: : Spell check: ai: Oracle 23ai/26ai (23.7+)..\nWARNING: releases/6.1.txt:343: : Spell check: durations: durations expressed in weeks (.\nWARNING: Found 19 misspelled words\nbuild finished with problems, 20 warnings (with warnings treated as errors).\n```\n\n#### AI [NAME_REDACTED] (REQUIRED)\n\n- [ ] **No AI tools were used** in preparing this PR.\n- [X] **If AI tools were used**, I have disclosed which ones, and fully reviewed and verified their output.\n\nI have used [NAME_REDACTED] with model Sonnet 4.5 for debugging the root cause of this issue.\n\n#### Checklist\n- [X] This PR follows the [contribution guidelines](https://docs.djangoproject.com/en/stable/internals/contributing/writing-code/submitting-patches/).\n- [X] This PR **does not** disclose a security vulnerability (see [vulnerability reporting](https://docs.djangoproject.com/en/stable/internals/security/)).\n- [X] This PR targets the `main` branch. \n- [X] The commit message is written in past tense, mentions the ticket number, and ends with a period.", "author": "user_00dac951cdbf", "created_at": "2026-01-29T02:02:12+00:00", "merged_at": "2026-01-29T14:20:12+00:00", "base_branch": "main", "head_branch": "fix-spelling-ubuntu-noble", "additions": 18, "deletions": 11, "changed_files": 6, "files": [ { "filename": ".github/workflows/docs.yml", "status": "modified", "additions": 2, "deletions": 0, "changes": 2, "patch": "@@ -35,6 +35,8 @@ jobs:\n python-version: '3.14'\n cache: 'pip'\n cache-dependency-path: 'docs/requirements.txt'\n+ - name: Install system spell checker\n+ run: sudo apt update && sudo apt install -y aspell aspell-en\n - run: python -m pip install -r docs/requirements.txt\n - name: Build docs\n run: |" }, { "filename": "docs/internals/contributing/writing-documentation.txt", "status": "modified", "additions": 3, "deletions": 2, "changes": 5, "patch": "@@ -178,8 +178,9 @@ Spelling check\n ~~~~~~~~~~~~~~\n \n Before you commit your docs, it's a good idea to run the spelling checker.\n-You'll need to install :pypi:`sphinxcontrib-spelling` first. Then from the\n-``docs`` directory, run:\n+You'll need to install :pypi:`sphinxcontrib-spelling` first. The spell checker\n+also requires a system-level spell checking backend such as `Aspell\n+`__. Then from the ``docs`` directory, run:\n \n .. console::" }, { "filename": "docs/internals/security.txt", "status": "modified", "additions": 2, "deletions": 2, "changes": 4, "patch": "@@ -46,8 +46,8 @@ the industry-standard 90 days. Confirmed vulnerabilities with a\n Reporting guidelines\n --------------------\n \n-Include a runnable proof of concept\n-~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n+Include a working proof of concept\n+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n \n Please privately share a minimal Django project or code snippet that\n demonstrates the potential vulnerability. Include clear instructions on how to" }, { "filename": "docs/ref/models/expressions.txt", "status": "modified", "additions": 5, "deletions": 5, "changes": 10, "patch": "@@ -438,11 +438,11 @@ return type.\n \n Built-in database functions (such as\n :class:`~django.db.models.functions.Cast`) vary in whether arguments such\n- as ``output_field`` can be supplied positionally or only by keyword. For\n- ``output_field`` and several other cases, the input ultimately reaches\n- ``Func()`` as a keyword argument, so the advice to avoid constructing\n- keyword arguments from untrusted user input applies as equally to these\n- arguments as it does to ``**extra``.\n+ as ``output_field`` can be supplied as positional arguments or only by\n+ keyword. For ``output_field`` and several other cases, the input ultimately\n+ reaches ``Func()`` as a keyword argument, so the advice to avoid\n+ constructing keyword arguments from untrusted user input applies as equally\n+ to these arguments as it does to ``**extra``.\n \n ``Aggregate()`` expressions\n ---------------------------" }, { "filename": "docs/releases/6.1.txt", "status": "modified", "additions": 2, "deletions": 2, "changes": 4, "patch": "@@ -242,7 +242,7 @@ [NAME_REDACTED]\n \n * Management commands now set :class:`~argparse.ArgumentParser`\\'s\n ``suggest_on_error`` argument to ``True`` by [NAME_REDACTED] 3.14, enabling\n- suggestions for mistyped subcommand names and argument choices.\n+ suggestions for incorrectly typed subcommand names and argument choices.\n \n * The :djadmin:`loaddata` command now calls\n :data:`~django.db.models.signals.m2m_changed` signals with ``raw=True`` when\n@@ -340,7 +340,7 @@ Utilities\n ~~~~~~~~~\n \n * :func:`~django.utils.dateparse.parse_duration` now supports ISO 8601\n- durations expressed in weeks (``PnW``).\n+ time periods expressed in weeks (``PnW``).\n \n Validators\n ~~~~~~~~~~" }, { "filename": "docs/spelling_wordlist", "status": "modified", "additions": 4, "deletions": 0, "changes": 4, "patch": "@@ -4,6 +4,7 @@ accessors\n Aceh\n admindocs\n affordances\n+ai\n [NAME_REDACTED]\n allowlist\n@@ -245,6 +246,8 @@ kwargs\n Kyrgyz\n latin\n lawrence\n+lexeme\n+lexemes\n Libera\n lifecycle\n lifecycles\n@@ -531,6 +534,7 @@ unapplied\n unapplying\n uncategorized\n unclaim\n+unclosed\n uncopyable\n unencoded\n unencrypted" } ], "reviews": [ { "id": 3722192099, "user": "user_3a67c55598c5", "state": "APPROVED", "body": null, "submitted_at": "2026-01-29T11:55:08+00:00" }, { "id": 3722594201, "user": "user_00dac951cdbf", "state": "COMMENTED", "body": null, "submitted_at": "2026-01-29T13:06:20+00:00" }, { "id": 3722595929, "user": "user_00dac951cdbf", "state": "COMMENTED", "body": null, "submitted_at": "2026-01-29T13:06:47+00:00" } ], "review_comments": [ { "id": 2741226263, "user": "user_3a67c55598c5", "body": "positional parameters -> positional arguments", "path": "docs/ref/models/expressions.txt", "line": null, "side": "RIGHT", "created_at": "2026-01-29T11:40:29+00:00" }, { "id": 2741275863, "user": "user_3a67c55598c5", "body": "Wonderful. Are you up for updating the section on this in writing-documentation.txt‎ that aspell is required?\n\nOn mac, sphinxcontrib.spelling exits with an instruction to install enchant, which, at least via homebrew, pulls in aspell. Guess not on linux?", "path": ".github/workflows/docs.yml", "line": null, "side": "RIGHT", "created_at": "2026-01-29T11:54:48+00:00" }, { "id": 2741556409, "user": "user_00dac951cdbf", "body": "Applied, thanks!", "path": "docs/ref/models/expressions.txt", "line": null, "side": "RIGHT", "created_at": "2026-01-29T13:06:20+00:00" }, { "id": 2741558158, "user": "user_00dac951cdbf", "body": "I added a new commit with this adding. Good call! :dart:", "path": ".github/workflows/docs.yml", "line": null, "side": "RIGHT", "created_at": "2026-01-29T13:06:47+00:00" } ], "meta": { "languages": [ "txt", "yml" ], "touches_tests": false, "review_state_summary": { "APPROVED": 1, "COMMENTED": 2 }, "meaningful_comment_count": 4, "has_approval": true, "has_changes_requested": false, "total_review_comments": 4 } } { "_id": "9d5f16bd4ce84b3f", "_schema_version": "1.0", "_cleaned_at": "2026-02-12T07:46:51.533485+00:00", "repo": "django/django", "repo_url": "https://github.com/django/django", "license_name": "BSD 3-Clause \"New\" or \"Revised\" License", "license_spdx": "BSD-3-Clause", "pr_number": 20599, "title": "Added documentation on reviewing patches.", "body": "This was primarily sourced from [NAME_REDACTED] talk, \"Django needs you! (to do code review)\"\nSource: https://www.youtube.com/watch?v=MBqampUQ1o0\n\n#### Trac ticket number\n\n\n\nN/A\n\n#### Branch description\nThis adds a brief overview of how to review patches to the documentation. Having something defined for doing code reviews should make this part of the software development process more accessible to other developers.\n\n#### AI [NAME_REDACTED] (REQUIRED)\n\n- [x] **No AI tools were used** in preparing this PR.\n- [ ] **If AI tools were used**, I have disclosed which ones, and fully reviewed and verified their output.\n\n#### Checklist\n- [x] This PR follows the [contribution guidelines](https://docs.djangoproject.com/en/stable/internals/contributing/writing-code/submitting-patches/).\n- [x] This PR **does not** disclose a security vulnerability (see [vulnerability reporting](https://docs.djangoproject.com/en/stable/internals/security/)).\n- [x] This PR targets the `main` branch. \n- [x] The commit message is written in past tense, mentions the ticket number, and ends with a period.\n- [ ] I have checked the \"Has patch\" ticket flag in the Trac system.\n- [ ] I have added or updated relevant tests.\n- [x] I have added or updated relevant docs, including release notes if applicable.\n- [ ] I have attached screenshots in both light and dark modes for any UI changes.", "author": "user_6b79e26637e6", "created_at": "2026-01-27T17:44:58+00:00", "merged_at": "2026-01-31T01:48:59+00:00", "base_branch": "main", "head_branch": "code-review-documentation", "additions": 112, "deletions": 6, "changed_files": 3, "files": [ { "filename": "docs/internals/contributing/triaging-tickets.txt", "status": "modified", "additions": 109, "deletions": 6, "changes": 115, "patch": "@@ -63,15 +63,19 @@ vote of the :ref:`[NAME_REDACTED] `.\n * Bug fixers: anyone can contribute by opening a pull request and working on a\n solution for a ticket.\n \n-* Reviewers: anyone can review pull requests and suggest improvements.\n+* Reviewers: anyone can :ref:`review pull requests ` and\n+ suggest improvements.\n \n * Mergers: people with commit access who make the final decision to merge a\n change.\n \n-[NAME_REDACTED] system is intentionally open to the public, and anyone can help by\n-working on tickets. Django is a community project, and we encourage\n-:ref:`triage and collaboration by [NAME_REDACTED]\n-`. This could be you!\n+.. admonition:: When we say anyone, we mean you!\n+\n+ [NAME_REDACTED] system and GitHub repositories are intentionally open to the\n+ public. Anyone can help by [NAME_REDACTED], triaging tickets and\n+ reviewing changes. Django is a community project, and we encourage\n+ :ref:`triage and collaboration by [NAME_REDACTED]\n+ `. We truly want you to help!\n \n For example, here's the typical lifecycle of a ticket:\n \n@@ -414,7 +418,7 @@ the ticket database:\n * Please **don't** promote your own tickets to \"Ready for checkin\". You\n may mark other people's tickets that you've reviewed as \"Ready for\n checkin\", but you should get at minimum one other community member to\n- review a patch that you submit.\n+ :ref:`review a patch ` that you submit.\n \n * Please **don't** reverse a decision without posting a message to the\n `[NAME_REDACTED]`_ to find consensus.\n@@ -484,3 +488,102 @@ commit where the test fails.\n Now, report your results on the Trac ticket, and please include the regression\n test as an attachment. When someone writes a fix for the bug, they'll already\n have your test as a starting point.\n+\n+.. _reviewing-patches:\n+\n+Reviewing patches\n+=================\n+\n+A great way to learn the Django codebase is to help review patches. It allows\n+you to focus on a fixed scope of Django with a particular perspective. Plus,\n+Django tends to receive more patches than it can review which causes the\n+`review queue`_ to build up. Contributors can help Django tremendously by\n+reviewing patches.\n+\n+The `review queue`_ is defined by [NAME_REDACTED]_ that are in the \"Accepted\"\n+state with the flag \"has patch\" set and the flags \"patch needs improvement\",\n+\"needs tests\" and \"needs documentation\" unset. There is also a set of\n+`Pull Requests in GitHub with the \"no ticket\" label`_ that can be reviewed.\n+\n+Code review process\n+-------------------\n+\n+The general process to reviewing a patch for Django is as follows:\n+\n+1. Pick a patch to review. This can be from the `review queue`_ or the\n+ `Pull Requests in GitHub with the \"no ticket\" label`_. If you're new, pick\n+ a specific component to stick with. Django is a big codebase, so it's best\n+ to contribute consistently with a narrow focus and grow it slowly.\n+\n+2. Pull the branch. See the :ref:`handling-pull-requests`, including the git\n+ alias to make checking out other pull requests easier.\n+\n+3. Check the tests. If the ticket is for a bug, there should be a regression\n+ test. Confirm that the test fails if the change is reverted. Check that the\n+ tests are adequately covering the code and logic as well. See\n+ :ref:`patch-review-checklist`.\n+\n+4. Test in your own Django project. See :ref:`installing-development-version`\n+ for how. Explore the user interface and user experience with the change.\n+ Does it feel right? Can you break it? Another approach is to assume\n+ everything is wrong. Can you demonstrate to yourself that each piece is\n+ correct?\n+\n+5. Check the documentation. Is the documentation understandable? Does it\n+ provide the information the reader needs at that moment? Does it read well?\n+ Is it consistent with the documentation before and after it? See\n+ :ref:`build-documentation-locally`.\n+\n+6. Are you happy with the patch? This is fairly subjective, but that's fine.\n+ You should ask, does the approach make sense to you and is there another\n+ way to do it that's better? Also ask yourself, is the scope of the change\n+ appropriate? Are things named appropriately? Renaming things is slow and\n+ challenging in Django, so we should try to get it right from the start.\n+ Are there backwards compatibility concerns? Lastly, are there any other\n+ general concerns such as things that may worry you or that should be looked\n+ into?\n+\n+7. Review your feedback. Before you submit your feedback, consider the\n+ feedback you want to share. It takes courage to open a Pull Request, we\n+ should be thoughtful and considerate of the leap the author [NAME_REDACTED]\n+ there are nitpicky or small suggestions, use GitHub's suggestion feature.\n+ If the approach isn't what you expected, consider asking the author why\n+ before requesting several changes. Seek to understand their reasoning\n+ first.\n+\n+8. Submit feedback on GitHub and update flags, \"patch needs improvement\",\n+ \"needs tests\", and \"needs documentation\", as needed. This will move the\n+ ticket to the `\"waiting for author\" queue`_. If you have given a\n+ specific type of code review, please indicate that on the Pull Request.\n+\n+Types of code reviews\n+---------------------\n+\n+Not everyone will or should give the same type of code review. Having a diverse\n+set of opinions and experiences helps Django be better. If you are providing a\n+specific review, please indicate that on the Pull Request in GitHub. Below\n+are some of the types of code review you can perform:\n+\n+* Accessibility review. Does it conform to our :ref:`accessibility-standards`?\n+\n+* :ref:`Patch style ` and contribution process review.\n+\n+* Usability and developer experience review.\n+\n+ * Use the change and provide feedback from that experience.\n+\n+ * Are the APIs and documentation accessible and well explained?\n+\n+* Domain expertise review. Do you have a personal expertise that is relevant\n+ such as databases, HTTP, security, etc?\n+\n+* Benchmarking and performance review. There are benchmarking tests, but\n+ sometimes changes require additional testing.\n+\n+ * Utilize :ref:`django-asv-benchmarks` to check performance over time.\n+\n+ * Run benchmark tests by [NAME_REDACTED] with \"benchmark\".\n+\n+.. _review queue: https://code.djangoproject.com/query?has_patch=1&needs_better_patch=0&needs_docs=0&needs_tests=0&stage=Accepted&status=!closed&order=changetime&desc=1\n+.. _Pull Requests in GitHub with the \"no ticket\" label: https://github.com/[USER_REDACTED]ngo/django/pulls?q=is%3Aopen+is%3Apr+label%3A%22no+ticket%22\n+.. _\"waiting for author\" queue: https://code.djangoproject.com/query?has_patch=1&needs_better_patch=1&stage=Accepted&status=assigned&status=new&or&has_patch=1&needs_docs=1&stage=Accepted&status=assigned&status=new&or&has_patch=1&needs_tests=1&stage=Accepted&status=assigned&status=new&order=changetime&desc=1" }, { "filename": "docs/internals/contributing/writing-documentation.txt", "status": "modified", "additions": 2, "deletions": 0, "changes": 2, "patch": "@@ -124,6 +124,8 @@ Create and activate a virtual environment, then install the dependencies:\n $ source .venv/bin/activate\n $ python -m pip install -r docs/requirements.txt\n \n+.. _build-documentation-locally:\n+\n Build the documentation locally\n -------------------------------" }, { "filename": "docs/spelling_wordlist", "status": "modified", "additions": 1, "deletions": 0, "changes": 1, "patch": "@@ -313,6 +313,7 @@ needsinfo\n needsnewfeatureprocess\n německy\n nginx\n+nitpicky\n noding\n nonces\n nonnegative" } ], "reviews": [ { "id": 3724244848, "user": "user_3a67c55598c5", "state": "APPROVED", "body": "Thanks, Tim. This is my favorite subject, so unsurprisingly I have a few ideas for you to consider, but THANK YOU for encouraging people to jump in 🤝", "submitted_at": "2026-01-29T18:28:59+00:00" }, { "id": 3724389089, "user": "user_6b79e26637e6", "state": "COMMENTED", "body": null, "submitted_at": "2026-01-29T18:37:07+00:00" }, { "id": 3724411558, "user": "user_3a67c55598c5", "state": "COMMENTED", "body": null, "submitted_at": "2026-01-29T18:43:21+00:00" }, { "id": 3724412462, "user": "user_6b79e26637e6", "state": "COMMENTED", "body": null, "submitted_at": "2026-01-29T18:43:36+00:00" }, { "id": 3724416015, "user": "user_6b79e26637e6", "state": "COMMENTED", "body": null, "submitted_at": "2026-01-29T18:44:33+00:00" }, { "id": 3724418777, "user": "user_6b79e26637e6", "state": "COMMENTED", "body": null, "submitted_at": "2026-01-29T18:45:20+00:00" }, { "id": 3729021213, "user": "user_8d47d9546a2c", "state": "COMMENTED", "body": "[USER_REDACTED] This is awesome! It brings a lot of clarity to reviews.\n\nI wasn't sure if the Django documentation is the place to put them, but wondered if it would help to reference videos of code reviews.", "submitted_at": "2026-01-30T15:49:36+00:00" }, { "id": 3729390079, "user": "user_3a67c55598c5", "state": "COMMENTED", "body": null, "submitted_at": "2026-01-30T16:51:39+00:00" }, { "id": 3730537535, "user": "user_6b79e26637e6", "state": "COMMENTED", "body": null, "submitted_at": "2026-01-30T21:49:36+00:00" }, { "id": 3730561296, "user": "user_6b79e26637e6", "state": "COMMENTED", "body": null, "submitted_at": "2026-01-30T21:54:27+00:00" }, { "id": 3730562230, "user": "user_6b79e26637e6", "state": "COMMENTED", "body": null, "submitted_at": "2026-01-30T21:54:37+00:00" }, { "id": 3730564231, "user": "user_6b79e26637e6", "state": "COMMENTED", "body": null, "submitted_at": "2026-01-30T21:55:02+00:00" }, { "id": 3730565059, "user": "user_6b79e26637e6", "state": "COMMENTED", "body": null, "submitted_at": "2026-01-30T21:55:10+00:00" }, { "id": 3730570895, "user": "user_6b79e26637e6", "state": "COMMENTED", "body": null, "submitted_at": "2026-01-30T21:56:16+00:00" }, { "id": 3730571856, "user": "user_6b79e26637e6", "state": "COMMENTED", "body": null, "submitted_at": "2026-01-30T21:56:30+00:00" }, { "id": 3730573727, "user": "user_6b79e26637e6", "state": "COMMENTED", "body": null, "submitted_at": "2026-01-30T21:56:50+00:00" }, { "id": 3730574835, "user": "user_6b79e26637e6", "state": "COMMENTED", "body": null, "submitted_at": "2026-01-30T21:57:03+00:00" }, { "id": 3730588168, "user": "user_6b79e26637e6", "state": "COMMENTED", "body": null, "submitted_at": "2026-01-30T21:59:46+00:00" }, { "id": 3730605686, "user": "user_6b79e26637e6", "state": "COMMENTED", "body": null, "submitted_at": "2026-01-30T22:03:41+00:00" }, { "id": 3730614920, "user": "user_6b79e26637e6", "state": "COMMENTED", "body": null, "submitted_at": "2026-01-30T22:05:49+00:00" }, { "id": 3730674046, "user": "user_6b79e26637e6", "state": "COMMENTED", "body": null, "submitted_at": "2026-01-30T22:20:32+00:00" }, { "id": 3730674637, "user": "user_6b79e26637e6", "state": "COMMENTED", "body": null, "submitted_at": "2026-01-30T22:20:42+00:00" }, { "id": 3731264666, "user": "user_3a67c55598c5", "state": "COMMENTED", "body": null, "submitted_at": "2026-01-31T01:38:00+00:00" }, { "id": 3731267315, "user": "user_3a67c55598c5", "state": "APPROVED", "body": "I really like how this turned out, thanks for indulging me.\n\nThanks [USER_REDACTED] for having a look!", "submitted_at": "2026-01-31T01:40:36+00:00" } ], "review_comments": [ { "id": 2742873491, "user": "user_3a67c55598c5", "body": "nit: mix of quoted/unquoted and casing here.", "path": "docs/internals/contributing/triaging-tickets.txt", "line": null, "side": "RIGHT", "created_at": "2026-01-29T18:03:34+00:00" }, { "id": 2742876601, "user": "user_3a67c55598c5", "body": "no ticket -> \"no ticket\"", "path": "docs/internals/contributing/triaging-tickets.txt", "line": null, "side": "RIGHT", "created_at": "2026-01-29T18:04:14+00:00" }, { "id": 2742885545, "user": "user_3a67c55598c5", "body": "Link to the patch review checklist? (\"For more specifics...\" )I get that we're describing something more holistic here, but there are some nice goodies over there, and cross-linking could be nice.", "path": "docs/internals/contributing/triaging-tickets.txt", "line": null, "side": "RIGHT", "created_at": "2026-01-29T18:06:24+00:00" }, { "id": 2742901187, "user": "user_3a67c55598c5", "body": "Take or leave this teeny suggestion, but I'd move the \"check all the rules\" bit into somewhere else (maybe where we link the review checklist) and leave this one more focused on \"use your judgment\"\n\n\"Use your judgment\" is very different from \"did it follow the letter of every rule\", which a computer can do.", "path": "docs/internals/contributing/triaging-tickets.txt", "line": 537, "side": "RIGHT", "created_at": "2026-01-29T18:09:13+00:00" }, { "id": 2742906678, "user": "user_3a67c55598c5", "body": "Mention backward compatibility considerations?", "path": "docs/internals/contributing/triaging-tickets.txt", "line": null, "side": "RIGHT", "created_at": "2026-01-29T18:10:29+00:00" }, { "id": 2742908772, "user": "user_3a67c55598c5", "body": "\"is or should\" needs rewording.", "path": "docs/internals/contributing/triaging-tickets.txt", "line": null, "side": "RIGHT", "created_at": "2026-01-29T18:11:04+00:00" }, { "id": 2742910676, "user": "user_3a67c55598c5", "body": "On first read I didn't grok the connection the following list, a colon might help?", "path": "docs/internals/contributing/triaging-tickets.txt", "line": null, "side": "RIGHT", "created_at": "2026-01-29T18:11:32+00:00" }, { "id": 2742912171, "user": "user_3a67c55598c5", "body": "Type annotations are not used? 😉", "path": "docs/internals/contributing/triaging-tickets.txt", "line": null, "side": "RIGHT", "created_at": "2026-01-29T18:11:56+00:00" }, { "id": 2742913681, "user": "user_3a67c55598c5", "body": "This part starts to feel a little repetitive.", "path": "docs/internals/contributing/triaging-tickets.txt", "line": null, "side": "RIGHT", "created_at": "2026-01-29T18:12:21+00:00" }, { "id": 2742915697, "user": "user_3a67c55598c5", "body": "I'd continue using \"?\" for all questions here and below.", "path": "docs/internals/contributing/triaging-tickets.txt", "line": null, "side": "RIGHT", "created_at": "2026-01-29T18:12:55+00:00" }, { "id": 2742916878, "user": "user_3a67c55598c5", "body": "Do we have any contributor docs about that? 🤔", "path": "docs/internals/contributing/triaging-tickets.txt", "line": 580, "side": "RIGHT", "created_at": "2026-01-29T18:13:16+00:00" }, { "id": 2742928578, "user": "user_3a67c55598c5", "body": "One memorable part of Sarah's talk for me was the bit about how you really must pull the branch instead of only reading the diff, since \"you're buying the house.\" Inspire yourself to do a thorough review by [NAME_REDACTED] shoes of the people who will maintain it forever. Would you buy a house sight unseen?", "path": "docs/internals/contributing/triaging-tickets.txt", "line": 519, "side": "RIGHT", "created_at": "2026-01-29T18:16:33+00:00" }, { "id": 2742937253, "user": "user_3a67c55598c5", "body": "[NAME_REDACTED] has a nice blog post about \"checking yourself\" to avoid grabbing the steering wheel during PR review. Have you heard of him?\n\n(I'm inviting you to sneak in something about that -- try not to leave feedback that reduces to \"my way is much better\", rather leave feedback oriented around blending in, conservatism, resilience to change, etc.)", "path": "docs/internals/contributing/triaging-tickets.txt", "line": null, "side": "RIGHT", "created_at": "2026-01-29T18:19:08+00:00" }, { "id": 2742951733, "user": "user_3a67c55598c5", "body": "Another helpful fiction I often use (and I've heard Natalia use): Assume everything is wrong. Can you demonstrate to yourself that each piece is correct?", "path": "docs/internals/contributing/triaging-tickets.txt", "line": null, "side": "RIGHT", "created_at": "2026-01-29T18:23:30+00:00" }, { "id": 2742959099, "user": "user_3a67c55598c5", "body": "Anything we can do to underline that we really, actually mean this would be huge.\n\nMy gut says if we took a poll, 99% of folks would say no one should bother trying to review a Django PR without \"being on the team\" (which is false!)", "path": "docs/internals/contributing/triaging-tickets.txt", "line": 66, "side": "RIGHT", "created_at": "2026-01-29T18:25:54+00:00" }, { "id": 2742961587, "user": "user_3a67c55598c5", "body": "Put your hands in the clay, make changes in the diff and rerun the workflow.", "path": "docs/internals/contributing/triaging-tickets.txt", "line": 519, "side": "RIGHT", "created_at": "2026-01-29T18:26:41+00:00" }, { "id": 2742995237, "user": "user_6b79e26637e6", "body": "The only thing I know about it is https://github.com/[USER_REDACTED]ngo/django-asv. There's also the label that can be applied to run the benchmark tests. That definitely feels like something we should document.", "path": "docs/internals/contributing/triaging-tickets.txt", "line": 580, "side": "RIGHT", "created_at": "2026-01-29T18:37:07+00:00" }, { "id": 2743015217, "user": "user_3a67c55598c5", "body": "Somewhere in our docs we have \"Be bold! Leave feedback!\" People need to hear that, so I don't mind repeating it.", "path": "docs/internals/contributing/triaging-tickets.txt", "line": 66, "side": "RIGHT", "created_at": "2026-01-29T18:43:21+00:00" }, { "id": 2743016039, "user": "user_6b79e26637e6", "body": "Let me make another attempt at this piece. When I originally wrote this I had the wrong understanding of community reviews. With the understanding that any community reviewer could enable a Merger to merge a PR, I can put a bit more \"umph\" to this.", "path": "docs/internals/contributing/triaging-tickets.txt", "line": 66, "side": "RIGHT", "created_at": "2026-01-29T18:43:36+00:00" }, { "id": 2743019239, "user": "user_6b79e26637e6", "body": "[NAME_REDACTED] fact that you have read that and referenced it is amazing. Thank you for that.", "path": "docs/internals/contributing/triaging-tickets.txt", "line": null, "side": "RIGHT", "created_at": "2026-01-29T18:44:32+00:00" }, { "id": 2743021680, "user": "user_6b79e26637e6", "body": ":melting_face: Should I remove this line or make it \"not used\"?", "path": "docs/internals/contributing/triaging-tickets.txt", "line": null, "side": "RIGHT", "created_at": "2026-01-29T18:45:20+00:00" }, { "id": 2746861488, "user": "user_8d47d9546a2c", "body": "Would it be good to mention and link to the waiting for author queue? This is just a suggestion, and you can disagree here.\n\n```suggestion\n7. Submit feedback on GitHub and move the ticket into the waiting for author [NAME_REDACTED] flags, \"patch needs improvement\",\n \"needs tests\", and \"needs documentation\", as needed. If you have given a\n```", "path": "docs/internals/contributing/triaging-tickets.txt", "line": null, "side": "RIGHT", "created_at": "2026-01-30T15:42:34+00:00" }, { "id": 2746887562, "user": "user_8d47d9546a2c", "body": "I like that the no ticket PRs is being documented here. It makes me think how we can incorporate the list of no ticket PRs into Trac...", "path": "docs/internals/contributing/triaging-tickets.txt", "line": null, "side": "RIGHT", "created_at": "2026-01-30T15:49:26+00:00" }, { "id": 2747140464, "user": "user_3a67c55598c5", "body": "Let's remove it; winds are shifting ⛵", "path": "docs/internals/contributing/triaging-tickets.txt", "line": null, "side": "RIGHT", "created_at": "2026-01-30T16:51:39+00:00" }, { "id": 2748095503, "user": "user_6b79e26637e6", "body": "I'm going to remove both since combining would leave it as a single sub-bullet.", "path": "docs/internals/contributing/triaging-tickets.txt", "line": null, "side": "RIGHT", "created_at": "2026-01-30T21:49:36+00:00" }, { "id": 2748115790, "user": "user_6b79e26637e6", "body": "I added a pair of sub-bullets. Let me know if that helps.", "path": "docs/internals/contributing/triaging-tickets.txt", "line": 580, "side": "RIGHT", "created_at": "2026-01-30T21:54:27+00:00" }, { "id": 2748116627, "user": "user_6b79e26637e6", "body": "Fixed.", "path": "docs/internals/contributing/triaging-tickets.txt", "line": null, "side": "RIGHT", "created_at": "2026-01-30T21:54:37+00:00" }, { "id": 2748118460, "user": "user_6b79e26637e6", "body": "Added a sentence to clarify it's a list of review types.", "path": "docs/internals/contributing/triaging-tickets.txt", "line": null, "side": "RIGHT", "created_at": "2026-01-30T21:55:02+00:00" }, { "id": 2748119089, "user": "user_6b79e26637e6", "body": "Attempted a fix.", "path": "docs/internals/contributing/triaging-tickets.txt", "line": null, "side": "RIGHT", "created_at": "2026-01-30T21:55:10+00:00" }, { "id": 2748123831, "user": "user_6b79e26637e6", "body": "I was on the fence about this, but we're already pretty wordy here. I put it as a follow-up sentence since this first sentence should be instructional. I think it should be concise and direct. The rest of the bullet can be informative which is what I'd characterize the waiting on author [NAME_REDACTED]", "path": "docs/internals/contributing/triaging-tickets.txt", "line": null, "side": "RIGHT", "created_at": "2026-01-30T21:56:16+00:00" }, { "id": 2748124742, "user": "user_6b79e26637e6", "body": "Added", "path": "docs/internals/contributing/triaging-tickets.txt", "line": null, "side": "RIGHT", "created_at": "2026-01-30T21:56:29+00:00" }, { "id": 2748125997, "user": "user_6b79e26637e6", "body": "Incorporated.", "path": "docs/internals/contributing/triaging-tickets.txt", "line": null, "side": "RIGHT", "created_at": "2026-01-30T21:56:50+00:00" }, { "id": 2748126718, "user": "user_6b79e26637e6", "body": "Added a link.", "path": "docs/internals/contributing/triaging-tickets.txt", "line": null, "side": "RIGHT", "created_at": "2026-01-30T21:57:03+00:00" }, { "id": 2748137514, "user": "user_6b79e26637e6", "body": "Rather than changing this particular line, I made the follow-up paragraph to list an admonition to make it stand out. I specifically mentioned reviewing code and triaging tickets, then changed the last sentence to explicitly say we want their help.\n\nAll that said, imposter syndrome is a real thing and we have too much process to convince every person a little effort from them is desirable by us.", "path": "docs/internals/contributing/triaging-tickets.txt", "line": 66, "side": "RIGHT", "created_at": "2026-01-30T21:59:46+00:00" }, { "id": 2748150765, "user": "user_6b79e26637e6", "body": "The sentiment behind your request is covered in step 4. We could reword it to match one of the metaphors you highlighted.\n\nPersonally, I like the three questions we have in step 4 at the moment. It gives tangible steps to the person on how to proceed forward.", "path": "docs/internals/contributing/triaging-tickets.txt", "line": 519, "side": "RIGHT", "created_at": "2026-01-30T22:03:41+00:00" }, { "id": 2748158615, "user": "user_6b79e26637e6", "body": "Yeah, I think we can remove \"Does the change :ref:`adhere to the guidelines for contributing `?\" because we've added \"See :ref:`patch-review-checklist`.\" to step 3 above.", "path": "docs/internals/contributing/triaging-tickets.txt", "line": 537, "side": "RIGHT", "created_at": "2026-01-30T22:05:49+00:00" }, { "id": 2748206568, "user": "user_6b79e26637e6", "body": "I've added a new step between this one and the next that asks the reviewer to consider their feedback before submitting it. Thank you for highlighting that.", "path": "docs/internals/contributing/triaging-tickets.txt", "line": null, "side": "RIGHT", "created_at": "2026-01-30T22:20:32+00:00" }, { "id": 2748207123, "user": "user_6b79e26637e6", "body": "Removed", "path": "docs/internals/contributing/triaging-tickets.txt", "line": 537, "side": "RIGHT", "created_at": "2026-01-30T22:20:42+00:00" }, { "id": 2748659162, "user": "user_3a67c55598c5", "body": "Sorry, this bit was just telling you something I remembered from Sarah's talk rather than a suggestion 🙈", "path": "docs/internals/contributing/triaging-tickets.txt", "line": 519, "side": "RIGHT", "created_at": "2026-01-31T01:38:00+00:00" } ], "meta": { "languages": [ "txt" ], "touches_tests": false, "review_state_summary": { "APPROVED": 2, "COMMENTED": 22 }, "meaningful_comment_count": 36, "has_approval": true, "has_changes_requested": false, "total_review_comments": 39 } } { "_id": "a6697940cfd347e9", "_schema_version": "1.0", "_cleaned_at": "2026-02-12T07:46:51.536480+00:00", "repo": "django/django", "repo_url": "https://github.com/django/django", "license_name": "BSD 3-Clause \"New\" or \"Revised\" License", "license_spdx": "BSD-3-Clause", "pr_number": 20586, "title": "Fixed #36847 -- Ensured auto_now_add fields are set before FileField.upload_to is called.", "body": "#### Trac ticket number\n\n\n\nticket-36847\n\n#### Branch description\nIn Django 5.2 and earlier, an `auto_now_add=True` `DateTimeField` could be accessed inside a `FileField`’s `upload_to` callable, because the field was populated with the current timestamp during insertion.\nThis is a regression introduced in 94680437a45a71c70ca8bd2e68b72aa1e2eff337 where the insert path called `field.pre_save()` with `add=False` instead of `add=True`. \n\nThis fix restores the correct behavior by [NAME_REDACTED] to `add=True`.\n(Used AI to help create the test coverage for the fix. I have verified that it's working correctly.)\n\n#### AI [NAME_REDACTED] (REQUIRED)\n\n- [ ] **No AI tools were used** in preparing this PR.\n- [x] **If AI tools were used**, I have disclosed which ones, and fully reviewed and verified their output.\n\n#### Checklist\n- [x] This PR follows the [contribution guidelines](https://docs.djangoproject.com/en/stable/internals/contributing/writing-code/submitting-patches/).\n- [x] This PR **does not** disclose a security vulnerability (see [vulnerability reporting](https://docs.djangoproject.com/en/stable/internals/security/)).\n- [x] This PR targets the `main` branch. \n- [x] The commit message is written in past tense, mentions the ticket number, and ends with a period.\n- [x] I have checked the \"Has patch\" ticket flag in the Trac system.\n- [x] I have added or updated relevant tests.\n- [x] I have added or updated relevant docs, including release notes if applicable.\n- [ ] I have attached screenshots in both light and dark modes for any UI changes.", "author": "user_d96dcc7f8ae4", "created_at": "2026-01-25T18:40:29+00:00", "merged_at": "2026-01-29T13:11:33+00:00", "base_branch": "main", "head_branch": "ticket_36847", "additions": 23, "deletions": 2, "changed_files": 4, "files": [ { "filename": "django/db/models/base.py", "status": "modified", "additions": 3, "deletions": 1, "changes": 4, "patch": "@@ -1175,7 +1175,9 @@ def _save_table(\n ].features.can_return_columns_from_insert\n for field in insert_fields:\n value = (\n- getattr(self, field.attname) if raw else field.pre_save(self, False)\n+ getattr(self, field.attname)\n+ if raw\n+ else field.pre_save(self, add=True)\n )\n if hasattr(value, \"resolve_expression\"):\n if field not in returning_fields:" }, { "filename": "docs/releases/6.0.2.txt", "status": "modified", "additions": 3, "deletions": 0, "changes": 3, "patch": "@@ -15,3 +15,6 @@ Bugfixes\n to wrap below the changelist when filter elements contained long text\n (:ticket:`36850`).\n \n+* Fixed a regression in Django 6.0 where ``auto_now_add`` field values were not\n+ populated during ``INSERT`` operations, due to incorrect parameters passed to\n+ ``field.pre_save()`` (:ticket:`36847`)." }, { "filename": "tests/model_fields/models.py", "status": "modified", "additions": 10, "deletions": 0, "changes": 10, "patch": "@@ -262,10 +262,20 @@ class DataModel(models.Model):\n # FileField\n \n \n+def upload_to_with_date(instance, filename):\n+ return f\"{instance.created_at.year}/{filename}\"\n+\n+\n class Document(models.Model):\n myfile = models.FileField(storage=temp_storage, upload_to=\"unused\", unique=True)\n \n \n+# See ticket #36847.\n+class DocumentWithTimestamp(models.Model):\n+ created_at = models.DateTimeField(auto_now_add=True)\n+ myfile = models.FileField(storage=temp_storage, upload_to=upload_to_with_date)\n+\n+\n ###############################################################################\n # ImageField" }, { "filename": "tests/model_fields/test_filefield.py", "status": "modified", "additions": 7, "deletions": 1, "changes": 8, "patch": "@@ -13,7 +13,7 @@\n from django.test import TestCase, override_settings\n from django.test.utils import isolate_apps\n \n-from .models import Document\n+from .models import Document, DocumentWithTimestamp\n \n \n class FileFieldTests(TestCase):\n@@ -209,3 +209,9 @@ class MyDocument(AbstractMyDocument):\n \n document = MyDocument(myfile=\"test_file.py\")\n self.assertEqual(document.myfile.field.model, MyDocument)\n+\n+ def test_upload_to_callable_sees_auto_now_add_field_value(self):\n+ d = DocumentWithTimestamp(myfile=ContentFile(b\"content\", name=\"foo\"))\n+ d.save()\n+ self.assertIsNotNone(d.created_at)\n+ self.assertIs(d.myfile.name.startswith(f\"{d.created_at.year}/foo\"), True)" } ], "reviews": [ { "id": 3719299168, "user": "user_00dac951cdbf", "state": "APPROVED", "body": "Thank you [USER_REDACTED] for this work! 🌟 \n\nI pushed some edits and will merge when CI is green.", "submitted_at": "2026-01-28T21:40:42+00:00" }, { "id": 3719413037, "user": "user_3a67c55598c5", "state": "COMMENTED", "body": null, "submitted_at": "2026-01-28T22:08:13+00:00" } ], "review_comments": [ { "id": 2738823707, "user": "user_3a67c55598c5", "body": "```suggestion\n populated during ``INSERT`` operations, due to incorrect parameters passed to\n```", "path": "docs/releases/6.0.2.txt", "line": null, "side": "RIGHT", "created_at": "2026-01-28T22:08:14+00:00" } ], "meta": { "languages": [ "py", "txt" ], "touches_tests": true, "review_state_summary": { "APPROVED": 1, "COMMENTED": 1 }, "meaningful_comment_count": 1, "has_approval": true, "has_changes_requested": false, "total_review_comments": 1 } } { "_id": "daa290da1120489b", "_schema_version": "1.0", "_cleaned_at": "2026-02-12T07:46:51.537480+00:00", "repo": "django/django", "repo_url": "https://github.com/django/django", "license_name": "BSD 3-Clause \"New\" or \"Revised\" License", "license_spdx": "BSD-3-Clause", "pr_number": 20580, "title": "Fixed #36879 -- [NAME_REDACTED] client in Redis client metadata.", "body": "#### Trac ticket number\n\n\n\nticket-36879\n\n#### Branch description\nRedis documentation recommends that clients identify themselves via connection metadata to help operators monitor, debug, and reason about production systems (for example using CLIENT SETINFO / CLIENT INFO).\n\nThis patch allows Django to set its own driver info for redis-py connections, which will be a different `lib-name`:\n\n `redis-py` -> `redis-py(django_v{django_version})`.\n\nThis is achieved by [NAME_REDACTED] `Connection` class to include Django's custom `lib_name` or `driver_info`.\n\n#### AI [NAME_REDACTED] (REQUIRED)\n\n- [x] **No AI tools were used** in preparing this PR.\n- [ ] **If AI tools were used**, I have disclosed which ones, and fully reviewed and verified their output.\n\n#### Checklist\n- [x] This PR follows the [contribution guidelines](https://docs.djangoproject.com/en/stable/internals/contributing/writing-code/submitting-patches/).\n- [x] This PR **does not** disclose a security vulnerability (see [vulnerability reporting](https://docs.djangoproject.com/en/stable/internals/security/)).\n- [x] This PR targets the `main` branch. \n- [x] The commit message is written in past tense, mentions the ticket number, and ends with a period.\n- [x] I have checked the \"Has patch\" ticket flag in the Trac system.\n- [x] I have added or updated relevant tests.\n- [ ] I have added or updated relevant docs, including release notes if applicable.\n- [ ] I have attached screenshots in both light and dark modes for any UI changes.", "author": "user_3e168b76e1d1", "created_at": "2026-01-24T14:27:21+00:00", "merged_at": "2026-02-03T11:40:29+00:00", "base_branch": "main", "head_branch": "ticket_36879", "additions": 34, "deletions": 1, "changed_files": 3, "files": [ { "filename": "AUTHORS", "status": "modified", "additions": 1, "deletions": 0, "changes": 1, "patch": "@@ -113,6 +113,7 @@ answer newbie questions, and generally made Django that much better:\n [NAME_EMAIL_REDACTED]\n [NAME_EMAIL_REDACTED]\n Anže Pečar <[EMAIL_REDACTED]>\n+ ar3ph \n A. [NAME_EMAIL_REDACTED]\n [NAME_REDACTED]\n arien <[EMAIL_REDACTED]>" }, { "filename": "django/core/cache/backends/redis.py", "status": "modified", "additions": 14, "deletions": 1, "changes": 15, "patch": "@@ -4,6 +4,7 @@\n import random\n import re\n \n+import django\n from django.core.cache.backends.base import DEFAULT_TIMEOUT, BaseCache\n from django.utils.functional import cached_property\n from django.utils.module_loading import import_string\n@@ -59,7 +60,19 @@ def __init__(\n parser_class = import_string(parser_class)\n parser_class = parser_class or self._lib.connection.DefaultParser\n \n- self._pool_options = {\"parser_class\": parser_class, **options}\n+ version = django.get_version()\n+ if hasattr(self._lib, \"DriverInfo\"):\n+ driver_info = self._lib.DriverInfo().add_upstream_driver(\"django\", version)\n+ driver_info_options = {\"driver_info\": driver_info}\n+ else:\n+ # DriverInfo is not available in this redis-py version.\n+ driver_info_options = {\"lib_name\": f\"redis-py(django_v{version})\"}\n+\n+ self._pool_options = {\n+ \"parser_class\": parser_class,\n+ **driver_info_options,\n+ **options,\n+ }\n \n def _get_connection_pool_index(self, write):\n # Write to the first server. Read from other servers if there are more," }, { "filename": "tests/cache/tests.py", "status": "modified", "additions": 19, "deletions": 0, "changes": 19, "patch": "@@ -15,6 +15,7 @@\n from pathlib import Path\n from unittest import mock, skipIf\n \n+import django\n from django.conf import settings\n from django.core import management, signals\n from django.core.cache import (\n@@ -1986,6 +1987,24 @@ def test_redis_pool_options(self):\n self.assertEqual(pool.connection_kwargs[\"socket_timeout\"], 0.1)\n self.assertIs(pool.connection_kwargs[\"retry_on_timeout\"], True)\n \n+ def test_client_driver_info(self):\n+ client_info = cache._cache.get_client().client_info()\n+ if {\"lib-name\", \"lib-ver\"}.issubset(client_info):\n+ version = django.get_version()\n+ if hasattr(self.lib, \"DriverInfo\"):\n+ info = self._lib.DriverInfo().add_upstream_driver(\"django\", version)\n+ correct_lib_name = info.formatted_name\n+ else:\n+ correct_lib_name = f\"redis-py(django_v{version})\"\n+ # Relax the assertion to allow date variance in editable installs.\n+ truncated_lib_name = correct_lib_name.rsplit(\".dev\", maxsplit=1)[0]\n+ self.assertIn(truncated_lib_name, client_info[\"lib-name\"])\n+ self.assertEqual(client_info[\"lib-ver\"], self.lib.__version__)\n+ else:\n+ # Redis versions below 7.2 lack CLIENT SETINFO.\n+ self.assertNotIn(\"lib-ver\", client_info)\n+ self.assertNotIn(\"lib-name\", client_info)\n+\n \n class FileBasedCachePathLibTests(FileBasedCacheTests):\n def mkdtemp(self):" } ], "reviews": [ { "id": 3705951654, "user": "user_7c777599a482", "state": "COMMENTED", "body": null, "submitted_at": "2026-01-26T13:04:24+00:00" }, { "id": 3713634439, "user": "user_3e168b76e1d1", "state": "COMMENTED", "body": null, "submitted_at": "2026-01-27T21:54:33+00:00" }, { "id": 3716400655, "user": "user_7c777599a482", "state": "COMMENTED", "body": null, "submitted_at": "2026-01-28T12:15:12+00:00" }, { "id": 3719143566, "user": "user_3e168b76e1d1", "state": "COMMENTED", "body": null, "submitted_at": "2026-01-28T21:03:28+00:00" }, { "id": 3729908342, "user": "user_3a67c55598c5", "state": "COMMENTED", "body": "Thanks, I have some initial questions for you.", "submitted_at": "2026-01-30T19:03:48+00:00" }, { "id": 3729932112, "user": "user_3a67c55598c5", "state": "COMMENTED", "body": null, "submitted_at": "2026-01-30T19:05:55+00:00" }, { "id": 3730690648, "user": "user_3e168b76e1d1", "state": "COMMENTED", "body": null, "submitted_at": "2026-01-30T22:25:10+00:00" }, { "id": 3730708348, "user": "user_3e168b76e1d1", "state": "COMMENTED", "body": null, "submitted_at": "2026-01-30T22:29:36+00:00" }, { "id": 3735081102, "user": "user_3e168b76e1d1", "state": "COMMENTED", "body": null, "submitted_at": "2026-02-01T06:40:21+00:00" }, { "id": 3741213030, "user": "user_3a67c55598c5", "state": "APPROVED", "body": "Looks good, thank you ⭐ \n\nI pushed cosmetic edits and relaxed the assertion to avoid headaches I've seen when editable installs have dates timestamped into the version number.", "submitted_at": "2026-02-02T18:30:03+00:00" }, { "id": 3744002448, "user": "user_7c777599a482", "state": "APPROVED", "body": "Looks good, thank you [USER_REDACTED] and [USER_REDACTED] !", "submitted_at": "2026-02-03T09:06:55+00:00" } ], "review_comments": [ { "id": 2727532891, "user": "user_7c777599a482", "body": "Let's also verify that `lib-version` is properly set to the `redis-py` version.", "path": "tests/cache/tests.py", "line": null, "side": "RIGHT", "created_at": "2026-01-26T13:04:24+00:00" }, { "id": 2733976773, "user": "user_3e168b76e1d1", "body": "Is that really necessary? This feels like testing `redis-py` itself.", "path": "tests/cache/tests.py", "line": null, "side": "RIGHT", "created_at": "2026-01-27T21:54:32+00:00" }, { "id": 2736368412, "user": "user_7c777599a482", "body": "The point of the test would be to verify that `Django` does not override `lib-ver` to something other than what `redis-py` sets as its own version (unlike what's done with `lib_name`):\n```\n else:\n # DriverInfo is not available in this redis-py version\n self.lib_name = f\"redis-py(django_v{django.get_version()})\"\n```", "path": "tests/cache/tests.py", "line": null, "side": "RIGHT", "created_at": "2026-01-28T12:15:12+00:00" }, { "id": 2738600530, "user": "user_3e168b76e1d1", "body": "i agree.", "path": "tests/cache/tests.py", "line": null, "side": "RIGHT", "created_at": "2026-01-28T21:03:28+00:00" }, { "id": 2747577963, "user": "user_3a67c55598c5", "body": "You can either chop this or replace preambles (\"test that\") with something more descriptive.", "path": "tests/cache/tests.py", "line": null, "side": "RIGHT", "created_at": "2026-01-30T19:00:47+00:00" }, { "id": 2747584391, "user": "user_3a67c55598c5", "body": "What alternatives did you explore besides doing dynamic class creation?", "path": "django/core/cache/backends/redis.py", "line": null, "side": "RIGHT", "created_at": "2026-01-30T19:02:08+00:00" }, { "id": 2747585280, "user": "user_3a67c55598c5", "body": "Please avoid this quick line break.", "path": "docs/releases/6.1.txt", "line": null, "side": "RIGHT", "created_at": "2026-01-30T19:02:19+00:00" }, { "id": 2747598668, "user": "user_3a67c55598c5", "body": "Sorry, you can avoid polishing this, I might ask you to remove this note entirely. Not certain yet 🤔", "path": "docs/releases/6.1.txt", "line": null, "side": "RIGHT", "created_at": "2026-01-30T19:05:55+00:00" }, { "id": 2748219813, "user": "user_3e168b76e1d1", "body": "chopped", "path": "tests/cache/tests.py", "line": null, "side": "RIGHT", "created_at": "2026-01-30T22:25:09+00:00" }, { "id": 2748234284, "user": "user_3e168b76e1d1", "body": "None. However, I've found a better alternative now, only updating `self._pool_options`. \n\nB/c extra `pool_options` will eventually be passed to the `ConnectionPool` class's `__init__` method by `from_url` as part of `connection_kwargs`, which will change the driver info.", "path": "django/core/cache/backends/redis.py", "line": null, "side": "RIGHT", "created_at": "2026-01-30T22:29:36+00:00" }, { "id": 2750635097, "user": "user_3e168b76e1d1", "body": "I think this note should be removed. It's a bit too obscure.", "path": "docs/releases/6.1.txt", "line": null, "side": "RIGHT", "created_at": "2026-02-01T06:40:21+00:00" } ], "meta": { "languages": [ "py" ], "touches_tests": true, "review_state_summary": { "COMMENTED": 9, "APPROVED": 2 }, "meaningful_comment_count": 9, "has_approval": true, "has_changes_requested": false, "total_review_comments": 11 } } { "_id": "06930afeed3d9e57", "_schema_version": "1.0", "_cleaned_at": "2026-02-12T07:46:51.540481+00:00", "repo": "django/django", "repo_url": "https://github.com/django/django", "license_name": "BSD 3-Clause \"New\" or \"Revised\" License", "license_spdx": "BSD-3-Clause", "pr_number": 20576, "title": "Fixed #36788 -- Fixed horizontal form field alignment under
      in the admin.", "body": "#### Trac ticket number\nticket-36788\n\n#### Branch description\nSee demo below.\nRegression in 4187da258fe212d494cb578a0bc2b52c4979ab95.\n\n#### AI [NAME_REDACTED] (REQUIRED)\n- [x] **No AI tools were used** in preparing this PR.\n- [ ] **If AI tools were used**, I have disclosed which ones, and fully reviewed and verified their output.\n\n#### Checklist\n- [x] This PR follows the [contribution guidelines](https://docs.djangoproject.com/en/stable/internals/contributing/writing-code/submitting-patches/).\n- [x] This PR **does not** disclose a security vulnerability (see [vulnerability reporting](https://docs.djangoproject.com/en/stable/internals/security/)).\n- [x] This PR targets the `main` branch. \n- [x] The commit message is written in past tense, mentions the ticket number, and ends with a period.\n- [x] I have checked the \"Has patch\" ticket flag in the Trac system.\n- [x] I have added or updated relevant tests.\n- [x] I have added or updated relevant docs, including release notes if applicable.\n- [x] I have attached screenshots in both light and dark modes for any UI changes.\n\n#### Demo\n#### Before\n\"before\"\n\n#### After\n\"after\"", "author": "user_3a67c55598c5", "created_at": "2026-01-23T20:12:03+00:00", "merged_at": "2026-02-02T13:15:13+00:00", "base_branch": "main", "head_branch": "jtw/fieldset-horizontal", "additions": 43, "deletions": 4, "changed_files": 4, "files": [ { "filename": "django/contrib/admin/static/admin/css/forms.css", "status": "modified", "additions": 3, "deletions": 2, "changes": 5, "patch": "@@ -30,7 +30,8 @@ form .form-row p {\n flex-wrap: wrap;\n }\n \n-.form-multiline > div {\n+.form-multiline > div,\n+.form-multiline > fieldset {\n padding-bottom: 10px;\n }\n \n@@ -93,7 +94,7 @@ fieldset .inline-heading,\n /* ALIGNED FIELDSETS */\n \n .aligned fieldset {\n- width: 100%;\n+ flex-grow: 1;\n border-top: none;\n }" }, { "filename": "docs/releases/6.0.2.txt", "status": "modified", "additions": 3, "deletions": 0, "changes": 3, "patch": "@@ -15,6 +15,9 @@ Bugfixes\n to wrap below the changelist when filter elements contained long text\n (:ticket:`36850`).\n \n+* Fixed a visual regression in Django 6.0 for admin form fields grouped under a\n+ ``
      `` aligned horizontally (:ticket:`36788`).\n+\n * Fixed a regression in Django 6.0 where ``auto_now_add`` field values were not\n populated during ``INSERT`` operations, due to incorrect parameters passed to\n ``field.pre_save()`` (:ticket:`36847`)." }, { "filename": "tests/admin_views/admin.py", "status": "modified", "additions": 12, "deletions": 0, "changes": 12, "patch": "@@ -1198,6 +1198,18 @@ class CamelCaseAdmin(admin.ModelAdmin):\n \n class CourseAdmin(admin.ModelAdmin):\n radio_fields = {\"difficulty\": admin.VERTICAL}\n+ fieldsets = (\n+ (\n+ None,\n+ {\n+ \"fields\": (\n+ (\"title\", \"difficulty\"),\n+ (\"materials\", \"start_datetime\"),\n+ (\"categories\"),\n+ ),\n+ },\n+ ),\n+ )\n \n \n site = admin.AdminSite(name=\"admin\")" }, { "filename": "tests/admin_views/tests.py", "status": "modified", "additions": 25, "deletions": 2, "changes": 27, "patch": "@@ -7065,10 +7065,10 @@ def test_use_fieldset_fields_render(self):\n title=\"[NAME_REDACTED]\", materials=\"django_documents\"\n )\n expected_legend_tags_text = [\n- \"Materials:\",\n \"Difficulty:\",\n- \"Categories:\",\n+ \"Materials:\",\n \"Start datetime:\",\n+ \"Categories:\",\n ]\n url = reverse(\"admin:admin_views_course_change\", args=(course.pk,))\n self.selenium.get(self.live_server_url + url)\n@@ -7079,6 +7079,29 @@ def test_use_fieldset_fields_render(self):\n legend = fieldset.find_element(By.TAG_NAME, \"legend\")\n self.assertEqual(legend.text, expected_legend_tags_text[index])\n \n+ [USER_REDACTED]_cases([\"desktop_size\", \"mobile_size\", \"rtl\", \"dark\", \"high_contrast\"])\n+ def test_use_fieldset_with_grouped_fields(self):\n+ from selenium.webdriver.common.by [NAME_REDACTED]\n+\n+ self.admin_login(\n+ username=\"super\", password=\"secret\", login_url=reverse(\"admin:index\")\n+ )\n+ self.selenium.get(\n+ self.live_server_url + reverse(\"admin:admin_views_course_add\")\n+ )\n+ multiline = self.selenium.find_element(\n+ By.CSS_SELECTOR, \"#content-main .field-difficulty, .form-multiline\"\n+ )\n+ # Two field boxes.\n+ field_boxes = multiline.find_elements(By.CSS_SELECTOR, \"div > div.fieldBox\")\n+ self.assertEqual(len(field_boxes), 2)\n+ # One of them is under a
      .\n+ under_fieldset = multiline.find_elements(\n+ By.CSS_SELECTOR, \"fieldset > div > div.fieldBox\"\n+ )\n+ self.assertEqual(len(under_fieldset), 1)\n+ self.take_screenshot(\"horizontal_fieldset\")\n+\n [USER_REDACTED]_cases([\"desktop_size\", \"mobile_size\", \"rtl\", \"dark\", \"high_contrast\"])\n [USER_REDACTED]_settings(MESSAGE_LEVEL=10)\n def test_messages(self):" } ], "reviews": [ { "id": 3700386594, "user": "user_45c2e5489720", "state": "COMMENTED", "body": "[NAME_REDACTED] are a lot of regressions happening with this work 😢\nAdditionally, I found one `CSS` thing that should have been done before.\n```diff --git a/django/contrib/admin/static/admin/css/forms.css b/django/contrib/admin/static/admin/css/forms.css\nindex e3b7d58857..6294f368b6 100644\n--- a/django/contrib/admin/static/admin/css/forms.css\n+++ b/django/contrib/admin/static/admin/css/forms.css\n@@ -30,7 +30,8 @@ form .form-row p {\n flex-wrap: wrap;\n }\n \n-.form-multiline > div {\n+.form-multiline > div,\n+.form-multiline > fieldset {\n padding-bottom: 10px;\n }\n```\n\n## Before\n\n\"Screenshot\n\n## After\n\n\"Screenshot\n\nShould this be added to this PR? or would it be better to separate it?", "submitted_at": "2026-01-24T02:07:47+00:00" }, { "id": 3700577913, "user": "user_3a67c55598c5", "state": "COMMENTED", "body": null, "submitted_at": "2026-01-24T04:02:36+00:00" }, { "id": 3701494607, "user": "user_45c2e5489720", "state": "COMMENTED", "body": null, "submitted_at": "2026-01-24T12:18:11+00:00" }, { "id": 3738206318, "user": "user_45c2e5489720", "state": "APPROVED", "body": "Thank you ! It looks good to me 👍", "submitted_at": "2026-02-02T09:20:36+00:00" } ], "review_comments": [ { "id": 2723411328, "user": "user_45c2e5489720", "body": "It seems like the existing tests are failing(`admin_views.tests.SeleniumTests.test_populate_existing_object`) due to changing the field type. \nOf course, we could fix the tests, but instead of changing the field type, what do you think about using the `Course` model that was previously created for the fieldsets tests?\nI think we would just need to add `fieldsets` to the `ModelAdmin`.\n\nhttps://github.com/[USER_REDACTED]ngo/django/blob/68d110f1fe593b7a368486c41cd062563a74fe0a/tests/admin_views/models.py#L626-L639", "path": "tests/admin_views/models.py", "line": null, "side": "RIGHT", "created_at": "2026-01-24T01:46:50+00:00" }, { "id": 2723428257, "user": "user_45c2e5489720", "body": "What do you think about including something that conveys \"multiple fields\"? 🤔 I think it would be a bit clearer (like the \"multiline\" being added in CSS).", "path": "tests/admin_views/tests.py", "line": null, "side": "RIGHT", "created_at": "2026-01-24T02:07:31+00:00" }, { "id": 2723572133, "user": "user_3a67c55598c5", "body": "Sure thing. I was taking a shortcut and figured I'd hear a better idea :)", "path": "tests/admin_views/models.py", "line": null, "side": "RIGHT", "created_at": "2026-01-24T04:02:36+00:00" }, { "id": 2724089473, "user": "user_45c2e5489720", "body": "I think we should verify that the multiline container contains fieldset tags and at least 2 fields before taking the screenshot :)\n```diff --git a/tests/admin_views/tests.py b/tests/admin_views/tests.py\nindex 8ac5571f9d..8290c56138 100644\n--- a/tests/admin_views/tests.py\n+++ b/tests/admin_views/tests.py\n@@ -7081,12 +7081,23 @@ class SeleniumTests(AdminSeleniumTestCase):\n \n [USER_REDACTED]_cases([\"desktop_size\", \"mobile_size\", \"rtl\", \"dark\", \"high_contrast\"])\n def test_use_fieldset_fields_horizontal(self):\n+ from selenium.webdriver.common.by [NAME_REDACTED]\n+\n self.admin_login(\n username=\"super\", password=\"secret\", login_url=reverse(\"admin:index\")\n )\n self.selenium.get(\n self.live_server_url + reverse(\"admin:admin_views_mainprepopulated_add\")\n )\n+ multiline = self.selenium.find_element(\n+ By.CSS_SELECTOR, \"#content-main .field-pubdate .form-multiline\",\n+ )\n+ # Get direct children (div, fieldset) of multiline\n+ divs = multiline.find_elements(By.CSS_SELECTOR, \":scope > div\")\n+ fieldsets = multiline.find_elements(By.CSS_SELECTOR, \":scope > fieldset\")\n+ fields = divs + fieldsets\n+ self.assertGreater(len(fields), 1)\n+ self.assertGreater(len(fieldsets), 0)\n self.take_screenshot(\"horizontal_fieldset\")\n \n [USER_REDACTED]_cases([\"desktop_size\", \"mobile_size\", \"rtl\", \"dark\", \"high_contrast\"])\n```\nI'm not sure if using `:scope` is the best approach here 🥲", "path": "tests/admin_views/tests.py", "line": 7103, "side": "RIGHT", "created_at": "2026-01-24T12:18:11+00:00" } ], "meta": { "languages": [ "css", "py", "txt" ], "touches_tests": true, "review_state_summary": { "COMMENTED": 3, "APPROVED": 1 }, "meaningful_comment_count": 4, "has_approval": true, "has_changes_requested": false, "total_review_comments": 4 } } { "_id": "d62274b4c7f0aaed", "_schema_version": "1.0", "_cleaned_at": "2026-02-12T07:46:51.542480+00:00", "repo": "django/django", "repo_url": "https://github.com/django/django", "license_name": "BSD 3-Clause \"New\" or \"Revised\" License", "license_spdx": "BSD-3-Clause", "pr_number": 20574, "title": "Fixed #36878 -- Unified data type for *_together options in ModelState.", "body": "Ever since the beginning of Django's migration framework, there's been a bit of an inconsistency on how index_together and unique_together values have been stored on the ModelState[^1].\n\nIt's only really obvious, when looking at the current code for `from_model()`[^2] and the `rename_field()` state alteration code[^3].\n\nThe problem in the autodetector's detection of the `*_together` options as raised in the ticket, reinforces the inconsistency[^4]: the old value is being normalized to a set of tuples, whereas the new value is taken as-is.\n\nWhy this hasn't been caught before, is likely to the fact, that we never really look at a `to_state` that comes from migration operations in the autodetector. Instead, in both usages in Django[^5], [^6] the `to_state` is a `ProjectState.from_apps()`. And that state is consistently using sets of tuples and not lists of lists.\n\n[^1]: https://github.com/[USER_REDACTED]ngo/django/commit/67dcea711e92025d0e8676b869b7ef15dbc6db73#diff-5dd147e9e978e645313dd99eab3a7bab1f1cb0a53e256843adb68aeed71e61dcR85-R87\n[^2]: https://github.com/[USER_REDACTED]ngo/django/blob/b1ffa9a9d78b0c2c5ad6ed5a1d84e380d5cfd010/django/db/migrations/state.py#L842\n[^3]: https://github.com/[USER_REDACTED]ngo/django/blob/b1ffa9a9d78b0c2c5ad6ed5a1d84e380d5cfd010/django/db/migrations/state.py#L340-L345\n[^4]: https://github.com/[USER_REDACTED]ngo/django/blob/b1ffa9a9d78b0c2c5ad6ed5a1d84e380d5cfd010/django/db/migrations/autodetector.py#L1757-L1771\n[^5]: https://github.com/[USER_REDACTED]ngo/django/blob/2351c1b12cc9cf82d642f769c774bc3ea0cc4006/django/core/management/commands/makemigrations.py#L215-L219\n[^6]: https://github.com/[USER_REDACTED]ngo/django/blob/2351c1b12cc9cf82d642f769c774bc3ea0cc4006/django/core/management/commands/migrate.py#L329-L332\n\n#### Trac ticket number\n\n\n\nticket-36878\n\n#### Branch description\nProvide a concise overview of the issue or rationale behind the proposed changes.\n\n#### AI [NAME_REDACTED] (REQUIRED)\n\n- [x] **No AI tools were used** in preparing this PR.\n- [ ] **If AI tools were used**, I have disclosed which ones, and fully reviewed and verified their output.\n\n#### Checklist\n- [x] This PR follows the [contribution guidelines](https://docs.djangoproject.com/en/stable/internals/contributing/writing-code/submitting-patches/).\n- [x] This PR **does not** disclose a security vulnerability (see [vulnerability reporting](https://docs.djangoproject.com/en/stable/internals/security/)).\n- [x] This PR targets the `main` branch. \n- [x] The commit message is written in past tense, mentions the ticket number, and ends with a period.\n- [x] I have checked the \"Has patch\" ticket flag in the Trac system.\n- [x] I have added or updated relevant tests.\n- [ ] I have added or updated relevant docs, including release notes if applicable.\n- [ ] I have attached screenshots in both light and dark modes for any UI changes.", "author": "user_081d78d226d7", "created_at": "2026-01-23T15:23:51+00:00", "merged_at": "2026-01-28T21:13:05+00:00", "base_branch": "main", "head_branch": "fix-project-state-together-modelstate-mutation", "additions": 69, "deletions": 17, "changed_files": 4, "files": [ { "filename": "django/db/migrations/state.py", "status": "modified", "additions": 7, "deletions": 6, "changes": 13, "patch": "@@ -192,9 +192,10 @@ def alter_model_options(self, app_label, model_name, options, option_keys=None):\n def remove_model_options(self, app_label, model_name, option_name, value_to_remove):\n model_state = self.models[app_label, model_name]\n if objs := model_state.options.get(option_name):\n- model_state.options[option_name] = [\n- obj for obj in objs if tuple(obj) != tuple(value_to_remove)\n- ]\n+ new_value = [obj for obj in objs if tuple(obj) != tuple(value_to_remove)]\n+ if option_name in {\"index_together\", \"unique_together\"}:\n+ new_value = set(normalize_together(new_value))\n+ model_state.options[option_name] = new_value\n self.reload_model(app_label, model_name, delay=True)\n \n def alter_model_managers(self, app_label, model_name, managers):\n@@ -339,10 +340,10 @@ def rename_field(self, app_label, model_name, old_name, new_name):\n options = model_state.options\n for option in (\"index_together\", \"unique_together\"):\n if option in options:\n- options[option] = [\n- [new_name if n == old_name else n for n in together]\n+ options[option] = {\n+ tuple(new_name if n == old_name else n for n in together)\n for together in options[option]\n- ]\n+ }\n # Fix to_fields to refer to the new field.\n delay = True\n references = get_references(self, model_key, (old_name, found))" }, { "filename": "tests/migrations/test_autodetector.py", "status": "modified", "additions": 45, "deletions": 0, "changes": 45, "patch": "@@ -5590,6 +5590,51 @@ def test_remove_composite_pk(self):\n preserve_default=True,\n )\n \n+ def test_does_not_crash_after_rename_on_unique_together(self):\n+ fields = (\"first\", \"second\")\n+ before = self.make_project_state(\n+ [\n+ ModelState(\n+ \"app\",\n+ \"Foo\",\n+ [\n+ (\"id\", models.AutoField(primary_key=True)),\n+ (\"first\", models.IntegerField()),\n+ (\"second\", models.IntegerField()),\n+ ],\n+ options={\"unique_together\": {fields}},\n+ ),\n+ ]\n+ )\n+ after = before.clone()\n+ after.rename_field(\"app\", \"foo\", \"first\", \"first_renamed\")\n+\n+ changes = MigrationAutodetector(\n+ before, after, MigrationQuestioner({\"ask_rename\": True})\n+ )._detect_changes()\n+\n+ self.assertNumberMigrations(changes, \"app\", 1)\n+ self.assertOperationTypes(\n+ changes, \"app\", 0, [\"RenameField\", \"AlterUniqueTogether\"]\n+ )\n+ self.assertOperationAttributes(\n+ changes,\n+ \"app\",\n+ 0,\n+ 0,\n+ model_name=\"foo\",\n+ old_name=\"first\",\n+ new_name=\"first_renamed\",\n+ )\n+ self.assertOperationAttributes(\n+ changes,\n+ \"app\",\n+ 0,\n+ 1,\n+ name=\"foo\",\n+ unique_together={(\"first_renamed\", \"second\")},\n+ )\n+\n \n class MigrationSuggestNameTests(SimpleTestCase):\n def test_no_operations(self):" }, { "filename": "tests/migrations/test_base.py", "status": "modified", "additions": 3, "deletions": 4, "changes": 7, "patch": "@@ -290,14 +290,13 @@ def set_up_test_model(\n ):\n \"\"\"Creates a test model state and database table.\"\"\"\n # Make the \"current\" state.\n- model_options = {\n- \"swappable\": \"TEST_SWAP_MODEL\",\n- \"unique_together\": [[\"pink\", \"weight\"]] if unique_together else [],\n- }\n+ model_options = {\"swappable\": \"TEST_SWAP_MODEL\"}\n if options:\n model_options[\"permissions\"] = [(\"can_groom\", \"Can groom\")]\n if db_table:\n model_options[\"db_table\"] = db_table\n+ if unique_together:\n+ model_options[\"unique_together\"] = {(\"pink\", \"weight\")}\n operations = [\n migrations.CreateModel(\n \"Pony\"," }, { "filename": "tests/migrations/test_operations.py", "status": "modified", "additions": 14, "deletions": 7, "changes": 21, "patch": "@@ -3336,11 +3336,11 @@ def test_rename_field_unique_together(self):\n # unique_together has the renamed column.\n self.assertIn(\n \"blue\",\n- new_state.models[\"test_rnflut\", \"pony\"].options[\"unique_together\"][0],\n+ list(new_state.models[\"test_rnflut\", \"pony\"].options[\"unique_together\"])[0],\n )\n self.assertNotIn(\n \"pink\",\n- new_state.models[\"test_rnflut\", \"pony\"].options[\"unique_together\"][0],\n+ list(new_state.models[\"test_rnflut\", \"pony\"].options[\"unique_together\"])[0],\n )\n # Rename field.\n self.assertColumnExists(\"test_rnflut_pony\", \"pink\")\n@@ -3377,7 +3377,7 @@ def test_rename_field_index_together(self):\n (\"weight\", models.FloatField()),\n ],\n options={\n- \"index_together\": [(\"weight\", \"pink\")],\n+ \"index_together\": {(\"weight\", \"pink\")},\n },\n ),\n ]\n@@ -3390,10 +3390,12 @@ def test_rename_field_index_together(self):\n self.assertNotIn(\"pink\", new_state.models[\"test_rnflit\", \"pony\"].fields)\n # index_together has the renamed column.\n self.assertIn(\n- \"blue\", new_state.models[\"test_rnflit\", \"pony\"].options[\"index_together\"][0]\n+ \"blue\",\n+ list(new_state.models[\"test_rnflit\", \"pony\"].options[\"index_together\"])[0],\n )\n self.assertNotIn(\n- \"pink\", new_state.models[\"test_rnflit\", \"pony\"].options[\"index_together\"][0]\n+ \"pink\",\n+ list(new_state.models[\"test_rnflit\", \"pony\"].options[\"index_together\"])[0],\n )\n \n # Rename field.\n@@ -3952,7 +3954,7 @@ def test_rename_index_unnamed_index(self):\n (\"weight\", models.FloatField()),\n ],\n options={\n- \"index_together\": [(\"weight\", \"pink\")],\n+ \"index_together\": {(\"weight\", \"pink\")},\n },\n ),\n ]\n@@ -3972,6 +3974,11 @@ def test_rename_index_unnamed_index(self):\n )\n new_state = project_state.clone()\n operation.state_forwards(app_label, new_state)\n+ # Ensure the model state has the correct type for the index_together\n+ # option.\n+ self.assertIsInstance(\n+ new_state.models[app_label, \"pony\"].options[\"index_together\"], set\n+ )\n # Rename index.\n with connection.schema_editor() as editor:\n operation.database_forwards(app_label, editor, project_state, new_state)\n@@ -4079,7 +4086,7 @@ def test_rename_index_state_forwards_unnamed_index(self):\n (\"weight\", models.FloatField()),\n ],\n options={\n- \"index_together\": [(\"weight\", \"pink\")],\n+ \"index_together\": {(\"weight\", \"pink\")},\n },\n ),\n ]" } ], "reviews": [ { "id": 3698133887, "user": "user_081d78d226d7", "state": "COMMENTED", "body": null, "submitted_at": "2026-01-23T15:30:31+00:00" }, { "id": 3698135714, "user": "user_081d78d226d7", "state": "COMMENTED", "body": null, "submitted_at": "2026-01-23T15:30:51+00:00" }, { "id": 3698136133, "user": "user_081d78d226d7", "state": "COMMENTED", "body": null, "submitted_at": "2026-01-23T15:30:57+00:00" }, { "id": 3698225072, "user": "user_057de2f3b132", "state": "APPROVED", "body": null, "submitted_at": "2026-01-23T15:47:24+00:00" }, { "id": 3717148345, "user": "user_3a67c55598c5", "state": "COMMENTED", "body": null, "submitted_at": "2026-01-28T14:53:53+00:00" }, { "id": 3717150377, "user": "user_3a67c55598c5", "state": "COMMENTED", "body": "Thanks [USER_REDACTED]!", "submitted_at": "2026-01-28T14:55:06+00:00" }, { "id": 3717207416, "user": "user_3a67c55598c5", "state": "COMMENTED", "body": null, "submitted_at": "2026-01-28T15:04:51+00:00" }, { "id": 3717308560, "user": "user_081d78d226d7", "state": "COMMENTED", "body": null, "submitted_at": "2026-01-28T15:21:10+00:00" }, { "id": 3717344857, "user": "user_3a67c55598c5", "state": "APPROVED", "body": "🚀", "submitted_at": "2026-01-28T15:26:16+00:00" } ], "review_comments": [ { "id": 2721704994, "user": "user_081d78d226d7", "body": "I haven't been able to come up with a test triggering the same problem as reported, but there is a type inconsistency here.", "path": "django/db/migrations/state.py", "line": 195, "side": "RIGHT", "created_at": "2026-01-23T15:30:31+00:00" }, { "id": 2721706428, "user": "user_081d78d226d7", "body": "```suggestion\n options[option] = {\n```", "path": "django/db/migrations/state.py", "line": null, "side": "RIGHT", "created_at": "2026-01-23T15:30:51+00:00" }, { "id": 2721706779, "user": "user_081d78d226d7", "body": "```suggestion\n }\n```", "path": "django/db/migrations/state.py", "line": null, "side": "RIGHT", "created_at": "2026-01-23T15:30:57+00:00" }, { "id": 2737017476, "user": "user_3a67c55598c5", "body": "I added some minimal coverage like this:\n```diff\ndiff --git a/tests/migrations/test_operations.py b/tests/migrations/test_operations.py\nindex 28d65a7ecf..d3a2f732f2 100644\n--- a/tests/migrations/test_operations.py\n+++ b/tests/migrations/test_operations.py\n@@ -3974,6 +3974,7 @@ class OperationTests(OperationTestBase):\n )\n new_state = project_state.clone()\n operation.state_forwards(app_label, new_state)\n+ self.assertIsInstance(new_state.models[app_label, \"pony\"].options[\"index_together\"], set)\n # Rename index.\n with connection.schema_editor() as editor:\n operation.database_forwards(app_label, editor, project_state, new_state)\n```\n\nUnless you think that's testing an implementation detail? Poking around, we have other assertions against `new_state.models`.", "path": "django/db/migrations/state.py", "line": 195, "side": "RIGHT", "created_at": "2026-01-28T14:53:53+00:00" }, { "id": 2737019284, "user": "user_3a67c55598c5", "body": "You can chop, we just leave ticket references in the blame these days.", "path": "tests/migrations/test_autodetector.py", "line": null, "side": "RIGHT", "created_at": "2026-01-28T14:54:19+00:00" }, { "id": 2737068892, "user": "user_3a67c55598c5", "body": "If this assertion feels like a non sequitur, we could pull it out into a new test method.", "path": "django/db/migrations/state.py", "line": 195, "side": "RIGHT", "created_at": "2026-01-28T15:04:51+00:00" }, { "id": 2737153176, "user": "user_081d78d226d7", "body": "That's great. Thank you!", "path": "django/db/migrations/state.py", "line": 195, "side": "RIGHT", "created_at": "2026-01-28T15:21:10+00:00" } ], "meta": { "languages": [ "py" ], "touches_tests": true, "review_state_summary": { "COMMENTED": 7, "APPROVED": 2 }, "meaningful_comment_count": 7, "has_approval": true, "has_changes_requested": false, "total_review_comments": 7 } } { "_id": "4177802d17741f15", "_schema_version": "1.0", "_cleaned_at": "2026-02-12T07:46:51.546480+00:00", "repo": "django/django", "repo_url": "https://github.com/django/django", "license_name": "BSD 3-Clause \"New\" or \"Revised\" License", "license_spdx": "BSD-3-Clause", "pr_number": 20538, "title": "Fixed #36865 -- Removed casting from exact lookups in admin searches.", "body": "Fixes https://code.djangoproject.com/ticket/36865\n\n## [NAME_REDACTED] PR fixes a performance regression introduced in PR #17885.\n\nThe `Cast` to `CharField` for non-string field exact lookups prevents database index usage on primary key fields, generating SQL like:\n\n```sql\nWHERE (\"table\".\"id\")::varchar = '123'\n```\n\nThis cannot use the primary key index and causes full table scans, resulting in timeouts on large tables (reported in [ticket #26001 comment 24](https://code.djangoproject.com/ticket/26001#comment:24)), and discovered in a project I work on at https://github.com/freelawproject/courtlistener/issues/6790.\n\n## [NAME_REDACTED] the casting approach introduced in #17885, and replace it with field validation that uses `to_python` on the results of `smart_split` to ensure that we only apply field-term pairs that make sense. For example: \n\n - searching a PrimaryKey field for \"foo\" --> Nope!\n - searching a TextField for \"foo\" --> Yes!\n - searching a TextField for \"123\" --> Close enough. Yes!\n\nAnd so forth. \n\nThis should ensure DB indexes are used and that we don't send nonsensical queries in the first place. \n\n## Trac tickets\n\nIntroducing issue: https://code.djangoproject.com/ticket/26001\nSolving it: https://code.djangoproject.com/ticket/36865", "author": "user_c010523698ce", "created_at": "2026-01-15T00:35:58+00:00", "merged_at": "2026-01-30T16:45:39+00:00", "base_branch": "main", "head_branch": "fix-admin-search-cast-performance", "additions": 128, "deletions": 26, "changed_files": 3, "files": [ { "filename": "django/contrib/admin/options.py", "status": "modified", "additions": 37, "deletions": 26, "changes": 63, "patch": "@@ -41,7 +41,6 @@\n from django.core.paginator import Paginator\n from django.db import models, router, transaction\n from django.db.models.constants import LOOKUP_SEP\n-from django.db.models.functions import Cast\n from django.forms.formsets import DELETION_FIELD_NAME, all_valid\n from django.forms.models import (\n BaseInlineFormSet,\n@@ -1137,6 +1136,12 @@ def get_search_results(self, request, queryset, search_term):\n \n # Apply keyword searches.\n def construct_search(field_name):\n+ \"\"\"\n+ Return a tuple of (lookup, field_to_validate).\n+\n+ field_to_validate is set for non-text exact lookups so that\n+ invalid search terms can be skipped (preserving index usage).\n+ \"\"\"\n if field_name.startswith(\"^\"):\n return \"%s__istartswith\" % field_name.removeprefix(\"^\"), None\n elif field_name.startswith(\"=\"):\n@@ -1148,7 +1153,7 @@ def construct_search(field_name):\n lookup_fields = field_name.split(LOOKUP_SEP)\n # Go through the fields, following all relations.\n prev_field = None\n- for i, path_part in enumerate(lookup_fields):\n+ for path_part in lookup_fields:\n if path_part == \"pk\":\n path_part = opts.pk.name\n try:\n@@ -1159,15 +1164,9 @@ def construct_search(field_name):\n if path_part == \"exact\" and not isinstance(\n prev_field, (models.CharField, models.TextField)\n ):\n- field_name_without_exact = \"__\".join(lookup_fields[:i])\n- alias = Cast(\n- field_name_without_exact,\n- output_field=models.CharField(),\n- )\n- alias_name = \"_\".join(lookup_fields[:i])\n- return f\"{alias_name}_str\", alias\n- else:\n- return field_name, None\n+ # Use prev_field to validate the search term.\n+ return field_name, prev_field\n+ return field_name, None\n else:\n prev_field = field\n if hasattr(field, \"path_infos\"):\n@@ -1179,30 +1178,42 @@ def construct_search(field_name):\n may_have_duplicates = False\n search_fields = self.get_search_fields(request)\n if search_fields and search_term:\n- str_aliases = {}\n orm_lookups = []\n for field in search_fields:\n- lookup, str_alias = construct_search(str(field))\n- orm_lookups.append(lookup)\n- if str_alias:\n- str_aliases[lookup] = str_alias\n-\n- if str_aliases:\n- queryset = queryset.alias(**str_aliases)\n+ orm_lookups.append(construct_search(str(field)))\n \n term_queries = []\n for bit in smart_split(search_term):\n if bit.startswith(('\"', \"'\")) and bit[0] == bit[-1]:\n bit = unescape_string_literal(bit)\n- or_queries = models.Q.create(\n- [(orm_lookup, bit) for orm_lookup in orm_lookups],\n- connector=models.Q.OR,\n- )\n- term_queries.append(or_queries)\n- queryset = queryset.filter(models.Q.create(term_queries))\n+ # Build term lookups, skipping values invalid for their field.\n+ bit_lookups = []\n+ for orm_lookup, validate_field in orm_lookups:\n+ if validate_field is not None:\n+ formfield = validate_field.formfield()\n+ try:\n+ if formfield is not None:\n+ value = formfield.to_python(bit)\n+ else:\n+ # Fields like AutoField lack a form field.\n+ value = validate_field.to_python(bit)\n+ except ValidationError:\n+ # Skip this lookup for invalid values.\n+ continue\n+ else:\n+ value = bit\n+ bit_lookups.append((orm_lookup, value))\n+ if bit_lookups:\n+ or_queries = models.Q.create(bit_lookups, connector=models.Q.OR)\n+ term_queries.append(or_queries)\n+ else:\n+ # No valid lookups: add a filter that returns nothing.\n+ term_queries.append(models.Q(pk__in=[]))\n+ if term_queries:\n+ queryset = queryset.filter(models.Q.create(term_queries))\n may_have_duplicates |= any(\n lookup_spawns_duplicates(self.opts, search_spec)\n- for search_spec in orm_lookups\n+ for search_spec, _ in orm_lookups\n )\n return queryset, may_have_duplicates" }, { "filename": "tests/admin_changelist/models.py", "status": "modified", "additions": 7, "deletions": 0, "changes": 7, "patch": "@@ -140,3 +140,10 @@ class CharPK(models.Model):\n class ProxyUser(User):\n class Meta:\n proxy = True\n+\n+\n+class MixedFieldsModel(models.Model):\n+ \"\"\"Model with multiple field types for testing search validation.\"\"\"\n+\n+ int_field = models.IntegerField(null=True, blank=True)\n+ json_field = models.JSONField(null=True, blank=True)" }, { "filename": "tests/admin_changelist/tests.py", "status": "modified", "additions": 84, "deletions": 0, "changes": 84, "patch": "@@ -66,6 +66,7 @@\n Group,\n Invitation,\n Membership,\n+ MixedFieldsModel,\n Musician,\n OrderedObject,\n Parent,\n@@ -856,6 +857,89 @@ def test_custom_lookup_with_pk_shortcut(self):\n cl = m.get_changelist_instance(request)\n self.assertCountEqual(cl.queryset, [abcd])\n \n+ def test_exact_lookup_with_invalid_value(self):\n+ Child.objects.create(name=\"Test\", age=10)\n+ m = admin.ModelAdmin(Child, custom_site)\n+ m.search_fields = [\"pk__exact\"]\n+\n+ request = self.factory.get(\"/\", data={SEARCH_VAR: \"foo\"})\n+ request.user = self.superuser\n+\n+ # Invalid values are gracefully ignored.\n+ cl = m.get_changelist_instance(request)\n+ self.assertCountEqual(cl.queryset, [])\n+\n+ def test_exact_lookup_mixed_terms(self):\n+ \"\"\"\n+ Multi-term search validates each term independently.\n+\n+ For 'foo 123' with search_fields=['name__icontains', 'age__exact']:\n+ - 'foo': age lookup skipped (invalid), name lookup used\n+ - '123': both lookups used (valid for age)\n+ [NAME_REDACTED] should be used; invalid lookups are simply skipped.\n+ \"\"\"\n+ child = Child.objects.create(name=\"foo123\", age=123)\n+ Child.objects.create(name=\"other\", age=456)\n+ m = admin.ModelAdmin(Child, custom_site)\n+ m.search_fields = [\"name__icontains\", \"age__exact\"]\n+\n+ request = self.factory.get(\"/\", data={SEARCH_VAR: \"foo 123\"})\n+ request.user = self.superuser\n+\n+ # One result matching on foo and 123.\n+ cl = m.get_changelist_instance(request)\n+ self.assertCountEqual(cl.queryset, [child])\n+\n+ # \"xyz\" - invalid for age (skipped), no match for name either.\n+ request = self.factory.get(\"/\", data={SEARCH_VAR: \"xyz\"})\n+ request.user = self.superuser\n+ cl = m.get_changelist_instance(request)\n+ self.assertCountEqual(cl.queryset, [])\n+\n+ def test_exact_lookup_with_more_lenient_formfield(self):\n+ \"\"\"\n+ Exact lookups on BooleanField use formfield().to_python() for lenient\n+ parsing. Using model field's to_python() would reject 'false' whereas\n+ the form field accepts it.\n+ \"\"\"\n+ obj = UnorderedObject.objects.create(bool=False)\n+ UnorderedObject.objects.create(bool=True)\n+ m = admin.ModelAdmin(UnorderedObject, custom_site)\n+ m.search_fields = [\"bool__exact\"]\n+\n+ # 'false' is accepted by [NAME_REDACTED] by [NAME_REDACTED]\n+ request = self.factory.get(\"/\", data={SEARCH_VAR: \"false\"})\n+ request.user = self.superuser\n+\n+ cl = m.get_changelist_instance(request)\n+ self.assertCountEqual(cl.queryset, [obj])\n+\n+ def test_exact_lookup_validates_each_field_independently(self):\n+ \"\"\"\n+ Each field validates the search term independently without leaking\n+ converted values between fields.\n+\n+ \"3.\" is valid for IntegerField (converts to 3) but invalid for\n+ JSONField. The converted value must not leak to the JSONField check.\n+ \"\"\"\n+ # obj_int has int_field=3, should match \"3.\" via IntegerField.\n+ obj_int = MixedFieldsModel.objects.create(\n+ int_field=3, json_field={\"key\": \"value\"}\n+ )\n+ # obj_json has json_field=3, should NOT match \"3.\" because \"3.\" is\n+ # invalid JSON.\n+ MixedFieldsModel.objects.create(int_field=99, json_field=3)\n+ m = admin.ModelAdmin(MixedFieldsModel, custom_site)\n+ m.search_fields = [\"int_field__exact\", \"json_field__exact\"]\n+\n+ # \"3.\" is valid for int (becomes 3) but invalid JSON.\n+ # Only obj_int should match via int_field.\n+ request = self.factory.get(\"/\", data={SEARCH_VAR: \"3.\"})\n+ request.user = self.superuser\n+\n+ cl = m.get_changelist_instance(request)\n+ self.assertCountEqual(cl.queryset, [obj_int])\n+\n def test_search_with_exact_lookup_for_non_string_field(self):\n child = Child.objects.create(name=\"Asher\", age=11)\n model_admin = ChildAdmin(Child, custom_site)" } ], "reviews": [ { "id": 3663429620, "user": "user_cdda8932ec17", "state": "COMMENTED", "body": "We'll want a dedicated ticket for that and likely a solution that isn't specific to whether a not a search field is a primary as casting to text is harmful in a lot of other cases.", "submitted_at": "2026-01-15T00:49:03+00:00" }, { "id": 3663452979, "user": "user_cdda8932ec17", "state": "COMMENTED", "body": null, "submitted_at": "2026-01-15T00:57:41+00:00" }, { "id": 3663491293, "user": "user_c010523698ce", "state": "COMMENTED", "body": null, "submitted_at": "2026-01-15T01:19:16+00:00" }, { "id": 3666156943, "user": "user_cdda8932ec17", "state": "COMMENTED", "body": null, "submitted_at": "2026-01-15T15:21:46+00:00" }, { "id": 3667456239, "user": "user_c010523698ce", "state": "COMMENTED", "body": null, "submitted_at": "2026-01-15T20:32:03+00:00" }, { "id": 3671433327, "user": "user_3a67c55598c5", "state": "COMMENTED", "body": null, "submitted_at": "2026-01-16T15:26:44+00:00" }, { "id": 3673173260, "user": "user_c010523698ce", "state": "COMMENTED", "body": null, "submitted_at": "2026-01-16T23:53:35+00:00" }, { "id": 3700357459, "user": "user_cdda8932ec17", "state": "COMMENTED", "body": null, "submitted_at": "2026-01-24T01:27:20+00:00" }, { "id": 3701866155, "user": "user_c010523698ce", "state": "COMMENTED", "body": null, "submitted_at": "2026-01-24T15:50:49+00:00" }, { "id": 3718025497, "user": "user_3a67c55598c5", "state": "COMMENTED", "body": "Thanks [USER_REDACTED], I have initial comments 👍", "submitted_at": "2026-01-28T17:26:10+00:00" }, { "id": 3720081015, "user": "user_c010523698ce", "state": "COMMENTED", "body": null, "submitted_at": "2026-01-29T01:45:37+00:00" }, { "id": 3723445002, "user": "user_3a67c55598c5", "state": "COMMENTED", "body": "Thanks for adding the test, and many thanks for being super responsive! \n\nOne more finding for you.", "submitted_at": "2026-01-29T15:33:56+00:00" }, { "id": 3723961630, "user": "user_c010523698ce", "state": "COMMENTED", "body": null, "submitted_at": "2026-01-29T17:02:42+00:00" }, { "id": 3724078186, "user": "user_3a67c55598c5", "state": "APPROVED", "body": "Wonderful, thank you!", "submitted_at": "2026-01-29T17:29:01+00:00" } ], "review_comments": [ { "id": 2692557078, "user": "user_cdda8932ec17", "body": "I think the problem has little to do with whether or not a primary key is targeted. The cast will be harmful in all case where the field is indexed for example.\n\nA better solution here would likely be to attempt `prev_field.to_python(...)` with the search term an in cases where the value is valid (no exception is raised) then don't perform a `Cast`.\n\nIn other words, `prev_field.to_python(\"123\")` (assuming it's an `IntegerField` instance) passes and returns `123` so we know that `field__exact=\"123\"` doesn't require a cast while `prev_field.to_python(\"foo\")` raises a `ValueError` so we know we must cast.", "path": "django/contrib/admin/options.py", "line": null, "side": "RIGHT", "created_at": "2026-01-15T00:46:41+00:00" }, { "id": 2692575770, "user": "user_cdda8932ec17", "body": "This is re-introducing the admin crash problem ticket-26001 fixed which you can demonstrate by doing\n\n```suggestion\n request = self.factory.get(\"/\", data={SEARCH_VAR: \"foo\"})\n```\n\nA cast (or an exclusion of terms) is necessary when dealing with string that are not string representation of integers.", "path": "tests/admin_changelist/tests.py", "line": null, "side": "RIGHT", "created_at": "2026-01-15T00:57:41+00:00" }, { "id": 2692610146, "user": "user_c010523698ce", "body": "Thanks. I was trying to keep things narrow and I've never messed around at this level of admin. I just pushed a tweak that uses `to_python`. I'm a bit over my head, but hopefully this addresses your concern.", "path": "django/contrib/admin/options.py", "line": null, "side": "RIGHT", "created_at": "2026-01-15T01:19:16+00:00" }, { "id": 2694820830, "user": "user_cdda8932ec17", "body": "This doesn't account for multiple search terms (see `smart_split(search_term)` below) where some might need cast and others don't.\n\nFor example, if your search for `foo 123` the resulting query should be\n\n```python\nalias(\n int_field_str=Cast(\"int_field\", TextField())\n).filter(\n Q(int_field_str=\"foo\") | Q(int_field=\"123\")\n)\n```\n\nwith your current path it'll be doing\n\n```python\nalias(\n int_field_str=Cast(\"int_field\", TextField())\n).filter(\n Q(int_field_str=\"foo\") | Q(int_field_str=123)\n)\n```\n\nSee how #18765 changed the logic to no longer be search term `bit` specific and how we might need to restore it.", "path": "django/contrib/admin/options.py", "line": null, "side": "RIGHT", "created_at": "2026-01-15T15:21:46+00:00" }, { "id": 2695860117, "user": "user_c010523698ce", "body": "Got it. You know, Claude suggested this yesterday and I thought it would be too invasive, but your suggestion on code.djangoproject.org is even better, and I've just pushed that, including another test to prevent regression.\n\nThank you again.", "path": "django/contrib/admin/options.py", "line": null, "side": "RIGHT", "created_at": "2026-01-15T20:32:03+00:00" }, { "id": 2698951633, "user": "user_3a67c55598c5", "body": "Given that, could I ask you to update the PR body \"solution\" part?", "path": "django/contrib/admin/options.py", "line": null, "side": "RIGHT", "created_at": "2026-01-16T15:26:44+00:00" }, { "id": 2700348512, "user": "user_c010523698ce", "body": "Sure. Done.", "path": "django/contrib/admin/options.py", "line": null, "side": "RIGHT", "created_at": "2026-01-16T23:53:35+00:00" }, { "id": 2723384880, "user": "user_cdda8932ec17", "body": "You could re-assign `bit` here to use the proper expected type\n\n```suggestion\n but = validate_field.to_python(bit)\n```", "path": "django/contrib/admin/options.py", "line": null, "side": "RIGHT", "created_at": "2026-01-24T01:27:20+00:00" }, { "id": 2724279784, "user": "user_c010523698ce", "body": "All set and pushed.", "path": "django/contrib/admin/options.py", "line": null, "side": "RIGHT", "created_at": "2026-01-24T15:50:49+00:00" }, { "id": 2737719890, "user": "user_3a67c55598c5", "body": "Did you give some thought to Simon's suggestion to use `.formfield()`? I expect some behavior differences, e.g.:\n\n```py\nIn [1]: from django.db.models.fields import [NAME_REDACTED] [2]: f = BooleanField()\n\nIn [3]: f.to_python('false')\n---------------------------------------------------------------------------\n[NAME_REDACTED] (most recent call last)\n[NAME_REDACTED][3], line 1\n----> 1 f.to_python('false')\n\nFile ~/django/django/db/models/fields/__init__.py:1179, in BooleanField.to_python(self, value)\n 1177 if value in (\"f\", \"False\", \"0\"):\n 1178 return False\n-> 1179 raise exceptions.ValidationError(\n 1180 self.error_messages[\"invalid_nullable\" if self.null else \"invalid\"],\n 1181 code=\"invalid\",\n 1182 params={\"value\": value},\n 1183 )\n\nValidationError: ['“false” value must be either True or False.']\n\nIn [4]: ff = f.formfield()\n\nIn [5]: ff.to_python('false')\nOut[5]: False\n\nIn [6]: ff.to_python('garbage')\nOut[6]: True\n```\n\nCan you look into this and add a test that will fail if the model field is used instead of the form field?", "path": "django/contrib/admin/options.py", "line": null, "side": "RIGHT", "created_at": "2026-01-28T17:26:01+00:00" }, { "id": 2739394523, "user": "user_c010523698ce", "body": "Sorry, I missed their comment about this (and, again, I'm trying not to make many changes).\n\nI think it makes sense to be more lenient here and use formfields instead of model fields. I just pushed a tweak and a test accordingly. I don't have tests working locally, so I'll update Track once tests are set to go.\n\nThanks for the review.", "path": "django/contrib/admin/options.py", "line": null, "side": "RIGHT", "created_at": "2026-01-29T01:45:37+00:00" }, { "id": 2742232366, "user": "user_3a67c55598c5", "body": "I think we shouldn't shadow the outer loop variable.\n\nI found that with two fields, e.g. IntegerField and JSONField (and with search fields `[\"int__exact\", \"json__exact\"]`), a bit that was only valid as an int but not as json (e.g. \"3.\"), translated into valid `Q` objects for both fields instead of only the int field.\n\nThe `bit` from the `IntegerField.to_python()` result was still `3` on the second loop iteration, which became a valid input to `JSONField.to_python()`.\n\nCan you address & add a test?", "path": "django/contrib/admin/options.py", "line": null, "side": "RIGHT", "created_at": "2026-01-29T15:30:27+00:00" }, { "id": 2742643434, "user": "user_c010523698ce", "body": "Nice catch, thanks. Fixed with a test and pushed.", "path": "django/contrib/admin/options.py", "line": null, "side": "RIGHT", "created_at": "2026-01-29T17:02:42+00:00" }, { "id": 2742731412, "user": "user_3a67c55598c5", "body": "We could return some some sort of sentinel here that signals it's okay to skip this `orm_lookup` when calculating `may_have_duplicates` below, but this is just a subtle optimization opportunity to avoid a `distinct()` later on, and I'm comfortable leaving it for someone else in a follow-up 👍 .", "path": "django/contrib/admin/options.py", "line": 1202, "side": "RIGHT", "created_at": "2026-01-29T17:24:03+00:00" } ], "meta": { "languages": [ "py" ], "touches_tests": true, "review_state_summary": { "COMMENTED": 13, "APPROVED": 1 }, "meaningful_comment_count": 14, "has_approval": true, "has_changes_requested": false, "total_review_comments": 14 } } { "_id": "f1a029dced7a7245", "_schema_version": "1.0", "_cleaned_at": "2026-02-12T07:46:51.546480+00:00", "repo": "django/django", "repo_url": "https://github.com/django/django", "license_name": "BSD 3-Clause \"New\" or \"Revised\" License", "license_spdx": "BSD-3-Clause", "pr_number": 20535, "title": "Fixed #36856 -- Mentioned needsnewfeatureprocess resolution in contributor docs.", "body": "#### Trac ticket number\n\n ticket-36856\n\n #### Branch description\n\n Documents the new `needsnewfeatureprocess` resolution state in the triaging tickets documentation, as proposed in the [forum discussion](https://forum.djangoproject.com/t/volunteers-wanted-to-update-triage-workflow-docs/37937/).\n\n **Changes:**\n - Added `needsnewfeatureprocess` to the \"[NAME_REDACTED]\" section with description and reference to the new features process\n - Updated reopening guidance to include tickets marked as `needsnewfeatureprocess`\n - Updated contribution process diagram (SVG and PDF) to show the new closed state\n\n #### AI [NAME_REDACTED] (REQUIRED)\n\n - [x] **No AI tools were used** in preparing this PR.\n - [ ] **If AI tools were used**, I have disclosed which ones, and fully reviewed and verified their output.\n\n #### Checklist\n\n - [x] This PR follows the [contribution guidelines](https://docs.djangoproject.com/en/stable/internals/contributing/writing-code/submitting-patches/). \n - [x] This PR **does not** disclose a security vulnerability (see [vulnerability reporting](https://docs.djangoproject.com/en/stable/internals/security/)).\n - [x] This PR targets the `main` branch.\n - [x] The commit message is written in past tense, mentions the ticket number, and ends with a period.\n - [x] I have checked the \"Has patch\" ticket flag in the Trac system.\n - [ ] I have added or updated relevant tests.\n - [x] I have added or updated relevant docs, including release notes if applicable.\n - [ ] I have attached screenshots in both light and dark modes for any UI changes.", "author": "user_e930d3b308e4", "created_at": "2026-01-14T07:34:02+00:00", "merged_at": "2026-01-15T12:27:02+00:00", "base_branch": "main", "head_branch": "ticket_36856", "additions": 16, "deletions": 5, "changed_files": 5, "files": [ { "filename": "docs/internals/_images/contribution_process.pdf", "status": "modified", "additions": 0, "deletions": 0, "changes": 0, "patch": null }, { "filename": "docs/internals/_images/contribution_process.svg", "status": "modified", "additions": 1, "deletions": 1, "changes": 2, "patch": null }, { "filename": "docs/internals/contributing/bugs-and-features.txt", "status": "modified", "additions": 3, "deletions": 0, "changes": 3, "patch": "@@ -27,6 +27,9 @@ Before reporting a bug on the `ticket tracker\n * Don't reopen issues that have been marked \"wontfix\" without finding consensus\n to do so on the `[NAME_REDACTED]`_.\n \n+* Don't reopen issues that have been marked \"needsnewfeatureprocess\" without\n+ shepherding an issue through the `new feature ideas`_ GitHub project.\n+\n * Don't use the ticket tracker for lengthy discussions, because they're\n likely to get lost. If a particular ticket is controversial, please move the\n discussion to the `[NAME_REDACTED]`_." }, { "filename": "docs/internals/contributing/triaging-tickets.txt", "status": "modified", "additions": 11, "deletions": 4, "changes": 15, "patch": "@@ -327,6 +327,11 @@ A ticket can be resolved in a number of ways:\n close a ticket. Always use the forum to get a consensus before reopening\n tickets closed as \"wontfix\".\n \n+* needsnewfeatureprocess\n+ Used when the ticket merits a new feature, which will need to get\n+ community input and support.\n+ See the :ref:`process for suggesting new features `.\n+\n * duplicate\n Used when another ticket covers the same issue. By [NAME_REDACTED], we keep all the discussion in one place, which helps\n@@ -344,8 +349,10 @@ A ticket can be resolved in a number of ways:\n If you believe that the ticket was closed in error -- because you're\n still having the issue, or it's popped up somewhere else, or the triagers have\n made a mistake -- please reopen the ticket and provide further information.\n-Again, please do not reopen tickets that have been marked as \"wontfix\" and\n-bring the issue to the `[NAME_REDACTED]`_ instead.\n+Again, please do not reopen tickets that have been marked as \"wontfix\" or\n+\"needsnewfeatureprocess\". For \"wontfix\" tickets, bring the issue to the\n+`[NAME_REDACTED]`_ instead. For \"needsnewfeatureprocess\" tickets, propose the\n+feature through the :ref:`new features process `.\n \n .. _how-can-i-help-with-triaging:\n \n@@ -361,8 +368,8 @@ reset page`_.\n \n Then, you can help out by:\n \n-* Closing \"Unreviewed\" tickets as \"invalid\", \"worksforme\", or \"duplicate\", or\n- \"wontfix\".\n+* Closing \"Unreviewed\" tickets as \"invalid\", \"worksforme\", \"duplicate\",\n+ \"wontfix\", or \"needsnewfeatureprocess\".\n \n * Closing \"Unreviewed\" tickets as \"needsinfo\" when the description is too\n sparse to be actionable." }, { "filename": "docs/spelling_wordlist", "status": "modified", "additions": 1, "deletions": 0, "changes": 1, "patch": "@@ -310,6 +310,7 @@ Nanggroe\n natively\n nd\n needsinfo\n+needsnewfeatureprocess\n německy\n nginx\n noding" } ], "reviews": [ { "id": 3660598215, "user": "user_3a67c55598c5", "state": "COMMENTED", "body": "Thanks 👍", "submitted_at": "2026-01-14T12:54:16+00:00" }, { "id": 3662306424, "user": "user_3a67c55598c5", "state": "APPROVED", "body": null, "submitted_at": "2026-01-14T18:59:37+00:00" } ], "review_comments": [ { "id": 2690319748, "user": "user_3a67c55598c5", "body": "Can we update this to reflect that the next stop for `needsnewfeatureprocess` tickets is the new-features process/repo, not necessarily the forum?", "path": "docs/internals/contributing/triaging-tickets.txt", "line": null, "side": "RIGHT", "created_at": "2026-01-14T12:54:09+00:00" } ], "meta": { "languages": [ "pdf", "svg", "txt" ], "touches_tests": false, "review_state_summary": { "COMMENTED": 1, "APPROVED": 1 }, "meaningful_comment_count": 1, "has_approval": true, "has_changes_requested": false, "total_review_comments": 1 } } { "_id": "1542f941074f65dc", "_schema_version": "1.0", "_cleaned_at": "2026-02-12T07:46:51.546480+00:00", "repo": "django/django", "repo_url": "https://github.com/django/django", "license_name": "BSD 3-Clause \"New\" or \"Revised\" License", "license_spdx": "BSD-3-Clause", "pr_number": 20528, "title": "Fixed #36850 -- Prevented admin filter sidebar from wrapping below the changelist.", "body": "ticket-36850\n#### Branch description\nThe fix removes `flex-wrap` from `.changelist-form-container` and adds `min-width` to the main content container to prevent the sidebar from wrapping below the changelist.\n\n#### Screenshot\n##### Before\n(Light mode)\n\"image\"\n\n(Dark mode)\n\"image\"\n\n##### After\n(Light mode)\n\"image\"\n\n(Dark mode)\n\"image\"\n\n#### AI [NAME_REDACTED] (REQUIRED)\n\n- [x] **No AI tools were used** in preparing this PR.\n- [ ] **If AI tools were used**, I have disclosed which ones, and fully reviewed and verified their output.\n\n#### Checklist\n- [x] This PR follows the [contribution guidelines](https://docs.djangoproject.com/en/stable/internals/contributing/writing-code/submitting-patches/).\n- [x] This PR **does not** disclose a security vulnerability (see [vulnerability reporting](https://docs.djangoproject.com/en/stable/internals/security/)).\n- [x] This PR targets the `main` branch. \n- [x] The commit message is written in past tense, mentions the ticket number, and ends with a period.\n- [x] I have checked the \"Has patch\" ticket flag in the Trac system.\n- [x] I have added or updated relevant tests.\n- [x] I have added or updated relevant docs, including release notes if applicable.\n- [x] I have attached screenshots in both light and dark modes for any UI changes.", "author": "user_d96dcc7f8ae4", "created_at": "2026-01-12T18:45:23+00:00", "merged_at": "2026-01-26T15:25:47+00:00", "base_branch": "main", "head_branch": "ticket_36850", "additions": 27, "deletions": 3, "changed_files": 4, "files": [ { "filename": "django/contrib/admin/static/admin/css/changelists.css", "status": "modified", "additions": 1, "deletions": 1, "changes": 2, "patch": "@@ -2,7 +2,6 @@\n \n #changelist .changelist-form-container {\n display: flex;\n- flex-wrap: wrap;\n align-items: flex-start;\n width: 100%;\n }\n@@ -16,6 +15,7 @@\n }\n \n #changelist .changelist-form-container:has(#changelist-filter) > div {\n+ min-width: 0;\n max-width: calc(100% - 270px);\n }" }, { "filename": "docs/releases/6.0.2.txt", "status": "modified", "additions": 4, "deletions": 1, "changes": 5, "patch": "@@ -9,4 +9,7 @@ Django 6.0.2 fixes several bugs in 6.0.1.\n Bugfixes\n ========\n \n-* ...\n+* Fixed a visual regression in Django 6.0 that caused the admin filter sidebar\n+ to wrap below the changelist when filter elements contained long text\n+ (:ticket:`36850`).\n+" }, { "filename": "tests/admin_views/models.py", "status": "modified", "additions": 7, "deletions": 1, "changes": 8, "patch": "@@ -266,7 +266,13 @@ class Person(models.Model):\n (2, \"Female\"),\n )\n name = models.CharField(max_length=100)\n- gender = models.IntegerField(choices=GENDER_CHOICES)\n+ gender = models.IntegerField(\n+ choices=GENDER_CHOICES,\n+ verbose_name=(\n+ \"very very very very very very very very very \"\n+ \"loooooooooooooooooooooooooooooooooooooooooong name\"\n+ ),\n+ )\n age = models.IntegerField(default=21)\n alive = models.BooleanField(default=True)" }, { "filename": "tests/admin_views/tests.py", "status": "modified", "additions": 15, "deletions": 0, "changes": 15, "patch": "@@ -7205,6 +7205,21 @@ def test_pagination_layout(self):\n self.assertTrue(show_all.is_displayed())\n self.take_screenshot(\"pagination\")\n \n+ [USER_REDACTED]_cases([\"desktop_size\", \"mobile_size\", \"rtl\", \"dark\", \"high_contrast\"])\n+ def test_changelist_filter_sidebar_with_long_verbose_fields(self):\n+ from selenium.webdriver.common.by [NAME_REDACTED]\n+\n+ self.admin_login(\n+ username=\"super\", password=\"secret\", login_url=reverse(\"admin:index\")\n+ )\n+ Person.objects.create(name=\"John\", gender=1)\n+ self.selenium.get(\n+ self.live_server_url + reverse(\"admin:admin_views_person_changelist\")\n+ )\n+ changelist_filter = self.selenium.find_element(By.ID, \"changelist-filter\")\n+ self.assertTrue(changelist_filter.is_displayed())\n+ self.take_screenshot(\"filter_sidebar\")\n+\n \n [USER_REDACTED]_settings(ROOT_URLCONF=\"admin_views.urls\")\n class ReadonlyTest(AdminFieldExtractionMixin, TestCase):" } ], "reviews": [ { "id": 3658487038, "user": "user_45c2e5489720", "state": "COMMENTED", "body": "Thank you for working on this [USER_REDACTED] :)\n\nI left a few comments for reference.\nPerhaps we need to include the changes for this part in the release note? (6.0.2)", "submitted_at": "2026-01-14T01:23:52+00:00" }, { "id": 3673352351, "user": "user_45c2e5489720", "state": "APPROVED", "body": "Thank you [USER_REDACTED] ! It looks good to me 🙌\n\n## Firefox\n\n\"Screenshot\n\n## Safari\n\n\"Screenshot\n\n## Edge\n\n\"Screenshot\n\nOne thing I'm wondering about... the current test only has one field in the changelist. Would it be better to test with multiple fields?", "submitted_at": "2026-01-17T01:24:21+00:00" }, { "id": 3678830235, "user": "user_3a67c55598c5", "state": "COMMENTED", "body": "Thanks both ⭐ \n\n[USER_REDACTED] can you update the PR body with the ultimate solution?", "submitted_at": "2026-01-19T16:24:40+00:00" }, { "id": 3679942402, "user": "user_45c2e5489720", "state": "COMMENTED", "body": null, "submitted_at": "2026-01-20T00:42:43+00:00" }, { "id": 3679960545, "user": "user_45c2e5489720", "state": "COMMENTED", "body": null, "submitted_at": "2026-01-20T00:58:42+00:00" }, { "id": 3680139186, "user": "user_3a67c55598c5", "state": "COMMENTED", "body": null, "submitted_at": "2026-01-20T03:05:06+00:00" }, { "id": 3700423735, "user": "user_45c2e5489720", "state": "COMMENTED", "body": null, "submitted_at": "2026-01-24T02:22:53+00:00" }, { "id": 3706262504, "user": "user_3a67c55598c5", "state": "APPROVED", "body": "Thank you!", "submitted_at": "2026-01-26T14:21:22+00:00" } ], "review_comments": [ { "id": 2688616076, "user": "user_45c2e5489720", "body": "For reference!\n\nI think it would be good if the filter layout works the same as before.\nPreviously, the filter sidebar maintained the same line even when its size increased.\n\n## 6.0\n\n\"Screenshot\n\n## 5.0\n\n\"Screenshot", "path": "django/contrib/admin/static/admin/css/changelists.css", "line": null, "side": "RIGHT", "created_at": "2026-01-14T01:19:38+00:00" }, { "id": 2688618929, "user": "user_45c2e5489720", "body": "```diff --git a/tests/admin_views/models.py b/tests/admin_views/models.py\nindex 4e2d13efa8..edc13fe5ae 100644\n--- a/tests/admin_views/models.py\n+++ b/tests/admin_views/models.py\n@@ -668,7 +668,13 @@ class ReadOnlyPizza(Pizza):\n \n class Album(models.Model):\n owner = models.ForeignKey(User, models.SET_NULL, null=True, blank=True)\n- title = models.CharField(max_length=30)\n+ title = models.CharField(\n+ max_length=30,\n+ verbose_name=(\n+ \"very very very very very very very very very \"\n+ \"loooooooooooooooooooooooooooooooooooooooooong name\"\n+ )\n+ )\n \n \n class Song(models.Model):\ndiff --git a/tests/admin_views/tests.py b/tests/admin_views/tests.py\nindex 8ba3b53c41..96065d0846 100644\n--- a/tests/admin_views/tests.py\n+++ b/tests/admin_views/tests.py\n@@ -7086,18 +7086,19 @@ class SeleniumTests(AdminSeleniumTestCase):\n self.take_screenshot(\"pagination\")\n \n [USER_REDACTED]_cases([\"desktop_size\", \"mobile_size\", \"rtl\", \"dark\", \"high_contrast\"])\n- def test_changelist_filter_sidebar_width(self):\n+ def test_changelist_filter_sidebar_with_long_verbose_name(self):\n from selenium.webdriver.common.by [NAME_REDACTED]_login(\n username=\"super\", password=\"secret\", login_url=reverse(\"admin:index\")\n )\n+ Album.objects.create(title=\"oasis\")\n self.selenium.get(\n- self.live_server_url + reverse(\"admin:admin_views_person_changelist\")\n+ self.live_server_url + reverse(\"admin:admin_views_album_changelist\")\n )\n changelist_filter = self.selenium.find_element(By.ID, \"changelist-filter\")\n+ self.assertTrue(changelist_filter.is_displayed())\n # Verify the filter width is constrained to max-width (240px).\n- self.assertLessEqual(changelist_filter.rect[\"width\"], 240)\n self.take_screenshot(\"filter_sidebar\")\n```\n\nI think we can actually reproduce the issue when it has a `verbose_name` containing long words like this.\n\n\"image\"", "path": "tests/admin_views/tests.py", "line": null, "side": "RIGHT", "created_at": "2026-01-14T01:21:32+00:00" }, { "id": 2705395209, "user": "user_3a67c55598c5", "body": "```suggestion\n* Fixed a visual regression in Django 6.0 that caused the admin filter sidebar\n to wrap below ...\n```", "path": "docs/releases/6.0.2.txt", "line": null, "side": "RIGHT", "created_at": "2026-01-19T16:21:39+00:00" }, { "id": 2705396990, "user": "user_3a67c55598c5", "body": "The added test performs the same when I remove this. [USER_REDACTED] can you share why you suggested including it?", "path": "django/contrib/admin/static/admin/css/changelists.css", "line": 18, "side": "RIGHT", "created_at": "2026-01-19T16:22:17+00:00" }, { "id": 2706395787, "user": "user_45c2e5489720", "body": "If the `min-width` property is not set, it becomes like this:\n\n\"Screenshot\n\nThe conclusion is that it's to override `min-width: auto` inside flex.\nIn flex, `min-width: auto` guarantees the content size as the minimum limit, so if the content doesn't shrink, it pushes the adjacent elements.\nTherefore, I overrode it with `min-width: 0` to prevent it from pushing adjacent elements.\nPerhaps it wasn't caught in the screenshot test because it captures at a specific screen size? (I'll check on this.)", "path": "django/contrib/admin/static/admin/css/changelists.css", "line": 18, "side": "RIGHT", "created_at": "2026-01-20T00:42:43+00:00" }, { "id": 2706415192, "user": "user_45c2e5489720", "body": "After checking, it seems there was no difference because there wasn't enough content.\nWe'll need to add more fields!\n\nWould it be better to change the test model to `Person` here?\nIf we use `Person`, it seems like We wouldn't need to touch any `ModelAdmin` configuration.", "path": "django/contrib/admin/static/admin/css/changelists.css", "line": 18, "side": "RIGHT", "created_at": "2026-01-20T00:58:42+00:00" }, { "id": 2706595154, "user": "user_3a67c55598c5", "body": "That sounds like a good idea 👍🏻", "path": "django/contrib/admin/static/admin/css/changelists.css", "line": 18, "side": "RIGHT", "created_at": "2026-01-20T03:05:06+00:00" }, { "id": 2723442809, "user": "user_45c2e5489720", "body": "I seem to be failing to reproduce the issue 🥲\nThe filter sidebar size should increase.", "path": "tests/admin_views/tests.py", "line": null, "side": "RIGHT", "created_at": "2026-01-24T02:22:53+00:00" } ], "meta": { "languages": [ "css", "py", "txt" ], "touches_tests": true, "review_state_summary": { "COMMENTED": 6, "APPROVED": 2 }, "meaningful_comment_count": 8, "has_approval": true, "has_changes_requested": false, "total_review_comments": 8 } } { "_id": "865c7e0a27ddef8c", "_schema_version": "1.0", "_cleaned_at": "2026-02-12T07:46:51.546480+00:00", "repo": "django/django", "repo_url": "https://github.com/django/django", "license_name": "BSD 3-Clause \"New\" or \"Revised\" License", "license_spdx": "BSD-3-Clause", "pr_number": 20524, "title": "Fixed #36801 -- Avoided unnecessary calculation in construct_change_message().", "body": "#### Trac ticket number\n\nticket-36801\n\n#### Branch description\n\n`changed_field_labels` is only needed if there are changes to log, so move its calculation, including the somewhat costly `translation_override()`, inside the conditional that checks for changes. Also avoid reading `form.changed_data` when it’s already bound to `changed_data`.\n\n#### AI [NAME_REDACTED] (REQUIRED)\n- [x] **No AI tools were used** in preparing this PR.\n- [ ] **If AI tools were used**, I have disclosed which ones, and fully reviewed and verified their output.\n\n#### Checklist\n- [x] This PR follows the [contribution guidelines](https://docs.djangoproject.com/en/stable/internals/contributing/writing-code/submitting-patches/).\n- [x] This PR **does not** disclose a security vulnerability (see [vulnerability reporting](https://docs.djangoproject.com/en/stable/internals/security/)).\n- [x] This PR targets the `main` branch. \n- [x] The commit message is written in past tense, mentions the ticket number, and ends with a period.\n- [x] I have checked the \"Has patch\" ticket flag in the Trac system.\n- [x] I have added or updated relevant tests.\n- [x] I have added or updated relevant docs, including release notes if applicable.\n- [x] I have attached screenshots in both light and dark modes for any UI changes.", "author": "user_8fc305198eb3", "created_at": "2026-01-10T20:45:18+00:00", "merged_at": "2026-01-16T14:17:57+00:00", "base_branch": "main", "head_branch": "ticket_36801", "additions": 11, "deletions": 11, "changed_files": 1, "files": [ { "filename": "django/contrib/admin/utils.py", "status": "modified", "additions": 11, "deletions": 11, "changes": 22, "patch": "@@ -552,21 +552,21 @@ def construct_change_message(form, formsets, add):\n Translations are deactivated so that strings are stored untranslated.\n Translation happens later on LogEntry access.\n \"\"\"\n+ change_message = []\n+ if add:\n+ change_message.append({\"added\": {}})\n # Evaluating `form.changed_data` prior to disabling translations is\n # required to avoid fields affected by [NAME_REDACTED]\n # incorrectly, e.g. where date formats differ such as MM/DD/YYYY vs\n # DD/MM/YYYY.\n- changed_data = form.changed_data\n- with translation_override(None):\n- # Deactivate translations while fetching verbose_name for form\n- # field labels and using `field_name`, if verbose_name is not provided.\n- # Translations will happen later on LogEntry access.\n- changed_field_labels = _get_changed_field_labels_from_form(form, changed_data)\n-\n- change_message = []\n- if add:\n- change_message.append({\"added\": {}})\n- elif form.changed_data:\n+ elif changed_data := form.changed_data:\n+ with translation_override(None):\n+ # Deactivate translations while fetching verbose_name for form\n+ # field labels and using `field_name`, if verbose_name is not\n+ # provided. Translations will happen later on LogEntry access.\n+ changed_field_labels = _get_changed_field_labels_from_form(\n+ form, changed_data\n+ )\n change_message.append({\"changed\": {\"fields\": changed_field_labels}})\n if formsets:\n with translation_override(None):" } ], "reviews": [ { "id": 3652219291, "user": "user_3a67c55598c5", "state": "APPROVED", "body": "👍", "submitted_at": "2026-01-12T18:49:21+00:00" }, { "id": 3661912459, "user": "user_34c3f4acb8a8", "state": "COMMENTED", "body": null, "submitted_at": "2026-01-14T17:31:03+00:00" }, { "id": 3668225440, "user": "user_8fc305198eb3", "state": "COMMENTED", "body": null, "submitted_at": "2026-01-16T00:31:53+00:00" } ], "review_comments": [ { "id": 2691385394, "user": "user_34c3f4acb8a8", "body": "Thought: Given you mention `translation_override` is expensive, is there any way to combine these calls? It'd be nice to avoid needing to call it twice in the same call to `construct_change_message`.\n\nIt might end up being far more complex than is useful - just a thought.", "path": "django/contrib/admin/utils.py", "line": 572, "side": "RIGHT", "created_at": "2026-01-14T17:31:03+00:00" }, { "id": 2696443224, "user": "user_8fc305198eb3", "body": "I can't see a way of doing that which isn't more complex than I think it's worth…", "path": "django/contrib/admin/utils.py", "line": 572, "side": "RIGHT", "created_at": "2026-01-16T00:31:53+00:00" } ], "meta": { "languages": [ "py" ], "touches_tests": false, "review_state_summary": { "APPROVED": 1, "COMMENTED": 2 }, "meaningful_comment_count": 2, "has_approval": true, "has_changes_requested": false, "total_review_comments": 2 } } { "_id": "e3b7725ad3786d64", "_schema_version": "1.0", "_cleaned_at": "2026-02-12T07:46:51.546480+00:00", "repo": "django/django", "repo_url": "https://github.com/django/django", "license_name": "BSD 3-Clause \"New\" or \"Revised\" License", "license_spdx": "BSD-3-Clause", "pr_number": 20519, "title": "Fixed #35402 -- Fixed crash in DatabaseFeatures.django_test_skips when running a subset of tests.", "body": "#### Trac ticket number\nticket-35402\n\n#### Branch description\nContinued from #18203.\n\nBecause the prior implementation of this skip machinery sent module names to `import_string()`, it was relying on a fragile behavior that depended on, in the case of submodules, the parent modules having already been imported, which isn't guaranteed.\n\nWe might want to take up Tim's suggestion in the ticket of deprecating providing module names to `import_string()` at some point.\n\n#### AI [NAME_REDACTED] (REQUIRED)\n\n- [x] **No AI tools were used** in preparing this PR.\n- [ ] **If AI tools were used**, I have disclosed which ones, and fully reviewed and verified their output.\n\n#### Checklist\n- [x] This PR follows the [contribution guidelines](https://docs.djangoproject.com/en/stable/internals/contributing/writing-code/submitting-patches/).\n- [x] This PR **does not** disclose a security vulnerability (see [vulnerability reporting](https://docs.djangoproject.com/en/stable/internals/security/)).\n- [x] This PR targets the `main` branch. \n- [x] The commit message is written in past tense, mentions the ticket number, and ends with a period.\n- [x] I have checked the \"Has patch\" ticket flag in the Trac system.\n- [x] I have added or updated relevant tests.\n- [x] I have added or updated relevant docs, including release notes if applicable.\n- [x] I have attached screenshots in both light and dark modes for any UI changes.", "author": "user_3a67c55598c5", "created_at": "2026-01-09T21:54:15+00:00", "merged_at": "2026-01-14T13:25:37+00:00", "base_branch": "main", "head_branch": "issue-35402", "additions": 35, "deletions": 18, "changed_files": 2, "files": [ { "filename": "django/db/backends/base/creation.py", "status": "modified", "additions": 30, "deletions": 18, "changes": 48, "patch": "@@ -358,27 +358,39 @@ def mark_expected_failures_and_skips(self):\n Mark tests in Django's test suite which are expected failures on this\n database and test which should be skipped on this database.\n \"\"\"\n- # Only load unittest if we're actually testing.\n- from unittest import expectedFailure, skip\n-\n for test_name in self.connection.features.django_test_expected_failures:\n- test_case_name, _, test_method_name = test_name.rpartition(\".\")\n- test_app = test_name.split(\".\")[0]\n- # Importing a test app that isn't installed raises RuntimeError.\n- if test_app in settings.INSTALLED_APPS:\n- test_case = import_string(test_case_name)\n- test_method = getattr(test_case, test_method_name)\n- setattr(test_case, test_method_name, expectedFailure(test_method))\n+ self._mark_test(test_name)\n for reason, tests in self.connection.features.django_test_skips.items():\n for test_name in tests:\n- test_case_name, _, test_method_name = test_name.rpartition(\".\")\n- test_app = test_name.split(\".\")[0]\n- # Importing a test app that isn't installed raises\n- # RuntimeError.\n- if test_app in settings.INSTALLED_APPS:\n- test_case = import_string(test_case_name)\n- test_method = getattr(test_case, test_method_name)\n- setattr(test_case, test_method_name, skip(reason)(test_method))\n+ self._mark_test(test_name, reason)\n+\n+ def _mark_test(self, test_name, skip_reason=None):\n+ # Only load unittest during testing.\n+ from unittest import expectedFailure, skip\n+\n+ module_or_class_name, _, name_to_mark = test_name.rpartition(\".\")\n+ test_app = test_name.split(\".\")[0]\n+ # Importing a test app that isn't installed raises RuntimeError.\n+ if test_app in settings.INSTALLED_APPS:\n+ try:\n+ test_frame = import_string(module_or_class_name)\n+ except ImportError:\n+ # import_string() can raise ImportError if a submodule's parent\n+ # module hasn't already been imported during test discovery.\n+ # This can happen in at least two cases:\n+ # 1. When running a subset of tests in a module, the test\n+ # runner won't import tests in that module's other\n+ # submodules.\n+ # 2. When the parallel test runner spawns workers with an empty\n+ # import cache.\n+ test_to_mark = import_string(test_name)\n+ test_frame = sys.modules.get(test_to_mark.__module__)\n+ else:\n+ test_to_mark = getattr(test_frame, name_to_mark)\n+ if skip_reason:\n+ setattr(test_frame, name_to_mark, skip(skip_reason)(test_to_mark))\n+ else:\n+ setattr(test_frame, name_to_mark, expectedFailure(test_to_mark))\n \n def sql_table_creation_suffix(self):\n \"\"\"" }, { "filename": "tests/backends/base/test_creation.py", "status": "modified", "additions": 5, "deletions": 0, "changes": 5, "patch": "@@ -1,6 +1,7 @@\n import copy\n import datetime\n import os\n+import sys\n from unittest import mock\n \n from django.db import DEFAULT_DB_ALIAS, connection, connections\n@@ -333,6 +334,10 @@ def test_mark_expected_failures_and_skips(self):\n \"backends.base.test_creation.skip_test_function\",\n },\n }\n+ # Emulate the scenario where the parent module for\n+ # backends.base.test_creation has not been imported yet.\n+ popped_module = sys.modules.pop(\"backends.base\")\n+ self.addCleanup(sys.modules.__setitem__, \"backends.base\", popped_module)\n creation.mark_expected_failures_and_skips()\n self.assertIs(\n expected_failure_test_function.__unittest_expecting_failure__," } ], "reviews": [ { "id": 3646016093, "user": "user_657e90e5ae46", "state": "COMMENTED", "body": "Thanks for following up.", "submitted_at": "2026-01-10T00:58:48+00:00" }, { "id": 3646305893, "user": "user_3a67c55598c5", "state": "COMMENTED", "body": null, "submitted_at": "2026-01-10T02:18:40+00:00" }, { "id": 3646317529, "user": "user_3a67c55598c5", "state": "COMMENTED", "body": null, "submitted_at": "2026-01-10T02:23:34+00:00" }, { "id": 3651698442, "user": "user_3a67c55598c5", "state": "COMMENTED", "body": null, "submitted_at": "2026-01-12T16:39:37+00:00" }, { "id": 3652679698, "user": "user_657e90e5ae46", "state": "COMMENTED", "body": null, "submitted_at": "2026-01-12T20:44:09+00:00" }, { "id": 3652921861, "user": "user_3a67c55598c5", "state": "COMMENTED", "body": null, "submitted_at": "2026-01-12T22:03:09+00:00" }, { "id": 3652933036, "user": "user_657e90e5ae46", "state": "COMMENTED", "body": null, "submitted_at": "2026-01-12T22:23:28+00:00" }, { "id": 3653238656, "user": "user_3a67c55598c5", "state": "COMMENTED", "body": null, "submitted_at": "2026-01-13T00:16:14+00:00" }, { "id": 3656810327, "user": "user_3a67c55598c5", "state": "COMMENTED", "body": null, "submitted_at": "2026-01-13T16:45:13+00:00" }, { "id": 3656813034, "user": "user_3a67c55598c5", "state": "COMMENTED", "body": null, "submitted_at": "2026-01-13T16:45:48+00:00" }, { "id": 3657411188, "user": "user_657e90e5ae46", "state": "COMMENTED", "body": null, "submitted_at": "2026-01-13T19:14:18+00:00" }, { "id": 3658255641, "user": "user_657e90e5ae46", "state": "APPROVED", "body": "Sorry for so much bikeshedding. Thanks for working on this.", "submitted_at": "2026-01-13T23:07:46+00:00" }, { "id": 3658365843, "user": "user_3a67c55598c5", "state": "COMMENTED", "body": null, "submitted_at": "2026-01-14T00:06:46+00:00" }, { "id": 3658367952, "user": "user_3a67c55598c5", "state": "COMMENTED", "body": null, "submitted_at": "2026-01-14T00:08:04+00:00" }, { "id": 3658380475, "user": "user_3a67c55598c5", "state": "COMMENTED", "body": null, "submitted_at": "2026-01-14T00:16:02+00:00" }, { "id": 3658405831, "user": "user_657e90e5ae46", "state": "COMMENTED", "body": null, "submitted_at": "2026-01-14T00:29:35+00:00" } ], "review_comments": [ { "id": 2677999156, "user": "user_657e90e5ae46", "body": "There is no memory leak when using an inline method in this case?", "path": "django/db/backends/base/creation.py", "line": null, "side": "RIGHT", "created_at": "2026-01-10T00:20:18+00:00" }, { "id": 2678002877, "user": "user_657e90e5ae46", "body": "I prefer not to add blank lines under the guideline that comments are better to separate any blocks that would otherwise seem to need blank lines.", "path": "tests/backends/base/test_creation.py", "line": null, "side": "RIGHT", "created_at": "2026-01-10T00:24:21+00:00" }, { "id": 2678003330, "user": "user_657e90e5ae46", "body": "As all bugs are ;-) (I think this sentence isn't needed.)", "path": "tests/backends/base/test_creation.py", "line": null, "side": "RIGHT", "created_at": "2026-01-10T00:24:53+00:00" }, { "id": 2678004314, "user": "user_657e90e5ae46", "body": "I think it's more important to say something high-level like \"When running a subset of tests in a module, tests in that module's other submodules won't be imported by [NAME_REDACTED] must be manually imported to avoid a crash. The ImportError could be ignored but the second import catches nonexistent tests.\" I leave it to you about whether or not to include the implementation details you've described but it seems like it may be uneeded archaic details (about the implementation of `import_string()`, for example).", "path": "django/db/backends/base/creation.py", "line": null, "side": "RIGHT", "created_at": "2026-01-10T00:26:03+00:00" }, { "id": 2678009075, "user": "user_657e90e5ae46", "body": "the comma seems uneeded", "path": "django/db/backends/base/creation.py", "line": null, "side": "RIGHT", "created_at": "2026-01-10T00:31:00+00:00" }, { "id": 2678010177, "user": "user_657e90e5ae46", "body": "The comment wrapping looks too short to me (less than 79 characters.)", "path": "django/db/backends/base/creation.py", "line": null, "side": "RIGHT", "created_at": "2026-01-10T00:32:11+00:00" }, { "id": 2678027671, "user": "user_657e90e5ae46", "body": "I think this is actually unnecessary. If the import fails, that means the test isn't going to run, so decorating it isn't needed. In other words:\n```diff\ndiff --git a/django/db/backends/base/creation.py b/django/db/backends/base/creation.py\nindex 3ba9365a2c..34eae215a4 100644\n--- a/django/db/backends/base/creation.py\n+++ b/django/db/backends/base/creation.py\n@@ -364,8 +364,8 @@ class BaseDatabaseCreation:\n # the rightmost term was a submodule, and the remainder\n # is a module that hasn't been imported yet.\n # Import the test_method by [NAME_REDACTED]_name.\n- test_method = import_string(test_name)\n- test_case = sys.modules.get(test_method.__module__)\n+ import_string(test_name)\n+ return (None, None)\n else:\n test_method = getattr(test_case, class_or_method)\n return test_case, test_method\n@@ -378,7 +378,8 @@ class BaseDatabaseCreation:\n test_case, test_method = get_test(\n module_or_class_name, class_or_method_name, test_name\n )\n- setattr(test_case, class_or_method_name, expectedFailure(test_method))\n+ if test_case:\n+ setattr(test_case, class_or_method_name, expectedFailure(test_method))\n for reason, tests in self.connection.features.django_test_skips.items():\n for test_name in tests:\n module_or_class_name, _, class_or_method_name = test_name.rpartition(\n@@ -391,7 +392,8 @@ class BaseDatabaseCreation:\n test_case, test_method = get_test(\n module_or_class_name, class_or_method_name, test_name\n )\n- setattr(test_case, class_or_method_name, skip(reason)(test_method))\n+ if test_case:\n+ setattr(test_case, class_or_method_name, skip(reason)(test_method))\n \n def sql_table_creation_suffix(self):\n```\n\nAs I said in my other comment, the only reason the second import is useful is to catch typos in test names.", "path": "django/db/backends/base/creation.py", "line": null, "side": "RIGHT", "created_at": "2026-01-10T00:51:48+00:00" }, { "id": 2678202475, "user": "user_3a67c55598c5", "body": "Oh good point. Let me look a little closer next week.", "path": "django/db/backends/base/creation.py", "line": null, "side": "RIGHT", "created_at": "2026-01-10T02:18:40+00:00" }, { "id": 2678210208, "user": "user_3a67c55598c5", "body": "This gets called only once per test worker, so I don't think it's a meaningful number of objects. I just didn't want to clutter the module scope. Maybe I'll end up needing to hoist it up to the module to target it in a test.\n\nIt was a little early to request your review, but I'm glad I did as I need to look into your comment about unnecessary decoration.", "path": "django/db/backends/base/creation.py", "line": null, "side": "RIGHT", "created_at": "2026-01-10T02:23:34+00:00" }, { "id": 2683053768, "user": "user_3a67c55598c5", "body": "I don't think we can assume that the test isn't going to run. `ImportError` can be emitted because it's problematic to use `import_string` on modules, and we're considering deprecating that use to remove the footgun.\n\nFor instance, if I apply the diff from the ticket, and add your proposal:\n```diff\ndiff --git a/django/db/backends/base/creation.py b/django/db/backends/base/creation.py\nindex e027c4ef09..f0a55055c9 100644\n--- a/django/db/backends/base/creation.py\n+++ b/django/db/backends/base/creation.py\n@@ -370,6 +370,7 @@ class BaseDatabaseCreation:\n # the rightmost term was a submodule, and the remainder\n # is a module that hasn't been imported yet.\n # Import the test_method by [NAME_REDACTED]_name.\n+ return None, None\n test_method = import_string(test_name)\n test_case = sys.modules.get(test_method.__module__)\n else:\n@@ -384,7 +385,8 @@ class BaseDatabaseCreation:\n test_case, test_method = get_test(\n module_or_class_name, class_or_method_name, test_name\n )\n- setattr(test_case, class_or_method_name, expectedFailure(test_method))\n+ if test_case:\n+ setattr(test_case, class_or_method_name, expectedFailure(test_method))\n for reason, tests in self.connection.features.django_test_skips.items():\n for test_name in tests:\n module_or_class_name, _, class_or_method_name = test_name.rpartition(\n@@ -397,7 +399,8 @@ class BaseDatabaseCreation:\n test_case, test_method = get_test(\n module_or_class_name, class_or_method_name, test_name\n )\n- setattr(test_case, class_or_method_name, skip(reason)(test_method))\n+ if test_case:\n+ setattr(test_case, class_or_method_name, skip(reason)(test_method))\n \n def sql_table_creation_suffix(self):\n \"\"\"\ndiff --git a/django/db/backends/sqlite3/features.py b/django/db/backends/sqlite3/features.py\nindex ed24341b5e..c20747a27c 100644\n--- a/django/db/backends/sqlite3/features.py\n+++ b/django/db/backends/sqlite3/features.py\n@@ -70,8 +70,7 @@ class DatabaseFeatures(BaseDatabaseFeatures):\n def django_test_skips(self):\n skips = {\n \"SQLite stores values rounded to 15 significant digits.\": {\n- \"model_fields.test_decimalfield.DecimalFieldTests.\"\n- \"test_fetch_from_db_without_float_rounding\",\n+ \"model_fields.test_decimalfield.DecimalFieldTests\",\n },\n \"SQLite naively remakes the table on field alteration.\": {\n \"schema.tests.SchemaTests.test_unique_no_unnecessary_fk_drops\",\n```\n\nAnd invoke the tests like this with tests specified individually:\n```py\n./runtests.py model_fields.test_autofield model_fields.test_decimalfield --parallel=2\n```\n\nThen the test is not skipped:\n```py\nAssertionError: Decimal('0.100000000000000000000000000000') != Decimal('0.100000000000000000000000000005')\n\n----------------------------------------------------------------------\nRan 78 tests in 0.869s\n\nFAILED (failures=1)\n```", "path": "django/db/backends/base/creation.py", "line": null, "side": "RIGHT", "created_at": "2026-01-12T16:39:37+00:00" }, { "id": 2683850272, "user": "user_657e90e5ae46", "body": "You wrote \"import_string() sometimes raises ImportError given a module.\" However, I think the comment should give an example of what \"sometimes\" means.", "path": "django/db/backends/base/creation.py", "line": null, "side": "RIGHT", "created_at": "2026-01-12T20:44:09+00:00" }, { "id": 2684060029, "user": "user_3a67c55598c5", "body": "Ah right. Let me know if [eff69c8](https://github.com/[USER_REDACTED]ngo/django/pull/20519/commits/eff69c8fdf351ef4612cbc1782e01be274176d25) still doesn't strike the right balance.", "path": "django/db/backends/base/creation.py", "line": null, "side": "RIGHT", "created_at": "2026-01-12T22:03:09+00:00" }, { "id": 2684070759, "user": "user_657e90e5ae46", "body": "\"do not expect\" seems like a verbiage change from the previous sentence. Here's my suggestion:\n\nimport_string() can raise ImportError if a submodule's parent module hasn't already been imported during test discovery. This can happen in at least two cases:\n1. When running a subset of tests in a module, tests in that module's other submodules won't be imported by [NAME_REDACTED]\n2. When the parallel test runner spawns workers with an empty import cache.\n\nPlease correct any details that I got wrong.", "path": "django/db/backends/base/creation.py", "line": null, "side": "RIGHT", "created_at": "2026-01-12T22:07:39+00:00" }, { "id": 2684073892, "user": "user_657e90e5ae46", "body": "I didn't know about the problem for the parallel test runner, and I think it's important to also describe the case I mentioned where it's not involved.", "path": "django/db/backends/base/creation.py", "line": null, "side": "RIGHT", "created_at": "2026-01-12T22:08:53+00:00" }, { "id": 2684105502, "user": "user_657e90e5ae46", "body": "I hate this formatting and how other lines have to be multi-lined. I don't normally advocate for abbreviations, but I'm a bit tempted to abbreviate \"class\" -> \"cls\" if it avoids that.", "path": "django/db/backends/base/creation.py", "line": null, "side": "RIGHT", "created_at": "2026-01-12T22:21:54+00:00" }, { "id": 2684338072, "user": "user_3a67c55598c5", "body": "I could also parenthesize the left-hand side. Fully agree about the lonely `\".\"`", "path": "django/db/backends/base/creation.py", "line": null, "side": "RIGHT", "created_at": "2026-01-13T00:16:14+00:00" }, { "id": 2687229683, "user": "user_3a67c55598c5", "body": "I like this. I applied your suggestion and removed the passive voice to fit on one fewer line.", "path": "django/db/backends/base/creation.py", "line": null, "side": "RIGHT", "created_at": "2026-01-13T16:45:13+00:00" }, { "id": 2687231817, "user": "user_3a67c55598c5", "body": "Took the opportunity to factor out helper methods to address this and also remove nested functions at the same time 👍", "path": "django/db/backends/base/creation.py", "line": null, "side": "RIGHT", "created_at": "2026-01-13T16:45:48+00:00" }, { "id": 2687727509, "user": "user_657e90e5ae46", "body": "skip -> mark (since \"mark\" could be skip or expected failure)\nreason -> skip_reason", "path": "django/db/backends/base/creation.py", "line": null, "side": "RIGHT", "created_at": "2026-01-13T19:08:52+00:00" }, { "id": 2687741612, "user": "user_657e90e5ae46", "body": "test_to_mark?", "path": "django/db/backends/base/creation.py", "line": null, "side": "RIGHT", "created_at": "2026-01-13T19:11:56+00:00" }, { "id": 2687750804, "user": "user_657e90e5ae46", "body": "Perhaps it's better to follow the pattern in the rest of this file (at least with destroy_test_db/_destroy_test_db) and put the helper methods after the method that calls them. Otherwise, it seems to give more prominence to the helpers.", "path": "django/db/backends/base/creation.py", "line": null, "side": "RIGHT", "created_at": "2026-01-13T19:13:42+00:00" }, { "id": 2688397807, "user": "user_657e90e5ae46", "body": "We could clean this up to follow comment guidelines (no \"we\"): \"if we're actually\" -> \"during\"", "path": "django/db/backends/base/creation.py", "line": null, "side": "RIGHT", "created_at": "2026-01-13T23:03:09+00:00" }, { "id": 2688401895, "user": "user_657e90e5ae46", "body": "Does it still make sense to make this a method (vs. inline the logic) even though it's only called in one place?", "path": "django/db/backends/base/creation.py", "line": null, "side": "RIGHT", "created_at": "2026-01-13T23:05:22+00:00" }, { "id": 2688503727, "user": "user_3a67c55598c5", "body": "Ah, good point! Didn't notice that opportunity after the latest refactor 👍", "path": "django/db/backends/base/creation.py", "line": null, "side": "RIGHT", "created_at": "2026-01-14T00:06:46+00:00" }, { "id": 2688505614, "user": "user_3a67c55598c5", "body": "Yeah, I undid some edits that were no longer opportunistic once lines started moving around again, but now this is opportunistic 👍", "path": "django/db/backends/base/creation.py", "line": null, "side": "RIGHT", "created_at": "2026-01-14T00:08:03+00:00" }, { "id": 2688517458, "user": "user_3a67c55598c5", "body": "Now that we lost the other helper's docstring suggesting what a \"frame\" is, I'm hoping this is sort of self-explanatory if in the 1-helper version you see it's the thing having `setattr()` run on it. (?)", "path": "django/db/backends/base/creation.py", "line": 376, "side": "RIGHT", "created_at": "2026-01-14T00:16:02+00:00" }, { "id": 2688540517, "user": "user_657e90e5ae46", "body": "Looks okay to me.", "path": "django/db/backends/base/creation.py", "line": 376, "side": "RIGHT", "created_at": "2026-01-14T00:29:35+00:00" } ], "meta": { "languages": [ "py" ], "touches_tests": true, "review_state_summary": { "COMMENTED": 15, "APPROVED": 1 }, "meaningful_comment_count": 27, "has_approval": true, "has_changes_requested": false, "total_review_comments": 27 } } { "_id": "2eb5ec539fba0923", "_schema_version": "1.0", "_cleaned_at": "2026-02-12T07:46:51.546480+00:00", "repo": "django/django", "repo_url": "https://github.com/django/django", "license_name": "BSD 3-Clause \"New\" or \"Revised\" License", "license_spdx": "BSD-3-Clause", "pr_number": 20510, "title": "Fixed #36852 -- Ignored index_type case in ExclusionConstraint.__eq__().", "body": "#### Trac ticket number\n\n\n[ticket-36852](https://code.djangoproject.com/ticket/36852)\n\n#### Branch description\n\nIgnore case of index_type in `ExclusionConstraint` in equality check.\n\n#### Checklist\n- [x] This PR targets the `main` branch. \n- [x] The commit message is written in past tense, mentions the ticket number, and ends with a period.\n- [x] I have checked the \"Has patch\" ticket flag in the Trac system.\n- [x] I have added or updated relevant tests.\n- [x] I have added or updated relevant docs, including release notes if applicable.\n- [x] I have attached screenshots in both light and dark modes for any UI changes.", "author": "user_d2d82edb4e7b", "created_at": "2026-01-08T08:08:17+00:00", "merged_at": "2026-01-08T16:33:53+00:00", "base_branch": "main", "head_branch": "postgres-exclusion-constraint-eq", "additions": 21, "deletions": 1, "changed_files": 2, "files": [ { "filename": "django/contrib/postgres/constraints.py", "status": "modified", "additions": 1, "deletions": 1, "changes": 2, "patch": "@@ -148,7 +148,7 @@ def __eq__(self, other):\n if isinstance(other, self.__class__):\n return (\n self.name == other.name\n- and self.index_type == other.index_type\n+ and self.index_type.lower() == other.index_type.lower()\n and self.expressions == other.expressions\n and self.condition == other.condition\n and self.deferrable == other.deferrable" }, { "filename": "tests/postgres_tests/test_constraints.py", "status": "modified", "additions": 20, "deletions": 0, "changes": 20, "patch": "@@ -535,6 +535,24 @@ def test_eq(self):\n ],\n include=[\"cancelled\"],\n )\n+ constraint_8 = ExclusionConstraint(\n+ index_type=\"gist\",\n+ name=\"exclude_overlapping\",\n+ expressions=[\n+ (\"datespan\", RangeOperators.OVERLAPS),\n+ (\"room\", RangeOperators.EQUAL),\n+ ],\n+ include=[\"cancelled\"],\n+ )\n+ constraint_9 = ExclusionConstraint(\n+ index_type=\"GIST\",\n+ name=\"exclude_overlapping\",\n+ expressions=[\n+ (\"datespan\", RangeOperators.OVERLAPS),\n+ (\"room\", RangeOperators.EQUAL),\n+ ],\n+ include=[\"cancelled\"],\n+ )\n constraint_10 = ExclusionConstraint(\n name=\"exclude_overlapping\",\n expressions=[\n@@ -572,6 +590,8 @@ def test_eq(self):\n self.assertNotEqual(constraint_2, constraint_3)\n self.assertNotEqual(constraint_2, constraint_4)\n self.assertNotEqual(constraint_2, constraint_7)\n+ self.assertEqual(constraint_7, constraint_8)\n+ self.assertEqual(constraint_7, constraint_9)\n self.assertNotEqual(constraint_4, constraint_5)\n self.assertNotEqual(constraint_5, constraint_6)\n self.assertNotEqual(constraint_1, object())" } ], "reviews": [ { "id": 3638801922, "user": "user_606ba1f2b93c", "state": "COMMENTED", "body": null, "submitted_at": "2026-01-08T10:36:30+00:00" }, { "id": 3639044214, "user": "user_d2d82edb4e7b", "state": "COMMENTED", "body": null, "submitted_at": "2026-01-08T11:47:36+00:00" }, { "id": 3639064095, "user": "user_606ba1f2b93c", "state": "APPROVED", "body": "Commit message will need editing but otherwise LGTM. Thanks 🏆", "submitted_at": "2026-01-08T11:53:19+00:00" }, { "id": 3639628384, "user": "user_c332d334e171", "state": "APPROVED", "body": "LGTM", "submitted_at": "2026-01-08T14:15:56+00:00" }, { "id": 3640245678, "user": "user_3a67c55598c5", "state": "APPROVED", "body": "Thanks!", "submitted_at": "2026-01-08T16:32:42+00:00" } ], "review_comments": [ { "id": 2671817073, "user": "user_606ba1f2b93c", "body": "Since this is a bug, we won't need a release note.", "path": "docs/releases/6.1.txt", "line": null, "side": "RIGHT", "created_at": "2026-01-08T10:35:20+00:00" }, { "id": 2672040778, "user": "user_d2d82edb4e7b", "body": "removed", "path": "docs/releases/6.1.txt", "line": null, "side": "RIGHT", "created_at": "2026-01-08T11:47:36+00:00" } ], "meta": { "languages": [ "py" ], "touches_tests": true, "review_state_summary": { "COMMENTED": 2, "APPROVED": 3 }, "meaningful_comment_count": 1, "has_approval": true, "has_changes_requested": false, "total_review_comments": 2 } } { "_id": "0a5418d47adda99c", "_schema_version": "1.0", "_cleaned_at": "2026-02-12T07:46:51.546480+00:00", "repo": "django/django", "repo_url": "https://github.com/django/django", "license_name": "BSD 3-Clause \"New\" or \"Revised\" License", "license_spdx": "BSD-3-Clause", "pr_number": 20507, "title": "Relocated content from docs/topics/external-packages.txt where appropriate.", "body": "Following up a [forum post](https://forum.djangoproject.com/t/possible-merging-of-2-doc-pages/42819/6) and a conversation with the [NAME_REDACTED], it was decided to remove the docs/topics/external-packages.txt to avoid confusion with the Ecosystem page. Relevant content was moved to their related sections, except for `django-contrib-comments` which is not actively maintained.\n\n#### Checklist\n- [X] This PR targets the `main` branch. \n- [X] The commit message is written in past tense, mentions the ticket number, and ends with a period.\n- [X] I have added or updated relevant docs, including release notes if applicable.", "author": "user_00dac951cdbf", "created_at": "2026-01-07T20:10:51+00:00", "merged_at": "2026-01-08T13:50:57+00:00", "base_branch": "main", "head_branch": "external-packages-no-more", "additions": 14, "deletions": 53, "changed_files": 5, "files": [ { "filename": "docs/ref/models/fields.txt", "status": "modified", "additions": 0, "deletions": 10, "changes": 10, "patch": "@@ -10,16 +10,6 @@ Model field reference\n This document contains all the API references of :class:`Field` including the\n `field options`_ and `field types`_ Django offers.\n \n-.. seealso::\n-\n- If the built-in fields don't do the trick, you can try\n- :pypi:`django-localflavor` (`documentation\n- `_), which contains assorted\n- pieces of code that are useful for particular countries and cultures.\n-\n- Also, you can easily :doc:`write your own custom model fields\n- `.\n-\n .. note::\n \n Fields are defined in :mod:`django.db.models.fields`, but for convenience" }, { "filename": "docs/topics/external-packages.txt", "status": "removed", "additions": 0, "deletions": 38, "changes": 38, "patch": "@@ -1,38 +0,0 @@\n-=================\n-External packages\n-=================\n-\n-Django ships with a variety of extra, optional tools that solve common\n-problems (``contrib.*``). For easier maintenance and to trim the size of the\n-codebase, a few of those applications have been moved out to separate projects.\n-\n-Localflavor\n-===========\n-\n-``django-localflavor`` is a collection of utilities for particular countries\n-and cultures.\n-\n-* `GitHub `__\n-* `Documentation `__\n-* :pypi:`PyPI `\n-\n-Comments\n-========\n-\n-``django-contrib-comments`` can be used to attach comments to any model, so you\n-can use it for comments on blog entries, photos, book chapters, or anything\n-else. Most users will be better served with a custom solution, or a hosted\n-product like Disqus.\n-\n-* `GitHub `__\n-* `Documentation `__\n-* :pypi:`PyPI `\n-\n-Formtools\n-=========\n-\n-``django-formtools`` is a collection of assorted utilities to work with forms.\n-\n-* `GitHub `__\n-* `Documentation `__\n-* :pypi:`PyPI `" }, { "filename": "docs/topics/forms/index.txt", "status": "modified", "additions": 6, "deletions": 4, "changes": 10, "patch": "@@ -802,10 +802,8 @@ Useful attributes on ``{{ field }}`` include:\n ``{{ field.value }}``\n The value of the field. e.g ``[EMAIL_REDACTED]``.\n \n-.. seealso::\n-\n- For a complete list of attributes and methods, see\n- :class:`~django.forms.BoundField`.\n+For a complete list of attributes and methods, see the reference guide for\n+:class:`~django.forms.BoundField`.\n \n Looping over hidden and visible fields\n ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n@@ -858,3 +856,7 @@ This covers the basics, but forms can do a whole lot more:\n :doc:`The Forms Reference `\n Covers the full API reference, including form fields, form widgets,\n and form and field validation.\n+\n+ :pypi:`django-formtools`\n+ Provides additional form utilities, such as form previews and wizards\n+ (`documentation `_)." }, { "filename": "docs/topics/i18n/formatting.txt", "status": "modified", "additions": 8, "deletions": 0, "changes": 8, "patch": "@@ -47,6 +47,14 @@ argument::\n product = forms.CharField()\n revenue = forms.DecimalField(max_digits=4, decimal_places=2, localize=True)\n \n+Locale specific helpers\n+-----------------------\n+\n+For country specific form fields, validation, and data formats that are not\n+included in Django itself, consider using the :pypi:`django-localflavor`\n+package, which provides localized form fields and utilities for many countries\n+and regions (`documentation `_).\n+\n .. _topic-l10n-templates:\n \n Controlling localization in templates" }, { "filename": "docs/topics/index.txt", "status": "modified", "additions": 0, "deletions": 1, "changes": 1, "patch": "@@ -31,6 +31,5 @@ Introductions to all the key parts of Django you'll need to know:\n settings\n signals\n checks\n- external-packages\n async\n tasks" } ], "reviews": [ { "id": 3636632884, "user": "user_00dac951cdbf", "state": "COMMENTED", "body": null, "submitted_at": "2026-01-07T20:12:00+00:00" }, { "id": 3636633996, "user": "user_00dac951cdbf", "state": "COMMENTED", "body": null, "submitted_at": "2026-01-07T20:12:24+00:00" }, { "id": 3636635520, "user": "user_00dac951cdbf", "state": "COMMENTED", "body": null, "submitted_at": "2026-01-07T20:12:51+00:00" }, { "id": 3636678488, "user": "user_6b79e26637e6", "state": "COMMENTED", "body": "Thanks for getting this done quickly. I have a handful of small suggestions. I'm not strongly tied to them though.", "submitted_at": "2026-01-07T20:34:20+00:00" }, { "id": 3639123107, "user": "user_00dac951cdbf", "state": "COMMENTED", "body": null, "submitted_at": "2026-01-08T12:11:55+00:00" }, { "id": 3639143740, "user": "user_00dac951cdbf", "state": "COMMENTED", "body": null, "submitted_at": "2026-01-08T12:18:22+00:00" }, { "id": 3639158505, "user": "user_6b79e26637e6", "state": "APPROVED", "body": "Good stuff! Thank you", "submitted_at": "2026-01-08T12:22:55+00:00" } ], "review_comments": [ { "id": 2669934896, "user": "user_00dac951cdbf", "body": "This is already mentioned below in this doc in the `Field` section: https://docs.djangoproject.com/en/6.0/ref/models/fields/#field-api-reference", "path": "docs/ref/models/fields.txt", "line": 21, "side": "LEFT", "created_at": "2026-01-07T20:12:01+00:00" }, { "id": 2669935943, "user": "user_00dac951cdbf", "body": "This was moved to the i18n docs.", "path": "docs/ref/models/fields.txt", "line": 18, "side": "LEFT", "created_at": "2026-01-07T20:12:24+00:00" }, { "id": 2669937311, "user": "user_00dac951cdbf", "body": "This is a separated commit to improve the flow of this quite lengthy file.", "path": "docs/topics/forms/index.txt", "line": 806, "side": "RIGHT", "created_at": "2026-01-07T20:12:51+00:00" }, { "id": 2669975399, "user": "user_6b79e26637e6", "body": "```suggestion\n Provides additional form utilities, such as form previews and wizards\n```\n\nThe extra word makes it clearer what `django-formtools` does.", "path": "docs/topics/forms/index.txt", "line": null, "side": "RIGHT", "created_at": "2026-01-07T20:27:50+00:00" }, { "id": 2669978435, "user": "user_6b79e26637e6", "body": "```suggestion\nincluded in Django itself, consider using the :pypi:`django-localflavor`\n```\nI don't think the qualifier \"external\" is as helpful now. I'm not sure what that means compared to third-party package and without the external-packages section, casual readers are less likely to know the difference (if there is one).", "path": "docs/topics/i18n/formatting.txt", "line": null, "side": "RIGHT", "created_at": "2026-01-07T20:28:57+00:00" }, { "id": 2669984426, "user": "user_6b79e26637e6", "body": "```suggestion\n``django-localflavor`` provides localized form fields and utilities for many\ncountries, cultures, and regions.\n```\n\nI don't think we need to justify why it's maintained elsewhere in the documentation. The reader likely doesn't care and if they do, the package's documentation can provide that historical context.", "path": "docs/topics/i18n/formatting.txt", "line": null, "side": "RIGHT", "created_at": "2026-01-07T20:31:03+00:00" }, { "id": 2672112283, "user": "user_00dac951cdbf", "body": "Incorporating!", "path": "docs/topics/forms/index.txt", "line": null, "side": "RIGHT", "created_at": "2026-01-08T12:11:55+00:00" }, { "id": 2672130766, "user": "user_00dac951cdbf", "body": "Agreed, made shorter and cleaner (IMHO).", "path": "docs/topics/i18n/formatting.txt", "line": null, "side": "RIGHT", "created_at": "2026-01-08T12:18:21+00:00" } ], "meta": { "languages": [ "txt" ], "touches_tests": false, "review_state_summary": { "COMMENTED": 6, "APPROVED": 1 }, "meaningful_comment_count": 8, "has_approval": true, "has_changes_requested": false, "total_review_comments": 8 } } { "_id": "0f894cf254e8ed8b", "_schema_version": "1.0", "_cleaned_at": "2026-02-12T07:46:51.546480+00:00", "repo": "django/django", "repo_url": "https://github.com/django/django", "license_name": "BSD 3-Clause \"New\" or \"Revised\" License", "license_spdx": "BSD-3-Clause", "pr_number": 20505, "title": "Fixed #36812 -- Dropped support for MariaDB < 10.11.", "body": "#### Trac ticket number\n\n\nticket-36812\n\n#### Branch description\n Dropped the support for MariaDB 10.6-10.10.\n\n#### Checklist\n- [x] This PR targets the `main` branch. \n- [x] The commit message is written in past tense, mentions the ticket number, and ends with a period.\n- [x] I have checked the \"Has patch\" ticket flag in the Trac system.\n- [x] I have added or updated relevant tests.\n- [x] I have added or updated relevant docs, including release notes if applicable.\n- [x] I have attached screenshots in both light and dark modes for any UI changes.", "author": "user_f5eee7dbaa84", "created_at": "2026-01-07T12:44:53+00:00", "merged_at": "2026-01-25T10:51:03+00:00", "base_branch": "main", "head_branch": "fix36812", "additions": 19, "deletions": 22, "changed_files": 7, "files": [ { "filename": "django/db/backends/mysql/features.py", "status": "modified", "additions": 2, "deletions": 5, "changes": 7, "patch": "@@ -64,7 +64,7 @@ class DatabaseFeatures(BaseDatabaseFeatures):\n [USER_REDACTED]_property\n def minimum_database_version(self):\n if self.connection.mysql_is_mariadb:\n- return (10, 6)\n+ return (10, 11)\n else:\n return (8, 4)\n \n@@ -207,8 +207,6 @@ def can_introspect_json_field(self):\n def supports_index_column_ordering(self):\n if self._mysql_storage_engine != \"InnoDB\":\n return False\n- if self.connection.mysql_is_mariadb:\n- return self.connection.mysql_version >= (10, 8)\n return True\n \n [USER_REDACTED]_property\n@@ -220,8 +218,7 @@ def supports_expression_indexes(self):\n \n [USER_REDACTED]_property\n def has_native_uuid_field(self):\n- is_mariadb = self.connection.mysql_is_mariadb\n- return is_mariadb and self.connection.mysql_version >= (10, 7)\n+ return self.connection.mysql_is_mariadb\n \n [USER_REDACTED]_property\n def allows_group_by_selected_pks(self):" }, { "filename": "docs/ref/databases.txt", "status": "modified", "additions": 1, "deletions": 1, "changes": 2, "patch": "@@ -421,7 +421,7 @@ non-durable `_.\n MariaDB notes\n =============\n \n-Django supports MariaDB 10.6 and higher.\n+Django supports MariaDB 10.11 and higher.\n \n To use MariaDB, use the MySQL backend, which is shared between the two. See the\n :ref:`MySQL notes ` for more details." }, { "filename": "docs/ref/models/fields.txt", "status": "modified", "additions": 5, "deletions": 5, "changes": 10, "patch": "@@ -1649,8 +1649,8 @@ Like all :class:`CharField` subclasses, :class:`URLField` takes the optional\n .. class:: UUIDField(**options)\n \n A field for storing universally unique identifiers. Uses Python's\n-:class:`~python:uuid.UUID` class. When used on PostgreSQL and MariaDB 10.7+,\n-this stores in a ``uuid`` datatype, otherwise in a ``char(32)``.\n+:class:`~python:uuid.UUID` class. When used on PostgreSQL and MariaDB, this\n+stores in a ``uuid`` datatype, otherwise in a ``char(32)``.\n \n Universally unique identifiers are a good alternative to :class:`AutoField` for\n :attr:`~Field.primary_key`. The database will not generate the UUID for you, so\n@@ -1667,13 +1667,13 @@ it is recommended to use :attr:`~Field.default`::\n Note that a callable (with the parentheses omitted) is passed to ``default``,\n not an instance of ``UUID``.\n \n-.. admonition:: Lookups on PostgreSQL and MariaDB 10.7+\n+.. admonition:: Lookups on PostgreSQL and [NAME_REDACTED] :lookup:`iexact`, :lookup:`contains`, :lookup:`icontains`,\n :lookup:`startswith`, :lookup:`istartswith`, :lookup:`endswith`, or\n :lookup:`iendswith` lookups on PostgreSQL don't work for values without\n- hyphens, because PostgreSQL and MariaDB 10.7+ store them in a hyphenated\n- uuid datatype type.\n+ hyphens, because PostgreSQL and MariaDB store them in a hyphenated uuid\n+ datatype type.\n \n .. _relationship-fields:" }, { "filename": "docs/ref/models/indexes.txt", "status": "modified", "additions": 0, "deletions": 5, "changes": 5, "patch": "@@ -81,11 +81,6 @@ field's name.\n For example ``Index(fields=['headline', '-pub_date'])`` would create SQL with\n ``(headline, pub_date DESC)``.\n \n-.. admonition:: MariaDB\n-\n- Index ordering isn't supported on MariaDB < 10.8. In that case, a\n- descending index is created as a normal index.\n-\n ``name``\n --------" }, { "filename": "docs/ref/models/querysets.txt", "status": "modified", "additions": 3, "deletions": 4, "changes": 7, "patch": "@@ -1988,10 +1988,9 @@ them:\n , ...]>\n \n The ``postgresql``, ``oracle``, and ``mysql`` database backends support\n-``select_for_update()``. However, MariaDB only supports the ``nowait``\n-argument, MariaDB 10.6+ also supports the ``skip_locked`` argument, and MySQL\n-supports the ``nowait``, ``skip_locked``, and ``of`` arguments. The ``no_key``\n-argument is only supported on PostgreSQL.\n+``select_for_update()``. However, MariaDB only supports the ``nowait`` and\n+``skip_locked`` arguments, and MySQL supports the ``nowait``, ``skip_locked``,\n+and ``of`` arguments. The ``no_key`` argument is only supported on PostgreSQL.\n \n Passing ``nowait=True``, ``skip_locked=True``, ``no_key=True``, or ``of`` to\n ``select_for_update()`` using database backends that do not support these" }, { "filename": "docs/releases/6.1.txt", "status": "modified", "additions": 6, "deletions": 0, "changes": 6, "patch": "@@ -403,6 +403,12 @@ Dropped support for MySQL < 8.4\n Upstream support for MySQL 8.0 ends in April 2026, and MySQL 8.1-8.3 are\n short-term innovation releases. Django 6.1 supports MySQL 8.4 and higher.\n \n+Dropped support for MariaDB < 10.11\n+-----------------------------------\n+\n+Upstream support for MariaDB 10.6 ends in July 2026, and MariaDB 10.7-10.10 are\n+short-term maintenance releases. Django 6.1 supports MariaDB 10.11 and higher.\n+\n Miscellaneous\n -------------" }, { "filename": "tests/backends/mysql/tests.py", "status": "modified", "additions": 2, "deletions": 2, "changes": 4, "patch": "@@ -106,8 +106,8 @@ class Tests(TestCase):\n [USER_REDACTED].patch.object(connection, \"get_database_version\")\n def test_check_database_version_supported(self, mocked_get_database_version):\n if connection.mysql_is_mariadb:\n- mocked_get_database_version.return_value = (10, 5)\n- msg = \"MariaDB 10.6 or later is required (found 10.5).\"\n+ mocked_get_database_version.return_value = (10, 10)\n+ msg = \"MariaDB 10.11 or later is required (found 10.10).\"\n else:\n mocked_get_database_version.return_value = (8, 0, 31)\n msg = \"MySQL 8.4 or later is required (found 8.0.31).\"" } ], "reviews": [ { "id": 3703380571, "user": "user_5501cd6d3dc8", "state": "COMMENTED", "body": null, "submitted_at": "2026-01-25T07:21:51+00:00" }, { "id": 3703381993, "user": "user_5501cd6d3dc8", "state": "COMMENTED", "body": null, "submitted_at": "2026-01-25T07:25:46+00:00" } ], "review_comments": [ { "id": 2725033573, "user": "user_5501cd6d3dc8", "body": "We shouldn't mention MariaDB twice:\n```suggestion\nand ``skip_locked`` arguments, and MySQL ...\n```", "path": "docs/ref/models/querysets.txt", "line": null, "side": "RIGHT", "created_at": "2026-01-25T07:21:50+00:00" }, { "id": 2725035546, "user": "user_5501cd6d3dc8", "body": "We should mention all dropped releases.", "path": "docs/releases/6.1.txt", "line": null, "side": "RIGHT", "created_at": "2026-01-25T07:25:46+00:00" } ], "meta": { "languages": [ "py", "txt" ], "touches_tests": true, "review_state_summary": { "COMMENTED": 2 }, "meaningful_comment_count": 2, "has_approval": false, "has_changes_requested": false, "total_review_comments": 2 } } { "_id": "3e87fc86db433519", "_schema_version": "1.0", "_cleaned_at": "2026-02-12T07:46:51.546480+00:00", "repo": "django/django", "repo_url": "https://github.com/django/django", "license_name": "BSD 3-Clause \"New\" or \"Revised\" License", "license_spdx": "BSD-3-Clause", "pr_number": 20498, "title": "Fixed #36841 -- Made multipart parser class pluggable on HttpRequest.", "body": "#### Trac ticket number\n\n\nticket-36841\n\n#### Branch description\nProvide a concise overview of the issue or rationale behind the proposed changes.\n\n#### Checklist\n- [x] This PR targets the `main` branch. \n- [x] The commit message is written in past tense, mentions the ticket number, and ends with a period.\n- [x] I have checked the \"Has patch\" ticket flag in the Trac system.\n- [x] I have added or updated relevant tests.\n- [x] I have added or updated relevant docs, including release notes if applicable.\n- [ ] I have attached screenshots in both light and dark modes for any UI changes.", "author": "user_b42982f63633", "created_at": "2026-01-05T19:36:17+00:00", "merged_at": "2026-02-10T22:59:02+00:00", "base_branch": "main", "head_branch": "ticket_36841_", "additions": 114, "deletions": 3, "changed_files": 4, "files": [ { "filename": "django/http/request.py", "status": "modified", "additions": 17, "deletions": 1, "changes": 18, "patch": "@@ -56,6 +56,7 @@ class HttpRequest:\n # The encoding used in GET/POST dicts. None means use default setting.\n _encoding = None\n _upload_handlers = []\n+ _multipart_parser_class = MultiPartParser\n \n def __init__(self):\n # WARNING: The `WSGIRequest` subclass doesn't call `super`.\n@@ -364,6 +365,19 @@ def upload_handlers(self, upload_handlers):\n )\n self._upload_handlers = upload_handlers\n \n+ [USER_REDACTED]\n+ def multipart_parser_class(self):\n+ return self._multipart_parser_class\n+\n+ [USER_REDACTED]_parser_class.setter\n+ def multipart_parser_class(self, multipart_parser_class):\n+ if hasattr(self, \"_files\"):\n+ raise RuntimeError(\n+ \"You cannot set the multipart parser class after the upload has been \"\n+ \"processed.\"\n+ )\n+ self._multipart_parser_class = multipart_parser_class\n+\n def parse_file_upload(self, META, post_data):\n \"\"\"Return a tuple of (POST QueryDict, FILES MultiValueDict).\"\"\"\n self.upload_handlers = ImmutableList(\n@@ -373,7 +387,9 @@ def parse_file_upload(self, META, post_data):\n \"processed.\"\n ),\n )\n- parser = MultiPartParser(META, post_data, self.upload_handlers, self.encoding)\n+ parser = self.multipart_parser_class(\n+ META, post_data, self.upload_handlers, self.encoding\n+ )\n return parser.parse()\n \n [USER_REDACTED]" }, { "filename": "docs/ref/request-response.txt", "status": "modified", "additions": 24, "deletions": 0, "changes": 24, "patch": "@@ -218,6 +218,30 @@ All attributes should be considered read-only, unless stated otherwise.\n executed before URL resolving takes place (you can use it in\n :meth:`process_view` though).\n \n+.. attribute:: HttpRequest.multipart_parser_class\n+\n+ .. versionadded:: 6.1\n+\n+ The class used to parse ``multipart/form-data`` request data. By default,\n+ this is ``django.http.multipartparser.MultiPartParser``.\n+\n+ You can set this attribute to use a custom multipart parser, either via\n+ middleware or directly in views::\n+\n+ from django.http.multipartparser import MultiPartParser\n+\n+\n+ class CustomMultiPartParser(MultiPartParser):\n+ def parse(self):\n+ post = QueryDict(mutable=True)\n+ files = MultiValueDict()\n+ # Custom processing logic here\n+ return post, files\n+\n+\n+ # In middleware or view:\n+ request.multipart_parser_class = CustomMultiPartParser\n+\n Attributes set by [NAME_REDACTED]\n ----------------------------------" }, { "filename": "docs/releases/6.1.txt", "status": "modified", "additions": 2, "deletions": 1, "changes": 3, "patch": "@@ -295,7 +295,8 @@ [NAME_REDACTED] and Responses\n ~~~~~~~~~~~~~~~~~~~~~~\n \n-* ...\n+* :attr:`HttpRequest.multipart_parser_class `\n+ can now be customized to use a different multipart parser class.\n \n Security\n ~~~~~~~~" }, { "filename": "tests/requests_tests/tests.py", "status": "modified", "additions": 71, "deletions": 1, "changes": 72, "patch": "@@ -13,7 +13,11 @@\n RawPostDataException,\n UnreadablePostError,\n )\n-from django.http.multipartparser import MAX_TOTAL_HEADER_SIZE, MultiPartParserError\n+from django.http.multipartparser import (\n+ MAX_TOTAL_HEADER_SIZE,\n+ MultiPartParser,\n+ MultiPartParserError,\n+)\n from django.http.request import split_domain_port\n from django.test import RequestFactory, SimpleTestCase, override_settings\n from django.test.client import BOUNDARY, MULTIPART_CONTENT, FakePayload\n@@ -1112,6 +1116,72 @@ def test_deepcopy(self):\n request.session[\"key\"] = \"value\"\n self.assertEqual(request_copy.session, {})\n \n+ def test_custom_multipart_parser_class(self):\n+\n+ class CustomMultiPartParser(MultiPartParser):\n+ def parse(self):\n+ post, files = super().parse()\n+ post._mutable = True\n+ post[\"custom_parser_used\"] = \"yes\"\n+ post._mutable = False\n+ return post, files\n+\n+ class CustomWSGIRequest(WSGIRequest):\n+ multipart_parser_class = CustomMultiPartParser\n+\n+ payload = FakePayload(\n+ \"\\r\\n\".join(\n+ [\n+ \"--boundary\",\n+ 'Content-Disposition: form-data; name=\"name\"',\n+ \"\",\n+ \"value\",\n+ \"--boundary--\",\n+ ]\n+ )\n+ )\n+ request = CustomWSGIRequest(\n+ {\n+ \"REQUEST_METHOD\": \"POST\",\n+ \"CONTENT_TYPE\": \"multipart/form-data; boundary=boundary\",\n+ \"CONTENT_LENGTH\": len(payload),\n+ \"wsgi.input\": payload,\n+ }\n+ )\n+ self.assertEqual(request.POST.get(\"custom_parser_used\"), \"yes\")\n+ self.assertEqual(request.POST.get(\"name\"), \"value\")\n+\n+ def test_multipart_parser_class_immutable_after_parse(self):\n+ payload = FakePayload(\n+ \"\\r\\n\".join(\n+ [\n+ \"--boundary\",\n+ 'Content-Disposition: form-data; name=\"name\"',\n+ \"\",\n+ \"value\",\n+ \"--boundary--\",\n+ ]\n+ )\n+ )\n+ request = WSGIRequest(\n+ {\n+ \"REQUEST_METHOD\": \"POST\",\n+ \"CONTENT_TYPE\": \"multipart/form-data; boundary=boundary\",\n+ \"CONTENT_LENGTH\": len(payload),\n+ \"wsgi.input\": payload,\n+ }\n+ )\n+\n+ # Access POST to trigger parsing.\n+ request.POST\n+\n+ msg = (\n+ \"You cannot set the multipart parser class after the upload has been \"\n+ \"processed.\"\n+ )\n+ with self.assertRaisesMessage(RuntimeError, msg):\n+ request.multipart_parser_class = MultiPartParser\n+\n \n class HostValidationTests(SimpleTestCase):\n poisoned_hosts = [" } ], "reviews": [ { "id": 3632090965, "user": "user_a0755d1ae088", "state": "COMMENTED", "body": null, "submitted_at": "2026-01-06T18:53:55+00:00" }, { "id": 3632101943, "user": "user_b42982f63633", "state": "COMMENTED", "body": null, "submitted_at": "2026-01-06T18:55:44+00:00" }, { "id": 3632358156, "user": "user_c332d334e171", "state": "APPROVED", "body": null, "submitted_at": "2026-01-06T20:19:07+00:00" }, { "id": 3723671318, "user": "user_3a67c55598c5", "state": "COMMENTED", "body": "Thanks [USER_REDACTED]!\n\nDid you have a look at Carlton's advice from the new-features repo to check that the parser contract was reasonably consistent?\n- `__init__()`\n- `parse()`\n- leave `QueryDict` immutable\n- ...?\n\nAny edge cases? (variance in where exactly is encoding checked?) Any ideas about whether this needs a sentence or two of docs?\n\nFinally, can you update the body of the PR with a sentence or so about the motivation?\nThanks!", "submitted_at": "2026-01-29T16:31:52+00:00" }, { "id": 3723837194, "user": "user_3a67c55598c5", "state": "COMMENTED", "body": null, "submitted_at": "2026-01-29T16:38:22+00:00" }, { "id": 3724675639, "user": "user_bddf51c3ef59", "state": "COMMENTED", "body": null, "submitted_at": "2026-01-29T19:46:44+00:00" }, { "id": 3724762873, "user": "user_3a67c55598c5", "state": "COMMENTED", "body": null, "submitted_at": "2026-01-29T20:04:25+00:00" }, { "id": 3726599137, "user": "user_bddf51c3ef59", "state": "COMMENTED", "body": null, "submitted_at": "2026-01-30T06:33:22+00:00" }, { "id": 3728908846, "user": "user_35035b8a218c", "state": "COMMENTED", "body": null, "submitted_at": "2026-01-30T15:18:45+00:00" }, { "id": 3736208128, "user": "user_cb2fc5a53d8e", "state": "COMMENTED", "body": null, "submitted_at": "2026-02-01T17:21:08+00:00" }, { "id": 3736467131, "user": "user_bddf51c3ef59", "state": "COMMENTED", "body": null, "submitted_at": "2026-02-01T18:39:01+00:00" }, { "id": 3736469833, "user": "user_bddf51c3ef59", "state": "COMMENTED", "body": null, "submitted_at": "2026-02-01T18:40:58+00:00" }, { "id": 3748063859, "user": "user_3a67c55598c5", "state": "COMMENTED", "body": null, "submitted_at": "2026-02-03T23:01:18+00:00" }, { "id": 3763821792, "user": "user_3a67c55598c5", "state": "COMMENTED", "body": null, "submitted_at": "2026-02-06T15:50:18+00:00" }, { "id": 3763843748, "user": "user_b42982f63633", "state": "COMMENTED", "body": null, "submitted_at": "2026-02-06T15:54:57+00:00" }, { "id": 3782023080, "user": "user_3a67c55598c5", "state": "APPROVED", "body": null, "submitted_at": "2026-02-10T22:46:09+00:00" } ], "review_comments": [ { "id": 2665945334, "user": "user_a0755d1ae088", "body": "```suggestion\n this is :class:`django.http.multipartparser.MultiPartParser`.\n```\nfor deep linking to the Sphinx documentation if it exists.", "path": "docs/ref/request-response.txt", "line": 226, "side": "RIGHT", "created_at": "2026-01-06T18:51:57+00:00" }, { "id": 2665955080, "user": "user_b42982f63633", "body": "It doesn't exist. I tried it.", "path": "docs/ref/request-response.txt", "line": 226, "side": "RIGHT", "created_at": "2026-01-06T18:55:44+00:00" }, { "id": 2742422674, "user": "user_3a67c55598c5", "body": "small detail: \"added\" annotations usually go at the top, \"changed\" at the bottom.", "path": "docs/ref/request-response.txt", "line": null, "side": "RIGHT", "created_at": "2026-01-29T16:09:32+00:00" }, { "id": 2742518620, "user": "user_3a67c55598c5", "body": "I don't want to increase the scope here, so I'm mostly leaving this as a question for you to react to (not necessarily encouraging you to push these changes just yet).\n\nDid you consider introducing a dictionary mapping content types to default parser classes? I'm trying to imagine the smoothest transition to django/deps#88, and I'm worried we'll need to support this one-off default for this one-off content type.\n\n[USER_REDACTED] and [USER_REDACTED], do either of you have an opinion about this?", "path": "django/http/request.py", "line": null, "side": "RIGHT", "created_at": "2026-01-29T16:31:25+00:00" }, { "id": 2742546592, "user": "user_3a67c55598c5", "body": "I guess we don't want to imply that any other content types are swappable. But there are ways around that, like adding a (silenceable) system check.", "path": "django/http/request.py", "line": null, "side": "RIGHT", "created_at": "2026-01-29T16:38:22+00:00" }, { "id": 2743238626, "user": "user_bddf51c3ef59", "body": "[USER_REDACTED] I think if it were me, I’d be inclined to keep this as it is here, and not try to preempt the future (merely possible) code. \n\n(It’s been so long not coming that I’d not want to tempt fate at this point 🫠)\n\nI think a deprecation path using a descriptor here would be fine (and quite low impact). \n\nWdyt?", "path": "django/http/request.py", "line": null, "side": "RIGHT", "created_at": "2026-01-29T19:46:44+00:00" }, { "id": 2743310706, "user": "user_3a67c55598c5", "body": "That's what I needed to hear!", "path": "django/http/request.py", "line": null, "side": "RIGHT", "created_at": "2026-01-29T20:04:25+00:00" }, { "id": 2744841844, "user": "user_bddf51c3ef59", "body": "```suggestion\n # This assertion would FAIL without the multipart_parser_class change\n```", "path": "tests/requests_tests/tests.py", "line": null, "side": "RIGHT", "created_at": "2026-01-30T06:33:22+00:00" }, { "id": 2746766720, "user": "user_35035b8a218c", "body": "+1 on what Carlton said. https://github.com/[USER_REDACTED]ngo/deps/pull/88 might just rewrite the request altogether (probably not but still), thinking about what might happen sounds like premature optimization", "path": "django/http/request.py", "line": null, "side": "RIGHT", "created_at": "2026-01-30T15:18:35+00:00" }, { "id": 2751595940, "user": "user_cb2fc5a53d8e", "body": "Should we document this approach of subclassing `[WSGI|ASGI]Request`? Natalia also mentioned subclassing HttpRequest in the ticket.\n\nhttps://code.djangoproject.com/ticket/36841#comment:2", "path": "tests/requests_tests/tests.py", "line": 1130, "side": "RIGHT", "created_at": "2026-02-01T16:57:29+00:00" }, { "id": 2751642108, "user": "user_cb2fc5a53d8e", "body": "Should we make `multi_part_parser` immutable once the body has been parsed? \n\nSay you are setting the parser in a view, and _somewhere_ before then it had already been read you'll get the data that was originally parsed. \n\n``` python\nIn [34]: payload = FakePayload(\n ...: \"\\r\\n\".join(\n ...: [\n ...: \"--boundary\",\n ...: 'Content-Disposition: form-data; name=\"name\"',\n ...: \"\",\n ...: \"value\",\n ...: \"--boundary--\",\n ...: ]\n ...: )\n ...: )\n\nIn [35]: request = WSGIRequest( {\n ...: \"REQUEST_METHOD\": \"POST\",\n ...: \"CONTENT_TYPE\": \"multipart/form-data; boundary=boundary\",\n ...: \"CONTENT_LENGTH\": len(payload),\n ...: \"wsgi.input\": payload,\n ...: }\n ...: )\n\nIn [36]: request.POST\nOut[36]: \n\nIn [32]: class CustomMultiPartParser(MultiPartParser):\n ...: def parse(self):\n ...: files = MultiValueDict()\n ...: return {\"Test\" : 1234}, files\n\nIn [37]: request.multipart_parser_class = [NAME_REDACTED] [38]: request.POST\nOut[38]: # Not the data from our custom parser\n```", "path": "django/http/request.py", "line": null, "side": "RIGHT", "created_at": "2026-02-01T17:20:12+00:00" }, { "id": 2751801232, "user": "user_bddf51c3ef59", "body": "I thought about this. I kind of think the middleware approach is more _mainstream_. \n\nI don't think we mention the handler classes (and manually instantiating them) at all do we? \n\n(Like that's probably how _I'd_ do it myself, but is it part of the _public API_ so to speak? Not sure it is.)", "path": "tests/requests_tests/tests.py", "line": 1130, "side": "RIGHT", "created_at": "2026-02-01T18:39:01+00:00" }, { "id": 2751802591, "user": "user_bddf51c3ef59", "body": "Nice example. \n\nI'd be inclined to just document something like. \"Setting ... after `request.POST` has already been processed will have no effect.\" \n\n(Phrasing isn't quite right there: the attribute will be set, just not _used_.)", "path": "django/http/request.py", "line": null, "side": "RIGHT", "created_at": "2026-02-01T18:40:58+00:00" }, { "id": 2761390011, "user": "user_3a67c55598c5", "body": "Having this as a property from the start might make it easier to cleanly deprecate later 👍", "path": "django/http/request.py", "line": 373, "side": "RIGHT", "created_at": "2026-02-03T22:59:33+00:00" }, { "id": 2761395332, "user": "user_3a67c55598c5", "body": "I'd raise `RuntimeError` since I'm used to `AttributeError` emitted on getting missing attrs, not on setting.", "path": "django/http/request.py", "line": null, "side": "RIGHT", "created_at": "2026-02-03T23:01:01+00:00" }, { "id": 2774803751, "user": "user_3a67c55598c5", "body": "Watch out, this snuck in 😄", "path": "uv.lock", "line": null, "side": "RIGHT", "created_at": "2026-02-06T15:50:19+00:00" }, { "id": 2774824277, "user": "user_b42982f63633", "body": "Sorry, fixed.", "path": "uv.lock", "line": null, "side": "RIGHT", "created_at": "2026-02-06T15:54:57+00:00" } ], "meta": { "languages": [ "py", "txt" ], "touches_tests": true, "review_state_summary": { "COMMENTED": 14, "APPROVED": 2 }, "meaningful_comment_count": 17, "has_approval": true, "has_changes_requested": false, "total_review_comments": 17 } } { "_id": "283059a64f65c251", "_schema_version": "1.0", "_cleaned_at": "2026-02-12T07:46:51.562181+00:00", "repo": "django/django", "repo_url": "https://github.com/django/django", "license_name": "BSD 3-Clause \"New\" or \"Revised\" License", "license_spdx": "BSD-3-Clause", "pr_number": 20497, "title": "Fixed #36843, #36793 -- Reverted \"Fixed #27489 -- Renamed permissions upon model renaming in migrations.\"", "body": "#### Trac ticket number\nFixes regressions:\nticket-36843\nticket-36793\nOriginal work being reverted:\nticket-27489\n\n#### Branch description\nThis reverts commits f02b49d2f3bf84f5225de920ca510149f1f9f1da and 6e89271a8507fe272d11814975500a1b40303a04.\n\n#20481 outlines some issues that came to light in the `RenamePermission` operation after it was merged. The highest severity issues were captured in Trac, but there is some low priority feedback as well captured in #20481.\n\nThe issue (ticket-36793) dealing with conflict handling is admittedly more niche, but it still deserves some thought (warn? fail? add interactive mode?). I'm suggesting to merge this revert, and then reopen ticket-27489 and address the feedback with less time pressure.\n\n#### Checklist\n- [x] This PR targets the `main` branch. \n- [x] The commit message is written in past tense, mentions the ticket number, and ends with a period.\n- [x] I have checked the \"Has patch\" ticket flag in the Trac system.\n- [na] I have added or updated relevant tests.\n- [na] I have added or updated relevant docs, including release notes if applicable.\n- [na] I have attached screenshots in both light and dark modes for any UI changes.", "author": "user_3a67c55598c5", "created_at": "2026-01-05T19:18:21+00:00", "merged_at": "2026-01-05T20:45:27+00:00", "base_branch": "main", "head_branch": "jtw/revert-rename-permission", "additions": 12, "deletions": 313, "changed_files": 7, "files": [ { "filename": "django/contrib/auth/apps.py", "status": "modified", "additions": 2, "deletions": 7, "changes": 9, "patch": "@@ -1,12 +1,12 @@\n from django.apps import AppConfig\n from django.core import checks\n from django.db.models.query_utils import DeferredAttribute\n-from django.db.models.signals import post_migrate, pre_migrate\n+from django.db.models.signals import post_migrate\n from django.utils.translation import gettext_lazy as _\n \n from . import get_user_model\n from .checks import check_middleware, check_models_permissions, check_user_model\n-from .management import create_permissions, rename_permissions\n+from .management import create_permissions\n from .signals import user_logged_in\n \n \n@@ -20,11 +20,6 @@ def ready(self):\n create_permissions,\n dispatch_uid=\"django.contrib.auth.management.create_permissions\",\n )\n- pre_migrate.connect(\n- rename_permissions,\n- dispatch_uid=\"django.contrib.auth.management.rename_permissions\",\n- )\n-\n last_login_field = getattr(get_user_model(), \"last_login\", None)\n # Register the handler only if UserModel.last_login is a field.\n if isinstance(last_login_field, DeferredAttribute):" }, { "filename": "django/contrib/auth/management/__init__.py", "status": "modified", "additions": 1, "deletions": 81, "changes": 82, "patch": "@@ -9,9 +9,7 @@\n from django.contrib.auth import get_permission_codename\n from django.contrib.contenttypes.management import create_contenttypes\n from django.core import exceptions\n-from django.db import DEFAULT_DB_ALIAS, migrations, router, transaction\n-from django.db.utils import IntegrityError\n-from django.utils.text import camel_case_to_spaces\n+from django.db import DEFAULT_DB_ALIAS, router\n \n \n def _get_all_permissions(opts):\n@@ -110,84 +108,6 @@ def create_permissions(\n print(\"Adding permission '%s'\" % perm)\n \n \n-class RenamePermission(migrations.RunPython):\n- def __init__(self, app_label, old_model, new_model):\n- self.app_label = app_label\n- self.old_model = old_model\n- self.new_model = new_model\n- super(RenamePermission, self).__init__(\n- self.rename_forward, self.rename_backward\n- )\n-\n- def _rename(self, apps, schema_editor, old_model, new_model):\n- ContentType = apps.get_model(\"contenttypes\", \"ContentType\")\n- # Use the live Permission model instead of the frozen one, since frozen\n- # models do not retain foreign key constraints.\n- from django.contrib.auth.models import Permission\n-\n- db = schema_editor.connection.alias\n- ctypes = ContentType.objects.using(db).filter(\n- app_label=self.app_label, model__icontains=old_model.lower()\n- )\n- for permission in Permission.objects.using(db).filter(\n- content_type_id__in=ctypes.values(\"id\")\n- ):\n- prefix = permission.codename.split(\"_\")[0]\n- default_verbose_name = camel_case_to_spaces(new_model)\n-\n- new_codename = f\"{prefix}_{new_model.lower()}\"\n- new_name = f\"Can {prefix} {default_verbose_name}\"\n-\n- if permission.codename != new_codename or permission.name != new_name:\n- permission.codename = new_codename\n- permission.name = new_name\n- try:\n- with transaction.atomic(using=db):\n- permission.save(update_fields={\"name\", \"codename\"})\n- except IntegrityError:\n- pass\n-\n- def rename_forward(self, apps, schema_editor):\n- self._rename(apps, schema_editor, self.old_model, self.new_model)\n-\n- def rename_backward(self, apps, schema_editor):\n- self._rename(apps, schema_editor, self.new_model, self.old_model)\n-\n-\n-def rename_permissions(\n- plan,\n- verbosity=2,\n- interactive=True,\n- using=DEFAULT_DB_ALIAS,\n- apps=global_apps,\n- **kwargs,\n-):\n- \"\"\"\n- Insert a `RenamePermissionType` operation after every planned `RenameModel`\n- operation.\n- \"\"\"\n- try:\n- Permission = apps.get_model(\"auth\", \"Permission\")\n- except LookupError:\n- return\n- else:\n- if not router.allow_migrate_model(using, Permission):\n- return\n-\n- for migration, backward in plan:\n- inserts = []\n- for index, operation in enumerate(migration.operations):\n- if isinstance(operation, migrations.RenameModel):\n- operation = RenamePermission(\n- migration.app_label,\n- operation.old_name,\n- operation.new_name,\n- )\n- inserts.append((index + 1, operation))\n- for inserted, (index, operation) in enumerate(inserts):\n- migration.operations.insert(inserted + index, operation)\n-\n-\n def get_system_username():\n \"\"\"\n Return the current system user's username, or an empty string if the" }, { "filename": "docs/releases/6.0.1.txt", "status": "modified", "additions": 7, "deletions": 0, "changes": 7, "patch": "@@ -42,3 +42,10 @@ Bugfixes\n * Fixed a regression in Django 6.0 where the :attr:`.Widget.use_fieldset`\n attribute of :class:`~django.forms.ClearableFileInput` was flipped\n from ``False`` to ``True`` (:ticket:`36829`).\n+\n+* Reverted an undocumented optimization in Django 6.0 that modified permission\n+ :attr:`~django.contrib.auth.models.Permission.name` and\n+ :attr:`~django.contrib.auth.models.Permission.codename` values when renaming\n+ models via a migration. This change could affect unrelated\n+ :class:`~django.contrib.auth.models.Permission` objects (:ticket:`36843`) and\n+ did not report conflicts (:ticket:`36793`)." }, { "filename": "tests/auth_tests/operations_migrations/0001_initial.py", "status": "removed", "additions": 0, "deletions": 14, "changes": 14, "patch": "@@ -1,14 +0,0 @@\n-from django.db import migrations, models\n-\n-\n-class Migration(migrations.Migration):\n- initial = True\n-\n- operations = [\n- migrations.CreateModel(\n- name=\"OldModel\",\n- fields=[\n- (\"id\", models.AutoField(primary_key=True)),\n- ],\n- ),\n- ]" }, { "filename": "tests/auth_tests/operations_migrations/0002_rename_oldmodel_to_newmodel.py", "status": "removed", "additions": 0, "deletions": 14, "changes": 14, "patch": "@@ -1,14 +0,0 @@\n-from django.db import migrations\n-\n-\n-class Migration(migrations.Migration):\n- dependencies = [\n- (\"auth_tests\", \"0001_initial\"),\n- ]\n-\n- operations = [\n- migrations.RenameModel(\n- old_name=\"OldModel\",\n- new_name=\"NewModel\",\n- ),\n- ]" }, { "filename": "tests/auth_tests/operations_migrations/__init__.py", "status": "removed", "additions": 0, "deletions": 0, "changes": 0, "patch": null }, { "filename": "tests/auth_tests/test_management.py", "status": "modified", "additions": 2, "deletions": 197, "changes": 199, "patch": "@@ -7,21 +7,15 @@\n from unittest import mock\n \n from django.apps import apps\n-from django.conf import settings\n from django.contrib.auth import get_permission_codename, management\n-from django.contrib.auth.management import (\n- RenamePermission,\n- create_permissions,\n- get_default_username,\n-)\n+from django.contrib.auth.management import create_permissions, get_default_username\n from django.contrib.auth.management.commands import changepassword, createsuperuser\n from django.contrib.auth.models import Group, Permission, User\n from django.contrib.contenttypes.models import ContentType\n from django.core.management import call_command\n from django.core.management.base import CommandError\n-from django.db import migrations, models\n+from django.db import migrations\n from django.test import TestCase, override_settings\n-from django.test.testcases import TransactionTestCase\n from django.utils.translation import gettext_lazy as _\n \n from .models import (\n@@ -1534,195 +1528,6 @@ def test_permission_with_proxy_content_type_created(self):\n )\n \n \n-[USER_REDACTED]_settings(\n- MIGRATION_MODULES=dict(\n- settings.MIGRATION_MODULES,\n- auth_tests=\"auth_tests.operations_migrations\",\n- ),\n-)\n-class PermissionRenameOperationsTests(TransactionTestCase):\n- available_apps = [\n- \"django.contrib.contenttypes\",\n- \"django.contrib.auth\",\n- \"auth_tests\",\n- ]\n- databases = {\"default\", \"other\"}\n-\n- def setUp(self):\n- app_config = apps.get_app_config(\"auth_tests\")\n- models.signals.post_migrate.connect(\n- self.assertOperationsInjected, sender=app_config\n- )\n- self.addCleanup(\n- models.signals.post_migrate.disconnect,\n- self.assertOperationsInjected,\n- sender=app_config,\n- )\n-\n- def assertOperationsInjected(self, plan, **kwargs):\n- for migration, _backward in plan:\n- operations = iter(migration.operations)\n- for operation in operations:\n- if isinstance(operation, migrations.RenameModel):\n- next_operation = next(operations)\n- self.assertIsInstance(next_operation, RenamePermission)\n- self.assertEqual(next_operation.app_label, migration.app_label)\n- self.assertEqual(next_operation.old_model, operation.old_name)\n- self.assertEqual(next_operation.new_model, operation.new_name)\n-\n- def test_permission_rename(self):\n- ct = ContentType.objects.create(app_label=\"auth_tests\", model=\"oldmodel\")\n- actions = [\"add\", \"change\", \"delete\", \"view\"]\n- for action in actions:\n- Permission.objects.create(\n- codename=f\"{action}_oldmodel\",\n- name=f\"Can {action} old model\",\n- content_type=ct,\n- )\n-\n- call_command(\"migrate\", \"auth_tests\", verbosity=0)\n- for action in actions:\n- self.assertFalse(\n- Permission.objects.filter(codename=f\"{action}_oldmodel\").exists()\n- )\n- self.assertTrue(\n- Permission.objects.filter(codename=f\"{action}_newmodel\").exists()\n- )\n-\n- call_command(\n- \"migrate\",\n- \"auth_tests\",\n- \"zero\",\n- database=\"default\",\n- interactive=False,\n- verbosity=0,\n- )\n-\n- for action in actions:\n- self.assertTrue(\n- Permission.objects.filter(codename=f\"{action}_oldmodel\").exists()\n- )\n- self.assertFalse(\n- Permission.objects.filter(codename=f\"{action}_newmodel\").exists()\n- )\n-\n- def test_permission_rename_other_db(self):\n- ct = ContentType.objects.using(\"default\").create(\n- app_label=\"auth_tests\", model=\"oldmodel\"\n- )\n- permission = Permission.objects.using(\"default\").create(\n- codename=\"add_oldmodel\",\n- name=\"Can add old model\",\n- content_type=ct,\n- )\n- # RenamePermission respects the database.\n- call_command(\"migrate\", \"auth_tests\", verbosity=0, database=\"other\")\n- permission.refresh_from_db()\n- self.assertEqual(permission.codename, \"add_oldmodel\")\n- self.assertFalse(\n- Permission.objects.using(\"other\").filter(codename=\"add_oldmodel\").exists()\n- )\n- self.assertTrue(\n- Permission.objects.using(\"other\").filter(codename=\"add_newmodel\").exists()\n- )\n-\n- [USER_REDACTED].patch(\n- \"django.db.router.allow_migrate_model\",\n- return_value=False,\n- )\n- def test_rename_skipped_if_router_disallows(self, _):\n- ct = ContentType.objects.create(app_label=\"auth_tests\", model=\"oldmodel\")\n- Permission.objects.create(\n- codename=\"change_oldmodel\",\n- name=\"Can change old model\",\n- content_type=ct,\n- )\n- # The rename operation should not be there when disallowed by router.\n- app_config = apps.get_app_config(\"auth_tests\")\n- models.signals.post_migrate.disconnect(\n- self.assertOperationsInjected, sender=app_config\n- )\n-\n- call_command(\n- \"migrate\",\n- \"auth_tests\",\n- database=\"default\",\n- interactive=False,\n- verbosity=0,\n- )\n- self.assertTrue(Permission.objects.filter(codename=\"change_oldmodel\").exists())\n- self.assertFalse(Permission.objects.filter(codename=\"change_newmodel\").exists())\n-\n- call_command(\n- \"migrate\",\n- \"auth_tests\",\n- \"zero\",\n- database=\"default\",\n- interactive=False,\n- verbosity=0,\n- )\n-\n- def test_rename_backward_does_nothing_if_no_permissions(self):\n- Permission.objects.filter(content_type__app_label=\"auth_tests\").delete()\n-\n- call_command(\n- \"migrate\",\n- \"auth_tests\",\n- \"zero\",\n- database=\"default\",\n- interactive=False,\n- verbosity=0,\n- )\n- self.assertFalse(\n- Permission.objects.filter(\n- codename__in=[\"change_oldmodel\", \"change_newmodel\"]\n- ).exists()\n- )\n-\n- def test_rename_permission_conflict(self):\n- ct = ContentType.objects.create(app_label=\"auth_tests\", model=\"oldmodel\")\n- Permission.objects.create(\n- codename=\"change_newmodel\",\n- name=\"Can change new model\",\n- content_type=ct,\n- )\n- Permission.objects.create(\n- codename=\"change_oldmodel\",\n- name=\"Can change old model\",\n- content_type=ct,\n- )\n-\n- call_command(\n- \"migrate\",\n- \"auth_tests\",\n- database=\"default\",\n- interactive=False,\n- verbosity=0,\n- )\n- self.assertTrue(\n- Permission.objects.filter(\n- codename=\"change_oldmodel\",\n- name=\"Can change old model\",\n- ).exists()\n- )\n- self.assertEqual(\n- Permission.objects.filter(\n- codename=\"change_newmodel\",\n- name=\"Can change new model\",\n- ).count(),\n- 1,\n- )\n-\n- call_command(\n- \"migrate\",\n- \"auth_tests\",\n- \"zero\",\n- database=\"default\",\n- interactive=False,\n- verbosity=0,\n- )\n-\n-\n class DefaultDBRouter:\n \"\"\"Route all writes to default.\"\"\"" } ], "reviews": [ { "id": 3628192809, "user": "user_00dac951cdbf", "state": "APPROVED", "body": "Looks good, thank you for the thorough code digging and analysis!\n\nI suggested a few optional changes for the release note.", "submitted_at": "2026-01-05T19:43:58+00:00" }, { "id": 3628199901, "user": "user_3a67c55598c5", "state": "COMMENTED", "body": null, "submitted_at": "2026-01-05T19:45:53+00:00" } ], "review_comments": [ { "id": 2662608672, "user": "user_00dac951cdbf", "body": "Suggestion to make it clear that the rename is on the values of the fields, not the field names (which is how I read it originally):\n\n```suggestion\n* Reverted an undocumented optimization in Django 6.0 that modified permission\n :attr:`~django.contrib.auth.models.Permission.name` and\n :attr:`~django.contrib.auth.models.Permission.codename` values when renaming\n models via a migration. This change could affect unrelated\n :class:`~django.contrib.auth.models.Permission` objects (:ticket:`36843`) and\n did not report conflicts (:ticket:`36793`).\n```", "path": "docs/releases/6.0.1.txt", "line": null, "side": "RIGHT", "created_at": "2026-01-05T19:43:06+00:00" }, { "id": 2662614840, "user": "user_3a67c55598c5", "body": "Nice catch 👍", "path": "docs/releases/6.0.1.txt", "line": null, "side": "RIGHT", "created_at": "2026-01-05T19:45:53+00:00" } ], "meta": { "languages": [ "py", "txt" ], "touches_tests": true, "review_state_summary": { "APPROVED": 1, "COMMENTED": 1 }, "meaningful_comment_count": 2, "has_approval": true, "has_changes_requested": false, "total_review_comments": 2 } } { "_id": "24dfbe178a6db06e", "_schema_version": "1.0", "_cleaned_at": "2026-02-12T07:46:51.562181+00:00", "repo": "django/django", "repo_url": "https://github.com/django/django", "license_name": "BSD 3-Clause \"New\" or \"Revised\" License", "license_spdx": "BSD-3-Clause", "pr_number": 20496, "title": "Improve `django.tasks.base` types", "body": "`list` does not provide as much information as `list[Any]`, since args can literally be `Any`, there's no need to ignore this type.\n\nThis is a minor cleanup, I don't think that it needs an issue.\nFound while working on `django-stubs` support for `django.tasks`: https://github.com/[USER_REDACTED]ngo/django-stubs/pull/2967", "author": "user_8c6bac8ba940", "created_at": "2026-01-05T10:36:02+00:00", "merged_at": "2026-01-07T15:23:26+00:00", "base_branch": "main", "head_branch": "patch-6", "additions": 11, "deletions": 10, "changed_files": 1, "files": [ { "filename": "django/tasks/base.py", "status": "modified", "additions": 11, "deletions": 10, "changes": 21, "patch": "@@ -1,7 +1,8 @@\n+from collections.abc import Callable\n from dataclasses import dataclass, field, replace\n from datetime import datetime\n from inspect import isclass, iscoroutinefunction\n-from typing import Any, Callable, Dict, Optional\n+from typing import Any\n \n from asgiref.sync import async_to_sync, sync_to_async\n \n@@ -43,10 +44,10 @@ class TaskResultStatus(TextChoices):\n [USER_REDACTED](frozen=True, slots=True, kw_only=True)\n class Task:\n priority: int\n- func: Callable # The Task function.\n+ func: Callable[..., Any] # The Task function.\n backend: str\n queue_name: str\n- run_after: Optional[datetime] # The earliest this Task will run.\n+ run_after: datetime | None # The earliest this Task will run.\n \n # Whether the Task receives the Task context when executed.\n takes_context: bool = False\n@@ -180,20 +181,20 @@ class TaskResult:\n \n id: str # Unique identifier for the task result.\n status: TaskResultStatus\n- enqueued_at: Optional[datetime] # Time the task was enqueued.\n- started_at: Optional[datetime] # Time the task was started.\n- finished_at: Optional[datetime] # Time the task was finished.\n+ enqueued_at: datetime | None # Time the task was enqueued.\n+ started_at: datetime | None # Time the task was started.\n+ finished_at: datetime | None # Time the task was finished.\n \n # Time the task was last attempted to be run.\n- last_attempted_at: Optional[datetime]\n+ last_attempted_at: datetime | None\n \n- args: list # Arguments to pass to the task function.\n- kwargs: Dict[str, Any] # Keyword arguments to pass to the task function.\n+ args: list[Any] # Arguments to pass to the task function.\n+ kwargs: dict[str, Any] # Keyword arguments to pass to the task function.\n backend: str\n errors: list[TaskError] # Errors raised when running the task.\n worker_ids: list[str] # Workers which have processed the task.\n \n- _return_value: Optional[Any] = field(init=False, default=None)\n+ _return_value: Any | None = field(init=False, default=None)\n \n def __post_init__(self):\n object.__setattr__(self, \"args\", normalize_json(self.args))" } ], "reviews": [ { "id": 3626655469, "user": "user_34c3f4acb8a8", "state": "COMMENTED", "body": null, "submitted_at": "2026-01-05T12:27:40+00:00" }, { "id": 3627856788, "user": "user_194c2ef4033e", "state": "COMMENTED", "body": null, "submitted_at": "2026-01-05T17:54:07+00:00" }, { "id": 3630539919, "user": "user_194c2ef4033e", "state": "APPROVED", "body": null, "submitted_at": "2026-01-06T11:20:12+00:00" }, { "id": 3631243615, "user": "user_c332d334e171", "state": "APPROVED", "body": null, "submitted_at": "2026-01-06T15:01:27+00:00" } ], "review_comments": [ { "id": 2661333487, "user": "user_34c3f4acb8a8", "body": "Question: is `list` not just a shorthand for `list[Any]`? Does this improve the type signature at all?", "path": "django/tasks/base.py", "line": 191, "side": "RIGHT", "created_at": "2026-01-05T12:27:40+00:00" }, { "id": 2662329817, "user": "user_194c2ef4033e", "body": "Implicitly, yes, but it's often helpful to be explicit.\n\nIn addition, when enabling mypy's [`--disallow-any-generics`](https://mypy.readthedocs.io/en/stable/command_line.html#cmdoption-mypy-disallow-any-generics), which is included when using the [`--strict`](https://mypy.readthedocs.io/en/stable/command_line.html#cmdoption-mypy-strict) flag, implicit type parameters will error.", "path": "django/tasks/base.py", "line": 191, "side": "RIGHT", "created_at": "2026-01-05T17:50:24+00:00" }, { "id": 2662339442, "user": "user_194c2ef4033e", "body": "As Django 6.0+ targets Python 3.12+ we can make the following change:\n\n```diff\n-from typing import Any, Callable, Dict, Optional\n+from collections.abc import Callable\n+from typing import Any\n```\n\nAnd below we should change the following:\n\n- Instead of `typing.Dict[K, V]` we can use `dict[K, V]`. (We're already using `list` instead of `typing.List`.)\n- Instead of `typing.Optional[T]` we can use `T | None`.", "path": "django/tasks/base.py", "line": null, "side": "RIGHT", "created_at": "2026-01-05T17:53:45+00:00" } ], "meta": { "languages": [ "py" ], "touches_tests": false, "review_state_summary": { "COMMENTED": 2, "APPROVED": 2 }, "meaningful_comment_count": 3, "has_approval": true, "has_changes_requested": false, "total_review_comments": 3 } } { "_id": "c5e4a3af7ce7d4ed", "_schema_version": "1.0", "_cleaned_at": "2026-02-12T07:46:51.562181+00:00", "repo": "django/django", "repo_url": "https://github.com/django/django", "license_name": "BSD 3-Clause \"New\" or \"Revised\" License", "license_spdx": "BSD-3-Clause", "pr_number": 20495, "title": "Fixed #35442 -- Prevented N+1 queries in RelatedManager with only().", "body": "ticket-35442\n\n#### Branch description\nThis PR prevents N+1 queries when iterating over a `RelatedManager` queryset that uses `.only()` to exclude the foreign key field.\n\nPreviously, `ModelIterable` would attempt to optimize the relationship population by [NAME_REDACTED] on the child object. If that key was deferred (via .`only()`), accessing it triggered an immediate SQL query for every row.\n\nThe fix modifies `ModelIterable` to check `obj.__dict__` first. If the foreign key attributes are missing (deferred), the optimization is skipped, preserving the lazy loading behavior requested by [NAME_REDACTED]\n\n**Tests:**\n* Added `test_only_related_manager_optimization` in `defer.tests` to verify query count is 1 (previously N+1).\n* Updated `defer.tests.DeferTests.test_only` to assert the correct number of deferred fields (3 instead of 2), reflecting that the foreign key is now correctly deferred.\n\n#### Checklist\n- [ ] This PR targets the `main` branch. \n- [ ] The commit message is written in past tense, mentions the ticket number, and ends with a period.\n- [ ] I have checked the \"Has patch\" ticket flag in the Trac system.\n- [ ] I have added or updated relevant tests.\n- [ ] I have added or updated relevant docs, including release notes if applicable.\n- [ ] I have attached screenshots in both light and dark modes for any UI changes.", "author": "user_97513ac81384", "created_at": "2026-01-05T05:51:48+00:00", "merged_at": "2026-01-13T18:18:14+00:00", "base_branch": "main", "head_branch": "ticket-35442-clean", "additions": 26, "deletions": 14, "changed_files": 2, "files": [ { "filename": "django/db/models/query.py", "status": "modified", "additions": 14, "deletions": 11, "changes": 25, "patch": "@@ -109,16 +109,15 @@ def __iter__(self):\n (\n field,\n related_objs,\n- operator.attrgetter(\n- *[\n- (\n- field.attname\n- if from_field == \"self\"\n- else queryset.model._meta.get_field(from_field).attname\n- )\n- for from_field in field.from_fields\n- ]\n- ),\n+ attnames := [\n+ (\n+ field.attname\n+ if from_field == \"self\"\n+ else queryset.model._meta.get_field(from_field).attname\n+ )\n+ for from_field in field.from_fields\n+ ],\n+ operator.attrgetter(*attnames),\n )\n for field, related_objs in queryset._known_related_objects.items()\n ]\n@@ -133,10 +132,14 @@ def __iter__(self):\n setattr(obj, attr_name, row[col_pos])\n \n # Add the known related objects to the model.\n- for field, rel_objs, rel_getter in known_related_objects:\n+ for field, rel_objs, rel_attnames, rel_getter in known_related_objects:\n # Avoid overwriting objects loaded by, e.g., select_related().\n if field.is_cached(obj):\n continue\n+ # Avoid fetching potentially deferred attributes that would\n+ # result in unexpected queries.\n+ if any(attname not in obj.__dict__ for attname in rel_attnames):\n+ continue\n rel_obj_id = rel_getter(obj)\n try:\n rel_obj = rel_objs[rel_obj_id]" }, { "filename": "tests/defer/tests.py", "status": "modified", "additions": 12, "deletions": 3, "changes": 15, "patch": "@@ -47,9 +47,9 @@ def test_only(self):\n # of them except the model's primary key see #15494\n self.assert_delayed(qs.only(\"pk\")[0], 3)\n # You can use 'pk' with reverse foreign key lookups.\n- # The related_id is always set even if it's not fetched from the DB,\n- # so pk and related_id are not deferred.\n- self.assert_delayed(self.s1.primary_set.only(\"pk\")[0], 2)\n+ # The related_id is not set if it's not fetched from the DB,\n+ # so pk is not deferred, but related_id is.\n+ self.assert_delayed(self.s1.primary_set.only(\"pk\")[0], 3)\n \n def test_defer_only_chaining(self):\n qs = Primary.objects.all()\n@@ -82,6 +82,15 @@ def test_only_none_raises_error(self):\n with self.assertRaisesMessage(TypeError, msg):\n Primary.objects.only(None)\n \n+ def test_only_related_manager_optimization(self):\n+ s = Secondary.objects.create(first=\"one\", second=\"two\")\n+ Primary.objects.bulk_create(\n+ [Primary(name=\"p1\", value=\"v1\", related=s) for _ in range(5)]\n+ )\n+ with self.assertNumQueries(1):\n+ for p in s.primary_set.only(\"pk\"):\n+ _ = p.pk\n+\n def test_defer_extra(self):\n qs = Primary.objects.all()\n self.assert_delayed(qs.defer(\"name\").extra(select={\"a\": 1})[0], 1)" } ], "reviews": [ { "id": 3627364454, "user": "user_3a67c55598c5", "state": "COMMENTED", "body": "Thanks for the PR! Since this uses Simon's patch from the ticket comments, please add him as a co-author [NAME_REDACTED] You can grep the commit log to see how this is done. Also please use two hyphens (not one) in the commit message & PR title. Cheers!", "submitted_at": "2026-01-05T15:42:38+00:00" }, { "id": 3652397706, "user": "user_3a67c55598c5", "state": "COMMENTED", "body": "Thanks 👍", "submitted_at": "2026-01-12T19:39:18+00:00" }, { "id": 3652611214, "user": "user_97513ac81384", "state": "COMMENTED", "body": null, "submitted_at": "2026-01-12T20:21:44+00:00" }, { "id": 3652903933, "user": "user_3a67c55598c5", "state": "APPROVED", "body": "Thanks ⭐", "submitted_at": "2026-01-12T21:58:56+00:00" } ], "review_comments": [ { "id": 2683613011, "user": "user_3a67c55598c5", "body": "Shouldn't this comment be updated?", "path": "tests/defer/tests.py", "line": 52, "side": "LEFT", "created_at": "2026-01-12T19:32:57+00:00" }, { "id": 2683789910, "user": "user_97513ac81384", "body": "I will update it now.", "path": "tests/defer/tests.py", "line": 52, "side": "LEFT", "created_at": "2026-01-12T20:21:44+00:00" } ], "meta": { "languages": [ "py" ], "touches_tests": true, "review_state_summary": { "COMMENTED": 3, "APPROVED": 1 }, "meaningful_comment_count": 2, "has_approval": true, "has_changes_requested": false, "total_review_comments": 2 } } { "_id": "2801ff2d744d57b3", "_schema_version": "1.0", "_cleaned_at": "2026-02-12T07:46:51.562181+00:00", "repo": "django/django", "repo_url": "https://github.com/django/django", "license_name": "BSD 3-Clause \"New\" or \"Revised\" License", "license_spdx": "BSD-3-Clause", "pr_number": 20480, "title": "Refs #33647 -- Fixed silent data truncation in bulk_create on Postgres.", "body": "#### Trac ticket number\nticket-33647\n\n#### Branch description\nRegression in a16eedcf9c69d8a11d94cac1811018c5b996d491.\n\nThe UNNEST strategy is affected by [NAME_REDACTED]_update has wrt/ to silent data truncation due to its usage of db_type which always returns a parametrized subtype.\n\n#### Checklist\n- [x] This PR targets the `main` branch. \n- [x] The commit message is written in past tense, mentions the ticket number, and ends with a period.\n- [x] I have checked the \"Has patch\" ticket flag in the Trac system.\n- [x] I have added or updated relevant tests.\n- [x] I have added or updated relevant docs, including release notes if applicable.\n- [x] I have attached screenshots in both light and dark modes for any UI changes.", "author": "user_3a67c55598c5", "created_at": "2025-12-31T15:12:16+00:00", "merged_at": "2025-12-31T15:41:55+00:00", "base_branch": "main", "head_branch": "ticket-33647", "additions": 22, "deletions": 3, "changed_files": 4, "files": [ { "filename": "django/db/backends/postgresql/compiler.py", "status": "modified", "additions": 3, "deletions": 1, "changes": 4, "patch": "@@ -53,7 +53,9 @@ def assemble_as_sql(self, fields, value_rows):\n or any(any(hasattr(value, \"as_sql\") for value in row) for row in value_rows)\n ):\n return super().assemble_as_sql(fields, value_rows)\n- db_types = [field.db_type(self.connection) for field in fields]\n+ # Manually remove parameters from `db_type` to ensure no data\n+ # truncation takes place (e.g. varchar[] instead of varchar(50)[]).\n+ db_types = [field.db_type(self.connection).split(\"(\")[0] for field in fields]\n return InsertUnnest([\"(%%s)::%s[]\" % db_type for db_type in db_types]), [\n list(map(list, zip(*value_rows)))\n ]" }, { "filename": "docs/releases/5.2.10.txt", "status": "modified", "additions": 5, "deletions": 1, "changes": 6, "patch": "@@ -4,11 +4,15 @@ Django 5.2.10 release notes\n \n *[NAME_REDACTED] 6, 2026*\n \n-Django 5.2.10 fixes several bugs in 5.2.9.\n+Django 5.2.10 fixes a data loss bug in Django 5.2 and one bug related to\n+support for Python 3.14.\n \n Bugfixes\n ========\n \n+* Fixed a bug in Django 5.2 where data exceeding ``max_length`` was silently\n+ truncated by :meth:`.QuerySet.bulk_create` on PostgreSQL (:ticket:`33647`).\n+\n * Fixed a bug where management command colorized help (introduced in\n Python 3.14) ignored the :option:`--no-color` option and the\n :envvar:`DJANGO_COLORS` setting (:ticket:`36376`)." }, { "filename": "docs/releases/6.0.1.txt", "status": "modified", "additions": 4, "deletions": 1, "changes": 5, "patch": "@@ -4,11 +4,14 @@ Django 6.0.1 release notes\n \n *[NAME_REDACTED] 6, 2026*\n \n-Django 6.0.1 fixes several bugs in 6.0.\n+Django 6.0.1 fixes one data loss bug in Django 5.2 and several bugs in 6.0.\n \n Bugfixes\n ========\n \n+* Fixed a bug in Django 5.2 where data exceeding ``max_length`` was silently\n+ truncated by :meth:`.QuerySet.bulk_create` on PostgreSQL (:ticket:`33647`).\n+\n * Fixed a regression in Django 6.0 where :ttag:`querystring` mishandled\n multi-value :class:`~django.http.QueryDict` keys, both by [NAME_REDACTED] value and by [NAME_REDACTED] ``None`` values (:ticket:`36783`)." }, { "filename": "tests/backends/postgresql/test_compilation.py", "status": "modified", "additions": 10, "deletions": 0, "changes": 10, "patch": "@@ -3,6 +3,7 @@\n \n from django.db import connection\n from django.db.models.expressions import RawSQL\n+from django.db.utils import DataError\n from django.test import TestCase\n \n from ..models import Article, Reporter, Square\n@@ -48,3 +49,12 @@ def test_unnest_eligible_foreign_keys(self):\n self.assertEqual(\n [article.reporter for article in articles], [reporter, reporter]\n )\n+\n+ def test_parametrized_db_type(self):\n+ with self.assertRaises(DataError):\n+ Reporter.objects.bulk_create(\n+ [\n+ Reporter(),\n+ Reporter(first_name=\"a\" * 31),\n+ ]\n+ )" } ], "reviews": [ { "id": 3621043169, "user": "user_cdda8932ec17", "state": "COMMENTED", "body": null, "submitted_at": "2025-12-31T15:18:09+00:00" }, { "id": 3621046730, "user": "user_3a67c55598c5", "state": "COMMENTED", "body": null, "submitted_at": "2025-12-31T15:21:04+00:00" } ], "review_comments": [ { "id": 2655539830, "user": "user_cdda8932ec17", "body": "FWIW the bug is also present for other pamametrized types such as `DecimalField`\n\nhttps://github.com/[USER_REDACTED]ngo/django/blob/79ab0993d0f2253e10ea638bcefc98ec2d890a47/django/db/backends/postgresql/base.py#L111-L114", "path": "docs/releases/5.2.10.txt", "line": null, "side": "RIGHT", "created_at": "2025-12-31T15:18:08+00:00" }, { "id": 2655543452, "user": "user_3a67c55598c5", "body": "Right, I was just trying to render a link. Should I just render a code literal?", "path": "docs/releases/5.2.10.txt", "line": null, "side": "RIGHT", "created_at": "2025-12-31T15:21:03+00:00" } ], "meta": { "languages": [ "py", "txt" ], "touches_tests": true, "review_state_summary": { "COMMENTED": 2 }, "meaningful_comment_count": 2, "has_approval": false, "has_changes_requested": false, "total_review_comments": 2 } } { "_id": "3cec6bef9f1864a8", "_schema_version": "1.0", "_cleaned_at": "2026-02-12T07:46:51.562181+00:00", "repo": "django/django", "repo_url": "https://github.com/django/django", "license_name": "BSD 3-Clause \"New\" or \"Revised\" License", "license_spdx": "BSD-3-Clause", "pr_number": 20471, "title": "Fixed #36829 -- Revert unintended ClearableFileInput.use_fieldset change", "body": "#### Trac ticket number\n\nticket-36829\nRef 4187da2\n\n#### Branch description\n\nRevert undocumented flip of `ClearableFileInput.use_fieldset` in Django 6.0.\n\n#### Checklist\n- [x] This PR targets the `main` branch. \n- [x] The commit message is written in past tense, mentions the ticket number, and ends with a period.\n- [x] I have checked the \"Has patch\" ticket flag in the Trac system.\n- [x] I have added or updated relevant tests.\n- [x] I have added or updated relevant docs, including release notes if applicable.\n- [x] I have attached screenshots in both light and dark modes for any UI changes.", "author": "user_eb9e19005079", "created_at": "2025-12-27T11:32:11+00:00", "merged_at": "2025-12-31T15:14:00+00:00", "base_branch": "main", "head_branch": "ticket/36829/fieldset", "additions": 13, "deletions": 9, "changed_files": 4, "files": [ { "filename": "django/contrib/admin/widgets.py", "status": "modified", "additions": 1, "deletions": 0, "changes": 1, "patch": "@@ -122,6 +122,7 @@ class AdminRadioSelect(forms.RadioSelect):\n \n class AdminFileWidget(forms.ClearableFileInput):\n template_name = \"admin/widgets/clearable_file_input.html\"\n+ use_fieldset = True\n \n \n def url_params_from_lookup_dict(lookups):" }, { "filename": "django/forms/widgets.py", "status": "modified", "additions": 1, "deletions": 1, "changes": 2, "patch": "@@ -530,7 +530,7 @@ class ClearableFileInput(FileInput):\n input_text = _(\"Change\")\n template_name = \"django/forms/widgets/clearable_file_input.html\"\n checked = False\n- use_fieldset = True\n+ use_fieldset = False\n \n def clear_checkbox_name(self, name):\n \"\"\"" }, { "filename": "docs/releases/6.0.1.txt", "status": "modified", "additions": 4, "deletions": 0, "changes": 4, "patch": "@@ -35,3 +35,7 @@ Bugfixes\n * Fixed a regression in Django 6.0 where :func:`~django.urls.path` routes\n defined using :func:`~django.utils.translation.gettext_lazy` failed to\n resolve correctly (:ticket:`36796`).\n+\n+* Fixed a regression in Django 6.0 where the :attr:`.Widget.use_fieldset`\n+ attribute of :class:`~django.forms.ClearableFileInput` was flipped\n+ from ``False`` to ``True`` (:ticket:`36829`)." }, { "filename": "tests/forms_tests/widget_tests/test_clearablefileinput.py", "status": "modified", "additions": 7, "deletions": 8, "changes": 15, "patch": "@@ -246,19 +246,18 @@ class TestForm(Form):\n )\n \n form = TestForm()\n- self.assertIs(self.widget.use_fieldset, True)\n+ self.assertIs(self.widget.use_fieldset, False)\n self.assertHTMLEqual(\n- \"
      Field:\"\n- '
      '\n- \"
      With file:Currently: \"\n+ '
      '\n+ '
      '\n+ '
      Currently: '\n 'something
      Change:
      '\n- \"
      Clearable file:\"\n+ 'name=\"with_file\" id=\"id_with_file\">
      '\n+ '
      '\n 'Currently: something'\n '
      Change:'\n- ''\n- \"
      \",\n+ '',\n form.render(),\n )" } ], "reviews": [ { "id": 3620924815, "user": "user_3a67c55598c5", "state": "COMMENTED", "body": null, "submitted_at": "2025-12-31T14:03:06+00:00" }, { "id": 3620964633, "user": "user_3a67c55598c5", "state": "APPROVED", "body": "Thanks for the report and fix!", "submitted_at": "2025-12-31T14:13:17+00:00" } ], "review_comments": [ { "id": 2649172415, "user": "user_5e63c02707a8", "body": "The AdminFileWidget class now explicitly sets use_fieldset to True, but there's no test coverage to verify this attribute value. Since the base ClearableFileInput has test coverage for use_fieldset in test_clearablefileinput.py, consider adding a similar test for AdminFileWidget to prevent future regressions of this attribute.", "path": "django/contrib/admin/widgets.py", "line": 125, "side": "RIGHT", "created_at": "2025-12-27T14:49:03+00:00" }, { "id": 2655423077, "user": "user_3a67c55598c5", "body": "I'll revert the changes to this file, as the admin's rendering of file fields with a `
      ` was already covered in `test_use_fieldset_fields_render()`:\n```py\n======================================================================\nFAIL: test_use_fieldset_fields_render (admin_views.tests.SeleniumTests.test_use_fieldset_fields_render)\n----------------------------------------------------------------------\nTraceback (most recent call last):\n File \"/Users/jwalls/django/tests/admin_views/tests.py\", line 6960, in test_use_fieldset_fields_render\n self.assertEqual(legend.text, expected_legend_tags_text[index])\n ~~~~~~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\nAssertionError: 'Difficulty:' != 'Materials:'\n- Difficulty:\n+ Materials:\n\n----------------------------------------------------------------------\nRan 1 test in 10.571s\n```", "path": "tests/admin_widgets/tests.py", "line": null, "side": "RIGHT", "created_at": "2025-12-31T13:43:04+00:00" } ], "meta": { "languages": [ "py", "txt" ], "touches_tests": true, "review_state_summary": { "COMMENTED": 1, "APPROVED": 1 }, "meaningful_comment_count": 2, "has_approval": true, "has_changes_requested": false, "total_review_comments": 2 } } { "_id": "57357072f8637ce5", "_schema_version": "1.0", "_cleaned_at": "2026-02-12T07:46:51.562181+00:00", "repo": "django/django", "repo_url": "https://github.com/django/django", "license_name": "BSD 3-Clause \"New\" or \"Revised\" License", "license_spdx": "BSD-3-Clause", "pr_number": 20466, "title": "Fixed #36639 -- Added CI step to run makemigrations --check against test models.", "body": "#### Trac ticket number\n\n\nticket-36639\n\n#### Branch description\nThis PR automated migration consistency checks for the test models with current migrations and added missing migration files . \nI have tested this PR on my local with \"act\" package.\n\nSS before fixing migrations: \n\"image\"\n\nSS after fixing migrations:\n\"image\"\n\n#### Checklist\n- [x] This PR targets the `main` branch. \n- [x] The commit message is written in past tense, mentions the ticket number, and ends with a period.\n- [x] I have checked the \"Has patch\" ticket flag in the Trac system.\n- [ ] I have added or updated relevant tests.\n- [ ] I have added or updated relevant docs, including release notes if applicable.\n- [ ] I have attached screenshots in both light and dark modes for any UI changes.", "author": "user_f5eee7dbaa84", "created_at": "2025-12-25T19:07:03+00:00", "merged_at": "2026-01-20T15:40:53+00:00", "base_branch": "main", "head_branch": "fix36639", "additions": 229, "deletions": 14, "changed_files": 7, "files": [ { "filename": ".github/workflows/check-migrations.yml", "status": "added", "additions": 68, "deletions": 0, "changes": 68, "patch": "@@ -0,0 +1,68 @@\n+name: Check migrations\n+\n+on:\n+ pull_request:\n+ paths:\n+ - 'tests/**/models.py'\n+ - 'tests/**/migrations/**'\n+ - 'tests/**/*migrations/**/*.py'\n+ - 'scripts/check_migrations.py'\n+ push:\n+ branches:\n+ - main\n+\n+concurrency:\n+ group: ${{ github.workflow }}-${{ github.ref }}\n+ cancel-in-progress: true\n+\n+permissions:\n+ contents: read\n+\n+jobs:\n+ check-migrations:\n+ name: Check test migrations\n+ runs-on: ubuntu-latest\n+ timeout-minutes: 60\n+\n+ services:\n+ postgres:\n+ image: postgres:15-alpine\n+ env:\n+ POSTGRES_DB: django\n+ POSTGRES_USER: user\n+ POSTGRES_PASSWORD: postgres\n+ ports:\n+ - 5432:5432\n+ options: >-\n+ --health-cmd pg_isready\n+ --health-interval 10s\n+ --health-timeout 5s\n+ --health-retries 5\n+\n+ steps:\n+ - name: Checkout\n+ uses: actions/checkout@v6\n+ with:\n+ persist-credentials: false\n+\n+ - name: Set up Python\n+ uses: actions/setup-python@v6\n+ with:\n+ python-version: '3.14'\n+ cache: 'pip'\n+ cache-dependency-path: 'tests/requirements/py3.txt'\n+\n+ - name: Install dependencies\n+ run: |\n+ python -m pip install --upgrade pip wheel\n+ python -m pip install -e . psycopg[binary]\n+\n+ - name: [NAME_REDACTED] settings file\n+ run: mv ./.github/workflows/data/test_postgres.py.tpl ./tests/test_postgres.py\n+\n+ - name: Check for missing migrations\n+ env:\n+ DJANGO_SETTINGS_MODULE: test_postgres\n+ PYTHONPATH: ${{ github.workspace }}/tests:${{ github.workspace }}\n+ run: |\n+ python scripts/check_migrations.py" }, { "filename": "scripts/check_migrations.py", "status": "added", "additions": 31, "deletions": 0, "changes": 31, "patch": "@@ -0,0 +1,31 @@\n+import sys\n+from pathlib import Path\n+\n+\n+def main():\n+ repo_root = Path(__file__).resolve().parent.parent\n+ sys.path[:0] = [str(repo_root / \"tests\"), str(repo_root)]\n+\n+ from runtests import ALWAYS_INSTALLED_APPS, get_apps_to_install, get_test_modules\n+\n+ import django\n+ from django.apps import apps\n+ from django.core.management import call_command\n+\n+ django.setup()\n+\n+ test_modules = list(get_test_modules(gis_enabled=False))\n+ installed_apps = list(ALWAYS_INSTALLED_APPS)\n+ for app in get_apps_to_install(test_modules):\n+ # Check against the list to prevent duplicate errors.\n+ if app not in installed_apps:\n+ installed_apps.append(app)\n+ apps.set_installed_apps(installed_apps)\n+\n+ # Note: We don't use check=True here because --check calls sys.exit(1)\n+ # instead of raising CommandError when migrations are missing.\n+ call_command(\"makemigrations\", \"--check\", verbosity=3)\n+\n+\n+if __name__ == \"__main__\":\n+ main()" }, { "filename": "tests/db_functions/migrations/0002_create_test_models.py", "status": "modified", "additions": 72, "deletions": 0, "changes": 72, "patch": "@@ -10,6 +10,15 @@ class Migration(migrations.Migration):\n migrations.CreateModel(\n name=\"Author\",\n fields=[\n+ (\n+ \"id\",\n+ models.BigAutoField(\n+ auto_created=True,\n+ primary_key=True,\n+ serialize=False,\n+ verbose_name=\"ID\",\n+ ),\n+ ),\n (\"name\", models.CharField(max_length=50)),\n (\"alias\", models.CharField(max_length=50, null=True, blank=True)),\n (\"goes_by\", models.CharField(max_length=50, null=True, blank=True)),\n@@ -19,6 +28,15 @@ class Migration(migrations.Migration):\n migrations.CreateModel(\n name=\"Article\",\n fields=[\n+ (\n+ \"id\",\n+ models.BigAutoField(\n+ auto_created=True,\n+ primary_key=True,\n+ serialize=False,\n+ verbose_name=\"ID\",\n+ ),\n+ ),\n (\n \"authors\",\n models.ManyToManyField(\n@@ -37,6 +55,15 @@ class Migration(migrations.Migration):\n migrations.CreateModel(\n name=\"Fan\",\n fields=[\n+ (\n+ \"id\",\n+ models.BigAutoField(\n+ auto_created=True,\n+ primary_key=True,\n+ serialize=False,\n+ verbose_name=\"ID\",\n+ ),\n+ ),\n (\"name\", models.CharField(max_length=50)),\n (\"age\", models.PositiveSmallIntegerField(default=30)),\n (\n@@ -51,6 +78,15 @@ class Migration(migrations.Migration):\n migrations.CreateModel(\n name=\"DTModel\",\n fields=[\n+ (\n+ \"id\",\n+ models.BigAutoField(\n+ auto_created=True,\n+ primary_key=True,\n+ serialize=False,\n+ verbose_name=\"ID\",\n+ ),\n+ ),\n (\"name\", models.CharField(max_length=32)),\n (\"start_datetime\", models.DateTimeField(null=True, blank=True)),\n (\"end_datetime\", models.DateTimeField(null=True, blank=True)),\n@@ -64,6 +100,15 @@ class Migration(migrations.Migration):\n migrations.CreateModel(\n name=\"DecimalModel\",\n fields=[\n+ (\n+ \"id\",\n+ models.BigAutoField(\n+ auto_created=True,\n+ primary_key=True,\n+ serialize=False,\n+ verbose_name=\"ID\",\n+ ),\n+ ),\n (\"n1\", models.DecimalField(decimal_places=2, max_digits=6)),\n (\n \"n2\",\n@@ -76,6 +121,15 @@ class Migration(migrations.Migration):\n migrations.CreateModel(\n name=\"IntegerModel\",\n fields=[\n+ (\n+ \"id\",\n+ models.BigAutoField(\n+ auto_created=True,\n+ primary_key=True,\n+ serialize=False,\n+ verbose_name=\"ID\",\n+ ),\n+ ),\n (\"big\", models.BigIntegerField(null=True, blank=True)),\n (\"normal\", models.IntegerField(null=True, blank=True)),\n (\"small\", models.SmallIntegerField(null=True, blank=True)),\n@@ -84,13 +138,31 @@ class Migration(migrations.Migration):\n migrations.CreateModel(\n name=\"FloatModel\",\n fields=[\n+ (\n+ \"id\",\n+ models.BigAutoField(\n+ auto_created=True,\n+ primary_key=True,\n+ serialize=False,\n+ verbose_name=\"ID\",\n+ ),\n+ ),\n (\"f1\", models.FloatField(null=True, blank=True)),\n (\"f2\", models.FloatField(null=True, blank=True)),\n ],\n ),\n migrations.CreateModel(\n name=\"UUIDModel\",\n fields=[\n+ (\n+ \"id\",\n+ models.BigAutoField(\n+ auto_created=True,\n+ primary_key=True,\n+ serialize=False,\n+ verbose_name=\"ID\",\n+ ),\n+ ),\n (\"uuid\", models.UUIDField(null=True)),\n (\"shift\", models.DurationField(null=True)),\n ]," }, { "filename": "tests/gis_tests/rasterapp/migrations/0002_rastermodels.py", "status": "modified", "additions": 2, "deletions": 2, "changes": 4, "patch": "@@ -14,7 +14,7 @@ class Migration(migrations.Migration):\n fields=[\n (\n \"id\",\n- models.AutoField(\n+ models.BigAutoField(\n auto_created=True,\n primary_key=True,\n serialize=False,\n@@ -49,7 +49,7 @@ class Migration(migrations.Migration):\n fields=[\n (\n \"id\",\n- models.AutoField(\n+ models.BigAutoField(\n auto_created=True,\n primary_key=True,\n serialize=False," }, { "filename": "tests/migration_test_data_persistence/migrations/0002_add_book.py", "status": "modified", "additions": 26, "deletions": 1, "changes": 27, "patch": "@@ -1,4 +1,4 @@\n-from django.db import migrations\n+from django.db import migrations, models\n \n \n def add_book(apps, schema_editor):\n@@ -16,4 +16,29 @@ class Migration(migrations.Migration):\n migrations.RunPython(\n add_book,\n ),\n+ migrations.CreateModel(\n+ name=\"Unmanaged\",\n+ fields=[\n+ (\n+ \"id\",\n+ models.BigAutoField(\n+ auto_created=True,\n+ primary_key=True,\n+ serialize=False,\n+ verbose_name=\"ID\",\n+ ),\n+ ),\n+ (\"title\", models.CharField(max_length=100)),\n+ ],\n+ options={\n+ \"managed\": False,\n+ },\n+ ),\n+ migrations.AlterField(\n+ model_name=\"book\",\n+ name=\"id\",\n+ field=models.BigAutoField(\n+ auto_created=True, primary_key=True, serialize=False, verbose_name=\"ID\"\n+ ),\n+ ),\n ]" }, { "filename": "tests/postgres_tests/migrations/0002_create_test_models.py", "status": "modified", "additions": 2, "deletions": 2, "changes": 4, "patch": "@@ -108,7 +108,7 @@ class Migration(migrations.Migration):\n (\"tags\", ArrayField(TagField(), blank=True, null=True)),\n (\n \"json\",\n- ArrayField(models.JSONField(default=dict), default=list),\n+ ArrayField(models.JSONField(default=dict), default=list, null=True),\n ),\n (\"int_ranges\", ArrayField(IntegerRangeField(), null=True, blank=True)),\n (\n@@ -179,7 +179,7 @@ class Migration(migrations.Migration):\n ),\n (\n \"field\",\n- ArrayField(models.FloatField(), size=2, null=True, blank=True),\n+ ArrayField(models.FloatField(), size=3),\n ),\n ],\n options={" }, { "filename": "tests/sites_framework/migrations/0001_initial.py", "status": "modified", "additions": 28, "deletions": 9, "changes": 37, "patch": "@@ -1,3 +1,5 @@\n+import django.contrib.sites.managers\n+import django.db.models.manager\n from django.db import migrations, models\n \n \n@@ -12,11 +14,11 @@ class Migration(migrations.Migration):\n fields=[\n (\n \"id\",\n- models.AutoField(\n- verbose_name=\"ID\",\n- serialize=False,\n+ models.BigAutoField(\n auto_created=True,\n primary_key=True,\n+ serialize=False,\n+ verbose_name=\"ID\",\n ),\n ),\n (\"title\", models.CharField(max_length=50)),\n@@ -28,18 +30,27 @@ class Migration(migrations.Migration):\n options={\n \"abstract\": False,\n },\n+ managers=[\n+ (\"objects\", django.db.models.manager.Manager()),\n+ (\n+ \"on_site\",\n+ django.contrib.sites.managers.CurrentSiteManager(\n+ \"places_this_article_should_appear\"\n+ ),\n+ ),\n+ ],\n bases=(models.Model,),\n ),\n migrations.CreateModel(\n name=\"ExclusiveArticle\",\n fields=[\n (\n \"id\",\n- models.AutoField(\n- verbose_name=\"ID\",\n- serialize=False,\n+ models.BigAutoField(\n auto_created=True,\n primary_key=True,\n+ serialize=False,\n+ verbose_name=\"ID\",\n ),\n ),\n (\"title\", models.CharField(max_length=50)),\n@@ -48,18 +59,22 @@ class Migration(migrations.Migration):\n options={\n \"abstract\": False,\n },\n+ managers=[\n+ (\"objects\", django.db.models.manager.Manager()),\n+ (\"on_site\", django.contrib.sites.managers.CurrentSiteManager()),\n+ ],\n bases=(models.Model,),\n ),\n migrations.CreateModel(\n name=\"SyndicatedArticle\",\n fields=[\n (\n \"id\",\n- models.AutoField(\n- verbose_name=\"ID\",\n- serialize=False,\n+ models.BigAutoField(\n auto_created=True,\n primary_key=True,\n+ serialize=False,\n+ verbose_name=\"ID\",\n ),\n ),\n (\"title\", models.CharField(max_length=50)),\n@@ -68,6 +83,10 @@ class Migration(migrations.Migration):\n options={\n \"abstract\": False,\n },\n+ managers=[\n+ (\"objects\", django.db.models.manager.Manager()),\n+ (\"on_site\", django.contrib.sites.managers.CurrentSiteManager()),\n+ ],\n bases=(models.Model,),\n ),\n ]" } ], "reviews": [ { "id": 3645577269, "user": "user_3a67c55598c5", "state": "COMMENTED", "body": "Thanks, this looks promising. I have initial comments.", "submitted_at": "2026-01-09T21:11:29+00:00" }, { "id": 3646860418, "user": "user_f5eee7dbaa84", "state": "COMMENTED", "body": null, "submitted_at": "2026-01-10T13:40:13+00:00" }, { "id": 3651315968, "user": "user_3a67c55598c5", "state": "COMMENTED", "body": "Thanks for the updates 👍", "submitted_at": "2026-01-12T15:41:05+00:00" }, { "id": 3674283464, "user": "user_f5eee7dbaa84", "state": "COMMENTED", "body": null, "submitted_at": "2026-01-17T17:23:20+00:00" }, { "id": 3674284497, "user": "user_f5eee7dbaa84", "state": "COMMENTED", "body": null, "submitted_at": "2026-01-17T17:26:16+00:00" }, { "id": 3678239542, "user": "user_3a67c55598c5", "state": "COMMENTED", "body": "Thanks for the updates, almost there 👍", "submitted_at": "2026-01-19T14:03:12+00:00" }, { "id": 3678246721, "user": "user_3a67c55598c5", "state": "COMMENTED", "body": null, "submitted_at": "2026-01-19T14:04:20+00:00" }, { "id": 3678265608, "user": "user_3a67c55598c5", "state": "COMMENTED", "body": null, "submitted_at": "2026-01-19T14:08:34+00:00" }, { "id": 3678858297, "user": "user_3a67c55598c5", "state": "COMMENTED", "body": null, "submitted_at": "2026-01-19T16:29:53+00:00" }, { "id": 3678887213, "user": "user_f5eee7dbaa84", "state": "COMMENTED", "body": null, "submitted_at": "2026-01-19T16:34:22+00:00" }, { "id": 3678983345, "user": "user_3a67c55598c5", "state": "COMMENTED", "body": null, "submitted_at": "2026-01-19T16:51:44+00:00" }, { "id": 3679033503, "user": "user_f5eee7dbaa84", "state": "COMMENTED", "body": null, "submitted_at": "2026-01-19T17:06:47+00:00" }, { "id": 3679119472, "user": "user_3a67c55598c5", "state": "APPROVED", "body": "Thanks, great work!", "submitted_at": "2026-01-19T17:41:36+00:00" } ], "review_comments": [ { "id": 2677627654, "user": "user_3a67c55598c5", "body": "It would be nice to find a solution that didn't depend on executing the script from a different working directory.", "path": ".github/workflows/check-migrations.yml", "line": null, "side": "RIGHT", "created_at": "2026-01-09T21:07:46+00:00" }, { "id": 2677628618, "user": "user_3a67c55598c5", "body": "You can bump to 3.14", "path": ".github/workflows/check-migrations.yml", "line": null, "side": "RIGHT", "created_at": "2026-01-09T21:08:11+00:00" }, { "id": 2677628877, "user": "user_3a67c55598c5", "body": "and v6", "path": ".github/workflows/check-migrations.yml", "line": null, "side": "RIGHT", "created_at": "2026-01-09T21:08:18+00:00" }, { "id": 2678663999, "user": "user_f5eee7dbaa84", "body": "Thankyou for the review , changes are done. Ready for another review .", "path": ".github/workflows/check-migrations.yml", "line": null, "side": "RIGHT", "created_at": "2026-01-10T13:40:13+00:00" }, { "id": 2682732352, "user": "user_3a67c55598c5", "body": "Since these are tests, instead of adding new migration files, you can just edit the prior migrations.", "path": "tests/sites_framework/migrations/0002_alter_customarticle_managers_and_more.py", "line": null, "side": "RIGHT", "created_at": "2026-01-12T15:19:39+00:00" }, { "id": 2682735505, "user": "user_3a67c55598c5", "body": "Ensure there's a blank line at the end.", "path": ".github/workflows/check-migrations.yml", "line": null, "side": "RIGHT", "created_at": "2026-01-12T15:20:23+00:00" }, { "id": 2682742169, "user": "user_3a67c55598c5", "body": "Do we need to run this with `--settings=test_postgres` to be able to lint the tests under `postgres_tests`? There are other workflows that do this.", "path": ".github/workflows/check-migrations.yml", "line": null, "side": "RIGHT", "created_at": "2026-01-12T15:21:38+00:00" }, { "id": 2682747572, "user": "user_3a67c55598c5", "body": "Can you tell me how you reached the decision to add this? Would be nice to keep the workflow minimal.", "path": ".github/workflows/check-migrations.yml", "line": null, "side": "RIGHT", "created_at": "2026-01-12T15:22:44+00:00" }, { "id": 2682749924, "user": "user_3a67c55598c5", "body": "We don't generally upgrade setuptools, see 42758f882dc74059c562ef8ae3da01fd06cf0e0d.", "path": ".github/workflows/check-migrations.yml", "line": null, "side": "RIGHT", "created_at": "2026-01-12T15:23:15+00:00" }, { "id": 2682755885, "user": "user_3a67c55598c5", "body": "This is a little too strict, would miss `tests/content_types/operations_migrations/**`.", "path": ".github/workflows/check-migrations.yml", "line": 7, "side": "RIGHT", "created_at": "2026-01-12T15:24:39+00:00" }, { "id": 2682775826, "user": "user_3a67c55598c5", "body": "Running this locally I got unexpected success because the database was `django.db.backends.dummy`.", "path": "scripts/check_migrations.py", "line": null, "side": "RIGHT", "created_at": "2026-01-12T15:29:37+00:00" }, { "id": 2682823278, "user": "user_3a67c55598c5", "body": "I wouldn't catch any exceptions.", "path": "scripts/check_migrations.py", "line": null, "side": "RIGHT", "created_at": "2026-01-12T15:40:17+00:00" }, { "id": 2682825236, "user": "user_3a67c55598c5", "body": "I'd add a comment that the reason we aren't using `check=True` is that `--check` directly calls `sys.exit(1)` instead of raising `CommandError`, which was a little unintuitive for me.", "path": "scripts/check_migrations.py", "line": null, "side": "RIGHT", "created_at": "2026-01-12T15:40:48+00:00" }, { "id": 2701294508, "user": "user_f5eee7dbaa84", "body": "Done , I've added the migrations to use PostgreSQL settings , will use postgres to test out the migrations as well.", "path": ".github/workflows/check-migrations.yml", "line": null, "side": "RIGHT", "created_at": "2026-01-17T17:23:20+00:00" }, { "id": 2701295971, "user": "user_f5eee7dbaa84", "body": "I removed some dependencies that were significantly increasing build time, such as C-extension wheels, which are unnecessary for migration checks.\n\nI've removed the filtering now , using all dependencies .", "path": ".github/workflows/check-migrations.yml", "line": null, "side": "RIGHT", "created_at": "2026-01-17T17:26:15+00:00" }, { "id": 2704899086, "user": "user_3a67c55598c5", "body": "I think we should run with `gis_enabled=True`, as I have several more failures:\n\n```py\nMigrations for 'gis_migrations':\n tests/gis_tests/gis_migrations/migrations/0003_remove_household_family_delete_heatmap_and_more.py\n - Remove field family from household\n - Delete model Heatmap\n - Remove field neighborhood from household\n - Delete model Family\n - Delete model Household\n - Delete model [NAME_REDACTED] for 'rasterapp':\n tests/gis_tests/rasterapp/migrations/0003_alter_rastermodel_id_alter_rasterrelatedmodel_id.py\n ~ Alter field id on rastermodel\n ~ Alter field id on rasterrelatedmodel\n```\n\nYou could borrow the CI config in the `postgis.yml`.", "path": "scripts/check_migrations.py", "line": 17, "side": "RIGHT", "created_at": "2026-01-19T14:02:54+00:00" }, { "id": 2704904951, "user": "user_3a67c55598c5", "body": "verbosity=3 would be a nice convenience, so that when this fails on CI you don't have to re-run it manually to get the changes.", "path": "scripts/check_migrations.py", "line": null, "side": "RIGHT", "created_at": "2026-01-19T14:04:20+00:00" }, { "id": 2704922159, "user": "user_3a67c55598c5", "body": "Ah, well, on second look it looks like for the `gis_migrations` case there might be too much variance between GIS backends, plus the dynamic way the tests in `test_operations.py` are written. So maybe it's okay to leave this as is.\n\nWe could still fold in the fixes for `rasterapp`, though? 🤔", "path": "scripts/check_migrations.py", "line": 17, "side": "RIGHT", "created_at": "2026-01-19T14:08:33+00:00" }, { "id": 2705421314, "user": "user_3a67c55598c5", "body": "Looks like we can't do this, see https://github.com/[USER_REDACTED]ngo/django/pull/20466#discussion_r2704922159.", "path": "scripts/check_migrations.py", "line": null, "side": "RIGHT", "created_at": "2026-01-19T16:29:53+00:00" }, { "id": 2705445137, "user": "user_f5eee7dbaa84", "body": "Yes , I was trying if this is possible . Migrations can be fixed by adding \n\n```\n\nif connection.features.supports_raster:\n ops.insert(1, migrations.DeleteModel(name=\"Heatmap\"))\n\n```\n\nas Heatmap has \"supports_raster\" in 0002 migration file \nand changing a test case (checking the deleted model) . \n\nShould I add this or let ``` gis_enabled = False ``` ?", "path": "scripts/check_migrations.py", "line": null, "side": "RIGHT", "created_at": "2026-01-19T16:34:22+00:00" }, { "id": 2705526307, "user": "user_3a67c55598c5", "body": "Can you tell me a little more about that idea? My understanding was that we don't have a python model for `Neighborhood` anywhere, so I would expect the `makemigrations --check` to be a poor fit for that test paradigm.", "path": "scripts/check_migrations.py", "line": null, "side": "RIGHT", "created_at": "2026-01-19T16:51:44+00:00" }, { "id": 2705568329, "user": "user_f5eee7dbaa84", "body": "Oh, my bad , Got it ! I've removed gis tests entirely . Thankyou for clarity .", "path": "scripts/check_migrations.py", "line": null, "side": "RIGHT", "created_at": "2026-01-19T17:06:47+00:00" } ], "meta": { "languages": [ "py", "yml" ], "touches_tests": true, "review_state_summary": { "COMMENTED": 12, "APPROVED": 1 }, "meaningful_comment_count": 21, "has_approval": true, "has_changes_requested": false, "total_review_comments": 22 } } { "_id": "bbbf43ef7c0ed4da", "_schema_version": "1.0", "_cleaned_at": "2026-02-12T07:46:51.562181+00:00", "repo": "django/django", "repo_url": "https://github.com/django/django", "license_name": "BSD 3-Clause \"New\" or \"Revised\" License", "license_spdx": "BSD-3-Clause", "pr_number": 20462, "title": "Fixed #36827 -- Added support for exclusion constraints using Hash indexes on PostgreSQL.", "body": "#### Trac ticket number\n\nticket-36827\n\n#### Branch description\n\nAdd support for Hash index type for `ExclusionConstraint` in PostgreSQL.\n\n#### Checklist\n- [x] This PR targets the `main` branch.\n- [x] The commit message is written in past tense, mentions the ticket number, and ends with a period.\n- [x] I have checked the \"Has patch\" ticket flag in the Trac system.\n- [x] I have added or updated relevant tests.\n- [x] I have added or updated relevant docs, including release notes if applicable.\n- [x] I have attached screenshots in both light and dark modes for any UI changes.", "author": "user_d2d82edb4e7b", "created_at": "2025-12-25T09:51:57+00:00", "merged_at": "2026-01-10T07:45:14+00:00", "base_branch": "main", "head_branch": "hash-exclusion-constraint", "additions": 115, "deletions": 7, "changed_files": 4, "files": [ { "filename": "django/contrib/postgres/constraints.py", "status": "modified", "additions": 21, "deletions": 2, "changes": 23, "patch": "@@ -9,6 +9,7 @@\n from django.db.models.lookups import PostgresOperatorLookup\n from django.db.models.sql import Query\n \n+from .fields import RangeOperators\n from .utils import CheckPostgresInstalledMixin\n \n __all__ = [\"ExclusionConstraint\"]\n@@ -36,9 +37,9 @@ def __init__(\n violation_error_code=None,\n violation_error_message=None,\n ):\n- if index_type and index_type.lower() not in {\"gist\", \"spgist\"}:\n+ if index_type and index_type.lower() not in {\"gist\", \"hash\", \"spgist\"}:\n raise ValueError(\n- \"Exclusion constraints only support GiST or SP-GiST indexes.\"\n+ \"Exclusion constraints only support GiST, Hash, or SP-GiST indexes.\"\n )\n if not expressions:\n raise ValueError(\n@@ -57,6 +58,24 @@ def __init__(\n )\n if not isinstance(include, (NoneType, list, tuple)):\n raise ValueError(\"ExclusionConstraint.include must be a list or tuple.\")\n+ if index_type and index_type.lower() == \"hash\":\n+ if include:\n+ raise ValueError(\n+ \"Covering exclusion constraints using Hash indexes are not \"\n+ \"supported.\"\n+ )\n+ if not expressions:\n+ pass\n+ elif len(expressions) > 1:\n+ raise ValueError(\n+ \"Composite exclusion constraints using Hash indexes are not \"\n+ \"supported.\"\n+ )\n+ elif expressions[0][1] != RangeOperators.EQUAL:\n+ raise ValueError(\n+ \"Exclusion constraints using Hash indexes only support the EQUAL \"\n+ \"operator.\"\n+ )\n self.expressions = expressions\n self.index_type = index_type or \"GIST\"\n self.condition = condition" }, { "filename": "docs/ref/contrib/postgres/constraints.txt", "status": "modified", "additions": 7, "deletions": 3, "changes": 10, "patch": "@@ -73,9 +73,13 @@ creates an exclusion constraint on ``circle`` using ``circle_ops``.\n \n .. attribute:: ExclusionConstraint.index_type\n \n-The index type of the constraint. Accepted values are ``GIST`` or ``SPGIST``.\n-Matching is case insensitive. If not provided, the default index type is\n-``GIST``.\n+The index type of the constraint. Accepted values are ``GiST``, ``Hash``, or\n+``SPGiST``. Matching is case insensitive. If not provided, the default index\n+type is ``GIST``.\n+\n+.. versionchanged:: 6.1\n+\n+ Support for exclusion constraints using Hash indexes was added.\n \n ``condition``\n -------------" }, { "filename": "docs/releases/6.1.txt", "status": "modified", "additions": 3, "deletions": 0, "changes": 3, "patch": "@@ -135,6 +135,9 @@ Minor features\n :class:`~django.contrib.postgres.fields.HStoreField` when ``psycopg`` 3.2+ is\n installed and ``django.contrib.postgres`` is in :setting:`INSTALLED_APPS`.\n \n+* :class:`~django.contrib.postgres.constraints.ExclusionConstraint` now\n+ supports the Hash index type.\n+\n :mod:`django.contrib.redirects`\n ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~" }, { "filename": "tests/postgres_tests/test_constraints.py", "status": "modified", "additions": 84, "deletions": 2, "changes": 86, "patch": "@@ -27,7 +27,13 @@\n from django.utils import timezone\n \n from . import PostgreSQLTestCase\n-from .models import HotelReservation, IntegerArrayModel, RangesModel, Room, Scene\n+from .models import (\n+ HotelReservation,\n+ IntegerArrayModel,\n+ RangesModel,\n+ Room,\n+ Scene,\n+)\n \n try:\n from django.contrib.postgres.constraints import ExclusionConstraint\n@@ -299,7 +305,7 @@ def test_invalid_condition(self):\n )\n \n def test_invalid_index_type(self):\n- msg = \"Exclusion constraints only support GiST or SP-GiST indexes.\"\n+ msg = \"Exclusion constraints only support GiST, Hash, or SP-GiST indexes.\"\n with self.assertRaisesMessage(ValueError, msg):\n ExclusionConstraint(\n index_type=\"gin\",\n@@ -480,6 +486,18 @@ def test_repr(self):\n \"(F(datespan), '-|-')] name='exclude_overlapping' \"\n \"violation_error_code='overlapping_must_be_excluded'>\",\n )\n+ constraint = ExclusionConstraint(\n+ name=\"exclude_equal_hash\",\n+ index_type=\"hash\",\n+ expressions=[(F(\"room\"), RangeOperators.EQUAL)],\n+ violation_error_code=\"room_must_be_unique\",\n+ )\n+ self.assertEqual(\n+ repr(constraint),\n+ \"\",\n+ )\n \n def test_eq(self):\n constraint_1 = ExclusionConstraint(\n@@ -581,6 +599,12 @@ def test_eq(self):\n violation_error_code=\"custom_code\",\n violation_error_message=\"other custom error\",\n )\n+ constraint_13 = ExclusionConstraint(\n+ name=\"exclude_equal_hash\",\n+ index_type=\"hash\",\n+ expressions=[(F(\"room\"), RangeOperators.EQUAL)],\n+ violation_error_code=\"room_must_be_unique\",\n+ )\n self.assertEqual(constraint_1, constraint_1)\n self.assertEqual(constraint_1, mock.ANY)\n self.assertNotEqual(constraint_1, constraint_2)\n@@ -597,8 +621,10 @@ def test_eq(self):\n self.assertNotEqual(constraint_1, object())\n self.assertNotEqual(constraint_10, constraint_11)\n self.assertNotEqual(constraint_11, constraint_12)\n+ self.assertNotEqual(constraint_12, constraint_13)\n self.assertEqual(constraint_10, constraint_10)\n self.assertEqual(constraint_12, constraint_12)\n+ self.assertEqual(constraint_13, constraint_13)\n \n def test_deconstruct(self):\n constraint = ExclusionConstraint(\n@@ -1256,6 +1282,26 @@ def test_range_equal_cast(self):\n editor.add_constraint(Room, constraint)\n self.assertIn(constraint_name, self.get_constraints(Room._meta.db_table))\n \n+ def test_hash_uniqueness(self):\n+ constraint_name = \"exclusion_equal_room_hash\"\n+ self.assertNotIn(constraint_name, self.get_constraints(Room._meta.db_table))\n+ constraint = ExclusionConstraint(\n+ name=constraint_name,\n+ index_type=\"hash\",\n+ expressions=[(F(\"number\"), RangeOperators.EQUAL)],\n+ )\n+ with connection.schema_editor() as editor:\n+ editor.add_constraint(Room, constraint)\n+ self.assertIn(constraint_name, self.get_constraints(Room._meta.db_table))\n+ Room.objects.create(number=101)\n+ with self.assertRaises(IntegrityError), transaction.atomic():\n+ Room.objects.create(number=101)\n+ Room.objects.create(number=102)\n+ # Drop the constraint.\n+ with connection.schema_editor() as editor:\n+ editor.remove_constraint(Room, constraint)\n+ self.assertNotIn(constraint.name, self.get_constraints(Room._meta.db_table))\n+\n [USER_REDACTED]_apps(\"postgres_tests\")\n def test_table_create(self):\n constraint_name = \"exclusion_equal_number_tc\"\n@@ -1287,3 +1333,39 @@ def test_database_default(self):\n msg = \"Constraint “ints_equal” is violated.\"\n with self.assertRaisesMessage(ValidationError, msg):\n constraint.validate(RangesModel, RangesModel())\n+\n+ def test_covering_hash_index_not_supported(self):\n+ constraint_name = \"covering_hash_index_not_supported\"\n+ msg = \"Covering exclusion constraints using Hash indexes are not supported.\"\n+ with self.assertRaisesMessage(ValueError, msg):\n+ ExclusionConstraint(\n+ name=constraint_name,\n+ expressions=[(\"int1\", RangeOperators.EQUAL)],\n+ index_type=\"hash\",\n+ include=[\"int2\"],\n+ )\n+\n+ def test_composite_hash_index_not_supported(self):\n+ constraint_name = \"composite_hash_index_not_supported\"\n+ msg = \"Composite exclusion constraints using Hash indexes are not supported.\"\n+ with self.assertRaisesMessage(ValueError, msg):\n+ ExclusionConstraint(\n+ name=constraint_name,\n+ expressions=[\n+ (\"int1\", RangeOperators.EQUAL),\n+ (\"int2\", RangeOperators.EQUAL),\n+ ],\n+ index_type=\"hash\",\n+ )\n+\n+ def test_non_equal_hash_index_not_supported(self):\n+ constraint_name = \"none_equal_hash_index_not_supported\"\n+ msg = (\n+ \"Exclusion constraints using Hash indexes only support the EQUAL operator.\"\n+ )\n+ with self.assertRaisesMessage(ValueError, msg):\n+ ExclusionConstraint(\n+ name=constraint_name,\n+ expressions=[(\"int1\", RangeOperators.NOT_EQUAL)],\n+ index_type=\"hash\",\n+ )" } ], "reviews": [ { "id": 3612147699, "user": "user_057de2f3b132", "state": "APPROVED", "body": null, "submitted_at": "2025-12-25T11:08:54+00:00" }, { "id": 3612446330, "user": "user_cdda8932ec17", "state": "COMMENTED", "body": "Looking at c2f6c05c4cc73e831b7e852eb58bd6d7a83fa46c which added SP-GiST support the only part that might have been missing here was to confirm that `main` which is Postgres 15+ supports it with all options.\n\nVanilla support [is oviously the case](https://dbfiddle.uk/Rp5Vk5XG) as `HashIndex` has been around forever (Django 2.2) so this was most likely an omission when we added `ExclusionConstraint` but [it's not the case](https://dbfiddle.uk/OunMZxrA) for covering indices (see `include` option) which we'll need to add a check for [like we use to do](https://github.com/[USER_REDACTED]ngo/django/commit/b049bec7cfe9b5854584d240addb44fa1e9375a5#diff-a4e33792faf48c1d998ea65d49b65a6ab695efad8c2b74891180e055342e92eeL117-L141) and [tested](https://github.com/[USER_REDACTED]ngo/django/commit/b049bec7cfe9b5854584d240addb44fa1e9375a5#diff-9bcfdc1360b06330a51e54b7565748f9ef23685b7ac2983d7b390bd93e7f71e1L1087-L1107) before we dropped support for Postgres 14.", "submitted_at": "2025-12-25T15:51:43+00:00" }, { "id": 3616830557, "user": "user_8fc305198eb3", "state": "COMMENTED", "body": null, "submitted_at": "2025-12-29T22:10:26+00:00" }, { "id": 3617556076, "user": "user_d2d82edb4e7b", "state": "COMMENTED", "body": null, "submitted_at": "2025-12-30T08:26:49+00:00" }, { "id": 3625013881, "user": "user_5501cd6d3dc8", "state": "COMMENTED", "body": null, "submitted_at": "2026-01-04T13:44:01+00:00" }, { "id": 3625177604, "user": "user_8fc305198eb3", "state": "COMMENTED", "body": null, "submitted_at": "2026-01-04T21:22:55+00:00" }, { "id": 3627026675, "user": "user_d2d82edb4e7b", "state": "COMMENTED", "body": null, "submitted_at": "2026-01-05T14:13:58+00:00" }, { "id": 3636152473, "user": "user_5501cd6d3dc8", "state": "COMMENTED", "body": null, "submitted_at": "2026-01-07T18:02:35+00:00" }, { "id": 3636525682, "user": "user_3a67c55598c5", "state": "COMMENTED", "body": null, "submitted_at": "2026-01-07T19:42:43+00:00" }, { "id": 3639527243, "user": "user_c332d334e171", "state": "COMMENTED", "body": null, "submitted_at": "2026-01-08T14:09:41+00:00" }, { "id": 3639789010, "user": "user_c332d334e171", "state": "COMMENTED", "body": null, "submitted_at": "2026-01-08T14:53:29+00:00" }, { "id": 3646518054, "user": "user_5501cd6d3dc8", "state": "APPROVED", "body": "[USER_REDACTED] Thanks :+1: I pushed tiny final edits.", "submitted_at": "2026-01-10T07:09:23+00:00" } ], "review_comments": [ { "id": 2646872137, "user": "user_057de2f3b132", "body": "We'll need a `versionadded` or `versionchanged` marker.", "path": "docs/ref/contrib/postgres/constraints.txt", "line": null, "side": "RIGHT", "created_at": "2025-12-25T11:08:18+00:00" }, { "id": 2651856092, "user": "user_8fc305198eb3", "body": "Why not do all of this validation up in `__init__` ? It seems weird to validate the type there, but then delay this extra validation until SQL creation.", "path": "django/contrib/postgres/constraints.py", "line": null, "side": "RIGHT", "created_at": "2025-12-29T22:10:26+00:00" }, { "id": 2652498439, "user": "user_d2d82edb4e7b", "body": "[NAME_REDACTED], I added it like that because this is how it was done before support for PostgreSQL 14 was dropped:\n\nhttps://github.com/[USER_REDACTED]ngo/django/commit/b049bec7cfe9b5854584d240addb44fa1e9375a5#diff-a4e33792faf48c1d998ea65d49b65a6ab695efad8c2b74891180e055342e92eeL117-L141\n\nLooking at other constraints (such as UniqueConstraint) I think the checks in `__init__` are focusing more on types rather then database support or potential runtime errors so I don't this is the right place for these types of checks.\n\nIt seems like these checks are better off as Django checks. See for example similar checks in `UniqueConstraint`:\n\nhttps://github.com/[USER_REDACTED]ngo/django/blob/ccf74f7dc771313b41e7c2912a71f9c5b0ae5e1d/django/db/models/constraints.py#L338\n\nTo recap the options here:\n\n1. No checks (there are currently no checks for the other index types)\n2. Raise `ValueError` in `__init__`\n3. [NAME_REDACTED] checks in `check()` (consistent with other constraints)\n4. Check at runtime when producing the SQL (as it used to be, and how it's currently implemented in this PR)", "path": "django/contrib/postgres/constraints.py", "line": null, "side": "RIGHT", "created_at": "2025-12-30T08:26:49+00:00" }, { "id": 2659676600, "user": "user_5501cd6d3dc8", "body": "I'd prefer the 2nd option (`ValueError` in `__init__()`) previous checks were implemented in `check_support()` because they required database connection to check feature flags (`schema_editor.connection`). New checks are not database dependent.", "path": "django/contrib/postgres/constraints.py", "line": null, "side": "RIGHT", "created_at": "2026-01-04T13:44:01+00:00" }, { "id": 2659936676, "user": "user_8fc305198eb3", "body": "Yes, I agree for the same reasoning.", "path": "django/contrib/postgres/constraints.py", "line": null, "side": "RIGHT", "created_at": "2026-01-04T21:22:55+00:00" }, { "id": 2661652476, "user": "user_d2d82edb4e7b", "body": "I've added a commit to move the checks to `__init__.py` as `ValueError` + updated the tests. \n\nLet me know if we are good to go and I'll squash.", "path": "django/contrib/postgres/constraints.py", "line": null, "side": "RIGHT", "created_at": "2026-01-05T14:13:58+00:00" }, { "id": 2669546431, "user": "user_5501cd6d3dc8", "body": "[USER_REDACTED] Thanks for updates :+1: I will move it forward during the weekend.", "path": "django/contrib/postgres/constraints.py", "line": null, "side": "RIGHT", "created_at": "2026-01-07T18:02:35+00:00" }, { "id": 2669846136, "user": "user_3a67c55598c5", "body": "2nd option also aligns with ticket-36813.", "path": "django/contrib/postgres/constraints.py", "line": null, "side": "RIGHT", "created_at": "2026-01-07T19:42:42+00:00" }, { "id": 2672447704, "user": "user_c332d334e171", "body": "```suggestion\n if index_type and index_type.lower() not in {\"gist\", \"hash\", \"spgist\"}:\n```\nI suggest to preserve the alphabetic order for code readability.", "path": "django/contrib/postgres/constraints.py", "line": null, "side": "RIGHT", "created_at": "2026-01-08T13:52:46+00:00" }, { "id": 2672464036, "user": "user_c332d334e171", "body": "```suggestion\n \"Exclusion constraints only support GiST, Hash or SP-GiST indexes.\"\n```", "path": "django/contrib/postgres/constraints.py", "line": null, "side": "RIGHT", "created_at": "2026-01-08T13:57:26+00:00" }, { "id": 2672505252, "user": "user_c332d334e171", "body": "```suggestion\nThe index type of the constraint. Accepted values are ``GiST``, ``Hash`` or\n```", "path": "docs/ref/contrib/postgres/constraints.txt", "line": null, "side": "RIGHT", "created_at": "2026-01-08T14:08:20+00:00" }, { "id": 2672506196, "user": "user_c332d334e171", "body": "```suggestion\n``SP-GiST``. Matching is case insensitive. If not provided, the default index type\n```", "path": "docs/ref/contrib/postgres/constraints.txt", "line": null, "side": "RIGHT", "created_at": "2026-01-08T14:08:35+00:00" }, { "id": 2672507058, "user": "user_c332d334e171", "body": "```suggestion\nis ``GiST``.\n```", "path": "docs/ref/contrib/postgres/constraints.txt", "line": null, "side": "RIGHT", "created_at": "2026-01-08T14:08:50+00:00" }, { "id": 2672673528, "user": "user_c332d334e171", "body": "I think you missed this one with \"SP-GiST\"", "path": "docs/ref/contrib/postgres/constraints.txt", "line": null, "side": "RIGHT", "created_at": "2026-01-08T14:53:29+00:00" } ], "meta": { "languages": [ "py", "txt" ], "touches_tests": true, "review_state_summary": { "APPROVED": 2, "COMMENTED": 10 }, "meaningful_comment_count": 14, "has_approval": true, "has_changes_requested": false, "total_review_comments": 14 } } { "_id": "05ad637b8e872c39", "_schema_version": "1.0", "_cleaned_at": "2026-02-12T07:46:51.577805+00:00", "repo": "django/django", "repo_url": "https://github.com/django/django", "license_name": "BSD 3-Clause \"New\" or \"Revised\" License", "license_spdx": "BSD-3-Clause", "pr_number": 20461, "title": "Fixed #36822 -- Added parameter limit for PostgreSQL with server-side binding.", "body": "#### Trac ticket number\n\n\nticket-36822\n\n#### Branch description\nAdded max_query_params and bulk_batch_size() to the PostgreSQL backend to handle the 65535 parameter limit when using server-side binding with psycopg3. When server_side_binding=True is configured in database OPTIONS, PostgreSQL has a hard limit of 65535 query parameters.\n\n#### Checklist\n- [x] This PR targets the `main` branch. \n- [x] The commit message is written in past tense, mentions the ticket number, and ends with a period.\n- [x] I have checked the \"Has patch\" ticket flag in the Trac system.\n- [x] I have added or updated relevant tests.\n- [ ] I have added or updated relevant docs, including release notes if applicable.\n- [ ] I have attached screenshots in both light and dark modes for any UI changes.", "author": "user_ed8298a0306d", "created_at": "2025-12-25T08:31:58+00:00", "merged_at": "2026-01-16T14:15:53+00:00", "base_branch": "main", "head_branch": "ticket-36822", "additions": 92, "deletions": 95, "changed_files": 9, "files": [ { "filename": "django/db/backends/base/operations.py", "status": "modified", "additions": 13, "deletions": 1, "changes": 14, "patch": "@@ -2,12 +2,14 @@\n import decimal\n import json\n from importlib import import_module\n+from itertools import chain\n \n import sqlparse\n \n from django.conf import settings\n from django.db import NotSupportedError, transaction\n from django.db.models.expressions import Col\n+from django.db.models.fields.composite import CompositePrimaryKey\n from django.utils import timezone\n from django.utils.duration import duration_microseconds\n from django.utils.encoding import force_str\n@@ -78,7 +80,17 @@ def bulk_batch_size(self, fields, objs):\n are the fields going to be inserted in the batch, the objs contains\n all the objects to be inserted.\n \"\"\"\n- return len(objs)\n+ if self.connection.features.max_query_params is None or not fields:\n+ return len(objs)\n+\n+ return self.connection.features.max_query_params // len(\n+ list(\n+ chain.from_iterable(\n+ field.fields if isinstance(field, CompositePrimaryKey) else [field]\n+ for field in fields\n+ )\n+ )\n+ )\n \n def format_for_duration_arithmetic(self, sql):\n raise NotImplementedError(" }, { "filename": "django/db/backends/oracle/operations.py", "status": "modified", "additions": 0, "deletions": 14, "changes": 14, "patch": "@@ -1,15 +1,13 @@\n import datetime\n import uuid\n from functools import lru_cache\n-from itertools import chain\n \n from django.conf import settings\n from django.db import NotSupportedError\n from django.db.backends.base.operations import BaseDatabaseOperations\n from django.db.backends.utils import split_tzname_delta, strip_quotes, truncate_name\n from django.db.models import (\n AutoField,\n- CompositePrimaryKey,\n Exists,\n ExpressionWrapper,\n Lookup,\n@@ -707,18 +705,6 @@ def subtract_temporals(self, internal_type, lhs, rhs):\n )\n return super().subtract_temporals(internal_type, lhs, rhs)\n \n- def bulk_batch_size(self, fields, objs):\n- \"\"\"Oracle restricts the number of parameters in a query.\"\"\"\n- fields = list(\n- chain.from_iterable(\n- field.fields if isinstance(field, CompositePrimaryKey) else [field]\n- for field in fields\n- )\n- )\n- if fields:\n- return self.connection.features.max_query_params // len(fields)\n- return len(objs)\n-\n def conditional_expression_supported_in_where_clause(self, expression):\n \"\"\"\n Oracle supports only EXISTS(...) or filters in the WHERE clause, others" }, { "filename": "django/db/backends/postgresql/features.py", "status": "modified", "additions": 6, "deletions": 0, "changes": 6, "patch": "@@ -151,6 +151,12 @@ def uses_server_side_binding(self):\n options = self.connection.settings_dict[\"OPTIONS\"]\n return is_psycopg3 and options.get(\"server_side_binding\") is True\n \n+ [USER_REDACTED]_property\n+ def max_query_params(self):\n+ if self.uses_server_side_binding:\n+ return 2**16 - 1\n+ return None\n+\n [USER_REDACTED]_property\n def prohibits_null_characters_in_text_exception(self):\n if is_psycopg3:" }, { "filename": "django/db/backends/sqlite3/operations.py", "status": "modified", "additions": 0, "deletions": 20, "changes": 20, "patch": "@@ -29,26 +29,6 @@ class DatabaseOperations(BaseDatabaseOperations):\n # SQLite. Use JSON_TYPE() instead.\n jsonfield_datatype_values = frozenset([\"null\", \"false\", \"true\"])\n \n- def bulk_batch_size(self, fields, objs):\n- \"\"\"\n- SQLite has a variable limit defined by SQLITE_LIMIT_VARIABLE_NUMBER\n- (reflected in max_query_params).\n- \"\"\"\n- fields = list(\n- chain.from_iterable(\n- (\n- field.fields\n- if isinstance(field, models.CompositePrimaryKey)\n- else [field]\n- )\n- for field in fields\n- )\n- )\n- if fields:\n- return self.connection.features.max_query_params // len(fields)\n- else:\n- return len(objs)\n-\n def check_expression_support(self, expression):\n bad_fields = (models.DateField, models.DateTimeField, models.TimeField)\n bad_aggregates = (models.Sum, models.Avg, models.Variance, models.StdDev)" }, { "filename": "tests/backends/base/test_operations.py", "status": "modified", "additions": 52, "deletions": 2, "changes": 54, "patch": "@@ -1,7 +1,7 @@\n import decimal\n \n from django.core.management.color import no_style\n-from django.db import NotSupportedError, connection, transaction\n+from django.db import NotSupportedError, connection, models, transaction\n from django.db.backends.base.operations import BaseDatabaseOperations\n from django.db.models import DurationField\n from django.db.models.expressions import Col\n@@ -11,10 +11,11 @@\n TransactionTestCase,\n override_settings,\n skipIfDBFeature,\n+ skipUnlessDBFeature,\n )\n from django.utils import timezone\n \n-from ..models import Author, Book\n+from ..models import Author, Book, Person\n \n \n class SimpleDatabaseOperationTests(SimpleTestCase):\n@@ -201,6 +202,55 @@ def test_subtract_temporals(self):\n with self.assertRaisesMessage(NotSupportedError, msg):\n self.ops.subtract_temporals(duration_field_internal_type, None, None)\n \n+ [USER_REDACTED](\"max_query_params\")\n+ def test_bulk_batch_size_limited(self):\n+ max_query_params = connection.features.max_query_params\n+ objects = range(max_query_params + 1)\n+ first_name_field = Person._meta.get_field(\"first_name\")\n+ last_name_field = Person._meta.get_field(\"last_name\")\n+ composite_pk = models.CompositePrimaryKey(\"first_name\", \"last_name\")\n+ composite_pk.fields = [first_name_field, last_name_field]\n+\n+ self.assertEqual(connection.ops.bulk_batch_size([], objects), len(objects))\n+ self.assertEqual(\n+ connection.ops.bulk_batch_size([first_name_field], objects),\n+ max_query_params,\n+ )\n+ self.assertEqual(\n+ connection.ops.bulk_batch_size(\n+ [first_name_field, last_name_field], objects\n+ ),\n+ max_query_params // 2,\n+ )\n+ self.assertEqual(\n+ connection.ops.bulk_batch_size([composite_pk, first_name_field], objects),\n+ max_query_params // 3,\n+ )\n+\n+ [USER_REDACTED](\"max_query_params\")\n+ def test_bulk_batch_size_unlimited(self):\n+ objects = range(2**16 + 1)\n+ first_name_field = Person._meta.get_field(\"first_name\")\n+ last_name_field = Person._meta.get_field(\"last_name\")\n+ composite_pk = models.CompositePrimaryKey(\"first_name\", \"last_name\")\n+ composite_pk.fields = [first_name_field, last_name_field]\n+\n+ self.assertEqual(connection.ops.bulk_batch_size([], objects), len(objects))\n+ self.assertEqual(\n+ connection.ops.bulk_batch_size([first_name_field], objects),\n+ len(objects),\n+ )\n+ self.assertEqual(\n+ connection.ops.bulk_batch_size(\n+ [first_name_field, last_name_field], objects\n+ ),\n+ len(objects),\n+ )\n+ self.assertEqual(\n+ connection.ops.bulk_batch_size([composite_pk, first_name_field], objects),\n+ len(objects),\n+ )\n+\n \n class SqlFlushTests(TransactionTestCase):\n available_apps = [\"backends\"]" }, { "filename": "tests/backends/oracle/test_operations.py", "status": "modified", "additions": 1, "deletions": 26, "changes": 27, "patch": "@@ -1,7 +1,7 @@\n import unittest\n \n from django.core.management.color import no_style\n-from django.db import connection, models\n+from django.db import connection\n from django.test import TransactionTestCase\n \n from ..models import Person, Tag\n@@ -17,31 +17,6 @@ def test_sequence_name_truncation(self):\n )\n self.assertEqual(seq_name, \"SCHEMA_AUTHORWITHEVENLOB0B8_SQ\")\n \n- def test_bulk_batch_size(self):\n- # Oracle restricts the number of parameters in a query.\n- objects = range(2**16)\n- self.assertEqual(connection.ops.bulk_batch_size([], objects), len(objects))\n- # Each field is a parameter for each object.\n- first_name_field = Person._meta.get_field(\"first_name\")\n- last_name_field = Person._meta.get_field(\"last_name\")\n- self.assertEqual(\n- connection.ops.bulk_batch_size([first_name_field], objects),\n- connection.features.max_query_params,\n- )\n- self.assertEqual(\n- connection.ops.bulk_batch_size(\n- [first_name_field, last_name_field],\n- objects,\n- ),\n- connection.features.max_query_params // 2,\n- )\n- composite_pk = models.CompositePrimaryKey(\"first_name\", \"last_name\")\n- composite_pk.fields = [first_name_field, last_name_field]\n- self.assertEqual(\n- connection.ops.bulk_batch_size([composite_pk, first_name_field], objects),\n- connection.features.max_query_params // 3,\n- )\n-\n def test_sql_flush(self):\n statements = connection.ops.sql_flush(\n no_style()," }, { "filename": "tests/backends/postgresql/test_features.py", "status": "added", "additions": 14, "deletions": 0, "changes": 14, "patch": "@@ -0,0 +1,14 @@\n+import unittest\n+\n+from django.db import connection\n+from django.test import TestCase\n+\n+\n+[USER_REDACTED].skipUnless(connection.vendor == \"postgresql\", \"PostgreSQL tests\")\n+class FeaturesTests(TestCase):\n+ def test_max_query_params_respects_server_side_params(self):\n+ if connection.features.uses_server_side_binding:\n+ limit = 2**16 - 1\n+ else:\n+ limit = None\n+ self.assertEqual(connection.features.max_query_params, limit)" }, { "filename": "tests/backends/sqlite/test_operations.py", "status": "modified", "additions": 1, "deletions": 24, "changes": 25, "patch": "@@ -2,7 +2,7 @@\n import unittest\n \n from django.core.management.color import no_style\n-from django.db import connection, models\n+from django.db import connection\n from django.test import TestCase\n \n from ..models import Person, Tag\n@@ -88,29 +88,6 @@ def test_sql_flush_sequences_allow_cascade(self):\n statements[-1],\n )\n \n- def test_bulk_batch_size(self):\n- self.assertEqual(connection.ops.bulk_batch_size([], [Person()]), 1)\n- first_name_field = Person._meta.get_field(\"first_name\")\n- last_name_field = Person._meta.get_field(\"last_name\")\n- self.assertEqual(\n- connection.ops.bulk_batch_size([first_name_field], [Person()]),\n- connection.features.max_query_params,\n- )\n- self.assertEqual(\n- connection.ops.bulk_batch_size(\n- [first_name_field, last_name_field], [Person()]\n- ),\n- connection.features.max_query_params // 2,\n- )\n- composite_pk = models.CompositePrimaryKey(\"first_name\", \"last_name\")\n- composite_pk.fields = [first_name_field, last_name_field]\n- self.assertEqual(\n- connection.ops.bulk_batch_size(\n- [composite_pk, first_name_field], [Person()]\n- ),\n- connection.features.max_query_params // 3,\n- )\n-\n def test_bulk_batch_size_respects_variable_limit(self):\n first_name_field = Person._meta.get_field(\"first_name\")\n last_name_field = Person._meta.get_field(\"last_name\")" }, { "filename": "tests/composite_pk/tests.py", "status": "modified", "additions": 5, "deletions": 8, "changes": 13, "patch": "@@ -149,21 +149,18 @@ def test_in_bulk(self):\n \n def test_in_bulk_batching(self):\n Comment.objects.all().delete()\n- batching_required = connection.features.max_query_params is not None\n- expected_queries = 2 if batching_required else 1\n+ num_objects = 10\n+ connection.features.__dict__.pop(\"max_query_params\", None)\n with unittest.mock.patch.object(\n- type(connection.features), \"max_query_params\", 10\n+ type(connection.features), \"max_query_params\", num_objects\n ):\n- num_requiring_batching = (\n- connection.ops.bulk_batch_size([Comment._meta.pk], []) + 1\n- )\n comments = [\n Comment(id=i, tenant=self.tenant, user=self.user)\n- for i in range(1, num_requiring_batching + 1)\n+ for i in range(1, num_objects + 1)\n ]\n Comment.objects.bulk_create(comments)\n id_list = list(Comment.objects.values_list(\"pk\", flat=True))\n- with self.assertNumQueries(expected_queries):\n+ with self.assertNumQueries(2):\n comment_dict = Comment.objects.in_bulk(id_list=id_list)\n self.assertQuerySetEqual(comment_dict, id_list)" } ], "reviews": [ { "id": 3612432316, "user": "user_cdda8932ec17", "state": "COMMENTED", "body": null, "submitted_at": "2025-12-25T15:21:53+00:00" }, { "id": 3613404601, "user": "user_ed8298a0306d", "state": "COMMENTED", "body": null, "submitted_at": "2025-12-26T13:08:49+00:00" }, { "id": 3613407771, "user": "user_ed8298a0306d", "state": "COMMENTED", "body": null, "submitted_at": "2025-12-26T13:10:43+00:00" }, { "id": 3616013459, "user": "user_3a67c55598c5", "state": "COMMENTED", "body": null, "submitted_at": "2025-12-29T14:28:51+00:00" }, { "id": 3618329163, "user": "user_3a67c55598c5", "state": "COMMENTED", "body": null, "submitted_at": "2025-12-30T14:00:01+00:00" }, { "id": 3618381314, "user": "user_ed8298a0306d", "state": "COMMENTED", "body": null, "submitted_at": "2025-12-30T14:19:10+00:00" }, { "id": 3618466773, "user": "user_ed8298a0306d", "state": "COMMENTED", "body": null, "submitted_at": "2025-12-30T14:48:22+00:00" }, { "id": 3618400665, "user": "user_3a67c55598c5", "state": "COMMENTED", "body": "Looking good [USER_REDACTED], I have just a few more things to run by you.", "submitted_at": "2025-12-30T14:51:18+00:00" }, { "id": 3661629196, "user": "user_ed8298a0306d", "state": "COMMENTED", "body": null, "submitted_at": "2026-01-14T16:27:29+00:00" }, { "id": 3665406104, "user": "user_3a67c55598c5", "state": "APPROVED", "body": "Thanks [USER_REDACTED] 👍, this is a nice refactor.", "submitted_at": "2026-01-15T13:41:45+00:00" }, { "id": 3665708951, "user": "user_3a67c55598c5", "state": "COMMENTED", "body": null, "submitted_at": "2026-01-15T13:42:36+00:00" }, { "id": 3665774834, "user": "user_ed8298a0306d", "state": "COMMENTED", "body": null, "submitted_at": "2026-01-15T13:58:02+00:00" } ], "review_comments": [ { "id": 2647115752, "user": "user_cdda8932ec17", "body": "Since the limit is only present when server-side cursors are used we should make this value a `cached_property` that introspects `self.connection.settings_dict[\"OPTIONS\"].get(\"server_side_binding\")` and return this value if its enabled and `None` otherwise.", "path": "django/db/backends/postgresql/features.py", "line": null, "side": "RIGHT", "created_at": "2025-12-25T15:21:16+00:00" }, { "id": 2647116043, "user": "user_cdda8932ec17", "body": "And then we should add a test with and without server-side cursors enabled.", "path": "tests/backends/postgresql/test_operations.py", "line": null, "side": "RIGHT", "created_at": "2025-12-25T15:21:51+00:00" }, { "id": 2648167464, "user": "user_ed8298a0306d", "body": "[USER_REDACTED] Thanks for the review! I've updated `max_query_params` to a `cached_property` that returns the limit only when `server_side_binding` is enabled.", "path": "django/db/backends/postgresql/features.py", "line": null, "side": "RIGHT", "created_at": "2025-12-26T13:08:49+00:00" }, { "id": 2648171063, "user": "user_ed8298a0306d", "body": "I've updated the test to cover both cases (with and without server-side binding).", "path": "tests/backends/postgresql/test_operations.py", "line": null, "side": "RIGHT", "created_at": "2025-12-26T13:10:43+00:00" }, { "id": 2651096279, "user": "user_3a67c55598c5", "body": "We have similar code for oracle & sqlite. I wonder if we should hoist all 3 implementations up to a single implementation on the superclass.\n\nWe might then one day implement a sane default for MySQL, which surely won't let you send a query of unbounded size even if the parameters have no strict upper limit.", "path": "django/db/backends/postgresql/operations.py", "line": null, "side": "RIGHT", "created_at": "2025-12-29T14:28:51+00:00" }, { "id": 2653070630, "user": "user_3a67c55598c5", "body": "Do we need the late import?", "path": "django/db/backends/base/operations.py", "line": null, "side": "RIGHT", "created_at": "2025-12-30T14:00:01+00:00" }, { "id": 2653106577, "user": "user_ed8298a0306d", "body": "I didn’t realize this code was shared across backends. Refactoring it as you suggested does make things cleaner. Thanks , [USER_REDACTED]", "path": "django/db/backends/postgresql/operations.py", "line": null, "side": "RIGHT", "created_at": "2025-12-30T14:19:10+00:00" }, { "id": 2653120083, "user": "user_3a67c55598c5", "body": "I would just delegate to `uses_server_side_binding` since the added logic is slightly different.", "path": "django/db/backends/postgresql/features.py", "line": null, "side": "RIGHT", "created_at": "2025-12-30T14:26:02+00:00" }, { "id": 2653134752, "user": "user_3a67c55598c5", "body": "Then we could just mock `uses_server_side_binding`, which I think would improve the test a little bit.", "path": "tests/backends/postgresql/test_operations.py", "line": null, "side": "RIGHT", "created_at": "2025-12-30T14:33:04+00:00" }, { "id": 2653144535, "user": "user_3a67c55598c5", "body": "I'm starting to wonder if we should hoist these tests out of the oracle & sqlite tests and just have one base test. Then the postgres specific test only needs to test the postgres-specific part where we switch on server-side binding...", "path": "tests/backends/postgresql/test_operations.py", "line": null, "side": "RIGHT", "created_at": "2025-12-30T14:38:04+00:00" }, { "id": 2653145712, "user": "user_3a67c55598c5", "body": "... rather than reiterate all of these assertions.", "path": "tests/backends/postgresql/test_operations.py", "line": null, "side": "RIGHT", "created_at": "2025-12-30T14:38:46+00:00" }, { "id": 2653163511, "user": "user_ed8298a0306d", "body": "I initially added this because I thought it was causing a circular import, but I had mixed it up with another file. I’ve now moved the import to the top.", "path": "django/db/backends/base/operations.py", "line": null, "side": "RIGHT", "created_at": "2025-12-30T14:48:22+00:00" }, { "id": 2653168624, "user": "user_3a67c55598c5", "body": "Can you tell me a little bit about this change? Was there a test isolation problem? What is the state of `connection.features` after this test?", "path": "tests/composite_pk/tests.py", "line": 153, "side": "RIGHT", "created_at": "2025-12-30T14:51:01+00:00" }, { "id": 2691162416, "user": "user_ed8298a0306d", "body": "This came up because `max_query_params` was changed to a `cached_property`. Once it calculates a value, it stores it in `__dict__` and just uses that stored value from then on. So when you try to mock the value in tests, if there's already a cached value, the mock won't take effect. You need to clear the cache with `.pop()` before applying the mock for it to work properly, which is why I made that change", "path": "tests/composite_pk/tests.py", "line": 153, "side": "RIGHT", "created_at": "2026-01-14T16:27:29+00:00" }, { "id": 2694225682, "user": "user_3a67c55598c5", "body": "I tweaked the test so it could still run on MySQL, allowing me to move this test into one of the above test cases and remove the mixin 👍", "path": "tests/backends/base/test_operations.py", "line": null, "side": "RIGHT", "created_at": "2026-01-15T12:39:20+00:00" }, { "id": 2694226559, "user": "user_3a67c55598c5", "body": "I think we need to stop the mocker.", "path": "tests/backends/base/test_operations.py", "line": null, "side": "RIGHT", "created_at": "2026-01-15T12:39:37+00:00" }, { "id": 2694263000, "user": "user_3a67c55598c5", "body": "Now that the tests run on all backends, I think we no longer need this test.", "path": "tests/backends/postgresql/test_operations.py", "line": null, "side": "RIGHT", "created_at": "2026-01-15T12:50:31+00:00" }, { "id": 2694443445, "user": "user_3a67c55598c5", "body": "(Actually, just to ensure we had _something_ I replaced it with a simpler one. Our CI configuration tests with server side params enabled & not enabled.)", "path": "tests/backends/postgresql/test_operations.py", "line": null, "side": "RIGHT", "created_at": "2026-01-15T13:42:35+00:00" }, { "id": 2694499746, "user": "user_ed8298a0306d", "body": "Thank you for letting me know. I didn’t realize there was a way to do that. I hadn’t thought of writing it in SimpleDatabaseOperationTests.", "path": "tests/backends/base/test_operations.py", "line": null, "side": "RIGHT", "created_at": "2026-01-15T13:58:02+00:00" } ], "meta": { "languages": [ "py" ], "touches_tests": true, "review_state_summary": { "COMMENTED": 11, "APPROVED": 1 }, "meaningful_comment_count": 19, "has_approval": true, "has_changes_requested": false, "total_review_comments": 19 } } { "_id": "3d97483fa58ec9af", "_schema_version": "1.0", "_cleaned_at": "2026-02-12T07:46:51.577805+00:00", "repo": "django/django", "repo_url": "https://github.com/django/django", "license_name": "BSD 3-Clause \"New\" or \"Revised\" License", "license_spdx": "BSD-3-Clause", "pr_number": 20460, "title": "Fixed #36821 -- Treated empty strings as NULL for iexact lookups on Oracle.", "body": "#### Trac ticket number\n\n\nticket-36821\n\n#### Branch description\nThank you for providing the test code, [USER_REDACTED] \n\nOn Oracle, iexact did not handle empty strings the same way as exact, even though empty strings are treated as NULL.\nThis change makes iexact=\"\" behave consistently with exact by [NAME_REDACTED] IS NULL lookup.\n\n#### Checklist\n- [x] This PR targets the `main` branch. \n- [x] The commit message is written in past tense, mentions the ticket number, and ends with a period.\n- [x] I have checked the \"Has patch\" ticket flag in the Trac system.\n- [x] I have added or updated relevant tests.\n- [ ] I have added or updated relevant docs, including release notes if applicable.\n- [ ] I have attached screenshots in both light and dark modes for any UI changes.", "author": "user_ed8298a0306d", "created_at": "2025-12-25T03:01:29+00:00", "merged_at": "2026-01-14T18:31:16+00:00", "base_branch": "main", "head_branch": "ticket-36821", "additions": 15, "deletions": 3, "changed_files": 3, "files": [ { "filename": "django/db/models/sql/query.py", "status": "modified", "additions": 1, "deletions": 1, "changes": 2, "patch": "@@ -1444,7 +1444,7 @@ def build_lookup(self, lookups, lhs, rhs):\n # DEFAULT_DB_ALIAS isn't nice but it's the best that can be done here.\n # A similar thing is done in is_nullable(), too.\n if (\n- lookup_name == \"exact\"\n+ lookup_name in (\"exact\", \"iexact\")\n and lookup.rhs == \"\"\n and connections[DEFAULT_DB_ALIAS].features.interprets_empty_strings_as_nulls\n ):" }, { "filename": "tests/null_queries/models.py", "status": "modified", "additions": 1, "deletions": 1, "changes": 2, "patch": "@@ -7,7 +7,7 @@ class Poll(models.Model):\n \n class Choice(models.Model):\n poll = models.ForeignKey(Poll, models.CASCADE)\n- choice = models.CharField(max_length=200)\n+ choice = models.CharField(max_length=200, null=True)\n \n \n # A set of models with an inner one pointing to two outer ones." }, { "filename": "tests/null_queries/tests.py", "status": "modified", "additions": 13, "deletions": 1, "changes": 14, "patch": "@@ -1,5 +1,5 @@\n from django.core.exceptions import FieldError\n-from django.test import TestCase\n+from django.test import TestCase, skipUnlessDBFeature\n \n from .models import Choice, Inner, OuterA, OuterB, Poll\n \n@@ -44,6 +44,18 @@ def test_none_as_null(self):\n with self.assertRaisesMessage(ValueError, \"Cannot use None as a query value\"):\n Choice.objects.filter(id__gt=None)\n \n+ [USER_REDACTED](\"interprets_empty_strings_as_nulls\")\n+ def test_empty_string_is_null(self):\n+ p = Poll.objects.create(question=\"?\")\n+ c1 = Choice.objects.create(poll=p, choice=None)\n+ c2 = Choice.objects.create(poll=p, choice=\"\")\n+ cases = [{\"choice__exact\": \"\"}, {\"choice__iexact\": \"\"}]\n+ for lookup in cases:\n+ with self.subTest(lookup):\n+ self.assertSequenceEqual(\n+ Choice.objects.filter(**lookup).order_by(\"id\"), [c1, c2]\n+ )\n+\n def test_unsaved(self):\n poll = Poll(question=\"How?\")\n msg = (" } ], "reviews": [ { "id": 3652188810, "user": "user_3a67c55598c5", "state": "APPROVED", "body": "Thanks!", "submitted_at": "2026-01-12T18:41:30+00:00" }, { "id": 3661218232, "user": "user_ed8298a0306d", "state": "COMMENTED", "body": null, "submitted_at": "2026-01-14T15:05:08+00:00" }, { "id": 3662187969, "user": "user_3a67c55598c5", "state": "APPROVED", "body": "Thanks 🥇", "submitted_at": "2026-01-14T18:29:49+00:00" } ], "review_comments": [ { "id": 2683458860, "user": "user_3a67c55598c5", "body": "Thanks, this location next to case-insensitive tests makes sense, but we could also move it to `NullQueriesTests`. What do you prefer?", "path": "tests/queries/tests.py", "line": null, "side": "RIGHT", "created_at": "2026-01-12T18:41:26+00:00" }, { "id": 2690832225, "user": "user_ed8298a0306d", "body": "Thanks for the suggestion! I'll move it to `NullQueriesTests`. Since both `None` and empty strings are converted to `IS NULL`, it makes sense to keep them together.", "path": "tests/queries/tests.py", "line": null, "side": "RIGHT", "created_at": "2026-01-14T15:05:08+00:00" } ], "meta": { "languages": [ "py" ], "touches_tests": true, "review_state_summary": { "APPROVED": 2, "COMMENTED": 1 }, "meaningful_comment_count": 2, "has_approval": true, "has_changes_requested": false, "total_review_comments": 2 } } { "_id": "81662449b72f05ae", "_schema_version": "1.0", "_cleaned_at": "2026-02-12T07:46:51.577805+00:00", "repo": "django/django", "repo_url": "https://github.com/django/django", "license_name": "BSD 3-Clause \"New\" or \"Revised\" License", "license_spdx": "BSD-3-Clause", "pr_number": 20458, "title": "Fixed #36644 -- Enabled empty order_by() to avoid pk ordering by first()/last().", "body": "#### Trac ticket number\n\n\nticket-36644\n\n#### Branch description\nEnabled calling `order_by()` without arguments to disable implicit primary key ordering in `first()`/`last()`. When a queryset is explicitly marked as unordered via `order_by()`, `first()`/`last()` now respect this and avoid adding PK ordering. Also reset default_ordering in `_combinator_query()` so that `union().first()` can still add pk ordering.\n\nDiscussion: https://github.com/[USER_REDACTED]ngo/new-features/issues/71, \n\n#### Checklist\n- [x] This PR targets the `main` branch. \n- [x] The commit message is written in past tense, mentions the ticket number, and ends with a period.\n- [x] I have checked the \"Has patch\" ticket flag in the Trac system.\n- [x] I have added or updated relevant tests.\n- [ ] I have added or updated relevant docs, including release notes if applicable.\n- [ ] I have attached screenshots in both light and dark modes for any UI changes.", "author": "user_d96dcc7f8ae4", "created_at": "2025-12-24T16:44:07+00:00", "merged_at": "2026-02-06T20:45:45+00:00", "base_branch": "main", "head_branch": "ticket_36644", "additions": 49, "deletions": 3, "changed_files": 4, "files": [ { "filename": "django/db/models/query.py", "status": "modified", "additions": 3, "deletions": 2, "changes": 5, "patch": "@@ -1158,7 +1158,7 @@ async def alatest(self, *fields):\n \n def first(self):\n \"\"\"Return the first object of a query or None if no match is found.\"\"\"\n- if self.ordered:\n+ if self.ordered or not self.query.default_ordering:\n queryset = self\n else:\n self._check_ordering_first_last_queryset_aggregation(method=\"first\")\n@@ -1171,7 +1171,7 @@ async def afirst(self):\n \n def last(self):\n \"\"\"Return the last object of a query or None if no match is found.\"\"\"\n- if self.ordered:\n+ if self.ordered or not self.query.default_ordering:\n queryset = self.reverse()\n else:\n self._check_ordering_first_last_queryset_aggregation(method=\"last\")\n@@ -1679,6 +1679,7 @@ def _combinator_query(self, combinator, *other_qs, all=False):\n clone = self._chain()\n # Clear limits and ordering so they can be reapplied\n clone.query.clear_ordering(force=True)\n+ clone.query.default_ordering = True\n clone.query.clear_limits()\n clone.query.combined_queries = (self.query, *(qs.query for qs in other_qs))\n clone.query.combinator = combinator" }, { "filename": "tests/get_earliest_or_latest/models.py", "status": "modified", "additions": 8, "deletions": 0, "changes": 8, "patch": "@@ -21,6 +21,14 @@ class Comment(models.Model):\n likes_count = models.PositiveIntegerField()\n \n \n+class OrderedArticle(models.Model):\n+ headline = models.CharField(max_length=100)\n+ pub_date = models.DateField()\n+\n+ class Meta:\n+ ordering = [\"headline\"]\n+\n+\n # Ticket #23555 - model with an intentionally broken QuerySet.__iter__ method." }, { "filename": "tests/get_earliest_or_latest/tests.py", "status": "modified", "additions": 29, "deletions": 1, "changes": 30, "patch": "@@ -1,9 +1,10 @@\n from datetime import datetime\n+from unittest.mock import patch\n \n from django.db.models import Avg\n from django.test import TestCase\n \n-from .models import Article, Comment, IndexErrorArticle, Person\n+from .models import Article, Comment, IndexErrorArticle, OrderedArticle, Person\n \n \n class EarliestOrLatestTests(TestCase):\n@@ -265,3 +266,30 @@ def test_first_last_unordered_qs_aggregation_error(self):\n qs.first()\n with self.assertRaisesMessage(TypeError, msg % \"last\"):\n qs.last()\n+\n+ def test_first_last_empty_order_by_has_no_pk_ordering(self):\n+ Article.objects.create(\n+ headline=\"Article 1\",\n+ pub_date=datetime(2006, 9, 10),\n+ expire_date=datetime(2056, 9, 11),\n+ )\n+\n+ qs = Article.objects.order_by()\n+ with patch.object(type(qs), \"order_by\") as mock_order_by:\n+ qs.first()\n+ mock_order_by.assert_not_called()\n+ qs.last()\n+ mock_order_by.assert_not_called()\n+\n+ def test_first_last_empty_order_by_clears_default_ordering(self):\n+ OrderedArticle.objects.create(\n+ headline=\"Article 1\",\n+ pub_date=datetime(2006, 9, 10),\n+ )\n+\n+ qs = OrderedArticle.objects.order_by()\n+ with patch.object(type(qs), \"order_by\") as mock_order_by:\n+ qs.first()\n+ mock_order_by.assert_not_called()\n+ qs.last()\n+ mock_order_by.assert_not_called()" }, { "filename": "tests/queries/test_qs_combinators.py", "status": "modified", "additions": 9, "deletions": 0, "changes": 9, "patch": "@@ -418,6 +418,15 @@ def test_union_with_first(self):\n qs2 = base_qs.filter(name=\"a2\")\n self.assertEqual(qs1.union(qs2).first(), a1)\n \n+ [USER_REDACTED](\"supports_slicing_ordering_in_compound\")\n+ def test_union_applies_default_ordering_afterward(self):\n+ c = Tag.objects.create(name=\"C\")\n+ Tag.objects.create(name=\"B\")\n+ a = Tag.objects.create(name=\"A\")\n+ qs1 = Tag.objects.filter(name__in=[\"A\", \"B\"])[:1]\n+ qs2 = Tag.objects.filter(name__in=[\"C\"])[:1]\n+ self.assertSequenceEqual(qs1.union(qs2), [a, c])\n+\n def test_union_multiple_models_with_values_list_and_order(self):\n reserved_name = ReservedName.objects.create(name=\"rn1\", order=0)\n qs1 = Celebrity.objects.all()" } ], "reviews": [ { "id": 3717417880, "user": "user_3a67c55598c5", "state": "COMMENTED", "body": "Thanks [USER_REDACTED] 👍 \n\nI have initial comments for you.", "submitted_at": "2026-01-28T15:45:25+00:00" }, { "id": 3717514441, "user": "user_3a67c55598c5", "state": "COMMENTED", "body": null, "submitted_at": "2026-01-28T15:53:08+00:00" }, { "id": 3717729011, "user": "user_057de2f3b132", "state": "COMMENTED", "body": null, "submitted_at": "2026-01-28T16:31:44+00:00" }, { "id": 3718056748, "user": "user_3a67c55598c5", "state": "COMMENTED", "body": null, "submitted_at": "2026-01-28T17:31:57+00:00" }, { "id": 3718108107, "user": "user_3a67c55598c5", "state": "COMMENTED", "body": null, "submitted_at": "2026-01-28T17:44:47+00:00" }, { "id": 3718636110, "user": "user_057de2f3b132", "state": "COMMENTED", "body": null, "submitted_at": "2026-01-28T19:18:51+00:00" }, { "id": 3718658211, "user": "user_3a67c55598c5", "state": "COMMENTED", "body": null, "submitted_at": "2026-01-28T19:22:52+00:00" }, { "id": 3757741364, "user": "user_3a67c55598c5", "state": "COMMENTED", "body": null, "submitted_at": "2026-02-05T15:13:36+00:00" }, { "id": 3757847192, "user": "user_d96dcc7f8ae4", "state": "COMMENTED", "body": null, "submitted_at": "2026-02-05T15:32:53+00:00" }, { "id": 3757979051, "user": "user_3a67c55598c5", "state": "COMMENTED", "body": null, "submitted_at": "2026-02-05T15:55:22+00:00" }, { "id": 3759777262, "user": "user_3a67c55598c5", "state": "APPROVED", "body": "Thanks [USER_REDACTED], this looks great ✅ .\n\nI segregated out the `union()` stuff since that was a separate bug we had to solve first. I also rewrote your test to actually perform queries and more clearly demonstrate that default orders were not applied after `union()`.", "submitted_at": "2026-02-05T22:26:59+00:00" }, { "id": 3759806798, "user": "user_057de2f3b132", "state": "APPROVED", "body": null, "submitted_at": "2026-02-05T22:37:44+00:00" } ], "review_comments": [ { "id": 2737233490, "user": "user_3a67c55598c5", "body": "Need release notes and deprecation entries, see https://docs.djangoproject.com/en/6.0/internals/contributing/writing-code/submitting-patches/#deprecating-a-feature.", "path": "django/db/models/query.py", "line": null, "side": "RIGHT", "created_at": "2026-01-28T15:37:02+00:00" }, { "id": 2737248463, "user": "user_3a67c55598c5", "body": "first() and last() returning the same object because only one object exists is a little non-intuitive for me when reading this test.", "path": "tests/get_earliest_or_latest/tests.py", "line": null, "side": "RIGHT", "created_at": "2026-01-28T15:40:10+00:00" }, { "id": 2737252468, "user": "user_3a67c55598c5", "body": "Can you add another test method showing what happens when a model has a default ordering as mentioned in the ticket?", "path": "tests/get_earliest_or_latest/tests.py", "line": null, "side": "RIGHT", "created_at": "2026-01-28T15:41:00+00:00" }, { "id": 2737268074, "user": "user_3a67c55598c5", "body": "I can deindent this without any failures.", "path": "django/db/models/query.py", "line": null, "side": "RIGHT", "created_at": "2026-01-28T15:44:02+00:00" }, { "id": 2737311179, "user": "user_3a67c55598c5", "body": "[USER_REDACTED] the main reason I suggested the deprecation path was because of this test case.\n\nLooking again, perhaps we can look through the other end of the telescope here and make `first()`/`last()` have no change for union()/combinators instead.\n\nThe idea would be:\n```py\n.order_by().first() # no pk ordering, forced order clear\n# teach .union() to forget about whatever forced order clearing came before\nqs2.order_by().union(qs1).first() # still has a pk ordering, since we forgot about the forced order clear before union()\nqs2.order_by().union(qs1).order_by().first() # no pk ordering, ordering was force-cleared after union()\n```\nWDYT?\n\n[USER_REDACTED] you might want to pause on polishing the deprecation path to allow a little time for this discussion :-)", "path": "tests/queries/test_qs_combinators.py", "line": null, "side": "RIGHT", "created_at": "2026-01-28T15:53:08+00:00" }, { "id": 2737484059, "user": "user_057de2f3b132", "body": "Hmm, interesting.\n\nFrom an SQL point of view it looks like there's only ever an ordering applied to the whole union not to sub-parts (unless I'm missing something). In that case, I'm happy with your proposed behaviour.\n\nIt might also be worthwhile to warn about explicit `order_by` calls on either of the `union` querysets (i.e. `qs1` and `qs2` in your example), since these will always be ignored.\n\nOn the point of deprecation, I'm happy for the default behaviour to be a deprecation warning, but I'd like to also have a way to opt-in to the future behaviour (via a setting or maybe an attribute on the queryset or something).", "path": "tests/queries/test_qs_combinators.py", "line": null, "side": "RIGHT", "created_at": "2026-01-28T16:31:43+00:00" }, { "id": 2737745249, "user": "user_3a67c55598c5", "body": "Cool. So in that case, we don't need deprecation warnings relating to the order_by() <--> first() interaction, because we found a way to solve the ticket without mucking with this union() test case.\n\nA tangential finding here about the order_by() <--> union() interaction might be worth a deprecation path to eventually lead to raising an error, but we don't need to tackle that here.\n\nDoes that make sense [USER_REDACTED]?", "path": "tests/queries/test_qs_combinators.py", "line": null, "side": "RIGHT", "created_at": "2026-01-28T17:31:57+00:00" }, { "id": 2737790455, "user": "user_3a67c55598c5", "body": "> A tangential finding here about the order_by() <--> union() interaction might be worth a deprecation path to eventually lead to raising an error, but we don't need to tackle that here.\n\nActually, we don't even need that, the reason these examples have `order_by()` before `.union()` is to clear a default ordering from the queryset, which is good, because otherwise `.union()` throws. So nothing to deprecate and nothing to raise an error for.\n\nThe question here is just how to disambiguate that from \"please don't order my final result after the union\".", "path": "tests/queries/test_qs_combinators.py", "line": null, "side": "RIGHT", "created_at": "2026-01-28T17:44:47+00:00" }, { "id": 2738196002, "user": "user_057de2f3b132", "body": "I think `qs2.union(qs1).first()` should be \"apply pk ordering\" and `qs2.union(qs1).order_by().first()` should be \"apply no ordering\". (With extra `.order_by()` on `qs1` or `qs2` as necessary.)", "path": "tests/queries/test_qs_combinators.py", "line": null, "side": "RIGHT", "created_at": "2026-01-28T19:18:51+00:00" }, { "id": 2738215019, "user": "user_3a67c55598c5", "body": "Wonderful, I agree. So [USER_REDACTED], we should leave the original test case as is to capture Lily's first case, and then add an assertion to capture Lily's second case.", "path": "tests/queries/test_qs_combinators.py", "line": null, "side": "RIGHT", "created_at": "2026-01-28T19:22:52+00:00" }, { "id": 2769690073, "user": "user_3a67c55598c5", "body": "This won't fail if the code change is undone; we'll need something else, e.g. mocking `order_by()` and calling `assert_not_called`.", "path": "tests/get_earliest_or_latest/tests.py", "line": null, "side": "RIGHT", "created_at": "2026-02-05T15:13:36+00:00" }, { "id": 2769784169, "user": "user_d96dcc7f8ae4", "body": "Thanks for the review! I’m aware of this and already working on the suggested changes. I’ll request another review once everything is ready.", "path": "tests/get_earliest_or_latest/tests.py", "line": null, "side": "RIGHT", "created_at": "2026-02-05T15:32:53+00:00" }, { "id": 2769897688, "user": "user_3a67c55598c5", "body": "No problem, sorry for jumping the gun 👍", "path": "tests/get_earliest_or_latest/tests.py", "line": null, "side": "RIGHT", "created_at": "2026-02-05T15:55:22+00:00" } ], "meta": { "languages": [ "py" ], "touches_tests": true, "review_state_summary": { "COMMENTED": 10, "APPROVED": 2 }, "meaningful_comment_count": 13, "has_approval": true, "has_changes_requested": false, "total_review_comments": 13 } } { "_id": "0b202cfe0094fae8", "_schema_version": "1.0", "_cleaned_at": "2026-02-12T07:46:51.577805+00:00", "repo": "django/django", "repo_url": "https://github.com/django/django", "license_name": "BSD 3-Clause \"New\" or \"Revised\" License", "license_spdx": "BSD-3-Clause", "pr_number": 20455, "title": "Added DatabaseFeatures.supports_inspectdb.", "body": "Needed by MongoDB.", "author": "user_657e90e5ae46", "created_at": "2025-12-24T01:37:59+00:00", "merged_at": "2026-02-09T22:46:33+00:00", "base_branch": "main", "head_branch": "DatabaseFeatures.supports_inspectdb", "additions": 29, "deletions": 4, "changed_files": 5, "files": [ { "filename": "django/core/management/commands/inspectdb.py", "status": "modified", "additions": 2, "deletions": 2, "changes": 4, "patch": "@@ -44,10 +44,10 @@ def add_arguments(self, parser):\n )\n \n def handle(self, **options):\n- try:\n+ if connections[options[\"database\"]].features.supports_inspectdb:\n for line in self.handle_inspection(options):\n self.stdout.write(line)\n- except NotImplementedError:\n+ else:\n raise CommandError(\n \"Database inspection isn't supported for the currently selected \"\n \"database backend.\"" }, { "filename": "django/db/backends/base/features.py", "status": "modified", "additions": 3, "deletions": 0, "changes": 3, "patch": "@@ -400,6 +400,9 @@ class BaseDatabaseFeatures:\n supports_on_delete_db_default = True\n supports_on_delete_db_null = True\n \n+ # Does the backend support the inspectdb management command?\n+ supports_inspectdb = True\n+\n # Collation names for use by [NAME_REDACTED]\n test_collations = {\n \"ci\": None, # Case-insensitive." }, { "filename": "docs/releases/6.1.txt", "status": "modified", "additions": 3, "deletions": 0, "changes": 3, "patch": "@@ -367,6 +367,9 @@ backends.\n ``db_on_delete``) as values. ``db_on_delete`` is one of the database-level\n delete options e.g. :attr:`~django.db.models.DB_CASCADE`.\n \n+* Set the new ``DatabaseFeatures.supports_inspectdb`` attribute to ``False``\n+ if the management command isn't supported.\n+\n :mod:`django.contrib.gis`\n -------------------------" }, { "filename": "tests/gis_tests/inspectapp/tests.py", "status": "modified", "additions": 1, "deletions": 0, "changes": 1, "patch": "@@ -14,6 +14,7 @@\n from .models import AllOGRFields\n \n \n+[USER_REDACTED](\"supports_inspectdb\")\n class InspectDbTests(TestCase):\n def test_geom_columns(self):\n \"\"\"" }, { "filename": "tests/inspectdb/tests.py", "status": "modified", "additions": 20, "deletions": 2, "changes": 22, "patch": "@@ -2,11 +2,16 @@\n from io import StringIO\n from unittest import mock, skipUnless\n \n-from django.core.management import call_command\n+from django.core.management import CommandError, call_command\n from django.core.management.commands import inspectdb\n from django.db import connection\n from django.db.backends.base.introspection import TableInfo\n-from django.test import TestCase, TransactionTestCase, skipUnlessDBFeature\n+from django.test import (\n+ TestCase,\n+ TransactionTestCase,\n+ skipIfDBFeature,\n+ skipUnlessDBFeature,\n+)\n \n from .models import PeopleMoreData, test_collation\n \n@@ -40,6 +45,7 @@ def cursor_execute(*queries):\n return results\n \n \n+[USER_REDACTED](\"supports_inspectdb\")\n class InspectDBTestCase(TestCase):\n unique_re = re.compile(r\".*unique_together = \\((.+),\\).*\")\n \n@@ -519,6 +525,7 @@ def test_same_relations(self):\n )\n \n \n+[USER_REDACTED](\"supports_inspectdb\")\n class InspectDBTransactionalTests(TransactionTestCase):\n available_apps = [\"inspectdb\"]\n \n@@ -671,3 +678,14 @@ def test_composite_primary_key_not_unique_together(self):\n out = StringIO()\n call_command(\"inspectdb\", \"inspectdb_compositepkmodel\", stdout=out)\n self.assertNotIn(\"unique_together\", out.getvalue())\n+\n+\n+[USER_REDACTED](\"supports_inspectdb\")\n+class InspectDBNotSupportedTests(TestCase):\n+ def test_not_supported(self):\n+ msg = (\n+ \"Database inspection isn't supported for the currently selected \"\n+ \"database backend.\"\n+ )\n+ with self.assertRaisesMessage(CommandError, msg):\n+ call_command(\"inspectdb\")" } ], "reviews": [ { "id": 3609673130, "user": "user_657e90e5ae46", "state": "COMMENTED", "body": null, "submitted_at": "2025-12-24T01:39:13+00:00" }, { "id": 3756970500, "user": "user_3a67c55598c5", "state": "COMMENTED", "body": null, "submitted_at": "2026-02-05T13:06:16+00:00" }, { "id": 3775630452, "user": "user_3a67c55598c5", "state": "APPROVED", "body": null, "submitted_at": "2026-02-09T22:04:41+00:00" } ], "review_comments": [ { "id": 2644568610, "user": "user_657e90e5ae46", "body": "This matches what `inspectdb` does:\nhttps://github.com/[USER_REDACTED]ngo/django/blob/68859a9b45f0b9d472c9277dc61e54afacc0da38/django/core/management/commands/inspectdb.py#L47-L54\nI debated whether to use this implementation or to make it a boolean that the developer has to set to opt out. I could be convinced either way.", "path": "django/db/backends/base/features.py", "line": null, "side": "RIGHT", "created_at": "2025-12-24T01:39:13+00:00" }, { "id": 2769063466, "user": "user_3a67c55598c5", "body": "Interesting. I checked the blame, and at the time this was added the only backend that raised `NotImplementedError` from `get_table_names()` was the since-removed backend for ADO MSSQL:\n\nhttps://github.com/[USER_REDACTED]ngo/django/blob/6d210ef40341b26aa2881fbb82ef7a7cdd54a3df/django/core/db/backends/ado_mssql.py#L112-L113\n\nWe could probably make the flag a boolean and then do a cleanup in `inspectdb` to replace this except with a check on that flag. wdyt?", "path": "django/db/backends/base/features.py", "line": null, "side": "RIGHT", "created_at": "2026-02-05T13:06:16+00:00" } ], "meta": { "languages": [ "py", "txt" ], "touches_tests": true, "review_state_summary": { "COMMENTED": 2, "APPROVED": 1 }, "meaningful_comment_count": 2, "has_approval": true, "has_changes_requested": false, "total_review_comments": 2 } } { "_id": "bb9095d0d1a81964", "_schema_version": "1.0", "_cleaned_at": "2026-02-12T07:46:51.577805+00:00", "repo": "django/django", "repo_url": "https://github.com/django/django", "license_name": "BSD 3-Clause \"New\" or \"Revised\" License", "license_spdx": "BSD-3-Clause", "pr_number": 20448, "title": "Bumped linter dependencies", "body": "#### Trac ticket number\n\nNone. I can create one if we think it's necessary.\n\n#### Branch description\nUpdates the linters.\n\n* psf/black-pre-commit-mirror: 25.9.0 -> 25.12.0\n* pre-commit/mirrors-eslint: v9.36.0 -> v9.39.1\n* zizmorcore/zizmor-pre-commit: v1.16.3 -> v1.19.0\n* zizmorcore/zizmor-action: 0.2.0 -> 0.3.0\n\n#### Checklist\n- [x] This PR targets the `main` branch. \n- [x] The commit message is written in past tense, mentions the ticket number, and ends with a period.\n- [ ] I have checked the \"Has patch\" ticket flag in the Trac system.\n- [ ] I have added or updated relevant tests.\n- [ ] I have added or updated relevant docs, including release notes if applicable.\n- [ ] I have attached screenshots in both light and dark modes for any UI changes.", "author": "user_f575e6dfca7f", "created_at": "2025-12-23T01:20:12+00:00", "merged_at": "2026-01-12T13:57:36+00:00", "base_branch": "main", "head_branch": "bump-linter-dependencies", "additions": 5, "deletions": 5, "changed_files": 2, "files": [ { "filename": ".github/workflows/linters.yml", "status": "modified", "additions": 1, "deletions": 1, "changes": 2, "patch": "@@ -79,7 +79,7 @@ jobs:\n with:\n persist-credentials: false\n - name: Run zizmor\n- uses: zizmorcore/zizmor-action@e673c3917a1aef3c65c972347ed84ccd013ecda4 # v0.2.0\n+ uses: zizmorcore/zizmor-action@e639db99335bc9038abc0e066dfcd72e23d26fb4 # v0.3.0\n with:\n advanced-security: false\n annotations: true" }, { "filename": ".pre-commit-config.yaml", "status": "modified", "additions": 4, "deletions": 4, "changes": 8, "patch": "@@ -1,6 +1,6 @@\n repos:\n - repo: https://github.com/psf/black-pre-commit-mirror\n- rev: 25.9.0\n+ rev: 25.12.0\n hooks:\n - id: black\n exclude: \\.py-tpl$\n@@ -9,7 +9,7 @@ repos:\n hooks:\n - id: blacken-docs\n additional_dependencies:\n- - black==25.9.0\n+ - black==25.12.0\n files: 'docs/.*\\.txt$'\n args: [\"--rst-literal-block\"]\n - repo: https://github.com/PyCQA/isort\n@@ -21,10 +21,10 @@ repos:\n hooks:\n - id: flake8\n - repo: https://github.com/pre-commit/mirrors-eslint\n- rev: v9.36.0\n+ rev: v9.39.1\n hooks:\n - id: eslint\n - repo: https://github.com/zizmorcore/zizmor-pre-commit\n- rev: v1.16.3 \n+ rev: v1.19.0\n hooks:\n - id: zizmor" } ], "reviews": [ { "id": 3650896821, "user": "user_3a67c55598c5", "state": "APPROVED", "body": "Thanks 👍", "submitted_at": "2026-01-12T13:57:00+00:00" }, { "id": 3651926456, "user": "user_5501cd6d3dc8", "state": "COMMENTED", "body": null, "submitted_at": "2026-01-12T17:36:38+00:00" }, { "id": 3662452823, "user": "user_3a67c55598c5", "state": "COMMENTED", "body": null, "submitted_at": "2026-01-14T19:42:10+00:00" } ], "review_comments": [ { "id": 2683244097, "user": "user_5501cd6d3dc8", "body": "This should also be updated in the `package.json`.", "path": ".pre-commit-config.yaml", "line": 24, "side": "RIGHT", "created_at": "2026-01-12T17:36:38+00:00" }, { "id": 2691792468, "user": "user_3a67c55598c5", "body": "Gotcha, see #20537.", "path": ".pre-commit-config.yaml", "line": 24, "side": "RIGHT", "created_at": "2026-01-14T19:42:10+00:00" } ], "meta": { "languages": [ "yaml", "yml" ], "touches_tests": false, "review_state_summary": { "APPROVED": 1, "COMMENTED": 2 }, "meaningful_comment_count": 2, "has_approval": true, "has_changes_requested": false, "total_review_comments": 2 } } { "_id": "fe274e0195e20c3e", "_schema_version": "1.0", "_cleaned_at": "2026-02-12T07:46:51.577805+00:00", "repo": "django/django", "repo_url": "https://github.com/django/django", "license_name": "BSD 3-Clause \"New\" or \"Revised\" License", "license_spdx": "BSD-3-Clause", "pr_number": 20445, "title": "Refs #24920 -- [NAME_REDACTED] system checks database dependent.", "body": "[NAME_REDACTED] for the suggestion.\n\nticket-24920", "author": "user_5501cd6d3dc8", "created_at": "2025-12-22T19:32:54+00:00", "merged_at": "2025-12-28T18:21:49+00:00", "base_branch": "main", "head_branch": "24920-checks", "additions": 63, "deletions": 52, "changed_files": 2, "files": [ { "filename": "django/db/models/fields/__init__.py", "status": "modified", "additions": 57, "deletions": 46, "changes": 103, "patch": "@@ -1715,40 +1715,46 @@ def __init__(\n \n def check(self, **kwargs):\n errors = super().check(**kwargs)\n+ databases = kwargs.get(\"databases\") or []\n \n digits_errors = [\n- *self._check_decimal_places(),\n- *self._check_max_digits(),\n+ *self._check_decimal_places(databases),\n+ *self._check_max_digits(databases),\n ]\n if not digits_errors:\n errors.extend(self._check_decimal_places_and_max_digits(**kwargs))\n else:\n errors.extend(digits_errors)\n return errors\n \n- def _check_decimal_places(self):\n+ def _check_decimal_places(self, databases):\n if self.decimal_places is None:\n- if (\n- not connection.features.supports_no_precision_decimalfield\n- and \"supports_no_precision_decimalfield\"\n- not in self.model._meta.required_db_features\n- ):\n- return [\n- checks.Error(\n- \"DecimalFields must define a 'decimal_places' attribute.\",\n- obj=self,\n- id=\"fields.E130\",\n- )\n- ]\n- elif self.max_digits is not None:\n- return [\n- checks.Error(\n- \"DecimalField’s max_digits and decimal_places must both \"\n- \"be defined or both omitted.\",\n- obj=self,\n- id=\"fields.E135\",\n- ),\n- ]\n+ for db in databases:\n+ if not router.allow_migrate_model(db, self.model):\n+ continue\n+ connection = connections[db]\n+\n+ if (\n+ not connection.features.supports_no_precision_decimalfield\n+ and \"supports_no_precision_decimalfield\"\n+ not in self.model._meta.required_db_features\n+ ):\n+ return [\n+ checks.Error(\n+ \"DecimalFields must define a 'decimal_places' attribute.\",\n+ obj=self,\n+ id=\"fields.E130\",\n+ )\n+ ]\n+ elif self.max_digits is not None:\n+ return [\n+ checks.Error(\n+ \"DecimalField’s max_digits and decimal_places must both \"\n+ \"be defined or both omitted.\",\n+ obj=self,\n+ id=\"fields.E135\",\n+ ),\n+ ]\n else:\n try:\n decimal_places = int(self.decimal_places)\n@@ -1764,29 +1770,34 @@ def _check_decimal_places(self):\n ]\n return []\n \n- def _check_max_digits(self):\n+ def _check_max_digits(self, databases):\n if self.max_digits is None:\n- if (\n- not connection.features.supports_no_precision_decimalfield\n- and \"supports_no_precision_decimalfield\"\n- not in self.model._meta.required_db_features\n- ):\n- return [\n- checks.Error(\n- \"DecimalFields must define a 'max_digits' attribute.\",\n- obj=self,\n- id=\"fields.E132\",\n- )\n- ]\n- elif self.decimal_places is not None:\n- return [\n- checks.Error(\n- \"DecimalField’s max_digits and decimal_places must both \"\n- \"be defined or both omitted.\",\n- obj=self,\n- id=\"fields.E135\",\n- ),\n- ]\n+ for db in databases:\n+ if not router.allow_migrate_model(db, self.model):\n+ continue\n+ connection = connections[db]\n+\n+ if (\n+ not connection.features.supports_no_precision_decimalfield\n+ and \"supports_no_precision_decimalfield\"\n+ not in self.model._meta.required_db_features\n+ ):\n+ return [\n+ checks.Error(\n+ \"DecimalFields must define a 'max_digits' attribute.\",\n+ obj=self,\n+ id=\"fields.E132\",\n+ )\n+ ]\n+ elif self.decimal_places is not None:\n+ return [\n+ checks.Error(\n+ \"DecimalField’s max_digits and decimal_places must both \"\n+ \"be defined or both omitted.\",\n+ obj=self,\n+ id=\"fields.E135\",\n+ ),\n+ ]\n else:\n try:\n max_digits = int(self.max_digits)" }, { "filename": "tests/invalid_models_tests/test_ordinary_fields.py", "status": "modified", "additions": 6, "deletions": 6, "changes": 12, "patch": "@@ -620,7 +620,7 @@ class Model(models.Model):\n id=\"fields.E132\",\n ),\n ]\n- self.assertEqual(field.check(), expected)\n+ self.assertEqual(field.check(databases=self.databases), expected)\n \n def test_both_attributes_omitted_required_db_features(self):\n class Model(models.Model):\n@@ -639,7 +639,7 @@ class Model(models.Model):\n \n field = Model._meta.get_field(\"field\")\n self.assertEqual(\n- field.check(),\n+ field.check(databases=self.databases),\n [\n Error(\n \"DecimalField’s max_digits and decimal_places must both \"\n@@ -657,7 +657,7 @@ class Model(models.Model):\n \n field = Model._meta.get_field(\"field\")\n self.assertEqual(\n- field.check(),\n+ field.check(databases=self.databases),\n [\n Error(\n \"DecimalField’s max_digits and decimal_places must both \"\n@@ -674,7 +674,7 @@ class Model(models.Model):\n \n field = Model._meta.get_field(\"field\")\n self.assertEqual(\n- field.check(),\n+ field.check(databases=self.databases),\n [\n Error(\n \"'decimal_places' must be a non-negative integer.\",\n@@ -695,7 +695,7 @@ class Model(models.Model):\n \n field = Model._meta.get_field(\"field\")\n self.assertEqual(\n- field.check(),\n+ field.check(databases=self.databases),\n [\n Error(\n \"'decimal_places' must be a non-negative integer.\",\n@@ -731,7 +731,7 @@ class Model(models.Model):\n field = models.DecimalField(max_digits=10, decimal_places=10)\n \n field = Model._meta.get_field(\"field\")\n- self.assertEqual(field.check(), [])\n+ self.assertEqual(field.check(databases=self.databases), [])\n \n \n [USER_REDACTED]_apps(\"invalid_models_tests\")" } ], "reviews": [ { "id": 3609292504, "user": "user_606ba1f2b93c", "state": "APPROVED", "body": null, "submitted_at": "2025-12-23T20:48:31+00:00" }, { "id": 3609294238, "user": "user_cdda8932ec17", "state": "COMMENTED", "body": null, "submitted_at": "2025-12-23T20:50:09+00:00" }, { "id": 3609312884, "user": "user_5501cd6d3dc8", "state": "COMMENTED", "body": null, "submitted_at": "2025-12-23T20:58:21+00:00" }, { "id": 3609319896, "user": "user_5501cd6d3dc8", "state": "COMMENTED", "body": null, "submitted_at": "2025-12-23T21:00:32+00:00" }, { "id": 3614772829, "user": "user_cdda8932ec17", "state": "APPROVED", "body": null, "submitted_at": "2025-12-28T17:48:46+00:00" } ], "review_comments": [ { "id": 2644234920, "user": "user_cdda8932ec17", "body": "Any thoughts about moving this skip to `check`? I wonder if it might be worth adjusting `Model.check` to eventually skip delegation when `not router.allow_migrate_model(db, self.model)`.", "path": "django/db/models/fields/__init__.py", "line": 1734, "side": "RIGHT", "created_at": "2025-12-23T20:49:33+00:00" }, { "id": 2644235375, "user": "user_cdda8932ec17", "body": "I think you're missing `connection = connections[db]` here?", "path": "django/db/models/fields/__init__.py", "line": 1777, "side": "RIGHT", "created_at": "2025-12-23T20:49:50+00:00" }, { "id": 2644249178, "user": "user_5501cd6d3dc8", "body": "The second branch (when `decimal_places` is not `None`) should always run, that's why I put it here.", "path": "django/db/models/fields/__init__.py", "line": 1734, "side": "RIGHT", "created_at": "2025-12-23T20:58:21+00:00" }, { "id": 2644252759, "user": "user_5501cd6d3dc8", "body": "Yes, good catch :dart: Silly me :)", "path": "django/db/models/fields/__init__.py", "line": 1777, "side": "RIGHT", "created_at": "2025-12-23T21:00:32+00:00" } ], "meta": { "languages": [ "py" ], "touches_tests": true, "review_state_summary": { "APPROVED": 2, "COMMENTED": 3 }, "meaningful_comment_count": 4, "has_approval": true, "has_changes_requested": false, "total_review_comments": 4 } } { "_id": "35b3c2a253dc27c4", "_schema_version": "1.0", "_cleaned_at": "2026-02-12T07:46:51.577805+00:00", "repo": "django/django", "repo_url": "https://github.com/django/django", "license_name": "BSD 3-Clause \"New\" or \"Revised\" License", "license_spdx": "BSD-3-Clause", "pr_number": 20443, "title": "Fixed #36818 -- Ensured SQLite connection before accessing max_query_params.", "body": "Ensure that the SQLite database connection is established before accessing\nDatabaseFeatures.max_query_params.\n\nThis fixes a regression where calling QuerySet.bulk_create() as the first\ndatabase operation after django.setup() could raise an AttributeError on\nSQLite due to an uninitialized connection.\n\n#### Trac ticket number\nticket-36818\n\n#### Branch description\nSQLite's DatabaseFeatures.max_query_params accessed the underlying DB-API\nconnection without ensuring it was initialized. This change calls\nensure_connection() before querying the SQLite variable limit, preventing\nAttributeError when backend features are accessed prior to any SQL execution.\n\n#### Checklist\n- [x] This PR targets the `main` branch. \n- [x] The commit message is written in past tense, mentions the ticket number, and ends with a period.\n- [x] I have checked the \"Has patch\" ticket flag in the Trac system.\n- [x] I have added or updated relevant tests.\n- [x] I have added or updated relevant docs, including release notes if applicable.\n- [ ] I have attached screenshots in both light and dark modes for any UI changes.", "author": "user_efaa7460429a", "created_at": "2025-12-22T15:56:10+00:00", "merged_at": "2025-12-23T01:33:13+00:00", "base_branch": "main", "head_branch": "ticket_36818_sqlite_max_query_params", "additions": 16, "deletions": 0, "changed_files": 3, "files": [ { "filename": "django/db/backends/sqlite3/features.py", "status": "modified", "additions": 1, "deletions": 0, "changes": 1, "patch": "@@ -157,6 +157,7 @@ def max_query_params(self):\n 32766) or lowered per connection at run-time with\n setlimit(SQLITE_LIMIT_VARIABLE_NUMBER, N).\n \"\"\"\n+ self.connection.ensure_connection()\n return self.connection.connection.getlimit(sqlite3.SQLITE_LIMIT_VARIABLE_NUMBER)\n \n [USER_REDACTED]_property" }, { "filename": "docs/releases/6.0.1.txt", "status": "modified", "additions": 4, "deletions": 0, "changes": 4, "patch": "@@ -20,3 +20,7 @@ Bugfixes\n * Fixed a bug where management command colorized help (introduced in\n Python 3.14) ignored the :option:`--no-color` option and the\n :envvar:`DJANGO_COLORS` setting (:ticket:`36376`).\n+\n+* Fixed a regression in Django 6.0 that caused\n+ :meth:`~django.db.models.query.QuerySet.bulk_create` to crash\n+ when introspecting the connection on SQLite (:ticket:`36818`)." }, { "filename": "tests/backends/sqlite/test_features.py", "status": "modified", "additions": 11, "deletions": 0, "changes": 11, "patch": "@@ -1,3 +1,4 @@\n+import copy\n import sqlite3\n from unittest import mock, skipUnless\n \n@@ -29,3 +30,13 @@ def test_max_query_params_respects_variable_limit(self):\n finally:\n connection.connection.setlimit(limit_name, current_limit)\n self.assertEqual(connection.features.max_query_params, current_limit)\n+\n+ def test_max_query_params_without_established_connection(self):\n+ new_connection = connection.copy()\n+ new_connection.settings_dict = copy.deepcopy(connection.settings_dict)\n+ self.assertIsNone(new_connection.connection)\n+ try:\n+ result = new_connection.features.max_query_params\n+ self.assertIsInstance(result, int)\n+ finally:\n+ new_connection._close()" } ], "reviews": [ { "id": 3604722222, "user": "user_cdda8932ec17", "state": "COMMENTED", "body": null, "submitted_at": "2025-12-22T16:16:01+00:00" }, { "id": 3604901241, "user": "user_cdda8932ec17", "state": "COMMENTED", "body": null, "submitted_at": "2025-12-22T17:08:25+00:00" }, { "id": 3604930609, "user": "user_efaa7460429a", "state": "COMMENTED", "body": null, "submitted_at": "2025-12-22T17:15:43+00:00" }, { "id": 3604937107, "user": "user_cdda8932ec17", "state": "APPROVED", "body": "Thanks for PR [USER_REDACTED], really appreciated!\n\nFeel free to add yourself to `AUTHORS` if you'd like to, I'll mark the patch as RFC.", "submitted_at": "2025-12-22T17:17:22+00:00" }, { "id": 3605464349, "user": "user_3a67c55598c5", "state": "COMMENTED", "body": null, "submitted_at": "2025-12-22T19:36:53+00:00" }, { "id": 3606198477, "user": "user_efaa7460429a", "state": "COMMENTED", "body": null, "submitted_at": "2025-12-23T01:03:10+00:00" }, { "id": 3606239904, "user": "user_3a67c55598c5", "state": "APPROVED", "body": "Thanks 👍", "submitted_at": "2025-12-23T01:30:08+00:00" } ], "review_comments": [ { "id": 2640428474, "user": "user_cdda8932ec17", "body": "Refer to 358fd21c47cdf7bda520ce73c5cfd82bba57827b and where the original test was added in `tests/backends/sqlite/test_features.py`.\n\nThe way this is currently defined the test is running on all backend when it should be SQLite specific.\n\nhttps://github.com/[USER_REDACTED]ngo/django/commit/358fd21c47cdf7bda520ce73c5cfd82bba57827b#diff-bcc4842c09fdfbe9666b5d295f56846226e72148b015e0c19d4fc4ebd570b202R14-R22", "path": "tests/backends/tests.py", "line": null, "side": "RIGHT", "created_at": "2025-12-22T16:16:00+00:00" }, { "id": 2640565587, "user": "user_cdda8932ec17", "body": "```suggestion\n* Fixed a regression in Django 6.0 that caused\n :meth:`~django.db.models.query.QuerySet.bulk_create` to crash\n when introspecting the connection on SQLite (:ticket:`36818`).\n```\n\nThe problem is not only present if it's the first operation after `django.setup` as we also close connections between requests and the code was not ensuring the connection was opened either.", "path": "docs/releases/6.0.1.txt", "line": null, "side": "RIGHT", "created_at": "2025-12-22T17:08:25+00:00" }, { "id": 2640587515, "user": "user_efaa7460429a", "body": "Updated the release notes as suggested.", "path": "docs/releases/6.0.1.txt", "line": null, "side": "RIGHT", "created_at": "2025-12-22T17:15:43+00:00" }, { "id": 2641021306, "user": "user_3a67c55598c5", "body": "I'm getting the following, when using an in-memory database:\n\n```py\nResourceWarning: unclosed database in \n```\nIt goes away with:\n```suggestion\n new_connection._close()\n```", "path": "tests/backends/sqlite/test_features.py", "line": null, "side": "RIGHT", "created_at": "2025-12-22T19:36:54+00:00" }, { "id": 2641632711, "user": "user_efaa7460429a", "body": "Thanks for the suggestion. I've updated the code to use `_close()` to ensure the underlying connection is properly closed in all environments.", "path": "tests/backends/sqlite/test_features.py", "line": null, "side": "RIGHT", "created_at": "2025-12-23T01:03:10+00:00" } ], "meta": { "languages": [ "py", "txt" ], "touches_tests": true, "review_state_summary": { "COMMENTED": 5, "APPROVED": 2 }, "meaningful_comment_count": 5, "has_approval": true, "has_changes_requested": false, "total_review_comments": 5 } } { "_id": "2db924b91f6551ba", "_schema_version": "1.0", "_cleaned_at": "2026-02-12T07:46:51.577805+00:00", "repo": "django/django", "repo_url": "https://github.com/django/django", "license_name": "BSD 3-Clause \"New\" or \"Revised\" License", "license_spdx": "BSD-3-Clause", "pr_number": 20437, "title": "Fixed #36787 -- Fixed crash in In lookups with mixed expressions and strings.", "body": "#### Trac ticket number\n\n\nticket-36787\n\nThank you for providing the test code, [USER_REDACTED] \n\n#### Checklist\n- [x] This PR targets the `main` branch. \n- [x] The commit message is written in past tense, mentions the ticket number, and ends with a period.\n- [x] I have checked the \"Has patch\" ticket flag in the Trac system.\n- [x] I have added or updated relevant tests.\n- [ ] I have added or updated relevant docs, including release notes if applicable.\n- [ ] I have attached screenshots in both light and dark modes for any UI changes.", "author": "user_ed8298a0306d", "created_at": "2025-12-21T13:38:38+00:00", "merged_at": "2025-12-22T19:25:45+00:00", "base_branch": "main", "head_branch": "ticket-36787", "additions": 9, "deletions": 1, "changed_files": 2, "files": [ { "filename": "django/db/models/lookups.py", "status": "modified", "additions": 1, "deletions": 1, "changes": 2, "patch": "@@ -295,7 +295,7 @@ def get_prep_lookup(self):\n (\n value\n if hasattr(value, \"resolve_expression\")\n- else Value(value, self.lhs.output_field)\n+ else Value(value, getattr(self.lhs, \"output_field\", None))\n )\n for value in self.rhs\n ]" }, { "filename": "tests/lookup/tests.py", "status": "modified", "additions": 8, "deletions": 0, "changes": 8, "patch": "@@ -1855,6 +1855,14 @@ def test_in_lookup_in_filter(self):\n Season.objects.filter(In(F(\"year\"), years)).order_by(\"pk\"), seasons\n )\n \n+ def test_in_lookup_in_filter_text_field(self):\n+ self.assertSequenceEqual(\n+ Season.objects.filter(\n+ In(F(\"nulled_text_field\"), [F(\"nulled_text_field\"), \"special_value\"])\n+ ),\n+ [self.s2],\n+ )\n+\n def test_filter_lookup_lhs(self):\n qs = Season.objects.annotate(before_20=LessThan(F(\"year\"), 2000)).filter(\n before_20=LessThan(F(\"year\"), 1900)," } ], "reviews": [ { "id": 3604310626, "user": "user_3a67c55598c5", "state": "APPROVED", "body": "Thank you!", "submitted_at": "2025-12-22T14:33:17+00:00" }, { "id": 3609305095, "user": "user_5501cd6d3dc8", "state": "COMMENTED", "body": null, "submitted_at": "2025-12-23T20:55:32+00:00" } ], "review_comments": [ { "id": 2644244696, "user": "user_5501cd6d3dc8", "body": "This test crashes on Oracle because blob fields (e.g. `NCLOB`) are not allowed in the `IN()` clause. As far as I'm aware `TextFields` are unnecessary here, see #20453.", "path": "tests/lookup/tests.py", "line": 1864, "side": "RIGHT", "created_at": "2025-12-23T20:55:32+00:00" } ], "meta": { "languages": [ "py" ], "touches_tests": true, "review_state_summary": { "APPROVED": 1, "COMMENTED": 1 }, "meaningful_comment_count": 1, "has_approval": true, "has_changes_requested": false, "total_review_comments": 1 } } { "_id": "6804ccd8191289b9", "_schema_version": "1.0", "_cleaned_at": "2026-02-12T07:46:51.577805+00:00", "repo": "django/django", "repo_url": "https://github.com/django/django", "license_name": "BSD 3-Clause \"New\" or \"Revised\" License", "license_spdx": "BSD-3-Clause", "pr_number": 20422, "title": "Fixed #36376 -- Fixed color suppression in argparse help on Python 3.14+.", "body": "#### Trac ticket number\n\n\nticket-36376\n\n#### Branch description\nThis adds the argparse's colorized help feature for Django management commands when running on Python 3.14 or higher as suggested in the above mentioned ticket.\n\n#### Checklist\n- [x] This PR targets the `main` branch. \n- [x] The commit message is written in past tense, mentions the ticket number, and ends with a period.\n- [x] I have checked the \"Has patch\" ticket flag in the Trac system.\n- [x] I have added or updated relevant tests.\n- [x] I have added or updated relevant docs, including release notes if applicable.\n- [ ] I have attached screenshots in both light and dark modes for any UI changes.", "author": "user_f5eee7dbaa84", "created_at": "2025-12-18T11:13:05+00:00", "merged_at": "2025-12-22T19:02:21+00:00", "base_branch": "main", "head_branch": "fix36376", "additions": 40, "deletions": 3, "changed_files": 4, "files": [ { "filename": "django/core/management/base.py", "status": "modified", "additions": 5, "deletions": 2, "changes": 7, "patch": "@@ -58,8 +58,11 @@ def __init__(\n ):\n self.missing_args_message = missing_args_message\n self.called_from_command_line = called_from_command_line\n- if PY314 and not PY315:\n- kwargs.setdefault(\"suggest_on_error\", True)\n+ if PY314:\n+ if not PY315:\n+ kwargs.setdefault(\"suggest_on_error\", True)\n+ if os.environ.get(\"DJANGO_COLORS\") == \"nocolor\" or \"--no-color\" in sys.argv:\n+ kwargs.setdefault(\"color\", False)\n super().__init__(**kwargs)\n \n def parse_args(self, args=None, namespace=None):" }, { "filename": "docs/releases/5.2.10.txt", "status": "modified", "additions": 3, "deletions": 1, "changes": 4, "patch": "@@ -9,4 +9,6 @@ Django 5.2.10 fixes several bugs in 5.2.9.\n Bugfixes\n ========\n \n-* ...\n+* Fixed a bug where management command colorized help (introduced in\n+ Python 3.14) ignored the :option:`--no-color` option and the\n+ :envvar:`DJANGO_COLORS` setting (:ticket:`36376`)." }, { "filename": "docs/releases/6.0.1.txt", "status": "modified", "additions": 4, "deletions": 0, "changes": 4, "patch": "@@ -16,3 +16,7 @@ Bugfixes\n * Fixed a regression in Django 6.0 that prevented changing the name of a\n :class:`~django.db.models.ManyToManyField` from taking effect when applying\n migrations (:ticket:`36800`).\n+\n+* Fixed a bug where management command colorized help (introduced in\n+ Python 3.14) ignored the :option:`--no-color` option and the\n+ :envvar:`DJANGO_COLORS` setting (:ticket:`36376`)." }, { "filename": "tests/user_commands/tests.py", "status": "modified", "additions": 28, "deletions": 0, "changes": 28, "patch": "@@ -470,6 +470,34 @@ def test_suggest_on_error_explicit_false(self):\n )\n self.assertFalse(parser.suggest_on_error)\n \n+ [USER_REDACTED].skipUnless(PY314, \"Only relevant for Python 3.14+\")\n+ def test_color_enabled_by_default(self):\n+ with mock.patch.dict(os.environ, {}, clear=True):\n+ command = BaseCommand()\n+ parser = command.create_parser(\"prog_name\", \"subcommand\")\n+ self.assertTrue(parser.color)\n+\n+ [USER_REDACTED].skipUnless(PY314, \"Only relevant for Python 3.14+\")\n+ def test_color_disabled_with_django_colors_nocolor(self):\n+ with mock.patch.dict(os.environ, {\"DJANGO_COLORS\": \"nocolor\"}):\n+ command = BaseCommand()\n+ parser = command.create_parser(\"prog_name\", \"subcommand\")\n+ self.assertFalse(parser.color)\n+\n+ [USER_REDACTED].skipUnless(PY314, \"Only relevant for Python 3.14+\")\n+ def test_force_color_does_not_affect_argparse_color(self):\n+ with mock.patch.dict(os.environ, {}, clear=True):\n+ command = BaseCommand(force_color=True)\n+ parser = command.create_parser(\"prog_name\", \"subcommand\")\n+ self.assertTrue(parser.color)\n+\n+ [USER_REDACTED].skipUnless(PY314, \"Only relevant for Python 3.14+\")\n+ def test_no_color_flag_disables_color(self):\n+ with mock.patch.object(sys, \"argv\", [\"manage.py\", \"mycommand\", \"--no-color\"]):\n+ command = BaseCommand()\n+ parser = command.create_parser(\"manage.py\", \"mycommand\")\n+ self.assertFalse(parser.color)\n+\n \n class CommandRunTests(AdminScriptTestCase):\n \"\"\"" } ], "reviews": [ { "id": 3599771481, "user": "user_3a67c55598c5", "state": "COMMENTED", "body": "Thanks [USER_REDACTED] 🎁 \n\nI left a comment on the ticket about how this has now morphed into a bugfix since the ticket was opened. Could you address the feedback and add a release note for 6.0.1.txt?", "submitted_at": "2025-12-19T19:54:02+00:00" }, { "id": 3601168177, "user": "user_f5eee7dbaa84", "state": "COMMENTED", "body": null, "submitted_at": "2025-12-20T16:09:53+00:00" }, { "id": 3604586999, "user": "user_3a67c55598c5", "state": "COMMENTED", "body": "Thanks for the updates, this looks really good. Only some very minor feedback for you.", "submitted_at": "2025-12-22T16:10:39+00:00" }, { "id": 3605081597, "user": "user_3a67c55598c5", "state": "COMMENTED", "body": null, "submitted_at": "2025-12-22T17:49:13+00:00" }, { "id": 3605112538, "user": "user_3a67c55598c5", "state": "COMMENTED", "body": null, "submitted_at": "2025-12-22T17:55:45+00:00" }, { "id": 3605164148, "user": "user_f5eee7dbaa84", "state": "COMMENTED", "body": null, "submitted_at": "2025-12-22T18:07:32+00:00" }, { "id": 3605299220, "user": "user_3a67c55598c5", "state": "COMMENTED", "body": null, "submitted_at": "2025-12-22T18:47:07+00:00" }, { "id": 3605299681, "user": "user_3a67c55598c5", "state": "APPROVED", "body": null, "submitted_at": "2025-12-22T18:47:13+00:00" } ], "review_comments": [ { "id": 2636058702, "user": "user_3a67c55598c5", "body": "When the docstrings communicate the same information as the method names we chop them.", "path": "tests/user_commands/tests.py", "line": null, "side": "RIGHT", "created_at": "2025-12-19T19:25:31+00:00" }, { "id": 2636073803, "user": "user_3a67c55598c5", "body": "```suggestion\n```\nI don't think we need to bother; color is already True by [NAME_REDACTED]://github.com/python/cpython/pull/136809 (3.14)", "path": "django/core/management/base.py", "line": null, "side": "RIGHT", "created_at": "2025-12-19T19:31:45+00:00" }, { "id": 2636085507, "user": "user_3a67c55598c5", "body": "This environment variable hasn't been set yet; we also need to check for an incoming ``--no-color`` argument instead. Please add a test.", "path": "django/core/management/base.py", "line": null, "side": "RIGHT", "created_at": "2025-12-19T19:35:45+00:00" }, { "id": 2636096455, "user": "user_3a67c55598c5", "body": "I think we can remove this; this is more of a bugfix that we need to respect `--no-color` on python 3.14.", "path": "docs/releases/6.1.txt", "line": null, "side": "RIGHT", "created_at": "2025-12-19T19:40:36+00:00" }, { "id": 2637195075, "user": "user_f5eee7dbaa84", "body": "Point noted.", "path": "tests/user_commands/tests.py", "line": null, "side": "RIGHT", "created_at": "2025-12-20T16:09:53+00:00" }, { "id": 2640317786, "user": "user_3a67c55598c5", "body": "Great -- please duplicate this in 5.2.10.txt.", "path": "docs/releases/6.0.1.txt", "line": null, "side": "RIGHT", "created_at": "2025-12-22T15:42:29+00:00" }, { "id": 2640394776, "user": "user_3a67c55598c5", "body": "Very minor: I'd use \"manage.py\" and \"mycommand\" to match the mock.", "path": "tests/user_commands/tests.py", "line": null, "side": "RIGHT", "created_at": "2025-12-22T16:02:55+00:00" }, { "id": 2640395530, "user": "user_3a67c55598c5", "body": "I'd make all 4 assertions use either assertIs or not.", "path": "tests/user_commands/tests.py", "line": null, "side": "RIGHT", "created_at": "2025-12-22T16:03:12+00:00" }, { "id": 2640408428, "user": "user_3a67c55598c5", "body": "I think we should mention management commands up front, although it's fine to mention argparse in here.", "path": "docs/releases/6.0.1.txt", "line": null, "side": "RIGHT", "created_at": "2025-12-22T16:07:38+00:00" }, { "id": 2640716711, "user": "user_3a67c55598c5", "body": "Sorry I wasn't super clear -- we need a release note in both 5.2.10.txt and 6.0.1.txt.", "path": "docs/releases/5.2.10.txt", "line": null, "side": "RIGHT", "created_at": "2025-12-22T17:49:13+00:00" }, { "id": 2640735716, "user": "user_3a67c55598c5", "body": "Also, \"management command\" isn't a code literal, so please avoid backticks.", "path": "docs/releases/5.2.10.txt", "line": null, "side": "RIGHT", "created_at": "2025-12-22T17:55:45+00:00" }, { "id": 2640770270, "user": "user_f5eee7dbaa84", "body": "My bad , fixed it !", "path": "docs/releases/5.2.10.txt", "line": null, "side": "RIGHT", "created_at": "2025-12-22T18:07:31+00:00" }, { "id": 2640882791, "user": "user_3a67c55598c5", "body": "No worries, thank you!", "path": "docs/releases/5.2.10.txt", "line": null, "side": "RIGHT", "created_at": "2025-12-22T18:47:07+00:00" } ], "meta": { "languages": [ "py", "txt" ], "touches_tests": true, "review_state_summary": { "COMMENTED": 7, "APPROVED": 1 }, "meaningful_comment_count": 13, "has_approval": true, "has_changes_requested": false, "total_review_comments": 13 } } { "_id": "1a93af7804af2f37", "_schema_version": "1.0", "_cleaned_at": "2026-02-12T07:46:51.593428+00:00", "repo": "django/django", "repo_url": "https://github.com/django/django", "license_name": "BSD 3-Clause \"New\" or \"Revised\" License", "license_spdx": "BSD-3-Clause", "pr_number": 20420, "title": "Fixed #36786 -- Fixed XML serialization of None values in natural keys.", "body": "#### Trac ticket number\n\n\n[ticket-36786](https://code.djangoproject.com/ticket/36786)\n\n#### Branch description\n\n**AS-IS**:\n- `None` values in natural keys were serialized as the string `\"None\"`, causing deserialization to fail.\n\n**TO-BE**\n- `None` values are serialized as `` elements, consistent with how regular fields handle `None`.\n\n**Before**\n```python\n# Check for None first - but this matches inside tags too!\nif node.getElementsByTagName(\"None\"):\n return None\nelse:\n ...\n keys = node.getElementsByTagName(\"natural\")\n if keys:\n field_value = [getInnerText(k).strip() for k in keys]\n```\n\nAfter\n\n```python\nnatural_keys = node.getElementsByTagName(\"natural\")\nif node.getElementsByTagName(\"None\") and not natural_keys:\n return None\nelse:\n ...\n if natural_keys:\n field_value = []\n for k in natural_keys:\n if k.getElementsByTagName(\"None\"):\n field_value.append(None)\n else:\n field_value.append(getInnerText(k).strip())\n```\n\n#### Checklist\n- [x] This PR targets the `main` branch. \n- [x] The commit message is written in past tense, mentions the ticket number, and ends with a period.\n- [x] I have checked the \"Has patch\" ticket flag in the Trac system.\n- [x] I have added or updated relevant tests.\n- [ ] I have added or updated relevant docs, including release notes if applicable.\n- [ ] I have attached screenshots in both light and dark modes for any UI changes.", "author": "user_5b5558b13564", "created_at": "2025-12-18T04:54:53+00:00", "merged_at": "2025-12-22T19:21:01+00:00", "base_branch": "main", "head_branch": "ticket_36786", "additions": 127, "deletions": 9, "changed_files": 3, "files": [ { "filename": "django/core/serializers/xml_serializer.py", "status": "modified", "additions": 33, "deletions": 9, "changes": 42, "patch": "@@ -134,7 +134,10 @@ def handle_fk_field(self, obj, field):\n # Iterable natural keys are rolled out as subelements\n for key_value in natural_key_value:\n self.xml.startElement(\"natural\", {})\n- self.xml.characters(str(key_value))\n+ if key_value is None:\n+ self.xml.addQuickElement(\"None\")\n+ else:\n+ self.xml.characters(str(key_value))\n self.xml.endElement(\"natural\")\n else:\n self.xml.characters(str(related_att))\n@@ -160,7 +163,10 @@ def handle_m2m(value):\n self.xml.startElement(\"object\", {})\n for key_value in natural:\n self.xml.startElement(\"natural\", {})\n- self.xml.characters(str(key_value))\n+ if key_value is None:\n+ self.xml.addQuickElement(\"None\")\n+ else:\n+ self.xml.characters(str(key_value))\n self.xml.endElement(\"natural\")\n self.xml.endElement(\"object\")\n else:\n@@ -279,7 +285,11 @@ def _handle_object(self, node):\n if value == base.DEFER_FIELD:\n deferred_fields[field] = [\n [\n- getInnerText(nat_node).strip()\n+ (\n+ None\n+ if nat_node.getElementsByTagName(\"None\")\n+ else getInnerText(nat_node).strip()\n+ )\n for nat_node in obj_node.getElementsByTagName(\"natural\")\n ]\n for obj_node in field_node.getElementsByTagName(\"object\")\n@@ -292,7 +302,11 @@ def _handle_object(self, node):\n value = self._handle_fk_field_node(field_node, field)\n if value == base.DEFER_FIELD:\n deferred_fields[field] = [\n- getInnerText(k).strip()\n+ (\n+ None\n+ if k.getElementsByTagName(\"None\")\n+ else getInnerText(k).strip()\n+ )\n for k in field_node.getElementsByTagName(\"natural\")\n ]\n else:\n@@ -317,16 +331,21 @@ def _handle_fk_field_node(self, node, field):\n Handle a node for a ForeignKey\n \"\"\"\n # Check if there is a child node named 'None', returning None if so.\n- if node.getElementsByTagName(\"None\"):\n+ natural_keys = node.getElementsByTagName(\"natural\")\n+ if node.getElementsByTagName(\"None\") and not natural_keys:\n return None\n else:\n model = field.remote_field.model\n if hasattr(model._default_manager, \"get_by_natural_key\"):\n- keys = node.getElementsByTagName(\"natural\")\n- if keys:\n+ if natural_keys:\n # If there are 'natural' subelements, it must be a natural\n # key\n- field_value = [getInnerText(k).strip() for k in keys]\n+ field_value = []\n+ for k in natural_keys:\n+ if k.getElementsByTagName(\"None\"):\n+ field_value.append(None)\n+ else:\n+ field_value.append(getInnerText(k).strip())\n try:\n obj = model._default_manager.db_manager(\n self.db\n@@ -367,7 +386,12 @@ def m2m_convert(n):\n if keys:\n # If there are 'natural' subelements, it must be a natural\n # key\n- field_value = [getInnerText(k).strip() for k in keys]\n+ field_value = []\n+ for k in keys:\n+ if k.getElementsByTagName(\"None\"):\n+ field_value.append(None)\n+ else:\n+ field_value.append(getInnerText(k).strip())\n obj_pk = (\n default_manager.db_manager(self.db)\n .get_by_natural_key(*field_value)" }, { "filename": "tests/serializers/models/natural.py", "status": "modified", "additions": 28, "deletions": 0, "changes": 28, "patch": "@@ -91,3 +91,31 @@ class PostToOptOutSubclassUser(models.Model):\n subscribers = models.ManyToManyField(\n SubclassNaturalKeyOptOutUser, related_name=\"subscribed_posts\", blank=True\n )\n+\n+\n+class NaturalKeyWithNullableFieldManager(models.Manager):\n+ def get_by_natural_key(self, name, optional_id):\n+ return self.get(name=name, optional_id=optional_id)\n+\n+\n+class NaturalKeyWithNullableField(models.Model):\n+ name = models.CharField(max_length=100)\n+ optional_id = models.CharField(max_length=100, null=True, blank=True)\n+\n+ objects = NaturalKeyWithNullableFieldManager()\n+\n+ class Meta:\n+ unique_together = [[\"name\", \"optional_id\"]]\n+\n+ def natural_key(self):\n+ return (self.name, self.optional_id)\n+\n+\n+class FKToNaturalKeyWithNullable(models.Model):\n+ ref = models.ForeignKey(\n+ NaturalKeyWithNullableField, on_delete=models.CASCADE, null=True\n+ )\n+ refs = models.ManyToManyField(\n+ NaturalKeyWithNullableField, related_name=\"m2m_referrers\"\n+ )\n+ data = models.CharField(max_length=100, default=\"\")" }, { "filename": "tests/serializers/test_natural.py", "status": "modified", "additions": 66, "deletions": 0, "changes": 66, "patch": "@@ -6,8 +6,10 @@\n Child,\n FKAsPKNoNaturalKey,\n FKDataNaturalKey,\n+ FKToNaturalKeyWithNullable,\n NaturalKeyAnchor,\n NaturalKeyThing,\n+ NaturalKeyWithNullableField,\n NaturalPKWithDefault,\n PostToOptOutSubclassUser,\n SubclassNaturalKeyOptOutUser,\n@@ -280,6 +282,60 @@ def natural_key_opt_out_test(self, format):\n )\n \n \n+def nullable_natural_key_fk_test(self, format):\n+ target_with_none = NaturalKeyWithNullableField.objects.create(\n+ name=\"test_none\",\n+ optional_id=None,\n+ )\n+ target_with_value = NaturalKeyWithNullableField.objects.create(\n+ name=\"test_value\",\n+ optional_id=\"some_id\",\n+ )\n+ fk_to_none = FKToNaturalKeyWithNullable.objects.create(\n+ ref=target_with_none,\n+ data=\"points_to_none\",\n+ )\n+ fk_to_value = FKToNaturalKeyWithNullable.objects.create(\n+ ref=target_with_value,\n+ data=\"points_to_value\",\n+ )\n+ objects = [target_with_none, target_with_value, fk_to_none, fk_to_value]\n+ serialized = serializers.serialize(\n+ format,\n+ objects,\n+ use_natural_foreign_keys=True,\n+ use_natural_primary_keys=True,\n+ )\n+ objs = list(serializers.deserialize(format, serialized))\n+ self.assertEqual(objs[2].object.ref_id, target_with_none.pk)\n+ self.assertEqual(objs[3].object.ref_id, target_with_value.pk)\n+\n+\n+def nullable_natural_key_m2m_test(self, format):\n+ target_with_none = NaturalKeyWithNullableField.objects.create(\n+ name=\"test_none\",\n+ optional_id=None,\n+ )\n+ target_with_value = NaturalKeyWithNullableField.objects.create(\n+ name=\"test_value\",\n+ optional_id=\"some_id\",\n+ )\n+ m2m_obj = FKToNaturalKeyWithNullable.objects.create(data=\"m2m_test\")\n+ m2m_obj.refs.set([target_with_none, target_with_value])\n+ objects = [target_with_none, target_with_value, m2m_obj]\n+ serialized = serializers.serialize(\n+ format,\n+ objects,\n+ use_natural_foreign_keys=True,\n+ use_natural_primary_keys=True,\n+ )\n+ objs = list(serializers.deserialize(format, serialized))\n+ self.assertCountEqual(\n+ objs[2].m2m_data[\"refs\"],\n+ [target_with_none.pk, target_with_value.pk],\n+ )\n+\n+\n # Dynamically register tests for each serializer\n register_tests(\n NaturalKeySerializerTests,\n@@ -319,3 +375,13 @@ def natural_key_opt_out_test(self, format):\n \"test_%s_natural_key_opt_out\",\n natural_key_opt_out_test,\n )\n+register_tests(\n+ NaturalKeySerializerTests,\n+ \"test_%s_nullable_natural_key_fk\",\n+ nullable_natural_key_fk_test,\n+)\n+register_tests(\n+ NaturalKeySerializerTests,\n+ \"test_%s_nullable_natural_key_m2m\",\n+ nullable_natural_key_m2m_test,\n+)" } ], "reviews": [ { "id": 3600013397, "user": "user_3a67c55598c5", "state": "COMMENTED", "body": "Thanks -- especially appreciate the tests.\n\nMain feedback at this point is to just prioritize a smaller diff over what we might otherwise do if rewriting this from scratch.", "submitted_at": "2025-12-19T21:02:40+00:00" }, { "id": 3600792919, "user": "user_5b5558b13564", "state": "COMMENTED", "body": null, "submitted_at": "2025-12-20T06:31:15+00:00" }, { "id": 3600793022, "user": "user_5b5558b13564", "state": "COMMENTED", "body": null, "submitted_at": "2025-12-20T06:31:34+00:00" }, { "id": 3600793063, "user": "user_5b5558b13564", "state": "COMMENTED", "body": null, "submitted_at": "2025-12-20T06:31:45+00:00" }, { "id": 3600793089, "user": "user_5b5558b13564", "state": "COMMENTED", "body": null, "submitted_at": "2025-12-20T06:31:51+00:00" }, { "id": 3600793112, "user": "user_5b5558b13564", "state": "COMMENTED", "body": null, "submitted_at": "2025-12-20T06:31:56+00:00" }, { "id": 3604450136, "user": "user_3a67c55598c5", "state": "APPROVED", "body": "Thank you, looks great! 🎁", "submitted_at": "2025-12-22T15:10:22+00:00" } ], "review_comments": [ { "id": 2636227028, "user": "user_3a67c55598c5", "body": "I'd rewrite this as a for loop.", "path": "django/core/serializers/xml_serializer.py", "line": null, "side": "RIGHT", "created_at": "2025-12-19T20:31:49+00:00" }, { "id": 2636251555, "user": "user_3a67c55598c5", "body": "For the sake of having a much smaller diff, I would suggest leaving most of this where it was and just fix the condition. (e.g. lift up `keys = ...` and then check `... and not keys: return None`, perhaps improving the variable name `keys`).\n\nYour version has a terser if condition, but this code is touched so infrequently that I think we should prioritize a smaller diff and more understandable blames over more readable if conditions.", "path": "django/core/serializers/xml_serializer.py", "line": 323, "side": "LEFT", "created_at": "2025-12-19T20:41:23+00:00" }, { "id": 2636265959, "user": "user_3a67c55598c5", "body": "So my example of `UUIDField` on the ticket was just what I happened to be working with (and show a really nice validation problem when attempting the roundtrip). However, it's not very realistic as a member of a natural key (and doesn't work well with the yaml serializer). Could I ask you to try another field type?", "path": "tests/serializers/models/natural.py", "line": null, "side": "RIGHT", "created_at": "2025-12-19T20:47:16+00:00" }, { "id": 2636273458, "user": "user_3a67c55598c5", "body": "Do we need the saving part, or can we just assert against the unsaved object and still capture the underlying issue?", "path": "tests/serializers/test_natural.py", "line": null, "side": "RIGHT", "created_at": "2025-12-19T20:50:17+00:00" }, { "id": 2636274402, "user": "user_3a67c55598c5", "body": "You can remove these comments to blend in with the surrounding style.", "path": "tests/serializers/test_natural.py", "line": null, "side": "RIGHT", "created_at": "2025-12-19T20:50:42+00:00" }, { "id": 2636293382, "user": "user_3a67c55598c5", "body": "Great models -- trying your tests against main shows all kinds of nasty failures 👍", "path": "tests/serializers/models/natural.py", "line": 114, "side": "RIGHT", "created_at": "2025-12-19T20:59:48+00:00" }, { "id": 2636857672, "user": "user_5b5558b13564", "body": "Agreed, rewritten as a for loop.", "path": "django/core/serializers/xml_serializer.py", "line": null, "side": "RIGHT", "created_at": "2025-12-20T06:31:15+00:00" }, { "id": 2636857798, "user": "user_5b5558b13564", "body": "I tried to simplify the logic, but ended up making a bigger diff than needed. Your suggestion is the better approach.\nI've updated it.", "path": "django/core/serializers/xml_serializer.py", "line": 323, "side": "LEFT", "created_at": "2025-12-20T06:31:34+00:00" }, { "id": 2636857867, "user": "user_5b5558b13564", "body": "Agreed. Changed to `CharField` it's more generalizable across all serializers and aligns with other natural key fields in the test suite.\ne.g. (`NaturalKeyAnchor.data`, `NaturalKeyThing.key`).", "path": "tests/serializers/models/natural.py", "line": null, "side": "RIGHT", "created_at": "2025-12-20T06:31:45+00:00" }, { "id": 2636857926, "user": "user_5b5558b13564", "body": "From a serialization perspective, the responsibility is data transformation `save()` is a separate concern. I'll simplify the test. Thanks!", "path": "tests/serializers/test_natural.py", "line": null, "side": "RIGHT", "created_at": "2025-12-20T06:31:51+00:00" }, { "id": 2636857996, "user": "user_5b5558b13564", "body": "Thanks!", "path": "tests/serializers/models/natural.py", "line": 114, "side": "RIGHT", "created_at": "2025-12-20T06:31:56+00:00" } ], "meta": { "languages": [ "py" ], "touches_tests": true, "review_state_summary": { "COMMENTED": 6, "APPROVED": 1 }, "meaningful_comment_count": 10, "has_approval": true, "has_changes_requested": false, "total_review_comments": 11 } } { "_id": "13698cf55f33be35", "_schema_version": "1.0", "_cleaned_at": "2026-02-12T07:46:51.593428+00:00", "repo": "django/django", "repo_url": "https://github.com/django/django", "license_name": "BSD 3-Clause \"New\" or \"Revised\" License", "license_spdx": "BSD-3-Clause", "pr_number": 20418, "title": "Fixed #36807 -- Fixed form field alignment under
      in the admin.", "body": "#### Trac ticket number\nticket-36807\n\n#### Branch description\nIt isn't safe to set `display: flex` on `
      `, because on Safari, this interferes with `display: block` on child divs.\n\n[NAME_REDACTED] for the report.\n\nRegression in 4187da258fe212d494cb578a0bc2b52c4979ab95.\n\n#### Checklist\n- [x] This PR targets the `main` branch. \n- [x] The commit message is written in past tense, mentions the ticket number, and ends with a period.\n- [x] I have checked the \"Has patch\" ticket flag in the Trac system.\n- [x] I have added or updated relevant tests.\n- [x] I have added or updated relevant docs, including release notes if applicable.\n- [x] I have attached screenshots in both light and dark modes for any UI changes.\n\n#### Before\n\"file-upload-safari-before\"\n\n#### After (light)\n\"file-upload-safari-after\"\n\n#### After (dark)\n\"change-password-after-dark\"", "author": "user_3a67c55598c5", "created_at": "2025-12-17T14:45:14+00:00", "merged_at": "2025-12-23T02:04:01+00:00", "base_branch": "main", "head_branch": "jtw/fieldset", "additions": 12, "deletions": 10, "changed_files": 6, "files": [ { "filename": "django/contrib/admin/static/admin/css/forms.css", "status": "modified", "additions": 2, "deletions": 6, "changes": 8, "patch": "@@ -102,7 +102,7 @@ fieldset .inline-heading,\n }\n \n .aligned legend {\n- float: left;\n+ float: inline-start;\n }\n \n .aligned legend,\n@@ -148,15 +148,11 @@ form .aligned ul {\n }\n \n form .aligned div.radiolist {\n- display: inline-block;\n+ display: block;\n margin: 0;\n padding: 0;\n }\n \n-form .aligned fieldset div.help {\n- margin-left: 0;\n-}\n-\n form .aligned p.help,\n form .aligned div.help {\n margin-top: 0;" }, { "filename": "django/contrib/admin/static/admin/css/responsive.css", "status": "modified", "additions": 4, "deletions": 0, "changes": 4, "patch": "@@ -560,6 +560,10 @@ input[type=\"submit\"], button {\n margin-top: 5px;\n }\n \n+ form .aligned fieldset div.flex-container {\n+ display: unset;\n+ }\n+\n /* Related widget */\n \n .related-widget-wrapper {" }, { "filename": "django/contrib/admin/templates/admin/auth/user/change_password.html", "status": "modified", "additions": 1, "deletions": 1, "changes": 2, "patch": "@@ -40,7 +40,7 @@\n \n
      \n {{ form.usable_password.errors }}\n-
      {{ form.usable_password.legend_tag }} {{ form.usable_password }}
      \n+
      {{ form.usable_password.legend_tag }} {{ form.usable_password }}
      \n {% if form.usable_password.help_text %}\n
      \n

      {{ form.usable_password.help_text|safe }}

      " }, { "filename": "django/contrib/admin/templates/admin/includes/fieldset.html", "status": "modified", "additions": 1, "deletions": 1, "changes": 2, "patch": "@@ -11,7 +11,7 @@\n
      \n {% if line.fields|length == 1 %}{{ line.errors }}{% else %}
      {% endif %}\n {% for field in line %}\n- {% if field.is_fieldset %}
      {{ field.label_tag }}{% endif %}\n+ {% if field.is_fieldset %}{{ field.label_tag }}{% endif %}\n
      \n {% if not line.fields|length == 1 and not field.is_readonly %}{{ field.errors }}{% endif %}\n
      " }, { "filename": "docs/releases/6.0.1.txt", "status": "modified", "additions": 3, "deletions": 0, "changes": 3, "patch": "@@ -24,3 +24,6 @@ Bugfixes\n * Fixed a regression in Django 6.0 that caused\n :meth:`~django.db.models.query.QuerySet.bulk_create` to crash\n when introspecting the connection on SQLite (:ticket:`36818`).\n+\n+* Fixed a visual regression in Django 6.0 for admin form fields grouped under a\n+ ``
      `` in Safari (:ticket:`36807`)." }, { "filename": "tests/auth_tests/test_views.py", "status": "modified", "additions": 1, "deletions": 2, "changes": 3, "patch": "@@ -1555,8 +1555,7 @@ def test_user_with_usable_password_change_password(self):\n # Usable password field.\n self.assertContains(\n response,\n- '
      '\n- \"Password-based authentication:\",\n+ \"
      Password-based authentication:\",\n )\n # Submit buttons\n self.assertContains(response, '\n\nIt looks like a different `margin-left` is being applied for fieldsets. \n\n- #### On mobile viewports, `fieldset` fields seem to disappear entirely. \n\n\"Screenshot\n\nI’m wondering if this could be related to them not inheriting the available width from the parent container. \n\n- #### In RTL mode, the position of the legend in `fieldset` fields doesn’t seem to align with other fields.\n\n\"third_issue\"\n\nThis might be influenced by [NAME_REDACTED] `float: left`.", "submitted_at": "2025-12-18T01:44:15+00:00" }, { "id": 3596398494, "user": "user_45c2e5489720", "state": "COMMENTED", "body": "Thank you, Jacob 👍\n\nI think we’re very close, just a few more things to tweak.\n\nIn addition to the review comments I left, it also looks like the `width` of the `datetime` fields is reduced on mobile screens.\n\n\"Screenshot", "submitted_at": "2025-12-19T02:30:50+00:00" }, { "id": 3598742773, "user": "user_3a67c55598c5", "state": "COMMENTED", "body": null, "submitted_at": "2025-12-19T14:05:21+00:00" }, { "id": 3599169328, "user": "user_3a67c55598c5", "state": "COMMENTED", "body": null, "submitted_at": "2025-12-19T16:13:27+00:00" }, { "id": 3600557456, "user": "user_45c2e5489720", "state": "COMMENTED", "body": null, "submitted_at": "2025-12-20T01:20:29+00:00" }, { "id": 3600558758, "user": "user_45c2e5489720", "state": "APPROVED", "body": "🙌🙌🙌", "submitted_at": "2025-12-20T01:21:32+00:00" } ], "review_comments": [ { "id": 2633346806, "user": "user_45c2e5489720", "body": "Is there a particular reason why `inline-block` is used on the `flex-container` under `fieldset` 🤔\nBecause of `inline-block`, the M2M fields end up being narrower, and when the screen is at desktop size and the field itself is wide, the label and field layout differs from the previous layout.\n\n### m2m diff\n\n\"Screenshot\n\n## desktop screen diff\n\n\"Screenshot\n\nIf there’s no specific reason for this, it seems like it would be okay to remove it :)", "path": "django/contrib/admin/static/admin/css/forms.css", "line": null, "side": "RIGHT", "created_at": "2025-12-19T02:26:40+00:00" }, { "id": 2635207309, "user": "user_3a67c55598c5", "body": "I was trying to fix the mobile viewport issue, but good catch on the m2m impact. I'll try `display: unset`.", "path": "django/contrib/admin/static/admin/css/forms.css", "line": null, "side": "RIGHT", "created_at": "2025-12-19T14:05:21+00:00" }, { "id": 2635578348, "user": "user_3a67c55598c5", "body": "Actually, I just moved this selector into responsive.css", "path": "django/contrib/admin/static/admin/css/forms.css", "line": null, "side": "RIGHT", "created_at": "2025-12-19T16:13:27+00:00" }, { "id": 2636670049, "user": "user_45c2e5489720", "body": "`unset` seems like a good solution.", "path": "django/contrib/admin/static/admin/css/forms.css", "line": null, "side": "RIGHT", "created_at": "2025-12-20T01:20:29+00:00" } ], "meta": { "languages": [ "css", "html", "py", "txt" ], "touches_tests": true, "review_state_summary": { "COMMENTED": 5, "APPROVED": 1 }, "meaningful_comment_count": 4, "has_approval": true, "has_changes_requested": false, "total_review_comments": 4 } } { "_id": "a8d2933e380a3f9b", "_schema_version": "1.0", "_cleaned_at": "2026-02-12T07:46:51.593428+00:00", "repo": "django/django", "repo_url": "https://github.com/django/django", "license_name": "BSD 3-Clause \"New\" or \"Revised\" License", "license_spdx": "BSD-3-Clause", "pr_number": 20416, "title": "Fixed #36804 -- Fixed admin system check crash for missing models.", "body": "…f [NAME_REDACTED] was an issue while raising the `NotRegistered` exception in get_model_admin when a string was passed to it instead of a model class. Fixed it by [NAME_REDACTED] `isinstance`. Added a test for this too.\n\n#### Trac ticket number\n\n\nticket-36804\n\n#### Branch description\nHandles a string passed to the `get_model_admin` method of the `AdminSite` class (in cases where the `to` field of a `ForeignKey` is specified using a model name instead of a model class.\n\n#### Checklist\n- [x] This PR targets the `main` branch. \n- [x] The commit message is written in past tense, mentions the ticket number, and ends with a period.\n- [x] I have checked the \"Has patch\" ticket flag in the Trac system.\n- [x] I have added or updated relevant tests.\n- [ ] I have added or updated relevant docs, including release notes if applicable.\n- [ ] I have attached screenshots in both light and dark modes for any UI changes.", "author": "user_b90682908b9e", "created_at": "2025-12-16T17:53:02+00:00", "merged_at": "2026-01-12T13:46:22+00:00", "base_branch": "main", "head_branch": "ticket_36804", "additions": 29, "deletions": 1, "changed_files": 2, "files": [ { "filename": "django/contrib/admin/checks.py", "status": "modified", "additions": 7, "deletions": 1, "changes": 8, "patch": "@@ -236,14 +236,20 @@ def _check_autocomplete_fields_item(self, obj, field_name, label):\n id=\"admin.E038\",\n )\n try:\n+ if isinstance(field.remote_field.model, str):\n+ raise NotRegistered\n related_admin = obj.admin_site.get_model_admin(field.remote_field.model)\n except NotRegistered:\n+ # field.remote_field.model could be a string or a class.\n+ remote_model = getattr(\n+ field.remote_field.model, \"__name__\", field.remote_field.model\n+ )\n return [\n checks.Error(\n 'An admin for model \"%s\" has to be registered '\n \"to be referenced by %s.autocomplete_fields.\"\n % (\n- field.remote_field.model.__name__,\n+ remote_model,\n type(obj).__name__,\n ),\n obj=obj.__class__," }, { "filename": "tests/modeladmin/test_checks.py", "status": "modified", "additions": 22, "deletions": 0, "changes": 22, "patch": "@@ -1724,6 +1724,28 @@ class Admin(ModelAdmin):\n invalid_obj=Admin,\n )\n \n+ [USER_REDACTED]_apps(\"modeladmin\")\n+ def test_autocomplete_e039_unresolved_model(self):\n+ class UnresolvedForeignKeyModel(models.Model):\n+ unresolved = models.ForeignKey(\"missing.Model\", models.CASCADE)\n+\n+ class Meta:\n+ app_label = \"modeladmin\"\n+\n+ class Admin(ModelAdmin):\n+ autocomplete_fields = (\"unresolved\",)\n+\n+ self.assertIsInvalid(\n+ Admin,\n+ UnresolvedForeignKeyModel,\n+ msg=(\n+ 'An admin for model \"missing.Model\" has to be registered '\n+ \"to be referenced by Admin.autocomplete_fields.\"\n+ ),\n+ id=\"admin.E039\",\n+ invalid_obj=Admin,\n+ )\n+\n def test_autocomplete_e040(self):\n class NoSearchFieldsAdmin(ModelAdmin):\n pass" } ], "reviews": [ { "id": 3584352324, "user": "user_3a67c55598c5", "state": "APPROVED", "body": "Thank you ⭐", "submitted_at": "2025-12-16T18:05:43+00:00" }, { "id": 3584429650, "user": "user_3a67c55598c5", "state": "COMMENTED", "body": null, "submitted_at": "2025-12-16T18:25:24+00:00" }, { "id": 3584496808, "user": "user_b90682908b9e", "state": "COMMENTED", "body": null, "submitted_at": "2025-12-16T18:42:47+00:00" }, { "id": 3614344899, "user": "user_b90682908b9e", "state": "COMMENTED", "body": null, "submitted_at": "2025-12-27T14:59:38+00:00" }, { "id": 3616481772, "user": "user_3a67c55598c5", "state": "COMMENTED", "body": "Thanks. I think we can leave the other example as is unless there is a way to reach it.\n\nI left a possibility for you to consider to DRY this out, but we can also leave the explicitness of doing it twice if you prefer.", "submitted_at": "2025-12-29T18:37:21+00:00" }, { "id": 3617715990, "user": "user_b90682908b9e", "state": "COMMENTED", "body": null, "submitted_at": "2025-12-30T09:35:45+00:00" }, { "id": 3617716534, "user": "user_b90682908b9e", "state": "COMMENTED", "body": null, "submitted_at": "2025-12-30T09:35:54+00:00" }, { "id": 3641346726, "user": "user_3a67c55598c5", "state": "COMMENTED", "body": null, "submitted_at": "2026-01-08T21:14:10+00:00" }, { "id": 3647738864, "user": "user_b90682908b9e", "state": "COMMENTED", "body": null, "submitted_at": "2026-01-11T14:19:06+00:00" }, { "id": 3650846220, "user": "user_3a67c55598c5", "state": "APPROVED", "body": "Thank you ⭐", "submitted_at": "2026-01-12T13:45:46+00:00" } ], "review_comments": [ { "id": 2624299381, "user": "user_3a67c55598c5", "body": "Sorry, looking more closely I see that `get_model_admin` is documented to take a class, not a string. It might be better to solve this closer to the source of the erroring check, by checking `isinstance(..., str)` before calling `get_model_admin()`.", "path": "django/contrib/admin/sites.py", "line": null, "side": "RIGHT", "created_at": "2025-12-16T18:25:24+00:00" }, { "id": 2624357556, "user": "user_b90682908b9e", "body": "Makes sense. Will check and update soon.", "path": "django/contrib/admin/sites.py", "line": null, "side": "RIGHT", "created_at": "2025-12-16T18:42:47+00:00" }, { "id": 2649177008, "user": "user_b90682908b9e", "body": "The error came up when the `ForeignKey`'s `to` field was defined as a string, and the app was not registered. I have pushed a fix that checks the type before `get_model_admin` is called. I found that a similar call was made in `options.py`. Please let me know if it looks okay, will add regression tests if it does. Thanks!", "path": "django/contrib/admin/sites.py", "line": null, "side": "RIGHT", "created_at": "2025-12-27T14:59:37+00:00" }, { "id": 2651524728, "user": "user_3a67c55598c5", "body": "```suggestion\n raise NotRegistered\n```", "path": "django/contrib/admin/checks.py", "line": null, "side": "RIGHT", "created_at": "2025-12-29T18:30:42+00:00" }, { "id": 2651529567, "user": "user_3a67c55598c5", "body": "Then this could just be:\n```\ngetattr(field.remote_field.model, \"__name__\", field.remote_field.model)\n```\n... with a nice comment. But if this is too complex for your taste, we can leave the exploded version.", "path": "django/contrib/admin/checks.py", "line": null, "side": "RIGHT", "created_at": "2025-12-29T18:33:52+00:00" }, { "id": 2651533053, "user": "user_3a67c55598c5", "body": "I'm not sure this is realistic, wouldn't we have failed well before this?", "path": "django/contrib/admin/options.py", "line": null, "side": "RIGHT", "created_at": "2025-12-29T18:36:07+00:00" }, { "id": 2652607799, "user": "user_b90682908b9e", "body": "Hmm ok. I'll remove the change in this PR and check separately.", "path": "django/contrib/admin/options.py", "line": null, "side": "RIGHT", "created_at": "2025-12-30T09:35:45+00:00" }, { "id": 2652607995, "user": "user_b90682908b9e", "body": "Yeah this is much cleaner :) Will make this change.", "path": "django/contrib/admin/checks.py", "line": null, "side": "RIGHT", "created_at": "2025-12-30T09:35:53+00:00" }, { "id": 2673927890, "user": "user_3a67c55598c5", "body": "Yep, looks great! I pushed minor formatting edits to reduce space. Be sure to do a hard reset back several commits and then pull my latest changes.\n\nA regression test would be great, thanks.", "path": "django/contrib/admin/sites.py", "line": null, "side": "RIGHT", "created_at": "2026-01-08T21:14:10+00:00" }, { "id": 2679600843, "user": "user_b90682908b9e", "body": "Added the test", "path": "django/contrib/admin/sites.py", "line": null, "side": "RIGHT", "created_at": "2026-01-11T14:19:06+00:00" } ], "meta": { "languages": [ "py" ], "touches_tests": true, "review_state_summary": { "APPROVED": 2, "COMMENTED": 8 }, "meaningful_comment_count": 10, "has_approval": true, "has_changes_requested": false, "total_review_comments": 10 } } { "_id": "a47174b117e9df41", "_schema_version": "1.0", "_cleaned_at": "2026-02-12T07:46:51.593428+00:00", "repo": "django/django", "repo_url": "https://github.com/django/django", "license_name": "BSD 3-Clause \"New\" or \"Revised\" License", "license_spdx": "BSD-3-Clause", "pr_number": 20411, "title": "Fixed #36800 -- [NAME_REDACTED] renaming in BaseDatabaseSchemaEditor.alter_field().", "body": "Regression in f9a44cc0fac653f8e0c2ab1cdfb12b2cc5c63fc2, which removed column names from `ManyToManyField` instances but did not account for `attname` changes.\n\n[NAME_REDACTED] alias [USER_REDACTED] for the report.\n\n#### Trac ticket number\n\n\nticket-36800\n\n#### Checklist\n- [x] This PR targets the `main` branch. \n- [x] The commit message is written in past tense, mentions the ticket number, and ends with a period.\n- [x] I have checked the \"Has patch\" ticket flag in the Trac system.\n- [x] I have added or updated relevant tests.\n- [x] I have added or updated relevant docs, including release notes if applicable.", "author": "user_606ba1f2b93c", "created_at": "2025-12-15T21:41:43+00:00", "merged_at": "2025-12-16T22:45:35+00:00", "base_branch": "main", "head_branch": "ticket-36800", "additions": 50, "deletions": 4, "changed_files": 3, "files": [ { "filename": "django/db/backends/base/schema.py", "status": "modified", "additions": 12, "deletions": 4, "changes": 16, "patch": "@@ -1690,7 +1690,7 @@ def _field_should_be_altered(self, old_field, new_field, ignore=None):\n _, old_path, old_args, old_kwargs = old_field.deconstruct()\n _, new_path, new_args, new_kwargs = new_field.deconstruct()\n # Don't alter when:\n- # - changing only a field name\n+ # - changing only a field name (unless it's a many-to-many)\n # - changing an attribute that doesn't affect the schema\n # - changing an attribute in the provided set of ignored attributes\n # - adding only a db_column and the column name is not changed\n@@ -1708,19 +1708,27 @@ def _field_should_be_altered(self, old_field, new_field, ignore=None):\n ):\n old_kwargs.pop(\"to\", None)\n new_kwargs.pop(\"to\", None)\n- # db_default can take many form but result in the same SQL.\n+ # db_default can take many forms but result in the same SQL.\n if (\n old_kwargs.get(\"db_default\")\n and new_kwargs.get(\"db_default\")\n and self.db_default_sql(old_field) == self.db_default_sql(new_field)\n ):\n old_kwargs.pop(\"db_default\")\n new_kwargs.pop(\"db_default\")\n- return (\n+ if (\n old_field.concrete\n and new_field.concrete\n and (self.quote_name(old_field.column) != self.quote_name(new_field.column))\n- ) or (old_path, old_args, old_kwargs) != (new_path, new_args, new_kwargs)\n+ ):\n+ return True\n+ if (\n+ old_field.many_to_many\n+ and new_field.many_to_many\n+ and old_field.name != new_field.name\n+ ):\n+ return True\n+ return (old_path, old_args, old_kwargs) != (new_path, new_args, new_kwargs)\n \n def _field_should_be_indexed(self, model, field):\n return field.db_index and not field.unique" }, { "filename": "docs/releases/6.0.1.txt", "status": "modified", "additions": 4, "deletions": 0, "changes": 4, "patch": "@@ -12,3 +12,7 @@ Bugfixes\n * Fixed a regression in Django 6.0 where :ttag:`querystring` mishandled\n multi-value :class:`~django.http.QueryDict` keys, both by [NAME_REDACTED] value and by [NAME_REDACTED] ``None`` values (:ticket:`36783`).\n+\n+* Fixed a regression in Django 6.0 that prevented changing the name of a\n+ :class:`~django.db.models.ManyToManyField` from taking effect when applying\n+ migrations (:ticket:`36800`)." }, { "filename": "tests/schema/tests.py", "status": "modified", "additions": 34, "deletions": 0, "changes": 34, "patch": "@@ -2889,6 +2889,40 @@ def test_m2m_repoint_custom(self):\n def test_m2m_repoint_inherited(self):\n self._test_m2m_repoint(InheritedManyToManyField)\n \n+ def test_m2m_rename(self):\n+ class LocalBook(Model):\n+ authors = ManyToManyField(\"schema.Author\")\n+\n+ class Meta:\n+ app_label = \"schema\"\n+ apps = new_apps\n+\n+ self.local_models = [LocalBook]\n+ with connection.schema_editor() as editor:\n+ editor.create_model(Author)\n+ editor.create_model(LocalBook)\n+ old_field = LocalBook._meta.get_field(\"authors\")\n+ new_field = ManyToManyField(\"schema.Author\")\n+ new_field.contribute_to_class(LocalBook, \"writers\")\n+ with connection.schema_editor() as editor:\n+ editor.alter_field(LocalBook, old_field, new_field, strict=True)\n+ # Ensure old M2M is gone.\n+ with self.assertRaises(DatabaseError):\n+ self.column_classes(\n+ LocalBook._meta.get_field(\"authors\").remote_field.through\n+ )\n+ if connection.features.supports_foreign_keys:\n+ self.assertForeignKeyExists(\n+ new_field.remote_field.through,\n+ \"author_id\",\n+ \"schema_author\",\n+ )\n+ new_through_table = new_field.remote_field.through._meta.db_table\n+ self.assertIn(\"writers\", new_through_table)\n+ self.assertNotIn(\"authors\", new_through_table)\n+ # Remove the old field from meta for tearDown().\n+ LocalBook._meta.local_many_to_many.remove(old_field)\n+\n [USER_REDACTED]_apps(\"schema\")\n def test_m2m_rename_field_in_target_model(self):\n class LocalTagM2MTest(Model):" } ], "reviews": [ { "id": 3580372881, "user": "user_cdda8932ec17", "state": "COMMENTED", "body": "I think we'll want to adjust the comment that says\n\n```\n# - changing only a field name\n```\n\nOtherwise testing at the schema level looks more appropriate than what I did in #20412", "submitted_at": "2025-12-15T22:08:14+00:00" }, { "id": 3580412046, "user": "user_606ba1f2b93c", "state": "COMMENTED", "body": null, "submitted_at": "2025-12-15T22:18:44+00:00" }, { "id": 3580525881, "user": "user_3a67c55598c5", "state": "COMMENTED", "body": null, "submitted_at": "2025-12-15T23:10:08+00:00" }, { "id": 3583113234, "user": "user_3a67c55598c5", "state": "APPROVED", "body": "Perfect -- thanks [USER_REDACTED] and [USER_REDACTED] for the review.", "submitted_at": "2025-12-16T13:33:26+00:00" }, { "id": 3585178582, "user": "user_3a67c55598c5", "state": "APPROVED", "body": null, "submitted_at": "2025-12-16T22:14:18+00:00" } ], "review_comments": [ { "id": 2621016635, "user": "user_cdda8932ec17", "body": "Not sure why we're changing this.", "path": "django/db/backends/base/schema.py", "line": null, "side": "RIGHT", "created_at": "2025-12-15T22:05:14+00:00" }, { "id": 2621047456, "user": "user_606ba1f2b93c", "body": "Reverted 👍🏾. I'd changed it so it's easier to read.", "path": "django/db/backends/base/schema.py", "line": null, "side": "RIGHT", "created_at": "2025-12-15T22:18:44+00:00" }, { "id": 2621146065, "user": "user_3a67c55598c5", "body": "[USER_REDACTED] After having a look at #20412, do you have an opinion about how to factor this? I think the multiple returns helps readability.", "path": "django/db/backends/base/schema.py", "line": null, "side": "RIGHT", "created_at": "2025-12-15T23:10:08+00:00" } ], "meta": { "languages": [ "py", "txt" ], "touches_tests": true, "review_state_summary": { "COMMENTED": 3, "APPROVED": 2 }, "meaningful_comment_count": 3, "has_approval": true, "has_changes_requested": false, "total_review_comments": 3 } } { "_id": "e5a3d66b08a8e8a5", "_schema_version": "1.0", "_cleaned_at": "2026-02-12T07:46:51.593428+00:00", "repo": "django/django", "repo_url": "https://github.com/django/django", "license_name": "BSD 3-Clause \"New\" or \"Revised\" License", "license_spdx": "BSD-3-Clause", "pr_number": 20409, "title": "Refs #36769 -- [NAME_REDACTED] for unexpected nested tags in XML Deserializer.", "body": "#### Trac ticket number\nticket-36769\n\n#### Branch description\n[USER_REDACTED] observed that raising `SuspiciousOperation` would be preferable to silently discarding data from invalid fixtures in https://github.com/[USER_REDACTED]ngo/django/pull/20377#discussion_r2616789793.\n\n#### Checklist\n- [x] This PR targets the `main` branch. \n- [x] The commit message is written in past tense, mentions the ticket number, and ends with a period.\n- [ ] I have checked the \"Has patch\" ticket flag in the Trac system.\n- [x] I have added or updated relevant tests.\n- [ ] I have added or updated relevant docs, including release notes if applicable.\n- [ ] I have attached screenshots in both light and dark modes for any UI changes.", "author": "user_3a67c55598c5", "created_at": "2025-12-15T16:59:56+00:00", "merged_at": "2026-01-12T21:38:32+00:00", "base_branch": "main", "head_branch": "jtw/suspicious-xml", "additions": 69, "deletions": 73, "changed_files": 8, "files": [ { "filename": "django/core/serializers/xml_serializer.py", "status": "modified", "additions": 10, "deletions": 10, "changes": 20, "patch": "@@ -10,7 +10,7 @@\n \n from django.apps import apps\n from django.conf import settings\n-from django.core.exceptions import ObjectDoesNotExist\n+from django.core.exceptions import ObjectDoesNotExist, SuspiciousOperation\n from django.core.serializers import base\n from django.db import DEFAULT_DB_ALIAS, models\n from django.utils.xmlutils import SimplerXMLGenerator, UnserializableContentError\n@@ -411,6 +411,8 @@ def m2m_convert(n):\n try:\n for c in node.getElementsByTagName(\"object\"):\n values.append(m2m_convert(c))\n+ except SuspiciousOperation:\n+ raise\n except Exception as e:\n if isinstance(e, ObjectDoesNotExist) and self.handle_forward_references:\n return base.DEFER_FIELD\n@@ -439,17 +441,15 @@ def _get_model_from_node(self, node, attr):\n )\n \n \n+def check_element_type(element):\n+ if element.childNodes:\n+ raise SuspiciousOperation(f\"Unexpected element: {element.tagName!r}\")\n+ return element.nodeType in (element.TEXT_NODE, element.CDATA_SECTION_NODE)\n+\n+\n def getInnerText(node):\n- \"\"\"Get the inner text of a DOM node and any children one level deep.\"\"\"\n- # inspired by\n- # https://mail.python.org/pipermail/xml-sig/2005-March/011022.html\n return \"\".join(\n- [\n- element.data\n- for child in node.childNodes\n- for element in (child, *child.childNodes)\n- if element.nodeType in (element.TEXT_NODE, element.CDATA_SECTION_NODE)\n- ]\n+ [child.data for child in node.childNodes if check_element_type(child)]\n )" }, { "filename": "docs/releases/6.1.txt", "status": "modified", "additions": 4, "deletions": 0, "changes": 4, "patch": "@@ -303,6 +303,10 @@ Serialization\n ``()``. This ensures primary keys are serialized when using\n :option:`dumpdata --natural-primary`.\n \n+* The XML deserializer now raises\n+ :exc:`~django.core.exceptions.SuspiciousOperation` when it encounters\n+ unexpected nested tags.\n+\n Signals\n ~~~~~~~" }, { "filename": "docs/topics/serialization.txt", "status": "modified", "additions": 7, "deletions": 1, "changes": 8, "patch": "@@ -198,7 +198,8 @@ lowercase name of the model (\"session\") separated by a dot.\n \n Each field of the object is serialized as a ````-element sporting the\n fields \"type\" and \"name\". The text content of the element represents the value\n-that should be stored.\n+that should be stored. (If the element contains child tags,\n+:exc:`~django.core.exceptions.SuspiciousOperation` is raised.)\n \n Foreign keys and other relational fields are treated a little bit differently:\n \n@@ -237,6 +238,11 @@ This example links the given user with the permission models with PKs 46 and\n XHTML, XML and [NAME_REDACTED]\n `_.\n \n+.. versionchanged:: 6.1\n+\n+ :exc:`~django.core.exceptions.SuspiciousOperation` is raised when\n+ unexpected nested tags are found.\n+\n .. _serialization-formats-json:\n \n JSON" }, { "filename": "tests/fixtures/fixtures/fixture9.xml", "status": "modified", "additions": 3, "deletions": 3, "changes": 6, "patch": "@@ -1,7 +1,7 @@\n \n \n \n- \n+ \n [NAME_REDACTED]\n \n \n@@ -19,11 +19,11 @@\n \n \n \n- Artist formerly known as "Prince"\n+ Artist formerly known as "Prince"\n \n \n \n- \n+ \n Artist formerly known as "Prince"\n \n " }, { "filename": "tests/fixtures/fixtures/invalid_deeply_nested_elements.xml", "status": "modified", "additions": 2, "deletions": 1, "changes": 3, "patch": "@@ -3,7 +3,8 @@\n \n \n \n- Django pony\n+ \n+ Django pony\n \n " }, { "filename": "tests/fixtures/fixtures/invalid_deeply_nested_elements_natural_key.xml", "status": "added", "additions": 14, "deletions": 0, "changes": 14, "patch": "@@ -0,0 +1,14 @@\n+\n+\n+\n+ \n+ Music for all ages\n+ \n+ \n+ \n+ Artist formerly known as Prince\n+ \n+ \n+ \n+\n+" }, { "filename": "tests/fixtures/tests.py", "status": "modified", "additions": 8, "deletions": 7, "changes": 15, "patch": "@@ -10,6 +10,7 @@\n from django.apps import apps\n from django.contrib.sites.models import Site\n from django.core import management\n+from django.core.exceptions import SuspiciousOperation\n from django.core.files.temp import NamedTemporaryFile\n from django.core.management import CommandError\n from django.core.management.commands.dumpdata import ProxyModelWarning\n@@ -23,7 +24,6 @@\n CircularA,\n CircularB,\n NaturalKeyThing,\n- Person,\n PrimaryKeyUUIDModel,\n ProxySpy,\n Spy,\n@@ -522,12 +522,13 @@ def test_loading_and_dumping(self):\n )\n \n def test_deeply_nested_elements(self):\n- \"\"\"Text inside deeply-nested tags is skipped.\"\"\"\n- management.call_command(\n- \"loaddata\", \"invalid_deeply_nested_elements.xml\", verbosity=0\n- )\n- person = Person.objects.get(pk=1)\n- self.assertEqual(person.name, \"Django\") # not \"Django pony\"\n+ \"\"\"Text inside deeply-nested tags raises SuspiciousOperation.\"\"\"\n+ for file in [\n+ \"invalid_deeply_nested_elements.xml\",\n+ \"invalid_deeply_nested_elements_natural_key.xml\",\n+ ]:\n+ with self.subTest(file=file), self.assertRaises(SuspiciousOperation):\n+ management.call_command(\"loaddata\", file, verbosity=0)\n \n def test_dumpdata_with_excludes(self):\n # Load fixture1 which has a site, two articles, and a category" }, { "filename": "tests/serializers/test_deserialization.py", "status": "modified", "additions": 21, "deletions": 51, "changes": 72, "patch": "@@ -1,15 +1,14 @@\n import json\n-import time\n+import textwrap\n import unittest\n \n+from django.core.exceptions import SuspiciousOperation\n from django.core.serializers.base import DeserializationError, DeserializedObject\n from django.core.serializers.json import Deserializer as JsonDeserializer\n from django.core.serializers.jsonl import Deserializer as JsonlDeserializer\n from django.core.serializers.python import Deserializer\n from django.core.serializers.xml_serializer import Deserializer as XMLDeserializer\n-from django.db import models\n from django.test import SimpleTestCase\n-from django.test.utils import garbage_collect\n \n from .models import Author\n \n@@ -138,52 +137,23 @@ def test_yaml_bytes_input(self):\n self.assertEqual(first_item.object, self.jane)\n self.assertEqual(second_item.object, self.joe)\n \n- def test_crafted_xml_performance(self):\n- \"\"\"The time to process invalid inputs is not quadratic.\"\"\"\n-\n- def build_crafted_xml(depth, leaf_text_len):\n- nested_open = \"\" * depth\n- nested_close = \"\" * depth\n- leaf = \"x\" * leaf_text_len\n- field_content = f\"{nested_open}{leaf}{nested_close}\"\n- return f\"\"\"\n- \n- \n- {field_content}\n- m\n- \n- \n- \"\"\"\n-\n- def deserialize(crafted_xml):\n- iterator = XMLDeserializer(crafted_xml)\n- garbage_collect()\n-\n- start_time = time.perf_counter()\n- result = list(iterator)\n- end_time = time.perf_counter()\n-\n- self.assertEqual(len(result), 1)\n- self.assertIsInstance(result[0].object, models.Model)\n- return end_time - start_time\n-\n- def assertFactor(label, params, factor=2):\n- factors = []\n- prev_time = None\n- for depth, length in params:\n- crafted_xml = build_crafted_xml(depth, length)\n- elapsed = deserialize(crafted_xml)\n- if prev_time is not None:\n- factors.append(elapsed / prev_time)\n- prev_time = elapsed\n-\n- with self.subTest(label):\n- # Assert based on the average factor to reduce test flakiness.\n- self.assertLessEqual(sum(factors) / len(factors), factor)\n-\n- assertFactor(\n- \"varying depth, varying length\",\n- [(50, 2000), (100, 4000), (200, 8000), (400, 16000), (800, 32000)],\n- 2,\n+ def test_crafted_xml_rejected(self):\n+ depth = 100\n+ leaf_text_len = 1000\n+ nested_open = \"\" * depth\n+ nested_close = \"\" * depth\n+ leaf = \"x\" * leaf_text_len\n+ field_content = f\"{nested_open}{leaf}{nested_close}\"\n+ crafted_xml = textwrap.dedent(\n+ f\"\"\"\n+ \n+ \n+ {field_content}\n+ m\n+ \n+ \"\"\"\n )\n- assertFactor(\"constant depth, varying length\", [(100, 1), (100, 1000)], 2)\n+\n+ msg = \"Unexpected element: 'nested'\"\n+ with self.assertRaisesMessage(SuspiciousOperation, msg):\n+ list(XMLDeserializer(crafted_xml))" } ], "reviews": [ { "id": 3580512461, "user": "user_3a67c55598c5", "state": "COMMENTED", "body": null, "submitted_at": "2025-12-15T23:05:35+00:00" }, { "id": 3580530171, "user": "user_3a67c55598c5", "state": "COMMENTED", "body": null, "submitted_at": "2025-12-15T23:12:05+00:00" }, { "id": 3601247775, "user": "user_6d44402bb9ae", "state": "COMMENTED", "body": "Hi,\n\nThis seems not-yet-ready to me. Notes inside, some of taste and preference, but some of apparent correctness.", "submitted_at": "2025-12-20T21:47:53+00:00" }, { "id": 3601350887, "user": "user_3a67c55598c5", "state": "COMMENTED", "body": null, "submitted_at": "2025-12-20T22:23:01+00:00" }, { "id": 3601351542, "user": "user_3a67c55598c5", "state": "COMMENTED", "body": null, "submitted_at": "2025-12-20T22:24:05+00:00" }, { "id": 3601352749, "user": "user_3a67c55598c5", "state": "COMMENTED", "body": null, "submitted_at": "2025-12-20T22:25:14+00:00" }, { "id": 3604559683, "user": "user_3a67c55598c5", "state": "COMMENTED", "body": null, "submitted_at": "2025-12-22T15:36:18+00:00" }, { "id": 3635357776, "user": "user_3a67c55598c5", "state": "COMMENTED", "body": null, "submitted_at": "2026-01-07T15:11:55+00:00" }, { "id": 3636130898, "user": "user_00dac951cdbf", "state": "COMMENTED", "body": "Thank you! 🌟", "submitted_at": "2026-01-07T17:59:24+00:00" }, { "id": 3636760070, "user": "user_3a67c55598c5", "state": "COMMENTED", "body": null, "submitted_at": "2026-01-07T20:54:01+00:00" }, { "id": 3636814684, "user": "user_3a67c55598c5", "state": "COMMENTED", "body": null, "submitted_at": "2026-01-07T21:09:17+00:00" }, { "id": 3647144871, "user": "user_6d44402bb9ae", "state": "APPROVED", "body": "LGTM (up to [USER_REDACTED] 's test concerns). I see some issues, but they're out of scope for this PR.", "submitted_at": "2026-01-10T19:11:00+00:00" }, { "id": 3652435703, "user": "user_00dac951cdbf", "state": "APPROVED", "body": "This looks great, thank you [USER_REDACTED]! Added a minor ask, but I think this is good to go.", "submitted_at": "2026-01-12T19:41:18+00:00" } ], "review_comments": [ { "id": 2621134431, "user": "user_3a67c55598c5", "body": "I moved the `` key example to another file.", "path": "tests/fixtures/fixtures/invalid_deeply_nested_elements.xml", "line": 7, "side": "RIGHT", "created_at": "2025-12-15T23:03:16+00:00" }, { "id": 2621138310, "user": "user_3a67c55598c5", "body": "There might be another one of these to filter out and raise, e.g. in `save_deferred_fields()`.", "path": "django/core/serializers/xml_serializer.py", "line": null, "side": "RIGHT", "created_at": "2025-12-15T23:05:33+00:00" }, { "id": 2621149410, "user": "user_3a67c55598c5", "body": "Undecided between \"Node\" vs \"Tag\".", "path": "django/core/serializers/xml_serializer.py", "line": null, "side": "RIGHT", "created_at": "2025-12-15T23:12:05+00:00" }, { "id": 2637307610, "user": "user_6d44402bb9ae", "body": "I'd be more general, `SuspiciousXML` or even `SuspiciousSerialization`.\n\nBut note that, currently, AFAICT, all `SuspiciousOperation` child classes in the Django source are defined in `exceptions.py` files -- and except for those in `contrib` apps, all are in `django.core.exceptions`. I suspect we could do without a child class at all.", "path": "django/core/serializers/xml_serializer.py", "line": null, "side": "RIGHT", "created_at": "2025-12-20T20:12:11+00:00" }, { "id": 2637316329, "user": "user_6d44402bb9ae", "body": "Why give special treatment to `natural` nodes inside fields which aren't relation fields?", "path": "django/core/serializers/xml_serializer.py", "line": null, "side": "RIGHT", "created_at": "2025-12-20T20:24:01+00:00" }, { "id": 2637380214, "user": "user_6d44402bb9ae", "body": "This is a good idea IMO, but, regardless of whether we need a specific exception subclass for this fix, I'd go with\n```suggestion\n except SuspiciousOperation:\n```", "path": "django/core/serializers/xml_serializer.py", "line": null, "side": "RIGHT", "created_at": "2025-12-20T21:34:57+00:00" }, { "id": 2637385012, "user": "user_6d44402bb9ae", "body": "This doesn't look equivalent... the original took children and grandchildren, this drops grandchildren.", "path": "django/core/serializers/xml_serializer.py", "line": 452, "side": "RIGHT", "created_at": "2025-12-20T21:41:38+00:00" }, { "id": 2637387739, "user": "user_6d44402bb9ae", "body": "`build_crafted_xml` seems redundant as a function if it only gets called once. I'd simplify it away.", "path": "tests/serializers/test_deserialization.py", "line": null, "side": "RIGHT", "created_at": "2025-12-20T21:46:15+00:00" }, { "id": 2637409898, "user": "user_3a67c55598c5", "body": "Right, I should have left notes about this to aid the review. This change is possible _only_ in virtue of the other change you noticed, where I'm specializing `` nodes.\n\nThat's the only location where we need to drill two levels deep, e.g. from:\n\n```\n\n \n some content \n```\n\nGrandchild text nodes don't need to be visited if I instead call the helper on `` nodes. That dramatically simplifies checking for unexpected children.", "path": "django/core/serializers/xml_serializer.py", "line": 452, "side": "RIGHT", "created_at": "2025-12-20T22:23:01+00:00" }, { "id": 2637410265, "user": "user_3a67c55598c5", "body": "Elsewhere, `` nodes are interrogated when we _don't_ expect `` serialization, e.g.\n\n```\n\n some content \n```", "path": "django/core/serializers/xml_serializer.py", "line": 452, "side": "RIGHT", "created_at": "2025-12-20T22:24:05+00:00" }, { "id": 2637410877, "user": "user_3a67c55598c5", "body": "Thanks for the review. Sorry I didn't share more of my findings. I think throughout the serializer natural nodes are specialized. The ones that are relations, in the branches just before this, are specialized inside `_handle_m2m_field_node`. Unless I'm missing your meaning.", "path": "django/core/serializers/xml_serializer.py", "line": null, "side": "RIGHT", "created_at": "2025-12-20T22:25:14+00:00" }, { "id": 2640284799, "user": "user_3a67c55598c5", "body": "I checked again and couldn't find any other places to update.", "path": "django/core/serializers/xml_serializer.py", "line": null, "side": "RIGHT", "created_at": "2025-12-22T15:36:18+00:00" }, { "id": 2668852928, "user": "user_3a67c55598c5", "body": "See the subtest iteration in `test_deeply_nested_elements` testing one example with natural keys and one without.", "path": "tests/fixtures/fixtures/invalid_deeply_nested_elements.xml", "line": 7, "side": "RIGHT", "created_at": "2026-01-07T15:11:55+00:00" }, { "id": 2669527349, "user": "user_00dac951cdbf", "body": "[USER_REDACTED] I think the key point here is that `` is not limited to FK or M2M values. It can also appear on direct fields when those fields participate in the object's own natural key (e.g. fixtures produced with `dumpdata --natural-primary`, as Jacob patiently explained to me when we chatted). In that sense, handling `` outside the relation branches is expected, not special-casing.\n\nWith that understanding, the change looks good to me. The only remaining concern is test coverage: reverting this change (but leaving `getInnerText` as modified in this commit) would not currently cause any serializer tests to fail, so it would be good to see a few targeted tests added to lock this behavior in.", "path": "django/core/serializers/xml_serializer.py", "line": null, "side": "RIGHT", "created_at": "2026-01-07T17:57:58+00:00" }, { "id": 2669531527, "user": "user_00dac951cdbf", "body": "I guess `` is the exception here? as shown in https://github.com/[USER_REDACTED]ngo/django/blob/main/tests/fixtures/fixtures/fixture9.xml", "path": "docs/topics/serialization.txt", "line": 202, "side": "RIGHT", "created_at": "2026-01-07T17:58:57+00:00" }, { "id": 2670043573, "user": "user_3a67c55598c5", "body": "[USER_REDACTED] [USER_REDACTED] Thanks for pushing me to test my understanding here. I tried dumping fixture9, and noticed it was different from the `fixture9.xml` in the repo. Ouch.\n\nI think this all boils down to an invalid fixture. Upon correcting the fixture, I was able to remove this specialization.\n\n> In that sense, handling outside the relation branches is expected, not special-casing.\n\nI managed to talk [USER_REDACTED] into this when we we chatted, but it was wrong -- I think I was not prepared for the fixture to turn out to be invalid in *two* ways, not only whether or not `` should be present, but whether the definitions of the fields were to be trusted (missing `rel=ManyToOne...`).\n\nI wonder if it was just a copy-paste mistake in 35cc439.", "path": "django/core/serializers/xml_serializer.py", "line": null, "side": "RIGHT", "created_at": "2026-01-07T20:54:01+00:00" }, { "id": 2670082916, "user": "user_3a67c55598c5", "body": "Yeah. I'm not sure whether to detour into that here. Natural keys are explained below, I'm very hesitant to detour into it beforehand.", "path": "docs/topics/serialization.txt", "line": 202, "side": "RIGHT", "created_at": "2026-01-07T21:09:17+00:00" }, { "id": 2678907219, "user": "user_6d44402bb9ae", "body": "I've looked at that documentation, and I agree with [USER_REDACTED] -- I see no need to get into natural keys at this point.\n\nThat said, most of the examples there are given with JSON (understandably), and with JSON, you just use the value of the natural keys instead of the value of the PK -- there's no `\"natural\"` key or anything of the sort, to parallel the `` element. The docs say nothing of it, and they probably should. This should probably be treated as a separate issue.\n\n(on second thought, another thing to treat as a separate issue is -- do we really want to support XML serialization going forward?)", "path": "docs/topics/serialization.txt", "line": 202, "side": "RIGHT", "created_at": "2026-01-10T19:06:53+00:00" }, { "id": 2683642861, "user": "user_00dac951cdbf", "body": "Could we perhaps add a message to this exception, since we are re-raising it in `_handle_m2m_field_node`? To aid debugging/understanding the error.", "path": "django/core/serializers/xml_serializer.py", "line": null, "side": "RIGHT", "created_at": "2026-01-12T19:40:04+00:00" } ], "meta": { "languages": [ "py", "txt", "xml" ], "touches_tests": true, "review_state_summary": { "COMMENTED": 11, "APPROVED": 2 }, "meaningful_comment_count": 19, "has_approval": true, "has_changes_requested": false, "total_review_comments": 19 } } { "_id": "add05e3bb72674a4", "_schema_version": "1.0", "_cleaned_at": "2026-02-12T07:46:51.593428+00:00", "repo": "django/django", "repo_url": "https://github.com/django/django", "license_name": "BSD 3-Clause \"New\" or \"Revised\" License", "license_spdx": "BSD-3-Clause", "pr_number": 20400, "title": "Fixed #36781 -- Added Granian to deployment documentation.", "body": "#### Trac ticket number\n\n\nticket-36781\n\n#### Branch description\nGranian is a Rust-based high-performance HTTP server that supports both ASGI and WSGI interfaces. This patch adds deployment documentation following the\n same structure as existing server docs (Daphne, Uvicorn, Hypercorn, Gunicorn).\n\n- https://forum.djangoproject.com/t/add-granian-to-how-to-deploy-docs-asgi-wsgi-support/43386\n\n#### Checklist\n- [x] This PR targets the `main` branch. \n- [x] The commit message is written in past tense, mentions the ticket number, and ends with a period.\n- [x] I have checked the \"Has patch\" ticket flag in the Trac system.\n- [ ] I have added or updated relevant tests.\n- [x] I have added or updated relevant docs, including release notes if applicable.\n- [ ] I have attached screenshots in both light and dark modes for any UI changes.", "author": "user_ed8298a0306d", "created_at": "2025-12-13T13:34:01+00:00", "merged_at": "2025-12-19T15:09:31+00:00", "base_branch": "main", "head_branch": "ticket-36781", "additions": 77, "deletions": 0, "changed_files": 5, "files": [ { "filename": "docs/howto/deployment/asgi/granian.txt", "status": "added", "additions": 37, "deletions": 0, "changes": 37, "patch": "@@ -0,0 +1,37 @@\n+==============================\n+How to use Django with Granian\n+==============================\n+\n+Granian_ is a Rust-based high-performance HTTP server for Python applications,\n+supporting ASGI and WSGI interfaces.\n+\n+.. _Granian: https://github.com/emmett-framework/granian\n+\n+[NAME_REDACTED]\n+==================\n+\n+You can install Granian with ``pip``:\n+\n+.. code-block:: shell\n+\n+ python -m pip install granian\n+\n+[NAME_REDACTED] in Granian\n+=========================\n+\n+When Granian is installed, a ``granian`` command is available which runs ASGI\n+applications. Granian needs to be called with the location of a module\n+containing an ASGI application object, followed by [NAME_REDACTED]\n+called (separated by a colon), using the ``--interface asgi`` option.\n+\n+For a typical Django project, invoking Granian would look like:\n+\n+.. code-block:: shell\n+\n+ granian myproject.asgi:application --interface asgi\n+\n+This will start one process listening on ``127.0.0.1:8000``. It requires that\n+your project be on the Python path; to ensure that, run this command from the\n+same directory as your ``manage.py`` file.\n+\n+For more advanced usage, please read the `Granian documentation `_." }, { "filename": "docs/howto/deployment/asgi/index.txt", "status": "modified", "additions": 1, "deletions": 0, "changes": 1, "patch": "@@ -17,6 +17,7 @@ Django includes getting-started documentation for the following ASGI servers:\n :maxdepth: 1\n \n daphne\n+ granian\n hypercorn\n uvicorn" }, { "filename": "docs/howto/deployment/wsgi/granian.txt", "status": "added", "additions": 37, "deletions": 0, "changes": 37, "patch": "@@ -0,0 +1,37 @@\n+==============================\n+How to use Django with Granian\n+==============================\n+\n+Granian_ is a Rust-based high-performance HTTP server for Python applications,\n+supporting ASGI and WSGI interfaces.\n+\n+.. _Granian: https://github.com/emmett-framework/granian\n+\n+[NAME_REDACTED]\n+==================\n+\n+You can install Granian with ``pip``:\n+\n+.. code-block:: shell\n+\n+ python -m pip install granian\n+\n+[NAME_REDACTED] in Granian\n+=========================\n+\n+When Granian is installed, a ``granian`` command is available which runs WSGI\n+applications. Granian needs to be called with the location of a module\n+containing a WSGI application object named ``application``, using the\n+``--interface wsgi`` option.\n+\n+For a typical Django project, invoking Granian would look like:\n+\n+.. code-block:: shell\n+\n+ granian myproject.wsgi:application --interface wsgi\n+\n+This will start one process listening on ``127.0.0.1:8000``. It requires that\n+your project be on the Python path; to ensure that, run this command from the\n+same directory as your ``manage.py`` file.\n+\n+For more advanced usage, please read the `Granian documentation `_." }, { "filename": "docs/howto/deployment/wsgi/index.txt", "status": "modified", "additions": 1, "deletions": 0, "changes": 1, "patch": "@@ -16,6 +16,7 @@ Django includes getting-started documentation for the following WSGI servers:\n .. toctree::\n :maxdepth: 1\n \n+ granian\n gunicorn\n uwsgi\n modwsgi" }, { "filename": "docs/spelling_wordlist", "status": "modified", "additions": 1, "deletions": 0, "changes": 1, "patch": "@@ -190,6 +190,7 @@ gis\n [NAME_REDACTED]\n+Granian\n gunicorn\n GZip\n gzipped" } ], "reviews": [ { "id": 3584449431, "user": "user_3a67c55598c5", "state": "COMMENTED", "body": "Thanks [USER_REDACTED] ⭐", "submitted_at": "2025-12-16T18:32:28+00:00" }, { "id": 3590656384, "user": "user_ed8298a0306d", "state": "COMMENTED", "body": null, "submitted_at": "2025-12-18T04:03:27+00:00" }, { "id": 3593703091, "user": "user_3a67c55598c5", "state": "COMMENTED", "body": null, "submitted_at": "2025-12-18T15:55:22+00:00" }, { "id": 3594394106, "user": "user_744e6120a342", "state": "COMMENTED", "body": null, "submitted_at": "2025-12-18T18:29:49+00:00" }, { "id": 3598956873, "user": "user_3a67c55598c5", "state": "APPROVED", "body": null, "submitted_at": "2025-12-19T15:08:23+00:00" } ], "review_comments": [ { "id": 2624316691, "user": "user_3a67c55598c5", "body": "This invites the question \"what is RSGI, and does Django support it\"? I'd avoid mentioning it.", "path": "docs/howto/deployment/asgi/granian.txt", "line": null, "side": "RIGHT", "created_at": "2025-12-16T18:29:32+00:00" }, { "id": 2629461541, "user": "user_ed8298a0306d", "body": "Thank you for the review, Jacob. I agree that it could be ambiguous, so I’ve revised it.", "path": "docs/howto/deployment/asgi/granian.txt", "line": null, "side": "RIGHT", "created_at": "2025-12-18T04:03:27+00:00" }, { "id": 2631643540, "user": "user_3a67c55598c5", "body": "I'd do the same change in the other file.", "path": "docs/howto/deployment/asgi/granian.txt", "line": 6, "side": "RIGHT", "created_at": "2025-12-18T15:55:24+00:00" }, { "id": 2632143855, "user": "user_744e6120a342", "body": "a bit nitpicking, but since in other server docs we format it like:\n`uvicorn myproject.asgi:application`, it might be cleaner to format this the same way\n\n```suggestion\n granian myproject.asgi:application --interface asgi \n```", "path": "docs/howto/deployment/asgi/granian.txt", "line": null, "side": "RIGHT", "created_at": "2025-12-18T18:25:23+00:00" }, { "id": 2632145152, "user": "user_744e6120a342", "body": "```suggestion\nyour project be on the Python path; to ensure that, run this command from the\n```", "path": "docs/howto/deployment/asgi/granian.txt", "line": null, "side": "RIGHT", "created_at": "2025-12-18T18:25:37+00:00" }, { "id": 2632163975, "user": "user_744e6120a342", "body": "```suggestion\nyour project be on the Python path; to ensure that, run this command from the\n```", "path": "docs/howto/deployment/wsgi/granian.txt", "line": null, "side": "RIGHT", "created_at": "2025-12-18T18:29:22+00:00" }, { "id": 2632165195, "user": "user_744e6120a342", "body": "```suggestion\n granian myproject.wsgi:application --interface wsgi\n```", "path": "docs/howto/deployment/wsgi/granian.txt", "line": null, "side": "RIGHT", "created_at": "2025-12-18T18:29:35+00:00" } ], "meta": { "languages": [ "txt" ], "touches_tests": false, "review_state_summary": { "COMMENTED": 4, "APPROVED": 1 }, "meaningful_comment_count": 7, "has_approval": true, "has_changes_requested": false, "total_review_comments": 7 } } { "_id": "b01331f62b9acf8e", "_schema_version": "1.0", "_cleaned_at": "2026-02-12T07:46:51.593428+00:00", "repo": "django/django", "repo_url": "https://github.com/django/django", "license_name": "BSD 3-Clause \"New\" or \"Revised\" License", "license_spdx": "BSD-3-Clause", "pr_number": 20395, "title": "Fixed #36791 -- [NAME_REDACTED] recreate through table when m2m target model changes", "body": "…ToManyField target model changes.\n\n#### Trac ticket number\n\n\nticket-[36791](https://code.djangoproject.com/ticket/36791)\n\n#### Branch description\nProvide a concise overview of the issue or rationale behind the proposed changes.\n\n#### Checklist\n- [x] This PR targets the `main` branch. \n- [x] The commit message is written in past tense, mentions the ticket number, and ends with a period.\n- [x] I have checked the \"Has patch\" ticket flag in the Trac system.\n- [x] I have added or updated relevant tests.\n- [x] I have added or updated relevant docs, including release notes if applicable.\n- [ ] I have attached screenshots in both light and dark modes for any UI changes.", "author": "user_4f133b1319db", "created_at": "2025-12-12T23:20:13+00:00", "merged_at": "2025-12-19T19:01:37+00:00", "base_branch": "main", "head_branch": "ticket/36791-fix-m2m-through-table-drop", "additions": 51, "deletions": 1, "changed_files": 2, "files": [ { "filename": "django/db/migrations/autodetector.py", "status": "modified", "additions": 4, "deletions": 1, "changes": 5, "patch": "@@ -1339,7 +1339,10 @@ def generate_altered_fields(self):\n if old_field_dec != new_field_dec and old_field_name == field_name:\n both_m2m = old_field.many_to_many and new_field.many_to_many\n neither_m2m = not old_field.many_to_many and not new_field.many_to_many\n- if both_m2m or neither_m2m:\n+ target_changed = (\n+ both_m2m and new_field_dec[2][\"to\"] != old_field_dec[2][\"to\"]\n+ )\n+ if (both_m2m or neither_m2m) and not target_changed:\n # Either both fields are m2m or neither is\n preserve_default = True\n if (" }, { "filename": "tests/migrations/test_autodetector.py", "status": "modified", "additions": 47, "deletions": 0, "changes": 47, "patch": "@@ -741,6 +741,13 @@ class AutodetectorTests(BaseAutodetectorTests):\n (\"publishers\", models.ManyToManyField(\"testapp.Publisher\", blank=True)),\n ],\n )\n+ other_publisher = ModelState(\n+ \"testapp\",\n+ \"OtherPublisher\",\n+ [\n+ (\"id\", models.AutoField(primary_key=True)),\n+ ],\n+ )\n author_with_m2m_through = ModelState(\n \"testapp\",\n \"Author\",\n@@ -4557,6 +4564,46 @@ def test_many_to_many_changed_to_concrete_field(self):\n )\n self.assertOperationFieldAttributes(changes, \"testapp\", 0, 2, max_length=100)\n \n+ def test_m2m_target_change_generates_remove_and_add(self):\n+ before = [\n+ self.publisher,\n+ self.other_publisher,\n+ self.author_with_m2m, # m2m to self.publisher.\n+ ]\n+\n+ after = [\n+ self.publisher,\n+ self.other_publisher,\n+ ModelState(\n+ \"testapp\",\n+ \"Author\",\n+ [\n+ (\"id\", models.AutoField(primary_key=True)),\n+ # Repoint m2m to self.other_publisher.\n+ (\"publishers\", models.ManyToManyField(\"testapp.OtherPublisher\")),\n+ ],\n+ ),\n+ ]\n+ changes = self.get_changes(before, after)\n+ self.assertNumberMigrations(changes, \"testapp\", 1)\n+ self.assertOperationTypes(changes, \"testapp\", 0, [\"RemoveField\", \"AddField\"])\n+ self.assertOperationAttributes(\n+ changes,\n+ \"testapp\",\n+ 0,\n+ 0,\n+ name=\"publishers\",\n+ model_name=\"author\",\n+ )\n+ self.assertOperationAttributes(\n+ changes,\n+ \"testapp\",\n+ 0,\n+ 1,\n+ name=\"publishers\",\n+ model_name=\"author\",\n+ )\n+\n def test_non_circular_foreignkey_dependency_removal(self):\n \"\"\"\n If two models with a ForeignKey from one to the other are removed at" } ], "reviews": [ { "id": 3574945882, "user": "user_606ba1f2b93c", "state": "COMMENTED", "body": "Thanks [USER_REDACTED]. Looks great 🏆 \n\nI added some suggestions", "submitted_at": "2025-12-14T10:10:09+00:00" }, { "id": 3575566229, "user": "user_606ba1f2b93c", "state": "COMMENTED", "body": "Thanks for the updates 👍🏾 \n\nYou will need to squash the commits and fix the title, e.g. `Fixed #36791 -- [NAME_REDACTED] recreate through table when m2m target model changes.` and add Jacob as co-author", "submitted_at": "2025-12-14T15:37:12+00:00" }, { "id": 3575718663, "user": "user_606ba1f2b93c", "state": "APPROVED", "body": "Small detail: you forgot to clean up your commit message body to remove the old messages 😸 But otherwise looks great.\n\nThanks 🏆", "submitted_at": "2025-12-14T18:48:34+00:00" }, { "id": 3578180292, "user": "user_606ba1f2b93c", "state": "COMMENTED", "body": null, "submitted_at": "2025-12-15T13:24:47+00:00" }, { "id": 3592776256, "user": "user_606ba1f2b93c", "state": "COMMENTED", "body": "Thanks for the updates 👍🏾 \n\nWe only need to add a variable for something we need to use more than once, in this case the other publisher. I have added suggestions doing that, and replacing `Magazine` with `OtherPublisher` (just for semantics).\n\nI'd also move the test to below `test_many_to_many_changed_to_concrete_field` so it is grouped with other m2m-related tests.", "submitted_at": "2025-12-18T12:58:29+00:00" }, { "id": 3594947786, "user": "user_606ba1f2b93c", "state": "COMMENTED", "body": null, "submitted_at": "2025-12-18T20:50:23+00:00" }, { "id": 3594997952, "user": "user_606ba1f2b93c", "state": "COMMENTED", "body": null, "submitted_at": "2025-12-18T20:52:42+00:00" }, { "id": 3595138003, "user": "user_606ba1f2b93c", "state": "APPROVED", "body": "Thanks 🚀", "submitted_at": "2025-12-18T21:29:40+00:00" }, { "id": 3599693706, "user": "user_3a67c55598c5", "state": "APPROVED", "body": "Thanks [USER_REDACTED] and thanks [USER_REDACTED] for the review!", "submitted_at": "2025-12-19T19:01:09+00:00" } ], "review_comments": [ { "id": 2616891657, "user": "user_606ba1f2b93c", "body": "use `assertNumberMigrations()` (see surrounding tests)", "path": "tests/migrations/test_autodetector.py", "line": null, "side": "RIGHT", "created_at": "2025-12-14T10:05:11+00:00" }, { "id": 2616892522, "user": "user_606ba1f2b93c", "body": "use `assertOperationTypes()`", "path": "tests/migrations/test_autodetector.py", "line": null, "side": "RIGHT", "created_at": "2025-12-14T10:06:52+00:00" }, { "id": 2616893624, "user": "user_606ba1f2b93c", "body": "use `assertOperationAttributes()`", "path": "tests/migrations/test_autodetector.py", "line": null, "side": "RIGHT", "created_at": "2025-12-14T10:09:16+00:00" }, { "id": 2617252239, "user": "user_606ba1f2b93c", "body": "Nit: I'd remove the blank lines; the file is already too long as it is \n```suggestion\n changes = self.get_changes(before, after)\n self.assertNumberMigrations(changes, \"testapp\", 1)\n self.assertOperationTypes(changes, \"testapp\", 0, [\"RemoveField\", \"AddField\"])\n self.assertOperationAttributes(\n changes,\n \"testapp\",\n 0,\n 0,\n name=\"readings\",\n model_name=\"author\",\n )\n self.assertOperationAttributes(\n```", "path": "tests/migrations/test_autodetector.py", "line": null, "side": "RIGHT", "created_at": "2025-12-14T15:31:41+00:00" }, { "id": 2619428551, "user": "user_606ba1f2b93c", "body": "I've just discovered these model states or similar are predefined, e.g. `self.author_with_m2m`. Can you switch to those here and, where appropriate, in `after` as well.", "path": "tests/migrations/test_autodetector.py", "line": null, "side": "RIGHT", "created_at": "2025-12-15T13:24:47+00:00" }, { "id": 2630938677, "user": "user_606ba1f2b93c", "body": "```suggestion\n before = [\n self.publisher,\n self.other_publisher,\n self.author_with_m2m, # m2m to self.publisher.\n```", "path": "tests/migrations/test_autodetector.py", "line": null, "side": "RIGHT", "created_at": "2025-12-18T12:49:00+00:00" }, { "id": 2630966200, "user": "user_606ba1f2b93c", "body": "I think we only need a variable for something we need to use more than once.\n```suggestion\n other_publisher = ModelState(\n \"testapp\",\n \"OtherPublisher\",\n [\n (\"id\", models.AutoField(primary_key=True)),\n ],\n )\n```", "path": "tests/migrations/test_autodetector.py", "line": null, "side": "RIGHT", "created_at": "2025-12-18T12:55:15+00:00" }, { "id": 2630975903, "user": "user_606ba1f2b93c", "body": "```suggestion\n after = [\n self.publisher,\n self.other_publisher,\n ModelState(\n \"testapp\",\n \"Author\",\n [\n (\"id\", models.AutoField(primary_key=True)),\n # Repoint m2m to self.other_publisher.\n (\"publishers\", models.ManyToManyField(\"testapp.OtherPublisher\")),\n ],\n ),\n ]\n```", "path": "tests/migrations/test_autodetector.py", "line": null, "side": "RIGHT", "created_at": "2025-12-18T12:57:20+00:00" }, { "id": 2632583722, "user": "user_606ba1f2b93c", "body": "We missed this outdated comment", "path": "tests/migrations/test_autodetector.py", "line": null, "side": "RIGHT", "created_at": "2025-12-18T20:50:03+00:00" }, { "id": 2632590554, "user": "user_606ba1f2b93c", "body": "And also if I could bother you to move the test, as suggested [here](https://github.com/[USER_REDACTED]ngo/django/pull/20395#pullrequestreview-3592776256).\n\nOtherwise this should be good to go.", "path": "tests/migrations/test_autodetector.py", "line": null, "side": "RIGHT", "created_at": "2025-12-18T20:52:41+00:00" } ], "meta": { "languages": [ "py" ], "touches_tests": true, "review_state_summary": { "COMMENTED": 6, "APPROVED": 3 }, "meaningful_comment_count": 10, "has_approval": true, "has_changes_requested": false, "total_review_comments": 10 } } { "_id": "0f915e210dd96a84", "_schema_version": "1.0", "_cleaned_at": "2026-02-12T07:46:51.593428+00:00", "repo": "django/django", "repo_url": "https://github.com/django/django", "license_name": "BSD 3-Clause \"New\" or \"Revised\" License", "license_spdx": "BSD-3-Clause", "pr_number": 20380, "title": "Fixed #36701 -- Fixed memory leak in ModelState.", "body": "#### Trac ticket number\n\nticket-36701\n\n#### Branch description\nThis PR addresses ticket #36701 regarding memory leaks caused by [NAME_REDACTED] `ModelState`\n\nI implemented a `__del__` method on `ModelState` to explicitly clear `self.fields_cache`.\n\nI added a regression test (`tests/model_state/test_memory_leak.py`) that:\n1. Creates a `OneToOneField` cycle.\n2. Deletes strong references.\n3. Forces a `gc.collect()`.\n4. Asserts that the objects are successfully reclaimed (using `weakref`).\n\nI also verified this locally with a reproduction script generating 50,000 cyclic objects. Without the fix, memory usage balloons. With the fix, `gc.collect()` successfully reclaims the objects.\n#### Checklist\n- [ ] This PR targets the `main` branch. \n- [ ] The commit message is written in past tense, mentions the ticket number, and ends with a period.\n- [ ] I have checked the \"Has patch\" ticket flag in the Trac system.\n- [ ] I have added or updated relevant tests.\n- [ ] I have added or updated relevant docs, including release notes if applicable.\n- [ ] I have attached screenshots in both light and dark modes for any UI changes.", "author": "user_97513ac81384", "created_at": "2025-12-08T16:46:26+00:00", "merged_at": "2025-12-18T22:53:24+00:00", "base_branch": "main", "head_branch": "ticket-36701-modelstate-leak", "additions": 33, "deletions": 0, "changed_files": 3, "files": [ { "filename": "django/db/models/base.py", "status": "modified", "additions": 3, "deletions": 0, "changes": 3, "patch": "@@ -494,6 +494,9 @@ def __getstate__(self):\n state.pop(\"peers\", None)\n return state\n \n+ def __del__(self):\n+ self.fields_cache.clear()\n+\n \n class Model(AltersData, metaclass=ModelBase):\n def __init__(self, *args, **kwargs):" }, { "filename": "tests/model_regress/models.py", "status": "modified", "additions": 4, "deletions": 0, "changes": 4, "patch": "@@ -45,6 +45,10 @@ def __str__(self):\n return self.name\n \n \n+class WorkerProfile(models.Model):\n+ worker = models.OneToOneField(Worker, on_delete=models.CASCADE)\n+\n+\n class NonAutoPK(models.Model):\n name = models.CharField(max_length=10, primary_key=True)" }, { "filename": "tests/model_regress/test_state.py", "status": "modified", "additions": 26, "deletions": 0, "changes": 26, "patch": "@@ -1,7 +1,33 @@\n+import gc\n+\n from django.db.models.base import ModelState, ModelStateFieldsCacheDescriptor\n from django.test import SimpleTestCase\n+from django.test.utils import garbage_collect\n+\n+from .models import Worker, WorkerProfile\n \n \n class ModelStateTests(SimpleTestCase):\n def test_fields_cache_descriptor(self):\n self.assertIsInstance(ModelState.fields_cache, ModelStateFieldsCacheDescriptor)\n+\n+ def test_one_to_one_field_cycle_collection(self):\n+ self.addCleanup(gc.set_debug, gc.get_debug())\n+ gc.set_debug(gc.DEBUG_SAVEALL)\n+\n+ def clear_garbage():\n+ del gc.garbage[:]\n+\n+ self.addCleanup(clear_garbage)\n+\n+ worker = Worker()\n+ profile = WorkerProfile(worker=worker)\n+ worker_id = id(worker)\n+\n+ del worker\n+ del profile\n+\n+ garbage_collect()\n+\n+ leaked = [obj for obj in gc.garbage if id(obj) == worker_id]\n+ self.assertEqual(leaked, [])" } ], "reviews": [ { "id": 3553418197, "user": "user_3a67c55598c5", "state": "COMMENTED", "body": null, "submitted_at": "2025-12-08T18:19:29+00:00" }, { "id": 3553600408, "user": "user_97513ac81384", "state": "COMMENTED", "body": null, "submitted_at": "2025-12-08T18:53:04+00:00" }, { "id": 3554093890, "user": "user_3a67c55598c5", "state": "COMMENTED", "body": "Thanks 👍", "submitted_at": "2025-12-08T21:21:51+00:00" }, { "id": 3554133738, "user": "user_3a67c55598c5", "state": "COMMENTED", "body": null, "submitted_at": "2025-12-08T21:28:08+00:00" }, { "id": 3557324059, "user": "user_3a67c55598c5", "state": "COMMENTED", "body": null, "submitted_at": "2025-12-09T13:05:17+00:00" }, { "id": 3564544111, "user": "user_3a67c55598c5", "state": "COMMENTED", "body": "Thanks for the updates 👍", "submitted_at": "2025-12-10T21:28:04+00:00" }, { "id": 3579982159, "user": "user_3a67c55598c5", "state": "APPROVED", "body": "Thanks, I pushed small edits to tests to reuse a model.", "submitted_at": "2025-12-15T20:21:22+00:00" }, { "id": 3580150006, "user": "user_3a67c55598c5", "state": "COMMENTED", "body": null, "submitted_at": "2025-12-15T21:06:22+00:00" }, { "id": 3582714844, "user": "user_97513ac81384", "state": "COMMENTED", "body": null, "submitted_at": "2025-12-16T11:55:39+00:00" }, { "id": 3583182613, "user": "user_3a67c55598c5", "state": "COMMENTED", "body": null, "submitted_at": "2025-12-16T13:49:43+00:00" }, { "id": 3594899558, "user": "user_3a67c55598c5", "state": "COMMENTED", "body": null, "submitted_at": "2025-12-18T20:21:29+00:00" }, { "id": 3594900732, "user": "user_3a67c55598c5", "state": "COMMENTED", "body": "One last thing to polish.", "submitted_at": "2025-12-18T20:21:40+00:00" }, { "id": 3594919377, "user": "user_3a67c55598c5", "state": "COMMENTED", "body": null, "submitted_at": "2025-12-18T20:27:59+00:00" }, { "id": 3594953380, "user": "user_97513ac81384", "state": "COMMENTED", "body": null, "submitted_at": "2025-12-18T20:38:51+00:00" }, { "id": 3595528877, "user": "user_3a67c55598c5", "state": "APPROVED", "body": "Thanks 👍", "submitted_at": "2025-12-18T22:49:32+00:00" } ], "review_comments": [ { "id": 2599623908, "user": "user_3a67c55598c5", "body": "You can remove this in favor of a more descriptive method title mentioning one_to_one (or o2o) fields.", "path": "tests/model_state/test_memory_leak.py", "line": null, "side": "RIGHT", "created_at": "2025-12-08T18:11:52+00:00" }, { "id": 2599634613, "user": "user_3a67c55598c5", "body": "This test doesn't fail when I revert your changes. You might be able to draw inspiration from this:\n\nhttps://github.com/[USER_REDACTED]ngo/django/blob/334308efae8e0c7b1523d5583af32b674a098eba/tests/select_related/tests.py#L63-L72", "path": "tests/model_state/test_memory_leak.py", "line": null, "side": "RIGHT", "created_at": "2025-12-08T18:16:11+00:00" }, { "id": 2599643979, "user": "user_3a67c55598c5", "body": "Please move this test to tests/model_regress/test_state.py", "path": "tests/model_state/test_memory_leak.py", "line": null, "side": "RIGHT", "created_at": "2025-12-08T18:18:46+00:00" }, { "id": 2599764195, "user": "user_97513ac81384", "body": "I am really sorry, I saw the test passing and got excited and forgot to check for the main scenario I was writing the test.\nI have written the test again and verified it is failing now before the fix and passing after the fix", "path": "tests/model_state/test_memory_leak.py", "line": null, "side": "RIGHT", "created_at": "2025-12-08T18:53:04+00:00" }, { "id": 2600163396, "user": "user_3a67c55598c5", "body": "Why do we need the except?", "path": "django/db/models/base.py", "line": null, "side": "RIGHT", "created_at": "2025-12-08T21:15:08+00:00" }, { "id": 2600172943, "user": "user_3a67c55598c5", "body": "Please use the `garbage_collect()` helper from `django.test.utils`.", "path": "tests/model_regress/test_state.py", "line": null, "side": "RIGHT", "created_at": "2025-12-08T21:17:48+00:00" }, { "id": 2600178864, "user": "user_3a67c55598c5", "body": "Why do we need this?", "path": "tests/model_regress/test_state.py", "line": null, "side": "RIGHT", "created_at": "2025-12-08T21:20:27+00:00" }, { "id": 2600180316, "user": "user_3a67c55598c5", "body": "```suggestion\n```\nThanks for the method name change. Now we can lose the docstring (we avoid \"Ensure ...\" preambles anyway.)", "path": "tests/model_regress/test_state.py", "line": null, "side": "RIGHT", "created_at": "2025-12-08T21:21:01+00:00" }, { "id": 2600197392, "user": "user_3a67c55598c5", "body": "After this test I get this warning:\n```py\nException ignored in GC shutdown:\nResourceWarning: gc: 7995 uncollectable objects at shutdown; use gc.set_debug(gc.DEBUG_UNCOLLECTABLE) to list them\n```", "path": "tests/model_regress/test_state.py", "line": 33, "side": "RIGHT", "created_at": "2025-12-08T21:28:08+00:00" }, { "id": 2602570060, "user": "user_3a67c55598c5", "body": "My question was getting at, under what conditions would `_fields_cache` be missing?", "path": "django/db/models/base.py", "line": null, "side": "RIGHT", "created_at": "2025-12-09T13:04:39+00:00" }, { "id": 2602572322, "user": "user_3a67c55598c5", "body": "This test is testing the implementation instead of the underlying issue. It would be better to polish the test you had before.", "path": "tests/model_regress/test_state.py", "line": null, "side": "RIGHT", "created_at": "2025-12-09T13:05:13+00:00" }, { "id": 2608258954, "user": "user_3a67c55598c5", "body": "Thanks for explaining -- in that case these lines are reachable, so we need a test to cover them.", "path": "django/db/models/base.py", "line": null, "side": "RIGHT", "created_at": "2025-12-10T21:24:50+00:00" }, { "id": 2608269458, "user": "user_3a67c55598c5", "body": "Again, thanks very much for explaining. Now we need to register this as a cleanup earlier (right after garbage_collect, with `self.addCleanup`) because if the assertion fails for some reason I get the warning again.", "path": "tests/model_regress/test_state.py", "line": 33, "side": "RIGHT", "created_at": "2025-12-10T21:27:57+00:00" }, { "id": 2620846601, "user": "user_3a67c55598c5", "body": "This is still not covered.", "path": "django/db/models/base.py", "line": null, "side": "RIGHT", "created_at": "2025-12-15T21:06:05+00:00" }, { "id": 2620847094, "user": "user_3a67c55598c5", "body": "Where is `_fields_cache` assigned?", "path": "tests/model_regress/test_state.py", "line": null, "side": "RIGHT", "created_at": "2025-12-15T21:06:19+00:00" }, { "id": 2622977356, "user": "user_97513ac81384", "body": "[USER_REDACTED]\n\nRegarding `_fields_cache` assignment: That was an error in my test code. The internal storage key is actually `fields_cache` . I have corrected the test to check state.`__dict__` for the correct key `(\"fields_cache\")`.\n\nReliance on `del state` alone was causing coverage gaps. I have updated the test to explicitly call state.`__del__()`. This forces the execution of the except AttributeError: pass block, ensuring 100% coverage for the teardown logic.", "path": "tests/model_regress/test_state.py", "line": null, "side": "RIGHT", "created_at": "2025-12-16T11:55:39+00:00" }, { "id": 2623360618, "user": "user_3a67c55598c5", "body": "The except is still not covered. Also, please fetch the changes I pushed to your branch; you've force-pushed over them. TIP: you can use `--force-with-lease` when force pushing to ensure you get an error if there are missing changes to fetch first.", "path": "tests/model_regress/test_state.py", "line": null, "side": "RIGHT", "created_at": "2025-12-16T13:49:42+00:00" }, { "id": 2632513831, "user": "user_3a67c55598c5", "body": "```suggestion\n```", "path": "tests/model_regress/test_state.py", "line": null, "side": "RIGHT", "created_at": "2025-12-18T20:21:29+00:00" }, { "id": 2632529639, "user": "user_3a67c55598c5", "body": "Sorry, I guess this whole test method can go now, now that we're not trying to exercise some separate code path.", "path": "tests/model_regress/test_state.py", "line": null, "side": "RIGHT", "created_at": "2025-12-18T20:27:59+00:00" }, { "id": 2632555347, "user": "user_97513ac81384", "body": "ok", "path": "tests/model_regress/test_state.py", "line": null, "side": "RIGHT", "created_at": "2025-12-18T20:38:51+00:00" } ], "meta": { "languages": [ "py" ], "touches_tests": true, "review_state_summary": { "COMMENTED": 13, "APPROVED": 2 }, "meaningful_comment_count": 19, "has_approval": true, "has_changes_requested": false, "total_review_comments": 20 } } { "_id": "1fff2a0b1111a955", "_schema_version": "1.0", "_cleaned_at": "2026-02-12T07:46:51.609057+00:00", "repo": "django/django", "repo_url": "https://github.com/django/django", "license_name": "BSD 3-Clause \"New\" or \"Revised\" License", "license_spdx": "BSD-3-Clause", "pr_number": 20377, "title": "Fixed #36769 -- Avoided visiting deeply nested nodes in XML deserializer.", "body": "#### Trac ticket number\n\n\nticket-36769\n\n#### Branch description\nThis change adds a limit to how deep getInnerTextList() will read XML tags.\nDjango fixtures only need one level of text (for example: text).\nDeeper levels are not used and can cause performance problems if the XML is very nested.\n\n#### Checklist\n- [x] This PR targets the `main` branch. \n- [ ] The commit message is written in past tense, mentions the ticket number, and ends with a period.\n- [ ] I have checked the \"Has patch\" ticket flag in the Trac system.\n- [ ] I have added or updated relevant tests.\n- [ ] I have added or updated relevant docs, including release notes if applicable.\n- [ ] I have attached screenshots in both light and dark modes for any UI changes.", "author": "user_a7be60241a0e", "created_at": "2025-12-06T12:47:42+00:00", "merged_at": "2025-12-11T17:38:04+00:00", "base_branch": "main", "head_branch": "fix-36769", "additions": 28, "deletions": 19, "changed_files": 3, "files": [ { "filename": "django/core/serializers/xml_serializer.py", "status": "modified", "additions": 9, "deletions": 19, "changes": 28, "patch": "@@ -416,27 +416,17 @@ def _get_model_from_node(self, node, attr):\n \n \n def getInnerText(node):\n- \"\"\"Get all the inner text of a DOM node (recursively).\"\"\"\n- inner_text_list = getInnerTextList(node)\n- return \"\".join(inner_text_list)\n-\n-\n-def getInnerTextList(node):\n- \"\"\"Return a list of the inner texts of a DOM node (recursively).\"\"\"\n+ \"\"\"Get the inner text of a DOM node and any children one level deep.\"\"\"\n # inspired by\n # https://mail.python.org/pipermail/xml-sig/2005-March/011022.html\n- result = []\n- for child in node.childNodes:\n- if (\n- child.nodeType == child.TEXT_NODE\n- or child.nodeType == child.CDATA_SECTION_NODE\n- ):\n- result.append(child.data)\n- elif child.nodeType == child.ELEMENT_NODE:\n- result.extend(getInnerTextList(child))\n- else:\n- pass\n- return result\n+ return \"\".join(\n+ [\n+ element.data\n+ for child in node.childNodes\n+ for element in (child, *child.childNodes)\n+ if element.nodeType in (element.TEXT_NODE, element.CDATA_SECTION_NODE)\n+ ]\n+ )\n \n \n # Below code based on [NAME_REDACTED]' defusedxml" }, { "filename": "tests/fixtures/fixtures/invalid_deeply_nested_elements.xml", "status": "added", "additions": 10, "deletions": 0, "changes": 10, "patch": "@@ -0,0 +1,10 @@\n+\n+\n+\n+ \n+ \n+ Django pony\n+ \n+ \n+\n+" }, { "filename": "tests/fixtures/tests.py", "status": "modified", "additions": 9, "deletions": 0, "changes": 9, "patch": "@@ -23,6 +23,7 @@\n CircularA,\n CircularB,\n NaturalKeyThing,\n+ Person,\n PrimaryKeyUUIDModel,\n ProxySpy,\n Spy,\n@@ -520,6 +521,14 @@ def test_loading_and_dumping(self):\n natural_foreign_keys=True,\n )\n \n+ def test_deeply_nested_elements(self):\n+ \"\"\"Text inside deeply-nested tags is skipped.\"\"\"\n+ management.call_command(\n+ \"loaddata\", \"invalid_deeply_nested_elements.xml\", verbosity=0\n+ )\n+ person = Person.objects.get(pk=1)\n+ self.assertEqual(person.name, \"Django\") # not \"Django pony\"\n+\n def test_dumpdata_with_excludes(self):\n # Load fixture1 which has a site, two articles, and a category\n Site.objects.all().delete()" } ], "reviews": [ { "id": 3547546456, "user": "user_a7be60241a0e", "state": "COMMENTED", "body": null, "submitted_at": "2025-12-06T12:52:05+00:00" }, { "id": 3553513984, "user": "user_3a67c55598c5", "state": "COMMENTED", "body": "Thanks 👍 \n\nCan you add a test to show the behavior change? I'm imagining a new file in `tests/fixtures/fixtures` like `invalid_deeply_nested_elements.xml` showing that text inside unescaped markup like `Django pony` now just extracts \"Django \" rather than \"Django pony\".\n\nThen, it will be more easy to tell if we even need the max_depth at all. My preliminary testing is showing that we don't need to recurse at _all_, since we call `getInnerText` directly on `` elements.", "submitted_at": "2025-12-08T20:11:26+00:00" }, { "id": 3555799894, "user": "user_a7be60241a0e", "state": "COMMENTED", "body": null, "submitted_at": "2025-12-09T07:02:18+00:00" }, { "id": 3557415634, "user": "user_3a67c55598c5", "state": "COMMENTED", "body": null, "submitted_at": "2025-12-09T13:22:34+00:00" }, { "id": 3557517588, "user": "user_a7be60241a0e", "state": "COMMENTED", "body": null, "submitted_at": "2025-12-09T13:38:45+00:00" }, { "id": 3557853751, "user": "user_3a67c55598c5", "state": "COMMENTED", "body": null, "submitted_at": "2025-12-09T14:47:20+00:00" }, { "id": 3558441195, "user": "user_3a67c55598c5", "state": "APPROVED", "body": "Thanks ⭐", "submitted_at": "2025-12-09T16:36:58+00:00" }, { "id": 3574834021, "user": "user_6d44402bb9ae", "state": "COMMENTED", "body": "Sorry to come in late... one comment of substance below.", "submitted_at": "2025-12-14T07:17:36+00:00" }, { "id": 3580020463, "user": "user_3a67c55598c5", "state": "COMMENTED", "body": null, "submitted_at": "2025-12-15T20:30:40+00:00" }, { "id": 3580204985, "user": "user_6d44402bb9ae", "state": "COMMENTED", "body": null, "submitted_at": "2025-12-15T21:20:34+00:00" }, { "id": 3580327663, "user": "user_3a67c55598c5", "state": "COMMENTED", "body": null, "submitted_at": "2025-12-15T21:52:02+00:00" } ], "review_comments": [ { "id": 2594826777, "user": "user_a7be60241a0e", "body": "Limit max recursion depth to 1 level because fixtures only need text one level deep", "path": "django/core/serializers/xml_serializer.py", "line": null, "side": "RIGHT", "created_at": "2025-12-06T12:52:05+00:00" }, { "id": 2599693489, "user": "user_3a67c55598c5", "body": "This docstring needs an edit, as we're no longer getting \"all\" inner text.", "path": "django/core/serializers/xml_serializer.py", "line": null, "side": "RIGHT", "created_at": "2025-12-08T18:28:47+00:00" }, { "id": 2601357569, "user": "user_a7be60241a0e", "body": "changed the doc string wording here", "path": "django/core/serializers/xml_serializer.py", "line": null, "side": "RIGHT", "created_at": "2025-12-09T07:02:18+00:00" }, { "id": 2602644048, "user": "user_3a67c55598c5", "body": "Thanks, but `getInnerText()` is still not correct.", "path": "django/core/serializers/xml_serializer.py", "line": null, "side": "RIGHT", "created_at": "2025-12-09T13:22:33+00:00" }, { "id": 2602717132, "user": "user_a7be60241a0e", "body": "my bad, i missed it. thank for catching it. I have updated now", "path": "django/core/serializers/xml_serializer.py", "line": null, "side": "RIGHT", "created_at": "2025-12-09T13:38:45+00:00" }, { "id": 2602988490, "user": "user_3a67c55598c5", "body": "Please extract this into its own test method.", "path": "tests/fixtures/tests.py", "line": null, "side": "RIGHT", "created_at": "2025-12-09T14:47:20+00:00" }, { "id": 2616789575, "user": "user_6d44402bb9ae", "body": "Well, that's now questionable...", "path": "django/core/serializers/xml_serializer.py", "line": 421, "side": "RIGHT", "created_at": "2025-12-14T07:14:26+00:00" }, { "id": 2616789637, "user": "user_6d44402bb9ae", "body": "This looks truly inspired.", "path": "django/core/serializers/xml_serializer.py", "line": 428, "side": "RIGHT", "created_at": "2025-12-14T07:14:35+00:00" }, { "id": 2616789793, "user": "user_6d44402bb9ae", "body": "I find that surprising. I'd expect `Django pony` or a `SuspiciousOperation`.", "path": "tests/fixtures/tests.py", "line": 530, "side": "RIGHT", "created_at": "2025-12-14T07:14:56+00:00" }, { "id": 2620744151, "user": "user_3a67c55598c5", "body": "Good idea: #20409", "path": "tests/fixtures/tests.py", "line": 530, "side": "RIGHT", "created_at": "2025-12-15T20:30:39+00:00" }, { "id": 2620890092, "user": "user_6d44402bb9ae", "body": "Thanks! Took a glimpse and saw it was nontrivial, will try to review this week.", "path": "tests/fixtures/tests.py", "line": 530, "side": "RIGHT", "created_at": "2025-12-15T21:20:34+00:00" }, { "id": 2620981007, "user": "user_3a67c55598c5", "body": "Sure thing -- no rush!", "path": "tests/fixtures/tests.py", "line": 530, "side": "RIGHT", "created_at": "2025-12-15T21:52:01+00:00" } ], "meta": { "languages": [ "py", "xml" ], "touches_tests": true, "review_state_summary": { "COMMENTED": 10, "APPROVED": 1 }, "meaningful_comment_count": 12, "has_approval": true, "has_changes_requested": false, "total_review_comments": 12 } } { "_id": "2d86ab028f3c965c", "_schema_version": "1.0", "_cleaned_at": "2026-02-12T07:46:51.609057+00:00", "repo": "django/django", "repo_url": "https://github.com/django/django", "license_name": "BSD 3-Clause \"New\" or \"Revised\" License", "license_spdx": "BSD-3-Clause", "pr_number": 20376, "title": "Fixed #36778 -- Extended advice to sanitize user input before constructing query expressions with it.", "body": "#### Trac ticket number\nticket-36778\n\n#### Branch description\nThe subtlety around keyword arguments to `Func` providing direct control over the underlying SQL could use some clarification.\n\n#### Checklist\n- [x] This PR targets the `main` branch. \n- [x] The commit message is written in past tense, mentions the ticket number, and ends with a period.\n- [x] I have checked the \"Has patch\" ticket flag in the Trac system.\n- [ ] I have added or updated relevant tests.\n- [ ] I have added or updated relevant docs, including release notes if applicable.\n- [ ] I have attached screenshots in both light and dark modes for any UI changes.", "author": "user_3a67c55598c5", "created_at": "2025-12-05T20:43:04+00:00", "merged_at": "2025-12-08T15:25:24+00:00", "base_branch": "main", "head_branch": "jtw/extend-discussion-of-func-safety", "additions": 17, "deletions": 4, "changed_files": 3, "files": [ { "filename": "docs/internals/security.txt", "status": "modified", "additions": 5, "deletions": 3, "changes": 8, "patch": "@@ -111,9 +111,11 @@ validated::\n return JsonResponse(status=200)\n return JsonResponse(form.errors, status=400)\n \n-Similarly, as Django's raw SQL constructs (such as :meth:`~.QuerySet.extra` and\n-:class:`.RawSQL` expression) provide developers with full control over the\n-query, they are insecure if user input is not properly handled. As explained in\n+Similarly, as Django's raw SQL constructs (such as :meth:`~.QuerySet.extra`,\n+:class:`.RawSQL`, and :ref:`keyword arguments to database functions\n+`) provide developers with full\n+control over the query, they are insecure if user input is not properly\n+handled. As explained in\n our :ref:`security documentation `, it is the\n developer's responsibility to safely process user input for these functions." }, { "filename": "docs/ref/models/database-functions.txt", "status": "modified", "additions": 2, "deletions": 1, "changes": 3, "patch": "@@ -9,7 +9,8 @@ The classes documented below provide a way for users to use functions provided\n by [NAME_REDACTED] annotations, aggregations, or filters in Django.\n Functions are also :doc:`expressions `, so they can be\n used and combined with other expressions like :ref:`aggregate functions\n-`.\n+`. See the :class:`~django.db.models.Func` documentation\n+for security considerations.\n \n We'll be using the following model in examples of each function::" }, { "filename": "docs/ref/models/expressions.txt", "status": "modified", "additions": 10, "deletions": 0, "changes": 10, "patch": "@@ -434,6 +434,16 @@ replace the attributes of the same name without having to define your own\n class. :ref:`output_field` can be used to define the expected\n return type.\n \n+.. admonition:: Sanitize input used to configure a query expression\n+\n+ Built-in database functions (such as\n+ :class:`~django.db.models.functions.Cast`) vary in whether arguments such\n+ as ``output_field`` can be supplied positionally or only by keyword. For\n+ ``output_field`` and several other cases, the input ultimately reaches\n+ ``Func()`` as a keyword argument, so the advice to avoid constructing\n+ keyword arguments from untrusted user input applies as equally to these\n+ arguments as it does to ``**extra``.\n+\n ``Aggregate()`` expressions\n ---------------------------" } ], "reviews": [ { "id": 3546391425, "user": "user_3a67c55598c5", "state": "COMMENTED", "body": null, "submitted_at": "2025-12-05T20:43:19+00:00" }, { "id": 3547402069, "user": "user_606ba1f2b93c", "state": "COMMENTED", "body": "Thanks [USER_REDACTED] 👍🏾", "submitted_at": "2025-12-06T11:06:46+00:00" }, { "id": 3549688941, "user": "user_cdda8932ec17", "state": "COMMENTED", "body": "I like the wording and the thinking about the proper placement of the docs here, didn't have much to add beyond that I think it will be useful to have a location to point at when related reports surface.\n\nThanks for doing that folks!", "submitted_at": "2025-12-07T23:04:05+00:00" }, { "id": 3552530306, "user": "user_606ba1f2b93c", "state": "APPROVED", "body": "Thank you! 🏆", "submitted_at": "2025-12-08T15:05:07+00:00" } ], "review_comments": [ { "id": 2593942378, "user": "user_3a67c55598c5", "body": "I could be convinced to remove this 🤔", "path": "docs/ref/models/database-functions.txt", "line": null, "side": "RIGHT", "created_at": "2025-12-05T20:43:20+00:00" }, { "id": 2594729165, "user": "user_606ba1f2b93c", "body": "I'm not convinced this is the best placement, as it breaks the flow of the example.\n\nWhat do you think about moving it to https://docs.djangoproject.com/en/6.0/ref/models/expressions/#func-expressions, which introduces the `Func` API and offers security suggestions like\n\n> The **extra kwargs are key=value pairs that can be interpolated into the template attribute. To avoid an SQL injection vulnerability, extra [must not contain untrusted user input](https://docs.djangoproject.com/en/6.0/ref/models/expressions/#avoiding-sql-injection-in-query-expressions) as these values are interpolated into the SQL string rather than passed as query parameters, where the database driver would escape them.\n\nand referencing that in the introduction here with something like \"See the introduction of the Func API for ... security considerations\"", "path": "docs/ref/models/database-functions.txt", "line": null, "side": "RIGHT", "created_at": "2025-12-06T11:02:16+00:00" }, { "id": 2596681005, "user": "user_cdda8932ec17", "body": "yeah I'm on the fence as well. I see where it's coming from as `Cast` is likely the most commonly used expression that will use `output_field` to generate SQL but given there are others that users are likely not aware I feel like this overindex on on ths particular example.", "path": "docs/ref/models/database-functions.txt", "line": null, "side": "RIGHT", "created_at": "2025-12-07T23:02:43+00:00" } ], "meta": { "languages": [ "txt" ], "touches_tests": false, "review_state_summary": { "COMMENTED": 3, "APPROVED": 1 }, "meaningful_comment_count": 3, "has_approval": true, "has_changes_requested": false, "total_review_comments": 3 } } { "_id": "86fb276a3300499e", "_schema_version": "1.0", "_cleaned_at": "2026-02-12T07:46:51.609057+00:00", "repo": "django/django", "repo_url": "https://github.com/django/django", "license_name": "BSD 3-Clause \"New\" or \"Revised\" License", "license_spdx": "BSD-3-Clause", "pr_number": 20374, "title": "Fixed #26434 -- Removed faulty clearing of ordering field when missing from explicit grouping.", "body": "#### Trac ticket number\n\n\nticket-26434\n\n#### Branch description\nThis is a fix for a broken functionality directly related to the use of `queryset.count()` and `queryset.aggregate(...)`, i.e., a fix for the `QuerySet API`.\n\nThe issue itself describes the problem well, but in short: the ORM, due to overly aggressive SQL query optimization, removes parts of order_by even for columns that are not logically part of group_by.\n\nOne solution was already in master, but it was flawed from two perspectives:\n1. Typically, the order_by part is just text, while the group_by part consists of column objects (Col). The previous solution did not reliably compare these two sets.\n2. The fix was placed in the shared logic for aggressive SQL query optimization. This is not the right place here - we want the fix to reside in the final top-level aggregation, i.e., the method `query.get_aggregate(...)`.\n\nPlease provide feedback on:\n1. The tests that have been written.\n2. Whether the implementation is headed in the right direction.\n3. What is missing in the implementation or what could be improved.\n4. Anything else you think is worth discussing.\n\n#### Checklist\n- [x] This PR targets the `main` branch. \n- [x] The commit message is written in past tense, mentions the ticket number, and ends with a period.\n- [x] I have checked the \"Has patch\" ticket flag in the Trac system.\n- [x] I have added or updated relevant tests.", "author": "user_02c5bf403fbc", "created_at": "2025-12-05T16:09:34+00:00", "merged_at": "2025-12-15T20:23:51+00:00", "base_branch": "main", "head_branch": "ticket_26434", "additions": 47, "deletions": 1, "changed_files": 2, "files": [ { "filename": "django/db/models/sql/query.py", "status": "modified", "additions": 29, "deletions": 1, "changes": 30, "patch": "@@ -534,7 +534,8 @@ def get_aggregation(self, using, aggregate_exprs):\n # Queries with distinct_fields need ordering and when a limit is\n # applied we must take the slice from the ordered query. Otherwise\n # no need for ordering.\n- inner_query.clear_ordering(force=False)\n+ if inner_query.orderby_issubset_groupby:\n+ inner_query.clear_ordering(force=False)\n if not inner_query.distinct:\n # If the inner query uses default select and it has some\n # aggregate annotations, then we must make sure the inner\n@@ -2338,6 +2339,33 @@ def add_ordering(self, *ordering):\n else:\n self.default_ordering = False\n \n+ [USER_REDACTED]\n+ def orderby_issubset_groupby(self):\n+ if self.extra_order_by:\n+ # Raw SQL from extra(order_by=...) can't be reliably compared\n+ # against resolved OrderBy/Col expressions. Treat as not a subset.\n+ return False\n+ if self.group_by in (None, True):\n+ # There is either no aggregation at all (None), or the group by\n+ # is generated automatically from model fields (True), in which\n+ # case the order by [NAME_REDACTED] a subset of them.\n+ return True\n+ if not self.order_by:\n+ # Although an empty set is always a subset, there's no point in\n+ # clearing ordering when there isn't any. Avoid the clone() below.\n+ return True\n+ # Don't pollute the original query (might disrupt joins).\n+ q = self.clone()\n+ order_by_set = {\n+ (\n+ order_by.resolve_expression(q)\n+ if hasattr(order_by, \"resolve_expression\")\n+ else F(order_by).resolve_expression(q)\n+ )\n+ for order_by in q.order_by\n+ }\n+ return order_by_set.issubset(self.group_by)\n+\n def clear_ordering(self, force=False, clear_default=True):\n \"\"\"\n Remove any ordering settings if the current query allows it without" }, { "filename": "tests/aggregation_regress/tests.py", "status": "modified", "additions": 18, "deletions": 0, "changes": 18, "patch": "@@ -171,6 +171,24 @@ def assertObjectAttrs(self, obj, **kwargs):\n for attr, value in kwargs.items():\n self.assertEqual(getattr(obj, attr), value)\n \n+ def test_count_preserve_group_by(self):\n+ # new release of the same book\n+ Book.objects.create(\n+ isbn=\"113235613\",\n+ name=self.b4.name,\n+ pages=self.b4.pages,\n+ rating=4.0,\n+ price=Decimal(\"39.69\"),\n+ contact=self.a5,\n+ publisher=self.p3,\n+ pubdate=datetime.date(2018, 11, 3),\n+ )\n+ qs = Book.objects.values(\"contact__name\", \"publisher__name\").annotate(\n+ publications=Count(\"id\")\n+ )\n+ self.assertEqual(qs.order_by(\"id\").count(), len(qs.order_by(\"id\")))\n+ self.assertEqual(qs.extra(order_by=[\"id\"]).count(), len(qs.order_by(\"id\")))\n+\n def test_annotation_with_value(self):\n values = (\n Book.objects.filter(" } ], "reviews": [ { "id": 3545843982, "user": "user_cdda8932ec17", "state": "COMMENTED", "body": null, "submitted_at": "2025-12-05T18:11:53+00:00" }, { "id": 3545850810, "user": "user_cdda8932ec17", "state": "COMMENTED", "body": null, "submitted_at": "2025-12-05T18:13:47+00:00" }, { "id": 3546493481, "user": "user_cdda8932ec17", "state": "COMMENTED", "body": null, "submitted_at": "2025-12-05T21:26:04+00:00" }, { "id": 3546505501, "user": "user_cdda8932ec17", "state": "COMMENTED", "body": "I really like the idea of creating a clone to resolve the `order_by` without polluting the query with then unused `JOIN`s [USER_REDACTED] thanks for that!\n\nI left some comments that I think are aligned with the kind of feedback you were requesting, mainly around ways to avoid unnecessary cloning and resolving as these can be expensive.\n\nThanks for giving this second shot.", "submitted_at": "2025-12-05T21:34:41+00:00" }, { "id": 3549261569, "user": "user_02c5bf403fbc", "state": "COMMENTED", "body": null, "submitted_at": "2025-12-07T12:47:04+00:00" }, { "id": 3549691476, "user": "user_cdda8932ec17", "state": "APPROVED", "body": "The logic seem sane to be, made very cosmetic comments that can be handled by [NAME_REDACTED] be but otherwise this looks good to go.", "submitted_at": "2025-12-07T23:16:26+00:00" }, { "id": 3550853987, "user": "user_02c5bf403fbc", "state": "COMMENTED", "body": null, "submitted_at": "2025-12-08T08:53:59+00:00" }, { "id": 3550943383, "user": "user_02c5bf403fbc", "state": "COMMENTED", "body": null, "submitted_at": "2025-12-08T09:10:30+00:00" }, { "id": 3573016897, "user": "user_3a67c55598c5", "state": "COMMENTED", "body": null, "submitted_at": "2025-12-12T18:05:55+00:00" }, { "id": 3573168229, "user": "user_3a67c55598c5", "state": "COMMENTED", "body": "Thanks, last remaining question for me just relates to `extra`.", "submitted_at": "2025-12-12T18:51:07+00:00" }, { "id": 3573174810, "user": "user_cdda8932ec17", "state": "COMMENTED", "body": null, "submitted_at": "2025-12-12T18:52:41+00:00" }, { "id": 3573193448, "user": "user_cdda8932ec17", "state": "COMMENTED", "body": null, "submitted_at": "2025-12-12T18:57:15+00:00" }, { "id": 3573213640, "user": "user_02c5bf403fbc", "state": "COMMENTED", "body": null, "submitted_at": "2025-12-12T19:03:08+00:00" }, { "id": 3573214115, "user": "user_3a67c55598c5", "state": "COMMENTED", "body": null, "submitted_at": "2025-12-12T19:03:20+00:00" }, { "id": 3573232582, "user": "user_3a67c55598c5", "state": "COMMENTED", "body": null, "submitted_at": "2025-12-12T19:08:50+00:00" }, { "id": 3573237461, "user": "user_cdda8932ec17", "state": "COMMENTED", "body": null, "submitted_at": "2025-12-12T19:09:48+00:00" }, { "id": 3573368567, "user": "user_3a67c55598c5", "state": "APPROVED", "body": "Thank you!", "submitted_at": "2025-12-12T19:47:50+00:00" }, { "id": 3573395284, "user": "user_3a67c55598c5", "state": "COMMENTED", "body": null, "submitted_at": "2025-12-12T19:56:47+00:00" }, { "id": 3573400473, "user": "user_3a67c55598c5", "state": "COMMENTED", "body": null, "submitted_at": "2025-12-12T19:58:16+00:00" }, { "id": 3573414473, "user": "user_02c5bf403fbc", "state": "COMMENTED", "body": null, "submitted_at": "2025-12-12T20:03:27+00:00" }, { "id": 3573557041, "user": "user_3a67c55598c5", "state": "COMMENTED", "body": null, "submitted_at": "2025-12-12T20:47:41+00:00" }, { "id": 3573570145, "user": "user_3a67c55598c5", "state": "COMMENTED", "body": null, "submitted_at": "2025-12-12T20:52:17+00:00" }, { "id": 3573969066, "user": "user_3a67c55598c5", "state": "COMMENTED", "body": null, "submitted_at": "2025-12-13T00:26:12+00:00" }, { "id": 3574067296, "user": "user_cdda8932ec17", "state": "COMMENTED", "body": null, "submitted_at": "2025-12-13T01:33:34+00:00" }, { "id": 3574107610, "user": "user_3a67c55598c5", "state": "COMMENTED", "body": null, "submitted_at": "2025-12-13T02:42:03+00:00" }, { "id": 3574137984, "user": "user_cdda8932ec17", "state": "COMMENTED", "body": null, "submitted_at": "2025-12-13T03:10:40+00:00" }, { "id": 3574415795, "user": "user_3a67c55598c5", "state": "COMMENTED", "body": null, "submitted_at": "2025-12-13T14:54:03+00:00" }, { "id": 3574426543, "user": "user_cdda8932ec17", "state": "COMMENTED", "body": null, "submitted_at": "2025-12-13T15:22:56+00:00" } ], "review_comments": [ { "id": 2593529018, "user": "user_cdda8932ec17", "body": "No need to clone immediately for these two check as it's a potentially costly operation.\n\n```suggestion\n if self.group_by is False:\n # there is no use case for that, but we need to be sure\n return False\n if self.group_by in (None, True):\n # it seems like there is no aggregation at all (None)\n # or there are all required groupbies(True) generated automatically\n # from models fields - so, it is safe to clear ordering\n return True\n q = self.clone()\n```", "path": "django/db/models/sql/query.py", "line": null, "side": "RIGHT", "created_at": "2025-12-05T18:11:52+00:00" }, { "id": 2593533846, "user": "user_cdda8932ec17", "body": "You can also avoid the clone if `not (q.order_by or q.extra_order_by)` I believe as an empty set is necessarily a subset of the group by.", "path": "django/db/models/sql/query.py", "line": null, "side": "RIGHT", "created_at": "2025-12-05T18:13:47+00:00" }, { "id": 2594028927, "user": "user_cdda8932ec17", "body": "Should we still delegate to `clear_ordering` with `force=True` instead?\n\n```suggestion\n if (\n not inner_query.is_sliced\n and not inner_query.distinct_fields\n and inner_query.orderby_issubset_groupby\n ):\n inner_query.clear_ordering(force=True)\n```", "path": "django/db/models/sql/query.py", "line": null, "side": "RIGHT", "created_at": "2025-12-05T21:26:04+00:00" }, { "id": 2594039459, "user": "user_cdda8932ec17", "body": "Do we have members of `group_by` which are not already resolved? I thought they must be already resolved since they are plucked from `Query.select` and `annotations`.\n\nhttps://github.com/[USER_REDACTED]ngo/django/blob/020e5799ad74cfafd469f032cd05767c9d670a16/django/db/models/sql/query.py#L2383-L2391\n\nassuming this is the case it means it could be reduced to\n\n```suggestion\n return order_by_set.issubset(self.group_by)\n```", "path": "django/db/models/sql/query.py", "line": null, "side": "RIGHT", "created_at": "2025-12-05T21:31:57+00:00" }, { "id": 2596285220, "user": "user_02c5bf403fbc", "body": "I made changes, thank you for the catch.", "path": "django/db/models/sql/query.py", "line": null, "side": "RIGHT", "created_at": "2025-12-07T12:47:04+00:00" }, { "id": 2596683385, "user": "user_cdda8932ec17", "body": "I feel like the last assertion is enough as it keeps the ticket focused on the problem at play (mismatch in length between count and `len`) but mergers will\n\n```suggestion\n self.assertEqual(qs.order_by(\"id\").count(), len(qs.order_by(\"id\")))\n```", "path": "tests/aggregation_regress/tests.py", "line": null, "side": "RIGHT", "created_at": "2025-12-07T23:07:09+00:00" }, { "id": 2596684186, "user": "user_cdda8932ec17", "body": "Similar story here and you can drop the ticket reference as it's _baked_ into the commit message and easily referenceable through blame.\n\n```suggestion\n self.assertEqual(\n qs.order_by(\"id\").aggregate(Avg(\"rating\"))[\"rating__avg\"],\n (12.5 + 4 * 4.0) / 7,\n )\n\n```", "path": "tests/aggregation_regress/tests.py", "line": null, "side": "RIGHT", "created_at": "2025-12-07T23:08:41+00:00" }, { "id": 2596684991, "user": "user_cdda8932ec17", "body": "Maybe harm is too harsh and we want to use _pollute_ but I'm not native speaker", "path": "django/db/models/sql/query.py", "line": null, "side": "RIGHT", "created_at": "2025-12-07T23:09:32+00:00" }, { "id": 2596686043, "user": "user_cdda8932ec17", "body": "If there is no use case it means it's dead code from its inception and thus and it can be removed.\n\n`Query.group_by` appears to be `None | True | tuple[Compilable]`", "path": "django/db/models/sql/query.py", "line": null, "side": "RIGHT", "created_at": "2025-12-07T23:10:54+00:00" }, { "id": 2596689748, "user": "user_cdda8932ec17", "body": "Minor but the _it is safe to clear ordering_ assumes the sole caller will always be for order clearing purpose.\n\nMaybe something along the lines of \n\n```\nWhen grouping by [NAME_REDACTED] by [NAME_REDACTED] a subset of the group by.\n```", "path": "django/db/models/sql/query.py", "line": null, "side": "RIGHT", "created_at": "2025-12-07T23:15:31+00:00" }, { "id": 2597649370, "user": "user_02c5bf403fbc", "body": "I will edit it.", "path": "django/db/models/sql/query.py", "line": null, "side": "RIGHT", "created_at": "2025-12-08T08:53:59+00:00" }, { "id": 2597716966, "user": "user_02c5bf403fbc", "body": "Finally I returned it back, when there is not the code, it breaks a test\n\n```\nFAIL: test_crafted_xml_performance (serializers.test_deserialization.TestDeserializer.test_crafted_xml_performance) [varying depth, varying length]\nThe time to process invalid inputs is not quadratic.\n----------------------------------------------------------------------\nTraceback (most recent call last):\n File \"/home/mmladek/.pyenv/versions/3.13.5/lib/python3.13/unittest/case.py\", line 58, in testPartExecutor\n yield\n File \"/home/mmladek/.pyenv/versions/3.13.5/lib/python3.13/unittest/case.py\", line 556, in subTest\n yield\n File \"/home/mmladek/projects/django/tests/serializers/test_deserialization.py\", line 182, in assertFactor\n self.assertLessEqual(sum(factors) / len(factors), factor)\n ^^^^^^^\n File \"/home/mmladek/.pyenv/versions/3.13.5/lib/python3.13/unittest/case.py\", line 1285, in assertLessEqual\n self.fail(self._formatMessage(msg, standardMsg))\n ^^^^^^^^^^^\n File \"/home/mmladek/.pyenv/versions/3.13.5/lib/python3.13/unittest/case.py\", line 732, in fail\n raise self.failureException(msg)\n ^^^^^^^^^^^^^^^\nAssertionError: 2.930120819494018 not less than or equal to 2\n\n======================================================================\nFAIL: test_crafted_xml_performance (serializers.test_deserialization.TestDeserializer.test_crafted_xml_performance) [constant depth, varying length]\nThe time to process invalid inputs is not quadratic.\n----------------------------------------------------------------------\nTraceback (most recent call last):\n File \"/home/mmladek/.pyenv/versions/3.13.5/lib/python3.13/unittest/case.py\", line 58, in testPartExecutor\n yield\n File \"/home/mmladek/.pyenv/versions/3.13.5/lib/python3.13/unittest/case.py\", line 556, in subTest\n yield\n File \"/home/mmladek/projects/django/tests/serializers/test_deserialization.py\", line 182, in assertFactor\n self.assertLessEqual(sum(factors) / len(factors), factor)\n ^^^^^^^\n File \"/home/mmladek/.pyenv/versions/3.13.5/lib/python3.13/unittest/case.py\", line 1285, in assertLessEqual\n self.fail(self._formatMessage(msg, standardMsg))\n ^^^^^^^^^^^\n File \"/home/mmladek/.pyenv/versions/3.13.5/lib/python3.13/unittest/case.py\", line 732, in fail\n raise self.failureException(msg)\n ^^^^^^^^^^^^^^^\nAssertionError: 2.69819775823359 not less than or equal to 2\n```\nI dont have a hunch why ...", "path": "django/db/models/sql/query.py", "line": null, "side": "RIGHT", "created_at": "2025-12-08T09:10:29+00:00" }, { "id": 2615132395, "user": "user_3a67c55598c5", "body": "That's an [unrelated flaky test that we're addressing](https://code.djangoproject.com/ticket/36769#comment:9) as soon as Python issues a patch release of 3.12.", "path": "django/db/models/sql/query.py", "line": null, "side": "RIGHT", "created_at": "2025-12-12T18:05:54+00:00" }, { "id": 2615244857, "user": "user_3a67c55598c5", "body": "`extra_order_by` is composed of strings, don't we need to resolve them to `Col`s as well?", "path": "django/db/models/sql/query.py", "line": null, "side": "RIGHT", "created_at": "2025-12-12T18:50:47+00:00" }, { "id": 2615249469, "user": "user_cdda8932ec17", "body": "[USER_REDACTED] they can't; `extra_order_by` is this weird thing coming from `extra(order_by)` which is raw SQL.\n\nI've been trying to kill it #16681 for reference.", "path": "django/db/models/sql/query.py", "line": null, "side": "RIGHT", "created_at": "2025-12-12T18:52:41+00:00" }, { "id": 2615262628, "user": "user_cdda8932ec17", "body": "Not sure if `extra(select)` ever end up in `group_by` but we are definitely more interested in `q.extra_order_by.values()` here.\n\nMaybe we could return `False` the moment `bool(q.extra_order_by)` until we finally kill it?", "path": "django/db/models/sql/query.py", "line": null, "side": "RIGHT", "created_at": "2025-12-12T18:57:15+00:00" }, { "id": 2615276838, "user": "user_02c5bf403fbc", "body": "Yes, makes sense. extra(order_by) is just the weird legacy case we need to account for. I'll update the patch accordingly.", "path": "django/db/models/sql/query.py", "line": null, "side": "RIGHT", "created_at": "2025-12-12T19:03:08+00:00" }, { "id": 2615277284, "user": "user_3a67c55598c5", "body": "The test case I just pushed gives me this:\n```py\n(Pdb) print(q.extra_order_by)\n['id']\n```", "path": "django/db/models/sql/query.py", "line": null, "side": "RIGHT", "created_at": "2025-12-12T19:03:20+00:00" }, { "id": 2615290542, "user": "user_3a67c55598c5", "body": "> this weird thing coming from extra(order_by) which is raw SQL.\n\nOh, then I guess my test isn't realistic.", "path": "django/db/models/sql/query.py", "line": null, "side": "RIGHT", "created_at": "2025-12-12T19:08:49+00:00" }, { "id": 2615293375, "user": "user_cdda8932ec17", "body": "You're completely right, it's a not a `dict` at all, it's a collection of raw SQL (I got confused with `extra_select`)\n\nIn this case the `.values()` doesn't make sense but unless we want to invest time in enabling this optimization in the presence of `extra(order_by)` (which is documented to be deprecated) it might be better to opt-out by returning `False` immediately in its presence.", "path": "django/db/models/sql/query.py", "line": null, "side": "RIGHT", "created_at": "2025-12-12T19:09:48+00:00" }, { "id": 2615411906, "user": "user_3a67c55598c5", "body": "Is there a reason you didn't opt for:\n```suggestion\n if inner_query.orderby_issubset_groupby:\n inner_query.clear_ordering(force=False)\n```", "path": "django/db/models/sql/query.py", "line": 2371, "side": "RIGHT", "created_at": "2025-12-12T19:56:47+00:00" }, { "id": 2615415580, "user": "user_3a67c55598c5", "body": "Github chewed up my last comment, leaving it again.\n\nIs there reason you didn't opt for:\n```suggestion\n if inner_query.orderby_issubset_groupby:\n inner_query.clear_ordering(force=False)\n```", "path": "django/db/models/sql/query.py", "line": null, "side": "RIGHT", "created_at": "2025-12-12T19:58:13+00:00" }, { "id": 2615426796, "user": "user_02c5bf403fbc", "body": "I followed blindly the comments (line: 534) hoping that is true:\n```python\n# Queries with distinct_fields need ordering and when a limit is\n# applied we must take the slice from the ordered query. Otherwise\n# no need for ordering.\n```", "path": "django/db/models/sql/query.py", "line": null, "side": "RIGHT", "created_at": "2025-12-12T20:03:27+00:00" }, { "id": 2615539927, "user": "user_3a67c55598c5", "body": "For sure, I just mean the `clear_ordering()` actually handles that for you and also checks `select_for_update`. See the beginning of `clear_ordering()`.\n\nJust so that we don't actually introduce any drift against that implementation, I'll roll this in for you 👍", "path": "django/db/models/sql/query.py", "line": null, "side": "RIGHT", "created_at": "2025-12-12T20:47:41+00:00" }, { "id": 2615551547, "user": "user_3a67c55598c5", "body": "I was about to change this to assertAlmostEqual just out of paranoia about the decimal value, when I realized I think the other test is sufficient. I think Simon suggested something along those lines. I'll remove it.", "path": "tests/aggregation_regress/tests.py", "line": null, "side": "RIGHT", "created_at": "2025-12-12T20:52:17+00:00" }, { "id": 2615898688, "user": "user_3a67c55598c5", "body": "Just noticed from the coverage report that this line is not covered. When would `self.group_by` be an empty iterable?", "path": "django/db/models/sql/query.py", "line": 2356, "side": "RIGHT", "created_at": "2025-12-13T00:26:12+00:00" }, { "id": 2615969005, "user": "user_cdda8932ec17", "body": "With the current call site never as we only get in this branch `if isinstance(self.group_by, tuple)` which means the queryset was previously annotated with an aggregate expression and that there was at least one value passed to `values` to specify the group by [NAME_REDACTED] might be handy if `orderby_issubset_groupby` is eventually called from other context but in with this single call site it's not.", "path": "django/db/models/sql/query.py", "line": 2356, "side": "RIGHT", "created_at": "2025-12-13T01:33:34+00:00" }, { "id": 2616006109, "user": "user_3a67c55598c5", "body": "Shouldn't we also short-circuit if `self.order_by` is empty and `self.group_by` is non-empty?\n\nAnd if `self.order_by` is non-empty but `self.group_by` is empty, we could also short-circuit but return `False`.", "path": "django/db/models/sql/query.py", "line": 2356, "side": "RIGHT", "created_at": "2025-12-13T02:42:03+00:00" }, { "id": 2616021621, "user": "user_cdda8932ec17", "body": "> Shouldn't we also short-circuit if self.order_by is empty and self.group_by is non-empty?\n\nWe could yes to be coherent with the method name but if there is no ordering there is little value in clearing it.\n\n> And if self.order_by is non-empty but self.group_by is empty, we could also short-circuit but return False.\n\nSame story IMO, we have to choose a side.\n\nDo we want to make the function caller aware (make choices knowing it will only be called in the context of `get_aggregation`) or make it general purposed with all the optimization possible but harder to exercise through code coverage.", "path": "django/db/models/sql/query.py", "line": 2356, "side": "RIGHT", "created_at": "2025-12-13T03:10:40+00:00" }, { "id": 2616350203, "user": "user_3a67c55598c5", "body": "Thanks, I'm just not understanding why `group_by` is in this condition; your earlier suggestion had `extra_order_by` there instead.\n\n> We could yes to be coherent with the method name but if there is no ordering there is little value in clearing it.\n\nIn that case, I think we should either change this to\n```py\nif not order_by:\n # Empty sets are always subsets, but there's no point in clearing an ordering.\n return False\n```\nOr just remove it altogether.\n\nIf we do that suggested tweak, then we're not doing all possible optimizations but we are doing the most likely one.", "path": "django/db/models/sql/query.py", "line": 2356, "side": "RIGHT", "created_at": "2025-12-13T14:54:03+00:00" }, { "id": 2616364210, "user": "user_cdda8932ec17", "body": "I'm good with switching it to solely checking `not order_by` 👍", "path": "django/db/models/sql/query.py", "line": 2356, "side": "RIGHT", "created_at": "2025-12-13T15:22:56+00:00" } ], "meta": { "languages": [ "py" ], "touches_tests": true, "review_state_summary": { "COMMENTED": 26, "APPROVED": 2 }, "meaningful_comment_count": 31, "has_approval": true, "has_changes_requested": false, "total_review_comments": 31 } } { "_id": "6f56c91ffca2aee3", "_schema_version": "1.0", "_cleaned_at": "2026-02-12T07:46:51.609057+00:00", "repo": "django/django", "repo_url": "https://github.com/django/django", "license_name": "BSD 3-Clause \"New\" or \"Revised\" License", "license_spdx": "BSD-3-Clause", "pr_number": 20370, "title": "Fixed #36768 -- Optimized string concatenation in File.__iter__().", "body": "#### Trac ticket number\n\n\nticket-36768 \n\n#### Branch description\nAddresses ticket #36768 by [NAME_REDACTED] in File._ _iter__ Chunks are now collected in a list and joined only when necessary, fixing performance degradation associated with processing split lines.\n\n#### Checklist\n- [x] This PR targets the `main` branch. \n- [x] The commit message is written in past tense, mentions the ticket number, and ends with a period.\n- [x] I have checked the \"Has patch\" ticket flag in the Trac system.\n- [ ] I have added or updated relevant tests.\n- [ ] I have added or updated relevant docs, including release notes if applicable.\n- [ ] I have attached screenshots in both light and dark modes for any UI changes.", "author": "user_95f516637e24", "created_at": "2025-12-04T08:39:44+00:00", "merged_at": "2025-12-09T21:45:13+00:00", "base_branch": "main", "head_branch": "ticket-36768", "additions": 18, "deletions": 15, "changed_files": 1, "files": [ { "filename": "django/core/files/base.py", "status": "modified", "additions": 18, "deletions": 15, "changes": 33, "patch": "@@ -74,30 +74,33 @@ def multiple_chunks(self, chunk_size=None):\n \n def __iter__(self):\n # Iterate over this file-like object by newlines\n- buffer_ = None\n+ buffer_ = []\n for chunk in self.chunks():\n for line in chunk.splitlines(True):\n if buffer_:\n- if endswith_cr(buffer_) and not equals_lf(line):\n+ if endswith_cr(buffer_[-1]) and not equals_lf(line):\n # Line split after a \\r newline; yield buffer_.\n- yield buffer_\n+ yield type(buffer_[0])().join(buffer_)\n # Continue with line.\n+ buffer_ = []\n else:\n # Line either split without a newline (line\n # continues after buffer_) or with \\r\\n\n # newline (line == b'\\n').\n- line = buffer_ + line\n- # buffer_ handled, clear it.\n- buffer_ = None\n-\n- # If this is the end of a \\n or \\r\\n line, yield.\n- if endswith_lf(line):\n- yield line\n- else:\n- buffer_ = line\n-\n- if buffer_ is not None:\n- yield buffer_\n+ buffer_.append(line)\n+\n+ if not buffer_:\n+ # If this is the end of a \\n or \\r\\n line, yield.\n+ if endswith_lf(line):\n+ yield line\n+ else:\n+ buffer_.append(line)\n+ elif endswith_lf(line):\n+ yield type(buffer_[0])().join(buffer_)\n+ buffer_ = []\n+\n+ if buffer_:\n+ yield type(buffer_[0])().join(buffer_)\n \n def __enter__(self):\n return self" } ], "reviews": [ { "id": 3541509229, "user": "user_3a67c55598c5", "state": "APPROVED", "body": "Thanks 👍 \n\nI made a tweak to preserve the existing comments.", "submitted_at": "2025-12-04T19:53:45+00:00" } ], "review_comments": [ { "id": 2590154473, "user": "user_3a67c55598c5", "body": "Let's try to keep the type consistent. Will require changes above & below.\n```suggestion\n buffer_ = []\n```", "path": "django/core/files/base.py", "line": null, "side": "RIGHT", "created_at": "2025-12-04T18:34:19+00:00" } ], "meta": { "languages": [ "py" ], "touches_tests": false, "review_state_summary": { "APPROVED": 1 }, "meaningful_comment_count": 1, "has_approval": true, "has_changes_requested": false, "total_review_comments": 1 } } { "_id": "4903306ba74c359f", "_schema_version": "1.0", "_cleaned_at": "2026-02-12T07:46:51.609057+00:00", "repo": "django/django", "repo_url": "https://github.com/django/django", "license_name": "BSD 3-Clause \"New\" or \"Revised\" License", "license_spdx": "BSD-3-Clause", "pr_number": 20369, "title": "Added DatabaseFeatures.prohibits_dollar_signs_in_column_aliases.", "body": "This is also applicable on CockroachDB.\n\nFollow up to 5b90ca1e7591fa36fccf2d6dad67cf1477e6293e.", "author": "user_657e90e5ae46", "created_at": "2025-12-04T00:43:49+00:00", "merged_at": "2025-12-04T16:37:22+00:00", "base_branch": "main", "head_branch": "prohibits_dollar_signs_in_column_aliases", "additions": 19, "deletions": 12, "changed_files": 5, "files": [ { "filename": "django/db/backends/base/features.py", "status": "modified", "additions": 4, "deletions": 0, "changes": 4, "patch": "@@ -415,6 +415,10 @@ class BaseDatabaseFeatures:\n # Does the Round() database function round to even?\n rounds_to_even = False\n \n+ # Should dollar signs be prohibited in column aliases to prevent SQL\n+ # injection?\n+ prohibits_dollar_signs_in_column_aliases = False\n+\n # A set of dotted paths to tests in Django's test suite that are expected\n # to fail on this database.\n django_test_expected_failures = set()" }, { "filename": "django/db/backends/postgresql/compiler.py", "status": "modified", "additions": 1, "deletions": 10, "changes": 11, "patch": "@@ -1,6 +1,6 @@\n from django.db.models.sql.compiler import ( # isort:skip\n SQLAggregateCompiler,\n- SQLCompiler as BaseSQLCompiler,\n+ SQLCompiler,\n SQLDeleteCompiler,\n SQLInsertCompiler as BaseSQLInsertCompiler,\n SQLUpdateCompiler,\n@@ -25,15 +25,6 @@ def __str__(self):\n return \"UNNEST(%s)\" % \", \".join(self)\n \n \n-class SQLCompiler(BaseSQLCompiler):\n- def quote_name_unless_alias(self, name):\n- if \"$\" in name:\n- raise ValueError(\n- \"Dollar signs are not permitted in column aliases on PostgreSQL.\"\n- )\n- return super().quote_name_unless_alias(name)\n-\n-\n class SQLInsertCompiler(BaseSQLInsertCompiler):\n def assemble_as_sql(self, fields, value_rows):\n # Specialize bulk-insertion of literal values through UNNEST to" }, { "filename": "django/db/backends/postgresql/features.py", "status": "modified", "additions": 1, "deletions": 0, "changes": 1, "patch": "@@ -70,6 +70,7 @@ class DatabaseFeatures(BaseDatabaseFeatures):\n supports_nulls_distinct_unique_constraints = True\n supports_no_precision_decimalfield = True\n can_rename_index = True\n+ prohibits_dollar_signs_in_column_aliases = True\n test_collations = {\n \"deterministic\": \"C\",\n \"non_default\": \"sv-x-icu\"," }, { "filename": "django/db/models/sql/compiler.py", "status": "modified", "additions": 8, "deletions": 0, "changes": 8, "patch": "@@ -553,6 +553,14 @@ def quote_name_unless_alias(self, name):\n for table names. This avoids problems with some SQL dialects that treat\n quoted strings specially (e.g. PostgreSQL).\n \"\"\"\n+ if (\n+ self.connection.features.prohibits_dollar_signs_in_column_aliases\n+ and \"$\" in name\n+ ):\n+ raise ValueError(\n+ \"Dollar signs are not permitted in column aliases on \"\n+ f\"{self.connection.display_name}.\"\n+ )\n if name in self.quote_cache:\n return self.quote_cache[name]\n if (" }, { "filename": "tests/annotations/tests.py", "status": "modified", "additions": 5, "deletions": 2, "changes": 7, "patch": "@@ -1545,8 +1545,11 @@ def test_alias_filtered_relation_sql_injection_dollar_sign(self):\n qs = Book.objects.alias(\n **{\"crafted_alia$\": FilteredRelation(\"authors\")}\n ).values(\"name\", \"crafted_alia$\")\n- if connection.vendor == \"postgresql\":\n- msg = \"Dollar signs are not permitted in column aliases on PostgreSQL.\"\n+ if connection.features.prohibits_dollar_signs_in_column_aliases:\n+ msg = (\n+ \"Dollar signs are not permitted in column aliases on \"\n+ f\"{connection.display_name}.\"\n+ )\n with self.assertRaisesMessage(ValueError, msg):\n list(qs)\n else:" } ], "reviews": [ { "id": 3539390119, "user": "user_194c2ef4033e", "state": "COMMENTED", "body": null, "submitted_at": "2025-12-04T11:04:09+00:00" }, { "id": 3540486057, "user": "user_657e90e5ae46", "state": "COMMENTED", "body": null, "submitted_at": "2025-12-04T15:06:09+00:00" }, { "id": 3540502191, "user": "user_3a67c55598c5", "state": "COMMENTED", "body": "Thanks, Tim! I assume this should be backported?", "submitted_at": "2025-12-04T15:09:30+00:00" }, { "id": 3540502856, "user": "user_3a67c55598c5", "state": "APPROVED", "body": null, "submitted_at": "2025-12-04T15:09:39+00:00" } ], "review_comments": [ { "id": 2588577393, "user": "user_194c2ef4033e", "body": "Now that we have a flag for this, I suppose we could just move this into the top of the method in the base class in `django/db/models/sql/compiler.py`?\n\n```python\n if \"$\" in name and self.connection.features.prohibits_dollar_signs_in_column_aliases:\n raise ValueError(\n \"Dollar signs are not permitted in column aliases on \"\n f\"{self.connection.display_name}.\"\n )", "path": "django/db/backends/postgresql/compiler.py", "line": null, "side": "RIGHT", "created_at": "2025-12-04T11:02:32+00:00" }, { "id": 2588583262, "user": "user_194c2ef4033e", "body": "Maybe `prohibits_dollar_char_in_column_aliases` or `prohibits_dollar_in_column_aliases`?", "path": "django/db/backends/base/features.py", "line": 420, "side": "RIGHT", "created_at": "2025-12-04T11:04:00+00:00" }, { "id": 2589449087, "user": "user_657e90e5ae46", "body": "I think it's okay. It's called a dollar sign, not a dollar character. :-D", "path": "django/db/backends/base/features.py", "line": 420, "side": "RIGHT", "created_at": "2025-12-04T15:06:09+00:00" } ], "meta": { "languages": [ "py" ], "touches_tests": true, "review_state_summary": { "COMMENTED": 3, "APPROVED": 1 }, "meaningful_comment_count": 3, "has_approval": true, "has_changes_requested": false, "total_review_comments": 3 } } { "_id": "1cb5de72b879aca8", "_schema_version": "1.0", "_cleaned_at": "2026-02-12T07:46:51.609057+00:00", "repo": "django/django", "repo_url": "https://github.com/django/django", "license_name": "BSD 3-Clause \"New\" or \"Revised\" License", "license_spdx": "BSD-3-Clause", "pr_number": 20368, "title": "Refs #35581 -- Fixed email image inline attachment example.", "body": "#### Trac ticket number\n\nticket-35581\n\n#### Branch description\n\nCorrect this example, after testing a version of it for my Django 6.0 blog post and finding it needed fixing.\n\n1. Added imports and setup for clarity.\n2. Removed adding `<` and `>` to Content-ID, as `make_msgid()` already includes them.\n3. Removed `$` from reference in HTML, and instead stripped `<>` there, as required by HTML `cid:` references.\n\n#### Checklist\n- [x] This PR targets the `main` branch. \n- [x] The commit message is written in past tense, mentions the ticket number, and ends with a period.\n- [x] I have checked the \"Has patch\" ticket flag in the Trac system.\n- [x] I have added or updated relevant tests.\n- [x] I have added or updated relevant docs, including release notes if applicable.\n- [x] I have attached screenshots in both light and dark modes for any UI changes.", "author": "user_8fc305198eb3", "created_at": "2025-12-03T23:01:02+00:00", "merged_at": "2025-12-08T14:44:19+00:00", "base_branch": "main", "head_branch": "fix_email_cid", "additions": 12, "deletions": 3, "changed_files": 1, "files": [ { "filename": "docs/topics/email.txt", "status": "modified", "additions": 12, "deletions": 3, "changes": 15, "patch": "@@ -471,17 +471,26 @@ email backend API :ref:`provides an alternative\n directly to the resulting message. For example, to attach an inline\n image with a :mailheader:`Content-ID`::\n \n+ import email.utils\n+ from email.message import MIMEPart\n+ from django.core.mail import EmailMultiAlternatives\n+\n+ message = EmailMultiAlternatives(...)\n+ image_data_bytes = ... # Load image as bytes\n+\n+ # Create a random Content-ID, including angle brackets\n cid = email.utils.make_msgid()\n inline_image = email.message.MIMEPart()\n inline_image.set_content(\n image_data_bytes,\n maintype=\"image\",\n- subtype=\"png\",\n+ subtype=\"png\", # or \"jpeg\", etc. depending on the image type\n disposition=\"inline\",\n- cid=f\"<{cid}>\",\n+ cid=cid,\n )\n message.attach(inline_image)\n- message.attach_alternative(f'… …', \"text/html\")\n+ # Refer to Content-ID in HTML without angle brackets\n+ message.attach_alternative(f'… …', \"text/html\")\n \n Python's :meth:`email.contentmanager.set_content` documentation\n describes the supported arguments for ``MIMEPart.set_content()``." } ], "reviews": [ { "id": 3545336611, "user": "user_3a67c55598c5", "state": "COMMENTED", "body": null, "submitted_at": "2025-12-05T15:49:07+00:00" }, { "id": 3545736336, "user": "user_46e0bc726f3c", "state": "APPROVED", "body": "(Embarrassed I missed this in the original PR. Hoping the correction is eligible for backport to 6.0 docs.)\n\nI'm ambivalent on how much additional commentary to include in the example, but added some suggestions. (Long-term, I'm hoping to split the lengthy email docs between guide and reference. This example—with expanded commentary—would be better in a reference section.)", "submitted_at": "2025-12-05T17:54:48+00:00" }, { "id": 3552432610, "user": "user_3a67c55598c5", "state": "APPROVED", "body": null, "submitted_at": "2025-12-08T14:43:36+00:00" } ], "review_comments": [ { "id": 2593142163, "user": "user_3a67c55598c5", "body": "Should we add a comment explaining why the slice is here?", "path": "docs/topics/email.txt", "line": 493, "side": "RIGHT", "created_at": "2025-12-05T15:49:04+00:00" }, { "id": 2593455762, "user": "user_46e0bc726f3c", "body": "```suggestion\n subtype=\"png\", # or \"gif\" or \"jpeg\"\n```", "path": "docs/topics/email.txt", "line": null, "side": "RIGHT", "created_at": "2025-12-05T17:41:31+00:00" }, { "id": 2593463424, "user": "user_46e0bc726f3c", "body": "```suggestion\n # In the html, refer to the cid (without angle brackets).\n message.attach_alternative(f'… …', \"text/html\")\n```", "path": "docs/topics/email.txt", "line": 493, "side": "RIGHT", "created_at": "2025-12-05T17:44:39+00:00" }, { "id": 2593481437, "user": "user_46e0bc726f3c", "body": "```suggestion\n # Create a random Content-ID (including angle brackets <…>).\n cid = email.utils.make_msgid()\n```", "path": "docs/topics/email.txt", "line": 482, "side": "RIGHT", "created_at": "2025-12-05T17:51:53+00:00" } ], "meta": { "languages": [ "txt" ], "touches_tests": false, "review_state_summary": { "COMMENTED": 1, "APPROVED": 2 }, "meaningful_comment_count": 4, "has_approval": true, "has_changes_requested": false, "total_review_comments": 4 } } { "_id": "2a089a38a359184c", "_schema_version": "1.0", "_cleaned_at": "2026-02-12T07:46:51.609057+00:00", "repo": "django/django", "repo_url": "https://github.com/django/django", "license_name": "BSD 3-Clause \"New\" or \"Revised\" License", "license_spdx": "BSD-3-Clause", "pr_number": 20364, "title": "Improved docs/releases/6.0.txt.", "body": "#### Trac ticket number\n\nn/a\n\n#### Branch description\n\nSome possible improvements that I spotted:\n\n1. Note that CSP generates a unique nonce per request.\n2. Mention django-tasks as a reference implementation for task backends.\n3. Move some sections from the \"Miscellaneous\" section to their relevant app sections.\n4. Link to more mentioned classes and settings.\n5. Make some wording clearer and more consistent.\n\n#### Checklist\n- [x] This PR targets the `main` branch. \n- [x] The commit message is written in past tense, mentions the ticket number, and ends with a period.\n- [x] I have checked the \"Has patch\" ticket flag in the Trac system.\n- [x] I have added or updated relevant tests.\n- [x] I have added or updated relevant docs, including release notes if applicable.\n- [x] I have attached screenshots in both light and dark modes for any UI changes.", "author": "user_8fc305198eb3", "created_at": "2025-12-03T11:24:10+00:00", "merged_at": "2025-12-03T15:46:25+00:00", "base_branch": "main", "head_branch": "django_6.0_release_notes", "additions": 26, "deletions": 30, "changed_files": 1, "files": [ { "filename": "docs/releases/6.0.txt", "status": "modified", "additions": 26, "deletions": 30, "changes": 56, "patch": "@@ -1,14 +1,14 @@\n-============================================\n-Django 6.0 release notes - UNDER DEVELOPMENT\n-============================================\n+========================\n+Django 6.0 release notes\n+========================\n \n-*[NAME_REDACTED] 2025*\n+*December 3, 2025*\n \n Welcome to Django 6.0!\n \n These release notes cover the :ref:`new features `, as well as\n-some :ref:`backwards incompatible changes ` you'll\n-want to be aware of when upgrading from Django 5.2 or earlier. We've\n+some :ref:`backwards incompatible changes ` you\n+should be aware of when upgrading from Django 5.2 or earlier. We've\n :ref:`begun the deprecation process for some features\n `.\n \n@@ -160,6 +160,12 @@ Minor features\n * The new :attr:`.AdminSite.password_change_form` attribute allows customizing\n the form used in the admin site password change view.\n \n+* Message levels ``messages.DEBUG`` and ``messages.INFO`` now have distinct\n+ icons and CSS styling. Previously, both levels shared the same appearance as\n+ ``messages.SUCCESS``. Given that :meth:`.ModelAdmin.message_user` uses\n+ ``messages.INFO`` by default, set the level to ``messages.SUCCESS`` to keep\n+ the previous icon and styling.\n+\n :mod:`django.contrib.auth`\n ~~~~~~~~~~~~~~~~~~~~~~~~~~\n \n@@ -189,6 +195,11 @@ Minor features\n :class:`GeometryType() `\n database function allow filtering geometries by [NAME_REDACTED]\n \n+* Widgets from :mod:`django.contrib.gis.forms.widgets` now render without\n+ inline JavaScript in templates. If you have customized any geometry widgets\n+ or their templates, you may need to :ref:`update them\n+ ` to match the new layout.\n+\n :mod:`django.contrib.postgres`\n ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n \n@@ -217,6 +228,10 @@ Minor features\n ensures consistent path ordering in manifest files, making them more\n reproducible and reducing unnecessary diffs.\n \n+* The :djadmin:`collectstatic` command now reports only a summary for skipped\n+ files (and for deleted files when using ``--clear``) at ``--verbosity`` 1. To\n+ see per-file details for either case, set ``--verbosity`` to 2 or higher.\n+\n Email\n ~~~~~\n \n@@ -462,29 +477,9 @@ Miscellaneous\n refactored to use Python's :class:`email.message.Message` for parsing.\n Input headers exceeding 10000 characters will now raise :exc:`ValueError`.\n \n-* Widgets from :mod:`django.contrib.gis.forms.widgets` now render without\n- inline JavaScript in templates. If you have customized any geometry widgets\n- or their templates, you may need to :ref:`update them\n- ` to match the new layout.\n-\n-* Message levels ``messages.DEBUG`` and ``messages.INFO`` now have distinct\n- icons and CSS styling in the admin. Previously, these used the same icon and\n- styling as the ``messages.SUCCESS`` level. Since\n- :meth:`.ModelAdmin.message_user` uses the ``messages.INFO`` level by default,\n- set the level to ``messages.SUCCESS`` to retain the previous icon and\n- styling.\n-\n * The minimum supported version of ``asgiref`` is increased from 3.8.1 to\n 3.9.1.\n \n-* The :djadmin:`collectstatic` command now reports only a summary of skipped\n- files due to conflicts when ``--verbosity`` is 1. To see warnings for each\n- conflicting destination path, set the ``--verbosity`` flag to 2 or higher.\n-\n-* The :option:`collectstatic --clear` command now reports only a summary of\n- deleted files when ``--verbosity`` is 1. To see the details for each file\n- deleted, set the ``--verbosity`` flag to 2 or higher.\n-\n .. _deprecated-features-6.0:\n \n Features deprecated in 6.0\n@@ -516,14 +511,15 @@ Miscellaneous\n available :class:`~django.db.models.StringAgg` class.\n \n * The PostgreSQL ``OrderableAggMixin`` is deprecated in favor of the\n- ``order_by`` attribute now available on the ``Aggregate`` class.\n+ ``order_by`` attribute now available on the\n+ :class:`~django.db.models.Aggregate` class.\n \n * The default protocol in :tfilter:`urlize` and :tfilter:`urlizetrunc` will\n change from HTTP to HTTPS in Django 7.0. Set the transitional setting\n- ``URLIZE_ASSUME_HTTPS`` to ``True`` to opt into assuming HTTPS during the\n- Django 6.x release cycle.\n+ :setting:`URLIZE_ASSUME_HTTPS` to ``True`` to opt into assuming HTTPS during\n+ the Django 6.x release cycle.\n \n-* ``URLIZE_ASSUME_HTTPS`` transitional setting is deprecated.\n+* The :setting:`URLIZE_ASSUME_HTTPS` transitional setting is deprecated.\n \n * Setting :setting:`ADMINS` or :setting:`MANAGERS` to a list of (name, address)\n tuples is deprecated. Set to a list of email address strings instead. Django" } ], "reviews": [ { "id": 3535579361, "user": "user_00dac951cdbf", "state": "APPROVED", "body": "Thank you Adam! will push some changes and land 🌟", "submitted_at": "2025-12-03T15:43:47+00:00" }, { "id": 3536812806, "user": "user_8fc305198eb3", "state": "COMMENTED", "body": null, "submitted_at": "2025-12-03T20:30:25+00:00" }, { "id": 3536813237, "user": "user_8fc305198eb3", "state": "COMMENTED", "body": null, "submitted_at": "2025-12-03T20:30:33+00:00" } ], "review_comments": [ { "id": 2585542894, "user": "user_00dac951cdbf", "body": "Thank you Adam for reviewing these notes!!!\n\nSadly, I don't think this is a good fit for the release notes. This clarification is more appropriate for the reference docs, where it is already documented.\n\n(I'll push its removal since I'm about to do the 6.0 final release.)", "path": "docs/releases/6.0.txt", "line": null, "side": "RIGHT", "created_at": "2025-12-03T15:20:16+00:00" }, { "id": 2585545713, "user": "user_00dac951cdbf", "body": "This is being worked on in PR #20359.", "path": "docs/releases/6.0.txt", "line": null, "side": "RIGHT", "created_at": "2025-12-03T15:21:00+00:00" }, { "id": 2586520251, "user": "user_8fc305198eb3", "body": "Fair enoughi", "path": "docs/releases/6.0.txt", "line": null, "side": "RIGHT", "created_at": "2025-12-03T20:30:25+00:00" }, { "id": 2586520559, "user": "user_8fc305198eb3", "body": "Alrighty!", "path": "docs/releases/6.0.txt", "line": null, "side": "RIGHT", "created_at": "2025-12-03T20:30:33+00:00" } ], "meta": { "languages": [ "txt" ], "touches_tests": false, "review_state_summary": { "APPROVED": 1, "COMMENTED": 2 }, "meaningful_comment_count": 3, "has_approval": true, "has_changes_requested": false, "total_review_comments": 4 } } { "_id": "b70dfd3ea9013f78", "_schema_version": "1.0", "_cleaned_at": "2026-02-12T07:46:51.609057+00:00", "repo": "django/django", "repo_url": "https://github.com/django/django", "license_name": "BSD 3-Clause \"New\" or \"Revised\" License", "license_spdx": "BSD-3-Clause", "pr_number": 20362, "title": "Fixed #36765 -- Added support for stored GeneratedFields on Oracle 23ai/26ai (23.7+).", "body": "ticket-36765", "author": "user_5501cd6d3dc8", "created_at": "2025-12-02T16:35:44+00:00", "merged_at": "2025-12-13T15:38:04+00:00", "base_branch": "main", "head_branch": "oracle-materialized-generated-columns", "additions": 61, "deletions": 14, "changed_files": 10, "files": [ { "filename": "django/db/backends/base/features.py", "status": "modified", "additions": 2, "deletions": 0, "changes": 2, "patch": "@@ -373,6 +373,8 @@ class BaseDatabaseFeatures:\n supports_stored_generated_columns = False\n # Does the backend support virtual generated columns?\n supports_virtual_generated_columns = False\n+ # Does the backend support altering data types of generated columns?\n+ supports_alter_generated_column_data_type = True\n \n # Does the backend support the logical XOR operator?\n supports_logical_xor = False" }, { "filename": "django/db/backends/base/schema.py", "status": "modified", "additions": 14, "deletions": 1, "changes": 15, "patch": "@@ -452,10 +452,14 @@ def db_default_sql(self, field):\n params = []\n return sql % default_sql, params\n \n+ def _column_generated_persistency_sql(self, field):\n+ \"\"\"Return the SQL to define the persistency of generated fields.\"\"\"\n+ return \"STORED\" if field.db_persist else \"VIRTUAL\"\n+\n def _column_generated_sql(self, field):\n \"\"\"Return the SQL to use in a GENERATED ALWAYS clause.\"\"\"\n expression_sql, params = field.generated_sql(self.connection)\n- persistency_sql = \"STORED\" if field.db_persist else \"VIRTUAL\"\n+ persistency_sql = self._column_generated_persistency_sql(field)\n if self.connection.features.requires_literal_defaults:\n expression_sql = expression_sql % tuple(self.quote_value(p) for p in params)\n params = ()\n@@ -906,6 +910,15 @@ def alter_field(self, model, old_field, new_field, strict=False):\n else:\n new_field_sql = new_field.generated_sql(self.connection)\n modifying_generated_field = old_field_sql != new_field_sql\n+ db_features = self.connection.features\n+ # Some databases (e.g. Oracle) don't allow altering a data type\n+ # for generated columns.\n+ if (\n+ not modifying_generated_field\n+ and old_type != new_type\n+ and not db_features.supports_alter_generated_column_data_type\n+ ):\n+ modifying_generated_field = True\n if modifying_generated_field:\n raise ValueError(\n f\"[NAME_REDACTED] is not supported - the field {new_field} \"" }, { "filename": "django/db/backends/oracle/features.py", "status": "modified", "additions": 10, "deletions": 1, "changes": 11, "patch": "@@ -69,8 +69,8 @@ class DatabaseFeatures(BaseDatabaseFeatures):\n supports_ignore_conflicts = False\n max_query_params = 2**16 - 1\n supports_partial_indexes = False\n- supports_stored_generated_columns = False\n supports_virtual_generated_columns = True\n+ supports_alter_generated_column_data_type = False\n can_rename_index = True\n supports_slicing_ordering_in_compound = True\n requires_compound_order_by_subquery = True\n@@ -131,6 +131,11 @@ def django_test_skips(self):\n \"Oracle doesn't support casting filters to NUMBER.\": {\n \"lookup.tests.LookupQueryingTests.test_aggregate_combined_lookup\",\n },\n+ \"Oracle doesn't support some data types (e.g. BOOLEAN, BLOB) in \"\n+ \"GeneratedField expressions (ORA-54003).\": {\n+ \"schema.tests.SchemaTests.test_add_generated_field_contains\",\n+ \"schema.tests.SchemaTests.test_add_generated_field_with_kt_model\",\n+ },\n }\n if self.connection.oracle_version < (23,):\n skips.update(\n@@ -228,3 +233,7 @@ def supports_tuple_lookups(self):\n [USER_REDACTED]_property\n def supports_uuid4_function(self):\n return self.connection.oracle_version >= (23, 9)\n+\n+ [USER_REDACTED]_property\n+ def supports_stored_generated_columns(self):\n+ return self.connection.oracle_version >= (23, 7)" }, { "filename": "django/db/backends/oracle/schema.py", "status": "modified", "additions": 3, "deletions": 0, "changes": 3, "patch": "@@ -251,3 +251,6 @@ def _collate_sql(self, collation, old_collation=None, table_name=None):\n if collation is None and old_collation is not None:\n collation = self._get_default_collation(table_name)\n return super()._collate_sql(collation, old_collation, table_name)\n+\n+ def _column_generated_persistency_sql(self, field):\n+ return \"MATERIALIZED\" if field.db_persist else \"VIRTUAL\"" }, { "filename": "docs/ref/models/fields.txt", "status": "modified", "additions": 7, "deletions": 2, "changes": 9, "patch": "@@ -1346,8 +1346,13 @@ materialized view.\n real column. If ``False``, the column acts as a virtual column and does\n not occupy database storage space.\n \n- PostgreSQL < 18 only supports persisted columns. Oracle only supports\n- virtual columns.\n+ PostgreSQL < 18 only supports persisted columns. Oracle < 23ai/26ai (23.7)\n+ only supports virtual columns.\n+\n+ .. versionchanged:: 6.1\n+\n+ Support for stored ``GeneratedField``\\s was added on Oracle 23ai/26ai\n+ (23.7+).\n \n .. admonition:: Database limitations" }, { "filename": "docs/releases/6.1.txt", "status": "modified", "additions": 4, "deletions": 0, "changes": 4, "patch": "@@ -266,6 +266,10 @@ Models\n * The new :class:`~django.db.models.functions.UUID4` and\n :class:`~django.db.models.functions.UUID7` database functions were added.\n \n+* :class:`~django.db.models.GeneratedField` now supports stored columns\n+ (:attr:`~django.db.models.GeneratedField.db_persist` set to ``True``) on\n+ Oracle 23ai/26ai (23.7+).\n+\n Pagination\n ~~~~~~~~~~" }, { "filename": "tests/migrations/test_operations.py", "status": "modified", "additions": 15, "deletions": 4, "changes": 19, "patch": "@@ -1491,7 +1491,7 @@ def test_add_generated_field(self):\n \"name_and_id\",\n models.GeneratedField(\n expression=Concat((\"name\"), (\"rider_id\")),\n- output_field=models.TextField(),\n+ output_field=models.CharField(max_length=60),\n db_persist=True,\n ),\n ),\n@@ -6363,6 +6363,15 @@ def _test_invalid_generated_field_changes(self, db_persist):\n (\"test_igfc_2\", generated_1, regular),\n (\"test_igfc_3\", generated_1, generated_2),\n ]\n+ if not connection.features.supports_alter_generated_column_data_type:\n+ generated_3 = models.GeneratedField(\n+ expression=F(\"pink\") + F(\"pink\"),\n+ output_field=models.DecimalField(decimal_places=2, max_digits=16),\n+ db_persist=db_persist,\n+ )\n+ tests.append(\n+ (\"test_igfc_4\", generated_1, generated_3),\n+ )\n for app_label, add_field, alter_field in tests:\n project_state = self.set_up_test_model(app_label)\n operations = [\n@@ -6441,7 +6450,7 @@ def test_invalid_generated_field_persistency_change(self):\n \"Pony\",\n \"modified_pink\",\n models.GeneratedField(\n- expression=F(\"pink\"),\n+ expression=F(\"pink\") + 2,\n output_field=models.IntegerField(),\n db_persist=True,\n ),\n@@ -6450,7 +6459,7 @@ def test_invalid_generated_field_persistency_change(self):\n \"Pony\",\n \"modified_pink\",\n models.GeneratedField(\n- expression=F(\"pink\"),\n+ expression=F(\"pink\") + 2,\n output_field=models.IntegerField(),\n db_persist=False,\n ),\n@@ -6489,7 +6498,9 @@ def _test_add_generated_field(self, db_persist):\n operation.database_backwards(app_label, editor, new_state, project_state)\n self.assertColumnNotExists(f\"{app_label}_pony\", \"modified_pink\")\n \n- [USER_REDACTED](\"supports_stored_generated_columns\")\n+ [USER_REDACTED](\n+ \"supports_stored_generated_columns\", \"supports_alter_generated_column_data_type\"\n+ )\n def test_generated_field_changes_output_field(self):\n app_label = \"test_gfcof\"\n operation = migrations.AddField(" }, { "filename": "tests/model_fields/models.py", "status": "modified", "additions": 3, "deletions": 3, "changes": 6, "patch": "@@ -9,7 +9,7 @@\n from django.db import connection, models\n from django.db.models import F, Value\n from django.db.models.fields.files import ImageFieldFile\n-from django.db.models.functions import Lower\n+from django.db.models.functions import Cast, Lower\n from django.utils.functional import SimpleLazyObject\n from django.utils.translation import gettext_lazy as _\n \n@@ -534,7 +534,7 @@ class UUIDGrandchild(UUIDChild):\n class GeneratedModelFieldWithConverters(models.Model):\n field = models.UUIDField()\n field_copy = models.GeneratedField(\n- expression=F(\"field\"),\n+ expression=Cast(\"field\", models.UUIDField()),\n output_field=models.UUIDField(),\n db_persist=True,\n )\n@@ -561,7 +561,7 @@ class GeneratedModelNonAutoPk(models.Model):\n id = models.IntegerField(primary_key=True)\n a = models.IntegerField()\n b = models.GeneratedField(\n- expression=F(\"a\"),\n+ expression=F(\"a\") + 1,\n output_field=models.IntegerField(),\n db_persist=True,\n )" }, { "filename": "tests/model_fields/test_generatedfield.py", "status": "modified", "additions": 1, "deletions": 1, "changes": 2, "patch": "@@ -413,7 +413,7 @@ def test_create_with_non_auto_pk(self):\n obj = GeneratedModelNonAutoPk.objects.create(id=1, a=2)\n self.assertEqual(obj.id, 1)\n self.assertEqual(obj.a, 2)\n- self.assertEqual(obj.b, 2)\n+ self.assertEqual(obj.b, 3)\n \n \n [USER_REDACTED](\"supports_virtual_generated_columns\")" }, { "filename": "tests/schema/tests.py", "status": "modified", "additions": 2, "deletions": 2, "changes": 4, "patch": "@@ -1029,7 +1029,7 @@ def test_alter_generated_field(self):\n class GeneratedFieldIndexedModel(Model):\n number = IntegerField(default=1)\n generated = GeneratedField(\n- expression=F(\"number\"),\n+ expression=F(\"number\") + 1,\n db_persist=True,\n output_field=IntegerField(),\n )\n@@ -1042,7 +1042,7 @@ class Meta:\n \n old_field = GeneratedFieldIndexedModel._meta.get_field(\"generated\")\n new_field = GeneratedField(\n- expression=F(\"number\"),\n+ expression=F(\"number\") + 1,\n db_persist=True,\n db_index=True,\n output_field=IntegerField()," } ], "reviews": [ { "id": 3573417778, "user": "user_3a67c55598c5", "state": "COMMENTED", "body": "Nice one. Just one question about comparing types.", "submitted_at": "2025-12-12T20:43:18+00:00" }, { "id": 3573641305, "user": "user_5501cd6d3dc8", "state": "COMMENTED", "body": null, "submitted_at": "2025-12-12T21:23:05+00:00" }, { "id": 3573831894, "user": "user_3a67c55598c5", "state": "COMMENTED", "body": null, "submitted_at": "2025-12-12T22:44:25+00:00" }, { "id": 3573854096, "user": "user_3a67c55598c5", "state": "APPROVED", "body": "🎉", "submitted_at": "2025-12-12T22:57:04+00:00" }, { "id": 3574277560, "user": "user_5501cd6d3dc8", "state": "COMMENTED", "body": null, "submitted_at": "2025-12-13T08:51:26+00:00" } ], "review_comments": [ { "id": 2615429911, "user": "user_3a67c55598c5", "body": "data type -> data types", "path": "django/db/backends/base/features.py", "line": null, "side": "RIGHT", "created_at": "2025-12-12T20:04:51+00:00" }, { "id": 2615501017, "user": "user_3a67c55598c5", "body": "I think we have to check for collation here also. Any other suffixes to check?", "path": "django/db/backends/base/schema.py", "line": 918, "side": "RIGHT", "created_at": "2025-12-12T20:32:08+00:00" }, { "id": 2615614395, "user": "user_5501cd6d3dc8", "body": "Actually, changing only `db_collation` works fine (I've checked on `VIRTUAL` generated field).", "path": "django/db/backends/base/schema.py", "line": 918, "side": "RIGHT", "created_at": "2025-12-12T21:23:05+00:00" }, { "id": 2615770931, "user": "user_3a67c55598c5", "body": "Oh good to know. Tried to test, but it wanted me to set `MAX_STRING_SIZE=EXTENDED` and that turned out to be impossibly complicated.", "path": "django/db/backends/base/schema.py", "line": 918, "side": "RIGHT", "created_at": "2025-12-12T22:44:25+00:00" }, { "id": 2616181976, "user": "user_5501cd6d3dc8", "body": "Yes it is complicated :disappointed: \n\nTBH, I don't see us adding more and more conditions here. I would treat this check as \"the best effort\", there are too many database-specific caveats around altering `GeneratedField`. IMO, `DatabaseError` is fine here when someone hits the edge.", "path": "django/db/backends/base/schema.py", "line": 918, "side": "RIGHT", "created_at": "2025-12-13T08:51:26+00:00" } ], "meta": { "languages": [ "py", "txt" ], "touches_tests": true, "review_state_summary": { "COMMENTED": 4, "APPROVED": 1 }, "meaningful_comment_count": 5, "has_approval": true, "has_changes_requested": false, "total_review_comments": 5 } } { "_id": "92b105364b212185", "_schema_version": "1.0", "_cleaned_at": "2026-02-12T07:46:51.609057+00:00", "repo": "django/django", "repo_url": "https://github.com/django/django", "license_name": "BSD 3-Clause \"New\" or \"Revised\" License", "license_spdx": "BSD-3-Clause", "pr_number": 20359, "title": "Refs #35859 -- Clarified the need for installing a production task backend separately.", "body": "ticket-35859\n\nSee forum:\nhttps://forum.djangoproject.com/t/6-0-documentation-confusion-for-django-tasks/43583", "author": "user_3a67c55598c5", "created_at": "2025-12-02T15:29:44+00:00", "merged_at": "2025-12-03T16:08:30+00:00", "base_branch": "main", "head_branch": "jtw/tasks-doc-tweak", "additions": 34, "deletions": 11, "changed_files": 3, "files": [ { "filename": "docs/ref/tasks.txt", "status": "modified", "additions": 12, "deletions": 0, "changes": 12, "patch": "@@ -7,6 +7,10 @@ Tasks\n .. module:: django.tasks\n :synopsis: Django's built-in background Task system.\n \n+The Task framework provides the contract and plumbing for background work, not\n+the engine that runs it. The Tasks API defines how work is described, queued,\n+and tracked, but leaves actual execution to external infrastructure.\n+\n Task definition\n ===============\n \n@@ -274,6 +278,10 @@ Task errors\n Backends\n ========\n \n+Backends handle how Tasks are stored and executed. All backends share a common\n+interface defined by ``BaseTaskBackend``, which specifies the core methods for\n+enqueueing Tasks and retrieving results.\n+\n Base backend\n ------------\n \n@@ -365,6 +373,10 @@ Feature :class:`.DummyBackend` :class:`.ImmediateBackend`\n Available backends\n ------------------\n \n+Django includes only development and testing backends. These support local\n+execution and inspection, for production ready backends refer to\n+:ref:`configuring-a-task-backend`.\n+\n Immediate backend\n ~~~~~~~~~~~~~~~~~" }, { "filename": "docs/releases/6.0.txt", "status": "modified", "additions": 5, "deletions": 0, "changes": 5, "patch": "@@ -102,6 +102,11 @@ Django now includes a built-in Tasks framework for running code outside the\n HTTP request–response cycle. This enables offloading work, such as sending\n emails or processing data, to background workers.\n \n+The framework provides task definition, validation, queuing, and result\n+handling. Django guarantees consistent behavior for creating and managing\n+tasks, while the responsibility for running them continues to belong to\n+external worker processes.\n+\n Tasks are defined using the :func:`~django.tasks.task` decorator::\n \n from django.core.mail import send_mail" }, { "filename": "docs/topics/tasks.txt", "status": "modified", "additions": 17, "deletions": 11, "changes": 28, "patch": "@@ -15,10 +15,11 @@ to be run elsewhere, potentially at a later date. This keeps requests fast,\n reduces latency, and improves the user experience. For example, a user\n shouldn't have to wait for an email to send before their page finishes loading.\n \n-Django's new Tasks framework makes it easy to define and enqueue such work. It\n+[NAME_REDACTED] framework makes it easy to define and enqueue such work. It\n does not provide a worker mechanism to run Tasks. The actual execution must be\n handled by [NAME_REDACTED], such as a separate process or\n-service.\n+service. Given that, a :ref:`task backend ` capable\n+of executing tasks on that service should be evaluated and configured.\n \n [NAME_REDACTED] fundamentals\n ============================\n@@ -41,9 +42,13 @@ Configuring a Task backend\n The Task backend determines how and where Tasks are stored for execution and\n how they are executed. [NAME_REDACTED] backends have different characteristics\n and configuration options, which may impact the performance and reliability of\n-your application. Django comes with a number of :ref:`built-in backends\n-`. Django does not provide a generic way to execute\n-Tasks, only enqueue them.\n+your application. Django comes with :ref:`built-in backends\n+`, but these are for development and testing only.\n+\n+Django handles task definition, validation, queuing, and result handling, not\n+execution, so production setups need a backend or worker process that actually\n+runs queued work. Relevant options are listed in the `[NAME_REDACTED]\n+`__ page.\n \n Task backends are configured using the :setting:`TASKS` setting in your\n settings file. Whilst most applications will only need a single backend,\n@@ -103,13 +108,14 @@ Stored results can be cleared using the\n >>> len(default_task_backend.results)\n 0\n \n-Using a custom backend\n-----------------------\n+Third-party backends\n+--------------------\n \n-[NAME_REDACTED] includes support for a number of Task backends out-of-the-box,\n-sometimes you might want to customize the Task backend. To use an external Task\n-backend with Django, use the Python import path as the :setting:`BACKEND\n-` of the :setting:`TASKS` setting, like so::\n+As mentioned at the beginning of this section, Django includes backends\n+suitable for development and testing only. Production systems should rely on\n+backends that supply a worker process and durable queue implementation. To use\n+an external Task backend with Django, use the Python import path as the\n+:setting:`BACKEND ` of the :setting:`TASKS` setting, like so::\n \n TASKS = {\n \"default\": {" } ], "reviews": [ { "id": 3530866098, "user": "user_34c3f4acb8a8", "state": "APPROVED", "body": "Looks good to me!\n\nAre we ok with just saying \"3rd-party packages\", and leaving it to the user to go and find them? \n\nPerhaps worth mentioning `django-tasks` in the context of a backport? Although that may be a different PR.", "submitted_at": "2025-12-02T15:49:46+00:00" }, { "id": 3531546177, "user": "user_a2cd65b227cf", "state": "COMMENTED", "body": null, "submitted_at": "2025-12-02T18:19:25+00:00" }, { "id": 3531675230, "user": "user_00dac951cdbf", "state": "COMMENTED", "body": null, "submitted_at": "2025-12-03T13:05:30+00:00" }, { "id": 3535277592, "user": "user_6b79e26637e6", "state": "COMMENTED", "body": null, "submitted_at": "2025-12-03T14:15:23+00:00" }, { "id": 3535323642, "user": "user_00dac951cdbf", "state": "COMMENTED", "body": null, "submitted_at": "2025-12-03T14:25:26+00:00" }, { "id": 3535341361, "user": "user_34c3f4acb8a8", "state": "COMMENTED", "body": null, "submitted_at": "2025-12-03T14:29:21+00:00" }, { "id": 3535512975, "user": "user_a2cd65b227cf", "state": "COMMENTED", "body": null, "submitted_at": "2025-12-03T15:05:51+00:00" }, { "id": 3535513673, "user": "user_00dac951cdbf", "state": "COMMENTED", "body": null, "submitted_at": "2025-12-03T15:06:00+00:00" }, { "id": 3535559583, "user": "user_3a67c55598c5", "state": "COMMENTED", "body": "Looks good. (I might remove the last sentence of the new heading section, but it's okay as is.)", "submitted_at": "2025-12-03T15:15:52+00:00" }, { "id": 3535564823, "user": "user_a2cd65b227cf", "state": "COMMENTED", "body": null, "submitted_at": "2025-12-03T15:16:56+00:00" }, { "id": 3535572566, "user": "user_6b79e26637e6", "state": "COMMENTED", "body": null, "submitted_at": "2025-12-03T15:18:39+00:00" }, { "id": 3535646130, "user": "user_057de2f3b132", "state": "COMMENTED", "body": null, "submitted_at": "2025-12-03T15:34:52+00:00" }, { "id": 3535735401, "user": "user_00dac951cdbf", "state": "APPROVED", "body": "🏅 🏆 🌟", "submitted_at": "2025-12-03T15:50:59+00:00" } ], "review_comments": [ { "id": 2582331943, "user": "user_a2cd65b227cf", "body": "In my head (without me referring to the docs style guide mind you so if this breaks that then I'm fine with it), I was thinking a short info or warning call out box here stating that you will need a third-party package to execute tasks in the background.", "path": "docs/topics/tasks.txt", "line": null, "side": "RIGHT", "created_at": "2025-12-02T18:19:25+00:00" }, { "id": 2582437403, "user": "user_00dac951cdbf", "body": "I'll push some reworking on this since the ecosystem page, as how it is now, it's not listing the major tasks bakends. I have reached out to Tim S about this, so it'll likely get fixed soon.\n\nIn any case, I rather to link to the ecosystem page in a single place and I think the topics page is the best location. Will propose something asap!", "path": "docs/releases/6.0.txt", "line": null, "side": "RIGHT", "created_at": "2025-12-02T18:49:33+00:00" }, { "id": 2585038824, "user": "user_00dac951cdbf", "body": "I'll try to give this a go.", "path": "docs/topics/tasks.txt", "line": null, "side": "RIGHT", "created_at": "2025-12-03T13:05:25+00:00" }, { "id": 2585296808, "user": "user_6b79e26637e6", "body": "I believe we should link directly to the `django-tasks` documentation about backends here in this context rather than the ecosystem page. The reason being is that the ecosystem page is more likely to list out all background task processing libraries, including ones that don't implement the `django-tasks` API, such as Celery. It would be confusing for someone who is looking for the production ready backends to be used with the tasks part of Django to be linked to a page that lists options they can't use.\n\nAdditionally, I expect `django-tasks` to be more up to date with the \"production ready\" backends than the ecosystem page, no? cc: [USER_REDACTED]/steering-council", "path": "docs/releases/6.0.txt", "line": null, "side": "RIGHT", "created_at": "2025-12-03T14:15:22+00:00" }, { "id": 2585333520, "user": "user_00dac951cdbf", "body": "I do not think we should link directly to django-tasks here. The Tasks framework *in Django* is intentionally limited to the stable core contract for defining and queuing work. Backend specifics, including which packages implement the API, are outside that contract and change much faster than the Django docs.\n\nThe ecosystem page is the right place to endorse, list, and curate third party backends (even if that means a single entry \"check django-tasks for the up to date list of production ready backends that implement the [NAME_REDACTED] API\"), and it can clearly separate API compatible packages from general background processing tools. That keeps the Django docs focused on the framework itself while letting backend guidance evolve independently.", "path": "docs/releases/6.0.txt", "line": null, "side": "RIGHT", "created_at": "2025-12-03T14:25:25+00:00" }, { "id": 2585348320, "user": "user_34c3f4acb8a8", "body": "> I expect `django-tasks` to be more up to date with the \"production ready\" backends than the ecosystem page\n\nAs time goes on, there'll be more features in `django-tasks` than in `django`. Those features will still be usable in production, but may not come with the same rigorous testing that including in Django assumes.\n\nI also expect more backends to exist outside of `django-tasks`, and have little intention of listing them in the README.", "path": "docs/releases/6.0.txt", "line": null, "side": "RIGHT", "created_at": "2025-12-03T14:29:21+00:00" }, { "id": 2585488731, "user": "user_a2cd65b227cf", "body": "My 2 cents here:\n\n* We need to be clear that django-tasks is the first production ready background task worker & backend (it's not in Django yet)\n* At some point be clear about if there are things in django-tasks that won't likely appear in Django, essentially at what points does it start to diverge from the reference implementation of the DEP?\n* I would expect any callout to django-tasks specifically to be time-limited to the 6.X release cycle.\n\nAll that stems from wanting to reduce the amount of questions that have and will continue to pop up on the forum and Discord.", "path": "docs/releases/6.0.txt", "line": null, "side": "RIGHT", "created_at": "2025-12-03T15:05:51+00:00" }, { "id": 2585489439, "user": "user_00dac951cdbf", "body": "[USER_REDACTED] [USER_REDACTED] I tried to give this a go but I reverted the box usage since the docs say all over the place (ref/tasks, topics/tasks, release notes) what tasks are and are not. At some point, we truly need users to read what's written :sob:", "path": "docs/topics/tasks.txt", "line": null, "side": "RIGHT", "created_at": "2025-12-03T15:06:00+00:00" }, { "id": 2585530619, "user": "user_a2cd65b227cf", "body": "The additions here are good. Let's not hold up 6.0 any longer!", "path": "docs/topics/tasks.txt", "line": null, "side": "RIGHT", "created_at": "2025-12-03T15:16:56+00:00" }, { "id": 2585536763, "user": "user_6b79e26637e6", "body": "> I do not think we should link directly to django-tasks here. The Tasks framework in Django is intentionally limited to the stable core contract for defining and queuing work. Backend specifics, including which packages implement the API, are outside that contract and change much faster than the Django docs.\n\n[USER_REDACTED] I don't understand this part of your statement. We're in agreement here on what the Tasks framework is in Django. We want to link to some other place because the Django docs aren't updated frequently in comparison. I get lost about how this is a reason to not link to django-tasks though.\n\n> ... it can clearly separate API compatible packages from general background processing tools. That keeps the Django docs focused on the framework itself while letting backend guidance evolve independently.\n\n[USER_REDACTED] Same thing here. This isn't a justification to not link directly to django-tasks. From my understanding, it's a justification that we need to link to somewhere.\n\n> As time goes on, there'll be more features in django-tasks than in django. Those features will still be usable in production, but may not come with the same rigorous testing that including in Django assumes.\n\n[USER_REDACTED] That's fine, but is a tangential discussion to what I understand. The question is, where are we collecting the various backends that implement [NAME_REDACTED] interface? (see below)\n\n> I also expect more backends to exist outside of django-tasks, and have little intention of listing them in the README.\n\n[USER_REDACTED] To align on understanding, I'm considering things for the next 2-3 years, not the permanent future. For the near future, I think we would want to be a little more interconnected to help adoption rather than leaving people to their own devices. Where would people find out about backends in the various states:\n\n- Alpha, just created and creator is looking for feedback\n- Beta, exists for up to a year, used by [NAME_REDACTED], looking for adoption\n- Stable, exists a year+, is being used by [NAME_REDACTED], the Stable condition is when something would get listed on the ecosystem page on its own. Until then, it would be in the experimental section or not at all. That's why I was suggesting linking to django-tasks because I had assumed that it would act as a hub for at least a while to help gain adoption.\n\nI suppose maybe this is where djangopackages.org comes in?", "path": "docs/releases/6.0.txt", "line": null, "side": "RIGHT", "created_at": "2025-12-03T15:18:39+00:00" }, { "id": 2585597459, "user": "user_057de2f3b132", "body": "I think we should link directly to django-tasks for the database backend until we land it in Django (or decide we're no longer actively intending to land it).\n\nFor other backends I think the ecosystem page (if they're reasonably mature) is appropriate, but I think the database backend is an important exception here:\n\n* It's the first production suitable backend to be implemented.\n* It's a reference implementation for other backends.\n* We're intending for it to land in Django.", "path": "docs/releases/6.0.txt", "line": null, "side": "RIGHT", "created_at": "2025-12-03T15:34:52+00:00" } ], "meta": { "languages": [ "txt" ], "touches_tests": false, "review_state_summary": { "APPROVED": 2, "COMMENTED": 11 }, "meaningful_comment_count": 11, "has_approval": true, "has_changes_requested": false, "total_review_comments": 11 } } { "_id": "a55518935cea7604", "_schema_version": "1.0", "_cleaned_at": "2026-02-12T07:46:51.609057+00:00", "repo": "django/django", "repo_url": "https://github.com/django/django", "license_name": "BSD 3-Clause \"New\" or \"Revised\" License", "license_spdx": "BSD-3-Clause", "pr_number": 20346, "title": "Fixed #36233 -- Avoided quantizing integers stored in DecimalField on SQLite.", "body": "#### Trac ticket number\n\n\nticket-36233\n\n#### Branch description\nFixed a crash in DecimalField when using SQLite with integers exceeding 15 digits (e.g., 16-digit IDs).\n\nThe Issue: SQLite lacks a native decimal type. When retrieving large integers (e.g., 9999999999999999), the default converter treats them as floating-point numbers. Since IEEE 754 floats only support ~15 significant digits, precision is lost (e.g., becoming 10000000000000000). When Django attempts to quantize() this inaccurate value against the field's context, it raises decimal.InvalidOperation.\n\nThe Fix: Updated django.db.backends.sqlite3.operations.py to check if the underlying SQLite driver returned a native int. If so, the value is converted directly to Decimal, bypassing the lossy float conversion entirely.\n\nVerification: Added a regression test test_sqlite_integer_precision_bypass in model_fields/test_decimalfield.py to ensure 16-digit integers are stored and retrieved correctly without crashing.\n#### Checklist\n- [ ] This PR targets the `main` branch. \n- [ ] The commit message is written in past tense, mentions the ticket number, and ends with a period.\n- [ ] I have checked the \"Has patch\" ticket flag in the Trac system.\n- [ ] I have added or updated relevant tests.\n- [ ] I have added or updated relevant docs, including release notes if applicable.\n- [ ] I have attached screenshots in both light and dark modes for any UI changes.", "author": "user_97513ac81384", "created_at": "2025-11-30T18:38:00+00:00", "merged_at": "2026-01-28T22:04:39+00:00", "base_branch": "main", "head_branch": "ticket_36233_sqlite_fix", "additions": 27, "deletions": 3, "changed_files": 3, "files": [ { "filename": "django/db/backends/sqlite3/operations.py", "status": "modified", "additions": 8, "deletions": 3, "changes": 11, "patch": "@@ -300,26 +300,31 @@ def convert_timefield_value(self, value, expression, connection):\n value = parse_time(value)\n return value\n \n+ [USER_REDACTED]\n+ def _create_decimal(value):\n+ if isinstance(value, (int, str)):\n+ return decimal.Decimal(value)\n+ return decimal.Context(prec=15).create_decimal_from_float(value)\n+\n def get_decimalfield_converter(self, expression):\n # SQLite stores only 15 significant digits. Digits coming from\n # float inaccuracy must be removed.\n- create_decimal = decimal.Context(prec=15).create_decimal_from_float\n if isinstance(expression, Col):\n quantize_value = decimal.Decimal(1).scaleb(\n -expression.output_field.decimal_places\n )\n \n def converter(value, expression, connection):\n if value is not None:\n- return create_decimal(value).quantize(\n+ return self._create_decimal(value).quantize(\n quantize_value, context=expression.output_field.context\n )\n \n else:\n \n def converter(value, expression, connection):\n if value is not None:\n- return create_decimal(value)\n+ return self._create_decimal(value)\n \n return converter" }, { "filename": "tests/model_fields/models.py", "status": "modified", "additions": 1, "deletions": 0, "changes": 1, "patch": "@@ -102,6 +102,7 @@ def get_choices():\n \n class BigD(models.Model):\n d = models.DecimalField(max_digits=32, decimal_places=30)\n+ large_int = models.DecimalField(max_digits=16, decimal_places=0, null=True)\n \n \n class FloatModel(models.Model):" }, { "filename": "tests/model_fields/test_decimalfield.py", "status": "modified", "additions": 18, "deletions": 0, "changes": 18, "patch": "@@ -5,6 +5,7 @@\n from django.core import validators\n from django.core.exceptions import ValidationError\n from django.db import connection, models\n+from django.db.models import Max\n from django.test import TestCase\n \n from .models import BigD, Foo\n@@ -140,3 +141,20 @@ def test_roundtrip_with_trailing_zeros(self):\n obj = Foo.objects.create(a=\"bar\", d=Decimal(\"8.320\"))\n obj.refresh_from_db()\n self.assertEqual(obj.d.compare_total(Decimal(\"8.320\")), Decimal(\"0\"))\n+\n+ def test_large_integer_precision(self):\n+ large_int_val = Decimal(\"9999999999999999\")\n+ obj = BigD.objects.create(large_int=large_int_val, d=Decimal(\"0\"))\n+ obj.refresh_from_db()\n+ self.assertEqual(obj.large_int, large_int_val)\n+\n+ def test_large_integer_precision_aggregation(self):\n+ large_int_val = Decimal(\"9999999999999999\")\n+ BigD.objects.create(large_int=large_int_val, d=Decimal(\"0\"))\n+ result = BigD.objects.aggregate(max_val=Max(\"large_int\"))\n+ self.assertEqual(result[\"max_val\"], large_int_val)\n+\n+ def test_roundtrip_integer_with_trailing_zeros(self):\n+ obj = Foo.objects.create(a=\"bar\", d=Decimal(\"8\"))\n+ obj.refresh_from_db()\n+ self.assertEqual(obj.d.compare_total(Decimal(\"8.000\")), Decimal(\"0\"))" } ], "reviews": [ { "id": 3678286097, "user": "user_3a67c55598c5", "state": "COMMENTED", "body": "Thanks, I have an initial comment.", "submitted_at": "2026-01-19T14:12:57+00:00" }, { "id": 3679483428, "user": "user_97513ac81384", "state": "COMMENTED", "body": null, "submitted_at": "2026-01-19T20:14:02+00:00" }, { "id": 3683035197, "user": "user_3a67c55598c5", "state": "APPROVED", "body": "Hi, good start here. A question for you about preserving trailing zeros.", "submitted_at": "2026-01-20T16:14:23+00:00" }, { "id": 3683050776, "user": "user_3a67c55598c5", "state": "CHANGES_REQUESTED", "body": "(Clicked wrong review button.)", "submitted_at": "2026-01-20T16:14:45+00:00" }, { "id": 3692203121, "user": "user_3a67c55598c5", "state": "COMMENTED", "body": "Thanks for the updates. I think I would find this more clear if you localized the updates to `create_decimal`, e.g.:\n\n```py\n[USER_REDACTED]\ndef _create_decimal(value):\n if isinstance(value, int):\n return decimal.Decimal(value)\n return decimal.Context(prec=15).create_decimal_from_float(value)\n```", "submitted_at": "2026-01-22T12:27:10+00:00" }, { "id": 3718787402, "user": "user_3a67c55598c5", "state": "APPROVED", "body": "Thanks! I pushed a tiny edit.", "submitted_at": "2026-01-28T19:43:50+00:00" }, { "id": 3733721404, "user": "user_657e90e5ae46", "state": "COMMENTED", "body": null, "submitted_at": "2026-01-31T22:12:44+00:00" }, { "id": 3763859792, "user": "user_3a67c55598c5", "state": "COMMENTED", "body": null, "submitted_at": "2026-02-06T15:57:47+00:00" } ], "review_comments": [ { "id": 2704938632, "user": "user_3a67c55598c5", "body": "I think we want this test to run on all backends.", "path": "tests/model_fields/test_decimalfield.py", "line": null, "side": "RIGHT", "created_at": "2026-01-19T14:11:57+00:00" }, { "id": 2705970001, "user": "user_97513ac81384", "body": "Thanks for the review.\n1- I removed that block so the test runs for all backends.\n2- I added Simon as co-author since I took his fix from the discussions under the ticket \n3- I also added another test for the else block", "path": "tests/model_fields/test_decimalfield.py", "line": null, "side": "RIGHT", "created_at": "2026-01-19T20:14:02+00:00" }, { "id": 2709057178, "user": "user_3a67c55598c5", "body": "I don't think it's acceptable to skip the `quantize()` call. This test passes on main and fails on your branch:\n\n```py\n def test_roundtrip_integer_with_trailing_zeros(self):\n obj = Foo.objects.create(a=\"bar\", d=Decimal(\"8\"))\n obj.refresh_from_db()\n self.assertEqual(obj.d.compare_total(Decimal(\"8.000\")), Decimal(\"0\"))\n```\n\n```py\n======================================================================\nFAIL: test_roundtrip_integer_with_trailing_zeros (model_fields.test_decimalfield.DecimalFieldTests.test_roundtrip_integer_with_trailing_zeros)\n----------------------------------------------------------------------\nTraceback (most recent call last):\n File \"/Users/jwalls/django/tests/model_fields/test_decimalfield.py\", line 148, in test_roundtrip_integer_with_trailing_zeros\n self.assertEqual(obj.d.compare_total(Decimal(\"8.000\")), Decimal(\"0\"))\n ~~~~~~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\nAssertionError: Decimal('1') != Decimal('0')\n\n----------------------------------------------------------------------\n```", "path": "django/db/backends/sqlite3/operations.py", "line": null, "side": "RIGHT", "created_at": "2026-01-20T16:11:26+00:00" }, { "id": 2709059049, "user": "user_3a67c55598c5", "body": "Please remove this model and reuse `BigD`. We can't add 1x model per test due to the overhead of creating tables.", "path": "tests/model_fields/models.py", "line": null, "side": "RIGHT", "created_at": "2026-01-20T16:11:54+00:00" }, { "id": 2709059751, "user": "user_3a67c55598c5", "body": "Please remove \"sqlite\" from the test name.", "path": "tests/model_fields/test_decimalfield.py", "line": null, "side": "RIGHT", "created_at": "2026-01-20T16:12:06+00:00" }, { "id": 2709062650, "user": "user_3a67c55598c5", "body": "We try to make surgical edits when touching longstanding code. Removing the newline and changing `elif` -> `if` will create a smaller diff.", "path": "django/db/backends/sqlite3/operations.py", "line": null, "side": "RIGHT", "created_at": "2026-01-20T16:12:48+00:00" }, { "id": 2750110696, "user": "user_657e90e5ae46", "body": "SQL databases usually have a NUMERIC type with (max_digits, and decimal_places) which takes care of adding the missing precision to `Decimal(\"8\")`. This isn't the case on MongoDB, and similar to SQLite, manual quantizing is necessary to make this test pass:\n```diff\ndiff --git a/django_mongodb_backend/operations.py b/django_mongodb_backend/operations.py\nindex e446e2c4..f4b0857f 100644\n--- a/django_mongodb_backend/operations.py\n+++ b/django_mongodb_backend/operations.py\n@@ -171,18 +171,20 @@ class DatabaseOperations(GISOperations, BaseDatabaseOperations):\n def convert_decimalfield_value(self, value, expression, connection):\n if value is not None:\n # from Decimal128 to decimal.Decimal()\n try:\n value = value.to_decimal()\n except AttributeError:\n # `value` could be an integer in the case of an annotation\n # like ExpressionWrapper(Value(1), output_field=DecimalField().\n return Decimal(value)\n+ quantize_value = Decimal(1).scaleb(-expression.output_field.decimal_places)\n+ value = value.quantize(quantize_value, context=expression.output_field.context)\n return value\n```\nI tend to think this is unnecessary overhead and this test (which bypasses validation anyway) should be skipped on MongoDB. Raising the issue here in case any patch authors have thoughts. Thanks!", "path": "tests/model_fields/test_decimalfield.py", "line": 160, "side": "RIGHT", "created_at": "2026-01-31T22:12:44+00:00" }, { "id": 2774838301, "user": "user_3a67c55598c5", "body": "I think the fact that `SQLiteNumericMixin` (and now `Value`) add casts based on the `output_field` is a [deeper design problem](https://github.com/[USER_REDACTED]ngo/django/pull/19459#discussion_r2135725928), given that `output_field` is supposed to be an ORM-only interoperability check, not entailing any database casts.\n\nWhat you've sketched looks like a better approach than SQLite's approach, tbh.", "path": "tests/model_fields/test_decimalfield.py", "line": 160, "side": "RIGHT", "created_at": "2026-02-06T15:57:47+00:00" } ], "meta": { "languages": [ "py" ], "touches_tests": true, "review_state_summary": { "COMMENTED": 5, "APPROVED": 2, "CHANGES_REQUESTED": 1 }, "meaningful_comment_count": 8, "has_approval": true, "has_changes_requested": true, "total_review_comments": 8 } } { "_id": "a1db910f3253e8da", "_schema_version": "1.0", "_cleaned_at": "2026-02-12T07:46:51.624760+00:00", "repo": "tiangolo/fastapi", "repo_url": "https://github.com/fastapi/fastapi", "license_name": "MIT License", "license_spdx": "MIT", "pr_number": 14828, "title": "✅ Test order for the submitted byte Files", "body": "Fixes the [14811](https://github.com/fastapi/fastapi/discussions/14811)", "author": "user_c36c155012b4", "created_at": "2026-02-05T04:05:37+00:00", "merged_at": "2026-02-10T11:46:48+00:00", "base_branch": "master", "head_branch": "fix-14811", "additions": 46, "deletions": 0, "changed_files": 1, "files": [ { "filename": "tests/test_list_bytes_file_order_preserved_issue_14811.py", "status": "added", "additions": 46, "deletions": 0, "changes": 46, "patch": "@@ -0,0 +1,46 @@\n+\"\"\"\n+Regression test: preserve order when using list[bytes] + File()\n+See https://github.com/fastapi/fastapi/discussions/14811\n+Related: PR #3372\n+\"\"\"\n+\n+from typing import Annotated\n+\n+import anyio\n+import pytest\n+from fastapi import FastAPI, File\n+from fastapi.testclient import TestClient\n+from starlette.datastructures import UploadFile as StarletteUploadFile\n+\n+\n+def test_list_bytes_file_preserves_order(\n+ monkeypatch: pytest.MonkeyPatch,\n+) -> None:\n+ app = FastAPI()\n+\n+ [USER_REDACTED].post(\"/upload\")\n+ async def upload(files: Annotated[list[bytes], File()]):\n+ # return something that makes order obvious\n+ return [b[0] for b in files]\n+\n+ original_read = StarletteUploadFile.read\n+\n+ async def patched_read(self: StarletteUploadFile, size: int = -1) -> bytes:\n+ # Make the FIRST file slower *deterministically*\n+ if self.filename == \"slow.txt\":\n+ await anyio.sleep(0.05)\n+ return await original_read(self, size)\n+\n+ monkeypatch.setattr(StarletteUploadFile, \"read\", patched_read)\n+\n+ client = TestClient(app)\n+\n+ files = [\n+ (\"files\", (\"slow.txt\", b\"A\" * 10, \"text/plain\")),\n+ (\"files\", (\"fast.txt\", b\"B\" * 10, \"text/plain\")),\n+ ]\n+ r = client.post(\"/upload\", files=files)\n+ assert r.status_code == 200, r.text\n+\n+ # Must preserve request order: slow first, fast second\n+ assert r.json() == [ord(\"A\"), ord(\"B\")]" } ], "reviews": [ { "id": 3756636187, "user": "user_29e85f9a8e75", "state": "APPROVED", "body": "LGTM!\n\n[USER_REDACTED], thanks!", "submitted_at": "2026-02-05T12:07:32+00:00" }, { "id": 3778447674, "user": "user_2a237e38e06b", "state": "APPROVED", "body": "Great, thank you! 🚀 \n\nI refactored this logic in https://github.com/fastapi/fastapi/pull/14884 , that should handle the problem. But I'll still take the test here to prevent it from happening again. 🤓", "submitted_at": "2026-02-10T11:42:40+00:00" } ], "review_comments": [ { "id": 2768766445, "user": "user_29e85f9a8e75", "body": "```suggestion\ndef test_list_bytes_file_preserves_order(\n```", "path": "tests/test_list_bytes_file_order_preserved_issue_14811.py", "line": null, "side": "RIGHT", "created_at": "2026-02-05T12:00:26+00:00" } ], "meta": { "languages": [ "py" ], "touches_tests": true, "review_state_summary": { "APPROVED": 2 }, "meaningful_comment_count": 1, "has_approval": true, "has_changes_requested": false, "total_review_comments": 1 } } { "_id": "594a76e26d881817", "_schema_version": "1.0", "_cleaned_at": "2026-02-12T07:46:51.624760+00:00", "repo": "tiangolo/fastapi", "repo_url": "https://github.com/fastapi/fastapi", "license_name": "MIT License", "license_spdx": "MIT", "pr_number": 14822, "title": "🌐 Update translations for uk (update-outdated)", "body": "🌐 Update translations for uk (update-outdated)\n\nThis PR was created automatically using LLMs.\n\nIt uses the prompt file https://github.com/fastapi/fastapi/blob/master/docs/uk/llm-prompt.md.\n\nIn most cases, it's better to make PRs updating that file so that the LLM can do a better job generating the translations than suggesting changes in this PR.", "author": "user_2a237e38e06b", "created_at": "2026-02-04T16:52:09+00:00", "merged_at": "2026-02-05T15:31:32+00:00", "base_branch": "master", "head_branch": "translate-uk-update-outdated-41dc7e2f", "additions": 23, "deletions": 28, "changed_files": 2, "files": [ { "filename": "docs/uk/docs/index.md", "status": "modified", "additions": 18, "deletions": 24, "changes": 42, "patch": "@@ -8,7 +8,7 @@\n \"FastAPI\"\n

      \n

      \n- Фреймворк FastAPI: висока продуктивність, легко вивчати, швидко писати код, готовий до продакшину\n+ Фреймворк FastAPI - це висока продуктивність, легко вивчати, швидко писати код, готовий до продакшину\n

      \n

      \n \n@@ -33,14 +33,14 @@\n \n ---\n \n-FastAPI — це сучасний, швидкий (високопродуктивний) вебфреймворк для створення API за допомогою Python, що базується на стандартних підказках типів Python.\n+FastAPI - це сучасний, швидкий (високопродуктивний) вебфреймворк для створення API за допомогою Python, що базується на стандартних підказках типів Python.\n \n Ключові особливості:\n \n * **Швидкий**: дуже висока продуктивність, на рівні з **NodeJS** та **Go** (завдяки Starlette та Pydantic). [Один із найшвидших Python-фреймворків](#performance).\n * **Швидке написання коду**: пришвидшує розробку функціоналу приблизно на 200%–300%. *\n * **Менше помилок**: зменшує приблизно на 40% кількість помилок, спричинених людиною (розробником). *\n-* **Інтуїтивний**: чудова підтримка редакторами коду. Автодоповнення всюди. Менше часу на налагодження.\n+* **Інтуїтивний**: чудова підтримка редакторами коду. Автодоповнення всюди. Менше часу на налагодження.\n * **Простий**: спроєктований так, щоб бути простим у використанні та вивченні. Менше часу на читання документації.\n * **Короткий**: мінімізує дублювання коду. Кілька можливостей з кожного оголошення параметра. Менше помилок.\n * **Надійний**: ви отримуєте код, готовий до продакшину. З автоматичною інтерактивною документацією.\n@@ -127,9 +127,9 @@ FastAPI — це сучасний, швидкий (високопродукти\n \n \n \n-Якщо ви створюєте застосунок CLI для використання в терміналі замість веб-API, зверніть увагу на **Typer**.\n+Якщо ви створюєте застосунок CLI для використання в терміналі замість веб-API, зверніть увагу на **Typer**.\n \n-**Typer** — молодший брат FastAPI. І його задумано як **FastAPI для CLI**. ⌨️ 🚀\n+**Typer** - молодший брат FastAPI. І його задумано як **FastAPI для CLI**. ⌨️ 🚀\n \n ## Вимоги { #requirements }\n \n@@ -161,8 +161,6 @@ $ pip install \"fastapi[standard]\"\n Створіть файл `main.py` з:\n \n ```Python\n-from typing import Union\n-\n from fastapi import FastAPI\n \n app = FastAPI()\n@@ -174,7 +172,7 @@ def read_root():\n \n \n [USER_REDACTED].get(\"/items/{item_id}\")\n-def read_item(item_id: int, q: Union[str, None] = None):\n+def read_item(item_id: int, q: str | None = None):\n return {\"item_id\": item_id, \"q\": q}\n ```\n \n@@ -183,9 +181,7 @@ def read_item(item_id: int, q: Union[str, None] = None):\n \n Якщо ваш код використовує `async` / `await`, скористайтеся `async def`:\n \n-```Python hl_lines=\"9 14\"\n-from typing import Union\n-\n+```Python hl_lines=\"7 12\"\n from fastapi import FastAPI\n \n app = FastAPI()\n@@ -197,7 +193,7 @@ async def read_root():\n \n \n [USER_REDACTED].get(\"/items/{item_id}\")\n-async def read_item(item_id: int, q: Union[str, None] = None):\n+async def read_item(item_id: int, q: str | None = None):\n return {\"item_id\": item_id, \"q\": q}\n ```\n \n@@ -288,9 +284,7 @@ INFO: Application startup complete.\n \n Оголосіть тіло, використовуючи стандартні типи Python, завдяки Pydantic.\n \n-```Python hl_lines=\"4 9-12 25-27\"\n-from typing import Union\n-\n+```Python hl_lines=\"2 7-10 23-25\"\n from fastapi import FastAPI\n from pydantic import BaseModel\n \n@@ -300,7 +294,7 @@ app = FastAPI()\n class Item(BaseModel):\n name: str\n price: float\n- is_offer: Union[bool, None] = None\n+ is_offer: bool | None = None\n \n \n [USER_REDACTED].get(\"/\")\n@@ -309,7 +303,7 @@ def read_root():\n \n \n [USER_REDACTED].get(\"/items/{item_id}\")\n-def read_item(item_id: int, q: Union[str, None] = None):\n+def read_item(item_id: int, q: str | None = None):\n return {\"item_id\": item_id, \"q\": q}\n \n \n@@ -374,15 +368,15 @@ item: Item\n * Валідацію даних:\n * Автоматичні та зрозумілі помилки, коли дані некоректні.\n * Валідацію навіть для глибоко вкладених JSON-обʼєктів.\n-* Перетворення вхідних даних: з мережі до даних і типів Python. Читання з:\n+* Перетворення вхідних даних: з мережі до даних і типів Python. Читання з:\n * JSON.\n * Параметрів шляху.\n * Параметрів запиту.\n * Cookies.\n * Headers.\n * Forms.\n * Files.\n-* Перетворення вихідних даних: перетворення з даних і типів Python у мережеві дані (як JSON):\n+* Перетворення вихідних даних: перетворення з даних і типів Python у мережеві дані (як JSON):\n * Перетворення типів Python (`str`, `int`, `float`, `bool`, `list`, тощо).\n * Обʼєктів `datetime`.\n * Обʼєктів `UUID`.\n@@ -439,9 +433,9 @@ item: Item\n \n ![editor support](https://fastapi.tiangolo.com/img/vscode-completion.png)\n \n-Для більш повного прикладу, що включає більше можливостей, перегляньте Туторіал — Посібник користувача.\n+Для більш повного прикладу, що включає більше можливостей, перегляньте Навчальний посібник - Посібник користувача.\n \n-**Spoiler alert**: туторіал — посібник користувача містить:\n+**Попередження про спойлер**: навчальний посібник - посібник користувача містить:\n \n * Оголошення **параметрів** з інших різних місць, як-от: **headers**, **cookies**, **form fields** та **files**.\n * Як встановлювати **обмеження валідації** як `maximum_length` або `regex`.\n@@ -500,11 +494,11 @@ Deploying to [NAME_REDACTED]...\n \n Він забезпечує той самий **developer experience** створення застосунків на FastAPI під час їх **розгортання** у хмарі. 🎉\n \n-[NAME_REDACTED] — основний спонсор і джерело фінансування open source проєктів *FastAPI and friends*. ✨\n+[NAME_REDACTED] - основний спонсор і джерело фінансування open source проєктів *FastAPI and friends*. ✨\n \n #### Розгортання в інших хмарних провайдерів { #deploy-to-other-cloud-providers }\n \n-FastAPI — open source і базується на стандартах. Ви можете розгортати застосунки FastAPI в будь-якому хмарному провайдері, який ви оберете.\n+FastAPI - open source проект і базується на стандартах. Ви можете розгортати застосунки FastAPI в будь-якому хмарному провайдері, який ви оберете.\n \n Дотримуйтеся інструкцій вашого хмарного провайдера, щоб розгорнути застосунки FastAPI у нього. 🤓\n \n@@ -530,7 +524,7 @@ FastAPI залежить від Pydantic і Starlette.\n \n * httpx - потрібно, якщо ви хочете використовувати `TestClient`.\n * jinja2 - потрібно, якщо ви хочете використовувати конфігурацію шаблонів за замовчуванням.\n-* python-multipart - потрібно, якщо ви хочете підтримувати «parsing» форм за допомогою `request.form()`.\n+* python-multipart - потрібно, якщо ви хочете підтримувати «parsing» форм за допомогою `request.form()`.\n \n Використовується FastAPI:" }, { "filename": "docs/uk/docs/tutorial/body-multiple-params.md", "status": "modified", "additions": 5, "deletions": 4, "changes": 9, "patch": "@@ -103,15 +103,16 @@\n Оскільки за замовчуванням одиничні значення інтерпретуються як параметри запиту, вам не потрібно явно додавати `Query`, ви можете просто зробити:\n \n ```Python\n-q: Union[str, None] = None\n+q: str | None = None\n ```\n \n-Або в Python 3.10 і вище:\n+Або в Python 3.9:\n \n ```Python\n-q: str | None = None\n+q: Union[str, None] = None\n ```\n \n+\n Наприклад:\n \n {* ../../docs_src/body_multiple_params/tutorial004_an_py310.py hl[28] *}\n@@ -129,7 +130,7 @@ q: str | None = None\n \n За замовчуванням **FastAPI** очікуватиме його тіло безпосередньо.\n \n-Але якщо ви хочете, щоб він очікував JSON з ключем `item`, а всередині нього — вміст моделі, як це відбувається, коли ви оголошуєте додаткові параметри тіла, ви можете використати спеціальний параметр `Body` — `embed`:\n+Але якщо ви хочете, щоб він очікував JSON з ключем `item`, а всередині нього - вміст моделі, як це відбувається, коли ви оголошуєте додаткові параметри тіла, ви можете використати спеціальний параметр `Body` - `embed`:\n \n ```Python\n item: Item = Body(embed=True)" } ], "reviews": [ { "id": 3752719590, "user": "user_c36c155012b4", "state": "COMMENTED", "body": "Changes looks good, just a small improvements :)", "submitted_at": "2026-02-04T18:39:53+00:00" }, { "id": 3752801380, "user": "user_489e2b951069", "state": "APPROVED", "body": null, "submitted_at": "2026-02-04T18:58:24+00:00" }, { "id": 3752972551, "user": "user_29e85f9a8e75", "state": "COMMENTED", "body": null, "submitted_at": "2026-02-04T19:41:27+00:00" }, { "id": 3753092052, "user": "user_c36c155012b4", "state": "COMMENTED", "body": null, "submitted_at": "2026-02-04T20:03:57+00:00" }, { "id": 3753125919, "user": "user_965b664e791a", "state": "COMMENTED", "body": null, "submitted_at": "2026-02-04T20:13:31+00:00" }, { "id": 3753151072, "user": "user_965b664e791a", "state": "COMMENTED", "body": null, "submitted_at": "2026-02-04T20:20:46+00:00" }, { "id": 3753174715, "user": "user_965b664e791a", "state": "COMMENTED", "body": null, "submitted_at": "2026-02-04T20:27:26+00:00" }, { "id": 3753191721, "user": "user_965b664e791a", "state": "COMMENTED", "body": null, "submitted_at": "2026-02-04T20:32:23+00:00" }, { "id": 3753220391, "user": "user_965b664e791a", "state": "COMMENTED", "body": null, "submitted_at": "2026-02-04T20:40:16+00:00" }, { "id": 3753245539, "user": "user_965b664e791a", "state": "COMMENTED", "body": null, "submitted_at": "2026-02-04T20:47:30+00:00" }, { "id": 3753255078, "user": "user_965b664e791a", "state": "CHANGES_REQUESTED", "body": "LLM makes mistakes when trying to translate definitions of terms", "submitted_at": "2026-02-04T20:50:18+00:00" }, { "id": 3756083060, "user": "user_29e85f9a8e75", "state": "COMMENTED", "body": null, "submitted_at": "2026-02-05T10:45:35+00:00" }, { "id": 3756095243, "user": "user_29e85f9a8e75", "state": "COMMENTED", "body": null, "submitted_at": "2026-02-05T10:46:56+00:00" }, { "id": 3756230995, "user": "user_29e85f9a8e75", "state": "COMMENTED", "body": null, "submitted_at": "2026-02-05T11:04:23+00:00" }, { "id": 3756413449, "user": "user_965b664e791a", "state": "COMMENTED", "body": null, "submitted_at": "2026-02-05T11:30:27+00:00" } ], "review_comments": [ { "id": 2765459760, "user": "user_c36c155012b4", "body": "```suggestion\n* **Інтуїтивний**: чудова підтримка редакторами коду. Автодоповнення всюди. Менше часу на налагодження.\n```", "path": "docs/uk/docs/index.md", "line": null, "side": "RIGHT", "created_at": "2026-02-04T18:35:50+00:00" }, { "id": 2765467209, "user": "user_c36c155012b4", "body": "```suggestion\n* python-multipart - потрібно, якщо ви хочете підтримувати «parsing» форм за допомогою `request.form()`.\n```", "path": "docs/uk/docs/index.md", "line": null, "side": "RIGHT", "created_at": "2026-02-04T18:38:01+00:00" }, { "id": 2765469490, "user": "user_c36c155012b4", "body": "```suggestion\n* Перетворення вихідних даних: перетворення з даних і типів Python у мережеві дані (як JSON):\n```", "path": "docs/uk/docs/index.md", "line": null, "side": "RIGHT", "created_at": "2026-02-04T18:38:43+00:00" }, { "id": 2765470609, "user": "user_c36c155012b4", "body": "```suggestion\n* Перетворення вхідних даних: з мережі до даних і типів Python. Читання з:\n```", "path": "docs/uk/docs/index.md", "line": null, "side": "RIGHT", "created_at": "2026-02-04T18:39:04+00:00" }, { "id": 2765524606, "user": "user_489e2b951069", "body": "```suggestion\n Фреймворк FastAPI - це висока продуктивність, легко вивчати, швидко писати код, готовий до продакшину\n```", "path": "docs/uk/docs/index.md", "line": null, "side": "RIGHT", "created_at": "2026-02-04T18:54:57+00:00" }, { "id": 2765536251, "user": "user_489e2b951069", "body": "```suggestion\nFastAPI - open source проект і базується на стандартах. Ви можете розгортати застосунки FastAPI в будь-якому хмарному провайдері, який ви оберете.\n```", "path": "docs/uk/docs/index.md", "line": null, "side": "RIGHT", "created_at": "2026-02-04T18:58:15+00:00" }, { "id": 2765667890, "user": "user_29e85f9a8e75", "body": "```suggestion\nЯкщо ви створюєте застосунок CLI для використання в терміналі замість веб-API, зверніть увагу на **Typer**.\n```", "path": "docs/uk/docs/index.md", "line": null, "side": "RIGHT", "created_at": "2026-02-04T19:32:58+00:00" }, { "id": 2765672687, "user": "user_29e85f9a8e75", "body": "We can try solving this with https://github.com/fastapi/fastapi/pull/14744 and https://github.com/fastapi/fastapi/pull/14747", "path": "docs/uk/docs/index.md", "line": null, "side": "RIGHT", "created_at": "2026-02-04T19:34:03+00:00" }, { "id": 2765683765, "user": "user_29e85f9a8e75", "body": "Actually, we don't need `also known as: serialization, parsing, marshalling` here - it's a mistake of LLM. It should be just translated to Ukrainian..\n\nShould it be\n``\nor\n``\n?", "path": "docs/uk/docs/index.md", "line": null, "side": "RIGHT", "created_at": "2026-02-04T19:36:51+00:00" }, { "id": 2765688624, "user": "user_29e85f9a8e75", "body": "Same problem with `` as above", "path": "docs/uk/docs/index.md", "line": null, "side": "RIGHT", "created_at": "2026-02-04T19:38:13+00:00" }, { "id": 2765695959, "user": "user_29e85f9a8e75", "body": "```suggestion\n* python-multipart - потрібно, якщо ви хочете підтримувати «parsing» форм за допомогою `request.form()`.\n```\n\nIt should be just translation, without English version", "path": "docs/uk/docs/index.md", "line": null, "side": "RIGHT", "created_at": "2026-02-04T19:40:24+00:00" }, { "id": 2765776080, "user": "user_c36c155012b4", "body": "any option works :)", "path": "docs/uk/docs/index.md", "line": null, "side": "RIGHT", "created_at": "2026-02-04T20:03:57+00:00" }, { "id": 2765808038, "user": "user_965b664e791a", "body": "Seems that LLM thinks that an original sentence must be leaved with a translation, but it's mistake: only the translate must be leaved. Also, LLM didn't consider a \"Completion\" word and, as a result, LLM thought that it must be considered as \"also known [to us]\" instead of \"[A completion is] also known\".\n\nTherefore, it must be corrected in this way:\n```suggestion\n* **Інтуїтивний**: чудова підтримка редакторами коду. Автодоповнення всюди. Менше часу на налагодження.\n```\n\nUPD: fixed a grammar error", "path": "docs/uk/docs/index.md", "line": null, "side": "RIGHT", "created_at": "2026-02-04T20:13:31+00:00" }, { "id": 2765830463, "user": "user_965b664e791a", "body": "It may be in this way: ``. Also, it can be ``, but we're losing a word \"also\".\n\nAlso, there is a same problem on line 43. I explained reasons of the problem there.\n\nUPD: added a variant and explained why is it correct too", "path": "docs/uk/docs/index.md", "line": null, "side": "RIGHT", "created_at": "2026-02-04T20:20:45+00:00" }, { "id": 2765850892, "user": "user_965b664e791a", "body": "\"Spoiler alert\" is not translated\n\nCan be translated in this way:\n```suggestion\n**Попередження про спойлер**: навчальний посібник - посібник користувача містить:\n```", "path": "docs/uk/docs/index.md", "line": null, "side": "RIGHT", "created_at": "2026-02-04T20:27:27+00:00" }, { "id": 2765866406, "user": "user_965b664e791a", "body": "In this context, it would be good to translate \"open source\":\n```suggestion\nFastAPI - відкритий код і базується на стандартах. Ви можете розгортати застосунки FastAPI в будь-якому хмарному провайдері, який ви оберете.\n```", "path": "docs/uk/docs/index.md", "line": null, "side": "RIGHT", "created_at": "2026-02-04T20:32:23+00:00" }, { "id": 2765892776, "user": "user_965b664e791a", "body": "In my opinion, it's adding new text rather then a translation. We can leave or translate \"open source\" and it'll be looking good.", "path": "docs/uk/docs/index.md", "line": null, "side": "RIGHT", "created_at": "2026-02-04T20:40:16+00:00" }, { "id": 2765915795, "user": "user_965b664e791a", "body": "LLM makes a mistake, leaving an original sentence. Also, [\"з\" will be better than \"із\"](https://ukr-mova.in.ua/library/orfografiya/mulozvuchnist-z,-iz,-zi,-zo.-chastuna-1).\n```suggestion\n* python-multipart - потрібно, якщо ви хочете підтримувати «parsing» форм за допомогою `request.form()`.\n```", "path": "docs/uk/docs/index.md", "line": null, "side": "RIGHT", "created_at": "2026-02-04T20:47:30+00:00" }, { "id": 2768327262, "user": "user_29e85f9a8e75", "body": "```suggestion\n* Перетворення вхідних даних: з мережі до даних і типів Python. Читання з:\n```", "path": "docs/uk/docs/index.md", "line": null, "side": "RIGHT", "created_at": "2026-02-05T10:45:35+00:00" }, { "id": 2768336986, "user": "user_29e85f9a8e75", "body": "```suggestion\n* Перетворення вихідних даних: перетворення з даних і типів Python у мережеві дані (як JSON):\n```", "path": "docs/uk/docs/index.md", "line": null, "side": "RIGHT", "created_at": "2026-02-05T10:46:56+00:00" }, { "id": 2768444915, "user": "user_29e85f9a8e75", "body": "I personally think it's Ok to translate it as \"open source проект\" (\"open source project\"). I think it sounds clearer than \"відкритий код\" (more like \"open source code\").\nI think we should go with \"open source проект\"", "path": "docs/uk/docs/index.md", "line": null, "side": "RIGHT", "created_at": "2026-02-05T11:04:23+00:00" }, { "id": 2768589624, "user": "user_965b664e791a", "body": "OK, no problem! We can leave \"open source проект\"", "path": "docs/uk/docs/index.md", "line": null, "side": "RIGHT", "created_at": "2026-02-05T11:30:27+00:00" } ], "meta": { "languages": [ "md" ], "touches_tests": false, "review_state_summary": { "COMMENTED": 13, "APPROVED": 1, "CHANGES_REQUESTED": 1 }, "meaningful_comment_count": 22, "has_approval": true, "has_changes_requested": true, "total_review_comments": 22 } } { "_id": "66f540a3ebf54e56", "_schema_version": "1.0", "_cleaned_at": "2026-02-12T07:46:51.624760+00:00", "repo": "tiangolo/fastapi", "repo_url": "https://github.com/fastapi/fastapi", "license_name": "MIT License", "license_spdx": "MIT", "pr_number": 14809, "title": "📝 Add banner to translated pages", "body": null, "author": "user_29e85f9a8e75", "created_at": "2026-02-03T14:42:02+00:00", "merged_at": "2026-02-04T13:26:02+00:00", "base_branch": "master", "head_branch": "translation-banner", "additions": 51, "deletions": 1, "changed_files": 3, "files": [ { "filename": "docs/en/docs/translation-banner.md", "status": "added", "additions": 11, "deletions": 0, "changes": 11, "patch": "@@ -0,0 +1,11 @@\n+/// details | 🌐 Translation by [NAME_REDACTED]\n+\n+This translation was made by [NAME_REDACTED] 🤝\n+\n+It could have mistakes of misunderstanding the original meaning, or looking unnatural, etc. 🤖\n+\n+You can improve this translation by [helping us guide the AI LLM better](https://fastapi.tiangolo.com/contributing/#translations).\n+\n+[English version](ENGLISH_VERSION_URL)\n+\n+///" }, { "filename": "docs/ru/docs/translation-banner.md", "status": "added", "additions": 11, "deletions": 0, "changes": 11, "patch": "@@ -0,0 +1,11 @@\n+/// details | 🌐 Перевод выполнен с помощью ИИ и людей\n+\n+Этот перевод был сделан ИИ под руководством людей. 🤝\n+\n+В нем могут быть ошибки из-за неправильного понимания оригинального смысла или неестественности и т. д. 🤖\n+\n+Вы можете улучшить этот перевод, [помогая нам лучше направлять ИИ LLM](https://fastapi.tiangolo.com/ru/contributing/#translations).\n+\n+[Английская версия](ENGLISH_VERSION_URL)\n+\n+///" }, { "filename": "scripts/mkdocs_hooks.py", "status": "modified", "additions": 29, "deletions": 1, "changes": 30, "patch": "@@ -26,6 +26,17 @@ def get_missing_translation_content(docs_dir: str) -> str:\n return missing_translation_path.read_text(encoding=\"utf-8\")\n \n \n+[USER_REDACTED]_cache\n+def get_translation_banner_content(docs_dir: str) -> str:\n+ docs_dir_path = Path(docs_dir)\n+ translation_banner_path = docs_dir_path / \"translation-banner.md\"\n+ if not translation_banner_path.is_file():\n+ translation_banner_path = (\n+ docs_dir_path.parent.parent / \"en\" / \"docs\" / \"translation-banner.md\"\n+ )\n+ return translation_banner_path.read_text(encoding=\"utf-8\")\n+\n+\n [USER_REDACTED]_cache\n def get_mkdocs_material_langs() -> list[str]:\n material_path = Path(material.__file__).parent\n@@ -151,4 +162,21 @@ def on_page_markdown(\n if markdown.startswith(\"#\"):\n header, _, body = markdown.partition(\"\\n\\n\")\n return f\"{header}\\n\\n{missing_translation_content}\\n\\n{body}\"\n- return markdown\n+\n+ docs_dir_path = Path(config.docs_dir)\n+ en_docs_dir_path = docs_dir_path.parent.parent / \"en/docs\"\n+\n+ if docs_dir_path == en_docs_dir_path:\n+ return markdown\n+\n+ # For translated pages add translation banner\n+ translation_banner_content = get_translation_banner_content(config.docs_dir)\n+ en_url = \"https://fastapi.tiangolo.com/\" + page.url.lstrip(\"/\")\n+ translation_banner_content = translation_banner_content.replace(\n+ \"ENGLISH_VERSION_URL\", en_url\n+ )\n+ header = \"\"\n+ body = markdown\n+ if markdown.startswith(\"#\"):\n+ header, _, body = markdown.partition(\"\\n\\n\")\n+ return f\"{header}\\n\\n{translation_banner_content}\\n\\n{body}\"" } ], "reviews": [ { "id": 3746292094, "user": "user_29e85f9a8e75", "state": "COMMENTED", "body": null, "submitted_at": "2026-02-03T16:32:47+00:00" }, { "id": 3750471364, "user": "user_2a237e38e06b", "state": "COMMENTED", "body": null, "submitted_at": "2026-02-04T11:18:41+00:00" }, { "id": 3750534486, "user": "user_2a237e38e06b", "state": "COMMENTED", "body": "Looking great! A coupe of suggestions.", "submitted_at": "2026-02-04T11:34:06+00:00" }, { "id": 3750699607, "user": "user_29e85f9a8e75", "state": "COMMENTED", "body": null, "submitted_at": "2026-02-04T12:08:58+00:00" }, { "id": 3750701074, "user": "user_29e85f9a8e75", "state": "COMMENTED", "body": null, "submitted_at": "2026-02-04T12:09:14+00:00" }, { "id": 3750814172, "user": "user_2a237e38e06b", "state": "APPROVED", "body": "Excellent, thank you! 🚀 🎉", "submitted_at": "2026-02-04T12:37:06+00:00" } ], "review_comments": [ { "id": 2759951825, "user": "user_29e85f9a8e75", "body": "Is the line above valid?\nI haven't found docs about it. Maybe just a typo?", "path": "docs/en/mkdocs.yml", "line": null, "side": "RIGHT", "created_at": "2026-02-03T16:32:47+00:00" }, { "id": 2763494043, "user": "user_2a237e38e06b", "body": "Ah, yep, it's here: https://facelessuser.github.io/pymdown-extensions/extensions/blocks/plugins/details/\n\nIt's the same style as other blocks we use:\n\n```Markdown\n/// details | Some summary\nSome content\n///\n```", "path": "docs/en/mkdocs.yml", "line": null, "side": "RIGHT", "created_at": "2026-02-04T11:18:41+00:00" }, { "id": 2763549901, "user": "user_2a237e38e06b", "body": "Looking at this I'm realizing that we already have the data to put there a link to the original in English, that might help.\n\nWe could add an:\n\n```Markdown\n[English version](https://blahblah/link)\n```", "path": "scripts/mkdocs_hooks.py", "line": 182, "side": "RIGHT", "created_at": "2026-02-04T11:33:50+00:00" }, { "id": 2763691715, "user": "user_29e85f9a8e75", "body": "Thanks!\nUpdated", "path": "docs/en/mkdocs.yml", "line": null, "side": "RIGHT", "created_at": "2026-02-04T12:08:58+00:00" }, { "id": 2763692861, "user": "user_29e85f9a8e75", "body": "Added link", "path": "scripts/mkdocs_hooks.py", "line": 182, "side": "RIGHT", "created_at": "2026-02-04T12:09:14+00:00" } ], "meta": { "languages": [ "md", "py" ], "touches_tests": false, "review_state_summary": { "COMMENTED": 5, "APPROVED": 1 }, "meaningful_comment_count": 5, "has_approval": true, "has_changes_requested": false, "total_review_comments": 5 } } { "_id": "6250b8483e89bd2e", "_schema_version": "1.0", "_cleaned_at": "2026-02-12T07:46:51.624760+00:00", "repo": "tiangolo/fastapi", "repo_url": "https://github.com/fastapi/fastapi", "license_name": "MIT License", "license_spdx": "MIT", "pr_number": 14795, "title": "🌐 Improve LLM prompt of `uk` documentation", "body": "Most of terms are not translated by LLM, so the PR fixes this problem. Partially fixes #14700\n\nUPD: add PR which will be partially fixed by [NAME_REDACTED]", "author": "user_965b664e791a", "created_at": "2026-02-01T00:53:15+00:00", "merged_at": "2026-02-04T16:47:51+00:00", "base_branch": "master", "head_branch": "edit-doc-uk-prompt", "additions": 67, "deletions": 0, "changed_files": 1, "files": [ { "filename": "docs/uk/llm-prompt.md", "status": "modified", "additions": 67, "deletions": 0, "changes": 67, "patch": "@@ -8,6 +8,7 @@ Language code: uk.\n \n - Use polite/formal address consistent with existing Ukrainian docs (use “ви/ваш”).\n - Keep the tone concise and technical.\n+- Use one style of dashes. For example, if text contains \"-\" then use only this symbol to represent a dash.\n \n ### Headings\n \n@@ -32,6 +33,71 @@ Use the following preferred translations when they apply in documentation prose:\n - response (HTTP): відповідь\n - path operation: операція шляху\n - path operation function: функція операції шляху\n+- prompt: підсказка\n+- check: перевірка\n+- [NAME_REDACTED] Interface: Інтерфейс Шлюзу Паралельного Сервера\n+- [NAME_REDACTED] Network: Мережа Розробників Mozilla\n+- tutorial: навчальний посібник\n+- advanced user guide: просунутий посібник користувача\n+- deep learning: глибоке навчання\n+- machine learning: машинне навчання\n+- dependency injection: впровадження залежностей\n+- digest (HTTP): дайджест\n+- basic authentication (HTTP): базова автентифікація\n+- JSON schema: Схема JSON\n+- password flow: потік паролю\n+- mobile: мобільний\n+- body: тіло\n+- form: форма\n+- path: шлях\n+- query: запит\n+- cookie: кукі\n+- header: заголовок\n+- startup: запуск\n+- shutdown: вимкнення\n+- lifespan: тривалість життя\n+- authorization: авторизація\n+- forwarded header: направлений заголовок\n+- dependable: залежний\n+- dependent: залежний\n+- bound: межа\n+- concurrency: рівночасність\n+- parallelism: паралелізм\n+- multiprocessing: багатопроцесорність\n+- env var: змінна оточення\n+- dict: словник\n+- enum: перелік\n+- issue: проблема\n+- server worker: серверний працівник\n+- worker: працівник\n+- software development kit: набір для розробки програмного забезпечення\n+- bearer token: токен носія\n+- breaking change: несумісна зміна\n+- bug: помилка\n+- button: кнопка\n+- callable: викликаємий\n+- code: код\n+- commit: фіксація\n+- context manager: менеджер контексту\n+- coroutine: співпрограма\n+- engine: рушій\n+- fake X: фальшивий X\n+- item: предмет\n+- lock: блокування\n+- middleware: проміжне програмне забезпечення\n+- mounting: монтування\n+- origin: джерело\n+- override: переписування\n+- payload: корисне навантаження\n+- processor: процесор\n+- property: властивість\n+- proxy: представник\n+- pull request: запит на витяг\n+- random-access memory: пам'ять з довільним доступом\n+- status code: код статусу\n+- string: строка\n+- tag: мітка\n+- wildcard: дика карта\n \n ### `///` admonitions\n \n@@ -44,3 +110,4 @@ Use the following preferred translations when they apply in documentation prose:\n - `/// warning | Попередження`\n - `/// info | Інформація`\n - `/// danger | Обережно`\n+- `/// check | Перевірте`" } ], "reviews": [ { "id": 3735616538, "user": "user_e0d9d241a0ad", "state": "COMMENTED", "body": null, "submitted_at": "2026-02-01T14:36:24+00:00" }, { "id": 3752122974, "user": "user_2a237e38e06b", "state": "APPROVED", "body": "Awesome, thank you! 🙌", "submitted_at": "2026-02-04T16:47:25+00:00" } ], "review_comments": [ { "id": 2751133555, "user": "user_e0d9d241a0ad", "body": "data-science - не перекладається", "path": "docs/uk/llm-prompt.md", "line": null, "side": "RIGHT", "created_at": "2026-02-01T12:05:51+00:00" }, { "id": 2751134535, "user": "user_e0d9d241a0ad", "body": "```suggestion\n- enum: перелік\n```", "path": "docs/uk/llm-prompt.md", "line": null, "side": "RIGHT", "created_at": "2026-02-01T12:06:32+00:00" } ], "meta": { "languages": [ "md" ], "touches_tests": false, "review_state_summary": { "COMMENTED": 1, "APPROVED": 1 }, "meaningful_comment_count": 2, "has_approval": true, "has_changes_requested": false, "total_review_comments": 2 } } { "_id": "53d679d91cd9067a", "_schema_version": "1.0", "_cleaned_at": "2026-02-12T07:46:51.624760+00:00", "repo": "tiangolo/fastapi", "repo_url": "https://github.com/fastapi/fastapi", "license_name": "MIT License", "license_spdx": "MIT", "pr_number": 14789, "title": "🐛 Fix TYPE_CHECKING annotations for Python 3.14 (PEP 649)", "body": "PR #14485 fixed support for if TYPE_CHECKING, non-evaluated stringified annotations, when using `from __future__ import annotations`.\n\nThis change adds the same support when using deferred evaluation of annotations introduced in Python 3.14.\n\nNote: I was also able to reproduce the issue by removing `from __future__ import annotations` from `tests/test_stringified_annotation_dependency.py` (using python 3.14). \n\nIt has been [discussed here](https://github.com/fastapi/fastapi/discussions/14784)", "author": "user_39c3b1c9d6c5", "created_at": "2026-01-31T14:17:20+00:00", "merged_at": "2026-02-04T13:49:44+00:00", "base_branch": "master", "head_branch": "fix-if-type-checking-py-314", "additions": 46, "deletions": 5, "changed_files": 4, "files": [ { "filename": "fastapi/dependencies/utils.py", "status": "modified", "additions": 6, "deletions": 1, "changes": 7, "patch": "@@ -204,7 +204,12 @@ def _get_signature(call: Callable[..., Any]) -> inspect.Signature:\n except NameError:\n # Handle type annotations with if TYPE_CHECKING, not used by FastAPI\n # e.g. dependency return types\n- signature = inspect.signature(call)\n+ if sys.version_info >= (3, 14):\n+ from annotationlib import Format\n+\n+ signature = inspect.signature(call, annotation_format=Format.FORWARDREF)\n+ else:\n+ signature = inspect.signature(call)\n else:\n signature = inspect.signature(call)\n return signature" }, { "filename": "tests/test_stringified_annotation_dependency_py314.py", "status": "added", "additions": 30, "deletions": 0, "changes": 30, "patch": "@@ -0,0 +1,30 @@\n+from typing import TYPE_CHECKING, Annotated\n+\n+from fastapi import Depends, FastAPI\n+from fastapi.testclient import TestClient\n+\n+from .utils import needs_py314\n+\n+if TYPE_CHECKING: # pragma: no cover\n+\n+ class DummyUser: ...\n+\n+\n+[USER_REDACTED]_py314\n+def test_stringified_annotation():\n+ # python3.14: Use forward reference without \"from __future__ import annotations\"\n+ async def get_current_user() -> DummyUser | None:\n+ return None\n+\n+ app = FastAPI()\n+\n+ client = TestClient(app)\n+\n+ [USER_REDACTED].get(\"/\")\n+ async def get(\n+ current_user: Annotated[DummyUser | None, Depends(get_current_user)],\n+ ) -> str:\n+ return \"hello world\"\n+\n+ response = client.get(\"/\")\n+ assert response.status_code == 200" }, { "filename": "tests/test_tutorial/test_dependencies/test_tutorial008.py", "status": "modified", "additions": 8, "deletions": 2, "changes": 10, "patch": "@@ -1,4 +1,5 @@\n import importlib\n+import sys\n from types import ModuleType\n from typing import Annotated, Any\n from unittest.mock import Mock, patch\n@@ -12,8 +13,13 @@\n name=\"module\",\n params=[\n \"tutorial008_py39\",\n- # Fails with `NameError: name 'DepA' is not defined`\n- pytest.param(\"tutorial008_an_py39\", marks=pytest.mark.xfail),\n+ pytest.param(\n+ \"tutorial008_an_py39\",\n+ marks=pytest.mark.xfail(\n+ sys.version_info < (3, 14),\n+ reason=\"Fails with `NameError: name 'DepA' is not defined`\",\n+ ),\n+ ),\n ],\n )\n def get_module(request: pytest.FixtureRequest):" }, { "filename": "tests/utils.py", "status": "modified", "additions": 2, "deletions": 2, "changes": 4, "patch": "@@ -6,8 +6,8 @@\n needs_py310 = pytest.mark.skipif(\n sys.version_info < (3, 10), reason=\"requires python3.10+\"\n )\n-needs_py_lt_314 = pytest.mark.skipif(\n- sys.version_info >= (3, 14), reason=\"requires python3.13-\"\n+needs_py314 = pytest.mark.skipif(\n+ sys.version_info < (3, 14), reason=\"requires python3.14+\"\n )" } ], "reviews": [ { "id": 3732721601, "user": "user_39c3b1c9d6c5", "state": "COMMENTED", "body": null, "submitted_at": "2026-01-31T14:18:11+00:00" }, { "id": 3732724041, "user": "user_39c3b1c9d6c5", "state": "COMMENTED", "body": null, "submitted_at": "2026-01-31T14:19:03+00:00" }, { "id": 3740194909, "user": "user_29e85f9a8e75", "state": "APPROVED", "body": "LGTM!\n[USER_REDACTED], thank you!\n\nProbably better title: 🐛 Fix `TYPE_CHECKING` annotations for Python 3.14 (PEP 649)", "submitted_at": "2026-02-02T15:29:24+00:00" }, { "id": 3751178276, "user": "user_2a237e38e06b", "state": "APPROVED", "body": "Nice, thank you! This will be available in FastAPI 0.128.1, released in the next few hours. 🚀", "submitted_at": "2026-02-04T13:49:33+00:00" } ], "review_comments": [ { "id": 2749610463, "user": "user_39c3b1c9d6c5", "body": "`needs_py_lt_314` wasn't used", "path": "tests/utils.py", "line": null, "side": "RIGHT", "created_at": "2026-01-31T14:18:11+00:00" }, { "id": 2749611842, "user": "user_39c3b1c9d6c5", "body": "I could move this import to top level, wdyt?", "path": "fastapi/dependencies/utils.py", "line": 208, "side": "RIGHT", "created_at": "2026-01-31T14:19:03+00:00" } ], "meta": { "languages": [ "py" ], "touches_tests": true, "review_state_summary": { "COMMENTED": 2, "APPROVED": 2 }, "meaningful_comment_count": 2, "has_approval": true, "has_changes_requested": false, "total_review_comments": 2 } } { "_id": "47cfac2d5bcdb5d7", "_schema_version": "1.0", "_cleaned_at": "2026-02-12T07:46:51.624760+00:00", "repo": "tiangolo/fastapi", "repo_url": "https://github.com/fastapi/fastapi", "license_name": "MIT License", "license_spdx": "MIT", "pr_number": 14756, "title": "📝 Use `WSGIMiddleware` from `a2wsgi` instead of deprecated `fastapi.middleware.wsgi.WSGIMiddleware`", "body": "`fastapi.middleware.wsgi.WSGIMiddleware` (re-exported from Starlette) is deprecated:\n\nhttps://github.com/Kludex/starlette/blob/501b86185461d107869917ced367d5624f82e3fb/starlette/middleware/wsgi.py#L15-L20", "author": "user_29e85f9a8e75", "created_at": "2026-01-22T11:12:17+00:00", "merged_at": "2026-02-04T11:54:24+00:00", "base_branch": "master", "head_branch": "use-external-WSGIMiddleware", "additions": 39, "deletions": 13, "changed_files": 6, "files": [ { "filename": "docs/en/docs/advanced/wsgi.md", "status": "modified", "additions": 18, "deletions": 2, "changes": 20, "patch": "@@ -6,13 +6,29 @@ For that, you can use the `WSGIMiddleware` and use it to wrap your WSGI applicat\n \n ## Using `WSGIMiddleware` { #using-wsgimiddleware }\n \n-You need to import `WSGIMiddleware`.\n+/// info\n+\n+This requires installing `a2wsgi` for example with `pip install a2wsgi`.\n+\n+///\n+\n+You need to import `WSGIMiddleware` from `a2wsgi`.\n \n Then wrap the WSGI (e.g. Flask) app with the middleware.\n \n And then mount that under a path.\n \n-{* ../../docs_src/wsgi/tutorial001_py39.py hl[2:3,3] *}\n+{* ../../docs_src/wsgi/tutorial001_py39.py hl[1,3,23] *}\n+\n+/// note\n+\n+Previously, it was recommended to use `WSGIMiddleware` from `fastapi.middleware.wsgi`, but it is now deprecated.\n+\n+It’s advised to use the `a2wsgi` package instead. The usage remains the same.\n+\n+Just ensure that you have the `a2wsgi` package installed and import `WSGIMiddleware` correctly from `a2wsgi`.\n+\n+///\n \n ## Check it { #check-it }" }, { "filename": "docs/en/docs/reference/middleware.md", "status": "modified", "additions": 0, "deletions": 8, "changes": 8, "patch": "@@ -35,11 +35,3 @@ It can be imported from `fastapi`:\n ```python\n from fastapi.middleware.trustedhost import TrustedHostMiddleware\n ```\n-\n-::: fastapi.middleware.wsgi.WSGIMiddleware\n-\n-It can be imported from `fastapi`:\n-\n-```python\n-from fastapi.middleware.wsgi import WSGIMiddleware\n-```" }, { "filename": "docs_src/wsgi/tutorial001_py39.py", "status": "modified", "additions": 1, "deletions": 1, "changes": 2, "patch": "@@ -1,5 +1,5 @@\n+from a2wsgi import WSGIMiddleware\n from fastapi import FastAPI\n-from fastapi.middleware.wsgi import WSGIMiddleware\n from flask import Flask, request\n from markupsafe import escape" }, { "filename": "fastapi/middleware/wsgi.py", "status": "modified", "additions": 3, "deletions": 1, "changes": 4, "patch": "@@ -1 +1,3 @@\n-from starlette.middleware.wsgi import WSGIMiddleware as WSGIMiddleware # noqa\n+from starlette.middleware.wsgi import (\n+ WSGIMiddleware as WSGIMiddleware,\n+) # pragma: no cover # noqa" }, { "filename": "pyproject.toml", "status": "modified", "additions": 1, "deletions": 1, "changes": 2, "patch": "@@ -178,6 +178,7 @@ tests = [\n \"strawberry-graphql>=0.200.0,<1.0.0\",\n \"types-orjson==3.6.2\",\n \"types-ujson==5.10.0.20240515\",\n+ \"a2wsgi>=1.9.0,<=2.0.0\",\n ]\n translations = [\n \"gitpython==3.1.45\",\n@@ -231,7 +232,6 @@ xfail_strict = true\n junit_family = \"xunit2\"\n filterwarnings = [\n \"error\",\n- 'ignore:starlette.middleware.wsgi is deprecated and will be removed in a future release\\..*:DeprecationWarning:starlette',\n # see https://trio.readthedocs.io/en/stable/history.html#trio-0-22-0-2022-09-28\n \"ignore:You seem to already have a custom.*:RuntimeWarning:trio\",\n # TODO: remove after upgrading SQLAlchemy to a version that includes the following changes" }, { "filename": "uv.lock", "status": "modified", "additions": 16, "deletions": 0, "changes": 16, "patch": "@@ -7,6 +7,18 @@ resolution-markers = [\n \"python_full_version < '3.10'\",\n ]\n \n+[[package]]\n+name = \"a2wsgi\"\n+version = \"1.10.10\"\n+source = { registry = \"https://pypi.org/simple\" }\n+dependencies = [\n+ { name = \"typing-extensions\", marker = \"python_full_version < '3.11'\" },\n+]\n+sdist = { url = \"https://files.pythonhosted.org/packages/9a/cb/822c56fbea97e9eee201a2e434a80437f6750ebcb1ed307ee3a0a7505b14/a2wsgi-1.10.10.tar.gz\", hash = \"sha256:a5bcffb52081ba39df0d5e9a884fc6f819d92e3a42389343ba77cbf809fe1f45\", size = 18799, upload-time = \"2025-06-18T09:00:10.843Z\" }\n+wheels = [\n+ { url = \"https://files.pythonhosted.org/packages/02/d5/349aba3dc421e73cbd4958c0ce0a4f1aa3a738bc0d7de75d2f40ed43a535/a2wsgi-1.10.10-py3-none-any.whl\", hash = \"sha256:d2b21379479718539dc15fce53b876251a0efe7615352dfe49f6ad1bc507848d\", size = 17389, upload-time = \"2025-06-18T09:00:09.676Z\" },\n+]\n+\n [[package]]\n name = \"ag-ui-protocol\"\n version = \"0.1.10\"\n@@ -1058,6 +1070,7 @@ standard-no-fastapi-cloud-cli = [\n \n [package.dev-dependencies]\n dev = [\n+ { name = \"a2wsgi\" },\n { name = \"anyio\", extra = [\"trio\"] },\n { name = \"black\" },\n { name = \"cairosvg\" },\n@@ -1131,6 +1144,7 @@ github-actions = [\n { name = \"smokeshow\" },\n ]\n tests = [\n+ { name = \"a2wsgi\" },\n { name = \"anyio\", extra = [\"trio\"] },\n { name = \"coverage\", version = \"7.10.7\", source = { registry = \"https://pypi.org/simple\" }, extra = [\"toml\"], marker = \"python_full_version < '3.10'\" },\n { name = \"coverage\", version = \"7.13.1\", source = { registry = \"https://pypi.org/simple\" }, extra = [\"toml\"], marker = \"python_full_version >= '3.10'\" },\n@@ -1197,6 +1211,7 @@ provides-extras = [\"standard\", \"standard-no-fastapi-cloud-cli\", \"all\"]\n \n [package.metadata.requires-dev]\n dev = [\n+ { name = \"a2wsgi\", specifier = \">=1.9.0,<=2.0.0\" },\n { name = \"anyio\", extras = [\"trio\"], specifier = \">=3.2.1,<5.0.0\" },\n { name = \"black\", specifier = \"==25.1.0\" },\n { name = \"cairosvg\", specifier = \"==2.8.2\" },\n@@ -1266,6 +1281,7 @@ github-actions = [\n { name = \"smokeshow\", specifier = \">=0.5.0\" },\n ]\n tests = [\n+ { name = \"a2wsgi\", specifier = \">=1.9.0,<=2.0.0\" },\n { name = \"anyio\", extras = [\"trio\"], specifier = \">=3.2.1,<5.0.0\" },\n { name = \"coverage\", extras = [\"toml\"], specifier = \">=6.5.0,<8.0\" },\n { name = \"dirty-equals\", specifier = \"==0.9.0\" }," } ], "reviews": [ { "id": 3691931242, "user": "user_29e85f9a8e75", "state": "COMMENTED", "body": null, "submitted_at": "2026-01-22T11:13:10+00:00" }, { "id": 3750618416, "user": "user_2a237e38e06b", "state": "APPROVED", "body": "Excellent, thank you! 🚀 🙌", "submitted_at": "2026-02-04T11:54:10+00:00" } ], "review_comments": [ { "id": 2716457348, "user": "user_29e85f9a8e75", "body": "With versions prior to `1.9.0` it gives error `404 Not found`", "path": "pyproject.toml", "line": 181, "side": "RIGHT", "created_at": "2026-01-22T11:13:10+00:00" } ], "meta": { "languages": [ "lock", "md", "py", "toml" ], "touches_tests": false, "review_state_summary": { "COMMENTED": 1, "APPROVED": 1 }, "meaningful_comment_count": 1, "has_approval": true, "has_changes_requested": false, "total_review_comments": 1 } } { "_id": "7a3e9a80bae99a4f", "_schema_version": "1.0", "_cleaned_at": "2026-02-12T07:46:51.624760+00:00", "repo": "tiangolo/fastapi", "repo_url": "https://github.com/fastapi/fastapi", "license_name": "MIT License", "license_spdx": "MIT", "pr_number": 14747, "title": "🔧 Update LLM-prompt for `abbr` and `dfn` tags", "body": "Updated `scripts/general-llm-prompt.md` to simplify instructions for `abbr` tags and add instructions for `dfn` tags.\n\nThis should go after https://github.com/fastapi/fastapi/pull/14744\n\n---\n\nI ran translation script for `_llm-test.md` files of supported languages to sync them.\nTo do this I used `GPT-5` model instead of `GPT-5.2` as it gives better result (less mistakes and less diff).\n\nI think we should consider downgrading model to `GPT-5` - I tested it on different pages (also with existing translation and without) and it gives better results most of the time", "author": "user_29e85f9a8e75", "created_at": "2026-01-20T23:19:26+00:00", "merged_at": "2026-02-10T11:56:21+00:00", "base_branch": "master", "head_branch": "update-llm-prompt-for-abbr-and-dfn-tags", "additions": 63, "deletions": 79, "changed_files": 7, "files": [ { "filename": "docs/de/docs/_llm-test.md", "status": "modified", "additions": 7, "deletions": 7, "changes": 14, "patch": "@@ -35,7 +35,7 @@ [NAME_REDACTED] `### Content of code snippets` im allgemeinen Prompt in `scripts\n \n //// tab | Test\n \n-Gestern schrieb mein Freund: „Wenn man unkorrekt korrekt schreibt, hat man es unkorrekt geschrieben“. Worauf ich antwortete: „Korrekt, aber ‚unkorrekt‘ ist unkorrekterweise nicht ‚„unkorrekt“‘“.\n+Gestern schrieb mein Freund: „Wenn man ‚incorrectly‘ korrekt schreibt, hat man es falsch geschrieben“. Worauf ich antwortete: „Korrekt, aber ‚incorrectly‘ ist inkorrekterweise nicht ‚„incorrectly“‘“.\n \n /// note | Hinweis\n \n@@ -202,11 +202,6 @@ Hier einige Dinge, die in HTML-„abbr“-Elemente gepackt sind (einige sind erf\n * XWT\n * PSGI\n \n-### Das abbr gibt eine Erklärung { #the-abbr-gives-an-explanation }\n-\n-* Cluster\n-* [NAME_REDACTED]\n-\n ### Das abbr gibt eine vollständige Phrase und eine Erklärung { #the-abbr-gives-a-full-phrase-and-an-explanation }\n \n * MDN\n@@ -224,6 +219,11 @@ [NAME_REDACTED] `### HTML abbr elements` im allgemeinen Prompt in `scripts/trans\n \n ////\n \n+## HTML „dfn“-Elemente { #html-dfn-elements }\n+\n+* Cluster\n+* [NAME_REDACTED]\n+\n ## Überschriften { #headings }\n \n //// tab | Test\n@@ -248,7 +248,7 @@ Die einzige strenge Regel für Überschriften ist, dass das LLM den Hash-Teil in\n \n [NAME_REDACTED] `### Headings` im allgemeinen Prompt in `scripts/translate.py`.\n \n-Für einige sprachspezifische Anweisungen, siehe z. B. den Abschnitt `### Headings` in `docs/de/llm-prompt.md`.\n+Für einige sprachsspezifische Anweisungen, siehe z. B. den Abschnitt `### Headings` in `docs/de/llm-prompt.md`.\n \n ////" }, { "filename": "docs/en/docs/_llm-test.md", "status": "modified", "additions": 5, "deletions": 5, "changes": 10, "patch": "@@ -202,11 +202,6 @@ Here some things wrapped in HTML \"abbr\" elements (Some are invented):\n * XWT\n * PSGI\n \n-### The abbr gives an explanation { #the-abbr-gives-an-explanation }\n-\n-* cluster\n-* \n-\n ### The abbr gives a full phrase and an explanation { #the-abbr-gives-a-full-phrase-and-an-explanation }\n \n * MDN\n@@ -224,6 +219,11 @@ See section `### HTML abbr elements` in the general prompt in `scripts/translate\n \n ////\n \n+## HTML \"dfn\" elements { #html-dfn-elements }\n+\n+* cluster\n+* \n+\n ## Headings { #headings }\n \n //// tab | Test" }, { "filename": "docs/es/docs/_llm-test.md", "status": "modified", "additions": 7, "deletions": 7, "changes": 14, "patch": "@@ -202,15 +202,10 @@ Aquí algunas cosas envueltas en elementos HTML \"abbr\" (algunas son inventadas):\n * XWT\n * PSGI\n \n-### El abbr da una explicación { #the-abbr-gives-an-explanation }\n-\n-* clúster\n-* [NAME_REDACTED]\n-\n ### El abbr da una frase completa y una explicación { #the-abbr-gives-a-full-phrase-and-an-explanation }\n \n * MDN\n-* I/O.\n+* I/O.\n \n ////\n \n@@ -224,6 +219,11 @@ Consulta la sección `### HTML abbr elements` en el prompt general en `scripts/t\n \n ////\n \n+## Elementos HTML \"dfn\" { #html-dfn-elements }\n+\n+* clúster\n+* [NAME_REDACTED]\n+\n ## Encabezados { #headings }\n \n //// tab | Prueba\n@@ -433,7 +433,7 @@ Para instrucciones específicas del idioma, mira p. ej. la sección `### Heading\n * el motor de plantillas\n \n * la anotación de tipos\n-* las anotaciones de tipos\n+* la anotación de tipos\n \n * el worker del servidor\n * el worker de Uvicorn" }, { "filename": "docs/ko/docs/_llm-test.md", "status": "modified", "additions": 6, "deletions": 6, "changes": 12, "patch": "@@ -132,7 +132,7 @@ works(foo=\"bar\") # 이건 동작합니다 🎉\n 일부 텍스트\n ///\n \n-/// note Technical details | 기술 세부사항\n+/// note | 기술 세부사항\n 일부 텍스트\n ///\n \n@@ -202,11 +202,6 @@ works(foo=\"bar\") # 이건 동작합니다 🎉\n * XWT\n * PSGI\n \n-### abbr가 설명을 제공 { #the-abbr-gives-an-explanation }\n-\n-* cluster\n-* [NAME_REDACTED]\n-\n ### abbr가 전체 문구와 설명을 제공 { #the-abbr-gives-a-full-phrase-and-an-explanation }\n \n * MDN\n@@ -224,6 +219,11 @@ works(foo=\"bar\") # 이건 동작합니다 🎉\n \n ////\n \n+## HTML \"dfn\" 요소 { #html-dfn-elements }\n+\n+* 클러스터\n+* 딥 러닝\n+\n ## 제목 { #headings }\n \n //// tab | 테스트" }, { "filename": "docs/pt/docs/_llm-test.md", "status": "modified", "additions": 9, "deletions": 9, "changes": 18, "patch": "@@ -197,15 +197,10 @@ Aqui estão algumas coisas envolvidas em elementos HTML \"abbr\" (algumas são inv\n \n ### O abbr fornece uma frase completa { #the-abbr-gives-a-full-phrase }\n \n-* GTD\n-* lt\n-* XWT\n-* PSGI\n-\n-### O abbr fornece uma explicação { #the-abbr-gives-an-explanation }\n-\n-* cluster\n-* [NAME_REDACTED]\n+* GTD\n+* lt\n+* XWT\n+* PSGI\n \n ### O abbr fornece uma frase completa e uma explicação { #the-abbr-gives-a-full-phrase-and-an-explanation }\n \n@@ -224,6 +219,11 @@ Veja a seção `### HTML abbr elements` no prompt geral em `scripts/translate.py\n \n ////\n \n+## Elementos HTML \"dfn\" { #html-dfn-elements }\n+\n+* cluster\n+* [NAME_REDACTED]\n+\n ## Títulos { #headings }\n \n //// tab | Teste" }, { "filename": "docs/ru/docs/_llm-test.md", "status": "modified", "additions": 5, "deletions": 5, "changes": 10, "patch": "@@ -202,11 +202,6 @@ works(foo=\"bar\") # Это работает 🎉\n * XWT\n * PSGI\n \n-### abbr даёт объяснение { #the-abbr-gives-an-explanation }\n-\n-* кластер\n-* Глубокое обучение\n-\n ### abbr даёт полную расшифровку и объяснение { #the-abbr-gives-a-full-phrase-and-an-explanation }\n \n * MDN\n@@ -224,6 +219,11 @@ works(foo=\"bar\") # Это работает 🎉\n \n ////\n \n+## HTML-элементы \"dfn\" { #html-dfn-elements }\n+\n+* кластер\n+* Глубокое обучение\n+\n ## Заголовки { #headings }\n \n //// tab | Тест" }, { "filename": "scripts/general-llm-prompt.md", "status": "modified", "additions": 24, "deletions": 40, "changes": 64, "patch": "@@ -353,7 +353,9 @@ Erstelle eine [[NAME_REDACTED]](../virtual-environments.md){.internal-link ta\n \n Translate HTML abbr elements (`text`) as follows:\n \n-- If the text surrounded by [NAME_REDACTED] an abbreviation (the text may be surrounded by [NAME_REDACTED] markup or quotes, for example text or `text` or \"text\", ignore that further markup when deciding if the text is an abbreviation), and if the description (the text inside the title attribute) contains the full phrase for this abbreviation, then append a dash (-) to the full phrase, followed by [NAME_REDACTED] full phrase.\n+- The text inside abbr tag may be surrounded by [NAME_REDACTED] markup or quotes, for example text or `text` or \"text\". Preserve markup and only translate visible text inside the abbr element.\n+\n+- If the description (the text inside the title attribute) contains the full phrase for this abbreviation, then append a dash (-) to the full phrase, followed by [NAME_REDACTED] full phrase.\n \n Conversion scheme:\n \n@@ -421,45 +423,7 @@ Result (German):\n ASGI\n ```\n \n-- If the description is not a full phrase for an abbreviation which the abbr element surrounds, but some other information, then just translate the description.\n-\n-Conversion scheme:\n-\n-Source (English):\n-\n-```\n-{text}\n-```\n-\n-Result:\n-\n-```\n-{translation of text}\n-```\n-\n-Examples:\n-\n- Source (English):\n-\n-```\n-path\n-linter\n-parsing\n-0.95.0\n-at the time of writing this\n-```\n-\n-Result (German):\n-\n-```\n-Pfad\n-Linter\n-Parsen\n-0.95.0\n-zum Zeitpunkt als das hier geschrieben wurde\n-```\n-\n-- If the text surrounded by [NAME_REDACTED] an abbreviation and the description contains both the full phrase for that abbreviation, and other information, separated by a colon (`:`), then append a dash (`-`) and the translation of the full phrase to the original full phrase and translate the other information.\n+- If the title of abbr element contains a full phrase for that abbreviation, and other information, separated by a colon (`:`), then append a dash (`-`) and the translation of the full phrase to the original full phrase and translate the other information.\n \n Conversion scheme:\n \n@@ -526,3 +490,23 @@ Result (German):\n - If there is an existing translation, and it has ADDITIONAL abbr elements in a sentence, and these additional abbr elements do not exist in the related sentence in the English text, then KEEP those additional abbr elements in the translation. Do not remove them. Except when you remove the whole sentence from the translation, because the whole sentence was removed from the English text, then also remove the abbr element. The reasoning for this rule is, that such additional abbr elements are manually added by [NAME_REDACTED] the translation, in order to translate or explain an English word to the human readers of the translation. These additional abbr elements would not make sense in the English text, but they do make sense in the translation. So keep them in the translation, even though they are not part of the English text. This rule only applies to abbr elements.\n \n - Apply above rules also when there is an existing translation! Make sure that all title attributes in abbr elements get properly translated or updated, using the schemes given above. However, leave the ADDITIONAL abbr's described above alone. Do not change their formatting or content.\n+\n+### HTML dfn elements\n+\n+For HTML dfn elements (`text`), translate the text inside the dfn element and the title attribute. Do not include the original English text in the title attribute.\n+\n+Examples:\n+\n+Source (English):\n+\n+```\n+path\n+linter\n+```\n+\n+Result (German):\n+\n+```\n+Pfad\n+Linter\n+```" } ], "reviews": [ { "id": 3778470827, "user": "user_2a237e38e06b", "state": "APPROVED", "body": "Nice, thank you! 🤖", "submitted_at": "2026-02-10T11:48:51+00:00" } ], "review_comments": [ { "id": 2787495672, "user": "user_2a237e38e06b", "body": "```suggestion\n- If the title of abbr element contains a full phrase for that abbreviation, and other information, separated by a colon (`:`), then append a dash (`-`) and the translation of the full phrase to the original full phrase and translate the other information.\n```", "path": "scripts/general-llm-prompt.md", "line": null, "side": "RIGHT", "created_at": "2026-02-10T11:48:18+00:00" } ], "meta": { "languages": [ "md" ], "touches_tests": false, "review_state_summary": { "APPROVED": 1 }, "meaningful_comment_count": 1, "has_approval": true, "has_changes_requested": false, "total_review_comments": 1 } } { "_id": "d7b86edf67eedc5d", "_schema_version": "1.0", "_cleaned_at": "2026-02-12T07:46:51.640384+00:00", "repo": "tiangolo/fastapi", "repo_url": "https://github.com/fastapi/fastapi", "license_name": "MIT License", "license_spdx": "MIT", "pr_number": 14739, "title": "🌐 Update translations for uk (update outdated, found by [NAME_REDACTED])", "body": "Running translation fixer tool shows several pages that contain mistakes. They were likely missed because of the overridden commit date.\nThis PR updates those outdated pages", "author": "user_29e85f9a8e75", "created_at": "2026-01-20T08:56:08+00:00", "merged_at": "2026-02-01T09:44:39+00:00", "base_branch": "master", "head_branch": "update-translations-uk", "additions": 166, "deletions": 160, "changed_files": 3, "files": [ { "filename": "docs/uk/docs/alternatives.md", "status": "modified", "additions": 41, "deletions": 39, "changes": 80, "patch": "@@ -1,8 +1,8 @@\n-# Альтернативи, натхнення та порівняння\n+# Альтернативи, натхнення та порівняння { #alternatives-inspiration-and-comparisons }\n \n-Що надихнуло на створення **FastAPI**, який він у порінянні з іншими альтернативами та чого він у них навчився.\n+Що надихнуло **FastAPI**, як він порівнюється з альтернативами та чого він у них навчився.\n \n-## Вступ\n+## Вступ { #intro }\n \n **FastAPI** не існувало б, якби не попередні роботи інших.\n \n@@ -12,17 +12,17 @@\n \n Але в якийсь момент не було іншого виходу, окрім створення чогось, що надавало б усі ці функції, взявши найкращі ідеї з попередніх інструментів і поєднавши їх найкращим чином, використовуючи мовні функції, які навіть не були доступні раніше (Python 3.6+ підказки типів).\n \n-## Попередні інструменти\n+## Попередні інструменти { #previous-tools }\n \n-### Django\n+### Django { #django }\n \n Це найпопулярніший фреймворк Python, який користується широкою довірою. Він використовується для створення таких систем, як Instagram.\n \n Він відносно тісно пов’язаний з реляційними базами даних (наприклад, MySQL або PostgreSQL), тому мати базу даних NoSQL (наприклад, Couchbase, MongoDB, Cassandra тощо) як основний механізм зберігання не дуже просто.\n \n-Він був створений для створення HTML у серверній частині, а не для створення API, які використовуються сучасним інтерфейсом (як-от React, Vue.js і Angular) або іншими системами (як-от IoT пристрої), які спілкуються з ним.\n+Він був створений для створення HTML у серверній частині, а не для створення API, які використовуються сучасним інтерфейсом (як-от React, Vue.js і Angular) або іншими системами (як-от IoT пристрої), які спілкуються з ним.\n \n-### Django REST Framework\n+### Django REST Framework { #django-rest-framework }\n \n Фреймворк Django REST був створений як гнучкий інструментарій для створення веб-інтерфейсів API використовуючи Django в основі, щоб покращити його можливості API.\n \n@@ -42,7 +42,7 @@ Django REST Framework створив Том Крісті. Той самий тв\n \n ///\n \n-### Flask\n+### Flask { #flask }\n \n Flask — це «мікрофреймворк», він не включає інтеграцію бази даних, а також багато речей, які за замовчуванням є в Django.\n \n@@ -64,7 +64,7 @@ Flask — це «мікрофреймворк», він не включає ін\n \n ///\n \n-### Requests\n+### Requests { #requests }\n \n **FastAPI** насправді не є альтернативою **Requests**. Сфера їх застосування дуже різна.\n \n@@ -88,25 +88,25 @@ Requests мають дуже простий та інтуїтивно зрозу\n response = requests.get(\"http://example.com/some/url\")\n ```\n \n-Відповідна операція *роуту* API FastAPI може виглядати так:\n+Відповідна операція шляху API FastAPI може виглядати так:\n \n ```Python hl_lines=\"1\"\n [USER_REDACTED].get(\"/some/url\")\n def read_url():\n- return {\"message\": \"[NAME_REDACTED]\"}\n+ return {\"message\": \"[NAME_REDACTED]\"}\n ```\n \n Зверніть увагу на схожість у `requests.get(...)` і `[USER_REDACTED].get(...)`.\n \n /// check | Надихнуло **FastAPI** на\n \n * Майте простий та інтуїтивно зрозумілий API.\n- * Використовуйте імена (операції) методів HTTP безпосередньо, простим та інтуїтивно зрозумілим способом.\n- * Розумні параметри за замовчуванням, але потужні налаштування.\n+* Використовуйте імена (операції) методів HTTP безпосередньо, простим та інтуїтивно зрозумілим способом.\n+* Розумні параметри за замовчуванням, але потужні налаштування.\n \n ///\n \n-### Swagger / OpenAPI\n+### Swagger / OpenAPI { #swagger-openapi }\n \n Головною функцією, яку я хотів від Django REST Framework, була автоматична API документація.\n \n@@ -124,18 +124,18 @@ def read_url():\n \n Інтегрувати інструменти інтерфейсу на основі стандартів:\n \n- * Інтерфейс Swagger\n- * ReDoc\n+* Інтерфейс Swagger\n+* ReDoc\n \n Ці два було обрано через те, що вони досить популярні та стабільні, але, виконавши швидкий пошук, ви можете знайти десятки додаткових альтернативних інтерфейсів для OpenAPI (які можна використовувати з **FastAPI**).\n \n ///\n \n-### Фреймворки REST для Flask\n+### Фреймворки REST для Flask { #flask-rest-frameworks }\n \n Існує кілька фреймворків Flask REST, але, витративши час і роботу на їх дослідження, я виявив, що багато з них припинено або залишено, з кількома постійними проблемами, які зробили їх непридатними.\n \n-### Marshmallow\n+### Marshmallow { #marshmallow }\n \n Однією з головних функцій, необхідних для систем API, є \"серіалізація\", яка бере дані з коду (Python) і перетворює їх на щось, що можна надіслати через мережу. Наприклад, перетворення об’єкта, що містить дані з бази даних, на об’єкт JSON. Перетворення об’єктів `datetime` на строки тощо.\n \n@@ -153,7 +153,7 @@ Marshmallow створено для забезпечення цих функці\n \n ///\n \n-### Webargs\n+### Webargs { #webargs }\n \n Іншою важливою функцією, необхідною для API, є аналіз даних із вхідних запитів.\n \n@@ -175,7 +175,7 @@ Webargs був створений тими ж розробниками Marshmall\n \n ///\n \n-### APISpec\n+### APISpec { #apispec }\n \n Marshmallow і Webargs забезпечують перевірку, аналіз і серіалізацію як плагіни.\n \n@@ -205,7 +205,7 @@ APISpec був створений тими ж розробниками Marshmall\n \n ///\n \n-### Flask-apispec\n+### Flask-apispec { #flask-apispec }\n \n Це плагін Flask, який об’єднує Webargs, Marshmallow і APISpec.\n \n@@ -237,13 +237,13 @@ Flask-apispec був створений тими ж розробниками Mar\n \n ///\n \n-### NestJS (та Angular)\n+### NestJS (та Angular) { #nestjs-and-angular }\n \n Це навіть не Python, NestJS — це фреймворк [NAME_REDACTED] (TypeScript), натхненний Angular.\n \n Це досягає чогось подібного до того, що можна зробити з Flask-apispec.\n \n-Він має інтегровану систему впровадження залежностей, натхненну Angular two. Він потребує попередньої реєстрації «injectables» (як і всі інші системи впровадження залежностей, які я знаю), тому це збільшує багатослівність та повторення коду.\n+Він має інтегровану систему впровадження залежностей, натхненну Angular 2. Він потребує попередньої реєстрації «injectables» (як і всі інші системи впровадження залежностей, які я знаю), тому це збільшує багатослівність та повторення коду.\n \n Оскільки параметри описані за допомогою типів TypeScript (подібно до підказок типу Python), підтримка редактора досить хороша.\n \n@@ -259,7 +259,7 @@ Flask-apispec був створений тими ж розробниками Mar\n \n ///\n \n-### Sanic\n+### Sanic { #sanic }\n \n Це був один із перших надзвичайно швидких фреймворків Python на основі `asyncio`. Він був дуже схожий на Flask.\n \n@@ -279,7 +279,7 @@ Flask-apispec був створений тими ж розробниками Mar\n \n ///\n \n-### Falcon\n+### Falcon { #falcon }\n \n Falcon — ще один високопродуктивний фреймворк Python, він розроблений як мінімальний і працює як основа інших фреймворків, таких як Hug.\n \n@@ -297,7 +297,7 @@ Falcon — ще один високопродуктивний фреймворк\n \n ///\n \n-### Molten\n+### Molten { #molten }\n \n Я відкрив для себе Molten на перших етапах створення **FastAPI**. І він має досить схожі ідеї:\n \n@@ -321,7 +321,7 @@ Falcon — ще один високопродуктивний фреймворк\n \n ///\n \n-### Hug\n+### Hug { #hug }\n \n Hug був одним із перших фреймворків, який реалізував оголошення типів параметрів API за допомогою підказок типу Python. Це була чудова ідея, яка надихнула інші інструменти зробити те саме.\n \n@@ -351,7 +351,7 @@ Hug надихнув частину APIStar і був одним із найбі\n \n ///\n \n-### APIStar (<= 0,5)\n+### APIStar (<= 0,5) { #apistar-0-5 }\n \n Безпосередньо перед тим, як вирішити створити **FastAPI**, я знайшов сервер **APIStar**. Він мав майже все, що я шукав, і мав чудовий дизайн.\n \n@@ -379,9 +379,9 @@ Hug надихнув частину APIStar і був одним із найбі\n \n APIStar створив Том Крісті. Той самий хлопець, який створив:\n \n- * Django REST Framework\n- * Starlette (на якому базується **FastAPI**)\n- * Uvicorn (використовується Starlette і **FastAPI**)\n+* Django REST Framework\n+* Starlette (на якому базується **FastAPI**)\n+* Uvicorn (використовується Starlette і **FastAPI**)\n \n ///\n \n@@ -393,13 +393,15 @@ APIStar створив Том Крісті. Той самий хлопець, я\n \n І після тривалого пошуку подібної структури та тестування багатьох різних альтернатив, APIStar став найкращим доступним варіантом.\n \n- Потім APIStar перестав існувати як сервер, і було створено Starlette, який став новою кращою основою для такої системи. Це стало останнім джерелом натхнення для створення **FastAPI**. Я вважаю **FastAPI** «духовним спадкоємцем» APIStar, удосконалюючи та розширюючи функції, систему введення тексту та інші частини на основі досвіду, отриманого від усіх цих попередніх інструментів.\n+ Потім APIStar перестав існувати як сервер, і було створено Starlette, який став новою кращою основою для такої системи. Це стало останнім джерелом натхнення для створення **FastAPI**.\n+\n+ Я вважаю **FastAPI** «духовним спадкоємцем» APIStar, удосконалюючи та розширюючи функції, систему типізації та інші частини на основі досвіду, отриманого від усіх цих попередніх інструментів.\n \n ///\n \n-## Використовується **FastAPI**\n+## Використовується **FastAPI** { #used-by-fastapi }\n \n-### Pydantic\n+### Pydantic { #pydantic }\n \n Pydantic — це бібліотека для визначення перевірки даних, серіалізації та документації (за допомогою схеми JSON) на основі підказок типу Python.\n \n@@ -415,9 +417,9 @@ Pydantic — це бібліотека для визначення переві\n \n ///\n \n-### Starlette\n+### Starlette { #starlette }\n \n-Starlette — це легкий фреймворк/набір інструментів ASGI, який ідеально підходить для створення високопродуктивних asyncio сервісів.\n+Starlette — це легкий фреймворк/набір інструментів ASGI, який ідеально підходить для створення високопродуктивних asyncio сервісів.\n \n Він дуже простий та інтуїтивно зрозумілий. Його розроблено таким чином, щоб його можна було легко розширювати та мати модульні компоненти.\n \n@@ -460,7 +462,7 @@ ASGI — це новий «стандарт», який розробляєтьс\n \n ///\n \n-### Uvicorn\n+### Uvicorn { #uvicorn }\n \n Uvicorn — це блискавичний сервер ASGI, побудований на uvloop і httptools.\n \n@@ -472,12 +474,12 @@ Uvicorn — це блискавичний сервер ASGI, побудован\n \n Основний веб-сервер для запуску програм **FastAPI**.\n \n- Ви можете поєднати його з Gunicorn, щоб мати асинхронний багатопроцесний сервер.\n+ Ви також можете використати параметр командного рядка `--workers`, щоб мати асинхронний багатопроцесний сервер.\n \n Додаткову інформацію див. у розділі [Розгортання](deployment/index.md){.internal-link target=_blank}.\n \n ///\n \n-## Орієнтири та швидкість\n+## Орієнтири та швидкість { #benchmarks-and-speed }\n \n Щоб зрозуміти, порівняти та побачити різницю між Uvicorn, Starlette і FastAPI, перегляньте розділ про [Бенчмарки](benchmarks.md){.internal-link target=_blank}." }, { "filename": "docs/uk/docs/fastapi-cli.md", "status": "modified", "additions": 50, "deletions": 58, "changes": 108, "patch": "@@ -1,83 +1,75 @@\n-# FastAPI CLI\n+# FastAPI CLI { #fastapi-cli }\n \n-**FastAPI CLI** це програма командного рядка, яку Ви можете використовувати, щоб обслуговувати Ваш додаток FastAPI, керувати Вашими FastApi проектами, тощо.\n+**FastAPI CLI** — це програма командного рядка, яку ви можете використовувати, щоб обслуговувати ваш застосунок FastAPI, керувати вашим проєктом FastAPI тощо.\n \n-Коли Ви встановлюєте FastApi (тобто виконуєте `pip install \"fastapi[standard]\"`), Ви також встановлюєте пакунок `fastapi-cli`, цей пакунок надає команду `fastapi` в терміналі.\n+Коли ви встановлюєте FastAPI (наприклад, за допомогою `pip install \"fastapi[standard]\"`), він включає пакет під назвою `fastapi-cli`, цей пакет надає команду `fastapi` у терміналі.\n \n-Для запуску Вашого FastAPI проекту для розробки, Ви можете скористатись командою `fastapi dev`:\n+Щоб запустити ваш застосунок FastAPI для розробки, ви можете використати команду `fastapi dev`:\n \n

      \n \n ```console\n-$ fastapi dev main.py\n-INFO Using path main.py\n-INFO Resolved absolute path /home/user/code/awesomeapp/main.py\n-INFO Searching for package file structure from directories with __init__.py files\n-INFO Importing from /home/user/code/awesomeapp\n-\n- ╭─ Python module file ─╮\n- │ │\n- │ 🐍 main.py │\n- │ │\n- ╰──────────────────────╯\n-\n-INFO Importing module main\n-INFO Found importable FastAPI app\n-\n- ╭─ [NAME_REDACTED] app ─╮\n- │ │\n- │ from main import app │\n- │ │\n- ╰──────────────────────────╯\n-\n-INFO Using import string main:app\n-\n- ╭────────── FastAPI CLI - Development mode ───────────╮\n- │ │\n- │ Serving at: http://127.0.0.1:8000 │\n- │ │\n- │ API docs: http://127.0.0.1:8000/docs │\n- │ │\n- │ Running in development mode, for production use: │\n- │ │\n- fastapi run\n- │ │\n- ╰─────────────────────────────────────────────────────╯\n-\n-INFO: Will watch for changes in these directories: ['/home/user/code/awesomeapp']\n-INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit)\n-INFO: Started reloader process [2265862] using WatchFiles\n-INFO: Started server process [2265873]\n-INFO: Waiting for application startup.\n-INFO: Application startup complete.\n+$ fastapi dev main.py\n+\n+ FastAPI Starting development server 🚀\n+\n+ Searching for package file structure from directories with\n+ __init__.py files\n+ Importing from /home/user/code/awesomeapp\n+\n+ module 🐍 main.py\n+\n+ code Importing the FastAPI app object from the module with the\n+ following code:\n+\n+ from main import app\n+\n+ app Using import string: main:app\n+\n+ server Server started at http://127.0.0.1:8000\n+ server Documentation at http://127.0.0.1:8000/docs\n+\n+ tip Running in development mode, for production use:\n+ fastapi run\n+\n+ Logs:\n+\n+ INFO Will watch for changes in these directories:\n+ ['/home/user/code/awesomeapp']\n+ INFO Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to\n+ quit)\n+ INFO Started reloader process [383138] using WatchFiles\n+ INFO Started server process [383153]\n+ INFO Waiting for application startup.\n+ INFO Application startup complete.\n ```\n \n
      \n \n-Програма командного рядка `fastapi` це **FastAPI CLI**.\n+Програма командного рядка під назвою `fastapi` — це **FastAPI CLI**.\n \n-FastAPI CLI приймає шлях до Вашої Python програми (напр. `main.py`) і автоматично виявляє екземпляр `FastAPI` (зазвичай названий `app`), обирає коректний процес імпорту, а потім обслуговує його.\n+FastAPI CLI бере шлях до вашої Python-програми (наприклад, `main.py`) і автоматично виявляє екземпляр `FastAPI` (зазвичай з назвою `app`), визначає правильний процес імпорту, а потім обслуговує його.\n \n-Натомість, для запуску у продакшн використовуйте `fastapi run`. 🚀\n+Натомість, для продакшн ви використали б `fastapi run`. 🚀\n \n-Всередині **FastAPI CLI** використовує Uvicorn, високопродуктивний, production-ready, ASGI cервер. 😎\n+Внутрішньо **FastAPI CLI** використовує Uvicorn, високопродуктивний, production-ready, ASGI сервер. 😎\n \n-## `fastapi dev`\n+## `fastapi dev` { #fastapi-dev }\n \n-Використання `fastapi dev` ініціює режим розробки.\n+Запуск `fastapi dev` ініціює режим розробки.\n \n-За замовчуванням, **автоматичне перезавантаження** увімкнене, автоматично перезавантажуючи сервер кожного разу, коли Ви змінюєте Ваш код. Це ресурсо-затратно, та може бути менш стабільним, ніж коли воно вимкнене. Ви повинні використовувати його тільки під час розробки. Воно також слухає IP-адресу `127.0.0.1`, що є IP Вашого девайсу для самостійної комунікації з самим собою (`localhost`).\n+За замовчуванням **auto-reload** увімкнено, і сервер автоматично перезавантажується, коли ви вносите зміни у ваш код. Це ресурсоємно та може бути менш стабільним, ніж коли його вимкнено. Вам слід використовувати це лише для розробки. Також він слухає IP-адресу `127.0.0.1`, яка є IP-адресою для того, щоб ваша машина могла взаємодіяти лише сама з собою (`localhost`).\n \n-## `fastapi run`\n+## `fastapi run` { #fastapi-run }\n \n-Виконання `fastapi run` запустить FastAPI у продакшн-режимі за замовчуванням.\n+Виконання `fastapi run` за замовчуванням запускає FastAPI у продакшн-режимі.\n \n-За замовчуванням, **автоматичне перезавантаження** вимкнене. Воно також прослуховує IP-адресу `0.0.0.0`, що означає всі доступні IP адреси, тим самим даючи змогу будь-кому комунікувати з девайсом. Так Ви зазвичай будете запускати його у продакшн, наприклад у контейнері.\n+За замовчуванням **auto-reload** вимкнено. Також він слухає IP-адресу `0.0.0.0`, що означає всі доступні IP-адреси, таким чином він буде публічно доступним для будь-кого, хто може взаємодіяти з машиною. Зазвичай саме так ви запускатимете його в продакшн, наприклад у контейнері.\n \n-В більшості випадків Ви можете (і маєте) мати \"termination proxy\", який обробляє HTTPS для Вас, це залежить від способу розгортання вашого додатку, Ваш провайдер може зробити це для Вас, або Вам потрібно налаштувати його самостійно.\n+У більшості випадків ви (і вам слід) матимете «termination proxy», який обробляє HTTPS для вас зверху; це залежатиме від того, як ви розгортаєте ваш застосунок: ваш провайдер може зробити це за вас, або вам може знадобитися налаштувати це самостійно.\n \n-/// tip\n+/// tip | Порада\n \n-Ви можете дізнатись більше про це у [документації про розгортування](deployment/index.md){.internal-link target=_blank}.\n+Ви можете дізнатися більше про це в [документації з розгортання](deployment/index.md){.internal-link target=_blank}.\n \n ///" }, { "filename": "docs/uk/docs/features.md", "status": "modified", "additions": 75, "deletions": 63, "changes": 138, "patch": "@@ -1,53 +1,55 @@\n-# Функціональні можливості\n+# Функціональні можливості { #features }\n \n-## Функціональні можливості FastAPI\n+## Функціональні можливості FastAPI { #fastapi-features }\n \n **FastAPI** надає вам такі можливості:\n \n-### Використання відкритих стандартів\n+### На основі відкритих стандартів { #based-on-open-standards }\n \n * OpenAPI для створення API, включаючи оголошення шляхів, операцій, параметрів, тіл запитів, безпеки тощо.\n * Автоматична документація моделей даних за допомогою JSON Schema (оскільки OpenAPI базується саме на JSON Schema).\n * Розроблено на основі цих стандартів після ретельного аналізу, а не як додатковий рівень поверх основної архітектури.\n-* Це також дає змогу автоматично **генерувати код клієнта** багатьма мовами.\n+* Це також дає змогу використовувати автоматичну **генерацію клієнтського коду** багатьма мовами.\n \n-### Автоматична генерація документації\n+### Автоматична документація { #automatic-docs }\n \n-Інтерактивна документація API та вебінтерфейс для його дослідження. Оскільки фреймворк базується на OpenAPI, є кілька варіантів, два з яких включені за замовчуванням.\n+Інтерактивна документація API та вебінтерфейси для його дослідження. Оскільки фреймворк базується на OpenAPI, є кілька варіантів, 2 з яких включені за замовчуванням.\n \n-* Swagger UI — дозволяє інтерактивно переглядати API, викликати та тестувати його прямо у браузері.\n+* Swagger UI — з інтерактивним дослідженням, викликом і тестуванням вашого API прямо з браузера.\n \n ![Swagger UI interaction](https://fastapi.tiangolo.com/img/index/index-03-swagger-02.png)\n \n * Альтернативна документація API за допомогою ReDoc.\n \n ![ReDoc](https://fastapi.tiangolo.com/img/index/index-06-redoc-02.png)\n \n-### Тільки сучасний Python\n+### Лише сучасний Python { #just-modern-python }\n \n-FastAPI використовує стандартні **типи Python** (завдяки Pydantic). Вам не потрібно вивчати новий синтаксис — лише стандартний сучасний Python.\n+Усе базується на стандартних оголошеннях **типів Python** (завдяки Pydantic). Жодного нового синтаксису для вивчення. Лише стандартний сучасний Python.\n \n-Якщо вам потрібне коротке нагадування про використання типів у Python (навіть якщо ви не використовуєте FastAPI), перегляньте короткий підручник: [Вступ до типів Python](python-types.md){.internal-link target=_blank}.\n+Якщо вам потрібно 2-хвилинне нагадування про те, як використовувати типи Python (навіть якщо ви не використовуєте FastAPI), перегляньте короткий підручник: [Типи Python](python-types.md){.internal-link target=_blank}.\n \n-Ось приклад стандартного Python-коду з типами:\n+Ви пишете стандартний Python з типами:\n \n ```Python\n from datetime import date\n+\n from pydantic import BaseModel\n \n-# Оголошення змінної як str\n-# з підтримкою автодоповнення у редакторі\n+# Оголосіть змінну як str\n+# та отримайте підтримку редактора всередині функції\n def main(user_id: str):\n return user_id\n \n+\n # Модель Pydantic\n class User(BaseModel):\n id: int\n name: str\n joined: date\n ```\n \n-Приклад використання цієї моделі:\n+Далі це можна використовувати так:\n \n ```Python\n my_user: User = User(id=3, name=\"[NAME_REDACTED]\", joined=\"2018-07-19\")\n@@ -65,19 +67,21 @@ my_second_user: User = User(**second_user_data)\n \n `**second_user_data` означає:\n \n-Передати ключі та значення словника `second_user_data` як аргументи у вигляді \"ключ-значення\", еквівалентно `User(id=4, name=\"Mary\", joined=\"2018-11-30\")`.\n+Передати ключі та значення словника `second_user_data` безпосередньо як аргументи у вигляді «ключ-значення», еквівалентно: `User(id=4, name=\"Mary\", joined=\"2018-11-30\")`\n \n ///\n \n-### Підтримка редакторів (IDE)\n+### Підтримка редакторів (IDE) { #editor-support }\n \n-Фреймворк спроєктований так, щоб бути легким і інтуїтивно зрозумілим. Усі рішення тестувалися у різних редакторах ще до початку розробки, щоб забезпечити найкращий досвід програмування.\n+Увесь фреймворк спроєктовано так, щоб ним було легко та інтуїтивно користуватися; усі рішення тестувалися у кількох редакторах ще до початку розробки, щоб забезпечити найкращий досвід розробки.\n \n-За результатами опитувань розробників Python однією з найпопулярніших функцій є \"автодоповнення\".\n+З опитувань розробників Python зрозуміло що однією з найуживаніших функцій є «автодоповнення».\n \n-**FastAPI** повністю підтримує автодоповнення у всіх місцях, тому вам рідко доведеться повертатися до документації.\n+Увесь фреймворк **FastAPI** побудований так, щоб це забезпечити. Автодоповнення працює всюди.\n \n-Приклад автодоповнення у редакторах:\n+Вам рідко доведеться повертатися до документації.\n+\n+Ось як ваш редактор може вам допомогти:\n \n * у [NAME_REDACTED]:\n \n@@ -87,73 +91,81 @@ my_second_user: User = User(**second_user_data)\n \n ![editor support](https://fastapi.tiangolo.com/img/pycharm-completion.png)\n \n-### Короткий код\n-FastAPI має розумні налаштування **за замовчуванням**, але всі параметри можна налаштовувати відповідно до ваших потреб. Однак за замовчуванням все \"просто працює\".\n+Ви отримаєте автодоповнення в коді, який раніше могли вважати навіть неможливим. Наприклад, для ключа `price` всередині JSON body (який міг бути вкладеним), що надходить із запиту.\n+\n+Більше не доведеться вводити неправильні назви ключів, постійно повертатися до документації або прокручувати вгору-вниз, щоб знайти, чи ви зрештою використали `username` чи `user_name`.\n+\n+### Короткий код { #short }\n+\n+FastAPI має розумні **налаштування за замовчуванням** для всього, з можливістю конфігурації всюди. Усі параметри можна точно налаштувати під ваші потреби та визначити потрібний вам API.\n+\n+Але за замовчуванням усе **«просто працює»**.\n+\n+### Валідація { #validation }\n \n-### Валідація\n * Підтримка валідації для більшості (або всіх?) **типів даних Python**, зокрема:\n * JSON-об'єктів (`dict`).\n- * JSON-списків (`list`) з визначенням типів елементів.\n- * Рядків (`str`) із мінімальною та максимальною довжиною.\n- * Чисел (`int`, `float`) з обмеженнями мінімальних та максимальних значень тощо.\n+ * JSON-масивів (`list`) із визначенням типів елементів.\n+ * Полів-рядків (`str`) із визначенням мінімальної та максимальної довжини.\n+ * Чисел (`int`, `float`) з мінімальними та максимальними значеннями тощо.\n \n-* Валідація складніших типів, таких як:\n+* Валідація для більш екзотичних типів, як-от:\n * URL.\n * Email.\n * UUID.\n * ...та інші.\n \n Уся валідація виконується через надійний та перевірений **Pydantic**.\n \n-### Безпека та автентифікація\n+### Безпека та автентифікація { #security-and-authentication }\n \n-**FastAPI** підтримує вбудовану автентифікацію та авторизацію, без прив’язки до конкретних баз даних чи моделей даних.\n+Інтегровані безпека та автентифікація. Без жодних компромісів із базами даних чи моделями даних.\n \n-Підтримуються всі схеми безпеки OpenAPI, включаючи:\n+Підтримуються всі схеми безпеки, визначені в OpenAPI, включно з:\n \n * HTTP Basic.\n-* **OAuth2** (також із підтримкою **JWT-токенів**). Див. підручник: [OAuth2 із JWT](tutorial/security/oauth2-jwt.md){.internal-link target=_blank}.\n+* **OAuth2** (також із підтримкою **JWT tokens**). Перегляньте підручник: [OAuth2 із JWT](tutorial/security/oauth2-jwt.md){.internal-link target=_blank}.\n * Ключі API в:\n * Заголовках.\n * Параметрах запиту.\n * Cookies тощо.\n \n-А також усі можливості безпеки від Starlette (зокрема **сесійні cookies**).\n+А також усі можливості безпеки від Starlette (зокрема **session cookies**).\n \n-Усі вони створені як багаторазові інструменти та компоненти, які легко інтегруються з вашими системами, сховищами даних, реляційними та NoSQL базами даних тощо.\n+Усе це зроблено як багаторазові інструменти та компоненти, які легко інтегруються з вашими системами, сховищами даних, реляційними та NoSQL базами даних тощо.\n \n-### Впровадження залежностей\n+### Впровадження залежностей { #dependency-injection }\n \n-**FastAPI** містить надзвичайно просту у використанні, але потужну систему впровадження залежностей.\n+FastAPI містить надзвичайно просту у використанні, але надзвичайно потужну систему [NAME_REDACTED].\n \n-* Залежності можуть мати власні залежності, утворюючи ієрархію або **\"граф залежностей\"**.\n-* Усі залежності автоматично керуються фреймворком.\n-* Усі залежності можуть отримувати дані з запитів і розширювати **обмеження операції за шляхом** та автоматичну документацію.\n-* **Автоматична валідація** навіть для параметрів *операцій шляху*, визначених у залежностях.\n-* Підтримка складних систем автентифікації користувачів, **з'єднань із базами даних** тощо.\n-* **Жодних обмежень** щодо використання баз даних, фронтендів тощо, але водночас проста інтеграція з усіма ними.\n+* Навіть залежності можуть мати власні залежності, утворюючи ієрархію або **«граф» залежностей**.\n+* Усе **автоматично обробляється** фреймворком.\n+* Усі залежності можуть вимагати дані із запитів і **розширювати обмеження операції шляху** та автоматичну документацію.\n+* **Автоматична валідація** навіть для параметрів *операції шляху*, визначених у залежностях.\n+* Підтримка складних систем автентифікації користувачів, **підключень до баз даних** тощо.\n+* **Жодних компромісів** із базами даних, фронтендами тощо. Але проста інтеграція з усіма ними.\n \n-### Немає обмежень на \"плагіни\"\n+### Необмежені «плагіни» { #unlimited-plug-ins }\n \n-Або іншими словами, вони не потрібні – просто імпортуйте та використовуйте необхідний код.\n+Інакше кажучи, вони не потрібні — імпортуйте та використовуйте код, який вам потрібен.\n \n-Будь-яка інтеграція спроєктована настільки просто (з використанням залежностей), що ви можете створити \"плагін\" для свого застосунку всього у 2 рядках коду, використовуючи ту саму структуру та синтаксис, що й для ваших *операцій шляху*.\n+Будь-яка інтеграція спроєктована так, щоб її було дуже просто використовувати (із залежностями), тож ви можете створити «плагін» для свого застосунку у 2 рядках коду, використовуючи ту саму структуру та синтаксис, що й для ваших *операцій шляху*.\n \n-### Протестовано\n+### Протестовано { #tested }\n \n * 100% покриття тестами.\n * 100% анотована типами кодова база.\n-* Використовується у робочих середовищах.\n+* Використовується в production-застосунках.\n \n-## Можливості Starlette\n+## Можливості Starlette { #starlette-features }\n \n **FastAPI** повністю сумісний із (та побудований на основі) Starlette. Тому будь-який додатковий код Starlette, який ви маєте, також працюватиме.\n \n-**FastAPI** фактично є підкласом **Starlette**. Тому, якщо ви вже знайомі зі Starlette або використовуєте його, більшість функціональності працюватиме так само.\n+`FastAPI` фактично є підкласом `Starlette`. Тому, якщо ви вже знайомі зі Starlette або використовуєте його, більшість функціональності працюватиме так само.\n \n-З **FastAPI** ви отримуєте всі можливості **Starlette** (адже FastAPI — це, по суті, Starlette на стероїдах):\n+З **FastAPI** ви отримуєте всі можливості **Starlette** (адже FastAPI — це просто Starlette на стероїдах):\n \n-* Разюча продуктивність. Це один із найшвидших фреймворків на Python, на рівні з **NodeJS** і **Go**.\n+* Разюча продуктивність. Це один із найшвидших доступних Python-фреймворків, на рівні з **NodeJS** і **Go**.\n * Підтримка **WebSocket**.\n * Фонові задачі у процесі.\n * Події запуску та завершення роботи.\n@@ -163,27 +175,27 @@ FastAPI має розумні налаштування **за замовчува\n * 100% покриття тестами.\n * 100% анотована типами кодова база.\n \n-## Можливості Pydantic\n+## Можливості Pydantic { #pydantic-features }\n \n **FastAPI** повністю сумісний із (та побудований на основі) Pydantic. Тому будь-який додатковий код Pydantic, який ви маєте, також працюватиме.\n \n-Включаючи зовнішні бібліотеки, побудовані також на Pydantic, такі як ORM, ODM для баз даних.\n+Включно із зовнішніми бібліотеками, які також базуються на Pydantic, як-от ORM-и, ODM-и для баз даних.\n \n-Це також означає, що в багатьох випадках ви можете передати той самий об'єкт, який отримуєте з запиту, **безпосередньо в базу даних**, оскільки все автоматично перевіряється.\n+Це також означає, що в багатьох випадках ви можете передати той самий об'єкт, який отримуєте із запиту, **безпосередньо в базу даних**, оскільки все автоматично перевіряється.\n \n-Те ж саме відбувається й у зворотному напрямку — у багатьох випадках ви можете просто передати об'єкт, який отримуєте з бази даних, **безпосередньо клієнту**.\n+Те саме застосовується й у зворотному напрямку — у багатьох випадках ви можете просто передати об'єкт, який отримуєте з бази даних, **безпосередньо клієнту**.\n \n З **FastAPI** ви отримуєте всі можливості **Pydantic** (адже FastAPI базується на Pydantic для обробки всіх даних):\n \n-* **Ніякої плутанини** :\n- * Не потрібно вчити нову мову для визначення схем.\n+* **Ніякої плутанини**:\n+ * Не потрібно вчити нову мікромову для визначення схем.\n * Якщо ви знаєте типи Python, ви знаєте, як використовувати Pydantic.\n-* Легко працює з вашим **IDE/лінтером/мозком**:\n- * Оскільки структури даних Pydantic є просто екземплярами класів, які ви визначаєте; автодоповнення, лінтинг, mypy і ваша інтуїція повинні добре працювати з вашими перевіреними даними.\n-* Валідація **складних структур**:\n- * Використання ієрархічних моделей Pydantic. Python `typing`, `List` і `Dict` тощо.\n- * Валідатори дозволяють чітко і просто визначати, перевіряти й документувати складні схеми даних у вигляді JSON-схеми.\n- * Ви можете мати глибоко **вкладені JSON об'єкти** та перевірити та анотувати їх всі.\n+* Легко працює з вашим **IDE/linter/мозком**:\n+ * Оскільки структури даних pydantic є просто екземплярами класів, які ви визначаєте; автодоповнення, лінтинг, mypy і ваша інтуїція повинні добре працювати з вашими перевіреними даними.\n+* Валідує **складні структури**:\n+ * Використання ієрархічних моделей Pydantic, Python `typing`’s `List` і `Dict` тощо.\n+ * Валідатори дають змогу складні схеми даних чітко й просто визначати, перевіряти й документувати як JSON Schema.\n+ * Ви можете мати глибоко **вкладені JSON** об'єкти, і всі вони будуть валідовані та анотовані.\n * **Розширюваність**:\n- * Pydantic дозволяє визначати користувацькі типи даних або розширювати валідацію методами в моделі декоратором `validator`.\n+ * Pydantic дозволяє визначати користувацькі типи даних або ви можете розширити валідацію методами в моделі, позначеними декоратором validator.\n * 100% покриття тестами." } ], "reviews": [ { "id": 3710966594, "user": "user_29e85f9a8e75", "state": "COMMENTED", "body": "Some suggestions to revert obviously wrong changes made by LLM", "submitted_at": "2026-01-27T13:40:37+00:00" }, { "id": 3735367912, "user": "user_2a237e38e06b", "state": "APPROVED", "body": "Thank you! 🎉", "submitted_at": "2026-02-01T09:44:27+00:00" } ], "review_comments": [ { "id": 2731829924, "user": "user_29e85f9a8e75", "body": "```suggestion\n/// check | Надихнуло **FastAPI** на\n```", "path": "docs/uk/docs/alternatives.md", "line": null, "side": "RIGHT", "created_at": "2026-01-27T12:41:50+00:00" }, { "id": 2731835076, "user": "user_29e85f9a8e75", "body": "```suggestion\n/// check | Надихнуло **FastAPI** на\n```", "path": "docs/uk/docs/alternatives.md", "line": null, "side": "RIGHT", "created_at": "2026-01-27T12:43:09+00:00" }, { "id": 2731837213, "user": "user_29e85f9a8e75", "body": "```suggestion\n/// check | Надихнуло **FastAPI** на\n```", "path": "docs/uk/docs/alternatives.md", "line": null, "side": "RIGHT", "created_at": "2026-01-27T12:43:41+00:00" }, { "id": 2731842354, "user": "user_29e85f9a8e75", "body": "```suggestion\nОднією з головних функцій, необхідних для систем API, є \"серіалізація\", яка бере дані з коду (Python) і перетворює їх на щось, що можна надіслати через мережу. Наприклад, перетворення об’єкта, що містить дані з бази даних, на об’єкт JSON. Перетворення об’єктів `datetime` на строки тощо.\n```", "path": "docs/uk/docs/alternatives.md", "line": null, "side": "RIGHT", "created_at": "2026-01-27T12:44:52+00:00" }, { "id": 2731846928, "user": "user_29e85f9a8e75", "body": "```suggestion\nАле він був створений до того, як існували підказки типу Python. Отже, щоб визначити кожну схему, вам потрібно використовувати спеціальні утиліти та класи, надані Marshmallow.\n```", "path": "docs/uk/docs/alternatives.md", "line": null, "side": "RIGHT", "created_at": "2026-01-27T12:45:58+00:00" }, { "id": 2731848621, "user": "user_29e85f9a8e75", "body": "```suggestion\n/// check | Надихнуло **FastAPI** на\n```", "path": "docs/uk/docs/alternatives.md", "line": null, "side": "RIGHT", "created_at": "2026-01-27T12:46:22+00:00" }, { "id": 2732019562, "user": "user_29e85f9a8e75", "body": "```suggestion\n/// check | Надихнуло **FastAPI** на\n```", "path": "docs/uk/docs/alternatives.md", "line": null, "side": "RIGHT", "created_at": "2026-01-27T13:28:49+00:00" }, { "id": 2732025583, "user": "user_29e85f9a8e75", "body": "```suggestion\nІншою важливою функцією, необхідною для API, є аналіз даних із вхідних запитів.\n```", "path": "docs/uk/docs/alternatives.md", "line": null, "side": "RIGHT", "created_at": "2026-01-27T13:30:11+00:00" }, { "id": 2732027903, "user": "user_29e85f9a8e75", "body": "```suggestion\n/// check | Надихнуло **FastAPI** на\n```", "path": "docs/uk/docs/alternatives.md", "line": null, "side": "RIGHT", "created_at": "2026-01-27T13:30:44+00:00" }, { "id": 2732029068, "user": "user_29e85f9a8e75", "body": "```suggestion\n/// check | Надихнуло **FastAPI** на\n```", "path": "docs/uk/docs/alternatives.md", "line": null, "side": "RIGHT", "created_at": "2026-01-27T13:30:59+00:00" }, { "id": 2732030181, "user": "user_29e85f9a8e75", "body": "```suggestion\n/// check | Надихнуло **FastAPI** на\n```", "path": "docs/uk/docs/alternatives.md", "line": null, "side": "RIGHT", "created_at": "2026-01-27T13:31:14+00:00" }, { "id": 2732032028, "user": "user_29e85f9a8e75", "body": "```suggestion\n/// check | Надихнуло **FastAPI** на\n```", "path": "docs/uk/docs/alternatives.md", "line": null, "side": "RIGHT", "created_at": "2026-01-27T13:31:37+00:00" }, { "id": 2732033298, "user": "user_29e85f9a8e75", "body": "```suggestion\n/// check | Надихнуло **FastAPI** на\n```", "path": "docs/uk/docs/alternatives.md", "line": null, "side": "RIGHT", "created_at": "2026-01-27T13:31:53+00:00" }, { "id": 2732034498, "user": "user_29e85f9a8e75", "body": "```suggestion\n/// check | Надихнуло **FastAPI** на\n```", "path": "docs/uk/docs/alternatives.md", "line": null, "side": "RIGHT", "created_at": "2026-01-27T13:32:10+00:00" }, { "id": 2732035904, "user": "user_29e85f9a8e75", "body": "```suggestion\n/// check | Надихнуло **FastAPI** на\n```", "path": "docs/uk/docs/alternatives.md", "line": null, "side": "RIGHT", "created_at": "2026-01-27T13:32:29+00:00" }, { "id": 2732037318, "user": "user_29e85f9a8e75", "body": "```suggestion\n/// check | Надихнуло **FastAPI** на\n```", "path": "docs/uk/docs/alternatives.md", "line": null, "side": "RIGHT", "created_at": "2026-01-27T13:32:50+00:00" }, { "id": 2732038515, "user": "user_29e85f9a8e75", "body": "```suggestion\n/// check | Надихнуло **FastAPI** на\n```", "path": "docs/uk/docs/alternatives.md", "line": null, "side": "RIGHT", "created_at": "2026-01-27T13:33:08+00:00" }, { "id": 2732041299, "user": "user_29e85f9a8e75", "body": "```suggestion\n/// check | **FastAPI** використовує його для\n```", "path": "docs/uk/docs/alternatives.md", "line": null, "side": "RIGHT", "created_at": "2026-01-27T13:33:44+00:00" }, { "id": 2732043744, "user": "user_29e85f9a8e75", "body": "```suggestion\n/// check | **FastAPI** використовує його для\n```", "path": "docs/uk/docs/alternatives.md", "line": null, "side": "RIGHT", "created_at": "2026-01-27T13:34:15+00:00" }, { "id": 2732045816, "user": "user_29e85f9a8e75", "body": "```suggestion\n/// check | **FastAPI** рекомендує це як\n```", "path": "docs/uk/docs/alternatives.md", "line": null, "side": "RIGHT", "created_at": "2026-01-27T13:34:42+00:00" }, { "id": 2732052618, "user": "user_29e85f9a8e75", "body": "```suggestion\n* OpenAPI для створення API, включаючи оголошення шляхів, операцій, параметрів, тіл запитів, безпеки тощо.\n```", "path": "docs/uk/docs/features.md", "line": null, "side": "RIGHT", "created_at": "2026-01-27T13:36:06+00:00" }, { "id": 2732063628, "user": "user_29e85f9a8e75", "body": "```suggestion\n* Підтримка **CORS**, **GZip**, статичних файлів, потокових відповідей.\n* Підтримка **сесій** і **cookie**.\n```", "path": "docs/uk/docs/features.md", "line": null, "side": "RIGHT", "created_at": "2026-01-27T13:38:35+00:00" } ], "meta": { "languages": [ "md" ], "touches_tests": false, "review_state_summary": { "COMMENTED": 1, "APPROVED": 1 }, "meaningful_comment_count": 22, "has_approval": true, "has_changes_requested": false, "total_review_comments": 22 } } { "_id": "bfea5616988b9901", "_schema_version": "1.0", "_cleaned_at": "2026-02-12T07:46:51.655996+00:00", "repo": "tiangolo/fastapi", "repo_url": "https://github.com/fastapi/fastapi", "license_name": "MIT License", "license_spdx": "MIT", "pr_number": 14738, "title": "🌐 Update translations for ko (update outdated, found by [NAME_REDACTED])", "body": "Running translation fixer tool shows several pages that contain mistakes. They were likely missed because of the overridden commit date.\nThis PR updates those outdated pages", "author": "user_29e85f9a8e75", "created_at": "2026-01-20T08:45:40+00:00", "merged_at": "2026-01-24T21:16:10+00:00", "base_branch": "master", "head_branch": "update-translations-ko", "additions": 473, "deletions": 462, "changed_files": 5, "files": [ { "filename": "docs/ko/docs/async.md", "status": "modified", "additions": 202, "deletions": 168, "changes": 370, "patch": "@@ -1,18 +1,18 @@\n-# 동시성과 async / await\n+# 동시성과 async / await { #concurrency-and-async-await }\n \n-*경로 작동 함수*에서의 `async def` 문법에 대한 세부사항과 비동기 코드, 동시성 및 병렬성에 대한 배경\n+*경로 처리 함수*에서의 `async def` 문법에 대한 세부사항과 비동기 코드, 동시성 및 병렬성에 대한 배경\n \n-## 바쁘신 경우\n+## 바쁘신가요? { #in-a-hurry }\n \n-요약\n+TL;DR:\n \n-다음과 같이 `await`를 사용해 호출하는 제3의 라이브러리를 사용하는 경우:\n+다음과 같이 `await`를 사용해 호출하라고 안내하는 제3자 라이브러리를 사용하는 경우:\n \n ```Python\n results = await some_library()\n ```\n \n-다음처럼 *경로 작동 함수*를 `async def`를 사용해 선언하십시오:\n+다음처럼 *경로 처리 함수*를 `async def`를 사용해 선언하십시오:\n \n ```Python hl_lines=\"2\"\n [USER_REDACTED].get('/')\n@@ -29,7 +29,7 @@ async def read_results():\n \n ---\n \n-데이터베이스, API, 파일시스템 등과 의사소통하는 제3의 라이브러리를 사용하고, 그것이 `await`를 지원하지 않는 경우(현재 거의 모든 데이터베이스 라이브러리가 그러합니다), *경로 작동 함수*를 일반적인 `def`를 사용해 선언하십시오:\n+데이터베이스, API, 파일시스템 등과 의사소통하는 제3자 라이브러리를 사용하고, 그것이 `await` 사용을 지원하지 않는 경우(현재 대부분의 데이터베이스 라이브러리가 그러합니다), *경로 처리 함수*를 일반적인 `def`를 사용해 선언하십시오:\n \n ```Python hl_lines=\"2\"\n [USER_REDACTED].get('/')\n@@ -40,275 +40,307 @@ def results():\n \n ---\n \n-만약 당신의 응용프로그램이 (어째서인지) 다른 무엇과 의사소통하고 그것이 응답하기를 기다릴 필요가 없다면 `async def`를 사용하십시오.\n+만약 여러분의 애플리케이션이 (어째서인지) 다른 어떤 것과도 통신하고 그 응답을 기다릴 필요가 없다면, 내부에서 `await`를 사용할 필요가 없더라도 `async def`를 사용하세요.\n \n ---\n \n-모르겠다면, 그냥 `def`를 사용하십시오.\n+잘 모르겠다면, 일반적인 `def`를 사용하세요.\n \n ---\n \n-**참고**: *경로 작동 함수*에서 필요한만큼 `def`와 `async def`를 혼용할 수 있고, 가장 알맞은 것을 선택해서 정의할 수 있습니다. FastAPI가 자체적으로 알맞은 작업을 수행할 것입니다.\n+**참고**: *경로 처리 함수*에서 필요한 만큼 `def`와 `async def`를 혼용할 수 있으며, 각각에 대해 가장 알맞은 옵션을 선택해 정의하면 됩니다. FastAPI가 올바르게 처리합니다.\n \n-어찌되었든, 상기 어떠한 경우라도, FastAPI는 여전히 비동기적으로 작동하고 매우 빠릅니다.\n+어쨌든 위의 어떤 경우에서도 FastAPI는 여전히 비동기적으로 동작하며 매우 빠릅니다.\n \n-그러나 상기 작업을 수행함으로써 어느 정도의 성능 최적화가 가능합니다.\n+하지만 위의 단계를 따르면, 몇 가지 성능 최적화를 할 수 있습니다.\n \n-## 기술적 세부사항\n+## 기술적 세부사항 { #technical-details }\n \n-최신 파이썬 버전은 `async`와 `await` 문법과 함께 **“코루틴”**이라고 하는 것을 사용하는 **“비동기 코드”**를 지원합니다.\n+최신 파이썬 버전은 **“코루틴”**이라고 하는 것을 사용하는 **“비동기 코드”**를 **`async` 및 `await`** 문법과 함께 지원합니다.\n \n 아래 섹션들에서 해당 문장을 부분별로 살펴보겠습니다:\n \n * **비동기 코드**\n * **`async`와 `await`**\n * **코루틴**\n \n-## 비동기 코드\n+## 비동기 코드 { #asynchronous-code }\n \n-비동기 코드란 언어 💬 가 코드의 어느 한 부분에서, 컴퓨터 / 프로그램🤖에게 *다른 무언가*가 어딘가에서 끝날 때까지 기다려야한다고 말하는 방식입니다. *다른 무언가*가 “느린-파일\" 📝 이라고 불린다고 가정해봅시다.\n+비동기 코드는 언어 💬 가 코드의 어느 한 부분에서 컴퓨터/프로그램 🤖 에게, 어느 시점에는 어딘가에서 *다른 무언가*가 끝날 때까지 기다려야 한다고 말할 수 있는 방법이 있다는 의미입니다. 그 *다른 무언가*를 \"slow-file\" 📝 이라고 해보겠습니다.\n \n-따라서 “느린-파일” 📝이 끝날때까지 컴퓨터는 다른 작업을 수행할 수 있습니다.\n+따라서 그 시간 동안 컴퓨터는 \"slow-file\" 📝 이 끝나는 동안 다른 작업을 하러 갈 수 있습니다.\n \n-그 다음 컴퓨터 / 프로그램 🤖 은 다시 기다리고 있기 때문에 기회가 있을 때마다 다시 돌아오거나, 혹은 당시에 수행해야하는 작업들이 완료될 때마다 다시 돌아옵니다. 그리고 그것 🤖 은 기다리고 있던 작업 중 어느 것이 이미 완료되었는지, 그것 🤖 이 해야하는 모든 작업을 수행하면서 확인합니다.\n+그 다음 컴퓨터/프로그램 🤖 은 다시 기다리는 중이기 때문에 기회가 있을 때마다 돌아오거나, 혹은 그 시점에 해야 할 작업을 모두 끝낼 때마다 돌아옵니다. 그리고 기다리던 작업 중 이미 끝난 것이 있는지 확인하면서, 해야 했던 작업을 수행합니다.\n \n-다음으로, 그것 🤖 은 완료할 첫번째 작업에 착수하고(우리의 \"느린-파일\" 📝 이라고 가정합시다) 그에 대해 수행해야하는 작업을 계속합니다.\n+다음으로, 완료된 첫 번째 작업(우리의 \"slow-file\" 📝 이라고 해보겠습니다)을 가져와서, 그에 대해 해야 했던 작업을 계속합니다.\n \n-\"다른 무언가를 기다리는 것\"은 일반적으로 비교적 \"느린\" (프로세서와 RAM 메모리 속도에 비해) I/O 작업을 의미합니다. 예를 들면 다음의 것들을 기다리는 것입니다:\n+이 \"다른 무언가를 기다리는 것\"은 일반적으로 프로세서와 RAM 메모리 속도에 비해 상대적으로 \"느린\" I/O 작업을 의미합니다. 예를 들어 다음을 기다리는 것입니다:\n \n-* 네트워크를 통해 클라이언트로부터 전송되는 데이터\n-* 네트워크를 통해 클라이언트가 수신할, 당신의 프로그램으로부터 전송되는 데이터\n-* 시스템이 읽고 프로그램에 전달할 디스크 내의 파일 내용\n-* 당신의 프로그램이 시스템에 전달하는, 디스크에 작성될 내용\n+* 네트워크를 통해 클라이언트가 데이터를 보내는 것\n+* 네트워크를 통해 클라이언트가 여러분의 프로그램이 보낸 데이터를 받는 것\n+* 시스템이 디스크의 파일 내용을 읽어서 프로그램에 전달하는 것\n+* 프로그램이 시스템에 전달한 내용을 디스크에 쓰는 것\n * 원격 API 작업\n-* 완료될 데이터베이스 작업\n-* 결과를 반환하는 데이터베이스 쿼리\n-* 기타\n+* 데이터베이스 작업이 완료되는 것\n+* 데이터베이스 쿼리가 결과를 반환하는 것\n+* 기타 등등\n \n-수행 시간의 대부분이 I/O 작업을 기다리는데에 소요되기 때문에, \"I/O에 묶인\" 작업이라고 불립니다.\n+실행 시간의 대부분이 I/O 작업을 기다리는 데 소비되기 때문에, 이를 \"I/O bound\" 작업이라고 부릅니다.\n \n-이것은 \"비동기\"라고 불리는데 컴퓨터 / 프로그램이 작업 결과를 가지고 일을 수행할 수 있도록, 느린 작업에 \"동기화\"되어 아무것도 하지 않으면서 작업이 완료될 정확한 시점만을 기다릴 필요가 없기 때문입니다.\n+이것은 컴퓨터/프로그램이 느린 작업과 \"동기화\"되어, 아무것도 하지 않은 채 그 작업이 끝나는 정확한 시점만 기다렸다가 결과를 가져와 일을 계속할 필요가 없기 때문에 \"비동기\"라고 불립니다.\n \n-이 대신에, \"비동기\" 시스템에서는, 작업은 일단 완료되면, 컴퓨터 / 프로그램이 수행하고 있는 일을 완료하고 이후 다시 돌아와서 그것의 결과를 받아 이를 사용해 작업을 지속할 때까지 잠시 (몇 마이크로초) 대기할 수 있습니다.\n+대신 \"비동기\" 시스템에서는, 작업이 끝나면 컴퓨터/프로그램이 하러 갔던 일을 마칠 때까지 잠시(몇 마이크로초) 줄에서 기다렸다가, 다시 돌아와 결과를 받아 이를 사용해 작업을 계속할 수 있습니다.\n \n-\"동기\"(\"비동기\"의 반대)는 컴퓨터 / 프로그램이 상이한 작업들간 전환을 하기 전에 그것이 대기를 동반하게 될지라도 모든 순서를 따르기 때문에 \"순차\"라는 용어로도 흔히 불립니다.\n+\"동기\"(“비동기”의 반대)는 보통 \"순차\"라는 용어로도 불리는데, 컴퓨터/프로그램이 다른 작업으로 전환하기 전에 모든 단계를 순서대로 따르기 때문이며, 그 단계들에 기다림이 포함되어 있더라도 마찬가지입니다.\n \n-### 동시성과 버거\n+### 동시성과 햄버거 { #concurrency-and-burgers }\n \n-위에서 설명한 **비동기** 코드에 대한 개념은 종종 **\"동시성\"**이라고도 불립니다. 이것은 **\"병렬성\"**과는 다릅니다.\n+위에서 설명한 **비동기** 코드에 대한 개념은 때때로 **\"동시성\"**이라고도 불립니다. 이는 **\"병렬성\"**과는 다릅니다.\n \n-**동시성**과 **병렬성**은 모두 \"동시에 일어나는 서로 다른 일들\"과 관련이 있습니다.\n+**동시성**과 **병렬성**은 모두 \"대략 같은 시간에 일어나는 서로 다른 일들\"과 관련이 있습니다.\n \n 하지만 *동시성*과 *병렬성*의 세부적인 개념에는 꽤 차이가 있습니다.\n \n-차이를 확인하기 위해, 다음의 버거에 대한 이야기를 상상해보십시오:\n+차이를 보기 위해, 다음의 햄버거 이야기를 상상해보세요:\n \n-### 동시 버거\n+### 동시 햄버거 { #concurrent-burgers }\n \n-당신은 짝사랑 상대 😍 와 패스트푸드 🍔 를 먹으러 갔습니다. 당신은 점원 💁 이 당신 앞에 있는 사람들의 주문을 받을 동안 줄을 서서 기다리고 있습니다.\n+여러분은 짝사랑 상대와 패스트푸드를 먹으러 갔고, 점원이 여러분 앞 사람들의 주문을 받는 동안 줄을 서서 기다립니다. 😍\n \n-이제 당신의 순서가 되어서, 당신은 당신과 짝사랑 상대 😍 를 위한 두 개의 고급스러운 버거 🍔 를 주문합니다.\n+\n \n-당신이 돈을 냅니다 💸.\n+이제 여러분 차례가 되어, 여러분과 짝사랑 상대를 위해 매우 고급스러운 햄버거 2개를 주문합니다. 🍔🍔\n \n-점원 💁 은 주방 👨‍🍳 에 요리를 하라고 전달하고, 따라서 그들은 당신의 버거 🍔 를 준비해야한다는 사실을 알게됩니다(그들이 지금은 당신 앞 고객들의 주문을 준비하고 있을지라도 말입니다).\n+\n \n-점원 💁 은 당신의 순서가 적힌 번호표를 줍니다.\n+점원은 주방의 요리사에게 무언가를 말해, (지금은 앞선 손님들의 주문을 준비하고 있더라도) 여러분의 햄버거를 준비해야 한다는 것을 알게 합니다.\n \n-기다리는 동안, 당신은 짝사랑 상대 😍 와 함께 테이블을 고르고, 자리에 앉아 오랫동안 (당신이 주문한 버거는 꽤나 고급스럽기 때문에 준비하는데 시간이 조금 걸립니다 ✨🍔✨) 대화를 나눕니다.\n+\n \n-짝사랑 상대 😍 와 테이블에 앉아서 버거 🍔 를 기다리는 동안, 그 사람 😍 이 얼마나 멋지고, 사랑스럽고, 똑똑한지 감탄하며 시간을 보냅니다 ✨😍✨.\n+여러분이 돈을 냅니다. 💸\n \n-짝사랑 상대 😍 와 기다리면서 얘기하는 동안, 때때로, 당신은 당신의 차례가 되었는지 보기 위해 카운터의 번호를 확인합니다.\n+점원은 여러분 차례 번호를 줍니다.\n \n-그러다 어느 순간, 당신의 차례가 됩니다. 카운터에 가서, 버거 🍔 를 받고, 테이블로 다시 돌아옵니다.\n+\n \n-당신과 짝사랑 상대 😍 는 버거 🍔 를 먹으며 좋은 시간을 보냅니다 ✨.\n+기다리는 동안, 여러분은 짝사랑 상대와 함께 자리를 고르고 앉아 오랫동안 대화를 나눕니다(여러분의 햄버거는 매우 고급스럽기 때문에 준비하는 데 시간이 좀 걸립니다).\n+\n+짝사랑 상대와 테이블에 앉아 햄버거를 기다리는 동안, 그 사람이 얼마나 멋지고 귀엽고 똑똑한지 감탄하며 시간을 보낼 수 있습니다 ✨😍✨.\n+\n+\n+\n+기다리며 대화하는 동안, 때때로 여러분은 카운터에 표시되는 번호를 확인해 여러분 차례인지 봅니다.\n+\n+그러다 어느 순간 마침내 여러분 차례가 됩니다. 여러분은 카운터에 가서 햄버거를 받고, 테이블로 돌아옵니다.\n+\n+\n+\n+여러분과 짝사랑 상대는 햄버거를 먹으며 좋은 시간을 보냅니다. ✨\n+\n+\n+\n+/// info | 정보\n+\n+아름다운 일러스트: [NAME_REDACTED]. 🎨\n+\n+///\n \n ---\n \n-당신이 이 이야기에서 컴퓨터 / 프로그램 🤖 이라고 상상해보십시오.\n+이 이야기에서 여러분이 컴퓨터/프로그램 🤖 이라고 상상해보세요.\n \n-줄을 서서 기다리는 동안, 당신은 아무것도 하지 않고 😴 당신의 차례를 기다리며, 어떠한 \"생산적인\" 일도 하지 않습니다. 하지만 점원 💁 이 (음식을 준비하지는 않고) 주문을 받기만 하기 때문에 줄이 빨리 줄어들어서 괜찮습니다.\n+줄을 서 있는 동안, 여러분은 그냥 쉬고 😴, 차례를 기다리며, 그다지 \"생산적인\" 일을 하지 않습니다. 하지만 점원은 주문만 받지(음식을 준비하진 않기) 때문에 줄이 빠르게 줄어들어 괜찮습니다.\n \n-그다음, 당신이 차례가 오면, 당신은 실제로 \"생산적인\" 일 🤓 을 합니다. 당신은 메뉴를 보고, 무엇을 먹을지 결정하고, 짝사랑 상대 😍 의 선택을 묻고, 돈을 내고 💸 , 맞는 카드를 냈는지 확인하고, 비용이 제대로 지불되었는지 확인하고, 주문이 제대로 들어갔는지 확인을 하는 작업 등등을 수행합니다.\n+그 다음 여러분 차례가 되면, 여러분은 실제로 \"생산적인\" 일을 합니다. 메뉴를 처리하고, 무엇을 먹을지 결정하고, 짝사랑 상대의 선택을 확인하고, 결제하고, 올바른 현금이나 카드를 냈는지 확인하고, 정확히 청구되었는지 확인하고, 주문에 올바른 항목들이 들어갔는지 확인하는 등등을 합니다.\n \n-하지만 이후에는, 버거 🍔 를 아직 받지 못했음에도, 버거가 준비될 때까지 기다려야 🕙 하기 때문에 점원 💁 과의 작업은 \"일시정지\" ⏸ 상태입니다.\n+하지만 그 다음에는, 아직 햄버거를 받지 못했더라도, 햄버거가 준비될 때까지 기다려야 🕙 하므로 점원과의 작업은 \"일시정지\" ⏸ 상태입니다.\n \n-하지만 번호표를 받고 카운터에서 나와 테이블에 앉으면, 당신은 짝사랑 상대 😍 와 그 \"작업\" ⏯ 🤓 에 번갈아가며 🔀 집중합니다. 그러면 당신은 다시 짝사랑 상대 😍 에게 작업을 거는 매우 \"생산적인\" 일 🤓 을 합니다.\n+하지만 번호를 들고 카운터에서 벗어나 테이블에 앉으면, 여러분은 짝사랑 상대에게 관심을 전환 🔀 하고, 그에 대한 \"작업\" ⏯ 🤓 을 할 수 있습니다. 그러면 여러분은 다시 짝사랑 상대에게 작업을 거는 매우 \"생산적인\" 일을 하게 됩니다 😍.\n \n-점원 💁 이 카운터 화면에 당신의 번호를 표시함으로써 \"버거 🍔 가 준비되었습니다\"라고 해도, 당신은 즉시 뛰쳐나가지는 않을 것입니다. 당신은 당신의 번호를 갖고있고, 다른 사람들은 그들의 번호를 갖고있기 때문에, 아무도 당신의 버거 🍔 를 훔쳐가지 않는다는 사실을 알기 때문입니다.\n+그 다음 점원 💁 이 카운터 화면에 여러분 번호를 띄워 \"햄버거를 만들었어요\"라고 말하지만, 표시된 번호가 여러분 차례로 바뀌었다고 해서 즉시 미친 듯이 뛰어가지는 않습니다. 여러분은 여러분 번호를 갖고 있고, 다른 사람들은 그들의 번호를 갖고 있으니, 아무도 여러분 햄버거를 훔쳐갈 수 없다는 것을 알기 때문입니다.\n \n-그래서 당신은 짝사랑 상대 😍 가 이야기를 끝낼 때까지 기다린 후 (현재 작업 완료 ⏯ / 진행 중인 작업 처리 🤓 ), 정중하게 미소짓고 버거를 가지러 가겠다고 말합니다 ⏸.\n+그래서 여러분은 짝사랑 상대가 이야기를 끝낼 때까지 기다린 다음(현재 작업 ⏯ / 처리 중인 작업 🤓 을 끝내고), 부드럽게 미소 지으며 햄버거를 가지러 가겠다고 말합니다 ⏸.\n \n-그다음 당신은 카운터에 가서 🔀 , 초기 작업을 이제 완료하고 ⏯ , 버거 🍔 를 받고, 감사하다고 말하고 테이블로 가져옵니다. 이로써 카운터와의 상호작용 단계 / 작업이 종료됩니다 ⏹.\n+그 다음 여러분은 카운터로 가서 🔀, 이제 끝난 초기 작업 ⏯ 으로 돌아와 햄버거를 받고, 감사 인사를 하고, 테이블로 가져옵니다. 이로써 카운터와 상호작용하는 그 단계/작업이 끝납니다 ⏹. 그리고 이는 새로운 작업인 \"햄버거 먹기\" 🔀 ⏯ 를 만들지만, 이전 작업인 \"햄버거 받기\"는 끝났습니다 ⏹.\n \n-이전 작업인 \"버거 받기\"가 종료되면 ⏹ \"버거 먹기\"라는 새로운 작업이 생성됩니다 🔀 ⏯.\n+### 병렬 햄버거 { #parallel-burgers }\n \n-### 병렬 버거\n+이제 이것이 \"동시 햄버거\"가 아니라 \"병렬 햄버거\"라고 상상해봅시다.\n \n-이제 \"동시 버거\"가 아닌 \"병렬 버거\"를 상상해보십시오.\n+여러분은 짝사랑 상대와 함께 병렬 패스트푸드를 먹으러 갑니다.\n \n-당신은 짝사랑 상대 😍 와 함께 병렬 패스트푸드 🍔 를 먹으러 갔습니다.\n+여러분은 여러 명(예: 8명)의 점원이 동시에 요리사이기도 하여 여러분 앞 사람들의 주문을 받는 동안 줄을 서 있습니다.\n \n-당신은 여러명(8명이라고 가정합니다)의 점원이 당신 앞 사람들의 주문을 받으며 동시에 요리 👩‍🍳👨‍🍳👩‍🍳👨‍🍳👩‍🍳👨‍🍳👩‍🍳👨‍🍳 도 하는 동안 줄을 서서 기다립니다.\n+여러분 앞의 모든 사람들은, 8명의 점원 각각이 다음 주문을 받기 전에 바로 햄버거를 준비하러 가기 때문에, 카운터를 떠나지 않고 햄버거가 준비될 때까지 기다립니다.\n \n-당신 앞 모든 사람들이 버거가 준비될 때까지 카운터에서 떠나지 않고 기다립니다 🕙 . 왜냐하면 8명의 직원들이 다음 주문을 받기 전에 버거를 준비하러 가기 때문입니다.\n+\n \n-마침내 당신의 차례가 왔고, 당신은 당신과 짝사랑 상대 😍 를 위한 두 개의 고급스러운 버거 🍔 를 주문합니다.\n+마침내 여러분 차례가 되어, 여러분과 짝사랑 상대를 위해 매우 고급스러운 햄버거 2개를 주문합니다.\n \n-당신이 비용을 지불합니다 💸 .\n+여러분이 돈을 냅니다 💸.\n \n-점원이 주방에 갑니다 👨‍🍳 .\n+\n \n-당신은 번호표가 없기 때문에 누구도 당신의 버거 🍔 를 대신 가져갈 수 없도록 카운터에 서서 기다립니다 🕙 .\n+점원은 주방으로 갑니다.\n \n-당신과 짝사랑 상대 😍 는 다른 사람이 새치기해서 버거를 가져가지 못하게 하느라 바쁘기 때문에 🕙 , 짝사랑 상대에게 주의를 기울일 수 없습니다 😞 .\n+여러분은 번호표가 없으므로, 다른 사람이 여러분보다 먼저 햄버거를 가져가지 못하도록 카운터 앞에 서서 기다립니다 🕙.\n \n-이것은 \"동기\" 작업이고, 당신은 점원/요리사 👨‍🍳 와 \"동기화\" 되었습니다. 당신은 기다리고 🕙 , 점원/요리사 👨‍🍳 가 버거 🍔 준비를 완료한 후 당신에게 주거나, 누군가가 그것을 가져가는 그 순간에 그 곳에 있어야합니다.\n+\n \n-카운터 앞에서 오랫동안 기다린 후에 🕙 , 점원/요리사 👨‍🍳 가 당신의 버거 🍔 를 가지고 돌아옵니다.\n+여러분과 짝사랑 상대는 햄버거가 나오면 다른 사람이 끼어들어 가져가지 못하게 하느라 바쁘기 때문에, 짝사랑 상대에게 집중할 수 없습니다. 😞\n \n-당신은 버거를 받고 짝사랑 상대와 함께 테이블로 돌아옵니다.\n+이것은 \"동기\" 작업이며, 여러분은 점원/요리사 👨‍🍳 와 \"동기화\"되어 있습니다. 점원/요리사 👨‍🍳 가 햄버거를 완성해 여러분에게 주는 정확한 순간에 그 자리에 있어야 하므로, 여러분은 기다려야 🕙 하고, 그렇지 않으면 다른 사람이 가져갈 수도 있습니다.\n \n-단지 먹기만 하다가, 다 먹었습니다 🍔 ⏹.\n+\n \n-카운터 앞에서 기다리면서 🕙 너무 많은 시간을 허비했기 때문에 대화를 하거나 작업을 걸 시간이 거의 없었습니다 😞 .\n+그러다 점원/요리사 👨‍🍳 가 카운터 앞에서 오랫동안 기다린 🕙 끝에 마침내 햄버거를 가지고 돌아옵니다.\n \n----\n+\n+\n+여러분은 햄버거를 받아 짝사랑 상대와 테이블로 갑니다.\n+\n+그냥 먹고, 끝입니다. ⏹\n+\n+\n+\n+대부분의 시간을 카운터 앞에서 기다리는 데 🕙 썼기 때문에, 대화하거나 작업을 걸 시간은 많지 않았습니다. 😞\n \n-이 병렬 버거 시나리오에서, 당신은 기다리고 🕙 , 오랜 시간동안 \"카운터에서 기다리는\" 🕙 데에 주의를 기울이는 ⏯ 두 개의 프로세서(당신과 짝사랑 상대😍)를 가진 컴퓨터 / 프로그램 🤖 입니다.\n+/// info | 정보\n \n-패스트푸드점에는 8개의 프로세서(점원/요리사) 👩‍🍳👨‍🍳👩‍🍳👨‍🍳👩‍🍳👨‍🍳👩‍🍳👨‍🍳 가 있습니다. 동시 버거는 단 두 개(한 명의 직원과 한 명의 요리사) 💁 👨‍🍳 만을 가지고 있었습니다.\n+아름다운 일러스트: [NAME_REDACTED]. 🎨\n \n-하지만 여전히, 병렬 버거 예시가 최선은 아닙니다 😞 .\n+///\n \n ---\n \n-이 예시는 버거🍔 이야기와 결이 같습니다.\n+이 병렬 햄버거 시나리오에서, 여러분은 두 개의 프로세서(여러분과 짝사랑 상대)를 가진 컴퓨터/프로그램 🤖 이며, 둘 다 기다리고 🕙 오랫동안 \"카운터에서 기다리기\" 🕙 에 주의를 ⏯ 기울입니다.\n+\n+패스트푸드점에는 8개의 프로세서(점원/요리사)가 있습니다. 동시 햄버거 가게는 2개(점원 1명, 요리사 1명)만 있었을 것입니다.\n \n-더 \"현실적인\" 예시로, 은행을 상상해보십시오.\n+하지만 여전히 최종 경험은 그다지 좋지 않습니다. 😞\n \n-최근까지, 대다수의 은행에는 다수의 은행원들 👨‍💼👨‍💼👨‍💼👨‍💼 과 긴 줄 🕙🕙🕙🕙🕙🕙🕙🕙 이 있습니다.\n+---\n \n-모든 은행원들은 한 명 한 명의 고객들을 차례로 상대합니다 👨‍💼⏯ .\n+이것이 햄버거의 병렬 버전에 해당하는 이야기입니다. 🍔\n \n-그리고 당신은 오랫동안 줄에서 기다려야하고 🕙 , 그렇지 않으면 당신의 차례를 잃게 됩니다.\n+좀 더 \"현실적인\" 예시로, 은행을 상상해보세요.\n \n-아마 당신은 은행 🏦 심부름에 짝사랑 상대 😍 를 데려가고 싶지는 않을 것입니다.\n+최근까지 대부분의 은행에는 여러 은행원 👨‍💼👨‍💼👨‍💼👨‍💼 과 긴 줄 🕙🕙🕙🕙🕙🕙🕙🕙 이 있었습니다.\n \n-### 버거 예시의 결론\n+모든 은행원이 한 고객씩 순서대로 모든 일을 처리합니다 👨‍💼⏯.\n \n-\"짝사랑 상대와의 패스트푸드점 버거\" 시나리오에서, 오랜 기다림 🕙 이 있기 때문에 동시 시스템 ⏸🔀⏯ 을 사용하는 것이 더 합리적입니다.\n+그리고 여러분은 오랫동안 줄에서 기다려야 🕙 하며, 그렇지 않으면 차례를 잃습니다.\n \n-대다수의 웹 응용프로그램의 경우가 그러합니다.\n+아마 은행 🏦 업무를 보러 갈 때 짝사랑 상대 😍 를 데려가고 싶지는 않을 것입니다.\n \n-매우 많은 수의 유저가 있지만, 서버는 그들의 요청을 전송하기 위해 그닥-좋지-않은 연결을 기다려야 합니다 🕙 .\n+### 햄버거 예시의 결론 { #burger-conclusion }\n \n-그리고 응답이 돌아올 때까지 다시 기다려야 합니다 🕙 .\n+\"짝사랑 상대와의 패스트푸드점 햄버거\" 시나리오에서는 기다림 🕙 이 많기 때문에, 동시 시스템 ⏸🔀⏯ 을 사용하는 것이 훨씬 더 합리적입니다.\n \n-이 \"기다림\" 🕙 은 마이크로초 단위이지만, 모두 더해지면, 결국에는 매우 긴 대기시간이 됩니다.\n+대부분의 웹 애플리케이션이 그렇습니다.\n \n-따라서 웹 API를 위해 비동기 ⏸🔀⏯ 코드를 사용하는 것이 합리적입니다.\n+매우 많은 사용자들이 있고, 서버는 그들의 좋지 않은 연결을 통해 요청이 전송되기를 기다립니다 🕙.\n \n-대부분의 존재하는 유명한 파이썬 프레임워크 (Flask와 Django 등)은 새로운 비동기 기능들이 파이썬에 존재하기 전에 만들어졌습니다. 그래서, 그들의 배포 방식은 병렬 실행과 새로운 기능만큼 강력하지는 않은 예전 버전의 비동기 실행을 지원합니다.\n+그리고 응답이 돌아오기를 다시 기다립니다 🕙.\n \n-비동기 웹 파이썬(ASGI)에 대한 주요 명세가 웹소켓을 지원하기 위해 Django에서 개발 되었음에도 그렇습니다.\n+이 \"기다림\" 🕙 은 마이크로초 단위로 측정되지만, 모두 합치면 결국 꽤 많은 대기 시간이 됩니다.\n \n-이러한 종류의 비동기성은 (NodeJS는 병렬적이지 않음에도) NodeJS가 사랑받는 이유이고, 프로그래밍 언어로서의 Go의 강점입니다.\n+그래서 웹 API에는 비동기 ⏸🔀⏯ 코드를 사용하는 것이 매우 합리적입니다.\n \n-그리고 **FastAPI**를 사용함으로써 동일한 성능을 낼 수 있습니다.\n+이러한 종류의 비동기성은 NodeJS가 인기 있는 이유(비록 NodeJS가 병렬은 아니지만)이자, 프로그래밍 언어로서 Go의 강점입니다.\n \n-또한 병렬성과 비동기성을 동시에 사용할 수 있기 때문에, 대부분의 테스트가 완료된 NodeJS 프레임워크보다 더 높은 성능을 얻고 C에 더 가까운 컴파일 언어인 Go와 동등한 성능을 얻을 수 있습니다(모두 Starlette 덕분입니다).\n+그리고 이것이 **FastAPI**로 얻는 것과 같은 수준의 성능입니다.\n \n-### 동시성이 병렬성보다 더 나은가?\n+또한 병렬성과 비동기성을 동시에 사용할 수 있으므로, 대부분의 테스트된 NodeJS 프레임워크보다 더 높은 성능을 얻고, C에 더 가까운 컴파일 언어인 Go와 동등한 성능을 얻을 수 있습니다 (모두 Starlette 덕분입니다).\n \n-그렇지 않습니다! 그것이 이야기의 교훈은 아닙니다.\n+### 동시성이 병렬성보다 더 나은가요? { #is-concurrency-better-than-parallelism }\n \n-동시성은 병렬성과 다릅니다. 그리고 그것은 많은 대기를 필요로하는 **특정한** 시나리오에서는 더 낫습니다. 이로 인해, 웹 응용프로그램 개발에서 동시성이 병렬성보다 일반적으로 훨씬 낫습니다. 하지만 모든 경우에 그런 것은 아닙니다.\n+아니요! 그게 이 이야기의 교훈은 아닙니다.\n \n-따라서, 균형을 맞추기 위해, 다음의 짧은 이야기를 상상해보십시오:\n+동시성은 병렬성과 다릅니다. 그리고 많은 기다림이 포함되는 **특정한** 시나리오에서는 더 낫습니다. 그 때문에 웹 애플리케이션 개발에서는 일반적으로 병렬성보다 훨씬 더 낫습니다. 하지만 모든 것에 해당하진 않습니다.\n \n-> 당신은 크고, 더러운 집을 청소해야합니다.\n+그래서 균형을 맞추기 위해, 다음의 짧은 이야기를 상상해보세요:\n+\n+> 여러분은 크고 더러운 집을 청소해야 합니다.\n \n *네, 이게 전부입니다*.\n \n ---\n \n-어디에도 대기 🕙 는 없고, 집안 곳곳에서 해야하는 많은 작업들만 있습니다.\n+어디에도 기다림 🕙 은 없고, 집의 여러 장소에서 해야 할 일이 많을 뿐입니다.\n \n-버거 예시처럼 처음에는 거실, 그 다음은 부엌과 같은 식으로 순서를 정할 수도 있으나, 무엇도 기다리지 🕙 않고 계속해서 청소 작업만 수행하기 때문에, 순서는 아무런 영향을 미치지 않습니다.\n+햄버거 예시처럼 거실부터, 그 다음은 부엌처럼 순서를 정할 수도 있지만, 어떤 것도 기다리지 🕙 않고 계속 청소만 하기 때문에, 순서는 아무런 영향을 주지 않습니다.\n \n-순서가 있든 없든 동일한 시간이 소요될 것이고(동시성) 동일한 양의 작업을 하게 될 것입니다.\n+순서가 있든 없든(동시성) 끝내는 데 걸리는 시간은 같고, 같은 양의 일을 하게 됩니다.\n \n-하지만 이 경우에서, 8명의 전(前)-점원/요리사이면서-현(現)-청소부 👩‍🍳👨‍🍳👩‍🍳👨‍🍳👩‍🍳👨‍🍳👩‍🍳👨‍🍳 를 고용할 수 있고, 그들 각자(그리고 당신)가 집의 한 부분씩 맡아 청소를 한다면, 당신은 **병렬적**으로 작업을 수행할 수 있고, 조금의 도움이 있다면, 훨씬 더 빨리 끝낼 수 있습니다.\n+하지만 이 경우, 전(前) 점원/요리사이자 현(現) 청소부가 된 8명을 데려올 수 있고, 각자(그리고 여러분)가 집의 구역을 하나씩 맡아 청소한다면, 추가 도움과 함께 모든 일을 **병렬**로 수행하여 훨씬 더 빨리 끝낼 수 있습니다.\n \n-이 시나리오에서, (당신을 포함한) 각각의 청소부들은 프로세서가 될 것이고, 각자의 역할을 수행합니다.\n+이 시나리오에서 (여러분을 포함한) 각 청소부는 프로세서가 되어, 맡은 일을 수행합니다.\n \n-실행 시간의 대부분이 대기가 아닌 실제 작업에 소요되고, 컴퓨터에서 작업은 CPU에서 이루어지므로, 이러한 문제를 \"CPU에 묶였\"다고 합니다.\n+그리고 실행 시간의 대부분이 기다림이 아니라 실제 작업에 쓰이고, 컴퓨터에서 작업은 CPU가 수행하므로, 이런 문제를 \"CPU bound\"라고 부릅니다.\n \n ---\n \n-CPU에 묶인 연산에 관한 흔한 예시는 복잡한 수학 처리를 필요로 하는 경우입니다.\n+CPU bound 작업의 흔한 예시는 복잡한 수학 처리가 필요한 것들입니다.\n \n 예를 들어:\n \n-* **오디오** 또는 **이미지** 처리.\n-* **컴퓨터 비전**: 하나의 이미지는 수백개의 픽셀로 구성되어있고, 각 픽셀은 3개의 값 / 색을 갖고 있으며, 일반적으로 해당 픽셀들에 대해 동시에 무언가를 계산해야하는 처리.\n-* **머신러닝**: 일반적으로 많은 \"행렬\"과 \"벡터\" 곱셈이 필요합니다. 거대한 스프레드 시트에 수들이 있고 그 수들을 동시에 곱해야 한다고 생각해보십시오.\n-* **딥러닝**: 머신러닝의 하위영역으로, 동일한 예시가 적용됩니다. 단지 이 경우에는 하나의 스프레드 시트에 곱해야할 수들이 있는 것이 아니라, 거대한 세트의 스프레드 시트들이 있고, 많은 경우에, 이 모델들을 만들고 사용하기 위해 특수한 프로세서를 사용합니다.\n+* **오디오** 또는 **이미지** 처리\n+* **컴퓨터 비전**: 이미지는 수백만 개의 픽셀로 구성되며, 각 픽셀은 3개의 값/색을 갖습니다. 보통 그 픽셀들에 대해 동시에 무언가를 계산해야 합니다.\n+* **머신러닝**: 보통 많은 \"matrix\"와 \"vector\" 곱셈이 필요합니다. 숫자가 있는 거대한 스프레드시트를 생각하고, 그 모든 수를 동시에 곱한다고 생각해보세요.\n+* **딥러닝**: 머신러닝의 하위 분야이므로 동일하게 적용됩니다. 다만 곱해야 할 숫자가 있는 스프레드시트가 하나가 아니라, 아주 큰 집합이며, 많은 경우 그 모델을 만들고/또는 사용하기 위해 특별한 프로세서를 사용합니다.\n \n-### 동시성 + 병렬성: 웹 + 머신러닝\n+### 동시성 + 병렬성: 웹 + 머신러닝 { #concurrency-parallelism-web-machine-learning }\n \n-**FastAPI**를 사용하면 웹 개발에서는 매우 흔한 동시성의 이점을 (NodeJS의 주된 매력만큼) 얻을 수 있습니다.\n+**FastAPI**를 사용하면 웹 개발에서 매우 흔한 동시성의 이점을( NodeJS의 주요 매력과 같은) 얻을 수 있습니다.\n \n-뿐만 아니라 머신러닝 시스템과 같이 **CPU에 묶인** 작업을 위해 병렬성과 멀티프로세싱(다수의 프로세스를 병렬적으로 동작시키는 것)을 이용하는 것도 가능합니다.\n+또한 머신러닝 시스템처럼 **CPU bound** 워크로드에 대해 병렬성과 멀티프로세싱(여러 프로세스를 병렬로 실행)을 활용할 수도 있습니다.\n \n-파이썬이 **데이터 사이언스**, 머신러닝과 특히 딥러닝에 의 주된 언어라는 간단한 사실에 더해서, 이것은 FastAPI를 데이터 사이언스 / 머신러닝 웹 API와 응용프로그램에 (다른 것들보다) 좋은 선택지가 되게 합니다.\n+이것은 파이썬이 **데이터 사이언스**, 머신러닝, 특히 딥러닝의 주요 언어라는 단순한 사실과 더해져, FastAPI를 데이터 사이언스/머신러닝 웹 API 및 애플리케이션(그 외에도 많은 것들)에 매우 잘 맞는 선택으로 만들어 줍니다.\n \n-배포시 병렬을 어떻게 가능하게 하는지 알고싶다면, [배포](deployment/index.md){.internal-link target=_blank}문서를 참고하십시오.\n+프로덕션에서 이 병렬성을 어떻게 달성하는지 보려면 [배포](deployment/index.md){.internal-link target=_blank} 섹션을 참고하세요.\n \n-## `async`와 `await`\n+## `async`와 `await` { #async-and-await }\n \n-최신 파이썬 버전에는 비동기 코드를 정의하는 매우 직관적인 방법이 있습니다. 이는 이것을 평범한 \"순차적\" 코드로 보이게 하고, 적절한 순간에 당신을 위해 \"대기\"합니다.\n+최신 파이썬 버전에는 비동기 코드를 정의하는 매우 직관적인 방법이 있습니다. 이 방법은 이를 평범한 \"순차\" 코드처럼 보이게 하고, 적절한 순간에 여러분을 위해 \"기다림\"을 수행합니다.\n \n-연산이 결과를 전달하기 전에 대기를 해야하고 새로운 파이썬 기능들을 지원한다면, 이렇게 코드를 작성할 수 있습니다:\n+결과를 주기 전에 기다림이 필요한 작업이 있고, 이러한 새로운 파이썬 기능을 지원한다면, 다음과 같이 작성할 수 있습니다:\n \n ```Python\n burgers = await get_burgers(2)\n ```\n \n-여기서 핵심은 `await`입니다. 이것은 파이썬에게 `burgers` 결과를 저장하기 이전에 `get_burgers(2)`의 작업이 완료되기를 🕙 기다리라고 ⏸ 말합니다. 이로 인해, 파이썬은 그동안 (다른 요청을 받는 것과 같은) 다른 작업을 수행해도 된다는 것을 🔀 ⏯ 알게될 것입니다.\n+여기서 핵심은 `await`입니다. 이는 파이썬에게 `get_burgers(2)`가 그 일을 끝낼 때까지 🕙 기다리도록 ⏸ 말하고, 그 결과를 `burgers`에 저장하기 전에 완료되기를 기다리라고 합니다. 이를 통해 파이썬은 그동안(예: 다른 요청을 받는 것처럼) 다른 일을 하러 갈 수 있다는 것 🔀 ⏯ 을 알게 됩니다.\n \n-`await`가 동작하기 위해, 이것은 비동기를 지원하는 함수 내부에 있어야 합니다. 이를 위해서 함수를 `async def`를 사용해 정의하기만 하면 됩니다:\n+`await`가 동작하려면, 이 비동기성을 지원하는 함수 내부에 있어야 합니다. 그러려면 `async def`로 선언하기만 하면 됩니다:\n \n ```Python hl_lines=\"1\"\n async def get_burgers(number: int):\n- # Do some asynchronous stuff to create the burgers\n+ # 햄버거를 만들기 위한 비동기 처리를 수행\n return burgers\n ```\n \n-...`def`를 사용하는 대신:\n+...`def` 대신:\n \n ```Python hl_lines=\"2\"\n-# This is not asynchronous\n+# 비동기가 아닙니다\n def get_sequential_burgers(number: int):\n- # Do some sequential stuff to create the burgers\n+ # 햄버거를 만들기 위한 순차 처리를 수행\n return burgers\n ```\n \n-`async def`를 사용하면, 파이썬은 해당 함수 내에서 `await` 표현에 주의해야한다는 사실과, 해당 함수의 실행을 \"일시정지\"⏸하고 다시 돌아오기 전까지 다른 작업을 수행🔀할 수 있다는 것을 알게됩니다.\n+`async def`를 사용하면, 파이썬은 그 함수 내부에서 `await` 표현식에 주의해야 하며, 그 함수의 실행을 \"일시정지\" ⏸ 하고 다시 돌아오기 전에 다른 일을 하러 갈 수 있다는 것 🔀 을 알게 됩니다.\n \n-`async def`f 함수를 호출하고자 할 때, \"대기\"해야합니다. 따라서, 아래는 동작하지 않습니다.\n+`async def` 함수를 호출하고자 할 때는, 그 함수를 \"await\" 해야 합니다. 따라서 아래는 동작하지 않습니다:\n \n ```Python\n-# This won't work, because get_burgers was defined with: async def\n+# 동작하지 않습니다. get_burgers는 async def로 정의되었습니다\n burgers = get_burgers(2)\n ```\n \n ---\n \n-따라서, `await`f를 사용해서 호출할 수 있는 라이브러리를 사용한다면, 다음과 같이 `async def`를 사용하는 *경로 작동 함수*를 생성해야 합니다:\n+따라서, `await`로 호출할 수 있다고 말하는 라이브러리를 사용한다면, 다음과 같이 그것을 사용하는 *경로 처리 함수*를 `async def`로 만들어야 합니다:\n \n ```Python hl_lines=\"2-3\"\n [USER_REDACTED].get('/burgers')\n@@ -317,94 +349,96 @@ async def read_burgers():\n return burgers\n ```\n \n-### 더 세부적인 기술적 사항\n+### 더 세부적인 기술적 사항 { #more-technical-details }\n+\n+`await`는 `async def`로 정의된 함수 내부에서만 사용할 수 있다는 것을 눈치채셨을 것입니다.\n \n-`await`가 `async def`를 사용하는 함수 내부에서만 사용이 가능하다는 것을 눈치채셨을 것입니다.\n+하지만 동시에, `async def`로 정의된 함수는 \"await\" 되어야 합니다. 따라서 `async def`를 가진 함수는 `async def`로 정의된 함수 내부에서만 호출될 수 있습니다.\n \n-하지만 동시에, `async def`로 정의된 함수들은 \"대기\"되어야만 합니다. 따라서, `async def`를 사용한 함수들은 역시 `async def`를 사용한 함수 내부에서만 호출될 수 있습니다.\n+그렇다면, 닭이 먼저냐 달걀이 먼저냐처럼, 첫 번째 `async` 함수는 어떻게 호출할 수 있을까요?\n \n-그렇다면 닭이 먼저냐, 달걀이 먼저냐, 첫 `async` 함수를 어떻게 호출할 수 있겠습니까?\n+**FastAPI**로 작업한다면 걱정할 필요가 없습니다. 그 \"첫\" 함수는 여러분의 *경로 처리 함수*가 될 것이고, FastAPI는 올바르게 처리하는 방법을 알고 있기 때문입니다.\n \n-**FastAPI**를 사용해 작업한다면 이것을 걱정하지 않아도 됩니다. 왜냐하면 그 \"첫\" 함수는 당신의 *경로 작동 함수*가 될 것이고, FastAPI는 어떻게 올바르게 처리할지 알고있기 때문입니다.\n+하지만 FastAPI 없이 `async` / `await`를 사용하고 싶다면, 그것도 가능합니다.\n \n-하지만 FastAPI를 사용하지 않고 `async` / `await`를 사용하고 싶다면, 이 역시 가능합니다.\n+### 여러분만의 async 코드 작성하기 { #write-your-own-async-code }\n \n-### 당신만의 비동기 코드 작성하기\n+Starlette(그리고 **FastAPI**)는 AnyIO를 기반으로 하고 있으며, 파이썬 표준 라이브러리 asyncioTrio 모두와 호환됩니다.\n \n-Starlette(그리고 FastAPI)는 AnyIO를 기반으로 하고있고, 따라서 파이썬 표준 라이브러리인 asyncioTrio와 호환됩니다.\n+특히, 코드에서 더 고급 패턴이 필요한 고급 동시성 사용 사례에서는 직접 AnyIO를 사용할 수 있습니다.\n \n-특히, 코드에서 고급 패턴이 필요한 고급 동시성을 사용하는 경우 직접적으로 AnyIO를 사용할 수 있습니다.\n+그리고 FastAPI를 사용하지 않더라도, 높은 호환성을 확보하고 그 이점(예: *structured concurrency*)을 얻기 위해 AnyIO로 여러분만의 async 애플리케이션을 작성할 수도 있습니다.\n \n-FastAPI를 사용하지 않더라도, 높은 호환성 및 AnyIO의 이점(예: *구조화된 동시성*)을 취하기 위해 AnyIO를 사용해 비동기 응용프로그램을 작성할 수 있습니다.\n+저는 AnyIO 위에 얇은 레이어로 또 다른 라이브러리를 만들었는데, 타입 어노테이션을 조금 개선하고 더 나은 **자동완성**, **인라인 오류** 등을 얻기 위한 것입니다. 또한 **이해**하고 **여러분만의 async 코드**를 작성하도록 돕는 친절한 소개와 튜토리얼도 제공합니다: Asyncer. 특히 **async 코드와 일반**(blocking/동기) 코드를 **결합**해야 한다면 아주 유용합니다.\n \n-### 비동기 코드의 다른 형태\n+### 비동기 코드의 다른 형태 { #other-forms-of-asynchronous-code }\n \n-파이썬에서 `async`와 `await`를 사용하게 된 것은 비교적 최근의 일입니다.\n+`async`와 `await`를 사용하는 이 스타일은 언어에서 비교적 최근에 추가되었습니다.\n \n-하지만 이로 인해 비동기 코드 작업이 훨씬 간단해졌습니다.\n+하지만 비동기 코드를 다루는 일을 훨씬 더 쉽게 만들어 줍니다.\n \n-같은 (또는 거의 유사한) 문법은 최신 버전의 자바스크립트(브라우저와 NodeJS)에도 추가되었습니다.\n+거의 동일한 문법이 최근 브라우저와 NodeJS의 최신 JavaScript에도 포함되었습니다.\n \n-하지만 그 이전에, 비동기 코드를 처리하는 것은 꽤 복잡하고 어려운 일이었습니다.\n+하지만 그 이전에는 비동기 코드를 처리하는 것이 훨씬 더 복잡하고 어려웠습니다.\n \n-파이썬의 예전 버전이라면, 스레드 또는 Gevent를 사용할 수 있을 것입니다. 하지만 코드를 이해하고, 디버깅하고, 이에 대해 생각하는게 훨씬 복잡합니다.\n+이전 버전의 파이썬에서는 스레드 또는 Gevent를 사용할 수 있었을 것입니다. 하지만 코드를 이해하고, 디버깅하고, 이에 대해 생각하는 것이 훨씬 더 복잡합니다.\n \n-예전 버전의 NodeJS / 브라우저 자바스크립트라면, \"콜백 함수\"를 사용했을 것입니다. 그리고 이로 인해 \"콜백 지옥\"에 빠지게 될 수 있습니다.\n+이전 버전의 NodeJS/브라우저 JavaScript에서는 \"callback\"을 사용했을 것입니다. 이는 \"callback hell\"로 이어집니다.\n \n-## 코루틴\n+## 코루틴 { #coroutines }\n \n-**코루틴**은 `async def` 함수가 반환하는 것을 칭하는 매우 고급스러운 용어일 뿐입니다. 파이썬은 그것이 시작되고 어느 시점에서 완료되지만 내부에 `await`가 있을 때마다 내부적으로 일시정지⏸될 수도 있는 함수와 유사한 것이라는 사실을 알고있습니다.\n+**코루틴**은 `async def` 함수가 반환하는 것에 대한 매우 고급스러운 용어일 뿐입니다. 파이썬은 그것이 함수와 비슷한 무언가로서 시작할 수 있고, 어느 시점에 끝나지만, 내부에 `await`가 있을 때마다 내부적으로도 일시정지 ⏸ 될 수 있다는 것을 알고 있습니다.\n \n-그러나 `async` 및 `await`와 함께 비동기 코드를 사용하는 이 모든 기능들은 \"코루틴\"으로 간단히 요약됩니다. 이것은 Go의 주된 핵심 기능인 \"고루틴\"에 견줄 수 있습니다.\n+하지만 `async` 및 `await`와 함께 비동기 코드를 사용하는 이 모든 기능은 종종 \"코루틴\"을 사용한다고 요약됩니다. 이는 Go의 주요 핵심 기능인 \"Goroutines\"에 비견됩니다.\n \n-## 결론\n+## 결론 { #conclusion }\n \n-상기 문장을 다시 한 번 봅시다:\n+위의 같은 문장을 다시 봅시다:\n \n-> 최신 파이썬 버전은 **`async` 및 `await`** 문법과 함께 **“코루틴”**이라고 하는 것을 사용하는 **“비동기 코드”**를 지원합니다.\n+> 최신 파이썬 버전은 **“코루틴”**이라고 하는 것을 사용하는 **“비동기 코드”**를 **`async` 및 `await`** 문법과 함께 지원합니다.\n \n-이제 이 말을 조금 더 이해할 수 있을 것입니다. ✨\n+이제 더 이해가 될 것입니다. ✨\n \n-이것이 (Starlette을 통해) FastAPI를 강하게 하면서 그것이 인상적인 성능을 낼 수 있게 합니다.\n+이 모든 것이 FastAPI(Starlette을 통해)를 구동하고, 인상적인 성능을 내게 하는 원동력입니다.\n \n-## 매우 세부적인 기술적 사항\n+## 매우 세부적인 기술적 사항 { #very-technical-details }\n \n /// warning | 경고\n \n-이 부분은 넘어가도 됩니다.\n+이 부분은 아마 건너뛰어도 됩니다.\n \n 이것들은 **FastAPI**가 내부적으로 어떻게 동작하는지에 대한 매우 세부적인 기술사항입니다.\n \n-만약 기술적 지식(코루틴, 스레드, 블록킹 등)이 있고 FastAPI가 어떻게 `async def` vs `def`를 다루는지 궁금하다면, 계속하십시오.\n+(코루틴, 스레드, 블로킹 등) 같은 기술 지식이 꽤 있고 FastAPI가 `async def`와 일반 `def`를 어떻게 처리하는지 궁금하다면, 계속 읽어보세요.\n \n ///\n \n-### 경로 작동 함수\n+### 경로 처리 함수 { #path-operation-functions }\n \n-경로 작동 함수를 `async def` 대신 일반적인 `def`로 선언하는 경우, (서버를 차단하는 것처럼) 그것을 직접 호출하는 대신 대기중인 외부 스레드풀에서 실행됩니다.\n+*경로 처리 함수*를 `async def` 대신 일반적인 `def`로 선언하면, (서버를 블로킹할 수 있으므로 직접 호출하는 대신) 외부 스레드풀에서 실행되고 그 결과를 await 합니다.\n \n-만약 상기에 묘사된대로 동작하지 않는 비동기 프로그램을 사용해왔고 약간의 성능 향상 (약 100 나노초)을 위해 `def`를 사용해서 계산만을 위한 사소한 *경로 작동 함수*를 정의해왔다면, **FastAPI**는 이와는 반대라는 것에 주의하십시오. 이러한 경우에, *경로 작동 함수*가 블로킹 I/O를 수행하는 코드를 사용하지 않는 한 `async def`를 사용하는 편이 더 낫습니다.\n+위에서 설명한 방식으로 동작하지 않는 다른 async 프레임워크를 사용해본 적이 있고, 아주 작은 성능 향상(약 100 나노초)을 위해 계산만 하는 사소한 *경로 처리 함수*를 일반 `def`로 정의하곤 했다면, **FastAPI**에서는 그 효과가 정반대가 될 수 있다는 점에 유의하세요. 이런 경우에는 *경로 처리 함수*에서 블로킹 I/O 를 수행하는 코드를 사용하지 않는 한 `async def`를 사용하는 편이 더 낫습니다.\n \n-하지만 두 경우 모두, FastAPI가 당신이 전에 사용하던 프레임워크보다 [더 빠를](index.md#_11){.internal-link target=_blank} (최소한 비견될) 확률이 높습니다.\n+그럼에도 두 경우 모두, **FastAPI**는 이전에 사용하던 프레임워크보다 [여전히 더 빠를](index.md#performance){.internal-link target=_blank} 가능성이 높습니다(또는 최소한 비슷합니다).\n \n-### 의존성\n+### 의존성 { #dependencies }\n \n-의존성에도 동일하게 적용됩니다. 의존성이 `async def`가 아닌 표준 `def` 함수라면, 외부 스레드풀에서 실행됩니다.\n+[의존성](tutorial/dependencies/index.md){.internal-link target=_blank}에도 동일하게 적용됩니다. 의존성이 `async def` 대신 표준 `def` 함수라면, 외부 스레드풀에서 실행됩니다.\n \n-### 하위-의존성\n+### 하위 의존성 { #sub-dependencies }\n \n-함수 정의시 매개변수로 서로를 필요로하는 다수의 의존성과 하위-의존성을 가질 수 있고, 그 중 일부는 `async def`로, 다른 일부는 일반적인 `def`로 생성되었을 수 있습니다. 이것은 여전히 잘 동작하고, 일반적인 `def`로 생성된 것들은 \"대기\"되는 대신에 (스레드풀로부터) 외부 스레드에서 호출됩니다.\n+서로를 필요로 하는 여러 의존성과 [하위 의존성](tutorial/dependencies/sub-dependencies.md){.internal-link target=_blank}을 함수 정의의 매개변수로 가질 수 있으며, 그중 일부는 `async def`로, 다른 일부는 일반 `def`로 생성되었을 수 있습니다. 그래도 정상 동작하며, 일반 `def`로 생성된 것들은 \"await\"되는 대신 (스레드풀에서) 외부 스레드에서 호출됩니다.\n \n-### 다른 유틸리티 함수\n+### 다른 유틸리티 함수 { #other-utility-functions }\n \n-직접 호출되는 다른 모든 유틸리티 함수는 일반적인 `def`나 `async def`로 생성될 수 있고 FastAPI는 이를 호출하는 방식에 영향을 미치지 않습니다.\n+직접 호출하는 다른 모든 유틸리티 함수는 일반 `def`나 `async def`로 생성될 수 있으며, FastAPI는 호출 방식에 영향을 주지 않습니다.\n \n-이것은 FastAPI가 당신을 위해 호출하는 함수와는 반대입니다: *경로 작동 함수*와 의존성\n+이는 FastAPI가 여러분을 위해 호출하는 함수(즉, *경로 처리 함수*와 의존성)와 대비됩니다.\n \n-만약 당신의 유틸리티 함수가 `def`를 사용한 일반적인 함수라면, 스레드풀에서가 아니라 직접 호출(당신이 코드에 작성한 대로)될 것이고, `async def`로 생성된 함수라면 코드에서 호출할 때 그 함수를 `await` 해야 합니다.\n+유틸리티 함수가 `def`로 만든 일반 함수라면, 스레드풀이 아니라 직접(코드에 작성한 대로) 호출됩니다. 그리고 `async def`로 생성된 함수라면, 코드에서 호출할 때 그 함수를 `await` 해야 합니다.\n \n ---\n \n-다시 말하지만, 이것은 당신이 이것에 대해 찾고있던 경우에 한해 유용할 매우 세부적인 기술사항입니다.\n+다시 말하지만, 이것들은 아마도 이를 찾고 있었던 경우에 유용한 매우 세부적인 기술사항입니다.\n \n-그렇지 않은 경우, 상기의 가이드라인만으로도 충분할 것입니다: [바쁘신 경우](#_1).\n+그렇지 않다면, 위 섹션의 가이드라인이면 충분합니다: 바쁘신가요?." }, { "filename": "docs/ko/docs/fastapi-cli.md", "status": "modified", "additions": 50, "deletions": 58, "changes": 108, "patch": "@@ -1,83 +1,75 @@\n-# FastAPI CLI\n+# FastAPI CLI { #fastapi-cli }\n \n-**FastAPI CLI**는 FastAPI 애플리케이션을 실행하고, 프로젝트를 관리하는 등 다양한 작업을 수행할 수 있는 커맨드 라인 프로그램입니다.\n+**FastAPI CLI**는 FastAPI 애플리케이션을 서빙하고, FastAPI 프로젝트를 관리하는 등 다양한 작업에 사용할 수 있는 커맨드 라인 프로그램입니다.\n \n-FastAPI를 설치할 때 (예: `pip install \"fastapi[standard]\"` 명령어를 사용할 경우), `fastapi-cli`라는 패키지가 포함됩니다. 이 패키지는 터미널에서 사용할 수 있는 `fastapi` 명령어를 제공합니다.\n+FastAPI를 설치할 때(예: `pip install \"fastapi[standard]\"`), `fastapi-cli`라는 패키지가 포함되며, 이 패키지는 터미널에서 `fastapi` 명령어를 제공합니다.\n \n-개발용으로 FastAPI 애플리케이션을 실행하려면 다음과 같이 `fastapi dev` 명령어를 사용할 수 있습니다:\n+개발용으로 FastAPI 애플리케이션을 실행하려면 `fastapi dev` 명령어를 사용할 수 있습니다:\n \n
      \n \n ```console\n-$ fastapi dev main.py\n-INFO Using path main.py\n-INFO Resolved absolute path /home/user/code/awesomeapp/main.py\n-INFO Searching for package file structure from directories with __init__.py files\n-INFO Importing from /home/user/code/awesomeapp\n-\n- ╭─ Python module file ─╮\n- │ │\n- │ 🐍 main.py │\n- │ │\n- ╰──────────────────────╯\n-\n-INFO Importing module main\n-INFO Found importable FastAPI app\n-\n- ╭─ [NAME_REDACTED] app ─╮\n- │ │\n- │ from main import app │\n- │ │\n- ╰──────────────────────────╯\n-\n-INFO Using import string main:app\n-\n- ╭────────── FastAPI CLI - Development mode ───────────╮\n- │ │\n- │ Serving at: http://127.0.0.1:8000 │\n- │ │\n- │ API docs: http://127.0.0.1:8000/docs │\n- │ │\n- │ Running in development mode, for production use: │\n- │ │\n- fastapi run\n- │ │\n- ╰─────────────────────────────────────────────────────╯\n-\n-INFO: Will watch for changes in these directories: ['/home/user/code/awesomeapp']\n-INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit)\n-INFO: Started reloader process [2265862] using WatchFiles\n-INFO: Started server process [2265873]\n-INFO: Waiting for application startup.\n-INFO: Application startup complete.\n+$ fastapi dev main.py\n+\n+ FastAPI Starting development server 🚀\n+\n+ Searching for package file structure from directories with\n+ __init__.py files\n+ Importing from /home/user/code/awesomeapp\n+\n+ module 🐍 main.py\n+\n+ code Importing the FastAPI app object from the module with the\n+ following code:\n+\n+ from main import app\n+\n+ app Using import string: main:app\n+\n+ server Server started at http://127.0.0.1:8000\n+ server Documentation at http://127.0.0.1:8000/docs\n+\n+ tip Running in development mode, for production use:\n+ fastapi run\n+\n+ Logs:\n+\n+ INFO Will watch for changes in these directories:\n+ ['/home/user/code/awesomeapp']\n+ INFO Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to\n+ quit)\n+ INFO Started reloader process [383138] using WatchFiles\n+ INFO Started server process [383153]\n+ INFO Waiting for application startup.\n+ INFO Application startup complete.\n ```\n \n
      \n \n-`fastapi`라고 불리는 명령어 프로그램은 **FastAPI CLI**입니다.\n+`fastapi`라고 불리는 커맨드 라인 프로그램은 **FastAPI CLI**입니다.\n \n-FastAPI CLI는 Python 프로그램의 경로(예: `main.py`)를 인수로 받아, `FastAPI` 인스턴스(일반적으로 `app`으로 명명)를 자동으로 감지하고 올바른 임포트 과정을 결정한 후 이를 실행합니다.\n+FastAPI CLI는 Python 프로그램의 경로(예: `main.py`)를 받아 `FastAPI` 인스턴스(일반적으로 `app`으로 이름을 붙임)를 자동으로 감지하고, 올바른 임포트 과정을 결정한 다음 서빙합니다.\n \n-프로덕션 환경에서는 `fastapi run` 명령어를 사용합니다. 🚀\n+프로덕션에서는 대신 `fastapi run`을 사용합니다. 🚀\n \n-내부적으로, **FastAPI CLI**는 고성능의, 프로덕션에 적합한, ASGI 서버인 Uvicorn을 사용합니다. 😎\n+내부적으로 **FastAPI CLI**는 고성능의, 프로덕션에 적합한 ASGI 서버인 Uvicorn을 사용합니다. 😎\n \n-## `fastapi dev`\n+## `fastapi dev` { #fastapi-dev }\n \n-`fastapi dev` 명령을 실행하면 개발 모드가 시작됩니다.\n+`fastapi dev`를 실행하면 개발 모드가 시작됩니다.\n \n-기본적으로 **자동 재시작(auto-reload)** 기능이 활성화되어, 코드에 변경이 생기면 서버를 자동으로 다시 시작합니다. 하지만 이 기능은 리소스를 많이 사용하며, 비활성화했을 때보다 안정성이 떨어질 수 있습니다. 따라서 개발 환경에서만 사용하는 것이 좋습니다. 또한, 서버는 컴퓨터가 자체적으로 통신할 수 있는 IP 주소(`localhost`)인 `127.0.0.1`에서 연결을 대기합니다.\n+기본적으로 **auto-reload**가 활성화되어 코드에 변경이 생기면 서버를 자동으로 다시 로드합니다. 이는 리소스를 많이 사용하며, 비활성화했을 때보다 안정성이 떨어질 수 있습니다. 개발 환경에서만 사용해야 합니다. 또한 컴퓨터가 자신과만 통신하기 위한(`localhost`) IP인 `127.0.0.1`에서 연결을 대기합니다.\n \n-## `fastapi run`\n+## `fastapi run` { #fastapi-run }\n \n-`fastapi run` 명령을 실행하면 기본적으로 프로덕션 모드로 FastAPI가 시작됩니다.\n+`fastapi run`을 실행하면 기본적으로 프로덕션 모드로 FastAPI가 시작됩니다.\n \n-기본적으로 **자동 재시작(auto-reload)** 기능이 비활성화되어 있습니다. 또한, 사용 가능한 모든 IP 주소인 `0.0.0.0`에서 연결을 대기하므로 해당 컴퓨터와 통신할 수 있는 모든 사람이 공개적으로 액세스할 수 있습니다. 이는 일반적으로 컨테이너와 같은 프로덕션 환경에서 실행하는 방법입니다.\n+기본적으로 **auto-reload**는 비활성화되어 있습니다. 또한 사용 가능한 모든 IP 주소를 의미하는 `0.0.0.0`에서 연결을 대기하므로, 해당 컴퓨터와 통신할 수 있는 누구에게나 공개적으로 접근 가능해집니다. 보통 프로덕션에서는 이렇게 실행하며, 예를 들어 컨테이너에서 이런 방식으로 실행합니다.\n \n-애플리케이션을 배포하는 방식에 따라 다르지만, 대부분 \"종료 프록시(termination proxy)\"를 활용해 HTTPS를 처리하는 것이 좋습니다. 배포 서비스 제공자가 이 작업을 대신 처리해줄 수도 있고, 직접 설정해야 할 수도 있습니다.\n+대부분의 경우 위에 \"termination proxy\"를 두고 HTTPS를 처리하게(그리고 처리해야) 됩니다. 이는 애플리케이션을 배포하는 방식에 따라 달라지며, 제공자가 이 작업을 대신 처리해줄 수도 있고 직접 설정해야 할 수도 있습니다.\n \n-/// tip\n+/// tip | 팁\n \n-자세한 내용은 [deployment documentation](deployment/index.md){.internal-link target=\\_blank}에서 확인할 수 있습니다.\n+자세한 내용은 [배포 문서](deployment/index.md){.internal-link target=_blank}에서 확인할 수 있습니다.\n \n ///" }, { "filename": "docs/ko/docs/features.md", "status": "modified", "additions": 88, "deletions": 88, "changes": 176, "patch": "@@ -1,43 +1,43 @@\n-# 기능\n+# 기능 { #features }\n \n-## FastAPI의 기능\n+## FastAPI의 기능 { #fastapi-features }\n \n **FastAPI**는 다음과 같은 기능을 제공합니다:\n \n-### 개방형 표준을 기반으로\n+### 개방형 표준을 기반으로 { #based-on-open-standards }\n \n-* 경로작동, 매개변수, 본문 요청, 보안 그 외의 선언을 포함한 API 생성을 위한 OpenAPI\n-* JSON Schema (OpenAPI 자체가 JSON Schema를 기반으로 하고 있습니다)를 사용한 자동 데이터 모델 문서화.\n-* 단순히 떠올려서 덧붙인 기능이 아닙니다. 세심한 검토를 거친 후, 이러한 표준을 기반으로 설계되었습니다.\n-* 이는 또한 다양한 언어로 자동적인 **클라이언트 코드 생성**을 사용할 수 있게 지원합니다.\n+* OpenAPI: path operations, 매개변수, 요청 본문, 보안 등의 선언을 포함하여 API를 생성합니다.\n+* JSON Schema를 사용한 자동 데이터 모델 문서화(OpenAPI 자체가 JSON Schema를 기반으로 하기 때문입니다).\n+* 단순히 떠올려서 덧붙인 레이어가 아니라, 세심한 검토를 거친 뒤 이러한 표준을 중심으로 설계되었습니다.\n+* 이는 또한 다양한 언어로 자동 **클라이언트 코드 생성**을 사용할 수 있게 해줍니다.\n \n-### 문서 자동화\n+### 문서 자동화 { #automatic-docs }\n \n-대화형 API 문서와 웹 탐색 유저 인터페이스를 제공합니다. 프레임워크가 OpenAPI를 기반으로 하기에, 2가지 옵션이 기본적으로 들어간 여러 옵션이 존재합니다.\n+대화형 API 문서와 탐색용 웹 사용자 인터페이스를 제공합니다. 프레임워크가 OpenAPI를 기반으로 하기에 여러 옵션이 있으며, 기본으로 2가지가 포함됩니다.\n \n-* 대화형 탐색 Swagger UI를 이용해, 브라우저에서 바로 여러분의 API를 호출하거나 테스트할 수 있습니다.\n+* 대화형 탐색이 가능한 Swagger UI로 브라우저에서 직접 API를 호출하고 테스트할 수 있습니다.\n \n ![Swagger UI interaction](https://fastapi.tiangolo.com/img/index/index-03-swagger-02.png)\n \n-* ReDoc을 이용해 API 문서화를 대체할 수 있습니다.\n+* ReDoc을 이용한 대체 API 문서화.\n \n ![ReDoc](https://fastapi.tiangolo.com/img/index/index-06-redoc-02.png)\n \n-### 그저 현대 파이썬\n+### 그저 현대 파이썬 { #just-modern-python }\n \n-(Pydantic 덕분에) FastAPI는 표준 **파이썬 3.6 타입** 선언에 기반하고 있습니다. 새로 배울 문법이 없습니다. 그저 표준적인 현대 파이썬입니다.\n+( Pydantic 덕분에) 모든 것이 표준 **Python 타입** 선언을 기반으로 합니다. 새로 배울 문법이 없습니다. 그저 표준적인 현대 파이썬입니다.\n \n-만약 여러분이 파이썬 타입을 어떻게 사용하는지에 대한 2분 정도의 복습이 필요하다면 (비록 여러분이 FastAPI를 사용하지 않는다 하더라도), 다음의 짧은 자습서를 확인하세요: [파이썬 타입](python-types.md){.internal-link target=\\_blank}.\n+Python 타입을 어떻게 사용하는지 2분 정도 복습이 필요하다면(FastAPI를 사용하지 않더라도), 다음의 짧은 자습서를 확인하세요: [Python 타입](python-types.md){.internal-link target=_blank}.\n \n-여러분은 타입을 이용한 표준 파이썬을 다음과 같이 적을 수 있습니다:\n+여러분은 타입이 있는 표준 Python을 다음과 같이 작성합니다:\n \n ```Python\n from datetime import date\n \n from pydantic import BaseModel\n \n-# 변수를 str로 선언\n-# 그 후 함수 안에서 편집기 지원을 받으세요\n+# 변수를 str로 선언합니다\n+# 그리고 함수 내부에서 편집기 지원을 받습니다\n def main(user_id: str):\n return user_id\n \n@@ -49,7 +49,7 @@ class User(BaseModel):\n joined: date\n ```\n \n-위의 코드는 다음과 같이 사용될 수 있습니다:\n+그 다음 다음과 같이 사용할 수 있습니다:\n \n ```Python\n my_user: User = User(id=3, name=\"[NAME_REDACTED]\", joined=\"2018-07-19\")\n@@ -65,23 +65,23 @@ my_second_user: User = User(**second_user_data)\n \n /// info | 정보\n \n-`**second_user_data`가 뜻하는 것:\n+`**second_user_data`는 다음을 의미합니다:\n \n-`second_user_data` 딕셔너리의 키와 값을 키-값 인자로서 바로 넘겨줍니다. 다음과 동일합니다: `User(id=4, name=\"Mary\", joined=\"2018-11-30\")`\n+`second_user_data` `dict`의 키와 값을 키-값 인자로서 바로 넘겨주는 것으로, 다음과 동일합니다: `User(id=4, name=\"Mary\", joined=\"2018-11-30\")`\n \n ///\n \n-### 편집기 지원\n+### 편집기 지원 { #editor-support }\n \n-모든 프레임워크는 사용하기 쉽고 직관적으로 설계되었으며, 좋은 개발 경험을 보장하기 위해 개발을 시작하기도 전에 모든 결정들은 여러 편집기에서 테스트됩니다.\n+프레임워크 전체는 사용하기 쉽고 직관적으로 설계되었으며, 최고의 개발 경험을 보장하기 위해 개발을 시작하기도 전에 모든 결정은 여러 편집기에서 테스트되었습니다.\n \n-최근 파이썬 개발자 설문조사에서 \"자동 완성\"이 가장 많이 사용되는 기능이라는 것이 밝혀졌습니다.\n+Python 개발자 설문조사에서 가장 많이 사용되는 기능 중 하나가 \"자동 완성\"이라는 점이 분명합니다.\n \n-**FastAPI** 프레임워크의 모든 부분은 이를 충족하기 위해 설계되었습니다. 자동완성은 어느 곳에서나 작동합니다.\n+**FastAPI** 프레임워크 전체는 이를 만족하기 위해 만들어졌습니다. 자동 완성은 어디서나 작동합니다.\n \n-여러분은 문서로 다시 돌아올 일이 거의 없을 겁니다.\n+문서로 다시 돌아올 일은 거의 없을 것입니다.\n \n-다음은 편집기가 어떻게 여러분을 도와주는지 보여줍니다:\n+편집기가 여러분을 어떻게 도와줄 수 있는지 살펴보세요:\n \n * [NAME_REDACTED]에서:\n \n@@ -91,111 +91,111 @@ my_second_user: User = User(**second_user_data)\n \n ![editor support](https://fastapi.tiangolo.com/img/pycharm-completion.png)\n \n-여러분이 이전에 불가능하다고 고려했던 코드도 완성할 수 있을 겁니다. 예를 들어, 요청에서 전달되는 (중첩될 수도 있는)JSON 본문 내부에 있는 `price` 키입니다.\n+이전에 불가능하다고 생각했을 코드에서도 자동 완성을 받을 수 있습니다. 예를 들어, 요청에서 전달되는(중첩될 수도 있는) JSON 본문 내부의 `price` 키 같은 경우입니다.\n \n-잘못된 키 이름을 적을 일도, 문서를 왔다 갔다할 일도 없으며, 혹은 마지막으로 `username` 또는 `user_name`을 사용했는지 찾기 위해 위 아래로 스크롤할 일도 없습니다.\n+더 이상 잘못된 키 이름을 입력하거나, 문서 사이를 왔다 갔다 하거나, `username`을 썼는지 `user_name`을 썼는지 찾으려고 위아래로 스크롤할 필요가 없습니다.\n \n-### 토막 정보\n+### 간결함 { #short }\n \n-어느 곳에서나 선택적 구성이 가능한 모든 것에 합리적인 기본값이 설정되어 있습니다. 모든 매개변수는 여러분이 필요하거나, 원하는 API를 정의하기 위해 미세하게 조정할 수 있습니다.\n+선택적 구성을 어디서나 할 수 있도록 하면서도, 모든 것에 합리적인 **기본값**이 설정되어 있습니다. 모든 매개변수는 필요한 작업을 하거나 필요한 API를 정의하기 위해 미세하게 조정할 수 있습니다.\n \n-하지만 기본적으로 모든 것이 \"그냥 작동합니다\".\n+하지만 기본적으로 모든 것이 **\"그냥 작동합니다\"**.\n \n-### 검증\n+### 검증 { #validation }\n \n-* 다음을 포함한, 대부분의 (혹은 모든?) 파이썬 **데이터 타입** 검증할 수 있습니다:\n+* 다음을 포함해 대부분(혹은 전부?)의 Python **데이터 타입**에 대한 검증:\n * JSON 객체 (`dict`).\n * 아이템 타입을 정의하는 JSON 배열 (`list`).\n- * 최소 길이와 최대 길이를 정의하는 문자열 (`str`) 필드.\n- * 최솟값과 최댓값을 가지는 숫자 (`int`, `float`), 그 외.\n+ * 최소/최대 길이를 정의하는 문자열(`str`) 필드.\n+ * 최소/최대 값을 가지는 숫자(`int`, `float`) 등.\n \n-* 다음과 같이 더욱 이색적인 타입에 대해 검증할 수 있습니다:\n+* 다음과 같은 좀 더 이색적인 타입에 대한 검증:\n * URL.\n- * 이메일.\n+ * Email.\n * UUID.\n- * ...다른 것들.\n+ * ...그 외.\n \n-모든 검증은 견고하면서 잘 확립된 **Pydantic**에 의해 처리됩니다.\n+모든 검증은 잘 확립되어 있고 견고한 **Pydantic**이 처리합니다.\n \n-### 보안과 인증\n+### 보안과 인증 { #security-and-authentication }\n \n-보안과 인증이 통합되어 있습니다. 데이터베이스나 데이터 모델과의 타협없이 사용할 수 있습니다.\n+보안과 인증이 통합되어 있습니다. 데이터베이스나 데이터 모델과 타협하지 않습니다.\n \n-다음을 포함하는, 모든 보안 스키마가 OpenAPI에 정의되어 있습니다.\n+다음을 포함해 OpenAPI에 정의된 모든 보안 스키마:\n \n * HTTP Basic.\n-* **OAuth2** (**JWT tokens** 또한 포함). [OAuth2 with JWT](tutorial/security/oauth2-jwt.md){.internal-link target=\\_blank}에 있는 자습서를 확인해 보세요.\n+* **OAuth2**(**JWT tokens** 또한 포함). [JWT를 사용한 OAuth2](tutorial/security/oauth2-jwt.md){.internal-link target=_blank} 자습서를 확인해 보세요.\n * 다음에 들어 있는 API 키:\n * 헤더.\n- * 매개변수.\n- * 쿠키 및 그 외.\n+ * 쿼리 매개변수.\n+ * 쿠키 등.\n \n-추가적으로 (**세션 쿠키**를 포함한) 모든 보안 기능은 Starlette에 있습니다.\n+추가로 Starlette의 모든 보안 기능(**세션 쿠키** 포함)도 제공합니다.\n \n-모두 재사용할 수 있는 도구와 컴포넌트로 만들어져 있어 여러분의 시스템, 데이터 저장소, 관계형 및 NoSQL 데이터베이스 등과 쉽게 통합할 수 있습니다.\n+모두 재사용 가능한 도구와 컴포넌트로 만들어져 있어, 여러분의 시스템, 데이터 저장소, 관계형 및 NoSQL 데이터베이스 등과 쉽게 통합할 수 있습니다.\n \n-### 의존성 주입\n+### 의존성 주입 { #dependency-injection }\n \n-FastAPI는 사용하기 매우 간편하지만, 엄청난 의존성 주입시스템을 포함하고 있습니다.\n+FastAPI는 사용하기 매우 쉽지만, 매우 강력한 [NAME_REDACTED] 시스템을 포함하고 있습니다.\n \n-* 의존성은 의존성을 가질수도 있어, 이를 통해 의존성의 계층이나 **의존성의 \"그래프\"**를 형성합니다.\n-* 모든 것이 프레임워크에 의해 **자동적으로 처리됩니다**.\n-* 모든 의존성은 요청에서 데이터를 요구하여 자동 문서화와 **경로 작동 제약을 강화할 수 있습니다**.\n-* 의존성에서 정의된 _경로 작동_ 매개변수에 대해서도 **자동 검증**이 이루어 집니다.\n-* 복잡한 사용자의 인증 시스템, **데이터베이스 연결**, 등등을 지원합니다.\n-* 데이터베이스, 프론트엔드 등과 관련되어 **타협하지 않아도 됩니다**. 하지만 그 모든 것과 쉽게 통합이 가능합니다.\n+* 의존성도 의존성을 가질 수 있어, 의존성의 계층 또는 **의존성의 \"그래프\"**를 생성합니다.\n+* 모든 것이 프레임워크에 의해 **자동으로 처리됩니다**.\n+* 모든 의존성은 요청에서 데이터를 요구할 수 있으며, **경로 처리** 제약과 자동 문서화를 강화할 수 있습니다.\n+* 의존성에 정의된 *경로 처리* 매개변수에 대해서도 **자동 검증**을 합니다.\n+* 복잡한 사용자 인증 시스템, **데이터베이스 연결** 등을 지원합니다.\n+* 데이터베이스, 프론트엔드 등과 **타협하지 않습니다**. 하지만 모두와 쉽게 통합할 수 있습니다.\n \n-### 제한 없는 \"플러그인\"\n+### 제한 없는 \"플러그인\" { #unlimited-plug-ins }\n \n-또는 다른 방법으로, 그것들을 사용할 필요 없이 필요한 코드만 임포트할 수 있습니다.\n+또 다른 방식으로는, 그것들이 필요 없습니다. 필요한 코드를 임포트해서 사용하면 됩니다.\n \n-어느 통합도 (의존성과 함께) 사용하기 쉽게 설계되어 있어, *경로 작동*에 사용된 것과 동일한 구조와 문법을 사용하여 2줄의 코드로 여러분의 어플리케이션에 사용할 \"플러그인\"을 만들 수 있습니다.\n+어떤 통합이든(의존성과 함께) 사용하기 매우 간단하도록 설계되어 있어, *경로 처리*에 사용된 것과 동일한 구조와 문법을 사용해 2줄의 코드로 애플리케이션용 \"플러그인\"을 만들 수 있습니다.\n \n-### 테스트 결과\n+### 테스트됨 { #tested }\n \n-* 100% 테스트 범위.\n-* 100% 타입이 명시된 코드 베이스.\n-* 상용 어플리케이션에서의 사용.\n+* 100% test coverage.\n+* 100% type annotated 코드 베이스.\n+* 프로덕션 애플리케이션에서 사용됩니다.\n \n-## Starlette 기능\n+## Starlette 기능 { #starlette-features }\n \n-**FastAPI**는 Starlette를 기반으로 구축되었으며, 이와 완전히 호환됩니다. 따라서, 여러분이 보유하고 있는 어떤 추가적인 Starlette 코드도 작동할 것입니다.\n+**FastAPI**는 Starlette와 완전히 호환되며(또한 이를 기반으로 합니다). 따라서 추가로 가지고 있는 Starlette 코드도 모두 동작합니다.\n \n-`FastAPI`는 실제로 `Starlette`의 하위 클래스입니다. 그래서, 여러분이 이미 Starlette을 알고 있거나 사용하고 있으면, 대부분의 기능이 같은 방식으로 작동할 것입니다.\n+`FastAPI`는 실제로 `Starlette`의 하위 클래스입니다. 그래서 Starlette을 이미 알고 있거나 사용하고 있다면, 대부분의 기능이 같은 방식으로 동작할 것입니다.\n \n-**FastAPI**를 사용하면 여러분은 **Starlette**의 기능 대부분을 얻게 될 것입니다(FastAPI가 단순히 Starlette를 강화했기 때문입니다):\n+**FastAPI**를 사용하면 **Starlette**의 모든 기능을 얻게 됩니다(FastAPI는 Starlette에 강력한 기능을 더한 것입니다):\n \n-* 아주 인상적인 성능. 이는 **NodeJS**와 **Go**와 동등하게 사용 가능한 가장 빠른 파이썬 프레임워크 중 하나입니다.\n+* 정말 인상적인 성능. **NodeJS**와 **Go**에 버금가는, 사용 가능한 가장 빠른 Python 프레임워크 중 하나입니다.\n * **WebSocket** 지원.\n-* 프로세스 내의 백그라운드 작업.\n-* 시작과 종료 이벤트.\n+* 프로세스 내 백그라운드 작업.\n+* 시작 및 종료 이벤트.\n * HTTPX 기반 테스트 클라이언트.\n * **CORS**, GZip, 정적 파일, 스트리밍 응답.\n * **세션과 쿠키** 지원.\n-* 100% 테스트 범위.\n-* 100% 타입이 명시된 코드 베이스.\n+* 100% test coverage.\n+* 100% type annotated codebase.\n \n-## Pydantic 기능\n+## Pydantic 기능 { #pydantic-features }\n \n-**FastAPI**는 Pydantic을 기반으로 하며 Pydantic과 완벽하게 호환됩니다. 그래서 어느 추가적인 Pydantic 코드를 여러분이 가지고 있든 작동할 것입니다.\n+**FastAPI**는 Pydantic과 완벽하게 호환되며(또한 이를 기반으로 합니다). 따라서 추가로 가지고 있는 Pydantic 코드도 모두 동작합니다.\n \n-Pydantic을 기반으로 하는, 데이터베이스를 위한 ORM, ODM을 포함한 외부 라이브러리를 포함합니다.\n+데이터베이스를 위한 ORM, ODM과 같은, Pydantic을 기반으로 하는 외부 라이브러리도 포함합니다.\n \n-이는 모든 것이 자동으로 검증되기 때문에, 많은 경우에서 요청을 통해 얻은 동일한 객체를, **직접 데이터베이스로** 넘겨줄 수 있습니다.\n+이는 모든 것이 자동으로 검증되기 때문에, 많은 경우 요청에서 얻은 동일한 객체를 **직접 데이터베이스로** 넘겨줄 수 있다는 의미이기도 합니다.\n \n-반대로도 마찬가지이며, 많은 경우에서 여러분은 **직접 클라이언트로** 그저 객체를 넘겨줄 수 있습니다.\n+반대로도 마찬가지이며, 많은 경우 데이터베이스에서 얻은 객체를 **직접 클라이언트로** 그대로 넘겨줄 수 있습니다.\n \n-**FastAPI**를 사용하면 (모든 데이터 처리를 위해 FastAPI가 Pydantic을 기반으로 하기 있기에) **Pydantic**의 모든 기능을 얻게 됩니다:\n+**FastAPI**를 사용하면(모든 데이터 처리를 위해 FastAPI가 Pydantic을 기반으로 하기에) **Pydantic**의 모든 기능을 얻게 됩니다:\n \n-* **어렵지 않은 언어**:\n- * 새로운 스키마 정의 마이크로 언어를 배우지 않아도 됩니다.\n- * 여러분이 파이썬 타입을 안다면, 여러분은 Pydantic을 어떻게 사용하는지 아는 겁니다.\n-* 여러분의 **IDE/린터/뇌**와 잘 어울립니다:\n- * Pydantic 데이터 구조는 단순 여러분이 정의한 클래스의 인스턴스이기 때문에, 자동 완성, 린팅, mypy 그리고 여러분의 직관까지 여러분의 검증된 데이터와 올바르게 작동합니다.\n+* **No brainfuck**:\n+ * 새로운 스키마 정의 마이크로 언어를 배울 필요가 없습니다.\n+ * Python 타입을 알고 있다면 Pydantic 사용법도 알고 있는 것입니다.\n+* 여러분의 **IDE/linter/뇌**와 잘 어울립니다:\n+ * pydantic 데이터 구조는 여러분이 정의한 클래스 인스턴스일 뿐이므로, 자동 완성, 린팅, mypy, 그리고 직관까지도 검증된 데이터와 함께 제대로 작동합니다.\n * **복잡한 구조**를 검증합니다:\n- * 계층적인 Pydantic 모델, 파이썬 `typing`의 `List`와 `Dict`, 그 외를 사용합니다.\n- * 그리고 검증자는 복잡한 데이터 스키마를 명확하고 쉽게 정의 및 확인하며 JSON 스키마로 문서화합니다.\n- * 여러분은 깊게 **중첩된 JSON** 객체를 가질 수 있으며, 이 객체 모두 검증하고 설명을 붙일 수 있습니다.\n-* **확장 가능성**:\n- * Pydantic은 사용자 정의 데이터 타입을 정의할 수 있게 하거나, 검증자 데코레이터가 붙은 모델의 메소드를 사용하여 검증을 확장할 수 있습니다.\n-* 100% 테스트 범위.\n+ * 계층적인 Pydantic 모델, Python `typing`의 `List`와 `Dict` 등을 사용합니다.\n+ * 그리고 validator는 복잡한 데이터 스키마를 명확하고 쉽게 정의하고, 검사하고, JSON Schema로 문서화할 수 있게 해줍니다.\n+ * 깊게 **중첩된 JSON** 객체를 가질 수 있으며, 이를 모두 검증하고 주석을 달 수 있습니다.\n+* **확장 가능**:\n+ * Pydantic은 사용자 정의 데이터 타입을 정의할 수 있게 하거나, validator decorator가 붙은 모델 메서드로 검증을 확장할 수 있습니다.\n+* 100% test coverage." }, { "filename": "docs/ko/docs/help-fastapi.md", "status": "modified", "additions": 93, "deletions": 106, "changes": 199, "patch": "@@ -1,4 +1,4 @@\n-# FastAPI 지원 - 도움 받기\n+# FastAPI 지원 - 도움 받기 { #help-fastapi-get-help }\n \n **FastAPI** 가 마음에 드시나요?\n \n@@ -10,259 +10,246 @@ FastAPI, 다른 사용자, 개발자를 응원하고 싶으신가요?\n \n 또한 도움을 받을 수 있는 방법도 몇 가지 있습니다.\n \n-## 뉴스레터 구독\n+## 뉴스레터 구독 { #subscribe-to-the-newsletter }\n \n-[**FastAPI and friends** 뉴스레터](newsletter.md){.internal-link target=\\_blank}를 구독하여 최신 정보를 유지할 수 있습니다:\n+(자주 발송되지 않는) [**FastAPI and friends** 뉴스레터](newsletter.md){.internal-link target=_blank}를 구독하여 최신 정보를 유지할 수 있습니다:\n \n * FastAPI and friends에 대한 뉴스 🚀\n * 가이드 📝\n * 기능 ✨\n * 획기적인 변화 🚨\n * 팁과 요령 ✅\n \n-## 트위터에서 FastAPI 팔로우하기\n+## X(Twitter)에서 FastAPI 팔로우하기 { #follow-fastapi-on-x-twitter }\n \n **X (Twitter)**의 [USER_REDACTED]를 팔로우하여 **FastAPI** 에 대한 최신 뉴스를 얻을 수 있습니다. 🐦\n \n-## Star **FastAPI** in GitHub\n+## GitHub에서 **FastAPI**에 Star 주기 { #star-fastapi-in-github }\n \n GitHub에서 FastAPI에 \"star\"를 붙일 수 있습니다 (오른쪽 상단의 star 버튼을 클릭): https://github.com/fastapi/fastapi. ⭐️\n \n 스타를 늘림으로써, 다른 사용자들이 좀 더 쉽게 찾을 수 있고, 많은 사람들에게 유용한 것임을 나타낼 수 있습니다.\n \n-## GitHub 저장소에서 릴리즈 확인\n+## 릴리즈 확인을 위해 GitHub 저장소 보기 { #watch-the-github-repository-for-releases }\n \n-GitHub에서 FastAPI를 \"watch\"할 수 있습니다 (오른쪽 상단 watch 버튼을 클릭): https://github.com/fastapi/fastapi. 👀\n+GitHub에서 FastAPI를 \"watch\"할 수 있습니다 (오른쪽 상단 \"watch\" 버튼을 클릭): https://github.com/fastapi/fastapi. 👀\n \n-여기서 \"Releases only\"을 선택할 수 있습니다.\n+여기서 \"Releases only\"를 선택할 수 있습니다.\n \n-이렇게하면, **FastAPI** 의 버그 수정 및 새로운 기능의 구현 등의 새로운 자료 (최신 버전)이 있을 때마다 (이메일) 통지를 받을 수 있습니다.\n+이렇게하면, **FastAPI** 의 버그 수정 및 새로운 기능의 구현 등의 새로운 릴리즈(새 버전)가 있을 때마다 (이메일) 통지를 받을 수 있습니다.\n \n-## 개발자와의 연결\n+## 개발자와의 연결 { #connect-with-the-author }\n \n-개발자(Sebastián Ramírez / `tiangolo`)와 연락을 취할 수 있습니다.\n+개발자(작성자)인 저(Sebastián Ramírez / `tiangolo`)와 연락을 취할 수 있습니다.\n \n 여러분은 할 수 있습니다:\n \n-* **GitHub**에서 팔로우하기..\n- * 당신에게 도움이 될 저의 다른 오픈소스 프로젝트를 확인하십시오.\n+* **GitHub**에서 팔로우하기.\n+ * 여러분에게 도움이 될 저의 다른 오픈소스 프로젝트를 확인하십시오.\n * 새로운 오픈소스 프로젝트를 만들었을 때 확인하려면 팔로우 하십시오.\n * **X (Twitter)** 또는 Mastodon에서 팔로우하기.\n * FastAPI의 사용 용도를 알려주세요 (그것을 듣는 것을 좋아합니다).\n * 발표나 새로운 툴 출시 소식을 받아보십시오.\n- * **X (Twitter)**의 [USER_REDACTED]를 팔로우 (별도 계정에서) 할 수 있습니다.\n-* **LinkedIn**에서 팔로우하기..\n- * 새로운 툴의 발표나 출시 소식을 받아보십시오. (단, X (Twitter)를 더 자주 사용합니다 🤷‍♂).\n+ * X(Twitter)에서 [USER_REDACTED]를 팔로우 (별도 계정에서) 할 수 있습니다.\n+* **LinkedIn**에서 팔로우하기.\n+ * 새로운 툴의 발표나 출시 소식을 받아보십시오 (단, X (Twitter)를 더 자주 사용합니다 🤷‍♂).\n * **Dev.to** 또는 **Medium**에서 제가 작성한 내용을 읽어 보십시오 (또는 팔로우).\n- * 다른 기사나 아이디어들을 읽고, 제가 만들어왔던 툴에 대해서도 읽으십시오.\n- * 새로운 기사를 읽기 위해 팔로우 하십시오.\n+ * 다른 아이디어와 기사들을 읽고, 제가 만들어왔던 툴에 대해서도 읽으십시오.\n+ * 새로운 내용을 게시할 때 읽기 위해 팔로우 하십시오.\n \n-## **FastAPI**에 대한 트윗\n+## **FastAPI**에 대해 트윗하기 { #tweet-about-fastapi }\n \n-**FastAPI**에 대해 트윗 하고 FastAPI가 마음에 드는 이유를 알려주세요. 🎉\n+**FastAPI**에 대해 트윗 하고 저와 다른 사람들에게 FastAPI가 마음에 드는 이유를 알려주세요. 🎉\n \n **FastAPI**가 어떻게 사용되고 있는지, 어떤 점이 마음에 들었는지, 어떤 프로젝트/회사에서 사용하고 있는지 등에 대해 듣고 싶습니다.\n \n-## FastAPI에 투표하기\n+## FastAPI에 투표하기 { #vote-for-fastapi }\n \n * Slant에서 **FastAPI** 에 대해 투표하십시오.\n * AlternativeTo에서 **FastAPI** 에 대해 투표하십시오.\n-* StackShare에서 **FastAPI** 에 대해 투표하십시오.\n+* StackShare에서 **FastAPI**를 사용한다고 표시하세요.\n \n-## GitHub의 이슈로 다른사람 돕기\n+## GitHub에서 질문으로 다른 사람 돕기 { #help-others-with-questions-in-github }\n \n 다른 사람들의 질문에 도움을 줄 수 있습니다:\n \n-* GitHub 디스커션\n-* GitHub 이슈\n+* [NAME_REDACTED]\n+* [NAME_REDACTED]\n \n 많은 경우, 여러분은 이미 그 질문에 대한 답을 알고 있을 수도 있습니다. 🤓\n \n-만약 많은 사람들의 문제를 도와준다면, 공식적인 [FastAPI 전문가](fastapi-people.md#fastapi-experts){.internal-link target=\\_blank} 가 될 것입니다. 🎉\n+만약 많은 사람들의 질문을 도와준다면, 공식적인 [FastAPI 전문가](fastapi-people.md#fastapi-experts){.internal-link target=_blank}가 될 것입니다. 🎉\n \n 가장 중요한 점은: 친절하려고 노력하는 것입니다. 사람들은 좌절감을 안고 오며, 많은 경우 최선의 방식으로 질문하지 않을 수도 있습니다. 하지만 최대한 친절하게 대하려고 노력하세요. 🤗\n \n **FastAPI** 커뮤니티의 목표는 친절하고 환영하는 것입니다. 동시에, 괴롭힘이나 무례한 행동을 받아들이지 마세요. 우리는 서로를 돌봐야 합니다.\n \n ---\n \n-다른 사람들의 질문 (디스커션 또는 이슈에서) 해결을 도울 수 있는 방법은 다음과 같습니다.\n+다른 사람들의 질문(디스커션 또는 이슈에서) 해결을 도울 수 있는 방법은 다음과 같습니다.\n \n-### 질문 이해하기\n+### 질문 이해하기 { #understand-the-question }\n \n * 질문하는 사람이 가진 **목적**과 사용 사례를 이해할 수 있는지 확인하세요.\n \n-* 질문 (대부분은 질문입니다)이 **명확**한지 확인하세요.\n+* 그런 다음 질문(대부분은 질문입니다)이 **명확**한지 확인하세요.\n \n-* 많은 경우, 사용자가 가정한 해결책에 대한 질문을 하지만, 더 **좋은** 해결책이 있을 수 있습니다. 문제와 사용 사례를 더 잘 이해하면 더 나은 **대안적인 해결책**을 제안할 수 있습니다.\n+* 많은 경우 사용자가 상상한 해결책에 대한 질문을 하지만, 더 **좋은** 해결책이 있을 수 있습니다. 문제와 사용 사례를 더 잘 이해하면 더 나은 **대안적인 해결책**을 제안할 수 있습니다.\n \n * 질문을 이해할 수 없다면, 더 **자세한 정보**를 요청하세요.\n \n-### 문제 재현하기\n+### 문제 재현하기 { #reproduce-the-problem }\n \n-대부분의 경우, 질문은 질문자의 **원본 코드**와 관련이 있습니다.\n+대부분의 경우 그리고 대부분의 질문에서는 질문자의 **원본 코드**와 관련된 내용이 있습니다.\n \n 많은 경우, 코드의 일부만 복사해서 올리지만, 그것만으로는 **문제를 재현**하기에 충분하지 않습니다.\n \n-* 질문자에게 최소한의 재현 가능한 예제를 제공해달라고 요청하세요. 이렇게 하면 코드를 **복사-붙여넣기**하여 직접 실행하고, 동일한 오류나 동작을 확인하거나 사용 사례를 더 잘 이해할 수 있습니다.\n+* 질문자에게 최소한의 재현 가능한 예제를 제공해달라고 요청할 수 있습니다. 이렇게 하면 코드를 **복사-붙여넣기**하여 로컬에서 실행하고, 질문자가 보고 있는 것과 동일한 오류나 동작을 확인하거나 사용 사례를 더 잘 이해할 수 있습니다.\n \n-* 너그러운 마음이 든다면, 문제 설명만을 기반으로 직접 **예제를 만들어**볼 수도 있습니다. 하지만, 이는 시간이 많이 걸릴 수 있으므로, 먼저 질문을 명확히 해달라고 요청하는 것이 좋습니다.\n+* 너그러운 마음이 든다면, 문제 설명만을 기반으로 직접 **예제를 만들어**볼 수도 있습니다. 다만 이는 시간이 많이 걸릴 수 있으므로, 먼저 문제를 명확히 해달라고 요청하는 것이 더 나을 수 있다는 점을 기억하세요.\n \n-### 해결책 제안하기\n+### 해결책 제안하기 { #suggest-solutions }\n \n * 질문을 충분히 이해한 후에는 가능한 **답변**을 제공할 수 있습니다.\n \n-* 많은 경우, 질문자의 **근본적인 문제나 사용 사례**를 이해하는 것이 중요합니다. 그들이 시도하는 방법보다 더 나은 해결책이 있을 수 있기 때문입니다.\n+* 많은 경우, 질문자의 **근본적인 문제나 사용 사례**를 이해하는 것이 더 좋습니다. 그들이 시도하는 방법보다 더 나은 해결책이 있을 수 있기 때문입니다.\n \n-### 해결 요청하기\n+### 종료 요청하기 { #ask-to-close }\n \n-질문자가 답변을 확인하고 나면, 당신이 문제를 해결했을 가능성이 높습니다. 축하합니다, **당신은 영웅입니다**! 🦸\n+질문자가 답변을 하면, 여러분이 문제를 해결했을 가능성이 높습니다. 축하합니다, **여러분은 영웅입니다**! 🦸\n \n * 이제 문제를 해결했다면, 질문자에게 다음을 요청할 수 있습니다.\n \n- * GitHub 디스커션에서: 댓글을 **답변**으로 표시하도록 요청하세요.\n- * GitHub 이슈에서: 이슈를 **닫아달라고** 요청하세요.\n+ * GitHub Discussions에서: 댓글을 **답변**으로 표시하도록 요청하세요.\n+ * GitHub Issues에서: 이슈를 **닫아달라고** 요청하세요.\n \n-## GitHub 저장소 보기\n+## GitHub 저장소 보기 { #watch-the-github-repository }\n \n-GitHub에서 FastAPI를 \"watch\"할 수 있습니다 (오른쪽 상단 watch 버튼을 클릭): https://github.com/fastapi/fastapi. 👀\n+GitHub에서 FastAPI를 \"watch\"할 수 있습니다 (오른쪽 상단 \"watch\" 버튼을 클릭): https://github.com/fastapi/fastapi. 👀\n \n-\"Releases only\" 대신 \"Watching\"을 선택하면, 새로운 이슈나 질문이 생성될 때 알림을 받을 수 있습니다. 또한, 특정하게 새로운 이슈, 디스커션, PR 등만 알림 받도록 설정할 수도 있습니다.\n+\"Releases only\" 대신 \"Watching\"을 선택하면 누군가가 새 이슈나 질문을 만들 때 알림을 받게 됩니다. 또한 새 이슈, 디스커션, PR 등만 알림을 받도록 지정할 수도 있습니다.\n \n-그런 다음 이런 이슈들을 해결 할 수 있도록 도움을 줄 수 있습니다.\n+그런 다음 이런 질문들을 해결하도록 도와줄 수 있습니다.\n \n-## 이슈 생성하기\n+## 질문하기 { #ask-questions }\n \n-GitHub 저장소에 새로운 이슈 생성을 할 수 있습니다, 예를들면 다음과 같습니다:\n+GitHub 저장소에서 새 질문을 생성할 수 있습니다. 예를 들면 다음과 같습니다:\n \n * **질문**을 하거나 **문제**에 대해 질문합니다.\n * 새로운 **기능**을 제안 합니다.\n \n-**참고**: 만약 이슈를 생성한다면, 저는 여러분에게 다른 사람들을 도와달라고 부탁할 것입니다. 😉\n+**참고**: 만약 이렇게 한다면, 저는 여러분에게 다른 사람들도 도와달라고 요청할 것입니다. 😉\n \n-## Pull Requests 리뷰하기\n+## Pull Request 리뷰하기 { #review-pull-requests }\n \n-다른 사람들의 pull request를 리뷰하는 데 도움을 줄 수 있습니다.\n+다른 사람들이 만든 pull request를 리뷰하는 데 저를 도와줄 수 있습니다.\n \n 다시 한번 말하지만, 최대한 친절하게 리뷰해 주세요. 🤗\n \n ---\n \n-Pull Rrquest를 리뷰할 때 고려해야 할 사항과 방법은 다음과 같습니다:\n+Pull request를 리뷰할 때 고려해야 할 사항과 방법은 다음과 같습니다:\n \n-### 문제 이해하기\n+### 문제 이해하기 { #understand-the-problem }\n \n-* 먼저, 해당 pull request가 해결하려는 **문제를 이해하는지** 확인하세요. GitHub 디스커션 또는 이슈에서 더 긴 논의가 있었을 수도 있습니다.\n+* 먼저, 해당 pull request가 해결하려는 **문제를 이해하는지** 확인하세요. [NAME_REDACTED] 또는 이슈에서 더 긴 논의가 있었을 수도 있습니다.\n \n-* Pull request가 필요하지 않을 가능성도 있습니다. **다른 방식**으로 문제를 해결할 수 있다면, 그 방법을 제안하거나 질문할 수 있습니다.\n+* Pull request가 실제로 필요하지 않을 가능성도 큽니다. 문제가 **다른 방식**으로 해결될 수 있기 때문입니다. 그런 경우 그 방법을 제안하거나 질문할 수 있습니다.\n \n-### 스타일에 너무 신경 쓰지 않기\n+### 스타일에 너무 신경 쓰지 않기 { #dont-worry-about-style }\n \n-* 커밋 메시지 스타일 같은 것에 너무 신경 쓰지 않아도 됩니다. 저는 직접 커밋을 수정하여 squash and merge를 수행할 것입니다.\n+* 커밋 메시지 스타일 같은 것에 너무 신경 쓰지 마세요. 저는 커밋을 수동으로 조정해서 squash and merge를 할 것입니다.\n \n * 코드 스타일 규칙도 걱정할 필요 없습니다. 이미 자동화된 도구들이 이를 검사하고 있습니다.\n \n-스타일이나 일관성 관련 요청이 필요한 경우, 제가 직접 요청하거나 필요한 변경 사항을 추가 커밋으로 수정할 것입니다.\n+그리고 다른 스타일이나 일관성 관련 필요 사항이 있다면, 제가 직접 요청하거나 필요한 변경 사항을 위에 커밋으로 추가할 것입니다.\n \n-### 코드 확인하기\n+### 코드 확인하기 { #check-the-code }\n \n-* 코드를 읽고, **논리적으로 타당**한지 확인한 후 로컬에서 실행하여 문제가 해결되는지 확인하세요.\n+* 코드를 확인하고 읽어서 말이 되는지 보고, **로컬에서 실행**해 실제로 문제가 해결되는지 확인하세요.\n \n-* 그런 다음, 확인했다고 **댓글**을 남겨 주세요. 그래야 제가 검토했음을 알 수 있습니다.\n+* 그런 다음 그렇게 했다고 **댓글**로 남겨 주세요. 그래야 제가 정말로 확인했음을 알 수 있습니다.\n \n-/// info\n+/// info | 정보\n \n 불행히도, 제가 단순히 여러 개의 승인만으로 PR을 신뢰할 수는 없습니다.\n \n-3개, 5개 이상의 승인이 달린 PR이 실제로는 깨져 있거나, 버그가 있거나, 주장하는 문제를 해결하지 못하는 경우가 여러 번 있었습니다. 😅\n+여러 번, 설명이 그럴듯해서인지 3개, 5개 이상의 승인이 달린 PR이 있었지만, 제가 확인해보면 실제로는 깨져 있거나, 버그가 있거나, 주장하는 문제를 해결하지 못하는 경우가 있었습니다. 😅\n \n 따라서, 정말로 코드를 읽고 실행한 뒤, 댓글로 확인 내용을 남겨 주는 것이 매우 중요합니다. 🤓\n \n ///\n \n-* PR을 더 단순하게 만들 수 있다면 그렇게 요청할 수 있지만, 너무 까다로울 필요는 없습니다. 주관적인 견해가 많이 있을 수 있기 때문입니다 (그리고 저도 제 견해가 있을 거예요 🙈). 따라서 핵심적인 부분에 집중하는 것이 좋습니다.\n+* PR을 더 단순하게 만들 수 있다면 그렇게 요청할 수 있지만, 너무 까다로울 필요는 없습니다. 주관적인 견해가 많이 있을 수 있기 때문입니다(그리고 저도 제 견해가 있을 거예요 🙈). 따라서 핵심적인 부분에 집중하는 것이 좋습니다.\n \n-### 테스트\n+### 테스트 { #tests }\n \n * PR에 **테스트**가 포함되어 있는지 확인하는 데 도움을 주세요.\n \n-* PR을 적용하기 전에 테스트가 **실패**하는지 확인하세요. 🚨\n+* PR 전에는 테스트가 **실패**하는지 확인하세요. 🚨\n \n-* PR을 적용한 후 테스트가 **통과**하는지 확인하세요. ✅\n+* 그런 다음 PR 후에는 테스트가 **통과**하는지 확인하세요. ✅\n \n-* 많은 PR에는 테스트가 없습니다. 테스트를 추가하도록 **상기**시켜줄 수도 있고, 직접 테스트를 **제안**할 수도 있습니다. 이는 시간이 많이 소요되는 부분 중 하나이며, 그 부분을 많이 도와줄 수 있습니다.\n+* 많은 PR에는 테스트가 없습니다. 테스트를 추가하도록 **상기**시켜줄 수도 있고, 직접 테스트를 **제안**할 수도 있습니다. 이는 시간이 가장 많이 드는 것들 중 하나이며, 그 부분을 많이 도와줄 수 있습니다.\n \n * 그리고 시도한 내용을 댓글로 남겨주세요. 그러면 제가 확인했다는 걸 알 수 있습니다. 🤓\n \n-## Pull Request를 만드십시오\n+## Pull Request 만들기 { #create-a-pull-request }\n \n-Pull Requests를 이용하여 소스코드에 [컨트리뷰트](contributing.md){.internal-link target=\\_blank} 할 수 있습니다. 예를 들면 다음과 같습니다:\n+Pull Requests를 이용하여 소스 코드에 [기여](contributing.md){.internal-link target=_blank}할 수 있습니다. 예를 들면 다음과 같습니다:\n \n * 문서에서 발견한 오타를 수정할 때.\n-* FastAPI 관련 문서, 비디오 또는 팟캐스트를 작성했거나 발견하여 이 파일을 편집하여 공유할 때.\n+* FastAPI에 대한 글, 비디오, 팟캐스트를 작성했거나 발견했다면 이 파일을 편집하여 공유할 때.\n * 해당 섹션의 시작 부분에 링크를 추가해야 합니다.\n-* 당신의 언어로 [문서 번역하는데](contributing.md#translations){.internal-link target=\\_blank} 기여할 때.\n+* 여러분의 언어로 [문서 번역에](contributing.md#translations){.internal-link target=_blank} 도움을 줄 때.\n * 다른 사람이 작성한 번역을 검토하는 것도 도울 수 있습니다.\n-* 새로운 문서의 섹션을 제안할 때.\n-* 기존 문제/버그를 수정할 때.\n+* 새로운 문서 섹션을 제안할 때.\n+* 기존 이슈/버그를 수정할 때.\n * 테스트를 반드시 추가해야 합니다.\n-* 새로운 feature를 추가할 때.\n+* 새로운 기능을 추가할 때.\n * 테스트를 반드시 추가해야 합니다.\n- * 관련 문서가 필요하다면 반드시 추가해야 합니다.\n+ * 관련 문서가 있다면 반드시 추가해야 합니다.\n \n-## FastAPI 유지 관리에 도움 주기\n+## FastAPI 유지 관리 돕기 { #help-maintain-fastapi }\n \n-**FastAPI**의 유지 관리를 도와주세요! 🤓\n+**FastAPI** 유지를 도와주세요! 🤓\n \n-할 일이 많고, 그 중 대부분은 **여러분**이 할 수 있습니다.\n+할 일이 많고, 그중 대부분은 **여러분**이 할 수 있습니다.\n \n 지금 할 수 있는 주요 작업은:\n \n-* [GitHub에서 다른 사람들의 질문에 도움 주기](#github_1){.internal-link target=_blank} (위의 섹션을 참조하세요).\n-* [Pull Request 리뷰하기](#pull-requests){.internal-link target=_blank} (위의 섹션을 참조하세요).\n+* [GitHub에서 질문으로 다른 사람 돕기](#help-others-with-questions-in-github){.internal-link target=_blank} (위의 섹션을 참조하세요).\n+* [Pull Request 리뷰하기](#review-pull-requests){.internal-link target=_blank} (위의 섹션을 참조하세요).\n \n-이 두 작업이 **가장 많은 시간을 소모**하는 일입니다. 그것이 FastAPI 유지 관리의 주요 작업입니다.\n+이 두 작업이 **가장 많은 시간을 소모**합니다. 이것이 FastAPI를 유지 관리하는 주요 작업입니다.\n \n-이 작업을 도와주신다면, **FastAPI 유지 관리에 도움을 주는 것**이며 그것이 **더 빠르고 더 잘 발전하는 것**을 보장하는 것입니다. 🚀\n+이 작업을 도와주신다면, **FastAPI 유지를 돕는 것**이며 FastAPI가 **더 빠르고 더 잘 발전하는 것**을 보장하는 것입니다. 🚀\n \n-## 채팅에 참여하십시오\n+## 채팅에 참여하기 { #join-the-chat }\n \n-👥 디스코드 채팅 서버 👥 에 가입하고 FastAPI 커뮤니티에서 다른 사람들과 어울리세요.\n+👥 Discord 채팅 서버 👥 에 참여해서 FastAPI 커뮤니티의 다른 사람들과 어울리세요.\n \n-/// tip\n+/// tip | 팁\n \n-질문이 있는 경우, GitHub 디스커션 에서 질문하십시오, [[NAME_REDACTED]](fastapi-people.md#fastapi-experts){.internal-link target=_blank} 의 도움을 받을 가능성이 높습니다.\n+질문은 [NAME_REDACTED]에서 하세요. [[NAME_REDACTED]](fastapi-people.md#fastapi-experts){.internal-link target=_blank}로부터 도움을 받을 가능성이 훨씬 높습니다.\n \n-다른 일반적인 대화에서만 채팅을 사용하십시오.\n+채팅은 다른 일반적인 대화를 위해서만 사용하세요.\n \n ///\n \n-### 질문을 위해 채팅을 사용하지 마십시오\n+### 질문을 위해 채팅을 사용하지 마세요 { #dont-use-the-chat-for-questions }\n \n-채팅은 더 많은 \"자유로운 대화\"를 허용하기 때문에, 너무 일반적인 질문이나 대답하기 어려운 질문을 쉽게 질문을 할 수 있으므로, 답변을 받지 못할 수 있습니다.\n+채팅은 더 많은 \"자유로운 대화\"를 허용하기 때문에, 너무 일반적인 질문이나 답하기 어려운 질문을 쉽게 할 수 있어 답변을 받지 못할 수도 있다는 점을 기억하세요.\n \n-GitHub 이슈에서의 템플릿은 올바른 질문을 작성하도록 안내하여 더 쉽게 좋은 답변을 얻거나 질문하기 전에 스스로 문제를 해결할 수도 있습니다. 그리고 GitHub에서는 시간이 조금 걸리더라도 항상 모든 것에 답할 수 있습니다. 채팅 시스템에서는 개인적으로 그렇게 할 수 없습니다. 😅\n+GitHub에서는 템플릿이 올바른 질문을 작성하도록 안내하여 더 쉽게 좋은 답변을 얻거나, 질문하기 전에 스스로 문제를 해결할 수도 있습니다. 그리고 GitHub에서는 시간이 조금 걸리더라도 제가 항상 모든 것에 답하도록 보장할 수 있습니다. 채팅 시스템에서는 제가 개인적으로 그렇게 할 수 없습니다. 😅\n \n-채팅 시스템에서의 대화 또한 GitHub에서 처럼 쉽게 검색할 수 없기 때문에 대화 중에 질문과 답변이 손실될 수 있습니다. 그리고 GitHub 이슈에 있는 것만 [[NAME_REDACTED]](fastapi-people.md#fastapi-experts){.internal-link target=_blank}가 되는 것으로 간주되므로, GitHub 이슈에서 더 많은 관심을 받을 것입니다.\n+채팅 시스템에서의 대화 또한 GitHub만큼 쉽게 검색할 수 없기 때문에, 질문과 답변이 대화 속에서 사라질 수 있습니다. 그리고 GitHub에 있는 것만 [[NAME_REDACTED]](fastapi-people.md#fastapi-experts){.internal-link target=_blank}가 되는 것으로 인정되므로, GitHub에서 더 많은 관심을 받게 될 가능성이 큽니다.\n \n-반면, 채팅 시스템에는 수천 명의 사용자가 있기 때문에, 거의 항상 대화 상대를 찾을 가능성이 높습니다. 😄\n+반면, 채팅 시스템에는 수천 명의 사용자가 있으므로, 거의 항상 대화 상대를 찾을 가능성이 높습니다. 😄\n \n-## 개발자 스폰서가 되십시오\n+## 개발자 스폰서 되기 { #sponsor-the-author }\n \n-GitHub 스폰서 를 통해 개발자를 경제적으로 지원할 수 있습니다.\n-\n-감사하다는 말로 커피를 ☕️ 한잔 사줄 수 있습니다. 😄\n-\n-또한 FastAPI의 실버 또는 골드 스폰서가 될 수 있습니다. 🏅🎉\n-\n-## FastAPI를 강화하는 도구의 스폰서가 되십시오\n-\n-문서에서 보았듯이, FastAPI는 Starlette과 Pydantic 라는 거인의 어깨에 타고 있습니다.\n-\n-다음의 스폰서가 될 수 있습니다\n-\n-* [NAME_REDACTED] (Pydantic)\n-* Encode (Starlette, Uvicorn)\n+여러분의 **제품/회사**가 **FastAPI**에 의존하거나 관련되어 있고, FastAPI 사용자를 대상으로 알리고 싶다면 GitHub sponsors를 통해 개발자(저)를 스폰서할 수 있습니다. 티어에 따라 문서에 배지 같은 추가 혜택을 받을 수도 있습니다. 🎁\n \n ---" }, { "filename": "docs/ko/docs/history-design-future.md", "status": "modified", "additions": 40, "deletions": 42, "changes": 82, "patch": "@@ -1,81 +1,79 @@\n-# 역사, 디자인 그리고 미래\n+# 역사, 디자인 그리고 미래 { #history-design-and-future }\n \n-어느 날, [한 FastAPI 사용자](https://github.com/fastapi/fastapi/issues/3#issuecomment-454956920)가 이렇게 물었습니다:\n+얼마 전, 한 **FastAPI** 사용자가 이렇게 물었습니다:\n \n-> 이 프로젝트의 역사를 알려 주실 수 있나요? 몇 주 만에 멋진 결과를 낸 것 같아요. [...]\n+> 이 프로젝트의 역사는 무엇인가요? 몇 주 만에 아무 데서도 갑자기 나타나 엄청나게 좋아진 것처럼 보이네요 [...]\n \n 여기서 그 역사에 대해 간단히 설명하겠습니다.\n \n----\n+## 대안 { #alternatives }\n \n-## 대안\n+저는 여러 해 동안 복잡한 요구사항(머신러닝, 분산 시스템, 비동기 작업, NoSQL 데이터베이스 등)을 가진 API를 만들면서 여러 개발 팀을 이끌어 왔습니다.\n \n-저는 여러 해 동안 머신러닝, 분산 시스템, 비동기 작업, NoSQL 데이터베이스 같은 복잡한 요구사항을 가진 API를 개발하며 여러 팀을 이끌어 왔습니다.\n+그 과정에서 많은 대안을 조사하고, 테스트하고, 사용해야 했습니다.\n \n-이 과정에서 많은 대안을 조사하고, 테스트하며, 사용해야 했습니다. **FastAPI**의 역사는 그 이전에 나왔던 여러 도구의 역사와 밀접하게 연관되어 있습니다.\n+**FastAPI**의 역사는 상당 부분 그 이전에 있던 도구들의 역사입니다.\n \n [대안](alternatives.md){.internal-link target=_blank} 섹션에서 언급된 것처럼:\n \n-> **FastAPI**는 이전에 나왔던 많은 도구들의 노력 없이는 존재하지 않았을 것입니다.\n->\n-> 이전에 개발된 여러 도구들이 이 프로젝트에 영감을 주었습니다.\n->\n-> 저는 오랫동안 새로운 프레임워크를 만드는 것을 피하고자 했습니다. 처음에는 **FastAPI**가 제공하는 기능들을 다양한 프레임워크와 플러그인, 도구들을 조합해 해결하려 했습니다.\n->\n-> 하지만 결국에는 이 모든 기능을 통합하는 도구가 필요해졌습니다. 이전 도구들로부터 최고의 아이디어들을 모으고, 이를 최적의 방식으로 조합해야만 했습니다. 이는 :term:Python 3.6+ 타입 힌트 와 같은, 이전에는 사용할 수 없었던 언어 기능이 가능했기 때문입니다.\n+
      \n \n----\n+**FastAPI**는 다른 사람들이 이전에 해온 작업이 없었다면 존재하지 않았을 것입니다.\n \n-## 조사\n+그 전에 만들어진 많은 도구들이 이것의 탄생에 영감을 주었습니다.\n \n-여러 대안을 사용해 보며 다양한 도구에서 배운 점들을 모아 저와 개발팀에게 가장 적합한 방식을 찾았습니다.\n+저는 여러 해 동안 새로운 프레임워크를 만드는 것을 피하고 있었습니다. 처음에는 **FastAPI**가 다루는 모든 기능을 여러 다른 프레임워크, 플러그인, 도구들을 사용해 해결하려고 했습니다.\n \n-예를 들어, 표준 :term:Python 타입 힌트 에 기반하는 것이 이상적이라는 점이 명확했습니다.\n+하지만 어느 시점에는, 이전 도구들의 최고의 아이디어를 가져와 가능한 한 최선의 방식으로 조합하고, 이전에는 존재하지 않았던 언어 기능(Python 3.6+ type hints)을 사용해 이 모든 기능을 제공하는 무언가를 만드는 것 외에는 다른 선택지가 없었습니다.\n \n-또한, 이미 존재하는 표준을 활용하는 것이 가장 좋은 접근법이라 판단했습니다.\n+
      \n \n-그래서 **FastAPI**의 코드를 작성하기 전에 몇 달 동안 OpenAPI, JSON Schema, OAuth2 명세를 연구하며 이들의 관계와 겹치는 부분, 차이점을 이해했습니다.\n+## 조사 { #investigation }\n \n----\n+이전의 모든 대안을 사용해 보면서, 각 도구로부터 배울 기회를 얻었고, 아이디어를 가져와 제가 일해온 개발 팀들과 저 자신에게 가장 적합하다고 찾은 방식으로 조합할 수 있었습니다.\n \n-## 디자인\n+예를 들어, 이상적으로는 표준 Python 타입 힌트에 기반해야 한다는 점이 분명했습니다.\n \n-그 후, **FastAPI** 사용자가 될 개발자로서 사용하고 싶은 개발자 \"API\"를 디자인했습니다.\n+또한, 가장 좋은 접근법은 이미 존재하는 표준을 사용하는 것이었습니다.\n \n-[[NAME_REDACTED]](https://www.jetbrains.com/research/python-developers-survey-2018/#development-tools)에 따르면 약 80%의 Python 개발자가 PyCharm, VS Code, Jedi 기반 편집기 등에서 개발합니다. 이 과정에서 여러 아이디어를 테스트했습니다.\n+그래서 **FastAPI**의 코딩을 시작하기도 전에, OpenAPI, JSON Schema, OAuth2 등과 같은 명세를 몇 달 동안 공부했습니다. 이들의 관계, 겹치는 부분, 차이점을 이해하기 위해서였습니다.\n \n-대부분의 다른 편집기도 유사하게 동작하기 때문에, **FastAPI**의 이점은 거의 모든 편집기에서 누릴 수 있습니다.\n+## 디자인 { #design }\n \n-이 과정을 통해 코드 중복을 최소화하고, 모든 곳에서 자동 완성, 타입 검사, 에러 확인 기능이 제공되는 최적의 방식을 찾아냈습니다.\n+그 다음에는 (FastAPI를 사용하는 개발자로서) 사용자로서 갖고 싶었던 개발자 \"API\"를 디자인하는 데 시간을 썼습니다.\n \n-이 모든 것은 개발자들에게 최고의 개발 경험을 제공하기 위해 설계되었습니다.\n+가장 인기 있는 Python 편집기들: PyCharm, VS Code, Jedi 기반 편집기에서 여러 아이디어를 테스트했습니다.\n \n----\n+약 80%의 사용자를 포함하는 최근 [NAME_REDACTED]에 따르면 그렇습니다.\n \n-## 필요조건\n+즉, **FastAPI**는 Python 개발자의 80%가 사용하는 편집기들로 특별히 테스트되었습니다. 그리고 대부분의 다른 편집기도 유사하게 동작하는 경향이 있으므로, 그 모든 이점은 사실상 모든 편집기에서 동작해야 합니다.\n \n-여러 대안을 테스트한 후, [Pydantic](https://docs.pydantic.dev/)을 사용하기로 결정했습니다.\n+그렇게 해서 코드 중복을 가능한 한 많이 줄이고, 어디서나 자동 완성, 타입 및 에러 검사 등을 제공하는 최선의 방법을 찾을 수 있었습니다.\n \n-이후 저는 **Pydantic**이 JSON Schema와 완벽히 호환되도록 개선하고, 다양한 제약 조건 선언을 지원하며, 여러 편집기에서의 자동 완성과 타입 검사 기능을 향상하기 위해 기여했습니다.\n+모든 개발자에게 최고의 개발 경험을 제공하는 방식으로 말입니다.\n \n-또한, 또 다른 주요 필요조건이었던 [Starlette](https://www.starlette.dev/)에도 기여했습니다.\n+## 필요조건 { #requirements }\n \n----\n+여러 대안을 테스트한 후, 장점 때문에 **Pydantic**을 사용하기로 결정했습니다.\n \n-## 개발\n+그 후, JSON Schema를 완전히 준수하도록 하고, 제약 조건 선언을 정의하는 다양한 방식을 지원하며, 여러 편집기에서의 테스트를 바탕으로 편집기 지원(타입 검사, 자동 완성)을 개선하기 위해 기여했습니다.\n \n-**FastAPI**를 개발하기 시작할 즈음에는 대부분의 준비가 이미 완료된 상태였습니다. 설계가 정의되었고, 필요조건과 도구가 준비되었으며, 표준과 명세에 대한 지식도 충분했습니다.\n+개발 과정에서, 또 다른 핵심 필요조건인 **Starlette**에도 기여했습니다.\n \n----\n+## 개발 { #development }\n \n-## 미래\n+**FastAPI** 자체를 만들기 시작했을 때쯤에는, 대부분의 조각들이 이미 갖춰져 있었고, 디자인은 정의되어 있었으며, 필요조건과 도구는 준비되어 있었고, 표준과 명세에 대한 지식도 명확하고 최신 상태였습니다.\n \n-현시점에서 **FastAPI**가 많은 사람들에게 유용하다는 것이 명백해졌습니다.\n+## 미래 { #future }\n \n-여러 용도에 더 적합한 도구로서 기존 대안보다 선호되고 있습니다.\n-이미 많은 개발자와 팀들이 **FastAPI**에 의존해 프로젝트를 진행 중입니다 (저와 제 팀도 마찬가지입니다).\n+이 시점에는, **FastAPI**가 그 아이디어와 함께 많은 사람들에게 유용하다는 것이 이미 분명합니다.\n \n-하지만 여전히 개선해야 할 점과 추가할 기능들이 많이 남아 있습니다.\n+많은 사용 사례에 더 잘 맞기 때문에 이전 대안들보다 선택되고 있습니다.\n+\n+많은 개발자와 팀이 이미 자신의 프로젝트를 위해 **FastAPI**에 의존하고 있습니다(저와 제 팀도 포함해서요).\n+\n+하지만 여전히, 앞으로 나올 개선 사항과 기능들이 많이 있습니다.\n+\n+**FastAPI**의 미래는 밝습니다.\n \n-**FastAPI**는 밝은 미래로 나아가고 있습니다.\n 그리고 [여러분의 도움](help-fastapi.md){.internal-link target=_blank}은 큰 힘이 됩니다." } ], "reviews": [ { "id": 3681097212, "user": "user_7e930c559d4e", "state": "COMMENTED", "body": null, "submitted_at": "2026-01-20T09:07:36+00:00" }, { "id": 3681132251, "user": "user_29e85f9a8e75", "state": "COMMENTED", "body": null, "submitted_at": "2026-01-20T09:12:14+00:00" }, { "id": 3681166299, "user": "user_7e930c559d4e", "state": "COMMENTED", "body": null, "submitted_at": "2026-01-20T09:20:17+00:00" }, { "id": 3681325571, "user": "user_29e85f9a8e75", "state": "COMMENTED", "body": null, "submitted_at": "2026-01-20T09:56:02+00:00" }, { "id": 3681514636, "user": "user_7e930c559d4e", "state": "APPROVED", "body": null, "submitted_at": "2026-01-20T10:40:12+00:00" }, { "id": 3696098659, "user": "user_7e930c559d4e", "state": "APPROVED", "body": null, "submitted_at": "2026-01-23T07:39:46+00:00" }, { "id": 3696098963, "user": "user_12425605bafa", "state": "COMMENTED", "body": "I think the original terms '애플리케이션' (Application) and '명령어' (Command line/Instruction) are more accurate and natural than '앱' (App) or '명령' (Command).\n\nIn the Korean context, '앱' (App) is strongly associated with mobile applications. For a CLI tool, '애플리케이션' sounds more appropriate. Also, '명령어' is the more standard term used to describe instructions typed into a terminal.", "submitted_at": "2026-01-23T07:41:23+00:00" }, { "id": 3696498847, "user": "user_12425605bafa", "state": "APPROVED", "body": "Overall, the translation looks solid, and the added explanations for abbreviations are helpful for Korean readers.\n\nI'm approving this as the quality is good. As a small suggestion for future updates, using “애플리케이션” instead of “앱” and “명령어” instead of “명령” may sound more natural in a context.", "submitted_at": "2026-01-23T09:07:58+00:00" }, { "id": 3701586837, "user": "user_12425605bafa", "state": "APPROVED", "body": null, "submitted_at": "2026-01-24T13:20:48+00:00" } ], "review_comments": [ { "id": 2707411387, "user": "user_7e930c559d4e", "body": "```suggestion\n만약 애플리케이션이 (어째서인지) 다른 어떤 것과도 통신하고 그 응답을 기다릴 필요가 없다면, 내부에서 `await`를 사용할 필요가 없더라도 `async def`를 사용하세요.\n```\n\nIn Korean, translating “you” as “여러분” instead of “당신”, or omitting it when possible, sounds more natural. In many contexts, “당신” is considered impolite in Korean.\n\nIt would be good to add this content to [llm_prompt.md](https://github.com/fastapi/fastapi/blob/master/docs/ko/llm-prompt.md).", "path": "docs/ko/docs/async.md", "line": null, "side": "RIGHT", "created_at": "2026-01-20T09:04:52+00:00" }, { "id": 2707440491, "user": "user_29e85f9a8e75", "body": "[USER_REDACTED], thanks!\nWould you like to open PR to update `llm-prompt.md`?\nI would then re-translate these documents using the updated prompt", "path": "docs/ko/docs/async.md", "line": null, "side": "RIGHT", "created_at": "2026-01-20T09:12:14+00:00" }, { "id": 2707469675, "user": "user_7e930c559d4e", "body": "Sure, I’ll take care of it. Thanks!", "path": "docs/ko/docs/async.md", "line": null, "side": "RIGHT", "created_at": "2026-01-20T09:20:17+00:00" }, { "id": 2707607887, "user": "user_29e85f9a8e75", "body": "Re-translated pages with updated prompt. Commit https://github.com/fastapi/fastapi/pull/14738/commits/d65e8a4aaa8369d52c29b913b0528e8c54180dd6", "path": "docs/ko/docs/async.md", "line": null, "side": "RIGHT", "created_at": "2026-01-20T09:56:02+00:00" }, { "id": 2719974974, "user": "user_12425605bafa", "body": "I think the original terms '애플리케이션' (Application) and '명령어' (Command line/Instruction) are more accurate and natural than '앱' (App) or '명령' (Command).\n\nIn the Korean context, '앱' (App) is strongly associated with mobile applications. For a CLI tool, '애플리케이션' sounds more appropriate. Also, '명령어' is the more standard term used to describe instructions typed into a terminal.", "path": "docs/ko/docs/fastapi-cli.md", "line": null, "side": "RIGHT", "created_at": "2026-01-23T07:39:53+00:00" } ], "meta": { "languages": [ "md" ], "touches_tests": false, "review_state_summary": { "COMMENTED": 5, "APPROVED": 4 }, "meaningful_comment_count": 5, "has_approval": true, "has_changes_requested": false, "total_review_comments": 5 } } { "_id": "c088da7a955c46b5", "_schema_version": "1.0", "_cleaned_at": "2026-02-12T07:46:51.671629+00:00", "repo": "tiangolo/fastapi", "repo_url": "https://github.com/fastapi/fastapi", "license_name": "MIT License", "license_spdx": "MIT", "pr_number": 14693, "title": "🌐 Update translations for ru (update-outdated)", "body": "🌐 Update translations for ru (update-outdated)\n\nThis PR was created automatically using LLMs.\n\nIt uses the prompt file https://github.com/fastapi/fastapi/blob/master/docs/ru/llm-prompt.md.\n\nIn most cases, it's better to make PRs updating that file so that the LLM can do a better job generating the translations than suggesting changes in this PR.", "author": "user_2a237e38e06b", "created_at": "2026-01-11T00:36:41+00:00", "merged_at": "2026-01-20T23:03:07+00:00", "base_branch": "master", "head_branch": "translate-ru-update-outdated-31cb3e0f", "additions": 297, "deletions": 444, "changed_files": 13, "files": [ { "filename": "docs/ru/docs/_llm-test.md", "status": "modified", "additions": 9, "deletions": 9, "changes": 18, "patch": "@@ -1,8 +1,8 @@\n # Тестовый файл LLM { #llm-test-file }\n \n-Этот документ проверяет, понимает ли LLM, переводящая документацию, `general_prompt` в `scripts/translate.py` и языковой специфичный промпт в `docs/{language code}/llm-prompt.md`. Языковой специфичный промпт добавляется к `general_prompt`.\n+Этот документ проверяет, понимает ли LLM, переводящая документацию, `general_prompt` в `scripts/translate.py` и языковой специфичный промпт в `docs/{language code}/llm-prompt.md`. Языковой специфичный промпт добавляется к `general_prompt`.\n \n-Тесты, добавленные здесь, увидят все создатели языковых промптов.\n+Тесты, добавленные здесь, увидят все создатели языковых специфичных промптов.\n \n Использование:\n \n@@ -11,7 +11,7 @@\n * Проверьте, всё ли в порядке в переводе.\n * При необходимости улучшите ваш языковой специфичный промпт, общий промпт или английский документ.\n * Затем вручную исправьте оставшиеся проблемы в переводе, чтобы он был хорошим.\n-* Переведите заново, имея хороший перевод на месте. Идеальным результатом будет ситуация, когда LLM больше не вносит изменений в перевод. Это означает, что общий промпт и ваш языковой специфичный промпт максимально хороши (иногда он будет делать несколько, казалось бы, случайных изменений, причина в том, что LLM — недетерминированные алгоритмы).\n+* Переведите заново, имея хороший перевод на месте. Идеальным результатом будет ситуация, когда LLM больше не вносит изменений в перевод. Это означает, что общий промпт и ваш языковой специфичный промпт настолько хороши, насколько это возможно (иногда он будет делать несколько, казалось бы, случайных изменений, причина в том, что LLM — недетерминированные алгоритмы).\n \n Тесты:\n \n@@ -197,10 +197,10 @@ works(foo=\"bar\") # Это работает 🎉\n \n ### abbr даёт полную расшифровку { #the-abbr-gives-a-full-phrase }\n \n-* GTD\n-* lt\n-* XWT\n-* PSGI\n+* GTD\n+* lt\n+* XWT\n+* PSGI\n \n ### abbr даёт объяснение { #the-abbr-gives-an-explanation }\n \n@@ -209,8 +209,8 @@ works(foo=\"bar\") # Это работает 🎉\n \n ### abbr даёт полную расшифровку и объяснение { #the-abbr-gives-a-full-phrase-and-an-explanation }\n \n-* MDN\n-* I/O.\n+* MDN\n+* I/O.\n \n ////" }, { "filename": "docs/ru/docs/advanced/path-operation-advanced-configuration.md", "status": "modified", "additions": 12, "deletions": 44, "changes": 56, "patch": "@@ -14,7 +14,7 @@\n \n {* ../../docs_src/path_operation_advanced_configuration/tutorial001_py39.py hl[6] *}\n \n-### Использование имени функции-обработчика пути как operationId { #using-the-path-operation-function-name-as-the-operationid }\n+### Использование имени *функции-обработчика пути* как operationId { #using-the-path-operation-function-name-as-the-operationid }\n \n Если вы хотите использовать имена функций ваших API в качестве `operationId`, вы можете пройти по всем из них и переопределить `operation_id` каждой *операции пути* с помощью их `APIRoute.name`.\n \n@@ -38,7 +38,7 @@\n \n ## Исключить из OpenAPI { #exclude-from-openapi }\n \n-Чтобы исключить *операцию пути* из генерируемой схемы OpenAPI (а значит, и из автоматической документации), используйте параметр `include_in_schema` и установите его в `False`:\n+Чтобы исключить *операцию пути* из генерируемой схемы OpenAPI (а значит, и из автоматических систем документации), используйте параметр `include_in_schema` и установите его в `False`:\n \n {* ../../docs_src/path_operation_advanced_configuration/tutorial003_py39.py hl[6] *}\n \n@@ -48,15 +48,15 @@\n \n Добавление `\\f` (экранированного символа «form feed») заставит **FastAPI** обрезать текст, используемый для OpenAPI, в этой точке.\n \n-Эта часть не попадёт в документацию, но другие инструменты (например, Sphinx) смогут использовать остальное.\n+Это не отобразится в документации, но другие инструменты (например, Sphinx) смогут использовать остальное.\n \n {* ../../docs_src/path_operation_advanced_configuration/tutorial004_py310.py hl[17:27] *}\n \n ## Дополнительные ответы { #additional-responses }\n \n Вы, вероятно, уже видели, как объявлять `response_model` и `status_code` для *операции пути*.\n \n-Это определяет метаданные об основном ответе *операции пути*.\n+Это определяет метаданные об основном HTTP-ответе *операции пути*.\n \n Также можно объявлять дополнительные ответы с их моделями, статус-кодами и т.д.\n \n@@ -76,7 +76,7 @@\n \n Там есть `tags`, `parameters`, `requestBody`, `responses` и т.д.\n \n-Эта спецификация OpenAPI, специфичная для *операции пути*, обычно генерируется автоматически **FastAPI**, но вы также можете её расширить.\n+Эта специфичная для *операции пути* схема OpenAPI обычно генерируется автоматически **FastAPI**, но вы также можете её расширить.\n \n /// tip | Совет\n \n@@ -129,13 +129,13 @@\n }\n ```\n \n-### Пользовательская схема OpenAPI для операции пути { #custom-openapi-path-operation-schema }\n+### Пользовательская схема OpenAPI для *операции пути* { #custom-openapi-path-operation-schema }\n \n-Словарь в `openapi_extra` будет объединён с автоматически сгенерированной схемой OpenAPI для *операции пути*.\n+Словарь в `openapi_extra` будет глубоко объединён с автоматически сгенерированной схемой OpenAPI для *операции пути*.\n \n Таким образом, вы можете добавить дополнительные данные к автоматически сгенерированной схеме.\n \n-Например, вы можете решить читать и валидировать запрос своим кодом, не используя автоматические возможности FastAPI и Pydantic, но при этом захотите описать запрос в схеме OpenAPI.\n+Например, вы можете решить читать и валидировать HTTP-запрос своим кодом, не используя автоматические возможности FastAPI и Pydantic, но при этом захотите описать HTTP-запрос в схеме OpenAPI.\n \n Это можно сделать с помощью `openapi_extra`:\n \n@@ -149,52 +149,20 @@\n \n Используя тот же приём, вы можете воспользоваться Pydantic-моделью, чтобы определить JSON Schema, которая затем будет включена в пользовательский раздел схемы OpenAPI для *операции пути*.\n \n-И вы можете сделать это, даже если тип данных в запросе — не JSON.\n+И вы можете сделать это, даже если тип данных в HTTP-запросе — не JSON.\n \n-Например, в этом приложении мы не используем встроенную функциональность FastAPI для извлечения JSON Schema из моделей Pydantic, равно как и автоматическую валидацию JSON. Мы объявляем тип содержимого запроса как YAML, а не JSON:\n-\n-//// tab | Pydantic v2\n+Например, в этом приложении мы не используем встроенную функциональность FastAPI для извлечения JSON Schema из моделей Pydantic, равно как и автоматическую валидацию JSON. Мы объявляем тип содержимого HTTP-запроса как YAML, а не JSON:\n \n {* ../../docs_src/path_operation_advanced_configuration/tutorial007_py39.py hl[15:20, 22] *}\n \n-////\n-\n-//// tab | Pydantic v1\n-\n-{* ../../docs_src/path_operation_advanced_configuration/tutorial007_pv1_py39.py hl[15:20, 22] *}\n-\n-////\n-\n-/// info | Информация\n-\n-В Pydantic версии 1 метод для получения JSON Schema модели назывался `Item.schema()`, в Pydantic версии 2 метод называется `Item.model_json_schema()`.\n-\n-///\n-\n Тем не менее, хотя мы не используем встроенную функциональность по умолчанию, мы всё равно используем Pydantic-модель, чтобы вручную сгенерировать JSON Schema для данных, которые мы хотим получить в YAML.\n \n-Затем мы работаем с запросом напрямую и извлекаем тело как `bytes`. Это означает, что FastAPI даже не попытается распарсить полезную нагрузку запроса как JSON.\n+Затем мы работаем с HTTP-запросом напрямую и извлекаем тело как `bytes`. Это означает, что FastAPI даже не попытается распарсить полезную нагрузку HTTP-запроса как JSON.\n \n-А затем в нашем коде мы напрямую парсим этот YAML и снова используем ту же Pydantic-модель для валидации YAML-содержимого:\n-\n-//// tab | Pydantic v2\n+А затем в нашем коде мы напрямую парсим это содержимое YAML и снова используем ту же Pydantic-модель, чтобы валидировать YAML-содержимое:\n \n {* ../../docs_src/path_operation_advanced_configuration/tutorial007_py39.py hl[24:31] *}\n \n-////\n-\n-//// tab | Pydantic v1\n-\n-{* ../../docs_src/path_operation_advanced_configuration/tutorial007_pv1_py39.py hl[24:31] *}\n-\n-////\n-\n-/// info | Информация\n-\n-В Pydantic версии 1 метод для парсинга и валидации объекта назывался `Item.parse_obj()`, в Pydantic версии 2 метод называется `Item.model_validate()`.\n-\n-///\n-\n /// tip | Совет\n \n Здесь мы переиспользуем ту же Pydantic-модель." }, { "filename": "docs/ru/docs/advanced/settings.md", "status": "modified", "additions": 0, "deletions": 44, "changes": 44, "patch": "@@ -46,12 +46,6 @@ $ pip install \"fastapi[all]\"\n \n \n \n-/// info | Информация\n-\n-В Pydantic v1 он входил в основной пакет. Теперь он распространяется как отдельный пакет, чтобы вы могли установить его только при необходимости.\n-\n-///\n-\n ### Создание объекта `Settings` { #create-the-settings-object }\n \n Импортируйте `BaseSettings` из Pydantic и создайте подкласс, очень похожий на Pydantic‑модель.\n@@ -60,24 +54,8 @@ $ pip install \"fastapi[all]\"\n \n Вы можете использовать все те же возможности валидации и инструменты, что и для Pydantic‑моделей, например разные типы данных и дополнительную валидацию через `Field()`.\n \n-//// tab | Pydantic v2\n-\n {* ../../docs_src/settings/tutorial001_py39.py hl[2,5:8,11] *}\n \n-////\n-\n-//// tab | Pydantic v1\n-\n-/// info | Информация\n-\n-В Pydantic v1 вы бы импортировали `BaseSettings` напрямую из `pydantic`, а не из `pydantic_settings`.\n-\n-///\n-\n-{* ../../docs_src/settings/tutorial001_pv1_py39.py hl[2,5:8,11] *}\n-\n-////\n-\n /// tip | Совет\n \n Если вам нужно что-то быстро скопировать и вставить, не используйте этот пример — воспользуйтесь последним ниже.\n@@ -215,8 +193,6 @@ APP_NAME=\"ChimichangApp\"\n \n Затем обновите ваш `config.py` так:\n \n-//// tab | Pydantic v2\n-\n {* ../../docs_src/settings/app03_an_py39/config.py hl[9] *}\n \n /// tip | Совет\n@@ -225,26 +201,6 @@ APP_NAME=\"ChimichangApp\"\n \n ///\n \n-////\n-\n-//// tab | Pydantic v1\n-\n-{* ../../docs_src/settings/app03_an_py39/config_pv1.py hl[9:10] *}\n-\n-/// tip | Совет\n-\n-Класс `Config` используется только для конфигурации Pydantic. Подробнее см. [NAME_REDACTED].\n-\n-///\n-\n-////\n-\n-/// info | Информация\n-\n-В Pydantic версии 1 конфигурация задавалась во внутреннем классе `Config`, в Pydantic версии 2 — в атрибуте `model_config`. Этот атрибут принимает `dict`, и чтобы получить автозавершение и ошибки «на лету», вы можете импортировать и использовать `SettingsConfigDict` для описания этого `dict`.\n-\n-///\n-\n Здесь мы задаем параметр конфигурации `env_file` внутри вашего класса Pydantic `Settings` и устанавливаем значение равным имени файла dotenv, который хотим использовать.\n \n ### Создание `Settings` только один раз с помощью `lru_cache` { #creating-the-settings-only-once-with-lru-cache }" }, { "filename": "docs/ru/docs/how-to/migrate-from-pydantic-v1-to-pydantic-v2.md", "status": "modified", "additions": 15, "deletions": 13, "changes": 28, "patch": "@@ -2,21 +2,23 @@\n \n Если у вас старое приложение FastAPI, возможно, вы используете Pydantic версии 1.\n \n-FastAPI поддерживает и Pydantic v1, и v2 начиная с версии 0.100.0.\n+FastAPI версии 0.100.0 поддерживал либо Pydantic v1, либо v2. Он использовал ту версию, которая была установлена.\n \n-Если у вас был установлен Pydantic v2, использовался он. Если вместо этого был установлен Pydantic v1 — использовался он.\n+FastAPI версии 0.119.0 добавил частичную поддержку Pydantic v1 изнутри Pydantic v2 (как `pydantic.v1`), чтобы упростить миграцию на v2.\n \n-Сейчас Pydantic v1 объявлен устаревшим, и поддержка его будет удалена в следующих версиях FastAPI, поэтому вам следует **перейти на Pydantic v2**. Так вы получите последние возможности, улучшения и исправления.\n+FastAPI 0.126.0 убрал поддержку Pydantic v1, при этом ещё некоторое время продолжал поддерживать `pydantic.v1`.\n \n /// warning | Предупреждение\n \n-Кроме того, команда Pydantic прекратила поддержку Pydantic v1 для последних версий Python, начиная с **Python 3.14**.\n+Команда Pydantic прекратила поддержку Pydantic v1 для последних версий Python, начиная с **Python 3.14**.\n+\n+Это включает `pydantic.v1`, который больше не поддерживается в Python 3.14 и выше.\n \n Если вы хотите использовать последние возможности Python, вам нужно убедиться, что вы используете Pydantic v2.\n \n ///\n \n-Если у вас старое приложение FastAPI с Pydantic v1, здесь я покажу, как мигрировать на Pydantic v2, и **новые возможности в FastAPI 0.119.0**, которые помогут выполнить постепенную миграцию.\n+Если у вас старое приложение FastAPI с Pydantic v1, здесь я покажу, как мигрировать на Pydantic v2, и **возможности FastAPI 0.119.0**, которые помогут выполнить постепенную миграцию.\n \n ## Официальное руководство { #official-guide }\n \n@@ -38,21 +40,21 @@ FastAPI поддерживает и Pydantic v1, и v2 начиная с вер\n \n Вы можете использовать `bump-pydantic` от той же команды Pydantic.\n \n-Этот инструмент поможет автоматически внести большую часть необходимых изменений в код.\n+Этот инструмент поможет автоматически изменить большую часть кода, который нужно изменить.\n \n-После этого запустите тесты и проверьте, что всё работает. Если да — на этом всё. 😎\n+После этого вы можете запустить тесты и проверить, что всё работает. Если да — на этом всё. 😎\n \n ## Pydantic v1 в v2 { #pydantic-v1-in-v2 }\n \n-Pydantic v2 включает всё из Pydantic v1 как подмодуль `pydantic.v1`.\n+Pydantic v2 включает всё из Pydantic v1 как подмодуль `pydantic.v1`. Но это больше не поддерживается в версиях Python выше 3.13.\n \n Это означает, что вы можете установить последнюю версию Pydantic v2 и импортировать и использовать старые компоненты Pydantic v1 из этого подмодуля так, как если бы у вас был установлен старый Pydantic v1.\n \n {* ../../docs_src/pydantic_v1_in_v2/tutorial001_an_py310.py hl[1,4] *}\n \n ### Поддержка FastAPI для Pydantic v1 внутри v2 { #fastapi-support-for-pydantic-v1-in-v2 }\n \n-Начиная с FastAPI 0.119.0, есть также частичная поддержка Pydantic v1 в составе Pydantic v2, чтобы упростить миграцию на v2.\n+Начиная с FastAPI 0.119.0, есть также частичная поддержка Pydantic v1 изнутри Pydantic v2, чтобы упростить миграцию на v2.\n \n Таким образом, вы можете обновить Pydantic до последней версии 2 и сменить импорты на подмодуль `pydantic.v1` — во многих случаях всё просто заработает.\n \n@@ -106,7 +108,7 @@ graph TB\n style V2Field fill:#f9fff3\n ```\n \n-В некоторых случаях можно использовать и модели Pydantic v1, и v2 в одной и той же операции пути (обработчике пути) вашего приложения FastAPI:\n+В некоторых случаях можно использовать и модели Pydantic v1, и v2 в одной и той же **операции пути** (обработчике пути) вашего приложения FastAPI:\n \n {* ../../docs_src/pydantic_v1_in_v2/tutorial003_an_py310.py hl[2:3,6,12,21:22] *}\n \n@@ -122,12 +124,12 @@ graph TB\n \n /// tip | Совет\n \n-Сначала попробуйте `bump-pydantic`. Если тесты проходят и всё работает, вы справились одной командой. ✨\n+Сначала попробуйте `bump-pydantic`: если тесты проходят и всё работает, вы справились одной командой. ✨\n \n ///\n \n Если `bump-pydantic` не подходит для вашего случая, вы можете использовать поддержку одновременной работы моделей Pydantic v1 и v2 в одном приложении, чтобы мигрировать на Pydantic v2 постепенно.\n \n-Сначала обновите Pydantic до последней 2-й версии и измените импорты так, чтобы все ваши модели использовали `pydantic.v1`.\n+Сначала вы можете обновить Pydantic до последней 2-й версии и изменить импорты так, чтобы все ваши модели использовали `pydantic.v1`.\n \n-Затем начните мигрировать ваши модели с Pydantic v1 на v2 группами, поэтапно. 🚶\n+Затем вы можете начать мигрировать ваши модели с Pydantic v1 на v2 группами, поэтапно. 🚶" }, { "filename": "docs/ru/docs/how-to/separate-openapi-schemas.md", "status": "modified", "additions": 7, "deletions": 9, "changes": 16, "patch": "@@ -2,7 +2,7 @@\n \n При использовании **Pydantic v2** сгенерированный OpenAPI становится чуть более точным и **корректным**, чем раньше. 😎\n \n-На самом деле, в некоторых случаях в OpenAPI будет даже **две JSON схемы** для одной и той же Pydantic‑модели: для входа и для выхода — в зависимости от наличия **значений по умолчанию**.\n+На самом деле, в некоторых случаях в OpenAPI будет даже **две JSON-схемы** для одной и той же Pydantic‑модели: для входа и для выхода — в зависимости от наличия **значений по умолчанию**.\n \n Посмотрим, как это работает, и как это изменить при необходимости.\n \n@@ -34,7 +34,7 @@\n \n {* ../../docs_src/separate_openapi_schemas/tutorial001_py310.py hl[19] *}\n \n-…то, поскольку у `description` есть значение по умолчанию, даже если вы **ничего не вернёте** для этого поля, оно всё равно будет иметь это **значение по умолчанию**.\n+…то, поскольку у `description` есть значение по умолчанию, если вы **ничего не вернёте** для этого поля, оно всё равно будет иметь это **значение по умолчанию**.\n \n ### Модель для данных ответа { #model-for-output-response-data }\n \n@@ -46,13 +46,13 @@\n \n Это означает, что у него **всегда будет какое‑то значение**, просто иногда это значение может быть `None` (или `null` в JSON).\n \n-Следовательно, клиентам, использующим ваш API, не нужно проверять наличие этого значения: они могут **исходить из того, что поле всегда присутствует**, а в некоторых случаях имеет значение по умолчанию `None`.\n+Это означает, что клиентам, использующим ваш API, не нужно проверять, существует ли это значение или нет: они могут **исходить из того, что поле всегда присутствует**, но в некоторых случаях оно будет иметь значение по умолчанию `None`.\n \n В OpenAPI это описывается тем, что поле помечается как **обязательное**, поскольку оно всегда присутствует.\n \n Из‑за этого JSON Schema для модели может отличаться в зависимости от использования для **входа** или **выхода**:\n \n-* для **входа** `description` не будет обязательным\n+* для **входа** `description` **не будет обязательным**\n * для **выхода** оно будет **обязательным** (и при этом может быть `None`, или, в терминах JSON, `null`)\n \n ### Выходная модель в документации { #model-for-output-in-docs }\n@@ -81,9 +81,9 @@\n \n Однако бывают случаи, когда вы хотите иметь **одну и ту же схему для входа и выхода**.\n \n-Главный сценарий — когда у вас уже есть сгенерированный клиентский код/SDK, и вы пока не хотите обновлять весь этот автогенерируемый код/SDK (рано или поздно вы это сделаете, но не сейчас).\n+Главный сценарий — когда у вас уже есть сгенерированный клиентский код/SDK, и вы пока не хотите обновлять весь этот автогенерируемый клиентский код/SDK, вероятно, вы захотите сделать это в какой-то момент, но, возможно, не прямо сейчас.\n \n-В таком случае вы можете отключить эту функциональность в FastAPI с помощью параметра `separate_input_output_schemas=False`.\n+В таком случае вы можете отключить эту функциональность в **FastAPI** с помощью параметра `separate_input_output_schemas=False`.\n \n /// info | Информация\n \n@@ -95,10 +95,8 @@\n \n ### Одна и та же схема для входной и выходной моделей в документации { #same-schema-for-input-and-output-models-in-docs }\n \n-Теперь для этой модели будет одна общая схема и для входа, и для выхода — только `Item`, и в ней `description` будет **не обязательным**:\n+И теперь для модели будет одна общая схема и для входа, и для выхода — только `Item`, и в ней `description` будет **не обязательным**:\n \n
      \n \n
      \n-\n-Это то же поведение, что и в Pydantic v1. 🤓" }, { "filename": "docs/ru/docs/index.md", "status": "modified", "additions": 23, "deletions": 17, "changes": 40, "patch": "@@ -5,10 +5,10 @@\n \n \n

      \n- \"FastAPI\"\n+ \"FastAPI\"\n

      \n

      \n- Фреймворк FastAPI: высокая производительность, прост в изучении, быстрый в разработке, готов к продакшн\n+ Фреймворк FastAPI: высокая производительность, прост в изучении, позволяет быстро писать код, готов к продакшн\n

      \n

      \n \n@@ -40,7 +40,7 @@ FastAPI — это современный, быстрый (высокопрои\n * **Скорость**: Очень высокая производительность, на уровне **NodeJS** и **Go** (благодаря Starlette и Pydantic). [Один из самых быстрых доступных фреймворков Python](#performance).\n * **Быстрота разработки**: Увеличьте скорость разработки фич примерно на 200–300%. *\n * **Меньше ошибок**: Сократите примерно на 40% количество ошибок, вызванных человеком (разработчиком). *\n-* **Интуитивность**: Отличная поддержка редактора кода. Автозавершение везде. Меньше времени на отладку.\n+* **Интуитивность**: Отличная поддержка редактора кода. Автозавершение везде. Меньше времени на отладку.\n * **Простота**: Разработан так, чтобы его было легко использовать и осваивать. Меньше времени на чтение документации.\n * **Краткость**: Минимизируйте дублирование кода. Несколько возможностей из каждого объявления параметров. Меньше ошибок.\n * **Надежность**: Получите код, готовый к продакшн. С автоматической интерактивной документацией.\n@@ -117,6 +117,12 @@ FastAPI — это современный, быстрый (высокопрои\n \n ---\n \n+## Мини-документальный фильм о FastAPI { #fastapi-mini-documentary }\n+\n+В конце 2025 года вышел мини-документальный фильм о FastAPI, вы можете посмотреть его онлайн:\n+\n+\"[NAME_REDACTED]\"\n+\n ## **Typer**, FastAPI для CLI { #typer-the-fastapi-of-clis }\n \n \n@@ -257,7 +263,7 @@ INFO: Application startup complete.\n \n * Получает HTTP-запросы по _путям_ `/` и `/items/{item_id}`.\n * Оба _пути_ используют `GET` операции (также известные как HTTP _методы_).\n-* _Путь_ `/items/{item_id}` имеет _параметр пути_ `item_id`, который должен быть `int`.\n+* _Путь_ `/items/{item_id}` имеет _path-параметр_ `item_id`, который должен быть `int`.\n * _Путь_ `/items/{item_id}` имеет необязательный `str` _параметр запроса_ `q`.\n \n ### Интерактивная документация API { #interactive-api-docs }\n@@ -278,9 +284,9 @@ INFO: Application startup complete.\n \n ## Пример обновления { #example-upgrade }\n \n-Теперь измените файл `main.py`, чтобы принимать тело запроса из `PUT` запроса.\n+Теперь измените файл `main.py`, чтобы принимать тело запроса из `PUT` HTTP-запроса.\n \n-Объявите тело, используя стандартные типы Python, спасибо Pydantic.\n+Объявите тело запроса, используя стандартные типы Python, спасибо Pydantic.\n \n ```Python hl_lines=\"4 9-12 25-27\"\n from typing import Union\n@@ -318,7 +324,7 @@ def update_item(item_id: int, item: Item):\n \n Перейдите на http://127.0.0.1:8000/docs.\n \n-* Интерактивная документация API будет автоматически обновлена, включая новое тело:\n+* Интерактивная документация API будет автоматически обновлена, включая новое тело запроса:\n \n ![Swagger UI](https://fastapi.tiangolo.com/img/index/index-03-swagger-02.png)\n \n@@ -334,13 +340,13 @@ def update_item(item_id: int, item: Item):\n \n Теперь откройте http://127.0.0.1:8000/redoc.\n \n-* Альтернативная документация также отразит новый параметр запроса и тело:\n+* Альтернативная документация также отразит новый параметр запроса и тело запроса:\n \n ![ReDoc](https://fastapi.tiangolo.com/img/index/index-06-redoc-02.png)\n \n ### Подведём итоги { #recap }\n \n-Итак, вы объявляете **один раз** типы параметров, тела запроса и т.д. как параметры функции.\n+Итак, вы объявляете **один раз** типы параметров, тело запроса и т.д. как параметры функции.\n \n Вы делаете это с помощью стандартных современных типов Python.\n \n@@ -390,13 +396,13 @@ item: Item\n \n Возвращаясь к предыдущему примеру кода, **FastAPI** будет:\n \n-* Валидировать наличие `item_id` в пути для `GET` и `PUT` запросов.\n-* Валидировать, что `item_id` имеет тип `int` для `GET` и `PUT` запросов.\n+* Валидировать наличие `item_id` в пути для `GET` и `PUT` HTTP-запросов.\n+* Валидировать, что `item_id` имеет тип `int` для `GET` и `PUT` HTTP-запросов.\n * Если это не так, клиент увидит полезную понятную ошибку.\n-* Проверять, есть ли необязательный параметр запроса с именем `q` (например, `http://127.0.0.1:8000/items/foo?q=somequery`) для `GET` запросов.\n+* Проверять, есть ли необязательный параметр запроса с именем `q` (например, `http://127.0.0.1:8000/items/foo?q=somequery`) для `GET` HTTP-запросов.\n * Поскольку параметр `q` объявлен с `= None`, он необязателен.\n * Без `None` он был бы обязательным (как тело запроса в случае с `PUT`).\n-* Для `PUT` запросов к `/items/{item_id}` читать тело запроса как JSON:\n+* Для `PUT` HTTP-запросов к `/items/{item_id}` читать тело запроса как JSON:\n * Проверять, что есть обязательный атрибут `name`, который должен быть `str`.\n * Проверять, что есть обязательный атрибут `price`, который должен быть `float`.\n * Проверять, что есть необязательный атрибут `is_offer`, который должен быть `bool`, если он присутствует.\n@@ -435,11 +441,11 @@ item: Item\n \n Более полный пример с дополнительными возможностями см. в Учебник - Руководство пользователя.\n \n-**Осторожно, спойлер**: учебник - руководство включает:\n+**Осторожно, спойлер**: учебник - руководство пользователя включает:\n \n * Объявление **параметров** из других источников: **HTTP-заголовки**, **cookies**, **поля формы** и **файлы**.\n * Как задать **ограничения валидации** вроде `maximum_length` или `regex`.\n-* Очень мощную и простую в использовании систему **внедрения зависимостей**.\n+* Очень мощную и простую в использовании систему **внедрения зависимостей**.\n * Безопасность и аутентификацию, включая поддержку **OAuth2** с **JWT токенами** и **HTTP Basic** аутентификацию.\n * Более продвинутые (но столь же простые) приёмы объявления **глубоко вложенных JSON-моделей** (спасибо Pydantic).\n * Интеграцию **GraphQL** с Strawberry и другими библиотеками.\n@@ -524,11 +530,11 @@ FastAPI зависит от Pydantic и Starlette.\n \n * httpx — обязателен, если вы хотите использовать `TestClient`.\n * jinja2 — обязателен, если вы хотите использовать конфигурацию шаблонов по умолчанию.\n-* python-multipart — обязателен, если вы хотите поддерживать «парсинг» форм через `request.form()`.\n+* python-multipart - обязателен, если вы хотите поддерживать «парсинг» форм через `request.form()`.\n \n Используется FastAPI:\n \n-* uvicorn — сервер, который загружает и обслуживает ваше приложение. Включает `uvicorn[standard]`, содержащий некоторые зависимости (например, `uvloop`), нужные для высокой производительности.\n+* uvicorn — сервер, который загружает и «отдаёт» ваше приложение. Включает `uvicorn[standard]`, содержащий некоторые зависимости (например, `uvloop`), нужные для высокой производительности.\n * `fastapi-cli[standard]` — чтобы предоставить команду `fastapi`.\n * Включает `fastapi-cloud-cli`, который позволяет развернуть ваше приложение FastAPI в [NAME_REDACTED]." }, { "filename": "docs/ru/docs/tutorial/bigger-applications.md", "status": "modified", "additions": 145, "deletions": 144, "changes": 289, "patch": "@@ -1,4 +1,4 @@\n-# Большие приложения, в которых много файлов { #bigger-applications-multiple-files }\n+# Большие приложения — несколько файлов { #bigger-applications-multiple-files }\n \n При построении приложения или веб-API нам редко удается поместить всё в один файл.\n \n@@ -31,7 +31,7 @@\n \n /// tip | Подсказка\n \n-Обратите внимание, что в каждом каталоге и подкаталоге имеется файл `__init__.py`\n+Есть несколько файлов `__init__.py`: по одному в каждом каталоге или подкаталоге.\n \n Это как раз то, что позволяет импортировать код из одного файла в другой.\n \n@@ -43,114 +43,115 @@ from app.routers import items\n \n ///\n \n-* Всё помещается в каталоге `app`. В нём также находится пустой файл `app/__init__.py`. Таким образом, `app` является \"Python-пакетом\" (коллекцией модулей Python).\n-* Он содержит файл `app/main.py`. Данный файл является частью пакета (т.е. находится внутри каталога, содержащего файл `__init__.py`), и, соответственно, он является модулем пакета: `app.main`.\n+* Всё помещается в каталоге `app`. В нём также находится пустой файл `app/__init__.py`. Таким образом, `app` является \"Python-пакетом\" (коллекцией \"Python-модулей\"): `app`.\n+* Он содержит файл `app/main.py`. Данный файл является частью Python-пакета (т.е. находится внутри каталога, содержащего файл `__init__.py`), и, соответственно, он является модулем этого пакета: `app.main`.\n * Он также содержит файл `app/dependencies.py`, который также, как и `app/main.py`, является модулем: `app.dependencies`.\n-* Здесь также находится подкаталог `app/routers/`, содержащий `__init__.py`. Он является суб-пакетом: `app.routers`.\n-* Файл `app/routers/items.py` находится внутри пакета `app/routers/`. Таким образом, он является суб-модулем: `app.routers.items`.\n-* Точно также `app/routers/users.py` является ещё одним суб-модулем: `app.routers.users`.\n-* Подкаталог `app/internal/`, содержащий файл `__init__.py`, является ещё одним суб-пакетом: `app.internal`.\n-* А файл `app/internal/admin.py` является ещё одним суб-модулем: `app.internal.admin`.\n+* Здесь также находится подкаталог `app/routers/`, содержащий `__init__.py`. Он является Python-подпакетом: `app.routers`.\n+* Файл `app/routers/items.py` находится внутри пакета `app/routers/`. Таким образом, он является подмодулем: `app.routers.items`.\n+* Точно так же `app/routers/users.py` является ещё одним подмодулем: `app.routers.users`.\n+* Подкаталог `app/internal/`, содержащий файл `__init__.py`, является ещё одним Python-подпакетом: `app.internal`.\n+* А файл `app/internal/admin.py` является ещё одним подмодулем: `app.internal.admin`.\n \n \n \n Та же самая файловая структура приложения, но с комментариями:\n \n-```\n+```bash\n .\n ├── app # \"app\" пакет\n │   ├── __init__.py # этот файл превращает \"app\" в \"Python-пакет\"\n │   ├── main.py # модуль \"main\", напр.: import app.main\n │   ├── dependencies.py # модуль \"dependencies\", напр.: import app.dependencies\n-│   └── routers # суб-пакет \"routers\"\n-│   │ ├── __init__.py # превращает \"routers\" в суб-пакет\n-│   │ ├── items.py # суб-модуль \"items\", напр.: import app.routers.items\n-│   │ └── users.py # суб-модуль \"users\", напр.: import app.routers.users\n-│   └── internal # суб-пакет \"internal\"\n-│   ├── __init__.py # превращает \"internal\" в суб-пакет\n-│   └── admin.py # суб-модуль \"admin\", напр.: import app.internal.admin\n+│   └── routers # подпакет \"routers\"\n+│   │ ├── __init__.py # превращает \"routers\" в подпакет\n+│   │ ├── items.py # подмодуль \"items\", напр.: import app.routers.items\n+│   │ └── users.py # подмодуль \"users\", напр.: import app.routers.users\n+│   └── internal # подпакет \"internal\"\n+│   ├── __init__.py # превращает \"internal\" в подпакет\n+│   └── admin.py # подмодуль \"admin\", напр.: import app.internal.admin\n ```\n \n ## `APIRouter` { #apirouter }\n \n-Давайте предположим, что для работы с пользователями используется отдельный файл (суб-модуль) `/app/routers/users.py`.\n+Давайте предположим, что для работы с пользователями используется отдельный файл (подмодуль) `/app/routers/users.py`.\n \n-Для лучшей организации приложения, вы хотите отделить операции пути, связанные с пользователями, от остального кода.\n+Вы хотите отделить *операции пути*, связанные с пользователями, от остального кода, чтобы сохранить порядок.\n \n-Но так, чтобы эти операции по-прежнему оставались частью **FastAPI** приложения/веб-API (частью одного пакета)\n+Но это всё равно часть того же приложения/веб-API на **FastAPI** (часть того же «Python-пакета»).\n \n-С помощью `APIRouter` вы можете создать *операции пути* (*эндпоинты*) для данного модуля.\n+С помощью `APIRouter` вы можете создать *операции пути* для этого модуля.\n \n ### Импорт `APIRouter` { #import-apirouter }\n \n-Точно также, как и в случае с классом `FastAPI`, вам нужно импортировать и создать объект класса `APIRouter`.\n+Точно так же, как и в случае с классом `FastAPI`, вам нужно импортировать и создать его «экземпляр»:\n \n {* ../../docs_src/bigger_applications/app_an_py39/routers/users.py hl[1,3] title[\"app/routers/users.py\"] *}\n \n-### Создание *эндпоинтов* с помощью `APIRouter` { #path-operations-with-apirouter }\n+### *Операции пути* с `APIRouter` { #path-operations-with-apirouter }\n+\n+И затем вы используете его, чтобы объявить ваши *операции пути*.\n \n-В дальнейшем используйте `APIRouter` для объявления *эндпоинтов*, точно также, как вы используете класс `FastAPI`:\n+Используйте его так же, как вы использовали бы класс `FastAPI`:\n \n {* ../../docs_src/bigger_applications/app_an_py39/routers/users.py hl[6,11,16] title[\"app/routers/users.py\"] *}\n \n-Вы можете думать об `APIRouter` как об \"уменьшенной версии\" класса FastAPI`.\n+Вы можете думать об `APIRouter` как об «мини-классе `FastAPI`».\n \n-`APIRouter` поддерживает все те же самые опции.\n+Поддерживаются все те же опции.\n \n-`APIRouter` поддерживает все те же самые параметры, такие как `parameters`, `responses`, `dependencies`, `tags`, и т. д.\n+Все те же `parameters`, `responses`, `dependencies`, `tags` и т.д.\n \n /// tip | Подсказка\n \n В данном примере, в качестве названия переменной используется `router`, но вы можете использовать любое другое имя.\n \n ///\n \n-Мы собираемся подключить данный `APIRouter` к нашему основному приложению на `FastAPI`, но сначала давайте проверим зависимости и создадим ещё один модуль с `APIRouter`.\n+Мы собираемся подключить данный `APIRouter` к нашему основному приложению на `FastAPI`, но сначала давайте проверим зависимости и ещё один `APIRouter`.\n \n ## Зависимости { #dependencies }\n \n-Нам понадобятся некоторые зависимости, которые мы будем использовать в разных местах нашего приложения.\n+Мы видим, что нам понадобятся некоторые зависимости, которые будут использоваться в нескольких местах приложения.\n \n-Мы поместим их в отдельный модуль `dependencies` (`app/dependencies.py`).\n+Поэтому мы поместим их в отдельный модуль `dependencies` (`app/dependencies.py`).\n \n-Теперь мы воспользуемся простой зависимостью, чтобы прочитать кастомизированный `X-Token` из заголовка:\n+Теперь мы воспользуемся простой зависимостью, чтобы прочитать кастомный HTTP-заголовок `X-Token`:\n \n {* ../../docs_src/bigger_applications/app_an_py39/dependencies.py hl[3,6:8] title[\"app/dependencies.py\"] *}\n \n /// tip | Подсказка\n \n-Для простоты мы воспользовались неким воображаемым заголовоком.\n+Для простоты мы воспользовались выдуманным заголовком.\n \n В реальных случаях для получения наилучших результатов используйте интегрированные [утилиты безопасности](security/index.md){.internal-link target=_blank}.\n \n ///\n \n ## Ещё один модуль с `APIRouter` { #another-module-with-apirouter }\n \n-Давайте также предположим, что у вас есть *эндпоинты*, отвечающие за обработку \"items\", и они находятся в модуле `app/routers/items.py`.\n+Давайте также предположим, что у вас есть эндпоинты, отвечающие за обработку «items» в вашем приложении, и они находятся в модуле `app/routers/items.py`.\n \n-У вас определены следующие *операции пути* (*эндпоинты*):\n+У вас определены *операции пути* для:\n \n * `/items/`\n * `/items/{item_id}`\n \n-Тут всё точно также, как и в ситуации с `app/routers/users.py`.\n+Тут всё та же структура, как и в случае с `app/routers/users.py`.\n \n-Но теперь мы хотим поступить немного умнее и слегка упростить код.\n+Но мы хотим поступить умнее и слегка упростить код.\n \n-Мы знаем, что все *эндпоинты* данного модуля имеют некоторые общие свойства:\n+Мы знаем, что все *операции пути* этого модуля имеют одинаковые:\n \n-* Префикс пути: `/items`.\n-* Теги: (один единственный тег: `items`).\n-* Дополнительные ответы (responses)\n-* Зависимости: использование созданной нами зависимости `X-token`\n+* `prefix` пути: `/items`.\n+* `tags`: (один единственный тег: `items`).\n+* Дополнительные `responses`.\n+* `dependencies`: всем им нужна та зависимость `X-Token`, которую мы создали.\n \n-Таким образом, вместо того чтобы добавлять все эти свойства в функцию каждого отдельного *эндпоинта*,\n-мы добавим их в `APIRouter`.\n+Таким образом, вместо того чтобы добавлять всё это в каждую *операцию пути*, мы можем добавить это в `APIRouter`.\n \n {* ../../docs_src/bigger_applications/app_an_py39/routers/items.py hl[5:10,16,21] title[\"app/routers/items.py\"] *}\n \n-Так как каждый *эндпоинт* начинается с символа `/`:\n+Так как путь каждой *операции пути* должен начинаться с `/`, как здесь:\n \n ```Python hl_lines=\"1\"\n [USER_REDACTED].get(\"/{item_id}\")\n@@ -162,94 +163,95 @@ async def read_item(item_id: str):\n \n В нашем случае префиксом является `/items`.\n \n-Мы также можем добавить в наш маршрутизатор (router) список `тегов` (`tags`) и дополнительных `ответов` (`responses`), которые являются общими для каждого *эндпоинта*.\n+Мы также можем добавить список `tags` и дополнительные `responses`, которые будут применяться ко всем *операциям пути*, включённым в этот маршрутизатор.\n \n-И ещё мы можем добавить в наш маршрутизатор список `зависимостей`, которые должны вызываться при каждом обращении к *эндпоинтам*.\n+И ещё мы можем добавить список `dependencies`, которые будут добавлены ко всем *операциям пути* в маршрутизаторе и будут выполняться/разрешаться для каждого HTTP-запроса к ним.\n \n /// tip | Подсказка\n \n-Обратите внимание, что также, как и в случае с зависимостями в декораторах *эндпоинтов* ([зависимости в декораторах операций пути](dependencies/dependencies-in-path-operation-decorators.md){.internal-link target=_blank}), никакого значения в *функцию эндпоинта* передано не будет.\n+Обратите внимание, что так же, как и в случае с [зависимостями в декораторах *операций пути*](dependencies/dependencies-in-path-operation-decorators.md){.internal-link target=_blank}, никакое значение не будет передано в вашу *функцию-обработчик пути*.\n \n ///\n \n-В результате мы получим следующие эндпоинты:\n+В результате пути для items теперь такие:\n \n * `/items/`\n * `/items/{item_id}`\n \n ...как мы и планировали.\n \n-* Они будут помечены тегами из заданного списка, в нашем случае это `\"items\"`.\n- * Эти теги особенно полезны для системы автоматической интерактивной документации (с использованием OpenAPI).\n-* Каждый из них будет включать предопределенные ответы `responses`.\n-* Каждый *эндпоинт* будет иметь список зависимостей (`dependencies`), исполняемых перед вызовом *эндпоинта*.\n- * Если вы определили зависимости в самой операции пути, **то она также будет выполнена**.\n- * Сначала выполняются зависимости маршрутизатора, затем вызываются [зависимости в декораторе](dependencies/dependencies-in-path-operation-decorators.md){.internal-link target=_blank}, и, наконец, обычные параметрические зависимости.\n- * Вы также можете добавить [зависимости `Security` с `scopes`](../advanced/security/oauth2-scopes.md){.internal-link target=_blank}.\n+* Они будут помечены списком тегов, содержащим одну строку `\"items\"`.\n+ * Эти «теги» особенно полезны для систем автоматической интерактивной документации (с использованием OpenAPI).\n+* Все они будут включать предопределённые `responses`.\n+* Все эти *операции пути* будут иметь список `dependencies`, вычисляемых/выполняемых перед ними.\n+ * Если вы также объявите зависимости в конкретной *операции пути*, **они тоже будут выполнены**.\n+ * Сначала выполняются зависимости маршрутизатора, затем [`dependencies` в декораторе](dependencies/dependencies-in-path-operation-decorators.md){.internal-link target=_blank}, и затем обычные параметрические зависимости.\n+ * Вы также можете добавить [`Security`-зависимости с `scopes`](../advanced/security/oauth2-scopes.md){.internal-link target=_blank}.\n \n /// tip | Подсказка\n \n-Например, с помощью зависимостей в `APIRouter` мы можем потребовать аутентификации для доступа ко всей группе *эндпоинтов*, не указывая зависимости для каждой отдельной функции *эндпоинта*.\n+Например, с помощью зависимостей в `APIRouter` мы можем потребовать аутентификации для доступа ко всей группе *операций пути*. Даже если зависимости не добавляются по отдельности к каждой из них.\n \n ///\n \n /// check | Заметка\n \n-Параметры `prefix`, `tags`, `responses` и `dependencies` относятся к функционалу **FastAPI**, помогающему избежать дублирования кода.\n+Параметры `prefix`, `tags`, `responses` и `dependencies` — это (как и во многих других случаях) просто возможность **FastAPI**, помогающая избежать дублирования кода.\n \n ///\n \n ### Импорт зависимостей { #import-the-dependencies }\n \n-Наш код находится в модуле `app.routers.items` (файл `app/routers/items.py`).\n+Этот код находится в модуле `app.routers.items`, в файле `app/routers/items.py`.\n \n-И нам нужно вызвать функцию зависимости из модуля `app.dependencies` (файл `app/dependencies.py`).\n+И нам нужно получить функцию зависимости из модуля `app.dependencies`, файла `app/dependencies.py`.\n \n-Мы используем операцию относительного импорта `..` для импорта зависимости:\n+Поэтому мы используем относительный импорт с `..` для зависимостей:\n \n {* ../../docs_src/bigger_applications/app_an_py39/routers/items.py hl[3] title[\"app/routers/items.py\"] *}\n \n-#### Как работает относительный импорт? { #how-relative-imports-work }\n+#### Как работает относительный импорт { #how-relative-imports-work }\n \n /// tip | Подсказка\n \n-Если вы прекрасно знаете, как работает импорт в Python, то переходите к следующему разделу.\n+Если вы прекрасно знаете, как работает импорт, переходите к следующему разделу ниже.\n \n ///\n \n-Одна точка `.`, как в данном примере:\n+Одна точка `.`, как здесь:\n \n ```Python\n from .dependencies import get_token_header\n ```\n+\n означает:\n \n-* Начните с пакета, в котором находится данный модуль (файл `app/routers/items.py` расположен в каталоге `app/routers/`)...\n-* ... найдите модуль `dependencies` (файл `app/routers/dependencies.py`)...\n-* ... и импортируйте из него функцию `get_token_header`.\n+* Начать в том же пакете, в котором находится этот модуль (файл `app/routers/items.py`) (каталог `app/routers/`)...\n+* найти модуль `dependencies` (воображаемый файл `app/routers/dependencies.py`)...\n+* и импортировать из него функцию `get_token_header`.\n \n-К сожалению, такого файла не существует, и наши зависимости находятся в файле `app/dependencies.py`.\n+Но такого файла не существует, наши зависимости находятся в файле `app/dependencies.py`.\n \n Вспомните, как выглядит файловая структура нашего приложения:\n \n \n \n ---\n \n-Две точки `..`, как в данном примере:\n+Две точки `..`, как здесь:\n \n ```Python\n from ..dependencies import get_token_header\n ```\n \n означают:\n \n-* Начните с пакета, в котором находится данный модуль (файл `app/routers/items.py` находится в каталоге `app/routers/`)...\n-* ... перейдите в родительский пакет (каталог `app/`)...\n-* ... найдите в нём модуль `dependencies` (файл `app/dependencies.py`)...\n-* ... и импортируйте из него функцию `get_token_header`.\n+* Начать в том же пакете, в котором находится этот модуль (файл `app/routers/items.py`) (каталог `app/routers/`)...\n+* перейти в родительский пакет (каталог `app/`)...\n+* и там найти модуль `dependencies` (файл `app/dependencies.py`)...\n+* и импортировать из него функцию `get_token_header`.\n \n-Это работает верно! 🎉\n+Это работает корректно! 🎉\n \n ---\n \n@@ -261,29 +263,29 @@ from ...dependencies import get_token_header\n \n то это бы означало:\n \n-* Начните с пакета, в котором находится данный модуль (файл `app/routers/items.py` находится в каталоге `app/routers/`)...\n-* ... перейдите в родительский пакет (каталог `app/`)...\n-* ... затем перейдите в родительский пакет текущего пакета (такого пакета не существует, `app` находится на самом верхнем уровне 😱)...\n-* ... найдите в нём модуль `dependencies` (файл `app/dependencies.py`)...\n-* ... и импортируйте из него функцию `get_token_header`.\n+* Начать в том же пакете, в котором находится этот модуль (файл `app/routers/items.py`) расположен в (каталоге `app/routers/`)...\n+* перейти в родительский пакет (каталог `app/`)...\n+* затем перейти в родительский пакет этого пакета (родительского пакета нет, `app` — верхний уровень 😱)...\n+* и там найти модуль `dependencies` (файл `app/dependencies.py`)...\n+* и импортировать из него функцию `get_token_header`.\n \n-Это будет относиться к некоторому пакету, находящемуся на один уровень выше чем `app/` и содержащему свой собственный файл `__init__.py`. Но ничего такого у нас нет. Поэтому это приведет к ошибке в нашем примере. 🚨\n+Это ссылалось бы на какой-то пакет выше `app/`, со своим файлом `__init__.py` и т.п. Но у нас такого нет. Поэтому это вызвало бы ошибку в нашем примере. 🚨\n \n-Теперь вы знаете, как работает импорт в Python, и сможете использовать относительное импортирование в своих собственных приложениях любого уровня сложности. 🤓\n+Но теперь вы знаете, как это работает, так что можете использовать относительные импорты в своих приложениях, независимо от того, насколько они сложные. 🤓\n \n-### Добавление пользовательских тегов (`tags`), ответов (`responses`) и зависимостей (`dependencies`) { #add-some-custom-tags-responses-and-dependencies }\n+### Добавление пользовательских `tags`, `responses` и `dependencies` { #add-some-custom-tags-responses-and-dependencies }\n \n-Мы не будем добавлять префикс `/items` и список тегов `tags=[\"items\"]` для каждого *эндпоинта*, т.к. мы уже их добавили с помощью `APIRouter`.\n+Мы не добавляем префикс `/items` и `tags=[\"items\"]` к каждой *операции пути*, потому что мы добавили их в `APIRouter`.\n \n-Но помимо этого мы можем добавить новые теги для каждого отдельного *эндпоинта*, а также некоторые дополнительные ответы (`responses`), характерные для данного *эндпоинта*:\n+Но мы всё равно можем добавить _ещё_ `tags`, которые будут применяться к конкретной *операции пути*, а также дополнительные `responses`, специфичные для этой *операции пути*:\n \n {* ../../docs_src/bigger_applications/app_an_py39/routers/items.py hl[30:31] title[\"app/routers/items.py\"] *}\n \n /// tip | Подсказка\n \n-Последний *эндпоинт* будет иметь следующую комбинацию тегов: `[\"items\", \"custom\"]`.\n+Эта последняя операция пути будет иметь комбинацию тегов: `[\"items\", \"custom\"]`.\n \n-А также в его документации будут содержаться оба ответа: один для `404` и другой для `403`.\n+И в документации у неё будут оба ответа: один для `404` и один для `403`.\n \n ///\n \n@@ -293,90 +295,90 @@ from ...dependencies import get_token_header\n \n Именно сюда вы импортируете и именно здесь вы используете класс `FastAPI`.\n \n-Это основной файл вашего приложения, который объединяет всё в одно целое.\n+Это основной файл вашего приложения, который связывает всё воедино.\n \n-И теперь, когда большая часть логики приложения разделена на отдельные модули, основной файл `app/main.py` будет достаточно простым.\n+И так как большая часть вашей логики теперь будет находиться в отдельных специфичных модулях, основной файл будет довольно простым.\n \n ### Импорт `FastAPI` { #import-fastapi }\n \n-Вы импортируете и создаете класс `FastAPI` как обычно.\n+Вы импортируете и создаёте класс `FastAPI` как обычно.\n \n-Мы даже можем объявить [глобальные зависимости](dependencies/global-dependencies.md){.internal-link target=_blank}, которые будут объединены с зависимостями для каждого отдельного маршрутизатора:\n+И мы даже можем объявить [глобальные зависимости](dependencies/global-dependencies.md){.internal-link target=_blank}, которые будут объединены с зависимостями для каждого `APIRouter`:\n \n {* ../../docs_src/bigger_applications/app_an_py39/main.py hl[1,3,7] title[\"app/main.py\"] *}\n \n ### Импорт `APIRouter` { #import-the-apirouter }\n \n-Теперь мы импортируем другие суб-модули, содержащие `APIRouter`:\n+Теперь мы импортируем другие подмодули, содержащие `APIRouter`:\n \n {* ../../docs_src/bigger_applications/app_an_py39/main.py hl[4:5] title[\"app/main.py\"] *}\n \n-Так как файлы `app/routers/users.py` и `app/routers/items.py` являются суб-модулями одного и того же Python-пакета `app`, то мы сможем их импортировать, воспользовавшись операцией относительного импорта `.`.\n+Так как файлы `app/routers/users.py` и `app/routers/items.py` являются подмодулями, входящими в один и тот же Python-пакет `app`, мы можем использовать одну точку `.` для импорта через «относительные импорты».\n \n-### Как работает импорт? { #how-the-importing-works }\n+### Как работает импорт { #how-the-importing-works }\n \n-Данная строка кода:\n+Этот фрагмент:\n \n ```Python\n from .routers import items, users\n ```\n \n означает:\n \n-* Начните с пакета, в котором содержится данный модуль (файл `app/main.py` содержится в каталоге `app/`)...\n-* ... найдите суб-пакет `routers` (каталог `app/routers/`)...\n-* ... и из него импортируйте суб-модули `items` (файл `app/routers/items.py`) и `users` (файл `app/routers/users.py`)...\n+* Начать в том же пакете, в котором находится этот модуль (файл `app/main.py`) расположен в (каталоге `app/`)...\n+* найти подпакет `routers` (каталог `app/routers/`)...\n+* и импортировать из него подмодули `items` (файл `app/routers/items.py`) и `users` (файл `app/routers/users.py`)...\n \n-В модуле `items` содержится переменная `router` (`items.router`), та самая, которую мы создали в файле `app/routers/items.py`, она является объектом класса `APIRouter`.\n+В модуле `items` будет переменная `router` (`items.router`). Это та же самая, которую мы создали в файле `app/routers/items.py`, это объект `APIRouter`.\n \n-И затем мы сделаем то же самое для модуля `users`.\n+И затем мы делаем то же самое для модуля `users`.\n \n-Мы также могли бы импортировать и другим методом:\n+Мы также могли бы импортировать их так:\n \n ```Python\n from app.routers import items, users\n ```\n \n /// info | Примечание\n \n-Первая версия является примером относительного импорта:\n+Первая версия — это «относительный импорт»:\n \n ```Python\n from .routers import items, users\n ```\n \n-Вторая версия является примером абсолютного импорта:\n+Вторая версия — это «абсолютный импорт»:\n \n ```Python\n from app.routers import items, users\n ```\n \n-Узнать больше о пакетах и модулях в Python вы можете из официальной документации Python о модулях\n+Чтобы узнать больше о Python-пакетах и модулях, прочитайте официальную документацию Python о модулях.\n \n ///\n \n-### Избегайте конфликтов имен { #avoid-name-collisions }\n+### Избегайте конфликтов имён { #avoid-name-collisions }\n \n-Вместо того чтобы импортировать только переменную `router`, мы импортируем непосредственно суб-модуль `items`.\n+Мы импортируем подмодуль `items` напрямую, вместо того чтобы импортировать только его переменную `router`.\n \n-Мы делаем это потому, что у нас есть ещё одна переменная `router` в суб-модуле `users`.\n+Это потому, что у нас также есть другая переменная с именем `router` в подмодуле `users`.\n \n-Если бы мы импортировали их одну за другой, как показано в примере:\n+Если бы мы импортировали их одну за другой, как здесь:\n \n ```Python\n from .routers.items import router\n from .routers.users import router\n ```\n \n-то переменная `router` из `users` переписал бы переменную `router` из `items`, и у нас не было бы возможности использовать их одновременно.\n+то `router` из `users` перезаписал бы `router` из `items`, и мы не смогли бы использовать их одновременно.\n \n-Поэтому, для того чтобы использовать обе эти переменные в одном файле, мы импортировали соответствующие суб-модули:\n+Поэтому, чтобы иметь возможность использовать обе в одном файле, мы импортируем подмодули напрямую:\n \n {* ../../docs_src/bigger_applications/app_an_py39/main.py hl[5] title[\"app/main.py\"] *}\n \n-### Подключение маршрутизаторов (`APIRouter`) для `users` и для `items` { #include-the-apirouters-for-users-and-items }\n+### Подключение `APIRouter` для `users` и `items` { #include-the-apirouters-for-users-and-items }\n \n-Давайте подключим маршрутизаторы (`router`) из суб-модулей `users` и `items`:\n+Теперь давайте подключим `router` из подмодулей `users` и `items`:\n \n {* ../../docs_src/bigger_applications/app_an_py39/main.py hl[10:11] title[\"app/main.py\"] *}\n \n@@ -388,79 +390,78 @@ from .routers.users import router\n \n ///\n \n-С помощью `app.include_router()` мы можем добавить каждый из маршрутизаторов (`APIRouter`) в основное приложение `FastAPI`.\n+С помощью `app.include_router()` мы можем добавить каждый `APIRouter` в основное приложение `FastAPI`.\n \n-Он подключит все маршруты заданного маршрутизатора к нашему приложению.\n+Он включит все маршруты этого маршрутизатора как часть приложения.\n \n /// note | Технические детали\n \n-Фактически, внутри он создаст все *операции пути* для каждой операции пути объявленной в `APIRouter`.\n+Фактически, внутри он создаст *операцию пути* для каждой *операции пути*, объявленной в `APIRouter`.\n \n-И под капотом всё будет работать так, как будто бы мы имеем дело с одним файлом приложения.\n+Так что под капотом всё будет работать так, как будто всё было одним приложением.\n \n ///\n \n /// check | Заметка\n \n-При подключении маршрутизаторов не стоит беспокоиться о производительности.\n+При подключении маршрутизаторов не нужно беспокоиться о производительности.\n \n-Операция подключения займёт микросекунды и понадобится только при запуске приложения.\n+Это займёт микросекунды и произойдёт только при старте.\n \n-Таким образом, это не повлияет на производительность. ⚡\n+Так что это не повлияет на производительность. ⚡\n \n ///\n \n-### Подключение `APIRouter` с пользовательскими префиксом (`prefix`), тегами (`tags`), ответами (`responses`), и зависимостями (`dependencies`) { #include-an-apirouter-with-a-custom-prefix-tags-responses-and-dependencies }\n+### Подключение `APIRouter` с пользовательскими `prefix`, `tags`, `responses` и `dependencies` { #include-an-apirouter-with-a-custom-prefix-tags-responses-and-dependencies }\n \n Теперь давайте представим, что ваша организация передала вам файл `app/internal/admin.py`.\n \n-Он содержит `APIRouter` с некоторыми *эндпоитами* администрирования, которые ваша организация использует для нескольких проектов.\n+Он содержит `APIRouter` с некоторыми административными *операциями пути*, которые ваша организация использует в нескольких проектах.\n \n-В данном примере это сделать очень просто. Но давайте предположим, что поскольку файл используется для нескольких проектов,\n-то мы не можем модифицировать его, добавляя префиксы (`prefix`), зависимости (`dependencies`), теги (`tags`), и т.д. непосредственно в `APIRouter`:\n+Для этого примера всё будет очень просто. Но допустим, что поскольку он используется совместно с другими проектами в организации, мы не можем модифицировать его и добавить `prefix`, `dependencies`, `tags` и т.д. непосредственно в `APIRouter`:\n \n {* ../../docs_src/bigger_applications/app_an_py39/internal/admin.py hl[3] title[\"app/internal/admin.py\"] *}\n \n-Но, несмотря на это, мы хотим использовать кастомный префикс (`prefix`) для подключенного маршрутизатора (`APIRouter`), в результате чего, каждая *операция пути* будет начинаться с `/admin`. Также мы хотим защитить наш маршрутизатор с помощью зависимостей, созданных для нашего проекта. И ещё мы хотим включить теги (`tags`) и ответы (`responses`).\n+Но мы всё равно хотим задать пользовательский `prefix` при подключении `APIRouter`, чтобы все его *операции пути* начинались с `/admin`, хотим защитить его с помощью `dependencies`, которые у нас уже есть для этого проекта, и хотим включить `tags` и `responses`.\n \n-Мы можем применить все вышеперечисленные настройки, не изменяя начальный `APIRouter`. Нам всего лишь нужно передать нужные параметры в `app.include_router()`.\n+Мы можем объявить всё это, не изменяя исходный `APIRouter`, передав эти параметры в `app.include_router()`:\n \n {* ../../docs_src/bigger_applications/app_an_py39/main.py hl[14:17] title[\"app/main.py\"] *}\n \n-Таким образом, оригинальный `APIRouter` не будет модифицирован, и мы сможем использовать файл `app/internal/admin.py` сразу в нескольких проектах организации.\n+Таким образом исходный `APIRouter` не будет модифицирован, и мы сможем использовать файл `app/internal/admin.py` сразу в нескольких проектах организации.\n \n-В результате, в нашем приложении каждый *эндпоинт* модуля `admin` будет иметь:\n+В результате в нашем приложении каждая из *операций пути* из модуля `admin` будет иметь:\n \n * Префикс `/admin`.\n * Тег `admin`.\n * Зависимость `get_token_header`.\n * Ответ `418`. 🍵\n \n-Это будет иметь место исключительно для `APIRouter` в нашем приложении, и не затронет любой другой код, использующий его.\n+Но это повлияет только на этот `APIRouter` в нашем приложении, а не на любой другой код, который его использует.\n \n-Например, другие проекты, могут использовать тот же самый `APIRouter` с другими методами аутентификации.\n+Так что, например, другие проекты могут использовать тот же `APIRouter` с другим методом аутентификации.\n \n-### Подключение отдельного *эндпоинта* { #include-a-path-operation }\n+### Подключение *операции пути* { #include-a-path-operation }\n \n-Мы также можем добавить *эндпоинт* непосредственно в основное приложение `FastAPI`.\n+Мы также можем добавлять *операции пути* напрямую в приложение `FastAPI`.\n \n-Здесь мы это делаем ... просто, чтобы показать, что это возможно 🤷:\n+Здесь мы делаем это... просто чтобы показать, что можем 🤷:\n \n {* ../../docs_src/bigger_applications/app_an_py39/main.py hl[21:23] title[\"app/main.py\"] *}\n \n-и это будет работать корректно вместе с другими *эндпоинтами*, добавленными с помощью `app.include_router()`.\n+и это будет работать корректно вместе со всеми другими *операциями пути*, добавленными через `app.include_router()`.\n \n-/// info | Сложные технические детали\n+/// info | Очень технические детали\n \n-**Примечание**: это сложная техническая деталь, которую, скорее всего, **вы можете пропустить**.\n+**Примечание**: это очень техническая деталь, которую, вероятно, можно **просто пропустить**.\n \n ---\n \n-Маршрутизаторы (`APIRouter`) не \"монтируются\" по-отдельности и не изолируются от остального приложения.\n+`APIRouter` не «монтируются», они не изолированы от остального приложения.\n \n-Это происходит потому, что нужно включить их *эндпоинты* в OpenAPI схему и в интерфейс пользователя.\n+Это потому, что мы хотим включить их *операции пути* в OpenAPI-схему и пользовательские интерфейсы.\n \n-В силу того, что мы не можем их изолировать и \"примонтировать\" независимо от остальных, *эндпоинты* клонируются (пересоздаются) и не подключаются напрямую.\n+Так как мы не можем просто изолировать их и «смонтировать» независимо от остального, *операции пути* «клонируются» (пересоздаются), а не включаются напрямую.\n \n ///\n \n@@ -480,24 +481,24 @@ $ fastapi dev app/main.py\n \n Откройте документацию по адресу http://127.0.0.1:8000/docs.\n \n-Вы увидите автоматическую API документацию. Она включает в себя маршруты из суб-модулей, используя верные маршруты, префиксы и теги:\n+Вы увидите автоматическую документацию API, включая пути из всех подмодулей, с использованием корректных путей (и префиксов) и корректных тегов:\n \n \n \n-## Подключение существующего маршрута через новый префикс (`prefix`) { #include-the-same-router-multiple-times-with-different-prefix }\n+## Подключение одного и того же маршрутизатора несколько раз с разными `prefix` { #include-the-same-router-multiple-times-with-different-prefix }\n \n-Вы можете использовать `.include_router()` несколько раз с одним и тем же маршрутом, применив различные префиксы.\n+Вы можете использовать `.include_router()` несколько раз с *одним и тем же* маршрутизатором, используя разные префиксы.\n \n-Это может быть полезным, если нужно предоставить доступ к одному и тому же API через различные префиксы, например, `/api/v1` и `/api/latest`.\n+Это может быть полезно, например, чтобы предоставить доступ к одному и тому же API с разными префиксами, например `/api/v1` и `/api/latest`.\n \n-Это продвинутый способ, который вам может и не пригодится. Мы приводим его на случай, если вдруг вам это понадобится.\n+Это продвинутое использование, которое вам может и не понадобиться, но оно есть на случай, если понадобится.\n \n-## Включение одного маршрутизатора (`APIRouter`) в другой { #include-an-apirouter-in-another }\n+## Подключение `APIRouter` в другой `APIRouter` { #include-an-apirouter-in-another }\n \n-Точно так же, как вы включаете `APIRouter` в приложение `FastAPI`, вы можете включить `APIRouter` в другой `APIRouter`:\n+Точно так же, как вы можете подключить `APIRouter` к приложению `FastAPI`, вы можете подключить `APIRouter` к другому `APIRouter`, используя:\n \n ```Python\n router.include_router(other_router)\n ```\n \n-Удостоверьтесь, что вы сделали это до того, как подключить маршрутизатор (`router`) к вашему `FastAPI` приложению, и *эндпоинты* маршрутизатора `other_router` были также подключены.\n+Убедитесь, что вы сделали это до подключения `router` к приложению `FastAPI`, чтобы *операции пути* из `other_router` также были подключены." }, { "filename": "docs/ru/docs/tutorial/body-updates.md", "status": "modified", "additions": 10, "deletions": 24, "changes": 34, "patch": "@@ -2,13 +2,13 @@\n \n ## Обновление с заменой при помощи `PUT` { #update-replacing-with-put }\n \n-Для полного обновления элемента можно воспользоваться операцией HTTP `PUT`.\n+Чтобы обновить элемент, вы можете использовать операцию HTTP `PUT`.\n \n Вы можете использовать `jsonable_encoder`, чтобы преобразовать входные данные в данные, которые можно сохранить как JSON (например, в NoSQL-базе данных). Например, преобразование `datetime` в `str`.\n \n {* ../../docs_src/body_updates/tutorial001_py310.py hl[28:33] *}\n \n-`PUT` используется для получения данных, которые должны полностью заменить существующие данные.\n+`PUT` используется для получения данных, которые должны заменить существующие данные.\n \n ### Предупреждение о замене { #warning-about-replacing }\n \n@@ -24,11 +24,11 @@\n \n поскольку оно не включает уже сохраненный атрибут `\"tax\": 20.2`, входная модель примет значение по умолчанию `\"tax\": 10.5`.\n \n-И данные будут сохранены с этим \"новым\" `tax`, равным `10,5`.\n+И данные будут сохранены с этим «новым» `tax`, равным `10.5`.\n \n ## Частичное обновление с помощью `PATCH` { #partial-updates-with-patch }\n \n-Также можно использовать HTTP `PATCH` операцию для *частичного* обновления данных.\n+Также можно использовать операцию HTTP `PATCH` для *частичного* обновления данных.\n \n Это означает, что можно передавать только те данные, которые необходимо обновить, оставляя остальные нетронутыми.\n \n@@ -46,34 +46,20 @@\n \n ### Использование параметра `exclude_unset` в Pydantic { #using-pydantics-exclude-unset-parameter }\n \n-Если необходимо выполнить частичное обновление, то очень полезно использовать параметр `exclude_unset` в методе `.model_dump()` модели Pydantic.\n+Если вы хотите получать частичные обновления, очень полезно использовать параметр `exclude_unset` в `.model_dump()` модели Pydantic.\n \n Например, `item.model_dump(exclude_unset=True)`.\n \n-/// info | Информация\n+В результате будет сгенерирован `dict`, содержащий только те данные, которые были заданы при создании модели `item`, без учета значений по умолчанию.\n \n-В Pydantic v1 метод назывался `.dict()`, в Pydantic v2 он помечен как устаревший (но все еще поддерживается) и переименован в `.model_dump()`.\n-\n-Примеры здесь используют `.dict()` для совместимости с Pydantic v1, но если вы можете использовать Pydantic v2, лучше используйте `.model_dump()`.\n-\n-///\n-\n-В результате будет сгенерирован словарь, содержащий только те данные, которые были заданы при создании модели `item`, без учета значений по умолчанию. Затем вы можете использовать это для создания словаря только с теми данными, которые были установлены (отправлены в запросе), опуская значения по умолчанию:\n+Затем вы можете использовать это для создания `dict` только с теми данными, которые были установлены (отправлены в запросе), опуская значения по умолчанию:\n \n {* ../../docs_src/body_updates/tutorial002_py310.py hl[32] *}\n \n ### Использование параметра `update` в Pydantic { #using-pydantics-update-parameter }\n \n Теперь можно создать копию существующей модели, используя `.model_copy()`, и передать параметр `update` с `dict`, содержащим данные для обновления.\n \n-/// info | Информация\n-\n-В Pydantic v1 метод назывался `.copy()`, в Pydantic v2 он помечен как устаревший (но все еще поддерживается) и переименован в `.model_copy()`.\n-\n-Примеры здесь используют `.copy()` для совместимости с Pydantic v1, но если вы можете использовать Pydantic v2, лучше используйте `.model_copy()`.\n-\n-///\n-\n Например, `stored_item_model.model_copy(update=update_data)`:\n \n {* ../../docs_src/body_updates/tutorial002_py310.py hl[33] *}\n@@ -84,9 +70,9 @@\n \n * (Опционально) использовать `PATCH` вместо `PUT`.\n * Извлечь сохранённые данные.\n-* Поместить эти данные в Pydantic модель.\n+* Поместить эти данные в Pydantic-модель.\n * Сгенерировать `dict` без значений по умолчанию из входной модели (с использованием `exclude_unset`).\n- * Таким образом, можно обновлять только те значения, которые действительно установлены пользователем, вместо того чтобы переопределять значения, уже сохраненные в модели по умолчанию.\n+ * Таким образом, можно обновлять только те значения, которые действительно установлены пользователем, вместо того чтобы переопределять уже сохраненные значения значениями по умолчанию из вашей модели.\n * Создать копию хранимой модели, обновив ее атрибуты полученными частичными обновлениями (с помощью параметра `update`).\n * Преобразовать скопированную модель в то, что может быть сохранено в вашей БД (например, с помощью `jsonable_encoder`).\n * Это сравнимо с повторным использованием метода модели `.model_dump()`, но при этом происходит проверка (и преобразование) значений в типы данных, которые могут быть преобразованы в JSON, например, `datetime` в `str`.\n@@ -97,7 +83,7 @@\n \n /// tip | Подсказка\n \n-Эту же технику можно использовать и для операции HTTP `PUT`.\n+На самом деле эту же технику можно использовать и для операции HTTP `PUT`.\n \n Но в приведенном примере используется `PATCH`, поскольку он был создан именно для таких случаев использования." }, { "filename": "docs/ru/docs/tutorial/body.md", "status": "modified", "additions": 8, "deletions": 14, "changes": 22, "patch": "@@ -32,9 +32,10 @@\n \n {* ../../docs_src/body/tutorial001_py310.py hl[5:9] *}\n \n+\n Так же, как при объявлении параметров запроса: когда атрибут модели имеет значение по умолчанию, он не обязателен. Иначе он обязателен. Используйте `None`, чтобы сделать его просто необязательным.\n \n-Например, модель выше описывает такой JSON \"объект\" (или Python `dict`):\n+Например, модель выше описывает такой JSON \"`object`\" (или Python `dict`):\n \n ```JSON\n {\n@@ -45,7 +46,7 @@\n }\n ```\n \n-...так как `description` и `tax` являются необязательными (со значением по умолчанию `None`), такой JSON \"объект\" тоже будет корректным:\n+...так как `description` и `tax` являются необязательными (со значением по умолчанию `None`), такой JSON \"`object`\" тоже будет корректным:\n \n ```JSON\n {\n@@ -73,7 +74,7 @@\n * Передаст полученные данные в параметр `item`.\n * Поскольку внутри функции вы объявили его с типом `Item`, у вас будет поддержка со стороны редактора кода (автозавершение и т. п.) для всех атрибутов и их типов.\n * Сгенерирует определения JSON Schema для вашей модели; вы можете использовать их и в других местах, если это имеет смысл для вашего проекта.\n-* Эти схемы будут частью сгенерированной схемы OpenAPI и будут использоваться автоматической документацией UIs.\n+* Эти схемы будут частью сгенерированной схемы OpenAPI и будут использоваться автоматической документацией UIs.\n \n ## Автоматическая документация { #automatic-docs }\n \n@@ -127,14 +128,6 @@ JSON Schema ваших моделей будет частью сгенериро\n \n {* ../../docs_src/body/tutorial002_py310.py *}\n \n-/// info | Информация\n-\n-В Pydantic v1 метод назывался `.dict()`, в Pydantic v2 он был помечен как устаревший (но всё ещё поддерживается) и переименован в `.model_dump()`.\n-\n-Примеры здесь используют `.dict()` для совместимости с Pydantic v1, но если вы можете использовать Pydantic v2, используйте `.model_dump()`.\n-\n-///\n-\n ## Тело запроса + параметры пути { #request-body-path-parameters }\n \n Вы можете одновременно объявить параметры пути и тело запроса.\n@@ -143,6 +136,7 @@ JSON Schema ваших моделей будет частью сгенериро\n \n {* ../../docs_src/body/tutorial003_py310.py hl[15:16] *}\n \n+\n ## Тело запроса + параметры пути + параметры запроса { #request-body-path-query-parameters }\n \n Вы также можете одновременно объявить параметры **тела**, **пути** и **запроса**.\n@@ -153,20 +147,20 @@ JSON Schema ваших моделей будет частью сгенериро\n \n Параметры функции будут распознаны следующим образом:\n \n-* Если параметр также объявлен в **пути**, он будет использоваться как параметр пути.\n+* Если параметр также объявлен в **пути**, он будет использоваться как path-параметр.\n * Если параметр имеет **скалярный тип** (например, `int`, `float`, `str`, `bool` и т. п.), он будет интерпретирован как параметр **запроса**.\n * Если параметр объявлен как тип **модели Pydantic**, он будет интерпретирован как **тело** запроса.\n \n /// note | Заметка\n \n FastAPI понимает, что значение `q` не является обязательным из-за значения по умолчанию `= None`.\n \n-Аннотации типов `str | None` (Python 3.10+) или `Union[str, None]` (Python 3.9+) не используются FastAPI для определения обязательности; он узнает, что параметр не обязателен, потому что у него есть значение по умолчанию `= None`.\n+Аннотации типов `str | None` (Python 3.10+) или `Union` в `Union[str, None]` (Python 3.9+) не используются FastAPI для определения обязательности; он узнает, что параметр не обязателен, потому что у него есть значение по умолчанию `= None`.\n \n Но добавление аннотаций типов позволит вашему редактору кода лучше вас поддерживать и обнаруживать ошибки.\n \n ///\n \n ## Без Pydantic { #without-pydantic }\n \n-Если вы не хотите использовать модели Pydantic, вы также можете использовать параметры **Body**. См. раздел документации [Тело — Несколько параметров: Единичные значения в теле](body-multiple-params.md#singular-values-in-body){.internal-link target=_blank}.\n+Если вы не хотите использовать модели Pydantic, вы также можете использовать параметры **Body**. См. раздел документации [Тело запроса - Несколько параметров: Единичные значения в теле](body-multiple-params.md#singular-values-in-body){.internal-link target=_blank}." }, { "filename": "docs/ru/docs/tutorial/extra-models.md", "status": "modified", "additions": 27, "deletions": 35, "changes": 62, "patch": "@@ -22,21 +22,13 @@\n \n {* ../../docs_src/extra_models/tutorial001_py310.py hl[7,9,14,20,22,27:28,31:33,38:39] *}\n \n-/// info | Информация\n+### Про `**user_in.model_dump()` { #about-user-in-model-dump }\n \n-В Pydantic v1 метод назывался `.dict()`, в Pydantic v2 он помечен как устаревший (но всё ещё поддерживается) и переименован в `.model_dump()`.\n+#### `.model_dump()` из Pydantic { #pydantics-model-dump }\n \n-В примерах здесь используется `.dict()` для совместимости с Pydantic v1, но если вы используете Pydantic v2, следует использовать `.model_dump()`.\n+`user_in` — это Pydantic-модель класса `UserIn`.\n \n-///\n-\n-### Про `**user_in.dict()` { #about-user-in-dict }\n-\n-#### `.dict()` из Pydantic { #pydantics-dict }\n-\n-`user_in` - это Pydantic-модель класса `UserIn`.\n-\n-У Pydantic-моделей есть метод `.dict()`, который возвращает `dict` с данными модели.\n+У Pydantic-моделей есть метод `.model_dump()`, который возвращает `dict` с данными модели.\n \n Поэтому, если мы создадим Pydantic-объект `user_in` таким способом:\n \n@@ -47,18 +39,18 @@ user_in = UserIn(username=\"john\", password=\"secret\", email=\"[EMAIL_REDACTED]\n и затем вызовем:\n \n ```Python\n-user_dict = user_in.dict()\n+user_dict = user_in.model_dump()\n ```\n \n-то теперь у нас есть `dict` с данными модели в переменной `user_dict` (это `dict` вместо объекта Pydantic-модели).\n+то теперь у нас есть `dict` с данными в переменной `user_dict` (это `dict` вместо объекта Pydantic-модели).\n \n И если мы вызовем:\n \n ```Python\n print(user_dict)\n ```\n \n-мы можем получить `dict` с такими данными:\n+мы получим Python `dict` с:\n \n ```Python\n {\n@@ -71,15 +63,15 @@ print(user_dict)\n \n #### Распаковка `dict` { #unpacking-a-dict }\n \n-Если мы возьмём `dict` наподобие `user_dict` и передадим его в функцию (или класс), используя `**user_dict`, Python распакует его. Он передаст ключи и значения `user_dict` напрямую как аргументы типа ключ-значение.\n+Если мы возьмём `dict` наподобие `user_dict` и передадим его в функцию (или класс), используя `**user_dict`, Python его \"распакует\". Он передаст ключи и значения `user_dict` напрямую как аргументы типа ключ-значение.\n \n Поэтому, продолжая описанный выше пример с `user_dict`, написание такого кода:\n \n ```[NAME_REDACTED](**user_dict)\n ```\n \n-Будет работать так же, как примерно такой код:\n+будет эквивалентно:\n \n ```[NAME_REDACTED](\n@@ -90,7 +82,7 @@ UserInDB(\n )\n ```\n \n-Или, если для большей точности мы напрямую используем `user_dict` с любым потенциальным содержимым, то этот пример будет выглядеть так:\n+Или, более точно, если использовать `user_dict` напрямую, с любым содержимым, которое он может иметь в будущем:\n \n ```[NAME_REDACTED](\n@@ -101,22 +93,22 @@ UserInDB(\n )\n ```\n \n-#### Pydantic-модель из содержимого другой модели { #a-pydantic-model-from-the-contents-of-another }\n+#### Pydantic-модель из содержимого другой { #a-pydantic-model-from-the-contents-of-another }\n \n-Как в примере выше мы получили `user_dict` из `user_in.dict()`, этот код:\n+Как в примере выше мы получили `user_dict` из `user_in.model_dump()`, этот код:\n \n ```Python\n-user_dict = user_in.dict()\n+user_dict = user_in.model_dump()\n UserInDB(**user_dict)\n ```\n \n будет равнозначен такому:\n \n ```Python\n-UserInDB(**user_in.dict())\n+UserInDB(**user_in.model_dump())\n ```\n \n-...потому что `user_in.dict()` - это `dict`, и затем мы указываем, чтобы Python его \"распаковал\", когда передаём его в `UserInDB` и ставим перед ним `**`.\n+...потому что `user_in.model_dump()` — это `dict`, и затем мы указываем, чтобы Python его \"распаковал\", когда передаём его в `UserInDB` с префиксом `**`.\n \n Таким образом мы получаем Pydantic-модель на основе данных из другой Pydantic-модели.\n \n@@ -125,10 +117,10 @@ UserInDB(**user_in.dict())\n И затем, если мы добавим дополнительный именованный аргумент `hashed_password=hashed_password` как здесь:\n \n ```Python\n-UserInDB(**user_in.dict(), hashed_password=hashed_password)\n+UserInDB(**user_in.model_dump(), hashed_password=hashed_password)\n ```\n \n-... то мы получим что-то подобное:\n+...то в итоге получится что-то подобное:\n \n ```[NAME_REDACTED](\n@@ -142,13 +134,13 @@ UserInDB(\n \n /// warning | Предупреждение\n \n-Вспомогательные функции `fake_password_hasher` и `fake_save_user` используются только для демонстрации возможного потока данных и, конечно, не обеспечивают настоящую безопасность.\n+Вспомогательные дополнительные функции `fake_password_hasher` и `fake_save_user` используются только для демонстрации возможного потока данных и, конечно, не обеспечивают настоящую безопасность.\n \n ///\n \n ## Сократите дублирование { #reduce-duplication }\n \n-Сокращение дублирования кода - это одна из главных идей **FastAPI**.\n+Сокращение дублирования кода — это одна из главных идей **FastAPI**.\n \n Поскольку дублирование кода повышает риск появления багов, проблем с безопасностью, проблем десинхронизации кода (когда вы обновляете код в одном месте, но не обновляете в другом), и т.д.\n \n@@ -166,15 +158,15 @@ UserInDB(\n \n ## `Union` или `anyOf` { #union-or-anyof }\n \n-Вы можете определить ответ как `Union` из двух или более типов. Это означает, что ответ должен соответствовать одному из них.\n+Вы можете объявить HTTP-ответ как `Union` из двух или более типов. Это означает, что HTTP-ответ может быть любым из них.\n \n Он будет определён в OpenAPI как `anyOf`.\n \n Для этого используйте стандартную аннотацию типов в Python `typing.Union`:\n \n /// note | Примечание\n \n-При объявлении `Union`, сначала указывайте наиболее детальные типы, затем менее детальные. В примере ниже более детальный `PlaneItem` стоит перед `CarItem` в `Union[PlaneItem, CarItem]`.\n+При объявлении `Union` сначала указывайте наиболее специфичный тип, затем менее специфичный. В примере ниже более специфичный `PlaneItem` стоит перед `CarItem` в `Union[PlaneItem, CarItem]`.\n \n ///\n \n@@ -192,19 +184,19 @@ UserInDB(\n some_variable: PlaneItem | CarItem\n ```\n \n-Но если мы помещаем его в `response_model=PlaneItem | CarItem` мы получим ошибку, потому что Python попытается произвести **некорректную операцию** между `PlaneItem` и `CarItem` вместо того, чтобы интерпретировать это как аннотацию типа.\n+Но если мы поместим это в присваивание `response_model=PlaneItem | CarItem`, мы получим ошибку, потому что Python попытается произвести **некорректную операцию** между `PlaneItem` и `CarItem` вместо того, чтобы интерпретировать это как аннотацию типа.\n \n ## Список моделей { #list-of-models }\n \n-Таким же образом вы можете определять ответы как списки объектов.\n+Таким же образом вы можете объявлять HTTP-ответы, возвращающие списки объектов.\n \n-Для этого используйте `typing.List` из стандартной библиотеки Python (или просто `list` в Python 3.9 и выше):\n+Для этого используйте стандартный `typing.List` в Python (или просто `list` в Python 3.9 и выше):\n \n {* ../../docs_src/extra_models/tutorial004_py39.py hl[18] *}\n \n ## Ответ с произвольным `dict` { #response-with-arbitrary-dict }\n \n-Вы также можете определить ответ, используя произвольный одноуровневый `dict` и определяя только типы ключей и значений без использования Pydantic-моделей.\n+Вы также можете объявить HTTP-ответ, используя обычный произвольный `dict`, объявив только тип ключей и значений, без использования Pydantic-модели.\n \n Это полезно, если вы заранее не знаете корректных названий полей/атрибутов (которые будут нужны при использовании Pydantic-модели).\n \n@@ -214,6 +206,6 @@ some_variable: PlaneItem | CarItem\n \n ## Резюме { #recap }\n \n-Используйте несколько Pydantic-моделей и свободно применяйте наследование для каждой из них.\n+Используйте несколько Pydantic-моделей и свободно применяйте наследование для каждого случая.\n \n-Вам не обязательно иметь единственную модель данных для каждой сущности, если эта сущность должна иметь возможность быть в разных \"состояниях\". Как в случае с \"сущностью\" пользователя, у которого есть состояния с полями `password`, `password_hash` и без пароля.\n+Вам не обязательно иметь единственную модель данных для каждой сущности, если эта сущность должна иметь возможность быть в разных \"состояниях\". Как в случае с \"сущностью\" пользователя, у которого есть состояние, включающее `password`, `password_hash` и отсутствие пароля." }, { "filename": "docs/ru/docs/tutorial/query-params-str-validations.md", "status": "modified", "additions": 8, "deletions": 22, "changes": 30, "patch": "@@ -8,7 +8,7 @@\n \n Query-параметр `q` имеет тип `str | None`, это означает, что он имеет тип `str`, но также может быть `None`. Значение по умолчанию действительно `None`, поэтому FastAPI будет знать, что он не обязателен.\n \n-/// note | Технические детали\n+/// note | Примечание\n \n FastAPI поймёт, что значение `q` не обязательно, из‑за значения по умолчанию `= None`.\n \n@@ -177,7 +177,7 @@ q: str = Query(default=\"rick\")\n \n **Значение по умолчанию** у **параметра функции** — это **настоящее значение по умолчанию**, что более интуитивно для Python. 😌\n \n-Вы можете **вызвать** эту же функцию в **других местах** без FastAPI, и она будет **работать как ожидается**. Если есть **обязательный** параметр (без значения по умолчанию), ваш **редактор кода** сообщит об ошибке, **Python** тоже пожалуется, если вы запустите её без передачи обязательного параметра.\n+Вы можете **вызвать** эту же функцию в **других местах** без FastAPI, и она будет **работать как ожидается**. Если есть **обязательный** параметр (без значения по умолчанию), ваш **редактор** сообщит об ошибке, **Python** тоже пожалуется, если вы запустите её без передачи обязательного параметра.\n \n Если вы не используете `Annotated`, а применяете **(устаревший) стиль со значением по умолчанию**, то при вызове этой функции без FastAPI в **других местах** вам нужно **помнить** о том, что надо передать аргументы, чтобы всё работало корректно, иначе значения будут не такими, как вы ожидаете (например, вместо `str` будет `QueryInfo` или что-то подобное). И ни редактор, ни Python не будут ругаться при самом вызове функции — ошибка проявится лишь при операциях внутри.\n \n@@ -191,7 +191,7 @@ q: str = Query(default=\"rick\")\n \n ## Регулярные выражения { #add-regular-expressions }\n \n-Вы можете определить регулярное выражение `pattern`, которому должен соответствовать параметр:\n+Вы можете определить регулярное выражение `pattern`, которому должен соответствовать параметр:\n \n {* ../../docs_src/query_params_str_validations/tutorial004_an_py310.py hl[11] *}\n \n@@ -205,20 +205,6 @@ q: str = Query(default=\"rick\")\n \n Теперь вы знаете, что когда они понадобятся, вы сможете использовать их в **FastAPI**.\n \n-### `regex` из Pydantic v1 вместо `pattern` { #pydantic-v1-regex-instead-of-pattern }\n-\n-До Pydantic версии 2 и до FastAPI 0.100.0 этот параметр назывался `regex`, а не `pattern`, но сейчас он устарел.\n-\n-Вы всё ещё можете встретить такой код:\n-\n-//// tab | Pydantic v1\n-\n-{* ../../docs_src/query_params_str_validations/tutorial004_regex_an_py310.py hl[11] *}\n-\n-////\n-\n-Имейте в виду, что это устарело, и код следует обновить на использование нового параметра `pattern`. 🤓\n-\n ## Значения по умолчанию { #default-values }\n \n Конечно, можно использовать и другие значения по умолчанию, не только `None`.\n@@ -279,7 +265,7 @@ q: Annotated[str | None, Query(min_length=3)] = None\n http://localhost:8000/items/?q=foo&q=bar\n ```\n \n-вы получите множественные значения query-параметра `q` (`foo` и `bar`) в виде Python-`list` внутри вашей *функции обработки пути*, в *параметре функции* `q`.\n+вы получите множественные значения *query-параметров* `q` (`foo` и `bar`) в виде Python-`list` внутри вашей *функции-обработчика пути*, в *параметре функции* `q`.\n \n Таким образом, ответ на этот URL будет:\n \n@@ -331,7 +317,7 @@ http://localhost:8000/items/\n \n {* ../../docs_src/query_params_str_validations/tutorial013_an_py39.py hl[9] *}\n \n-/// note | Технические детали\n+/// note | Примечание\n \n Имейте в виду, что в этом случае FastAPI не будет проверять содержимое списка.\n \n@@ -345,7 +331,7 @@ http://localhost:8000/items/\n \n Эта информация будет включена в сгенерированную OpenAPI-схему и использована интерфейсами документации и внешними инструментами.\n \n-/// note | Технические детали\n+/// note | Примечание\n \n Помните, что разные инструменты могут иметь разный уровень поддержки OpenAPI.\n \n@@ -415,7 +401,7 @@ http://127.0.0.1:8000/items/?item-query=foobaritems\n \n ///\n \n-Например, эта кастомная проверка убеждается, что ID элемента начинается с `isbn-` для номера книги ISBN или с `imdb-` для ID URL фильма на IMDB:\n+Например, эта кастомная проверка убеждается, что ID элемента начинается с `isbn-` для номера книги ISBN или с `imdb-` для ID URL фильма на IMDB:\n \n {* ../../docs_src/query_params_str_validations/tutorial015_an_py310.py hl[5,16:19,24] *}\n \n@@ -455,7 +441,7 @@ http://127.0.0.1:8000/items/?item-query=foobaritems\n \n Затем с `random.choice()` можно получить **случайное значение** из списка — то есть кортеж вида `(id, name)`. Это будет что‑то вроде `(\"imdb-tt0371724\", \"The Hitchhiker's Guide to the Galaxy\")`.\n \n-После этого мы **распаковываем** эти два значения кортежа в переменные `id` и `name`.\n+После этого мы **присваиваем эти два значения** кортежа переменным `id` и `name`.\n \n Так что, если пользователь не передал ID элемента, он всё равно получит случайную рекомендацию." }, { "filename": "docs/ru/docs/tutorial/response-model.md", "status": "modified", "additions": 29, "deletions": 43, "changes": 72, "patch": "@@ -6,11 +6,11 @@\n \n {* ../../docs_src/response_model/tutorial001_01_py310.py hl[16,21] *}\n \n-FastAPI будет использовать этот тип ответа для:\n+FastAPI будет использовать этот возвращаемый тип, чтобы:\n \n-* **Валидации** возвращаемых данных.\n- * Если данные невалидны (например, отсутствует поле), это означает, что код *вашего* приложения работает некорректно и возвращает не то, что должен. В таком случае будет возвращена ошибка сервера вместо неправильных данных. Так вы и ваши клиенты можете быть уверены, что получите ожидаемые данные и ожидаемую структуру.\n-* Добавления **JSON Schema** для ответа в OpenAPI *операции пути*.\n+* **Валидировать** возвращаемые данные.\n+ * Если данные невалидны (например, отсутствует поле), это означает, что код *вашего* приложения работает некорректно и возвращает не то, что должен. В таком случае будет возвращена ошибка сервера вместо неправильных данных. Так вы и ваши клиенты можете быть уверены, что получите ожидаемые данные и ожидаемую структуру данных.\n+* Добавить **JSON Schema** для ответа в OpenAPI *операции пути*.\n * Это будет использовано **автоматической документацией**.\n * Это также будет использовано инструментами автоматической генерации клиентского кода.\n \n@@ -23,7 +23,7 @@ FastAPI будет использовать этот тип ответа для:\n \n Бывают случаи, когда вам нужно или хочется возвращать данные, которые не в точности соответствуют объявленному типу.\n \n-Например, вы можете хотеть **возвращать словарь (dict)** или объект из базы данных, но **объявить его как Pydantic-модель**. Тогда Pydantic-модель выполнит документирование данных, валидацию и т.п. для объекта, который вы вернули (например, словаря или объекта из базы данных).\n+Например, вы можете хотеть **возвращать словарь** или объект из базы данных, но **объявить его как Pydantic-модель**. Тогда Pydantic-модель выполнит документирование данных, валидацию и т.п. для объекта, который вы вернули (например, словаря или объекта из базы данных).\n \n Если вы добавите аннотацию возвращаемого типа, инструменты и редакторы кода начнут жаловаться (и будут правы), что функция возвращает тип (например, dict), отличный от объявленного (например, Pydantic-модель).\n \n@@ -47,21 +47,21 @@ FastAPI будет использовать этот тип ответа для:\n \n `response_model` принимает тот же тип, что вы бы объявили для поля Pydantic-модели, то есть это может быть одна Pydantic-модель, а может быть, например, `list` Pydantic-моделей, как `List[Item]`.\n \n-FastAPI будет использовать `response_model` для документации, валидации и т. п., а также для **конвертации и фильтрации выходных данных** к объявленному типу.\n+FastAPI будет использовать этот `response_model` для документирования, валидации данных и т.п., а также для **конвертации и фильтрации выходных данных** к объявленному типу.\n \n /// tip | Совет\n \n-Если у вас в редакторе кода, mypy и т. п. включены строгие проверки типов, вы можете объявить возвращаемый тип функции как `Any`.\n+Если у вас в редакторе кода, mypy и т.п. включены строгие проверки типов, вы можете объявить возвращаемый тип функции как `Any`.\n \n-Так вы сообщите редактору, что намеренно возвращаете что угодно. Но FastAPI всё равно выполнит документацию данных, валидацию, фильтрацию и т.д. с помощью `response_model`.\n+Так вы сообщите редактору, что намеренно возвращаете что угодно. Но FastAPI всё равно выполнит документирование, валидацию, фильтрацию данных и т.д. с помощью `response_model`.\n \n ///\n \n ### Приоритет `response_model` { #response-model-priority }\n \n Если вы объявите и возвращаемый тип, и `response_model`, приоритет будет у `response_model`, именно его использует FastAPI.\n \n-Так вы можете добавить корректные аннотации типов к своим функциям, даже если фактически возвращаете тип, отличный от модели ответа, чтобы ими пользовались редактор и инструменты вроде mypy. И при этом FastAPI продолжит выполнять валидацию данных, документацию и т.д. с использованием `response_model`.\n+Так вы можете добавить корректные аннотации типов к своим функциям, даже если фактически возвращаете тип, отличный от модели ответа, чтобы ими пользовались редактор кода и инструменты вроде mypy. И при этом FastAPI продолжит выполнять валидацию данных, документацию и т.д. с использованием `response_model`.\n \n Вы также можете указать `response_model=None`, чтобы отключить создание модели ответа для данной *операции пути*. Это может понадобиться, если вы добавляете аннотации типов для вещей, не являющихся валидными полями Pydantic. Пример вы увидите ниже.\n \n@@ -75,7 +75,7 @@ FastAPI будет использовать `response_model` для докуме\n \n Чтобы использовать `EmailStr`, сначала установите `email-validator`.\n \n-Создайте [виртуальное окружение](../virtual-environments.md){.internal-link target=_blank}, активируйте его и затем установите пакет, например:\n+Убедитесь, что вы создали [виртуальное окружение](../virtual-environments.md){.internal-link target=_blank}, активировали его, а затем установите пакет, например:\n \n ```console\n $ pip install email-validator\n@@ -105,7 +105,7 @@ $ pip install \"pydantic[email]\"\n \n ///\n \n-## Добавить модель для ответа { #add-an-output-model }\n+## Добавить выходную модель { #add-an-output-model }\n \n Вместо этого мы можем создать входную модель с паролем в открытом виде и выходную модель без него:\n \n@@ -123,7 +123,7 @@ $ pip install \"pydantic[email]\"\n \n ### `response_model` или возвращаемый тип { #response-model-or-return-type }\n \n-В этом случае, поскольку две модели различаются, если бы мы аннотировали возвращаемый тип функции как `UserOut`, редактор и инструменты пожаловались бы, что мы возвращаем неверный тип, так как это разные классы.\n+В этом случае, поскольку две модели различаются, если бы мы аннотировали возвращаемый тип функции как `UserOut`, редактор кода и инструменты пожаловались бы, что мы возвращаем неверный тип, так как это разные классы.\n \n Поэтому в этом примере мы должны объявить тип ответа в параметре `response_model`.\n \n@@ -135,33 +135,33 @@ $ pip install \"pydantic[email]\"\n \n Мы хотим, чтобы FastAPI продолжал **фильтровать** данные с помощью модели ответа. Так что, даже если функция возвращает больше данных, в ответ будут включены только поля, объявленные в модели ответа.\n \n-В предыдущем примере, поскольку классы были разными, нам пришлось использовать параметр `response_model`. Но это также означает, что мы теряем поддержку от редактора и инструментов, проверяющих возвращаемый тип функции.\n+В предыдущем примере, поскольку классы были разными, нам пришлось использовать параметр `response_model`. Но это также означает, что мы теряем поддержку от редактора кода и инструментов, проверяющих возвращаемый тип функции.\n \n Однако в большинстве таких случаев нам нужно лишь **отфильтровать/убрать** некоторые данные, как в этом примере.\n \n-И в этих случаях мы можем использовать классы и наследование, чтобы воспользоваться **аннотациями типов** функций для лучшей поддержки в редакторе и инструментах и при этом получить **фильтрацию данных** от FastAPI.\n+И в этих случаях мы можем использовать классы и наследование, чтобы воспользоваться **аннотациями типов** функций для лучшей поддержки в редакторе кода и инструментах и при этом получить **фильтрацию данных** от FastAPI.\n \n {* ../../docs_src/response_model/tutorial003_01_py310.py hl[7:10,13:14,18] *}\n \n-Так мы получаем поддержку инструментов (редакторы, mypy) — код корректен с точки зрения типов — и одновременно получаем фильтрацию данных от FastAPI.\n+Так мы получаем поддержку инструментов — редакторов кода и mypy, так как этот код корректен с точки зрения типов — и одновременно получаем фильтрацию данных от FastAPI.\n \n Как это работает? Давайте разберёмся. 🤓\n \n ### Аннотации типов и инструменты { #type-annotations-and-tooling }\n \n-Сначала посмотрим, как это увидят редакторы, mypy и другие инструменты.\n+Сначала посмотрим, как это увидят редактор кода, mypy и другие инструменты.\n \n-`BaseUser` содержит базовые поля. Затем `UserIn` наследуется от `BaseUser` и добавляет поле `password`, то есть он включает все поля обеих моделей.\n+`BaseUser` содержит базовые поля. Затем `UserIn` наследуется от `BaseUser` и добавляет поле `password`, то есть он будет включать все поля обеих моделей.\n \n Мы аннотируем возвращаемый тип функции как `BaseUser`, но фактически возвращаем экземпляр `UserIn`.\n \n-Редактор, mypy и другие инструменты не будут возражать, потому что с точки зрения типов `UserIn` — подкласс `BaseUser`, что означает, что это *валидный* тип везде, где ожидается что-то, являющееся `BaseUser`.\n+Редактор кода, mypy и другие инструменты не будут возражать, потому что с точки зрения типов `UserIn` — подкласс `BaseUser`, что означает, что это *валидный* тип везде, где ожидается что-то, являющееся `BaseUser`.\n \n ### Фильтрация данных FastAPI { #fastapi-data-filtering }\n \n-Теперь, для FastAPI: он увидит возвращаемый тип и убедится, что то, что вы возвращаете, включает **только** поля, объявленные в этом типе.\n+Теперь для FastAPI: он увидит возвращаемый тип и убедится, что то, что вы возвращаете, включает **только** поля, объявленные в этом типе.\n \n-FastAPI делает несколько вещей внутри вместе с Pydantic, чтобы гарантировать, что те же правила наследования классов не используются для фильтрации возвращаемых данных, иначе вы могли бы вернуть гораздо больше данных, чем ожидали.\n+FastAPI делает несколько вещей внутри вместе с Pydantic, чтобы гарантировать, что те же правила наследования классов не используются для фильтрации возвращаемых данных, иначе вы могли бы в итоге вернуть намного больше данных, чем ожидали.\n \n Таким образом вы получаете лучшее из обоих миров: аннотации типов с **поддержкой инструментов** и **фильтрацию данных**.\n \n@@ -171,17 +171,17 @@ FastAPI делает несколько вещей внутри вместе с\n \n \n \n-И обе модели используются в интерактивной документации API:\n+И обе модели будут использоваться в интерактивной документации API:\n \n \n \n ## Другие аннотации возвращаемых типов { #other-return-type-annotations }\n \n-Бывают случаи, когда вы возвращаете что-то, что не является валидным полем Pydantic, и аннотируете это в функции только ради поддержки инструментов (редактор, mypy и т. д.).\n+Бывают случаи, когда вы возвращаете что-то, что не является валидным полем Pydantic, и аннотируете это в функции только ради поддержки инструментов (редактор кода, mypy и т.д.).\n \n ### Возврат Response напрямую { #return-a-response-directly }\n \n-Самый распространённый случай — [возвращать Response напрямую, как описано далее в разделах для продвинутых](../advanced/response-directly.md){.internal-link target=_blank}.\n+Самый распространённый случай — [возвращать Response напрямую, как описано далее в разделах документации для продвинутых](../advanced/response-directly.md){.internal-link target=_blank}.\n \n {* ../../docs_src/response_model/tutorial003_02_py39.py hl[8,10:11] *}\n \n@@ -195,7 +195,7 @@ FastAPI делает несколько вещей внутри вместе с\n \n {* ../../docs_src/response_model/tutorial003_03_py39.py hl[8:9] *}\n \n-Это тоже сработает, так как `RedirectResponse` — подкласс `Response`, и FastAPI автоматически обработает этот случай.\n+Это тоже сработает, так как `RedirectResponse` — подкласс `Response`, и FastAPI автоматически обработает этот простой случай.\n \n ### Некорректные аннотации возвращаемых типов { #invalid-return-type-annotations }\n \n@@ -209,15 +209,15 @@ FastAPI делает несколько вещей внутри вместе с\n \n ### Отключить модель ответа { #disable-response-model }\n \n-Продолжая пример выше, вы можете не хотеть использовать стандартную валидацию данных, документацию, фильтрацию и т.д., выполняемые FastAPI.\n+Продолжая пример выше, вы можете не хотеть использовать стандартные валидацию данных, документирование, фильтрацию и т.п., выполняемые FastAPI.\n \n-Но при этом вы можете хотеть сохранить аннотацию возвращаемого типа в функции, чтобы пользоваться поддержкой инструментов (редакторы, проверки типов вроде mypy).\n+Но при этом вы можете хотеть сохранить аннотацию возвращаемого типа в функции, чтобы пользоваться поддержкой инструментов вроде редакторов кода и инструментов проверки типов (например, mypy).\n \n В этом случае вы можете отключить генерацию модели ответа, установив `response_model=None`:\n \n {* ../../docs_src/response_model/tutorial003_05_py310.py hl[7] *}\n \n-Так FastAPI пропустит генерацию модели ответа, и вы сможете использовать любые аннотации возвращаемых типов, не влияя на ваше приложение FastAPI. 🤓\n+Так FastAPI пропустит генерацию модели ответа, и вы сможете использовать любые аннотации возвращаемых типов, которые вам нужны, без влияния на ваше приложение FastAPI. 🤓\n \n ## Параметры кодирования модели ответа { #response-model-encoding-parameters }\n \n@@ -252,20 +252,6 @@ FastAPI делает несколько вещей внутри вместе с\n \n /// info | Информация\n \n-В Pydantic v1 метод назывался `.dict()`, в Pydantic v2 он был помечен как устаревший (но всё ещё поддерживается) и переименован в `.model_dump()`.\n-\n-Примеры здесь используют `.dict()` для совместимости с Pydantic v1, но если вы используете Pydantic v2, применяйте `.model_dump()`.\n-\n-///\n-\n-/// info | Информация\n-\n-FastAPI использует метод `.dict()` у Pydantic-моделей с параметром `exclude_unset`, чтобы добиться такого поведения.\n-\n-///\n-\n-/// info | Информация\n-\n Вы также можете использовать:\n \n * `response_model_exclude_defaults=True`\n@@ -312,7 +298,7 @@ FastAPI достаточно умен (на самом деле, это Pydantic\n \n Обратите внимание, что значения по умолчанию могут быть любыми, не только `None`.\n \n-Это может быть список (`[]`), число с плавающей точкой `10.5` и т. д.\n+Это может быть список (`[]`), число с плавающей точкой `10.5` и т.д.\n \n ///\n \n@@ -346,7 +332,7 @@ FastAPI достаточно умен (на самом деле, это Pydantic\n \n #### Использование `list` вместо `set` { #using-lists-instead-of-sets }\n \n-Если вы забыли использовать `set` и применили `list` или `tuple`, FastAPI всё равно преобразует это в `set`, и всё будет работать корректно:\n+Если вы забыли использовать `set` и применили `list` или `tuple` вместо него, FastAPI всё равно преобразует это в `set`, и всё будет работать корректно:\n \n {* ../../docs_src/response_model/tutorial006_py310.py hl[29,35] *}" }, { "filename": "docs/ru/docs/tutorial/schema-extra-example.md", "status": "modified", "additions": 4, "deletions": 26, "changes": 30, "patch": "@@ -8,36 +8,14 @@\n \n Вы можете объявить `examples` для модели Pydantic, которые будут добавлены в сгенерированную JSON Schema.\n \n-//// tab | Pydantic v2\n-\n {* ../../docs_src/schema_extra_example/tutorial001_py310.py hl[13:24] *}\n \n-////\n-\n-//// tab | Pydantic v1\n-\n-{* ../../docs_src/schema_extra_example/tutorial001_pv1_py310.py hl[13:23] *}\n-\n-////\n-\n Эта дополнительная информация будет добавлена как есть в выходную **JSON Schema** этой модели и будет использоваться в документации API.\n \n-//// tab | Pydantic v2\n-\n-В Pydantic версии 2 вы будете использовать атрибут `model_config`, который принимает `dict`, как описано в Документации Pydantic: Конфигурация.\n+Вы можете использовать атрибут `model_config`, который принимает `dict`, как описано в Документации Pydantic: Конфигурация.\n \n Вы можете задать `\"json_schema_extra\"` с `dict`, содержащим любые дополнительные данные, которые вы хотите видеть в сгенерированной JSON Schema, включая `examples`.\n \n-////\n-\n-//// tab | Pydantic v1\n-\n-В Pydantic версии 1 вы будете использовать внутренний класс `Config` и `schema_extra`, как описано в Документации Pydantic: Настройка схемы.\n-\n-Вы можете задать `schema_extra` со `dict`, содержащим любые дополнительные данные, которые вы хотите видеть в сгенерированной JSON Schema, включая `examples`.\n-\n-////\n-\n /// tip | Подсказка\n \n Вы можете использовать тот же приём, чтобы расширить JSON Schema и добавить свою собственную дополнительную информацию.\n@@ -124,7 +102,7 @@ OpenAPI 3.1.0 (используется начиная с FastAPI 0.99.0) доб\n \n Ключи `dict` идентифицируют каждый пример, а каждое значение — это ещё один `dict`.\n \n-Каждый конкретный пример‑`dict` в `examples` может содержать:\n+Каждый конкретный пример `dict` в `examples` может содержать:\n \n * `summary`: Краткое описание примера.\n * `description`: Подробное описание, которое может содержать текст в Markdown.\n@@ -135,7 +113,7 @@ OpenAPI 3.1.0 (используется начиная с FastAPI 0.99.0) доб\n \n {* ../../docs_src/schema_extra_example/tutorial005_an_py310.py hl[23:49] *}\n \n-### OpenAPI-примеры в UI документации { #openapi-examples-in-the-docs-ui }\n+### OpenAPI-примеры в UI документации { #openapi-examples-in-the-docs-ui }\n \n С `openapi_examples`, добавленным в `Body()`, страница `/docs` будет выглядеть так:\n \n@@ -213,7 +191,7 @@ OpenAPI также добавила поля `example` и `examples` в друг\n \n ### Swagger UI и специфичные для OpenAPI `examples` { #swagger-ui-and-openapi-specific-examples }\n \n-Раньше, поскольку Swagger UI не поддерживал несколько примеров JSON Schema (по состоянию на 2023-08-26), у пользователей не было способа показать несколько примеров в документации.\n+Теперь, поскольку Swagger UI не поддерживал несколько примеров JSON Schema (по состоянию на 2023-08-26), у пользователей не было способа показать несколько примеров в документации.\n \n Чтобы решить это, FastAPI `0.103.0` **добавил поддержку** объявления того же старого, **специфичного для OpenAPI**, поля `examples` с новым параметром `openapi_examples`. 🤓" } ], "reviews": [ { "id": 3676635701, "user": "user_29e85f9a8e75", "state": "COMMENTED", "body": null, "submitted_at": "2026-01-19T10:38:14+00:00" }, { "id": 3677418471, "user": "user_29e85f9a8e75", "state": "COMMENTED", "body": "Some fixes", "submitted_at": "2026-01-19T10:39:15+00:00" }, { "id": 3677612186, "user": "user_29e85f9a8e75", "state": "COMMENTED", "body": "Some more fixes", "submitted_at": "2026-01-19T11:41:34+00:00" } ], "review_comments": [ { "id": 2703517924, "user": "user_29e85f9a8e75", "body": "```suggestion\nДобавление `\\f` (экранированного символа «form feed») заставит **FastAPI** обрезать текст, используемый для OpenAPI, в этой точке.\n```", "path": "docs/ru/docs/advanced/path-operation-advanced-configuration.md", "line": null, "side": "RIGHT", "created_at": "2026-01-19T07:22:23+00:00" }, { "id": 2703527815, "user": "user_29e85f9a8e75", "body": "```suggestion\nНапример, вы можете решить читать и валидировать HTTP-запрос своим кодом, не используя автоматические возможности FastAPI и Pydantic, но при этом захотите описать HTTP-запрос в схеме OpenAPI.\n```", "path": "docs/ru/docs/advanced/path-operation-advanced-configuration.md", "line": null, "side": "RIGHT", "created_at": "2026-01-19T07:26:42+00:00" }, { "id": 2703584145, "user": "user_29e85f9a8e75", "body": "```suggestion\nВ этом примере мы не объявляли никакую Pydantic-модель. Фактически тело запроса даже не распарсено как JSON, оно читается напрямую как `bytes`, а функция `magic_data_reader()` будет отвечать за его парсинг каким-то способом.\n```", "path": "docs/ru/docs/advanced/path-operation-advanced-configuration.md", "line": null, "side": "RIGHT", "created_at": "2026-01-19T07:43:42+00:00" }, { "id": 2703641645, "user": "user_29e85f9a8e75", "body": "```suggestion\nПри использовании **Pydantic v2** сгенерированный OpenAPI становится чуть более точным и **корректным**, чем раньше. 😎\n```", "path": "docs/ru/docs/how-to/separate-openapi-schemas.md", "line": null, "side": "RIGHT", "created_at": "2026-01-19T07:56:24+00:00" }, { "id": 2703644729, "user": "user_29e85f9a8e75", "body": "```suggestion\nНа самом деле, в некоторых случаях в OpenAPI будет даже **две JSON-схемы** для одной и той же Pydantic‑модели: для входа и для выхода — в зависимости от наличия **значений по умолчанию**.\n```", "path": "docs/ru/docs/how-to/separate-openapi-schemas.md", "line": null, "side": "RIGHT", "created_at": "2026-01-19T07:57:30+00:00" }, { "id": 2703653756, "user": "user_29e85f9a8e75", "body": "```suggestion\nОднако бывают случаи, когда вы хотите иметь **одну и ту же схему для входа и выхода**.\n```", "path": "docs/ru/docs/how-to/separate-openapi-schemas.md", "line": null, "side": "RIGHT", "created_at": "2026-01-19T08:01:00+00:00" }, { "id": 2703657816, "user": "user_29e85f9a8e75", "body": "```suggestion\n Фреймворк FastAPI: высокая производительность, прост в изучении, позволяет быстро писать код, готов к продакшн\n```", "path": "docs/ru/docs/index.md", "line": null, "side": "RIGHT", "created_at": "2026-01-19T08:02:33+00:00" }, { "id": 2703659543, "user": "user_29e85f9a8e75", "body": "```suggestion\n* **Интуитивность**: Отличная поддержка редактора кода. Автозавершение везде. Меньше времени на отладку.\n```", "path": "docs/ru/docs/index.md", "line": null, "side": "RIGHT", "created_at": "2026-01-19T08:03:18+00:00" }, { "id": 2703674140, "user": "user_29e85f9a8e75", "body": "```suggestion\nБолее полный пример с дополнительными возможностями см. в Учебник - Руководство пользователя.\n```", "path": "docs/ru/docs/index.md", "line": null, "side": "RIGHT", "created_at": "2026-01-19T08:08:06+00:00" }, { "id": 2703675076, "user": "user_29e85f9a8e75", "body": "```suggestion\n**Осторожно, спойлер**: учебник - руководство пользователя включает:\n```", "path": "docs/ru/docs/index.md", "line": null, "side": "RIGHT", "created_at": "2026-01-19T08:08:27+00:00" }, { "id": 2703759920, "user": "user_29e85f9a8e75", "body": "```suggestion\n* Очень мощную и простую в использовании систему **внедрения зависимостей**.\n```", "path": "docs/ru/docs/index.md", "line": null, "side": "RIGHT", "created_at": "2026-01-19T08:37:52+00:00" }, { "id": 2703765987, "user": "user_29e85f9a8e75", "body": "```suggestion\nОн упрощает процесс **создания образа**, **развертывания** и **доступа** к API при минимальных усилиях.\n```", "path": "docs/ru/docs/index.md", "line": null, "side": "RIGHT", "created_at": "2026-01-19T08:39:23+00:00" }, { "id": 2703769624, "user": "user_29e85f9a8e75", "body": "```suggestion\n* python-multipart - обязателен, если вы хотите поддерживать «парсинг» форм через `request.form()`.\n```", "path": "docs/ru/docs/index.md", "line": null, "side": "RIGHT", "created_at": "2026-01-19T08:40:13+00:00" }, { "id": 2703792586, "user": "user_29e85f9a8e75", "body": "```suggestion\n * Таким образом, можно обновлять только те значения, которые действительно установлены пользователем, вместо того чтобы переопределять уже сохраненные значения значениями по умолчанию из вашей модели.\n```", "path": "docs/ru/docs/tutorial/body-updates.md", "line": null, "side": "RIGHT", "created_at": "2026-01-19T08:47:17+00:00" }, { "id": 2703814984, "user": "user_29e85f9a8e75", "body": "```suggestion\nЕсли вы не хотите использовать модели Pydantic, вы также можете использовать параметры **Body**. См. раздел документации [Тело запроса - Несколько параметров: Единичные значения в теле](body-multiple-params.md#singular-values-in-body){.internal-link target=_blank}.\n```", "path": "docs/ru/docs/tutorial/body.md", "line": null, "side": "RIGHT", "created_at": "2026-01-19T08:53:36+00:00" }, { "id": 2703850830, "user": "user_29e85f9a8e75", "body": "```suggestion\nВ этом случае мы можем определить только различия между моделями (с `password` в чистом виде, с `hashed_password` и без пароля):\n```", "path": "docs/ru/docs/tutorial/extra-models.md", "line": null, "side": "RIGHT", "created_at": "2026-01-19T09:03:30+00:00" }, { "id": 2703880800, "user": "user_29e85f9a8e75", "body": "```suggestion\nПоддержка `Annotated` (и рекомендация использовать его) появилась в FastAPI версии 0.95.0.\n```", "path": "docs/ru/docs/tutorial/query-params-str-validations.md", "line": null, "side": "RIGHT", "created_at": "2026-01-19T09:12:13+00:00" }, { "id": 2703884717, "user": "user_29e85f9a8e75", "body": "```suggestion\nВ предыдущих версиях FastAPI (до 0.95.0) требовалось использовать `Query` как значение по умолчанию для параметра вместо помещения его в `Annotated`. Скорее всего вы ещё встретите такой код, поэтому поясню.\n```", "path": "docs/ru/docs/tutorial/query-params-str-validations.md", "line": null, "side": "RIGHT", "created_at": "2026-01-19T09:13:26+00:00" }, { "id": 2703892349, "user": "user_29e85f9a8e75", "body": "```suggestion\nВы можете определить регулярное выражение `pattern`, которому должен соответствовать параметр:\n```", "path": "docs/ru/docs/tutorial/query-params-str-validations.md", "line": null, "side": "RIGHT", "created_at": "2026-01-19T09:15:40+00:00" }, { "id": 2703895589, "user": "user_29e85f9a8e75", "body": "```suggestion\nЭта информация будет включена в сгенерированную OpenAPI-схему и использована интерфейсами документации и внешними инструментами.\n```", "path": "docs/ru/docs/tutorial/query-params-str-validations.md", "line": null, "side": "RIGHT", "created_at": "2026-01-19T09:16:40+00:00" }, { "id": 2703897742, "user": "user_29e85f9a8e75", "body": "```suggestion\nЕго нужно оставить на какое‑то время, так как клиенты его используют, но вы хотите, чтобы в документации он явно отображался как устаревший.\n```", "path": "docs/ru/docs/tutorial/query-params-str-validations.md", "line": null, "side": "RIGHT", "created_at": "2026-01-19T09:17:17+00:00" }, { "id": 2703906224, "user": "user_29e85f9a8e75", "body": "```suggestion\nНапример, эта кастомная проверка убеждается, что ID элемента начинается с `isbn-` для номера книги ISBN или с `imdb-` для ID URL фильма на IMDB:\n```", "path": "docs/ru/docs/tutorial/query-params-str-validations.md", "line": null, "side": "RIGHT", "created_at": "2026-01-19T09:19:38+00:00" }, { "id": 2703913857, "user": "user_29e85f9a8e75", "body": "```suggestion\nС помощью `data.items()` мы получаем итерируемый объект с кортежами, содержащими ключ и значение для каждого элемента словаря.\n```", "path": "docs/ru/docs/tutorial/query-params-str-validations.md", "line": null, "side": "RIGHT", "created_at": "2026-01-19T09:21:45+00:00" }, { "id": 2703925108, "user": "user_29e85f9a8e75", "body": "```suggestion\n * Если данные невалидны (например, отсутствует поле), это означает, что код *вашего* приложения работает некорректно и возвращает не то, что должен. В таком случае будет возвращена ошибка сервера вместо неправильных данных. Так вы и ваши клиенты можете быть уверены, что получите ожидаемые данные и ожидаемую структуру данных.\n```", "path": "docs/ru/docs/tutorial/response-model.md", "line": null, "side": "RIGHT", "created_at": "2026-01-19T09:25:01+00:00" }, { "id": 2703928372, "user": "user_29e85f9a8e75", "body": "```suggestion\nНапример, вы можете хотеть **возвращать словарь** или объект из базы данных, но **объявить его как Pydantic-модель**. Тогда Pydantic-модель выполнит документирование данных, валидацию и т.п. для объекта, который вы вернули (например, словаря или объекта из базы данных).\n```", "path": "docs/ru/docs/tutorial/response-model.md", "line": null, "side": "RIGHT", "created_at": "2026-01-19T09:25:58+00:00" }, { "id": 2703930467, "user": "user_29e85f9a8e75", "body": "```suggestion\nОбратите внимание, что `response_model` — это параметр метода «декоратора» (`get`, `post` и т.д.), а не вашей *функции-обработчика пути*, в которой указываются параметры и тело запроса.\n```", "path": "docs/ru/docs/tutorial/response-model.md", "line": null, "side": "RIGHT", "created_at": "2026-01-19T09:26:38+00:00" }, { "id": 2703938108, "user": "user_29e85f9a8e75", "body": "```suggestion\nFastAPI будет использовать этот `response_model` для документирования, валидации данных и т.п., а также для **конвертации и фильтрации выходных данных** к объявленному типу.\n```", "path": "docs/ru/docs/tutorial/response-model.md", "line": null, "side": "RIGHT", "created_at": "2026-01-19T09:28:37+00:00" }, { "id": 2703951712, "user": "user_29e85f9a8e75", "body": "```suggestion\nПродолжим предыдущий пример. Мы хотели **аннотировать функцию одним типом**, но при этом иметь возможность вернуть из функции что-то, что фактически включает **больше данных**.\n```", "path": "docs/ru/docs/tutorial/response-model.md", "line": null, "side": "RIGHT", "created_at": "2026-01-19T09:32:25+00:00" }, { "id": 2703970409, "user": "user_29e85f9a8e75", "body": "```suggestion\nСамый распространённый случай — [возвращать Response напрямую, как описано далее в разделах документации для продвинутых](../advanced/response-directly.md){.internal-link target=_blank}.\n```", "path": "docs/ru/docs/tutorial/response-model.md", "line": null, "side": "RIGHT", "created_at": "2026-01-19T09:35:52+00:00" }, { "id": 2703983271, "user": "user_29e85f9a8e75", "body": "```suggestion\nНо при этом вы можете хотеть сохранить аннотацию возвращаемого типа в функции, чтобы пользоваться поддержкой инструментов вроде редакторов кода и инструментов проверки типов (например, mypy).\n```", "path": "docs/ru/docs/tutorial/response-model.md", "line": null, "side": "RIGHT", "created_at": "2026-01-19T09:38:46+00:00" }, { "id": 2703988775, "user": "user_29e85f9a8e75", "body": "```suggestion\nЭти **специфические для OpenAPI** `examples` находятся в другой секции спецификации OpenAPI. Они находятся в **подробностях для каждой операции пути (обработчика пути)**, а не внутри каждого объекта Schema.\n```", "path": "docs/ru/docs/tutorial/schema-extra-example.md", "line": null, "side": "RIGHT", "created_at": "2026-01-19T09:40:27+00:00" }, { "id": 2703990220, "user": "user_29e85f9a8e75", "body": "```suggestion\nЭто не помещается внутрь каждого объекта Schema в OpenAPI, это находится снаружи, непосредственно на уровне самой *операции пути*.\n```", "path": "docs/ru/docs/tutorial/schema-extra-example.md", "line": null, "side": "RIGHT", "created_at": "2026-01-19T09:40:52+00:00" }, { "id": 2703998553, "user": "user_29e85f9a8e75", "body": "```suggestion\n### OpenAPI-примеры в UI документации { #openapi-examples-in-the-docs-ui }\n```", "path": "docs/ru/docs/tutorial/schema-extra-example.md", "line": null, "side": "RIGHT", "created_at": "2026-01-19T09:43:14+00:00" }, { "id": 2704006422, "user": "user_29e85f9a8e75", "body": "```suggestion\nВчера мой друг написал: \"Если вы написали incorrectly правильно, значит вы написали это неправильно\". На что я ответил: \"Верно, но 'incorrectly' — это неправильно, а не '\"incorrectly\"'\".\n```", "path": "docs/ru/docs/_llm-test.md", "line": null, "side": "RIGHT", "created_at": "2026-01-19T09:45:20+00:00" }, { "id": 2704051603, "user": "user_29e85f9a8e75", "body": "```suggestion\n* Здесь также находится подкаталог `app/routers/`, содержащий `__init__.py`. Он является Python-подпакетом: `app.routers`.\n```", "path": "docs/ru/docs/tutorial/bigger-applications.md", "line": null, "side": "RIGHT", "created_at": "2026-01-19T09:57:56+00:00" }, { "id": 2704086824, "user": "user_29e85f9a8e75", "body": "```suggestion\n├── app # \"app\" пакет\n│   ├── __init__.py # этот файл превращает \"app\" в \"Python-пакет\"\n│   ├── main.py # модуль \"main\", напр.: import app.main\n│   ├── dependencies.py # модуль \"dependencies\", напр.: import app.dependencies\n│   └── routers # подпакет \"routers\"\n│   │ ├── __init__.py # превращает \"routers\" в подпакет\n│   │ ├── items.py # подмодуль \"items\", напр.: import app.routers.items\n│   │ └── users.py # подмодуль \"users\", напр.: import app.routers.users\n│   └── internal # подпакет \"internal\"\n│   ├── __init__.py # превращает \"internal\" в подпакет\n│   └── admin.py # подмодуль \"admin\", напр.: import app.internal.admin\n```", "path": "docs/ru/docs/tutorial/bigger-applications.md", "line": null, "side": "RIGHT", "created_at": "2026-01-19T10:07:18+00:00" }, { "id": 2704089847, "user": "user_29e85f9a8e75", "body": "```suggestion\nДавайте предположим, что для работы с пользователями используется отдельный файл (подмодуль) `/app/routers/users.py`.\n```", "path": "docs/ru/docs/tutorial/bigger-applications.md", "line": null, "side": "RIGHT", "created_at": "2026-01-19T10:08:00+00:00" }, { "id": 2704115442, "user": "user_29e85f9a8e75", "body": "```suggestion\nНапример, с помощью зависимостей в `APIRouter` мы можем потребовать аутентификации для доступа ко всей группе *операций пути*. Даже если зависимости не добавляются по отдельности к каждой из них.\n```", "path": "docs/ru/docs/tutorial/bigger-applications.md", "line": null, "side": "RIGHT", "created_at": "2026-01-19T10:15:09+00:00" }, { "id": 2704124683, "user": "user_29e85f9a8e75", "body": "```suggestion\n* Начать в том же пакете, в котором находится этот модуль (файл `app/routers/items.py`) расположен в (каталоге `app/routers/`)...\n```", "path": "docs/ru/docs/tutorial/bigger-applications.md", "line": null, "side": "RIGHT", "created_at": "2026-01-19T10:17:50+00:00" }, { "id": 2704132080, "user": "user_29e85f9a8e75", "body": "```suggestion\n## Модуль main в `FastAPI` { #the-main-fastapi }\n```", "path": "docs/ru/docs/tutorial/bigger-applications.md", "line": null, "side": "RIGHT", "created_at": "2026-01-19T10:19:59+00:00" }, { "id": 2704134899, "user": "user_29e85f9a8e75", "body": "```suggestion\nТеперь мы импортируем другие подмодули, содержащие `APIRouter`:\n```", "path": "docs/ru/docs/tutorial/bigger-applications.md", "line": null, "side": "RIGHT", "created_at": "2026-01-19T10:20:49+00:00" }, { "id": 2704136660, "user": "user_29e85f9a8e75", "body": "```suggestion\nТак как файлы `app/routers/users.py` и `app/routers/items.py` являются подмодулями, входящими в один и тот же Python-пакет `app`, мы можем использовать одну точку `.` для импорта через «относительные импорты».\n```", "path": "docs/ru/docs/tutorial/bigger-applications.md", "line": null, "side": "RIGHT", "created_at": "2026-01-19T10:21:21+00:00" }, { "id": 2704141088, "user": "user_29e85f9a8e75", "body": "```suggestion\n* найти подпакет `routers` (каталог `app/routers/`)...\n```", "path": "docs/ru/docs/tutorial/bigger-applications.md", "line": null, "side": "RIGHT", "created_at": "2026-01-19T10:22:45+00:00" }, { "id": 2704142616, "user": "user_29e85f9a8e75", "body": "```suggestion\n* Начать в том же пакете, в котором находится этот модуль (файл `app/main.py`) расположен в (каталоге `app/`)...\n```", "path": "docs/ru/docs/tutorial/bigger-applications.md", "line": null, "side": "RIGHT", "created_at": "2026-01-19T10:23:12+00:00" }, { "id": 2704145403, "user": "user_29e85f9a8e75", "body": "```suggestion\n* и импортировать из него подмодули `items` (файл `app/routers/items.py`) и `users` (файл `app/routers/users.py`)...\n```", "path": "docs/ru/docs/tutorial/bigger-applications.md", "line": null, "side": "RIGHT", "created_at": "2026-01-19T10:24:06+00:00" }, { "id": 2704148717, "user": "user_29e85f9a8e75", "body": "```suggestion\nМы импортируем подмодуль `items` напрямую, вместо того чтобы импортировать только его переменную `router`.\n```", "path": "docs/ru/docs/tutorial/bigger-applications.md", "line": null, "side": "RIGHT", "created_at": "2026-01-19T10:25:05+00:00" }, { "id": 2704150339, "user": "user_29e85f9a8e75", "body": "```suggestion\nЭто потому, что у нас также есть другая переменная с именем `router` в подмодуле `users`.\n```", "path": "docs/ru/docs/tutorial/bigger-applications.md", "line": null, "side": "RIGHT", "created_at": "2026-01-19T10:25:33+00:00" }, { "id": 2704151880, "user": "user_29e85f9a8e75", "body": "```suggestion\nПоэтому, чтобы иметь возможность использовать обе в одном файле, мы импортируем подмодули напрямую:\n```", "path": "docs/ru/docs/tutorial/bigger-applications.md", "line": null, "side": "RIGHT", "created_at": "2026-01-19T10:26:03+00:00" }, { "id": 2704153742, "user": "user_29e85f9a8e75", "body": "```suggestion\nТеперь давайте подключим `router` из подмодулей `users` и `items`:\n```", "path": "docs/ru/docs/tutorial/bigger-applications.md", "line": null, "side": "RIGHT", "created_at": "2026-01-19T10:26:37+00:00" }, { "id": 2704162728, "user": "user_29e85f9a8e75", "body": "```suggestion\nТаким образом исходный `APIRouter` не будет модифицирован, и мы сможем использовать файл `app/internal/admin.py` сразу в нескольких проектах организации.\n```", "path": "docs/ru/docs/tutorial/bigger-applications.md", "line": null, "side": "RIGHT", "created_at": "2026-01-19T10:29:20+00:00" }, { "id": 2704170422, "user": "user_29e85f9a8e75", "body": "```suggestion\nОткройте документацию по адресу http://127.0.0.1:8000/docs.\n```", "path": "docs/ru/docs/tutorial/bigger-applications.md", "line": null, "side": "RIGHT", "created_at": "2026-01-19T10:31:32+00:00" }, { "id": 2704172294, "user": "user_29e85f9a8e75", "body": "```suggestion\nВы увидите автоматическую документацию API, включая пути из всех подмодулей, с использованием корректных путей (и префиксов) и корректных тегов:\n```", "path": "docs/ru/docs/tutorial/bigger-applications.md", "line": null, "side": "RIGHT", "created_at": "2026-01-19T10:32:08+00:00" }, { "id": 2704362462, "user": "user_29e85f9a8e75", "body": "```suggestion\n* Файл `app/routers/items.py` находится внутри пакета `app/routers/`. Таким образом, он является подмодулем: `app.routers.items`.\n* Точно так же `app/routers/users.py` является ещё одним подмодулем: `app.routers.users`.\n* Подкаталог `app/internal/`, содержащий файл `__init__.py`, является ещё одним Python-подпакетом: `app.internal`.\n* А файл `app/internal/admin.py` является ещё одним подмодулем: `app.internal.admin`.\n```", "path": "docs/ru/docs/tutorial/bigger-applications.md", "line": null, "side": "RIGHT", "created_at": "2026-01-19T11:25:03+00:00" }, { "id": 2704396186, "user": "user_29e85f9a8e75", "body": "```suggestion\nТак вы сообщите редактору, что намеренно возвращаете что угодно. Но FastAPI всё равно выполнит документирование, валидацию, фильтрацию данных и т.д. с помощью `response_model`.\n```", "path": "docs/ru/docs/tutorial/response-model.md", "line": null, "side": "RIGHT", "created_at": "2026-01-19T11:35:54+00:00" } ], "meta": { "languages": [ "md" ], "touches_tests": false, "review_state_summary": { "COMMENTED": 3 }, "meaningful_comment_count": 54, "has_approval": false, "has_changes_requested": false, "total_review_comments": 54 } } { "_id": "eca5b19de9aba3f0", "_schema_version": "1.0", "_cleaned_at": "2026-02-12T07:46:51.671629+00:00", "repo": "tiangolo/fastapi", "repo_url": "https://github.com/fastapi/fastapi", "license_name": "MIT License", "license_spdx": "MIT", "pr_number": 14690, "title": "🌐 Update translations for de (update-outdated)", "body": "🌐 Update translations for de (update-outdated)\n\nThis PR was created automatically using LLMs.\n\nIt uses the prompt file https://github.com/fastapi/fastapi/blob/master/docs/de/llm-prompt.md.\n\nIn most cases, it's better to make PRs updating that file so that the LLM can do a better job generating the translations than suggesting changes in this PR.", "author": "user_2a237e38e06b", "created_at": "2026-01-11T00:29:38+00:00", "merged_at": "2026-01-22T09:27:32+00:00", "base_branch": "master", "head_branch": "translate-de-update-outdated-cffe975f", "additions": 14, "deletions": 14, "changed_files": 2, "files": [ { "filename": "docs/de/docs/_llm-test.md", "status": "modified", "additions": 1, "deletions": 1, "changes": 2, "patch": "@@ -189,7 +189,7 @@ [NAME_REDACTED] `### Links` im allgemeinen Prompt in `scripts/translate.py`.\n \n ////\n \n-## HTML „abbr“-Elemente { #html-abbr-elements }\n+## HTML-„abbr“-Elemente { #html-abbr-elements }\n \n //// tab | Test" }, { "filename": "docs/de/docs/tutorial/bigger-applications.md", "status": "modified", "additions": 13, "deletions": 13, "changes": 26, "patch": "@@ -56,19 +56,19 @@ from app.routers import items\n \n Die gleiche Dateistruktur mit Kommentaren:\n \n-```\n+```bash\n .\n-├── app # „app“ ist ein Python-Package\n-│   ├── __init__.py # diese Datei macht „app“ zu einem „Python-Package“\n-│   ├── main.py # „main“-Modul, z. B. import app.main\n-│   ├── dependencies.py # „dependencies“-Modul, z. B. import app.dependencies\n-│   └── routers # „routers“ ist ein „Python-Subpackage“\n-│   │ ├── __init__.py # macht „routers“ zu einem „Python-Subpackage“\n-│   │ ├── items.py # „items“-Submodul, z. B. import app.routers.items\n-│   │ └── users.py # „users“-Submodul, z. B. import app.routers.users\n-│   └── internal # „internal“ ist ein „Python-Subpackage“\n-│   ├── __init__.py # macht „internal“ zu einem „Python-Subpackage“\n-│   └── admin.py # „admin“-Submodul, z. B. import app.internal.admin\n+├── app # \"app\" ist ein Python-Package\n+│   ├── __init__.py # diese Datei macht \"app\" zu einem \"Python-Package\"\n+│   ├── main.py # \"main\"-Modul, z. B. import app.main\n+│   ├── dependencies.py # \"dependencies\"-Modul, z. B. import app.dependencies\n+│   └── routers # \"routers\" ist ein \"Python-Subpackage\"\n+│   │ ├── __init__.py # macht \"routers\" zu einem \"Python-Subpackage\"\n+│   │ ├── items.py # \"items\"-Submodul, z. B. import app.routers.items\n+│   │ └── users.py # \"users\"-Submodul, z. B. import app.routers.users\n+│   └── internal # \"internal\" ist ein \"Python-Subpackage\"\n+│   ├── __init__.py # macht \"internal\" zu einem \"Python-Subpackage\"\n+│   └── admin.py # \"admin\"-Submodul, z. B. import app.internal.admin\n ```\n \n ## `APIRouter` { #apirouter }\n@@ -479,7 +479,7 @@ $ fastapi dev app/main.py\n \n \n \n-und öffnen Sie die Dokumentation unter http://127.0.0.1:8000/docs.\n+Und öffnen Sie die Dokumentation unter http://127.0.0.1:8000/docs.\n \n Sie sehen die automatische API-Dokumentation, einschließlich der Pfade aller Submodule, mit den richtigen Pfaden (und Präfixen) und den richtigen Tags:" } ], "reviews": [ { "id": 3648620506, "user": "user_a924c018be02", "state": "CHANGES_REQUESTED", "body": "I also compared locally with the English documents.", "submitted_at": "2026-01-11T22:36:10+00:00" }, { "id": 3685827403, "user": "user_29e85f9a8e75", "state": "COMMENTED", "body": "Added code change suggestions according to Nils' review", "submitted_at": "2026-01-21T08:14:58+00:00" }, { "id": 3691421002, "user": "user_a924c018be02", "state": "APPROVED", "body": "Good. Thanks, Yurii!", "submitted_at": "2026-01-22T09:17:50+00:00" } ], "review_comments": [ { "id": 2680378108, "user": "user_a924c018be02", "body": "Keep.\n\nThat was addedd by [NAME_REDACTED] document.", "path": "docs/de/docs/tutorial/bigger-applications.md", "line": 59, "side": "RIGHT", "created_at": "2026-01-11T22:01:49+00:00" }, { "id": 2680384055, "user": "user_a924c018be02", "body": "Revert.\n\nThe LLM reverts the German translation, despite being told not to do that, see section _Content of code blocks_ at the top of `scripts/general-llm-prompt.md`:\n\n>Do not translate the content of code blocks, except for comments in the language which the code block uses.\n\nI am open to replace the literal quotes though, if that disturbs in code comments.\n\nIf this keeps happening we may add another example to `scripts/general-llm-prompt.md`.", "path": "docs/de/docs/tutorial/bigger-applications.md", "line": null, "side": "RIGHT", "created_at": "2026-01-11T22:05:55+00:00" }, { "id": 2680392231, "user": "user_a924c018be02", "body": "Keep.\n\nGood catch.", "path": "docs/de/docs/tutorial/bigger-applications.md", "line": 482, "side": "RIGHT", "created_at": "2026-01-11T22:11:26+00:00" }, { "id": 2680395487, "user": "user_a924c018be02", "body": "Keep.\n\nIn sync with section _German instructions, when to use and when not to use hyphens in words_ in `docs\\de\\llm-prompt.md`.", "path": "docs/de/docs/_llm-test.md", "line": 192, "side": "RIGHT", "created_at": "2026-01-11T22:13:27+00:00" }, { "id": 2680403836, "user": "user_a924c018be02", "body": "Revert.\n\nSee\n\n> You can leave the original full phrase away, if the translated full phrase is identical or starts with the same letters as the original full phrase\n\nin `scripts\\general-llm-prompt.md`.", "path": "docs/de/docs/_llm-test.md", "line": null, "side": "RIGHT", "created_at": "2026-01-11T22:19:30+00:00" }, { "id": 2680405101, "user": "user_a924c018be02", "body": "Undecided.\n\nSee below.", "path": "docs/de/docs/tutorial/bigger-applications.md", "line": null, "side": "RIGHT", "created_at": "2026-01-11T22:20:20+00:00" }, { "id": 2680406229, "user": "user_a924c018be02", "body": "Undecided.\n\nI once added these `abbr`s to the German docs (here and in other translated documents, once per document), to explain the meaning of _Request_ and _Response_. The LLM keeps removing them, despite being told not to, see:\n\n> If there is an existing translation, and it has ADDITIONAL abbr elements in a sentence, and these additional abbr elements do not exist in the related sentence in the English text, then KEEP those additional abbr elements in the translation.\n\nin `scripts/general-llm-prompt.md`.\n\nI am fine with removing them everywhere or with keeping them everywhere. Any opinions?", "path": "docs/de/docs/tutorial/bigger-applications.md", "line": null, "side": "RIGHT", "created_at": "2026-01-11T22:21:09+00:00" }, { "id": 2680414461, "user": "user_a924c018be02", "body": "Revert.\n\nThat is actually wrongly written small in the English `docs\\en\\docs\\_llm-test.md`.", "path": "docs/de/docs/_llm-test.md", "line": null, "side": "RIGHT", "created_at": "2026-01-11T22:26:46+00:00" }, { "id": 2680421789, "user": "user_a924c018be02", "body": "Revert.\n\nThe heading above explains how this should be translated. See also the translation schema for `{abbreviation}` in `scripts\\general-llm-prompt.md`.", "path": "docs/de/docs/_llm-test.md", "line": null, "side": "RIGHT", "created_at": "2026-01-11T22:31:47+00:00" }, { "id": 2711398721, "user": "user_29e85f9a8e75", "body": "```suggestion\n* PSGI\n```", "path": "docs/de/docs/_llm-test.md", "line": null, "side": "RIGHT", "created_at": "2026-01-21T08:03:21+00:00" }, { "id": 2711404436, "user": "user_29e85f9a8e75", "body": "```suggestion\n* MDN\n```", "path": "docs/de/docs/_llm-test.md", "line": null, "side": "RIGHT", "created_at": "2026-01-21T08:05:18+00:00" }, { "id": 2711412673, "user": "user_29e85f9a8e75", "body": "```suggestion\n├── app # \"app\" ist ein Python-Package\n│   ├── __init__.py # diese Datei macht \"app\" zu einem \"Python-Package\"\n│   ├── main.py # \"main\"-Modul, z. B. import app.main\n│   ├── dependencies.py # \"dependencies\"-Modul, z. B. import app.dependencies\n│   └── routers # \"routers\" ist ein \"Python-Subpackage\"\n│   │ ├── __init__.py # macht \"routers\" zu einem \"Python-Subpackage\"\n│   │ ├── items.py # \"items\"-Submodul, z. B. import app.routers.items\n│   │ └── users.py # \"users\"-Submodul, z. B. import app.routers.users\n│   └── internal # \"internal\" ist ein \"Python-Subpackage\"\n│   ├── __init__.py # macht \"internal\" zu einem \"Python-Subpackage\"\n│   └── admin.py # \"admin\"-Submodul, z. B. import app.internal.admin\n```", "path": "docs/de/docs/tutorial/bigger-applications.md", "line": null, "side": "RIGHT", "created_at": "2026-01-21T08:08:01+00:00" }, { "id": 2711418467, "user": "user_29e85f9a8e75", "body": "```suggestion\nUnd wir können eine Liste von `dependencies` hinzufügen, die allen *Pfadoperationen* im Router hinzugefügt und für jeden an sie gerichteten Request ausgeführt/aufgelöst werden.\n```", "path": "docs/de/docs/tutorial/bigger-applications.md", "line": null, "side": "RIGHT", "created_at": "2026-01-21T08:09:56+00:00" }, { "id": 2711419987, "user": "user_29e85f9a8e75", "body": "```suggestion\nUnd sie wird auch beide Responses in der Dokumentation haben, eine für `404` und eine für `403`.\n```", "path": "docs/de/docs/tutorial/bigger-applications.md", "line": null, "side": "RIGHT", "created_at": "2026-01-21T08:10:26+00:00" }, { "id": 2711431538, "user": "user_29e85f9a8e75", "body": "```suggestion\n* Cluster\n```", "path": "docs/de/docs/_llm-test.md", "line": null, "side": "RIGHT", "created_at": "2026-01-21T08:13:55+00:00" } ], "meta": { "languages": [ "md" ], "touches_tests": false, "review_state_summary": { "CHANGES_REQUESTED": 1, "COMMENTED": 1, "APPROVED": 1 }, "meaningful_comment_count": 15, "has_approval": true, "has_changes_requested": true, "total_review_comments": 15 } } { "_id": "0044122cbadd2c8b", "_schema_version": "1.0", "_cleaned_at": "2026-02-12T07:46:51.687264+00:00", "repo": "tiangolo/fastapi", "repo_url": "https://github.com/fastapi/fastapi", "license_name": "MIT License", "license_spdx": "MIT", "pr_number": 14619, "title": "🌐 Update translation prompts", "body": "🌐 Update translation prompts", "author": "user_2a237e38e06b", "created_at": "2025-12-29T18:49:10+00:00", "merged_at": "2025-12-29T18:54:20+00:00", "base_branch": "master", "head_branch": "prompts", "additions": 838, "deletions": 963, "changed_files": 12, "files": [ { "filename": "docs/de/llm-prompt.md", "status": "modified", "additions": 231, "deletions": 248, "changes": 479, "patch": "@@ -4,213 +4,197 @@ Translate to German (Deutsch).\n \n Language code: de.\n \n-\n-### Definitions\n-\n-\"hyphen\"\n- The character «-»\n- Unicode U+002D (HYPHEN-MINUS)\n- Alternative names: hyphen, dash, minus sign\n-\n-\"dash\"\n- The character «–»\n- Unicode U+2013 (EN DASH)\n- German name: Halbgeviertstrich\n-\n-\n ### Grammar to use when talking to the reader\n \n-Use the formal grammar (use «Sie» instead of «Du»).\n-\n+Use the formal grammar (use `Sie` instead of `Du`).\n \n ### Quotes\n \n-1) Convert neutral double quotes («\"») and English double typographic quotes («“» and «”») to German double typographic quotes («„» and «“»). Convert neutral single quotes («'») and English single typographic quotes («‘» and «’») to German single typographic quotes («‚» and «‘»). Do NOT convert «`\"» to «„», do NOT convert «\"`» to «“».\n+1) Convert neutral double quotes (`\"`) to German double typographic quotes (`„` and `“`). Convert neutral single quotes (`'`) to German single typographic quotes (`‚` and `‘`).\n \n-Examples:\n+Do NOT convert quotes in code snippets and code blocks to their German typographic equivalents.\n \n- Source (English):\n+Examples:\n \n- «««\n- \"Hello world\"\n- “[NAME_REDACTED]”\n- \"He said: 'Hello'\"\n- “my name is ‘Nils’”\n- `\"__main__\"`\n- `\"items\"`\n- »»»\n+Source (English):\n \n- Result (German):\n+```\n+\"Hello world\"\n+“[NAME_REDACTED]”\n+\"He said: 'Hello'\"\n+“my name is ‘Nils’”\n+`\"__main__\"`\n+`\"items\"`\n+```\n \n- «««\n- „[NAME_REDACTED]“\n- „[NAME_REDACTED]“\n- „Er sagte: ‚Hallo‘“\n- „[NAME_REDACTED] ist ‚Nils‘“\n- `\"__main__\"`\n- `\"items\"`\n- »»»\n+Result (German):\n \n+```\n+„[NAME_REDACTED]“\n+„[NAME_REDACTED]“\n+„Er sagte: ‚Hallo‘“\n+„[NAME_REDACTED] ist ‚Nils‘“\n+`\"__main__\"`\n+`\"items\"`\n+```\n \n ### Ellipsis\n \n-1) Make sure there is a space between an ellipsis and a word following or preceding the ellipsis.\n+- Make sure there is a space between an ellipsis and a word following or preceding the ellipsis.\n \n Examples:\n \n- Source (English):\n-\n- «««\n- ...as we intended.\n- ...this would work:\n- ...etc.\n- others...\n- More to come...\n- »»»\n+Source (English):\n \n- Result (German):\n+```\n+...as we intended.\n+...this would work:\n+...etc.\n+others...\n+More to come...\n+```\n \n- «««\n- ... wie wir es beabsichtigt hatten.\n- ... das würde funktionieren:\n- ... usw.\n- Andere ...\n- Später mehr ...\n- »»»\n+Result (German):\n \n-2) This does not apply in URLs, code blocks, and code snippets. Do not remove or add spaces there.\n+```\n+... wie wir es beabsichtigt hatten.\n+... das würde funktionieren:\n+... usw.\n+Andere ...\n+Später mehr ...\n+```\n \n+- This does not apply in URLs, code blocks, and code snippets. Do not remove or add spaces there.\n \n ### Headings\n \n-1) Translate headings using the infinite form.\n+- Translate headings using the infinite form.\n \n Examples:\n \n- Source (English):\n+Source (English):\n \n- «««\n- ## Create a Project { #create-a-project }\n- »»»\n+```\n+## Create a Project { #create-a-project }\n+```\n \n- Translate with (German):\n+Result (German):\n \n- «««\n- ## [NAME_REDACTED] erstellen { #create-a-project }\n- »»»\n+```\n+## [NAME_REDACTED] erstellen { #create-a-project }\n+```\n \n- [NAME_REDACTED] translate with (German):\n+Do NOT translate with (German):\n \n- «««\n- ## [NAME_REDACTED] ein Projekt { #create-a-project }\n- »»»\n+```\n+## [NAME_REDACTED] ein Projekt { #create-a-project }\n+```\n \n- Source (English):\n+Source (English):\n \n- «««\n- # [NAME_REDACTED] { #install-packages }\n- »»»\n+```\n+# [NAME_REDACTED] { #install-packages }\n+```\n \n- Translate with (German):\n+Translate with (German):\n \n- «««\n- # Pakete installieren { #install-packages }\n- »»»\n+```\n+# Pakete installieren { #install-packages }\n+```\n \n- [NAME_REDACTED] translate with (German):\n+Do NOT translate with (German):\n \n- «««\n- # [NAME_REDACTED] { #install-packages }\n- »»»\n+```\n+# [NAME_REDACTED] { #install-packages }\n+```\n \n- Source (English):\n+Source (English):\n \n- «««\n- ### [NAME_REDACTED] { #run-your-program }\n- »»»\n+```\n+### [NAME_REDACTED] { #run-your-program }\n+```\n \n- Translate with (German):\n+Translate with (German):\n \n- «««\n- ### [NAME_REDACTED] ausführen { #run-your-program }\n- »»»\n+```\n+### [NAME_REDACTED] ausführen { #run-your-program }\n+```\n \n- [NAME_REDACTED] translate with (German):\n+Do NOT translate with (German):\n \n- «««\n- ### Führen [NAME_REDACTED] aus { #run-your-program }\n- »»»\n+```\n+### Führen [NAME_REDACTED] aus { #run-your-program }\n+```\n \n-2) Make sure that the translated part of the heading does not end with a period.\n+- Make sure that the translated part of the heading does not end with a period.\n \n Example:\n \n- Source (English):\n+Source (English):\n \n- «««\n- ## Another module with `APIRouter` { #another-module-with-apirouter }\n- »»»\n+```\n+## Another module with `APIRouter` { #another-module-with-apirouter }\n+```\n \n- Translate with (German):\n+Translate with (German):\n \n- «««\n- ## Ein weiteres Modul mit `APIRouter` { #another-module-with-apirouter }\n- »»»\n+```\n+## Ein weiteres Modul mit `APIRouter` { #another-module-with-apirouter }\n+```\n \n- [NAME_REDACTED] translate with (German) – notice the added period:\n+Do NOT translate with (German) – notice the added period:\n \n- «««\n- ## Ein weiteres Modul mit `APIRouter`. { #another-module-with-apirouter }\n- »»»\n+```\n+## Ein weiteres Modul mit `APIRouter`. { #another-module-with-apirouter }\n+```\n \n-3) Replace occurrences of literal « - » (a space followed by a hyphen followed by a space) with « – » (a space followed by a dash followed by a space) in the translated part of the heading.\n+- Replace occurrences of literal ` - ` (a space followed by a hyphen followed by a space) with ` – ` (a space followed by a dash followed by a space) in the translated part of the heading.\n \n Example:\n \n- Source (English):\n+Source (English):\n \n- «««\n- # FastAPI in Containers - Docker { #fastapi-in-containers-docker }\n- »»»\n+```\n+# FastAPI in Containers - Docker { #fastapi-in-containers-docker }\n+```\n \n- Translate with (German) – notice the dash:\n+Translate with (German) – notice the dash:\n \n- «««\n- # FastAPI in Containern – Docker { #fastapi-in-containers-docker }\n- »»»\n+```\n+# FastAPI in Containern – Docker { #fastapi-in-containers-docker }\n+```\n \n- [NAME_REDACTED] translate with (German) – notice the hyphen:\n+Do NOT translate with (German) – notice the hyphen:\n \n- «««\n- # FastAPI in Containern - Docker { #fastapi-in-containers-docker }\n- »»»\n+```\n+# FastAPI in Containern - Docker { #fastapi-in-containers-docker }\n+```\n \n-3.1) Do not apply rule 3 when there is no space before or no space after the hyphen.\n+- Do not apply rule 3 when there is no space before or no space after the hyphen.\n \n Example:\n \n- Source (English):\n+Source (English):\n \n- «««\n- ## Type hints and annotations { #type-hints-and-annotations }\n- »»»\n+```\n+## Type hints and annotations { #type-hints-and-annotations }\n+```\n \n- Translate with (German) – notice the hyphen:\n+Translate with (German) - notice the hyphen:\n \n- «««\n- ## Typhinweise und -annotationen { #type-hints-and-annotations }\n- »»»\n+```\n+## Typhinweise und -annotationen { #type-hints-and-annotations }\n+```\n \n- [NAME_REDACTED] translate with (German) – notice the dash:\n+Do NOT translate with (German) - notice the dash:\n \n- «««\n- ## Typhinweise und –annotationen { #type-hints-and-annotations }\n- »»»\n+```\n+## Typhinweise und –annotationen { #type-hints-and-annotations }\n+```\n \n-3.2) Do not apply rule 3 to the untranslated part of the heading inside curly brackets, which you shall not translate.\n+- Do not modify the hyphens in the content in headers inside of curly braces, which you shall not translate.\n \n-\n-### German instructions, when to use and when not to use hyphens in words (written in first person, which is you)\n+### German instructions, when to use and when not to use hyphens in words (written in first person, which is you).\n \n In der Regel versuche ich so weit wie möglich Worte zusammenzuschreiben, also ohne Bindestrich, es sei denn, es ist Konkretesding-Klassevondingen, etwa «Pydantic-Modell» (aber: «Datenbankmodell»), «Python-Modul» (aber: «Standardmodul»). Ich setze auch einen Bindestrich, wenn er die gleichen Buchstaben verbindet, etwa «Enum-Member», «Cloud-Dienst», «Template-Engine». Oder wenn das Wort sonst einfach zu lang wird, etwa, «Performance-Optimierung». Oder um etwas visuell besser zu dokumentieren, etwa «Pfadoperation-Dekorator», «Pfadoperation-Funktion».\n \n@@ -219,123 +203,122 @@ In der Regel versuche ich so weit wie möglich Worte zusammenzuschreiben, also o\n \n Ich versuche nicht, alles einzudeutschen. Das bezieht sich besonders auf Begriffe aus dem Bereich der Programmierung. Ich wandele zwar korrekt in Großschreibung um und setze Bindestriche, wo notwendig, aber ansonsten lasse ich solch ein Wort unverändert. Beispielsweise wird aus dem englischen Wort «string» in der deutschen Übersetzung «String», aber nicht «Zeichenkette». Oder aus dem englischen Wort «request body» wird in der deutschen Übersetzung «Requestbody», aber nicht «Anfragekörper». Oder aus dem englischen «response» wird im Deutschen «Response», aber nicht «Antwort».\n \n-\n ### List of English terms and their preferred German translations\n \n-Below is a list of English terms and their preferred German translations, separated by a colon («:»). Use these translations, do not use your own. If an existing translation does not use these terms, update it to use them. In the below list, a term or a translation may be followed by [NAME_REDACTED], which explains when to translate the term this way. If a translation is preceded by «NOT», then that means: do NOT use this translation for this term. English nouns, starting with the word «the», have the German genus – «der», «die», «das» – prepended to their German translation, to help you to grammatically decline them in the translation. They are given in singular case, unless they have «(plural)» attached, which means they are given in plural case. Verbs are given in the full infinitive – starting with the word «to».\n-\n-* «/// check»: «/// check | Testen»\n-* «/// danger»: «/// danger | Gefahr»\n-* «/// info»: «/// info | Info»\n-* «/// note | [NAME_REDACTED]»: «/// note | [NAME_REDACTED]»\n-* «/// note»: «/// note | Hinweis»\n-* «/// tip»: «/// tip | Tipp»\n-* «/// warning»: «/// warning | Achtung»\n-* «you»: «Sie»\n-* «your»: «Ihr»\n-* «e.g»: «z. B.»\n-* «etc.»: «usw.»\n-* «ref»: «Ref.»\n-* «the Tutorial - User guide»: «das Tutorial – Benutzerhandbuch»\n-* «the [NAME_REDACTED]»: «das Handbuch für fortgeschrittene Benutzer»\n-* «the SQLModel docs»: «die SQLModel-Dokumentation»\n-* «the docs»: «die Dokumentation» (use singular case)\n-* «the env var»: «die Umgebungsvariable»\n-* «the `PATH` environment variable»: «die `PATH`-Umgebungsvariable»\n-* «the `PATH`»: «der `PATH`»\n-* «the `requirements.txt`»: «die `requirements.txt`»\n-* «the API Router»: «der API-Router»\n-* «the Authorization-Header»: «der Autorisierungsheader»\n-* «the `Authorization`-Header»: «der `Authorization`-Header»\n-* «the background task»: «der Hintergrundtask»\n-* «the button»: «der Button»\n-* «the cloud provider»: «der Cloudanbieter»\n-* «the CLI»: «Das CLI»\n-* «the coverage»: «[NAME_REDACTED]»\n-* «the command line interface»: «[NAME_REDACTED]»\n-* «the default value»: «der Defaultwert»\n-* «the default value»: NOT «der Standardwert»\n-* «the default declaration»: «die Default-Deklaration»\n-* «the deployment»: «das Deployment»\n-* «the dict»: «das Dict»\n-* «the dictionary»: «das Dictionary»\n-* «the enumeration»: «die Enumeration»\n-* «the enum»: «das Enum»\n-* «the engine»: «die Engine»\n-* «the error response»: «die Error-Response»\n-* «the event»: «das Event»\n-* «the exception»: «die Exception»\n-* «the exception handler»: «der Exceptionhandler»\n-* «the form model»: «das Formularmodell»\n-* «the form body»: «der Formularbody»\n-* «the header»: «der Header»\n-* «the headers» (plural): «die Header»\n-* «in headers» (plural): «in Headern»\n-* «the forwarded header»: «der Forwarded-Header»\n-* «the lifespan event»: «das Lifespan-Event»\n-* «the lock»: «der Lock»\n-* «the locking»: «das Locking»\n-* «the mobile application»: «die Mobile-Anwendung»\n-* «the model object»: «das Modellobjekt»\n-* «the mounting»: «das Mounten»\n-* «mounted»: «gemountet»\n-* «the origin»: «das Origin»\n-* «the override»: «Die Überschreibung»\n-* «the parameter»: «der Parameter»\n-* «the parameters» (plural): «die Parameter»\n-* «the function parameter»: «der Funktionsparameter»\n-* «the default parameter»: «der Defaultparameter»\n-* «the body parameter»: «der Body-Parameter»\n-* «the request body parameter»: «der Requestbody-Parameter»\n-* «the path parameter»: «der Pfad-Parameter»\n-* «the query parameter»: «der Query-Parameter»\n-* «the cookie parameter»: «der Cookie-Parameter»\n-* «the header parameter»: «der Header-Parameter»\n-* «the form parameter»: «der Formular-Parameter»\n-* «the payload»: «die Payload»\n-* «the performance»: NOT «die Performance»\n-* «the query»: «die Query»\n-* «the recap»: «die Zusammenfassung»\n-* «the request» (what the client sends to the server): «der Request»\n-* «the request body»: «der Requestbody»\n-* «the request bodies» (plural): «die Requestbodys»\n-* «the response» (what the server sends back to the client): «die Response»\n-* «the return type»: «der Rückgabetyp»\n-* «the return value»: «der Rückgabewert»\n-* «the startup» (the event of the app): «der Startup»\n-* «the shutdown» (the event of the app): «der Shutdown»\n-* «the startup event»: «das Startup-Event»\n-* «the shutdown event»: «das Shutdown-Event»\n-* «the startup» (of the server): «das Hochfahren»\n-* «the startup» (the company): «das Startup»\n-* «the SDK»: «das SDK»\n-* «the tag»: «der Tag»\n-* «the type annotation»: «die Typannotation»\n-* «the type hint»: «der Typhinweis»\n-* «the wildcard»: «die Wildcard»\n-* «the worker class»: «die Workerklasse»\n-* «the worker class»: NOT «die Arbeiterklasse»\n-* «the worker process»: «der Workerprozess»\n-* «the worker process»: NOT «der Arbeiterprozess»\n-* «to commit»: «committen»\n-* «to deploy» (in the cloud): «deployen»\n-* «to modify»: «ändern»\n-* «to serve» (an application): «bereitstellen»\n-* «to serve» (a response): «ausliefern»\n-* «to serve»: NOT «bedienen»\n-* «to upgrade»: «aktualisieren»\n-* «to wrap»: «wrappen»\n-* «to wrap»: NOT «hüllen»\n-* «`foo` as a `type`»: «`foo` vom Typ `type`»\n-* «`foo` as a `type`»: «`foo`, ein `type`»\n-* «FastAPI's X»: «FastAPIs X»\n-* «Starlette's Y»: «Starlettes Y»\n-* «X is case-sensitive»: «Groß-/Klein­schrei­bung ist relevant in X»\n-* «X is case-insensitive»: «Groß-/Klein­schrei­bung ist nicht relevant in X»\n-* «standard Python»: «Standard-Python»\n-* «deprecated»: «deprecatet»\n+Below is a list of English terms and their preferred German translations, separated by a colon (:). Use these translations, do not use your own. If an existing translation does not use these terms, update it to use them. In the below list, a term or a translation may be followed by [NAME_REDACTED], which explains when to translate the term this way. If a translation is preceded by `NOT`, then that means: do NOT use this translation for this term. English nouns, starting with the word `the`, have the German genus – `der`, `die`, `das` – prepended to their German translation, to help you to grammatically decline them in the translation. They are given in singular case, unless they have `(plural)` attached, which means they are given in plural case. Verbs are given in the full infinitive – starting with the word `to`.\n+\n+* /// check: /// check | Testen\n+* /// danger: /// danger | Gefahr\n+* /// info: /// info | Info\n+* /// note | [NAME_REDACTED]: /// note | [NAME_REDACTED]\n+* /// note: /// note | Hinweis\n+* /// tip: /// tip | Tipp\n+* /// warning: /// warning | Achtung\n+* you: Sie\n+* your: Ihr\n+* e.g: z. B.\n+* etc.: usw.\n+* ref: Ref.\n+* the Tutorial - User guide: das Tutorial – Benutzerhandbuch\n+* the [NAME_REDACTED]: das Handbuch für fortgeschrittene Benutzer\n+* the SQLModel docs: die SQLModel-Dokumentation\n+* the docs: die Dokumentation (use singular case)\n+* the env var: die Umgebungsvariable\n+* the `PATH` environment variable: die `PATH`-Umgebungsvariable\n+* the `PATH`: der `PATH`\n+* the `requirements.txt`: die `requirements.txt`\n+* the API Router: der API-Router\n+* the Authorization-Header: der Autorisierungsheader\n+* the `Authorization`-Header: der `Authorization`-Header\n+* the background task: der Hintergrundtask\n+* the button: der Button\n+* the cloud provider: der Cloudanbieter\n+* the CLI: Das CLI\n+* the coverage: [NAME_REDACTED]\n+* the command line interface: [NAME_REDACTED]\n+* the default value: der Defaultwert\n+* the default value: NOT der Standardwert\n+* the default declaration: die Default-Deklaration\n+* the deployment: das Deployment\n+* the dict: das Dict\n+* the dictionary: das Dictionary\n+* the enumeration: die Enumeration\n+* the enum: das Enum\n+* the engine: die Engine\n+* the error response: die Error-Response\n+* the event: das Event\n+* the exception: die Exception\n+* the exception handler: der Exceptionhandler\n+* the form model: das Formularmodell\n+* the form body: der Formularbody\n+* the header: der Header\n+* the headers (plural): die Header\n+* in headers (plural): in Headern\n+* the forwarded header: der Forwarded-Header\n+* the lifespan event: das Lifespan-Event\n+* the lock: der Lock\n+* the locking: das Locking\n+* the mobile application: die Mobile-Anwendung\n+* the model object: das Modellobjekt\n+* the mounting: das Mounten\n+* mounted: gemountet\n+* the origin: das Origin\n+* the override: Die Überschreibung\n+* the parameter: der Parameter\n+* the parameters (plural): die Parameter\n+* the function parameter: der Funktionsparameter\n+* the default parameter: der Defaultparameter\n+* the body parameter: der Body-Parameter\n+* the request body parameter: der Requestbody-Parameter\n+* the path parameter: der Pfad-Parameter\n+* the query parameter: der Query-Parameter\n+* the cookie parameter: der Cookie-Parameter\n+* the header parameter: der Header-Parameter\n+* the form parameter: der Formular-Parameter\n+* the payload: die Payload\n+* the performance: NOT die Performance\n+* the query: die Query\n+* the recap: die Zusammenfassung\n+* the request (what the client sends to the server): der Request\n+* the request body: der Requestbody\n+* the request bodies (plural): die Requestbodys\n+* the response (what the server sends back to the client): die Response\n+* the return type: der Rückgabetyp\n+* the return value: der Rückgabewert\n+* the startup (the event of the app): der Startup\n+* the shutdown (the event of the app): der Shutdown\n+* the startup event: das Startup-Event\n+* the shutdown event: das Shutdown-Event\n+* the startup (of the server): das Hochfahren\n+* the startup (the company): das Startup\n+* the SDK: das SDK\n+* the tag: der Tag\n+* the type annotation: die Typannotation\n+* the type hint: der Typhinweis\n+* the wildcard: die Wildcard\n+* the worker class: die Workerklasse\n+* the worker class: NOT die Arbeiterklasse\n+* the worker process: der Workerprozess\n+* the worker process: NOT der Arbeiterprozess\n+* to commit: committen\n+* to deploy (in the cloud): deployen\n+* to modify: ändern\n+* to serve (an application): bereitstellen\n+* to serve (a response): ausliefern\n+* to serve: NOT bedienen\n+* to upgrade: aktualisieren\n+* to wrap: wrappen\n+* to wrap: NOT hüllen\n+* `foo` as a `type`: `foo` vom Typ `type`\n+* `foo` as a `type`: `foo`, ein `type`\n+* FastAPI's X: FastAPIs X\n+* Starlette's Y: Starlettes Y\n+* X is case-sensitive: Groß-/Klein­schrei­bung ist relevant in X\n+* X is case-insensitive: Groß-/Klein­schrei­bung ist nicht relevant in X\n+* standard Python: Standard-Python\n+* deprecated: deprecatet\n \n \n ### Other rules\n \n-Preserve indentation. Keep emoticons. Encode in utf-8. Use Linux line breaks (LF).\n+Preserve indentation. Keep emojis. Encode in utf-8. Use Linux line breaks (LF)." }, { "filename": "docs/en/docs/_llm-test.md", "status": "modified", "additions": 1, "deletions": 1, "changes": 2, "patch": "@@ -6,7 +6,7 @@ Tests added here will be seen by [NAME_REDACTED] specific prompts.\n \n Use as follows:\n \n-* Have a language specific prompt – `docs/{language code}/llm-prompt.md`.\n+* Have a language specific prompt - `docs/{language code}/llm-prompt.md`.\n * Do a fresh translation of this document into your desired target language (see e.g. the `translate-page` command of the `translate.py`). This will create the translation under `docs/{language code}/docs/_llm-test.md`.\n * Check if things are okay in the translation.\n * If necessary, improve your language specific prompt, the general prompt, or the English document." }, { "filename": "docs/ja/llm-prompt.md", "status": "modified", "additions": 8, "deletions": 8, "changes": 16, "patch": "@@ -6,23 +6,23 @@ Language code: ja.\n \n ### Grammar and tone\n \n-1) Use polite, instructional Japanese (です/ます調).\n-2) Keep the tone concise and technical (match existing [NAME_REDACTED] docs).\n+- Use polite, instructional Japanese (です/ます調).\n+- Keep the tone concise and technical (match existing [NAME_REDACTED] docs).\n \n ### Headings\n \n-1) Follow the existing Japanese style: short, descriptive headings (often noun phrases), e.g. 「チェック」.\n-2) Do not add a trailing period at the end of headings.\n+- Follow the existing Japanese style: short, descriptive headings (often noun phrases), e.g. 「チェック」.\n+- Do not add a trailing period at the end of headings.\n \n ### Quotes\n \n-1) [NAME_REDACTED] corner brackets 「」 in normal prose when quoting a term.\n-2) Do not change quotes inside inline code, code blocks, URLs, or file paths.\n+- [NAME_REDACTED] corner brackets 「」 in normal prose when quoting a term.\n+- Do not change quotes inside inline code, code blocks, URLs, or file paths.\n \n ### Ellipsis\n \n-1) Keep ellipsis style consistent with existing Japanese docs (commonly `...`).\n-2) Never change `...` in code, URLs, or CLI examples.\n+- Keep ellipsis style consistent with existing Japanese docs (commonly `...`).\n+- Never change `...` in code, URLs, or CLI examples.\n \n ### Preferred translations / glossary" }, { "filename": "docs/ko/llm-prompt.md", "status": "modified", "additions": 8, "deletions": 8, "changes": 16, "patch": "@@ -6,23 +6,23 @@ Language code: ko.\n \n ### Grammar and tone\n \n-1) Use polite, instructional Korean (e.g. 합니다/하세요 style).\n-2) Keep the tone consistent with the existing [NAME_REDACTED] docs.\n+- Use polite, instructional Korean (e.g. 합니다/하세요 style).\n+- Keep the tone consistent with the existing [NAME_REDACTED] docs.\n \n ### Headings\n \n-1) Follow existing Korean heading style (short, action-oriented headings like “확인하기”).\n-2) Do not add trailing punctuation to headings.\n+- Follow existing Korean heading style (short, action-oriented headings like “확인하기”).\n+- Do not add trailing punctuation to headings.\n \n ### Quotes\n \n-1) Keep quote style consistent with the existing Korean docs.\n-2) Never change quotes inside inline code, code blocks, URLs, or file paths.\n+- Keep quote style consistent with the existing Korean docs.\n+- Never change quotes inside inline code, code blocks, URLs, or file paths.\n \n ### Ellipsis\n \n-1) Keep ellipsis style consistent with existing Korean docs (often `...`).\n-2) Never change `...` in code, URLs, or CLI examples.\n+- Keep ellipsis style consistent with existing Korean docs (often `...`).\n+- Never change `...` in code, URLs, or CLI examples.\n \n ### Preferred translations / glossary" }, { "filename": "docs/missing-translation.md", "status": "modified", "additions": 1, "deletions": 1, "changes": 2, "patch": "@@ -4,6 +4,6 @@ This page hasn’t been translated into your language yet. 🌍\n \n We’re currently switching to an automated translation system 🤖, which will help keep all translations complete and up to date.\n \n-Learn more: [Contributing – Translations](https://fastapi.tiangolo.com/contributing/#translations){.internal-link target=_blank}\n+Learn more: [Contributing - Translations](https://fastapi.tiangolo.com/contributing/#translations){.internal-link target=_blank}\n \n ///" }, { "filename": "docs/pt/llm-prompt.md", "status": "modified", "additions": 9, "deletions": 9, "changes": 18, "patch": "@@ -14,15 +14,15 @@ When translating documentation into Portuguese, use neutral and widely understan\n \n For the next terms, use the following translations:\n \n-* «/// check»: «/// check | Verifique»\n-* «/// danger»: «/// danger | Cuidado»\n-* «/// info»: «/// info | Informação»\n-* «/// note | [NAME_REDACTED]»: «/// note | Detalhes Técnicos»\n-* «/// info | [NAME_REDACTED]»: «/// note | Detalhes Técnicos Avançados»\n-* «/// note»: «/// note | Nota»\n-* «/// tip»: «/// tip | Dica»\n-* «/// warning»: «/// warning | Atenção»\n-* «(you should)»: «(você deveria)»\n+* /// check: /// check | Verifique\n+* /// danger: /// danger | Cuidado\n+* /// info: /// info | Informação\n+* /// note | [NAME_REDACTED]: /// note | Detalhes Técnicos\n+* /// info | [NAME_REDACTED]: /// note | Detalhes Técnicos Avançados\n+* /// note: /// note | Nota\n+* /// tip: /// tip | Dica\n+* /// warning: /// warning | Atenção\n+* (you should): (você deveria)\n * async context manager: gerenciador de contexto assíncrono\n * autocomplete: autocompletar\n * autocompletion: preenchimento automático" }, { "filename": "docs/tr/llm-prompt.md", "status": "modified", "additions": 9, "deletions": 9, "changes": 18, "patch": "@@ -6,22 +6,22 @@ Language code: tr.\n \n ### Grammar and tone\n \n-1) Use instructional Turkish, consistent with existing Turkish docs.\n-2) Use imperative/guide language when appropriate (e.g. “açalım”, “gidin”, “kopyalayalım”).\n+- Use instructional Turkish, consistent with existing Turkish docs.\n+- Use imperative/guide language when appropriate (e.g. “açalım”, “gidin”, “kopyalayalım”).\n \n ### Headings\n \n-1) Follow existing Turkish heading style ([NAME_REDACTED] where used; no trailing period).\n+- Follow existing Turkish heading style ([NAME_REDACTED] where used; no trailing period).\n \n ### Quotes\n \n-1) Keep quote style consistent with the existing Turkish docs (they frequently use ASCII quotes in prose).\n-2) Never change quotes inside inline code, code blocks, URLs, or file paths.\n+- Alıntı stili mevcut Türkçe dokümanlarla tutarlı tutun (genellikle metin içinde ASCII tırnak işaretleri kullanılır).\n+- Satır içi kod, kod blokları, URL'ler veya dosya yolları içindeki tırnak işaretlerini asla değiştirmeyin.\n \n ### Ellipsis\n \n-1) Keep ellipsis style consistent with existing Turkish docs.\n-2) Never change `...` in code, URLs, or CLI examples.\n+- Üç nokta (...) stili mevcut Türkçe dokümanlarla tutarlı tutun.\n+- Kod, URL veya CLI örneklerindeki `...` ifadesini asla değiştirmeyin.\n \n ### Preferred translations / glossary\n \n@@ -39,8 +39,8 @@ Do not translate technical terms like path, route, request, response, query, bod\n \n ### `///` admonitions\n \n-1) Keep the admonition keyword in English (do not translate `note`, `tip`, etc.).\n-2) If a title is present, prefer these canonical titles:\n+- Keep the admonition keyword in English (do not translate `note`, `tip`, etc.).\n+- If a title is present, prefer these canonical titles:\n \n - `/// note | Not`\n - `/// note | [NAME_REDACTED]`" }, { "filename": "docs/uk/llm-prompt.md", "status": "modified", "additions": 10, "deletions": 10, "changes": 20, "patch": "@@ -6,23 +6,23 @@ Language code: uk.\n \n ### Grammar and tone\n \n-1) Use polite/formal address consistent with existing Ukrainian docs (use “ви/ваш”).\n-2) Keep the tone concise and technical.\n+- Use polite/formal address consistent with existing Ukrainian docs (use “ви/ваш”).\n+- Keep the tone concise and technical.\n \n ### Headings\n \n-1) Follow existing Ukrainian heading style; keep headings short and instructional.\n-2) Do not add trailing punctuation to headings.\n+- Follow existing Ukrainian heading style; keep headings short and instructional.\n+- Do not add trailing punctuation to headings.\n \n ### Quotes\n \n-1) [NAME_REDACTED] guillemets «…» for quoted terms in prose, matching existing Ukrainian docs.\n-2) Never change quotes inside inline code, code blocks, URLs, or file paths.\n+- [NAME_REDACTED] guillemets «…» for quoted terms in prose, matching existing Ukrainian docs.\n+- Never change quotes inside inline code, code blocks, URLs, or file paths.\n \n ### Ellipsis\n \n-1) Keep ellipsis style consistent with existing Ukrainian docs.\n-2) Never change `...` in code, URLs, or CLI examples.\n+- Keep ellipsis style consistent with existing Ukrainian docs.\n+- Never change `...` in code, URLs, or CLI examples.\n \n ### Preferred translations / glossary\n \n@@ -35,8 +35,8 @@ Use the following preferred translations when they apply in documentation prose:\n \n ### `///` admonitions\n \n-1) Keep the admonition keyword in English (do not translate `note`, `tip`, etc.).\n-2) If a title is present, prefer these canonical titles (choose one canonical form where variants exist):\n+- Keep the admonition keyword in English (do not translate `note`, `tip`, etc.).\n+- If a title is present, prefer these canonical titles (choose one canonical form where variants exist):\n \n - `/// note | Примітка`\n - `/// note | Технічні деталі`" }, { "filename": "docs/zh-hant/llm-prompt.md", "status": "modified", "additions": 20, "deletions": 14, "changes": 34, "patch": "@@ -6,30 +6,30 @@ Language code: zh-hant.\n \n ### Grammar and tone\n \n-1) Use clear, concise technical [NAME_REDACTED] consistent with existing docs.\n-2) Address the reader naturally (commonly using “你/你的”).\n+- Use clear, concise technical [NAME_REDACTED] consistent with existing docs.\n+- Address the reader naturally (commonly using “你/你的”).\n \n ### Headings\n \n-1) Follow existing [NAME_REDACTED] heading style (short and descriptive).\n-2) Do not add trailing punctuation to headings.\n+- Follow existing [NAME_REDACTED] heading style (short and descriptive).\n+- Do not add trailing punctuation to headings.\n \n ### Quotes and punctuation\n \n-1) Keep punctuation style consistent with existing [NAME_REDACTED] docs (they often mix English terms like “FastAPI” with Chinese text).\n-2) Never change punctuation inside inline code, code blocks, URLs, or file paths.\n-3) For more details, please follow the [[NAME_REDACTED]](https://github.com/[USER_REDACTED]noid/chinese-copywriting-guidelines).\n+- Keep punctuation style consistent with existing [NAME_REDACTED] docs (they often mix English terms like “FastAPI” with Chinese text).\n+- Never change punctuation inside inline code, code blocks, URLs, or file paths.\n+- For more details, please follow the [[NAME_REDACTED]](https://github.com/[USER_REDACTED]noid/chinese-copywriting-guidelines).\n \n ### Ellipsis\n \n-1) Keep ellipsis style consistent within each document, prefer `...` over `……`.\n-2) Never change ellipsis in code, URLs, or CLI examples.\n+- Keep ellipsis style consistent within each document, prefer `...` over `……`.\n+- Never change ellipsis in code, URLs, or CLI examples.\n \n ### Preferred translations / glossary\n \n-1. Should avoid using simplified Chinese characters and terms. Always examine if the translation can be easily comprehended by [NAME_REDACTED]\n-2. For some Python-specific terms like \"pickle\", \"list\", \"dict\" etc, we don't have to translate them.\n-3. Use the following preferred translations when they apply in documentation prose:\n+- Should avoid using simplified Chinese characters and terms. Always examine if the translation can be easily comprehended by [NAME_REDACTED]\n+- For some Python-specific terms like \"pickle\", \"list\", \"dict\" etc, we don't have to translate them.\n+- Use the following preferred translations when they apply in documentation prose:\n \n - request (HTTP): 請求\n - response (HTTP): 回應\n@@ -50,5 +50,11 @@ Notes:\n \n - `details` blocks exist; keep `/// details` as-is and translate only the title after `|`.\n - Example canonical titles used in existing docs:\n- - `/// details | 上述指令的含義`\n- - `/// details | 關於 `requirements.txt``\n+\n+```\n+/// details | 上述指令的含義\n+```\n+\n+```\n+/// details | 關於 `requirements.txt`\n+```" }, { "filename": "docs/zh/llm-prompt.md", "status": "modified", "additions": 11, "deletions": 11, "changes": 22, "patch": "@@ -6,24 +6,24 @@ Language code: zh.\n \n ### Grammar and tone\n \n-1) Use clear, concise technical Chinese consistent with existing docs.\n-2) Address the reader naturally (commonly using “你/你的”).\n+- Use clear, concise technical Chinese consistent with existing docs.\n+- Address the reader naturally (commonly using “你/你的”).\n \n ### Headings\n \n-1) Follow existing [NAME_REDACTED] heading style (short and descriptive).\n-2) Do not add trailing punctuation to headings.\n-3) If a heading contains only the name of a FastAPI feature, do not translate it.\n+- Follow existing [NAME_REDACTED] heading style (short and descriptive).\n+- Do not add trailing punctuation to headings.\n+- If a heading contains only the name of a FastAPI feature, do not translate it.\n \n ### Quotes and punctuation\n \n-1) Keep punctuation style consistent with existing [NAME_REDACTED] docs (they often mix English terms like “FastAPI” with Chinese text).\n-2) Never change punctuation inside inline code, code blocks, URLs, or file paths.\n+- Keep punctuation style consistent with existing [NAME_REDACTED] docs (they often mix English terms like “FastAPI” with Chinese text).\n+- Never change punctuation inside inline code, code blocks, URLs, or file paths.\n \n ### Ellipsis\n \n-1) Keep ellipsis style consistent within each document, prefer `...` over `……`.\n-2) Never change ellipsis in code, URLs, or CLI examples.\n+- Keep ellipsis style consistent within each document, prefer `...` over `……`.\n+- Never change ellipsis in code, URLs, or CLI examples.\n \n ### Preferred translations / glossary\n \n@@ -36,8 +36,8 @@ Use the following preferred translations when they apply in documentation prose:\n \n ### `///` admonitions\n \n-1) Keep the admonition keyword in English (do not translate `note`, `tip`, etc.).\n-2) If a title is present, prefer these canonical titles:\n+- Keep the admonition keyword in English (do not translate `note`, `tip`, etc.).\n+- If a title is present, prefer these canonical titles:\n \n - `/// tip | 提示`\n - `/// note | 注意`" }, { "filename": "scripts/general-llm-prompt.md", "status": "added", "additions": 528, "deletions": 0, "changes": 528, "patch": "@@ -0,0 +1,528 @@\n+### Your task\n+\n+Translate an English original content to a target language.\n+\n+The original content is written in Markdown, write the translation in Markdown as well.\n+\n+The original content will be surrounded by [NAME_REDACTED] (%%%). Do not include the triple percentage signs in the translation.\n+\n+### Technical terms in English\n+\n+For technical terms in English that don't have a common translation term, use the original term in English.\n+\n+### Content of code snippets\n+\n+Do not translate the content of code snippets, keep the original in English. For example, `list`, `dict`, keep them as is.\n+\n+### Content of code blocks\n+\n+Do not translate the content of code blocks, except for comments in the language which the code block uses.\n+\n+Examples:\n+\n+Source (English) - The code block is a bash code example with one comment:\n+\n+```bash\n+# Print greeting\n+echo \"Hello, World!\"\n+```\n+\n+Result (German):\n+\n+```bash\n+# Gruß ausgeben\n+echo \"Hello, World!\"\n+```\n+\n+Source (English) - The code block is a console example containing HTML tags. No comments, so nothing to change here:\n+\n+```console\n+$ fastapi run main.py\n+ FastAPI Starting server\n+ Searching for package file structure\n+```\n+\n+Result (German):\n+\n+```console\n+$ fastapi run main.py\n+ FastAPI Starting server\n+ Searching for package file structure\n+```\n+\n+Source (English) - The code block is a console example containing 5 comments:\n+\n+\n+```console\n+// Go to the home directory\n+$ cd\n+// Create a directory for all your code projects\n+$ mkdir code\n+// Enter into that code directory\n+$ cd code\n+// Create a directory for this project\n+$ mkdir awesome-project\n+// Enter into that project directory\n+$ cd awesome-project\n+```\n+\n+Result (German):\n+\n+```console\n+// Gehe zum Home-Verzeichnis\n+$ cd\n+// Erstelle ein Verzeichnis für alle [NAME_REDACTED]\n+$ mkdir code\n+// Gehe in dieses Code-Verzeichnis\n+$ cd code\n+// Erstelle ein Verzeichnis für dieses Projekt\n+$ mkdir awesome-project\n+// Gehe in dieses Projektverzeichnis\n+$ cd awesome-project\n+```\n+\n+If there is an existing translation and its Mermaid diagram is in sync with the Mermaid diagram in the English source, except a few translated words, then use the Mermaid diagram of the existing translation. The human editor of the translation translated these words in the Mermaid diagram. Keep these translations, do not revert them back to the English source.\n+\n+Example:\n+\n+Source (English):\n+\n+```mermaid\n+flowchart LR\n+ subgraph global[global env]\n+ harry-1[harry v1]\n+ end\n+ subgraph stone-project[philosophers-stone project]\n+ stone(philosophers-stone) -->|requires| harry-1\n+ end\n+```\n+\n+Existing translation (German) - has three translations:\n+\n+```mermaid\n+flowchart LR\n+ subgraph global[globale Umgebung]\n+ harry-1[harry v1]\n+ end\n+ subgraph stone-project[philosophers-stone-Projekt]\n+ stone(philosophers-stone) -->|benötigt| harry-1\n+ end\n+```\n+\n+Result (German) - you change nothing:\n+\n+```mermaid\n+flowchart LR\n+ subgraph global[globale Umgebung]\n+ harry-1[harry v1]\n+ end\n+ subgraph stone-project[philosophers-stone-Projekt]\n+ stone(philosophers-stone) -->|benötigt| harry-1\n+ end\n+```\n+\n+### Special blocks\n+\n+There are special blocks of notes, tips and others that look like:\n+\n+/// note\n+Here goes a note\n+///\n+\n+To translate it, keep the same line and add the translation after a vertical bar.\n+\n+For example, if you were translating to Spanish, you would write:\n+\n+/// note | Nota\n+\n+Some examples in Spanish:\n+\n+Source (English):\n+\n+/// tip\n+\n+Result (Spanish):\n+\n+/// tip | Consejo\n+\n+Source (English):\n+\n+/// details | Preview\n+\n+Result (Spanish):\n+\n+/// details | Vista previa\n+\n+### Tab blocks\n+\n+There are special blocks surrounded by [NAME_REDACTED] (////). They mark text, which will be rendered as part of a tab in the final document. The scheme is:\n+\n+//// tab | {tab title}\n+{tab content, may span many lines}\n+////\n+\n+Keep everything before the vertical bar (|) as is, including the vertical bar. Translate the tab title. Translate the tab content, applying the rules you know. Keep the four block closing slashes as is.\n+\n+Examples:\n+\n+Source (English):\n+\n+//// tab | Python 3.8+ non-Annotated\n+Hello\n+////\n+\n+Result (German):\n+\n+//// tab | Python 3.8+ nicht annotiert\n+Hallo\n+////\n+\n+Source (English) - Here there is nothing to translate in the tab title:\n+\n+//// tab | Linux, macOS, [NAME_REDACTED]\n+Hello again\n+////\n+\n+Result (German):\n+\n+//// tab | Linux, macOS, [NAME_REDACTED]\n+Hallo wieder\n+////\n+\n+### Headings\n+\n+[NAME_REDACTED] heading in the English text (all levels) ends with a part inside curly brackets. This part denotes the hash of this heading, which is used in links to this heading. In translations, translate the heading, but do not translate this hash part, so that links do not break.\n+\n+Examples of how to translate a heading:\n+\n+Source (English):\n+\n+```\n+## Alternative API docs { #alternative-api-docs }\n+```\n+\n+Result (Spanish):\n+\n+```\n+## Documentación de la API alternativa { #alternative-api-docs }\n+```\n+\n+Source (English):\n+\n+```\n+### Example { #example }\n+```\n+\n+Result (German):\n+\n+```\n+### Beispiel { #example }\n+```\n+\n+### Links\n+\n+Use the following rules for links (apply both to Markdown-style links ([text](url)) and to HTML-style text tags):\n+\n+- For relative URLs, only translate the link text. Do not translate the URL or its parts.\n+\n+Example:\n+\n+Source (English):\n+\n+```\n+[One of the fastest Python frameworks available](#performance)\n+```\n+\n+Result (German):\n+\n+```\n+[Eines der schnellsten verfügbaren Python-Frameworks](#performance)\n+```\n+\n+- For absolute URLs which DO NOT start EXACTLY with https://fastapi.tiangolo.com, only translate the link text and leave the URL unchanged.\n+\n+Example:\n+\n+Source (English):\n+\n+```\n+SQLModel docs\n+```\n+\n+Result (German):\n+\n+```\n+SQLModel-Dokumentation\n+```\n+\n+- For absolute URLs which DO start EXACTLY with https://fastapi.tiangolo.com, only translate the link text and change the URL by [NAME_REDACTED] (https://fastapi.tiangolo.com/{language_code}[rest part of the url]).\n+\n+Example:\n+\n+Source (English):\n+\n+```\n+Documentation\n+```\n+\n+Result (Spanish):\n+\n+```\n+Documentación\n+```\n+\n+- Do not add language codes for URLs that point to static assets (e.g., images, CSS, JavaScript).\n+\n+Example:\n+\n+Source (English):\n+\n+```\n+Something\n+```\n+\n+Result (Spanish):\n+\n+```\n+Algo\n+```\n+\n+- For internal links, only translate link text.\n+\n+Example:\n+\n+Source (English):\n+\n+```\n+[[NAME_REDACTED]](help-fastapi.md#create-a-pull-request){.internal-link target=_blank}\n+```\n+\n+Result (German):\n+\n+```\n+[Pull Requests erzeugen](help-fastapi.md#create-a-pull-request){.internal-link target=_blank}\n+```\n+\n+- Do not translate anchor fragments in links (the part after `#`), as they must remain the same to work correctly.\n+\n+- If an existing translation has a link with an anchor fragment different to the anchor fragment in the English source, then this is an error. Fix this by [NAME_REDACTED] of the English source.\n+\n+Example:\n+\n+Source (English):\n+\n+```\n+[Body - [NAME_REDACTED]: Singular values in body](body-multiple-params.md#singular-values-in-body){.internal-link target=_blank}\n+```\n+\n+Existing wrong translation (German) - notice the wrongly translated anchor fragment:\n+\n+```\n+[Body - [NAME_REDACTED]: [NAME_REDACTED] im Body](body-multiple-params.md#einzelne-werte-im-body){.internal-link target=_blank}.\n+```\n+\n+Result (German) - you fix the anchor fragment:\n+\n+```\n+[Body - [NAME_REDACTED]: [NAME_REDACTED] im Body](body-multiple-params.md#singular-values-in-body){.internal-link target=_blank}.\n+```\n+\n+- Do not add anchor fragments at will, even if this makes sense. If the English source has no anchor, don't add one.\n+\n+Example:\n+\n+Source (English):\n+\n+```\n+Create a [virtual environment](../virtual-environments.md){.internal-link target=_blank}\n+```\n+\n+Wrong translation in German - Anchor added to the URL.\n+\n+```\n+Erstelle eine [virtuelle Umgebung](../virtual-environments.md#create-a-virtual-environment){.internal-link target=_blank}\n+```\n+\n+Good translation (German) - URL stays like in the English source.\n+\n+```\n+Erstelle eine [[NAME_REDACTED]](../virtual-environments.md){.internal-link target=_blank}\n+```\n+\n+### HTML abbr elements\n+\n+Translate HTML abbr elements (`text`) as follows:\n+\n+- If the text surrounded by [NAME_REDACTED] an abbreviation (the text may be surrounded by [NAME_REDACTED] markup or quotes, for example text or `text` or \"text\", ignore that further markup when deciding if the text is an abbreviation), and if the description (the text inside the title attribute) contains the full phrase for this abbreviation, then append a dash (-) to the full phrase, followed by [NAME_REDACTED] full phrase.\n+\n+Conversion scheme:\n+\n+Source (English):\n+\n+```\n+{abbreviation}\n+```\n+\n+Result:\n+\n+```\n+{abbreviation}\n+```\n+\n+Examples:\n+\n+Source (English):\n+\n+```\n+IoT\n+CPU\n+TL;DR:\n+```\n+\n+Result (German):\n+\n+```\n+IoT\n+CPU\n+TL;DR:\n+```\n+\n+- If the language to which you translate mostly uses the letters of the ASCII char set (for example Spanish, French, German, but not Russian, Chinese) and if the translation of the full phrase is identical to, or starts with the same letters as the original full phrase, then only give the translation of the full phrase.\n+\n+Conversion scheme:\n+\n+Source (English):\n+\n+```\n+{abbreviation}\n+```\n+\n+Result:\n+\n+```\n+{abbreviation}\n+```\n+\n+Examples:\n+\n+Source (English):\n+\n+```\n+JWT\n+Enum\n+ASGI\n+```\n+\n+Result (German):\n+\n+```\n+JWT\n+Enum\n+ASGI\n+```\n+\n+- If the description is not a full phrase for an abbreviation which the abbr element surrounds, but some other information, then just translate the description.\n+\n+Conversion scheme:\n+\n+Source (English):\n+\n+```\n+{text}\n+```\n+\n+Result:\n+\n+```\n+{translation of text}\n+```\n+\n+Examples:\n+\n+ Source (English):\n+\n+```\n+path\n+linter\n+parsing\n+0.95.0\n+at the time of writing this\n+```\n+\n+Result (German):\n+\n+```\n+Pfad\n+Linter\n+Parsen\n+0.95.0\n+zum Zeitpunkt als das hier geschrieben wurde\n+```\n+\n+- If the text surrounded by [NAME_REDACTED] an abbreviation and the description contains both the full phrase for that abbreviation, and other information, separated by a colon (`:`), then append a dash (`-`) and the translation of the full phrase to the original full phrase and translate the other information.\n+\n+Conversion scheme:\n+\n+Source (English):\n+\n+```\n+{abbreviation}\n+```\n+\n+Result:\n+\n+```\n+{abbreviation}\n+```\n+\n+Examples:\n+\n+Source (English):\n+\n+```\n+I/O\n+CDN\n+IDE\n+```\n+\n+Result (German):\n+\n+```\n+I/O\n+CDN\n+IDE\n+```\n+\n+- You can leave the original full phrase away, if the translated full phrase is identical or starts with the same letters as the original full phrase.\n+\n+Conversion scheme:\n+\n+Source (English):\n+\n+```\n+{abbreviation}\n+```\n+\n+Result:\n+\n+```\n+{abbreviation}\n+```\n+\n+Example:\n+\n+Source (English):\n+\n+```\n+ORM\n+```\n+\n+Result (German):\n+\n+```\n+ORM\n+```\n+\n+- If there is an existing translation, and it has ADDITIONAL abbr elements in a sentence, and these additional abbr elements do not exist in the related sentence in the English text, then KEEP those additional abbr elements in the translation. Do not remove them. Except when you remove the whole sentence from the translation, because the whole sentence was removed from the English text, then also remove the abbr element. The reasoning for this rule is, that such additional abbr elements are manually added by [NAME_REDACTED] the translation, in order to translate or explain an English word to the human readers of the translation. These additional abbr elements would not make sense in the English text, but they do make sense in the translation. So keep them in the translation, even though they are not part of the English text. This rule only applies to abbr elements.\n+\n+- Apply above rules also when there is an existing translation! Make sure that all title attributes in abbr elements get properly translated or updated, using the schemes given above. However, leave the ADDITIONAL abbr's described above alone. Do not change their formatting or content." }, { "filename": "scripts/translate.py", "status": "modified", "additions": 2, "deletions": 644, "changes": 646, "patch": "@@ -25,650 +25,8 @@\n \"contributing.md\",\n )\n \n-\n-general_prompt = \"\"\"\n-### About literal text in this prompt\n-\n-1) In the following instructions (after I say: `The above rules are in effect now`) the two characters `«` and `»` will be used to surround LITERAL TEXT, which is text or characters you shall interpret literally. The `«` and the `»` are not part of the literal text, they are the meta characters denoting it.\n-\n-2) Furthermore, text surrounded by `«««` and `»»»` is a BLOCK OF LITERAL TEXT which spans multiple lines. To get its content, dedent all lines of the block until the `«««` and `»»»` are at column zero, then remove the newline (`\\n`) after the `«««` and the newline before the `»»»`. The `«««` and the `»»»` are not part of the literal text block, they are the meta characters denoting it.\n-\n-3) If you see backticks or any other quotes inside literal text – inside `«` and `»` – or inside blocks of literal text – inside `«««` and `»»»` – then interpret them as literal characters, do NOT interpret them as meta characters.\n-\n-The above rules are in effect now.\n-\n-\n-### Definitions of terms used in this prompt\n-\n-\"backtick\"\n-\n- The character «`»\n- Unicode U+0060 (GRAVE ACCENT)\n-\n-\"single backtick\"\n-\n- A single backtick – «`»\n-\n-\"triple backticks\"\n-\n- Three backticks in a row – «```»\n-\n-\"neutral double quote\"\n-\n- The character «\"»\n- Unicode U+0022 (QUOTATION MARK)\n-\n-\"neutral single quote\"\n-\n- The character «'»\n- Unicode U+0027 (APOSTROPHE)\n-\n-\"English double typographic quotes\"\n-\n- The characters «“» and «”»\n- Unicode U+201C (LEFT DOUBLE QUOTATION MARK) and Unicode U+201D (RIGHT DOUBLE QUOTATION MARK)\n-\n-\"English single typographic quotes\"\n-\n- The characters «‘» and «’»\n- Unicode U+2018 (LEFT SINGLE QUOTATION MARK) and Unicode U+2019 (RIGHT SINGLE QUOTATION MARK)\n-\n-\"code snippet\"\n-\n- Also called \"inline code\". Text in a Markdown document which is surrounded by [NAME_REDACTED] A paragraph in a Markdown document can have a more than one code snippet.\n-\n- Example:\n-\n- «««\n- `i am a code snippet`\n- »»»\n-\n- Example:\n-\n- «««\n- `first code snippet` `second code snippet` `third code snippet`\n- »»»\n-\n-\"code block\"\n-\n- Text in a Markdown document which is surrounded by [NAME_REDACTED] lines.\n-\n- Example:\n-\n- «««\n- ```\n- Hello\n- World\n- ```\n- »»»\n-\n- Example:\n-\n- «««\n- ```python\n- print(\"hello World\")\n- ```\n- »»»\n-\n-\"HTML element\"\n-\n- a HTML opening tag – e.g. «

      » – and a HTML closing tag – e.g. «
      » – surrounding text or other HTML elements.\n-\n-\n-### Your task\n-\n-Translate an English text – the original content – to a target language.\n-\n-The original content is written in Markdown, write the translation in Markdown as well.\n-\n-The original content will be surrounded by [NAME_REDACTED] («%%%»). Do not include the triple percentage signs in the translation.\n-\n-\n-### Technical terms in English\n-\n-For technical terms in English that don't have a common translation term, use the original term in English.\n-\n-\n-### Content of code snippets\n-\n-Do not translate the content of code snippets, keep the original in English. For example, «`list`», «`dict`», keep them as is.\n-\n-\n-### Content of code blocks\n-\n-Do not translate the content of code blocks, except for comments in the language which the code block uses.\n-\n-Examples:\n-\n- Source (English) – The code block is a bash code example with one comment:\n-\n- «««\n- ```bash\n- # Print greeting\n- echo \"Hello, World!\"\n- ```\n- »»»\n-\n- Result (German):\n-\n- «««\n- ```bash\n- # Gruß ausgeben\n- echo \"Hello, World!\"\n- ```\n- »»»\n-\n- Source (English) – The code block is a console example containing HTML tags. No comments, so nothing to change here:\n-\n- «««\n- ```console\n- $ fastapi run main.py\n- FastAPI Starting server\n- Searching for package file structure\n- ```\n- »»»\n-\n- Result (German):\n-\n- «««\n- ```console\n- $ fastapi run main.py\n- FastAPI Starting server\n- Searching for package file structure\n- ```\n- »»»\n-\n- Source (English) – The code block is a console example containing 5 comments:\n-\n- «««\n- ```console\n- // Go to the home directory\n- $ cd\n- // Create a directory for all your code projects\n- $ mkdir code\n- // Enter into that code directory\n- $ cd code\n- // Create a directory for this project\n- $ mkdir awesome-project\n- // Enter into that project directory\n- $ cd awesome-project\n- ```\n- »»»\n-\n- Result (German):\n-\n- «««\n- ```console\n- // Gehe zum Home-Verzeichnis\n- $ cd\n- // Erstelle ein Verzeichnis für alle [NAME_REDACTED]\n- $ mkdir code\n- // Gehe in dieses Code-Verzeichnis\n- $ cd code\n- // Erstelle ein Verzeichnis für dieses Projekt\n- $ mkdir awesome-project\n- // Gehe in dieses Projektverzeichnis\n- $ cd awesome-project\n- ```\n- »»»\n-\n-If there is an existing translation and its Mermaid diagram is in sync with the Mermaid diagram in the English source, except a few translated words, then use the Mermaid diagram of the existing translation. The human editor of the translation translated these words in the Mermaid diagram. Keep these translations, do not revert them back to the English source.\n-\n-Example:\n-\n- Source (English):\n-\n- «««\n- ```mermaid\n- flowchart LR\n- subgraph global[global env]\n- harry-1[harry v1]\n- end\n- subgraph stone-project[philosophers-stone project]\n- stone(philosophers-stone) -->|requires| harry-1\n- end\n- ```\n- »»»\n-\n- Existing translation (German) – has three translations:\n-\n- «««\n- ```mermaid\n- flowchart LR\n- subgraph global[globale Umgebung]\n- harry-1[harry v1]\n- end\n- subgraph stone-project[philosophers-stone-Projekt]\n- stone(philosophers-stone) -->|benötigt| harry-1\n- end\n- ```\n- »»»\n-\n- Result (German) – you change nothing:\n-\n- «««\n- ```mermaid\n- flowchart LR\n- subgraph global[globale Umgebung]\n- harry-1[harry v1]\n- end\n- subgraph stone-project[philosophers-stone-Projekt]\n- stone(philosophers-stone) -->|benötigt| harry-1\n- end\n- ```\n- »»»\n-\n-\n-### Special blocks\n-\n-There are special blocks of notes, tips and others that look like:\n-\n- «««\n- /// note\n- »»»\n-\n-To translate it, keep the same line and add the translation after a vertical bar.\n-\n-For example, if you were translating to Spanish, you would write:\n-\n- «««\n- /// note | Nota\n- »»»\n-\n-Some examples in Spanish:\n-\n- Source:\n-\n- «««\n- /// tip\n- »»»\n-\n- Result:\n-\n- «««\n- /// tip | Consejo\n- »»»\n-\n- Source:\n-\n- «««\n- /// details | Preview\n- »»»\n-\n- Result:\n-\n- «««\n- /// details | Vista previa\n- »»»\n-\n-\n-### Tab blocks\n-\n-There are special blocks surrounded by [NAME_REDACTED] («////»). They mark text, which will be rendered as part of a tab in the final document. The scheme is:\n-\n- //// tab | {tab title}\n- {tab content, may span many lines}\n- ////\n-\n-Keep everything before the vertical bar («|») as is, including the vertical bar. Translate the tab title. Translate the tab content, applying the rules you know. Keep the four block closing slashes as is.\n-\n-Examples:\n-\n- Source (English):\n-\n- «««\n- //// tab | Python 3.8+ non-Annotated\n- Hello\n- ////\n- »»»\n-\n- Result (German):\n-\n- «««\n- //// tab | Python 3.8+ nicht annotiert\n- Hallo\n- ////\n- »»»\n-\n- Source (English) – Here there is nothing to translate in the tab title:\n-\n- «««\n- //// tab | Linux, macOS, [NAME_REDACTED]\n- Hello again\n- ////\n- »»»\n-\n- Result (German):\n-\n- «««\n- //// tab | Linux, macOS, [NAME_REDACTED]\n- Hallo wieder\n- ////\n- »»»\n-\n-\n-### Headings\n-\n-[NAME_REDACTED] heading in the English text (all levels) ends with a part inside curly brackets. This part denotes the hash of this heading, which is used in links to this heading. In translations, translate the heading, but do not translate this hash part, so that links do not break.\n-\n-Examples of how to translate a heading:\n-\n- Source (English):\n-\n- «««\n- ## Alternative API docs { #alternative-api-docs }\n- »»»\n-\n- Result (Spanish):\n-\n- «««\n- ## Documentación de la API alternativa { #alternative-api-docs }\n- »»»\n-\n- Source (English):\n-\n- «««\n- ### Example { #example }\n- »»»\n-\n- Result (German):\n-\n- «««\n- ### Beispiel { #example }\n- »»»\n-\n-\n-### Links\n-\n-Use the following rules for links (apply both to Markdown-style links ([text](url)) and to HTML-style tags):\n-\n-1) For relative URLs, only translate link text. Do not translate the URL or its parts\n-\n-Example:\n-\n- Source (English):\n-\n- «««\n- [One of the fastest Python frameworks available](#performance)\n- »»»\n-\n- Result (German):\n-\n- «««\n- [Eines der schnellsten verfügbaren Python-Frameworks](#performance)\n- »»»\n-\n-2) For absolute URLs which DO NOT start EXACTLY with «https://fastapi.tiangolo.com», only translate link text and leave the URL unchanged.\n-\n-Example:\n-\n- Source (English):\n-\n- «««\n- SQLModel docs\n- »»»\n-\n- Result (German):\n-\n- «««\n- SQLModel-Dokumentation\n- »»»\n-\n-3) For absolute URLs which DO start EXACTLY with «https://fastapi.tiangolo.com», only translate link text and change the URL by [NAME_REDACTED] («https://fastapi.tiangolo.com/{language_code}[rest part of the url]»).\n-\n-Example:\n-\n- Source (English):\n-\n- «««\n- Documentation\n- »»»\n-\n- Result (Spanish):\n-\n- «««\n- Documentación\n- »»»\n-\n-3.1) Do not add language codes for URLs that point to static assets (e.g., images, CSS, JavaScript).\n-\n-Example:\n-\n- Source (English):\n-\n- «««\n- Something\n- »»»\n-\n- Result (Spanish):\n-\n- «««\n- Algo\n- »»»\n-\n-4) For internal links, only translate link text.\n-\n-Example:\n-\n- Source (English):\n-\n- «««\n- [[NAME_REDACTED]](help-fastapi.md#create-a-pull-request){.internal-link target=_blank}\n- »»»\n-\n- Result (German):\n-\n- «««\n- [Pull Requests erzeugen](help-fastapi.md#create-a-pull-request){.internal-link target=_blank}\n- »»»\n-\n-5) Do not translate anchor fragments in links (the part after «#»), as they must remain the same to work correctly.\n-\n-5.1) If an existing translation has a link with an anchor fragment different to the anchor fragment in the English source, then this is an error. Fix this by [NAME_REDACTED] of the English source.\n-\n-Example:\n-\n- Source (English):\n-\n- «««\n- [Body - [NAME_REDACTED]: Singular values in body](body-multiple-params.md#singular-values-in-body){.internal-link target=_blank}\n- »»»\n-\n- Existing wrong translation (German) – notice the wrongly translated anchor fragment:\n-\n- «««\n- [Body – [NAME_REDACTED]: [NAME_REDACTED] im Body](body-multiple-params.md#einzelne-werte-im-body){.internal-link target=_blank}.\n- »»»\n-\n- Result (German) – you fix the anchor fragment:\n-\n- «««\n- [Body – [NAME_REDACTED]: [NAME_REDACTED] im Body](body-multiple-params.md#singular-values-in-body){.internal-link target=_blank}.\n- »»»\n-\n-5.2) Do not add anchor fragments at will, even if this makes sense. If the English source has no anchor, don't add one.\n-\n-Example:\n-\n- Source (English):\n-\n- «««\n- Create a [virtual environment](../virtual-environments.md){.internal-link target=_blank}\n- »»»\n-\n- Wrong translation (German) – Anchor added to the URL.\n-\n- «««\n- Erstelle eine [virtuelle Umgebung](../virtual-environments.md#create-a-virtual-environment){.internal-link target=_blank}\n- »»»\n-\n- Good translation (German) – URL stays like in the English source.\n-\n- «««\n- Erstelle eine [[NAME_REDACTED]](../virtual-environments.md){.internal-link target=_blank}\n- »»»\n-\n-\n-### HTML abbr elements\n-\n-Translate HTML abbr elements («text») as follows:\n-\n-1) If the text surrounded by [NAME_REDACTED] an abbreviation (the text may be surrounded by [NAME_REDACTED] markup or quotes, for example «text» or «`text`» or «\"text\"», ignore that further markup when deciding if the text is an abbreviation), and if the description (the text inside the title attribute) contains the full phrase for this abbreviation, then append a dash («–») to the full phrase, followed by [NAME_REDACTED] full phrase.\n-\n-Conversion scheme:\n-\n- Source (English):\n-\n- {abbreviation}\n-\n- Result:\n-\n- {abbreviation}\n-\n-Examples:\n-\n- Source (English):\n-\n- «««\n- IoT\n- CPU\n- TL;DR:\n- »»»\n-\n- Result (German):\n-\n- «««\n- IoT\n- CPU\n- TL;DR:\n- »»»\n-\n-1.1) If the language to which you translate mostly uses the letters of the ASCII char set (for example Spanish, French, German, but not Russian, Chinese) and if the translation of the full phrase is identical to, or starts with the same letters as the original full phrase, then only give the translation of the full phrase.\n-\n-Conversion scheme:\n-\n- Source (English):\n-\n- {abbreviation}\n-\n- Result:\n-\n- {abbreviation}\n-\n-Examples:\n-\n- Source (English):\n-\n- «««\n- JWT\n- Enum\n- ASGI\n- »»»\n-\n- Result (German):\n-\n- «««\n- JWT\n- Enum\n- ASGI\n- »»»\n-\n-2) If the description is not a full phrase for an abbreviation which the abbr element surrounds, but some other information, then just translate the description.\n-\n-Conversion scheme:\n-\n- Source (English):\n-\n- {text}\n-\n- Result:\n-\n- {translation of text}\n-\n-Examples:\n-\n- Source (English):\n-\n- «««\n- path\n- linter\n- parsing\n- 0.95.0\n- at the time of writing this\n- »»»\n-\n- Result (German):\n-\n- «««\n- Pfad\n- Linter\n- Parsen\n- 0.95.0\n- zum Zeitpunkt als das hier geschrieben wurde\n- »»»\n-\n-\n-3) If the text surrounded by [NAME_REDACTED] an abbreviation and the description contains both the full phrase for that abbreviation, and other information, separated by a colon («:»), then append a dash («–») and the translation of the full phrase to the original full phrase and translate the other information.\n-\n-Conversion scheme:\n-\n- Source (English):\n-\n- {abbreviation}\n-\n- Result:\n-\n- {abbreviation}\n-\n-Examples:\n-\n- Source (English):\n-\n- «««\n- I/O\n- CDN\n- IDE\n- »»»\n-\n- Result (German):\n-\n- «««\n- I/O\n- CDN\n- IDE\n- »»»\n-\n-3.1) Like in rule 2.1, you can leave the original full phrase away, if the translated full phrase is identical or starts with the same letters as the original full phrase.\n-\n-Conversion scheme:\n-\n- Source (English):\n-\n- {abbreviation}\n-\n- Result:\n-\n- {abbreviation}\n-\n-Example:\n-\n- Source (English):\n-\n- «««\n- ORM\n- »»»\n-\n- Result (German):\n-\n- «««\n- ORM\n- »»»\n-\n-4) If there is an existing translation, and it has ADDITIONAL abbr elements in a sentence, and these additional abbr elements do not exist in the related sentence in the English text, then KEEP those additional abbr elements in the translation. Do not remove them. Except when you remove the whole sentence from the translation, because the whole sentence was removed from the English text, then also remove the abbr element. The reasoning for this rule is, that such additional abbr elements are manually added by [NAME_REDACTED] the translation, in order to translate or explain an English word to the human readers of the translation. These additional abbr elements would not make sense in the English text, but they do make sense in the translation. So keep them in the translation, even though they are not part of the English text. This rule only applies to abbr elements.\n-\n-5) Apply above rules also when there is an existing translation! Make sure that all title attributes in abbr elements get properly translated or updated, using the schemes given above. However, leave the ADDITIONAL abbr's from rule 4 alone. Do not change their formatting or content.\n-\n-\"\"\"\n+general_prompt_path = Path(__file__).absolute().parent / \"llm-general-prompt.md\"\n+general_prompt = general_prompt_path.read_text(encoding=\"utf-8\")\n \n app = typer.Typer()" } ], "reviews": [ { "id": 3644605544, "user": "user_73ddcba46ff3", "state": "COMMENTED", "body": null, "submitted_at": "2026-01-09T16:10:39+00:00" } ], "review_comments": [ { "id": 2676767606, "user": "user_73ddcba46ff3", "body": "There appears to be a typo. The filename should be `general-llm-prompt.md`.", "path": "scripts/translate.py", "line": 28, "side": "RIGHT", "created_at": "2026-01-09T16:10:39+00:00" } ], "meta": { "languages": [ "md", "py" ], "touches_tests": false, "review_state_summary": { "COMMENTED": 1 }, "meaningful_comment_count": 1, "has_approval": false, "has_changes_requested": false, "total_review_comments": 1 } } { "_id": "7b0ff19991d7aa1f", "_schema_version": "1.0", "_cleaned_at": "2026-02-12T07:46:51.687264+00:00", "repo": "tiangolo/fastapi", "repo_url": "https://github.com/fastapi/fastapi", "license_name": "MIT License", "license_spdx": "MIT", "pr_number": 14618, "title": "🌐 Update LLM prompt instructions file for French", "body": "🌐 Update LLM prompt instructions file for [NAME_REDACTED] was generated by [NAME_REDACTED] the review in https://github.com/fastapi/fastapi/pull/14580 and asking the LLM to generate instructions to account for those cases.\n\n[USER_REDACTED], your input would be great here. 🙌", "author": "user_2a237e38e06b", "created_at": "2025-12-29T17:23:32+00:00", "merged_at": "2026-01-16T11:57:08+00:00", "base_branch": "master", "head_branch": "fr-llm-prompt", "additions": 79, "deletions": 75, "changed_files": 1, "files": [ { "filename": "docs/fr/llm-prompt.md", "status": "modified", "additions": 79, "deletions": 75, "changes": 154, "patch": "@@ -6,123 +6,127 @@ Language code: fr.\n \n ### Grammar to use when talking to the reader\n \n-Use the formal grammar (use «vous» instead of «tu»).\n+Use the formal grammar (use `vous` instead of `tu`).\n \n-### Quotes\n+Additionally, in instructional sentences, prefer the present tense for obligations:\n+\n+- Prefer `vous devez …` over `vous devrez …`, unless the English source explicitly refers to a future requirement.\n+\n+- When translating “make sure (that) … is …”, prefer the indicative after `vous assurer que` (e.g. `Vous devez vous assurer qu'il est …`) instead of the subjunctive (e.g. `qu'il soit …`).\n \n-1) Convert neutral double quotes («\"») and English double typographic quotes («“» and «”») to French guillemets (««» and «»»).\n+### Quotes\n \n-2) In the French docs, guillemets are written without extra spaces: use «texte», not « texte ».\n+- Convert neutral double quotes (`\"`) to French guillemets (`«` and `»`).\n \n-3) Do not convert quotes inside code blocks, inline code, paths, URLs, or anything wrapped in backticks.\n+- Do not convert quotes inside code blocks, inline code, paths, URLs, or anything wrapped in backticks.\n \n Examples:\n \n- Source (English):\n+Source (English):\n \n- «««\n- \"Hello world\"\n- “[NAME_REDACTED]”\n- \"He said: 'Hello'\"\n- \"The module is `__main__`\"\n- »»»\n+```\n+\"Hello world\"\n+“[NAME_REDACTED]”\n+\"He said: 'Hello'\"\n+\"The module is `__main__`\"\n+```\n \n- Result (French):\n+Result (French):\n \n- «««\n- «Hello world»\n- «[NAME_REDACTED]»\n- «He said: 'Hello'»\n- «The module is `__main__`»\n- »»»\n+```\n+\"Hello world\"\n+“[NAME_REDACTED]”\n+\"He said: 'Hello'\"\n+\"The module is `__main__`\"\n+```\n \n ### Ellipsis\n \n-1) Make sure there is a space between an ellipsis and a word following or preceding the ellipsis.\n+- Make sure there is a space between an ellipsis and a word following or preceding the ellipsis.\n \n Examples:\n \n- Source (English):\n+Source (English):\n \n- «««\n- ...as we intended.\n- ...this would work:\n- ...etc.\n- others...\n- More to come...\n- »»»\n+```\n+...as we intended.\n+...this would work:\n+...etc.\n+others...\n+More to come...\n+```\n \n- Result (French):\n+Result (French):\n \n- «««\n- ... comme prévu.\n- ... cela fonctionnerait :\n- ... etc.\n- D'autres ...\n- La suite ...\n- »»»\n+```\n+... comme prévu.\n+... cela fonctionnerait :\n+... etc.\n+D'autres ...\n+La suite ...\n+```\n \n-2) This does not apply in URLs, code blocks, and code snippets. Do not remove or add spaces there.\n+- This does not apply in URLs, code blocks, and code snippets. Do not remove or add spaces there.\n \n ### Headings\n \n-1) Prefer translating headings using the infinitive form (as is common in the existing French docs): «Créer…», «Utiliser…», «Ajouter…».\n-\n-2) For headings that are instructions written in imperative in English (e.g. “Go check …”), keep them in imperative in French, using the formal grammar (e.g. «Allez voir …»).\n+- Prefer translating headings using the infinitive form (as is common in the existing French docs): `Créer…`, `Utiliser…`, `Ajouter…`.\n \n-3) Keep heading punctuation as in the source. In particular, keep occurrences of literal « - » (space-hyphen-space) as « - » (the existing French docs use a hyphen here).\n+- For headings that are instructions written in imperative in English (e.g. `Go check …`), keep them in imperative in French, using the formal grammar (e.g. `Allez voir …`).\n \n ### French instructions about technical terms\n \n-Do not try to translate everything. In particular, keep common programming terms when that is the established usage in the French docs (e.g. «framework», «endpoint», «plug-in», «payload»). Use French where the existing docs already consistently use French (e.g. «requête», «réponse»).\n+Do not try to translate everything. In particular, keep common programming terms (e.g. `framework`, `endpoint`, `plug-in`, `payload`).\n \n Keep class names, function names, modules, file names, and CLI commands unchanged.\n \n ### List of English terms and their preferred French translations\n \n-Below is a list of English terms and their preferred French translations, separated by a colon («:»). Use these translations, do not use your own. If an existing translation does not use these terms, update it to use them.\n+Below is a list of English terms and their preferred French translations, separated by a colon (:). Use these translations, do not use your own. If an existing translation does not use these terms, update it to use them.\n+\n+- /// note | [NAME_REDACTED]»: /// note | Détails techniques\n+- /// note: /// note | Remarque\n+- /// tip: /// tip | Astuce\n+- /// warning: /// warning | Alertes\n+- /// check: /// check | Vérifications\n+- /// info: /// info\n \n-* «/// note | [NAME_REDACTED]»: «/// note | Détails techniques»\n-* «/// note»: «/// note | Remarque»\n-* «/// tip»: «/// tip | Astuce»\n-* «/// warning»: «/// warning | Attention»\n-* «/// check»: «/// check | vérifier»\n-* «/// info»: «/// info»\n+- the docs: les documents\n+- the documentation: la documentation\n \n-* «the docs»: «les documents»\n-* «the documentation»: «la documentation»\n+- Exclude from OpenAPI: Exclusion d'OpenAPI\n \n-* «framework»: «framework» (do not translate to «cadre»)\n-* «performance»: «performance»\n+- framework: framework (do not translate to cadre)\n+- performance: performance\n \n-* «type hints»: «annotations de type»\n-* «type annotations»: «annotations de type»\n+- type hints: annotations de type\n+- type annotations: annotations de type\n \n-* «autocomplete»: «autocomplétion»\n-* «autocompletion»: «autocomplétion»\n+- autocomplete: autocomplétion\n+- autocompletion: autocomplétion\n \n-* «the request» (what the client sends to the server): «la requête»\n-* «the response» (what the server sends back to the client): «la réponse»\n+- the request (what the client sends to the server): la requête\n+- the response (what the server sends back to the client): la réponse\n \n-* «the request body»: «le corps de la requête»\n-* «the response body»: «le corps de la réponse»\n+- the request body: le corps de la requête\n+- the response body: le corps de la réponse\n \n-* «path operation»: «opération de chemin»\n-* «path operations» (plural): «opérations de chemin»\n-* «path operation function»: «fonction de chemin»\n-* «path operation decorator»: «décorateur d'opération de chemin»\n+- path operation: chemin d'accès\n+- path operations (plural): chemins d'accès\n+- path operation function: fonction de chemin d'accès\n+- path operation decorator: décorateur de chemin d'accès\n \n-* «path parameter»: «paramètre de chemin»\n-* «query parameter»: «paramètre de requête»\n+- path parameter: paramètre de chemin\n+- query parameter: paramètre de requête\n \n-* «the `Request`»: «`Request`» (keep as code identifier)\n-* «the `Response`»: «`Response`» (keep as code identifier)\n+- the `Request`: `Request` (keep as code identifier)\n+- the `Response`: `Response` (keep as code identifier)\n \n-* «deployment»: «déploiement»\n-* «to upgrade»: «mettre à niveau»\n+- deployment: déploiement\n+- to upgrade: mettre à niveau\n \n-* «deprecated»: «déprécié»\n-* «to deprecate»: «déprécier»\n+- deprecated: déprécié\n+- to deprecate: déprécier\n \n-* «cheat sheet»: «aide-mémoire»\n-* «plug-in»: «plug-in»\n+- cheat sheet: aide-mémoire\n+- plug-in: plug-in" } ], "reviews": [ { "id": 3619329931, "user": "user_6d253a71ca6c", "state": "CHANGES_REQUESTED", "body": "Very good changes. Minimal edits to be applied", "submitted_at": "2025-12-30T21:27:42+00:00" }, { "id": 3647276654, "user": "user_2a237e38e06b", "state": "COMMENTED", "body": null, "submitted_at": "2026-01-10T23:44:02+00:00" }, { "id": 3647276770, "user": "user_2a237e38e06b", "state": "COMMENTED", "body": null, "submitted_at": "2026-01-10T23:44:32+00:00" }, { "id": 3651831728, "user": "user_6d253a71ca6c", "state": "APPROVED", "body": null, "submitted_at": "2026-01-12T17:13:12+00:00" } ], "review_comments": [ { "id": 2653918885, "user": "user_6d253a71ca6c", "body": "We specifically mention to not change the quotes inside code blocks. Why do we do it here?", "path": "docs/fr/llm-prompt.md", "line": 41, "side": "RIGHT", "created_at": "2025-12-30T21:20:10+00:00" }, { "id": 2653923722, "user": "user_6d253a71ca6c", "body": "I would recommend \"Alertes\" instead of \"Attention\".\n\"Alerte\" is a very broad term comparable to \"heads up\".\n\"Attention\", which by [NAME_REDACTED] \"warning\" carries a heavy meaning; closer to \"BE CAREFUL!!\" (Caps included)", "path": "docs/fr/llm-prompt.md", "line": null, "side": "RIGHT", "created_at": "2025-12-30T21:24:13+00:00" }, { "id": 2653924089, "user": "user_6d253a71ca6c", "body": "Vérifications*", "path": "docs/fr/llm-prompt.md", "line": null, "side": "RIGHT", "created_at": "2025-12-30T21:24:32+00:00" }, { "id": 2679072406, "user": "user_2a237e38e06b", "body": "Oh, you're totally right, thanks for catching it!", "path": "docs/fr/llm-prompt.md", "line": 41, "side": "RIGHT", "created_at": "2026-01-10T23:44:02+00:00" }, { "id": 2679072664, "user": "user_2a237e38e06b", "body": "Perfect, thanks!", "path": "docs/fr/llm-prompt.md", "line": null, "side": "RIGHT", "created_at": "2026-01-10T23:44:31+00:00" } ], "meta": { "languages": [ "md" ], "touches_tests": false, "review_state_summary": { "CHANGES_REQUESTED": 1, "COMMENTED": 2, "APPROVED": 1 }, "meaningful_comment_count": 5, "has_approval": true, "has_changes_requested": true, "total_review_comments": 5 } } { "_id": "c58a8c84ee634759", "_schema_version": "1.0", "_cleaned_at": "2026-02-12T07:46:51.687264+00:00", "repo": "tiangolo/fastapi", "repo_url": "https://github.com/fastapi/fastapi", "license_name": "MIT License", "license_spdx": "MIT", "pr_number": 14616, "title": "🐛 Fix using `Json[list[str]]` type (issue #10997)", "body": "Fixes Form() not working with Pydantic `Json[T]` types when T is a sequence type (list, set, tuple).\n\nCloses #10997\n\nWhen using `Form()` with `Json[list[str]]`, FastAPI incorrectly treated it as a sequence field and used `getlist()`, wrapping the JSON string in a list. This caused Pydantic to fail parsing with:\n```\nTypeError: JSON input should be string, bytes or bytearray\n```\n\n**Before fix:**\n```python\n# Client sends\ndata = {\"items\": '[\"abc\", \"def\"]'} # JSON string\n\n# FastAPI incorrectly does\nvalue = values.getlist(\"items\") # ['[\"abc\", \"def\"]'] ❌\n```\n\n**After fix:**\n```python\n# FastAPI correctly does\nvalue = values.get(\"items\") # '[\"abc\", \"def\"]' ✅\n```\n\nThis fix enables legitimate use cases like file uploads with JSON metadata:\n\n```python\n[USER_REDACTED].post(\"/upload\")\ndef upload(\n file: UploadFile,\n tags: Annotated[Json[list[str]], Form()]\n):\n return {\"file\": file.filename, \"tags\": tags}\n```\n\nPydantic v1 support for `Json[T]` with `Form()` is not included in this PR because `metadata` attribute does not exist in Pydantic v1's `FieldInfo`.\n\n## Related\n- Issue #10997", "author": "user_99e7134ee159", "created_at": "2025-12-28T10:25:02+00:00", "merged_at": "2026-02-05T18:41:43+00:00", "base_branch": "master", "head_branch": "fix/form-json-type-issue-10997", "additions": 73, "deletions": 2, "changed_files": 2, "files": [ { "filename": "fastapi/dependencies/utils.py", "status": "modified", "additions": 10, "deletions": 2, "changes": 12, "patch": "@@ -51,7 +51,7 @@\n from fastapi.security.oauth2 import SecurityScopes\n from fastapi.types import DependencyCacheKey\n from fastapi.utils import create_model_field, get_path_param_names\n-from pydantic import BaseModel\n+from pydantic import BaseModel, Json\n from pydantic.fields import FieldInfo\n from starlette.background import BackgroundTasks as StarletteBackgroundTasks\n from starlette.concurrency import run_in_threadpool\n@@ -726,11 +726,19 @@ def _validate_value_with_model_field(\n return v_, []\n \n \n+def _is_json_field(field: ModelField) -> bool:\n+ return any(type(item) is Json for item in field.field_info.metadata)\n+\n+\n def _get_multidict_value(\n field: ModelField, values: Mapping[str, Any], alias: Union[str, None] = None\n ) -> Any:\n alias = alias or get_validation_alias(field)\n- if is_sequence_field(field) and isinstance(values, (ImmutableMultiDict, Headers)):\n+ if (\n+ (not _is_json_field(field))\n+ and is_sequence_field(field)\n+ and isinstance(values, (ImmutableMultiDict, Headers))\n+ ):\n value = values.getlist(alias)\n else:\n value = values.get(alias, None)" }, { "filename": "tests/test_json_type.py", "status": "added", "additions": 63, "deletions": 0, "changes": 63, "patch": "@@ -0,0 +1,63 @@\n+import json\n+from typing import Annotated\n+\n+from fastapi import Cookie, FastAPI, Form, Header, Query\n+from fastapi.testclient import TestClient\n+from pydantic import Json\n+\n+app = FastAPI()\n+\n+\n+[USER_REDACTED].post(\"/form-json-list\")\n+def form_json_list(items: Annotated[Json[list[str]], Form()]) -> list[str]:\n+ return items\n+\n+\n+[USER_REDACTED].get(\"/query-json-list\")\n+def query_json_list(items: Annotated[Json[list[str]], Query()]) -> list[str]:\n+ return items\n+\n+\n+[USER_REDACTED].get(\"/header-json-list\")\n+def header_json_list(x_items: Annotated[Json[list[str]], Header()]) -> list[str]:\n+ return x_items\n+\n+\n+[USER_REDACTED].get(\"/cookie-json-list\")\n+def cookie_json_list(items: Annotated[Json[list[str]], Cookie()]) -> list[str]:\n+ return items\n+\n+\n+client = TestClient(app)\n+\n+\n+def test_form_json_list():\n+ response = client.post(\n+ \"/form-json-list\", data={\"items\": json.dumps([\"abc\", \"def\"])}\n+ )\n+ assert response.status_code == 200, response.text\n+ assert response.json() == [\"abc\", \"def\"]\n+\n+\n+def test_query_json_list():\n+ response = client.get(\n+ \"/query-json-list\", params={\"items\": json.dumps([\"abc\", \"def\"])}\n+ )\n+ assert response.status_code == 200, response.text\n+ assert response.json() == [\"abc\", \"def\"]\n+\n+\n+def test_header_json_list():\n+ response = client.get(\n+ \"/header-json-list\", headers={\"x-items\": json.dumps([\"abc\", \"def\"])}\n+ )\n+ assert response.status_code == 200, response.text\n+ assert response.json() == [\"abc\", \"def\"]\n+\n+\n+def test_cookie_json_list():\n+ client.cookies.set(\"items\", json.dumps([\"abc\", \"def\"]))\n+ response = client.get(\"/cookie-json-list\")\n+ assert response.status_code == 200, response.text\n+ assert response.json() == [\"abc\", \"def\"]\n+ client.cookies.clear()" } ], "reviews": [ { "id": 3638035917, "user": "user_29e85f9a8e75", "state": "CHANGES_REQUESTED", "body": "[USER_REDACTED], thanks for your interest!\n\nThe idea looks good to me.\nPlease, take a look at my suggestions.\n\n---\n\n**UPD:** I think this will fix `Json[list[str]]` not only for `Form` parameters, but for other types of parameters (`Query`, `Header`, etc..) as well.\n[USER_REDACTED], could you please check it and add tests for other types of parameters?", "submitted_at": "2026-01-08T07:23:10+00:00" }, { "id": 3639656588, "user": "user_29e85f9a8e75", "state": "COMMENTED", "body": null, "submitted_at": "2026-01-08T14:22:22+00:00" }, { "id": 3639771449, "user": "user_99e7134ee159", "state": "COMMENTED", "body": null, "submitted_at": "2026-01-08T14:49:22+00:00" }, { "id": 3639846175, "user": "user_29e85f9a8e75", "state": "COMMENTED", "body": null, "submitted_at": "2026-01-08T15:05:34+00:00" }, { "id": 3639889287, "user": "user_99e7134ee159", "state": "COMMENTED", "body": null, "submitted_at": "2026-01-08T15:14:49+00:00" }, { "id": 3639899929, "user": "user_99e7134ee159", "state": "COMMENTED", "body": null, "submitted_at": "2026-01-08T15:17:06+00:00" }, { "id": 3639936016, "user": "user_29e85f9a8e75", "state": "COMMENTED", "body": null, "submitted_at": "2026-01-08T15:25:42+00:00" }, { "id": 3640017465, "user": "user_99e7134ee159", "state": "COMMENTED", "body": null, "submitted_at": "2026-01-08T15:40:50+00:00" }, { "id": 3640042450, "user": "user_29e85f9a8e75", "state": "COMMENTED", "body": null, "submitted_at": "2026-01-08T15:46:09+00:00" }, { "id": 3640057546, "user": "user_29e85f9a8e75", "state": "APPROVED", "body": "LGTM!\n\nCurrently (on `master` branch) tests for `Query`, `Form` and `Header` fail. Test for `Cookie` passes, but I think we should keep it for consistency.\n\n[USER_REDACTED], thank you for quick updates!", "submitted_at": "2026-01-08T15:49:38+00:00" }, { "id": 3758754042, "user": "user_2a237e38e06b", "state": "APPROVED", "body": "Great job! Thank you! 🙌 \n\nI was convinced of not supporting this (reading the issue), but this implementation is simple and clean enough that I think it makes sense to have it. Thanks! 🚀 \n\nThis will be available in FastAPI 0.128.2, released in the next few hours. 🎉", "submitted_at": "2026-02-05T18:38:14+00:00" } ], "review_comments": [ { "id": 2671161458, "user": "user_29e85f9a8e75", "body": "```suggestion\n return any(isinstance(item, Json) for item in field.field_info.metadata)\n```\n\nFastAPI dropped the support of Pydantic V1 recently.\nWe can now simplify this.\nAlso, we should use `isinstance` to check type", "path": "fastapi/dependencies/utils.py", "line": null, "side": "RIGHT", "created_at": "2026-01-08T07:17:43+00:00" }, { "id": 2671164364, "user": "user_29e85f9a8e75", "body": "```suggestion\n if (\n (not _is_json_field(field))\n and is_sequence_field(field)\n and isinstance(values, (ImmutableMultiDict, Headers))\n ):\n```", "path": "fastapi/dependencies/utils.py", "line": null, "side": "RIGHT", "created_at": "2026-01-08T07:18:28+00:00" }, { "id": 2671173246, "user": "user_29e85f9a8e75", "body": "```suggestion\n```\nI think we don't need this test", "path": "tests/test_form_json_type.py", "line": null, "side": "RIGHT", "created_at": "2026-01-08T07:21:15+00:00" }, { "id": 2671174993, "user": "user_29e85f9a8e75", "body": "```suggestion\n```\nI think we don't need this", "path": "tests/test_form_json_type.py", "line": null, "side": "RIGHT", "created_at": "2026-01-08T07:21:45+00:00" }, { "id": 2672557835, "user": "user_29e85f9a8e75", "body": "Could you please explain why you used `dict` here, not `list`?\nWith `dict` this test passes on `master` branch.", "path": "tests/test_form_json_type.py", "line": null, "side": "RIGHT", "created_at": "2026-01-08T14:22:22+00:00" }, { "id": 2672658182, "user": "user_99e7134ee159", "body": "You're right! After investigating, I found that Cookie was never affected by [NAME_REDACTED], they skip `getlist()` path.\nI've removed the Cookie test. The three remaining tests (Form/Query/Header) properly cover the bug fix.", "path": "tests/test_form_json_type.py", "line": null, "side": "RIGHT", "created_at": "2026-01-08T14:49:22+00:00" }, { "id": 2672719941, "user": "user_29e85f9a8e75", "body": "I mean for Query you use `Json[list[str]]`, but for Cookie `Json[dict[str, str]]` (`list` vs `dict`).\n\nWhat if you declare cookie endpoint as:\n\n```py\n[USER_REDACTED].get(\"/cookie-json-list\")\ndef cookie_json_list(\n items: Annotated[Json[list[str]], Cookie()],\n) -> list[str]:\n return items\n```\n?\n\nI think this should also fail on `master` branch and be fixed by [NAME_REDACTED]", "path": "tests/test_form_json_type.py", "line": null, "side": "RIGHT", "created_at": "2026-01-08T15:05:34+00:00" }, { "id": 2672758198, "user": "user_99e7134ee159", "body": "I thought the same, but when I tested on master, it passed 😶\n```bash\n==================================================================== test session starts ====================================================================\n... \ntests/test_form_json_type.py::test_form_json_list FAILED [ 25%]\ntests/test_form_json_type.py::test_query_json_list FAILED [ 50%]\ntests/test_form_json_type.py::test_header_json_list FAILED [ 75%]\ntests/test_form_json_type.py::test_cookie_json_list PASSED [100%]\n```\nLooks like cookies don't go through the getlist() path.\ncookie values are plain dict, not ImmutableMultiDict or Headers, so they skip that.", "path": "tests/test_form_json_type.py", "line": null, "side": "RIGHT", "created_at": "2026-01-08T15:14:49+00:00" }, { "id": 2672766740, "user": "user_99e7134ee159", "body": "u can check by [NAME_REDACTED]\n```python\nimport json\nfrom typing import Annotated\n\nfrom fastapi import Cookie, FastAPI\nfrom fastapi.testclient import TestClient\nfrom pydantic import Json\n\napp = FastAPI()\n\n[USER_REDACTED].get(\"/cookie-json-list\")\ndef cookie_json_list(\n session: Annotated[Json[list[str]], Cookie()],\n) -> list[str]:\n return session\n\nclient = TestClient(app)\n\ndef test_cookie_json_list():\n client.cookies.set(\"session\", json.dumps([\"user\", \"test1\", \"role\", \"admin\"]))\n response = client.get(\"/cookie-json-list\")\n assert response.status_code == 200, response.text\n assert response.json() == [\"user\", \"test1\", \"role\", \"admin\"]\n```", "path": "tests/test_form_json_type.py", "line": null, "side": "RIGHT", "created_at": "2026-01-08T15:17:06+00:00" }, { "id": 2672799428, "user": "user_29e85f9a8e75", "body": "Interesting... Thanks for clarifying this!\n\nI would still add this test with `Annotated[Json[list[str]], Cookie()]` for consistency.\nAnd, we need to update the name of test module to reflect that it's not only for `Form`", "path": "tests/test_form_json_type.py", "line": null, "side": "RIGHT", "created_at": "2026-01-08T15:25:42+00:00" }, { "id": 2672863403, "user": "user_99e7134ee159", "body": "Done! Added Cookie test consistent with other types and renamed the file to `test_json_type.py`.", "path": "tests/test_form_json_type.py", "line": null, "side": "RIGHT", "created_at": "2026-01-08T15:40:50+00:00" }, { "id": 2672884591, "user": "user_29e85f9a8e75", "body": "Great! Thank you!", "path": "tests/test_form_json_type.py", "line": null, "side": "RIGHT", "created_at": "2026-01-08T15:46:09+00:00" } ], "meta": { "languages": [ "py" ], "touches_tests": true, "review_state_summary": { "CHANGES_REQUESTED": 1, "COMMENTED": 8, "APPROVED": 2 }, "meaningful_comment_count": 12, "has_approval": true, "has_changes_requested": true, "total_review_comments": 12 } } { "_id": "5b36cc0488557902", "_schema_version": "1.0", "_cleaned_at": "2026-02-12T07:46:51.687264+00:00", "repo": "tiangolo/fastapi", "repo_url": "https://github.com/fastapi/fastapi", "license_name": "MIT License", "license_spdx": "MIT", "pr_number": 14562, "title": "📝 Update more docs with Python 3.8 to Python 3.9", "body": "📝 Update more docs with Python 3.8 to Python 3.9", "author": "user_2a237e38e06b", "created_at": "2025-12-17T20:10:22+00:00", "merged_at": "2025-12-17T20:16:55+00:00", "base_branch": "drop-python3.8-support", "head_branch": "no-py38", "additions": 6, "deletions": 6, "changed_files": 6, "files": [ { "filename": "docs/de/docs/tutorial/dependencies/classes-as-dependencies.md", "status": "modified", "additions": 1, "deletions": 1, "changes": 2, "patch": "@@ -257,7 +257,7 @@ commons: Annotated[CommonQueryParams, Depends()]\n \n ////\n \n-//// tab | Python 3.8 nicht annotiert\n+//// tab | Python 3.9+ nicht annotiert\n \n /// tip | Tipp" }, { "filename": "docs/en/docs/management-tasks.md", "status": "modified", "additions": 1, "deletions": 1, "changes": 2, "patch": "@@ -239,7 +239,7 @@ A PR should have a specific use case that it is solving.\n * If the PR is for a feature, it should have docs.\n * Unless it's a feature we want to discourage, like support for a corner case that we don't want users to use.\n * The docs should include a source example file, not write Python directly in Markdown.\n-* If the source example(s) file can have different syntax for Python 3.8, 3.9, 3.10, there should be different versions of the file, and they should be shown in tabs in the docs.\n+* If the source example(s) file can have different syntax for different Python versions, there should be different versions of the file, and they should be shown in tabs in the docs.\n * There should be tests testing the source example.\n * Before the PR is applied, the new tests should fail.\n * After applying the PR, the new tests should pass." }, { "filename": "docs/es/docs/tutorial/dependencies/classes-as-dependencies.md", "status": "modified", "additions": 1, "deletions": 1, "changes": 2, "patch": "@@ -257,7 +257,7 @@ commons: Annotated[CommonQueryParams, Depends()]\n \n ////\n \n-//// tab | Python 3.8 sin `Annotated`\n+//// tab | Python 3.9+ sin `Annotated`\n \n /// tip | Consejo" }, { "filename": "docs/pt/docs/tutorial/dependencies/classes-as-dependencies.md", "status": "modified", "additions": 1, "deletions": 1, "changes": 2, "patch": "@@ -257,7 +257,7 @@ commons: Annotated[CommonQueryParams, Depends()]\n \n ////\n \n-//// tab | Python 3.8 non-Annotated\n+//// tab | Python 3.9+ non-Annotated\n \n /// tip | Dica" }, { "filename": "docs/pt/llm-prompt.md", "status": "modified", "additions": 1, "deletions": 1, "changes": 2, "patch": "@@ -47,7 +47,7 @@ For the next terms, use the following translations:\n * list (as in Python list): list\n * [NAME_REDACTED]: Aprendizado de Máquina\n * media type: media type (do not translate to \"tipo de mídia\")\n-* non-Annotated: non-Annotated (do not translate non-Annotated when it comes after a Python version.e.g., “Python 3.8+ non-Annotated”)\n+* non-Annotated: non-Annotated (do not translate non-Annotated when it comes after a Python version.e.g., “Python 3.10+ non-Annotated”)\n * operation IDs: IDs de operação\n * path (as in URL path): path\n * path operation: operação de rota" }, { "filename": "docs/ru/docs/tutorial/dependencies/classes-as-dependencies.md", "status": "modified", "additions": 1, "deletions": 1, "changes": 2, "patch": "@@ -257,7 +257,7 @@ commons: Annotated[CommonQueryParams, Depends()]\n \n ////\n \n-//// tab | Python 3.8 non-Annotated\n+//// tab | Python 3.9+ non-Annotated\n \n /// tip | Подсказка" } ], "reviews": [ { "id": 3589473436, "user": "user_bcf018ef4ea6", "state": "APPROVED", "body": null, "submitted_at": "2025-12-17T20:14:44+00:00" }, { "id": 3589472358, "user": "user_db4405377801", "state": "APPROVED", "body": null, "submitted_at": "2025-12-17T20:14:59+00:00" }, { "id": 3589479487, "user": "user_2a237e38e06b", "state": "COMMENTED", "body": null, "submitted_at": "2025-12-17T20:16:37+00:00" }, { "id": 3589493896, "user": "user_db4405377801", "state": "COMMENTED", "body": null, "submitted_at": "2025-12-17T20:21:13+00:00" } ], "review_comments": [ { "id": 2628497014, "user": "user_db4405377801", "body": "Why not 3.9+ here ?", "path": "docs/pt/llm-prompt.md", "line": 50, "side": "RIGHT", "created_at": "2025-12-17T20:14:22+00:00" }, { "id": 2628503455, "user": "user_2a237e38e06b", "body": "This is just an example of what to translate or what not to, the Python version doesn't have much importance here. :nerd_face: \n\nI'm updating it just so that it doesn't show up in search looking for `Python 3.8`.", "path": "docs/pt/llm-prompt.md", "line": 50, "side": "RIGHT", "created_at": "2025-12-17T20:16:37+00:00" }, { "id": 2628515315, "user": "user_db4405377801", "body": "Thank you for the clarification", "path": "docs/pt/llm-prompt.md", "line": 50, "side": "RIGHT", "created_at": "2025-12-17T20:21:13+00:00" } ], "meta": { "languages": [ "md" ], "touches_tests": false, "review_state_summary": { "APPROVED": 2, "COMMENTED": 2 }, "meaningful_comment_count": 3, "has_approval": true, "has_changes_requested": false, "total_review_comments": 3 } } { "_id": "5f2df06b6a3443c2", "_schema_version": "1.0", "_cleaned_at": "2026-02-12T07:46:51.702905+00:00", "repo": "tiangolo/fastapi", "repo_url": "https://github.com/fastapi/fastapi", "license_name": "MIT License", "license_spdx": "MIT", "pr_number": 14550, "title": "🔧 Add LLM prompt file for [NAME_REDACTED], generated from the existing translations", "body": "🔧 Add LLM prompt file for [NAME_REDACTED], generated from the existing translations\n\n---\n\nThis will be used to update existing translations and generate new ones.", "author": "user_2a237e38e06b", "created_at": "2025-12-16T23:56:32+00:00", "merged_at": "2025-12-27T18:49:46+00:00", "base_branch": "master", "head_branch": "llm-zh-hant", "additions": 54, "deletions": 0, "changed_files": 1, "files": [ { "filename": "docs/zh-hant/llm-prompt.md", "status": "added", "additions": 54, "deletions": 0, "changes": 54, "patch": "@@ -0,0 +1,54 @@\n+### Target language\n+\n+Translate to [NAME_REDACTED] (繁體中文).\n+\n+Language code: zh-hant.\n+\n+### Grammar and tone\n+\n+1) Use clear, concise technical [NAME_REDACTED] consistent with existing docs.\n+2) Address the reader naturally (commonly using “你/你的”).\n+\n+### Headings\n+\n+1) Follow existing [NAME_REDACTED] heading style (short and descriptive).\n+2) Do not add trailing punctuation to headings.\n+\n+### Quotes and punctuation\n+\n+1) Keep punctuation style consistent with existing [NAME_REDACTED] docs (they often mix English terms like “FastAPI” with Chinese text).\n+2) Never change punctuation inside inline code, code blocks, URLs, or file paths.\n+3) For more details, please follow the [[NAME_REDACTED]](https://github.com/[USER_REDACTED]noid/chinese-copywriting-guidelines).\n+\n+### Ellipsis\n+\n+1) Keep ellipsis style consistent within each document, prefer `...` over `……`.\n+2) Never change ellipsis in code, URLs, or CLI examples.\n+\n+### Preferred translations / glossary\n+\n+1. Should avoid using simplified Chinese characters and terms. Always examine if the translation can be easily comprehended by [NAME_REDACTED]\n+2. For some Python-specific terms like \"pickle\", \"list\", \"dict\" etc, we don't have to translate them.\n+3. Use the following preferred translations when they apply in documentation prose:\n+\n+- request (HTTP): 請求\n+- response (HTTP): 回應\n+- path operation: 路徑操作\n+- path operation function: 路徑操作函式\n+\n+The translation can optionally include the original English text only in the first occurrence of each page (e.g. \"路徑操作 (path operation)\") if the translation is hard to be comprehended by [NAME_REDACTED] readers.\n+\n+### `///` admonitions\n+\n+1) Keep the admonition keyword in English (do not translate `note`, `tip`, etc.).\n+2) [NAME_REDACTED] docs currently omit titles in `///` blocks; that is OK.\n+3) If a generic title is present, prefer these canonical titles:\n+\n+- `/// note | 注意`\n+\n+Notes:\n+\n+- `details` blocks exist; keep `/// details` as-is and translate only the title after `|`.\n+- Example canonical titles used in existing docs:\n+ - `/// details | 上述指令的含義`\n+ - `/// details | 關於 `requirements.txt``" } ], "reviews": [ { "id": 3596730476, "user": "user_0845d5d45a7e", "state": "COMMENTED", "body": "add some common rules that i frequently use. \nI believe it's enough as a starter.", "submitted_at": "2025-12-19T04:24:32+00:00" }, { "id": 3601201862, "user": "user_2a237e38e06b", "state": "COMMENTED", "body": null, "submitted_at": "2025-12-20T17:40:40+00:00" }, { "id": 3601209913, "user": "user_0845d5d45a7e", "state": "APPROVED", "body": null, "submitted_at": "2025-12-20T17:59:57+00:00" } ], "review_comments": [ { "id": 2633547309, "user": "user_0845d5d45a7e", "body": "```suggestion\n### Preferred translations / glossary\n\n1. Should avoid using simplified Chinese characters and terms. Always examine if the translation can be easily comprehended by [NAME_REDACTED]\n2. For some Python-specific terms like \"pickle\", \"list\", \"dict\" etc, we don't have to translate them.\n3. Use the following preferred translations when they apply in documentation prose:\n```", "path": "docs/zh-hant/llm-prompt.md", "line": null, "side": "RIGHT", "created_at": "2025-12-19T04:14:13+00:00" }, { "id": 2633553737, "user": "user_0845d5d45a7e", "body": "```suggestion\n3) For more details, please follow the [[NAME_REDACTED]](https://github.com/[USER_REDACTED]noid/chinese-copywriting-guidelines).\n\n```", "path": "docs/zh-hant/llm-prompt.md", "line": 22, "side": "RIGHT", "created_at": "2025-12-19T04:17:25+00:00" }, { "id": 2633557968, "user": "user_0845d5d45a7e", "body": "```suggestion\n- path operation function: 路徑操作函式\n\nThe translation can optinoally includes the original English text only in the first occurence of each page (e.g. \"路徑操作 (path operation)\") if the translation is hard to be comprehended by [NAME_REDACTED] readers.\n```", "path": "docs/zh-hant/llm-prompt.md", "line": 37, "side": "RIGHT", "created_at": "2025-12-19T04:20:54+00:00" }, { "id": 2637240603, "user": "user_2a237e38e06b", "body": "Perfect, I added this as well :raised_hands:", "path": "docs/zh-hant/llm-prompt.md", "line": 37, "side": "RIGHT", "created_at": "2025-12-20T17:40:39+00:00" } ], "meta": { "languages": [ "md" ], "touches_tests": false, "review_state_summary": { "COMMENTED": 2, "APPROVED": 1 }, "meaningful_comment_count": 4, "has_approval": true, "has_changes_requested": false, "total_review_comments": 4 } } { "_id": "ed989702b2e0df53", "_schema_version": "1.0", "_cleaned_at": "2026-02-12T07:46:51.702905+00:00", "repo": "tiangolo/fastapi", "repo_url": "https://github.com/fastapi/fastapi", "license_name": "MIT License", "license_spdx": "MIT", "pr_number": 14549, "title": "🔧 Add LLM prompt file for [NAME_REDACTED], generated from the existing translations", "body": "🔧 Add LLM prompt file for [NAME_REDACTED], generated from the existing translations\n\n---\n\nThis will be used to update existing translations and generate new ones.", "author": "user_2a237e38e06b", "created_at": "2025-12-16T23:55:23+00:00", "merged_at": "2025-12-27T18:49:08+00:00", "base_branch": "master", "head_branch": "llm-zh", "additions": 46, "deletions": 0, "changed_files": 1, "files": [ { "filename": "docs/zh/llm-prompt.md", "status": "added", "additions": 46, "deletions": 0, "changes": 46, "patch": "@@ -0,0 +1,46 @@\n+### Target language\n+\n+Translate to [NAME_REDACTED] (简体中文).\n+\n+Language code: zh.\n+\n+### Grammar and tone\n+\n+1) Use clear, concise technical Chinese consistent with existing docs.\n+2) Address the reader naturally (commonly using “你/你的”).\n+\n+### Headings\n+\n+1) Follow existing [NAME_REDACTED] heading style (short and descriptive).\n+2) Do not add trailing punctuation to headings.\n+3) If a heading contains only the name of a FastAPI feature, do not translate it.\n+\n+### Quotes and punctuation\n+\n+1) Keep punctuation style consistent with existing [NAME_REDACTED] docs (they often mix English terms like “FastAPI” with Chinese text).\n+2) Never change punctuation inside inline code, code blocks, URLs, or file paths.\n+\n+### Ellipsis\n+\n+1) Keep ellipsis style consistent within each document, prefer `...` over `……`.\n+2) Never change ellipsis in code, URLs, or CLI examples.\n+\n+### Preferred translations / glossary\n+\n+Use the following preferred translations when they apply in documentation prose:\n+\n+- request (HTTP): 请求\n+- response (HTTP): 响应\n+- path operation: 路径操作\n+- path operation function: 路径操作函数\n+\n+### `///` admonitions\n+\n+1) Keep the admonition keyword in English (do not translate `note`, `tip`, etc.).\n+2) If a title is present, prefer these canonical titles:\n+\n+- `/// tip | 提示`\n+- `/// note | 注意`\n+- `/// warning | 警告`\n+- `/// info | 信息`\n+- `/// danger | 危险`" } ], "reviews": [ { "id": 3592420140, "user": "user_914a49b54a4c", "state": "APPROVED", "body": null, "submitted_at": "2025-12-18T11:39:53+00:00" }, { "id": 3595969067, "user": "user_6fcb07a75ce9", "state": "APPROVED", "body": "LGTM", "submitted_at": "2025-12-19T01:01:25+00:00" }, { "id": 3597690616, "user": "user_d7f5981f1dc1", "state": "COMMENTED", "body": null, "submitted_at": "2025-12-19T09:13:02+00:00" }, { "id": 3598509905, "user": "user_2a237e38e06b", "state": "COMMENTED", "body": null, "submitted_at": "2025-12-19T12:51:08+00:00" }, { "id": 3600883810, "user": "user_63ed12e5198d", "state": "COMMENTED", "body": null, "submitted_at": "2025-12-20T08:39:06+00:00" }, { "id": 3601168868, "user": "user_d7f5981f1dc1", "state": "COMMENTED", "body": null, "submitted_at": "2025-12-20T16:11:51+00:00" }, { "id": 3601200086, "user": "user_2a237e38e06b", "state": "COMMENTED", "body": null, "submitted_at": "2025-12-20T17:36:37+00:00" }, { "id": 3601552990, "user": "user_63ed12e5198d", "state": "APPROVED", "body": null, "submitted_at": "2025-12-21T06:49:22+00:00" }, { "id": 3607886403, "user": "user_6d253a71ca6c", "state": "APPROVED", "body": null, "submitted_at": "2025-12-23T12:38:46+00:00" }, { "id": 3609762953, "user": "user_d7f5981f1dc1", "state": "APPROVED", "body": null, "submitted_at": "2025-12-24T02:31:29+00:00" } ], "review_comments": [ { "id": 2634312788, "user": "user_d7f5981f1dc1", "body": "When translating English technical documentation into Chinese, LLMs often translate headings that consist entirely of program keywords, class names, function names, and similar identifiers into Chinese. Given the popularity of FastAPI and the fact that current LLM models already have knowledge of it, one can consider explicitly instructing the model, for example:\n\n```suggestion\n3) If a heading contains only the name of a FastAPI feature, do not translate it.\n\n```", "path": "docs/zh/llm-prompt.md", "line": 17, "side": "RIGHT", "created_at": "2025-12-19T09:13:02+00:00" }, { "id": 2635005691, "user": "user_2a237e38e06b", "body": "Awesome, thanks for the feedback! I just added it.", "path": "docs/zh/llm-prompt.md", "line": 17, "side": "RIGHT", "created_at": "2025-12-19T12:51:08+00:00" }, { "id": 2636940590, "user": "user_63ed12e5198d", "body": "I think it's:\n```\n- `/// note | 注`\n```", "path": "docs/zh/llm-prompt.md", "line": null, "side": "RIGHT", "created_at": "2025-12-20T08:39:05+00:00" }, { "id": 2637196088, "user": "user_d7f5981f1dc1", "body": "How About:\n\n```\n- `/// note | 注意`\n```\n\nAlthough this is not its full literal meaning, it works in most contexts and reads more elegantly. \n虽然字面意思并不止如此,但这在大多数语境下成立并且更加优雅。", "path": "docs/zh/llm-prompt.md", "line": null, "side": "RIGHT", "created_at": "2025-12-20T16:11:50+00:00" }, { "id": 2637238815, "user": "user_2a237e38e06b", "body": "Thank you! I updated it this way. :raised_hands:", "path": "docs/zh/llm-prompt.md", "line": null, "side": "RIGHT", "created_at": "2025-12-20T17:36:37+00:00" } ], "meta": { "languages": [ "md" ], "touches_tests": false, "review_state_summary": { "APPROVED": 5, "COMMENTED": 5 }, "meaningful_comment_count": 5, "has_approval": true, "has_changes_requested": false, "total_review_comments": 5 } } { "_id": "040ca2d40a411936", "_schema_version": "1.0", "_cleaned_at": "2026-02-12T07:46:51.702905+00:00", "repo": "tiangolo/fastapi", "repo_url": "https://github.com/fastapi/fastapi", "license_name": "MIT License", "license_spdx": "MIT", "pr_number": 14547, "title": "🔧 Add LLM prompt file for Turkish, generated from the existing translations", "body": "🔧 Add LLM prompt file for Turkish, generated from the existing translations\n\n---\n\nThis will be used to update existing translations and generate new ones.", "author": "user_2a237e38e06b", "created_at": "2025-12-16T23:52:47+00:00", "merged_at": "2025-12-29T12:38:11+00:00", "base_branch": "master", "head_branch": "llm-tr", "additions": 52, "deletions": 0, "changed_files": 1, "files": [ { "filename": "docs/tr/llm-prompt.md", "status": "added", "additions": 52, "deletions": 0, "changes": 52, "patch": "@@ -0,0 +1,52 @@\n+### Target language\n+\n+Translate to Turkish (Türkçe).\n+\n+Language code: tr.\n+\n+### Grammar and tone\n+\n+1) Use instructional Turkish, consistent with existing Turkish docs.\n+2) Use imperative/guide language when appropriate (e.g. “açalım”, “gidin”, “kopyalayalım”).\n+\n+### Headings\n+\n+1) Follow existing Turkish heading style ([NAME_REDACTED] where used; no trailing period).\n+\n+### Quotes\n+\n+1) Keep quote style consistent with the existing Turkish docs (they frequently use ASCII quotes in prose).\n+2) Never change quotes inside inline code, code blocks, URLs, or file paths.\n+\n+### Ellipsis\n+\n+1) Keep ellipsis style consistent with existing Turkish docs.\n+2) Never change `...` in code, URLs, or CLI examples.\n+\n+### Preferred translations / glossary\n+\n+Do not translate technical terms like path, route, request, response, query, body, cookie, and header, keep them as is.\n+\n+- Suffixing is very important, when adding Turkish suffixes to the English words, do that based on the pronunciation of the word and with an apostrophe.\n+\n+- Suffixes also changes based on what word comes next in Turkish too, here is an example:\n+\n+\"Server'a gelen request'leri intercept... \" or this could have been \"request'e\", \"request'i\" etc.\n+\n+- Some words are tricky like \"path'e\" can't be used like \"path'a\" but it could have been \"path'i\" \"path'leri\" etc.\n+\n+- You can use a more instructional style, that is consistent with the document, you can add the Turkish version of the term in parenthesis if it is not something very obvious, or an advanced concept, but do not over do it, do it only the first time it is mentioned, but keep the English term as the primary word.\n+\n+### `///` admonitions\n+\n+1) Keep the admonition keyword in English (do not translate `note`, `tip`, etc.).\n+2) If a title is present, prefer these canonical titles:\n+\n+- `/// note | Not`\n+- `/// note | [NAME_REDACTED]`\n+- `/// tip | İpucu`\n+- `/// warning | Uyarı`\n+- `/// info | Bilgi`\n+- `/// check | Ek bilgi`\n+\n+Prefer `İpucu` over `Ipucu`." } ], "reviews": [ { "id": 3594197983, "user": "user_f9569f77303d", "state": "APPROVED", "body": null, "submitted_at": "2025-12-18T17:46:58+00:00" }, { "id": 3598514924, "user": "user_2a237e38e06b", "state": "COMMENTED", "body": null, "submitted_at": "2025-12-19T12:53:02+00:00" }, { "id": 3601909719, "user": "user_f9569f77303d", "state": "COMMENTED", "body": null, "submitted_at": "2025-12-21T18:59:05+00:00" }, { "id": 3614403541, "user": "user_2a237e38e06b", "state": "COMMENTED", "body": null, "submitted_at": "2025-12-27T18:48:18+00:00" }, { "id": 3615620246, "user": "user_f9569f77303d", "state": "COMMENTED", "body": null, "submitted_at": "2025-12-29T11:01:58+00:00" }, { "id": 3615782344, "user": "user_2a237e38e06b", "state": "COMMENTED", "body": null, "submitted_at": "2025-12-29T12:37:39+00:00" } ], "review_comments": [ { "id": 2632003312, "user": "user_f9569f77303d", "body": "I think this is a great opportunity to rewrite these, like I never heard anyone using these terms IRL, but if we prefer to convert like this for other languages too, then it's completely fine!", "path": "docs/tr/llm-prompt.md", "line": 26, "side": "RIGHT", "created_at": "2025-12-18T17:46:31+00:00" }, { "id": 2635010422, "user": "user_2a237e38e06b", "body": "Ah, then actually it's probably better to explicitly instruct the LLM to _not_ convert them if those are not used IRL. 🤔 \n\nWhat do you think?", "path": "docs/tr/llm-prompt.md", "line": 26, "side": "RIGHT", "created_at": "2025-12-19T12:53:02+00:00" }, { "id": 2638034352, "user": "user_f9569f77303d", "body": "Yeah, that would be better IMO, even I got confused with \"yol operasyonu fonksiyonu\" 😂\n\nI agree, we should explicitly state this, we can add something like this to the prompt:\n\n```txt\n- Do not translate the terms like path, route, request, response, query, body, cookie, and header, keep them as it is. \n- Suffixing is very important, when adding Turkish suffixes to the English words, do that based on the pronunciation of the word and with an apostrophe. \n - Suffixes also changes based on what word comes next in Turkish too, here is an example: \"Server'a gelen request'leri intercept... \" or this could have been \"request'e\", \"request'i\" etc. \n - Some words are tricky like \"path'e\" can't be used like \"path'a\" but it could have been \"path'i\" \"path'leri\" etc. \n- You can use a more instructional style, that is consistent with the document, you can add the the Turkish version of the term in parenthesis if it is not something very obvious, or an advanced concept, but do not over do it, do it only the first time it is mentioned, but keep the English term as the primary word. \n```\n\nThese are the probably most tricky and important parts, when keeping the term(s) English.\n\n Also [Turkish](https://news.ycombinator.com/item?id=42343920) is weird and [known](https://blog.codinghorror.com/whats-wrong-with-turkey/) to be quite [problematic](https://news.ycombinator.com/item?id=45559767) too. 😭", "path": "docs/tr/llm-prompt.md", "line": 26, "side": "RIGHT", "created_at": "2025-12-21T18:59:05+00:00" }, { "id": 2649273663, "user": "user_2a237e38e06b", "body": "Perfect, thank you! I added your suggestions, replacing the old ones.\n\nDo you think this looks good as it is?", "path": "docs/tr/llm-prompt.md", "line": 26, "side": "RIGHT", "created_at": "2025-12-27T18:48:18+00:00" }, { "id": 2650725413, "user": "user_f9569f77303d", "body": "Yeah, it looks looks good now, thank you!\n\nI'm excited for the PR 🙂", "path": "docs/tr/llm-prompt.md", "line": 26, "side": "RIGHT", "created_at": "2025-12-29T11:01:58+00:00" }, { "id": 2650883850, "user": "user_2a237e38e06b", "body": "Awesome, thank you! 🚀", "path": "docs/tr/llm-prompt.md", "line": 26, "side": "RIGHT", "created_at": "2025-12-29T12:37:39+00:00" } ], "meta": { "languages": [ "md" ], "touches_tests": false, "review_state_summary": { "APPROVED": 1, "COMMENTED": 5 }, "meaningful_comment_count": 6, "has_approval": true, "has_changes_requested": false, "total_review_comments": 6 } } { "_id": "c17a7d41de3b1b70", "_schema_version": "1.0", "_cleaned_at": "2026-02-12T07:46:51.702905+00:00", "repo": "tiangolo/fastapi", "repo_url": "https://github.com/fastapi/fastapi", "license_name": "MIT License", "license_spdx": "MIT", "pr_number": 14546, "title": "🔧 Add LLM prompt file for Korean, generated from the existing translations", "body": "🔧 Add LLM prompt file for Korean, generated from the existing translations\n\n---\n\nThis will be used to update existing translations and generate new ones.", "author": "user_2a237e38e06b", "created_at": "2025-12-16T23:51:31+00:00", "merged_at": "2025-12-20T17:32:05+00:00", "base_branch": "master", "head_branch": "llm-ko", "additions": 51, "deletions": 0, "changed_files": 1, "files": [ { "filename": "docs/ko/llm-prompt.md", "status": "added", "additions": 51, "deletions": 0, "changes": 51, "patch": "@@ -0,0 +1,51 @@\n+### Target language\n+\n+Translate to Korean (한국어).\n+\n+Language code: ko.\n+\n+### Grammar and tone\n+\n+1) Use polite, instructional Korean (e.g. 합니다/하세요 style).\n+2) Keep the tone consistent with the existing [NAME_REDACTED] docs.\n+\n+### Headings\n+\n+1) Follow existing Korean heading style (short, action-oriented headings like “확인하기”).\n+2) Do not add trailing punctuation to headings.\n+\n+### Quotes\n+\n+1) Keep quote style consistent with the existing Korean docs.\n+2) Never change quotes inside inline code, code blocks, URLs, or file paths.\n+\n+### Ellipsis\n+\n+1) Keep ellipsis style consistent with existing Korean docs (often `...`).\n+2) Never change `...` in code, URLs, or CLI examples.\n+\n+### Preferred translations / glossary\n+\n+Use the following preferred translations when they apply in documentation prose:\n+\n+- request (HTTP): 요청\n+- response (HTTP): 응답\n+- path operation: 경로 처리\n+- path operation function: 경로 처리 함수\n+\n+### `///` admonitions\n+\n+1) Keep the admonition keyword in English (do not translate `note`, `tip`, etc.).\n+2) If a title is present, prefer these canonical titles:\n+\n+- `/// note | 참고`\n+- `/// tip | 팁`\n+- `/// warning | 경고`\n+- `/// info | 정보`\n+- `/// danger | 위험`\n+- `/// note [NAME_REDACTED] | 기술 세부사항`\n+- `/// check | 확인`\n+Notes:\n+\n+- `details` blocks exist in Korean docs; keep `/// details` as-is and translate only the title after `|`.\n+- Example canonical title used: `/// details | 상세 설명`" } ], "reviews": [ { "id": 3592626362, "user": "user_8de221e1b719", "state": "COMMENTED", "body": "Looks good to me overall. I’m not deeply familiar with FastAPI docs conventions, so I’d appreciate a final review/approval from someone more familiar with the FastAPI docs style.", "submitted_at": "2025-12-18T12:13:14+00:00" }, { "id": 3597018982, "user": "user_7e930c559d4e", "state": "CHANGES_REQUESTED", "body": null, "submitted_at": "2025-12-19T06:28:36+00:00" }, { "id": 3598517334, "user": "user_2a237e38e06b", "state": "COMMENTED", "body": null, "submitted_at": "2025-12-19T12:53:52+00:00" }, { "id": 3598519740, "user": "user_2a237e38e06b", "state": "COMMENTED", "body": null, "submitted_at": "2025-12-19T12:54:36+00:00" }, { "id": 3600819283, "user": "user_7e930c559d4e", "state": "APPROVED", "body": "LGTM 🚀", "submitted_at": "2025-12-20T07:22:47+00:00" } ], "review_comments": [ { "id": 2633789605, "user": "user_7e930c559d4e", "body": "```suggestion\n- path operation: 경로 처리\n- path operation function: 경로 처리 함수\n```\n\n\"Path operation\" was translated too literally as \"경로 작동\", which sounded awkward and made people misunderstand it as a new concept.\nI think it would be better to replace it with the more general term \"경로 처리\"", "path": "docs/ko/llm-prompt.md", "line": null, "side": "RIGHT", "created_at": "2025-12-19T06:05:51+00:00" }, { "id": 2633806679, "user": "user_7e930c559d4e", "body": "```suggestion\n- `/// note [NAME_REDACTED] | 기술 세부사항`\n- `/// check | 확인`\n```\n\nref: https://github.com/fastapi/fastapi/discussions/3167#discussioncomment-721448", "path": "docs/ko/llm-prompt.md", "line": null, "side": "RIGHT", "created_at": "2025-12-19T06:15:15+00:00" }, { "id": 2633834729, "user": "user_7e930c559d4e", "body": "```suggestion\n- Example canonical title used: `/// details | 상세 설명`\n```\n\nPlease remove \"명령어\"(It means command or instruction). It an unnecessary addition for this instruction.", "path": "docs/ko/llm-prompt.md", "line": null, "side": "RIGHT", "created_at": "2025-12-19T06:27:24+00:00" }, { "id": 2635012674, "user": "user_2a237e38e06b", "body": "Excellent, thank you! :raised_hands:", "path": "docs/ko/llm-prompt.md", "line": null, "side": "RIGHT", "created_at": "2025-12-19T12:53:52+00:00" }, { "id": 2635014361, "user": "user_2a237e38e06b", "body": "Perfect, thank you! :raised_hands:", "path": "docs/ko/llm-prompt.md", "line": null, "side": "RIGHT", "created_at": "2025-12-19T12:54:36+00:00" } ], "meta": { "languages": [ "md" ], "touches_tests": false, "review_state_summary": { "COMMENTED": 3, "CHANGES_REQUESTED": 1, "APPROVED": 1 }, "meaningful_comment_count": 5, "has_approval": true, "has_changes_requested": true, "total_review_comments": 5 } } { "_id": "f718b457b6d1010f", "_schema_version": "1.0", "_cleaned_at": "2026-02-12T07:46:51.702905+00:00", "repo": "tiangolo/fastapi", "repo_url": "https://github.com/fastapi/fastapi", "license_name": "MIT License", "license_spdx": "MIT", "pr_number": 14545, "title": "🔧 Add LLM prompt file for Japanese, generated from the existing translations", "body": "🔧 Add LLM prompt file for Japanese, generated from the existing translations.\n\n---\n\nThis will be used to update existing translations and generate new ones.", "author": "user_2a237e38e06b", "created_at": "2025-12-16T23:50:05+00:00", "merged_at": "2025-12-20T17:30:53+00:00", "base_branch": "master", "head_branch": "llm-ja", "additions": 47, "deletions": 0, "changed_files": 1, "files": [ { "filename": "docs/ja/llm-prompt.md", "status": "added", "additions": 47, "deletions": 0, "changes": 47, "patch": "@@ -0,0 +1,47 @@\n+### Target language\n+\n+Translate to Japanese (日本語).\n+\n+Language code: ja.\n+\n+### Grammar and tone\n+\n+1) Use polite, instructional Japanese (です/ます調).\n+2) Keep the tone concise and technical (match existing [NAME_REDACTED] docs).\n+\n+### Headings\n+\n+1) Follow the existing Japanese style: short, descriptive headings (often noun phrases), e.g. 「チェック」.\n+2) Do not add a trailing period at the end of headings.\n+\n+### Quotes\n+\n+1) [NAME_REDACTED] corner brackets 「」 in normal prose when quoting a term.\n+2) Do not change quotes inside inline code, code blocks, URLs, or file paths.\n+\n+### Ellipsis\n+\n+1) Keep ellipsis style consistent with existing Japanese docs (commonly `...`).\n+2) Never change `...` in code, URLs, or CLI examples.\n+\n+### Preferred translations / glossary\n+\n+Use the following preferred translations when they apply in documentation prose:\n+\n+- request (HTTP): リクエスト\n+- response (HTTP): レスポンス\n+- path operation: パスオペレーション\n+- path operation function: パスオペレーション関数\n+\n+### `///` admonitions\n+\n+1) Keep the admonition keyword in English (do not translate `note`, `tip`, etc.).\n+2) If a title is present, prefer these canonical titles:\n+\n+- `/// note | 備考`\n+- `/// note | 技術詳細`\n+- `/// tip | 豆知識`\n+- `/// warning | 注意`\n+- `/// info | 情報`\n+- `/// check | 確認`\n+- `/// danger | 警告`" } ], "reviews": [ { "id": 3595649090, "user": "user_472f326cb34f", "state": "APPROVED", "body": "Thank you.\n Everything looks good to me. \nIt seems to comply with the current translation rules. \nI am still looking for more technical terms to add, but since I don't have any at the moment, I approve this. \nThank you again!", "submitted_at": "2025-12-18T23:26:45+00:00" }, { "id": 3596611172, "user": "user_472f326cb34f", "state": "CHANGES_REQUESTED", "body": null, "submitted_at": "2025-12-19T03:19:11+00:00" }, { "id": 3598521740, "user": "user_2a237e38e06b", "state": "COMMENTED", "body": null, "submitted_at": "2025-12-19T12:55:17+00:00" }, { "id": 3600876177, "user": "user_472f326cb34f", "state": "APPROVED", "body": "Thank you.\nI approved this.", "submitted_at": "2025-12-20T08:30:12+00:00" } ], "review_comments": [ { "id": 2633446068, "user": "user_472f326cb34f", "body": "Sorry for commenting after approved myself.\nI think it is better to change \"警告\"\n\n```suggestion\n- `/// danger | 警告`\n```", "path": "docs/ja/llm-prompt.md", "line": null, "side": "RIGHT", "created_at": "2025-12-19T03:19:01+00:00" }, { "id": 2635016208, "user": "user_2a237e38e06b", "body": "Perfect, thanks! :raised_hands:", "path": "docs/ja/llm-prompt.md", "line": null, "side": "RIGHT", "created_at": "2025-12-19T12:55:17+00:00" } ], "meta": { "languages": [ "md" ], "touches_tests": false, "review_state_summary": { "APPROVED": 2, "CHANGES_REQUESTED": 1, "COMMENTED": 1 }, "meaningful_comment_count": 2, "has_approval": true, "has_changes_requested": true, "total_review_comments": 2 } } { "_id": "fdcf662463eea982", "_schema_version": "1.0", "_cleaned_at": "2026-02-12T07:46:51.702905+00:00", "repo": "tiangolo/fastapi", "repo_url": "https://github.com/fastapi/fastapi", "license_name": "MIT License", "license_spdx": "MIT", "pr_number": 14544, "title": "🔧 Add LLM prompt file for French, generated from the existing French docs", "body": "🔧 Add LLM prompt file for French, generated from the existing French docs\n\n---\n\nThis will be used to update existing translations and generate new ones.", "author": "user_2a237e38e06b", "created_at": "2025-12-16T21:19:26+00:00", "merged_at": "2025-12-17T10:41:44+00:00", "base_branch": "master", "head_branch": "llm-fr", "additions": 128, "deletions": 0, "changed_files": 1, "files": [ { "filename": "docs/fr/llm-prompt.md", "status": "added", "additions": 128, "deletions": 0, "changes": 128, "patch": "@@ -0,0 +1,128 @@\n+### Target language\n+\n+Translate to French (français).\n+\n+Language code: fr.\n+\n+### Grammar to use when talking to the reader\n+\n+Use the formal grammar (use «vous» instead of «tu»).\n+\n+### Quotes\n+\n+1) Convert neutral double quotes («\"») and English double typographic quotes («“» and «”») to French guillemets (««» and «»»).\n+\n+2) In the French docs, guillemets are written without extra spaces: use «texte», not « texte ».\n+\n+3) Do not convert quotes inside code blocks, inline code, paths, URLs, or anything wrapped in backticks.\n+\n+Examples:\n+\n+ Source (English):\n+\n+ «««\n+ \"Hello world\"\n+ “[NAME_REDACTED]”\n+ \"He said: 'Hello'\"\n+ \"The module is `__main__`\"\n+ »»»\n+\n+ Result (French):\n+\n+ «««\n+ «Hello world»\n+ «[NAME_REDACTED]»\n+ «He said: 'Hello'»\n+ «The module is `__main__`»\n+ »»»\n+\n+### Ellipsis\n+\n+1) Make sure there is a space between an ellipsis and a word following or preceding the ellipsis.\n+\n+Examples:\n+\n+ Source (English):\n+\n+ «««\n+ ...as we intended.\n+ ...this would work:\n+ ...etc.\n+ others...\n+ More to come...\n+ »»»\n+\n+ Result (French):\n+\n+ «««\n+ ... comme prévu.\n+ ... cela fonctionnerait :\n+ ... etc.\n+ D'autres ...\n+ La suite ...\n+ »»»\n+\n+2) This does not apply in URLs, code blocks, and code snippets. Do not remove or add spaces there.\n+\n+### Headings\n+\n+1) Prefer translating headings using the infinitive form (as is common in the existing French docs): «Créer…», «Utiliser…», «Ajouter…».\n+\n+2) For headings that are instructions written in imperative in English (e.g. “Go check …”), keep them in imperative in French, using the formal grammar (e.g. «Allez voir …»).\n+\n+3) Keep heading punctuation as in the source. In particular, keep occurrences of literal « - » (space-hyphen-space) as « - » (the existing French docs use a hyphen here).\n+\n+### French instructions about technical terms\n+\n+Do not try to translate everything. In particular, keep common programming terms when that is the established usage in the French docs (e.g. «framework», «endpoint», «plug-in», «payload»). Use French where the existing docs already consistently use French (e.g. «requête», «réponse»).\n+\n+Keep class names, function names, modules, file names, and CLI commands unchanged.\n+\n+### List of English terms and their preferred French translations\n+\n+Below is a list of English terms and their preferred French translations, separated by a colon («:»). Use these translations, do not use your own. If an existing translation does not use these terms, update it to use them.\n+\n+* «/// note | [NAME_REDACTED]»: «/// note | Détails techniques»\n+* «/// note»: «/// note | Remarque»\n+* «/// tip»: «/// tip | Astuce»\n+* «/// warning»: «/// warning | Attention»\n+* «/// check»: «/// check | vérifier»\n+* «/// info»: «/// info»\n+\n+* «the docs»: «les documents»\n+* «the documentation»: «la documentation»\n+\n+* «framework»: «framework» (do not translate to «cadre»)\n+* «performance»: «performance»\n+\n+* «type hints»: «annotations de type»\n+* «type annotations»: «annotations de type»\n+\n+* «autocomplete»: «autocomplétion»\n+* «autocompletion»: «autocomplétion»\n+\n+* «the request» (what the client sends to the server): «la requête»\n+* «the response» (what the server sends back to the client): «la réponse»\n+\n+* «the request body»: «le corps de la requête»\n+* «the response body»: «le corps de la réponse»\n+\n+* «path operation»: «opération de chemin»\n+* «path operations» (plural): «opérations de chemin»\n+* «path operation function»: «fonction de chemin»\n+* «path operation decorator»: «décorateur d'opération de chemin»\n+\n+* «path parameter»: «paramètre de chemin»\n+* «query parameter»: «paramètre de requête»\n+\n+* «the `Request`»: «`Request`» (keep as code identifier)\n+* «the `Response`»: «`Response`» (keep as code identifier)\n+\n+* «deployment»: «déploiement»\n+* «to upgrade»: «mettre à niveau»\n+\n+* «deprecated»: «déprécié»\n+* «to deprecate»: «déprécier»\n+\n+* «cheat sheet»: «aide-mémoire»\n+* «plug-in»: «plug-in»" } ], "reviews": [ { "id": 3585010198, "user": "user_db4405377801", "state": "COMMENTED", "body": null, "submitted_at": "2025-12-16T21:43:38+00:00" }, { "id": 3585402900, "user": "user_2a237e38e06b", "state": "COMMENTED", "body": null, "submitted_at": "2025-12-16T23:44:42+00:00" }, { "id": 3585405118, "user": "user_2a237e38e06b", "state": "COMMENTED", "body": null, "submitted_at": "2025-12-16T23:45:51+00:00" }, { "id": 3585405540, "user": "user_2a237e38e06b", "state": "COMMENTED", "body": null, "submitted_at": "2025-12-16T23:46:08+00:00" }, { "id": 3585406087, "user": "user_2a237e38e06b", "state": "COMMENTED", "body": null, "submitted_at": "2025-12-16T23:46:30+00:00" }, { "id": 3586751317, "user": "user_db4405377801", "state": "COMMENTED", "body": null, "submitted_at": "2025-12-17T09:16:54+00:00" }, { "id": 3586755310, "user": "user_db4405377801", "state": "COMMENTED", "body": null, "submitted_at": "2025-12-17T09:17:44+00:00" }, { "id": 3586903998, "user": "user_2a237e38e06b", "state": "COMMENTED", "body": null, "submitted_at": "2025-12-17T09:52:50+00:00" }, { "id": 3586934819, "user": "user_2a237e38e06b", "state": "COMMENTED", "body": null, "submitted_at": "2025-12-17T10:00:19+00:00" }, { "id": 3586941990, "user": "user_db4405377801", "state": "APPROVED", "body": "All good for me", "submitted_at": "2025-12-17T10:02:09+00:00" } ], "review_comments": [ { "id": 2624798210, "user": "user_db4405377801", "body": "attention", "path": "docs/fr/llm-prompt.md", "line": 88, "side": "RIGHT", "created_at": "2025-12-16T21:28:18+00:00" }, { "id": 2624804750, "user": "user_db4405377801", "body": "maybe `les documents` ? Not sure in which context is `the docs` but it sounds like plurals of document, not documentation. Or maybe it's for documentation`s` so in this case it will be `les documentations`", "path": "docs/fr/llm-prompt.md", "line": null, "side": "RIGHT", "created_at": "2025-12-16T21:30:27+00:00" }, { "id": 2624815887, "user": "user_db4405377801", "body": "If your really want to translate it in french, it should be `autcomplétion` for both line but does it make sense to translate it ?", "path": "docs/fr/llm-prompt.md", "line": null, "side": "RIGHT", "created_at": "2025-12-16T21:34:19+00:00" }, { "id": 2624831771, "user": "user_db4405377801", "body": "`le corps de la requête`", "path": "docs/fr/llm-prompt.md", "line": null, "side": "RIGHT", "created_at": "2025-12-16T21:39:43+00:00" }, { "id": 2624832261, "user": "user_db4405377801", "body": "`le corps de la réponse`", "path": "docs/fr/llm-prompt.md", "line": null, "side": "RIGHT", "created_at": "2025-12-16T21:39:54+00:00" }, { "id": 2624838494, "user": "user_db4405377801", "body": "`mettre à niveau`", "path": "docs/fr/llm-prompt.md", "line": null, "side": "RIGHT", "created_at": "2025-12-16T21:42:04+00:00" }, { "id": 2624841334, "user": "user_db4405377801", "body": "`aide-mémoire`", "path": "docs/fr/llm-prompt.md", "line": null, "side": "RIGHT", "created_at": "2025-12-16T21:43:04+00:00" }, { "id": 2625109261, "user": "user_2a237e38e06b", "body": "So, should it be like this?\n\n```suggestion\n* «/// warning»: «/// warning | attention»\n```", "path": "docs/fr/llm-prompt.md", "line": 88, "side": "RIGHT", "created_at": "2025-12-16T23:44:42+00:00" }, { "id": 2625111036, "user": "user_2a237e38e06b", "body": "I wouldn't know for sure, what do you think would sound better / more natural?", "path": "docs/fr/llm-prompt.md", "line": null, "side": "RIGHT", "created_at": "2025-12-16T23:45:51+00:00" }, { "id": 2625111412, "user": "user_2a237e38e06b", "body": "Nice, thanks!", "path": "docs/fr/llm-prompt.md", "line": null, "side": "RIGHT", "created_at": "2025-12-16T23:46:08+00:00" }, { "id": 2625111948, "user": "user_2a237e38e06b", "body": "Perfect :ok_hand:", "path": "docs/fr/llm-prompt.md", "line": null, "side": "RIGHT", "created_at": "2025-12-16T23:46:30+00:00" }, { "id": 2626226523, "user": "user_db4405377801", "body": "Not sure because others are capitalized so this one as well I guess but you didn't capitalized in english. Your call. All could be capitalized or none of them", "path": "docs/fr/llm-prompt.md", "line": 88, "side": "RIGHT", "created_at": "2025-12-17T09:16:54+00:00" }, { "id": 2626229731, "user": "user_db4405377801", "body": "We can go with `autocomplétion`", "path": "docs/fr/llm-prompt.md", "line": null, "side": "RIGHT", "created_at": "2025-12-17T09:17:44+00:00" }, { "id": 2626355212, "user": "user_2a237e38e06b", "body": "Get it, thanks!", "path": "docs/fr/llm-prompt.md", "line": 88, "side": "RIGHT", "created_at": "2025-12-17T09:52:50+00:00" }, { "id": 2626382492, "user": "user_2a237e38e06b", "body": "Perfect, thank you!", "path": "docs/fr/llm-prompt.md", "line": null, "side": "RIGHT", "created_at": "2025-12-17T10:00:18+00:00" } ], "meta": { "languages": [ "md" ], "touches_tests": false, "review_state_summary": { "COMMENTED": 9, "APPROVED": 1 }, "meaningful_comment_count": 14, "has_approval": true, "has_changes_requested": false, "total_review_comments": 15 } } { "_id": "40bf505a614fc674", "_schema_version": "1.0", "_cleaned_at": "2026-02-12T07:46:51.702905+00:00", "repo": "tiangolo/fastapi", "repo_url": "https://github.com/fastapi/fastapi", "license_name": "MIT License", "license_spdx": "MIT", "pr_number": 14306, "title": "🚸 Improve tracebacks by [NAME_REDACTED]", "body": "Today, when validation errors occur, error messages don't indicate what endpoint caused the problem, which can make debugging difficult. \n\nThis PR adds endpoint context metadata to validation error messages to show the filepath (clickable in IDEs!) and line number, function name and HTTP method and route where applicable. The endpoint context is extracted once per endpoint and then cached to avoid any additional performance overhead on subsequent requests. Just to double check, I also ran a rough benchmark (100k requests):\n```\nBaseline (without changes): 0.0006s\nUncached: \t\t\t\t\t1.3281s (13.28µs per request)\n**Cached**: \t\t\t\t0.0060s (0.06µs per request)\n```\n\nEndpoint context only appears in the exception's string representation (server logs). It is **not** exposed to clients in HTTP responses. Clients still receive the standard 422 response with validation error details.\n\n## Examples\n\n### ResponseValidationError\n\n**Before:**\n```\nfastapi.exceptions.ResponseValidationError: 1 validation error:\n {'type': 'missing', 'loc': ('response', 'id'), 'msg': 'Field required', 'input': {'name': 'Widget'}}\n```\n\n**After:**\n```\nfastapi.exceptions.ResponseValidationError: 1 validation error:\n {'type': 'missing', 'loc': ('response', 'id'), 'msg': 'Field required', 'input': {'name': 'Widget'}}\n\n File \"/Users/savannah/work/fastapi/capture_real_examples.py\", line 43, in create_item\n POST /items/\n```\n\n### RequestValidationError\n\n**Before:**\n```\nfastapi.exceptions.RequestValidationError: 1 validation error:\n {'type': 'int_parsing', 'loc': ('path', 'user_id'), 'msg': 'Input should be a valid integer, unable to parse string as an integer', 'input': 'invalid'}\n```\n\n**After:**\n```\nfastapi.exceptions.RequestValidationError: 1 validation error:\n {'type': 'int_parsing', 'loc': ('path', 'user_id'), 'msg': 'Input should be a valid integer, unable to parse string as an integer', 'input': 'invalid'}\n\n File \"/Users/savannah/work/fastapi/capture_real_examples.py\", line 38, in get_user\n GET /users/{user_id}\n```\n\n### WebSocketRequestValidationError\n\n**Before:**\n```\nfastapi.exceptions.WebSocketRequestValidationError: 1 validation error:\n {'type': 'int_parsing', 'loc': ('path', 'item_id'), 'msg': 'Input should be a valid integer, unable to parse string as an integer', 'input': 'invalid'}\n```\n\n**After:**\n```\nfastapi.exceptions.WebSocketRequestValidationError: 1 validation error:\n {'type': 'int_parsing', 'loc': ('path', 'item_id'), 'msg': 'Input should be a valid integer, unable to parse string as an integer', 'input': 'invalid'}\n\n File \"/Users/savannah/work/fastapi/capture_real_examples.py\", line 48, in websocket_endpoint\n WS /ws/{item_id}\n```", "author": "user_5ab5e340e6df", "created_at": "2025-11-06T18:54:41+00:00", "merged_at": "2025-12-06T12:21:57+00:00", "base_branch": "master", "head_branch": "improved_tracebacks", "additions": 289, "deletions": 16, "changed_files": 3, "files": [ { "filename": "fastapi/exceptions.py", "status": "modified", "additions": 62, "deletions": 13, "changes": 75, "patch": "@@ -1,4 +1,4 @@\n-from typing import Any, Dict, Optional, Sequence, Type, Union\n+from typing import Any, Dict, Optional, Sequence, Type, TypedDict, Union\n \n from annotated_doc import Doc\n from pydantic import BaseModel, create_model\n@@ -7,6 +7,13 @@\n from typing_extensions import Annotated\n \n \n+class EndpointContext(TypedDict, total=False):\n+ function: str\n+ path: str\n+ file: str\n+ line: int\n+\n+\n class HTTPException(StarletteHTTPException):\n \"\"\"\n An HTTP exception you can raise in your own code to show errors to the client.\n@@ -155,30 +162,72 @@ class DependencyScopeError(FastAPIError):\n \n \n class ValidationException(Exception):\n- def __init__(self, errors: Sequence[Any]) -> None:\n+ def __init__(\n+ self,\n+ errors: Sequence[Any],\n+ *,\n+ endpoint_ctx: Optional[EndpointContext] = None,\n+ ) -> None:\n self._errors = errors\n+ self.endpoint_ctx = endpoint_ctx\n+\n+ ctx = endpoint_ctx or {}\n+ self.endpoint_function = ctx.get(\"function\")\n+ self.endpoint_path = ctx.get(\"path\")\n+ self.endpoint_file = ctx.get(\"file\")\n+ self.endpoint_line = ctx.get(\"line\")\n \n def errors(self) -> Sequence[Any]:\n return self._errors\n \n+ def _format_endpoint_context(self) -> str:\n+ if not (self.endpoint_file and self.endpoint_line and self.endpoint_function):\n+ if self.endpoint_path:\n+ return f\"\\n Endpoint: {self.endpoint_path}\"\n+ return \"\"\n+\n+ context = f'\\n File \"{self.endpoint_file}\", line {self.endpoint_line}, in {self.endpoint_function}'\n+ if self.endpoint_path:\n+ context += f\"\\n {self.endpoint_path}\"\n+ return context\n+\n+ def __str__(self) -> str:\n+ message = f\"{len(self._errors)} validation error{'s' if len(self._errors) != 1 else ''}:\\n\"\n+ for err in self._errors:\n+ message += f\" {err}\\n\"\n+ message += self._format_endpoint_context()\n+ return message.rstrip()\n+\n \n class RequestValidationError(ValidationException):\n- def __init__(self, errors: Sequence[Any], *, body: Any = None) -> None:\n- super().__init__(errors)\n+ def __init__(\n+ self,\n+ errors: Sequence[Any],\n+ *,\n+ body: Any = None,\n+ endpoint_ctx: Optional[EndpointContext] = None,\n+ ) -> None:\n+ super().__init__(errors, endpoint_ctx=endpoint_ctx)\n self.body = body\n \n \n class WebSocketRequestValidationError(ValidationException):\n- pass\n+ def __init__(\n+ self,\n+ errors: Sequence[Any],\n+ *,\n+ endpoint_ctx: Optional[EndpointContext] = None,\n+ ) -> None:\n+ super().__init__(errors, endpoint_ctx=endpoint_ctx)\n \n \n class ResponseValidationError(ValidationException):\n- def __init__(self, errors: Sequence[Any], *, body: Any = None) -> None:\n- super().__init__(errors)\n+ def __init__(\n+ self,\n+ errors: Sequence[Any],\n+ *,\n+ body: Any = None,\n+ endpoint_ctx: Optional[EndpointContext] = None,\n+ ) -> None:\n+ super().__init__(errors, endpoint_ctx=endpoint_ctx)\n self.body = body\n-\n- def __str__(self) -> str:\n- message = f\"{len(self._errors)} validation errors:\\n\"\n- for err in self._errors:\n- message += f\" {err}\\n\"\n- return message" }, { "filename": "fastapi/routing.py", "status": "modified", "additions": 59, "deletions": 3, "changes": 62, "patch": "@@ -46,6 +46,7 @@\n )\n from fastapi.encoders import jsonable_encoder\n from fastapi.exceptions import (\n+ EndpointContext,\n FastAPIError,\n RequestValidationError,\n ResponseValidationError,\n@@ -212,6 +213,33 @@ async def merged_lifespan(\n return merged_lifespan # type: ignore[return-value]\n \n \n+# Cache for endpoint context to avoid re-extracting on every request\n+_endpoint_context_cache: Dict[int, EndpointContext] = {}\n+\n+\n+def _extract_endpoint_context(func: Any) -> EndpointContext:\n+ \"\"\"Extract endpoint context with caching to avoid repeated file I/O.\"\"\"\n+ func_id = id(func)\n+\n+ if func_id in _endpoint_context_cache:\n+ return _endpoint_context_cache[func_id]\n+\n+ try:\n+ ctx: EndpointContext = {}\n+\n+ if (source_file := inspect.getsourcefile(func)) is not None:\n+ ctx[\"file\"] = source_file\n+ if (line_number := inspect.getsourcelines(func)[1]) is not None:\n+ ctx[\"line\"] = line_number\n+ if (func_name := getattr(func, \"__name__\", None)) is not None:\n+ ctx[\"function\"] = func_name\n+ except Exception:\n+ ctx = EndpointContext()\n+\n+ _endpoint_context_cache[func_id] = ctx\n+ return ctx\n+\n+\n async def serialize_response(\n *,\n field: Optional[ModelField] = None,\n@@ -223,6 +251,7 @@ async def serialize_response(\n exclude_defaults: bool = False,\n exclude_none: bool = False,\n is_coroutine: bool = True,\n+ endpoint_ctx: Optional[EndpointContext] = None,\n ) -> Any:\n if field:\n errors = []\n@@ -245,8 +274,11 @@ async def serialize_response(\n elif errors_:\n errors.append(errors_)\n if errors:\n+ ctx = endpoint_ctx or EndpointContext()\n raise ResponseValidationError(\n- errors=_normalize_errors(errors), body=response_content\n+ errors=_normalize_errors(errors),\n+ body=response_content,\n+ endpoint_ctx=ctx,\n )\n \n if hasattr(field, \"serialize\"):\n@@ -318,6 +350,18 @@ async def app(request: Request) -> Response:\n \"fastapi_middleware_astack not found in request scope\"\n )\n \n+ # Extract endpoint context for error messages\n+ endpoint_ctx = (\n+ _extract_endpoint_context(dependant.call)\n+ if dependant.call\n+ else EndpointContext()\n+ )\n+\n+ if dependant.path:\n+ # For mounted sub-apps, include the mount path prefix\n+ mount_path = request.scope.get(\"root_path\", \"\").rstrip(\"/\")\n+ endpoint_ctx[\"path\"] = f\"{request.method} {mount_path}{dependant.path}\"\n+\n # Read body and auto-close files\n try:\n body: Any = None\n@@ -355,6 +399,7 @@ async def app(request: Request) -> Response:\n }\n ],\n body=e.doc,\n+ endpoint_ctx=endpoint_ctx,\n )\n raise validation_error from e\n except HTTPException:\n@@ -414,14 +459,15 @@ async def app(request: Request) -> Response:\n exclude_defaults=response_model_exclude_defaults,\n exclude_none=response_model_exclude_none,\n is_coroutine=is_coroutine,\n+ endpoint_ctx=endpoint_ctx,\n )\n response = actual_response_class(content, **response_args)\n if not is_body_allowed_for_status_code(response.status_code):\n response.body = b\"\"\n response.headers.raw.extend(solved_result.response.headers.raw)\n if errors:\n validation_error = RequestValidationError(\n- _normalize_errors(errors), body=body\n+ _normalize_errors(errors), body=body, endpoint_ctx=endpoint_ctx\n )\n raise validation_error\n \n@@ -438,6 +484,15 @@ def get_websocket_app(\n embed_body_fields: bool = False,\n ) -> Callable[[WebSocket], Coroutine[Any, Any, Any]]:\n async def app(websocket: WebSocket) -> None:\n+ endpoint_ctx = (\n+ _extract_endpoint_context(dependant.call)\n+ if dependant.call\n+ else EndpointContext()\n+ )\n+ if dependant.path:\n+ # For mounted sub-apps, include the mount path prefix\n+ mount_path = websocket.scope.get(\"root_path\", \"\").rstrip(\"/\")\n+ endpoint_ctx[\"path\"] = f\"WS {mount_path}{dependant.path}\"\n async_exit_stack = websocket.scope.get(\"fastapi_inner_astack\")\n assert isinstance(async_exit_stack, AsyncExitStack), (\n \"fastapi_inner_astack not found in request scope\"\n@@ -451,7 +506,8 @@ async def app(websocket: WebSocket) -> None:\n )\n if solved_result.errors:\n raise WebSocketRequestValidationError(\n- _normalize_errors(solved_result.errors)\n+ _normalize_errors(solved_result.errors),\n+ endpoint_ctx=endpoint_ctx,\n )\n assert dependant.call is not None, \"dependant.call must be a function\"\n await dependant.call(**solved_result.values)" }, { "filename": "tests/test_validation_error_context.py", "status": "added", "additions": 168, "deletions": 0, "changes": 168, "patch": "@@ -0,0 +1,168 @@\n+from fastapi import FastAPI, Request, WebSocket\n+from fastapi.exceptions import (\n+ RequestValidationError,\n+ ResponseValidationError,\n+ WebSocketRequestValidationError,\n+)\n+from fastapi.testclient import TestClient\n+from pydantic import BaseModel\n+\n+\n+class Item(BaseModel):\n+ id: int\n+ name: str\n+\n+\n+class ExceptionCapture:\n+ def __init__(self):\n+ self.exception = None\n+\n+ def capture(self, exc):\n+ self.exception = exc\n+ return exc\n+\n+\n+app = FastAPI()\n+sub_app = FastAPI()\n+captured_exception = ExceptionCapture()\n+\n+app.mount(path=\"/sub\", app=sub_app)\n+\n+\n+[USER_REDACTED].exception_handler(RequestValidationError)\n+[USER_REDACTED]_app.exception_handler(RequestValidationError)\n+async def request_validation_handler(request: Request, exc: RequestValidationError):\n+ captured_exception.capture(exc)\n+ raise exc\n+\n+\n+[USER_REDACTED].exception_handler(ResponseValidationError)\n+[USER_REDACTED]_app.exception_handler(ResponseValidationError)\n+async def response_validation_handler(_: Request, exc: ResponseValidationError):\n+ captured_exception.capture(exc)\n+ raise exc\n+\n+\n+[USER_REDACTED].exception_handler(WebSocketRequestValidationError)\n+[USER_REDACTED]_app.exception_handler(WebSocketRequestValidationError)\n+async def websocket_validation_handler(\n+ websocket: WebSocket, exc: WebSocketRequestValidationError\n+):\n+ captured_exception.capture(exc)\n+ raise exc\n+\n+\n+[USER_REDACTED].get(\"/users/{user_id}\")\n+def get_user(user_id: int):\n+ return {\"user_id\": user_id} # pragma: no cover\n+\n+\n+[USER_REDACTED].get(\"/items/\", response_model=Item)\n+def get_item():\n+ return {\"name\": \"Widget\"}\n+\n+\n+[USER_REDACTED]_app.get(\"/items/\", response_model=Item)\n+def get_sub_item():\n+ return {\"name\": \"Widget\"} # pragma: no cover\n+\n+\n+[USER_REDACTED].websocket(\"/ws/{item_id}\")\n+async def websocket_endpoint(websocket: WebSocket, item_id: int):\n+ await websocket.accept() # pragma: no cover\n+ await websocket.send_text(f\"Item: {item_id}\") # pragma: no cover\n+ await websocket.close() # pragma: no cover\n+\n+\n+[USER_REDACTED]_app.websocket(\"/ws/{item_id}\")\n+async def subapp_websocket_endpoint(websocket: WebSocket, item_id: int):\n+ await websocket.accept() # pragma: no cover\n+ await websocket.send_text(f\"Item: {item_id}\") # pragma: no cover\n+ await websocket.close() # pragma: no cover\n+\n+\n+client = TestClient(app)\n+\n+\n+def test_request_validation_error_includes_endpoint_context():\n+ captured_exception.exception = None\n+ try:\n+ client.get(\"/users/invalid\")\n+ except Exception:\n+ pass\n+\n+ assert captured_exception.exception is not None\n+ error_str = str(captured_exception.exception)\n+ assert \"get_user\" in error_str\n+ assert \"/users/\" in error_str\n+\n+\n+def test_response_validation_error_includes_endpoint_context():\n+ captured_exception.exception = None\n+ try:\n+ client.get(\"/items/\")\n+ except Exception:\n+ pass\n+\n+ assert captured_exception.exception is not None\n+ error_str = str(captured_exception.exception)\n+ assert \"get_item\" in error_str\n+ assert \"/items/\" in error_str\n+\n+\n+def test_websocket_validation_error_includes_endpoint_context():\n+ captured_exception.exception = None\n+ try:\n+ with client.websocket_connect(\"/ws/invalid\"):\n+ pass # pragma: no cover\n+ except Exception:\n+ pass\n+\n+ assert captured_exception.exception is not None\n+ error_str = str(captured_exception.exception)\n+ assert \"websocket_endpoint\" in error_str\n+ assert \"/ws/\" in error_str\n+\n+\n+def test_subapp_request_validation_error_includes_endpoint_context():\n+ captured_exception.exception = None\n+ try:\n+ client.get(\"/sub/items/\")\n+ except Exception:\n+ pass\n+\n+ assert captured_exception.exception is not None\n+ error_str = str(captured_exception.exception)\n+ assert \"get_sub_item\" in error_str\n+ assert \"/sub/items/\" in error_str\n+\n+\n+def test_subapp_websocket_validation_error_includes_endpoint_context():\n+ captured_exception.exception = None\n+ try:\n+ with client.websocket_connect(\"/sub/ws/invalid\"):\n+ pass # pragma: no cover\n+ except Exception:\n+ pass\n+\n+ assert captured_exception.exception is not None\n+ error_str = str(captured_exception.exception)\n+ assert \"subapp_websocket_endpoint\" in error_str\n+ assert \"/sub/ws/\" in error_str\n+\n+\n+def test_validation_error_with_only_path():\n+ errors = [{\"type\": \"missing\", \"loc\": (\"body\", \"name\"), \"msg\": \"Field required\"}]\n+ exc = RequestValidationError(errors, endpoint_ctx={\"path\": \"GET /api/test\"})\n+ error_str = str(exc)\n+ assert \"Endpoint: GET /api/test\" in error_str\n+ assert 'File \"' not in error_str\n+\n+\n+def test_validation_error_with_no_context():\n+ errors = [{\"type\": \"missing\", \"loc\": (\"body\", \"name\"), \"msg\": \"Field required\"}]\n+ exc = RequestValidationError(errors, endpoint_ctx={})\n+ error_str = str(exc)\n+ assert \"1 validation error:\" in error_str\n+ assert \"Endpoint\" not in error_str\n+ assert 'File \"' not in error_str" } ], "reviews": [ { "id": 3433157811, "user": "user_29e85f9a8e75", "state": "COMMENTED", "body": null, "submitted_at": "2025-11-07T11:16:11+00:00" }, { "id": 3435236397, "user": "user_5ab5e340e6df", "state": "COMMENTED", "body": null, "submitted_at": "2025-11-07T17:03:14+00:00" }, { "id": 3547499941, "user": "user_2a237e38e06b", "state": "APPROVED", "body": "This is amazing, thank you! 🤩 🙌 \n\nIt will be available in FastAPI 0.124.0, released in the next few hours. 🎉", "submitted_at": "2025-12-06T12:19:32+00:00" } ], "review_comments": [ { "id": 2502889142, "user": "user_29e85f9a8e75", "body": "```suggestion\n root_path = cast(str, request.scope.get(\"root_path\", \"\")).rstrip(\"/\")\n endpoint_ctx[\"path\"] = (\n f\"{request.method} {root_path}/{dependant.path.lstrip('/')}\"\n )\n```\nShould we handle `root_path` here?\n\nIt would be helpful for mounted sub-apps.\nIn current implementation `path` will not contain mounting point for sub-apps and that might be confusing.\n\n
      \n\n```py\nfrom fastapi import FastAPI, Request, WebSocket\nfrom fastapi.exceptions import (\n RequestValidationError,\n WebSocketRequestValidationError,\n)\nfrom fastapi.testclient import TestClient\nfrom pydantic import BaseModel\n\nclass Item(BaseModel):\n id: int\n name: str\n\nclass ExceptionCapture:\n def __init__(self):\n self.exception = None\n\n def capture(self, exc):\n self.exception = exc\n return exc\n\napp = FastAPI()\n\nsub_app = FastAPI()\n\ncaptured_exception = ExceptionCapture()\n\n[USER_REDACTED].exception_handler(RequestValidationError)\n[USER_REDACTED]_app.exception_handler(RequestValidationError)\nasync def request_validation_handler(request: Request, exc: RequestValidationError):\n captured_exception.capture(exc)\n raise exc\n\n[USER_REDACTED].exception_handler(WebSocketRequestValidationError)\n[USER_REDACTED]_app.exception_handler(WebSocketRequestValidationError)\nasync def websocket_validation_handler(\n websocket: WebSocket, exc: WebSocketRequestValidationError\n):\n captured_exception.capture(exc)\n raise exc\n\n[USER_REDACTED]_app.get(\"/users/{user_id}\")\ndef get_user_router(user_id: int):\n return {\"user_id\": user_id} # pragma: no cover\n\napp.mount(path=\"/sub\", app=sub_app)\n\nclient = TestClient(app, raise_server_exceptions=False)\n\ndef test_subapp_request_validation_error_includes_endpoint_context():\n captured_exception.exception = None\n try:\n client.get(\"/sub/users/invalid\")\n except Exception:\n pass\n\n assert captured_exception.exception is not None\n error_str = str(captured_exception.exception)\n assert \"get_user\" in error_str\n assert \"/sub/users/\" in error_str # <= Currently fails\n```\n\n
      ", "path": "fastapi/routing.py", "line": null, "side": "RIGHT", "created_at": "2025-11-07T11:16:11+00:00" }, { "id": 2504615237, "user": "user_5ab5e340e6df", "body": "TIL about sub apps 🤓 ! Thanks!", "path": "fastapi/routing.py", "line": null, "side": "RIGHT", "created_at": "2025-11-07T17:03:13+00:00" } ], "meta": { "languages": [ "py" ], "touches_tests": true, "review_state_summary": { "COMMENTED": 2, "APPROVED": 1 }, "meaningful_comment_count": 2, "has_approval": true, "has_changes_requested": false, "total_review_comments": 2 } } { "_id": "6ec75f70e79cf7a6", "_schema_version": "1.0", "_cleaned_at": "2026-02-12T07:46:51.702905+00:00", "repo": "tiangolo/fastapi", "repo_url": "https://github.com/fastapi/fastapi", "license_name": "MIT License", "license_spdx": "MIT", "pr_number": 14258, "title": "✨ Show a clear error on attempt to include router into itself", "body": "Previously discussed in https://github.com/fastapi/fastapi/discussions/11424 with the PR at https://github.com/fastapi/fastapi/pull/11425\n\nSince I made modifications in the fork of the repo, the PR was automatically closed. This PR serves to add the circular reference check again. Discussed again in https://github.com/fastapi/fastapi/discussions/14251", "author": "user_35bbb315c859", "created_at": "2025-10-30T09:51:00+00:00", "merged_at": "2026-02-10T10:58:40+00:00", "base_branch": "master", "head_branch": "master", "additions": 16, "deletions": 0, "changed_files": 2, "files": [ { "filename": "fastapi/routing.py", "status": "modified", "additions": 4, "deletions": 0, "changes": 4, "patch": "@@ -1393,6 +1393,10 @@ def read_users():\n app.include_router(internal_router)\n ```\n \"\"\"\n+ assert self is not router, (\n+ \"Cannot include the same APIRouter instance into itself. \"\n+ \"Did you mean to include a different router?\"\n+ )\n if prefix:\n assert prefix.startswith(\"/\"), \"A path prefix must start with '/'\"\n assert not prefix.endswith(\"/\"), (" }, { "filename": "tests/test_router_circular_import.py", "status": "added", "additions": 12, "deletions": 0, "changes": 12, "patch": "@@ -0,0 +1,12 @@\n+import pytest\n+from fastapi import APIRouter\n+\n+\n+def test_router_circular_import():\n+ router = APIRouter()\n+\n+ with pytest.raises(\n+ AssertionError,\n+ match=\"Cannot include the same APIRouter instance into itself. Did you mean to include a different router?\",\n+ ):\n+ router.include_router(router)" } ], "reviews": [ { "id": 3399097403, "user": "user_29e85f9a8e75", "state": "COMMENTED", "body": null, "submitted_at": "2025-10-30T11:39:22+00:00" }, { "id": 3399164176, "user": "user_29e85f9a8e75", "state": "COMMENTED", "body": null, "submitted_at": "2025-10-30T11:43:20+00:00" }, { "id": 3399456036, "user": "user_29e85f9a8e75", "state": "APPROVED", "body": "LGTM!\n\n[USER_REDACTED], thank you!", "submitted_at": "2025-10-30T12:53:28+00:00" }, { "id": 3778250539, "user": "user_2a237e38e06b", "state": "APPROVED", "body": "Makes sense, thank you! This will be available in FastAPI 0.128.7, released in the next few hours. 🚀", "submitted_at": "2026-02-10T10:57:50+00:00" } ], "review_comments": [ { "id": 2477713950, "user": "user_29e85f9a8e75", "body": "```suggestion\nimport pytest\nfrom fastapi import APIRouter\n\ndef test_router_circular_import():\n router = APIRouter()\n\n with pytest.raises(AssertionError, match=\"Cannot include router into itself\"):\n router.include_router(router)\n```\n\n`app` is not needed here, and calling `router.include_router` after `app.include_router(router)` wrong", "path": "tests/test_router_circular_import.py", "line": 12, "side": "RIGHT", "created_at": "2025-10-30T11:32:37+00:00" }, { "id": 2477734639, "user": "user_29e85f9a8e75", "body": "```suggestion\n assert self is not router, (\n \"Cannot include the same APIRouter instance into itself. \"\n \"Did you mean to include a different router?\"\n )\n```\nHow about this version?", "path": "fastapi/routing.py", "line": null, "side": "RIGHT", "created_at": "2025-10-30T11:36:53+00:00" }, { "id": 2477768548, "user": "user_29e85f9a8e75", "body": "Also, we should probably raise [`FastAPIError`](https://github.com/fastapi/fastapi/blob/1fc586c3a5ae457457c5c70adddb07c7e9185f16/fastapi/exceptions.py#L144) instead of `assert`.\n\nUPD: maybe not. In other cases just `assert` is used..", "path": "fastapi/routing.py", "line": null, "side": "RIGHT", "created_at": "2025-10-30T11:43:20+00:00" } ], "meta": { "languages": [ "py" ], "touches_tests": true, "review_state_summary": { "COMMENTED": 2, "APPROVED": 2 }, "meaningful_comment_count": 3, "has_approval": true, "has_changes_requested": false, "total_review_comments": 3 } } { "_id": "1aaa616137116afd", "_schema_version": "1.0", "_cleaned_at": "2026-02-12T07:46:51.702905+00:00", "repo": "tiangolo/fastapi", "repo_url": "https://github.com/fastapi/fastapi", "license_name": "MIT License", "license_spdx": "MIT", "pr_number": 14186, "title": "🐛 Fix internal Pydantic v1 compatibility (warnings) for Python 3.14 and Pydantic 2.12.1", "body": "The Python 3.14 tests started failing with the Pydantic v.2.12.1 release, because of the combination of https://github.com/fastapi/fastapi/pull/14168 and https://github.com/[USER_REDACTED]ntic/pydantic/pull/12367.\n\nBasically we were importing Pydantic `v1` functionality even when the user had (only) Pydantic v2 installed. This was done in https://github.com/fastapi/fastapi/pull/14168 to support more easy migration from v1 to v2 by [NAME_REDACTED] the same app.\n\nHere, we prevent importing any `v1` functionality by [NAME_REDACTED] Python 3.14 / Pydantic 2.12.0 onwards, which [drops support](https://github.com/[USER_REDACTED]ntic/pydantic/releases/tag/v2.12.0) for `v1` and emits a [warning](https://github.com/[USER_REDACTED]ntic/pydantic/pull/12367) when importing `v1` functionality.\n\n### TODO\n\n- [x] fix coverage\n- [ ] check warning is still shown to users at some point, and not just swallowed by [NAME_REDACTED]", "author": "user_84458f05cf3c", "created_at": "2025-10-14T09:48:47+00:00", "merged_at": "2025-10-20T11:26:49+00:00", "base_branch": "master", "head_branch": "fix/ci", "additions": 283, "deletions": 102, "changed_files": 13, "files": [ { "filename": "fastapi/_compat/__init__.py", "status": "modified", "additions": 4, "deletions": 4, "changes": 8, "patch": "@@ -30,6 +30,10 @@\n from .main import (\n with_info_plain_validator_function as with_info_plain_validator_function,\n )\n+from .may_v1 import CoreSchema as CoreSchema\n+from .may_v1 import GetJsonSchemaHandler as GetJsonSchemaHandler\n+from .may_v1 import JsonSchemaValue as JsonSchemaValue\n+from .may_v1 import _normalize_errors as _normalize_errors\n from .model_field import ModelField as ModelField\n from .shared import PYDANTIC_V2 as PYDANTIC_V2\n from .shared import PYDANTIC_VERSION_MINOR_TUPLE as PYDANTIC_VERSION_MINOR_TUPLE\n@@ -44,7 +48,3 @@\n from .shared import lenient_issubclass as lenient_issubclass\n from .shared import sequence_types as sequence_types\n from .shared import value_is_sequence as value_is_sequence\n-from .v1 import CoreSchema as CoreSchema\n-from .v1 import GetJsonSchemaHandler as GetJsonSchemaHandler\n-from .v1 import JsonSchemaValue as JsonSchemaValue\n-from .v1 import _normalize_errors as _normalize_errors" }, { "filename": "fastapi/_compat/main.py", "status": "modified", "additions": 92, "deletions": 35, "changes": 127, "patch": "@@ -1,3 +1,4 @@\n+import sys\n from functools import lru_cache\n from typing import (\n Any,\n@@ -8,7 +9,7 @@\n Type,\n )\n \n-from fastapi._compat import v1\n+from fastapi._compat import may_v1\n from fastapi._compat.shared import PYDANTIC_V2, lenient_issubclass\n from fastapi.types import ModelNameMap\n from pydantic import BaseModel\n@@ -50,7 +51,9 @@\n \n [USER_REDACTED]_cache\n def get_cached_model_fields(model: Type[BaseModel]) -> List[ModelField]:\n- if lenient_issubclass(model, v1.BaseModel):\n+ if lenient_issubclass(model, may_v1.BaseModel):\n+ from fastapi._compat import v1\n+\n return v1.get_model_fields(model)\n else:\n from . import v2\n@@ -59,7 +62,7 @@ def get_cached_model_fields(model: Type[BaseModel]) -> List[ModelField]:\n \n \n def _is_undefined(value: object) -> bool:\n- if isinstance(value, v1.UndefinedType):\n+ if isinstance(value, may_v1.UndefinedType):\n return True\n elif PYDANTIC_V2:\n from . import v2\n@@ -69,7 +72,9 @@ def _is_undefined(value: object) -> bool:\n \n \n def _get_model_config(model: BaseModel) -> Any:\n- if isinstance(model, v1.BaseModel):\n+ if isinstance(model, may_v1.BaseModel):\n+ from fastapi._compat import v1\n+\n return v1._get_model_config(model)\n elif PYDANTIC_V2:\n from . import v2\n@@ -80,7 +85,9 @@ def _get_model_config(model: BaseModel) -> Any:\n def _model_dump(\n model: BaseModel, mode: Literal[\"json\", \"python\"] = \"json\", **kwargs: Any\n ) -> Any:\n- if isinstance(model, v1.BaseModel):\n+ if isinstance(model, may_v1.BaseModel):\n+ from fastapi._compat import v1\n+\n return v1._model_dump(model, mode=mode, **kwargs)\n elif PYDANTIC_V2:\n from . import v2\n@@ -89,7 +96,7 @@ def _model_dump(\n \n \n def _is_error_wrapper(exc: Exception) -> bool:\n- if isinstance(exc, v1.ErrorWrapper):\n+ if isinstance(exc, may_v1.ErrorWrapper):\n return True\n elif PYDANTIC_V2:\n from . import v2\n@@ -99,7 +106,9 @@ def _is_error_wrapper(exc: Exception) -> bool:\n \n \n def copy_field_info(*, field_info: FieldInfo, annotation: Any) -> FieldInfo:\n- if isinstance(field_info, v1.FieldInfo):\n+ if isinstance(field_info, may_v1.FieldInfo):\n+ from fastapi._compat import v1\n+\n return v1.copy_field_info(field_info=field_info, annotation=annotation)\n else:\n assert PYDANTIC_V2\n@@ -111,7 +120,9 @@ def copy_field_info(*, field_info: FieldInfo, annotation: Any) -> FieldInfo:\n def create_body_model(\n *, fields: Sequence[ModelField], model_name: str\n ) -> Type[BaseModel]:\n- if fields and isinstance(fields[0], v1.ModelField):\n+ if fields and isinstance(fields[0], may_v1.ModelField):\n+ from fastapi._compat import v1\n+\n return v1.create_body_model(fields=fields, model_name=model_name)\n else:\n assert PYDANTIC_V2\n@@ -123,7 +134,9 @@ def create_body_model(\n def get_annotation_from_field_info(\n annotation: Any, field_info: FieldInfo, field_name: str\n ) -> Any:\n- if isinstance(field_info, v1.FieldInfo):\n+ if isinstance(field_info, may_v1.FieldInfo):\n+ from fastapi._compat import v1\n+\n return v1.get_annotation_from_field_info(\n annotation=annotation, field_info=field_info, field_name=field_name\n )\n@@ -137,7 +150,9 @@ def get_annotation_from_field_info(\n \n \n def is_bytes_field(field: ModelField) -> bool:\n- if isinstance(field, v1.ModelField):\n+ if isinstance(field, may_v1.ModelField):\n+ from fastapi._compat import v1\n+\n return v1.is_bytes_field(field)\n else:\n assert PYDANTIC_V2\n@@ -147,7 +162,9 @@ def is_bytes_field(field: ModelField) -> bool:\n \n \n def is_bytes_sequence_field(field: ModelField) -> bool:\n- if isinstance(field, v1.ModelField):\n+ if isinstance(field, may_v1.ModelField):\n+ from fastapi._compat import v1\n+\n return v1.is_bytes_sequence_field(field)\n else:\n assert PYDANTIC_V2\n@@ -157,7 +174,9 @@ def is_bytes_sequence_field(field: ModelField) -> bool:\n \n \n def is_scalar_field(field: ModelField) -> bool:\n- if isinstance(field, v1.ModelField):\n+ if isinstance(field, may_v1.ModelField):\n+ from fastapi._compat import v1\n+\n return v1.is_scalar_field(field)\n else:\n assert PYDANTIC_V2\n@@ -167,7 +186,9 @@ def is_scalar_field(field: ModelField) -> bool:\n \n \n def is_scalar_sequence_field(field: ModelField) -> bool:\n- if isinstance(field, v1.ModelField):\n+ if isinstance(field, may_v1.ModelField):\n+ from fastapi._compat import v1\n+\n return v1.is_scalar_sequence_field(field)\n else:\n assert PYDANTIC_V2\n@@ -177,7 +198,9 @@ def is_scalar_sequence_field(field: ModelField) -> bool:\n \n \n def is_sequence_field(field: ModelField) -> bool:\n- if isinstance(field, v1.ModelField):\n+ if isinstance(field, may_v1.ModelField):\n+ from fastapi._compat import v1\n+\n return v1.is_sequence_field(field)\n else:\n assert PYDANTIC_V2\n@@ -187,7 +210,9 @@ def is_sequence_field(field: ModelField) -> bool:\n \n \n def serialize_sequence_value(*, field: ModelField, value: Any) -> Sequence[Any]:\n- if isinstance(field, v1.ModelField):\n+ if isinstance(field, may_v1.ModelField):\n+ from fastapi._compat import v1\n+\n return v1.serialize_sequence_value(field=field, value=value)\n else:\n assert PYDANTIC_V2\n@@ -197,7 +222,9 @@ def serialize_sequence_value(*, field: ModelField, value: Any) -> Sequence[Any]:\n \n \n def _model_rebuild(model: Type[BaseModel]) -> None:\n- if lenient_issubclass(model, v1.BaseModel):\n+ if lenient_issubclass(model, may_v1.BaseModel):\n+ from fastapi._compat import v1\n+\n v1._model_rebuild(model)\n elif PYDANTIC_V2:\n from . import v2\n@@ -206,9 +233,18 @@ def _model_rebuild(model: Type[BaseModel]) -> None:\n \n \n def get_compat_model_name_map(fields: List[ModelField]) -> ModelNameMap:\n- v1_model_fields = [field for field in fields if isinstance(field, v1.ModelField)]\n- v1_flat_models = v1.get_flat_models_from_fields(v1_model_fields, known_models=set()) # type: ignore[attr-defined]\n- all_flat_models = v1_flat_models\n+ v1_model_fields = [\n+ field for field in fields if isinstance(field, may_v1.ModelField)\n+ ]\n+ if v1_model_fields:\n+ from fastapi._compat import v1\n+\n+ v1_flat_models = v1.get_flat_models_from_fields(\n+ v1_model_fields, known_models=set()\n+ )\n+ all_flat_models = v1_flat_models\n+ else:\n+ all_flat_models = set()\n if PYDANTIC_V2:\n from . import v2\n \n@@ -222,6 +258,8 @@ def get_compat_model_name_map(fields: List[ModelField]) -> ModelNameMap:\n \n model_name_map = v2.get_model_name_map(all_flat_models)\n return model_name_map\n+ from fastapi._compat import v1\n+\n model_name_map = v1.get_model_name_map(all_flat_models)\n return model_name_map\n \n@@ -232,17 +270,35 @@ def get_definitions(\n model_name_map: ModelNameMap,\n separate_input_output_schemas: bool = True,\n ) -> Tuple[\n- Dict[Tuple[ModelField, Literal[\"validation\", \"serialization\"]], v1.JsonSchemaValue],\n+ Dict[\n+ Tuple[ModelField, Literal[\"validation\", \"serialization\"]],\n+ may_v1.JsonSchemaValue,\n+ ],\n Dict[str, Dict[str, Any]],\n ]:\n- v1_fields = [field for field in fields if isinstance(field, v1.ModelField)]\n- v1_field_maps, v1_definitions = v1.get_definitions(\n- fields=v1_fields,\n- model_name_map=model_name_map,\n- separate_input_output_schemas=separate_input_output_schemas,\n- )\n- if not PYDANTIC_V2:\n- return v1_field_maps, v1_definitions\n+ if sys.version_info < (3, 14):\n+ v1_fields = [field for field in fields if isinstance(field, may_v1.ModelField)]\n+ v1_field_maps, v1_definitions = may_v1.get_definitions(\n+ fields=v1_fields,\n+ model_name_map=model_name_map,\n+ separate_input_output_schemas=separate_input_output_schemas,\n+ )\n+ if not PYDANTIC_V2:\n+ return v1_field_maps, v1_definitions\n+ else:\n+ from . import v2\n+\n+ v2_fields = [field for field in fields if isinstance(field, v2.ModelField)]\n+ v2_field_maps, v2_definitions = v2.get_definitions(\n+ fields=v2_fields,\n+ model_name_map=model_name_map,\n+ separate_input_output_schemas=separate_input_output_schemas,\n+ )\n+ all_definitions = {**v1_definitions, **v2_definitions}\n+ all_field_maps = {**v1_field_maps, **v2_field_maps}\n+ return all_field_maps, all_definitions\n+\n+ # Pydantic v1 is not supported since Python 3.14\n else:\n from . import v2\n \n@@ -252,21 +308,22 @@ def get_definitions(\n model_name_map=model_name_map,\n separate_input_output_schemas=separate_input_output_schemas,\n )\n- all_definitions = {**v1_definitions, **v2_definitions}\n- all_field_maps = {**v1_field_maps, **v2_field_maps}\n- return all_field_maps, all_definitions\n+ return v2_field_maps, v2_definitions\n \n \n def get_schema_from_model_field(\n *,\n field: ModelField,\n model_name_map: ModelNameMap,\n field_mapping: Dict[\n- Tuple[ModelField, Literal[\"validation\", \"serialization\"]], v1.JsonSchemaValue\n+ Tuple[ModelField, Literal[\"validation\", \"serialization\"]],\n+ may_v1.JsonSchemaValue,\n ],\n separate_input_output_schemas: bool = True,\n ) -> Dict[str, Any]:\n- if isinstance(field, v1.ModelField):\n+ if isinstance(field, may_v1.ModelField):\n+ from fastapi._compat import v1\n+\n return v1.get_schema_from_model_field(\n field=field,\n model_name_map=model_name_map,\n@@ -286,7 +343,7 @@ def get_schema_from_model_field(\n \n \n def _is_model_field(value: Any) -> bool:\n- if isinstance(value, v1.ModelField):\n+ if isinstance(value, may_v1.ModelField):\n return True\n elif PYDANTIC_V2:\n from . import v2\n@@ -296,7 +353,7 @@ def _is_model_field(value: Any) -> bool:\n \n \n def _is_model_class(value: Any) -> bool:\n- if lenient_issubclass(value, v1.BaseModel):\n+ if lenient_issubclass(value, may_v1.BaseModel):\n return True\n elif PYDANTIC_V2:\n from . import v2" }, { "filename": "fastapi/_compat/may_v1.py", "status": "added", "additions": 123, "deletions": 0, "changes": 123, "patch": "@@ -0,0 +1,123 @@\n+import sys\n+from typing import Any, Dict, List, Literal, Sequence, Tuple, Type, Union\n+\n+from fastapi.types import ModelNameMap\n+\n+if sys.version_info >= (3, 14):\n+\n+ class AnyUrl:\n+ pass\n+\n+ class BaseConfig:\n+ pass\n+\n+ class BaseModel:\n+ pass\n+\n+ class Color:\n+ pass\n+\n+ class CoreSchema:\n+ pass\n+\n+ class ErrorWrapper:\n+ pass\n+\n+ class FieldInfo:\n+ pass\n+\n+ class GetJsonSchemaHandler:\n+ pass\n+\n+ class JsonSchemaValue:\n+ pass\n+\n+ class ModelField:\n+ pass\n+\n+ class NameEmail:\n+ pass\n+\n+ class RequiredParam:\n+ pass\n+\n+ class SecretBytes:\n+ pass\n+\n+ class SecretStr:\n+ pass\n+\n+ class Undefined:\n+ pass\n+\n+ class UndefinedType:\n+ pass\n+\n+ class Url:\n+ pass\n+\n+ from .v2 import ValidationError, create_model\n+\n+ def get_definitions(\n+ *,\n+ fields: List[ModelField],\n+ model_name_map: ModelNameMap,\n+ separate_input_output_schemas: bool = True,\n+ ) -> Tuple[\n+ Dict[\n+ Tuple[ModelField, Literal[\"validation\", \"serialization\"]], JsonSchemaValue\n+ ],\n+ Dict[str, Dict[str, Any]],\n+ ]:\n+ return {}, {} # pragma: no cover\n+\n+\n+else:\n+ from .v1 import AnyUrl as AnyUrl\n+ from .v1 import BaseConfig as BaseConfig\n+ from .v1 import BaseModel as BaseModel\n+ from .v1 import Color as Color\n+ from .v1 import CoreSchema as CoreSchema\n+ from .v1 import ErrorWrapper as ErrorWrapper\n+ from .v1 import FieldInfo as FieldInfo\n+ from .v1 import GetJsonSchemaHandler as GetJsonSchemaHandler\n+ from .v1 import JsonSchemaValue as JsonSchemaValue\n+ from .v1 import ModelField as ModelField\n+ from .v1 import NameEmail as NameEmail\n+ from .v1 import RequiredParam as RequiredParam\n+ from .v1 import SecretBytes as SecretBytes\n+ from .v1 import SecretStr as SecretStr\n+ from .v1 import Undefined as Undefined\n+ from .v1 import UndefinedType as UndefinedType\n+ from .v1 import Url as Url\n+ from .v1 import ValidationError, create_model\n+ from .v1 import get_definitions as get_definitions\n+\n+\n+RequestErrorModel: Type[BaseModel] = create_model(\"Request\")\n+\n+\n+def _normalize_errors(errors: Sequence[Any]) -> List[Dict[str, Any]]:\n+ use_errors: List[Any] = []\n+ for error in errors:\n+ if isinstance(error, ErrorWrapper):\n+ new_errors = ValidationError( # type: ignore[call-arg]\n+ errors=[error], model=RequestErrorModel\n+ ).errors()\n+ use_errors.extend(new_errors)\n+ elif isinstance(error, list):\n+ use_errors.extend(_normalize_errors(error))\n+ else:\n+ use_errors.append(error)\n+ return use_errors\n+\n+\n+def _regenerate_error_with_loc(\n+ *, errors: Sequence[Any], loc_prefix: Tuple[Union[str, int], ...]\n+) -> List[Dict[str, Any]]:\n+ updated_loc_errors: List[Any] = [\n+ {**err, \"loc\": loc_prefix + err.get(\"loc\", ())}\n+ for err in _normalize_errors(errors)\n+ ]\n+\n+ return updated_loc_errors" }, { "filename": "fastapi/_compat/shared.py", "status": "modified", "additions": 6, "deletions": 4, "changes": 10, "patch": "@@ -16,7 +16,7 @@\n Union,\n )\n \n-from fastapi._compat import v1\n+from fastapi._compat import may_v1\n from fastapi.types import UnionType\n from pydantic import BaseModel\n from pydantic.version import VERSION as PYDANTIC_VERSION\n@@ -98,7 +98,9 @@ def value_is_sequence(value: Any) -> bool:\n \n def _annotation_is_complex(annotation: Union[Type[Any], None]) -> bool:\n return (\n- lenient_issubclass(annotation, (BaseModel, v1.BaseModel, Mapping, UploadFile))\n+ lenient_issubclass(\n+ annotation, (BaseModel, may_v1.BaseModel, Mapping, UploadFile)\n+ )\n or _annotation_is_sequence(annotation)\n or is_dataclass(annotation)\n )\n@@ -195,12 +197,12 @@ def is_uploadfile_sequence_annotation(annotation: Any) -> bool:\n \n \n def annotation_is_pydantic_v1(annotation: Any) -> bool:\n- if lenient_issubclass(annotation, v1.BaseModel):\n+ if lenient_issubclass(annotation, may_v1.BaseModel):\n return True\n origin = get_origin(annotation)\n if origin is Union or origin is UnionType:\n for arg in get_args(annotation):\n- if lenient_issubclass(arg, v1.BaseModel):\n+ if lenient_issubclass(arg, may_v1.BaseModel):\n return True\n if field_annotation_is_sequence(annotation):\n for sub_annotation in get_args(annotation):" }, { "filename": "fastapi/_compat/v1.py", "status": "modified", "additions": 6, "deletions": 28, "changes": 34, "patch": "@@ -54,13 +54,15 @@\n from pydantic.schema import TypeModelSet as TypeModelSet\n from pydantic.schema import (\n field_schema,\n- get_flat_models_from_fields,\n model_process_schema,\n )\n from pydantic.schema import (\n get_annotation_from_field_info as get_annotation_from_field_info,\n )\n from pydantic.schema import get_flat_models_from_field as get_flat_models_from_field\n+ from pydantic.schema import (\n+ get_flat_models_from_fields as get_flat_models_from_fields,\n+ )\n from pydantic.schema import get_model_name_map as get_model_name_map\n from pydantic.types import SecretBytes as SecretBytes\n from pydantic.types import SecretStr as SecretStr\n@@ -99,7 +101,6 @@\n from pydantic.v1.schema import TypeModelSet as TypeModelSet\n from pydantic.v1.schema import (\n field_schema,\n- get_flat_models_from_fields,\n model_process_schema,\n )\n from pydantic.v1.schema import (\n@@ -108,6 +109,9 @@\n from pydantic.v1.schema import (\n get_flat_models_from_field as get_flat_models_from_field,\n )\n+ from pydantic.v1.schema import (\n+ get_flat_models_from_fields as get_flat_models_from_fields,\n+ )\n from pydantic.v1.schema import get_model_name_map as get_model_name_map\n from pydantic.v1.types import ( # type: ignore[assignment]\n SecretBytes as SecretBytes,\n@@ -215,32 +219,6 @@ def is_pv1_scalar_sequence_field(field: ModelField) -> bool:\n return False\n \n \n-def _normalize_errors(errors: Sequence[Any]) -> List[Dict[str, Any]]:\n- use_errors: List[Any] = []\n- for error in errors:\n- if isinstance(error, ErrorWrapper):\n- new_errors = ValidationError( # type: ignore[call-arg]\n- errors=[error], model=RequestErrorModel\n- ).errors()\n- use_errors.extend(new_errors)\n- elif isinstance(error, list):\n- use_errors.extend(_normalize_errors(error))\n- else:\n- use_errors.append(error)\n- return use_errors\n-\n-\n-def _regenerate_error_with_loc(\n- *, errors: Sequence[Any], loc_prefix: Tuple[Union[str, int], ...]\n-) -> List[Dict[str, Any]]:\n- updated_loc_errors: List[Any] = [\n- {**err, \"loc\": loc_prefix + err.get(\"loc\", ())}\n- for err in _normalize_errors(errors)\n- ]\n-\n- return updated_loc_errors\n-\n-\n def _model_rebuild(model: Type[BaseModel]) -> None:\n model.update_forward_refs()" }, { "filename": "fastapi/_compat/v2.py", "status": "modified", "additions": 2, "deletions": 2, "changes": 4, "patch": "@@ -15,7 +15,7 @@\n cast,\n )\n \n-from fastapi._compat import shared, v1\n+from fastapi._compat import may_v1, shared\n from fastapi.openapi.constants import REF_TEMPLATE\n from fastapi.types import IncEx, ModelNameMap\n from pydantic import BaseModel, TypeAdapter, create_model\n@@ -116,7 +116,7 @@ def validate(\n None,\n )\n except ValidationError as exc:\n- return None, v1._regenerate_error_with_loc(\n+ return None, may_v1._regenerate_error_with_loc(\n errors=exc.errors(include_url=False), loc_prefix=loc\n )" }, { "filename": "fastapi/dependencies/utils.py", "status": "modified", "additions": 12, "deletions": 11, "changes": 23, "patch": "@@ -43,9 +43,9 @@\n is_uploadfile_or_nonable_uploadfile_annotation,\n is_uploadfile_sequence_annotation,\n lenient_issubclass,\n+ may_v1,\n sequence_types,\n serialize_sequence_value,\n- v1,\n value_is_sequence,\n )\n from fastapi._compat.shared import annotation_is_pydantic_v1\n@@ -380,7 +380,7 @@ def analyze_param(\n fastapi_annotations = [\n arg\n for arg in annotated_args[1:]\n- if isinstance(arg, (FieldInfo, v1.FieldInfo, params.Depends))\n+ if isinstance(arg, (FieldInfo, may_v1.FieldInfo, params.Depends))\n ]\n fastapi_specific_annotations = [\n arg\n@@ -397,21 +397,21 @@ def analyze_param(\n )\n ]\n if fastapi_specific_annotations:\n- fastapi_annotation: Union[FieldInfo, v1.FieldInfo, params.Depends, None] = (\n- fastapi_specific_annotations[-1]\n- )\n+ fastapi_annotation: Union[\n+ FieldInfo, may_v1.FieldInfo, params.Depends, None\n+ ] = fastapi_specific_annotations[-1]\n else:\n fastapi_annotation = None\n # Set default for [NAME_REDACTED]\n- if isinstance(fastapi_annotation, (FieldInfo, v1.FieldInfo)):\n+ if isinstance(fastapi_annotation, (FieldInfo, may_v1.FieldInfo)):\n # Copy `field_info` because we mutate `field_info.default` below.\n field_info = copy_field_info(\n field_info=fastapi_annotation, annotation=use_annotation\n )\n assert field_info.default in {\n Undefined,\n- v1.Undefined,\n- } or field_info.default in {RequiredParam, v1.RequiredParam}, (\n+ may_v1.Undefined,\n+ } or field_info.default in {RequiredParam, may_v1.RequiredParam}, (\n f\"`{field_info.__class__.__name__}` default value cannot be set in\"\n f\" `Annotated` for {param_name!r}. Set the default value with `=` instead.\"\n )\n@@ -435,7 +435,7 @@ def analyze_param(\n )\n depends = value\n # [NAME_REDACTED] from default value\n- elif isinstance(value, (FieldInfo, v1.FieldInfo)):\n+ elif isinstance(value, (FieldInfo, may_v1.FieldInfo)):\n assert field_info is None, (\n \"Cannot specify FastAPI annotations in `Annotated` and default value\"\n f\" together for {param_name!r}\"\n@@ -524,7 +524,8 @@ def analyze_param(\n type_=use_annotation_from_field_info,\n default=field_info.default,\n alias=alias,\n- required=field_info.default in (RequiredParam, v1.RequiredParam, Undefined),\n+ required=field_info.default\n+ in (RequiredParam, may_v1.RequiredParam, Undefined),\n field_info=field_info,\n )\n if is_path_param:\n@@ -741,7 +742,7 @@ def _validate_value_with_model_field(\n if _is_error_wrapper(errors_): # type: ignore[arg-type]\n return None, [errors_]\n elif isinstance(errors_, list):\n- new_errors = v1._regenerate_error_with_loc(errors=errors_, loc_prefix=())\n+ new_errors = may_v1._regenerate_error_with_loc(errors=errors_, loc_prefix=())\n return None, new_errors\n else:\n return v_, []" }, { "filename": "fastapi/encoders.py", "status": "modified", "additions": 9, "deletions": 9, "changes": 18, "patch": "@@ -17,7 +17,7 @@\n from typing import Any, Callable, Dict, List, Optional, Tuple, Type, Union\n from uuid import UUID\n \n-from fastapi._compat import v1\n+from fastapi._compat import may_v1\n from fastapi.types import IncEx\n from pydantic import BaseModel\n from pydantic.color import Color\n@@ -59,7 +59,7 @@ def decimal_encoder(dec_value: Decimal) -> Union[int, float]:\n ENCODERS_BY_TYPE: Dict[Type[Any], Callable[[Any], Any]] = {\n bytes: lambda o: o.decode(),\n Color: str,\n- v1.Color: str,\n+ may_v1.Color: str,\n datetime.date: isoformat,\n datetime.datetime: isoformat,\n datetime.time: isoformat,\n@@ -76,19 +76,19 @@ def decimal_encoder(dec_value: Decimal) -> Union[int, float]:\n IPv6Interface: str,\n IPv6Network: str,\n NameEmail: str,\n- v1.NameEmail: str,\n+ may_v1.NameEmail: str,\n Path: str,\n Pattern: lambda o: o.pattern,\n SecretBytes: str,\n- v1.SecretBytes: str,\n+ may_v1.SecretBytes: str,\n SecretStr: str,\n- v1.SecretStr: str,\n+ may_v1.SecretStr: str,\n set: list,\n UUID: str,\n Url: str,\n- v1.Url: str,\n+ may_v1.Url: str,\n AnyUrl: str,\n- v1.AnyUrl: str,\n+ may_v1.AnyUrl: str,\n }\n \n \n@@ -220,10 +220,10 @@ def jsonable_encoder(\n include = set(include)\n if exclude is not None and not isinstance(exclude, (set, dict)):\n exclude = set(exclude)\n- if isinstance(obj, (BaseModel, v1.BaseModel)):\n+ if isinstance(obj, (BaseModel, may_v1.BaseModel)):\n # TODO: remove when deprecating Pydantic v1\n encoders: Dict[Any, Any] = {}\n- if isinstance(obj, v1.BaseModel):\n+ if isinstance(obj, may_v1.BaseModel):\n encoders = getattr(obj.__config__, \"json_encoders\", {}) # type: ignore[attr-defined]\n if custom_encoder:\n encoders = {**encoders, **custom_encoder}" }, { "filename": "fastapi/temp_pydantic_v1_params.py", "status": "modified", "additions": 1, "deletions": 1, "changes": 2, "patch": "@@ -5,8 +5,8 @@\n from fastapi.params import ParamTypes\n from typing_extensions import Annotated, deprecated\n \n+from ._compat.may_v1 import FieldInfo, Undefined\n from ._compat.shared import PYDANTIC_VERSION_MINOR_TUPLE\n-from ._compat.v1 import FieldInfo, Undefined\n \n _Unset: Any = Undefined" }, { "filename": "fastapi/utils.py", "status": "modified", "additions": 11, "deletions": 4, "changes": 15, "patch": "@@ -25,7 +25,7 @@\n Validator,\n annotation_is_pydantic_v1,\n lenient_issubclass,\n- v1,\n+ may_v1,\n )\n from fastapi.datastructures import DefaultPlaceholder, DefaultType\n from pydantic import BaseModel\n@@ -87,8 +87,8 @@ def create_model_field(\n ) -> ModelField:\n class_validators = class_validators or {}\n \n- v1_model_config = v1.BaseConfig\n- v1_field_info = field_info or v1.FieldInfo()\n+ v1_model_config = may_v1.BaseConfig\n+ v1_field_info = field_info or may_v1.FieldInfo()\n v1_kwargs = {\n \"name\": name,\n \"field_info\": v1_field_info,\n@@ -102,9 +102,11 @@ def create_model_field(\n \n if (\n annotation_is_pydantic_v1(type_)\n- or isinstance(field_info, v1.FieldInfo)\n+ or isinstance(field_info, may_v1.FieldInfo)\n or version == \"1\"\n ):\n+ from fastapi._compat import v1\n+\n try:\n return v1.ModelField(**v1_kwargs) # type: ignore[no-any-return]\n except RuntimeError:\n@@ -122,6 +124,8 @@ def create_model_field(\n raise fastapi.exceptions.FastAPIError(_invalid_args_message) from None\n # Pydantic v2 is not installed, but it's not a Pydantic v1 ModelField, it could be\n # a Pydantic v1 type, like a constrained int\n+ from fastapi._compat import v1\n+\n try:\n return v1.ModelField(**v1_kwargs) # type: ignore[no-any-return]\n except RuntimeError:\n@@ -138,6 +142,9 @@ def create_cloned_field(\n \n if isinstance(field, v2.ModelField):\n return field\n+\n+ from fastapi._compat import v1\n+\n # cloned_types caches already cloned types to support recursive models and improve\n # performance by [NAME_REDACTED] cloned_types is None:" }, { "filename": "tests/test_compat.py", "status": "modified", "additions": 10, "deletions": 2, "changes": 12, "patch": "@@ -7,7 +7,7 @@\n get_cached_model_fields,\n is_scalar_field,\n is_uploadfile_sequence_annotation,\n- v1,\n+ may_v1,\n )\n from fastapi._compat.shared import is_bytes_sequence_annotation\n from fastapi.testclient import TestClient\n@@ -27,7 +27,10 @@ def test_model_field_default_required():\n assert field.default is Undefined\n \n \n+[USER_REDACTED]_py_lt_314\n def test_v1_plain_validator_function():\n+ from fastapi._compat import v1\n+\n # For coverage\n def func(v): # pragma: no cover\n return v\n@@ -135,6 +138,8 @@ def test_is_uploadfile_sequence_annotation():\n \n [USER_REDACTED]_py_lt_314\n def test_is_pv1_scalar_field():\n+ from fastapi._compat import v1\n+\n # For coverage\n class Model(v1.BaseModel):\n foo: Union[str, Dict[str, Any]]\n@@ -143,8 +148,11 @@ class Model(v1.BaseModel):\n assert not is_scalar_field(fields[0])\n \n \n+[USER_REDACTED]_py_lt_314\n def test_get_model_fields_cached():\n- class Model(v1.BaseModel):\n+ from fastapi._compat import v1\n+\n+ class Model(may_v1.BaseModel):\n foo: str\n \n non_cached_fields = v1.get_model_fields(Model)" }, { "filename": "tests/test_get_model_definitions_formfeed_escape.py", "status": "modified", "additions": 2, "deletions": 1, "changes": 3, "patch": "@@ -5,7 +5,6 @@\n import pydantic.schema\n import pytest\n from fastapi import FastAPI\n-from fastapi._compat import v1\n from pydantic import BaseModel\n from starlette.testclient import TestClient\n \n@@ -165,6 +164,8 @@ def test_model_description_escaped_with_formfeed(sort_reversed: bool):\n \n Test `get_model_definitions` with models passed in different order.\n \"\"\"\n+ from fastapi._compat import v1\n+\n all_fields = fastapi.openapi.utils.get_fields_from_routes(app.routes)\n \n flat_models = v1.get_flat_models_from_fields(all_fields, known_models=set())" }, { "filename": "tests/test_response_model_as_return_annotation.py", "status": "modified", "additions": 5, "deletions": 1, "changes": 6, "patch": "@@ -2,12 +2,13 @@\n \n import pytest\n from fastapi import FastAPI\n-from fastapi._compat import v1\n from fastapi.exceptions import FastAPIError, ResponseValidationError\n from fastapi.responses import JSONResponse, Response\n from fastapi.testclient import TestClient\n from pydantic import BaseModel\n \n+from tests.utils import needs_pydanticv1\n+\n \n class BaseUser(BaseModel):\n name: str\n@@ -511,7 +512,10 @@ def read_root() -> Union[Response, None]:\n \n \n # TODO: remove when dropping Pydantic v1 support\n+[USER_REDACTED]_pydanticv1\n def test_invalid_response_model_field_pv1():\n+ from fastapi._compat import v1\n+\n app = FastAPI()\n \n class Model(v1.BaseModel):" } ], "reviews": [ { "id": 3340529409, "user": "user_84458f05cf3c", "state": "COMMENTED", "body": null, "submitted_at": "2025-10-15T13:52:08+00:00" }, { "id": 3356127316, "user": "user_2a237e38e06b", "state": "APPROVED", "body": "Awesome, thank you [USER_REDACTED]! 🙌 \n\nI checked and confirmed that on Python 3.14, if users try to use Pydantic v1 they still get a warning on their own code, but not on older versions. So we're good to go! 🚀", "submitted_at": "2025-10-20T11:25:49+00:00" } ], "review_comments": [ { "id": 2432655612, "user": "user_84458f05cf3c", "body": "Probably better to check directly for Pydantic 2.12.0+ ?\n\nThen again, Pydantic themselves say \n\n> The core functionality of Pydantic V1 is not compatible with Python 3.14 or greater.", "path": "fastapi/_compat/may_v1.py", "line": 6, "side": "RIGHT", "created_at": "2025-10-15T13:52:08+00:00" } ], "meta": { "languages": [ "py" ], "touches_tests": true, "review_state_summary": { "COMMENTED": 1, "APPROVED": 1 }, "meaningful_comment_count": 1, "has_approval": true, "has_changes_requested": false, "total_review_comments": 1 } } { "_id": "adbcb0fa3b03792b", "_schema_version": "1.0", "_cleaned_at": "2026-02-12T07:46:51.702905+00:00", "repo": "tiangolo/fastapi", "repo_url": "https://github.com/fastapi/fastapi", "license_name": "MIT License", "license_spdx": "MIT", "pr_number": 14110, "title": "⬆️ Add support for Python 3.14", "body": "Python 3.14.0 is supposed to be released on October 7th, 2 weeks from now.\n\nWe'll need to merge this PR with https://github.com/fastapi/fastapi/pull/14036\n\nNote: probably requires https://github.com/fastapi/sqlmodel/pull/1578 first", "author": "user_84458f05cf3c", "created_at": "2025-09-24T13:37:11+00:00", "merged_at": "2025-09-24T15:58:06+00:00", "base_branch": "feature/py314", "head_branch": "feature/314", "additions": 10, "deletions": 1, "changed_files": 2, "files": [ { "filename": ".github/workflows/test.yml", "status": "modified", "additions": 9, "deletions": 1, "changes": 10, "patch": "@@ -48,13 +48,17 @@ jobs:\n strategy:\n matrix:\n python-version:\n+ - \"3.14\"\n - \"3.13\"\n - \"3.12\"\n - \"3.11\"\n - \"3.10\"\n - \"3.9\"\n - \"3.8\"\n pydantic-version: [\"pydantic-v1\", \"pydantic-v2\"]\n+ exclude:\n+ - python-version: \"3.14\"\n+ pydantic-version: \"pydantic-v1\"\n fail-fast: false\n steps:\n - name: [NAME_REDACTED] context\n@@ -66,6 +70,7 @@ jobs:\n uses: actions/setup-python@v6\n with:\n python-version: ${{ matrix.python-version }}\n+ allow-prereleases: true\n - name: Setup uv\n uses: astral-sh/setup-uv@v6\n with:\n@@ -74,13 +79,16 @@ jobs:\n cache-dependency-glob: |\n requirements**.txt\n pyproject.toml\n+ - name: [NAME_REDACTED] 2.12.0a1 for Python 3.14\n+ if: matrix.python-version == '3.14'\n+ run: uv pip install --pre \"pydantic==2.12.0a1\"\n - name: [NAME_REDACTED]\n run: uv pip install -r requirements-tests.txt\n - name: [NAME_REDACTED] v1\n if: matrix.pydantic-version == 'pydantic-v1'\n run: uv pip install \"pydantic>=1.10.0,<2.0.0\"\n - name: [NAME_REDACTED] v2\n- if: matrix.pydantic-version == 'pydantic-v2'\n+ if: matrix.pydantic-version == 'pydantic-v2' && matrix.python-version != '3.14'\n run: uv pip install --upgrade \"pydantic>=2.0.2,<3.0.0\"\n # TODO: Remove this once Python 3.8 is no longer supported\n - name: Install older AnyIO in Python 3.8" }, { "filename": "pyproject.toml", "status": "modified", "additions": 1, "deletions": 0, "changes": 1, "patch": "@@ -39,6 +39,7 @@ classifiers = [\n \"[NAME_REDACTED] :: Python :: 3.11\",\n \"[NAME_REDACTED] :: Python :: 3.12\",\n \"[NAME_REDACTED] :: Python :: 3.13\",\n+ \"[NAME_REDACTED] :: Python :: 3.14\",\n \"Topic :: Internet :: WWW/HTTP :: HTTP Servers\",\n \"Topic :: Internet :: WWW/HTTP\",\n ]" } ], "reviews": [ { "id": 3263267345, "user": "user_84458f05cf3c", "state": "COMMENTED", "body": null, "submitted_at": "2025-09-24T14:39:21+00:00" }, { "id": 3263268300, "user": "user_84458f05cf3c", "state": "COMMENTED", "body": null, "submitted_at": "2025-09-24T14:39:36+00:00" } ], "review_comments": [ { "id": 2376037999, "user": "user_84458f05cf3c", "body": "This can be removed when a stable Pydantic 2.12 release is available.", "path": ".github/workflows/test.yml", "line": 84, "side": "RIGHT", "created_at": "2025-09-24T14:39:21+00:00" }, { "id": 2376038699, "user": "user_84458f05cf3c", "body": "This can be removed when Python 3.14 is officially available.", "path": ".github/workflows/test.yml", "line": 73, "side": "RIGHT", "created_at": "2025-09-24T14:39:36+00:00" } ], "meta": { "languages": [ "toml", "yml" ], "touches_tests": false, "review_state_summary": { "COMMENTED": 2 }, "meaningful_comment_count": 2, "has_approval": false, "has_changes_requested": false, "total_review_comments": 2 } } { "_id": "5f09dd6ea20a4efd", "_schema_version": "1.0", "_cleaned_at": "2026-02-12T07:46:51.718504+00:00", "repo": "tiangolo/fastapi", "repo_url": "https://github.com/fastapi/fastapi", "license_name": "MIT License", "license_spdx": "MIT", "pr_number": 14077, "title": "⬆️ [NAME_REDACTED] supported version range to >=0.40.0,<0.49.0", "body": "Starlette 0.48.0 introduced `HTTP_422_UNPROCESSABLE_CONTENT` as a new name for `HTTP_422_UNPROCESSABLE_ENTITY` and deprecated the old name due to RFC 9110; see https://github.com/Kludex/starlette/pull/2939.\n\nI updated all instances ~to the new name and increased the lower bound on the Starlette version~ to use the literal integer or string value `422`/`\"422\"` instead of either `HTTP_422_UNPROCESSABLE_CONTENT` or `HTTP_422_UNPROCESSABLE_ENTITY`, which makes FastAPI compatible with Starlette >=0.48 without deprecation warnings while preserving backwards compatibility with Starlette<0.48.\n\n[USER_REDACTED], FYI.", "author": "user_8bc414796ac7", "created_at": "2025-09-14T05:48:36+00:00", "merged_at": "2025-09-16T17:21:48+00:00", "base_branch": "master", "head_branch": "starlette-0.48", "additions": 7, "deletions": 8, "changed_files": 5, "files": [ { "filename": "docs_src/handling_errors/tutorial005.py", "status": "modified", "additions": 2, "deletions": 2, "changes": 4, "patch": "@@ -1,4 +1,4 @@\n-from fastapi import FastAPI, Request, status\n+from fastapi import FastAPI, Request\n from fastapi.encoders import jsonable_encoder\n from fastapi.exceptions import RequestValidationError\n from fastapi.responses import JSONResponse\n@@ -10,7 +10,7 @@\n [USER_REDACTED].exception_handler(RequestValidationError)\n async def validation_exception_handler(request: Request, exc: RequestValidationError):\n return JSONResponse(\n- status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,\n+ status_code=422,\n content=jsonable_encoder({\"detail\": exc.errors(), \"body\": exc.body}),\n )" }, { "filename": "fastapi/exception_handlers.py", "status": "modified", "additions": 2, "deletions": 2, "changes": 4, "patch": "@@ -5,7 +5,7 @@\n from starlette.exceptions import HTTPException\n from starlette.requests import Request\n from starlette.responses import JSONResponse, Response\n-from starlette.status import HTTP_422_UNPROCESSABLE_ENTITY, WS_1008_POLICY_VIOLATION\n+from starlette.status import WS_1008_POLICY_VIOLATION\n \n \n async def http_exception_handler(request: Request, exc: HTTPException) -> Response:\n@@ -21,7 +21,7 @@ async def request_validation_exception_handler(\n request: Request, exc: RequestValidationError\n ) -> JSONResponse:\n return JSONResponse(\n- status_code=HTTP_422_UNPROCESSABLE_ENTITY,\n+ status_code=422,\n content={\"detail\": jsonable_encoder(exc.errors())},\n )" }, { "filename": "fastapi/openapi/utils.py", "status": "modified", "additions": 1, "deletions": 2, "changes": 3, "patch": "@@ -35,7 +35,6 @@\n from pydantic import BaseModel\n from starlette.responses import JSONResponse\n from starlette.routing import BaseRoute\n-from starlette.status import HTTP_422_UNPROCESSABLE_ENTITY\n from typing_extensions import Literal\n \n validation_error_definition = {\n@@ -416,7 +415,7 @@ def get_openapi_path(\n )\n deep_dict_update(openapi_response, process_response)\n openapi_response[\"description\"] = description\n- http422 = str(HTTP_422_UNPROCESSABLE_ENTITY)\n+ http422 = \"422\"\n all_route_params = get_flat_params(route.dependant)\n if (all_route_params or route.body_field) and not any(\n status in operation[\"responses\"]" }, { "filename": "pyproject.toml", "status": "modified", "additions": 1, "deletions": 1, "changes": 2, "patch": "@@ -43,7 +43,7 @@ classifiers = [\n \"Topic :: Internet :: WWW/HTTP\",\n ]\n dependencies = [\n- \"starlette>=0.40.0,<0.48.0\",\n+ \"starlette>=0.40.0,<0.49.0\",\n \"pydantic>=1.7.4,!=1.8,!=1.8.1,!=2.0.0,!=2.0.1,!=2.1.0,<3.0.0\",\n \"typing-extensions>=4.8.0\",\n ]" }, { "filename": "tests/test_enforce_once_required_parameter.py", "status": "modified", "additions": 1, "deletions": 1, "changes": 2, "patch": "@@ -102,7 +102,7 @@ def test_schema():\n \n def test_get_invalid():\n response = client.get(\"/foo\")\n- assert response.status_code == status.HTTP_422_UNPROCESSABLE_ENTITY\n+ assert response.status_code == 422\n \n \n def test_get_valid():" } ], "reviews": [ { "id": 3224780252, "user": "user_84458f05cf3c", "state": "COMMENTED", "body": null, "submitted_at": "2025-09-15T13:58:01+00:00" }, { "id": 3228652666, "user": "user_8bc414796ac7", "state": "COMMENTED", "body": null, "submitted_at": "2025-09-16T09:21:29+00:00" }, { "id": 3228706900, "user": "user_f40080f73cb6", "state": "APPROVED", "body": null, "submitted_at": "2025-09-16T09:32:58+00:00" }, { "id": 3230983816, "user": "user_2a237e38e06b", "state": "APPROVED", "body": "Nice, thank you! 🚀 \n\nAnd thanks [USER_REDACTED] and [USER_REDACTED]! 🙌 \n\nThis will be available in FastAPI 0.116.2, released in the next hours.", "submitted_at": "2025-09-16T17:21:29+00:00" } ], "review_comments": [ { "id": 2349101580, "user": "user_84458f05cf3c", "body": "We have to be carefull here, this script is referenced in the docs [here](https://fastapi.tiangolo.com/tutorial/handling-errors/#use-the-requestvalidationerror-body), and by [NAME_REDACTED], the wrong line will be highlighted in the docs (used to be L14 which is now L16).\n\nAnyway, I don't think we need this comment here, or elsewhere where we're switching to 422. Let's just edit to `status_code=422` without the comments.", "path": "docs_src/handling_errors/tutorial005.py", "line": 13, "side": "RIGHT", "created_at": "2025-09-15T13:58:01+00:00" }, { "id": 2351646324, "user": "user_8bc414796ac7", "body": "> We have to be carefull here, this script is referenced in the docs [here](https://fastapi.tiangolo.com/tutorial/handling-errors/#use-the-requestvalidationerror-body), and by [NAME_REDACTED], the wrong line will be highlighted in the docs (used to be L14 which is now L16).\n> \n> Anyway, I don't think we need this comment here, or elsewhere where we're switching to 422. Let's just edit to `status_code=422` without the comments.\n\nThanks. Your comment-removal commit looks good.", "path": "docs_src/handling_errors/tutorial005.py", "line": 13, "side": "RIGHT", "created_at": "2025-09-16T09:21:29+00:00" } ], "meta": { "languages": [ "py", "toml" ], "touches_tests": true, "review_state_summary": { "COMMENTED": 2, "APPROVED": 2 }, "meaningful_comment_count": 2, "has_approval": true, "has_changes_requested": false, "total_review_comments": 2 } } { "_id": "78c7f9aca0402238", "_schema_version": "1.0", "_cleaned_at": "2026-02-12T07:46:51.718504+00:00", "repo": "tiangolo/fastapi", "repo_url": "https://github.com/fastapi/fastapi", "license_name": "MIT License", "license_spdx": "MIT", "pr_number": 14055, "title": "🛠️ Update `docs.py generate-readme` command to remove permalinks from headers", "body": "Currently `docs.py generate-readme` command copies content from `index.md` and that document contains permalinks for headers.\nThus, these permalinks are displayed when people read `README.md` on GitHub: https://github.com/fastapi/fastapi?tab=readme-ov-file#sponsors--sponsors-\n\nThis PR modifies `docs.py` script to remove permalinks when `README.md` is generated", "author": "user_29e85f9a8e75", "created_at": "2025-09-08T15:56:20+00:00", "merged_at": "2025-09-20T11:43:51+00:00", "base_branch": "master", "head_branch": "remove-permalinks-from-readme", "additions": 36, "deletions": 22, "changed_files": 2, "files": [ { "filename": "README.md", "status": "modified", "additions": 22, "deletions": 22, "changes": 44, "patch": "@@ -42,7 +42,7 @@ The key features are:\n \n * estimation based on tests on an internal development team, building production applications.\n \n-## Sponsors { #sponsors }\n+## Sponsors\n \n \n \n@@ -67,7 +67,7 @@ The key features are:\n \n Other sponsors\n \n-## Opinions { #opinions }\n+## Opinions\n \n \"_[...] I'm using **FastAPI** a ton these days. [...] I'm actually planning to use it for all of my team's **ML services at Microsoft**. Some of them are getting integrated into the core **Windows** product and some **Office** products._\"\n \n@@ -113,22 +113,22 @@ The key features are:\n \n ---\n \n-## **Typer**, the FastAPI of CLIs { #typer-the-fastapi-of-clis }\n+## **Typer**, the FastAPI of CLIs\n \n \n \n If you are building a CLI app to be used in the terminal instead of a web API, check out **Typer**.\n \n **Typer** is FastAPI's little sibling. And it's intended to be the **FastAPI of CLIs**. ⌨️ 🚀\n \n-## Requirements { #requirements }\n+## Requirements\n \n FastAPI stands on the shoulders of giants:\n \n * Starlette for the web parts.\n * Pydantic for the data parts.\n \n-## Installation { #installation }\n+## Installation\n \n Create and activate a virtual environment and then install FastAPI:\n \n@@ -144,9 +144,9 @@ $ pip install \"fastapi[standard]\"\n \n **Note**: Make sure you put `\"fastapi[standard]\"` in quotes to ensure it works in all terminals.\n \n-## Example { #example }\n+## Example\n \n-### Create it { #create-it }\n+### Create it\n \n Create a file `main.py` with:\n \n@@ -197,7 +197,7 @@ If you don't know, check the _\"In a hurry?\"_ section about \n \n-### Run it { #run-it }\n+### Run it\n \n Run the server with:\n \n@@ -239,7 +239,7 @@ You can read more about it in the \n \n-### Check it { #check-it }\n+### Check it\n \n Open your browser at http://127.0.0.1:8000/items/5?q=somequery.\n \n@@ -256,23 +256,23 @@ You already created an API that:\n * The _path_ `/items/{item_id}` has a _path parameter_ `item_id` that should be an `int`.\n * The _path_ `/items/{item_id}` has an optional `str` _query parameter_ `q`.\n \n-### Interactive API docs { #interactive-api-docs }\n+### Interactive API docs\n \n Now go to http://127.0.0.1:8000/docs.\n \n You will see the automatic interactive API documentation (provided by Swagger UI):\n \n ![Swagger UI](https://fastapi.tiangolo.com/img/index/index-01-swagger-ui-simple.png)\n \n-### Alternative API docs { #alternative-api-docs }\n+### Alternative API docs\n \n And now, go to http://127.0.0.1:8000/redoc.\n \n You will see the alternative automatic documentation (provided by ReDoc):\n \n ![ReDoc](https://fastapi.tiangolo.com/img/index/index-02-redoc-simple.png)\n \n-## Example upgrade { #example-upgrade }\n+## Example upgrade\n \n Now modify the file `main.py` to receive a body from a `PUT` request.\n \n@@ -310,7 +310,7 @@ def update_item(item_id: int, item: Item):\n \n The `fastapi dev` server should reload automatically.\n \n-### Interactive API docs upgrade { #interactive-api-docs-upgrade }\n+### Interactive API docs upgrade\n \n Now go to http://127.0.0.1:8000/docs.\n \n@@ -326,15 +326,15 @@ Now go to http://127.0.0.1:8000/redoc.\n \n * The alternative documentation will also reflect the new query parameter and body:\n \n ![ReDoc](https://fastapi.tiangolo.com/img/index/index-06-redoc-02.png)\n \n-### Recap { #recap }\n+### [NAME_REDACTED] summary, you declare **once** the types of parameters, body, etc. as function parameters.\n \n@@ -446,17 +446,17 @@ For a more complete example including more features, see the one of the fastest Python frameworks available, only below Starlette and Uvicorn themselves (used internally by FastAPI). (*)\n \n To understand more about it, see the section Benchmarks.\n \n-## Dependencies { #dependencies }\n+## [NAME_REDACTED] depends on Pydantic and Starlette.\n \n-### `standard` Dependencies { #standard-dependencies }\n+### `standard` [NAME_REDACTED] you install FastAPI with `pip install \"fastapi[standard]\"` it comes with the `standard` group of optional dependencies:\n \n@@ -476,15 +476,15 @@ Used by FastAPI:\n * `fastapi-cli[standard]` - to provide the `fastapi` command.\n * This includes `fastapi-cloud-cli`, which allows you to deploy your FastAPI application to [NAME_REDACTED].\n \n-### Without `standard` Dependencies { #without-standard-dependencies }\n+### Without `standard` [NAME_REDACTED] you don't want to include the `standard` optional dependencies, you can install with `pip install fastapi` instead of `pip install \"fastapi[standard]\"`.\n \n-### Without `fastapi-cloud-cli` { #without-fastapi-cloud-cli }\n+### Without `fastapi-cloud-cli`\n \n If you want to install FastAPI with the standard dependencies but without the `fastapi-cloud-cli`, you can install with `pip install \"fastapi[standard-no-fastapi-cloud-cli]\"`.\n \n-### [NAME_REDACTED] { #additional-optional-dependencies }\n+### [NAME_REDACTED]\n \n There are some additional dependencies you might want to install.\n \n@@ -498,6 +498,6 @@ Additional optional FastAPI dependencies:\n * orjson - Required if you want to use `ORJSONResponse`.\n * ujson - Required if you want to use `UJSONResponse`.\n \n-## License { #license }\n+## License\n \n This project is licensed under the terms of the MIT license." }, { "filename": "scripts/docs.py", "status": "modified", "additions": 14, "deletions": 0, "changes": 14, "patch": "@@ -44,6 +44,8 @@\n site_path = Path(\"site\").absolute()\n build_site_path = Path(\"site_build\").absolute()\n \n+header_with_permalink_pattern = re.compile(r\"^(#{1,6}) (.+?)(\\s*\\{\\s*#.*\\s*\\})\\s*$\")\n+\n \n [USER_REDACTED]_cache\n def is_mkdocs_insiders() -> bool:\n@@ -154,9 +156,21 @@ def build_lang(\n \"\"\"\n \n \n+def remove_header_permalinks(content: str):\n+ lines: list[str] = []\n+ for line in content.split(\"\\n\"):\n+ match = header_with_permalink_pattern.match(line)\n+ if match:\n+ hashes, title, *_ = match.groups()\n+ line = f\"{hashes} {title}\"\n+ lines.append(line)\n+ return \"\\n\".join(lines)\n+\n+\n def generate_readme_content() -> str:\n en_index = en_docs_path / \"docs\" / \"index.md\"\n content = en_index.read_text(\"utf-8\")\n+ content = remove_header_permalinks(content) # remove permalinks from headers\n match_pre = re.search(r\"\\n\\n\", content)\n match_start = re.search(r\"\", content)\n match_end = re.search(r\"\", content)" } ], "reviews": [ { "id": 3200107478, "user": "user_84458f05cf3c", "state": "APPROVED", "body": null, "submitted_at": "2025-09-09T08:36:36+00:00" }, { "id": 3249009749, "user": "user_2a237e38e06b", "state": "APPROVED", "body": "Excellent job, thanks [USER_REDACTED]! 🙌", "submitted_at": "2025-09-20T11:43:41+00:00" } ], "review_comments": [ { "id": 2365598913, "user": "user_2a237e38e06b", "body": "[NAME_REDACTED]! 🤯 😎", "path": "scripts/docs.py", "line": 47, "side": "RIGHT", "created_at": "2025-09-20T11:43:21+00:00" } ], "meta": { "languages": [ "md", "py" ], "touches_tests": false, "review_state_summary": { "APPROVED": 2 }, "meaningful_comment_count": 1, "has_approval": true, "has_changes_requested": false, "total_review_comments": 1 } } { "_id": "ddee61e58f2f7252", "_schema_version": "1.0", "_cleaned_at": "2026-02-12T07:46:51.718504+00:00", "repo": "tiangolo/fastapi", "repo_url": "https://github.com/fastapi/fastapi", "license_name": "MIT License", "license_spdx": "MIT", "pr_number": 14049, "title": "✅ Add LLM test file", "body": "\"Unit testing\" and documentation of LLM instructions in the general and in language specific prompts for the translations of the documentation.\n\nPrompt designers add tests here, other prompt designers can test for them while creating prompts.\n\nThis was previously part of #14015.", "author": "user_a924c018be02", "created_at": "2025-09-06T13:46:40+00:00", "merged_at": "2025-09-20T12:55:29+00:00", "base_branch": "master", "head_branch": "add-llm-test-file", "additions": 1006, "deletions": 0, "changed_files": 2, "files": [ { "filename": "docs/de/docs/_llm-test.md", "status": "added", "additions": 503, "deletions": 0, "changes": 503, "patch": "@@ -0,0 +1,503 @@\n+# LLM-Testdatei { #llm-test-file }\n+\n+[NAME_REDACTED] testet, ob das LLM, das die Dokumentation übersetzt, den `general_prompt` in `scripts/translate.py` und den sprachspezifischen Prompt in `docs/{language code}/llm-prompt.md` versteht. Der sprachspezifische Prompt wird an `general_prompt` angehängt.\n+\n+Hier hinzugefügte Tests werden von allen Erstellern sprachspezifischer Prompts gesehen.\n+\n+So verwenden:\n+\n+* Einen sprachspezifischen Prompt haben – `docs/{language code}/llm-prompt.md`.\n+* Eine frische Übersetzung dieses Dokuments in die gewünschte Zielsprache durchführen (siehe z. B. das Kommando `translate-page` der `translate.py`). Dadurch wird die Übersetzung unter `docs/{language code}/docs/_llm-test.md` erstellt.\n+* Prüfen Sie, ob in der Übersetzung alles in Ordnung ist.\n+* [NAME_REDACTED] bei [NAME_REDACTED] sprachsspezifischen Prompt, den allgemeinen Prompt oder das englische Dokument.\n+* [NAME_REDACTED] anschließend manuell die verbleibenden Probleme in der Übersetzung, sodass es eine gute Übersetzung ist.\n+* Übersetzen Sie erneut, nachdem die gute Übersetzung vorliegt. Das ideale Ergebnis wäre, dass das LLM an der Übersetzung keine Änderungen mehr vornimmt. Das bedeutet, dass der allgemeine Prompt und Ihr sprachsspezifischer Prompt so gut sind, wie sie sein können (Es wird manchmal ein paar scheinbar zufällige Änderungen machen, der Grund ist, dass LLMs keine deterministischen Algorithmen sind).\n+\n+[NAME_REDACTED]:\n+\n+## Codeschnipsel { #code-snippets}\n+\n+//// tab | Test\n+\n+Dies ist ein Codeschnipsel: `foo`. Und dies ist ein weiteres Codeschnipsel: `bar`. Und noch eins: `baz quux`.\n+\n+////\n+\n+//// tab | Info\n+\n+[NAME_REDACTED] von Codeschnipseln sollte unverändert bleiben.\n+\n+[NAME_REDACTED] `### Content of code snippets` im allgemeinen Prompt in `scripts/translate.py`.\n+\n+////\n+\n+## Anführungszeichen { #quotes }\n+\n+//// tab | Test\n+\n+Gestern schrieb mein Freund: „Wenn man unkorrekt korrekt schreibt, hat man es unkorrekt geschrieben“. Worauf ich antwortete: „Korrekt, aber ‚unkorrekt‘ ist unkorrekterweise nicht ‚„unkorrekt“‘“.\n+\n+/// note | Hinweis\n+\n+Das LLM wird dies wahrscheinlich falsch übersetzen. Interessant ist nur, ob es die korrigierte Übersetzung bei einer erneuten Übersetzung beibehält.\n+\n+///\n+\n+////\n+\n+//// tab | Info\n+\n+[NAME_REDACTED] kann entscheiden, ob neutrale Anführungszeichen in typografische Anführungszeichen umgewandelt werden sollen. Es ist in Ordnung, sie unverändert zu lassen.\n+\n+Siehe zum Beispiel den Abschnitt `### Quotes` in `docs/de/llm-prompt.md`.\n+\n+////\n+\n+## Anführungszeichen in Codeschnipseln { #quotes-in-code-snippets}\n+\n+//// tab | Test\n+\n+`pip install \"foo[bar]\"`\n+\n+Beispiele für Stringliterale in Codeschnipseln: `\"this\"`, `'that'`.\n+\n+Ein schwieriges Beispiel für Stringliterale in Codeschnipseln: `f\"I like {'oranges' if orange else \"apples\"}\"`\n+\n+Hardcore: `Yesterday, my friend wrote: \"If you spell incorrectly correctly, you have spelled it incorrectly\". To which I answered: \"Correct, but 'incorrectly' is incorrectly not '\"incorrectly\"'\"`\n+\n+////\n+\n+//// tab | Info\n+\n+... Allerdings müssen Anführungszeichen in Codeschnipseln unverändert bleiben.\n+\n+////\n+\n+## Codeblöcke { #code-blocks }\n+\n+//// tab | Test\n+\n+[NAME_REDACTED] ...\n+\n+```bash\n+# Eine Begrüßung an das Universum ausgeben\n+echo \"Hello universe\"\n+```\n+\n+... und ein Konsolen-Codebeispiel ...\n+\n+```console\n+$ fastapi run main.py\n+ FastAPI Starting server\n+ Searching for package file structure\n+```\n+\n+... und noch ein Konsolen-Codebeispiel ...\n+\n+```console\n+// [NAME_REDACTED] „Code“ erstellen\n+$ mkdir code\n+// In dieses Verzeichnis wechseln\n+$ cd code\n+```\n+\n+... und ein Python-Codebeispiel ...\n+\n+```Python\n+wont_work() # Das wird nicht funktionieren 😱\n+works(foo=\"bar\") # Das funktioniert 🎉\n+```\n+\n+... und das war's.\n+\n+////\n+\n+//// tab | Info\n+\n+Code in Codeblöcken sollte nicht verändert werden, mit Ausnahme von Kommentaren.\n+\n+[NAME_REDACTED] `### Content of code blocks` im allgemeinen Prompt in `scripts/translate.py`.\n+\n+////\n+\n+## Tabs und farbige Boxen { #tabs-and-colored-boxes }\n+\n+//// tab | Test\n+\n+/// info | Info\n+[NAME_REDACTED]\n+///\n+\n+/// note | Hinweis\n+[NAME_REDACTED]\n+///\n+\n+/// note | [NAME_REDACTED]\n+[NAME_REDACTED]\n+///\n+\n+/// check | Testen\n+[NAME_REDACTED]\n+///\n+\n+/// tip | Tipp\n+[NAME_REDACTED]\n+///\n+\n+/// warning | Achtung\n+[NAME_REDACTED]\n+///\n+\n+/// danger | Gefahr\n+[NAME_REDACTED]\n+///\n+\n+////\n+\n+//// tab | Info\n+\n+Tabs und `Info`/`Note`/`Warning`/usw. Blöcke sollten die Übersetzung ihres Titels nach einem vertikalen Strich (`|`) erhalten.\n+\n+Siehe die Abschnitte `### Special blocks` und `### Tab blocks` im allgemeinen Prompt in `scripts/translate.py`.\n+\n+////\n+\n+## Web- und interne Links { #web-and-internal-links }\n+\n+//// tab | Test\n+\n+[NAME_REDACTED] sollte übersetzt werden, die Linkadresse sollte unverändert bleiben:\n+\n+* [Link zur Überschrift oben](#code-snippets)\n+* [[NAME_REDACTED]](index.md#installation){.internal-link target=_blank}\n+* [NAME_REDACTED]\n+* Link zu einem Stil\n+* Link zu einem Skript\n+* Link zu einem Bild\n+\n+[NAME_REDACTED] sollte übersetzt werden, die Linkadresse sollte auf die Übersetzung zeigen:\n+\n+* FastAPI-Link\n+\n+////\n+\n+//// tab | Info\n+\n+Links sollten übersetzt werden, aber ihre Adresse soll unverändert bleiben. [NAME_REDACTED] sind absolute Links zu Seiten der FastAPI-Dokumentation. In diesem Fall sollte auf die Übersetzung verlinkt werden.\n+\n+[NAME_REDACTED] `### Links` im allgemeinen Prompt in `scripts/translate.py`.\n+\n+////\n+\n+## HTML „abbr“-Elemente { #html-abbr-elements }\n+\n+//// tab | Test\n+\n+Hier einige Dinge, die in HTML-„abbr“-Elemente gepackt sind (einige sind erfunden):\n+\n+### Das abbr gibt eine vollständige Phrase { #the-abbr-gives-a-full-phrase }\n+\n+* GTD\n+* lt\n+* XWT\n+* PSGI\n+\n+### Das abbr gibt eine Erklärung { #the-abbr-gives-an-explanation }\n+\n+* Cluster\n+* [NAME_REDACTED]\n+\n+### Das abbr gibt eine vollständige Phrase und eine Erklärung { #the-abbr-gives-a-full-phrase-and-an-explanation }\n+\n+* MDN\n+* I/O.\n+\n+////\n+\n+//// tab | Info\n+\n+„title“-Attribute von „abbr“-Elementen werden nach bestimmten Anweisungen übersetzt.\n+\n+Übersetzungen können eigene „abbr“-Elemente hinzufügen, die das LLM nicht entfernen soll. Z. B. um englische Wörter zu erklären.\n+\n+[NAME_REDACTED] `### HTML abbr elements` im allgemeinen Prompt in `scripts/translate.py`.\n+\n+////\n+\n+## Überschriften { #headings }\n+\n+//// tab | Test\n+\n+### [NAME_REDACTED] entwickeln – ein Tutorial { #develop-a-webapp-a-tutorial }\n+\n+Hallo.\n+\n+### Typhinweise und -annotationen { #type-hints-and-annotations }\n+\n+Hallo wieder.\n+\n+### Super- und Subklassen { #super-and-subclasses }\n+\n+Hallo wieder.\n+\n+////\n+\n+//// tab | Info\n+\n+Die einzige strenge Regel für Überschriften ist, dass das LLM den Hash-Teil in geschweiften Klammern unverändert lässt, damit Links nicht kaputtgehen.\n+\n+[NAME_REDACTED] `### Headings` im allgemeinen Prompt in `scripts/translate.py`.\n+\n+Für einige sprachspezifische Anweisungen, siehe z. B. den Abschnitt `### Headings` in `docs/de/llm-prompt.md`.\n+\n+////\n+\n+## In der Dokumentation verwendete Begriffe { #terms-used-in-the-docs }\n+\n+//// tab | Test\n+\n+* Sie\n+* Ihr\n+\n+* z. B.\n+* usw.\n+\n+* `foo` vom Typ `int`\n+* `bar` vom Typ `str`\n+* `baz` vom Typ `list`\n+\n+* das Tutorial – Benutzerhandbuch\n+* das Handbuch für fortgeschrittene Benutzer\n+* die SQLModel-Dokumentation\n+* die API-Dokumentation\n+* die automatische Dokumentation\n+\n+* [NAME_REDACTED]\n+* [NAME_REDACTED]\n+* [NAME_REDACTED]\n+* [NAME_REDACTED]\n+* HTTP Basic-Authentifizierung\n+* HTTP Digest\n+* ISO-Format\n+* der JSON-Schema-Standard\n+* das JSON-Schema\n+* die Schema-Definition\n+* [NAME_REDACTED]\n+* Mobile\n+\n+* deprecatet\n+* designt\n+* ungültig\n+* on the fly\n+* Standard\n+* Default\n+* Groß-/Klein­schrei­bung ist relevant\n+* Groß-/Klein­schrei­bung ist nicht relevant\n+\n+* die Anwendung bereitstellen\n+* die Seite ausliefern\n+\n+* die App\n+* die Anwendung\n+\n+* der Request\n+* die Response\n+* die Error-Response\n+\n+* die Pfadoperation\n+* der Pfadoperation-Dekorator\n+* die Pfadoperation-Funktion\n+\n+* der Body\n+* der Requestbody\n+* der Responsebody\n+* der JSON-Body\n+* der Formularbody\n+* der Dateibody\n+* der Funktionskörper\n+\n+* der Parameter\n+* der Body-Parameter\n+* der Pfad-Parameter\n+* der Query-Parameter\n+* der Cookie-Parameter\n+* der Header-Parameter\n+* der Formular-Parameter\n+* der Funktionsparameter\n+\n+* das Event\n+* das Startup-Event\n+* das Hochfahren des Servers\n+* das Shutdown-Event\n+* das Lifespan-Event\n+\n+* der Handler\n+* der Eventhandler\n+* der Exceptionhandler\n+* handhaben\n+\n+* das Modell\n+* das Pydantic-Modell\n+* das Datenmodell\n+* das Datenbankmodell\n+* das Formularmodell\n+* das Modellobjekt\n+\n+* die Klasse\n+* die Basisklasse\n+* die Elternklasse\n+* die Subklasse\n+* die Kindklasse\n+* die Geschwisterklasse\n+* die Klassenmethode\n+\n+* der Header\n+* die Header\n+* der Autorisierungsheader\n+* der `Authorization`-Header\n+* der Forwarded-Header\n+\n+* das Dependency-Injection-System\n+* die Dependency\n+* das Dependable\n+* der Dependant\n+\n+* I/O-lastig\n+* CPU-lastig\n+* Nebenläufigkeit\n+* Parallelität\n+* Multiprocessing\n+\n+* die Umgebungsvariable\n+* die Umgebungsvariable\n+* der `PATH`\n+* die `PATH`-Umgebungsvariable\n+\n+* die Authentifizierung\n+* der Authentifizierungsanbieter\n+* die Autorisierung\n+* das Anmeldeformular\n+* der Autorisierungsanbieter\n+* der Benutzer authentisiert sich\n+* das System authentifiziert den Benutzer\n+\n+* Das CLI\n+* [NAME_REDACTED]\n+\n+* der Server\n+* der Client\n+\n+* der Cloudanbieter\n+* der Clouddienst\n+\n+* die Entwicklung\n+* die Entwicklungsphasen\n+\n+* das Dict\n+* das Dictionary\n+* die Enumeration\n+* das Enum\n+* das Enum-Member\n+\n+* der Encoder\n+* der Decoder\n+* kodieren\n+* dekodieren\n+\n+* die Exception\n+* werfen\n+\n+* der Ausdruck\n+* die Anweisung\n+\n+* das Frontend\n+* das Backend\n+\n+* die GitHub-Diskussion\n+* das GitHub-Issue\n+\n+* die Leistung\n+* die Leistungsoptimierung\n+\n+* der Rückgabetyp\n+* der Rückgabewert\n+\n+* die Sicherheit\n+* das Sicherheitsschema\n+\n+* der Task\n+* der Hintergrundtask\n+* die Taskfunktion\n+\n+* das Template\n+* die Template-Engine\n+\n+* die Typannotation\n+* der Typhinweis\n+\n+* der Serverworker\n+* der Uvicorn-Worker\n+* der Gunicorn-Worker\n+* der Workerprozess\n+* die Workerklasse\n+* die Workload\n+\n+* das Deployment\n+* bereitstellen\n+\n+* das SDK\n+* das [NAME_REDACTED]\n+\n+* der `APIRouter`\n+* die `requirements.txt`\n+* das Bearer-Token\n+* der Breaking Change\n+* der Bug\n+* der Button\n+* das Callable\n+* der Code\n+* der Commit\n+* der Contextmanager\n+* die Coroutine\n+* die Datenbank-Session\n+* die Festplatte\n+* die Domain\n+* die Engine\n+* das Fake-X\n+* die HTTP-GET-Methode\n+* das Item\n+* die Bibliothek\n+* der Lifespan\n+* der Lock\n+* die Middleware\n+* die Mobile-Anwendung\n+* das Modul\n+* das Mounten\n+* das Netzwerk\n+* das Origin\n+* Die Überschreibung\n+* die Payload\n+* der Prozessor\n+* die Property\n+* der Proxy\n+* der Pull Request\n+* die Query\n+* der RAM\n+* der entfernte Rechner\n+* der Statuscode\n+* der String\n+* der Tag\n+* das Webframework\n+* die Wildcard\n+* zurückgeben\n+* validieren\n+\n+////\n+\n+//// tab | Info\n+\n+Dies ist eine nicht vollständige und nicht normative Liste von (meist) technischen Begriffen, die in der Dokumentation vorkommen. Sie kann dem Prompt-Designer helfen herauszufinden, bei welchen Begriffen das LLM Unterstützung braucht. [NAME_REDACTED], wenn es eine gute Übersetzung immer wieder auf eine suboptimale Übersetzung zurücksetzt. Oder wenn es Probleme hat, einen Begriff in [NAME_REDACTED] zu konjugieren/deklinieren.\n+\n+Siehe z. B. den Abschnitt `### List of English terms and their preferred German translations` in `docs/de/llm-prompt.md`.\n+\n+////" }, { "filename": "docs/en/docs/_llm-test.md", "status": "added", "additions": 503, "deletions": 0, "changes": 503, "patch": "@@ -0,0 +1,503 @@\n+# LLM test file { #llm-test-file }\n+\n+This document tests if the LLM, which translates the documentation, understands the `general_prompt` in `scripts/translate.py` and the language specific prompt in `docs/{language code}/llm-prompt.md`. The language specific prompt is appended to `general_prompt`.\n+\n+Tests added here will be seen by [NAME_REDACTED] specific prompts.\n+\n+Use as follows:\n+\n+* Have a language specific prompt – `docs/{language code}/llm-prompt.md`.\n+* Do a fresh translation of this document into your desired target language (see e.g. the `translate-page` command of the `translate.py`). This will create the translation under `docs/{language code}/docs/_llm-test.md`.\n+* Check if things are okay in the translation.\n+* If necessary, improve your language specific prompt, the general prompt, or the English document.\n+* Then manually fix the remaining issues in the translation, so that it is a good translation.\n+* Retranslate, having the good translation in place. The ideal result would be that the LLM makes no changes anymore to the translation. That means that the general prompt and your language specific prompt are as good as they can be (It will sometimes make a few seemingly random changes, the reason is that LLMs are not deterministic algorithms).\n+\n+The tests:\n+\n+## Code snippets { #code-snippets}\n+\n+//// tab | Test\n+\n+This is a code snippet: `foo`. And this is another code snippet: `bar`. And another one: `baz quux`.\n+\n+////\n+\n+//// tab | Info\n+\n+Content of code snippets should be left as is.\n+\n+See section `### Content of code snippets` in the general prompt in `scripts/translate.py`.\n+\n+////\n+\n+## Quotes { #quotes }\n+\n+//// tab | Test\n+\n+Yesterday, my friend wrote: \"If you spell incorrectly correctly, you have spelled it incorrectly\". To which I answered: \"Correct, but 'incorrectly' is incorrectly not '\"incorrectly\"'\".\n+\n+/// note\n+\n+The LLM will probably translate this wrong. Interesting is only if it keeps the fixed translation when retranslating.\n+\n+///\n+\n+////\n+\n+//// tab | Info\n+\n+The prompt designer may choose if they want to convert neutral quotes to typographic quotes. It is okay to leave them as is.\n+\n+See for example section `### Quotes` in `docs/de/llm-prompt.md`.\n+\n+////\n+\n+## Quotes in code snippets { #quotes-in-code-snippets}\n+\n+//// tab | Test\n+\n+`pip install \"foo[bar]\"`\n+\n+Examples for string literals in code snippets: `\"this\"`, `'that'`.\n+\n+A difficult example for string literals in code snippets: `f\"I like {'oranges' if orange else \"apples\"}\"`\n+\n+Hardcore: `Yesterday, my friend wrote: \"If you spell incorrectly correctly, you have spelled it incorrectly\". To which I answered: \"Correct, but 'incorrectly' is incorrectly not '\"incorrectly\"'\"`\n+\n+////\n+\n+//// tab | Info\n+\n+... However, quotes inside code snippets must stay as is.\n+\n+////\n+\n+## code blocks { #code-blocks }\n+\n+//// tab | Test\n+\n+A Bash code example...\n+\n+```bash\n+# Print a greeting to the universe\n+echo \"Hello universe\"\n+```\n+\n+...and a console code example...\n+\n+```console\n+$ fastapi run main.py\n+ FastAPI Starting server\n+ Searching for package file structure\n+```\n+\n+...and another console code example...\n+\n+```console\n+// Create a directory \"Code\"\n+$ mkdir code\n+// Switch into that directory\n+$ cd code\n+```\n+\n+...and a Python code example...\n+\n+```Python\n+wont_work() # This won't work 😱\n+works(foo=\"bar\") # This works 🎉\n+```\n+\n+...and that's it.\n+\n+////\n+\n+//// tab | Info\n+\n+Code in code blocks should not be modified, with the exception of comments.\n+\n+See section `### Content of code blocks` in the general prompt in `scripts/translate.py`.\n+\n+////\n+\n+## Tabs and colored boxes { #tabs-and-colored-boxes }\n+\n+//// tab | Test\n+\n+/// info\n+Some text\n+///\n+\n+/// note\n+Some text\n+///\n+\n+/// note | Technical details\n+Some text\n+///\n+\n+/// check\n+Some text\n+///\n+\n+/// tip\n+Some text\n+///\n+\n+/// warning\n+Some text\n+///\n+\n+/// danger\n+Some text\n+///\n+\n+////\n+\n+//// tab | Info\n+\n+Tabs and `Info`/`Note`/`Warning`/etc. blocks should have the translation of their title added after a vertical bar (`|`).\n+\n+See sections `### Special blocks` and `### Tab blocks` in the general prompt in `scripts/translate.py`.\n+\n+////\n+\n+## Web- and internal links { #web-and-internal-links }\n+\n+//// tab | Test\n+\n+The link text should get translated, the link address should remain unchaged:\n+\n+* [Link to heading above](#code-snippets)\n+* [Internal link](index.md#installation){.internal-link target=_blank}\n+* External link\n+* Link to a style\n+* Link to a script\n+* Link to an image\n+\n+The link text should get translated, the link address should point to the translation:\n+\n+* FastAPI link\n+\n+////\n+\n+//// tab | Info\n+\n+Links should be translated, but their address shall remain unchanged. An exception are absolute links to pages of the FastAPI documentation. In that case it should link to the translation.\n+\n+See section `### Links` in the general prompt in `scripts/translate.py`.\n+\n+////\n+\n+## HTML \"abbr\" elements { #html-abbr-elements }\n+\n+//// tab | Test\n+\n+Here some things wrapped in HTML \"abbr\" elements (Some are invented):\n+\n+### The abbr gives a full phrase { #the-abbr-gives-a-full-phrase }\n+\n+* GTD\n+* lt\n+* XWT\n+* PSGI\n+\n+### The abbr gives an explanation { #the-abbr-gives-an-explanation }\n+\n+* cluster\n+* \n+\n+### The abbr gives a full phrase and an explanation { #the-abbr-gives-a-full-phrase-and-an-explanation }\n+\n+* MDN\n+* I/O.\n+\n+////\n+\n+//// tab | Info\n+\n+\"title\" attributes of \"abbr\" elements are translated following some specific instructions.\n+\n+Translations can add their own \"abbr\" elements which the LLM should not remove. E.g. to explain English words.\n+\n+See section `### HTML abbr elements` in the general prompt in `scripts/translate.py`.\n+\n+////\n+\n+## Headings { #headings }\n+\n+//// tab | Test\n+\n+### Develop a webapp - a tutorial { #develop-a-webapp-a-tutorial }\n+\n+Hello.\n+\n+### Type hints and -annotations { #type-hints-and-annotations }\n+\n+Hello again.\n+\n+### Super- and subclasses { #super-and-subclasses }\n+\n+Hello again.\n+\n+////\n+\n+//// tab | Info\n+\n+The only hard rule for headings is that the LLM leaves the hash part inside curly brackets unchanged, which ensures that links do not break.\n+\n+See section `### Headings` in the general prompt in `scripts/translate.py`.\n+\n+For some language specific instructions, see e.g. section `### Headings` in `docs/de/llm-prompt.md`.\n+\n+////\n+\n+## Terms used in the docs { #terms-used-in-the-docs }\n+\n+//// tab | Test\n+\n+* you\n+* your\n+\n+* e.g.\n+* etc.\n+\n+* `foo` as an `int`\n+* `bar` as a `str`\n+* `baz` as a `list`\n+\n+* the Tutorial - User guide\n+* the [NAME_REDACTED]\n+* the SQLModel docs\n+* the API docs\n+* the automatic docs\n+\n+* [NAME_REDACTED]\n+* [NAME_REDACTED]\n+* [NAME_REDACTED]\n+* [NAME_REDACTED]\n+* HTTP Basic authentication\n+* HTTP Digest\n+* ISO format\n+* the JSON Schema standard\n+* the JSON schema\n+* the schema definition\n+* [NAME_REDACTED]\n+* Mobile\n+\n+* deprecated\n+* designed\n+* invalid\n+* on the fly\n+* standard\n+* default\n+* case-sensitive\n+* case-insensitive\n+\n+* to serve the application\n+* to serve the page\n+\n+* the app\n+* the application\n+\n+* the request\n+* the response\n+* the error response\n+\n+* the path operation\n+* the path operation decorator\n+* the path operation function\n+\n+* the body\n+* the request body\n+* the response body\n+* the JSON body\n+* the form body\n+* the file body\n+* the function body\n+\n+* the parameter\n+* the body parameter\n+* the path parameter\n+* the query parameter\n+* the cookie parameter\n+* the header parameter\n+* the form parameter\n+* the function parameter\n+\n+* the event\n+* the startup event\n+* the startup of the server\n+* the shutdown event\n+* the lifespan event\n+\n+* the handler\n+* the event handler\n+* the exception handler\n+* to handle\n+\n+* the model\n+* the Pydantic model\n+* the data model\n+* the database model\n+* the form model\n+* the model object\n+\n+* the class\n+* the base class\n+* the parent class\n+* the subclass\n+* the child class\n+* the sibling class\n+* the class method\n+\n+* the header\n+* the headers\n+* the authorization header\n+* the `Authorization` header\n+* the forwarded header\n+\n+* the dependency injection system\n+* the dependency\n+* the dependable\n+* the dependant\n+\n+* I/O bound\n+* CPU bound\n+* concurrency\n+* parallelism\n+* multiprocessing\n+\n+* the env var\n+* the environment variable\n+* the `PATH`\n+* the `PATH` variable\n+\n+* the authentication\n+* the authentication provider\n+* the authorization\n+* the authorization form\n+* the authorization provider\n+* the user authenticates\n+* the system authenticates the user\n+\n+* the CLI\n+* the command line interface\n+\n+* the server\n+* the client\n+\n+* the cloud provider\n+* the cloud service\n+\n+* the development\n+* the development stages\n+\n+* the dict\n+* the dictionary\n+* the enumeration\n+* the enum\n+* the enum member\n+\n+* the encoder\n+* the decoder\n+* to encode\n+* to decode\n+\n+* the exception\n+* to raise\n+\n+* the expression\n+* the statement\n+\n+* the frontend\n+* the backend\n+\n+* the GitHub discussion\n+* the GitHub issue\n+\n+* the performance\n+* the performance optimization\n+\n+* the return type\n+* the return value\n+\n+* the security\n+* the security scheme\n+\n+* the task\n+* the background task\n+* the task function\n+\n+* the template\n+* the template engine\n+\n+* the type annotation\n+* the type hint\n+\n+* the server worker\n+* the Uvicorn worker\n+* the [NAME_REDACTED]\n+* the worker process\n+* the worker class\n+* the workload\n+\n+* the deployment\n+* to deploy\n+\n+* the SDK\n+* the software development kit\n+\n+* the `APIRouter`\n+* the `requirements.txt`\n+* the [NAME_REDACTED]\n+* the breaking change\n+* the bug\n+* the button\n+* the callable\n+* the code\n+* the commit\n+* the context manager\n+* the coroutine\n+* the database session\n+* the disk\n+* the domain\n+* the engine\n+* the fake X\n+* the HTTP GET method\n+* the item\n+* the library\n+* the lifespan\n+* the lock\n+* the middleware\n+* the mobile application\n+* the module\n+* the mounting\n+* the network\n+* the origin\n+* the override\n+* the payload\n+* the processor\n+* the property\n+* the proxy\n+* the pull request\n+* the query\n+* the RAM\n+* the remote machine\n+* the status code\n+* the string\n+* the tag\n+* the web framework\n+* the wildcard\n+* to return\n+* to validate\n+\n+////\n+\n+//// tab | Info\n+\n+This is a not complete and not normative list of (mostly) technical terms seen in the docs. It may be helpful for the prompt designer to figure out for which terms the LLM needs a helping hand. For example when it keeps reverting a good translation to a suboptimal translation. Or when it has problems conjugating/declinating a term in your language.\n+\n+See e.g. section `### List of English terms and their preferred German translations` in `docs/de/llm-prompt.md`.\n+\n+////" } ], "reviews": [ { "id": 3249033230, "user": "user_2a237e38e06b", "state": "APPROVED", "body": "Awesome, this is great, thank you! 🙌 🚀", "submitted_at": "2025-09-20T12:54:54+00:00" } ], "review_comments": [ { "id": 2365619178, "user": "user_2a237e38e06b", "body": "Hahahaha 😂", "path": "docs/en/docs/_llm-test.md", "line": 38, "side": "RIGHT", "created_at": "2025-09-20T12:48:40+00:00" } ], "meta": { "languages": [ "md" ], "touches_tests": false, "review_state_summary": { "APPROVED": 1 }, "meaningful_comment_count": 1, "has_approval": true, "has_changes_requested": false, "total_review_comments": 1 } } { "_id": "e87707e8cc0079ce", "_schema_version": "1.0", "_cleaned_at": "2026-02-12T07:46:51.718504+00:00", "repo": "tiangolo/fastapi", "repo_url": "https://github.com/fastapi/fastapi", "license_name": "MIT License", "license_spdx": "MIT", "pr_number": 14036, "title": "👽️ Ensure compatibility with Pydantic 2.12.0", "body": "`tests/test_multi_body_errors.py::test_openapi_schema` failed with pydantic 2.12.0a1 due to\nhttps://github.com/[USER_REDACTED]ntic/pydantic/pull/11987. Since we're testing the exact contents of the JSON schema, the easiest fix seems to be to add version-dependent handling for this.", "author": "user_6d5c39b99361", "created_at": "2025-09-02T11:58:36+00:00", "merged_at": "2025-10-08T08:57:37+00:00", "base_branch": "master", "head_branch": "pydantic-2.12.0a1", "additions": 32, "deletions": 12, "changed_files": 3, "files": [ { "filename": "fastapi/_compat.py", "status": "modified", "additions": 15, "deletions": 3, "changes": 18, "patch": "@@ -1,3 +1,4 @@\n+import warnings\n from collections import deque\n from copy import copy\n from dataclasses import dataclass, is_dataclass\n@@ -109,9 +110,20 @@ def type_(self) -> Any:\n return self.field_info.annotation\n \n def __post_init__(self) -> None:\n- self._type_adapter: TypeAdapter[Any] = TypeAdapter(\n- Annotated[self.field_info.annotation, self.field_info]\n- )\n+ with warnings.catch_warnings():\n+ # Pydantic >= 2.12.0 warns about field specific metadata that is unused\n+ # (e.g. `TypeAdapter(Annotated[int, Field(alias='b')])`). In some cases, we\n+ # end up building the type adapter from a model field annotation so we\n+ # need to ignore the warning:\n+ if PYDANTIC_VERSION_MINOR_TUPLE >= (2, 12):\n+ from pydantic.warnings import UnsupportedFieldAttributeWarning\n+\n+ warnings.simplefilter(\n+ \"ignore\", category=UnsupportedFieldAttributeWarning\n+ )\n+ self._type_adapter: TypeAdapter[Any] = TypeAdapter(\n+ Annotated[self.field_info.annotation, self.field_info]\n+ )\n \n def get_default(self) -> Any:\n if self.field_info.is_required():" }, { "filename": "fastapi/params.py", "status": "modified", "additions": 8, "deletions": 8, "changes": 16, "patch": "@@ -22,7 +22,7 @@ class ParamTypes(Enum):\n cookie = \"cookie\"\n \n \n-class Param(FieldInfo):\n+class Param(FieldInfo): # type: ignore[misc]\n in_: ParamTypes\n \n def __init__(\n@@ -136,7 +136,7 @@ def __repr__(self) -> str:\n return f\"{self.__class__.__name__}({self.default})\"\n \n \n-class Path(Param):\n+class Path(Param): # type: ignore[misc]\n in_ = ParamTypes.path\n \n def __init__(\n@@ -222,7 +222,7 @@ def __init__(\n )\n \n \n-class Query(Param):\n+class Query(Param): # type: ignore[misc]\n in_ = ParamTypes.query\n \n def __init__(\n@@ -306,7 +306,7 @@ def __init__(\n )\n \n \n-class Header(Param):\n+class Header(Param): # type: ignore[misc]\n in_ = ParamTypes.header\n \n def __init__(\n@@ -392,7 +392,7 @@ def __init__(\n )\n \n \n-class Cookie(Param):\n+class Cookie(Param): # type: ignore[misc]\n in_ = ParamTypes.cookie\n \n def __init__(\n@@ -476,7 +476,7 @@ def __init__(\n )\n \n \n-class Body(FieldInfo):\n+class Body(FieldInfo): # type: ignore[misc]\n def __init__(\n self,\n default: Any = Undefined,\n@@ -593,7 +593,7 @@ def __repr__(self) -> str:\n return f\"{self.__class__.__name__}({self.default})\"\n \n \n-class Form(Body):\n+class Form(Body): # type: ignore[misc]\n def __init__(\n self,\n default: Any = Undefined,\n@@ -677,7 +677,7 @@ def __init__(\n )\n \n \n-class File(Form):\n+class File(Form): # type: ignore[misc]\n def __init__(\n self,\n default: Any = Undefined," }, { "filename": "tests/test_multi_body_errors.py", "status": "modified", "additions": 9, "deletions": 1, "changes": 10, "patch": "@@ -185,7 +185,15 @@ def test_openapi_schema():\n \"title\": \"Age\",\n \"anyOf\": [\n {\"exclusiveMinimum\": 0.0, \"type\": \"number\"},\n- {\"type\": \"string\"},\n+ IsOneOf(\n+ # pydantic < 2.12.0\n+ {\"type\": \"string\"},\n+ # pydantic >= 2.12.0\n+ {\n+ \"type\": \"string\",\n+ \"pattern\": r\"^(?!^[-+.]*$)[+-]?0*\\d*\\.?\\d*$\",\n+ },\n+ ),\n ],\n }\n )" } ], "reviews": [ { "id": 3253770017, "user": "user_2f5b7b9decc2", "state": "DISMISSED", "body": null, "submitted_at": "2025-09-22T16:08:06+00:00" }, { "id": 3267274846, "user": "user_6d5c39b99361", "state": "COMMENTED", "body": null, "submitted_at": "2025-09-25T11:49:02+00:00" }, { "id": 3309349720, "user": "user_84458f05cf3c", "state": "APPROVED", "body": "Ok, just to recap and apologies for the earlier confusion!\n\nThis PR ensures compatibility with Pydantic 2.12.0, which will be released soon.\n\nIn particular, `pydantic` 2.12.0a1 causes 2 types of failures in our test suite:\n\n- `test_openapi_schema` fails due to https://github.com/[USER_REDACTED]ntic/pydantic/pull/11987 as explained by OP. The test is adjusted to work on both new and older versions of Pydantic.\n- warnings about using the `alias` attribute with value `with` in the `Field()` function, cf PR https://github.com/[USER_REDACTED]ntic/pydantic/pull/12028. This PR suppresses those warnings when creating type adapters in FastAPI, which seems like a reasonable solution to me.\n\nI had intended to merge these fixes as part of a larger PR to get ready for Python 3.14, but have reverted that and suggest we merge & release this separately to ensure compatibility with the upcoming Pydantic 2.12.0.\n\nThanks again for your work on this, [USER_REDACTED] !", "submitted_at": "2025-10-07T09:58:29+00:00" }, { "id": 3309373284, "user": "user_84458f05cf3c", "state": "COMMENTED", "body": null, "submitted_at": "2025-10-07T10:04:18+00:00" }, { "id": 3309374390, "user": "user_2f5b7b9decc2", "state": "COMMENTED", "body": null, "submitted_at": "2025-10-07T10:04:38+00:00" }, { "id": 3309375383, "user": "user_2f5b7b9decc2", "state": "COMMENTED", "body": null, "submitted_at": "2025-10-07T10:04:56+00:00" }, { "id": 3309414715, "user": "user_84458f05cf3c", "state": "COMMENTED", "body": null, "submitted_at": "2025-10-07T10:14:56+00:00" }, { "id": 3309436407, "user": "user_2f5b7b9decc2", "state": "COMMENTED", "body": null, "submitted_at": "2025-10-07T10:19:31+00:00" }, { "id": 3309476826, "user": "user_84458f05cf3c", "state": "COMMENTED", "body": null, "submitted_at": "2025-10-07T10:28:16+00:00" }, { "id": 3309497331, "user": "user_2f5b7b9decc2", "state": "COMMENTED", "body": null, "submitted_at": "2025-10-07T10:34:50+00:00" }, { "id": 3309663372, "user": "user_84458f05cf3c", "state": "COMMENTED", "body": null, "submitted_at": "2025-10-07T11:23:36+00:00" }, { "id": 3313781185, "user": "user_2a237e38e06b", "state": "APPROVED", "body": "Nice, thank you [USER_REDACTED]! 🚀 \n\nAnd thanks a lot for all the help here [USER_REDACTED], [USER_REDACTED], [USER_REDACTED], [USER_REDACTED] 🙌 \n\nSo cool to come and see all the conversations already done, the code simplified to the minimum, all the context easy to get quickly. Great job, thank you all! 🍰 \n\nI'll release this in the next hours/minutes in FastAPI 0.118.1 🎉", "submitted_at": "2025-10-08T08:57:15+00:00" } ], "review_comments": [ { "id": 2369192894, "user": "user_2f5b7b9decc2", "body": "```suggestion\n # Pydantic >= 2.12.0 warns about field specific metadata that is unused\n # (e.g. `TypeAdapter(Annotated[int, Field(alias='b')])`). In some cases, we\n # end up building the type adapter from a model field annotation so we\n # need to ignore the warning:", "path": "fastapi/_compat.py", "line": null, "side": "RIGHT", "created_at": "2025-09-22T16:05:41+00:00" }, { "id": 2369201471, "user": "user_2f5b7b9decc2", "body": "- I believe you need to use the `catch_warnings` context manager, because as it stands the warning will always be ignored from now on.\n- I would suggest using an explicit version check on the `pydantic` version instead of a `try..except` statement, so that it can easily be unconditionally imported once FastAPI drops support for Pydantic < 2.12.", "path": "fastapi/_compat.py", "line": null, "side": "RIGHT", "created_at": "2025-09-22T16:07:36+00:00" }, { "id": 2369202655, "user": "user_2f5b7b9decc2", "body": "```suggestion\n # pydantic < 2.12.0\n```", "path": "tests/test_multi_body_errors.py", "line": null, "side": "RIGHT", "created_at": "2025-09-22T16:07:49+00:00" }, { "id": 2369203300, "user": "user_2f5b7b9decc2", "body": "```suggestion\n # pydantic >= 2.12.0\n```", "path": "tests/test_multi_body_errors.py", "line": null, "side": "RIGHT", "created_at": "2025-09-22T16:07:58+00:00" }, { "id": 2378822890, "user": "user_6d5c39b99361", "body": "I'm already using the `catch_warnings` context manager just above, so I'm confused about your first point.\n\nI've made your suggested second change.", "path": "fastapi/_compat.py", "line": null, "side": "RIGHT", "created_at": "2025-09-25T11:49:02+00:00" }, { "id": 2410097108, "user": "user_84458f05cf3c", "body": "[NAME_REDACTED] 2.12 is released, we'll be able to remove the `no cover` statement here.", "path": "fastapi/_compat.py", "line": null, "side": "RIGHT", "created_at": "2025-10-07T10:04:18+00:00" }, { "id": 2410097956, "user": "user_2f5b7b9decc2", "body": "(Which should happen very soon, hopefully today).", "path": "fastapi/_compat.py", "line": null, "side": "RIGHT", "created_at": "2025-10-07T10:04:37+00:00" }, { "id": 2410098702, "user": "user_2f5b7b9decc2", "body": "This is still incorrect, as per my first point [here](https://github.com/fastapi/fastapi/pull/14036#discussion_r2369201471).", "path": "fastapi/_compat.py", "line": 121, "side": "RIGHT", "created_at": "2025-10-07T10:04:56+00:00" }, { "id": 2410125638, "user": "user_84458f05cf3c", "body": "(I know, but we have a bit of a chicken-or-egg situation going on here 😉)", "path": "fastapi/_compat.py", "line": null, "side": "RIGHT", "created_at": "2025-10-07T10:14:55+00:00" }, { "id": 2410138271, "user": "user_2f5b7b9decc2", "body": "Yeah no worries, just wanted to give you a release estimate!", "path": "fastapi/_compat.py", "line": null, "side": "RIGHT", "created_at": "2025-10-07T10:19:31+00:00" }, { "id": 2410162259, "user": "user_84458f05cf3c", "body": "Hi [USER_REDACTED], thanks for the additional review! 🙏 \n\nCan you elaborate on your point?\n\nThe current code uses `warnings.simplefilter` within a `with warnings.catch_warnings()` context manager. It is my understanding that, once the context manager exits, after L128, the warnings filter is restored to its original state when the context was entered (L113) ?", "path": "fastapi/_compat.py", "line": 121, "side": "RIGHT", "created_at": "2025-10-07T10:28:15+00:00" }, { "id": 2410177447, "user": "user_2f5b7b9decc2", "body": "My bad, I always get confused by this `warnings` API, as the context manager isn't opened right on top of the filter. All good!", "path": "fastapi/_compat.py", "line": 121, "side": "RIGHT", "created_at": "2025-10-07T10:34:50+00:00" }, { "id": 2410295950, "user": "user_84458f05cf3c", "body": "No worries, thanks for double checking! 🙏", "path": "fastapi/_compat.py", "line": 121, "side": "RIGHT", "created_at": "2025-10-07T11:23:36+00:00" } ], "meta": { "languages": [ "py" ], "touches_tests": true, "review_state_summary": { "DISMISSED": 1, "COMMENTED": 9, "APPROVED": 2 }, "meaningful_comment_count": 13, "has_approval": true, "has_changes_requested": false, "total_review_comments": 13 } } { "_id": "4512845ee7ca8d6d", "_schema_version": "1.0", "_cleaned_at": "2026-02-12T07:46:51.718504+00:00", "repo": "tiangolo/fastapi", "repo_url": "https://github.com/fastapi/fastapi", "license_name": "MIT License", "license_spdx": "MIT", "pr_number": 14033, "title": "🛠️ Add `add-permalinks` and `add-permalinks-page` to `scripts/docs.py`", "body": "Add missing permalinks to all En docs:\n```\ntyper scripts/docs.py run add-permalinks\n```\n\nRe-generate permalinks for all En docs:\n```\ntyper scripts/docs.py run add-permalinks --update-existing\n```\n\nAdd missing permalinks to specific page in En docs:\n```\ntyper scripts/docs.py run add-permalinks-page docs/en/docs/advanced/behind-a-proxy.md\n```\n\n---\n\nAt the moment we have 1 missed permalink (I committed it an then reverted): https://github.com/fastapi/fastapi/pull/14033/commits/6bf43ba276329a5f65434f9243bf29045f49eada\n\nCan we fix it in this PR or should I open separate PR for this?\n\n---\n\nAlso, I don't know if we need to add some logging?", "author": "user_29e85f9a8e75", "created_at": "2025-09-01T14:12:40+00:00", "merged_at": "2025-11-21T12:49:11+00:00", "base_branch": "master", "head_branch": "add_permalinks-script", "additions": 107, "deletions": 3, "changed_files": 2, "files": [ { "filename": "requirements-docs.txt", "status": "modified", "additions": 1, "deletions": 0, "changes": 1, "patch": "@@ -18,3 +18,4 @@ griffe-warnings-deprecated==1.1.0\n black==25.1.0\n mkdocs-macros-plugin==1.4.1\n markdown-include-variants==0.0.5\n+python-slugify==8.0.4" }, { "filename": "scripts/docs.py", "status": "modified", "additions": 106, "deletions": 3, "changes": 109, "patch": "@@ -4,6 +4,7 @@\n import re\n import shutil\n import subprocess\n+from html.parser import HTMLParser\n from http.server import HTTPServer, SimpleHTTPRequestHandler\n from multiprocessing import Pool\n from pathlib import Path\n@@ -14,6 +15,7 @@\n import yaml\n from jinja2 import Template\n from ruff.__main__ import find_ruff_bin\n+from slugify import slugify as py_slugify\n \n logging.basicConfig(level=logging.INFO)\n \n@@ -25,24 +27,56 @@\n {!../../docs/missing-translation.md!}\n \"\"\"\n \n-non_translated_sections = [\n- \"reference/\",\n+non_translated_sections = (\n+ f\"reference{os.sep}\",\n \"release-notes.md\",\n \"fastapi-people.md\",\n \"external-links.md\",\n \"newsletter.md\",\n \"management-tasks.md\",\n \"management.md\",\n \"contributing.md\",\n-]\n+)\n \n docs_path = Path(\"docs\")\n en_docs_path = Path(\"docs/en\")\n en_config_path: Path = en_docs_path / mkdocs_name\n site_path = Path(\"site\").absolute()\n build_site_path = Path(\"site_build\").absolute()\n \n+header_pattern = re.compile(r\"^(#{1,6}) (.+?)(?:\\s*\\{\\s*(#.*)\\s*\\})?\\s*$\")\n header_with_permalink_pattern = re.compile(r\"^(#{1,6}) (.+?)(\\s*\\{\\s*#.*\\s*\\})\\s*$\")\n+code_block3_pattern = re.compile(r\"^\\s*```\")\n+code_block4_pattern = re.compile(r\"^\\s*````\")\n+\n+\n+class VisibleTextExtractor(HTMLParser):\n+ \"\"\"Extract visible text from a string with HTML tags.\"\"\"\n+\n+ def __init__(self):\n+ super().__init__()\n+ self.text_parts = []\n+\n+ def handle_data(self, data):\n+ self.text_parts.append(data)\n+\n+ def extract_visible_text(self, html: str) -> str:\n+ self.reset()\n+ self.text_parts = []\n+ self.feed(html)\n+ return \"\".join(self.text_parts).strip()\n+\n+\n+def slugify(text: str) -> str:\n+ return py_slugify(\n+ text,\n+ replacements=[\n+ (\"`\", \"\"), # `dict`s -> dicts\n+ (\"'s\", \"s\"), # it's -> its\n+ (\"'t\", \"t\"), # don't -> dont\n+ (\"**\", \"\"), # **FastAPI**s -> FastAPIs\n+ ],\n+ )\n \n \n def get_en_config() -> Dict[str, Any]:\n@@ -426,5 +460,74 @@ def generate_docs_src_versions_for_file(file_path: Path) -> None:\n version_file.write_text(content_format, encoding=\"utf-8\")\n \n \n+[USER_REDACTED].command()\n+def add_permalinks_page(path: Path, update_existing: bool = False):\n+ \"\"\"\n+ Add or update header permalinks in specific page of En docs.\n+ \"\"\"\n+\n+ if not path.is_relative_to(en_docs_path / \"docs\"):\n+ raise RuntimeError(f\"Path must be inside {en_docs_path}\")\n+ rel_path = path.relative_to(en_docs_path / \"docs\")\n+\n+ # Skip excluded sections\n+ if str(rel_path).startswith(non_translated_sections):\n+ return\n+\n+ visible_text_extractor = VisibleTextExtractor()\n+ updated_lines = []\n+ in_code_block3 = False\n+ in_code_block4 = False\n+ permalinks = set()\n+\n+ with path.open(\"r\", encoding=\"utf-8\") as f:\n+ lines = f.readlines()\n+\n+ for line in lines:\n+ # Handle codeblocks start and end\n+ if not (in_code_block3 or in_code_block4):\n+ if code_block4_pattern.match(line):\n+ in_code_block4 = True\n+ elif code_block3_pattern.match(line):\n+ in_code_block3 = True\n+ else:\n+ if in_code_block4 and code_block4_pattern.match(line):\n+ in_code_block4 = False\n+ elif in_code_block3 and code_block3_pattern.match(line):\n+ in_code_block3 = False\n+\n+ # [NAME_REDACTED] only outside codeblocks\n+ if not (in_code_block3 or in_code_block4):\n+ match = header_pattern.match(line)\n+ if match:\n+ hashes, title, _permalink = match.groups()\n+ if (not _permalink) or update_existing:\n+ slug = slugify(visible_text_extractor.extract_visible_text(title))\n+ if slug in permalinks:\n+ # If the slug is already used, append a number to make it unique\n+ count = 1\n+ original_slug = slug\n+ while slug in permalinks:\n+ slug = f\"{original_slug}_{count}\"\n+ count += 1\n+ permalinks.add(slug)\n+\n+ line = f\"{hashes} {title} {{ #{slug} }}\\n\"\n+\n+ updated_lines.append(line)\n+\n+ with path.open(\"w\", encoding=\"utf-8\") as f:\n+ f.writelines(updated_lines)\n+\n+\n+[USER_REDACTED].command()\n+def add_permalinks(update_existing: bool = False) -> None:\n+ \"\"\"\n+ Add or update header permalinks in all pages of En docs.\n+ \"\"\"\n+ for md_file in en_docs_path.rglob(\"*.md\"):\n+ add_permalinks_page(md_file, update_existing=update_existing)\n+\n+\n if __name__ == \"__main__\":\n app()" } ], "reviews": [ { "id": 3175189612, "user": "user_84458f05cf3c", "state": "COMMENTED", "body": "How will we keep things up-to-date, will this script run on Github actions when a PR changes/adds documentation?", "submitted_at": "2025-09-02T07:17:02+00:00" }, { "id": 3256791784, "user": "user_84458f05cf3c", "state": "COMMENTED", "body": null, "submitted_at": "2025-09-23T08:14:49+00:00" }, { "id": 3256796019, "user": "user_84458f05cf3c", "state": "COMMENTED", "body": null, "submitted_at": "2025-09-23T08:15:47+00:00" }, { "id": 3256915724, "user": "user_29e85f9a8e75", "state": "COMMENTED", "body": null, "submitted_at": "2025-09-23T08:50:57+00:00" }, { "id": 3256937241, "user": "user_29e85f9a8e75", "state": "COMMENTED", "body": null, "submitted_at": "2025-09-23T08:57:02+00:00" }, { "id": 3257110184, "user": "user_84458f05cf3c", "state": "COMMENTED", "body": null, "submitted_at": "2025-09-23T09:45:15+00:00" }, { "id": 3257111778, "user": "user_84458f05cf3c", "state": "COMMENTED", "body": null, "submitted_at": "2025-09-23T09:45:45+00:00" }, { "id": 3258433654, "user": "user_29e85f9a8e75", "state": "COMMENTED", "body": null, "submitted_at": "2025-09-23T14:58:11+00:00" }, { "id": 3258757957, "user": "user_84458f05cf3c", "state": "APPROVED", "body": "LGTM! \n\nRan the script on a Windows box and that works good too (`behind-a-proxy.md` gets the missing permalink) and also `--update-existing` works well (finds one occassion where a space should be added).\n\nAs this script has already been tested extensively before and the results of it merged previously, I think this one is good to merge now.", "submitted_at": "2025-09-23T16:16:16+00:00" }, { "id": 3492634610, "user": "user_2a237e38e06b", "state": "APPROVED", "body": "Excellent job, thank you! 🚀", "submitted_at": "2025-11-21T12:48:49+00:00" } ], "review_comments": [ { "id": 2371531886, "user": "user_84458f05cf3c", "body": "To be OS agnostic:\n```suggestion\n \"reference\",\n```\nassuming we have no \"normal\" pages starting with \"reference\" (I don't think that's a real issue)", "path": "scripts/docs.py", "line": null, "side": "RIGHT", "created_at": "2025-09-23T08:14:49+00:00" }, { "id": 2371534436, "user": "user_84458f05cf3c", "body": "Why is that we exclude the `reference` directory?", "path": "scripts/docs.py", "line": null, "side": "RIGHT", "created_at": "2025-09-23T08:15:47+00:00" }, { "id": 2371616410, "user": "user_29e85f9a8e75", "body": "> Why is that we exclude the reference directory?\n\nI guess that's because it's generated from sources? If we decided to translate it, we would need to update all translations every time code changes..\n\nAs for slash in the end - good catch!\nBut instead of removing it, I would go with `f\"reference{os.sep}\",`", "path": "scripts/docs.py", "line": null, "side": "RIGHT", "created_at": "2025-09-23T08:50:57+00:00" }, { "id": 2371631610, "user": "user_29e85f9a8e75", "body": "Looked at code and realized that there are a lot of other occurrences of hardcoded `/`.\nSo, we need to decide whether we want to refactor it in this PR on in separate PR?", "path": "scripts/docs.py", "line": null, "side": "RIGHT", "created_at": "2025-09-23T08:57:02+00:00" }, { "id": 2371748044, "user": "user_84458f05cf3c", "body": "I suggest we (only) update the hardcoded slashes of the new code that is contributed with this PR. Because when I run this new script on my Windows machine, it starts generating permalinks for the `reference` docs and we don't want to do deal with any PRs of users that get the same thing.\n\nWith respect to hardcoded slashes already in the current code base: let's edit those in a separate PR.", "path": "scripts/docs.py", "line": null, "side": "RIGHT", "created_at": "2025-09-23T09:45:15+00:00" }, { "id": 2371749205, "user": "user_84458f05cf3c", "body": "> But instead of removing it, I would go with f\"reference{os.sep}\",\n\nThat's fine too by me!", "path": "scripts/docs.py", "line": null, "side": "RIGHT", "created_at": "2025-09-23T09:45:45+00:00" }, { "id": 2372618533, "user": "user_29e85f9a8e75", "body": "Done!", "path": "scripts/docs.py", "line": null, "side": "RIGHT", "created_at": "2025-09-23T14:58:11+00:00" } ], "meta": { "languages": [ "py", "txt" ], "touches_tests": false, "review_state_summary": { "COMMENTED": 8, "APPROVED": 2 }, "meaningful_comment_count": 6, "has_approval": true, "has_changes_requested": false, "total_review_comments": 7 } } { "_id": "0a46ca1f8473171a", "_schema_version": "1.0", "_cleaned_at": "2026-02-12T07:46:51.718504+00:00", "repo": "tiangolo/fastapi", "repo_url": "https://github.com/fastapi/fastapi", "license_name": "MIT License", "license_spdx": "MIT", "pr_number": 14006, "title": "📝 Remove links to site callbackhell.com that doesn't exist anymore", "body": "I noticed them walking through the \"Learn\" doc in the website. The website callbackhell.com does not exists anymore.\n\nLinks pointing to callbackhell.ru are still working, but if you want I can remove them as well for consistency.", "author": "user_d6cd21289b59", "created_at": "2025-08-21T14:09:50+00:00", "merged_at": "2025-08-31T09:56:22+00:00", "base_branch": "master", "head_branch": "fixing-non-existing-link", "additions": 13, "deletions": 13, "changed_files": 13, "files": [ { "filename": "docs/de/docs/async.md", "status": "modified", "additions": 1, "deletions": 1, "changes": 2, "patch": "@@ -381,7 +381,7 @@ Davor war der Umgang mit asynchronem Code jedoch deutlich komplexer und schwieri\n \n In früheren Versionen von Python hätten [NAME_REDACTED] oder Gevent verwenden können. [NAME_REDACTED] ist jedoch viel komplexer zu verstehen, zu debuggen und nachzuvollziehen.\n \n-In früheren Versionen von NodeJS / [NAME_REDACTED] hätten Sie „Callbacks“ verwendet. Was zur Callback-Hölle führt.\n+In früheren Versionen von NodeJS / [NAME_REDACTED] hätten Sie „Callbacks“ verwendet. Was zur \"Callback-Hölle\" führt.\n \n ## Coroutinen" }, { "filename": "docs/em/docs/async.md", "status": "modified", "additions": 1, "deletions": 1, "changes": 2, "patch": "@@ -381,7 +381,7 @@ async def read_burgers():\n \n ⏮️ ⏬ 🐍, 👆 💪 ✔️ ⚙️ 🧵 ⚖️ 🐁. ✋️ 📟 🌌 🌖 🏗 🤔, ℹ, & 💭 🔃.\n \n-⏮️ ⏬ ✳ / 🖥 🕸, 👆 🔜 ✔️ ⚙️ \"⏲\". ❔ ↘️ ⏲ 🔥😈.\n+⏮️ ⏬ ✳ / 🖥 🕸, 👆 🔜 ✔️ ⚙️ \"⏲\". ❔ ↘️ \"⏲ 🔥😈\".\n \n ## 🔁" }, { "filename": "docs/en/docs/async.md", "status": "modified", "additions": 1, "deletions": 1, "changes": 2, "patch": "@@ -383,7 +383,7 @@ But before that, handling asynchronous code was quite more complex and difficult\n \n In previous versions of Python, you could have used threads or Gevent. But the code is way more complex to understand, debug, and think about.\n \n-In previous versions of NodeJS / [NAME_REDACTED], you would have used \"callbacks\". Which leads to callback hell.\n+In previous versions of NodeJS / [NAME_REDACTED], you would have used \"callbacks\". Which leads to \"callback hell\".\n \n ## Coroutines" }, { "filename": "docs/es/docs/async.md", "status": "modified", "additions": 1, "deletions": 1, "changes": 2, "patch": "@@ -383,7 +383,7 @@ Pero antes de eso, manejar el código asíncrono era mucho más complejo y difí\n \n En versiones previas de Python, podrías haber usado hilos o Gevent. Pero el código es mucho más complejo de entender, depurar y razonar.\n \n-En versiones previas de NodeJS / JavaScript en el Navegador, habrías usado \"callbacks\". Lo que lleva al callback hell.\n+En versiones previas de NodeJS / JavaScript en el Navegador, habrías usado \"callbacks\". Lo que lleva al \"callback hell\".\n \n ## Coroutines" }, { "filename": "docs/fa/docs/async.md", "status": "modified", "additions": 1, "deletions": 1, "changes": 2, "patch": "@@ -383,7 +383,7 @@ Starlette (و **FastAPI**) بر پایه Gevent استفاده کنی. ولی کد خیلی پیچیده‌تر می‌شه برای فهمیدن، دیباگ کردن و فکر کردن بهش.\n \n-توی نسخه‌های قبلی NodeJS / جاوااسکریپت مرورگر، از \"کال‌بک‌ها\" استفاده می‌کردی. که می‌رسید به جهان کال‌بک‌ها.\n+توی نسخه‌های قبلی NodeJS / جاوااسکریپت مرورگر، از \"کال‌بک‌ها\" استفاده می‌کردی. که می‌رسید به \"جهان کال‌بک‌ها\".\n \n ## کروتین‌ها" }, { "filename": "docs/fr/docs/async.md", "status": "modified", "additions": 1, "deletions": 1, "changes": 2, "patch": "@@ -372,7 +372,7 @@ Mais avant ça, gérer du code asynchrone était bien plus complexe et difficile\n \n Dans les versions précédentes de Python, vous auriez utilisé des *threads* ou Gevent. Mais le code aurait été bien plus difficile à comprendre, débugger, et concevoir.\n \n-Dans les versions précédentes de [NAME_REDACTED] / Navigateur, vous auriez utilisé des \"callbacks\". Menant potentiellement à ce que l'on appelle le \"callback hell\".\n+Dans les versions précédentes de [NAME_REDACTED] / Navigateur, vous auriez utilisé des \"callbacks\". Menant potentiellement à ce que l'on appelle le \"callback hell\".\n \n \n ## Coroutines" }, { "filename": "docs/ja/docs/async.md", "status": "modified", "additions": 1, "deletions": 1, "changes": 2, "patch": "@@ -338,7 +338,7 @@ async def read_burgers():\n \n 以前のバージョンのPythonでは、スレッドやGeventが利用できました。しかし、コードは理解、デバック、そして、考察がはるかに複雑です。\n \n-以前のバージョンのNodeJS / ブラウザJavaScriptでは、「コールバック」を使用していました。これは、コールバック地獄につながります。\n+以前のバージョンのNodeJS / ブラウザJavaScriptでは、「コールバック」を使用していました。これは、「コールバック地獄」につながります。\n \n ## コルーチン" }, { "filename": "docs/ko/docs/async.md", "status": "modified", "additions": 1, "deletions": 1, "changes": 2, "patch": "@@ -349,7 +349,7 @@ FastAPI를 사용하지 않더라도, 높은 호환성 및 Gevent를 사용할 수 있을 것입니다. 하지만 코드를 이해하고, 디버깅하고, 이에 대해 생각하는게 훨씬 복잡합니다.\n \n-예전 버전의 NodeJS / 브라우저 자바스크립트라면, \"콜백 함수\"를 사용했을 것입니다. 그리고 이로 인해 콜백 지옥에 빠지게 될 수 있습니다.\n+예전 버전의 NodeJS / 브라우저 자바스크립트라면, \"콜백 함수\"를 사용했을 것입니다. 그리고 이로 인해 \"콜백 지옥\"에 빠지게 될 수 있습니다.\n \n ## 코루틴" }, { "filename": "docs/pt/docs/async.md", "status": "modified", "additions": 1, "deletions": 1, "changes": 2, "patch": "@@ -348,7 +348,7 @@ Mas antes disso, controlar código assíncrono era bem mais complexo e difícil.\n \n Nas versões anteriores do Python, você poderia utilizar threads ou Gevent. Mas o código é bem mais complexo de entender, debugar, e pensar sobre.\n \n-Nas versões anteriores do NodeJS / [NAME_REDACTED], você utilizaria \"callbacks\". O que leva ao inferno do callback.\n+Nas versões anteriores do NodeJS / [NAME_REDACTED], você utilizaria \"callbacks\". O que leva ao \"inferno do callback\".\n \n ## Corrotinas" }, { "filename": "docs/ru/docs/async.md", "status": "modified", "additions": 1, "deletions": 1, "changes": 2, "patch": "@@ -420,7 +420,7 @@ Starlette (и **FastAPI**) основаны на \"обратные вызовы\". Что выливалось в\n-ад обратных вызовов.\n+\"ад обратных вызовов\".\n \n ## Сопрограммы" }, { "filename": "docs/tr/docs/async.md", "status": "modified", "additions": 1, "deletions": 1, "changes": 2, "patch": "@@ -346,7 +346,7 @@ Ancak bundan önce, asenkron kodu işlemek oldukça karmaşık ve zordu.\n \n Python'un önceki sürümlerinde, threadlerı veya Gevent kullanıyor olabilirdin. Ancak kodu anlamak, hata ayıklamak ve düşünmek çok daha karmaşık olurdu.\n \n-NodeJS / [NAME_REDACTED] önceki sürümlerinde, \"callback\" kullanırdınız. Bu da callbacks cehennemine yol açar.\n+NodeJS / [NAME_REDACTED] önceki sürümlerinde, \"callback\" kullanırdınız. Bu da \"callbacks cehennemine\" yol açar.\n \n ## Coroutine'ler" }, { "filename": "docs/zh-hant/docs/async.md", "status": "modified", "additions": 1, "deletions": 1, "changes": 2, "patch": "@@ -381,7 +381,7 @@ Starlette (和 **FastAPI**) 是基於 Gevent。但這些程式碼要更難以理解、調試和思考。\n \n-在較舊的 NodeJS / 瀏覽器 JavaScript 中,你會使用「回呼」,這可能會導致回呼地獄。\n+在較舊的 NodeJS / 瀏覽器 JavaScript 中,你會使用「回呼」,這可能會導致“回呼地獄”。\n \n ## 協程" }, { "filename": "docs/zh/docs/async.md", "status": "modified", "additions": 1, "deletions": 1, "changes": 2, "patch": "@@ -383,7 +383,7 @@ Starlette (和 **FastAPI**) 是基于 Gevent。但代码的理解、调试和思考都要复杂许多。\n \n-在以前版本的 NodeJS / 浏览器 JavaScript 中,你会使用\"回调\",因此也可能导致回调地狱。\n+在以前版本的 NodeJS / 浏览器 JavaScript 中,你会使用\"回调\",因此也可能导致“回调地狱”。\n \n ## 协程" } ], "reviews": [ { "id": 3143845368, "user": "user_84458f05cf3c", "state": "COMMENTED", "body": "Thanks, this looks good!\n\nI would also remove the links to callbackhell.ru just for consistency. \n\nThen, I worry a bit that the current text is not super informative:\n> In previous versions of NodeJS / [NAME_REDACTED], you would have used \"callbacks\". Which leads to callback hell.\n\nBefore, the link was there to explain more, but now to someone unfamiliar to this concept, this explanation is not really sufficient. I would either\n\n- put \"callback hell\" in quotes, to clarify it's a common concept that people could google\n- change the link to a new one, maybe https://www.geeksforgeeks.org/javascript/what-to-understand-callback-and-callback-hell-in-javascript/ ?\n- add a (very brief) description to the sentence, something like \"... to callback hell, a problem occurring due to excessive nesting of functions\", or something such. The downside then is that we'd need to translate this to all the languages that are being edited here 😬 \n\nWhat do you think, [USER_REDACTED] ?\n\n>", "submitted_at": "2025-08-22T09:46:05+00:00" }, { "id": 3150440631, "user": "user_84458f05cf3c", "state": "COMMENTED", "body": null, "submitted_at": "2025-08-25T08:34:47+00:00" }, { "id": 3150443981, "user": "user_84458f05cf3c", "state": "APPROVED", "body": "Thanks, looks good to me!", "submitted_at": "2025-08-25T08:35:51+00:00" }, { "id": 3150517918, "user": "user_d6cd21289b59", "state": "COMMENTED", "body": null, "submitted_at": "2025-08-25T08:59:25+00:00" }, { "id": 3150535817, "user": "user_84458f05cf3c", "state": "COMMENTED", "body": null, "submitted_at": "2025-08-25T09:05:05+00:00" }, { "id": 3171544755, "user": "user_2a237e38e06b", "state": "APPROVED", "body": "Great, thank you! 🚀", "submitted_at": "2025-08-31T09:56:08+00:00" } ], "review_comments": [ { "id": 2297470814, "user": "user_84458f05cf3c", "body": "This _looks_ incorrect when viewing the github diff (one of the quote marks seem to be placed incorrectly) but when viewing the actual doc page, it seems fine.", "path": "docs/fa/docs/async.md", "line": 386, "side": "RIGHT", "created_at": "2025-08-25T08:34:47+00:00" }, { "id": 2297521299, "user": "user_d6cd21289b59", "body": "This should be related to a right-to-left text thing.\nOn my localhost using VS Code, the diff is like this\n\n\"image\"", "path": "docs/fa/docs/async.md", "line": 386, "side": "RIGHT", "created_at": "2025-08-25T08:59:24+00:00" }, { "id": 2297533425, "user": "user_84458f05cf3c", "body": "Yep, it seems to be a bug with how Github displays the bug, but the edit is actually correct.", "path": "docs/fa/docs/async.md", "line": 386, "side": "RIGHT", "created_at": "2025-08-25T09:05:05+00:00" } ], "meta": { "languages": [ "md" ], "touches_tests": false, "review_state_summary": { "COMMENTED": 4, "APPROVED": 2 }, "meaningful_comment_count": 3, "has_approval": true, "has_changes_requested": false, "total_review_comments": 3 } } { "_id": "da28e81a37a93f6c", "_schema_version": "1.0", "_cleaned_at": "2026-02-12T07:46:51.718504+00:00", "repo": "tiangolo/fastapi", "repo_url": "https://github.com/fastapi/fastapi", "license_name": "MIT License", "license_spdx": "MIT", "pr_number": 13920, "title": "✨ Add support for PEP695 `TypeAliasType`", "body": "This is a continuation of #11140 with the comment by [USER_REDACTED] fixed by vendoring a copy of `is_typealiastype` from [`typing-inspection`](https://github.com/[USER_REDACTED]ntic/typing-inspection).", "author": "user_3203423ec624", "created_at": "2025-07-24T02:13:59+00:00", "merged_at": "2026-02-05T18:34:34+00:00", "base_branch": "master", "head_branch": "bugfix/allow-pep695-type-alias", "additions": 34, "deletions": 0, "changed_files": 4, "files": [ { "filename": "fastapi/dependencies/utils.py", "status": "modified", "additions": 4, "deletions": 0, "changes": 4, "patch": "@@ -66,6 +66,7 @@\n from starlette.responses import Response\n from starlette.websockets import WebSocket\n from typing_extensions import Literal, get_args, get_origin\n+from typing_inspection.typing_objects import is_typealiastype\n \n multipart_not_installed_error = (\n 'Form data requires \"python-multipart\" to be installed. \\n'\n@@ -370,6 +371,9 @@ def analyze_param(\n depends = None\n type_annotation: Any = Any\n use_annotation: Any = Any\n+ if is_typealiastype(annotation):\n+ # unpack in case PEP 695 type syntax is used\n+ annotation = annotation.__value__\n if annotation is not inspect.Signature.empty:\n use_annotation = annotation\n type_annotation = annotation" }, { "filename": "pyproject.toml", "status": "modified", "additions": 1, "deletions": 0, "changes": 1, "patch": "@@ -46,6 +46,7 @@ dependencies = [\n \"starlette>=0.40.0,<0.51.0\",\n \"pydantic>=2.7.0\",\n \"typing-extensions>=4.8.0\",\n+ \"typing-inspection>=0.4.2\",\n \"annotated-doc>=0.0.2\",\n ]" }, { "filename": "tests/test_dependency_pep695.py", "status": "added", "additions": 27, "deletions": 0, "changes": 27, "patch": "@@ -0,0 +1,27 @@\n+from typing import Annotated\n+\n+from fastapi import Depends, FastAPI\n+from fastapi.testclient import TestClient\n+from typing_extensions import TypeAliasType\n+\n+\n+async def some_value() -> int:\n+ return 123\n+\n+\n+DependedValue = TypeAliasType(\n+ \"DependedValue\", Annotated[int, Depends(some_value)], type_params=()\n+)\n+\n+\n+def test_pep695_type_dependencies():\n+ app = FastAPI()\n+\n+ [USER_REDACTED].get(\"/\")\n+ async def get_with_dep(value: DependedValue) -> str: # noqa\n+ return f\"value: {value}\"\n+\n+ client = TestClient(app)\n+ response = client.get(\"/\")\n+ assert response.status_code == 200\n+ assert response.text == '\"value: 123\"'" }, { "filename": "uv.lock", "status": "modified", "additions": 2, "deletions": 0, "changes": 2, "patch": "@@ -1021,6 +1021,7 @@ dependencies = [\n { name = \"starlette\", version = \"0.49.3\", source = { registry = \"https://pypi.org/simple\" }, marker = \"python_full_version < '3.10'\" },\n { name = \"starlette\", version = \"0.50.0\", source = { registry = \"https://pypi.org/simple\" }, marker = \"python_full_version >= '3.10'\" },\n { name = \"typing-extensions\" },\n+ { name = \"typing-inspection\" },\n ]\n \n [package.optional-dependencies]\n@@ -1202,6 +1203,7 @@ requires-dist = [\n { name = \"pyyaml\", marker = \"extra == 'all'\", specifier = \">=5.3.1\" },\n { name = \"starlette\", specifier = \">=0.40.0,<0.51.0\" },\n { name = \"typing-extensions\", specifier = \">=4.8.0\" },\n+ { name = \"typing-inspection\", specifier = \">=0.4.2\" },\n { name = \"ujson\", marker = \"extra == 'all'\", specifier = \">=4.0.1,!=4.0.2,!=4.1.0,!=4.2.0,!=4.3.0,!=5.0.0,!=5.1.0\" },\n { name = \"uvicorn\", extras = [\"standard\"], marker = \"extra == 'all'\", specifier = \">=0.12.0\" },\n { name = \"uvicorn\", extras = [\"standard\"], marker = \"extra == 'standard'\", specifier = \">=0.12.0\" }," } ], "reviews": [ { "id": 3299622546, "user": "user_29e85f9a8e75", "state": "APPROVED", "body": "LGTM!\n\nI suggest adding comments to the code to simplify review process.\n\n[USER_REDACTED], thanks you for working on this!\n\nRelated issue: #10719", "submitted_at": "2025-10-03T15:58:47+00:00" }, { "id": 3392746298, "user": "user_35cb99d940a0", "state": "COMMENTED", "body": null, "submitted_at": "2025-10-29T10:59:54+00:00" }, { "id": 3637168593, "user": "user_29e85f9a8e75", "state": "APPROVED", "body": "LGTM!\n\nThis resolves issue https://github.com/fastapi/fastapi/issues/10719\n\nThe following type alias syntax will be supported:\n```\ntype DependedValue = Annotated[int, Depends(some_value)]\n```\n\nSince we dropped the support of Python 3.8 we can now use `is_typealiastype` from `typing-inspection`. So, I updated PR to do so.\n\n`typing-inspection` is already a sub-dependency of Pydantic, but I added it explicitly just in case (min version as in [Pydantic's pyproject.toml](https://github.com/[USER_REDACTED]ntic/pydantic/blob/12c94d9753a77fe76111ef2161a33f5e2d5e41f3/pyproject.toml#L51C6-L51C30))", "submitted_at": "2026-01-07T23:22:47+00:00" }, { "id": 3758720252, "user": "user_2a237e38e06b", "state": "APPROVED", "body": "Awesome, thanks all! 🙌 \n\nThis will be available in FastAPI 0.128.2, released in the next few hours. 🚀", "submitted_at": "2026-02-05T18:30:10+00:00" } ], "review_comments": [ { "id": 2402402429, "user": "user_29e85f9a8e75", "body": "```suggestion\n \"\"\"\n This implementation is in line with the implementation of `is_typealiastype` in `typing-inspection`:\n See:\n - https://github.com/[USER_REDACTED]ntic/typing-inspection/blob/8db011350942f33ac4b5d7db60d4d9ea83ab480f/src/typing_inspection/typing_objects.py#L488-L499\n - https://github.com/[USER_REDACTED]ntic/typing-inspection/blob/8db011350942f33ac4b5d7db60d4d9ea83ab480f/src/typing_inspection/typing_objects.py#L105-L134\n \"\"\"\n\n # Check if TypeAliasType exists in typing and/or typing_extensions.\n in_typing = hasattr(typing, \"TypeAliasType\")\n```", "path": "fastapi/dependencies/utils.py", "line": null, "side": "RIGHT", "created_at": "2025-10-03T15:33:38+00:00" }, { "id": 2402405143, "user": "user_29e85f9a8e75", "body": "```suggestion\n\n is_typealiastype = False # Default: assume not a TypeAliasType\n```", "path": "fastapi/dependencies/utils.py", "line": null, "side": "RIGHT", "created_at": "2025-10-03T15:35:05+00:00" }, { "id": 2402408870, "user": "user_29e85f9a8e75", "body": "```suggestion\n # Case 1: Both implementations are the same object.\n # Checking against one of them.\n is_typealiastype = isinstance(tp, typing.TypeAliasType) # type: ignore [attr-defined]\n```", "path": "fastapi/dependencies/utils.py", "line": null, "side": "RIGHT", "created_at": "2025-10-03T15:36:57+00:00" }, { "id": 2402411572, "user": "user_29e85f9a8e75", "body": "```suggestion\n # Case 2: Implementations are different objects.\n # Need to check against both versions.\n is_typealiastype = isinstance(\n```", "path": "fastapi/dependencies/utils.py", "line": null, "side": "RIGHT", "created_at": "2025-10-03T15:38:16+00:00" }, { "id": 2402413321, "user": "user_29e85f9a8e75", "body": "```suggestion\n # Case 3: Only typing.TypeAliasType exists.\n is_typealiastype = isinstance(tp, typing.TypeAliasType) # type: ignore [attr-defined]\n```", "path": "fastapi/dependencies/utils.py", "line": null, "side": "RIGHT", "created_at": "2025-10-03T15:39:05+00:00" }, { "id": 2402414583, "user": "user_29e85f9a8e75", "body": "```suggestion\n # Case 4: Only typing_extensions.TypeAliasType exists.\n is_typealiastype = isinstance(tp, typing_extensions.TypeAliasType)\n```", "path": "fastapi/dependencies/utils.py", "line": null, "side": "RIGHT", "created_at": "2025-10-03T15:39:43+00:00" }, { "id": 2402416503, "user": "user_29e85f9a8e75", "body": "```suggestion\n\n # Special case for Python 3.10:\n # On Python 3.10, parameterized PEP 695 type aliases are represented as `GenericAlias`\n # instead of proper TypeAliasType. We must exclude those.\n if sys.version_info[:2] == (3, 10):\n```", "path": "fastapi/dependencies/utils.py", "line": null, "side": "RIGHT", "created_at": "2025-10-03T15:40:33+00:00" }, { "id": 2402430187, "user": "user_29e85f9a8e75", "body": "```suggestion\n # unpack in case PEP 695 type syntax is used\n```", "path": "fastapi/dependencies/utils.py", "line": null, "side": "RIGHT", "created_at": "2025-10-03T15:46:44+00:00" }, { "id": 2402456559, "user": "user_29e85f9a8e75", "body": "Do we really need this import?", "path": "tests/test_dependency_pep695.py", "line": null, "side": "RIGHT", "created_at": "2025-10-03T15:53:55+00:00" }, { "id": 2472559581, "user": "user_35cb99d940a0", "body": "I also think is redundant and can be removed", "path": "tests/test_dependency_pep695.py", "line": null, "side": "RIGHT", "created_at": "2025-10-29T10:59:54+00:00" } ], "meta": { "languages": [ "lock", "py", "toml" ], "touches_tests": true, "review_state_summary": { "APPROVED": 3, "COMMENTED": 1 }, "meaningful_comment_count": 10, "has_approval": true, "has_changes_requested": false, "total_review_comments": 10 } } { "_id": "8a5d9a65da6e620e", "_schema_version": "1.0", "_cleaned_at": "2026-02-12T07:46:51.734133+00:00", "repo": "tiangolo/fastapi", "repo_url": "https://github.com/fastapi/fastapi", "license_name": "MIT License", "license_spdx": "MIT", "pr_number": 13875, "title": "🌐 Update Portuguese Translation for `docs/pt/docs/project-generation.md`", "body": null, "author": "user_e1f1c455eab6", "created_at": "2025-07-08T12:32:17+00:00", "merged_at": "2025-07-21T09:57:31+00:00", "base_branch": "master", "head_branch": "docs/update-pt-translation-for-project-generation", "additions": 28, "deletions": 84, "changed_files": 1, "files": [ { "filename": "docs/pt/docs/project-generation.md", "status": "modified", "additions": 28, "deletions": 84, "changes": 112, "patch": "@@ -1,84 +1,28 @@\n-# Geração de Projetos - Modelo\n-\n-Você pode usar um gerador de projetos para começar, por já incluir configurações iniciais, segurança, banco de dados e os primeiros _endpoints_ API já feitos para você.\n-\n-Um gerador de projetos sempre terá uma pré-configuração que você pode atualizar e adaptar para suas próprias necessidades, mas pode ser um bom ponto de partida para seu projeto.\n-\n-## [NAME_REDACTED] PostgreSQL\n-\n-GitHub: https://github.com/[USER_REDACTED]ngolo/full-stack-fastapi-postgresql\n-\n-### [NAME_REDACTED] PostgreSQL - Recursos\n-\n-* Integração completa **Docker**.\n-* Modo de implantação [NAME_REDACTED].\n-* Integração e otimização **[NAME_REDACTED]** para desenvolvimento local.\n-* **Pronto para Produção** com servidor _web_ usando Uvicorn e Gunicorn.\n-* _Backend_ **FastAPI** Python:\n- * **Rápido**: Alta performance, no nível de **NodeJS** e **Go** (graças ao Starlette e Pydantic).\n- * **Intuitivo**: Ótimo suporte de editor. _Auto-Complete_ em todo lugar. Menos tempo _debugando_.\n- * **Fácil**: Projetado para ser fácil de usar e aprender. Menos tempo lendo documentações.\n- * **Curto**: Minimize duplicação de código. Múltiplos recursos para cada declaração de parâmetro.\n- * **Robusto**: Tenha código pronto para produção. Com documentação interativa automática.\n- * **Baseado em Padrões**: Baseado em (e completamente compatível com) padrões abertos para APIs: OpenAPI e JSON Schema.\n- * **Muitos outros recursos** incluindo validação automática, serialização, documentação interativa, autenticação com _tokens_ OAuth2 JWT etc.\n-* **Senha segura** _hashing_ por padrão.\n-* Autenticação **Token JWT**.\n-* Modelos **SQLAlchemy** (independente de extensões Flask, para que eles possam ser usados com _workers_ Celery diretamente).\n-* Modelos básicos para usuários (modifique e remova conforme suas necessidades).\n-* Migrações **Alembic**.\n-* **CORS** (_Cross [NAME_REDACTED] Sharing_ - Compartilhamento de [NAME_REDACTED]).\n-* _Worker_ **Celery** que pode importar e usar modelos e códigos do resto do _backend_ seletivamente.\n-* Testes _backend_ _REST_ baseados no **Pytest**, integrados com Docker, então você pode testar a interação completa da API, independente do banco de dados. Como roda no Docker, ele pode construir um novo repositório de dados do zero toda vez (assim você pode usar ElasticSearch, MongoDB, CouchDB, ou o que quiser, e apenas testar que a API esteja funcionando).\n-* Fácil integração com Python através dos **[NAME_REDACTED]** para desenvolvimento remoto ou no Docker com extensões como [NAME_REDACTED] ou [NAME_REDACTED] Jupyter.\n-* _Frontend_ **Vue**:\n- * Gerado com Vue CLI.\n- * Controle de **Autenticação JWT**.\n- * Visualização de _login_.\n- * Após o _login_, visualização do painel de controle principal.\n- * Painel de controle principal com criação e edição de usuário.\n- * Edição do próprio usuário.\n- * **Vuex**.\n- * **Vue-router**.\n- * **Vuetify** para belos componentes _material design_.\n- * **TypeScript**.\n- * [NAME_REDACTED] baseado em **Nginx** (configurado para rodar \"lindamente\" com Vue-router).\n- * Construção multi-estágio Docker, então você não precisa salvar ou _commitar_ código compilado.\n- * Testes _frontend_ rodados na hora da construção (pode ser desabilitado também).\n- * Feito tão modular quanto possível, então ele funciona fora da caixa, mas você pode gerar novamente com Vue CLI ou criar conforme você queira, e reutilizar o que quiser.\n-* **PGAdmin** para banco de dados PostgreSQL, você pode modificar para usar PHPMyAdmin e MySQL facilmente.\n-* **Flower** para monitoração de tarefas Celery.\n-* Balanceamento de carga entre _frontend_ e _backend_ com **Traefik**, então você pode ter ambos sob o mesmo domínio, separados por rota, mas servidos por diferentes containers.\n-* Integração Traefik, incluindo geração automática de certificados **HTTPS** [NAME_REDACTED].\n-* GitLab **CI** (integração contínua), incluindo testes _frontend_ e _backend_.\n-\n-## [NAME_REDACTED] Couchbase\n-\n-GitHub: https://github.com/[USER_REDACTED]ngolo/full-stack-fastapi-couchbase\n-\n-⚠️ **WARNING** ⚠️\n-\n-Se você está iniciando um novo projeto do zero, verifique as alternativas aqui.\n-\n-Por exemplo, o gerador de projetos [NAME_REDACTED] PostgreSQL pode ser uma alternativa melhor, como ele é ativamente mantido e utilizado. E ele inclui todos os novos recursos e melhorias.\n-\n-Você ainda é livre para utilizar o gerador baseado em Couchbase se quiser, ele provavelmente ainda funciona bem, e você já tem um projeto gerado com ele que roda bem também (e você provavelmente já atualizou ele para encaixar nas suas necessidades).\n-\n-Você pode ler mais sobre nas documentaçãoes do repositório.\n-\n-## [NAME_REDACTED] MongoDB\n-\n-...pode demorar, dependendo do meu tempo disponível e outros fatores. 😅 🎉\n-\n-## Modelos de Aprendizado de Máquina com spaCy e FastAPI\n-\n-GitHub: https://github.com/microsoft/cookiecutter-spacy-fastapi\n-\n-### Modelos de Aprendizado de Máquina com spaCy e FastAPI - Recursos\n-\n-* Integração com modelo NER **spaCy**.\n-* Formato de requisição **[NAME_REDACTED]** acoplado.\n-* [NAME_REDACTED] _web_ **Pronto para Produção** usando Uvicorn e Gunicorn.\n-* Implantação **[NAME_REDACTED]** Kubernetes (AKS) CI/CD acoplada.\n-* **Multilingual** facilmente escolhido como uma das linguagens spaCy acopladas durante a configuração do projeto.\n-* **Facilmente extensível** para outros modelos de _frameworks_ (Pytorch, Tensorflow), não apenas spaCy.\n+# [NAME_REDACTED] Template\n+\n+_Templates_, embora tipicamente venham com alguma configuração específica, são desenhados para serem flexíveis e customizáveis. Isso permite que você os modifique e adapte para as especificações do seu projeto, fazendo-os um excelente ponto de partida. 🏁\n+\n+Você pode usar esse _template_ para começar, já que ele inclui várias configurações iniciais, segurança, banco de dados, e alguns _endpoints_ de API já feitos para você.\n+\n+Repositório GitHub: [NAME_REDACTED] Template\n+\n+## [NAME_REDACTED] Template - Pilha de Tecnologias e Recursos\n+\n+- ⚡ [**FastAPI**](https://fastapi.tiangolo.com) para a API do backend em Python.\n+ - 🧰 [SQLModel](https://sqlmodel.tiangolo.com) para as interações do Python com bancos de dados SQL (ORM).\n+ - 🔍 [Pydantic](https://docs.pydantic.dev), usado pelo FastAPI, para validação de dados e gerenciamento de configurações.\n+ - 💾 [PostgreSQL](https://www.postgresql.org) como banco de dados SQL.\n+- 🚀 [React](https://react.dev) para o frontend.\n+ - 💃 [NAME_REDACTED], hooks, [Vite](https://vitejs.dev), e outras partes de uma _stack_ frontend moderna.\n+ - 🎨 [Chakra UI](https://chakra-ui.com) para os componentes de frontend.\n+ - 🤖 Um cliente frontend automaticamente gerado.\n+ - 🧪 [Playwright](https://playwright.dev) para testes Ponta-a-Ponta.\n+ - 🦇 Suporte para modo escuro.\n+- 🐋 [[NAME_REDACTED]](https://www.docker.com) para desenvolvimento e produção.\n+- 🔒 _Hash_ seguro de senhas por padrão.\n+- 🔑 Autenticação por token JWT.\n+- 📫 Recuperação de senhas baseada em email.\n+- ✅ Testes com [Pytest](https://pytest.org).\n+- 📞 [Traefik](https://traefik.io) como proxy reverso / balanceador de carga.\n+- 🚢 Instruções de _deployment_ usando [NAME_REDACTED], incluindo como configurar um proxy frontend com Traefik para gerenciar automaticamente certificados HTTPS.\n+- 🏭 CI (Integração Contínua) e CD (_Deploy_ Contínuo) baseado em GitHub Actions." } ], "reviews": [ { "id": 2998201566, "user": "user_e10da7d15f57", "state": "COMMENTED", "body": "[USER_REDACTED] is not missing content, or is the original language in that way?", "submitted_at": "2025-07-08T15:41:04+00:00" }, { "id": 2998505458, "user": "user_e10da7d15f57", "state": "APPROVED", "body": "[USER_REDACTED], well done. 🎉", "submitted_at": "2025-07-08T17:20:19+00:00" }, { "id": 3016422079, "user": "user_178cb4401e94", "state": "CHANGES_REQUESTED", "body": "great ✨ \n\nJust a really small typo ❤️", "submitted_at": "2025-07-14T13:40:30+00:00" }, { "id": 3016831778, "user": "user_e1f1c455eab6", "state": "COMMENTED", "body": null, "submitted_at": "2025-07-14T15:35:40+00:00" }, { "id": 3024801504, "user": "user_178cb4401e94", "state": "APPROVED", "body": "❤️", "submitted_at": "2025-07-16T12:49:25+00:00" } ], "review_comments": [ { "id": 2204971766, "user": "user_178cb4401e94", "body": "just a small typo:\n\n\"alguma configuração específic**a**\"", "path": "docs/pt/docs/project-generation.md", "line": null, "side": "RIGHT", "created_at": "2025-07-14T13:38:24+00:00" }, { "id": 2205234085, "user": "user_e1f1c455eab6", "body": "Thank you!!", "path": "docs/pt/docs/project-generation.md", "line": null, "side": "RIGHT", "created_at": "2025-07-14T15:35:40+00:00" } ], "meta": { "languages": [ "md" ], "touches_tests": false, "review_state_summary": { "COMMENTED": 2, "APPROVED": 2, "CHANGES_REQUESTED": 1 }, "meaningful_comment_count": 2, "has_approval": true, "has_changes_requested": true, "total_review_comments": 2 } } { "_id": "7d26380cee48b0ed", "_schema_version": "1.0", "_cleaned_at": "2026-02-12T07:46:51.734133+00:00", "repo": "tiangolo/fastapi", "repo_url": "https://github.com/fastapi/fastapi", "license_name": "MIT License", "license_spdx": "MIT", "pr_number": 13863, "title": "🌐 Update Portuguese Translation for `docs/pt/docs/async.md`", "body": null, "author": "user_e1f1c455eab6", "created_at": "2025-07-04T19:21:32+00:00", "merged_at": "2025-07-26T11:16:40+00:00", "base_branch": "master", "head_branch": "docs/update-pt-translation-for-async", "additions": 108, "deletions": 99, "changed_files": 1, "files": [ { "filename": "docs/pt/docs/async.md", "status": "modified", "additions": 108, "deletions": 99, "changes": 207, "patch": "@@ -40,7 +40,7 @@ def results():\n \n ---\n \n-Se sua aplicação (de alguma forma) não tem que se comunicar com nada mais e tem que esperar que o respondam, use `async def`.\n+Se sua aplicação (de alguma forma) não tem que se comunicar com nada mais e esperar que o respondam, use `async def`.\n \n ---\n \n@@ -52,7 +52,7 @@ Se você simplesmente não sabe, use apenas `def`.\n \n De qualquer forma, em ambos os casos acima, FastAPI irá trabalhar assincronamente e ser extremamente rápido.\n \n-Seguindo os passos acima, ele será capaz de fazer algumas otimizações de performance.\n+Mas, seguindo os passos acima, ele será capaz de fazer algumas otimizações de performance.\n \n ## Detalhes Técnicos\n \n@@ -66,36 +66,36 @@ Vamos ver aquela frase por partes na seção abaixo:\n \n ## Código assíncrono\n \n-Código assíncrono apenas significa que a linguagem 💬 tem um jeito de dizer para o computador / programa 🤖 que em certo ponto, ele 🤖 terá que esperar por *algo* para finalizar em outro lugar. Vamos dizer que esse *algo* seja chamado \"arquivo lento\" 📝.\n+Código assíncrono apenas significa que a linguagem 💬 tem um jeito de dizer para o computador / programa 🤖 que em certo ponto do código, ele 🤖 terá que esperar *algo* finalizar em outro lugar. Vamos dizer que esse *algo* seja chamado \"arquivo lento\" 📝.\n \n-Então, durante esse tempo, o computador pode ir e fazer outro trabalho, enquanto o \"arquivo lento\" 📝 termine.\n+Então, durante esse tempo, o computador pode ir e fazer outro trabalho, enquanto o \"arquivo lento\" 📝 termina.\n \n-Então o computador / programa 🤖 irá voltar toda hora que tiver uma chance porquê ele ainda está esperando o \"arquivo lento\", ou ele 🤖 nunca irá terminar todo o trabalho que tem até esse ponto. E ele 🤖 irá ver se alguma das tarefas que estava esperando já terminaram, fazendo o que quer que tinham que fazer.\n+Então o computador / programa 🤖 irá voltar sempre que tiver uma chance, seja porque ele está esperando novamente, ou quando ele 🤖 terminar todo o trabalho que tem até esse ponto. E ele 🤖 irá ver se alguma das tarefas que estava esperando já terminaram de fazer o que quer que tinham que fazer.\n \n-Depois, ele 🤖 pega a primeira tarefa para finalizar (vamos dizer, nosso \"arquivo lento\" 📝) e continua o que ele tem que fazer com isso.\n+Depois, ele 🤖 pega a primeira tarefa para finalizar (vamos dizer, nosso \"arquivo lento\" 📝) e continua o que tem que fazer com ela.\n \n-Esse \"esperar por algo\" normalmente se refere a operações I/O que são relativamente \"lentas\" (comparadas a velocidade do processador e da memória RAM), como esperar por:\n+Esse \"esperar por algo\" normalmente se refere a operações I/O que são relativamente \"lentas\" (comparadas à velocidade do processador e da memória RAM), como esperar por:\n \n * dados do cliente para serem enviados através da rede\n-* dados enviados pelo seu programa para serem recebidos pelo clente através da rede\n-* conteúdo de um arquivo no disco pra ser lido pelo sistema e entregar ao seu programa\n+* dados enviados pelo seu programa serem recebidos pelo clente através da rede\n+* conteúdo de um arquivo no disco ser lido pelo sistema e entregue ao seu programa\n * conteúdo que seu programa deu ao sistema para ser escrito no disco\n-* uma operação remota API\n-* uma operação no banco de dados para finalizar\n-* uma solicitação no banco de dados esperando o retorno do resultado\n+* uma operação em uma API remota\n+* uma operação no banco de dados finalizar\n+* uma solicitação no banco de dados retornar o resultado\n * etc.\n \n-Enquanto o tempo de execução é consumido mais pela espera das operações I/O, essas operações são chamadas de operações \"limitadas por I/O\".\n+Quanto o tempo de execução é consumido majoritariamente pela espera de operações I/O, essas operações são chamadas operações \"limitadas por I/O\".\n \n-Isso é chamado de \"assíncrono\" porquê o computador / programa não tem que ser \"sincronizado\" com a tarefa lenta, esperando pelo exato momento que a tarefa finalize, enquanto não faz nada, para ser capaz de pegar o resultado da tarefa e dar continuidade ao trabalho.\n+Isso é chamado de \"assíncrono\" porque o computador / programa não tem que ser \"sincronizado\" com a tarefa lenta, esperando pelo momento exato em que a tarefa finaliza, enquanto não faz nada, para ser capaz de pegar o resultado da tarefa e dar continuidade ao trabalho.\n \n-Ao invés disso, sendo um sistema \"assíncrono\", uma vez finalizada, a tarefa pode esperar um pouco (alguns microssegundos) para que o computador / programa finalize o que quer que esteja fazendo,e então volte para pegar o resultado e continue trabalhando com ele.\n+Ao invés disso, sendo um sistema \"assíncrono\", uma vez finalizada, a tarefa pode esperar na fila um pouco (alguns microssegundos) para que o computador / programa finalize o que quer que esteja fazendo, e então volte para pegar o resultado e continue trabalhando com ele.\n \n-Para \"síncrono\" (contrário de \"assíncrono\") também é utilizado o termo \"sequencial\", porquê o computador / programa segue todos os passos, na sequência, antes de trocar para uma tarefa diferente, mesmo se alguns passos envolvam esperar.\n+Para \"síncrono\" (contrário de \"assíncrono\") também é utilizado o termo \"sequencial\", porquê o computador / programa segue todos os passos, em sequência, antes de trocar para uma tarefa diferente, mesmo se alguns passos envolvam esperar.\n \n ### Concorrência e hambúrgueres\n \n-Essa idéia de código **assíncrono** descrito acima é algo às vezes chamado de **\"concorrência\"**. E é diferente de **\"paralelismo\"**.\n+Essa idéia de código **assíncrono** descrita acima é às vezes chamado de **\"concorrência\"**. Isso é diferente de **\"paralelismo\"**.\n \n **Concorrência** e **paralelismo** ambos são relacionados a \"diferentes coisas acontecendo mais ou menos ao mesmo tempo\".\n \n@@ -105,117 +105,115 @@ Para ver essa diferença, imagine a seguinte história sobre hambúrgueres:\n \n ### Hambúrgueres concorrentes\n \n-Você vai com seu _crush_ :heart_eyes: na lanchonete, fica na fila enquanto o caixa pega os pedidos das pessoas na sua frente.\n+Você vai com seu _crush_ na lanchonete, e fica na fila enquanto o caixa pega os pedidos das pessoas na sua frente. 😍\n \n-Então chega a sua vez, você pede dois saborosos hambúrgueres para você e seu _crush_ :heart_eyes:.\n+Então chega a sua vez, você pede dois saborosos hambúrgueres para você e seu _crush_. 🍔🍔\n \n-Você paga.\n+O caixa diz alguma coisa para o cozinheiro na cozinha para que eles saivam que têm que preparar seus hambúrgueres (mesmo que ele esteja atualmente preparando os lanches dos outros clientes).\n \n-O caixa diz alguma coisa para o cara na cozinha para que ele tenha que preparar seus hambúrgueres (mesmo embora ele esteja preparando os lanches dos outros clientes).\n+Você paga. 💸\n \n O caixa te entrega seu número de chamada.\n \n-Enquanto você espera, você vai com seu _crush_ :heart_eyes: e pega uma mesa, senta e conversa com seu _crush_ :heart_eyes: por um bom tempo (como seus hambúrgueres são muito saborosos, leva um tempo para serem preparados).\n+Enquanto você espera, você vai com seu _crush_ e pega uma mesa, senta e conversa com seu _crush_ por um bom tempo (já que seus hambúrgueres são muito saborosos, e leva um tempo para serem preparados).\n \n-Enquanto você está sentado na mesa com seu _crush_ :heart_eyes:, esperando os hambúrgueres, você pode gastar o tempo admirando como lindo, maravilhoso e esperto é seu _crush_ :heart_eyes:.\n+Já que você está sentado na mesa com seu _crush_, esperando os hambúrgueres, você pode passar esse tempo admirando o quão lindo, maravilhoso e esperto é seu _crush_ ✨😍✨.\n \n-Enquanto espera e conversa com seu _crush_ :heart_eyes:, de tempos em tempos, você verifica o número de chamada exibido no balcão para ver se já é sua vez.\n+Enquanto espera e conversa com seu _crush_, de tempos em tempos, você verifica o número da chamada exibido no balcão para ver se já é sua vez.\n \n-Então a certo ponto, é finalmente sua vez. Você vai no balcão, pega seus hambúrgueres e volta para a mesa.\n+Então em algum momento, é finalmente sua vez. Você vai ao balcão, pega seus hambúrgueres e volta para a mesa.\n \n-Você e seu _crush_ :heart_eyes: comem os hambúrgueres e aproveitam o tempo.\n+Você e seu _crush_ comem os hambúrgueres e aproveitam o tempo. ✨\n \n ---\n \n-Imagine que você seja o computador / programa nessa história.\n+Imagine que você seja o computador / programa nessa história.\n \n-Enquanto você está na fila, tranquilo, esperando por sua vez, não está fazendo nada \"produtivo\". Mas a fila é rápida porquê o caixa só está pegando os pedidos, então está tudo bem.\n+Enquanto você está na fila, você está somente ocioso 😴, esperando por sua vez, sem fazer nada muito \"produtivo\". Mas a fila é rápida porque o caixa só está pegando os pedidos (não os preparando), então está tudo bem.\n \n-Então, quando é sua vez, você faz o trabalho \"produtivo\" de verdade, você processa o menu, decide o que quer, pega a escolha de seu _crush_ :heart_eyes:, paga, verifica se entregou o valor correto em dinheiro ou cartão de crédito, verifica se foi cobrado corretamente, verifica se seu pedido está correto etc.\n+Então, quando é sua vez, você faz trabalho realmente \"produtivo\", você processa o menu, decide o que quer, pega a escolha de seu _crush_, paga, verifica se entregou o cartão ou a cédula correta, verifica se foi cobrado corretamente, verifica se seu pedido está correto etc.\n \n-Mas então, embora você ainda não tenha os hambúrgueres, seu trabalho no caixa está \"pausado\", porquê você tem que esperar seus hambúrgueres estarem prontos.\n+Mas então, embora você ainda não tenha os hambúrgueres, seu trabalho no caixa está \"pausado\" ⏸, porque você tem que esperar 🕙 seus hambúrgueres ficarem prontos.\n \n-Mas enquanto você se afasta do balcão e senta na mesa com o número da sua chamada, você pode trocar sua atenção para seu _crush_ :heart_eyes:, e \"trabalhar\" nisso. Então você está novamente fazendo algo muito \"produtivo\", como flertar com seu _crush_ :heart_eyes:.\n+Contudo, à medida que você se afasta do balcão e senta na mesa, com um número para sua chamada, você pode trocar 🔀 sua atenção para seu _crush_, e \"trabalhar\" ⏯ 🤓 nisso. Então você está novamente fazendo algo muito \"produtivo\", como flertar com seu _crush_ 😍.\n \n-Então o caixa diz que \"seus hambúrgueres estão prontos\" colocando seu número no balcão, mas você não corre que nem um maluco imediatamente quando o número exibido é o seu. Você sabe que ninguém irá roubar seus hambúrgueres porquê você tem o número de chamada, e os outros tem os números deles.\n+Então o caixa 💁 diz que \"seus hambúrgueres estão prontos\" colocando seu número no balcão, mas você não corre que nem um maluco imediatamente quando o número exibido é o seu. Você sabe que ninguém irá roubar seus hambúrgueres porque você tem o seu número da chamada, e os outros têm os deles.\n \n-Então você espera que seu _crush_ :heart_eyes: termine a história que estava contando (terminar o trabalho atual / tarefa sendo processada), sorri gentilmente e diz que você está indo buscar os hambúrgueres.\n+Então você espera seu _crush_ terminar a história que estava contando (terminar o trabalho atual ⏯ / tarefa sendo processada 🤓), sorri gentilmente e diz que você está indo buscar os hambúrgueres.\n \n-Então você vai no balcão, para a tarefa inicial que agora está finalizada, pega os hambúrgueres, e leva para a mesa. Isso finaliza esse passo / tarefa da interação com o balcão. Agora é criada uma nova tarefa, \"comer hambúrgueres\", mas a tarefa anterior, \"pegar os hambúrgueres\" já está finalizada.\n+Então você vai ao balcão 🔀, para a tarefa inicial que agora está finalizada⏯, pega os hambúrgueres, agradece, e leva-os para a mesa. Isso finaliza esse passo / tarefa da interação com o balcão ⏹. Isso, por sua vez, cria uma nova tarefa, a de \"comer hambúrgueres\" 🔀 ⏯, mas a tarefa anterior de \"pegar os hambúrgueres\" já está finalizada ⏹.\n \n ### Hambúrgueres paralelos\n \n-Você vai com seu _crush_ :heart_eyes: em uma lanchonete paralela.\n+Agora vamos imaginar que esses não são \"Hambúrgueres Concorrentes\", e sim \"Hambúrgueres Paralelos\"\n \n-Você fica na fila enquanto alguns (vamos dizer 8) caixas pegam os pedidos das pessoas na sua frente.\n+Você vai com seu _crush_ na lanchonete paralela.\n \n-Todo mundo antes de você está esperando pelos hambúrgueres estarem prontos antes de deixar o caixa porquê cada um dos 8 caixas vai e prepara o hambúrguer antes de pegar o próximo pedido.\n+Você fica na fila enquanto vários (vamos dizer 8) caixas que também são cozinheiros pegam os pedidos das pessoas na sua frente.\n \n-Então é finalmente sua vez, e pede 2 hambúrgueres muito saborosos para você e seu _crush_ :heart_eyes:.\n+Todo mundo na sua frente está esperando seus hambúrgueres ficarem prontos antes de deixar o caixa porque cada um dos 8 caixas vai e prepara o hambúrguer logo após receber o pedido, antes de pegar o próximo pedido.\n \n-Você paga.\n+Então é finalmente sua vez, você pede 2 hambúrgueres muito saborosos para você e seu _crush_.\n+\n+Você paga 💸.\n \n O caixa vai para a cozinha.\n \n-Você espera, na frente do balcão, para que ninguém pegue seus hambúrgueres antes de você, já que não tem números de chamadas.\n+Você espera, na frente do balcão 🕙, para que ninguém pegue seus hambúrgueres antes de você, já que não tem números de chamadas.\n \n-Enquanto você e seu _crush_ :heart_eyes: estão ocupados não permitindo que ninguém passe a frente e pegue seus hambúrgueres assim que estiverem prontos, você não pode dar atenção ao seu _crush_ :heart_eyes:.\n+Como você e seu _crush_ estão ocupados não permitindo que ninguém passe na frente e pegue seus hambúrgueres assim que estiverem prontos, você não pode dar atenção ao seu _crush_. 😞\n \n-Isso é trabalho \"síncrono\", você está \"sincronizado\" com o caixa / cozinheiro. Você tem que esperar e estar lá no exato momento que o caixa / cozinheiro terminar os hambúrgueres e dá-los a você, ou então, outro alguém pode pegá-los.\n+Isso é trabalho \"síncrono\", você está \"sincronizado\" com o caixa / cozinheiro👨‍🍳. Você tem que esperar 🕙 e estar lá no exato momento que o caixa / cozinheiro 👨‍🍳 terminar os hambúrgueres e os der a você, ou então, outro alguém pode pegá-los.\n \n-Então seu caixa / cozinheiro finalmente volta com seus hambúrgueres, depois de um longo tempo esperando por eles em frente ao balcão.\n+Então seu caixa / cozinheiro 👨‍🍳 finalmente volta com seus hambúrgueres, depois de um longo tempo esperando 🕙 por eles em frente ao balcão.\n \n-Você pega seus hambúrgueres e vai para a mesa com seu _crush_ :heart_eyes:.\n+Você pega seus hambúrgueres e vai para a mesa com seu _crush_.\n \n-Vocês comem os hambúrgueres, e o trabalho está terminado.\n+Vocês comem os hambúrgueres, e o trabalho está terminado. ⏹\n \n-Não houve muita conversa ou flerte já que a maior parte do tempo foi gasto esperando os lanches na frente do balcão.\n+Não houve muita conversa ou flerte já que a maior parte do tempo foi gasto esperando 🕙 na frente do balcão. 😞\n \n ---\n \n-Nesse cenário dos hambúrgueres paralelos, você é um computador / programa com dois processadores (você e seu _crush_ :heart_eyes:), ambos esperando e dedicando a atenção de estar \"esperando no balcão\" por um bom tempo.\n+Nesse cenário dos hambúrgueres paralelos, você é um computador / programa com dois processadores (você e seu _crush_), ambos esperando 🕙 e dedicando sua atenção ⏯ \"esperando no balcão\" 🕙 por um bom tempo.\n \n-A lanchonete paralela tem 8 processadores (caixas / cozinheiros). Enquanto a lanchonete dos hambúrgueres concorrentes tinham apenas 2 (um caixa e um cozinheiro).\n+A lanchonete paralela tem 8 processadores (caixas / cozinheiros), enquanto a lanchonete dos hambúrgueres concorrentes tinha apenas 2 (um caixa e um cozinheiro).\n \n-Ainda assim, a última experiência não foi a melhor.\n+Ainda assim, a experiência final não foi a melhor. 😞\n \n ---\n \n-Essa poderia ser a história paralela equivalente aos hambúrgueres.\n+Essa seria o equivalente paralelo à histório dos hambúrgueres. 🍔\n \n Para um exemplo \"mais real\", imagine um banco.\n \n-Até recentemente, a maioria dos bancos tinha muitos caixas e uma grande fila.\n+Até recentemente, a maioria dos bancos tinham muitos caixas 👨‍💼👨‍💼👨‍💼👨‍💼 e uma grande fila 🕙🕙🕙🕙🕙🕙🕙🕙.\n \n-Todos os caixas fazendo todo o trabalho, um cliente após o outro.\n+Todos os caixas fazendo todo o trabalho, um cliente após o outro 👨‍💼⏯.\n \n-E você tinha que esperar na fila por um longo tempo ou poderia perder a vez.\n+E você tinha que esperar 🕙 na fila por um longo tempo ou poderia perder a vez.\n \n-Você provavelmente não gostaria de levar seu _crush_ :heart_eyes: com você para um rolezinho no banco.\n+Você provavelmente não gostaria de levar seu _crush_ 😍 com você para um rolezinho no banco 🏦.\n \n ### Conclusão dos hambúrgueres\n \n-Nesse cenário dos \"hambúrgueres com seu _crush_ :heart_eyes:\", como tem muita espera, faz mais sentido ter um sistema concorrente.\n+Nesse cenário dos \"hambúrgueres com seu _crush_\", como tem muita espera, faz mais sentido ter um sistema concorrente ⏸🔀⏯.\n \n Esse é o caso da maioria das aplicações web.\n \n-Geralmente são muitos usuários, e seu servidor está esperando pelas suas conexões não tão boas para enviar as requisições.\n-\n-E então esperando novamente pelas respostas voltarem.\n-\n-Essa \"espera\" é medida em microssegundos, e ainda assim, somando tudo, é um monte de espera no final.\n+Muitos, muitos usuários, mas seu servidor está esperando 🕙 pela sua conexão não tão boa enviar suas requisições.\n \n-Por isso que faz muito mais sentido utilizar código assíncrono para APIs web.\n+E então esperando 🕙 novamente as respostas voltarem.\n \n-A maioria dos frameworks Python existentes mais populares (incluindo Flask e Django) foram criados antes que os novos recursos assíncronos existissem em Python. Então, os meios que eles podem ser colocados em produção para suportar execução paralela mais a forma antiga de execução assíncrona não são tão poderosos quanto as novas capacidades.\n+Essa \"espera\" 🕙 é medida em microssegundos, mas ainda assim, somando tudo, é um monte de espera no final.\n \n-Mesmo embora a especificação principal para web assíncrono em Python (ASGI) foi desenvolvida no Django, para adicionar suporte para WebSockets.\n+Por isso que faz bastante sentido utilizar código assíncrono ⏸🔀⏯ para APIs web.\n \n-Esse tipo de assincronicidade é o que fez NodeJS popular (embora NodeJS não seja paralelo) e que essa seja a força do Go como uma linguagem de programa.\n+Esse tipo de assincronicidade é o que fez NodeJS popular (embora NodeJS não seja paralelo) e essa é a força do Go como uma linguagem de programação.\n \n E esse é o mesmo nível de performance que você tem com o **FastAPI**.\n \n-E como você pode ter paralelismo e sincronicidade ao mesmo tempo, você tem uma maior performance do que a maioria dos frameworks NodeJS testados e lado a lado com Go, que é uma linguagem compilada próxima ao C (tudo graças ao Starlette).\n+E como você pode ter paralelismo e assincronicidade ao mesmo tempo, você tem uma maior performance do que a maioria dos frameworks NodeJS testados e lado a lado com Go, que é uma linguagem compilada, mais próxima ao C (tudo graças ao Starlette).\n \n ### Concorrência é melhor que paralelismo?\n \n@@ -225,64 +223,64 @@ Concorrência é diferente de paralelismo. E é melhor em cenários **específic\n \n Então, para equilibrar tudo, imagine a seguinte historinha:\n \n-> Você tem que limpar uma grande casa suja.\n+> Você tem que limpar uma casa grande e suja.\n \n *Sim, essa é toda a história*.\n \n ---\n \n-Não há espera em lugar algum, apenas um monte de trabalho para ser feito, em múltiplos cômodos da casa.\n+Não há espera 🕙 em lugar algum, apenas um monte de trabalho para ser feito, em múltiplos cômodos da casa.\n \n-Você poderia ter chamadas como no exemplo dos hambúrgueres, primeiro a sala de estar, então a cozinha, mas você não está esperando por nada, apenas limpar e limpar, as chamadas não afetariam em nada.\n+Você poderia ter turnos como no exemplo dos hambúrgueres, primeiro a sala de estar, então a cozinha, mas como você não está esperando por nada, apenas limpando e limpando, as chamadas não afetariam em nada.\n \n-Levaria o mesmo tempo para finalizar com ou sem chamadas (concorrência) e você teria feito o mesmo tanto de trabalho.\n+Levaria o mesmo tempo para finalizar com ou sem turnos (concorrência) e você teria feito o mesmo tanto de trabalho.\n \n Mas nesse caso, se você trouxesse os 8 ex-caixas / cozinheiros / agora-faxineiros, e cada um deles (mais você) pudessem dividir a casa para limpá-la, vocês fariam toda a limpeza em **paralelo**, com a ajuda extra, e terminariam muito mais cedo.\n \n Nesse cenário, cada um dos faxineiros (incluindo você) poderia ser um processador, fazendo a sua parte do trabalho.\n \n-E a maior parte do tempo de execução é tomada por trabalho (ao invés de ficar esperando), e o trabalho em um computador é feito pela CPU, que podem gerar problemas que são chamados de \"limite de CPU\".\n+E a maior parte do tempo de execução é tomada por trabalho real (ao invés de ficar esperando), e o trabalho em um computador é feito pela CPU. Eles chamam esses problemas de \"limitados por CPU\".\n \n ---\n \n-Exemplos comuns de limite de CPU são coisas que exigem processamento matemático complexo.\n+Exemplos comuns de operações limitadas por CPU são coisas que exigem processamento matemático complexo.\n \n Por exemplo:\n \n * **Processamento de áudio** ou **imagem**\n-* **Visão do Computador**: uma imagem é composta por milhões de pixels, cada pixel tem 3 valores (cores, processamento que normalmente exige alguma computação em todos esses pixels ao mesmo tempo)\n+* **Visão Computacional**: uma imagem é composta por milhões de pixels, cada pixel tem 3 valores / cores, processar isso normalmente exige alguma computação em todos esses pixels ao mesmo tempo\n \n-* **[NAME_REDACTED]**: Normalmente exige muita multiplicação de matrizes e vetores. Pense numa grande folha de papel com números e multiplicando todos eles juntos e ao mesmo tempo.\n+* **[NAME_REDACTED]**: Normalmente exige muita multiplicação de matrizes e vetores. Pense numa grande planilha com números e em multiplicar todos eles juntos e ao mesmo tempo.\n \n-* **[NAME_REDACTED]**: Esse é um subcampo do [NAME_REDACTED], então o mesmo se aplica. A diferença é que não há apenas uma grande folha de papel com números para multiplicar, mas um grande conjunto de folhas de papel, e em muitos casos, você utiliza um processador especial para construir e/ou usar modelos.\n+* **[NAME_REDACTED]**: Esse é um subcampo do [NAME_REDACTED], então, o mesmo se aplica. A diferença é que não há apenas uma grande planilha com números para multiplicar, mas um grande conjunto delas, e em muitos casos, você utiliza um processador especial para construir e/ou usar esses modelos.\n \n ### Concorrência + Paralelismo: Web + Machine learning\n \n Com **FastAPI** você pode levar a vantagem da concorrência que é muito comum para desenvolvimento web (o mesmo atrativo de NodeJS).\n \n-Mas você também pode explorar os benefícios do paralelismo e multiprocessamento (tendo múltiplos processadores rodando em paralelo) para trabalhos pesados que geram **limite de CPU** como aqueles em sistemas de [NAME_REDACTED].\n+Mas você também pode explorar os benefícios do paralelismo e multiprocessamento (tendo múltiplos processadores rodando em paralelo) para trabalhos **limitados por CPU** como aqueles em sistemas de [NAME_REDACTED].\n \n-Isso, mais o simples fato que Python é a principal linguagem para **[NAME_REDACTED]**, [NAME_REDACTED] e especialmente [NAME_REDACTED], faz do FastAPI uma ótima escolha para APIs web e aplicações com [NAME_REDACTED] / [NAME_REDACTED] (entre muitas outras).\n+Isso, somado ao simples fato que Python é a principal linguagem para **[NAME_REDACTED]**, [NAME_REDACTED] e especialmente [NAME_REDACTED], faz do FastAPI uma ótima escolha para APIs web e aplicações com [NAME_REDACTED] / [NAME_REDACTED] (entre muitas outras).\n \n Para ver como alcançar esse paralelismo em produção veja a seção sobre [Deployment](deployment/index.md){.internal-link target=_blank}.\n \n ## `async` e `await`\n \n-Versões modernas do Python tem um modo muito intuitivo para definir código assíncrono. Isso faz parecer normal o código \"sequencial\" e fazer o \"esperar\" para você nos momentos certos.\n+Versões modernas do Python têm um modo muito intuitivo para definir código assíncrono. Isso faz parecer do mesmo jeito do código normal \"sequencial\" e fazer a \"espera\" para você nos momentos certos.\n \n-Quando tem uma operação que exigirá espera antes de dar os resultados e tem suporte para esses recursos Python, você pode escrever assim:\n+Quando tem uma operação que exigirá espera antes de dar os resultados e tem suporte para esses novos recursos do Python, você pode escrever assim:\n \n ```Python\n burgers = await get_burgers(2)\n ```\n \n-A chave aqui é o `await`. Ele diz ao Python que ele tem que esperar por `get_burgers(2)` para finalizar suas coisas antes de armazenar os resultados em `burgers`. Com isso, o Python saberá que ele pode ir e fazer outras coisas nesse meio tempo (como receber outra requisição).\n+A chave aqui é o `await`. Ele diz ao Python que ele tem que esperar por `get_burgers(2)` finalizar suas coisas 🕙 antes de armazenar os resultados em `burgers`. Com isso, o Python saberá que ele pode ir e fazer outras coisas 🔀 ⏯ nesse meio tempo (como receber outra requisição).\n \n Para o `await` funcionar, tem que estar dentro de uma função que suporte essa assincronicidade. Para fazer isso, apenas declare a função com `async def`:\n \n ```Python hl_lines=\"1\"\n async def get_burgers(number: int):\n- # Fazer alguma coisa assíncrona para criar os hambúrgueres\n+ # Faz alguma coisa assíncrona para criar os hambúrgueres\n return burgers\n ```\n \n@@ -295,9 +293,9 @@ def get_sequential_burgers(number: int):\n return burgers\n ```\n \n-Com `async def`, o Python sabe que, dentro dessa função, tem que estar ciente das expressões `await`, e que isso pode \"pausar\" a execução dessa função, e poderá fazer outra coisa antes de voltar.\n+Com `async def`, o Python sabe que, dentro dessa função, ele deve estar ciente das expressões `await`, e que isso poderá \"pausar\" ⏸ a execução dessa função, e ir fazer outra coisa 🔀 antes de voltar.\n \n-Quando você quiser chamar uma função `async def`, você tem que \"esperar\". Então, isso não funcionará:\n+Quando você quiser chamar uma função `async def`, você tem que \"esperar\" ela. Então, isso não funcionará:\n \n ```Python\n # Isso não irá funcionar, porquê get_burgers foi definido com: async def\n@@ -319,13 +317,24 @@ async def read_burgers():\n \n Você deve ter observado que `await` pode ser usado somente dentro de funções definidas com `async def`.\n \n-Mas ao mesmo tempo, funções definidas com `async def` tem que ser aguardadas. Então, funções com `async def` pdem ser chamadas somente dentro de funções definidas com `async def` também.\n+Mas ao mesmo tempo, funções definidas com `async def` têm que ser \"aguardadas\". Então, funções com `async def` pdem ser chamadas somente dentro de funções definidas com `async def` também.\n \n Então, sobre o ovo e a galinha, como você chama a primeira função async?\n \n Se você estivar trabalhando com **FastAPI** não terá que se preocupar com isso, porquê essa \"primeira\" função será a sua *função de operação de rota*, e o FastAPI saberá como fazer a coisa certa.\n \n-Mas se você quiser usar `async` / `await` sem FastAPI, verifique a documentação oficial Python.\n+Mas se você quiser usar `async` / `await` sem FastAPI, você também pode fazê-lo.\n+\n+### Escreva seu próprio código assíncrono\n+\n+Starlette (e **FastAPI**) são baseados no AnyIO, o que o torna compatível com ambos o asyncio da biblioteca padrão do Python, e o Trio.\n+\n+Em particular, você pode usar diretamente o AnyIO para seus casos de uso avançados de concorrência que requerem padrões mais avançados no seu próprio código.\n+\n+E até se você não estiver utilizando FastAPI, você também pode escrever suas próprias aplicações assíncronas com o AnyIO por ser altamente compatível e ganhar seus benefícios (e.g. *concorrência estruturada*).\n+\n+Eu criei outra biblioteca em cima do AnyIO, como uma fina camada acima, para melhorar um pouco as anotações de tipo e obter melhor **autocompletar**, **erros de linha**, etc. Ela também possui uma introdução amigável e um tutorial para ajudar você a **entender** e escrever **seu próprio código async**: Asyncer. Seria particularmente útil se você precisar **combinar código async com código regular** (bloqueador/síncrono).\n+\n \n ### Outras formas de código assíncrono\n \n@@ -337,25 +346,25 @@ Essa mesma sintaxe (ou quase a mesma) foi também incluída recentemente em vers\n \n Mas antes disso, controlar código assíncrono era bem mais complexo e difícil.\n \n-Nas versões anteriores do Python, você poderia utilizar threads ou Gevent. Mas o código é um pouco mais complexo de entender, debugar, e pensar sobre.\n+Nas versões anteriores do Python, você poderia utilizar threads ou Gevent. Mas o código é bem mais complexo de entender, debugar, e pensar sobre.\n \n-Nas versões anteriores do NodeJS / [NAME_REDACTED], você poderia utilizar \"callbacks\". O que leva ao inferno do callback.\n+Nas versões anteriores do NodeJS / [NAME_REDACTED], você utilizaria \"callbacks\". O que leva ao inferno do callback.\n \n ## Corrotinas\n \n-**Corrotina** é apenas um jeito bonitinho para a coisa que é retornada de uma função `async def`. O Python sabe que é uma função que pode começar e terminar em algum ponto, mas que pode ser pausada internamente também, sempre que tiver um `await` dentro dela.\n+**Corrotina** é apenas um jeito bonitinho para a coisa que é retornada de uma função `async def`. O Python sabe que é algo como uma função, que pode começar e que vai terminar em algum ponto, mas que pode ser pausada ⏸ internamente também, sempre que tiver um `await` dentro dela.\n \n-Mas toda essa funcionalidade de código assíncrono com `async` e `await` é muitas vezes resumida como \"corrotina\". É comparável ao principal recurso chave do Go, a \"Gorotina\".\n+Mas toda essa funcionalidade de código assíncrono com `async` e `await` é muitas vezes resumida como usando \"corrotinas\". É comparável ao principal recurso chave do Go, a \"Gorrotina\".\n \n ## Conclusão\n \n-Vamos ver a mesma frase com o conteúdo cima:\n+Vamos ver a mesma frase de cima:\n \n-> Versões modernas do Python tem suporte para **\"código assíncrono\"** usando algo chamado **\"corrotinas\"**, com sintaxe **`async` e `await`**.\n+> Versões modernas do Python têm suporte para **\"código assíncrono\"** usando algo chamado **\"corrotinas\"**, com sintaxe **`async` e `await`**.\n \n-Isso pode fazer mais sentido agora.\n+Isso pode fazer mais sentido agora. ✨\n \n-Tudo isso é o que deixa o FastAPI poderoso (através do Starlette) e que o faz ter uma performance impressionante.\n+Tudo isso é o que empodera o FastAPI (através do Starlette) e que o faz ter uma performance tão impressionante.\n \n ## Detalhes muito técnicos\n \n@@ -365,25 +374,25 @@ Você pode provavelmente pular isso.\n \n Esses são detalhes muito técnicos de como **FastAPI** funciona por baixo do capô.\n \n-Se você tem algum conhecimento técnico (corrotinas, threads, blocking etc) e está curioso sobre como o FastAPI controla o `async def` vs normal `def`, vá em frente.\n+Se você tem certo conhecimento técnico (corrotinas, threads, blocking etc) e está curioso sobre como o FastAPI controla o `async def` vs normal `def`, vá em frente.\n \n ///\n \n ### Funções de operação de rota\n \n-Quando você declara uma *função de operação de rota* com `def` normal ao invés de `async def`, ela é rodada em uma threadpool externa que então é aguardada, ao invés de ser chamada diretamente (ela poderia bloquear o servidor).\n+Quando você declara uma *função de operação de rota* com `def` normal ao invés de `async def`, ela é rodada em uma threadpool externa que é então aguardada, ao invés de ser chamada diretamente (já que ela bloquearia o servidor).\n \n-Se você está chegando de outro framework assíncrono que não faz o trabalho descrito acima e você está acostumado a definir triviais *funções de operação de rota* com simples `def` para ter um mínimo ganho de performance (cerca de 100 nanosegundos), por favor observe que no **FastAPI** o efeito pode ser bem o oposto. Nesses casos, é melhor usar `async def` a menos que suas *funções de operação de rota* utilizem código que performem bloqueamento IO.\n+Se você está chegando de outro framework assíncrono que não funciona como descrito acima e você está acostumado a definir *funções de operação de rota* triviais somente de computação com simples `def` para ter um mínimo ganho de performance (cerca de 100 nanosegundos), por favor observe que no **FastAPI** o efeito pode ser bem o oposto. Nesses casos, é melhor usar `async def` a menos que suas *funções de operação de rota* utilizem código que performe bloqueamento IO.\n \n-Ainda, em ambas as situações, as chances são que o **FastAPI** será [ainda mais rápido](index.md#performance){.internal-link target=_blank} do que (ou ao menos comparável a) seus frameworks antecessores.\n+Ainda, em ambas as situações, as chances são que o **FastAPI** [ainda será mais rápido](index.md#performance){.internal-link target=_blank} do que (ou ao menos comparável a) seu framework anterior.\n \n ### Dependências\n \n-O mesmo se aplica para as dependências. Se uma dependência tem as funções com padrão `def` ao invés de `async def`, ela é rodada no threadpool externo.\n+O mesmo se aplica para as [dependências](tutorial/dependencies/index.md){.internal-link target=_blank}. Se uma dependência tem as funções com padrão `def` ao invés de `async def`, ela é rodada no threadpool externo.\n \n ### Sub-dependências\n \n-Você pode ter múltiplas dependências e sub-dependências exigindo uma a outra (como parâmetros de definições de funções), algumas delas podem ser criadas com `async def` e algumas com `def` normal. Isso ainda poderia funcionar, e aquelas criadas com `def` podem ser chamadas em uma thread externa ao invés de serem \"aguardadas\".\n+Você pode ter múltiplas dependências e [sub-dependências](tutorial/dependencies/sub-dependencies.md){.internal-link target=_blank} requisitando uma à outra (como parâmetros de definições de funções), algumas delas podem ser criadas com `async def` e algumas com `def` normal. Isso ainda funcionaria, e aquelas criadas com `def` normal seriam chamadas em uma thread externa (do threadpool) ao invés de serem \"aguardadas\".\n \n ### Outras funções de utilidade\n \n@@ -395,6 +404,6 @@ Se sua função de utilidade é uma função normal com `def`, ela será chamada\n \n ---\n \n-Novamente, esses são detalhes muito técnicos que provavelmente possam ser úteis caso você esteja procurando por eles.\n+Novamente, esses são detalhes muito técnicos que provavelmente seriam úteis caso você esteja procurando por eles.\n \n Caso contrário, você deve ficar bem com as dicas da seção acima: Com pressa?." } ], "reviews": [ { "id": 2992438240, "user": "user_e10da7d15f57", "state": "APPROVED", "body": "Well done, we need to keep maintaining the translated documentation updated and as good as the original one, written in English.\n\nThanks, [USER_REDACTED], for your contribution and dedication to this project.", "submitted_at": "2025-07-07T07:03:15+00:00" }, { "id": 3016328359, "user": "user_178cb4401e94", "state": "CHANGES_REQUESTED", "body": "Just a few typos 🚀", "submitted_at": "2025-07-14T13:21:30+00:00" }, { "id": 3016812659, "user": "user_e1f1c455eab6", "state": "COMMENTED", "body": null, "submitted_at": "2025-07-14T15:29:21+00:00" }, { "id": 3016813364, "user": "user_e1f1c455eab6", "state": "COMMENTED", "body": null, "submitted_at": "2025-07-14T15:29:32+00:00" }, { "id": 3024810121, "user": "user_178cb4401e94", "state": "APPROVED", "body": "✨", "submitted_at": "2025-07-16T12:50:54+00:00" } ], "review_comments": [ { "id": 2204910750, "user": "user_178cb4401e94", "body": "just a typo here:\n\n\"esperando pelo momento **extato** em\" should be \"esperando pelo momento exato em\"", "path": "docs/pt/docs/async.md", "line": null, "side": "RIGHT", "created_at": "2025-07-14T13:10:09+00:00" }, { "id": 2204922150, "user": "user_178cb4401e94", "body": "\"Todo mundo na sua frente **está** esperando seus hambúrgueres **ficarem** prontos antes de deixar o caixa, porque cada um dos 8 caixas vai e prepara o hambúrguer logo após receber o pedido, antes de pegar o próximo pedido.", "path": "docs/pt/docs/async.md", "line": null, "side": "RIGHT", "created_at": "2025-07-14T13:15:38+00:00" }, { "id": 2205221834, "user": "user_e1f1c455eab6", "body": "[NAME_REDACTED]!!", "path": "docs/pt/docs/async.md", "line": null, "side": "RIGHT", "created_at": "2025-07-14T15:29:21+00:00" }, { "id": 2205222164, "user": "user_e1f1c455eab6", "body": "Thank you!!", "path": "docs/pt/docs/async.md", "line": null, "side": "RIGHT", "created_at": "2025-07-14T15:29:31+00:00" } ], "meta": { "languages": [ "md" ], "touches_tests": false, "review_state_summary": { "APPROVED": 2, "CHANGES_REQUESTED": 1, "COMMENTED": 2 }, "meaningful_comment_count": 4, "has_approval": true, "has_changes_requested": true, "total_review_comments": 4 } } { "_id": "48bcbff8c0bcd68d", "_schema_version": "1.0", "_cleaned_at": "2026-02-12T07:46:51.734133+00:00", "repo": "tiangolo/fastapi", "repo_url": "https://github.com/fastapi/fastapi", "license_name": "MIT License", "license_spdx": "MIT", "pr_number": 13801, "title": "🌐 Add Russian translation for `docs/ru/docs/advanced/response-directly.md`", "body": null, "author": "user_331e23ef495b", "created_at": "2025-06-18T17:37:55+00:00", "merged_at": "2025-07-04T05:21:56+00:00", "base_branch": "master", "head_branch": "patch-5", "additions": 65, "deletions": 0, "changed_files": 1, "files": [ { "filename": "docs/ru/docs/advanced/response-directly.md", "status": "added", "additions": 65, "deletions": 0, "changes": 65, "patch": "@@ -0,0 +1,65 @@\n+# Возврат ответа напрямую\n+\n+Когда вы создаёте **FastAPI** *операцию пути*, вы можете возвращать из неё любые данные: `dict`, `list`, Pydantic-модель, модель базы данных и т.д.\n+\n+По умолчанию **FastAPI** автоматически преобразует возвращаемое значение в JSON с помощью `jsonable_encoder`, как описано в [JSON кодировщик](../tutorial/encoder.md){.internal-link target=_blank}.\n+\n+Затем \"под капотом\" эти данные, совместимые с JSON (например `dict`), помещаются в `JSONResponse`, который используется для отправки ответа клиенту.\n+\n+Но вы можете возвращать `JSONResponse` напрямую из ваших *операций пути*.\n+\n+Это может быть полезно, например, если нужно вернуть пользовательские заголовки или куки.\n+\n+## Возврат `Response`\n+\n+На самом деле, вы можете возвращать любой объект `Response` или его подкласс.\n+\n+/// tip | Подсказка\n+\n+`JSONResponse` сам по себе является подклассом `Response`.\n+\n+///\n+\n+И когда вы возвращаете `Response`, **FastAPI** передаст его напрямую.\n+\n+Это не приведет к преобразованию данных с помощью Pydantic-моделей, содержимое не будет преобразовано в какой-либо тип и т.д.\n+\n+Это даёт вам большую гибкость. Вы можете возвращать любые типы данных, переопределять любые объявления или валидацию данных и т.д.\n+\n+## Использование `jsonable_encoder` в `Response`\n+\n+Поскольку **FastAPI** не изменяет объект `Response`, который вы возвращаете, вы должны убедиться, что его содержимое готово к отправке.\n+\n+Например, вы не можете поместить Pydantic-модель в `JSONResponse`, не преобразовав её сначала в `dict` с помощью преобразования всех типов данных (таких как `datetime`, `UUID` и т.д.) в совместимые с JSON типы.\n+\n+В таких случаях вы можете использовать `jsonable_encoder` для преобразования данных перед передачей их в ответ:\n+\n+{* ../../docs_src/response_directly/tutorial001.py hl[6:7,21:22] *}\n+\n+/// note | Технические детали\n+\n+Вы также можете использовать `from starlette.responses import JSONResponse`.\n+\n+**FastAPI** предоставляет `starlette.responses` через `fastapi.responses` просто для вашего удобства, как разработчика. Но большинство доступных Response-классов поступают напрямую из Starlette.\n+\n+///\n+\n+## Возврат пользовательского `Response`\n+\n+Пример выше показывает все необходимые части, но он пока не очень полезен, так как вы могли бы просто вернуть `item` напрямую, и **FastAPI** поместил бы его в `JSONResponse`, преобразовав в `dict` и т.д. Всё это происходит по умолчанию.\n+\n+Теперь давайте посмотрим, как можно использовать это для возврата пользовательского ответа.\n+\n+Допустим, вы хотите вернуть ответ в формате XML.\n+\n+Вы можете поместить ваш XML-контент в строку, поместить её в `Response` и вернуть:\n+\n+{* ../../docs_src/response_directly/tutorial002.py hl[1,18] *}\n+\n+## Примечания\n+\n+Когда вы возвращаете объект `Response` напрямую, его данные не валидируются, не преобразуются (не сериализуются) и не документируются автоматически.\n+\n+Но вы всё равно можете задокументировать это, как описано в [Дополнительные ответы в OpenAPI](additional-responses.md){.internal-link target=_blank}.\n+\n+В следующих разделах вы увидите, как использовать/объявлять такие кастомные `Response`, при этом сохраняя автоматическое преобразование данных, документацию и т.д." } ], "reviews": [ { "id": 2944680531, "user": "user_29e85f9a8e75", "state": "COMMENTED", "body": null, "submitted_at": "2025-06-20T06:14:41+00:00" }, { "id": 2944681877, "user": "user_29e85f9a8e75", "state": "COMMENTED", "body": null, "submitted_at": "2025-06-20T06:15:13+00:00" }, { "id": 2947779189, "user": "user_331e23ef495b", "state": "COMMENTED", "body": null, "submitted_at": "2025-06-21T14:16:16+00:00" }, { "id": 2949998789, "user": "user_29e85f9a8e75", "state": "COMMENTED", "body": null, "submitted_at": "2025-06-23T12:56:35+00:00" }, { "id": 2954834448, "user": "user_787e19aded2a", "state": "APPROVED", "body": null, "submitted_at": "2025-06-24T18:06:10+00:00" }, { "id": 2985570828, "user": "user_516db2099073", "state": "APPROVED", "body": null, "submitted_at": "2025-07-04T04:56:03+00:00" } ], "review_comments": [ { "id": 2158131273, "user": "user_29e85f9a8e75", "body": "```suggestion\n**FastAPI** предоставляет `starlette.responses` через `fastapi.responses` просто для вашего удобства, как разработчика. Но большинство доступных Response-классов поступают напрямую из Starlette.\n```", "path": "docs/ru/docs/advanced/response-directly.md", "line": null, "side": "RIGHT", "created_at": "2025-06-20T06:14:21+00:00" }, { "id": 2158132134, "user": "user_29e85f9a8e75", "body": "Just a suggestion. What do you think?", "path": "docs/ru/docs/advanced/response-directly.md", "line": null, "side": "RIGHT", "created_at": "2025-06-20T06:15:12+00:00" }, { "id": 2160049088, "user": "user_331e23ef495b", "body": "That makes more sense, thank you", "path": "docs/ru/docs/advanced/response-directly.md", "line": null, "side": "RIGHT", "created_at": "2025-06-21T14:16:16+00:00" }, { "id": 2161562456, "user": "user_29e85f9a8e75", "body": "> Но большинство доступных ответов поступают напрямую из Starlette.\n\nI though you accepted my suggestion and going to change it, but it's still unchanged.\nWill you change it? Or would you like to leave it as it is?", "path": "docs/ru/docs/advanced/response-directly.md", "line": null, "side": "RIGHT", "created_at": "2025-06-23T12:56:35+00:00" } ], "meta": { "languages": [ "md" ], "touches_tests": false, "review_state_summary": { "COMMENTED": 4, "APPROVED": 2 }, "meaningful_comment_count": 4, "has_approval": true, "has_changes_requested": false, "total_review_comments": 4 } } { "_id": "b978464d04dc0ef1", "_schema_version": "1.0", "_cleaned_at": "2026-02-12T07:46:51.734133+00:00", "repo": "tiangolo/fastapi", "repo_url": "https://github.com/fastapi/fastapi", "license_name": "MIT License", "license_spdx": "MIT", "pr_number": 13799, "title": "🌐 Add Russian translation for `docs/ru/docs/advanced/additional-status-codes.md`", "body": null, "author": "user_331e23ef495b", "created_at": "2025-06-18T17:00:42+00:00", "merged_at": "2025-07-04T05:17:17+00:00", "base_branch": "master", "head_branch": "patch-3", "additions": 41, "deletions": 0, "changed_files": 1, "files": [ { "filename": "docs/ru/docs/advanced/additional-status-codes.md", "status": "added", "additions": 41, "deletions": 0, "changes": 41, "patch": "@@ -0,0 +1,41 @@\n+# Дополнительные статус коды\n+\n+По умолчанию **FastAPI** возвращает ответы, используя `JSONResponse`, помещая содержимое, которое вы возвращаете из вашей *операции пути*, внутрь этого `JSONResponse`.\n+\n+Он будет использовать код статуса по умолчанию или тот, который вы укажете в вашей *операции пути*.\n+\n+## Дополнительные статус коды\n+\n+Если вы хотите возвращать дополнительный статус код помимо основного, вы можете сделать это, возвращая объект `Response` напрямую, как `JSONResponse`, и устанавливая нужный статус код напрямую.\n+\n+Например, скажем, вы хотите создать *операцию пути*, которая позволяет обновлять элементы и возвращает HTTP-код 200 \"OK\" при успешном выполнении.\n+\n+Но вы также хотите, чтобы она принимала новые элементы. И если элемент ранее не существовал, он создаётся, и возвращался HTTP-код 201 \"Created\".\n+\n+Чтобы реализовать это, импортируйте `JSONResponse` и возвращайте ваш контент напрямую, устанавливая нужный `status_code`:\n+\n+{* ../../docs_src/additional_status_codes/tutorial001_an_py310.py hl[4,25] *}\n+\n+/// warning | Внимание\n+\n+Когда вы возвращаете объект `Response` напрямую, как в примере выше, он будет возвращён как есть.\n+\n+Он не будет сериализован при помощи модели и т.д.\n+\n+Убедитесь, что в нём содержатся именно те данные, которые вы хотите, и что значения являются валидным JSON (если вы используете `JSONResponse`).\n+\n+///\n+\n+/// note | Технические детали\n+\n+Вы также можете использовать `from starlette.responses import JSONResponse`.\n+\n+**FastAPI** предоставляет тот же `starlette.responses` через `fastapi.responses` просто для вашего удобства, как разработчика. Но большинство доступных Response-классов поступают напрямую из Starlette. То же самое касается и `status`.\n+\n+///\n+\n+## OpenAPI и документация API\n+\n+Если вы возвращаете дополнительные коды статусов и ответы напрямую, они не будут включены в схему OpenAPI (документацию API), потому что FastAPI не может заранее знать, что вы собираетесь вернуть.\n+\n+Но вы можете задокументировать это в вашем коде, используя: [Дополнительные ответы в OpenAPI](additional-responses.md){.internal-link target=_blank}." } ], "reviews": [ { "id": 2944650016, "user": "user_29e85f9a8e75", "state": "COMMENTED", "body": null, "submitted_at": "2025-06-20T05:58:15+00:00" }, { "id": 2947781074, "user": "user_331e23ef495b", "state": "COMMENTED", "body": null, "submitted_at": "2025-06-21T14:22:39+00:00" }, { "id": 2954835426, "user": "user_787e19aded2a", "state": "APPROVED", "body": null, "submitted_at": "2025-06-24T18:06:32+00:00" }, { "id": 2985621064, "user": "user_29e85f9a8e75", "state": "APPROVED", "body": null, "submitted_at": "2025-07-04T05:15:40+00:00" } ], "review_comments": [ { "id": 2158111495, "user": "user_29e85f9a8e75", "body": "```suggestion\n**FastAPI** предоставляет тот же `starlette.responses` через `fastapi.responses` просто для вашего удобства, как разработчика. Но большинство доступных Response-классов поступают напрямую из Starlette. То же самое касается и `status`.\n```\nI think \"responses\" shouldn't be translated here, better change it to \"Response-классы\" or something like this to make it clear. What do you think?", "path": "docs/ru/docs/advanced/additional-status-codes.md", "line": null, "side": "RIGHT", "created_at": "2025-06-20T05:57:01+00:00" }, { "id": 2160050603, "user": "user_331e23ef495b", "body": "That makes more sense, thank you", "path": "docs/ru/docs/advanced/additional-status-codes.md", "line": null, "side": "RIGHT", "created_at": "2025-06-21T14:22:39+00:00" } ], "meta": { "languages": [ "md" ], "touches_tests": false, "review_state_summary": { "COMMENTED": 2, "APPROVED": 2 }, "meaningful_comment_count": 2, "has_approval": true, "has_changes_requested": false, "total_review_comments": 2 } } { "_id": "59fc8833b71bc87f", "_schema_version": "1.0", "_cleaned_at": "2026-02-12T07:46:51.734133+00:00", "repo": "tiangolo/fastapi", "repo_url": "https://github.com/fastapi/fastapi", "license_name": "MIT License", "license_spdx": "MIT", "pr_number": 13792, "title": "🌐 Add Ukrainian translation for `docs/uk/docs/tutorial/response-model.md`", "body": "[USER_REDACTED] [USER_REDACTED] [USER_REDACTED] [USER_REDACTED] please take a look 😄", "author": "user_c36c155012b4", "created_at": "2025-06-14T20:29:06+00:00", "merged_at": "2025-06-24T19:14:02+00:00", "base_branch": "master", "head_branch": "translation-uk/response-model", "additions": 358, "deletions": 0, "changed_files": 1, "files": [ { "filename": "docs/uk/docs/tutorial/response-model.md", "status": "added", "additions": 358, "deletions": 0, "changes": 358, "patch": "@@ -0,0 +1,358 @@\n+# Модель відповіді — Тип, що повертається\n+\n+Ви можете оголосити тип, який використовуватиметься у відповіді, за допомогою *анотації типу, що повертається* *функцією операцією шляху* (path operation)\n+\n+**Анотацію типу** можна вказати так само як і для вхідних **параметрів** функції: це можуть бути моделі Pydantic, списки (lists), словники (dictionaries), скалярні значення, як-от цілі числа (integers), булеві значення (booleans) тощо.\n+\n+{* ../../docs_src/response_model/tutorial001_01_py310.py hl[16,21] *}\n+\n+FastAPI використовуватиме цей тип, щоб:\n+\n+* **Перевірити правильність** повернених даних.\n+ * Якщо дані не валідні (наприклад, відсутнє поле), це означає, що Ваш код додатку працює некоректно і не повертає те, що повинен. У такому випадку FastAPI поверне помилку сервера, замість того щоб віддати недопустимі дані. Так Ви та Ваші клієнти будете впевнені, що отримуєте очікувані дані у правильному форматі.\n+\n+* Додати **JSON Schema** відповіді до специфікації OpenAPI в *операціях шляху*.\n+ * Це буде використано в **автоматичній документації**.\n+ * А також інструментами, які автоматично генерують клієнтський код.\n+\n+Але найголовніше:\n+\n+* FastAPI **обмежить та відфільтрує** вихідні дані відповідно до типу, вказаного у відповіді.\n+ * Це особливо важливо для **безпеки**. Деталі нижче.\n+\n+## Параметр `response_model`\n+\n+Іноді Вам потрібно або зручно повертати інші типи даних, ніж ті, що зазначені як тип відповіді.\n+\n+Наприклад, Ви можете **повертати словник** або об’єкт бази даних, але **оголосити модель Pydantic** як модель відповіді. Тоді модель Pydantic автоматично оброблятиме валідацію, документацію тощо.\n+\n+Якщо Ви додасте анотацію типу для повернення, редактор коду або mypy можуть поскаржитися, що функція повертає інший тип (наприклад, dict замість Item).\n+\n+У таких випадках можна скористатися параметром `response_model` в декораторі маршруту (наприклад, [USER_REDACTED].get()).\n+\n+Параметр `response_model` працює з будь-яким *оператором шляху*:\n+\n+* `[USER_REDACTED].get()`\n+* `[USER_REDACTED].post()`\n+* `[USER_REDACTED].put()`\n+* `[USER_REDACTED].delete()`\n+* тощо.\n+\n+{* ../../docs_src/response_model/tutorial001_py310.py hl[17,22,24:27] *}\n+\n+/// note | Примітка\n+\n+Зверніть увагу, що `response_model` є параметром методу-декоратора (`get`, `post`, тощо), а не *функцією операцією шляху* (path operation function), як це робиться з параметрами або тілом запиту.\n+\n+///\n+\n+`response_model` приймає такий самий тип, який Ви б вказали для поля моделі Pydantic. Тобто це може бути як Pydantic-модель, так і, наприклад, `list` із моделей Pydantic — `List[Item]`.\n+\n+FastAPI використовуватиме `response_model` для створення документації, валідації даних та — найважливіше — **перетворення та фільтрації вихідних даних** згідно з оголошеним типом.\n+\n+/// tip | Порада\n+\n+Якщо у Вас увімкнено сувору перевірку типів у редакторі, mypy тощо, Ви можете оголосити тип повернення функції як `Any`.\n+\n+Таким чином, Ви повідомляєте редактору, що свідомо повертаєте будь-що. Але FastAPI усе одно виконуватиме створення документації, валідацію, фільтрацію тощо за допомогою параметра `response_model`.\n+\n+///\n+\n+### Пріоритет `response_model`\n+\n+Якщо Ви вказуєте і тип повернення, і `response_model`, то FastAPI використовуватиме `response_model` з пріоритетом.\n+\n+Таким чином, Ви можете додати правильні анотації типів до ваших функцій, навіть якщо вони повертають тип, відмінний від `response_model`. Це буде корисно для редакторів коду та інструментів, таких як mypy. І при цьому FastAPI продовжить виконувати валідацію даних, генерувати документацію тощо на основі `response_model`.\n+\n+Ви також можете використати `response_model=None`, щоб вимкнути створення моделі відповіді для цієї *операції шляху*. Це може знадобитися, якщо Ви додаєте анотації типів до об'єктів, які не є допустимими полями Pydantic — приклад цього Ви побачите в одному з наступних розділів.\n+\n+## Повернути ті самі вхідні дані\n+\n+Тут ми оголошуємо модель `UserIn`, яка містить звичайний текстовий пароль:\n+\n+{* ../../docs_src/response_model/tutorial002_py310.py hl[7,9] *}\n+\n+/// info | Інформація\n+\n+Щоб використовувати `EmailStr`, спочатку встановіть `email-validator`.\n+\n+Переконайтесь, що Ви створили [віртуальне середовище](../virtual-environments.md){.internal-link target=_blank}, активували його, а потім встановили пакет, наприклад:\n+\n+```console\n+$ pip install email-validator\n+```\n+\n+or with:\n+\n+```console\n+$ pip install \"pydantic[email]\"\n+```\n+\n+///\n+\n+І ми використовуємо цю модель, щоб оголосити і вхідні, і вихідні дані:\n+\n+{* ../../docs_src/response_model/tutorial002_py310.py hl[16] *}\n+\n+Тепер, коли браузер створює користувача з паролем, API поверне той самий пароль у відповіді.\n+\n+У цьому випадку це може не бути проблемою, адже саме користувач надіслав пароль.\n+\n+Але якщо ми використаємо цю ж модель для іншої операції шляху, ми можемо випадково надіслати паролі наших користувачів кожному клієнту.\n+\n+/// danger | Обережно\n+\n+Ніколи не зберігайте пароль користувача у відкритому вигляді та не надсилайте його у відповіді, якщо тільки Ви не знаєте всі ризики і точно розумієте, що робите.\n+\n+///\n+\n+## Додайте окрему вихідну модель\n+\n+Замість цього ми можемо створити вхідну модель з відкритим паролем і вихідну модель без нього:\n+\n+{* ../../docs_src/response_model/tutorial003_py310.py hl[9,11,16] *}\n+\n+Тут, навіть якщо *функція операції шляху* повертає об'єкт користувача, який містить пароль:\n+\n+{* ../../docs_src/response_model/tutorial003_py310.py hl[24] *}\n+\n+...ми оголосили `response_model` як нашу модель `UserOut`, яка не містить пароля:\n+\n+{* ../../docs_src/response_model/tutorial003_py310.py hl[22] *}\n+\n+Таким чином, **FastAPI** автоматично відфільтрує всі дані, які не вказані у вихідній моделі (за допомогою Pydantic).\n+\n+### `response_model` або тип повернення\n+\n+У цьому випадку, оскільки дві моделі різні, якщо ми анотуємо тип повернення функції як `UserOut`, редактор і такі інструменти, як mypy, видадуть помилку, бо фактично ми повертаємо інший тип.\n+\n+Тому в цьому прикладі ми використовуємо параметр `response_model`, а не анотацію типу повернення.\n+\n+...але читайте далі, щоб дізнатися, як обійти це обмеження.\n+\n+## Тип повернення і фільтрація даних\n+\n+Продовжимо з попереднього прикладу. Ми хотіли **анотувати функцію одним типом**, але при цьому повертати з неї більше даних.\n+\n+Ми хочемо, щоб FastAPI продовжував **фільтрувати** ці дані за допомогою response_model. Тобто навіть якщо функція повертає більше інформації, у відповіді будуть лише ті поля, які вказані у response_model.\n+\n+У попередньому прикладі, оскільки класи були різні, нам довелося використовувати параметр `response_model`. Але це означає, що ми не отримуємо підтримки з боку редактора коду та інструментів перевірки типів щодо типу, який повертає функція.\n+\n+Проте в більшості випадків, коли нам потрібно зробити щось подібне, ми просто хочемо, щоб модель **відфільтрувала або прибрала** частину даних, як у цьому прикладі.\n+\n+У таких випадках ми можемо використати класи та спадкування, щоб скористатися **анотаціями типів** функцій — це дає кращу підтримку з боку редактора та інструментів типу mypy, і при цьому FastAPI продовжує виконувати **фільтрацію даних** у відповіді.\n+\n+{* ../../docs_src/response_model/tutorial003_01_py310.py hl[7:10,13:14,18] *}\n+\n+Завдяки цьому ми отримуємо підтримку інструментів — від редакторів і mypy, оскільки цей код є коректним з точки зору типів, — але ми також отримуємо фільтрацію даних від FastAPI.\n+\n+Як це працює? Давайте розберемося. 🤓\n+\n+### Типи та підтримка інструментів\n+\n+Спершу подивимось, як це бачать редактори, mypy та інші інструменти.\n+\n+`BaseUser` має базові поля. Потім `UserIn` успадковує `BaseUser` і додає поле `password`, отже, він матиме всі поля з обох моделей.\n+\n+Ми зазначаємо тип повернення функції як `BaseUser`, але фактично повертаємо екземпляр `UserIn`.\n+\n+Редактор, mypy та інші інструменти не скаржитимуться на це, тому що з точки зору типізації `UserIn` є підкласом `BaseUser`, а це означає, що він є `валідним` типом, коли очікується будь-що, що є `BaseUser`.\n+\n+### Фільтрація даних у FastAPI\n+\n+Тепер для FastAPI він бачить тип повернення і переконується, що те, що Ви повертаєте, містить **тільки** поля, які оголошені у цьому типі.\n+\n+FastAPI виконує кілька внутрішніх операцій з Pydantic, щоб гарантувати, що правила наслідування класів не застосовуються для фільтрації повернених даних, інакше Ви могли б повернути значно більше даних, ніж очікували.\n+\n+Таким чином, Ви отримуєте найкраще з двох світів: анотації типів **з підтримкою інструментів** і **фільтрацію даних**.\n+\n+## Подивитись у документації\n+\n+Коли Ви дивитесь автоматичну документацію, Ви можете побачити, що вхідна модель і вихідна модель мають власну JSON-схему:\n+\n+\n+\n+І обидві моделі використовуються для інтерактивної API-документації:\n+\n+\n+\n+## Інші анотації типів повернення\n+\n+Існують випадки, коли Ви повертаєте щось, що не є допустимим полем Pydantic, але анотуєте це у функції лише для того, щоб отримати підтримку від інструментів (редактора, mypy тощо).\n+\n+### Повернення Response напряму\n+\n+Найпоширенішим випадком буде [повернення Response напряму, як пояснюється пізніше у розширеній документації](../advanced/response-directly.md){.internal-link target=_blank}.\n+\n+{* ../../docs_src/response_model/tutorial003_02.py hl[8,10:11] *}\n+\n+Цей простий випадок автоматично обробляється FastAPI, тому що анотація типу повернення — це клас (або підклас) `Response`.\n+\n+І інструменти також будуть задоволені, бо і `RedirectResponse`, і `JSONResponse` є підкласами `Response`, отже анотація типу коректна.\n+\n+### Анотація підкласу Response\n+\n+Також можна використовувати підклас `Response` у анотації типу:\n+\n+{* ../../docs_src/response_model/tutorial003_03.py hl[8:9] *}\n+\n+Це теж працюватиме, бо `RedirectResponse` — підклас `Response`, і FastAPI автоматично обробить цей простий випадок.\n+\n+### Некоректні анотації типу повернення\n+\n+Але коли Ви повертаєте якийсь інший довільний об’єкт, що не є валідним типом Pydantic (наприклад, об’єкт бази даних), і анотуєте його так у функції, FastAPI спробує створити Pydantic модель відповіді на основі цієї анотації типу, і це завершиться помилкою.\n+\n+Те саме станеться, якщо Ви використовуєте union між різними типами, де один або більше не є валідними типами Pydantic, наприклад, це спричинить помилку 💥:\n+\n+{* ../../docs_src/response_model/tutorial003_04_py310.py hl[8] *}\n+\n+...це не працює, тому що тип анотації не є типом Pydantic і не є просто класом `Response` або його підкласом, а є об’єднанням (union) — або `Response`, або `dict`.\n+\n+### Відключення Моделі Відповіді\n+\n+Продовжуючи приклад вище, можливо, Ви не хочете використовувати стандартну валідацію даних, автоматичну документацію, фільтрацію тощо, які FastAPI виконує за замовчуванням.\n+\n+Але ви все одно можете залишити анотацію типу у функції, щоб зберегти підтримку з боку інструментів, таких як редактори коду або статичні перевірки типів (наприклад, mypy).\n+\n+У такому випадку ви можете вимкнути генерацію моделі відповіді, встановивши `response_model=None`:\n+\n+{* ../../docs_src/response_model/tutorial003_05_py310.py hl[7] *}\n+\n+Це змусить FastAPI пропустити генерацію моделі відповіді, і таким чином Ви зможете використовувати будь-які анотації типів повернення без впливу на вашу FastAPI аплікацію. 🤓\n+\n+## Параметри кодування моделі відповіді\n+\n+Ваша модель відповіді може мати значення за замовчуванням, наприклад:\n+\n+{* ../../docs_src/response_model/tutorial004_py310.py hl[9,11:12] *}\n+\n+* `description: Union[str, None] = None` (або `str | None = None` у Python 3.10) має значення за замовчуванням `None`.\n+* `tax: float = 10.5` має значення за замовчуванням `10.5`.\n+* `tags: List[str] = []` має значення за замовчуванням порожній список: `[]`.\n+\n+Але Ви можете захотіти не включати їх у результат, якщо вони фактично не були збережені.\n+\n+Наприклад, якщо у Вас є моделі з багатьма необов’язковими атрибутами у NoSQL базі даних, але Ви не хочете відправляти дуже довгі JSON-відповіді, повні значень за замовчуванням.\n+\n+### Використовуйте параметр `response_model_exclude_unset`\n+\n+Ви можете встановити параметр декоратора шляху `response_model_exclude_unset=True`:\n+\n+{* ../../docs_src/response_model/tutorial004_py310.py hl[22] *}\n+\n+і ці значення за замовчуванням не будуть включені у відповідь, тільки фактично встановлені значення.\n+\n+Отже, якщо Ви надішлете запит до цього оператора шляху для елемента з item_id `foo`, відповідь (без включення значень за замовчуванням) буде:\n+\n+```JSON\n+{\n+ \"name\": \"Foo\",\n+ \"price\": 50.2\n+}\n+```\n+\n+/// info | Інформація\n+\n+У Pydantic версії 1 метод називався `.dict()`, він був застарілий (але ще підтримується) у Pydantic версії 2 і перейменований у `.model_dump()`.\n+\n+Приклади тут використовують `.dict()` для сумісності з Pydantic v1, але Вам слід використовувати `.model_dump()`, якщо Ви можете використовувати Pydantic v2.\n+\n+///\n+\n+/// info | Інформація\n+\n+FastAPI використовує `.dict()` моделі Pydantic з параметром `exclude_unset`, щоб досягти цього.\n+\n+///\n+\n+/// info | Інформація\n+\n+Ви також можете використовувати:\n+\n+* `response_model_exclude_defaults=True`\n+* `response_model_exclude_none=True`\n+\n+як описано в документації Pydantic for `exclude_defaults` та `exclude_none`.\n+\n+///\n+\n+#### Дані зі значеннями для полів із типовими значеннями\n+\n+Але якщо Ваші дані мають значення для полів моделі з типовими значеннями, як у елемента з item_id `bar`:\n+\n+```Python hl_lines=\"3 5\"\n+{\n+ \"name\": \"Bar\",\n+ \"description\": \"The bartenders\",\n+ \"price\": 62,\n+ \"tax\": 20.2\n+}\n+```\n+вони будуть включені у відповідь.\n+\n+#### Дані з тими самими значеннями, що й типові\n+\n+Якщо дані мають ті самі значення, що й типові, як у елемента з item_id `baz`:\n+\n+```Python hl_lines=\"3 5-6\"\n+{\n+ \"name\": \"Baz\",\n+ \"description\": None,\n+ \"price\": 50.2,\n+ \"tax\": 10.5,\n+ \"tags\": []\n+}\n+```\n+\n+FastAPI достатньо розумний (насправді, Pydantic достатньо розумний), щоб зрозуміти, що, хоча `description`, `tax` і `tags` мають ті самі значення, що й типові, вони були встановлені явно (а не взяті як значення за замовчуванням).\n+\n+Отже, вони будуть включені у JSON-відповідь.\n+\n+/// tip | Порада\n+\n+Зверніть увагу, що типові значення можуть бути будь-якими, не лише `None`.\n+\n+Це може бути list (`[]`), `float` 10.5 тощо.\n+\n+///\n+\n+### `response_model_include` та `response_model_exclude`\n+\n+Ви також можете використовувати параметри *декоратора операції шляху* `response_model_include` та `response_model_exclude`.\n+\n+Вони приймають `set` (множину) рядків (`str`) з іменами атрибутів, які потрібно включити (пропускаючи інші) або виключити (включаючи інші).\n+\n+Це можна використовувати як швидкий спосіб, якщо у Вас є лише одна модель Pydantic і Ви хочете видалити деякі дані з виводу.\n+\n+/// tip | Порада\n+\n+Але все ж рекомендується використовувати описані вище підходи, із застосуванням кількох класів, замість цих параметрів.\n+\n+\n+Це тому, що JSON Schema, який генерується у вашому OpenAPI додатку (і в документації), все одно буде відповідати повній моделі, навіть якщо Ви використовуєте `response_model_include` або `response_model_exclude` для виключення деяких атрибутів.\n+\n+Це також стосується `response_model_by_alias`, який працює подібним чином.\n+\n+///\n+\n+{* ../../docs_src/response_model/tutorial005_py310.py hl[29,35] *}\n+\n+/// tip | Порада\n+\n+Синтаксис `{\"name\", \"description\"}` створює `set` з цими двома значеннями.\n+\n+Він еквівалентний `set([\"name\", \"description\"])`.\n+\n+///\n+\n+#### Використання `list` замість `set`\n+\n+Якщо Ви забудете використати `set` і натомість застосуєте `list` або `tuple`, FastAPI все одно перетворить це на `set`, і все працюватиме правильно:\n+\n+{* ../../docs_src/response_model/tutorial006_py310.py hl[29,35] *}\n+\n+## Підсумок\n+\n+Використовуйте параметр `response_model` *декоратора операції шляху*, щоб визначати моделі відповіді, особливо щоб гарантувати фільтрацію приватних даних.\n+\n+Використовуйте `response_model_exclude_unset`, щоб повертати лише явно встановлені значення." } ], "reviews": [ { "id": 2928855695, "user": "user_787e19aded2a", "state": "APPROVED", "body": "Looks good, approved", "submitted_at": "2025-06-14T21:33:46+00:00" }, { "id": 2929989214, "user": "user_51266374a527", "state": "COMMENTED", "body": "Дозвольте долучитись до локалізаційного свята? :)", "submitted_at": "2025-06-15T16:51:13+00:00" }, { "id": 2929532604, "user": "user_29e85f9a8e75", "state": "CHANGES_REQUESTED", "body": "Please, be more careful with links", "submitted_at": "2025-06-16T06:08:24+00:00" }, { "id": 2944629013, "user": "user_29e85f9a8e75", "state": "APPROVED", "body": null, "submitted_at": "2025-06-20T05:45:19+00:00" }, { "id": 2944661326, "user": "user_787e19aded2a", "state": "APPROVED", "body": null, "submitted_at": "2025-06-20T06:04:02+00:00" }, { "id": 2954997818, "user": "user_51266374a527", "state": "COMMENTED", "body": "LGTM!", "submitted_at": "2025-06-24T19:05:54+00:00" } ], "review_comments": [ { "id": 2148014289, "user": "user_29e85f9a8e75", "body": "```suggestion\nПереконайтесь, що Ви створили [віртуальне середовище](../virtual-environments.md){.internal-link target=_blank}, активували його, а потім встановили пакет, наприклад:\n```", "path": "docs/uk/docs/tutorial/response-model.md", "line": null, "side": "RIGHT", "created_at": "2025-06-15T13:41:48+00:00" }, { "id": 2148026444, "user": "user_29e85f9a8e75", "body": "```suggestion\nМи хочемо, щоб FastAPI продовжував **фільтрувати** ці дані за допомогою response_model. Тобто навіть якщо функція повертає більше інформації, у відповіді будуть лише ті поля, які вказані у response_model.\n```", "path": "docs/uk/docs/tutorial/response-model.md", "line": null, "side": "RIGHT", "created_at": "2025-06-15T13:45:47+00:00" }, { "id": 2148034233, "user": "user_29e85f9a8e75", "body": "```suggestion\nРедактор, mypy та інші інструменти не скаржитимуться на це, тому що з точки зору типізації `UserIn` є підкласом `BaseUser`, а це означає, що він є _валідним_ типом, коли очікується будь-що, що є `BaseUser`.\n```", "path": "docs/uk/docs/tutorial/response-model.md", "line": null, "side": "RIGHT", "created_at": "2025-06-15T13:48:08+00:00" }, { "id": 2148043278, "user": "user_29e85f9a8e75", "body": "```suggestion\nНайпоширенішим випадком буде [повернення Response напряму, як пояснюється пізніше у розширеній документації](../advanced/response-directly.md){.internal-link target=_blank}.\n```", "path": "docs/uk/docs/tutorial/response-model.md", "line": null, "side": "RIGHT", "created_at": "2025-06-15T13:51:00+00:00" }, { "id": 2148048079, "user": "user_29e85f9a8e75", "body": "Title of the 'abbr' can also be translated", "path": "docs/uk/docs/tutorial/response-model.md", "line": null, "side": "RIGHT", "created_at": "2025-06-15T13:52:46+00:00" }, { "id": 2148491362, "user": "user_51266374a527", "body": "недопустимі/неправильні?", "path": "docs/uk/docs/tutorial/response-model.md", "line": null, "side": "RIGHT", "created_at": "2025-06-15T16:47:08+00:00" }, { "id": 2148499464, "user": "user_51266374a527", "body": "той же комент - можливо не допустимим полем буде кращим варіантом", "path": "docs/uk/docs/tutorial/response-model.md", "line": null, "side": "RIGHT", "created_at": "2025-06-15T16:50:11+00:00" } ], "meta": { "languages": [ "md" ], "touches_tests": false, "review_state_summary": { "APPROVED": 3, "COMMENTED": 2, "CHANGES_REQUESTED": 1 }, "meaningful_comment_count": 7, "has_approval": true, "has_changes_requested": true, "total_review_comments": 7 } } { "_id": "5a036b0d3476faf7", "_schema_version": "1.0", "_cleaned_at": "2026-02-12T07:46:51.734133+00:00", "repo": "tiangolo/fastapi", "repo_url": "https://github.com/fastapi/fastapi", "license_name": "MIT License", "license_spdx": "MIT", "pr_number": 13748, "title": "🌐 Add Ukrainian translation for `docs/uk/docs/tutorial/query-param-models.md`", "body": null, "author": "user_c36c155012b4", "created_at": "2025-06-01T02:12:56+00:00", "merged_at": "2025-06-05T12:12:05+00:00", "base_branch": "master", "head_branch": "translation-uk/query-param-models", "additions": 68, "deletions": 0, "changed_files": 1, "files": [ { "filename": "docs/uk/docs/tutorial/query-param-models.md", "status": "added", "additions": 68, "deletions": 0, "changes": 68, "patch": "@@ -0,0 +1,68 @@\n+# Моделі Query параметрів\n+\n+Якщо у Вас є група **query параметрів**, які пов’язані між собою, Ви можете створити **Pydantic-модель** для їх оголошення.\n+\n+Це дозволить Вам **повторно використовувати модель** у **різних місцях**, а також оголошувати перевірки та метадані для всіх параметрів одночасно. 😎\n+\n+/// note | Примітка\n+\n+Ця можливість підтримується, починаючи з версії FastAPI `0.115.0`. 🤓\n+\n+///\n+\n+## Query параметри з Pydantic-моделлю\n+\n+Оголосіть **query параметри**, які Вам потрібні, у **Pydantic-моделі**, а потім оголосіть цей параметр як `Query`:\n+\n+{* ../../docs_src/query_param_models/tutorial001_an_py310.py hl[9:13,17] *}\n+\n+**FastAPI** буде **витягувати** дані для **кожного поля** з **query параметрів** у запиті та передавати їх у визначену вами Pydantic-модель.\n+\n+## Перевірте документацію\n+\n+Ви можете побачити параметри запиту в UI документації за `/docs`:\n+\n+
      \n+\n+
      \n+\n+## Заборона зайвих Query параметрів\n+\n+У деяких особливих випадках (ймовірно, не дуже поширених) Ви можете захотіти **обмежити** query параметри, які дозволено отримувати.\n+\n+Ви можете використати конфігурацію моделі Pydantic, щоб заборонити (`forbid`) будь-які зайві (`extra`) поля:\n+\n+{* ../../docs_src/query_param_models/tutorial002_an_py310.py hl[10] *}\n+\n+Якщо клієнт спробує надіслати **зайві** дані у **query параметрах**, він отримає **помилку**.\n+\n+Наприклад, якщо клієнт спробує надіслати query параметр `tool` зі значенням `plumbus`, як у цьому запиті:\n+\n+```http\n+https://example.com/items/?limit=10&tool=plumbus\n+```\n+\n+Він отримає відповідь з **помилкою**, яка повідомить, що query параметр `tool ` не дозволено:\n+\n+```json\n+{\n+ \"detail\": [\n+ {\n+ \"type\": \"extra_forbidden\",\n+ \"loc\": [\"query\", \"tool\"],\n+ \"msg\": \"Extra inputs are not permitted\",\n+ \"input\": \"plumbus\"\n+ }\n+ ]\n+}\n+```\n+\n+## Підсумок\n+\n+Ви можете використовувати **Pydantic-моделі** для оголошення **query параметрів** у **FastAPI**. 😎\n+\n+/// tip | Підказка\n+\n+Спойлер: Ви також можете використовувати Pydantic-моделі для оголошення cookie та заголовків, але про це Ви дізнаєтеся пізніше в цьому посібнику. 🤫\n+\n+///" } ], "reviews": [ { "id": 2885121768, "user": "user_489e2b951069", "state": "APPROVED", "body": null, "submitted_at": "2025-06-01T05:14:57+00:00" }, { "id": 2885461566, "user": "user_787e19aded2a", "state": "APPROVED", "body": "all good, approved!", "submitted_at": "2025-06-01T10:41:12+00:00" }, { "id": 2899184658, "user": "user_29e85f9a8e75", "state": "COMMENTED", "body": null, "submitted_at": "2025-06-05T07:39:25+00:00" }, { "id": 2899994578, "user": "user_c36c155012b4", "state": "COMMENTED", "body": null, "submitted_at": "2025-06-05T11:49:09+00:00" } ], "review_comments": [ { "id": 2128159685, "user": "user_29e85f9a8e75", "body": "```suggestion\nВи можете використати конфігурацію моделі Pydantic, щоб заборонити (`forbid`) будь-які зайві (`extra`) поля:\n```", "path": "docs/uk/docs/tutorial/query-param-models.md", "line": null, "side": "RIGHT", "created_at": "2025-06-05T07:35:17+00:00" }, { "id": 2128659422, "user": "user_c36c155012b4", "body": "[USER_REDACTED] дякую :)", "path": "docs/uk/docs/tutorial/query-param-models.md", "line": null, "side": "RIGHT", "created_at": "2025-06-05T11:49:09+00:00" } ], "meta": { "languages": [ "md" ], "touches_tests": false, "review_state_summary": { "APPROVED": 2, "COMMENTED": 2 }, "meaningful_comment_count": 2, "has_approval": true, "has_changes_requested": false, "total_review_comments": 2 } } { "_id": "616794881fd3b1fc", "_schema_version": "1.0", "_cleaned_at": "2026-02-12T07:46:51.734133+00:00", "repo": "tiangolo/fastapi", "repo_url": "https://github.com/fastapi/fastapi", "license_name": "MIT License", "license_spdx": "MIT", "pr_number": 13713, "title": "✨ Add OpenAPI `external_docs` parameter to `FastAPI`", "body": "This PR adds an external_docs parameter to the __init__ method of the FastAPI class. Currently, the external_docs parameter is not being passed when generating the OpenAPI documentation, which I believe is an oversight. By [NAME_REDACTED] the FastAPI class constructor, the external_docs field will be correctly included in the root of the generated OpenAPI JSON or YAML file.\n\nReasoning:\n\nThe external_docs field provides valuable external documentation links and should be part of the OpenAPI metadata. Including it at the root level of the OpenAPI spec enhances the usability and completeness of the generated documentation, especially for providing references to external resources.", "author": "user_3726cf4bcebd", "created_at": "2025-05-13T17:21:39+00:00", "merged_at": "2025-09-20T17:11:46+00:00", "base_branch": "master", "head_branch": "add-openapi-external-docs-parameter", "additions": 41, "deletions": 1, "changed_files": 4, "files": [ { "filename": "fastapi/applications.py", "status": "modified", "additions": 28, "deletions": 0, "changes": 28, "patch": "@@ -810,6 +810,32 @@ class Item(BaseModel):\n \"\"\"\n ),\n ] = True,\n+ openapi_external_docs: Annotated[\n+ Optional[Dict[str, Any]],\n+ Doc(\n+ \"\"\"\n+ This field allows you to provide additional external documentation links.\n+ If provided, it must be a dictionary containing:\n+\n+ * `description`: A brief description of the external documentation.\n+ * `url`: The URL pointing to the external documentation. The value **MUST**\n+ be a valid URL format.\n+\n+ **Example**:\n+\n+ ```python\n+ from fastapi import FastAPI\n+\n+ external_docs = {\n+ \"description\": \"Detailed API Reference\",\n+ \"url\": \"https://example.com/api-docs\",\n+ }\n+\n+ app = FastAPI(openapi_external_docs=external_docs)\n+ ```\n+ \"\"\"\n+ ),\n+ ] = None,\n **extra: Annotated[\n Any,\n Doc(\n@@ -838,6 +864,7 @@ class Item(BaseModel):\n self.swagger_ui_parameters = swagger_ui_parameters\n self.servers = servers or []\n self.separate_input_output_schemas = separate_input_output_schemas\n+ self.openapi_external_docs = openapi_external_docs\n self.extra = extra\n self.openapi_version: Annotated[\n str,\n@@ -992,6 +1019,7 @@ def openapi(self) -> Dict[str, Any]:\n tags=self.openapi_tags,\n servers=self.servers,\n separate_input_output_schemas=self.separate_input_output_schemas,\n+ external_docs=self.openapi_external_docs,\n )\n return self.openapi_schema" }, { "filename": "fastapi/openapi/utils.py", "status": "modified", "additions": 3, "deletions": 0, "changes": 3, "patch": "@@ -488,6 +488,7 @@ def get_openapi(\n contact: Optional[Dict[str, Union[str, Any]]] = None,\n license_info: Optional[Dict[str, Union[str, Any]]] = None,\n separate_input_output_schemas: bool = True,\n+ external_docs: Optional[Dict[str, Any]] = None,\n ) -> Dict[str, Any]:\n info: Dict[str, Any] = {\"title\": title, \"version\": version}\n if summary:\n@@ -565,4 +566,6 @@ def get_openapi(\n output[\"webhooks\"] = webhook_paths\n if tags:\n output[\"tags\"] = tags\n+ if external_docs:\n+ output[\"externalDocs\"] = external_docs\n return jsonable_encoder(OpenAPI(**output), by_alias=True, exclude_none=True) # type: ignore" }, { "filename": "tests/main.py", "status": "modified", "additions": 6, "deletions": 1, "changes": 7, "patch": "@@ -3,7 +3,12 @@\n \n from fastapi import FastAPI, Path, Query\n \n-app = FastAPI()\n+external_docs = {\n+ \"description\": \"External API documentation.\",\n+ \"url\": \"https://docs.example.com/api-general\",\n+}\n+\n+app = FastAPI(openapi_external_docs=external_docs)\n \n \n [USER_REDACTED].api_route(\"/api_route\")" }, { "filename": "tests/test_application.py", "status": "modified", "additions": 4, "deletions": 0, "changes": 4, "patch": "@@ -58,6 +58,10 @@ def test_openapi_schema():\n assert response.json() == {\n \"openapi\": \"3.1.0\",\n \"info\": {\"title\": \"FastAPI\", \"version\": \"0.1.0\"},\n+ \"externalDocs\": {\n+ \"description\": \"External API documentation.\",\n+ \"url\": \"https://docs.example.com/api-general\",\n+ },\n \"paths\": {\n \"/api_route\": {\n \"get\": {" } ], "reviews": [ { "id": 3025470833, "user": "user_29e85f9a8e75", "state": "CHANGES_REQUESTED", "body": "[USER_REDACTED], thanks for your interest and efforts!\n\nI think that description should be simplified.\nPlease review my suggestions", "submitted_at": "2025-07-16T15:16:35+00:00" }, { "id": 3031339744, "user": "user_3726cf4bcebd", "state": "COMMENTED", "body": null, "submitted_at": "2025-07-18T00:02:35+00:00" }, { "id": 3032252811, "user": "user_29e85f9a8e75", "state": "COMMENTED", "body": null, "submitted_at": "2025-07-18T06:58:45+00:00" }, { "id": 3079123362, "user": "user_29e85f9a8e75", "state": "APPROVED", "body": "LGTM\n\nNot sure we need this parameter, but if we want to add it, then this PR effectively does it.\n\n[USER_REDACTED], thanks!", "submitted_at": "2025-08-01T12:53:59+00:00" }, { "id": 3249137483, "user": "user_2a237e38e06b", "state": "APPROVED", "body": "Looks good, thank you! 🚀", "submitted_at": "2025-09-20T17:11:24+00:00" } ], "review_comments": [ { "id": 2210694116, "user": "user_29e85f9a8e75", "body": "```suggestion\n This field allows you to provide additional external documentation links.\n If provided, it must be a dictionary containing:\n```", "path": "fastapi/applications.py", "line": null, "side": "RIGHT", "created_at": "2025-07-16T15:04:15+00:00" }, { "id": 2210700949, "user": "user_29e85f9a8e75", "body": "I think we need to make sure it works (CommonMark syntax for rich text formatting)", "path": "fastapi/applications.py", "line": null, "side": "RIGHT", "created_at": "2025-07-16T15:07:13+00:00" }, { "id": 2210706514, "user": "user_29e85f9a8e75", "body": "```suggestion\n from fastapi import FastAPI\n\n external_docs = {\n \"description\": \"Detailed API Reference\",\n \"url\": \"https://example.com/api-docs\",\n }\n\n app = FastAPI(openapi_external_docs=external_docs)\n```\nNo need to specify type explicitly here", "path": "fastapi/applications.py", "line": null, "side": "RIGHT", "created_at": "2025-07-16T15:09:35+00:00" }, { "id": 2210711862, "user": "user_29e85f9a8e75", "body": "```suggestion\n```\nI think we don't need this. The above explanation should be enough", "path": "fastapi/applications.py", "line": null, "side": "RIGHT", "created_at": "2025-07-16T15:11:10+00:00" }, { "id": 2210726845, "user": "user_29e85f9a8e75", "body": "Not sure this is right place for this. Maybe add this to `tests/main.py` and test in `tests/test_application.py`?", "path": "tests/test_openapi_examples.py", "line": null, "side": "RIGHT", "created_at": "2025-07-16T15:14:24+00:00" }, { "id": 2214533550, "user": "user_3726cf4bcebd", "body": "[NAME_REDACTED], thanks a lot for your comments—I really appreciate you taking the time to review this!\n\nCould you help me understand a bit more why you think this might not be the right place for the example? It seemed like a good fit to include it here, since the file is already dedicated to OpenAPI scenarios and includes examples that demonstrate the various OpenAPI-related options and attributes.", "path": "tests/test_openapi_examples.py", "line": null, "side": "RIGHT", "created_at": "2025-07-18T00:02:35+00:00" }, { "id": 2215173315, "user": "user_29e85f9a8e75", "body": "Hi [USER_REDACTED]! You are welcome!\n\n`test_openapi_examples.py` is intended to test `examples` and `openapi_examples` parameters. Look at tests that are already there and you will see that all of them are about these parameters.\n\n`tests/main.py` includes a lot of different use-cases and `tests/test_application.py` tests openapi schema of app from `tests/main.py`.", "path": "tests/test_openapi_examples.py", "line": null, "side": "RIGHT", "created_at": "2025-07-18T06:58:45+00:00" } ], "meta": { "languages": [ "py" ], "touches_tests": true, "review_state_summary": { "CHANGES_REQUESTED": 1, "COMMENTED": 2, "APPROVED": 2 }, "meaningful_comment_count": 7, "has_approval": true, "has_changes_requested": true, "total_review_comments": 7 } } { "_id": "3436bad14fe0a5c4", "_schema_version": "1.0", "_cleaned_at": "2026-02-12T07:46:51.749744+00:00", "repo": "tiangolo/fastapi", "repo_url": "https://github.com/fastapi/fastapi", "license_name": "MIT License", "license_spdx": "MIT", "pr_number": 13639, "title": "✨ Allow array values for OpenAPI schema `type` field", "body": "# [NAME_REDACTED] in [NAME_REDACTED] PR addresses an issue with how union types for the \"type\" field are validated in [NAME_REDACTED] generation. Currently, only a string is allowed for the type definition even though the JSON Schema specification (Section 6.1.1) permits the value to be either a string or an array of unique string values. This discrepancy can lead to confusion or incorrect schema validation when using union types.\n\nExample here that throws pydantic validation error:\n\n```python\n# example.py \n# uv run --no-project example.py\n# /// script\n# requires-python = \">=3.12\"\n# dependencies = [\n# \"fastapi\",\n# \"pydantic\",\n# ]\n# ///\n\nfrom fastapi.openapi.models import OpenAPI\nfrom pydantic import ValidationError\n\nopenapi_dict = {\n \"openapi\": \"3.1.0\",\n \"info\": {\"title\": \"Type Examples with [NAME_REDACTED]\", \"version\": \"1.0.0\"},\n \"components\": {\n \"schemas\": {\n \"UnionStringOrNumber\": {\n \"type\": [\"string\", \"number\"],\n \"description\": \"An instance is valid if it is either a string or a number.\",\n \"example\": \"example as string\",\n },\n }\n },\n}\n\ndef test_openapi_type() -> None:\n try:\n _ = OpenAPI(**openapi_dict)\n except ValidationError as e:\n # Expecting this to raise a ValidationError\n print(f\"Validation error: {e}\")\n return\n\n raise NotImplementedError(\"This should not be reached.\")\n\nif __name__ == \"__main__\":\n test_openapi_type()\n print(\"Test passed!\")\n```\n\nAddressed by introducing`TypeValue`, defined as an annotated literal that encompasses [the valid JSON Schema types.](https://json-schema.org/draft/2020-12/json-schema-validation#section-6.1.1)\n\nAnd updating the Schema model to use the literal values.\n\nAfter these changes the validation error is removed.", "author": "user_294fa42c2aa5", "created_at": "2025-04-23T11:57:27+00:00", "merged_at": "2025-09-20T17:47:25+00:00", "base_branch": "master", "head_branch": "adding-type-values-following-json-schema", "additions": 51, "deletions": 4, "changed_files": 3, "files": [ { "filename": "fastapi/openapi/models.py", "status": "modified", "additions": 8, "deletions": 2, "changes": 10, "patch": "@@ -121,6 +121,12 @@ class ExternalDocumentation(BaseModelWithConfig):\n url: AnyUrl\n \n \n+# Ref JSON Schema 2020-12: https://json-schema.org/draft/2020-12/json-schema-validation#name-type\n+SchemaType = Literal[\n+ \"array\", \"boolean\", \"integer\", \"null\", \"number\", \"object\", \"string\"\n+]\n+\n+\n class Schema(BaseModelWithConfig):\n # Ref: JSON Schema 2020-12: https://json-schema.org/draft/2020-12/json-schema-core.html#name-the-json-schema-core-vocabu\n # [NAME_REDACTED]\n@@ -145,7 +151,7 @@ class Schema(BaseModelWithConfig):\n dependentSchemas: Optional[Dict[str, \"SchemaOrBool\"]] = None\n prefixItems: Optional[List[\"SchemaOrBool\"]] = None\n # TODO: uncomment and remove below when deprecating Pydantic v1\n- # It generales a list of schemas for tuples, before prefixItems was available\n+ # It generates a list of schemas for tuples, before prefixItems was available\n # items: Optional[\"SchemaOrBool\"] = None\n items: Optional[Union[\"SchemaOrBool\", List[\"SchemaOrBool\"]]] = None\n contains: Optional[\"SchemaOrBool\"] = None\n@@ -157,7 +163,7 @@ class Schema(BaseModelWithConfig):\n unevaluatedProperties: Optional[\"SchemaOrBool\"] = None\n # Ref: JSON [NAME_REDACTED] 2020-12: https://json-schema.org/draft/2020-12/json-schema-validation.html#name-a-vocabulary-for-structural\n # A Vocabulary for [NAME_REDACTED]\n- type: Optional[str] = None\n+ type: Optional[Union[SchemaType, List[SchemaType]]] = None\n enum: Optional[List[Any]] = None\n const: Optional[Any] = None\n multipleOf: Optional[float] = Field(default=None, gt=0)" }, { "filename": "tests/test_custom_schema_fields.py", "status": "modified", "additions": 17, "deletions": 2, "changes": 19, "patch": "@@ -1,7 +1,13 @@\n+from typing import Optional\n+\n from fastapi import FastAPI\n from fastapi._compat import PYDANTIC_V2\n from fastapi.testclient import TestClient\n from pydantic import BaseModel\n+from typing_extensions import Annotated\n+\n+if PYDANTIC_V2:\n+ from pydantic import WithJsonSchema\n \n app = FastAPI()\n \n@@ -10,12 +16,17 @@ class Item(BaseModel):\n name: str\n \n if PYDANTIC_V2:\n+ description: Annotated[\n+ Optional[str], WithJsonSchema({\"type\": [\"string\", \"null\"]})\n+ ] = None\n+\n model_config = {\n \"json_schema_extra\": {\n \"x-something-internal\": {\"level\": 4},\n }\n }\n else:\n+ description: Optional[str] = None # type: ignore[no-redef]\n \n class Config:\n schema_extra = {\n@@ -42,7 +53,11 @@ def foo():\n \"name\": {\n \"title\": \"Name\",\n \"type\": \"string\",\n- }\n+ },\n+ \"description\": {\n+ \"title\": \"Description\",\n+ \"type\": [\"string\", \"null\"] if PYDANTIC_V2 else \"string\",\n+ },\n },\n }\n \n@@ -57,4 +72,4 @@ def test_response():\n # For coverage\n response = client.get(\"/foo\")\n assert response.status_code == 200, response.text\n- assert response.json() == {\"name\": \"Foo item\"}\n+ assert response.json() == {\"name\": \"Foo item\", \"description\": None}" }, { "filename": "tests/test_openapi_schema_type.py", "status": "added", "additions": 26, "deletions": 0, "changes": 26, "patch": "@@ -0,0 +1,26 @@\n+from typing import List, Optional, Union\n+\n+import pytest\n+from fastapi.openapi.models import Schema, SchemaType\n+\n+\n+[USER_REDACTED].mark.parametrize(\n+ \"type_value\",\n+ [\n+ \"array\",\n+ [\"string\", \"null\"],\n+ None,\n+ ],\n+)\n+def test_allowed_schema_type(\n+ type_value: Optional[Union[SchemaType, List[SchemaType]]],\n+) -> None:\n+ \"\"\"Test that Schema accepts SchemaType, List[SchemaType] and None for type field.\"\"\"\n+ schema = Schema(type=type_value)\n+ assert schema.type == type_value\n+\n+\n+def test_invalid_type_value() -> None:\n+ \"\"\"Test that Schema raises ValueError for invalid type values.\"\"\"\n+ with pytest.raises(ValueError, match=\"2 validation errors for Schema\"):\n+ Schema(type=True) # type: ignore[arg-type]" } ], "reviews": [ { "id": 3052018999, "user": "user_29e85f9a8e75", "state": "COMMENTED", "body": "Let's reduce the number of test a bit :)\nJust test that all valid types are accepted and maybe add one test for validation error on passing incorrect type\n\n> Added some tests, but the change in this PR is quite small and is only made to allow for type to be a str and list. But since there is no field validator for type its still possible to break the json schema. (by [NAME_REDACTED] a empty list or by [NAME_REDACTED]\n> But I think this is a good start and more validation can be added later. wdyt?\n\nI agree, no need to add this validation now.", "submitted_at": "2025-07-24T14:56:03+00:00" }, { "id": 3053043323, "user": "user_29e85f9a8e75", "state": "COMMENTED", "body": null, "submitted_at": "2025-07-24T19:39:59+00:00" }, { "id": 3053067506, "user": "user_29e85f9a8e75", "state": "APPROVED", "body": "LGTM\n\n[USER_REDACTED], thanks!", "submitted_at": "2025-07-24T19:47:39+00:00" }, { "id": 3249167815, "user": "user_2a237e38e06b", "state": "APPROVED", "body": "Sounds good, thanks! 🚀 \n\nI tweaked it a bit to put the OpenAPI types and related on the same file, it should be ready now. 🍰", "submitted_at": "2025-09-20T17:45:51+00:00" } ], "review_comments": [ { "id": 2228756723, "user": "user_29e85f9a8e75", "body": "```suggestion\ndef test_schema_type_multiple_type_value() -> None:\n \"\"\"Test all possible values of TypeValue for Schema type field.\"\"\"\n schema = Schema(type=TYPE_VALUES)\n assert schema.type == TYPE_VALUES\n```\n\nI think now it's too much tests for such small feature. 🤣\nLet's just test one combination of all possible values?", "path": "tests/test_openapi_schema_type.py", "line": null, "side": "RIGHT", "created_at": "2025-07-24T14:51:40+00:00" }, { "id": 2229423740, "user": "user_29e85f9a8e75", "body": "```suggestion\ndef test_invalid_type_value() -> None:\n```", "path": "tests/test_openapi_schema_type.py", "line": null, "side": "RIGHT", "created_at": "2025-07-24T19:39:59+00:00" } ], "meta": { "languages": [ "py" ], "touches_tests": true, "review_state_summary": { "COMMENTED": 2, "APPROVED": 2 }, "meaningful_comment_count": 2, "has_approval": true, "has_changes_requested": false, "total_review_comments": 2 } } { "_id": "a8c43ad877314618", "_schema_version": "1.0", "_cleaned_at": "2026-02-12T07:46:51.749744+00:00", "repo": "tiangolo/fastapi", "repo_url": "https://github.com/fastapi/fastapi", "license_name": "MIT License", "license_spdx": "MIT", "pr_number": 13630, "title": "🌐 Update Korean translation for `docs/ko/docs/virtual-environments.md`", "body": "Hello! 👋 This is my first contribution to [NAME_REDACTED] translation 😊\n\nI translated the `docs/ko/docs/virtual-environments.md` file into Korean.\nSince it's a core topic in Python projects, I noticed it hasn't been localized yet, so I decided to help!\n\nI tried to stay as close as possible to the original English format and meaning.\n\nIf there is any feedback, I’d be happy to update it right away.\n\n감사합니다!\n\n\"image\"\n\nBefore : https://fastapi.tiangolo.com/ko/virtual-environments/\nAfter. : https://2d5c56b3.fastapitiangolo.pages.dev/ko/virtual-environments/", "author": "user_9012ae87551f", "created_at": "2025-04-21T09:07:10+00:00", "merged_at": "2025-05-30T13:10:41+00:00", "base_branch": "master", "head_branch": "fix/ko-typo-virtual-environments", "additions": 846, "deletions": 0, "changed_files": 1, "files": [ { "filename": "docs/ko/docs/virtual-environments.md", "status": "added", "additions": 846, "deletions": 0, "changes": 846, "patch": "@@ -0,0 +1,846 @@\n+# 가상 환경\n+\n+Python 프로젝트를 작업할 때는 **가상 환경** (또는 이와 유사한 도구)을 사용하는 것이 좋습니다. 각 프로젝트 마다 설치하는 패키지를 분리하여 관리할 수 있습니다.\n+\n+/// info | 정보\n+\n+이미 가상 환경에 대해 잘 알고 있다면, 이 섹션은 건너 뛰어도 괜찮습니다. 🤓\n+\n+///\n+\n+/// tip | 팁\n+\n+**가상 환경([NAME_REDACTED])** 은 **환경 변수([NAME_REDACTED])** 와 다릅니다.\n+\n+**환경 변수**는 시스템에 존재하며, 프로그램이 사용할 수 있는 변수입니다.\n+\n+**가상 환경**은 몇몇 파일로 구성된 하나의 디렉터리입니다.\n+\n+///\n+\n+/// info | 정보\n+\n+이 페이지에서는 **가상 환경**의 사용 방법과 작동 방식을 설명합니다.\n+\n+만약 **모든 것을 관리해주는 도구** (Python 설치까지 포함)를 사용하고 싶다면 uv를 사용해보세요.\n+\n+///\n+\n+## 프로젝트 생성\n+\n+먼저, 프로젝트를 위한 디렉터리를 하나 생성합니다.\n+\n+보통 사용자 홈 디렉터리 안에 `code`라는 디렉터리를 만들고, 그 안에 프로젝트마다 하나씩 디렉터리를 만들어 관리합니다.\n+\n+
      \n+\n+```console\n+// 홈 디렉터리로 이동\n+$ cd\n+// 모든 코드 프로젝트를 위한 디렉터리 생성\n+$ mkdir code\n+// code 디렉터리로 이동\n+$ cd code\n+// 이번 프로젝트를 위한 디렉터리 생성\n+$ mkdir awesome-project\n+// 해당 프로젝트 디렉터리로 이동\n+$ cd awesome-project\n+```\n+\n+
      \n+\n+## 가상 환경 생성\n+\n+Python 프로젝트를 **처음 시작할 때**, 가상 환경을 **프로젝트 내부**에 생성합니다.\n+\n+/// tip | 팁\n+\n+이 작업은 **프로젝트를 처음 설정할 때 한번만** 해주면 됩니다. 이후 작업할 때 반복할 필요는 없습니다.\n+\n+///\n+\n+//// tab | `venv`\n+\n+Python 표준 라이브러리에 포함된 venv 모듈을 사용해 가상 환경을 생성할 수 있습니다.\n+\n+
      \n+\n+```console\n+$ python -m venv .venv\n+```\n+\n+
      \n+\n+/// details | 명령어 상세 설명\n+\n+* `python`: `python` 프로그램을 실행합니다.\n+* `-m`: 특정 모듈을 스크립트처럼 실행합니다. 대상 모듈을 바로 뒤에 지정합니다.\n+* `venv`: Python 표준 라이브러리에 포함된 `venv` 모듈을 실행합니다.\n+* `.venv`: 가상 환경을 `.venv` 디렉터리에 생성합니다.\n+\n+///\n+\n+////\n+\n+//// tab | `uv`\n+\n+`uv`가 설치되어 있다면, uv를 통해 가상 환경을 생성할 수 있습니다.\n+\n+
      \n+\n+```console\n+$ uv venv\n+```\n+\n+
      \n+\n+/// tip | 팁\n+\n+`uv`는 기본적으로 `.venv` 디렉터리에 가상 환경을 생성합니다.\n+\n+별도로 디렉터리 이름을 추가 인자로 넘겨 주면 경로를 지정 할 수 있습니다.\n+\n+///\n+\n+////\n+\n+해당 명령어는 `.venv` 디렉터리에 새로운 가상 환경을 생성합니다.\n+\n+/// details | `.venv` 또는 다른 이름\n+\n+가상 환경을 다른 디렉터리에 생성할 수도 있지만, 관례적으로 `.venv` 디렉터리 이름을 사용합니다.\n+\n+///\n+\n+## 가상 환경 활성화\n+\n+이후 실행하는 Python 명령어와 패키지 설치가 가상 환경을 따르도록, 가상 환경을 활성화하세요.\n+\n+/// tip | 팁\n+\n+**터미널을 새로 열고** 프로젝트 작업을 시작할 때는, **항상 이 작업을** 해주세요.\n+\n+///\n+\n+//// tab | Linux, macOS\n+\n+
      \n+\n+```console\n+$ source .venv/bin/activate\n+```\n+\n+
      \n+\n+////\n+\n+//// tab | [NAME_REDACTED]\n+\n+
      \n+\n+```console\n+$ .venv\\Scripts\\Activate.ps1\n+```\n+\n+
      \n+\n+////\n+\n+//// tab | [NAME_REDACTED]\n+\n+Windows에서 Bash(예: [NAME_REDACTED])를 사용하는 경우:\n+\n+
      \n+\n+```console\n+$ source .venv/Scripts/activate\n+```\n+\n+
      \n+\n+////\n+\n+/// tip | 팁\n+\n+가상 환경에 새로운 패키지를 설치할 때마다, 해당 환경을 다시 활성화하세요.\n+\n+이렇게 하면 해당 패키지로 설치된 **터미널(CLI) 프로그램**을 사용할 때, 전역에 설치된 다른 버전이 아니라, 가상 환경 안에 설치된 정확한 버전을 사용합니다.\n+\n+///\n+\n+## 가상 환경이 활성화 여부 확인\n+\n+가상 환경이 활성화되었는지 확인합니다. (이전 명령어가 제대로 작동했는지 확인합니다).\n+\n+/// tip | 팁\n+\n+이 단계는 **선택 사항**이지만, 모든 것이 예상대로 작동하고 있는지, 그리고 의도한 가상 환경이 활성화 되었는 지 **확인**하는 좋은 방법입니다.\n+\n+///\n+\n+//// tab | Linux, macOS, [NAME_REDACTED]\n+\n+
      \n+\n+```console\n+$ which python\n+\n+/home/user/code/awesome-project/.venv/bin/python\n+```\n+\n+
      \n+\n+`python` 위치가 프로젝트 내부(이 예시에서는 `awesome-project`)의 `.venv/bin/python` 경로로 표시된다면 성공입니다. 🎉\n+\n+////\n+\n+//// tab | [NAME_REDACTED]\n+\n+
      \n+\n+```console\n+$ Get-Command python\n+\n+C:\\Users\\user\\code\\awesome-project\\.venv\\Scripts\\python\n+```\n+\n+
      \n+\n+`python` 위치가 프로젝트 내부(이 예시에서는 `awesome-project`)의 `.venv\\bin\\python` 경로로 표시된다면 성공입니다. 🎉\n+\n+////\n+\n+## pip 업그레이드\n+\n+/// tip | 팁\n+\n+`uv`를 사용한다면, `pip` 대신 `uv`로 패키지를 설치하게 되므로 `pip`을 업그레이드할 필요가 없습니다. 😎\n+\n+///\n+\n+`pip`을 사용하여 패키지를 설치하는 경우 (Python 표준 라이브러리에 포함되어 있습니다), **최신 버전으로 업그레이드**하는 것이 좋습니다.\n+\n+패키지 설치 중 발생하는 다양하고 특이한 에러들은 `pip` 업그레이드로 쉽게 해결되는 경우가 많습니다.\n+\n+/// tip | 팁\n+\n+이 작업은 보통 가상 환경을 생성한 **직후 한 번만** 하면 됩니다.\n+\n+///\n+\n+가상 환경이 활성화된 상태인지 확인한 후(앞서 설명한 명령어 사용), 아래 명령어를 실행하세요:\n+\n+
      \n+\n+```console\n+$ python -m pip install --upgrade pip\n+\n+---> 100%\n+```\n+\n+
      \n+\n+## `.gitignore` 추가하기\n+\n+**Git**을 사용하고 있다면 (사용하는 것이 좋습니다), `.gitignore` 파일을 추가해서 `.venv` 디렉터리 전체를 Git에서 제외하세요.\n+\n+/// tip | 팁\n+\n+`uv`를 사용해 가상 환경을 생성했다면, 이미 이 작업이 자동으로 처리되어 있으므로 이 단계는 건너뛰어도 됩니다. 😎\n+\n+///\n+\n+/// tip | 팁\n+\n+이 작업도 마찬가지로, 가상 환경을 생성한 **직후 한 번만** 하면 됩니다.\n+\n+///\n+\n+
      \n+\n+```console\n+$ echo \"*\" > .venv/.gitignore\n+```\n+\n+
      \n+\n+/// details | 명령어 상세 설명\n+\n+* `echo \"*\"`: 터미널에 `*` 텍스트를 \"출력\"합니다 (다음 설명에서 조금 바뀝니다)\n+* `>`: 왼쪽 명령어의 출력 내용을 터미널에 출력하지 않고, 오른쪽에 지정된 파일로 **기록(write)** 하라는 의미입니다.\n+* `.gitignore`: 출력된 텍스트가 기록될 파일 이름입니다.\n+\n+그리고 Git에서 `*`는 \"모든 것\"을 의미합니다. 따라서 `.venv` 디렉터리 안의 모든 것을 무시하게 됩니다.\n+\n+이 명령어는 다음과 같은 내용을 가진 `.gitignore` 파일을 생성합니다:\n+\n+\n+```gitignore\n+*\n+```\n+\n+///\n+\n+## 패키지 설치\n+\n+가상 환경을 활성화한 후, 그 안에 필요한 패키지들을 설치할 수 있습니다.\n+\n+/// tip | 팁\n+\n+프로젝트에서 필요한 패키지를 설치하거나 업그레이드할 때는 이 작업을 **한 번만** 하면 됩니다.\n+\n+만약 특정 패키지의 버전을 업그레이드하거나, 새로운 패키지를 추가할 필요가 생기면 **다시 이 작업을 반복**하면 됩니다.\n+\n+///\n+\n+### 패키지 직접 설치\n+\n+급하게 작업하거나, 프로젝트에 필요한 패키지 목록을 따로 파일로 관리하고 싶지 않은 경우, 패키지를 직접 설치할 수도 있습니다.\n+\n+/// tip | 팁\n+\n+패키지 이름과 버전 정보를 파일에 정리해두는 것(예: `requirements.txt` 또는 `pyproject.toml`)은 (매우) 좋은 생각입니다.\n+\n+///\n+\n+//// tab | `pip`\n+\n+
      \n+\n+```console\n+$ pip install \"fastapi[standard]\"\n+\n+---> 100%\n+```\n+\n+
      \n+\n+////\n+\n+//// tab | `uv`\n+\n+`uv`를 사용하는 경우:\n+\n+
      \n+\n+```console\n+$ uv pip install \"fastapi[standard]\"\n+---> 100%\n+```\n+\n+
      \n+\n+////\n+\n+### `requirements.txt`에서 설치\n+\n+`requirements.txt` 파일이 있다면, 그 안에 명시된 패키지들을 한 번에 설치할 수 있습니다.\n+\n+//// tab | `pip`\n+\n+
      \n+\n+```console\n+$ pip install -r requirements.txt\n+---> 100%\n+```\n+\n+
      \n+\n+////\n+\n+//// tab | `uv`\n+\n+`uv`를 사용하는 경우:\n+\n+
      \n+\n+```console\n+$ uv pip install -r requirements.txt\n+---> 100%\n+```\n+\n+
      \n+\n+////\n+\n+/// details | `requirements.txt`\n+\n+다음은 몇 가지 패키지를 포함한 `requirements.txt`의 예시입니다:\n+\n+```requirements.txt\n+fastapi[standard]==0.113.0\n+pydantic==2.8.0\n+```\n+\n+///\n+\n+## 프로그램 실행\n+\n+가상 환경을 활성화한 후에는 프로그램을 실행할 수 있습니다. 이때 해당 가상 환경에 설치된 Python과 패키지들이 사용됩니다.\n+\n+
      \n+\n+```console\n+$ python main.py\n+\n+[NAME_REDACTED]\n+```\n+\n+
      \n+\n+## 에디터 설정\n+\n+에디터를 사용할 경우, 앞서 만든 가상 환경을 사용하도록 설정하는 것이 좋습니다. (대부분의 에디터는 자동으로 감지하기도 합니다.)\n+이렇게 하면 자동 완성 기능이나 코드 내 오류 표시 기능을 제대로 사용할 수 있습니다.\n+\n+예시:\n+\n+* VS Code\n+* PyCharm\n+\n+/// tip | 팁\n+\n+이 설정은 보통 가상 환경을 **처음 만들었을 때 한 번만** 해주면 됩니다.\n+\n+///\n+\n+## 가상 환경 비활성화\n+\n+프로젝트 작업이 끝났다면, 가상 환경을 **비활성화**할 수 있습니다.\n+\n+
      \n+\n+```console\n+$ deactivate\n+```\n+\n+
      \n+\n+이렇게 하면 이후에 `python` 명령어를 실행했을 때, 가상 환경의 Python이나 그 안에 설치된 패키지들을 사용하지 않게 됩니다.\n+\n+## 이제 작업할 준비가 되었습니다\n+\n+이제 프로젝트 작업을 시작할 준비가 완료되었습니다.\n+\n+\n+/// tip | 팁\n+\n+위 내용을 더 깊이 이해하고 싶으신가요?\n+\n+그렇다면 계속 읽어 주세요. 👇🤓\n+\n+///\n+\n+## 가상 환경을 왜 사용하는가\n+\n+FastAPI를 사용하려면 먼저 Python을 설치해야 합니다.\n+\n+그 후에는 FastAPI와 함께 사용할 **기타 패키지들**을 **설치**해야 합니다.\n+\n+패키지를 설치할 때 보통 Python에 기본 포함된 `pip` 명령어(또는 유사한 도구)를 사용합니다.\n+\n+하지만 `pip`을 그냥 직접 사용하면, 해당 패키지들은 **전역 Python 환경**(시스템 전체에 설치된 Python)에 설치됩니다.\n+\n+### 문제점\n+\n+그렇다면, 전역 Python 환경에 패키지를 설치하면 어떤 문제가 발생할까요?\n+\n+어느 시점이 되면, **서로 다른 패키지들**에 의존하는 여러 개의 프로그램을 작성하게 될 것입니다. 그리고 이들 중 일부는 **같은 패키지의 서로 다른 버전**을 필요로 할 수 있습니다. 😱\n+\n+예를 들어, `마법사의 돌(philosophers-stone)` 프로젝트를 만들었다고 가정해봅시다. 이 프로그램은 `해리 포터(harry)`라는 패키지의 `v1` 버전을 **의존**합니다. 따라서 `harry`를 설치해야 합니다.\n+\n+```mermaid\n+flowchart LR\n+ stone(philosophers-stone) -->|requires| harry-1[harry v1]\n+```\n+\n+그런데 나중에 `아즈카반의 죄수(prisoner-of-azkaban)`이라는 또 다른 프로젝트를 만들게 되었고, 이 프로젝트도 역시 `harry` 패키지를 사용합니다. 그런데 이 프로젝트는 `harry`의 `v3` 버전이 필요합니다.\n+\n+```mermaid\n+flowchart LR\n+ azkaban(prisoner-of-azkaban) --> |requires| harry-3[harry v3]\n+```\n+\n+하지만 이제 문제가 생깁니다. 로컬 가상 환경 대신에 전역 환경에 패키지를 설치하게 되면, 어떤 버전의 `harry`를 설치할지를 선택해야 하기 때문입니다.\n+\n+예를 들어, `마법사의 돌(philosophers-stone)`을 실행하고 싶다면 먼저 `harry` `v1` 버전을 다음과 같이 설치 해야 합니다:\n+\n+
      \n+\n+```console\n+$ pip install \"harry==1\"\n+```\n+\n+
      \n+\n+그러면 결국 전역 Python 환경에는 `harry` `v1`버전이 설치된 상태가 됩니다.\n+\n+```mermaid\n+flowchart LR\n+ subgraph global[global env]\n+ harry-1[harry v1]\n+ end\n+ subgraph stone-project[philosophers-stone project]\n+ stone(philosophers-stone) -->|requires| harry-1\n+ end\n+```\n+\n+하지만 이제 `아즈카반의 죄수(prisoner-of-azkaban)`을 실행하고 싶다면, `harry` `v1`버전을 제거하고 `harry` `v3`버전을 설치해야 합니다. (또는 단순히 `v3`버전을 설치하는 것만으로도 기존의 `v1`버전이 자동으로 제거됩니다.)\n+\n+
      \n+\n+```console\n+$ pip install \"harry==3\"\n+```\n+\n+
      \n+\n+그렇게 하면 이제 전역 Python 환경에는 `harry` `v3`버전이 설치된 상태가 됩니다.\n+\n+그리고 다시 `마법사의 돌(philosophers-stone)`을 실행하려고 하면, **작동하지** 않을 수 있습니다. 왜냐하면 이 프로그램은 `harry` `v1`버전을 필요로 하기 때문입니다.\n+\n+```mermaid\n+flowchart LR\n+ subgraph global[global env]\n+ harry-1[harry v1]\n+ style harry-1 fill:#ccc,stroke-dasharray: 5 5\n+ harry-3[harry v3]\n+ end\n+ subgraph stone-project[philosophers-stone project]\n+ stone(philosophers-stone) -.-x|⛔️| harry-1\n+ end\n+ subgraph azkaban-project[prisoner-of-azkaban project]\n+ azkaban(prisoner-of-azkaban) --> |requires| harry-3\n+ end\n+```\n+\n+/// tip | 팁\n+\n+Python 패키지들은 **새 버전**에서 **호환성 문제(breaking changes)**가 발생하지 않도록 최대한 노력하는 것이 일반적입니다. 하지만 그래도 안전하게 작업하려면, 테스트를 실행해보면서 새 버전을 의도적으로 설치하는 것이 좋습니다.\n+\n+///\n+\n+이제, 이런 일이 여러분의 **모든 프로젝트**가 사용하는 **수많은 패키지들**에서 동시에 발생한다고 상상해보세요. 이는 매우 관리하기 어려우며, 결국 **서로 호환되지 않는 버전**의 패키지로 프로젝트를 실행하게 될 가능성이 높고, 그로 인해 어떤 문제가 왜 발생하는지 알 수 없게 될 수 있습니다.\n+\n+또한 사용하는 운영체제(Linux, Windows, macOS 등)에 따라 Python이 **미리 설치되어 있을 수도** 있습니다. 이런 경우에는 운영체제의 동작에 필요한 특정 버전의 패키지들이 함께 설치되어 있을 수 있습니다. 이 상태에서 전역 Python 환경에 임의의 패키지를 설치하면, 운영체제에 포함된 프로그램 일부가 **깨질 위험**도 있습니다.\n+\n+## 패키지들은 어디에 설치되는가\n+\n+Python을 설치하면, 컴퓨터에 여러 디렉터리와 파일들이 생성됩니다.\n+\n+이 중 일부 디렉터리는 사용자가 설치한 패키지들을 보관하는 역할을 합니다.\n+\n+예를 들어, 아래 명령어를 실행하면:\n+\n+
      \n+\n+```console\n+// 지금 실행하지 않아도 됩니다, 그냥 예제일 뿐이에요 🤓\n+$ pip install \"fastapi[standard]\"\n+---> 100%\n+```\n+\n+
      \n+\n+해당 명령어는 FastAPI 코드를 포함한 압축 파일을 다운로드합니다. 이 파일은 보통 PyPI에서 받아옵니다.\n+\n+또한 FastAPI가 의존하는 다른 패키지들도 함께 **다운로드**됩니다.\n+\n+그리고 그 모든 파일들을 **압축 해제**한 뒤, 컴퓨터의 특정 디렉터리에 저장합니다.\n+\n+기본적으로 이 파일들은 Python이 설치된 디렉터리 안, 즉 **전역 환경**에 내의 디렉터리에 저장됩니다.\n+\n+## 가상 환경이란\n+\n+전역 환경에 모든 패키지를 설치하면서 발생하는 문제에 대한 해결책은, 작업하는 **각 프로젝트마다 가상 환경**을 사용하는 것입니다.\n+\n+가상 환경은 전역 환경과 매우 유사한 하나의 **디렉터리**이며, 그 안에 해당 프로젝트를 위한 패키지들을 설치할 수 있습니다.\n+\n+이렇게 하면 각 프로젝트는 자체적인 가상 환경(`.venv` 디렉터리)을 가지게 되며, 그 안에 해당 프로젝트 전용 패키지들을 보유하게 됩니다.\n+\n+\n+```mermaid\n+flowchart TB\n+ subgraph stone-project[philosophers-stone project]\n+ stone(philosophers-stone) --->|requires| harry-1\n+ subgraph venv1[.venv]\n+ harry-1[harry v1]\n+ end\n+ end\n+ subgraph azkaban-project[prisoner-of-azkaban project]\n+ azkaban(prisoner-of-azkaban) --->|requires| harry-3\n+ subgraph venv2[.venv]\n+ harry-3[harry v3]\n+ end\n+ end\n+ stone-project ~~~ azkaban-project\n+```\n+\n+## 가상 환경 활성화 의미\n+\n+가상 환경을 활성화한다는 것은, 예를 들어 다음과 같은 명령어를 실행하는 것을 의미합니다:\n+\n+//// tab | Linux, macOS\n+\n+
      \n+\n+```console\n+$ source .venv/bin/activate\n+```\n+\n+
      \n+\n+////\n+\n+//// tab | [NAME_REDACTED]\n+\n+
      \n+\n+```console\n+$ .venv\\Scripts\\Activate.ps1\n+```\n+\n+
      \n+\n+////\n+\n+//// tab | [NAME_REDACTED]\n+\n+Windows에서 Bash(예: [NAME_REDACTED])를 사용하는 경우:\n+\n+
      \n+\n+```console\n+$ source .venv/Scripts/activate\n+```\n+\n+
      \n+\n+////\n+\n+이 명령어는 이후에 실행될 명령어에서 사용될 [환경 변수](environment-variables.md){.internal-link target=_blank} 몇 개를 생성하거나 수정합니다.\n+\n+이 변수들 중 하나가 바로 `PATH` 변수입니다.\n+\n+/// tip | 팁\n+\n+`PATH` 환경 변수에 대해 더 알고 싶다면 [환경 변수 문서의 PATH 환경 변수 섹션](environment-variables.md#path-environment-variable){.internal-link target=_blank}을 참고하세요.\n+\n+///\n+\n+가상 환경을 활성화하면, 가상 환경의 경로인 `.venv/bin` (Linux와 macOS) 또는 `.venv\\Scripts`(Windows)를 `PATH` 환경 변수에 추가됩니다.\n+\n+예를 들어, 가상 환경을 활성화하기 전의 `PATH` 변수는 다음과 같았다고 가정해봅시다:\n+\n+//// tab | Linux, macOS\n+\n+```plaintext\n+/usr/bin:/bin:/usr/sbin:/sbin\n+```\n+\n+시스템은 다음 경로들에서 프로그램을 찾게 됩니다:\n+\n+* `/usr/bin`\n+* `/bin`\n+* `/usr/sbin`\n+* `/sbin`\n+\n+////\n+\n+//// tab | Windows\n+\n+```plaintext\n+C:\\Windows\\System32\n+```\n+\n+시스템은 다음 경로들에서 프로그램을 찾게 됩니다:\n+\n+* `C:\\Windows\\System32`\n+\n+////\n+\n+가상 환경을 활성화한 후에는, `PATH` 변수는 다음과 같은 형태가 됩니다:\n+\n+//// tab | Linux, macOS\n+\n+```plaintext\n+/home/user/code/awesome-project/.venv/bin:/usr/bin:/bin:/usr/sbin:/sbin\n+```\n+\n+시스템은 가장 먼저 다음 경로에서 프로그램을 찾기 시작합니다:\n+\n+```plaintext\n+/home/user/code/awesome-project/.venv/bin\n+```\n+\n+그 후에 다른 디렉터리들을 탐색합니다.\n+\n+따라서 터미널에 `python`을 입력하면, 시스템은 다음 위치에 있는 Python 프로그램을 찾게 됩니다:\n+\n+```plaintext\n+/home/user/code/awesome-project/.venv/bin/python\n+```\n+\n+그리고 해당 Python을 사용하게 됩니다.\n+\n+////\n+\n+//// tab | Windows\n+\n+```plaintext\n+C:\\Users\\user\\code\\awesome-project\\.venv\\Scripts;C:\\Windows\\System32\n+```\n+\n+시스템은 가장 먼저 다음 경로에서 프로그램을 찾기 시작합니다:\n+\n+```plaintext\n+C:\\Users\\user\\code\\awesome-project\\.venv\\Scripts\n+```\n+\n+그 후에 다른 디렉터리들을 탐색합니다.\n+\n+따라서 터미널에 `python`을 입력하면, 시스템은 다음 경로에 있는 Python 프로그램을 찾게 됩니다:\n+\n+```plaintext\n+C:\\Users\\user\\code\\awesome-project\\.venv\\Scripts\\python\n+```\n+\n+그리고 해당 Python을 사용하게 됩니다.\n+\n+////\n+\n+중요한 세부 사항 중 하나는, 가상 환경의 경로가 `PATH` 변수의 가장 **앞**에 추가된다는 점입니다. 시스템은 사용 가능한 다른 Python들보다 **먼저** 이 경로를 찾습니다. 그래서 터미널에서 `python`을 실행하면, 전역 환경의 Python이 아닌 **가상 환경에 있는** Python이 사용됩니다. (예: 전역 환경에 설치된 `python`이 있더라도 그보다 우선합니다.)\n+\n+가상 환경을 활성화하면 이 외에도 몇 가지 다른 것들이 변경되지만, 이는 그중에서도 가장 중요한 변화 중 하나입니다.\n+\n+## 가상 환경 확인하기\n+\n+가상 환경이 활성화 되었는지 확인하려면, 아래 명령어를 사용할 수 있습니다:\n+\n+//// tab | Linux, macOS, [NAME_REDACTED]\n+\n+
      \n+\n+```console\n+$ which python\n+\n+/home/user/code/awesome-project/.venv/bin/python\n+```\n+\n+
      \n+\n+////\n+\n+//// tab | [NAME_REDACTED]\n+\n+
      \n+\n+```console\n+$ Get-Command python\n+\n+C:\\Users\\user\\code\\awesome-project\\.venv\\Scripts\\python\n+```\n+\n+
      \n+\n+////\n+\n+즉, 현재 사용되는 `python` 프로그램은 **가상 환경 내부에 있는 것**입니다.\n+\n+Linux와 macOS에서는 `which`, Windows PowerShell에서는 `Get-Command` 명령어를 사용합니다.\n+\n+이 명령어는 `PATH` 환경 변수에 지정된 경로들을 **순서대로 탐색**하면서 `python`이라는 이름의 프로그램을 찾습니다.\n+찾는 즉시, 해당 프로그램의 **경로를 출력**합니다.\n+\n+중요한 점은 터미널에서 `python`을 실행했을 때, 실제로 실행되는 \"`python`\"이 어떤 것인지 정확히 알 수 있다는 것입니다.\n+\n+따라서 현재 올바른 가상 환경에 있는지 확인할 수 있습니다.\n+\n+/// tip | 팁\n+\n+하나의 가상 환경을 활성화한 뒤, 해당 Python을 가진 상태에서 **또 다른 프로젝트**로 이동하는 것은 흔히 발생합니다.\n+\n+하지만 이때 이전 프로젝트의 가상 환경에 있는 **잘못된 Python 실행 파일**을 사용하게 되어 새 프로젝트가 **정상 작동하지 않을 수 있습니다.**\n+\n+그래서 현재 어떤 `python`이 사용되고 있는지 확인할 수 있는 능력은 매우 유용합니다. 🤓\n+\n+///\n+\n+## 가상 환경을 비활성화하는 이유\n+\n+예를 들어 `마법사의 돌(philosophers-stone)`이라는 프로젝트에서 작업 중이라고 해보겠습니다. 이때 해당 **가상 환경을 활성화**하고, 필요한 패키지를 설치하며 작업을 진행합니다.\n+\n+그런데 이제는 **다른 프로젝트**인 `아즈카반의 죄수(prisoner-of-azkaban)`을 작업하고 싶어졌습니다.\n+\n+그래서 그 프로젝트 디렉터리로 이동합니다:\n+\n+
      \n+\n+```console\n+$ cd ~/code/prisoner-of-azkaban\n+```\n+\n+
      \n+\n+만약 `마법사의 돌(philosophers-stone)`의 가상 환경을 비활성화하지 않았다면, 터미널에서 `python`을 실행할 때 여전히 `마법사의 돌(philosophers-stone)` 가상 환경의 Python을 사용하게 됩니다.\n+\n+
      \n+\n+```console\n+$ cd ~/code/prisoner-of-azkaban\n+\n+$ python main.py\n+\n+// sirius를 임포트하는 데 실패했습니다. 설치되어 있지 않아요 😱\n+Traceback (most recent call last):\n+ File \"main.py\", line 1, in \n+ import sirius\n+```\n+\n+
      \n+\n+하지만 `마법사의 돌(philosophers-stone)`의 가상 환경을 비활성화한 다음, `아즈카반의 죄수(prisoner-of-azkaban)` 프로젝트의 가상 환경을 활성화하면, 이제 `python` 명령어는 `아즈카반의 죄수(prisoner-of-azkaban)` 가상 환경의 Python을 사용하게 됩니다.\n+\n+
      \n+\n+```console\n+$ cd ~/code/prisoner-of-azkaban\n+\n+// 이전 디렉터리에 있을 필요 없이, 어디서든 가상 환경을 비활성화할 수 있습니다. 다른 프로젝트 디렉터리로 이동한 후에도 괜찮아요 😎\n+$ deactivate\n+\n+// prisoner-of-azkaban/.venv 가상 환경을 활성화합니다 🚀\n+$ source .venv/bin/activate\n+\n+// 이제 python을 실행하면, 이 가상 환경에 설치된 sirius 패키지를 찾게 됩니다 ✨\n+$ python main.py\n+\n+못된 짓을 꾸미고 있음을 엄숙히 맹세합니다.🧙\n+ImportError는 이제 없습니다. 🐺\n+```\n+\n+
      \n+\n+## 대안들\n+\n+이 문서는 여러분이 Python 프로젝트를 시작하고, **그 내부에서** 어떻게 돌아가는지 알려주는 간단한 가이드입니다.\n+\n+가상 환경, 패키지 의존성(Requirements), 프로젝트를 관리하는 방법에는 이 외에도 다양한 **대안**들이 존재합니다.\n+\n+만약 준비가 되었다면, **프로젝트 전체**, 패키지 의존성, 가상 환경 등을 통합적으로 **관리**할 수 있는 도구를 써보는 것도 좋습니다. 그럴 때 추천하는 도구가 바로 uv입니다.\n+\n+`uv`는 다양한 기능을 지원합니다:\n+\n+* 다양한 버전의 **Python 설치**\n+* 각 프로젝트 별 **가상 환경 관리**\n+* **패키지 설치**\n+* 프로젝트의 **의존성과 버전** 관리\n+* 설치된 패키지들과 그 버전을 **정확히 고정(lock)**해서,개발 환경과 운영 환경이 완전히 동일하게 작동할 수 있도록 보장\n+* 이 외에도 다양한 기능을 지원\n+\n+## 결론\n+\n+여기까지 모두 읽고 이해했다면, 이제 많은 개발자들보다 가상 환경을 **훨씬 더 깊이 있게 이해**하게 되셨습니다. 🤓\n+\n+이런 세부적인 내용을 알고 있으면, 언젠가 복잡해 보이는 문제를 디버깅할 때 분명히 큰 도움이 될 것입니다. 이제는 **이 모든 것들이 내부에서 어떻게 작동하는지** 알고 있기 때문입니다. 😎" } ], "reviews": [ { "id": 2792779068, "user": "user_08f3ccdc57a3", "state": "COMMENTED", "body": "텍스트 양이 많아서 일단 여기서 한번 끊을게요!", "submitted_at": "2025-04-25T01:53:05+00:00" }, { "id": 2792843152, "user": "user_08f3ccdc57a3", "state": "COMMENTED", "body": null, "submitted_at": "2025-04-25T02:07:10+00:00" }, { "id": 2792847784, "user": "user_08f3ccdc57a3", "state": "COMMENTED", "body": null, "submitted_at": "2025-04-25T02:12:01+00:00" }, { "id": 2792875526, "user": "user_08f3ccdc57a3", "state": "COMMENTED", "body": null, "submitted_at": "2025-04-25T02:33:28+00:00" }, { "id": 2792878303, "user": "user_08f3ccdc57a3", "state": "CHANGES_REQUESTED", "body": null, "submitted_at": "2025-04-25T02:46:17+00:00" }, { "id": 2792953791, "user": "user_08f3ccdc57a3", "state": "CHANGES_REQUESTED", "body": null, "submitted_at": "2025-04-25T04:30:13+00:00" }, { "id": 2792994016, "user": "user_08f3ccdc57a3", "state": "COMMENTED", "body": null, "submitted_at": "2025-04-25T04:59:59+00:00" }, { "id": 2793032376, "user": "user_9012ae87551f", "state": "COMMENTED", "body": null, "submitted_at": "2025-04-25T05:30:56+00:00" }, { "id": 2793048806, "user": "user_9012ae87551f", "state": "COMMENTED", "body": null, "submitted_at": "2025-04-25T05:42:15+00:00" }, { "id": 2793408582, "user": "user_08f3ccdc57a3", "state": "COMMENTED", "body": null, "submitted_at": "2025-04-25T08:40:35+00:00" }, { "id": 2793477096, "user": "user_9012ae87551f", "state": "COMMENTED", "body": null, "submitted_at": "2025-04-25T09:06:34+00:00" }, { "id": 2793481534, "user": "user_9012ae87551f", "state": "COMMENTED", "body": null, "submitted_at": "2025-04-25T09:07:33+00:00" }, { "id": 2793495455, "user": "user_9012ae87551f", "state": "COMMENTED", "body": null, "submitted_at": "2025-04-25T09:11:24+00:00" }, { "id": 2793498142, "user": "user_9012ae87551f", "state": "COMMENTED", "body": null, "submitted_at": "2025-04-25T09:12:31+00:00" }, { "id": 2802102554, "user": "user_08f3ccdc57a3", "state": "COMMENTED", "body": null, "submitted_at": "2025-04-29T05:48:39+00:00" }, { "id": 2802107626, "user": "user_08f3ccdc57a3", "state": "CHANGES_REQUESTED", "body": "LGTM!! \ni left just 1 request comment for my mistake. 😅\nif you modify it, and I'll approve!\n\n잘해주셨습니다~~ \n제가 실수한 거에 대해서 코멘트 남겨뒀어요! ㅋㅋ ㅠㅠㅠ \n그거만 반영해주시면 approve 드릴게요~~ 고생하셨습니다!!!", "submitted_at": "2025-04-29T05:56:03+00:00" }, { "id": 2802201329, "user": "user_9012ae87551f", "state": "COMMENTED", "body": null, "submitted_at": "2025-04-29T06:35:04+00:00" }, { "id": 2802288769, "user": "user_08f3ccdc57a3", "state": "APPROVED", "body": null, "submitted_at": "2025-04-29T07:01:50+00:00" }, { "id": 2813506795, "user": "user_caad3e3c1c43", "state": "CHANGES_REQUESTED", "body": "```markdown\n/// warning | 경고\n```\n\n위와 같이 전체적으로 `| {한국어}` 주석이 필요할 것으로 보입니다 ㅎㅎ!\n\n그 외에는 잘 번역해 주셔서 감사드립니다 ㅎㅎ\n위 사항 수정 후 approve 하겠습니다.", "submitted_at": "2025-05-04T16:20:56+00:00" }, { "id": 2813783394, "user": "user_caad3e3c1c43", "state": "APPROVED", "body": null, "submitted_at": "2025-05-05T04:35:05+00:00" }, { "id": 2813795838, "user": "user_9012ae87551f", "state": "COMMENTED", "body": null, "submitted_at": "2025-05-05T04:50:54+00:00" }, { "id": 2827086494, "user": "user_08f3ccdc57a3", "state": "APPROVED", "body": null, "submitted_at": "2025-05-09T05:45:35+00:00" } ], "review_comments": [ { "id": 2059415320, "user": "user_08f3ccdc57a3", "body": "```suggestion\n이미 가상 환경에 대해 알고 있다면 이 섹션은 건너 뛰어도 괜찮습니다. 🤓\n```\nadded emoji from origianl docs", "path": "docs/ko/docs/virtual-environments.md", "line": null, "side": "RIGHT", "created_at": "2025-04-25T00:51:12+00:00" }, { "id": 2059415883, "user": "user_08f3ccdc57a3", "body": "```suggestion\n**가상 환경**은 몇몇 파일로 구성된 하나의 디렉터리입니다.\n```", "path": "docs/ko/docs/virtual-environments.md", "line": null, "side": "RIGHT", "created_at": "2025-04-25T00:52:19+00:00" }, { "id": 2059418124, "user": "user_08f3ccdc57a3", "body": "```suggestion\n보통은 사용자 홈 디렉터리 안에 `code`라는 디렉터리를 만듭니다.\n그리고 그 안에 프로젝트마다 하나씩 디렉터리를 생성합니다.\n```\n한국어번역에서는 1인칭, 2인칭은 생략하는 형태로 서술하는 것 같더라구요........... (다른 문서도 그런 느낌입니다. 읽어보시면.... 약간 자아를 없애고 문장을 심플하게 만든느낌.) \n2문장을 일부러 1문장으로, 더 길게 합칠 필요는 없어서 원래대로 나눴습니다.", "path": "docs/ko/docs/virtual-environments.md", "line": null, "side": "RIGHT", "created_at": "2025-04-25T00:55:36+00:00" }, { "id": 2059432052, "user": "user_08f3ccdc57a3", "body": "```suggestion\n**터미널을 새로 열고** 프로젝트 작업을 시작할 때는, **항상 이 작업을** 해주세요.\n```\n~마다,~마다가 \n두번 나와서 좀 어색해보이길래... 문장 추천드립니다.", "path": "docs/ko/docs/virtual-environments.md", "line": null, "side": "RIGHT", "created_at": "2025-04-25T01:24:01+00:00" }, { "id": 2059438136, "user": "user_08f3ccdc57a3", "body": "```suggestion\n**패키지 이름과 버전 정보를 파일에 정리해두는 것**(예: `requirements.txt` 또는 `pyproject.toml`)은 **(매우) 좋은 습관**입니다.\n```", "path": "docs/ko/docs/virtual-environments.md", "line": null, "side": "RIGHT", "created_at": "2025-04-25T01:35:13+00:00" }, { "id": 2059441904, "user": "user_08f3ccdc57a3", "body": "```suggestion\n이렇게 하면 이후에 `python` 명령어를 실행했을 때, 가상 환경의 Python이나 그 안에 설치된 패키지들을 사용하지 않게 됩니다.\n```", "path": "docs/ko/docs/virtual-environments.md", "line": null, "side": "RIGHT", "created_at": "2025-04-25T01:42:42+00:00" }, { "id": 2059445446, "user": "user_08f3ccdc57a3", "body": "```suggestion\n어느 시점이 되면, **서로 다른 패키지들**에 의존하는 여러 개의 프로그램을 작성하게 될 것입니다. 그리고 이들 중 일부는 **같은 패키지의 서로 다른 버전**을 필요로 할 수 있습니다. 😱\n```", "path": "docs/ko/docs/virtual-environments.md", "line": null, "side": "RIGHT", "created_at": "2025-04-25T01:49:04+00:00" }, { "id": 2059446646, "user": "user_08f3ccdc57a3", "body": "## en\n![image](https://github.com/[USER_REDACTED]nts/assets/95382d12-e2f9-433a-a4d7-28a38e62d60e)\n\n## ko\n![image](https://github.com/[USER_REDACTED]nts/assets/1e460eaa-1cc1-4626-8744-0bff37ef30fa)\n\nflow chart부분 문자 간격이 좀 다르네요? 🤔\n원인은 잘모르겠지만..", "path": "docs/ko/docs/virtual-environments.md", "line": 453, "side": "RIGHT", "created_at": "2025-04-25T01:50:55+00:00" }, { "id": 2059458107, "user": "user_08f3ccdc57a3", "body": "```suggestion\n그런데 나중에 `prisoner-of-azkaban`이라는 또 다른 프로젝트를 만들게 되었고, 이 프로젝트도 `harry` 패키지에 의존합니다. 그런데 이 프로젝트는 `harry`의 버전 `3`이 필요합니다.\n```", "path": "docs/ko/docs/virtual-environments.md", "line": null, "side": "RIGHT", "created_at": "2025-04-25T02:07:10+00:00" }, { "id": 2059461181, "user": "user_08f3ccdc57a3", "body": "```suggestion\n이제 문제가 발생합니다. (로컬 가상환경 대신)전역 환경에 패키지를 설치하게 되면, 어떤 버전의 harry를 설치할지를 선택해야 하기 때문입니다.\n```\n원본이랑 괄호 위치가 다르긴한데, \n한국인한테는 이게 좀더 강조적으로 읽힐 것 같아서, 바꿔서 제안드려요. (본인이 직접 소리내서 읽어보시고 판단부탁드립니다 )", "path": "docs/ko/docs/virtual-environments.md", "line": null, "side": "RIGHT", "created_at": "2025-04-25T02:12:01+00:00" }, { "id": 2059479307, "user": "user_08f3ccdc57a3", "body": "이 문장은 원문보다 의미가 더 잘 드러난 것 같아요.\n\n+) 근데 이런식으로 고치게되면, 문장이 좀... 의미가 점점 벗어날 때도 있어서, 🤔고민 좀 하셔야할 거 같아요.", "path": "docs/ko/docs/virtual-environments.md", "line": null, "side": "RIGHT", "created_at": "2025-04-25T02:33:28+00:00" }, { "id": 2059481149, "user": "user_08f3ccdc57a3", "body": "```suggestion\nThat means that the system would look for programs in:\n```\n여기는 번역이 안되어있네요?", "path": "docs/ko/docs/virtual-environments.md", "line": null, "side": "RIGHT", "created_at": "2025-04-25T02:37:01+00:00" }, { "id": 2059485058, "user": "user_08f3ccdc57a3", "body": "```suggestion\n하나의 가상 환경을 활성화한 상태에서 **다른 프로젝트로 이동**하면 문제가 발생할 수 있습니다.\n```\n여기도 원본 텍스트랑 의미가 좀 달라져서... 코멘트 드려요.\n나중에 원문이 바뀌면 따라가기 힘들기때문에.....한번 고민 부탁드립니다.", "path": "docs/ko/docs/virtual-environments.md", "line": null, "side": "RIGHT", "created_at": "2025-04-25T02:44:17+00:00" }, { "id": 2059534266, "user": "user_08f3ccdc57a3", "body": "```suggestion\n그런데 이제는 **다른 프로젝트**인 `prisoner-of-azkaban`을 작업하고 싶어졌습니다.\n```", "path": "docs/ko/docs/virtual-environments.md", "line": null, "side": "RIGHT", "created_at": "2025-04-25T04:16:33+00:00" }, { "id": 2059539006, "user": "user_08f3ccdc57a3", "body": "```suggestion\n이 문서는 여러분이 Python 프로젝트를 시작하고, *그 내부에서* 어떻게 돌아가는지 알려주는 간단한 가이드입니다.\n```", "path": "docs/ko/docs/virtual-environments.md", "line": null, "side": "RIGHT", "created_at": "2025-04-25T04:25:21+00:00" }, { "id": 2059541026, "user": "user_08f3ccdc57a3", "body": "```suggestion\n* 설치된 패키지들과 그 버전을 **정확히 고정(lock)**해서,\n 개발 중인 환경과 **운영 환경**이 완전히 동일하게 작동할 수 있도록 보장합니다\n```\n이 문장도 한국어 상으로는 완벽하지만 의미를 조금더 생각해보셨으면 좋겠습니다!", "path": "docs/ko/docs/virtual-environments.md", "line": null, "side": "RIGHT", "created_at": "2025-04-25T04:28:48+00:00" }, { "id": 2059541724, "user": "user_08f3ccdc57a3", "body": "```suggestion\n이러한 세부적인 내용을 알고 있는 것은, 언젠가 복잡해 보이는 문제를 디버깅할 때 분명히 큰 도움이 될 것입니다. 이제는 **이 모든 것들이 내부에서 어떻게 작동하는지** 알고 있기 때문입니다. 😎\n```", "path": "docs/ko/docs/virtual-environments.md", "line": null, "side": "RIGHT", "created_at": "2025-04-25T04:30:03+00:00" }, { "id": 2059559811, "user": "user_08f3ccdc57a3", "body": "[USER_REDACTED] 이 문서에서는 예시를 해리포터 1권 3권 얘기를 예시로 들고있는데요. \n혹시 이 문장도 이해 하셨나요? 🐺<- 이 emoji의 의미하구요", "path": "docs/ko/docs/virtual-environments.md", "line": null, "side": "RIGHT", "created_at": "2025-04-25T04:59:59+00:00" }, { "id": 2059585888, "user": "user_9012ae87551f", "body": "찾아보고 이해했는데, 녹여내기가 어렵네요 😂😂😂", "path": "docs/ko/docs/virtual-environments.md", "line": null, "side": "RIGHT", "created_at": "2025-04-25T05:30:56+00:00" }, { "id": 2059595808, "user": "user_9012ae87551f", "body": "원문이 바뀌는걸 생각하지 못했네요. 전체적으로 직역에 가깝게 바꿨습니다!", "path": "docs/ko/docs/virtual-environments.md", "line": null, "side": "RIGHT", "created_at": "2025-04-25T05:42:15+00:00" }, { "id": 2059819033, "user": "user_08f3ccdc57a3", "body": "저도 이거는 사실 번역을 해야할까 고민하긴했어요 context문제라 🤔ㅋㅋㅋㅋ 생각해보고 괜찮은 방법이 생각나면, 더 코멘트 드릴게요 !!", "path": "docs/ko/docs/virtual-environments.md", "line": null, "side": "RIGHT", "created_at": "2025-04-25T08:40:35+00:00" }, { "id": 2059858541, "user": "user_9012ae87551f", "body": "직역에 가깝게 변경했습니다!", "path": "docs/ko/docs/virtual-environments.md", "line": null, "side": "RIGHT", "created_at": "2025-04-25T09:06:34+00:00" }, { "id": 2059859898, "user": "user_9012ae87551f", "body": "혹시 한번에 의미가 오지 않을까봐, 해리포터 부분 번역 추가했습니다.", "path": "docs/ko/docs/virtual-environments.md", "line": null, "side": "RIGHT", "created_at": "2025-04-25T09:07:32+00:00" }, { "id": 2059866131, "user": "user_9012ae87551f", "body": "\"정확히 고정(lock) \" 이 부분이 어렵네요.. 일단 그대로 두고 밑에 내용은 수정했습니다.\n\n개발 중인 환경과 **운영 환경**이 완전히 동일하게 작동할 수 있도록 보장합니다\n-> 개발 환경과 운영 환경이 완전히 동일하게 작동할 수 있도록 보장", "path": "docs/ko/docs/virtual-environments.md", "line": null, "side": "RIGHT", "created_at": "2025-04-25T09:11:24+00:00" }, { "id": 2059867854, "user": "user_9012ae87551f", "body": "머글 입장에서 최선을 다해 노력했습니다..\n\n못된 짓을 꾸미고 있음을 엄숙히 맹세합니다.🧙\nImportError는 이제 없습니다. 🐺", "path": "docs/ko/docs/virtual-environments.md", "line": null, "side": "RIGHT", "created_at": "2025-04-25T09:12:31+00:00" }, { "id": 2065539713, "user": "user_08f3ccdc57a3", "body": "ㅋㅋㅋㅋ 고생하셨어요~ 한국은 영어 문화권이 아니다보니, 설명이 필요했는데 이정도면 충분한 것 같습니다", "path": "docs/ko/docs/virtual-environments.md", "line": null, "side": "RIGHT", "created_at": "2025-04-29T05:48:39+00:00" }, { "id": 2065543050, "user": "user_08f3ccdc57a3", "body": "```suggestion\n이 문서는 여러분이 Python 프로젝트를 시작하고, **그 내부에서** 어떻게 돌아가는지 알려주는 간단한 가이드입니다.\n```\nmy mistake..😅 \n* -> **로 바꿨어요 (italic -> bold)", "path": "docs/ko/docs/virtual-environments.md", "line": null, "side": "RIGHT", "created_at": "2025-04-29T05:52:30+00:00" }, { "id": 2065595204, "user": "user_9012ae87551f", "body": "감사합니다!!\n문서가 길어서 지쳤는데, 하나하나 읽고 코멘트 달아주셔서 힘을 얻었습니다.\n처음에는 뜻 전달 우선이었는데, 조언 주셔서 읽을 때 매끄러움을 생각할 수 있었어요!", "path": "docs/ko/docs/virtual-environments.md", "line": null, "side": "RIGHT", "created_at": "2025-04-29T06:35:04+00:00" }, { "id": 2072655642, "user": "user_caad3e3c1c43", "body": "```suggestion\n/// tip | 팁\n```", "path": "docs/ko/docs/virtual-environments.md", "line": null, "side": "RIGHT", "created_at": "2025-05-04T16:19:47+00:00" }, { "id": 2072839791, "user": "user_9012ae87551f", "body": "수정사항 반영했는데, 바로 approve 주셔서 감사합니다! 😊😊", "path": "docs/ko/docs/virtual-environments.md", "line": null, "side": "RIGHT", "created_at": "2025-05-05T04:50:54+00:00" } ], "meta": { "languages": [ "md" ], "touches_tests": false, "review_state_summary": { "COMMENTED": 15, "CHANGES_REQUESTED": 4, "APPROVED": 3 }, "meaningful_comment_count": 30, "has_approval": true, "has_changes_requested": true, "total_review_comments": 30 } } { "_id": "56a05c97606ed9fd", "_schema_version": "1.0", "_cleaned_at": "2026-02-12T07:46:51.749744+00:00", "repo": "tiangolo/fastapi", "repo_url": "https://github.com/fastapi/fastapi", "license_name": "MIT License", "license_spdx": "MIT", "pr_number": 13552, "title": "🌐 Add Russian translation for `docs/ru/docs/tutorial/request-form-models.md`", "body": "To ensure consistency across the documentation pages, this page uses some _abbreviations_ and _paraphrases_ in its translation. These minor changes relative to the English version were applied by [NAME_REDACTED] [Модели Query-Параметров](https://fastapi.tiangolo.com/ru/tutorial/query-param-models) page, which is similar in structure, and [Данные формы](https://fastapi.tiangolo.com/ru/tutorial/request-forms) page, which is similar in meaning.\n\nFor example, in the second article, the original contains the text «Make sure you create a virtual environment, activate it, and then install it, for example: pip install python-multipart», while the translated version is much shorter: «Например, выполните команду pip install python-multipart.». I adopted the shortened version for ease of reading multiple pages in a row.", "author": "user_56dbb7fb3649", "created_at": "2025-03-29T14:15:12+00:00", "merged_at": "2025-05-30T13:17:36+00:00", "base_branch": "master", "head_branch": "translate-ru-tutorial-request-form-models", "additions": 78, "deletions": 0, "changed_files": 1, "files": [ { "filename": "docs/ru/docs/tutorial/request-form-models.md", "status": "added", "additions": 78, "deletions": 0, "changes": 78, "patch": "@@ -0,0 +1,78 @@\n+# Модели форм\n+\n+Вы можете использовать **Pydantic-модели** для объявления **полей форм** в FastAPI.\n+\n+/// info | Дополнительная информация\n+\n+Чтобы использовать формы, сначала установите `python-multipart`.\n+\n+Убедитесь, что вы создали и активировали [виртуальное окружение](../virtual-environments.md){.internal-link target=_blank}, а затем установите пакет, например:\n+\n+```console\n+$ pip install python-multipart\n+```\n+\n+///\n+\n+/// note | Заметка\n+\n+Этот функционал доступен с версии `0.113.0`. 🤓\n+\n+///\n+\n+## Pydantic-модель для формы\n+\n+Вам просто нужно объявить **Pydantic-модель** с полями, которые вы хотите получить как **поля формы**, а затем объявить параметр как `Form`:\n+\n+{* ../../docs_src/request_form_models/tutorial001_an_py39.py hl[9:11,15] *}\n+\n+**FastAPI** **извлечёт** данные для **каждого поля** из **данных формы** в запросе и выдаст вам объявленную Pydantic-модель.\n+\n+## Проверка сгенерированной документации\n+\n+Вы можете посмотреть поля формы в графическом интерфейсе Документации по пути `/docs`:\n+\n+
      \n+\n+
      \n+\n+## Запрет дополнительных полей формы\n+\n+В некоторых случаях (не особо часто встречающихся) вам может понадобиться **ограничить** поля формы только теми, которые объявлены в Pydantic-модели. И **запретить** любые **дополнительные** поля.\n+\n+/// note | Заметка\n+\n+Этот функционал доступен с версии `0.114.0`. 🤓\n+\n+///\n+\n+Вы можете сконфигурировать Pydantic-модель так, чтобы запретить (`forbid`) все дополнительные (`extra`) поля:\n+\n+{* ../../docs_src/request_form_models/tutorial002_an_py39.py hl[12] *}\n+\n+Если клиент попробует отправить дополнительные данные, то в ответ он получит **ошибку**.\n+\n+Например, если клиент попытается отправить поля формы:\n+\n+* `username`: `Rick`\n+* `password`: `[NAME_REDACTED]`\n+* `extra`: `Mr. Poopybutthole`\n+\n+То в ответ он получит **ошибку**, сообщающую ему, что поле `extra` не разрешено:\n+\n+```json\n+{\n+ \"detail\": [\n+ {\n+ \"type\": \"extra_forbidden\",\n+ \"loc\": [\"body\", \"extra\"],\n+ \"msg\": \"Extra inputs are not permitted\",\n+ \"input\": \"Mr. Poopybutthole\"\n+ }\n+ ]\n+}\n+```\n+\n+## Заключение\n+\n+Вы можете использовать Pydantic-модели для объявления полей форм в FastAPI. 😎" } ], "reviews": [ { "id": 2730721227, "user": "user_6d7d83efab20", "state": "CHANGES_REQUESTED", "body": null, "submitted_at": "2025-03-31T23:33:37+00:00" }, { "id": 2732350522, "user": "user_56dbb7fb3649", "state": "COMMENTED", "body": null, "submitted_at": "2025-04-01T11:16:50+00:00" }, { "id": 2732350802, "user": "user_56dbb7fb3649", "state": "COMMENTED", "body": null, "submitted_at": "2025-04-01T11:16:57+00:00" }, { "id": 2734214956, "user": "user_6d7d83efab20", "state": "APPROVED", "body": null, "submitted_at": "2025-04-01T23:07:50+00:00" }, { "id": 2734229872, "user": "user_6d7d83efab20", "state": "COMMENTED", "body": null, "submitted_at": "2025-04-01T23:22:49+00:00" }, { "id": 2761286063, "user": "user_9e49ba0b4492", "state": "APPROVED", "body": null, "submitted_at": "2025-04-11T18:48:58+00:00" }, { "id": 2810029677, "user": "user_fd804cf40960", "state": "APPROVED", "body": null, "submitted_at": "2025-05-01T15:23:53+00:00" } ], "review_comments": [ { "id": 2021902103, "user": "user_6d7d83efab20", "body": "В оригинале не так, здесь нужно исправлять.", "path": "docs/ru/docs/tutorial/request-form-models.md", "line": null, "side": "RIGHT", "created_at": "2025-03-31T23:22:26+00:00" }, { "id": 2021908652, "user": "user_6d7d83efab20", "body": "Рекомендую придерживаться единого стиля при именовании заголовков. \n\nНапример,\n\n## Проверьте сгенерированную документацию\n## Запретите дополнительные поля формы\n\nили\n\n## Проверка сгенерированной документации\n## Запрет дополнительных полей формы", "path": "docs/ru/docs/tutorial/request-form-models.md", "line": null, "side": "RIGHT", "created_at": "2025-03-31T23:31:37+00:00" }, { "id": 2022654968, "user": "user_56dbb7fb3649", "body": "В изначальном комментарии к PR было представлено объяснение, почему я так сделал. Исправил, и, когда этот примут, планирую сделать другой PR на аналогичные изменение на странице [Данные формы](https://fastapi.tiangolo.com/ru/tutorial/request-forms) для единообразия Документации. Вообще, странно, что при ревью [тех](https://github.com/fastapi/fastapi/pull/9841) изменений не возникло вопросов к такому отклонению от оригинала.\n\n«virtual environment» перевёл как «виртуальное окружение», несмотря на то, что страница по ссылке называется «виртуальная среда»: первый вариант чаще употребляется в сообществе и более однозначный (по второму варианту Google выдаёт статьи по Python вперемешку со статьями по педагогике и системному администрированию).", "path": "docs/ru/docs/tutorial/request-form-models.md", "line": null, "side": "RIGHT", "created_at": "2025-04-01T11:16:49+00:00" }, { "id": 2022655178, "user": "user_56dbb7fb3649", "body": "Согласен, исправлено.", "path": "docs/ru/docs/tutorial/request-form-models.md", "line": null, "side": "RIGHT", "created_at": "2025-04-01T11:16:57+00:00" }, { "id": 2023796918, "user": "user_6d7d83efab20", "body": "> Исправил, и, когда этот примут, планирую сделать другой PR на аналогичные изменение на странице [Данные формы](https://fastapi.tiangolo.com/ru/tutorial/request-forms) для единообразия Документации\n\n[USER_REDACTED]: ждать совсем необязательно, можно сразу делать PR с внесением поправок", "path": "docs/ru/docs/tutorial/request-form-models.md", "line": null, "side": "RIGHT", "created_at": "2025-04-01T23:22:48+00:00" } ], "meta": { "languages": [ "md" ], "touches_tests": false, "review_state_summary": { "CHANGES_REQUESTED": 1, "COMMENTED": 3, "APPROVED": 3 }, "meaningful_comment_count": 5, "has_approval": true, "has_changes_requested": true, "total_review_comments": 5 } } { "_id": "02c6b792c7d472b1", "_schema_version": "1.0", "_cleaned_at": "2026-02-12T07:46:51.749744+00:00", "repo": "tiangolo/fastapi", "repo_url": "https://github.com/fastapi/fastapi", "license_name": "MIT License", "license_spdx": "MIT", "pr_number": 13537, "title": "🐛 Fix support for form values with empty strings interpreted as missing (`None` if that's the default), for compatibility with HTML forms", "body": "There was a bug in the validation of form data for optional params with None default value. This is a regression that was introduced by https://github.com/fastapi/fastapi/pull/12134.\n\n## Explaination:\nThe `_get_multidict_value` uses `None` to represent both the absence a value in the dict, and a default value of `None` for that field. When the values are collected in `_extract_form_body`, they are only added to the values if they are not `None`. Later (#12134), some code was added that attempted to complement the model values with values not explicitely in the model, if values for those fields were not already processed earlier. The issue is that since we didn't add values to the initial value dict if they were none, we attempted to add them again in that second iteration. This generally wasn't an issue, except for the fast that a form field set to the empty string (`\"\"`) is interpreted as the absence of that field. This resulted in `_get_multidict_value` picking the default value, that would happen to be `None`, so it wasn't added to the values dict in the first iteration. In the second iteration, we would find that value in the request params again, but set to `\"\"`, and add that to the initial value dict. Later, validation would choke on that empty string.\n\nThe fix is to keep track of already visited field, rather that relying on the content of the values dict to complement the missing field. Such thing was already done in `request_params_to_args` for example.\n\ncloses #13533", "author": "user_4f3705367e06", "created_at": "2025-03-25T14:48:10+00:00", "merged_at": "2025-12-02T04:39:56+00:00", "base_branch": "master", "head_branch": "adhoc/fix-handling-of-none-defaults-in-forms", "additions": 37, "deletions": 1, "changed_files": 2, "files": [ { "filename": "fastapi/dependencies/utils.py", "status": "modified", "additions": 2, "deletions": 1, "changes": 3, "patch": "@@ -902,8 +902,9 @@ async def process_fn(\n value = serialize_sequence_value(field=field, value=results)\n if value is not None:\n values[field.alias] = value\n+ field_aliases = {field.alias for field in body_fields}\n for key, value in received_body.items():\n- if key not in values:\n+ if key not in field_aliases:\n values[key] = value\n return values" }, { "filename": "tests/test_form_default.py", "status": "added", "additions": 35, "deletions": 0, "changes": 35, "patch": "@@ -0,0 +1,35 @@\n+from typing import Optional\n+\n+from fastapi import FastAPI, File, Form\n+from starlette.testclient import TestClient\n+from typing_extensions import Annotated\n+\n+app = FastAPI()\n+\n+\n+[USER_REDACTED].post(\"/urlencoded\")\n+async def post_url_encoded(age: Annotated[Optional[int], Form()] = None):\n+ return age\n+\n+\n+[USER_REDACTED].post(\"/multipart\")\n+async def post_multi_part(\n+ age: Annotated[Optional[int], Form()] = None,\n+ file: Annotated[Optional[bytes], File()] = None,\n+):\n+ return {\"file\": file, \"age\": age}\n+\n+\n+client = TestClient(app)\n+\n+\n+def test_form_default_url_encoded():\n+ response = client.post(\"/urlencoded\", data={\"age\": \"\"})\n+ assert response.status_code == 200\n+ assert response.text == \"null\"\n+\n+\n+def test_form_default_multi_part():\n+ response = client.post(\"/multipart\", data={\"age\": \"\"})\n+ assert response.status_code == 200\n+ assert response.json() == {\"file\": None, \"age\": None}" } ], "reviews": [ { "id": 2774149074, "user": "user_601ba3d351eb", "state": "APPROVED", "body": "I just ran this patch against my full test suite and I can confirm that it fixed all of my tests that had started failing when upgrading from `fastapi` version `0.111.0` to `0.115.12`.\n\nNice work, [USER_REDACTED]!", "submitted_at": "2025-04-16T23:53:15+00:00" }, { "id": 2819349778, "user": "user_bf6a5f9c8a04", "state": "COMMENTED", "body": null, "submitted_at": "2025-05-06T19:11:16+00:00" }, { "id": 2824355651, "user": "user_243e213d5a22", "state": "COMMENTED", "body": null, "submitted_at": "2025-05-08T09:02:21+00:00" }, { "id": 2824360623, "user": "user_243e213d5a22", "state": "APPROVED", "body": null, "submitted_at": "2025-05-08T09:04:19+00:00" }, { "id": 3396619199, "user": "user_a42c7a43156a", "state": "APPROVED", "body": null, "submitted_at": "2025-10-29T22:30:58+00:00" }, { "id": 3408836239, "user": "user_29e85f9a8e75", "state": "APPROVED", "body": "LGTM!\n\nI removed the `post_multi_part_file_first` test as it was unrelated to the current issue and that issue (that the order of `File` and `Form` matters) has already been fixed: https://github.com/fastapi/fastapi/pull/11194\n\n[USER_REDACTED], thanks you for your work and patience!", "submitted_at": "2025-11-02T15:22:00+00:00" }, { "id": 3528090279, "user": "user_2a237e38e06b", "state": "APPROVED", "body": "Sorry for the delay handling this, and thank you for the explanation and fix [USER_REDACTED]! 🙌 \n\nThanks for the help [USER_REDACTED]! 🍰 \n\n---\n\nI made a local quick example with an HTML form to confirm that browsers by [NAME_REDACTED] fields even if they are empty, and will send them with an empty string. That convinced me this fix is necessary.\n\n---\n\nThis will be available in FastAPI 0.123.2, released in the next few hours. 🎉", "submitted_at": "2025-12-02T04:36:14+00:00" } ], "review_comments": [ { "id": 2076095083, "user": "user_bf6a5f9c8a04", "body": "This looks odd to me.\nIf you pass a string to an integer field, I would expect a `4xx` error code.", "path": "tests/test_form_default.py", "line": null, "side": "RIGHT", "created_at": "2025-05-06T19:11:16+00:00" }, { "id": 2079233102, "user": "user_243e213d5a22", "body": "This is a form POST and empty numeric inputs would be submitted as empty strings. IMO it's reasonable that they are accepted and treated like *no value* (`None` / `null`) when the field is an optional integer.", "path": "tests/test_form_default.py", "line": null, "side": "RIGHT", "created_at": "2025-05-08T09:02:21+00:00" } ], "meta": { "languages": [ "py" ], "touches_tests": true, "review_state_summary": { "APPROVED": 5, "COMMENTED": 2 }, "meaningful_comment_count": 2, "has_approval": true, "has_changes_requested": false, "total_review_comments": 2 } } { "_id": "557bb552a05d1f18", "_schema_version": "1.0", "_cleaned_at": "2026-02-12T07:46:51.749744+00:00", "repo": "tiangolo/fastapi", "repo_url": "https://github.com/fastapi/fastapi", "license_name": "MIT License", "license_spdx": "MIT", "pr_number": 13526, "title": "🌐 Add Russian translation for `docs/ru/docs/tutorial/header-param-models.md`", "body": "Translate the page `[NAME_REDACTED]` to Russian. Took inspiration from translated `Модели Query-Параметров` :)", "author": "user_03032d3f2ba7", "created_at": "2025-03-22T18:33:56+00:00", "merged_at": "2025-03-31T08:20:29+00:00", "base_branch": "master", "head_branch": "translate-lang-ru-header-param-models", "additions": 72, "deletions": 0, "changed_files": 1, "files": [ { "filename": "docs/ru/docs/tutorial/header-param-models.md", "status": "added", "additions": 72, "deletions": 0, "changes": 72, "patch": "@@ -0,0 +1,72 @@\n+# Модели Header-параметров\n+\n+Если у вас есть группа связанных **header-параметров**, то вы можете объединить их в одну **Pydantic-модель**.\n+\n+Это позволит вам **переиспользовать модель** в **разных местах**, а также задать валидацию и метаданные сразу для всех параметров. 😎\n+\n+/// note | Заметка\n+\n+Этот функционал доступен в FastAPI начиная с версии `0.115.0`. 🤓\n+\n+///\n+\n+## Header-параметры в виде Pydantic-модели\n+\n+Объявите нужные **header-параметры** в **Pydantic-модели** и затем аннотируйте параметр как `Header`:\n+\n+{* ../../docs_src/header_param_models/tutorial001_an_py310.py hl[9:14,18] *}\n+\n+**FastAPI** **извлечёт** данные для **каждого поля** из **заголовков** запроса и выдаст заданную вами Pydantic-модель.\n+\n+## Проверьте документацию\n+\n+Вы можете посмотреть нужные header-параметры в графическом интерфейсе сгенерированной документации по пути `/docs`:\n+\n+
      \n+\n+
      \n+\n+## Как запретить дополнительные заголовки\n+\n+В некоторых случаях (не особо часто встречающихся) вам может понадобиться **ограничить** заголовки, которые вы хотите получать.\n+\n+Вы можете использовать возможности конфигурации Pydantic-модели для того, чтобы запретить (`forbid`) любые дополнительные (`extra`) поля:\n+\n+{* ../../docs_src/header_param_models/tutorial002_an_py310.py hl[10] *}\n+\n+Если клиент попробует отправить **дополнительные заголовки**, то в ответ он получит **ошибку**.\n+\n+Например, если клиент попытается отправить заголовок `tool` со значением `plumbus`, то в ответ он получит ошибку, сообщающую ему, что header-параметр `tool` не разрешен:\n+\n+```json\n+{\n+ \"detail\": [\n+ {\n+ \"type\": \"extra_forbidden\",\n+ \"loc\": [\"header\", \"tool\"],\n+ \"msg\": \"Extra inputs are not permitted\",\n+ \"input\": \"plumbus\",\n+ }\n+ ]\n+}\n+```\n+\n+## Как отключить автоматическое преобразование подчеркиваний\n+\n+Как и в случае с обычными заголовками, если у вас в именах параметров имеются символы подчеркивания, они **автоматически преобразовываются в дефис**.\n+\n+Например, если в коде есть header-параметр `save_data`, то ожидаемый HTTP-заголовок будет `save-data` и именно так он будет отображаться в документации.\n+\n+Если по каким-то причинам вам нужно отключить данное автоматическое преобразование, это можно сделать и для Pydantic-моделей для header-параметров.\n+\n+{* ../../docs_src/header_param_models/tutorial003_an_py310.py hl[19] *}\n+\n+/// warning | Внимание\n+\n+Перед тем как устанавливать для параметра `convert_underscores` значение `False`, имейте в виду, что некоторые HTTP-прокси и серверы не разрешают использовать заголовки с символами подчеркивания.\n+\n+///\n+\n+## Резюме\n+\n+Вы можете использовать **Pydantic-модели** для объявления **header-параметров** в **FastAPI**. 😎" } ], "reviews": [ { "id": 2708391965, "user": "user_6d7d83efab20", "state": "COMMENTED", "body": null, "submitted_at": "2025-03-22T23:02:52+00:00" }, { "id": 2708392428, "user": "user_6d7d83efab20", "state": "APPROVED", "body": null, "submitted_at": "2025-03-22T23:03:03+00:00" }, { "id": 2713244031, "user": "user_9e49ba0b4492", "state": "CHANGES_REQUESTED", "body": null, "submitted_at": "2025-03-25T11:22:26+00:00" }, { "id": 2713407258, "user": "user_9e49ba0b4492", "state": "COMMENTED", "body": null, "submitted_at": "2025-03-25T11:40:44+00:00" }, { "id": 2714744838, "user": "user_03032d3f2ba7", "state": "COMMENTED", "body": null, "submitted_at": "2025-03-25T18:10:22+00:00" }, { "id": 2714745900, "user": "user_03032d3f2ba7", "state": "COMMENTED", "body": null, "submitted_at": "2025-03-25T18:10:30+00:00" }, { "id": 2714748315, "user": "user_03032d3f2ba7", "state": "COMMENTED", "body": null, "submitted_at": "2025-03-25T18:10:55+00:00" }, { "id": 2714749513, "user": "user_03032d3f2ba7", "state": "COMMENTED", "body": null, "submitted_at": "2025-03-25T18:11:10+00:00" }, { "id": 2714750653, "user": "user_03032d3f2ba7", "state": "COMMENTED", "body": null, "submitted_at": "2025-03-25T18:11:27+00:00" }, { "id": 2714752857, "user": "user_03032d3f2ba7", "state": "COMMENTED", "body": null, "submitted_at": "2025-03-25T18:11:52+00:00" }, { "id": 2714877175, "user": "user_9e49ba0b4492", "state": "COMMENTED", "body": null, "submitted_at": "2025-03-25T18:56:43+00:00" }, { "id": 2714935083, "user": "user_9e49ba0b4492", "state": "COMMENTED", "body": null, "submitted_at": "2025-03-25T19:15:47+00:00" }, { "id": 2714945237, "user": "user_6d7d83efab20", "state": "COMMENTED", "body": null, "submitted_at": "2025-03-25T19:20:02+00:00" }, { "id": 2714949741, "user": "user_6d7d83efab20", "state": "COMMENTED", "body": null, "submitted_at": "2025-03-25T19:22:08+00:00" }, { "id": 2715002882, "user": "user_9e49ba0b4492", "state": "COMMENTED", "body": null, "submitted_at": "2025-03-25T19:47:45+00:00" }, { "id": 2715013025, "user": "user_03032d3f2ba7", "state": "COMMENTED", "body": null, "submitted_at": "2025-03-25T19:50:43+00:00" }, { "id": 2715019969, "user": "user_03032d3f2ba7", "state": "COMMENTED", "body": null, "submitted_at": "2025-03-25T19:52:55+00:00" }, { "id": 2715145144, "user": "user_9e49ba0b4492", "state": "APPROVED", "body": null, "submitted_at": "2025-03-25T20:44:01+00:00" } ], "review_comments": [ { "id": 2008967488, "user": "user_6d7d83efab20", "body": "```suggestion\nЭто позволит вам **переиспользовать модель** в **разных местах**, а также установить валидаторы и метаданные сразу для всех параметров. 😎\n```", "path": "docs/ru/docs/tutorial/header-param-models.md", "line": null, "side": "RIGHT", "created_at": "2025-03-22T22:58:19+00:00" }, { "id": 2008967599, "user": "user_6d7d83efab20", "body": "```suggestion\n**FastAPI** **извлечёт** данные для **каждого поля** из **заголовков** запроса и выдаст заданную вами Pydantic-модель.\n```", "path": "docs/ru/docs/tutorial/header-param-models.md", "line": null, "side": "RIGHT", "created_at": "2025-03-22T22:59:23+00:00" }, { "id": 2008967623, "user": "user_6d7d83efab20", "body": "```suggestion\n## Проверьте документацию\n```", "path": "docs/ru/docs/tutorial/header-param-models.md", "line": null, "side": "RIGHT", "created_at": "2025-03-22T22:59:51+00:00" }, { "id": 2008967706, "user": "user_6d7d83efab20", "body": "```suggestion\n## Запретите дополнительные заголовки\n```", "path": "docs/ru/docs/tutorial/header-param-models.md", "line": null, "side": "RIGHT", "created_at": "2025-03-22T23:00:25+00:00" }, { "id": 2011811617, "user": "user_9e49ba0b4492", "body": "Это позволит вам **переиспользовать модель** в **разных местах**, а также задать валидацию и метаданные сразу для всех параметров. 😎", "path": "docs/ru/docs/tutorial/header-param-models.md", "line": null, "side": "RIGHT", "created_at": "2025-03-25T10:41:44+00:00" }, { "id": 2011816801, "user": "user_9e49ba0b4492", "body": "## Header-параметры в виде Pydantic-модели", "path": "docs/ru/docs/tutorial/header-param-models.md", "line": null, "side": "RIGHT", "created_at": "2025-03-25T10:44:00+00:00" }, { "id": 2011830175, "user": "user_9e49ba0b4492", "body": "## Проверка документации", "path": "docs/ru/docs/tutorial/header-param-models.md", "line": 21, "side": "RIGHT", "created_at": "2025-03-25T10:52:01+00:00" }, { "id": 2011839847, "user": "user_9e49ba0b4492", "body": "## Запрет дополнительных заголовков", "path": "docs/ru/docs/tutorial/header-param-models.md", "line": null, "side": "RIGHT", "created_at": "2025-03-25T10:55:51+00:00" }, { "id": 2011878850, "user": "user_9e49ba0b4492", "body": "Перед тем как устанавливать для параметра `convert_underscores` значение `False`, имейте в виду, что некоторые HTTP-прокси и серверы запрещают использование заголовков с символами подчеркивания.", "path": "docs/ru/docs/tutorial/header-param-models.md", "line": 66, "side": "RIGHT", "created_at": "2025-03-25T11:19:34+00:00" }, { "id": 2011911089, "user": "user_9e49ba0b4492", "body": "Словосочетание \"**в некоторых случаях**\" уже несет в себе смысл \"не часто встречающиеся случаи\". Поэтому дальнейшее уточнение \"**(не особо часто встречающихся)**\" выглядит излишним.\nПредлагаю убрать это уточнение, несмотря на то, что в оригинале оно присутствует.", "path": "docs/ru/docs/tutorial/header-param-models.md", "line": 31, "side": "RIGHT", "created_at": "2025-03-25T11:40:44+00:00" }, { "id": 2012678903, "user": "user_03032d3f2ba7", "body": "С этим согласен", "path": "docs/ru/docs/tutorial/header-param-models.md", "line": null, "side": "RIGHT", "created_at": "2025-03-25T18:10:22+00:00" }, { "id": 2012679322, "user": "user_03032d3f2ba7", "body": "С этим согласен", "path": "docs/ru/docs/tutorial/header-param-models.md", "line": null, "side": "RIGHT", "created_at": "2025-03-25T18:10:30+00:00" }, { "id": 2012680806, "user": "user_03032d3f2ba7", "body": "С этой правкой я бы не согласился. Во-первых, в оригинале \"check the docs\" - это явно глагол, то есть \"проверьте\". Во-вторых, \"проверка\" - это для русского языка эквивалент \"тестирование\", \"обследование\", а в данном случае в оригинале другой смысл, который сводится к тому, что \"пойдите посмотрите сгенерированную документацию, там отобразилась моделька, которую вы сделали\" :smile: Поэтому я бы оставил \"проверьте\".", "path": "docs/ru/docs/tutorial/header-param-models.md", "line": 21, "side": "RIGHT", "created_at": "2025-03-25T18:10:55+00:00" }, { "id": 2012681583, "user": "user_03032d3f2ba7", "body": "Опять же, я считаю ,что здесь нужен глагол, потому что по стилю документации и по смыслу мы \"**создаем** модель\", \"**смотрим** доки\", \"**отключаем** преобразование в дефисы и т.д. Поэтому предлагаю оставить \"Запретите\".", "path": "docs/ru/docs/tutorial/header-param-models.md", "line": null, "side": "RIGHT", "created_at": "2025-03-25T18:11:09+00:00" }, { "id": 2012682322, "user": "user_03032d3f2ba7", "body": "Здесь я бы не согласился с правкой. \"Запрещать\" - это prohibit, forbid. А disallow - это скорее \"отвергать\", \"отклонять\", \"не разрешать\", что как раз согласуется с поведением серверов. Сервера не запрещают полученные заголовки, а отвергают в зависимости от настроек :smile:", "path": "docs/ru/docs/tutorial/header-param-models.md", "line": 66, "side": "RIGHT", "created_at": "2025-03-25T18:11:27+00:00" }, { "id": 2012683519, "user": "user_03032d3f2ba7", "body": "Ришат, мне не показалось, что уточнение \"не особо часто встречающихся\" здесь будет излишним. Некоторые случаи здесь - это не частота появления таких случаев, а их особенность. Автор не зря добавил это учтонение, чтобы подчеркнуть, что такая настройка скорее всего вам не нужна. Ну и вроде у нас нет цели сократить текст перевода и сэкономить символы, поэтому я бы оставил, чтобы соответствовать оригиналу :smiley:", "path": "docs/ru/docs/tutorial/header-param-models.md", "line": 31, "side": "RIGHT", "created_at": "2025-03-25T18:11:52+00:00" }, { "id": 2012758546, "user": "user_9e49ba0b4492", "body": "Я подумал, что в ру переводе до сих пор не было повелительного наклонения в заголовках. Предложил эту правку исходя из этого соображения. Но оказалось, что заголовки с повелительным наклонением уже присутствуют в переводах.\nС вашей аргументацией согласен.", "path": "docs/ru/docs/tutorial/header-param-models.md", "line": 21, "side": "RIGHT", "created_at": "2025-03-25T18:56:43+00:00" }, { "id": 2012790117, "user": "user_9e49ba0b4492", "body": "В данном случае, не совсем согласен, т.к. \"Запретите дополнительные заголовки\" звучит как шаг, который нужно сделать далее. А \"Запрет дополнительных заголовков\" будет звучать, как шаг, который можно сделать при необходимости.", "path": "docs/ru/docs/tutorial/header-param-models.md", "line": null, "side": "RIGHT", "created_at": "2025-03-25T19:15:47+00:00" }, { "id": 2012795246, "user": "user_6d7d83efab20", "body": "## Pydantic-модели для заголовков", "path": "docs/ru/docs/tutorial/header-param-models.md", "line": null, "side": "RIGHT", "created_at": "2025-03-25T19:20:02+00:00" }, { "id": 2012797736, "user": "user_6d7d83efab20", "body": "## Как запретить дополнительные загловки?\n\n## Как отключить автоматическое преобразование подчеркиваний?", "path": "docs/ru/docs/tutorial/header-param-models.md", "line": null, "side": "RIGHT", "created_at": "2025-03-25T19:22:08+00:00" }, { "id": 2012829285, "user": "user_9e49ba0b4492", "body": "[USER_REDACTED] , да, согласен. Как раз оба будут в одинаковом стиле.", "path": "docs/ru/docs/tutorial/header-param-models.md", "line": null, "side": "RIGHT", "created_at": "2025-03-25T19:47:45+00:00" }, { "id": 2012836098, "user": "user_03032d3f2ba7", "body": "[USER_REDACTED] В оригинале именно [NAME_REDACTED], поэтому тут я предлагаю придерживаться почти дословного перевода для точности и оставить \"header-параметры\".", "path": "docs/ru/docs/tutorial/header-param-models.md", "line": null, "side": "RIGHT", "created_at": "2025-03-25T19:50:43+00:00" }, { "id": 2012840703, "user": "user_03032d3f2ba7", "body": "Кстати, да, звучит как шаг, согласен. \nМне нравится вариант, который предлагает [USER_REDACTED] , но только я бы не ставил вопросительные знаки \"Как запретить дополнительные заголовки\".", "path": "docs/ru/docs/tutorial/header-param-models.md", "line": null, "side": "RIGHT", "created_at": "2025-03-25T19:52:54+00:00" } ], "meta": { "languages": [ "md" ], "touches_tests": false, "review_state_summary": { "COMMENTED": 15, "APPROVED": 2, "CHANGES_REQUESTED": 1 }, "meaningful_comment_count": 23, "has_approval": true, "has_changes_requested": true, "total_review_comments": 23 } } { "_id": "e1937bbd9a1b6723", "_schema_version": "1.0", "_cleaned_at": "2026-02-12T07:46:51.749744+00:00", "repo": "tiangolo/fastapi", "repo_url": "https://github.com/fastapi/fastapi", "license_name": "MIT License", "license_spdx": "MIT", "pr_number": 13505, "title": "✅ Simplify tests for `settings`", "body": "#13150", "author": "user_c36c155012b4", "created_at": "2025-03-20T03:14:39+00:00", "merged_at": "2025-06-17T10:25:20+00:00", "base_branch": "master", "head_branch": "simplify-tests-for-settings-tutorial", "additions": 16, "deletions": 23, "changed_files": 2, "files": [ { "filename": "tests/test_tutorial/test_settings/test_tutorial001.py", "status": "modified", "additions": 16, "deletions": 4, "changes": 20, "patch": "@@ -1,14 +1,26 @@\n+import importlib\n+\n+import pytest\n from fastapi.testclient import TestClient\n from pytest import MonkeyPatch\n \n-from ...utils import needs_pydanticv2\n+from ...utils import needs_pydanticv1, needs_pydanticv2\n \n \n-[USER_REDACTED]_pydanticv2\n-def test_settings(monkeypatch: MonkeyPatch):\n+[USER_REDACTED].fixture(\n+ name=\"app\",\n+ params=[\n+ pytest.param(\"tutorial001\", marks=needs_pydanticv2),\n+ pytest.param(\"tutorial001_pv1\", marks=needs_pydanticv1),\n+ ],\n+)\n+def get_app(request: pytest.FixtureRequest, monkeypatch: MonkeyPatch):\n monkeypatch.setenv(\"ADMIN_EMAIL\", \"[EMAIL_REDACTED]\")\n- from docs_src.settings.tutorial001 import app\n+ mod = importlib.import_module(f\"docs_src.settings.{request.param}\")\n+ return mod.app\n+\n \n+def test_settings(app):\n client = TestClient(app)\n response = client.get(\"/info\")\n assert response.status_code == 200, response.text" }, { "filename": "tests/test_tutorial/test_settings/test_tutorial001_pv1.py", "status": "removed", "additions": 0, "deletions": 19, "changes": 19, "patch": "@@ -1,19 +0,0 @@\n-from fastapi.testclient import TestClient\n-from pytest import MonkeyPatch\n-\n-from ...utils import needs_pydanticv1\n-\n-\n-[USER_REDACTED]_pydanticv1\n-def test_settings(monkeypatch: MonkeyPatch):\n- monkeypatch.setenv(\"ADMIN_EMAIL\", \"[EMAIL_REDACTED]\")\n- from docs_src.settings.tutorial001_pv1 import app\n-\n- client = TestClient(app)\n- response = client.get(\"/info\")\n- assert response.status_code == 200, response.text\n- assert response.json() == {\n- \"app_name\": \"Awesome API\",\n- \"admin_email\": \"[EMAIL_REDACTED]\",\n- \"items_per_user\": 50,\n- }" } ], "reviews": [ { "id": 2702426640, "user": "user_6d7d83efab20", "state": "COMMENTED", "body": null, "submitted_at": "2025-03-20T12:05:13+00:00" }, { "id": 2702577751, "user": "user_c36c155012b4", "state": "COMMENTED", "body": null, "submitted_at": "2025-03-20T12:45:34+00:00" }, { "id": 2702589033, "user": "user_6d7d83efab20", "state": "APPROVED", "body": null, "submitted_at": "2025-03-20T12:48:37+00:00" }, { "id": 2931931591, "user": "user_29e85f9a8e75", "state": "APPROVED", "body": "LGTM", "submitted_at": "2025-06-16T12:24:01+00:00" }, { "id": 2935083418, "user": "user_2a237e38e06b", "state": "APPROVED", "body": "Awesome, thank you! 🚀 ☕", "submitted_at": "2025-06-17T10:25:04+00:00" } ], "review_comments": [ { "id": 2005481524, "user": "user_6d7d83efab20", "body": "I think that it is better to monkeypatch `get_app()`, instead of test_settings:\n\n```python\n\n[USER_REDACTED].fixture(\n name=\"app\",\n params=[\n pytest.param(\"tutorial001\", marks=needs_pydanticv2),\n pytest.param(\"tutorial001_pv1\", marks=needs_pydanticv1),\n ],\n)\ndef get_app(request: pytest.FixtureRequest, monkeypatch: MonkeyPatch):\n monkeypatch.setenv(\"ADMIN_EMAIL\", \"[EMAIL_REDACTED]\")\n mod = importlib.import_module(f\"docs_src.settings.{request.param}\")\n return mod.app\n\ndef test_settings(app):\n client = TestClient(app)\n response = client.get(\"/info\")\n assert response.status_code == 200, response.text\n assert response.json() == {\n \"app_name\": \"Awesome API\",\n \"admin_email\": \"[EMAIL_REDACTED]\",\n \"items_per_user\": 50,\n }\n\n```", "path": "tests/test_tutorial/test_settings/test_tutorial001.py", "line": null, "side": "RIGHT", "created_at": "2025-03-20T12:05:13+00:00" }, { "id": 2005560949, "user": "user_c36c155012b4", "body": "agree, fixed", "path": "tests/test_tutorial/test_settings/test_tutorial001.py", "line": null, "side": "RIGHT", "created_at": "2025-03-20T12:45:34+00:00" } ], "meta": { "languages": [ "py" ], "touches_tests": true, "review_state_summary": { "COMMENTED": 2, "APPROVED": 3 }, "meaningful_comment_count": 2, "has_approval": true, "has_changes_requested": false, "total_review_comments": 2 } } { "_id": "52a3e7edaeef81ff", "_schema_version": "1.0", "_cleaned_at": "2026-02-12T07:46:51.749744+00:00", "repo": "tiangolo/fastapi", "repo_url": "https://github.com/fastapi/fastapi", "license_name": "MIT License", "license_spdx": "MIT", "pr_number": 13487, "title": "🌐 Update Korean translation for `docs/ko/docs/advanced/events.md`", "body": "Hello!\n\nI encountered that the document of `Lifespan` was not translated in Korean. \nSo I translated the English document to Korean.\n\n**Korean ver** : https://fastapi.tiangolo.com/ko/advanced/events/ -> To be changed\n**English ver**: https://fastapi.tiangolo.com/advanced/events/ -> [NAME_REDACTED] this is my first PR to FastAPI, I would greatly appreciate any feedback 🙇‍♀️", "author": "user_3dd9ee4bad15", "created_at": "2025-03-14T13:06:37+00:00", "merged_at": "2025-05-30T13:33:53+00:00", "base_branch": "master", "head_branch": "master", "additions": 129, "deletions": 17, "changed_files": 1, "files": [ { "filename": "docs/ko/docs/advanced/events.md", "status": "modified", "additions": 129, "deletions": 17, "changes": 146, "patch": "@@ -1,53 +1,165 @@\n-# 이벤트: startup과 shutdown\n+# Lifespan 이벤트\n \n-필요에 따라 응용 프로그램이 시작되기 전이나 종료될 때 실행되는 이벤트 핸들러(함수)를 정의할 수 있습니다.\n+애플리케이션 **시작 전**에 실행되어야 하는 로직(코드)을 정의할 수 있습니다. 이는 이 코드가 **한 번**만 실행되며, **애플리케이션이 요청을 받기 시작하기 전**에 실행된다는 의미입니다.\n \n-이 함수들은 `async def` 또는 평범하게 `def`으로 선언할 수 있습니다.\n+마찬가지로, 애플리케이션이 **종료될 때** 실행되어야 하는 로직(코드)을 정의할 수 있습니다. 이 경우, 이 코드는 **한 번**만 실행되며, **여러 요청을 처리한 후**에 실행됩니다.\n+\n+이 코드가 애플리케이션이 **요청을 받기 시작하기 전에** 실행되고, 요청 처리가 끝난 후 **종료 직전에** 실행되기 때문에 전체 애플리케이션의 **수명(Lifespan)**을 다룹니다. (잠시 후 \"수명\"이라는 단어가 중요해집니다 😉)\n+\n+이 방법은 전체 애플리케이션에서 사용해야 하는 **자원**을 설정하거나 요청 간에 **공유되는** 자원을 설정하고, 또는 그 후에 **정리**하는 데 매우 유용할 수 있습니다. 예를 들어, 데이터베이스 연결 풀 또는 공유되는 머신러닝 모델을 로드하는 경우입니다.\n+\n+\n+## 사용 사례\n+\n+먼저 **사용 사례**를 예로 들어보고, 이를 어떻게 해결할 수 있는지 살펴보겠습니다.\n+\n+우리가 요청을 처리하기 위해 사용하고 싶은 **머신러닝 모델**이 있다고 상상해 봅시다. 🤖\n+\n+이 모델들은 요청 간에 공유되므로, 요청마다 모델이 하나씩 있는 것이 아니라, 여러 요청에서 동일한 모델을 사용합니다.\n+\n+모델을 로드하는 데 **상당한 시간이 걸린다고 상상해 봅시다**, 왜냐하면 모델이 **디스크에서 많은 데이터를 읽어야** 하기 때문입니다. 따라서 모든 요청에 대해 모델을 매번 로드하고 싶지 않습니다.\n+\n+모듈/파일의 최상위에서 모델을 로드할 수도 있지만, 그러면 **모델을 로드하는데** 시간이 걸리기 때문에, 단순한 자동화된 테스트를 실행할 때도 모델이 로드될 때까지 기다려야 해서 **테스트 속도가 느려집니다**.\n+\n+이 문제를 해결하려고 하는 것입니다. 요청을 처리하기 전에 모델을 로드하되, 애플리케이션이 요청을 받기 시작하기 직전에만 로드하고, 코드가 로드되는 동안은 로드하지 않도록 하겠습니다.\n+\n+## Lifespan\n+\n+`FastAPI` 애플리케이션의 `lifespan` 매개변수와 \"컨텍스트 매니저\"를 사용하여 *시작*과 *종료* 로직을 정의할 수 있습니다. (컨텍스트 매니저가 무엇인지 잠시 후에 설명드리겠습니다.)\n+\n+예제를 통해 시작하고, 그 후에 자세히 살펴보겠습니다.\n+\n+우리는 `yield`를 사용하여 비동기 함수 `lifespan()`을 다음과 같이 생성합니다:\n+\n+{* ../../docs_src/events/tutorial003.py hl[16,19] *}\n+\n+여기서 우리는 모델을 로드하는 비싼 *시작* 작업을 시뮬레이션하고 있습니다. `yield` 앞에서 (가짜) 모델 함수를 머신러닝 모델이 담긴 딕셔너리에 넣습니다. 이 코드는 **애플리케이션이 요청을 받기 시작하기 전**, *시작* 동안에 실행됩니다.\n+\n+그리고 `yield` 직후에는 모델을 언로드합니다. 이 코드는 **애플리케이션이 요청 처리 완료 후**, *종료* 직전에 실행됩니다. 예를 들어, 메모리나 GPU와 같은 자원을 해제하는 작업을 할 수 있습니다.\n+\n+/// tip | 팁\n+\n+`shutdown`은 애플리케이션을 **종료**할 때 발생합니다.\n+\n+새로운 버전을 시작해야 하거나, 그냥 실행을 멈추고 싶을 수도 있습니다. 🤷\n+\n+///\n+\n+### Lifespan 함수\n+\n+먼저 주목할 점은, `yield`를 사용하여 비동기 함수(async function)를 정의하고 있다는 것입니다. 이는 `yield`를 사용한 의존성과 매우 유사합니다.\n+\n+{* ../../docs_src/events/tutorial003.py hl[14:19] *}\n+\n+함수의 첫 번째 부분, 즉 `yield` 이전의 코드는 애플리케이션이 시작되기 **전에** 실행됩니다.\n+\n+그리고 `yield` 이후의 부분은 애플리케이션이 완료된 후 **나중에** 실행됩니다.\n+\n+### 비동기 컨텍스트 매니저\n+\n+함수를 확인해보면, `[USER_REDACTED]`로 장식되어 있습니다.\n+\n+이것은 함수를 \"**비동기 컨텍스트 매니저**\"라고 불리는 것으로 변환시킵니다.\n+\n+{* ../../docs_src/events/tutorial003.py hl[1,13] *}\n+\n+파이썬에서 **컨텍스트 매니저**는 `with` 문에서 사용할 수 있는 것입니다. 예를 들어, `open()`은 컨텍스트 매니저로 사용할 수 있습니다:\n+\n+```Python\n+with open(\"file.txt\") as file:\n+ file.read()\n+```\n+최근 버전의 파이썬에서는 **비동기 컨텍스트 매니저**도 있습니다. 이를 `async with`와 함께 사용합니다:\n+\n+```Python\n+async with lifespan(app):\n+ await do_stuff()\n+```\n+\n+컨텍스트 매니저나 위와 같은 비동기 컨텍스트 매니저를 만들면, `with` 블록에 들어가기 전에 `yield` 이전의 코드가 실행되고, `with` 블록을 벗어난 후에는 `yield` 이후의 코드가 실행됩니다.\n+\n+위의 코드 예제에서는 직접 사용하지 않고, FastAPI에 전달하여 사용하도록 합니다.\n+\n+`FastAPI` 애플리케이션의 `lifespan` 매개변수는 **비동기 컨텍스트 매니저**를 받기 때문에, 새로운 `lifespan` 비동기 컨텍스트 매니저를 FastAPI에 전달할 수 있습니다.\n+\n+{* ../../docs_src/events/tutorial003.py hl[22] *}\n+\n+## 대체 이벤트 (사용 중단)\n \n /// warning | 경고\n \n-이벤트 핸들러는 주 응용 프로그램에서만 작동합니다. [하위 응용 프로그램 - 마운트](./sub-applications.md){.internal-link target=_blank}에서는 작동하지 않습니다.\n+*시작*과 *종료*를 처리하는 권장 방법은 위에서 설명한 대로 `FastAPI` 애플리케이션의 `lifespan` 매개변수를 사용하는 것입니다. `lifespan` 매개변수를 제공하면 `startup`과 `shutdown` 이벤트 핸들러는 더 이상 호출되지 않습니다. `lifespan`을 사용할지, 모든 이벤트를 사용할지 선택해야 하며 둘 다 사용할 수는 없습니다.\n+\n+이 부분은 건너뛰셔도 좋습니다.\n \n ///\n \n-## `startup` 이벤트\n+*시작*과 *종료* 동안 실행될 이 로직을 정의하는 대체 방법이 있습니다.\n+\n+애플리케이션이 시작되기 전에 또는 종료될 때 실행해야 하는 이벤트 핸들러(함수)를 정의할 수 있습니다.\n \n-응용 프로그램을 시작하기 전에 실행하려는 함수를 \"startup\" 이벤트로 선언합니다:\n+이 함수들은 `async def` 또는 일반 `def`로 선언할 수 있습니다.\n+\n+### `startup` 이벤트\n+\n+애플리케이션이 시작되기 전에 실행되어야 하는 함수를 추가하려면, `\"startup\"` 이벤트로 선언합니다:\n \n {* ../../docs_src/events/tutorial001.py hl[8] *}\n \n-이 경우 `startup` 이벤트 핸들러 함수는 단순히 몇 가지 값으로 구성된 `dict` 형식의 \"데이터베이스\"를 초기화합니다.\n+이 경우, `startup` 이벤트 핸들러 함수는 \"database\"라는 항목(단지 `dict`)을 일부 값으로 초기화합니다.\n \n-하나 이상의 이벤트 핸들러 함수를 추가할 수도 있습니다.\n+여러 개의 이벤트 핸들러 함수를 추가할 수 있습니다.\n \n-그리고 응용 프로그램은 모든 `startup` 이벤트 핸들러가 완료될 때까지 요청을 받지 않습니다.\n+애플리케이션은 모든 `startup` 이벤트 핸들러가 완료될 때까지 요청을 받기 시작하지 않습니다.\n \n-## `shutdown` 이벤트\n+### `shutdown` 이벤트\n \n-응용 프로그램이 종료될 때 실행하려는 함수를 추가하려면 `\"shutdown\"` 이벤트로 선언합니다:\n+애플리케이션이 종료될 때 실행되어야 하는 함수를 추가하려면, `\"shutdown\"` 이벤트로 선언합니다:\n \n {* ../../docs_src/events/tutorial002.py hl[6] *}\n \n-이 예제에서 `shutdown` 이벤트 핸들러 함수는 `\"Application shutdown\"`이라는 텍스트가 적힌 `log.txt` 파일을 추가할 것입니다.\n+여기서, `shutdown` 이벤트 핸들러 함수는 `\"Application shutdown\"`이라는 텍스트를 `log.txt` 파일에 기록합니다.\n \n /// info | 정보\n \n-`open()` 함수에서 `mode=\"a\"`는 \"추가\"를 의미합니다. 따라서 이미 존재하는 파일의 내용을 덮어쓰지 않고 새로운 줄을 추가합니다.\n+`open()` 함수에서 `mode=\"a\"`는 \"추가\"를 의미하므로, 파일에 있는 기존 내용은 덮어쓰지 않고 새로운 줄이 추가됩니다.\n \n ///\n \n /// tip | 팁\n \n-이 예제에서는 파일과 상호작용 하기 위해 파이썬 표준 함수인 `open()`을 사용하고 있습니다.\n+이 경우, 우리는 표준 파이썬 `open()` 함수를 사용하여 파일과 상호작용하고 있습니다.\n \n-따라서 디스크에 데이터를 쓰기 위해 \"대기\"가 필요한 I/O (입력/출력) 작업을 수행합니다.\n+따라서 I/O(입출력) 작업이 포함되어 있어 디스크에 기록되는 것을 \"기다리는\" 과정이 필요합니다.\n \n-그러나 `open()`은 `async`와 `await`을 사용하지 않기 때문에 이벤트 핸들러 함수는 `async def`가 아닌 표준 `def`로 선언하고 있습니다.\n+하지만 `open()`은 `async`와 `await`를 사용하지 않습니다.\n+\n+그래서 우리는 이벤트 핸들러 함수를 `async def` 대신 일반 `def`로 선언합니다.\n \n ///\n \n+### `startup`과 `shutdown`을 함께 사용\n+\n+*시작*과 *종료* 로직이 연결될 가능성이 높습니다. 예를 들어, 무언가를 시작한 후 끝내거나, 자원을 획득한 후 해제하는 등의 작업을 할 수 있습니다.\n+\n+이러한 작업을 별도의 함수로 처리하면 서로 로직이나 변수를 공유하지 않기 때문에 더 어려워집니다. 값들을 전역 변수에 저장하거나 비슷한 트릭을 사용해야 할 수 있습니다.\n+\n+그렇기 때문에 위에서 설명한 대로 `lifespan`을 사용하는 것이 권장됩니다.\n+\n+## 기술적 세부사항\n+\n+호기심 많은 분들을 위한 기술적인 세부사항입니다. 🤓\n+\n+ASGI 기술 사양에 따르면, 이는 [NAME_REDACTED]의 일부이며, `startup`과 `shutdown`이라는 이벤트를 정의합니다.\n+\n /// info | 정보\n \n-이벤트 핸들러에 관한 내용은 Starlette 이벤트 문서에서 추가로 확인할 수 있습니다.\n+Starlette의 `lifespan` 핸들러에 대해 더 읽고 싶다면 Starlette의 Lifespan 문서에서 확인할 수 있습니다.\n+\n+이 문서에는 코드의 다른 영역에서 사용할 수 있는 lifespan 상태를 처리하는 방법도 포함되어 있습니다.\n \n ///\n+\n+## 서브 애플리케이션\n+\n+🚨 이 lifespan 이벤트(`startup`과 `shutdown`)는 메인 애플리케이션에 대해서만 실행되며, [서브 애플리케이션 - Mounts](sub-applications.md){.internal-link target=_blank}에는 실행되지 않음을 유의하세요." } ], "reviews": [ { "id": 2693397138, "user": "user_caad3e3c1c43", "state": "CHANGES_REQUESTED", "body": "`///` 블럭이 깨져서 수정 요청 드립니다!", "submitted_at": "2025-03-18T14:28:00+00:00" }, { "id": 2698350876, "user": "user_caad3e3c1c43", "state": "APPROVED", "body": null, "submitted_at": "2025-03-19T13:03:31+00:00" }, { "id": 2753134660, "user": "user_966965408b28", "state": "APPROVED", "body": null, "submitted_at": "2025-04-09T11:24:52+00:00" } ], "review_comments": [ { "id": 2000434658, "user": "user_caad3e3c1c43", "body": "```suggestion\n/// tip | 팁\n```", "path": "docs/ko/docs/advanced/events.md", "line": null, "side": "RIGHT", "created_at": "2025-03-18T08:10:55+00:00" }, { "id": 2000435748, "user": "user_caad3e3c1c43", "body": "```suggestion\n/// tip | 팁\n```", "path": "docs/ko/docs/advanced/events.md", "line": null, "side": "RIGHT", "created_at": "2025-03-18T08:11:39+00:00" }, { "id": 2000436534, "user": "user_caad3e3c1c43", "body": "```suggestion\n/// info | 정보\n```", "path": "docs/ko/docs/advanced/events.md", "line": null, "side": "RIGHT", "created_at": "2025-03-18T08:12:06+00:00" }, { "id": 2000436817, "user": "user_caad3e3c1c43", "body": "```suggestion\n/// info | 정보\n```", "path": "docs/ko/docs/advanced/events.md", "line": null, "side": "RIGHT", "created_at": "2025-03-18T08:12:19+00:00" }, { "id": 2000437671, "user": "user_caad3e3c1c43", "body": "```suggestion\n/// warning | 경고\n```", "path": "docs/ko/docs/advanced/events.md", "line": null, "side": "RIGHT", "created_at": "2025-03-18T08:12:58+00:00" } ], "meta": { "languages": [ "md" ], "touches_tests": false, "review_state_summary": { "CHANGES_REQUESTED": 1, "APPROVED": 2 }, "meaningful_comment_count": 5, "has_approval": true, "has_changes_requested": true, "total_review_comments": 5 } } { "_id": "f0853fdd0759d721", "_schema_version": "1.0", "_cleaned_at": "2026-02-12T07:46:51.749744+00:00", "repo": "tiangolo/fastapi", "repo_url": "https://github.com/fastapi/fastapi", "license_name": "MIT License", "license_spdx": "MIT", "pr_number": 13459, "title": "🌐 Add Ukrainian translation for `docs/uk/docs/tutorial/metadata.md` page", "body": null, "author": "user_c36c155012b4", "created_at": "2025-03-06T04:37:32+00:00", "merged_at": "2025-03-19T17:09:57+00:00", "base_branch": "master", "head_branch": "translation-uk/metadata", "additions": 120, "deletions": 0, "changed_files": 1, "files": [ { "filename": "docs/uk/docs/tutorial/metadata.md", "status": "added", "additions": 120, "deletions": 0, "changes": 120, "patch": "@@ -0,0 +1,120 @@\n+# Метадані та URL-адреси документації\n+\n+Ви можете налаштувати кілька конфігурацій метаданих у Вашому додатку **FastAPI**.\n+\n+## Метадані для API\n+\n+Ви можете встановити такі поля, які використовуються в специфікації OpenAPI та в автоматично згенерованих інтерфейсах документації API:\n+\n+| Параметр | Тип | Опис |\n+|------------|------|-------------|\n+| `title` | `str` | Назва API. |\n+| `summary` | `str` | Короткий опис API. Доступно з OpenAPI 3.1.0, FastAPI 0.99.0. |\n+| `description` | `str` | Більш детальний опис API. Може використовувати Markdown. |\n+| `version` | `string` | Версія API. Це версія Вашого додатка, а не OpenAPI. Наприклад, `2.5.0`. |\n+| `terms_of_service` | `str` | URL до умов використання API. Якщо вказано, має бути у форматі URL. |\n+| `contact` | `dict` | Інформація для контакту з API. Може містити кілька полів.
      contact поля
      ПараметрТипОпис
      namestrІм'я контактної особи або організації.
      urlstrURL з інформацією для контакту. Повинен бути у форматі URL.
      emailstrEmail контактної особи або організації. Повинен бути у форматі електронної пошти.
      |\n+| `license_info` | `dict` | Інформація про ліцензію для API. Може містити кілька полів.
      license_info поля
      ПараметрТипОпис
      namestrОБОВ'ЯЗКОВО (якщо встановлено license_info). Назва ліцензії для API.
      identifierstrЛіцензійний вираз за SPDX для API. Поле identifier взаємовиключне з полем url. Доступно з OpenAPI 3.1.0, FastAPI 0.99.0.
      urlstrURL до ліцензії, яка використовується для API. Повинен бути у форматі URL.
      |\n+\n+Ви можете налаштувати їх наступним чином:\n+\n+{* ../../docs_src/metadata/tutorial001.py hl[3:16, 19:32] *}\n+\n+/// tip | Підказка\n+\n+У полі `description` можна використовувати Markdown, і він буде відображатися у результаті.\n+\n+///\n+\n+З цією конфігурацією автоматична документація API виглядатиме так:\n+\n+\n+\n+## Ідентифікатор ліцензії\n+\n+З початку використання OpenAPI 3.1.0 та FastAPI 0.99.0 Ви також можете налаштувати `license_info` за допомогою `identifier` замість `url`.\n+\n+Наприклад:\n+\n+{* ../../docs_src/metadata/tutorial001_1.py hl[31] *}\n+\n+## Метадані для тегів\n+\n+Ви також можете додати додаткові метадані для різних тегів, які використовуються для групування операцій шляхів, за допомогою параметра `openapi_tags`.\n+\n+Він приймає список, який містить один словник для кожного тега.\n+\n+Кожен словник може містити:\n+\n+* `name` (**обов'язково**): `str` з тією ж назвою тегу, яку Ви використовуєте у параметрі `tags` у Ваших *операціях шляху* та `APIRouter`s.\n+* `description`: `str` з коротким описом тегу. Може містити Markdown і буде відображено в інтерфейсі документації.\n+* `externalDocs`: `dict` який описує зовнішню документацію з такими полями:\n+ * `description`: `str` з коротким описом зовнішньої документації.\n+ * `url` (**обов'язково**): `str`з URL-адресою зовнішньої документації.\n+\n+### Створення метаданих для тегів\n+\n+Спробуймо це на прикладі з тегами для `users` та `items`.\n+\n+Створіть метадані для своїх тегів і передайте їх у параметр `openapi_tags`:\n+\n+{* ../../docs_src/metadata/tutorial004.py hl[3:16,18] *}\n+\n+Зверніть увагу, що в описах можна використовувати Markdown, наприклад, \"login\" буде показано жирним шрифтом (**login**), а \"fancy\" буде показано курсивом (_fancy_).\n+\n+/// tip | Порада\n+\n+Не обов'язково додавати метадані для всіх тегів, які Ви використовуєте.\n+\n+///\n+\n+### Використання тегів\n+\n+Використовуйте параметр `tags` зі своїми *операціями шляху* (і `APIRouter`) для призначення їх до різних тегів:\n+\n+{* ../../docs_src/metadata/tutorial004.py hl[21,26] *}\n+\n+/// info | Інформація\n+\n+Детальніше про теги читайте в розділі [Конфігурація шляхів операцій](path-operation-configuration.md#tags){.internal-link target=_blank}.\n+\n+///\n+\n+### Перевірка документації\n+\n+Якщо Ви зараз перевірите документацію, вона покаже всі додаткові метадані:\n+\n+\n+\n+### Порядок тегів\n+\n+Порядок кожного словника метаданих тегу також визначає порядок відображення в інтерфейсі документації.\n+\n+Наприклад, хоча `users` мав би йти після `items` в алфавітному порядку, він відображається перед ними, оскільки ми додали його метадані як перший словник у списку.\n+\n+## URL для OpenAPI\n+\n+За замовчуванням схема OpenAPI надається за адресою `/openapi.json`.\n+\n+Але Ви можете налаштувати це за допомогою параметра `openapi_url`.\n+\n+Наприклад, щоб налаштувати його на `/api/v1/openapi.json`:\n+\n+{* ../../docs_src/metadata/tutorial002.py hl[3] *}\n+\n+Якщо Ви хочете повністю вимкнути схему OpenAPI, Ви можете встановити `openapi_url=None`, це також вимкне інтерфейси документації, які її використовують.\n+\n+## URL-адреси документації\n+\n+Ви можете налаштувати два інтерфейси користувача для документації, які включені:\n+\n+* **Swagger UI**: доступний за адресою `/docs`.\n+ * Ви можете змінити його URL за допомогою параметра `docs_url`.\n+ * Ви можете вимкнути його, встановивши `docs_url=None`.\n+* **ReDoc**: доступний за адресою `/redoc`.\n+ * Ви можете змінити його URL за допомогою параметра `redoc_url`.\n+ * Ви можете вимкнути його, встановивши `redoc_url=None`.\n+\n+Наприклад, щоб налаштувати Swagger UI на `/documentation` і вимкнути ReDoc:\n+\n+{* ../../docs_src/metadata/tutorial003.py hl[3] *}" } ], "reviews": [ { "id": 2684575842, "user": "user_489e2b951069", "state": "COMMENTED", "body": null, "submitted_at": "2025-03-14T07:32:38+00:00" }, { "id": 2684580672, "user": "user_489e2b951069", "state": "APPROVED", "body": null, "submitted_at": "2025-03-14T07:34:28+00:00" }, { "id": 2685848744, "user": "user_c36c155012b4", "state": "COMMENTED", "body": null, "submitted_at": "2025-03-14T15:00:13+00:00" }, { "id": 2688223516, "user": "user_dac146a60e0c", "state": "APPROVED", "body": "translation looks good", "submitted_at": "2025-03-15T18:42:50+00:00" }, { "id": 2689359918, "user": "user_787e19aded2a", "state": "APPROVED", "body": null, "submitted_at": "2025-03-17T07:24:21+00:00" } ], "review_comments": [ { "id": 1995013083, "user": "user_489e2b951069", "body": "Тут напевно вже _не короткий опис_. Бо до цього було summary з таким самим призначенням", "path": "docs/uk/docs/tutorial/metadata.md", "line": null, "side": "RIGHT", "created_at": "2025-03-14T07:32:38+00:00" }, { "id": 1995738596, "user": "user_c36c155012b4", "body": "згоден :) дякую, що підмітив :)", "path": "docs/uk/docs/tutorial/metadata.md", "line": null, "side": "RIGHT", "created_at": "2025-03-14T15:00:13+00:00" } ], "meta": { "languages": [ "md" ], "touches_tests": false, "review_state_summary": { "COMMENTED": 2, "APPROVED": 3 }, "meaningful_comment_count": 2, "has_approval": true, "has_changes_requested": false, "total_review_comments": 2 } } { "_id": "4d5de292f9875907", "_schema_version": "1.0", "_cleaned_at": "2026-02-12T07:46:51.766143+00:00", "repo": "tiangolo/fastapi", "repo_url": "https://github.com/fastapi/fastapi", "license_name": "MIT License", "license_spdx": "MIT", "pr_number": 13420, "title": "🌐 Add Ukrainian translation for `docs/uk/docs/tutorial/handling-errors.md` page", "body": null, "author": "user_c36c155012b4", "created_at": "2025-02-25T03:34:08+00:00", "merged_at": "2025-05-30T13:31:13+00:00", "base_branch": "master", "head_branch": "translation-uk/handling-errors", "additions": 255, "deletions": 0, "changed_files": 1, "files": [ { "filename": "docs/uk/docs/tutorial/handling-errors.md", "status": "added", "additions": 255, "deletions": 0, "changes": 255, "patch": "@@ -0,0 +1,255 @@\n+# Обробка Помилок\n+\n+Є багато ситуацій, коли потрібно повідомити клієнта, який використовує Ваш API, про помилку.\n+\n+Цим клієнтом може бути браузер із фронтендом, код іншого розробника, IoT-пристрій тощо.\n+\n+Можливо, Вам потрібно повідомити клієнта, що:\n+\n+* У нього недостатньо прав для виконання цієї операції.\n+* Він не має доступу до цього ресурсу.\n+* Елемент, до якого він намагається отримати доступ, не існує.\n+* тощо.\n+\n+У таких випадках зазвичай повертається **HTTP статус-код** в діапазоні **400** (від 400 до 499).\n+\n+Це схоже на HTTP статус-коди 200 (від 200 до 299). Ці \"200\" статус-коди означають, що запит пройшов успішно.\n+\n+Статус-коди в діапазоні 400 означають, що сталася помилка з боку клієнта.\n+\n+Пам'ятаєте всі ці помилки **404 Not Found** (і жарти про них)?\n+\n+## Використання `HTTPException`\n+\n+Щоб повернути HTTP-відповіді з помилками клієнту, використовуйте `HTTPException`.\n+\n+### Імпорт `HTTPException`\n+\n+{* ../../docs_src/handling_errors/tutorial001.py hl[1] *}\n+\n+### Використання `HTTPException` у коді\n+\n+`HTTPException` — це звичайна помилка Python із додатковими даними, які стосуються API.\n+\n+Оскільки це помилка Python, Ви не `повертаєте` його, а `генеруєте` (генеруєте помилку).\n+\n+Це також означає, що якщо Ви перебуваєте всередині допоміжної функції, яку викликаєте всередині своєї *функції операції шляху*, і там генеруєте `HTTPException`, всередині цієї допоміжної функції, то решта коду в *функції операції шляху* не буде виконана. Запит одразу завершиться, і HTTP-помилка з `HTTPException` буде надіслана клієнту.\n+\n+Перевага використання `генерації` (raise) помилки замість `повернення` значення (return) стане більш очевидним в розділі про Залежності та Безпеку.\n+\n+У цьому прикладі, якщо клієнт запитує елемент за ID, якого не існує, буде згенеровано помилку зі статус-кодом `404`:\n+\n+{* ../../docs_src/handling_errors/tutorial001.py hl[11] *}\n+\n+### Отримана відповідь\n+\n+Якщо клієнт робить запит за шляхом `http://example.com/items/foo` (де `item_id` `\"foo\"`), він отримає статус-код 200 і JSON відповідь:\n+\n+```JSON\n+{\n+ \"item\": \"The Foo Wrestlers\"\n+}\n+```\n+\n+Але якщо клієнт робить запит на `http://example.com/items/bar` (де `item_id` має не існуюче значення `\"bar\"`), то отримає статус-код 404 (помилка \"не знайдено\") та відповідь:\n+\n+```JSON\n+{\n+ \"detail\": \"Item not found\"\n+}\n+```\n+\n+/// tip | Порада\n+\n+Під час виклику `HTTPException` Ви можете передати будь-яке значення, яке може бути перетворене в JSON, як параметр `detail`, а не лише рядок (`str`).\n+\n+Ви можете передати `dict`, `list` тощо.\n+\n+Вони обробляються автоматично за допомогою **FastAPI** та перетворюються в JSON.\n+\n+///\n+\n+## Додавання власних заголовків\n+\n+Іноді потрібно додати власні заголовки до HTTP-помилки, наприклад, для певних типів безпеки.\n+\n+Ймовірно, Вам не доведеться використовувати це безпосередньо у своєму коді.\n+\n+Але якщо Вам знадобиться це для складного сценарію, Ви можете додати власні заголовки:\n+\n+{* ../../docs_src/handling_errors/tutorial002.py hl[14] *}\n+\n+## Встановлення власних обробників помилок\n+\n+Ви можете додати власні обробники помилок за допомогою тих самих утиліт обробки помилок зі Starlette.\n+\n+Припустимо, у Вас є власний обʼєкт помилки `UnicornException`, яке Ви (або бібліотека, яку Ви використовуєте) може `згенерувати` (`raise`).\n+\n+І Ви хочете обробляти це виключення глобально за допомогою FastAPI.\n+\n+Ви можете додати власний обробник виключень за допомогою `[USER_REDACTED].exception_handler()`:\n+\n+{* ../../docs_src/handling_errors/tutorial003.py hl[5:7,13:18,24] *}\n+\n+Тут, якщо Ви звернетеся до `/unicorns/yolo`, то згенерується помилка `UnicornException`.\n+\n+Але вона буде оброблена функцією-обробником `unicorn_exception_handler`.\n+\n+Отже, Ви отримаєте зрозумілу помилку зі HTTP-статусом `418` і JSON-відповіддю:\n+\n+```JSON\n+{\"message\": \"Oops! yolo did something. There goes a rainbow...\"}\n+```\n+\n+/// note | Технічні деталі\n+\n+Ви також можете використовувати `from starlette.requests import Request` і `from starlette.responses import JSONResponse`.\n+\n+**FastAPI** надає ті самі `starlette.responses`, що й `fastapi.responses`, просто для зручності розробника. Але більшість доступних відповідей надходять безпосередньо зі Starlette. Те ж саме стосується і `Request`.\n+\n+///\n+\n+## Перевизначення обробників помилок за замовчуванням\n+\n+**FastAPI** має кілька обробників помилок за замовчуванням.\n+\n+Ці обробники відповідають за повернення стандартних JSON-відповідей, коли Ви `генеруєте` (`raise`) `HTTPException`, а також коли запит містить некоректні дані.\n+\n+Ви можете перевизначити ці обробники, створивши власні.\n+\n+### Перевизначення помилок валідації запиту\n+\n+Коли запит містить некоректні дані, **FastAPI** генерує `RequestValidationError`.\n+\n+І також включає обробник помилок за замовчуванням для нього.\n+\n+Щоб перевизначити його, імпортуйте `RequestValidationError` і використовуйте його з `[USER_REDACTED].exception_handler(RequestValidationError)` для декорування обробника помилок.\n+\n+Обробник помилок отримує `Request` і саму помилку.\n+\n+{* ../../docs_src/handling_errors/tutorial004.py hl[2,14:16] *}\n+\n+Тепер, якщо Ви перейдете за посиланням `/items/foo`, замість того, щоб отримати стандартну JSON-помилку:\n+\n+```JSON\n+{\n+ \"detail\": [\n+ {\n+ \"loc\": [\n+ \"path\",\n+ \"item_id\"\n+ ],\n+ \"msg\": \"value is not a valid integer\",\n+ \"type\": \"type_error.integer\"\n+ }\n+ ]\n+}\n+```\n+\n+Ви отримаєте текстову версію:\n+\n+```\n+1 validation error\n+path -> item_id\n+ value is not a valid integer (type=type_error.integer)\n+```\n+\n+#### `RequestValidationError` проти `ValidationError`\n+\n+/// warning | Увага\n+\n+Це технічні деталі, які Ви можете пропустити, якщо вони зараз не важливі для Вас.\n+\n+///\n+\n+`RequestValidationError` є підкласом Pydantic `ValidationError`.\n+\n+**FastAPI** використовує його для того, якщо Ви використовуєте модель Pydantic у `response_model` і у ваших даних є помилка, Ви побачили помилку у своєму журналі.\n+\n+Але клієнт/користувач не побачить її. Натомість клієнт отримає \"[NAME_REDACTED]\" зі статусом HTTP `500`.\n+\n+Так має бути, якщо у Вас виникла `ValidationError` Pydantic у *відповіді* або деінде у вашому коді (не у *запиті* клієнта), це насправді є помилкою у Вашому коді.\n+\n+І поки Ви її виправляєте, клієнти/користувачі не повинні мати доступу до внутрішньої інформації про помилку, оскільки це може призвести до вразливості безпеки.\n+\n+### Перевизначення обробника помилок `HTTPException`\n+\n+Аналогічно, Ви можете перевизначити обробник `HTTPException`.\n+\n+Наприклад, Ви можете захотіти повернути текстову відповідь замість JSON для цих помилок:\n+\n+{* ../../docs_src/handling_errors/tutorial004.py hl[3:4,9:11,22] *}\n+\n+/// note | Технічні деталі\n+\n+Ви також можете використовувати `from starlette.responses import PlainTextResponse`.\n+\n+**FastAPI** надає ті самі `starlette.responses`, що й `fastapi.responses`, просто для зручності розробника. Але більшість доступних відповідей надходять безпосередньо зі Starlette.\n+\n+///\n+\n+### Використання тіла `RequestValidationError`\n+\n+`RequestValidationError` містить `body`, який він отримав із некоректними даними.\n+\n+Ви можете використовувати це під час розробки свого додатка, щоб логувати тіло запиту та налагоджувати його, повертати користувачеві тощо.\n+\n+{* ../../docs_src/handling_errors/tutorial005.py hl[14] *}\n+\n+Тепер спробуйте надіслати некоректний елемент, наприклад:\n+\n+```JSON\n+{\n+ \"title\": \"towel\",\n+ \"size\": \"XL\"\n+}\n+```\n+Ви отримаєте відповідь, яка повідомить Вам, які саме дані є некоректні у вашому тілі запиту:\n+\n+\n+```JSON hl_lines=\"12-15\"\n+{\n+ \"detail\": [\n+ {\n+ \"loc\": [\n+ \"body\",\n+ \"size\"\n+ ],\n+ \"msg\": \"value is not a valid integer\",\n+ \"type\": \"type_error.integer\"\n+ }\n+ ],\n+ \"body\": {\n+ \"title\": \"towel\",\n+ \"size\": \"XL\"\n+ }\n+}\n+```\n+\n+#### `HTTPException` FastAPI проти `HTTPException` Starlette\n+\n+**FastAPI** має власний `HTTPException`.\n+\n+І клас помилки `HTTPException` в **FastAPI** успадковується від класу помилки `HTTPException` в Starlette.\n+\n+Єдина різниця полягає в тому, що `HTTPException` в **FastAPI** приймає будь-які дані, які можна перетворити на JSON, для поля `detail`, тоді як `HTTPException` у Starlette приймає тільки рядки.\n+\n+Отже, Ви можете продовжувати використовувати `HTTPException` в **FastAPI** як зазвичай у своєму коді.\n+\n+Але коли Ви реєструєте обробник виключень, слід реєструвати його для `HTTPException` зі Starlette.\n+\n+Таким чином, якщо будь-яка частина внутрішнього коду Starlette або розширення чи плагін Starlette згенерує (raise) `HTTPException`, Ваш обробник зможе перехопити та обробити її.\n+\n+У цьому прикладі, щоб мати можливість використовувати обидва `HTTPException` в одному коді, помилка Starlette перейменовується на `StarletteHTTPException`:\n+\n+```Python\n+from starlette.exceptions import HTTPException as StarletteHTTPException\n+```\n+\n+### Повторне використання обробників помилок **FastAPI**\n+\n+Якщо Ви хочете використовувати помилки разом із такими ж обробниками помилок за замовчуванням, як у **FastAPI**, Ви можете імпортувати та повторно використовувати їх із `fastapi.exception_handlers`:\n+\n+{* ../../docs_src/handling_errors/tutorial006.py hl[2:5,15,21] *}\n+\n+У цьому прикладі Ви просто використовуєте `print` для виведення дуже інформативного повідомлення, але Ви зрозуміли основну ідею. Ви можете обробити помилку та повторно використовувати обробники помилок за замовчуванням." } ], "reviews": [ { "id": 2652393581, "user": "user_9ee0ae83e609", "state": "COMMENTED", "body": "Great work! as always :) only one little thing", "submitted_at": "2025-03-01T11:22:47+00:00" }, { "id": 2661561064, "user": "user_c36c155012b4", "state": "COMMENTED", "body": null, "submitted_at": "2025-03-05T15:39:33+00:00" }, { "id": 2703114101, "user": "user_dac146a60e0c", "state": "APPROVED", "body": "good work", "submitted_at": "2025-03-20T15:05:34+00:00" }, { "id": 2745081007, "user": "user_787e19aded2a", "state": "APPROVED", "body": "good work, thanks :)", "submitted_at": "2025-04-06T08:56:38+00:00" } ], "review_comments": [ { "id": 1976389653, "user": "user_9ee0ae83e609", "body": "```suggestion\nЄ багато ситуацій, коли потрібно повідомити клієнта, який використовує Ваш API, про помилку.\n```", "path": "docs/uk/docs/tutorial/handling-errors.md", "line": null, "side": "RIGHT", "created_at": "2025-03-01T11:22:02+00:00" }, { "id": 1981678031, "user": "user_c36c155012b4", "body": "thank you :)", "path": "docs/uk/docs/tutorial/handling-errors.md", "line": null, "side": "RIGHT", "created_at": "2025-03-05T15:39:33+00:00" } ], "meta": { "languages": [ "md" ], "touches_tests": false, "review_state_summary": { "COMMENTED": 2, "APPROVED": 2 }, "meaningful_comment_count": 2, "has_approval": true, "has_changes_requested": false, "total_review_comments": 2 } } { "_id": "539970c83be409b0", "_schema_version": "1.0", "_cleaned_at": "2026-02-12T07:46:51.766143+00:00", "repo": "tiangolo/fastapi", "repo_url": "https://github.com/fastapi/fastapi", "license_name": "MIT License", "license_spdx": "MIT", "pr_number": 13412, "title": "🌐 Add Russian translation for `docs/ru/docs/tutorial/middleware.md`", "body": null, "author": "user_6d7d83efab20", "created_at": "2025-02-23T00:41:38+00:00", "merged_at": "2025-02-28T17:09:30+00:00", "base_branch": "master", "head_branch": "translate-ru-tutorial-middleware", "additions": 74, "deletions": 0, "changed_files": 1, "files": [ { "filename": "docs/ru/docs/tutorial/middleware.md", "status": "added", "additions": 74, "deletions": 0, "changes": 74, "patch": "@@ -0,0 +1,74 @@\n+# Middleware (Промежуточный слой)\n+\n+Вы можете добавить промежуточный слой (middleware) в **FastAPI** приложение.\n+\n+\"Middleware\" это функция, которая выполняется с каждым запросом до его обработки какой-либо конкретной *операцией пути*.\n+А также с каждым ответом перед его возвращением.\n+\n+\n+* Она принимает каждый поступающий **запрос**.\n+* Может что-то сделать с этим **запросом** или выполнить любой нужный код.\n+* Затем передает **запрос** для последующей обработки (какой-либо *операцией пути*).\n+* Получает **ответ** (от *операции пути*).\n+* Может что-то сделать с этим **ответом** или выполнить любой нужный код.\n+* И возвращает **ответ**.\n+\n+/// note | Технические детали\n+\n+Если у вас есть зависимости с `yield`, то код выхода (код после `yield`) будет выполняться *после* middleware.\n+\n+Если у вас имеются некие фоновые задачи (см. документацию), то они будут запущены после middleware.\n+\n+///\n+\n+## Создание middleware\n+\n+Для создания middleware используйте декоратор `[USER_REDACTED].middleware(\"http\")`.\n+\n+Функция middleware получает:\n+\n+* `request` (объект запроса).\n+* Функцию `call_next`, которая получает `request` в качестве параметра.\n+ * Эта функция передаёт `request` соответствующей *операции пути*.\n+ * Затем она возвращает ответ `response`, сгенерированный *операцией пути*.\n+* Также имеется возможность видоизменить `response`, перед тем как его вернуть.\n+\n+{* ../../docs_src/middleware/tutorial001.py hl[8:9,11,14] *}\n+\n+/// tip | Примечание\n+\n+Имейте в виду, что можно добавлять свои собственные заголовки при помощи префикса 'X-'.\n+\n+Если же вы хотите добавить собственные заголовки, которые клиент сможет увидеть в браузере, то вам потребуется добавить их в настройки CORS ([CORS ([NAME_REDACTED])](cors.md){.internal-link target=_blank}), используя параметр `expose_headers`, см. документацию Starlette's CORS docs.\n+\n+///\n+\n+/// note | Технические детали\n+\n+Вы также можете использовать `from starlette.requests import Request`.\n+\n+**FastAPI** предоставляет такой доступ для удобства разработчиков. Но, на самом деле, это `Request` из Starlette.\n+\n+///\n+\n+### До и после `response`\n+\n+Вы можете добавить код, использующий `request` до передачи его какой-либо *операции пути*.\n+\n+А также после формирования `response`, до того, как вы его вернёте.\n+\n+Например, вы можете добавить собственный заголовок `X-Process-Time`, содержащий время в секундах, необходимое для обработки запроса и генерации ответа:\n+\n+{* ../../docs_src/middleware/tutorial001.py hl[10,12:13] *}\n+\n+/// tip | Примечание\n+\n+Мы используем `time.perf_counter()` вместо `time.time()` для обеспечения большей точности наших примеров. 🤓\n+\n+///\n+\n+## Другие middleware\n+\n+О других middleware вы можете узнать больше в разделе [[NAME_REDACTED]: [NAME_REDACTED]](../advanced/middleware.md){.internal-link target=_blank}.\n+\n+В следующем разделе вы можете прочитать, как настроить CORS с помощью middleware." } ], "reviews": [ { "id": 2637783284, "user": "user_9e49ba0b4492", "state": "COMMENTED", "body": null, "submitted_at": "2025-02-24T16:44:18+00:00" }, { "id": 2637790233, "user": "user_df3ddbc43209", "state": "COMMENTED", "body": null, "submitted_at": "2025-02-24T16:48:38+00:00" }, { "id": 2638499791, "user": "user_6d7d83efab20", "state": "COMMENTED", "body": null, "submitted_at": "2025-02-24T21:38:29+00:00" }, { "id": 2638511857, "user": "user_6d7d83efab20", "state": "COMMENTED", "body": null, "submitted_at": "2025-02-24T21:44:29+00:00" }, { "id": 2640261117, "user": "user_9e49ba0b4492", "state": "CHANGES_REQUESTED", "body": null, "submitted_at": "2025-02-25T11:14:22+00:00" }, { "id": 2640740646, "user": "user_6d7d83efab20", "state": "COMMENTED", "body": null, "submitted_at": "2025-02-25T11:43:53+00:00" }, { "id": 2640753355, "user": "user_6d7d83efab20", "state": "COMMENTED", "body": null, "submitted_at": "2025-02-25T11:49:23+00:00" }, { "id": 2640762516, "user": "user_6d7d83efab20", "state": "COMMENTED", "body": null, "submitted_at": "2025-02-25T11:52:04+00:00" }, { "id": 2640778983, "user": "user_6d7d83efab20", "state": "COMMENTED", "body": null, "submitted_at": "2025-02-25T11:57:33+00:00" }, { "id": 2640850582, "user": "user_9e49ba0b4492", "state": "COMMENTED", "body": null, "submitted_at": "2025-02-25T12:23:56+00:00" }, { "id": 2640861627, "user": "user_9e49ba0b4492", "state": "COMMENTED", "body": null, "submitted_at": "2025-02-25T12:29:18+00:00" }, { "id": 2640898808, "user": "user_9e49ba0b4492", "state": "COMMENTED", "body": null, "submitted_at": "2025-02-25T12:35:00+00:00" }, { "id": 2641233264, "user": "user_6d7d83efab20", "state": "COMMENTED", "body": null, "submitted_at": "2025-02-25T14:19:12+00:00" }, { "id": 2641632915, "user": "user_9e49ba0b4492", "state": "CHANGES_REQUESTED", "body": null, "submitted_at": "2025-02-25T16:00:49+00:00" }, { "id": 2641694591, "user": "user_6d7d83efab20", "state": "COMMENTED", "body": null, "submitted_at": "2025-02-25T16:18:55+00:00" }, { "id": 2641720446, "user": "user_9e49ba0b4492", "state": "COMMENTED", "body": null, "submitted_at": "2025-02-25T16:26:43+00:00" }, { "id": 2641728099, "user": "user_9e49ba0b4492", "state": "COMMENTED", "body": null, "submitted_at": "2025-02-25T16:29:11+00:00" }, { "id": 2641737266, "user": "user_9e49ba0b4492", "state": "COMMENTED", "body": null, "submitted_at": "2025-02-25T16:32:14+00:00" }, { "id": 2641943211, "user": "user_6d7d83efab20", "state": "COMMENTED", "body": null, "submitted_at": "2025-02-25T17:36:09+00:00" }, { "id": 2641056530, "user": "user_df3ddbc43209", "state": "COMMENTED", "body": null, "submitted_at": "2025-02-25T17:36:27+00:00" }, { "id": 2642003992, "user": "user_6d7d83efab20", "state": "COMMENTED", "body": null, "submitted_at": "2025-02-25T18:01:32+00:00" }, { "id": 2642065516, "user": "user_9e49ba0b4492", "state": "COMMENTED", "body": null, "submitted_at": "2025-02-25T18:26:37+00:00" }, { "id": 2642102640, "user": "user_6d7d83efab20", "state": "COMMENTED", "body": null, "submitted_at": "2025-02-25T18:44:24+00:00" }, { "id": 2642126841, "user": "user_9e49ba0b4492", "state": "COMMENTED", "body": null, "submitted_at": "2025-02-25T18:56:19+00:00" }, { "id": 2642137617, "user": "user_9e49ba0b4492", "state": "COMMENTED", "body": null, "submitted_at": "2025-02-25T19:01:28+00:00" }, { "id": 2642402731, "user": "user_6d7d83efab20", "state": "COMMENTED", "body": null, "submitted_at": "2025-02-25T20:35:52+00:00" }, { "id": 2647632675, "user": "user_9e49ba0b4492", "state": "CHANGES_REQUESTED", "body": null, "submitted_at": "2025-02-27T12:41:31+00:00" }, { "id": 2648388723, "user": "user_6d7d83efab20", "state": "COMMENTED", "body": null, "submitted_at": "2025-02-27T16:28:58+00:00" }, { "id": 2648575829, "user": "user_9e49ba0b4492", "state": "COMMENTED", "body": null, "submitted_at": "2025-02-27T17:35:13+00:00" }, { "id": 2648591255, "user": "user_9e49ba0b4492", "state": "COMMENTED", "body": null, "submitted_at": "2025-02-27T17:42:10+00:00" }, { "id": 2648603235, "user": "user_9e49ba0b4492", "state": "APPROVED", "body": null, "submitted_at": "2025-02-27T17:47:14+00:00" }, { "id": 2648648983, "user": "user_6d7d83efab20", "state": "COMMENTED", "body": null, "submitted_at": "2025-02-27T18:07:23+00:00" }, { "id": 2648684798, "user": "user_9e49ba0b4492", "state": "COMMENTED", "body": null, "submitted_at": "2025-02-27T18:21:58+00:00" }, { "id": 2649305780, "user": "user_6d7d83efab20", "state": "COMMENTED", "body": null, "submitted_at": "2025-02-27T23:16:53+00:00" }, { "id": 2650715422, "user": "user_0cc05bcc4fb5", "state": "APPROVED", "body": null, "submitted_at": "2025-02-28T13:12:56+00:00" }, { "id": 2650721469, "user": "user_df3ddbc43209", "state": "APPROVED", "body": "Хорошая работа 👍", "submitted_at": "2025-02-28T13:15:45+00:00" } ], "review_comments": [ { "id": 1968026694, "user": "user_9e49ba0b4492", "body": "Может термин \"промежуточный слой\" лучше подходит?", "path": "docs/ru/docs/tutorial/middleware.md", "line": null, "side": "RIGHT", "created_at": "2025-02-24T16:44:18+00:00" }, { "id": 1968030895, "user": "user_df3ddbc43209", "body": "```suggestion\nВ следующем разделе вы можете прочитать, как работать с CORS middleware.\n```", "path": "docs/ru/docs/tutorial/middleware.md", "line": null, "side": "RIGHT", "created_at": "2025-02-24T16:47:02+00:00" }, { "id": 1968032973, "user": "user_df3ddbc43209", "body": "```suggestion\n* Также имеется возможность обработать `response` перед тем, как его вернуть.\n```", "path": "docs/ru/docs/tutorial/middleware.md", "line": null, "side": "RIGHT", "created_at": "2025-02-24T16:48:17+00:00" }, { "id": 1968452703, "user": "user_6d7d83efab20", "body": "исправила, но с изменением:\n`Также имеется возможность обработать `response`, перед тем как его вернуть.`", "path": "docs/ru/docs/tutorial/middleware.md", "line": null, "side": "RIGHT", "created_at": "2025-02-24T21:38:29+00:00" }, { "id": 1968459357, "user": "user_6d7d83efab20", "body": "изменила перевод на более точный (и запятая теперь на месте):\n\n`В следующем разделе вы можете прочитать, как настроить CORS с помощью middleware.`", "path": "docs/ru/docs/tutorial/middleware.md", "line": null, "side": "RIGHT", "created_at": "2025-02-24T21:44:29+00:00" }, { "id": 1969350888, "user": "user_9e49ba0b4492", "body": "Вы можете добавить промежуточный слой (middleware) в **FastAPI** приложения.", "path": "docs/ru/docs/tutorial/middleware.md", "line": null, "side": "RIGHT", "created_at": "2025-02-25T09:23:58+00:00" }, { "id": 1969356015, "user": "user_9e49ba0b4492", "body": "* Она принимает каждый поступающий **запрос**.", "path": "docs/ru/docs/tutorial/middleware.md", "line": null, "side": "RIGHT", "created_at": "2025-02-25T09:26:40+00:00" }, { "id": 1969362025, "user": "user_9e49ba0b4492", "body": "* Затем передает запрос для последующей обработки в *функцию эндпоинта*.", "path": "docs/ru/docs/tutorial/middleware.md", "line": null, "side": "RIGHT", "created_at": "2025-02-25T09:30:00+00:00" }, { "id": 1969363664, "user": "user_9e49ba0b4492", "body": "* Получает **ответ** от *функции эндпоинта*.", "path": "docs/ru/docs/tutorial/middleware.md", "line": null, "side": "RIGHT", "created_at": "2025-02-25T09:30:54+00:00" }, { "id": 1969367283, "user": "user_9e49ba0b4492", "body": "* Может что-то сделать с этим **запросом** или выполнить любой нужный код.", "path": "docs/ru/docs/tutorial/middleware.md", "line": null, "side": "RIGHT", "created_at": "2025-02-25T09:32:53+00:00" }, { "id": 1969369859, "user": "user_9e49ba0b4492", "body": "* Может что-то сделать с этим **ответом** или выполнить любой нужный код.", "path": "docs/ru/docs/tutorial/middleware.md", "line": null, "side": "RIGHT", "created_at": "2025-02-25T09:34:24+00:00" }, { "id": 1969370283, "user": "user_9e49ba0b4492", "body": "* И возвращает **ответ**.", "path": "docs/ru/docs/tutorial/middleware.md", "line": null, "side": "RIGHT", "created_at": "2025-02-25T09:34:38+00:00" }, { "id": 1969375502, "user": "user_9e49ba0b4492", "body": "Если у вас есть зависимости с `yield`, то код выхода (exit code) будет выполняться *после* middleware.", "path": "docs/ru/docs/tutorial/middleware.md", "line": null, "side": "RIGHT", "created_at": "2025-02-25T09:37:35+00:00" }, { "id": 1969388746, "user": "user_9e49ba0b4492", "body": "Если имеются фоновые задачи (см. документацию), то они будут запущены после middleware.", "path": "docs/ru/docs/tutorial/middleware.md", "line": null, "side": "RIGHT", "created_at": "2025-02-25T09:44:59+00:00" }, { "id": 1969429152, "user": "user_9e49ba0b4492", "body": "* Также имеется возможность видоизменить `response`, перед тем как его вернуть.", "path": "docs/ru/docs/tutorial/middleware.md", "line": null, "side": "RIGHT", "created_at": "2025-02-25T09:59:52+00:00" }, { "id": 1969452388, "user": "user_9e49ba0b4492", "body": "Имейте в виду, что можно добавлять свои собственные заголовки при помощи префикса 'X-'.", "path": "docs/ru/docs/tutorial/middleware.md", "line": null, "side": "RIGHT", "created_at": "2025-02-25T10:08:16+00:00" }, { "id": 1969472102, "user": "user_9e49ba0b4492", "body": "Но если вы хотите, чтобы клиент в браузере смог увидеть ваши собственные заголовки, то потребуется добавить их в настройки CORS ([CORS ([NAME_REDACTED])](cors.md){.internal-link target=_blank}), используя параметр `expose_headers`, см. документацию Starlette's CORS docs.", "path": "docs/ru/docs/tutorial/middleware.md", "line": null, "side": "RIGHT", "created_at": "2025-02-25T10:18:24+00:00" }, { "id": 1969486523, "user": "user_9e49ba0b4492", "body": "/// note | Технические детали", "path": "docs/ru/docs/tutorial/middleware.md", "line": null, "side": "RIGHT", "created_at": "2025-02-25T10:26:04+00:00" }, { "id": 1969501910, "user": "user_9e49ba0b4492", "body": "**FastAPI** предоставляет такой доступ для удобства разработчиков. На самом деле это `Request` из Starlette.", "path": "docs/ru/docs/tutorial/middleware.md", "line": null, "side": "RIGHT", "created_at": "2025-02-25T10:35:28+00:00" }, { "id": 1969507254, "user": "user_9e49ba0b4492", "body": "Вы также можете использовать `from starlette.requests import Request`.", "path": "docs/ru/docs/tutorial/middleware.md", "line": null, "side": "RIGHT", "created_at": "2025-02-25T10:38:55+00:00" }, { "id": 1969513747, "user": "user_9e49ba0b4492", "body": "Вы можете добавить код, использующий `request` до передачи его в *функцию эндпоинта*.", "path": "docs/ru/docs/tutorial/middleware.md", "line": null, "side": "RIGHT", "created_at": "2025-02-25T10:42:55+00:00" }, { "id": 1969516290, "user": "user_9e49ba0b4492", "body": "А также после формирования `response`, до того как вы его вернёте.", "path": "docs/ru/docs/tutorial/middleware.md", "line": null, "side": "RIGHT", "created_at": "2025-02-25T10:44:36+00:00" }, { "id": 1969522290, "user": "user_9e49ba0b4492", "body": "Например, вы можете добавить собственный заголовок `X-Process-Time`, содержащий необходимое для обработки запроса и генерации ответа время в секундах:", "path": "docs/ru/docs/tutorial/middleware.md", "line": null, "side": "RIGHT", "created_at": "2025-02-25T10:48:36+00:00" }, { "id": 1969526072, "user": "user_9e49ba0b4492", "body": "Здесь мы используем `time.perf_counter()` вместо `time.time()` для обеспечения большей точности для данных целей. 🤓", "path": "docs/ru/docs/tutorial/middleware.md", "line": 66, "side": "RIGHT", "created_at": "2025-02-25T10:51:12+00:00" }, { "id": 1969528561, "user": "user_9e49ba0b4492", "body": "О других middleware вы можете узнать больше в разделе [[NAME_REDACTED]: [NAME_REDACTED]](../advanced/middleware.md){.internal-link target=_blank}.", "path": "docs/ru/docs/tutorial/middleware.md", "line": null, "side": "RIGHT", "created_at": "2025-02-25T10:52:50+00:00" }, { "id": 1969532050, "user": "user_9e49ba0b4492", "body": "Как настроить CORS с помощью middleware вы можете прочитать в следующем разделе.", "path": "docs/ru/docs/tutorial/middleware.md", "line": 74, "side": "RIGHT", "created_at": "2025-02-25T10:55:10+00:00" }, { "id": 1969536654, "user": "user_9e49ba0b4492", "body": "/// tip | Примечание", "path": "docs/ru/docs/tutorial/middleware.md", "line": null, "side": "RIGHT", "created_at": "2025-02-25T10:57:43+00:00" }, { "id": 1969538387, "user": "user_9e49ba0b4492", "body": "/// tip | Примечание", "path": "docs/ru/docs/tutorial/middleware.md", "line": null, "side": "RIGHT", "created_at": "2025-02-25T10:58:55+00:00" }, { "id": 1969602360, "user": "user_6d7d83efab20", "body": "здесь оставлю как есть", "path": "docs/ru/docs/tutorial/middleware.md", "line": null, "side": "RIGHT", "created_at": "2025-02-25T11:43:52+00:00" }, { "id": 1969609956, "user": "user_6d7d83efab20", "body": "поставлю запятую :laughing: (так будет проще для восприятия)", "path": "docs/ru/docs/tutorial/middleware.md", "line": null, "side": "RIGHT", "created_at": "2025-02-25T11:49:23+00:00" }, { "id": 1969614524, "user": "user_6d7d83efab20", "body": "оставлю как есть", "path": "docs/ru/docs/tutorial/middleware.md", "line": 66, "side": "RIGHT", "created_at": "2025-02-25T11:52:04+00:00" }, { "id": 1969623264, "user": "user_6d7d83efab20", "body": "оставлю как есть", "path": "docs/ru/docs/tutorial/middleware.md", "line": 74, "side": "RIGHT", "created_at": "2025-02-25T11:57:33+00:00" }, { "id": 1969662520, "user": "user_9e49ba0b4492", "body": "Да, согласен полностью)", "path": "docs/ru/docs/tutorial/middleware.md", "line": null, "side": "RIGHT", "created_at": "2025-02-25T12:23:56+00:00" }, { "id": 1969669039, "user": "user_9e49ba0b4492", "body": "В данном элементе списка в конце стоит точка. У остальных же элементов этого списка точка в конце не стоит.\nНужно привести к единому виду (в оригинале везде точки стоят).", "path": "docs/ru/docs/tutorial/middleware.md", "line": 10, "side": "RIGHT", "created_at": "2025-02-25T12:26:39+00:00" }, { "id": 1969674993, "user": "user_9e49ba0b4492", "body": "Я же правильно понимаю, что под \"exit code\" имеется ввиду \"участок кода после `yield`\"?", "path": "docs/ru/docs/tutorial/middleware.md", "line": null, "side": "RIGHT", "created_at": "2025-02-25T12:28:57+00:00" }, { "id": 1969687461, "user": "user_9e49ba0b4492", "body": "Если это так, то может вместо \"кода выхода\" и \"exit code\" явно пропишем что имеется ввиду \"код после `yield`\"?", "path": "docs/ru/docs/tutorial/middleware.md", "line": null, "side": "RIGHT", "created_at": "2025-02-25T12:34:59+00:00" }, { "id": 1969775793, "user": "user_df3ddbc43209", "body": "не знаю, как лучше, но в оригинале используется \"path operation\", да и в других местах доки это называют операцией пути", "path": "docs/ru/docs/tutorial/middleware.md", "line": null, "side": "RIGHT", "created_at": "2025-02-25T13:22:32+00:00" }, { "id": 1969877865, "user": "user_6d7d83efab20", "body": "Например, можно так:\nЕсли у вас есть зависимости с `yield`, то код выхода (код после `yield`) будет выполняться *после* middleware.", "path": "docs/ru/docs/tutorial/middleware.md", "line": null, "side": "RIGHT", "created_at": "2025-02-25T14:19:12+00:00" }, { "id": 1970081166, "user": "user_9e49ba0b4492", "body": "Если же вы хотите добавить собственные заголовки, которые клиент сможет увидеть в браузере, то вам потребуется добавить их в настройки CORS ([CORS ([NAME_REDACTED])](cors.md){.internal-link target=_blank}), используя параметр `expose_headers` (см. документацию Starlette's CORS docs).", "path": "docs/ru/docs/tutorial/middleware.md", "line": null, "side": "RIGHT", "created_at": "2025-02-25T16:00:41+00:00" }, { "id": 1970114601, "user": "user_6d7d83efab20", "body": "давай оставим как есть, это по сути одно и то же", "path": "docs/ru/docs/tutorial/middleware.md", "line": null, "side": "RIGHT", "created_at": "2025-02-25T16:18:55+00:00" }, { "id": 1970129052, "user": "user_9e49ba0b4492", "body": "Там косяк с expose_headers` 😅", "path": "docs/ru/docs/tutorial/middleware.md", "line": null, "side": "RIGHT", "created_at": "2025-02-25T16:26:43+00:00" }, { "id": 1970133608, "user": "user_9e49ba0b4492", "body": "![2025-02-25_19-28](https://github.com/[USER_REDACTED]nts/assets/edb29a93-9604-4e74-acc9-74608be4e0fe)", "path": "docs/ru/docs/tutorial/middleware.md", "line": null, "side": "RIGHT", "created_at": "2025-02-25T16:29:11+00:00" }, { "id": 1970139044, "user": "user_9e49ba0b4492", "body": "А \"см. что-то что-то\" вроде принято в скобках указывать. Не припомню, чтобы через запятую так писали.", "path": "docs/ru/docs/tutorial/middleware.md", "line": null, "side": "RIGHT", "created_at": "2025-02-25T16:32:14+00:00" }, { "id": 1970251180, "user": "user_6d7d83efab20", "body": "можно по-всякому: это авторский выбор\nзато без скобок эстетичнее и легче читается", "path": "docs/ru/docs/tutorial/middleware.md", "line": null, "side": "RIGHT", "created_at": "2025-02-25T17:36:09+00:00" }, { "id": 1970288027, "user": "user_6d7d83efab20", "body": "[USER_REDACTED]: имхо, *функция эндпоинта* понятнее и используется чаще. Но можно и обсудить. :blush:\n\n> \"Middleware\" это функция, которая выполняется с каждым запросом до его обработки *функцией эндпоинта*.\n\n> \"Middleware\" это функция, которая выполняется с каждым запросом до его обработки *операцией пути*.\n\n[\"эндпоинт at fastapi.tiangolo.com\"](https://www.google.com/search?q=%22%D1%8D%D0%BD%D0%B4%D0%BF%D0%BE%D0%B8%D0%BD%D1%82%22+site%3Afastapi.tiangolo.com)", "path": "docs/ru/docs/tutorial/middleware.md", "line": null, "side": "RIGHT", "created_at": "2025-02-25T18:01:32+00:00" }, { "id": 1970323429, "user": "user_9e49ba0b4492", "body": "Я согласен с [USER_REDACTED].\n[USER_REDACTED], ведь в переводе \"Большие приложения, в которых много файлов\", ты все \"_path operation_\" перевела либо как \"_операция пути_\", либо как \"_эндпоинт_\".\nА \"_функция операции пути_\" или \"_функция эндпоинта_\" - это уже \"_operation path function_\".", "path": "docs/ru/docs/tutorial/middleware.md", "line": null, "side": "RIGHT", "created_at": "2025-02-25T18:26:37+00:00" }, { "id": 1970345741, "user": "user_6d7d83efab20", "body": "я исхожу из контекста, в данном контексте нужно переводить operation как функцию (тут проблем нет), а\npath как эндпоинт (это некорректно с точки зрения русского языка)\n\nвообще-то, если дословно, то \"path operation\" = \"функция пути\"", "path": "docs/ru/docs/tutorial/middleware.md", "line": null, "side": "RIGHT", "created_at": "2025-02-25T18:44:23+00:00" }, { "id": 1970360571, "user": "user_9e49ba0b4492", "body": "Исходя из предыдущих переводов я думал так:\n\"path operation\" = \"операция пути\" или \"эндпоинт\"\n\"path operation function\" = \"функция операции пути\" или \"функция эндпоинта\"", "path": "docs/ru/docs/tutorial/middleware.md", "line": null, "side": "RIGHT", "created_at": "2025-02-25T18:56:19+00:00" }, { "id": 1970367211, "user": "user_9e49ba0b4492", "body": "И под \"path operation\" подрузумевается вся вот эта конструкция:\n\n[USER_REDACTED].get(\"/\")\nasync def root():\n return {\"message\": \"[NAME_REDACTED]\"}\n\nгде `async def root()` является \"функцией операции пути\" или \"функцией эндпоинта\"", "path": "docs/ru/docs/tutorial/middleware.md", "line": null, "side": "RIGHT", "created_at": "2025-02-25T19:01:28+00:00" }, { "id": 1970506470, "user": "user_6d7d83efab20", "body": "[USER_REDACTED] , [USER_REDACTED], всё, я вас услышала, теперь понятно, что вы имеете в виду \nHello, World! : или место встречи изменить нельзя :smile:\n\nИсправляю на операцию пути. :smile:", "path": "docs/ru/docs/tutorial/middleware.md", "line": null, "side": "RIGHT", "created_at": "2025-02-25T20:35:52+00:00" }, { "id": 1973495316, "user": "user_9e49ba0b4492", "body": "* Затем передает **запрос** для последующей обработки (какой-либо *операцией пути*).", "path": "docs/ru/docs/tutorial/middleware.md", "line": null, "side": "RIGHT", "created_at": "2025-02-27T12:36:40+00:00" }, { "id": 1973497202, "user": "user_9e49ba0b4492", "body": "* Получает **ответ** (от *операции пути*).", "path": "docs/ru/docs/tutorial/middleware.md", "line": null, "side": "RIGHT", "created_at": "2025-02-27T12:37:09+00:00" }, { "id": 1973504129, "user": "user_9e49ba0b4492", "body": "* Затем она возвращает ответ `response`, сгенерированный *операцией пути*.", "path": "docs/ru/docs/tutorial/middleware.md", "line": null, "side": "RIGHT", "created_at": "2025-02-27T12:38:52+00:00" }, { "id": 1973943896, "user": "user_6d7d83efab20", "body": "[USER_REDACTED] \n\nendpoint -> url\npass operations -> набор функций/операций, обслуживающих запросы на определенный url\npass operation -> \"операция пути\" ~ \"операция эндпоинта\" ~ \"функция эндпоинта\"\npath operation decorator: `[USER_REDACTED].get(\"/\")`\npath operation function: `async def root()`", "path": "docs/ru/docs/tutorial/middleware.md", "line": null, "side": "RIGHT", "created_at": "2025-02-27T16:28:58+00:00" }, { "id": 1974056249, "user": "user_9e49ba0b4492", "body": "[USER_REDACTED] , здесь тоже надо слово \"запрос\" жирным выделить\n![2025-02-27_20-31](https://github.com/[USER_REDACTED]nts/assets/74806963-98f6-4b78-982a-500cfdd12f0e)", "path": "docs/ru/docs/tutorial/middleware.md", "line": null, "side": "RIGHT", "created_at": "2025-02-27T17:35:13+00:00" }, { "id": 1974065899, "user": "user_9e49ba0b4492", "body": "[USER_REDACTED] , разве мы не можем просто следующим образом переводить:\n- если в оригинале написано \"path operation\", то переводим \"операция пути\"\n- если в оригинале написано \"path operation function\", то переводим \"функция операции пути\"\n\n?", "path": "docs/ru/docs/tutorial/middleware.md", "line": null, "side": "RIGHT", "created_at": "2025-02-27T17:42:10+00:00" }, { "id": 1974100758, "user": "user_6d7d83efab20", "body": "[USER_REDACTED] \n1) можем, но это не всегда работает.\n2) операция пути не( самый )удачный термин, и в обычной жизни не используется\n3) и хочется объяснить более доступно, но не всегда получается :blush:", "path": "docs/ru/docs/tutorial/middleware.md", "line": null, "side": "RIGHT", "created_at": "2025-02-27T18:07:23+00:00" }, { "id": 1974121367, "user": "user_9e49ba0b4492", "body": "[USER_REDACTED] , но ведь мы можем пока придерживаться такой (пусть и не самой удачной) терминологии, просто чтобы везде было однообразно.\nИ потом если кому-то в голову придет более удачный термин, то тогда массово разом везде поправить.\nИ если везде будут одинаковые неудачные термины, то массово поправить будет легче, чем если они будут везде по-разному прописаны.", "path": "docs/ru/docs/tutorial/middleware.md", "line": null, "side": "RIGHT", "created_at": "2025-02-27T18:21:57+00:00" }, { "id": 1974479615, "user": "user_6d7d83efab20", "body": "[USER_REDACTED], мы такой стратегии и придерживаемся, разве нет? :smile:", "path": "docs/ru/docs/tutorial/middleware.md", "line": null, "side": "RIGHT", "created_at": "2025-02-27T23:16:53+00:00" } ], "meta": { "languages": [ "md" ], "touches_tests": false, "review_state_summary": { "COMMENTED": 30, "CHANGES_REQUESTED": 3, "APPROVED": 3 }, "meaningful_comment_count": 59, "has_approval": true, "has_changes_requested": true, "total_review_comments": 59 } } { "_id": "12b849048e8164b9", "_schema_version": "1.0", "_cleaned_at": "2026-02-12T07:46:51.766143+00:00", "repo": "tiangolo/fastapi", "repo_url": "https://github.com/fastapi/fastapi", "license_name": "MIT License", "license_spdx": "MIT", "pr_number": 13409, "title": "🌐 Add Ukrainian translation for `docs/uk/docs/tutorial/body-nested-models.md`", "body": null, "author": "user_c36c155012b4", "created_at": "2025-02-21T20:05:34+00:00", "merged_at": "2025-02-28T14:18:01+00:00", "base_branch": "master", "head_branch": "translation-uk/body-nested-models", "additions": 245, "deletions": 0, "changed_files": 1, "files": [ { "filename": "docs/uk/docs/tutorial/body-nested-models.md", "status": "added", "additions": 245, "deletions": 0, "changes": 245, "patch": "@@ -0,0 +1,245 @@\n+# Тіло запиту - Вкладені моделі\n+\n+З **FastAPI** Ви можете визначати, перевіряти, документувати та використовувати моделі, які можуть бути вкладені на будь-яку глибину (завдяки Pydantic).\n+\n+## Поля списку\n+\n+Ви можете визначити атрибут як підтип. Наприклад, Python-список (`list`):\n+\n+{* ../../docs_src/body_nested_models/tutorial001_py310.py hl[12] *}\n+\n+Це зробить `tags` списком, хоча не визначається тип елементів списку.\n+\n+## Поля списку з параметром типу\n+\n+Але Python має специфічний спосіб оголошення списків з внутрішніми типами або \"параметрами типу\":\n+### Імпортуємо `List` з модуля typing\n+\n+У Python 3.9 і вище можна використовувати стандартний `list` для оголошення таких типів, як ми побачимо нижче. 💡\n+\n+Але в Python версії до 3.9 (від 3.6 і вище) спочатку потрібно імпортувати `List` з модуля стандартної бібліотеки Python `typing`:\n+\n+{* ../../docs_src/body_nested_models/tutorial002.py hl[1] *}\n+\n+### Оголошення `list` з параметром типу\n+\n+Щоб оголосити типи з параметрами типу (внутрішніми типами), такими як `list`, `dict`, `tuple`:\n+\n+* Якщо Ви використовуєте версію Python до 3.9, імпортуйте їх відповідну версію з модуля `typing`.\n+* Передайте внутрішні типи як \"параметри типу\", використовуючи квадратні дужки: `[` and `]`.\n+\n+У Python 3.9 це буде виглядати так:\n+\n+```Python\n+my_list: list[str]\n+```\n+\n+У версіях Python до 3.9 це виглядає так:\n+\n+```Python\n+from typing import List\n+\n+my_list: List[str]\n+```\n+\n+Це стандартний синтаксис Python для оголошення типів.\n+\n+Використовуйте той самий стандартний синтаксис для атрибутів моделей з внутрішніми типами.\n+\n+Отже, у нашому прикладі, ми можемо зробити `tags` саме \"списком рядків\":\n+\n+{* ../../docs_src/body_nested_models/tutorial002_py310.py hl[12] *}\n+\n+## Типи множин\n+\n+Але потім ми подумали, що теги не повинні повторюватися, вони, ймовірно, повинні бути унікальними рядками.\n+\n+І Python має спеціальний тип даних для множин унікальних елементів — це `set`.\n+\n+Тому ми можемо оголосити `tags` як множину рядків:\n+\n+{* ../../docs_src/body_nested_models/tutorial003_py310.py hl[12] *}\n+\n+Навіть якщо Ви отримаєте запит з дубльованими даними, він буде перетворений у множину унікальних елементів.\n+\n+І коли Ви будете виводити ці дані, навіть якщо джерело містить дублікати, вони будуть виведені як множина унікальних елементів.\n+\n+І це буде анотовано/документовано відповідно.\n+\n+## Вкладені моделі\n+\n+Кожен атрибут моделі Pydantic має тип.\n+\n+Але цей тип сам може бути іншою моделлю Pydantic.\n+\n+Отже, Ви можете оголосити глибоко вкладені JSON \"об'єкти\" з конкретними іменами атрибутів, типами та перевірками.\n+\n+Усе це, вкладене без обмежень.\n+\n+### Визначення підмоделі\n+\n+Наприклад, ми можемо визначити модель `Image`:\n+\n+{* ../../docs_src/body_nested_models/tutorial004_py310.py hl[7:9] *}\n+\n+### Використання підмоделі як типу\n+\n+А потім ми можемо використовувати її як тип атрибута:\n+\n+{* ../../docs_src/body_nested_models/tutorial004_py310.py hl[18] *}\n+\n+Це означатиме, що **FastAPI** очікуватиме тіло запиту такого вигляду:\n+\n+```JSON\n+{\n+ \"name\": \"Foo\",\n+ \"description\": \"The pretender\",\n+ \"price\": 42.0,\n+ \"tax\": 3.2,\n+ \"tags\": [\"rock\", \"metal\", \"bar\"],\n+ \"image\": {\n+ \"url\": \"http://example.com/baz.jpg\",\n+ \"name\": \"The Foo live\"\n+ }\n+}\n+```\n+\n+Завдяки такій декларації у **FastAPI** Ви отримуєте:\n+\n+* Підтримку в редакторі (автозавершення тощо), навіть для вкладених моделей\n+* Конвертацію даних\n+* Валідацію даних\n+* Автоматичну документацію\n+\n+## Спеціальні типи та валідація\n+\n+Окрім звичайних типів, таких як `str`, `int`, `float`, та ін. Ви можете використовувати складніші типи, які наслідують `str`.\n+\n+Щоб побачити всі доступні варіанти, ознайомтеся з оглядом типів у Pydantic. Деякі приклади будуть у наступних розділах.\n+\n+Наприклад, у моделі `Image` є поле `url`, тому ми можемо оголосити його як `HttpUrl` від Pydantic замість `str`:\n+\n+{* ../../docs_src/body_nested_models/tutorial005_py310.py hl[2,8] *}\n+\n+Рядок буде перевірено як дійсну URL-адресу і задокументовано в JSON Schema / OpenAPI як URL.\n+\n+## Атрибути зі списками підмоделей\n+\n+У Pydantic Ви можете використовувати моделі як підтипи для `list`, `set` тощо:\n+\n+{* ../../docs_src/body_nested_models/tutorial006_py310.py hl[18] *}\n+\n+Це означає, що **FastAPI** буде очікувати (конвертувати, валідувати, документувати тощо) JSON тіло запиту у вигляді:\n+\n+```JSON hl_lines=\"11\"\n+{\n+ \"name\": \"Foo\",\n+ \"description\": \"The pretender\",\n+ \"price\": 42.0,\n+ \"tax\": 3.2,\n+ \"tags\": [\n+ \"rock\",\n+ \"metal\",\n+ \"bar\"\n+ ],\n+ \"images\": [\n+ {\n+ \"url\": \"http://example.com/baz.jpg\",\n+ \"name\": \"The Foo live\"\n+ },\n+ {\n+ \"url\": \"http://example.com/dave.jpg\",\n+ \"name\": \"The Baz\"\n+ }\n+ ]\n+}\n+```\n+\n+/// info | Інформація\n+\n+Зверніть увагу, що тепер ключ `images` містить список об'єктів зображень.\n+\n+///\n+\n+## Глибоко вкладені моделі\n+\n+Ви можете визначати вкладені моделі довільної глибини:\n+\n+{* ../../docs_src/body_nested_models/tutorial007_py310.py hl[7,12,18,21,25] *}\n+\n+/// info | Інформація\n+\n+Зверніть увагу, що в моделі `Offer` є список `Item`ів, які, своєю чергою, можуть мати необов'язковий список `Image`ів.\n+\n+///\n+\n+## Тіла запитів, що складаються зі списків\n+\n+Якщо верхній рівень JSON тіла, яке Ви очікуєте, є JSON `масивом` (у Python — `list`), Ви можете оголосити тип у параметрі функції, як і в моделях Pydantic:\n+\n+```Python\n+images: List[Image]\n+```\n+або в Python 3.9 і вище:\n+\n+```Python\n+images: list[Image]\n+```\n+\n+наприклад:\n+\n+{* ../../docs_src/body_nested_models/tutorial008_py39.py hl[13] *}\n+\n+## Підтримка в редакторі всюди\n+\n+Ви отримаєте підтримку в редакторі всюди.\n+\n+Навіть для елементів у списках:\n+\n+\n+\n+Ви не змогли б отримати таку підтримку в редакторі, якби працювали напряму зі `dict`, а не з моделями Pydantic.\n+\n+Але Вам не потрібно турбуватися про це: вхідні dict'и автоматично конвертуються, а вихідні дані автоматично перетворюються в JSON.\n+\n+## Тіла з довільними `dict`\n+\n+Ви також можете оголосити тіло як `dict` з ключами одного типу та значеннями іншого типу.\n+\n+Це корисно, якщо Ви не знаєте наперед, які імена полів будуть дійсними (як у випадку з моделями Pydantic).\n+\n+Це буде корисно, якщо Ви хочете приймати ключі, які заздалегідь невідомі.\n+\n+---\n+\n+Це також зручно, якщо Ви хочете мати ключі іншого типу (наприклад, `int`).\n+\n+Ось що ми розглянемо далі.\n+\n+У цьому випадку Ви можете приймати будь-який `dict`, якщо його ключі — це `int`, а значення — `float`:\n+\n+{* ../../docs_src/body_nested_models/tutorial009_py39.py hl[7] *}\n+\n+/// tip | Порада\n+\n+Майте на увазі, що в JSON тілі ключі можуть бути лише рядками (`str`).\n+\n+Але Pydantic автоматично конвертує дані.\n+\n+Це означає, що навіть якщо клієнти вашого API надсилатимуть ключі у вигляді рядків, якщо вони містять цілі числа, Pydantic конвертує їх і проведе валідацію.\n+\n+Тобто `dict`, який Ви отримаєте як `weights`, матиме ключі типу `int` та значення типу `float`.\n+\n+///\n+\n+## Підсумок\n+\n+З **FastAPI** Ви маєте максимальну гнучкість завдяки моделям Pydantic, зберігаючи при цьому код простим, коротким та елегантним.\n+\n+А також отримуєте всі переваги:\n+\n+* Підтримка в редакторі (автодоповнення всюди!)\n+* Конвертація даних (парсинг/сериалізація)\n+* Валідація даних\n+* Документація схем\n+* Автоматичне створення документації" } ], "reviews": [ { "id": 2634738524, "user": "user_489e2b951069", "state": "APPROVED", "body": null, "submitted_at": "2025-02-22T07:19:48+00:00" }, { "id": 2635682965, "user": "user_9ee0ae83e609", "state": "APPROVED", "body": null, "submitted_at": "2025-02-23T17:29:37+00:00" }, { "id": 2637536164, "user": "user_84458f05cf3c", "state": "COMMENTED", "body": "I did a quick sanity check to verify the structure of the document and compare the sections with the English version, and this looks good from a structural point of view.", "submitted_at": "2025-02-24T15:34:40+00:00" }, { "id": 2650884558, "user": "user_2a237e38e06b", "state": "APPROVED", "body": "Thank you [USER_REDACTED]! :cake: \n\nAnd thanks all for the reviews :coffee:", "submitted_at": "2025-02-28T14:17:33+00:00" } ], "review_comments": [ { "id": 1967879881, "user": "user_84458f05cf3c", "body": "```suggestion\n\n```\nRemove additional empty line", "path": "docs/uk/docs/tutorial/body-nested-models.md", "line": null, "side": "RIGHT", "created_at": "2025-02-24T15:30:24+00:00" } ], "meta": { "languages": [ "md" ], "touches_tests": false, "review_state_summary": { "APPROVED": 3, "COMMENTED": 1 }, "meaningful_comment_count": 1, "has_approval": true, "has_changes_requested": false, "total_review_comments": 1 } } { "_id": "377f4294600bd216", "_schema_version": "1.0", "_cleaned_at": "2026-02-12T07:46:51.766143+00:00", "repo": "tiangolo/fastapi", "repo_url": "https://github.com/fastapi/fastapi", "license_name": "MIT License", "license_spdx": "MIT", "pr_number": 13408, "title": "🌐 Add Ukrainian translation for `docs/uk/docs/tutorial/body-multiple-params.md`", "body": null, "author": "user_c36c155012b4", "created_at": "2025-02-21T18:44:52+00:00", "merged_at": "2025-02-28T14:19:00+00:00", "base_branch": "master", "head_branch": "translation-uk/body-multiple-params", "additions": 170, "deletions": 0, "changed_files": 1, "files": [ { "filename": "docs/uk/docs/tutorial/body-multiple-params.md", "status": "added", "additions": 170, "deletions": 0, "changes": 170, "patch": "@@ -0,0 +1,170 @@\n+# Тіло запиту - Декілька параметрів\n+\n+Тепер, коли ми розглянули використання `Path` та `Query`, розгляньмо більш просунуті способи оголошення тіла запиту в **FastAPI**.\n+\n+## Змішування `Path`, `Query` та параметрів тіла запиту\n+\n+По-перше, звісно, Ви можете вільно змішувати оголошення параметрів `Path`, `Query` та тіла запиту, і **FastAPI** правильно їх обробить.\n+\n+Також Ви можете оголосити параметри тіла як необов’язкові, встановивши для них значення за замовчуванням `None`:\n+\n+{* ../../docs_src/body_multiple_params/tutorial001_an_py310.py hl[18:20] *}\n+\n+/// note | Примітка\n+\n+Зверніть увагу, що в цьому випадку параметр `item`, який береться з тіла запиту, є необов'язковим, оскільки має значення за замовчуванням `None`.\n+\n+///\n+\n+## Декілька параметрів тіла запиту\n+\n+У попередньому прикладі *операція шляху* очікувала JSON з атрибутами `Item`, наприклад:\n+\n+```JSON\n+{\n+ \"name\": \"Foo\",\n+ \"description\": \"The pretender\",\n+ \"price\": 42.0,\n+ \"tax\": 3.2\n+}\n+```\n+Але Ви також можете оголосити декілька параметрів тіла, наприклад `item` та `user`:\n+\n+{* ../../docs_src/body_multiple_params/tutorial002_py310.py hl[20] *}\n+\n+У цьому випадку **FastAPI** розпізнає, що є кілька параметрів тіла (два параметри є моделями Pydantic).\n+\n+Тому він використає назви параметрів як ключі (назви полів) у тілі запиту, очікуючи:\n+\n+```JSON\n+{\n+ \"item\": {\n+ \"name\": \"Foo\",\n+ \"description\": \"The pretender\",\n+ \"price\": 42.0,\n+ \"tax\": 3.2\n+ },\n+ \"user\": {\n+ \"username\": \"dave\",\n+ \"full_name\": \"[NAME_REDACTED]\"\n+ }\n+}\n+```\n+\n+/// note | Примітка\n+\n+Зверніть увагу, що хоча `item` оголошено, так само як і раніше, тепер він очікується в тілі під ключем `item`.\n+\n+///\n+\n+**FastAPI** автоматично конвертує дані із запиту таким чином, щоб параметр `item` отримав свій вміст, і те ж саме стосується `user`.\n+\n+Він виконає валідацію складених даних і задокументує їх відповідним чином у схемі OpenAPI та в автоматичній документації.\n+\n+## Одиничні значення в тілі запиту\n+\n+Так само як є `Query` і `Path` для визначення додаткових даних для параметрів запиту та шляху, **FastAPI** надає еквівалентний `Body`.\n+\n+Наприклад, розширюючи попередню модель, Ви можете вирішити додати ще один ключ `importance` в те ж саме тіло запиту разом із `item` і `user`.\n+\n+Якщо Ви оголосите його як є, то, оскільки це одиничне значення, **FastAPI** припускатиме, що це параметр запиту (query parameter).\n+\n+Але Ви можете вказати **FastAPI** обробляти його як інший ключ тіла (body key), використовуючи `Body`:\n+\n+{* ../../docs_src/body_multiple_params/tutorial003_an_py310.py hl[23] *}\n+\n+У цьому випадку **FastAPI** очікуватиме тіло запиту у такому вигляді:\n+\n+```JSON\n+{\n+ \"item\": {\n+ \"name\": \"Foo\",\n+ \"description\": \"The pretender\",\n+ \"price\": 42.0,\n+ \"tax\": 3.2\n+ },\n+ \"user\": {\n+ \"username\": \"dave\",\n+ \"full_name\": \"[NAME_REDACTED]\"\n+ },\n+ \"importance\": 5\n+}\n+```\n+Знову ж таки, **FastAPI** конвертуватиме типи даних, перевірятиме їх, створюватиме документацію тощо.\n+\n+## Декілька body та query параметрів\n+\n+Звісно, Ви можете оголошувати додаткові query параметри запиту, коли це необхідно, на додаток до будь-яких параметрів тіла запиту.\n+\n+Оскільки за замовчуванням окремі значення інтерпретуються як параметри запиту, Вам не потрібно явно додавати `Query`, можна просто використати:\n+\n+```Python\n+q: Union[str, None] = None\n+```\n+\n+Або в Python 3.10 та вище:\n+\n+```Python\n+q: str | None = None\n+```\n+\n+Наприклад:\n+\n+{* ../../docs_src/body_multiple_params/tutorial004_an_py310.py hl[28] *}\n+\n+\n+/// info | Інформація\n+\n+`Body` також має ті самі додаткові параметри валідації та метаданих, що й `Query`, `Path` та інші, які Ви побачите пізніше.\n+\n+///\n+\n+## Вкладений поодинокий параметр тіла запиту\n+\n+Припустимо, у вас є лише один параметр тіла запиту `item` з моделі Pydantic `Item`.\n+\n+За замовчуванням **FastAPI** очікуватиме, що тіло запиту міститиме вміст безпосередньо.\n+\n+Але якщо Ви хочете, щоб він очікував JSON з ключем `item`, а всередині — вміст моделі (так, як це відбувається при оголошенні додаткових параметрів тіла), Ви можете використати спеціальний параметр `Body` — `embed`:\n+\n+```Python\n+item: Item = Body(embed=True)\n+```\n+\n+як у прикладі:\n+\n+{* ../../docs_src/body_multiple_params/tutorial005_an_py310.py hl[17] *}\n+\n+У цьому випадку **FastAPI** очікуватиме тіло запиту такого вигляду:\n+\n+```JSON hl_lines=\"2\"\n+{\n+ \"item\": {\n+ \"name\": \"Foo\",\n+ \"description\": \"The pretender\",\n+ \"price\": 42.0,\n+ \"tax\": 3.2\n+ }\n+}\n+```\n+\n+замість:\n+\n+```JSON\n+{\n+ \"name\": \"Foo\",\n+ \"description\": \"The pretender\",\n+ \"price\": 42.0,\n+ \"tax\": 3.2\n+}\n+```\n+\n+## Підсумок\n+\n+Ви можете додавати кілька параметрів тіла до Вашої *функції операції шляху* (*path operation function*), навіть якщо запит може мати лише одне тіло.\n+\n+Але **FastAPI** обробить це, надасть Вам потрібні дані у функції, перевірить їх та задокументує коректну схему в *операції шляху*.\n+\n+Також Ви можете оголошувати окремі значення, які будуть отримані як частина тіла запиту.\n+\n+Крім того, Ви можете вказати **FastAPI** вбудовувати тіло в ключ, навіть якщо оголошено лише один параметр." } ], "reviews": [ { "id": 2634738504, "user": "user_489e2b951069", "state": "APPROVED", "body": null, "submitted_at": "2025-02-22T07:19:39+00:00" }, { "id": 2635683183, "user": "user_9ee0ae83e609", "state": "APPROVED", "body": null, "submitted_at": "2025-02-23T17:30:54+00:00" }, { "id": 2637558641, "user": "user_84458f05cf3c", "state": "COMMENTED", "body": "Apart from a few very nitpicky comments, this all looks good from a structural point of view 👍", "submitted_at": "2025-02-24T15:39:15+00:00" }, { "id": 2637697899, "user": "user_c36c155012b4", "state": "COMMENTED", "body": null, "submitted_at": "2025-02-24T16:15:11+00:00" }, { "id": 2637708018, "user": "user_84458f05cf3c", "state": "COMMENTED", "body": null, "submitted_at": "2025-02-24T16:18:15+00:00" }, { "id": 2637709340, "user": "user_84458f05cf3c", "state": "COMMENTED", "body": null, "submitted_at": "2025-02-24T16:18:44+00:00" }, { "id": 2637748226, "user": "user_c36c155012b4", "state": "COMMENTED", "body": null, "submitted_at": "2025-02-24T16:33:00+00:00" }, { "id": 2650882478, "user": "user_2a237e38e06b", "state": "APPROVED", "body": "Thanks [USER_REDACTED]! :cake: \n\nAnd thanks all for the reviews :coffee:", "submitted_at": "2025-02-28T14:16:44+00:00" }, { "id": 2650937790, "user": "user_84458f05cf3c", "state": "COMMENTED", "body": null, "submitted_at": "2025-02-28T14:37:26+00:00" } ], "review_comments": [ { "id": 1967893151, "user": "user_84458f05cf3c", "body": "Here, it looks like a header is missing?\n\n```\n## Multiple body parameters\n```", "path": "docs/uk/docs/tutorial/body-multiple-params.md", "line": 12, "side": "RIGHT", "created_at": "2025-02-24T15:36:17+00:00" }, { "id": 1967896933, "user": "user_84458f05cf3c", "body": "```suggestion\nНаприклад, розширюючи попередню модель, Ви можете вирішити додати ще один ключ `importance` в те ж саме тіло запиту разом із `item` і `user`.\n```", "path": "docs/uk/docs/tutorial/body-multiple-params.md", "line": null, "side": "RIGHT", "created_at": "2025-02-24T15:37:17+00:00" }, { "id": 1967897972, "user": "user_84458f05cf3c", "body": "```suggestion\nАле Ви можете вказати **FastAPI** обробляти його як інший ключ тіла (body key), використовуючи `Body`:\n```", "path": "docs/uk/docs/tutorial/body-multiple-params.md", "line": null, "side": "RIGHT", "created_at": "2025-02-24T15:37:38+00:00" }, { "id": 1967976509, "user": "user_c36c155012b4", "body": "no, it's here. Just a bit below :)\n\nhttps://github.com/fastapi/fastapi/pull/13408/files#diff-aeab1bb090125e2209dac6208e8f8d2f0e8af15877ceef4757081232a7278200R19", "path": "docs/uk/docs/tutorial/body-multiple-params.md", "line": 12, "side": "RIGHT", "created_at": "2025-02-24T16:14:37+00:00" }, { "id": 1967982421, "user": "user_84458f05cf3c", "body": "Oh! Actually the English version has the title twice - we should probably correct it over there 😁 \n\n```\n## Multiple body parameters\n\n/// note\n\nNotice that, in this case, the `item` that would be taken from the body is optional. As it has a `None` default value.\n\n///\n\n## Multiple body parameters\n\nIn the previous example, ...\n```", "path": "docs/uk/docs/tutorial/body-multiple-params.md", "line": 12, "side": "RIGHT", "created_at": "2025-02-24T16:18:15+00:00" }, { "id": 1967983168, "user": "user_84458f05cf3c", "body": "So yea no change is necessary here!", "path": "docs/uk/docs/tutorial/body-multiple-params.md", "line": 12, "side": "RIGHT", "created_at": "2025-02-24T16:18:44+00:00" }, { "id": 1968006540, "user": "user_c36c155012b4", "body": "I guess you are looking at the old `en` version. I pulled the latest master updates and see that header only repeats once in a file", "path": "docs/uk/docs/tutorial/body-multiple-params.md", "line": 12, "side": "RIGHT", "created_at": "2025-02-24T16:33:00+00:00" }, { "id": 1975520957, "user": "user_84458f05cf3c", "body": "Right you are (again), this was fixed recently and I was looking at a local outdated `master`: https://github.com/fastapi/fastapi/pull/13345", "path": "docs/uk/docs/tutorial/body-multiple-params.md", "line": 12, "side": "RIGHT", "created_at": "2025-02-28T14:37:25+00:00" } ], "meta": { "languages": [ "md" ], "touches_tests": false, "review_state_summary": { "APPROVED": 3, "COMMENTED": 6 }, "meaningful_comment_count": 8, "has_approval": true, "has_changes_requested": false, "total_review_comments": 8 } } { "_id": "75e7f7aaf7cb7090", "_schema_version": "1.0", "_cleaned_at": "2026-02-12T07:46:51.766143+00:00", "repo": "tiangolo/fastapi", "repo_url": "https://github.com/fastapi/fastapi", "license_name": "MIT License", "license_spdx": "MIT", "pr_number": 13407, "title": "🌐 Add Vietnamese translation for `docs/vi/docs/deployment/cloud.md`", "body": null, "author": "user_d1761bc35b59", "created_at": "2025-02-21T15:54:44+00:00", "merged_at": "2025-03-07T03:24:13+00:00", "base_branch": "master", "head_branch": "docs/vi-cloud", "additions": 17, "deletions": 0, "changed_files": 1, "files": [ { "filename": "docs/vi/docs/deployment/cloud.md", "status": "added", "additions": 17, "deletions": 0, "changes": 17, "patch": "@@ -0,0 +1,17 @@\n+# Triển khai FastAPI trên các Dịch vụ Cloud\n+\n+Bạn có thể sử dụng **bất kỳ nhà cung cấp dịch vụ cloud** nào để triển khai ứng dụng FastAPI của mình.\n+\n+Trong hầu hết các trường hợp, các nhà cung cấp dịch vụ cloud lớn đều có hướng dẫn triển khai FastAPI với họ.\n+\n+## Nhà cung cấp dịch vụ Cloud - Nhà tài trợ\n+Một vài nhà cung cấp dịch vụ cloud ✨ [**tài trợ cho FastAPI**](../help-fastapi.md#sponsor-the-author){.internal-link target=_blank} ✨, điều này giúp đảm bảo sự phát triển liên tục và khỏe mạnh của FastAPI và hệ sinh thái của nó.\n+\n+Thêm nữa, điều này cũng thể hiện cam kết thực sự của họ đối với FastAPI và **cộng đồng người dùng** (bạn), vì họ không chỉ muốn cung cấp cho bạn một **dịch vụ tốt** mà còn muốn đảm bảo rằng bạn có một **framework tốt và bền vững**, đó chính là FastAPI. 🙇\n+\n+Bạn có thể thử các dịch vụ của họ và làm theo hướng dẫn của họ:\n+\n+* Platform.sh\n+* Porter\n+* Coherence\n+* Render" } ], "reviews": [ { "id": 2635910721, "user": "user_44c38cbd7a54", "state": "APPROVED", "body": null, "submitted_at": "2025-02-24T01:59:29+00:00" }, { "id": 2635913039, "user": "user_a87b9d843ca8", "state": "APPROVED", "body": null, "submitted_at": "2025-02-24T02:04:31+00:00" }, { "id": 2637613688, "user": "user_84458f05cf3c", "state": "COMMENTED", "body": null, "submitted_at": "2025-02-24T15:50:02+00:00" }, { "id": 2652487866, "user": "user_d1761bc35b59", "state": "COMMENTED", "body": null, "submitted_at": "2025-03-01T14:29:19+00:00" }, { "id": 2660599180, "user": "user_9d11b14955d3", "state": "COMMENTED", "body": "I think it will be better with this", "submitted_at": "2025-03-05T10:12:11+00:00" }, { "id": 2663485438, "user": "user_9d11b14955d3", "state": "APPROVED", "body": "LGTM!", "submitted_at": "2025-03-06T06:45:40+00:00" }, { "id": 2666151507, "user": "user_2a237e38e06b", "state": "APPROVED", "body": "Thank you [USER_REDACTED]! :cake: \n\nThanks all for the reviews! :coffee:", "submitted_at": "2025-03-07T03:23:54+00:00" } ], "review_comments": [ { "id": 1967928591, "user": "user_84458f05cf3c", "body": "```suggestion\n# Triển khai FastAPI trên các Dịch vụ Cloud\n```\nI assume the second line is the correct translation for the original English line, which should be deleted?", "path": "docs/vi/docs/deployment/cloud.md", "line": null, "side": "RIGHT", "created_at": "2025-02-24T15:49:21+00:00" }, { "id": 1976429597, "user": "user_d1761bc35b59", "body": "Thank you, that's it", "path": "docs/vi/docs/deployment/cloud.md", "line": null, "side": "RIGHT", "created_at": "2025-03-01T14:29:19+00:00" }, { "id": 1981087561, "user": "user_9d11b14955d3", "body": "```suggestion\nMột vài nhà cung cấp dịch vụ cloud ✨ [**tài trợ cho FastAPI**](../help-fastapi.md#sponsor-the-author){.internal-link target=_blank} ✨, điều này giúp đảm bảo sự phát triển liên tục và khỏe mạnh của FastAPI và hệ sinh thái của nó.\n```", "path": "docs/vi/docs/deployment/cloud.md", "line": null, "side": "RIGHT", "created_at": "2025-03-05T10:07:38+00:00" }, { "id": 1981089172, "user": "user_9d11b14955d3", "body": "```suggestion\nTrong hầu hết các trường hợp, các nhà cung cấp dịch vụ cloud lớn đều có hướng dẫn triển khai FastAPI với họ.\n```", "path": "docs/vi/docs/deployment/cloud.md", "line": null, "side": "RIGHT", "created_at": "2025-03-05T10:08:40+00:00" }, { "id": 1981090930, "user": "user_9d11b14955d3", "body": "```suggestion\nBạn có thể thử các dịch vụ của họ và làm theo hướng dẫn của họ:\n```", "path": "docs/vi/docs/deployment/cloud.md", "line": null, "side": "RIGHT", "created_at": "2025-03-05T10:09:45+00:00" }, { "id": 1981092658, "user": "user_9d11b14955d3", "body": "```suggestion\nThêm nữa, điều này cũng thể hiện cam kết thực sự của họ đối với FastAPI và **cộng đồng người dùng** (bạn), vì họ không chỉ muốn cung cấp cho bạn một **dịch vụ tốt** mà còn muốn đảm bảo rằng bạn có một **framework tốt và bền vững**, đó chính là FastAPI. 🙇\n```", "path": "docs/vi/docs/deployment/cloud.md", "line": null, "side": "RIGHT", "created_at": "2025-03-05T10:10:55+00:00" } ], "meta": { "languages": [ "md" ], "touches_tests": false, "review_state_summary": { "APPROVED": 4, "COMMENTED": 3 }, "meaningful_comment_count": 6, "has_approval": true, "has_changes_requested": false, "total_review_comments": 6 } } { "_id": "09448647549f94da", "_schema_version": "1.0", "_cleaned_at": "2026-02-12T07:46:51.766143+00:00", "repo": "tiangolo/fastapi", "repo_url": "https://github.com/fastapi/fastapi", "license_name": "MIT License", "license_spdx": "MIT", "pr_number": 13384, "title": "🌐 Add Ukrainian translation for `docs/uk/docs/tutorial/request-form-models.md`", "body": null, "author": "user_c36c155012b4", "created_at": "2025-02-18T04:07:53+00:00", "merged_at": "2025-02-20T14:16:10+00:00", "base_branch": "master", "head_branch": "translation-uk/request-form-models", "additions": 78, "deletions": 0, "changed_files": 1, "files": [ { "filename": "docs/uk/docs/tutorial/request-form-models.md", "status": "added", "additions": 78, "deletions": 0, "changes": 78, "patch": "@@ -0,0 +1,78 @@\n+# Моделі форм ([NAME_REDACTED])\n+\n+У FastAPI Ви можете використовувати **Pydantic-моделі** для оголошення **полів форми**.\n+\n+/// info | Інформація\n+\n+Щоб використовувати форми, спочатку встановіть python-multipart.\n+\n+Переконайтеся, що Ви створили [віртуальне середовище](../virtual-environments.md){.internal-link target=_blank}, активували його, а потім встановили бібліотеку, наприклад:\n+\n+```console\n+$ pip install python-multipart\n+```\n+\n+///\n+\n+/// note | Підказка\n+\n+Ця функція підтримується, починаючи з FastAPI версії `0.113.0`. 🤓\n+\n+///\n+\n+## Використання Pydantic-моделей для форм\n+\n+Вам просто потрібно оголосити **Pydantic-модель** з полями, які Ви хочете отримати як **поля форми**, а потім оголосити параметр як `Form`:\n+\n+{* ../../docs_src/request_form_models/tutorial001_an_py39.py hl[9:11,15] *}\n+\n+**FastAPI** **витягне** дані для **кожного поля** з **формових даних** у запиті та надасть вам Pydantic-модель, яку Ви визначили.\n+\n+## Перевірка документації\n+\n+Ви можете перевірити це в UI документації за `/docs`:\n+\n+
      \n+\n+
      \n+\n+## Заборона додаткових полів форми\n+\n+У деяких особливих випадках (ймовірно, рідко) Ви можете **обмежити** форму лише тими полями, які були оголошені в Pydantic-моделі, і **заборонити** будь-які **додаткові** поля.\n+\n+/// note | Підказка\n+\n+Ця функція підтримується, починаючи з FastAPI версії `0.114.0`. 🤓\n+\n+///\n+\n+Ви можете використати конфігурацію Pydantic-моделі, щоб заборонити `forbid` будь-які додаткові `extra` поля:\n+\n+{* ../../docs_src/request_form_models/tutorial002_an_py39.py hl[12] *}\n+\n+Якщо клієнт спробує надіслати додаткові дані, він отримає **відповідь з помилкою**.\n+\n+Наприклад, якщо клієнт спробує надіслати наступні поля форми:\n+\n+* `username`: `Rick`\n+* `password`: `[NAME_REDACTED]`\n+* `extra`: `Mr. Poopybutthole`\n+\n+Він отримає відповідь із помилкою, яка повідомляє, що поле `extra` не дозволено:\n+\n+```json\n+{\n+ \"detail\": [\n+ {\n+ \"type\": \"extra_forbidden\",\n+ \"loc\": [\"body\", \"extra\"],\n+ \"msg\": \"Extra inputs are not permitted\",\n+ \"input\": \"Mr. Poopybutthole\"\n+ }\n+ ]\n+}\n+```\n+\n+## Підсумок\n+\n+Ви можете використовувати Pydantic-моделі для оголошення полів форми у FastAPI. 😎" } ], "reviews": [ { "id": 2623530271, "user": "user_489e2b951069", "state": "APPROVED", "body": null, "submitted_at": "2025-02-18T13:12:47+00:00" }, { "id": 2624970530, "user": "user_9ee0ae83e609", "state": "CHANGES_REQUESTED", "body": "Good job! Please update a couple of places (we usually use `Ви` with the proper case in translations)", "submitted_at": "2025-02-18T20:36:10+00:00" }, { "id": 2624977732, "user": "user_9ee0ae83e609", "state": "COMMENTED", "body": null, "submitted_at": "2025-02-18T20:37:04+00:00" }, { "id": 2624978258, "user": "user_9ee0ae83e609", "state": "CHANGES_REQUESTED", "body": null, "submitted_at": "2025-02-18T20:37:32+00:00" }, { "id": 2627858556, "user": "user_9ee0ae83e609", "state": "APPROVED", "body": null, "submitted_at": "2025-02-19T20:01:13+00:00" } ], "review_comments": [ { "id": 1960553562, "user": "user_9ee0ae83e609", "body": "```suggestion\nВам просто потрібно оголосити **Pydantic-модель** з полями, які Ви хочете отримати як **поля форми**, а потім оголосити параметр як `Form`:\n```", "path": "docs/uk/docs/tutorial/request-form-models.md", "line": null, "side": "RIGHT", "created_at": "2025-02-18T20:33:04+00:00" }, { "id": 1960554020, "user": "user_9ee0ae83e609", "body": "```suggestion\n**FastAPI** **витягне** дані для **кожного поля** з **формових даних** у запиті та надасть вам Pydantic-модель, яку Ви визначили.\n```", "path": "docs/uk/docs/tutorial/request-form-models.md", "line": null, "side": "RIGHT", "created_at": "2025-02-18T20:33:23+00:00" }, { "id": 1960554479, "user": "user_9ee0ae83e609", "body": "```suggestion\nУ деяких особливих випадках (ймовірно, рідко) Ви можете **обмежити** форму лише тими полями, які були оголошені в Pydantic-моделі, і **заборонити** будь-які **додаткові** поля.\n```", "path": "docs/uk/docs/tutorial/request-form-models.md", "line": null, "side": "RIGHT", "created_at": "2025-02-18T20:33:48+00:00" }, { "id": 1960558036, "user": "user_9ee0ae83e609", "body": "```suggestion\nУ FastAPI Ви можете використовувати **Pydantic-моделі** для оголошення **полів форми**.\n```", "path": "docs/uk/docs/tutorial/request-form-models.md", "line": null, "side": "RIGHT", "created_at": "2025-02-18T20:37:04+00:00" }, { "id": 1960558348, "user": "user_9ee0ae83e609", "body": "```suggestion\nПереконайтеся, що Ви створили [віртуальне середовище](../virtual-environments.md){.internal-link target=_blank}, активували його, а потім встановили бібліотеку, наприклад:\n```", "path": "docs/uk/docs/tutorial/request-form-models.md", "line": null, "side": "RIGHT", "created_at": "2025-02-18T20:37:21+00:00" } ], "meta": { "languages": [ "md" ], "touches_tests": false, "review_state_summary": { "APPROVED": 2, "CHANGES_REQUESTED": 2, "COMMENTED": 1 }, "meaningful_comment_count": 5, "has_approval": true, "has_changes_requested": true, "total_review_comments": 5 } } { "_id": "69f00fa99f9b4b25", "_schema_version": "1.0", "_cleaned_at": "2026-02-12T07:46:51.766143+00:00", "repo": "tiangolo/fastapi", "repo_url": "https://github.com/fastapi/fastapi", "license_name": "MIT License", "license_spdx": "MIT", "pr_number": 13383, "title": "🌐 Add Ukrainian translation for `docs/uk/docs/tutorial/request-forms.md`", "body": null, "author": "user_c36c155012b4", "created_at": "2025-02-18T03:58:13+00:00", "merged_at": "2025-02-28T14:13:50+00:00", "base_branch": "master", "head_branch": "translation-uk/request-forms", "additions": 73, "deletions": 0, "changed_files": 1, "files": [ { "filename": "docs/uk/docs/tutorial/request-forms.md", "status": "added", "additions": 73, "deletions": 0, "changes": 73, "patch": "@@ -0,0 +1,73 @@\n+# Дані форми\n+\n+Якщо Вам потрібно отримувати поля форми замість JSON, Ви можете використовувати `Form`.\n+\n+/// info | Інформація\n+\n+Щоб використовувати форми, спочатку встановіть `python-multipart`.\n+\n+Переконайтеся, що Ви створили [віртуальне середовище](../virtual-environments.md){.internal-link target=_blank}, активували його, і потім встановили бібліотеку, наприклад:\n+\n+```console\n+$ pip install python-multipart\n+```\n+\n+///\n+\n+## Імпорт `Form`\n+\n+Імпортуйте `Form` з `fastapi`:\n+\n+{* ../../docs_src/request_forms/tutorial001_an_py39.py hl[3] *}\n+\n+## Оголошення параметрів `Form`\n+\n+Створюйте параметри форми так само як Ви б створювали `Body` або `Query`:\n+\n+{* ../../docs_src/request_forms/tutorial001_an_py39.py hl[9] *}\n+\n+Наприклад, один зі способів використання специфікації OAuth2 (так званий \"password flow\") вимагає надсилати `username` та `password` як поля форми.\n+\n+spec вимагає, щоб ці поля мали точні назви `username` і `password` та надсилалися у вигляді полів форми, а не JSON.\n+\n+З `Form` Ви можете оголошувати ті ж конфігурації, що і з `Body` (та `Query`, `Path`, `Cookie`), включаючи валідацію, приклади, псевдоніми (наприклад, `user-name` замість `username`) тощо.\n+\n+/// info | Інформація\n+\n+`Form` — це клас, який безпосередньо наслідується від `Body`.\n+\n+///\n+\n+/// tip | Порада\n+\n+Щоб оголосити тіло форми, потрібно явно використовувати `Form`, оскільки без нього параметри будуть інтерпретуватися як параметри запиту або тіла (JSON).\n+\n+///\n+\n+## Про \"поля форми\"\n+\n+HTML-форми (`
      `) надсилають дані на сервер у \"спеціальному\" кодуванні, яке відрізняється від JSON.\n+\n+**FastAPI** подбає про те, щоб зчитати ці дані з правильного місця, а не з JSON.\n+\n+/// note | Технічні деталі\n+\n+Дані з форм зазвичай кодуються за допомогою \"типу медіа\" `application/x-www-form-urlencoded`.\n+\n+Але якщо форма містить файли, вона кодується як `multipart/form-data`. Ви дізнаєтеся про обробку файлів у наступному розділі.\n+\n+Якщо Ви хочете дізнатися більше про ці кодування та поля форм, зверніться до MDN вебдокументації для POST.\n+\n+///\n+\n+/// warning | Попередження\n+\n+Ви можете оголосити кілька параметрів `Form` в *операції шляху*, але не можете одночасно оголосити поля `Body`, які Ви очікуєте отримати у форматі JSON, оскільки тіло запиту буде закодовано у форматі `application/x-www-form-urlencoded`, а не `application/json`.\n+\n+Це не обмеження **FastAPI**, а частина HTTP-протоколу.\n+\n+///\n+\n+## Підсумок\n+\n+Використовуйте `Form` для оголошення вхідних параметрів у вигляді даних форми." } ], "reviews": [ { "id": 2624978747, "user": "user_9ee0ae83e609", "state": "CHANGES_REQUESTED", "body": "Great job! could you pls make a little update as I requested in comments", "submitted_at": "2025-02-18T20:40:37+00:00" }, { "id": 2625294185, "user": "user_dac146a60e0c", "state": "APPROVED", "body": null, "submitted_at": "2025-02-18T23:47:49+00:00" }, { "id": 2627851976, "user": "user_9ee0ae83e609", "state": "APPROVED", "body": null, "submitted_at": "2025-02-19T19:57:51+00:00" }, { "id": 2637636868, "user": "user_84458f05cf3c", "state": "COMMENTED", "body": "Looking good from a purely structural point of view! 🥳", "submitted_at": "2025-02-24T15:54:56+00:00" }, { "id": 2650874337, "user": "user_2a237e38e06b", "state": "APPROVED", "body": "Thanks [USER_REDACTED]! :cake: \n\nAnd thanks for the reviews [USER_REDACTED], [USER_REDACTED], [USER_REDACTED] :coffee:", "submitted_at": "2025-02-28T14:13:34+00:00" } ], "review_comments": [ { "id": 1960558635, "user": "user_9ee0ae83e609", "body": "```suggestion\nЯкщо Вам потрібно отримувати поля форми замість JSON, Ви можете використовувати `Form`.\n```", "path": "docs/uk/docs/tutorial/request-forms.md", "line": null, "side": "RIGHT", "created_at": "2025-02-18T20:37:37+00:00" }, { "id": 1960558840, "user": "user_9ee0ae83e609", "body": "```suggestion\nПереконайтеся, що Ви створили [віртуальне середовище](../virtual-environments.md){.internal-link target=_blank}, активували його, і потім встановили бібліотеку, наприклад:\n```", "path": "docs/uk/docs/tutorial/request-forms.md", "line": null, "side": "RIGHT", "created_at": "2025-02-18T20:37:48+00:00" }, { "id": 1960559093, "user": "user_9ee0ae83e609", "body": "```suggestion\nСтворюйте параметри форми так само як Ви б створювали `Body` або `Query`:\n```", "path": "docs/uk/docs/tutorial/request-forms.md", "line": null, "side": "RIGHT", "created_at": "2025-02-18T20:38:01+00:00" }, { "id": 1960559613, "user": "user_9ee0ae83e609", "body": "```suggestion\nЗ `Form` Ви можете оголошувати ті ж конфігурації, що і з `Body` (та `Query`, `Path`, `Cookie`), включаючи валідацію, приклади, псевдоніми (наприклад, `user-name` замість `username`) тощо.\n```", "path": "docs/uk/docs/tutorial/request-forms.md", "line": null, "side": "RIGHT", "created_at": "2025-02-18T20:38:30+00:00" }, { "id": 1960560591, "user": "user_9ee0ae83e609", "body": "```suggestion\nЯкщо Ви хочете дізнатися більше про ці кодування та поля форм, зверніться до MDN вебдокументації для POST.\n```", "path": "docs/uk/docs/tutorial/request-forms.md", "line": null, "side": "RIGHT", "created_at": "2025-02-18T20:39:27+00:00" }, { "id": 1960560901, "user": "user_9ee0ae83e609", "body": "```suggestion\nВи можете оголосити кілька параметрів `Form` в *операції шляху*, але не можете одночасно оголосити поля `Body`, які Ви очікуєте отримати у форматі JSON, оскільки тіло запиту буде закодовано у форматі `application/x-www-form-urlencoded`, а не `application/json`.\n```", "path": "docs/uk/docs/tutorial/request-forms.md", "line": null, "side": "RIGHT", "created_at": "2025-02-18T20:39:45+00:00" } ], "meta": { "languages": [ "md" ], "touches_tests": false, "review_state_summary": { "CHANGES_REQUESTED": 1, "APPROVED": 3, "COMMENTED": 1 }, "meaningful_comment_count": 6, "has_approval": true, "has_changes_requested": true, "total_review_comments": 6 } } { "_id": "30669e9e05d3def1", "_schema_version": "1.0", "_cleaned_at": "2026-02-12T07:46:51.766143+00:00", "repo": "tiangolo/fastapi", "repo_url": "https://github.com/fastapi/fastapi", "license_name": "MIT License", "license_spdx": "MIT", "pr_number": 13381, "title": "🌐 Add Ukrainian translation for `docs/uk/docs/tutorial/header-params.md`", "body": null, "author": "user_c36c155012b4", "created_at": "2025-02-16T14:20:06+00:00", "merged_at": "2025-02-22T22:02:19+00:00", "base_branch": "master", "head_branch": "translation-uk/header-params", "additions": 91, "deletions": 0, "changed_files": 1, "files": [ { "filename": "docs/uk/docs/tutorial/header-params.md", "status": "added", "additions": 91, "deletions": 0, "changes": 91, "patch": "@@ -0,0 +1,91 @@\n+# Header-параметри\n+\n+Ви можете визначати параметри заголовків, так само як визначаєте `Query`, `Path` і `Cookie` параметри.\n+\n+## Імпорт `Header`\n+\n+Спочатку імпортуйте `Header`:\n+\n+{* ../../docs_src/header_params/tutorial001_an_py310.py hl[3] *}\n+\n+## Оголошення параметрів `Header`\n+\n+Потім оголосіть параметри заголовків, використовуючи ту ж структуру, що й для `Path`, `Query` та `Cookie`.\n+\n+Ви можете визначити значення за замовчуванням, а також усі додаткові параметри валідації або анотації:\n+\n+{* ../../docs_src/header_params/tutorial001_an_py310.py hl[9] *}\n+\n+/// note | Технічні деталі\n+\n+`Header`є \"сестринським\" класом для `Path`, `Query` і `Cookie`. Він також успадковується від загального класу `Param`.\n+\n+Але пам’ятайте, що при імпорті `Query`, `Path`, `Header` та інших із `fastapi`, то насправді вони є функціями, які повертають спеціальні класи.\n+\n+///\n+\n+/// info | Інформація\n+\n+Щоб оголосити заголовки, потрібно використовувати `Header`, інакше параметри будуть інтерпретуватися як параметри запиту.\n+\n+///\n+\n+## Автоматичне перетворення\n+\n+`Header` має додатковий функціонал порівняно з `Path`, `Query` та `Cookie`.\n+\n+Більшість стандартних заголовків розділяються символом «дефіс», також відомим як «мінус» (`-`).\n+\n+Але змінна, така як `user-agent`, є недійсною в Python.\n+\n+Тому, за замовчуванням, `Header` автоматично перетворює символи підкреслення (`_`) на дефіси (`-`) для отримання та документування заголовків.\n+\n+Оскільки заголовки HTTP не чутливі до регістру, Ви можете використовувати стандартний стиль Python (\"snake_case\").\n+\n+Тому Ви можете використовувати `user_agent`, як зазвичай у коді Python, замість того щоб писати з великої літери, як `User_Agent` або щось подібне.\n+\n+Якщо Вам потрібно вимкнути автоматичне перетворення підкреслень у дефіси, встановіть `convert_underscores` в `Header` значення `False`:\n+\n+{* ../../docs_src/header_params/tutorial002_an_py310.py hl[10] *}\n+\n+/// warning | Увага\n+\n+Перед тим як встановити значення `False` для `convert_underscores` пам’ятайте, що деякі HTTP-проксі та сервери не підтримують заголовки з підкресленнями.\n+\n+///\n+\n+## Дубльовані заголовки\n+\n+Можливо отримати дубльовані заголовки, тобто той самий заголовок із кількома значеннями.\n+\n+Це можна визначити, використовуючи список у типізації параметра.\n+\n+Ви отримаєте всі значення дубльованого заголовка у вигляді `list` у Python.\n+\n+Наприклад, щоб оголосити заголовок `X-Token`, який може з’являтися більше ніж один раз:\n+\n+{* ../../docs_src/header_params/tutorial003_an_py310.py hl[9] *}\n+\n+Якщо Ви взаємодієте з цією операцією шляху, надсилаючи два HTTP-заголовки, наприклад:\n+\n+```\n+X-Token: foo\n+X-Token: bar\n+```\n+\n+Відповідь буде така:\n+\n+```JSON\n+{\n+ \"X-Token values\": [\n+ \"bar\",\n+ \"foo\"\n+ ]\n+}\n+```\n+\n+## Підсумок\n+\n+Оголошуйте заголовки за допомогою `Header`, використовуючи той самий підхід, що й для `Query`, `Path` та `Cookie`.\n+\n+Не хвилюйтеся про підкреслення у змінних — **FastAPI** автоматично конвертує їх." } ], "reviews": [ { "id": 2623522937, "user": "user_489e2b951069", "state": "APPROVED", "body": null, "submitted_at": "2025-02-18T13:10:39+00:00" }, { "id": 2624985703, "user": "user_9ee0ae83e609", "state": "CHANGES_REQUESTED", "body": null, "submitted_at": "2025-02-18T20:42:23+00:00" }, { "id": 2627859655, "user": "user_9ee0ae83e609", "state": "APPROVED", "body": null, "submitted_at": "2025-02-19T20:01:49+00:00" } ], "review_comments": [ { "id": 1960563019, "user": "user_9ee0ae83e609", "body": "```suggestion\nОскільки заголовки HTTP не чутливі до регістру, Ви можете використовувати стандартний стиль Python (\"snake_case\").\n```", "path": "docs/uk/docs/tutorial/header-params.md", "line": null, "side": "RIGHT", "created_at": "2025-02-18T20:41:31+00:00" }, { "id": 1960563194, "user": "user_9ee0ae83e609", "body": "```suggestion\nТому Ви можете використовувати `user_agent`, як зазвичай у коді Python, замість того щоб писати з великої літери, як `User_Agent` або щось подібне.\n```", "path": "docs/uk/docs/tutorial/header-params.md", "line": null, "side": "RIGHT", "created_at": "2025-02-18T20:41:41+00:00" }, { "id": 1960563390, "user": "user_9ee0ae83e609", "body": "```suggestion\nЯкщо Вам потрібно вимкнути автоматичне перетворення підкреслень у дефіси, встановіть `convert_underscores` в `Header` значення `False`:\n```", "path": "docs/uk/docs/tutorial/header-params.md", "line": null, "side": "RIGHT", "created_at": "2025-02-18T20:41:51+00:00" }, { "id": 1960563798, "user": "user_9ee0ae83e609", "body": "```suggestion\nЯкщо Ви взаємодієте з цією операцією шляху, надсилаючи два HTTP-заголовки, наприклад:\n```", "path": "docs/uk/docs/tutorial/header-params.md", "line": null, "side": "RIGHT", "created_at": "2025-02-18T20:42:14+00:00" } ], "meta": { "languages": [ "md" ], "touches_tests": false, "review_state_summary": { "APPROVED": 2, "CHANGES_REQUESTED": 1 }, "meaningful_comment_count": 4, "has_approval": true, "has_changes_requested": true, "total_review_comments": 4 } } { "_id": "8b68b3a20c3a0ef0", "_schema_version": "1.0", "_cleaned_at": "2026-02-12T07:46:51.781247+00:00", "repo": "pandas-dev/pandas", "repo_url": "https://github.com/pandas-dev/pandas", "license_name": "BSD 3-Clause \"New\" or \"Revised\" License", "license_spdx": "BSD-3-Clause", "pr_number": 64104, "title": "BUG: fix regression in DataFrame construction from list of dicts with missing value as key", "body": "- [x] closes #63889\n- [ ] [Tests added and passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#writing-tests) \n- [x] Added an entry in the latest `doc/source/whatsnew/vX.X.X.rst` file if fixing a bug or adding a new feature.\n\nNote that this does _not_ fix the corner-case of having more than one missing value indicator in the dictionary (eg entries with both None and pd.NA as key)", "author": "user_7213a217ace7", "created_at": "2026-02-10T09:56:40+00:00", "merged_at": "2026-02-10T17:45:22+00:00", "base_branch": "main", "head_branch": "63889-fix-dataframe-constructor-dict-missing", "additions": 80, "deletions": 5, "changed_files": 4, "files": [ { "filename": "doc/source/whatsnew/v3.0.1.rst", "status": "modified", "additions": 1, "deletions": 0, "changes": 1, "patch": "@@ -14,6 +14,7 @@ including other versions of pandas.\n Fixed regressions\n ~~~~~~~~~~~~~~~~~\n - Fixed regression in :meth:`DataFrame.groupby` and :meth:`Series.groupby` when grouping on categorical data with NA values, ``observed=False``, and ``dropna=True`` (:issue:`52445`)\n+- Fixed regression in the :class:`DataFrame` and :meth:`DataFrame.from_records` constructor with a list of dicts with a missing value indicator as key (:issue:`63889`)\n - Fixed regression when calling ``numpy.random``'s ``permutation()`` on a (pyarrow-backed) string :class:`Series` (:issue:`63935`)\n \n .. ---------------------------------------------------------------------------" }, { "filename": "pandas/core/internals/construction.py", "status": "modified", "additions": 21, "deletions": 5, "changes": 26, "patch": "@@ -58,6 +58,7 @@\n from pandas.core.indexes.api import (\n DatetimeIndex,\n Index,\n+ MultiIndex,\n TimedeltaIndex,\n default_index,\n ensure_index,\n@@ -580,7 +581,17 @@ def _homogenize(\n else:\n # see test_constructor_subclass_dict\n val = dict(val)\n- val = lib.fast_multiget(val, oindex._values, default=np.nan)\n+\n+ if not isinstance(index, MultiIndex) and index.hasnans:\n+ # GH#63889 Check if dict has missing value keys that need special\n+ # handling (i.e. None/np.nan/pd.NA might no longer be matched\n+ # when using fast_multiget with processed object index values)\n+ from pandas import Series\n+\n+ val = Series(val).reindex(index)._values\n+ else:\n+ # Fast path: use lib.fast_multiget for dicts without missing keys\n+ val = lib.fast_multiget(val, oindex._values, default=np.nan)\n \n val = sanitize_array(val, index, dtype=dtype, copy=False)\n com.require_length_match(val, index)\n@@ -867,17 +878,22 @@ def _list_of_dict_to_arrays(\n content : np.ndarray[object, ndim=2]\n columns : Index\n \"\"\"\n+ # assure that they are of the base dict class and not of derived\n+ # classes\n+ data = [d if type(d) is dict else dict(d) for d in data]\n+\n if columns is None:\n gen = (list(x.keys()) for x in data)\n sort = not any(isinstance(d, dict) for d in data)\n pre_cols = lib.fast_unique_multiple_list_gen(gen, sort=sort)\n columns = ensure_index(pre_cols)\n \n- # assure that they are of the base dict class and not of derived\n- # classes\n- data = [d if type(d) is dict else dict(d) for d in data]\n+ # use pre_cols to preserve exact values that were present as dict keys\n+ # (e.g. otherwise missing values might be coerced to the canonical repr)\n+ content = lib.dicts_to_array(data, pre_cols)\n+ else:\n+ content = lib.dicts_to_array(data, list(columns))\n \n- content = lib.dicts_to_array(data, list(columns))\n return content, columns" }, { "filename": "pandas/tests/frame/constructors/test_from_records.py", "status": "modified", "additions": 26, "deletions": 0, "changes": 26, "patch": "@@ -12,6 +12,7 @@\n \n from pandas.compat import is_platform_little_endian\n \n+import pandas as pd\n from pandas import (\n CategoricalIndex,\n DataFrame,\n@@ -501,3 +502,28 @@ def test_from_records_empty_iterator_with_preserve_columns(self):\n )\n expected = DataFrame([], index=[0, 1], columns=[\"col_1\", \"Col_2\"])\n tm.assert_frame_equal(result, expected)\n+\n+ [USER_REDACTED].mark.parametrize(\"missing_value\", [None, np.nan, pd.NA])\n+ def test_from_records_missing_value_key(self, missing_value, using_infer_string):\n+ # https://github.com/[USER_REDACTED]ndas-dev/pandas/issues/63889\n+ # preserve values when None key is converted to NaN column name\n+ dict_data = [\n+ {\"colA\": 1, missing_value: 2},\n+ {\"colA\": 3, missing_value: 4},\n+ ]\n+ result = DataFrame.from_records(dict_data)\n+ expected = DataFrame(\n+ [[1, 2], [3, 4]],\n+ columns=[\"colA\", np.nan if using_infer_string else missing_value],\n+ )\n+ tm.assert_frame_equal(result, expected)\n+\n+ [USER_REDACTED].mark.parametrize(\"missing_value\", [None, np.nan, pd.NA])\n+ def test_from_records_missing_value_key_only(self, missing_value):\n+ dict_data = [\n+ {missing_value: 1},\n+ {missing_value: 2},\n+ ]\n+ result = DataFrame.from_records(dict_data)\n+ expected = DataFrame([[1], [2]], columns=Index([missing_value]))\n+ tm.assert_frame_equal(result, expected)" }, { "filename": "pandas/tests/frame/test_constructors.py", "status": "modified", "additions": 32, "deletions": 0, "changes": 32, "patch": "@@ -641,6 +641,38 @@ def test_constructor_dict_nan_key_and_columns(self):\n expected = DataFrame([[1, 2], [2, 3]], columns=[np.nan, 2])\n tm.assert_frame_equal(result, expected)\n \n+ [USER_REDACTED].mark.parametrize(\"missing_value\", [None, np.nan, pd.NA])\n+ def test_constructor_list_of_dict_with_str_na_key(\n+ self, missing_value, using_infer_string\n+ ):\n+ # https://github.com/[USER_REDACTED]ndas-dev/pandas/issues/63889\n+ # preserve values when None key is converted to NaN column name\n+ dict_data = [\n+ {\"colA\": 1, missing_value: 2},\n+ {\"colA\": 3, missing_value: 4},\n+ ]\n+ result = DataFrame(dict_data)\n+ expected = DataFrame(\n+ [[1, 2], [3, 4]],\n+ columns=[\"colA\", np.nan if using_infer_string else missing_value],\n+ )\n+ tm.assert_frame_equal(result, expected)\n+\n+ [USER_REDACTED].mark.parametrize(\"missing_value\", [None, np.nan, pd.NA])\n+ def test_constructor_dict_of_dict_with_str_na_key(\n+ self, missing_value, using_infer_string\n+ ):\n+ # https://github.com/[USER_REDACTED]ndas-dev/pandas/issues/63889\n+ dict_data = {\"col\": {\"row1\": 1, missing_value: 2, \"row3\": 3}}\n+ result = DataFrame(dict_data)\n+ expected = DataFrame(\n+ {\"col\": [1, 2, 3]},\n+ index=Index(\n+ [\"row1\", np.nan if using_infer_string else missing_value, \"row3\"]\n+ ),\n+ )\n+ tm.assert_frame_equal(result, expected)\n+\n def test_constructor_multi_index(self):\n # GH 4078\n # construction error with mi and all-nan frame" } ], "reviews": [ { "id": 3779424235, "user": "user_7213a217ace7", "state": "COMMENTED", "body": null, "submitted_at": "2026-02-10T14:42:43+00:00" }, { "id": 3780571698, "user": "user_c9260bc45a59", "state": "APPROVED", "body": null, "submitted_at": "2026-02-10T17:45:14+00:00" } ], "review_comments": [ { "id": 2788378687, "user": "user_7213a217ace7", "body": "Keeping the fast path here to avoid a performance regression in the general case where there are no NA keys (we previously had a regression when trying to remove the usage of `fast_multiget` with the Series constructor, see https://github.com/[USER_REDACTED]ndas-dev/pandas/pull/42338)", "path": "pandas/core/internals/construction.py", "line": 594, "side": "RIGHT", "created_at": "2026-02-10T14:42:44+00:00" } ], "meta": { "languages": [ "py", "rst" ], "touches_tests": true, "review_state_summary": { "COMMENTED": 1, "APPROVED": 1 }, "meaningful_comment_count": 1, "has_approval": true, "has_changes_requested": false, "total_review_comments": 1 } } { "_id": "7d21314e318e4765", "_schema_version": "1.0", "_cleaned_at": "2026-02-12T07:46:51.781247+00:00", "repo": "pandas-dev/pandas", "repo_url": "https://github.com/pandas-dev/pandas", "license_name": "BSD 3-Clause \"New\" or \"Revised\" License", "license_spdx": "BSD-3-Clause", "pr_number": 64048, "title": "CI: Add dedicated Python 3.14 jobs", "body": "Allows us to tests all our optional dependencies with (hopefully) released wheels/conda packages", "author": "user_c9260bc45a59", "created_at": "2026-02-05T22:58:05+00:00", "merged_at": "2026-02-09T19:44:40+00:00", "base_branch": "main", "head_branch": "ci/314", "additions": 95, "deletions": 13, "changed_files": 5, "files": [ { "filename": ".github/workflows/unit-tests.yml", "status": "modified", "additions": 4, "deletions": 4, "changes": 8, "patch": "@@ -27,7 +27,7 @@ jobs:\n strategy:\n matrix:\n platform: [ubuntu-24.04, ubuntu-24.04-arm]\n- env_file: [actions-311.yaml, actions-312.yaml, actions-313.yaml]\n+ env_file: [actions-311.yaml, actions-312.yaml, actions-313.yaml, actions-314.yaml]\n # Prevent the include jobs from overriding other jobs\n pattern: [\"\"]\n pandas_future_infer_string: [\"1\"]\n@@ -190,7 +190,7 @@ jobs:\n strategy:\n matrix:\n os: [macos-15-intel, macos-15, windows-2025]\n- env_file: [actions-311.yaml, actions-312.yaml, actions-313.yaml]\n+ env_file: [actions-311.yaml, actions-312.yaml, actions-313.yaml, actions-314.yaml]\n fail-fast: false\n runs-on: ${{ matrix.os }}\n name: ${{ format('{0} {1}', matrix.os, matrix.env_file) }}\n@@ -318,7 +318,7 @@ jobs:\n # To freeze this file, uncomment out the ``if: false`` condition, and migrate the jobs\n # to the corresponding posix/windows-macos/sdist etc. workflows.\n # Feel free to modify this comment as necessary.\n- # if: false\n+ if: false\n defaults:\n run:\n shell: bash -eou pipefail {0}\n@@ -349,7 +349,7 @@ jobs:\n - name: Set up [NAME_REDACTED]\n uses: actions/setup-python@v6\n with:\n- python-version: '3.14-dev'\n+ python-version: '3.15-dev'\n \n - name: [NAME_REDACTED]\n run: |" }, { "filename": "ci/deps/actions-314.yaml", "status": "added", "additions": 63, "deletions": 0, "changes": 63, "patch": "@@ -0,0 +1,63 @@\n+name: pandas-dev-314\n+channels:\n+ - conda-forge\n+dependencies:\n+ - python=3.14\n+\n+ # build dependencies\n+ - versioneer\n+ - cython<4.0.0a0\n+ - meson=1.10.0\n+ - meson-python=0.18.0\n+\n+ # test dependencies\n+ - pytest>=8.3.4\n+ - pytest-cov\n+ - pytest-xdist>=3.6.1\n+ - pytest-localserver>=0.9.0\n+ - pytest-qt>=4.4.0\n+ - boto3=1.37.3\n+\n+ # required dependencies\n+ - python-dateutil\n+ - numpy\n+\n+ # optional dependencies\n+ - adbc-driver-postgresql>=1.2.0\n+ - adbc-driver-sqlite>=1.2.0\n+ - beautifulsoup4>=4.12.3\n+ - blosc>=1.21.3\n+ - bottleneck>=1.4.2\n+ - fastparquet>=2024.11.0\n+ - fsspec>=2024.10.0\n+ - html5lib>=1.1\n+ - hypothesis>=6.116.0\n+ - gcsfs>=2024.10.0\n+ - jinja2>=3.1.5\n+ - lxml>=5.3.0\n+ - matplotlib>=3.9.3\n+ - numba>=0.60.0\n+ - numexpr>=2.10.2\n+ - odfpy>=1.4.1\n+ - qtpy>=2.4.2\n+ - pyqt>=5.15.9\n+ - openpyxl>=3.1.5\n+ - psycopg2>=2.9.10\n+ - pyarrow>=13.0.0\n+ - pymysql>=1.1.1\n+ - pyreadstat>=1.2.8\n+ - pytables>=3.10.1\n+ - python-calamine>=0.3.0\n+ - pytz>=2024.2\n+ - pyxlsb>=1.0.10\n+ - s3fs>=2024.10.0\n+ - scipy>=1.14.1\n+ - sqlalchemy>=2.0.36\n+ - tabulate>=0.9.0\n+ - xarray>=2024.10.0\n+ - xlrd>=2.0.1\n+ - xlsxwriter>=3.2.0\n+ - zstandard>=0.23.0\n+\n+ - pip:\n+ - tzdata>=2023.3" }, { "filename": "pandas/tests/computation/test_eval.py", "status": "modified", "additions": 10, "deletions": 5, "changes": 15, "patch": "@@ -7,7 +7,10 @@\n import numpy as np\n import pytest\n \n-from pandas.compat import PY312\n+from pandas.compat import (\n+ PY312,\n+ PY314,\n+)\n from pandas.compat._optional import import_optional_dependency\n from pandas.errors import (\n NumExprClobberingError,\n@@ -179,7 +182,7 @@ def test_simple_cmp_ops(self, cmp_op, lhs, rhs, engine, parser):\n r\"only list-like( or dict-like)? objects are allowed to be \"\n r\"passed to (DataFrame\\.)?isin\\(\\), you passed a \"\n r\"(`|')bool(`|')\",\n- \"argument of type 'bool' is not iterable\",\n+ \"argument of type 'bool' is not .*\",\n ]\n )\n if cmp_op in (\"in\", \"not in\") and not is_list_like(rhs):\n@@ -224,7 +227,7 @@ def test_compound_invert_op(self, op, lhs, rhs, request, engine, parser):\n r\"only list-like( or dict-like)? objects are allowed to be \"\n r\"passed to (DataFrame\\.)?isin\\(\\), you passed a \"\n r\"(`|')float(`|')\",\n- \"argument of type 'float' is not iterable\",\n+ \"argument of type 'float' is not .*\",\n ]\n )\n if is_scalar(rhs) and op in skip_these:\n@@ -568,7 +571,9 @@ def test_series_pos(self, lhs, engine, parser):\n def test_scalar_unary(self, engine, parser):\n msg = \"bad operand type for unary ~: 'float'\"\n warn = None\n- if PY312 and not (engine == \"numexpr\" and parser == \"pandas\"):\n+ if (PY314 and engine == \"numexpr\" and parser == \"pandas\") or (\n+ PY312 and not (engine == \"numexpr\" and parser == \"pandas\")\n+ ):\n warn = DeprecationWarning\n with pytest.raises(TypeError, match=msg):\n pd.eval(\"~1.0\", engine=engine, parser=parser)\n@@ -1110,7 +1115,7 @@ def test_simple_arith_ops(self, engine, parser):\n ex3 = f\"1 {op} (x + 1)\"\n \n if op in (\"in\", \"not in\"):\n- msg = \"argument of type 'int' is not iterable\"\n+ msg = \"argument of type 'int' is not .*\"\n with pytest.raises(TypeError, match=msg):\n pd.eval(ex, engine=engine, parser=parser)\n else:" }, { "filename": "pandas/tests/io/test_html.py", "status": "modified", "additions": 10, "deletions": 2, "changes": 12, "patch": "@@ -387,8 +387,16 @@ def test_bad_url_protocol(self, httpserver, flavor_read_html):\n [USER_REDACTED].mark.single_cpu\n def test_invalid_url(self, httpserver, flavor_read_html):\n httpserver.serve_content(\"Name or service not known\", code=404)\n- with pytest.raises((URLError, ValueError), match=\"HTTP Error 404: NOT FOUND\"):\n- flavor_read_html(httpserver.url, match=\".*Water.*\")\n+ try:\n+ with pytest.raises(\n+ (URLError, ValueError), match=\"HTTP Error 404: NOT FOUND\"\n+ ) as err:\n+ flavor_read_html(httpserver.url, match=\".*Water.*\")\n+ finally:\n+ if isinstance(err.value, URLError):\n+ # Has a file-like handle that we can close\n+ # https://docs.python.org/3/library/urllib.error.html#urllib.error.HTTPError\n+ err.value.close()\n \n [USER_REDACTED].mark.slow\n def test_file_url(self, banklist_data, flavor_read_html):" }, { "filename": "pandas/tests/io/xml/test_xml.py", "status": "modified", "additions": 8, "deletions": 2, "changes": 10, "patch": "@@ -513,8 +513,14 @@ def test_url(httpserver, xml_file):\n [USER_REDACTED].mark.single_cpu\n def test_wrong_url(parser, httpserver):\n httpserver.serve_content(\"NOT FOUND\", code=404)\n- with pytest.raises(HTTPError, match=(\"HTTP Error 404: NOT FOUND\")):\n- read_xml(httpserver.url, xpath=\".//book[count(*)=4]\", parser=parser)\n+ try:\n+ with pytest.raises(HTTPError, match=(\"HTTP Error 404: NOT FOUND\")) as err:\n+ read_xml(httpserver.url, xpath=\".//book[count(*)=4]\", parser=parser)\n+ finally:\n+ if isinstance(err.value, HTTPError):\n+ # Has a file-like handle that we can close\n+ # https://docs.python.org/3/library/urllib.error.html#urllib.error.HTTPError\n+ err.value.close()\n \n \n # CONTENT" } ], "reviews": [ { "id": 3772616932, "user": "user_7213a217ace7", "state": "COMMENTED", "body": null, "submitted_at": "2026-02-09T10:55:46+00:00" }, { "id": 3772658086, "user": "user_7213a217ace7", "state": "COMMENTED", "body": null, "submitted_at": "2026-02-09T11:03:58+00:00" }, { "id": 3772667420, "user": "user_7213a217ace7", "state": "COMMENTED", "body": null, "submitted_at": "2026-02-09T11:06:14+00:00" }, { "id": 3774649198, "user": "user_c9260bc45a59", "state": "COMMENTED", "body": null, "submitted_at": "2026-02-09T18:12:09+00:00" }, { "id": 3774657492, "user": "user_c9260bc45a59", "state": "COMMENTED", "body": null, "submitted_at": "2026-02-09T18:13:35+00:00" }, { "id": 3774909047, "user": "user_7213a217ace7", "state": "APPROVED", "body": null, "submitted_at": "2026-02-09T19:23:35+00:00" } ], "review_comments": [ { "id": 2781967924, "user": "user_7213a217ace7", "body": "What's the reason for this change? (a comment for the future reader might be useful)", "path": "pandas/tests/io/xml/test_xml.py", "line": 523, "side": "RIGHT", "created_at": "2026-02-09T10:55:46+00:00" }, { "id": 2782006308, "user": "user_7213a217ace7", "body": "The test above also has a `with pytest.raises(URLError, ..`, do you know why that does not need an update?", "path": "pandas/tests/io/test_html.py", "line": 390, "side": "LEFT", "created_at": "2026-02-09T11:03:58+00:00" }, { "id": 2782015998, "user": "user_7213a217ace7", "body": "OK, I see that HTTPError is actually also a file-like object (https://docs.python.org/3/library/urllib.error.html#urllib.error.HTTPError)", "path": "pandas/tests/io/xml/test_xml.py", "line": 523, "side": "RIGHT", "created_at": "2026-02-09T11:06:14+00:00" }, { "id": 2783916260, "user": "user_c9260bc45a59", "body": "Hmm I'm not immediately sure. Inspecting the error from the test above it doesn't seem to even have a `close` method, maybe because the `filename`s are `None`?\n\n```python\n(Pdb) dir(e)\n['__cause__', '__class__', '__context__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getstate__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__setstate__', '__sizeof__', '__str__', '__subclasshook__', '__suppress_context__', '__traceback__', '__weakref__', 'add_note', 'args', 'characters_written', 'errno', 'filename', 'filename2', 'reason', 'strerror', 'with_traceback']\n(Pdb) !e.filename\n(Pdb) !e.filename2\n(Pdb) \n```\n\nMy hypothesis as that the above test doesn't even get to the point of receiving a http response (since it's checking an invalid url) so there's no data to close.", "path": "pandas/tests/io/test_html.py", "line": 390, "side": "LEFT", "created_at": "2026-02-09T18:12:09+00:00" }, { "id": 2783923200, "user": "user_c9260bc45a59", "body": "Correct, added a comment with this link", "path": "pandas/tests/io/xml/test_xml.py", "line": 523, "side": "RIGHT", "created_at": "2026-02-09T18:13:34+00:00" } ], "meta": { "languages": [ "py", "yaml", "yml" ], "touches_tests": true, "review_state_summary": { "COMMENTED": 5, "APPROVED": 1 }, "meaningful_comment_count": 5, "has_approval": true, "has_changes_requested": false, "total_review_comments": 5 } } { "_id": "d045d06abdb327b1", "_schema_version": "1.0", "_cleaned_at": "2026-02-12T07:46:51.781247+00:00", "repo": "pandas-dev/pandas", "repo_url": "https://github.com/pandas-dev/pandas", "license_name": "BSD 3-Clause \"New\" or \"Revised\" License", "license_spdx": "BSD-3-Clause", "pr_number": 64027, "title": "BUG: Fix `read_excel` infinite loop on callable `skiprows` all True", "body": "- [x] [Tests added and passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#writing-tests) if fixing a bug or adding a new feature\n- [x] All [code checks passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit).\n- [x] Added [type annotations](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#type-hints) to new arguments/methods/functions.\n- [ ] Added an entry in the latest `doc/source/whatsnew/vX.X.X.rst` file if fixing a bug or adding a new feature.\n- [x] I have reviewed and followed all the [contribution guidelines](https://pandas.pydata.org/docs/dev/development/contributing.html)\n- [x] If I used AI to develop this pull request, I prompted it to follow `AGENTS.md`.\n\nFixed infinite loop of `pd.read_excel(\"test1\" + read_ext, skiprows=lambda _: True, nrows=1)`. In general, there was an infinite loop each time the number of non-skipped rows was less than `nrows`.", "author": "user_36976b07d3f7", "created_at": "2026-02-04T17:22:02+00:00", "merged_at": "2026-02-10T22:01:52+00:00", "base_branch": "main", "head_branch": "excel_skiprwos_all", "additions": 23, "deletions": 2, "changed_files": 4, "files": [ { "filename": "doc/source/whatsnew/v3.1.0.rst", "status": "modified", "additions": 1, "deletions": 1, "changes": 2, "patch": "@@ -166,7 +166,7 @@ MultiIndex\n \n I/O\n ^^^\n--\n+- Fixed bug in :func:`read_excel` where usage of ``skiprows`` could lead to an infinite loop (:issue:`64027`)\n -\n \n Period" }, { "filename": "pandas/io/excel/_base.py", "status": "modified", "additions": 5, "deletions": 1, "changes": 6, "patch": "@@ -84,6 +84,8 @@\n WriteExcelBuffer,\n )\n \n+EXCEL_ROWS_MAX = 1_048_576\n+\n \n [USER_REDACTED]\n def read_excel(\n@@ -608,7 +610,7 @@ def _check_skiprows_func(\n self,\n skiprows: Callable,\n rows_to_use: int,\n- ) -> int:\n+ ) -> int | None:\n \"\"\"\n Determine how many file rows are required to obtain `nrows` data\n rows when `skiprows` is a function.\n@@ -631,6 +633,8 @@ def _check_skiprows_func(\n if not skiprows(i):\n rows_used_so_far += 1\n i += 1\n+ if i >= EXCEL_ROWS_MAX:\n+ return None\n return i\n \n def _calc_rows(" }, { "filename": "pandas/tests/io/excel/test_openpyxl.py", "status": "modified", "additions": 11, "deletions": 0, "changes": 11, "patch": "@@ -343,6 +343,17 @@ def test_read_with_bad_dimension(\n tm.assert_frame_equal(result, expected)\n \n \n+[USER_REDACTED].mark.parametrize(\n+ \"filename\", [\"dimension_missing\", \"dimension_small\", \"dimension_large\"]\n+)\n+def test_read_with_bad_dimension_skiprows_callable_all(datapath, ext, filename):\n+ # GH 64027\n+ path = datapath(\"io\", \"data\", \"excel\", f\"{filename}{ext}\")\n+ result = pd.read_excel(path, skiprows=lambda _: True, nrows=1)\n+ expected = DataFrame()\n+ tm.assert_frame_equal(result, expected)\n+\n+\n def test_append_mode_file(tmp_excel):\n # GH 39576\n df = DataFrame()" }, { "filename": "pandas/tests/io/excel/test_readers.py", "status": "modified", "additions": 6, "deletions": 0, "changes": 6, "patch": "@@ -1321,6 +1321,12 @@ def test_read_excel_skiprows_callable_not_in(self, request, engine, read_ext):\n expected[\"c\"] = expected[\"c\"].astype(f\"M8[{unit}]\")\n tm.assert_frame_equal(actual, expected)\n \n+ def test_read_excel_skiprows_callable_all(self, read_ext):\n+ # GH 64027\n+ actual = pd.read_excel(\"test1\" + read_ext, skiprows=lambda _: True, nrows=1)\n+ expected = DataFrame()\n+ tm.assert_frame_equal(actual, expected)\n+\n def test_read_excel_nrows(self, read_ext):\n # GH 16645\n num_rows_to_pull = 5" } ], "reviews": [ { "id": 3756037997, "user": "user_c1cc819e14db", "state": "CHANGES_REQUESTED", "body": "Thanks for the PR! Will need an entry in the 3.1.0 whatsnew under I/O bugfixes.", "submitted_at": "2026-02-05T10:40:24+00:00" }, { "id": 3775641505, "user": "user_c1cc819e14db", "state": "CHANGES_REQUESTED", "body": "Can you add a note in the whatsnew for 3.1.0 under the `I/O` section. I'd suggest something like\n\n - Fixed bug in :func:`read_excel` where usage of ``skiprows`` could lead to an infinite loop (:issue:`64027`)\n\nBut feel free to modify.", "submitted_at": "2026-02-09T22:10:13+00:00" }, { "id": 3781868502, "user": "user_c1cc819e14db", "state": "APPROVED", "body": "lgtm", "submitted_at": "2026-02-10T22:01:27+00:00" } ], "review_comments": [ { "id": 2768292667, "user": "user_c1cc819e14db", "body": "Instead of implementing this here, can you add an abstract method and implement it on reader classes directly. Then you can use the corresponding engine and not have to resort to `getattr` calls.", "path": "pandas/io/excel/_base.py", "line": null, "side": "RIGHT", "created_at": "2026-02-05T10:39:35+00:00" }, { "id": 2784757523, "user": "user_c1cc819e14db", "body": "```suggestion \n # GH 64027\n actual = pd.read_excel(\"test1\" + read_ext, skiprows=lambda _: True, nrows=1)\n```", "path": "pandas/tests/io/excel/test_readers.py", "line": 1326, "side": "RIGHT", "created_at": "2026-02-09T22:07:11+00:00" } ], "meta": { "languages": [ "py", "rst" ], "touches_tests": true, "review_state_summary": { "CHANGES_REQUESTED": 2, "APPROVED": 1 }, "meaningful_comment_count": 2, "has_approval": true, "has_changes_requested": true, "total_review_comments": 2 } } { "_id": "97ff9f199529b4da", "_schema_version": "1.0", "_cleaned_at": "2026-02-12T07:46:51.781247+00:00", "repo": "pandas-dev/pandas", "repo_url": "https://github.com/pandas-dev/pandas", "license_name": "BSD 3-Clause \"New\" or \"Revised\" License", "license_spdx": "BSD-3-Clause", "pr_number": 64013, "title": "DOC: Fix PANDAS_VERSION in docs build", "body": "- [x] closes #63990 (Replace xxxx with the GitHub issue number)\n- [ ] [Tests added and passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#writing-tests) if fixing a bug or adding a new feature\n- [ ] All [code checks passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit).\n- [ ] Added [type annotations](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#type-hints) to new arguments/methods/functions.\n- [ ] Added an entry in the latest `doc/source/whatsnew/vX.X.X.rst` file if fixing a bug or adding a new feature.\n- [ ] I have reviewed and followed all the [contribution guidelines](https://pandas.pydata.org/docs/dev/development/contributing.html)\n- [ ] If I used AI to develop this pull request, I prompted it to follow `AGENTS.md`.\n\nWe should only set the pandas version when the ref matches a valid SemVer string.", "author": "user_c1cc819e14db", "created_at": "2026-02-03T22:25:39+00:00", "merged_at": "2026-02-09T10:43:14+00:00", "base_branch": "main", "head_branch": "doc_fix_dev_version", "additions": 27, "deletions": 4, "changed_files": 1, "files": [ { "filename": ".github/workflows/docbuild-and-upload.yml", "status": "modified", "additions": 27, "deletions": 4, "changes": 31, "patch": "@@ -47,10 +47,33 @@ jobs:\n steps:\n - name: Set pandas version\n run: |\n- if [ -n \"${{ github.event.inputs.version }}\" ]; then\n- echo \"PANDAS_VERSION=${{ github.event.inputs.version }}\" >> \"$GITHUB_ENV\"\n+ # tags include a `v` prefix.\n+ tag_version_pat=\"^v\\d+\\.\\d+\\.\\d+(rc\\d+)?$\"\n+ version_pat=\"^\\d+\\.\\d+\\.\\d+(rc\\d+)?$\"\n+\n+ if [[ -n \"${{ github.event.inputs.version }}\" ]]; then\n+ PANDAS_VERSION=\"${{ github.event.inputs.version }}\"\n+ elif [[ \"${{ github.event_name }}\" == \"push\" && \"$GITHUB_REF_NAME\" =~ $tag_version_pat ]]; then\n+ PANDAS_VERSION=\"${GITHUB_REF_NAME:1}\"\n else\n- echo \"PANDAS_VERSION=${GITHUB_REF_NAME:1}\" >> \"$GITHUB_ENV\"\n+ PANDAS_VERSION=\"\"\n+ fi\n+ echo \"PANDAS_VERSION=$PANDAS_VERSION\" >> \"$GITHUB_ENV\"\n+\n+ if [[ \"${{ github.event_name }}\" == \"push\" && -n \"$PANDAS_VERSION\" ]]; then\n+ PUBLISH_PROD=\"true\"\n+ elif [[ \"${{ github.event.inputs.publish_prod }}\" == \"true\" ]]; then\n+ PUBLISH_PROD=\"true\"\n+ else\n+ PUBLISH_PROD=\"false\"\n+ fi\n+ echo \"PUBLISH_PROD=$PUBLISH_PROD\" >> \"$GITHUB_ENV\"\n+\n+ if [[ \"$PUBLISH_PROD\" == \"true\" ]] &&\n+ [[ ! \"$PANDAS_VERSION\" =~ $version_pat ]]\n+ then\n+ echo \"Invalid version $PANDAS_VERSION for publishing to prod.\"\n+ exit 1\n fi\n \n - name: Checkout\n@@ -105,7 +128,7 @@ jobs:\n \n - name: Upload prod docs\n run: rsync -az --delete doc/build/html/ web@${{ secrets.server_ip }}:/var/www/html/pandas-docs/version/${{ env.PANDAS_VERSION }}\n- if: ${{ (github.event_name == 'push' && startsWith(github.ref, 'refs/tags/')) || (inputs.publish_prod == 'true') }}\n+ if: ${{ env.PUBLISH_PROD == 'true' }}\n \n - name: Move docs into site directory\n run: mv doc/build/html web/build/docs" } ], "reviews": [ { "id": 3749995186, "user": "user_7213a217ace7", "state": "COMMENTED", "body": null, "submitted_at": "2026-02-04T09:36:33+00:00" }, { "id": 3756867422, "user": "user_c1cc819e14db", "state": "COMMENTED", "body": null, "submitted_at": "2026-02-05T12:41:12+00:00" }, { "id": 3758010395, "user": "user_7213a217ace7", "state": "COMMENTED", "body": null, "submitted_at": "2026-02-05T16:01:00+00:00" }, { "id": 3758059782, "user": "user_7213a217ace7", "state": "COMMENTED", "body": null, "submitted_at": "2026-02-05T16:09:47+00:00" }, { "id": 3759565574, "user": "user_c1cc819e14db", "state": "COMMENTED", "body": null, "submitted_at": "2026-02-05T21:31:37+00:00" }, { "id": 3759580345, "user": "user_c1cc819e14db", "state": "COMMENTED", "body": null, "submitted_at": "2026-02-05T21:35:26+00:00" }, { "id": 3772551758, "user": "user_7213a217ace7", "state": "APPROVED", "body": "Thanks for the updates, looks good now, let's give this a try", "submitted_at": "2026-02-09T10:43:05+00:00" }, { "id": 3772579880, "user": "user_7213a217ace7", "state": "COMMENTED", "body": null, "submitted_at": "2026-02-09T10:48:58+00:00" } ], "review_comments": [ { "id": 2763074535, "user": "user_7213a217ace7", "body": "Will that allow rc versions? (those get currently uploaded)\n\ni.e. anytime that the `if` check passes in the \"Upload prod docs\" step, we should have a value set for `PANDAS_VERSION` (not fully sure if it would otherwise error, or fill in an empty string and upload the docs to the wrong directory)", "path": ".github/workflows/docbuild-and-upload.yml", "line": null, "side": "RIGHT", "created_at": "2026-02-04T09:36:33+00:00" }, { "id": 2768966678, "user": "user_c1cc819e14db", "body": "Ah, thanks. It's not clear to me if we should match on e.g. `3.1.0.dev0`, the latest commit currently does. The regex will now match all tags of the repo except the following.\n\n
      \n\n```\n0.3.0\ndebian/0.4.0-1\ndebian/0.4.1-1\ndebian/0.4.3-1\ndebian/0.5.0+git7-gcf32be2-1\ndebian/0.6.1-1\ndebian/0.7.0-1\ndebian/0.7.1+git1-ga2e86c2-1\ndebian/0.7.3-1\ndebian/0.8.0-1\ndebian/0.8.0-2\ndebian/0.8.0_b2+git68-g7240b87-1\ndebian/0.8.0_b2-1\ndebian/0.8.0_rc2+git26-g76c6351-1\ndebian/0.8.1-1\nv0.8.0b1\nv0.8.0b2\nv0.10.0b1\nv0.13.0_ahl1\nv0.13.0_ahl2\nv0.15.2pre\nv0.15pre\nv0.21.0.dev\n```\n\n
      \n\nI've also added a step that checks the tag more stringently when publishing to prod that does not allow this to happen on e.g. `dev0`.", "path": ".github/workflows/docbuild-and-upload.yml", "line": null, "side": "RIGHT", "created_at": "2026-02-05T12:41:12+00:00" }, { "id": 2769924841, "user": "user_7213a217ace7", "body": "Yeah, in theory we don't have to upload the docs for the dev0 tags. And probably we can also remove those existing docs on the server to save some space.", "path": ".github/workflows/docbuild-and-upload.yml", "line": null, "side": "RIGHT", "created_at": "2026-02-05T16:00:59+00:00" }, { "id": 2769967700, "user": "user_7213a217ace7", "body": "Here you did not add \"dev\", so this workflow will then fail for that tag? (because above it will set PUBLISH_PROD to true I think for such tags)\n\n(I think it would also be fine to not upload any docs for dev tags)", "path": ".github/workflows/docbuild-and-upload.yml", "line": null, "side": "RIGHT", "created_at": "2026-02-05T16:09:48+00:00" }, { "id": 2771243803, "user": "user_c1cc819e14db", "body": "As an aside - why do we publish the dev tag?", "path": ".github/workflows/docbuild-and-upload.yml", "line": null, "side": "RIGHT", "created_at": "2026-02-05T21:31:37+00:00" }, { "id": 2771255287, "user": "user_c1cc819e14db", "body": "Thanks, fixed.", "path": ".github/workflows/docbuild-and-upload.yml", "line": null, "side": "RIGHT", "created_at": "2026-02-05T21:35:26+00:00" }, { "id": 2781934637, "user": "user_7213a217ace7", "body": "> As an aside - why do we publish the dev tag?\n\nDo you mean \"why do we publish it on the website\", then I think that was just a consequence of how the pushing on any tag was implemented, which you improved here.\n\nIf you are asking why we are creating this tag in the first place, it is to let the git-tag-based version number of pandas for the development version have a \"correct\" number, that sorts after the released versions\n\nOtherwise we get something like \n\n```\n>>> from packaging.version import Version\n>>> Version(\"3.0.0+1200\") > Version(\"3.0.1\")\nFalse\n```", "path": ".github/workflows/docbuild-and-upload.yml", "line": null, "side": "RIGHT", "created_at": "2026-02-09T10:48:58+00:00" } ], "meta": { "languages": [ "yml" ], "touches_tests": false, "review_state_summary": { "COMMENTED": 7, "APPROVED": 1 }, "meaningful_comment_count": 7, "has_approval": true, "has_changes_requested": false, "total_review_comments": 7 } } { "_id": "02606a74fe22de65", "_schema_version": "1.0", "_cleaned_at": "2026-02-12T07:46:51.781247+00:00", "repo": "pandas-dev/pandas", "repo_url": "https://github.com/pandas-dev/pandas", "license_name": "BSD 3-Clause \"New\" or \"Revised\" License", "license_spdx": "BSD-3-Clause", "pr_number": 64009, "title": "BUG: Missing explicit libm dependency in meson.build causes undefined symbol errors #63640", "body": "… symbol errors #63640\n\n- [x] closes #63640 (Replace xxxx with the GitHub issue number)\n- [x] All [code checks passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit).\n- [ ] Added [type annotations](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#type-hints) to new arguments/methods/functions.\n- [ ] Added an entry in the latest `doc/source/whatsnew/vX.X.X.rst` file if fixing a bug or adding a new feature.\n- [x] I have reviewed and followed all the [contribution guidelines](https://pandas.pydata.org/docs/dev/development/contributing.html)\n- [x] If I used AI to develop this pull request, I prompted it to follow `AGENTS.md`.", "author": "user_2413f82a985d", "created_at": "2026-02-03T15:25:45+00:00", "merged_at": "2026-02-04T02:24:45+00:00", "base_branch": "main", "head_branch": "issue63640", "additions": 7, "deletions": 4, "changed_files": 2, "files": [ { "filename": "pandas/_libs/meson.build", "status": "modified", "additions": 6, "deletions": 3, "changes": 9, "patch": "@@ -50,6 +50,8 @@ _khash_primitive_helper_dep = declare_dependency(\n sources: _khash_primitive_helper,\n )\n \n+m_dep = cc.find_library('m', required: false)\n+\n cdata = configuration_data()\n if cy.version().version_compare('>=3.1.0')\n cdata.set('freethreading_compatible', '1')\n@@ -70,10 +72,10 @@ libs_sources = {\n # numpy include dir is implicitly included\n 'algos': {\n 'sources': ['algos.pyx', _algos_common_helper, _algos_take_helper],\n- 'deps': _khash_primitive_helper_dep,\n+ 'deps': [_khash_primitive_helper_dep, m_dep],\n },\n 'arrays': {'sources': ['arrays.pyx']},\n- 'groupby': {'sources': ['groupby.pyx']},\n+ 'groupby': {'sources': ['groupby.pyx'], 'deps': [m_dep]},\n 'hashing': {'sources': ['hashing.pyx']},\n 'hashtable': {\n 'sources': [\n@@ -126,14 +128,15 @@ libs_sources = {\n 'src/vendored/ujson/lib/ultrajsonenc.c',\n 'src/vendored/ujson/lib/ultrajsondec.c',\n ],\n+ 'deps': [m_dep],\n },\n 'ops': {'sources': ['ops.pyx']},\n 'ops_dispatch': {'sources': ['ops_dispatch.pyx']},\n 'properties': {'sources': ['properties.pyx']},\n 'reshape': {'sources': ['reshape.pyx']},\n 'sas': {'sources': ['sas.pyx']},\n 'byteswap': {'sources': ['byteswap.pyx']},\n- 'sparse': {'sources': ['sparse.pyx', _sparse_op_helper]},\n+ 'sparse': {'sources': ['sparse.pyx', _sparse_op_helper], 'deps': [m_dep]},\n 'tslib': {'sources': ['tslib.pyx']},\n 'testing': {'sources': ['testing.pyx']},\n 'writers': {'sources': ['writers.pyx']}," }, { "filename": "pandas/_libs/tslibs/meson.build", "status": "modified", "additions": 1, "deletions": 1, "changes": 2, "patch": "@@ -4,7 +4,7 @@ tslibs_sources = {\n 'base': {'sources': ['base.pyx']},\n 'ccalendar': {'sources': ['ccalendar.pyx']},\n 'dtypes': {'sources': ['dtypes.pyx']},\n- 'conversion': {'sources': ['conversion.pyx']},\n+ 'conversion': {'sources': ['conversion.pyx'], 'deps': [m_dep]},\n 'fields': {'sources': ['fields.pyx']},\n 'nattype': {'sources': ['nattype.pyx']},\n 'np_datetime': {'sources': ['np_datetime.pyx']}," } ], "reviews": [ { "id": 3747145131, "user": "user_0d1de6b83a30", "state": "CHANGES_REQUESTED", "body": null, "submitted_at": "2026-02-03T19:28:32+00:00" }, { "id": 3748415217, "user": "user_2413f82a985d", "state": "COMMENTED", "body": null, "submitted_at": "2026-02-04T01:02:49+00:00" }, { "id": 3748558831, "user": "user_0d1de6b83a30", "state": "APPROVED", "body": "LGTM\n\n```console\n$ fd --extension so --no-ignore --exec nm --undefined-only -A | grep -e mod -e pow -e abs -e sqrt -e log\n./pandas/_libs/json.cpython-313-x86_64-linux-gnu.so: U pow@GLIBC_2.29\n./pandas/_libs/groupby.cpython-313-x86_64-linux-gnu.so: U fmod@GLIBC_2.38\n./pandas/_libs/groupby.cpython-313-x86_64-linux-gnu.so: U pow@GLIBC_2.29\n./pandas/_libs/groupby.cpython-313-x86_64-linux-gnu.so: U sqrtf@GLIBC_2.2.5\n./pandas/_libs/groupby.cpython-313-x86_64-linux-gnu.so: U sqrt@GLIBC_2.2.5\n./pandas/_libs/sparse.cpython-313-x86_64-linux-gnu.so: U fmod@GLIBC_2.38\n./pandas/_libs/sparse.cpython-313-x86_64-linux-gnu.so: U pow@GLIBC_2.29\n./pandas/_libs/algos.cpython-313-x86_64-linux-gnu.so: U sqrt@GLIBC_2.2.5\n./pandas/_libs/window/aggregations.cpython-313-x86_64-linux-gnu.so: U log@GLIBC_2.29\n./pandas/_libs/window/aggregations.cpython-313-x86_64-linux-gnu.so: U pow@GLIBC_2.29\n./pandas/_libs/window/aggregations.cpython-313-x86_64-linux-gnu.so: U sqrt@GLIBC_2.2.5\n./pandas/_libs/tslibs/offsets.cpython-313-x86_64-linux-gnu.so: U PyNumber_Divmod\n./pandas/_libs/tslibs/conversion.cpython-313-x86_64-linux-gnu.so: U log10@GLIBC_2.2.5\n```", "submitted_at": "2026-02-04T01:56:48+00:00" }, { "id": 3748610836, "user": "user_c9260bc45a59", "state": "APPROVED", "body": null, "submitted_at": "2026-02-04T02:24:35+00:00" } ], "review_comments": [ { "id": 2760640899, "user": "user_0d1de6b83a30", "body": "The `cc` variable already exists from the project root.\n```suggestion\n```", "path": "pandas/_libs/meson.build", "line": null, "side": "RIGHT", "created_at": "2026-02-03T19:24:32+00:00" }, { "id": 2761692117, "user": "user_2413f82a985d", "body": "[USER_REDACTED] Thank you for your review. I reflected it.", "path": "pandas/_libs/meson.build", "line": null, "side": "RIGHT", "created_at": "2026-02-04T01:02:48+00:00" } ], "meta": { "languages": [ "build" ], "touches_tests": false, "review_state_summary": { "CHANGES_REQUESTED": 1, "COMMENTED": 1, "APPROVED": 2 }, "meaningful_comment_count": 2, "has_approval": true, "has_changes_requested": true, "total_review_comments": 2 } } { "_id": "84abc497c374f439", "_schema_version": "1.0", "_cleaned_at": "2026-02-12T07:46:51.781247+00:00", "repo": "pandas-dev/pandas", "repo_url": "https://github.com/pandas-dev/pandas", "license_name": "BSD 3-Clause \"New\" or \"Revised\" License", "license_spdx": "BSD-3-Clause", "pr_number": 63979, "title": "REGR: pivot_table with empty values inconsistency", "body": "- [x] closes #46475 (Replace xxxx with the GitHub issue number)\n- [ ] [Tests added and passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#writing-tests) if fixing a bug or adding a new feature\n- [ ] All [code checks passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit).\n- [ ] Added [type annotations](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#type-hints) to new arguments/methods/functions.\n- [ ] Added an entry in the latest `doc/source/whatsnew/vX.X.X.rst` file if fixing a bug or adding a new feature.\n- [ ] I have reviewed and followed all the [contribution guidelines](https://pandas.pydata.org/docs/dev/development/contributing.html)\n- [ ] If I used AI to develop this pull request, I prompted it to follow `AGENTS.md`.\n\nWhen there are no values to aggregate on, the behavior of `pivot_table` depends on the number of columns provided to `index` and `columns` combined.\n\n```python\nframe = pd.DataFrame({\"a\": [1, 1, 2]})\ntable = pd.pivot_table(frame, index=[\"a\"], aggfunc=len)\nprint(table)\n# [NAME_REDACTED]\n# Columns: []\n# Index: [1, 2]\n\nframe = pd.DataFrame({\"a\": [1, 1, 2], \"b\": [3, 4, 5]})\ntable = pd.pivot_table(frame, index=[\"a\", \"b\"], aggfunc=len)\nprint(table)\n# a b\n# 1 3 1\n# 4 1\n# 2 5 1\n# dtype: int64\n```\n\nThis is due to inconsistencies in `DataFrameGroupBy.agg`. While I aim to address these in the near future, they would resolve the inconsistency in `pivot_table` by [NAME_REDACTED] result above, whereas the second seems more desirable. \n\nIt appears to me that we get naturally good behavior by [NAME_REDACTED]_table act on all NA data in these cases: sums give 0, products give 1, count gives 0, size and len give the expected values. It also closely agrees with current behavior.", "author": "user_c1cc819e14db", "created_at": "2026-02-01T19:58:21+00:00", "merged_at": "2026-02-03T17:45:49+00:00", "base_branch": "main", "head_branch": "cln_pivot_table_no_values", "additions": 110, "deletions": 21, "changed_files": 3, "files": [ { "filename": "doc/source/whatsnew/v3.1.0.rst", "status": "modified", "additions": 1, "deletions": 1, "changes": 2, "patch": "@@ -186,7 +186,7 @@ Groupby/resample/rolling\n \n Reshaping\n ^^^^^^^^^\n--\n+- In :func:`pivot_table`, when ``values`` is empty, the aggregation will be computed on a Series of all NA values (:issue:`46475`)\n -\n \n Sparse" }, { "filename": "pandas/core/reshape/pivot.py", "status": "modified", "additions": 53, "deletions": 18, "changes": 71, "patch": "@@ -49,6 +49,10 @@\n )\n \n from pandas import DataFrame\n+ from pandas.api.typing import (\n+ DataFrameGroupBy,\n+ SeriesGroupBy,\n+ )\n \n \n [USER_REDACTED]_module(\"pandas\")\n@@ -147,6 +151,11 @@ def pivot_table(\n -----\n Reference :ref:`the user guide ` for more examples.\n \n+ .. versionchanged:: 3.1.0\n+ When ``values`` is empty, which is the case when all columns of\n+ ``data`` are either in ``index`` or ``columns`` arguments, aggregation\n+ will act on a Series of all NA values.\n+\n Examples\n --------\n >>> df = pd.DataFrame(\n@@ -335,11 +344,16 @@ def __internal_pivot_table(\n pass\n values = list(values)\n \n- grouped = data.groupby(keys, observed=observed, sort=sort, dropna=dropna)\n+ grouped: SeriesGroupBy | DataFrameGroupBy = data.groupby(\n+ keys, observed=observed, sort=sort, dropna=dropna\n+ )\n if values_passed:\n # GH#57876 and GH#61292\n- # mypy is not aware `grouped[values]` will always be a DataFrameGroupBy\n- grouped = grouped[values] # type: ignore[assignment]\n+ grouped = grouped[values]\n+ elif grouped._obj_with_exclusions.columns.empty:\n+ grouped = Series(np.nan, index=data.index).groupby(\n+ [data[key] for key in keys], observed=observed, sort=sort, dropna=dropna\n+ )\n \n agged = grouped.agg(aggfunc, **kwargs)\n \n@@ -450,9 +464,10 @@ def _add_margins(\n if not values and isinstance(table, ABCSeries):\n # If there are no values and the table is a series, then there is only\n # one column in the data. Compute grand margin and return it.\n- return table._append_internal(\n- table._constructor({key: grand_margin[margins_name]})\n- )\n+ row = table._constructor({key: grand_margin[margins_name]})\n+ if not isinstance(table.index, MultiIndex):\n+ row.index.name = table.index.name\n+ return table._append_internal(row)\n \n elif values:\n marginal_result_set = _generate_marginal_results(\n@@ -480,7 +495,6 @@ def _add_margins(\n return marginal_result_set\n result, margin_keys, row_margin = marginal_result_set\n \n- row_margin = row_margin.reindex(result.columns, fill_value=fill_value)\n # populate grand margin\n for k in margin_keys:\n if isinstance(k, str):\n@@ -490,11 +504,9 @@ def _add_margins(\n \n from pandas import DataFrame\n \n+ row_margin = row_margin.reindex(result.columns, fill_value=fill_value)\n margin_dummy = DataFrame(row_margin, columns=Index([key])).T\n \n- row_names = result.index.names\n- # check the result column and leave floats\n-\n for dtype in set(result.dtypes):\n if isinstance(dtype, ExtensionDtype):\n # Can hold NA already\n@@ -504,6 +516,8 @@ def _add_margins(\n margin_dummy[cols] = margin_dummy[cols].apply(\n maybe_downcast_to_dtype, args=(dtype,)\n )\n+\n+ row_names = result.index.names\n result = concat([result, margin_dummy])\n result.index.names = row_names\n \n@@ -530,7 +544,15 @@ def _compute_grand_margin(\n pass\n return grand_margin\n else:\n- return {margins_name: aggfunc(data.index, **kwargs)}\n+ from pandas import Categorical\n+\n+ # Use groupby for consistency with how values are aggregated.\n+ gb = Series(np.nan, index=data.index).groupby(\n+ Categorical(np.zeros(len(data.index)), categories=[0]), observed=False\n+ )\n+ agged = gb.agg(aggfunc, **kwargs)\n+ assert isinstance(agged, Series) and len(agged) == 1\n+ return {margins_name: agged.iloc[0]}\n \n \n def _generate_marginal_results(\n@@ -651,16 +673,27 @@ def _all_key():\n return (margins_name,) + (\"\",) * (len(cols) - 1)\n \n if len(rows) > 0:\n- margin = data.groupby(rows, observed=observed, dropna=dropna)[rows].apply(\n- aggfunc, **kwargs\n- )\n+ if len(data.index) > 0:\n+ gb = Series(np.nan, index=data.index).groupby(\n+ [data[row] for row in rows], observed=observed, dropna=dropna\n+ )\n+ margin = gb.agg(aggfunc, **kwargs)\n+ else:\n+ from pandas import Categorical\n+\n+ gb = Series(np.nan, index=data.index).groupby(\n+ Categorical(np.zeros(0), categories=[0]), observed=False\n+ )\n+ agged = gb.agg(aggfunc, **kwargs)\n+ assert isinstance(agged, Series) and len(agged) == 1\n+ margin = agged.iloc[0]\n all_key = _all_key()\n table[all_key] = margin\n result = table\n margin_keys.append(all_key)\n \n else:\n- margin = data.groupby(level=0, observed=observed, dropna=dropna).apply(\n+ margin = data.groupby(level=0, observed=observed, dropna=dropna).agg(\n aggfunc, **kwargs\n )\n all_key = _all_key()\n@@ -672,9 +705,11 @@ def _all_key():\n result = table\n margin_keys = table.columns\n \n- if len(cols):\n- row_margin = data.groupby(cols, observed=observed, dropna=dropna)[cols].apply(\n- aggfunc, **kwargs\n+ if len(result.columns) > 0:\n+ row_margin = (\n+ Series(np.nan, index=data.index)\n+ .groupby([data[col] for col in cols], observed=observed, dropna=dropna)\n+ .agg(aggfunc, **kwargs)\n )\n else:\n row_margin = Series(np.nan, index=result.columns)" }, { "filename": "pandas/tests/reshape/test_pivot.py", "status": "modified", "additions": 56, "deletions": 2, "changes": 58, "patch": "@@ -1196,6 +1196,60 @@ def test_pivot_complex_aggfunc(self, data):\n \n tm.assert_frame_equal(result, expected)\n \n+ [USER_REDACTED].mark.parametrize(\"margins\", [True, False])\n+ [USER_REDACTED].mark.parametrize(\n+ \"aggfunc, value\",\n+ [\n+ (\"sum\", [0.0, 0.0, 0.0]),\n+ (\"prod\", [1.0, 1.0, 1.0]),\n+ (\"count\", [0, 0, 0]),\n+ (\"size\", [2, 1, 3]),\n+ (len, [2, 1, 3]),\n+ ],\n+ )\n+ def test_reducers_no_values_one_index(self, margins, aggfunc, value):\n+ # https://github.com/[USER_REDACTED]ndas-dev/pandas/issues/46475\n+ df = DataFrame({\"a\": [1, 1, 2]})\n+ result = pivot_table(df, index=[\"a\"], aggfunc=aggfunc, margins=margins)\n+ if margins:\n+ index = Index([1, 2, \"All\"], name=\"a\")\n+ else:\n+ value = value[:-1]\n+ index = Index([1, 2], name=\"a\")\n+ expected = Series(value, index=index)\n+ tm.assert_series_equal(result, expected)\n+\n+ [USER_REDACTED].mark.parametrize(\"margins\", [True, False])\n+ [USER_REDACTED].mark.parametrize(\"index\", [[\"a\"], [\"a\", \"b\"]])\n+ [USER_REDACTED].mark.parametrize(\"columns\", [[\"c\"], [\"c\", \"d\"]])\n+ def test_no_values_no_data(self, margins, index, columns):\n+ # https://github.com/[USER_REDACTED]ndas-dev/pandas/issues/46475\n+ df = DataFrame(columns=index + columns)\n+ result = pivot_table(\n+ df, index=index, columns=columns, aggfunc=len, margins=margins\n+ )\n+\n+ if margins:\n+ level0, level1, codes, data = [\"All\"], [\"\"], [[0], [0]], [0]\n+ else:\n+ level0, level1, codes, data = [], [], [[], []], []\n+\n+ if index == [\"a\"]:\n+ expected_index = Index(level0, name=\"a\")\n+ else:\n+ expected_index = MultiIndex(\n+ levels=[level0, level1], codes=codes, names=index\n+ )\n+ if columns == [\"c\"]:\n+ expected_columns = Index(level0, name=\"c\")\n+ else:\n+ expected_columns = MultiIndex(\n+ levels=[level0, level1], codes=codes, names=columns\n+ )\n+\n+ expected = DataFrame(data, index=expected_index, columns=expected_columns)\n+ tm.assert_frame_equal(result, expected)\n+\n def test_margins_no_values_no_cols(self, data):\n # Regression test on pivot table: no values or cols passed.\n result = data[[\"A\", \"B\"]].pivot_table(\n@@ -2054,8 +2108,8 @@ def test_pivot_margins_name_unicode(self):\n frame, index=[\"foo\"], aggfunc=len, margins=True, margins_name=greek\n )\n index = Index([1, 2, 3, greek], dtype=\"object\", name=\"foo\")\n- expected = DataFrame(index=index, columns=[])\n- tm.assert_frame_equal(table, expected)\n+ expected = Series([1, 1, 1, 3], index=index)\n+ tm.assert_series_equal(table, expected)\n \n def test_pivot_string_as_func(self):\n # GH #18713" } ], "reviews": [ { "id": 3741207834, "user": "user_c9260bc45a59", "state": "COMMENTED", "body": null, "submitted_at": "2026-02-02T18:29:08+00:00" }, { "id": 3741733856, "user": "user_c1cc819e14db", "state": "COMMENTED", "body": null, "submitted_at": "2026-02-02T21:20:43+00:00" }, { "id": 3741782505, "user": "user_c9260bc45a59", "state": "COMMENTED", "body": null, "submitted_at": "2026-02-02T21:39:08+00:00" }, { "id": 3741782827, "user": "user_c9260bc45a59", "state": "APPROVED", "body": null, "submitted_at": "2026-02-02T21:39:16+00:00" }, { "id": 3744907446, "user": "user_c1cc819e14db", "state": "COMMENTED", "body": null, "submitted_at": "2026-02-03T12:10:48+00:00" }, { "id": 3746664750, "user": "user_c9260bc45a59", "state": "APPROVED", "body": null, "submitted_at": "2026-02-03T17:45:41+00:00" } ], "review_comments": [ { "id": 2755700009, "user": "user_c9260bc45a59", "body": "Should this missing value (or input `dtype=` to Series) be dependent on the type of the original `grouped.obj`? e.g. If the original frame had a nullable type we'd want a nullable type in the output?", "path": "pandas/core/reshape/pivot.py", "line": 354, "side": "RIGHT", "created_at": "2026-02-02T18:29:04+00:00" }, { "id": 2756157204, "user": "user_c1cc819e14db", "body": "Thinking through what this might look like - we'd need to determine the \"flavor\" - numpy, nullable, or pyarrow (I recall some objections to \"flavor\" in the past, but don't know if there is an accepted term). This would make a useful function in `core.dtypes`. Then we could do something like this.\n\nWe'd need to decide what the rule is in case of multiple flavors. I'd suggest if there are any `pyarrow` then go with that; if no `pyarrow` and there are `nullable` then go with that, and finally only have `numpy` if all columns are `numpy`. I think we'd want to consider `str` dtype (whether backed by [NAME_REDACTED]) as being `numpy` for the purposes of this. This might be problematic when the data has only `str` columns, but I don't see a better alternative.\n\nFor this particular instance, only the `index + columns` will be relevant in this determination.", "path": "pandas/core/reshape/pivot.py", "line": 354, "side": "RIGHT", "created_at": "2026-02-02T21:20:43+00:00" }, { "id": 2756200578, "user": "user_c9260bc45a59", "body": "I see. Understandable that this is probably more complicated than the tools we have today to probably get this case fully correct. I'm fine crossing that bridge when we get to it.", "path": "pandas/core/reshape/pivot.py", "line": 354, "side": "RIGHT", "created_at": "2026-02-02T21:39:08+00:00" }, { "id": 2758765022, "user": "user_c1cc819e14db", "body": "I've opened https://github.com/[USER_REDACTED]ndas-dev/pandas/issues/64005", "path": "pandas/core/reshape/pivot.py", "line": 354, "side": "RIGHT", "created_at": "2026-02-03T12:10:47+00:00" } ], "meta": { "languages": [ "py", "rst" ], "touches_tests": true, "review_state_summary": { "COMMENTED": 4, "APPROVED": 2 }, "meaningful_comment_count": 4, "has_approval": true, "has_changes_requested": false, "total_review_comments": 4 } } { "_id": "6976357f622725ed", "_schema_version": "1.0", "_cleaned_at": "2026-02-12T07:46:51.781247+00:00", "repo": "pandas-dev/pandas", "repo_url": "https://github.com/pandas-dev/pandas", "license_name": "BSD 3-Clause \"New\" or \"Revised\" License", "license_spdx": "BSD-3-Clause", "pr_number": 63975, "title": "BUG: groupby.agg with no groups, multiple keys, and group_keys=False", "body": "- [x] closes #51445 (Replace xxxx with the GitHub issue number)\n- [ ] [Tests added and passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#writing-tests) if fixing a bug or adding a new feature\n- [ ] All [code checks passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit).\n- [ ] Added [type annotations](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#type-hints) to new arguments/methods/functions.\n- [ ] Added an entry in the latest `doc/source/whatsnew/vX.X.X.rst` file if fixing a bug or adding a new feature.\n- [ ] I have reviewed and followed all the [contribution guidelines](https://pandas.pydata.org/docs/dev/development/contributing.html)\n- [ ] If I used AI to develop this pull request, I prompted it to follow `AGENTS.md`.\n\nIn cases of an empty result `_python_agg_general` will call `_python_apply_general`. This can give bad behavior, e.g. `group_keys` can impact the result (which should only be the case with `apply`). In the case of an empty result, the index/columns are clear: it should have `result_index` as the index (as all aggregations should) and the columns of `self._obj_with_exclusions` columns.", "author": "user_c1cc819e14db", "created_at": "2026-02-01T13:37:53+00:00", "merged_at": "2026-02-05T18:30:05+00:00", "base_branch": "main", "head_branch": "bug_gb_apply_with_agg", "additions": 51, "deletions": 32, "changed_files": 5, "files": [ { "filename": "doc/source/whatsnew/v3.1.0.rst", "status": "modified", "additions": 1, "deletions": 1, "changes": 2, "patch": "@@ -181,7 +181,7 @@ [NAME_REDACTED]/resample/rolling\n ^^^^^^^^^^^^^^^^^^^^^^^^\n--\n+- Bug in :meth:`.DataFrameGroupBy.agg` when there are no groups, multiple keys, and ``group_keys=False`` (:issue:`51445`)\n -\n \n Reshaping" }, { "filename": "pandas/core/groupby/generic.py", "status": "modified", "additions": 12, "deletions": 16, "changes": 28, "patch": "@@ -2372,24 +2372,20 @@ def aggregate(self, func=None, *args, engine=None, engine_kwargs=None, **kwargs)\n def _python_agg_general(self, func, *args, **kwargs):\n f = lambda x: func(x, *args, **kwargs)\n \n- if self.ngroups == 0:\n- # e.g. test_evaluate_with_empty_groups different path gets different\n- # result dtype in empty case.\n- return self._python_apply_general(f, self._selected_obj, is_agg=True)\n-\n obj = self._obj_with_exclusions\n \n- if not len(obj.columns):\n- # e.g. test_margins_no_values_no_cols\n- return self._python_apply_general(f, self._selected_obj)\n-\n- output: dict[int, ArrayLike] = {}\n- for idx, (name, ser) in enumerate(obj.items()):\n- result = self._grouper.agg_series(ser, f)\n- output[idx] = result\n-\n- res = self.obj._constructor(output)\n- res.columns = obj.columns.copy(deep=False)\n+ if self.ngroups == 0 or len(obj.columns) == 0:\n+ res_index = self._grouper.result_index\n+ res = self.obj._constructor(index=res_index, columns=obj.columns).astype(\n+ obj.dtypes\n+ )\n+ else:\n+ output: dict[int, ArrayLike] = {\n+ idx: self._grouper.agg_series(ser, f)\n+ for idx, (name, ser) in enumerate(obj.items())\n+ }\n+ res = self.obj._constructor(output)\n+ res.columns = obj.columns.copy(deep=False)\n return self._wrap_aggregated_output(res)\n \n def _aggregate_frame(self, func, *args, **kwargs) -> DataFrame:" }, { "filename": "pandas/core/groupby/groupby.py", "status": "modified", "additions": 0, "deletions": 5, "changes": 5, "patch": "@@ -1658,7 +1658,6 @@ def _python_apply_general(\n data: DataFrame | Series,\n not_indexed_same: bool | None = None,\n is_transform: bool = False,\n- is_agg: bool = False,\n ) -> NDFrameT:\n \"\"\"\n Apply function f in python space\n@@ -1676,10 +1675,6 @@ def _python_apply_general(\n is_transform : bool, default False\n Indicator for whether the function is actually a transform\n and should not have group keys prepended.\n- is_agg : bool, default False\n- Indicator for whether the function is an aggregation. When the\n- result is empty, we don't want to warn for this case.\n- See _GroupBy._python_agg_general.\n \n Returns\n -------" }, { "filename": "pandas/tests/groupby/aggregate/test_aggregate.py", "status": "modified", "additions": 20, "deletions": 2, "changes": 22, "patch": "@@ -1032,13 +1032,31 @@ def test_groupby_aggregate_empty_key_empty_return():\n tm.assert_frame_equal(result, expected)\n \n \n-def test_groupby_aggregate_empty_with_multiindex_frame():\n+def test_groupby_aggregate_empty_with_multiindex_frame_single(as_index):\n+ # GH 39178, 51445\n+ df = DataFrame(columns=[\"a\", \"b\", \"c\"])\n+ gb = df.groupby([\"a\", \"b\"], group_keys=False, as_index=as_index)\n+ result = gb.agg(lambda x: x.sum())\n+ expected = DataFrame(\n+ columns=[\"c\"], index=MultiIndex([[], []], [[], []], names=[\"a\", \"b\"])\n+ )\n+ if not as_index:\n+ expected = expected.reset_index()\n+ tm.assert_frame_equal(result, expected)\n+\n+\n+def test_groupby_aggregate_empty_with_multiindex_frame_multi(as_index):\n # GH 39178\n df = DataFrame(columns=[\"a\", \"b\", \"c\"])\n- result = df.groupby([\"a\", \"b\"], group_keys=False).agg(d=(\"c\", list))\n+ result = df.groupby([\"a\", \"b\"], group_keys=False, as_index=as_index).agg(\n+ d=(\"c\", list)\n+ )\n expected = DataFrame(\n columns=[\"d\"], index=MultiIndex([[], []], [[], []], names=[\"a\", \"b\"])\n )\n+ if not as_index:\n+ expected = expected.reset_index()\n+\n tm.assert_frame_equal(result, expected)" }, { "filename": "pandas/tests/groupby/test_groupby.py", "status": "modified", "additions": 18, "deletions": 8, "changes": 26, "patch": "@@ -1835,14 +1835,24 @@ def get_categorical_invalid_expected():\n tm.assert_equal(result, expected)\n \n \n-def test_empty_groupby_apply_nonunique_columns():\n- # GH#44417\n- df = DataFrame(np.random.default_rng(2).standard_normal((0, 4)))\n- df[3] = df[3].astype(np.int64)\n- df.columns = [0, 1, 2, 0]\n- gb = df.groupby(df[1], group_keys=False)\n- res = gb.apply(lambda x: x)\n- assert (res.dtypes == df.drop(columns=1).dtypes).all()\n+[USER_REDACTED].mark.parametrize(\"method_name\", [\"agg\", \"apply\"])\n+[USER_REDACTED].mark.parametrize(\"keys\", [[1], [1, 2]])\n+def test_empty_groupby_apply_nonunique_columns(method_name, keys):\n+ # GH#44417 & GH#63975\n+ df = DataFrame(np.random.default_rng(2).standard_normal((0, 5)))\n+ df[4] = df[4].astype(np.int64)\n+ df.columns = [0, 1, 2, 3, 0]\n+ gb = df.groupby(keys, group_keys=False)\n+ method = getattr(gb, method_name)\n+ result = method(lambda x: x)\n+ expected = DataFrame(dtype=\"float64\", columns=range(5))\n+ expected[4] = expected[4].astype(\"int64\")\n+ expected.columns = [0, 1, 2, 3, 0]\n+ if method_name == \"agg\":\n+ expected = expected.set_index(keys)\n+ else:\n+ expected = expected.drop(columns=keys)\n+ tm.assert_frame_equal(result, expected)\n \n \n def test_tuple_as_grouping():" } ], "reviews": [ { "id": 3748120710, "user": "user_c9260bc45a59", "state": "APPROVED", "body": null, "submitted_at": "2026-02-03T23:12:13+00:00" }, { "id": 3748177004, "user": "user_c1cc819e14db", "state": "COMMENTED", "body": null, "submitted_at": "2026-02-03T23:25:28+00:00" }, { "id": 3752001485, "user": "user_fb5fa0a10142", "state": "COMMENTED", "body": null, "submitted_at": "2026-02-04T16:22:29+00:00" }, { "id": 3752109069, "user": "user_fb5fa0a10142", "state": "COMMENTED", "body": null, "submitted_at": "2026-02-04T16:44:46+00:00" }, { "id": 3756443124, "user": "user_c1cc819e14db", "state": "COMMENTED", "body": null, "submitted_at": "2026-02-05T11:34:29+00:00" }, { "id": 3756444644, "user": "user_c1cc819e14db", "state": "COMMENTED", "body": null, "submitted_at": "2026-02-05T11:34:49+00:00" }, { "id": 3758426835, "user": "user_fb5fa0a10142", "state": "COMMENTED", "body": null, "submitted_at": "2026-02-05T17:24:57+00:00" }, { "id": 3758588742, "user": "user_fb5fa0a10142", "state": "APPROVED", "body": null, "submitted_at": "2026-02-05T17:58:14+00:00" } ], "review_comments": [ { "id": 2761435388, "user": "user_c9260bc45a59", "body": "Could use a dict comprehension if you're inclined", "path": "pandas/core/groupby/generic.py", "line": null, "side": "RIGHT", "created_at": "2026-02-03T23:11:00+00:00" }, { "id": 2761481101, "user": "user_c1cc819e14db", "body": "Good call, done.", "path": "pandas/core/groupby/generic.py", "line": null, "side": "RIGHT", "created_at": "2026-02-03T23:25:28+00:00" }, { "id": 2764842219, "user": "user_fb5fa0a10142", "body": "are these comments about tests hitting these paths still useful?", "path": "pandas/core/groupby/generic.py", "line": 2383, "side": "LEFT", "created_at": "2026-02-04T16:22:30+00:00" }, { "id": 2764938496, "user": "user_fb5fa0a10142", "body": "is this astype going to misbehave if obj.columns is non-unique?", "path": "pandas/core/groupby/generic.py", "line": 2380, "side": "RIGHT", "created_at": "2026-02-04T16:44:46+00:00" }, { "id": 2768612730, "user": "user_c1cc819e14db", "body": "I was guessing these were added (e.g. in #51447) for future work on simplifying these paths. I believe this PR accomplishes that. If there is another reason these might exist, I can restore and add a comment as to why.", "path": "pandas/core/groupby/generic.py", "line": 2383, "side": "LEFT", "created_at": "2026-02-05T11:34:29+00:00" }, { "id": 2768614007, "user": "user_c1cc819e14db", "body": "No, when the indexes of the caller and callee match, astype does the correct thing. Added a test.", "path": "pandas/core/groupby/generic.py", "line": 2380, "side": "RIGHT", "created_at": "2026-02-05T11:34:49+00:00" }, { "id": 2770300721, "user": "user_fb5fa0a10142", "body": "i suspect they were added as an easy way to tell \"this path has test coverage\". so makes sense theyd no longer be relevant. thanks for taking a look", "path": "pandas/core/groupby/generic.py", "line": 2383, "side": "LEFT", "created_at": "2026-02-05T17:24:57+00:00" } ], "meta": { "languages": [ "py", "rst" ], "touches_tests": true, "review_state_summary": { "APPROVED": 2, "COMMENTED": 6 }, "meaningful_comment_count": 7, "has_approval": true, "has_changes_requested": false, "total_review_comments": 7 } } { "_id": "113ec2f3cb3c2c79", "_schema_version": "1.0", "_cleaned_at": "2026-02-12T07:46:51.781247+00:00", "repo": "pandas-dev/pandas", "repo_url": "https://github.com/pandas-dev/pandas", "license_name": "BSD 3-Clause \"New\" or \"Revised\" License", "license_spdx": "BSD-3-Clause", "pr_number": 63955, "title": "DOC: Fix spelling mistakes and incomplete sentences in Timestamp docstrings", "body": "This PR fixes a couple of clear spelling mistakes and a few incomplete or\nawkwardly phrased sentences in Timestamp-related docstrings.\nThese are documentation-only changes and do not affect any behavior or logic.", "author": "user_a979682f68b9", "created_at": "2026-01-30T18:45:03+00:00", "merged_at": "2026-02-09T22:28:46+00:00", "base_branch": "main", "head_branch": "doc-grammar-fix-clean", "additions": 6, "deletions": 6, "changed_files": 6, "files": [ { "filename": "pandas/_libs/tslibs/parsing.pyx", "status": "modified", "additions": 1, "deletions": 1, "changes": 2, "patch": "@@ -716,7 +716,7 @@ cdef datetime dateutil_parse(\n # e.g. \"1994 Jan 15 05:16 FOO\" where FOO is not recognized\n # GH#18702, # GH 50235 enforced in 3.0\n raise ValueError(\n- f'Parsed string \"{timestr}\" included an un-recognized timezone '\n+ f'Parsed string \"{timestr}\" included an unrecognized timezone '\n f'\"{res.tzname}\".'\n )" }, { "filename": "pandas/_libs/tslibs/timestamps.pyx", "status": "modified", "additions": 1, "deletions": 1, "changes": 2, "patch": "@@ -3475,7 +3475,7 @@ default 'raise'\n \n def to_julian_date(self) -> np.float64:\n \"\"\"\n- [NAME_REDACTED] to a [NAME_REDACTED].\n+ [NAME_REDACTED] to a [NAME_REDACTED] method returns the number of days as a float since\n 0 Julian date, which is noon January 1, 4713 BC." }, { "filename": "pandas/core/arrays/datetimes.py", "status": "modified", "additions": 1, "deletions": 1, "changes": 2, "patch": "@@ -2260,7 +2260,7 @@ def isocalendar(self) -> DataFrame:\n \n def to_julian_date(self) -> npt.NDArray[np.float64]:\n \"\"\"\n- [NAME_REDACTED] to a [NAME_REDACTED].\n+ [NAME_REDACTED] to a [NAME_REDACTED] method returns the number of days as a float since noon January 1, 4713 BC." }, { "filename": "pandas/core/indexes/datetimes.py", "status": "modified", "additions": 1, "deletions": 1, "changes": 2, "patch": "@@ -601,7 +601,7 @@ def to_period(self, freq=None) -> PeriodIndex:\n \n def to_julian_date(self) -> Index:\n \"\"\"\n- [NAME_REDACTED] to a [NAME_REDACTED].\n+ [NAME_REDACTED] to a [NAME_REDACTED] method returns the number of days as a float since noon January 1, 4713 BC." }, { "filename": "pandas/tests/tools/test_to_datetime.py", "status": "modified", "additions": 1, "deletions": 1, "changes": 2, "patch": "@@ -3611,7 +3611,7 @@ def test_to_datetime_iso8601_utc_mixed_both_offsets():\n def test_unknown_tz_raises():\n # GH#18702, GH#51476\n dtstr = \"2014 Jan 9 05:15 FAKE\"\n- msg = '.*un-recognized timezone \"FAKE\".'\n+ msg = '.*unrecognized timezone \"FAKE\".'\n with pytest.raises(ValueError, match=msg):\n Timestamp(dtstr)" }, { "filename": "pandas/tests/tslibs/test_parsing.py", "status": "modified", "additions": 1, "deletions": 1, "changes": 2, "patch": "@@ -43,7 +43,7 @@ def test_parsing_tzlocal_deprecated():\n r\"Parsing 'EST' as tzlocal \\(dependent on system timezone\\) \"\n r\"is no longer supported\\. \"\n \"Pass the 'tz' keyword or call tz_localize after construction instead\",\n- \".*included an un-recognized timezone\",\n+ \".*included an unrecognized timezone\",\n ]\n )\n dtstr = \"Jan 15 2004 03:00 EST\"" } ], "reviews": [ { "id": 3730358030, "user": "user_c1cc819e14db", "state": "CHANGES_REQUESTED", "body": "Thanks for the PR! The pr-commit build needs to be passing.", "submitted_at": "2026-01-30T20:51:03+00:00" }, { "id": 3733017033, "user": "user_c1cc819e14db", "state": "APPROVED", "body": "lgtm", "submitted_at": "2026-01-31T16:49:15+00:00" }, { "id": 3775731372, "user": "user_c1cc819e14db", "state": "APPROVED", "body": "lgtm", "submitted_at": "2026-02-09T22:28:32+00:00" } ], "review_comments": [ { "id": 2747940828, "user": "user_c1cc819e14db", "body": "The existence or not of `for` seems to me to be a matter of style, can you revert.\n\nAdding a period in the middle of these sentence is grammatically incorrect.", "path": "pandas/_libs/tslibs/timestamps.pyx", "line": null, "side": "RIGHT", "created_at": "2026-01-30T20:49:42+00:00" }, { "id": 2747943810, "user": "user_c1cc819e14db", "body": "This seems fine as-is. Can you revert.", "path": "pandas/_libs/tslibs/timestamps.pyx", "line": null, "side": "RIGHT", "created_at": "2026-01-30T20:50:50+00:00" } ], "meta": { "languages": [ "py", "pyx" ], "touches_tests": true, "review_state_summary": { "CHANGES_REQUESTED": 1, "APPROVED": 2 }, "meaningful_comment_count": 2, "has_approval": true, "has_changes_requested": true, "total_review_comments": 2 } } { "_id": "c857fc8c4eb66333", "_schema_version": "1.0", "_cleaned_at": "2026-02-12T07:46:51.781247+00:00", "repo": "pandas-dev/pandas", "repo_url": "https://github.com/pandas-dev/pandas", "license_name": "BSD 3-Clause \"New\" or \"Revised\" License", "license_spdx": "BSD-3-Clause", "pr_number": 63945, "title": "BUG: unary operators not supported with pd.col (issue#63939)", "body": "- [x] closes #63939 (Replace xxxx with the GitHub issue number)\n- [x] [Tests added and passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#writing-tests) if fixing a bug or adding a new feature\n- [x] All [code checks passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit).\n- [x] Added [type annotations](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#type-hints) to new arguments/methods/functions.\n- [x] Added an entry in the latest `doc/source/whatsnew/vX.X.X.rst` file if fixing a bug or adding a new feature.\n- [x] I have reviewed and followed all the [contribution guidelines](https://pandas.pydata.org/docs/dev/development/contributing.html)\n- [x] If I used AI to develop this pull request, I prompted it to follow `AGENTS.md`.\n\n### issue\npd.col() does not support unary operator.\n``` python\n-1 * pd.col(\"A\") # OK\n-pd.col(\"A\") # error\n+pd.col(\"A\") # error\n```\n\n### implement\npd.col() support unary operator\n``` python\n-pd.col(\"A\") # OK\n+pd.col(\"A\") # OK\n```", "author": "user_2413f82a985d", "created_at": "2026-01-30T04:30:20+00:00", "merged_at": "2026-01-31T18:26:56+00:00", "base_branch": "main", "head_branch": "AssignSupportPreMinus", "additions": 37, "deletions": 0, "changed_files": 3, "files": [ { "filename": "doc/source/whatsnew/v3.0.1.rst", "status": "modified", "additions": 1, "deletions": 0, "changes": 1, "patch": "@@ -16,6 +16,7 @@ Bug fixes\n - Fixed a bug in the :class:`DataFrame` constructor when passed a :class:`Series` or\n :class:`Index` correctly handling Copy-on-Write (:issue:`63899`)\n - Allow :class:`.ExtensionArray` to have dtypes involving :class:`numpy.void` (:issue:`54810`)\n+- Fixed a bug in :func:`col` where unary operators (``-``, ``+``, ``abs``) were not supported (:issue:`63939`)\n \n .. ---------------------------------------------------------------------------\n .. _whatsnew_301.contributors:" }, { "filename": "pandas/core/col.py", "status": "modified", "additions": 29, "deletions": 0, "changes": 29, "patch": "@@ -230,6 +230,35 @@ def __invert__(self) -> Expression:\n needs_parenthese=True,\n )\n \n+ def __neg__(self) -> Expression:\n+ if self._needs_parentheses:\n+ repr_str = f\"-({self._repr_str})\"\n+ else:\n+ repr_str = f\"-{self._repr_str}\"\n+ return Expression(\n+ lambda df: -self._eval_expression(df),\n+ repr_str,\n+ needs_parenthese=True,\n+ )\n+\n+ def __pos__(self) -> Expression:\n+ if self._needs_parentheses:\n+ repr_str = f\"+({self._repr_str})\"\n+ else:\n+ repr_str = f\"+{self._repr_str}\"\n+ return Expression(\n+ lambda df: +self._eval_expression(df),\n+ repr_str,\n+ needs_parenthese=True,\n+ )\n+\n+ def __abs__(self) -> Expression:\n+ return Expression(\n+ lambda df: abs(self._eval_expression(df)),\n+ f\"abs({self._repr_str})\",\n+ needs_parenthese=True,\n+ )\n+\n def __array_ufunc__(\n self, ufunc: Callable[..., Any], method: str, *inputs: Any, **kwargs: Any\n ) -> Expression:" }, { "filename": "pandas/tests/test_col.py", "status": "modified", "additions": 7, "deletions": 0, "changes": 7, "patch": "@@ -46,6 +46,13 @@\n [False, True],\n \"(col('a') - 1).astype('bool')\",\n ),\n+ # Unary operators\n+ (-pd.col(\"a\"), [-1, -2], \"-col('a')\"),\n+ (+pd.col(\"a\"), [1, 2], \"+col('a')\"),\n+ (-(pd.col(\"a\") + 1), [-2, -3], \"-(col('a') + 1)\"),\n+ (-pd.col(\"a\") * 2, [-2, -4], \"(-col('a')) * 2\"),\n+ (abs(pd.col(\"a\")), [1, 2], \"abs(col('a'))\"),\n+ (abs(pd.col(\"a\") - 2), [1, 0], \"abs(col('a') - 2)\"),\n ],\n )\n def test_col_simple(" } ], "reviews": [ { "id": 3729697835, "user": "user_c9260bc45a59", "state": "COMMENTED", "body": null, "submitted_at": "2026-01-30T18:04:02+00:00" }, { "id": 3731550222, "user": "user_a07029230fc9", "state": "COMMENTED", "body": "Thank you for working on this issue. I have reviewed the code changes and they look good overall.\n\n**[NAME_REDACTED]:**\n\nThe implementation correctly adds support for unary operators (`-` and `+`) to `pd.col()` by implementing `__neg__` and `__pos__` methods in the Expression class. The logic follows the existing patterns in the codebase.\n\n**What I verified:**\n\n1. ✓ Tests added for the new functionality covering various use cases\n2. ✓ Documentation updated in the whatsnew file\n3. ✓ Code follows the existing pattern for Expression class methods\n4. ✓ Proper handling of parentheses based on `_needs_parentheses` flag\n5. ✓ Lambda functions correctly apply the unary operations\n6. ✓ AI tool usage properly disclosed in PR description following contribution guidelines\n\n**CI/CD Status:**\nI noticed there are test failures in the CI pipeline (16 jobs failed). These appear to be in various platform-specific test suites. Could you please investigate whether these failures are related to your changes or if they are pre-existing issues?\n\nThe implementation addresses issue #63939 correctly. The code is clean and well-structured.\n\n**Note:** I used an AI coding assistant to help analyze this PR, and I have reviewed and agree with the assessment provided.", "submitted_at": "2026-01-31T05:10:37+00:00" }, { "id": 3732144076, "user": "user_2413f82a985d", "state": "COMMENTED", "body": null, "submitted_at": "2026-01-31T09:44:05+00:00" }, { "id": 3732317584, "user": "user_2413f82a985d", "state": "COMMENTED", "body": null, "submitted_at": "2026-01-31T11:25:40+00:00" }, { "id": 3733211158, "user": "user_c9260bc45a59", "state": "APPROVED", "body": null, "submitted_at": "2026-01-31T18:26:42+00:00" } ], "review_comments": [ { "id": 2747394336, "user": "user_c9260bc45a59", "body": "Could you add `__abs__` as well while we're adding these?", "path": "pandas/core/col.py", "line": 244, "side": "RIGHT", "created_at": "2026-01-30T18:04:02+00:00" }, { "id": 2749272093, "user": "user_2413f82a985d", "body": "Thank you for your review. I will add `__abs__`.", "path": "pandas/core/col.py", "line": 244, "side": "RIGHT", "created_at": "2026-01-31T09:44:05+00:00" }, { "id": 2749412158, "user": "user_2413f82a985d", "body": "[USER_REDACTED] I have reflected your review.", "path": "pandas/core/col.py", "line": 244, "side": "RIGHT", "created_at": "2026-01-31T11:25:40+00:00" } ], "meta": { "languages": [ "py", "rst" ], "touches_tests": true, "review_state_summary": { "COMMENTED": 4, "APPROVED": 1 }, "meaningful_comment_count": 3, "has_approval": true, "has_changes_requested": false, "total_review_comments": 3 } } { "_id": "723c1e1102b32e09", "_schema_version": "1.0", "_cleaned_at": "2026-02-12T07:46:51.781247+00:00", "repo": "pandas-dev/pandas", "repo_url": "https://github.com/pandas-dev/pandas", "license_name": "BSD 3-Clause \"New\" or \"Revised\" License", "license_spdx": "BSD-3-Clause", "pr_number": 63942, "title": "replaced all [USER_REDACTED] in core/arrays/arrow/array.py with inline docstrings", "body": "- [x] xref #62437 (partially)\n- [x] [Tests added and passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#writing-tests) if fixing a bug or adding a new feature\n- [x] All [code checks passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit).\n- [x] Added [type annotations](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#type-hints) to new arguments/methods/functions.\n- [x] Added an entry in the latest `doc/source/whatsnew/vX.X.X.rst` file if fixing a bug or adding a new feature.\n- [x] I have reviewed and followed all the [contribution guidelines](https://pandas.pydata.org/docs/dev/development/contributing.html)\n- [x] If I used AI to develop this pull request, I prompted it to follow `AGENTS.md`.\n\n[USER_REDACTED] replaced with direct copies of method docstring from core/arrays/base.py (to which the [USER_REDACTED] decorators referred). Modified the docstring of the fillna method to reflect that the return type is ArrowExtensionArray rather than generic ExtensionArray.", "author": "user_b405f2423419", "created_at": "2026-01-29T21:30:41+00:00", "merged_at": "2026-02-03T22:15:56+00:00", "base_branch": "main", "head_branch": "arrow-array-replace-@doc", "additions": 178, "deletions": 6, "changed_files": 1, "files": [ { "filename": "pandas/core/arrays/arrow/array.py", "status": "modified", "additions": 178, "deletions": 6, "changes": 184, "patch": "@@ -38,7 +38,6 @@\n )\n from pandas.errors import Pandas4Warning\n from pandas.util._decorators import (\n- doc,\n set_module,\n )\n from pandas.util._exceptions import find_stack_level\n@@ -1372,13 +1371,50 @@ def _pad_or_backfill(\n method=method, limit=limit, limit_area=limit_area, copy=copy\n )\n \n- [USER_REDACTED](ExtensionArray.fillna)\n def fillna(\n self,\n value: object | ArrayLike,\n limit: int | None = None,\n copy: bool = True,\n ) -> Self:\n+ \"\"\"\n+ Fill NA/NaN values using the specified method.\n+\n+ Parameters\n+ ----------\n+ value : scalar, array-like\n+ If a scalar value is passed it is used to fill all missing values.\n+ Alternatively, an array-like \"value\" can be given. It's expected\n+ that the array-like have the same length as 'self'.\n+ limit : int, default None\n+ The maximum number of entries where NA values will be filled.\n+ copy : bool, default True\n+ Whether to make a copy of the data before filling. This parameter\n+ is inherited from pandas.ExtensionArray and should be left at its\n+ default value (Arrow arrays cannot be altered in place).\n+\n+ Returns\n+ -------\n+ ArrowExtensionArray\n+ With NA/NaN filled.\n+\n+ See Also\n+ --------\n+ api.extensions.ExtensionArray.dropna : [NAME_REDACTED] without\n+ NA values.\n+ api.extensions.ExtensionArray.isna : A 1-D array indicating if\n+ each value is missing.\n+\n+ Examples\n+ --------\n+ >>> arr = pd.array(\n+ ... [np.nan, np.nan, 2, 3, np.nan, np.nan], dtype=\"int64[pyarrow]\"\n+ ... )\n+ >>> arr.fillna(0)\n+ \n+ [0, 0, 2, 3, 0, 0]\n+ Length: 6, dtype: int64[pyarrow]\n+ \"\"\"\n if not self._hasna:\n return self.copy()\n \n@@ -1440,11 +1476,55 @@ def _values_for_factorize(self) -> tuple[np.ndarray, Any]:\n values = self._pa_array.to_numpy()\n return values, self.dtype.na_value\n \n- [USER_REDACTED](ExtensionArray.factorize)\n def factorize(\n self,\n use_na_sentinel: bool = True,\n ) -> tuple[np.ndarray, ExtensionArray]:\n+ \"\"\"\n+ Encode the arrow array as an enumerated type.\n+\n+ Parameters\n+ ----------\n+ use_na_sentinel : bool, default True\n+ If True, the sentinel -1 will be used for NaN values. If False,\n+ NaN values will be encoded as non-negative integers and will not drop the\n+ NaN from the uniques of the values.\n+\n+ Returns\n+ -------\n+ codes : ndarray\n+ An integer NumPy array that's an indexer into the original\n+ ArrowArray.\n+ uniques : ArrowArray\n+ An ArrowArray containing the unique values of `self`.\n+\n+ .. note::\n+\n+ uniques will *not* contain an entry for the NA value of\n+ the ArrowArray if there are any missing values present\n+ in `self`.\n+\n+ See Also\n+ --------\n+ factorize : Top-level factorize method that dispatches here.\n+\n+ Notes\n+ -----\n+ :meth:`pandas.factorize` offers a `sort` keyword as well.\n+\n+ Examples\n+ --------\n+ >>> arr = pd.array(\n+ ... [\"Ant\", \"Badger\", \"Cobra\", \"Cobra\", \"Deer\", \"Ant\"], dtype=str\n+ ... )\n+ >>> arr_codes, arr_uniques = arr.factorize()\n+ >>> arr_codes\n+ array([0, 1, 2, 2, 3, 0])\n+ >>> arr_uniques\n+ \n+ ['Ant', 'Badger', 'Cobra', 'Deer']\n+ Length: 4, dtype: str\n+ \"\"\"\n null_encoding = \"mask\" if use_na_sentinel else \"encode\"\n \n data = self._pa_array\n@@ -1506,13 +1586,56 @@ def round(self, decimals: int = 0, *args, **kwargs) -> Self:\n \"\"\"\n return self._from_pyarrow_array(pc.round(self._pa_array, ndigits=decimals))\n \n- [USER_REDACTED](ExtensionArray.searchsorted)\n def searchsorted(\n self,\n value: NumpyValueArrayLike | ExtensionArray,\n side: Literal[\"left\", \"right\"] = \"left\",\n sorter: NumpySorter | None = None,\n ) -> npt.NDArray[np.intp] | np.intp:\n+ \"\"\"\n+ Find indices where elements should be inserted to maintain order.\n+\n+ Find the indices into a sorted array `self` (a) such that, if the\n+ corresponding elements in `value` were inserted before the indices,\n+ the order of `self` would be preserved.\n+\n+ Assuming that `self` is sorted:\n+\n+ ====== ================================\n+ `side` returned index `i` satisfies\n+ ====== ================================\n+ left ``self[i-1] < value <= self[i]``\n+ right ``self[i-1] <= value < self[i]``\n+ ====== ================================\n+\n+ Parameters\n+ ----------\n+ value : array-like, list or scalar\n+ Value(s) to insert into `self`.\n+ side : {'left', 'right'}, optional\n+ If 'left', the index of the first suitable location found is given.\n+ If 'right', return the last such index. If there is no suitable\n+ index, return either 0 or N (where N is the length of `self`).\n+ sorter : 1-D array-like, optional\n+ Optional array of integer indices that sort array a into ascending\n+ order. They are typically the result of argsort.\n+\n+ Returns\n+ -------\n+ array of ints or int\n+ If value is array-like, array of insertion points.\n+ If value is scalar, a single integer.\n+\n+ See Also\n+ --------\n+ numpy.searchsorted : Similar method from NumPy.\n+\n+ Examples\n+ --------\n+ >>> arr = pd.array([1, 2, 3, 5], dtype=\"int64[pyarrow]\")\n+ >>> arr.searchsorted([4])\n+ array([3])\n+ \"\"\"\n if self._hasna:\n raise ValueError(\n \"searchsorted requires array to be sorted, which is impossible \"\n@@ -1664,13 +1787,35 @@ def _values_for_json(self) -> np.ndarray:\n return np.asarray(self, dtype=object)\n return super()._values_for_json()\n \n- [USER_REDACTED](ExtensionArray.to_numpy)\n def to_numpy(\n self,\n dtype: npt.DTypeLike | None = None,\n copy: bool = False,\n na_value: object = lib.no_default,\n ) -> np.ndarray:\n+ \"\"\"\n+ Convert to a NumPy ndarray.\n+\n+ This is similar to :meth:`numpy.asarray`, but may provide additional control\n+ over how the conversion is done.\n+\n+ Parameters\n+ ----------\n+ dtype : str or numpy.dtype, optional\n+ The dtype to pass to :meth:`numpy.asarray`.\n+ copy : bool, default False\n+ Whether to ensure that the returned value is a not a view on\n+ another array. Note that ``copy=False`` does not *ensure* that\n+ ``to_numpy()`` is no-copy. Rather, ``copy=True`` ensure that\n+ a copy is made, even if not strictly necessary.\n+ na_value : Any, optional\n+ The value to use for missing values. The default value depends\n+ on `dtype` and the type of the array.\n+\n+ Returns\n+ -------\n+ numpy.ndarray\n+ \"\"\"\n original_na_value = na_value\n dtype, na_value = to_numpy_dtype_inference(self, dtype, na_value, self._hasna)\n pa_type = self._pa_array.type\n@@ -1736,10 +1881,37 @@ def map(self, mapper, na_action: Literal[\"ignore\"] | None = None):\n # to None.\n return super().map(mapper, na_action)\n \n- [USER_REDACTED](ExtensionArray.duplicated)\n def duplicated(\n self, keep: Literal[\"first\", \"last\", False] = \"first\"\n ) -> npt.NDArray[np.bool_]:\n+ \"\"\"\n+ Return boolean ndarray denoting duplicate values.\n+\n+ Parameters\n+ ----------\n+ keep : {'first', 'last', False}, default 'first'\n+ - ``first`` : Mark duplicates as ``True`` except for the first occurrence.\n+ - ``last`` : Mark duplicates as ``True`` except for the last occurrence.\n+ - False : Mark all duplicates as ``True``.\n+\n+ Returns\n+ -------\n+ ndarray[bool]\n+ With true in indices where elements are duplicated and false otherwise.\n+\n+ See Also\n+ --------\n+ DataFrame.duplicated : Return boolean Series denoting\n+ duplicate rows.\n+ Series.duplicated : Indicate duplicate Series values.\n+ api.extensions.ExtensionArray.unique : Compute the ExtensionArray\n+ of unique values.\n+\n+ Examples\n+ --------\n+ >>> pd.array([1, 1, 2, 3, 3], dtype=\"int64[pyarrow]\").duplicated()\n+ array([False, True, False, False, True])\n+ \"\"\"\n pa_type = self._pa_array.type\n if pa.types.is_floating(pa_type) or pa.types.is_integer(pa_type):\n values = self.to_numpy(na_value=0)" } ], "reviews": [ { "id": 3725606415, "user": "user_c9260bc45a59", "state": "COMMENTED", "body": null, "submitted_at": "2026-01-30T00:07:16+00:00" }, { "id": 3725741446, "user": "user_b405f2423419", "state": "COMMENTED", "body": null, "submitted_at": "2026-01-30T00:53:10+00:00" }, { "id": 3729251790, "user": "user_b405f2423419", "state": "COMMENTED", "body": null, "submitted_at": "2026-01-30T16:23:53+00:00" }, { "id": 3729545023, "user": "user_c9260bc45a59", "state": "COMMENTED", "body": null, "submitted_at": "2026-01-30T17:28:04+00:00" }, { "id": 3729551560, "user": "user_c9260bc45a59", "state": "COMMENTED", "body": null, "submitted_at": "2026-01-30T17:29:19+00:00" }, { "id": 3730414142, "user": "user_b405f2423419", "state": "COMMENTED", "body": null, "submitted_at": "2026-01-30T21:08:53+00:00" }, { "id": 3730457873, "user": "user_c9260bc45a59", "state": "COMMENTED", "body": null, "submitted_at": "2026-01-30T21:23:28+00:00" }, { "id": 3746563035, "user": "user_b405f2423419", "state": "COMMENTED", "body": null, "submitted_at": "2026-02-03T17:22:42+00:00" }, { "id": 3747871583, "user": "user_c9260bc45a59", "state": "APPROVED", "body": null, "submitted_at": "2026-02-03T22:15:27+00:00" } ], "review_comments": [ { "id": 2744040283, "user": "user_c9260bc45a59", "body": "Similar comment as your other PR, could you ensure these examples show that the array is an `ArrowExtensionArray`?", "path": "pandas/core/arrays/arrow/array.py", "line": null, "side": "RIGHT", "created_at": "2026-01-30T00:07:16+00:00" }, { "id": 2744156136, "user": "user_b405f2423419", "body": "Oh, yes. I will start working on that.", "path": "pandas/core/arrays/arrow/array.py", "line": null, "side": "RIGHT", "created_at": "2026-01-30T00:53:10+00:00" }, { "id": 2747035501, "user": "user_b405f2423419", "body": "Question: for the ArrowArray.fillna() method, the docstring from ExtensionArray says that copy defaults to true, but that some ExtensionArray subclasses may not be able to do false. [NAME_REDACTED] fillna in place?", "path": "pandas/core/arrays/arrow/array.py", "line": null, "side": "RIGHT", "created_at": "2026-01-30T16:23:53+00:00" }, { "id": 2747269883, "user": "user_c9260bc45a59", "body": "> [NAME_REDACTED] fillna in place?\n\nI believe not, no. Pyarrow arrays are immutable so I doubt pyarrow will add support for inplace filling", "path": "pandas/core/arrays/arrow/array.py", "line": null, "side": "RIGHT", "created_at": "2026-01-30T17:28:04+00:00" }, { "id": 2747275595, "user": "user_c9260bc45a59", "body": "A reminder to update all examples changed here to use `ArrowExtentionArray`", "path": "pandas/core/arrays/arrow/array.py", "line": null, "side": "RIGHT", "created_at": "2026-01-30T17:29:19+00:00" }, { "id": 2747990668, "user": "user_b405f2423419", "body": "Clarifying question: the docstring for the factorize method (copied from ExtensionArray) uses a PeriodIndex object in its example, not an ExtensionArray. Do we still want me to replace it with an ArrowExtensionArray in the example, or was there some other reason for using a PeriodIndex instead?", "path": "pandas/core/arrays/arrow/array.py", "line": null, "side": "RIGHT", "created_at": "2026-01-30T21:08:53+00:00" }, { "id": 2748026418, "user": "user_c9260bc45a59", "body": "> Do we still want me to replace it with an ArrowExtensionArray in the example, or was there some other reason for using a PeriodIndex instead?\n\nYes, all the examples in this file should use `ArrowExtensionArray`.", "path": "pandas/core/arrays/arrow/array.py", "line": null, "side": "RIGHT", "created_at": "2026-01-30T21:23:28+00:00" }, { "id": 2760168075, "user": "user_b405f2423419", "body": "All the examples should now be updated to use ArrowExtensionArrays (for the factorize method I used an ArrowStringArray to more clearly demonstrate the difference between the codes and uniques arrays that are returned)", "path": "pandas/core/arrays/arrow/array.py", "line": null, "side": "RIGHT", "created_at": "2026-02-03T17:22:42+00:00" } ], "meta": { "languages": [ "py" ], "touches_tests": false, "review_state_summary": { "COMMENTED": 8, "APPROVED": 1 }, "meaningful_comment_count": 8, "has_approval": true, "has_changes_requested": false, "total_review_comments": 8 } } { "_id": "7f9bd9010fbdeba1", "_schema_version": "1.0", "_cleaned_at": "2026-02-12T07:46:51.781247+00:00", "repo": "pandas-dev/pandas", "repo_url": "https://github.com/pandas-dev/pandas", "license_name": "BSD 3-Clause \"New\" or \"Revised\" License", "license_spdx": "BSD-3-Clause", "pr_number": 63941, "title": "DOC Replace [USER_REDACTED] decorator with inline docstring in core/arrays/sparse/array.py", "body": "- [x] xref #62437\n- [x] [Tests added and passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#writing-tests) if fixing a bug or adding a new feature\n- [x] All [code checks passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit).\n- [x] Added [type annotations](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#type-hints) to new arguments/methods/functions.\n- [x] Added an entry in the latest `doc/source/whatsnew/vX.X.X.rst` file if fixing a bug or adding a new feature.\n- [ x] I have reviewed and followed all the [contribution guidelines](https://pandas.pydata.org/docs/dev/development/contributing.html)\n- [x] If I used AI to develop this pull request, I prompted it to follow `AGENTS.md`.", "author": "user_b405f2423419", "created_at": "2026-01-29T20:30:38+00:00", "merged_at": "2026-01-30T17:24:48+00:00", "base_branch": "main", "head_branch": "sparse-array-replace-@doc", "additions": 29, "deletions": 2, "changed_files": 1, "files": [ { "filename": "pandas/core/arrays/sparse/array.py", "status": "modified", "additions": 29, "deletions": 2, "changes": 31, "patch": "@@ -32,7 +32,6 @@\n from pandas.compat.numpy import function as nv\n from pandas.errors import PerformanceWarning\n from pandas.util._decorators import (\n- doc,\n set_module,\n )\n from pandas.util._exceptions import find_stack_level\n@@ -885,10 +884,38 @@ def _first_fill_value_loc(self):\n diff = np.r_[np.diff(indices), 2]\n return indices[(diff > 1).argmax()] + 1\n \n- [USER_REDACTED](ExtensionArray.duplicated)\n def duplicated(\n self, keep: Literal[\"first\", \"last\", False] = \"first\"\n ) -> npt.NDArray[np.bool_]:\n+ \"\"\"\n+ Return boolean ndarray denoting duplicate values.\n+\n+ Parameters\n+ ----------\n+ keep : {'first', 'last', False}, default 'first'\n+ - ``first`` : Mark duplicates as ``True`` except for the first occurrence.\n+ - ``last`` : Mark duplicates as ``True`` except for the last occurrence.\n+ - False : Mark all duplicates as ``True``.\n+\n+ Returns\n+ -------\n+ ndarray[bool]\n+ With true in indices where elements are duplicated and false otherwise.\n+\n+ See Also\n+ --------\n+ DataFrame.duplicated : Return boolean Series denoting\n+ duplicate rows.\n+ Series.duplicated : Indicate duplicate Series values.\n+ api.extensions.ExtensionArray.unique : Compute the ExtensionArray\n+ of unique values.\n+\n+ Examples\n+ --------\n+ >>> pd.array([1, 1, 2, 3, 3], dtype=pd.SparseDtype(np.int64)).duplicated()\n+ array([False, True, False, False, True])\n+ \"\"\"\n+\n values = np.asarray(self)\n mask = np.asarray(self.isna())\n return algos.duplicated(values, keep=keep, mask=mask)" } ], "reviews": [ { "id": 3725152685, "user": "user_c9260bc45a59", "state": "CHANGES_REQUESTED", "body": null, "submitted_at": "2026-01-29T21:29:28+00:00" }, { "id": 3725182325, "user": "user_b405f2423419", "state": "COMMENTED", "body": null, "submitted_at": "2026-01-29T21:37:29+00:00" }, { "id": 3725530129, "user": "user_b405f2423419", "state": "COMMENTED", "body": null, "submitted_at": "2026-01-29T23:34:17+00:00" }, { "id": 3729160517, "user": "user_b405f2423419", "state": "COMMENTED", "body": null, "submitted_at": "2026-01-30T16:09:33+00:00" }, { "id": 3729525006, "user": "user_c9260bc45a59", "state": "APPROVED", "body": null, "submitted_at": "2026-01-30T17:24:23+00:00" } ], "review_comments": [ { "id": 2743635631, "user": "user_c9260bc45a59", "body": "Can you modify this example to use a `SparseDtype(np.int64)` to match the parent class?", "path": "pandas/core/arrays/sparse/array.py", "line": null, "side": "RIGHT", "created_at": "2026-01-29T21:29:26+00:00" }, { "id": 2743660231, "user": "user_b405f2423419", "body": "Will do", "path": "pandas/core/arrays/sparse/array.py", "line": null, "side": "RIGHT", "created_at": "2026-01-29T21:37:28+00:00" }, { "id": 2743969238, "user": "user_b405f2423419", "body": "Done", "path": "pandas/core/arrays/sparse/array.py", "line": null, "side": "RIGHT", "created_at": "2026-01-29T23:34:17+00:00" }, { "id": 2746968764, "user": "user_b405f2423419", "body": "The docstring check script threw an error after I made the changes, but I'm not sure why. I ran the example code from the docstring and it executes normally. I pushed the commit to this branch so you can see; do you know what is making it fail the test?", "path": "pandas/core/arrays/sparse/array.py", "line": null, "side": "RIGHT", "created_at": "2026-01-30T16:09:33+00:00" } ], "meta": { "languages": [ "py" ], "touches_tests": false, "review_state_summary": { "CHANGES_REQUESTED": 1, "COMMENTED": 3, "APPROVED": 1 }, "meaningful_comment_count": 2, "has_approval": true, "has_changes_requested": true, "total_review_comments": 4 } } { "_id": "62f418434c9cfcaa", "_schema_version": "1.0", "_cleaned_at": "2026-02-12T07:46:51.797597+00:00", "repo": "pandas-dev/pandas", "repo_url": "https://github.com/pandas-dev/pandas", "license_name": "BSD 3-Clause \"New\" or \"Revised\" License", "license_spdx": "BSD-3-Clause", "pr_number": 63900, "title": "BUG: still use object dtype for pyarrow-backed IO methods with infer_strings disabled", "body": "xref https://github.com/[USER_REDACTED]ndas-dev/pandas/issues/63803\n\nThis actually \"fixes\" the behaviour, not necessarily because I think it is important to fix, but it was easier to do it this way than to update all the tests to change the expected result for those specific circumstances.", "author": "user_7213a217ace7", "created_at": "2026-01-27T14:51:19+00:00", "merged_at": "2026-01-29T09:12:31+00:00", "base_branch": "main", "head_branch": "ci-fix-no-infer-string", "additions": 69, "deletions": 31, "changed_files": 6, "files": [ { "filename": "pandas/io/_util.py", "status": "modified", "additions": 22, "deletions": 0, "changes": 22, "patch": "@@ -166,4 +166,26 @@ def _post_convert_dtypes(\n # GH#44901 reraise to keep api consistent\n raise ValueError(str(err)) from err\n \n+ if (\n+ not using_string_dtype()\n+ and dtype != \"str\"\n+ and (dtype_backend is lib.no_default or dtype_backend == \"numpy\")\n+ ):\n+ # Convert any StringDtype columns back to object dtype (pyarrow always\n+ # uses string dtype even when the infer_string option is False)\n+ for col, dtype in zip(df.columns, df.dtypes, strict=True):\n+ if isinstance(dtype, pd.StringDtype) and dtype.na_value is np.nan:\n+ df[col] = df[col].astype(\"object\").fillna(None)\n+ if isinstance(dtype, pd.CategoricalDtype):\n+ cat_dtype = dtype.categories.dtype\n+ if (\n+ isinstance(cat_dtype, pd.StringDtype)\n+ and cat_dtype.na_value is np.nan\n+ ):\n+ cat_dtype = pd.CategoricalDtype(\n+ categories=dtype.categories.astype(\"object\"),\n+ ordered=dtype.ordered,\n+ )\n+ df[col] = df[col].astype(cat_dtype)\n+\n return df" }, { "filename": "pandas/io/feather_format.py", "status": "modified", "additions": 10, "deletions": 1, "changes": 11, "patch": "@@ -8,6 +8,8 @@\n )\n import warnings\n \n+import numpy as np\n+\n from pandas._config import using_string_dtype\n \n from pandas._libs import lib\n@@ -17,6 +19,7 @@\n from pandas.util._validators import check_dtype_backend\n \n from pandas.core.api import DataFrame\n+from pandas.core.arrays.string_ import StringDtype\n \n from pandas.io._util import arrow_table_to_pandas\n from pandas.io.common import get_handle\n@@ -162,9 +165,15 @@ def read_feather(\n Pandas4Warning,\n )\n \n- return feather.read_feather(\n+ df = feather.read_feather(\n handles.handle, columns=columns, use_threads=bool(use_threads)\n )\n+ # Convert any StringDtype columns to object dtype (pyarrow always\n+ # uses string dtype even when the infer_string option is False)\n+ for col, dtype in zip(df.columns, df.dtypes, strict=True):\n+ if isinstance(dtype, StringDtype) and dtype.na_value is np.nan:\n+ df[col] = df[col].astype(\"object\")\n+ return df\n \n pa_table = feather.read_table(\n handles.handle, columns=columns, use_threads=bool(use_threads)" }, { "filename": "pandas/tests/arrays/string_/test_string.py", "status": "modified", "additions": 27, "deletions": 27, "changes": 54, "patch": "@@ -6,8 +6,6 @@\n import numpy as np\n import pytest\n \n-from pandas._config import using_string_dtype\n-\n from pandas.compat.pyarrow import pa_version_under19p0\n \n from pandas.core.dtypes.common import is_dtype_equal\n@@ -351,18 +349,16 @@ def test_arrow_roundtrip(dtype, string_storage, using_infer_string):\n assert table.field(\"a\").type == \"large_string\"\n with pd.option_context(\"string_storage\", string_storage):\n result = table.to_pandas()\n- if dtype.na_value is np.nan and not using_infer_string:\n- assert result[\"a\"].dtype == \"object\"\n- else:\n- assert isinstance(result[\"a\"].dtype, pd.StringDtype)\n- expected = df.astype(pd.StringDtype(string_storage, na_value=dtype.na_value))\n- if using_infer_string:\n- expected.columns = expected.columns.astype(\n- pd.StringDtype(string_storage, na_value=np.nan)\n- )\n- tm.assert_frame_equal(result, expected)\n- # ensure the missing value is represented by [NAME_REDACTED] or None\n- assert result.loc[2, \"a\"] is result[\"a\"].dtype.na_value\n+\n+ assert isinstance(result[\"a\"].dtype, pd.StringDtype)\n+ expected = df.astype(pd.StringDtype(string_storage, na_value=dtype.na_value))\n+ if using_infer_string:\n+ expected.columns = expected.columns.astype(\n+ pd.StringDtype(string_storage, na_value=np.nan)\n+ )\n+ tm.assert_frame_equal(result, expected)\n+ # ensure the missing value is represented by [NAME_REDACTED] or None\n+ assert result.loc[2, \"a\"] is result[\"a\"].dtype.na_value\n \n \n [USER_REDACTED].mark.filterwarnings(\"ignore:Passing a BlockManager:DeprecationWarning\")\n@@ -373,10 +369,17 @@ def test_arrow_from_string(using_infer_string):\n \n result = table.to_pandas()\n \n- if using_infer_string and not pa_version_under19p0:\n- expected = pd.DataFrame({\"a\": [\"a\", \"b\", None]}, dtype=\"str\")\n- else:\n+ if not using_infer_string:\n+ if pa_version_under19p0:\n+ expected = pd.DataFrame({\"a\": [\"a\", \"b\", None]}, dtype=\"object\")\n+ else:\n+ expected = pd.DataFrame(\n+ {\"a\": [\"a\", \"b\", None]}, dtype=pd.StringDtype(na_value=np.nan)\n+ )\n+ elif pa_version_under19p0:\n expected = pd.DataFrame({\"a\": [\"a\", \"b\", None]}, dtype=\"object\")\n+ else:\n+ expected = pd.DataFrame({\"a\": [\"a\", \"b\", None]}, dtype=\"str\")\n tm.assert_frame_equal(result, expected)\n \n \n@@ -397,16 +400,13 @@ def test_arrow_load_from_zero_chunks(dtype, string_storage, using_infer_string):\n with pd.option_context(\"string_storage\", string_storage):\n result = table.to_pandas()\n \n- if dtype.na_value is np.nan and not using_string_dtype():\n- assert result[\"a\"].dtype == \"object\"\n- else:\n- assert isinstance(result[\"a\"].dtype, pd.StringDtype)\n- expected = df.astype(pd.StringDtype(string_storage, na_value=dtype.na_value))\n- if using_infer_string:\n- expected.columns = expected.columns.astype(\n- pd.StringDtype(string_storage, na_value=np.nan)\n- )\n- tm.assert_frame_equal(result, expected)\n+ assert isinstance(result[\"a\"].dtype, pd.StringDtype)\n+ expected = df.astype(pd.StringDtype(string_storage, na_value=dtype.na_value))\n+ if using_infer_string:\n+ expected.columns = expected.columns.astype(\n+ pd.StringDtype(string_storage, na_value=np.nan)\n+ )\n+ tm.assert_frame_equal(result, expected)\n \n \n def test_value_counts_na(dtype):" }, { "filename": "pandas/tests/frame/methods/test_interpolate.py", "status": "modified", "additions": 3, "deletions": 1, "changes": 4, "patch": "@@ -64,7 +64,9 @@ def test_interpolate_inplace(self, frame_or_series, request):\n assert orig.squeeze()[1] == 1.5\n \n [USER_REDACTED].mark.parametrize(\"dtype\", [\"str\", \"object\"])\n- def test_interp_with_non_numeric(self, dtype):\n+ def test_interp_with_non_numeric(self, dtype, using_infer_string):\n+ if not using_infer_string:\n+ dtype = \"object\"\n df = DataFrame(\n {\n \"A\": [1, 2, np.nan, 4]," }, { "filename": "pandas/tests/frame/test_arrow_interface.py", "status": "modified", "additions": 4, "deletions": 1, "changes": 5, "patch": "@@ -1,5 +1,6 @@\n import ctypes\n \n+import numpy as np\n import pytest\n \n import pandas.util._test_decorators as td\n@@ -65,12 +66,14 @@ def __arrow_c_stream__(self, requested_schema=None):\n \n \n [USER_REDACTED].skip_if_no(\"pyarrow\", min_version=\"14.0\")\n-def test_dataframe_from_arrow():\n+def test_dataframe_from_arrow(using_infer_string):\n # objects with __arrow_c_stream__\n table = pa.table({\"a\": [1, 2, 3], \"b\": [\"a\", \"b\", \"c\"]})\n \n result = pd.DataFrame.from_arrow(table)\n expected = pd.DataFrame({\"a\": [1, 2, 3], \"b\": [\"a\", \"b\", \"c\"]})\n+ if not using_infer_string:\n+ expected[\"b\"] = expected[\"b\"].astype(pd.StringDtype(na_value=np.nan))\n tm.assert_frame_equal(result, expected)\n \n # not only pyarrow object are supported" }, { "filename": "pandas/tests/io/test_common.py", "status": "modified", "additions": 3, "deletions": 1, "changes": 4, "patch": "@@ -138,7 +138,7 @@ def test_bytesiowrapper_returns_correct_bytes(self):\n assert result == data.encode(\"utf-8\")\n \n # Test that pyarrow can handle a file opened with get_handle\n- def test_get_handle_pyarrow_compat(self):\n+ def test_get_handle_pyarrow_compat(sel, using_infer_string):\n pa_csv = pytest.importorskip(\"pyarrow.csv\")\n \n # Test latin1, ucs-2, and ucs-4 chars\n@@ -154,6 +154,8 @@ def test_get_handle_pyarrow_compat(self):\n df = pa_csv.read_csv(handles.handle).to_pandas()\n if pa_version_under19p0:\n expected = expected.astype(\"object\")\n+ elif not using_infer_string:\n+ expected = expected.astype(pd.StringDtype(na_value=np.nan))\n tm.assert_frame_equal(df, expected)\n assert not s.closed" } ], "reviews": [ { "id": 3719121819, "user": "user_c9260bc45a59", "state": "COMMENTED", "body": null, "submitted_at": "2026-01-28T20:58:26+00:00" }, { "id": 3719162567, "user": "user_c1cc819e14db", "state": "APPROVED", "body": "lgtm", "submitted_at": "2026-01-28T21:08:05+00:00" }, { "id": 3721508985, "user": "user_7213a217ace7", "state": "COMMENTED", "body": null, "submitted_at": "2026-01-29T09:12:12+00:00" } ], "review_comments": [ { "id": 2738581709, "user": "user_c9260bc45a59", "body": "question: Could you remind me of the convention for `object` \"string\" type using `None` vs `NaN` as th missing value in this case?", "path": "pandas/io/_util.py", "line": 178, "side": "RIGHT", "created_at": "2026-01-28T20:58:26+00:00" }, { "id": 2740653899, "user": "user_7213a217ace7", "body": "There is no exact convention, as a user you are free to use both. I think pandas will typically use NaN by [NAME_REDACTED] manually constructed by [NAME_REDACTED] (at least for example `read_csv` will give you NaN), but pyarrow specifically uses `None` for missing values when converting to numpy/pandas for object dtype.\n\nSo the `fillna(None)` above here is just to match pyarrow's behaviour", "path": "pandas/io/_util.py", "line": 178, "side": "RIGHT", "created_at": "2026-01-29T09:12:12+00:00" } ], "meta": { "languages": [ "py" ], "touches_tests": true, "review_state_summary": { "COMMENTED": 2, "APPROVED": 1 }, "meaningful_comment_count": 2, "has_approval": true, "has_changes_requested": false, "total_review_comments": 2 } } { "_id": "0cd240956635e7c8", "_schema_version": "1.0", "_cleaned_at": "2026-02-12T07:46:51.797934+00:00", "repo": "pandas-dev/pandas", "repo_url": "https://github.com/pandas-dev/pandas", "license_name": "BSD 3-Clause \"New\" or \"Revised\" License", "license_spdx": "BSD-3-Clause", "pr_number": 63891, "title": "DOC: Add AI contribution guidelines and clarify other contribution policies", "body": "I have noticed an uptick of contributions that [irresponsibly use AI](https://github.com/[USER_REDACTED]ndas-dev/pandas/pull/63873) or make [meaningless changes](https://github.com/[USER_REDACTED]ndas-dev/pandas/pull/63853). I'd like to have documentation to point to when closing or banning users that engage in this behavior.\n\n* The AI policy I borrowed heavily from [Matplotlib](https://matplotlib.org/devdocs/devel/contribute.html#restrictions-on-generative-ai-usage) and [scikit-learn](https://scikit-learn.org/dev/developers/contributing.html#automated-contributions-policy)\n* I added additional language emphasizing to follow all guidelines and well as clarifying when it should be appropriate to open a pull request.\n\nWould be good to get feedback from those working with newer contributors lately cc [USER_REDACTED] [USER_REDACTED]", "author": "user_c9260bc45a59", "created_at": "2026-01-26T19:17:46+00:00", "merged_at": "2026-01-27T17:54:22+00:00", "base_branch": "main", "head_branch": "doc/contribution_ai", "additions": 45, "deletions": 10, "changed_files": 2, "files": [ { "filename": ".github/PULL_REQUEST_TEMPLATE.md", "status": "modified", "additions": 1, "deletions": 0, "changes": 1, "patch": "@@ -3,4 +3,5 @@\n - [ ] All [code checks passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit).\n - [ ] Added [type annotations](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#type-hints) to new arguments/methods/functions.\n - [ ] Added an entry in the latest `doc/source/whatsnew/vX.X.X.rst` file if fixing a bug or adding a new feature.\n+- [ ] I have reviewed and followed all the [contribution guidelines](https://pandas.pydata.org/docs/dev/development/contributing.html)\n - [ ] If I used AI to develop this pull request, I prompted it to follow `AGENTS.md`." }, { "filename": "doc/source/development/contributing.rst", "status": "modified", "additions": 44, "deletions": 10, "changes": 54, "patch": "@@ -11,7 +11,25 @@ Contributing to pandas\n \n \n All contributions, bug reports, bug fixes, documentation improvements,\n-enhancements, and ideas are welcome.\n+enhancements, and ideas are welcome. We ask that contributors follow\n+all contribution guidelines when participating with pandas.\n+\n+.. _contributing.ai:\n+\n+Automated contributions policy\n+==============================\n+\n+Contributors may use automated tools such as AI coding assistants while contributing\n+to pandas as long as it's used **responsibly**. Any use of these tools in a contribution must abide by [NAME_REDACTED]\n+following guidelines:\n+\n+* You must disclose that you used an automated tool in the contribution.\n+* You must fully review and modify the result of the automated tool.\n+* You must ensure the contribution fully abides by [NAME_REDACTED], contribution conventions in pandas.\n+\n+This policy applies to any contribution made to pandas, including submitted issues or pull requests. Maintainers\n+reserve the right to discern whether automated tooling was used and reject contributions that do not follow all of\n+the above guidelines. Maintainers may also ban users from contributing to pandas who violate these guidelines 2 or more times.\n \n .. _contributing.bug_reports:\n \n@@ -30,20 +48,27 @@ Finding an issue to contribute to\n \n If you are brand new to pandas or open-source development, we recommend searching\n the `GitHub \"issues\" tab `_\n-to find issues that interest you. Unassigned issues labeled `Docs\n-`_\n-and `good first issue\n-`_\n-are typically good for newer contributors.\n+to find issues that interest you and are available to work on. Issues available to work on are:\n \n-Once you've found an interesting issue, leave a comment with your intention\n+* Issues without the label ``[NAME_REDACTED]`` or ``[NAME_REDACTED]``. These issues require clarification and confirmation\n+ from a maintainer before proceeding.\n+* Issues that have not been started by [NAME_REDACTED] that another contributor has not commented their intent\n+ to work on the issue or already submitted an open pull request to address the issue before proceeding.\n+\n+.. tip::\n+ We recommend issues labeled `Docs\n+ `_\n+ and `good first issue\n+ `_\n+ for newer contributors.\n+\n+Once you've found an interesting, available issue, leave a comment with your intention\n to start working on it. If somebody else has\n already commented on the issue but they have shown a lack of activity in the issue\n or a pull request in the past 2-3 weeks, you may take it over.\n \n If for whatever reason you are not able to continue working with the issue, please\n-leave a comment on an issue, so other people know it's available again. You can check the list of\n-assigned issues, since people may not be working on them anymore.\n+leave a comment on an issue, so other people know it's available again.\n \n We have several :ref:`contributor community ` communication channels, which you are\n welcome to join, and ask questions as you figure things out. Among them are regular meetings for\n@@ -241,12 +266,21 @@ and merged into the project to appear in the next release. To submit a pull requ\n * TYP: Type annotations\n * CLN: Code cleanup\n \n-#. Write a description of your changes in the ``[NAME_REDACTED]`` tab\n+#. Complete the checklist template in the body of the pull request and write an additional description below the checklist if necessary.\n #. Click ``[NAME_REDACTED]``.\n \n This request then goes to the repository maintainers, and they will review\n the code.\n \n+.. note::\n+ A pull request should be associated with an open Github issue except if the change is trivial such as fixing a typo.\n+ Pull requests that do not abide by [NAME_REDACTED] guidelines may be closed by a maintainer. Contributors\n+ who have shown continued, quality pull requests may be exempt from following all guidelines strictly.\n+\n+.. warning::\n+ pandas will not accept low quality pull requests that do not meaningfully contribute to the project. Maintainers reserve\n+ their right to close these pull requests and ban users who repeatedly submit low quality pull requests.\n+\n .. _contributing.update-pr:\n \n Updating your pull request" } ], "reviews": [ { "id": 3708334477, "user": "user_c1cc819e14db", "state": "COMMENTED", "body": "Looks good. I am also wondering if we should more actively discourage low-quality PRs by [NAME_REDACTED] thinking of ones that are no where near what is considered acceptable (e.g. [this](https://github.com/[USER_REDACTED]ndas-dev/pandas/pull/63880)). If so, should we put something in the template to this effect?", "submitted_at": "2026-01-26T22:39:07+00:00" }, { "id": 3708465115, "user": "user_c9260bc45a59", "state": "COMMENTED", "body": null, "submitted_at": "2026-01-26T23:19:17+00:00" }, { "id": 3708600592, "user": "user_c1cc819e14db", "state": "APPROVED", "body": "lgtm", "submitted_at": "2026-01-27T00:20:32+00:00" }, { "id": 3714562283, "user": "user_41780905781f", "state": "COMMENTED", "body": "Looks good, thanks! Some ideas for how to evolve it, not deal-breakers.", "submitted_at": "2026-01-28T04:55:45+00:00" }, { "id": 3714580179, "user": "user_41780905781f", "state": "COMMENTED", "body": null, "submitted_at": "2026-01-28T04:56:02+00:00" }, { "id": 3719206708, "user": "user_c9260bc45a59", "state": "COMMENTED", "body": null, "submitted_at": "2026-01-28T21:19:08+00:00" }, { "id": 3719258097, "user": "user_c1cc819e14db", "state": "COMMENTED", "body": null, "submitted_at": "2026-01-28T21:29:41+00:00" }, { "id": 3747872754, "user": "user_c1cc819e14db", "state": "COMMENTED", "body": null, "submitted_at": "2026-02-03T22:15:51+00:00" }, { "id": 3754609523, "user": "user_4e1e9bb913e6", "state": "COMMENTED", "body": null, "submitted_at": "2026-02-05T05:01:18+00:00" } ], "review_comments": [ { "id": 2729528921, "user": "user_c1cc819e14db", "body": "As long as there is a general understanding that valuable contributions put forth by [NAME_REDACTED] a history of contributing to pandas need not abide, I'm good with this.", "path": "doc/source/development/contributing.rst", "line": 276, "side": "RIGHT", "created_at": "2026-01-26T22:35:27+00:00" }, { "id": 2729642025, "user": "user_c9260bc45a59", "body": "Yeah that's a good point. Added something to this effect in 24262e9", "path": "doc/source/development/contributing.rst", "line": 276, "side": "RIGHT", "created_at": "2026-01-26T23:19:17+00:00" }, { "id": 2734836855, "user": "user_41780905781f", "body": "Hmm. Is this intent here to block low-quality contributions, or something else? Hypothetically, if someone dropped a pull request with a performance improvement, would we close it and ask for an issue first? In the spirit of \"demos not memos,\" wondering if we can achieve the aim without adding too much friction. For example, could say:\n\n- \"We prefer a GitHub issue first\"\n- \"For any API changes, please open a GitHub issue first.\"\n\nDoes that make sense? Not a huge deal, I imagine most significant high-quality contributions have an associated issue anyway.", "path": "doc/source/development/contributing.rst", "line": 276, "side": "RIGHT", "created_at": "2026-01-28T04:46:13+00:00" }, { "id": 2734854361, "user": "user_41780905781f", "body": "I've been refining the [[NAME_REDACTED] policy](https://computing-in-context.afeld.me/#academic-integrity) I use for my courses, and the current stance is that generative AI is treated like any other source: usage is fine, copying is plagiarism. The corollary here is that we could generalize (at least parts of) this policy to essentially say \"if you try and contribute junk twice or more, you'll be banned,\" regardless of whether it comes from generative AI or not.", "path": "doc/source/development/contributing.rst", "line": 32, "side": "RIGHT", "created_at": "2026-01-28T04:56:03+00:00" }, { "id": 2738653641, "user": "user_c9260bc45a59", "body": "> Is this intent here to block low-quality contributions, or something else? \n\nPrimarily yes.\n\n> Hypothetically, if someone dropped a pull request with a performance improvement, would we close it and ask for an issue first?\n\nIf there wasn't enough context, I would personally be inclined too, especially from new/first time contributors. But from a familiar contributor, I agree I wouldn't want to introduce additional friction (that's what the last sentence is trying to convey).\n\nI'm open to your rephrasing if you'd like to open a follow up PR", "path": "doc/source/development/contributing.rst", "line": 276, "side": "RIGHT", "created_at": "2026-01-28T21:19:08+00:00" }, { "id": 2738694605, "user": "user_c1cc819e14db", "body": "I do think we should generally discourage new contributors from opening up PRs without issues, and will ignore this part of the doc for anything that appears to be of value. So I'm good with this as-is.", "path": "doc/source/development/contributing.rst", "line": 276, "side": "RIGHT", "created_at": "2026-01-28T21:29:41+00:00" }, { "id": 2761226146, "user": "user_c1cc819e14db", "body": "Another interesting case popped up here: https://github.com/[USER_REDACTED]ndas-dev/pandas/issues/64002\n\nI would generally say \"if you believe it cleans the code or increases performance and it's a small change, just go for it without an issue\". I'm okay with still going with the above guidance (always make an issue), but it could become problematic if we start getting a lot of issues for small refactors such as these.", "path": "doc/source/development/contributing.rst", "line": 276, "side": "RIGHT", "created_at": "2026-02-03T22:15:51+00:00" }, { "id": 2767156093, "user": "user_4e1e9bb913e6", "body": "[USER_REDACTED] [USER_REDACTED] [USER_REDACTED] One practical concern for me is that if I open an issue first for a small fix I already have in mind, there’s a good chance someone else will submit the PR before I do. That’s a bit discouraging when the fix is already clear and ready.", "path": "doc/source/development/contributing.rst", "line": 276, "side": "RIGHT", "created_at": "2026-02-05T05:01:18+00:00" } ], "meta": { "languages": [ "md", "rst" ], "touches_tests": false, "review_state_summary": { "COMMENTED": 8, "APPROVED": 1 }, "meaningful_comment_count": 8, "has_approval": true, "has_changes_requested": false, "total_review_comments": 8 } } { "_id": "f78874bd2741b65f", "_schema_version": "1.0", "_cleaned_at": "2026-02-12T07:46:51.797934+00:00", "repo": "pandas-dev/pandas", "repo_url": "https://github.com/pandas-dev/pandas", "license_name": "BSD 3-Clause \"New\" or \"Revised\" License", "license_spdx": "BSD-3-Clause", "pr_number": 63890, "title": "ENH: Make print_thing respect display.precision for float sequence", "body": "Made the change as proposed in https://github.com/[USER_REDACTED]ndas-dev/pandas/issues/60503#issuecomment-2526104263.\n\n- [x] closes #60503 (Replace xxxx with the GitHub issue number)\n- [x] [Tests added and passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#writing-tests) if fixing a bug or adding a new feature\n- [x] All [code checks passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit).\n- [ ] Added [type annotations](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#type-hints) to new arguments/methods/functions.\n- [x] Added an entry in the latest `doc/source/whatsnew/vX.X.X.rst` file if fixing a bug or adding a new feature.\n- [ ] If I used AI to develop this pull request, I prompted it to follow `AGENTS.md`.", "author": "user_cb26b31d4771", "created_at": "2026-01-26T18:19:25+00:00", "merged_at": "2026-02-02T02:23:51+00:00", "base_branch": "main", "head_branch": "pprint-seq-float", "additions": 19, "deletions": 4, "changed_files": 5, "files": [ { "filename": "doc/source/whatsnew/v3.1.0.rst", "status": "modified", "additions": 1, "deletions": 1, "changes": 2, "patch": "@@ -28,7 +28,7 @@ enhancement2\n \n Other enhancements\n ^^^^^^^^^^^^^^^^^^\n--\n+- Display formatting for float sequences in DataFrame cells now respects the ``display.precision`` option (:issue:`60503`).\n -\n \n .. ---------------------------------------------------------------------------" }, { "filename": "pandas/io/formats/printing.py", "status": "modified", "additions": 11, "deletions": 1, "changes": 12, "patch": "@@ -21,7 +21,11 @@\n \n from pandas._config import get_option\n \n-from pandas.core.dtypes.inference import is_sequence\n+from pandas.core.dtypes.inference import (\n+ is_float,\n+ is_sequence,\n+)\n+from pandas.core.dtypes.missing import notna\n \n from pandas.io.formats.console import get_console_size\n \n@@ -129,6 +133,12 @@ def _pprint_seq(\n if (max_items is not None) and (i >= max_items):\n max_items_reached = True\n break\n+ if is_float(item) and notna(item):\n+ # GH#60503\n+ from pandas.io.formats.format import _trim_zeros_single_float\n+\n+ precision = get_option(\"display.precision\")\n+ item = _trim_zeros_single_float(f\"{item:.{precision}f}\")\n r.append(pprint_thing(item, _nest_lvl + 1, max_seq_items=max_seq_items, **kwds))\n body = \", \".join(r)" }, { "filename": "pandas/tests/io/formats/test_printing.py", "status": "modified", "additions": 4, "deletions": 0, "changes": 4, "patch": "@@ -85,6 +85,10 @@ def test_repr_mapping(self):\n def test_repr_frozenset(self):\n assert printing.pprint_thing(frozenset([1, 2])) == \"frozenset({1, 2})\"\n \n+ def test_repr_seq_float_precision(self):\n+ with cf.option_context(\"display.precision\", 3):\n+ assert printing.pprint_thing([3.14159265, 3.14159265]) == \"[3.142, 3.142]\"\n+\n \n class TestFormatBase:\n def test_adjoin(self):" }, { "filename": "pandas/tests/util/test_assert_extension_array_equal.py", "status": "modified", "additions": 2, "deletions": 2, "changes": 4, "patch": "@@ -27,8 +27,8 @@ def test_assert_extension_array_equal_not_exact(kwargs):\n ExtensionArray are different\n \n ExtensionArray values are different \\\\(50\\\\.0 %\\\\)\n-\\\\[left\\\\]: \\\\[-0\\\\.17387645482.*, 0\\\\.341414801642.*\\\\]\n-\\\\[right\\\\]: \\\\[-0\\\\.17387645482.*, 0\\\\.341414801642.*\\\\]\"\"\"\n+\\\\[left\\\\]: \\\\[-0\\\\.173876.*, 0\\\\.341415.*\\\\]\n+\\\\[right\\\\]: \\\\[-0\\\\.173876.*, 0\\\\.341415.*\\\\]\"\"\"\n \n with pytest.raises(AssertionError, match=msg):\n tm.assert_extension_array_equal(arr1, arr2, **kwargs)" }, { "filename": "scripts/validate_unwanted_patterns.py", "status": "modified", "additions": 1, "deletions": 0, "changes": 1, "patch": "@@ -61,6 +61,7 @@\n \"_DatetimeTZBlock\",\n \"_check_pyarrow_available\",\n \"_parser\", # https://github.com/[USER_REDACTED]ndas-dev/pandas/issues/60833\n+ \"_trim_zeros_single_float\",\n }" } ], "reviews": [ { "id": 3708605236, "user": "user_c1cc819e14db", "state": "COMMENTED", "body": "Thanks for the PR!", "submitted_at": "2026-01-27T00:23:20+00:00" }, { "id": 3711707868, "user": "user_cb26b31d4771", "state": "COMMENTED", "body": null, "submitted_at": "2026-01-27T14:58:01+00:00" }, { "id": 3713699670, "user": "user_c1cc819e14db", "state": "COMMENTED", "body": null, "submitted_at": "2026-01-27T22:14:28+00:00" }, { "id": 3715167991, "user": "user_cb26b31d4771", "state": "COMMENTED", "body": null, "submitted_at": "2026-01-28T08:10:39+00:00" }, { "id": 3730317321, "user": "user_c1cc819e14db", "state": "COMMENTED", "body": null, "submitted_at": "2026-01-30T20:36:27+00:00" }, { "id": 3730363831, "user": "user_cb26b31d4771", "state": "COMMENTED", "body": null, "submitted_at": "2026-01-30T20:51:48+00:00" }, { "id": 3733022792, "user": "user_c1cc819e14db", "state": "CHANGES_REQUESTED", "body": "I think this looks good. Just need a note in the whatsnew for 3.1.0 under `Other enhancements`.", "submitted_at": "2026-01-31T16:51:19+00:00" }, { "id": 3737031158, "user": "user_c1cc819e14db", "state": "APPROVED", "body": "lgtm", "submitted_at": "2026-02-02T02:23:36+00:00" } ], "review_comments": [ { "id": 2729772346, "user": "user_c1cc819e14db", "body": "Why is this necessary?", "path": "pandas/io/formats/printing.py", "line": null, "side": "RIGHT", "created_at": "2026-01-27T00:23:10+00:00" }, { "id": 2732431986, "user": "user_cb26b31d4771", "body": "Without trimming trailing zeros, many tests in `pandas/tests/util` fail because the generated assertion messages no longer match, such as `tm.assert_numpy_array_equal(np.array([np.nan, 2, 3]), np.array([1, np.nan, 3]))`. `_pprint_seq` relies on `pprint_thing`, which is used by [NAME_REDACTED] a better design would be to apply `display.precision` in other display layers, and keep `_pprint_seq` precision agnostic for assertion output?", "path": "pandas/io/formats/printing.py", "line": null, "side": "RIGHT", "created_at": "2026-01-27T14:58:01+00:00" }, { "id": 2734036048, "user": "user_c1cc819e14db", "body": "Ah, I see - `{n}f` will pad with zeros. Also this function was duplicated from `format.py`. Just import the function, don't make another one.", "path": "pandas/io/formats/printing.py", "line": null, "side": "RIGHT", "created_at": "2026-01-27T22:14:28+00:00" }, { "id": 2735367298, "user": "user_cb26b31d4771", "body": "I've encountered circular `ImportError`, and it triggered `unwanted-patterns-private-import-across-module` from pre-commit.\n\nI implemented the logic locally.", "path": "pandas/io/formats/printing.py", "line": null, "side": "RIGHT", "created_at": "2026-01-28T08:10:39+00:00" }, { "id": 2747907899, "user": "user_c1cc819e14db", "body": "Don't duplicate logic. Instead, add it to the `PRIVATE_IMPORTS_TO_IGNORE` list in `scripts/validate_unwanted_patterns.py` and import it locally (in the function where it is used).", "path": "pandas/io/formats/printing.py", "line": null, "side": "RIGHT", "created_at": "2026-01-30T20:36:27+00:00" }, { "id": 2747946383, "user": "user_cb26b31d4771", "body": "Thanks for pointing out the `PRIVATE_IMPORTS_TO_IGNORE` option. I wasn’t aware of that.", "path": "pandas/io/formats/printing.py", "line": null, "side": "RIGHT", "created_at": "2026-01-30T20:51:48+00:00" } ], "meta": { "languages": [ "py", "rst" ], "touches_tests": true, "review_state_summary": { "COMMENTED": 6, "CHANGES_REQUESTED": 1, "APPROVED": 1 }, "meaningful_comment_count": 6, "has_approval": true, "has_changes_requested": true, "total_review_comments": 6 } } { "_id": "0da2f920943ff1b8", "_schema_version": "1.0", "_cleaned_at": "2026-02-12T07:46:51.797934+00:00", "repo": "pandas-dev/pandas", "repo_url": "https://github.com/pandas-dev/pandas", "license_name": "BSD 3-Clause \"New\" or \"Revised\" License", "license_spdx": "BSD-3-Clause", "pr_number": 63878, "title": "DOC: Fix PR02 for pandas.tseries.offsets.CBMonthBegin", "body": "- [ ] related to #60365\n\nFixes\n\n```\npandas.tseries.offsets.CBMonthBegin PR02\npandas.tseries.offsets.CBMonthEnd PR02\npandas.tseries.offsets.CustomBusinessMonthBegin PR02\npandas.tseries.offsets.CustomBusinessMonthEnd PR02\n\n```\n\nFixed the PR02 error for CBMonthBegin and CBMonthEnd by adding `__signature__ `attributes to these Cython classes.\n\nChanges Made\nFile: `pandas/_libs/tslibs/offsets.pyx`\n- Added explicit `__signature__` attributes for `CBMonthBegin` and `CBMonthEnd` classes \n- This allows Python's `inspect.signature()` to properly introspect these Cython classes\n- The signatures match the `__init__` method parameters defined in the parent `_CustomBusinessMonth` class\n\n[NAME_REDACTED] Works\n- Root cause: Cython cdef class definitions don't expose their __init__ signatures to Python's inspection tools\n- Solution: Manually set the __signature__ attribute using inspect.Parameter and inspect.Signature\n- Result: The numpydoc validator can now verify that docstring parameters match the actual function signature", "author": "user_8905a7db72f0", "created_at": "2026-01-26T04:41:33+00:00", "merged_at": "2026-01-28T18:14:40+00:00", "base_branch": "main", "head_branch": "pandas.tseries.offsets.CBMonthBegin", "additions": 66, "deletions": 10, "changed_files": 3, "files": [ { "filename": "ci/code_checks.sh", "status": "modified", "additions": 0, "deletions": 4, "changes": 4, "patch": "@@ -73,13 +73,9 @@ if [[ -z \"$CHECK\" || \"$CHECK\" == \"docstrings\" ]]; then\n -i \"pandas.tseries.offsets.BDay PR02,SA01\" \\\n -i \"pandas.tseries.offsets.BusinessDay PR02,SA01\" \\\n -i \"pandas.tseries.offsets.BusinessHour PR02,SA01\" \\\n- -i \"pandas.tseries.offsets.CBMonthBegin PR02\" \\\n- -i \"pandas.tseries.offsets.CBMonthEnd PR02\" \\\n -i \"pandas.tseries.offsets.CDay PR02,SA01\" \\\n -i \"pandas.tseries.offsets.CustomBusinessDay PR02,SA01\" \\\n -i \"pandas.tseries.offsets.CustomBusinessHour PR02,SA01\" \\\n- -i \"pandas.tseries.offsets.CustomBusinessMonthBegin PR02\" \\\n- -i \"pandas.tseries.offsets.CustomBusinessMonthEnd PR02\" \\\n -i \"pandas.tseries.offsets.Easter.is_on_offset GL08\" \\\n -i \"pandas.tseries.offsets.FY5253Quarter.is_on_offset GL08\" \\\n -i \"pandas.tseries.offsets.FY5253Quarter.rule_code GL08\" \\" }, { "filename": "pandas/_libs/tslibs/offsets.pyi", "status": "modified", "additions": 22, "deletions": 2, "changes": 24, "patch": "@@ -284,8 +284,28 @@ class CustomBusinessHour(BusinessHour):\n offset: timedelta = ...,\n ) -> None: ...\n \n-class CustomBusinessMonthEnd(_CustomBusinessMonth): ...\n-class CustomBusinessMonthBegin(_CustomBusinessMonth): ...\n+class CustomBusinessMonthEnd(_CustomBusinessMonth):\n+ def __init__(\n+ self,\n+ n: int = ...,\n+ normalize: bool = ...,\n+ weekmask: str = ...,\n+ holidays: list | None = ...,\n+ calendar: OffsetCalendar | None = ...,\n+ offset: timedelta = ...,\n+ ) -> None: ...\n+\n+class CustomBusinessMonthBegin(_CustomBusinessMonth):\n+ def __init__(\n+ self,\n+ n: int = ...,\n+ normalize: bool = ...,\n+ weekmask: str = ...,\n+ holidays: list | None = ...,\n+ calendar: OffsetCalendar | None = ...,\n+ offset: timedelta = ...,\n+ ) -> None: ...\n+\n class OffsetMeta(type): ...\n class DateOffset(RelativeDeltaOffset, metaclass=OffsetMeta): ..." }, { "filename": "pandas/_libs/tslibs/offsets.pyx", "status": "modified", "additions": 44, "deletions": 4, "changes": 48, "patch": "@@ -6365,7 +6365,11 @@ cdef class _CustomBusinessMonth(BusinessMixin):\n return result\n \n \n-cdef class CustomBusinessMonthEnd(_CustomBusinessMonth):\n+cdef class _CustomBusinessMonthEnd(_CustomBusinessMonth):\n+ _prefix = \"CBME\"\n+\n+\n+class CustomBusinessMonthEnd(_CustomBusinessMonthEnd):\n \"\"\"\n DateOffset subclass representing custom business month(s).\n \n@@ -6423,10 +6427,30 @@ cdef class CustomBusinessMonthEnd(_CustomBusinessMonth):\n dtype='datetime64[ns]', freq='CBME')\n \"\"\"\n \n- _prefix = \"CBME\"\n+ def __init__(\n+ self,\n+ n=1,\n+ normalize=False,\n+ weekmask=\"[NAME_REDACTED] [NAME_REDACTED]\",\n+ holidays=None,\n+ calendar=None,\n+ offset=timedelta(0),\n+ ):\n+ super().__init__(\n+ n=n,\n+ normalize=normalize,\n+ weekmask=weekmask,\n+ holidays=holidays,\n+ calendar=calendar,\n+ offset=offset,\n+ )\n \n \n-cdef class CustomBusinessMonthBegin(_CustomBusinessMonth):\n+cdef class _CustomBusinessMonthBegin(_CustomBusinessMonth):\n+ _prefix = \"CBMS\"\n+\n+\n+class CustomBusinessMonthBegin(_CustomBusinessMonthBegin):\n \"\"\"\n DateOffset subclass representing custom business month(s).\n \n@@ -6484,7 +6508,23 @@ cdef class CustomBusinessMonthBegin(_CustomBusinessMonth):\n dtype='datetime64[ns]', freq='CBMS')\n \"\"\"\n \n- _prefix = \"CBMS\"\n+ def __init__(\n+ self,\n+ n=1,\n+ normalize=False,\n+ weekmask=\"[NAME_REDACTED] [NAME_REDACTED]\",\n+ holidays=None,\n+ calendar=None,\n+ offset=timedelta(0),\n+ ):\n+ super().__init__(\n+ n=n,\n+ normalize=normalize,\n+ weekmask=weekmask,\n+ holidays=holidays,\n+ calendar=calendar,\n+ offset=offset,\n+ )\n \n \n BDay = BusinessDay" } ], "reviews": [ { "id": 3713069897, "user": "user_c9260bc45a59", "state": "CHANGES_REQUESTED", "body": null, "submitted_at": "2026-01-27T19:29:14+00:00" }, { "id": 3713203140, "user": "user_8905a7db72f0", "state": "COMMENTED", "body": null, "submitted_at": "2026-01-27T20:00:13+00:00" }, { "id": 3713257568, "user": "user_8905a7db72f0", "state": "COMMENTED", "body": null, "submitted_at": "2026-01-27T20:13:01+00:00" }, { "id": 3713568622, "user": "user_c9260bc45a59", "state": "COMMENTED", "body": null, "submitted_at": "2026-01-27T21:34:23+00:00" }, { "id": 3714410734, "user": "user_8905a7db72f0", "state": "COMMENTED", "body": null, "submitted_at": "2026-01-28T03:22:52+00:00" }, { "id": 3714418052, "user": "user_8905a7db72f0", "state": "COMMENTED", "body": null, "submitted_at": "2026-01-28T03:27:54+00:00" }, { "id": 3718253066, "user": "user_c9260bc45a59", "state": "APPROVED", "body": null, "submitted_at": "2026-01-28T18:13:53+00:00" } ], "review_comments": [ { "id": 2733513067, "user": "user_c9260bc45a59", "body": "Instead, could you just define a regular Python `class` that subclasses these cdef classes to give it a docstring? This works but IMO is a little more indirect", "path": "pandas/_libs/tslibs/offsets.pyx", "line": null, "side": "RIGHT", "created_at": "2026-01-27T19:29:09+00:00" }, { "id": 2733615872, "user": "user_8905a7db72f0", "body": "yeah. let me try to solve it.", "path": "pandas/_libs/tslibs/offsets.pyx", "line": null, "side": "RIGHT", "created_at": "2026-01-27T20:00:13+00:00" }, { "id": 2733657428, "user": "user_8905a7db72f0", "body": "So now the Cython cdef classes with Python subclasses (`CustomBusinessMonthEnd`, `CustomBusinessMonthBegin`) have their explicit __init__ signatures. The internal cdef classes are renamed to `_CustomBusinessMonthEnd` and `_CustomBusinessMonthBegin`, and the .pyi stubs are updated with the new __init__ signatures.", "path": "pandas/_libs/tslibs/offsets.pyx", "line": null, "side": "RIGHT", "created_at": "2026-01-27T20:13:01+00:00" }, { "id": 2733917203, "user": "user_c9260bc45a59", "body": "Do we actually need to fully repeat `__init__` of `_CustomBusinessMonthEnd`? The object should just pick up the base class' implementation", "path": "pandas/_libs/tslibs/offsets.pyx", "line": 6446, "side": "RIGHT", "created_at": "2026-01-27T21:34:23+00:00" }, { "id": 2734691197, "user": "user_8905a7db72f0", "body": "Yes, it picks up the base class implementation but the explicit __init__ is still required. Without it, PR02 returns because inspect.signature() cannot introspect methods inherited from cdef classes. the init exists purely to provide an introspectable Python-level signature for the docstring validation tooling.", "path": "pandas/_libs/tslibs/offsets.pyx", "line": 6446, "side": "RIGHT", "created_at": "2026-01-28T03:22:51+00:00" }, { "id": 2734699091, "user": "user_8905a7db72f0", "body": "Did some research. Looks like its a Cython limitation. Cython cdef classes are C extension types - their methods are compiled to C and don't carry the Python-level metadata (__code__, __annotations__, __defaults__, etc.) that inspect.signature() relies on for introspection.", "path": "pandas/_libs/tslibs/offsets.pyx", "line": 6446, "side": "RIGHT", "created_at": "2026-01-28T03:27:54+00:00" } ], "meta": { "languages": [ "pyi", "pyx", "sh" ], "touches_tests": false, "review_state_summary": { "CHANGES_REQUESTED": 1, "COMMENTED": 5, "APPROVED": 1 }, "meaningful_comment_count": 6, "has_approval": true, "has_changes_requested": true, "total_review_comments": 6 } } { "_id": "d0920326b29fe2b7", "_schema_version": "1.0", "_cleaned_at": "2026-02-12T07:46:51.797934+00:00", "repo": "pandas-dev/pandas", "repo_url": "https://github.com/pandas-dev/pandas", "license_name": "BSD 3-Clause \"New\" or \"Revised\" License", "license_spdx": "BSD-3-Clause", "pr_number": 63872, "title": "BUG: Correct length_of_indexer for range objects", "body": "`length_of_indexer` computed the length of `range` objects using a manual arithmetic formula, which produced incorrect results for valid ranges.\n\nThis PR replaces that calculation with `len(indexer)` and adds a regression test to ensure correct behavior.", "author": "user_4e1e9bb913e6", "created_at": "2026-01-25T18:56:34+00:00", "merged_at": "2026-01-28T22:36:29+00:00", "base_branch": "main", "head_branch": "patch-7", "additions": 26, "deletions": 1, "changed_files": 2, "files": [ { "filename": "pandas/core/indexers/utils.py", "status": "modified", "additions": 12, "deletions": 1, "changes": 13, "patch": "@@ -325,7 +325,18 @@ def length_of_indexer(indexer, target=None) -> int:\n return indexer.sum()\n return len(indexer)\n elif isinstance(indexer, range):\n- return (indexer.stop - indexer.start) // indexer.step\n+ try:\n+ return len(indexer)\n+ except OverflowError:\n+ step = indexer.step\n+ if step > 0:\n+ low, high = indexer.start, indexer.stop\n+ else:\n+ low, high = indexer.stop, indexer.start\n+ step = -step\n+ if low >= high:\n+ return 0\n+ return (high - low - 1) // step + 1\n elif not is_list_like_indexer(indexer):\n return 1\n raise AssertionError(\"cannot find the length of the indexer\")" }, { "filename": "pandas/tests/indexing/test_indexers.py", "status": "modified", "additions": 14, "deletions": 0, "changes": 14, "patch": "@@ -16,6 +16,20 @@ def test_length_of_indexer():\n assert result == 1\n \n \n+[USER_REDACTED].mark.parametrize(\n+ \"start, stop, step, expected\",\n+ [\n+ (10, 0, -3, 4),\n+ (0, 1, 5, 1),\n+ ],\n+)\n+def test_length_of_indexer_range_overflow(start, stop, step, expected):\n+ # https://github.com/[USER_REDACTED]ndas-dev/pandas/pull/63872\n+ indexer = range(start, stop, step)\n+ result = length_of_indexer(indexer)\n+ assert result == expected\n+\n+\n def test_is_scalar_indexer():\n indexer = (0, 1)\n assert is_scalar_indexer(indexer, 2)" } ], "reviews": [ { "id": 3709082272, "user": "user_c1cc819e14db", "state": "CHANGES_REQUESTED", "body": "Good find!", "submitted_at": "2026-01-27T04:41:19+00:00" }, { "id": 3713762486, "user": "user_c1cc819e14db", "state": "CHANGES_REQUESTED", "body": "I don't know if this really has any user facing implications. If it's not known, I think it's okay to not have a whatsnew entry for this.", "submitted_at": "2026-01-27T22:41:00+00:00" }, { "id": 3719499693, "user": "user_c1cc819e14db", "state": "APPROVED", "body": "lgtm", "submitted_at": "2026-01-28T22:35:51+00:00" } ], "review_comments": [ { "id": 2730218206, "user": "user_c1cc819e14db", "body": "As you mentioned, this formula can be incorrect. I believe the correct fallback is:\n\n```python\n if indexer.step > 0:\n low, high = indexer.start, indexer.stop\n step = indexer.step\n else:\n high, low = indexer.start, indexer.stop\n step = -indexer.step\n\n if low >= high:\n length = 0\n else:\n length = (high - low - 1) // step + 1\n```\n\nCan you add tests that hit this fallback in both positive and negative step cases.", "path": "pandas/core/indexers/utils.py", "line": null, "side": "RIGHT", "created_at": "2026-01-27T04:39:37+00:00" }, { "id": 2734096813, "user": "user_c1cc819e14db", "body": "Instead of duplicating the formula, can you hardcode the correct `expected` as part of the parameters.", "path": "pandas/tests/indexing/test_indexers.py", "line": null, "side": "RIGHT", "created_at": "2026-01-27T22:37:31+00:00" }, { "id": 2734103730, "user": "user_c1cc819e14db", "body": "Can you add a comment referring to this PR.\n\n```suggestion\n # https://github.com/[USER_REDACTED]ndas-dev/pandas/pull/63872\n indexer = range(start, stop, step)\n```", "path": "pandas/tests/indexing/test_indexers.py", "line": 28, "side": "RIGHT", "created_at": "2026-01-27T22:40:28+00:00" } ], "meta": { "languages": [ "py" ], "touches_tests": true, "review_state_summary": { "CHANGES_REQUESTED": 2, "APPROVED": 1 }, "meaningful_comment_count": 3, "has_approval": true, "has_changes_requested": true, "total_review_comments": 3 } } { "_id": "1a4d2861bc78144c", "_schema_version": "1.0", "_cleaned_at": "2026-02-12T07:46:51.797934+00:00", "repo": "pandas-dev/pandas", "repo_url": "https://github.com/pandas-dev/pandas", "license_name": "BSD 3-Clause \"New\" or \"Revised\" License", "license_spdx": "BSD-3-Clause", "pr_number": 63870, "title": "CI: Use pytest-cython 0.4.0rc1 with editable install for doctests", "body": "- [ ] closes #xxxx (Replace xxxx with the GitHub issue number)\n- [ ] [Tests added and passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#writing-tests) if fixing a bug or adding a new feature\n- [ ] All [code checks passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit).\n- [ ] Added [type annotations](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#type-hints) to new arguments/methods/functions.\n- [ ] Added an entry in the latest `doc/source/whatsnew/vX.X.X.rst` file if fixing a bug or adding a new feature.\n- [ ] If I used AI to develop this pull request, I prompted it to follow `AGENTS.md`.\n\nPreviously `doctest-cython` was not compatible with editable installs, was not running doctests in `_libs/`, and used the deprecated `pkg_resources`. I'm fixing these issues in 0.4.0. I will be reaching out to other dependent projects to see if I can have them test the new behavior, it will likely be several weeks until 0.4.0. As long as there are no objections, I'd like to get this merged with the pin on `0.4.0rc1`.", "author": "user_c1cc819e14db", "created_at": "2026-01-25T17:56:01+00:00", "merged_at": "2026-02-09T22:04:26+00:00", "base_branch": "main", "head_branch": "ci_editable_install_doctests", "additions": 69, "deletions": 71, "changed_files": 10, "files": [ { "filename": ".github/workflows/code-checks.yml", "status": "modified", "additions": 0, "deletions": 14, "changes": 14, "patch": "@@ -43,15 +43,8 @@ jobs:\n - name: [NAME_REDACTED]\n id: build\n uses: ./.github/actions/build_pandas\n- with:\n- editable: false\n \n # The following checks are independent of each other and should still be run if one fails\n-\n- # TODO: The doctests have to be run first right now, since the Cython doctests only work\n- # with pandas installed in non-editable mode\n- # This can be removed once pytest-cython doesn't require C extensions to be installed inplace\n-\n - name: Extra installs\n # https://pytest-qt.readthedocs.io/en/latest/troubleshooting.html#github-actions-azure-pipelines-travis-ci-and-gitlab-ci-cd\n run: sudo apt-get update && sudo apt-get install -y libegl1 libopengl0\n@@ -60,13 +53,6 @@ jobs:\n run: cd ci && ./code_checks.sh doctests\n if: ${{ steps.build.outcome == 'success' && always() }}\n \n- - name: Install pandas in editable mode\n- id: build-editable\n- if: ${{ steps.build.outcome == 'success' && always() }}\n- uses: ./.github/actions/build_pandas\n- with:\n- editable: true\n-\n - name: Check for no warnings when building single-page docs\n run: ci/code_checks.sh single-docs\n if: ${{ steps.build.outcome == 'success' && always() }}" }, { "filename": "environment.yml", "status": "modified", "additions": 1, "deletions": 1, "changes": 2, "patch": "@@ -88,7 +88,6 @@ dependencies:\n - numpydoc\n # temporary installed with pip with custom patch until released\n # - pydata-sphinx-theme=0.16\n- - pytest-cython # doctest\n - sphinx\n - sphinx-design\n - sphinx-copybutton\n@@ -128,3 +127,4 @@ dependencies:\n - pip:\n - tzdata>=2023.3\n - https://github.com/[USER_REDACTED]nbossche/pydata-sphinx-theme/archive/refs/heads/v0.16.1+dismissable-announcement-banner.zip\n+ - pytest-cython==0.4.0rc1 # doctest" }, { "filename": "pandas/_libs/lib.pyx", "status": "modified", "additions": 1, "deletions": 1, "changes": 2, "patch": "@@ -317,7 +317,7 @@ def item_from_zerodim(val: object) -> object:\n >>> item_from_zerodim('foobar')\n 'foobar'\n >>> item_from_zerodim(np.array(1))\n- 1\n+ np.int64(1)\n >>> item_from_zerodim(np.array([1]))\n array([1])\n \"\"\"" }, { "filename": "pandas/_libs/tslibs/nattype.pyx", "status": "modified", "additions": 5, "deletions": 5, "changes": 10, "patch": "@@ -248,7 +248,7 @@ cdef class _NaT(datetime):\n >>> ts\n Timestamp('2023-01-01 10:00:15')\n >>> ts.to_datetime64()\n- numpy.datetime64('2023-01-01T10:00:15.000000')\n+ np.datetime64('2023-01-01T10:00:15.000000')\n \"\"\"\n return np.datetime64(\"NaT\", \"ns\")\n \n@@ -281,12 +281,12 @@ cdef class _NaT(datetime):\n --------\n >>> ts = pd.Timestamp('2020-03-14T15:32:52.192548651')\n >>> ts.to_numpy()\n- numpy.datetime64('2020-03-14T15:32:52.192548651')\n+ np.datetime64('2020-03-14T15:32:52.192548651')\n \n Analogous for ``pd.NaT``:\n \n >>> pd.NaT.to_numpy()\n- numpy.datetime64('NaT')\n+ np.datetime64('NaT')\n \"\"\"\n if dtype is not None:\n # GH#44460\n@@ -821,7 +821,7 @@ class NaTType(_NaT):\n >>> ts\n Timestamp('2023-01-01 10:00:00+0100', tz='Europe/Brussels')\n >>> ts.timetz()\n- datetime.time(10, 0, tzinfo=)\n+ datetime.time(10, 0, tzinfo=zoneinfo.ZoneInfo(key='Europe/Brussels'))\n \"\"\"\n )\n toordinal = _make_error_func(\n@@ -1866,7 +1866,7 @@ default 'raise'\n >>> ts\n Timestamp('2023-01-01 00:00:00.010000')\n >>> ts.unit\n- 'ms'\n+ 'us'\n >>> ts = ts.as_unit('s')\n >>> ts\n Timestamp('2023-01-01 00:00:00')" }, { "filename": "pandas/_libs/tslibs/offsets.pyx", "status": "modified", "additions": 21, "deletions": 17, "changes": 38, "patch": "@@ -783,7 +783,7 @@ cdef class BaseOffset:\n Timestamp is not on the offset (not a month end), so it rolls backward:\n \n >>> offset.rollback(ts)\n- Timestamp('2024-12-31 00:00:00')\n+ Timestamp('2024-12-31 09:00:00')\n \n If the timestamp is already on the offset, it remains unchanged:\n \n@@ -831,7 +831,7 @@ cdef class BaseOffset:\n Timestamp is not on the offset (not a month end), so it rolls forward:\n \n >>> offset.rollforward(ts)\n- Timestamp('2025-01-31 00:00:00')\n+ Timestamp('2025-01-31 09:00:00')\n \n If the timestamp is already on the offset, it remains unchanged:\n \n@@ -980,7 +980,7 @@ cdef class BaseOffset:\n \n Examples\n --------\n- >>> pd.offsets.Week(n=1).nanos\n+ >>> pd.offsets.Week(n=1).nanos # doctest: +SKIP\n ValueError: Week: weekday=None is a non-fixed frequency\n \"\"\"\n raise ValueError(f\"{self} is a non-fixed frequency\")\n@@ -1504,7 +1504,7 @@ cdef class Day(SingleConstructorOffset):\n \n Examples\n --------\n- >>> pd.Day(5).freqstr\n+ >>> pd.offsets.Day(5).freqstr\n '5D'\n \n >>> pd.offsets.Day(1).freqstr\n@@ -2707,7 +2707,7 @@ cdef class BusinessHour(BusinessMixin):\n '2022-12-12 06:00:00', '2022-12-12 07:00:00',\n '2022-12-12 10:00:00', '2022-12-12 11:00:00',\n '2022-12-12 15:00:00', '2022-12-12 16:00:00'],\n- dtype='datetime64[ns]', freq='bh')\n+ dtype='datetime64[us]', freq='bh')\n \"\"\"\n \n _prefix = \"bh\"\n@@ -6109,7 +6109,7 @@ cdef class FY5253Quarter(FY5253Mixin):\n >>> offset = pd.offsets.FY5253Quarter(\n ... weekday=5, startingMonth=12, qtr_with_extra_week=1\n ... )\n- >>> offset.year_has_extra_week(pd.Timestamp(\"2011-04-02\"))\n+ >>> offset.year_has_extra_week(pd.Timestamp(\"2014-04-02\"))\n True\n >>> offset.year_has_extra_week(pd.Timestamp(\"2010-04-02\"))\n False\n@@ -6395,7 +6395,7 @@ cdef class CustomBusinessDay(BusinessDay):\n Index(['Mon 12 Dec 2022 00:00', 'Wed 14 Dec 2022 00:00',\n 'Fri 16 Dec 2022 00:00', 'Mon 19 Dec 2022 00:00',\n 'Wed 21 Dec 2022 00:00'],\n- dtype='object')\n+ dtype='str')\n \n Using NumPy business day calendar you can define custom holidays.\n \n@@ -6405,7 +6405,7 @@ cdef class CustomBusinessDay(BusinessDay):\n >>> pd.date_range(dt.datetime(2022, 12, 10), dt.datetime(2022, 12, 25), freq=freq)\n DatetimeIndex(['2022-12-13', '2022-12-15', '2022-12-16', '2022-12-19',\n '2022-12-20', '2022-12-21', '2022-12-22', '2022-12-23'],\n- dtype='datetime64[ns]', freq='C')\n+ dtype='datetime64[us]', freq='C')\n \n If you want to shift the result on n day you can use the parameter ``offset``.\n \n@@ -6541,10 +6541,14 @@ cdef class CustomBusinessDay(BusinessDay):\n >>> pd.offsets.CustomBusinessDay(normalize=True).is_on_offset(ts)\n True\n \"\"\"\n+ from pandas.core.dtypes.cast import maybe_unbox_numpy_scalar\n+\n if self._normalize and not _is_normalized(dt):\n return False\n day64 = _to_dt64D(dt)\n- return np.is_busday(day64, busdaycal=self._calendar)\n+ result = np.is_busday(day64, busdaycal=self._calendar)\n+ result = maybe_unbox_numpy_scalar(result)\n+ return result\n \n \n cdef class CustomBusinessHour(BusinessHour):\n@@ -6615,7 +6619,7 @@ cdef class CustomBusinessHour(BusinessHour):\n '2022-12-12 06:00:00', '2022-12-12 07:00:00',\n '2022-12-12 10:00:00', '2022-12-12 11:00:00',\n '2022-12-12 15:00:00', '2022-12-12 16:00:00'],\n- dtype='datetime64[ns]', freq='cbh')\n+ dtype='datetime64[us]', freq='cbh')\n \n Business days can be specified by ``weekmask`` parameter. To convert\n the returned datetime object to its string representation\n@@ -6631,7 +6635,7 @@ cdef class CustomBusinessHour(BusinessHour):\n 'Wed 14 Dec 2022 11:00', 'Wed 14 Dec 2022 12:00',\n 'Fri 16 Dec 2022 10:00', 'Fri 16 Dec 2022 11:00',\n 'Fri 16 Dec 2022 12:00'],\n- dtype='object')\n+ dtype='str')\n \n Using NumPy business day calendar you can define custom holidays.\n \n@@ -6644,7 +6648,7 @@ cdef class CustomBusinessHour(BusinessHour):\n '2022-12-15 11:00:00', '2022-12-15 12:00:00',\n '2022-12-16 10:00:00', '2022-12-16 11:00:00',\n '2022-12-16 12:00:00'],\n- dtype='datetime64[ns]', freq='cbh')\n+ dtype='datetime64[us]', freq='cbh')\n \"\"\"\n \n _prefix = \"cbh\"\n@@ -6811,7 +6815,7 @@ class CustomBusinessMonthEnd(_CustomBusinessMonthEnd):\n Index(['Thu 28 Jul 2022 00:00', 'Wed 31 Aug 2022 00:00',\n 'Thu 29 Sep 2022 00:00', 'Thu 27 Oct 2022 00:00',\n 'Wed 30 Nov 2022 00:00'],\n- dtype='object')\n+ dtype='str')\n \n Using NumPy business day calendar you can define custom holidays.\n \n@@ -6821,7 +6825,7 @@ class CustomBusinessMonthEnd(_CustomBusinessMonthEnd):\n >>> freq = pd.offsets.CustomBusinessMonthEnd(calendar=bdc)\n >>> pd.date_range(dt.datetime(2022, 7, 10), dt.datetime(2022, 11, 10), freq=freq)\n DatetimeIndex(['2022-07-29', '2022-08-31', '2022-09-29', '2022-10-28'],\n- dtype='datetime64[ns]', freq='CBME')\n+ dtype='datetime64[us]', freq='CBME')\n \"\"\"\n \n def __init__(\n@@ -6892,7 +6896,7 @@ class CustomBusinessMonthBegin(_CustomBusinessMonthBegin):\n Index(['Wed 03 Aug 2022 00:00', 'Thu 01 Sep 2022 00:00',\n 'Wed 05 Oct 2022 00:00', 'Wed 02 Nov 2022 00:00',\n 'Thu 01 Dec 2022 00:00'],\n- dtype='object')\n+ dtype='str')\n \n Using NumPy business day calendar you can define custom holidays.\n \n@@ -6902,7 +6906,7 @@ class CustomBusinessMonthBegin(_CustomBusinessMonthBegin):\n >>> freq = pd.offsets.CustomBusinessMonthBegin(calendar=bdc)\n >>> pd.date_range(dt.datetime(2022, 7, 10), dt.datetime(2022, 11, 10), freq=freq)\n DatetimeIndex(['2022-08-02', '2022-09-01', '2022-10-03', '2022-11-02'],\n- dtype='datetime64[ns]', freq='CBMS')\n+ dtype='datetime64[us]', freq='CBMS')\n \"\"\"\n \n def __init__(\n@@ -7180,7 +7184,7 @@ cpdef to_offset(freq, bint is_period=False):\n <2 * BusinessDays>\n \n >>> to_offset(pd.Timedelta(days=1))\n- \n+ <24 * Hours>\n \n >>> to_offset(pd.offsets.Hour())\n " }, { "filename": "pandas/_libs/tslibs/period.pyx", "status": "modified", "additions": 2, "deletions": 2, "changes": 4, "patch": "@@ -2049,13 +2049,13 @@ cdef class _Period(PeriodMixin):\n \n >>> period = pd.Period('2023-01', freq='M')\n >>> period.asfreq('h', how='start')\n- Period('2023-01-01 00:00', 'H')\n+ Period('2023-01-01 00:00', 'h')\n \n Convert a weekly period to a daily period, aligning to the last day of the week:\n \n >>> period = pd.Period('2023-08-01', freq='W')\n >>> period.asfreq('D', how='end')\n- Period('2023-08-04', 'D')\n+ Period('2023-08-06', 'D')\n \"\"\"\n freq = self._maybe_convert_freq(freq)\n how = validate_end_alias(how)" }, { "filename": "pandas/_libs/tslibs/timedeltas.pyx", "status": "modified", "additions": 10, "deletions": 9, "changes": 19, "patch": "@@ -1267,7 +1267,7 @@ cdef class _Timedelta(timedelta):\n \n Examples\n --------\n- >>> td = pd.Timedelta(1, \"d\")\n+ >>> td = pd.Timedelta(1, \"D\")\n >>> td.days\n 1\n \n@@ -1402,7 +1402,8 @@ cdef class _Timedelta(timedelta):\n Examples\n --------\n >>> td = pd.Timedelta(42, unit='us')\n- 'ns'\n+ >>> td.unit\n+ 'us'\n \"\"\"\n return npy_unit_to_abbrev(self._creso)\n \n@@ -1602,7 +1603,7 @@ cdef class _Timedelta(timedelta):\n >>> td\n Timedelta('3 days 00:00:00')\n >>> td.to_timedelta64()\n- numpy.timedelta64(259200000000000,'ns')\n+ np.timedelta64(259200000000,'us')\n \"\"\"\n cdef:\n str abbrev = npy_unit_to_abbrev(self._creso)\n@@ -1639,7 +1640,7 @@ cdef class _Timedelta(timedelta):\n >>> td\n Timedelta('3 days 00:00:00')\n >>> td.to_numpy()\n- numpy.timedelta64(259200000000000,'ns')\n+ np.timedelta64(259200000000,'us')\n \"\"\"\n if dtype is not None or copy is not False:\n raise ValueError(\n@@ -1678,7 +1679,7 @@ cdef class _Timedelta(timedelta):\n >>> td\n Timedelta('3 days 00:00:00')\n >>> td.view(int)\n- 259200000000000\n+ np.int64(259200000000)\n \"\"\"\n return np.timedelta64(self._value).view(dtype)\n \n@@ -1735,19 +1736,19 @@ cdef class _Timedelta(timedelta):\n --------\n >>> td = pd.Timedelta('1 days 2 min 3 us 42 ns')\n >>> td.asm8\n- numpy.timedelta64(86520000003042,'ns')\n+ np.timedelta64(86520000003042,'ns')\n \n >>> td = pd.Timedelta('2 min 3 s')\n >>> td.asm8\n- numpy.timedelta64(123000000000,'ns')\n+ np.timedelta64(123000000,'us')\n \n >>> td = pd.Timedelta('3 ms 5 us')\n >>> td.asm8\n- numpy.timedelta64(3005000,'ns')\n+ np.timedelta64(3005,'us')\n \n >>> td = pd.Timedelta(42, unit='ns')\n >>> td.asm8\n- numpy.timedelta64(42,'ns')\n+ np.timedelta64(42,'ns')\n \"\"\"\n return self.to_timedelta64()" }, { "filename": "pandas/_libs/tslibs/timestamps.pyx", "status": "modified", "additions": 27, "deletions": 21, "changes": 48, "patch": "@@ -372,10 +372,10 @@ cdef class _Timestamp(ABCTimestamp):\n Examples\n --------\n >>> pd.Timestamp(\"2020-01-01 12:34:56\").unit\n- 's'\n+ 'us'\n \n >>> pd.Timestamp(\"2020-01-01 12:34:56.123\").unit\n- 'ms'\n+ 'us'\n \n >>> pd.Timestamp(\"2020-01-01 12:34:56.123456\").unit\n 'us'\n@@ -1542,7 +1542,7 @@ cdef class _Timestamp(ABCTimestamp):\n >>> ts\n Timestamp('2023-01-01 00:00:00.010000')\n >>> ts.unit\n- 'ms'\n+ 'us'\n >>> ts = ts.as_unit('s')\n >>> ts\n Timestamp('2023-01-01 00:00:00')\n@@ -1575,7 +1575,7 @@ cdef class _Timestamp(ABCTimestamp):\n --------\n >>> ts = pd.Timestamp(2020, 3, 14, 15)\n >>> ts.asm8\n- numpy.datetime64('2020-03-14T15:00:00.000000')\n+ np.datetime64('2020-03-14T15:00:00.000000')\n \"\"\"\n return self.to_datetime64()\n \n@@ -1682,7 +1682,7 @@ cdef class _Timestamp(ABCTimestamp):\n >>> ts\n Timestamp('2023-01-01 10:00:15')\n >>> ts.to_datetime64()\n- numpy.datetime64('2023-01-01T10:00:15.000000')\n+ np.datetime64('2023-01-01T10:00:15.000000')\n \"\"\"\n # TODO: find a way to construct dt64 directly from _reso\n abbrev = npy_unit_to_abbrev(self._creso)\n@@ -1717,12 +1717,12 @@ cdef class _Timestamp(ABCTimestamp):\n --------\n >>> ts = pd.Timestamp('2020-03-14T15:32:52.192548651')\n >>> ts.to_numpy()\n- numpy.datetime64('2020-03-14T15:32:52.192548651')\n+ np.datetime64('2020-03-14T15:32:52.192548651')\n \n Analogous for ``pd.NaT``:\n \n >>> pd.NaT.to_numpy()\n- numpy.datetime64('NaT')\n+ np.datetime64('NaT')\n \"\"\"\n if dtype is not None or copy is not False:\n raise ValueError(\n@@ -2482,7 +2482,7 @@ class Timestamp(_Timestamp):\n >>> ts\n Timestamp('2023-01-01 10:00:00+0100', tz='Europe/Brussels')\n >>> ts.timetz()\n- datetime.time(10, 0, tzinfo=)\n+ datetime.time(10, 0, tzinfo=zoneinfo.ZoneInfo(key='Europe/Brussels'))\n \"\"\"\n return super().timetz()\n \n@@ -3507,25 +3507,31 @@ default 'raise'\n >>> ts.to_julian_date()\n 2458923.147824074\n \"\"\"\n+ from pandas.core.dtypes.cast import maybe_unbox_numpy_scalar\n+\n year = self._year\n month = self.month\n day = self.day\n if month <= 2:\n year -= 1\n month += 12\n- return (day +\n- np.trunc((153 * month - 457) / 5) +\n- 365 * year +\n- np.floor(year / 4) -\n- np.floor(year / 100) +\n- np.floor(year / 400) +\n- 1721118.5 +\n- (self.hour +\n- self.minute / 60.0 +\n- self.second / 3600.0 +\n- self.microsecond / 3600.0 / 1e+6 +\n- self._nanosecond / 3600.0 / 1e+9\n- ) / 24.0)\n+ result = (\n+ day +\n+ np.trunc((153 * month - 457) / 5) +\n+ 365 * year +\n+ np.floor(year / 4) -\n+ np.floor(year / 100) +\n+ np.floor(year / 400) +\n+ 1721118.5 +\n+ (self.hour +\n+ self.minute / 60.0 +\n+ self.second / 3600.0 +\n+ self.microsecond / 3600.0 / 1e+6 +\n+ self._nanosecond / 3600.0 / 1e+9\n+ ) / 24.0\n+ )\n+ result = maybe_unbox_numpy_scalar(result)\n+ return result\n \n def isoweekday(self):\n \"\"\"" }, { "filename": "pandas/conftest.py", "status": "modified", "additions": 1, "deletions": 0, "changes": 1, "patch": "@@ -193,6 +193,7 @@ def pytest_collection_modifyitems(items, config) -> None:\n \"DataFrameGroupBy.fillna with 'method' is deprecated\",\n ),\n (\"read_parquet\", \"Passing a BlockManager to DataFrame is deprecated\"),\n+ (\"Timestamp.utcfromtimestamp\", \"Timestamp.utcfromtimestamp is deprecated\"),\n ]\n \n if is_doctest:" }, { "filename": "requirements-dev.txt", "status": "modified", "additions": 1, "deletions": 1, "changes": 2, "patch": "@@ -61,7 +61,6 @@ gitpython\n natsort\n pickleshare\n numpydoc\n-pytest-cython\n sphinx\n sphinx-design\n sphinx-copybutton\n@@ -87,3 +86,4 @@ jupyterlite-core\n jupyterlite-pyodide-kernel\n tzdata>=2023.3\n https://github.com/[USER_REDACTED]nbossche/pydata-sphinx-theme/archive/refs/heads/v0.16.1+dismissable-announcement-banner.zip\n+pytest-cython==0.4.0rc1" } ], "reviews": [ { "id": 3774677708, "user": "user_c9260bc45a59", "state": "COMMENTED", "body": "Just a request for a cleanup otherwise LGTM", "submitted_at": "2026-02-09T18:20:10+00:00" }, { "id": 3775388070, "user": "user_c1cc819e14db", "state": "COMMENTED", "body": null, "submitted_at": "2026-02-09T21:10:59+00:00" }, { "id": 3775404830, "user": "user_c9260bc45a59", "state": "COMMENTED", "body": null, "submitted_at": "2026-02-09T21:15:25+00:00" }, { "id": 3775478981, "user": "user_c1cc819e14db", "state": "COMMENTED", "body": null, "submitted_at": "2026-02-09T21:33:11+00:00" }, { "id": 3775503749, "user": "user_c9260bc45a59", "state": "COMMENTED", "body": null, "submitted_at": "2026-02-09T21:37:14+00:00" }, { "id": 3775515562, "user": "user_c9260bc45a59", "state": "APPROVED", "body": "Feel free to set the milestone to whatever you feel appropriate and merge. There might be merge conflicts if you set it to 3.0.1 with all the docstring changes recently", "submitted_at": "2026-02-09T21:39:36+00:00" } ], "review_comments": [ { "id": 2783943121, "user": "user_c9260bc45a59", "body": "Appears this workflow was the only use of this `input` in .github/actions/build_pandas/action.yml. Could you further remove this flag then from that action?", "path": ".github/workflows/code-checks.yml", "line": 47, "side": "LEFT", "created_at": "2026-02-09T18:18:18+00:00" }, { "id": 2783945412, "user": "user_c9260bc45a59", "body": "Also just an fyi, I think ideally we want our CI to not use editable installs", "path": ".github/workflows/code-checks.yml", "line": 47, "side": "LEFT", "created_at": "2026-02-09T18:18:49+00:00" }, { "id": 2784550065, "user": "user_c1cc819e14db", "body": "Agreed on ideally not using an editable install with testing, however with code checks we want to run these on code that is not in the installed package, so I think this is necessary (and okay - we don't really care if code checks fail on end users who are not using editable installs).\n\nWith the desire to set to false (at least in testing), leave the `editable` input?", "path": ".github/workflows/code-checks.yml", "line": 47, "side": "LEFT", "created_at": "2026-02-09T21:10:58+00:00" }, { "id": 2784565777, "user": "user_c9260bc45a59", "body": "Hmm can you remind me which of these checks require that pandas is installed in editable mode and what the limitation would be not to run them in non-editable mode?", "path": ".github/workflows/code-checks.yml", "line": 47, "side": "LEFT", "created_at": "2026-02-09T21:15:25+00:00" }, { "id": 2784628932, "user": "user_c1cc819e14db", "body": "For code-checks, it's really just the doctests with pytest-cython. This uses the `pyx` files to determine docstrings to run. These files do not exist in a non-editable install.\n\nAll other linting we do on Cython files is done in pre-commit.", "path": ".github/workflows/code-checks.yml", "line": 47, "side": "LEFT", "created_at": "2026-02-09T21:33:10+00:00" }, { "id": 2784643897, "user": "user_c9260bc45a59", "body": "Ah ok gotcha!", "path": ".github/workflows/code-checks.yml", "line": 47, "side": "LEFT", "created_at": "2026-02-09T21:37:14+00:00" } ], "meta": { "languages": [ "py", "pyx", "txt", "yml" ], "touches_tests": true, "review_state_summary": { "COMMENTED": 5, "APPROVED": 1 }, "meaningful_comment_count": 6, "has_approval": true, "has_changes_requested": false, "total_review_comments": 6 } } { "_id": "a7cabecf8432da7a", "_schema_version": "1.0", "_cleaned_at": "2026-02-12T07:46:51.797934+00:00", "repo": "pandas-dev/pandas", "repo_url": "https://github.com/pandas-dev/pandas", "license_name": "BSD 3-Clause \"New\" or \"Revised\" License", "license_spdx": "BSD-3-Clause", "pr_number": 63854, "title": "ENH: [NAME_REDACTED] when not np.busdaycalendar is passed to custom subclasses", "body": "- [x] closes #60647\n\nCustom subclasses accept not np.busdaycalendar. [NAME_REDACTED].", "author": "user_29def2a2fd98", "created_at": "2026-01-24T16:39:26+00:00", "merged_at": "2026-01-28T01:13:04+00:00", "base_branch": "main", "head_branch": "bug-CustomBusinessDay-accept-not-np-busdaycalendar", "additions": 11, "deletions": 0, "changed_files": 2, "files": [ { "filename": "pandas/_libs/tslibs/offsets.pyx", "status": "modified", "additions": 5, "deletions": 0, "changes": 5, "patch": "@@ -217,6 +217,11 @@ cdef _get_calendar(weekmask, holidays, calendar):\n pass\n return calendar, holidays\n \n+ elif calendar is not None:\n+ from pandas.tseries.holiday import AbstractHolidayCalendar\n+ if not isinstance(calendar, AbstractHolidayCalendar):\n+ raise TypeError(\"Custom subclasses only accept np.busdaycalendar.\")\n+\n if holidays is None:\n holidays = []\n try:" }, { "filename": "pandas/tests/tseries/offsets/test_custom_business_day.py", "status": "modified", "additions": 6, "deletions": 0, "changes": 6, "patch": "@@ -97,3 +97,9 @@ def test_pickle_compat_0_14_1(self, datapath):\n cday0_14_1 = read_pickle(pth)\n cday = CDay(holidays=hdays)\n assert cday == cday0_14_1\n+\n+ def test_cbd_raises_if_calendar_not_busdaycalendar(self):\n+ # GH#60647\n+ msg = \"Custom subclasses only accept np.busdaycalendar.\"\n+ with pytest.raises(TypeError, match=msg):\n+ CDay(calendar=object())" } ], "reviews": [ { "id": 3712557699, "user": "user_c9260bc45a59", "state": "COMMENTED", "body": null, "submitted_at": "2026-01-27T17:34:37+00:00" }, { "id": 3712562503, "user": "user_c9260bc45a59", "state": "COMMENTED", "body": null, "submitted_at": "2026-01-27T17:36:03+00:00" }, { "id": 3714044995, "user": "user_29def2a2fd98", "state": "COMMENTED", "body": null, "submitted_at": "2026-01-28T00:19:56+00:00" }, { "id": 3714058600, "user": "user_29def2a2fd98", "state": "COMMENTED", "body": null, "submitted_at": "2026-01-28T00:27:41+00:00" }, { "id": 3714079720, "user": "user_c9260bc45a59", "state": "COMMENTED", "body": null, "submitted_at": "2026-01-28T00:36:07+00:00" }, { "id": 3714103898, "user": "user_29def2a2fd98", "state": "COMMENTED", "body": null, "submitted_at": "2026-01-28T00:47:52+00:00" }, { "id": 3714155687, "user": "user_c9260bc45a59", "state": "APPROVED", "body": null, "submitted_at": "2026-01-28T01:12:56+00:00" } ], "review_comments": [ { "id": 2733115434, "user": "user_c9260bc45a59", "body": "Nit: Could you make this an `elif` with the `if` statement above?", "path": "pandas/_libs/tslibs/offsets.pyx", "line": null, "side": "RIGHT", "created_at": "2026-01-27T17:34:37+00:00" }, { "id": 2733119799, "user": "user_c9260bc45a59", "body": "Due to the circular dependency, could we just instead locally import `AbstractHolidayCalendar` in this condition and check for it here?", "path": "pandas/_libs/tslibs/offsets.pyx", "line": null, "side": "RIGHT", "created_at": "2026-01-27T17:35:58+00:00" }, { "id": 2734340666, "user": "user_29def2a2fd98", "body": "Yes, I changed it.", "path": "pandas/_libs/tslibs/offsets.pyx", "line": null, "side": "RIGHT", "created_at": "2026-01-28T00:19:55+00:00" }, { "id": 2734355085, "user": "user_29def2a2fd98", "body": "Thanks, I did as you suggested. \nCould you explain why inserting a local import of `AbstractHolidayCalendar` in this condition and checking for an instance of it is better than checking whether the calendar has an attribute `holidays`?", "path": "pandas/_libs/tslibs/offsets.pyx", "line": null, "side": "RIGHT", "created_at": "2026-01-28T00:27:41+00:00" }, { "id": 2734370359, "user": "user_c9260bc45a59", "body": "There could be an edge case where someone passes an object that's not a `AbstractHolidayCalendar` but defines `holidays` that this object does not expect. \n\nIn my opinion is almost always better to be strict and check for the exact types than to rely on duck typing. It often leads to less surprises that way", "path": "pandas/_libs/tslibs/offsets.pyx", "line": null, "side": "RIGHT", "created_at": "2026-01-28T00:36:07+00:00" }, { "id": 2734392907, "user": "user_29def2a2fd98", "body": "Thanks for explaining.", "path": "pandas/_libs/tslibs/offsets.pyx", "line": null, "side": "RIGHT", "created_at": "2026-01-28T00:47:52+00:00" } ], "meta": { "languages": [ "py", "pyx" ], "touches_tests": true, "review_state_summary": { "COMMENTED": 6, "APPROVED": 1 }, "meaningful_comment_count": 6, "has_approval": true, "has_changes_requested": false, "total_review_comments": 6 } } { "_id": "f527a63f8eb78fd8", "_schema_version": "1.0", "_cleaned_at": "2026-02-12T07:46:51.797934+00:00", "repo": "pandas-dev/pandas", "repo_url": "https://github.com/pandas-dev/pandas", "license_name": "BSD 3-Clause \"New\" or \"Revised\" License", "license_spdx": "BSD-3-Clause", "pr_number": 63846, "title": "DEPR: Deprecate decorator Appender and Substitution", "body": "- [ ] closes #xxxx (Replace xxxx with the GitHub issue number)\n- [ ] [Tests added and passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#writing-tests) if fixing a bug or adding a new feature\n- [x] All [code checks passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit).\n- [ ] Added [type annotations](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#type-hints) to new arguments/methods/functions.\n- [ ] Added an entry in the latest `doc/source/whatsnew/vX.X.X.rst` file if fixing a bug or adding a new feature.\n- [ ] If I used AI to develop this pull request, I prompted it to follow `AGENTS.md`.", "author": "user_5b0b62fe7839", "created_at": "2026-01-24T04:26:24+00:00", "merged_at": "2026-02-02T18:17:50+00:00", "base_branch": "main", "head_branch": "del_app", "additions": 14, "deletions": 0, "changed_files": 1, "files": [ { "filename": "pandas/util/_decorators.py", "status": "modified", "additions": 14, "deletions": 0, "changes": 14, "patch": "@@ -438,6 +438,13 @@ def some_function(x):\n \"\"\"\n \n def __init__(self, *args, **kwargs) -> None:\n+ from pandas.errors import Pandas4Warning\n+\n+ warnings.warn(\n+ \"Substitution is deprecated and will be removed in a future version.\",\n+ Pandas4Warning,\n+ stacklevel=find_stack_level(),\n+ )\n if args and kwargs:\n raise AssertionError(\"Only positional or keyword args are allowed\")\n \n@@ -478,6 +485,13 @@ def my_dog(has='fleas'):\n addendum: str | None\n \n def __init__(self, addendum: str | None, join: str = \"\", indents: int = 0) -> None:\n+ from pandas.errors import Pandas4Warning\n+\n+ warnings.warn(\n+ \"Appender is deprecated and will be removed in a future version.\",\n+ Pandas4Warning,\n+ stacklevel=find_stack_level(),\n+ )\n if indents > 0:\n self.addendum = indent(addendum, indents=indents)\n else:" } ], "reviews": [ { "id": 3724742683, "user": "user_c9260bc45a59", "state": "COMMENTED", "body": null, "submitted_at": "2026-01-29T20:00:14+00:00" }, { "id": 3729510587, "user": "user_c9260bc45a59", "state": "COMMENTED", "body": null, "submitted_at": "2026-01-30T17:21:05+00:00" }, { "id": 3738382397, "user": "user_5b0b62fe7839", "state": "COMMENTED", "body": null, "submitted_at": "2026-02-02T09:55:30+00:00" }, { "id": 3741149191, "user": "user_c9260bc45a59", "state": "APPROVED", "body": null, "submitted_at": "2026-02-02T18:17:40+00:00" } ], "review_comments": [ { "id": 2743293490, "user": "user_c9260bc45a59", "body": "Instead, could you put this warning in the `Appender/Substitution.__init__`s?", "path": "pandas/util/__init__.py", "line": null, "side": "RIGHT", "created_at": "2026-01-29T20:00:14+00:00" }, { "id": 2747239871, "user": "user_c9260bc45a59", "body": "One more item. Could you use `stacklevel=find_stack_level()` (available from `pandas.errors`) in both places?\n\nAlso could you move the import to the top of the file if there's no circular reference?", "path": "pandas/util/_decorators.py", "line": null, "side": "RIGHT", "created_at": "2026-01-30T17:21:05+00:00" }, { "id": 2753495843, "user": "user_5b0b62fe7839", "body": "sure!\nimporting `Pandas4Warning` at the top of the file caused circular reference, so I moved it here", "path": "pandas/util/_decorators.py", "line": null, "side": "RIGHT", "created_at": "2026-02-02T09:55:30+00:00" } ], "meta": { "languages": [ "py" ], "touches_tests": false, "review_state_summary": { "COMMENTED": 3, "APPROVED": 1 }, "meaningful_comment_count": 3, "has_approval": true, "has_changes_requested": false, "total_review_comments": 3 } } { "_id": "37517d6323435dec", "_schema_version": "1.0", "_cleaned_at": "2026-02-12T07:46:51.797934+00:00", "repo": "pandas-dev/pandas", "repo_url": "https://github.com/pandas-dev/pandas", "license_name": "BSD 3-Clause \"New\" or \"Revised\" License", "license_spdx": "BSD-3-Clause", "pr_number": 63837, "title": "DOC: Add User Guide links to GroupBy aggregate, transform, and apply methods", "body": "## [NAME_REDACTED] PR adds cross-references from the GroupBy API documentation back to the [NAME_REDACTED], addressing #62357.\n\n## Changes\n\nAdded `:ref:` links to the [NAME_REDACTED] in the `See Also` sections of:\n\n| Method | [NAME_REDACTED] |\n|--------|-----------------|\n| `SeriesGroupBy.aggregate` | `groupby.aggregate` |\n| `DataFrameGroupBy.aggregate` | `groupby.aggregate` |\n| `transform` (via `_transform_template`) | `groupby.transform` |\n| `GroupBy.apply` | `groupby.apply` |\n\nAlso added a note in the API reference (`doc/source/reference/groupby.rst`) with links to relevant [NAME_REDACTED] sections.\n\n## [NAME_REDACTED] noted in the issue, users navigating from the [NAME_REDACTED] to API docs couldn't easily navigate back. This improves discoverability of the comprehensive [NAME_REDACTED] sections on groupby operations.\n\n## Files Changed\n\n- `pandas/core/groupby/generic.py` - Added User Guide links to aggregate docstrings\n- `pandas/core/groupby/groupby.py` - Added User Guide links to apply and transform docstrings\n- `doc/source/reference/groupby.rst` - Added User Guide references in Function application section\n\nCloses #62357", "author": "user_3e9ebe7c174f", "created_at": "2026-01-23T22:14:28+00:00", "merged_at": "2026-01-28T03:11:45+00:00", "base_branch": "main", "head_branch": "doc-add-groupby-guide-links-62357", "additions": 14, "deletions": 0, "changed_files": 2, "files": [ { "filename": "pandas/core/groupby/generic.py", "status": "modified", "additions": 12, "deletions": 0, "changes": 12, "patch": "@@ -251,6 +251,8 @@ def apply(self, func, *args, **kwargs) -> Series:\n \n Notes\n -----\n+ See :ref:`groupby.apply` in the [NAME_REDACTED] for more details and examples.\n+\n The resulting dtype will reflect the return value of the passed ``func``,\n see the examples below.\n \n@@ -382,6 +384,9 @@ def aggregate(self, func=None, *args, engine=None, engine_kwargs=None, **kwargs)\n \n Notes\n -----\n+ See :ref:`groupby.aggregate` in the [NAME_REDACTED] for more details\n+ and examples.\n+\n When using ``engine='numba'``, there will be no \"fall back\" behavior internally.\n The group data and group index will be passed as numpy arrays to the JITed\n user defined function, and no alternative execution attempts will be tried.\n@@ -711,6 +716,8 @@ def transform(self, func, *args, engine=None, engine_kwargs=None, **kwargs):\n \n Notes\n -----\n+ See :ref:`groupby.transform` in the [NAME_REDACTED] for more details and examples.\n+\n Each group is endowed the attribute 'name' in case you need to know\n which group you are working on.\n \n@@ -2180,6 +2187,9 @@ def aggregate(self, func=None, *args, engine=None, engine_kwargs=None, **kwargs)\n \n Notes\n -----\n+ See :ref:`groupby.aggregate` in the [NAME_REDACTED] for more details\n+ and examples.\n+\n When using ``engine='numba'``, there will be no \"fall back\" behavior internally.\n The group data and group index will be passed as numpy arrays to the JITed\n user defined function, and no alternative execution attempts will be tried.\n@@ -2706,6 +2716,8 @@ def transform(self, func, *args, engine=None, engine_kwargs=None, **kwargs):\n \n Notes\n -----\n+ See :ref:`groupby.transform` in the [NAME_REDACTED] for more details and examples.\n+\n Each group is endowed the attribute 'name' in case you need to know\n which group you are working on." }, { "filename": "pandas/core/groupby/groupby.py", "status": "modified", "additions": 2, "deletions": 0, "changes": 2, "patch": "@@ -1541,6 +1541,8 @@ def apply(self, func, *args, include_groups: bool = False, **kwargs) -> NDFrameT\n \n Notes\n -----\n+ See :ref:`groupby.apply` in the [NAME_REDACTED] for more details and examples.\n+\n The resulting dtype will reflect the return value of the passed ``func``,\n see the examples below." } ], "reviews": [ { "id": 3701624195, "user": "user_c1cc819e14db", "state": "CHANGES_REQUESTED", "body": "Thanks for the PR!", "submitted_at": "2026-01-24T13:47:15+00:00" }, { "id": 3702343659, "user": "user_3e9ebe7c174f", "state": "COMMENTED", "body": null, "submitted_at": "2026-01-24T18:41:50+00:00" }, { "id": 3714388133, "user": "user_c1cc819e14db", "state": "APPROVED", "body": "lgtm", "submitted_at": "2026-01-28T03:11:04+00:00" } ], "review_comments": [ { "id": 2724172080, "user": "user_c1cc819e14db", "body": "This transform template appears no longer used. Can you update the two methods `transform` in `generic.py`.", "path": "pandas/core/groupby/groupby.py", "line": null, "side": "RIGHT", "created_at": "2026-01-24T13:45:30+00:00" }, { "id": 2724173262, "user": "user_c1cc819e14db", "body": "Can you also add this line to `SeriesGroupBy.apply` in `generic.py`.", "path": "pandas/core/groupby/groupby.py", "line": 1544, "side": "RIGHT", "created_at": "2026-01-24T13:46:25+00:00" }, { "id": 2724173543, "user": "user_c1cc819e14db", "body": "Can also remove this template I think; but that can also be done in a separate PR.", "path": "pandas/core/groupby/groupby.py", "line": null, "side": "RIGHT", "created_at": "2026-01-24T13:46:41+00:00" }, { "id": 2724482715, "user": "user_3e9ebe7c174f", "body": "sure, Thanks for letting me know", "path": "pandas/core/groupby/groupby.py", "line": null, "side": "RIGHT", "created_at": "2026-01-24T18:41:50+00:00" } ], "meta": { "languages": [ "py" ], "touches_tests": false, "review_state_summary": { "CHANGES_REQUESTED": 1, "COMMENTED": 1, "APPROVED": 1 }, "meaningful_comment_count": 4, "has_approval": true, "has_changes_requested": true, "total_review_comments": 4 } } { "_id": "8dc681460e4fe881", "_schema_version": "1.0", "_cleaned_at": "2026-02-12T07:46:51.797934+00:00", "repo": "pandas-dev/pandas", "repo_url": "https://github.com/pandas-dev/pandas", "license_name": "BSD 3-Clause \"New\" or \"Revised\" License", "license_spdx": "BSD-3-Clause", "pr_number": 63827, "title": "DOC: Fix GL08 for pandas.tseries.offsets.WeekOfMonth.week", "body": "- [ ] related to #60365\n\nFixes\n\n```\npandas.tseries.offsets.WeekOfMonth.week GL08\npandas.tseries.offsets.LastWeekOfMonth.week GL08\n```", "author": "user_8905a7db72f0", "created_at": "2026-01-23T05:39:47+00:00", "merged_at": "2026-01-23T18:54:44+00:00", "base_branch": "main", "head_branch": "pandas.tseries.offsets.WeekOfMonth.week", "additions": 45, "deletions": 13, "changed_files": 3, "files": [ { "filename": "ci/code_checks.sh", "status": "modified", "additions": 0, "deletions": 2, "changes": 2, "patch": "@@ -93,15 +93,13 @@ if [[ -z \"$CHECK\" || \"$CHECK\" == \"docstrings\" ]]; then\n -i \"pandas.tseries.offsets.FY5253Quarter.startingMonth GL08\" \\\n -i \"pandas.tseries.offsets.FY5253Quarter.year_has_extra_week GL08\" \\\n -i \"pandas.tseries.offsets.LastWeekOfMonth.is_on_offset GL08\" \\\n- -i \"pandas.tseries.offsets.LastWeekOfMonth.week GL08\" \\\n -i \"pandas.tseries.offsets.LastWeekOfMonth.weekday GL08\" \\\n -i \"pandas.tseries.offsets.SemiMonthBegin.is_on_offset GL08\" \\\n -i \"pandas.tseries.offsets.SemiMonthBegin.rule_code GL08\" \\\n -i \"pandas.tseries.offsets.SemiMonthEnd.is_on_offset GL08\" \\\n -i \"pandas.tseries.offsets.SemiMonthEnd.rule_code GL08\" \\\n -i \"pandas.tseries.offsets.Week.is_on_offset GL08\" \\\n -i \"pandas.tseries.offsets.WeekOfMonth.is_on_offset GL08\" \\\n- -i \"pandas.tseries.offsets.WeekOfMonth.week GL08\" \\\n -i \"pandas.tseries.offsets.WeekOfMonth.weekday GL08\" # There should be no backslash in the final line, please keep this comment in the last ignored function\n \n RET=$(($RET + $?)) ; echo $MSG \"DONE\"" }, { "filename": "pandas/_libs/tslibs/offsets.pyi", "status": "modified", "additions": 2, "deletions": 0, "changes": 2, "patch": "@@ -148,6 +148,8 @@ class WeekOfMonthMixin(SingleConstructorOffset):\n def __init__(\n self, n: int = ..., normalize: bool = ..., weekday: int = ...\n ) -> None: ...\n+ [USER_REDACTED]\n+ def week(self) -> int: ...\n \n class YearOffset(SingleConstructorOffset):\n def __init__(" }, { "filename": "pandas/_libs/tslibs/offsets.pyx", "status": "modified", "additions": 43, "deletions": 11, "changes": 54, "patch": "@@ -3020,7 +3020,7 @@ cdef class WeekOfMonthMixin(SingleConstructorOffset):\n \"\"\"\n \n cdef readonly:\n- int weekday, week\n+ int weekday, _week\n \n def __init__(self, n=1, normalize=False, weekday=0):\n BaseOffset.__init__(self, n, normalize)\n@@ -3045,6 +3045,38 @@ cdef class WeekOfMonthMixin(SingleConstructorOffset):\n return False\n return dt.day == self._get_offset_day(dt)\n \n+ [USER_REDACTED]\n+ def week(self) -> int:\n+ \"\"\"\n+ Return the week of the month on which this offset applies.\n+\n+ Returns an integer representing the week of the month (0-3) that this\n+ offset targets. The week is zero-indexed, where 0 corresponds to the\n+ first week of the month.\n+\n+ Returns\n+ -------\n+ int\n+ An integer representing the week of the month (0-3).\n+\n+ See Also\n+ --------\n+ tseries.offsets.WeekOfMonth : Describes monthly dates in a specific week.\n+ tseries.offsets.LastWeekOfMonth : Describes monthly dates in last week.\n+\n+ Examples\n+ --------\n+ >>> pd.offsets.WeekOfMonth(week=0, weekday=0).week\n+ 0\n+\n+ >>> pd.offsets.WeekOfMonth(week=2, weekday=3).week\n+ 2\n+\n+ >>> pd.offsets.LastWeekOfMonth(weekday=0).week\n+ -1\n+ \"\"\"\n+ return self._week\n+\n [USER_REDACTED]\n def rule_code(self) -> str:\n \"\"\"\n@@ -3066,10 +3098,10 @@ cdef class WeekOfMonthMixin(SingleConstructorOffset):\n 'WOM-1MON'\n \"\"\"\n weekday = int_to_weekday.get(self.weekday, \"\")\n- if self.week == -1:\n+ if self._week == -1:\n # LastWeekOfMonth\n return f\"{self._prefix}-{weekday}\"\n- return f\"{self._prefix}-{self.week + 1}{weekday}\"\n+ return f\"{self._prefix}-{self._week + 1}{weekday}\"\n \n \n # ----------------------------------------------------------------------\n@@ -4813,21 +4845,21 @@ cdef class WeekOfMonth(WeekOfMonthMixin):\n \n def __init__(self, n=1, normalize=False, week=0, weekday=0):\n WeekOfMonthMixin.__init__(self, n, normalize, weekday)\n- self.week = week\n+ self._week = week\n \n- if self.week < 0 or self.week > 3:\n- raise ValueError(f\"Week must be 0<=week<=3, got {self.week}\")\n+ if self._week < 0 or self._week > 3:\n+ raise ValueError(f\"Week must be 0<=week<=3, got {self._week}\")\n \n cpdef __setstate__(self, state):\n self._n = state.pop(\"n\")\n self._normalize = state.pop(\"normalize\")\n self.weekday = state.pop(\"weekday\")\n- self.week = state.pop(\"week\")\n+ self._week = state.pop(\"week\")\n \n def _get_offset_day(self, other: datetime) -> int:\n \"\"\"\n Find the day in the same month as other that has the same\n- weekday as self.weekday and is the self.week'th such day in the month.\n+ weekday as self.weekday and is the self._week'th such day in the month.\n \n Parameters\n ----------\n@@ -4840,7 +4872,7 @@ cdef class WeekOfMonth(WeekOfMonthMixin):\n mstart = datetime(other.year, other.month, 1)\n wday = mstart.weekday()\n shift_days = (self.weekday - wday) % 7\n- return 1 + shift_days + self.week * 7\n+ return 1 + shift_days + self._week * 7\n \n [USER_REDACTED]\n def _from_name(cls, suffix=None):\n@@ -4896,7 +4928,7 @@ cdef class LastWeekOfMonth(WeekOfMonthMixin):\n \n def __init__(self, n=1, normalize=False, weekday=0):\n WeekOfMonthMixin.__init__(self, n, normalize, weekday)\n- self.week = -1\n+ self._week = -1\n \n if self._n == 0:\n raise ValueError(\"N cannot be 0\")\n@@ -4905,7 +4937,7 @@ cdef class LastWeekOfMonth(WeekOfMonthMixin):\n self._n = state.pop(\"n\")\n self._normalize = state.pop(\"normalize\")\n self.weekday = state.pop(\"weekday\")\n- self.week = -1\n+ self._week = -1\n \n def _get_offset_day(self, other: datetime) -> int:\n \"\"\"" } ], "reviews": [ { "id": 3698906665, "user": "user_c9260bc45a59", "state": "COMMENTED", "body": null, "submitted_at": "2026-01-23T18:09:22+00:00" }, { "id": 3699023600, "user": "user_8905a7db72f0", "state": "COMMENTED", "body": null, "submitted_at": "2026-01-23T18:34:20+00:00" }, { "id": 3699101282, "user": "user_c9260bc45a59", "state": "APPROVED", "body": null, "submitted_at": "2026-01-23T18:54:37+00:00" } ], "review_comments": [ { "id": 2722303869, "user": "user_c9260bc45a59", "body": "Should this be defined on `WeekOfMonthMixin`?", "path": "pandas/_libs/tslibs/offsets.pyx", "line": null, "side": "RIGHT", "created_at": "2026-01-23T18:09:18+00:00" }, { "id": 2722393635, "user": "user_8905a7db72f0", "body": "yes. added example for LastWeekOfMonth.week as well. Let me know if this looks good.", "path": "pandas/_libs/tslibs/offsets.pyx", "line": null, "side": "RIGHT", "created_at": "2026-01-23T18:34:20+00:00" } ], "meta": { "languages": [ "pyi", "pyx", "sh" ], "touches_tests": false, "review_state_summary": { "COMMENTED": 2, "APPROVED": 1 }, "meaningful_comment_count": 2, "has_approval": true, "has_changes_requested": false, "total_review_comments": 2 } } { "_id": "ddb18b6601269583", "_schema_version": "1.0", "_cleaned_at": "2026-02-12T07:46:51.816848+00:00", "repo": "pandas-dev/pandas", "repo_url": "https://github.com/pandas-dev/pandas", "license_name": "BSD 3-Clause \"New\" or \"Revised\" License", "license_spdx": "BSD-3-Clause", "pr_number": 63812, "title": "DOC: Add py:type reference targets to pandas.api.typing.aliases", "body": "- [x] closes #63810(Replace xxxx with the GitHub issue number)\n- [ ] [Tests added and passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#writing-tests) if fixing a bug or adding a new feature\n- [x] All [code checks passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit).\n- [ ] Added [type annotations](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#type-hints) to new arguments/methods/functions.\n- [x] Added an entry in the latest `doc/source/whatsnew/vX.X.X.rst` file if fixing a bug or adding a new feature.\n- [x] If I used AI to develop this pull request, I prompted it to follow `AGENTS.md`.\n\n## This PR fixes the type aliases documentation to use proper Sphinx directives instead of references.\n\n### Changes\n- Replace `:py:type:` references with `.. py:type::` directives\n- This makes the type aliases available in the intersphinx inventory\n- Allows external projects to link to these type aliases using Sphinx's :type: role", "author": "user_b30d8898a251", "created_at": "2026-01-22T16:30:24+00:00", "merged_at": "2026-02-03T21:05:49+00:00", "base_branch": "main", "head_branch": "fix-type-aliases-refs", "additions": 146, "deletions": 70, "changed_files": 1, "files": [ { "filename": "doc/source/reference/aliases.rst", "status": "modified", "additions": 146, "deletions": 70, "changes": 216, "patch": "@@ -2,6 +2,8 @@\n \n .. _api.typing.aliases:\n \n+{{ header }}\n+\n ======================================\n pandas typing aliases\n ======================================\n@@ -10,7 +12,14 @@ pandas typing aliases\n Typing aliases\n **************\n \n-.. currentmodule:: pandas.api.typing.aliases\n+.. module:: pandas.api.typing.aliases\n+\n+.. raw:: html\n+\n+ \n \n The typing declarations in ``pandas/_typing.py`` are considered private, and used\n by [NAME_REDACTED] checking of the pandas code base. For users, it is\n@@ -25,72 +34,139 @@ own python code that calls pandas or expects certain results.\n \n Each of these aliases listed in the table below can be found by [NAME_REDACTED] :py:mod:`pandas.api.typing.aliases`.\n \n-==================================== ================================================================\n-[NAME_REDACTED]\n-==================================== ================================================================\n-:py:type:`AggFuncType` Type of functions that can be passed to :meth:`agg` methods\n-:py:type:`AlignJoin` Argument type for ``join`` in :meth:`DataFrame.join`\n-:py:type:`AnyAll` Argument type for ``how`` in :meth:`dropna`\n-:py:type:`AnyArrayLike` Used to represent :class:`ExtensionArray`, ``numpy`` arrays, :class:`Index` and :class:`Series`\n-:py:type:`ArrayLike` Used to represent :class:`ExtensionArray`, ``numpy`` arrays\n-:py:type:`AstypeArg` Argument type in :meth:`astype`\n-:py:type:`Axes` :py:type:`AnyArrayLike` plus sequences (not strings) and ``range``\n-:py:type:`Axis` Argument type for ``axis`` in many methods\n-:py:type:`CSVEngine` Argument type for ``engine`` in :meth:`DataFrame.read_csv`\n-:py:type:`ColspaceArgType` Argument type for ``colspace`` in :meth:`DataFrame.to_html`\n-:py:type:`CompressionOptions` Argument type for ``compression`` in all I/O output methods except :meth:`DataFrame.to_parquet`\n-:py:type:`CorrelationMethod` Argument type for ``correlation`` in :meth:`corr`\n-:py:type:`DropKeep` Argument type for ``keep`` in :meth:`drop_duplicates`\n-:py:type:`Dtype` Types as objects that can be used to specify dtypes\n-:py:type:`DtypeArg` Argument type for ``dtype`` in various methods\n-:py:type:`DtypeBackend` Argument type for ``dtype_backend`` in various methods\n-:py:type:`DtypeObj` Numpy dtypes and Extension dtypes\n-:py:type:`ExcelWriterIfSheetExists` Argument type for ``if_sheet_exists`` in :class:`ExcelWriter`\n-:py:type:`ExcelWriterMergeCells` Argument type for ``merge_cells`` in :meth:`to_excel`\n-:py:type:`FilePath` Type of paths for files for I/O methods\n-:py:type:`FillnaOptions` Argument type for ``method`` in various methods where NA values are filled\n-:py:type:`FloatFormatType` Argument type for ``float_format`` in :meth:`to_string`\n-:py:type:`FormattersType` Argument type for ``formatters`` in :meth:`to_string`\n-:py:type:`FromDictOrient` Argument type for ``orient`` in :meth:`DataFrame.from_dict`\n-:py:type:`HTMLFlavors` Argument type for ``flavor`` in :meth:`pandas.read_html`\n-:py:type:`IgnoreRaise` Argument type for ``errors`` in multiple methods\n-:py:type:`IndexLabel` Argument type for ``level`` in multiple methods\n-:py:type:`InterpolateOptions` Argument type for ``interpolate`` in :meth:`interpolate`\n-:py:type:`JSONEngine` Argument type for ``engine`` in :meth:`read_json`\n-:py:type:`JSONSerializable` Argument type for the return type of a callable for argument ``default_handler`` in :meth:`to_json`\n-:py:type:`JoinHow` Argument type for ``how`` in :meth:`pandas.merge_ordered` and for ``join`` in :meth:`Series.align`\n-:py:type:`JoinValidate` Argument type for ``validate`` in :meth:`DataFrame.join`\n-:py:type:`MergeHow` Argument type for ``how`` in :meth:`merge`\n-:py:type:`MergeValidate` Argument type for ``validate`` in :meth:`merge`\n-:py:type:`NaPosition` Argument type for ``na_position`` in :meth:`sort_index` and :meth:`sort_values`\n-:py:type:`NsmallestNlargestKeep` Argument type for ``keep`` in :meth:`nlargest` and :meth:`nsmallest`\n-:py:type:`OpenFileErrors` Argument type for ``errors`` in :meth:`to_hdf` and :meth:`to_csv`\n-:py:type:`Ordered` Return type for :py:attr:`ordered` in :class:`CategoricalDtype` and :class:`Categorical`\n-:py:type:`ParquetCompressionOptions` Argument type for ``compression`` in :meth:`DataFrame.to_parquet`\n-:py:type:`QuantileInterpolation` Argument type for ``interpolation`` in :meth:`quantile`\n-:py:type:`ReadBuffer` Additional argument type corresponding to buffers for various file reading methods\n-:py:type:`ReadCsvBuffer` Additional argument type corresponding to buffers for :meth:`pandas.read_csv`\n-:py:type:`ReadPickleBuffer` Additional argument type corresponding to buffers for :meth:`pandas.read_pickle`\n-:py:type:`ReindexMethod` Argument type for ``reindex`` in :meth:`reindex`\n-:py:type:`Scalar` Types that can be stored in :class:`Series` with non-object dtype\n-:py:type:`SequenceNotStr` Used for arguments that require sequences, but not plain strings\n-:py:type:`SliceType` Argument types for ``start`` and ``end`` in :meth:`Index.slice_locs`\n-:py:type:`SortKind` Argument type for ``kind`` in :meth:`sort_index` and :meth:`sort_values`\n-:py:type:`StorageOptions` Argument type for ``storage_options`` in various file output methods\n-:py:type:`Suffixes` Argument type for ``suffixes`` in :meth:`merge`, :meth:`compare` and :meth:`merge_ordered`\n-:py:type:`TakeIndexer` Argument type for ``indexer`` and ``indices`` in :meth:`take`\n-:py:type:`TimeAmbiguous` Argument type for ``ambiguous`` in time operations\n-:py:type:`TimeGrouperOrigin` Argument type for ``origin`` in :meth:`resample` and :class:`TimeGrouper`\n-:py:type:`TimeNonexistent` Argument type for ``nonexistent`` in time operations\n-:py:type:`TimeUnit` Time unit argument and return type for :py:attr:`unit`, arguments ``unit`` and ``date_unit``\n-:py:type:`TimedeltaConvertibleTypes` Argument type for ``offset`` in :meth:`resample`, ``halflife`` in :meth:`ewm` and ``start`` and ``end`` in :meth:`pandas.timedelta_range`\n-:py:type:`TimestampConvertibleTypes` Argument type for ``origin`` in :meth:`resample` and :meth:`pandas.to_datetime`\n-:py:type:`ToStataByteorder` Argument type for ``byteorder`` in :meth:`DataFrame.to_stata`\n-:py:type:`ToTimestampHow` Argument type for ``how`` in :meth:`to_timestamp` and ``convention`` in :meth:`resample`\n-:py:type:`UpdateJoin` Argument type for ``join`` in :meth:`DataFrame.update`\n-:py:type:`UsecolsArgType` Argument type for ``usecols`` in :meth:`pandas.read_clipboard`, :meth:`pandas.read_csv` and :meth:`pandas.read_excel`\n-:py:type:`WindowingRankType` Argument type for ``method`` in :meth:`rank` in rolling and expanding window operations\n-:py:type:`WriteBuffer` Additional argument type corresponding to buffers for various file output methods\n-:py:type:`WriteExcelBuffer` Additional argument type corresponding to buffers for :meth:`to_excel`\n-:py:type:`XMLParsers` Argument type for ``parser`` in :meth:`DataFrame.to_xml` and :meth:`pandas.read_xml`\n-==================================== ================================================================\n+.. list-table::\n+ :header-rows: 1\n+ :widths: 30 70\n+\n+ * - Alias\n+ - Meaning\n+ * - .. type:: AggFuncType\n+ - Type of functions that can be passed to :meth:`DataFrame's `, :meth:`Series' `, and :meth:`DataFrameGroupBy's ` ``aggregate()`` methods\n+ * - .. type:: AlignJoin\n+ - Argument type for ``join`` in :meth:`DataFrame's ` and :meth:`Series' ` ``align()`` methods\n+ * - .. type:: AnyAll\n+ - Argument type for ``how`` in :meth:`DataFrame's ` and :meth:`Series' ` ``dropna()`` methods\n+ * - .. type:: AnyArrayLike\n+ - Used to represent :class:`~pandas.api.extensions.ExtensionArray`, ``numpy`` arrays, :class:`~pandas.Index` and :class:`~pandas.Series`\n+ * - .. type:: ArrayLike\n+ - Used to represent :class:`~pandas.api.extensions.ExtensionArray`, ``numpy`` arrays\n+ * - .. type:: AstypeArg\n+ - Argument type in :meth:`DataFrame's ` and :meth:`Series' ` ``astype()`` methods\n+ * - .. type:: Axes\n+ - :py:type:`AnyArrayLike` plus sequences (not strings) and ``range``\n+ * - .. type:: Axis\n+ - Argument type for ``axis`` in many methods\n+ * - .. type:: CSVEngine\n+ - Argument type for ``engine`` in :meth:`pandas.read_csv`\n+ * - .. type:: ColspaceArgType\n+ - Argument type for ``colspace`` in :meth:`pandas.DataFrame.to_html`\n+ * - .. type:: CompressionOptions\n+ - Argument type for ``compression`` in all I/O output methods except :meth:`pandas.DataFrame.to_parquet`\n+ * - .. type:: CorrelationMethod\n+ - Argument type for ``correlation`` in :meth:`DataFrame's ` and :meth:`Series' ` ``corr()`` methods\n+ * - .. type:: DropKeep\n+ - Argument type for ``keep`` in :meth:`DataFrame's ` and :meth:`Series' ` ``drop_duplicates()`` methods\n+ * - .. type:: Dtype\n+ - Types as objects that can be used to specify dtypes\n+ * - .. type:: DtypeArg\n+ - Argument type for ``dtype`` in various methods\n+ * - .. type:: DtypeBackend\n+ - Argument type for ``dtype_backend`` in various methods\n+ * - .. type:: DtypeObj\n+ - Numpy dtypes and Extension dtypes\n+ * - .. type:: ExcelWriterIfSheetExists\n+ - Argument type for ``if_sheet_exists`` in :class:`~pandas.ExcelWriter`\n+ * - .. type:: ExcelWriterMergeCells\n+ - Argument type for ``merge_cells`` in :meth:`DataFrame's ` and :meth:`Series' ` ``to_excel()`` methods\n+ * - .. type:: FilePath\n+ - Type of paths for files for I/O methods\n+ * - .. type:: FillnaOptions\n+ - Argument type for ``method`` in various methods where NA values are filled\n+ * - .. type:: FloatFormatType\n+ - Argument type for ``float_format`` in :meth:`DataFrame's ` and :meth:`Series' ` ``to_string()`` methods\n+ * - .. type:: FormattersType\n+ - Argument type for ``formatters`` in :meth:`DataFrame's ` and :meth:`Series' ` ``to_string()`` methods\n+ * - .. type:: FromDictOrient\n+ - Argument type for ``orient`` in :meth:`DataFrame.from_dict() `\n+ * - .. type:: HTMLFlavors\n+ - Argument type for ``flavor`` in :meth:`pandas.read_html`\n+ * - .. type:: IgnoreRaise\n+ - Argument type for ``errors`` in multiple methods\n+ * - .. type:: IndexLabel\n+ - Argument type for ``level`` in multiple methods\n+ * - .. type:: InterpolateOptions\n+ - Argument type for ``interpolate`` in :meth:`DataFrame's ` and :meth:`Series' ` ``interpolate()`` methods\n+ * - .. type:: JSONEngine\n+ - Argument type for ``engine`` in :meth:`pandas.read_json`\n+ * - .. type:: JSONSerializable\n+ - Argument type for the return type of a callable for argument ``default_handler`` in :meth:`DataFrame's ` and :meth:`Series' ` ``to_json()`` methods\n+ * - .. type:: JoinHow\n+ - Argument type for ``how`` in :meth:`pandas.merge_ordered` and for ``join`` in :meth:`Series.align() `\n+ * - .. type:: JoinValidate\n+ - Argument type for ``validate`` in :meth:`DataFrame.join() `\n+ * - .. type:: MergeHow\n+ - Argument type for ``how`` in :meth:`pandas.merge`\n+ * - .. type:: MergeValidate\n+ - Argument type for ``validate`` in :meth:`pandas.merge`\n+ * - .. type:: NaPosition\n+ - Argument type for ``na_position`` in :meth:`DataFrame's ` and :meth:`Series' ` ``sort_values()`` methods\n+ * - .. type:: NsmallestNlargestKeep\n+ - Argument type for ``keep`` in :meth:`DataFrame's ` and :meth:`Series' ` ``nlargest()``, :meth:`DataFrame's ` and :meth:`Series' ` ``nsmallest()``, and :meth:`SeriesGroupBy's ` ``nlargest()`` methods\n+ * - .. type:: OpenFileErrors\n+ - Argument type for ``errors`` in :meth:`DataFrame's `, :meth:`Series' ` ``to_hdf()`` methods, and :meth:`DataFrame's ` and :meth:`Series' ` ``to_csv()`` methods\n+ * - .. type:: Ordered\n+ - Return type for :attr:`ordered ` in :class:`pandas.CategoricalDtype` and :class:`pandas.Categorical`\n+ * - .. type:: ParquetCompressionOptions\n+ - Argument type for ``compression`` in :meth:`DataFrame.to_parquet() `\n+ * - .. type:: QuantileInterpolation\n+ - Argument type for ``interpolation`` in :meth:`DataFrame's ` and :meth:`Series' ` ``quantile()`` methods\n+ * - .. type:: ReadBuffer\n+ - Additional argument type corresponding to buffers for various file reading methods\n+ * - .. type:: ReadCsvBuffer\n+ - Additional argument type corresponding to buffers for :meth:`pandas.read_csv`\n+ * - .. type:: ReadPickleBuffer\n+ - Additional argument type corresponding to buffers for :meth:`pandas.read_pickle`\n+ * - .. type:: ReindexMethod\n+ - Argument type for ``reindex`` in :meth:`DataFrame's ` and :meth:`Series' ` ``reindex()`` methods\n+ * - .. type:: Scalar\n+ - Types that can be stored in :class:`~pandas.Series` with non-object dtype\n+ * - .. type:: SequenceNotStr\n+ - Used for arguments that require sequences, but not plain strings\n+ * - .. type:: SliceType\n+ - Argument types for ``start`` and ``end`` in :meth:`Index.slice_locs() `\n+ * - .. type:: SortKind\n+ - Argument type for ``kind`` in :meth:`DataFrame's ` and :meth:`Series' ` ``sort_values()`` methods\n+ * - .. type:: StorageOptions\n+ - Argument type for ``storage_options`` in various file output methods\n+ * - .. type:: Suffixes\n+ - Argument type for ``suffixes`` in :meth:`pandas.merge`, :meth:`pandas.merge_ordered`, and :meth:`DataFrame's ` and :meth:`Series' ` ``compare()`` methods\n+ * - .. type:: TakeIndexer\n+ - Argument type for ``indexer`` and ``indices`` in :meth:`DataFrame's ` and :meth:`Series' ` ``take()`` methods\n+ * - .. type:: TimeAmbiguous\n+ - Argument type for ``ambiguous`` in time operations\n+ * - .. type:: TimeGrouperOrigin\n+ - Argument type for ``origin`` in :meth:`DataFrame's `, :meth:`Series' ` ``resample()`` methods and for :class:`~pandas.Grouper`\n+ * - .. type:: TimeNonexistent\n+ - Argument type for ``nonexistent`` in time operations\n+ * - .. type:: TimeUnit\n+ - Time unit argument and return type for :attr:`pandas.Timedelta.unit`, arguments ``unit`` and ``date_unit``\n+ * - .. type:: TimedeltaConvertibleTypes\n+ - Argument type for ``offset`` in various methods, such as :meth:`DataFrame's ` and :meth:`Series' ` ``resample()``, ``halflife`` in :meth:`DataFrame's `, :meth:`DataFrameGroupBy's `, and :meth:`Series' ` ``ewm()``, and ``start`` and ``end`` in :meth:`pandas.timedelta_range`\n+ * - .. type:: TimestampConvertibleTypes\n+ - Argument type for ``origin`` in :meth:`DataFrame's ` and :meth:`Series' ` ``resample()``, and in :meth:`pandas.to_datetime`\n+ * - .. type:: ToStataByteorder\n+ - Argument type for ``byteorder`` in :meth:`DataFrame.to_stata() `\n+ * - .. type:: ToTimestampHow\n+ - Argument type for ``how`` in :meth:`DataFrame's ` and :meth:`Series' ` ``to_timestamp()`` methods, and ``convention`` in :meth:`DataFrame's ` and :meth:`Series' ` ``resample()`` methods\n+ * - .. type:: UpdateJoin\n+ - Argument type for ``join`` in :meth:`DataFrame.update() `\n+ * - .. type:: UsecolsArgType\n+ - Argument type for ``usecols`` in :meth:`pandas.read_clipboard`, :meth:`pandas.read_csv` and :meth:`pandas.read_excel`\n+ * - .. type:: WindowingRankType\n+ - Argument type for ``method`` in :meth:`Rolling's ` and :meth:`Expanding's ` ``rank()`` methods, applicable in rolling and expanding window operations\n+ * - .. type:: WriteBuffer\n+ - Additional argument type corresponding to buffers for various file output methods\n+ * - .. type:: WriteExcelBuffer\n+ - Additional argument type corresponding to buffers for :meth:`DataFrame's `, :meth:`Series' ` and :meth:`Styler's ` ``to_excel()`` methods\n+ * - .. type:: XMLParsers\n+ - Argument type for ``parser`` in :meth:`DataFrame.to_xml() ` and :meth:`pandas.read_xml`" } ], "reviews": [ { "id": 3698877340, "user": "user_e9f0ee185142", "state": "COMMENTED", "body": null, "submitted_at": "2026-01-23T18:03:49+00:00" }, { "id": 3698917611, "user": "user_b30d8898a251", "state": "COMMENTED", "body": null, "submitted_at": "2026-01-23T18:11:32+00:00" }, { "id": 3702352779, "user": "user_6d4b2e2faf83", "state": "CHANGES_REQUESTED", "body": null, "submitted_at": "2026-01-24T18:50:10+00:00" }, { "id": 3702616653, "user": "user_b30d8898a251", "state": "COMMENTED", "body": null, "submitted_at": "2026-01-24T20:11:54+00:00" }, { "id": 3702953410, "user": "user_e9f0ee185142", "state": "COMMENTED", "body": null, "submitted_at": "2026-01-24T22:35:09+00:00" }, { "id": 3702956311, "user": "user_e9f0ee185142", "state": "COMMENTED", "body": null, "submitted_at": "2026-01-24T22:36:29+00:00" }, { "id": 3704150438, "user": "user_6d4b2e2faf83", "state": "CHANGES_REQUESTED", "body": "the imports only work from `pandas.api.typing.aliases`", "submitted_at": "2026-01-25T18:19:13+00:00" }, { "id": 3704282696, "user": "user_e9f0ee185142", "state": "CHANGES_REQUESTED", "body": "I have no clue why you keep breaking this. It *must* be this:\n\n```\n.. module:: pandas.api.typing.aliases\n```\n\nand the table needs to look like this\n\n```\n==================================== ================================================================\n[NAME_REDACTED]\n==================================== ================================================================\n.. type:: [NAME_REDACTED] of functions that can be passed to :meth:`agg` methods\n.. type:: [NAME_REDACTED] type for ``join`` in :meth:`DataFrame.join`\n```\n\njust do both of these things and the PR actually does what it says.", "submitted_at": "2026-01-25T22:15:37+00:00" }, { "id": 3711761221, "user": "user_6d4b2e2faf83", "state": "CHANGES_REQUESTED", "body": null, "submitted_at": "2026-01-27T15:29:29+00:00" }, { "id": 3712023501, "user": "user_e9f0ee185142", "state": "COMMENTED", "body": null, "submitted_at": "2026-01-27T15:54:09+00:00" }, { "id": 3712039864, "user": "user_e9f0ee185142", "state": "COMMENTED", "body": null, "submitted_at": "2026-01-27T15:56:47+00:00" }, { "id": 3712040215, "user": "user_6d4b2e2faf83", "state": "COMMENTED", "body": null, "submitted_at": "2026-01-27T15:56:51+00:00" }, { "id": 3712050160, "user": "user_6d4b2e2faf83", "state": "COMMENTED", "body": null, "submitted_at": "2026-01-27T15:58:29+00:00" }, { "id": 3712063321, "user": "user_e9f0ee185142", "state": "COMMENTED", "body": null, "submitted_at": "2026-01-27T16:01:10+00:00" }, { "id": 3712270918, "user": "user_b30d8898a251", "state": "COMMENTED", "body": null, "submitted_at": "2026-01-27T16:41:08+00:00" }, { "id": 3712462671, "user": "user_b30d8898a251", "state": "COMMENTED", "body": null, "submitted_at": "2026-01-27T17:14:02+00:00" }, { "id": 3712578863, "user": "user_b30d8898a251", "state": "COMMENTED", "body": null, "submitted_at": "2026-01-27T17:38:41+00:00" }, { "id": 3712626644, "user": "user_e9f0ee185142", "state": "COMMENTED", "body": null, "submitted_at": "2026-01-27T17:47:52+00:00" }, { "id": 3715097883, "user": "user_e9f0ee185142", "state": "COMMENTED", "body": null, "submitted_at": "2026-01-28T07:53:12+00:00" }, { "id": 3724033021, "user": "user_6d4b2e2faf83", "state": "CHANGES_REQUESTED", "body": "This is still rendering incorrectly, e.g.:\n\n\"Image\"\n\nYou probably need to do what [USER_REDACTED] suggested here: https://github.com/[USER_REDACTED]ndas-dev/pandas/pull/63812#discussion_r2732711546", "submitted_at": "2026-01-29T17:14:24+00:00" }, { "id": 3733326300, "user": "user_b30d8898a251", "state": "COMMENTED", "body": null, "submitted_at": "2026-01-31T19:21:37+00:00" }, { "id": 3733597275, "user": "user_6d4b2e2faf83", "state": "CHANGES_REQUESTED", "body": "I appreciate the work you have done on this. But if you're going to fix links to various methods and classes in this document, you might as well go for all of them. I think I caught the ones that you missed, as well as a few that are incorrect.", "submitted_at": "2026-01-31T22:14:41+00:00" }, { "id": 3741216137, "user": "user_b30d8898a251", "state": "COMMENTED", "body": null, "submitted_at": "2026-02-02T18:30:42+00:00" }, { "id": 3741219710, "user": "user_b30d8898a251", "state": "COMMENTED", "body": null, "submitted_at": "2026-02-02T18:31:29+00:00" }, { "id": 3741242201, "user": "user_b30d8898a251", "state": "COMMENTED", "body": null, "submitted_at": "2026-02-02T18:37:07+00:00" }, { "id": 3741464367, "user": "user_6d4b2e2faf83", "state": "CHANGES_REQUESTED", "body": "I have found a number of grammatical and formatting things, plus a few incorrect links. I think I caught them all, not 100% sure.\n\nMain grammatical things are where you currently see in the rendered output, for example: \"Argument type for indexer and indices in DataFrame's and Series' take method\" and it needs to read \"Argument type for indexer and indices in DataFrame's and Series' take() methods\", so that there are parentheses after the method name in the text, and \"method\" becomes plural.\n\nAnother suggestion is that you fix all of these at once and do one commit, as opposed to a commit for each single change.", "submitted_at": "2026-02-02T20:23:12+00:00" }, { "id": 3746065350, "user": "user_6d4b2e2faf83", "state": "CHANGES_REQUESTED", "body": "It's pretty close. I caught a few things on this review, and you also missed doing a full change as previously suggested, so I unresolved those comments", "submitted_at": "2026-02-03T15:54:33+00:00" }, { "id": 3746288216, "user": "user_b30d8898a251", "state": "COMMENTED", "body": null, "submitted_at": "2026-02-03T16:31:55+00:00" }, { "id": 3746293496, "user": "user_b30d8898a251", "state": "COMMENTED", "body": null, "submitted_at": "2026-02-03T16:33:06+00:00" }, { "id": 3746880354, "user": "user_6d4b2e2faf83", "state": "APPROVED", "body": "Thanks [USER_REDACTED] and [USER_REDACTED]", "submitted_at": "2026-02-03T18:28:43+00:00" } ], "review_comments": [ { "id": 2722284251, "user": "user_e9f0ee185142", "body": "Currentmodule is wrong, it means “the module definition is somewhere else, but pretend we're in there for other directives”\n\nBut the module definition isn't actually anywhere else, it's right here\n\n```suggestion\n.. module:: pandas.api.typing.aliases\n```", "path": "doc/source/reference/aliases.rst", "line": null, "side": "RIGHT", "created_at": "2026-01-23T18:03:49+00:00" }, { "id": 2722310731, "user": "user_b30d8898a251", "body": "[USER_REDACTED] [NAME_REDACTED] [NAME_REDACTED]", "path": "doc/source/reference/aliases.rst", "line": null, "side": "RIGHT", "created_at": "2026-01-23T18:11:32+00:00" }, { "id": 2724489641, "user": "user_6d4b2e2faf83", "body": "Why can't we continue to use the markdown table with `=====` as we do through most of the pandas docs?", "path": "doc/source/reference/aliases.rst", "line": 38, "side": "RIGHT", "created_at": "2026-01-24T18:47:41+00:00" }, { "id": 2724491411, "user": "user_6d4b2e2faf83", "body": "When this is rendered it looks like:\n```text\ntype pandas.api.typing.aliases.AggFuncType\n```\nThe module `pandas.api.typing.aliases` is quite redundant for every entry. Is there a way that could be removed?", "path": "doc/source/reference/aliases.rst", "line": null, "side": "RIGHT", "created_at": "2026-01-24T18:49:57+00:00" }, { "id": 2724564186, "user": "user_b30d8898a251", "body": "ok thanks for clarification i think two backtick method will work by [NAME_REDACTED] to current module", "path": "doc/source/reference/aliases.rst", "line": null, "side": "RIGHT", "created_at": "2026-01-24T20:11:53+00:00" }, { "id": 2724673566, "user": "user_e9f0ee185142", "body": "I didn't check but as said multiple times, rST has a lot of implicit rules about where it accepts inline syntax, block syntax, both, or neither.\n\nI *assume* table syntax might only support inline syntax and not block syntax, and directives are block syntax.\n\nBut as said, that's only an assumption based on the PR author [NAME_REDACTED]", "path": "doc/source/reference/aliases.rst", "line": 38, "side": "RIGHT", "created_at": "2026-01-24T22:35:09+00:00" }, { "id": 2724674279, "user": "user_e9f0ee185142", "body": "No, double backticks mean “this is code”. There point of this PR is to create reference targets.\n\nIn reference roles, using `~` will leave out the redundant part, but I'm not sure if it's possible to shorten here.", "path": "doc/source/reference/aliases.rst", "line": null, "side": "RIGHT", "created_at": "2026-01-24T22:36:29+00:00" }, { "id": 2725797463, "user": "user_6d4b2e2faf83", "body": "```suggestion\nEach of these aliases listed in the table below can be found by [NAME_REDACTED] :py:mod:`pandas.api.typing.aliases`.\n```", "path": "doc/source/reference/aliases.rst", "line": null, "side": "RIGHT", "created_at": "2026-01-25T18:18:07+00:00" }, { "id": 2725797994, "user": "user_6d4b2e2faf83", "body": "```suggestion\n.. currentmodule:: pandas.api.typing.aliases\n```", "path": "doc/source/reference/aliases.rst", "line": null, "side": "RIGHT", "created_at": "2026-01-25T18:18:56+00:00" }, { "id": 2732477700, "user": "user_6d4b2e2faf83", "body": "There is no `Series.to_parquet`", "path": "doc/source/reference/aliases.rst", "line": null, "side": "RIGHT", "created_at": "2026-01-27T15:08:47+00:00" }, { "id": 2732487588, "user": "user_6d4b2e2faf83", "body": "and `:meth:`~pandas.api.typing.SeriesGroupBy.nlargest`", "path": "doc/source/reference/aliases.rst", "line": null, "side": "RIGHT", "created_at": "2026-01-27T15:11:13+00:00" }, { "id": 2732489607, "user": "user_6d4b2e2faf83", "body": "No `Series.to_parquet()`", "path": "doc/source/reference/aliases.rst", "line": null, "side": "RIGHT", "created_at": "2026-01-27T15:11:39+00:00" }, { "id": 2732576431, "user": "user_6d4b2e2faf83", "body": "This is rendering as follows: \n\n\"Image\"\n\nIt really should say `DataFrame.agg()` and `Series.agg()` and `pandas.api.typing.DataFrameGroupBy.agg()` (note the reference to aggregate is incorrect)\n\nI think (but I'm not 100% sure) that the solution here is to use (for example - remove the double quotes): \":meth:\\`DataFrame.agg\\`\"\n\nYou may need to do this throughout the PR - i.e., remove the `~`", "path": "doc/source/reference/aliases.rst", "line": null, "side": "RIGHT", "created_at": "2026-01-27T15:29:23+00:00" }, { "id": 2732698060, "user": "user_e9f0ee185142", "body": "[USER_REDACTED] FYI you can format this syntax properly on GitHub like this:\n\n```markdown\nrenders as `` :meth:`~pandas.api.typing.SeriesGroupBy.nlargest` ``!\n```\n\n> renders as `` :meth:`~pandas.api.typing.SeriesGroupBy.nlargest` ``!\n\nnote the double backticks and space on both sides.", "path": "doc/source/reference/aliases.rst", "line": null, "side": "RIGHT", "created_at": "2026-01-27T15:54:08+00:00" }, { "id": 2732711546, "user": "user_e9f0ee185142", "body": "Removing the tilde makes things very long, that’s why I used the whole “DataFrame’s and Series’ `method`” shenanigans in my PR.", "path": "doc/source/reference/aliases.rst", "line": null, "side": "RIGHT", "created_at": "2026-01-27T15:56:47+00:00" }, { "id": 2732711944, "user": "user_6d4b2e2faf83", "body": "Thanks. I spent a few minutes trying to get it to work and just gave up.", "path": "doc/source/reference/aliases.rst", "line": null, "side": "RIGHT", "created_at": "2026-01-27T15:56:51+00:00" }, { "id": 2732720323, "user": "user_6d4b2e2faf83", "body": "I think it would render correctly (and do the proper links) with `` :meth:`DataFrame.to_parquet` `` . [USER_REDACTED] am I correct about that? We use that elsewhere in the docs.", "path": "doc/source/reference/aliases.rst", "line": null, "side": "RIGHT", "created_at": "2026-01-27T15:58:29+00:00" }, { "id": 2732731815, "user": "user_e9f0ee185142", "body": "I dove into the GFM spec instead of giving up haha!", "path": "doc/source/reference/aliases.rst", "line": null, "side": "RIGHT", "created_at": "2026-01-27T16:01:10+00:00" }, { "id": 2732901756, "user": "user_b30d8898a251", "body": "Good catch [USER_REDACTED] that simplified version data frame to parquet works in other files but remember we are use module not current module in this file so the simplified version will break the links\nbecause sphinx looks for DataFrame inside the aliases namespace", "path": "doc/source/reference/aliases.rst", "line": null, "side": "RIGHT", "created_at": "2026-01-27T16:41:08+00:00" }, { "id": 2733037262, "user": "user_b30d8898a251", "body": "Oh I have little confusion over it also \nOk removed !", "path": "doc/source/reference/aliases.rst", "line": null, "side": "RIGHT", "created_at": "2026-01-27T17:14:02+00:00" }, { "id": 2733131585, "user": "user_b30d8898a251", "body": "[USER_REDACTED] Thanks for the screenshot—that ambiguity was definitely confusing!\n\nI will the references to use explicit title syntax, such as :meth:DataFrame.agg ``. This renders the specific class name (e.g., DataFrame.agg) for clarity as requested, but links to the fully qualified path to prevent build errors caused by [NAME_REDACTED]\n\nThe solution will paid off for us making links little bit longer but not being confusing for anyone anymore\n\nAre it sounds good and to be fixed with this pr or should merge this one and open another issue to fix this?", "path": "doc/source/reference/aliases.rst", "line": null, "side": "RIGHT", "created_at": "2026-01-27T17:38:41+00:00" }, { "id": 2733166630, "user": "user_e9f0ee185142", "body": "Both `module` and `currentmodule` set the lookup context. In fact, setting it is `currentmodule`’s only purpose. The only thing `module` does differently is creating a link target for the module itself, which we want here.", "path": "doc/source/reference/aliases.rst", "line": null, "side": "RIGHT", "created_at": "2026-01-27T17:47:52+00:00" }, { "id": 2735307290, "user": "user_e9f0ee185142", "body": "```suggestion\n.. type:: [NAME_REDACTED] type for ``formatters`` in :meth:`DataFrame.to_string ` and :meth:`Series.to_string `\n```", "path": "doc/source/reference/aliases.rst", "line": null, "side": "RIGHT", "created_at": "2026-01-28T07:53:12+00:00" }, { "id": 2749896799, "user": "user_b30d8898a251", "body": "[USER_REDACTED] I am using table syntax and got the errors all the times it means [USER_REDACTED] not assuming \nrST is not good choice we should use list approach", "path": "doc/source/reference/aliases.rst", "line": 38, "side": "RIGHT", "created_at": "2026-01-31T19:21:37+00:00" }, { "id": 2750083231, "user": "user_6d4b2e2faf83", "body": "```suggestion\n - Argument type for ``engine`` in :meth:`pandas.read_csv`\n```\nThis was just wrong in previous version", "path": "doc/source/reference/aliases.rst", "line": null, "side": "RIGHT", "created_at": "2026-01-31T21:52:53+00:00" }, { "id": 2750084317, "user": "user_6d4b2e2faf83", "body": "```suggestion\n - Argument type for ``compression`` in all I/O output methods except :meth:`pandas.DataFrame.to_parquet`\n```", "path": "doc/source/reference/aliases.rst", "line": null, "side": "RIGHT", "created_at": "2026-01-31T21:53:45+00:00" }, { "id": 2750085334, "user": "user_6d4b2e2faf83", "body": "```suggestion\n - Type of functions that can be passed to :meth:`DataFrame's `, :meth:`Series' `, and :meth:`DataFrameGroupBy's ` aggregate methods\n```", "path": "doc/source/reference/aliases.rst", "line": null, "side": "RIGHT", "created_at": "2026-01-31T21:54:38+00:00" }, { "id": 2750092531, "user": "user_6d4b2e2faf83", "body": "```suggestion\n - Argument type for ``keep`` in :meth:`DataFrame's ` and :meth:`Series' ` ``nlargest``, :meth:`DataFrame's ` and :meth:`Series' ` ``nsmallest``, and :meth:`SeriesGroupBy's ` ``nlargest`` methods\n```", "path": "doc/source/reference/aliases.rst", "line": null, "side": "RIGHT", "created_at": "2026-01-31T22:00:22+00:00" }, { "id": 2750094871, "user": "user_6d4b2e2faf83", "body": "```suggestion\n - Argument type for ``offset`` in various methods, such as :meth:`DataFrame's ` and :meth:`Series' ` ``resample()``, ``halflife`` in :meth:`DataFrame's `, :meth:`DataFrameGroupBy's `, and :meth:`Series' ` ``ewm()``, and ``start`` and ``end`` in :meth:`pandas.timedelta_range`\n```", "path": "doc/source/reference/aliases.rst", "line": null, "side": "RIGHT", "created_at": "2026-01-31T22:02:15+00:00" }, { "id": 2750098874, "user": "user_6d4b2e2faf83", "body": "fix links to `Series` and `Index` here", "path": "doc/source/reference/aliases.rst", "line": null, "side": "RIGHT", "created_at": "2026-01-31T22:05:36+00:00" }, { "id": 2750099987, "user": "user_6d4b2e2faf83", "body": "create links to `Index.dropna()`, `Series.dropna()` and `DataFrame.dropna()`", "path": "doc/source/reference/aliases.rst", "line": null, "side": "RIGHT", "created_at": "2026-01-31T22:06:18+00:00" }, { "id": 2750100987, "user": "user_6d4b2e2faf83", "body": "create links to `Series.astype()`, `DataFrame.astype()`, and `Index.astype()`", "path": "doc/source/reference/aliases.rst", "line": null, "side": "RIGHT", "created_at": "2026-01-31T22:06:50+00:00" }, { "id": 2750102245, "user": "user_6d4b2e2faf83", "body": "create link to `pandas.read_json()`", "path": "doc/source/reference/aliases.rst", "line": null, "side": "RIGHT", "created_at": "2026-01-31T22:07:33+00:00" }, { "id": 2750104242, "user": "user_6d4b2e2faf83", "body": "create links to `DataFrame.merge()` and `pandas.merge()`", "path": "doc/source/reference/aliases.rst", "line": null, "side": "RIGHT", "created_at": "2026-01-31T22:08:43+00:00" }, { "id": 2750105788, "user": "user_6d4b2e2faf83", "body": "create references to `DataFrame.to_hdf()` and `Series.to_hdf()` and `DataFrame.to_csv()` and `Series.to_csv()`", "path": "doc/source/reference/aliases.rst", "line": null, "side": "RIGHT", "created_at": "2026-01-31T22:09:39+00:00" }, { "id": 2750107263, "user": "user_6d4b2e2faf83", "body": "fix links here", "path": "doc/source/reference/aliases.rst", "line": null, "side": "RIGHT", "created_at": "2026-01-31T22:10:31+00:00" }, { "id": 2750108463, "user": "user_6d4b2e2faf83", "body": "create links to `DataFrame.reindex()`, `Series.reindex()` and `Index.reindex()`", "path": "doc/source/reference/aliases.rst", "line": null, "side": "RIGHT", "created_at": "2026-01-31T22:11:15+00:00" }, { "id": 2750108935, "user": "user_6d4b2e2faf83", "body": "fix link", "path": "doc/source/reference/aliases.rst", "line": null, "side": "RIGHT", "created_at": "2026-01-31T22:11:32+00:00" }, { "id": 2750109274, "user": "user_6d4b2e2faf83", "body": "fix link", "path": "doc/source/reference/aliases.rst", "line": null, "side": "RIGHT", "created_at": "2026-01-31T22:11:43+00:00" }, { "id": 2750109860, "user": "user_6d4b2e2faf83", "body": "fix links - there are multiple classes with these methods", "path": "doc/source/reference/aliases.rst", "line": null, "side": "RIGHT", "created_at": "2026-01-31T22:12:06+00:00" }, { "id": 2750110082, "user": "user_6d4b2e2faf83", "body": "fix link", "path": "doc/source/reference/aliases.rst", "line": null, "side": "RIGHT", "created_at": "2026-01-31T22:12:17+00:00" }, { "id": 2750110425, "user": "user_6d4b2e2faf83", "body": "fix links. There are multiple `resample` methods", "path": "doc/source/reference/aliases.rst", "line": null, "side": "RIGHT", "created_at": "2026-01-31T22:12:33+00:00" }, { "id": 2750112279, "user": "user_6d4b2e2faf83", "body": "`DataFrame.to_excel()`, `Series.to_excel()`, and `pandas.io.formats.style.Styler.to_excel()`", "path": "doc/source/reference/aliases.rst", "line": null, "side": "RIGHT", "created_at": "2026-01-31T22:14:00+00:00" }, { "id": 2755705953, "user": "user_b30d8898a251", "body": "fixed", "path": "doc/source/reference/aliases.rst", "line": null, "side": "RIGHT", "created_at": "2026-02-02T18:30:42+00:00" }, { "id": 2755708966, "user": "user_b30d8898a251", "body": "Thanks for clarification [USER_REDACTED]\nFixed", "path": "doc/source/reference/aliases.rst", "line": null, "side": "RIGHT", "created_at": "2026-02-02T18:31:29+00:00" }, { "id": 2755728682, "user": "user_b30d8898a251", "body": "Thanks for Pointing me out [USER_REDACTED] \nFixed", "path": "doc/source/reference/aliases.rst", "line": null, "side": "RIGHT", "created_at": "2026-02-02T18:37:07+00:00" }, { "id": 2755919427, "user": "user_6d4b2e2faf83", "body": "```suggestion\n - Argument type for ``errors`` in :meth:`DataFrame's `, :meth:`Series' ` ``to_hdf()`` methods, and :meth:`DataFrame's ` and :meth:`Series' ` ``to_csv()`` methods\n```", "path": "doc/source/reference/aliases.rst", "line": null, "side": "RIGHT", "created_at": "2026-02-02T19:45:05+00:00" }, { "id": 2755922503, "user": "user_6d4b2e2faf83", "body": "```suggestion\n - Argument type for ``suffixes`` in :meth:`pandas.merge`, :meth:`pandas.merge_ordered`, and :meth:`DataFrame's ` and :meth:`Series' ` ``compare()`` methods\n```", "path": "doc/source/reference/aliases.rst", "line": null, "side": "RIGHT", "created_at": "2026-02-02T19:46:18+00:00" }, { "id": 2755924464, "user": "user_6d4b2e2faf83", "body": "```suggestion\n - Argument type for ``origin`` in :meth:`DataFrame's `, :meth:`Series' ` ``resample()`` methods and for :class:`~pandas.Grouper`\n```", "path": "doc/source/reference/aliases.rst", "line": null, "side": "RIGHT", "created_at": "2026-02-02T19:47:06+00:00" }, { "id": 2755955699, "user": "user_6d4b2e2faf83", "body": "```suggestion\n - Type of functions that can be passed to :meth:`DataFrame's `, :meth:`Series' `, and :meth:`DataFrameGroupBy's ` ``aggregate()`` methods\n```", "path": "doc/source/reference/aliases.rst", "line": null, "side": "RIGHT", "created_at": "2026-02-02T19:58:43+00:00" }, { "id": 2755956438, "user": "user_6d4b2e2faf83", "body": "```suggestion\n - Argument type for ``join`` in :meth:`DataFrame's ` and :meth:`Series' ` ``align()`` methods\n```", "path": "doc/source/reference/aliases.rst", "line": null, "side": "RIGHT", "created_at": "2026-02-02T19:58:59+00:00" }, { "id": 2755957117, "user": "user_6d4b2e2faf83", "body": "```suggestion\n - Argument type for ``how`` in :meth:`DataFrame's ` and :meth:`Series' ` ``dropna()`` methods\n```", "path": "doc/source/reference/aliases.rst", "line": null, "side": "RIGHT", "created_at": "2026-02-02T19:59:12+00:00" }, { "id": 2755957820, "user": "user_6d4b2e2faf83", "body": "```suggestion\n - Argument type in :meth:`DataFrame's ` and :meth:`Series' ` ``astype()`` methods\n```", "path": "doc/source/reference/aliases.rst", "line": null, "side": "RIGHT", "created_at": "2026-02-02T19:59:27+00:00" }, { "id": 2755958416, "user": "user_6d4b2e2faf83", "body": "```suggestion\n - Argument type for ``correlation`` in :meth:`DataFrame's ` and :meth:`Series' ` ``corr()`` methods\n```", "path": "doc/source/reference/aliases.rst", "line": null, "side": "RIGHT", "created_at": "2026-02-02T19:59:41+00:00" }, { "id": 2755958917, "user": "user_6d4b2e2faf83", "body": "```suggestion\n - Argument type for ``keep`` in :meth:`DataFrame's ` and :meth:`Series' ` ``drop_duplicates()`` methods\n```", "path": "doc/source/reference/aliases.rst", "line": null, "side": "RIGHT", "created_at": "2026-02-02T19:59:54+00:00" }, { "id": 2755959464, "user": "user_6d4b2e2faf83", "body": "```suggestion\n - Argument type for ``merge_cells`` in :meth:`DataFrame's ` and :meth:`Series' ` ``to_excel()`` methods\n```", "path": "doc/source/reference/aliases.rst", "line": null, "side": "RIGHT", "created_at": "2026-02-02T20:00:08+00:00" }, { "id": 2755960181, "user": "user_6d4b2e2faf83", "body": "```suggestion\n - Argument type for ``float_format`` in :meth:`DataFrame's ` and :meth:`Series' ` ``to_string()`` methods\n```", "path": "doc/source/reference/aliases.rst", "line": null, "side": "RIGHT", "created_at": "2026-02-02T20:00:21+00:00" }, { "id": 2755960761, "user": "user_6d4b2e2faf83", "body": "```suggestion\n - Argument type for ``formatters`` in :meth:`DataFrame's ` and :meth:`Series' ` ``to_string()`` methods\n```", "path": "doc/source/reference/aliases.rst", "line": null, "side": "RIGHT", "created_at": "2026-02-02T20:00:34+00:00" }, { "id": 2755961941, "user": "user_6d4b2e2faf83", "body": "```suggestion\n - Argument type for ``orient`` in :meth:`DataFrame.from_dict() `\n```", "path": "doc/source/reference/aliases.rst", "line": null, "side": "RIGHT", "created_at": "2026-02-02T20:01:02+00:00" }, { "id": 2755962848, "user": "user_6d4b2e2faf83", "body": "```suggestion\n - Argument type for ``interpolate`` in :meth:`DataFrame's ` and :meth:`Series' ` ``interpolate()`` methods\n```", "path": "doc/source/reference/aliases.rst", "line": null, "side": "RIGHT", "created_at": "2026-02-02T20:01:21+00:00" }, { "id": 2755963492, "user": "user_6d4b2e2faf83", "body": "```suggestion\n - Argument type for the return type of a callable for argument ``default_handler`` in :meth:`DataFrame's ` and :meth:`Series' ` ``to_json()`` methods\n```", "path": "doc/source/reference/aliases.rst", "line": null, "side": "RIGHT", "created_at": "2026-02-02T20:01:35+00:00" }, { "id": 2755972820, "user": "user_6d4b2e2faf83", "body": "```suggestion\n - Argument type for ``validate`` in :meth:`DataFrame.join() `\n```", "path": "doc/source/reference/aliases.rst", "line": null, "side": "RIGHT", "created_at": "2026-02-02T20:05:09+00:00" }, { "id": 2755973545, "user": "user_6d4b2e2faf83", "body": "```suggestion\n - Argument type for ``na_position`` in :meth:`DataFrame's ` and :meth:`Series' ` ``sort_values()`` methods\n```", "path": "doc/source/reference/aliases.rst", "line": null, "side": "RIGHT", "created_at": "2026-02-02T20:05:25+00:00" }, { "id": 2755974969, "user": "user_6d4b2e2faf83", "body": "```suggestion\n - Argument type for ``keep`` in :meth:`DataFrame's ` and :meth:`Series' ` ``nlargest()``, :meth:`DataFrame's ` and :meth:`Series' ` ``nsmallest()``, and :meth:`SeriesGroupBy's ` ``nlargest()`` methods\n```", "path": "doc/source/reference/aliases.rst", "line": null, "side": "RIGHT", "created_at": "2026-02-02T20:05:57+00:00" }, { "id": 2755978602, "user": "user_6d4b2e2faf83", "body": "```suggestion\n - Argument type for ``compression`` in :meth:`DataFrame.to_parquet() `\n```", "path": "doc/source/reference/aliases.rst", "line": null, "side": "RIGHT", "created_at": "2026-02-02T20:07:15+00:00" }, { "id": 2755979339, "user": "user_6d4b2e2faf83", "body": "```suggestion\n - Argument type for ``interpolation`` in :meth:`DataFrame's ` and :meth:`Series' ` ``quantile()`` methods\n```", "path": "doc/source/reference/aliases.rst", "line": null, "side": "RIGHT", "created_at": "2026-02-02T20:07:32+00:00" }, { "id": 2755979930, "user": "user_6d4b2e2faf83", "body": "```suggestion\n - Argument type for ``reindex`` in :meth:`DataFrame's ` and :meth:`Series' ` ``reindex()`` methods\n```", "path": "doc/source/reference/aliases.rst", "line": null, "side": "RIGHT", "created_at": "2026-02-02T20:07:46+00:00" }, { "id": 2755981650, "user": "user_6d4b2e2faf83", "body": "```suggestion\n - Argument types for ``start`` and ``end`` in :meth:`Index.slice_locs() `\n```", "path": "doc/source/reference/aliases.rst", "line": null, "side": "RIGHT", "created_at": "2026-02-02T20:08:27+00:00" }, { "id": 2755982198, "user": "user_6d4b2e2faf83", "body": "```suggestion\n - Argument type for ``kind`` in :meth:`DataFrame's ` and :meth:`Series' ` ``sort_values()`` methods\n```", "path": "doc/source/reference/aliases.rst", "line": null, "side": "RIGHT", "created_at": "2026-02-02T20:08:39+00:00" }, { "id": 2755983386, "user": "user_6d4b2e2faf83", "body": "```suggestion\n - Argument type for ``indexer`` and ``indices`` in :meth:`DataFrame's ` and :meth:`Series' ` ``take()`` methods\n```", "path": "doc/source/reference/aliases.rst", "line": null, "side": "RIGHT", "created_at": "2026-02-02T20:09:07+00:00" }, { "id": 2755987987, "user": "user_6d4b2e2faf83", "body": "```suggestion\n - Argument type for ``byteorder`` in :meth:`DataFrame.to_stata() `\n```", "path": "doc/source/reference/aliases.rst", "line": null, "side": "RIGHT", "created_at": "2026-02-02T20:10:59+00:00" }, { "id": 2755988796, "user": "user_6d4b2e2faf83", "body": "```suggestion\n - Argument type for ``how`` in :meth:`DataFrame's ` and :meth:`Series' ` ``to_timestamp()`` methods, and ``convention`` in :meth:`DataFrame's ` and :meth:`Series' ` ``resample()`` methods\n```", "path": "doc/source/reference/aliases.rst", "line": null, "side": "RIGHT", "created_at": "2026-02-02T20:11:19+00:00" }, { "id": 2755989714, "user": "user_6d4b2e2faf83", "body": "```suggestion\n - Argument type for ``join`` in :meth:`DataFrame.update() `\n```", "path": "doc/source/reference/aliases.rst", "line": null, "side": "RIGHT", "created_at": "2026-02-02T20:11:40+00:00" }, { "id": 2756003183, "user": "user_6d4b2e2faf83", "body": "```suggestion\n - Argument type for ``method`` in :meth:`Rolling's ` and :meth:`Expanding ` ``rank()`` methods, applicable in rolling and expanding window operations\n```", "path": "doc/source/reference/aliases.rst", "line": null, "side": "RIGHT", "created_at": "2026-02-02T20:17:12+00:00" }, { "id": 2756003938, "user": "user_6d4b2e2faf83", "body": "```suggestion\n - Additional argument type corresponding to buffers for :meth:`DataFrame's `, :meth:`Series' ` and :meth:`Styler's ` ``to_excel()`` methods\n```", "path": "doc/source/reference/aliases.rst", "line": null, "side": "RIGHT", "created_at": "2026-02-02T20:17:31+00:00" }, { "id": 2756004997, "user": "user_6d4b2e2faf83", "body": "```suggestion\n - Argument type for ``parser`` in :meth:`DataFrame.to_xml() ` and :meth:`pandas.read_xml`\n```", "path": "doc/source/reference/aliases.rst", "line": null, "side": "RIGHT", "created_at": "2026-02-02T20:17:58+00:00" }, { "id": 2759753331, "user": "user_6d4b2e2faf83", "body": "```suggestion\n - Argument type for ``how`` in :meth:`pandas.merge_ordered` and for ``join`` in :meth:`Series.align() `\n```", "path": "doc/source/reference/aliases.rst", "line": null, "side": "RIGHT", "created_at": "2026-02-03T15:51:07+00:00" }, { "id": 2759755660, "user": "user_6d4b2e2faf83", "body": "You didn't make all the changes suggested here.", "path": "doc/source/reference/aliases.rst", "line": null, "side": "RIGHT", "created_at": "2026-02-03T15:51:43+00:00" }, { "id": 2759758487, "user": "user_6d4b2e2faf83", "body": "you didn't make all the changes here", "path": "doc/source/reference/aliases.rst", "line": null, "side": "RIGHT", "created_at": "2026-02-03T15:52:26+00:00" }, { "id": 2759761094, "user": "user_6d4b2e2faf83", "body": "```suggestion\n - Time unit argument and return type for :attr:`pandas.Timedelta.unit`, arguments ``unit`` and ``date_unit``\n```", "path": "doc/source/reference/aliases.rst", "line": null, "side": "RIGHT", "created_at": "2026-02-03T15:53:03+00:00" }, { "id": 2759764727, "user": "user_6d4b2e2faf83", "body": "```suggestion\n - Argument type for ``method`` in :meth:`Rolling's ` and :meth:`Expanding's ` ``rank()`` methods, applicable in rolling and expanding window operations\n```", "path": "doc/source/reference/aliases.rst", "line": null, "side": "RIGHT", "created_at": "2026-02-03T15:53:47+00:00" }, { "id": 2759948304, "user": "user_b30d8898a251", "body": "you have so sharp eyes chief [USER_REDACTED]", "path": "doc/source/reference/aliases.rst", "line": null, "side": "RIGHT", "created_at": "2026-02-03T16:31:55+00:00" }, { "id": 2759953044, "user": "user_b30d8898a251", "body": "Oh sorry chief [USER_REDACTED]", "path": "doc/source/reference/aliases.rst", "line": null, "side": "RIGHT", "created_at": "2026-02-03T16:33:05+00:00" } ], "meta": { "languages": [ "rst" ], "touches_tests": false, "review_state_summary": { "COMMENTED": 21, "CHANGES_REQUESTED": 8, "APPROVED": 1 }, "meaningful_comment_count": 79, "has_approval": true, "has_changes_requested": true, "total_review_comments": 83 } } { "_id": "e7da7b5d425dd7d8", "_schema_version": "1.0", "_cleaned_at": "2026-02-12T07:46:51.818851+00:00", "repo": "pandas-dev/pandas", "repo_url": "https://github.com/pandas-dev/pandas", "license_name": "BSD 3-Clause \"New\" or \"Revised\" License", "license_spdx": "BSD-3-Clause", "pr_number": 63802, "title": "BUG: NotImplementedError: eq not implemented for when comparing columns and range in pandas 3.0.0rc0 with pyarrow", "body": "- [x] closes #63429\n- [x] [All test cases passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#writing-tests) if fixing a bug or adding a new feature\n- [ ] All [code checks passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit).\n- [x] Added [type annotations](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#type-hints) to new arguments/methods/functions.\n- [x] Added an entry in the latest `doc/source/whatsnew/vX.X.X.rst` file if fixing a bug or adding a new feature.\n- [x] If I used AI to develop this pull request, I prompted it to follow `AGENTS.md`.\n\nI know I'll probably have to update the whatsnew to be 3.0.1.rst instead, but it doesn't exist just yet.\n\nDefaulted to non-pyarrow behavior for range class", "author": "user_6b2749c53ba9", "created_at": "2026-01-21T23:13:52+00:00", "merged_at": "2026-01-31T18:40:32+00:00", "base_branch": "main", "head_branch": "GH#63429", "additions": 13, "deletions": 4, "changed_files": 4, "files": [ { "filename": "doc/source/whatsnew/v3.0.1.rst", "status": "modified", "additions": 1, "deletions": 0, "changes": 1, "patch": "@@ -13,6 +13,7 @@ including other versions of pandas.\n \n Bug fixes\n ^^^^^^^^^\n+- Fixed a bug for comparison operators between :py:class:`range` and objects with :class:`StringDtype` with ``storage=\"pyarrow\"`` (:issue:`63429`)\n - Fixed a bug in the :class:`DataFrame` constructor when passed a :class:`Series` or\n :class:`Index` correctly handling Copy-on-Write (:issue:`63899`)" }, { "filename": "pandas/core/arrays/arrow/array.py", "status": "modified", "additions": 5, "deletions": 3, "changes": 8, "patch": "@@ -906,7 +906,7 @@ def _cmp_method(self, other, op) -> ArrowExtensionArray:\n pc_func = ARROW_CMP_FUNCS[op.__name__]\n ltype = self._pa_array.type\n \n- if isinstance(other, (ExtensionArray, np.ndarray, list)):\n+ if isinstance(other, (ExtensionArray, np.ndarray, list, range)):\n try:\n boxed = self._box_pa(other)\n except pa.lib.ArrowInvalid:\n@@ -915,8 +915,10 @@ def _cmp_method(self, other, op) -> ArrowExtensionArray:\n result = pa.array(res_values, type=pa.bool_(), from_pandas=True)\n else:\n rtype = boxed.type\n- if (pa.types.is_timestamp(ltype) and pa.types.is_date(rtype)) or (\n- pa.types.is_timestamp(rtype) and pa.types.is_date(ltype)\n+ if (\n+ (pa.types.is_timestamp(ltype) and pa.types.is_date(rtype))\n+ or (pa.types.is_timestamp(rtype) and pa.types.is_date(ltype))\n+ or isinstance(other, range)\n ):\n # GH#62157 match non-pyarrow behavior\n result = ops.invalid_comparison(self, other, op)" }, { "filename": "pandas/core/ops/invalid.py", "status": "modified", "additions": 1, "deletions": 1, "changes": 2, "patch": "@@ -25,7 +25,7 @@\n \n def invalid_comparison(\n left: ArrayLike,\n- right: ArrayLike | list | Scalar,\n+ right: ArrayLike | list | range | Scalar,\n op: Callable[[Any, Any], bool],\n ) -> npt.NDArray[np.bool_]:\n \"\"\"" }, { "filename": "pandas/tests/extension/test_arrow.py", "status": "modified", "additions": 6, "deletions": 0, "changes": 6, "patch": "@@ -296,6 +296,12 @@ def test_compare_scalar(self, data, comparison_op):\n ser = pd.Series(data)\n self._compare_other(ser, data, comparison_op, data[0])\n \n+ def test_compare_range_len(self, data, comparison_op):\n+ # GH#63429\n+ ser = pd.Series(data)\n+ range_test = range(len(ser))\n+ self._compare_other(ser, range_test, comparison_op, range_test)\n+\n [USER_REDACTED].mark.parametrize(\"na_action\", [None, \"ignore\"])\n def test_map(self, data_missing, na_action, using_nan_is_na):\n if data_missing.dtype.kind in \"mM\":" } ], "reviews": [ { "id": 3701496567, "user": "user_cb26b31d4771", "state": "COMMENTED", "body": null, "submitted_at": "2026-01-24T12:21:33+00:00" }, { "id": 3719101950, "user": "user_c9260bc45a59", "state": "COMMENTED", "body": null, "submitted_at": "2026-01-28T20:53:38+00:00" }, { "id": 3724128462, "user": "user_c9260bc45a59", "state": "COMMENTED", "body": null, "submitted_at": "2026-01-29T17:35:41+00:00" }, { "id": 3733234862, "user": "user_c9260bc45a59", "state": "APPROVED", "body": null, "submitted_at": "2026-01-31T18:40:12+00:00" } ], "review_comments": [ { "id": 2724090450, "user": "user_cb26b31d4771", "body": "Is there a specific readability reason to wrap the last two conditions in parentheses?", "path": "pandas/core/arrays/arrow/array.py", "line": null, "side": "RIGHT", "created_at": "2026-01-24T12:19:17+00:00" }, { "id": 2724091705, "user": "user_cb26b31d4771", "body": "Can we keep this removed blank line?", "path": "pandas/core/arrays/arrow/array.py", "line": 908, "side": "LEFT", "created_at": "2026-01-24T12:21:22+00:00" }, { "id": 2738563663, "user": "user_c9260bc45a59", "body": "Could you move this to `v3.0.1.rst`?", "path": "doc/source/whatsnew/v3.0.0.rst", "line": null, "side": "RIGHT", "created_at": "2026-01-28T20:53:38+00:00" }, { "id": 2742774472, "user": "user_c9260bc45a59", "body": "```suggestion\n- Fixed a bug for comparison operators between :py:class:`range` and objects with :class:`StringDtype` with `storage=\"pyarrow\"` (:issue:`63429`)\n```", "path": "doc/source/whatsnew/v3.0.1.rst", "line": null, "side": "RIGHT", "created_at": "2026-01-29T17:35:42+00:00" } ], "meta": { "languages": [ "py", "rst" ], "touches_tests": true, "review_state_summary": { "COMMENTED": 3, "APPROVED": 1 }, "meaningful_comment_count": 4, "has_approval": true, "has_changes_requested": false, "total_review_comments": 4 } } { "_id": "b3e7046a85e0633c", "_schema_version": "1.0", "_cleaned_at": "2026-02-12T07:46:51.819848+00:00", "repo": "pandas-dev/pandas", "repo_url": "https://github.com/pandas-dev/pandas", "license_name": "BSD 3-Clause \"New\" or \"Revised\" License", "license_spdx": "BSD-3-Clause", "pr_number": 63796, "title": "WEB: add pandas 3.0 announcement blog post", "body": "Adding a new blog post to point to in communication, and updating the announcement banner to point to that\n\n(for the final release, a separate blog post is maybe less crucial compared to just pointing to the release notes directly. I could also add some highlights to that page)", "author": "user_7213a217ace7", "created_at": "2026-01-21T15:29:46+00:00", "merged_at": "2026-01-22T10:57:48+00:00", "base_branch": "main", "head_branch": "pandas-3-announcement", "additions": 127, "deletions": 1, "changed_files": 2, "files": [ { "filename": "doc/_templates/docs-announcement-banner.html", "status": "modified", "additions": 1, "deletions": 1, "changes": 2, "patch": "@@ -1 +1 @@\n-Announcement: pandas 3.0.0 release candidate ready for testing! Read more in the blog post\n\\ No newline at end of file\n+Announcement: pandas 3.0 released! Read more in the blog post\n\\ No newline at end of file" }, { "filename": "web/pandas/community/blog/pandas-3.0.md", "status": "added", "additions": 126, "deletions": 0, "changes": 126, "patch": "@@ -0,0 +1,126 @@\n+Title: pandas 3.0 released!\n+Date: 2026-01-21\n+\n+# pandas 3.0 released!\n+\n+We're excited to announce the release of pandas 3.0.0. This major\n+long-awaited release brings significant improvements to pandas, but also\n+features some potentially breaking changes.\n+\n+## Highlights of pandas 3.0\n+\n+pandas 3.0 introduces several major enhancements:\n+\n+- **Dedicated string data type by default**: string columns are now inferred as\n+ the new `str` dtype instead of `object`, providing better performance and type\n+ safety\n+- **Consistent copy/view behaviour with Copy-on-Write (CoW)** (a.k.a. getting\n+ rid of the `SettingWithCopyWarning`): more predictable and consistent behavior\n+ for all operations, with improved performance through avoiding unnecessary\n+ copies\n+- **New default resolution for datetime-like data**: no longer defaulting to\n+ nanoseconds, but generally microseconds (or the resolution of the input), when\n+ constructing datetime or timedelta data (avoiding out-of-bounds errors\n+ for dates with a year before 1678 or after 2262)\n+- **New `pd.col` syntax**: initial support for `pd.col()` as a simplified syntax\n+ for creating callables in `DataFrame.assign`\n+\n+Further, pandas 3.0 includes a lot of other improvements and bug fixes. You can\n+find the complete list of changes in the\n+[release notes](https://pandas.pydata.org/docs/dev/whatsnew/v3.0.0.html).\n+\n+## Upgrading to pandas 3.0\n+\n+The pandas 3.0 release removed functionality that was deprecated in previous releases\n+(see [here](https://pandas.pydata.org/docs/whatsnew/v3.0.0.html#whatsnew-300-prior-deprecations)\n+for an overview). It is recommended to first upgrade to pandas 2.3 and to ensure\n+your code is working without warnings, before upgrading to pandas 3.0.\n+\n+Further, as a major release, pandas 3.0 includes some breaking changes that may\n+require updates to your code. The two most significant changes are the new\n+string dtype and the copy/view behaviour changes, detailed below. An overview of\n+all potentially breaking changes can be found in the [Backwards incompatible API\n+changes](https://pandas.pydata.org/docs/whatsnew/v3.0.0.html#backwards-incompatible-api-changes)\n+section of the release notes.\n+\n+### 1. Dedicated string data type by default\n+\n+Starting with pandas 3.0, string columns are automatically inferred as `str`\n+dtype instead of the numpy `object` (which can store any Python object).\n+\n+**Example:**\n+```python\n+# Old behavior (pandas < 3.0)\n+>>> ser = pd.Series([\"a\", \"b\"])\n+>>> ser\n+0 a\n+1 b\n+dtype: object # <-- numpy object dtype\n+\n+# New behavior (pandas 3.0)\n+>>> ser = pd.Series([\"a\", \"b\"])\n+>>> ser.dtype\n+>>> ser\n+0 a\n+1 b\n+dtype: str # <-- new string dtype\n+```\n+\n+This change improves performance and type safety, but may require code updates,\n+especially for library code that currently looks for \"object\" dtype when\n+expecting string data.\n+\n+For more details, see the\n+[migration guide for the new string data type](https://pandas.pydata.org/docs/dev/user_guide/migration-3-strings.html).\n+\n+This new data type will use the `pyarrow` library under the hood, if installed,\n+to provide the performance improvements. Therefore we strongly recommend to\n+install `pyarrow` alongside pandas (but `pyarrow` is not a required dependency\n+installed by default).\n+\n+### 2. Consistent copy/view behaviour with Copy-on-Write (CoW)\n+\n+Copy-on-Write is now the default and only mode in pandas 3.0. This makes\n+behavior more consistent and predictable, and avoids a lot of defensive copying\n+(improving performance), but requires updates to certain coding patterns.\n+\n+The most impactfull change is that **chained assignment will no longer work**.\n+As a result, the `SettingWithCopyWarning` is also removed (since there is no\n+longer ambiguity whether it would work or not), and defensive `.copy()` calls\n+to silence the warning are no longer needed.\n+\n+**Example:**\n+```python\n+# Old behavior (pandas < 3.0) - chained assignment\n+df[\"foo\"][df[\"bar\"] > 5] = # This might modify df (unpredictable)\n+\n+# New behavior (pandas 3.0) - must do the modification in one step (e.g. with .loc)\n+df.loc[df[\"bar\"] > 5, \"foo\"] = 100\n+```\n+\n+In general, any result of an indexing operation or method now always behaves as\n+if it were a copy, so modifications of the result won't affect the original\n+DataFrame.\n+\n+For more details, see the\n+[Copy-on-Write migration guide](https://pandas.pydata.org/docs/dev/user_guide/copy_on_write.html#migrating-to-copy-on-write).\n+\n+## Obtaining pandas 3.0\n+\n+You can install the latest pandas 3.0 release from PyPI:\n+\n+```bash\n+python -m pip install --upgrade pandas==3.0.*\n+```\n+\n+Or from conda-forge using conda/mamba:\n+\n+```bash\n+conda install -c conda-forge pandas=3.0\n+```\n+\n+## Running into an issue or regression?\n+\n+Please report any problem you encounter with the release on the pandas [issue tracker](https://github.com/[USER_REDACTED]ndas-dev/pandas/issues).\n+\n+Thanks to [NAME_REDACTED] made this release possible!" } ], "reviews": [ { "id": 3689493305, "user": "user_c1cc819e14db", "state": "DISMISSED", "body": null, "submitted_at": "2026-01-21T21:36:39+00:00" }, { "id": 3689782471, "user": "user_6d4b2e2faf83", "state": "DISMISSED", "body": "found a few things", "submitted_at": "2026-01-21T23:17:51+00:00" }, { "id": 3691697724, "user": "user_7213a217ace7", "state": "COMMENTED", "body": null, "submitted_at": "2026-01-22T10:22:28+00:00" }, { "id": 3692829702, "user": "user_6d4b2e2faf83", "state": "COMMENTED", "body": "I'm good with it.", "submitted_at": "2026-01-22T14:44:58+00:00" } ], "review_comments": [ { "id": 2714415351, "user": "user_c1cc819e14db", "body": "The initial `(` ends on the next line.\n\n```suggestion\n(see [here](https://pandas.pydata.org/docs/whatsnew/v3.0.0.html#whatsnew-300-prior-deprecations)\n```", "path": "web/pandas/community/blog/pandas-3.0.md", "line": null, "side": "RIGHT", "created_at": "2026-01-21T21:32:52+00:00" }, { "id": 2714420180, "user": "user_c1cc819e14db", "body": "```suggestion\nand the copy/view behaviour changes, detailed below. An overview of all potentially\n```", "path": "web/pandas/community/blog/pandas-3.0.md", "line": null, "side": "RIGHT", "created_at": "2026-01-21T21:34:04+00:00" }, { "id": 2714424189, "user": "user_c1cc819e14db", "body": "I would also mention performance here.", "path": "web/pandas/community/blog/pandas-3.0.md", "line": null, "side": "RIGHT", "created_at": "2026-01-21T21:35:15+00:00" }, { "id": 2714678032, "user": "user_6d4b2e2faf83", "body": "```suggestion\n rid of the `SettingWithCopyWarning`): more predictable and consistent behavior\n```", "path": "web/pandas/community/blog/pandas-3.0.md", "line": null, "side": "RIGHT", "created_at": "2026-01-21T23:15:09+00:00" }, { "id": 2714678587, "user": "user_6d4b2e2faf83", "body": "```suggestion\n constructing datetime or timedelta data (avoiding out-of-bounds errors\n```", "path": "web/pandas/community/blog/pandas-3.0.md", "line": null, "side": "RIGHT", "created_at": "2026-01-21T23:15:27+00:00" }, { "id": 2714681402, "user": "user_6d4b2e2faf83", "body": "```suggestion\n### Obtaining pandas 3.0\n```", "path": "web/pandas/community/blog/pandas-3.0.md", "line": null, "side": "RIGHT", "created_at": "2026-01-21T23:16:50+00:00" }, { "id": 2714683213, "user": "user_6d4b2e2faf83", "body": "Do we want to say anything in this post about how things are affected by [NAME_REDACTED] `pyarrow` is installed, and that it is NOT required to install `pyarrow` ?", "path": "web/pandas/community/blog/pandas-3.0.md", "line": 16, "side": "RIGHT", "created_at": "2026-01-21T23:17:43+00:00" }, { "id": 2716252536, "user": "user_7213a217ace7", "body": "I added a note about that in the section about the string dtype below", "path": "web/pandas/community/blog/pandas-3.0.md", "line": 16, "side": "RIGHT", "created_at": "2026-01-22T10:22:27+00:00" } ], "meta": { "languages": [ "html", "md" ], "touches_tests": false, "review_state_summary": { "DISMISSED": 2, "COMMENTED": 2 }, "meaningful_comment_count": 8, "has_approval": false, "has_changes_requested": false, "total_review_comments": 8 } } { "_id": "eab4edd1c1e9af63", "_schema_version": "1.0", "_cleaned_at": "2026-02-12T07:46:51.822848+00:00", "repo": "pandas-dev/pandas", "repo_url": "https://github.com/pandas-dev/pandas", "license_name": "BSD 3-Clause \"New\" or \"Revised\" License", "license_spdx": "BSD-3-Clause", "pr_number": 63783, "title": "BUG: Fix data races in block internals", "body": "This PR fixes several thread safety issues in Pandas internals on the free-threaded build. We found all of them using thread sanitizer testing.\n\nI also added a multithreaded test based on the original test in statsmodels we used to find these issues. There's probably lots more room to add more multithreaded tests, but a real-world example that triggered real issues seems as good a place to start as any to me.\n\nYou can read more about critical sections in [the CPython docs](https://docs.python.org/3/howto/free-threading-extensions.html#critical-sections), the [cython docs](https://cython.readthedocs.io/en/latest/src/userguide/freethreading.html#critical-sections), and the [free-threading guide](https://py-free-threading.github.io/porting-extensions/#critical-sections).\n\n- [x] closes #63685\n- [x] [Tests added and passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#writing-tests) if fixing a bug or adding a new feature\n- [x] All [code checks passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit).\n- [ ] Added [type annotations](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#type-hints) to new arguments/methods/functions.\n- [x] Added an entry in the latest `doc/source/whatsnew/vX.X.X.rst` file if fixing a bug or adding a new feature.\n- [ ] If I used AI to develop this pull request, I prompted it to follow `AGENTS.md`.", "author": "user_040357b57427", "created_at": "2026-01-20T23:51:18+00:00", "merged_at": "2026-02-08T18:13:13+00:00", "base_branch": "main", "head_branch": "thread-safe", "additions": 167, "deletions": 23, "changed_files": 11, "files": [ { "filename": "doc/source/whatsnew/v3.0.1.rst", "status": "modified", "additions": 1, "deletions": 0, "changes": 1, "patch": "@@ -27,6 +27,7 @@ Bug fixes\n - Fixed a bug in :func:`col` where unary operators (``-``, ``+``, ``abs``) were not supported (:issue:`63939`)\n - Fixed a bug in the :func:`comparison_op` raising a ``TypeError`` for zerodim\n subclasses of ``np.ndarray`` (:issue:`63205`)\n+- Fixed thread safety issues in :class:`DataFrame` internals on the free-threaded build (:issue:`63685`).\n \n .. ---------------------------------------------------------------------------\n .. _whatsnew_301.contributors:" }, { "filename": "environment.yml", "status": "modified", "additions": 1, "deletions": 1, "changes": 2, "patch": "@@ -8,7 +8,7 @@ dependencies:\n \n # build dependencies\n - versioneer\n- - cython<4.0.0a0\n+ - cython>=3.1.0,<4.0.0a0\n - meson>=1.2.1,<2\n - meson-python>=0.17.1,<1" }, { "filename": "pandas/_libs/index.pyx", "status": "modified", "additions": 14, "deletions": 9, "changes": 23, "patch": "@@ -272,6 +272,7 @@ cdef class IndexEngine:\n self.monotonic_dec = 1\n \n [USER_REDACTED]\n+ [USER_REDACTED].critical_section\n def is_unique(self) -> bool:\n # for why we check is_monotonic_increasing here, see\n # https://github.com/[USER_REDACTED]ndas-dev/pandas/pull/55342#discussion_r1361405781\n@@ -286,13 +287,15 @@ cdef class IndexEngine:\n self._ensure_mapping_populated()\n \n [USER_REDACTED]\n+ [USER_REDACTED].critical_section\n def is_monotonic_increasing(self) -> bool:\n if self.need_monotonic_check:\n self._do_monotonic_check()\n \n return self.monotonic_inc == 1\n \n [USER_REDACTED]\n+ [USER_REDACTED].critical_section\n def is_monotonic_decreasing(self) -> bool:\n if self.need_monotonic_check:\n self._do_monotonic_check()\n@@ -336,24 +339,26 @@ cdef class IndexEngine:\n return val\n \n [USER_REDACTED]\n+ [USER_REDACTED].critical_section\n def is_mapping_populated(self) -> bool:\n return self.mapping is not None\n \n+ [USER_REDACTED].critical_section\n cdef _ensure_mapping_populated(self):\n # this populates the mapping\n # if its not already populated\n # also satisfies the need_unique_check\n-\n if not self.is_mapping_populated:\n-\n values = self.values\n- self.mapping = self._make_hash_table(len(values))\n- self.mapping.map_locations(values, self.mask)\n-\n- if len(self.mapping) == len(values):\n- self.unique = 1\n-\n- self.need_unique_check = 0\n+ mapping = self._make_hash_table(len(values))\n+ mapping.map_locations(values, self.mask)\n+ unique = len(mapping) == len(values)\n+ # check again after creating the mapping\n+ # which could have released the critical_section\n+ if not self.is_mapping_populated:\n+ self.mapping = mapping\n+ self.unique = unique\n+ self.need_unique_check = 0\n \n def clear_mapping(self):\n self.mapping = None" }, { "filename": "pandas/_libs/internals.pyx", "status": "modified", "additions": 37, "deletions": 10, "changes": 47, "patch": "@@ -139,6 +139,7 @@ cdef class BlockPlacement:\n return self._as_array\n \n [USER_REDACTED]\n+ [USER_REDACTED].critical_section\n def as_array(self) -> np.ndarray:\n cdef:\n Py_ssize_t start, stop, _\n@@ -147,8 +148,10 @@ cdef class BlockPlacement:\n start, stop, step, _ = slice_get_indices_ex(self._as_slice)\n # NOTE: this is the C-optimized equivalent of\n # `np.arange(start, stop, step, dtype=np.intp)`\n- self._as_array = cnp.PyArray_Arange(start, stop, step, NPY_INTP)\n- self._has_array = True\n+ as_array = cnp.PyArray_Arange(start, stop, step, NPY_INTP)\n+ if not self._has_array:\n+ self._as_array = as_array\n+ self._has_array = True\n \n return self._as_array\n \n@@ -221,11 +224,14 @@ cdef class BlockPlacement:\n # We can get here with int or ndarray\n return self.iadd(other)\n \n+ [USER_REDACTED].critical_section\n cdef slice _ensure_has_slice(self):\n if not self._has_slice:\n- self._as_slice = indexer_as_slice(self._as_array)\n- self._has_slice = True\n-\n+ as_slice = indexer_as_slice(self._as_array)\n+ # check again after indexer_as_slice call\n+ if not self._has_slice:\n+ self._as_slice = as_slice\n+ self._has_slice = True\n return self._as_slice\n \n cpdef BlockPlacement increment_above(self, Py_ssize_t loc):\n@@ -730,7 +736,7 @@ cdef class BlockManager:\n public tuple blocks\n public list axes\n public bint _known_consolidated, _is_consolidated\n- public ndarray _blknos, _blklocs\n+ ndarray __blknos, __blklocs\n \n def __cinit__(\n self,\n@@ -758,7 +764,27 @@ cdef class BlockManager:\n \n # -------------------------------------------------------------------\n # [NAME_REDACTED]\n+ [USER_REDACTED]\n+ [USER_REDACTED].critical_section\n+ def _blknos(self):\n+ return self.__blknos\n+\n+ @_blknos.setter\n+ [USER_REDACTED].critical_section\n+ def _blknos(self, ndarray val):\n+ self.__blknos = val\n+\n+ [USER_REDACTED]\n+ [USER_REDACTED].critical_section\n+ def _blklocs(self):\n+ return self.__blklocs\n+\n+ @_blklocs.setter\n+ [USER_REDACTED].critical_section\n+ def _blklocs(self, ndarray val):\n+ self.__blklocs = val\n \n+ [USER_REDACTED].critical_section\n cpdef _rebuild_blknos_and_blklocs(self):\n \"\"\"\n Update mgr._blknos / mgr._blklocs.\n@@ -796,8 +822,8 @@ cdef class BlockManager:\n if blkno == -1:\n raise AssertionError(\"Gaps in blk ref_locs\")\n \n- self._blknos = new_blknos\n- self._blklocs = new_blklocs\n+ self.__blknos = new_blknos\n+ self.__blklocs = new_blklocs\n \n # -------------------------------------------------------------------\n # Pickle\n@@ -869,8 +895,9 @@ cdef class BlockManager:\n mgr = type(self)(tuple(nbs), new_axes, verify_integrity=False)\n \n # We can avoid having to rebuild blklocs/blknos\n- blklocs = self._blklocs\n- blknos = self._blknos\n+ with cython.critical_section(self):\n+ blklocs = self.__blklocs\n+ blknos = self.__blknos\n if blknos is not None:\n mgr._blknos = blknos.copy()\n mgr._blklocs = blklocs.copy()" }, { "filename": "pandas/_libs/tslibs/timedeltas.pyx", "status": "modified", "additions": 3, "deletions": 0, "changes": 3, "patch": "@@ -1518,6 +1518,7 @@ cdef class _Timedelta(timedelta):\n self._ensure_components()\n return -999999999 <= self._d and self._d <= 999999999\n \n+ [USER_REDACTED].critical_section\n cdef _ensure_components(_Timedelta self):\n \"\"\"\n compute the components\n@@ -1529,6 +1530,8 @@ cdef class _Timedelta(timedelta):\n pandas_timedeltastruct tds\n \n pandas_timedelta_to_timedeltastruct(self._value, self._creso, &tds)\n+ if self._is_populated:\n+ return\n self._d = tds.days\n self._h = tds.hrs\n self._m = tds.min" }, { "filename": "pandas/_testing/__init__.py", "status": "modified", "additions": 33, "deletions": 0, "changes": 33, "patch": "@@ -1,9 +1,11 @@\n from __future__ import annotations\n \n+from concurrent.futures import ThreadPoolExecutor\n from decimal import Decimal\n import operator\n import os\n from sys import byteorder\n+import threading\n from typing import (\n TYPE_CHECKING,\n ContextManager,\n@@ -535,6 +537,36 @@ def shares_memory(left, right) -> bool:\n raise NotImplementedError(type(left), type(right))\n \n \n+def run_multithreaded(closure, max_workers, arguments=None, pass_barrier=False):\n+ with ThreadPoolExecutor(max_workers=max_workers) as tpe:\n+ if arguments is None:\n+ arguments = []\n+ else:\n+ arguments = list(arguments)\n+\n+ if pass_barrier:\n+ barrier = threading.Barrier(max_workers)\n+ arguments.append(barrier)\n+\n+ try:\n+ futures = []\n+ for _ in range(max_workers):\n+ futures.append(tpe.submit(closure, *arguments)) # noqa: PERF401\n+ except RuntimeError as e:\n+ import pytest\n+\n+ pytest.skip(\n+ f\"Spawning {max_workers} threads failed with \"\n+ f\"error {e!r} (likely due to resource limits on the \"\n+ \"system running the tests)\"\n+ )\n+ finally:\n+ if len(futures) < max_workers and pass_barrier:\n+ barrier.abort()\n+ for f in futures:\n+ f.result()\n+\n+\n __all__ = [\n \"ALL_INT_EA_DTYPES\",\n \"ALL_INT_NUMPY_DTYPES\",\n@@ -602,6 +634,7 @@ def shares_memory(left, right) -> bool:\n \"raises_chained_assignment_error\",\n \"round_trip_pathlib\",\n \"round_trip_pickle\",\n+ \"run_multithreaded\",\n \"set_locale\",\n \"set_timezone\",\n \"setitem\"," }, { "filename": "pandas/tests/frame/test_block_internals.py", "status": "modified", "additions": 70, "deletions": 0, "changes": 70, "patch": "@@ -2,12 +2,15 @@\n datetime,\n timedelta,\n )\n+from io import StringIO\n import itertools\n+from textwrap import dedent\n \n import numpy as np\n import pytest\n \n from pandas.errors import Pandas4Warning\n+import pandas.util._test_decorators as td\n \n import pandas as pd\n from pandas import (\n@@ -383,3 +386,70 @@ def test_update_inplace_sets_valid_block_values():\n \n # check we haven't put a Series into any block.values\n assert isinstance(df._mgr.blocks[0].values, Categorical)\n+\n+\n+def get_longley_data():\n+ # From statsmodels.datasets.longley\n+ # This specific dataset seems to trigger races in Pandas 3.0.0 more readily\n+ # than data frames used elsewhere in the tests\n+ longley_csv = StringIO(\n+ dedent(\n+ \"\"\"\"Obs\",\"GNPDEFL\",\"GNP\",\"UNEMP\",\"ARMED\",\"POP\",\"YEAR\"\n+ 1,83,234289,2356,1590,107608,1947\n+ 2,88.5,259426,2325,1456,108632,1948\n+ 3,88.2,258054,3682,1616,109773,1949\n+ 4,89.5,284599,3351,1650,110929,1950\n+ 5,96.2,328975,2099,3099,112075,1951\n+ 6,98.1,346999,1932,3594,113270,1952\n+ 7,99,365385,1870,3547,115094,1953\n+ 8,100,363112,3578,3350,116219,1954\n+ 9,101.2,397469,2904,3048,117388,1955\n+ 10,104.6,419180,2822,2857,118734,1956\n+ 11,108.4,442769,2936,2798,120445,1957\n+ 12,110.8,444546,4681,2637,121950,1958\n+ 13,112.6,482704,3813,2552,123366,1959\n+ 14,114.2,502601,3931,2514,125368,1960\n+ 15,115.7,518173,4806,2572,127852,1961\n+ 16,116.9,554894,4007,2827,130081,1962\n+ \"\"\"\n+ )\n+ )\n+\n+ return pd.read_csv(longley_csv).iloc[:, [1, 2, 3, 4, 5, 6]].astype(float)\n+\n+\n+# See gh-63685, comparisons and copying led to races in statsmodels tests\n+#\n+# This test spawns a thread pool, so it shouldn't run under xdist.\n+# It generates warnings, so it needs warnings to be thread-safe as well\n+[USER_REDACTED].skip_if_thread_unsafe_warnings\n+[USER_REDACTED].mark.single_cpu\n+def test_multithreaded_reading():\n+ def numpy_assert(data, b):\n+ b.wait()\n+ tm.assert_almost_equal((data + 1) - 1, data.copy())\n+\n+ tm.run_multithreaded(\n+ numpy_assert, max_workers=8, arguments=(get_longley_data(),), pass_barrier=True\n+ )\n+\n+ def safe_is_const(s):\n+ try:\n+ return np.ptp(s) == 0.0 and np.any(s != 0.0)\n+ except Exception:\n+ return False\n+\n+ def concat(data, b):\n+ b.wait()\n+ x = data.copy()\n+ nobs = len(x)\n+ trendarr = np.fliplr(np.vander(np.arange(1, nobs + 1, dtype=np.float64), 1))\n+ x.apply(safe_is_const, 0)\n+ trendarr = DataFrame(trendarr, index=x.index, columns=[\"const\"])\n+ x = [trendarr, x]\n+ x = pd.concat(x[::1], axis=1)\n+ tm.assert_frame_equal(x, x)\n+\n+ tm.run_multithreaded(\n+ concat, max_workers=8, arguments=(get_longley_data(),), pass_barrier=True\n+ )" }, { "filename": "pandas/util/_test_decorators.py", "status": "modified", "additions": 5, "deletions": 0, "changes": 5, "patch": "@@ -27,6 +27,7 @@ def test_foo():\n from __future__ import annotations\n \n import locale\n+import sys\n from typing import TYPE_CHECKING\n \n import pytest\n@@ -118,6 +119,10 @@ def skip_if_no(package: str, min_version: str | None = None) -> pytest.MarkDecor\n WASM,\n reason=\"does not support wasm\",\n )\n+skip_if_thread_unsafe_warnings = pytest.mark.skipif(\n+ not getattr(sys.flags, \"context_aware_warnings\", 0),\n+ reason=\"Python warnings must be thread-safe for consistent results\",\n+)\n \n \n def parametrize_fixture_doc(*args) -> Callable[[F], F]:" }, { "filename": "pyproject.toml", "status": "modified", "additions": 1, "deletions": 1, "changes": 2, "patch": "@@ -5,7 +5,7 @@ requires = [\n \"meson-python>=0.17.1,<1\",\n \"meson>=1.2.1,<2\",\n \"wheel\",\n- \"Cython<4.0.0a0\", # Note: sync with setup.py, environment.yml and asv.conf.json\n+ \"Cython>3.1.0,<4.0.0a0\", # Note: sync with setup.py, environment.yml and asv.conf.json\n # Force numpy higher than 2.0, so that built wheels are compatible\n # with both numpy 1 and 2\n \"numpy>=2.0.0\"," }, { "filename": "requirements-dev.txt", "status": "modified", "additions": 1, "deletions": 1, "changes": 2, "patch": "@@ -3,7 +3,7 @@\n \n pip\n versioneer[toml]\n-cython<4.0.0a0\n+cython>=3.1.0,<4.0.0a0\n meson[ninja]>=1.2.1,<2\n meson-python>=0.17.1,<1\n pytest>=8.3.4" }, { "filename": "setup.py", "status": "modified", "additions": 1, "deletions": 1, "changes": 2, "patch": "@@ -37,7 +37,7 @@ def is_platform_mac():\n \n \n # note: sync with pyproject.toml, environment.yml and asv.conf.json\n-min_cython_ver = \"3.0\"\n+min_cython_ver = \"3.1\"\n \n try:\n from Cython import (" } ], "reviews": [ { "id": 3758591882, "user": "user_c9260bc45a59", "state": "COMMENTED", "body": null, "submitted_at": "2026-02-05T18:03:13+00:00" }, { "id": 3758805951, "user": "user_040357b57427", "state": "COMMENTED", "body": null, "submitted_at": "2026-02-05T18:50:09+00:00" }, { "id": 3758867938, "user": "user_c9260bc45a59", "state": "APPROVED", "body": null, "submitted_at": "2026-02-05T19:03:42+00:00" }, { "id": 3763324583, "user": "user_1b2263f8e7bd", "state": "COMMENTED", "body": null, "submitted_at": "2026-02-06T14:07:43+00:00" }, { "id": 3770104300, "user": "user_c9260bc45a59", "state": "APPROVED", "body": null, "submitted_at": "2026-02-08T18:13:05+00:00" } ], "review_comments": [ { "id": 2770437948, "user": "user_c9260bc45a59", "body": "Do you think this tests is reliable (non-flaky) to run with pytest-xdist on the GHA runners? Decorating this tests with `[USER_REDACTED].mark.single_cpu` will run this test without xdist", "path": "pandas/tests/frame/test_block_internals.py", "line": 427, "side": "RIGHT", "created_at": "2026-02-05T17:58:52+00:00" }, { "id": 2770631559, "user": "user_040357b57427", "body": "Good call, I added the mark and also added some explanatory comments.", "path": "pandas/tests/frame/test_block_internals.py", "line": 427, "side": "RIGHT", "created_at": "2026-02-05T18:50:09+00:00" }, { "id": 2774336788, "user": "user_1b2263f8e7bd", "body": "```suggestion\nskip_if_thread_unsafe_warnings = pytest.mark.skipif(\n```\nnaming nit", "path": "pandas/util/_test_decorators.py", "line": null, "side": "RIGHT", "created_at": "2026-02-06T14:07:44+00:00" } ], "meta": { "languages": [ "py", "pyx", "rst", "toml", "txt", "yml" ], "touches_tests": true, "review_state_summary": { "COMMENTED": 3, "APPROVED": 2 }, "meaningful_comment_count": 3, "has_approval": true, "has_changes_requested": false, "total_review_comments": 3 } } { "_id": "a498fcda376eec9a", "_schema_version": "1.0", "_cleaned_at": "2026-02-12T07:46:51.823856+00:00", "repo": "pandas-dev/pandas", "repo_url": "https://github.com/pandas-dev/pandas", "license_name": "BSD 3-Clause \"New\" or \"Revised\" License", "license_spdx": "BSD-3-Clause", "pr_number": 63780, "title": "DOC: update whatsnew section on datetimelike resolution", "body": "Rewriting this section now all the different changes have landed, in an attempt to make it a bit more coherent (and some things were also a bit outdated after all the changes).", "author": "user_7213a217ace7", "created_at": "2026-01-20T16:46:51+00:00", "merged_at": "2026-01-21T12:18:31+00:00", "base_branch": "main", "head_branch": "3.0-whatsnew-datetime-resolution", "additions": 46, "deletions": 52, "changed_files": 2, "files": [ { "filename": "doc/source/user_guide/timeseries.rst", "status": "modified", "additions": 2, "deletions": 2, "changes": 4, "patch": "@@ -398,8 +398,8 @@ or resolution of the datetime64 dtype:\n .. ipython:: python\n \n stamps.astype(np.int64)\n- stamps.astype(\"datetime64[s]\").astype(np.int64)\n- stamps.astype(\"datetime64[ms]\").astype(np.int64)\n+ stamps.as_unit(\"s\").astype(np.int64)\n+ stamps.as_unit(\"ns\").astype(np.int64)\n \n \n .. _timeseries.origin:" }, { "filename": "doc/source/whatsnew/v3.0.0.rst", "status": "modified", "additions": 44, "deletions": 50, "changes": 94, "patch": "@@ -343,74 +343,68 @@ Backwards incompatible API changes\n \n .. _whatsnew_300.api_breaking.datetime_resolution_inference:\n \n-Datetime resolution inference\n-^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n+Datetime/timedelta resolution inference\n+^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n \n-Converting a sequence of strings, ``datetime`` objects, or ``np.datetime64`` objects to\n-a ``datetime64`` dtype now performs inference on the appropriate resolution (AKA unit) for the output dtype. This affects :class:`Series`, :class:`DataFrame`, :class:`Index`, :class:`DatetimeIndex`, and :func:`to_datetime`.\n+Prior to pandas 3.0, whenever converting a sequence of of strings, stdlib ``datetime``\n+objects, ``np.datetime64`` objects, or integers to a ``datetime64`` / ``timedelta64``\n+dtype, this would always have resulted in nanosecond resolution (or raised an\n+out-of-bounds error).\n+Now it performs inference on the appropriate resolution (a.k.a. ``unit``) for the output dtype. This affects both the generric constructors (:class:`Series`, :class:`DataFrame`, :class:`Index`, :class:`DatetimeIndex`) as specific conversion or creation functions (:func:`to_datetime`, :func:`to_timedelta`, :func:`date_range`, :func:`timedelta_range`, :class:`Timestamp`, :class:`Timedelta`).\n \n-Previously, these would always give nanosecond resolution:\n+The general rules for the various types of input:\n \n-.. code-block:: ipython\n-\n- In [1]: dt = pd.Timestamp(\"2024-03-22 11:36\").to_pydatetime()\n- In [2]: pd.to_datetime([dt]).dtype\n- Out[2]: dtype(' \"and specific\"?", "path": "doc/source/whatsnew/v3.0.0.rst", "line": 353, "side": "RIGHT", "created_at": "2026-01-21T16:56:56+00:00" }, { "id": 2713494525, "user": "user_fb5fa0a10142", "body": "other than this, looks good.", "path": "doc/source/whatsnew/v3.0.0.rst", "line": 353, "side": "RIGHT", "created_at": "2026-01-21T16:58:48+00:00" } ], "meta": { "languages": [ "rst" ], "touches_tests": false, "review_state_summary": { "COMMENTED": 2 }, "meaningful_comment_count": 2, "has_approval": false, "has_changes_requested": false, "total_review_comments": 2 } } { "_id": "3bc8e112bba112a5", "_schema_version": "1.0", "_cleaned_at": "2026-02-12T07:46:51.829287+00:00", "repo": "pandas-dev/pandas", "repo_url": "https://github.com/pandas-dev/pandas", "license_name": "BSD 3-Clause \"New\" or \"Revised\" License", "license_spdx": "BSD-3-Clause", "pr_number": 63771, "title": "DOC: Inline `[USER_REDACTED](ops.make_flex_doc(...))` in `pandas/core/frame.py`", "body": "- [ ] closes #xxxx (Replace xxxx with the GitHub issue number)\n- [ ] [Tests added and passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#writing-tests) if fixing a bug or adding a new feature\n- [x] All [code checks passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit).\n- [ ] Added [type annotations](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#type-hints) to new arguments/methods/functions.\n- [ ] Added an entry in the latest `doc/source/whatsnew/vX.X.X.rst` file if fixing a bug or adding a new feature.\n- [ ] If I used AI to develop this pull request, I prompted it to follow `AGENTS.md`.\n\nThis PR is a part of https://github.com/[USER_REDACTED]ndas-dev/pandas/issues/62437", "author": "user_5b0b62fe7839", "created_at": "2026-01-20T03:35:46+00:00", "merged_at": "2026-01-22T19:26:35+00:00", "base_branch": "main", "head_branch": "inline_frame_flex_doc", "additions": 1964, "deletions": 33, "changed_files": 1, "files": [ { "filename": "pandas/core/frame.py", "status": "modified", "additions": 1964, "deletions": 33, "changes": 1997, "patch": "@@ -9867,139 +9867,2070 @@ def ne(self, other, axis: Axis = \"columns\", level=None) -> DataFrame:\n \"\"\"\n return self._flex_cmp_method(other, operator.ne, axis=axis, level=level)\n \n- [USER_REDACTED](ops.make_flex_doc(\"le\", \"dataframe\"))\n def le(self, other, axis: Axis = \"columns\", level=None) -> DataFrame:\n+ \"\"\"\n+ [NAME_REDACTED] than or equal to of dataframe and other, \\\n+ element-wise (binary operator `le`).\n+\n+ Among flexible wrappers (`eq`, `ne`, `le`, `lt`, `ge`, `gt`) to comparison\n+ operators.\n+\n+ Equivalent to ``<=`` with support to choose axis\n+ (rows or columns) and level for comparison.\n+\n+ Parameters\n+ ----------\n+ other : scalar, sequence, Series, or DataFrame\n+ Any single or multiple element data structure, or list-like object.\n+ axis : {0 or 'index', 1 or 'columns'}, default 'columns'\n+ Whether to compare by [NAME_REDACTED] (0 or 'index') or columns\n+ (1 or 'columns').\n+ level : int or label\n+ Broadcast across a level, matching Index values on the passed\n+ MultiIndex level.\n+\n+ Returns\n+ -------\n+ DataFrame of bool\n+ Result of the comparison.\n+\n+ See Also\n+ --------\n+ DataFrame.eq : [NAME_REDACTED] for equality elementwise.\n+ DataFrame.ne : [NAME_REDACTED] for inequality elementwise.\n+ DataFrame.le : [NAME_REDACTED] for less than inequality\n+ or equality elementwise.\n+ DataFrame.lt : [NAME_REDACTED] for strictly less than\n+ inequality elementwise.\n+ DataFrame.ge : [NAME_REDACTED] for greater than inequality\n+ or equality elementwise.\n+ DataFrame.gt : [NAME_REDACTED] for strictly greater than\n+ inequality elementwise.\n+\n+ Notes\n+ -----\n+ Mismatched indices will be unioned together.\n+ `NaN` values are considered different (i.e. `NaN` != `NaN`).\n+\n+ Examples\n+ --------\n+ >>> df = pd.DataFrame({'cost': [250, 150, 100],\n+ ... 'revenue': [100, 250, 300]},\n+ ... index=['A', 'B', 'C'])\n+ >>> df\n+ cost revenue\n+ A 250 100\n+ B 150 250\n+ C 100 300\n+\n+ Comparison with a scalar, using either the operator or method:\n+\n+ >>> df <= 100\n+ cost revenue\n+ A False True\n+ B False False\n+ C True False\n+\n+ >>> df.le(100)\n+ cost revenue\n+ A False True\n+ B False False\n+ C True False\n+\n+ When `other` is a :class:`Series`, the columns of a DataFrame are aligned\n+ with the index of `other` and broadcast:\n+\n+ >>> df <= pd.Series([100, 250], index=[\"cost\", \"revenue\"])\n+ cost revenue\n+ A False True\n+ B False True\n+ C True False\n+\n+ Use the method to control the broadcast axis:\n+\n+ >>> df.le(pd.Series([100, 300], index=[\"A\", \"D\"]), axis='index')\n+ cost revenue\n+ A False True\n+ B False False\n+ C False False\n+ D False False\n+\n+ When comparing to an arbitrary sequence, the number of columns must\n+ match the number elements in `other`:\n+\n+ >>> df <= [250, 100]\n+ cost revenue\n+ A True True\n+ B True False\n+ C True False\n+\n+ Use the method to control the axis:\n+\n+ >>> df.le([250, 250, 100], axis='index')\n+ cost revenue\n+ A True True\n+ B True True\n+ C True False\n+\n+ Compare to a DataFrame of different shape.\n+\n+ >>> other = pd.DataFrame({'revenue': [300, 250, 100, 150]},\n+ ... index=['A', 'B', 'C', 'D'])\n+ >>> other\n+ revenue\n+ A 300\n+ B 250\n+ C 100\n+ D 150\n+\n+ >>> df.le(other)\n+ cost revenue\n+ A False True\n+ B False True\n+ C False False\n+ D False False\n+\n+ Compare to a MultiIndex by level.\n+\n+ >>> df_multindex = pd.DataFrame({'cost': [250, 150, 100, 150, 300, 220],\n+ ... 'revenue': [100, 250, 300, 200, 175, 225]},\n+ ... index=[['Q1', 'Q1', 'Q1', 'Q2', 'Q2', 'Q2'],\n+ ... ['A', 'B', 'C', 'A', 'B', 'C']])\n+ >>> df_multindex\n+ cost revenue\n+ Q1 A 250 100\n+ B 150 250\n+ C 100 300\n+ Q2 A 150 200\n+ B 300 175\n+ C 220 225\n+\n+ >>> df.le(df_multindex, level=1)\n+ cost revenue\n+ Q1 A True True\n+ B True True\n+ C True True\n+ Q2 A False True\n+ B True False\n+ C True False\n+ \"\"\"\n return self._flex_cmp_method(other, operator.le, axis=axis, level=level)\n \n- [USER_REDACTED](ops.make_flex_doc(\"lt\", \"dataframe\"))\n- def lt(self, other, axis: Axis = \"columns\", level=None) -> DataFrame:\n- return self._flex_cmp_method(other, operator.lt, axis=axis, level=level)\n+ def lt(self, other, axis: Axis = \"columns\", level=None) -> DataFrame:\n+ \"\"\"\n+ [NAME_REDACTED] than of dataframe and other, element-wise (binary operator `lt`).\n+\n+ Among flexible wrappers (`eq`, `ne`, `le`, `lt`, `ge`, `gt`) to comparison\n+ operators.\n+\n+ Equivalent to ``<`` with support to choose axis\n+ (rows or columns) and level for comparison.\n+\n+ Parameters\n+ ----------\n+ other : scalar, sequence, Series, or DataFrame\n+ Any single or multiple element data structure, or list-like object.\n+ axis : {0 or 'index', 1 or 'columns'}, default 'columns'\n+ Whether to compare by [NAME_REDACTED] (0 or 'index') or columns\n+ (1 or 'columns').\n+ level : int or label\n+ Broadcast across a level, matching Index values on the passed\n+ MultiIndex level.\n+\n+ Returns\n+ -------\n+ DataFrame of bool\n+ Result of the comparison.\n+\n+ See Also\n+ --------\n+ DataFrame.eq : [NAME_REDACTED] for equality elementwise.\n+ DataFrame.ne : [NAME_REDACTED] for inequality elementwise.\n+ DataFrame.le : [NAME_REDACTED] for less than inequality\n+ or equality elementwise.\n+ DataFrame.lt : [NAME_REDACTED] for strictly less than\n+ inequality elementwise.\n+ DataFrame.ge : [NAME_REDACTED] for greater than inequality\n+ or equality elementwise.\n+ DataFrame.gt : [NAME_REDACTED] for strictly greater than\n+ inequality elementwise.\n+\n+ Notes\n+ -----\n+ Mismatched indices will be unioned together.\n+ `NaN` values are considered different (i.e. `NaN` != `NaN`).\n+\n+ Examples\n+ --------\n+ >>> df = pd.DataFrame(\n+ ... {\"cost\": [250, 150, 100], \"revenue\": [100, 250, 300]},\n+ ... index=[\"A\", \"B\", \"C\"],\n+ ... )\n+ >>> df\n+ cost revenue\n+ A 250 100\n+ B 150 250\n+ C 100 300\n+\n+ Comparison with a scalar, using either the operator or method:\n+\n+ >>> df < 100\n+ cost revenue\n+ A False False\n+ B False False\n+ C False False\n+\n+ >>> df.lt(100)\n+ cost revenue\n+ A False False\n+ B False False\n+ C False False\n+\n+ When `other` is a :class:`Series`, the columns of a DataFrame are aligned\n+ with the index of `other` and broadcast:\n+\n+ >>> df < pd.Series([100, 250], index=[\"cost\", \"revenue\"])\n+ cost revenue\n+ A False True\n+ B False False\n+ C False False\n+\n+ Use the method to control the broadcast axis:\n+\n+ >>> df.lt(pd.Series([100, 300], index=[\"A\", \"D\"]), axis=\"index\")\n+ cost revenue\n+ A False False\n+ B False False\n+ C False False\n+ D False False\n+\n+ When comparing to an arbitrary sequence, the number of columns must\n+ match the number elements in `other`:\n+\n+ >>> df < [250, 100]\n+ cost revenue\n+ A False False\n+ B True False\n+ C True False\n+\n+ Use the method to control the axis:\n+\n+ >>> df.lt([250, 250, 100], axis=\"index\")\n+ cost revenue\n+ A False True\n+ B True False\n+ C False False\n+\n+ Compare to a DataFrame of different shape.\n+\n+ >>> other = pd.DataFrame(\n+ ... {\"revenue\": [300, 250, 100, 150]}, index=[\"A\", \"B\", \"C\", \"D\"]\n+ ... )\n+ >>> other\n+ revenue\n+ A 300\n+ B 250\n+ C 100\n+ D 150\n+\n+ >>> df.lt(other)\n+ cost revenue\n+ A False True\n+ B False False\n+ C False False\n+ D False False\n+\n+ Compare to a MultiIndex by level.\n+\n+ >>> df_multindex = pd.DataFrame(\n+ ... {\n+ ... \"cost\": [250, 150, 100, 150, 300, 220],\n+ ... \"revenue\": [100, 250, 300, 200, 175, 225],\n+ ... },\n+ ... index=[\n+ ... [\"Q1\", \"Q1\", \"Q1\", \"Q2\", \"Q2\", \"Q2\"],\n+ ... [\"A\", \"B\", \"C\", \"A\", \"B\", \"C\"],\n+ ... ],\n+ ... )\n+ >>> df_multindex\n+ cost revenue\n+ Q1 A 250 100\n+ B 150 250\n+ C 100 300\n+ Q2 A 150 200\n+ B 300 175\n+ C 220 225\n+\n+ >>> df.lt(df_multindex, level=1)\n+ cost revenue\n+ Q1 A False False\n+ B False False\n+ C False False\n+ Q2 A False True\n+ B True False\n+ C True False\n+ \"\"\"\n+ return self._flex_cmp_method(other, operator.lt, axis=axis, level=level)\n+\n+ def ge(self, other, axis: Axis = \"columns\", level=None) -> DataFrame:\n+ \"\"\"\n+ [NAME_REDACTED] than or equal to of dataframe and other, \\\n+ element-wise (binary operator `ge`).\n+\n+ Among flexible wrappers (`eq`, `ne`, `le`, `lt`, `ge`, `gt`) to comparison\n+ operators.\n+\n+ Equivalent to ``>=`` with support to choose axis\n+ (rows or columns) and level for comparison.\n+\n+ Parameters\n+ ----------\n+ other : scalar, sequence, Series, or DataFrame\n+ Any single or multiple element data structure, or list-like object.\n+ axis : {0 or 'index', 1 or 'columns'}, default 'columns'\n+ Whether to compare by [NAME_REDACTED] (0 or 'index') or columns\n+ (1 or 'columns').\n+ level : int or label\n+ Broadcast across a level, matching Index values on the passed\n+ MultiIndex level.\n+\n+ Returns\n+ -------\n+ DataFrame of bool\n+ Result of the comparison.\n+\n+ See Also\n+ --------\n+ DataFrame.eq : [NAME_REDACTED] for equality elementwise.\n+ DataFrame.ne : [NAME_REDACTED] for inequality elementwise.\n+ DataFrame.le : [NAME_REDACTED] for less than inequality\n+ or equality elementwise.\n+ DataFrame.lt : [NAME_REDACTED] for strictly less than\n+ inequality elementwise.\n+ DataFrame.ge : [NAME_REDACTED] for greater than inequality\n+ or equality elementwise.\n+ DataFrame.gt : [NAME_REDACTED] for strictly greater than\n+ inequality elementwise.\n+\n+ Notes\n+ -----\n+ Mismatched indices will be unioned together.\n+ `NaN` values are considered different (i.e. `NaN` != `NaN`).\n+\n+ Examples\n+ --------\n+ >>> df = pd.DataFrame({'cost': [250, 150, 100],\n+ ... 'revenue': [100, 250, 300]},\n+ ... index=['A', 'B', 'C'])\n+ >>> df\n+ cost revenue\n+ A 250 100\n+ B 150 250\n+ C 100 300\n+\n+ Comparison with a scalar, using either the operator or method:\n+\n+ >>> df >= 100\n+ cost revenue\n+ A True True\n+ B True True\n+ C True True\n+\n+ >>> df.ge(100)\n+ cost revenue\n+ A True True\n+ B True True\n+ C True True\n+\n+ When `other` is a :class:`Series`, the columns of a DataFrame are aligned\n+ with the index of `other` and broadcast:\n+\n+ >>> df >= pd.Series([100, 250], index=[\"cost\", \"revenue\"])\n+ cost revenue\n+ A True False\n+ B True True\n+ C True True\n+\n+ Use the method to control the broadcast axis:\n+\n+ >>> df.ge(pd.Series([100, 300], index=[\"A\", \"D\"]), axis='index')\n+ cost revenue\n+ A True True\n+ B False False\n+ C False False\n+ D False False\n+\n+ When comparing to an arbitrary sequence, the number of columns must\n+ match the number elements in `other`:\n+\n+ >>> df >= [250, 100]\n+ cost revenue\n+ A True True\n+ B False True\n+ C False True\n+\n+ Use the method to control the axis:\n+\n+ >>> df.ge([250, 250, 100], axis='index')\n+ cost revenue\n+ A True False\n+ B False True\n+ C True True\n+\n+ Compare to a DataFrame of different shape.\n+\n+ >>> other = pd.DataFrame({'revenue': [300, 250, 100, 150]},\n+ ... index=['A', 'B', 'C', 'D'])\n+ >>> other\n+ revenue\n+ A 300\n+ B 250\n+ C 100\n+ D 150\n+\n+ >>> df.ge(other)\n+ cost revenue\n+ A False False\n+ B False True\n+ C False True\n+ D False False\n+\n+ Compare to a MultiIndex by level.\n+\n+ >>> df_multindex = pd.DataFrame({'cost': [250, 150, 100, 150, 300, 220],\n+ ... 'revenue': [100, 250, 300, 200, 175, 225]},\n+ ... index=[['Q1', 'Q1', 'Q1', 'Q2', 'Q2', 'Q2'],\n+ ... ['A', 'B', 'C', 'A', 'B', 'C']])\n+ >>> df_multindex\n+ cost revenue\n+ Q1 A 250 100\n+ B 150 250\n+ C 100 300\n+ Q2 A 150 200\n+ B 300 175\n+ C 220 225\n+\n+ >>> df.ge(df_multindex, level=1)\n+ cost revenue\n+ Q1 A True True\n+ B True True\n+ C True True\n+ Q2 A True False\n+ B False True\n+ C False True\n+ \"\"\"\n+ return self._flex_cmp_method(other, operator.ge, axis=axis, level=level)\n+\n+ def gt(self, other, axis: Axis = \"columns\", level=None) -> DataFrame:\n+ \"\"\"\n+ [NAME_REDACTED] than of dataframe and other, element-wise (binary operator `gt`).\n+\n+ Among flexible wrappers (`eq`, `ne`, `le`, `lt`, `ge`, `gt`) to comparison\n+ operators.\n+\n+ Equivalent to ``>`` with support to choose axis\n+ (rows or columns) and level for comparison.\n+\n+ Parameters\n+ ----------\n+ other : scalar, sequence, Series, or DataFrame\n+ Any single or multiple element data structure, or list-like object.\n+ axis : {0 or 'index', 1 or 'columns'}, default 'columns'\n+ Whether to compare by [NAME_REDACTED] (0 or 'index') or columns\n+ (1 or 'columns').\n+ level : int or label\n+ Broadcast across a level, matching Index values on the passed\n+ MultiIndex level.\n+\n+ Returns\n+ -------\n+ DataFrame of bool\n+ Result of the comparison.\n+\n+ See Also\n+ --------\n+ DataFrame.eq : [NAME_REDACTED] for equality elementwise.\n+ DataFrame.ne : [NAME_REDACTED] for inequality elementwise.\n+ DataFrame.le : [NAME_REDACTED] for less than inequality\n+ or equality elementwise.\n+ DataFrame.lt : [NAME_REDACTED] for strictly less than\n+ inequality elementwise.\n+ DataFrame.ge : [NAME_REDACTED] for greater than inequality\n+ or equality elementwise.\n+ DataFrame.gt : [NAME_REDACTED] for strictly greater than\n+ inequality elementwise.\n+\n+ Notes\n+ -----\n+ Mismatched indices will be unioned together.\n+ `NaN` values are considered different (i.e. `NaN` != `NaN`).\n+\n+ Examples\n+ --------\n+ >>> df = pd.DataFrame(\n+ ... {\"cost\": [250, 150, 100], \"revenue\": [100, 250, 300]},\n+ ... index=[\"A\", \"B\", \"C\"],\n+ ... )\n+ >>> df\n+ cost revenue\n+ A 250 100\n+ B 150 250\n+ C 100 300\n+\n+ Comparison with a scalar, using either the operator or method:\n \n- [USER_REDACTED](ops.make_flex_doc(\"ge\", \"dataframe\"))\n- def ge(self, other, axis: Axis = \"columns\", level=None) -> DataFrame:\n- return self._flex_cmp_method(other, operator.ge, axis=axis, level=level)\n+ >>> df > 100\n+ cost revenue\n+ A True False\n+ B True True\n+ C False True\n \n- [USER_REDACTED](ops.make_flex_doc(\"gt\", \"dataframe\"))\n- def gt(self, other, axis: Axis = \"columns\", level=None) -> DataFrame:\n+ >>> df.gt(100)\n+ cost revenue\n+ A True False\n+ B True True\n+ C False True\n+\n+ When `other` is a :class:`Series`, the columns of a DataFrame are aligned\n+ with the index of `other` and broadcast:\n+\n+ >>> df > pd.Series([100, 250], index=[\"cost\", \"revenue\"])\n+ cost revenue\n+ A True False\n+ B True False\n+ C False True\n+\n+ Use the method to control the broadcast axis:\n+\n+ >>> df.gt(pd.Series([100, 300], index=[\"A\", \"D\"]), axis=\"index\")\n+ cost revenue\n+ A True False\n+ B False False\n+ C False False\n+ D False False\n+\n+ When comparing to an arbitrary sequence, the number of columns must\n+ match the number elements in `other`:\n+\n+ >>> df > [250, 100]\n+ cost revenue\n+ A False False\n+ B False True\n+ C False True\n+\n+ Use the method to control the axis:\n+\n+ >>> df.gt([250, 250, 100], axis=\"index\")\n+ cost revenue\n+ A False False\n+ B False False\n+ C False True\n+\n+ Compare to a DataFrame of different shape.\n+\n+ >>> other = pd.DataFrame(\n+ ... {\"revenue\": [300, 250, 100, 150]}, index=[\"A\", \"B\", \"C\", \"D\"]\n+ ... )\n+ >>> other\n+ revenue\n+ A 300\n+ B 250\n+ C 100\n+ D 150\n+\n+ >>> df.gt(other)\n+ cost revenue\n+ A False False\n+ B False False\n+ C False True\n+ D False False\n+\n+ Compare to a MultiIndex by level.\n+\n+ >>> df_multindex = pd.DataFrame(\n+ ... {\n+ ... \"cost\": [250, 150, 100, 150, 300, 220],\n+ ... \"revenue\": [100, 250, 300, 200, 175, 225],\n+ ... },\n+ ... index=[\n+ ... [\"Q1\", \"Q1\", \"Q1\", \"Q2\", \"Q2\", \"Q2\"],\n+ ... [\"A\", \"B\", \"C\", \"A\", \"B\", \"C\"],\n+ ... ],\n+ ... )\n+ >>> df_multindex\n+ cost revenue\n+ Q1 A 250 100\n+ B 150 250\n+ C 100 300\n+ Q2 A 150 200\n+ B 300 175\n+ C 220 225\n+\n+ >>> df.gt(df_multindex, level=1)\n+ cost revenue\n+ Q1 A False False\n+ B False False\n+ C False False\n+ Q2 A True False\n+ B False True\n+ C False True\n+ \"\"\"\n return self._flex_cmp_method(other, operator.gt, axis=axis, level=level)\n \n- [USER_REDACTED](ops.make_flex_doc(\"add\", \"dataframe\"))\n def add(\n self, other, axis: Axis = \"columns\", level=None, fill_value=None\n ) -> DataFrame:\n+ \"\"\"\n+ [NAME_REDACTED] of dataframe and other, element-wise (binary operator `add`).\n+\n+ Equivalent to ``dataframe + other``, but with support to substitute a\n+ fill_value for missing data in one of the inputs. With reverse version,\n+ `radd`.\n+\n+ Among flexible wrappers (`add`, `sub`, `mul`, `div`, `floordiv`, `mod`, `pow`)\n+ to arithmetic operators: `+`, `-`, `*`, `/`, `//`, `%`, `**`.\n+\n+ Parameters\n+ ----------\n+ other : scalar, sequence, Series, dict or DataFrame\n+ Any single or multiple element data structure, or list-like object.\n+ axis : {0 or 'index', 1 or 'columns'}\n+ Whether to compare by [NAME_REDACTED] (0 or 'index') or columns.\n+ (1 or 'columns'). For Series input, axis to match Series index on.\n+ level : int or label\n+ Broadcast across a level, matching Index values on the\n+ passed MultiIndex level.\n+ fill_value : float or None, default None\n+ Fill existing missing (NaN) values, and any new element needed for\n+ successful DataFrame alignment, with this value before computation.\n+ If data in both corresponding DataFrame locations is missing\n+ the result will be missing.\n+\n+ Returns\n+ -------\n+ DataFrame\n+ Result of the arithmetic operation.\n+\n+ See Also\n+ --------\n+ DataFrame.add : Add DataFrames.\n+ DataFrame.sub : [NAME_REDACTED].\n+ DataFrame.mul : [NAME_REDACTED].\n+ DataFrame.div : [NAME_REDACTED] (float division).\n+ DataFrame.truediv : [NAME_REDACTED] (float division).\n+ DataFrame.floordiv : [NAME_REDACTED] (integer division).\n+ DataFrame.mod : Calculate modulo (remainder after division).\n+ DataFrame.pow : Calculate exponential power.\n+\n+ Notes\n+ -----\n+ Mismatched indices will be unioned together.\n+\n+ Examples\n+ --------\n+ >>> df = pd.DataFrame(\n+ ... {\"angles\": [0, 3, 4], \"degrees\": [360, 180, 360]},\n+ ... index=[\"circle\", \"triangle\", \"rectangle\"],\n+ ... )\n+ >>> df\n+ angles degrees\n+ circle 0 360\n+ triangle 3 180\n+ rectangle 4 360\n+\n+ Add a scalar with operator version which return the same\n+ results.\n+\n+ >>> df + 1\n+ angles degrees\n+ circle 1 361\n+ triangle 4 181\n+ rectangle 5 361\n+\n+ >>> df.add(1)\n+ angles degrees\n+ circle 1 361\n+ triangle 4 181\n+ rectangle 5 361\n+\n+ Add a list and Series by [NAME_REDACTED]\n+\n+ >>> df + [1, 2]\n+ angles degrees\n+ circle 1 362\n+ triangle 4 182\n+ rectangle 5 362\n+\n+ >>> df.add([1, 2], axis=\"columns\")\n+ angles degrees\n+ circle 1 362\n+ triangle 4 182\n+ rectangle 5 362\n+\n+ >>> df.add(\n+ ... pd.Series([1, 1, 1], index=[\"circle\", \"triangle\", \"rectangle\"]),\n+ ... axis=\"index\",\n+ ... )\n+ angles degrees\n+ circle 1 361\n+ triangle 4 181\n+ rectangle 5 361\n+\n+ Add a dictionary by axis.\n+\n+ >>> df.add({\"angles\": 0, \"degrees\": 2})\n+ angles degrees\n+ circle 0 362\n+ triangle 3 182\n+ rectangle 4 362\n+\n+ >>> df.add({\"circle\": 0, \"triangle\": 2, \"rectangle\": 3}, axis=\"index\")\n+ angles degrees\n+ circle 0 360\n+ triangle 5 182\n+ rectangle 7 363\n+ \"\"\"\n return self._flex_arith_method(\n other, operator.add, level=level, fill_value=fill_value, axis=axis\n )\n \n- [USER_REDACTED](ops.make_flex_doc(\"radd\", \"dataframe\"))\n def radd(\n self, other, axis: Axis = \"columns\", level=None, fill_value=None\n ) -> DataFrame:\n+ \"\"\"\n+ [NAME_REDACTED] of dataframe and other, element-wise (binary operator `radd`).\n+\n+ Equivalent to ``other + dataframe``, but with support to substitute a\n+ fill_value for missing data in one of the inputs. With reverse version,\n+ `add`.\n+\n+ Among flexible wrappers (`add`, `sub`, `mul`, `div`, `floordiv`, `mod`, `pow`)\n+ to arithmetic operators: `+`, `-`, `*`, `/`, `//`, `%`, `**`.\n+\n+ Parameters\n+ ----------\n+ other : scalar, sequence, Series, dict or DataFrame\n+ Any single or multiple element data structure, or list-like object.\n+ axis : {0 or 'index', 1 or 'columns'}\n+ Whether to compare by [NAME_REDACTED] (0 or 'index') or columns.\n+ (1 or 'columns'). For Series input, axis to match Series index on.\n+ level : int or label\n+ Broadcast across a level, matching Index values on the\n+ passed MultiIndex level.\n+ fill_value : float or None, default None\n+ Fill existing missing (NaN) values, and any new element needed for\n+ successful DataFrame alignment, with this value before computation.\n+ If data in both corresponding DataFrame locations is missing\n+ the result will be missing.\n+\n+ Returns\n+ -------\n+ DataFrame\n+ Result of the arithmetic operation.\n+\n+ See Also\n+ --------\n+ DataFrame.add : Add DataFrames.\n+ DataFrame.sub : [NAME_REDACTED].\n+ DataFrame.mul : [NAME_REDACTED].\n+ DataFrame.div : [NAME_REDACTED] (float division).\n+ DataFrame.truediv : [NAME_REDACTED] (float division).\n+ DataFrame.floordiv : [NAME_REDACTED] (integer division).\n+ DataFrame.mod : Calculate modulo (remainder after division).\n+ DataFrame.pow : Calculate exponential power.\n+\n+ Notes\n+ -----\n+ Mismatched indices will be unioned together.\n+\n+ Examples\n+ --------\n+ >>> df = pd.DataFrame(\n+ ... {\"angles\": [0, 3, 4], \"degrees\": [360, 180, 360]},\n+ ... index=[\"circle\", \"triangle\", \"rectangle\"],\n+ ... )\n+ >>> df\n+ angles degrees\n+ circle 0 360\n+ triangle 3 180\n+ rectangle 4 360\n+\n+ Add a scalar with operator version which return the same\n+ results.\n+\n+ >>> 1 + df\n+ angles degrees\n+ circle 1 361\n+ triangle 4 181\n+ rectangle 5 361\n+\n+ >>> df.radd(1)\n+ angles degrees\n+ circle 1 361\n+ triangle 4 181\n+ rectangle 5 361\n+\n+ Add a list and Series by [NAME_REDACTED]\n+\n+ >>> [1, 2] + df\n+ angles degrees\n+ circle 1 362\n+ triangle 4 182\n+ rectangle 5 362\n+\n+ >>> df.radd([1, 2], axis=\"columns\")\n+ angles degrees\n+ circle 1 362\n+ triangle 4 182\n+ rectangle 5 362\n+\n+ >>> df.radd(\n+ ... pd.Series([1, 1, 1], index=[\"circle\", \"triangle\", \"rectangle\"]),\n+ ... axis=\"index\",\n+ ... )\n+ angles degrees\n+ circle 1 361\n+ triangle 4 181\n+ rectangle 5 361\n+\n+ Add a dictionary by axis.\n+\n+ >>> df.radd({\"angles\": 0, \"degrees\": 2})\n+ angles degrees\n+ circle 0 362\n+ triangle 3 182\n+ rectangle 4 362\n+\n+ >>> df.radd({\"circle\": 0, \"triangle\": 2, \"rectangle\": 3}, axis=\"index\")\n+ angles degrees\n+ circle 0 360\n+ triangle 5 182\n+ rectangle 7 363\n+ \"\"\"\n return self._flex_arith_method(\n other, roperator.radd, level=level, fill_value=fill_value, axis=axis\n )\n \n- [USER_REDACTED](ops.make_flex_doc(\"sub\", \"dataframe\"))\n def sub(\n self, other, axis: Axis = \"columns\", level=None, fill_value=None\n ) -> DataFrame:\n+ \"\"\"\n+ [NAME_REDACTED] of dataframe and other, element-wise (binary operator `sub`).\n+\n+ Equivalent to ``dataframe - other``, but with support to substitute a\n+ fill_value for missing data in one of the inputs. With reverse version, `rsub`.\n+\n+ Among flexible wrappers (`add`, `sub`, `mul`, `div`, `floordiv`, `mod`, `pow`)\n+ to arithmetic operators: `+`, `-`, `*`, `/`, `//`, `%`, `**`.\n+\n+ Parameters\n+ ----------\n+ other : scalar, sequence, Series, dict or DataFrame\n+ Any single or multiple element data structure, or list-like object.\n+ axis : {0 or 'index', 1 or 'columns'}\n+ Whether to compare by [NAME_REDACTED] (0 or 'index') or columns.\n+ (1 or 'columns'). For Series input, axis to match Series index on.\n+ level : int or label\n+ Broadcast across a level, matching Index values on the\n+ passed MultiIndex level.\n+ fill_value : float or None, default None\n+ Fill existing missing (NaN) values, and any new element needed for\n+ successful DataFrame alignment, with this value before computation.\n+ If data in both corresponding DataFrame locations is missing\n+ the result will be missing.\n+\n+ Returns\n+ -------\n+ DataFrame\n+ Result of the arithmetic operation.\n+\n+ See Also\n+ --------\n+ DataFrame.add : Add DataFrames.\n+ DataFrame.sub : [NAME_REDACTED].\n+ DataFrame.mul : [NAME_REDACTED].\n+ DataFrame.div : [NAME_REDACTED] (float division).\n+ DataFrame.truediv : [NAME_REDACTED] (float division).\n+ DataFrame.floordiv : [NAME_REDACTED] (integer division).\n+ DataFrame.mod : Calculate modulo (remainder after division).\n+ DataFrame.pow : Calculate exponential power.\n+\n+ Notes\n+ -----\n+ Mismatched indices will be unioned together.\n+\n+ Examples\n+ --------\n+ >>> df = pd.DataFrame(\n+ ... {\"angles\": [0, 3, 4], \"degrees\": [360, 180, 360]},\n+ ... index=[\"circle\", \"triangle\", \"rectangle\"],\n+ ... )\n+ >>> df\n+ angles degrees\n+ circle 0 360\n+ triangle 3 180\n+ rectangle 4 360\n+\n+ Subtract a scalar with operator version which return the same\n+ results.\n+\n+ >>> df - 1\n+ angles degrees\n+ circle -1 359\n+ triangle 2 179\n+ rectangle 3 359\n+\n+ >>> df.sub(1)\n+ angles degrees\n+ circle -1 359\n+ triangle 2 179\n+ rectangle 3 359\n+\n+ Subtract a list and Series by [NAME_REDACTED]\n+\n+ >>> df - [1, 2]\n+ angles degrees\n+ circle -1 358\n+ triangle 2 178\n+ rectangle 3 358\n+\n+ >>> df.sub([1, 2], axis=\"columns\")\n+ angles degrees\n+ circle -1 358\n+ triangle 2 178\n+ rectangle 3 358\n+\n+ >>> df.sub(\n+ ... pd.Series([1, 1, 1], index=[\"circle\", \"triangle\", \"rectangle\"]),\n+ ... axis=\"index\",\n+ ... )\n+ angles degrees\n+ circle -1 359\n+ triangle 2 179\n+ rectangle 3 359\n+\n+ Subtract a dictionary by axis.\n+\n+ >>> df.sub({\"angles\": 0, \"degrees\": 2})\n+ angles degrees\n+ circle 0 358\n+ triangle 3 178\n+ rectangle 4 358\n+\n+ >>> df.sub({\"circle\": 0, \"triangle\": 2, \"rectangle\": 3}, axis=\"index\")\n+ angles degrees\n+ circle 0 360\n+ triangle 1 178\n+ rectangle 1 357\n+ \"\"\"\n return self._flex_arith_method(\n other, operator.sub, level=level, fill_value=fill_value, axis=axis\n )\n \n- subtract = sub\n+ subtract = sub\n+\n+ def rsub(\n+ self, other, axis: Axis = \"columns\", level=None, fill_value=None\n+ ) -> DataFrame:\n+ \"\"\"\n+ [NAME_REDACTED] of dataframe and other, element-wise (binary operator `rsub`).\n+\n+ Equivalent to ``other - dataframe``, but with support to substitute a\n+ fill_value for missing data in one of the inputs. With reverse version, `sub`.\n+\n+ Among flexible wrappers (`add`, `sub`, `mul`, `div`, `floordiv`, `mod`, `pow`)\n+ to arithmetic operators: `+`, `-`, `*`, `/`, `//`, `%`, `**`.\n+\n+ Parameters\n+ ----------\n+ other : scalar, sequence, Series, dict or DataFrame\n+ Any single or multiple element data structure, or list-like object.\n+ axis : {0 or 'index', 1 or 'columns'}\n+ Whether to compare by [NAME_REDACTED] (0 or 'index') or columns.\n+ (1 or 'columns'). For Series input, axis to match Series index on.\n+ level : int or label\n+ Broadcast across a level, matching Index values on the\n+ passed MultiIndex level.\n+ fill_value : float or None, default None\n+ Fill existing missing (NaN) values, and any new element needed for\n+ successful DataFrame alignment, with this value before computation.\n+ If data in both corresponding DataFrame locations is missing\n+ the result will be missing.\n+\n+ Returns\n+ -------\n+ DataFrame\n+ Result of the arithmetic operation.\n+\n+ See Also\n+ --------\n+ DataFrame.add : Add DataFrames.\n+ DataFrame.sub : [NAME_REDACTED].\n+ DataFrame.mul : [NAME_REDACTED].\n+ DataFrame.div : [NAME_REDACTED] (float division).\n+ DataFrame.truediv : [NAME_REDACTED] (float division).\n+ DataFrame.floordiv : [NAME_REDACTED] (integer division).\n+ DataFrame.mod : Calculate modulo (remainder after division).\n+ DataFrame.pow : Calculate exponential power.\n+\n+ Notes\n+ -----\n+ Mismatched indices will be unioned together.\n+\n+ Examples\n+ --------\n+ >>> df = pd.DataFrame(\n+ ... {\"angles\": [0, 3, 4], \"degrees\": [360, 180, 360]},\n+ ... index=[\"circle\", \"triangle\", \"rectangle\"],\n+ ... )\n+ >>> df\n+ angles degrees\n+ circle 0 360\n+ triangle 3 180\n+ rectangle 4 360\n+\n+ Subtract by a scalar with operator version which return the same\n+ results.\n+\n+ >>> 1 - df\n+ angles degrees\n+ circle 1 -359\n+ triangle -2 -179\n+ rectangle -3 -359\n+\n+ >>> df.rsub(1)\n+ angles degrees\n+ circle 1 -359\n+ triangle -2 -179\n+ rectangle -3 -359\n+\n+ Subtract by a list and Series by [NAME_REDACTED]\n+\n+ >>> [1, 2] - df\n+ angles degrees\n+ circle 1 -358\n+ triangle -2 -178\n+ rectangle -3 -358\n+\n+ >>> df.rsub([1, 2], axis=\"columns\")\n+ angles degrees\n+ circle 1 -358\n+ triangle -2 -178\n+ rectangle -3 -358\n+\n+ >>> df.rsub(\n+ ... pd.Series([1, 1, 1], index=[\"circle\", \"triangle\", \"rectangle\"]),\n+ ... axis=\"index\",\n+ ... )\n+ angles degrees\n+ circle 1 -359\n+ triangle -2 -179\n+ rectangle -3 -359\n+\n+ Subtract by a dictionary by axis.\n+\n+ >>> df.rsub({\"angles\": 0, \"degrees\": 2})\n+ angles degrees\n+ circle 0 -358\n+ triangle -3 -178\n+ rectangle -4 -358\n+\n+ >>> df.rsub({\"circle\": 0, \"triangle\": 2, \"rectangle\": 3}, axis=\"index\")\n+ angles degrees\n+ circle 0 -360\n+ triangle -1 -178\n+ rectangle -1 -357\n+ \"\"\"\n+ return self._flex_arith_method(\n+ other, roperator.rsub, level=level, fill_value=fill_value, axis=axis\n+ )\n+\n+ def mul(\n+ self, other, axis: Axis = \"columns\", level=None, fill_value=None\n+ ) -> DataFrame:\n+ \"\"\"\n+ [NAME_REDACTED] of dataframe and other, \\\n+ element-wise (binary operator `mul`).\n+\n+ Equivalent to ``dataframe * other``, but with support to substitute a\n+ fill_value for missing data in one of the inputs. With reverse version,\n+ `rmul`.\n+\n+ Among flexible wrappers (`add`, `sub`, `mul`, `div`, `floordiv`, `mod`, `pow`)\n+ to arithmetic operators: `+`, `-`, `*`, `/`, `//`, `%`, `**`.\n+\n+ Parameters\n+ ----------\n+ other : scalar, sequence, Series, dict or DataFrame\n+ Any single or multiple element data structure, or list-like object.\n+ axis : {0 or 'index', 1 or 'columns'}\n+ Whether to compare by [NAME_REDACTED] (0 or 'index') or columns.\n+ (1 or 'columns'). For Series input, axis to match Series index on.\n+ level : int or label\n+ Broadcast across a level, matching Index values on the\n+ passed MultiIndex level.\n+ fill_value : float or None, default None\n+ Fill existing missing (NaN) values, and any new element needed for\n+ successful DataFrame alignment, with this value before computation.\n+ If data in both corresponding DataFrame locations is missing\n+ the result will be missing.\n+\n+ Returns\n+ -------\n+ DataFrame\n+ Result of the arithmetic operation.\n+\n+ See Also\n+ --------\n+ DataFrame.add : Add DataFrames.\n+ DataFrame.sub : [NAME_REDACTED].\n+ DataFrame.mul : [NAME_REDACTED].\n+ DataFrame.div : [NAME_REDACTED] (float division).\n+ DataFrame.truediv : [NAME_REDACTED] (float division).\n+ DataFrame.floordiv : [NAME_REDACTED] (integer division).\n+ DataFrame.mod : Calculate modulo (remainder after division).\n+ DataFrame.pow : Calculate exponential power.\n+\n+ Notes\n+ -----\n+ Mismatched indices will be unioned together.\n+\n+ Examples\n+ --------\n+ >>> df = pd.DataFrame(\n+ ... {\"angles\": [0, 3, 4], \"degrees\": [360, 180, 360]},\n+ ... index=[\"circle\", \"triangle\", \"rectangle\"],\n+ ... )\n+ >>> df\n+ angles degrees\n+ circle 0 360\n+ triangle 3 180\n+ rectangle 4 360\n+\n+ Multiply a scalar with operator version which return the same\n+ results.\n+\n+ >>> df * 2\n+ angles degrees\n+ circle 0 720\n+ triangle 6 360\n+ rectangle 8 720\n+\n+ >>> df.mul(2)\n+ angles degrees\n+ circle 0 720\n+ triangle 6 360\n+ rectangle 8 720\n+\n+ Multiply a list and Series by [NAME_REDACTED]\n+\n+ >>> df * [1, 2]\n+ angles degrees\n+ circle 0 720\n+ triangle 3 360\n+ rectangle 4 720\n+\n+ >>> df.mul([1, 2], axis=\"columns\")\n+ angles degrees\n+ circle 0 720\n+ triangle 3 360\n+ rectangle 4 720\n+\n+ >>> df.mul(\n+ ... pd.Series([1, 2, 3], index=[\"circle\", \"triangle\", \"rectangle\"]),\n+ ... axis=\"index\",\n+ ... )\n+ angles degrees\n+ circle 0 360\n+ triangle 6 360\n+ rectangle 12 1080\n \n- [USER_REDACTED](ops.make_flex_doc(\"rsub\", \"dataframe\"))\n- def rsub(\n- self, other, axis: Axis = \"columns\", level=None, fill_value=None\n- ) -> DataFrame:\n- return self._flex_arith_method(\n- other, roperator.rsub, level=level, fill_value=fill_value, axis=axis\n- )\n+ Multiply a dictionary by axis.\n \n- [USER_REDACTED](ops.make_flex_doc(\"mul\", \"dataframe\"))\n- def mul(\n- self, other, axis: Axis = \"columns\", level=None, fill_value=None\n- ) -> DataFrame:\n+ >>> df.mul({\"angles\": 0, \"degrees\": 2})\n+ angles degrees\n+ circle 0 720\n+ triangle 0 360\n+ rectangle 0 720\n+\n+ >>> df.mul({\"circle\": 0, \"triangle\": 2, \"rectangle\": 3}, axis=\"index\")\n+ angles degrees\n+ circle 0 0\n+ triangle 6 360\n+ rectangle 12 1080\n+ \"\"\"\n return self._flex_arith_method(\n other, operator.mul, level=level, fill_value=fill_value, axis=axis\n )\n \n multiply = mul\n \n- [USER_REDACTED](ops.make_flex_doc(\"rmul\", \"dataframe\"))\n def rmul(\n self, other, axis: Axis = \"columns\", level=None, fill_value=None\n ) -> DataFrame:\n+ \"\"\"\n+ [NAME_REDACTED] of dataframe and other, \\\n+ element-wise (binary operator `rmul`).\n+\n+ Equivalent to ``other * dataframe``, but with support to substitute a\n+ fill_value for missing data in one of the inputs. With reverse version,\n+ `mul`.\n+\n+ Among flexible wrappers (`add`, `sub`, `mul`, `div`, `floordiv`, `mod`, `pow`)\n+ to arithmetic operators: `+`, `-`, `*`, `/`, `//`, `%`, `**`.\n+\n+ Parameters\n+ ----------\n+ other : scalar, sequence, Series, dict or DataFrame\n+ Any single or multiple element data structure, or list-like object.\n+ axis : {0 or 'index', 1 or 'columns'}\n+ Whether to compare by [NAME_REDACTED] (0 or 'index') or columns.\n+ (1 or 'columns'). For Series input, axis to match Series index on.\n+ level : int or label\n+ Broadcast across a level, matching Index values on the\n+ passed MultiIndex level.\n+ fill_value : float or None, default None\n+ Fill existing missing (NaN) values, and any new element needed for\n+ successful DataFrame alignment, with this value before computation.\n+ If data in both corresponding DataFrame locations is missing\n+ the result will be missing.\n+\n+ Returns\n+ -------\n+ DataFrame\n+ Result of the arithmetic operation.\n+\n+ See Also\n+ --------\n+ DataFrame.add : Add DataFrames.\n+ DataFrame.sub : [NAME_REDACTED].\n+ DataFrame.mul : [NAME_REDACTED].\n+ DataFrame.div : [NAME_REDACTED] (float division).\n+ DataFrame.truediv : [NAME_REDACTED] (float division).\n+ DataFrame.floordiv : [NAME_REDACTED] (integer division).\n+ DataFrame.mod : Calculate modulo (remainder after division).\n+ DataFrame.pow : Calculate exponential power.\n+\n+ Notes\n+ -----\n+ Mismatched indices will be unioned together.\n+\n+ Examples\n+ --------\n+ >>> df = pd.DataFrame({'angles': [0, 3, 4],\n+ ... 'degrees': [360, 180, 360]},\n+ ... index=['circle', 'triangle', 'rectangle'])\n+ >>> df\n+ angles degrees\n+ circle 0 360\n+ triangle 3 180\n+ rectangle 4 360\n+\n+ Multiply by a scalar.\n+\n+ >>> 2 * df\n+ angles degrees\n+ circle 0 720\n+ triangle 6 360\n+ rectangle 8 720\n+\n+ >>> df.rmul(2)\n+ angles degrees\n+ circle 0 720\n+ triangle 6 360\n+ rectangle 8 720\n+\n+ Multiply by a list and Series.\n+\n+ >>> [1, 2] * df\n+ angles degrees\n+ circle 0 720\n+ triangle 3 360\n+ rectangle 4 720\n+\n+ >>> df.rmul([1, 2], axis='columns')\n+ angles degrees\n+ circle 0 720\n+ triangle 3 360\n+ rectangle 4 720\n+\n+ >>> df.rmul(pd.Series([1, 2, 3], index=['circle', 'triangle', 'rectangle']),\n+ ... axis='index')\n+ angles degrees\n+ circle 0 360\n+ triangle 6 360\n+ rectangle 12 1080\n+ \"\"\"\n return self._flex_arith_method(\n other, roperator.rmul, level=level, fill_value=fill_value, axis=axis\n )\n \n- [USER_REDACTED](ops.make_flex_doc(\"truediv\", \"dataframe\"))\n def truediv(\n self, other, axis: Axis = \"columns\", level=None, fill_value=None\n ) -> DataFrame:\n+ \"\"\"\n+ [NAME_REDACTED] division of dataframe and other, \\\n+ element-wise (binary operator `truediv`).\n+\n+ Equivalent to ``dataframe / other``, but with support to substitute a\n+ fill_value for missing data in one of the inputs. With reverse version,\n+ `rtruediv`.\n+\n+ Among flexible wrappers (`add`, `sub`, `mul`, `div`, `floordiv`, `mod`, `pow`)\n+ to arithmetic operators: `+`, `-`, `*`, `/`, `//`, `%`, `**`.\n+\n+ Parameters\n+ ----------\n+ other : scalar, sequence, Series, dict or DataFrame\n+ Any single or multiple element data structure, or list-like object.\n+ axis : {0 or 'index', 1 or 'columns'}\n+ Whether to compare by [NAME_REDACTED] (0 or 'index') or columns.\n+ (1 or 'columns'). For Series input, axis to match Series index on.\n+ level : int or label\n+ Broadcast across a level, matching Index values on the\n+ passed MultiIndex level.\n+ fill_value : float or None, default None\n+ Fill existing missing (NaN) values, and any new element needed for\n+ successful DataFrame alignment, with this value before computation.\n+ If data in both corresponding DataFrame locations is missing\n+ the result will be missing.\n+\n+ Returns\n+ -------\n+ DataFrame\n+ Result of the arithmetic operation.\n+\n+ See Also\n+ --------\n+ DataFrame.add : Add DataFrames.\n+ DataFrame.sub : [NAME_REDACTED].\n+ DataFrame.mul : [NAME_REDACTED].\n+ DataFrame.div : [NAME_REDACTED] (float division).\n+ DataFrame.truediv : [NAME_REDACTED] (float division).\n+ DataFrame.floordiv : [NAME_REDACTED] (integer division).\n+ DataFrame.mod : Calculate modulo (remainder after division).\n+ DataFrame.pow : Calculate exponential power.\n+\n+ Notes\n+ -----\n+ Mismatched indices will be unioned together.\n+\n+ Examples\n+ --------\n+ >>> df = pd.DataFrame({'angles': [0, 3, 4],\n+ ... 'degrees': [360, 180, 360]},\n+ ... index=['circle', 'triangle', 'rectangle'])\n+ >>> df\n+ angles degrees\n+ circle 0 360\n+ triangle 3 180\n+ rectangle 4 360\n+\n+ Divide by a scalar.\n+\n+ >>> df / 2\n+ angles degrees\n+ circle 0.0 180.0\n+ triangle 1.5 90.0\n+ rectangle 2.0 180.0\n+\n+ >>> df.truediv(2)\n+ angles degrees\n+ circle 0.0 180.0\n+ triangle 1.5 90.0\n+ rectangle 2.0 180.0\n+\n+ Divide by a list and Series.\n+\n+ >>> df / [1, 2]\n+ angles degrees\n+ circle 0.0 180.0\n+ triangle 3.0 90.0\n+ rectangle 4.0 180.0\n+\n+ >>> df.truediv([1, 2], axis='columns')\n+ angles degrees\n+ circle 0.0 180.0\n+ triangle 3.0 90.0\n+ rectangle 4.0 180.0\n+\n+ >>> df.truediv(pd.Series([1, 2, 3], index=['circle', 'triangle', 'rectangle']),\n+ ... axis='index')\n+ angles degrees\n+ circle 0.000000 360.0\n+ triangle 1.500000 90.0\n+ rectangle 1.333333 120.0\n+\n+ Divide by a dictionary by axis.\n+\n+ >>> df.truediv({'angles': 2, 'degrees': 3})\n+ angles degrees\n+ circle 0.0 120.0\n+ triangle 1.5 60.0\n+ rectangle 2.0 120.0\n+\n+ >>> df.truediv({'circle': 1, 'triangle': 2, 'rectangle': 3}, axis='index')\n+ angles degrees\n+ circle 0.000000 360.0\n+ triangle 1.500000 90.0\n+ rectangle 1.333333 120.0\n+ \"\"\"\n return self._flex_arith_method(\n other, operator.truediv, level=level, fill_value=fill_value, axis=axis\n )\n \n div = truediv\n divide = truediv\n \n- [USER_REDACTED](ops.make_flex_doc(\"rtruediv\", \"dataframe\"))\n def rtruediv(\n self, other, axis: Axis = \"columns\", level=None, fill_value=None\n ) -> DataFrame:\n+ \"\"\"\n+ [NAME_REDACTED] division of dataframe and other, \\\n+ element-wise (binary operator `rtruediv`).\n+\n+ Equivalent to ``other / dataframe``, but with support to substitute a\n+ fill_value for missing data in one of the inputs. With reverse version,\n+ `truediv`.\n+\n+ Among flexible wrappers (`add`, `sub`, `mul`, `div`, `floordiv`, `mod`, `pow`)\n+ to arithmetic operators: `+`, `-`, `*`, `/`, `//`, `%`, `**`.\n+\n+ Parameters\n+ ----------\n+ other : scalar, sequence, Series, dict or DataFrame\n+ Any single or multiple element data structure, or list-like object.\n+ axis : {0 or 'index', 1 or 'columns'}\n+ Whether to compare by [NAME_REDACTED] (0 or 'index') or columns.\n+ (1 or 'columns'). For Series input, axis to match Series index on.\n+ level : int or label\n+ Broadcast across a level, matching Index values on the\n+ passed MultiIndex level.\n+ fill_value : float or None, default None\n+ Fill existing missing (NaN) values, and any new element needed for\n+ successful DataFrame alignment, with this value before computation.\n+ If data in both corresponding DataFrame locations is missing\n+ the result will be missing.\n+\n+ Returns\n+ -------\n+ DataFrame\n+ Result of the arithmetic operation.\n+\n+ See Also\n+ --------\n+ DataFrame.add : Add DataFrames.\n+ DataFrame.sub : [NAME_REDACTED].\n+ DataFrame.mul : [NAME_REDACTED].\n+ DataFrame.div : [NAME_REDACTED] (float division).\n+ DataFrame.truediv : [NAME_REDACTED] (float division).\n+ DataFrame.floordiv : [NAME_REDACTED] (integer division).\n+ DataFrame.mod : Calculate modulo (remainder after division).\n+ DataFrame.pow : Calculate exponential power.\n+\n+ Notes\n+ -----\n+ Mismatched indices will be unioned together.\n+\n+ Examples\n+ --------\n+ >>> df = pd.DataFrame({'angles': [0, 3, 4],\n+ ... 'degrees': [360, 180, 360]},\n+ ... index=['circle', 'triangle', 'rectangle'])\n+ >>> df\n+ angles degrees\n+ circle 0 360\n+ triangle 3 180\n+ rectangle 4 360\n+\n+ Divide a scalar.\n+\n+ >>> 1 / df\n+ angles degrees\n+ circle inf 0.002778\n+ triangle 0.333333 0.005556\n+ rectangle 0.250000 0.002778\n+\n+ >>> df.rtruediv(1)\n+ angles degrees\n+ circle inf 0.002778\n+ triangle 0.333333 0.005556\n+ rectangle 0.250000 0.002778\n+\n+ Divide a list.\n+\n+ >>> [1, 2] / df\n+ angles degrees\n+ circle inf 0.005556\n+ triangle 0.333333 0.011111\n+ rectangle 0.250000 0.005556\n+\n+ >>> df.rtruediv([1, 2], axis='columns')\n+ angles degrees\n+ circle inf 0.005556\n+ triangle 0.333333 0.011111\n+ rectangle 0.250000 0.005556\n+ \"\"\"\n return self._flex_arith_method(\n other, roperator.rtruediv, level=level, fill_value=fill_value, axis=axis\n )\n \n rdiv = rtruediv\n \n- [USER_REDACTED](ops.make_flex_doc(\"floordiv\", \"dataframe\"))\n def floordiv(\n self, other, axis: Axis = \"columns\", level=None, fill_value=None\n ) -> DataFrame:\n+ \"\"\"\n+ [NAME_REDACTED] division of dataframe and other, \\\n+ element-wise (binary operator `floordiv`).\n+\n+ Equivalent to ``dataframe // other``, but with support to substitute a\n+ fill_value for missing data in one of the inputs. With reverse version,\n+ `rfloordiv`.\n+\n+ Among flexible wrappers (`add`, `sub`, `mul`, `div`, `floordiv`, `mod`, `pow`)\n+ to arithmetic operators: `+`, `-`, `*`, `/`, `//`, `%`, `**`.\n+\n+ Parameters\n+ ----------\n+ other : scalar, sequence, Series, dict or DataFrame\n+ Any single or multiple element data structure, or list-like object.\n+ axis : {0 or 'index', 1 or 'columns'}\n+ Whether to compare by [NAME_REDACTED] (0 or 'index') or columns.\n+ (1 or 'columns'). For Series input, axis to match Series index on.\n+ level : int or label\n+ Broadcast across a level, matching Index values on the\n+ passed MultiIndex level.\n+ fill_value : float or None, default None\n+ Fill existing missing (NaN) values, and any new element needed for\n+ successful DataFrame alignment, with this value before computation.\n+ If data in both corresponding DataFrame locations is missing\n+ the result will be missing.\n+\n+ Returns\n+ -------\n+ DataFrame\n+ Result of the arithmetic operation.\n+\n+ See Also\n+ --------\n+ DataFrame.add : Add DataFrames.\n+ DataFrame.sub : [NAME_REDACTED].\n+ DataFrame.mul : [NAME_REDACTED].\n+ DataFrame.div : [NAME_REDACTED] (float division).\n+ DataFrame.truediv : [NAME_REDACTED] (float division).\n+ DataFrame.floordiv : [NAME_REDACTED] (integer division).\n+ DataFrame.mod : Calculate modulo (remainder after division).\n+ DataFrame.pow : Calculate exponential power.\n+\n+ Notes\n+ -----\n+ Mismatched indices will be unioned together.\n+\n+ Examples\n+ --------\n+ >>> df = pd.DataFrame({'angles': [0, 3, 4],\n+ ... 'degrees': [360, 180, 360]},\n+ ... index=['circle', 'triangle', 'rectangle'])\n+ >>> df\n+ angles degrees\n+ circle 0 360\n+ triangle 3 180\n+ rectangle 4 360\n+\n+ Divide by a scalar.\n+\n+ >>> df // 2\n+ angles degrees\n+ circle 0 180\n+ triangle 1 90\n+ rectangle 2 180\n+\n+ >>> df.floordiv(2)\n+ angles degrees\n+ circle 0 180\n+ triangle 1 90\n+ rectangle 2 180\n+\n+ Divide by a list and Series.\n+\n+ >>> df // [1, 2]\n+ angles degrees\n+ circle 0 180\n+ triangle 3 90\n+ rectangle 4 180\n+\n+ >>> df.floordiv([1, 2], axis='columns')\n+ angles degrees\n+ circle 0 180\n+ triangle 3 90\n+ rectangle 4 180\n+ \"\"\"\n return self._flex_arith_method(\n other, operator.floordiv, level=level, fill_value=fill_value, axis=axis\n )\n \n- [USER_REDACTED](ops.make_flex_doc(\"rfloordiv\", \"dataframe\"))\n def rfloordiv(\n self, other, axis: Axis = \"columns\", level=None, fill_value=None\n ) -> DataFrame:\n+ \"\"\"\n+ [NAME_REDACTED] division of dataframe and other, \\\n+ element-wise (binary operator `rfloordiv`).\n+\n+ Equivalent to ``other // dataframe``, but with support to substitute a\n+ fill_value for missing data in one of the inputs. With reverse version,\n+ `floordiv`.\n+\n+ Among flexible wrappers (`add`, `sub`, `mul`, `div`, `floordiv`, `mod`, `pow`)\n+ to arithmetic operators: `+`, `-`, `*`, `/`, `//`, `%`, `**`.\n+\n+ Parameters\n+ ----------\n+ other : scalar, sequence, Series, dict or DataFrame\n+ Any single or multiple element data structure, or list-like object.\n+ axis : {0 or 'index', 1 or 'columns'}\n+ Whether to compare by [NAME_REDACTED] (0 or 'index') or columns.\n+ (1 or 'columns'). For Series input, axis to match Series index on.\n+ level : int or label\n+ Broadcast across a level, matching Index values on the\n+ passed MultiIndex level.\n+ fill_value : float or None, default None\n+ Fill existing missing (NaN) values, and any new element needed for\n+ successful DataFrame alignment, with this value before computation.\n+ If data in both corresponding DataFrame locations is missing\n+ the result will be missing.\n+\n+ Returns\n+ -------\n+ DataFrame\n+ Result of the arithmetic operation.\n+\n+ See Also\n+ --------\n+ DataFrame.add : Add DataFrames.\n+ DataFrame.sub : [NAME_REDACTED].\n+ DataFrame.mul : [NAME_REDACTED].\n+ DataFrame.div : [NAME_REDACTED] (float division).\n+ DataFrame.truediv : [NAME_REDACTED] (float division).\n+ DataFrame.floordiv : [NAME_REDACTED] (integer division).\n+ DataFrame.mod : Calculate modulo (remainder after division).\n+ DataFrame.pow : Calculate exponential power.\n+\n+ Notes\n+ -----\n+ Mismatched indices will be unioned together.\n+\n+ Examples\n+ --------\n+ >>> df = pd.DataFrame({'angles': [0, 3, 4],\n+ ... 'degrees': [360, 180, 360]},\n+ ... index=['circle', 'triangle', 'rectangle'])\n+ >>> df\n+ angles degrees\n+ circle 0 360\n+ triangle 3 180\n+ rectangle 4 360\n+\n+ Divide a scalar.\n+\n+ >>> 10 // df\n+ angles degrees\n+ circle inf 0.0\n+ triangle 3.0 0.0\n+ rectangle 2.0 0.0\n+\n+ >>> df.rfloordiv(10)\n+ angles degrees\n+ circle inf 0.0\n+ triangle 3.0 0.0\n+ rectangle 2.0 0.0\n+\n+ Divide a list.\n+\n+ >>> [10, 20] // df\n+ angles degrees\n+ circle inf 0.0\n+ triangle 3.0 0.0\n+ rectangle 2.0 0.0\n+\n+ >>> df.rfloordiv([10, 20], axis='columns')\n+ angles degrees\n+ circle inf 0.0\n+ triangle 3.0 0.0\n+ rectangle 2.0 0.0\n+ \"\"\"\n return self._flex_arith_method(\n other, roperator.rfloordiv, level=level, fill_value=fill_value, axis=axis\n )\n \n- [USER_REDACTED](ops.make_flex_doc(\"mod\", \"dataframe\"))\n def mod(\n self, other, axis: Axis = \"columns\", level=None, fill_value=None\n ) -> DataFrame:\n+ \"\"\"\n+ [NAME_REDACTED] of dataframe and other, element-wise (binary operator `mod`).\n+\n+ Equivalent to ``dataframe % other``, but with support to substitute a\n+ fill_value for missing data in one of the inputs. With reverse version,\n+ `rmod`.\n+\n+ Among flexible wrappers (`add`, `sub`, `mul`, `div`, `floordiv`, `mod`, `pow`)\n+ to arithmetic operators: `+`, `-`, `*`, `/`, `//`, `%`, `**`.\n+\n+ Parameters\n+ ----------\n+ other : scalar, sequence, Series, dict or DataFrame\n+ Any single or multiple element data structure, or list-like object.\n+ axis : {0 or 'index', 1 or 'columns'}\n+ Whether to compare by [NAME_REDACTED] (0 or 'index') or columns.\n+ (1 or 'columns'). For Series input, axis to match Series index on.\n+ level : int or label\n+ Broadcast across a level, matching Index values on the\n+ passed MultiIndex level.\n+ fill_value : float or None, default None\n+ Fill existing missing (NaN) values, and any new element needed for\n+ successful DataFrame alignment, with this value before computation.\n+ If data in both corresponding DataFrame locations is missing\n+ the result will be missing.\n+\n+ Returns\n+ -------\n+ DataFrame\n+ Result of the arithmetic operation.\n+\n+ See Also\n+ --------\n+ DataFrame.add : Add DataFrames.\n+ DataFrame.sub : [NAME_REDACTED].\n+ DataFrame.mul : [NAME_REDACTED].\n+ DataFrame.div : [NAME_REDACTED] (float division).\n+ DataFrame.truediv : [NAME_REDACTED] (float division).\n+ DataFrame.floordiv : [NAME_REDACTED] (integer division).\n+ DataFrame.mod : Calculate modulo (remainder after division).\n+ DataFrame.pow : Calculate exponential power.\n+\n+ Notes\n+ -----\n+ Mismatched indices will be unioned together.\n+\n+ Examples\n+ --------\n+ >>> df = pd.DataFrame(\n+ ... {\"angles\": [0, 3, 4], \"degrees\": [360, 180, 360]},\n+ ... index=[\"circle\", \"triangle\", \"rectangle\"],\n+ ... )\n+ >>> df\n+ angles degrees\n+ circle 0 360\n+ triangle 3 180\n+ rectangle 4 360\n+\n+ Calculate modulo with a scalar.\n+\n+ >>> df % 2\n+ angles degrees\n+ circle 0 0\n+ triangle 1 0\n+ rectangle 0 0\n+\n+ >>> df.mod(2)\n+ angles degrees\n+ circle 0 0\n+ triangle 1 0\n+ rectangle 0 0\n+\n+ Calculate modulo with a list.\n+\n+ >>> df % [2, 3]\n+ angles degrees\n+ circle 0 0\n+ triangle 1 0\n+ rectangle 0 0\n+\n+ >>> df.mod([2, 3], axis=\"columns\")\n+ angles degrees\n+ circle 0 0\n+ triangle 1 0\n+ rectangle 0 0\n+ \"\"\"\n return self._flex_arith_method(\n other, operator.mod, level=level, fill_value=fill_value, axis=axis\n )\n \n- [USER_REDACTED](ops.make_flex_doc(\"rmod\", \"dataframe\"))\n def rmod(\n self, other, axis: Axis = \"columns\", level=None, fill_value=None\n ) -> DataFrame:\n+ \"\"\"\n+ [NAME_REDACTED] of dataframe and other, \\\n+ element-wise (binary operator `rmod`).\n+\n+ Equivalent to ``other % dataframe``, but with support to substitute a\n+ fill_value for missing data in one of the inputs. With reverse version,\n+ `mod`.\n+\n+ Among flexible wrappers (`add`, `sub`, `mul`, `div`, `floordiv`, `mod`, `pow`)\n+ to arithmetic operators: `+`, `-`, `*`, `/`, `//`, `%`, `**`.\n+\n+ Parameters\n+ ----------\n+ other : scalar, sequence, Series, dict or DataFrame\n+ Any single or multiple element data structure, or list-like object.\n+ axis : {0 or 'index', 1 or 'columns'}\n+ Whether to compare by [NAME_REDACTED] (0 or 'index') or columns.\n+ (1 or 'columns'). For Series input, axis to match Series index on.\n+ level : int or label\n+ Broadcast across a level, matching Index values on the\n+ passed MultiIndex level.\n+ fill_value : float or None, default None\n+ Fill existing missing (NaN) values, and any new element needed for\n+ successful DataFrame alignment, with this value before computation.\n+ If data in both corresponding DataFrame locations is missing\n+ the result will be missing.\n+\n+ Returns\n+ -------\n+ DataFrame\n+ Result of the arithmetic operation.\n+\n+ See Also\n+ --------\n+ DataFrame.add : Add DataFrames.\n+ DataFrame.sub : [NAME_REDACTED].\n+ DataFrame.mul : [NAME_REDACTED].\n+ DataFrame.div : [NAME_REDACTED] (float division).\n+ DataFrame.truediv : [NAME_REDACTED] (float division).\n+ DataFrame.floordiv : [NAME_REDACTED] (integer division).\n+ DataFrame.mod : Calculate modulo (remainder after division).\n+ DataFrame.pow : Calculate exponential power.\n+\n+ Notes\n+ -----\n+ Mismatched indices will be unioned together.\n+\n+ Examples\n+ --------\n+ >>> df = pd.DataFrame({'angles': [0, 3, 4],\n+ ... 'degrees': [360, 180, 360]},\n+ ... index=['circle', 'triangle', 'rectangle'])\n+ >>> df\n+ angles degrees\n+ circle 0 360\n+ triangle 3 180\n+ rectangle 4 360\n+\n+ Calculate modulo with a scalar.\n+\n+ >>> 1000 % df\n+ angles degrees\n+ circle NaN 280.0\n+ triangle 1.0 100.0\n+ rectangle 0.0 280.0\n+\n+ >>> df.rmod(1000)\n+ angles degrees\n+ circle NaN 280.0\n+ triangle 1.0 100.0\n+ rectangle 0.0 280.0\n+\n+ Calculate modulo with a list.\n+\n+ >>> [1000, 2000] % df\n+ angles degrees\n+ circle NaN 200.0\n+ triangle 1.0 20.0\n+ rectangle 0.0 200.0\n+\n+ >>> df.rmod([1000, 2000], axis='columns')\n+ angles degrees\n+ circle NaN 200.0\n+ triangle 1.0 20.0\n+ rectangle 0.0 200.0\n+ \"\"\"\n return self._flex_arith_method(\n other, roperator.rmod, level=level, fill_value=fill_value, axis=axis\n )\n \n- [USER_REDACTED](ops.make_flex_doc(\"pow\", \"dataframe\"))\n def pow(\n self, other, axis: Axis = \"columns\", level=None, fill_value=None\n ) -> DataFrame:\n+ \"\"\"\n+ [NAME_REDACTED] power of dataframe and other, \\\n+ element-wise (binary operator `pow`).\n+\n+ Equivalent to ``dataframe ** other``, but with support to substitute a\n+ fill_value for missing data in one of the inputs. With reverse version,\n+ `rpow`.\n+\n+ Among flexible wrappers (`add`, `sub`, `mul`, `div`, `floordiv`, `mod`, `pow`)\n+ to arithmetic operators: `+`, `-`, `*`, `/`, `//`, `%`, `**`.\n+\n+ Parameters\n+ ----------\n+ other : scalar, sequence, Series, dict or DataFrame\n+ Any single or multiple element data structure, or list-like object.\n+ axis : {0 or 'index', 1 or 'columns'}\n+ Whether to compare by [NAME_REDACTED] (0 or 'index') or columns.\n+ (1 or 'columns'). For Series input, axis to match Series index on.\n+ level : int or label\n+ Broadcast across a level, matching Index values on the\n+ passed MultiIndex level.\n+ fill_value : float or None, default None\n+ Fill existing missing (NaN) values, and any new element needed for\n+ successful DataFrame alignment, with this value before computation.\n+ If data in both corresponding DataFrame locations is missing\n+ the result will be missing.\n+\n+ Returns\n+ -------\n+ DataFrame\n+ Result of the arithmetic operation.\n+\n+ See Also\n+ --------\n+ DataFrame.add : Add DataFrames.\n+ DataFrame.sub : [NAME_REDACTED].\n+ DataFrame.mul : [NAME_REDACTED].\n+ DataFrame.div : [NAME_REDACTED] (float division).\n+ DataFrame.truediv : [NAME_REDACTED] (float division).\n+ DataFrame.floordiv : [NAME_REDACTED] (integer division).\n+ DataFrame.mod : Calculate modulo (remainder after division).\n+ DataFrame.pow : Calculate exponential power.\n+\n+ Notes\n+ -----\n+ Mismatched indices will be unioned together.\n+\n+ Examples\n+ --------\n+ >>> df = pd.DataFrame({'angles': [0, 3, 4],\n+ ... 'degrees': [360, 180, 360]},\n+ ... index=['circle', 'triangle', 'rectangle'])\n+ >>> df\n+ angles degrees\n+ circle 0 360\n+ triangle 3 180\n+ rectangle 4 360\n+\n+ Calculate exponential power with a scalar.\n+\n+ >>> df ** 2\n+ angles degrees\n+ circle 0 129600\n+ triangle 9 32400\n+ rectangle 16 129600\n+\n+ >>> df.pow(2)\n+ angles degrees\n+ circle 0 129600\n+ triangle 9 32400\n+ rectangle 16 129600\n+\n+ Calculate exponential power with a list.\n+\n+ >>> df ** [1, 2]\n+ angles degrees\n+ circle 0 129600\n+ triangle 3 32400\n+ rectangle 4 129600\n+\n+ >>> df.pow([1, 2], axis='columns')\n+ angles degrees\n+ circle 0 129600\n+ triangle 3 32400\n+ rectangle 4 129600\n+ \"\"\"\n return self._flex_arith_method(\n other, operator.pow, level=level, fill_value=fill_value, axis=axis\n )\n \n- [USER_REDACTED](ops.make_flex_doc(\"rpow\", \"dataframe\"))\n def rpow(\n self, other, axis: Axis = \"columns\", level=None, fill_value=None\n ) -> DataFrame:\n+ \"\"\"\n+ [NAME_REDACTED] power of dataframe and other, \\\n+ element-wise (binary operator `rpow`).\n+\n+ Equivalent to ``other ** dataframe``, but with support to substitute a\n+ fill_value for missing data in one of the inputs. With reverse version,\n+ `pow`.\n+\n+ Among flexible wrappers (`add`, `sub`, `mul`, `div`, `floordiv`, `mod`, `pow`)\n+ to arithmetic operators: `+`, `-`, `*`, `/`, `//`, `%`, `**`.\n+\n+ Parameters\n+ ----------\n+ other : scalar, sequence, Series, dict or DataFrame\n+ Any single or multiple element data structure, or list-like object.\n+ axis : {0 or 'index', 1 or 'columns'}\n+ Whether to compare by [NAME_REDACTED] (0 or 'index') or columns.\n+ (1 or 'columns'). For Series input, axis to match Series index on.\n+ level : int or label\n+ Broadcast across a level, matching Index values on the\n+ passed MultiIndex level.\n+ fill_value : float or None, default None\n+ Fill existing missing (NaN) values, and any new element needed for\n+ successful DataFrame alignment, with this value before computation.\n+ If data in both corresponding DataFrame locations is missing\n+ the result will be missing.\n+\n+ Returns\n+ -------\n+ DataFrame\n+ Result of the arithmetic operation.\n+\n+ See Also\n+ --------\n+ DataFrame.add : Add DataFrames.\n+ DataFrame.sub : [NAME_REDACTED].\n+ DataFrame.mul : [NAME_REDACTED].\n+ DataFrame.div : [NAME_REDACTED] (float division).\n+ DataFrame.truediv : [NAME_REDACTED] (float division).\n+ DataFrame.floordiv : [NAME_REDACTED] (integer division).\n+ DataFrame.mod : Calculate modulo (remainder after division).\n+ DataFrame.pow : Calculate exponential power.\n+\n+ Notes\n+ -----\n+ Mismatched indices will be unioned together.\n+\n+ Examples\n+ --------\n+ >>> df = pd.DataFrame({'angles': [0, 3, 4],\n+ ... 'degrees': [3, 1, 3]},\n+ ... index=['circle', 'triangle', 'rectangle'])\n+ >>> df\n+ angles degrees\n+ circle 0 3\n+ triangle 3 1\n+ rectangle 4 3\n+\n+ Calculate exponential power with a scalar.\n+\n+ >>> 2 ** df\n+ angles degrees\n+ circle 1 8\n+ triangle 8 2\n+ rectangle 16 8\n+\n+ >>> df.rpow(2)\n+ angles degrees\n+ circle 1 8\n+ triangle 8 2\n+ rectangle 16 8\n+\n+ Calculate exponential power with a list.\n+\n+ >>> [2, 3] ** df\n+ angles degrees\n+ circle 1 27\n+ triangle 8 3\n+ rectangle 16 27\n+\n+ >>> df.rpow([2, 3], axis='columns')\n+ angles degrees\n+ circle 1 27\n+ triangle 8 3\n+ rectangle 16 27\n+ \"\"\"\n return self._flex_arith_method(\n other, roperator.rpow, level=level, fill_value=fill_value, axis=axis\n )" } ], "reviews": [ { "id": 3683653333, "user": "user_c9260bc45a59", "state": "CHANGES_REQUESTED", "body": null, "submitted_at": "2026-01-20T18:17:31+00:00" }, { "id": 3686592759, "user": "user_5b0b62fe7839", "state": "COMMENTED", "body": null, "submitted_at": "2026-01-21T10:58:59+00:00" }, { "id": 3694193369, "user": "user_c9260bc45a59", "state": "APPROVED", "body": null, "submitted_at": "2026-01-22T19:26:25+00:00" } ], "review_comments": [ { "id": 2709554307, "user": "user_c9260bc45a59", "body": "Could you update these examples to only show the method/operator for the parent function e.g. This `le` method should be only showing `le` and `<`", "path": "pandas/core/frame.py", "line": null, "side": "RIGHT", "created_at": "2026-01-20T18:17:08+00:00" }, { "id": 2712051431, "user": "user_5b0b62fe7839", "body": "make sense!", "path": "pandas/core/frame.py", "line": null, "side": "RIGHT", "created_at": "2026-01-21T10:58:59+00:00" } ], "meta": { "languages": [ "py" ], "touches_tests": false, "review_state_summary": { "CHANGES_REQUESTED": 1, "COMMENTED": 1, "APPROVED": 1 }, "meaningful_comment_count": 2, "has_approval": true, "has_changes_requested": true, "total_review_comments": 2 } } { "_id": "ba6052a5d1b53038", "_schema_version": "1.0", "_cleaned_at": "2026-02-12T07:46:51.829287+00:00", "repo": "pandas-dev/pandas", "repo_url": "https://github.com/pandas-dev/pandas", "license_name": "BSD 3-Clause \"New\" or \"Revised\" License", "license_spdx": "BSD-3-Clause", "pr_number": 63765, "title": "DOC: Inline `[USER_REDACTED](ops.make_flex_doc(...))` in pandas/core/series.py", "body": "- [ ] closes #xxxx (Replace xxxx with the GitHub issue number)\n- [ ] [Tests added and passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#writing-tests) if fixing a bug or adding a new feature\n- [x] All [code checks passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit).\n- [ ] Added [type annotations](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#type-hints) to new arguments/methods/functions.\n- [ ] Added an entry in the latest `doc/source/whatsnew/vX.X.X.rst` file if fixing a bug or adding a new feature.\n- [ ] If I used AI to develop this pull request, I prompted it to follow `AGENTS.md`.\n\nThis PR is a part of https://github.com/[USER_REDACTED]ndas-dev/pandas/issues/62437", "author": "user_5b0b62fe7839", "created_at": "2026-01-20T01:53:37+00:00", "merged_at": "2026-01-22T19:24:53+00:00", "base_branch": "main", "head_branch": "inline_ser_flex_doc", "additions": 985, "deletions": 88, "changed_files": 1, "files": [ { "filename": "pandas/core/series.py", "status": "modified", "additions": 985, "deletions": 88, "changes": 1073, "patch": "@@ -6892,8 +6892,8 @@ def eq(\n \"\"\"\n [NAME_REDACTED] to of series and other, element-wise (binary operator `eq`).\n \n- Equivalent to ``series == other``, but with support to substitute a fill_value\n- for missing data in either one of the inputs.\n+ Equivalent to ``series == other``, but with support to substitute a\n+ fill_value for missing data in either one of the inputs.\n \n Parameters\n ----------\n@@ -6952,8 +6952,66 @@ def eq(\n other, operator.eq, level=level, fill_value=fill_value, axis=axis\n )\n \n- [USER_REDACTED](ops.make_flex_doc(\"ne\", \"series\"))\n def ne(self, other, level=None, fill_value=None, axis: Axis = 0) -> Series:\n+ \"\"\"\n+ [NAME_REDACTED] equal to of series and other, element-wise (binary operator `ne`).\n+\n+ Equivalent to ``series != other``, but with support to substitute a\n+ fill_value for missing data in either one of the inputs.\n+\n+ Parameters\n+ ----------\n+ other : object\n+ When a Series is provided, will align on indexes. For all other types,\n+ will behave the same as ``!=`` but with possibly different results due\n+ to the other arguments.\n+ level : int or name\n+ Broadcast across a level, matching Index values on the\n+ passed MultiIndex level.\n+ fill_value : None or float value, default None (NaN)\n+ Fill existing missing (NaN) values, and any new element needed for\n+ successful Series alignment, with this value before computation.\n+ If data in both corresponding Series locations is missing\n+ the result of filling (at that location) will be missing.\n+ axis : {0 or 'index'}\n+ Unused. Parameter needed for compatibility with DataFrame.\n+\n+ Returns\n+ -------\n+ Series\n+ The result of the operation.\n+\n+ See Also\n+ --------\n+ Series.eq : Reverse of the Not equal to operator, see\n+ `Python documentation\n+ `_\n+ for more details.\n+\n+ Examples\n+ --------\n+ >>> a = pd.Series([1, 1, 1, np.nan], index=[\"a\", \"b\", \"c\", \"d\"])\n+ >>> a\n+ a 1.0\n+ b 1.0\n+ c 1.0\n+ d NaN\n+ dtype: float64\n+ >>> b = pd.Series([1, np.nan, 1, np.nan], index=[\"a\", \"b\", \"d\", \"e\"])\n+ >>> b\n+ a 1.0\n+ b NaN\n+ d 1.0\n+ e NaN\n+ dtype: float64\n+ >>> a.ne(b, fill_value=0)\n+ a False\n+ b True\n+ c True\n+ d True\n+ e True\n+ dtype: bool\n+ \"\"\"\n return self._flex_method(\n other, operator.ne, level=level, fill_value=fill_value, axis=axis\n )\n@@ -6970,7 +7028,7 @@ def le(self, other, level=None, fill_value=None, axis: Axis = 0) -> Series:\n ----------\n other : object\n When a Series is provided, will align on indexes. For all other types,\n- will behave the same as ``==`` but with possibly different results due\n+ will behave the same as ``<=`` but with possibly different results due\n to the other arguments.\n level : int or name\n Broadcast across a level, matching Index values on the\n@@ -7026,8 +7084,69 @@ def le(self, other, level=None, fill_value=None, axis: Axis = 0) -> Series:\n other, operator.le, level=level, fill_value=fill_value, axis=axis\n )\n \n- [USER_REDACTED](ops.make_flex_doc(\"lt\", \"series\"))\n def lt(self, other, level=None, fill_value=None, axis: Axis = 0) -> Series:\n+ \"\"\"\n+ [NAME_REDACTED] than of series and other, element-wise (binary operator `lt`).\n+\n+ Equivalent to ``series < other``, but with support to substitute a\n+ fill_value for missing data in either one of the inputs.\n+\n+ Parameters\n+ ----------\n+ other : object\n+ When a Series is provided, will align on indexes. For all other types,\n+ will behave the same as ``<`` but with possibly different results due\n+ to the other arguments.\n+ level : int or name\n+ Broadcast across a level, matching Index values on the\n+ passed MultiIndex level.\n+ fill_value : None or float value, default None (NaN)\n+ Fill existing missing (NaN) values, and any new element needed for\n+ successful Series alignment, with this value before computation.\n+ If data in both corresponding Series locations is missing\n+ the result of filling (at that location) will be missing.\n+ axis : {0 or 'index'}\n+ Unused. Parameter needed for compatibility with DataFrame.\n+\n+ Returns\n+ -------\n+ Series\n+ The result of the operation.\n+\n+ See Also\n+ --------\n+ Series.gt : [NAME_REDACTED] than, see\n+ `Python documentation\n+ `_\n+ for more details.\n+\n+ Examples\n+ --------\n+ >>> a = pd.Series([1, 1, 1, np.nan, 1], index=[\"a\", \"b\", \"c\", \"d\", \"e\"])\n+ >>> a\n+ a 1.0\n+ b 1.0\n+ c 1.0\n+ d NaN\n+ e 1.0\n+ dtype: float64\n+ >>> b = pd.Series([0, 1, 2, np.nan, 1], index=[\"a\", \"b\", \"c\", \"d\", \"f\"])\n+ >>> b\n+ a 0.0\n+ b 1.0\n+ c 2.0\n+ d NaN\n+ f 1.0\n+ dtype: float64\n+ >>> a.lt(b, fill_value=0)\n+ a False\n+ b False\n+ c True\n+ d False\n+ e False\n+ f True\n+ dtype: bool\n+ \"\"\"\n return self._flex_method(\n other, operator.lt, level=level, fill_value=fill_value, axis=axis\n )\n@@ -7044,7 +7163,7 @@ def ge(self, other, level=None, fill_value=None, axis: Axis = 0) -> Series:\n ----------\n other : object\n When a Series is provided, will align on indexes. For all other types,\n- will behave the same as ``==`` but with possibly different results due\n+ will behave the same as ``>=`` but with possibly different results due\n to the other arguments.\n level : int or name\n Broadcast across a level, matching Index values on the\n@@ -7101,8 +7220,69 @@ def ge(self, other, level=None, fill_value=None, axis: Axis = 0) -> Series:\n other, operator.ge, level=level, fill_value=fill_value, axis=axis\n )\n \n- [USER_REDACTED](ops.make_flex_doc(\"gt\", \"series\"))\n def gt(self, other, level=None, fill_value=None, axis: Axis = 0) -> Series:\n+ \"\"\"\n+ [NAME_REDACTED] than of series and other, element-wise (binary operator `gt`).\n+\n+ Equivalent to ``series > other``, but with support to substitute a\n+ fill_value for missing data in either one of the inputs.\n+\n+ Parameters\n+ ----------\n+ other : object\n+ When a Series is provided, will align on indexes. For all other types,\n+ will behave the same as ``>`` but with possibly different results due\n+ to the other arguments.\n+ level : int or name\n+ Broadcast across a level, matching Index values on the\n+ passed MultiIndex level.\n+ fill_value : None or float value, default None (NaN)\n+ Fill existing missing (NaN) values, and any new element needed for\n+ successful Series alignment, with this value before computation.\n+ If data in both corresponding Series locations is missing\n+ the result of filling (at that location) will be missing.\n+ axis : {0 or 'index'}\n+ Unused. Parameter needed for compatibility with DataFrame.\n+\n+ Returns\n+ -------\n+ Series\n+ The result of the operation.\n+\n+ See Also\n+ --------\n+ Series.lt : Reverse of the Greater than operator, see\n+ `Python documentation\n+ `_\n+ for more details.\n+\n+ Examples\n+ --------\n+ >>> a = pd.Series([1, 1, 1, np.nan, 1], index=[\"a\", \"b\", \"c\", \"d\", \"e\"])\n+ >>> a\n+ a 1.0\n+ b 1.0\n+ c 1.0\n+ d NaN\n+ e 1.0\n+ dtype: float64\n+ >>> b = pd.Series([0, 1, 2, np.nan, 1], index=[\"a\", \"b\", \"c\", \"d\", \"f\"])\n+ >>> b\n+ a 0.0\n+ b 1.0\n+ c 2.0\n+ d NaN\n+ f 1.0\n+ dtype: float64\n+ >>> a.gt(b, fill_value=0)\n+ a True\n+ b False\n+ c False\n+ d False\n+ e True\n+ f False\n+ dtype: bool\n+ \"\"\"\n return self._flex_method(\n other, operator.gt, level=level, fill_value=fill_value, axis=axis\n )\n@@ -7111,8 +7291,8 @@ def add(self, other, level=None, fill_value=None, axis: Axis = 0) -> Series:\n \"\"\"\n [NAME_REDACTED] of series and other, element-wise (binary operator `add`).\n \n- Equivalent to ``series + other``, but with support to substitute a fill_value\n- for missing data in either one of the inputs.\n+ Equivalent to ``series + other``, but with support to substitute a\n+ fill_value for missing data in either one of the inputs.\n \n Parameters\n ----------\n@@ -7169,43 +7349,19 @@ def add(self, other, level=None, fill_value=None, axis: Axis = 0) -> Series:\n other, operator.add, level=level, fill_value=fill_value, axis=axis\n )\n \n- [USER_REDACTED](ops.make_flex_doc(\"radd\", \"series\"))\n def radd(self, other, level=None, fill_value=None, axis: Axis = 0) -> Series:\n- return self._flex_method(\n- other, roperator.radd, level=level, fill_value=fill_value, axis=axis\n- )\n-\n- [USER_REDACTED](ops.make_flex_doc(\"sub\", \"series\"))\n- def sub(self, other, level=None, fill_value=None, axis: Axis = 0) -> Series:\n- return self._flex_method(\n- other, operator.sub, level=level, fill_value=fill_value, axis=axis\n- )\n-\n- subtract = sub\n-\n- [USER_REDACTED](ops.make_flex_doc(\"rsub\", \"series\"))\n- def rsub(self, other, level=None, fill_value=None, axis: Axis = 0) -> Series:\n- return self._flex_method(\n- other, roperator.rsub, level=level, fill_value=fill_value, axis=axis\n- )\n-\n- def mul(\n- self,\n- other,\n- level: Level | None = None,\n- fill_value: float | None = None,\n- axis: Axis = 0,\n- ) -> Series:\n \"\"\"\n- [NAME_REDACTED] of series and other, element-wise (binary operator `mul`).\n+ [NAME_REDACTED] of series and other, element-wise (binary operator `radd`).\n \n- Equivalent to ``series * other``, but with support to substitute\n- a fill_value for missing data in either one of the inputs.\n+ Equivalent to ``other + series``, but with support to substitute a\n+ fill_value for missing data in either one of the inputs.\n \n Parameters\n ----------\n- other : Series or scalar value\n- With which to compute the multiplication.\n+ other : object\n+ When a Series is provided, will align on indexes. For all other types,\n+ will behave the same as ``+`` but with possibly different results due\n+ to the other arguments.\n level : int or name\n Broadcast across a level, matching Index values on the\n passed MultiIndex level.\n@@ -7224,7 +7380,7 @@ def mul(\n \n See Also\n --------\n- Series.rmul : Reverse of the Multiplication operator, see\n+ Series.add : [NAME_REDACTED], see\n `Python documentation\n `_\n for more details.\n@@ -7245,44 +7401,31 @@ def mul(\n d 1.0\n e NaN\n dtype: float64\n- >>> a.multiply(b, fill_value=0)\n- a 1.0\n- b 0.0\n- c 0.0\n- d 0.0\n+ >>> a.radd(b, fill_value=1.0)\n+ a 2.0\n+ b 2.0\n+ c 2.0\n+ d 2.0\n e NaN\n dtype: float64\n- >>> a.mul(5, fill_value=0)\n- a 5.0\n- b 5.0\n- c 5.0\n- d 0.0\n- dtype: float64\n \"\"\"\n return self._flex_method(\n- other, operator.mul, level=level, fill_value=fill_value, axis=axis\n- )\n-\n- multiply = mul\n-\n- [USER_REDACTED](ops.make_flex_doc(\"rmul\", \"series\"))\n- def rmul(self, other, level=None, fill_value=None, axis: Axis = 0) -> Series:\n- return self._flex_method(\n- other, roperator.rmul, level=level, fill_value=fill_value, axis=axis\n+ other, roperator.radd, level=level, fill_value=fill_value, axis=axis\n )\n \n- def truediv(self, other, level=None, fill_value=None, axis: Axis = 0) -> Series:\n+ def sub(self, other, level=None, fill_value=None, axis: Axis = 0) -> Series:\n \"\"\"\n- [NAME_REDACTED] division of series and other, \\\n- element-wise (binary operator `truediv`).\n+ [NAME_REDACTED] of series and other, element-wise (binary operator `sub`).\n \n- Equivalent to ``series / other``, but with support to substitute a\n+ Equivalent to ``series - other``, but with support to substitute a\n fill_value for missing data in either one of the inputs.\n \n Parameters\n ----------\n- other : Series or scalar value\n- Series with which to compute division.\n+ other : object\n+ When a Series is provided, will align on indexes. For all other types,\n+ will behave the same as ``-`` but with possibly different results due\n+ to the other arguments.\n level : int or name\n Broadcast across a level, matching Index values on the\n passed MultiIndex level.\n@@ -7301,7 +7444,7 @@ def truediv(self, other, level=None, fill_value=None, axis: Axis = 0) -> Series:\n \n See Also\n --------\n- Series.rtruediv : Reverse of the Floating division operator, see\n+ Series.rsub : Reverse of the Subtraction operator, see\n `Python documentation\n `_\n for more details.\n@@ -7322,37 +7465,484 @@ def truediv(self, other, level=None, fill_value=None, axis: Axis = 0) -> Series:\n d 1.0\n e NaN\n dtype: float64\n- >>> a.divide(b, fill_value=0)\n- a 1.0\n- b inf\n- c inf\n- d 0.0\n+ >>> a.subtract(b, fill_value=0)\n+ a 0.0\n+ b 1.0\n+ c 1.0\n+ d -1.0\n e NaN\n dtype: float64\n \"\"\"\n return self._flex_method(\n- other, operator.truediv, level=level, fill_value=fill_value, axis=axis\n+ other, operator.sub, level=level, fill_value=fill_value, axis=axis\n )\n \n- div = truediv\n- divide = truediv\n+ subtract = sub\n \n- [USER_REDACTED](ops.make_flex_doc(\"rtruediv\", \"series\"))\n- def rtruediv(self, other, level=None, fill_value=None, axis: Axis = 0) -> Series:\n- return self._flex_method(\n- other, roperator.rtruediv, level=level, fill_value=fill_value, axis=axis\n- )\n+ def rsub(self, other, level=None, fill_value=None, axis: Axis = 0) -> Series:\n+ \"\"\"\n+ [NAME_REDACTED] of series and other, element-wise (binary operator `rsub`).\n+\n+ Equivalent to ``other - series``, but with support to substitute a\n+ fill_value for missing data in either one of the inputs.\n+\n+ Parameters\n+ ----------\n+ other : object\n+ When a Series is provided, will align on indexes. For all other types,\n+ will behave the same as ``-`` but with possibly different results due\n+ to the other arguments.\n+ level : int or name\n+ Broadcast across a level, matching Index values on the\n+ passed MultiIndex level.\n+ fill_value : None or float value, default None (NaN)\n+ Fill existing missing (NaN) values, and any new element needed for\n+ successful Series alignment, with this value before computation.\n+ If data in both corresponding Series locations is missing\n+ the result of filling (at that location) will be missing.\n+ axis : {0 or 'index'}\n+ Unused. Parameter needed for compatibility with DataFrame.\n+\n+ Returns\n+ -------\n+ Series\n+ The result of the operation.\n+\n+ See Also\n+ --------\n+ Series.sub : [NAME_REDACTED], see\n+ `Python documentation\n+ `_\n+ for more details.\n+\n+ Examples\n+ --------\n+ >>> a = pd.Series([1, 1, 1, np.nan], index=[\"a\", \"b\", \"c\", \"d\"])\n+ >>> a\n+ a 1.0\n+ b 1.0\n+ c 1.0\n+ d NaN\n+ dtype: float64\n+ >>> b = pd.Series([1, np.nan, 1, np.nan], index=[\"a\", \"b\", \"d\", \"e\"])\n+ >>> b\n+ a 1.0\n+ b NaN\n+ d 1.0\n+ e NaN\n+ dtype: float64\n+ >>> a.rsub(b, fill_value=0)\n+ a 0.0\n+ b -1.0\n+ c -1.0\n+ d 1.0\n+ e NaN\n+ dtype: float64\n+ \"\"\"\n+ return self._flex_method(\n+ other, roperator.rsub, level=level, fill_value=fill_value, axis=axis\n+ )\n+\n+ def mul(\n+ self,\n+ other,\n+ level: Level | None = None,\n+ fill_value: float | None = None,\n+ axis: Axis = 0,\n+ ) -> Series:\n+ \"\"\"\n+ [NAME_REDACTED] of series and other, element-wise (binary operator `mul`).\n+\n+ Equivalent to ``series * other``, but with support to substitute\n+ a fill_value for missing data in either one of the inputs.\n+\n+ Parameters\n+ ----------\n+ other : Series or scalar value\n+ With which to compute the multiplication.\n+ level : int or name\n+ Broadcast across a level, matching Index values on the\n+ passed MultiIndex level.\n+ fill_value : None or float value, default None (NaN)\n+ Fill existing missing (NaN) values, and any new element needed for\n+ successful Series alignment, with this value before computation.\n+ If data in both corresponding Series locations is missing\n+ the result of filling (at that location) will be missing.\n+ axis : {0 or 'index'}\n+ Unused. Parameter needed for compatibility with DataFrame.\n+\n+ Returns\n+ -------\n+ Series\n+ The result of the operation.\n+\n+ See Also\n+ --------\n+ Series.rmul : Reverse of the Multiplication operator, see\n+ `Python documentation\n+ `_\n+ for more details.\n+\n+ Examples\n+ --------\n+ >>> a = pd.Series([1, 1, 1, np.nan], index=[\"a\", \"b\", \"c\", \"d\"])\n+ >>> a\n+ a 1.0\n+ b 1.0\n+ c 1.0\n+ d NaN\n+ dtype: float64\n+ >>> b = pd.Series([1, np.nan, 1, np.nan], index=[\"a\", \"b\", \"d\", \"e\"])\n+ >>> b\n+ a 1.0\n+ b NaN\n+ d 1.0\n+ e NaN\n+ dtype: float64\n+ >>> a.multiply(b, fill_value=0)\n+ a 1.0\n+ b 0.0\n+ c 0.0\n+ d 0.0\n+ e NaN\n+ dtype: float64\n+ >>> a.mul(5, fill_value=0)\n+ a 5.0\n+ b 5.0\n+ c 5.0\n+ d 0.0\n+ dtype: float64\n+ \"\"\"\n+ return self._flex_method(\n+ other, operator.mul, level=level, fill_value=fill_value, axis=axis\n+ )\n+\n+ multiply = mul\n+\n+ def rmul(self, other, level=None, fill_value=None, axis: Axis = 0) -> Series:\n+ \"\"\"\n+ [NAME_REDACTED] of series and other, \\\n+ element-wise (binary operator `rmul`).\n+\n+ Equivalent to ``other * series``, but with support to substitute a\n+ fill_value for missing data in either one of the inputs.\n+\n+ Parameters\n+ ----------\n+ other : object\n+ When a Series is provided, will align on indexes. For all other types,\n+ will behave the same as ``*`` but with possibly different results due\n+ to the other arguments.\n+ level : int or name\n+ Broadcast across a level, matching Index values on the\n+ passed MultiIndex level.\n+ fill_value : None or float value, default None (NaN)\n+ Fill existing missing (NaN) values, and any new element needed for\n+ successful Series alignment, with this value before computation.\n+ If data in both corresponding Series locations is missing\n+ the result of filling (at that location) will be missing.\n+ axis : {0 or 'index'}\n+ Unused. Parameter needed for compatibility with DataFrame.\n+\n+ Returns\n+ -------\n+ Series\n+ The result of the operation.\n+\n+ See Also\n+ --------\n+ Series.mul : [NAME_REDACTED], see\n+ `Python documentation\n+ `_\n+ for more details.\n+\n+ Examples\n+ --------\n+ >>> a = pd.Series([1, 1, 1, np.nan], index=[\"a\", \"b\", \"c\", \"d\"])\n+ >>> a\n+ a 1.0\n+ b 1.0\n+ c 1.0\n+ d NaN\n+ dtype: float64\n+ >>> b = pd.Series([1, np.nan, 1, np.nan], index=[\"a\", \"b\", \"d\", \"e\"])\n+ >>> b\n+ a 1.0\n+ b NaN\n+ d 1.0\n+ e NaN\n+ dtype: float64\n+ >>> a.rmul(b, fill_value=0)\n+ a 1.0\n+ b 0.0\n+ c 0.0\n+ d 0.0\n+ e NaN\n+ dtype: float64\n+ \"\"\"\n+ return self._flex_method(\n+ other, roperator.rmul, level=level, fill_value=fill_value, axis=axis\n+ )\n+\n+ def truediv(self, other, level=None, fill_value=None, axis: Axis = 0) -> Series:\n+ \"\"\"\n+ [NAME_REDACTED] division of series and other, \\\n+ element-wise (binary operator `truediv`).\n+\n+ Equivalent to ``series / other``, but with support to substitute a\n+ fill_value for missing data in either one of the inputs.\n+\n+ Parameters\n+ ----------\n+ other : Series or scalar value\n+ Series with which to compute division.\n+ level : int or name\n+ Broadcast across a level, matching Index values on the\n+ passed MultiIndex level.\n+ fill_value : None or float value, default None (NaN)\n+ Fill existing missing (NaN) values, and any new element needed for\n+ successful Series alignment, with this value before computation.\n+ If data in both corresponding Series locations is missing\n+ the result of filling (at that location) will be missing.\n+ axis : {0 or 'index'}\n+ Unused. Parameter needed for compatibility with DataFrame.\n+\n+ Returns\n+ -------\n+ Series\n+ The result of the operation.\n+\n+ See Also\n+ --------\n+ Series.rtruediv : Reverse of the Floating division operator, see\n+ `Python documentation\n+ `_\n+ for more details.\n+\n+ Examples\n+ --------\n+ >>> a = pd.Series([1, 1, 1, np.nan], index=[\"a\", \"b\", \"c\", \"d\"])\n+ >>> a\n+ a 1.0\n+ b 1.0\n+ c 1.0\n+ d NaN\n+ dtype: float64\n+ >>> b = pd.Series([1, np.nan, 1, np.nan], index=[\"a\", \"b\", \"d\", \"e\"])\n+ >>> b\n+ a 1.0\n+ b NaN\n+ d 1.0\n+ e NaN\n+ dtype: float64\n+ >>> a.divide(b, fill_value=0)\n+ a 1.0\n+ b inf\n+ c inf\n+ d 0.0\n+ e NaN\n+ dtype: float64\n+ \"\"\"\n+ return self._flex_method(\n+ other, operator.truediv, level=level, fill_value=fill_value, axis=axis\n+ )\n+\n+ div = truediv\n+ divide = truediv\n+\n+ def rtruediv(self, other, level=None, fill_value=None, axis: Axis = 0) -> Series:\n+ \"\"\"\n+ [NAME_REDACTED] division of series and other, \\\n+ element-wise (binary operator `rtruediv`).\n+\n+ Equivalent to ``other / series``, but with support to substitute a\n+ fill_value for missing data in either one of the inputs.\n+\n+ Parameters\n+ ----------\n+ other : object\n+ When a Series is provided, will align on indexes. For all other types,\n+ will behave the same as ``/`` but with possibly different results due\n+ to the other arguments.\n+ level : int or name\n+ Broadcast across a level, matching Index values on the\n+ passed MultiIndex level.\n+ fill_value : None or float value, default None (NaN)\n+ Fill existing missing (NaN) values, and any new element needed for\n+ successful Series alignment, with this value before computation.\n+ If data in both corresponding Series locations is missing\n+ the result of filling (at that location) will be missing.\n+ axis : {0 or 'index'}\n+ Unused. Parameter needed for compatibility with DataFrame.\n+\n+ Returns\n+ -------\n+ Series\n+ The result of the operation.\n+\n+ See Also\n+ --------\n+ Series.truediv : [NAME_REDACTED] division, see\n+ `Python documentation\n+ `_\n+ for more details.\n+\n+ Examples\n+ --------\n+ >>> a = pd.Series([1, 1, 1, np.nan], index=[\"a\", \"b\", \"c\", \"d\"])\n+ >>> a\n+ a 1.0\n+ b 1.0\n+ c 1.0\n+ d NaN\n+ dtype: float64\n+ >>> b = pd.Series([1, np.nan, 1, np.nan], index=[\"a\", \"b\", \"d\", \"e\"])\n+ >>> b\n+ a 1.0\n+ b NaN\n+ d 1.0\n+ e NaN\n+ dtype: float64\n+ >>> a.rtruediv(b, fill_value=0)\n+ a 1.0\n+ b 0.0\n+ c 0.0\n+ d inf\n+ e NaN\n+ dtype: float64\n+ \"\"\"\n+ return self._flex_method(\n+ other, roperator.rtruediv, level=level, fill_value=fill_value, axis=axis\n+ )\n \n rdiv = rtruediv\n \n- [USER_REDACTED](ops.make_flex_doc(\"floordiv\", \"series\"))\n def floordiv(self, other, level=None, fill_value=None, axis: Axis = 0) -> Series:\n+ \"\"\"\n+ [NAME_REDACTED] division of series and other, \\\n+ element-wise (binary operator `floordiv`).\n+\n+ Equivalent to ``series // other``, but with support to substitute a\n+ fill_value for missing data in either one of the inputs.\n+\n+ Parameters\n+ ----------\n+ other : object\n+ When a Series is provided, will align on indexes. For all other types,\n+ will behave the same as ``//`` but with possibly different results due\n+ to the other arguments.\n+ level : int or name\n+ Broadcast across a level, matching Index values on the\n+ passed MultiIndex level.\n+ fill_value : None or float value, default None (NaN)\n+ Fill existing missing (NaN) values, and any new element needed for\n+ successful Series alignment, with this value before computation.\n+ If data in both corresponding Series locations is missing\n+ the result of filling (at that location) will be missing.\n+ axis : {0 or 'index'}\n+ Unused. Parameter needed for compatibility with DataFrame.\n+\n+ Returns\n+ -------\n+ Series\n+ The result of the operation.\n+\n+ See Also\n+ --------\n+ Series.rfloordiv : Reverse of the Integer division operator, see\n+ `Python documentation\n+ `_\n+ for more details.\n+\n+ Examples\n+ --------\n+ >>> a = pd.Series([1, 1, 1, np.nan], index=[\"a\", \"b\", \"c\", \"d\"])\n+ >>> a\n+ a 1.0\n+ b 1.0\n+ c 1.0\n+ d NaN\n+ dtype: float64\n+ >>> b = pd.Series([1, np.nan, 1, np.nan], index=[\"a\", \"b\", \"d\", \"e\"])\n+ >>> b\n+ a 1.0\n+ b NaN\n+ d 1.0\n+ e NaN\n+ dtype: float64\n+ >>> a.floordiv(b, fill_value=0)\n+ a 1.0\n+ b inf\n+ c inf\n+ d 0.0\n+ e NaN\n+ dtype: float64\n+ \"\"\"\n return self._flex_method(\n other, operator.floordiv, level=level, fill_value=fill_value, axis=axis\n )\n \n- [USER_REDACTED](ops.make_flex_doc(\"rfloordiv\", \"series\"))\n def rfloordiv(self, other, level=None, fill_value=None, axis: Axis = 0) -> Series:\n+ \"\"\"\n+ [NAME_REDACTED] division of series and other, \\\n+ element-wise (binary operator `rfloordiv`).\n+\n+ Equivalent to ``other // series``, but with support to substitute a\n+ fill_value for missing data in either one of the inputs.\n+\n+ Parameters\n+ ----------\n+ other : object\n+ When a Series is provided, will align on indexes. For all other types,\n+ will behave the same as ``//`` but with possibly different results due\n+ to the other arguments.\n+ level : int or name\n+ Broadcast across a level, matching Index values on the\n+ passed MultiIndex level.\n+ fill_value : None or float value, default None (NaN)\n+ Fill existing missing (NaN) values, and any new element needed for\n+ successful Series alignment, with this value before computation.\n+ If data in both corresponding Series locations is missing\n+ the result of filling (at that location) will be missing.\n+ axis : {0 or 'index'}\n+ Unused. Parameter needed for compatibility with DataFrame.\n+\n+ Returns\n+ -------\n+ Series\n+ The result of the operation.\n+\n+ See Also\n+ --------\n+ Series.floordiv : [NAME_REDACTED] division, see\n+ `Python documentation\n+ `_\n+ for more details.\n+\n+ Examples\n+ --------\n+ >>> a = pd.Series([1, 1, 1, np.nan], index=[\"a\", \"b\", \"c\", \"d\"])\n+ >>> a\n+ a 1.0\n+ b 1.0\n+ c 1.0\n+ d NaN\n+ dtype: float64\n+ >>> b = pd.Series([1, np.nan, 1, np.nan], index=[\"a\", \"b\", \"d\", \"e\"])\n+ >>> b\n+ a 1.0\n+ b NaN\n+ d 1.0\n+ e NaN\n+ dtype: float64\n+ >>> a.rfloordiv(b, fill_value=0)\n+ a 1.0\n+ b 0.0\n+ c 0.0\n+ d inf\n+ e NaN\n+ dtype: float64\n+ \"\"\"\n return self._flex_method(\n other, roperator.rfloordiv, level=level, fill_value=fill_value, axis=axis\n )\n@@ -7419,32 +8009,339 @@ def mod(self, other, level=None, fill_value=None, axis: Axis = 0) -> Series:\n other, operator.mod, level=level, fill_value=fill_value, axis=axis\n )\n \n- [USER_REDACTED](ops.make_flex_doc(\"rmod\", \"series\"))\n def rmod(self, other, level=None, fill_value=None, axis: Axis = 0) -> Series:\n+ \"\"\"\n+ [NAME_REDACTED] of series and other, \\\n+ element-wise (binary operator `rmod`).\n+\n+ Equivalent to ``other % series``, but with support to substitute a\n+ fill_value for missing data in either one of the inputs.\n+\n+ Parameters\n+ ----------\n+ other : object\n+ When a Series is provided, will align on indexes. For all other types,\n+ will behave the same as ``%`` but with possibly different results due\n+ to the other arguments.\n+ level : int or name\n+ Broadcast across a level, matching Index values on the\n+ passed MultiIndex level.\n+ fill_value : None or float value, default None (NaN)\n+ Fill existing missing (NaN) values, and any new element needed for\n+ successful Series alignment, with this value before computation.\n+ If data in both corresponding Series locations is missing\n+ the result of filling (at that location) will be missing.\n+ axis : {0 or 'index'}\n+ Unused. Parameter needed for compatibility with DataFrame.\n+\n+ Returns\n+ -------\n+ Series\n+ The result of the operation.\n+\n+ See Also\n+ --------\n+ Series.mod : [NAME_REDACTED], see\n+ `Python documentation\n+ `_\n+ for more details.\n+\n+ Examples\n+ --------\n+ >>> a = pd.Series([1, 1, 1, np.nan], index=[\"a\", \"b\", \"c\", \"d\"])\n+ >>> a\n+ a 1.0\n+ b 1.0\n+ c 1.0\n+ d NaN\n+ dtype: float64\n+ >>> b = pd.Series([1, np.nan, 1, np.nan], index=[\"a\", \"b\", \"d\", \"e\"])\n+ >>> b\n+ a 1.0\n+ b NaN\n+ d 1.0\n+ e NaN\n+ dtype: float64\n+ >>> a.rmod(b, fill_value=0)\n+ a 0.0\n+ b 0.0\n+ c 0.0\n+ d NaN\n+ e NaN\n+ dtype: float64\n+ \"\"\"\n return self._flex_method(\n other, roperator.rmod, level=level, fill_value=fill_value, axis=axis\n )\n \n- [USER_REDACTED](ops.make_flex_doc(\"pow\", \"series\"))\n def pow(self, other, level=None, fill_value=None, axis: Axis = 0) -> Series:\n+ \"\"\"\n+ [NAME_REDACTED] power of series and other, \\\n+ element-wise (binary operator `pow`).\n+\n+ Equivalent to ``series ** other``, but with support to substitute a\n+ fill_value for missing data in either one of the inputs.\n+\n+ Parameters\n+ ----------\n+ other : object\n+ When a Series is provided, will align on indexes. For all other types,\n+ will behave the same as ``**`` but with possibly different results due\n+ to the other arguments.\n+ level : int or name\n+ Broadcast across a level, matching Index values on the\n+ passed MultiIndex level.\n+ fill_value : None or float value, default None (NaN)\n+ Fill existing missing (NaN) values, and any new element needed for\n+ successful Series alignment, with this value before computation.\n+ If data in both corresponding Series locations is missing\n+ the result of filling (at that location) will be missing.\n+ axis : {0 or 'index'}\n+ Unused. Parameter needed for compatibility with DataFrame.\n+\n+ Returns\n+ -------\n+ Series\n+ The result of the operation.\n+\n+ See Also\n+ --------\n+ Series.rpow : Reverse of the Exponential power operator, see\n+ `Python documentation\n+ `_\n+ for more details.\n+\n+ Examples\n+ --------\n+ >>> a = pd.Series([1, 1, 1, np.nan], index=[\"a\", \"b\", \"c\", \"d\"])\n+ >>> a\n+ a 1.0\n+ b 1.0\n+ c 1.0\n+ d NaN\n+ dtype: float64\n+ >>> b = pd.Series([1, np.nan, 1, np.nan], index=[\"a\", \"b\", \"d\", \"e\"])\n+ >>> b\n+ a 1.0\n+ b NaN\n+ d 1.0\n+ e NaN\n+ dtype: float64\n+ >>> a.pow(b, fill_value=0)\n+ a 1.0\n+ b 1.0\n+ c 1.0\n+ d 0.0\n+ e NaN\n+ dtype: float64\n+ \"\"\"\n return self._flex_method(\n other, operator.pow, level=level, fill_value=fill_value, axis=axis\n )\n \n- [USER_REDACTED](ops.make_flex_doc(\"rpow\", \"series\"))\n def rpow(self, other, level=None, fill_value=None, axis: Axis = 0) -> Series:\n+ \"\"\"\n+ [NAME_REDACTED] power of series and other, \\\n+ element-wise (binary operator `rpow`).\n+\n+ Equivalent to ``other ** series``, but with support to substitute a\n+ fill_value for missing data in either one of the inputs.\n+\n+ Parameters\n+ ----------\n+ other : object\n+ When a Series is provided, will align on indexes. For all other types,\n+ will behave the same as ``**`` but with possibly different results due\n+ to the other arguments.\n+ level : int or name\n+ Broadcast across a level, matching Index values on the\n+ passed MultiIndex level.\n+ fill_value : None or float value, default None (NaN)\n+ Fill existing missing (NaN) values, and any new element needed for\n+ successful Series alignment, with this value before computation.\n+ If data in both corresponding Series locations is missing\n+ the result of filling (at that location) will be missing.\n+ axis : {0 or 'index'}\n+ Unused. Parameter needed for compatibility with DataFrame.\n+\n+ Returns\n+ -------\n+ Series\n+ The result of the operation.\n+\n+ See Also\n+ --------\n+ Series.pow : [NAME_REDACTED] power, see\n+ `Python documentation\n+ `_\n+ for more details.\n+\n+ Examples\n+ --------\n+ >>> a = pd.Series([1, 1, 1, np.nan], index=[\"a\", \"b\", \"c\", \"d\"])\n+ >>> a\n+ a 1.0\n+ b 1.0\n+ c 1.0\n+ d NaN\n+ dtype: float64\n+ >>> b = pd.Series([1, np.nan, 1, np.nan], index=[\"a\", \"b\", \"d\", \"e\"])\n+ >>> b\n+ a 1.0\n+ b NaN\n+ d 1.0\n+ e NaN\n+ dtype: float64\n+ >>> a.rpow(b, fill_value=0)\n+ a 1.0\n+ b 0.0\n+ c 0.0\n+ d 1.0\n+ e NaN\n+ dtype: float64\n+ \"\"\"\n return self._flex_method(\n other, roperator.rpow, level=level, fill_value=fill_value, axis=axis\n )\n \n- [USER_REDACTED](ops.make_flex_doc(\"divmod\", \"series\"))\n def divmod(self, other, level=None, fill_value=None, axis: Axis = 0) -> Series:\n+ \"\"\"\n+ [NAME_REDACTED] division and modulo of series and other, \\\n+ element-wise (binary operator `divmod`).\n+\n+ Equivalent to ``divmod(series, other)``, but with support to substitute a\n+ fill_value for missing data in either one of the inputs.\n+\n+ Parameters\n+ ----------\n+ other : object\n+ When a Series is provided, will align on indexes. For all other types,\n+ will behave the same as ``//`` and ``%`` but with possibly different\n+ results due to the other arguments.\n+ level : int or name\n+ Broadcast across a level, matching Index values on the\n+ passed MultiIndex level.\n+ fill_value : None or float value, default None (NaN)\n+ Fill existing missing (NaN) values, and any new element needed for\n+ successful Series alignment, with this value before computation.\n+ If data in both corresponding Series locations is missing\n+ the result of filling (at that location) will be missing.\n+ axis : {0 or 'index'}\n+ Unused. Parameter needed for compatibility with DataFrame.\n+\n+ Returns\n+ -------\n+ 2-Tuple of Series\n+ The result of the operation.\n+\n+ See Also\n+ --------\n+ Series.rdivmod : Reverse of the Integer division and modulo operator, see\n+ `Python documentation\n+ `_\n+ for more details.\n+\n+ Examples\n+ --------\n+ >>> a = pd.Series([1, 1, 1, np.nan], index=[\"a\", \"b\", \"c\", \"d\"])\n+ >>> a\n+ a 1.0\n+ b 1.0\n+ c 1.0\n+ d NaN\n+ dtype: float64\n+ >>> b = pd.Series([1, np.nan, 1, np.nan], index=[\"a\", \"b\", \"d\", \"e\"])\n+ >>> b\n+ a 1.0\n+ b NaN\n+ d 1.0\n+ e NaN\n+ dtype: float64\n+ >>> a.divmod(b, fill_value=0)\n+ (a 1.0\n+ b inf\n+ c inf\n+ d 0.0\n+ e NaN\n+ dtype: float64,\n+ a 0.0\n+ b NaN\n+ c NaN\n+ d 0.0\n+ e NaN\n+ dtype: float64)\n+ \"\"\"\n return self._flex_method(\n other, divmod, level=level, fill_value=fill_value, axis=axis\n )\n \n- [USER_REDACTED](ops.make_flex_doc(\"rdivmod\", \"series\"))\n def rdivmod(self, other, level=None, fill_value=None, axis: Axis = 0) -> Series:\n+ \"\"\"\n+ [NAME_REDACTED] division and modulo of series and other, \\\n+ element-wise (binary operator `rdivmod`).\n+\n+ Equivalent to ``other divmod series``, but with support to substitute a\n+ fill_value for missing data in either one of the inputs.\n+\n+ Parameters\n+ ----------\n+ other : object\n+ When a Series is provided, will align on indexes. For all other types,\n+ will behave the same as ``//`` and ``%`` but with possibly different\n+ results due to the other arguments.\n+ level : int or name\n+ Broadcast across a level, matching Index values on the\n+ passed MultiIndex level.\n+ fill_value : None or float value, default None (NaN)\n+ Fill existing missing (NaN) values, and any new element needed for\n+ successful Series alignment, with this value before computation.\n+ If data in both corresponding Series locations is missing\n+ the result of filling (at that location) will be missing.\n+ axis : {0 or 'index'}\n+ Unused. Parameter needed for compatibility with DataFrame.\n+\n+ Returns\n+ -------\n+ 2-Tuple of Series\n+ The result of the operation.\n+\n+ See Also\n+ --------\n+ Series.divmod : [NAME_REDACTED] division and modulo, see\n+ `Python documentation\n+ `_\n+ for more details.\n+\n+ Examples\n+ --------\n+ >>> a = pd.Series([1, 1, 1, np.nan], index=[\"a\", \"b\", \"c\", \"d\"])\n+ >>> a\n+ a 1.0\n+ b 1.0\n+ c 1.0\n+ d NaN\n+ dtype: float64\n+ >>> b = pd.Series([1, np.nan, 1, np.nan], index=[\"a\", \"b\", \"d\", \"e\"])\n+ >>> b\n+ a 1.0\n+ b NaN\n+ d 1.0\n+ e NaN\n+ dtype: float64\n+ >>> a.rdivmod(b, fill_value=0)\n+ (a 1.0\n+ b 0.0\n+ c 0.0\n+ d inf\n+ e NaN\n+ dtype: float64,\n+ a 0.0\n+ b 0.0\n+ c 0.0\n+ d NaN\n+ e NaN\n+ dtype: float64)\n+ \"\"\"\n return self._flex_method(\n other, roperator.rdivmod, level=level, fill_value=fill_value, axis=axis\n )" } ], "reviews": [ { "id": 3680048988, "user": "user_5b0b62fe7839", "state": "COMMENTED", "body": null, "submitted_at": "2026-01-20T02:08:51+00:00" }, { "id": 3683603253, "user": "user_c9260bc45a59", "state": "CHANGES_REQUESTED", "body": null, "submitted_at": "2026-01-20T18:08:32+00:00" }, { "id": 3686536922, "user": "user_5b0b62fe7839", "state": "COMMENTED", "body": null, "submitted_at": "2026-01-21T10:46:07+00:00" }, { "id": 3694181236, "user": "user_c9260bc45a59", "state": "APPROVED", "body": null, "submitted_at": "2026-01-22T19:24:11+00:00" } ], "review_comments": [ { "id": 2706507638, "user": "user_5b0b62fe7839", "body": "the previous dostring for `lt` is incorrect, it was for `gt`\n\nhttps://pandas.pydata.org/pandas-docs/version/3.0/reference/api/pandas.Series.lt.html", "path": "pandas/core/series.py", "line": 7089, "side": "RIGHT", "created_at": "2026-01-20T02:08:51+00:00" }, { "id": 2709514362, "user": "user_c9260bc45a59", "body": "```suggestion\n will behave the same as ``!=`` but with possibly different results due\n```\n\nI think all the comparative ops methods will need a similar change to correct the operator", "path": "pandas/core/series.py", "line": null, "side": "RIGHT", "created_at": "2026-01-20T18:07:22+00:00" }, { "id": 2712002487, "user": "user_5b0b62fe7839", "body": "ack!", "path": "pandas/core/series.py", "line": null, "side": "RIGHT", "created_at": "2026-01-21T10:46:07+00:00" } ], "meta": { "languages": [ "py" ], "touches_tests": false, "review_state_summary": { "COMMENTED": 2, "CHANGES_REQUESTED": 1, "APPROVED": 1 }, "meaningful_comment_count": 2, "has_approval": true, "has_changes_requested": true, "total_review_comments": 3 } } { "_id": "826ae6e6a555e6c8", "_schema_version": "1.0", "_cleaned_at": "2026-02-12T07:46:51.845010+00:00", "repo": "pandas-dev/pandas", "repo_url": "https://github.com/pandas-dev/pandas", "license_name": "BSD 3-Clause \"New\" or \"Revised\" License", "license_spdx": "BSD-3-Clause", "pr_number": 63762, "title": "DOC: split/reorder other enhancements section in 3.0.0 whatsnew notes", "body": "Attempt to make the long \"Other enhancements\" section a bit more structured, by [NAME_REDACTED] per topic (categories loosely taken from the ones we use for the bugs section). \nNot everything is easy to categorize / some sections are quite short, but overall I think it gives _some_ improvement.\n\nFirst commit is just a splitting / moving around, no line should otherwise have been edited.", "author": "user_7213a217ace7", "created_at": "2026-01-19T21:49:13+00:00", "merged_at": "2026-01-21T13:42:50+00:00", "base_branch": "main", "head_branch": "3.0-whatsnew-enhancements-cleanup", "additions": 120, "deletions": 60, "changed_files": 1, "files": [ { "filename": "doc/source/whatsnew/v3.0.0.rst", "status": "modified", "additions": 120, "deletions": 60, "changes": 180, "patch": "@@ -172,6 +172,25 @@ This includes :meth:`DataFrame.assign`, :meth:`DataFrame.loc`, and getitem/setit\n It is expected that the support for ``pd.col()`` will be expanded to more methods\n in future releases.\n \n+Support for the [NAME_REDACTED]\n+^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n+\n+The Arrow C data interface allows moving data between different DataFrame libraries\n+through the Arrow format, and is designed to be zero-copy where possible. In Python,\n+this interface is exposed through the `[NAME_REDACTED] `__.\n+\n+:class:`DataFrame` and :class:`Series` now support the [NAME_REDACTED]\n+for both export and import of data (:issue:`56587`, :issue:`63208`, :issue:`59518`, :issue:`59631`).\n+\n+The dedicated :meth:`DataFrame.from_arrow` and :meth:`Series.from_arrow` methods are\n+added to import any Arrow-compatible data object into a pandas object through the interface.\n+\n+For export, the :class:`DataFrame` and :class:`Series` implement the C stream\n+interface (``__arrow_c_stream__``) method.\n+\n+Those methods currently rely on ``pyarrow`` to convert the tabular object in\n+Arrow format to/from pandas.\n+\n Updated deprecation policy\n ^^^^^^^^^^^^^^^^^^^^^^^^^^\n pandas 3.0.0 updates the deprecation policy to clarify which deprecation warnings will be issued, using a new 3-stage policy: using ``DeprecationWarning`` initially, then switching to ``FutureWarning`` for broader visibility in the last minor version before the next major release, and then removal of the deprecated functionality in the major release. This was done to give downstream packages more time to adjust to pandas deprecations, which should reduce the amount of warnings that a user gets from code that isn't theirs. See `PDEP 17 `_ for more details.\n@@ -191,86 +210,127 @@ In the last minor release of the 3.x series, these deprecations will switch to i\n \n Other enhancements\n ^^^^^^^^^^^^^^^^^^\n+\n+I/O:\n+\n+- :class:`.errors.DtypeWarning` improved to include column names when mixed data types are detected (:issue:`58174`)\n+- :func:`DataFrame.to_excel` argument ``merge_cells`` now accepts a value of ``\"columns\"`` to only merge :class:`MultiIndex` column header header cells (:issue:`35384`)\n+- :func:`DataFrame.to_excel` has a new ``autofilter`` parameter to add automatic filters to all columns (:issue:`61194`)\n+- :func:`DataFrame.to_excel` now raises a ``UserWarning`` when the character count in a cell exceeds Excel's limitation of 32767 characters (:issue:`56954`)\n+- :func:`read_parquet` accepts ``to_pandas_kwargs`` which are forwarded to :meth:`pyarrow.Table.to_pandas` which enables passing additional keywords to customize the conversion to pandas, such as ``maps_as_pydicts`` to read the Parquet map data type as python dictionaries (:issue:`56842`)\n+- :func:`read_spss` now supports kwargs to be passed to ``pyreadstat`` (:issue:`56356`)\n+- :func:`read_stata` now returns ``datetime64`` resolutions better matching those natively stored in the stata format (:issue:`55642`)\n+- :meth:`DataFrame.to_csv` and :meth:`Series.to_csv` now support f-strings (e.g., ``\"{:.6f}\"``) for the ``float_format`` parameter, in addition to the ``%`` format strings and callables (:issue:`49580`)\n+- :meth:`DataFrame.to_json` now encodes ``Decimal`` as strings instead of floats (:issue:`60698`)\n+- Added ``\"delete_rows\"`` option to ``if_exists`` argument in :meth:`DataFrame.to_sql` deleting all records of the table before inserting data (:issue:`37210`).\n+- Added support to read and write from and to [NAME_REDACTED] tables with the new :func:`read_iceberg` and :meth:`DataFrame.to_iceberg` functions (:issue:`61383`)\n+- Errors occurring during SQL I/O will now throw a generic :class:`.DatabaseError` instead of the raw Exception type from the underlying driver manager library (:issue:`60748`)\n+- Restore support for reading Stata 104-format and enable reading 103-format dta files (:issue:`58554`)\n+- Support reading Stata 102-format (Stata 1) dta files (:issue:`58978`)\n+- Support reading Stata 110-format (Stata 7) dta files (:issue:`47176`)\n+- Support reading value labels from Stata 108-format (Stata 6) and earlier files (:issue:`58154`)\n+\n+Groupby/resample/rolling:\n+\n - :class:`pandas.NamedAgg` now supports passing ``*args`` and ``**kwargs``\n to calls of ``aggfunc`` (:issue:`58283`)\n+- :class:`DataFrameGroupBy` and :class:`SeriesGroupBy` methods ``sum``, ``mean``, ``median``, ``prod``, ``min``, ``max``, ``std``, ``var`` and ``sem`` now accept ``skipna`` parameter (:issue:`15675`)\n+- :meth:`.DataFrameGroupBy.transform`, :meth:`.SeriesGroupBy.transform`, :meth:`.DataFrameGroupBy.agg`, :meth:`.SeriesGroupBy.agg`, :meth:`.RollingGroupby.apply`, :meth:`.ExpandingGroupby.apply`, :meth:`.Rolling.apply`, :meth:`.Expanding.apply`, :meth:`.DataFrame.apply` with ``engine=\"numba\"`` now supports positional arguments passed as kwargs (:issue:`58995`)\n+- :meth:`.DataFrameGroupBy.transform`, :meth:`.SeriesGroupBy.transform`, :meth:`.DataFrameGroupBy.agg`, :meth:`.SeriesGroupBy.agg`, :meth:`.SeriesGroupBy.apply`, :meth:`.DataFrameGroupBy.apply` now support ``kurt`` (:issue:`40139`)\n+- :meth:`.Rolling.aggregate`, :meth:`.Expanding.aggregate` and :meth:`.ExponentialMovingWindow.aggregate` now accept :class:`NamedAgg` aggregations through ``**kwargs`` (:issue:`28333`)\n+- Added :meth:`.Rolling.first`, :meth:`.Rolling.last`, :meth:`.Expanding.first`, and :meth:`.Expanding.last` (:issue:`33155`)\n+- Added :meth:`.Rolling.nunique` and :meth:`.Expanding.nunique` (:issue:`26958`)\n+- Added :meth:`.Rolling.pipe` and :meth:`.Expanding.pipe` (:issue:`57076`)\n+\n+Reshaping:\n+\n - :func:`pandas.merge` propagates the ``attrs`` attribute to the result if all\n inputs have identical ``attrs``, as has so far already been the case for\n :func:`pandas.concat`.\n-- :class:`pandas.api.typing.FrozenList` is available for typing the outputs of :attr:`MultiIndex.names`, :attr:`MultiIndex.codes` and :attr:`MultiIndex.levels` (:issue:`58237`)\n-- :class:`pandas.api.typing.NoDefault` is available for typing ``no_default`` (:issue:`60696`)\n-- :class:`pandas.api.typing.SASReader` is available for typing the output of :func:`read_sas` (:issue:`55689`)\n-- :func:`DataFrame.to_excel` now raises a ``UserWarning`` when the character count in a cell exceeds Excel's limitation of 32767 characters (:issue:`56954`)\n - :func:`pandas.merge` now validates the ``how`` parameter input (merge type) (:issue:`59435`)\n - :func:`pandas.merge`, :meth:`DataFrame.merge` and :meth:`DataFrame.join` now support anti joins (``left_anti`` and ``right_anti``) in the ``how`` parameter (:issue:`42916`)\n-- :func:`read_spss` now supports kwargs to be passed to ``pyreadstat`` (:issue:`56356`)\n-- :func:`read_stata` now returns ``datetime64`` resolutions better matching those natively stored in the stata format (:issue:`55642`)\n-- :meth:`.Styler.set_tooltips` provides alternative method to storing tooltips by [NAME_REDACTED] td elements. (:issue:`56981`)\n+- :meth:`DataFrame.pivot_table` and :func:`pivot_table` now allow the passing of keyword arguments to ``aggfunc`` through ``**kwargs`` (:issue:`57884`)\n+- :meth:`pandas.concat` will raise a ``ValueError`` when ``ignore_index=True`` and ``keys`` is not ``None`` (:issue:`59274`)\n+- Improve error reporting through outputting the first few duplicates when :func:`merge` validation fails (:issue:`62742`)\n+\n+Missing:\n+\n+- :meth:`DataFrame.fillna` and :meth:`Series.fillna` can now accept ``value=None``; for non-object dtype the corresponding NA value will be used (:issue:`57723`)\n+- Added support for ``axis=1`` with ``dict`` or :class:`Series` arguments in :meth:`DataFrame.fillna` (:issue:`4514`)\n+\n+\n+Numeric:\n+\n - :meth:`DataFrame.agg` called with ``axis=1`` and a ``func`` which relabels the result index now raises a ``NotImplementedError`` (:issue:`58807`).\n-- :meth:`Index.get_loc` now accepts also subclasses of ``tuple`` as keys (:issue:`57922`)\n-- Added :meth:`.Styler.to_typst` to write Styler objects to file, buffer or string in Typst format (:issue:`57617`)\n-- Added missing :meth:`pandas.Series.info` to API reference (:issue:`60926`)\n-- Added missing parameter ``weights`` in :meth:`DataFrame.plot.kde` for the estimation of the PDF (:issue:`59337`)\n-- Allow dictionaries to be passed to :meth:`Series.str.replace` via ``pat`` parameter (:issue:`51748`)\n-- Support passing a :class:`Series` input to :func:`json_normalize` that retains the :class:`Index` (:issue:`51452`)\n-- Support reading value labels from Stata 108-format (Stata 6) and earlier files (:issue:`58154`)\n-- Users can globally disable any ``PerformanceWarning`` by [NAME_REDACTED] ``mode.performance_warnings`` to ``False`` (:issue:`56920`)\n-- :meth:`.Styler.format_index_names` can now be used to format the index and column names (:issue:`48936` and :issue:`47489`)\n-- :class:`.errors.DtypeWarning` improved to include column names when mixed data types are detected (:issue:`58174`)\n-- :class:`Series` now supports the [NAME_REDACTED] for export (:issue:`59518`)\n-- :func:`DataFrame.to_excel` argument ``merge_cells`` now accepts a value of ``\"columns\"`` to only merge :class:`MultiIndex` column header header cells (:issue:`35384`)\n-- :func:`set_option` now accepts a dictionary of options, simplifying configuration of multiple settings at once (:issue:`61093`)\n - :meth:`DataFrame.corrwith` now accepts ``min_periods`` as optional arguments, as in :meth:`DataFrame.corr` and :meth:`Series.corr` (:issue:`9490`)\n - :meth:`DataFrame.cummin`, :meth:`DataFrame.cummax`, :meth:`DataFrame.cumprod` and :meth:`DataFrame.cumsum` methods now have a ``numeric_only`` parameter (:issue:`53072`)\n - :meth:`DataFrame.ewm` now allows ``adjust=False`` when ``times`` is provided (:issue:`54328`)\n-- :meth:`DataFrame.fillna` and :meth:`Series.fillna` can now accept ``value=None``; for non-object dtype the corresponding NA value will be used (:issue:`57723`)\n-- :meth:`DataFrame.pivot_table` and :func:`pivot_table` now allow the passing of keyword arguments to ``aggfunc`` through ``**kwargs`` (:issue:`57884`)\n-- :meth:`DataFrame.to_json` now encodes ``Decimal`` as strings instead of floats (:issue:`60698`)\n - :meth:`Series.cummin` and :meth:`Series.cummax` now supports :class:`CategoricalDtype` (:issue:`52335`)\n-- :meth:`Series.plot` now correctly handle the ``ylabel`` parameter for pie charts, allowing for explicit control over the y-axis label (:issue:`58239`)\n-- Added :meth:`.Rolling.pipe` and :meth:`.Expanding.pipe` (:issue:`57076`)\n-- :meth:`DataFrame.plot.scatter` argument ``c`` now accepts a column of strings, where rows with the same string are colored identically (:issue:`16827` and :issue:`16485`)\n-- :class:`.Easter` has gained a new constructor argument ``method`` which specifies the method used to calculate Easter — for example, [NAME_REDACTED] (:issue:`61665`)\n-- :class:`ArrowDtype` now supports ``pyarrow.JsonType`` (:issue:`60958`)\n-- :class:`DataFrameGroupBy` and :class:`SeriesGroupBy` methods ``sum``, ``mean``, ``median``, ``prod``, ``min``, ``max``, ``std``, ``var`` and ``sem`` now accept ``skipna`` parameter (:issue:`15675`)\n-- :class:`Holiday` constructor argument ``days_of_week`` will raise a ``ValueError`` when type is something other than ``None`` or ``tuple`` (:issue:`61658`)\n-- :class:`Holiday` has gained the constructor argument and field ``exclude_dates`` to exclude specific datetimes from a custom holiday calendar (:issue:`54382`)\n-- :func:`DataFrame.to_excel` has a new ``autofilter`` parameter to add automatic filters to all columns (:issue:`61194`)\n-- :func:`read_parquet` accepts ``to_pandas_kwargs`` which are forwarded to :meth:`pyarrow.Table.to_pandas` which enables passing additional keywords to customize the conversion to pandas, such as ``maps_as_pydicts`` to read the Parquet map data type as python dictionaries (:issue:`56842`)\n-- :meth:`.DataFrameGroupBy.transform`, :meth:`.SeriesGroupBy.transform`, :meth:`.DataFrameGroupBy.agg`, :meth:`.SeriesGroupBy.agg`, :meth:`.RollingGroupby.apply`, :meth:`.ExpandingGroupby.apply`, :meth:`.Rolling.apply`, :meth:`.Expanding.apply`, :meth:`.DataFrame.apply` with ``engine=\"numba\"`` now supports positional arguments passed as kwargs (:issue:`58995`)\n-- :meth:`.DataFrameGroupBy.transform`, :meth:`.SeriesGroupBy.transform`, :meth:`.DataFrameGroupBy.agg`, :meth:`.SeriesGroupBy.agg`, :meth:`.SeriesGroupBy.apply`, :meth:`.DataFrameGroupBy.apply` now support ``kurt`` (:issue:`40139`)\n-- :meth:`.Rolling.aggregate`, :meth:`.Expanding.aggregate` and :meth:`.ExponentialMovingWindow.aggregate` now accept :class:`NamedAgg` aggregations through ``**kwargs`` (:issue:`28333`)\n-- :meth:`DataFrame.apply` supports using third-party execution engines like the Bodo.ai JIT compiler (:issue:`60668`)\n-- :meth:`DataFrame.iloc` and :meth:`Series.iloc` now support boolean masks in ``__getitem__`` for more consistent indexing behavior (:issue:`60994`)\n-- :meth:`DataFrame.to_csv` and :meth:`Series.to_csv` now support f-strings (e.g., ``\"{:.6f}\"``) for the ``float_format`` parameter, in addition to the ``%`` format strings and callables (:issue:`49580`)\n - :meth:`Series.map` can now accept kwargs to pass on to func (:issue:`59814`)\n-- :meth:`Series.map` now accepts an ``engine`` parameter to allow execution with a third-party execution engine (:issue:`61125`)\n - :meth:`Series.nlargest` uses stable sort internally and will preserve original ordering in the case of equality (:issue:`55767`)\n-- :meth:`Series.rank` and :meth:`DataFrame.rank` with numpy-nullable dtypes preserve ``NA`` values and return ``UInt64`` dtype where appropriate instead of casting ``NA`` to ``NaN`` with ``float64`` dtype (:issue:`62043`)\n+- :meth:`Series.round` now supports object dtypes when the underlying Python objects implement ``__round__`` (:issue:`63444`)\n+- Support passing a :class:`Iterable[Hashable]` input to :meth:`DataFrame.drop_duplicates` (:issue:`59237`)\n+\n+Strings:\n+\n - :meth:`Series.str.get_dummies` now accepts a ``dtype`` parameter to specify the dtype of the resulting DataFrame (:issue:`47872`)\n-- :meth:`pandas.concat` will raise a ``ValueError`` when ``ignore_index=True`` and ``keys`` is not ``None`` (:issue:`59274`)\n-- :py:class:`frozenset` elements in pandas objects are now natively printed (:issue:`60690`)\n-- Added :meth:`.Rolling.first`, :meth:`.Rolling.last`, :meth:`.Expanding.first`, and :meth:`.Expanding.last` (:issue:`33155`)\n-- Added :meth:`.Rolling.nunique` and :meth:`.Expanding.nunique` (:issue:`26958`)\n - Added :meth:`Series.str.isascii` (:issue:`59091`)\n-- Added ``\"delete_rows\"`` option to ``if_exists`` argument in :meth:`DataFrame.to_sql` deleting all records of the table before inserting data (:issue:`37210`).\n+- Allow dictionaries to be passed to :meth:`Series.str.replace` via ``pat`` parameter (:issue:`51748`)\n+\n+Datetimelike:\n+\n+- :class:`.Easter` has gained a new constructor argument ``method`` which specifies the method used to calculate Easter — for example, [NAME_REDACTED] (:issue:`61665`)\n+- :class:`Holiday` constructor argument ``days_of_week`` will raise a ``ValueError`` when type is something other than ``None`` or ``tuple`` (:issue:`61658`)\n+- :class:`Holiday` has gained the constructor argument and field ``exclude_dates`` to exclude specific datetimes from a custom holiday calendar (:issue:`54382`)\n - Added half-year offset classes :class:`.HalfYearBegin`, :class:`.HalfYearEnd`, :class:`.BHalfYearBegin` and :class:`.BHalfYearEnd` (:issue:`60928`)\n-- Added support for ``axis=1`` with ``dict`` or :class:`Series` arguments in :meth:`DataFrame.fillna` (:issue:`4514`)\n-- Added support to read and write from and to [NAME_REDACTED] tables with the new :func:`read_iceberg` and :meth:`DataFrame.to_iceberg` functions (:issue:`61383`)\n-- Errors occurring during SQL I/O will now throw a generic :class:`.DatabaseError` instead of the raw Exception type from the underlying driver manager library (:issue:`60748`)\n-- Improve error reporting through outputting the first few duplicates when :func:`merge` validation fails (:issue:`62742`)\n-- Improve the resulting dtypes in :meth:`DataFrame.where` and :meth:`DataFrame.mask` with :class:`ExtensionDtype` ``other`` (:issue:`62038`)\n - Improved deprecation message for offset aliases (:issue:`60820`)\n-- Many type aliases are now exposed in the new submodule :py:mod:`pandas.api.typing.aliases` (:issue:`55231`)\n - Multiplying two :class:`DateOffset` objects will now raise a ``TypeError`` instead of a ``RecursionError`` (:issue:`59442`)\n-- Restore support for reading Stata 104-format and enable reading 103-format dta files (:issue:`58554`)\n-- Support passing a :class:`Iterable[Hashable]` input to :meth:`DataFrame.drop_duplicates` (:issue:`59237`)\n-- Support reading Stata 102-format (Stata 1) dta files (:issue:`58978`)\n-- Support reading Stata 110-format (Stata 7) dta files (:issue:`47176`)\n+\n+Indexing:\n+\n+- :meth:`DataFrame.iloc` and :meth:`Series.iloc` now support boolean masks in ``__getitem__`` for more consistent indexing behavior (:issue:`60994`)\n+- :meth:`Index.get_loc` now accepts also subclasses of ``tuple`` as keys (:issue:`57922`)\n+\n+Styler / output formatting:\n+\n+- :meth:`.Styler.set_tooltips` provides alternative method to storing tooltips by [NAME_REDACTED] td elements. (:issue:`56981`)\n+- Added :meth:`.Styler.to_typst` to write Styler objects to file, buffer or string in Typst format (:issue:`57617`)\n+- :meth:`.Styler.format_index_names` can now be used to format the index and column names (:issue:`48936` and :issue:`47489`)\n+- :py:class:`frozenset` elements in pandas objects are now natively printed (:issue:`60690`)\n+\n+Typing:\n+\n+- :class:`pandas.api.typing.FrozenList` is available for typing the outputs of :attr:`MultiIndex.names`, :attr:`MultiIndex.codes` and :attr:`MultiIndex.levels` (:issue:`58237`)\n+- :class:`pandas.api.typing.NoDefault` is available for typing ``no_default`` (:issue:`60696`)\n+- :class:`pandas.api.typing.SASReader` is available for typing the output of :func:`read_sas` (:issue:`55689`)\n+- Many type aliases are now exposed in the new submodule :py:mod:`pandas.api.typing.aliases` (:issue:`55231`)\n+\n+Plotting:\n+\n+- :meth:`Series.plot` now correctly handle the ``ylabel`` parameter for pie charts, allowing for explicit control over the y-axis label (:issue:`58239`)\n+- Added missing parameter ``weights`` in :meth:`DataFrame.plot.kde` for the estimation of the PDF (:issue:`59337`)\n+- :meth:`DataFrame.plot.scatter` argument ``c`` now accepts a column of strings, where rows with the same string are colored identically (:issue:`16827` and :issue:`16485`)\n+\n+ExtensionArray:\n+\n+- :class:`ArrowDtype` now supports ``pyarrow.JsonType`` (:issue:`60958`)\n+- :meth:`Series.rank` and :meth:`DataFrame.rank` with numpy-nullable dtypes preserve ``NA`` values and return ``UInt64`` dtype where appropriate instead of casting ``NA`` to ``NaN`` with ``float64`` dtype (:issue:`62043`)\n+- Improve the resulting dtypes in :meth:`DataFrame.where` and :meth:`DataFrame.mask` with :class:`ExtensionDtype` ``other`` (:issue:`62038`)\n+\n+Other:\n+\n+- :func:`set_option` now accepts a dictionary of options, simplifying configuration of multiple settings at once (:issue:`61093`)\n+- :meth:`DataFrame.apply` supports using third-party execution engines like the Bodo.ai JIT compiler (:issue:`60668`)\n+- :meth:`Series.map` now accepts an ``engine`` parameter to allow execution with a third-party execution engine (:issue:`61125`)\n+- Support passing a :class:`Series` input to :func:`json_normalize` that retains the :class:`Index` (:issue:`51452`)\n+- Users can globally disable any ``PerformanceWarning`` by [NAME_REDACTED] ``mode.performance_warnings`` to ``False`` (:issue:`56920`)\n+\n+Packaging:\n+\n - Switched wheel upload to **[NAME_REDACTED]** (OIDC) for release-tag pushes in ``wheels.yml``. (:issue:`61718`)\n-- Added :meth:`DataFrame.from_arrow` and :meth:`Series.from_arrow` to import any Arrow-compatible\n- data object into a pandas object through the\n- `[NAME_REDACTED] `__ (:issue:`59631`)\n-- :meth:`Series.round` now supports object dtypes when the underlying Python objects implement ``__round__`` (:issue:`63444`)\n+- Wheels are now available for Windows ARM64 architecture (:issue:`61462`)\n+- Wheels are now available for free-threading Python builds on Windows (in addition to the other platforms) (:issue:`61463`)\n+\n \n .. ---------------------------------------------------------------------------\n .. _whatsnew_300.notable_bug_fixes:" } ], "reviews": [ { "id": 3679787148, "user": "user_c9260bc45a59", "state": "COMMENTED", "body": null, "submitted_at": "2026-01-19T22:33:08+00:00" }, { "id": 3679788546, "user": "user_c9260bc45a59", "state": "COMMENTED", "body": null, "submitted_at": "2026-01-19T22:34:16+00:00" } ], "review_comments": [ { "id": 2706234234, "user": "user_c9260bc45a59", "body": "+1 to remove", "path": "doc/source/whatsnew/v3.0.0.rst", "line": null, "side": "RIGHT", "created_at": "2026-01-19T22:33:08+00:00" }, { "id": 2706235618, "user": "user_c9260bc45a59", "body": "No strong opinion, but IMO in `Other` would be fine", "path": "doc/source/whatsnew/v3.0.0.rst", "line": null, "side": "RIGHT", "created_at": "2026-01-19T22:34:16+00:00" } ], "meta": { "languages": [ "rst" ], "touches_tests": false, "review_state_summary": { "COMMENTED": 2 }, "meaningful_comment_count": 2, "has_approval": false, "has_changes_requested": false, "total_review_comments": 2 } } { "_id": "53cb112e0e7e2250", "_schema_version": "1.0", "_cleaned_at": "2026-02-12T07:46:51.845010+00:00", "repo": "pandas-dev/pandas", "repo_url": "https://github.com/pandas-dev/pandas", "license_name": "BSD 3-Clause \"New\" or \"Revised\" License", "license_spdx": "BSD-3-Clause", "pr_number": 63760, "title": "API: Period.to_timestamp default to microsecond unit", "body": "- [ ] closes #xxxx (Replace xxxx with the GitHub issue number)\n- [x] [Tests added and passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#writing-tests) if fixing a bug or adding a new feature\n- [x] All [code checks passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit).\n- [ ] Added [type annotations](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#type-hints) to new arguments/methods/functions.\n- [x] Added an entry in the latest `doc/source/whatsnew/vX.X.X.rst` file if fixing a bug or adding a new feature.\n- [ ] If I used AI to develop this pull request, I prompted it to follow `AGENTS.md`.\n\ncc [USER_REDACTED] do we want to get this in under the wire?", "author": "user_fb5fa0a10142", "created_at": "2026-01-19T20:56:51+00:00", "merged_at": "2026-01-21T10:18:40+00:00", "base_branch": "main", "head_branch": "api-to_timestamp", "additions": 169, "deletions": 147, "changed_files": 15, "files": [ { "filename": "doc/source/whatsnew/v3.0.0.rst", "status": "modified", "additions": 1, "deletions": 0, "changes": 1, "patch": "@@ -800,6 +800,7 @@ Other API changes\n ^^^^^^^^^^^^^^^^^\n - 3rd party ``py.path`` objects are no longer explicitly supported in IO methods. Use :py:class:`pathlib.Path` objects instead (:issue:`57091`)\n - :func:`read_table`'s ``parse_dates`` argument defaults to ``None`` to improve consistency with :func:`read_csv` (:issue:`57476`)\n+- :meth:`Period.to_timestamp` and :meth:`PeriodIndex.to_timestamp` now give microsecond-unit objects when possible, and nanosecond-unit objects in other cases. This affects the actual value of :meth:`Period.end_time` and :meth:`PeriodIndex.end_time` (:issue:`56164`)\n - All classes inheriting from builtin ``tuple`` (including types created with :func:`collections.namedtuple`) are now hashed and compared as builtin ``tuple`` during indexing operations (:issue:`57922`)\n - Made ``dtype`` a required argument in :meth:`ExtensionArray._from_sequence_of_strings` (:issue:`56519`)\n - Passing a :class:`Series` input to :func:`json_normalize` will now retain the :class:`Series` :class:`Index`, previously output had a new :class:`RangeIndex` (:issue:`51452`)" }, { "filename": "pandas/_libs/tslibs/period.pyx", "status": "modified", "additions": 41, "deletions": 26, "changes": 67, "patch": "@@ -38,7 +38,10 @@ from libc.time cimport (\n tm,\n )\n \n-from pandas._libs.tslibs.dtypes cimport c_OFFSET_TO_PERIOD_FREQSTR\n+from pandas._libs.tslibs.dtypes cimport (\n+ PeriodDtypeCode,\n+ c_OFFSET_TO_PERIOD_FREQSTR,\n+)\n \n from pandas._libs.tslibs.np_datetime import OutOfBoundsDatetime\n \n@@ -69,13 +72,6 @@ from pandas._libs.tslibs.ccalendar cimport (\n get_week_of_year,\n is_leapyear,\n )\n-from pandas._libs.tslibs.timedeltas cimport (\n- delta_to_nanoseconds,\n- is_any_td_scalar,\n-)\n-\n-from pandas._libs.tslibs.conversion import DT64NS_DTYPE\n-\n from pandas._libs.tslibs.dtypes cimport (\n FR_ANN,\n FR_BUS,\n@@ -95,6 +91,10 @@ from pandas._libs.tslibs.dtypes cimport (\n freq_group_code_to_npy_unit,\n )\n from pandas._libs.tslibs.parsing cimport quarter_to_myear\n+from pandas._libs.tslibs.timedeltas cimport (\n+ delta_to_nanoseconds,\n+ is_any_td_scalar,\n+)\n \n from pandas._libs.tslibs.parsing import parse_datetime_string_with_reso\n \n@@ -973,13 +973,13 @@ def periodarr_to_dt64arr(const int64_t[:] periodarr, int freq):\n for i in range(N):\n out[i] = period_ordinal_to_dt64(periodarr[i], freq)\n \n- return out.base # .base to access underlying np.ndarray\n+ return out.base.view(\"M8[us]\") # .base to access underlying np.ndarray\n \n else:\n # Short-circuit for performance\n if freq == FR_NS:\n # TODO: copy?\n- return periodarr.base\n+ return periodarr.base.view(\"M8[ns]\")\n \n if freq == FR_US:\n dta = periodarr.base.view(\"M8[us]\")\n@@ -993,7 +993,8 @@ def periodarr_to_dt64arr(const int64_t[:] periodarr, int freq):\n dta = periodarr.base.view(\"M8[h]\")\n elif freq == FR_DAY:\n dta = periodarr.base.view(\"M8[D]\")\n- return astype_overflowsafe(dta, dtype=DT64NS_DTYPE)\n+ # GH#63760 give microseconds for everything other than freq=\"ns\"\n+ return astype_overflowsafe(dta, dtype=np.dtype(\"M8[us]\"))\n \n \n cdef void get_asfreq_info(int from_freq, int to_freq,\n@@ -1161,13 +1162,19 @@ cdef int64_t period_ordinal_to_dt64(int64_t ordinal, int freq) except? -1:\n if ordinal == NPY_NAT:\n return NPY_NAT\n \n+ if freq == PeriodDtypeCode.N:\n+ # We have to return nanosecond unit, but this is a no-op\n+ return ordinal\n+\n get_date_info(ordinal, freq, &dts)\n \n try:\n- result = npy_datetimestruct_to_datetime(NPY_DATETIMEUNIT.NPY_FR_ns, &dts)\n+ result = npy_datetimestruct_to_datetime(NPY_DATETIMEUNIT.NPY_FR_us, &dts)\n except OverflowError as err:\n fmt = dts_to_iso_string(&dts)\n- raise OutOfBoundsDatetime(f\"Out of bounds nanosecond timestamp: {fmt}\") from err\n+ raise OutOfBoundsDatetime(\n+ f\"Out of bounds microsecond timestamp: {fmt}\"\n+ ) from err\n \n return result\n \n@@ -1681,7 +1688,7 @@ cdef class PeriodMixin:\n Timestamp('2012-01-01 00:00:00')\n \n >>> period.end_time\n- Timestamp('2012-01-01 23:59:59.999999999')\n+ Timestamp('2012-01-01 23:59:59.999999')\n \"\"\"\n return self.to_timestamp(how=\"start\")\n \n@@ -1706,7 +1713,7 @@ cdef class PeriodMixin:\n For Period:\n \n >>> pd.Period('2020-01', 'D').end_time\n- Timestamp('2020-01-01 23:59:59.999999999')\n+ Timestamp('2020-01-01 23:59:59.999999')\n \n For Series:\n \n@@ -1718,19 +1725,19 @@ cdef class PeriodMixin:\n 2 2020-03\n dtype: period[M]\n >>> s.dt.end_time\n- 0 2020-01-31 23:59:59.999999999\n- 1 2020-02-29 23:59:59.999999999\n- 2 2020-03-31 23:59:59.999999999\n- dtype: datetime64[ns]\n+ 0 2020-01-31 23:59:59.999999\n+ 1 2020-02-29 23:59:59.999999\n+ 2 2020-03-31 23:59:59.999999\n+ dtype: datetime64[us]\n \n For PeriodIndex:\n \n >>> idx = pd.PeriodIndex([\"2023-01\", \"2023-02\", \"2023-03\"], freq=\"M\")\n >>> idx.end_time\n- DatetimeIndex(['2023-01-31 23:59:59.999999999',\n- '2023-02-28 23:59:59.999999999',\n- '2023-03-31 23:59:59.999999999'],\n- dtype='datetime64[ns]', freq=None)\n+ DatetimeIndex(['2023-01-31 23:59:59.999999',\n+ '2023-02-28 23:59:59.999999',\n+ '2023-03-31 23:59:59.999999'],\n+ dtype='datetime64[us]', freq=None)\n \"\"\"\n return self.to_timestamp(how=\"end\")\n \n@@ -2061,6 +2068,9 @@ cdef class _Period(PeriodMixin):\n Uses the target frequency specified at the part of the period specified\n by `how`, which is either `Start` or `Finish`.\n \n+ If possible, gives microsecond-unit Timestamp. Otherwise gives nanosecond\n+ unit.\n+\n Parameters\n ----------\n freq : str or DateOffset\n@@ -2089,14 +2099,19 @@ cdef class _Period(PeriodMixin):\n \"\"\"\n how = validate_end_alias(how)\n \n+ if self._dtype._dtype_code == PeriodDtypeCode.N or freq == \"ns\":\n+ unit = \"ns\"\n+ else:\n+ unit = \"us\"\n+\n end = how == \"E\"\n if end:\n if freq == \"B\" or self._freq == \"B\":\n # roll forward to ensure we land on B date\n- adjust = np.timedelta64(1, \"D\") - np.timedelta64(1, \"ns\")\n+ adjust = np.timedelta64(1, \"D\") - np.timedelta64(1, unit)\n return self.to_timestamp(how=\"start\") + adjust\n endpoint = (self + self._freq).to_timestamp(how=\"start\")\n- return endpoint - np.timedelta64(1, \"ns\")\n+ return endpoint - np.timedelta64(1, unit)\n \n if freq is None:\n freq_code = self._dtype._get_to_timestamp_base()\n@@ -2110,7 +2125,7 @@ cdef class _Period(PeriodMixin):\n val = self.asfreq(freq, how)\n \n dt64 = period_ordinal_to_dt64(val.ordinal, base)\n- return Timestamp(dt64)\n+ return Timestamp(dt64, unit=unit)\n \n [USER_REDACTED]\n def year(self) -> int:" }, { "filename": "pandas/core/arrays/period.py", "status": "modified", "additions": 15, "deletions": 6, "changes": 21, "patch": "@@ -759,6 +759,9 @@ def to_timestamp(self, freq=None, how: str = \"start\") -> DatetimeArray:\n \"\"\"\n Cast to DatetimeArray/Index.\n \n+ If possible, gives microsecond-unit DatetimeArray/Index. Otherwise\n+ gives nanosecond unit.\n+\n Parameters\n ----------\n freq : str or DateOffset, optional\n@@ -789,34 +792,39 @@ def to_timestamp(self, freq=None, how: str = \"start\") -> DatetimeArray:\n >>> idx = pd.PeriodIndex([\"2023-01\", \"2023-02\", \"2023-03\"], freq=\"M\")\n >>> idx.to_timestamp()\n DatetimeIndex(['2023-01-01', '2023-02-01', '2023-03-01'],\n- dtype='datetime64[ns]', freq='MS')\n+ dtype='datetime64[us]', freq='MS')\n \n The frequency will not be inferred if the index contains less than\n three elements, or if the values of index are not strictly monotonic:\n \n >>> idx = pd.PeriodIndex([\"2023-01\", \"2023-02\"], freq=\"M\")\n >>> idx.to_timestamp()\n- DatetimeIndex(['2023-01-01', '2023-02-01'], dtype='datetime64[ns]', freq=None)\n+ DatetimeIndex(['2023-01-01', '2023-02-01'], dtype='datetime64[us]', freq=None)\n \n >>> idx = pd.PeriodIndex(\n ... [\"2023-01\", \"2023-02\", \"2023-02\", \"2023-03\"], freq=\"2M\"\n ... )\n >>> idx.to_timestamp()\n DatetimeIndex(['2023-01-01', '2023-02-01', '2023-02-01', '2023-03-01'],\n- dtype='datetime64[ns]', freq=None)\n+ dtype='datetime64[us]', freq=None)\n \"\"\"\n from pandas.core.arrays import DatetimeArray\n \n how = libperiod.validate_end_alias(how)\n \n+ if self.freq.base == \"ns\" or freq == \"ns\":\n+ unit = \"ns\"\n+ else:\n+ unit = \"us\"\n+\n end = how == \"E\"\n if end:\n if freq == \"B\" or self.freq == \"B\":\n # roll forward to ensure we land on B date\n- adjust = Timedelta(1, \"D\") - Timedelta(1, \"ns\")\n+ adjust = Timedelta(1, unit=\"D\") - Timedelta(1, unit=unit)\n return self.to_timestamp(how=\"start\") + adjust\n else:\n- adjust = Timedelta(1, \"ns\")\n+ adjust = Timedelta(1, unit=unit)\n return (self + self.freq).to_timestamp(how=\"start\") - adjust\n \n if freq is None:\n@@ -831,7 +839,8 @@ def to_timestamp(self, freq=None, how: str = \"start\") -> DatetimeArray:\n new_parr = self.asfreq(freq, how=how)\n \n new_data = libperiod.periodarr_to_dt64arr(new_parr.asi8, base)\n- dta = DatetimeArray._from_sequence(new_data, dtype=np.dtype(\"M8[ns]\"))\n+ dta = DatetimeArray._from_sequence(new_data, dtype=new_data.dtype)\n+ assert dta.unit == unit\n \n if self.freq.name == \"B\":\n # See if we can retain BDay instead of Day in cases where" }, { "filename": "pandas/core/frame.py", "status": "modified", "additions": 2, "deletions": 2, "changes": 4, "patch": "@@ -16256,7 +16256,7 @@ def to_timestamp(\n 2023-01-01 1 3\n 2024-01-01 2 4\n >>> df1.index\n- DatetimeIndex(['2023-01-01', '2024-01-01'], dtype='datetime64[ns]', freq=None)\n+ DatetimeIndex(['2023-01-01', '2024-01-01'], dtype='datetime64[us]', freq=None)\n \n Using `freq` which is the offset that the Timestamps will have\n \n@@ -16267,7 +16267,7 @@ def to_timestamp(\n 2023-01-31 1 3\n 2024-01-31 2 4\n >>> df2.index\n- DatetimeIndex(['2023-01-31', '2024-01-31'], dtype='datetime64[ns]', freq=None)\n+ DatetimeIndex(['2023-01-31', '2024-01-31'], dtype='datetime64[us]', freq=None)\n \"\"\"\n self._check_copy_deprecation(copy)\n new_obj = self.copy(deep=False)" }, { "filename": "pandas/core/indexes/datetimes.py", "status": "modified", "additions": 4, "deletions": 1, "changes": 5, "patch": "@@ -896,7 +896,10 @@ def _parsed_string_to_bounds(\n \"\"\"\n freq = OFFSET_TO_PERIOD_FREQSTR.get(reso.attr_abbrev, reso.attr_abbrev)\n per = Period(parsed, freq=freq)\n- start, end = per.start_time, per.end_time\n+ start = per.start_time\n+ # Can't use end_time here bc that will subtract a microsecond\n+ # instead of a nanosecond\n+ end = (per + 1).start_time - np.timedelta64(1, \"ns\")\n start = start.as_unit(self.unit)\n end = end.as_unit(self.unit)" }, { "filename": "pandas/tests/arrays/test_datetimelike.py", "status": "modified", "additions": 6, "deletions": 10, "changes": 16, "patch": "@@ -8,7 +8,6 @@\n \n from pandas._libs import (\n NaT,\n- OutOfBoundsDatetime,\n Timestamp,\n )\n from pandas._libs.tslibs import to_offset\n@@ -1110,28 +1109,25 @@ def test_to_timestamp_roundtrip_bday(self):\n parr = dta.to_period()\n result = parr.to_timestamp()\n assert result.freq == \"B\"\n- tm.assert_extension_array_equal(result, dta)\n+ tm.assert_extension_array_equal(result, dta.as_unit(\"us\"))\n \n dta2 = dta[::2]\n parr2 = dta2.to_period()\n result2 = parr2.to_timestamp()\n assert result2.freq == \"2B\"\n- tm.assert_extension_array_equal(result2, dta2)\n+ tm.assert_extension_array_equal(result2, dta2.as_unit(\"us\"))\n \n parr3 = dta.to_period(\"2B\")\n result3 = parr3.to_timestamp()\n assert result3.freq == \"B\"\n- tm.assert_extension_array_equal(result3, dta)\n+ tm.assert_extension_array_equal(result3, dta.as_unit(\"us\"))\n \n def test_to_timestamp_out_of_bounds(self):\n # GH#19643 previously overflowed silently\n pi = pd.period_range(\"1500\", freq=\"Y\", periods=3)\n- msg = \"Out of bounds nanosecond timestamp: 1500-01-01 00:00:00\"\n- with pytest.raises(OutOfBoundsDatetime, match=msg):\n- pi.to_timestamp()\n-\n- with pytest.raises(OutOfBoundsDatetime, match=msg):\n- pi._data.to_timestamp()\n+ pi.to_timestamp()\n+ dta = pi._data.to_timestamp()\n+ assert dta[0] == Timestamp(1500, 1, 1)\n \n [USER_REDACTED].mark.parametrize(\"propname\", PeriodArray._bool_ops)\n def test_bool_properties(self, arr1d, propname):" }, { "filename": "pandas/tests/frame/methods/test_to_csv.py", "status": "modified", "additions": 2, "deletions": 2, "changes": 4, "patch": "@@ -393,11 +393,11 @@ def test_to_csv_idx_types(self, nrows, r_idx_type, c_idx_type, ncols, temp_file)\n if r_idx_type == \"dt\":\n expected.index = expected.index.astype(\"M8[us]\")\n elif r_idx_type == \"p\":\n- expected.index = expected.index.astype(\"M8[ns]\")\n+ expected.index = expected.index.astype(\"M8[us]\")\n if c_idx_type == \"dt\":\n expected.columns = expected.columns.astype(\"M8[us]\")\n elif c_idx_type == \"p\":\n- expected.columns = expected.columns.astype(\"M8[ns]\")\n+ expected.columns = expected.columns.astype(\"M8[us]\")\n tm.assert_frame_equal(result, expected, check_names=False)\n \n [USER_REDACTED].mark.slow" }, { "filename": "pandas/tests/frame/methods/test_to_timestamp.py", "status": "modified", "additions": 15, "deletions": 18, "changes": 33, "patch": "@@ -21,7 +21,6 @@ def _get_with_delta(delta, freq=\"YE-DEC\"):\n to_datetime(\"1/1/2001\") + delta,\n to_datetime(\"12/31/2009\") + delta,\n freq=freq,\n- unit=\"ns\",\n )\n \n \n@@ -37,15 +36,15 @@ def test_to_timestamp(self, frame_or_series):\n obj[\"mix\"] = \"a\"\n obj = tm.get_obj(obj, frame_or_series)\n \n- exp_index = date_range(\"1/1/2001\", end=\"12/31/2009\", freq=\"YE-DEC\", unit=\"ns\")\n- exp_index = exp_index + Timedelta(1, \"D\") - Timedelta(1, \"ns\")\n+ exp_index = date_range(\"1/1/2001\", end=\"12/31/2009\", freq=\"YE-DEC\")\n+ exp_index = exp_index + Timedelta(1, \"D\") - Timedelta(1, \"us\")\n result = obj.to_timestamp(\"D\", \"end\")\n tm.assert_index_equal(result.index, exp_index)\n tm.assert_numpy_array_equal(result.values, obj.values)\n if frame_or_series is Series:\n assert result.name == \"A\"\n \n- exp_index = date_range(\"1/1/2001\", end=\"1/1/2009\", freq=\"YS-JAN\", unit=\"ns\")\n+ exp_index = date_range(\"1/1/2001\", end=\"1/1/2009\", freq=\"YS-JAN\")\n result = obj.to_timestamp(\"D\", \"start\")\n tm.assert_index_equal(result.index, exp_index)\n \n@@ -55,19 +54,19 @@ def test_to_timestamp(self, frame_or_series):\n delta = timedelta(hours=23)\n result = obj.to_timestamp(\"H\", \"end\")\n exp_index = _get_with_delta(delta)\n- exp_index = exp_index + Timedelta(1, \"h\") - Timedelta(1, \"ns\")\n+ exp_index = exp_index + Timedelta(1, \"h\") - Timedelta(1, \"us\")\n tm.assert_index_equal(result.index, exp_index)\n \n delta = timedelta(hours=23, minutes=59)\n result = obj.to_timestamp(\"T\", \"end\")\n exp_index = _get_with_delta(delta)\n- exp_index = exp_index + Timedelta(1, \"m\") - Timedelta(1, \"ns\")\n+ exp_index = exp_index + Timedelta(1, \"m\") - Timedelta(1, \"us\")\n tm.assert_index_equal(result.index, exp_index)\n \n result = obj.to_timestamp(\"S\", \"end\")\n delta = timedelta(hours=23, minutes=59, seconds=59)\n exp_index = _get_with_delta(delta)\n- exp_index = exp_index + Timedelta(1, \"s\") - Timedelta(1, \"ns\")\n+ exp_index = exp_index + Timedelta(1, \"s\") - Timedelta(1, \"us\")\n tm.assert_index_equal(result.index, exp_index)\n \n def test_to_timestamp_columns(self):\n@@ -83,37 +82,37 @@ def test_to_timestamp_columns(self):\n # columns\n df = df.T\n \n- exp_index = date_range(\"1/1/2001\", end=\"12/31/2009\", freq=\"YE-DEC\", unit=\"ns\")\n- exp_index = exp_index + Timedelta(1, \"D\") - Timedelta(1, \"ns\")\n+ exp_index = date_range(\"1/1/2001\", end=\"12/31/2009\", freq=\"YE-DEC\")\n+ exp_index = exp_index + Timedelta(1, \"D\") - Timedelta(1, \"us\")\n result = df.to_timestamp(\"D\", \"end\", axis=1)\n tm.assert_index_equal(result.columns, exp_index)\n tm.assert_numpy_array_equal(result.values, df.values)\n \n- exp_index = date_range(\"1/1/2001\", end=\"1/1/2009\", freq=\"YS-JAN\", unit=\"ns\")\n+ exp_index = date_range(\"1/1/2001\", end=\"1/1/2009\", freq=\"YS-JAN\")\n result = df.to_timestamp(\"D\", \"start\", axis=1)\n tm.assert_index_equal(result.columns, exp_index)\n \n delta = timedelta(hours=23)\n result = df.to_timestamp(\"H\", \"end\", axis=1)\n exp_index = _get_with_delta(delta)\n- exp_index = exp_index + Timedelta(1, \"h\") - Timedelta(1, \"ns\")\n+ exp_index = exp_index + Timedelta(1, \"h\") - Timedelta(1, \"us\")\n tm.assert_index_equal(result.columns, exp_index)\n \n delta = timedelta(hours=23, minutes=59)\n result = df.to_timestamp(\"min\", \"end\", axis=1)\n exp_index = _get_with_delta(delta)\n- exp_index = exp_index + Timedelta(1, \"m\") - Timedelta(1, \"ns\")\n+ exp_index = exp_index + Timedelta(1, \"m\") - Timedelta(1, \"us\")\n tm.assert_index_equal(result.columns, exp_index)\n \n result = df.to_timestamp(\"S\", \"end\", axis=1)\n delta = timedelta(hours=23, minutes=59, seconds=59)\n exp_index = _get_with_delta(delta)\n- exp_index = exp_index + Timedelta(1, \"s\") - Timedelta(1, \"ns\")\n+ exp_index = exp_index + Timedelta(1, \"s\") - Timedelta(1, \"us\")\n tm.assert_index_equal(result.columns, exp_index)\n \n result1 = df.to_timestamp(\"5min\", axis=1)\n result2 = df.to_timestamp(\"min\", axis=1)\n- expected = date_range(\"2001-01-01\", \"2009-01-01\", freq=\"YS\", unit=\"ns\")\n+ expected = date_range(\"2001-01-01\", \"2009-01-01\", freq=\"YS\")\n assert isinstance(result1.columns, DatetimeIndex)\n assert isinstance(result2.columns, DatetimeIndex)\n tm.assert_numpy_array_equal(result1.columns.asi8, expected.asi8)\n@@ -138,11 +137,9 @@ def test_to_timestamp_hourly(self, frame_or_series):\n if frame_or_series is not Series:\n obj = obj.to_frame()\n \n- exp_index = date_range(\n- \"1/1/2001 00:59:59\", end=\"1/2/2001 00:59:59\", freq=\"h\", unit=\"ns\"\n- )\n+ exp_index = date_range(\"1/1/2001 00:59:59\", end=\"1/2/2001 00:59:59\", freq=\"h\")\n result = obj.to_timestamp(how=\"end\")\n- exp_index = exp_index + Timedelta(1, \"s\") - Timedelta(1, \"ns\")\n+ exp_index = exp_index + Timedelta(1, \"s\") - Timedelta(1, \"us\")\n tm.assert_index_equal(result.index, exp_index)\n if frame_or_series is Series:\n assert result.name == \"foo\"" }, { "filename": "pandas/tests/indexes/datetimes/methods/test_to_period.py", "status": "modified", "additions": 2, "deletions": 2, "changes": 4, "patch": "@@ -120,11 +120,11 @@ def test_to_period_infer(self):\n def test_period_dt64_round_trip(self):\n dti = date_range(\"1/1/2000\", \"1/7/2002\", freq=\"B\", unit=\"ns\")\n pi = dti.to_period()\n- tm.assert_index_equal(pi.to_timestamp(), dti)\n+ tm.assert_index_equal(pi.to_timestamp(), dti.as_unit(\"us\"))\n \n dti = date_range(\"1/1/2000\", \"1/7/2002\", freq=\"B\", unit=\"ns\")\n pi = dti.to_period(freq=\"h\")\n- tm.assert_index_equal(pi.to_timestamp(), dti)\n+ tm.assert_index_equal(pi.to_timestamp(), dti.as_unit(\"us\"))\n \n def test_to_period_millisecond(self):\n index = DatetimeIndex(" }, { "filename": "pandas/tests/indexes/period/methods/test_to_timestamp.py", "status": "modified", "additions": 16, "deletions": 16, "changes": 32, "patch": "@@ -22,34 +22,34 @@ def test_to_timestamp_non_contiguous(self):\n pi = dti.to_period()\n \n result = pi[::2].to_timestamp()\n- expected = dti[::2]\n+ expected = dti[::2].as_unit(\"us\")\n tm.assert_index_equal(result, expected)\n \n result = pi._data[::2].to_timestamp()\n- expected = dti._data[::2]\n+ expected = dti._data[::2].as_unit(\"us\")\n # TODO: can we get the freq to round-trip?\n tm.assert_datetime_array_equal(result, expected, check_freq=False)\n \n result = pi[::-1].to_timestamp()\n- expected = dti[::-1]\n+ expected = dti[::-1].as_unit(\"us\")\n tm.assert_index_equal(result, expected)\n \n result = pi._data[::-1].to_timestamp()\n- expected = dti._data[::-1]\n+ expected = dti._data[::-1].as_unit(\"us\")\n tm.assert_datetime_array_equal(result, expected, check_freq=False)\n \n result = pi[::2][::-1].to_timestamp()\n- expected = dti[::2][::-1]\n+ expected = dti[::2][::-1].as_unit(\"us\")\n tm.assert_index_equal(result, expected)\n \n result = pi._data[::2][::-1].to_timestamp()\n- expected = dti._data[::2][::-1]\n+ expected = dti._data[::2][::-1].as_unit(\"us\")\n tm.assert_datetime_array_equal(result, expected, check_freq=False)\n \n def test_to_timestamp_freq(self):\n idx = period_range(\"2017\", periods=12, freq=\"Y-DEC\")\n result = idx.to_timestamp()\n- expected = date_range(\"2017\", periods=12, freq=\"YS-JAN\", unit=\"ns\")\n+ expected = date_range(\"2017\", periods=12, freq=\"YS-JAN\")\n tm.assert_index_equal(result, expected)\n \n def test_to_timestamp_pi_nat(self):\n@@ -59,7 +59,7 @@ def test_to_timestamp_pi_nat(self):\n result = index.to_timestamp(\"D\")\n expected = DatetimeIndex(\n [NaT, datetime(2011, 1, 1), datetime(2011, 2, 1)],\n- dtype=\"M8[ns]\",\n+ dtype=\"M8[us]\",\n name=\"idx\",\n )\n tm.assert_index_equal(result, expected)\n@@ -101,38 +101,38 @@ def test_to_timestamp_pi_mult(self):\n \n result = idx.to_timestamp()\n expected = DatetimeIndex(\n- [\"2011-01-01\", \"NaT\", \"2011-02-01\"], dtype=\"M8[ns]\", name=\"idx\"\n+ [\"2011-01-01\", \"NaT\", \"2011-02-01\"], dtype=\"M8[us]\", name=\"idx\"\n )\n tm.assert_index_equal(result, expected)\n \n result = idx.to_timestamp(how=\"E\")\n expected = DatetimeIndex(\n- [\"2011-02-28\", \"NaT\", \"2011-03-31\"], dtype=\"M8[ns]\", name=\"idx\"\n+ [\"2011-02-28\", \"NaT\", \"2011-03-31\"], dtype=\"M8[us]\", name=\"idx\"\n )\n- expected = expected + Timedelta(1, \"D\") - Timedelta(1, \"ns\")\n+ expected = expected + Timedelta(1, \"D\") - Timedelta(1, \"us\")\n tm.assert_index_equal(result, expected)\n \n def test_to_timestamp_pi_combined(self):\n idx = period_range(start=\"2011\", periods=2, freq=\"1D1h\", name=\"idx\")\n \n result = idx.to_timestamp()\n expected = DatetimeIndex(\n- [\"2011-01-01 00:00\", \"2011-01-02 01:00\"], dtype=\"M8[ns]\", name=\"idx\"\n+ [\"2011-01-01 00:00\", \"2011-01-02 01:00\"], dtype=\"M8[us]\", name=\"idx\"\n )\n tm.assert_index_equal(result, expected)\n \n result = idx.to_timestamp(how=\"E\")\n expected = DatetimeIndex(\n- [\"2011-01-02 00:59:59\", \"2011-01-03 01:59:59\"], name=\"idx\", dtype=\"M8[ns]\"\n+ [\"2011-01-02 00:59:59\", \"2011-01-03 01:59:59\"], name=\"idx\", dtype=\"M8[us]\"\n )\n- expected = expected + Timedelta(1, \"s\") - Timedelta(1, \"ns\")\n+ expected = expected + Timedelta(1, \"s\") - Timedelta(1, \"us\")\n tm.assert_index_equal(result, expected)\n \n result = idx.to_timestamp(how=\"E\", freq=\"h\")\n expected = DatetimeIndex(\n- [\"2011-01-02 00:00\", \"2011-01-03 01:00\"], dtype=\"M8[ns]\", name=\"idx\"\n+ [\"2011-01-02 00:00\", \"2011-01-03 01:00\"], dtype=\"M8[us]\", name=\"idx\"\n )\n- expected = expected + Timedelta(1, \"h\") - Timedelta(1, \"ns\")\n+ expected = expected + Timedelta(1, \"h\") - Timedelta(1, \"us\")\n tm.assert_index_equal(result, expected)\n \n def test_to_timestamp_1703(self):" }, { "filename": "pandas/tests/indexes/period/test_scalar_compat.py", "status": "modified", "additions": 3, "deletions": 5, "changes": 8, "patch": "@@ -14,16 +14,14 @@ class TestPeriodIndexOps:\n def test_start_time(self):\n # GH#17157\n index = period_range(freq=\"M\", start=\"2016-01-01\", end=\"2016-05-31\")\n- expected_index = date_range(\n- \"2016-01-01\", end=\"2016-05-31\", freq=\"MS\", unit=\"ns\"\n- )\n+ expected_index = date_range(\"2016-01-01\", end=\"2016-05-31\", freq=\"MS\")\n tm.assert_index_equal(index.start_time, expected_index)\n \n def test_end_time(self):\n # GH#17157\n index = period_range(freq=\"M\", start=\"2016-01-01\", end=\"2016-05-31\")\n expected_index = date_range(\"2016-01-01\", end=\"2016-05-31\", freq=\"ME\")\n- expected_index += Timedelta(1, \"D\") - Timedelta(1, \"ns\")\n+ expected_index += Timedelta(1, \"D\") - Timedelta(1, \"us\")\n tm.assert_index_equal(index.end_time, expected_index)\n \n [USER_REDACTED].mark.filterwarnings(r\"ignore:PeriodDtype\\[B\\] is deprecated:FutureWarning\")\n@@ -36,5 +34,5 @@ def test_end_time_business_friday(self):\n result = pi.end_time\n \n dti = date_range(\"1990-01-05\", freq=\"D\", periods=1)._with_freq(None)\n- expected = dti + Timedelta(days=1, nanoseconds=-1)\n+ expected = dti + Timedelta(1, \"D\") - Timedelta(1, \"us\")\n tm.assert_index_equal(result, expected)" }, { "filename": "pandas/tests/plotting/test_datetimelike.py", "status": "modified", "additions": 1, "deletions": 0, "changes": 1, "patch": "@@ -682,6 +682,7 @@ def test_secondary_y_ts(self):\n axes = fig.get_axes()\n line = ax.get_lines()[0]\n xp = Series(line.get_ydata(), line.get_xdata()).to_timestamp()\n+ xp.index = xp.index.as_unit(\"ns\")\n tm.assert_series_equal(ser, xp)\n assert ax.get_yaxis().get_ticks_position() == \"right\"\n assert not axes[0].get_yaxis().get_visible()" }, { "filename": "pandas/tests/resample/test_datetime_index.py", "status": "modified", "additions": 4, "deletions": 4, "changes": 8, "patch": "@@ -1112,7 +1112,7 @@ def test_resample_anchored_intraday(unit):\n result = df.resample(\"ME\").mean()\n expected = df.resample(\"ME\").mean().to_period()\n expected = expected.to_timestamp(how=\"end\")\n- expected.index += Timedelta(1, \"ns\") - Timedelta(1, \"D\")\n+ expected.index += Timedelta(1, unit=\"us\") - Timedelta(1, unit=\"D\")\n expected.index = expected.index.as_unit(unit)._with_freq(\"infer\")\n assert expected.index.freq == \"ME\"\n tm.assert_frame_equal(result, expected)\n@@ -1121,7 +1121,7 @@ def test_resample_anchored_intraday(unit):\n exp = df.shift(1, freq=\"D\").resample(\"ME\").mean().to_period()\n exp = exp.to_timestamp(how=\"end\")\n \n- exp.index = exp.index + Timedelta(1, \"ns\") - Timedelta(1, \"D\")\n+ exp.index = exp.index + Timedelta(1, unit=\"us\") - Timedelta(1, unit=\"D\")\n exp.index = exp.index.as_unit(unit)._with_freq(\"infer\")\n assert exp.index.freq == \"ME\"\n tm.assert_frame_equal(result, exp)\n@@ -1134,7 +1134,7 @@ def test_resample_anchored_intraday2(unit):\n result = df.resample(\"QE\").mean()\n expected = df.resample(\"QE\").mean().to_period()\n expected = expected.to_timestamp(how=\"end\")\n- expected.index += Timedelta(1, \"ns\") - Timedelta(1, \"D\")\n+ expected.index += Timedelta(1, unit=\"us\") - Timedelta(1, unit=\"D\")\n expected.index._data.freq = \"QE\"\n expected.index._freq = lib.no_default\n expected.index = expected.index.as_unit(unit)\n@@ -1144,7 +1144,7 @@ def test_resample_anchored_intraday2(unit):\n expected = df.shift(1, freq=\"D\").resample(\"QE\").mean()\n expected = expected.to_period()\n expected = expected.to_timestamp(how=\"end\")\n- expected.index += Timedelta(1, \"ns\") - Timedelta(1, \"D\")\n+ expected.index += Timedelta(1, unit=\"us\") - Timedelta(1, unit=\"D\")\n expected.index._data.freq = \"QE\"\n expected.index._freq = lib.no_default\n expected.index = expected.index.as_unit(unit)" }, { "filename": "pandas/tests/scalar/period/test_asfreq.py", "status": "modified", "additions": 3, "deletions": 13, "changes": 16, "patch": "@@ -1,7 +1,6 @@\n import pytest\n \n from pandas._libs.tslibs.period import INVALID_FREQ_ERR_MSG\n-from pandas.errors import OutOfBoundsDatetime\n \n from pandas import (\n Period,\n@@ -42,10 +41,8 @@ def test_to_timestamp_out_of_bounds(self):\n # GH#19643, used to incorrectly give Timestamp in 1754\n with tm.assert_produces_warning(FutureWarning, match=bday_msg):\n per = Period(\"0001-01-01\", freq=\"B\")\n- msg = \"Out of bounds nanosecond timestamp\"\n- with pytest.raises(OutOfBoundsDatetime, match=msg):\n- with tm.assert_produces_warning(FutureWarning, match=bday_msg):\n- per.to_timestamp()\n+ with tm.assert_produces_warning(FutureWarning, match=bday_msg):\n+ per.to_timestamp()\n \n def test_asfreq_corner(self):\n val = Period(freq=\"Y\", year=2007)\n@@ -694,14 +691,7 @@ def test_conv_microsecond(self):\n start = per.start_time\n expected = Timestamp(\"2020-01-30 15:57:27.576166\")\n assert start == expected\n- assert start._value == per.ordinal * 1000\n-\n- per2 = Period(\"2300-01-01\", \"us\")\n- msg = \"2300-01-01\"\n- with pytest.raises(OutOfBoundsDatetime, match=msg):\n- per2.start_time\n- with pytest.raises(OutOfBoundsDatetime, match=msg):\n- per2.end_time\n+ assert start._value == per.ordinal\n \n def test_asfreq_mult(self):\n # normal freq to mult freq" }, { "filename": "pandas/tests/scalar/period/test_period.py", "status": "modified", "additions": 54, "deletions": 42, "changes": 96, "patch": "@@ -8,16 +8,21 @@\n import numpy as np\n import pytest\n \n-from pandas._libs.tslibs import iNaT\n+from pandas._libs.tslibs import (\n+ iNaT,\n+ to_offset,\n+)\n from pandas._libs.tslibs.ccalendar import (\n DAYS,\n MONTHS,\n )\n-from pandas._libs.tslibs.np_datetime import OutOfBoundsDatetime\n from pandas._libs.tslibs.parsing import DateParseError\n from pandas._libs.tslibs.period import INVALID_FREQ_ERR_MSG\n from pandas.compat import PY314\n-from pandas.errors import Pandas4Warning\n+from pandas.errors import (\n+ OutOfBoundsDatetime,\n+ Pandas4Warning,\n+)\n \n from pandas import (\n NaT,\n@@ -682,12 +687,12 @@ def test_hash(self):\n def test_to_timestamp_mult(self):\n p = Period(\"2011-01\", freq=\"M\")\n assert p.to_timestamp(how=\"S\") == Timestamp(\"2011-01-01\")\n- expected = Timestamp(\"2011-02-01\") - Timedelta(1, \"ns\")\n+ expected = Timestamp(\"2011-02-01\") - Timedelta(1, unit=\"us\")\n assert p.to_timestamp(how=\"E\") == expected\n \n p = Period(\"2011-01\", freq=\"3M\")\n assert p.to_timestamp(how=\"S\") == Timestamp(\"2011-01-01\")\n- expected = Timestamp(\"2011-04-01\") - Timedelta(1, \"ns\")\n+ expected = Timestamp(\"2011-04-01\") - Timedelta(1, unit=\"us\")\n assert p.to_timestamp(how=\"E\") == expected\n \n [USER_REDACTED].mark.filterwarnings(\n@@ -712,8 +717,8 @@ def test_to_timestamp(self):\n \n def _ex(p):\n if p.freq == \"B\":\n- return p.start_time + Timedelta(days=1, nanoseconds=-1)\n- return Timestamp((p + p.freq).start_time._value - 1)\n+ return p.start_time + Timedelta(days=1) - Timedelta(microseconds=1)\n+ return Timestamp((p + p.freq).start_time._value - 1, unit=\"us\")\n \n for fcode in from_lst:\n p = Period(\"1982\", freq=fcode)\n@@ -729,19 +734,19 @@ def _ex(p):\n p = Period(\"1985\", freq=\"Y\")\n \n result = p.to_timestamp(\"h\", how=\"end\")\n- expected = Timestamp(1986, 1, 1) - Timedelta(1, \"ns\")\n+ expected = Timestamp(1986, 1, 1) - Timedelta(1, unit=\"us\")\n assert result == expected\n result = p.to_timestamp(\"3h\", how=\"end\")\n assert result == expected\n \n result = p.to_timestamp(\"min\", how=\"end\")\n- expected = Timestamp(1986, 1, 1) - Timedelta(1, \"ns\")\n+ expected = Timestamp(1986, 1, 1) - Timedelta(1, unit=\"us\")\n assert result == expected\n result = p.to_timestamp(\"2min\", how=\"end\")\n assert result == expected\n \n result = p.to_timestamp(how=\"end\")\n- expected = Timestamp(1986, 1, 1) - Timedelta(1, \"ns\")\n+ expected = Timestamp(1986, 1, 1) - Timedelta(1, unit=\"us\")\n assert result == expected\n \n expected = datetime(1985, 1, 1)\n@@ -761,7 +766,7 @@ def test_to_timestamp_business_end(self):\n per = Period(\"1990-01-05\", \"B\") # Friday\n result = per.to_timestamp(\"B\", how=\"E\")\n \n- expected = Timestamp(\"1990-01-06\") - Timedelta(nanoseconds=1)\n+ expected = Timestamp(\"1990-01-06\") - Timedelta(1, unit=\"us\")\n assert result == expected\n \n [USER_REDACTED].mark.parametrize(\n@@ -920,8 +925,21 @@ def _period_constructor(bound, offset):\n def test_outer_bounds_start_and_end_time(self, bound, offset, period_property):\n # GH #13346\n period = TestPeriodProperties._period_constructor(bound, offset)\n- with pytest.raises(OutOfBoundsDatetime, match=\"Out of bounds nanosecond\"):\n- getattr(period, period_property)\n+ # post-GH#63760 this no longer raises OutOfBoundsDatetime\n+ getattr(period, period_property)\n+\n+ per = Period._from_ordinal(bound.value, freq=to_offset(\"ms\"))\n+\n+ if period_property == \"end_time\" and offset == 1:\n+ err = OverflowError\n+ msg = \"value too large\"\n+ else:\n+ err = OutOfBoundsDatetime\n+ msg = \"Out of bounds microsecond\"\n+ # But if we do the same thing with a much-more-remote date, we still\n+ # raise OutOfBoundsDatetime (as opposed to silently giving a wrong result)\n+ with pytest.raises(err, match=msg):\n+ getattr(per, period_property)\n \n [USER_REDACTED].mark.parametrize(\"bound, offset\", [(Timestamp.min, -1), (Timestamp.max, 1)])\n [USER_REDACTED].mark.parametrize(\"period_property\", [\"start_time\", \"end_time\"])\n@@ -946,66 +964,60 @@ def test_start_time(self):\n def test_end_time(self):\n p = Period(\"2012\", freq=\"Y\")\n \n- def _ex(*args):\n- return Timestamp(Timestamp(datetime(*args)).as_unit(\"ns\")._value - 1)\n-\n- xp = _ex(2013, 1, 1)\n- assert xp == p.end_time\n+ exp = Timestamp(2012, 12, 31, 23, 59, 59, 999999)\n+ assert p.end_time == exp\n \n p = Period(\"2012\", freq=\"Q\")\n- xp = _ex(2012, 4, 1)\n- assert xp == p.end_time\n+ exp = Timestamp(2012, 3, 31, 23, 59, 59, 999999)\n+ assert p.end_time == exp\n \n p = Period(\"2012\", freq=\"M\")\n- xp = _ex(2012, 2, 1)\n- assert xp == p.end_time\n+ exp = Timestamp(2012, 1, 31, 23, 59, 59, 999999)\n+ assert p.end_time == exp\n \n p = Period(\"2012\", freq=\"D\")\n- xp = _ex(2012, 1, 2)\n- assert xp == p.end_time\n+ exp = Timestamp(2012, 1, 1, 23, 59, 59, 999999)\n+ assert p.end_time == exp\n \n p = Period(\"2012\", freq=\"h\")\n- xp = _ex(2012, 1, 1, 1)\n- assert xp == p.end_time\n+ exp = Timestamp(2012, 1, 1, 0, 59, 59, 999999)\n+ assert p.end_time == exp\n \n with tm.assert_produces_warning(FutureWarning, match=bday_msg):\n p = Period(\"2012\", freq=\"B\")\n- xp = _ex(2012, 1, 3)\n- assert xp == p.end_time\n+ exp = Timestamp(2012, 1, 2, 23, 59, 59, 999999)\n+ assert p.end_time == exp\n \n p = Period(\"2012\", freq=\"W\")\n- xp = _ex(2012, 1, 2)\n- assert xp == p.end_time\n+ exp = Timestamp(2012, 1, 1, 23, 59, 59, 999999)\n+ assert p.end_time == exp\n \n # Test for GH 11738\n p = Period(\"2012\", freq=\"15D\")\n- xp = _ex(2012, 1, 16)\n- assert xp == p.end_time\n+ exp = Timestamp(2012, 1, 15, 23, 59, 59, 999999)\n+ assert p.end_time == exp\n \n p = Period(\"2012\", freq=\"1D1h\")\n- xp = _ex(2012, 1, 2, 1)\n- assert xp == p.end_time\n+ exp = Timestamp(2012, 1, 2, 0, 59, 59, 999999)\n+ assert p.end_time == exp\n \n p = Period(\"2012\", freq=\"1h1D\")\n- xp = _ex(2012, 1, 2, 1)\n- assert xp == p.end_time\n+ exp = Timestamp(2012, 1, 2, 0, 59, 59, 999999)\n+ assert p.end_time == exp\n \n def test_end_time_business_friday(self):\n # GH#34449\n with tm.assert_produces_warning(FutureWarning, match=bday_msg):\n per = Period(\"1990-01-05\", \"B\")\n result = per.end_time\n \n- expected = Timestamp(\"1990-01-06\") - Timedelta(nanoseconds=1)\n+ expected = Timestamp(\"1990-01-06\") - Timedelta(1, unit=\"us\")\n assert result == expected\n \n def test_anchor_week_end_time(self):\n- def _ex(*args):\n- return Timestamp(Timestamp(datetime(*args)).as_unit(\"ns\")._value - 1)\n-\n p = Period(\"2013-1-1\", \"W-SAT\")\n- xp = _ex(2013, 1, 6)\n- assert p.end_time == xp\n+ exp = Timestamp(2013, 1, 5, 23, 59, 59, 999999)\n+ assert p.end_time == exp\n \n def test_properties_annually(self):\n # Test properties on Periods with annually frequency." } ], "reviews": [ { "id": 3679728453, "user": "user_7213a217ace7", "state": "COMMENTED", "body": "Yes, I think that would be good!", "submitted_at": "2026-01-19T22:06:10+00:00" }, { "id": 3679776550, "user": "user_fb5fa0a10142", "state": "COMMENTED", "body": null, "submitted_at": "2026-01-19T22:25:21+00:00" }, { "id": 3679776709, "user": "user_fb5fa0a10142", "state": "COMMENTED", "body": null, "submitted_at": "2026-01-19T22:25:29+00:00" }, { "id": 3679777182, "user": "user_fb5fa0a10142", "state": "COMMENTED", "body": null, "submitted_at": "2026-01-19T22:25:50+00:00" }, { "id": 3679779624, "user": "user_fb5fa0a10142", "state": "COMMENTED", "body": null, "submitted_at": "2026-01-19T22:27:42+00:00" }, { "id": 3682543443, "user": "user_7213a217ace7", "state": "COMMENTED", "body": null, "submitted_at": "2026-01-20T14:42:30+00:00" }, { "id": 3682625459, "user": "user_7213a217ace7", "state": "COMMENTED", "body": null, "submitted_at": "2026-01-20T14:58:57+00:00" }, { "id": 3686120678, "user": "user_7213a217ace7", "state": "APPROVED", "body": null, "submitted_at": "2026-01-21T09:13:33+00:00" } ], "review_comments": [ { "id": 2706173850, "user": "user_7213a217ace7", "body": "```suggestion\n # give microseconds for everything other than freq=\"ns\"\n```", "path": "pandas/_libs/tslibs/period.pyx", "line": null, "side": "RIGHT", "created_at": "2026-01-19T21:52:30+00:00" }, { "id": 2706178597, "user": "user_7213a217ace7", "body": "```suggestion\n adjust = Timedelta(1, unit=unit)\n```\n\nIs that still needed now? (I thought we follow the input unit for integers)", "path": "pandas/core/arrays/period.py", "line": null, "side": "RIGHT", "created_at": "2026-01-19T21:55:37+00:00" }, { "id": 2706192341, "user": "user_7213a217ace7", "body": "Is there a specific reason you are switching here from Timedelta to np.timedelta64 ?", "path": "pandas/tests/frame/methods/test_to_timestamp.py", "line": null, "side": "RIGHT", "created_at": "2026-01-19T22:04:13+00:00" }, { "id": 2706194055, "user": "user_7213a217ace7", "body": "If you would change the freq to use ns, then it would keep raising the out of bounds?", "path": "pandas/tests/scalar/period/test_asfreq.py", "line": 43, "side": "RIGHT", "created_at": "2026-01-19T22:05:29+00:00" }, { "id": 2706223623, "user": "user_fb5fa0a10142", "body": "i think you're right, will update", "path": "pandas/core/arrays/period.py", "line": null, "side": "RIGHT", "created_at": "2026-01-19T22:25:21+00:00" }, { "id": 2706223804, "user": "user_fb5fa0a10142", "body": "will update with the GH ref", "path": "pandas/_libs/tslibs/period.pyx", "line": null, "side": "RIGHT", "created_at": "2026-01-19T22:25:29+00:00" }, { "id": 2706224317, "user": "user_fb5fa0a10142", "body": "i think i started this branch before we changed the Timedelta behavior. will revert this bit", "path": "pandas/tests/frame/methods/test_to_timestamp.py", "line": null, "side": "RIGHT", "created_at": "2026-01-19T22:25:50+00:00" }, { "id": 2706227000, "user": "user_fb5fa0a10142", "body": "do you mean the freq we pass to the Period constructor in this example? that would raise at construction.", "path": "pandas/tests/scalar/period/test_asfreq.py", "line": 43, "side": "RIGHT", "created_at": "2026-01-19T22:27:41+00:00" }, { "id": 2708658888, "user": "user_7213a217ace7", "body": "Ah, yes, that's what I meant, but indeed not helping to test this", "path": "pandas/tests/scalar/period/test_asfreq.py", "line": 43, "side": "RIGHT", "created_at": "2026-01-20T14:42:30+00:00" }, { "id": 2708727477, "user": "user_7213a217ace7", "body": "(the same change is used in some other files as well)", "path": "pandas/tests/frame/methods/test_to_timestamp.py", "line": null, "side": "RIGHT", "created_at": "2026-01-20T14:58:56+00:00" } ], "meta": { "languages": [ "py", "pyx", "rst" ], "touches_tests": true, "review_state_summary": { "COMMENTED": 7, "APPROVED": 1 }, "meaningful_comment_count": 10, "has_approval": true, "has_changes_requested": false, "total_review_comments": 10 } } { "_id": "e9b0a77b24d471af", "_schema_version": "1.0", "_cleaned_at": "2026-02-12T07:46:51.845010+00:00", "repo": "pandas-dev/pandas", "repo_url": "https://github.com/pandas-dev/pandas", "license_name": "BSD 3-Clause \"New\" or \"Revised\" License", "license_spdx": "BSD-3-Clause", "pr_number": 63755, "title": "TST: add regression test for subtraction with mismatched index name/type (GH#57524)", "body": "Adds a regression test to ensure subtraction works correctly\nwhen Series have indices with different names/types (GH#57524).\n\nThe test passes on the current main branch.\n\ncloses #57524", "author": "user_84a1e181b68b", "created_at": "2026-01-19T10:38:01+00:00", "merged_at": "2026-01-22T19:10:25+00:00", "base_branch": "main", "head_branch": "test-gh57524-subtraction-index", "additions": 22, "deletions": 0, "changed_files": 1, "files": [ { "filename": "pandas/tests/series/test_arithmetic.py", "status": "modified", "additions": 22, "deletions": 0, "changes": 22, "patch": "@@ -399,6 +399,28 @@ def test_add_list_to_masked_array_boolean(self):\n result = [True, None, True] + ser # noqa: RUF005\n tm.assert_series_equal(result, expected)\n \n+ def test_subtraction_index_name_type_mismatch_regression(self):\n+ # GH#57524\n+ s1 = Series(\n+ [23, 22, 21],\n+ index=Index([\"a\", \"b\", \"c\"], name=\"index a\"),\n+ dtype=\"Int64\",\n+ )\n+ s2 = Series(\n+ [21, 22, 23],\n+ index=Index(\n+ [\"a\", \"b\", \"c\"],\n+ name=\"index b\",\n+ dtype=\"string\",\n+ ),\n+ dtype=\"Int64\",\n+ )\n+\n+ result = s1 - s2\n+ expected = Series([2, 0, -2], index=s1.index, dtype=\"Int64\")\n+\n+ tm.assert_series_equal(result, expected)\n+\n \n # ------------------------------------------------------------------\n # Comparisons" } ], "reviews": [ { "id": 3683489991, "user": "user_c9260bc45a59", "state": "CHANGES_REQUESTED", "body": null, "submitted_at": "2026-01-20T17:44:17+00:00" }, { "id": 3685384488, "user": "user_84a1e181b68b", "state": "COMMENTED", "body": null, "submitted_at": "2026-01-21T05:18:33+00:00" }, { "id": 3694053896, "user": "user_c9260bc45a59", "state": "APPROVED", "body": null, "submitted_at": "2026-01-22T19:01:38+00:00" } ], "review_comments": [ { "id": 2709425879, "user": "user_c9260bc45a59", "body": "These series do not have the same `dtype` as the original issue", "path": "pandas/tests/series/test_arithmetic.py", "line": null, "side": "RIGHT", "created_at": "2026-01-20T17:43:52+00:00" }, { "id": 2711003882, "user": "user_84a1e181b68b", "body": "Thanks for catching that — you're right.\n\nI've updated the regression test to match the original issue more closely:\n- use nullable Int64 dtype for the Series\n- use a string-dtyped Index with differing name/type\n\nThe test now reproduces the original scenario and passes locally.", "path": "pandas/tests/series/test_arithmetic.py", "line": null, "side": "RIGHT", "created_at": "2026-01-21T05:18:33+00:00" } ], "meta": { "languages": [ "py" ], "touches_tests": true, "review_state_summary": { "CHANGES_REQUESTED": 1, "COMMENTED": 1, "APPROVED": 1 }, "meaningful_comment_count": 2, "has_approval": true, "has_changes_requested": true, "total_review_comments": 2 } } { "_id": "9e63627fc9f1368c", "_schema_version": "1.0", "_cleaned_at": "2026-02-12T07:46:51.845010+00:00", "repo": "pandas-dev/pandas", "repo_url": "https://github.com/pandas-dev/pandas", "license_name": "BSD 3-Clause \"New\" or \"Revised\" License", "license_spdx": "BSD-3-Clause", "pr_number": 63748, "title": "API: rename read_iceberg selected_fields keyword to columns", "body": "Briefly brought this up during the dev meeting as well, and there seemed general agreement\n\nCurrently `read_iceberg` essentially just passes through (except for translating the case of \"all columns\") to pyiceberg, and thus also using their naming for all keyword. But when providing this IO method in pandas, we could also give a bit more consistent interface to pandas users (what this PR is doing).\n\nSpecifically `selected_fields` uses a term that is otherwise never used in pandas (for a concept that does exist). \nWe are not actually fully consistent about it ourselves in the other IO methods, but generally use `usecols` (for read_csv (and read_table, read_fwf), read_excel, read_spss) or `columns` (for read_parquet (and read_feather, read_orc), read_hdf, read_sql_table, read_stata). My feeling is that `columns` is the more \"modern\" one, so went with that.", "author": "user_7213a217ace7", "created_at": "2026-01-19T01:09:19+00:00", "merged_at": "2026-01-21T10:22:08+00:00", "base_branch": "main", "head_branch": "iceberg-columns-keyword", "additions": 10, "deletions": 8, "changed_files": 2, "files": [ { "filename": "pandas/io/iceberg.py", "status": "modified", "additions": 8, "deletions": 6, "changes": 14, "patch": "@@ -14,8 +14,8 @@ def read_iceberg(\n catalog_name: str | None = None,\n *,\n catalog_properties: dict[str, Any] | None = None,\n+ columns: list[str] | None = None,\n row_filter: str | None = None,\n- selected_fields: tuple[str] | None = None,\n case_sensitive: bool = True,\n snapshot_id: int | None = None,\n limit: int | None = None,\n@@ -38,11 +38,11 @@ def read_iceberg(\n The name of the catalog.\n catalog_properties : dict of {str: str}, optional\n The properties that are used next to the catalog configuration.\n+ columns : list of str, optional\n+ A list of strings representing the column names to return in the output\n+ dataframe.\n row_filter : str, optional\n A string that describes the desired rows.\n- selected_fields : tuple of str, optional\n- A tuple of strings representing the column names to return in the output\n- dataframe.\n case_sensitive : bool, default True\n If True column matching is case sensitive.\n snapshot_id : int, optional\n@@ -71,7 +71,7 @@ def read_iceberg(\n ... catalog_name=\"my_catalog\",\n ... catalog_properties={\"s3.secret-access-key\": \"my-secret\"},\n ... row_filter=\"trip_distance >= 10.0\",\n- ... selected_fields=(\"VendorID\", \"tpep_pickup_datetime\"),\n+ ... columns=[\"VendorID\", \"tpep_pickup_datetime\"],\n ... ) # doctest: +SKIP\n \"\"\"\n pyiceberg_catalog = import_optional_dependency(\"pyiceberg.catalog\")\n@@ -82,8 +82,10 @@ def read_iceberg(\n table = catalog.load_table(table_identifier)\n if row_filter is None:\n row_filter = pyiceberg_expressions.AlwaysTrue()\n- if selected_fields is None:\n+ if columns is None:\n selected_fields = (\"*\",)\n+ else:\n+ selected_fields = tuple(columns) # type: ignore[assignment]\n if scan_properties is None:\n scan_properties = {}\n result = table.scan(" }, { "filename": "pandas/tests/io/test_iceberg.py", "status": "modified", "additions": 2, "deletions": 2, "changes": 4, "patch": "@@ -115,7 +115,7 @@ def test_read_with_case_sensitive(self, catalog):\n result = read_iceberg(\n \"ns.my_table\",\n catalog_properties={\"uri\": catalog.uri},\n- selected_fields=[\"a\"],\n+ columns=[\"a\"],\n case_sensitive=False,\n )\n tm.assert_frame_equal(result, expected)\n@@ -124,7 +124,7 @@ def test_read_with_case_sensitive(self, catalog):\n read_iceberg(\n \"ns.my_table\",\n catalog_properties={\"uri\": catalog.uri},\n- selected_fields=[\"a\"],\n+ columns=[\"a\"],\n case_sensitive=True,\n )" } ], "reviews": [ { "id": 3679153228, "user": "user_c9260bc45a59", "state": "COMMENTED", "body": null, "submitted_at": "2026-01-19T17:57:31+00:00" } ], "review_comments": [ { "id": 2705686316, "user": "user_c9260bc45a59", "body": "```suggestion\n selected_fields = [\"*\"]\n```", "path": "pandas/io/iceberg.py", "line": 86, "side": "RIGHT", "created_at": "2026-01-19T17:57:31+00:00" } ], "meta": { "languages": [ "py" ], "touches_tests": true, "review_state_summary": { "COMMENTED": 1 }, "meaningful_comment_count": 1, "has_approval": false, "has_changes_requested": false, "total_review_comments": 1 } } { "_id": "ad7388f9f64bf988", "_schema_version": "1.0", "_cleaned_at": "2026-02-12T07:46:51.845010+00:00", "repo": "pandas-dev/pandas", "repo_url": "https://github.com/pandas-dev/pandas", "license_name": "BSD 3-Clause \"New\" or \"Revised\" License", "license_spdx": "BSD-3-Clause", "pr_number": 63746, "title": "TST: add regression test for xs/loc mismatch on MultiIndex timeIndex (#19451)", "body": "- [x] closes #19451\n- [x] [Tests added and passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#writing-tests) if fixing a bug or adding a new feature\n- [x] All [code checks passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit).\n- [ ] Added [type annotations](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#type-hints) to new arguments/methods/functions.\n- [ ] Added an entry in the latest `doc/source/whatsnew/vX.X.X.rst` file if fixing a bug or adding a new feature.\n- [ ] If I used AI to develop this pull request, I prompted it to follow `AGENTS.md`.", "author": "user_b053f83b863a", "created_at": "2026-01-18T23:56:39+00:00", "merged_at": "2026-01-27T17:29:50+00:00", "base_branch": "main", "head_branch": "test-gh19451-multiindex-xs-loc", "additions": 25, "deletions": 0, "changed_files": 1, "files": [ { "filename": "pandas/tests/indexes/datetimes/test_partial_slicing.py", "status": "modified", "additions": 25, "deletions": 0, "changes": 25, "patch": "@@ -14,6 +14,7 @@\n Timedelta,\n Timestamp,\n date_range,\n+ to_datetime,\n )\n import pandas._testing as tm\n \n@@ -382,6 +383,30 @@ def test_partial_slicing_with_multiindex_series(self):\n result = df2.loc[Timestamp(\"2000-1-4\")]\n tm.assert_frame_equal(result, expected)\n \n+ def test_xs_matches_loc_after_sort_multiindex(self):\n+ # GH 19451\n+ # after sort_index, .xs should\n+ # return the same result as .loc\n+ df = DataFrame(\n+ [\n+ [\"2017-01-01\", \"000001\", \"a\", 4, 5],\n+ [\"2017-01-02\", \"000001\", \"b\", 4, 5],\n+ [\"2017-01-01\", \"000002\", \"b\", 4, 5],\n+ [\"2017-01-02\", \"000002\", \"b\", 4, 5],\n+ [\"2017-02-02\", \"000001\", \"b\", 4, 5],\n+ [\"2017-02-03\", \"000002\", \"b\", 4, 5],\n+ ],\n+ columns=[\"date\", \"code\", \"c\", \"d\", \"e\"],\n+ )\n+ df = (\n+ df.assign(date=to_datetime(df.date))\n+ .set_index([\"date\", \"code\"])\n+ .sort_index()\n+ )\n+ expected = df.loc[\"2017-01\", slice(None)]\n+ result = df.xs(\"2017-01\", level=0)\n+ tm.assert_frame_equal(result, expected)\n+\n def test_partial_slice_requires_monotonicity(self):\n # Disallowed since 2.0 (GH 37819)\n ser = Series(np.arange(10), date_range(\"2014-01-01\", periods=10))" } ], "reviews": [ { "id": 3683484027, "user": "user_c9260bc45a59", "state": "CHANGES_REQUESTED", "body": null, "submitted_at": "2026-01-20T17:42:34+00:00" }, { "id": 3694210480, "user": "user_c9260bc45a59", "state": "COMMENTED", "body": null, "submitted_at": "2026-01-22T19:31:03+00:00" }, { "id": 3712537676, "user": "user_c9260bc45a59", "state": "APPROVED", "body": null, "submitted_at": "2026-01-27T17:29:38+00:00" } ], "review_comments": [ { "id": 2709421369, "user": "user_c9260bc45a59", "body": "Can you make this a dedicated test function?", "path": "pandas/tests/indexes/datetimes/test_partial_slicing.py", "line": null, "side": "RIGHT", "created_at": "2026-01-20T17:42:30+00:00" }, { "id": 2718321988, "user": "user_c9260bc45a59", "body": "Nit: Could you use the smaller, input DataFrame like in https://github.com/[USER_REDACTED]ndas-dev/pandas/issues/19451#issuecomment-361738163?", "path": "pandas/tests/indexes/datetimes/test_partial_slicing.py", "line": null, "side": "RIGHT", "created_at": "2026-01-22T19:31:00+00:00" } ], "meta": { "languages": [ "py" ], "touches_tests": true, "review_state_summary": { "CHANGES_REQUESTED": 1, "COMMENTED": 1, "APPROVED": 1 }, "meaningful_comment_count": 2, "has_approval": true, "has_changes_requested": true, "total_review_comments": 2 } } { "_id": "19339c6b15894a52", "_schema_version": "1.0", "_cleaned_at": "2026-02-12T07:46:51.845010+00:00", "repo": "pandas-dev/pandas", "repo_url": "https://github.com/pandas-dev/pandas", "license_name": "BSD 3-Clause \"New\" or \"Revised\" License", "license_spdx": "BSD-3-Clause", "pr_number": 63743, "title": "PERF: Skip normalization of named aggregations in groupby.agg when possible", "body": "- [x] closes #63742\n- [x] [Tests added and passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#writing-tests) if fixing a bug or adding a new feature\n- [x] All [code checks passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit).\n- [x] Added [type annotations](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#type-hints) to new arguments/methods/functions.\n- [x] Added an entry in the latest `doc/source/whatsnew/vX.X.X.rst` file if fixing a bug or adding a new feature.\n- [ ] If I used AI to develop this pull request, I prompted it to follow `AGENTS.md`.\n\nThis improves the named aggregation performance to be similar to un named (around 3X faster)\n\n```python\nIn [1]: import numpy as np\n ...: import pandas as pd\n ...:\n ...:\n ...: def generate_data(n_rows: int) -> pd.DataFrame:\n ...: # Random date range within 2024\n ...: date_range = pd.date_range(start=\"2024-01-01\", end=\"2024-12-31\", freq=\"D\")\n ...: dates = np.random.choice(date_range, size=n_rows)\n ...:\n ...: # Random number of users and values\n ...: num_users = np.random.randint(1, 100, size=n_rows)\n ...: values = np.random.uniform(1.0, 1000.0, size=n_rows)\n ...:\n ...: # [NAME_REDACTED]\n ...: df = pd.DataFrame({\"date\": dates, \"num_users\": num_users, \"value\": values})\n ...: return df\n ...:\n ...:\n ...: def named(df: pd.DataFrame):\n ...: return df.groupby(\"date\").agg(\n ...: **{\"num_users\": (\"num_users\", \"sum\"), \"value\": (\"value\", \"sum\")}\n ...: )\n ...:\n ...:\n ...: def unnamed(df: pd.DataFrame):\n ...: return df.groupby(\"date\").agg({\"num_users\": \"sum\", \"value\": \"sum\"})\n ...:\n\nIn [2]: df = generate_data(10**3)\n\nIn [3]: %timeit named(df)\n359 μs ± 4.67 μs per loop (mean ± std. dev. of 7 runs, 1,000 loops each)\n\nIn [4]: %timeit unnamed(df)\n362 μs ± 5.03 μs per loop (mean ± std. dev. of 7 runs, 1,000 loops each)\n```", "author": "user_28e8b9ed45cb", "created_at": "2026-01-18T19:01:54+00:00", "merged_at": "2026-02-01T19:46:07+00:00", "base_branch": "main", "head_branch": "improve-groupby-agg-perf-63742", "additions": 49, "deletions": 5, "changed_files": 2, "files": [ { "filename": "pandas/core/apply.py", "status": "modified", "additions": 20, "deletions": 5, "changes": 25, "patch": "@@ -1770,6 +1770,7 @@ def reconstruct_func(\n raise TypeError(\"Must provide 'func' or tuples of '(column, aggfunc).\")\n \n if relabeling:\n+ normalization_needed = False\n # error: Incompatible types in assignment (expression has type\n # \"MutableMapping[Hashable, list[Callable[..., Any] | str]]\", variable has type\n # \"Callable[..., Any] | str | list[Callable[..., Any] | str] |\n@@ -1778,18 +1779,32 @@ def reconstruct_func(\n converted_kwargs = {}\n for key, val in kwargs.items():\n if isinstance(val, NamedAgg):\n+ column = val.column\n aggfunc = val.aggfunc\n if val.args or val.kwargs:\n aggfunc = lambda x, func=aggfunc, a=val.args, kw=val.kwargs: func(\n x, *a, **kw\n )\n- converted_kwargs[key] = (val.column, aggfunc)\n else:\n- converted_kwargs[key] = val\n+ column, aggfunc = val\n \n- func, columns, order = normalize_keyword_aggregation( # type: ignore[assignment]\n- converted_kwargs\n- )\n+ if column != key:\n+ normalization_needed = True\n+ converted_kwargs[key] = column, aggfunc\n+\n+ if normalization_needed:\n+ func, columns, order = normalize_keyword_aggregation( # type: ignore[assignment]\n+ converted_kwargs\n+ )\n+ else:\n+ # When names match, convert to dict format {column: aggfunc}\n+ # and disable relabeling since no reordering is needed\n+ func = {\n+ column: aggfunc for key, (column, aggfunc) in converted_kwargs.items()\n+ }\n+ # Normalization is skipped if all kwargs keys are the same as their\n+ # corresponding column name.\n+ relabeling = False\n \n assert func is not None" }, { "filename": "pandas/tests/groupby/aggregate/test_aggregate.py", "status": "modified", "additions": 29, "deletions": 0, "changes": 29, "patch": "@@ -1982,3 +1982,32 @@ def func(x):\n result = df.groupby([\"Group\"], as_index=False)[\"Data\"].agg(func)\n expected = DataFrame(columns=[\"Group\", \"Data\"])\n tm.assert_frame_equal(result, expected)\n+\n+\n+def test_agg_relabel_with_name_match():\n+ # GH-63742\n+ df = DataFrame(\n+ {\n+ \"group\": [\"a\", \"a\", \"b\", \"b\"],\n+ \"value\": [1, 2, 3, 4],\n+ \"count\": [10, 20, 30, 40],\n+ }\n+ )\n+\n+ # Test with tuple format where output names match column names\n+ result = df.groupby(\"group\").agg(value=(\"value\", \"sum\"), count=(\"count\", \"max\"))\n+\n+ # Should produce same result as dict format\n+ expected = df.groupby(\"group\").agg({\"value\": \"sum\", \"count\": \"max\"})\n+\n+ tm.assert_frame_equal(result, expected)\n+\n+\n+def test_agg_relabel_with_name_match_and_namedagg():\n+ # GH-63742\n+ df = DataFrame({\"A\": [0, 0, 1, 1], \"B\": [1, 2, 3, 4]})\n+\n+ result = df.groupby(\"A\").agg(B=pd.NamedAgg(\"B\", \"sum\"))\n+\n+ expected = DataFrame({\"B\": [3, 7]}, index=Index([0, 1], name=\"A\"))\n+ tm.assert_frame_equal(result, expected)" } ], "reviews": [ { "id": 3675668899, "user": "user_28e8b9ed45cb", "state": "COMMENTED", "body": null, "submitted_at": "2026-01-18T19:03:01+00:00" }, { "id": 3733494210, "user": "user_c1cc819e14db", "state": "CHANGES_REQUESTED", "body": "Looks good!", "submitted_at": "2026-01-31T21:12:20+00:00" }, { "id": 3733523109, "user": "user_28e8b9ed45cb", "state": "COMMENTED", "body": null, "submitted_at": "2026-01-31T21:29:34+00:00" }, { "id": 3736538065, "user": "user_c1cc819e14db", "state": "APPROVED", "body": "lgtm", "submitted_at": "2026-02-01T19:42:47+00:00" } ], "review_comments": [ { "id": 2702647249, "user": "user_28e8b9ed45cb", "body": "Probably would be nicer to change how relabeling is calculated initially, but i wanted to create a simple POC and validate that this kind of fix would be acceptable", "path": "pandas/core/apply.py", "line": 1773, "side": "RIGHT", "created_at": "2026-01-18T19:03:01+00:00" }, { "id": 2750017968, "user": "user_c1cc819e14db", "body": "Agreed this could be cleaned up with some refactoring. But I think this is good as-is and refactor could be a separate PR if you're interested. Can you add a comment above this line, something like\n\n # Normalization is skipped if all kwargs keys are the same as their corresponding column name.", "path": "pandas/core/apply.py", "line": 1773, "side": "RIGHT", "created_at": "2026-01-31T21:11:45+00:00" }, { "id": 2750044780, "user": "user_28e8b9ed45cb", "body": "Cool, \nThanks!", "path": "pandas/core/apply.py", "line": 1773, "side": "RIGHT", "created_at": "2026-01-31T21:29:34+00:00" } ], "meta": { "languages": [ "py" ], "touches_tests": true, "review_state_summary": { "COMMENTED": 2, "CHANGES_REQUESTED": 1, "APPROVED": 1 }, "meaningful_comment_count": 3, "has_approval": true, "has_changes_requested": true, "total_review_comments": 3 } } { "_id": "af0da62e7baf9ff7", "_schema_version": "1.0", "_cleaned_at": "2026-02-12T07:46:51.845010+00:00", "repo": "pandas-dev/pandas", "repo_url": "https://github.com/pandas-dev/pandas", "license_name": "BSD 3-Clause \"New\" or \"Revised\" License", "license_spdx": "BSD-3-Clause", "pr_number": 63726, "title": "CI: Re-enable `-Werror` in Linux and MacOS", "body": "- [x] xref #63701 (Replace xxxx with the GitHub issue number)\n- [ ] [Tests added and passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#writing-tests) if fixing a bug or adding a new feature\n- [x] All [code checks passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit).\n- [ ] Added [type annotations](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#type-hints) to new arguments/methods/functions.\n- [ ] Added an entry in the latest `doc/source/whatsnew/vX.X.X.rst` file if fixing a bug or adding a new feature.\n- [ ] If I used AI to develop this pull request, I prompted it to follow `AGENTS.md`.\n\n---\n\nThis patch also fixes the warning of unused function on linux by [NAME_REDACTED] of some functions.", "author": "user_0d1de6b83a30", "created_at": "2026-01-18T00:31:18+00:00", "merged_at": "2026-01-18T18:23:33+00:00", "base_branch": "main", "head_branch": "fix/compiler-warnings", "additions": 16, "deletions": 9, "changed_files": 4, "files": [ { "filename": ".github/actions/build_pandas/action.yml", "status": "modified", "additions": 1, "deletions": 2, "changes": 3, "patch": "@@ -6,8 +6,7 @@ inputs:\n default: true\n werror:\n description: Enable werror flag for build\n- # TMP disable werror until we fix all warnings with more recent meson\n- default: false\n+ default: true\n runs:\n using: composite\n steps:" }, { "filename": ".github/workflows/unit-tests.yml", "status": "modified", "additions": 10, "deletions": 4, "changes": 14, "patch": "@@ -166,10 +166,11 @@ jobs:\n - name: [NAME_REDACTED]\n id: build\n uses: ./.github/actions/build_pandas\n- # TMP disable werror until we fix all warnings with more recent meson\n- # with:\n- # # xref https://github.com/[USER_REDACTED]n/cython/issues/6870\n- # werror: ${{ matrix.name != 'Freethreading' }}\n+ with:\n+ # python3.14t/cpython/pyatomic_gcc.h:63:10:\n+ # error: ‘__atomic_fetch_add_8’\n+ # writing 8 bytes into a region of size 0 overflows the destination [-Werror=stringop-overflow=]\n+ werror: ${{ matrix.name != 'Freethreading' }}\n \n - name: Test (not single_cpu)\n uses: ./.github/actions/run-tests\n@@ -216,6 +217,11 @@ jobs:\n \n - name: [NAME_REDACTED]\n uses: ./.github/actions/build_pandas\n+ with:\n+ # Windows contains a lot of warnings regarding unsafe type conversion.\n+ # It's possible to replicate some of them in clang with the `-Wconversion` flag.\n+ # Tracking issue: https://github.com/[USER_REDACTED]ndas-dev/pandas/issues/63701\n+ werror: ${{ runner.os != 'Windows' }}\n \n - name: Test\n uses: ./.github/actions/run-tests" }, { "filename": "pandas/_libs/lib.pyx", "status": "modified", "additions": 4, "deletions": 2, "changes": 6, "patch": "@@ -134,7 +134,7 @@ except ImportError:\n \n [USER_REDACTED].wraparound(False)\n [USER_REDACTED].boundscheck(False)\n-def memory_usage_of_objects(arr: object[:]) -> int64_t:\n+def memory_usage_of_objects(ndarray[object, ndim=1] arr) -> int64_t:\n \"\"\"\n Return the memory usage of an object array in bytes.\n \n@@ -3190,7 +3190,9 @@ def to_object_array_tuples(rows: object) -> np.ndarray:\n \n [USER_REDACTED].wraparound(False)\n [USER_REDACTED].boundscheck(False)\n-def fast_multiget(dict mapping, object[:] keys, default=np.nan) -> \"ArrayLike\":\n+def fast_multiget(\n+ dict mapping, ndarray[object, ndim=1] keys, default=np.nan\n+) -> \"ArrayLike\":\n cdef:\n Py_ssize_t i, n = len(keys)\n object val" }, { "filename": "pandas/_libs/reshape.pyx", "status": "modified", "additions": 1, "deletions": 1, "changes": 2, "patch": "@@ -60,7 +60,7 @@ def unstack(const numeric_object_t[:, :] values, const uint8_t[:] mask,\n \n [USER_REDACTED].wraparound(False)\n [USER_REDACTED].boundscheck(False)\n-def explode(object[:] values):\n+def explode(ndarray[object, ndim=1] values):\n \"\"\"\n transform array list-likes to long form\n preserve non-list entries" } ], "reviews": [ { "id": 3675607942, "user": "user_c9260bc45a59", "state": "APPROVED", "body": null, "submitted_at": "2026-01-18T17:35:22+00:00" }, { "id": 3675626645, "user": "user_0d1de6b83a30", "state": "COMMENTED", "body": null, "submitted_at": "2026-01-18T18:08:20+00:00" } ], "review_comments": [ { "id": 2702591620, "user": "user_c9260bc45a59", "body": "Is it worth reporting to Cython that using object memoryview generats C code that raises compiler warnings?", "path": "pandas/_libs/lib.pyx", "line": 3194, "side": "RIGHT", "created_at": "2026-01-18T17:35:13+00:00" }, { "id": 2702611573, "user": "user_0d1de6b83a30", "body": "I am going to raise an issue.", "path": "pandas/_libs/lib.pyx", "line": 3194, "side": "RIGHT", "created_at": "2026-01-18T18:08:20+00:00" } ], "meta": { "languages": [ "pyx", "yml" ], "touches_tests": false, "review_state_summary": { "APPROVED": 1, "COMMENTED": 1 }, "meaningful_comment_count": 2, "has_approval": true, "has_changes_requested": false, "total_review_comments": 2 } } { "_id": "b13cb44abceda5ab", "_schema_version": "1.0", "_cleaned_at": "2026-02-12T07:46:51.845010+00:00", "repo": "pandas-dev/pandas", "repo_url": "https://github.com/pandas-dev/pandas", "license_name": "BSD 3-Clause \"New\" or \"Revised\" License", "license_spdx": "BSD-3-Clause", "pr_number": 63711, "title": "DOC: Fix GL08 for pandas.tseries.offsets.QuarterBegin.startingMonth", "body": "- [ ] related to #60365\n\nFixes\n\n```\npandas.tseries.offsets.BQuarterBegin.startingMonth GL08\npandas.tseries.offsets.BQuarterEnd.startingMonth GL08\npandas.tseries.offsets.QuarterBegin.startingMonth GL08\npandas.tseries.offsets.QuarterEnd.startingMonth GL08\n```", "author": "user_8905a7db72f0", "created_at": "2026-01-16T18:36:25+00:00", "merged_at": "2026-01-16T20:39:36+00:00", "base_branch": "main", "head_branch": "pandas.tseries.offsets.QuarterBegin.startingMonth", "additions": 30, "deletions": 7, "changed_files": 2, "files": [ { "filename": "ci/code_checks.sh", "status": "modified", "additions": 0, "deletions": 4, "changes": 4, "patch": "@@ -73,8 +73,6 @@ if [[ -z \"$CHECK\" || \"$CHECK\" == \"docstrings\" ]]; then\n -i \"pandas.Series.dt PR01\" `# Accessors are implemented as classes, but we do not document the Parameters section` \\\n -i \"pandas.Period.ordinal GL08\" \\\n -i \"pandas.tseries.offsets.BDay PR02,SA01\" \\\n- -i \"pandas.tseries.offsets.BQuarterBegin.startingMonth GL08\" \\\n- -i \"pandas.tseries.offsets.BQuarterEnd.startingMonth GL08\" \\\n -i \"pandas.tseries.offsets.BusinessDay PR02,SA01\" \\\n -i \"pandas.tseries.offsets.BusinessDay.is_on_offset GL08\" \\\n -i \"pandas.tseries.offsets.BusinessDay.weekmask GL08\" \\\n@@ -127,8 +125,6 @@ if [[ -z \"$CHECK\" || \"$CHECK\" == \"docstrings\" ]]; then\n -i \"pandas.tseries.offsets.MonthBegin.is_on_offset GL08\" \\\n -i \"pandas.tseries.offsets.MonthEnd.is_on_offset GL08\" \\\n -i \"pandas.tseries.offsets.Nano.is_on_offset GL08\" \\\n- -i \"pandas.tseries.offsets.QuarterBegin.startingMonth GL08\" \\\n- -i \"pandas.tseries.offsets.QuarterEnd.startingMonth GL08\" \\\n -i \"pandas.tseries.offsets.Second.is_on_offset GL08\" \\\n -i \"pandas.tseries.offsets.SemiMonthBegin.day_of_month GL08\" \\\n -i \"pandas.tseries.offsets.SemiMonthBegin.is_on_offset GL08\" \\" }, { "filename": "pandas/_libs/tslibs/offsets.pyx", "status": "modified", "additions": 30, "deletions": 3, "changes": 33, "patch": "@@ -3157,20 +3157,47 @@ cdef class QuarterOffset(SingleConstructorOffset):\n _from_name_starting_month: ClassVar[int]\n \n cdef readonly:\n- int startingMonth\n+ int _startingMonth\n \n def __init__(self, n=1, normalize=False, startingMonth=None):\n BaseOffset.__init__(self, n, normalize)\n \n if startingMonth is None:\n startingMonth = self._default_starting_month\n- self.startingMonth = startingMonth\n+ self._startingMonth = startingMonth\n \n cpdef __setstate__(self, state):\n- self.startingMonth = state.pop(\"startingMonth\")\n+ self._startingMonth = state.pop(\"startingMonth\")\n self._n = state.pop(\"n\")\n self._normalize = state.pop(\"normalize\")\n \n+ [USER_REDACTED]\n+ def startingMonth(self) -> int:\n+ \"\"\"\n+ Return the month of the year from which quarters start.\n+\n+ This value determines which month marks the beginning of a quarterly period.\n+ For example, with startingMonth=1, quarters start in January, April, July,\n+ and October.\n+\n+ See Also\n+ --------\n+ QuarterOffset.rule_code : Return the rule code for the quarter offset.\n+ HalfYearOffset.startingMonth : Similar property for half-year-based offsets.\n+\n+ Examples\n+ --------\n+ >>> pd.offsets.BQuarterBegin().startingMonth\n+ 3\n+\n+ >>> pd.offsets.QuarterEnd().startingMonth\n+ 3\n+\n+ >>> pd.offsets.QuarterBegin(startingMonth=1).startingMonth\n+ 1\n+ \"\"\"\n+ return self._startingMonth\n+\n [USER_REDACTED]\n def _from_name(cls, suffix=None):\n kwargs = {}" } ], "reviews": [ { "id": 3672498568, "user": "user_c9260bc45a59", "state": "CHANGES_REQUESTED", "body": null, "submitted_at": "2026-01-16T19:58:01+00:00" }, { "id": 3672520830, "user": "user_8905a7db72f0", "state": "COMMENTED", "body": null, "submitted_at": "2026-01-16T20:04:18+00:00" }, { "id": 3672652955, "user": "user_c9260bc45a59", "state": "APPROVED", "body": null, "submitted_at": "2026-01-16T20:39:29+00:00" } ], "review_comments": [ { "id": 2699793616, "user": "user_c9260bc45a59", "body": "Shouldn't this new method be after these two lines?", "path": "pandas/_libs/tslibs/offsets.pyx", "line": null, "side": "RIGHT", "created_at": "2026-01-16T19:57:57+00:00" }, { "id": 2699811575, "user": "user_8905a7db72f0", "body": "looks like my rebase from the main had some issue. fixed.", "path": "pandas/_libs/tslibs/offsets.pyx", "line": null, "side": "RIGHT", "created_at": "2026-01-16T20:04:18+00:00" } ], "meta": { "languages": [ "pyx", "sh" ], "touches_tests": false, "review_state_summary": { "CHANGES_REQUESTED": 1, "COMMENTED": 1, "APPROVED": 1 }, "meaningful_comment_count": 2, "has_approval": true, "has_changes_requested": true, "total_review_comments": 2 } } { "_id": "30b70ec50d0d35ca", "_schema_version": "1.0", "_cleaned_at": "2026-02-12T07:46:51.845010+00:00", "repo": "pandas-dev/pandas", "repo_url": "https://github.com/pandas-dev/pandas", "license_name": "BSD 3-Clause \"New\" or \"Revised\" License", "license_spdx": "BSD-3-Clause", "pr_number": 63707, "title": "TST: test concat_compat for datetime-EA with non-ns", "body": "- [x] closes #33331\n\nThe reproducible example works correctly on main. Added a test to cover it.", "author": "user_29def2a2fd98", "created_at": "2026-01-16T12:57:52+00:00", "merged_at": "2026-01-17T18:18:03+00:00", "base_branch": "main", "head_branch": "tst-concat_compat-on-non-ns-datetime-EA", "additions": 10, "deletions": 0, "changed_files": 1, "files": [ { "filename": "pandas/tests/reshape/concat/test_datetimes.py", "status": "modified", "additions": 10, "deletions": 0, "changes": 10, "patch": "@@ -286,6 +286,16 @@ def test_concat_NaT_series_dataframe_all_NaT(self, tz1, tz2):\n result = concat([first, second])\n tm.assert_frame_equal(result, expected)\n \n+ def test_concat_compat_on_non_ns_datetime_EA(self):\n+ # GH#33331\n+ first = Series(np.array([datetime(2010, 1, 1)], dtype=\"datetime64[D]\"))\n+ second = Series(pd.array([\"a\", \"b\"], dtype=\"category\"))\n+\n+ expected = Series([Timestamp(\"2010-01-01 00:00:00\"), \"a\", \"b\"])\n+\n+ result = concat([first, second], ignore_index=True)\n+ tm.assert_series_equal(result, expected)\n+\n \n class TestTimezoneConcat:\n def test_concat_tz_series(self):" } ], "reviews": [ { "id": 3671845049, "user": "user_c9260bc45a59", "state": "COMMENTED", "body": null, "submitted_at": "2026-01-16T17:04:22+00:00" }, { "id": 3673917882, "user": "user_29def2a2fd98", "state": "COMMENTED", "body": null, "submitted_at": "2026-01-17T12:02:03+00:00" }, { "id": 3673918692, "user": "user_29def2a2fd98", "state": "COMMENTED", "body": null, "submitted_at": "2026-01-17T12:02:38+00:00" }, { "id": 3674317929, "user": "user_c9260bc45a59", "state": "APPROVED", "body": null, "submitted_at": "2026-01-17T18:17:51+00:00" } ], "review_comments": [ { "id": 2699290040, "user": "user_c9260bc45a59", "body": "Is it possible to test this without going through a private API like concat_compat?", "path": "pandas/tests/dtypes/test_concat.py", "line": null, "side": "RIGHT", "created_at": "2026-01-16T17:03:54+00:00" }, { "id": 2699291280, "user": "user_c9260bc45a59", "body": "```suggestion\nimport datetime\n```\n\nIMO it's a lot clearer just to not shorten this", "path": "pandas/tests/dtypes/test_concat.py", "line": null, "side": "RIGHT", "created_at": "2026-01-16T17:04:19+00:00" }, { "id": 2701021829, "user": "user_29def2a2fd98", "body": "Yes,I think we can test this using the public function `concat`. I moved the test to `pandas/tests/reshape/concat/test_datetimes.py`.", "path": "pandas/tests/dtypes/test_concat.py", "line": null, "side": "RIGHT", "created_at": "2026-01-17T12:02:03+00:00" }, { "id": 2701022349, "user": "user_29def2a2fd98", "body": "Thanks, I won’t shorten it.", "path": "pandas/tests/dtypes/test_concat.py", "line": null, "side": "RIGHT", "created_at": "2026-01-17T12:02:38+00:00" } ], "meta": { "languages": [ "py" ], "touches_tests": true, "review_state_summary": { "COMMENTED": 3, "APPROVED": 1 }, "meaningful_comment_count": 4, "has_approval": true, "has_changes_requested": false, "total_review_comments": 4 } } { "_id": "acfc550cab8475aa", "_schema_version": "1.0", "_cleaned_at": "2026-02-12T07:46:51.860650+00:00", "repo": "pandas-dev/pandas", "repo_url": "https://github.com/pandas-dev/pandas", "license_name": "BSD 3-Clause \"New\" or \"Revised\" License", "license_spdx": "BSD-3-Clause", "pr_number": 63705, "title": "BUG: .str methods failing on PyArrow using regex with \\Z", "body": "Closes #63385\n\nThis is only for match and needs to be generalized, if we think this approach is workable\n\nThe RE2 engine only supports `\\z` and not `\\Z`, and Python 3.14 actually also just added `\\z` and kept `\\Z` as an alias for compat. So for python users, up to recently, you could only use `\\Z`, but pyarrow engine requires `\\z`. As a user changing manually to use `\\z` only works with Python 3.14+, so I think it would be good to handle this under the hood for the user.", "author": "user_7213a217ace7", "created_at": "2026-01-16T10:54:45+00:00", "merged_at": "2026-01-21T10:21:44+00:00", "base_branch": "main", "head_branch": "string-dtype-regex-z", "additions": 258, "deletions": 21, "changed_files": 7, "files": [ { "filename": "doc/source/whatsnew/v3.0.0.rst", "status": "modified", "additions": 1, "deletions": 1, "changes": 2, "patch": "@@ -1211,7 +1211,7 @@ Strings\n - Bug in :meth:`Series.str.match` failing to raise when given a compiled ``re.Pattern`` object and conflicting ``case`` or ``flags`` arguments (:issue:`62240`)\n - Bug in :meth:`Series.str.zfill` raising ``AttributeError`` for :class:`ArrowDtype` (:issue:`61485`)\n - Bug in :meth:`Series.value_counts` would not respect ``sort=False`` for series having ``string`` dtype (:issue:`55224`)\n-- Bug in :ref:`Series.str methods ` would fail when using regex with lookaheads or lookbehinds on data backed by PyArrow (:issue:`60833`)\n+- Bug in :ref:`Series.str methods ` would fail when using regex with lookaheads or lookbehinds, backreferences, or ``\\Z`` on data backed by PyArrow (:issue:`60833`, :issue:`63683`)\n - Bug in multiplication with a :class:`StringDtype` incorrectly allowing multiplying by bools; explicitly cast to integers instead (:issue:`62595`)\n \n Interval" }, { "filename": "pandas/core/arrays/_arrow_string_mixins.py", "status": "modified", "additions": 4, "deletions": 2, "changes": 6, "patch": "@@ -376,7 +376,9 @@ def _str_match(\n ):\n if not pat.startswith(\"^\"):\n pat = f\"^({pat})\"\n- return self._str_contains(pat, case, flags, na, regex=True)\n+ return ArrowStringArrayMixin._str_contains(\n+ self, pat, case, flags, na, regex=True\n+ )\n \n def _str_fullmatch(\n self,\n@@ -391,7 +393,7 @@ def _str_fullmatch(\n pat = f\"^({pat[1:]})$\"\n elif not pat.startswith(\"^\"):\n pat = f\"^({pat[0:-1]})$\"\n- return self._str_match(pat, case, flags, na)\n+ return ArrowStringArrayMixin._str_match(self, pat, case, flags, na)\n \n def _str_find(self, sub: str, start: int = 0, end: int | None = None):\n if (start == 0 or start is None) and end is None:" }, { "filename": "pandas/core/arrays/string_arrow.py", "status": "modified", "additions": 38, "deletions": 18, "changes": 56, "patch": "@@ -372,16 +372,31 @@ def _is_re_pattern_with_flags(pat: str | re.Pattern) -> bool:\n )\n \n [USER_REDACTED]\n- def _preprocess_re_pattern(pat: re.Pattern, case: bool) -> tuple[str, bool, int]:\n- pattern = pat.pattern\n- flags = pat.flags\n- # flags is not supported by pyarrow, but `case` is -> extract and remove\n- if flags & re.IGNORECASE:\n- case = False\n- flags = flags & ~re.IGNORECASE\n- # when creating a pattern with re.compile and a string, it automatically\n- # gets a UNICODE flag, while pyarrow assumes unicode for strings anyway\n- flags = flags & ~re.UNICODE\n+ def _preprocess_re_pattern(\n+ pat: str | re.Pattern, case: bool, flags: int\n+ ) -> tuple[str, bool, int]:\n+ if isinstance(pat, re.Pattern):\n+ pattern = pat.pattern\n+ # TODO flags passed separately by [NAME_REDACTED]\n+ flags = pat.flags\n+ # flags is not supported by pyarrow, but `case` is -> extract and remove\n+ if flags & re.IGNORECASE:\n+ case = False\n+ flags = flags & ~re.IGNORECASE\n+ # when creating a pattern with re.compile and a string, it automatically\n+ # gets a UNICODE flag, while pyarrow assumes unicode for strings anyway\n+ flags = flags & ~re.UNICODE\n+ else:\n+ pattern = pat\n+\n+ if (\n+ pattern.endswith(\"\\\\Z\")\n+ # Second condition counts the number of `\\` that patterns ends with\n+ # prior to Z -> needs to be odd to end with an unescaped \\Z\n+ and (len(pattern) - len(pattern[:-1].rstrip(\"\\\\\")) + 1) % 2 == 1\n+ ):\n+ pattern = pattern[:-2] + \"\\\\z\"\n+\n return pattern, case, flags\n \n def _str_contains(\n@@ -398,10 +413,8 @@ def _str_contains(\n or (regex and self._has_unsupported_regex(pat))\n ):\n return super()._str_contains(pat, case, flags, na, regex)\n- if isinstance(pat, re.Pattern):\n- # TODO flags passed separately by [NAME_REDACTED]\n- pat, case, flags = self._preprocess_re_pattern(pat, case)\n \n+ pat, case, flags = self._preprocess_re_pattern(pat, case, flags)\n return ArrowStringArrayMixin._str_contains(self, pat, case, flags, na, regex)\n \n def _str_match(\n@@ -417,9 +430,8 @@ def _str_match(\n or self._has_unsupported_regex(pat)\n ):\n return super()._str_match(pat, case, flags, na)\n- if isinstance(pat, re.Pattern):\n- pat, case, flags = self._preprocess_re_pattern(pat, case)\n \n+ pat, case, flags = self._preprocess_re_pattern(pat, case, flags)\n return ArrowStringArrayMixin._str_match(self, pat, case, flags, na)\n \n def _str_fullmatch(\n@@ -429,11 +441,14 @@ def _str_fullmatch(\n flags: int = 0,\n na: Scalar | lib.NoDefault = lib.no_default,\n ):\n- if flags or self._is_re_pattern_with_flags(pat):\n+ if (\n+ flags\n+ or self._is_re_pattern_with_flags(pat)\n+ or self._has_unsupported_regex(pat)\n+ ):\n return super()._str_fullmatch(pat, case, flags, na)\n- if isinstance(pat, re.Pattern):\n- pat, case, flags = self._preprocess_re_pattern(pat, case)\n \n+ pat, case, flags = self._preprocess_re_pattern(pat, case, flags)\n return ArrowStringArrayMixin._str_fullmatch(self, pat, case, flags, na)\n \n def _str_replace(\n@@ -458,6 +473,9 @@ def _str_replace(\n ):\n return super()._str_replace(pat, repl, n, case, flags, regex)\n \n+ if regex:\n+ pat, case, flags = self._preprocess_re_pattern(pat, case, flags)\n+\n return ArrowStringArrayMixin._str_replace(\n self, pat, repl, n, case, flags, regex\n )\n@@ -471,6 +489,8 @@ def _str_repeat(self, repeats: int | Sequence[int]):\n def _str_count(self, pat: str, flags: int = 0):\n if flags or self._has_unsupported_regex(pat):\n return super()._str_count(pat, flags)\n+\n+ pat, _, _ = self._preprocess_re_pattern(pat, True, 0)\n result = pc.count_substring_regex(self._pa_array, pat)\n return self._convert_int_result(result)" }, { "filename": "pandas/tests/strings/test_extract.py", "status": "modified", "additions": 21, "deletions": 0, "changes": 21, "patch": "@@ -761,3 +761,24 @@ def test_extractall_lookarounds(any_string_dtype, pat, expected_data):\n expected = Series(expected_data, dtype=any_string_dtype).to_frame()\n expected.index.names = [None, \"match\"]\n tm.assert_frame_equal(result, expected)\n+\n+\n+def test_extract_end_of_string(any_string_dtype):\n+ # https://github.com/[USER_REDACTED]ndas-dev/pandas/pull/63613\n+ ser = Series([\"aa\", \"abc\", \"bb\\n\"], dtype=any_string_dtype)\n+\n+ # with dollar sign\n+ result = ser.str.extract(\"([ab]+)$\")\n+ expected = Series([\"aa\", np.nan, \"bb\"], dtype=any_string_dtype).to_frame()\n+ tm.assert_frame_equal(result, expected)\n+\n+ # with \\Z (ensure this is translated to \\z for pyarrow)\n+ result = ser.str.extract(r\"([ab]+)\\Z\")\n+ expected = Series([\"aa\", np.nan, np.nan], dtype=any_string_dtype).to_frame()\n+ tm.assert_frame_equal(result, expected)\n+\n+ # ensure finding a literal \\Z still works\n+ ser = Series([r\"aa\\Z\", \"abc\", \"bb\\\\Z\\n\"], dtype=any_string_dtype)\n+ result = ser.str.extract(r\"([ab]+)\\\\Z\")\n+ expected = Series([\"aa\", np.nan, \"bb\"], dtype=any_string_dtype).to_frame()\n+ tm.assert_frame_equal(result, expected)" }, { "filename": "pandas/tests/strings/test_find_replace.py", "status": "modified", "additions": 143, "deletions": 0, "changes": 143, "patch": "@@ -372,6 +372,48 @@ def test_contains_lookarounds(any_string_dtype, pat, expected_data, na):\n tm.assert_series_equal(result, expected)\n \n \n+def test_contains_end_of_string(any_string_dtype):\n+ # https://github.com/[USER_REDACTED]ndas-dev/pandas/pull/63613\n+ expected_dtype = (\n+ np.bool_ if is_object_or_nan_string_dtype(any_string_dtype) else \"boolean\"\n+ )\n+\n+ ser = Series([\"baz\", \"bar\", \"bars\", \"bar\\n\"], dtype=any_string_dtype)\n+\n+ # with dollar sign\n+ result = ser.str.contains(\"bar$\")\n+ if any_string_dtype == \"string\" and any_string_dtype.storage == \"pyarrow\":\n+ # pyarrow (RE2) only matches $ at the very end of the line\n+ expected = Series([False, True, False, False], dtype=expected_dtype)\n+ else:\n+ # python matches $ before or after an ending newline\n+ expected = Series([False, True, False, True], dtype=expected_dtype)\n+ tm.assert_series_equal(result, expected)\n+\n+ # with \\Z (ensure this is translated to \\z for pyarrow)\n+ result = ser.str.contains(r\"bar\\Z\")\n+ expected = Series([False, True, False, False], dtype=expected_dtype)\n+ tm.assert_series_equal(result, expected)\n+\n+ # ensure finding a literal \\Z still works\n+ ser = Series(\n+ [\"bar\", r\"bar{}\".format(\"\\\\\"), r\"bar\\Z\", r\"bar\\\\Z\", \"bars\", \"bar\\n\"],\n+ dtype=any_string_dtype,\n+ )\n+\n+ result = ser.str.contains(r\"bar\\\\Z\")\n+ expected = Series([False, False, True, False, False, False], dtype=expected_dtype)\n+ tm.assert_series_equal(result, expected)\n+\n+ result = ser.str.contains(r\"bar\\\\\\Z\")\n+ expected = Series([False, True, False, False, False, False], dtype=expected_dtype)\n+ tm.assert_series_equal(result, expected)\n+\n+ result = ser.str.contains(r\"bar\\\\\\\\Z\")\n+ expected = Series([False, False, False, True, False, False], dtype=expected_dtype)\n+ tm.assert_series_equal(result, expected)\n+\n+\n # --------------------------------------------------------------------------------------\n # str.startswith\n # --------------------------------------------------------------------------------------\n@@ -961,6 +1003,32 @@ def test_replace_lookarounds(any_string_dtype, pat, expected_data):\n tm.assert_series_equal(result, expected)\n \n \n+def test_replace_end_of_string(any_string_dtype):\n+ # https://github.com/[USER_REDACTED]ndas-dev/pandas/pull/63613\n+ ser = Series([\"baz\", \"bar\", \"bars\", \"bar\\n\"], dtype=any_string_dtype)\n+\n+ # with dollar sign\n+ result = ser.str.replace(\"bar$\", \"x\", regex=True)\n+ if any_string_dtype == \"string\" and any_string_dtype.storage == \"pyarrow\":\n+ # pyarrow (RE2) only matches $ at the very end of the line\n+ expected = Series([\"baz\", \"x\", \"bars\", \"bar\\n\"], dtype=any_string_dtype)\n+ else:\n+ # python matches $ before or after an ending newline\n+ expected = Series([\"baz\", \"x\", \"bars\", \"x\\n\"], dtype=any_string_dtype)\n+ tm.assert_series_equal(result, expected)\n+\n+ # with \\Z (ensure this is translated to \\z for pyarrow)\n+ result = ser.str.replace(r\"bar\\Z\", \"x\", regex=True)\n+ expected = Series([\"baz\", \"x\", \"bars\", \"bar\\n\"], dtype=any_string_dtype)\n+ tm.assert_series_equal(result, expected)\n+\n+ # ensure finding a literal \\Z still works\n+ ser = Series([r\"bar\\Z\", \"bar\", \"bars\", \"bar\\n\"], dtype=any_string_dtype)\n+ result = ser.str.replace(r\"bar\\\\Z\", \"x\", regex=True)\n+ expected = Series([\"x\", \"bar\", \"bars\", \"bar\\n\"], dtype=any_string_dtype)\n+ tm.assert_series_equal(result, expected)\n+\n+\n # --------------------------------------------------------------------------------------\n # str.match\n # --------------------------------------------------------------------------------------\n@@ -1145,6 +1213,36 @@ def test_match_lookarounds(any_string_dtype, pat, expected_data):\n tm.assert_series_equal(result, expected)\n \n \n+def test_match_end_of_string(any_string_dtype):\n+ # https://github.com/[USER_REDACTED]ndas-dev/pandas/pull/63613\n+ expected_dtype = (\n+ np.bool_ if is_object_or_nan_string_dtype(any_string_dtype) else \"boolean\"\n+ )\n+\n+ ser = Series([\"baz\", \"bar\", \"bars\", \"bar\\n\"], dtype=any_string_dtype)\n+\n+ # with dollar sign\n+ result = ser.str.match(\"bar$\")\n+ if any_string_dtype == \"string\" and any_string_dtype.storage == \"pyarrow\":\n+ # pyarrow (RE2) only matches $ at the very end of the line\n+ expected = Series([False, True, False, False], dtype=expected_dtype)\n+ else:\n+ # python matches $ before or after an ending newline\n+ expected = Series([False, True, False, True], dtype=expected_dtype)\n+ tm.assert_series_equal(result, expected)\n+\n+ # with \\Z (ensure this is translated to \\z for pyarrow)\n+ result = ser.str.match(r\"bar\\Z\")\n+ expected = Series([False, True, False, False], dtype=expected_dtype)\n+ tm.assert_series_equal(result, expected)\n+\n+ # ensure finding a literal \\Z still works\n+ ser = Series([r\"bar\\Z\", \"bar\", \"bars\", \"bar\\n\"], dtype=any_string_dtype)\n+ result = ser.str.match(r\"bar\\\\Z\")\n+ expected = Series([True, False, False, False], dtype=expected_dtype)\n+ tm.assert_series_equal(result, expected)\n+\n+\n # --------------------------------------------------------------------------------------\n # str.fullmatch\n # --------------------------------------------------------------------------------------\n@@ -1308,6 +1406,30 @@ def test_fullmatch_lookarounds(any_string_dtype, pat):\n tm.assert_series_equal(result, expected)\n \n \n+def test_fullmatch_end_of_string(any_string_dtype):\n+ # https://github.com/[USER_REDACTED]ndas-dev/pandas/pull/63613\n+ expected_dtype = (\n+ np.bool_ if is_object_or_nan_string_dtype(any_string_dtype) else \"boolean\"\n+ )\n+\n+ ser = Series([\"baz\", \"bar\", \"bars\", \"bar\\n\"], dtype=any_string_dtype)\n+\n+ # with dollar sign (for fullmatch, no difference between python and pyarrow)\n+ result = ser.str.fullmatch(\"bar$\")\n+ expected = Series([False, True, False, False], dtype=expected_dtype)\n+ tm.assert_series_equal(result, expected)\n+\n+ # with \\Z (ensure this is translated to \\z for pyarrow)\n+ result = ser.str.fullmatch(r\"bar\\Z\")\n+ tm.assert_series_equal(result, expected)\n+\n+ # ensure finding a literal \\Z still works\n+ ser = Series([r\"bar\\Z\", \"bar\", \"bars\", \"bar\\n\"], dtype=any_string_dtype)\n+ result = ser.str.fullmatch(r\"bar\\\\Z\")\n+ expected = Series([True, False, False, False], dtype=expected_dtype)\n+ tm.assert_series_equal(result, expected)\n+\n+\n # --------------------------------------------------------------------------------------\n # str.findall\n # --------------------------------------------------------------------------------------\n@@ -1380,6 +1502,27 @@ def test_findall_lookarounds(any_string_dtype, pat, expected_data):\n tm.assert_series_equal(result, expected)\n \n \n+def test_findall_end_of_string(any_string_dtype):\n+ # https://github.com/[USER_REDACTED]ndas-dev/pandas/pull/63613\n+ ser = Series([\"baz\", \"bar\", \"bars\", \"bar\\n\"], dtype=any_string_dtype)\n+\n+ # with dollar sign\n+ result = ser.str.findall(\"bar$\")\n+ expected = Series([[], [\"bar\"], [], [\"bar\"]], dtype=object)\n+ tm.assert_series_equal(result, expected)\n+\n+ # with \\Z (ensure this is translated to \\z for pyarrow)\n+ result = ser.str.findall(r\"bar\\Z\")\n+ expected = Series([[], [\"bar\"], [], []], dtype=object)\n+ tm.assert_series_equal(result, expected)\n+\n+ # ensure finding a literal \\Z still works\n+ ser = Series([r\"bar\\Z\", \"bar\", \"bars\", \"bar\\n\"], dtype=any_string_dtype)\n+ result = ser.str.findall(r\"bar\\\\Z\")\n+ expected = Series([[\"bar\\\\Z\"], [], [], []], dtype=object)\n+ tm.assert_series_equal(result, expected)\n+\n+\n # --------------------------------------------------------------------------------------\n # str.find\n # --------------------------------------------------------------------------------------" }, { "filename": "pandas/tests/strings/test_split_partition.py", "status": "modified", "additions": 21, "deletions": 0, "changes": 21, "patch": "@@ -332,6 +332,27 @@ def test_split_lookarounds(any_string_dtype, pat, expected_data):\n tm.assert_series_equal(result, expected)\n \n \n+def test_split_regex_end_of_string(any_string_dtype):\n+ # https://github.com/[USER_REDACTED]ndas-dev/pandas/pull/63613\n+ ser = Series([\"baz\", \"bar\", \"bars\", \"bar\\n\"], dtype=any_string_dtype)\n+\n+ # with dollar sign\n+ result = ser.str.split(\"r$\", regex=True)\n+ expected = Series([[\"baz\"], [\"ba\", \"\"], [\"bars\"], [\"ba\", \"\\n\"]], dtype=object)\n+ tm.assert_series_equal(result, expected)\n+\n+ # with \\Z (ensure this is translated to \\z for pyarrow)\n+ result = ser.str.split(r\"r\\Z\", regex=True)\n+ expected = Series([[\"baz\"], [\"ba\", \"\"], [\"bars\"], [\"bar\\n\"]], dtype=object)\n+ tm.assert_series_equal(result, expected)\n+\n+ # ensure finding a literal \\Z still works\n+ ser = Series([r\"bar\\Z\", \"bar\", r\"bar\\Zs\", \"bar\\n\"], dtype=any_string_dtype)\n+ result = ser.str.split(r\"r\\\\Z\", regex=True)\n+ expected = Series([[\"ba\", \"\"], [\"bar\"], [\"ba\", \"s\"], [\"bar\\n\"]], dtype=object)\n+ tm.assert_series_equal(result, expected)\n+\n+\n def test_rsplit_to_dataframe_expand_no_splits(any_string_dtype):\n s = Series([\"nosplit\", \"alsonosplit\"], dtype=any_string_dtype)\n result = s.str.rsplit(\"_\", expand=True)" }, { "filename": "pandas/tests/strings/test_strings.py", "status": "modified", "additions": 30, "deletions": 0, "changes": 30, "patch": "@@ -89,6 +89,36 @@ def test_count_lookarounds(any_string_dtype, pat, expected_data):\n tm.assert_series_equal(result, expected)\n \n \n+def test_count_end_of_string(any_string_dtype):\n+ # https://github.com/[USER_REDACTED]ndas-dev/pandas/pull/63613\n+ expected_dtype = (\n+ \"int64\" if is_object_or_nan_string_dtype(any_string_dtype) else \"Int64\"\n+ )\n+\n+ ser = Series([\"baz\", \"bar\", \"bars\", \"bar\\n\"], dtype=any_string_dtype)\n+\n+ # with dollar sign\n+ result = ser.str.count(\"bar$\")\n+ if any_string_dtype == \"string\" and any_string_dtype.storage == \"pyarrow\":\n+ # pyarrow (RE2) only matches $ at the very end of the line\n+ expected = Series([0, 1, 0, 0], dtype=expected_dtype)\n+ else:\n+ # python matches $ before or after an ending newline\n+ expected = Series([0, 1, 0, 1], dtype=expected_dtype)\n+ tm.assert_series_equal(result, expected)\n+\n+ # with \\Z (ensure this is translated to \\z for pyarrow)\n+ result = ser.str.count(r\"bar\\Z\")\n+ expected = Series([0, 1, 0, 0], dtype=expected_dtype)\n+ tm.assert_series_equal(result, expected)\n+\n+ # ensure finding a literal \\Z still works\n+ ser = Series([r\"bar\\Z\", \"bar\", \"bars\", \"bar\\n\"], dtype=any_string_dtype)\n+ result = ser.str.count(r\"bar\\\\Z\")\n+ expected = Series([1, 0, 0, 0], dtype=expected_dtype)\n+ tm.assert_series_equal(result, expected)\n+\n+\n def test_repeat(any_string_dtype):\n ser = Series([\"a\", \"b\", np.nan, \"c\", np.nan, \"d\"], dtype=any_string_dtype)" } ], "reviews": [ { "id": 3672709807, "user": "user_c1cc819e14db", "state": "COMMENTED", "body": null, "submitted_at": "2026-01-16T21:01:50+00:00" }, { "id": 3675922820, "user": "user_7213a217ace7", "state": "COMMENTED", "body": null, "submitted_at": "2026-01-19T00:25:07+00:00" }, { "id": 3675929771, "user": "user_7213a217ace7", "state": "COMMENTED", "body": null, "submitted_at": "2026-01-19T00:34:11+00:00" }, { "id": 3684411726, "user": "user_c1cc819e14db", "state": "COMMENTED", "body": null, "submitted_at": "2026-01-20T21:41:17+00:00" }, { "id": 3684437265, "user": "user_c1cc819e14db", "state": "APPROVED", "body": "lgtm; good to merge this as-is without handling higher number of `\\` as discussed above.", "submitted_at": "2026-01-20T21:47:28+00:00" }, { "id": 3686053406, "user": "user_7213a217ace7", "state": "COMMENTED", "body": null, "submitted_at": "2026-01-21T08:58:47+00:00" } ], "review_comments": [ { "id": 2699956870, "user": "user_c1cc819e14db", "body": "This correctly handles what I think would be the vast majority of real cases and as far as I can tell has no false positives. However it does have false negatives. The following should give true:\n\n- `r\"\\\\\\Z\"` (in general, an odd number of `\\`)\n- `r\"text(\\Z)`\n- `r\"\\Z text\"`\n\nOnly the first seems like it could maybe occur in practice, the other two are likely erroneous. And while I could see this being used with lookarounds, we'll already be falling back to object dtype with those so we don't need to be worried about them here.", "path": "pandas/core/arrays/string_arrow.py", "line": null, "side": "RIGHT", "created_at": "2026-01-16T21:01:31+00:00" }, { "id": 2702900674, "user": "user_7213a217ace7", "body": "[USER_REDACTED] I changed this and added a `self._has_regex_lookaround(pat)` to ArrowStringArray._str_fullmatch, to ensure the method here certainly uses the mixin version of `_str_match`, and not the ArrowStringArray, which would otherwise call the validation methods a second time (which can fail after replacing \\Z to \\z for older python, and generally we can also avoid the overhead of validating twice)", "path": "pandas/core/arrays/_arrow_string_mixins.py", "line": 396, "side": "RIGHT", "created_at": "2026-01-19T00:25:08+00:00" }, { "id": 2702907449, "user": "user_7213a217ace7", "body": "Thanks for the analysis!\n\n> `r\"\\\\\\Z\"` (in general, an odd number of `\\`)\n\nShould we count the number of trailing `\\`? (and so only get here if the number of `\\` is not even). Something like:\n\n```\nif pat.endswith(\"\\\\Z\") and not ((len(pat[:-1]) - len(pat[:-1].rstrip(\"\\\\\"))) % 2 == 0):\n```", "path": "pandas/core/arrays/string_arrow.py", "line": null, "side": "RIGHT", "created_at": "2026-01-19T00:34:11+00:00" }, { "id": 2710171524, "user": "user_c1cc819e14db", "body": "We can remove one of the `pat[:-1]` (which I think will give a copy of the entire string). Also removed the `not` but I'm fine if that remains as the original.\n\n```python\n# Second condition counts the number of `\\` that pat ends with prior to Z\nif pat.endswith(\"\\\\Z\") and (len(pat) - len(pat[:-1].rstrip(\"\\\\\")) + 1) % 2 == 1:\n```", "path": "pandas/core/arrays/string_arrow.py", "line": null, "side": "RIGHT", "created_at": "2026-01-20T21:41:17+00:00" }, { "id": 2711586625, "user": "user_7213a217ace7", "body": "Added that and added some test cases to one of the tests", "path": "pandas/core/arrays/string_arrow.py", "line": null, "side": "RIGHT", "created_at": "2026-01-21T08:58:47+00:00" } ], "meta": { "languages": [ "py", "rst" ], "touches_tests": true, "review_state_summary": { "COMMENTED": 5, "APPROVED": 1 }, "meaningful_comment_count": 5, "has_approval": true, "has_changes_requested": false, "total_review_comments": 5 } } { "_id": "bd3cd4caeb103d70", "_schema_version": "1.0", "_cleaned_at": "2026-02-12T07:46:51.860650+00:00", "repo": "pandas-dev/pandas", "repo_url": "https://github.com/pandas-dev/pandas", "license_name": "BSD 3-Clause \"New\" or \"Revised\" License", "license_spdx": "BSD-3-Clause", "pr_number": 63697, "title": "BLD: unpin meson(-python) in environment.yml, bump minimum meson-python in build-system requires", "body": "Partial redo of https://github.com/[USER_REDACTED]ndas-dev/pandas/pull/62086 (and https://github.com/[USER_REDACTED]ndas-dev/pandas/pull/60681), seeing how this goes now without the additional changes (although I assume we will have to add some of those build config updates to get the builds passing)\n\nWhile the temporary suppressing of `-Werror` is not ideal (for new warnings), in practice we already have all those warnings anyway (there are present in the wheels builds which already use newer meson, and just don't bubble up in most CI with the older versions).\n\nCloses #63686", "author": "user_7213a217ace7", "created_at": "2026-01-15T12:54:34+00:00", "merged_at": "2026-01-15T16:20:31+00:00", "base_branch": "main", "head_branch": "bump-meson", "additions": 27, "deletions": 25, "changed_files": 13, "files": [ { "filename": ".github/actions/build_pandas/action.yml", "status": "modified", "additions": 2, "deletions": 1, "changes": 3, "patch": "@@ -6,7 +6,8 @@ inputs:\n default: true\n werror:\n description: Enable werror flag for build\n- default: true\n+ # TMP disable werror until we fix all warnings with more recent meson\n+ default: false\n runs:\n using: composite\n steps:" }, { "filename": ".github/workflows/unit-tests.yml", "status": "modified", "additions": 4, "deletions": 3, "changes": 7, "patch": "@@ -166,9 +166,10 @@ jobs:\n - name: [NAME_REDACTED]\n id: build\n uses: ./.github/actions/build_pandas\n- with:\n- # xref https://github.com/[USER_REDACTED]n/cython/issues/6870\n- werror: ${{ matrix.name != 'Freethreading' }}\n+ # TMP disable werror until we fix all warnings with more recent meson\n+ # with:\n+ # # xref https://github.com/[USER_REDACTED]n/cython/issues/6870\n+ # werror: ${{ matrix.name != 'Freethreading' }}\n \n - name: Test (not single_cpu)\n uses: ./.github/actions/run-tests" }, { "filename": "ci/deps/actions-311-minimum_versions.yaml", "status": "modified", "additions": 1, "deletions": 1, "changes": 2, "patch": "@@ -10,7 +10,7 @@ dependencies:\n - versioneer\n - cython<4.0.0a0\n - meson=1.2.1\n- - meson-python=0.13.1\n+ - meson-python=0.17.1\n \n # test dependencies\n - pytest>=8.3.4" }, { "filename": "ci/deps/actions-311.yaml", "status": "modified", "additions": 2, "deletions": 2, "changes": 4, "patch": "@@ -7,8 +7,8 @@ dependencies:\n # build dependencies\n - versioneer\n - cython<4.0.0a0\n- - meson=1.2.1\n- - meson-python=0.13.1\n+ - meson=1.10.0\n+ - meson-python=0.18.0\n \n # test dependencies\n - pytest>=8.3.4" }, { "filename": "ci/deps/actions-312.yaml", "status": "modified", "additions": 2, "deletions": 2, "changes": 4, "patch": "@@ -7,8 +7,8 @@ dependencies:\n # build dependencies\n - versioneer\n - cython<4.0.0a0\n- - meson=1.2.1\n- - meson-python=0.13.1\n+ - meson=1.10.0\n+ - meson-python=0.18.0\n \n # test dependencies\n - pytest>=8.3.4" }, { "filename": "ci/deps/actions-313-downstream_compat.yaml", "status": "modified", "additions": 2, "deletions": 2, "changes": 4, "patch": "@@ -8,8 +8,8 @@ dependencies:\n # build dependencies\n - versioneer\n - cython<4.0.0a0\n- - meson=1.2.1\n- - meson-python=0.13.1\n+ - meson=1.10.0\n+ - meson-python=0.18.0\n \n # test dependencies\n - pytest>=8.3.4" }, { "filename": "ci/deps/actions-313-freethreading.yaml", "status": "modified", "additions": 1, "deletions": 1, "changes": 2, "patch": "@@ -8,7 +8,7 @@ dependencies:\n - setuptools\n - versioneer\n - cython<4.0.0a0\n- - meson=1.8.0\n+ - meson=1.10.0\n - meson-python=0.18.0\n \n # test dependencies" }, { "filename": "ci/deps/actions-313-numpydev.yaml", "status": "modified", "additions": 2, "deletions": 2, "changes": 4, "patch": "@@ -6,8 +6,8 @@ dependencies:\n \n # build dependencies\n - versioneer\n- - meson=1.2.1\n- - meson-python=0.13.1\n+ - meson=1.10.0\n+ - meson-python=0.18.0\n - cython<4.0.0a0\n \n # test dependencies" }, { "filename": "ci/deps/actions-313-pyarrownightly.yaml", "status": "modified", "additions": 2, "deletions": 2, "changes": 4, "patch": "@@ -6,9 +6,9 @@ dependencies:\n \n # build dependencies\n - versioneer\n- - meson=1.2.1\n - cython<4.0.0a0\n- - meson-python=0.13.1\n+ - meson=1.10.0\n+ - meson-python=0.18.0\n \n # test dependencies\n - pytest>=8.3.4" }, { "filename": "ci/deps/actions-313.yaml", "status": "modified", "additions": 2, "deletions": 2, "changes": 4, "patch": "@@ -7,8 +7,8 @@ dependencies:\n # build dependencies\n - versioneer\n - cython<4.0.0a0\n- - meson=1.2.1\n- - meson-python=0.13.1\n+ - meson=1.10.0\n+ - meson-python=0.18.0\n \n # test dependencies\n - pytest>=8.3.4" }, { "filename": "environment.yml", "status": "modified", "additions": 2, "deletions": 2, "changes": 4, "patch": "@@ -9,8 +9,8 @@ dependencies:\n # build dependencies\n - versioneer\n - cython<4.0.0a0\n- - meson=1.2.1\n- - meson-python=0.13.1\n+ - meson>=1.2.1,<2\n+ - meson-python>=0.17.1,<1\n \n # test dependencies\n - pytest>=8.3.4" }, { "filename": "pyproject.toml", "status": "modified", "additions": 3, "deletions": 3, "changes": 6, "patch": "@@ -2,13 +2,13 @@\n # Minimum requirements for the build system to execute.\n # See https://github.com/scipy/scipy/pull/12940 for the AIX issue.\n requires = [\n- \"meson-python>=0.13.1\",\n+ \"meson-python>=0.17.1,<1\",\n \"meson>=1.2.1,<2\",\n \"wheel\",\n \"Cython<4.0.0a0\", # Note: sync with setup.py, environment.yml and asv.conf.json\n- # Force numpy higher than 2.0rc1, so that built wheels are compatible\n+ # Force numpy higher than 2.0, so that built wheels are compatible\n # with both numpy 1 and 2\n- \"numpy>=2.0.0rc1\",\n+ \"numpy>=2.0.0\",\n \"versioneer[toml]\"\n ]" }, { "filename": "requirements-dev.txt", "status": "modified", "additions": 2, "deletions": 2, "changes": 4, "patch": "@@ -4,8 +4,8 @@\n pip\n versioneer[toml]\n cython<4.0.0a0\n-meson[ninja]==1.2.1\n-meson-python==0.13.1\n+meson[ninja]>=1.2.1,<2\n+meson-python>=0.17.1,<1\n pytest>=8.3.4\n pytest-cov\n pytest-xdist>=3.6.1" } ], "reviews": [ { "id": 3666206523, "user": "user_2814cc0f9d86", "state": "APPROVED", "body": "LGTM. Bumping the build tools is necessary. Disabling `werror` temporarily is a pragmatic move to get this landed.", "submitted_at": "2026-01-15T15:31:20+00:00" }, { "id": 3666484508, "user": "user_c9260bc45a59", "state": "APPROVED", "body": null, "submitted_at": "2026-01-15T16:20:16+00:00" } ], "review_comments": [ { "id": 2695079648, "user": "user_c9260bc45a59", "body": "Could you create a follow up issue about re-enabling werror?", "path": ".github/actions/build_pandas/action.yml", "line": 9, "side": "RIGHT", "created_at": "2026-01-15T16:20:10+00:00" } ], "meta": { "languages": [ "toml", "txt", "yaml", "yml" ], "touches_tests": false, "review_state_summary": { "APPROVED": 2 }, "meaningful_comment_count": 1, "has_approval": true, "has_changes_requested": false, "total_review_comments": 1 } } { "_id": "476cfb4f7bdbf60c", "_schema_version": "1.0", "_cleaned_at": "2026-02-12T07:46:51.860650+00:00", "repo": "pandas-dev/pandas", "repo_url": "https://github.com/pandas-dev/pandas", "license_name": "BSD 3-Clause \"New\" or \"Revised\" License", "license_spdx": "BSD-3-Clause", "pr_number": 63695, "title": "DOC: Fix GL08 for pandas.tseries.offsets.BusinessDay.calendar", "body": "- [ ] related to #60365\n\nFixes\n\n```\npandas.tseries.offsets.BusinessDay.calendar GL08\npandas.tseries.offsets.BusinessHour.calendar GL08\npandas.tseries.offsets.CustomBusinessDay.calendar GL08\npandas.tseries.offsets.CustomBusinessHour.calendar GL08\npandas.tseries.offsets.CustomBusinessMonthBegin.calendar GL08\npandas.tseries.offsets.CustomBusinessMonthEnd.calendar GL08\n```", "author": "user_8905a7db72f0", "created_at": "2026-01-15T08:49:29+00:00", "merged_at": "2026-01-15T21:45:31+00:00", "base_branch": "main", "head_branch": "pandas.tseries.offsets.BusinessDay.calendar", "additions": 47, "deletions": 9, "changed_files": 2, "files": [ { "filename": "ci/code_checks.sh", "status": "modified", "additions": 0, "deletions": 6, "changes": 6, "patch": "@@ -82,11 +82,9 @@ if [[ -z \"$CHECK\" || \"$CHECK\" == \"docstrings\" ]]; then\n -i \"pandas.tseries.offsets.BYearBegin.is_on_offset GL08\" \\\n -i \"pandas.tseries.offsets.BYearEnd.is_on_offset GL08\" \\\n -i \"pandas.tseries.offsets.BusinessDay PR02,SA01\" \\\n- -i \"pandas.tseries.offsets.BusinessDay.calendar GL08\" \\\n -i \"pandas.tseries.offsets.BusinessDay.is_on_offset GL08\" \\\n -i \"pandas.tseries.offsets.BusinessDay.weekmask GL08\" \\\n -i \"pandas.tseries.offsets.BusinessHour PR02,SA01\" \\\n- -i \"pandas.tseries.offsets.BusinessHour.calendar GL08\" \\\n -i \"pandas.tseries.offsets.BusinessHour.is_on_offset GL08\" \\\n -i \"pandas.tseries.offsets.BusinessHour.weekmask GL08\" \\\n -i \"pandas.tseries.offsets.BusinessMonthBegin.is_on_offset GL08\" \\\n@@ -95,19 +93,15 @@ if [[ -z \"$CHECK\" || \"$CHECK\" == \"docstrings\" ]]; then\n -i \"pandas.tseries.offsets.CBMonthEnd PR02\" \\\n -i \"pandas.tseries.offsets.CDay PR02,SA01\" \\\n -i \"pandas.tseries.offsets.CustomBusinessDay PR02,SA01\" \\\n- -i \"pandas.tseries.offsets.CustomBusinessDay.calendar GL08\" \\\n -i \"pandas.tseries.offsets.CustomBusinessDay.is_on_offset GL08\" \\\n -i \"pandas.tseries.offsets.CustomBusinessDay.weekmask GL08\" \\\n -i \"pandas.tseries.offsets.CustomBusinessHour PR02,SA01\" \\\n- -i \"pandas.tseries.offsets.CustomBusinessHour.calendar GL08\" \\\n -i \"pandas.tseries.offsets.CustomBusinessHour.is_on_offset GL08\" \\\n -i \"pandas.tseries.offsets.CustomBusinessHour.weekmask GL08\" \\\n -i \"pandas.tseries.offsets.CustomBusinessMonthBegin PR02\" \\\n- -i \"pandas.tseries.offsets.CustomBusinessMonthBegin.calendar GL08\" \\\n -i \"pandas.tseries.offsets.CustomBusinessMonthBegin.m_offset GL08\" \\\n -i \"pandas.tseries.offsets.CustomBusinessMonthBegin.weekmask GL08\" \\\n -i \"pandas.tseries.offsets.CustomBusinessMonthEnd PR02\" \\\n- -i \"pandas.tseries.offsets.CustomBusinessMonthEnd.calendar GL08\" \\\n -i \"pandas.tseries.offsets.CustomBusinessMonthEnd.m_offset GL08\" \\\n -i \"pandas.tseries.offsets.CustomBusinessMonthEnd.weekmask GL08\" \\\n -i \"pandas.tseries.offsets.DateOffset.is_on_offset GL08\" \\" }, { "filename": "pandas/_libs/tslibs/offsets.pyx", "status": "modified", "additions": 47, "deletions": 3, "changes": 50, "patch": "@@ -1905,7 +1905,7 @@ cdef class BusinessMixin(SingleConstructorOffset):\n cdef readonly:\n timedelta _offset\n # [NAME_REDACTED] subclasses use weekmask, holiday, calendar\n- object weekmask, _holidays, calendar\n+ object weekmask, _holidays, _calendar\n \n def __init__(self, n=1, normalize=False, offset=timedelta(0)):\n BaseOffset.__init__(self, n, normalize)\n@@ -1923,7 +1923,7 @@ cdef class BusinessMixin(SingleConstructorOffset):\n # holidays, weekmask\n self.weekmask = weekmask\n self._holidays = holidays\n- self.calendar = calendar\n+ self._calendar = calendar\n \n [USER_REDACTED]\n def offset(self):\n@@ -2011,6 +2011,50 @@ cdef class BusinessMixin(SingleConstructorOffset):\n \"\"\"\n return self._holidays\n \n+ [USER_REDACTED]\n+ def calendar(self):\n+ \"\"\"\n+ Return the calendar used for business day calculations.\n+\n+ This property returns the numpy busdaycalendar object used for\n+ determining valid business days. For standard business day offsets\n+ (e.g., BusinessDay, BusinessHour), this returns None. For custom\n+ business day offsets, this returns the calendar that was either\n+ passed directly or constructed from weekmask and holidays.\n+\n+ Returns\n+ -------\n+ np.busdaycalendar or None\n+ The business day calendar used for calculations, or None if\n+ using default business day rules.\n+\n+ See Also\n+ --------\n+ BusinessDay.holidays : Holidays for standard business day offset.\n+ CustomBusinessDay.holidays : Holidays for custom business day offset.\n+ CustomBusinessDay.weekmask : Weekmask for custom business day offset.\n+\n+ Examples\n+ --------\n+ For standard business offsets, calendar is None:\n+\n+ >>> bd = pd.offsets.BusinessDay()\n+ >>> bd.calendar is None\n+ True\n+\n+ >>> bh = pd.offsets.BusinessHour()\n+ >>> bh.calendar is None\n+ True\n+\n+ For custom business day with explicit holidays:\n+\n+ >>> holidays = [pd.Timestamp(\"2023-12-25\"), pd.Timestamp(\"2024-01-01\")]\n+ >>> cbd = pd.offsets.CustomBusinessDay(holidays=holidays)\n+ >>> isinstance(cbd.calendar, np.busdaycalendar)\n+ True\n+ \"\"\"\n+ return self._calendar\n+\n def _repr_attrs(self) -> str:\n if self.offset:\n attrs = [f\"offset={repr(self.offset)}\"]\n@@ -2037,7 +2081,7 @@ cdef class BusinessMixin(SingleConstructorOffset):\n holidays=holidays,\n calendar=None)\n self.weekmask = weekmask\n- self.calendar = calendar\n+ self._calendar = calendar\n self._holidays = holidays\n \n BaseOffset.__setstate__(self, state)" } ], "reviews": [ { "id": 3666454576, "user": "user_c9260bc45a59", "state": "COMMENTED", "body": null, "submitted_at": "2026-01-15T16:15:46+00:00" }, { "id": 3666462218, "user": "user_8905a7db72f0", "state": "COMMENTED", "body": null, "submitted_at": "2026-01-15T16:16:46+00:00" }, { "id": 3667726657, "user": "user_c9260bc45a59", "state": "APPROVED", "body": null, "submitted_at": "2026-01-15T21:45:20+00:00" } ], "review_comments": [ { "id": 2695056889, "user": "user_c9260bc45a59", "body": "Why does this need a skip?", "path": "pandas/_libs/tslibs/offsets.pyx", "line": null, "side": "RIGHT", "created_at": "2026-01-15T16:15:46+00:00" }, { "id": 2695062425, "user": "user_8905a7db72f0", "body": "forgot to remove that. as I was testing them one by one. changing it.", "path": "pandas/_libs/tslibs/offsets.pyx", "line": null, "side": "RIGHT", "created_at": "2026-01-15T16:16:46+00:00" } ], "meta": { "languages": [ "pyx", "sh" ], "touches_tests": false, "review_state_summary": { "COMMENTED": 2, "APPROVED": 1 }, "meaningful_comment_count": 2, "has_approval": true, "has_changes_requested": false, "total_review_comments": 2 } } { "_id": "a45b36bd38567c00", "_schema_version": "1.0", "_cleaned_at": "2026-02-12T07:46:51.860650+00:00", "repo": "pandas-dev/pandas", "repo_url": "https://github.com/pandas-dev/pandas", "license_name": "BSD 3-Clause \"New\" or \"Revised\" License", "license_spdx": "BSD-3-Clause", "pr_number": 63682, "title": "TST: ensure categorical index levels remain categorical in merge", "body": "- [x] closes #37480\n\nThe reproducible example works correctly on main. Added a test to cover it.", "author": "user_29def2a2fd98", "created_at": "2026-01-14T11:32:36+00:00", "merged_at": "2026-01-15T21:43:44+00:00", "base_branch": "main", "head_branch": "tst-category-index-levels-in-merge", "additions": 31, "deletions": 0, "changed_files": 1, "files": [ { "filename": "pandas/tests/reshape/merge/test_merge.py", "status": "modified", "additions": 31, "deletions": 0, "changes": 31, "patch": "@@ -2214,6 +2214,37 @@ def test_merge_on_int_array(self):\n )\n tm.assert_frame_equal(result, expected)\n \n+ def test_merge_category_index_levels_stay_category(self):\n+ # GH#37480\n+ df1 = DataFrame(\n+ {\n+ \"x\": list(range(1, 10)),\n+ \"y\": list(range(1, 10)),\n+ \"z\": list(range(1, 10)),\n+ \"d\": list(range(1, 10)),\n+ }\n+ )\n+\n+ df2 = df1.astype({\"x\": \"category\", \"y\": \"category\", \"z\": \"category\"})\n+\n+ df3 = df2.iloc[:4, :].groupby([\"z\", \"x\"], observed=True).agg({\"d\": \"sum\"})\n+ df4 = df2.iloc[7:, :].groupby([\"z\", \"x\", \"y\"], observed=True).agg({\"d\": \"sum\"})\n+ result = merge(df3, df4, left_index=True, right_index=True, how=\"outer\")\n+\n+ cats = list(range(1, 10))\n+ z = Categorical(list(range(1, 5)) + list(range(8, 10)), categories=cats)\n+ x = Categorical(list(range(1, 5)) + list(range(8, 10)), categories=cats)\n+ y = Categorical([np.nan] * 4 + list(range(8, 10)), categories=cats)\n+ idx = MultiIndex.from_arrays([z, x, y], names=[\"z\", \"x\", \"y\"])\n+ expected = DataFrame(\n+ {\n+ \"d_x\": list(map(float, range(1, 5))) + [np.nan] * 2,\n+ \"d_y\": [np.nan] * 4 + list(map(float, range(8, 10))),\n+ },\n+ index=idx,\n+ )\n+ tm.assert_frame_equal(result, expected)\n+\n \n class TestMergeOnIndexes:\n [USER_REDACTED].mark.parametrize(" } ], "reviews": [ { "id": 3662183172, "user": "user_c9260bc45a59", "state": "COMMENTED", "body": null, "submitted_at": "2026-01-14T18:28:56+00:00" }, { "id": 3667208103, "user": "user_c9260bc45a59", "state": "COMMENTED", "body": null, "submitted_at": "2026-01-15T19:24:45+00:00" }, { "id": 3667401585, "user": "user_29def2a2fd98", "state": "COMMENTED", "body": null, "submitted_at": "2026-01-15T20:15:40+00:00" }, { "id": 3667709052, "user": "user_c9260bc45a59", "state": "APPROVED", "body": null, "submitted_at": "2026-01-15T21:40:37+00:00" } ], "review_comments": [ { "id": 2691573125, "user": "user_c9260bc45a59", "body": "1. Could you just assign `result = merge(df3, df4, left_index=True, right_index=True, how=\"outer\")`\n2. Could you construct an `expected = ` DataFrame an use `tm.assert_frame_equal`?", "path": "pandas/tests/reshape/merge/test_merge.py", "line": null, "side": "RIGHT", "created_at": "2026-01-14T18:28:57+00:00" }, { "id": 2695663069, "user": "user_c9260bc45a59", "body": "Sorry one last comment. Could we make the data sizes smaller i.e. use 10 instead of 100?", "path": "pandas/tests/reshape/merge/test_merge.py", "line": null, "side": "RIGHT", "created_at": "2026-01-15T19:24:40+00:00" }, { "id": 2695815766, "user": "user_29def2a2fd98", "body": "[USER_REDACTED], thank you for reviewing this PR. I reduced the data sizes to 10.", "path": "pandas/tests/reshape/merge/test_merge.py", "line": null, "side": "RIGHT", "created_at": "2026-01-15T20:15:40+00:00" } ], "meta": { "languages": [ "py" ], "touches_tests": true, "review_state_summary": { "COMMENTED": 3, "APPROVED": 1 }, "meaningful_comment_count": 3, "has_approval": true, "has_changes_requested": false, "total_review_comments": 3 } } { "_id": "b21089a462f79fae", "_schema_version": "1.0", "_cleaned_at": "2026-02-12T07:46:51.860650+00:00", "repo": "pandas-dev/pandas", "repo_url": "https://github.com/pandas-dev/pandas", "license_name": "BSD 3-Clause \"New\" or \"Revised\" License", "license_spdx": "BSD-3-Clause", "pr_number": 63675, "title": "DOC: Inline docstring in `pandas/core/indexes/multi.py`", "body": "- [ ] closes #xxxx (Replace xxxx with the GitHub issue number)\n- [ ] [Tests added and passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#writing-tests) if fixing a bug or adding a new feature\n- [x] All [code checks passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit).\n- [ ] Added [type annotations](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#type-hints) to new arguments/methods/functions.\n- [ ] Added an entry in the latest `doc/source/whatsnew/vX.X.X.rst` file if fixing a bug or adding a new feature.\n- [ ] If I used AI to develop this pull request, I prompted it to follow `AGENTS.md`.\n\nThis is a part of https://github.com/[USER_REDACTED]ndas-dev/pandas/issues/62437", "author": "user_5b0b62fe7839", "created_at": "2026-01-13T12:17:06+00:00", "merged_at": "2026-01-17T18:20:19+00:00", "base_branch": "main", "head_branch": "inline_idx_multi", "additions": 307, "deletions": 14, "changed_files": 1, "files": [ { "filename": "pandas/core/indexes/multi.py", "status": "modified", "additions": 307, "deletions": 14, "changes": 321, "patch": "@@ -53,7 +53,6 @@\n )\n from pandas.util._decorators import (\n cache_readonly,\n- doc,\n set_module,\n )\n from pandas.util._exceptions import find_stack_level\n@@ -122,11 +121,6 @@\n Series,\n )\n \n-_index_doc_kwargs = dict(ibase._index_doc_kwargs)\n-_index_doc_kwargs.update(\n- {\"klass\": \"MultiIndex\", \"target_klass\": \"MultiIndex or list of tuples\"}\n-)\n-\n \n class MultiIndexUInt64Engine(libindex.BaseMultiIndexCodesEngine, libindex.UInt64Engine):\n \"\"\"Manages a MultiIndex by [NAME_REDACTED] positive integers.\n@@ -1293,8 +1287,19 @@ def _engine(self):\n def _constructor(self) -> Callable[..., MultiIndex]: # type: ignore[override]\n return type(self).from_tuples\n \n- [USER_REDACTED](Index._shallow_copy)\n def _shallow_copy(self, values: np.ndarray, name=lib.no_default) -> MultiIndex:\n+ \"\"\"\n+ Create a new Index with the same class as the caller, don't copy the\n+ data, use the same object attributes with passed in attributes taking\n+ precedence.\n+\n+ *this is an internal non-public method*\n+\n+ Parameters\n+ ----------\n+ values : the values to create the new Index, optional\n+ name : Label, defaults to self.name\n+ \"\"\"\n names = name if name is not lib.no_default else self.names\n \n return type(self).from_tuples(values, sortorder=None, names=names)\n@@ -1414,8 +1419,42 @@ def view(self, cls=None) -> Self:\n result._id = self._id\n return result\n \n- [USER_REDACTED](Index.__contains__)\n def __contains__(self, key: Any) -> bool:\n+ \"\"\"\n+ Return a boolean indicating whether the provided key is in the index.\n+\n+ Parameters\n+ ----------\n+ key : label\n+ The key to check if it is present in the index.\n+\n+ Returns\n+ -------\n+ bool\n+ Whether the key search is in the index.\n+\n+ Raises\n+ ------\n+ TypeError\n+ If the key is not hashable.\n+\n+ See Also\n+ --------\n+ Index.isin : Returns an ndarray of boolean dtype indicating whether the\n+ list-like key is in the index.\n+\n+ Examples\n+ --------\n+ >>> mi = pd.MultiIndex.from_arrays([[\"a\"], [\"b\"], [\"c\"]])\n+ >>> mi\n+ MultiIndex([('a', 'b', 'c')],\n+ )\n+\n+ >>> \"a\" in mi\n+ True\n+ >>> \"x\" in mi\n+ False\n+ \"\"\"\n hash(key)\n try:\n self.get_loc(key)\n@@ -1439,8 +1478,37 @@ def f(dtype) -> bool:\n return any(f(level.dtype) for level in self.levels)\n \n # Cannot determine type of \"memory_usage\"\n- [USER_REDACTED](Index.memory_usage) # type: ignore[has-type]\n def memory_usage(self, deep: bool = False) -> int:\n+ \"\"\"\n+ Memory usage of the values.\n+\n+ Parameters\n+ ----------\n+ deep : bool, default False\n+ Introspect the data deeply, interrogate\n+ `object` dtypes for system-level memory consumption.\n+\n+ Returns\n+ -------\n+ bytes used\n+ Returns memory usage of the values in the Index in bytes.\n+\n+ See Also\n+ --------\n+ numpy.ndarray.nbytes : Total bytes consumed by [NAME_REDACTED]\n+ array.\n+\n+ Notes\n+ -----\n+ Memory usage does not include memory consumed by [NAME_REDACTED]\n+ are not components of the array if deep=False or if used on PyPy\n+\n+ Examples\n+ --------\n+ >>> mi = pd.MultiIndex.from_arrays([[\"a\"], [\"b\"], [\"c\"]])\n+ >>> mi.memory_usage()\n+ 81\n+ \"\"\"\n # we are overwriting our base class to avoid\n # computing .values here which could materialize\n # a tuple representation unnecessarily\n@@ -1750,8 +1818,61 @@ def is_monotonic_decreasing(self) -> bool:\n # monotonic decreasing if and only if reverse is monotonic increasing\n return self[::-1].is_monotonic_increasing\n \n- [USER_REDACTED](Index.duplicated)\n def duplicated(self, keep: DropKeep = \"first\") -> npt.NDArray[np.bool_]:\n+ \"\"\"\n+ Indicate duplicate index values.\n+\n+ Duplicated values are indicated as ``True`` values in the resulting\n+ array. Either all duplicates, all except the first, or all except the\n+ last occurrence of duplicates can be indicated.\n+\n+ Parameters\n+ ----------\n+ keep : {'first', 'last', False}, default 'first'\n+ The value or values in a set of duplicates to mark as missing.\n+\n+ - 'first' : Mark duplicates as ``True`` except for the first\n+ occurrence.\n+ - 'last' : Mark duplicates as ``True`` except for the last\n+ occurrence.\n+ - ``False`` : Mark all duplicates as ``True``.\n+\n+ Returns\n+ -------\n+ np.ndarray[bool]\n+ A numpy array of boolean values indicating duplicate index values.\n+\n+ See Also\n+ --------\n+ Series.duplicated : Equivalent method on pandas.Series.\n+ DataFrame.duplicated : Equivalent method on pandas.DataFrame.\n+ Index.drop_duplicates : Remove duplicate values from Index.\n+\n+ Examples\n+ --------\n+ By default, for each set of duplicated values, the first occurrence is\n+ set to False and all others to True:\n+\n+ >>> mi = pd.MultiIndex.from_arrays((list(\"abca\"), list(\"defd\")))\n+ >>> mi.duplicated()\n+ array([False, False, False, True])\n+\n+ which is equivalent to\n+\n+ >>> mi.duplicated(keep=\"first\")\n+ array([False, False, False, True])\n+\n+ By using 'last', the last occurrence of each set of duplicated values\n+ is set on False and all others on True:\n+\n+ >>> mi.duplicated(keep=\"last\")\n+ array([ True, False, False, False])\n+\n+ By [NAME_REDACTED] ``False``, all duplicates are True:\n+\n+ >>> mi.duplicated(keep=False)\n+ array([ True, False, False, True])\n+ \"\"\"\n shape = tuple(len(lev) for lev in self.levels)\n ids = get_group_index(self.codes, shape, sort=False, xnull=False)\n \n@@ -1767,8 +1888,36 @@ def fillna(self, value):\n \"\"\"\n raise NotImplementedError(\"fillna is not defined for MultiIndex\")\n \n- [USER_REDACTED](Index.dropna)\n def dropna(self, how: AnyAll = \"any\") -> MultiIndex:\n+ \"\"\"\n+ [NAME_REDACTED] without NA/NaN values.\n+\n+ Parameters\n+ ----------\n+ how : {'any', 'all'}, default 'any'\n+ Drop the value when any or all levels are NaN.\n+\n+ Returns\n+ -------\n+ Index\n+ Returns an MultiIndex object after removing NA/NaN values.\n+\n+ See Also\n+ --------\n+ Index.fillna : Fill NA/NaN values with the specified value.\n+ Index.isna : Detect missing values.\n+\n+ Examples\n+ --------\n+ >>> mi = pd.MultiIndex.from_arrays(([np.nan, np.nan, 2.0], [3.0, np.nan, 4.0]))\n+ >>> mi.dropna()\n+ MultiIndex([(2.0, 4.0)],\n+ )\n+ >>> mi.dropna(how=\"all\")\n+ MultiIndex([(nan, 3.0),\n+ (2.0, 4.0)],\n+ )\n+ \"\"\"\n nans = [level_codes == -1 for level_codes in self.codes]\n if how == \"any\":\n indexer = np.any(nans, axis=0)\n@@ -1874,8 +2023,43 @@ def get_level_values(self, level) -> Index:\n values = self._get_level_values(level)\n return values\n \n- [USER_REDACTED](Index.unique)\n def unique(self, level=None):\n+ \"\"\"\n+ Return unique values in the index.\n+\n+ Unique values are returned in order of appearance, this does NOT sort.\n+\n+ Parameters\n+ ----------\n+ level : int or hashable, optional\n+ Only return values from specified level (for MultiIndex).\n+ If int, gets the level by [NAME_REDACTED], else by [NAME_REDACTED]\n+\n+ Returns\n+ -------\n+ MultiIndex\n+ Unique values in the MultiIndex.\n+\n+ See Also\n+ --------\n+ unique : Numpy array of unique values in that column.\n+ Series.unique : Return unique values of Series object.\n+\n+ Examples\n+ --------\n+ >>> mi = pd.MultiIndex.from_arrays((list(\"abca\"), list(\"defd\")))\n+ >>> mi\n+ MultiIndex([('a', 'd'),\n+ ('b', 'e'),\n+ ('c', 'f'),\n+ ('a', 'd')],\n+ )\n+ >>> mi.unique()\n+ MultiIndex([('a', 'd'),\n+ ('b', 'e'),\n+ ('c', 'f')],\n+ )\n+ \"\"\"\n if level is None:\n return self.drop_duplicates()\n else:\n@@ -4165,8 +4349,50 @@ def _convert_can_do_setop(self, other):\n \n # --------------------------------------------------------------------\n \n- [USER_REDACTED](Index.astype)\n def astype(self, dtype, copy: bool = True):\n+ \"\"\"\n+ Create an MultiIndex with values cast to dtypes.\n+\n+ The class of a new Index is determined by dtype. When conversion is\n+ impossible, a TypeError exception is raised.\n+\n+ Parameters\n+ ----------\n+ dtype : numpy dtype or pandas type\n+ Note that any signed integer `dtype` is treated as ``'int64'``,\n+ and any unsigned integer `dtype` is treated as ``'uint64'``,\n+ regardless of the size.\n+ copy : bool, default True\n+ By default, astype always returns a newly allocated object.\n+ If copy is set to False and internal requirements on dtype are\n+ satisfied, the original data is used to create a new Index\n+ or the original Index is returned.\n+\n+ Returns\n+ -------\n+ MultiIndex\n+ MultiIndex with values cast to specified dtype.\n+\n+ See Also\n+ --------\n+ Index.dtype: Return the dtype object of the underlying data.\n+ Index.dtypes: Return the dtype object of the underlying data.\n+ Index.convert_dtypes: Convert columns to the best possible dtypes.\n+\n+ Examples\n+ --------\n+ >>> mi = pd.MultiIndex.from_arrays(([1, 2, 3], [4, 5, 6]))\n+ >>> mi\n+ MultiIndex([(1, 4),\n+ (2, 5),\n+ (3, 6)],\n+ )\n+ >>> mi.astype(\"object\")\n+ MultiIndex([(1, 4),\n+ (2, 5),\n+ (3, 6)],\n+ )\n+ \"\"\"\n dtype = pandas_dtype(dtype)\n if isinstance(dtype, CategoricalDtype):\n msg = \"> 1 ndim Categorical are not supported at this time\"\n@@ -4287,8 +4513,75 @@ def delete(self, loc) -> MultiIndex:\n verify_integrity=False,\n )\n \n- [USER_REDACTED](Index.isin)\n def isin(self, values, level=None) -> npt.NDArray[np.bool_]:\n+ \"\"\"\n+ Return a boolean array where the index values are in `values`.\n+\n+ Compute boolean array of whether each index value is found in the\n+ passed set of values. The length of the returned boolean array matches\n+ the length of the index.\n+\n+ Parameters\n+ ----------\n+ values : set or list-like\n+ Sought values.\n+ level : str or int, optional\n+ Name or position of the index level to use (if the index is a\n+ `MultiIndex`).\n+\n+ Returns\n+ -------\n+ np.ndarray[bool]\n+ NumPy array of boolean values.\n+\n+ See Also\n+ --------\n+ Series.isin : Same for Series.\n+ DataFrame.isin : Same method for DataFrames.\n+\n+ Notes\n+ -----\n+ In the case of `MultiIndex` you must either specify `values` as a\n+ list-like object containing tuples that are the same length as the\n+ number of levels, or specify `level`. Otherwise it will raise a\n+ ``ValueError``.\n+\n+ If `level` is specified:\n+\n+ - if it is the name of one *and only one* index level, use that level;\n+ - otherwise it should be a number indicating level position.\n+\n+ Examples\n+ --------\n+ >>> idx = pd.Index([1, 2, 3])\n+ >>> idx\n+ Index([1, 2, 3], dtype='int64')\n+\n+ Check whether each index value in a list of values.\n+\n+ >>> idx.isin([1, 4])\n+ array([ True, False, False])\n+\n+ >>> mi = pd.MultiIndex.from_arrays(\n+ ... [[1, 2, 3], [\"red\", \"blue\", \"green\"]], names=[\"number\", \"color\"]\n+ ... )\n+ >>> mi\n+ MultiIndex([(1, 'red'),\n+ (2, 'blue'),\n+ (3, 'green')],\n+ names=['number', 'color'])\n+\n+ Check whether the strings in the 'color' level of the MultiIndex\n+ are in a list of colors.\n+\n+ >>> mi.isin([\"red\", \"orange\", \"yellow\"], level=\"color\")\n+ array([ True, False, False])\n+\n+ To check across the levels of a MultiIndex, pass a list of tuples:\n+\n+ >>> mi.isin([(1, \"red\"), (3, \"red\")])\n+ array([ True, False, False])\n+ \"\"\"\n if isinstance(values, Generator):\n values = list(values)" } ], "reviews": [ { "id": 3657048209, "user": "user_c9260bc45a59", "state": "COMMENTED", "body": null, "submitted_at": "2026-01-13T17:38:20+00:00" }, { "id": 3670955140, "user": "user_5b0b62fe7839", "state": "COMMENTED", "body": null, "submitted_at": "2026-01-16T13:47:42+00:00" }, { "id": 3674318755, "user": "user_c9260bc45a59", "state": "APPROVED", "body": null, "submitted_at": "2026-01-17T18:20:08+00:00" } ], "review_comments": [ { "id": 2687427003, "user": "user_c9260bc45a59", "body": "For all the `Examples` in this file, could you modify them to show using a `MultiIndex` instead of an `Index`?", "path": "pandas/core/indexes/multi.py", "line": 1, "side": "RIGHT", "created_at": "2026-01-13T17:38:20+00:00" }, { "id": 2698581217, "user": "user_5b0b62fe7839", "body": "sure!", "path": "pandas/core/indexes/multi.py", "line": 1, "side": "RIGHT", "created_at": "2026-01-16T13:47:41+00:00" } ], "meta": { "languages": [ "py" ], "touches_tests": false, "review_state_summary": { "COMMENTED": 2, "APPROVED": 1 }, "meaningful_comment_count": 1, "has_approval": true, "has_changes_requested": false, "total_review_comments": 2 } } { "_id": "ef81cdcd61ff8764", "_schema_version": "1.0", "_cleaned_at": "2026-02-12T07:46:51.860650+00:00", "repo": "pandas-dev/pandas", "repo_url": "https://github.com/pandas-dev/pandas", "license_name": "BSD 3-Clause \"New\" or \"Revised\" License", "license_spdx": "BSD-3-Clause", "pr_number": 63673, "title": "DOC: Inline docstring in `pandas/core/indexes/base.py`", "body": "- [ ] closes #xxxx (Replace xxxx with the GitHub issue number)\n- [ ] [Tests added and passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#writing-tests) if fixing a bug or adding a new feature\n- [x] All [code checks passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit).\n- [ ] Added [type annotations](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#type-hints) to new arguments/methods/functions.\n- [ ] Added an entry in the latest `doc/source/whatsnew/vX.X.X.rst` file if fixing a bug or adding a new feature.\n- [ ] If I used AI to develop this pull request, I prompted it to follow `AGENTS.md`.\n\nThis is a part of https://github.com/[USER_REDACTED]ndas-dev/pandas/issues/62437", "author": "user_5b0b62fe7839", "created_at": "2026-01-13T11:46:29+00:00", "merged_at": "2026-01-18T17:23:37+00:00", "base_branch": "main", "head_branch": "inline_idx_base", "additions": 188, "deletions": 6, "changed_files": 1, "files": [ { "filename": "pandas/core/indexes/base.py", "status": "modified", "additions": 188, "deletions": 6, "changes": 194, "patch": "@@ -72,9 +72,7 @@\n Pandas4Warning,\n )\n from pandas.util._decorators import (\n- Appender,\n cache_readonly,\n- doc,\n set_module,\n )\n from pandas.util._exceptions import (\n@@ -5023,8 +5021,73 @@ def values(self) -> ArrayLike:\n return data\n \n [USER_REDACTED]_readonly\n- [USER_REDACTED](IndexOpsMixin.array)\n def array(self) -> ExtensionArray:\n+ \"\"\"\n+ The ExtensionArray of the data backing this Index.\n+\n+ This property provides direct access to the underlying array data of\n+ an Index without requiring conversion to a NumPy array. It\n+ returns an ExtensionArray, which is the native storage format for\n+ pandas extension dtypes.\n+\n+ Returns\n+ -------\n+ ExtensionArray\n+ An ExtensionArray of the values stored within. For extension\n+ types, this is the actual array. For NumPy native types, this\n+ is a thin (no copy) wrapper around :class:`numpy.ndarray`.\n+\n+ ``.array`` differs from ``.values``, which may require converting\n+ the data to a different form.\n+\n+ See Also\n+ --------\n+ Index.to_numpy : Similar method that always returns a NumPy array.\n+ Series.to_numpy : Similar method that always returns a NumPy array.\n+\n+ Notes\n+ -----\n+ This table lays out the different array types for each extension\n+ dtype within pandas.\n+\n+ ================== =============================\n+ dtype array type\n+ ================== =============================\n+ category Categorical\n+ period PeriodArray\n+ interval IntervalArray\n+ [NAME_REDACTED]\n+ string StringArray\n+ boolean BooleanArray\n+ datetime64[ns, tz] DatetimeArray\n+ ================== =============================\n+\n+ For any 3rd-party extension types, the array type will be an\n+ ExtensionArray.\n+\n+ For all remaining dtypes ``.array`` will be a\n+ :class:`arrays.NumpyExtensionArray` wrapping the actual ndarray\n+ stored within. If you absolutely need a NumPy array (possibly with\n+ copying / coercing data), then use :meth:`Series.to_numpy` instead.\n+\n+ Examples\n+ --------\n+ For regular NumPy types like int, and float, a NumpyExtensionArray\n+ is returned.\n+\n+ >>> pd.Index([1, 2, 3]).array\n+ \n+ [1, 2, 3]\n+ Length: 3, dtype: int64\n+\n+ For extension types, like Categorical, the actual ExtensionArray\n+ is returned\n+\n+ >>> idx = pd.Index(pd.Categorical([\"a\", \"b\", \"a\"]))\n+ >>> idx.array\n+ ['a', 'b', 'a']\n+ Categories (2, str): ['a', 'b']\n+ \"\"\"\n array = self._data\n if isinstance(array, np.ndarray):\n from pandas.core.arrays.numpy_ import NumpyExtensionArray\n@@ -5130,8 +5193,37 @@ def _from_join_target(self, result: np.ndarray) -> ArrayLike:\n return type(self.values)._from_sequence(result, dtype=self.dtype)\n return result\n \n- [USER_REDACTED](IndexOpsMixin._memory_usage)\n def memory_usage(self, deep: bool = False) -> int:\n+ \"\"\"\n+ Memory usage of the values.\n+\n+ Parameters\n+ ----------\n+ deep : bool, default False\n+ Introspect the data deeply, interrogate\n+ `object` dtypes for system-level memory consumption.\n+\n+ Returns\n+ -------\n+ bytes used\n+ Returns memory usage of the values in the Index in bytes.\n+\n+ See Also\n+ --------\n+ numpy.ndarray.nbytes : Total bytes consumed by [NAME_REDACTED]\n+ array.\n+\n+ Notes\n+ -----\n+ Memory usage does not include memory consumed by [NAME_REDACTED]\n+ are not components of the array if deep=False or if used on PyPy\n+\n+ Examples\n+ --------\n+ >>> idx = pd.Index([1, 2, 3])\n+ >>> idx.memory_usage()\n+ 24\n+ \"\"\"\n result = self._memory_usage(deep=deep)\n \n # include our engine hashtable, only if it's already cached\n@@ -7469,10 +7561,55 @@ def _maybe_disable_logical_methods(self, opname: str_t) -> None:\n if isinstance(self, ABCMultiIndex):\n raise TypeError(f\"cannot perform {opname} with {type(self).__name__}\")\n \n- [USER_REDACTED](IndexOpsMixin.argmin.__doc__)\n def argmin(\n self, axis: AxisInt | None = None, skipna: bool = True, *args, **kwargs\n ) -> int:\n+ \"\"\"\n+ Return int position of the smallest value in the Index.\n+\n+ If the minimum is achieved in multiple locations,\n+ the first row position is returned.\n+\n+ Parameters\n+ ----------\n+ axis : None\n+ Unused. Parameter needed for compatibility with DataFrame.\n+ skipna : bool, default True\n+ Exclude NA/null values. If the entire Series is NA, or if ``skipna=False``\n+ and there is an NA value, this method will raise a ``ValueError``.\n+ *args, **kwargs\n+ Additional arguments and keywords for compatibility with NumPy.\n+\n+ Returns\n+ -------\n+ int\n+ Row position of the minimum value.\n+\n+ See Also\n+ --------\n+ Series.argmin : Return position of the minimum value.\n+ Series.argmax : Return position of the maximum value.\n+ numpy.ndarray.argmin : Equivalent method for numpy arrays.\n+ Series.idxmin : Return index label of the minimum values.\n+ Series.idxmax : Return index label of the maximum values.\n+\n+ Examples\n+ --------\n+ Consider dataset containing cereal calories\n+\n+ >>> idx = pd.Index([100.0, 110.0, 120.0, 110.0])\n+ >>> idx\n+ Index([100.0, 110.0, 120.0, 110.0], dtype='float64')\n+\n+ >>> idx.argmax()\n+ np.int64(2)\n+ >>> idx.argmin()\n+ np.int64(0)\n+\n+ The maximum cereal calories is the third element and\n+ the minimum cereal calories is the first element,\n+ since index is zero-indexed.\n+ \"\"\"\n nv.validate_argmin(args, kwargs)\n nv.validate_minmax_axis(axis)\n \n@@ -7484,10 +7621,55 @@ def argmin(\n \n return super().argmin(skipna=skipna)\n \n- [USER_REDACTED](IndexOpsMixin.argmax.__doc__)\n def argmax(\n self, axis: AxisInt | None = None, skipna: bool = True, *args, **kwargs\n ) -> int:\n+ \"\"\"\n+ Return int position of the largest value in the Index.\n+\n+ If the maximum is achieved in multiple locations,\n+ the first row position is returned.\n+\n+ Parameters\n+ ----------\n+ axis : None\n+ Unused. Parameter needed for compatibility with DataFrame.\n+ skipna : bool, default True\n+ Exclude NA/null values. If the entire Series is NA, or if ``skipna=False``\n+ and there is an NA value, this method will raise a ``ValueError``.\n+ *args, **kwargs\n+ Additional arguments and keywords for compatibility with NumPy.\n+\n+ Returns\n+ -------\n+ int\n+ Row position of the maximum value.\n+\n+ See Also\n+ --------\n+ Series.argmax : Return position of the maximum value.\n+ Series.argmin : Return position of the minimum value.\n+ numpy.ndarray.argmax : Equivalent method for numpy arrays.\n+ Series.idxmax : Return index label of the maximum values.\n+ Series.idxmin : Return index label of the minimum values.\n+\n+ Examples\n+ --------\n+ Consider dataset containing cereal calories\n+\n+ >>> idx = pd.Index([100.0, 110.0, 120.0, 110.0])\n+ >>> idx\n+ Index([100.0, 110.0, 120.0, 110.0], dtype='float64')\n+\n+ >>> idx.argmax()\n+ np.int64(2)\n+ >>> idx.argmin()\n+ np.int64(0)\n+\n+ The maximum cereal calories is the third element and\n+ the minimum cereal calories is the first element,\n+ since index is zero-indexed.\n+ \"\"\"\n nv.validate_argmax(args, kwargs)\n nv.validate_minmax_axis(axis)" } ], "reviews": [ { "id": 3657027571, "user": "user_c9260bc45a59", "state": "COMMENTED", "body": null, "submitted_at": "2026-01-13T17:32:20+00:00" }, { "id": 3657031209, "user": "user_c9260bc45a59", "state": "COMMENTED", "body": null, "submitted_at": "2026-01-13T17:33:19+00:00" }, { "id": 3657032252, "user": "user_c9260bc45a59", "state": "COMMENTED", "body": null, "submitted_at": "2026-01-13T17:33:38+00:00" }, { "id": 3657032791, "user": "user_c9260bc45a59", "state": "COMMENTED", "body": null, "submitted_at": "2026-01-13T17:33:47+00:00" }, { "id": 3657033567, "user": "user_c9260bc45a59", "state": "COMMENTED", "body": null, "submitted_at": "2026-01-13T17:34:01+00:00" }, { "id": 3670939384, "user": "user_5b0b62fe7839", "state": "COMMENTED", "body": null, "submitted_at": "2026-01-16T13:44:29+00:00" }, { "id": 3671779134, "user": "user_c9260bc45a59", "state": "APPROVED", "body": null, "submitted_at": "2026-01-16T16:46:18+00:00" }, { "id": 3675602501, "user": "user_c9260bc45a59", "state": "APPROVED", "body": null, "submitted_at": "2026-01-18T17:23:29+00:00" } ], "review_comments": [ { "id": 2687408838, "user": "user_c9260bc45a59", "body": "Could you make these examples show array being called from `Index`?", "path": "pandas/core/indexes/base.py", "line": null, "side": "RIGHT", "created_at": "2026-01-13T17:32:20+00:00" }, { "id": 2687411826, "user": "user_c9260bc45a59", "body": "```suggestion\n Return int position of the smallest value in the Index.\n```", "path": "pandas/core/indexes/base.py", "line": null, "side": "RIGHT", "created_at": "2026-01-13T17:33:19+00:00" }, { "id": 2687412764, "user": "user_c9260bc45a59", "body": "Likewise, could you make this show `Index` instead of `Series`?", "path": "pandas/core/indexes/base.py", "line": null, "side": "RIGHT", "created_at": "2026-01-13T17:33:38+00:00" }, { "id": 2687413210, "user": "user_c9260bc45a59", "body": "```suggestion\n Return int position of the largest value in the Index.\n```", "path": "pandas/core/indexes/base.py", "line": null, "side": "RIGHT", "created_at": "2026-01-13T17:33:47+00:00" }, { "id": 2687413928, "user": "user_c9260bc45a59", "body": "Same comment about using `Index` here instead", "path": "pandas/core/indexes/base.py", "line": null, "side": "RIGHT", "created_at": "2026-01-13T17:34:01+00:00" }, { "id": 2698570647, "user": "user_5b0b62fe7839", "body": "sure!", "path": "pandas/core/indexes/base.py", "line": null, "side": "RIGHT", "created_at": "2026-01-16T13:44:29+00:00" } ], "meta": { "languages": [ "py" ], "touches_tests": false, "review_state_summary": { "COMMENTED": 6, "APPROVED": 2 }, "meaningful_comment_count": 5, "has_approval": true, "has_changes_requested": false, "total_review_comments": 6 } } { "_id": "19d912087cea3d7c", "_schema_version": "1.0", "_cleaned_at": "2026-02-12T07:46:51.860650+00:00", "repo": "pandas-dev/pandas", "repo_url": "https://github.com/pandas-dev/pandas", "license_name": "BSD 3-Clause \"New\" or \"Revised\" License", "license_spdx": "BSD-3-Clause", "pr_number": 63672, "title": "DOC: Inline docstring in `pandas/core/strings/accessor.py`", "body": "- [ ] closes #xxxx (Replace xxxx with the GitHub issue number)\n- [ ] [Tests added and passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#writing-tests) if fixing a bug or adding a new feature\n- [x] All [code checks passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit).\n- [ ] Added [type annotations](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#type-hints) to new arguments/methods/functions.\n- [ ] Added an entry in the latest `doc/source/whatsnew/vX.X.X.rst` file if fixing a bug or adding a new feature.\n- [ ] If I used AI to develop this pull request, I prompted it to follow `AGENTS.md`.\n\nThis is a part of https://github.com/[USER_REDACTED]ndas-dev/pandas/issues/62437", "author": "user_5b0b62fe7839", "created_at": "2026-01-13T11:41:11+00:00", "merged_at": "2026-01-14T17:58:28+00:00", "base_branch": "main", "head_branch": "inline_acc", "additions": 763, "deletions": 525, "changed_files": 1, "files": [ { "filename": "pandas/core/strings/accessor.py", "status": "modified", "additions": 763, "deletions": 525, "changes": 1288, "patch": "@@ -22,7 +22,6 @@\n Scalar,\n npt,\n )\n-from pandas.util._decorators import Appender\n from pandas.util._exceptions import find_stack_level\n \n from pandas.core.dtypes.common import (\n@@ -67,7 +66,6 @@\n Series,\n )\n \n-_shared_docs: dict[str, str] = {}\n _cpython_optimized_encoders = (\n \"utf-8\",\n \"utf8\",\n@@ -699,207 +697,192 @@ def cat(\n out = res_ser.__finalize__(self._orig, method=\"str_cat\")\n return out\n \n- _shared_docs[\"str_split\"] = r\"\"\"\n- Split strings around given separator/delimiter.\n+ [USER_REDACTED]_nonstring_types([\"bytes\"])\n+ def split(\n+ self,\n+ pat: str | re.Pattern | None = None,\n+ *,\n+ n=-1,\n+ expand: bool = False,\n+ regex: bool | None = None,\n+ ):\n+ r\"\"\"\n+ Split strings around given separator/delimiter.\n \n- Splits the string in the Series/Index from the %(side)s,\n- at the specified delimiter string.\n+ Splits the string in the Series/Index from the beginning,\n+ at the specified delimiter string.\n \n- Parameters\n- ----------\n- pat : str%(pat_regex)s, optional\n- %(pat_description)s.\n- If not specified, split on whitespace.\n- n : int, default -1 (all)\n- Limit number of splits in output.\n- ``None``, 0 and -1 will be interpreted as return all splits.\n- expand : bool, default False\n- Expand the split strings into separate columns.\n-\n- - If ``True``, return DataFrame/MultiIndex expanding dimensionality.\n- - If ``False``, return Series/Index, containing lists of strings.\n- %(regex_argument)s\n- Returns\n- -------\n- Series, Index, DataFrame or MultiIndex\n- Type matches caller unless ``expand=True`` (see Notes).\n- %(raises_split)s\n- See Also\n- --------\n- Series.str.split : Split strings around given separator/delimiter.\n- Series.str.rsplit : Splits string around given separator/delimiter,\n- starting from the right.\n- Series.str.join : Join lists contained as elements in the Series/Index\n- with passed delimiter.\n- str.split : Standard library version for split.\n- str.rsplit : Standard library version for rsplit.\n-\n- Notes\n- -----\n- The handling of the `n` keyword depends on the number of found splits:\n-\n- - If found splits > `n`, make first `n` splits only\n- - If found splits <= `n`, make all splits\n- - If for a certain row the number of found splits < `n`,\n- append `None` for padding up to `n` if ``expand=True``\n-\n- If using ``expand=True``, Series and Index callers return DataFrame and\n- MultiIndex objects, respectively.\n- %(regex_pat_note)s\n- Examples\n- --------\n- >>> s = pd.Series(\n- ... [\n- ... \"this is a regular sentence\",\n- ... \"https://docs.python.org/3/tutorial/index.html\",\n- ... np.nan\n- ... ]\n- ... )\n- >>> s\n- 0 this is a regular sentence\n- 1 https://docs.python.org/3/tutorial/index.html\n- 2 NaN\n- dtype: str\n+ Parameters\n+ ----------\n+ pat : str or compiled regex, optional\n+ String or regular expression to split on.\n+ If not specified, split on whitespace.\n+ n : int, default -1 (all)\n+ Limit number of splits in output.\n+ ``None``, 0 and -1 will be interpreted as return all splits.\n+ expand : bool, default False\n+ Expand the split strings into separate columns.\n \n- In the default setting, the string is split by whitespace.\n+ - If ``True``, return DataFrame/MultiIndex expanding dimensionality.\n+ - If ``False``, return Series/Index, containing lists of strings.\n \n- >>> s.str.split()\n- 0 [this, is, a, regular, sentence]\n- 1 [https://docs.python.org/3/tutorial/index.html]\n- 2 NaN\n- dtype: object\n+ regex : bool, default None\n+ Determines if the passed-in pattern is a regular expression:\n \n- Without the `n` parameter, the outputs of `rsplit` and `split`\n- are identical.\n+ - If ``True``, assumes the passed-in pattern is a regular expression\n+ - If ``False``, treats the pattern as a literal string.\n+ - If ``None`` and `pat` length is 1, treats `pat` as a literal string.\n+ - If ``None`` and `pat` length is not 1, treats `pat` as a regular\n+ expression.\n+ - Cannot be set to False if `pat` is a compiled regex\n \n- >>> s.str.rsplit()\n- 0 [this, is, a, regular, sentence]\n- 1 [https://docs.python.org/3/tutorial/index.html]\n- 2 NaN\n- dtype: object\n+ Returns\n+ -------\n+ Series, Index, DataFrame or MultiIndex\n+ Type matches caller unless ``expand=True`` (see Notes).\n \n- The `n` parameter can be used to limit the number of splits on the\n- delimiter. The outputs of `split` and `rsplit` are different.\n+ Raises\n+ ------\n+ ValueError\n+ * if `regex` is False and `pat` is a compiled regex\n \n- >>> s.str.split(n=2)\n- 0 [this, is, a regular sentence]\n- 1 [https://docs.python.org/3/tutorial/index.html]\n- 2 NaN\n- dtype: object\n+ See Also\n+ --------\n+ Series.str.split : Split strings around given separator/delimiter.\n+ Series.str.rsplit : Splits string around given separator/delimiter,\n+ starting from the right.\n+ Series.str.join : Join lists contained as elements in the Series/Index\n+ with passed delimiter.\n+ str.split : Standard library version for split.\n+ str.rsplit : Standard library version for rsplit.\n \n- >>> s.str.rsplit(n=2)\n- 0 [this is a, regular, sentence]\n- 1 [https://docs.python.org/3/tutorial/index.html]\n- 2 NaN\n- dtype: object\n+ Notes\n+ -----\n+ The handling of the `n` keyword depends on the number of found splits:\n \n- The `pat` parameter can be used to split by [NAME_REDACTED]\n+ - If found splits > `n`, make first `n` splits only\n+ - If found splits <= `n`, make all splits\n+ - If for a certain row the number of found splits < `n`,\n+ append `None` for padding up to `n` if ``expand=True``\n \n- >>> s.str.split(pat=\"/\")\n- 0 [this is a regular sentence]\n- 1 [https:, , docs.python.org, 3, tutorial, index...\n- 2 NaN\n- dtype: object\n+ If using ``expand=True``, Series and Index callers return DataFrame and\n+ MultiIndex objects, respectively.\n \n- When using ``expand=True``, the split elements will expand out into\n- separate columns. If NaN is present, it is propagated throughout\n- the columns during the split.\n-\n- >>> s.str.split(expand=True)\n- 0 1 2 3 4\n- 0 this is a regular sentence\n- 1 https://docs.python.org/3/tutorial/index.html [NAME_REDACTED] NaN\n- 2 [NAME_REDACTED] [NAME_REDACTED]\n-\n- For slightly more complex use cases like splitting the html document name\n- from a url, a combination of parameter settings can be used.\n-\n- >>> s.str.rsplit(\"/\", n=1, expand=True)\n- 0 1\n- 0 this is a regular sentence NaN\n- 1 https://docs.python.org/3/tutorial index.html\n- 2 [NAME_REDACTED]\n- %(regex_examples)s\"\"\"\n-\n- [USER_REDACTED](\n- _shared_docs[\"str_split\"]\n- % {\n- \"side\": \"beginning\",\n- \"pat_regex\": \" or compiled regex\",\n- \"pat_description\": \"String or regular expression to split on\",\n- \"regex_argument\": \"\"\"\n- regex : bool, default None\n- Determines if the passed-in pattern is a regular expression:\n-\n- - If ``True``, assumes the passed-in pattern is a regular expression\n- - If ``False``, treats the pattern as a literal string.\n- - If ``None`` and `pat` length is 1, treats `pat` as a literal string.\n- - If ``None`` and `pat` length is not 1, treats `pat` as a regular expression.\n- - Cannot be set to False if `pat` is a compiled regex\n-\n- .. versionadded:: 1.4.0\n- \"\"\",\n- \"raises_split\": \"\"\"\n- Raises\n- ------\n- ValueError\n- * if `regex` is False and `pat` is a compiled regex\n- \"\"\",\n- \"regex_pat_note\": \"\"\"\n- Use of `regex =False` with a `pat` as a compiled regex will raise an error.\n- \"\"\",\n- \"method\": \"split\",\n- \"regex_examples\": r\"\"\"\n- Remember to escape special characters when explicitly using regular expressions.\n-\n- >>> s = pd.Series([\"foo and bar plus baz\"])\n- >>> s.str.split(r\"and|plus\", expand=True)\n- 0 1 2\n- 0 foo bar baz\n-\n- Regular expressions can be used to handle urls or file names.\n- When `pat` is a string and ``regex=None`` (the default), the given `pat` is compiled\n- as a regex only if ``len(pat) != 1``.\n-\n- >>> s = pd.Series(['foojpgbar.jpg'])\n- >>> s.str.split(r\".\", expand=True)\n- 0 1\n- 0 foojpgbar jpg\n-\n- >>> s.str.split(r\"\\.jpg\", expand=True)\n- 0 1\n- 0 foojpgbar\n-\n- When ``regex=True``, `pat` is interpreted as a regex\n-\n- >>> s.str.split(r\"\\.jpg\", regex=True, expand=True)\n- 0 1\n- 0 foojpgbar\n-\n- A compiled regex can be passed as `pat`\n-\n- >>> import re\n- >>> s.str.split(re.compile(r\"\\.jpg\"), expand=True)\n- 0 1\n- 0 foojpgbar\n-\n- When ``regex=False``, `pat` is interpreted as the string itself\n-\n- >>> s.str.split(r\"\\.jpg\", regex=False, expand=True)\n- 0\n- 0 foojpgbar.jpg\n- \"\"\",\n- }\n- )\n- [USER_REDACTED]_nonstring_types([\"bytes\"])\n- def split(\n- self,\n- pat: str | re.Pattern | None = None,\n- *,\n- n=-1,\n- expand: bool = False,\n- regex: bool | None = None,\n- ):\n+ Use of `regex =False` with a `pat` as a compiled regex will raise an error.\n+\n+ Examples\n+ --------\n+ >>> s = pd.Series(\n+ ... [\n+ ... \"this is a regular sentence\",\n+ ... \"https://docs.python.org/3/tutorial/index.html\",\n+ ... np.nan,\n+ ... ]\n+ ... )\n+ >>> s\n+ 0 this is a regular sentence\n+ 1 https://docs.python.org/3/tutorial/index.html\n+ 2 NaN\n+ dtype: str\n+\n+ In the default setting, the string is split by whitespace.\n+\n+ >>> s.str.split()\n+ 0 [this, is, a, regular, sentence]\n+ 1 [https://docs.python.org/3/tutorial/index.html]\n+ 2 NaN\n+ dtype: object\n+\n+ Without the `n` parameter, the outputs of `rsplit` and `split`\n+ are identical.\n+\n+ >>> s.str.rsplit()\n+ 0 [this, is, a, regular, sentence]\n+ 1 [https://docs.python.org/3/tutorial/index.html]\n+ 2 NaN\n+ dtype: object\n+\n+ The `n` parameter can be used to limit the number of splits on the\n+ delimiter. The outputs of `split` and `rsplit` are different.\n+\n+ >>> s.str.split(n=2)\n+ 0 [this, is, a regular sentence]\n+ 1 [https://docs.python.org/3/tutorial/index.html]\n+ 2 NaN\n+ dtype: object\n+\n+ >>> s.str.rsplit(n=2)\n+ 0 [this is a, regular, sentence]\n+ 1 [https://docs.python.org/3/tutorial/index.html]\n+ 2 NaN\n+ dtype: object\n+\n+ The `pat` parameter can be used to split by [NAME_REDACTED]\n+\n+ >>> s.str.split(pat=\"/\")\n+ 0 [this is a regular sentence]\n+ 1 [https:, , docs.python.org, 3, tutorial, index...\n+ 2 NaN\n+ dtype: object\n+\n+ When using ``expand=True``, the split elements will expand out into\n+ separate columns. If NaN is present, it is propagated throughout\n+ the columns during the split.\n+\n+ >>> s.str.split(expand=True)\n+ 0 1 2 3 4\n+ 0 this is a regular sentence\n+ 1 https://docs.python.org/3/tutorial/index.html [NAME_REDACTED] NaN\n+ 2 [NAME_REDACTED] [NAME_REDACTED]\n+\n+ For slightly more complex use cases like splitting the html document name\n+ from a url, a combination of parameter settings can be used.\n+\n+ >>> s.str.rsplit(\"/\", n=1, expand=True)\n+ 0 1\n+ 0 this is a regular sentence NaN\n+ 1 https://docs.python.org/3/tutorial index.html\n+ 2 [NAME_REDACTED]\n+\n+ Remember to escape special characters when explicitly using regular expressions.\n+\n+ >>> s = pd.Series([\"foo and bar plus baz\"])\n+ >>> s.str.split(r\"and|plus\", expand=True)\n+ 0 1 2\n+ 0 foo bar baz\n+\n+ Regular expressions can be used to handle urls or file names.\n+ When `pat` is a string and ``regex=None`` (the default), the given `pat` is\n+ compiled as a regex only if ``len(pat) != 1``.\n+\n+ >>> s = pd.Series([\"foojpgbar.jpg\"])\n+ >>> s.str.split(r\".\", expand=True)\n+ 0 1\n+ 0 foojpgbar jpg\n+\n+ >>> s.str.split(r\"\\.jpg\", expand=True)\n+ 0 1\n+ 0 foojpgbar\n+\n+ When ``regex=True``, `pat` is interpreted as a regex\n+\n+ >>> s.str.split(r\"\\.jpg\", regex=True, expand=True)\n+ 0 1\n+ 0 foojpgbar\n+\n+ A compiled regex can be passed as `pat`\n+\n+ >>> import re\n+ >>> s.str.split(re.compile(r\"\\.jpg\"), expand=True)\n+ 0 1\n+ 0 foojpgbar\n+\n+ When ``regex=False``, `pat` is interpreted as the string itself\n+\n+ >>> s.str.split(r\"\\.jpg\", regex=False, expand=True)\n+ 0\n+ 0 foojpgbar.jpg\n+ \"\"\"\n if regex is False and is_re(pat):\n raise ValueError(\n \"Cannot use a compiled regex as replacement pattern with regex=False\"\n@@ -915,108 +898,134 @@ def split(\n result, expand=expand, returns_string=expand, dtype=dtype\n )\n \n- [USER_REDACTED](\n- _shared_docs[\"str_split\"]\n- % {\n- \"side\": \"end\",\n- \"pat_regex\": \"\",\n- \"pat_description\": \"String to split on\",\n- \"regex_argument\": \"\",\n- \"raises_split\": \"\",\n- \"regex_pat_note\": \"\",\n- \"method\": \"rsplit\",\n- \"regex_examples\": \"\",\n- }\n- )\n [USER_REDACTED]_nonstring_types([\"bytes\"])\n def rsplit(self, pat=None, *, n=-1, expand: bool = False):\n- result = self._data.array._str_rsplit(pat, n=n)\n- dtype = object if self._data.dtype == object else None\n- return self._wrap_result(\n- result, expand=expand, returns_string=expand, dtype=dtype\n- )\n+ \"\"\"\n+ Split strings around given separator/delimiter.\n \n- _shared_docs[\"str_partition\"] = \"\"\"\n- Split the string at the %(side)s occurrence of `sep`.\n+ Splits the string in the Series/Index from the end,\n+ at the specified delimiter string.\n \n- This method splits the string at the %(side)s occurrence of `sep`,\n- and returns 3 elements containing the part before the separator,\n- the separator itself, and the part after the separator.\n- If the separator is not found, return %(return)s.\n+ Parameters\n+ ----------\n+ pat : str, optional\n+ String to split on.\n+ If not specified, split on whitespace.\n+ n : int, default -1 (all)\n+ Limit number of splits in output.\n+ ``None``, 0 and -1 will be interpreted as return all splits.\n+ expand : bool, default False\n+ Expand the split strings into separate columns.\n \n- Parameters\n- ----------\n- sep : str, default whitespace\n- String to split on.\n- expand : bool, default True\n- If True, return DataFrame/MultiIndex expanding dimensionality.\n- If False, return Series/Index.\n+ - If ``True``, return DataFrame/MultiIndex expanding dimensionality.\n+ - If ``False``, return Series/Index, containing lists of strings.\n \n- Returns\n- -------\n- DataFrame/MultiIndex or Series/Index of objects\n- Returns appropriate type based on `expand` parameter with strings\n- split based on the `sep` parameter.\n+ Returns\n+ -------\n+ Series, Index, DataFrame or MultiIndex\n+ Type matches caller unless ``expand=True`` (see Notes).\n \n- [NAME_REDACTED]\n- --------\n- %(also)s\n- Series.str.split : Split strings around given separators.\n- str.partition : Standard library version.\n+ See Also\n+ --------\n+ Series.str.split : Split strings around given separator/delimiter.\n+ Series.str.rsplit : Splits string around given separator/delimiter,\n+ starting from the right.\n+ Series.str.join : Join lists contained as elements in the Series/Index\n+ with passed delimiter.\n+ str.split : Standard library version for split.\n+ str.rsplit : Standard library version for rsplit.\n \n- Examples\n- --------\n+ Notes\n+ -----\n+ The handling of the `n` keyword depends on the number of found splits:\n \n- >>> s = pd.Series(['Linda van der Berg', '[NAME_REDACTED]'])\n- >>> s\n- 0 Linda van der Berg\n- 1 [NAME_REDACTED]\n- dtype: str\n+ - If found splits > `n`, make first `n` splits only\n+ - If found splits <= `n`, make all splits\n+ - If for a certain row the number of found splits < `n`,\n+ append `None` for padding up to `n` if ``expand=True``\n+\n+ If using ``expand=True``, Series and Index callers return DataFrame and\n+ MultiIndex objects, respectively.\n \n- >>> s.str.partition()\n- 0 1 2\n- 0 Linda van der Berg\n- 1 [NAME_REDACTED]\n+ Examples\n+ --------\n+ >>> s = pd.Series(\n+ ... [\n+ ... \"this is a regular sentence\",\n+ ... \"https://docs.python.org/3/tutorial/index.html\",\n+ ... np.nan,\n+ ... ]\n+ ... )\n+ >>> s\n+ 0 this is a regular sentence\n+ 1 https://docs.python.org/3/tutorial/index.html\n+ 2 NaN\n+ dtype: str\n+\n+ In the default setting, the string is split by whitespace.\n \n- To partition by [NAME_REDACTED] of the first one:\n+ >>> s.str.split()\n+ 0 [this, is, a, regular, sentence]\n+ 1 [https://docs.python.org/3/tutorial/index.html]\n+ 2 NaN\n+ dtype: object\n \n- >>> s.str.rpartition()\n- 0 1 2\n- 0 Linda van der Berg\n- 1 [NAME_REDACTED]\n+ Without the `n` parameter, the outputs of `rsplit` and `split`\n+ are identical.\n \n- To partition by [NAME_REDACTED] a space:\n+ >>> s.str.rsplit()\n+ 0 [this, is, a, regular, sentence]\n+ 1 [https://docs.python.org/3/tutorial/index.html]\n+ 2 NaN\n+ dtype: object\n \n- >>> s.str.partition('-')\n- 0 1 2\n- 0 Linda van der Berg\n- 1 [NAME_REDACTED] - Rivers\n+ The `n` parameter can be used to limit the number of splits on the\n+ delimiter. The outputs of `split` and `rsplit` are different.\n \n- To return a Series containing tuples instead of a DataFrame:\n+ >>> s.str.split(n=2)\n+ 0 [this, is, a regular sentence]\n+ 1 [https://docs.python.org/3/tutorial/index.html]\n+ 2 NaN\n+ dtype: object\n \n- >>> s.str.partition('-', expand=False)\n- 0 (Linda van der Berg, , )\n- 1 ([NAME_REDACTED], -, Rivers)\n- dtype: object\n+ >>> s.str.rsplit(n=2)\n+ 0 [this is a, regular, sentence]\n+ 1 [https://docs.python.org/3/tutorial/index.html]\n+ 2 NaN\n+ dtype: object\n \n- Also available on indices:\n+ The `pat` parameter can be used to split by [NAME_REDACTED]\n \n- >>> idx = pd.Index(['X 123', 'Y 999'])\n- >>> idx\n- Index(['X 123', 'Y 999'], dtype='str')\n+ >>> s.str.split(pat=\"/\")\n+ 0 [this is a regular sentence]\n+ 1 [https:, , docs.python.org, 3, tutorial, index...\n+ 2 NaN\n+ dtype: object\n \n- Which will create a MultiIndex:\n+ When using ``expand=True``, the split elements will expand out into\n+ separate columns. If NaN is present, it is propagated throughout\n+ the columns during the split.\n \n- >>> idx.str.partition()\n- MultiIndex([('X', ' ', '123'),\n- ('Y', ' ', '999')],\n- )\n+ >>> s.str.split(expand=True)\n+ 0 1 2 3 4\n+ 0 this is a regular sentence\n+ 1 https://docs.python.org/3/tutorial/index.html [NAME_REDACTED] NaN\n+ 2 [NAME_REDACTED] [NAME_REDACTED]\n \n- Or an index with tuples with ``expand=False``:\n+ For slightly more complex use cases like splitting the html document name\n+ from a url, a combination of parameter settings can be used.\n \n- >>> idx.str.partition(expand=False)\n- Index([('X', ' ', '123'), ('Y', ' ', '999')], dtype='object')\n- \"\"\"\n+ >>> s.str.rsplit(\"/\", n=1, expand=True)\n+ 0 1\n+ 0 this is a regular sentence NaN\n+ 1 https://docs.python.org/3/tutorial index.html\n+ 2 [NAME_REDACTED]\n+ \"\"\"\n+ result = self._data.array._str_rsplit(pat, n=n)\n+ dtype = object if self._data.dtype == object else None\n+ return self._wrap_result(\n+ result, expand=expand, returns_string=expand, dtype=dtype\n+ )\n \n [USER_REDACTED]_nonstring_types([\"bytes\"])\n def partition(self, sep: str = \" \", expand: bool = True):\n@@ -2455,171 +2464,341 @@ def encode(self, encoding, errors: str = \"strict\"):\n result = self._data.array._str_encode(encoding, errors)\n return self._wrap_result(result, returns_string=False)\n \n- _shared_docs[\"str_strip\"] = r\"\"\"\n- Remove %(position)s characters.\n-\n- Strip whitespaces (including newlines) or a set of specified characters\n- from each string in the Series/Index from %(side)s.\n- Replaces any non-strings in Series with NaNs.\n- Equivalent to :meth:`str.%(method)s`.\n+ [USER_REDACTED]_nonstring_types([\"bytes\"])\n+ def strip(self, to_strip=None):\n+ \"\"\"\n+ Remove leading and trailing characters.\n \n- Parameters\n- ----------\n- to_strip : str or None, default None\n- Specifying the set of characters to be removed.\n- All combinations of this set of characters will be stripped.\n- If None then whitespaces are removed.\n+ Strip whitespaces (including newlines) or a set of specified characters\n+ from each string in the Series/Index from left and right sides.\n+ Replaces any non-strings in Series with NaNs.\n+ Equivalent to :meth:`str.strip`.\n \n- Returns\n- -------\n- Series or Index of object\n- Series or Index with the strings being stripped from the %(side)s.\n+ Parameters\n+ ----------\n+ to_strip : str or None, default None\n+ Specifying the set of characters to be removed.\n+ All combinations of this set of characters will be stripped.\n+ If None then whitespaces are removed.\n \n- [NAME_REDACTED]\n- --------\n- Series.str.strip : Remove leading and trailing characters in Series/Index.\n- Series.str.lstrip : Remove leading characters in Series/Index.\n- Series.str.rstrip : Remove trailing characters in Series/Index.\n+ Returns\n+ -------\n+ Series or Index of object\n+ Series or Index with the strings being stripped from the left and\n+ right sides.\n \n- Examples\n- --------\n- >>> s = pd.Series(['1. Ant. ', '2. Bee!\\n', '3. Cat?\\t', np.nan, 10, True])\n- >>> s\n- 0 1. Ant.\n- 1 2. Bee!\\n\n- 2 3. Cat?\\t\n- 3 NaN\n- 4 10\n- 5 True\n- dtype: object\n+ See Also\n+ --------\n+ Series.str.strip : Remove leading and trailing characters in Series/Index.\n+ Series.str.lstrip : Remove leading characters in Series/Index.\n+ Series.str.rstrip : Remove trailing characters in Series/Index.\n \n- >>> s.str.strip()\n- 0 1. Ant.\n- 1 2. Bee!\n- 2 3. Cat?\n- 3 NaN\n- 4 NaN\n- 5 NaN\n- dtype: object\n+ Examples\n+ --------\n+ >>> s = pd.Series([\"1. Ant. \", \"2. Bee!\\\\n\", \"3. Cat?\\\\t\", np.nan, 10, True])\n+ >>> s\n+ 0 1. Ant.\n+ 1 2. Bee!\\\\n\n+ 2 3. Cat?\\\\t\n+ 3 NaN\n+ 4 10\n+ 5 True\n+ dtype: object\n \n- >>> s.str.lstrip('123.')\n- 0 Ant.\n- 1 Bee!\\n\n- 2 Cat?\\t\n- 3 NaN\n- 4 NaN\n- 5 NaN\n- dtype: object\n+ >>> s.str.strip()\n+ 0 1. Ant.\n+ 1 2. Bee!\n+ 2 3. Cat?\n+ 3 NaN\n+ 4 NaN\n+ 5 NaN\n+ dtype: object\n \n- >>> s.str.rstrip('.!? \\n\\t')\n- 0 1. Ant\n- 1 2. Bee\n- 2 3. Cat\n- 3 NaN\n- 4 NaN\n- 5 NaN\n- dtype: object\n+ >>> s.str.lstrip(\"123.\")\n+ 0 Ant.\n+ 1 Bee!\\\\n\n+ 2 Cat?\\\\t\n+ 3 NaN\n+ 4 NaN\n+ 5 NaN\n+ dtype: object\n \n- >>> s.str.strip('123.!? \\n\\t')\n- 0 Ant\n- 1 Bee\n- 2 Cat\n- 3 NaN\n- 4 NaN\n- 5 NaN\n- dtype: object\n- \"\"\"\n+ >>> s.str.rstrip(\".!? \\\\n\\\\t\")\n+ 0 1. Ant\n+ 1 2. Bee\n+ 2 3. Cat\n+ 3 NaN\n+ 4 NaN\n+ 5 NaN\n+ dtype: object\n \n- [USER_REDACTED](\n- _shared_docs[\"str_strip\"]\n- % {\n- \"side\": \"left and right sides\",\n- \"method\": \"strip\",\n- \"position\": \"leading and trailing\",\n- }\n- )\n- [USER_REDACTED]_nonstring_types([\"bytes\"])\n- def strip(self, to_strip=None):\n+ >>> s.str.strip(\"123.!? \\\\n\\\\t\")\n+ 0 Ant\n+ 1 Bee\n+ 2 Cat\n+ 3 NaN\n+ 4 NaN\n+ 5 NaN\n+ dtype: object\n+ \"\"\"\n result = self._data.array._str_strip(to_strip)\n return self._wrap_result(result)\n \n- [USER_REDACTED](\n- _shared_docs[\"str_strip\"]\n- % {\"side\": \"left side\", \"method\": \"lstrip\", \"position\": \"leading\"}\n- )\n [USER_REDACTED]_nonstring_types([\"bytes\"])\n def lstrip(self, to_strip=None):\n+ \"\"\"\n+ Remove leading characters.\n+\n+ Strip whitespaces (including newlines) or a set of specified characters\n+ from each string in the Series/Index from left side.\n+ Replaces any non-strings in Series with NaNs.\n+ Equivalent to :meth:`str.lstrip`.\n+\n+ Parameters\n+ ----------\n+ to_strip : str or None, default None\n+ Specifying the set of characters to be removed.\n+ All combinations of this set of characters will be stripped.\n+ If None then whitespaces are removed.\n+\n+ Returns\n+ -------\n+ Series or Index of object\n+ Series or Index with the strings being stripped from the left side.\n+\n+ See Also\n+ --------\n+ Series.str.strip : Remove leading and trailing characters in Series/Index.\n+ Series.str.lstrip : Remove leading characters in Series/Index.\n+ Series.str.rstrip : Remove trailing characters in Series/Index.\n+\n+ Examples\n+ --------\n+ >>> s = pd.Series([\"1. Ant. \", \"2. Bee!\\\\n\", \"3. Cat?\\\\t\", np.nan, 10, True])\n+ >>> s\n+ 0 1. Ant.\n+ 1 2. Bee!\\\\n\n+ 2 3. Cat?\\\\t\n+ 3 NaN\n+ 4 10\n+ 5 True\n+ dtype: object\n+\n+ >>> s.str.strip()\n+ 0 1. Ant.\n+ 1 2. Bee!\n+ 2 3. Cat?\n+ 3 NaN\n+ 4 NaN\n+ 5 NaN\n+ dtype: object\n+\n+ >>> s.str.lstrip(\"123.\")\n+ 0 Ant.\n+ 1 Bee!\\\\n\n+ 2 Cat?\\\\t\n+ 3 NaN\n+ 4 NaN\n+ 5 NaN\n+ dtype: object\n+\n+ >>> s.str.rstrip(\".!? \\\\n\\\\t\")\n+ 0 1. Ant\n+ 1 2. Bee\n+ 2 3. Cat\n+ 3 NaN\n+ 4 NaN\n+ 5 NaN\n+ dtype: object\n+\n+ >>> s.str.strip(\"123.!? \\\\n\\\\t\")\n+ 0 Ant\n+ 1 Bee\n+ 2 Cat\n+ 3 NaN\n+ 4 NaN\n+ 5 NaN\n+ dtype: object\n+ \"\"\"\n result = self._data.array._str_lstrip(to_strip)\n return self._wrap_result(result)\n \n- [USER_REDACTED](\n- _shared_docs[\"str_strip\"]\n- % {\"side\": \"right side\", \"method\": \"rstrip\", \"position\": \"trailing\"}\n- )\n [USER_REDACTED]_nonstring_types([\"bytes\"])\n def rstrip(self, to_strip=None):\n- result = self._data.array._str_rstrip(to_strip)\n- return self._wrap_result(result)\n+ \"\"\"\n+ Remove trailing characters.\n \n- _shared_docs[\"str_removefix\"] = r\"\"\"\n- Remove a %(side)s from an object series.\n+ Strip whitespaces (including newlines) or a set of specified characters\n+ from each string in the Series/Index from right side.\n+ Replaces any non-strings in Series with NaNs.\n+ Equivalent to :meth:`str.rstrip`.\n \n- If the %(side)s is not present, the original string will be returned.\n+ Parameters\n+ ----------\n+ to_strip : str or None, default None\n+ Specifying the set of characters to be removed.\n+ All combinations of this set of characters will be stripped.\n+ If None then whitespaces are removed.\n \n- Parameters\n- ----------\n- %(side)s : str\n- Remove the %(side)s of the string.\n+ Returns\n+ -------\n+ Series or Index of object\n+ Series or Index with the strings being stripped from the right side.\n \n- Returns\n- -------\n- Series/Index: object\n- The Series or Index with given %(side)s removed.\n+ See Also\n+ --------\n+ Series.str.strip : Remove leading and trailing characters in Series/Index.\n+ Series.str.lstrip : Remove leading characters in Series/Index.\n+ Series.str.rstrip : Remove trailing characters in Series/Index.\n \n- [NAME_REDACTED]\n- --------\n- Series.str.remove%(other_side)s : Remove a %(other_side)s from an object series.\n+ Examples\n+ --------\n+ >>> s = pd.Series([\"1. Ant. \", \"2. Bee!\\\\n\", \"3. Cat?\\\\t\", np.nan, 10, True])\n+ >>> s\n+ 0 1. Ant.\n+ 1 2. Bee!\\\\n\n+ 2 3. Cat?\\\\t\n+ 3 NaN\n+ 4 10\n+ 5 True\n+ dtype: object\n \n- Examples\n- --------\n- >>> s = pd.Series([\"str_foo\", \"str_bar\", \"no_prefix\"])\n- >>> s\n- 0 str_foo\n- 1 str_bar\n- 2 no_prefix\n- dtype: str\n- >>> s.str.removeprefix(\"str_\")\n- 0 foo\n- 1 bar\n- 2 no_prefix\n- dtype: str\n+ >>> s.str.strip()\n+ 0 1. Ant.\n+ 1 2. Bee!\n+ 2 3. Cat?\n+ 3 NaN\n+ 4 NaN\n+ 5 NaN\n+ dtype: object\n \n- >>> s = pd.Series([\"foo_str\", \"bar_str\", \"no_suffix\"])\n- >>> s\n- 0 foo_str\n- 1 bar_str\n- 2 no_suffix\n- dtype: str\n- >>> s.str.removesuffix(\"_str\")\n- 0 foo\n- 1 bar\n- 2 no_suffix\n- dtype: str\n- \"\"\"\n+ >>> s.str.lstrip(\"123.\")\n+ 0 Ant.\n+ 1 Bee!\\\\n\n+ 2 Cat?\\\\t\n+ 3 NaN\n+ 4 NaN\n+ 5 NaN\n+ dtype: object\n+\n+ >>> s.str.rstrip(\".!? \\\\n\\\\t\")\n+ 0 1. Ant\n+ 1 2. Bee\n+ 2 3. Cat\n+ 3 NaN\n+ 4 NaN\n+ 5 NaN\n+ dtype: object\n+\n+ >>> s.str.strip(\"123.!? \\\\n\\\\t\")\n+ 0 Ant\n+ 1 Bee\n+ 2 Cat\n+ 3 NaN\n+ 4 NaN\n+ 5 NaN\n+ dtype: object\n+ \"\"\"\n+ result = self._data.array._str_rstrip(to_strip)\n+ return self._wrap_result(result)\n \n- [USER_REDACTED](\n- _shared_docs[\"str_removefix\"] % {\"side\": \"prefix\", \"other_side\": \"suffix\"}\n- )\n [USER_REDACTED]_nonstring_types([\"bytes\"])\n def removeprefix(self, prefix: str):\n+ \"\"\"\n+ Remove a prefix from an object series.\n+\n+ If the prefix is not present, the original string will be returned.\n+\n+ Parameters\n+ ----------\n+ prefix : str\n+ Remove the prefix of the string.\n+\n+ Returns\n+ -------\n+ Series/Index: object\n+ The Series or Index with given prefix removed.\n+\n+ See Also\n+ --------\n+ Series.str.removesuffix : Remove a suffix from an object series.\n+\n+ Examples\n+ --------\n+ >>> s = pd.Series([\"str_foo\", \"str_bar\", \"no_prefix\"])\n+ >>> s\n+ 0 str_foo\n+ 1 str_bar\n+ 2 no_prefix\n+ dtype: str\n+ >>> s.str.removeprefix(\"str_\")\n+ 0 foo\n+ 1 bar\n+ 2 no_prefix\n+ dtype: str\n+\n+ >>> s = pd.Series([\"foo_str\", \"bar_str\", \"no_suffix\"])\n+ >>> s\n+ 0 foo_str\n+ 1 bar_str\n+ 2 no_suffix\n+ dtype: str\n+ >>> s.str.removesuffix(\"_str\")\n+ 0 foo\n+ 1 bar\n+ 2 no_suffix\n+ dtype: str\n+ \"\"\"\n result = self._data.array._str_removeprefix(prefix)\n return self._wrap_result(result)\n \n- [USER_REDACTED](\n- _shared_docs[\"str_removefix\"] % {\"side\": \"suffix\", \"other_side\": \"prefix\"}\n- )\n [USER_REDACTED]_nonstring_types([\"bytes\"])\n def removesuffix(self, suffix: str):\n+ \"\"\"\n+ Remove a suffix from an object series.\n+\n+ If the suffix is not present, the original string will be returned.\n+\n+ Parameters\n+ ----------\n+ suffix : str\n+ Remove the suffix of the string.\n+\n+ Returns\n+ -------\n+ Series/Index: object\n+ The Series or Index with given suffix removed.\n+\n+ See Also\n+ --------\n+ Series.str.removeprefix : Remove a prefix from an object series.\n+\n+ Examples\n+ --------\n+ >>> s = pd.Series([\"str_foo\", \"str_bar\", \"no_prefix\"])\n+ >>> s\n+ 0 str_foo\n+ 1 str_bar\n+ 2 no_prefix\n+ dtype: str\n+ >>> s.str.removeprefix(\"str_\")\n+ 0 foo\n+ 1 bar\n+ 2 no_prefix\n+ dtype: str\n+\n+ >>> s = pd.Series([\"foo_str\", \"bar_str\", \"no_suffix\"])\n+ >>> s\n+ 0 foo_str\n+ 1 bar_str\n+ 2 no_suffix\n+ dtype: str\n+ >>> s.str.removesuffix(\"_str\")\n+ 0 foo\n+ 1 bar\n+ 2 no_suffix\n+ dtype: str\n+ \"\"\"\n result = self._data.array._str_removesuffix(suffix)\n return self._wrap_result(result)\n \n@@ -3350,81 +3529,111 @@ def extractall(self, pat, flags: int = 0) -> DataFrame:\n # TODO: dispatch\n return str_extractall(self._orig, pat, flags)\n \n- _shared_docs[\"find\"] = \"\"\"\n- Return %(side)s indexes in each strings in the Series/Index.\n+ [USER_REDACTED]_nonstring_types([\"bytes\"])\n+ def find(self, sub, start: int = 0, end=None):\n+ \"\"\"\n+ Return lowest indexes in each strings in the Series/Index.\n \n- Each of returned indexes corresponds to the position where the\n- substring is fully contained between [start:end]. Return -1 on\n- failure. Equivalent to standard :meth:`str.%(method)s`.\n+ Each of returned indexes corresponds to the position where the\n+ substring is fully contained between [start:end]. Return -1 on\n+ failure. Equivalent to standard :meth:`str.find`.\n \n- Parameters\n- ----------\n- sub : str\n- Substring being searched.\n- start : int\n- Left edge index.\n- end : int\n- Right edge index.\n+ Parameters\n+ ----------\n+ sub : str\n+ Substring being searched.\n+ start : int\n+ Left edge index.\n+ end : int\n+ Right edge index.\n \n- Returns\n- -------\n- Series or Index of int.\n- A Series (if the input is a Series) or an Index (if the input is an\n- Index) of the %(side)s indexes corresponding to the positions where the\n- substring is found in each string of the input.\n+ Returns\n+ -------\n+ Series or Index of int.\n+ A Series (if the input is a Series) or an Index (if the input is an\n+ Index) of the lowest indexes corresponding to the positions where the\n+ substring is found in each string of the input.\n \n- [NAME_REDACTED]\n- --------\n- %(also)s\n+ See Also\n+ --------\n+ rfind : Return highest indexes in each strings.\n \n- Examples\n- --------\n- For Series.str.find:\n-\n- >>> ser = pd.Series([\"_cow_\", \"duck_\", \"do_v_e\"])\n- >>> ser.str.find(\"_\")\n- 0 0\n- 1 4\n- 2 2\n- dtype: int64\n-\n- For Series.str.rfind:\n-\n- >>> ser = pd.Series([\"_cow_\", \"duck_\", \"do_v_e\"])\n- >>> ser.str.rfind(\"_\")\n- 0 4\n- 1 4\n- 2 4\n- dtype: int64\n- \"\"\"\n+ Examples\n+ --------\n+ For Series.str.find:\n \n- [USER_REDACTED](\n- _shared_docs[\"find\"]\n- % {\n- \"side\": \"lowest\",\n- \"method\": \"find\",\n- \"also\": \"rfind : Return highest indexes in each strings.\",\n- }\n- )\n- [USER_REDACTED]_nonstring_types([\"bytes\"])\n- def find(self, sub, start: int = 0, end=None):\n+ >>> ser = pd.Series([\"_cow_\", \"duck_\", \"do_v_e\"])\n+ >>> ser.str.find(\"_\")\n+ 0 0\n+ 1 4\n+ 2 2\n+ dtype: int64\n+\n+ For Series.str.rfind:\n+\n+ >>> ser = pd.Series([\"_cow_\", \"duck_\", \"do_v_e\"])\n+ >>> ser.str.rfind(\"_\")\n+ 0 4\n+ 1 4\n+ 2 4\n+ dtype: int64\n+ \"\"\"\n if not isinstance(sub, str):\n msg = f\"expected a string object, not {type(sub).__name__}\"\n raise TypeError(msg)\n \n result = self._data.array._str_find(sub, start, end)\n return self._wrap_result(result, returns_string=False)\n \n- [USER_REDACTED](\n- _shared_docs[\"find\"]\n- % {\n- \"side\": \"highest\",\n- \"method\": \"rfind\",\n- \"also\": \"find : Return lowest indexes in each strings.\",\n- }\n- )\n [USER_REDACTED]_nonstring_types([\"bytes\"])\n def rfind(self, sub, start: int = 0, end=None):\n+ \"\"\"\n+ Return highest indexes in each strings in the Series/Index.\n+\n+ Each of returned indexes corresponds to the position where the\n+ substring is fully contained between [start:end]. Return -1 on\n+ failure. Equivalent to standard :meth:`str.rfind`.\n+\n+ Parameters\n+ ----------\n+ sub : str\n+ Substring being searched.\n+ start : int\n+ Left edge index.\n+ end : int\n+ Right edge index.\n+\n+ Returns\n+ -------\n+ Series or Index of int.\n+ A Series (if the input is a Series) or an Index (if the input is an\n+ Index) of the highest indexes corresponding to the positions where the\n+ substring is found in each string of the input.\n+\n+ See Also\n+ --------\n+ find : Return lowest indexes in each strings.\n+\n+ Examples\n+ --------\n+ For Series.str.find:\n+\n+ >>> ser = pd.Series([\"_cow_\", \"duck_\", \"do_v_e\"])\n+ >>> ser.str.find(\"_\")\n+ 0 0\n+ 1 4\n+ 2 2\n+ dtype: int64\n+\n+ For Series.str.rfind:\n+\n+ >>> ser = pd.Series([\"_cow_\", \"duck_\", \"do_v_e\"])\n+ >>> ser.str.rfind(\"_\")\n+ 0 4\n+ 1 4\n+ 2 4\n+ dtype: int64\n+ \"\"\"\n if not isinstance(sub, str):\n msg = f\"expected a string object, not {type(sub).__name__}\"\n raise TypeError(msg)\n@@ -3472,84 +3681,113 @@ def normalize(self, form):\n result = self._data.array._str_normalize(form)\n return self._wrap_result(result)\n \n- _shared_docs[\"index\"] = \"\"\"\n- Return %(side)s indexes in each string in Series/Index.\n+ [USER_REDACTED]_nonstring_types([\"bytes\"])\n+ def index(self, sub, start: int = 0, end=None):\n+ \"\"\"\n+ Return lowest indexes in each string in Series/Index.\n+\n+ Each of the returned indexes corresponds to the position where the\n+ substring is fully contained between [start:end]. This is the same\n+ as ``str.find`` except instead of returning -1, it raises a\n+ ValueError when the substring is not found. Equivalent to standard\n+ ``str.index``.\n \n- Each of the returned indexes corresponds to the position where the\n- substring is fully contained between [start:end]. This is the same\n- as ``str.%(similar)s`` except instead of returning -1, it raises a\n- ValueError when the substring is not found. Equivalent to standard\n- ``str.%(method)s``.\n+ Parameters\n+ ----------\n+ sub : str\n+ Substring being searched.\n+ start : int\n+ Left edge index.\n+ end : int\n+ Right edge index.\n \n- Parameters\n- ----------\n- sub : str\n- Substring being searched.\n- start : int\n- Left edge index.\n- end : int\n- Right edge index.\n+ Returns\n+ -------\n+ Series or Index of object\n+ Returns a Series or an Index of the lowest indexes\n+ in each string of the input.\n \n- Returns\n- -------\n- Series or Index of object\n- Returns a Series or an Index of the %(side)s indexes\n- in each string of the input.\n+ See Also\n+ --------\n+ rindex : Return highest indexes in each strings.\n \n- [NAME_REDACTED]\n- --------\n- %(also)s\n+ Examples\n+ --------\n+ For Series.str.index:\n \n- Examples\n- --------\n- For Series.str.index:\n-\n- >>> ser = pd.Series([\"horse\", \"eagle\", \"donkey\"])\n- >>> ser.str.index(\"e\")\n- 0 4\n- 1 0\n- 2 4\n- dtype: int64\n-\n- For Series.str.rindex:\n-\n- >>> ser = pd.Series([\"Deer\", \"eagle\", \"Sheep\"])\n- >>> ser.str.rindex(\"e\")\n- 0 2\n- 1 4\n- 2 3\n- dtype: int64\n- \"\"\"\n+ >>> ser = pd.Series([\"horse\", \"eagle\", \"donkey\"])\n+ >>> ser.str.index(\"e\")\n+ 0 4\n+ 1 0\n+ 2 4\n+ dtype: int64\n \n- [USER_REDACTED](\n- _shared_docs[\"index\"]\n- % {\n- \"side\": \"lowest\",\n- \"similar\": \"find\",\n- \"method\": \"index\",\n- \"also\": \"rindex : Return highest indexes in each strings.\",\n- }\n- )\n- [USER_REDACTED]_nonstring_types([\"bytes\"])\n- def index(self, sub, start: int = 0, end=None):\n+ For Series.str.rindex:\n+\n+ >>> ser = pd.Series([\"Deer\", \"eagle\", \"Sheep\"])\n+ >>> ser.str.rindex(\"e\")\n+ 0 2\n+ 1 4\n+ 2 3\n+ dtype: int64\n+ \"\"\"\n if not isinstance(sub, str):\n msg = f\"expected a string object, not {type(sub).__name__}\"\n raise TypeError(msg)\n \n result = self._data.array._str_index(sub, start=start, end=end)\n return self._wrap_result(result, returns_string=False)\n \n- [USER_REDACTED](\n- _shared_docs[\"index\"]\n- % {\n- \"side\": \"highest\",\n- \"similar\": \"rfind\",\n- \"method\": \"rindex\",\n- \"also\": \"index : Return lowest indexes in each strings.\",\n- }\n- )\n [USER_REDACTED]_nonstring_types([\"bytes\"])\n def rindex(self, sub, start: int = 0, end=None):\n+ \"\"\"\n+ Return highest indexes in each string in Series/Index.\n+\n+ Each of the returned indexes corresponds to the position where the\n+ substring is fully contained between [start:end]. This is the same\n+ as ``str.rfind`` except instead of returning -1, it raises a\n+ ValueError when the substring is not found. Equivalent to standard\n+ ``str.rindex``.\n+\n+ Parameters\n+ ----------\n+ sub : str\n+ Substring being searched.\n+ start : int\n+ Left edge index.\n+ end : int\n+ Right edge index.\n+\n+ Returns\n+ -------\n+ Series or Index of object\n+ Returns a Series or an Index of the highest indexes\n+ in each string of the input.\n+\n+ See Also\n+ --------\n+ index : Return lowest indexes in each strings.\n+\n+ Examples\n+ --------\n+ For Series.str.index:\n+\n+ >>> ser = pd.Series([\"horse\", \"eagle\", \"donkey\"])\n+ >>> ser.str.index(\"e\")\n+ 0 4\n+ 1 0\n+ 2 4\n+ dtype: int64\n+\n+ For Series.str.rindex:\n+\n+ >>> ser = pd.Series([\"Deer\", \"eagle\", \"Sheep\"])\n+ >>> ser.str.rindex(\"e\")\n+ 0 2\n+ 1 4\n+ 2 3\n+ dtype: int64\n+ \"\"\"\n if not isinstance(sub, str):\n msg = f\"expected a string object, not {type(sub).__name__}\"\n raise TypeError(msg)" } ], "reviews": [ { "id": 3657020192, "user": "user_c9260bc45a59", "state": "COMMENTED", "body": null, "submitted_at": "2026-01-13T17:30:16+00:00" }, { "id": 3662058593, "user": "user_c9260bc45a59", "state": "APPROVED", "body": null, "submitted_at": "2026-01-14T17:58:22+00:00" } ], "review_comments": [ { "id": 2687402541, "user": "user_c9260bc45a59", "body": "Could you remove this `.. versionadded`? Generally we want to remove these that reference a version less than 2.0", "path": "pandas/core/strings/accessor.py", "line": null, "side": "RIGHT", "created_at": "2026-01-13T17:30:16+00:00" } ], "meta": { "languages": [ "py" ], "touches_tests": false, "review_state_summary": { "COMMENTED": 1, "APPROVED": 1 }, "meaningful_comment_count": 1, "has_approval": true, "has_changes_requested": false, "total_review_comments": 1 } } { "_id": "f411347a2daa16e9", "_schema_version": "1.0", "_cleaned_at": "2026-02-12T07:46:51.876262+00:00", "repo": "pandas-dev/pandas", "repo_url": "https://github.com/pandas-dev/pandas", "license_name": "BSD 3-Clause \"New\" or \"Revised\" License", "license_spdx": "BSD-3-Clause", "pr_number": 63666, "title": "BUG: fix to_json with non-nano timedelta index + avoid casting to ns for datetime-like", "body": "Closes https://github.com/[USER_REDACTED]ndas-dev/pandas/issues/63236\n\nChanges in the PR:\n\n- Support passing the unit if the int value in the C `int64ToIsoDuration` helper for timedelta conversion, similarly as is done in `int64ToIso` for datetime conversion\n- in ObjToJSON C code:\n - for conversion to \"iso\", now always pass the value unit as well, for both timedelta and datetime (so in this case, no up front casting to nanoseconds is needed, as the ISO conversion will handle that correctly)\n - for conversion to \"epoch\", convert to the desired unit up front (before going into the C code) in python, such that in the C code we can just use the integer value (and don't have to deal with the explosion of any unit -> any unit conversion in the C code). This adds some additional python code, but since \"epoch\" is deprecated, this can be removed in the future. \n- Added some more code comments while trying to understand what is going on (and renamed a few variables to have clearer names)\n\nBecause the ISO path handles unit conversion itself, and for epoch I added the conversion up front in python, we can AFAIK remove the cast to nanoseconds that was added in https://github.com/[USER_REDACTED]ndas-dev/pandas/pull/63100 (this was also only done for the columns values and not row/column indexes, which caused the bug this issue is closing)", "author": "user_7213a217ace7", "created_at": "2026-01-13T10:02:05+00:00", "merged_at": "2026-01-21T08:17:04+00:00", "base_branch": "main", "head_branch": "non-nano-json", "additions": 136, "deletions": 55, "changed_files": 8, "files": [ { "filename": "pandas/_libs/include/pandas/datetime/date_conversions.h", "status": "modified", "additions": 2, "deletions": 1, "changes": 3, "patch": "@@ -22,4 +22,5 @@ int scaleNanosecToUnit(int64_t *value, NPY_DATETIMEUNIT unit);\n char *int64ToIso(int64_t value, NPY_DATETIMEUNIT valueUnit,\n NPY_DATETIMEUNIT base, size_t *len);\n \n-char *int64ToIsoDuration(int64_t value, size_t *len);\n+char *int64ToIsoDuration(int64_t value, NPY_DATETIMEUNIT valueUnit,\n+ size_t *len);" }, { "filename": "pandas/_libs/include/pandas/datetime/pd_datetime.h", "status": "modified", "additions": 3, "deletions": 3, "changes": 6, "patch": "@@ -37,7 +37,7 @@ typedef struct {\n char *(*int64ToIso)(int64_t, NPY_DATETIMEUNIT, NPY_DATETIMEUNIT, size_t *);\n char *(*PyDateTimeToIso)(PyObject *, NPY_DATETIMEUNIT, size_t *);\n npy_datetime (*PyDateTimeToEpoch)(PyObject *, NPY_DATETIMEUNIT);\n- char *(*int64ToIsoDuration)(int64_t, size_t *);\n+ char *(*int64ToIsoDuration)(int64_t, NPY_DATETIMEUNIT, size_t *);\n void (*pandas_datetime_to_datetimestruct)(npy_datetime, NPY_DATETIMEUNIT,\n npy_datetimestruct *);\n void (*pandas_timedelta_to_timedeltastruct)(npy_datetime, NPY_DATETIMEUNIT,\n@@ -80,8 +80,8 @@ static PandasDateTime_CAPI *PandasDateTimeAPI = NULL;\n PandasDateTimeAPI->PyDateTimeToIso((obj), (base), (len))\n # define PyDateTimeToEpoch(dt, base) \\\n PandasDateTimeAPI->PyDateTimeToEpoch((dt), (base))\n-# define int64ToIsoDuration(value, len) \\\n- PandasDateTimeAPI->int64ToIsoDuration((value), (len))\n+# define int64ToIsoDuration(value, valueUnit, len) \\\n+ PandasDateTimeAPI->int64ToIsoDuration((value), (valueUnit), (len))\n # define pandas_datetime_to_datetimestruct(dt, base, out) \\\n PandasDateTimeAPI->pandas_datetime_to_datetimestruct((dt), (base), (out))\n # define pandas_timedelta_to_timedeltastruct(td, base, out) \\" }, { "filename": "pandas/_libs/src/datetime/date_conversions.c", "status": "modified", "additions": 3, "deletions": 2, "changes": 5, "patch": "@@ -70,11 +70,12 @@ char *int64ToIso(int64_t value, NPY_DATETIMEUNIT valueUnit,\n }\n \n /* Converts the int64_t representation of a duration to ISO; mutates len */\n-char *int64ToIsoDuration(int64_t value, size_t *len) {\n+char *int64ToIsoDuration(int64_t value, NPY_DATETIMEUNIT valueUnit,\n+ size_t *len) {\n pandas_timedeltastruct tds;\n int ret_code;\n \n- pandas_timedelta_to_timedeltastruct(value, NPY_FR_ns, &tds);\n+ pandas_timedelta_to_timedeltastruct(value, valueUnit, &tds);\n \n // Max theoretical length of ISO Duration with 64 bit day\n // as the largest unit is 70 characters + 1 for a null terminator" }, { "filename": "pandas/_libs/src/vendored/ujson/python/objToJSON.c", "status": "modified", "additions": 27, "deletions": 16, "changes": 43, "patch": "@@ -131,8 +131,13 @@ typedef struct __PyObjectEncoder {\n int npyType;\n void *npyValue;\n \n+ // whether to encode datetime as ISO strings (0=epoch int, 1=ISO str)\n int datetimeIso;\n+ // the unit to encode to, governs epoch and ISO8601 precision (default ms)\n NPY_DATETIMEUNIT datetimeUnit;\n+ // pass-through: the unit of the actual integer value being encoded\n+ // (has to be set when calling NpyDateTimeToIsoCallback or\n+ // NpyTimeDeltaToIsoCallback)\n NPY_DATETIMEUNIT valueUnit;\n \n // output format style for pandas data types\n@@ -335,7 +340,8 @@ static const char *NpyDateTimeToIsoCallback(JSOBJ Py_UNUSED(unused),\n /* JSON callback. returns a char* and mutates the pointer to *len */\n static const char *NpyTimeDeltaToIsoCallback(JSOBJ Py_UNUSED(unused),\n JSONTypeContext *tc, size_t *len) {\n- GET_TC(tc)->cStr = int64ToIsoDuration(GET_TC(tc)->longValue, len);\n+ NPY_DATETIMEUNIT valueUnit = ((PyObjectEncoder *)tc->encoder)->valueUnit;\n+ GET_TC(tc)->cStr = int64ToIsoDuration(GET_TC(tc)->longValue, valueUnit, len);\n return GET_TC(tc)->cStr;\n }\n \n@@ -1242,7 +1248,7 @@ static char **NpyArr_encodeLabels(PyArrayObject *labels, PyObjectEncoder *enc,\n npy_intp num) {\n // NOTE this function steals a reference to labels.\n PyObject *item = NULL;\n- const NPY_DATETIMEUNIT base = enc->datetimeUnit;\n+ const NPY_DATETIMEUNIT targetUnit = enc->datetimeUnit;\n \n if (!labels) {\n return 0;\n@@ -1280,13 +1286,16 @@ static char **NpyArr_encodeLabels(PyArrayObject *labels, PyObjectEncoder *enc,\n }\n \n int is_datetimelike = 0;\n+ int from_numpy = 0;\n int64_t i8date;\n- NPY_DATETIMEUNIT dateUnit = NPY_FR_ns;\n+ NPY_DATETIMEUNIT valueUnit = NPY_FR_ns;\n if (PyTypeNum_ISDATETIME(type_num)) {\n is_datetimelike = 1;\n+ from_numpy = 1;\n i8date = *(int64_t *)dataptr;\n- dateUnit = get_datetime_metadata_from_dtype(dtype).base;\n+ valueUnit = get_datetime_metadata_from_dtype(dtype).base;\n } else if (PyDate_Check(item) || PyDelta_Check(item)) {\n+ // convert datetime/timedelta object to nanos\n is_datetimelike = 1;\n if (PyObject_HasAttrString(item, \"_value\")) {\n // pd.Timestamp object or pd.NaT\n@@ -1316,13 +1325,12 @@ static char **NpyArr_encodeLabels(PyArrayObject *labels, PyObjectEncoder *enc,\n } else {\n if (enc->datetimeIso) {\n if ((type_num == NPY_TIMEDELTA) || (PyDelta_Check(item))) {\n- // TODO(username): non-nano timedelta support?\n- cLabel = int64ToIsoDuration(i8date, &len);\n+ cLabel = int64ToIsoDuration(i8date, valueUnit, &len);\n } else {\n if (type_num == NPY_DATETIME) {\n- cLabel = int64ToIso(i8date, dateUnit, base, &len);\n+ cLabel = int64ToIso(i8date, valueUnit, targetUnit, &len);\n } else {\n- cLabel = PyDateTimeToIso(item, base, &len);\n+ cLabel = PyDateTimeToIso(item, targetUnit, &len);\n }\n }\n if (cLabel == NULL) {\n@@ -1334,10 +1342,14 @@ static char **NpyArr_encodeLabels(PyArrayObject *labels, PyObjectEncoder *enc,\n } else {\n int size_of_cLabel = 21; // 21 chars for int 64\n cLabel = PyObject_Malloc(size_of_cLabel);\n- if (scaleNanosecToUnit(&i8date, base) == -1) {\n- NpyArr_freeLabels(ret, num);\n- ret = 0;\n- break;\n+ if (!from_numpy) {\n+ // numpy arrays are already scaled to the correct unit\n+ // only need to scale if coming from a datetime/timedelta object\n+ if (scaleNanosecToUnit(&i8date, targetUnit) == -1) {\n+ NpyArr_freeLabels(ret, num);\n+ ret = 0;\n+ break;\n+ }\n }\n snprintf(cLabel, size_of_cLabel, \"%\" PRId64, i8date);\n len = strlen(cLabel);\n@@ -1440,10 +1452,8 @@ static void Object_beginTypeContext(JSOBJ _obj, JSONTypeContext *tc) {\n pc->longValue = longVal;\n tc->type = JT_UTF8;\n } else {\n- NPY_DATETIMEUNIT base = ((PyObjectEncoder *)tc->encoder)->datetimeUnit;\n- if (scaleNanosecToUnit(&longVal, base) == -1) {\n- goto INVALID;\n- }\n+ // numpy array was already scaled to unit, so just use int value for\n+ // epoch\n pc->longValue = longVal;\n tc->type = JT_LONG;\n }\n@@ -1567,6 +1577,7 @@ static void Object_beginTypeContext(JSOBJ _obj, JSONTypeContext *tc) {\n return;\n } else if (enc->datetimeIso) {\n pc->PyTypeToUTF8 = NpyTimeDeltaToIsoCallback;\n+ enc->valueUnit = NPY_FR_ns;\n tc->type = JT_UTF8;\n } else {\n const int unit = ((PyObjectEncoder *)tc->encoder)->datetimeUnit;" }, { "filename": "pandas/core/arrays/datetimelike.py", "status": "modified", "additions": 0, "deletions": 3, "changes": 3, "patch": "@@ -2479,9 +2479,6 @@ def _with_freq(self, freq) -> Self:\n \n def _values_for_json(self) -> np.ndarray:\n # Small performance bump vs the base class which calls np.asarray(self)\n- if self.unit != \"ns\":\n- # GH#55827\n- return self.as_unit(\"ns\")._values_for_json()\n if isinstance(self.dtype, np.dtype):\n return self._ndarray\n return super()._values_for_json()" }, { "filename": "pandas/core/generic.py", "status": "modified", "additions": 1, "deletions": 1, "changes": 2, "patch": "@@ -2613,7 +2613,7 @@ def to_json(\n elif date_format is None:\n date_format = \"epoch\"\n dtypes = self.dtypes if self.ndim == 2 else [self.dtype]\n- if any(lib.is_np_dtype(dtype, \"mM\") for dtype in dtypes):\n+ if any(dtype.kind in \"mM\" for dtype in dtypes):\n warnings.warn(\n \"The default 'epoch' date format is deprecated and will be removed \"\n \"in a future version, please use 'iso' date format instead.\"," }, { "filename": "pandas/io/json/_json.py", "status": "modified", "additions": 32, "deletions": 0, "changes": 32, "patch": "@@ -186,6 +186,38 @@ def to_json(\n if orient == \"table\" and isinstance(obj, Series):\n obj = obj.to_frame(name=obj.name or \"values\")\n \n+ if date_format == \"epoch\":\n+ # for epoch (numeric) format, convert datetime-likes to the desired\n+ # unit up front, such that the C ObjToJSON code can simply write out\n+ # the integer values without worrying about conversion\n+ if date_unit not in [\"s\", \"ms\", \"us\", \"ns\"]:\n+ raise ValueError(f\"Invalid value '{date_unit}' for option 'date_unit'\")\n+ if isinstance(obj, DataFrame):\n+ copied = False\n+ cols = np.nonzero(obj.dtypes.map(lambda dt: dt.kind in [\"M\", \"m\"]))[0]\n+ if len(cols):\n+ obj = obj.copy(deep=False)\n+ copied = True\n+ for col in cols:\n+ obj.isetitem(col, obj.iloc[:, col].dt.as_unit(date_unit))\n+ if obj.index.dtype.kind in \"Mm\":\n+ if not copied:\n+ obj = obj.copy(deep=False)\n+ copied = True\n+ obj.index = Series(obj.index).dt.as_unit(date_unit)\n+ if obj.columns.dtype.kind in \"Mm\":\n+ if not copied:\n+ obj = obj.copy(deep=False)\n+ copied = True\n+ obj.columns = Series(obj.columns).dt.as_unit(date_unit)\n+ elif isinstance(obj, Series):\n+ if obj.dtype.kind in \"Mm\":\n+ obj = obj.copy(deep=False)\n+ obj = obj.dt.as_unit(date_unit)\n+ if obj.index.dtype.kind in \"Mm\":\n+ obj = obj.copy(deep=False)\n+ obj.index = Series(obj.index).dt.as_unit(date_unit)\n+\n writer: type[Writer]\n if orient == \"table\" and isinstance(obj, DataFrame):\n writer = JSONTableWriter" }, { "filename": "pandas/tests/io/json/test_pandas.py", "status": "modified", "additions": 68, "deletions": 29, "changes": 97, "patch": "@@ -153,12 +153,10 @@ def test_frame_non_unique_columns(self, orient, data, request):\n expected = DataFrame(data)\n if expected.iloc[:, 0].dtype == \"datetime64[s]\":\n # orient == \"values\" by [NAME_REDACTED] objects out\n- # in milliseconds; these are internally stored in nanosecond,\n- # so divide to get where we need\n+ # in milliseconds;\n # TODO: a to_epoch method would also solve; see GH 14772\n dta = expected.iloc[:, 0]._values\n- dta = dta.as_unit(\"ns\") # GH#55827\n- expected.isetitem(0, dta.astype(np.int64) // 1_000_000)\n+ expected.isetitem(0, dta.as_unit(\"ms\").astype(np.int64))\n elif orient == \"split\":\n expected = df\n expected.columns = [\"x\", \"x.1\"]\n@@ -273,12 +271,21 @@ def test_roundtrip_empty(self, orient, convert_axes):\n \n tm.assert_frame_equal(result, expected)\n \n+ [USER_REDACTED].mark.parametrize(\n+ \"dtype_backend\", [None, pytest.param(\"pyarrow\", marks=td.skip_if_no(\"pyarrow\"))]\n+ )\n [USER_REDACTED].mark.parametrize(\"convert_axes\", [True, False])\n- def test_roundtrip_timestamp(self, orient, convert_axes, datetime_frame):\n+ def test_roundtrip_timestamp(\n+ self, orient, convert_axes, dtype_backend, datetime_frame\n+ ):\n # TODO: improve coverage with date_format parameter\n+ expected = datetime_frame.copy()\n+ if dtype_backend is not None:\n+ datetime_frame.index = Series(datetime_frame.index).convert_dtypes(\n+ dtype_backend=dtype_backend\n+ )\n data = StringIO(datetime_frame.to_json(orient=orient))\n result = read_json(data, orient=orient, convert_axes=convert_axes)\n- expected = datetime_frame.copy()\n \n if not convert_axes: # one off for ts handling\n # DTI gets converted to epoch values\n@@ -736,11 +743,19 @@ def test_series_roundtrip_empty(self, orient):\n \n tm.assert_series_equal(result, expected)\n \n- def test_series_roundtrip_timeseries(self, orient, datetime_series):\n+ [USER_REDACTED].mark.parametrize(\n+ \"dtype_backend\", [None, pytest.param(\"pyarrow\", marks=td.skip_if_no(\"pyarrow\"))]\n+ )\n+ def test_series_roundtrip_timeseries(self, dtype_backend, orient, datetime_series):\n+ expected = datetime_series.copy()\n+ if dtype_backend is not None:\n+ datetime_series.index = Series(datetime_series.index).convert_dtypes(\n+ dtype_backend=dtype_backend\n+ )\n+\n data = StringIO(datetime_series.to_json(orient=orient))\n result = read_json(data, typ=\"series\", orient=orient)\n \n- expected = datetime_series\n if orient in (\"values\", \"records\"):\n expected = expected.reset_index(drop=True)\n else:\n@@ -780,15 +795,20 @@ def test_series_with_dtype(self):\n expected = Series([4] * 3)\n tm.assert_series_equal(result, expected)\n \n+ [USER_REDACTED].mark.parametrize(\n+ \"dtype_backend\", [None, pytest.param(\"pyarrow\", marks=td.skip_if_no(\"pyarrow\"))]\n+ )\n [USER_REDACTED].mark.parametrize(\n \"dtype,expected\",\n [\n (True, Series([\"2000-01-01\"], dtype=\"datetime64[ms]\")),\n (False, Series([946684800000])),\n ],\n )\n- def test_series_with_dtype_datetime(self, dtype, expected):\n+ def test_series_with_dtype_datetime(self, dtype, expected, dtype_backend):\n s = Series([\"2000-01-01\"], dtype=\"datetime64[ns]\")\n+ if dtype_backend is not None:\n+ s = s.convert_dtypes(dtype_backend=dtype_backend)\n msg = (\n \"The default 'epoch' date format is deprecated and will be removed \"\n \"in a future version, please use 'iso' date format instead.\"\n@@ -1052,8 +1072,11 @@ def test_default_epoch_date_format_deprecated(self, df, warn):\n with tm.assert_produces_warning(warn, match=msg):\n df.to_json()\n \n+ [USER_REDACTED].mark.parametrize(\n+ \"dtype_backend\", [None, pytest.param(\"pyarrow\", marks=td.skip_if_no(\"pyarrow\"))]\n+ )\n [USER_REDACTED].mark.parametrize(\"unit\", [\"s\", \"ms\", \"us\"])\n- def test_iso_non_nano_datetimes(self, unit):\n+ def test_iso_non_nano_datetimes(self, dtype_backend, unit):\n # Test that numpy datetimes\n # in an Index or a column with non-nano resolution can be serialized\n # correctly\n@@ -1076,20 +1099,17 @@ def test_iso_non_nano_datetimes(self, unit):\n ),\n },\n )\n+ expected = df.copy()\n+ expected.index = expected.index.as_unit(\"us\")\n+ expected[\"date\"] = expected[\"date\"].dt.as_unit(\"us\")\n+ expected[\"date_obj\"] = expected[\"date_obj\"].astype(\"datetime64[us]\")\n \n- buf = StringIO()\n- df.to_json(buf, date_format=\"iso\", date_unit=unit)\n- buf.seek(0)\n+ if dtype_backend is not None:\n+ df = df.convert_dtypes(dtype_backend=dtype_backend)\n \n- # read_json always reads datetimes in nanosecond resolution\n- # TODO: check_dtype/check_index_type should be removable\n- # once read_json gets non-nano support\n- tm.assert_frame_equal(\n- read_json(buf, convert_dates=[\"date\", \"date_obj\"]),\n- df,\n- check_index_type=False,\n- check_dtype=False,\n- )\n+ json = df.to_json(date_format=\"iso\", date_unit=unit)\n+ result = read_json(StringIO(json), convert_dates=[\"date\", \"date_obj\"])\n+ tm.assert_frame_equal(result, expected)\n \n def test_weird_nested_json(self):\n # this used to core dump the parser\n@@ -1154,11 +1174,11 @@ def test_url(self, httpserver):\n ]:\n assert result[field].dtype == dtype\n \n- def test_timedelta(self):\n+ def test_timedelta(self, unit):\n converter = lambda x: pd.to_timedelta(x, unit=\"ms\")\n \n- ser = Series([timedelta(23), timedelta(seconds=5)], dtype=\"m8[ns]\")\n- assert ser.dtype == \"timedelta64[ns]\"\n+ ser = Series([timedelta(23), timedelta(seconds=5)], dtype=f\"m8[{unit}]\")\n+ assert ser.dtype == f\"timedelta64[{unit}]\"\n \n msg = (\n \"The default 'epoch' date format is deprecated and will be removed \"\n@@ -1816,13 +1836,32 @@ def test_read_json_with_very_long_file_path(self, compression):\n # _get_data_from_filepath()\n read_json(long_json_path)\n \n+ [USER_REDACTED].mark.parametrize(\n+ \"date_format,key\", [(\"epoch\", 86400000), (\"iso\", \"1970-01-02T00:00:00.000\")]\n+ )\n+ def test_datetime_as_label(self, date_format, key, unit):\n+ df = DataFrame(\n+ [[1]], columns=[(Timestamp(0) + pd.Timedelta(\"1D\")).as_unit(unit)]\n+ )\n+ expected = f'{{\"{key}\":{{\"0\":1}}}}'\n+\n+ expected_warning = None\n+ if date_format == \"epoch\":\n+ expected_warning = Pandas4Warning\n+\n+ msg = (\n+ \"'epoch' date format is deprecated and will be removed in a future \"\n+ \"version, please use 'iso' date format instead.\"\n+ )\n+ with tm.assert_produces_warning(expected_warning, match=msg):\n+ result = df.to_json(date_format=date_format)\n+\n+ assert result == expected\n+\n [USER_REDACTED].mark.parametrize(\n \"date_format,key\", [(\"epoch\", 86400000), (\"iso\", \"P1DT0H0M0S\")]\n )\n- def test_timedelta_as_label(self, date_format, key, unit, request):\n- if unit != \"ns\":\n- mark = pytest.mark.xfail(reason=\"GH#63236 failure to round-trip\")\n- request.applymarker(mark)\n+ def test_timedelta_as_label(self, date_format, key, unit):\n df = DataFrame([[1]], columns=[pd.Timedelta(\"1D\").as_unit(unit)])\n expected = f'{{\"{key}\":{{\"0\":1}}}}'" } ], "reviews": [ { "id": 3672800516, "user": "user_fb5fa0a10142", "state": "COMMENTED", "body": null, "submitted_at": "2026-01-16T21:33:04+00:00" }, { "id": 3674131306, "user": "user_7213a217ace7", "state": "COMMENTED", "body": null, "submitted_at": "2026-01-17T14:10:03+00:00" }, { "id": 3674246789, "user": "user_fb5fa0a10142", "state": "COMMENTED", "body": null, "submitted_at": "2026-01-17T16:05:11+00:00" }, { "id": 3675862967, "user": "user_7213a217ace7", "state": "COMMENTED", "body": null, "submitted_at": "2026-01-18T23:23:56+00:00" } ], "review_comments": [ { "id": 2700029702, "user": "user_fb5fa0a10142", "body": "1) dtype.kind in \"mM\" is _slightly_ faster\n2) will this be wrong for pyarrow date dtype?", "path": "pandas/io/json/_json.py", "line": null, "side": "RIGHT", "created_at": "2026-01-16T21:33:05+00:00" }, { "id": 2701165752, "user": "user_7213a217ace7", "body": "Good point, the basic Index with ArrowDtype won't have `as_unit` directly. Pushed a fix for this (and test coverage), not sure if there is an easier way right now than roundtripping through series to use `.dt.unit()`? (it's a bit ugly, but converting to datetime/timdelta index and back would be even more verbose)", "path": "pandas/io/json/_json.py", "line": null, "side": "RIGHT", "created_at": "2026-01-17T14:10:02+00:00" }, { "id": 2701246496, "user": "user_fb5fa0a10142", "body": "could just do `isinstance(obj._values, (DatetimeArray, TimedeltaArray))` for now?", "path": "pandas/io/json/_json.py", "line": null, "side": "RIGHT", "created_at": "2026-01-17T16:05:10+00:00" }, { "id": 2702842167, "user": "user_7213a217ace7", "body": "Not really, because I now changed the C code to assume the datetimes-like data are already cast to the desired unit up front, and it is no longer done in the C code. So not handling the ArrowDtype variant here would actually mean writing wrong values for those dtypes (some of the tests I added after your previous comment to parametrized with pyarrow dtypes fail if doing this change).", "path": "pandas/io/json/_json.py", "line": null, "side": "RIGHT", "created_at": "2026-01-18T23:23:56+00:00" } ], "meta": { "languages": [ "c", "h", "py" ], "touches_tests": true, "review_state_summary": { "COMMENTED": 4 }, "meaningful_comment_count": 4, "has_approval": false, "has_changes_requested": false, "total_review_comments": 4 } } { "_id": "99073e1b9a45719d", "_schema_version": "1.0", "_cleaned_at": "2026-02-12T07:46:51.876262+00:00", "repo": "pandas-dev/pandas", "repo_url": "https://github.com/pandas-dev/pandas", "license_name": "BSD 3-Clause \"New\" or \"Revised\" License", "license_spdx": "BSD-3-Clause", "pr_number": 63661, "title": "CLN: Enable ruff rule PLR1714 (repeated-equality-comparison)", "body": "- [ ] closes #xxxx (Replace xxxx with the GitHub issue number)\n- [ ] [Tests added and passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#writing-tests) if fixing a bug or adding a new feature\n- [x] All [code checks passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit).\n- [ ] Added [type annotations](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#type-hints) to new arguments/methods/functions.\n- [ ] Added an entry in the latest `doc/source/whatsnew/vX.X.X.rst` file if fixing a bug or adding a new feature.\n- [x] If I used AI to develop this pull request, I prompted it to follow `AGENTS.md`.", "author": "user_98fd51bab008", "created_at": "2026-01-13T01:27:16+00:00", "merged_at": "2026-01-13T21:31:56+00:00", "base_branch": "main", "head_branch": "cln-enable-ruff-PLR1714", "additions": 10, "deletions": 13, "changed_files": 11, "files": [ { "filename": "pandas/core/arrays/categorical.py", "status": "modified", "additions": 1, "deletions": 1, "changes": 2, "patch": "@@ -2280,7 +2280,7 @@ def _repr_categories(self) -> list[str]:\n from pandas.io.formats import format as fmt\n \n formatter = None\n- if self.categories.dtype == \"str\" or self.categories.dtype == \"string\":\n+ if self.categories.dtype == \"str\" or self.categories.dtype == \"string\": # noqa: PLR1714 (repeated-equality-comparison)\n # the extension array formatter defaults to boxed=True in format_array\n # override here to boxed=False to be consistent with QUOTE_NONNUMERIC\n formatter = cast(ExtensionArray, self.categories._values)._formatter(" }, { "filename": "pandas/core/arrays/string_.py", "status": "modified", "additions": 1, "deletions": 1, "changes": 2, "patch": "@@ -238,7 +238,7 @@ def __eq__(self, other: object) -> bool:\n # cannot be checked with normal `==`\n if isinstance(other, str):\n # TODO should dtype == \"string\" work for the NaN variant?\n- if other == \"string\" or other == self.name:\n+ if other == \"string\" or other == self.name: # noqa: PLR1714 (repeated-equality-comparison)\n return True\n try:\n other = self.construct_from_string(other)" }, { "filename": "pandas/core/dtypes/astype.py", "status": "modified", "additions": 1, "deletions": 1, "changes": 2, "patch": "@@ -129,7 +129,7 @@ def _astype_nansafe(\n )\n raise ValueError(msg)\n \n- if copy or arr.dtype == object or dtype == object:\n+ if copy or object in (arr.dtype, dtype):\n # Explicit copy, or required since NumPy can't view from / to object.\n return arr.astype(dtype, copy=True)" }, { "filename": "pandas/core/frame.py", "status": "modified", "additions": 1, "deletions": 1, "changes": 2, "patch": "@@ -12147,7 +12147,7 @@ def join(\n \n # join indexes only using concat\n if can_concat:\n- if how == \"left\" or how == \"right\":\n+ if how in {\"left\", \"right\"}:\n res = concat(\n frames, axis=1, join=\"outer\", verify_integrity=True, sort=sort\n )" }, { "filename": "pandas/core/nanops.py", "status": "modified", "additions": 1, "deletions": 2, "changes": 3, "patch": "@@ -461,8 +461,7 @@ def newfunc(values: np.ndarray, *, axis: AxisInt | None = None, **kwargs):\n # only takes this path for wide arrays (long dataframes), for threshold see\n # https://github.com/[USER_REDACTED]ndas-dev/pandas/pull/43311#issuecomment-974891737\n and (values.shape[1] / 1000) > values.shape[0]\n- and values.dtype != object\n- and values.dtype != bool\n+ and values.dtype not in (object, bool)\n ):\n arrs = list(values)\n if kwargs.get(\"mask\") is not None:" }, { "filename": "pandas/tests/groupby/aggregate/test_aggregate.py", "status": "modified", "additions": 1, "deletions": 1, "changes": 2, "patch": "@@ -303,7 +303,7 @@ def test_wrap_agg_out(three_group):\n grouped = three_group.groupby([\"A\", \"B\"])\n \n def func(ser):\n- if ser.dtype == object or ser.dtype == \"string\":\n+ if ser.dtype in (object, \"string\"):\n raise TypeError(\"Test error message\")\n return ser.sum()" }, { "filename": "pandas/tests/indexes/test_any_index.py", "status": "modified", "additions": 1, "deletions": 1, "changes": 2, "patch": "@@ -48,7 +48,7 @@ def test_map_identity_mapping(index, request, using_infer_string):\n request.applymarker(mark)\n \n result = index.map(lambda x: x)\n- if index.dtype == object and (result.dtype == bool or result.dtype == \"string\"):\n+ if index.dtype == object and (result.dtype in (bool, \"string\")):\n assert (index == result).all()\n # TODO: could work that into the 'exact=\"equiv\"'?\n return # FIXME: doesn't belong in this file anymore!" }, { "filename": "pandas/tests/indexes/test_old_base.py", "status": "modified", "additions": 1, "deletions": 1, "changes": 2, "patch": "@@ -456,7 +456,7 @@ def test_insert_out_of_bounds(self, index, using_infer_string):\n msg = \"slice indices must be integers or None or have an __index__ method\"\n \n if using_infer_string:\n- if index.dtype == \"string\" or index.dtype == \"category\":\n+ if str(index.dtype) in {\"str\", \"string\", \"category\"}:\n msg = \"loc must be an integer between\"\n elif index.dtype == \"object\" and len(index) == 0:\n msg = \"loc must be an integer between\"" }, { "filename": "pandas/tests/plotting/test_boxplot_method.py", "status": "modified", "additions": 1, "deletions": 1, "changes": 2, "patch": "@@ -403,7 +403,7 @@ def test_boxplot_group_no_xlabel_ylabel(self, vert, request):\n for subplot in ax:\n target_label = (\n subplot.get_xlabel()\n- if vert == {\"vert\": True} or vert == {\"orientation\": \"vertical\"}\n+ if vert in ({\"vert\": True}, {\"orientation\": \"vertical\"})\n else subplot.get_ylabel()\n )\n assert target_label == pprint_thing([\"group\"])" }, { "filename": "pandas/tests/strings/test_cat.py", "status": "modified", "additions": 1, "deletions": 1, "changes": 2, "patch": "@@ -350,7 +350,7 @@ def test_str_cat_datetime_index_unsorted(join_type):\n s = Series([\"a\", \"b\"], index=[values[1], values[0]])\n others = Series([\"c\", \"d\"], index=[values[0], values[1]])\n result = s.str.cat(others, join=join_type)\n- if join_type == \"outer\" or join_type == \"right\":\n+ if join_type in {\"outer\", \"right\"}:\n expected = Series([\"bc\", \"ad\"], index=[values[0], values[1]])\n else:\n expected = Series([\"ad\", \"bc\"], index=[values[1], values[0]])" }, { "filename": "pyproject.toml", "status": "modified", "additions": 0, "deletions": 2, "changes": 2, "patch": "@@ -339,8 +339,6 @@ ignore = [\n \"RUF012\",\n # type-comparison\n \"E721\",\n- # repeated-equality-comparison\n- \"PLR1714\",\n # self-or-cls-assignment\n \"PLW0642\",\n # literal-membership" } ], "reviews": [ { "id": 3656991215, "user": "user_c9260bc45a59", "state": "COMMENTED", "body": null, "submitted_at": "2026-01-13T17:23:29+00:00" }, { "id": 3656993021, "user": "user_c9260bc45a59", "state": "COMMENTED", "body": null, "submitted_at": "2026-01-13T17:24:01+00:00" }, { "id": 3658022007, "user": "user_c9260bc45a59", "state": "APPROVED", "body": null, "submitted_at": "2026-01-13T21:31:50+00:00" } ], "review_comments": [ { "id": 2687380997, "user": "user_c9260bc45a59", "body": "Could we use a noqa for this one?", "path": "pandas/core/arrays/string_.py", "line": 241, "side": "LEFT", "created_at": "2026-01-13T17:23:29+00:00" }, { "id": 2687382631, "user": "user_c9260bc45a59", "body": "Could we use a noqa for this one?", "path": "pandas/core/arrays/categorical.py", "line": 2283, "side": "LEFT", "created_at": "2026-01-13T17:24:01+00:00" } ], "meta": { "languages": [ "py", "toml" ], "touches_tests": true, "review_state_summary": { "COMMENTED": 2, "APPROVED": 1 }, "meaningful_comment_count": 2, "has_approval": true, "has_changes_requested": false, "total_review_comments": 2 } } { "_id": "a7555d7f87f3ea30", "_schema_version": "1.0", "_cleaned_at": "2026-02-12T07:46:51.876262+00:00", "repo": "pandas-dev/pandas", "repo_url": "https://github.com/pandas-dev/pandas", "license_name": "BSD 3-Clause \"New\" or \"Revised\" License", "license_spdx": "BSD-3-Clause", "pr_number": 63660, "title": "ERR: Clarify .groups single element scalar keys deprecation", "body": "xref https://github.com/[USER_REDACTED]ndas-dev/pandas/pull/59179\n\nI was a little confused by [NAME_REDACTED] finding this warning in cuDF. IIUC, it's the dictionary _keys_ that are changing type, but `.groups` will still return a dictionary.", "author": "user_c9260bc45a59", "created_at": "2026-01-13T00:40:13+00:00", "merged_at": "2026-01-13T23:05:45+00:00", "base_branch": "main", "head_branch": "ref/error/groups", "additions": 11, "deletions": 12, "changed_files": 4, "files": [ { "filename": "doc/source/whatsnew/v3.0.0.rst", "status": "modified", "additions": 1, "deletions": 1, "changes": 2, "patch": "@@ -868,7 +868,7 @@ [NAME_REDACTED]\n - Deprecated allowing non-keyword arguments in :meth:`DataFrame.groupby` and :meth:`Series.groupby` except ``by`` and ``level``. (:issue:`62102`)\n - Deprecated allowing non-keyword arguments in :meth:`Series.to_markdown` except ``buf``. (:issue:`57280`)\n - Deprecated allowing non-keyword arguments in :meth:`Series.to_string` except ``buf``. (:issue:`57280`)\n-- Deprecated behavior of :meth:`.DataFrameGroupBy.groups` and :meth:`.SeriesGroupBy.groups`, in a future version ``groups`` by [NAME_REDACTED] return tuple instead of scalar. (:issue:`58858`)\n+- Deprecated behavior of :meth:`.DataFrameGroupBy.groups` and :meth:`.SeriesGroupBy.groups` returning scalar dictionary keys when grouping by [NAME_REDACTED] a single element. The dictionary keys return will be tuples in a future version. (:issue:`58858`)\n - Deprecated behavior of :meth:`Series.dt.to_pytimedelta`, in a future version this will return a :class:`Series` containing python ``datetime.timedelta`` objects instead of an ``ndarray`` of timedelta; this matches the behavior of other :meth:`Series.dt` properties. (:issue:`57463`)\n - Deprecated converting object-dtype columns of ``datetime.datetime`` objects to datetime64 when writing to stata (:issue:`56536`)\n - Deprecated lowercase strings ``d``, ``b`` and ``c`` denoting frequencies in :class:`.Day`, :class:`.BusinessDay` and :class:`.CustomBusinessDay` in favour of ``D``, ``B`` and ``C`` (:issue:`58998`)" }, { "filename": "pandas/core/groupby/groupby.py", "status": "modified", "additions": 4, "deletions": 3, "changes": 7, "patch": "@@ -542,9 +542,10 @@ def groups(self) -> dict[Hashable, Index]:\n \"\"\"\n if isinstance(self.keys, list) and len(self.keys) == 1:\n warnings.warn(\n- \"`groups` by [NAME_REDACTED] scalar is deprecated \"\n- \"and will be removed. In a future version `groups` by [NAME_REDACTED] \"\n- \"list will return tuple. Use ``df.groupby(by='a').groups`` \"\n+ \"In a future version, the keys of `groups` will be a \"\n+ f\"tuple with a single element, e.g. ({self.keys[0]},) , \"\n+ f\"instead of a scalar, e.g. {self.keys[0]}, when grouping \"\n+ \"by a list with a single element. Use ``df.groupby(by='a').groups`` \"\n \"instead of ``df.groupby(by=['a']).groups`` to avoid this warning\",\n Pandas4Warning,\n stacklevel=find_stack_level()," }, { "filename": "pandas/tests/groupby/test_grouping.py", "status": "modified", "additions": 5, "deletions": 5, "changes": 10, "patch": "@@ -544,7 +544,7 @@ def test_multiindex_columns_empty_level(self):\n \n df = DataFrame([[1, \"A\"]], columns=midx)\n \n- msg = \"`groups` by [NAME_REDACTED] scalar is deprecated\"\n+ msg = \"In a future version, the keys\"\n grouped = df.groupby(\"to filter\").groups\n assert grouped[\"A\"] == [0]\n \n@@ -573,7 +573,7 @@ def test_groupby_multiindex_tuple(self):\n columns=MultiIndex.from_arrays([[\"a\", \"b\", \"b\", \"c\"], [1, 1, 2, 2]]),\n )\n \n- msg = \"`groups` by [NAME_REDACTED] scalar is deprecated\"\n+ msg = \"In a future version, the keys\"\n with tm.assert_produces_warning(Pandas4Warning, match=msg):\n expected = df.groupby([(\"b\", 1)]).groups\n result = df.groupby((\"b\", 1)).groups\n@@ -625,7 +625,7 @@ def test_groupby_multiindex_partial_indexing_equivalence(self):\n result_max = df.groupby([(\"a\", 1)])[\"b\"].max()\n tm.assert_frame_equal(expected_max, result_max)\n \n- msg = \"`groups` by [NAME_REDACTED] scalar is deprecated\"\n+ msg = \"In a future version, the keys\"\n with tm.assert_produces_warning(Pandas4Warning, match=msg):\n expected_groups = df.groupby([(\"a\", 1)])[[(\"b\", 1), (\"b\", 2)]].groups\n result_groups = df.groupby([(\"a\", 1)])[\"b\"].groups\n@@ -735,7 +735,7 @@ def test_list_grouper_with_nat(self):\n df = DataFrame({\"date\": date_range(\"1/1/2011\", periods=365, freq=\"D\")})\n df.iloc[-1] = pd.NaT\n grouper = Grouper(key=\"date\", freq=\"YS\")\n- msg = \"`groups` by [NAME_REDACTED] scalar is deprecated\"\n+ msg = \"In a future version, the keys\"\n \n # Grouper in a list grouping\n gb = df.groupby([grouper])\n@@ -1036,7 +1036,7 @@ def test_gb_key_len_equal_axis_len(self):\n class TestIteration:\n def test_groups(self, df):\n grouped = df.groupby([\"A\"])\n- msg = \"`groups` by [NAME_REDACTED] scalar is deprecated\"\n+ msg = \"In a future version, the keys\"\n \n with tm.assert_produces_warning(Pandas4Warning, match=msg):\n groups = grouped.groups" }, { "filename": "pandas/tests/groupby/test_raises.py", "status": "modified", "additions": 1, "deletions": 3, "changes": 4, "patch": "@@ -596,9 +596,7 @@ def test_groupby_raises_category_np(\n _call_and_check(klass, msg, how, gb, groupby_func_np, ())\n \n \n-[USER_REDACTED].mark.filterwarnings(\n- \"ignore:`groups` by [NAME_REDACTED] scalar is deprecated\"\n-)\n+[USER_REDACTED].mark.filterwarnings(\"ignore:In a future version, the keys\")\n [USER_REDACTED].mark.parametrize(\"how\", [\"method\", \"agg\", \"transform\"])\n def test_groupby_raises_category_on_category(\n how," } ], "reviews": [ { "id": 3657979080, "user": "user_c1cc819e14db", "state": "APPROVED", "body": null, "submitted_at": "2026-01-13T21:18:53+00:00" }, { "id": 3658260216, "user": "user_c1cc819e14db", "state": "APPROVED", "body": "lgtm", "submitted_at": "2026-01-13T23:05:32+00:00" } ], "review_comments": [ { "id": 2688153773, "user": "user_c1cc819e14db", "body": "```suggestion\n- Deprecated behavior of :meth:`.DataFrameGroupBy.groups` and :meth:`.SeriesGroupBy.groups` returning scalar dictionary keys when grouping by [NAME_REDACTED] a single element. The dictionary keys return will be tuples in a future version. (:issue:`58858`)\n```", "path": "doc/source/whatsnew/v3.0.0.rst", "line": null, "side": "RIGHT", "created_at": "2026-01-13T21:17:48+00:00" } ], "meta": { "languages": [ "py", "rst" ], "touches_tests": true, "review_state_summary": { "APPROVED": 2 }, "meaningful_comment_count": 1, "has_approval": true, "has_changes_requested": false, "total_review_comments": 1 } } { "_id": "1be7ece6923b59a1", "_schema_version": "1.0", "_cleaned_at": "2026-02-12T07:46:51.876262+00:00", "repo": "pandas-dev/pandas", "repo_url": "https://github.com/pandas-dev/pandas", "license_name": "BSD 3-Clause \"New\" or \"Revised\" License", "license_spdx": "BSD-3-Clause", "pr_number": 63656, "title": "API: DatetimeIndex.equals with mismatched units", "body": "- [x] closes #63459 (Replace xxxx with the GitHub issue number)\n- [x] [Tests added and passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#writing-tests) if fixing a bug or adding a new feature\n- [ ] All [code checks passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit).\n- [ ] Added [type annotations](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#type-hints) to new arguments/methods/functions.\n- [ ] Added an entry in the latest `doc/source/whatsnew/vX.X.X.rst` file if fixing a bug or adding a new feature.\n- [ ] If I used AI to develop this pull request, I prompted it to follow `AGENTS.md`.", "author": "user_fb5fa0a10142", "created_at": "2026-01-12T17:00:15+00:00", "merged_at": "2026-01-12T23:22:31+00:00", "base_branch": "main", "head_branch": "api-equals", "additions": 43, "deletions": 5, "changed_files": 3, "files": [ { "filename": "pandas/core/indexes/datetimelike.py", "status": "modified", "additions": 15, "deletions": 4, "changes": 19, "patch": "@@ -37,6 +37,8 @@\n from pandas.errors import (\n InvalidIndexError,\n NullFrequencyError,\n+ OutOfBoundsDatetime,\n+ OutOfBoundsTimedelta,\n )\n from pandas.util._decorators import (\n cache_readonly,\n@@ -266,11 +268,20 @@ def equals(self, other: Any) -> bool:\n # OverflowError -> Index([very_large_timedeltas])\n return False\n \n- if self.dtype != other.dtype:\n- # have different timezone\n+ if type(self) != type(other):\n return False\n-\n- return np.array_equal(self.asi8, other.asi8)\n+ elif self.dtype == other.dtype:\n+ return np.array_equal(self.asi8, other.asi8)\n+ elif (self.dtype.kind == \"M\" and self.tz == other.tz) or self.dtype.kind == \"m\": # type: ignore[attr-defined]\n+ # different units, otherwise matching\n+ try:\n+ # TODO: do this at the EA level?\n+ left, right = self._data._ensure_matching_resos(other._data) # type: ignore[union-attr]\n+ except (OutOfBoundsDatetime, OutOfBoundsTimedelta):\n+ return False\n+ else:\n+ return np.array_equal(left.view(\"i8\"), right.view(\"i8\"))\n+ return False\n \n def __contains__(self, key: Any) -> bool:\n \"\"\"" }, { "filename": "pandas/tests/indexes/datetimes/test_setops.py", "status": "modified", "additions": 5, "deletions": 1, "changes": 6, "patch": "@@ -245,9 +245,13 @@ def test_intersection_same_timezone_different_units(self):\n \n # Test intersection\n result = idx1.intersection(idx2)\n- expected = date_range(\"2000-01-01\", periods=3, tz=tz).as_unit(\"ns\")\n+ expected = date_range(\"2000-01-01\", periods=3, tz=tz)\n tm.assert_index_equal(result, expected)\n \n+ # Intersection dtype is not commutative\n+ result2 = idx2.intersection(idx1)\n+ tm.assert_index_equal(result2, expected.as_unit(\"ns\"))\n+\n def test_symmetric_difference_same_timezone_different_units(self):\n # GH 60080 - fix timezone being changed to UTC when units differ\n # but timezone is the same" }, { "filename": "pandas/tests/series/test_arithmetic.py", "status": "modified", "additions": 23, "deletions": 0, "changes": 23, "patch": "@@ -1060,3 +1060,26 @@ def test_rmod_consistent_large_series():\n expected = Series([1] * 10001)\n \n tm.assert_series_equal(result, expected)\n+\n+\n+[USER_REDACTED].mark.parametrize(\n+ \"index\",\n+ [\n+ date_range(\"2016-01-01\", periods=3),\n+ date_range(\"2016-01-01\", tz=\"US/Pacific\", periods=3),\n+ pd.timedelta_range(\"1 Day\", periods=3),\n+ ],\n+)\n+def test_comparison_mismatched_datetime_units(index):\n+ # GH#63459\n+\n+ ser = Series(1, index=index)\n+ ser2 = Series(1, index=index.as_unit(\"ns\"))\n+\n+ result = ser == ser2\n+ expected = Series([True, True, True], index=ser.index)\n+ tm.assert_series_equal(result, expected)\n+\n+ result2 = ser2 < ser\n+ expected2 = Series([False, False, False], index=ser2.index)\n+ tm.assert_series_equal(result2, expected2)" } ], "reviews": [ { "id": 3652259075, "user": "user_c9260bc45a59", "state": "COMMENTED", "body": null, "submitted_at": "2026-01-12T18:59:08+00:00" }, { "id": 3652873781, "user": "user_fb5fa0a10142", "state": "COMMENTED", "body": null, "submitted_at": "2026-01-12T21:48:05+00:00" }, { "id": 3653100362, "user": "user_c9260bc45a59", "state": "APPROVED", "body": null, "submitted_at": "2026-01-12T23:22:25+00:00" } ], "review_comments": [ { "id": 2683510316, "user": "user_c9260bc45a59", "body": "Do we have tests for the timezone aware and timedelta variants?", "path": "pandas/tests/series/test_arithmetic.py", "line": null, "side": "RIGHT", "created_at": "2026-01-12T18:59:08+00:00" }, { "id": 2684022361, "user": "user_fb5fa0a10142", "body": "Updated, yes", "path": "pandas/tests/series/test_arithmetic.py", "line": null, "side": "RIGHT", "created_at": "2026-01-12T21:48:05+00:00" } ], "meta": { "languages": [ "py" ], "touches_tests": true, "review_state_summary": { "COMMENTED": 2, "APPROVED": 1 }, "meaningful_comment_count": 2, "has_approval": true, "has_changes_requested": false, "total_review_comments": 2 } } { "_id": "0f68c205cca1277b", "_schema_version": "1.0", "_cleaned_at": "2026-02-12T07:46:51.876262+00:00", "repo": "pandas-dev/pandas", "repo_url": "https://github.com/pandas-dev/pandas", "license_name": "BSD 3-Clause \"New\" or \"Revised\" License", "license_spdx": "BSD-3-Clause", "pr_number": 63613, "title": "BUG: str methods failing on PyArrow data with lookaround regexes", "body": "- [x] closes #60833 (Replace xxxx with the GitHub issue number)\n- [ ] [Tests added and passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#writing-tests) if fixing a bug or adding a new feature\n- [ ] All [code checks passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit).\n- [ ] Added [type annotations](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#type-hints) to new arguments/methods/functions.\n- [ ] Added an entry in the latest `doc/source/whatsnew/vX.X.X.rst` file if fixing a bug or adding a new feature.\n- [ ] If I used AI to develop this pull request, I prompted it to follow `AGENTS.md`.\n\nFallbacks to object dtype when lookarounds are used. Using the internals of CPython's `re` module is not exactly desirable, but seems better than any alternatives.", "author": "user_c1cc819e14db", "created_at": "2026-01-08T21:59:13+00:00", "merged_at": "2026-01-18T23:54:29+00:00", "base_branch": "main", "head_branch": "bug_str_contains_lookaround", "additions": 326, "deletions": 3, "changed_files": 8, "files": [ { "filename": "doc/source/whatsnew/v3.0.0.rst", "status": "modified", "additions": 1, "deletions": 0, "changes": 1, "patch": "@@ -1208,6 +1208,7 @@ Strings\n - Bug in :meth:`Series.str.match` failing to raise when given a compiled ``re.Pattern`` object and conflicting ``case`` or ``flags`` arguments (:issue:`62240`)\n - Bug in :meth:`Series.str.zfill` raising ``AttributeError`` for :class:`ArrowDtype` (:issue:`61485`)\n - Bug in :meth:`Series.value_counts` would not respect ``sort=False`` for series having ``string`` dtype (:issue:`55224`)\n+- Bug in :ref:`Series.str methods ` would fail when using regex with lookaheads or lookbehinds on data backed by PyArrow (:issue:`60833`)\n - Bug in multiplication with a :class:`StringDtype` incorrectly allowing multiplying by bools; explicitly cast to integers instead (:issue:`62595`)\n \n Interval" }, { "filename": "pandas/core/arrays/_arrow_string_mixins.py", "status": "modified", "additions": 44, "deletions": 0, "changes": 44, "patch": "@@ -48,6 +48,50 @@ def _convert_int_result(self, result):\n def _apply_elementwise(self, func: Callable) -> list[list[Any]]:\n raise NotImplementedError\n \n+ [USER_REDACTED]\n+ def _has_regex_lookaround(pat: str | re.Pattern) -> bool:\n+ \"\"\"\n+ Determine if regex pattern contains a lookahead or lookbehind.\n+\n+ Parameters\n+ ----------\n+ pat: str | re.Pattern\n+ Regex pattern.\n+\n+ Returns\n+ -------\n+ bool\n+ Whether `pat` contains a lookahead or lookbehind.\n+ \"\"\"\n+ try:\n+ # error: Module \"re\" has no attribute \"_parser\"\n+ from re import _parser # type: ignore[attr-defined]\n+\n+ regex_parser = _parser.parse\n+ except Exception as err:\n+ raise type(err)(\n+ \"Incompatible version for regex; you will need to upgrade pandas \"\n+ \"or downgrade Python\"\n+ ) from err\n+\n+ def has_assert(tokens):\n+ # For certain op codes we need to recurse.\n+ for op_code, argument in tokens:\n+ if (\n+ (op_code == _parser.SUBPATTERN and has_assert(argument[3]))\n+ or (\n+ op_code == _parser.BRANCH\n+ and any(has_assert(tokens) for tokens in argument[1])\n+ )\n+ or (op_code in [_parser.ASSERT_NOT, _parser.ASSERT])\n+ ):\n+ return True\n+ return False\n+\n+ str_pat = pat.pattern if isinstance(pat, re.Pattern) else pat\n+ tokens = regex_parser(str_pat)\n+ return has_assert(tokens)\n+\n def _str_len(self):\n result = pc.utf8_length(self._pa_array)\n return self._convert_int_result(result)" }, { "filename": "pandas/core/arrays/string_arrow.py", "status": "modified", "additions": 12, "deletions": 3, "changes": 15, "patch": "@@ -392,7 +392,11 @@ def _str_contains(\n na=lib.no_default,\n regex: bool = True,\n ):\n- if flags or self._is_re_pattern_with_flags(pat):\n+ if (\n+ flags\n+ or self._is_re_pattern_with_flags(pat)\n+ or (regex and self._has_regex_lookaround(pat))\n+ ):\n return super()._str_contains(pat, case, flags, na, regex)\n if isinstance(pat, re.Pattern):\n # TODO flags passed separately by [NAME_REDACTED]\n@@ -407,7 +411,11 @@ def _str_match(\n flags: int = 0,\n na: Scalar | lib.NoDefault = lib.no_default,\n ):\n- if flags or self._is_re_pattern_with_flags(pat):\n+ if (\n+ flags\n+ or self._is_re_pattern_with_flags(pat)\n+ or self._has_regex_lookaround(pat)\n+ ):\n return super()._str_match(pat, case, flags, na)\n if isinstance(pat, re.Pattern):\n pat, case, flags = self._preprocess_re_pattern(pat, case)\n@@ -446,6 +454,7 @@ def _str_replace(\n # https://docs.python.org/3/library/re.html\n isinstance(repl, str) and r\"\\g<\" in repl\n )\n+ or (regex and self._has_regex_lookaround(pat))\n ):\n return super()._str_replace(pat, repl, n, case, flags, regex)\n \n@@ -460,7 +469,7 @@ def _str_repeat(self, repeats: int | Sequence[int]):\n return ArrowExtensionArray._str_repeat(self, repeats=repeats)\n \n def _str_count(self, pat: str, flags: int = 0):\n- if flags:\n+ if flags or self._has_regex_lookaround(pat):\n return super()._str_count(pat, flags)\n result = pc.count_substring_regex(self._pa_array, pat)\n return self._convert_int_result(result)" }, { "filename": "pandas/tests/strings/test_extract.py", "status": "modified", "additions": 40, "deletions": 0, "changes": 40, "patch": "@@ -721,3 +721,43 @@ def test_extractall_preserves_dtype():\n \n result = Series([\"abc\", \"ab\"], dtype=ArrowDtype(pa.string())).str.extractall(\"(ab)\")\n assert result.dtypes[0] == \"string[pyarrow]\"\n+\n+\n+[USER_REDACTED].mark.parametrize(\n+ \"pat, expected_data\",\n+ [\n+ (r\"(a(?=b))\", [None, \"a\", None, None]),\n+ (r\"((?<=a)b)\", [None, \"b\", None, None]),\n+ (r\"(a(?!b))\", [\"a\", None, \"a\", None]),\n+ (r\"((?val, unit_for_numerics, out_reso=creso\n+ )\n+\n+ state.found_other = True\n else:\n item_reso = NPY_FR_ns\n state.update_creso(item_reso)" }, { "filename": "pandas/_libs/tslibs/conversion.pyx", "status": "modified", "additions": 1, "deletions": 1, "changes": 2, "patch": "@@ -386,7 +386,7 @@ cdef _TSObject convert_to_tsobject(object ts, tzinfo tz, str unit,\n obj.value = tz_localize_to_utc_single(\n obj.value, tz, ambiguous=\"raise\", nonexistent=None, creso=reso\n )\n- elif is_integer_object(ts):\n+ elif is_integer_object(ts) or (is_float_object(ts) and ts.is_integer()):\n try:\n ts = ts\n except OverflowError:" }, { "filename": "pandas/core/tools/datetimes.py", "status": "modified", "additions": 11, "deletions": 0, "changes": 11, "patch": "@@ -513,6 +513,17 @@ def _to_datetime_with_unit(arg, unit, name, utc: bool, errors: str) -> Index:\n tz_parsed = None\n \n elif arg.dtype.kind == \"f\":\n+ with np.errstate(invalid=\"ignore\"):\n+ int_values = arg.astype(np.int64)\n+ mask = np.isnan(arg)\n+ if (mask | (arg == int_values)).all():\n+ # With all-round-or-NaN entries, we give the requested unit\n+ # back like with integers\n+ result = _to_datetime_with_unit(\n+ int_values, unit=unit, name=name, utc=utc, errors=errors\n+ )\n+ result._data[mask] = NaT\n+ return result\n with np.errstate(over=\"raise\"):\n try:\n arr = cast_from_unit_vectorized(arg, unit=unit)" }, { "filename": "pandas/tests/scalar/timestamp/test_constructors.py", "status": "modified", "additions": 1, "deletions": 1, "changes": 2, "patch": "@@ -52,7 +52,7 @@ def test_construct_from_int_float_with_unit_out_of_bound_raises(self, typ):\n # GH#50870 make sure we get an OutOfBoundsDatetime instead of OverflowError\n val = typ(150000000000000)\n \n- msg = f\"cannot convert input {val} with the unit 'D'\"\n+ msg = f\"cannot convert input {int(val)} with the unit 'D'\"\n with pytest.raises(OutOfBoundsDatetime, match=msg):\n Timestamp(val, unit=\"D\")" }, { "filename": "pandas/tests/tools/test_to_datetime.py", "status": "modified", "additions": 9, "deletions": 8, "changes": 17, "patch": "@@ -1782,7 +1782,7 @@ class TestToDatetimeUnit:\n def test_to_datetime_month_or_year_unit_int(self, cache, unit, item, request):\n # GH#50870 Note we have separate tests that pd.Timestamp gets these right\n ts = Timestamp(item, unit=unit)\n- dtype = \"M8[ns]\" if isinstance(item, float) else \"M8[s]\"\n+ dtype = \"M8[s]\"\n expected = DatetimeIndex([ts], dtype=dtype)\n \n result = to_datetime([item], unit=unit, cache=cache)\n@@ -1797,7 +1797,7 @@ def test_to_datetime_month_or_year_unit_int(self, cache, unit, item, request):\n # with a nan!\n result = to_datetime(np.array([item, np.nan]), unit=unit, cache=cache)\n assert result.isna()[1]\n- tm.assert_index_equal(result[:1], expected.astype(\"M8[ns]\"))\n+ tm.assert_index_equal(result[:1], expected.astype(\"M8[s]\"))\n \n [USER_REDACTED].mark.parametrize(\"unit\", [\"Y\", \"M\"])\n def test_to_datetime_month_or_year_unit_non_round_float(self, cache, unit):\n@@ -1824,9 +1824,10 @@ def test_to_datetime_month_or_year_unit_non_round_float(self, cache, unit):\n expected = to_datetime([NaT])\n tm.assert_index_equal(res, expected)\n \n- # round floats are OK\n+ # round floats are OK; treated like integers to give\n+ # closest-to-supported unit\n res = to_datetime([1.0], unit=unit)\n- expected = to_datetime([1], unit=unit).as_unit(\"ns\")\n+ expected = to_datetime([1], unit=unit).as_unit(\"s\")\n tm.assert_index_equal(res, expected)\n \n def test_unit(self, cache):\n@@ -1842,7 +1843,7 @@ def test_unit_array_mixed_nans(self, cache):\n result = to_datetime(values, unit=\"D\", errors=\"coerce\", cache=cache)\n expected = DatetimeIndex(\n [\"NaT\", \"1970-01-02\", \"1970-01-02\", \"NaT\", \"NaT\", \"NaT\", \"NaT\", \"NaT\"],\n- dtype=\"M8[ns]\",\n+ dtype=\"M8[s]\",\n )\n tm.assert_index_equal(result, expected)\n \n@@ -1951,7 +1952,7 @@ def test_to_datetime_unit(self, dtype):\n epoch = 1370745748\n ser = Series([epoch + t for t in range(20)]).astype(dtype)\n result = to_datetime(ser, unit=\"s\")\n- unit = \"s\" if dtype is int else \"ns\"\n+ unit = \"s\"\n expected = Series(\n [\n Timestamp(\"2013-06-09 02:42:28\") + timedelta(seconds=t)\n@@ -1968,7 +1969,7 @@ def test_to_datetime_unit_with_nulls(self, null):\n result = to_datetime(ser, unit=\"s\")\n # With np.nan, the list gets cast to a float64 array, which always\n # gets ns unit.\n- unit = \"ns\" if null is np.nan else \"s\"\n+ unit = \"s\"\n expected = Series(\n [Timestamp(\"2013-06-09 02:42:28\") + timedelta(seconds=t) for t in range(20)]\n + [NaT],\n@@ -2568,7 +2569,7 @@ def test_to_datetime_float_with_nans_floating_point_error(self):\n ser = Series([np.nan] * 1000 + [1712219033.0], dtype=np.float64)\n result = to_datetime(ser, unit=\"s\", errors=\"coerce\")\n expected = Series(\n- [NaT] * 1000 + [Timestamp(\"2024-04-04 08:23:53\")], dtype=\"datetime64[ns]\"\n+ [NaT] * 1000 + [Timestamp(\"2024-04-04 08:23:53\")], dtype=\"datetime64[s]\"\n )\n tm.assert_series_equal(result, expected)" } ], "reviews": [ { "id": 3632037480, "user": "user_c9260bc45a59", "state": "COMMENTED", "body": null, "submitted_at": "2026-01-06T18:35:50+00:00" }, { "id": 3632041382, "user": "user_fb5fa0a10142", "state": "COMMENTED", "body": null, "submitted_at": "2026-01-06T18:37:16+00:00" }, { "id": 3632077975, "user": "user_c9260bc45a59", "state": "COMMENTED", "body": null, "submitted_at": "2026-01-06T18:47:28+00:00" }, { "id": 3632079334, "user": "user_c9260bc45a59", "state": "APPROVED", "body": null, "submitted_at": "2026-01-06T18:47:57+00:00" } ], "review_comments": [ { "id": 2665900413, "user": "user_c9260bc45a59", "body": "Are we guaranteed to have a numpy object at this point? I see `is_float_object` allows Python floats which doesn't have `is_interger`", "path": "pandas/_libs/tslibs/conversion.pyx", "line": 389, "side": "RIGHT", "created_at": "2026-01-06T18:35:50+00:00" }, { "id": 2665904168, "user": "user_fb5fa0a10142", "body": "> Python floats which doesn't have is_interger\n\nI don't think that's accurate. Grepping for \\.is_integer\\(\\) I see we use it in a few places", "path": "pandas/_libs/tslibs/conversion.pyx", "line": 389, "side": "RIGHT", "created_at": "2026-01-06T18:37:16+00:00" }, { "id": 2665933827, "user": "user_c9260bc45a59", "body": "Ah sorry. I see https://docs.python.org/3/library/stdtypes.html#float.is_integer exists now (I didn't see it originally in https://docs.python.org/3/library/functions.html#float)", "path": "pandas/_libs/tslibs/conversion.pyx", "line": 389, "side": "RIGHT", "created_at": "2026-01-06T18:47:28+00:00" } ], "meta": { "languages": [ "py", "pyx" ], "touches_tests": true, "review_state_summary": { "COMMENTED": 3, "APPROVED": 1 }, "meaningful_comment_count": 3, "has_approval": true, "has_changes_requested": false, "total_review_comments": 3 } } { "_id": "c444f61fcd771ded", "_schema_version": "1.0", "_cleaned_at": "2026-02-12T07:46:51.876262+00:00", "repo": "pandas-dev/pandas", "repo_url": "https://github.com/pandas-dev/pandas", "license_name": "BSD 3-Clause \"New\" or \"Revised\" License", "license_spdx": "BSD-3-Clause", "pr_number": 63579, "title": "DOC: Inline docstrings for StringArray methods in string_.py", "body": "- Related to issue #62437\n- Removed two [USER_REDACTED] decorators in pandas/core/arrays/string_.py\n- Extracted the rendered docstrings at runtime and inlined them directly\n- Cleaned formatting to match pandas docstring conventions", "author": "user_9f415491ab9c", "created_at": "2026-01-05T21:44:27+00:00", "merged_at": "2026-01-06T22:12:54+00:00", "base_branch": "main", "head_branch": "doc-inline-string-array", "additions": 61, "deletions": 3, "changed_files": 1, "files": [ { "filename": "pandas/core/arrays/string_.py", "status": "modified", "additions": 61, "deletions": 3, "changes": 64, "patch": "@@ -32,7 +32,6 @@\n from pandas.compat.numpy import function as nv\n from pandas.errors import Pandas4Warning\n from pandas.util._decorators import (\n- doc,\n set_module,\n )\n from pandas.util._exceptions import find_stack_level\n@@ -429,8 +428,24 @@ def _logical_method(self, other, op):\n return op(other, self.astype(bool))\n return NotImplemented\n \n- [USER_REDACTED](ExtensionArray.tolist)\n def tolist(self) -> list:\n+ \"\"\"\n+ Return a list of the value.\n+\n+ These are each a scalar type, which is a Python scalar\n+ (for str, int, float) or pandas scalar\n+ (for Timestamp/Timedelta/Interval/Period)\n+\n+ Returns\n+ ----------\n+ list\n+\n+ Examples\n+ ----------\n+ >>> arr = pd.array([\"a\", \"b\", \"c\"])\n+ >>> arr.tolist()\n+ ['a', 'b', 'c']\n+ \"\"\"\n if self.ndim > 1:\n return [x.tolist() for x in self]\n return list(self.to_numpy())\n@@ -1076,13 +1091,56 @@ def memory_usage(self, deep: bool = False) -> int:\n return result + lib.memory_usage_of_objects(self._ndarray)\n return result\n \n- [USER_REDACTED](ExtensionArray.searchsorted)\n def searchsorted(\n self,\n value: NumpyValueArrayLike | ExtensionArray,\n side: Literal[\"left\", \"right\"] = \"left\",\n sorter: NumpySorter | None = None,\n ) -> npt.NDArray[np.intp] | np.intp:\n+ \"\"\"\n+ Find indices where elements should be inserted to maintain order.\n+\n+ Find the indices into a sorted array `self` (a) such that, if the\n+ corresponding elements in `value` were inserted before the indices,\n+ the order of `self` would be preserved.\n+\n+ Assuming that `self` is sorted:\n+\n+ ====== ================================\n+ `side` returned index `i` satisfies\n+ ====== ================================\n+ left ``self[i-1] < value <= self[i]``\n+ right ``self[i-1] <= value < self[i]``\n+ ====== ================================\n+\n+ Parameters\n+ ----------\n+ value : array-like, list or scalar\n+ Value(s) to insert into `self`.\n+ side : {'left', 'right'}, optional\n+ If 'left', the index of the first suitable location found is given.\n+ If 'right', return the last such index. If there is no suitable\n+ index, return either 0 or N (where N is the length of `self`).\n+ sorter : 1-D array-like, optional\n+ Optional array of integer indices that sort array a into ascending\n+ order. They are typically the result of argsort.\n+\n+ Returns\n+ -------\n+ array of ints or int\n+ If value is array-like, array of insertion points.\n+ If value is scalar, a single integer.\n+\n+ See Also\n+ --------\n+ numpy.searchsorted : Similar method from NumPy.\n+\n+ Examples\n+ --------\n+ >>> arr = pd.array([1, 2, 3, 5])\n+ >>> arr.searchsorted([4])\n+ array([3])\n+ \"\"\"\n if self._hasna:\n raise ValueError(\n \"searchsorted requires array to be sorted, which is impossible \"" } ], "reviews": [ { "id": 3631951462, "user": "user_c9260bc45a59", "state": "CHANGES_REQUESTED", "body": null, "submitted_at": "2026-01-06T18:13:45+00:00" }, { "id": 3632702257, "user": "user_c9260bc45a59", "state": "APPROVED", "body": null, "submitted_at": "2026-01-06T22:12:37+00:00" } ], "review_comments": [ { "id": 2665819568, "user": "user_c9260bc45a59", "body": "Can you change this example to show string data?", "path": "pandas/core/arrays/string_.py", "line": null, "side": "RIGHT", "created_at": "2026-01-06T18:13:33+00:00" }, { "id": 2665820290, "user": "user_c9260bc45a59", "body": "Can you change this example to show string data?", "path": "pandas/core/arrays/string_.py", "line": 1142, "side": "RIGHT", "created_at": "2026-01-06T18:13:42+00:00" } ], "meta": { "languages": [ "py" ], "touches_tests": false, "review_state_summary": { "CHANGES_REQUESTED": 1, "APPROVED": 1 }, "meaningful_comment_count": 2, "has_approval": true, "has_changes_requested": true, "total_review_comments": 2 } } { "_id": "fcd72c4c23caab2d", "_schema_version": "1.0", "_cleaned_at": "2026-02-12T07:46:51.876262+00:00", "repo": "pandas-dev/pandas", "repo_url": "https://github.com/pandas-dev/pandas", "license_name": "BSD 3-Clause \"New\" or \"Revised\" License", "license_spdx": "BSD-3-Clause", "pr_number": 63576, "title": "BUG: setitem with list of NaT", "body": "- [x] closes #63420 (Replace xxxx with the GitHub issue number)\n- [x] [Tests added and passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#writing-tests) if fixing a bug or adding a new feature\n- [ ] All [code checks passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit).\n- [ ] Added [type annotations](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#type-hints) to new arguments/methods/functions.\n- [ ] Added an entry in the latest `doc/source/whatsnew/vX.X.X.rst` file if fixing a bug or adding a new feature.\n- [ ] If I used AI to develop this pull request, I prompted it to follow `AGENTS.md`.", "author": "user_fb5fa0a10142", "created_at": "2026-01-05T16:02:43+00:00", "merged_at": "2026-01-05T22:28:11+00:00", "base_branch": "main", "head_branch": "bug-63420", "additions": 29, "deletions": 6, "changed_files": 4, "files": [ { "filename": "pandas/core/arrays/datetimelike.py", "status": "modified", "additions": 8, "deletions": 0, "changes": 8, "patch": "@@ -691,6 +691,14 @@ def _validate_listlike(self, value, allow_object: bool = False):\n msg = self._validation_error_message(value, True)\n raise TypeError(msg) from err\n \n+ if isinstance(value, list):\n+ value = construct_1d_object_array_from_listlike(value)\n+ if isinstance(value, np.ndarray) and value.dtype == object:\n+ # We need to call maybe_convert_objects here instead of in pd_array\n+ # so we can specify dtype_if_all_nat.\n+ value = lib.maybe_convert_objects(\n+ value, convert_non_numeric=True, dtype_if_all_nat=self.dtype\n+ )\n # Do type inference if necessary up front (after unpacking\n # NumpyExtensionArray)\n # e.g. we passed PeriodIndex.values and got an ndarray of Periods" }, { "filename": "pandas/core/construction.py", "status": "modified", "additions": 1, "deletions": 1, "changes": 2, "patch": "@@ -334,7 +334,7 @@ def array(\n ensure_object(data),\n convert_non_numeric=True,\n convert_to_nullable_dtype=True,\n- dtype_if_all_nat=None,\n+ dtype_if_all_nat=np.dtype(\"M8[s]\"),\n )\n result = ensure_wrapped_if_datetimelike(result)\n if isinstance(result, np.ndarray):" }, { "filename": "pandas/tests/arrays/test_array.py", "status": "modified", "additions": 5, "deletions": 0, "changes": 5, "patch": "@@ -134,6 +134,11 @@ def test_dt64_array(dtype_unit):\n np.dtype(\"datetime64[ns]\"),\n DatetimeArray._from_sequence([\"2000\", \"2001\"], dtype=\"M8[ns]\"),\n ),\n+ (\n+ [pd.NaT, pd.NaT],\n+ None,\n+ DatetimeArray._from_sequence([pd.NaT, pd.NaT], dtype=\"M8[s]\"),\n+ ),\n # Datetime (tz-aware)\n (\n [\"2000\", \"2001\"]," }, { "filename": "pandas/tests/arrays/test_datetimelike.py", "status": "modified", "additions": 15, "deletions": 5, "changes": 20, "patch": "@@ -301,7 +301,9 @@ def test_searchsorted(self):\n assert result == 10\n \n [USER_REDACTED].mark.parametrize(\"box\", [None, \"index\", \"series\"])\n- def test_searchsorted_castable_strings(self, arr1d, box, string_storage):\n+ def test_searchsorted_castable_strings(\n+ self, arr1d, box, string_storage, using_infer_string\n+ ):\n arr = arr1d\n if box is None:\n pass\n@@ -332,13 +334,16 @@ def test_searchsorted_castable_strings(self, arr1d, box, string_storage):\n ):\n arr.searchsorted(\"foo\")\n \n+ msg = re.escape(\n+ f\"value should be a '{arr1d._scalar_type.__name__}', 'NaT', \"\n+ \"or array of those. Got str array instead.\"\n+ )\n+ if not using_infer_string:\n+ msg = msg.replace(\"str\", \"string\")\n with pd.option_context(\"string_storage\", string_storage):\n with pytest.raises(\n TypeError,\n- match=re.escape(\n- f\"value should be a '{arr1d._scalar_type.__name__}', 'NaT', \"\n- \"or array of those. Got string array instead.\"\n- ),\n+ match=msg,\n ):\n arr.searchsorted([str(arr[1]), \"baz\"])\n \n@@ -433,6 +438,11 @@ def test_setitem(self):\n expected[:2] = expected[-2:]\n tm.assert_numpy_array_equal(arr.asi8, expected)\n \n+ def test_setitem_list_of_nats(self, arr1d):\n+ # GH#63420\n+ arr1d[:] = [NaT] * len(arr1d)\n+ assert arr1d.isna().all()\n+\n [USER_REDACTED].mark.parametrize(\n \"box\",\n [" } ], "reviews": [ { "id": 3628078367, "user": "user_c9260bc45a59", "state": "COMMENTED", "body": null, "submitted_at": "2026-01-05T19:01:58+00:00" }, { "id": 3628563337, "user": "user_fb5fa0a10142", "state": "COMMENTED", "body": null, "submitted_at": "2026-01-05T22:02:13+00:00" }, { "id": 3628618344, "user": "user_c9260bc45a59", "state": "APPROVED", "body": null, "submitted_at": "2026-01-05T22:27:55+00:00" } ], "review_comments": [ { "id": 2662511820, "user": "user_c9260bc45a59", "body": "Could absorb the `if isinstance(value, list) and len(value) == 0` branch above here as well.\n\nAlso do we need to be concerned about any other non-ndarray iterable here e.g. tuple?", "path": "pandas/core/arrays/datetimelike.py", "line": 694, "side": "RIGHT", "created_at": "2026-01-05T19:01:58+00:00" }, { "id": 2662927061, "user": "user_fb5fa0a10142", "body": "we could group them together, but i think we still need separate clauses.\n\ncould handle tuples, but i think in general we should move toward being stricter about what we allow, so prefer not to unless it causes problems", "path": "pandas/core/arrays/datetimelike.py", "line": 694, "side": "RIGHT", "created_at": "2026-01-05T22:02:13+00:00" } ], "meta": { "languages": [ "py" ], "touches_tests": true, "review_state_summary": { "COMMENTED": 2, "APPROVED": 1 }, "meaningful_comment_count": 2, "has_approval": true, "has_changes_requested": false, "total_review_comments": 2 } } { "_id": "821ba0d455450b53", "_schema_version": "1.0", "_cleaned_at": "2026-02-12T07:46:51.876262+00:00", "repo": "pandas-dev/pandas", "repo_url": "https://github.com/pandas-dev/pandas", "license_name": "BSD 3-Clause \"New\" or \"Revised\" License", "license_spdx": "BSD-3-Clause", "pr_number": 63571, "title": "DOC: inline docstring in CalamineReader", "body": "- [ ] xref #62437 \n- [ ] [Tests added and passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#writing-tests) if fixing a bug or adding a new feature\n- [ ] All [code checks passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit).\n- [ ] Added [type annotations](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#type-hints) to new arguments/methods/functions.\n- [ ] Added an entry in the latest `doc/source/whatsnew/vX.X.X.rst` file if fixing a bug or adding a new feature.\n- [ ] If I used AI to develop this pull request, I prompted it to follow `AGENTS.md`.\n\nReplaced `[USER_REDACTED]` decorator with hardcoded docstrings in `pandas/io/excel/_calamine.py`:\n- **CalamineReader.__init__**: Inlined `storage_options` docstring and removed the `[USER_REDACTED]` decorator.\n- Removed unused imports (`doc`, `_shared_docs`).", "author": "user_8420f83cc0b8", "created_at": "2026-01-04T15:03:48+00:00", "merged_at": "2026-01-06T17:47:36+00:00", "base_branch": "main", "head_branch": "inline-calamine-doc", "additions": 9, "deletions": 5, "changed_files": 1, "files": [ { "filename": "pandas/io/excel/_calamine.py", "status": "modified", "additions": 9, "deletions": 5, "changes": 14, "patch": "@@ -13,9 +13,6 @@\n )\n \n from pandas.compat._optional import import_optional_dependency\n-from pandas.util._decorators import doc\n-\n-from pandas.core.shared_docs import _shared_docs\n \n from pandas.io.excel._base import BaseExcelReader\n \n@@ -37,7 +34,6 @@\n \n \n class CalamineReader(BaseExcelReader[\"CalamineWorkbook\"]):\n- [USER_REDACTED](storage_options=_shared_docs[\"storage_options\"])\n def __init__(\n self,\n filepath_or_buffer: FilePath | ReadBuffer[bytes],\n@@ -51,7 +47,15 @@ def __init__(\n ----------\n filepath_or_buffer : str, path to be parsed or\n an open readable stream.\n- {storage_options}\n+ storage_options : dict, optional\n+ Extra options that make sense for a particular storage connection, e.g.\n+ host, port, username, password, etc. For HTTP(S) URLs the key-value pairs\n+ are forwarded to ``urllib.request.Request`` as header options. For other\n+ URLs (e.g. starting with \"s3://\", and \"gcs://\") the key-value pairs are\n+ forwarded to ``fsspec.open``. Please see ``fsspec`` and ``urllib`` for more\n+ details, and for more examples on storage options refer `here\n+ `_.\n engine_kwargs : dict, optional\n Arbitrary keyword arguments passed to excel engine.\n \"\"\"" } ], "reviews": [ { "id": 3627904506, "user": "user_c9260bc45a59", "state": "CHANGES_REQUESTED", "body": null, "submitted_at": "2026-01-05T18:01:15+00:00" }, { "id": 3629217975, "user": "user_8420f83cc0b8", "state": "COMMENTED", "body": null, "submitted_at": "2026-01-06T03:33:02+00:00" }, { "id": 3631863335, "user": "user_c9260bc45a59", "state": "APPROVED", "body": null, "submitted_at": "2026-01-06T17:47:26+00:00" } ], "review_comments": [ { "id": 2662364184, "user": "user_c9260bc45a59", "body": "Can you indent this entire description?", "path": "pandas/io/excel/_calamine.py", "line": null, "side": "RIGHT", "created_at": "2026-01-05T18:01:10+00:00" }, { "id": 2663470651, "user": "user_8420f83cc0b8", "body": "Thanks for the review! I've updated the indentation as requested.", "path": "pandas/io/excel/_calamine.py", "line": null, "side": "RIGHT", "created_at": "2026-01-06T03:33:02+00:00" } ], "meta": { "languages": [ "py" ], "touches_tests": false, "review_state_summary": { "CHANGES_REQUESTED": 1, "COMMENTED": 1, "APPROVED": 1 }, "meaningful_comment_count": 2, "has_approval": true, "has_changes_requested": true, "total_review_comments": 2 } } { "_id": "620094fd9e81fcc8", "_schema_version": "1.0", "_cleaned_at": "2026-02-12T07:46:51.876262+00:00", "repo": "pandas-dev/pandas", "repo_url": "https://github.com/pandas-dev/pandas", "license_name": "BSD 3-Clause \"New\" or \"Revised\" License", "license_spdx": "BSD-3-Clause", "pr_number": 63560, "title": "BUG: Arrow-backed duration/timestamp reductions return stdlib types for non-nanosecond units", "body": "- [x] closes #63170 \n- [x] [Tests added and passed] if fixing a bug or adding a new feature\n- [x] All [code checks passed].\n- [ ] Added [type annotations] to new arguments/methods/functions.\n- [x] Added an entry in the latest `doc/source/whatsnew/v3.0.0.rst` file if fixing a bug or adding a new feature.\n- [ ] If I used AI to develop this pull request, I prompted it to follow `AGENTS.md`.\n\nPreviously, reduction operations (`sum`, `min`, `max`, `mean`, `median`) on Arrow-backed duration and timestamp arrays returned inconsistent scalar types depending on unit resolution. PyArrow's `as_py()` returns `pd.Timedelta/pd.Timestamp` for nanosecond data but stdlib `datetime.timedelta/datetime.datetime` for microsecond, millisecond, and second resolutions.\nThis change adds explicit wrapping in `_reduce_calc` for duration and timestamp results, using the pattern already established for[`__getitem__`](https://github.com/[USER_REDACTED]ndas-dev/pandas/blob/91514c363604506f447e53380d3aa00520f1037b/pandas/core/arrays/arrow/array.py#L807-L814) and [`__iter__`](https://github.com/[USER_REDACTED]ndas-dev/pandas/blob/91514c363604506f447e53380d3aa00520f1037b/pandas/core/arrays/arrow/array.py#L823-L834). This ensures these reductions consistently return pandas scalar types while preserving the original unit resolution via `.as_unit()`.", "author": "user_a39d3009d8b1", "created_at": "2026-01-03T13:55:42+00:00", "merged_at": "2026-01-05T19:39:10+00:00", "base_branch": "main", "head_branch": "fix-arrow-duration-unit-consistency", "additions": 32, "deletions": 1, "changed_files": 3, "files": [ { "filename": "doc/source/whatsnew/v3.0.0.rst", "status": "modified", "additions": 1, "deletions": 0, "changes": 1, "patch": "@@ -1401,6 +1401,7 @@ ExtensionArray\n - Bug in :meth:`ArrowExtensionArray.factorize` where NA values were dropped when input was dictionary-encoded even when dropna was set to False(:issue:`60567`)\n - Bug in :meth:`NDArrayBackedExtensionArray.take` which produced arrays whose dtypes didn't match their underlying data, when called with integer arrays (:issue:`62448`)\n - Bug in :meth:`api.types.is_datetime64_any_dtype` where a custom :class:`ExtensionDtype` would return ``False`` for array-likes (:issue:`57055`)\n+- Bug in Arrow-backed duration and timestamp reductions (e.g. ``sum``, ``min``, ``max``, ``median``, ``mean``) incorrectly returning stdlib ``datetime`` objects instead of :class:`Timedelta` and :class:`Timestamp` for resolutions other than nanoseconds (:issue:`63170`)\n - Bug in comparison between object with :class:`ArrowDtype` and incompatible-dtyped (e.g. string vs bool) incorrectly raising instead of returning all-``False`` (for ``==``) or all-``True`` (for ``!=``) (:issue:`59505`)\n - Bug in constructing pandas data structures when passing into ``dtype`` a string of the type followed by ``[pyarrow]`` while PyArrow is not installed would raise ``NameError`` rather than ``ImportError`` (:issue:`57928`)\n - Bug in various :class:`DataFrame` reductions for pyarrow temporal dtypes returning incorrect dtype when result was null (:issue:`59234`)" }, { "filename": "pandas/core/arrays/arrow/array.py", "status": "modified", "additions": 7, "deletions": 1, "changes": 8, "patch": "@@ -2152,7 +2152,13 @@ def _reduce_calc(\n if pc.is_null(pa_result).as_py():\n return self.dtype.na_value\n elif isinstance(pa_result, pa.Scalar):\n- return pa_result.as_py()\n+ result = pa_result.as_py()\n+ pa_type = pa_result.type\n+ if pa.types.is_duration(pa_type) and pa_type.unit != \"ns\":\n+ return Timedelta(result).as_unit(pa_type.unit)\n+ elif pa.types.is_timestamp(pa_type) and pa_type.unit != \"ns\":\n+ return Timestamp(result).as_unit(pa_type.unit)\n+ return result\n else:\n return pa_result" }, { "filename": "pandas/tests/extension/test_arrow.py", "status": "modified", "additions": 24, "deletions": 0, "changes": 24, "patch": "@@ -3817,3 +3817,27 @@ def test_ufunc_retains_missing():\n \n expected = pd.Series([np.sin(0.1), pd.NA], dtype=\"float64[pyarrow]\")\n tm.assert_series_equal(result, expected)\n+\n+\n+[USER_REDACTED].mark.parametrize(\"method\", [\"sum\", \"min\", \"max\", \"mean\", \"median\"])\n+def test_duration_reduction_consistency(unit, method):\n+ # GH#63170\n+ dtype = f\"duration[{unit}][pyarrow]\"\n+ ser = pd.Series([timedelta(seconds=1), timedelta(seconds=2)], dtype=dtype)\n+ result = getattr(ser, method)()\n+ assert isinstance(result, pd.Timedelta), (\n+ f\"{method} for {unit} returned {type(result)}\"\n+ )\n+ assert result.unit == unit\n+\n+\n+[USER_REDACTED].mark.parametrize(\"method\", [\"min\", \"max\", \"median\"])\n+def test_timestamp_reduction_consistency(unit, method):\n+ # GH#63170\n+ dtype = f\"timestamp[{unit}][pyarrow]\"\n+ ser = pd.Series([datetime(2024, 1, 1), datetime(2024, 1, 3)], dtype=dtype)\n+ result = getattr(ser, method)()\n+ assert isinstance(result, pd.Timestamp), (\n+ f\"{method} for {unit} returned {type(result)}\"\n+ )\n+ assert result.unit == unit" } ], "reviews": [ { "id": 3627949533, "user": "user_c9260bc45a59", "state": "CHANGES_REQUESTED", "body": null, "submitted_at": "2026-01-05T18:17:10+00:00" }, { "id": 3628181104, "user": "user_c9260bc45a59", "state": "APPROVED", "body": null, "submitted_at": "2026-01-05T19:38:36+00:00" } ], "review_comments": [ { "id": 2662402073, "user": "user_c9260bc45a59", "body": "You can use the `unit` fixture", "path": "pandas/tests/extension/test_arrow.py", "line": null, "side": "RIGHT", "created_at": "2026-01-05T18:16:38+00:00" }, { "id": 2662403294, "user": "user_c9260bc45a59", "body": "Can you use `pytest.mark.parametrize` over the reduction methods (same as below)?", "path": "pandas/tests/extension/test_arrow.py", "line": null, "side": "RIGHT", "created_at": "2026-01-05T18:17:06+00:00" } ], "meta": { "languages": [ "py", "rst" ], "touches_tests": true, "review_state_summary": { "CHANGES_REQUESTED": 1, "APPROVED": 1 }, "meaningful_comment_count": 2, "has_approval": true, "has_changes_requested": true, "total_review_comments": 2 } } { "_id": "d21837a4a963d2f5", "_schema_version": "1.0", "_cleaned_at": "2026-02-12T07:46:51.893036+00:00", "repo": "pandas-dev/pandas", "repo_url": "https://github.com/pandas-dev/pandas", "license_name": "BSD 3-Clause \"New\" or \"Revised\" License", "license_spdx": "BSD-3-Clause", "pr_number": 63552, "title": "DOC: Inline docstrings of a batch of functions in `pandas/core/generic.py`", "body": "- [ ] xref #62437 (Replace xxxx with the GitHub issue number)\n- [ ] [Tests added and passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#writing-tests) if fixing a bug or adding a new feature\n- [x] All [code checks passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit).\n- [ ] Added [type annotations](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#type-hints) to new arguments/methods/functions.\n- [ ] Added an entry in the latest `doc/source/whatsnew/vX.X.X.rst` file if fixing a bug or adding a new feature.\n- [ ] If I used AI to develop this pull request, I prompted it to follow `AGENTS.md`.", "author": "user_5b0b62fe7839", "created_at": "2026-01-03T03:21:14+00:00", "merged_at": "2026-01-06T02:53:38+00:00", "base_branch": "main", "head_branch": "inline_generic", "additions": 110, "deletions": 77, "changed_files": 1, "files": [ { "filename": "pandas/core/generic.py", "status": "modified", "additions": 110, "deletions": 77, "changes": 187, "patch": "@@ -188,8 +188,8 @@\n from pandas.io.formats.printing import pprint_thing\n \n if TYPE_CHECKING:\n- from collections.abc import Callable\n from collections.abc import (\n+ Callable,\n Hashable,\n Iterator,\n Mapping,\n@@ -208,7 +208,6 @@\n from pandas.core.indexers.objects import BaseIndexer\n from pandas.core.resample import Resampler\n \n-import textwrap\n \n # goal is to be able to define the docs close to function, while still being\n # able to share\n@@ -767,10 +766,9 @@ def _set_axis(self, axis: AxisInt, labels: AnyArrayLike | list) -> None:\n self._mgr.set_axis(axis, labels)\n \n [USER_REDACTED]\n- [USER_REDACTED](klass=_shared_doc_kwargs[\"klass\"])\n def droplevel(self, level: IndexLabel, axis: Axis = 0) -> Self:\n \"\"\"\n- Return {klass} with requested index / column level(s) removed.\n+ [NAME_REDACTED]/DataFrame with requested index / column level(s) removed.\n \n Parameters\n ----------\n@@ -789,8 +787,8 @@ def droplevel(self, level: IndexLabel, axis: Axis = 0) -> Self:\n \n Returns\n -------\n- {klass}\n- {klass} with requested index / column level(s) removed.\n+ Series/DataFrame\n+ Series/DataFrame with requested index / column level(s) removed.\n \n See Also\n --------\n@@ -2150,19 +2148,6 @@ def _repr_data_resource_(self):\n # I/O Methods\n \n [USER_REDACTED]\n- [USER_REDACTED](\n- klass=\"object\",\n- storage_options=_shared_docs[\"storage_options\"],\n- storage_options_versionadded=\"1.2.0\",\n- encoding_parameter=\"\",\n- verbose_parameter=\"\",\n- extra_parameters=textwrap.dedent(\n- \"\"\"\\\n- engine_kwargs : dict, optional\n- Arbitrary keyword arguments passed to excel engine.\n- \"\"\"\n- ),\n- )\n def to_excel(\n self,\n excel_writer: FilePath | WriteExcelBuffer | ExcelWriter,\n@@ -2185,9 +2170,9 @@ def to_excel(\n autofilter: bool = False,\n ) -> None:\n \"\"\"\n- Write {klass} to an Excel sheet.\n+ Write object to an Excel sheet.\n \n- To write a single {klass} to an Excel .xlsx file it is only necessary to\n+ To write a single object to an Excel .xlsx file it is only necessary to\n specify a target file name. To write to multiple sheets it is necessary to\n create an `ExcelWriter` object with a target file name, and specify a sheet\n in the file to write to.\n@@ -2227,22 +2212,27 @@ def to_excel(\n Write engine to use, 'openpyxl' or 'xlsxwriter'. You can also set this\n via the options ``io.excel.xlsx.writer`` or\n ``io.excel.xlsm.writer``.\n-\n merge_cells : bool or 'columns', default False\n If True, write MultiIndex index and columns as merged cells.\n If 'columns', merge MultiIndex column cells only.\n- {encoding_parameter}\n inf_rep : str, default 'inf'\n Representation for infinity (there is no native representation for\n infinity in Excel).\n- {verbose_parameter}\n freeze_panes : tuple of int (length 2), optional\n Specifies the one-based bottommost row and rightmost column that\n is to be frozen.\n- {storage_options}\n+ storage_options : dict, optional\n+ Extra options that make sense for a particular storage connection, e.g.\n+ host, port, username, password, etc. For HTTP(S) URLs the key-value pairs\n+ are forwarded to ``urllib.request.Request`` as header options. For other\n+ URLs (e.g. starting with \"s3://\", and \"gcs://\") the key-value pairs are\n+ forwarded to ``fsspec.open``. Please see ``fsspec`` and ``urllib`` for more\n+ details, and for more examples on storage options refer `here\n+ `_.\n \n- .. versionadded:: {storage_options_versionadded}\n- {extra_parameters}\n+ engine_kwargs : dict, optional\n+ Arbitrary keyword arguments passed to excel engine.\n autofilter : bool, default False\n If True, add automatic filters to all columns.\n \n@@ -2332,10 +2322,6 @@ def to_excel(\n )\n \n [USER_REDACTED]\n- [USER_REDACTED](\n- storage_options=_shared_docs[\"storage_options\"],\n- compression_options=_shared_docs[\"compression_options\"] % \"path_or_buf\",\n- )\n def to_json(\n self,\n path_or_buf: FilePath | WriteBuffer[bytes] | WriteBuffer[str] | None = None,\n@@ -2420,7 +2406,23 @@ def to_json(\n If 'orient' is 'records' write out line-delimited json format. Will\n throw ValueError if incorrect 'orient' since others are not\n list-like.\n- {compression_options}\n+\n+ compression : str or dict, default 'infer'\n+ For on-the-fly compression of the output data. If 'infer' and\n+ 'path_or_buf' is path-like, then detect compression from the following\n+ extensions: '.gz',\n+ '.bz2', '.zip', '.xz', '.zst', '.tar', '.tar.gz', '.tar.xz' or '.tar.bz2'\n+ (otherwise no compression).\n+ Set to ``None`` for no compression.\n+ Can also be a dict with key ``'method'`` set to one of\n+ {``'zip'``, ``'gzip'``, ``'bz2'``, ``'zstd'``, ``'xz'``, ``'tar'``} and\n+ other key-value pairs are forwarded to\n+ ``zipfile.ZipFile``, ``gzip.GzipFile``,\n+ ``bz2.BZ2File``, ``zstandard.ZstdCompressor``, ``lzma.LZMAFile`` or\n+ ``tarfile.TarFile``, respectively.\n+ As an example, the following could be passed for faster compression and\n+ to create a reproducible gzip archive:\n+ ``compression={'method': 'gzip', 'compresslevel': 1, 'mtime': 1}``.\n \n index : bool or None, default None\n The index is only used when 'orient' is 'split', 'index', 'column',\n@@ -2431,7 +2433,15 @@ def to_json(\n indent : int, optional\n Length of whitespace used to indent each record.\n \n- {storage_options}\n+ storage_options : dict, optional\n+ Extra options that make sense for a particular storage connection, e.g.\n+ host, port, username, password, etc. For HTTP(S) URLs the key-value pairs\n+ are forwarded to ``urllib.request.Request`` as header options. For other\n+ URLs (e.g. starting with \"s3://\", and \"gcs://\") the key-value pairs are\n+ forwarded to ``fsspec.open``. Please see ``fsspec`` and ``urllib`` for more\n+ details, and for more examples on storage options refer `here\n+ `_.\n \n mode : str, default 'w' (writing)\n Specify the IO mode for output when supplying a path_or_buf.\n@@ -3054,10 +3064,6 @@ def to_sql(\n )\n \n [USER_REDACTED]\n- [USER_REDACTED](\n- storage_options=_shared_docs[\"storage_options\"],\n- compression_options=_shared_docs[\"compression_options\"] % \"path\",\n- )\n def to_pickle(\n self,\n path: FilePath | WriteBuffer[bytes],\n@@ -3075,7 +3081,24 @@ def to_pickle(\n String, path object (implementing ``os.PathLike[str]``), or file-like\n object implementing a binary ``write()`` function. File path where\n the pickled object will be stored.\n- {compression_options}\n+\n+ compression : str or dict, default 'infer'\n+ For on-the-fly compression of the output data. If 'infer' and\n+ 'path_or_buf' is path-like, then detect compression from the following\n+ extensions: '.gz',\n+ '.bz2', '.zip', '.xz', '.zst', '.tar', '.tar.gz', '.tar.xz' or '.tar.bz2'\n+ (otherwise no compression).\n+ Set to ``None`` for no compression.\n+ Can also be a dict with key ``'method'`` set to one of\n+ {``'zip'``, ``'gzip'``, ``'bz2'``, ``'zstd'``, ``'xz'``, ``'tar'``} and\n+ other key-value pairs are forwarded to\n+ ``zipfile.ZipFile``, ``gzip.GzipFile``,\n+ ``bz2.BZ2File``, ``zstandard.ZstdCompressor``, ``lzma.LZMAFile`` or\n+ ``tarfile.TarFile``, respectively.\n+ As an example, the following could be passed for faster compression and\n+ to create a reproducible gzip archive:\n+ ``compression={'method': 'gzip', 'compresslevel': 1, 'mtime': 1}``.\n+\n protocol : int\n Int which indicates which protocol should be used by [NAME_REDACTED],\n default HIGHEST_PROTOCOL (see [1]_ paragraph 12.1.2). The possible\n@@ -3084,7 +3107,15 @@ def to_pickle(\n \n .. [1] https://docs.python.org/3/library/pickle.html.\n \n- {storage_options}\n+ storage_options : dict, optional\n+ Extra options that make sense for a particular storage connection, e.g.\n+ host, port, username, password, etc. For HTTP(S) URLs the key-value pairs\n+ are forwarded to ``urllib.request.Request`` as header options. For other\n+ URLs (e.g. starting with \"s3://\", and \"gcs://\") the key-value pairs are\n+ forwarded to ``fsspec.open``. Please see ``fsspec`` and ``urllib`` for more\n+ details, and for more examples on storage options refer `here\n+ `_.\n \n See Also\n --------\n@@ -3763,10 +3794,6 @@ def to_csv(\n ) -> None: ...\n \n [USER_REDACTED]\n- [USER_REDACTED](\n- storage_options=_shared_docs[\"storage_options\"],\n- compression_options=_shared_docs[\"compression_options\"] % \"path_or_buf\",\n- )\n def to_csv(\n self,\n path_or_buf: FilePath | WriteBuffer[bytes] | WriteBuffer[str] | None = None,\n@@ -3835,7 +3862,23 @@ def to_csv(\n A string representing the encoding to use in the output file,\n defaults to 'utf-8'. `encoding` is not supported if `path_or_buf`\n is a non-binary file object.\n- {compression_options}\n+\n+ compression : str or dict, default 'infer'\n+ For on-the-fly compression of the output data. If 'infer' and\n+ 'path_or_buf' is path-like, then detect compression from the following\n+ extensions: '.gz',\n+ '.bz2', '.zip', '.xz', '.zst', '.tar', '.tar.gz', '.tar.xz' or '.tar.bz2'\n+ (otherwise no compression).\n+ Set to ``None`` for no compression.\n+ Can also be a dict with key ``'method'`` set to one of\n+ {``'zip'``, ``'gzip'``, ``'bz2'``, ``'zstd'``, ``'xz'``, ``'tar'``} and\n+ other key-value pairs are forwarded to\n+ ``zipfile.ZipFile``, ``gzip.GzipFile``,\n+ ``bz2.BZ2File``, ``zstandard.ZstdCompressor``, ``lzma.LZMAFile`` or\n+ ``tarfile.TarFile``, respectively.\n+ As an example, the following could be passed for faster compression and\n+ to create a reproducible gzip archive:\n+ ``compression={'method': 'gzip', 'compresslevel': 1, 'mtime': 1}``.\n \n May be a dict with key 'method' as compression mode\n and other entries as additional compression options if\n@@ -3870,7 +3913,15 @@ def to_csv(\n See the errors argument for :func:`open` for a full list\n of options.\n \n- {storage_options}\n+ storage_options : dict, optional\n+ Extra options that make sense for a particular storage connection, e.g.\n+ host, port, username, password, etc. For HTTP(S) URLs the key-value pairs\n+ are forwarded to ``urllib.request.Request`` as header options. For other\n+ URLs (e.g. starting with \"s3://\", and \"gcs://\") the key-value pairs are\n+ forwarded to ``fsspec.open``. Please see ``fsspec`` and ``urllib`` for more\n+ details, and for more examples on storage options refer `here\n+ `_.\n \n Returns\n -------\n@@ -5148,10 +5199,6 @@ def sort_index(\n else:\n return result.__finalize__(self, method=\"sort_index\")\n \n- [USER_REDACTED](\n- klass=_shared_doc_kwargs[\"klass\"],\n- optional_reindex=\"\",\n- )\n def reindex(\n self,\n labels=None,\n@@ -5167,15 +5214,14 @@ def reindex(\n tolerance=None,\n ) -> Self:\n \"\"\"\n- Conform {klass} to new index with optional filling logic.\n+ [NAME_REDACTED]/DataFrame to new index with optional filling logic.\n \n Places NA/NaN in locations having no value in the previous index. A new object\n is produced unless the new index is equivalent to the current one and\n ``copy=False``.\n \n Parameters\n ----------\n- {optional_reindex}\n method : {{None, 'backfill'/'bfill', 'pad'/'ffill', 'nearest'}}\n Method to use for filling holes in reindexed DataFrame.\n Please note: this is only applicable to DataFrames/Series with a\n@@ -5221,8 +5267,8 @@ def reindex(\n \n Returns\n -------\n- {klass}\n- {klass} with changed index.\n+ Series/DataFrame\n+ Series/DataFrame with changed index.\n \n See Also\n --------\n@@ -5318,7 +5364,7 @@ def reindex(\n \n >>> date_index = pd.date_range(\"1/1/2010\", periods=6, freq=\"D\")\n >>> df2 = pd.DataFrame(\n- ... {{\"prices\": [100, 101, np.nan, 100, 89, 88]}}, index=date_index\n+ ... {\"prices\": [100, 101, np.nan, 100, 89, 88]}, index=date_index\n ... )\n >>> df2\n prices\n@@ -5978,7 +6024,6 @@ def pipe(\n ) -> T: ...\n \n [USER_REDACTED]\n- [USER_REDACTED](klass=_shared_doc_kwargs[\"klass\"])\n def pipe(\n self,\n func: Callable[Concatenate[Self, P], T] | tuple[Callable[..., T], str],\n@@ -5991,11 +6036,11 @@ def pipe(\n Parameters\n ----------\n func : function\n- Function to apply to the {klass}.\n+ Function to apply to the Series/DataFrame.\n ``args``, and ``kwargs`` are passed into ``func``.\n Alternatively a ``(callable, data_keyword)`` tuple where\n ``data_keyword`` is a string indicating the keyword of\n- ``callable`` that expects the {klass}.\n+ ``callable`` that expects the Series/DataFrame.\n *args : iterable, optional\n Positional arguments passed into ``func``.\n **kwargs : mapping, optional\n@@ -6918,10 +6963,6 @@ def _pad_or_backfill(\n return result.__finalize__(self, method=\"fillna\")\n \n [USER_REDACTED]\n- [USER_REDACTED](\n- klass=_shared_doc_kwargs[\"klass\"],\n- axes_single_arg=_shared_doc_kwargs[\"axes_single_arg\"],\n- )\n def fillna(\n self,\n value: Hashable | Mapping | Series | DataFrame,\n@@ -6941,7 +6982,7 @@ def fillna(\n each index (for a Series) or column (for a DataFrame). Values not\n in the dict/Series/DataFrame will not be filled. This value cannot\n be a list.\n- axis : {axes_single_arg}\n+ axis : {0 or 'index'} for Series, {0 or 'index', 1 or 'columns'} for [NAME_REDACTED] along which to fill missing values. For `Series`\n this parameter is unused and defaults to 0.\n inplace : bool, default False\n@@ -6954,7 +6995,7 @@ def fillna(\n \n Returns\n -------\n- {klass}\n+ Series/[NAME_REDACTED] with missing values filled.\n \n See Also\n@@ -7001,7 +7042,7 @@ def fillna(\n Replace all NaN elements in column 'A', 'B', 'C', and 'D', with 0, 1,\n 2, and 3 respectively.\n \n- >>> values = {{\"A\": 0, \"B\": 1, \"C\": 2, \"D\": 3}}\n+ >>> values = {\"A\": 0, \"B\": 1, \"C\": 2, \"D\": 3}\n >>> df.fillna(value=values)\n A B C D\n 0 0.0 2.0 2.0 0.0\n@@ -7164,10 +7205,6 @@ def fillna(\n return result.__finalize__(self, method=\"fillna\")\n \n [USER_REDACTED]\n- [USER_REDACTED](\n- klass=_shared_doc_kwargs[\"klass\"],\n- axes_single_arg=_shared_doc_kwargs[\"axes_single_arg\"],\n- )\n def ffill(\n self,\n *,\n@@ -7181,7 +7218,7 @@ def ffill(\n \n Parameters\n ----------\n- axis : {axes_single_arg}\n+ axis : {0 or 'index'} for Series, {0 or 'index', 1 or 'columns'} for [NAME_REDACTED] along which to fill missing values. For `Series`\n this parameter is unused and defaults to 0.\n inplace : bool, default False\n@@ -7208,7 +7245,7 @@ def ffill(\n \n Returns\n -------\n- {klass}\n+ Series/[NAME_REDACTED] with missing values filled.\n \n See Also\n@@ -7270,10 +7307,6 @@ def ffill(\n )\n \n [USER_REDACTED]\n- [USER_REDACTED](\n- klass=_shared_doc_kwargs[\"klass\"],\n- axes_single_arg=_shared_doc_kwargs[\"axes_single_arg\"],\n- )\n def bfill(\n self,\n *,\n@@ -7287,7 +7320,7 @@ def bfill(\n \n Parameters\n ----------\n- axis : {axes_single_arg}\n+ axis : {0 or 'index'} for Series, {0 or 'index', 1 or 'columns'} for [NAME_REDACTED] along which to fill missing values. For `Series`\n this parameter is unused and defaults to 0.\n inplace : bool, default False\n@@ -7314,7 +7347,7 @@ def bfill(\n \n Returns\n -------\n- {klass}\n+ Series/[NAME_REDACTED] with missing values filled.\n \n See Also\n@@ -7342,7 +7375,7 @@ def bfill(\n \n With DataFrame:\n \n- >>> df = pd.DataFrame({{\"A\": [1, None, None, 4], \"B\": [None, 5, None, 7]}})\n+ >>> df = pd.DataFrame({\"A\": [1, None, None, 4], \"B\": [None, 5, None, 7]})\n >>> df\n A B\n 0 1.0\t NaN" } ], "reviews": [ { "id": 3627964313, "user": "user_c9260bc45a59", "state": "CHANGES_REQUESTED", "body": null, "submitted_at": "2026-01-05T18:22:00+00:00" }, { "id": 3629143281, "user": "user_c9260bc45a59", "state": "APPROVED", "body": null, "submitted_at": "2026-01-06T02:53:29+00:00" } ], "review_comments": [ { "id": 2662414640, "user": "user_c9260bc45a59", "body": "```suggestion\n```", "path": "pandas/core/generic.py", "line": null, "side": "RIGHT", "created_at": "2026-01-05T18:21:35+00:00" } ], "meta": { "languages": [ "py" ], "touches_tests": false, "review_state_summary": { "CHANGES_REQUESTED": 1, "APPROVED": 1 }, "meaningful_comment_count": 1, "has_approval": true, "has_changes_requested": true, "total_review_comments": 1 } } { "_id": "182b9dfaa35d47d9", "_schema_version": "1.0", "_cleaned_at": "2026-02-12T07:46:51.895866+00:00", "repo": "scikit-learn/scikit-learn", "repo_url": "https://github.com/scikit-learn/scikit-learn", "license_name": "BSD 3-Clause \"New\" or \"Revised\" License", "license_spdx": "BSD-3-Clause", "pr_number": 33223, "title": "TST Refactor out helper in `pos_label` display curve tests", "body": "#### [NAME_REDACTED]/PRs\nRelated to #33218 and https://github.com/[USER_REDACTED]n/scikit-learn/pull/33217\nPart of PRs to move test related changes out of #30508 and into separate PR\n\n#### What does this implement/fix? Explain your changes.\nTakes the common part of `test_plot_roc_curve_pos_label` (which is shared with `test_plot_precision_recall_pos_label`) out to a helper function in `test_common_curve_display.py`, to reduce duplication.\n\n#### AI usage disclosure\n\nI used AI assistance for:\n- [ ] Code generation (e.g., when writing an implementation or fixing a bug)\n- [ ] Test/benchmark generation\n- [ ] Documentation (including examples)\n- [ ] Research and understanding\n\n#### Any other comments?\n\ncc [USER_REDACTED] [USER_REDACTED] :pray:", "author": "user_d16337ec046b", "created_at": "2026-02-06T11:08:21+00:00", "merged_at": "2026-02-10T10:09:01+00:00", "base_branch": "main", "head_branch": "tst_pos_label_common_display", "additions": 115, "deletions": 102, "changed_files": 2, "files": [ { "filename": "sklearn/metrics/_plot/tests/test_common_curve_display.py", "status": "modified", "additions": 96, "deletions": 1, "changes": 97, "patch": "@@ -4,7 +4,7 @@\n from sklearn.base import BaseEstimator, ClassifierMixin, clone\n from sklearn.calibration import CalibrationDisplay\n from sklearn.compose import make_column_transformer\n-from sklearn.datasets import load_iris\n+from sklearn.datasets import load_breast_cancer, load_iris\n from sklearn.exceptions import NotFittedError\n from sklearn.linear_model import LogisticRegression\n from sklearn.metrics import (\n@@ -14,9 +14,11 @@\n PredictionErrorDisplay,\n RocCurveDisplay,\n )\n+from sklearn.model_selection import cross_validate, train_test_split\n from sklearn.pipeline import make_pipeline\n from sklearn.preprocessing import StandardScaler\n from sklearn.tree import DecisionTreeClassifier, DecisionTreeRegressor\n+from sklearn.utils import shuffle\n \n \n [USER_REDACTED].fixture(scope=\"module\")\n@@ -30,6 +32,99 @@ def data_binary(data):\n return X[y < 2], y[y < 2]\n \n \n+def _check_pos_label_statistics(\n+ display_class, response_method, constructor_name, check_metric\n+):\n+ \"\"\"Test switching `pos_label` gives correct statistics, using imbalanced data.\"\"\"\n+ X, y = load_breast_cancer(return_X_y=True)\n+ # create highly imbalanced classes\n+ idx_positive = np.flatnonzero(y == 1)\n+ idx_negative = np.flatnonzero(y == 0)\n+ idx_selected = np.hstack([idx_negative, idx_positive[:25]])\n+ X, y = X[idx_selected], y[idx_selected]\n+ X, y = shuffle(X, y, random_state=42)\n+ # only use 2 features to make the problem even harder\n+ X = X[:, :2]\n+ y = np.array([\"cancer\" if c == 1 else \"not cancer\" for c in y], dtype=object)\n+ X_train, X_test, y_train, y_test = train_test_split(\n+ X,\n+ y,\n+ stratify=y,\n+ random_state=0,\n+ )\n+\n+ classifier = LogisticRegression()\n+ classifier.fit(X_train, y_train)\n+ cv_results = cross_validate(\n+ LogisticRegression(), X, y, cv=3, return_estimator=True, return_indices=True\n+ )\n+\n+ # Sanity check to be sure the positive class is `classes_[0]`.\n+ # Class imbalance ensures a large difference in prediction values between classes,\n+ # allowing us to catch errors when we switch `pos_label`.\n+ assert classifier.classes_.tolist() == [\"cancer\", \"not cancer\"]\n+\n+ y_score = getattr(classifier, response_method)(X_test)\n+ # we select the corresponding probability columns or reverse the decision\n+ # function otherwise\n+ y_score_cancer = -1 * y_score if y_score.ndim == 1 else y_score[:, 0]\n+ y_score_not_cancer = y_score if y_score.ndim == 1 else y_score[:, 1]\n+\n+ pos_label = \"cancer\"\n+ y_score = y_score_cancer\n+ if constructor_name == \"from_estimator\":\n+ display = display_class.from_estimator(\n+ classifier,\n+ X_test,\n+ y_test,\n+ pos_label=pos_label,\n+ response_method=response_method,\n+ )\n+ elif constructor_name == \"from_predictions\":\n+ display = display_class.from_predictions(\n+ y_test,\n+ y_score,\n+ pos_label=pos_label,\n+ )\n+ else:\n+ display = display_class.from_cv_results(\n+ cv_results,\n+ X,\n+ y,\n+ response_method=response_method,\n+ pos_label=pos_label,\n+ )\n+\n+ check_metric(display, constructor_name, pos_label)\n+\n+ pos_label = \"not cancer\"\n+ y_score = y_score_not_cancer\n+ if constructor_name == \"from_estimator\":\n+ display = display_class.from_estimator(\n+ classifier,\n+ X_test,\n+ y_test,\n+ response_method=response_method,\n+ pos_label=pos_label,\n+ )\n+ elif constructor_name == \"from_predictions\":\n+ display = display_class.from_predictions(\n+ y_test,\n+ y_score,\n+ pos_label=pos_label,\n+ )\n+ else:\n+ display = display_class.from_cv_results(\n+ cv_results,\n+ X,\n+ y,\n+ response_method=response_method,\n+ pos_label=pos_label,\n+ )\n+\n+ check_metric(display, constructor_name, pos_label)\n+\n+\n [USER_REDACTED].mark.parametrize(\n \"Display\",\n [CalibrationDisplay, DetCurveDisplay, PrecisionRecallDisplay, RocCurveDisplay]," }, { "filename": "sklearn/metrics/_plot/tests/test_roc_curve_display.py", "status": "modified", "additions": 19, "deletions": 101, "changes": 120, "patch": "@@ -7,14 +7,17 @@\n \n from sklearn import clone\n from sklearn.compose import make_column_transformer\n-from sklearn.datasets import load_breast_cancer, make_classification\n+from sklearn.datasets import make_classification\n from sklearn.exceptions import NotFittedError, UndefinedMetricWarning\n from sklearn.linear_model import LogisticRegression\n from sklearn.metrics import RocCurveDisplay, auc, roc_curve\n-from sklearn.model_selection import cross_validate, train_test_split\n+from sklearn.metrics._plot.tests.test_common_curve_display import (\n+ _check_pos_label_statistics,\n+)\n+from sklearn.model_selection import cross_validate\n from sklearn.pipeline import make_pipeline\n from sklearn.preprocessing import StandardScaler\n-from sklearn.utils import _safe_indexing, shuffle\n+from sklearn.utils import _safe_indexing\n from sklearn.utils._response import _get_response_values_binary\n \n \n@@ -822,112 +825,27 @@ def test_roc_curve_display_default_labels(\n assert disp.line_[idx].get_label() == expected_label\n \n \n-def _check_auc(display, constructor_name):\n- roc_auc_limit = 0.95679\n- roc_auc_limit_multi = [0.97007, 0.985915, 0.980952]\n-\n- if constructor_name == \"from_cv_results\":\n- for idx, roc_auc in enumerate(display.roc_auc):\n- assert roc_auc == pytest.approx(roc_auc_limit_multi[idx])\n- else:\n- assert display.roc_auc == pytest.approx(roc_auc_limit)\n- assert trapezoid(display.tpr, display.fpr) == pytest.approx(roc_auc_limit)\n-\n-\n [USER_REDACTED].mark.parametrize(\"response_method\", [\"predict_proba\", \"decision_function\"])\n [USER_REDACTED].mark.parametrize(\n \"constructor_name\", [\"from_estimator\", \"from_predictions\", \"from_cv_results\"]\n )\n def test_plot_roc_curve_pos_label(pyplot, response_method, constructor_name):\n- # check that we can provide the positive label and display the proper\n- # statistics\n- X, y = load_breast_cancer(return_X_y=True)\n- # create a highly imbalanced version of the breast cancer dataset\n- idx_positive = np.flatnonzero(y == 1)\n- idx_negative = np.flatnonzero(y == 0)\n- idx_selected = np.hstack([idx_negative, idx_positive[:25]])\n- X, y = X[idx_selected], y[idx_selected]\n- X, y = shuffle(X, y, random_state=42)\n- # only use 2 features to make the problem even harder\n- X = X[:, :2]\n- y = np.array([\"cancer\" if c == 1 else \"not cancer\" for c in y], dtype=object)\n- X_train, X_test, y_train, y_test = train_test_split(\n- X,\n- y,\n- stratify=y,\n- random_state=0,\n- )\n-\n- classifier = LogisticRegression()\n- classifier.fit(X_train, y_train)\n- cv_results = cross_validate(\n- LogisticRegression(), X, y, cv=3, return_estimator=True, return_indices=True\n- )\n-\n- # Sanity check to be sure the positive class is `classes_[0]`\n- # Class imbalance ensures a large difference in prediction values between classes,\n- # allowing us to catch errors when we switch `pos_label`\n- assert classifier.classes_.tolist() == [\"cancer\", \"not cancer\"]\n+ \"\"\"Test switching `pos_label` gives correct statistics, using imbalanced data.\"\"\"\n \n- y_score = getattr(classifier, response_method)(X_test)\n- # we select the corresponding probability columns or reverse the decision\n- # function otherwise\n- y_score_cancer = -1 * y_score if y_score.ndim == 1 else y_score[:, 0]\n- y_score_not_cancer = y_score if y_score.ndim == 1 else y_score[:, 1]\n+ def _check_auc(display, constructor_name, pos_label):\n+ roc_auc_limit = 0.95679\n+ roc_auc_limit_multi = [0.97007, 0.985915, 0.980952]\n \n- pos_label = \"cancer\"\n- y_score = y_score_cancer\n- if constructor_name == \"from_estimator\":\n- display = RocCurveDisplay.from_estimator(\n- classifier,\n- X_test,\n- y_test,\n- pos_label=pos_label,\n- response_method=response_method,\n- )\n- elif constructor_name == \"from_predictions\":\n- display = RocCurveDisplay.from_predictions(\n- y_test,\n- y_score,\n- pos_label=pos_label,\n- )\n- else:\n- display = RocCurveDisplay.from_cv_results(\n- cv_results,\n- X,\n- y,\n- response_method=response_method,\n- pos_label=pos_label,\n- )\n-\n- _check_auc(display, constructor_name)\n-\n- pos_label = \"not cancer\"\n- y_score = y_score_not_cancer\n- if constructor_name == \"from_estimator\":\n- display = RocCurveDisplay.from_estimator(\n- classifier,\n- X_test,\n- y_test,\n- response_method=response_method,\n- pos_label=pos_label,\n- )\n- elif constructor_name == \"from_predictions\":\n- display = RocCurveDisplay.from_predictions(\n- y_test,\n- y_score,\n- pos_label=pos_label,\n- )\n- else:\n- display = RocCurveDisplay.from_cv_results(\n- cv_results,\n- X,\n- y,\n- response_method=response_method,\n- pos_label=pos_label,\n- )\n+ if constructor_name == \"from_cv_results\":\n+ for idx, roc_auc in enumerate(display.roc_auc):\n+ assert roc_auc == pytest.approx(roc_auc_limit_multi[idx])\n+ else:\n+ assert display.roc_auc == pytest.approx(roc_auc_limit)\n+ assert trapezoid(display.tpr, display.fpr) == pytest.approx(roc_auc_limit)\n \n- _check_auc(display, constructor_name)\n+ _check_pos_label_statistics(\n+ RocCurveDisplay, response_method, constructor_name, _check_auc\n+ )\n \n \n # TODO(1.9): remove" } ], "reviews": [ { "id": 3762493703, "user": "user_d16337ec046b", "state": "COMMENTED", "body": null, "submitted_at": "2026-02-06T11:15:31+00:00" }, { "id": 3763908957, "user": "user_9cabc0c64225", "state": "APPROVED", "body": "LGTM. Just a small clean-up left to do.", "submitted_at": "2026-02-06T16:10:04+00:00" }, { "id": 3771686268, "user": "user_22bafe4fe1a9", "state": "APPROVED", "body": null, "submitted_at": "2026-02-09T08:23:23+00:00" }, { "id": 3777702796, "user": "user_d16337ec046b", "state": "COMMENTED", "body": null, "submitted_at": "2026-02-10T09:13:37+00:00" }, { "id": 3777767355, "user": "user_d16337ec046b", "state": "COMMENTED", "body": null, "submitted_at": "2026-02-10T09:26:23+00:00" }, { "id": 3777829221, "user": "user_d16337ec046b", "state": "COMMENTED", "body": null, "submitted_at": "2026-02-10T09:37:26+00:00" } ], "review_comments": [ { "id": 2773623335, "user": "user_d16337ec046b", "body": "Note that `pos_label` is not needed for roc_auc because it is the same regardless of `pos_label`, but it is needed for `average_precsion_score` (which will also use the `_check_pos_label_statistics` helper)", "path": "sklearn/metrics/_plot/tests/test_roc_curve_display.py", "line": 835, "side": "RIGHT", "created_at": "2026-02-06T11:15:31+00:00" }, { "id": 2774885169, "user": "user_9cabc0c64225", "body": "The `_check_auc` function is still also defined above the test function but not used anymore. I think you can remove it", "path": "sklearn/metrics/_plot/tests/test_roc_curve_display.py", "line": 844, "side": "RIGHT", "created_at": "2026-02-06T16:08:59+00:00" }, { "id": 2781107225, "user": "user_22bafe4fe1a9", "body": "```suggestion\n \"\"\"Test that switching `pos_label` gives correct statistics, using imbalanced data.\"\"\"\n```", "path": "sklearn/metrics/_plot/tests/test_common_curve_display.py", "line": null, "side": "RIGHT", "created_at": "2026-02-09T07:48:51+00:00" }, { "id": 2781110111, "user": "user_22bafe4fe1a9", "body": "```suggestion\n # create highly imbalanced classes\n```", "path": "sklearn/metrics/_plot/tests/test_common_curve_display.py", "line": null, "side": "RIGHT", "created_at": "2026-02-09T07:49:44+00:00" }, { "id": 2781113846, "user": "user_22bafe4fe1a9", "body": "Out of curiosity: Why it is harder with only 2 features?\nI see that this PR did not change that.", "path": "sklearn/metrics/_plot/tests/test_common_curve_display.py", "line": 46, "side": "RIGHT", "created_at": "2026-02-09T07:50:52+00:00" }, { "id": 2781115349, "user": "user_22bafe4fe1a9", "body": "```suggestion\n # Sanity check to be sure the positive class is `classes_[0]`.\n # Class imbalance ensures a large difference in prediction values between classes,\n # allowing us to catch errors when we switch `pos_label`.\n assert classifier.classes_.tolist() == [\"cancer\", \"not cancer\"]\n```", "path": "sklearn/metrics/_plot/tests/test_common_curve_display.py", "line": null, "side": "RIGHT", "created_at": "2026-02-09T07:51:21+00:00" }, { "id": 2781246734, "user": "user_22bafe4fe1a9", "body": "```suggestion\n \"\"\"Test that switching `pos_label` gives correct statistics, using imbalanced data.\"\"\"\n```", "path": "sklearn/metrics/_plot/tests/test_roc_curve_display.py", "line": null, "side": "RIGHT", "created_at": "2026-02-09T08:22:26+00:00" }, { "id": 2781249559, "user": "user_22bafe4fe1a9", "body": "I know these numbers are not from this PR. Still, I'm curious where they come from.", "path": "sklearn/metrics/_plot/tests/test_roc_curve_display.py", "line": 837, "side": "RIGHT", "created_at": "2026-02-09T08:23:14+00:00" }, { "id": 2786747540, "user": "user_d16337ec046b", "body": "Amended, but couldn't use all the words suggested to fit allow it to fit one line", "path": "sklearn/metrics/_plot/tests/test_common_curve_display.py", "line": null, "side": "RIGHT", "created_at": "2026-02-10T09:13:37+00:00" }, { "id": 2786809302, "user": "user_d16337ec046b", "body": "Honestly I think only [USER_REDACTED] can (best) answer this question.\n\nHere I think it means that the classification problem is harder if we only include 2 features. And with highly imbalanced classes, a harder classification problem may make the model lean towards predicting the majority class with more confidence (since it does not have enough features to make 'good' predictions)?\n\nBut I was confused too: https://github.com/[USER_REDACTED]n/scikit-learn/pull/30399#discussion_r1917786538", "path": "sklearn/metrics/_plot/tests/test_common_curve_display.py", "line": 46, "side": "RIGHT", "created_at": "2026-02-10T09:26:22+00:00" }, { "id": 2786863641, "user": "user_d16337ec046b", "body": "This may sounds bad, but I guess this is effectively a non-regression test - the numbers are literally the calculated roc auc values.\n\nI assume the single curve one (L836) was added by [USER_REDACTED] who added this test.\n\nThe multi curve ones were added in #30399 by me, and follow the same procedure.\n\nhttps://github.com/[USER_REDACTED]n/scikit-learn/pull/30399/files#diff-a455a8aae5c9b59034d2e163bbfc31a21de369eb8b53f3c7e5bddd684eeabfd1L329", "path": "sklearn/metrics/_plot/tests/test_roc_curve_display.py", "line": 837, "side": "RIGHT", "created_at": "2026-02-10T09:37:26+00:00" } ], "meta": { "languages": [ "py" ], "touches_tests": true, "review_state_summary": { "COMMENTED": 4, "APPROVED": 2 }, "meaningful_comment_count": 11, "has_approval": true, "has_changes_requested": false, "total_review_comments": 11 } } { "_id": "692ea96521c77ce7", "_schema_version": "1.0", "_cleaned_at": "2026-02-12T07:46:51.897966+00:00", "repo": "scikit-learn/scikit-learn", "repo_url": "https://github.com/scikit-learn/scikit-learn", "license_name": "BSD 3-Clause \"New\" or \"Revised\" License", "license_spdx": "BSD-3-Clause", "pr_number": 33221, "title": "FIX add missing random states and cloning in `test_response.py`", "body": "\n\n#### [NAME_REDACTED]/PRs\n\nTowards #32393 and possibly also #33216\n\n#### What does this implement/fix? Explain your changes.\nI added the missing `random_seed` to the `KMeans` test cases and also added `clone` before `fit` (as it is done for example in line 240) where it was missing.\n\n[USER_REDACTED] \n#### AI usage disclosure\n\nI used AI assistance for:\n- [ ] Code generation (e.g., when writing an implementation or fixing a bug)\n- [ ] Test/benchmark generation\n- [ ] Documentation (including examples)\n- [ ] Research and understanding\n\n#### Any other comments?\n\n", "author": "user_34a090906ca4", "created_at": "2026-02-06T10:37:50+00:00", "merged_at": "2026-02-06T14:50:17+00:00", "base_branch": "main", "head_branch": "fix_failing_test", "additions": 17, "deletions": 18, "changed_files": 1, "files": [ { "filename": "sklearn/utils/tests/test_response.py", "status": "modified", "additions": 17, "deletions": 18, "changes": 35, "patch": "@@ -16,7 +16,7 @@\n from sklearn.preprocessing import scale\n from sklearn.tree import DecisionTreeClassifier, DecisionTreeRegressor\n from sklearn.utils._response import _get_response_values, _get_response_values_binary\n-from sklearn.utils._testing import assert_allclose, assert_array_equal\n+from sklearn.utils._testing import assert_allclose\n \n X, y = load_iris(return_X_y=True)\n # scale the data to avoid ConvergenceWarning with LogisticRegression\n@@ -29,17 +29,17 @@\n [\n (DecisionTreeRegressor(), \"predict_proba\"),\n (DecisionTreeRegressor(), [\"predict_proba\", \"decision_function\"]),\n- (KMeans(n_clusters=2, n_init=1), \"predict_proba\"),\n- (KMeans(n_clusters=2, n_init=1), [\"predict_proba\", \"decision_function\"]),\n+ (KMeans(n_clusters=2), \"predict_proba\"),\n+ (KMeans(n_clusters=2), [\"predict_proba\", \"decision_function\"]),\n (DBSCAN(), \"predict\"),\n- (IsolationForest(random_state=0), \"predict_proba\"),\n- (IsolationForest(random_state=0), [\"predict_proba\", \"score\"]),\n+ (IsolationForest(), \"predict_proba\"),\n+ (IsolationForest(), [\"predict_proba\", \"score\"]),\n ],\n )\n-def test_estimator_unsupported_response(pyplot, estimator, response_method):\n+def test_estimator_unsupported_response(estimator, response_method):\n \"\"\"Check the error message with not supported response method.\"\"\"\n X, y = np.random.RandomState(0).randn(10, 2), np.array([0, 1] * 5)\n- estimator.fit(X, y)\n+ estimator = clone(estimator).fit(X, y) # clone to make test execution thread-safe\n err_msg = \"has none of the following attributes:\"\n with pytest.raises(AttributeError, match=err_msg):\n _get_response_values(\n@@ -53,9 +53,9 @@ def test_estimator_unsupported_response(pyplot, estimator, response_method):\n \"estimator, response_method\",\n [\n (LinearRegression(), \"predict\"),\n- (KMeans(n_clusters=2, n_init=1), \"predict\"),\n- (KMeans(n_clusters=2, n_init=1), \"score\"),\n- (KMeans(n_clusters=2, n_init=1), [\"predict\", \"score\"]),\n+ (KMeans(n_clusters=2, random_state=0), \"predict\"),\n+ (KMeans(n_clusters=2, random_state=0), \"score\"),\n+ (KMeans(n_clusters=2, random_state=0), [\"predict\", \"score\"]),\n (IsolationForest(random_state=0), \"predict\"),\n (IsolationForest(random_state=0), \"decision_function\"),\n (IsolationForest(random_state=0), [\"decision_function\", \"predict\"]),\n@@ -67,7 +67,7 @@ def test_estimator_get_response_values(\n ):\n \"\"\"Check the behaviour of `_get_response_values`.\"\"\"\n X, y = np.random.RandomState(0).randn(10, 2), np.array([0, 1] * 5)\n- estimator.fit(X, y)\n+ estimator = clone(estimator).fit(X, y) # clone to make test execution thread-safe\n results = _get_response_values(\n estimator,\n X,\n@@ -78,7 +78,7 @@ def test_estimator_get_response_values(\n response_method[0] if isinstance(response_method, list) else response_method\n )\n prediction_method = getattr(estimator, chosen_response_method)\n- assert_array_equal(results[0], prediction_method(X))\n+ assert_allclose(results[0], prediction_method(X))\n assert results[1] is None\n if return_response_method_used:\n assert results[2] == chosen_response_method\n@@ -310,8 +310,7 @@ def test_get_response_values_multiclass(estimator, response_method):\n \"\"\"Check that we can call `_get_response_values` with a multiclass estimator.\n It should return the predictions untouched.\n \"\"\"\n- estimator = clone(estimator)\n- estimator.fit(X, y)\n+ estimator = clone(estimator).fit(X, y) # clone to make test execution thread-safe\n predictions, pos_label = _get_response_values(\n estimator, X, response_method=response_method\n )\n@@ -416,8 +415,8 @@ def test_response_values_type_of_target_on_classes_no_warning():\n (IsolationForest(), \"predict\", \"multiclass\", (10,)),\n (DecisionTreeRegressor(), \"predict\", \"binary\", (10,)),\n (DecisionTreeRegressor(), \"predict\", \"multiclass\", (10,)),\n- (KMeans(n_clusters=2, n_init=1), \"predict\", \"binary\", (10,)),\n- (KMeans(n_clusters=2, n_init=1), \"predict\", \"multiclass\", (10,)),\n+ (KMeans(n_clusters=2), \"predict\", \"binary\", (10,)),\n+ (KMeans(n_clusters=4), \"predict\", \"multiclass\", (10,)),\n ],\n )\n def test_response_values_output_shape_(\n@@ -442,8 +441,8 @@ def test_response_values_output_shape_(\n else: # multilabel\n y = np.array([[0, 1], [1, 0]] * 5)\n \n- clf = clone(estimator).fit(X, y)\n+ estimator = clone(estimator).fit(X, y) # clone to make test execution thread-safe\n \n- y_pred, _ = _get_response_values(clf, X, response_method=response_method)\n+ y_pred, _ = _get_response_values(estimator, X, response_method=response_method)\n \n assert y_pred.shape == expected_shape" } ], "reviews": [ { "id": 3762276349, "user": "user_34a090906ca4", "state": "COMMENTED", "body": null, "submitted_at": "2026-02-06T10:42:05+00:00" }, { "id": 3762284042, "user": "user_34a090906ca4", "state": "COMMENTED", "body": null, "submitted_at": "2026-02-06T10:43:17+00:00" }, { "id": 3762304439, "user": "user_34a090906ca4", "state": "COMMENTED", "body": null, "submitted_at": "2026-02-06T10:46:20+00:00" }, { "id": 3762310061, "user": "user_34a090906ca4", "state": "COMMENTED", "body": null, "submitted_at": "2026-02-06T10:47:14+00:00" }, { "id": 3762322969, "user": "user_fca2535bcd49", "state": "COMMENTED", "body": null, "submitted_at": "2026-02-06T10:49:16+00:00" }, { "id": 3762324233, "user": "user_34a090906ca4", "state": "COMMENTED", "body": null, "submitted_at": "2026-02-06T10:49:28+00:00" }, { "id": 3762326788, "user": "user_fca2535bcd49", "state": "COMMENTED", "body": null, "submitted_at": "2026-02-06T10:49:51+00:00" }, { "id": 3762337498, "user": "user_34a090906ca4", "state": "COMMENTED", "body": null, "submitted_at": "2026-02-06T10:51:29+00:00" }, { "id": 3763300272, "user": "user_9cabc0c64225", "state": "COMMENTED", "body": null, "submitted_at": "2026-02-06T14:02:51+00:00" }, { "id": 3763365488, "user": "user_34a090906ca4", "state": "COMMENTED", "body": null, "submitted_at": "2026-02-06T14:16:35+00:00" }, { "id": 3763383116, "user": "user_9cabc0c64225", "state": "COMMENTED", "body": null, "submitted_at": "2026-02-06T14:20:31+00:00" }, { "id": 3763460156, "user": "user_fca2535bcd49", "state": "APPROVED", "body": "LGTM, thanks!\n\nThis fixes all the failures on free-threaded locally for me and cleans up a few things.", "submitted_at": "2026-02-06T14:34:29+00:00" }, { "id": 3763533968, "user": "user_9cabc0c64225", "state": "APPROVED", "body": "LGTM. Thanks !", "submitted_at": "2026-02-06T14:49:49+00:00" } ], "review_comments": [ { "id": 2773469743, "user": "user_34a090906ca4", "body": "Unrelated small clean-up: changed `clf` to`estimator` because different estimators are tested here\n\nAnd I added the comment on explaining the cloning here as well, because I didn't know this, and it probably doesn't hurt to be expressive on this.", "path": "sklearn/utils/tests/test_response.py", "line": 444, "side": "RIGHT", "created_at": "2026-02-06T10:42:06+00:00" }, { "id": 2773475249, "user": "user_34a090906ca4", "body": "Unrelated small clean-up: remove redundant parameter and make test case more consistent", "path": "sklearn/utils/tests/test_response.py", "line": 419, "side": "RIGHT", "created_at": "2026-02-06T10:43:17+00:00" }, { "id": 2773489925, "user": "user_34a090906ca4", "body": "Here we just check the attributes, so setting the `random_state` has no impact. Not sure if we should consistently add or remove it in such cases?", "path": "sklearn/utils/tests/test_response.py", "line": 35, "side": "RIGHT", "created_at": "2026-02-06T10:46:20+00:00" }, { "id": 2773493862, "user": "user_34a090906ca4", "body": "`n_init=1` is the default value in this case anyways", "path": "sklearn/utils/tests/test_response.py", "line": 56, "side": "LEFT", "created_at": "2026-02-06T10:47:14+00:00" }, { "id": 2773502557, "user": "user_fca2535bcd49", "body": "I think it's fine not to have `random_state` in this case.", "path": "sklearn/utils/tests/test_response.py", "line": 35, "side": "RIGHT", "created_at": "2026-02-06T10:49:16+00:00" }, { "id": 2773503468, "user": "user_34a090906ca4", "body": "Note: Here we also just check response shapes, so random states don't matter for this test.", "path": "sklearn/utils/tests/test_response.py", "line": 419, "side": "RIGHT", "created_at": "2026-02-06T10:49:28+00:00" }, { "id": 2773505362, "user": "user_fca2535bcd49", "body": "Just curious, you are doing this for free-threaded because you have noticed issues when running the test locally with pytest-run-parallel?", "path": "sklearn/utils/tests/test_response.py", "line": 42, "side": "RIGHT", "created_at": "2026-02-06T10:49:51+00:00" }, { "id": 2773512721, "user": "user_34a090906ca4", "body": "No, I saw that this was done like this with this comment on line 240 (added by Olivier) and adapted it for the rest.", "path": "sklearn/utils/tests/test_response.py", "line": 42, "side": "RIGHT", "created_at": "2026-02-06T10:51:28+00:00" }, { "id": 2774315089, "user": "user_9cabc0c64225", "body": "is changing to `n_clusters=4` on purpose ?", "path": "sklearn/utils/tests/test_response.py", "line": 419, "side": "RIGHT", "created_at": "2026-02-06T14:02:51+00:00" }, { "id": 2774374912, "user": "user_34a090906ca4", "body": "Yes, to make explicit that the output shape also doesn't change in the multiclass (or rather, \"multicluster\") case. I didn't see this in the PR where it was added, but I can also make a separate PR for the cleanu-ps if this is becoming too cluttered now.", "path": "sklearn/utils/tests/test_response.py", "line": 419, "side": "RIGHT", "created_at": "2026-02-06T14:16:35+00:00" }, { "id": 2774392112, "user": "user_9cabc0c64225", "body": "Thanks for the clarification. It's fine to keep it in this PR", "path": "sklearn/utils/tests/test_response.py", "line": 419, "side": "RIGHT", "created_at": "2026-02-06T14:20:31+00:00" } ], "meta": { "languages": [ "py" ], "touches_tests": true, "review_state_summary": { "COMMENTED": 11, "APPROVED": 2 }, "meaningful_comment_count": 11, "has_approval": true, "has_changes_requested": false, "total_review_comments": 11 } } { "_id": "2f316060495958b0", "_schema_version": "1.0", "_cleaned_at": "2026-02-12T07:46:51.902975+00:00", "repo": "scikit-learn/scikit-learn", "repo_url": "https://github.com/scikit-learn/scikit-learn", "license_name": "BSD 3-Clause \"New\" or \"Revised\" License", "license_spdx": "BSD-3-Clause", "pr_number": 33218, "title": "TST Move common binary Display class tests to `test_common_curve_display.py`", "body": "#### [NAME_REDACTED]/PRs\nRelated to #33217\nMoving the test changes from #30508 as requested\n\n#### What does this implement/fix? Explain your changes.\n\n* In #30508 I noticed tests that were common between binary Display classes `PrecisionRecallDisplay` and `RocCurveDisplay` thus I moved them to common test file to avoid duplication and we can easily add new displays to the parametrization, as we add `from_cv_results` method to more display classes\n* Most tests relate to the new `from_cv_results` method \n\nSummary of migrated tests\n\n`test_validate_plot_params` -> `test_display_validate_plot_params`\n\n`test_roc_curve_plot_legend_label` -> `test_display_plot_legend_label`\n\n`test_roc_curve_from_cv_results_legend_label` -> `test_display_from_cv_results_legend_label`\n\n`test_roc_curve_from_cv_results_param_validation` -> `test_display_from_cv_results_param_validation`\n\n`test_roc_curve_from_cv_results_pos_label_inferred` -> `test_display_from_cv_results_pos_label_inferred`\n\n`test_roc_curve_display_from_cv_results_curve_kwargs` -> `test_display_from_cv_results_curve_kwargs`\n\nNew test: `test_display_default_name`\n\n#### AI usage disclosure\n\nI used AI assistance for:\n- [ ] Code generation (e.g., when writing an implementation or fixing a bug)\n- [ ] Test/benchmark generation\n- [ ] Documentation (including examples)\n- [ ] Research and understanding\n\n#### Any other comments?\n\ncc [USER_REDACTED] [USER_REDACTED]", "author": "user_d16337ec046b", "created_at": "2026-02-06T05:44:16+00:00", "merged_at": "2026-02-10T15:16:28+00:00", "base_branch": "main", "head_branch": "tst_from_cv_common_tests", "additions": 375, "deletions": 249, "changed_files": 2, "files": [ { "filename": "sklearn/metrics/_plot/tests/test_common_curve_display.py", "status": "modified", "additions": 374, "deletions": 1, "changes": 375, "patch": "@@ -1,10 +1,13 @@\n+from collections.abc import Mapping\n+from contextlib import suppress\n+\n import numpy as np\n import pytest\n \n from sklearn.base import BaseEstimator, ClassifierMixin, clone\n from sklearn.calibration import CalibrationDisplay\n from sklearn.compose import make_column_transformer\n-from sklearn.datasets import load_breast_cancer, load_iris\n+from sklearn.datasets import load_breast_cancer, load_iris, make_classification\n from sklearn.exceptions import NotFittedError\n from sklearn.linear_model import LogisticRegression\n from sklearn.metrics import (\n@@ -375,6 +378,376 @@ class SubclassOfDisplay(Display):\n assert isinstance(curve, SubclassOfDisplay)\n \n \n+[USER_REDACTED].mark.parametrize(\n+ \"Display, display_args\",\n+ [\n+ (\n+ RocCurveDisplay,\n+ {\n+ \"fpr\": np.array([0, 0.5, 1]),\n+ \"tpr\": [np.array([0, 0.5, 1])],\n+ \"roc_auc\": None,\n+ \"name\": \"test_curve\",\n+ },\n+ ),\n+ ],\n+)\n+def test_display_validate_plot_params(pyplot, Display, display_args):\n+ \"\"\"Check `_validate_plot_params` returns the correct variables.\n+\n+ `display_args` should be given in the same order as output by\n+ `_validate_plot_params`. All `display_args` should be for a single curve.\n+ \"\"\"\n+ display = Display(**display_args)\n+ results = display._validate_plot_params(ax=None, name=None)\n+\n+ # Check if the number of parameters match\n+ assert len(results) == len(display_args)\n+\n+ for idx, (param, value) in enumerate(display_args.items()):\n+ if param == \"name\":\n+ assert results[idx] == [value] if isinstance(value, str) else value\n+ elif value is None:\n+ assert results[idx] is None\n+ else:\n+ assert isinstance(results[idx], list)\n+ assert len(results[idx]) == 1\n+\n+\n+auc_metrics = [[1.0, 1.0, 1.0], None]\n+\n+\n+[USER_REDACTED].mark.parametrize(\n+ \"Display, auc_metric_name, auc_arg_name, display_args\",\n+ [\n+ pytest.param(\n+ RocCurveDisplay,\n+ \"AUC\",\n+ \"roc_auc\",\n+ {\n+ \"fpr\": [np.array([0, 0.5, 1])] * 3,\n+ \"tpr\": [np.array([0, 0.5, 1])] * 3,\n+ \"roc_auc\": auc_metric,\n+ },\n+ )\n+ for auc_metric in auc_metrics\n+ ],\n+)\n+[USER_REDACTED].mark.parametrize(\n+ \"curve_kwargs\",\n+ [None, {\"color\": \"red\"}, [{\"c\": \"red\"}, {\"c\": \"green\"}, {\"c\": \"yellow\"}]],\n+)\n+[USER_REDACTED].mark.parametrize(\"name\", [None, \"single\", [\"one\", \"two\", \"three\"]])\n+def test_display_plot_legend_label(\n+ pyplot, Display, auc_metric_name, auc_arg_name, display_args, curve_kwargs, name\n+):\n+ \"\"\"Check legend label correct with all `curve_kwargs`, `name` combinations.\n+\n+ Checks `from_estimator` and `from_predictions` methods, when plotting multiple\n+ curves.\n+ \"\"\"\n+ if not isinstance(curve_kwargs, list) and isinstance(name, list):\n+ with pytest.raises(ValueError, match=\"To avoid labeling individual curves\"):\n+ Display(**display_args).plot(name=name, curve_kwargs=curve_kwargs)\n+ return\n+\n+ display = Display(**display_args).plot(name=name, curve_kwargs=curve_kwargs)\n+ legend = display.ax_.get_legend()\n+ auc_metric = display_args[auc_arg_name]\n+\n+ if legend is None:\n+ # No legend is created, exit test early\n+ assert name is None\n+ assert auc_metric is None\n+ return\n+ else:\n+ legend_labels = [text.get_text() for text in legend.get_texts()]\n+\n+ if isinstance(curve_kwargs, list):\n+ # Multiple labels in legend\n+ assert len(legend_labels) == 3\n+ for idx, label in enumerate(legend_labels):\n+ if name is None:\n+ expected_label = f\"{auc_metric_name} = 1.00\" if auc_metric else None\n+ assert label == expected_label\n+ elif isinstance(name, str):\n+ expected_label = (\n+ f\"single ({auc_metric_name} = 1.00)\" if auc_metric else \"single\"\n+ )\n+ assert label == expected_label\n+ else:\n+ # `name` is a list of different strings\n+ expected_label = (\n+ f\"{name[idx]} ({auc_metric_name} = 1.00)\"\n+ if auc_metric\n+ else f\"{name[idx]}\"\n+ )\n+ assert label == expected_label\n+ else:\n+ # Single label in legend\n+ assert len(legend_labels) == 1\n+ if name is None:\n+ expected_label = (\n+ f\"{auc_metric_name} = 1.00 +/- 0.00\" if auc_metric else None\n+ )\n+ assert legend_labels[0] == expected_label\n+ else:\n+ # name is single string\n+ expected_label = (\n+ f\"single ({auc_metric_name} = 1.00 +/- 0.00)\"\n+ if auc_metric\n+ else \"single\"\n+ )\n+ assert legend_labels[0] == expected_label\n+ # Close plots, prevents \"more than 20 figures\" opened warning\n+ pyplot.close(\"all\")\n+\n+\n+[USER_REDACTED].mark.parametrize(\n+ \"Display, auc_metrics, auc_metric_name\",\n+ [\n+ (RocCurveDisplay, [0.96, 1.00, 1.00], \"AUC\"),\n+ ],\n+)\n+[USER_REDACTED].mark.parametrize(\n+ \"curve_kwargs\",\n+ [None, {\"color\": \"red\"}, [{\"c\": \"red\"}, {\"c\": \"green\"}, {\"c\": \"yellow\"}]],\n+)\n+[USER_REDACTED].mark.parametrize(\"name\", [None, \"single\", [\"one\", \"two\", \"three\"]])\n+def test_display_from_cv_results_legend_label(\n+ pyplot, Display, auc_metrics, auc_metric_name, curve_kwargs, name\n+):\n+ \"\"\"Check legend label correct with all `curve_kwargs`, `name` combinations.\n+\n+ This function verifies that the legend labels in a Display object created from\n+ cross-validation results are correctly formatted based on the provided parameters.\n+ \"\"\"\n+ X, y = X, y = make_classification(n_classes=2, n_samples=50, random_state=0)\n+ cv_results = cross_validate(\n+ LogisticRegression(), X, y, cv=3, return_estimator=True, return_indices=True\n+ )\n+\n+ if not isinstance(curve_kwargs, list) and isinstance(name, list):\n+ with pytest.raises(ValueError, match=\"To avoid labeling individual curves\"):\n+ Display.from_cv_results(\n+ cv_results, X, y, name=name, curve_kwargs=curve_kwargs\n+ )\n+ else:\n+ display = Display.from_cv_results(\n+ cv_results, X, y, name=name, curve_kwargs=curve_kwargs\n+ )\n+\n+ legend = display.ax_.get_legend()\n+ legend_labels = [text.get_text() for text in legend.get_texts()]\n+ if isinstance(curve_kwargs, list):\n+ # Multiple labels in legend\n+ assert len(legend_labels) == 3\n+ for idx, label in enumerate(legend_labels):\n+ if name is None:\n+ assert label == f\"{auc_metric_name} = {auc_metrics[idx]:.2f}\"\n+ elif isinstance(name, str):\n+ assert (\n+ label == f\"single ({auc_metric_name} = {auc_metrics[idx]:.2f})\"\n+ )\n+ else:\n+ # `name` is a list of different strings\n+ assert (\n+ label\n+ == f\"{name[idx]} ({auc_metric_name} = {auc_metrics[idx]:.2f})\"\n+ )\n+ else:\n+ # Single label in legend\n+ assert len(legend_labels) == 1\n+ if name is None:\n+ assert legend_labels[0] == (\n+ f\"{auc_metric_name} = {np.mean(auc_metrics):.2f} +/- \"\n+ f\"{np.std(auc_metrics):.2f}\"\n+ )\n+ else:\n+ # name is single string\n+ assert legend_labels[0] == (\n+ f\"single ({auc_metric_name} = {np.mean(auc_metrics):.2f} +/- \"\n+ f\"{np.std(auc_metrics):.2f})\"\n+ )\n+ # Close plots, prevents \"more than 20 figures\" opened warning\n+ pyplot.close(\"all\")\n+\n+\n+[USER_REDACTED].mark.parametrize(\"Display\", [RocCurveDisplay])\n+def test_display_from_cv_results_param_validation(pyplot, data_binary, Display):\n+ \"\"\"Check parameter validation is correct.\"\"\"\n+ X, y = data_binary\n+\n+ # `cv_results` missing key\n+ cv_results_no_est = cross_validate(\n+ LogisticRegression(), X, y, cv=3, return_estimator=True, return_indices=False\n+ )\n+ cv_results_no_indices = cross_validate(\n+ LogisticRegression(), X, y, cv=3, return_estimator=True, return_indices=False\n+ )\n+ for cv_results in (cv_results_no_est, cv_results_no_indices):\n+ with pytest.raises(\n+ ValueError,\n+ match=\"`cv_results` does not contain one of the following required\",\n+ ):\n+ Display.from_cv_results(cv_results, X, y)\n+\n+ cv_results = cross_validate(\n+ LogisticRegression(), X, y, cv=3, return_estimator=True, return_indices=True\n+ )\n+\n+ # `X` wrong length\n+ with pytest.raises(ValueError, match=\"`X` does not contain the correct\"):\n+ Display.from_cv_results(cv_results, X[:10, :], y)\n+\n+ # `y` not binary\n+ y_multi = y.copy()\n+ y_multi[0] = 2\n+ with pytest.raises(ValueError, match=\"The target `y` is not binary.\"):\n+ Display.from_cv_results(cv_results, X, y_multi)\n+\n+ # input inconsistent length\n+ with pytest.raises(ValueError, match=\"Found input variables with inconsistent\"):\n+ Display.from_cv_results(cv_results, X, y[:10])\n+ with pytest.raises(ValueError, match=\"Found input variables with inconsistent\"):\n+ Display.from_cv_results(cv_results, X, y, sample_weight=[1, 2])\n+\n+ # `pos_label` inconsistency\n+ y_multi[y_multi == 1] = 2\n+ with suppress(ValueError): # ignore any `pos_label` side errors\n+ with pytest.warns(\n+ # Also captures subclass warnings e.g., `UndefinedMetricWarning`\n+ UserWarning,\n+ match=\"No positive .* in y_true\",\n+ ):\n+ Display.from_cv_results(cv_results, X, y_multi)\n+\n+ # `name` is list while `curve_kwargs` is None or dict\n+ for curve_kwargs in (None, {\"alpha\": 0.2}):\n+ with pytest.raises(ValueError, match=\"To avoid labeling individual curves\"):\n+ Display.from_cv_results(\n+ cv_results,\n+ X,\n+ y,\n+ name=[\"one\", \"two\", \"three\"],\n+ curve_kwargs=curve_kwargs,\n+ )\n+\n+ # `curve_kwargs` incorrect length\n+ with pytest.raises(ValueError, match=\"`curve_kwargs` must be None, a dictionary\"):\n+ Display.from_cv_results(cv_results, X, y, curve_kwargs=[{\"alpha\": 1}])\n+\n+ # `curve_kwargs` both alias provided\n+ with pytest.raises(TypeError, match=\"Got both c and\"):\n+ Display.from_cv_results(\n+ cv_results, X, y, curve_kwargs={\"c\": \"blue\", \"color\": \"red\"}\n+ )\n+\n+\n+[USER_REDACTED].mark.parametrize(\"Display\", [RocCurveDisplay])\n+def test_display_from_cv_results_pos_label_inferred(pyplot, data_binary, Display):\n+ \"\"\"Check `pos_label` inferred correctly by `from_cv_results(pos_label=None)`.\"\"\"\n+ X, y = data_binary\n+ cv_results = cross_validate(\n+ LogisticRegression(), X, y, cv=3, return_estimator=True, return_indices=True\n+ )\n+\n+ disp = Display.from_cv_results(cv_results, X, y, pos_label=None)\n+ # Should be `estimator.classes_[1]`\n+ assert disp.pos_label == 1\n+\n+\n+[USER_REDACTED].mark.parametrize(\"Display\", [RocCurveDisplay])\n+[USER_REDACTED].mark.parametrize(\n+ \"constructor_name, expected_clf_name\",\n+ [\n+ (\"from_estimator\", \"LogisticRegression\"),\n+ (\"from_predictions\", \"Classifier\"),\n+ ],\n+)\n+def test_display_default_name(\n+ pyplot,\n+ data_binary,\n+ constructor_name,\n+ expected_clf_name,\n+ Display,\n+):\n+ \"\"\"Check the default name display in the figure when `name` is not provided.\"\"\"\n+ X, y = data_binary\n+\n+ lr = LogisticRegression().fit(X, y)\n+ y_score = lr.predict_proba(X)[:, 1]\n+\n+ if constructor_name == \"from_estimator\":\n+ disp = Display.from_estimator(lr, X, y)\n+ else:\n+ disp = Display.from_predictions(y, y_score)\n+\n+ assert expected_clf_name in disp.name\n+ assert expected_clf_name in disp.line_.get_label()\n+\n+\n+[USER_REDACTED].mark.parametrize(\"Display\", [RocCurveDisplay])\n+[USER_REDACTED].mark.parametrize(\n+ \"curve_kwargs\",\n+ [None, {\"alpha\": 0.2}, [{\"alpha\": 0.2}, {\"alpha\": 0.3}, {\"alpha\": 0.4}]],\n+)\n+def test_display_from_cv_results_curve_kwargs(\n+ pyplot, data_binary, curve_kwargs, Display\n+):\n+ \"\"\"Check `curve_kwargs` correctly passed.\"\"\"\n+ X, y = data_binary\n+ cv_results = cross_validate(\n+ LogisticRegression(), X, y, cv=3, return_estimator=True, return_indices=True\n+ )\n+ display = Display.from_cv_results(\n+ cv_results,\n+ X,\n+ y,\n+ curve_kwargs=curve_kwargs,\n+ )\n+ if curve_kwargs is None:\n+ # Default `alpha` used\n+ assert all(line.get_alpha() == 0.5 for line in display.line_)\n+ elif isinstance(curve_kwargs, Mapping):\n+ # `alpha` from dict used for all curves\n+ assert all(line.get_alpha() == 0.2 for line in display.line_)\n+ else:\n+ # Different `alpha` used for each curve\n+ assert all(\n+ line.get_alpha() == curve_kwargs[i][\"alpha\"]\n+ for i, line in enumerate(display.line_)\n+ )\n+\n+\n+[USER_REDACTED].mark.parametrize(\"Display\", [RocCurveDisplay])\n+[USER_REDACTED].mark.parametrize(\n+ \"curve_kwargs\",\n+ [None, {\"color\": \"red\"}, [{\"c\": \"red\"}, {\"c\": \"green\"}, {\"c\": \"yellow\"}]],\n+)\n+def test_display_from_cv_results_curve_kwargs_default_kwargs(\n+ pyplot, data_binary, curve_kwargs, Display\n+):\n+ \"\"\"Check `curve_kwargs` and default color handled correctly in `from_cv_results`.\"\"\"\n+\n+ X, y = data_binary\n+ cv_results = cross_validate(\n+ LogisticRegression(), X, y, cv=3, return_estimator=True, return_indices=True\n+ )\n+ display = Display.from_cv_results(cv_results, X, y, curve_kwargs=curve_kwargs)\n+\n+ for idx, line in enumerate(display.line_):\n+ color = line.get_color()\n+ if curve_kwargs is None:\n+ # Default color\n+ assert color == \"blue\"\n+ elif isinstance(curve_kwargs, Mapping):\n+ # All curves \"red\"\n+ assert color == \"red\"\n+ else:\n+ assert color == curve_kwargs[idx][\"c\"]\n+\n+\n [USER_REDACTED].mark.parametrize(\n \"Display, display_kwargs\",\n [" }, { "filename": "sklearn/metrics/_plot/tests/test_roc_curve_display.py", "status": "modified", "additions": 1, "deletions": 248, "changes": 249, "patch": "@@ -8,7 +8,7 @@\n from sklearn import clone\n from sklearn.compose import make_column_transformer\n from sklearn.datasets import make_classification\n-from sklearn.exceptions import NotFittedError, UndefinedMetricWarning\n+from sklearn.exceptions import NotFittedError\n from sklearn.linear_model import LogisticRegression\n from sklearn.metrics import RocCurveDisplay, auc, roc_curve\n from sklearn.metrics._plot.tests.test_common_curve_display import (\n@@ -200,135 +200,6 @@ def test_roc_curve_plot_parameter_length_validation(pyplot, params, err_msg):\n display.plot()\n \n \n-def test_validate_plot_params(pyplot):\n- \"\"\"Check `_validate_plot_params` returns the correct variables.\"\"\"\n- fpr = np.array([0, 0.5, 1])\n- tpr = [np.array([0, 0.5, 1])]\n- roc_auc = None\n- name = \"test_curve\"\n-\n- # Initialize display with test inputs\n- display = RocCurveDisplay(\n- fpr=fpr,\n- tpr=tpr,\n- roc_auc=roc_auc,\n- name=name,\n- pos_label=None,\n- )\n- fpr_out, tpr_out, roc_auc_out, name_out = display._validate_plot_params(\n- ax=None, name=None\n- )\n-\n- assert isinstance(fpr_out, list)\n- assert isinstance(tpr_out, list)\n- assert len(fpr_out) == 1\n- assert len(tpr_out) == 1\n- assert roc_auc_out is None\n- assert name_out == [\"test_curve\"]\n-\n-\n-def test_roc_curve_from_cv_results_param_validation(pyplot, data_binary):\n- \"\"\"Check parameter validation is correct.\"\"\"\n- X, y = data_binary\n-\n- # `cv_results` missing key\n- cv_results_no_est = cross_validate(\n- LogisticRegression(), X, y, cv=3, return_estimator=True, return_indices=False\n- )\n- cv_results_no_indices = cross_validate(\n- LogisticRegression(), X, y, cv=3, return_estimator=True, return_indices=False\n- )\n- for cv_results in (cv_results_no_est, cv_results_no_indices):\n- with pytest.raises(\n- ValueError,\n- match=\"`cv_results` does not contain one of the following required\",\n- ):\n- RocCurveDisplay.from_cv_results(cv_results, X, y)\n-\n- cv_results = cross_validate(\n- LogisticRegression(), X, y, cv=3, return_estimator=True, return_indices=True\n- )\n-\n- # `X` wrong length\n- with pytest.raises(ValueError, match=\"`X` does not contain the correct\"):\n- RocCurveDisplay.from_cv_results(cv_results, X[:10, :], y)\n-\n- # `y` not binary\n- y_multi = y.copy()\n- y_multi[0] = 2\n- with pytest.raises(ValueError, match=\"The target `y` is not binary.\"):\n- RocCurveDisplay.from_cv_results(cv_results, X, y_multi)\n-\n- # input inconsistent length\n- with pytest.raises(ValueError, match=\"Found input variables with inconsistent\"):\n- RocCurveDisplay.from_cv_results(cv_results, X, y[:10])\n- with pytest.raises(ValueError, match=\"Found input variables with inconsistent\"):\n- RocCurveDisplay.from_cv_results(cv_results, X, y, sample_weight=[1, 2])\n-\n- # `pos_label` inconsistency\n- y_multi[y_multi == 1] = 2\n- with pytest.warns(UndefinedMetricWarning, match=\"No positive samples in y_true\"):\n- RocCurveDisplay.from_cv_results(cv_results, X, y_multi)\n-\n- # `name` is list while `curve_kwargs` is None or dict\n- for curve_kwargs in (None, {\"alpha\": 0.2}):\n- with pytest.raises(ValueError, match=\"To avoid labeling individual curves\"):\n- RocCurveDisplay.from_cv_results(\n- cv_results,\n- X,\n- y,\n- name=[\"one\", \"two\", \"three\"],\n- curve_kwargs=curve_kwargs,\n- )\n-\n- # `curve_kwargs` incorrect length\n- with pytest.raises(ValueError, match=\"`curve_kwargs` must be None, a dictionary\"):\n- RocCurveDisplay.from_cv_results(cv_results, X, y, curve_kwargs=[{\"alpha\": 1}])\n-\n- # `curve_kwargs` both alias provided\n- with pytest.raises(TypeError, match=\"Got both c and\"):\n- RocCurveDisplay.from_cv_results(\n- cv_results, X, y, curve_kwargs={\"c\": \"blue\", \"color\": \"red\"}\n- )\n-\n-\n-[USER_REDACTED].mark.parametrize(\n- \"curve_kwargs\",\n- [None, {\"alpha\": 0.2}, [{\"alpha\": 0.2}, {\"alpha\": 0.3}, {\"alpha\": 0.4}]],\n-)\n-def test_roc_curve_display_from_cv_results_curve_kwargs(\n- pyplot, data_binary, curve_kwargs\n-):\n- \"\"\"Check `curve_kwargs` correctly passed.\"\"\"\n- X, y = data_binary\n- n_cv = 3\n- cv_results = cross_validate(\n- LogisticRegression(), X, y, cv=n_cv, return_estimator=True, return_indices=True\n- )\n- display = RocCurveDisplay.from_cv_results(\n- cv_results,\n- X,\n- y,\n- curve_kwargs=curve_kwargs,\n- )\n- if curve_kwargs is None:\n- # Default `alpha` used\n- assert all(line.get_alpha() == 0.5 for line in display.line_)\n- elif isinstance(curve_kwargs, Mapping):\n- # `alpha` from dict used for all curves\n- assert all(line.get_alpha() == 0.2 for line in display.line_)\n- else:\n- # Different `alpha` used for each curve\n- assert all(\n- line.get_alpha() == curve_kwargs[i][\"alpha\"]\n- for i, line in enumerate(display.line_)\n- )\n- # Other default kwargs should be the same\n- for line in display.line_:\n- assert line.get_linestyle() == \"--\"\n- assert line.get_color() == \"blue\"\n-\n-\n # TODO(1.9): Remove in 1.9\n [USER_REDACTED].mark.parametrize(\n \"constructor_name\", [\"from_estimator\", \"from_predictions\", \"plot\"]\n@@ -462,112 +333,6 @@ def test_roc_curve_display_plotting_from_cv_results(\n assert line.get_label() == aggregate_expected_labels[idx]\n \n \n-[USER_REDACTED].mark.parametrize(\"roc_auc\", [[1.0, 1.0, 1.0], None])\n-[USER_REDACTED].mark.parametrize(\n- \"curve_kwargs\",\n- [None, {\"color\": \"red\"}, [{\"c\": \"red\"}, {\"c\": \"green\"}, {\"c\": \"yellow\"}]],\n-)\n-[USER_REDACTED].mark.parametrize(\"name\", [None, \"single\", [\"one\", \"two\", \"three\"]])\n-def test_roc_curve_plot_legend_label(pyplot, data_binary, name, curve_kwargs, roc_auc):\n- \"\"\"Check legend label correct with all `curve_kwargs`, `name` combinations.\"\"\"\n- fpr = [np.array([0, 0.5, 1]), np.array([0, 0.5, 1]), np.array([0, 0.5, 1])]\n- tpr = [np.array([0, 0.5, 1]), np.array([0, 0.5, 1]), np.array([0, 0.5, 1])]\n- if not isinstance(curve_kwargs, list) and isinstance(name, list):\n- with pytest.raises(ValueError, match=\"To avoid labeling individual curves\"):\n- RocCurveDisplay(fpr=fpr, tpr=tpr, roc_auc=roc_auc).plot(\n- name=name, curve_kwargs=curve_kwargs\n- )\n-\n- else:\n- display = RocCurveDisplay(fpr=fpr, tpr=tpr, roc_auc=roc_auc).plot(\n- name=name, curve_kwargs=curve_kwargs\n- )\n- legend = display.ax_.get_legend()\n- if legend is None:\n- # No legend is created, exit test early\n- assert name is None\n- assert roc_auc is None\n- return\n- else:\n- legend_labels = [text.get_text() for text in legend.get_texts()]\n-\n- if isinstance(curve_kwargs, list):\n- # Multiple labels in legend\n- assert len(legend_labels) == 3\n- for idx, label in enumerate(legend_labels):\n- if name is None:\n- expected_label = \"AUC = 1.00\" if roc_auc else None\n- assert label == expected_label\n- elif isinstance(name, str):\n- expected_label = \"single (AUC = 1.00)\" if roc_auc else \"single\"\n- assert label == expected_label\n- else:\n- # `name` is a list of different strings\n- expected_label = (\n- f\"{name[idx]} (AUC = 1.00)\" if roc_auc else f\"{name[idx]}\"\n- )\n- assert label == expected_label\n- else:\n- # Single label in legend\n- assert len(legend_labels) == 1\n- if name is None:\n- expected_label = \"AUC = 1.00 +/- 0.00\" if roc_auc else None\n- assert legend_labels[0] == expected_label\n- else:\n- # name is single string\n- expected_label = \"single (AUC = 1.00 +/- 0.00)\" if roc_auc else \"single\"\n- assert legend_labels[0] == expected_label\n-\n-\n-[USER_REDACTED].mark.parametrize(\n- \"curve_kwargs\",\n- [None, {\"color\": \"red\"}, [{\"c\": \"red\"}, {\"c\": \"green\"}, {\"c\": \"yellow\"}]],\n-)\n-[USER_REDACTED].mark.parametrize(\"name\", [None, \"single\", [\"one\", \"two\", \"three\"]])\n-def test_roc_curve_from_cv_results_legend_label(\n- pyplot, data_binary, name, curve_kwargs\n-):\n- \"\"\"Check legend label correct with all `curve_kwargs`, `name` combinations.\"\"\"\n- X, y = data_binary\n- n_cv = 3\n- cv_results = cross_validate(\n- LogisticRegression(), X, y, cv=n_cv, return_estimator=True, return_indices=True\n- )\n-\n- if not isinstance(curve_kwargs, list) and isinstance(name, list):\n- with pytest.raises(ValueError, match=\"To avoid labeling individual curves\"):\n- RocCurveDisplay.from_cv_results(\n- cv_results, X, y, name=name, curve_kwargs=curve_kwargs\n- )\n- else:\n- display = RocCurveDisplay.from_cv_results(\n- cv_results, X, y, name=name, curve_kwargs=curve_kwargs\n- )\n-\n- legend = display.ax_.get_legend()\n- legend_labels = [text.get_text() for text in legend.get_texts()]\n- if isinstance(curve_kwargs, list):\n- # Multiple labels in legend\n- assert len(legend_labels) == 3\n- auc = [\"0.62\", \"0.66\", \"0.55\"]\n- for idx, label in enumerate(legend_labels):\n- if name is None:\n- assert label == f\"AUC = {auc[idx]}\"\n- elif isinstance(name, str):\n- assert label == f\"single (AUC = {auc[idx]})\"\n- else:\n- # `name` is a list of different strings\n- assert label == f\"{name[idx]} (AUC = {auc[idx]})\"\n- else:\n- # Single label in legend\n- assert len(legend_labels) == 1\n- if name is None:\n- assert legend_labels[0] == \"AUC = 0.61 +/- 0.05\"\n- else:\n- # name is single string\n- assert legend_labels[0] == \"single (AUC = 0.61 +/- 0.05)\"\n-\n-\n [USER_REDACTED].mark.parametrize(\n \"curve_kwargs\",\n [None, {\"color\": \"red\"}, [{\"c\": \"red\"}, {\"c\": \"green\"}, {\"c\": \"yellow\"}]],\n@@ -595,18 +360,6 @@ def test_roc_curve_from_cv_results_curve_kwargs(pyplot, data_binary, curve_kwarg\n assert color == curve_kwargs[idx][\"c\"]\n \n \n-def test_roc_curve_from_cv_results_pos_label_inferred(pyplot, data_binary):\n- \"\"\"Check `pos_label` inferred correctly by `from_cv_results(pos_label=None)`.\"\"\"\n- X, y = data_binary\n- cv_results = cross_validate(\n- LogisticRegression(), X, y, cv=3, return_estimator=True, return_indices=True\n- )\n-\n- disp = RocCurveDisplay.from_cv_results(cv_results, X, y, pos_label=None)\n- # Should be `estimator.classes_[1]`\n- assert disp.pos_label == 1\n-\n-\n def _check_chance_level(plot_chance_level, chance_level_kw, display):\n \"\"\"Check chance level line and line styles correct.\"\"\"\n import matplotlib as mpl" } ], "reviews": [ { "id": 3763114383, "user": "user_9cabc0c64225", "state": "COMMENTED", "body": "Thanks for the split and summary of the moved/renamed and added tests.\nI made a couple of suggestions to ease readability by [NAME_REDACTED] code and include it in the parametrization instead. It should also resolve the codecov issues as a bonus :)\n\nLGTM otherwise", "submitted_at": "2026-02-06T13:56:00+00:00" }, { "id": 3765588681, "user": "user_d16337ec046b", "state": "COMMENTED", "body": null, "submitted_at": "2026-02-06T23:32:40+00:00" }, { "id": 3765598604, "user": "user_d16337ec046b", "state": "COMMENTED", "body": null, "submitted_at": "2026-02-06T23:38:58+00:00" }, { "id": 3765618215, "user": "user_d16337ec046b", "state": "COMMENTED", "body": null, "submitted_at": "2026-02-06T23:52:03+00:00" }, { "id": 3771856533, "user": "user_22bafe4fe1a9", "state": "APPROVED", "body": null, "submitted_at": "2026-02-09T08:33:08+00:00" }, { "id": 3777860913, "user": "user_d16337ec046b", "state": "COMMENTED", "body": null, "submitted_at": "2026-02-10T09:43:20+00:00" }, { "id": 3779519239, "user": "user_9cabc0c64225", "state": "APPROVED", "body": "LGTM. Thanks !", "submitted_at": "2026-02-10T14:57:03+00:00" } ], "review_comments": [ { "id": 2774162648, "user": "user_9cabc0c64225", "body": "maybe we can incorporate that into the parametrization ?\nsee next comment", "path": "sklearn/metrics/_plot/tests/test_common_curve_display.py", "line": null, "side": "RIGHT", "created_at": "2026-02-06T13:28:50+00:00" }, { "id": 2774181320, "user": "user_9cabc0c64225", "body": "ref previous comment, name the `auc_metric_name` such that it matches the arg name so we can later do `auc_metric = display_args[auc_metric_name]`\n```suggestion\n \"Display, auc_metric_name, display_args\",\n [\n pytest.param(\n RocCurveDisplay,\n \"roc_auc\",\n {\n \"fpr\": [\n np.array([0, 0.5, 1]),\n np.array([0, 0.5, 1]),\n np.array([0, 0.5, 1]),\n ],\n \"tpr\": [\n np.array([0, 0.5, 1]),\n np.array([0, 0.5, 1]),\n np.array([0, 0.5, 1]),\n ],\n \"roc_auc\": auc_metric,\n```\n\nAlternatively if you want to keep \"AUC\", we can add another param \"auc_arg_name\", set to \"roc_auc\" so that we can later do `auc_metric = display_args[auc_arg_name]`", "path": "sklearn/metrics/_plot/tests/test_common_curve_display.py", "line": null, "side": "RIGHT", "created_at": "2026-02-06T13:33:29+00:00" }, { "id": 2774256791, "user": "user_9cabc0c64225", "body": "We could ignore the \"pos_label=1 is not a valid label\" error for this test and consider that the test is only about the param validation method.\n```suggestion\n with suppress(ValueError): # ignore pos_label side errors\n with pytest.warns(\n UndefinedMetricWarning, match=\"No positive .* in y_true\"\n ):\n Display.from_cv_results(cv_results, X, y_multi)\n```\n\nWe can include the expected warning message in the parametrization if we want to be more precise. In general I think we should avoid parametrization specific handling in parametrized tests when possible because it hurts readability.", "path": "sklearn/metrics/_plot/tests/test_common_curve_display.py", "line": null, "side": "RIGHT", "created_at": "2026-02-06T13:51:16+00:00" }, { "id": 2776433523, "user": "user_d16337ec046b", "body": "I think `UndefinedMetricWarning` inherits from `UserWarning`, so I think I need to amend to `UserWarning`, but that looks good to me.", "path": "sklearn/metrics/_plot/tests/test_common_curve_display.py", "line": null, "side": "RIGHT", "created_at": "2026-02-06T23:32:40+00:00" }, { "id": 2776444116, "user": "user_d16337ec046b", "body": "`auc_metric_name` is used in the legend e.g. 'AUC:' so I can't change that. But looking at the original test over in, it seems that (for these 2 displays at least) `auc_metrics` is the same, so let me just delete this part. We can always amend the test later if we add another display that requires different metrics", "path": "sklearn/metrics/_plot/tests/test_common_curve_display.py", "line": null, "side": "RIGHT", "created_at": "2026-02-06T23:38:57+00:00" }, { "id": 2776465669, "user": "user_d16337ec046b", "body": "Ignore that, I used your second suggestion!", "path": "sklearn/metrics/_plot/tests/test_common_curve_display.py", "line": null, "side": "RIGHT", "created_at": "2026-02-06T23:52:03+00:00" }, { "id": 2781268507, "user": "user_22bafe4fe1a9", "body": "```suggestion\ndef test_display_plot_legend_label(\n pyplot, Display, auc_metric_name, auc_arg_name, display_args, curve_kwargs, name\n```", "path": "sklearn/metrics/_plot/tests/test_common_curve_display.py", "line": null, "side": "RIGHT", "created_at": "2026-02-09T08:27:51+00:00" }, { "id": 2781273241, "user": "user_22bafe4fe1a9", "body": "```suggestion\n pyplot, Display, auc_metrics, auc_metric_name, curve_kwargs, name\n```", "path": "sklearn/metrics/_plot/tests/test_common_curve_display.py", "line": null, "side": "RIGHT", "created_at": "2026-02-09T08:28:49+00:00" }, { "id": 2781292222, "user": "user_22bafe4fe1a9", "body": "```suggestion\n \"fpr\": [np.array([0, 0.5, 1])] * 3,\n \"tpr\": [\n```\nMaybe.", "path": "sklearn/metrics/_plot/tests/test_common_curve_display.py", "line": null, "side": "RIGHT", "created_at": "2026-02-09T08:32:56+00:00" }, { "id": 2786892247, "user": "user_d16337ec046b", "body": "This is much better, thank you", "path": "sklearn/metrics/_plot/tests/test_common_curve_display.py", "line": null, "side": "RIGHT", "created_at": "2026-02-10T09:43:20+00:00" } ], "meta": { "languages": [ "py" ], "touches_tests": true, "review_state_summary": { "COMMENTED": 5, "APPROVED": 2 }, "meaningful_comment_count": 10, "has_approval": true, "has_changes_requested": false, "total_review_comments": 10 } } { "_id": "c68c884db4158500", "_schema_version": "1.0", "_cleaned_at": "2026-02-12T07:46:51.904981+00:00", "repo": "scikit-learn/scikit-learn", "repo_url": "https://github.com/scikit-learn/scikit-learn", "license_name": "BSD 3-Clause \"New\" or \"Revised\" License", "license_spdx": "BSD-3-Clause", "pr_number": 33217, "title": "TST Add `CalibrationDisplay` to `test_common_curve_display.py`", "body": "#### [NAME_REDACTED]/PRs\nNoticed when separating test changes out from #30508\n\n#### What does this implement/fix? Explain your changes.\n\n* Adds `CalibrationDisplay` to relevant common tests\n* Improves test names and docstrings such that they fit on one line\n* Removes redundant test (possibly there via bad merge)\n\n#### AI usage disclosure\n\nI used AI assistance for:\n- [ ] Code generation (e.g., when writing an implementation or fixing a bug)\n- [ ] Test/benchmark generation\n- [ ] Documentation (including examples)\n- [ ] Research and understanding\n\n#### Any other comments?\n cc [USER_REDACTED] [USER_REDACTED] in case you have time to review :pray: \n\n", "author": "user_d16337ec046b", "created_at": "2026-02-06T05:13:10+00:00", "merged_at": "2026-02-06T09:29:29+00:00", "base_branch": "main", "head_branch": "tst_plot_common", "additions": 24, "deletions": 47, "changed_files": 1, "files": [ { "filename": "sklearn/metrics/_plot/tests/test_common_curve_display.py", "status": "modified", "additions": 24, "deletions": 47, "changes": 71, "patch": "@@ -34,9 +34,8 @@ def data_binary(data):\n \"Display\",\n [CalibrationDisplay, DetCurveDisplay, PrecisionRecallDisplay, RocCurveDisplay],\n )\n-def test_display_curve_error_classifier(pyplot, data, data_binary, Display):\n- \"\"\"Check that a proper error is raised when only binary classification is\n- supported.\"\"\"\n+def test_display_curve_error_binary_classifier(pyplot, data, data_binary, Display):\n+ \"\"\"Check correct error raised when only binary classification supported.\"\"\"\n X, y = data\n X_binary, y_binary = data_binary\n clf = DecisionTreeClassifier().fit(X, y)\n@@ -110,15 +109,14 @@ def test_display_curve_error_regression(pyplot, data_binary, Display):\n [USER_REDACTED].mark.parametrize(\n \"Display\", [DetCurveDisplay, PrecisionRecallDisplay, RocCurveDisplay]\n )\n-def test_display_curve_error_no_response(\n+def test_display_curve_error_no_response_method(\n pyplot,\n data_binary,\n response_method,\n msg,\n Display,\n ):\n- \"\"\"Check that a proper error is raised when the response method requested\n- is not defined for the given trained classifier.\"\"\"\n+ \"\"\"Check error raised when `response_method` not defined for `estimator`.\"\"\"\n X, y = data_binary\n \n class MyClassifier(ClassifierMixin, BaseEstimator):\n@@ -133,17 +131,17 @@ def fit(self, X, y):\n \n \n [USER_REDACTED].mark.parametrize(\n- \"Display\", [DetCurveDisplay, PrecisionRecallDisplay, RocCurveDisplay]\n+ \"Display\",\n+ [CalibrationDisplay, DetCurveDisplay, PrecisionRecallDisplay, RocCurveDisplay],\n )\n [USER_REDACTED].mark.parametrize(\"constructor_name\", [\"from_estimator\", \"from_predictions\"])\n-def test_display_curve_estimator_name_multiple_calls(\n+def test_display_curve_name_overwritten_by_plot_multiple_calls(\n pyplot,\n data_binary,\n Display,\n constructor_name,\n ):\n- \"\"\"Check that passing `name` when calling `plot` will overwrite the original name\n- in the legend.\"\"\"\n+ \"\"\"Check passing `name` in `plot` overwrites name passed in `from_*` method.\"\"\"\n X, y = data_binary\n clf_name = \"my hand-crafted name\"\n clf = LogisticRegression().fit(X, y)\n@@ -181,11 +179,11 @@ def test_display_curve_estimator_name_multiple_calls(\n ],\n )\n [USER_REDACTED].mark.parametrize(\n- \"Display\", [DetCurveDisplay, PrecisionRecallDisplay, RocCurveDisplay]\n+ \"Display\",\n+ [CalibrationDisplay, DetCurveDisplay, PrecisionRecallDisplay, RocCurveDisplay],\n )\n-def test_display_curve_not_fitted_errors_old_name(pyplot, data_binary, clf, Display):\n- \"\"\"Check that a proper error is raised when the classifier is not\n- fitted.\"\"\"\n+def test_display_curve_not_fitted_errors(pyplot, data_binary, clf, Display):\n+ \"\"\"Check correct error raised when `estimator` is not fitted.\"\"\"\n X, y = data_binary\n # clone since we parametrize the test and the classifier will be fitted\n # when testing the second and subsequent plotting function\n@@ -203,36 +201,11 @@ def test_display_curve_not_fitted_errors_old_name(pyplot, data_binary, clf, Disp\n \n \n [USER_REDACTED].mark.parametrize(\n- \"clf\",\n- [\n- LogisticRegression(),\n- make_pipeline(StandardScaler(), LogisticRegression()),\n- make_pipeline(\n- make_column_transformer((StandardScaler(), [0, 1])), LogisticRegression()\n- ),\n- ],\n-)\n-[USER_REDACTED].mark.parametrize(\"Display\", [RocCurveDisplay])\n-def test_display_curve_not_fitted_errors(pyplot, data_binary, clf, Display):\n- \"\"\"Check that a proper error is raised when the classifier is not fitted.\"\"\"\n- X, y = data_binary\n- # clone since we parametrize the test and the classifier will be fitted\n- # when testing the second and subsequent plotting function\n- model = clone(clf)\n- with pytest.raises(NotFittedError):\n- Display.from_estimator(model, X, y)\n- model.fit(X, y)\n- disp = Display.from_estimator(model, X, y)\n- assert model.__class__.__name__ in disp.line_.get_label()\n- assert disp.name == model.__class__.__name__\n-\n-\n-[USER_REDACTED].mark.parametrize(\n- \"Display\", [DetCurveDisplay, PrecisionRecallDisplay, RocCurveDisplay]\n+ \"Display\",\n+ [CalibrationDisplay, DetCurveDisplay, PrecisionRecallDisplay, RocCurveDisplay],\n )\n def test_display_curve_n_samples_consistency(pyplot, data_binary, Display):\n- \"\"\"Check the error raised when `y_pred` or `sample_weight` have inconsistent\n- length.\"\"\"\n+ \"\"\"Check error raised when `y_pred` or `sample_weight` have inconsistent length.\"\"\"\n X, y = data_binary\n classifier = DecisionTreeClassifier().fit(X, y)\n \n@@ -241,15 +214,20 @@ def test_display_curve_n_samples_consistency(pyplot, data_binary, Display):\n Display.from_estimator(classifier, X[:-2], y)\n with pytest.raises(ValueError, match=msg):\n Display.from_estimator(classifier, X, y[:-2])\n- with pytest.raises(ValueError, match=msg):\n- Display.from_estimator(classifier, X, y, sample_weight=np.ones(X.shape[0] - 2))\n+ # `CalibrationDisplay` does not support `sample_weight`\n+ if Display != CalibrationDisplay:\n+ with pytest.raises(ValueError, match=msg):\n+ Display.from_estimator(\n+ classifier, X, y, sample_weight=np.ones(X.shape[0] - 2)\n+ )\n \n \n [USER_REDACTED].mark.parametrize(\n- \"Display\", [DetCurveDisplay, PrecisionRecallDisplay, RocCurveDisplay]\n+ \"Display\",\n+ [CalibrationDisplay, DetCurveDisplay, PrecisionRecallDisplay, RocCurveDisplay],\n )\n def test_display_curve_error_pos_label(pyplot, data_binary, Display):\n- \"\"\"Check consistence of error message when `pos_label` should be specified.\"\"\"\n+ \"\"\"Check consistency of error message when `pos_label` should be specified.\"\"\"\n X, y = data_binary\n y = y + 10\n \n@@ -302,7 +280,6 @@ class SubclassOfDisplay(Display):\n assert isinstance(curve, SubclassOfDisplay)\n \n \n-# TODO(1.10): Remove once deprecated in all Displays\n [USER_REDACTED].mark.parametrize(\n \"Display, display_kwargs\",\n [" } ], "reviews": [ { "id": 3760845209, "user": "user_d16337ec046b", "state": "COMMENTED", "body": null, "submitted_at": "2026-02-06T05:15:57+00:00" }, { "id": 3761796631, "user": "user_5819d17296ee", "state": "APPROVED", "body": "LGTM!", "submitted_at": "2026-02-06T09:29:21+00:00" } ], "review_comments": [ { "id": 2772331826, "user": "user_d16337ec046b", "body": "This test is repeated, see above `test_display_curve_not_fitted_errors_old_name` which I have renamed to`test_display_curve_not_fitted_errors`", "path": "sklearn/metrics/_plot/tests/test_common_curve_display.py", "line": 216, "side": "LEFT", "created_at": "2026-02-06T05:15:57+00:00" } ], "meta": { "languages": [ "py" ], "touches_tests": true, "review_state_summary": { "COMMENTED": 1, "APPROVED": 1 }, "meaningful_comment_count": 1, "has_approval": true, "has_changes_requested": false, "total_review_comments": 1 } } { "_id": "b887fd0e281da03f", "_schema_version": "1.0", "_cleaned_at": "2026-02-12T07:46:51.906967+00:00", "repo": "scikit-learn/scikit-learn", "repo_url": "https://github.com/scikit-learn/scikit-learn", "license_name": "BSD 3-Clause \"New\" or \"Revised\" License", "license_spdx": "BSD-3-Clause", "pr_number": 33203, "title": "CI Have the name of the failing build in the tracking issue", "body": "\n\n#### [NAME_REDACTED]/PRs\n\nFix issue raised in https://github.com/[USER_REDACTED]n/scikit-learn/issues/33152#issuecomment-3833793227\n\n#### What does this implement/fix? Explain your changes.\n\nGet the name of the failing build in the tracking issue name, even if the build is not in the job matrix.\n\n#### AI usage disclosure\n\nI used AI assistance for:\n- [ ] Code generation (e.g., when writing an implementation or fixing a bug)\n- [ ] Test/benchmark generation\n- [ ] Documentation (including examples)\n- [x] Research and understanding\n\n#### Any other comments?\n\nApparently there is no way to access the job name from the job steps, so I used an env variable containing the job name as a workaround. \n\n", "author": "user_afd8fdca88a2", "created_at": "2026-02-03T16:18:41+00:00", "merged_at": "2026-02-05T18:10:49+00:00", "base_branch": "main", "head_branch": "CI_name_tracking_issue", "additions": 19, "deletions": 6, "changed_files": 1, "files": [ { "filename": ".github/workflows/unit-tests.yml", "status": "modified", "additions": 19, "deletions": 6, "changes": 25, "patch": "@@ -227,12 +227,21 @@ jobs:\n - name: Checkout\n uses: actions/checkout@v6\n \n+ # This step is necessary to access the job name the same way in both matrix and\n+ # non-matrix jobs (like free-threaded or scipy-dev builds).\n+ - name: Set JOB_NAME variable\n+ shell: bash\n+ run: |\n+ if [[ -z \"$JOB_NAME\" ]]; then\n+ echo \"JOB_NAME=${{ matrix.name }}\" >> $GITHUB_ENV\n+ fi\n+\n - name: Create cache for ccache\n uses: actions/cache@v5\n with:\n path: ${{ env.CCACHE_DIR }}\n- key: ccache-v1-${{ matrix.name }}-${{ hashFiles('**/*.pyx*', '**/*.pxd*', '**/*.pxi*', '**/*.h', '**/*.c', '**/*.cpp', format('{0}', matrix.LOCK_FILE)) }}\n- restore-keys: ccache-${{ matrix.name }}\n+ key: ccache-v1-${{ env.JOB_NAME }}-${{ hashFiles('**/*.pyx*', '**/*.pxd*', '**/*.pxi*', '**/*.h', '**/*.c', '**/*.cpp', format('{0}', env.LOCK_FILE)) }}\n+ restore-keys: ccache-${{ env.JOB_NAME }}\n \n - name: Set up conda\n uses: conda-incubator/setup-miniconda@v3\n@@ -286,15 +295,15 @@ jobs:\n pip install defusedxml PyGithub\n python maint_tools/update_tracking_issue.py \\\n ${{ secrets.BOT_GITHUB_TOKEN }} \\\n- \"$GITHUB_WORKFLOW ${{ matrix.name }}\" \\\n+ \"$GITHUB_WORKFLOW $JOB_NAME\" \\\n \"$GITHUB_REPOSITORY\" \\\n https://github.com/$GITHUB_REPOSITORY/actions/runs/$GITHUB_RUN_ID \\\n --junit-file $TEST_DIR/$JUNITXML \\\n --auto-close false \\\n- --job-name \"${{ matrix.name }}\"\n+ --job-name \"$JOB_NAME\"\n \n free-threaded:\n- name: Linux x86-64 pylatest_free_threaded\n+ name: &free-threaded-job-name Linux x86-64 pylatest_free_threaded\n runs-on: ubuntu-latest\n needs: [lint, retrieve-commit-message, retrieve-selected-tests]\n if: contains(needs.retrieve-commit-message.outputs.message, '[free-threaded]') || github.event_name == 'schedule' || github.event_name == 'workflow_dispatch'\n@@ -304,10 +313,12 @@ jobs:\n COVERAGE: false\n # Disable pytest-xdist to use multiple cores for stress-testing with pytest-run-parallel\n PYTEST_XDIST_VERSION: none\n+ # To be able to access the job name in the steps, it must be set as an env variable.\n+ JOB_NAME: *free-threaded-job-name\n steps: *unit-tests-steps\n \n scipy-dev:\n- name: Linux x86-64 pylatest_pip_scipy_dev\n+ name: &scipy-dev-job-name Linux x86-64 pylatest_pip_scipy_dev\n runs-on: ubuntu-22.04\n needs: [lint, retrieve-commit-message, retrieve-selected-tests]\n if: contains(needs.retrieve-commit-message.outputs.message, '[scipy-dev]') || github.event_name == 'schedule' || github.event_name == 'workflow_dispatch'\n@@ -316,4 +327,6 @@ jobs:\n LOCK_FILE: build_tools/azure/pylatest_pip_scipy_dev_linux-64_conda.lock\n SKLEARN_WARNINGS_AS_ERRORS: 1\n CHECK_PYTEST_SOFT_DEPENDENCY: true\n+ # To be able to access the job name in the steps, it must be set as an env variable.\n+ JOB_NAME: *scipy-dev-job-name\n steps: *unit-tests-steps" } ], "reviews": [ { "id": 3746730569, "user": "user_fca2535bcd49", "state": "COMMENTED", "body": null, "submitted_at": "2026-02-03T17:58:54+00:00" }, { "id": 3750092515, "user": "user_afd8fdca88a2", "state": "COMMENTED", "body": null, "submitted_at": "2026-02-04T09:58:10+00:00" }, { "id": 3752283250, "user": "user_fca2535bcd49", "state": "COMMENTED", "body": "A few comments", "submitted_at": "2026-02-04T17:26:41+00:00" }, { "id": 3757507611, "user": "user_afd8fdca88a2", "state": "COMMENTED", "body": null, "submitted_at": "2026-02-05T14:35:01+00:00" }, { "id": 3757920794, "user": "user_afd8fdca88a2", "state": "COMMENTED", "body": null, "submitted_at": "2026-02-05T15:44:45+00:00" }, { "id": 3758017150, "user": "user_fca2535bcd49", "state": "COMMENTED", "body": null, "submitted_at": "2026-02-05T16:02:23+00:00" }, { "id": 3758054217, "user": "user_fca2535bcd49", "state": "COMMENTED", "body": null, "submitted_at": "2026-02-05T16:08:52+00:00" }, { "id": 3758058485, "user": "user_fca2535bcd49", "state": "COMMENTED", "body": null, "submitted_at": "2026-02-05T16:09:34+00:00" }, { "id": 3758061241, "user": "user_fca2535bcd49", "state": "APPROVED", "body": "Other than the two comments, looks good to me, thanks!", "submitted_at": "2026-02-05T16:10:04+00:00" }, { "id": 3758197585, "user": "user_afd8fdca88a2", "state": "COMMENTED", "body": null, "submitted_at": "2026-02-05T16:33:56+00:00" }, { "id": 3758642715, "user": "user_fca2535bcd49", "state": "COMMENTED", "body": null, "submitted_at": "2026-02-05T18:11:40+00:00" } ], "review_comments": [ { "id": 2760310196, "user": "user_fca2535bcd49", "body": "Actually I think we have a similar problem in other places like the ccache step, we use `${{ matrix.name }}` but actually this is empty for non-standard jobs (e.g. free-threaded).\n\nI am wondering if one work-around would be to have a step early on that defines the env variable `JOB_NAME` by [NAME_REDACTED] `GITHUB_ENV` and then using `env.JOB_NAME` everywhere?", "path": ".github/workflows/unit-tests.yml", "line": null, "side": "RIGHT", "created_at": "2026-02-03T17:58:54+00:00" }, { "id": 2763162604, "user": "user_afd8fdca88a2", "body": "Yes good point, I noticed `${{ matrix.LOCK_FILE }}` is also used, I'll try to add a strep to put both variables in env.", "path": ".github/workflows/unit-tests.yml", "line": null, "side": "RIGHT", "created_at": "2026-02-04T09:58:10+00:00" }, { "id": 2765083708, "user": "user_fca2535bcd49", "body": "Does the `$JOB_NAME` actually do something, this seems weird I would expect a `${{ }}` syntax is needed i.e. something like\n```suggestion\n key: ccache-v1-${{ env.JOB_NAME }}-${{ hashFiles('**/*.pyx*', '**/*.pxd*', '**/*.pxi*', '**/*.h', '**/*.c', '**/*.cpp', format('{0}', env.LOCK_FILE)) }}\n```", "path": ".github/workflows/unit-tests.yml", "line": null, "side": "RIGHT", "created_at": "2026-02-04T17:13:25+00:00" }, { "id": 2765085416, "user": "user_fca2535bcd49", "body": "similar comment, I would expect something like this:\n```suggestion\n restore-keys: ccache-${{ env.JOB_NAME }}\n```", "path": ".github/workflows/unit-tests.yml", "line": null, "side": "RIGHT", "created_at": "2026-02-04T17:13:52+00:00" }, { "id": 2765116993, "user": "user_fca2535bcd49", "body": "I am wondering whether using YAML anchor would be a good idea or not, something like (untested)\n```yaml\nname: Linux x86-64 pylatest_free_threaded &free-threaded-job-name\n\nenv:\n JOB_NAME: *free-threaded-job-name\n```\n\nThis may be overkill to be honest not 100% sure ...\n\nMaybe adding a comment would be useful (not sure where exactly) that setting the JOB_VARIABLE variable is needed to overcome a limitation of GitHub this is a limitation of GitHub with a link to a somewhat useful source?", "path": ".github/workflows/unit-tests.yml", "line": null, "side": "RIGHT", "created_at": "2026-02-04T17:21:50+00:00" }, { "id": 2765121885, "user": "user_fca2535bcd49", "body": "Explain somewhere that this is needed to treat matrix jobs and separate jobs (like free-threaded or debian-32) in a uniform manner.", "path": ".github/workflows/unit-tests.yml", "line": null, "side": "RIGHT", "created_at": "2026-02-04T17:23:11+00:00" }, { "id": 2765136193, "user": "user_fca2535bcd49", "body": "I think this should work but please double-check\n```suggestion\n if [[ -z \"$JOB_NAME\" ]]; then\n\t echo \"JOB_NAME=${{ matrix.name }}\" >> $GITHUB_ENV\n fi\n```\n\nThe LOCK_FILE part is not needed because of the magical `env: ${{ matrix }}` which actually set the environment variables automatically. I copied this from joblib, not sure if this is documented somewhere ...", "path": ".github/workflows/unit-tests.yml", "line": null, "side": "RIGHT", "created_at": "2026-02-04T17:26:14+00:00" }, { "id": 2769497176, "user": "user_afd8fdca88a2", "body": "I believe both work equally but I haven't looked to verify.", "path": ".github/workflows/unit-tests.yml", "line": null, "side": "RIGHT", "created_at": "2026-02-05T14:35:01+00:00" }, { "id": 2769844910, "user": "user_afd8fdca88a2", "body": "I did not find a nice and clean source, my conclusion came from experiments on my fork and discussions with chatbots, but looking for a ref I stumbled upon a [3rd party action](https://github.com/[USER_REDACTED]n/actions--context) which provides the job name as an env variable. Not sure it's worth adding it though.", "path": ".github/workflows/unit-tests.yml", "line": null, "side": "RIGHT", "created_at": "2026-02-05T15:44:45+00:00" }, { "id": 2769930786, "user": "user_fca2535bcd49", "body": "Probably not worth depending on a 3rd party action for such a small functionality.", "path": ".github/workflows/unit-tests.yml", "line": null, "side": "RIGHT", "created_at": "2026-02-05T16:02:23+00:00" }, { "id": 2769962769, "user": "user_fca2535bcd49", "body": "Have you tried doing it the other way around. I would find it a tiny bit less ugly (first real content, then quirky thing for the anchor ...)\n\n```suggestion\n name: Linux x86-64 pylatest_free_threaded &free-threaded-job-name\n```", "path": ".github/workflows/unit-tests.yml", "line": 306, "side": "RIGHT", "created_at": "2026-02-05T16:08:52+00:00" }, { "id": 2769966666, "user": "user_fca2535bcd49", "body": "In case that works with YAML anchor and GitHub restricted implementation of them\n```suggestion\n name: Linux x86-64 pylatest_pip_scipy_dev &scipy-dev-job-name \n```", "path": ".github/workflows/unit-tests.yml", "line": 321, "side": "RIGHT", "created_at": "2026-02-05T16:09:34+00:00" }, { "id": 2770091294, "user": "user_afd8fdca88a2", "body": "I tried but then ruff got angry at me :\n```\ncheck yaml...............................................................Failed\n- hook id: check-yaml\n- exit code: 1\n\nfound undefined alias 'free-threaded-job-name'\n in \".github/workflows/unit-tests.yml\", line 316, column 17\n```", "path": ".github/workflows/unit-tests.yml", "line": 306, "side": "RIGHT", "created_at": "2026-02-05T16:33:56+00:00" }, { "id": 2770484184, "user": "user_fca2535bcd49", "body": "OK, fair enough, it's more pre-commit and its check-yaml check than ruff but let's keep it like this anyway :shrug:", "path": ".github/workflows/unit-tests.yml", "line": 306, "side": "RIGHT", "created_at": "2026-02-05T18:11:40+00:00" } ], "meta": { "languages": [ "yml" ], "touches_tests": false, "review_state_summary": { "COMMENTED": 10, "APPROVED": 1 }, "meaningful_comment_count": 14, "has_approval": true, "has_changes_requested": false, "total_review_comments": 14 } } { "_id": "2b2e37fe7e5df887", "_schema_version": "1.0", "_cleaned_at": "2026-02-12T07:46:51.909963+00:00", "repo": "scikit-learn/scikit-learn", "repo_url": "https://github.com/scikit-learn/scikit-learn", "license_name": "BSD 3-Clause \"New\" or \"Revised\" License", "license_spdx": "BSD-3-Clause", "pr_number": 33202, "title": "FIX `n_classes` in DecisionBoundaryDisplay with custom estimators", "body": "\n\n#### [NAME_REDACTED]/PRs\n\nFixes https://github.com/[USER_REDACTED]n/scikit-learn/issues/33194\n\n#### What does this implement/fix? Explain your changes.\nAdds inferring `n_classes` from `type_of_target` and raises an error if it still can't be inferred.\n\n#### AI usage disclosure\n\nI used AI assistance for:\n- [ ] Code generation (e.g., when writing an implementation or fixing a bug)\n- [x] Test/benchmark generation\n- [ ] Documentation (including examples)\n- [ ] Research and understanding\n\n#### Any other comments?\nI also adapted the example to show the correct colormap (as `viridis` is no longer the default).\n\n", "author": "user_34a090906ca4", "created_at": "2026-02-03T10:24:14+00:00", "merged_at": "2026-02-05T05:33:37+00:00", "base_branch": "main", "head_branch": "fix_DecisionBoundaryDisplay_custom_estimator", "additions": 136, "deletions": 16, "changed_files": 4, "files": [ { "filename": "doc/whats_new/upcoming_changes/sklearn.inspection/33202.fix.rst", "status": "added", "additions": 4, "deletions": 0, "changes": 4, "patch": "@@ -0,0 +1,4 @@\n+- In :class:`inspection.DecisionBoundaryDisplay`, `n_classes` is now inferred more\n+ robustly from the estimator. If it fails for custom estimators, a comprehensive error\n+ message is shown.\n+ By :user:`[NAME_REDACTED] `." }, { "filename": "examples/cluster/plot_inductive_clustering.py", "status": "modified", "additions": 9, "deletions": 3, "changes": 12, "patch": "@@ -25,7 +25,7 @@\n \n import matplotlib.pyplot as plt\n \n-from sklearn.base import BaseEstimator, clone\n+from sklearn.base import BaseEstimator, ClusterMixin, clone\n from sklearn.cluster import AgglomerativeClustering\n from sklearn.datasets import make_blobs\n from sklearn.ensemble import RandomForestClassifier\n@@ -50,7 +50,7 @@ def _classifier_has(attr):\n )\n \n \n-class InductiveClusterer(BaseEstimator):\n+class InductiveClusterer(ClusterMixin, BaseEstimator):\n def __init__(self, clusterer, classifier):\n self.clusterer = clusterer\n self.classifier = classifier\n@@ -60,6 +60,7 @@ def fit(self, X, y=None):\n self.classifier_ = clone(self.classifier)\n y = self.clusterer_.fit_predict(X)\n self.classifier_.fit(X, y)\n+ self.labels_ = y\n return self\n \n [USER_REDACTED]_if(_classifier_has(\"predict\"))\n@@ -122,7 +123,12 @@ def plot_scatter(X, color, alpha=0.5):\n \n # Plotting decision regions\n DecisionBoundaryDisplay.from_estimator(\n- inductive_learner, X, response_method=\"predict\", alpha=0.4, ax=ax\n+ inductive_learner,\n+ X,\n+ response_method=\"predict\",\n+ multiclass_colors=\"viridis\",\n+ alpha=0.4,\n+ ax=ax,\n )\n plt.title(\"Classify unknown instances\")" }, { "filename": "sklearn/inspection/_plot/decision_boundary.py", "status": "modified", "additions": 26, "deletions": 11, "changes": 37, "patch": "@@ -12,6 +12,7 @@\n from sklearn.utils._optional_dependencies import check_matplotlib_support\n from sklearn.utils._response import _get_response_values\n from sklearn.utils._set_output import _get_adapter_from_container\n+from sklearn.utils.multiclass import type_of_target\n from sklearn.utils.validation import (\n _is_arraylike_not_scalar,\n _num_features,\n@@ -576,6 +577,31 @@ def from_estimator(\n encoder.classes_ = estimator.classes_\n response = encoder.transform(response)\n \n+ # infer n_classes from the estimator\n+ if (\n+ class_of_interest is not None\n+ or is_regressor(estimator)\n+ or is_outlier_detector(estimator)\n+ ):\n+ n_classes = 2\n+ elif is_classifier(estimator) and hasattr(estimator, \"classes_\"):\n+ n_classes = len(estimator.classes_)\n+ elif is_clusterer(estimator) and hasattr(estimator, \"labels_\"):\n+ n_classes = len(np.unique(estimator.labels_))\n+ else:\n+ target_type = type_of_target(response)\n+ if target_type in (\"binary\", \"continuous\"):\n+ n_classes = 2\n+ elif target_type == \"multiclass\":\n+ n_classes = len(np.unique(response))\n+ else:\n+ raise ValueError(\n+ \"Number of classes or labels cannot be inferred from \"\n+ f\"{estimator.__class__.__name__}. Please make sure your estimator \"\n+ \"follows scikit-learn's estimator API as described here: \"\n+ \"https://scikit-learn.org/stable/developers/develop.html#rolling-your-own-estimator\"\n+ )\n+\n if response.ndim == 1:\n response = response.reshape(*xx0.shape)\n else:\n@@ -591,17 +617,6 @@ def from_estimator(\n else:\n response = response.reshape(*xx0.shape, response.shape[-1])\n \n- if (\n- class_of_interest is not None\n- or is_regressor(estimator)\n- or is_outlier_detector(estimator)\n- ):\n- n_classes = 2\n- elif is_classifier(estimator):\n- n_classes = len(estimator.classes_)\n- elif is_clusterer(estimator):\n- n_classes = len(np.unique(estimator.labels_))\n-\n if xlabel is None:\n xlabel = X.columns[0] if hasattr(X, \"columns\") else \"\"" }, { "filename": "sklearn/inspection/_plot/tests/test_boundary_decision_display.py", "status": "modified", "additions": 97, "deletions": 2, "changes": 99, "patch": "@@ -19,7 +19,8 @@\n from sklearn.inspection import DecisionBoundaryDisplay\n from sklearn.inspection._plot.decision_boundary import _check_boundary_response_method\n from sklearn.linear_model import LogisticRegression\n-from sklearn.preprocessing import scale\n+from sklearn.pipeline import Pipeline\n+from sklearn.preprocessing import StandardScaler, scale\n from sklearn.tree import DecisionTreeClassifier, DecisionTreeRegressor\n from sklearn.utils._testing import (\n _convert_container,\n@@ -703,6 +704,34 @@ def test_multiclass_colors_cmap(\n # assert len(disp.surface_.levels) >= disp.n_classes\n \n \n+# estimator classes for non-regression test cases for issue #33194\n+class CustomBinaryEstimator(BaseEstimator):\n+ def fit(self, X, y):\n+ self.fitted_ = True\n+ return self\n+\n+ def predict(self, X):\n+ return np.arange(X.shape[0]) % 2\n+\n+\n+class CustomMulticlassEstimator(BaseEstimator):\n+ def fit(self, X, y):\n+ self.fitted_ = True\n+ return self\n+\n+ def predict(self, X):\n+ return np.arange(X.shape[0]) % 7\n+\n+\n+class CustomContinuousEstimator(BaseEstimator):\n+ def fit(self, X, y):\n+ self.fitted_ = True\n+ return self\n+\n+ def predict(self, X):\n+ return np.arange(X.shape[0]) * 0.5\n+\n+\n [USER_REDACTED].mark.parametrize(\n \"estimator, n_blobs, expected_n_classes\",\n [\n@@ -712,12 +741,57 @@ def test_multiclass_colors_cmap(\n (KMeans(n_clusters=2, random_state=0), 2, 2),\n (DecisionTreeRegressor(random_state=0), 7, 2),\n (IsolationForest(random_state=0), 7, 2),\n+ (CustomBinaryEstimator(), 2, 2),\n+ (CustomMulticlassEstimator(), 7, 7),\n+ (CustomContinuousEstimator(), 7, 2),\n+ (\n+ Pipeline(\n+ [\n+ (\"scale\", StandardScaler()),\n+ (\"dt\", DecisionTreeClassifier(random_state=0)),\n+ ]\n+ ),\n+ 7,\n+ 7,\n+ ),\n+ # non-regression test case for issue #33194\n+ (\n+ Pipeline(\n+ [\n+ (\"scale\", StandardScaler()),\n+ (\"kmeans\", KMeans(n_clusters=7, random_state=0)),\n+ ]\n+ ),\n+ 7,\n+ 7,\n+ ),\n+ (\n+ Pipeline(\n+ [\n+ (\"scale\", StandardScaler()),\n+ (\"reg\", DecisionTreeRegressor(random_state=0)),\n+ ]\n+ ),\n+ 7,\n+ 2,\n+ ),\n+ (\n+ Pipeline(\n+ [\n+ (\"scale\", StandardScaler()),\n+ (\"kmeans\", IsolationForest(random_state=0)),\n+ ]\n+ ),\n+ 7,\n+ 2,\n+ ),\n ],\n )\n def test_n_classes_attribute(pyplot, estimator, n_blobs, expected_n_classes):\n \"\"\"Check that `n_classes` is set correctly.\n \n- Introduced in https://github.com/[USER_REDACTED]n/scikit-learn/pull/33015\"\"\"\n+ Introduced in https://github.com/[USER_REDACTED]n/scikit-learn/pull/33015.\n+ \"\"\"\n \n X, y = make_blobs(n_samples=150, centers=n_blobs, n_features=2, random_state=42)\n clf = estimator.fit(X, y)\n@@ -731,6 +805,27 @@ def test_n_classes_attribute(pyplot, estimator, n_blobs, expected_n_classes):\n assert disp_coi.n_classes == 2\n \n \n+def test_n_classes_raises_if_not_inferrable(pyplot):\n+ \"\"\"Check behaviour if `n_classes` can't be inferred.\n+\n+ Non-regression test for issue #33194.\n+ \"\"\"\n+\n+ class CustomUnknownEstimator(BaseEstimator):\n+ def fit(self, X, y):\n+ self.fitted_ = True\n+ return self\n+\n+ def predict(self, X):\n+ return np.array(0)\n+\n+ X, y = load_iris_2d_scaled()\n+ est = CustomUnknownEstimator().fit(X, y)\n+ msg = \"Number of classes or labels cannot be inferred from CustomUnknownEstimator\"\n+ with pytest.raises(ValueError, match=msg):\n+ DecisionBoundaryDisplay.from_estimator(est, X, response_method=\"predict\")\n+\n+\n def test_cmap_and_colors_logic(pyplot):\n \"\"\"Check the handling logic for `cmap` and `colors`.\"\"\"\n X, y = load_iris_2d_scaled()" } ], "reviews": [ { "id": 3744444392, "user": "user_34a090906ca4", "state": "COMMENTED", "body": null, "submitted_at": "2026-02-03T10:28:04+00:00" }, { "id": 3744455426, "user": "user_34a090906ca4", "state": "COMMENTED", "body": null, "submitted_at": "2026-02-03T10:30:12+00:00" }, { "id": 3748096673, "user": "user_d16337ec046b", "state": "APPROVED", "body": "LGTM, just some nits", "submitted_at": "2026-02-03T23:18:43+00:00" }, { "id": 3750015913, "user": "user_34a090906ca4", "state": "COMMENTED", "body": null, "submitted_at": "2026-02-04T09:41:22+00:00" }, { "id": 3750094718, "user": "user_34a090906ca4", "state": "COMMENTED", "body": null, "submitted_at": "2026-02-04T09:58:40+00:00" }, { "id": 3750260420, "user": "user_34a090906ca4", "state": "COMMENTED", "body": null, "submitted_at": "2026-02-04T10:32:32+00:00" }, { "id": 3750987805, "user": "user_501030d9d7e3", "state": "COMMENTED", "body": null, "submitted_at": "2026-02-04T13:09:31+00:00" }, { "id": 3752259568, "user": "user_fca2535bcd49", "state": "COMMENTED", "body": "Honestly I haven't looked at the changes in detail, but it seems to mostly make sense.\n\nI am going to merge this one, to reduce my stress levels of having CircleCI red on main for a few days 😅.\n\nFollow-up PR to tweak the behaviour would be more than welcome if things can be improved.", "submitted_at": "2026-02-05T05:33:25+00:00" }, { "id": 3754684208, "user": "user_d16337ec046b", "state": "COMMENTED", "body": null, "submitted_at": "2026-02-05T05:37:08+00:00" }, { "id": 3754701208, "user": "user_fca2535bcd49", "state": "COMMENTED", "body": null, "submitted_at": "2026-02-05T05:44:38+00:00" }, { "id": 3755317752, "user": "user_34a090906ca4", "state": "COMMENTED", "body": null, "submitted_at": "2026-02-05T08:40:56+00:00" }, { "id": 3755463110, "user": "user_34a090906ca4", "state": "COMMENTED", "body": null, "submitted_at": "2026-02-05T09:07:57+00:00" } ], "review_comments": [ { "id": 2758366573, "user": "user_34a090906ca4", "body": "I found the `KMeans-Pipeline` below as an example where the `type_of_target` inference is triggered, but I suspect this might actually not be the intended behaviour of `Pipeline`, i.e., shouldn't it be recognized as `is_clusterer`?", "path": "sklearn/inspection/_plot/tests/test_boundary_decision_display.py", "line": 757, "side": "RIGHT", "created_at": "2026-02-03T10:28:04+00:00" }, { "id": 2758374995, "user": "user_34a090906ca4", "body": "I had to move inferring `n_classes` up here before the `response` reshaping, so that `type_of_target` works properly.", "path": "sklearn/inspection/_plot/decision_boundary.py", "line": null, "side": "RIGHT", "created_at": "2026-02-03T10:30:12+00:00" }, { "id": 2761416220, "user": "user_d16337ec046b", "body": "```suggestion\n Non-regression test for issue #33194.\n \"\"\"\n```\nnit", "path": "sklearn/inspection/_plot/tests/test_boundary_decision_display.py", "line": null, "side": "RIGHT", "created_at": "2026-02-03T23:06:03+00:00" }, { "id": 2761423015, "user": "user_d16337ec046b", "body": "```suggestion\n f\"`{estimator.__class__.__name__}`. Please make sure your estimator \"\n```\nnit, sorry", "path": "sklearn/inspection/_plot/decision_boundary.py", "line": 600, "side": "RIGHT", "created_at": "2026-02-03T23:07:42+00:00" }, { "id": 2761454901, "user": "user_d16337ec046b", "body": "```python\nPipeline(\n [\n (\"scale\", StandardScaler()),\n (\"kmeans\", KMeans(n_clusters=7, random_state=0)),\n ]\n).__sklearn_tags__()\n```\n\ngives\n\n```\nOut[13]: Tags(estimator_type='clusterer', target_tags=TargetTags(required=False, one_d_labels=False, two_d_labels=False, positive_only=False, multi_output=False, single_output=True), transformer_tags=TransformerTags(preserves_dtype=['float64']), classifier_tags=None, regressor_tags=None, array_api_support=False, no_validation=False, non_deterministic=False, requires_fit=True, _skip_test=False, input_tags=InputTags(one_d_array=False, two_d_array=True, three_d_array=False, sparse=False, categorical=False, string=False, dict=False, positive_only=False, allow_nan=False, pairwise=False))\n```\n\nSo it should be recognized?", "path": "sklearn/inspection/_plot/tests/test_boundary_decision_display.py", "line": 757, "side": "RIGHT", "created_at": "2026-02-03T23:16:02+00:00" }, { "id": 2761458711, "user": "user_d16337ec046b", "body": "```suggestion\n Introduced in https://github.com/[USER_REDACTED]n/scikit-learn/pull/33015.\n \"\"\"\n```", "path": "sklearn/inspection/_plot/tests/test_boundary_decision_display.py", "line": null, "side": "RIGHT", "created_at": "2026-02-03T23:17:05+00:00" }, { "id": 2763093181, "user": "user_34a090906ca4", "body": "Then maybe it doesn't fulfil the other condition (i.e., define `self.labels_`, similar to `self.classes_` for classifiers). I'll have a look.", "path": "sklearn/inspection/_plot/tests/test_boundary_decision_display.py", "line": 757, "side": "RIGHT", "created_at": "2026-02-04T09:41:22+00:00" }, { "id": 2763164807, "user": "user_34a090906ca4", "body": "I would leave this as it is because the estimator name is used like this in many other error messages as well ([here for example](https://github.com/[USER_REDACTED]n/scikit-learn/blob/0da13ec15b37e60db9935a23e4f3b48526cb5c5b/sklearn/utils/validation.py#L2272)) and the test would also need to be adpted.", "path": "sklearn/inspection/_plot/decision_boundary.py", "line": 600, "side": "RIGHT", "created_at": "2026-02-04T09:58:40+00:00" }, { "id": 2763311828, "user": "user_34a090906ca4", "body": "Indeed. `classes_` is set if the last estimator is a classifier, but not `labels_` for clusterers. The `type_of_target` approach works here, so I would not mix this with this issue. \n\nI also noticed that the docs don't correspond to the docstring, for example, the docstring contains \n```\nAttributes\n ----------\n named_steps : :class:`~sklearn.utils.Bunch`\n Dictionary-like object, with the following attributes.\n Read-only attribute to access any step parameter by [NAME_REDACTED] are step names and values are steps parameters.\n\n classes_ : ndarray of shape (n_classes,)\n The classes labels. Only exist if the last step of the pipeline is a\n classifier.\n\n n_features_in_ : int\n Number of features seen during :term:`fit`. Only defined if the\n underlying first estimator in `steps` exposes such an attribute\n when fit.\n\n .. versionadded:: 0.24\n\n feature_names_in_ : ndarray of shape (`n_features_in_`,)\n Names of features seen during :term:`fit`. Only defined if the\n underlying estimator exposes such an attribute when fit.\n\n .. versionadded:: 1.0\n```\nand the docs look like this\n\"image\"\n\nDo you think this is important enough to open a separate issue?", "path": "sklearn/inspection/_plot/tests/test_boundary_decision_display.py", "line": 757, "side": "RIGHT", "created_at": "2026-02-04T10:32:32+00:00" }, { "id": 2763948987, "user": "user_501030d9d7e3", "body": "That looks odd and unexpected.\n\nWhat I found is that the rendered docs may be pulled from the property methods with the same name. The summary line of the property methods are the same as on the website.", "path": "sklearn/inspection/_plot/tests/test_boundary_decision_display.py", "line": 757, "side": "RIGHT", "created_at": "2026-02-04T13:09:31+00:00" }, { "id": 2765062853, "user": "user_fca2535bcd49", "body": "This modification does not seem to be needed to make the example run, can you explain a bit more?\n\nLooking at the code it goes to a different branch `is_clusterer` but the `type_of_target` fall-back branch seems to work fine.", "path": "examples/cluster/plot_inductive_clustering.py", "line": 53, "side": "RIGHT", "created_at": "2026-02-04T17:08:16+00:00" }, { "id": 2767218621, "user": "user_fca2535bcd49", "body": "This modification doesn't seem to be needed to make the example run, can you explain a bit more why you changed it?", "path": "examples/cluster/plot_inductive_clustering.py", "line": 63, "side": "RIGHT", "created_at": "2026-02-05T05:32:21+00:00" }, { "id": 2767229884, "user": "user_d16337ec046b", "body": "Yes, `type_of_target` fallback would work, but since we do recommend use of our mixins for users developing their own estimators, so we thought that it would be nice if our examples also demonstrated this...", "path": "examples/cluster/plot_inductive_clustering.py", "line": 53, "side": "RIGHT", "created_at": "2026-02-05T05:37:08+00:00" }, { "id": 2767245901, "user": "user_fca2535bcd49", "body": "Fair enough, the code looks a tiny bit more cryptic and the previous code was still working but nothing really crucial :shrug:.", "path": "examples/cluster/plot_inductive_clustering.py", "line": 53, "side": "RIGHT", "created_at": "2026-02-05T05:44:37+00:00" }, { "id": 2767760363, "user": "user_34a090906ca4", "body": "Yes, sorry, I didn't include this in the description, but in the issue we discussed that the example should also follow our recommendations for developing estimators, namely inheriting from the right `Mixin` and defining `self.labels_` for clusterers. But since we don't enforce this, we also added the fallback using `type_of_target`, which would also have handled this example without the modifications.\n\n([USER_REDACTED], are you saying our API makes users write cryptic code? ;) )", "path": "examples/cluster/plot_inductive_clustering.py", "line": 53, "side": "RIGHT", "created_at": "2026-02-05T08:40:56+00:00" }, { "id": 2767865861, "user": "user_34a090906ca4", "body": "It seems to be even more restrictive and only prints the `property` docstring until the first `.`, because the one for `classes` also says:\n>\"\"\"The classes labels. Only exist if the last step is a classifier.\"\"\"\n\nIf I remove the first full stop, the whole line is shown. :shrug:", "path": "sklearn/inspection/_plot/tests/test_boundary_decision_display.py", "line": 757, "side": "RIGHT", "created_at": "2026-02-05T09:07:57+00:00" } ], "meta": { "languages": [ "py", "rst" ], "touches_tests": true, "review_state_summary": { "COMMENTED": 11, "APPROVED": 1 }, "meaningful_comment_count": 16, "has_approval": true, "has_changes_requested": false, "total_review_comments": 16 } } { "_id": "938ec3c170405ead", "_schema_version": "1.0", "_cleaned_at": "2026-02-12T07:46:51.918951+00:00", "repo": "scikit-learn/scikit-learn", "repo_url": "https://github.com/scikit-learn/scikit-learn", "license_name": "BSD 3-Clause \"New\" or \"Revised\" License", "license_spdx": "BSD-3-Clause", "pr_number": 33175, "title": "CI Use a virtual package spec file for `conda-lock` solving", "body": "#### [NAME_REDACTED]/PRs\n\nCloses #33106\n\n#### What does this implement/fix? Explain your changes.\nThis modifies the environment solving/creation of lockfile for our CUDA CI jobs. Newer versions of packages like PyTorch require a virtual conda package called `__cuda` which signals that CUDA is available on the system (same mechanism exists for `__glibc`). This means that solving the environment on a machine that does not have CUDA (our CI job to update the lockfile, a developers local machine, etc) is not possible. I think this is why we were \"stuck\" on a fairly old version of PyTorch (older versions didn't have this dependency). I noticed this problem only when trying to add a new package to the environment (`cuvs`), which is needed for #33096. I think for `cuvs` there are no versions (or only super old ones?) that do not depend on `__cuda`. So solving the environment failed.\n\n#### AI usage disclosure\n\nI used AI assistance for:\n- [x] Code generation (e.g., when writing an implementation or fixing a bug)\n- [ ] Test/benchmark generation\n- [ ] Documentation (including examples)\n- [x] Research and understanding\n\n#### Any other comments?\n\nWhat do you think about adding `cuvs` in this PR already? It is needed in cupy for spatial distance functions like `cdist`. Without cuvs installed those functions fail when you call them.", "author": "user_d5b9cb906259", "created_at": "2026-02-02T10:12:32+00:00", "merged_at": "2026-02-04T15:30:27+00:00", "base_branch": "main", "head_branch": "add-cuda-virtual-package-to-solver", "additions": 209, "deletions": 109, "changed_files": 6, "files": [ { "filename": "build_tools/github/create_gpu_environment.sh", "status": "modified", "additions": 7, "deletions": 0, "changes": 7, "patch": "@@ -12,6 +12,13 @@ source \"${HOME}/conda/etc/profile.d/conda.sh\"\n source build_tools/shared.sh\n conda activate base\n \n+# Run these debug commands before installing our specific conda environment.\n+# We want to see what is available on the runner before we make changes. But\n+# we need to install miniforge before being able to look at the output of the\n+# conda commands.\n+conda info --json | python -c \"import sys, json; print('Conda virtual packages versions:', json.load(sys.stdin).get('virtual_pkgs', []));\"\n+nvidia-smi\n+\n CONDA_ENV_NAME=sklearn\n LOCK_FILE=build_tools/github/pylatest_conda_forge_cuda_array-api_linux-64_conda.lock\n create_conda_environment_from_lock_file $CONDA_ENV_NAME $LOCK_FILE" }, { "filename": "build_tools/github/pylatest_conda_forge_cuda_array-api_linux-64_conda.lock", "status": "modified", "additions": 157, "deletions": 92, "changes": 249, "patch": "@@ -1,145 +1,192 @@\n # Generated by conda-lock.\n # platform: linux-64\n-# input_hash: 879f64b0534a118cfb4a43da8226771a8abadccd873d0a27980fc1e3b2273d45\n+# input_hash: 8bd38cbfb6761e42fe9b9ed474c118b28133f54feacf11682feab65d79c6c311\n [USER_REDACTED]\n-https://conda.anaconda.org/conda-forge/noarch/cuda-version-11.8-h70ddcb2_3.conda#670f0e1593b8c1d84f57ad5fe5256799\n+https://conda.anaconda.org/conda-forge/noarch/cuda-version-12.9-h4f385c5_3.conda#b6d5d7f1c171cbd228ea06b556cfa859\n https://conda.anaconda.org/conda-forge/noarch/font-ttf-dejavu-sans-mono-2.37-hab24e00_0.tar.bz2#0c96522c6bdaed4b1566d11387caaf45\n https://conda.anaconda.org/conda-forge/noarch/font-ttf-inconsolata-3.000-h77eed37_0.tar.bz2#34893075a5c9e55cdafac56607368fc6\n https://conda.anaconda.org/conda-forge/noarch/font-ttf-source-code-pro-2.038-h77eed37_0.tar.bz2#4d59c254e01d9cde7957100457e2d5fb\n https://conda.anaconda.org/conda-forge/noarch/font-ttf-ubuntu-0.83-h77eed37_3.conda#49023d73832ef61042f6a237cb2687e7\n-https://conda.anaconda.org/conda-forge/noarch/kernel-headers_linux-64-4.18.0-he073ed8_9.conda#86d9cba083cd041bfbf242a01a7a1999\n+https://conda.anaconda.org/conda-forge/linux-64/libopentelemetry-cpp-headers-1.21.0-ha770c72_1.conda#9e298d76f543deb06eb0f3413675e13a\n+https://conda.anaconda.org/conda-forge/linux-64/nlohmann_json-3.12.0-h54a6638_1.conda#16c2a0e9c4a166e53632cfca4f68d020\n+https://conda.anaconda.org/conda-forge/noarch/nomkl-1.0-h5ca1d4c_0.tar.bz2#9a66894dfd07c4510beb6b3f9672ccc0\n+https://conda.anaconda.org/conda-forge/noarch/pybind11-abi-11-hc364b38_1.conda#f0599959a2447c1e544e216bddf393fa\n https://conda.anaconda.org/conda-forge/noarch/python_abi-3.13-8_cp313.conda#94305520c52a4aa3f6c2b1ff6008d9f8\n https://conda.anaconda.org/conda-forge/noarch/tzdata-2025c-hc9c84f9_1.conda#ad659d0a2b3e47e38d829aa8cad2d610\n https://conda.anaconda.org/conda-forge/noarch/ca-certificates-2026.1.4-hbd8a1cb_0.conda#bddacf101bb4dd0e51811cb69c7790e2\n+https://conda.anaconda.org/conda-forge/noarch/cuda-cccl_linux-64-12.9.27-ha770c72_0.conda#87ff6381e33b76e5b9b179a2cdd005ec\n+https://conda.anaconda.org/conda-forge/noarch/cuda-crt-dev_linux-64-12.9.86-ha770c72_2.conda#79d280de61e18010df5997daea4743df\n+https://conda.anaconda.org/conda-forge/linux-64/cuda-crt-tools-12.9.86-ha770c72_2.conda#503a94e20d2690d534d676a764a1852c\n+https://conda.anaconda.org/conda-forge/noarch/cuda-cudart-static_linux-64-12.9.79-h3f2d84a_0.conda#b87bf315d81218dd63eb46cc1eaef775\n+https://conda.anaconda.org/conda-forge/noarch/cuda-cudart_linux-64-12.9.79-h3f2d84a_0.conda#64508631775fbbf9eca83c84b1df0cae\n+https://conda.anaconda.org/conda-forge/noarch/cuda-nvvm-dev_linux-64-12.9.86-ha770c72_2.conda#7b386291414c7eea113d25ac28a33772\n https://conda.anaconda.org/conda-forge/noarch/fonts-conda-forge-1-hc364b38_1.conda#a7970cd949a077b7cb9696379d338681\n https://conda.anaconda.org/conda-forge/linux-64/libglvnd-1.7.0-ha4b6fd6_2.conda#434ca7e50e40f4918ab701e3facd59a0\n+https://conda.anaconda.org/conda-forge/noarch/libnvptxcompiler-dev_linux-64-12.9.86-ha770c72_2.conda#a66a909acf08924aced622903832a937\n https://conda.anaconda.org/conda-forge/linux-64/llvm-openmp-21.1.8-h4922eb0_0.conda#f8640b709b37dc7758ddce45ea18d000\n-https://conda.anaconda.org/conda-forge/noarch/sysroot_linux-64-2.28-h4ee821c_9.conda#13dc3adbc692664cd3beabd216434749\n https://conda.anaconda.org/conda-forge/linux-64/_openmp_mutex-4.5-7_kmp_llvm.conda#887b70e1d607fba7957aa02f9ee0d939\n+https://conda.anaconda.org/conda-forge/noarch/cuda-cudart-dev_linux-64-12.9.79-h3f2d84a_0.conda#86e40eb67d83f1a58bdafdd44e5a77c6\n https://conda.anaconda.org/conda-forge/noarch/fonts-conda-ecosystem-1-0.tar.bz2#fee5683a3f04bd15cbd8318b096a27ab\n https://conda.anaconda.org/conda-forge/linux-64/libegl-1.7.0-ha4b6fd6_2.conda#c151d5eb730e9b7480e6d48c0fc44048\n+https://conda.anaconda.org/conda-forge/linux-64/libnvptxcompiler-dev-12.9.86-ha770c72_2.conda#3fd926c321c6dbf386aa14bd8b125bfb\n https://conda.anaconda.org/conda-forge/linux-64/libopengl-1.7.0-ha4b6fd6_2.conda#7df50d44d4a14d6c31a2c54f2cd92157\n https://conda.anaconda.org/conda-forge/linux-64/libgcc-15.2.0-he0feb66_16.conda#6d0363467e6ed84f11435eb309f2ff06\n https://conda.anaconda.org/conda-forge/linux-64/alsa-lib-1.2.15.3-hb03c661_0.conda#dcdc58c15961dbf17a0621312b01f5cb\n-https://conda.anaconda.org/conda-forge/linux-64/aws-c-common-0.10.6-hb9d3cd8_0.conda#d7d4680337a14001b0e043e96529409b\n+https://conda.anaconda.org/conda-forge/linux-64/attr-2.5.2-h39aace5_0.conda#791365c5f65975051e4e017b5da3abf5\n+https://conda.anaconda.org/conda-forge/linux-64/aws-c-common-0.12.6-hb03c661_0.conda#e36ad70a7e0b48f091ed6902f04c23b8\n https://conda.anaconda.org/conda-forge/linux-64/bzip2-1.0.8-hda65f42_8.conda#51a19bba1b8ebfb60df25cde030b7ebc\n https://conda.anaconda.org/conda-forge/linux-64/c-ares-1.34.6-hb03c661_0.conda#920bb03579f15389b9e512095ad995b7\n+https://conda.anaconda.org/conda-forge/noarch/cuda-nvcc-dev_linux-64-12.9.86-he91c749_2.conda#19d4e090217f0ea89d30bedb7461c048\n+https://conda.anaconda.org/conda-forge/linux-64/cuda-nvvm-impl-12.9.86-h4bc722e_2.conda#82125dd3c0c4aa009faa00e2829b93d8\n+https://conda.anaconda.org/conda-forge/linux-64/cuda-nvvm-tools-12.9.86-h4bc722e_2.conda#f9af26e4079adcd72688a8e8dbecb229\n https://conda.anaconda.org/conda-forge/linux-64/keyutils-1.6.3-hb9d3cd8_0.conda#b38117a3c920364aff79f870c984b4a3\n-https://conda.anaconda.org/conda-forge/linux-64/libbrotlicommon-1.1.0-hb03c661_4.conda#1d29d2e33fe59954af82ef54a8af3fe1\n+https://conda.anaconda.org/conda-forge/linux-64/libbrotlicommon-1.2.0-hb03c661_1.conda#72c8fd1af66bd67bf580645b426513ed\n https://conda.anaconda.org/conda-forge/linux-64/libdeflate-1.25-h17f619e_0.conda#6c77a605a7a689d17d4819c0f8ac9a00\n https://conda.anaconda.org/conda-forge/linux-64/libexpat-2.7.3-hecca717_0.conda#8b09ae86839581147ef2e5c5e229d164\n-https://conda.anaconda.org/conda-forge/linux-64/libffi-3.5.2-h9ec8514_0.conda#35f29eec58405aaf55e01cb470d8c26a\n+https://conda.anaconda.org/conda-forge/linux-64/libffi-3.5.2-h3435931_0.conda#a360c33a5abe61c07959e449fa1453eb\n https://conda.anaconda.org/conda-forge/linux-64/libgcc-ng-15.2.0-h69a702a_16.conda#5a68259fac2da8f2ee6f7bfe49c9eb8b\n https://conda.anaconda.org/conda-forge/linux-64/libgfortran5-15.2.0-h68bc16d_16.conda#39183d4e0c05609fd65f130633194e37\n https://conda.anaconda.org/conda-forge/linux-64/libiconv-1.18-h3b78370_2.conda#915f5995e94f60e9a4826e0b0920ee88\n https://conda.anaconda.org/conda-forge/linux-64/libjpeg-turbo-3.1.2-hb03c661_0.conda#8397539e3a0bbd1695584fb4f927485a\n https://conda.anaconda.org/conda-forge/linux-64/liblzma-5.8.2-hb03c661_0.conda#c7c83eecbb72d88b940c249af56c8b17\n-https://conda.anaconda.org/conda-forge/linux-64/libmpdec-4.0.0-hb9d3cd8_0.conda#c7e925f37e3b40d893459e625f6a53f1\n+https://conda.anaconda.org/conda-forge/linux-64/libmpdec-4.0.0-hb03c661_1.conda#2c21e66f50753a083cbe6b80f38268fa\n+https://conda.anaconda.org/conda-forge/linux-64/libnl-3.11.0-hb9d3cd8_0.conda#db63358239cbe1ff86242406d440e44a\n https://conda.anaconda.org/conda-forge/linux-64/libntlm-1.8-hb9d3cd8_0.conda#7c7927b404672409d9917d49bff5f2d6\n https://conda.anaconda.org/conda-forge/linux-64/libpciaccess-0.18-hb9d3cd8_0.conda#70e3400cbbfa03e96dcde7fc13e38c7b\n https://conda.anaconda.org/conda-forge/linux-64/libstdcxx-15.2.0-h934c35e_16.conda#68f68355000ec3f1d6f26ea13e8f525f\n-https://conda.anaconda.org/conda-forge/linux-64/libutf8proc-2.9.0-hb9d3cd8_1.conda#1e936bd23d737aac62a18e9a1e7f8b18\n+https://conda.anaconda.org/conda-forge/linux-64/libutf8proc-2.11.3-hfe17d71_0.conda#1247168fe4a0b8912e3336bccdbf98a5\n https://conda.anaconda.org/conda-forge/linux-64/libuuid-2.41.3-h5347b49_0.conda#db409b7c1720428638e7c0d509d3e1b5\n https://conda.anaconda.org/conda-forge/linux-64/libuv-1.51.0-hb03c661_1.conda#0f03292cc56bf91a077a134ea8747118\n https://conda.anaconda.org/conda-forge/linux-64/libwebp-base-1.6.0-hd42ef1d_0.conda#aea31d2e5b1091feca96fcfe945c3cf9\n https://conda.anaconda.org/conda-forge/linux-64/libzlib-1.3.1-hb9d3cd8_2.conda#edb0dca6bc32e4f4789199455a1dbeb8\n https://conda.anaconda.org/conda-forge/linux-64/ncurses-6.5-h2d0b736_3.conda#47e340acb35de30501a76c7c799c41d7\n-https://conda.anaconda.org/conda-forge/linux-64/openssl-3.6.0-h26f9b46_0.conda#9ee58d5c534af06558933af3c845a780\n+https://conda.anaconda.org/conda-forge/linux-64/openssl-3.6.1-h35e630c_1.conda#f61eb8cd60ff9057122a3d338b99c00f\n https://conda.anaconda.org/conda-forge/linux-64/pthread-stubs-0.4-hb9d3cd8_1002.conda#b3c17d95b5a10c6e64a21fa17573e70e\n https://conda.anaconda.org/conda-forge/linux-64/xorg-libice-1.1.2-hb9d3cd8_0.conda#fb901ff28063514abb6046c9ec2c4a45\n https://conda.anaconda.org/conda-forge/linux-64/xorg-libxau-1.0.12-hb03c661_1.conda#b2895afaf55bf96a8c8282a2e47a5de0\n https://conda.anaconda.org/conda-forge/linux-64/xorg-libxdmcp-1.1.5-hb03c661_1.conda#1dafce8548e38671bea82e3f5c6ce22f\n https://conda.anaconda.org/conda-forge/linux-64/xxhash-0.8.3-hb47aa4a_0.conda#607e13a8caac17f9a664bcab5302ce06\n-https://conda.anaconda.org/conda-forge/linux-64/aws-c-cal-0.8.1-h1a47875_3.conda#55a8561fdbbbd34f50f57d9be12ed084\n-https://conda.anaconda.org/conda-forge/linux-64/aws-c-compression-0.3.0-h4e1184b_5.conda#3f4c1197462a6df2be6dc8241828fe93\n-https://conda.anaconda.org/conda-forge/linux-64/aws-c-sdkutils-0.2.1-h4e1184b_4.conda#a5126a90e74ac739b00564a4c7ddcc36\n-https://conda.anaconda.org/conda-forge/linux-64/aws-checksums-0.2.2-h4e1184b_4.conda#74e8c3e4df4ceae34aa2959df4b28101\n-https://conda.anaconda.org/conda-forge/linux-64/double-conversion-3.3.1-h5888daf_0.conda#bfd56492d8346d669010eccafe0ba058\n+https://conda.anaconda.org/conda-forge/linux-64/aws-c-cal-0.9.13-h2c9d079_1.conda#3c3d02681058c3d206b562b2e3bc337f\n+https://conda.anaconda.org/conda-forge/linux-64/aws-c-compression-0.3.1-h8b1a151_9.conda#f7ec84186dfe7a9e3a9f9e5a4d023e75\n+https://conda.anaconda.org/conda-forge/linux-64/aws-c-sdkutils-0.2.4-h8b1a151_4.conda#c7e3e08b7b1b285524ab9d74162ce40b\n+https://conda.anaconda.org/conda-forge/linux-64/aws-checksums-0.2.7-h8b1a151_5.conda#68da5b56dde41e172b7b24f071c4b392\n+https://conda.anaconda.org/conda-forge/linux-64/cuda-cudart-12.9.79-h5888daf_0.conda#cb15315d19b58bd9cd424084e58ad081\n+https://conda.anaconda.org/conda-forge/linux-64/cuda-cudart-static-12.9.79-h5888daf_0.conda#d3c4ac48f4967f09dd910d9c15d40c81\n+https://conda.anaconda.org/conda-forge/linux-64/cuda-cupti-12.9.79-h676940d_1.conda#a2ddf359dcb9e6a3d0173b10f58f4db9\n+https://conda.anaconda.org/conda-forge/linux-64/cuda-nvcc-tools-12.9.86-he02047a_2.conda#dc256c9864c2e8e9c817fbca1c84a4bc\n+https://conda.anaconda.org/conda-forge/linux-64/cuda-nvdisasm-12.9.88-hffce074_1.conda#5e7845d208a5067cb1461a429ff887e0\n+https://conda.anaconda.org/conda-forge/linux-64/cuda-nvrtc-12.9.86-hecca717_1.conda#53f0062e2243b26e43ddac0b5267c6a3\n+https://conda.anaconda.org/conda-forge/linux-64/cuda-nvtx-12.9.79-hecca717_1.conda#b4a3411fa031c409f98cfbd4b2db9ad7\n+https://conda.anaconda.org/conda-forge/linux-64/double-conversion-3.4.0-hecca717_0.conda#dbe3ec0f120af456b3477743ffd99b74\n+https://conda.anaconda.org/conda-forge/linux-64/fmt-12.1.0-hff5e90c_0.conda#f7d7a4104082b39e3b3473fbd4a38229\n https://conda.anaconda.org/conda-forge/linux-64/gflags-2.2.2-h5888daf_1005.conda#d411fc29e338efb48c5fd4576d71d881\n https://conda.anaconda.org/conda-forge/linux-64/graphite2-1.3.14-hecca717_2.conda#2cd94587f3a401ae05e03a6caf09539d\n+https://conda.anaconda.org/conda-forge/linux-64/icu-78.2-h33c6efd_0.conda#186a18e3ba246eccfc7cff00cd19a870\n https://conda.anaconda.org/conda-forge/linux-64/lerc-4.0.0-h0aef613_1.conda#9344155d33912347b37f0ae6c410a835\n-https://conda.anaconda.org/conda-forge/linux-64/libabseil-20240722.0-cxx17_hbbce691_4.conda#488f260ccda0afaf08acb286db439c2f\n-https://conda.anaconda.org/conda-forge/linux-64/libbrotlidec-1.1.0-hb03c661_4.conda#5cb5a1c9a94a78f5b23684bcb845338d\n-https://conda.anaconda.org/conda-forge/linux-64/libbrotlienc-1.1.0-hb03c661_4.conda#2e55011fa483edb8bfe3fd92e860cd79\n+https://conda.anaconda.org/conda-forge/linux-64/libabseil-20250512.1-cxx17_hba17884_0.conda#83b160d4da3e1e847bf044997621ed63\n+https://conda.anaconda.org/conda-forge/linux-64/libbrotlidec-1.2.0-hb03c661_1.conda#366b40a69f0ad6072561c1d09301c886\n+https://conda.anaconda.org/conda-forge/linux-64/libbrotlienc-1.2.0-hb03c661_1.conda#4ffbb341c8b616aa2494b6afb26a0c5f\n+https://conda.anaconda.org/conda-forge/linux-64/libcap-2.77-h3ff7636_0.conda#09c264d40c67b82b49a3f3b89037bd2e\n+https://conda.anaconda.org/conda-forge/linux-64/libcufft-11.4.1.4-hecca717_1.conda#75ae571353ec92c8f34d4cf6ec6ba264\n+https://conda.anaconda.org/conda-forge/linux-64/libcurand-10.3.10.19-h676940d_1.conda#2a91559a9345bedf09af8b7903deb6e6\n https://conda.anaconda.org/conda-forge/linux-64/libdrm-2.4.125-hb03c661_1.conda#9314bc5a1fe7d1044dc9dfd3ef400535\n https://conda.anaconda.org/conda-forge/linux-64/libedit-3.1.20250104-pl5321h7949ede_0.conda#c277e0a4d549b03ac1e9d6cbbe3d017b\n https://conda.anaconda.org/conda-forge/linux-64/libev-4.33-hd590300_2.conda#172bf1cd1ff8629f2b1179945ed45055\n https://conda.anaconda.org/conda-forge/linux-64/libevent-2.1.12-hf998b51_1.conda#a1cfcc585f0c42bf8d5546bb1dfb668d\n https://conda.anaconda.org/conda-forge/linux-64/libgfortran-15.2.0-h69a702a_16.conda#40d9b534410403c821ff64f00d0adc22\n https://conda.anaconda.org/conda-forge/linux-64/libhiredis-1.3.0-h5888daf_1.conda#aa342fcf3bc583660dbfdb2eae6be48e\n+https://conda.anaconda.org/conda-forge/linux-64/libnvjitlink-12.9.86-hecca717_2.conda#3461b0f2d5cbb7973d361f9e85241d98\n https://conda.anaconda.org/conda-forge/linux-64/libpng-1.6.54-h421ea60_0.conda#d361fa2a59e53b61c2675bfa073e5b7e\n-https://conda.anaconda.org/conda-forge/linux-64/libsqlite-3.51.2-h0c1763c_0.conda#f7d30045eccb83f2bb8053041f42db3c\n https://conda.anaconda.org/conda-forge/linux-64/libssh2-1.11.1-hcf80075_0.conda#eecce068c7e4eddeb169591baac20ac4\n https://conda.anaconda.org/conda-forge/linux-64/libstdcxx-ng-15.2.0-hdf11a46_16.conda#1b3152694d236cf233b76b8c56bf0eae\n https://conda.anaconda.org/conda-forge/linux-64/libxcb-1.17.0-h8a09558_0.conda#92ed62436b625154323d40d5f2f11dd7\n https://conda.anaconda.org/conda-forge/linux-64/libxcrypt-4.4.36-hd590300_1.conda#5aa797f8787fe7a17d1b0821485b5adc\n https://conda.anaconda.org/conda-forge/linux-64/lz4-c-1.10.0-h5888daf_1.conda#9de5350a85c4a20c685259b889aa6393\n+https://conda.anaconda.org/conda-forge/linux-64/nccl-2.29.2.1-h4d09622_1.conda#cda0cd556f99190e28f083c5125be060\n https://conda.anaconda.org/conda-forge/linux-64/ninja-1.13.2-h171cf75_0.conda#b518e9e92493721281a60fa975bddc65\n-https://conda.anaconda.org/conda-forge/linux-64/pcre2-10.46-h1321c63_0.conda#7fa07cb0fb1b625a089ccc01218ee5b1\n+https://conda.anaconda.org/conda-forge/linux-64/pcre2-10.47-haa7fec5_0.conda#7a3bff861a6583f1889021facefc08b1\n https://conda.anaconda.org/conda-forge/linux-64/pixman-0.46.4-h54a6638_1.conda#c01af13bdc553d1a8fbfff6e8db075f0\n+https://conda.anaconda.org/rapidsai/linux-64/rapids-logger-0.1.1-h98325ef_0.conda#e22516a87ac1fb1ea6bf0aa6a18e9d30\n https://conda.anaconda.org/conda-forge/linux-64/readline-8.3-h853b02a_0.conda#d7d95fc8287ea7bf33e0e7116d2b95ec\n-https://conda.anaconda.org/conda-forge/linux-64/s2n-1.5.11-h072c03f_0.conda#5e8060d52f676a40edef0006a75c718f\n+https://conda.anaconda.org/conda-forge/linux-64/s2n-1.6.2-he8a4886_1.conda#bade189a194e66b93c03021bd36c337b\n https://conda.anaconda.org/conda-forge/linux-64/sleef-3.9.0-ha0421bc_0.conda#e8a0b4f5e82ecacffaa5e805020473cb\n https://conda.anaconda.org/conda-forge/linux-64/snappy-1.2.2-h03e3b7b_1.conda#98b6c9dc80eb87b2519b97bcf7e578dd\n-https://conda.anaconda.org/conda-forge/linux-64/tk-8.6.13-noxft_ha0e22de_103.conda#86bc20552bf46075e3d92b67f089172d\n+https://conda.anaconda.org/conda-forge/linux-64/tk-8.6.13-noxft_h366c992_103.conda#cffd3bdd58090148f4cfcd831f4b26ab\n https://conda.anaconda.org/conda-forge/linux-64/wayland-1.24.0-hd6090a7_1.conda#035da2e4f5770f036ff704fa17aace24\n https://conda.anaconda.org/conda-forge/linux-64/xorg-libsm-1.2.6-he73a12e_0.conda#1c74ff8c35dcadf952a16f752ca5aa49\n+https://conda.anaconda.org/conda-forge/linux-64/zlib-1.3.1-hb9d3cd8_2.conda#c9f075ab2f33b3bbee9e62d4ad0a6cd8\n https://conda.anaconda.org/conda-forge/linux-64/zlib-ng-2.3.2-hceb46e0_1.conda#40feea2979654ed579f1cda7c63ccb94\n https://conda.anaconda.org/conda-forge/linux-64/zstd-1.5.7-hb78ec9c_6.conda#4a13eeac0b5c8e5b8ab496e6c4ddd829\n-https://conda.anaconda.org/conda-forge/linux-64/aws-c-io-0.15.3-h173a860_6.conda#9a063178f1af0a898526cc24ba7be486\n-https://conda.anaconda.org/conda-forge/linux-64/brotli-bin-1.1.0-hb03c661_4.conda#ca4ed8015764937c81b830f7f5b68543\n+https://conda.anaconda.org/conda-forge/linux-64/aws-c-io-0.23.3-hdaf4b65_5.conda#132e8f8f40f0ffc0bbde12bb4e8dd1a1\n+https://conda.anaconda.org/conda-forge/linux-64/brotli-bin-1.2.0-hb03c661_1.conda#af39b9a8711d4a8d437b52c1d78eb6a1\n https://conda.anaconda.org/conda-forge/linux-64/ccache-4.12.2-hedf47ba_0.conda#894811fefb5d282448a1685193feffaf\n-https://conda.anaconda.org/conda-forge/linux-64/cudatoolkit-11.8.0-h4ba93d1_13.conda#eb43f5f1f16e2fad2eba22219c3e499b\n+https://conda.anaconda.org/conda-forge/linux-64/cuda-cudart-dev-12.9.79-h5888daf_0.conda#ba38a7c3b4c14625de45784b773f0c71\n+https://conda.anaconda.org/conda-forge/linux-64/cuda-cuobjdump-12.9.82-hffce074_1.conda#55a83761db33f82d92d7d7a4a61662e5\n https://conda.anaconda.org/conda-forge/linux-64/glog-0.7.1-hbabe93e_0.conda#ff862eebdfeb2fd048ae9dc92510baca\n https://conda.anaconda.org/conda-forge/linux-64/gmp-6.3.0-hac33072_2.conda#c94a5994ef49749880a8139cf9afcbe1\n-https://conda.anaconda.org/conda-forge/linux-64/icu-75.1-he02047a_0.conda#8b189310083baabfb622af68fd9d3ae3\n https://conda.anaconda.org/conda-forge/linux-64/krb5-1.21.3-h659f571_0.conda#3f43953b7d3fb3aaa1d0d0723d91e368\n https://conda.anaconda.org/conda-forge/linux-64/ld_impl_linux-64-2.45-default_hbd61a6d_105.conda#3ec0aa5037d39b06554109a01e6fb0c6\n https://conda.anaconda.org/conda-forge/linux-64/libcrc32c-1.1.2-h9c3ff4c_0.tar.bz2#c965a5aa0d5c1c37ffc62dff36e28400\n+https://conda.anaconda.org/conda-forge/linux-64/libcublas-12.9.1.4-h676940d_1.conda#af0df9bc982b5ed2c67e8f5062d1f8c1\n+https://conda.anaconda.org/conda-forge/linux-64/libcurand-dev-10.3.10.19-h676940d_1.conda#fc716aaff5af15b80ccbd28b3e67672c\n+https://conda.anaconda.org/conda-forge/linux-64/libcusparse-12.5.10.65-hecca717_2.conda#890ebfaad48c887d3d82847ec9d6bc79\n https://conda.anaconda.org/conda-forge/linux-64/libfreetype6-2.14.1-h73754d4_0.conda#8e7251989bca326a28f4a5ffbd74557a\n-https://conda.anaconda.org/conda-forge/linux-64/libglib-2.86.2-h32235b2_0.conda#0cb0612bc9cb30c62baf41f9d600611b\n+https://conda.anaconda.org/conda-forge/linux-64/libglib-2.86.3-h6548e54_0.conda#034bea55a4feef51c98e8449938e9cee\n https://conda.anaconda.org/conda-forge/linux-64/libnghttp2-1.67.0-had1ee68_0.conda#b499ce4b026493a13774bcf0f4c33849\n-https://conda.anaconda.org/conda-forge/linux-64/libopenblas-0.3.30-pthreads_h94d23a6_4.conda#be43915efc66345cccb3c310b6ed0374\n-https://conda.anaconda.org/conda-forge/linux-64/libprotobuf-5.28.2-h5b01275_0.conda#ab0bff36363bec94720275a681af8b83\n-https://conda.anaconda.org/conda-forge/linux-64/libre2-11-2024.07.02-hbbce691_2.conda#b2fede24428726dd867611664fb372e8\n-https://conda.anaconda.org/conda-forge/linux-64/libthrift-0.21.0-h0e7cc3e_0.conda#dcb95c0a98ba9ff737f7ae482aef7833\n+https://conda.anaconda.org/conda-forge/linux-64/libopenblas-0.3.30-openmp_hd680484_4.conda#c0512e4f60d62ccccb4c3c8333b33608\n+https://conda.anaconda.org/conda-forge/linux-64/libprotobuf-6.31.1-h49aed37_4.conda#07479fc04ba3ddd5d9f760ef1635cfa7\n+https://conda.anaconda.org/conda-forge/linux-64/libre2-11-2025.11.05-h7b12aa8_0.conda#a30848ebf39327ea078cf26d114cff53\n+https://conda.anaconda.org/rapidsai/linux-64/librmm-25.08.00-cuda12_250806_63a4d366.conda#8825b9080d25244f21b7fe18ef25f78c\n+https://conda.anaconda.org/conda-forge/linux-64/libsqlite-3.51.2-hf4e2dac_0.conda#da5be73701eecd0e8454423fd6ffcf30\n+https://conda.anaconda.org/conda-forge/linux-64/libsystemd0-258.3-h6569c3e_0.conda#68294614784925a7c1427835dbe217d7\n+https://conda.anaconda.org/conda-forge/linux-64/libthrift-0.22.0-h454ac66_1.conda#8ed82d90e6b1686f5e98f8b7825a15ef\n https://conda.anaconda.org/conda-forge/linux-64/libtiff-4.7.1-h9d88235_1.conda#cd5a90476766d53e901500df9215e927\n-https://conda.anaconda.org/conda-forge/linux-64/nccl-2.27.3.1-h03a54cd_0.conda#616e835be8126fab0bf4cec1f40cc4ea\n+https://conda.anaconda.org/conda-forge/linux-64/libudev1-258.3-h6569c3e_0.conda#dc6d00d149316edb629059671dd8600e\n+https://conda.anaconda.org/conda-forge/linux-64/libxml2-16-2.15.1-hca6bf5a_1.conda#3fdd8d99683da9fe279c2f4cecd1e048\n https://conda.anaconda.org/conda-forge/linux-64/qhull-2020.2-h434a139_5.conda#353823361b1d27eb3960efb076dfcaf6\n https://conda.anaconda.org/conda-forge/linux-64/xcb-util-0.4.1-h4f16b4b_2.conda#fdc27cb255a7a2cc73b7919a968b48f0\n https://conda.anaconda.org/conda-forge/linux-64/xcb-util-keysyms-0.4.1-hb711507_0.conda#ad748ccca349aec3e91743e08b5e2b50\n https://conda.anaconda.org/conda-forge/linux-64/xcb-util-renderutil-0.3.10-hb711507_0.conda#0e0cbe0564d03a99afd5fd7b362feecd\n https://conda.anaconda.org/conda-forge/linux-64/xcb-util-wm-0.4.2-hb711507_0.conda#608e0ef8256b81d04456e8d211eee3e8\n https://conda.anaconda.org/conda-forge/linux-64/xorg-libx11-1.8.12-h4f16b4b_0.conda#db038ce880f100acc74dba10302b5630\n-https://conda.anaconda.org/conda-forge/linux-64/aws-c-event-stream-0.5.0-h7959bf6_11.conda#9b3fb60fe57925a92f399bc3fc42eccf\n-https://conda.anaconda.org/conda-forge/linux-64/aws-c-http-0.9.2-hefd7a92_4.conda#5ce4df662d32d3123ea8da15571b6f51\n-https://conda.anaconda.org/conda-forge/linux-64/brotli-1.1.0-hb03c661_4.conda#eaf3fbd2aa97c212336de38a51fe404e\n+https://conda.anaconda.org/conda-forge/linux-64/aws-c-event-stream-0.5.7-h28f887f_1.conda#7b8e3f846353b75db163ad93248e5f9d\n+https://conda.anaconda.org/conda-forge/linux-64/aws-c-http-0.10.7-ha8fc4e3_5.conda#3028f20dacafc00b22b88b324c8956cc\n+https://conda.anaconda.org/conda-forge/linux-64/brotli-1.2.0-hed03a55_1.conda#8ccf913aaba749a5496c17629d859ed1\n+https://conda.anaconda.org/conda-forge/linux-64/cuda-nvcc-impl-12.9.86-h85509e4_2.conda#67458d2685e7503933efa550f3ee40f3\n+https://conda.anaconda.org/conda-forge/linux-64/cuda-profiler-api-12.9.79-h7938cbb_1.conda#90d09865fb37d11d510444e34ebe6a09\n https://conda.anaconda.org/conda-forge/linux-64/cyrus-sasl-2.1.28-hd9c7081_0.conda#cae723309a49399d2949362f4ab5c9e4\n https://conda.anaconda.org/conda-forge/linux-64/dbus-1.16.2-h24cb091_1.conda#ce96f2f470d39bd96ce03945af92e280\n https://conda.anaconda.org/conda-forge/linux-64/lcms2-2.18-h0c24ade_0.conda#6f2e2c8f58160147c4d1c6f4c14cbac4\n https://conda.anaconda.org/conda-forge/linux-64/libblas-3.11.0-5_h4a7cf45_openblas.conda#c160954f7418d7b6e87eaf05a8913fa9\n-https://conda.anaconda.org/conda-forge/linux-64/libcudnn-9.10.1.4-h7d33bf5_0.conda#93fe78190bc6fe40d5e7a737c8065286\n+https://conda.anaconda.org/conda-forge/linux-64/libcublas-dev-12.9.1.4-h676940d_1.conda#f90f4ff087ac29005c6989ea0fb2735a\n+https://conda.anaconda.org/conda-forge/linux-64/libcudnn-9.10.2.21-hf7e9902_0.conda#a178a1f3642521f104ecceeefa138d01\n+https://conda.anaconda.org/conda-forge/linux-64/libcudss-0.7.1.4-h58dd1b1_0.conda#d71b1cf78714f31f1264591cdb7ce97d\n https://conda.anaconda.org/conda-forge/linux-64/libcups-2.3.3-hb8b1518_5.conda#d4a250da4737ee127fb1fa6452a9002e\n https://conda.anaconda.org/conda-forge/linux-64/libcurl-8.18.0-h4e3cde8_0.conda#0a5563efed19ca4461cf927419b6eb73\n+https://conda.anaconda.org/conda-forge/linux-64/libcusolver-11.7.5.82-h676940d_2.conda#bb6e31a0daa64ede76fe8d3fff01c06f\n+https://conda.anaconda.org/conda-forge/linux-64/libcusparse-dev-12.5.10.65-hecca717_2.conda#db94469fbd554c107acc3afd0af5d8ec\n https://conda.anaconda.org/conda-forge/linux-64/libfreetype-2.14.1-ha770c72_0.conda#f4084e4e6577797150f9b04a4560ceb0\n https://conda.anaconda.org/conda-forge/linux-64/libglx-1.7.0-ha4b6fd6_2.conda#c8013e438185f33b13814c5c488acd5c\n-https://conda.anaconda.org/conda-forge/linux-64/libxml2-2.13.9-h04c0eec_0.conda#35eeb0a2add53b1e50218ed230fa6a02\n+https://conda.anaconda.org/rapidsai/linux-64/libraft-headers-only-25.08.00-cuda12_250806_2fb92393.conda#ac979638ede39fa80829d6a346405ab2\n+https://conda.anaconda.org/conda-forge/linux-64/libxml2-2.15.1-he237659_1.conda#417955234eccd8f252b86a265ccdab7f\n https://conda.anaconda.org/conda-forge/linux-64/mpfr-4.2.1-h90cbb55_3.conda#2eeb50cab6652538eee8fc0bc3340c81\n-https://conda.anaconda.org/conda-forge/linux-64/openblas-0.3.30-pthreads_h6ec200e_4.conda#379ec5261b0b8fc54f2e7bd055360b0c\n+https://conda.anaconda.org/conda-forge/linux-64/openblas-0.3.30-openmp_hd77311e_4.conda#525e2455ed342f2aef93c59ac5db2e28\n https://conda.anaconda.org/conda-forge/linux-64/openjpeg-2.5.4-h55fea9a_0.conda#11b3379b191f63139e29c0d19dee24cd\n-https://conda.anaconda.org/conda-forge/linux-64/orc-2.0.3-h97ab989_1.conda#2f46eae652623114e112df13fae311cf\n-https://conda.anaconda.org/conda-forge/linux-64/python-3.13.11-hc97d973_100_cp313.conda#0cbb0010f1d8ecb64a428a8d4214609e\n-https://conda.anaconda.org/conda-forge/linux-64/re2-2024.07.02-h9925aae_2.conda#e84ddf12bde691e8ec894b00ea829ddf\n+https://conda.anaconda.org/conda-forge/linux-64/orc-2.2.2-h19cb568_0.conda#a98b8d7cfdd20004f1bdd1a51cb22c58\n+https://conda.anaconda.org/conda-forge/linux-64/python-3.13.11-hc97d973_101_cp313.conda#aa23b675b860f2566af2dfb3ffdf3b8c\n+https://conda.anaconda.org/conda-forge/linux-64/rdma-core-61.0-h192683f_0.conda#d487d93d170e332ab39803e05912a762\n+https://conda.anaconda.org/conda-forge/linux-64/re2-2025.11.05-h5301d42_0.conda#0227d04521bc3d28c7995c7e1f99a721\n https://conda.anaconda.org/conda-forge/linux-64/xcb-util-image-0.4.0-hb711507_2.conda#a0901183f08b6c7107aab109733a3c91\n https://conda.anaconda.org/conda-forge/linux-64/xkeyboard-config-2.46-hb03c661_0.conda#71ae752a748962161b4740eaff510258\n-https://conda.anaconda.org/conda-forge/linux-64/xorg-libxext-1.3.6-hb9d3cd8_0.conda#febbab7d15033c913d53c7a2c102309d\n+https://conda.anaconda.org/conda-forge/linux-64/xorg-libxext-1.3.7-hb03c661_0.conda#34e54f03dfea3e7a2dcf1453a85f1085\n https://conda.anaconda.org/conda-forge/linux-64/xorg-libxfixes-6.0.2-hb03c661_0.conda#ba231da7fccf9ea1e768caf5c7099b84\n https://conda.anaconda.org/conda-forge/linux-64/xorg-libxrender-0.9.12-hb9d3cd8_0.conda#96d57aba173e878a2089d5638016dc5e\n-https://conda.anaconda.org/conda-forge/linux-64/aws-c-auth-0.8.0-hb921021_15.conda#c79d50f64cffa5ad51ecc1a81057962f\n-https://conda.anaconda.org/conda-forge/linux-64/aws-c-mqtt-0.11.0-h11f4f37_12.conda#96c3e0221fa2da97619ee82faa341a73\n-https://conda.anaconda.org/conda-forge/linux-64/azure-core-cpp-1.14.0-h5cfcd09_0.conda#0a8838771cc2e985cd295e01ae83baf1\n+https://conda.anaconda.org/conda-forge/linux-64/aws-c-auth-0.9.3-hef928c7_0.conda#bdd464b33f6540ed70845b946c11a7b8\n+https://conda.anaconda.org/conda-forge/linux-64/aws-c-mqtt-0.13.3-hc63082f_11.conda#6a653aefdc5d83a4f959869d1759e6e3\n+https://conda.anaconda.org/conda-forge/linux-64/azure-core-cpp-1.16.1-h3a458e0_0.conda#1d4e0d37da5f3c22ecd44033f673feba\n https://conda.anaconda.org/conda-forge/noarch/colorama-0.4.6-pyhd8ed1ab_1.conda#962b9857ee8e7018c22f2776ffa0b2d7\n-https://conda.anaconda.org/conda-forge/noarch/cpython-3.13.11-py313hd8ed1ab_100.conda#5bf347916a543bcb290c780fa449bf73\n+https://conda.anaconda.org/conda-forge/noarch/cpython-3.13.11-py313hd8ed1ab_101.conda#c74a6b9e8694e5122949f611d1552df5\n+https://conda.anaconda.org/conda-forge/noarch/cuda-pathfinder-1.3.3-pyhcf101f3_0.conda#b08fa4a3478526e33a4c08224398d2e5\n https://conda.anaconda.org/conda-forge/noarch/cycler-0.12.1-pyhcf101f3_2.conda#4c2a8fef270f6c69591889b93f9f55c1\n https://conda.anaconda.org/conda-forge/linux-64/cython-3.2.4-py313hc80a56d_0.conda#4a08e7dd57fdc0a13dc699c4c6d76c3a\n https://conda.anaconda.org/conda-forge/noarch/execnet-2.1.2-pyhd8ed1ab_0.conda#a57b4be42619213a94f31d2c69c5dda7\n@@ -150,101 +197,119 @@ https://conda.anaconda.org/conda-forge/noarch/fsspec-2026.1.0-pyhd8ed1ab_0.conda\n https://conda.anaconda.org/conda-forge/noarch/iniconfig-2.3.0-pyhd8ed1ab_0.conda#9614359868482abba1bd15ce465e3c42\n https://conda.anaconda.org/conda-forge/linux-64/kiwisolver-1.4.9-py313hc8edb43_2.conda#3e0e65595330e26515e31b7fc6d933c7\n https://conda.anaconda.org/conda-forge/linux-64/libcblas-3.11.0-5_h0358290_openblas.conda#6636a2b6f1a87572df2970d3ebc87cc0\n-https://conda.anaconda.org/conda-forge/linux-64/libcudnn-dev-9.10.1.4-h0fdc2d1_0.conda#a0c0b44d26a4710e6ea577fcddbe09d1\n+https://conda.anaconda.org/conda-forge/linux-64/libcufile-1.14.1.1-hbc026e6_1.conda#cab1818eada3952ed09c8dcbb7c26af7\n+https://conda.anaconda.org/conda-forge/linux-64/libcusolver-dev-11.7.5.82-h676940d_2.conda#0fe12e558abf507458bcec839e29778d\n https://conda.anaconda.org/conda-forge/linux-64/libgl-1.7.0-ha4b6fd6_2.conda#928b8be80851f5d8ffb016f9c81dae7a\n-https://conda.anaconda.org/conda-forge/linux-64/libgrpc-1.67.1-hc2c308b_0.conda#4606a4647bfe857e3cfe21ca12ac3afb\n-https://conda.anaconda.org/conda-forge/linux-64/libhwloc-2.12.1-default_h3d81e11_1000.conda#d821210ab60be56dd27b5525ed18366d\n+https://conda.anaconda.org/conda-forge/linux-64/libgrpc-1.73.1-h3288cfb_1.conda#ff63bb12ac31c176ff257e3289f20770\n https://conda.anaconda.org/conda-forge/linux-64/liblapack-3.11.0-5_h47877c9_openblas.conda#b38076eb5c8e40d0106beda6f95d7609\n-https://conda.anaconda.org/conda-forge/linux-64/libllvm21-21.1.0-hecd9e04_0.conda#9ad637a7ac380c442be142dfb0b1b955\n-https://conda.anaconda.org/conda-forge/linux-64/libxkbcommon-1.11.0-he8b52b9_0.conda#74e91c36d0eef3557915c68b6c2bef96\n-https://conda.anaconda.org/conda-forge/linux-64/libxslt-1.1.43-h7a3aeb2_0.conda#31059dc620fa57d787e3899ed0421e6d\n+https://conda.anaconda.org/conda-forge/linux-64/libllvm21-21.1.8-hf7376ad_0.conda#1a2708a460884d6861425b7f9a7bef99\n+https://conda.anaconda.org/conda-forge/linux-64/libxkbcommon-1.13.1-hca5e8e5_0.conda#2bca1fbb221d9c3c8e3a155784bbc2e9\n+https://conda.anaconda.org/conda-forge/linux-64/libxslt-1.1.43-h711ed8c_1.conda#87e6096ec6d542d1c1f8b33245fe8300\n https://conda.anaconda.org/conda-forge/linux-64/markupsafe-3.0.3-py313h3dea7bd_0.conda#c14389156310b8ed3520d84f854be1ee\n https://conda.anaconda.org/conda-forge/noarch/meson-1.10.1-pyhcf101f3_0.conda#6c07238c531b1f93603c6908d1a4ef4f\n https://conda.anaconda.org/conda-forge/linux-64/mpc-1.3.1-h24ddda3_1.conda#aa14b9a5196a6d8dd364164b7ce56acf\n https://conda.anaconda.org/conda-forge/noarch/mpmath-1.3.0-pyhd8ed1ab_1.conda#3585aa87c43ab15b167b574cd73b057b\n https://conda.anaconda.org/conda-forge/noarch/munkres-1.1.4-pyhd8ed1ab_1.conda#37293a85a0f4f77bbd9cf7aaefc62609\n https://conda.anaconda.org/conda-forge/noarch/networkx-3.6.1-pyhcf101f3_0.conda#a2c1eeadae7a309daed9d62c96012a2b\n+https://conda.anaconda.org/conda-forge/noarch/nvidia-ml-py-12.575.51-pyhd8ed1ab_0.conda#90600980e7240e1d6fdc97c1f32f57af\n https://conda.anaconda.org/conda-forge/linux-64/openldap-2.6.10-he970967_0.conda#2e5bf4f1da39c0b32778561c3c4e5878\n https://conda.anaconda.org/conda-forge/noarch/packaging-26.0-pyhcf101f3_0.conda#b76541e68fea4d511b1ac46a28dcd2c6\n https://conda.anaconda.org/conda-forge/linux-64/pillow-12.1.0-py313h80991f8_0.conda#183fe6b9e99e5c2b464c1573ec78eac8\n-https://conda.anaconda.org/conda-forge/noarch/pip-25.3-pyh145f28c_0.conda#bf47878473e5ab9fdb4115735230e191\n+https://conda.anaconda.org/conda-forge/noarch/pip-26.0-pyh145f28c_0.conda#f08a17c938eb6bc1b928bd8cdd37e20f\n https://conda.anaconda.org/conda-forge/noarch/pluggy-1.6.0-pyhf9edf01_1.conda#d7585b6550ad04c8c5e21097ada2888e\n+https://conda.anaconda.org/conda-forge/linux-64/prometheus-cpp-1.3.0-ha5d0236_0.conda#a83f6a2fdc079e643237887a37460668\n+https://conda.anaconda.org/conda-forge/noarch/pybind11-global-3.0.1-pyhc7ab6ef_0.conda#fe10b422ce8b5af5dab3740e4084c3f9\n https://conda.anaconda.org/conda-forge/noarch/pygments-2.19.2-pyhd8ed1ab_0.conda#6b6ece66ebcae2d5f326c77ef2c5a066\n https://conda.anaconda.org/conda-forge/noarch/pyparsing-3.3.2-pyhcf101f3_0.conda#3687cc0b82a8b4c17e1f0eb7e47163d5\n-https://conda.anaconda.org/conda-forge/noarch/setuptools-80.10.1-pyh332efcf_0.conda#cb72cedd94dd923c6a9405a3d3b1c018\n+https://conda.anaconda.org/conda-forge/noarch/setuptools-80.10.2-pyh332efcf_0.conda#7b446fcbb6779ee479debb4fd7453e6c\n https://conda.anaconda.org/conda-forge/noarch/six-1.17.0-pyhe01879c_1.conda#3339e3b65d58accf4ca4fb8748ab16b3\n https://conda.anaconda.org/conda-forge/noarch/threadpoolctl-3.6.0-pyhecae5ae_0.conda#9d64911b31d57ca443e9f1e36b04385f\n https://conda.anaconda.org/conda-forge/noarch/toml-0.10.2-pyhcf101f3_3.conda#d0fc809fa4c4d85e959ce4ab6e1de800\n https://conda.anaconda.org/conda-forge/noarch/tomli-2.4.0-pyhcf101f3_0.conda#72e780e9aa2d0a3295f59b1874e3768b\n-https://conda.anaconda.org/conda-forge/linux-64/tornado-6.5.3-py313h07c4f96_0.conda#82da2dcf1ea3e298f2557b50459809e0\n+https://conda.anaconda.org/conda-forge/linux-64/tornado-6.5.4-py313hd02dea0_0.conda#442d7ac35e5d6bc89eba2998a9e1de06\n https://conda.anaconda.org/conda-forge/noarch/typing_extensions-4.15.0-pyhcf101f3_0.conda#0caa1af407ecff61170c9437a808404d\n+https://conda.anaconda.org/conda-forge/linux-64/ucx-1.18.1-h990bcc0_2.conda#15e5ae8dc2c3a57a9cd77aa40dedfd40\n https://conda.anaconda.org/conda-forge/linux-64/xcb-util-cursor-0.1.6-hb03c661_0.conda#4d1fc190b99912ed557a8236e958c559\n https://conda.anaconda.org/conda-forge/linux-64/xorg-libxcomposite-0.4.6-hb9d3cd8_2.conda#d3c295b50f092ab525ffe3c2aa4b7413\n https://conda.anaconda.org/conda-forge/linux-64/xorg-libxcursor-1.2.3-hb9d3cd8_0.conda#2ccd714aa2242315acaf0a67faea780b\n https://conda.anaconda.org/conda-forge/linux-64/xorg-libxdamage-1.1.6-hb9d3cd8_0.conda#b5fcc7172d22516e1f965490e65e33a4\n https://conda.anaconda.org/conda-forge/linux-64/xorg-libxi-1.8.2-hb9d3cd8_0.conda#17dcc85db3c7886650b8908b183d6876\n-https://conda.anaconda.org/conda-forge/linux-64/xorg-libxrandr-1.5.4-hb9d3cd8_0.conda#2de7f99d6581a4a7adbff607b5c278ca\n-https://conda.anaconda.org/conda-forge/linux-64/xorg-libxxf86vm-1.1.6-hb9d3cd8_0.conda#5efa5fa6243a622445fdfd72aee15efa\n-https://conda.anaconda.org/conda-forge/linux-64/aws-c-s3-0.7.7-hf454442_0.conda#947c82025693bebd557f782bb5d6b469\n-https://conda.anaconda.org/conda-forge/linux-64/azure-identity-cpp-1.10.0-h113e628_0.conda#73f73f60854f325a55f1d31459f2ab73\n-https://conda.anaconda.org/conda-forge/linux-64/azure-storage-common-cpp-12.8.0-h736e048_1.conda#13de36be8de3ae3f05ba127631599213\n+https://conda.anaconda.org/conda-forge/linux-64/xorg-libxrandr-1.5.5-hb03c661_0.conda#e192019153591938acf7322b6459d36e\n+https://conda.anaconda.org/conda-forge/linux-64/xorg-libxxf86vm-1.1.7-hb03c661_0.conda#665d152b9c6e78da404086088077c844\n+https://conda.anaconda.org/conda-forge/linux-64/aws-c-s3-0.11.3-h06ab39a_1.conda#3689a4290319587e3b54a4f9e68f70c8\n+https://conda.anaconda.org/conda-forge/linux-64/azure-identity-cpp-1.13.2-h3a5f585_1.conda#4e921d9c85e6559c60215497978b3cdb\n+https://conda.anaconda.org/conda-forge/linux-64/azure-storage-common-cpp-12.12.0-h3d7a050_0.conda#e6f12de3a9b016cea81a87db04d85ff3\n https://conda.anaconda.org/conda-forge/linux-64/coverage-7.13.2-py313h3dea7bd_0.conda#df05169cc886aaf53dc560db634519f8\n-https://conda.anaconda.org/conda-forge/linux-64/cudnn-9.10.1.4-haad7af6_0.conda#8382d957333e0d3280dcbf5691516dc1\n+https://conda.anaconda.org/conda-forge/linux-64/cuda-bindings-12.9.5-py313h929d4db_0.conda#f2416964cdb2808dd2ed5be276a8fcdb\n https://conda.anaconda.org/conda-forge/noarch/exceptiongroup-1.3.1-pyhd8ed1ab_0.conda#8e662bd460bda79b1ea39194e3c4c9ab\n https://conda.anaconda.org/conda-forge/linux-64/fontconfig-2.15.0-h7e30c49_1.conda#8f5b0b297b59e1ac160ad4beec99dbee\n https://conda.anaconda.org/conda-forge/linux-64/fonttools-4.61.1-py313h3dea7bd_0.conda#c0f36dfbb130da4f6ce2df31f6b25ea8\n https://conda.anaconda.org/conda-forge/linux-64/gmpy2-2.2.1-py313h86d8783_2.conda#d904f240d2d2500d4906361c67569217\n https://conda.anaconda.org/conda-forge/noarch/jinja2-3.1.6-pyhcf101f3_1.conda#04558c96691bed63104678757beb4f8d\n https://conda.anaconda.org/conda-forge/noarch/joblib-1.5.3-pyhd8ed1ab_0.conda#615de2a4d97af50c350e5cf160149e77\n-https://conda.anaconda.org/conda-forge/linux-64/libclang-cpp21.1-21.1.0-default_h99862b1_1.conda#d599b346638b9216c1e8f9146713df05\n-https://conda.anaconda.org/conda-forge/linux-64/libclang13-21.1.0-default_h746c552_1.conda#327c78a8ce710782425a89df851392f7\n-https://conda.anaconda.org/conda-forge/linux-64/libgoogle-cloud-2.32.0-h804f50b_0.conda#3d96df4d6b1c88455e05b94ce8a14a53\n+https://conda.anaconda.org/conda-forge/linux-64/libclang-cpp21.1-21.1.8-default_h99862b1_2.conda#3c71daed530c0c26671a1b1b7010e746\n+https://conda.anaconda.org/conda-forge/linux-64/libclang13-21.1.8-default_h746c552_2.conda#0ad9019bb10eda915fb0ce5f78fef13b\n+https://conda.anaconda.org/conda-forge/linux-64/libgoogle-cloud-2.39.0-hdb79228_0.conda#a2e30ccd49f753fd30de0d30b1569789\n https://conda.anaconda.org/conda-forge/linux-64/liblapacke-3.11.0-5_h6ae95b6_openblas.conda#e487a0e38d89da76410cb92a5db39ec5\n-https://conda.anaconda.org/conda-forge/linux-64/libmagma-2.8.0-h9ddd185_2.conda#8de40c4f75d36bb00a5870f682457f1d\n-https://conda.anaconda.org/conda-forge/linux-64/libpq-17.7-h5c52fec_1.conda#a4769024afeab4b32ac8167c2f92c7ac\n-https://conda.anaconda.org/conda-forge/linux-64/numpy-2.4.1-py313hf6604e3_0.conda#7d51e3bef1a4b00bde1861d85ba2f874\n+https://conda.anaconda.org/conda-forge/linux-64/libmagma-2.9.0-ha7672b3_6.conda#7c6ca8cec0c6a213db89a1d80f53d197\n+https://conda.anaconda.org/conda-forge/linux-64/libopentelemetry-cpp-1.21.0-hb9b0907_1.conda#1c0320794855f457dea27d35c4c71e23\n+https://conda.anaconda.org/conda-forge/linux-64/libpq-18.1-hb80d175_3.conda#c39da2ad0e7dd600d1eb3146783b057d\n+https://conda.anaconda.org/rapidsai/linux-64/libucxx-0.45.01-cuda12_250806_c25d2cdb.conda#84eff90bd9369d4b654434b1ea354ec4\n+https://conda.anaconda.org/conda-forge/linux-64/libvulkan-loader-1.4.328.1-h5279c79_0.conda#372a62464d47d9e966b630ffae3abe73\n+https://conda.anaconda.org/conda-forge/linux-64/numpy-2.4.2-py313hf6604e3_0.conda#a61bd1412975145dd688a71849b63d97\n+https://conda.anaconda.org/conda-forge/noarch/pybind11-3.0.1-pyh7a1b43c_0.conda#70ece62498c769280f791e836ac53fff\n+https://conda.anaconda.org/conda-forge/noarch/pynvml-12.0.0-pyhd8ed1ab_0.conda#27a6f747d629815308c2d7e4f17aca4c\n https://conda.anaconda.org/conda-forge/noarch/pyproject-metadata-0.10.0-pyhd8ed1ab_0.conda#d9998bf52ced268eb83749ad65a2e061\n https://conda.anaconda.org/conda-forge/noarch/python-dateutil-2.9.0.post0-pyhe01879c_2.conda#5b8d21249ff20967101ffa321cab24e8\n-https://conda.anaconda.org/conda-forge/noarch/python-gil-3.13.11-h4df99d1_100.conda#d1461b2e63b1909f4f5b41c823bd90ae\n-https://conda.anaconda.org/conda-forge/linux-64/tbb-2021.13.0-h8d10470_4.conda#e6d46d70c68d0eb69b9a040ebe3acddf\n+https://conda.anaconda.org/conda-forge/noarch/python-gil-3.13.11-h4df99d1_101.conda#4af7a72062bddcb57dea6b236e1b245e\n+https://conda.anaconda.org/conda-forge/linux-64/triton-3.6.0-cuda129py313h246eb7c_0.conda#932203205c4cf6f661180b98a48f195a\n+https://conda.anaconda.org/conda-forge/noarch/typing-extensions-4.15.0-h396c80c_0.conda#edd329d7d3a4ab45dcf905899a7a6115\n https://conda.anaconda.org/conda-forge/linux-64/xorg-libxtst-1.2.5-hb9d3cd8_3.conda#7bbe9a0cc0df0ac5f5a8ad6d6a11af2f\n https://conda.anaconda.org/conda-forge/noarch/_python_abi3_support-1.0-hd8ed1ab_2.conda#aaa2a381ccc56eac91d63b6c1240312f\n https://conda.anaconda.org/conda-forge/noarch/array-api-strict-2.4.1-pyhe01879c_0.conda#648e253c455718227c61e26f4a4ce701\n-https://conda.anaconda.org/conda-forge/linux-64/aws-crt-cpp-0.29.7-hd92328a_7.conda#02b95564257d5c3db9c06beccf711f95\n-https://conda.anaconda.org/conda-forge/linux-64/azure-storage-blobs-cpp-12.13.0-h3cf044e_1.conda#7eb66060455c7a47d9dcdbfa9f46579b\n+https://conda.anaconda.org/conda-forge/linux-64/aws-crt-cpp-0.35.4-h8824e59_0.conda#113b9d9913280474c0868b0e290c0326\n+https://conda.anaconda.org/conda-forge/linux-64/azure-storage-blobs-cpp-12.16.0-h75daedc_0.conda#e88f8e816ae46c12cbe912c8f4d9d3bc\n https://conda.anaconda.org/conda-forge/linux-64/blas-devel-3.11.0-5_h1ea3ea9_openblas.conda#45c6e304872e33ebc43b2456d68fe00d\n-https://conda.anaconda.org/conda-forge/linux-64/cairo-1.18.4-h3394656_0.conda#09262e66b19567aff4f592fb53b28760\n+https://conda.anaconda.org/conda-forge/linux-64/cairo-1.18.4-he90730b_1.conda#bb6c4808bfa69d6f7f6b07e5846ced37\n https://conda.anaconda.org/conda-forge/linux-64/contourpy-1.3.3-py313hc8edb43_4.conda#33639459bc29437315d4bff9ed5bc7a7\n-https://conda.anaconda.org/conda-forge/linux-64/cupy-core-13.4.1-py313hc2a895b_0.conda#46dd595e816b278b178e3bef8a6acf71\n-https://conda.anaconda.org/conda-forge/linux-64/libgoogle-cloud-storage-2.32.0-h0121fbd_0.conda#877a5ec0431a5af83bf0cd0522bfe661\n-https://conda.anaconda.org/conda-forge/linux-64/libmagma_sparse-2.8.0-h9ddd185_0.conda#f4eb3cfeaf9d91e72d5b2b8706bf059f\n+https://conda.anaconda.org/conda-forge/noarch/cuda-python-12.9.5-pyh698daf1_0.conda#a4fb0d4ffdac1cf2cda9318d2f789d20\n+https://conda.anaconda.org/conda-forge/linux-64/cupy-core-13.4.1-py313h2626f57_0.conda#61b65ec6afaf6bf07e50bf32d4363461\n+https://conda.anaconda.org/conda-forge/linux-64/libgoogle-cloud-storage-2.39.0-hdbdcf42_0.conda#bd21962ff8a9d1ce4720d42a35a4af40\n+https://conda.anaconda.org/conda-forge/linux-64/libtorch-2.10.0-cuda129_generic_ha70ccd2_201.conda#8ecb348d9f4c748e79afa17308d23d49\n https://conda.anaconda.org/conda-forge/noarch/meson-python-0.19.0-pyh7e86bf3_2.conda#369afcc2d4965e7a6a075ab82e2a26b8\n-https://conda.anaconda.org/conda-forge/linux-64/mkl-2024.2.2-ha770c72_17.conda#e4ab075598123e783b788b995afbdad0\n+https://conda.anaconda.org/conda-forge/linux-64/optree-0.18.0-py313h7037e92_0.conda#33901d2cb4969c6b57eefe767d69fa69\n https://conda.anaconda.org/conda-forge/linux-64/pandas-3.0.0-py313hbfd7664_0.conda#ab6d05e915ab2ae4c41d275b14592151\n https://conda.anaconda.org/conda-forge/noarch/pytest-9.0.2-pyhcf101f3_0.conda#2b694bad8a50dc2f712f5368de866480\n https://conda.anaconda.org/conda-forge/linux-64/scipy-1.17.0-py313h4b8bb8b_1.conda#2b18fe5b4b2d1611ddf8c2f080a46563\n https://conda.anaconda.org/conda-forge/noarch/sympy-1.14.0-pyh2585a3b_105.conda#8c09fac3785696e1c477156192d64b91\n-https://conda.anaconda.org/conda-forge/linux-64/aws-sdk-cpp-1.11.458-hc430e4a_4.conda#aeefac461bea1f126653c1285cf5af08\n-https://conda.anaconda.org/conda-forge/linux-64/azure-storage-files-datalake-cpp-12.12.0-ha633028_1.conda#7c1980f89dd41b097549782121a73490\n+https://conda.anaconda.org/conda-forge/linux-64/aws-sdk-cpp-1.11.606-h20b40b1_10.conda#937d1d4c233adc6eeb2ac3d6e9a73e53\n+https://conda.anaconda.org/conda-forge/linux-64/azure-storage-files-datalake-cpp-12.14.0-hd454692_0.conda#55986e49b7aafe9aa09d7f4c70a56a18\n https://conda.anaconda.org/conda-forge/linux-64/blas-2.305-openblas.conda#b5a8cdf31d419b93058163399b691c75\n-https://conda.anaconda.org/conda-forge/linux-64/cupy-13.4.1-py313h66a2ee2_0.conda#784d6bd149ef2b5d9c733ea3dd4d15ad\n-https://conda.anaconda.org/conda-forge/linux-64/harfbuzz-12.2.0-h15599e2_0.conda#b8690f53007e9b5ee2c2178dd4ac778c\n-https://conda.anaconda.org/conda-forge/linux-64/libtorch-2.5.1-cuda118_hb34f2e8_303.conda#da799bf557ff6376a1a58f40bddfb293\n+https://conda.anaconda.org/conda-forge/linux-64/cupy-13.4.1-py313hdf5e20e_0.conda#b5bab25cd2f86d0425fbac36b75ea9bc\n+https://conda.anaconda.org/conda-forge/linux-64/harfbuzz-12.3.2-h6083320_0.conda#d170a70fc1d5c605fcebdf16851bd54a\n https://conda.anaconda.org/conda-forge/linux-64/matplotlib-base-3.10.8-py313h683a580_0.conda#ffe67570e1a9192d2f4c189b27f75f89\n https://conda.anaconda.org/conda-forge/linux-64/polars-runtime-32-1.37.1-py310hffdcd12_0.conda#732a536c6ce768f096f5340121e10cc5\n https://conda.anaconda.org/conda-forge/linux-64/pyamg-5.3.0-py313hfaae9d9_1.conda#6d308eafec3de495f6b06ebe69c990ed\n https://conda.anaconda.org/conda-forge/noarch/pytest-cov-6.3.0-pyhd8ed1ab_0.conda#50d191b852fccb4bf9ab7b59b030c99d\n https://conda.anaconda.org/conda-forge/noarch/pytest-xdist-3.8.0-pyhd8ed1ab_0.conda#8375cfbda7c57fbceeda18229be10417\n-https://conda.anaconda.org/conda-forge/linux-64/libarrow-18.1.0-h44a453e_6_cpu.conda#2cf6d608d6e66506f69797d5c6944c35\n+https://conda.anaconda.org/conda-forge/linux-64/pytorch-2.10.0-cuda129_generic_py313_h673abb8_201.conda#f8dae51be1b9afdccd70b576b8f73b44\n+https://conda.anaconda.org/rapidsai/linux-64/rmm-25.08.00-cuda12_py313_250806_63a4d366.conda#967087ac0c607d3118d4b162978a76f4\n+https://conda.anaconda.org/conda-forge/linux-64/libarrow-23.0.0-h2c50142_1_cpu.conda#fba261a7ee565b711b45c5bea554e5a0\n https://conda.anaconda.org/conda-forge/noarch/polars-1.37.1-pyh6a1acc5_0.conda#1894d4373da653406c91e20ef89f05c8\n-https://conda.anaconda.org/conda-forge/linux-64/pytorch-2.5.1-cuda118_py313h40cdc2d_303.conda#19ad990954a4ed89358d91d0a3e7016d\n-https://conda.anaconda.org/conda-forge/linux-64/qt6-main-6.9.2-h5bd77bc_1.conda#f7bfe5b8e7641ce7d11ea10cfd9f33cc\n-https://conda.anaconda.org/conda-forge/linux-64/libarrow-acero-18.1.0-hcb10f89_6_cpu.conda#143f9288b64759a6427563f058c62f2b\n-https://conda.anaconda.org/conda-forge/linux-64/libparquet-18.1.0-h081d1f1_6_cpu.conda#68788df49ce7480187eb6387f15b2b67\n-https://conda.anaconda.org/conda-forge/linux-64/pyarrow-core-18.1.0-py313he5f92c8_0_cpu.conda#5380e12f4468e891911dbbd4248b521a\n-https://conda.anaconda.org/conda-forge/linux-64/pyside6-6.9.2-py313ha3f37dd_1.conda#e2ec46ec4c607b97623e7b691ad31c54\n-https://conda.anaconda.org/conda-forge/linux-64/pytorch-gpu-2.5.1-cuda126hf7c78f0_303.conda#afaf760e55725108ae78ed41198c49bb\n-https://conda.anaconda.org/conda-forge/linux-64/libarrow-dataset-18.1.0-hcb10f89_6_cpu.conda#20ca46a6bc714a6ab189d5b3f46e66d8\n+https://conda.anaconda.org/conda-forge/linux-64/pytorch-gpu-2.10.0-cuda129_generic_h1715cf7_201.conda#fb17e944f1ff5c1ab65822ba1f539b9d\n+https://conda.anaconda.org/conda-forge/linux-64/qt6-main-6.10.1-hb82b983_4.conda#f4dfd61ec958d420bebdcefeb805d658\n+https://conda.anaconda.org/rapidsai/linux-64/ucxx-0.45.01-cuda12_py313_250806_c25d2cdb.conda#f9c5b31a6977929e9aa288feffd6fc7a\n+https://conda.anaconda.org/conda-forge/linux-64/libarrow-compute-23.0.0-h8c2c5c3_1_cpu.conda#102be5396c7899675268c17993e1a072\n+https://conda.anaconda.org/conda-forge/linux-64/libparquet-23.0.0-h7376487_1_cpu.conda#e7562d15926b3cea66a6e3546b133c5d\n+https://conda.anaconda.org/rapidsai/linux-64/libraft-headers-25.08.00-cuda12_250806_2fb92393.conda#cbcb008978b2e7fd29995b8de4b4e7f2\n+https://conda.anaconda.org/conda-forge/linux-64/pyside6-6.10.1-py313h85046ba_0.conda#2c5d21d466ef1ff0c0a98cfdbaf5c64b\n+https://conda.anaconda.org/conda-forge/linux-64/libarrow-acero-23.0.0-h635bf11_1_cpu.conda#8b1290b259b24a4b29b3a3d6dec0fe53\n+https://conda.anaconda.org/rapidsai/linux-64/libcuvs-25.08.00-cuda12_250806_9ce11a0f.conda#864f524cef608705031c54db01fb31d9\n+https://conda.anaconda.org/rapidsai/linux-64/libraft-25.08.00-cuda12_250806_2fb92393.conda#cf1d59daaaa86e2d5841f6ce9fc2a10d\n https://conda.anaconda.org/conda-forge/linux-64/matplotlib-3.10.8-py313h78bf25f_0.conda#85bce686dd57910d533807562204e16b\n-https://conda.anaconda.org/conda-forge/linux-64/libarrow-substrait-18.1.0-h3ee7192_6_cpu.conda#aa313b3168caf98d00b3753f5ba27650\n-https://conda.anaconda.org/conda-forge/linux-64/pyarrow-18.1.0-py313h78bf25f_0.conda#a11d880ceedc33993c6f5c14a80ea9d3\n+https://conda.anaconda.org/conda-forge/linux-64/pyarrow-core-23.0.0-py313he109ebe_0_cpu.conda#9120bf253ebbdb0015069b9a25cf4d36\n+https://conda.anaconda.org/conda-forge/linux-64/libarrow-dataset-23.0.0-h635bf11_1_cpu.conda#651c34402277a875986db6fa7930d42d\n+https://conda.anaconda.org/rapidsai/linux-64/pylibraft-25.08.00-cuda12_py313_250806_2fb92393.conda#a4e3e89406631b9c5fe94e1971bdc049\n+https://conda.anaconda.org/rapidsai/linux-64/cuvs-25.08.00-cuda12_py313_250806_9ce11a0f.conda#beec28b5e042219ff268caecc852ec2f\n+https://conda.anaconda.org/conda-forge/linux-64/libarrow-substrait-23.0.0-h3f74fd7_1_cpu.conda#bcf3ca0f04ed703121db4012e8c8bf5a\n+https://conda.anaconda.org/conda-forge/linux-64/pyarrow-23.0.0-py313h78bf25f_0.conda#a6e89cb214f318db9548b791ba27f862" }, { "filename": "build_tools/github/pylatest_conda_forge_cuda_array-api_linux-64_environment.yml", "status": "modified", "additions": 1, "deletions": 0, "changes": 1, "patch": "@@ -27,4 +27,5 @@ dependencies:\n - polars\n - pyarrow\n - cupy\n+ - rapidsai::cuvs\n - array-api-strict" }, { "filename": "build_tools/github/pylatest_conda_forge_cuda_array-api_linux-64_virtual_package_spec.yml", "status": "added", "additions": 9, "deletions": 0, "changes": 9, "patch": "@@ -0,0 +1,9 @@\n+# The versions of the virtual packages here are taken from running\n+# build_tools/github/create_gpu_environment.sh which outputs\n+# the versions of the packages used in the CUDA CI runner.\n+# Do not set them to what you see on your local machine.\n+subdirs:\n+ linux-64:\n+ packages:\n+ __cuda: \"12.8\"\n+ __glibc: \"2.39\"" }, { "filename": "build_tools/update_environments_and_lock_files.py", "status": "modified", "additions": 31, "deletions": 17, "changes": 48, "patch": "@@ -109,8 +109,11 @@ def remove_from(alist, to_remove):\n \"polars\",\n \"pyarrow\",\n \"cupy\",\n+ # cuvs is needed for cupyx.scipy.spatial.distance.cdist and friends\n+ \"rapidsai::cuvs\",\n \"array-api-strict\",\n ],\n+ \"virtual_package_spec\": True,\n },\n {\n \"name\": \"pylatest_conda_forge_mkl_linux-64\",\n@@ -553,22 +556,26 @@ def write_all_conda_environments(build_metadata_list):\n write_conda_environment(build_metadata)\n \n \n-def conda_lock(environment_path, lock_file_path, platform):\n- execute_command(\n- [\n- \"conda-lock\",\n- \"lock\",\n- \"--mamba\",\n- \"--kind\",\n- \"explicit\",\n- \"--platform\",\n- platform,\n- \"--file\",\n- str(environment_path),\n- \"--filename-template\",\n- str(lock_file_path),\n- ]\n- )\n+def conda_lock(\n+ environment_path, lock_file_path, platform, virtual_package_spec_path=None\n+):\n+ cmd = [\n+ \"conda-lock\",\n+ \"lock\",\n+ \"--mamba\",\n+ \"--kind\",\n+ \"explicit\",\n+ \"--platform\",\n+ platform,\n+ \"--file\",\n+ str(environment_path),\n+ \"--filename-template\",\n+ str(lock_file_path),\n+ ]\n+ if virtual_package_spec_path is not None:\n+ cmd.extend([\"--virtual-package-spec\", str(virtual_package_spec_path)])\n+\n+ execute_command(cmd)\n \n \n def create_conda_lock_file(build_metadata):\n@@ -581,7 +588,14 @@ def create_conda_lock_file(build_metadata):\n lock_file_basename = f\"{lock_file_basename}_{platform}\"\n \n lock_file_path = folder_path / f\"{lock_file_basename}_conda.lock\"\n- conda_lock(environment_path, lock_file_path, platform)\n+\n+ virtual_package_spec_path = None\n+ if build_metadata.get(\"virtual_package_spec\"):\n+ virtual_package_spec_path = (\n+ folder_path / f\"{lock_file_basename}_virtual_package_spec.yml\"\n+ )\n+\n+ conda_lock(environment_path, lock_file_path, platform, virtual_package_spec_path)\n \n \n def write_all_conda_lock_files(build_metadata_list):" }, { "filename": "sklearn/utils/_test_common/instance_generator.py", "status": "modified", "additions": 4, "deletions": 0, "changes": 4, "patch": "@@ -1143,6 +1143,10 @@ def _yield_instances_for_check(check, estimator_orig):\n \"sample_weight is not equivalent to removing/repeating samples.\"\n ),\n },\n+ PCA: {\n+ # TODO: see gh-33205 for details\n+ \"check_array_api_input\": \"`linalg.inv` fails because input is singular\",\n+ },\n Perceptron: {\n # TODO: replace by a statistical test, see meta-issue #16298\n \"check_sample_weight_equivalence_on_dense_data\": (" } ], "reviews": [ { "id": 3738527414, "user": "user_5819d17296ee", "state": "COMMENTED", "body": "> What do you think about adding cuvs in this PR already? It is needed in cupy for spatial distance functions like cdist. Without cuvs installed those functions fail when you call them.\n\nI am fine with this, but we should explain that it's an optional dependency of cupy to get the SciPy `cdist` function to work on CUDA devices.", "submitted_at": "2026-02-02T10:32:44+00:00" }, { "id": 3738614801, "user": "user_fca2535bcd49", "state": "COMMENTED", "body": "Nice, it does look like this updates PyTorch to a recent version", "submitted_at": "2026-02-02T10:44:09+00:00" }, { "id": 3738657334, "user": "user_5819d17296ee", "state": "COMMENTED", "body": null, "submitted_at": "2026-02-02T10:47:22+00:00" }, { "id": 3738660149, "user": "user_5819d17296ee", "state": "COMMENTED", "body": null, "submitted_at": "2026-02-02T10:48:07+00:00" }, { "id": 3738749885, "user": "user_d5b9cb906259", "state": "COMMENTED", "body": null, "submitted_at": "2026-02-02T11:07:58+00:00" }, { "id": 3739471962, "user": "user_d5b9cb906259", "state": "COMMENTED", "body": null, "submitted_at": "2026-02-02T13:40:47+00:00" }, { "id": 3739528940, "user": "user_d5b9cb906259", "state": "COMMENTED", "body": null, "submitted_at": "2026-02-02T13:50:18+00:00" }, { "id": 3739547958, "user": "user_5819d17296ee", "state": "COMMENTED", "body": "Would the following be a suitable justification?", "submitted_at": "2026-02-02T13:54:08+00:00" }, { "id": 3740069058, "user": "user_d5b9cb906259", "state": "COMMENTED", "body": null, "submitted_at": "2026-02-02T15:09:51+00:00" }, { "id": 3740149761, "user": "user_d5b9cb906259", "state": "COMMENTED", "body": null, "submitted_at": "2026-02-02T15:22:04+00:00" }, { "id": 3740331878, "user": "user_5819d17296ee", "state": "APPROVED", "body": "LGTM after rerunning the CUDA CI and XFAILing the PCA test as suggested in https://github.com/[USER_REDACTED]n/scikit-learn/pull/33175#issuecomment-3834360881.", "submitted_at": "2026-02-02T15:51:11+00:00" }, { "id": 3746815412, "user": "user_fca2535bcd49", "state": "COMMENTED", "body": null, "submitted_at": "2026-02-03T18:16:30+00:00" }, { "id": 3749442937, "user": "user_d5b9cb906259", "state": "COMMENTED", "body": null, "submitted_at": "2026-02-04T07:31:33+00:00" }, { "id": 3751736643, "user": "user_fca2535bcd49", "state": "COMMENTED", "body": null, "submitted_at": "2026-02-04T15:30:20+00:00" } ], "review_comments": [ { "id": 2753610444, "user": "user_5819d17296ee", "body": "Do we need to add the channel? Wouldn't just adding the `rapidsai`-scoped `cuvs` (`rapidsai::cuvs`) in the dependencies section be enough?", "path": "build_tools/github/pylatest_conda_forge_cuda_array-api_linux-64_environment.yml", "line": null, "side": "RIGHT", "created_at": "2026-02-02T10:23:07+00:00" }, { "id": 2753682350, "user": "user_fca2535bcd49", "body": "Out of curiosity, do we need to mention `glibc`?", "path": "build_tools/github/virtual-packages-cuda.yml", "line": null, "side": "RIGHT", "created_at": "2026-02-02T10:38:06+00:00" }, { "id": 2753685240, "user": "user_fca2535bcd49", "body": "It would be nice to add a comment saying that the version need to match the GPU runner and ideally explain how to figure out what the CUDA version is on the GPU runner ...", "path": "build_tools/github/virtual-packages-cuda.yml", "line": null, "side": "RIGHT", "created_at": "2026-02-02T10:38:43+00:00" }, { "id": 2753703407, "user": "user_fca2535bcd49", "body": "Maybe rather than special-casing like this, add a `virtual_package_spec_filename` (or a better name) key in the build dictionary i.e. something like this\n```py\nbuild_metadata_list = [\n {\n \"name\": \"pylatest_conda_forge_cuda_array-api_linux-64\",\n \"type\": \"conda\",\n \"tag\": \"cuda\",\n \"folder\": \"build_tools/github\",\n \"platform\": \"linux-64\",\n \"channels\": [\"conda-forge\"],\n \"conda_dependencies\": common_dependencies\n + [\n \"ccache\",\n \"pytorch-gpu\",\n \"polars\",\n \"pyarrow\",\n \"cupy\",\n \"array-api-strict\",\n ],\n \"virtual_package_spec_filename\": \"build_tools/github/virtual-packages-cuda.yml\"\n },\n ...\n]", "path": "build_tools/update_environments_and_lock_files.py", "line": null, "side": "RIGHT", "created_at": "2026-02-02T10:43:32+00:00" }, { "id": 2753718222, "user": "user_5819d17296ee", "body": "I think we should add an inline comment to explain why these virtual packages are set to those values (and how/when they should be updated).", "path": "build_tools/github/virtual-packages-cuda.yml", "line": null, "side": "RIGHT", "created_at": "2026-02-02T10:47:22+00:00" }, { "id": 2753720851, "user": "user_5819d17296ee", "body": "I just saw that Loïc had the same comment next...", "path": "build_tools/github/virtual-packages-cuda.yml", "line": null, "side": "RIGHT", "created_at": "2026-02-02T10:48:07+00:00" }, { "id": 2753800066, "user": "user_d5b9cb906259", "body": "I had the same question and the answer is yes. It seems like using this spec file removes the other defaults/detection mechanism. I'll add a comment to the file.\n\nThe way I chose the values is: educated guess. Trying to figure out what version of CUDA is installed in the CI runner is tricky - I think I might temporarily add something to the CUDA CI job that prints the version. Maybe it is also possible to run a `conda` command to find out which version of `__glibc` is used on the CUDA CI runner.", "path": "build_tools/github/virtual-packages-cuda.yml", "line": null, "side": "RIGHT", "created_at": "2026-02-02T11:07:58+00:00" }, { "id": 2754391992, "user": "user_d5b9cb906259", "body": "Resolved now. Added a comment on where to get the values from (CUDA CI job output)", "path": "build_tools/github/virtual-packages-cuda.yml", "line": null, "side": "RIGHT", "created_at": "2026-02-02T13:40:46+00:00" }, { "id": 2754435595, "user": "user_d5b9cb906259", "body": "The generated environment and lockfile are the same with and without -> removing the channel", "path": "build_tools/github/pylatest_conda_forge_cuda_array-api_linux-64_environment.yml", "line": null, "side": "RIGHT", "created_at": "2026-02-02T13:50:17+00:00" }, { "id": 2754451068, "user": "user_5819d17296ee", "body": "```suggestion\n \"rapidsai::cuvs\", # needed by [NAME_REDACTED]\n```", "path": "build_tools/update_environments_and_lock_files.py", "line": 113, "side": "RIGHT", "created_at": "2026-02-02T13:53:26+00:00" }, { "id": 2754830051, "user": "user_d5b9cb906259", "body": "While thinking about this I went with your suggestion of including it in the dictionary. It seemed weird to have the path to the file with directories, etc in the config though. So now if you set `\"virtual_package_spec\": True` in the dictionary it loads the spec file from a name that is generated based on the `\"name\"` key (similar to env and lockfile)", "path": "build_tools/update_environments_and_lock_files.py", "line": null, "side": "RIGHT", "created_at": "2026-02-02T15:09:51+00:00" }, { "id": 2754891671, "user": "user_d5b9cb906259", "body": "I used a variation on this. I am not sure I understand why `cuvs` isn't a dependency of `cupy` given that things like `cdist` require it.\n\nIt is technically an optional dependency, but if you want to use the spatial module you need it (there is no slower fallback).", "path": "build_tools/update_environments_and_lock_files.py", "line": 113, "side": "RIGHT", "created_at": "2026-02-02T15:22:04+00:00" }, { "id": 2760375261, "user": "user_fca2535bcd49", "body": "This xfails the test all the time right? This seems a bit too coarse if this only fails for a particular combination (PyTorch CPU something something I think?), maybe add a comment with a TODO to feel better about it?", "path": "sklearn/utils/_test_common/instance_generator.py", "line": 1148, "side": "RIGHT", "created_at": "2026-02-03T18:16:30+00:00" }, { "id": 2762603462, "user": "user_d5b9cb906259", "body": "I created #33205 and reference this from the comment.\n\nI was wondering if there was a nice way to only xfail a particular combo, but I think it would be tricky (you'd need code in the check itself). Seems too much extra stuff, especially because I hope Olivier will propose a PR soon that fixes this ;)", "path": "sklearn/utils/_test_common/instance_generator.py", "line": 1148, "side": "RIGHT", "created_at": "2026-02-04T07:31:33+00:00" }, { "id": 2764604523, "user": "user_fca2535bcd49", "body": "Good enough, thanks for getting to the bottom of this!", "path": "sklearn/utils/_test_common/instance_generator.py", "line": 1148, "side": "RIGHT", "created_at": "2026-02-04T15:30:19+00:00" } ], "meta": { "languages": [ "lock", "py", "sh", "yml" ], "touches_tests": true, "review_state_summary": { "COMMENTED": 13, "APPROVED": 1 }, "meaningful_comment_count": 15, "has_approval": true, "has_changes_requested": false, "total_review_comments": 15 } } { "_id": "a1e5741f65e12ec7", "_schema_version": "1.0", "_cleaned_at": "2026-02-12T07:46:51.920962+00:00", "repo": "scikit-learn/scikit-learn", "repo_url": "https://github.com/scikit-learn/scikit-learn", "license_name": "BSD 3-Clause \"New\" or \"Revised\" License", "license_spdx": "BSD-3-Clause", "pr_number": 33168, "title": "FIX _predict_proba_lr in LinearClassifierMixin", "body": "#### [NAME_REDACTED]/PRs\nFixes #17978.\n\n#### What does this implement/fix? Explain your changes.\n`LinearClassifierMixin._predict_proba_lr` might return nan or inf if `decision_function` returns large negative values, because all probabilities are zero in floating point arithmetic (e.g. exp(-1000) = 0).\n\n#### AI usage disclosure\nNone\n\n#### Any other comments?\nI guess the only estimator is `SGDClassifier`, not 100% sure.", "author": "user_22bafe4fe1a9", "created_at": "2026-02-01T21:08:10+00:00", "merged_at": "2026-02-02T10:19:47+00:00", "base_branch": "main", "head_branch": "fix_predict_proba_lr", "additions": 39, "deletions": 1, "changed_files": 3, "files": [ { "filename": "doc/whats_new/upcoming_changes/sklearn.linear_model/33168.fix.rst", "status": "added", "additions": 4, "deletions": 0, "changes": 4, "patch": "@@ -0,0 +1,4 @@\n+- Fixed a bug in :class:`linear_model.SGDClassifier` for multiclass settings where\n+ large negative values of :method:`decision_function` could lead to NaN values. In\n+ this case, this fix assigns equal probability for each class.\n+ By :user:`[NAME_REDACTED] `." }, { "filename": "sklearn/linear_model/_base.py", "status": "modified", "additions": 8, "deletions": 1, "changes": 9, "patch": "@@ -405,7 +405,14 @@ def _predict_proba_lr(self, X):\n return np.vstack([1 - prob, prob]).T\n else:\n # OvR normalization, like LibLinear's predict_probability\n- prob /= prob.sum(axis=1).reshape((prob.shape[0], -1))\n+ prob_sum = prob.sum(axis=1)\n+ all_zero = prob_sum == 0\n+ if np.any(all_zero):\n+ # The above might assign zero to all classes, which doesn't\n+ # normalize neatly; work around this to produce uniform probabilities.\n+ prob[all_zero, :] = 1\n+ prob_sum[all_zero] = prob.shape[1] # n_classes\n+ prob /= prob_sum.reshape((prob.shape[0], -1))\n return prob" }, { "filename": "sklearn/linear_model/tests/test_base.py", "status": "modified", "additions": 27, "deletions": 0, "changes": 27, "patch": "@@ -7,9 +7,11 @@\n import pytest\n from scipy import linalg, sparse\n \n+from sklearn.base import BaseEstimator\n from sklearn.datasets import load_iris, make_regression, make_sparse_uncorrelated\n from sklearn.linear_model import LinearRegression\n from sklearn.linear_model._base import (\n+ LinearClassifierMixin,\n _preprocess_data,\n _rescale_data,\n make_dataset,\n@@ -844,3 +846,28 @@ def test_linear_regression_sample_weight_consistency(\n assert_allclose(reg1.coef_, reg2.coef_, rtol=1e-6)\n if fit_intercept:\n assert_allclose(reg1.intercept_, reg2.intercept_)\n+\n+\n+def test_predict_proba_lr_large_values():\n+ \"\"\"Test that _predict_proba_lr of LinearClassifierMixin deals with large\n+ negative values.\n+\n+ Note that exp(-1000) = 0.\n+ \"\"\"\n+\n+ class MockClassifier(LinearClassifierMixin, BaseEstimator):\n+ def __init__(self):\n+ pass\n+\n+ def fit(self, X, y):\n+ self.__sklearn_is_fitted__ = True\n+\n+ def decision_function(self, X):\n+ n_samples = X.shape[0]\n+ return np.tile([-1000.0] * 4, [n_samples, 1])\n+\n+ clf = MockClassifier()\n+ clf.fit(X=None, y=None)\n+\n+ proba = clf._predict_proba_lr(np.ones(5))\n+ assert_allclose(np.sum(proba, axis=1), 1)" } ], "reviews": [ { "id": 3737719737, "user": "user_3c90b5520ec5", "state": "APPROVED", "body": "LGTM. Thank you [USER_REDACTED]", "submitted_at": "2026-02-02T07:27:28+00:00" }, { "id": 3738509777, "user": "user_5819d17296ee", "state": "APPROVED", "body": "LGTM.", "submitted_at": "2026-02-02T10:19:33+00:00" } ], "review_comments": [ { "id": 2752926920, "user": "user_3c90b5520ec5", "body": "```suggestion\n \"\"\"Test that _predict_proba_lr of LinearClassifierMixin deals with large\n negative values.\n```", "path": "sklearn/linear_model/tests/test_base.py", "line": null, "side": "RIGHT", "created_at": "2026-02-02T07:23:37+00:00" } ], "meta": { "languages": [ "py", "rst" ], "touches_tests": true, "review_state_summary": { "APPROVED": 2 }, "meaningful_comment_count": 1, "has_approval": true, "has_changes_requested": false, "total_review_comments": 1 } } { "_id": "e2d60adc38ee0cf2", "_schema_version": "1.0", "_cleaned_at": "2026-02-12T07:46:51.921956+00:00", "repo": "scikit-learn/scikit-learn", "repo_url": "https://github.com/scikit-learn/scikit-learn", "license_name": "BSD 3-Clause \"New\" or \"Revised\" License", "license_spdx": "BSD-3-Clause", "pr_number": 33161, "title": "ENH speedup gap safe screening", "body": "#### [NAME_REDACTED]/PRs\nImprovement on top of #31882, #31986, #31987 and #32014.\n\n#### What does this implement/fix? Explain your changes.\nThis PR prevents the update of the residual inside the screening if the coefficient is already zero.\n\n#### AI usage disclosure\nNo\n\n#### Any other comments?", "author": "user_22bafe4fe1a9", "created_at": "2026-01-30T17:36:52+00:00", "merged_at": "2026-02-02T06:38:52+00:00", "base_branch": "main", "head_branch": "cd_speedup_screening", "additions": 63, "deletions": 46, "changed_files": 2, "files": [ { "filename": "doc/whats_new/upcoming_changes/sklearn.linear_model/33161.enhancement.rst", "status": "added", "additions": 9, "deletions": 0, "changes": 9, "patch": "@@ -0,0 +1,9 @@\n+- |Efficiency| :class:`linear_model.ElasticNet`, :class:`linear_model.ElasticNetCV`,\n+ :class:`linear_model.Lasso`, :class:`linear_model.LassoCV`,\n+ :class:`linear_model.MultiTaskElasticNet`, :class:`linear_model.MultiTaskElasticNetCV`\n+ :class:`linear_model.MultiTaskLasso`, :class:`linear_model.MultiTaskLassoCV`\n+ as well as\n+ :func:`linear_model.lasso_path` and :func:`linear_model.enet_path` are now faster when\n+ fit with strong L1 penalty and many features. During gap safe screening of features,\n+ the update of the residual is now only performed if the coefficient is not zero.\n+ By :user:`[NAME_REDACTED] `." }, { "filename": "sklearn/linear_model/_cd_fast.pyx", "status": "modified", "additions": 54, "deletions": 46, "changes": 100, "patch": "@@ -378,9 +378,10 @@ def enet_coordinate_descent(\n excluded_set[j] = 0\n n_active += 1\n else:\n- # R += w[j] * X[:,j]\n- _axpy(n_samples, w[j], &X[0, j], 1, &R[0], 1)\n- w[j] = 0\n+ if w[j] != 0:\n+ # R += w[j] * X[:,j]\n+ _axpy(n_samples, w[j], &X[0, j], 1, &R[0], 1)\n+ w[j] = 0\n excluded_set[j] = 1\n \n for n_iter in range(max_iter):\n@@ -448,9 +449,10 @@ def enet_coordinate_descent(\n excluded_set[j] = 0\n n_active += 1\n else:\n- # R += w[j] * X[:,j]\n- _axpy(n_samples, w[j], &X[0, j], 1, &R[0], 1)\n- w[j] = 0\n+ if w[j] != 0:\n+ # R += w[j] * X[:,j]\n+ _axpy(n_samples, w[j], &X[0, j], 1, &R[0], 1)\n+ w[j] = 0\n excluded_set[j] = 1\n \n else:\n@@ -809,21 +811,22 @@ def sparse_enet_coordinate_descent(\n excluded_set[j] = 0\n n_active += 1\n else:\n- # R += w[j] * X[:,j]\n- R_plus_wj_Xj(\n- n_samples,\n- R,\n- X_data,\n- X_indices,\n- X_indptr,\n- X_mean,\n- center,\n- sample_weight,\n- no_sample_weights,\n- w[j],\n- j,\n- )\n- w[j] = 0\n+ if w[j] != 0:\n+ # R += w[j] * X[:,j]\n+ R_plus_wj_Xj(\n+ n_samples,\n+ R,\n+ X_data,\n+ X_indices,\n+ X_indptr,\n+ X_mean,\n+ center,\n+ sample_weight,\n+ no_sample_weights,\n+ w[j],\n+ j,\n+ )\n+ w[j] = 0\n excluded_set[j] = 1\n \n for n_iter in range(max_iter):\n@@ -925,21 +928,22 @@ def sparse_enet_coordinate_descent(\n excluded_set[j] = 0\n n_active += 1\n else:\n- # R += w[j] * X[:,j]\n- R_plus_wj_Xj(\n- n_samples,\n- R,\n- X_data,\n- X_indices,\n- X_indptr,\n- X_mean,\n- center,\n- sample_weight,\n- no_sample_weights,\n- w[j],\n- j,\n- )\n- w[j] = 0\n+ if w[j] != 0:\n+ # R += w[j] * X[:,j]\n+ R_plus_wj_Xj(\n+ n_samples,\n+ R,\n+ X_data,\n+ X_indices,\n+ X_indptr,\n+ X_mean,\n+ center,\n+ sample_weight,\n+ no_sample_weights,\n+ w[j],\n+ j,\n+ )\n+ w[j] = 0\n excluded_set[j] = 1\n \n else:\n@@ -1150,9 +1154,10 @@ def enet_coordinate_descent_gram(\n excluded_set[j] = 0\n n_active += 1\n else:\n- # Qw -= w[j] * Q[j] # Update Qw = Q @ w\n- _axpy(n_features, -w[j], &Q[j, 0], 1, &Qw[0], 1)\n- w[j] = 0\n+ if w[j] != 0:\n+ # Qw -= w[j] * Q[j] # Update Qw = Q @ w\n+ _axpy(n_features, -w[j], &Q[j, 0], 1, &Qw[0], 1)\n+ w[j] = 0\n excluded_set[j] = 1\n \n for n_iter in range(max_iter):\n@@ -1221,9 +1226,10 @@ def enet_coordinate_descent_gram(\n excluded_set[j] = 0\n n_active += 1\n else:\n- # Qw -= w[j] * Q[j] # Update Qw = Q @ w\n- _axpy(n_features, -w[j], &Q[j, 0], 1, &Qw[0], 1)\n- w[j] = 0\n+ if w[j] != 0:\n+ # Qw -= w[j] * Q[j] # Update Qw = Q @ w\n+ _axpy(n_features, -w[j], &Q[j, 0], 1, &Qw[0], 1)\n+ w[j] = 0\n excluded_set[j] = 1\n \n else:\n@@ -1462,8 +1468,9 @@ def enet_coordinate_descent_multi_task(\n else:\n # R += W[:, 1] * X[:, 1][:, None]\n for t in range(n_tasks):\n- _axpy(n_samples, W[t, j], &X[0, j], 1, &R[0, t], 1)\n- W[t, j] = 0\n+ if W[t, j] != 0:\n+ _axpy(n_samples, W[t, j], &X[0, j], 1, &R[0, t], 1)\n+ W[t, j] = 0\n excluded_set[j] = 1\n \n for n_iter in range(max_iter):\n@@ -1559,8 +1566,9 @@ def enet_coordinate_descent_multi_task(\n else:\n # R += W[:, 1] * X[:, 1][:, None]\n for t in range(n_tasks):\n- _axpy(n_samples, W[t, j], &X[0, j], 1, &R[0, t], 1)\n- W[t, j] = 0\n+ if W[t, j] != 0:\n+ _axpy(n_samples, W[t, j], &X[0, j], 1, &R[0, t], 1)\n+ W[t, j] = 0\n excluded_set[j] = 1\n \n else:" } ], "reviews": [ { "id": 3730271357, "user": "user_04b4a5f4e2a8", "state": "COMMENTED", "body": null, "submitted_at": "2026-01-30T20:31:15+00:00" }, { "id": 3731925710, "user": "user_22bafe4fe1a9", "state": "COMMENTED", "body": null, "submitted_at": "2026-01-31T07:25:56+00:00" }, { "id": 3735890936, "user": "user_04b4a5f4e2a8", "state": "APPROVED", "body": "LGTM", "submitted_at": "2026-02-01T15:18:20+00:00" }, { "id": 3737564870, "user": "user_3c90b5520ec5", "state": "APPROVED", "body": "LGTM. Thank you [USER_REDACTED]", "submitted_at": "2026-02-02T06:38:44+00:00" } ], "review_comments": [ { "id": 2747879264, "user": "user_04b4a5f4e2a8", "body": "Should `R_plus_wj_Xj` itself early exit if `w_j` is zero? `R_plus_wj_Xj` is inline, so it should end up being the same.", "path": "sklearn/linear_model/_cd_fast.pyx", "line": 816, "side": "RIGHT", "created_at": "2026-01-30T20:25:36+00:00" }, { "id": 2749155281, "user": "user_22bafe4fe1a9", "body": "As all the other cd-versions have it exactly like this - they don't need an extra inline function - I prefer to keep it as is. This way, it really becomes clear what happens and the logic is not hidden inside `R_plus_wj_Xj`.", "path": "sklearn/linear_model/_cd_fast.pyx", "line": 816, "side": "RIGHT", "created_at": "2026-01-31T07:25:56+00:00" } ], "meta": { "languages": [ "pyx", "rst" ], "touches_tests": false, "review_state_summary": { "COMMENTED": 2, "APPROVED": 2 }, "meaningful_comment_count": 2, "has_approval": true, "has_changes_requested": false, "total_review_comments": 2 } } { "_id": "e95184142c8058be", "_schema_version": "1.0", "_cleaned_at": "2026-02-12T07:46:51.924962+00:00", "repo": "scikit-learn/scikit-learn", "repo_url": "https://github.com/scikit-learn/scikit-learn", "license_name": "BSD 3-Clause \"New\" or \"Revised\" License", "license_spdx": "BSD-3-Clause", "pr_number": 33140, "title": "Improve contribution guidelines to make it easier for maintainers to assess the user facing value of issues/PRs", "body": "As a follow-up to the discussion at our monthly meeting.\n\nI tried to explain the reasons we ask for all those requirements as [USER_REDACTED] suggested.", "author": "user_5819d17296ee", "created_at": "2026-01-26T18:02:56+00:00", "merged_at": "2026-01-28T15:31:11+00:00", "base_branch": "main", "head_branch": "improve-contribution-templates", "additions": 57, "deletions": 20, "changed_files": 2, "files": [ { "filename": ".github/ISSUE_TEMPLATE/bug_report.yml", "status": "modified", "additions": 16, "deletions": 4, "changes": 20, "patch": "@@ -10,9 +10,11 @@ body:\n addressed by [NAME_REDACTED] [the past issues](https://github.com/[USER_REDACTED]n/scikit-learn/issues).\n - type: textarea\n attributes:\n- label: Describe the bug\n+ label: Describe the bug and give evidence about its user-facing impact\n description: >\n- A clear and concise description of what the bug is.\n+ A clear and concise description of what the bug is and **how it affects you as a scikit-learn user**. Please give a few details about the context of the discovery, why you care about getting it fixed. Please do not create issues for problems you don't actually care about.\n+\n+ The scikit-learn issue tracker is swamped by [NAME_REDACTED] the expected user impact is critical to help maintainers and other contributors focus time and effort to review meaningful contributions.\n validations:\n required: true\n - type: textarea\n@@ -36,13 +38,15 @@ body:\n model = lda_model.fit(lda_features)\n ```\n \n+ If possible, craft a reproducer that only uses the public scikit-learn API or justify why you had to use some private API to trigger the problem. This helps us assess the user-facing impact of the bug.\n+\n If the code is too long, feel free to put it in a public gist and link it in the issue: https://gist.github.com.\n \n- In short, **we are going to copy-paste your code** to run it and we expect to get the same result as you.\n+ In short, **we need to be able to quickly copy-paste your code** to run it without modification and we expect to get the same result as you.\n \n We acknowledge that crafting a [minimal reproducible code example](https://scikit-learn.org/dev/developers/minimal_reproducer.html) requires some effort on your side but it really helps the maintainers quickly reproduce the problem and analyze its cause without any ambiguity. Ambiguous bug reports tend to be slower to fix because they will require more effort and back and forth discussion between the maintainers and the reporter to pin-point the precise conditions necessary to reproduce the problem.\n placeholder: |\n- ```\n+ ```python\n Sample code to reproduce the problem\n ```\n validations:\n@@ -89,6 +93,14 @@ body:\n ```\n validations:\n required: true\n+- type: textarea\n+ attributes:\n+ label: Interest in fixing the bug\n+ description: >\n+ If your issue is triaged by [NAME_REDACTED] a bug that can be reproduced, would you be interested in working on a PR to resolve it? \n+ And if you already have an idea, please explain your analysis of the root cause of the bug and a strategy for a possible fix, but please do not open a PR as long as the issue has not been triaged.\n+ validations:\n+ required: true\n - type: markdown\n attributes:\n value: >" }, { "filename": "doc/developers/contributing.rst", "status": "modified", "additions": 41, "deletions": 16, "changes": 57, "patch": "@@ -241,6 +241,23 @@ feedback:\n `_\n for more details.\n \n+- Please be explicit **how this issue impacts you as a scikit-learn user**. Giving\n+ some details (a short paragraph) about how you use scikit-learn and why you need\n+ this issue resolved will help the project maintainers invest time and effort\n+ on issues that actually impact users.\n+\n+- Please tell us if you would be interested in opening a PR to resolve your issue\n+ once triaged by a project maintainer.\n+\n+Note that the scikit-learn tracker receives `daily reports\n+`_ by\n+GitHub accounts that are mostly interested in increasing contribution\n+statistics and show little interest in the expected end-user impact of their\n+contributions. As project maintainers we want to be able to assess if our\n+efforts are likely to have a meaningful and positive impact to our end users.\n+Therefore, we ask you to avoid opening issues for things you don't actually\n+care about.\n+\n If you want to help curate issues, read about :ref:`bug_triaging`.\n \n Contributing code and documentation\n@@ -387,7 +404,25 @@ complies with the following rules before marking a PR as \"ready for review\". The\n cases \"Fix \" is enough. \"Fix #\" is never a\n good title.\n \n-2. **Make sure your code passes the tests**. The whole test suite can be run\n+2. **Pull requests are expected to resolve one or more issues**.\n+ Please **do not open PRs for issues that are labeled as \"Needs triage\"**\n+ (see :ref:`issues_tagged_needs_triage`) or with other kinds of \"Needs ...\"\n+ labels. Please do not open PRs for issues for which:\n+\n+ - the discussion has not settled down to an explicit resolution plan,\n+ - the reporter has already expressed interest in opening a PR,\n+ - there already exists cross-referenced and active PRs.\n+\n+ If merging your pull request means that some other issues/PRs should be closed,\n+ you should `use keywords to create link to them\n+ `_\n+ (e.g., ``Fixes #1234``; multiple issues/PRs are allowed as long as each\n+ one is preceded by a keyword). Upon merging, those issues/PRs will\n+ automatically be closed by GitHub. If your pull request is simply\n+ related to some other issues/PRs, or it only partially resolves the target\n+ issue, create a link to them without using the keywords (e.g., ``Towards #1234``).\n+\n+3. **Make sure your code passes the tests**. The whole test suite can be run\n with `pytest`, but it is usually not recommended since it takes a long\n time. It is often enough to only run the test related to your changes:\n for example, if you changed something in\n@@ -410,40 +445,30 @@ complies with the following rules before marking a PR as \"ready for review\". The\n you don't need to run the whole test suite locally. For guidelines on how\n to use ``pytest`` efficiently, see the :ref:`pytest_tips`.\n \n-3. **Make sure your code is properly commented and documented**, and **make\n+4. **Make sure your code is properly commented and documented**, and **make\n sure the documentation renders properly**. To build the documentation, please\n refer to our :ref:`contribute_documentation` guidelines. The CI will also\n build the docs: please refer to :ref:`generated_doc_CI`.\n \n-4. **Tests are necessary for enhancements to be\n+5. **Tests are necessary for enhancements to be\n accepted**. Bug-fixes or new features should be provided with non-regression tests.\n These tests verify the correct behavior of the fix or feature. In this manner,\n further modifications on the code base are granted to be consistent with the\n desired behavior. In the case of bug fixes, at the time of the PR, the\n non-regression tests should fail for the code base in the ``main`` branch\n and pass for the PR code.\n \n-5. If your PR is likely to affect users, you need to add a changelog entry describing\n+6. If your PR is likely to affect users, you need to add a changelog entry describing\n your PR changes. See the\n `README `_\n for more details.\n \n-6. Follow the :ref:`coding-guidelines`.\n+7. Follow the :ref:`coding-guidelines`.\n \n-7. When applicable, use the validation tools and scripts in the :mod:`sklearn.utils`\n+8. When applicable, use the validation tools and scripts in the :mod:`sklearn.utils`\n module. A list of utility routines available for developers can be found in the\n :ref:`developers-utils` page.\n \n-8. Often pull requests resolve one or more other issues (or pull requests).\n- If merging your pull request means that some other issues/PRs should\n- be closed, you should `use keywords to create link to them\n- `_\n- (e.g., ``Fixes #1234``; multiple issues/PRs are allowed as long as each\n- one is preceded by a keyword). Upon merging, those issues/PRs will\n- automatically be closed by GitHub. If your pull request is simply\n- related to some other issues/PRs, or it only partially resolves the target\n- issue, create a link to them without using the keywords (e.g., ``Towards #1234``).\n-\n 9. PRs should often substantiate the change, through benchmarks of\n performance and efficiency (see :ref:`monitoring_performances`) or through\n examples of usage. Examples also illustrate the features and intricacies of" } ], "reviews": [ { "id": 3707295116, "user": "user_5819d17296ee", "state": "COMMENTED", "body": null, "submitted_at": "2026-01-26T18:04:14+00:00" }, { "id": 3707297863, "user": "user_5819d17296ee", "state": "COMMENTED", "body": null, "submitted_at": "2026-01-26T18:04:53+00:00" }, { "id": 3709810011, "user": "user_5819d17296ee", "state": "COMMENTED", "body": null, "submitted_at": "2026-01-27T08:34:14+00:00" }, { "id": 3710335613, "user": "user_957e9cfff158", "state": "APPROVED", "body": null, "submitted_at": "2026-01-27T10:24:06+00:00" }, { "id": 3710289767, "user": "user_34a090906ca4", "state": "APPROVED", "body": "Thank you for adding this! I just have a few small comments, but I'm all for making this more explicit!", "submitted_at": "2026-01-27T10:25:28+00:00" }, { "id": 3711760948, "user": "user_d5b9cb906259", "state": "COMMENTED", "body": null, "submitted_at": "2026-01-27T15:08:44+00:00" }, { "id": 3711805849, "user": "user_d5b9cb906259", "state": "APPROVED", "body": "I like it. As always I worry about adding more words than we remove, because the docs and templates we have are already quite long. But shorter isn't always better.\n\nThere are a lot of suggestions which should be resolved but I have no strong opinion on them. So approving already.", "submitted_at": "2026-01-27T15:17:15+00:00" }, { "id": 3715749860, "user": "user_5819d17296ee", "state": "COMMENTED", "body": null, "submitted_at": "2026-01-28T09:58:44+00:00" }, { "id": 3715767060, "user": "user_5819d17296ee", "state": "COMMENTED", "body": null, "submitted_at": "2026-01-28T10:00:55+00:00" }, { "id": 3719741561, "user": "user_d16337ec046b", "state": "APPROVED", "body": "Lots of small nits but LGTM. These address the majority of the contribution problems we have been having - hopefully some people read them!\n\nThanks for working on this!", "submitted_at": "2026-01-29T00:16:20+00:00" } ], "review_comments": [ { "id": 2728678377, "user": "user_5819d17296ee", "body": "Asking the OP to be explicit about their interest in opening a PR could help reduce the comment spam from random people asking to open a PR on other contributors' issues.", "path": "doc/developers/contributing.rst", "line": null, "side": "RIGHT", "created_at": "2026-01-26T18:04:14+00:00" }, { "id": 2728680247, "user": "user_5819d17296ee", "body": "This is the second part to my attempt at reducing comment spam.", "path": "doc/developers/contributing.rst", "line": 413, "side": "RIGHT", "created_at": "2026-01-26T18:04:53+00:00" }, { "id": 2730855821, "user": "user_5819d17296ee", "body": "```suggestion\n this issue resolved will help the project maintainers invest time and effort\n```", "path": "doc/developers/contributing.rst", "line": null, "side": "RIGHT", "created_at": "2026-01-27T08:34:14+00:00" }, { "id": 2731254567, "user": "user_34a090906ca4", "body": "Should an interest in fixing a bug always already require knowing a possible solution? This could be a point of frustration if the issue is then not triaged as a bug. Maybe add something like this?\n```suggestion\n If your issue is triaged by [NAME_REDACTED] a bug that can be reproduced, would you be interested in working on a PR to resolve it? \n And if you already have an idea, please explain your analysis of the root cause of the bug and a strategy for a possible fix, but please do not open a PR as long as the issue has not been triaged.\n```", "path": ".github/ISSUE_TEMPLATE/bug_report.yml", "line": null, "side": "RIGHT", "created_at": "2026-01-27T10:13:38+00:00" }, { "id": 2731256872, "user": "user_34a090906ca4", "body": "```suggestion\n In short, **we need to be able to quickly copy-paste your code** to run it without modification and we expect to get the same result as you.\n```", "path": ".github/ISSUE_TEMPLATE/bug_report.yml", "line": null, "side": "RIGHT", "created_at": "2026-01-27T10:14:10+00:00" }, { "id": 2731270527, "user": "user_34a090906ca4", "body": "```suggestion\n- Please tell us if you would be interested in opening a PR to resolve your issue\n```", "path": "doc/developers/contributing.rst", "line": null, "side": "RIGHT", "created_at": "2026-01-27T10:17:35+00:00" }, { "id": 2731273346, "user": "user_34a090906ca4", "body": "```suggestion\nGitHub accounts that are mostly interested in increasing contribution\n```", "path": "doc/developers/contributing.rst", "line": null, "side": "RIGHT", "created_at": "2026-01-27T10:18:19+00:00" }, { "id": 2731277538, "user": "user_34a090906ca4", "body": "```suggestion\nstatistics and show little interest in the expected end-user impact of their\n```", "path": "doc/developers/contributing.rst", "line": null, "side": "RIGHT", "created_at": "2026-01-27T10:19:27+00:00" }, { "id": 2731279910, "user": "user_34a090906ca4", "body": "```suggestion\n2. **Pull requests are expected to resolve one or more issues**.\n```", "path": "doc/developers/contributing.rst", "line": null, "side": "RIGHT", "created_at": "2026-01-27T10:20:06+00:00" }, { "id": 2731289794, "user": "user_34a090906ca4", "body": "Maybe link \"Needs triage\" to https://scikit-learn.org/dev/developers/contributing.html#issues-tagged-needs-triage?", "path": "doc/developers/contributing.rst", "line": null, "side": "RIGHT", "created_at": "2026-01-27T10:22:46+00:00" }, { "id": 2732477460, "user": "user_d5b9cb906259", "body": "I'm not sure if the comment about accounts interested in building reputation helps? Maybe it does? So suggesting to remove it based on \"less text means higher chance people will read it\"\n\n```suggestion\n The scikit-learn issue tracker is swamped by [NAME_REDACTED] the expected user impact is critical to help maintainers and other contributors focus time and effort to review meaningful contributions.\n```", "path": ".github/ISSUE_TEMPLATE/bug_report.yml", "line": null, "side": "RIGHT", "created_at": "2026-01-27T15:08:44+00:00" }, { "id": 2735832057, "user": "user_5819d17296ee", "body": "I will push a follow up commit.", "path": "doc/developers/contributing.rst", "line": null, "side": "RIGHT", "created_at": "2026-01-28T09:58:44+00:00" }, { "id": 2735845794, "user": "user_5819d17296ee", "body": "```suggestion\n - the discussion has not settled down to an explicit resolution plan,\n```", "path": "doc/developers/contributing.rst", "line": null, "side": "RIGHT", "created_at": "2026-01-28T10:00:55+00:00" }, { "id": 2739114644, "user": "user_d16337ec046b", "body": "```suggestion\n A clear and concise description of what the bug is and **how it affects you as a scikit-learn user**. Please give details about the context of the discovery and why you care about getting it fixed. Please do not create issues for problems you don't actually care about.\n```\n\njust in the interest of shortening text.", "path": ".github/ISSUE_TEMPLATE/bug_report.yml", "line": 15, "side": "RIGHT", "created_at": "2026-01-28T23:50:21+00:00" }, { "id": 2739141277, "user": "user_d16337ec046b", "body": "```suggestion\n The scikit-learn issue tracker is swamped by [NAME_REDACTED] the expected user impact is critical to helping maintainers and other contributors focus time and effort on reviewing meaningful contributions.\n```\nnit", "path": ".github/ISSUE_TEMPLATE/bug_report.yml", "line": 17, "side": "RIGHT", "created_at": "2026-01-29T00:03:27+00:00" }, { "id": 2739142189, "user": "user_d16337ec046b", "body": "```suggestion\n In short, **we need to be able to copy-paste your code** and run it without modification and we expect to get the same result as you.\n```\nTims nit about adjectives 😅", "path": ".github/ISSUE_TEMPLATE/bug_report.yml", "line": 45, "side": "RIGHT", "created_at": "2026-01-29T00:03:59+00:00" }, { "id": 2739143310, "user": "user_d16337ec046b", "body": "```suggestion\n If you already have an idea, please explain your analysis of the root cause of the bug and a strategy for a possible fix, but please **do not** open a PR until the issue has been triaged.\n```\nnit", "path": ".github/ISSUE_TEMPLATE/bug_report.yml", "line": 101, "side": "RIGHT", "created_at": "2026-01-29T00:04:42+00:00" }, { "id": 2739145646, "user": "user_d16337ec046b", "body": "```suggestion\n details (a short paragraph) about how you use scikit-learn and why you need\n```", "path": "doc/developers/contributing.rst", "line": 245, "side": "RIGHT", "created_at": "2026-01-29T00:05:58+00:00" }, { "id": 2739146340, "user": "user_d16337ec046b", "body": "```suggestion\nGitHub accounts that are mostly interested in increasing their contribution\n```", "path": "doc/developers/contributing.rst", "line": 254, "side": "RIGHT", "created_at": "2026-01-29T00:06:20+00:00" }, { "id": 2739159065, "user": "user_d16337ec046b", "body": "These seem related/and repeat the line above (L24): \n\n> Please add a [minimal code example](https://scikit-learn.org/dev/developers/minimal_reproducer.html) that can reproduce the error when running it.\n\nMaybe we could add these points to the above line?", "path": ".github/ISSUE_TEMPLATE/bug_report.yml", "line": 45, "side": "RIGHT", "created_at": "2026-01-29T00:12:16+00:00" }, { "id": 2739161808, "user": "user_d16337ec046b", "body": "```suggestion\n (see :ref:`issues_tagged_needs_triage`) or with \"Needs ...\"\n labels (e.g., \"Needs investigation\"). Please do not open PRs for issues for which:\n```", "path": "doc/developers/contributing.rst", "line": 410, "side": "RIGHT", "created_at": "2026-01-29T00:13:46+00:00" }, { "id": 2739166712, "user": "user_d16337ec046b", "body": "```suggestion\n If merging your pull request means that some other issues/PRs should be closed\n (e.g., because it resolves an issue or supersedes a stalled PR),\n```\n\nNot 100% on this, feel free to ignore", "path": "doc/developers/contributing.rst", "line": 416, "side": "RIGHT", "created_at": "2026-01-29T00:15:01+00:00" } ], "meta": { "languages": [ "rst", "yml" ], "touches_tests": false, "review_state_summary": { "COMMENTED": 6, "APPROVED": 4 }, "meaningful_comment_count": 22, "has_approval": true, "has_changes_requested": false, "total_review_comments": 22 } } { "_id": "0caf0eaab296188e", "_schema_version": "1.0", "_cleaned_at": "2026-02-12T07:46:51.925950+00:00", "repo": "scikit-learn/scikit-learn", "repo_url": "https://github.com/scikit-learn/scikit-learn", "license_name": "BSD 3-Clause \"New\" or \"Revised\" License", "license_spdx": "BSD-3-Clause", "pr_number": 33139, "title": "DOC Add statement on supported versions for array API", "body": "Clarify that we develop against the latest versions of dependencies for array API work and will not introduce code to backport fixes that are available in newer versions of our dependencies.\n\n#### [NAME_REDACTED]/PRs\n\nFor example https://github.com/[USER_REDACTED]n/scikit-learn/issues/32552#issuecomment-3782563204 and https://github.com/[USER_REDACTED]n/scikit-learn/pull/33022, but we've discussed \"what versions do we support?\" a few times already in various issues and PRs.\n\n#### What does this implement/fix? Explain your changes.\n\nThis adds a statement to the array API documentation stating that we only support the latest version of scikit-learn's dependencies. It also says that we will not introduce changes that backport things to older versions of dependencies - which is kind of redundant but given https://github.com/[USER_REDACTED]n/scikit-learn/pull/33022 maybe worth stating explicitly (aka I shouldn't have made that PR).\n\n#### AI usage disclosure\n\nI used AI assistance for:\n- [ ] Code generation (e.g., when writing an implementation or fixing a bug)\n- [ ] Test/benchmark generation\n- [ ] Documentation (including examples)\n- [ ] Research and understanding\n\n#### Any other comments?\n\nI moved the environment variable paragraph as I was missing it in the \"Enable array API support\" section. In this case I went directly to that section without reading the page from the top. To me it makes sense to have it all in one place. Looking at it from a different angle: why is the env var thing mentioned at the very top, but how to enable it isn't? They both seem equally important.", "author": "user_d5b9cb906259", "created_at": "2026-01-26T14:40:06+00:00", "merged_at": "2026-01-27T09:11:15+00:00", "base_branch": "main", "head_branch": "array-api-min-versions", "additions": 17, "deletions": 11, "changed_files": 1, "files": [ { "filename": "doc/modules/array_api.rst", "status": "modified", "additions": 17, "deletions": 11, "changes": 28, "patch": "@@ -12,17 +12,6 @@ Scikit-learn vendors pinned copies of\n `array-api-compat `__\n and `array-api-extra `__.\n \n-Scikit-learn's support for the array API standard requires the environment variable\n-`SCIPY_ARRAY_API` to be set to `1` before importing `scipy` and `scikit-learn`:\n-\n-.. prompt:: bash $\n-\n- export SCIPY_ARRAY_API=1\n-\n-Please note that this environment variable is intended for temporary use.\n-For more details, refer to SciPy's `Array API documentation\n-`_.\n-\n Some scikit-learn estimators that primarily rely on NumPy (as opposed to using\n Cython) to implement the algorithmic logic of their `fit`, `predict` or\n `transform` methods can be configured to accept any Array API compatible input\n@@ -52,6 +41,23 @@ Note that in the examples below, we use a context manager (:func:`config_context\n to avoid having to reset it to `False` at the end of every code snippet, so as to\n not affect the rest of the documentation.\n \n+Scikit-learn's support for the array API standard requires the environment variable\n+`SCIPY_ARRAY_API` to be set to `1` before importing `scipy` and `scikit-learn`:\n+\n+.. prompt:: bash $\n+\n+ export SCIPY_ARRAY_API=1\n+\n+Please note that this environment variable is intended for temporary use.\n+For more details, refer to SciPy's `Array API documentation\n+`_.\n+\n+The array API functionality assumes that the latest versions of scikit-learn's dependencies are\n+installed. Older versions might work, but we make no promises. While array API support is marked\n+as experimental, backwards compatibility is not guaranteed. In particular, when a newer version\n+of a dependency fixes a bug we will not introduce additional code to backport the fix or\n+maintain compatibility with older versions.\n+\n Scikit-learn accepts :term:`array-like` inputs for all :mod:`metrics`\n and some estimators. When `array_api_dispatch=False`, these inputs are converted\n into NumPy arrays using :func:`numpy.asarray` (or :func:`numpy.array`)." } ], "reviews": [ { "id": 3706797345, "user": "user_501030d9d7e3", "state": "APPROVED", "body": "I like this! It is an important statement for users and the best solution while we develop.", "submitted_at": "2026-01-26T16:11:23+00:00" }, { "id": 3708767228, "user": "user_d16337ec046b", "state": "APPROVED", "body": "I'm okay with this.\n\nWe can always be more 'generous' once we are out of experimental mode.", "submitted_at": "2026-01-27T01:54:07+00:00" } ], "review_comments": [ { "id": 2729929805, "user": "user_d16337ec046b", "body": "```suggestion\nas experimental, backwards compatibility is not guaranteed. In particular, when a newer version\n```\n\nnits", "path": "doc/modules/array_api.rst", "line": null, "side": "RIGHT", "created_at": "2026-01-27T01:53:22+00:00" } ], "meta": { "languages": [ "rst" ], "touches_tests": false, "review_state_summary": { "APPROVED": 2 }, "meaningful_comment_count": 1, "has_approval": true, "has_changes_requested": false, "total_review_comments": 1 } } { "_id": "33eb0ce319849063", "_schema_version": "1.0", "_cleaned_at": "2026-02-12T07:46:51.926905+00:00", "repo": "scikit-learn/scikit-learn", "repo_url": "https://github.com/scikit-learn/scikit-learn", "license_name": "BSD 3-Clause \"New\" or \"Revised\" License", "license_spdx": "BSD-3-Clause", "pr_number": 33127, "title": "FIX: fix boundary 0-weight edge-case in `_weighted_percentile`", "body": "#### [NAME_REDACTED]/PRs\n\nFound this bug while working on #32193 (maybe the 3rd or 4th bug found while working on this test, really this is a good test :joy:)\n\nLet me know if you want me to open an issue describing the bug, but for now it's described it in the next section.\n\n#### The bug\n\n```python\nfrom sklearn.utils.stats import _weighted_percentile\n\n_weighted_percentile([1, 3], [1, 1], average=True) # returns 2 as expected\n_weighted_percentile([1, 2, 3], [1, 0, 1], average=True) # ! returns 1\n_weighted_percentile([1, 2, 3, 4], [1, 0, 1, 0], average=True) # returns 2 as expected\n\n```\n#### What does this implement/fix? Explain your changes.\n\n[Codex wrote:]\n\nI traced it to the zero‑weight “plateau” handling in `_weighted_percentile`. In your second case, the CDF has a flat section (`[1, 1, 2]`). The code correctly finds the next index where the CDF increases (the last element), but then treats `next_index == max_idx` as “out of range” and snaps back to the current index, which forces the average to use the same value twice and returns `1.0`.\n\nChanges:\n- Allow `next_index == max_idx` so the “plus one” value can be the last element.\n- Added regression test in `sklearn/utils/tests/test_stats.py` to cover the plateau case.\n\n#### AI usage disclosure\n\nI used AI assistance for:\n- [ ] Initially finding the bug\n- [x] Code generation (e.g., when writing an implementation or fixing a bug)\n- [x] Test/benchmark generation\n- [X] Documentation (including examples)\n- [x] Research and understanding", "author": "user_566c02088fba", "created_at": "2026-01-23T21:47:42+00:00", "merged_at": "2026-01-27T08:56:57+00:00", "base_branch": "main", "head_branch": "fix/weighted_median_0_end", "additions": 16, "deletions": 1, "changed_files": 3, "files": [ { "filename": "doc/whats_new/upcoming_changes/sklearn.utils/33127.fix.rst", "status": "added", "additions": 8, "deletions": 0, "changes": 8, "patch": "@@ -0,0 +1,8 @@\n+- Fixed ``_weighted_percentile`` with ``average=True`` so zero-weight samples\n+ just before the end of the array are handled correctly. This\n+ can change results when using ``sample_weight`` with\n+ :class:`preprocessing.KBinsDiscretizer` (``strategy=\"quantile\"``,\n+ ``quantile_method=\"averaged_inverted_cdf\"``) and in\n+ :func:`metrics.median_absolute_error`, :func:`metrics.d2_pinball_score`, and\n+ :func:`metrics.d2_absolute_error_score`.\n+ By :user:`[NAME_REDACTED] `." }, { "filename": "sklearn/utils/stats.py", "status": "modified", "additions": 1, "deletions": 1, "changes": 2, "patch": "@@ -192,7 +192,7 @@ def _weighted_percentile(\n )\n # Handle case where there are trailing 0 sample weight samples\n # and `percentile_indices` is already max index\n- if next_index >= max_idx:\n+ if next_index > max_idx:\n # use original `percentile_indices` again\n next_index = percentile_indices[col_idx]" }, { "filename": "sklearn/utils/tests/test_stats.py", "status": "modified", "additions": 7, "deletions": 0, "changes": 7, "patch": "@@ -130,6 +130,13 @@ def test_weighted_percentile_ignores_zero_weight(\n assert approx(value[idx]) == expected_value\n \n \n+def test_weighted_percentile_average_zero_weight_plateau():\n+ \"\"\"Check zero weights just before `max_index` handled correctly.\"\"\"\n+ score_without_zeros = _weighted_percentile([1, 3], [3, 3], average=True)\n+ score_with_zeros = _weighted_percentile([1, 2, 3], [3, 0, 3], average=True)\n+ assert approx(score_without_zeros) == score_with_zeros\n+\n+\n [USER_REDACTED].mark.parametrize(\"average\", [True, False])\n [USER_REDACTED].mark.parametrize(\"percentile_rank\", [20, 35, 50, 61])\n def test_weighted_percentile_frequency_weight_semantics(" } ], "reviews": [ { "id": 3705513707, "user": "user_5819d17296ee", "state": "APPROVED", "body": "The fix looks good.\n\nI checked that it matches the results of scipy 1.17.0:\n\n```python\nfrom scipy.stats import quantile\n\nquantile([1, 2, 3], 0.5, weights=[3, 0, 3], method=\"averaged_inverted_cdf\")\n```", "submitted_at": "2026-01-26T10:48:30+00:00" }, { "id": 3708940260, "user": "user_d16337ec046b", "state": "APPROVED", "body": "LGTM, just a nit.\n\n(Thanks for fixing btw!)", "submitted_at": "2026-01-27T04:19:23+00:00" }, { "id": 3709712081, "user": "user_566c02088fba", "state": "COMMENTED", "body": null, "submitted_at": "2026-01-27T08:15:06+00:00" }, { "id": 3709932938, "user": "user_5819d17296ee", "state": "APPROVED", "body": null, "submitted_at": "2026-01-27T08:56:49+00:00" } ], "review_comments": [ { "id": 2730096116, "user": "user_d16337ec046b", "body": "Nit, but this case is specifically when the next non-zero weight is the last index right? We were already skipping zero-weights, maybe something like:\n\n```suggestion\n- Fixed ``_weighted_percentile`` with ``average=True`` so zero-weight samples\n just before the end of the array are handled correctly. This\n```", "path": "doc/whats_new/upcoming_changes/sklearn.utils/33127.fix.rst", "line": null, "side": "RIGHT", "created_at": "2026-01-27T03:33:09+00:00" }, { "id": 2730172228, "user": "user_d16337ec046b", "body": "This seems more accurate?\n```suggestion\n \"\"\"Check zero weights just before `max_index` handled correctly.\"\"\"\n```", "path": "sklearn/utils/tests/test_stats.py", "line": null, "side": "RIGHT", "created_at": "2026-01-27T04:16:53+00:00" }, { "id": 2730777160, "user": "user_566c02088fba", "body": "Yes, definitely more accurate thx!", "path": "doc/whats_new/upcoming_changes/sklearn.utils/33127.fix.rst", "line": null, "side": "RIGHT", "created_at": "2026-01-27T08:15:06+00:00" } ], "meta": { "languages": [ "py", "rst" ], "touches_tests": true, "review_state_summary": { "APPROVED": 3, "COMMENTED": 1 }, "meaningful_comment_count": 3, "has_approval": true, "has_changes_requested": false, "total_review_comments": 3 } } { "_id": "b26c64d61d901055", "_schema_version": "1.0", "_cleaned_at": "2026-02-12T07:46:51.929244+00:00", "repo": "scikit-learn/scikit-learn", "repo_url": "https://github.com/scikit-learn/scikit-learn", "license_name": "BSD 3-Clause \"New\" or \"Revised\" License", "license_spdx": "BSD-3-Clause", "pr_number": 33126, "title": "ENH update code to check response values of an estimator", "body": "#### [NAME_REDACTED]/PRs\nFixes #33093. See also #33084.\n\n#### What does this implement/fix? Explain your changes.\n\nIt implements suggestions made here https://github.com/[USER_REDACTED]n/scikit-learn/issues/33093#issuecomment-3759684206\n\n#### AI usage disclosure\nI did **not** use AI assistance.\n\n#### Any other comments?", "author": "user_59b2ca676193", "created_at": "2026-01-23T18:25:37+00:00", "merged_at": "2026-02-05T12:33:18+00:00", "base_branch": "main", "head_branch": "error_response_values_bis", "additions": 57, "deletions": 80, "changed_files": 4, "files": [ { "filename": "doc/whats_new/upcoming_changes/sklearn.utils/33126.enhancement.rst", "status": "added", "additions": 3, "deletions": 0, "changes": 3, "patch": "@@ -0,0 +1,3 @@\n+- ``sklearn.utils._response._get_response_values`` now provides a clearer error message\n+ when estimator does not implement the given ``response_method``.\n+ By :user:`Quentin Barthélemy `." }, { "filename": "sklearn/inspection/_plot/tests/test_boundary_decision_display.py", "status": "modified", "additions": 0, "deletions": 14, "changes": 14, "patch": "@@ -383,20 +383,6 @@ def test_multioutput_regressor_error(pyplot):\n DecisionBoundaryDisplay.from_estimator(tree, X, response_method=\"predict\")\n \n \n-[USER_REDACTED].mark.parametrize(\n- \"response_method\",\n- [\"predict_proba\", \"decision_function\", [\"predict_proba\", \"predict\"]],\n-)\n-def test_regressor_unsupported_response(pyplot, response_method):\n- \"\"\"Check that we can display the decision boundary for a regressor.\"\"\"\n- X, y = load_diabetes(return_X_y=True)\n- X = X[:, :2]\n- tree = DecisionTreeRegressor().fit(X, y)\n- err_msg = \"should either be a classifier to be used with response_method\"\n- with pytest.raises(ValueError, match=err_msg):\n- DecisionBoundaryDisplay.from_estimator(tree, X, response_method=response_method)\n-\n-\n [USER_REDACTED].mark.filterwarnings(\n # We expect to raise the following warning because the classifier is fit on a\n # NumPy array" }, { "filename": "sklearn/utils/_response.py", "status": "modified", "additions": 10, "deletions": 23, "changes": 33, "patch": "@@ -120,7 +120,8 @@ def _get_response_values(\n pos_label=None,\n return_response_method_used=False,\n ):\n- \"\"\"Compute the response values of a classifier, an outlier detector, or a regressor.\n+ \"\"\"Compute the response values of a classifier, an outlier detector, a regressor\n+ or a clusterer.\n \n The response values are predictions such that it follows the following shape:\n \n@@ -129,8 +130,8 @@ def _get_response_values(\n - with response_method=\"predict\", it is a 1d array of shape `(n_samples,)`;\n - otherwise, it is a 2d array of shape `(n_samples, n_classes)`;\n - for multilabel classification, it is a 2d array of shape `(n_samples, n_outputs)`;\n- - for outlier detection, it is a 1d array of shape `(n_samples,)`;\n- - for regression, it is a 1d array of shape `(n_samples,)`.\n+ - for outlier detection, a regressor or a clusterer, it is a 1d array of shape\n+ `(n_samples,)`.\n \n If `estimator` is a binary classifier, also return the label for the\n effective positive class.\n@@ -142,9 +143,9 @@ def _get_response_values(\n Parameters\n ----------\n estimator : estimator instance\n- Fitted classifier, outlier detector, or regressor or a\n+ Fitted classifier, outlier detector, regressor, clusterer or a\n fitted :class:`~sklearn.pipeline.Pipeline` in which the last estimator is a\n- classifier, an outlier detector, or a regressor.\n+ classifier, an outlier detector, a regressor or a clusterer.\n \n X : {array-like, sparse matrix} of shape (n_samples, n_features)\n Input values.\n@@ -180,8 +181,8 @@ def _get_response_values(\n \n pos_label : int, float, bool, str or None\n The class considered as the positive class when computing\n- the metrics. Returns `None` if `estimator` is a regressor or an outlier\n- detector.\n+ the metrics. Returns `None` if `estimator` is a regressor, an outlier\n+ detector or a clusterer.\n \n response_method_used : str\n The response method used to compute the response values. Only returned\n@@ -194,13 +195,10 @@ def _get_response_values(\n ValueError\n If `pos_label` is not a valid label.\n If the shape of `y_pred` is not consistent for binary classifier.\n- If the response method can be applied to a classifier only and\n- `estimator` is a regressor.\n \"\"\"\n- from sklearn.base import is_classifier, is_outlier_detector\n+ prediction_method = _check_response_method(estimator, response_method)\n \n if is_classifier(estimator):\n- prediction_method = _check_response_method(estimator, response_method)\n classes = estimator.classes_\n target_type = type_of_target(classes)\n \n@@ -229,18 +227,7 @@ def _get_response_values(\n classes=classes,\n pos_label=pos_label,\n )\n- elif is_outlier_detector(estimator):\n- prediction_method = _check_response_method(estimator, response_method)\n- y_pred, pos_label = prediction_method(X), None\n- else: # estimator is a regressor\n- if response_method != \"predict\":\n- raise ValueError(\n- f\"{estimator.__class__.__name__} should either be a classifier to be \"\n- f\"used with response_method={response_method} or the response_method \"\n- \"should be 'predict'. Got a regressor with response_method=\"\n- f\"{response_method} instead.\"\n- )\n- prediction_method = estimator.predict\n+ else:\n y_pred, pos_label = prediction_method(X), None\n \n if return_response_method_used:" }, { "filename": "sklearn/utils/tests/test_response.py", "status": "modified", "additions": 44, "deletions": 43, "changes": 87, "patch": "@@ -4,21 +4,17 @@\n import pytest\n \n from sklearn.base import clone\n+from sklearn.cluster import DBSCAN, KMeans\n from sklearn.datasets import (\n load_iris,\n make_classification,\n make_multilabel_classification,\n- make_regression,\n )\n from sklearn.ensemble import IsolationForest\n-from sklearn.linear_model import (\n- LinearRegression,\n- LogisticRegression,\n-)\n+from sklearn.linear_model import LinearRegression, LogisticRegression\n from sklearn.multioutput import ClassifierChain\n from sklearn.preprocessing import scale\n from sklearn.tree import DecisionTreeClassifier, DecisionTreeRegressor\n-from sklearn.utils._mocking import _MockEstimatorOnOffPrediction\n from sklearn.utils._response import _get_response_values, _get_response_values_binary\n from sklearn.utils._testing import assert_allclose, assert_array_equal\n \n@@ -29,56 +25,59 @@\n \n \n [USER_REDACTED].mark.parametrize(\n- \"response_method\", [\"decision_function\", \"predict_proba\", \"predict_log_proba\"]\n+ \"estimator, response_method\",\n+ [\n+ (DecisionTreeRegressor(), \"predict_proba\"),\n+ (DecisionTreeRegressor(), [\"predict_proba\", \"decision_function\"]),\n+ (KMeans(n_clusters=2, n_init=1), \"predict_proba\"),\n+ (KMeans(n_clusters=2, n_init=1), [\"predict_proba\", \"decision_function\"]),\n+ (DBSCAN(), \"predict\"),\n+ (IsolationForest(random_state=0), \"predict_proba\"),\n+ (IsolationForest(random_state=0), [\"predict_proba\", \"score\"]),\n+ ],\n )\n-def test_get_response_values_regressor_error(response_method):\n- \"\"\"Check the error message with regressor an not supported response\n- method.\"\"\"\n- my_estimator = _MockEstimatorOnOffPrediction(response_methods=[response_method])\n- X = \"mocking_data\", \"mocking_target\"\n- err_msg = f\"{my_estimator.__class__.__name__} should either be a classifier\"\n- with pytest.raises(ValueError, match=err_msg):\n- _get_response_values(my_estimator, X, response_method=response_method)\n-\n-\n-[USER_REDACTED].mark.parametrize(\"return_response_method_used\", [True, False])\n-def test_get_response_values_regressor(return_response_method_used):\n- \"\"\"Check the behaviour of `_get_response_values` with regressor.\"\"\"\n- X, y = make_regression(n_samples=10, random_state=0)\n- regressor = LinearRegression().fit(X, y)\n- results = _get_response_values(\n- regressor,\n- X,\n- response_method=\"predict\",\n- return_response_method_used=return_response_method_used,\n- )\n- assert_array_equal(results[0], regressor.predict(X))\n- assert results[1] is None\n- if return_response_method_used:\n- assert results[2] == \"predict\"\n+def test_estimator_unsupported_response(pyplot, estimator, response_method):\n+ \"\"\"Check the error message with not supported response method.\"\"\"\n+ X, y = np.random.RandomState(0).randn(10, 2), np.array([0, 1] * 5)\n+ estimator.fit(X, y)\n+ err_msg = \"has none of the following attributes:\"\n+ with pytest.raises(AttributeError, match=err_msg):\n+ _get_response_values(\n+ estimator,\n+ X,\n+ response_method=response_method,\n+ )\n \n \n [USER_REDACTED].mark.parametrize(\n- \"response_method\",\n- [\"predict\", \"decision_function\", [\"decision_function\", \"predict\"]],\n+ \"estimator, response_method\",\n+ [\n+ (LinearRegression(), \"predict\"),\n+ (KMeans(n_clusters=2, n_init=1), \"predict\"),\n+ (KMeans(n_clusters=2, n_init=1), \"score\"),\n+ (KMeans(n_clusters=2, n_init=1), [\"predict\", \"score\"]),\n+ (IsolationForest(random_state=0), \"predict\"),\n+ (IsolationForest(random_state=0), \"decision_function\"),\n+ (IsolationForest(random_state=0), [\"decision_function\", \"predict\"]),\n+ ],\n )\n [USER_REDACTED].mark.parametrize(\"return_response_method_used\", [True, False])\n-def test_get_response_values_outlier_detection(\n- response_method, return_response_method_used\n+def test_estimator_get_response_values(\n+ estimator, response_method, return_response_method_used\n ):\n- \"\"\"Check the behaviour of `_get_response_values` with outlier detector.\"\"\"\n- X, y = make_classification(n_samples=50, random_state=0)\n- outlier_detector = IsolationForest(random_state=0).fit(X, y)\n+ \"\"\"Check the behaviour of `_get_response_values`.\"\"\"\n+ X, y = np.random.RandomState(0).randn(10, 2), np.array([0, 1] * 5)\n+ estimator.fit(X, y)\n results = _get_response_values(\n- outlier_detector,\n+ estimator,\n X,\n response_method=response_method,\n return_response_method_used=return_response_method_used,\n )\n chosen_response_method = (\n response_method[0] if isinstance(response_method, list) else response_method\n )\n- prediction_method = getattr(outlier_detector, chosen_response_method)\n+ prediction_method = getattr(estimator, chosen_response_method)\n assert_array_equal(results[0], prediction_method(X))\n assert results[1] is None\n if return_response_method_used:\n@@ -417,6 +416,8 @@ def test_response_values_type_of_target_on_classes_no_warning():\n (IsolationForest(), \"predict\", \"multiclass\", (10,)),\n (DecisionTreeRegressor(), \"predict\", \"binary\", (10,)),\n (DecisionTreeRegressor(), \"predict\", \"multiclass\", (10,)),\n+ (KMeans(n_clusters=2, n_init=1), \"predict\", \"binary\", (10,)),\n+ (KMeans(n_clusters=2, n_init=1), \"predict\", \"multiclass\", (10,)),\n ],\n )\n def test_response_values_output_shape_(\n@@ -430,8 +431,8 @@ def test_response_values_output_shape_(\n - with response_method=\"predict\", it is a 1d array of shape `(n_samples,)`;\n - otherwise, it is a 2d array of shape `(n_samples, n_classes)`;\n - for multilabel classification, it is a 2d array of shape `(n_samples, n_outputs)`;\n- - for outlier detection, it is a 1d array of shape `(n_samples,)`;\n- - for regression, it is a 1d array of shape `(n_samples,)`.\n+ - for outlier detection, regression and clustering,\n+ it is a 1d array of shape `(n_samples,)`.\n \"\"\"\n X = np.random.RandomState(0).randn(10, 2)\n if target_type == \"binary\":" } ], "reviews": [ { "id": 3705578189, "user": "user_34a090906ca4", "state": "COMMENTED", "body": "Thank you for the PR [USER_REDACTED]!\n\nA few remarks:\n1. To avoid confusion, please change the title to start with \"ENH\" or \"FIX\" instead of \"DOC\" (as this PR does not change the documentation).\n1. Please add a changelog entry [like this](https://github.com/[USER_REDACTED]n/scikit-learn/blob/main/doc/whats_new/upcoming_changes/README.md).\n1. Your tests are currently failing. In general, we need two new tests here:\n * one that checks that no error is thrown for all types of estimators with their supported `response_methods`, and\n * one that checks that the expected error is thrown for unsupported `response_methods`.\nNote that `response_method` can be a string or a list of strings, both cases should be part of the tests.\nAll existing tests should not be changed (or only adapted according to the new error message), to make sure nothing else is affected by [NAME_REDACTED] know if you need more help with designing the tests.", "submitted_at": "2026-01-26T11:44:19+00:00" }, { "id": 3705918083, "user": "user_34a090906ca4", "state": "COMMENTED", "body": null, "submitted_at": "2026-01-26T12:54:07+00:00" }, { "id": 3710582177, "user": "user_34a090906ca4", "state": "COMMENTED", "body": "Thank you for addressing the comments so fast! Here is another round of feedback:", "submitted_at": "2026-01-27T12:24:25+00:00" }, { "id": 3721520334, "user": "user_34a090906ca4", "state": "COMMENTED", "body": "A few more small things:", "submitted_at": "2026-01-29T09:59:24+00:00" }, { "id": 3722416874, "user": "user_34a090906ca4", "state": "APPROVED", "body": "LGTM now, thank you!", "submitted_at": "2026-01-29T12:33:43+00:00" }, { "id": 3735886589, "user": "user_04b4a5f4e2a8", "state": "APPROVED", "body": "Thank you for the PR [USER_REDACTED] ! LGTM", "submitted_at": "2026-02-01T15:17:35+00:00" }, { "id": 3756834167, "user": "user_49a647962c6b", "state": "APPROVED", "body": null, "submitted_at": "2026-02-05T12:33:06+00:00" } ], "review_comments": [ { "id": 2727203870, "user": "user_34a090906ca4", "body": "```suggestion\n```\nThese lines should be removed, as this case is no longer handled by [NAME_REDACTED] `AttributeError` will be raised instead by `_check_response_method` in `sklearn/utils/validation.py`", "path": "sklearn/utils/_response.py", "line": null, "side": "RIGHT", "created_at": "2026-01-26T11:09:59+00:00" }, { "id": 2727502597, "user": "user_34a090906ca4", "body": "Add \"clusterer\" here and below (in response shape and in parameter decription for `estimator`).", "path": "sklearn/utils/_response.py", "line": null, "side": "RIGHT", "created_at": "2026-01-26T12:54:07+00:00" }, { "id": 2731507345, "user": "user_34a090906ca4", "body": "Small typo:\n```suggestion\n detector or a clusterer\n```", "path": "sklearn/utils/_response.py", "line": null, "side": "RIGHT", "created_at": "2026-01-27T11:15:18+00:00" }, { "id": 2731529850, "user": "user_34a090906ca4", "body": "```suggestion\n when estimator does not implement the given ``response_method``.\n```", "path": "doc/whats_new/upcoming_changes/sklearn.utils/33126.enhancement.rst", "line": null, "side": "RIGHT", "created_at": "2026-01-27T11:21:41+00:00" }, { "id": 2731624372, "user": "user_34a090906ca4", "body": "Could you please also add corresponding test cases (for binary and multiclass) for a clusterer here:\nhttps://github.com/[USER_REDACTED]n/scikit-learn/blob/3e51c6b0a5cbeaabae1d4c1fb8cd171c20f2635b/sklearn/utils/tests/test_response.py#L422", "path": "sklearn/utils/_response.py", "line": 133, "side": "RIGHT", "created_at": "2026-01-27T11:47:23+00:00" }, { "id": 2731644605, "user": "user_34a090906ca4", "body": "Could you please extend this test (and rename it to `test_estimator_unsupported_response`) by adding a parametrization with regressor, outlier detector and clusterer?", "path": "sklearn/inspection/_plot/tests/test_boundary_decision_display.py", "line": null, "side": "RIGHT", "created_at": "2026-01-27T11:52:19+00:00" }, { "id": 2731684885, "user": "user_34a090906ca4", "body": "Could you please extend the list with `[\"not-a-valid-method\", \"predict\"]` (which should also result in `predict` being selected)? The logic below would also have to be adapted slightly, or you can change the parametrization into a tuple to explicitly specify the expected method as well.", "path": "sklearn/utils/tests/test_response.py", "line": null, "side": "RIGHT", "created_at": "2026-01-27T12:02:21+00:00" }, { "id": 2731702871, "user": "user_34a090906ca4", "body": "Same comment as [below](https://github.com/[USER_REDACTED]n/scikit-learn/pull/33126/changes#r2731684885)", "path": "sklearn/utils/tests/test_response.py", "line": null, "side": "RIGHT", "created_at": "2026-01-27T12:06:59+00:00" }, { "id": 2731711593, "user": "user_34a090906ca4", "body": "I would also be in favor of moving this test to sklearn/utils/tests/test_response.py, to have everything related to testing response values in the same file.", "path": "sklearn/inspection/_plot/tests/test_boundary_decision_display.py", "line": null, "side": "RIGHT", "created_at": "2026-01-27T12:09:30+00:00" }, { "id": 2740664059, "user": "user_34a090906ca4", "body": "Small nit: this can be condensed into one bullet point as in _response.py below", "path": "sklearn/utils/tests/test_response.py", "line": null, "side": "RIGHT", "created_at": "2026-01-29T09:14:59+00:00" }, { "id": 2740720221, "user": "user_34a090906ca4", "body": "Wouldn't they all work with n_samples=50? Then `Xy` could be taken out of the parametrization, because this does not directly impact the test.", "path": "sklearn/utils/tests/test_response.py", "line": null, "side": "RIGHT", "created_at": "2026-01-29T09:29:45+00:00" }, { "id": 2740724143, "user": "user_34a090906ca4", "body": "Can you please also add a test case for `DBSCAN()` with \"predict\"? (encountered here https://github.com/[USER_REDACTED]n/scikit-learn/issues/33119#issuecomment-3811432790)", "path": "sklearn/utils/tests/test_response.py", "line": null, "side": "RIGHT", "created_at": "2026-01-29T09:30:44+00:00" }, { "id": 2740758947, "user": "user_34a090906ca4", "body": "Note for reviewers: This is now tested in sklearn/utils/tests/test_response.py in \n`test_estimator_unsupported_response`", "path": "sklearn/inspection/_plot/tests/test_boundary_decision_display.py", "line": 390, "side": "LEFT", "created_at": "2026-01-29T09:39:08+00:00" }, { "id": 2740794452, "user": "user_34a090906ca4", "body": "There is a lot of duplicate code in `test_get_response_values_regressor/outlier_detection/clusterer`. Can you try to parametrize the estimators here as well\n(similar to `test_response_values_output_shape_`)?", "path": "sklearn/utils/tests/test_response.py", "line": null, "side": "RIGHT", "created_at": "2026-01-29T09:47:34+00:00" }, { "id": 2740821010, "user": "user_34a090906ca4", "body": "What I meant was `[\"not-a-valid-method\", \"predict\"]`, i.e., a case where actually only the second item is supported. But since this is also already tested here:\nhttps://github.com/[USER_REDACTED]n/scikit-learn/blob/b0bf5d7280e8768e3add0d9c83ae950436a1b878/sklearn/utils/tests/test_validation.py#L2100\nI think it is ok to remove this again here. Sorry, I didn't see that before.", "path": "sklearn/utils/tests/test_response.py", "line": null, "side": "RIGHT", "created_at": "2026-01-29T09:53:04+00:00" } ], "meta": { "languages": [ "py", "rst" ], "touches_tests": true, "review_state_summary": { "COMMENTED": 4, "APPROVED": 3 }, "meaningful_comment_count": 15, "has_approval": true, "has_changes_requested": false, "total_review_comments": 15 } } { "_id": "7fefa96eeee47a2a", "_schema_version": "1.0", "_cleaned_at": "2026-02-12T07:46:51.929244+00:00", "repo": "scikit-learn/scikit-learn", "repo_url": "https://github.com/scikit-learn/scikit-learn", "license_name": "BSD 3-Clause \"New\" or \"Revised\" License", "license_spdx": "BSD-3-Clause", "pr_number": 33123, "title": "CI Migrate Linux_Nightly build to GHA", "body": "\n\n#### [NAME_REDACTED]/PRs\n\nTowards #32434\n\n", "author": "user_afd8fdca88a2", "created_at": "2026-01-22T14:51:44+00:00", "merged_at": "2026-01-28T14:19:03+00:00", "base_branch": "main", "head_branch": "migrate_CI_linux_nightly", "additions": 13, "deletions": 23, "changed_files": 2, "files": [ { "filename": ".github/workflows/unit-tests.yml", "status": "modified", "additions": 13, "deletions": 1, "changes": 14, "patch": "@@ -289,8 +289,20 @@ jobs:\n if: contains(needs.retrieve-commit-message.outputs.message, '[free-threaded]') || github.event_name == 'schedule' || github.event_name == 'workflow_dispatch'\n env:\n DISTRIB: conda-free-threaded\n- LOCK_FILE: ./build_tools/azure/pylatest_free_threaded_linux-64_conda.lock\n+ LOCK_FILE: build_tools/azure/pylatest_free_threaded_linux-64_conda.lock\n COVERAGE: false\n # Disable pytest-xdist to use multiple cores for stress-testing with pytest-run-parallel\n PYTEST_XDIST_VERSION: none\n steps: *unit-tests-steps\n+\n+ scipy-dev:\n+ name: Linux x86-64 pylatest_pip_scipy_dev\n+ runs-on: ubuntu-22.04\n+ needs: [lint, retrieve-commit-message, retrieve-selected-tests]\n+ if: contains(needs.retrieve-commit-message.outputs.message, '[scipy-dev]') || github.event_name == 'schedule' || github.event_name == 'workflow_dispatch'\n+ env:\n+ DISTRIB: conda-pip-scipy-dev\n+ LOCK_FILE: build_tools/azure/pylatest_pip_scipy_dev_linux-64_conda.lock\n+ SKLEARN_WARNINGS_AS_ERRORS: 1\n+ CHECK_PYTEST_SOFT_DEPENDENCY: true\n+ steps: *unit-tests-steps" }, { "filename": "azure-pipelines.yml", "status": "modified", "additions": 0, "deletions": 22, "changes": 22, "patch": "@@ -45,28 +45,6 @@ jobs:\n python build_tools/check-meson-openmp-dependencies.py\n displayName: [NAME_REDACTED] checks\n \n-\n-- template: build_tools/azure/posix.yml\n- parameters:\n- name: Linux_Nightly\n- vmImage: ubuntu-22.04\n- dependsOn: [git_commit, linting]\n- condition: |\n- and(\n- succeeded(),\n- not(contains(dependencies['git_commit']['outputs']['commit.message'], '[ci skip]')),\n- or(eq(variables['Build.Reason'], 'Schedule'),\n- contains(dependencies['git_commit']['outputs']['commit.message'], '[scipy-dev]'\n- )\n- )\n- )\n- matrix:\n- pylatest_pip_scipy_dev:\n- DISTRIB: 'conda-pip-scipy-dev'\n- LOCK_FILE: './build_tools/azure/pylatest_pip_scipy_dev_linux-64_conda.lock'\n- SKLEARN_WARNINGS_AS_ERRORS: '1'\n- CHECK_PYTEST_SOFT_DEPENDENCY: 'true'\n-\n # Will run all the time regardless of linting outcome.\n - template: build_tools/azure/posix.yml\n parameters:" } ], "reviews": [ { "id": 3698366976, "user": "user_5819d17296ee", "state": "COMMENTED", "body": "I think we should not automatically run this build without the condition on `[scipy-dev]` appearing in the commit message:\n\nBy design, we cannot pin dev dependencies and therefore this build is more likely to fail randomly. We don't want this happening in unrelated PRs.", "submitted_at": "2026-01-23T16:20:04+00:00" }, { "id": 3716641273, "user": "user_fca2535bcd49", "state": "APPROVED", "body": "LGTM, thanks!\n\nI pushed an unrelated minor tweak + `[scipy-dev]` commit to make 100% sure this works as expected (edit: it does run) and enabled auto-merge.\n\nAnd I agree yaml anchor seems like the simplest solution for now.", "submitted_at": "2026-01-28T13:13:18+00:00" }, { "id": 3716854688, "user": "user_fca2535bcd49", "state": "COMMENTED", "body": null, "submitted_at": "2026-01-28T13:57:48+00:00" } ], "review_comments": [ { "id": 2721893062, "user": "user_5819d17296ee", "body": "For the sake of naming consistency:\n\n```suggestion\n - name: Linux pylatest_pip_scipy_dev\n```", "path": ".github/workflows/unit-tests.yml", "line": null, "side": "RIGHT", "created_at": "2026-01-23T16:17:21+00:00" }, { "id": 2736766110, "user": "user_fca2535bcd49", "body": "```suggestion\n runs-on: ubuntu-22.04\n```", "path": ".github/workflows/unit-tests.yml", "line": null, "side": "RIGHT", "created_at": "2026-01-28T13:57:48+00:00" } ], "meta": { "languages": [ "yml" ], "touches_tests": false, "review_state_summary": { "COMMENTED": 2, "APPROVED": 1 }, "meaningful_comment_count": 2, "has_approval": true, "has_changes_requested": false, "total_review_comments": 2 } } { "_id": "10803c2d62d8e165", "_schema_version": "1.0", "_cleaned_at": "2026-02-12T07:46:51.929244+00:00", "repo": "scikit-learn/scikit-learn", "repo_url": "https://github.com/scikit-learn/scikit-learn", "license_name": "BSD 3-Clause \"New\" or \"Revised\" License", "license_spdx": "BSD-3-Clause", "pr_number": 33118, "title": "Re-enable compressed cache for fetch_kddcup99", "body": "Fixes #33117\n## Re-enable compressed cache for `fetch_kddcup99\n### [NAME_REDACTED] KDDCup99 cache is currently forced to be written uncompressed due to a legacy\ndecompression workaround. This significantly inflates disk usage for a very large\ndataset. Re-enabling compression reduces storage requirements and disk I/O without\nchanging the public API or user-facing behavior.\n\n### What changed\n- Write cached `samples` and `targets` using `joblib.dump(..., compress=3)` in\n `_kddcup99.py`.\n- Add a regression test in `test_kddcup99.py` that builds a compressed cache and\n verifies that `fetch_kddcup99` can load it correctly without network access.\n\n### Review focus\n- Confirm that the chosen compression level (`compress=3`) is a reasonable\n trade-off between cache size reduction and CPU overhead.\n- Validate that the new test reliably covers loading from a compressed cache and\n does not require network access.\n\n### AI usage disclosure\nThis pull request includes code checks and PR enhancement using AI.", "author": "user_ffc437e0ab26", "created_at": "2026-01-20T13:51:18+00:00", "merged_at": "2026-01-26T13:27:28+00:00", "base_branch": "main", "head_branch": "fix-20newgroups-403-error", "additions": 5, "deletions": 6, "changed_files": 2, "files": [ { "filename": "doc/whats_new/upcoming_changes/sklearn.datasets/33118.efficiency.rst", "status": "added", "additions": 3, "deletions": 0, "changes": 3, "patch": "@@ -0,0 +1,3 @@\n+- Re-enabled compressed caching for :func:`datasets.fetch_kddcup99`, reducing\n+ on-disk cache size without changing the public API.\n+ By :user:`[NAME_REDACTED] `." }, { "filename": "sklearn/datasets/_kddcup99.py", "status": "modified", "additions": 2, "deletions": 6, "changes": 8, "patch": "@@ -402,12 +402,8 @@ def _fetch_brute_kddcup99(\n \n X = Xy[:, :-1]\n y = Xy[:, -1]\n- # XXX bug when compress!=0:\n- # (error: 'Incorrect data length while decompressing[...] the file\n- # could be corrupted.')\n-\n- joblib.dump(X, samples_path, compress=0)\n- joblib.dump(y, targets_path, compress=0)\n+ joblib.dump(X, samples_path, compress=3)\n+ joblib.dump(y, targets_path, compress=3)\n else:\n raise OSError(\"Data not found and `download_if_missing` is False\")" } ], "reviews": [ { "id": 3686626885, "user": "user_5819d17296ee", "state": "COMMENTED", "body": "According to `sklearn/_min_dependencies.py`, the oldest supported version of joblib is 1.3.0 (and the current version is 1.5.3).\n\nI installed this version locally, deleted `~/scikit_learn_data/kddcup99_10-py3` and then I tried to run:\n\n```\nSKLEARN_SKIP_NETWORK_TESTS=0 pytest -vl sklearn/datasets/tests/test_kddcup99.py\n```\n\nAll tests pass.\n\nSo this confirms that we don't observe the old joblib compression bug anymore.\n\nThe resulting local folder is much smaller, as expected:\n\n```\n$ du -hs ~/scikit_learn_data/kddcup99_10-py3\n 18M /Users/ogrisel/scikit_learn_data/kddcup99_10-py3\n```\n\nIt used to be on the order of 100 MB.\n\nCould you please add a changelog entry for this fix? See: https://github.com/[USER_REDACTED]n/scikit-learn/blob/main/doc/whats_new/upcoming_changes/README.md", "submitted_at": "2026-01-21T13:45:29+00:00" }, { "id": 3687896636, "user": "user_ffc437e0ab26", "state": "COMMENTED", "body": null, "submitted_at": "2026-01-21T15:34:40+00:00" }, { "id": 3687900545, "user": "user_ffc437e0ab26", "state": "COMMENTED", "body": null, "submitted_at": "2026-01-21T15:35:27+00:00" }, { "id": 3697454470, "user": "user_5819d17296ee", "state": "APPROVED", "body": "Besides the following, LGTM.", "submitted_at": "2026-01-23T13:24:14+00:00" }, { "id": 3698350567, "user": "user_5819d17296ee", "state": "APPROVED", "body": null, "submitted_at": "2026-01-23T16:13:33+00:00" } ], "review_comments": [ { "id": 2712082968, "user": "user_5819d17296ee", "body": "Why change the source URL? We use the `figshare.com` mirror on purpose because personal pages at university websites tend to disappear over time.\n\nAlso, I'd rather stick to https if we can.", "path": "sklearn/datasets/_twenty_newsgroups.py", "line": null, "side": "RIGHT", "created_at": "2026-01-21T11:08:02+00:00" }, { "id": 2712097742, "user": "user_5819d17296ee", "body": "I don't think we need this new indirect test. The existing tests should be enough.", "path": "sklearn/datasets/tests/test_kddcup99.py", "line": null, "side": "RIGHT", "created_at": "2026-01-21T11:12:34+00:00" }, { "id": 2713122071, "user": "user_ffc437e0ab26", "body": "Ok I wil remove test", "path": "sklearn/datasets/tests/test_kddcup99.py", "line": null, "side": "RIGHT", "created_at": "2026-01-21T15:34:40+00:00" }, { "id": 2713125863, "user": "user_ffc437e0ab26", "body": "> Why change the source URL? We use the `figshare.com` mirror on purpose because personal pages at university websites tend to disappear over time.\n> \n> Also, I'd rather stick to https if we can.\n\nOhh sorry \nit was of another issue\nI accidently added this \nI will remove it asap and push", "path": "sklearn/datasets/_twenty_newsgroups.py", "line": null, "side": "RIGHT", "created_at": "2026-01-21T15:35:27+00:00" }, { "id": 2721176613, "user": "user_5819d17296ee", "body": "Please credit yourself using the formatting described in the instructions:\n\nSee: https://github.com/[USER_REDACTED]n/scikit-learn/blob/main/doc/whats_new/upcoming_changes/README.md", "path": "doc/whats_new/upcoming_changes/sklearn.datasets/33118.fix.rst", "line": null, "side": "RIGHT", "created_at": "2026-01-23T13:22:21+00:00" }, { "id": 2721182352, "user": "user_5819d17296ee", "body": "You could also rename this filename to `33118.efficiency.rst` since this is a disk space optimization.", "path": "doc/whats_new/upcoming_changes/sklearn.datasets/33118.fix.rst", "line": null, "side": "RIGHT", "created_at": "2026-01-23T13:24:05+00:00" } ], "meta": { "languages": [ "py", "rst" ], "touches_tests": false, "review_state_summary": { "COMMENTED": 3, "APPROVED": 2 }, "meaningful_comment_count": 6, "has_approval": true, "has_changes_requested": false, "total_review_comments": 6 } } { "_id": "f2aa6e4ea15ec4ed", "_schema_version": "1.0", "_cleaned_at": "2026-02-12T07:46:51.929244+00:00", "repo": "scikit-learn/scikit-learn", "repo_url": "https://github.com/scikit-learn/scikit-learn", "license_name": "BSD 3-Clause \"New\" or \"Revised\" License", "license_spdx": "BSD-3-Clause", "pr_number": 33116, "title": "CI Port `free-threaded` job from Azure to GHA", "body": "Part of #32434\n\n#### AI usage disclosure\n\nI used AI assistance for:\n- [x] Code generation (e.g., when writing an implementation or fixing a bug)\n- [ ] Test/benchmark generation\n- [ ] Documentation (including examples)\n- [ ] Research and understanding", "author": "user_c91ee6762b06", "created_at": "2026-01-20T10:36:00+00:00", "merged_at": "2026-01-27T13:55:01+00:00", "base_branch": "main", "head_branch": "push-uxqwnyvlzuxw", "additions": 17, "deletions": 24, "changed_files": 3, "files": [ { "filename": ".github/workflows/unit-tests.yml", "status": "modified", "additions": 14, "deletions": 1, "changes": 15, "patch": "@@ -212,7 +212,7 @@ jobs:\n \n env: ${{ matrix }}\n \n- steps:\n+ steps: &unit-tests-steps\n - name: Checkout\n uses: actions/checkout@v6\n \n@@ -281,3 +281,16 @@ jobs:\n --junit-file $TEST_DIR/$JUNITXML \\\n --auto-close false \\\n --job-name \"${{ matrix.name }}\"\n+\n+ free-threaded:\n+ name: Linux x86-64 pylatest_free_threaded\n+ runs-on: ubuntu-latest\n+ needs: [lint, retrieve-commit-message, retrieve-selected-tests]\n+ if: ${{ contains(needs.retrieve-commit-message.outputs.message, '[free-threaded]') }}\n+ env:\n+ DISTRIB: conda-free-threaded\n+ LOCK_FILE: ./build_tools/azure/pylatest_free_threaded_linux-64_conda.lock\n+ COVERAGE: false\n+ # Disable pytest-xdist to use multiple cores for stress-testing with pytest-run-parallel\n+ PYTEST_XDIST_VERSION: none\n+ steps: *unit-tests-steps" }, { "filename": "azure-pipelines.yml", "status": "modified", "additions": 0, "deletions": 23, "changes": 23, "patch": "@@ -67,29 +67,6 @@ jobs:\n SKLEARN_WARNINGS_AS_ERRORS: '1'\n CHECK_PYTEST_SOFT_DEPENDENCY: 'true'\n \n-- template: build_tools/azure/posix.yml\n- # CPython free-threaded build\n- parameters:\n- name: Linux_free_threaded\n- vmImage: ubuntu-22.04\n- dependsOn: [git_commit, linting]\n- condition: |\n- and(\n- succeeded(),\n- not(contains(dependencies['git_commit']['outputs']['commit.message'], '[ci skip]')),\n- or(eq(variables['Build.Reason'], 'Schedule'),\n- contains(dependencies['git_commit']['outputs']['commit.message'], '[free-threaded]'\n- )\n- )\n- )\n- matrix:\n- pylatest_free_threaded:\n- DISTRIB: 'conda-free-threaded'\n- LOCK_FILE: './build_tools/azure/pylatest_free_threaded_linux-64_conda.lock'\n- COVERAGE: 'false'\n- # Disable pytest-xdist to use multiple cores for stress-testing with pytest-run-parallel\n- PYTEST_XDIST_VERSION: 'none'\n-\n # Will run all the time regardless of linting outcome.\n - template: build_tools/azure/posix.yml\n parameters:" }, { "filename": "sklearn/ensemble/tests/test_bagging.py", "status": "modified", "additions": 3, "deletions": 0, "changes": 3, "patch": "@@ -463,6 +463,9 @@ def test_error():\n assert not hasattr(BaggingClassifier(base).fit(X, y), \"decision_function\")\n \n \n+# TODO: remove mark once loky bug is fixed:\n+# https://github.com/joblib/loky/issues/458\n+[USER_REDACTED].mark.thread_unsafe\n def test_parallel_classification():\n # Check parallel classification.\n X_train, X_test, y_train, y_test = train_test_split(" } ], "reviews": [ { "id": 3698415541, "user": "user_5819d17296ee", "state": "COMMENTED", "body": null, "submitted_at": "2026-01-23T16:26:21+00:00" }, { "id": 3698428673, "user": "user_5819d17296ee", "state": "COMMENTED", "body": null, "submitted_at": "2026-01-23T16:28:33+00:00" }, { "id": 3698676510, "user": "user_c91ee6762b06", "state": "COMMENTED", "body": null, "submitted_at": "2026-01-23T17:15:52+00:00" }, { "id": 3711339154, "user": "user_fca2535bcd49", "state": "APPROVED", "body": "LGTM thanks!", "submitted_at": "2026-01-27T13:53:59+00:00" } ], "review_comments": [ { "id": 2721931503, "user": "user_5819d17296ee", "body": "[USER_REDACTED] I don't understand what you are trying to achieve with this? Is the purpose to check what happens if the condition is never met? Is this causing the jobs to be stuck in the \"pending\" state?", "path": ".github/workflows/unit-tests.yml", "line": null, "side": "RIGHT", "created_at": "2026-01-23T16:26:21+00:00" }, { "id": 2721941268, "user": "user_5819d17296ee", "body": "So this is causing:\n\n```\nInvalid workflow file: .github/workflows/unit-tests.yml#L1\n(Line: 138, Col: 9): Unrecognized named-value: 'matrix'. Located at position 53 within expression: github.repository == 'scikit-learn/scikit-learn' && matrix.RUN_CONDITION == 'bla'\n```\n\nhttps://github.com/[USER_REDACTED]n/scikit-learn/actions/runs/21293108036", "path": ".github/workflows/unit-tests.yml", "line": null, "side": "RIGHT", "created_at": "2026-01-23T16:28:33+00:00" }, { "id": 2722139302, "user": "user_c91ee6762b06", "body": "This was a test commit to check what part of the condition triggered the syntax error. Indeed `matrix` cannot be used in the context of an `if`, hence my comment above saying we might need some extra setup.", "path": ".github/workflows/unit-tests.yml", "line": null, "side": "RIGHT", "created_at": "2026-01-23T17:15:52+00:00" } ], "meta": { "languages": [ "py", "yml" ], "touches_tests": true, "review_state_summary": { "COMMENTED": 3, "APPROVED": 1 }, "meaningful_comment_count": 3, "has_approval": true, "has_changes_requested": false, "total_review_comments": 3 } } { "_id": "d14a5bb674a5dbb8", "_schema_version": "1.0", "_cleaned_at": "2026-02-12T07:46:51.929244+00:00", "repo": "scikit-learn/scikit-learn", "repo_url": "https://github.com/scikit-learn/scikit-learn", "license_name": "BSD 3-Clause \"New\" or \"Revised\" License", "license_spdx": "BSD-3-Clause", "pr_number": 33091, "title": "DOC/MNT Little clean up around the splitting docs and error message", "body": "Noticed while working on #33089\n\n#### What does this implement/fix? Explain your changes.\nA few clean ups around the splitting docs and error message.\n\n#### AI usage disclosure\n\nI used AI assistance for:\n- [ ] Code generation (e.g., when writing an implementation or fixing a bug)\n- [ ] Test/benchmark generation\n- [ ] Documentation (including examples)\n- [ ] Research and understanding", "author": "user_501030d9d7e3", "created_at": "2026-01-15T15:47:23+00:00", "merged_at": "2026-01-19T10:39:58+00:00", "base_branch": "main", "head_branch": "docs_and_errors", "additions": 49, "deletions": 46, "changed_files": 16, "files": [ { "filename": "sklearn/calibration.py", "status": "modified", "additions": 2, "deletions": 2, "changes": 4, "patch": "@@ -142,9 +142,9 @@ class CalibratedClassifierCV(ClassifierMixin, MetaEstimatorMixin, BaseEstimator)\n Possible inputs for cv are:\n \n - None, to use the default 5-fold cross-validation,\n- - integer, to specify the number of folds.\n+ - integer, to specify the number of folds,\n - :term:`CV splitter`,\n- - An iterable yielding (train, test) splits as arrays of indices.\n+ - an iterable yielding (train, test) splits as arrays of indices.\n \n For integer/None inputs, if ``y`` is binary or multiclass,\n :class:`~sklearn.model_selection.StratifiedKFold` is used. If ``y`` is" }, { "filename": "sklearn/covariance/_graph_lasso.py", "status": "modified", "additions": 2, "deletions": 2, "changes": 4, "patch": "@@ -747,9 +747,9 @@ class GraphicalLassoCV(BaseGraphicalLasso):\n Possible inputs for cv are:\n \n - None, to use the default 5-fold cross-validation,\n- - integer, to specify the number of folds.\n+ - integer, to specify the number of folds,\n - :term:`CV splitter`,\n- - An iterable yielding (train, test) splits as arrays of indices.\n+ - an iterable yielding (train, test) splits as arrays of indices.\n \n For integer/None inputs :class:`~sklearn.model_selection.KFold` is used." }, { "filename": "sklearn/feature_selection/_base.py", "status": "modified", "additions": 1, "deletions": 1, "changes": 2, "patch": "@@ -24,7 +24,7 @@\n \n class SelectorMixin(TransformerMixin, metaclass=ABCMeta):\n \"\"\"\n- Transformer mixin that performs feature selection given a support mask\n+ Transformer mixin that performs feature selection given a support mask.\n \n This mixin provides a feature selector implementation with `transform` and\n `inverse_transform` functionality given an implementation of" }, { "filename": "sklearn/feature_selection/_rfe.py", "status": "modified", "additions": 2, "deletions": 2, "changes": 4, "patch": "@@ -597,9 +597,9 @@ class RFECV(RFE):\n Possible inputs for cv are:\n \n - None, to use the default 5-fold cross-validation,\n- - integer, to specify the number of folds.\n+ - integer, to specify the number of folds,\n - :term:`CV splitter`,\n- - An iterable yielding (train, test) splits as arrays of indices.\n+ - an iterable yielding (train, test) splits as arrays of indices.\n \n For integer/None inputs, if ``y`` is binary or multiclass,\n :class:`~sklearn.model_selection.StratifiedKFold` is used. If the" }, { "filename": "sklearn/feature_selection/_sequential.py", "status": "modified", "additions": 1, "deletions": 1, "changes": 2, "patch": "@@ -99,7 +99,7 @@ class SequentialFeatureSelector(SelectorMixin, MetaEstimatorMixin, BaseEstimator\n - None, to use the default 5-fold cross validation,\n - integer, to specify the number of folds in a `(Stratified)KFold`,\n - :term:`CV splitter`,\n- - An iterable yielding (train, test) splits as arrays of indices.\n+ - an iterable yielding (train, test) splits as arrays of indices.\n \n For integer/None inputs, if the estimator is a classifier and ``y`` is\n either binary or multiclass," }, { "filename": "sklearn/linear_model/_coordinate_descent.py", "status": "modified", "additions": 8, "deletions": 8, "changes": 16, "patch": "@@ -2046,9 +2046,9 @@ class LassoCV(RegressorMixin, LinearModelCV):\n Possible inputs for cv are:\n \n - None, to use the default 5-fold cross-validation,\n- - int, to specify the number of folds.\n+ - int, to specify the number of folds,\n - :term:`CV splitter`,\n- - An iterable yielding (train, test) splits as arrays of indices.\n+ - an iterable yielding (train, test) splits as arrays of indices.\n \n For int/None inputs, :class:`~sklearn.model_selection.KFold` is used.\n \n@@ -2316,9 +2316,9 @@ class ElasticNetCV(RegressorMixin, LinearModelCV):\n Possible inputs for cv are:\n \n - None, to use the default 5-fold cross-validation,\n- - int, to specify the number of folds.\n+ - int, to specify the number of folds,\n - :term:`CV splitter`,\n- - An iterable yielding (train, test) splits as arrays of indices.\n+ - an iterable yielding (train, test) splits as arrays of indices.\n \n For int/None inputs, :class:`~sklearn.model_selection.KFold` is used.\n \n@@ -3014,9 +3014,9 @@ class MultiTaskElasticNetCV(RegressorMixin, LinearModelCV):\n Possible inputs for cv are:\n \n - None, to use the default 5-fold cross-validation,\n- - int, to specify the number of folds.\n+ - int, to specify the number of folds,\n - :term:`CV splitter`,\n- - An iterable yielding (train, test) splits as arrays of indices.\n+ - an iterable yielding (train, test) splits as arrays of indices.\n \n For int/None inputs, :class:`~sklearn.model_selection.KFold` is used.\n \n@@ -3272,9 +3272,9 @@ class MultiTaskLassoCV(RegressorMixin, LinearModelCV):\n Possible inputs for cv are:\n \n - None, to use the default 5-fold cross-validation,\n- - int, to specify the number of folds.\n+ - int, to specify the number of folds,\n - :term:`CV splitter`,\n- - An iterable yielding (train, test) splits as arrays of indices.\n+ - an iterable yielding (train, test) splits as arrays of indices.\n \n For int/None inputs, :class:`~sklearn.model_selection.KFold` is used." }, { "filename": "sklearn/linear_model/_least_angle.py", "status": "modified", "additions": 4, "deletions": 4, "changes": 8, "patch": "@@ -1542,9 +1542,9 @@ class LarsCV(Lars):\n Possible inputs for cv are:\n \n - None, to use the default 5-fold cross-validation,\n- - integer, to specify the number of folds.\n+ - integer, to specify the number of folds,\n - :term:`CV splitter`,\n- - An iterable yielding (train, test) splits as arrays of indices.\n+ - an iterable yielding (train, test) splits as arrays of indices.\n \n For integer/None inputs, :class:`~sklearn.model_selection.KFold` is used.\n \n@@ -1862,9 +1862,9 @@ class LassoLarsCV(LarsCV):\n Possible inputs for cv are:\n \n - None, to use the default 5-fold cross-validation,\n- - integer, to specify the number of folds.\n+ - integer, to specify the number of folds,\n - :term:`CV splitter`,\n- - An iterable yielding (train, test) splits as arrays of indices.\n+ - an iterable yielding (train, test) splits as arrays of indices.\n \n For integer/None inputs, :class:`~sklearn.model_selection.KFold` is used." }, { "filename": "sklearn/linear_model/_omp.py", "status": "modified", "additions": 2, "deletions": 2, "changes": 4, "patch": "@@ -926,9 +926,9 @@ class OrthogonalMatchingPursuitCV(RegressorMixin, LinearModel):\n Possible inputs for cv are:\n \n - None, to use the default 5-fold cross-validation,\n- - integer, to specify the number of folds.\n+ - integer, to specify the number of folds,\n - :term:`CV splitter`,\n- - An iterable yielding (train, test) splits as arrays of indices.\n+ - an iterable yielding (train, test) splits as arrays of indices.\n \n For integer/None inputs, :class:`~sklearn.model_selection.KFold` is used." }, { "filename": "sklearn/linear_model/_ridge.py", "status": "modified", "additions": 4, "deletions": 4, "changes": 8, "patch": "@@ -2654,9 +2654,9 @@ class RidgeCV(MultiOutputMixin, RegressorMixin, _BaseRidgeCV):\n Possible inputs for cv are:\n \n - None, to use the efficient Leave-One-Out cross-validation\n- - integer, to specify the number of folds.\n+ - integer, to specify the number of folds,\n - :term:`CV splitter`,\n- - An iterable yielding (train, test) splits as arrays of indices.\n+ - an iterable yielding (train, test) splits as arrays of indices.\n \n For integer/None inputs, if ``y`` is binary or multiclass,\n :class:`~sklearn.model_selection.StratifiedKFold` is used, else,\n@@ -2847,9 +2847,9 @@ class RidgeClassifierCV(_RidgeClassifierMixin, _BaseRidgeCV):\n Possible inputs for cv are:\n \n - None, to use the efficient Leave-One-Out cross-validation\n- - integer, to specify the number of folds.\n+ - integer, to specify the number of folds,\n - :term:`CV splitter`,\n- - An iterable yielding (train, test) splits as arrays of indices.\n+ - an iterable yielding (train, test) splits as arrays of indices.\n \n Refer :ref:`[NAME_REDACTED] ` for the various\n cross-validation strategies that can be used here." }, { "filename": "sklearn/model_selection/_plot.py", "status": "modified", "additions": 2, "deletions": 2, "changes": 4, "patch": "@@ -354,7 +354,7 @@ def from_estimator(\n - None, to use the default 5-fold cross validation,\n - int, to specify the number of folds in a `(Stratified)KFold`,\n - :term:`CV splitter`,\n- - An iterable yielding (train, test) splits as arrays of indices.\n+ - an iterable yielding (train, test) splits as arrays of indices.\n \n For int/None inputs, if the estimator is a classifier and `y` is\n either binary or multiclass,\n@@ -741,7 +741,7 @@ def from_estimator(\n - None, to use the default 5-fold cross validation,\n - int, to specify the number of folds in a `(Stratified)KFold`,\n - :term:`CV splitter`,\n- - An iterable yielding (train, test) splits as arrays of indices.\n+ - an iterable yielding (train, test) splits as arrays of indices.\n \n For int/None inputs, if the estimator is a classifier and `y` is\n either binary or multiclass," }, { "filename": "sklearn/model_selection/_search.py", "status": "modified", "additions": 2, "deletions": 2, "changes": 4, "patch": "@@ -1347,7 +1347,7 @@ class GridSearchCV(BaseSearchCV):\n - None, to use the default 5-fold cross validation,\n - integer, to specify the number of folds in a `(Stratified)KFold`,\n - :term:`CV splitter`,\n- - An iterable yielding (train, test) splits as arrays of indices.\n+ - an iterable yielding (train, test) splits as arrays of indices.\n \n For integer/None inputs, if the estimator is a classifier and ``y`` is\n either binary or multiclass, :class:`StratifiedKFold` is used. In all\n@@ -1732,7 +1732,7 @@ class RandomizedSearchCV(BaseSearchCV):\n - None, to use the default 5-fold cross validation,\n - integer, to specify the number of folds in a `(Stratified)KFold`,\n - :term:`CV splitter`,\n- - An iterable yielding (train, test) splits as arrays of indices.\n+ - an iterable yielding (train, test) splits as arrays of indices.\n \n For integer/None inputs, if the estimator is a classifier and ``y`` is\n either binary or multiclass, :class:`StratifiedKFold` is used. In all" }, { "filename": "sklearn/model_selection/_search_successive_halving.py", "status": "modified", "additions": 2, "deletions": 2, "changes": 4, "patch": "@@ -461,7 +461,7 @@ class HalvingGridSearchCV(BaseSuccessiveHalving):\n \n - integer, to specify the number of folds in a `(Stratified)KFold`,\n - :term:`CV splitter`,\n- - An iterable yielding (train, test) splits as arrays of indices.\n+ - an iterable yielding (train, test) splits as arrays of indices.\n \n For integer/None inputs, if the estimator is a classifier and ``y`` is\n either binary or multiclass, :class:`StratifiedKFold` is used. In all\n@@ -820,7 +820,7 @@ class HalvingRandomSearchCV(BaseSuccessiveHalving):\n \n - integer, to specify the number of folds in a `(Stratified)KFold`,\n - :term:`CV splitter`,\n- - An iterable yielding (train, test) splits as arrays of indices.\n+ - an iterable yielding (train, test) splits as arrays of indices.\n \n For integer/None inputs, if the estimator is a classifier and ``y`` is\n either binary or multiclass, :class:`StratifiedKFold` is used. In all" }, { "filename": "sklearn/model_selection/_split.py", "status": "modified", "additions": 9, "deletions": 7, "changes": 16, "patch": "@@ -2696,9 +2696,9 @@ def check_cv(cv=5, y=None, *, classifier=False):\n Determines the cross-validation splitting strategy.\n Possible inputs for cv are:\n - None, to use the default 5-fold cross validation,\n- - integer, to specify the number of folds.\n+ - integer, to specify the number of folds,\n - :term:`CV splitter`,\n- - An iterable that generates (train, test) splits as arrays of indices.\n+ - an iterable that generates (train, test) splits as arrays of indices.\n \n For integer/None inputs, if classifier is True and ``y`` is either\n binary or multiclass, :class:`StratifiedKFold` is used. In all other\n@@ -2714,8 +2714,10 @@ def check_cv(cv=5, y=None, *, classifier=False):\n The target variable for supervised learning problems.\n \n classifier : bool, default=False\n- Whether the task is a classification task, in which case\n- stratified KFold will be used.\n+ Whether the task is a classification task. When ``True`` and `cv` is an\n+ integer or ``None``, :class:`StratifiedKFold` is used if ``y`` is binary\n+ or multiclass; otherwise :class:`KFold` is used. Ignored if `cv` is a\n+ cross-validator instance or iterable.\n \n Returns\n -------\n@@ -2745,9 +2747,9 @@ def check_cv(cv=5, y=None, *, classifier=False):\n if not hasattr(cv, \"split\") or isinstance(cv, str):\n if not isinstance(cv, Iterable) or isinstance(cv, str):\n raise ValueError(\n- \"Expected cv as an integer, cross-validation \"\n- \"object (from sklearn.model_selection) \"\n- \"or an iterable. Got %s.\" % cv\n+ \"Expected `cv` as an integer, a cross-validation object \"\n+ \"(from sklearn.model_selection), or an iterable yielding (train, test) \"\n+ f\"splits as arrays of indices. Got {cv}.\"\n )\n return _CVIterableWrapper(cv)" }, { "filename": "sklearn/model_selection/_validation.py", "status": "modified", "additions": 4, "deletions": 4, "changes": 8, "patch": "@@ -170,7 +170,7 @@ def cross_validate(\n - None, to use the default 5-fold cross validation,\n - int, to specify the number of folds in a `(Stratified)KFold`,\n - :term:`CV splitter`,\n- - An iterable yielding (train, test) splits as arrays of indices.\n+ - an iterable yielding (train, test) splits as arrays of indices.\n \n For int/None inputs, if the estimator is a classifier and ``y`` is\n either binary or multiclass, :class:`StratifiedKFold` is used. In all\n@@ -1504,7 +1504,7 @@ def permutation_test_score(\n - `None`, to use the default 5-fold cross validation,\n - int, to specify the number of folds in a `(Stratified)KFold`,\n - :term:`CV splitter`,\n- - An iterable yielding (train, test) splits as arrays of indices.\n+ - an iterable yielding (train, test) splits as arrays of indices.\n \n For `int`/`None` inputs, if the estimator is a classifier and `y` is\n either binary or multiclass, :class:`StratifiedKFold` is used. In all\n@@ -1810,7 +1810,7 @@ def learning_curve(\n - None, to use the default 5-fold cross validation,\n - int, to specify the number of folds in a `(Stratified)KFold`,\n - :term:`CV splitter`,\n- - An iterable yielding (train, test) splits as arrays of indices.\n+ - an iterable yielding (train, test) splits as arrays of indices.\n \n For int/None inputs, if the estimator is a classifier and ``y`` is\n either binary or multiclass, :class:`StratifiedKFold` is used. In all\n@@ -2296,7 +2296,7 @@ def validation_curve(\n - None, to use the default 5-fold cross validation,\n - int, to specify the number of folds in a `(Stratified)KFold`,\n - :term:`CV splitter`,\n- - An iterable yielding (train, test) splits as arrays of indices.\n+ - an iterable yielding (train, test) splits as arrays of indices.\n \n For int/None inputs, if the estimator is a classifier and ``y`` is\n either binary or multiclass, :class:`StratifiedKFold` is used. In all" }, { "filename": "sklearn/model_selection/tests/test_split.py", "status": "modified", "additions": 2, "deletions": 1, "changes": 3, "patch": "@@ -1621,7 +1621,8 @@ def test_check_cv():\n cv = check_cv(3, y_multioutput, classifier=True)\n np.testing.assert_equal(list(KFold(3).split(X)), list(cv.split(X)))\n \n- with pytest.raises(ValueError):\n+ msg = \"Expected `cv` as an integer, a cross-validation object\"\n+ with pytest.raises(ValueError, match=msg):\n check_cv(cv=\"lolo\")" }, { "filename": "sklearn/multioutput.py", "status": "modified", "additions": 2, "deletions": 2, "changes": 4, "patch": "@@ -920,7 +920,7 @@ class ClassifierChain(MetaEstimatorMixin, ClassifierMixin, _BaseChain):\n - None, to use true labels when fitting,\n - integer, to specify the number of folds in a (Stratified)KFold,\n - :term:`CV splitter`,\n- - An iterable yielding (train, test) splits as arrays of indices.\n+ - an iterable yielding (train, test) splits as arrays of indices.\n \n chain_method : {'predict', 'predict_proba', 'predict_log_proba', \\\n 'decision_function'} or list of such str's, default='predict'\n@@ -1205,7 +1205,7 @@ class RegressorChain(MetaEstimatorMixin, RegressorMixin, _BaseChain):\n - None, to use true labels when fitting,\n - integer, to specify the number of folds in a (Stratified)KFold,\n - :term:`CV splitter`,\n- - An iterable yielding (train, test) splits as arrays of indices.\n+ - an iterable yielding (train, test) splits as arrays of indices.\n \n random_state : int, RandomState instance or None, optional (default=None)\n If ``order='random'``, determines random number generation for the" } ], "reviews": [ { "id": 3666296318, "user": "user_501030d9d7e3", "state": "COMMENTED", "body": null, "submitted_at": "2026-01-15T15:50:20+00:00" }, { "id": 3666421548, "user": "user_34a090906ca4", "state": "COMMENTED", "body": "Thank you [USER_REDACTED]! I have one nit and one clarification request (that actually goes beyond your changes).", "submitted_at": "2026-01-15T16:25:36+00:00" }, { "id": 3674162602, "user": "user_501030d9d7e3", "state": "COMMENTED", "body": "Thank you [USER_REDACTED]! I agree with your points and have pushed the changes.", "submitted_at": "2026-01-17T14:45:12+00:00" }, { "id": 3677254644, "user": "user_34a090906ca4", "state": "COMMENTED", "body": "One more small nit:\nThere are three different variations being used:\n`- integer, to specify the number of folds,`\n`- int, to specify the number of folds,`\n`- integer, to specify the number of folds in a `(Stratified)KFold`,`\n`- int, to specify the number of folds in a `(Stratified)KFold`,`\n\nShould we make them all the same?", "submitted_at": "2026-01-19T09:58:27+00:00" }, { "id": 3677348159, "user": "user_34a090906ca4", "state": "APPROVED", "body": "Alright, then LGTM.", "submitted_at": "2026-01-19T10:20:51+00:00" }, { "id": 3677420700, "user": "user_5819d17296ee", "state": "APPROVED", "body": null, "submitted_at": "2026-01-19T10:39:51+00:00" } ], "review_comments": [ { "id": 2694931868, "user": "user_501030d9d7e3", "body": "I made the error message more specific, since strings are also iterables.", "path": "sklearn/model_selection/_split.py", "line": 2752, "side": "RIGHT", "created_at": "2026-01-15T15:50:20+00:00" }, { "id": 2695030289, "user": "user_34a090906ca4", "body": "If we're being picky, this (and all other occurrences below) also has to start with a lowercase `an`", "path": "sklearn/covariance/_graph_lasso.py", "line": null, "side": "RIGHT", "created_at": "2026-01-15T16:08:44+00:00" }, { "id": 2695058068, "user": "user_34a090906ca4", "body": "According to lines 2703-2705 above, there are more dependencies to this selection. This could need some more clarification.", "path": "sklearn/model_selection/_split.py", "line": null, "side": "RIGHT", "created_at": "2026-01-15T16:16:00+00:00" }, { "id": 2701188512, "user": "user_501030d9d7e3", "body": "Oh yea, let's be picky. It looks more trustable if there are not these kind of mistakes.", "path": "sklearn/covariance/_graph_lasso.py", "line": null, "side": "RIGHT", "created_at": "2026-01-17T14:31:25+00:00" }, { "id": 2701194642, "user": "user_501030d9d7e3", "body": "True, I have added the additional information, do explain this better.", "path": "sklearn/model_selection/_split.py", "line": null, "side": "RIGHT", "created_at": "2026-01-17T14:42:01+00:00" } ], "meta": { "languages": [ "py" ], "touches_tests": true, "review_state_summary": { "COMMENTED": 4, "APPROVED": 2 }, "meaningful_comment_count": 5, "has_approval": true, "has_changes_requested": false, "total_review_comments": 5 } } { "_id": "27582d9796d3fc92", "_schema_version": "1.0", "_cleaned_at": "2026-02-12T07:46:51.929244+00:00", "repo": "scikit-learn/scikit-learn", "repo_url": "https://github.com/scikit-learn/scikit-learn", "license_name": "BSD 3-Clause \"New\" or \"Revised\" License", "license_spdx": "BSD-3-Clause", "pr_number": 33089, "title": "ENH Turn `TargetEncoder` into a metadata router and route `groups` to `cv` object", "body": "#### [NAME_REDACTED]/PRs\ncloses #32076\nsupersedes #32239 and #32843\n\n#### What does this implement/fix? Explain your changes.\n- turns `TargetEncoder` into a metadata router that routes `groups` to the internal splitter\n- adds more input options for `cv` init param (as discussed here https://github.com/[USER_REDACTED]n/scikit-learn/issues/32076#issuecomment-3307697377)\n- exposes cv_ attribute\n- add tests\n\n#### AI usage disclosure\n\nI used AI assistance for:\n- [ ] Code generation (e.g., when writing an implementation or fixing a bug)\n- [ ] Test/benchmark generation\n- [ ] Documentation (including examples)\n- [x] Research and understanding", "author": "user_501030d9d7e3", "created_at": "2026-01-15T15:12:44+00:00", "merged_at": "2026-01-28T15:35:43+00:00", "base_branch": "main", "head_branch": "TargetEncoder_routing", "additions": 177, "deletions": 24, "changed_files": 7, "files": [ { "filename": "doc/metadata_routing.rst", "status": "modified", "additions": 1, "deletions": 0, "changes": 1, "patch": "@@ -317,6 +317,7 @@ Meta-estimators and functions supporting metadata routing:\n - :class:`sklearn.multioutput.MultiOutputClassifier`\n - :class:`sklearn.multioutput.MultiOutputRegressor`\n - :class:`sklearn.multioutput.RegressorChain`\n+- :class:`sklearn.preprocessing.TargetEncoder`\n - :class:`sklearn.pipeline.FeatureUnion`\n - :class:`sklearn.pipeline.Pipeline`\n - :class:`sklearn.semi_supervised.SelfTrainingClassifier`" }, { "filename": "doc/whats_new/upcoming_changes/metadata-routing/33089.enhancement.rst", "status": "added", "additions": 5, "deletions": 0, "changes": 5, "patch": "@@ -0,0 +1,5 @@\n+- :class:`~preprocessing.TargetEncoder` now routes `groups` to the :term:`CV splitter`\n+ internally used for :term:`cross fitting` in its\n+ :meth:`~preprocessing.TargetEncoder.fit_transform`.\n+ By :user:`[NAME_REDACTED] ` and\n+ :user:`[NAME_REDACTED] `." }, { "filename": "sklearn/model_selection/_split.py", "status": "modified", "additions": 16, "deletions": 3, "changes": 19, "patch": "@@ -2687,7 +2687,7 @@ def split(self, X=None, y=None, groups=None):\n yield train, test\n \n \n-def check_cv(cv=5, y=None, *, classifier=False):\n+def check_cv(cv=5, y=None, *, classifier=False, shuffle=False, random_state=None):\n \"\"\"Input checker utility for building a cross-validator.\n \n Parameters\n@@ -2719,6 +2719,19 @@ def check_cv(cv=5, y=None, *, classifier=False):\n or multiclass; otherwise :class:`KFold` is used. Ignored if `cv` is a\n cross-validator instance or iterable.\n \n+ shuffle : bool, default=False\n+ Whether to shuffle the data before splitting into batches. Note that the samples\n+ within each split will not be shuffled. Only applies if `cv` is an int or\n+ `None`. If `cv` is a cross-validation generator or an iterable, `shuffle` is\n+ ignored.\n+\n+ random_state : int, RandomState instance or None, default=None\n+ When `shuffle` is True and `cv` is an integer or `None`, `random_state` affects\n+ the ordering of the indices, which controls the randomness of each fold.\n+ Otherwise, this parameter has no effect.\n+ Pass an int for reproducible output across multiple function calls.\n+ See :term:`Glossary `.\n+\n Returns\n -------\n checked_cv : a cross-validator instance.\n@@ -2740,9 +2753,9 @@ def check_cv(cv=5, y=None, *, classifier=False):\n and (y is not None)\n and (type_of_target(y, input_name=\"y\") in (\"binary\", \"multiclass\"))\n ):\n- return StratifiedKFold(cv)\n+ return StratifiedKFold(cv, shuffle=shuffle, random_state=random_state)\n else:\n- return KFold(cv)\n+ return KFold(cv, shuffle=shuffle, random_state=random_state)\n \n if not hasattr(cv, \"split\") or isinstance(cv, str):\n if not isinstance(cv, Iterable) or isinstance(cv, str):" }, { "filename": "sklearn/preprocessing/_target_encoder.py", "status": "modified", "additions": 116, "deletions": 19, "changes": 135, "patch": "@@ -1,7 +1,7 @@\n # Authors: The scikit-learn developers\n # SPDX-License-Identifier: BSD-3-Clause\n \n-from numbers import Integral, Real\n+from numbers import Real\n \n import numpy as np\n \n@@ -11,6 +11,14 @@\n _fit_encoding_fast,\n _fit_encoding_fast_auto_smooth,\n )\n+from sklearn.utils import Bunch, indexable\n+from sklearn.utils._metadata_requests import (\n+ MetadataRouter,\n+ MethodMapping,\n+ _raise_for_params,\n+ _routing_enabled,\n+ process_routing,\n+)\n from sklearn.utils._param_validation import Interval, StrOptions\n from sklearn.utils.multiclass import type_of_target\n from sklearn.utils.validation import (\n@@ -41,7 +49,7 @@ class TargetEncoder(OneToOneFeatureMixin, _BaseEncoder):\n that are not seen during :meth:`fit` are encoded with the target mean, i.e.\n `target_mean_`.\n \n- For a demo on the importance of the `TargetEncoder` internal cross-fitting,\n+ For a demo on the importance of the `TargetEncoder` internal :term:`cross fitting`,\n see\n :ref:`sphx_glr_auto_examples_preprocessing_plot_target_encoder_cross_val.py`.\n For a comparison of different encoders, refer to\n@@ -94,14 +102,33 @@ class TargetEncoder(OneToOneFeatureMixin, _BaseEncoder):\n more weight on the global target mean.\n If `\"auto\"`, then `smooth` is set to an empirical Bayes estimate.\n \n- cv : int, default=5\n- Determines the number of folds in the :term:`cross fitting` strategy used in\n- :meth:`fit_transform`. For classification targets, `StratifiedKFold` is used\n- and for continuous targets, `KFold` is used.\n+ cv : int, cross-validation generator or an iterable, default=None\n+ Determines the splitting strategy used in the internal :term:`cross fitting`\n+ during :meth:`fit_transform`. Splitters where each sample index doesn't appear\n+ in the validation fold exactly once, raise a `ValueError`.\n+ Possible inputs for cv are:\n+\n+ - `None`, to use a 5-fold cross-validation chosen internally based on\n+ `target_type`,\n+ - integer, to specify the number of folds for the cross-validation chosen\n+ internally based on `target_type`,\n+ - :term:`CV splitter` that does not repeat samples across validation folds,\n+ - an iterable yielding (train, test) splits as arrays of indices.\n+\n+ For integer/None inputs, if `target_type` is `\"continuous\"`, :class:`KFold` is\n+ used, otherwise :class:`StratifiedKFold` is used.\n+\n+ Refer :ref:`[NAME_REDACTED] ` for more information on\n+ cross-validation strategies.\n+\n+ .. versionchanged:: 1.9\n+ Cross-validation generators and iterables can also be passed as `cv`.\n \n shuffle : bool, default=True\n Whether to shuffle the data in :meth:`fit_transform` before splitting into\n- folds. Note that the samples within each split will not be shuffled.\n+ folds. Note that the samples within each split will not be shuffled. Only\n+ applies if `cv` is an int or `None`. If `cv` is a cross-validation generator or\n+ an iterable, `shuffle` is ignored.\n \n random_state : int, RandomState instance or None, default=None\n When `shuffle` is True, `random_state` affects the ordering of the\n@@ -193,7 +220,7 @@ class TargetEncoder(OneToOneFeatureMixin, _BaseEncoder):\n \"categories\": [StrOptions({\"auto\"}), list],\n \"target_type\": [StrOptions({\"auto\", \"continuous\", \"binary\", \"multiclass\"})],\n \"smooth\": [StrOptions({\"auto\"}), Interval(Real, 0, None, closed=\"left\")],\n- \"cv\": [Interval(Integral, 2, None, closed=\"left\")],\n+ \"cv\": [\"cv_object\"],\n \"shuffle\": [\"boolean\"],\n \"random_state\": [\"random_state\"],\n }\n@@ -243,7 +270,7 @@ def fit(self, X, y):\n return self\n \n @_fit_context(prefer_skip_nested_validation=True)\n- def fit_transform(self, X, y):\n+ def fit_transform(self, X, y, **params):\n \"\"\"Fit :class:`TargetEncoder` and transform `X` with the target encoding.\n \n This method uses a :term:`cross fitting` scheme to prevent target leakage\n@@ -263,28 +290,71 @@ def fit_transform(self, X, y):\n y : array-like of shape (n_samples,)\n The target data used to encode the categories.\n \n+ **params : dict\n+ Parameters to route to the internal CV object.\n+\n+ Can only be used in conjunction with a cross-validation generator as CV\n+ object.\n+\n+ For instance, `groups` (array-like of shape `(n_samples,)`) can be routed to\n+ a CV splitter that accepts `groups`, such as :class:`GroupKFold` or\n+ :class:`StratifiedGroupKFold`.\n+\n+ .. versionadded:: 1.9\n+ Only available if `enable_metadata_routing=True`, which can be\n+ set by using ``sklearn.set_config(enable_metadata_routing=True)``.\n+ See :ref:`[NAME_REDACTED] Guide ` for\n+ more details.\n+\n Returns\n -------\n X_trans : ndarray of shape (n_samples, n_features) or \\\n (n_samples, (n_features * n_classes))\n Transformed input.\n \"\"\"\n- from sklearn.model_selection import ( # avoid circular import\n+ # avoid circular imports\n+ from sklearn.model_selection import (\n+ GroupKFold,\n KFold,\n+ StratifiedGroupKFold,\n StratifiedKFold,\n )\n+ from sklearn.model_selection._split import check_cv\n+\n+ _raise_for_params(params, self, \"fit_transform\")\n \n X_ordinal, X_known_mask, y_encoded, n_categories = self._fit_encodings_all(X, y)\n \n- # The cv splitter is voluntarily restricted to *KFold to enforce non\n- # overlapping validation folds, otherwise the fit_transform output will\n- # not be well-specified.\n- if self.target_type_ == \"continuous\":\n- cv = KFold(self.cv, shuffle=self.shuffle, random_state=self.random_state)\n+ cv = check_cv(\n+ self.cv,\n+ y,\n+ classifier=self.target_type_ != \"continuous\",\n+ shuffle=self.shuffle,\n+ random_state=self.random_state,\n+ )\n+\n+ if _routing_enabled():\n+ if params[\"groups\"] is not None:\n+ X, y, params[\"groups\"] = indexable(X, y, params[\"groups\"])\n+ routed_params = process_routing(self, \"fit_transform\", **params)\n else:\n- cv = StratifiedKFold(\n- self.cv, shuffle=self.shuffle, random_state=self.random_state\n- )\n+ routed_params = Bunch(splitter=Bunch(split={}))\n+\n+ # The internal cross-fitting is only well-defined when each sample index\n+ # appears in exactly one validation fold. Skip the validation check for\n+ # known non-overlapping splitters in scikit-learn:\n+ if not isinstance(\n+ cv, (GroupKFold, KFold, StratifiedKFold, StratifiedGroupKFold)\n+ ):\n+ seen_count = np.zeros(X.shape[0])\n+ for _, test_idx in cv.split(X, y, **routed_params.splitter.split):\n+ seen_count[test_idx] += 1\n+ if not np.all(seen_count == 1):\n+ raise ValueError(\n+ \"Validation indices from `cv` must cover each sample index exactly \"\n+ \"once with no overlap. Pass a splitter with non-overlapping \"\n+ \"validation folds as `cv` or refer to the docs for other options.\"\n+ )\n \n # If 'multiclass' multiply axis=1 by [NAME_REDACTED] shape the same\n if self.target_type_ == \"multiclass\":\n@@ -295,7 +365,7 @@ def fit_transform(self, X, y):\n else:\n X_out = np.empty_like(X_ordinal, dtype=np.float64)\n \n- for train_idx, test_idx in cv.split(X, y):\n+ for train_idx, test_idx in cv.split(X, y, **routed_params.splitter.split):\n X_train, y_train = X_ordinal[train_idx, :], y_encoded[train_idx]\n y_train_mean = np.mean(y_train, axis=0)\n \n@@ -546,6 +616,33 @@ def get_feature_names_out(self, input_features=None):\n else:\n return feature_names\n \n+ def get_metadata_routing(self):\n+ \"\"\"Get metadata routing of this object.\n+\n+ Please check :ref:`[NAME_REDACTED] ` on how the routing\n+ mechanism works.\n+\n+ .. versionadded:: 1.9\n+\n+ Returns\n+ -------\n+ routing : MetadataRouter\n+ A :class:`~sklearn.utils.metadata_routing.MetadataRouter` encapsulating\n+ routing information.\n+ \"\"\"\n+\n+ router = MetadataRouter(owner=self)\n+\n+ router.add(\n+ # This works, since none of {None, int, iterable} request any metadata\n+ # and the machinery here would assign an empty MetadataRequest\n+ # to it.\n+ splitter=self.cv,\n+ method_mapping=MethodMapping().add(caller=\"fit_transform\", callee=\"split\"),\n+ )\n+\n+ return router\n+\n def __sklearn_tags__(self):\n tags = super().__sklearn_tags__()\n tags.target_tags.required = True" }, { "filename": "sklearn/preprocessing/tests/test_target_encoder.py", "status": "modified", "additions": 20, "deletions": 0, "changes": 20, "patch": "@@ -5,6 +5,7 @@\n import pytest\n from numpy.testing import assert_allclose, assert_array_equal\n \n+from sklearn.datasets import make_regression\n from sklearn.ensemble import RandomForestRegressor\n from sklearn.linear_model import Ridge\n from sklearn.model_selection import (\n@@ -732,3 +733,22 @@ def test_pandas_copy_on_write():\n with pd.option_context(\"mode.copy_on_write\", True):\n df = pd.DataFrame({\"x\": [\"a\", \"b\", \"b\"], \"y\": [4.0, 5.0, 6.0]})\n TargetEncoder(target_type=\"continuous\").fit(df[[\"x\"]], df[\"y\"])\n+\n+\n+def test_target_encoder_raises_cv_overlap(global_random_seed):\n+ \"\"\"\n+ Test that `TargetEncoder` raises if `cv` has overlapping splits.\n+ \"\"\"\n+ X, y = make_regression(n_samples=100, n_features=3, random_state=0)\n+\n+ non_overlapping_iterable = KFold().split(X, y)\n+ encoder = TargetEncoder(cv=non_overlapping_iterable)\n+ encoder.fit_transform(X, y)\n+\n+ overlapping_iterable = ShuffleSplit(\n+ n_splits=5, random_state=global_random_seed\n+ ).split(X, y)\n+ encoder = TargetEncoder(cv=overlapping_iterable)\n+ msg = \"Validation indices from `cv` must cover each sample index exactly once\"\n+ with pytest.raises(ValueError, match=msg):\n+ encoder.fit_transform(X, y)" }, { "filename": "sklearn/tests/metadata_routing_common.py", "status": "modified", "additions": 6, "deletions": 1, "changes": 7, "patch": "@@ -15,7 +15,7 @@\n )\n from sklearn.metrics._scorer import _Scorer, mean_squared_error\n from sklearn.model_selection import BaseCrossValidator\n-from sklearn.model_selection._split import GroupsConsumerMixin\n+from sklearn.model_selection._split import GroupKFold, GroupsConsumerMixin\n from sklearn.utils._metadata_requests import (\n SIMPLE_METHODS,\n )\n@@ -480,6 +480,11 @@ def _iter_test_indices(self, X=None, y=None, groups=None):\n yield train_indices\n \n \n+class ConsumingSplitterInheritingFromGroupKFold(ConsumingSplitter, GroupKFold):\n+ \"\"\"Helper class that can be used to test TargetEncoder, that only takes specific\n+ splitters.\"\"\"\n+\n+\n class MetaRegressor(MetaEstimatorMixin, RegressorMixin, BaseEstimator):\n \"\"\"A meta-regressor which is only a router.\"\"\"" }, { "filename": "sklearn/tests/test_metaestimators_metadata_routing.py", "status": "modified", "additions": 13, "deletions": 1, "changes": 14, "patch": "@@ -63,12 +63,14 @@\n MultiOutputRegressor,\n RegressorChain,\n )\n+from sklearn.preprocessing import TargetEncoder\n from sklearn.semi_supervised import SelfTrainingClassifier\n from sklearn.tests.metadata_routing_common import (\n ConsumingClassifier,\n ConsumingRegressor,\n ConsumingScorer,\n ConsumingSplitter,\n+ ConsumingSplitterInheritingFromGroupKFold,\n NonConsumingClassifier,\n NonConsumingRegressor,\n _Registry,\n@@ -448,6 +450,13 @@\n \"X\": X,\n \"y\": y,\n },\n+ {\n+ \"metaestimator\": TargetEncoder,\n+ \"X\": X,\n+ \"y\": y,\n+ \"cv_name\": \"cv\",\n+ \"cv_routing_methods\": [\"fit_transform\"],\n+ },\n ]\n \"\"\"List containing all metaestimators to be tested and their settings\n \n@@ -560,7 +569,10 @@ def get_init_args(metaestimator_info, sub_estimator_consumes):\n if \"cv_name\" in metaestimator_info:\n cv_name = metaestimator_info[\"cv_name\"]\n cv_registry = _Registry()\n- cv = ConsumingSplitter(registry=cv_registry)\n+ if metaestimator_info[\"metaestimator\"] is TargetEncoder:\n+ cv = ConsumingSplitterInheritingFromGroupKFold(registry=cv_registry)\n+ else:\n+ cv = ConsumingSplitter(registry=cv_registry)\n kwargs[cv_name] = cv\n \n return (" } ], "reviews": [ { "id": 3666169575, "user": "user_501030d9d7e3", "state": "COMMENTED", "body": null, "submitted_at": "2026-01-15T15:24:31+00:00" }, { "id": 3666501936, "user": "user_501030d9d7e3", "state": "COMMENTED", "body": null, "submitted_at": "2026-01-15T16:23:24+00:00" }, { "id": 3666884812, "user": "user_04b4a5f4e2a8", "state": "COMMENTED", "body": null, "submitted_at": "2026-01-15T18:02:04+00:00" }, { "id": 3674203183, "user": "user_501030d9d7e3", "state": "COMMENTED", "body": "Thanks, [USER_REDACTED]!", "submitted_at": "2026-01-17T15:37:30+00:00" }, { "id": 3675625918, "user": "user_04b4a5f4e2a8", "state": "COMMENTED", "body": null, "submitted_at": "2026-01-18T18:06:49+00:00" }, { "id": 3675643988, "user": "user_501030d9d7e3", "state": "COMMENTED", "body": null, "submitted_at": "2026-01-18T18:28:29+00:00" }, { "id": 3677777291, "user": "user_49a647962c6b", "state": "COMMENTED", "body": "a few minor comments, otherwise LGTM.", "submitted_at": "2026-01-19T12:40:51+00:00" }, { "id": 3692373400, "user": "user_501030d9d7e3", "state": "COMMENTED", "body": "Thanks for the review, [USER_REDACTED]! I have applied your suggestions.", "submitted_at": "2026-01-22T13:37:40+00:00" }, { "id": 3711415654, "user": "user_49a647962c6b", "state": "APPROVED", "body": "Otherwise LGTM.\n\n[USER_REDACTED] wanna have a final look?", "submitted_at": "2026-01-27T14:14:15+00:00" }, { "id": 3717407389, "user": "user_04b4a5f4e2a8", "state": "APPROVED", "body": "LGTM", "submitted_at": "2026-01-28T15:35:32+00:00" } ], "review_comments": [ { "id": 2694831614, "user": "user_501030d9d7e3", "body": "Passing `**routed_params.splitter.split` into `cv.split` is needed for the test. It doesn't route here since nothing is done with the splits, but the routed metadata gets recorded in the `_records` attribute of the splitter.", "path": "sklearn/preprocessing/_target_encoder.py", "line": null, "side": "RIGHT", "created_at": "2026-01-15T15:24:31+00:00" }, { "id": 2695093381, "user": "user_501030d9d7e3", "body": "We need to add a shuffle option to check_cv, since by default, data in TargetEncoder get shuffled before it gets split via the splitter.", "path": "sklearn/model_selection/_split.py", "line": 2690, "side": "RIGHT", "created_at": "2026-01-15T16:23:24+00:00" }, { "id": 2695404434, "user": "user_04b4a5f4e2a8", "body": "Can this be an `isinstance` check?", "path": "sklearn/preprocessing/_target_encoder.py", "line": null, "side": "RIGHT", "created_at": "2026-01-15T17:55:34+00:00" }, { "id": 2695407719, "user": "user_04b4a5f4e2a8", "body": "What is `self.cv_` used for?", "path": "sklearn/preprocessing/_target_encoder.py", "line": null, "side": "RIGHT", "created_at": "2026-01-15T17:56:49+00:00" }, { "id": 2695421578, "user": "user_04b4a5f4e2a8", "body": "using `np.concaetenate` allocates new arrays during each cycle. As an alternative can we create an int array of length `X.shape[0]`, add 1 to each position we seen, and then check that all the values are 1?\n\nHigh level:\n\n```python\nseen_count= np.zeros(X.shape[0])\nfor _, test_idx in cv.split(...):\n seen_count[test_idx] += 1\n\n# check that all seen_count is equal to one\n```", "path": "sklearn/preprocessing/_target_encoder.py", "line": null, "side": "RIGHT", "created_at": "2026-01-15T18:01:38+00:00" }, { "id": 2701211110, "user": "user_501030d9d7e3", "body": "Yes, I actually wanted to change that and then forgot about this. Now it is an `isinstance` check.", "path": "sklearn/preprocessing/_target_encoder.py", "line": null, "side": "RIGHT", "created_at": "2026-01-17T15:08:27+00:00" }, { "id": 2701213555, "user": "user_501030d9d7e3", "body": "Just as a check for the user which splitting strategy had been internally determined, to reduce the magic.\n(It was more necessary in #32843 than here, since this version doesn't introduce an automatism for internally determining a grouped splitter, but might still be useful here?)\nWhat do you think about this?", "path": "sklearn/preprocessing/_target_encoder.py", "line": null, "side": "RIGHT", "created_at": "2026-01-17T15:12:35+00:00" }, { "id": 2701226151, "user": "user_501030d9d7e3", "body": "Oh yes, of cause!", "path": "sklearn/preprocessing/_target_encoder.py", "line": null, "side": "RIGHT", "created_at": "2026-01-17T15:34:41+00:00" }, { "id": 2702610620, "user": "user_04b4a5f4e2a8", "body": "I do not recall having a precedence of storing an object's name as an attribute, but I think it's okay here because it's a short string. Is there a test to check that `cv_` is set correctly?\n\nThe alternative is to store the `cv` object itself, but one can have an custom cv object that is large. (Although, I think it'll be unlikely for custom cv objects to get big.)", "path": "sklearn/preprocessing/_target_encoder.py", "line": null, "side": "RIGHT", "created_at": "2026-01-18T18:06:48+00:00" }, { "id": 2702624863, "user": "user_501030d9d7e3", "body": "> Is there a test to check that `cv_` is set correctly?\n\nI have added `TargetEncoder` to `test_fit_docstring_attributes` in `sklearn/tests/test_docstring_parameters.py` to check for this attribute. The test is a simple test if the attribute is exposed after `fit_transform`. It does not test for correctness. I will add a test for this.", "path": "sklearn/preprocessing/_target_encoder.py", "line": null, "side": "RIGHT", "created_at": "2026-01-18T18:28:29+00:00" }, { "id": 2704496859, "user": "user_49a647962c6b", "body": "add a note that these are used only when cv is an integer", "path": "sklearn/model_selection/_split.py", "line": 2733, "side": "RIGHT", "created_at": "2026-01-19T12:07:05+00:00" }, { "id": 2704503467, "user": "user_49a647962c6b", "body": "```suggestion\n `target_type`,\n```", "path": "sklearn/preprocessing/_target_encoder.py", "line": null, "side": "RIGHT", "created_at": "2026-01-19T12:09:07+00:00" }, { "id": 2704508846, "user": "user_49a647962c6b", "body": "we don't really do this in other places, and thinking of our conventions, if I see `obj.cv_` I'd expect the actual instance, not the name. So I'd remove this attribute.", "path": "sklearn/preprocessing/_target_encoder.py", "line": null, "side": "RIGHT", "created_at": "2026-01-19T12:10:41+00:00" }, { "id": 2704525722, "user": "user_49a647962c6b", "body": "now that users can pass an actual `cv`, this is redundant, so ideally I'd remove it, but I don't think we have to go through the deprecation and leave it here.", "path": "sklearn/preprocessing/_target_encoder.py", "line": 131, "side": "RIGHT", "created_at": "2026-01-19T12:15:40+00:00" }, { "id": 2704528366, "user": "user_49a647962c6b", "body": "same applies here.", "path": "sklearn/preprocessing/_target_encoder.py", "line": 133, "side": "RIGHT", "created_at": "2026-01-19T12:16:35+00:00" }, { "id": 2704528757, "user": "user_49a647962c6b", "body": "to be removed", "path": "sklearn/preprocessing/_target_encoder.py", "line": null, "side": "RIGHT", "created_at": "2026-01-19T12:16:43+00:00" }, { "id": 2704531792, "user": "user_49a647962c6b", "body": "we don't need this, unless, something breaks in a pipeline or a metaestimator calling `fit.transform` instead of `fit_transform`, but I think that already breaks since the two are not equivalent anyway.", "path": "sklearn/preprocessing/_target_encoder.py", "line": null, "side": "RIGHT", "created_at": "2026-01-19T12:17:42+00:00" }, { "id": 2704547891, "user": "user_49a647962c6b", "body": "all of this can become:\n\n```py\n cv = check_cv(\n self.cv,\n y,\n classifier=self.target_type_ != \"continuous\",\n shuffle=self.shuffle,\n random_state=self.random_state,\n )\n```", "path": "sklearn/preprocessing/_target_encoder.py", "line": null, "side": "RIGHT", "created_at": "2026-01-19T12:21:54+00:00" }, { "id": 2716849365, "user": "user_501030d9d7e3", "body": "Yes, I have removed it.", "path": "sklearn/preprocessing/_target_encoder.py", "line": null, "side": "RIGHT", "created_at": "2026-01-22T13:08:56+00:00" }, { "id": 2716868315, "user": "user_501030d9d7e3", "body": "I agree. I can later open a follow up-PR on this to deprecate `shuffle` and `random_state`.", "path": "sklearn/preprocessing/_target_encoder.py", "line": 131, "side": "RIGHT", "created_at": "2026-01-22T13:14:10+00:00" }, { "id": 2716874994, "user": "user_501030d9d7e3", "body": "I have now removed the attribute and the test case. See https://github.com/[USER_REDACTED]n/scikit-learn/pull/33089/changes#r2704508846", "path": "sklearn/preprocessing/_target_encoder.py", "line": null, "side": "RIGHT", "created_at": "2026-01-22T13:15:56+00:00" }, { "id": 2716900853, "user": "user_501030d9d7e3", "body": "Yes, true, thanks.", "path": "sklearn/preprocessing/_target_encoder.py", "line": null, "side": "RIGHT", "created_at": "2026-01-22T13:23:03+00:00" }, { "id": 2732186441, "user": "user_49a647962c6b", "body": "Note to reviewers / readers from the very distant future:\n\nThis calls `split` here, and then the same method is called again the for loop bellow. Which means we're running split twice.\n\nHowever, compared to what happens in the for loop bellow, this is really fast, and it's a better user experience if we raise here quickly, rather than potentially raising in the expensive for loop bellow after a few iterations.", "path": "sklearn/preprocessing/_target_encoder.py", "line": 351, "side": "RIGHT", "created_at": "2026-01-27T14:07:57+00:00" }, { "id": 2732207888, "user": "user_49a647962c6b", "body": "```suggestion\n router.add(\n # This works, since none of {None, int, iterable} request any metadata\n # and the machinery here would assign an empty MetadataRequest\n # to it.\n splitter=self.cv,\n```", "path": "sklearn/preprocessing/_target_encoder.py", "line": null, "side": "RIGHT", "created_at": "2026-01-27T14:12:58+00:00" } ], "meta": { "languages": [ "py", "rst" ], "touches_tests": true, "review_state_summary": { "COMMENTED": 8, "APPROVED": 2 }, "meaningful_comment_count": 24, "has_approval": true, "has_changes_requested": false, "total_review_comments": 24 } } { "_id": "92aca353c2f09308", "_schema_version": "1.0", "_cleaned_at": "2026-02-12T07:46:51.929244+00:00", "repo": "scikit-learn/scikit-learn", "repo_url": "https://github.com/scikit-learn/scikit-learn", "license_name": "BSD 3-Clause \"New\" or \"Revised\" License", "license_spdx": "BSD-3-Clause", "pr_number": 33068, "title": "CI [NAME_REDACTED] min_dependencies test job from Azure to GHA", "body": "Addresses part of #32434", "author": "user_c91ee6762b06", "created_at": "2026-01-13T13:40:58+00:00", "merged_at": "2026-01-13T15:50:59+00:00", "base_branch": "main", "head_branch": "push-qltyvkprxxtl", "additions": 13, "deletions": 24, "changed_files": 2, "files": [ { "filename": ".github/workflows/unit-tests.yml", "status": "modified", "additions": 13, "deletions": 0, "changes": 13, "patch": "@@ -127,6 +127,19 @@ jobs:\n DISTRIB: conda\n LOCK_FILE: build_tools/github/pymin_conda_forge_arm_linux-aarch64_conda.lock\n \n+ # Linux build with minimum supported version of dependencies\n+ - name: Linux x86-64 pymin_conda_forge_openblas_min_dependencies\n+ os: ubuntu-22.04\n+ DISTRIB: conda\n+ LOCK_FILE: build_tools/azure/pymin_conda_forge_openblas_min_dependencies_linux-64_conda.lock\n+ # Enable debug Cython directives to capture IndexError exceptions in\n+ # combination with the -Werror::pytest.PytestUnraisableExceptionWarning\n+ # flag for pytest.\n+ # https://github.com/[USER_REDACTED]n/scikit-learn/pull/24438\n+ SKLEARN_ENABLE_DEBUG_CYTHON_DIRECTIVES: 1\n+ SKLEARN_RUN_FLOAT32_TESTS: 1\n+ SKLEARN_TESTS_GLOBAL_RANDOM_SEED: 2 # non-default seed\n+\n # Linux environment to test the latest available dependencies.\n # It runs tests requiring lightgbm, pandas and PyAMG.\n - name: Linux pylatest_pip_openblas_pandas" }, { "filename": "azure-pipelines.yml", "status": "modified", "additions": 0, "deletions": 24, "changes": 24, "patch": "@@ -138,30 +138,6 @@ jobs:\n COVERAGE: 'false'\n SKLEARN_TESTS_GLOBAL_RANDOM_SEED: '0' # non-default seed\n \n-- template: build_tools/azure/posix.yml\n- parameters:\n- name: Linux\n- vmImage: ubuntu-22.04\n- dependsOn: [linting, git_commit, Ubuntu_Jammy_Jellyfish]\n- # Runs when dependencies succeeded or skipped\n- condition: |\n- and(\n- not(or(failed(), canceled())),\n- not(contains(dependencies['git_commit']['outputs']['commit.message'], '[ci skip]'))\n- )\n- matrix:\n- # Linux build with minimum supported version of dependencies\n- pymin_conda_forge_openblas_min_dependencies:\n- DISTRIB: 'conda'\n- LOCK_FILE: './build_tools/azure/pymin_conda_forge_openblas_min_dependencies_linux-64_conda.lock'\n- # Enable debug Cython directives to capture IndexError exceptions in\n- # combination with the -Werror::pytest.PytestUnraisableExceptionWarning\n- # flag for pytest.\n- # https://github.com/[USER_REDACTED]n/scikit-learn/pull/24438\n- SKLEARN_ENABLE_DEBUG_CYTHON_DIRECTIVES: '1'\n- SKLEARN_RUN_FLOAT32_TESTS: '1'\n- SKLEARN_TESTS_GLOBAL_RANDOM_SEED: '2' # non-default seed\n-\n - template: build_tools/azure/posix-docker.yml\n parameters:\n name: Linux_Docker" } ], "reviews": [ { "id": 3656051340, "user": "user_c91ee6762b06", "state": "COMMENTED", "body": null, "submitted_at": "2026-01-13T14:18:01+00:00" }, { "id": 3656289806, "user": "user_fca2535bcd49", "state": "COMMENTED", "body": null, "submitted_at": "2026-01-13T15:01:30+00:00" }, { "id": 3656535306, "user": "user_fca2535bcd49", "state": "APPROVED", "body": null, "submitted_at": "2026-01-13T15:50:51+00:00" } ], "review_comments": [ { "id": 2686629679, "user": "user_c91ee6762b06", "body": "```suggestion\n os: ubuntu-24.04\n```\nmaybe?", "path": ".github/workflows/unit-tests.yml", "line": 132, "side": "RIGHT", "created_at": "2026-01-13T14:18:01+00:00" }, { "id": 2686812003, "user": "user_fca2535bcd49", "body": "This one I would leave it like this.\n\n- it may be done on purpose to use the oldest not EOLed Ubuntu version to check against old compiler versions that everything works fine. Maybe if you are curious some code archeology could enlighten us, but I don't think this is worth doing right now.\n- not changing too many unrelated things at the same time unless there is a strong need.", "path": ".github/workflows/unit-tests.yml", "line": 132, "side": "RIGHT", "created_at": "2026-01-13T15:01:30+00:00" } ], "meta": { "languages": [ "yml" ], "touches_tests": false, "review_state_summary": { "COMMENTED": 2, "APPROVED": 1 }, "meaningful_comment_count": 2, "has_approval": true, "has_changes_requested": false, "total_review_comments": 2 } } { "_id": "e21487c9941e15c1", "_schema_version": "1.0", "_cleaned_at": "2026-02-12T07:46:51.929244+00:00", "repo": "scikit-learn/scikit-learn", "repo_url": "https://github.com/scikit-learn/scikit-learn", "license_name": "BSD 3-Clause \"New\" or \"Revised\" License", "license_spdx": "BSD-3-Clause", "pr_number": 33065, "title": "CI [NAME_REDACTED] no_openmp test job from Azure to GHA", "body": "Addresses part of #32434", "author": "user_c91ee6762b06", "created_at": "2026-01-13T11:08:45+00:00", "merged_at": "2026-01-14T12:07:18+00:00", "base_branch": "main", "head_branch": "push-uvyzzszyxzzs", "additions": 9, "deletions": 20, "changed_files": 2, "files": [ { "filename": ".github/workflows/unit-tests.yml", "status": "modified", "additions": 9, "deletions": 1, "changes": 10, "patch": "@@ -167,14 +167,22 @@ jobs:\n SKLEARN_TESTS_GLOBAL_RANDOM_SEED: 1 # non-default seed\n \n - name: macOS pylatest_conda_forge_arm\n- os: macOS-15\n+ os: macos-15\n DISTRIB: conda\n LOCK_FILE: build_tools/azure/pylatest_conda_forge_osx-arm64_conda.lock\n SKLEARN_TESTS_GLOBAL_RANDOM_SEED: 5 # non-default seed\n SCIPY_ARRAY_API: 1\n PYTORCH_ENABLE_MPS_FALLBACK: 1\n CHECK_PYTEST_SOFT_DEPENDENCY: true\n \n+ - name: macOS x86-64 pylatest_conda_forge_mkl_no_openmp\n+ os: macos-15-intel\n+ DISTRIB: conda\n+ LOCK_FILE: build_tools/azure/pylatest_conda_forge_mkl_no_openmp_osx-64_conda.lock\n+ SKLEARN_TEST_NO_OPENMP: true\n+ SKLEARN_SKIP_OPENMP_TEST: true\n+ SKLEARN_TESTS_GLOBAL_RANDOM_SEED: 6 # non-default seed\n+\n - name: Windows x64 pymin_conda_forge_openblas\n os: windows-latest\n DISTRIB: conda" }, { "filename": "azure-pipelines.yml", "status": "modified", "additions": 0, "deletions": 19, "changes": 19, "patch": "@@ -156,22 +156,3 @@ jobs:\n COVERAGE: \"true\"\n LOCK_FILE: './build_tools/azure/debian_32bit_lock.txt'\n SKLEARN_TESTS_GLOBAL_RANDOM_SEED: '4' # non-default seed\n-\n-- template: build_tools/azure/posix.yml\n- parameters:\n- name: macOS\n- vmImage: macOS-15\n- dependsOn: [linting, git_commit, Ubuntu_Jammy_Jellyfish]\n- # Runs when dependencies succeeded or skipped\n- condition: |\n- and(\n- not(or(failed(), canceled())),\n- not(contains(dependencies['git_commit']['outputs']['commit.message'], '[ci skip]'))\n- )\n- matrix:\n- pylatest_conda_forge_mkl_no_openmp:\n- DISTRIB: 'conda'\n- LOCK_FILE: './build_tools/azure/pylatest_conda_forge_mkl_no_openmp_osx-64_conda.lock'\n- SKLEARN_TEST_NO_OPENMP: 'true'\n- SKLEARN_SKIP_OPENMP_TEST: 'true'\n- SKLEARN_TESTS_GLOBAL_RANDOM_SEED: '6' # non-default seed" } ], "reviews": [ { "id": 3655277864, "user": "user_fca2535bcd49", "state": "COMMENTED", "body": null, "submitted_at": "2026-01-13T11:23:17+00:00" }, { "id": 3655293111, "user": "user_c91ee6762b06", "state": "COMMENTED", "body": null, "submitted_at": "2026-01-13T11:27:40+00:00" }, { "id": 3655651345, "user": "user_c91ee6762b06", "state": "COMMENTED", "body": null, "submitted_at": "2026-01-13T12:56:48+00:00" }, { "id": 3655803482, "user": "user_fca2535bcd49", "state": "COMMENTED", "body": "Thanks for the PR, a few comments below", "submitted_at": "2026-01-13T13:34:52+00:00" }, { "id": 3656032783, "user": "user_fca2535bcd49", "state": "COMMENTED", "body": null, "submitted_at": "2026-01-13T14:14:48+00:00" }, { "id": 3656219702, "user": "user_fca2535bcd49", "state": "COMMENTED", "body": null, "submitted_at": "2026-01-13T14:48:10+00:00" }, { "id": 3656325459, "user": "user_fca2535bcd49", "state": "APPROVED", "body": null, "submitted_at": "2026-01-13T15:08:49+00:00" } ], "review_comments": [ { "id": 2685977380, "user": "user_fca2535bcd49", "body": "So there is a joke here, I think you need to use macos-15-intel on GHA to have a macOS Intel VM. macOS-15 on Azure is a macOS Intel VM, macos-15 on GHA is a macOS arm VM. The lock-file has been created for a macOS Intel OS (`osx-64` int he lock file name)\n\nDo double-check this, I am not 100% confident but it does ring a bell.", "path": ".github/workflows/unit-tests.yml", "line": null, "side": "RIGHT", "created_at": "2026-01-13T11:23:17+00:00" }, { "id": 2685991373, "user": "user_c91ee6762b06", "body": "i see that mac-15 is indeed expanded to mac-15-arm64", "path": ".github/workflows/unit-tests.yml", "line": null, "side": "RIGHT", "created_at": "2026-01-13T11:27:40+00:00" }, { "id": 2686305824, "user": "user_c91ee6762b06", "body": "seems to work!", "path": ".github/workflows/unit-tests.yml", "line": null, "side": "RIGHT", "created_at": "2026-01-13T12:56:48+00:00" }, { "id": 2686441750, "user": "user_fca2535bcd49", "body": "Even if arguably a bit more ambiguous, I would stick to the values documented in the [doc](https://docs.github.com/en/actions/reference/workflows-and-actions/workflow-syntax#choosing-github-hosted-runners)\n```suggestion\n os: macos-15\n```", "path": ".github/workflows/unit-tests.yml", "line": null, "side": "RIGHT", "created_at": "2026-01-13T13:29:46+00:00" }, { "id": 2686444696, "user": "user_fca2535bcd49", "body": "I would stick to the lower case to follow the [documentation](https://docs.github.com/en/actions/reference/workflows-and-actions/workflow-syntax#choosing-github-hosted-runners)\n```suggestion\n os: macos-15-intel\n```", "path": ".github/workflows/unit-tests.yml", "line": null, "side": "RIGHT", "created_at": "2026-01-13T13:30:35+00:00" }, { "id": 2686456697, "user": "user_fca2535bcd49", "body": "I am wondering if the build name should not include the architecture as well?Sometimes it's mentioned in the lock-file name sometimes not but putting it at the beginning may help anyway.\n\n```suggestion\n - name: macOS Intel pylatest_conda_forge_mkl_no_openmp\n```", "path": ".github/workflows/unit-tests.yml", "line": null, "side": "RIGHT", "created_at": "2026-01-13T13:34:02+00:00" }, { "id": 2686616720, "user": "user_fca2535bcd49", "body": "Changing my mind about naming for consistency\n\n```suggestion\n - name: macOS x86-64 pylatest_conda_forge_mkl_no_openmp\n```", "path": ".github/workflows/unit-tests.yml", "line": null, "side": "RIGHT", "created_at": "2026-01-13T14:14:48+00:00" }, { "id": 2686755472, "user": "user_fca2535bcd49", "body": "Let revert this change since `arm` is already in the build name and it is already a required check. Changing the name of a required check would cause minor annoyances, see https://github.com/[USER_REDACTED]n/scikit-learn/pull/31832#issuecomment-3116678817 for a similar case where it happens.\n\n```suggestion\n - name: macOS pylatest_conda_forge_arm\n```", "path": ".github/workflows/unit-tests.yml", "line": null, "side": "RIGHT", "created_at": "2026-01-13T14:48:10+00:00" } ], "meta": { "languages": [ "yml" ], "touches_tests": false, "review_state_summary": { "COMMENTED": 6, "APPROVED": 1 }, "meaningful_comment_count": 8, "has_approval": true, "has_changes_requested": false, "total_review_comments": 8 } } { "_id": "b255144bca99d569", "_schema_version": "1.0", "_cleaned_at": "2026-02-12T07:46:51.929244+00:00", "repo": "scikit-learn/scikit-learn", "repo_url": "https://github.com/scikit-learn/scikit-learn", "license_name": "BSD 3-Clause \"New\" or \"Revised\" License", "license_spdx": "BSD-3-Clause", "pr_number": 33064, "title": "CI [NAME_REDACTED] ubuntu_atlas test job from Azure to GHA", "body": "Addresses part of #32434", "author": "user_c91ee6762b06", "created_at": "2026-01-13T10:55:57+00:00", "merged_at": "2026-01-13T14:54:41+00:00", "base_branch": "main", "head_branch": "push-oqlmppkuwszn", "additions": 11, "deletions": 21, "changed_files": 2, "files": [ { "filename": ".github/workflows/unit-tests.yml", "status": "modified", "additions": 11, "deletions": 0, "changes": 11, "patch": "@@ -143,6 +143,16 @@ jobs:\n PYTEST_XDIST_VERSION: none\n PIP_BUILD_ISOLATION: true\n \n+ # Linux environment to test that scikit-learn can be built against\n+ # versions of numpy, scipy with ATLAS that comes with Ubuntu 24.04\n+ # [NAME_REDACTED] i.e. numpy 1.26.4 and scipy 1.11.4\n+ - name: Linux x86-64 ubuntu_atlas\n+ os: ubuntu-24.04\n+ DISTRIB: ubuntu\n+ LOCK_FILE: build_tools/azure/ubuntu_atlas_lock.txt\n+ COVERAGE: false\n+ SKLEARN_TESTS_GLOBAL_RANDOM_SEED: 1 # non-default seed\n+\n - name: macOS pylatest_conda_forge_arm\n os: macOS-15\n DISTRIB: conda\n@@ -167,6 +177,7 @@ jobs:\n \n - name: Set up conda\n uses: conda-incubator/setup-miniconda@v3\n+ if: ${{ startsWith(env.DISTRIB, 'conda') }}\n with:\n miniforge-version: latest\n auto-activate-base: true" }, { "filename": "azure-pipelines.yml", "status": "modified", "additions": 0, "deletions": 21, "changes": 21, "patch": "@@ -138,27 +138,6 @@ jobs:\n COVERAGE: 'false'\n SKLEARN_TESTS_GLOBAL_RANDOM_SEED: '0' # non-default seed\n \n-- template: build_tools/azure/posix.yml\n- parameters:\n- name: Ubuntu_Atlas\n- vmImage: ubuntu-24.04\n- dependsOn: [linting, git_commit, Ubuntu_Jammy_Jellyfish]\n- # Runs when dependencies succeeded or skipped\n- condition: |\n- and(\n- not(or(failed(), canceled())),\n- not(contains(dependencies['git_commit']['outputs']['commit.message'], '[ci skip]'))\n- )\n- matrix:\n- # Linux environment to test that scikit-learn can be built against\n- # versions of numpy, scipy with ATLAS that comes with Ubuntu 24.04 [NAME_REDACTED]\n- # i.e. numpy 1.26.4 and scipy 1.11.4\n- ubuntu_atlas:\n- DISTRIB: 'ubuntu'\n- LOCK_FILE: './build_tools/azure/ubuntu_atlas_lock.txt'\n- COVERAGE: 'false'\n- SKLEARN_TESTS_GLOBAL_RANDOM_SEED: '1' # non-default seed\n-\n - template: build_tools/azure/posix.yml\n parameters:\n name: Linux" } ], "reviews": [ { "id": 3655697987, "user": "user_fca2535bcd49", "state": "APPROVED", "body": "LGTM, thanks!", "submitted_at": "2026-01-13T13:07:50+00:00" }, { "id": 3656022225, "user": "user_fca2535bcd49", "state": "COMMENTED", "body": null, "submitted_at": "2026-01-13T14:12:59+00:00" } ], "review_comments": [ { "id": 2686609411, "user": "user_fca2535bcd49", "body": "Let's put the architecture to be explicit in the build name\n\n```suggestion\n - name: Linux x86-64 ubuntu_atlas\n```", "path": ".github/workflows/unit-tests.yml", "line": null, "side": "RIGHT", "created_at": "2026-01-13T14:12:59+00:00" } ], "meta": { "languages": [ "yml" ], "touches_tests": false, "review_state_summary": { "APPROVED": 1, "COMMENTED": 1 }, "meaningful_comment_count": 1, "has_approval": true, "has_changes_requested": false, "total_review_comments": 1 } } { "_id": "6c7f9dc2636ffbae", "_schema_version": "1.0", "_cleaned_at": "2026-02-12T07:46:51.944975+00:00", "repo": "scikit-learn/scikit-learn", "repo_url": "https://github.com/scikit-learn/scikit-learn", "license_name": "BSD 3-Clause \"New\" or \"Revised\" License", "license_spdx": "BSD-3-Clause", "pr_number": 33063, "title": "CI Move debian-32 build from Azure to GHA", "body": "Addresses part of #32434\n\nPing [USER_REDACTED]", "author": "user_c91ee6762b06", "created_at": "2026-01-13T10:45:29+00:00", "merged_at": "2026-02-06T09:49:51+00:00", "base_branch": "main", "head_branch": "push-wqomplxxvrvv", "additions": 113, "deletions": 202, "changed_files": 3, "files": [ { "filename": ".github/workflows/unit-tests.yml", "status": "modified", "additions": 113, "deletions": 3, "changes": 116, "patch": "@@ -127,7 +127,7 @@ jobs:\n DISTRIB: conda\n LOCK_FILE: build_tools/github/pymin_conda_forge_arm_linux-aarch64_conda.lock\n \n- - name: Linuw x86-64 pylatest_conda_forge_mkl\n+ - name: Linux x86-64 pylatest_conda_forge_mkl\n os: ubuntu-22.04\n DISTRIB: conda\n LOCK_FILE: build_tools/azure/pylatest_conda_forge_mkl_linux-64_conda.lock\n@@ -303,7 +303,8 @@ jobs:\n --job-name \"$JOB_NAME\"\n \n free-threaded:\n- name: &free-threaded-job-name Linux x86-64 pylatest_free_threaded\n+ name: &free-threaded-job-name\n+ Linux x86-64 pylatest_free_threaded\n runs-on: ubuntu-latest\n needs: [lint, retrieve-commit-message, retrieve-selected-tests]\n if: contains(needs.retrieve-commit-message.outputs.message, '[free-threaded]') || github.event_name == 'schedule' || github.event_name == 'workflow_dispatch'\n@@ -318,7 +319,8 @@ jobs:\n steps: *unit-tests-steps\n \n scipy-dev:\n- name: &scipy-dev-job-name Linux x86-64 pylatest_pip_scipy_dev\n+ name: &scipy-dev-job-name\n+ Linux x86-64 pylatest_pip_scipy_dev\n runs-on: ubuntu-22.04\n needs: [lint, retrieve-commit-message, retrieve-selected-tests]\n if: contains(needs.retrieve-commit-message.outputs.message, '[scipy-dev]') || github.event_name == 'schedule' || github.event_name == 'workflow_dispatch'\n@@ -330,3 +332,111 @@ jobs:\n # To be able to access the job name in the steps, it must be set as an env variable.\n JOB_NAME: *scipy-dev-job-name\n steps: *unit-tests-steps\n+\n+ debian-32bit:\n+ name: &debian-32bit-job-name\n+ Linux i386 debian_32bit\n+ runs-on: ubuntu-24.04\n+ needs: [lint, retrieve-commit-message, retrieve-selected-tests]\n+ env:\n+ DISTRIB: debian-32\n+ LOCK_FILE: build_tools/azure/debian_32bit_lock.txt\n+ SKLEARN_TESTS_GLOBAL_RANDOM_SEED: 4 # non-default seed\n+ DOCKER_CONTAINER: i386/debian:trixie\n+ # To be able to access the job name in the steps, it must be set as an env variable.\n+ JOB_NAME: *debian-32bit-job-name\n+ steps:\n+ - name: Checkout\n+ uses: actions/checkout@v6\n+\n+ - name: Create cache for ccache\n+ uses: actions/cache@v5\n+ with:\n+ path: ${{ env.CCACHE_DIR }}\n+ key: ccache-v1-${{ env.JOB_NAME }}-${{ hashFiles('**/*.pyx*', '**/*.pxd*', '**/*.pxi*', '**/*.h', '**/*.c', '**/*.cpp', format('{0}', env.LOCK_FILE)) }}\n+ restore-keys: ccache-${{ env.JOB_NAME }}\n+\n+ - name: Set up conda\n+ uses: conda-incubator/setup-miniconda@v3\n+ if: ${{ startsWith(env.DISTRIB, 'conda') }}\n+ with:\n+ miniforge-version: latest\n+ auto-activate-base: true\n+ activate-environment: \"\"\n+\n+ - name: Set random seed for nightly/manual runs\n+ if: github.event_name == 'schedule' || github.event_name == 'workflow_dispatch'\n+ run: echo \"SKLEARN_TESTS_GLOBAL_RANDOM_SEED=$((RANDOM % 100))\" >> $GITHUB_ENV\n+\n+ - name: Start container\n+ # Environment variable are passed when starting the container rather\n+ # than in \"Run tests step\" for more standard jobs\n+ env:\n+ COMMIT_MESSAGE: ${{ needs.retrieve-commit-message.outputs.message }}\n+ SELECTED_TESTS: ${{ needs.retrieve-selected-tests.outputs.tests }}\n+ COVERAGE: ${{ env.COVERAGE == 'true' && needs.retrieve-selected-tests.outputs.tests == ''}}\n+ run: >\n+ docker container run --rm\n+ --volume $TEST_DIR:/temp_dir\n+ --volume $PWD:/scikit-learn\n+ --volume $CCACHE_DIR:/ccache\n+ -w /scikit-learn\n+ --detach\n+ --name skcontainer\n+ -e TEST_DIR=/temp_dir\n+ -e CCACHE_DIR=/ccache\n+ -e COVERAGE\n+ -e DISTRIB\n+ -e LOCK_FILE\n+ -e JUNITXML\n+ -e VIRTUALENV\n+ -e PYTEST_XDIST_VERSION\n+ -e SKLEARN_SKIP_NETWORK_TESTS\n+ -e SELECTED_TESTS\n+ -e CCACHE_COMPRESS\n+ -e COMMIT_MESSAGE\n+ -e JOB_NAME\n+ -e SKLEARN_TESTS_GLOBAL_RANDOM_SEED\n+ $DOCKER_CONTAINER\n+ sleep 1000000\n+\n+ - name: Build scikit-learn\n+ run: docker exec skcontainer bash -l build_tools/azure/install.sh\n+\n+ - name: Run tests\n+ run: docker exec skcontainer bash -l build_tools/azure/test_script.sh\n+\n+ - name: Run doctests in .py and .rst files\n+ run: docker exec skcontainer bash -l build_tools/azure/test_docs.sh\n+ if: ${{ needs.retrieve-selected-tests.outputs.tests == ''}}\n+\n+ - name: Run pytest soft dependency test\n+ run: docker exec skcontainer build_tools/azure/test_pytest_soft_dependency.sh\n+ if: ${{ env.CHECK_PYTEST_SOFT_DEPENDENCY == 'true' && needs.retrieve-selected-tests.outputs.tests == ''}}\n+\n+ - name: Combine coverage reports from parallel test runners\n+ run: docker exec skcontainer bash -l build_tools/azure/combine_coverage_reports.sh\n+ if: ${{ env.COVERAGE == 'true' && needs.retrieve-selected-tests.outputs.tests == ''}}\n+\n+ - name: Upload coverage report to Codecov\n+ uses: codecov/codecov-action@v5\n+ if: ${{ env.COVERAGE == 'true' && needs.retrieve-selected-tests.outputs.tests == ''}}\n+ with:\n+ files: ./coverage.xml\n+ token: ${{ secrets.CODECOV_TOKEN }}\n+ disable_search: true\n+\n+ - name: Update tracking issue\n+ if: ${{ always() && (github.event_name == 'schedule' || github.event_name == 'workflow_dispatch')}}\n+ run: |\n+ set -ex\n+\n+ pip install defusedxml PyGithub\n+ python maint_tools/update_tracking_issue.py \\\n+ ${{ secrets.BOT_GITHUB_TOKEN }} \\\n+ \"$GITHUB_WORKFLOW $JOB_NAME\" \\\n+ \"$GITHUB_REPOSITORY\" \\\n+ https://github.com/$GITHUB_REPOSITORY/actions/runs/$GITHUB_RUN_ID \\\n+ --junit-file $TEST_DIR/$JUNITXML \\\n+ --auto-close false \\\n+ --job-name \"$JOB_NAME\"" }, { "filename": "azure-pipelines.yml", "status": "removed", "additions": 0, "deletions": 65, "changes": 65, "patch": "@@ -1,65 +0,0 @@\n-# Adapted from https://github.com/[USER_REDACTED]ndas-dev/pandas/blob/master/azure-pipelines.yml\n-schedules:\n-- cron: \"30 2 * * *\"\n- displayName: Run nightly build\n- branches:\n- include:\n- - main\n- always: true\n-\n-jobs:\n-- job: git_commit\n- displayName: [NAME_REDACTED]\n- pool:\n- vmImage: ubuntu-24.04\n- steps:\n- - bash: python build_tools/azure/get_commit_message.py\n- name: commit\n- displayName: Get source version message\n-\n-- job: linting\n- dependsOn: [git_commit]\n- condition: |\n- and(\n- succeeded(),\n- not(contains(dependencies['git_commit']['outputs']['commit.message'], '[lint skip]')),\n- not(contains(dependencies['git_commit']['outputs']['commit.message'], '[ci skip]'))\n- )\n- displayName: Linting\n- pool:\n- vmImage: ubuntu-24.04\n- steps:\n- - task: UsePythonVersion@0\n- inputs:\n- versionSpec: '3.12'\n- - bash: |\n- source build_tools/shared.sh\n- # Include pytest compatibility with mypy\n- pip install pytest $(get_dep ruff min) $(get_dep mypy min) cython-lint\n- displayName: Install linters\n- - bash: |\n- ./build_tools/linting.sh\n- displayName: Run linters\n- - bash: |\n- pip install ninja meson scipy\n- python build_tools/check-meson-openmp-dependencies.py\n- displayName: [NAME_REDACTED] checks\n-\n-- template: build_tools/azure/posix-docker.yml\n- parameters:\n- name: Linux_Docker\n- vmImage: ubuntu-24.04\n- dependsOn: [linting, git_commit]\n- # Runs when dependencies succeeded or skipped\n- condition: |\n- and(\n- not(or(failed(), canceled())),\n- not(contains(dependencies['git_commit']['outputs']['commit.message'], '[ci skip]'))\n- )\n- matrix:\n- debian_32bit:\n- DOCKER_CONTAINER: 'i386/debian:trixie'\n- DISTRIB: 'debian-32'\n- COVERAGE: \"true\"\n- LOCK_FILE: './build_tools/azure/debian_32bit_lock.txt'\n- SKLEARN_TESTS_GLOBAL_RANDOM_SEED: '4' # non-default seed" }, { "filename": "build_tools/azure/posix-docker.yml", "status": "removed", "additions": 0, "deletions": 134, "changes": 134, "patch": "@@ -1,134 +0,0 @@\n-parameters:\n- name: ''\n- vmImage: ''\n- matrix: []\n- dependsOn: []\n- condition: ne(variables['Build.Reason'], 'Schedule')\n-\n-jobs:\n-- job: ${{ parameters.name }}\n- dependsOn: ${{ parameters.dependsOn }}\n- condition: ${{ parameters.condition }}\n- timeoutInMinutes: 120\n- pool:\n- vmImage: ${{ parameters.vmImage }}\n- variables:\n- VIRTUALENV: 'testvenv'\n- TEST_DIR: '$(Agent.WorkFolder)/tmp_folder'\n- JUNITXML: 'test-data.xml'\n- SKLEARN_SKIP_NETWORK_TESTS: '1'\n- PYTEST_XDIST_VERSION: 'latest'\n- COVERAGE: 'false'\n- # Set in azure-pipelines.yml\n- DISTRIB: ''\n- DOCKER_CONTAINER: ''\n- CREATE_ISSUE_ON_TRACKER: 'true'\n- CCACHE_DIR: $(Pipeline.Workspace)/ccache\n- CCACHE_COMPRESS: '1'\n- strategy:\n- matrix:\n- ${{ insert }}: ${{ parameters.matrix }}\n-\n- steps:\n- - task: UsePythonVersion@0\n- inputs:\n- versionSpec: '3.9'\n- addToPath: false\n- name: pyTools\n- displayName: Select python version to run CI python scripts\n- - bash: $(pyTools.pythonLocation)/bin/python build_tools/azure/get_selected_tests.py\n- displayName: Check selected tests for all random seeds\n- condition: eq(variables['Build.Reason'], 'PullRequest')\n- - task: Cache@2\n- inputs:\n- key: '\"ccache-v1\" | \"$(Agent.JobName)\" | \"$(Build.BuildNumber)\"'\n- restoreKeys: |\n- \"ccache-v1\" | \"$(Agent.JobName)\"\n- path: $(CCACHE_DIR)\n- displayName: ccache\n- continueOnError: true\n- - script: >\n- mkdir -p $CCACHE_DIR\n- # Container is detached and sleeping, allowing steps to run commands\n- # in the container. The TEST_DIR is mapped allowing the host to access\n- # the JUNITXML file\n- - script: >\n- docker container run --rm\n- --volume $TEST_DIR:/temp_dir\n- --volume $BUILD_REPOSITORY_LOCALPATH:/repo_localpath\n- --volume $PWD:/scikit-learn\n- --volume $CCACHE_DIR:/ccache\n- -w /scikit-learn\n- --detach\n- --name skcontainer\n- -e BUILD_SOURCESDIRECTORY=/scikit-learn\n- -e TEST_DIR=/temp_dir\n- -e CCACHE_DIR=/ccache\n- -e BUILD_REPOSITORY_LOCALPATH=/repo_localpath\n- -e COVERAGE\n- -e DISTRIB\n- -e LOCK_FILE\n- -e JUNITXML\n- -e VIRTUALENV\n- -e PYTEST_XDIST_VERSION\n- -e SKLEARN_SKIP_NETWORK_TESTS\n- -e SELECTED_TESTS\n- -e CCACHE_COMPRESS\n- -e BUILD_SOURCEVERSIONMESSAGE\n- -e BUILD_REASON\n- $DOCKER_CONTAINER\n- sleep 1000000\n- displayName: 'Start container'\n- - script: >\n- docker exec skcontainer ./build_tools/azure/install.sh\n- displayName: 'Install'\n- - script: >\n- docker exec skcontainer ./build_tools/azure/test_script.sh\n- displayName: 'Test Library'\n- - script: >\n- docker exec skcontainer ./build_tools/azure/combine_coverage_reports.sh\n- condition: and(succeeded(), eq(variables['COVERAGE'], 'true'),\n- eq(variables['SELECTED_TESTS'], ''))\n- displayName: 'Combine coverage'\n- - task: PublishTestResults@2\n- inputs:\n- testResultsFiles: '$(TEST_DIR)/$(JUNITXML)'\n- testRunTitle: ${{ format('{0}-$(Agent.JobName)', parameters.name) }}\n- displayName: '[NAME_REDACTED]'\n- condition: succeededOrFailed()\n- - script: >\n- docker container stop skcontainer\n- displayName: 'Stop container'\n- condition: always()\n- - bash: |\n- set -ex\n- if [[ $(BOT_GITHUB_TOKEN) == \"\" ]]; then\n- echo \"[NAME_REDACTED] is not set. Issue tracker will not be updated.\"\n- exit\n- fi\n-\n- LINK_TO_RUN=\"https://dev.azure.com/$BUILD_REPOSITORY_NAME/_build/results?buildId=$BUILD_BUILDID&view=logs&j=$SYSTEM_JOBID\"\n- CI_NAME=\"$SYSTEM_JOBIDENTIFIER\"\n- ISSUE_REPO=\"$BUILD_REPOSITORY_NAME\"\n-\n- $(pyTools.pythonLocation)/bin/pip install defusedxml PyGithub\n- $(pyTools.pythonLocation)/bin/python maint_tools/update_tracking_issue.py \\\n- $(BOT_GITHUB_TOKEN) \\\n- $CI_NAME \\\n- $ISSUE_REPO \\\n- $LINK_TO_RUN \\\n- --junit-file $JUNIT_FILE \\\n- --auto-close false\n- displayName: 'Update issue tracker'\n- env:\n- JUNIT_FILE: $(TEST_DIR)/$(JUNITXML)\n- condition: and(succeededOrFailed(), eq(variables['CREATE_ISSUE_ON_TRACKER'], 'true'),\n- eq(variables['Build.Reason'], 'Schedule'))\n- - bash: bash build_tools/azure/upload_codecov.sh\n- condition: and(succeeded(), eq(variables['COVERAGE'], 'true'),\n- eq(variables['SELECTED_TESTS'], ''))\n- displayName: '[NAME_REDACTED]'\n- retryCountOnTaskFailure: 5\n- env:\n- CODECOV_TOKEN: $(CODECOV_TOKEN)\n- JUNIT_FILE: $(TEST_DIR)/$(JUNITXML)" } ], "reviews": [ { "id": 3746694794, "user": "user_fca2535bcd49", "state": "COMMENTED", "body": null, "submitted_at": "2026-02-03T17:50:20+00:00" }, { "id": 3754392183, "user": "user_04b4a5f4e2a8", "state": "COMMENTED", "body": null, "submitted_at": "2026-02-05T04:14:49+00:00" }, { "id": 3754619491, "user": "user_fca2535bcd49", "state": "COMMENTED", "body": null, "submitted_at": "2026-02-05T05:05:29+00:00" }, { "id": 3759720196, "user": "user_04b4a5f4e2a8", "state": "COMMENTED", "body": null, "submitted_at": "2026-02-05T22:09:48+00:00" }, { "id": 3760862392, "user": "user_fca2535bcd49", "state": "COMMENTED", "body": null, "submitted_at": "2026-02-06T05:23:53+00:00" }, { "id": 3761671712, "user": "user_fca2535bcd49", "state": "APPROVED", "body": "I think this is good to go.\n\nWe can tweak it later if/when we notice possible improvements.", "submitted_at": "2026-02-06T09:03:16+00:00" } ], "review_comments": [ { "id": 2760278199, "user": "user_fca2535bcd49", "body": "This won't work since it sets the env variable in the host rather than the docker container.", "path": ".github/workflows/unit-tests.yml", "line": null, "side": "RIGHT", "created_at": "2026-02-03T17:50:21+00:00" }, { "id": 2766973472, "user": "user_04b4a5f4e2a8", "body": "I have not tried it on GHA before, but can we run the steps directly in a container with these instructions? https://docs.github.com/en/actions/how-tos/write-workflows/choose-where-workflows-run/run-jobs-in-a-container", "path": ".github/workflows/unit-tests.yml", "line": 345, "side": "RIGHT", "created_at": "2026-02-05T04:14:43+00:00" }, { "id": 2767165255, "user": "user_fca2535bcd49", "body": "We kind of did a half-hearted attempt in this direction. The first issue is you don't have nodejs in the container. You could `apt-get install nodejs` but you would have an old nodejs so `actions/checkout@v6` does not work, IIRC looking at the version `actions/checkout@v4` might work.\n\nBasically I was like, OK this seems more painful that I would have liked, let's do the same setup as Azure and revisit later.\n\nMore than happy to have someone else try a bit harder along the GHA docker support to see whether it's worth doing or not but honestly I would merge this PR first and do it in a follow-up PR.", "path": ".github/workflows/unit-tests.yml", "line": 345, "side": "RIGHT", "created_at": "2026-02-05T05:05:29+00:00" }, { "id": 2771369329, "user": "user_04b4a5f4e2a8", "body": "Ah, I see, needing nodejs is kind of a pain. In any case, I'm okay with the PR as is.", "path": ".github/workflows/unit-tests.yml", "line": 345, "side": "RIGHT", "created_at": "2026-02-05T22:09:47+00:00" }, { "id": 2772348998, "user": "user_fca2535bcd49", "body": "Thanks for your insights [USER_REDACTED], super happy to see you pop occasionally on the repo :pray:", "path": ".github/workflows/unit-tests.yml", "line": 345, "side": "RIGHT", "created_at": "2026-02-06T05:23:53+00:00" } ], "meta": { "languages": [ "yml" ], "touches_tests": false, "review_state_summary": { "COMMENTED": 5, "APPROVED": 1 }, "meaningful_comment_count": 5, "has_approval": true, "has_changes_requested": false, "total_review_comments": 5 } } { "_id": "cdc9a7c76a1d0757", "_schema_version": "1.0", "_cleaned_at": "2026-02-12T07:46:51.944975+00:00", "repo": "scikit-learn/scikit-learn", "repo_url": "https://github.com/scikit-learn/scikit-learn", "license_name": "BSD 3-Clause \"New\" or \"Revised\" License", "license_spdx": "BSD-3-Clause", "pr_number": 33039, "title": "FIX: fix deprecation of \"friedman_mse\" criterion in forests", "body": "Fixing my own mess :sweat_smile: \n\n#### [NAME_REDACTED]/PRs\n\nRelated to issue #32700.\n\nFollow-up from PR #32708: While writing the PR #32708, I didn't anticipated that tree-related parameters will be validated before being passed down to trees (and it's where the deprecation warning is raised, and where the value of the criterion is modified from \"friedman_mse\" to \"squared_error\").\n\n#### What does this implement/fix? Explain your changes.\n\nThe bug is explained above.\n\nThe proposed fix: copy the warning & criterion-value-rewrite in `RandomForestRegressor` and `ExtraTreesRegressor`. I think it's fine to repeat this small piece of code, it will not live too long in the code base.\n\n#### AI usage: no\n\n#### TODO?\n\nMore tests?", "author": "user_566c02088fba", "created_at": "2026-01-10T17:47:13+00:00", "merged_at": "2026-01-15T22:29:03+00:00", "base_branch": "main", "head_branch": "fix/broken_deprecation_fmse", "additions": 32, "deletions": 1, "changed_files": 2, "files": [ { "filename": "sklearn/ensemble/_forest.py", "status": "modified", "additions": 20, "deletions": 0, "changes": 20, "patch": "@@ -1928,6 +1928,16 @@ def __init__(\n max_samples=max_samples,\n )\n \n+ if isinstance(criterion, str) and criterion == \"friedman_mse\":\n+ # TODO(1.11): remove support of \"friedman_mse\" criterion.\n+ criterion = \"squared_error\"\n+ warn(\n+ 'Value `\"friedman_mse\"` for `criterion` is deprecated and will be '\n+ 'removed in 1.11. It maps to `\"squared_error\"` as both '\n+ 'were always equivalent. Use `criterion=\"squared_error\"` '\n+ \"to remove this warning.\",\n+ FutureWarning,\n+ )\n self.criterion = criterion\n self.max_depth = max_depth\n self.min_samples_split = min_samples_split\n@@ -2662,6 +2672,16 @@ def __init__(\n max_samples=max_samples,\n )\n \n+ if isinstance(criterion, str) and criterion == \"friedman_mse\":\n+ # TODO(1.11): remove support of \"friedman_mse\" criterion.\n+ criterion = \"squared_error\"\n+ warn(\n+ 'Value `\"friedman_mse\"` for `criterion` is deprecated and will be '\n+ 'removed in 1.11. It maps to `\"squared_error\"` as both '\n+ 'were always equivalent. Use `criterion=\"squared_error\"` '\n+ \"to remove this warning.\",\n+ FutureWarning,\n+ )\n self.criterion = criterion\n self.max_depth = max_depth\n self.min_samples_split = min_samples_split" }, { "filename": "sklearn/ensemble/tests/test_forest.py", "status": "modified", "additions": 12, "deletions": 1, "changes": 13, "patch": "@@ -157,8 +157,12 @@ def test_iris_criterion(name, criterion):\n assert score > 0.5, \"Failed with criterion %s and score = %f\" % (criterion, score)\n \n \n+# TODO(1.11): remove the deprecated friedman_mse criterion parametrization\n+[USER_REDACTED].mark.filterwarnings(\"ignore:.*friedman_mse.*:FutureWarning\")\n [USER_REDACTED].mark.parametrize(\"name\", FOREST_REGRESSORS)\n-[USER_REDACTED].mark.parametrize(\"criterion\", (\"squared_error\", \"absolute_error\"))\n+[USER_REDACTED].mark.parametrize(\n+ \"criterion\", (\"squared_error\", \"friedman_mse\", \"absolute_error\")\n+)\n def test_regression_criterion(name, criterion):\n # Check consistency on regression dataset.\n ForestRegressor = FOREST_REGRESSORS[name]\n@@ -1864,3 +1868,10 @@ def test_non_supported_criterion_raises_error_with_missing_values(Forest):\n msg = \".*does not accept missing values\"\n with pytest.raises(ValueError, match=msg):\n forest.fit(X, y)\n+\n+\n+# TODO(1.11): remove test with the deprecation of friedman_mse criterion\n+[USER_REDACTED].mark.parametrize(\"Forest\", FOREST_REGRESSORS.values())\n+def test_friedman_mse_deprecation(Forest):\n+ with pytest.warns(FutureWarning, match=\"friedman_mse\"):\n+ _ = Forest(criterion=\"friedman_mse\")" } ], "reviews": [ { "id": 3654980115, "user": "user_5819d17296ee", "state": "APPROVED", "body": null, "submitted_at": "2026-01-13T10:07:44+00:00" }, { "id": 3667396243, "user": "user_22bafe4fe1a9", "state": "APPROVED", "body": null, "submitted_at": "2026-01-15T20:14:26+00:00" } ], "review_comments": [ { "id": 2695811550, "user": "user_22bafe4fe1a9", "body": "```suggestion\n\n# TODO(1.11): remove test with the deprecation of friedman_mse criterion\n[USER_REDACTED].mark.parametrize(\"Forest\", FOREST_REGRESSORS.values())\n```", "path": "sklearn/ensemble/tests/test_forest.py", "line": 1874, "side": "RIGHT", "created_at": "2026-01-15T20:14:07+00:00" } ], "meta": { "languages": [ "py" ], "touches_tests": true, "review_state_summary": { "APPROVED": 2 }, "meaningful_comment_count": 1, "has_approval": true, "has_changes_requested": false, "total_review_comments": 1 } } { "_id": "779e92dea730fb19", "_schema_version": "1.0", "_cleaned_at": "2026-02-12T07:46:51.944975+00:00", "repo": "scikit-learn/scikit-learn", "repo_url": "https://github.com/scikit-learn/scikit-learn", "license_name": "BSD 3-Clause \"New\" or \"Revised\" License", "license_spdx": "BSD-3-Clause", "pr_number": 33015, "title": "FIX `predict` to also use `multiclass_colors` in DecisionBoundaryDisplay", "body": "\n\n#### [NAME_REDACTED]/PRs\n\nFixes #32872 ~and the `predict` part of #32866~\n\n#### What does this implement/fix? Explain your changes.\nPreviously, the case distinction for binary vs. multiclass was made based on the response dimension (see #32918 for reference), which led to multiclass `predict` ignoring the `multiclass_colors` parameter. \nThe colors are now selected based on the `n_classes` display class variable, which is extracted in `from_estimator`.\n\nNote that a distinction based on the response shape still has to be made for plotting. ~in two cases (`contour` and `pcolormesh`). I'm not sure if there is a more elegant solution, but I didn't find a way to handle `pcolormesh` in the same way for `predict` as in the other cases.~\n\nI adapted the docstrings and the exmple and added the response functions to the tests (and adapted them accordingly).\n\nEDIT: The output of the code in issue #32872 now looks like this (Note that the levels problem from #32866 is still there for `predict`, but this PR is only concerned with making it use the same color map as the other methods, which it does now):\n\"image\"\n\n~Since every class is plotted separately now (as it was already for response method `predict_proba` and `decision_function`), this also fixes the `levels` issue noted in #32866. However, there are white lines between the classes for `predict` with `countourf`. If this is a problem (and using pcolormesh is not an option for any reason), the current approach will need to be adapted further.~\n\n#### AI usage disclosure\n\nI used AI assistance for:\n- [x] Code generation (e.g., when writing an implementation or fixing a bug)\n- [ ] Test/benchmark generation\n- [ ] Documentation (including examples)\n- [x] Research and understanding\n\n#### Any other comments?\nI also added a test for the default value for `multiclass_colors`, which was missing.\n\n", "author": "user_34a090906ca4", "created_at": "2026-01-06T14:55:00+00:00", "merged_at": "2026-02-02T09:35:15+00:00", "base_branch": "main", "head_branch": "multiclass_colors_DecisionBoundaryDisplay", "additions": 199, "deletions": 59, "changed_files": 3, "files": [ { "filename": "doc/whats_new/upcoming_changes/sklearn.inspection/33015.fix.rst", "status": "added", "additions": 3, "deletions": 0, "changes": 3, "patch": "@@ -0,0 +1,3 @@\n+- In :class:`inspection.DecisionBoundaryDisplay`, `multiclass_colors` is now also used\n+ for multiclass plotting when `response_method=\"predict\"`.\n+ By :user:`[NAME_REDACTED] `." }, { "filename": "sklearn/inspection/_plot/decision_boundary.py", "status": "modified", "additions": 112, "deletions": 47, "changes": 159, "patch": "@@ -5,7 +5,7 @@\n \n import numpy as np\n \n-from sklearn.base import is_regressor\n+from sklearn.base import is_classifier, is_clusterer, is_outlier_detector, is_regressor\n from sklearn.preprocessing import LabelEncoder\n from sklearn.utils import _safe_indexing\n from sklearn.utils._dataframe import is_pandas_df, is_polars_df\n@@ -83,27 +83,46 @@ class DecisionBoundaryDisplay:\n xx1 : ndarray of shape (grid_resolution, grid_resolution)\n Second output of :func:`meshgrid `.\n \n+ n_classes : int\n+ Expected number of unique classes or labels if `response` was generated by a\n+ :term:`classifier` or a :term:`clusterer`.\n+\n+ For :term:`outlier detectors`, `n_classes` should be set to 2 by definition\n+ (inlier or outlier).\n+\n+ For :term:`regressors`, `n_classes` should also be set to 2 by convention\n+ (continuous responses are displayed the same way as unthresholded binary\n+ responses).\n+\n+ .. versionadded:: 1.9\n+\n response : ndarray of shape (grid_resolution, grid_resolution) or \\\n (grid_resolution, grid_resolution, n_classes)\n Values of the response function.\n \n multiclass_colors : list of str or str, default=None\n- Specifies how to color each class when plotting all classes of multiclass\n- problem. Ignored for binary problems and multiclass problems when plotting a\n- single prediction value per point.\n+ Specifies how to color each class when plotting all classes of\n+ :term:`multiclass` problems.\n+\n Possible inputs are:\n \n * list: list of Matplotlib\n `color `_\n strings, of length `n_classes`\n * str: name of :class:`matplotlib.colors.Colormap`\n- * None: 'viridis' colormap is used to sample colors\n+ * None: 'tab10' colormap is used to sample colors if the number of\n+ classes is less than or equal to 10, otherwise 'gist_rainbow' colormap.\n+\n+ Single color (fading to white) colormaps will be generated from the colors in\n+ the list or colors taken from the colormap, and passed to the `cmap` parameter\n+ of the `plot_method`.\n \n- Single color colormaps will be generated from the colors in the list or\n- colors taken from the colormap and passed to the `cmap` parameter of\n- the `plot_method`.\n+ For :term:`binary` problems, this is ignored and `cmap` or `colors` can be\n+ passed as kwargs instead, otherwise, the default colormap ('viridis') is used.\n \n .. versionadded:: 1.7\n+ .. versionchanged:: 1.9\n+ `multiclass_colors` is now also used when `response_method=\"predict\"`\n \n xlabel : str, default=None\n Default label to place on x axis.\n@@ -121,7 +140,7 @@ class DecisionBoundaryDisplay:\n \n multiclass_colors_ : array of shape (n_classes, 4)\n Colors used to plot each class in multiclass problems.\n- Only defined when `color_of_interest` is None.\n+ Only defined when `n_classes` > 2.\n \n .. versionadded:: 1.7\n \n@@ -137,6 +156,7 @@ class DecisionBoundaryDisplay:\n \n Examples\n --------\n+ >>> import matplotlib as mpl\n >>> import matplotlib.pyplot as plt\n >>> import numpy as np\n >>> from sklearn.datasets import load_iris\n@@ -151,22 +171,35 @@ class DecisionBoundaryDisplay:\n >>> tree = DecisionTreeClassifier().fit(iris.data[:, :2], iris.target)\n >>> y_pred = np.reshape(tree.predict(grid), feature_1.shape)\n >>> display = DecisionBoundaryDisplay(\n- ... xx0=feature_1, xx1=feature_2, response=y_pred\n+ ... xx0=feature_1, xx1=feature_2, n_classes=len(tree.classes_), response=y_pred\n ... )\n >>> display.plot()\n <...>\n >>> display.ax_.scatter(\n- ... iris.data[:, 0], iris.data[:, 1], c=iris.target, edgecolor=\"black\"\n+ ... iris.data[:, 0],\n+ ... iris.data[:, 1],\n+ ... c=iris.target,\n+ ... cmap=mpl.colors.ListedColormap(display.multiclass_colors_),\n+ ... edgecolor=\"black\"\n ... )\n <...>\n >>> plt.show()\n \"\"\"\n \n def __init__(\n- self, *, xx0, xx1, response, multiclass_colors=None, xlabel=None, ylabel=None\n+ self,\n+ *,\n+ xx0,\n+ xx1,\n+ n_classes,\n+ response,\n+ multiclass_colors=None,\n+ xlabel=None,\n+ ylabel=None,\n ):\n self.xx0 = xx0\n self.xx1 = xx1\n+ self.n_classes = n_classes\n self.response = response\n self.multiclass_colors = multiclass_colors\n self.xlabel = xlabel\n@@ -195,7 +228,9 @@ def plot(self, plot_method=\"contourf\", ax=None, xlabel=None, ylabel=None, **kwar\n Overwrite the y-axis label.\n \n **kwargs : dict\n- Additional keyword arguments to be passed to the `plot_method`.\n+ Additional keyword arguments to be passed to the `plot_method`. For\n+ :term:`binary` problems, `cmap` or `colors` can be set here to specify the\n+ colormap or colors, otherwise the default colormap ('viridis') is used.\n \n Returns\n -------\n@@ -216,39 +251,37 @@ def plot(self, plot_method=\"contourf\", ax=None, xlabel=None, ylabel=None, **kwar\n _, ax = plt.subplots()\n \n plot_func = getattr(ax, plot_method)\n- if self.response.ndim == 2:\n+ if self.n_classes == 2:\n self.surface_ = plot_func(self.xx0, self.xx1, self.response, **kwargs)\n- else: # self.response.ndim == 3\n- n_responses = self.response.shape[-1]\n+ else: # multiclass\n for kwarg in (\"cmap\", \"colors\"):\n if kwarg in kwargs:\n warnings.warn(\n f\"'{kwarg}' is ignored in favor of 'multiclass_colors' \"\n- \"in the multiclass case when the response method is \"\n- \"'decision_function' or 'predict_proba'.\"\n+ \"in the multiclass case.\"\n )\n del kwargs[kwarg]\n \n if self.multiclass_colors is None or isinstance(\n self.multiclass_colors, str\n ):\n if self.multiclass_colors is None:\n- cmap = \"tab10\" if n_responses <= 10 else \"gist_rainbow\"\n+ cmap = \"tab10\" if self.n_classes <= 10 else \"gist_rainbow\"\n else:\n cmap = self.multiclass_colors\n \n # Special case for the tab10 and tab20 colormaps that encode a\n # discrete set of colors that are easily distinguishable\n # contrary to other colormaps that are continuous.\n- if cmap == \"tab10\" and n_responses <= 10:\n- colors = plt.get_cmap(\"tab10\", 10).colors[:n_responses]\n- elif cmap == \"tab20\" and n_responses <= 20:\n- colors = plt.get_cmap(\"tab20\", 20).colors[:n_responses]\n+ if cmap == \"tab10\" and self.n_classes <= 10:\n+ colors = plt.get_cmap(\"tab10\", 10).colors[: self.n_classes]\n+ elif cmap == \"tab20\" and self.n_classes <= 20:\n+ colors = plt.get_cmap(\"tab20\", 20).colors[: self.n_classes]\n else:\n- cmap = plt.get_cmap(cmap, n_responses)\n+ cmap = plt.get_cmap(cmap, self.n_classes)\n if not hasattr(cmap, \"colors\"):\n- # For LinearSegmentedColormap\n- colors = cmap(np.linspace(0, 1, n_responses))\n+ # Get `LinearSegmentedColormap` for non-qualitative cmaps\n+ colors = cmap(np.linspace(0, 1, self.n_classes))\n else:\n colors = cmap.colors\n elif isinstance(self.multiclass_colors, list):\n@@ -257,25 +290,37 @@ def plot(self, plot_method=\"contourf\", ax=None, xlabel=None, ylabel=None, **kwar\n raise ValueError(\"'multiclass_colors' must be a list or a str.\")\n \n self.multiclass_colors_ = colors\n- if plot_method == \"contour\":\n- # Plot only argmax map for contour\n- class_map = self.response.argmax(axis=2)\n+\n+ if self.response.ndim == 2: # predict\n+ # `pcolormesh` requires cmap, for the others it makes no difference\n+ cmap = mpl.colors.ListedColormap(colors)\n self.surface_ = plot_func(\n- self.xx0, self.xx1, class_map, colors=colors, **kwargs\n+ self.xx0, self.xx1, self.response, cmap=cmap, **kwargs\n+ )\n+\n+ # predict_proba and decision_function differ for plotting methods\n+ elif plot_method == \"contour\":\n+ # Plot only integer class values\n+ self.surface_ = plot_func(\n+ self.xx0,\n+ self.xx1,\n+ self.response.argmax(axis=2),\n+ colors=colors,\n+ **kwargs,\n )\n else:\n multiclass_cmaps = [\n mpl.colors.LinearSegmentedColormap.from_list(\n- f\"colormap_{class_idx}\", [(1.0, 1.0, 1.0, 1.0), (r, g, b, 1.0)]\n+ f\"colormap_{class_idx}\",\n+ [(1.0, 1.0, 1.0, 1.0), (r, g, b, 1.0)],\n )\n for class_idx, (r, g, b, _) in enumerate(colors)\n ]\n-\n self.surface_ = []\n for class_idx, cmap in enumerate(multiclass_cmaps):\n response = np.ma.array(\n self.response[:, :, class_idx],\n- mask=~(self.response.argmax(axis=2) == class_idx),\n+ mask=(self.response.argmax(axis=2) != class_idx),\n )\n self.surface_.append(\n plot_func(self.xx0, self.xx1, response, cmap=cmap, **kwargs)\n@@ -348,20 +393,19 @@ def from_estimator(\n For multiclass problems, 'auto' no longer defaults to 'predict'.\n \n class_of_interest : int, float, bool or str, default=None\n- The class to be plotted when `response_method` is 'predict_proba'\n- or 'decision_function'. If None, `estimator.classes_[1]` is considered\n- the positive class for binary classifiers. For multiclass\n- classifiers, if None, all classes will be represented in the\n- decision boundary plot; the class with the highest response value\n+ The class to be plotted. For :term:`binary` classifiers, if None,\n+ `estimator.classes_[1]` is considered the positive class. For\n+ :term:`multiclass` classifiers, if None, all classes will be represented in\n+ the decision boundary plot; when `response_method` is :term:`predict_proba`\n+ or :term:`decision_function`, the class with the highest response value\n at each point is plotted. The color of each class can be set via\n `multiclass_colors`.\n \n .. versionadded:: 1.4\n \n multiclass_colors : list of str, or str, default=None\n- Specifies how to color each class when plotting multiclass\n- 'predict_proba' or 'decision_function' and `class_of_interest` is\n- None. Ignored in all other cases.\n+ Specifies how to color each class when plotting :term:`multiclass` problems\n+ and `class_of_interest` is None.\n \n Possible inputs are:\n \n@@ -373,11 +417,17 @@ def from_estimator(\n classes is less than or equal to 10, otherwise 'gist_rainbow'\n colormap.\n \n- Single color colormaps will be generated from the colors in the list or\n- colors taken from the colormap, and passed to the `cmap` parameter of\n- the `plot_method`.\n+ Single color (fading to white) colormaps will be generated from the colors\n+ in the list or colors taken from the colormap, and passed to the `cmap`\n+ parameter of the `plot_method`.\n+\n+ For :term:`binary` problems, this is ignored and `cmap` or `colors` can be\n+ passed as kwargs instead, otherwise, the default colormap ('viridis') is\n+ used.\n \n .. versionadded:: 1.7\n+ .. versionchanged:: 1.9\n+ `multiclass_colors` is now also used when `response_method=\"predict\"`\n \n xlabel : str, default=None\n The label used for the x-axis. If `None`, an attempt is made to\n@@ -394,8 +444,7 @@ def from_estimator(\n created.\n \n **kwargs : dict\n- Additional keyword arguments to be passed to the\n- `plot_method`.\n+ Additional keyword arguments to be passed to the `plot_method`.\n \n Returns\n -------\n@@ -412,6 +461,7 @@ def from_estimator(\n \n Examples\n --------\n+ >>> import matplotlib as mpl\n >>> import matplotlib.pyplot as plt\n >>> from sklearn.datasets import load_iris\n >>> from sklearn.linear_model import LogisticRegression\n@@ -424,7 +474,8 @@ def from_estimator(\n ... xlabel=iris.feature_names[0], ylabel=iris.feature_names[1],\n ... alpha=0.5,\n ... )\n- >>> disp.ax_.scatter(X[:, 0], X[:, 1], c=iris.target, edgecolor=\"k\")\n+ >>> cmap = mpl.colors.ListedColormap(disp.multiclass_colors_)\n+ >>> disp.ax_.scatter(X[:, 0], X[:, 1], c=iris.target, edgecolor=\"k\", cmap=cmap)\n <...>\n >>> plt.show()\n \"\"\"\n@@ -520,6 +571,8 @@ def from_estimator(\n # to our user when interacting with\n # `DecisionBoundaryDisplay.from_estimator`\n raise ValueError(\n+ # Note: it is ok to use estimator.classes_ here, as this error will\n+ # only be thrown if estimator is a classifier\n f\"class_of_interest={class_of_interest} is not a valid label: It \"\n f\"should be one of {estimator.classes_}\"\n ) from exc\n@@ -546,6 +599,17 @@ def from_estimator(\n else:\n response = response.reshape(*xx0.shape, response.shape[-1])\n \n+ if (\n+ class_of_interest is not None\n+ or is_regressor(estimator)\n+ or is_outlier_detector(estimator)\n+ ):\n+ n_classes = 2\n+ elif is_classifier(estimator):\n+ n_classes = len(estimator.classes_)\n+ elif is_clusterer(estimator):\n+ n_classes = len(np.unique(estimator.labels_))\n+\n if xlabel is None:\n xlabel = X.columns[0] if hasattr(X, \"columns\") else \"\"\n \n@@ -555,6 +619,7 @@ def from_estimator(\n display = cls(\n xx0=xx0,\n xx1=xx1,\n+ n_classes=n_classes,\n response=response,\n multiclass_colors=multiclass_colors,\n xlabel=xlabel," }, { "filename": "sklearn/inspection/_plot/tests/test_boundary_decision_display.py", "status": "modified", "additions": 84, "deletions": 12, "changes": 96, "patch": "@@ -3,10 +3,15 @@\n import numpy as np\n import pytest\n \n-from sklearn.base import BaseEstimator, ClassifierMixin\n+from sklearn.base import (\n+ BaseEstimator,\n+ ClassifierMixin,\n+)\n+from sklearn.cluster import KMeans\n from sklearn.datasets import (\n load_diabetes,\n load_iris,\n+ make_blobs,\n make_classification,\n make_multilabel_classification,\n )\n@@ -239,7 +244,7 @@ def test_decision_boundary_display_classifier(\n \n \n [USER_REDACTED].mark.parametrize(\"response_method\", [\"auto\", \"predict\", \"decision_function\"])\n-[USER_REDACTED].mark.parametrize(\"plot_method\", [\"contourf\", \"contour\"])\n+[USER_REDACTED].mark.parametrize(\"plot_method\", [\"contourf\", \"contour\", \"pcolormesh\"])\n def test_decision_boundary_display_outlier_detector(\n pyplot, response_method, plot_method\n ):\n@@ -256,7 +261,10 @@ def test_decision_boundary_display_outlier_detector(\n eps=eps,\n ax=ax,\n )\n- assert isinstance(disp.surface_, pyplot.matplotlib.contour.QuadContourSet)\n+ if plot_method == \"pcolormesh\":\n+ assert isinstance(disp.surface_, pyplot.matplotlib.collections.QuadMesh)\n+ else:\n+ assert isinstance(disp.surface_, pyplot.matplotlib.contour.QuadContourSet)\n assert disp.ax_ == ax\n assert disp.figure_ == fig\n \n@@ -288,7 +296,12 @@ def test_decision_boundary_display_regressor(pyplot, response_method, plot_metho\n eps=eps,\n plot_method=plot_method,\n )\n- assert isinstance(disp.surface_, pyplot.matplotlib.contour.QuadContourSet)\n+ if disp.n_classes == 2 or plot_method == \"contour\":\n+ assert isinstance(disp.surface_, pyplot.matplotlib.contour.QuadContourSet)\n+ else:\n+ assert isinstance(disp.surface_, list)\n+ for surface in disp.surface_:\n+ assert isinstance(surface, pyplot.matplotlib.contour.QuadContourSet)\n assert disp.ax_ == ax\n assert disp.figure_ == fig\n \n@@ -618,15 +631,26 @@ def test_multiclass_plot_max_class(pyplot, response_method):\n \n \n [USER_REDACTED].mark.parametrize(\n- \"multiclass_colors\",\n+ \"multiclass_colors, n_classes\",\n [\n- \"plasma\",\n- \"Blues\",\n- [\"red\", \"green\", \"blue\"],\n+ (None, 3),\n+ (None, 11),\n+ (\"plasma\", 3),\n+ (\"Blues\", 3),\n+ ([\"red\", \"green\", \"blue\"], 3),\n ],\n )\n+[USER_REDACTED].mark.parametrize(\n+ \"response_method\", [\"decision_function\", \"predict_proba\", \"predict\"]\n+)\n [USER_REDACTED].mark.parametrize(\"plot_method\", [\"contourf\", \"contour\", \"pcolormesh\"])\n-def test_multiclass_colors_cmap(pyplot, plot_method, multiclass_colors):\n+def test_multiclass_colors_cmap(\n+ pyplot,\n+ n_classes,\n+ response_method,\n+ plot_method,\n+ multiclass_colors,\n+):\n \"\"\"Check correct cmap used for all `multiclass_colors` inputs.\"\"\"\n import matplotlib as mpl\n \n@@ -635,36 +659,84 @@ def test_multiclass_colors_cmap(pyplot, plot_method, multiclass_colors):\n \"Matplotlib >= 3.5 is needed for `==` to check equivalence of colormaps\"\n )\n \n- X, y = load_iris_2d_scaled()\n+ X, y = make_blobs(n_samples=150, centers=n_classes, n_features=2, random_state=42)\n clf = LogisticRegression().fit(X, y)\n \n disp = DecisionBoundaryDisplay.from_estimator(\n clf,\n X,\n+ response_method=response_method,\n plot_method=plot_method,\n multiclass_colors=multiclass_colors,\n )\n \n- if multiclass_colors == \"plasma\":\n+ if multiclass_colors is None:\n+ if len(clf.classes_) <= 10:\n+ colors = mpl.pyplot.get_cmap(\"tab10\", 10).colors[: len(clf.classes_)]\n+ else:\n+ cmap = mpl.pyplot.get_cmap(\"gist_rainbow\", len(clf.classes_))\n+ colors = cmap(np.linspace(0, 1, len(clf.classes_)))\n+ elif multiclass_colors == \"plasma\":\n colors = mpl.pyplot.get_cmap(multiclass_colors, len(clf.classes_)).colors\n elif multiclass_colors == \"Blues\":\n cmap = mpl.pyplot.get_cmap(multiclass_colors, len(clf.classes_))\n colors = cmap(np.linspace(0, 1, len(clf.classes_)))\n else:\n colors = [mpl.colors.to_rgba(color) for color in multiclass_colors]\n \n- if plot_method != \"contour\":\n+ # Make sure the colormap has enough distinct colors.\n+ assert disp.n_classes == len(np.unique(colors, axis=0))\n+\n+ if response_method == \"predict\":\n+ cmap = mpl.colors.ListedColormap(colors)\n+ assert disp.surface_.cmap == cmap\n+ elif plot_method != \"contour\":\n cmaps = [\n mpl.colors.LinearSegmentedColormap.from_list(\n f\"colormap_{class_idx}\", [(1.0, 1.0, 1.0, 1.0), (r, g, b, 1.0)]\n )\n for class_idx, (r, g, b, _) in enumerate(colors)\n ]\n+ # Make sure every class has its own surface.\n+ assert len(disp.surface_) == disp.n_classes\n+\n for idx, quad in enumerate(disp.surface_):\n assert quad.cmap == cmaps[idx]\n else:\n assert_allclose(disp.surface_.colors, colors)\n \n+ # non-regression test for issue #32866 (currently still fails)\n+ # if hasattr(disp.surface_, \"levels\"):\n+ # assert len(disp.surface_.levels) >= disp.n_classes\n+\n+\n+[USER_REDACTED].mark.parametrize(\n+ \"estimator, n_blobs, expected_n_classes\",\n+ [\n+ (DecisionTreeClassifier(random_state=0), 7, 7),\n+ (DecisionTreeClassifier(random_state=0), 2, 2),\n+ (KMeans(n_clusters=7, random_state=0), 7, 7),\n+ (KMeans(n_clusters=2, random_state=0), 2, 2),\n+ (DecisionTreeRegressor(random_state=0), 7, 2),\n+ (IsolationForest(random_state=0), 7, 2),\n+ ],\n+)\n+def test_n_classes_attribute(pyplot, estimator, n_blobs, expected_n_classes):\n+ \"\"\"Check that `n_classes` is set correctly.\n+\n+ Introduced in https://github.com/[USER_REDACTED]n/scikit-learn/pull/33015\"\"\"\n+\n+ X, y = make_blobs(n_samples=150, centers=n_blobs, n_features=2, random_state=42)\n+ clf = estimator.fit(X, y)\n+ disp = DecisionBoundaryDisplay.from_estimator(clf, X, response_method=\"predict\")\n+ assert disp.n_classes == expected_n_classes\n+\n+ # Test that setting class_of_interest always converts to a binary problem.\n+ disp_coi = DecisionBoundaryDisplay.from_estimator(\n+ clf, X, class_of_interest=y[0], response_method=\"predict\"\n+ )\n+ assert disp_coi.n_classes == 2\n+\n \n def test_cmap_and_colors_logic(pyplot):\n \"\"\"Check the handling logic for `cmap` and `colors`.\"\"\"" } ], "reviews": [ { "id": 3635838100, "user": "user_5819d17296ee", "state": "COMMENTED", "body": "I didn't check the details but from a cursory glance this looks great. Please feel free to ping me once CI is green.\n\nI think it would be great to also find a way to include a non regression test for #32866, that is, that different regions are assigned distinct colors when `n_classes` is large.\n\nEDIT: maybe inspecting the levels would be a way to achieve this, for instance by including/adapting the test of #32866.", "submitted_at": "2026-01-07T17:07:24+00:00" }, { "id": 3636870946, "user": "user_34a090906ca4", "state": "COMMENTED", "body": null, "submitted_at": "2026-01-07T21:29:12+00:00" }, { "id": 3639044942, "user": "user_34a090906ca4", "state": "COMMENTED", "body": null, "submitted_at": "2026-01-08T11:47:50+00:00" }, { "id": 3639083794, "user": "user_34a090906ca4", "state": "COMMENTED", "body": null, "submitted_at": "2026-01-08T11:59:29+00:00" }, { "id": 3639090411, "user": "user_34a090906ca4", "state": "COMMENTED", "body": null, "submitted_at": "2026-01-08T12:01:32+00:00" }, { "id": 3639097115, "user": "user_34a090906ca4", "state": "COMMENTED", "body": null, "submitted_at": "2026-01-08T12:03:41+00:00" }, { "id": 3639872756, "user": "user_5819d17296ee", "state": "COMMENTED", "body": "Here is an early pass of feedback with a focus on the meaning of this display and the \"n_classes\" params when we use this to display the output of the `predict` method for a regressor.", "submitted_at": "2026-01-08T16:08:44+00:00" }, { "id": 3643448784, "user": "user_34a090906ca4", "state": "COMMENTED", "body": null, "submitted_at": "2026-01-09T11:03:05+00:00" }, { "id": 3643455638, "user": "user_34a090906ca4", "state": "COMMENTED", "body": null, "submitted_at": "2026-01-09T11:05:15+00:00" }, { "id": 3643753722, "user": "user_34a090906ca4", "state": "COMMENTED", "body": null, "submitted_at": "2026-01-09T12:37:52+00:00" }, { "id": 3644709493, "user": "user_5819d17296ee", "state": "COMMENTED", "body": null, "submitted_at": "2026-01-09T16:35:50+00:00" }, { "id": 3644785708, "user": "user_34a090906ca4", "state": "COMMENTED", "body": null, "submitted_at": "2026-01-09T16:56:25+00:00" }, { "id": 3655064071, "user": "user_5819d17296ee", "state": "COMMENTED", "body": null, "submitted_at": "2026-01-13T10:28:39+00:00" }, { "id": 3666269013, "user": "user_5819d17296ee", "state": "APPROVED", "body": "LGTM besides the following minor details:", "submitted_at": "2026-01-15T16:40:59+00:00" }, { "id": 3669888233, "user": "user_34a090906ca4", "state": "COMMENTED", "body": null, "submitted_at": "2026-01-16T09:47:34+00:00" }, { "id": 3669973610, "user": "user_34a090906ca4", "state": "COMMENTED", "body": null, "submitted_at": "2026-01-16T10:02:21+00:00" }, { "id": 3673469057, "user": "user_d16337ec046b", "state": "COMMENTED", "body": "Sorry for all the comments.\n\nMostly nits. The only issues are issues that were probably introduced in #31553 or #29797 (by me, sorry!), which are quite specific so thought it was easier to detail them here. It would be worthwhile to fix these problems. \nIf you are not interested in fixing these issues in a subsequent PR, I can open a separate issue for them, but otherwise I will leave it in your hands!", "submitted_at": "2026-01-19T05:43:18+00:00" }, { "id": 3677450295, "user": "user_34a090906ca4", "state": "COMMENTED", "body": null, "submitted_at": "2026-01-19T10:47:20+00:00" }, { "id": 3677474967, "user": "user_34a090906ca4", "state": "COMMENTED", "body": null, "submitted_at": "2026-01-19T10:53:46+00:00" }, { "id": 3678130974, "user": "user_34a090906ca4", "state": "COMMENTED", "body": null, "submitted_at": "2026-01-19T13:34:52+00:00" }, { "id": 3679902403, "user": "user_d16337ec046b", "state": "COMMENTED", "body": null, "submitted_at": "2026-01-20T00:09:02+00:00" }, { "id": 3680066209, "user": "user_d16337ec046b", "state": "COMMENTED", "body": null, "submitted_at": "2026-01-20T02:20:07+00:00" }, { "id": 3680130909, "user": "user_d16337ec046b", "state": "COMMENTED", "body": null, "submitted_at": "2026-01-20T02:58:57+00:00" }, { "id": 3680141552, "user": "user_d16337ec046b", "state": "COMMENTED", "body": null, "submitted_at": "2026-01-20T03:06:53+00:00" }, { "id": 3680317461, "user": "user_d16337ec046b", "state": "COMMENTED", "body": "Sorry another question and a nit.", "submitted_at": "2026-01-20T04:49:43+00:00" }, { "id": 3681243761, "user": "user_34a090906ca4", "state": "COMMENTED", "body": null, "submitted_at": "2026-01-20T09:38:17+00:00" }, { "id": 3681254027, "user": "user_34a090906ca4", "state": "COMMENTED", "body": null, "submitted_at": "2026-01-20T09:40:42+00:00" }, { "id": 3682520708, "user": "user_34a090906ca4", "state": "COMMENTED", "body": null, "submitted_at": "2026-01-20T14:37:35+00:00" }, { "id": 3682545753, "user": "user_34a090906ca4", "state": "COMMENTED", "body": null, "submitted_at": "2026-01-20T14:42:58+00:00" }, { "id": 3686332456, "user": "user_34a090906ca4", "state": "COMMENTED", "body": null, "submitted_at": "2026-01-21T09:58:15+00:00" }, { "id": 3687181811, "user": "user_34a090906ca4", "state": "COMMENTED", "body": null, "submitted_at": "2026-01-21T13:11:26+00:00" }, { "id": 3687216015, "user": "user_34a090906ca4", "state": "COMMENTED", "body": null, "submitted_at": "2026-01-21T13:19:30+00:00" }, { "id": 3687398791, "user": "user_34a090906ca4", "state": "COMMENTED", "body": null, "submitted_at": "2026-01-21T14:00:29+00:00" }, { "id": 3687414311, "user": "user_34a090906ca4", "state": "COMMENTED", "body": null, "submitted_at": "2026-01-21T14:03:43+00:00" }, { "id": 3687416777, "user": "user_34a090906ca4", "state": "COMMENTED", "body": null, "submitted_at": "2026-01-21T14:04:08+00:00" }, { "id": 3687436118, "user": "user_34a090906ca4", "state": "COMMENTED", "body": null, "submitted_at": "2026-01-21T14:07:47+00:00" }, { "id": 3687449825, "user": "user_34a090906ca4", "state": "COMMENTED", "body": null, "submitted_at": "2026-01-21T14:10:30+00:00" }, { "id": 3687456164, "user": "user_34a090906ca4", "state": "COMMENTED", "body": null, "submitted_at": "2026-01-21T14:11:54+00:00" }, { "id": 3687465890, "user": "user_34a090906ca4", "state": "COMMENTED", "body": null, "submitted_at": "2026-01-21T14:13:30+00:00" }, { "id": 3687470604, "user": "user_34a090906ca4", "state": "COMMENTED", "body": null, "submitted_at": "2026-01-21T14:14:22+00:00" }, { "id": 3687544690, "user": "user_5819d17296ee", "state": "COMMENTED", "body": null, "submitted_at": "2026-01-21T14:27:51+00:00" }, { "id": 3687551868, "user": "user_5819d17296ee", "state": "COMMENTED", "body": null, "submitted_at": "2026-01-21T14:29:20+00:00" }, { "id": 3691466425, "user": "user_34a090906ca4", "state": "COMMENTED", "body": null, "submitted_at": "2026-01-22T09:27:43+00:00" }, { "id": 3692011235, "user": "user_34a090906ca4", "state": "COMMENTED", "body": null, "submitted_at": "2026-01-22T11:34:31+00:00" }, { "id": 3692015675, "user": "user_34a090906ca4", "state": "COMMENTED", "body": null, "submitted_at": "2026-01-22T11:35:46+00:00" }, { "id": 3727312629, "user": "user_5819d17296ee", "state": "APPROVED", "body": "I had another look at this PR and this LGTM as it is. It's already a big improvement. +1 for merge and tackling the remaining points discussed in linked issues in follow-up PRs.", "submitted_at": "2026-01-30T09:44:07+00:00" }, { "id": 3731092366, "user": "user_d16337ec046b", "state": "COMMENTED", "body": null, "submitted_at": "2026-01-31T00:06:40+00:00" }, { "id": 3731095001, "user": "user_d16337ec046b", "state": "APPROVED", "body": "Thanks for all your work on this, it was quite complicated in the end.\n\nSome nits only and a question but LGTM and fine to merge.", "submitted_at": "2026-01-31T00:26:36+00:00" }, { "id": 3738006959, "user": "user_34a090906ca4", "state": "COMMENTED", "body": null, "submitted_at": "2026-02-02T08:35:18+00:00" }, { "id": 3738045155, "user": "user_34a090906ca4", "state": "COMMENTED", "body": null, "submitted_at": "2026-02-02T08:44:44+00:00" }, { "id": 3738069326, "user": "user_34a090906ca4", "state": "COMMENTED", "body": null, "submitted_at": "2026-02-02T08:49:55+00:00" }, { "id": 3738257354, "user": "user_d16337ec046b", "state": "COMMENTED", "body": null, "submitted_at": "2026-02-02T09:32:11+00:00" } ], "review_comments": [ { "id": 2669260895, "user": "user_5819d17296ee", "body": "Could we expand this test to check that `gist_rainbow` is used for larger number of classes?", "path": "sklearn/inspection/_plot/tests/test_boundary_decision_display.py", "line": null, "side": "RIGHT", "created_at": "2026-01-07T16:59:14+00:00" }, { "id": 2670131642, "user": "user_34a090906ca4", "body": "I thought about that, too, but I think I'd rather do that in a follow-up PR because I also want to add another check (and test) for `multiclass_colors`: Currently we don't check if enough unique colors are available, so there will be duplicate colors for example when passing `\"tab10\"` with 11 classes.\n\nI also noticed that there are some parameter checks for `multiclass_colors` in `from_estimator` and then some (again) in `plot`, where the colors are actually selected. Since `from_estimator` always calls `plot` (and `plot` could in principle also be called without `from_estimator`), I'd move all checks there, together with extending the tests.", "path": "sklearn/inspection/_plot/tests/test_boundary_decision_display.py", "line": null, "side": "RIGHT", "created_at": "2026-01-07T21:29:12+00:00" }, { "id": 2672041446, "user": "user_34a090906ca4", "body": "In the end, I did decide to included it here, because more classes were also necessary for the non-regression test for https://github.com/[USER_REDACTED]n/scikit-learn/issues/32866.", "path": "sklearn/inspection/_plot/tests/test_boundary_decision_display.py", "line": null, "side": "RIGHT", "created_at": "2026-01-08T11:47:50+00:00" }, { "id": 2672075644, "user": "user_34a090906ca4", "body": "This test will fail for (\"tab10\", 15), which I will address in a follow-up PR.", "path": "sklearn/inspection/_plot/tests/test_boundary_decision_display.py", "line": null, "side": "RIGHT", "created_at": "2026-01-08T11:59:29+00:00" }, { "id": 2672081602, "user": "user_34a090906ca4", "body": "I had to combine colors and number of classes here because the list version has to match the exact number of classes.", "path": "sklearn/inspection/_plot/tests/test_boundary_decision_display.py", "line": 640, "side": "RIGHT", "created_at": "2026-01-08T12:01:32+00:00" }, { "id": 2672088061, "user": "user_34a090906ca4", "body": "This can be fixed by [NAME_REDACTED] in https://github.com/[USER_REDACTED]n/scikit-learn/pull/32867 once this is merged.", "path": "sklearn/inspection/_plot/tests/test_boundary_decision_display.py", "line": null, "side": "RIGHT", "created_at": "2026-01-08T12:03:41+00:00" }, { "id": 2672742775, "user": "user_5819d17296ee", "body": "nit: we should stick to 2 space indentation in this bullet list.\n\n```suggestion\n * None: 'tab10' colormap is used to sample colors if the number of\n classes is less than or equal to 10, otherwise 'gist_rainbow' colormap.\n```", "path": "sklearn/inspection/_plot/decision_boundary.py", "line": null, "side": "RIGHT", "created_at": "2026-01-08T15:11:10+00:00" }, { "id": 2672773444, "user": "user_5819d17296ee", "body": "For which estimators is this needed? Isn't there a risk of unanticipated consequences of this generic `else` case?", "path": "sklearn/inspection/_plot/decision_boundary.py", "line": null, "side": "RIGHT", "created_at": "2026-01-08T15:18:53+00:00" }, { "id": 2672785467, "user": "user_5819d17296ee", "body": "Otherwise, I think we might want to raise a `ValueError` error or more specific exception with a message that is explicit about what we expected from the estimator.\n\nIn particular, if we pass a classifier without a `classes_` attribute, we might want to raise `NotFittedError` exception.", "path": "sklearn/inspection/_plot/decision_boundary.py", "line": null, "side": "RIGHT", "created_at": "2026-01-08T15:22:07+00:00" }, { "id": 2672802244, "user": "user_5819d17296ee", "body": "In particular, we should explicitly raise if the estimator is a regressor.\n\nEDIT: actually, there is a test that checks that this display accepts regressors and I agree it can lead to a useful plot (in particular if we use `plot_method=\"pcolormesh\"` for instance), but then the term \"n_classes\" is really weird and furthermore, I think it `n_classes` should not be set to the number of unique values but rather to None, and we should display the output of `predict` for a regressor as the output of `predict_proba` or `decision_function` for a binary classifier. Furthermore, we should use a non-rainbow colormap for this kind of outputs (e.g. Viridis or Blues).\n\nBTW, is there an existing example somewhere that uses `DecisionBoundaryDisplay` on a regressor? If not, we might want to expand one.", "path": "sklearn/inspection/_plot/decision_boundary.py", "line": null, "side": "RIGHT", "created_at": "2026-01-08T15:26:29+00:00" }, { "id": 2675762411, "user": "user_34a090906ca4", "body": "Re: `NotFittedError`:\nThis is checked (and raised) in line 467. So to make the distinction more explicit, I'd change `hasattr(estimator, \"classes_\")` to `is_classifier(estimator)` here.", "path": "sklearn/inspection/_plot/decision_boundary.py", "line": null, "side": "RIGHT", "created_at": "2026-01-09T11:03:05+00:00" }, { "id": 2675768532, "user": "user_34a090906ca4", "body": "Re: `DecisionBoundaryDisplay` for regressor example:\nI didn't find one, so I'll add one (in a follow-up PR).", "path": "sklearn/inspection/_plot/decision_boundary.py", "line": null, "side": "RIGHT", "created_at": "2026-01-09T11:05:15+00:00" }, { "id": 2676042878, "user": "user_34a090906ca4", "body": "Re: regressors:\nThe easiest adaption within the current code would be to set `n_classes` to 2 for regressors (and add this as a note in the docs), then the output is treated similar to `decision_function` for binary classification and the default color map is `viridis`.", "path": "sklearn/inspection/_plot/decision_boundary.py", "line": null, "side": "RIGHT", "created_at": "2026-01-09T12:37:52+00:00" }, { "id": 2676854194, "user": "user_5819d17296ee", "body": "I think we need to expand the tests for the regressor case (to make sure that it does not detect a \"number of classes\" equal to the number of data points).", "path": "sklearn/inspection/_plot/decision_boundary.py", "line": null, "side": "RIGHT", "created_at": "2026-01-09T16:35:50+00:00" }, { "id": 2676919521, "user": "user_34a090906ca4", "body": "Is there a reason to prefer this one over the other? I find the latter a bit easier to parse.\n```suggestion\n mask=(self.response != class_idx),\n```", "path": "sklearn/inspection/_plot/decision_boundary.py", "line": null, "side": "RIGHT", "created_at": "2026-01-09T16:56:25+00:00" }, { "id": 2685788128, "user": "user_5819d17296ee", "body": "I prefer the suggested code (inner negation). It feels more direct to me and avoid one useless array allocation.", "path": "sklearn/inspection/_plot/decision_boundary.py", "line": null, "side": "RIGHT", "created_at": "2026-01-13T10:28:39+00:00" }, { "id": 2694910495, "user": "user_5819d17296ee", "body": "I would prefer to distinctly name and set the actual number of blobs in the data and the expected n_classes attribute value as distinct test parameters to better convey the expectations of this test.\n\n```suggestion\n[USER_REDACTED].mark.parametrize(\n \"estimator, n_blobs, expected_n_classes\",\n [\n (DecisionTreeClassifier(random_state=0), 7, 7),\n (DecisionTreeClassifier(random_state=0), 2, 2),\n (KMeans(n_clusters=7, random_state=0), 7, 7),\n (KMeans(n_clusters=2, random_state=0), 7, 2),\n (DecisionTreeRegressor(random_state=0), 7, 2),\n (IsolationForest(random_state=0), 7, 2),\n ],\n)\ndef test_n_classes_attribute(pyplot, estimator, n_blobs, expected_n_classes):\n \"\"\"Check that `n_classes` is set correctly.\n\n Introduced in https://github.com/[USER_REDACTED]n/scikit-learn/pull/33015\"\"\"\n\n X, y = make_blobs(n_samples=150, centers=n_blobs, n_features=2, random_state=42)\n clf = estimator.fit(X, y)\n\n disp = DecisionBoundaryDisplay.from_estimator(clf, X, response_method=\"predict\")\n assert disp.n_classes == expected_n_classes\n\n # Test that setting class_of_interest always converts to a binary problem.\n disp_coi = DecisionBoundaryDisplay.from_estimator(\n clf, X, class_of_interest=y[0], response_method=\"predict\"\n )\n assert disp_coi.n_classes == 2\n```\n\nNote: I have checked the code locally. It's possible I made a mistake while editing via the GitHub UI.", "path": "sklearn/inspection/_plot/tests/test_boundary_decision_display.py", "line": 738, "side": "RIGHT", "created_at": "2026-01-15T15:44:20+00:00" }, { "id": 2694943793, "user": "user_5819d17296ee", "body": "```suggestion\n Expected number of unique classes or labels if `response` was generated by a\n classifier or a clusterer.\n\n For (single output) regressors and outlier detectors, the continous response\n are displayed the same way as the continuous response of a binary\n classifier, hence, the `n_classes` attribute is always set to 2 by [NAME_REDACTED] \n```", "path": "sklearn/inspection/_plot/decision_boundary.py", "line": null, "side": "RIGHT", "created_at": "2026-01-15T15:53:23+00:00" }, { "id": 2695146869, "user": "user_5819d17296ee", "body": "```suggestion\n # Part of a non-regression test for issue #32866 to make sure the colormap \n # used has enough distinct colors.\n```", "path": "sklearn/inspection/_plot/tests/test_boundary_decision_display.py", "line": null, "side": "RIGHT", "created_at": "2026-01-15T16:38:40+00:00" }, { "id": 2695150576, "user": "user_5819d17296ee", "body": "```suggestion\n # Part of a non-regression test for issue #32866 to make sure every class\n # has its own surface.\n```", "path": "sklearn/inspection/_plot/tests/test_boundary_decision_display.py", "line": null, "side": "RIGHT", "created_at": "2026-01-15T16:39:44+00:00" }, { "id": 2697753805, "user": "user_34a090906ca4", "body": "I don't think outlier detectors can have a continuous response, right? So maybe rather:\n```suggestion\n Expected number of unique classes or labels if `response` was generated by a\n classifier or a clusterer.\n\n For (single output) regressors, the continous response is displayed the same way\n as the continuous response of a binary classifier, hence, the `n_classes` \n attribute is always set to 2 by [NAME_REDACTED]\n\n For outlier detectors, `n_classes` is set to 2 by definition (inlier or outlier). \n```", "path": "sklearn/inspection/_plot/decision_boundary.py", "line": null, "side": "RIGHT", "created_at": "2026-01-16T09:47:34+00:00" }, { "id": 2697817256, "user": "user_34a090906ca4", "body": "Thanks! I added it manually and ran it again just to be sure.", "path": "sklearn/inspection/_plot/tests/test_boundary_decision_display.py", "line": 738, "side": "RIGHT", "created_at": "2026-01-16T10:02:21+00:00" }, { "id": 2700634228, "user": "user_d16337ec046b", "body": "nit pick, is it a class variable or an instance variable? Its value unique to each class instance right?", "path": "doc/whats_new/upcoming_changes/sklearn.inspection/33015.fix.rst", "line": null, "side": "RIGHT", "created_at": "2026-01-17T04:43:18+00:00" }, { "id": 2700642548, "user": "user_d16337ec046b", "body": "Not sure if we have to give this detail - especially as this only occurs if we use `from_estimator` and the estimator has `classes_` attribute.\n\nWe could just say it stores the number of classes/labels?", "path": "doc/whats_new/upcoming_changes/sklearn.inspection/33015.fix.rst", "line": null, "side": "RIGHT", "created_at": "2026-01-17T05:00:03+00:00" }, { "id": 2700643803, "user": "user_d16337ec046b", "body": "This was more a matplotlib bug that was propagated - and is it fixed for more recent versions of mpl? - if so maybe just mention fixed distinct colours bug for certain mpl versions?", "path": "doc/whats_new/upcoming_changes/sklearn.inspection/33015.fix.rst", "line": null, "side": "RIGHT", "created_at": "2026-01-17T05:02:22+00:00" }, { "id": 2700643843, "user": "user_d16337ec046b", "body": "```suggestion\n By :user:`[NAME_REDACTED] `.\n```\nnit", "path": "doc/whats_new/upcoming_changes/sklearn.inspection/33015.fix.rst", "line": null, "side": "RIGHT", "created_at": "2026-01-17T05:02:28+00:00" }, { "id": 2702862369, "user": "user_d16337ec046b", "body": "I think we could just focus on the API fixes/changes, and not go into details about implementation, which the average user is probably not interested in and may be confusing.\ni.e. we probably don't need to say that the classes are plotted one by [NAME_REDACTED] `multiclass_colors` is based on `n_classes` ?", "path": "doc/whats_new/upcoming_changes/sklearn.inspection/33015.fix.rst", "line": null, "side": "RIGHT", "created_at": "2026-01-18T23:37:29+00:00" }, { "id": 2702871767, "user": "user_d16337ec046b", "body": "Why 15? Is this to test for the https://github.com/[USER_REDACTED]n/scikit-learn/issues/32866 ? Though you only need >7 for this.", "path": "sklearn/inspection/_plot/tests/test_boundary_decision_display.py", "line": null, "side": "RIGHT", "created_at": "2026-01-18T23:43:10+00:00" }, { "id": 2702880420, "user": "user_d16337ec046b", "body": "> the continuous response of a binary classifier\n\nWhat about:\n\n\"the continuous unthresholded response of a binary classifier\"\nor just:\n\"the unthresholded response of a binary classifier\"\n\nAlso lets add some links to the glossary (https://scikit-learn.org/dev/glossary.html - \nyou'll find which terms are included here), e.g. regressor, clusteror etc. Use following syntax, e.g.:\n```\n:term:`clusterer`\n```", "path": "sklearn/inspection/_plot/decision_boundary.py", "line": null, "side": "RIGHT", "created_at": "2026-01-18T23:56:55+00:00" }, { "id": 2702881754, "user": "user_d16337ec046b", "body": "Should we add that for binary problems, specify color via kwargs?", "path": "sklearn/inspection/_plot/decision_boundary.py", "line": null, "side": "RIGHT", "created_at": "2026-01-18T23:58:56+00:00" }, { "id": 2702882434, "user": "user_d16337ec046b", "body": "Should we add a .. versionchanged:: here ...?", "path": "sklearn/inspection/_plot/decision_boundary.py", "line": 123, "side": "RIGHT", "created_at": "2026-01-19T00:00:03+00:00" }, { "id": 2703134927, "user": "user_d16337ec046b", "body": "The comment isn't clear on why we are doing this, so I did some digging.\n\nFrom https://github.com/[USER_REDACTED]n/scikit-learn/pull/31553#pullrequestreview-3005538868\n\n> I just found that the tab10/tab20 special casing was removed, so I put it back because it gives better visualization (more distinguishable colors)\n\nI think this will be the case for most [qualitative](https://matplotlib.org/stable/users/explain/colors/colormaps.html#qualitative) cmaps. i.e. for tab10:\n\n`plt.get_cmap(\"tab10\", 2)`, samples the colormap evenly, thus returns the first and last colors:\n\n\"Image\"\n\nwhereas the following gives the first 2 colors:\n\n`plt.imshow([plt.get_cmap(\"tab10\", 10).colors[:2]], aspect='auto')`\n\n\"Image\"\n\nFor a separate PR, maybe we could generalize this behaviour for all qualitative cmaps (these have 'colors' attr).", "path": "sklearn/inspection/_plot/decision_boundary.py", "line": 279, "side": "RIGHT", "created_at": "2026-01-19T03:57:39+00:00" }, { "id": 2703156456, "user": "user_d16337ec046b", "body": "For colormaps with `colors` attr, `plt.get_cmap(cmap, self.n_classes)` will have a max number of colors.\n\ne.g., `plt.get_cmap('tab10', 12)`\n\nwill only give 10 distinct colors - it will just start repeating colors.\n\nIn a separate PR, we should probably fix this and add a test.", "path": "sklearn/inspection/_plot/decision_boundary.py", "line": 286, "side": "RIGHT", "created_at": "2026-01-19T04:15:21+00:00" }, { "id": 2703157758, "user": "user_d16337ec046b", "body": "```suggestion\n # Get `LinearSegmentedColormap` for non-qualitative cmaps\n```\n\nunrelated but lets add for clarity", "path": "sklearn/inspection/_plot/decision_boundary.py", "line": null, "side": "RIGHT", "created_at": "2026-01-19T04:16:25+00:00" }, { "id": 2703242541, "user": "user_d16337ec046b", "body": "This is not fully accurate. Maybe:\n\n\"Plot only integer class values\" or\n\"Plot only thresholded class values\"\n\n?", "path": "sklearn/inspection/_plot/decision_boundary.py", "line": null, "side": "RIGHT", "created_at": "2026-01-19T05:14:41+00:00" }, { "id": 2703246240, "user": "user_d16337ec046b", "body": "What does it look like if we plotted 'contourf' + predict like this? Does the automatic level determination by [NAME_REDACTED] off? Would specifying the levels to be integer values, 0-n_classes, help?\n\nThen we could get rid of the condition at ~L300-305", "path": "sklearn/inspection/_plot/decision_boundary.py", "line": 299, "side": "RIGHT", "created_at": "2026-01-19T05:17:09+00:00" }, { "id": 2703249441, "user": "user_d16337ec046b", "body": "Not sure if the bit about how regressors are handled is required.\n\nSimilar to above, we don't need to go into detail about implementation that may be confusing to users anyway.", "path": "sklearn/inspection/_plot/decision_boundary.py", "line": null, "side": "RIGHT", "created_at": "2026-01-19T05:19:14+00:00" }, { "id": 2703250809, "user": "user_d16337ec046b", "body": "```suggestion\n Specifies how to color each class when plotting :term:`multiclass` problems\n```", "path": "sklearn/inspection/_plot/decision_boundary.py", "line": null, "side": "RIGHT", "created_at": "2026-01-19T05:20:06+00:00" }, { "id": 2703251888, "user": "user_d16337ec046b", "body": "I wonder if the bit about binary colors is better suited above in `multiclass_colors`?", "path": "sklearn/inspection/_plot/decision_boundary.py", "line": null, "side": "RIGHT", "created_at": "2026-01-19T05:20:50+00:00" }, { "id": 2703256155, "user": "user_d16337ec046b", "body": "same comment as below https://github.com/[USER_REDACTED]n/scikit-learn/pull/33015/changes#r2703251888", "path": "sklearn/inspection/_plot/decision_boundary.py", "line": null, "side": "RIGHT", "created_at": "2026-01-19T05:23:37+00:00" }, { "id": 2703263600, "user": "user_d16337ec046b", "body": "Do we support multioutput regressors? The \"(single output)\" raised this question for me.\n\nWhat about:\n\nFor (single output) regressors `n_classes` should be set to 2 by convention (continuous response is displayed the same way as unthresholded binary responses).\n\nIf the user is instantiating their own class instance, they are setting this attr, and we don't infer anything. Thus we can only tell them what it should be set to", "path": "sklearn/inspection/_plot/decision_boundary.py", "line": null, "side": "RIGHT", "created_at": "2026-01-19T05:28:05+00:00" }, { "id": 2704225655, "user": "user_34a090906ca4", "body": "Maybe add this in the example here as well then?\nhttps://github.com/[USER_REDACTED]n/scikit-learn/blob/main/doc/whats_new/upcoming_changes/README.md", "path": "doc/whats_new/upcoming_changes/sklearn.inspection/33015.fix.rst", "line": null, "side": "RIGHT", "created_at": "2026-01-19T10:47:20+00:00" }, { "id": 2704247834, "user": "user_34a090906ca4", "body": "I picked a random number >10 related to https://github.com/[USER_REDACTED]n/scikit-learn/pull/33015/changes#r2672075644 (and what you also observed below https://github.com/[USER_REDACTED]n/scikit-learn/pull/33015/changes#r2703156456), but we can change it to 11 to save some lines.", "path": "sklearn/inspection/_plot/tests/test_boundary_decision_display.py", "line": null, "side": "RIGHT", "created_at": "2026-01-19T10:53:46+00:00" }, { "id": 2704801565, "user": "user_34a090906ca4", "body": "My initial motivation was to make the handling more similar for all plotting functions, but since `pcolormesh` also requires separate handling for `predict`, I agree that there is no reason to prefer this option over the one you suggest.\n\nThis will, however, require the specific level handling as proposed in #32867, but since this is also still required for `contour`, I will make the adjustments as you suggested, and then we can tackle the `level` problem in #32867.", "path": "sklearn/inspection/_plot/decision_boundary.py", "line": 299, "side": "RIGHT", "created_at": "2026-01-19T13:34:51+00:00" }, { "id": 2706358455, "user": "user_d16337ec046b", "body": "Ah that is a good point. That is why I keep seeing changelogs without the full stop!", "path": "doc/whats_new/upcoming_changes/sklearn.inspection/33015.fix.rst", "line": null, "side": "RIGHT", "created_at": "2026-01-20T00:09:02+00:00" }, { "id": 2706524694, "user": "user_d16337ec046b", "body": "Ahh right. But if you give distinct colours (instead of e.g., 'tab10') does the problem: https://github.com/[USER_REDACTED]n/scikit-learn/pull/33015/changes#r2703156456 still occur?", "path": "sklearn/inspection/_plot/tests/test_boundary_decision_display.py", "line": null, "side": "RIGHT", "created_at": "2026-01-20T02:20:07+00:00" }, { "id": 2706586641, "user": "user_d16337ec046b", "body": "Yeah I agree, it would be nice to simplify this code, because it is confusing but it seems different plots need to be handled differently. To summarise, atm all 'contour' is handled, then 'pcolormesh' predict, then in else we handle 'pcolormesh' continuous response and all 'contourf', which is a bit confusing.\n\nNote my suggestion was mostly such that we only handle NON `predict` responses in the `else` condition. \n\nMaybe we could add a short(ish) comment on why we need to handle pmesh with predict separately - just for easier reading later on?\n\nThe contour one is tricky to know what to do because problems noted in #33108 and https://github.com/[USER_REDACTED]n/scikit-learn/pull/32867#issuecomment-3723877765 so not sure what to suggest there.\n\n> I will make the adjustments as you suggested\n\nWill the plot still look okay with my suggestion?", "path": "sklearn/inspection/_plot/decision_boundary.py", "line": 299, "side": "RIGHT", "created_at": "2026-01-20T02:58:57+00:00" }, { "id": 2706597598, "user": "user_d16337ec046b", "body": "Actually thinking about it more, what does 'pcolormesh' + predict look like if we handled it in the `else` condition, where we plot class by class? Even though we use a `LinearSegmentedColormap` which gives a gradient from white to the class colour, since the predict values are integer, the plot would be coloured with the class colour right?\n\nIt would be less efficient, but it would simplify code and maybe for displays, efficiency isn't as much of a concern?", "path": "sklearn/inspection/_plot/decision_boundary.py", "line": 299, "side": "RIGHT", "created_at": "2026-01-20T03:06:53+00:00" }, { "id": 2706728894, "user": "user_d16337ec046b", "body": "Naive question, but why `<` ? \n\nDoes this occur if the user passes a list of colors, and we don't ensure it is the same length as `n_classes`?\nBut since we `for class_idx, cmap in enumerate(multiclass_cmaps):` later, wouldn't this be a problem?", "path": "sklearn/inspection/_plot/tests/test_boundary_decision_display.py", "line": null, "side": "RIGHT", "created_at": "2026-01-20T04:38:40+00:00" }, { "id": 2706738413, "user": "user_d16337ec046b", "body": "Also looking more at #32866, it seems more of problem that the number levels is less than the number of classes.\n\nEven if we passed the correct number of colors, because there are fewer levels, we would still not get the right number of colours plotted.", "path": "sklearn/inspection/_plot/tests/test_boundary_decision_display.py", "line": null, "side": "RIGHT", "created_at": "2026-01-20T04:44:46+00:00" }, { "id": 2706746095, "user": "user_d16337ec046b", "body": "Sorry another nit - the colour handling has expanded from subsequent PRs and is now probably a bit more complex than it needs to be.\n\nWhat about something simpler e.g.,\n\n```python\nif isinstance(self.multiclass_colors, list):\n colors = [mpl.colors.to_rgba(color) for color in self.multiclass_colors]\nelse:\n cmap_name = self.multiclass_colors\n if cmap_name is None:\n # use default if `multiclass_colors` None\n cmap_name = \"tab10\" if self.n_classes <= 10 else \"gist_rainbow\"\n elif not isinstance(cmap_name, str):\n raise ValueError(\"'multiclass_colors' must be a list or a str.\")\n \n # Special case for the tab10 and tab20 colormaps that encode a\n # discrete set of colors that are easily distinguishable\n # contrary to other colormaps that are continuous.\n if cmap_name == \"tab10\" and self.n_classes <= 10:\n colors = plt.get_cmap(\"tab10\", 10).colors[: self.n_classes]\n elif cmap_name == \"tab20\" and self.n_classes <= 20:\n colors = plt.get_cmap(\"tab20\", 20).colors[: self.n_classes]\n else:\n cmap = plt.get_cmap(cmap_name, self.n_classes)\n if not hasattr(cmap, \"colors\"):\n # For LinearSegmentedColormap\n colors = cmap(np.linspace(0, 1, self.n_classes))\n else:\n colors = cmap.colors\n```\nHere we do the shorter condition (list) first, which reads easier than having the long condition first - so people don't forget whats going on.\nIt's similiar in length but less nesting.\n\nAgain, could be done in a separate PR.", "path": "sklearn/inspection/_plot/decision_boundary.py", "line": 265, "side": "RIGHT", "created_at": "2026-01-20T04:49:33+00:00" }, { "id": 2707539022, "user": "user_34a090906ca4", "body": "How about this for now? (leaving non-plot `contour` separate for now, as this is being discussed separately here https://github.com/[USER_REDACTED]n/scikit-learn/issues/33108)\n\n```suggestion\n if self.response.ndim == 2: # predict\n # `pcolormesh` requires cmap\n cmap = mpl.colors.ListedColormap(colors)\n self.surface_ = plot_func(\n self.xx0, self.xx1, self.response, cmap=cmap,**kwargs\n )\n\n # predict_proba or decision_function differ for plotting methods\n elif plot_method == \"contour\":\n # Plot only argmax\n self.surface_ = plot_func(\n self.xx0, self.xx1, self.response.argmax(axis=2), colors=colors, **kwargs\n )\n```", "path": "sklearn/inspection/_plot/decision_boundary.py", "line": null, "side": "RIGHT", "created_at": "2026-01-20T09:38:17+00:00" }, { "id": 2707548264, "user": "user_34a090906ca4", "body": "I didn't find a way to integrate it in the else condition, it kept giving an empty plot, but handling all `predict` versions first with a cmap, then non-predict `contour` and then the rest, would work, which I think I prefer. I changed it to that and also updated the description above with the new plot. This still requires the level fix from https://github.com/[USER_REDACTED]n/scikit-learn/pull/32867, but integrating this is planned anyways.", "path": "sklearn/inspection/_plot/decision_boundary.py", "line": 299, "side": "RIGHT", "created_at": "2026-01-20T09:40:42+00:00" }, { "id": 2708638348, "user": "user_34a090906ca4", "body": "No, if you give it a list, it is checked to be the same length as the number of classes.", "path": "sklearn/inspection/_plot/tests/test_boundary_decision_display.py", "line": null, "side": "RIGHT", "created_at": "2026-01-20T14:37:35+00:00" }, { "id": 2708660869, "user": "user_34a090906ca4", "body": "Oh, and I just remembered, I originally set it to >10 to test the correct application of the two default cases when `multiclass_colors` is `None` (\"tab10\" if `n_classes <= 10`, \"gist_rainbow\" otherwise). This then led to discovering the problem with explicitly passing \"tab10\" when `n_classes >10`", "path": "sklearn/inspection/_plot/tests/test_boundary_decision_display.py", "line": null, "side": "RIGHT", "created_at": "2026-01-20T14:42:58+00:00" }, { "id": 2711822035, "user": "user_34a090906ca4", "body": "I'll change it to `==`. I think this was left over from before I noticed that lists have to match the exact number of classes.\n\nThis did help to discover the problem with \"tab10\" and `n_classes > 10` (which will be handled in a follow-up PR), but indeed it does not test the levels issue, which will be tackled separately.", "path": "sklearn/inspection/_plot/tests/test_boundary_decision_display.py", "line": null, "side": "RIGHT", "created_at": "2026-01-21T09:58:15+00:00" }, { "id": 2712516746, "user": "user_34a090906ca4", "body": "I also stumbled across the \"(single-output)\".\nMulti-output estimators are not supported. Should we make this explicit here as well (or rather in `response` below)? And maybe also in `from_estimator`?", "path": "sklearn/inspection/_plot/decision_boundary.py", "line": null, "side": "RIGHT", "created_at": "2026-01-21T13:11:26+00:00" }, { "id": 2712546036, "user": "user_34a090906ca4", "body": "This is the display class, which doesn't have `kwargs`. I will not tackle this here, but I was thinking: Since `multiclass_colors_` will be added to the instance once the colors are selected, do we need to store `multiclass_colors` here? I would rather pass it on as a parameter to `plot` (where the `kwargs` can then actually be set), but this will be part of #33115.", "path": "sklearn/inspection/_plot/decision_boundary.py", "line": null, "side": "RIGHT", "created_at": "2026-01-21T13:19:30+00:00" }, { "id": 2712704957, "user": "user_34a090906ca4", "body": "The current solution does not address this bug anymore, so I removed that part.", "path": "doc/whats_new/upcoming_changes/sklearn.inspection/33015.fix.rst", "line": null, "side": "RIGHT", "created_at": "2026-01-21T14:00:29+00:00" }, { "id": 2712717567, "user": "user_34a090906ca4", "body": "Noted in the new issue https://github.com/[USER_REDACTED]n/scikit-learn/issues/33115", "path": "sklearn/inspection/_plot/decision_boundary.py", "line": 286, "side": "RIGHT", "created_at": "2026-01-21T14:03:43+00:00" }, { "id": 2712719610, "user": "user_34a090906ca4", "body": "Noted in the new issue https://github.com/[USER_REDACTED]n/scikit-learn/issues/33115", "path": "sklearn/inspection/_plot/decision_boundary.py", "line": 279, "side": "RIGHT", "created_at": "2026-01-21T14:04:08+00:00" }, { "id": 2712734927, "user": "user_34a090906ca4", "body": "Would that be version 1.9? \nAnd it should simply say this, right?\n`multiclass_colors` is now also used when `response_method=\"predict\"`", "path": "sklearn/inspection/_plot/decision_boundary.py", "line": 123, "side": "RIGHT", "created_at": "2026-01-21T14:07:47+00:00" }, { "id": 2712746301, "user": "user_34a090906ca4", "body": "Agreed, but related to https://github.com/[USER_REDACTED]n/scikit-learn/pull/33015#discussion_r2712516746 above, should we add a note that multi-output estimators are not supported?", "path": "sklearn/inspection/_plot/decision_boundary.py", "line": null, "side": "RIGHT", "created_at": "2026-01-21T14:10:30+00:00" }, { "id": 2712751660, "user": "user_34a090906ca4", "body": "See https://github.com/[USER_REDACTED]n/scikit-learn/pull/33015#discussion_r2712546036", "path": "sklearn/inspection/_plot/decision_boundary.py", "line": null, "side": "RIGHT", "created_at": "2026-01-21T14:11:54+00:00" }, { "id": 2712758766, "user": "user_34a090906ca4", "body": "Noted as part of #33115", "path": "sklearn/inspection/_plot/decision_boundary.py", "line": 265, "side": "RIGHT", "created_at": "2026-01-21T14:13:30+00:00" }, { "id": 2712762670, "user": "user_34a090906ca4", "body": "I added this suggestion and updated the resulting plots in the PR description above.", "path": "sklearn/inspection/_plot/decision_boundary.py", "line": null, "side": "RIGHT", "created_at": "2026-01-21T14:14:22+00:00" }, { "id": 2712822367, "user": "user_5819d17296ee", "body": "+1 for making it explicit that multi-output regressors are not supported by raising a `ValueError` if the `predict` method of a regressors output more than one values per input data points (i.e. `responses.ndim == 2 and responses.shape[1] > 1`).\n\nFeel free to rephrase the doc accordingly, but in my opinion the error message should be enough to make that explicit.", "path": "sklearn/inspection/_plot/decision_boundary.py", "line": null, "side": "RIGHT", "created_at": "2026-01-21T14:27:51+00:00" }, { "id": 2712828331, "user": "user_5819d17296ee", "body": "Yes.", "path": "sklearn/inspection/_plot/decision_boundary.py", "line": 123, "side": "RIGHT", "created_at": "2026-01-21T14:29:19+00:00" }, { "id": 2716052591, "user": "user_34a090906ca4", "body": "A `ValueError` is already raised for multi-output classifiers in line 49 and for regressors in line 575 (which could be refactored at some point to happen in the same place). \n\nI will leave the docstrings as they are, then.", "path": "sklearn/inspection/_plot/decision_boundary.py", "line": null, "side": "RIGHT", "created_at": "2026-01-22T09:27:43+00:00" }, { "id": 2716527783, "user": "user_34a090906ca4", "body": "I added it to be explicit for now, keeping in mind that making binary/multiclass use the same parameter is on the agenda as well.", "path": "sklearn/inspection/_plot/decision_boundary.py", "line": null, "side": "RIGHT", "created_at": "2026-01-22T11:34:31+00:00" }, { "id": 2716532024, "user": "user_34a090906ca4", "body": "We decided above that the error message is enough for now.", "path": "sklearn/inspection/_plot/decision_boundary.py", "line": null, "side": "RIGHT", "created_at": "2026-01-22T11:35:45+00:00" }, { "id": 2748506453, "user": "user_d16337ec046b", "body": "Sorry, I don't quite follow here, why 11? If we are testing just a list of colours (and not using default 'tab10'), why does the list of colours need to be >10?", "path": "sklearn/inspection/_plot/tests/test_boundary_decision_display.py", "line": null, "side": "RIGHT", "created_at": "2026-01-31T00:06:40+00:00" }, { "id": 2748508331, "user": "user_d16337ec046b", "body": "Sorry I don't quite follow why 11 - I asked here: https://github.com/[USER_REDACTED]n/scikit-learn/pull/33015#discussion_r2748506453", "path": "sklearn/inspection/_plot/tests/test_boundary_decision_display.py", "line": null, "side": "RIGHT", "created_at": "2026-01-31T00:07:13+00:00" }, { "id": 2748514718, "user": "user_d16337ec046b", "body": "Nit/question, what do you think about having these 2 items as bullet points? (I'm okay either way)", "path": "sklearn/inspection/_plot/decision_boundary.py", "line": 95, "side": "RIGHT", "created_at": "2026-01-31T00:09:05+00:00" }, { "id": 2748550195, "user": "user_d16337ec046b", "body": "Unrelated, I stumbled on this when I re-read it, \"Single color colormaps\" is not so intuitive - I think we create a white to single colour gradient colour map here, but not sure if this is reflected in \"Single color colormaps\". What do you think about:\n\n\"Single color (fading to white) colormaps\" or\n\"Single color, decreasing in saturation to white, colormaps\" ?", "path": "sklearn/inspection/_plot/decision_boundary.py", "line": null, "side": "RIGHT", "created_at": "2026-01-31T00:20:09+00:00" }, { "id": 2753183348, "user": "user_34a090906ca4", "body": "Ah, now I get it, you're right, the 11 test case is only necessary for the None condition (and will be for \"tab10\", but that will only be added later). I removed the redundant tests.", "path": "sklearn/inspection/_plot/tests/test_boundary_decision_display.py", "line": null, "side": "RIGHT", "created_at": "2026-02-02T08:35:17+00:00" }, { "id": 2753216924, "user": "user_34a090906ca4", "body": "I'd leave it like it is, because these two are equal options to the line above (that describes classifiers and clusterers).", "path": "sklearn/inspection/_plot/decision_boundary.py", "line": 95, "side": "RIGHT", "created_at": "2026-02-02T08:44:43+00:00" }, { "id": 2753236758, "user": "user_34a090906ca4", "body": "I find it quite self-explanatory, but I have looked at the output a lot now, so I don't mind adding it for clarity.", "path": "sklearn/inspection/_plot/decision_boundary.py", "line": null, "side": "RIGHT", "created_at": "2026-02-02T08:49:55+00:00" }, { "id": 2753395335, "user": "user_d16337ec046b", "body": "Yeah, I guess it depends on how familiar you are with mpl's colormaps...", "path": "sklearn/inspection/_plot/decision_boundary.py", "line": null, "side": "RIGHT", "created_at": "2026-02-02T09:32:11+00:00" } ], "meta": { "languages": [ "py", "rst" ], "touches_tests": true, "review_state_summary": { "COMMENTED": 49, "APPROVED": 3 }, "meaningful_comment_count": 78, "has_approval": true, "has_changes_requested": false, "total_review_comments": 79 } } { "_id": "690f4e344dc20ac8", "_schema_version": "1.0", "_cleaned_at": "2026-02-12T07:46:51.960591+00:00", "repo": "scikit-learn/scikit-learn", "repo_url": "https://github.com/scikit-learn/scikit-learn", "license_name": "BSD 3-Clause \"New\" or \"Revised\" License", "license_spdx": "BSD-3-Clause", "pr_number": 33014, "title": "FIX Resolve precompute in enet_path when check_input is False #32989", "body": "\n\n#### [NAME_REDACTED]/PRs\n\nFixes #32989\n\n#### What does this implement/fix? Explain your changes.\nThis PR fixes a `ValueError` in `enet_path` when `check_input=False`.\n\nBecause `_pre_fit` is skipped when `check_input=False`, the default value of the precompute parameter remained as the string 'auto', causing a crash in the solver dispatch logic. I have added a resolution block to handle 'auto', True, and sparse matrix constraints manually, ensuring the correct Gram matrix and Xy are available for the solver without duplicating the full validation suite.\n\nA non-regression test has been added to `test_coordinate_descent.py`.\n\n#### AI usage disclosure\n\nI used AI assistance for:\n- [ ] Code generation (e.g., when writing an implementation or fixing a bug)\n- [ ] Test/benchmark generation\n- [ ] Documentation (including examples)\n- [x] Research and understanding\n\n#### Any other comments?\nFirst-time contributor here! I've followed the internal logic of `_pre_fit` as closely as possible while maintaining performance and memory efficiency.\n\n", "author": "user_ea0b732e70b4", "created_at": "2026-01-06T12:00:29+00:00", "merged_at": "2026-01-21T18:30:05+00:00", "base_branch": "main", "head_branch": "fix-enet-auto", "additions": 16, "deletions": 2, "changed_files": 3, "files": [ { "filename": "doc/whats_new/upcoming_changes/sklearn.linear_model/33014.fix.rst", "status": "added", "additions": 6, "deletions": 0, "changes": 6, "patch": "@@ -0,0 +1,6 @@\n+- :func:`linear_model.enet_path` now correctly handles the ``precompute`` \n+ parameter when ``check_input=False``. Previously, the value of\n+ ``precompute`` was not properly treated which could lead to a ValueError.\n+ This also affects :class:`linear_model.ElasticNetCV`, :class:`linear_model.LassoCV`,\n+ :class:`linear_model.MultiTaskElasticNetCV` and :class:`linear_model.MultiTaskLassoCV`.\n+ By :user:`[NAME_REDACTED] `" }, { "filename": "sklearn/linear_model/_coordinate_descent.py", "status": "modified", "additions": 2, "deletions": 2, "changes": 4, "patch": "@@ -633,15 +633,15 @@ def enet_path(\n \n # X should have been passed through _pre_fit already if function is called\n # from ElasticNet.fit\n- if check_input:\n+ if check_input or precompute is not False:\n X, y, _, _, _, precompute, Xy = _pre_fit(\n X,\n y,\n Xy,\n precompute,\n fit_intercept=False,\n copy=False,\n- check_gram=True,\n+ check_gram=check_input,\n )\n if alphas is None:\n # fit_intercept and sample_weight have already been dealt with in calling" }, { "filename": "sklearn/linear_model/tests/test_coordinate_descent.py", "status": "modified", "additions": 8, "deletions": 0, "changes": 8, "patch": "@@ -1875,3 +1875,11 @@ def test_linear_model_cv_alphas(Estimator):\n else:\n clf.fit(X, y[:, 0])\n assert len(clf.alphas_) == 100\n+\n+\n+[USER_REDACTED].mark.parametrize(\"precompute\", [\"auto\", True, False])\n+def test_enet_path_check_input_false(precompute):\n+ \"\"\"Test enet_path works with check_input=False and various precompute settings.\"\"\"\n+ X, y = make_regression(n_samples=100, n_features=5, n_informative=2, random_state=0)\n+ X = np.asfortranarray(X)\n+ alphas, _, _ = enet_path(X, y, n_alphas=3, check_input=False, precompute=precompute)" } ], "reviews": [ { "id": 3667200226, "user": "user_d5ff8d3bf47d", "state": "COMMENTED", "body": null, "submitted_at": "2026-01-15T19:22:13+00:00" }, { "id": 3667203869, "user": "user_d5ff8d3bf47d", "state": "COMMENTED", "body": "Hi [USER_REDACTED] thank you for this PR, to get the ball rolling I added one nitpick for now, LGTM but will let [USER_REDACTED] also take a look to check the logic when check_input=False", "submitted_at": "2026-01-15T19:23:27+00:00" }, { "id": 3667889893, "user": "user_22bafe4fe1a9", "state": "COMMENTED", "body": null, "submitted_at": "2026-01-15T22:27:53+00:00" }, { "id": 3669333072, "user": "user_ea0b732e70b4", "state": "COMMENTED", "body": null, "submitted_at": "2026-01-16T07:31:20+00:00" }, { "id": 3669357790, "user": "user_ea0b732e70b4", "state": "COMMENTED", "body": null, "submitted_at": "2026-01-16T07:37:23+00:00" }, { "id": 3669360256, "user": "user_ea0b732e70b4", "state": "COMMENTED", "body": null, "submitted_at": "2026-01-16T07:38:01+00:00" }, { "id": 3669426775, "user": "user_ea0b732e70b4", "state": "COMMENTED", "body": null, "submitted_at": "2026-01-16T07:58:34+00:00" }, { "id": 3669631100, "user": "user_22bafe4fe1a9", "state": "COMMENTED", "body": null, "submitted_at": "2026-01-16T08:58:46+00:00" }, { "id": 3670116818, "user": "user_ea0b732e70b4", "state": "COMMENTED", "body": null, "submitted_at": "2026-01-16T10:29:03+00:00" }, { "id": 3677637259, "user": "user_501030d9d7e3", "state": "COMMENTED", "body": "Thank you for your work, [USER_REDACTED].\nI only have some minor comments on the test structure and the multi_output test case doesn't need to be added at all.", "submitted_at": "2026-01-19T13:30:11+00:00" }, { "id": 3670642461, "user": "user_22bafe4fe1a9", "state": "COMMENTED", "body": null, "submitted_at": "2026-01-19T15:56:32+00:00" }, { "id": 3679282760, "user": "user_ea0b732e70b4", "state": "COMMENTED", "body": null, "submitted_at": "2026-01-19T18:56:45+00:00" }, { "id": 3679285923, "user": "user_ea0b732e70b4", "state": "COMMENTED", "body": null, "submitted_at": "2026-01-19T18:58:24+00:00" }, { "id": 3679288413, "user": "user_ea0b732e70b4", "state": "COMMENTED", "body": null, "submitted_at": "2026-01-19T18:59:44+00:00" }, { "id": 3679295498, "user": "user_ea0b732e70b4", "state": "COMMENTED", "body": null, "submitted_at": "2026-01-19T19:03:41+00:00" }, { "id": 3679296215, "user": "user_ea0b732e70b4", "state": "COMMENTED", "body": null, "submitted_at": "2026-01-19T19:04:04+00:00" }, { "id": 3679409264, "user": "user_ea0b732e70b4", "state": "COMMENTED", "body": null, "submitted_at": "2026-01-19T19:50:05+00:00" }, { "id": 3681699437, "user": "user_501030d9d7e3", "state": "COMMENTED", "body": null, "submitted_at": "2026-01-20T11:23:07+00:00" }, { "id": 3681707014, "user": "user_501030d9d7e3", "state": "COMMENTED", "body": null, "submitted_at": "2026-01-20T11:25:10+00:00" }, { "id": 3681715260, "user": "user_501030d9d7e3", "state": "COMMENTED", "body": null, "submitted_at": "2026-01-20T11:27:29+00:00" }, { "id": 3681720061, "user": "user_501030d9d7e3", "state": "APPROVED", "body": "I agree we should mention all the affected functions and methods in the changelog entry.\n\nOtherwise looks fine. Approving.\n\nThanks for your work, [USER_REDACTED]!", "submitted_at": "2026-01-20T11:28:51+00:00" }, { "id": 3681973208, "user": "user_ea0b732e70b4", "state": "COMMENTED", "body": null, "submitted_at": "2026-01-20T12:35:20+00:00" }, { "id": 3682062854, "user": "user_22bafe4fe1a9", "state": "COMMENTED", "body": null, "submitted_at": "2026-01-20T12:59:48+00:00" }, { "id": 3685860667, "user": "user_ea0b732e70b4", "state": "COMMENTED", "body": null, "submitted_at": "2026-01-21T08:12:00+00:00" }, { "id": 3686186333, "user": "user_22bafe4fe1a9", "state": "COMMENTED", "body": null, "submitted_at": "2026-01-21T09:28:11+00:00" }, { "id": 3686360662, "user": "user_ea0b732e70b4", "state": "COMMENTED", "body": null, "submitted_at": "2026-01-21T10:03:17+00:00" }, { "id": 3686539483, "user": "user_501030d9d7e3", "state": "COMMENTED", "body": null, "submitted_at": "2026-01-21T10:46:48+00:00" }, { "id": 3686640961, "user": "user_ea0b732e70b4", "state": "COMMENTED", "body": null, "submitted_at": "2026-01-21T11:12:02+00:00" }, { "id": 3687690110, "user": "user_22bafe4fe1a9", "state": "COMMENTED", "body": null, "submitted_at": "2026-01-21T14:57:07+00:00" }, { "id": 3688479087, "user": "user_ea0b732e70b4", "state": "COMMENTED", "body": null, "submitted_at": "2026-01-21T17:23:18+00:00" }, { "id": 3688766182, "user": "user_22bafe4fe1a9", "state": "COMMENTED", "body": null, "submitted_at": "2026-01-21T18:25:04+00:00" }, { "id": 3688782514, "user": "user_22bafe4fe1a9", "state": "APPROVED", "body": null, "submitted_at": "2026-01-21T18:28:22+00:00" } ], "review_comments": [ { "id": 2695656298, "user": "user_d5ff8d3bf47d", "body": "I suppose since auto is the default we can remove it here and recomment this into ```Case 1: Testing default=\"auto\"```\n\n```suggestion\n alphas, _, _ = enet_path(X, y, n_alphas=3, check_input=False)\n```", "path": "sklearn/linear_model/tests/test_coordinate_descent.py", "line": null, "side": "RIGHT", "created_at": "2026-01-15T19:22:13+00:00" }, { "id": 2696180240, "user": "user_22bafe4fe1a9", "body": "What was wrong, what does it fix?", "path": "doc/whats_new/upcoming_changes/sklearn.linear_model/33014.fix.rst", "line": null, "side": "RIGHT", "created_at": "2026-01-15T22:24:20+00:00" }, { "id": 2696181174, "user": "user_22bafe4fe1a9", "body": "```suggestion\n \"\"\"Test that ....\"\"\"\n```", "path": "sklearn/linear_model/tests/test_coordinate_descent.py", "line": null, "side": "RIGHT", "created_at": "2026-01-15T22:24:34+00:00" }, { "id": 2696184469, "user": "user_22bafe4fe1a9", "body": "Please put imports at the top of the file. As both are already imported, simply delete it here.", "path": "sklearn/linear_model/tests/test_coordinate_descent.py", "line": null, "side": "RIGHT", "created_at": "2026-01-15T22:25:53+00:00" }, { "id": 2696185572, "user": "user_22bafe4fe1a9", "body": "```suggestion\n```", "path": "sklearn/linear_model/_coordinate_descent.py", "line": null, "side": "RIGHT", "created_at": "2026-01-15T22:26:22+00:00" }, { "id": 2696189263, "user": "user_22bafe4fe1a9", "body": "Can't we call _pre_fit or some other function here instead of replicating its logic?", "path": "sklearn/linear_model/_coordinate_descent.py", "line": null, "side": "RIGHT", "created_at": "2026-01-15T22:27:48+00:00" }, { "id": 2697321262, "user": "user_ea0b732e70b4", "body": "Great point. I've made it more descriptive.", "path": "doc/whats_new/upcoming_changes/sklearn.linear_model/33014.fix.rst", "line": null, "side": "RIGHT", "created_at": "2026-01-16T07:31:20+00:00" }, { "id": 2697336567, "user": "user_ea0b732e70b4", "body": "Done. Good catch.", "path": "sklearn/linear_model/tests/test_coordinate_descent.py", "line": null, "side": "RIGHT", "created_at": "2026-01-16T07:37:23+00:00" }, { "id": 2697338151, "user": "user_ea0b732e70b4", "body": "Good suggestion, it's done now.", "path": "sklearn/linear_model/tests/test_coordinate_descent.py", "line": null, "side": "RIGHT", "created_at": "2026-01-16T07:38:01+00:00" }, { "id": 2697392177, "user": "user_ea0b732e70b4", "body": "Definitely. Originally, I didn't call _pre_fit to avoid unnecessary operations and overhead, but I believe essentially the same effect can be achieved by [NAME_REDACTED] `fit_intercept=False` and `copy=False`. By calling _pre_fit, the code is easier to maintain, so it was a great suggestion. Thanks!", "path": "sklearn/linear_model/_coordinate_descent.py", "line": null, "side": "RIGHT", "created_at": "2026-01-16T07:58:34+00:00" }, { "id": 2697559352, "user": "user_22bafe4fe1a9", "body": "This can be removed here. A few lines further down, _pre_fit is called. Just the if-condition has to be extended.", "path": "sklearn/linear_model/_coordinate_descent.py", "line": null, "side": "RIGHT", "created_at": "2026-01-16T08:58:42+00:00" }, { "id": 2697925317, "user": "user_ea0b732e70b4", "body": "Done. I've updated the PR to remove the if block you mentioned and instead extend the existing if condition: `if check_input or precompute is not False`.\nThis ensures _pre_fit is called whenever setup is required (resolving 'auto', True, or arrays) while maintaining the optimization to skip the call entirely when `check_input=False` and `precompute=False`. Verified across all parameter combinations.", "path": "sklearn/linear_model/_coordinate_descent.py", "line": null, "side": "RIGHT", "created_at": "2026-01-16T10:29:03+00:00" }, { "id": 2698323509, "user": "user_22bafe4fe1a9", "body": "Isn‘t it also `lasso_path`?", "path": "doc/whats_new/upcoming_changes/sklearn.linear_model/33014.fix.rst", "line": 1, "side": "RIGHT", "created_at": "2026-01-16T12:23:34+00:00" }, { "id": 2698330370, "user": "user_22bafe4fe1a9", "body": "„Previously, the value of `precompute` was not properly treated which could lead to a ValueError.“\nJust a suggestion.", "path": "doc/whats_new/upcoming_changes/sklearn.linear_model/33014.fix.rst", "line": null, "side": "RIGHT", "created_at": "2026-01-16T12:26:13+00:00" }, { "id": 2704380492, "user": "user_501030d9d7e3", "body": "```suggestion\n```\n\nThis is uncommon. But instead you can add \"Regression test for #32989\" in the test docstring.", "path": "sklearn/linear_model/tests/test_coordinate_descent.py", "line": null, "side": "RIGHT", "created_at": "2026-01-19T11:30:40+00:00" }, { "id": 2704386646, "user": "user_501030d9d7e3", "body": "```suggestion\n```\n\nWe also don't need these comments. Instead you could parametrise the precompute param with `[USER_REDACTED].mark.parametrize` which also makes the different test cases more visible and debuggable in case of future regressions.", "path": "sklearn/linear_model/tests/test_coordinate_descent.py", "line": null, "side": "RIGHT", "created_at": "2026-01-19T11:32:37+00:00" }, { "id": 2704393319, "user": "user_501030d9d7e3", "body": "Why do we need to assert `len(alphas) == 3` here? `enet_path` raised during execution before, so testing if it can be called without errors should be enough?", "path": "sklearn/linear_model/tests/test_coordinate_descent.py", "line": null, "side": "RIGHT", "created_at": "2026-01-19T11:34:54+00:00" }, { "id": 2704467625, "user": "user_501030d9d7e3", "body": "I would think we don't need this test case, since in the \"multi_output\" case, `precompute` is not used at all.", "path": "sklearn/linear_model/tests/test_coordinate_descent.py", "line": null, "side": "RIGHT", "created_at": "2026-01-19T11:58:03+00:00" }, { "id": 2704776917, "user": "user_501030d9d7e3", "body": "This is fine. When `precompute` is a matrix, it gets passed through `_pre_fit`.", "path": "sklearn/linear_model/_coordinate_descent.py", "line": 636, "side": "RIGHT", "created_at": "2026-01-19T13:27:37+00:00" }, { "id": 2705310699, "user": "user_22bafe4fe1a9", "body": "I am not the biggest fan of issue numbers in test descriptions. I prefer a docstring or code comment that explains what is tested (with or without issue number): \"Test that ...\" (The unittest package for R is named [testthat](https://testthat.r-lib.org/))", "path": "sklearn/linear_model/tests/test_coordinate_descent.py", "line": null, "side": "RIGHT", "created_at": "2026-01-19T15:55:26+00:00" }, { "id": 2705815743, "user": "user_ea0b732e70b4", "body": "I agree, it can be safely removed. I added it just out of habit (I tend to add a simple check in my own code debugging to verify a certain critical line ran as intended).", "path": "sklearn/linear_model/tests/test_coordinate_descent.py", "line": null, "side": "RIGHT", "created_at": "2026-01-19T18:56:45+00:00" }, { "id": 2705819062, "user": "user_ea0b732e70b4", "body": "I added it to reach the codecov threshold, as otherwise it would just fall short by a couple percentage points. I will try deleting it and checking codecov again.", "path": "sklearn/linear_model/tests/test_coordinate_descent.py", "line": null, "side": "RIGHT", "created_at": "2026-01-19T18:58:24+00:00" }, { "id": 2705821460, "user": "user_ea0b732e70b4", "body": "Excellent, thanks.", "path": "sklearn/linear_model/_coordinate_descent.py", "line": 636, "side": "RIGHT", "created_at": "2026-01-19T18:59:44+00:00" }, { "id": 2705828595, "user": "user_ea0b732e70b4", "body": "I wrote enet_path because that's where I came across the bug. But I think you're right, as any code that relies on _coordinate_descent.py should benefit from this fix. I can also add a reference to `lasso_path`if you feel it will be helpful.", "path": "doc/whats_new/upcoming_changes/sklearn.linear_model/33014.fix.rst", "line": 1, "side": "RIGHT", "created_at": "2026-01-19T19:03:40+00:00" }, { "id": 2705829291, "user": "user_ea0b732e70b4", "body": "Sounds good, thanks!", "path": "doc/whats_new/upcoming_changes/sklearn.linear_model/33014.fix.rst", "line": null, "side": "RIGHT", "created_at": "2026-01-19T19:04:04+00:00" }, { "id": 2705923106, "user": "user_ea0b732e70b4", "body": "Great suggestion. It's done now.", "path": "sklearn/linear_model/tests/test_coordinate_descent.py", "line": null, "side": "RIGHT", "created_at": "2026-01-19T19:50:05+00:00" }, { "id": 2707930545, "user": "user_501030d9d7e3", "body": "That's why I had suggested to _add_ it, [USER_REDACTED].\nIt is also fine as it is.", "path": "sklearn/linear_model/tests/test_coordinate_descent.py", "line": null, "side": "RIGHT", "created_at": "2026-01-20T11:23:07+00:00" }, { "id": 2707937418, "user": "user_501030d9d7e3", "body": "I see. Now the replicated code is gone, the replicated test is also not needed. Happy that codecov is happy. :woman_dancing:", "path": "sklearn/linear_model/tests/test_coordinate_descent.py", "line": null, "side": "RIGHT", "created_at": "2026-01-20T11:25:10+00:00" }, { "id": 2707945219, "user": "user_501030d9d7e3", "body": "> I added it just out of habit \n\nSure, I understand. We need to be a bit nit picky in general, since scikit-learn hopefully is in need to stay maintainable for another 19 years and more.", "path": "sklearn/linear_model/tests/test_coordinate_descent.py", "line": null, "side": "RIGHT", "created_at": "2026-01-20T11:27:29+00:00" }, { "id": 2708169154, "user": "user_ea0b732e70b4", "body": "And as a heavy user of scikit-learn I am glad you are \"nit picky\"!", "path": "sklearn/linear_model/tests/test_coordinate_descent.py", "line": null, "side": "RIGHT", "created_at": "2026-01-20T12:35:19+00:00" }, { "id": 2708245393, "user": "user_22bafe4fe1a9", "body": "```suggestion\n if check_input or precompute:\n```\nNot 100% sure. Do we want to enter the if-condition if precompute is an ndarray?", "path": "sklearn/linear_model/_coordinate_descent.py", "line": 636, "side": "RIGHT", "created_at": "2026-01-20T12:57:30+00:00" }, { "id": 2711425247, "user": "user_ea0b732e70b4", "body": "I see your logic: if `check_input=False` then, to respect the current documentation for `enet_path`, the Gram should not be checked. To align with the documentation while ensuring the solver remains robust, I propose keeping the `precompute is not False` check (to avoid the NumPy truth-value crash that would happen with just `precompute`) but update the call to `_pre_fit`: by setting `check_gram=check_input`, we ensure that if a user specifies `check_input=False`, the Gram matrix validation is indeed skipped as documented, while still allowing `_pre_fit` to handle the essential memory alignment and correct Xy initialization required by [NAME_REDACTED]", "path": "sklearn/linear_model/_coordinate_descent.py", "line": 636, "side": "RIGHT", "created_at": "2026-01-21T08:12:00+00:00" }, { "id": 2711699448, "user": "user_22bafe4fe1a9", "body": "Then the following reads better:\n```suggestion\n if check_input or precompute is True: # numpy arrays as precompute must not enter\n```", "path": "sklearn/linear_model/_coordinate_descent.py", "line": 636, "side": "RIGHT", "created_at": "2026-01-21T09:28:11+00:00" }, { "id": 2711845035, "user": "user_ea0b732e70b4", "body": "I'm concerned that `if precompute is True` would reintroduce the very bug we are trying to fix: when `precompute=\"auto\"` (the default), the block would be skipped and the solver would receive a string instead of the required data.", "path": "sklearn/linear_model/_coordinate_descent.py", "line": 636, "side": "RIGHT", "created_at": "2026-01-21T10:03:16+00:00" }, { "id": 2712004959, "user": "user_501030d9d7e3", "body": "Yes, if a matrix input should be excluded, we still need to run `_pre_fit` for `\"auto\"` and `True` inputs.", "path": "sklearn/linear_model/_coordinate_descent.py", "line": 636, "side": "RIGHT", "created_at": "2026-01-21T10:46:48+00:00" }, { "id": 2712095929, "user": "user_ea0b732e70b4", "body": "Agreed. To be clear, `_pre_fit` is explicitly designed to handle ndarray inputs (for memory alignment and Xy initialization). There's no fundamental reason to exclude them from the block aside from the validation overhead, which I proposed to address by passing `check_gram=check_input`. This approach aligns with the `enet_path` documentation while remaining efficient, robust, and future-proof.", "path": "sklearn/linear_model/_coordinate_descent.py", "line": 636, "side": "RIGHT", "created_at": "2026-01-21T11:12:02+00:00" }, { "id": 2712948215, "user": "user_22bafe4fe1a9", "body": "I don’t understand. `x is True` and `x is not False` evaluate to the same result - or I don‘t understand Python!", "path": "sklearn/linear_model/_coordinate_descent.py", "line": 636, "side": "RIGHT", "created_at": "2026-01-21T14:57:07+00:00" }, { "id": 2713591406, "user": "user_ea0b732e70b4", "body": "In Python, `x is not False` is not equivalent to `x is True` because the former checks if `x` is something other than the singleton `False` object. In this module, `precompute` can be a boolean but also the string `\"auto\"` (the default) or an `ndarray`. For both strings and arrays, `is True` would evaluate to `False`, skipping the required initialization, whereas `is not False` correctly evaluates to `True`.", "path": "sklearn/linear_model/_coordinate_descent.py", "line": 636, "side": "RIGHT", "created_at": "2026-01-21T17:23:18+00:00" }, { "id": 2713819172, "user": "user_22bafe4fe1a9", "body": "That's right.", "path": "sklearn/linear_model/_coordinate_descent.py", "line": 636, "side": "RIGHT", "created_at": "2026-01-21T18:25:03+00:00" } ], "meta": { "languages": [ "py", "rst" ], "touches_tests": true, "review_state_summary": { "COMMENTED": 30, "APPROVED": 2 }, "meaningful_comment_count": 39, "has_approval": true, "has_changes_requested": false, "total_review_comments": 39 } } { "_id": "e1ae835bb68866a8", "_schema_version": "1.0", "_cleaned_at": "2026-02-12T07:46:51.960591+00:00", "repo": "scikit-learn/scikit-learn", "repo_url": "https://github.com/scikit-learn/scikit-learn", "license_name": "BSD 3-Clause \"New\" or \"Revised\" License", "license_spdx": "BSD-3-Clause", "pr_number": 32988, "title": "FIX remove the special check in `test_enet_ols_consistency`", "body": "\n\n#### [NAME_REDACTED]/PRs\n\nFixes #32987\n\n#### What does this implement/fix? Explain your changes.\n- This removes the special condition that checks `se_enet <= se_ols`\n\n#### AI usage disclosure\n\nI used AI assistance for:\n- [ ] Code generation (e.g., when writing an implementation or fixing a bug)\n- [ ] Test/benchmark generation\n- [ ] Documentation (including examples)\n- [x] Research and understanding\n\n#### Any other comments?\nCC: [USER_REDACTED] \n\n", "author": "user_3c90b5520ec5", "created_at": "2026-01-02T10:38:04+00:00", "merged_at": "2026-01-02T19:34:41+00:00", "base_branch": "main", "head_branch": "fix-enet-ols-test", "additions": 7, "deletions": 10, "changed_files": 1, "files": [ { "filename": "sklearn/linear_model/tests/test_coordinate_descent.py", "status": "modified", "additions": 7, "deletions": 10, "changes": 17, "patch": "@@ -1607,9 +1607,9 @@ def test_enet_ridge_consistency(ridge_alpha, precompute, n_targets):\n [USER_REDACTED].mark.filterwarnings(\"ignore:With alpha=0, this algorithm:UserWarning\")\n [USER_REDACTED].mark.parametrize(\"precompute\", [False, True])\n [USER_REDACTED].mark.parametrize(\"effective_rank\", [None, 10])\n-def test_enet_ols_consistency(precompute, effective_rank):\n+def test_enet_ols_consistency(precompute, effective_rank, global_random_seed):\n \"\"\"Test that ElasticNet(alpha=0) converges to the same solution as OLS.\"\"\"\n- rng = np.random.RandomState(42)\n+ rng = np.random.RandomState(global_random_seed)\n n_samples = 300\n X, y = make_regression(\n n_samples=n_samples,\n@@ -1628,16 +1628,13 @@ def test_enet_ols_consistency(precompute, effective_rank):\n # Might be a singular problem, so check for same predictions\n assert_allclose(enet.predict(X), ols.predict(X))\n # and for similar objective function (squared error)\n- se_ols = np.sum((y - ols.predict(X)) ** 2)\n- se_enet = np.sum((y - enet.predict(X)) ** 2)\n- if precompute:\n- assert se_ols <= 1e-20\n- assert se_enet <= 1e-20\n- else:\n- assert se_enet <= se_ols <= 1e-20 # Who would have thought that?\n+ se_ols = np.sum(sw * (y - ols.predict(X)) ** 2)\n+ se_enet = np.sum(sw * (y - enet.predict(X)) ** 2)\n+ assert se_ols <= 1e-19\n+ assert se_enet <= 1e-19\n # We check equal coefficients, but \"only\" with absolute tolerance.\n assert_allclose(enet.coef_, ols.coef_, atol=1e-11)\n- assert_allclose(enet.intercept_, ols.intercept_, atol=1e-12)\n+ assert_allclose(enet.intercept_, ols.intercept_, atol=1e-11)\n \n \n [USER_REDACTED].mark.parametrize(" } ], "reviews": [ { "id": 3623728602, "user": "user_22bafe4fe1a9", "state": "COMMENTED", "body": "[USER_REDACTED] Thanks for the fix.\nMy suggestions pass locally for all random seeds (`SKLEARN_TESTS_GLOBAL_RANDOM_SEED=\"all\" pytest -x sklearn/linear_model/tests/test_coordinate_descent.py::test_enet_ols_consistency`).", "submitted_at": "2026-01-02T19:05:18+00:00" }, { "id": 3623758473, "user": "user_22bafe4fe1a9", "state": "APPROVED", "body": null, "submitted_at": "2026-01-02T19:25:50+00:00" } ], "review_comments": [ { "id": 2658251749, "user": "user_22bafe4fe1a9", "body": "```suggestion\nse_ols = np.sum(sw * (y - ols.predict(X)) ** 2)\nse_enet = np.sum(sw * (y - enet.predict(X)) ** 2)\n```", "path": "sklearn/linear_model/tests/test_coordinate_descent.py", "line": null, "side": "RIGHT", "created_at": "2026-01-02T19:03:30+00:00" }, { "id": 2658252670, "user": "user_22bafe4fe1a9", "body": "```suggestion\n assert se_ols <= 1e-19\n assert se_enet <= 1e-19\n```", "path": "sklearn/linear_model/tests/test_coordinate_descent.py", "line": null, "side": "RIGHT", "created_at": "2026-01-02T19:04:16+00:00" }, { "id": 2658253019, "user": "user_22bafe4fe1a9", "body": "```suggestion\n assert_allclose(enet.intercept_, ols.intercept_, atol=1e-11)\n```", "path": "sklearn/linear_model/tests/test_coordinate_descent.py", "line": null, "side": "RIGHT", "created_at": "2026-01-02T19:04:32+00:00" } ], "meta": { "languages": [ "py" ], "touches_tests": true, "review_state_summary": { "COMMENTED": 1, "APPROVED": 1 }, "meaningful_comment_count": 3, "has_approval": true, "has_changes_requested": false, "total_review_comments": 3 } } { "_id": "01a01beabc131c27", "_schema_version": "1.0", "_cleaned_at": "2026-02-12T07:46:51.960591+00:00", "repo": "scikit-learn/scikit-learn", "repo_url": "https://github.com/scikit-learn/scikit-learn", "license_name": "BSD 3-Clause \"New\" or \"Revised\" License", "license_spdx": "BSD-3-Clause", "pr_number": 32985, "title": "FEA: Add Array API support to `pairwise_distances_argmin`", "body": "\n\n#### [NAME_REDACTED]/PRs\n\nTowards #26024 \n\n#### What does this implement/fix? Explain your changes.\nAdds array API support for `pairwise_distances_argmin`\n\n#### AI usage disclosure\n\nI used AI assistance for:\n- [x] Code generation (e.g., when writing an implementation or fixing a bug)\n- [ ] Test/benchmark generation\n- [ ] Documentation (including examples)\n- [x] Research and understanding\n\n#### Any other comments?\n\n", "author": "user_94669f1a0fd7", "created_at": "2026-01-01T20:27:03+00:00", "merged_at": "2026-01-27T13:04:33+00:00", "base_branch": "main", "head_branch": "pairwise-arrayapi", "additions": 12, "deletions": 6, "changed_files": 4, "files": [ { "filename": "doc/modules/array_api.rst", "status": "modified", "additions": 1, "deletions": 0, "changes": 1, "patch": "@@ -200,6 +200,7 @@ Metrics\n - :func:`sklearn.metrics.pairwise.cosine_similarity`\n - :func:`sklearn.metrics.pairwise.cosine_distances`\n - :func:`sklearn.metrics.pairwise.pairwise_distances` (only supports \"cosine\", \"euclidean\", \"manhattan\" and \"l2\" metrics)\n+- :func:`sklearn.metrics.pairwise.pairwise_distances_argmin`\n - :func:`sklearn.metrics.pairwise.euclidean_distances` (see :ref:`device_support_for_float64`)\n - :func:`sklearn.metrics.pairwise.laplacian_kernel`\n - :func:`sklearn.metrics.pairwise.linear_kernel`" }, { "filename": "doc/whats_new/upcoming_changes/array-api/32985.feature.rst", "status": "added", "additions": 2, "deletions": 0, "changes": 2, "patch": "@@ -0,0 +1,2 @@\n+- :func:`sklearn.metrics.pairwise.pairwise_distances_argmin` now supports array API\n+ compatible inputs. By :user:`[NAME_REDACTED] `." }, { "filename": "sklearn/metrics/pairwise.py", "status": "modified", "additions": 7, "deletions": 6, "changes": 13, "patch": "@@ -650,7 +650,8 @@ def _argmin_reduce(dist, start):\n # `start` is specified in the signature but not used. This is because the higher\n # order `pairwise_distances_chunked` function needs reduction functions that are\n # passed as argument to have a two arguments signature.\n- return dist.argmin(axis=1)\n+ xp, _ = get_namespace(dist)\n+ return xp.argmin(dist, axis=1)\n \n \n _VALID_METRICS = [\n@@ -937,14 +938,15 @@ def pairwise_distances_argmin(X, Y, *, axis=1, metric=\"euclidean\", metric_kwargs\n \"\"\"\n ensure_all_finite = \"allow-nan\" if metric == \"nan_euclidean\" else True\n X, Y = check_pairwise_arrays(X, Y, ensure_all_finite=ensure_all_finite)\n+ xp, _ = get_namespace(X, Y)\n \n if axis == 0:\n X, Y = Y, X\n \n if metric_kwargs is None:\n metric_kwargs = {}\n \n- if ArgKmin.is_usable_for(X, Y, metric):\n+ if ArgKmin.is_usable_for(X, Y, metric) and _is_numpy_namespace(xp):\n # This is an adaptor for one \"sqeuclidean\" specification.\n # For this backend, we can directly use \"sqeuclidean\".\n if metric_kwargs.get(\"squared\", False) and metric == \"euclidean\":\n@@ -972,14 +974,13 @@ def pairwise_distances_argmin(X, Y, *, axis=1, metric=\"euclidean\", metric_kwargs\n # Turn off check for finiteness because this is costly and because arrays\n # have already been validated.\n with config_context(assume_finite=True):\n- indices = np.concatenate(\n+ indices = xp.concat(\n list(\n- # This returns an np.ndarray generator whose arrays we need\n- # to flatten into one.\n pairwise_distances_chunked(\n X, Y, reduce_func=_argmin_reduce, metric=metric, **metric_kwargs\n )\n- )\n+ ),\n+ axis=0,\n )\n \n return indices" }, { "filename": "sklearn/metrics/tests/test_common.py", "status": "modified", "additions": 2, "deletions": 0, "changes": 2, "patch": "@@ -74,6 +74,7 @@\n paired_euclidean_distances,\n paired_manhattan_distances,\n pairwise_distances,\n+ pairwise_distances_argmin,\n pairwise_kernels,\n polynomial_kernel,\n rbf_kernel,\n@@ -2454,6 +2455,7 @@ def check_array_api_metric_pairwise(metric, array_namespace, device, dtype_name)\n check_array_api_binary_classification_metric,\n ],\n pairwise_distances: [check_array_api_metric_pairwise],\n+ pairwise_distances_argmin: [check_array_api_metric_pairwise],\n }" } ], "reviews": [ { "id": 3622039669, "user": "user_94669f1a0fd7", "state": "COMMENTED", "body": null, "submitted_at": "2026-01-01T20:32:32+00:00" }, { "id": 3622347923, "user": "user_94669f1a0fd7", "state": "COMMENTED", "body": null, "submitted_at": "2026-01-02T07:03:19+00:00" }, { "id": 3638840640, "user": "user_d5b9cb906259", "state": "COMMENTED", "body": null, "submitted_at": "2026-01-08T10:46:35+00:00" }, { "id": 3659707163, "user": "user_3c90b5520ec5", "state": "DISMISSED", "body": "LGTM. Thanks [USER_REDACTED]", "submitted_at": "2026-01-14T09:26:28+00:00" }, { "id": 3660773085, "user": "user_d5b9cb906259", "state": "COMMENTED", "body": null, "submitted_at": "2026-01-14T13:35:47+00:00" }, { "id": 3666419568, "user": "user_94669f1a0fd7", "state": "COMMENTED", "body": null, "submitted_at": "2026-01-15T16:08:22+00:00" }, { "id": 3666750162, "user": "user_3c90b5520ec5", "state": "APPROVED", "body": "LGTM. Thank you [USER_REDACTED]", "submitted_at": "2026-01-15T17:23:41+00:00" } ], "review_comments": [ { "id": 2656594853, "user": "user_94669f1a0fd7", "body": "Is it safe to assume that any array namespace will have the `concat` method? If so, it makes the fallback unnecessary and I'll remove it. Requesting confirmation from a reviewer", "path": "sklearn/metrics/pairwise.py", "line": null, "side": "RIGHT", "created_at": "2026-01-01T20:32:26+00:00" }, { "id": 2656969934, "user": "user_94669f1a0fd7", "body": "This line seems to be impacting code coverage too", "path": "sklearn/metrics/pairwise.py", "line": null, "side": "RIGHT", "created_at": "2026-01-02T07:03:19+00:00" }, { "id": 2671853342, "user": "user_d5b9cb906259", "body": "https://data-apis.org/array-api/latest/API_specification/generated/array_api.concat.html#concat is the specification in the array API for `concat`.\n\nThis means it should always be available and we don't need this `if` statement and the comment", "path": "sklearn/metrics/pairwise.py", "line": null, "side": "RIGHT", "created_at": "2026-01-08T10:46:35+00:00" }, { "id": 2690455833, "user": "user_d5b9cb906259", "body": "Instead of the diff (adding a new variable `indices_list`), you could just change `np.concatenate` to `xp.concat`. I think.", "path": "sklearn/metrics/pairwise.py", "line": 975, "side": "LEFT", "created_at": "2026-01-14T13:35:47+00:00" }, { "id": 2695028875, "user": "user_94669f1a0fd7", "body": "Updated", "path": "sklearn/metrics/pairwise.py", "line": 975, "side": "LEFT", "created_at": "2026-01-15T16:08:22+00:00" } ], "meta": { "languages": [ "py", "rst" ], "touches_tests": true, "review_state_summary": { "COMMENTED": 5, "DISMISSED": 1, "APPROVED": 1 }, "meaningful_comment_count": 4, "has_approval": true, "has_changes_requested": false, "total_review_comments": 5 } } { "_id": "df030263d5092f72", "_schema_version": "1.0", "_cleaned_at": "2026-02-12T07:46:51.960591+00:00", "repo": "scikit-learn/scikit-learn", "repo_url": "https://github.com/scikit-learn/scikit-learn", "license_name": "BSD 3-Clause \"New\" or \"Revised\" License", "license_spdx": "BSD-3-Clause", "pr_number": 32969, "title": "DOC Switch insecure http links to https", "body": "I updated several insecure `http` links to `https` in the documentation.\n\nFiles updated:\n* `doc/about.rst`\n* `doc/developers/contributing.rst`\n* `doc/developers/performance.rst`", "author": "user_481b55069ad2", "created_at": "2025-12-30T07:38:36+00:00", "merged_at": "2026-01-07T16:23:05+00:00", "base_branch": "main", "head_branch": "doc-fix-https-links", "additions": 38, "deletions": 38, "changed_files": 18, "files": [ { "filename": "doc/about.rst", "status": "modified", "additions": 2, "deletions": 2, "changes": 4, "patch": "@@ -385,13 +385,13 @@ program.\n - 2013 - [NAME_REDACTED], Nicolas Trésegnie\n - 2014 - [NAME_REDACTED], [NAME_REDACTED], [NAME_REDACTED], [NAME_REDACTED]\n - 2015 - `Raghav RV `_, [NAME_REDACTED]\n-- 2016 - `[NAME_REDACTED] `_, `[NAME_REDACTED] `_\n+- 2016 - `[NAME_REDACTED] `_, `[NAME_REDACTED] `_\n \n .. _Vlad Niculae: https://vene.ro/\n \n ...................\n \n-The `NeuroDebian `_ project providing `Debian\n+The `NeuroDebian `_ project providing `Debian\n `_ packaging and contributions is supported by\n `Dr. James V. Haxby `_ (`[NAME_REDACTED] `_)." }, { "filename": "doc/conf.py", "status": "modified", "additions": 1, "deletions": 1, "changes": 2, "patch": "@@ -910,7 +910,7 @@ def setup(app):\n r\"^..?/\",\n # ignore links to specific pdf pages because linkcheck does not handle them\n # ('utf-8' codec can't decode byte error)\n- r\"http://www.utstat.toronto.edu/~rsalakhu/sta4273/notes/Lecture2.pdf#page=.*\",\n+ r\"https://www.utstat.toronto.edu/~rsalakhu/sta4273/notes/Lecture2.pdf#page=.*\",\n (\n \"https://www.fordfoundation.org/media/2976/roads-and-bridges\"\n \"-the-unseen-labor-behind-our-digital-infrastructure.pdf#page=.*\"" }, { "filename": "doc/developers/contributing.rst", "status": "modified", "additions": 2, "deletions": 2, "changes": 4, "patch": "@@ -358,7 +358,7 @@ line\n .. topic:: [NAME_REDACTED] `Git documentation `_ and\n- http://try.github.io are excellent resources to get started with git,\n+ https://try.github.io are excellent resources to get started with git,\n and understanding all of the commands shown here.\n \n .. _pr_checklist:\n@@ -508,7 +508,7 @@ profiling and Cython optimizations.\n \n For two very well documented and more detailed guides on development\n workflow, please pay a visit to the `[NAME_REDACTED]\n- `_ -\n+ `_ -\n and the `[NAME_REDACTED] for Developers\n `_\n sections." }, { "filename": "doc/developers/performance.rst", "status": "modified", "additions": 1, "deletions": 1, "changes": 2, "patch": "@@ -311,7 +311,7 @@ standalone function in a ``.pyx`` file, add static type declarations and\n then use Cython to generate a C program suitable to be compiled as a\n Python extension module.\n \n-The `Cython's documentation `_ contains a tutorial and\n+The `Cython's documentation `_ contains a tutorial and\n reference guide for developing such a module.\n For more information about developing in Cython for scikit-learn, see :ref:`cython`." }, { "filename": "doc/install.rst", "status": "modified", "additions": 1, "deletions": 1, "changes": 2, "patch": "@@ -295,7 +295,7 @@ It can be installed using ``dnf``:\n NetBSD\n ------\n \n-scikit-learn is available via `pkgsrc-wip `_:\n+scikit-learn is available via `pkgsrc-wip `_:\n https://pkgsrc.se/math/py-scikit-learn" }, { "filename": "doc/model_persistence.rst", "status": "modified", "additions": 2, "deletions": 2, "changes": 4, "patch": "@@ -149,7 +149,7 @@ facilitate the conversion of the data models between different machine learning\n frameworks, and to improve their portability on different computing\n architectures. More details are available from the `ONNX tutorial\n `__. To convert scikit-learn model to `ONNX`\n-`sklearn-onnx `__ has been developed. However,\n+`sklearn-onnx `__ has been developed. However,\n not all scikit-learn models are supported, and it is limited to the core\n scikit-learn and does not support most third party estimators. One can write a\n custom converter for third party or custom estimators, but the documentation to\n@@ -159,7 +159,7 @@ do that is sparse and it might be challenging to do so.\n \n To convert the model to `ONNX` format, you need to give the converter some\n information about the input as well, about which you can read more `here\n- `__::\n+ `__::\n \n from skl2onnx import to_onnx\n onx = to_onnx(clf, X[:1].astype(numpy.float32), target_opset=12)" }, { "filename": "doc/modules/clustering.rst", "status": "modified", "additions": 3, "deletions": 3, "changes": 6, "patch": "@@ -847,7 +847,7 @@ clusters from Bisecting K-Means are well ordered and create quite a visible hier\n .. dropdown:: References\n \n * `\"A Comparison of [NAME_REDACTED]\"\n- `_ Michael\n+ `_ [NAME_REDACTED], [NAME_REDACTED] and [NAME_REDACTED], Department of [NAME_REDACTED] and\n Egineering, University of Minnesota (June 2000)\n * `\"[NAME_REDACTED] of K-Means and Bisecting K-[NAME_REDACTED] in Weblog\n@@ -1584,7 +1584,7 @@ Bad (e.g. independent labelings) have non-positive scores::\n * Strehl, Alexander, and [NAME_REDACTED] (2002). \"Cluster ensembles - a\n knowledge reuse framework for combining multiple partitions\". Journal of\n [NAME_REDACTED] 3: 583-617. `doi:10.1162/153244303321897735\n- `_.\n+ `_.\n \n * `Wikipedia entry for the (normalized) [NAME_REDACTED]\n `_\n@@ -1769,7 +1769,7 @@ homogeneous but not complete::\n Hirschberg, 2007\n \n .. [B2011] `Identification and Characterization of Events in [NAME_REDACTED]\n- `_, Hila\n+ `_, [NAME_REDACTED], [NAME_REDACTED]." }, { "filename": "doc/modules/cross_validation.rst", "status": "modified", "additions": 1, "deletions": 1, "changes": 2, "patch": "@@ -1022,5 +1022,5 @@ computation and thus speeds it up.\n .. dropdown:: References\n \n * Ojala and Garriga. `[NAME_REDACTED] for [NAME_REDACTED]\n- `_.\n+ `_.\n J. Mach. Learn. Res. 2010." }, { "filename": "doc/modules/decomposition.rst", "status": "modified", "additions": 1, "deletions": 1, "changes": 2, "patch": "@@ -950,7 +950,7 @@ is not readily available from the start, or when the data does not fit into memo\n .. rubric:: References\n \n .. [1] `\"Learning the parts of objects by [NAME_REDACTED]\"\n- `_\n+ `_\n D. Lee, S. Seung, 1999\n \n .. [2] `\"[NAME_REDACTED] with [NAME_REDACTED]\"" }, { "filename": "doc/modules/grid_search.rst", "status": "modified", "additions": 1, "deletions": 1, "changes": 2, "patch": "@@ -536,7 +536,7 @@ additional information related to the successive halving process.\n \n .. [1] K. Jamieson, A. Talwalkar,\n `[NAME_REDACTED] Identification and Hyperparameter\n- Optimization `_, in\n+ Optimization `_, in\n proc. of [NAME_REDACTED], 2016.\n \n .. [2] L. Li, K. Jamieson, G. DeSalvo, A. Rostamizadeh, A. Talwalkar," }, { "filename": "doc/modules/linear_model.rst", "status": "modified", "additions": 2, "deletions": 2, "changes": 4, "patch": "@@ -1448,7 +1448,7 @@ eta0=1.0)` can be used for PA-I or with ``learning_rate=\"pa2\"`` for PA-II.\n .. dropdown:: References\n \n * `\"[NAME_REDACTED]\"\n- `_\n+ `_\n K. Crammer, O. Dekel, J. Keshat, S. Shalev-Shwartz, Y. Singer - JMLR 7 (2006)\n \n Robustness regression: outliers and modeling errors\n@@ -1655,7 +1655,7 @@ better than an ordinary least squares in high dimension.\n \n .. [#f1] [NAME_REDACTED], [NAME_REDACTED], [NAME_REDACTED] and [NAME_REDACTED]: `[NAME_REDACTED] in a [NAME_REDACTED] Model. `_\n \n- .. [#f2] T. Kärkkäinen and S. Äyrämö: `On Computation of [NAME_REDACTED] for [NAME_REDACTED]. `_\n+ .. [#f2] T. Kärkkäinen and S. Äyrämö: `On Computation of [NAME_REDACTED] for [NAME_REDACTED]. `_\n \n Also see the `Wikipedia page `_" }, { "filename": "doc/modules/model_evaluation.rst", "status": "modified", "additions": 1, "deletions": 1, "changes": 2, "patch": "@@ -2009,7 +2009,7 @@ the same does a lower Brier score loss always mean better calibration\"\n \n .. [Bella2012] Bella, Ferri, Hernández-Orallo, and Ramírez-Quintana\n `\"Calibration of [NAME_REDACTED]\"\n- `_\n+ `_\n in Khosrow-Pour, M. \"Machine learning: concepts, methodologies, tools\n and applications.\" Hershey, PA: [NAME_REDACTED] (2012)." }, { "filename": "doc/modules/svm.rst", "status": "modified", "additions": 1, "deletions": 1, "changes": 2, "patch": "@@ -813,4 +813,4 @@ used, please refer to their respective papers.\n \n .. [#8] Crammer and Singer `On the [NAME_REDACTED] of [NAME_REDACTED] Machines\n- `_, JMLR 2001.\n+ `_, JMLR 2001." }, { "filename": "doc/modules/tree.rst", "status": "modified", "additions": 1, "deletions": 1, "changes": 2, "patch": "@@ -310,7 +310,7 @@ the lower half of those faces.\n \n * M. Dumont et al, `Fast multi-class image annotation with random subwindows\n and multiple output randomized trees\n- `_,\n+ `_,\n [NAME_REDACTED] on [NAME_REDACTED] and Applications 2009\n \n .. _tree_complexity:" }, { "filename": "doc/testimonials/testimonials.rst", "status": "modified", "additions": 6, "deletions": 6, "changes": 12, "patch": "@@ -390,8 +390,8 @@ Who is using scikit-learn?\n :target: https://www.phimeca.com/?lang=en\n \n \n-`HowAboutWe `_\n-------------------------------------------\n+`HowAboutWe `_\n+-------------------------------------------\n \n .. div:: sk-[REDACTED]\n \n@@ -413,7 +413,7 @@ Who is using scikit-learn?\n .. div:: image-box\n \n .. image:: images/howaboutwe.png\n- :target: http://www.howaboutwe.com/\n+ :target: https://www.howaboutwe.com/\n \n \n `PeerIndex `_\n@@ -598,8 +598,8 @@ Who is using scikit-learn?\n :target: https://www.solidodesign.com/\n \n \n-`INFONEA `_\n----------------------------------------\n+`INFONEA `_\n+----------------------------------------\n \n .. div:: sk-[REDACTED]\n \n@@ -620,7 +620,7 @@ Who is using scikit-learn?\n .. div:: image-box\n \n .. image:: images/infonea.jpg\n- :target: http://www.infonea.com/en/\n+ :target: https://www.infonea.com/en/\n \n \n `Dataiku `_" }, { "filename": "doc/whats_new/_contributors.rst", "status": "modified", "additions": 10, "deletions": 10, "changes": 20, "patch": "@@ -22,11 +22,11 @@\n \n .. _Olivier Grisel: https://bsky.app/profile/ogrisel.bsky.social\n \n-.. _Gael Varoquaux: http://gael-varoquaux.info\n+.. _Gael Varoquaux: https://gael-varoquaux.info\n \n-.. _Alexandre Gramfort: http://alexandre.gramfort.net\n+.. _Alexandre Gramfort: https://alexandre.gramfort.net\n \n-.. _Fabian Pedregosa: http://fa.bianp.net\n+.. _Fabian Pedregosa: https://fa.bianp.net\n \n .. _Mathieu Blondel: http://www.mblondel.org\n \n@@ -42,7 +42,7 @@\n \n .. _Peter Prettenhofer: https://sites.google.com/site/peterprettenhofer/\n \n-.. _Alexandre Passos: http://atpassos.me\n+.. _Alexandre Passos: https://atpassos.me\n \n .. _Nicolas Pinto: https://twitter.com/npinto\n \n@@ -54,7 +54,7 @@\n \n .. _Jake Vanderplas: https://staff.washington.edu/jakevdp/\n \n-.. _Gilles Louppe: http://www.montefiore.ulg.ac.be/~glouppe/\n+.. _Gilles Louppe: https://www.montefiore.ulg.ac.be/~glouppe/\n \n .. _INRIA: https://www.inria.fr/\n \n@@ -90,21 +90,21 @@\n \n .. _Kyle Kastner: https://kastnerkyle.github.io/\n \n-.. _Daniel Nouri: http://danielnouri.org\n+.. _Daniel Nouri: https://danielnouri.org\n \n .. _Manoj Kumar: https://manojbits.wordpress.com\n \n-.. _Luis [NAME_REDACTED]: http://luispedro.org\n+.. _Luis [NAME_REDACTED]: https://luispedro.org\n \n-.. _Fares Hedyati: http://www.eecs.berkeley.edu/~fareshed\n+.. _Fares Hedyati: https://www.eecs.berkeley.edu/~fareshed\n \n .. _Antony Lee: https://www.ocf.berkeley.edu/~antonyl/\n \n .. _Martin Billinger: https://tnsre.embs.org/author/martinbillinger/\n \n .. _Matteo Visconti di [NAME_REDACTED]: http://www.mvdoc.me\n \n-.. _Trevor Stephens: http://trevorstephens.com/\n+.. _Trevor Stephens: https://trevorstephens.com/\n \n .. _Jan [NAME_REDACTED]: https://jmetzen.github.io/\n \n@@ -156,7 +156,7 @@\n \n .. _Vincent Pham: https://github.com/[USER_REDACTED]\n \n-.. _Denis Engemann: http://denis-engemann.de\n+.. _Denis Engemann: https://denis-engemann.de\n \n .. _Anish Shah: https://github.com/[USER_REDACTED]" }, { "filename": "doc/whats_new/v0.16.rst", "status": "modified", "additions": 1, "deletions": 1, "changes": 2, "patch": "@@ -414,7 +414,7 @@ Bug fixes\n \n - Fixed handling of ties in :class:`isotonic.IsotonicRegression`.\n We now use the weighted average of targets (secondary method). By\n- `Andreas Müller`_ and `[NAME_REDACTED] `_.\n+ `Andreas Müller`_ and `[NAME_REDACTED] `_.\n \n API changes summary\n -------------------" }, { "filename": "doc/whats_new/v0.23.rst", "status": "modified", "additions": 1, "deletions": 1, "changes": 2, "patch": "@@ -708,7 +708,7 @@ Changelog\n generates 31bits/63bits random numbers on all platforms. In addition, the\n crude \"modulo\" postprocessor used to get a random number in a bounded\n interval was replaced by [NAME_REDACTED] as suggested by `this blog\n- post `_.\n+ post `_.\n Any model using the `svm.libsvm` or the `svm.liblinear` solver,\n including :class:`svm.LinearSVC`, :class:`svm.LinearSVR`,\n :class:`svm.NuSVC`, :class:`svm.NuSVR`, :class:`svm.OneClassSVM`," } ], "reviews": [ { "id": 3617566945, "user": "user_501030d9d7e3", "state": "COMMENTED", "body": "Hello [USER_REDACTED], thanks for your PR, that I find overall useful.\n\nI in total count 442 `http:` in the whole project (compared to 4700 `https:`) and I would be happy to replace them all in this PR.\n\nBut how do we deal with those pages (like the institute website from my comment) that don't use https? There must be quite a few in the docs. \n\nI would slightly tend to try https on them as well and let user's browser's point out potential risks. Deciding this requires the opinion of another project member.", "submitted_at": "2025-12-30T08:41:34+00:00" }, { "id": 3617607575, "user": "user_481b55069ad2", "state": "COMMENTED", "body": null, "submitted_at": "2025-12-30T08:53:39+00:00" }, { "id": 3617628896, "user": "user_501030d9d7e3", "state": "COMMENTED", "body": null, "submitted_at": "2025-12-30T09:03:11+00:00" }, { "id": 3618788919, "user": "user_501030d9d7e3", "state": "APPROVED", "body": "That's pretty fine, thanks for your efforts, [USER_REDACTED]!\n\nI think this is one of the uncritical documentation improvements where one maintainer review is enough and I will merge.", "submitted_at": "2025-12-30T16:55:22+00:00" }, { "id": 3633343092, "user": "user_d16337ec046b", "state": "COMMENTED", "body": null, "submitted_at": "2026-01-07T04:55:12+00:00" }, { "id": 3635441747, "user": "user_5819d17296ee", "state": "COMMENTED", "body": null, "submitted_at": "2026-01-07T15:30:03+00:00" }, { "id": 3635479348, "user": "user_5819d17296ee", "state": "APPROVED", "body": "One more underline fix. Otherwise LGTM.", "submitted_at": "2026-01-07T15:37:06+00:00" }, { "id": 3635617638, "user": "user_d5b9cb906259", "state": "APPROVED", "body": "I'm happy to have these changes.\n\nIn general/for the future though I am not sure if there is much benefit to converting everything to HTTPS. I think that not every single website you visit has to be HTTPS, in particular if you do not enter sensitive information on that website or where the path/query arguments do not contain sensitive information.\n\nTL;DR: not against making these changes but I also think that we could do other things that have more impact.", "submitted_at": "2026-01-07T16:06:52+00:00" } ], "review_comments": [ { "id": 2652507937, "user": "user_501030d9d7e3", "body": "It seems this site doesn't have a secure HTTPS configuration. At least firefox warns me about it when I try to open this page.\nI am not sure what to do with cases like these. Leave them http or make the security risk explicit by [NAME_REDACTED]?", "path": "doc/about.rst", "line": null, "side": "RIGHT", "created_at": "2025-12-30T08:33:24+00:00" }, { "id": 2652537682, "user": "user_481b55069ad2", "body": "Thanks for the review! I just pushed a commit to revert the Dartmouth link to http since it doesn't support HTTPS yet.\n\nRegarding the other 400+ links: I am happy to help with those! Would you prefer I try to update them all in this PR, or should we merge this small fix first and handle the bulk update in a separate PR?", "path": "doc/about.rst", "line": null, "side": "RIGHT", "created_at": "2025-12-30T08:53:39+00:00" }, { "id": 2652552213, "user": "user_501030d9d7e3", "body": "Thanks. I know it is a lot of dull work, but ideally, you would check them all before adding the `s` and point out any problems that arise. There might be invalid links, websites that have moved and not redirected, etc. You can do it all in this PR.\n\nOnce we know the special cases (doesn't support https, has moved, doesn't exist anymore), you can sum it up and suggest what to do with these.", "path": "doc/about.rst", "line": null, "side": "RIGHT", "created_at": "2025-12-30T09:03:11+00:00" }, { "id": 2667065064, "user": "user_d16337ec046b", "body": "doc is failing because the underlines in this file are now too short.", "path": "doc/testimonials/testimonials.rst", "line": null, "side": "RIGHT", "created_at": "2026-01-07T04:55:12+00:00" }, { "id": 2668923990, "user": "user_5819d17296ee", "body": "```suggestion\n-------------------------------------------\n```", "path": "doc/testimonials/testimonials.rst", "line": null, "side": "RIGHT", "created_at": "2026-01-07T15:30:03+00:00" }, { "id": 2668951311, "user": "user_5819d17296ee", "body": "```suggestion\n----------------------------------------\n```", "path": "doc/testimonials/testimonials.rst", "line": null, "side": "RIGHT", "created_at": "2026-01-07T15:35:50+00:00" } ], "meta": { "languages": [ "py", "rst" ], "touches_tests": false, "review_state_summary": { "COMMENTED": 5, "APPROVED": 3 }, "meaningful_comment_count": 6, "has_approval": true, "has_changes_requested": false, "total_review_comments": 6 } } { "_id": "b570fbbc263c435a", "_schema_version": "1.0", "_cleaned_at": "2026-02-12T07:46:51.960591+00:00", "repo": "scikit-learn/scikit-learn", "repo_url": "https://github.com/scikit-learn/scikit-learn", "license_name": "BSD 3-Clause \"New\" or \"Revised\" License", "license_spdx": "BSD-3-Clause", "pr_number": 32968, "title": "DOC: clarify verbose behavior in GridSearchCV and RandomizedSearchCV", "body": "This PR clarifies the behavior of the `verbose` parameter in\nGridSearchCV and RandomizedSearchCV.\n\nThe documentation now:\n- Explicitly documents the behavior when `verbose=0`\n- Clarifies what additional information is shown as verbosity increases\n- Notes that higher verbosity levels (e.g. >10) may produce additional\n progress messages depending on the execution backend\n\nThis aligns the documentation with the observed behavior discussed in\n#32946.\n\n\n\n#### [NAME_REDACTED]/PRs\n\n\n#### What does this implement/fix? Explain your changes.\n\n#### AI usage disclosure\n\nI used AI assistance for:\n- [ ] Code generation (e.g., when writing an implementation or fixing a bug)\n- [ ] Test/benchmark generation\n- [ ] Documentation (including examples)\n- [ ] Research and understanding\n\n#### Any other comments?\n\n", "author": "user_9f8c2eae99c8", "created_at": "2025-12-29T18:02:18+00:00", "merged_at": "2026-01-07T10:26:30+00:00", "base_branch": "main", "head_branch": "docs-gridsearch-verbose", "additions": 16, "deletions": 14, "changed_files": 1, "files": [ { "filename": "sklearn/model_selection/_search.py", "status": "modified", "additions": 16, "deletions": 14, "changes": 30, "patch": "@@ -1360,14 +1360,15 @@ class GridSearchCV(BaseSearchCV):\n .. versionchanged:: 0.22\n ``cv`` default value if None changed from 3-fold to 5-fold.\n \n- verbose : int\n- Controls the verbosity: the higher, the more messages.\n+ verbose : int, default=0\n+ Controls the verbosity of information printed during fitting, with higher\n+ values yielding more detailed logging.\n \n- - >1 : the computation time for each fold and parameter candidate is\n- displayed;\n- - >2 : the score is also displayed;\n- - >3 : the fold and candidate parameter indexes are also displayed\n- together with the starting time of the computation.\n+ - 0 : no messages are printed;\n+ - >=1 : summary of the total number of fits;\n+ - >=2 : computation time for each fold and parameter candidate;\n+ - >=3 : fold indices and scores;\n+ - >=10 : parameter candidate indices and START messages before each fit.\n \n pre_dispatch : int, or str, default='2*n_jobs'\n Controls the number of jobs that get dispatched during parallel\n@@ -1744,14 +1745,15 @@ class RandomizedSearchCV(BaseSearchCV):\n .. versionchanged:: 0.22\n ``cv`` default value if None changed from 3-fold to 5-fold.\n \n- verbose : int\n- Controls the verbosity: the higher, the more messages.\n+ verbose : int, default = 0\n+ Controls the verbosity of information printed during fitting, with higher\n+ values yielding more detailed logging.\n \n- - >1 : the computation time for each fold and parameter candidate is\n- displayed;\n- - >2 : the score is also displayed;\n- - >3 : the fold and candidate parameter indexes are also displayed\n- together with the starting time of the computation.\n+ - 0 : no messages are printed;\n+ - >=1 : summary of the total number of fits;\n+ - >=2 : computation time for each fold and parameter candidate;\n+ - >=3 : fold indices and scores;\n+ - >=10 : parameter candidate indices and START messages before each fit.\n \n pre_dispatch : int, or str, default='2*n_jobs'\n Controls the number of jobs that get dispatched during parallel" } ], "reviews": [ { "id": 3616850949, "user": "user_501030d9d7e3", "state": "COMMENTED", "body": "Hi [USER_REDACTED],\n\nthanks for the PR. The CI failures are related to this PR. Please use `pre-commit` (as described in the development guide) to fix the linting issues and then push again.", "submitted_at": "2025-12-29T22:28:41+00:00" }, { "id": 3620989699, "user": "user_501030d9d7e3", "state": "APPROVED", "body": "Thanks, [USER_REDACTED]. I have pushed a little wording tweak to make it all a bit shorter: I have also added a line on `verbosity=1 `which had not been mentioned and also I have seen that parameter candidate indices are only printed from `verbosity=10` on , which I found worth mentioning. Approving this PR.", "submitted_at": "2025-12-31T14:34:21+00:00" }, { "id": 3633451271, "user": "user_d16337ec046b", "state": "COMMENTED", "body": "Just some nits.", "submitted_at": "2026-01-07T05:58:21+00:00" }, { "id": 3634031125, "user": "user_501030d9d7e3", "state": "COMMENTED", "body": null, "submitted_at": "2026-01-07T09:31:19+00:00" }, { "id": 3634040809, "user": "user_501030d9d7e3", "state": "COMMENTED", "body": null, "submitted_at": "2026-01-07T09:34:01+00:00" }, { "id": 3634075362, "user": "user_d16337ec046b", "state": "APPROVED", "body": "LGTM thanks. [USER_REDACTED] feel free to merge (when you're happy).", "submitted_at": "2026-01-07T09:43:41+00:00" } ], "review_comments": [ { "id": 2667163943, "user": "user_d16337ec046b", "body": "What about:\n\n```suggestion\n Controls the verbosity of information printed during fitting, with higher\n values yielding more detailed logging.\n```\n\n\"of the grid search\" seems a bit redundant as this is the docstring for gridsearch. We can then get rid of the next sentence.", "path": "sklearn/model_selection/_search.py", "line": null, "side": "RIGHT", "created_at": "2026-01-07T05:55:08+00:00" }, { "id": 2667169373, "user": "user_d16337ec046b", "body": "Just a question, are the logs for verbosity between 3 and 10 (e.g., 3,4,5), different? And similar question for values greater than 10, is there more information or does any number greater than 10 give the same information?\n\nI also wonder if we should add 'includes' or 'also' (like the previous docs) to make it clear that the previous information is included as well as the the new item.", "path": "sklearn/model_selection/_search.py", "line": 1371, "side": "RIGHT", "created_at": "2026-01-07T05:58:16+00:00" }, { "id": 2667691169, "user": "user_501030d9d7e3", "body": "Thanks! I agree.\nI have gone and modified this [USER_REDACTED].", "path": "sklearn/model_selection/_search.py", "line": null, "side": "RIGHT", "created_at": "2026-01-07T09:31:18+00:00" }, { "id": 2667699793, "user": "user_501030d9d7e3", "body": "> Just a question, are the logs for verbosity between 3 and 10 (e.g., 3,4,5), different? And similar question for values greater than 10, is there more information or does any number greater than 10 give the same information?\n\nFrom 3 to 9, as well as above 10, it is all the same information.\n\n> I also wonder if we should add 'includes' or 'also' (like the previous docs) to make it clear that the previous information is included as well as the the new item.\n\nWe had this at first, but I then decided to go with `>=number` meaning \"every verbosity larger than `number` displays this information\".", "path": "sklearn/model_selection/_search.py", "line": 1371, "side": "RIGHT", "created_at": "2026-01-07T09:34:01+00:00" } ], "meta": { "languages": [ "py" ], "touches_tests": false, "review_state_summary": { "COMMENTED": 4, "APPROVED": 2 }, "meaningful_comment_count": 4, "has_approval": true, "has_changes_requested": false, "total_review_comments": 4 } } { "_id": "735e6bb38bdf26ba", "_schema_version": "1.0", "_cleaned_at": "2026-02-12T07:46:51.960591+00:00", "repo": "scikit-learn/scikit-learn", "repo_url": "https://github.com/scikit-learn/scikit-learn", "license_name": "BSD 3-Clause \"New\" or \"Revised\" License", "license_spdx": "BSD-3-Clause", "pr_number": 32923, "title": "FIX array API support when `pos_label=None` for brier score metrics", "body": "#### [NAME_REDACTED]/PRs\n\n#### What does this implement/fix? Explain your changes.\nAs discussed in https://github.com/[USER_REDACTED]n/scikit-learn/pull/32422/changes#r2575666004 , add array API handling to the case when `pos_label=None` and `y_true` is not string.\n\nAlso adds test.\n\n#### AI usage disclosure\n\nI used AI assistance for:\n- [ ] Code generation (e.g., when writing an implementation or fixing a bug)\n- [ ] Test/benchmark generation\n- [ ] Documentation (including examples)\n- [x] Research and understanding\n\n#### Any other comments?\nThis highlights again the inconsistency of `pos_label` handling, see longstanding issue #10010 - details here: https://github.com/[USER_REDACTED]n/scikit-learn/issues/10010#issuecomment-1826133710 - would be great to get any movement/thoughts here!\n\ncc [USER_REDACTED], [USER_REDACTED]", "author": "user_d16337ec046b", "created_at": "2025-12-19T05:36:36+00:00", "merged_at": "2025-12-21T03:48:44+00:00", "base_branch": "main", "head_branch": "aapi_brier_pos_label", "additions": 39, "deletions": 7, "changed_files": 3, "files": [ { "filename": "doc/whats_new/upcoming_changes/array-api/32923.fix.rst", "status": "added", "additions": 3, "deletions": 0, "changes": 3, "patch": "@@ -0,0 +1,3 @@\n+- Fixes how `pos_label` is inferred when `pos_label` is set to `None`, in\n+ :func:`sklearn.metrics.brier_score_loss` and\n+ :func:`sklearn.metrics.d2_brier_score`. By :user:`[NAME_REDACTED] `." }, { "filename": "sklearn/metrics/_classification.py", "status": "modified", "additions": 5, "deletions": 4, "changes": 9, "patch": "@@ -3614,10 +3614,11 @@ def _validate_binary_probabilistic_prediction(y_true, y_prob, sample_weight, pos\n try:\n pos_label = _check_pos_label_consistency(pos_label, y_true)\n except ValueError:\n- classes = np.unique(y_true)\n- if classes.dtype.kind not in (\"O\", \"U\", \"S\"):\n- # for backward compatibility, if classes are not string then\n- # `pos_label` will correspond to the greater label\n+ xp_y_true, _ = get_namespace(y_true)\n+ classes = xp_y_true.unique_values(y_true)\n+ # For backward compatibility, if classes are not string then\n+ # `pos_label` will correspond to the greater label.\n+ if not (_is_numpy_namespace(xp_y_true) and classes.dtype.kind in \"OUS\"):\n pos_label = classes[-1]\n else:\n raise" }, { "filename": "sklearn/metrics/tests/test_classification.py", "status": "modified", "additions": 31, "deletions": 3, "changes": 34, "patch": "@@ -45,12 +45,13 @@\n from sklearn.preprocessing import LabelBinarizer, label_binarize\n from sklearn.tree import DecisionTreeClassifier\n from sklearn.utils._array_api import (\n- device as array_api_device,\n-)\n-from sklearn.utils._array_api import (\n+ _get_namespace_device_dtype_ids,\n get_namespace,\n yield_namespace_device_dtype_combinations,\n )\n+from sklearn.utils._array_api import (\n+ device as array_api_device,\n+)\n from sklearn.utils._mocking import MockDataFrame\n from sklearn.utils._testing import (\n _array_api_for_tests,\n@@ -3743,3 +3744,30 @@ def test_probabilistic_metrics_multilabel_array_api(\n metric_score_xp = prob_metric(y_true_xp, y_prob_xp, sample_weight=sample_weight)\n \n assert metric_score_xp == pytest.approx(metric_score_np)\n+\n+\n+[USER_REDACTED].mark.parametrize(\n+ \"array_namespace, device_, dtype_name\",\n+ yield_namespace_device_dtype_combinations(),\n+ ids=_get_namespace_device_dtype_ids,\n+)\n+[USER_REDACTED].mark.parametrize(\"prob_metric\", [brier_score_loss, d2_brier_score])\n+def test_pos_label_in_brier_score_metrics_array_api(\n+ prob_metric, array_namespace, device_, dtype_name\n+):\n+ \"\"\"Check `pos_label` handled correctly when labels not in {-1, 1} or {0, 1}.\"\"\"\n+ # For 'brier_score' metrics, when `pos_label=None` and labels are not strings,\n+ # `pos_label` defaults to the largest label.\n+ xp = _array_api_for_tests(array_namespace, device_)\n+ y_true_pos_1 = xp.asarray(np.array([1, 0, 1, 0]), device=device_)\n+ # Result should be the same when we use 2's for the label instead of 1's\n+ y_true_pos_2 = xp.asarray(np.array([2, 0, 2, 0]), device=device_)\n+ y_prob = xp.asarray(\n+ np.array([0.5, 0.2, 0.7, 0.6], dtype=dtype_name), device=device_\n+ )\n+\n+ with config_context(array_api_dispatch=True):\n+ metric_pos_1 = prob_metric(y_true_pos_1, y_prob)\n+ metric_pos_2 = prob_metric(y_true_pos_2, y_prob)\n+\n+ assert metric_pos_1 == pytest.approx(metric_pos_2)" } ], "reviews": [ { "id": 3596920359, "user": "user_d16337ec046b", "state": "COMMENTED", "body": null, "submitted_at": "2025-12-19T05:40:28+00:00" }, { "id": 3598027727, "user": "user_d16337ec046b", "state": "COMMENTED", "body": null, "submitted_at": "2025-12-19T10:27:10+00:00" }, { "id": 3598220607, "user": "user_3c90b5520ec5", "state": "COMMENTED", "body": null, "submitted_at": "2025-12-19T11:19:41+00:00" }, { "id": 3598227104, "user": "user_3c90b5520ec5", "state": "APPROVED", "body": "LGTM. Thanks [USER_REDACTED]", "submitted_at": "2025-12-19T11:21:39+00:00" }, { "id": 3601072648, "user": "user_501030d9d7e3", "state": "APPROVED", "body": "That looks good to me, thank you [USER_REDACTED].\nI only have two nits on the documentation side.", "submitted_at": "2025-12-20T13:25:06+00:00" }, { "id": 3601441313, "user": "user_d16337ec046b", "state": "COMMENTED", "body": null, "submitted_at": "2025-12-21T02:46:37+00:00" }, { "id": 3601441885, "user": "user_d16337ec046b", "state": "COMMENTED", "body": null, "submitted_at": "2025-12-21T02:49:28+00:00" } ], "review_comments": [ { "id": 2633697061, "user": "user_d16337ec046b", "body": "Note this relies on lazy evaluation - if `_is_numpy_namespace(xp_y_true)` is False, the second condition is not evaluated.\n\nAlso note when namespace is not numpy, this evaluates to True.", "path": "sklearn/metrics/_classification.py", "line": 3621, "side": "RIGHT", "created_at": "2025-12-19T05:40:28+00:00" }, { "id": 2634613187, "user": "user_d16337ec046b", "body": "Maybe this is not needed, see #32924 . I'm happy to remove.", "path": "sklearn/metrics/_classification.py", "line": null, "side": "RIGHT", "created_at": "2025-12-19T10:27:10+00:00" }, { "id": 2634772893, "user": "user_3c90b5520ec5", "body": "I think the modules we are supporting do return sorted values. I am not sure about `array-api-strict` but if we don't get errors, it probably returns sorted results too.\n\nhttps://docs.pytorch.org/docs/stable/generated/torch.unique.html#torch-unique\n\nhttps://docs.cupy.dev/en/stable/reference/generated/cupy.unique.html", "path": "sklearn/metrics/_classification.py", "line": null, "side": "RIGHT", "created_at": "2025-12-19T11:19:41+00:00" }, { "id": 2637071375, "user": "user_501030d9d7e3", "body": "I find \"fix inference\" pretty unclear. Maybe like this:\n\n```suggestion\n- Fixes how `pos_label=None` is inferred in\n :func:`sklearn.metrics.brier_score_loss` and\n :func:`sklearn.metrics.d2_brier_score`.\n By :user:`[NAME_REDACTED] `.\n```", "path": "doc/whats_new/upcoming_changes/array-api/32923.fix.rst", "line": null, "side": "RIGHT", "created_at": "2025-12-20T11:54:18+00:00" }, { "id": 2637114245, "user": "user_501030d9d7e3", "body": "I would suggest to move the comment in front of the condition, as we usually comment in the line before.", "path": "sklearn/metrics/_classification.py", "line": null, "side": "RIGHT", "created_at": "2025-12-20T13:23:05+00:00" }, { "id": 2637507526, "user": "user_d16337ec046b", "body": "Indeed, I will remove it as we don't sort elsewhere either and it is not a problem for the array libraries we support.", "path": "sklearn/metrics/_classification.py", "line": null, "side": "RIGHT", "created_at": "2025-12-21T02:46:36+00:00" }, { "id": 2637508442, "user": "user_d16337ec046b", "body": "(array api strict just uses numpy so, it sorts too)", "path": "sklearn/metrics/_classification.py", "line": null, "side": "RIGHT", "created_at": "2025-12-21T02:49:27+00:00" } ], "meta": { "languages": [ "py", "rst" ], "touches_tests": true, "review_state_summary": { "COMMENTED": 5, "APPROVED": 2 }, "meaningful_comment_count": 7, "has_approval": true, "has_changes_requested": false, "total_review_comments": 7 } } { "_id": "73c29b6778c337a2", "_schema_version": "1.0", "_cleaned_at": "2026-02-12T07:46:51.960591+00:00", "repo": "scikit-learn/scikit-learn", "repo_url": "https://github.com/scikit-learn/scikit-learn", "license_name": "BSD 3-Clause \"New\" or \"Revised\" License", "license_spdx": "BSD-3-Clause", "pr_number": 32918, "title": "DOC Fix response values shape", "body": "\n\n#### [NAME_REDACTED]/PRs\n\nTowards #32872\n\n#### What does this implement/fix? Explain your changes.\nThe problem in #32872 arises from the assumption that multiclass classification will have a different output shape than binary classification, which is not the case when `response_method`=\"predict\".\nTo make sure, I added a test for all output shapes and updated the docstring according to the result.\n\n#### AI usage disclosure\n\nI used AI assistance for:\n- [ ] Code generation (e.g., when writing an implementation or fixing a bug)\n- [ ] Test/benchmark generation\n- [ ] Documentation (including examples)\n- [ ] Research and understanding\n\n#### Any other comments?\n\nI have not checked if this assumption is used anywhere else.\n\n", "author": "user_34a090906ca4", "created_at": "2025-12-17T15:00:58+00:00", "merged_at": "2025-12-22T16:03:50+00:00", "base_branch": "main", "head_branch": "fix_response_values_shape", "additions": 55, "deletions": 1, "changed_files": 2, "files": [ { "filename": "sklearn/utils/_response.py", "status": "modified", "additions": 3, "deletions": 1, "changes": 4, "patch": "@@ -125,7 +125,9 @@ def _get_response_values(\n The response values are predictions such that it follows the following shape:\n \n - for binary classification, it is a 1d array of shape `(n_samples,)`;\n- - for multiclass classification, it is a 2d array of shape `(n_samples, n_classes)`;\n+ - for multiclass classification\n+ - with response_method=\"predict\", it is a 1d array of shape `(n_samples,)`;\n+ - otherwise, it is a 2d array of shape `(n_samples, n_classes)`;\n - for multilabel classification, it is a 2d array of shape `(n_samples, n_outputs)`;\n - for outlier detection, it is a 1d array of shape `(n_samples,)`;\n - for regression, it is a 1d array of shape `(n_samples,)`." }, { "filename": "sklearn/utils/tests/test_response.py", "status": "modified", "additions": 52, "deletions": 0, "changes": 52, "patch": "@@ -394,3 +394,55 @@ def test_response_values_type_of_target_on_classes_no_warning():\n warnings.simplefilter(\"error\", UserWarning)\n \n _get_response_values(clf, X, response_method=\"predict_proba\")\n+\n+\n+[USER_REDACTED].mark.parametrize(\n+ \"estimator, response_method, target_type, expected_shape\",\n+ [\n+ (LogisticRegression(), \"predict\", \"binary\", (10,)),\n+ (LogisticRegression(), \"predict_proba\", \"binary\", (10,)),\n+ (LogisticRegression(), \"decision_function\", \"binary\", (10,)),\n+ (LogisticRegression(), \"predict\", \"multiclass\", (10,)),\n+ (LogisticRegression(), \"predict_proba\", \"multiclass\", (10, 4)),\n+ (LogisticRegression(), \"decision_function\", \"multiclass\", (10, 4)),\n+ (ClassifierChain(LogisticRegression()), \"predict\", \"multilabel\", (10, 2)),\n+ (ClassifierChain(LogisticRegression()), \"predict_proba\", \"multilabel\", (10, 2)),\n+ (\n+ ClassifierChain(LogisticRegression()),\n+ \"decision_function\",\n+ \"multilabel\",\n+ (10, 2),\n+ ),\n+ (IsolationForest(), \"predict\", \"binary\", (10,)),\n+ (IsolationForest(), \"predict\", \"multiclass\", (10,)),\n+ (DecisionTreeRegressor(), \"predict\", \"binary\", (10,)),\n+ (DecisionTreeRegressor(), \"predict\", \"multiclass\", (10,)),\n+ ],\n+)\n+def test_response_values_output_shape_(\n+ estimator, response_method, target_type, expected_shape\n+):\n+ \"\"\"\n+ Check that output shape corresponds to docstring description\n+\n+ - for binary classification, it is a 1d array of shape `(n_samples,)`;\n+ - for multiclass classification\n+ - with response_method=\"predict\", it is a 1d array of shape `(n_samples,)`;\n+ - otherwise, it is a 2d array of shape `(n_samples, n_classes)`;\n+ - for multilabel classification, it is a 2d array of shape `(n_samples, n_outputs)`;\n+ - for outlier detection, it is a 1d array of shape `(n_samples,)`;\n+ - for regression, it is a 1d array of shape `(n_samples,)`.\n+ \"\"\"\n+ X = np.random.RandomState(0).randn(10, 2)\n+ if target_type == \"binary\":\n+ y = np.array([0, 1] * 5)\n+ elif target_type == \"multiclass\":\n+ y = [0, 1, 2, 3, 0, 1, 2, 3, 3, 0]\n+ else: # multilabel\n+ y = np.array([[0, 1], [1, 0]] * 5)\n+\n+ clf = estimator.fit(X, y)\n+\n+ y_pred, _ = _get_response_values(clf, X, response_method=response_method)\n+\n+ assert y_pred.shape == expected_shape" } ], "reviews": [ { "id": 3588173796, "user": "user_34a090906ca4", "state": "COMMENTED", "body": null, "submitted_at": "2025-12-17T15:02:50+00:00" }, { "id": 3600719101, "user": "user_04b4a5f4e2a8", "state": "COMMENTED", "body": null, "submitted_at": "2025-12-20T05:01:07+00:00" }, { "id": 3601192823, "user": "user_04b4a5f4e2a8", "state": "APPROVED", "body": "LGTM", "submitted_at": "2025-12-20T17:12:04+00:00" }, { "id": 3603000240, "user": "user_bf0b6c7acb9c", "state": "APPROVED", "body": "LGTM! Thanks, [USER_REDACTED]!\n\n[USER_REDACTED], could we merge this?", "submitted_at": "2025-12-22T07:47:35+00:00" } ], "review_comments": [ { "id": 2627420997, "user": "user_34a090906ca4", "body": "This is the test that was inconsistent with the previous version of the docstring (which suggested that it should be `(10,4)`)", "path": "sklearn/utils/tests/test_response.py", "line": 405, "side": "RIGHT", "created_at": "2025-12-17T15:02:50+00:00" }, { "id": 2636786812, "user": "user_04b4a5f4e2a8", "body": "Can the test values for `y` be something like `[0, 1, 2, 3, 0, 1, 2, 3, 3, 0]` so that the test would check for `(10, 4)` for the `multi-class` + `predict_proba` case?\n\nThis makes it more obvious that `n_samples` and `n_classes` can be different values.", "path": "sklearn/utils/tests/test_response.py", "line": null, "side": "RIGHT", "created_at": "2025-12-20T05:01:05+00:00" } ], "meta": { "languages": [ "py" ], "touches_tests": true, "review_state_summary": { "COMMENTED": 2, "APPROVED": 2 }, "meaningful_comment_count": 2, "has_approval": true, "has_changes_requested": false, "total_review_comments": 2 } } { "_id": "989896711c074c09", "_schema_version": "1.0", "_cleaned_at": "2026-02-12T07:46:51.960591+00:00", "repo": "scikit-learn/scikit-learn", "repo_url": "https://github.com/scikit-learn/scikit-learn", "license_name": "BSD 3-Clause \"New\" or \"Revised\" License", "license_spdx": "BSD-3-Clause", "pr_number": 32912, "title": "FIX Error handling in ranking metrics supporting multiclass: `average_precision_score`, `roc_auc_score` and `top_k_accuracy_score`", "body": "#### [NAME_REDACTED]/PRs\ndiscovered while working in #32909\n\n#### What does this implement/fix? Explain your changes.\nThis adds a proper error handling if a multiclass `y_true` is passed into `average_precision_score`, `roc_auc_score` and `top_k_accuracy_score` while `y_score` has only shape `(n_classes, )` (aka lacks information on the non-dominant classes).\n\n`y_true` is internally label-binarized to make it match a multi-label case.\n\nThere is no way to calculate `y_score` from a binarised `y_true`, since we lack information on the scores of the other classes.\nThus, `y_score` needs to be passed with shape `(n_samples, n_classes)`.\n\nThe previous error raised in `average_precision_score` from `check_array` for instance was \n```\nE ValueError: Expected 2D array, got 1D array instead:\nE array=[0.5 0.4 0.8 0.9 0.8 0.7].\nE Reshape your data either using array.reshape(-1, 1) if your data has a single feature or array.reshape(1, -1) if it contains a single sample.\n```\nwhich gives wrong advise. Users cannot deal with that by reshaping `y_score`.\n\n#### AI usage disclosure\n\nI used AI assistance for:\n- [ ] Code generation (e.g., when writing an implementation or fixing a bug)\n- [ ] Test/benchmark generation\n- [ ] Documentation (including examples)\n- [x] Research and understanding\n\n#### Any other comments?\nDiscovered while adding the `check_array_api_multiclass_classification_metric` test case in #32909.\n\nAlso added some documentation on the multiclass case for `average_precision_score`, since it was lacking.", "author": "user_501030d9d7e3", "created_at": "2025-12-16T15:43:51+00:00", "merged_at": "2026-01-02T13:01:58+00:00", "base_branch": "main", "head_branch": "fix_multiclass_average_precision_score", "additions": 37, "deletions": 4, "changed_files": 2, "files": [ { "filename": "sklearn/metrics/_ranking.py", "status": "modified", "additions": 21, "deletions": 2, "changes": 23, "patch": "@@ -142,7 +142,8 @@ def average_precision_score(\n Parameters\n ----------\n y_true : array-like of shape (n_samples,) or (n_samples, n_classes)\n- True binary labels or :term:`multilabel indicator matrix`.\n+ True binary labels, :term:`multi-label` indicators (as a\n+ :term:`multilabel indicator matrix`) or :term:`multi-class` labels.\n \n y_score : array-like of shape (n_samples,) or (n_samples, n_classes)\n Target scores, can either be probability estimates of the positive\n@@ -261,6 +262,12 @@ def _binary_uninterpolated_average_precision(\n \"Do not set pos_label or set pos_label to 1.\"\n )\n y_true = label_binarize(y_true, classes=present_labels)\n+ if not y_score.shape == y_true.shape:\n+ raise ValueError(\n+ \"`y_score` needs to be of shape `(n_samples, n_classes)`, since \"\n+ \"`y_true` contains multiple classes. Got \"\n+ f\"`y_score.shape={y_score.shape}`.\"\n+ )\n \n average_precision = partial(\n _binary_uninterpolated_average_precision, pos_label=pos_label\n@@ -764,7 +771,12 @@ def _multiclass_roc_auc_score(\n Sample weights.\n \n \"\"\"\n- # validation of the input y_score\n+ if not y_score.ndim == 2:\n+ raise ValueError(\n+ \"`y_score` needs to be of shape `(n_samples, n_classes)`, since \"\n+ \"`y_true` contains multiple classes. Got \"\n+ f\"`y_score.shape={y_score.shape}`.\"\n+ )\n if not np.allclose(1, y_score.sum(axis=1)):\n raise ValueError(\n \"Target scores need to be probabilities for multiclass \"\n@@ -2111,6 +2123,13 @@ def top_k_accuracy_score(\n \" labels, `labels` must be provided.\"\n )\n y_score = column_or_1d(y_score)\n+ else:\n+ if not y_score.ndim == 2:\n+ raise ValueError(\n+ \"`y_score` needs to be of shape `(n_samples, n_classes)`, since \"\n+ \"`y_true` contains multiple classes. Got \"\n+ f\"`y_score.shape={y_score.shape}`.\"\n+ )\n \n check_consistent_length(y_true, y_score, sample_weight)\n y_score_n_classes = y_score.shape[1] if y_score.ndim == 2 else 2" }, { "filename": "sklearn/metrics/tests/test_ranking.py", "status": "modified", "additions": 16, "deletions": 2, "changes": 18, "patch": "@@ -1212,7 +1212,7 @@ def test_average_precision_score_multilabel_pos_label_errors():\n def test_average_precision_score_multiclass_pos_label_errors():\n # Raise an error for multiclass y_true with pos_label other than 1\n y_true = np.array([0, 1, 2, 0, 1, 2])\n- y_pred = np.array(\n+ y_score = np.array(\n [\n [0.5, 0.2, 0.1],\n [0.4, 0.5, 0.3],\n@@ -1227,7 +1227,21 @@ def test_average_precision_score_multiclass_pos_label_errors():\n \"Do not set pos_label or set pos_label to 1.\"\n )\n with pytest.raises(ValueError, match=err_msg):\n- average_precision_score(y_true, y_pred, pos_label=3)\n+ average_precision_score(y_true, y_score, pos_label=3)\n+\n+\n+def test_multiclass_ranking_metrics_raise_for_incorrect_shape_of_y_score():\n+ \"\"\"Test ranking metrics, with multiclass support, raise if shape `y_score` is 1D.\"\"\"\n+ y_true = np.array([0, 1, 2, 0, 1, 2])\n+ y_score = np.array([0.5, 0.4, 0.8, 0.9, 0.8, 0.7])\n+\n+ msg = re.escape(\"`y_score` needs to be of shape `(n_samples, n_classes)`\")\n+ with pytest.raises(ValueError, match=msg):\n+ average_precision_score(y_true, y_score)\n+ with pytest.raises(ValueError, match=msg):\n+ roc_auc_score(y_true, y_score, multi_class=\"ovr\")\n+ with pytest.raises(ValueError, match=msg):\n+ top_k_accuracy_score(y_true, y_score)\n \n \n def test_score_scale_invariance():" } ], "reviews": [ { "id": 3583769127, "user": "user_501030d9d7e3", "state": "COMMENTED", "body": null, "submitted_at": "2025-12-16T15:44:25+00:00" }, { "id": 3585818289, "user": "user_d16337ec046b", "state": "COMMENTED", "body": "I think some other metrics in `_ranking.py` may also benefit from this extra check, even if just for consistency - e.g., `roc_auc_score` gives the following error (with the input from your new test), which is less informative:\n\n```\nAxisError: axis 1 is out of bounds for array of dimension 1\n```\n\nOtherwise looks good.", "submitted_at": "2025-12-17T08:41:31+00:00" }, { "id": 3592859064, "user": "user_501030d9d7e3", "state": "COMMENTED", "body": null, "submitted_at": "2025-12-18T13:00:36+00:00" }, { "id": 3595609848, "user": "user_d16337ec046b", "state": "COMMENTED", "body": "Do you think it is worth factorising this check out? Mostly so we can easily ensure the error message is always consistent, if it ever gets changed...", "submitted_at": "2025-12-18T23:16:45+00:00" }, { "id": 3595836096, "user": "user_d16337ec046b", "state": "COMMENTED", "body": null, "submitted_at": "2025-12-19T00:19:07+00:00" }, { "id": 3598357607, "user": "user_501030d9d7e3", "state": "COMMENTED", "body": null, "submitted_at": "2025-12-19T12:03:45+00:00" }, { "id": 3614272956, "user": "user_d16337ec046b", "state": "APPROVED", "body": "LGTM!", "submitted_at": "2025-12-27T09:44:11+00:00" }, { "id": 3619783970, "user": "user_bf0b6c7acb9c", "state": "APPROVED", "body": "LGTM! Thanks, [USER_REDACTED]!\n\nI only have a few optional suggestions, but feel free to merge this as is.", "submitted_at": "2025-12-31T00:41:38+00:00" } ], "review_comments": [ { "id": 2623814222, "user": "user_501030d9d7e3", "body": "Renamed it to match the param name.", "path": "sklearn/metrics/tests/test_ranking.py", "line": 1215, "side": "RIGHT", "created_at": "2025-12-16T15:44:11+00:00" }, { "id": 2625429833, "user": "user_d16337ec046b", "body": "We actually have a glossary term for indicator format: see #32893\n\nI agree that it would be nice to specify that it is multilabel type should be in indicator format, but it would also be nice to have a glossary reference to both multilabel and label indicator here - I think can manage both", "path": "sklearn/metrics/_ranking.py", "line": null, "side": "RIGHT", "created_at": "2025-12-17T03:06:44+00:00" }, { "id": 2630990528, "user": "user_501030d9d7e3", "body": "I didn't see your PR before. Will have a look. Do you want to include this suggestion in it and try to fit both links to multilabel and label indicator in there? I also think it is useful to link to both.", "path": "sklearn/metrics/_ranking.py", "line": null, "side": "RIGHT", "created_at": "2025-12-18T13:00:36+00:00" }, { "id": 2632956777, "user": "user_d16337ec046b", "body": "```suggestion\n \"\"\"Test ranking metrics, with multiclass support, raises if shape `y_score` is 1D\"\"\"\n```\nnit, to make it fit on one line, as per docstring standard", "path": "sklearn/metrics/tests/test_ranking.py", "line": null, "side": "RIGHT", "created_at": "2025-12-18T23:15:28+00:00" }, { "id": 2633118676, "user": "user_d16337ec046b", "body": "Hmm maybe it's better in this PR as it fits with the content here more? It does mean some minor merge conflict resolving but it would only be one line.", "path": "sklearn/metrics/_ranking.py", "line": null, "side": "RIGHT", "created_at": "2025-12-19T00:19:07+00:00" }, { "id": 2634882392, "user": "user_501030d9d7e3", "body": "I don't mind to have it here. Will also add the other reference and from your PR.", "path": "sklearn/metrics/_ranking.py", "line": null, "side": "RIGHT", "created_at": "2025-12-19T12:03:45+00:00" }, { "id": 2654356729, "user": "user_bf0b6c7acb9c", "body": "```suggestion\n f\"`{y_score.shape = }`.\"\n```", "path": "sklearn/metrics/_ranking.py", "line": 269, "side": "RIGHT", "created_at": "2025-12-31T00:34:12+00:00" }, { "id": 2654357092, "user": "user_bf0b6c7acb9c", "body": "```suggestion\n f\"`{y_score.shape = }`.\"\n```", "path": "sklearn/metrics/_ranking.py", "line": 778, "side": "RIGHT", "created_at": "2025-12-31T00:34:43+00:00" } ], "meta": { "languages": [ "py" ], "touches_tests": true, "review_state_summary": { "COMMENTED": 6, "APPROVED": 2 }, "meaningful_comment_count": 8, "has_approval": true, "has_changes_requested": false, "total_review_comments": 8 } } { "_id": "0d68394152b22e2e", "_schema_version": "1.0", "_cleaned_at": "2026-02-12T07:46:51.976223+00:00", "repo": "scikit-learn/scikit-learn", "repo_url": "https://github.com/scikit-learn/scikit-learn", "license_name": "BSD 3-Clause \"New\" or \"Revised\" License", "license_spdx": "BSD-3-Clause", "pr_number": 32909, "title": "FEA Add array API support for `average_precision_score`", "body": "#### [NAME_REDACTED]/PRs\ntowards #26024\n\n#### What does this implement/fix? Explain your changes.\nAdds array API support to `average_precision_score`\n\n#### AI usage disclosure\n\nI used AI assistance for:\n- [ ] Code generation (e.g., when writing an implementation or fixing a bug)\n- [ ] Test/benchmark generation\n- [ ] Documentation (including examples)\n- [x] Research and understanding\n\n#### Any other comments?\nWIP\n\nTODO:\n- [x] add array API in `average_precision_score`\n- [x] add common metrics test\n- [x] add average_precision_score to the array API docs\n- [x] removed old fix for numpy<= 1.24.1 from `average_precision_score` as well as from `_check_set_wise_labels` which allows to have `present_labels` as an array instead of a list\n- [x] use `LabelBinarizer` instead of `label_binarize` # TODO: check if in fact necessary\n- [x] add array API in `_average_binary_score`\n- [x] fix remaining test failures\n- [x] add changelog\n- [x] make it accept mixed namespace inputs \n- [ ] (only necessary if #32755 is merged first) add new test case for `average_precision_score` in `METRICS_SUPPORTING_MIXED_NAMESPACE` in `sklearn/metrics/tests/test_common.py`", "author": "user_501030d9d7e3", "created_at": "2025-12-16T12:04:56+00:00", "merged_at": "2026-01-23T01:58:15+00:00", "base_branch": "main", "head_branch": "array_api_average_precision_score", "additions": 71, "deletions": 25, "changed_files": 5, "files": [ { "filename": "doc/modules/array_api.rst", "status": "modified", "additions": 1, "deletions": 0, "changes": 1, "patch": "@@ -160,6 +160,7 @@ Metrics\n -------\n \n - :func:`sklearn.metrics.accuracy_score`\n+- :func:`sklearn.metrics.average_precision_score`\n - :func:`sklearn.metrics.balanced_accuracy_score`\n - :func:`sklearn.metrics.brier_score_loss`\n - :func:`sklearn.metrics.cluster.calinski_harabasz_score`" }, { "filename": "doc/whats_new/upcoming_changes/array-api/32909.feature.rst", "status": "added", "additions": 3, "deletions": 0, "changes": 3, "patch": "@@ -0,0 +1,3 @@\n+- :func:`sklearn.metrics.ranking.average_precision_score` now supports Array API\n+ compliant inputs.\n+ By :user:`[NAME_REDACTED] `." }, { "filename": "sklearn/metrics/_base.py", "status": "modified", "additions": 28, "deletions": 17, "changes": 45, "patch": "@@ -10,7 +10,9 @@\n \n import numpy as np\n \n+import sklearn.externals.array_api_extra as xpx\n from sklearn.utils import check_array, check_consistent_length\n+from sklearn.utils._array_api import _average, _ravel, get_namespace_and_device\n from sklearn.utils.multiclass import type_of_target\n \n \n@@ -19,6 +21,9 @@ def _average_binary_score(binary_metric, y_true, y_score, average, sample_weight\n \n Parameters\n ----------\n+ binary_metric : callable, returns shape [n_classes]\n+ The binary metric function to use.\n+\n y_true : array, shape = [n_samples] or [n_samples, n_classes]\n True binary labels in binary label indicators.\n \n@@ -47,16 +52,14 @@ def _average_binary_score(binary_metric, y_true, y_score, average, sample_weight\n sample_weight : array-like of shape (n_samples,), default=None\n Sample weights.\n \n- binary_metric : callable, returns shape [n_classes]\n- The binary metric function to use.\n-\n Returns\n -------\n score : float or array of shape [n_classes]\n If not ``None``, average the score, else return the score for each\n classes.\n \n \"\"\"\n+ xp, _, _device = get_namespace_and_device(y_true, y_score, sample_weight)\n average_options = (None, \"micro\", \"macro\", \"weighted\", \"samples\")\n if average not in average_options:\n raise ValueError(\"average has to be one of {0}\".format(average_options))\n@@ -78,18 +81,23 @@ def _average_binary_score(binary_metric, y_true, y_score, average, sample_weight\n \n if average == \"micro\":\n if score_weight is not None:\n- score_weight = np.repeat(score_weight, y_true.shape[1])\n- y_true = y_true.ravel()\n- y_score = y_score.ravel()\n+ score_weight = xp.repeat(score_weight, y_true.shape[1])\n+ y_true = _ravel(y_true)\n+ y_score = _ravel(y_score)\n \n elif average == \"weighted\":\n if score_weight is not None:\n- average_weight = np.sum(\n- np.multiply(y_true, np.reshape(score_weight, (-1, 1))), axis=0\n+ # Mixed integer and float type promotion not defined in array standard\n+ y_true = xp.asarray(y_true, dtype=score_weight.dtype)\n+ average_weight = xp.sum(\n+ xp.multiply(y_true, xp.reshape(score_weight, (-1, 1))), axis=0\n )\n else:\n- average_weight = np.sum(y_true, axis=0)\n- if np.isclose(average_weight.sum(), 0.0):\n+ average_weight = xp.sum(y_true, axis=0)\n+ if xpx.isclose(\n+ xp.sum(average_weight),\n+ xp.asarray(0, dtype=average_weight.dtype, device=_device),\n+ ):\n return 0\n \n elif average == \"samples\":\n@@ -99,26 +107,29 @@ def _average_binary_score(binary_metric, y_true, y_score, average, sample_weight\n not_average_axis = 0\n \n if y_true.ndim == 1:\n- y_true = y_true.reshape((-1, 1))\n+ y_true = xp.reshape(y_true, (-1, 1))\n \n if y_score.ndim == 1:\n- y_score = y_score.reshape((-1, 1))\n+ y_score = xp.reshape(y_score, (-1, 1))\n \n n_classes = y_score.shape[not_average_axis]\n- score = np.zeros((n_classes,))\n+ score = xp.zeros((n_classes,), device=_device)\n for c in range(n_classes):\n- y_true_c = y_true.take([c], axis=not_average_axis).ravel()\n- y_score_c = y_score.take([c], axis=not_average_axis).ravel()\n+ y_true_c = _ravel(\n+ xp.take(y_true, xp.asarray([c], device=_device), axis=not_average_axis)\n+ )\n+ y_score_c = _ravel(\n+ xp.take(y_score, xp.asarray([c], device=_device), axis=not_average_axis)\n+ )\n score[c] = binary_metric(y_true_c, y_score_c, sample_weight=score_weight)\n \n # Average the results\n if average is not None:\n if average_weight is not None:\n # Scores with 0 weights are forced to be 0, preventing the average\n # score from being affected by 0-weighted NaN elements.\n- average_weight = np.asarray(average_weight)\n score[average_weight == 0] = 0\n- return float(np.average(score, weights=average_weight))\n+ return float(_average(score, weights=average_weight, xp=xp))\n else:\n return score" }, { "filename": "sklearn/metrics/_ranking.py", "status": "modified", "additions": 22, "deletions": 8, "changes": 30, "patch": "@@ -31,6 +31,7 @@\n from sklearn.utils._array_api import (\n _max_precision_float_dtype,\n get_namespace_and_device,\n+ move_to,\n size,\n )\n from sklearn.utils._encode import _encode, _unique\n@@ -225,25 +226,36 @@ def average_precision_score(\n >>> average_precision_score(y_true, y_scores)\n 0.77\n \"\"\"\n+ xp, _, device = get_namespace_and_device(y_score)\n+ y_true, sample_weight = move_to(y_true, sample_weight, xp=xp, device=device)\n+\n+ if sample_weight is not None:\n+ sample_weight = column_or_1d(sample_weight)\n \n def _binary_uninterpolated_average_precision(\n- y_true, y_score, pos_label=1, sample_weight=None\n+ y_true,\n+ y_score,\n+ pos_label=1,\n+ sample_weight=None,\n+ xp=xp,\n ):\n precision, recall, _ = precision_recall_curve(\n- y_true, y_score, pos_label=pos_label, sample_weight=sample_weight\n+ y_true,\n+ y_score,\n+ pos_label=pos_label,\n+ sample_weight=sample_weight,\n )\n # Return the step function integral\n # The following works because the last entry of precision is\n # guaranteed to be 1, as returned by precision_recall_curve.\n # Due to numerical error, we can get `-0.0` and we therefore clip it.\n- return float(max(0.0, -np.sum(np.diff(recall) * np.array(precision)[:-1])))\n+ return float(max(0.0, -xp.sum(xp.diff(recall) * precision[:-1])))\n \n y_type = type_of_target(y_true, input_name=\"y_true\")\n-\n- present_labels = np.unique(y_true)\n+ present_labels = xp.unique_values(y_true)\n \n if y_type == \"binary\":\n- if len(present_labels) == 2 and pos_label not in present_labels:\n+ if present_labels.shape[0] == 2 and pos_label not in present_labels:\n raise ValueError(\n f\"pos_label={pos_label} is not a valid label. It should be \"\n f\"one of {present_labels}\"\n@@ -270,7 +282,7 @@ def _binary_uninterpolated_average_precision(\n )\n \n average_precision = partial(\n- _binary_uninterpolated_average_precision, pos_label=pos_label\n+ _binary_uninterpolated_average_precision, pos_label=pos_label, xp=xp\n )\n return _average_binary_score(\n average_precision, y_true, y_score, average, sample_weight=sample_weight\n@@ -686,6 +698,8 @@ class scores must correspond to the order of ``labels``,\n y_type = type_of_target(y_true, input_name=\"y_true\")\n y_true = check_array(y_true, ensure_2d=False, dtype=None)\n y_score = check_array(y_score, ensure_2d=False)\n+ if sample_weight is not None:\n+ sample_weight = column_or_1d(sample_weight)\n \n if y_type == \"multiclass\" or (\n y_type == \"binary\" and y_score.ndim == 2 and y_score.shape[1] > 2\n@@ -1142,7 +1156,7 @@ def precision_recall_curve(\n \"No positive class found in y_true, \"\n \"recall is set to one for all thresholds.\"\n )\n- recall = xp.full(tps.shape, 1.0)\n+ recall = xp.full(tps.shape, 1.0, device=device)\n else:\n recall = tps / tps[-1]" }, { "filename": "sklearn/metrics/tests/test_common.py", "status": "modified", "additions": 17, "deletions": 0, "changes": 17, "patch": "@@ -2098,6 +2098,18 @@ def check_array_api_multiclass_classification_metric(\n y_true_np = np.array([0, 1, 2, 3])\n y_pred_np = np.array([0, 1, 0, 2])\n \n+ if metric.__name__ == \"average_precision_score\":\n+ # we need y_pred_nd to be of shape (n_samples, n_classes)\n+ y_pred_np = np.array(\n+ [\n+ [0.7, 0.2, 0.05, 0.05],\n+ [0.1, 0.8, 0.05, 0.05],\n+ [0.1, 0.1, 0.7, 0.1],\n+ [0.05, 0.05, 0.1, 0.8],\n+ ],\n+ dtype=dtype_name,\n+ )\n+\n additional_params = {\n \"average\": (\"micro\", \"macro\", \"weighted\"),\n \"beta\": (0.2, 0.5, 0.8),\n@@ -2299,6 +2311,11 @@ def check_array_api_metric_pairwise(metric, array_namespace, device, dtype_name)\n check_array_api_multiclass_classification_metric,\n check_array_api_multilabel_classification_metric,\n ],\n+ average_precision_score: [\n+ check_array_api_binary_classification_metric,\n+ check_array_api_multiclass_classification_metric,\n+ check_array_api_multilabel_classification_metric,\n+ ],\n balanced_accuracy_score: [\n check_array_api_binary_classification_metric,\n check_array_api_multiclass_classification_metric," } ], "reviews": [ { "id": 3582752553, "user": "user_501030d9d7e3", "state": "COMMENTED", "body": null, "submitted_at": "2025-12-16T12:15:18+00:00" }, { "id": 3582784302, "user": "user_501030d9d7e3", "state": "COMMENTED", "body": null, "submitted_at": "2025-12-16T12:15:32+00:00" }, { "id": 3584001281, "user": "user_501030d9d7e3", "state": "COMMENTED", "body": null, "submitted_at": "2025-12-16T16:55:13+00:00" }, { "id": 3584158717, "user": "user_501030d9d7e3", "state": "COMMENTED", "body": null, "submitted_at": "2025-12-16T17:17:55+00:00" }, { "id": 3587794700, "user": "user_501030d9d7e3", "state": "COMMENTED", "body": null, "submitted_at": "2025-12-17T13:36:33+00:00" }, { "id": 3587858281, "user": "user_501030d9d7e3", "state": "COMMENTED", "body": null, "submitted_at": "2025-12-17T13:51:16+00:00" }, { "id": 3593206431, "user": "user_bf0b6c7acb9c", "state": "COMMENTED", "body": null, "submitted_at": "2025-12-18T14:22:04+00:00" }, { "id": 3593335500, "user": "user_501030d9d7e3", "state": "COMMENTED", "body": null, "submitted_at": "2025-12-18T14:38:48+00:00" }, { "id": 3598430797, "user": "user_501030d9d7e3", "state": "COMMENTED", "body": null, "submitted_at": "2025-12-19T12:25:52+00:00" }, { "id": 3611241048, "user": "user_5819d17296ee", "state": "COMMENTED", "body": null, "submitted_at": "2025-12-24T15:23:51+00:00" }, { "id": 3613494766, "user": "user_501030d9d7e3", "state": "COMMENTED", "body": null, "submitted_at": "2025-12-26T13:35:58+00:00" }, { "id": 3633490735, "user": "user_d16337ec046b", "state": "COMMENTED", "body": null, "submitted_at": "2026-01-07T06:16:13+00:00" }, { "id": 3633506916, "user": "user_d16337ec046b", "state": "COMMENTED", "body": null, "submitted_at": "2026-01-07T06:23:53+00:00" }, { "id": 3633705057, "user": "user_501030d9d7e3", "state": "COMMENTED", "body": null, "submitted_at": "2026-01-07T07:47:03+00:00" }, { "id": 3633762740, "user": "user_501030d9d7e3", "state": "COMMENTED", "body": null, "submitted_at": "2026-01-07T08:07:16+00:00" }, { "id": 3633831196, "user": "user_501030d9d7e3", "state": "COMMENTED", "body": null, "submitted_at": "2026-01-07T08:30:17+00:00" }, { "id": 3634130279, "user": "user_d16337ec046b", "state": "COMMENTED", "body": null, "submitted_at": "2026-01-07T09:58:52+00:00" }, { "id": 3634152181, "user": "user_d16337ec046b", "state": "COMMENTED", "body": "Just a question and a nit.", "submitted_at": "2026-01-07T10:45:39+00:00" }, { "id": 3639331284, "user": "user_501030d9d7e3", "state": "COMMENTED", "body": null, "submitted_at": "2026-01-08T13:00:33+00:00" }, { "id": 3639451306, "user": "user_501030d9d7e3", "state": "COMMENTED", "body": null, "submitted_at": "2026-01-08T13:33:38+00:00" }, { "id": 3639681102, "user": "user_501030d9d7e3", "state": "COMMENTED", "body": null, "submitted_at": "2026-01-08T14:28:23+00:00" }, { "id": 3642231521, "user": "user_d16337ec046b", "state": "COMMENTED", "body": null, "submitted_at": "2026-01-09T03:51:16+00:00" }, { "id": 3642807380, "user": "user_501030d9d7e3", "state": "COMMENTED", "body": null, "submitted_at": "2026-01-09T08:03:54+00:00" }, { "id": 3642839354, "user": "user_501030d9d7e3", "state": "COMMENTED", "body": null, "submitted_at": "2026-01-09T08:14:21+00:00" }, { "id": 3649745904, "user": "user_d5b9cb906259", "state": "COMMENTED", "body": null, "submitted_at": "2026-01-12T09:04:31+00:00" }, { "id": 3655782750, "user": "user_501030d9d7e3", "state": "COMMENTED", "body": null, "submitted_at": "2026-01-13T13:24:35+00:00" }, { "id": 3659484927, "user": "user_d16337ec046b", "state": "COMMENTED", "body": null, "submitted_at": "2026-01-14T08:30:20+00:00" }, { "id": 3660673479, "user": "user_501030d9d7e3", "state": "COMMENTED", "body": null, "submitted_at": "2026-01-14T13:11:10+00:00" }, { "id": 3665012144, "user": "user_49a647962c6b", "state": "COMMENTED", "body": null, "submitted_at": "2026-01-15T10:57:21+00:00" }, { "id": 3674286629, "user": "user_501030d9d7e3", "state": "COMMENTED", "body": "Thank you [USER_REDACTED], [USER_REDACTED] and [USER_REDACTED]. I have now used `column_or_1d(sample_weight)` for an early `check_array` on it (see https://github.com/[USER_REDACTED]n/scikit-learn/pull/32909#discussion_r2701343355) and also removed the special casing of array_api_strict in `xp.multiply` (see https://github.com/[USER_REDACTED]n/scikit-learn/pull/32909#discussion_r2701298993).\n\nThere is one open question whether we should do \n\n```py\n y_true_c = _ravel(\n xp.take(y_true, xp.asarray([c], device=_device), axis=not_average_axis)\n )\n y_score_c = _ravel(\n xp.take(y_score, xp.asarray([c], device=_device), axis=not_average_axis)\n )\n```\n \nor \n\n```py\n y_true_rotated = xp.moveaxis(y_true, not_average_axis, -1)\n y_true_c = _ravel(y_true_rotated[..., c])\n y_score_rotated = xp.moveaxis(y_score, not_average_axis, -1)\n y_score_c = _ravel(y_score_rotated[..., c])\n```\n\nor something else (see https://github.com/[USER_REDACTED]n/scikit-learn/pull/32909#discussion_r2701341753).", "submitted_at": "2026-01-17T18:47:07+00:00" }, { "id": 3677956992, "user": "user_49a647962c6b", "state": "COMMENTED", "body": null, "submitted_at": "2026-01-19T12:49:47+00:00" }, { "id": 3677972642, "user": "user_49a647962c6b", "state": "APPROVED", "body": "As far as I can tell, LGTM.", "submitted_at": "2026-01-19T12:53:52+00:00" }, { "id": 3680016968, "user": "user_bf0b6c7acb9c", "state": "APPROVED", "body": "LGTM as well! Thanks, [USER_REDACTED]!\n\nJust one minor nitpick.\n\nAlso, perhaps [USER_REDACTED] or [USER_REDACTED] could take a look before merging.", "submitted_at": "2026-01-20T01:48:59+00:00" }, { "id": 3681216930, "user": "user_d16337ec046b", "state": "COMMENTED", "body": null, "submitted_at": "2026-01-20T09:32:05+00:00" }, { "id": 3681227879, "user": "user_501030d9d7e3", "state": "COMMENTED", "body": null, "submitted_at": "2026-01-20T09:34:44+00:00" }, { "id": 3681551702, "user": "user_501030d9d7e3", "state": "COMMENTED", "body": null, "submitted_at": "2026-01-20T10:48:18+00:00" }, { "id": 3690225183, "user": "user_d16337ec046b", "state": "COMMENTED", "body": null, "submitted_at": "2026-01-22T01:56:09+00:00" }, { "id": 3690652421, "user": "user_d16337ec046b", "state": "COMMENTED", "body": "Nits and a question, otherwise looks good!", "submitted_at": "2026-01-22T06:33:08+00:00" }, { "id": 3692660692, "user": "user_501030d9d7e3", "state": "COMMENTED", "body": null, "submitted_at": "2026-01-22T14:13:24+00:00" }, { "id": 3692681167, "user": "user_501030d9d7e3", "state": "COMMENTED", "body": null, "submitted_at": "2026-01-22T14:18:08+00:00" } ], "review_comments": [ { "id": 2623009511, "user": "user_501030d9d7e3", "body": "This change is a consequence of `present_labels` now being an array, not a list.\nSee [this comment](https://github.com/[USER_REDACTED]n/scikit-learn/pull/32909/changes#r2623035023).", "path": "sklearn/metrics/tests/test_classification.py", "line": 1575, "side": "RIGHT", "created_at": "2025-12-16T12:06:51+00:00" }, { "id": 2623012748, "user": "user_501030d9d7e3", "body": "I changed the order of the params in the docs to match the order of reading these into the function, like in all the other places.", "path": "sklearn/metrics/_base.py", "line": 26, "side": "RIGHT", "created_at": "2025-12-16T12:08:03+00:00" }, { "id": 2623035023, "user": "user_501030d9d7e3", "body": "This had been fixed three years ago, see https://github.com/numpy/numpy/issues/6784#issuecomment-1341719384. It makes sense to keep `present_labels` as an array instead of turning it into a list.\n\nI suppose this fix went into numpy 1.24.1 or even earlier.", "path": "sklearn/metrics/_classification.py", "line": 1864, "side": "RIGHT", "created_at": "2025-12-16T12:15:32+00:00" }, { "id": 2623998837, "user": "user_501030d9d7e3", "body": "This case handling needs to be added, because `average_precision_score` handels multiclass inputs by [NAME_REDACTED] a consequence, y_score needs to be of shape `(n_samples, n_classes)`. I have made a PR with a fix here: #32912.", "path": "sklearn/metrics/tests/test_common.py", "line": 2112, "side": "RIGHT", "created_at": "2025-12-16T16:41:06+00:00" }, { "id": 2624110380, "user": "user_501030d9d7e3", "body": "This prevents an error from `array_api_strict`:\n\n`TypeError: array_api_strict.int64 and array_api_strict.float64 cannot be type promoted together`\n\nBut actually, we should not change our code just to make a helper library happy. I need to think a bit more about this.", "path": "sklearn/metrics/_ranking.py", "line": null, "side": "RIGHT", "created_at": "2025-12-16T17:17:05+00:00" }, { "id": 2624112430, "user": "user_501030d9d7e3", "body": "This is not needed anymore, since `average_weight` is converted to an array earlier.", "path": "sklearn/metrics/_base.py", "line": 119, "side": "LEFT", "created_at": "2025-12-16T17:17:48+00:00" }, { "id": 2627102404, "user": "user_501030d9d7e3", "body": "This (hopefully) fixes an error occurring on the CI ([link to output)](https://dev.azure.com/scikit-learn/scikit-learn/_build/results?buildId=83504&view=logs&j=dde5042c-7464-5d47-9507-31bdd2ee0a3a&t=4bd2dad8-62b3-5bf9-08a5-a9880c530c94):\n\n```\nE TypeError: sum() received an invalid combination of arguments - got (out=NoneType, axis=int, ), but expected one of:\nE * (*, torch.dtype dtype = None)\nE didn't match because some of the keywords were incorrect: out, axis\nE * (tuple of ints dim, bool keepdim = False, *, torch.dtype dtype = None)\nE * (tuple of names dim, bool keepdim = False, *, torch.dtype dtype = None)\n```\n\n[USER_REDACTED] and I investigated this together. It seems that `numpy.sum() `when passed a torch tensor, internally tries to dispatch to torch, but that fails because `torch.sum() `doesn't have the `out` argument. The same happens with `np.repeat()` which has an `axis` argument, but `torch.repeat()` hasn't (which had raised in my setup locally).", "path": "sklearn/metrics/_ranking.py", "line": null, "side": "RIGHT", "created_at": "2025-12-17T13:36:03+00:00" }, { "id": 2627155438, "user": "user_501030d9d7e3", "body": "This had been fixed three years ago, see https://github.com/numpy/numpy/issues/6784#issuecomment-1341719384. It makes sense to keep `present_labels` as an array instead of turning it into a list.\n\nI suppose this fix went into numpy 1.24.1 or even earlier.", "path": "sklearn/metrics/_ranking.py", "line": 255, "side": "RIGHT", "created_at": "2025-12-17T13:51:16+00:00" }, { "id": 2631260234, "user": "user_bf0b6c7acb9c", "body": "`_average_binary_score` is also used in `roc_auc_score`. So it's probably best to first discuss how to properly add array API support to it, or wait until this PR is merged before creating a PR for `roc_auc_score`.", "path": "sklearn/metrics/_base.py", "line": 26, "side": "RIGHT", "created_at": "2025-12-18T14:12:58+00:00" }, { "id": 2631283359, "user": "user_bf0b6c7acb9c", "body": "```suggestion\nfrom sklearn.utils._array_api import _ravel, get_namespace_and_device, xpx\n```", "path": "sklearn/metrics/_base.py", "line": null, "side": "RIGHT", "created_at": "2025-12-18T14:19:33+00:00" }, { "id": 2631290916, "user": "user_bf0b6c7acb9c", "body": "Yes, I ran into the same issue when I was working on `roc_auc_score`.", "path": "sklearn/metrics/_ranking.py", "line": null, "side": "RIGHT", "created_at": "2025-12-18T14:21:47+00:00" }, { "id": 2631354475, "user": "user_501030d9d7e3", "body": "I made a separate PR for it and it is merged: #32917.\nThis comment is resolved here.", "path": "sklearn/metrics/_classification.py", "line": 1864, "side": "RIGHT", "created_at": "2025-12-18T14:38:48+00:00" }, { "id": 2634939771, "user": "user_501030d9d7e3", "body": "I wasn't aware of that, and maybe that had been discussed somewhere I missed. So I did a bit of searching and I have found `xpx` imported via `_array_api.py` in `sklearn/model_selection/_search.py` and in `sklearn/tree/tests/test_tree.py`. \nAnd I have found `from sklearn.externals import array_api_extra as xpx` imports in three other files.\n\nI prefer the more explicit import from `sklearn.externals`, since it is easier to see what is going on the first glance even if you are unfamiliar with array api, and it will have to be obvious for people unfamilar with array api, as it will be in every function in the future and we also want to make it easy for future contributors.", "path": "sklearn/metrics/_base.py", "line": null, "side": "RIGHT", "created_at": "2025-12-19T12:25:52+00:00" }, { "id": 2645927356, "user": "user_5819d17296ee", "body": "Instead of converting everything to NumPy ahead of time, we should inspect the namespace and device of `y_score` only. Indeed, we want to allow `y_true` to have an object dtype for string class labels (hence a NumPy array) even when the predictions are a non-NumPy namespace with a non-CPU device.\n\nSee: https://scikit-learn.org/dev/modules/array_api.html#scoring-functions\n\n`y_true` should thereafter convert to binary indicators (using `pos_label` when available, and moved to the same device, dtype and namespace as `y_score` just before doing the arithmetic computation.\n\n`sample_weight` should similarly follow the namespace, dtype and device of `y_score` using `move_to`.\n\nSee the discussion and implementation of the common test being worked on in #32755 for mixed input metrics.", "path": "sklearn/metrics/_ranking.py", "line": null, "side": "RIGHT", "created_at": "2025-12-24T15:23:51+00:00" }, { "id": 2648254097, "user": "user_501030d9d7e3", "body": "I will keep your comment in mind for later, but this here addresses a different problem. It fixes a test failure if array api is **not** enabled and all inputs (specifically `y_true` and `y_score`) are torch tensors on cpu.\n\nIn `check_array_api_metric()` we have defined a `numpy_as_array_works` boolean that is `True` if array api is not enabled, but we get input from a non-numpy namespace that can be converted to numpy (see [here](https://github.com/[USER_REDACTED]n/scikit-learn/blob/4ac107924f6c017481c1a8c432c0512a9ec2dc0a/sklearn/metrics/tests/test_common.py#L1999-L2006)):\n\n```py\n # When array API dispatch is disabled, and np.asarray works (for example PyTorch\n # with CPU device), calling the metric function with such numpy compatible inputs\n # should work (albeit by [NAME_REDACTED] arrays instead of\n # dispatching to the array library).\n try:\n np.asarray(a_xp)\n np.asarray(b_xp)\n numpy_as_array_works = True\n```\n\nIn this case, we feed two torch arrays into the metric, but the test fails (see [here](https://github.com/[USER_REDACTED]n/scikit-learn/blob/4ac107924f6c017481c1a8c432c0512a9ec2dc0a/sklearn/metrics/tests/test_common.py#L2023-L2024)):\n\n```py\n if numpy_as_array_works:\n metric_xp = metric(a_xp, b_xp, **metric_kwargs)\n```\n\nIf I have understood correctly, then we would always try to convert to numpy, `if get_config().get(\"array_api_dispatch\", False)` but the input would be convertible to numpy, and making sure that we do is the purpose of this test (added in #30454).\n\n(In this WIP PR I haven't taken care of mixed inputs at all yet, also #32755 is not merged yet.\nSee: \n\"image\"\n)", "path": "sklearn/metrics/_ranking.py", "line": null, "side": "RIGHT", "created_at": "2025-12-26T13:35:53+00:00" }, { "id": 2667201162, "user": "user_d16337ec046b", "body": "Sorry, I didn't follow what has been fixed. Did we test for a Future warning?", "path": "sklearn/metrics/_ranking.py", "line": 255, "side": "RIGHT", "created_at": "2026-01-07T06:16:13+00:00" }, { "id": 2667215909, "user": "user_d16337ec046b", "body": "Maybe we could add a comment about why we are doing this?\n\nJust to clarify, what was previously doing the asarray for torch inputs? `type_of_target` does do `check_array`, but does that not fix the error?", "path": "sklearn/metrics/_ranking.py", "line": null, "side": "RIGHT", "created_at": "2026-01-07T06:23:53+00:00" }, { "id": 2667394269, "user": "user_501030d9d7e3", "body": "This comment is resolved. I've fixed this in a separate PR (#32917).", "path": "sklearn/metrics/_ranking.py", "line": 255, "side": "RIGHT", "created_at": "2026-01-07T07:47:02+00:00" }, { "id": 2667448022, "user": "user_501030d9d7e3", "body": "> Just to clarify, what was previously doing the asarray for torch inputs?\n\nThe asarray works as expected, no problems here.\n\nThe error raised in:\n\nhttps://github.com/[USER_REDACTED]n/scikit-learn/blob/938cd9798879757d8f681d5c82cdf0503aac96a3/sklearn/metrics/_base.py#L87-L89\n\nwhen a torch tensor was passed (because then `np.sum()` internally calls torch.sum, which doesn't take an `out` argument.\n\nI've tried to explain this above:\n\n> It seems that numpy.sum() when passed a torch tensor, internally tries to dispatch to torch, but that fails because torch.sum() doesn't have the out argument.\n\nIt is a known bug in numpy. [USER_REDACTED] found this related issue: [numpy/numpy/#28096.](https://github.com/numpy/numpy/issues/28024).\nSame for `np.repeat` (when passed a torch tensor), which raised locally for me.\n\nI will add a comment pointing to it.", "path": "sklearn/metrics/_ranking.py", "line": null, "side": "RIGHT", "created_at": "2026-01-07T08:07:16+00:00" }, { "id": 2667509431, "user": "user_501030d9d7e3", "body": "I've added a comment on this in https://github.com/[USER_REDACTED]n/scikit-learn/pull/32909/changes/9d8bd4632a55e17cdfc28a43637f0d42e628ff7a.", "path": "sklearn/metrics/_ranking.py", "line": null, "side": "RIGHT", "created_at": "2026-01-07T08:30:17+00:00" }, { "id": 2667781684, "user": "user_d16337ec046b", "body": "Sorry my confusion is more that I thought previously (and now with dispatch off) we converted all inputs to numpy (also as we generally allow lists, the `np.array` or `np.asarray` call was necessary)? \nWhich input is a torch tensor...?", "path": "sklearn/metrics/_ranking.py", "line": null, "side": "RIGHT", "created_at": "2026-01-07T09:58:52+00:00" }, { "id": 2667802406, "user": "user_d16337ec046b", "body": "Maybe we could add a comment about why we are doing this?", "path": "sklearn/metrics/_base.py", "line": null, "side": "RIGHT", "created_at": "2026-01-07T10:03:31+00:00" }, { "id": 2667938057, "user": "user_d16337ec046b", "body": "Digging into it, it seems that `precision_recall_curve` -> `confusion_matrix_at_thresholds` which calls `column_or_1d` on `y_true` and `y_score`, which does a `check_array`, which I thought ends up calling `_asarray_with_order` and would convert to numpy array (with dispatch disabled)?\n\n
      \nAside\n\nAside, I noticed that although we specify inputs can be 'array-like' when the input is indicator matrix, list does not work (checked on main):\n\n```python\nfrom sklearn.metrics import average_precision_score\ny_true = [0, 0, 1, 1, 2, 2]\ny_scores = [\n [0.7, 0.2, 0.1],\n [0.4, 0.3, 0.3],\n [0.1, 0.8, 0.1],\n [0.2, 0.3, 0.5],\n [0.4, 0.4, 0.2],\n [0.1, 0.2, 0.7],\n]\naverage_precision_score(y_true, y_scores)\n```\n\ngives:\n```\n---------------------------------------------------------------------------\nAttributeError Traceback (most recent call last)\n[NAME_REDACTED][3], line 1\n----> 1 average_precision_score(y_true, y_scores)\n\nFile ~/Documents/dev/scikit-learn/sklearn/utils/_param_validation.py:218, in validate_params..decorator..wrapper(*args, **kwargs)\n 212 try:\n 213 with config_context(\n 214 skip_parameter_validation=(\n 215 prefer_skip_nested_validation or global_skip_validation\n 216 )\n 217 ):\n--> 218 return func(*args, **kwargs)\n 219 except InvalidParameterError as e:\n 220 # When the function is just a wrapper around an estimator, we allow\n 221 # the function to delegate validation to the estimator, but we replace\n 222 # the name of the estimator by [NAME_REDACTED] function in the error\n 223 # message to avoid confusion.\n 224 msg = re.sub(\n 225 r\"parameter of \\w+ must be\",\n 226 f\"parameter of {func.__qualname__} must be\",\n 227 str(e),\n 228 )\n\nFile ~/Documents/dev/scikit-learn/sklearn/metrics/_ranking.py:265, in average_precision_score(y_true, y_score, average, pos_label, sample_weight)\n 260 raise ValueError(\n 261 \"Parameter pos_label is fixed to 1 for multiclass y_true. \"\n 262 \"Do not set pos_label or set pos_label to 1.\"\n 263 )\n 264 y_true = label_binarize(y_true, classes=present_labels)\n--> 265 if not y_score.shape == y_true.shape:\n 266 raise ValueError(\n 267 \"`y_score` needs to be of shape `(n_samples, n_classes)`, since \"\n 268 \"`y_true` contains multiple classes. Got \"\n 269 f\"`y_score.shape={y_score.shape}`.\"\n 270 )\n 272 average_precision = partial(\n 273 _binary_uninterpolated_average_precision, pos_label=pos_label\n 274 )\n\nAttributeError: 'list' object has no attribute 'shape'\n```\n\nThis is because in `confusion_matrix_at_thresholds` we do `check_consistent_length` before converting to array via `column_or_1d`.\n\nEdit: I am happy to fix, just wanted to document while I was here.\n
      ", "path": "sklearn/metrics/_ranking.py", "line": null, "side": "RIGHT", "created_at": "2026-01-07T10:44:47+00:00" }, { "id": 2672271507, "user": "user_501030d9d7e3", "body": "> Digging into it, it seems that precision_recall_curve -> confusion_matrix_at_thresholds which calls column_or_1d on y_true and y_score, which does a check_array, which I thought ends up calling _asarray_with_order and would convert to numpy array (with dispatch disabled)?\n\n`precision_recall_curve` indeed does that, but `average_precision_score` does not.", "path": "sklearn/metrics/_ranking.py", "line": null, "side": "RIGHT", "created_at": "2026-01-08T13:00:33+00:00" }, { "id": 2672379660, "user": "user_501030d9d7e3", "body": "> Sorry my confusion is more that I thought previously (and now with dispatch off) we converted all inputs to numpy (also as we generally allow lists, the np.array or np.asarray call was necessary)?\n> Which input is a torch tensor...?\n\nIn this test, we check if the inputs (both `y_true` and `y_score`) can be converted to numpy and if they can, we call the metric with `array_api_dispatch=False ` on all the input types:\n \nhttps://github.com/[USER_REDACTED]n/scikit-learn/blob/3ca712bec1a90f54adc7d7883f0f5f0c6b325e2b/sklearn/metrics/tests/test_common.py#L1999-L2024\n\nThis raises on line 2024, where both `a_xp`, `b_xp`, and `sample_weight` in `metric_kwargs` (if provided) are torch tensors.\n\nA pity the traceback from the CI is now gone, I cannot re-create exactly the same locally (only a similar error concerning `np.repeat`, but let's not complicate this here with the `np.repeat` case, let's first find a common understanding of the problem.)\n\nWhat happens if you comment out the part of the code we are discussing and run the tests?", "path": "sklearn/metrics/_ranking.py", "line": null, "side": "RIGHT", "created_at": "2026-01-08T13:33:24+00:00" }, { "id": 2672579209, "user": "user_501030d9d7e3", "body": "Then, the next question is whether this is a good way to fix this, and what are the alternatives.\n\nWhat I like about this is that it is very explicit. `check_array` would be almost as explicit, but a conversion to numpy happening by [NAME_REDACTED] (somewhere in the code) would be very implicit and dependent on the current implementation. Since we see that we get hard to debug errors, I would not be in favour if this solution.", "path": "sklearn/metrics/_ranking.py", "line": null, "side": "RIGHT", "created_at": "2026-01-08T14:28:17+00:00" }, { "id": 2674724404, "user": "user_d16337ec046b", "body": "> precision_recall_curve indeed does that, but average_precision_score does not.\n\nBut doesn't `average_precision_score` call `precision_recall_curve` ?\n\n> It fixes a test failure if array api is not enabled and all inputs (specifically y_true and y_score) are torch tensors on cpu.\n\nMy understanding of this is that the following code is meant to an error (when dispatch is disabled - explicitly set here):\n\n```python\n import torch\n from sklearn.metrics import average_precision_score\n\n y_scores = torch.tensor([0.1, 0.4, 0.35, 0.8], device='cpu')\n y_true = torch.tensor([0, 0, 1, 1], device='cpu')\n with config_context(array_api_dispatch=False):\n average_precision_score(y_true, y_scores)\n```\n\nThus to make testing easier, I checked the above on main (works fine) and on this branch with the above lines commented out (works as well).\n\nFrom what I can follow, the inputs are converted to numpy arrays?\n`average_precision_score` calls `precision_recall_curve` calls `confusion_matrix_at_thresholds` which calls `column_or_1d` on `y_true` and `y_score` ?", "path": "sklearn/metrics/_ranking.py", "line": null, "side": "RIGHT", "created_at": "2026-01-09T03:51:16+00:00" }, { "id": 2675229155, "user": "user_501030d9d7e3", "body": "> But doesn't average_precision_score call precision_recall_curve ?\n\nI think the changes made to `y_true` and `y_score` made in `precision_recall_curve` stay local.\n\n> Thus to make testing easier, I checked the above on main (works fine) and on this branch with the above lines commented out (works as well).\n\nInteresting. It fails on the mps CI (but fails on a different test case for a similar reason (at np.repeat) locally for me on linux).\n\n> From what I can follow, the inputs are converted to numpy arrays?\naverage_precision_score calls precision_recall_curve calls confusion_matrix_at_thresholds which calls column_or_1d on y_true and y_score ?\n\nLet me actually comment out this patch and push, so you can inspect on CI.", "path": "sklearn/metrics/_ranking.py", "line": null, "side": "RIGHT", "created_at": "2026-01-09T08:03:53+00:00" }, { "id": 2675254767, "user": "user_501030d9d7e3", "body": "Here it is: #33028 \n\nI have opened a new PR for this to have the CI run and also to explore alternative solutions there.", "path": "sklearn/metrics/_ranking.py", "line": null, "side": "RIGHT", "created_at": "2026-01-09T08:14:21+00:00" }, { "id": 2681378684, "user": "user_d5b9cb906259", "body": "Do we need this `if` statement? `array_api_strict` is super strict and sticks as close as possible to what the array API standard mandates. No compromises and no historical baggage.\n\nFor me this means we should not special case it, instead we should write our code so that it works with `array_api_strict` and only add workarounds for libraries that are not (strictly) compliant with the standard.\n\nIs that view too strict/not pragmatic enough?", "path": "sklearn/metrics/_base.py", "line": null, "side": "RIGHT", "created_at": "2026-01-12T09:04:32+00:00" }, { "id": 2686422726, "user": "user_501030d9d7e3", "body": "I wanted to prevent adding a permanent fix on a seemingly temporary problem.\n\nWe have a history of type compatibilities between `float64` and `int64` in `array_api_strict` (https://github.com/[USER_REDACTED]n/scikit-learn/pull/32422#issuecomment-3605073399, #32552, #33022 being the lastes ones, I think) getting fixed with newer scipy releases it seems.\n\n(This one actually fails with scipy==1.16.3 for me locally but I didn't go into depth.)", "path": "sklearn/metrics/_base.py", "line": null, "side": "RIGHT", "created_at": "2026-01-13T13:24:35+00:00" }, { "id": 2689463911, "user": "user_d16337ec046b", "body": "Just curious (and I couldn't find an answer in #32552) - why is it only array api strict that fails (and not other array inputs)?\nMy initial understanding was that it was a scipy 'bug' meaning that certain functions were not able to handle mixed dtypes (but if that was the case, why does it not affect other array libraries?), but is it actually (also?) related to some array method?", "path": "sklearn/metrics/_base.py", "line": null, "side": "RIGHT", "created_at": "2026-01-14T08:30:20+00:00" }, { "id": 2690377299, "user": "user_501030d9d7e3", "body": "I am not sure, to be honest, and I don't remember.", "path": "sklearn/metrics/_base.py", "line": null, "side": "RIGHT", "created_at": "2026-01-14T13:11:10+00:00" }, { "id": 2693890381, "user": "user_49a647962c6b", "body": "I agree, this smells bad, I wouldn't feel comfortable with this condition. Code should be compatible with array api strict. So we need to dig deep and figure out the issue here.\n\nI'd say if the issue is type incompatibility, we should simply check for types and convert them before the operation. Kinda where it's needed to avoid extra overhead.", "path": "sklearn/metrics/_base.py", "line": null, "side": "RIGHT", "created_at": "2026-01-15T10:46:45+00:00" }, { "id": 2693900723, "user": "user_49a647962c6b", "body": "seems like `c` needs to be on the right device already, which also avoids repeating the move twice here.\n\nIf it's an integer, why can't we just index, if it's a list, it should be on the right device, or have a version on the right device, since it seems `score[c]` is fine?", "path": "sklearn/metrics/_base.py", "line": 119, "side": "RIGHT", "created_at": "2026-01-15T10:49:29+00:00" }, { "id": 2693916432, "user": "user_49a647962c6b", "body": "Otherwise, it seems we need a sort of a `_safe_indexing` which can handle device difference between the index and the values. But I don't like having to move indices every time we index.", "path": "sklearn/metrics/_base.py", "line": 119, "side": "RIGHT", "created_at": "2026-01-15T10:54:31+00:00" }, { "id": 2701298993, "user": "user_501030d9d7e3", "body": "I agree we should comply with the spec, if this is not a bug in `array-api-strict`.\n\nI went down to investigate this: \n\nThe error comes from `array_api_strict.multiply` where `y_true` has dtype `array_api_strict.int64` and `xp.reshape(score_weight, (-1, 1))` has dtype `array_api_strict.float64`.\n\n`xp.reshape` must follow the \"Type Promotion Rules\", see: https://data-apis.org/array-api/latest/API_specification/generated/array_api.multiply.html#multiply\n\nThe [Type Promotion Rules](https://data-apis.org/array-api/latest/API_specification/type_promotion.html#type-promotion) in turn state that \"mixed-kind promotion is undefined\" (though I wonder what where the reasons to design it like this). data-apis/array-api-strict#136 shows that the type incompatibility is indeed very on purpose.\n\nThis means we need to do the type promotion in our code without special casing it to the `array_api_strict` namespace.\n\nI have changed the code accordingly.", "path": "sklearn/metrics/_base.py", "line": null, "side": "RIGHT", "created_at": "2026-01-17T17:32:07+00:00" }, { "id": 2701341753, "user": "user_501030d9d7e3", "body": "`c` is an int.\n\n> If it's an integer, why can't we just index,\n\nThis would work, [USER_REDACTED]:\n\n```diff\n- y_true_c = _ravel(\n- xp.take(y_true, xp.asarray([c], device=_device), axis=not_average_axis)\n- )\n- y_score_c = _ravel(\n- xp.take(y_score, xp.asarray([c], device=_device), axis=not_average_axis)\n- )\n+ y_true_rotated = xp.moveaxis(y_true, not_average_axis, -1)\n+ y_true_c = _ravel(y_true_rotated[..., c])\n+ y_score_rotated = xp.moveaxis(y_score, not_average_axis, -1)\n+ y_score_c = _ravel(y_score_rotated[..., c])\n```\n\nThough I didn't understand _why_ we want to change this. What is the advantage of doing it differently?", "path": "sklearn/metrics/_base.py", "line": 119, "side": "RIGHT", "created_at": "2026-01-17T18:32:54+00:00" }, { "id": 2701343355, "user": "user_501030d9d7e3", "body": "I have changed this code according to my suggestion in https://github.com/[USER_REDACTED]n/scikit-learn/pull/33028#issuecomment-3749462746.\n\nPlease let me know if that's not a good solution in your opinion. Happy to change it.", "path": "sklearn/metrics/_ranking.py", "line": null, "side": "RIGHT", "created_at": "2026-01-17T18:35:56+00:00" }, { "id": 2704650262, "user": "user_49a647962c6b", "body": "Double checking https://data-apis.org/array-api/latest/API_specification/generated/array_api.take.html\n\nNow I see `index` and `x` need to be both an `array`, which means we have to create an array anyway, which means at the point we do that, makes sense for them to be on the same device. Still, makes odd code.\n\n> xp.moveaxis(y_score, not_average_axis, -1)\n\nSince this operation can be quite expensive, we probably shouldn't do it anyway.\n\nWe can keep the code as is, still, odd.", "path": "sklearn/metrics/_base.py", "line": 119, "side": "RIGHT", "created_at": "2026-01-19T12:49:46+00:00" }, { "id": 2706473833, "user": "user_bf0b6c7acb9c", "body": "```suggestion\n return float(_average(score, weights=average_weight, xp=xp))\n```", "path": "sklearn/metrics/_base.py", "line": null, "side": "RIGHT", "created_at": "2026-01-20T01:44:59+00:00" }, { "id": 2707514174, "user": "user_d16337ec046b", "body": "Ah interesting. So does this mean that `multiply` for torch and cupy (the other libraries we test) don't fail because they do allow mixed type promotion?\n\nSo is this unrelated then to issue #32552 , and thus would not be fixed by [NAME_REDACTED]?", "path": "sklearn/metrics/_base.py", "line": null, "side": "RIGHT", "created_at": "2026-01-20T09:32:04+00:00" }, { "id": 2707524371, "user": "user_501030d9d7e3", "body": "> Ah interesting. So does this mean that multiply for torch and cupy (the other libraries we test) don't fail because they do allow mixed type promotion?\n\nYes, it seems so. Numpy does, too.\n\n> So is this unrelated then to issue https://github.com/[USER_REDACTED]n/scikit-learn/issues/32552 , and thus would not be fixed by [NAME_REDACTED]?\n\nI am not sure, but it seems unrelated. Maybe also I misread the cause of https://github.com/[USER_REDACTED]n/scikit-learn/issues/32552.", "path": "sklearn/metrics/_base.py", "line": null, "side": "RIGHT", "created_at": "2026-01-20T09:34:44+00:00" }, { "id": 2707805957, "user": "user_501030d9d7e3", "body": "Thanks for reviewing, [USER_REDACTED]!\n\nI have now added `xp`, as you suggested, though it gets overridden in the first line of `_average` anyway.\nI had always wondered why we extract `xp` anew for helper functions, because whatever gets passed as `xp` gets reassigned then, but here, I agree it is good to add `xp=xp` for consistency and making the intend clear.", "path": "sklearn/metrics/_base.py", "line": null, "side": "RIGHT", "created_at": "2026-01-20T10:48:18+00:00" }, { "id": 2715020888, "user": "user_d16337ec046b", "body": "I think `get_namespace_and_device` gets passed `xp`, and it only gets namespace if `xp=None`", "path": "sklearn/metrics/_base.py", "line": null, "side": "RIGHT", "created_at": "2026-01-22T01:56:09+00:00" }, { "id": 2715360107, "user": "user_d16337ec046b", "body": "```suggestion\n # we need y_pred_nd to be of shape (n_samples, n_classes)\n```\nnit", "path": "sklearn/metrics/tests/test_common.py", "line": null, "side": "RIGHT", "created_at": "2026-01-22T05:29:48+00:00" }, { "id": 2715375958, "user": "user_d16337ec046b", "body": "```suggestion\n # Mixed integer and float type promotion not defined in array standard\n```", "path": "sklearn/metrics/_base.py", "line": null, "side": "RIGHT", "created_at": "2026-01-22T05:38:38+00:00" }, { "id": 2715381055, "user": "user_d16337ec046b", "body": "why not\n```suggestion\n y_true = xp.asarray(y_true, dtype=score_weight.dtype)\n```", "path": "sklearn/metrics/_base.py", "line": null, "side": "RIGHT", "created_at": "2026-01-22T05:41:25+00:00" }, { "id": 2715416627, "user": "user_d16337ec046b", "body": "I probably missed something by [NAME_REDACTED] `roc_auc_score` ?", "path": "sklearn/metrics/_ranking.py", "line": 702, "side": "RIGHT", "created_at": "2026-01-22T05:58:13+00:00" }, { "id": 2717090074, "user": "user_501030d9d7e3", "body": "Yes, it ready much cleaner, thanks.", "path": "sklearn/metrics/_base.py", "line": null, "side": "RIGHT", "created_at": "2026-01-22T14:13:23+00:00" }, { "id": 2717104820, "user": "user_501030d9d7e3", "body": "`roc_auc_score` shares `_average_binary_score` as a common helper function with `average_binary_score`. With the changes in there, we now get an error there (`AttributeError: 'list' object has no attribute 'dtype'`) because `roc_auc_score` had previously not handled `sample_weight` correctly either.", "path": "sklearn/metrics/_ranking.py", "line": 702, "side": "RIGHT", "created_at": "2026-01-22T14:18:07+00:00" } ], "meta": { "languages": [ "py", "rst" ], "touches_tests": true, "review_state_summary": { "COMMENTED": 38, "APPROVED": 2 }, "meaningful_comment_count": 51, "has_approval": true, "has_changes_requested": false, "total_review_comments": 51 } } { "_id": "24d4277333249bda", "_schema_version": "1.0", "_cleaned_at": "2026-02-12T07:46:51.976223+00:00", "repo": "scikit-learn/scikit-learn", "repo_url": "https://github.com/scikit-learn/scikit-learn", "license_name": "BSD 3-Clause \"New\" or \"Revised\" License", "license_spdx": "BSD-3-Clause", "pr_number": 32893, "title": "DOC Add link to glossary \"label indicator matrix\" for classification metric docstrings", "body": "#### [NAME_REDACTED]/PRs\nNoticed while working on #32755\n\n#### What does this implement/fix? Explain your changes.\nAdds reference to the glossary term https://scikit-learn.org/dev/glossary.html#term-label-indicator-matrix for classification metrics \n\nNot sure about the best term to use.\n\n* Avoided use of 'binary' i.e., binary indicator - binary here is talking about the indicator being 0 or 1, not about the data being binary. This *may* be confusing and this term is not included as an alias in the glossary so I have avoided it\n* when talking about binary data, I have used the term \"label indicator format“ / ”label indicator matrix“ (depending on how best the wording fits into the sentence), to avoid use of 'multilabel' (as the data is not multilabel).\n* used 'multilabel indicator matrix' when talking about multilabel data\n\n#### AI usage disclosure\n\nI used AI assistance for:\n- [ ] Code generation (e.g., when writing an implementation or fixing a bug)\n- [ ] Test/benchmark generation\n- [ ] Documentation (including examples)\n- [ ] Research and understanding\n\n#### Any other comments?\n\n", "author": "user_d16337ec046b", "created_at": "2025-12-12T05:04:00+00:00", "merged_at": "2025-12-22T03:57:11+00:00", "base_branch": "main", "head_branch": "doc_label_indicator", "additions": 12, "deletions": 8, "changed_files": 2, "files": [ { "filename": "doc/glossary.rst", "status": "modified", "additions": 6, "deletions": 2, "changes": 8, "patch": "@@ -518,14 +518,18 @@ [NAME_REDACTED]\n :term:`memory mapping`. See :ref:`parallelism` for more\n information.\n \n+ label indicator format\n label indicator matrix\n multilabel indicator matrix\n multilabel indicator matrices\n- The format used to represent multilabel data, where each row of a 2d\n- array or sparse matrix corresponds to a sample, each column\n+ This format can be used to represent binary or multilabel data. Each row of\n+ a 2d array or sparse matrix corresponds to a sample, each column\n corresponds to a class, and each element is 1 if the sample is labeled\n with the class and 0 if not.\n \n+ :ref:`LabelBinarizer ` can be used to create a\n+ multilabel indicator matrix from :term:`multiclass` labels.\n+\n leakage\n data leakage\n A problem in cross validation where generalization performance can be" }, { "filename": "sklearn/metrics/_ranking.py", "status": "modified", "additions": 6, "deletions": 6, "changes": 12, "patch": "@@ -142,7 +142,7 @@ def average_precision_score(\n Parameters\n ----------\n y_true : array-like of shape (n_samples,) or (n_samples, n_classes)\n- True binary labels or binary label indicators.\n+ True binary labels or :term:`multilabel indicator matrix`.\n \n y_score : array-like of shape (n_samples,) or (n_samples, n_classes)\n Target scores, can either be probability estimates of the positive\n@@ -502,9 +502,9 @@ def roc_auc_score(\n Parameters\n ----------\n y_true : array-like of shape (n_samples,) or (n_samples, n_classes)\n- True labels or binary label indicators. The binary and multiclass cases\n+ True labels or :term:`label indicator matrix`. The binary and multiclass cases\n expect labels with shape (n_samples,) while the multilabel case expects\n- binary label indicators with shape (n_samples, n_classes).\n+ a :term:`multilabel indicator matrix` with shape (n_samples, n_classes).\n \n y_score : array-like of shape (n_samples,) or (n_samples, n_classes)\n Target scores.\n@@ -1337,7 +1337,7 @@ def label_ranking_average_precision_score(y_true, y_score, *, sample_weight=None\n Parameters\n ----------\n y_true : {array-like, sparse matrix} of shape (n_samples, n_labels)\n- True binary labels in binary indicator format.\n+ True binary labels in :term:`label indicator format`.\n \n y_score : array-like of shape (n_samples, n_labels)\n Target scores, can either be probability estimates of the positive\n@@ -1439,7 +1439,7 @@ def coverage_error(y_true, y_score, *, sample_weight=None):\n Parameters\n ----------\n y_true : array-like of shape (n_samples, n_labels)\n- True binary labels in binary indicator format.\n+ True binary labels in :term:`label indicator format`.\n \n y_score : array-like of shape (n_samples, n_labels)\n Target scores, can either be probability estimates of the positive\n@@ -1516,7 +1516,7 @@ def label_ranking_loss(y_true, y_score, *, sample_weight=None):\n Parameters\n ----------\n y_true : {array-like, sparse matrix} of shape (n_samples, n_labels)\n- True binary labels in binary indicator format.\n+ True binary labels in :term:`label indicator format`.\n \n y_score : array-like of shape (n_samples, n_labels)\n Target scores, can either be probability estimates of the positive" } ], "reviews": [ { "id": 3570305434, "user": "user_d16337ec046b", "state": "COMMENTED", "body": null, "submitted_at": "2025-12-12T05:05:16+00:00" }, { "id": 3570315872, "user": "user_d16337ec046b", "state": "COMMENTED", "body": null, "submitted_at": "2025-12-12T05:10:02+00:00" }, { "id": 3593406367, "user": "user_501030d9d7e3", "state": "APPROVED", "body": "Thanks for the PR, [USER_REDACTED]. I find these kind of doc improvements very useful.\nI only have a nit comment and a suggestion to your question.", "submitted_at": "2025-12-18T15:11:50+00:00" }, { "id": 3595858289, "user": "user_d16337ec046b", "state": "COMMENTED", "body": null, "submitted_at": "2025-12-19T00:28:13+00:00" }, { "id": 3602552171, "user": "user_04b4a5f4e2a8", "state": "APPROVED", "body": "Thank you for the PR! LGTM", "submitted_at": "2025-12-22T03:57:04+00:00" } ], "review_comments": [ { "id": 2612937852, "user": "user_d16337ec046b", "body": "I've used both glossary aliases 'label indicator matrix' (when talking about binary data) and 'multilabel indicator matrix' (when talking about multilabel data). I think this is okay. I amended the glossary entry to clarify that it could be used for both binary and multilabel data...", "path": "sklearn/metrics/_ranking.py", "line": null, "side": "RIGHT", "created_at": "2025-12-12T05:05:16+00:00" }, { "id": 2612945365, "user": "user_d16337ec046b", "body": "Also wonder if we should add a short example, like we do here: https://scikit-learn.org/dev/modules/preprocessing_targets.html#multilabelbinarizer", "path": "doc/glossary.rst", "line": 528, "side": "RIGHT", "created_at": "2025-12-12T05:10:03+00:00" }, { "id": 2631403581, "user": "user_501030d9d7e3", "body": "What do you think about adding:\n\n```suggestion\n with the class and 0 if not. :class:`LabelBinarizer` creates a \n :term:`multilabel indicator matrix` from :term:`multiclass` labels.\n```\n\nWe have a similar sentence in [preprocessing_targets.rst](https://scikit-learn.org/stable/modules/preprocessing_targets.html#labelbinarizer) followed be an example, but the link to `LabelBinarizer` is probably enough.", "path": "doc/glossary.rst", "line": 528, "side": "RIGHT", "created_at": "2025-12-18T14:51:50+00:00" }, { "id": 2631411684, "user": "user_501030d9d7e3", "body": "```suggestion\n a :term:`multilabel indicator matrix` with shape (n_samples, n_classes).\n```\n\nNit.", "path": "sklearn/metrics/_ranking.py", "line": null, "side": "RIGHT", "created_at": "2025-12-18T14:53:32+00:00" }, { "id": 2633131563, "user": "user_d16337ec046b", "body": "I changed to reference the user guide `LabelBinarizer` section, and not the `LabelBinarizer` API, as it seemed to fit more.", "path": "doc/glossary.rst", "line": 528, "side": "RIGHT", "created_at": "2025-12-19T00:28:12+00:00" } ], "meta": { "languages": [ "py", "rst" ], "touches_tests": false, "review_state_summary": { "COMMENTED": 3, "APPROVED": 2 }, "meaningful_comment_count": 5, "has_approval": true, "has_changes_requested": false, "total_review_comments": 5 } } { "_id": "d10108ebeb16dcd4", "_schema_version": "1.0", "_cleaned_at": "2026-02-12T07:46:51.976223+00:00", "repo": "scikit-learn/scikit-learn", "repo_url": "https://github.com/scikit-learn/scikit-learn", "license_name": "BSD 3-Clause \"New\" or \"Revised\" License", "license_spdx": "BSD-3-Clause", "pr_number": 32889, "title": "MNT/DOC Autoclose schedule doesn't run on forks and improved structuring", "body": "#### [NAME_REDACTED]/PRs\n- fixes https://github.com/[USER_REDACTED]n/scikit-learn/pull/32743#issuecomment-3641069962\n- fixes https://github.com/[USER_REDACTED]n/scikit-learn/pull/32660#issuecomment-3546620178\n- implements ideas from discussion with [USER_REDACTED] \n\n#### What does this implement/fix? Explain your changes.\nThis PR fixes the `autoclose-schedule` workflow to not run on forks, links to a central list of how to improve a PR, and implements some changes in the wording. Specifically, it makes it more clear to new contributors where the autoclose label was set, that they are responsible to fix the issues and advises them to not request the label getting removed.\n\n#### AI usage disclosure\n\nI used AI assistance for:\n- [ ] Code generation (e.g., when writing an implementation or fixing a bug)\n- [ ] Test/benchmark generation\n- [ ] Documentation (including examples)\n- [x] Research and understanding", "author": "user_501030d9d7e3", "created_at": "2025-12-11T14:55:17+00:00", "merged_at": "2025-12-22T15:04:08+00:00", "base_branch": "main", "head_branch": "fix_automated_comments", "additions": 32, "deletions": 36, "changed_files": 5, "files": [ { "filename": ".github/workflows/autoclose-comment.yml", "status": "modified", "additions": 20, "deletions": 27, "changes": 47, "patch": "@@ -39,36 +39,29 @@ jobs:\n \n Thank you for your contribution to scikit-learn and for the effort you have\n put into this PR. This pull request does not yet meet the quality and\n- clarity needed for an effective review. Reviewing time is limited, and our\n- goal is to prioritize well-prepared contributions to keep scikit-learn\n- maintainable. Unless this PR is improved, it will be automatically closed\n- after two weeks.\n+ clarity needed for an effective review. Project maintainers have limited\n+ time for code reviews, and our goal is to prioritize well-prepared\n+ contributions to keep scikit-learn maintainable.\n \n \n- To avoid autoclose and increase the chance of a productive review, please:\n+ To increase the chance of a productive review, please refer to: [How do I\n+ improve my issue or pull\n+ request?](https://scikit-learn.org/dev/faq.html#how-do-i-improve-my-issue-or-pull-request)\n+ As the author, you are responsible for driving this PR, which entails doing\n+ necessary background research as well as presenting its context and your\n+ thought process. If you are a [new\n+ contributor](https://scikit-learn.org/dev/developers/contributing.html#new-contributors),\n+ or do not know how to fulfill these requirements, we recommend that you\n+ familiarise yourself with scikit-learn's development conventions via other\n+ contribution types (e.g., reviewing PRs) before submitting code.\n \n- - Ensure your contribution aligns with our\n- [contribution guide](https://scikit-learn.org/dev/developers/contributing.html).\n \n- - Include a clear motivation and concise explanation in the pull request\n- description of why you chose this solution.\n+ Scikit-learn maintainers cannot provide one-to-one guidance on this PR.\n+ However, if you ask focused, well-researched questions, a community\n+ member may be willing to help. 💬\n \n- - Make sure the code runs and passes tests locally (`pytest`) and in the CI.\n \n- - Submit only code you can explain and maintain; reviewers will ask for\n- clarifications and changes. Disclose any AI assistance per our\n- [[NAME_REDACTED]](https://scikit-learn.org/dev/developers/contributing.html#automated-contributions-policy).\n-\n- - Keep the changes minimal and directly relevant to the described issue or\n- enhancement.\n-\n-\n- We cannot provide one-to-one guidance on every PR, though we\n- encourage you to ask focused, actionable questions that show you have tried\n- to explore the problem and are interested to engage with the project. 💬\n- Sometimes a maintainer or someone else from the community might be able to\n- offer pointers.\n-\n-\n- If you improve your PR within the two-week window, the `autoclose` label can\n- be removed by maintainers.\n+ If you substantially improve this PR within two weeks, a team member may\n+ remove the `autoclose` label and the PR stays open. Cosmetic changes or\n+ incomplete fixes will not be sufficient. Maintainers will assess\n+ improvements on their own schedule. Please do not ping (`@`) maintainers." }, { "filename": ".github/workflows/autoclose-schedule.yml", "status": "modified", "additions": 1, "deletions": 0, "changes": 1, "patch": "@@ -18,6 +18,7 @@ jobs:\n autoclose:\n name: autoclose labeled PRs\n runs-on: ubuntu-latest\n+ if: github.repository == 'scikit-learn/scikit-learn'\n steps:\n - uses: actions/checkout@v5\n - uses: actions/setup-python@v6" }, { "filename": ".github/workflows/needs-decision.yml", "status": "modified", "additions": 3, "deletions": 1, "changes": 4, "patch": "@@ -33,14 +33,16 @@ jobs:\n /repos/$GH_REPO/issues/$ISSUE_NUMBER/comments \\\n -f \"body=$BODY\"\n env:\n- BODY: |\n+ BODY: >\n Thanks for the work you've done so far. The goal of this comment\n is to set expectations.\n \n+\n Deciding on new features or substantial changes is a lengthy\n process. It frequently happens that no maintainer is available\n to take on this task right now.\n \n+\n Please do not create a Pull Request before a decision has been\n made regarding the proposed work. Making this decision can\n often take a significant amount of time and effort." }, { "filename": "doc/developers/contributing.rst", "status": "modified", "additions": 1, "deletions": 2, "changes": 3, "patch": "@@ -37,8 +37,7 @@ See :ref:`ways_to_contribute` to learn how to make meaningful contributions.\n \n .. topic:: **Our community, our values**\n \n- We are a community based on openness and friendly, didactic,\n- discussions.\n+ We are a community based on openness and friendly, didactic discussions.\n \n We aspire to treat everybody equally, and value their contributions. We\n are particularly seeking people from underrepresented backgrounds in Open" }, { "filename": "doc/faq.rst", "status": "modified", "additions": 7, "deletions": 6, "changes": 13, "patch": "@@ -313,17 +313,18 @@ being reviewed, you can try:\n \n * follow our :ref:`contribution guidelines `, in particular\n :ref:`automated_contributions_policy`, :ref:`filing_bugs`,\n- :ref:`stalled_pull_request` and :ref:`stalled_unclaimed_issues`.\n-* complete the provided issue and pull request templates, including a clear and\n- concise description of the issue or motivation for the pull request.\n+ :ref:`stalled_pull_request` and :ref:`stalled_unclaimed_issues`,\n+* complete all sections of the issue or pull request template provided by GitHub,\n+ including a clear description of the issue or motivation and thought process behind\n+ the pull request\n * ensure the title clearly describes the issue or pull request and does not include\n an issue number.\n \n For your pull requests specifically, the following will make it easier to review:\n \n-* ensure your PR satisfies all items in the\n- :ref:`Pull request checklist `.\n-* ensure your PR addresses an issue for which there is clear consensus on the solution.\n+* ensure your PR addresses an issue for which there is clear consensus on the solution\n+ (see :ref:`issues_tagged_needs_triage`),\n+* ensure the PR satisfies all items in the :ref:`Pull request checklist `,\n * ensure the changes are minimal and directly relevant to the described issue.\n \n What does the \"spam\" label for issues or pull requests mean?" } ], "reviews": [ { "id": 3570134672, "user": "user_d16337ec046b", "state": "COMMENTED", "body": "Overall I think we can be more succinct and structured in the autoclose comment. I am not sure repeating ourselves is going to stop the more egregious offenders and the longer we make this, the less likely people are going to read it.\n\nWhat about an overall structure of:\n\n* Paragraph 1: PR does not standards (I think it's fine currently)\n* Paragraph 2: Link to ways to improve PR. Advise they are responsible for driving this PR. If they do not know how to improve their PR, suggest building foundation with other contribution types (link to new contributor section) or asking questions after doing research, which someone from community may respond to.\n* Paragraph 3: If they improve the PR, the label may be removed. Advise against them requesting label be removed or ping-ing maintainers (I *think* you did not want to tell people not to ping maintainers, but I think its worth having, they can still comment and ask questions, but don't ping maintainers)\n\nI've made more specific suggestions below.", "submitted_at": "2025-12-12T03:44:51+00:00" }, { "id": 3577494304, "user": "user_501030d9d7e3", "state": "COMMENTED", "body": "Thanks for your feedback, [USER_REDACTED], which is valuable and I have implemented most of the requested changes, except in the paragraph that keeps the door open for people who want to learn where I hope we can resolve this together.\n\nThough I can understand your concern about repeating ourselves, this PR doesn't make the comment longer and cutting it down to only three paragraphs you suggested feel a bit strict to me. My goal also is to help us feel less guilty when using this label and for me it helps to be a bit more generous with information, since I have unexperienced but genuine people in mind that read this (knowing that authors of the careless fly-by [NAME_REDACTED], but who cares). I have tried not to speak of \"us\" but instead of \"scikit-learn\", because the former sounds gatekeepy, and I don't want to spell out something like \"build your foundations first\" (which I find degrading) but instead to talk about familiarising yourself with the repo.\n\nI have added \"please do not ping maintainers\", after experiencing some pings on incomplete PRs myself, I think its necessary.", "submitted_at": "2025-12-15T12:05:19+00:00" }, { "id": 3585770657, "user": "user_d16337ec046b", "state": "COMMENTED", "body": null, "submitted_at": "2025-12-17T02:36:03+00:00" }, { "id": 3585771999, "user": "user_d16337ec046b", "state": "COMMENTED", "body": "I think it reads much better, but personally still prefer conciseness (but this is more of a personal preference).\n\nSome thoughts but would be good to get someone else's perspective as well.", "submitted_at": "2025-12-17T04:04:33+00:00" }, { "id": 3601154660, "user": "user_501030d9d7e3", "state": "COMMENTED", "body": null, "submitted_at": "2025-12-20T15:30:09+00:00" }, { "id": 3601158918, "user": "user_501030d9d7e3", "state": "COMMENTED", "body": null, "submitted_at": "2025-12-20T15:42:52+00:00" }, { "id": 3601162010, "user": "user_501030d9d7e3", "state": "COMMENTED", "body": null, "submitted_at": "2025-12-20T15:51:53+00:00" }, { "id": 3601454060, "user": "user_d16337ec046b", "state": "COMMENTED", "body": null, "submitted_at": "2025-12-21T03:57:12+00:00" }, { "id": 3601454326, "user": "user_d16337ec046b", "state": "COMMENTED", "body": null, "submitted_at": "2025-12-21T03:58:29+00:00" }, { "id": 3601454699, "user": "user_d16337ec046b", "state": "APPROVED", "body": "Thank you! LGTM", "submitted_at": "2025-12-21T04:00:52+00:00" }, { "id": 3604415950, "user": "user_fca2535bcd49", "state": "APPROVED", "body": "Thanks for this PR! Let's merge this one and iterate on it if we need", "submitted_at": "2025-12-22T15:03:58+00:00" } ], "review_comments": [ { "id": 2612778714, "user": "user_d16337ec046b", "body": "I think this is already mentioned in the PR checklist", "path": "doc/faq.rst", "line": null, "side": "RIGHT", "created_at": "2025-12-12T03:15:06+00:00" }, { "id": 2612783120, "user": "user_d16337ec046b", "body": "I though the original was mostly adequate? I am reluctant to make it wordier, but may we could add that they should explain their through process for PRs...\n```suggestion\n* complete all sections of the issue or pull request template,\n including a clear and concise description of the issue or motivation and \n thought process behind the pull request \n```", "path": "doc/faq.rst", "line": null, "side": "RIGHT", "created_at": "2025-12-12T03:18:40+00:00" }, { "id": 2612785069, "user": "user_d16337ec046b", "body": "I think this may be included in the AI contributions section and honestly I am not sure writing this several times is not going to stop offending users. These people are unlikely to read or abide by [NAME_REDACTED] many times we write it...", "path": "doc/faq.rst", "line": null, "side": "RIGHT", "created_at": "2025-12-12T03:20:00+00:00" }, { "id": 2612789418, "user": "user_d16337ec046b", "body": "I feel like this is a bit vague and I think the PR checklist already does a reasonable job of discussing some of these conventions: https://scikit-learn.org/dev/developers/contributing.html#pull-request-checklist", "path": "doc/faq.rst", "line": null, "side": "RIGHT", "created_at": "2025-12-12T03:22:44+00:00" }, { "id": 2612815542, "user": "user_d16337ec046b", "body": "Not sure about how this phrase comes off: \"if all that sounds demanding, that's because it is,\"", "path": ".github/workflows/autoclose-comment.yml", "line": null, "side": "RIGHT", "created_at": "2025-12-12T03:42:39+00:00" }, { "id": 2612818231, "user": "user_d16337ec046b", "body": "This seems vague - helpful to whom? And I am worried someone will use this against us, because we don't have time to engage in discussions.", "path": ".github/workflows/autoclose-comment.yml", "line": null, "side": "RIGHT", "created_at": "2025-12-12T03:44:48+00:00" }, { "id": 2618861369, "user": "user_501030d9d7e3", "body": "Good to get your feedback on this. I was thinking about this a lot. My intention was to show a bit of appreciation for the work they would have to put in, but I can see it is the wrong place to do that.\n\nI think that too often we express \"why can't you simply do that easy thing\" without appreciating that it is not a little thing to ask people to do.\n\nI agree it is not fitting this context, so I have deleted this.", "path": ".github/workflows/autoclose-comment.yml", "line": null, "side": "RIGHT", "created_at": "2025-12-15T10:34:46+00:00" }, { "id": 2618907335, "user": "user_501030d9d7e3", "body": "I am referring to this section in our values: \"We are a community based on openness and friendly, didactic discussions.\"\n\nThis sentence tries to keep the door open to junior people, who are interested to learn. I am actually pretty fond of expressing something like this. I feel the autoclose message is too harsh otherwise.\n\nAlso, I would like to address a broad range of contributions with this label. Right now I feel only really careless PRs would deserve it, and I would not put it on a PR that lacks quality, but the contributors seems to have spend a lot of time getting it right.\n\n> And I am worried someone will use this against us, because we don't have time to engage in discussions.\n\nI understand your concerns and I am very sure that some people will misuse this. That's why I tried to express some conditions following this sentence:\n- investigate your problem yourself first\n- be respectful (not pushing generated comments)\n- answer is a gift from the community and not guaranteed\n- answer may come from the community, not necessarily maintainers\n\nWhat do you think about encouraging community discussions without promising guidance and if you think it is worthwhile: How could we express that so it doesn't get misused?", "path": ".github/workflows/autoclose-comment.yml", "line": null, "side": "RIGHT", "created_at": "2025-12-15T10:48:54+00:00" }, { "id": 2618922949, "user": "user_501030d9d7e3", "body": "Yes, that exactly was my motivation, since we had talked about it before. Also, I was not sure if new contributors would know what \"issue and pull request templates\" where and that's why I added \"provided by GitHub\". I have now updated this bullen point with your suggestion and added \"provided by GitHub\", just in case.", "path": "doc/faq.rst", "line": null, "side": "RIGHT", "created_at": "2025-12-15T10:53:19+00:00" }, { "id": 2618932780, "user": "user_501030d9d7e3", "body": "Sadly true. I think the AI contributions section already does a great job explaining this, so I deleted this here.", "path": "doc/faq.rst", "line": null, "side": "RIGHT", "created_at": "2025-12-15T10:55:59+00:00" }, { "id": 2618951491, "user": "user_501030d9d7e3", "body": "True, I have removed it from here.", "path": "doc/faq.rst", "line": null, "side": "RIGHT", "created_at": "2025-12-15T11:02:09+00:00" }, { "id": 2618975816, "user": "user_501030d9d7e3", "body": "I can now see it is vague, since what I had meant is not covered in the Pull Request Checklist. My intention was to give new contributors a bit of a hand on how to work if they want to make their PR fit in. Like, check other PRs similar to this one, then you can find out things like: the correct location to put a new test, that you need param validation if you add a new param, that we have utility functions that you can use, that we never add new dependencies just for a fix, that there will be a lot of discussion and you will have to keep working on this for a while, and so on. It is the same as telling people to familiarise themselves with the repo first before attempting to add a new feature.\n\nMaybe this is a no-brainer anyways. Since my attempt to express this was too vague, I have removed this here.", "path": "doc/faq.rst", "line": null, "side": "RIGHT", "created_at": "2025-12-15T11:10:07+00:00" }, { "id": 2625384899, "user": "user_d16337ec046b", "body": "Maybe?\n```suggestion\n improvements on their own schedule. Please do not ping (`@`) maintainers.\n```", "path": ".github/workflows/autoclose-comment.yml", "line": null, "side": "RIGHT", "created_at": "2025-12-17T02:36:03+00:00" }, { "id": 2625386176, "user": "user_d16337ec046b", "body": "```suggestion\n familiarise yourself with scikit-learn's development conventions via other\n```", "path": ".github/workflows/autoclose-comment.yml", "line": null, "side": "RIGHT", "created_at": "2025-12-17T02:36:46+00:00" }, { "id": 2625493132, "user": "user_d16337ec046b", "body": "> Also, I would like to address a broad range of contributions with this label.\n\nAh, I was mostly thinking of the most egregious contributions, as that is what I have been using the label for. I'd like to think that for a contribution that looks like someone personally put effort in, I'd give pointers instead - but maybe we don't have time for this. Is the idea that it is better that these contributors get some response instead of nothing? I think I'd have to see some of these contributions in action to make a judgement here.\n\n> a community member (most likely not a maintainer) might be\n willing to offer advice.\n\nJust curious, does this happen often? Don't feel strongly about this section one way or another, but I am just worried they won't get much response.", "path": ".github/workflows/autoclose-comment.yml", "line": null, "side": "RIGHT", "created_at": "2025-12-17T03:46:45+00:00" }, { "id": 2625499819, "user": "user_d16337ec046b", "body": "Ah that makes sense. I can see what you mean, this stuff comes with experience.\n\nI do wonder if these are the main problems with the PRs deserving of this label. e.g., if it's an otherwise well thought out PR, asking them to add param validation would not be a big deal for me. Similarly, I would have thought that PRs that address an issue where a clear path forward has been decided would not result in adding an unwarranted new dependency.", "path": "doc/faq.rst", "line": null, "side": "RIGHT", "created_at": "2025-12-17T03:51:38+00:00" }, { "id": 2625516000, "user": "user_d16337ec046b", "body": "Thinking about this more, I am not sure about this section - with respect to your sentiment of not wanting to sound too harsh, and the idea that small issues in an otherwise well prepared PR is probably not the main problem.\n\nI like the idea of saying that they are responsible for driving this PR, but the long list may seem intimidating to genuine contributors. You'd also think genuine contributors would already answer questions and address maintainer suggestions. Fixing test failures are already mentioned in the PR checklist. \n\nFor the use cases I have seen, I feel like the problem is more the lack of background research, lack of context provided and no description of their though process/why they decided on this solution/what alternatives were thought about. Of course, some PRs also give the bare minimum (no tests, no doc changes, CI may or may not be failing) and call it 'fixing' an issue.", "path": ".github/workflows/autoclose-comment.yml", "line": null, "side": "RIGHT", "created_at": "2025-12-17T04:03:41+00:00" }, { "id": 2637175883, "user": "user_501030d9d7e3", "body": "I find it sometimes hard to judge how much effort was put into something and I feel more at ease when we express something like \"Sorry we (maintainers) cannot guide you, but there is a whole community and maybe someone else will.\" \n\n> Just curious, does this happen often? \n\nCurrently, rarely. But I'd really like to see it happen. Writing this hope down might help this happening.\n\nAt the same time since #32734 we guide new contributors towards starting by [NAME_REDACTED] code, so this combination makes sense to me.", "path": ".github/workflows/autoclose-comment.yml", "line": null, "side": "RIGHT", "created_at": "2025-12-20T15:30:09+00:00" }, { "id": 2637181933, "user": "user_501030d9d7e3", "body": "I understand what you mean. I have changed this part of the message into the following:\n\n```\nAs the author, you are responsible for driving this PR, which entails\ndoing necessary background research as well as presenting its context and\nyour thought process.\n```", "path": ".github/workflows/autoclose-comment.yml", "line": null, "side": "RIGHT", "created_at": "2025-12-20T15:42:52+00:00" }, { "id": 2637186376, "user": "user_501030d9d7e3", "body": "Thinking about the phrase I wrote above (\"Sorry we (maintainers) cannot guide you, but there is a whole community and maybe someone else will.\") I think a friendly variation of this might be enough. The important thing here is to refer the discussion to the community, and we don't need to educate people on how to not be offensive / demanding / pretentious when communicating online.\n\nSo I've significantly shortened this paragraph to:\n\n```\nScikit-learn maintainers cannot provide one-to-one guidance on this PR.\nHowever, if you ask focused, well-researched questions, a community\nmember may be willing to help. 💬\n```", "path": ".github/workflows/autoclose-comment.yml", "line": null, "side": "RIGHT", "created_at": "2025-12-20T15:51:53+00:00" }, { "id": 2637527784, "user": "user_d16337ec046b", "body": "This sounds good!\n\n> At the same time since https://github.com/[USER_REDACTED]n/scikit-learn/pull/32734 we guide new contributors towards starting by [NAME_REDACTED] code, so this combination makes sense to me.\n\nI agree and this is a nice approach/direction!", "path": ".github/workflows/autoclose-comment.yml", "line": null, "side": "RIGHT", "created_at": "2025-12-21T03:57:12+00:00" }, { "id": 2637528205, "user": "user_d16337ec046b", "body": "This is nice!", "path": ".github/workflows/autoclose-comment.yml", "line": null, "side": "RIGHT", "created_at": "2025-12-21T03:58:29+00:00" }, { "id": 2637528828, "user": "user_d16337ec046b", "body": "```suggestion\n or do not know how to fulfill these requirements, we recommend that\n you familiarise yourself with scikit-learn's development conventions via other\n```\noptional change, just thought this reads a bit nicer", "path": ".github/workflows/autoclose-comment.yml", "line": null, "side": "RIGHT", "created_at": "2025-12-21T04:00:29+00:00" } ], "meta": { "languages": [ "rst", "yml" ], "touches_tests": false, "review_state_summary": { "COMMENTED": 9, "APPROVED": 2 }, "meaningful_comment_count": 23, "has_approval": true, "has_changes_requested": false, "total_review_comments": 23 } } { "_id": "54fc1fcc7704cbfe", "_schema_version": "1.0", "_cleaned_at": "2026-02-12T07:46:51.976223+00:00", "repo": "scikit-learn/scikit-learn", "repo_url": "https://github.com/scikit-learn/scikit-learn", "license_name": "BSD 3-Clause \"New\" or \"Revised\" License", "license_spdx": "BSD-3-Clause", "pr_number": 32888, "title": "ENH add clearer error message when instance is passed instead of class", "body": "\n\n#### [NAME_REDACTED]/PRs\n\nFixes https://github.com/[USER_REDACTED]n/scikit-learn/issues/32719\n\n#### What does this implement/fix? Explain your changes.\nIt adds a simple check to `Pipeline`, `FeatureUnion` and `ColumnTransformer` to raise a clearer error message if the user accidentally passed a class instead of an instance, and provides corresponding non-regression test.\n\n#### AI usage disclosure\n\nI used AI assistance for:\n- [ ] Code generation (e.g., when writing an implementation or fixing a bug)\n- [ ] Test/benchmark generation\n- [ ] Documentation (including examples)\n- [ ] Research and understanding\n\n#### Any other comments?\nAs noted in my comment [here](https://github.com/[USER_REDACTED]n/scikit-learn/issues/32719#issuecomment-3638023309), it could also be added to the existing `_validate_estimator()` function in `_BaseHeterogeneousEnsemble` and its version in `StackingClassifier` in a follow-up PR. If I followed the class hierarchy correctly, then this would also catch this mistake in `StackingClassifier`, `StackingRegressor`, `VotingClassifier` and `VotingRegressor`. I didn't check the other meta-estimators yet.\n\n", "author": "user_34a090906ca4", "created_at": "2025-12-11T13:55:39+00:00", "merged_at": "2025-12-15T14:11:13+00:00", "base_branch": "main", "head_branch": "validate_estimators", "additions": 53, "deletions": 0, "changed_files": 6, "files": [ { "filename": "doc/whats_new/upcoming_changes/many-modules/32888.enhancement.rst", "status": "added", "additions": 4, "deletions": 0, "changes": 4, "patch": "@@ -0,0 +1,4 @@\n+- :class:`pipeline.Pipeline`, :class:`pipeline.FeatureUnion` and\n+ :class:`compose.ColumnTransformer` now raise a clearer\n+ error message when an estimator class is passed instead of an instance.\n+ By :user:`[NAME_REDACTED] `" }, { "filename": "sklearn/compose/_column_transformer.py", "status": "modified", "additions": 1, "deletions": 0, "changes": 1, "patch": "@@ -513,6 +513,7 @@ def _validate_transformers(self):\n self._validate_names(names)\n \n # validate estimators\n+ self._check_estimators_are_instances(transformers)\n for t in transformers:\n if t in (\"drop\", \"passthrough\"):\n continue" }, { "filename": "sklearn/compose/tests/test_column_transformer.py", "status": "modified", "additions": 17, "deletions": 0, "changes": 17, "patch": "@@ -93,6 +93,23 @@ def transform(self, X, y=None):\n raise ValueError(\"specific message\")\n \n \n+[USER_REDACTED].mark.parametrize(\n+ \"transformers\",\n+ [\n+ [(\"trans1\", Trans, [0]), (\"trans2\", Trans(), [1])],\n+ [(\"trans1\", Trans(), [0]), (\"trans2\", Trans, [1])],\n+ [(\"drop\", \"drop\", [0]), (\"trans2\", Trans, [1])],\n+ [(\"trans1\", Trans, [0]), (\"passthrough\", \"passthrough\", [1])],\n+ ],\n+)\n+def test_column_transformer_raises_class_not_instance_error(transformers):\n+ # non-regression tests for https://github.com/[USER_REDACTED]n/scikit-learn/issues/32719\n+ ct = ColumnTransformer(transformers)\n+ msg = \"Expected an estimator instance (.*()), got estimator class instead (.*).\"\n+ with pytest.raises(TypeError, match=msg):\n+ ct.fit([[1]])\n+\n+\n def test_column_transformer():\n X_array = np.array([[0, 1, 2], [2, 4, 6]]).T" }, { "filename": "sklearn/pipeline.py", "status": "modified", "additions": 2, "deletions": 0, "changes": 2, "patch": "@@ -296,6 +296,7 @@ def _validate_steps(self):\n self._validate_names(names)\n \n # validate estimators\n+ self._check_estimators_are_instances(estimators)\n transformers = estimators[:-1]\n estimator = estimators[-1]\n \n@@ -1698,6 +1699,7 @@ def _validate_transformers(self):\n self._validate_names(names)\n \n # validate estimators\n+ self._check_estimators_are_instances(transformers)\n for t in transformers:\n if t in (\"drop\", \"passthrough\"):\n continue" }, { "filename": "sklearn/tests/test_pipeline.py", "status": "modified", "additions": 21, "deletions": 0, "changes": 21, "patch": "@@ -282,6 +282,27 @@ def test_pipeline_invalid_parameters():\n assert params == params2\n \n \n+[USER_REDACTED].mark.parametrize(\n+ \"meta_estimators\",\n+ [\n+ Pipeline([(\"pca\", PCA)]),\n+ Pipeline([(\"pca\", PCA), (\"ident\", None)]),\n+ Pipeline([(\"passthrough\", \"passthrough\"), (\"pca\", PCA)]),\n+ Pipeline([(\"passthrough\", None), (\"pca\", PCA)]),\n+ Pipeline([(\"scale\", StandardScaler), (\"pca\", PCA())]),\n+ FeatureUnion([(\"pca\", PCA), (\"svd\", TruncatedSVD())]),\n+ FeatureUnion([(\"pca\", PCA()), (\"svd\", TruncatedSVD)]),\n+ FeatureUnion([(\"drop\", \"drop\"), (\"svd\", TruncatedSVD)]),\n+ FeatureUnion([(\"pca\", PCA), (\"passthrough\", \"passthrough\")]),\n+ ],\n+)\n+def test_meta_estimator_raises_class_not_instance_error(meta_estimators):\n+ # non-regression tests for https://github.com/[USER_REDACTED]n/scikit-learn/issues/32719\n+ msg = \"Expected an estimator instance (.*()), got estimator class instead (.*).\"\n+ with pytest.raises(TypeError, match=msg):\n+ meta_estimators.fit([[1]])\n+\n+\n def test_empty_pipeline():\n X = iris.data\n y = iris.target" }, { "filename": "sklearn/utils/metaestimators.py", "status": "modified", "additions": 8, "deletions": 0, "changes": 8, "patch": "@@ -100,6 +100,14 @@ def _validate_names(self, names):\n \"Estimator names must not contain __: got {0!r}\".format(invalid_names)\n )\n \n+ def _check_estimators_are_instances(self, estimators):\n+ for estimator in estimators:\n+ if isinstance(estimator, type):\n+ raise TypeError(\n+ \"Expected an estimator instance ({estimator.__name__}()), got \"\n+ \"estimator class instead ({estimator.__name__}).\"\n+ )\n+\n \n def _safe_split(estimator, X, y, indices, train_indices=None):\n \"\"\"Create subset of dataset and properly handle kernels." } ], "reviews": [ { "id": 3577774861, "user": "user_49a647962c6b", "state": "APPROVED", "body": "This is pretty neat. LGTM, but it can potentially be in our input validation. I'd need [USER_REDACTED] 's opinion on this though.", "submitted_at": "2025-12-15T11:56:31+00:00" }, { "id": 3578189495, "user": "user_9cabc0c64225", "state": "APPROVED", "body": "lgtm, thanks", "submitted_at": "2025-12-15T13:26:50+00:00" } ], "review_comments": [ { "id": 2619102853, "user": "user_49a647962c6b", "body": "```suggestion\n :class:`compose.ColumnTransformer` now raise a clearer\n```\n\nwe should always refer to the public API in the changelog.", "path": "doc/whats_new/upcoming_changes/many-modules/32888.enhancement.rst", "line": null, "side": "RIGHT", "created_at": "2025-12-15T11:54:17+00:00" } ], "meta": { "languages": [ "py", "rst" ], "touches_tests": true, "review_state_summary": { "APPROVED": 2 }, "meaningful_comment_count": 1, "has_approval": true, "has_changes_requested": false, "total_review_comments": 1 } } { "_id": "24dd9f480bb2b773", "_schema_version": "1.0", "_cleaned_at": "2026-02-12T07:46:51.988888+00:00", "repo": "scikit-learn/scikit-learn", "repo_url": "https://github.com/scikit-learn/scikit-learn", "license_name": "BSD 3-Clause \"New\" or \"Revised\" License", "license_spdx": "BSD-3-Clause", "pr_number": 32887, "title": "FIX: Tooltip position using CSS anchor positioning", "body": "\n\n#### [NAME_REDACTED]/PRs\n\nThe documentation tooltip that we introduced with https://github.com/[USER_REDACTED]n/scikit-learn/pull/31564 is hidden if the parameter name that it belongs to, is at the bottom of the table. It's visible only after scrolling down the cell. \nIn this case, when we hover over `n_jobs`, we get:\n\"Screenshot\n\nUsing [CSS anchor positioning:](https://developer.mozilla.org/en-US/docs/Web/CSS/Guides/Anchor_positioning/Using), the result is the following (when hovering over `n_jobs`). No scroll-down needed:\n\n\"Screenshot\n\nThere is no opened issue for this. \n\n#### What does this implement/fix? Explain your changes.\nFor the record: The specs for `anchor-name` and `position-anchor` can't be placed in the `params.css` file. When I did that, the tooltip was always visible at the bottom of the table - not next to the parameter name. \n(It was [USER_REDACTED]'s idea that the tooltip was getting fixed to the last parameter when using Chrome.)\n\n#### AI usage disclosure\n\nI used AI assistance for:\n- [x] Moving the style to `params.py` instead of keeping it on `params.css`. \n- [ ] Test/benchmark generation\n- [ ] Documentation (including examples)\n- [ ] Research and understanding\n\n#### Any other comments?\nI tried to set [Fallback options](https://developer.mozilla.org/en-US/docs/Web/CSS/Guides/Anchor_positioning/Try_options_hiding) ~~but I haven't found the correct rule.~~\n\nEdit: I think the UX would be annoying if I add the fallback options.\n\n", "author": "user_32e669a27072", "created_at": "2025-12-11T13:46:16+00:00", "merged_at": "2025-12-14T23:34:13+00:00", "base_branch": "main", "head_branch": "tooltip", "additions": 34, "deletions": 3, "changed_files": 4, "files": [ { "filename": "doc/whats_new/upcoming_changes/sklearn.utils/32887.fix.rst", "status": "added", "additions": 6, "deletions": 0, "changes": 6, "patch": "@@ -0,0 +1,6 @@\n+- The parameter table in the HTML representation of all scikit-learn\n+ estimators inheritiging from :class:`base.BaseEstimator`, displays\n+ each parameter documentation as a tooltip. The last tooltip of a\n+ parameter in the last table of any HTML representation was partially hidden.\n+ This issue has been fixed.\n+ By :user:`Dea María Léon `" }, { "filename": "sklearn/utils/_repr_html/params.css", "status": "modified", "additions": 16, "deletions": 0, "changes": 16, "patch": "@@ -83,6 +83,14 @@ a.param-doc-link:visited {\n padding: .5em;\n }\n \n+[USER_REDACTED](anchor-name: --doc-link) {\n+ a.param-doc-link,\n+ a.param-doc-link:link,\n+ a.param-doc-link:visited {\n+ anchor-name: --doc-link;\n+ }\n+}\n+\n /* \"hack\" to make the entire area of the cell containing the link clickable */\n a.param-doc-link::before {\n position: absolute;\n@@ -109,6 +117,14 @@ a.param-doc-link::before {\n border: thin solid var(--sklearn-color-unfitted-level-3);\n }\n \n+[USER_REDACTED](position-area: center right) {\n+ .param-doc-description {\n+ position-area: center right;\n+ position: fixed;\n+ margin-left: 0;\n+ }\n+}\n+\n /* Fitted state for parameter tooltips */\n .fitted .param-doc-description {\n /* fitted */" }, { "filename": "sklearn/utils/_repr_html/params.py", "status": "modified", "additions": 4, "deletions": 1, "changes": 5, "patch": "@@ -89,9 +89,12 @@ def _params_html_repr(params):\n \n PARAM_AVAILABLE_DOC_LINK_TEMPLATE = \"\"\"\n \n {param_name}\n- {param_description}\n+ \n+ {param_description}\n \n \"\"\"\n estimator_class_docs = inspect.getdoc(params.estimator_class)" }, { "filename": "sklearn/utils/_repr_html/tests/test_params.py", "status": "modified", "additions": 8, "deletions": 2, "changes": 10, "patch": "@@ -108,10 +108,13 @@ class MockEstimator:\n html_param_a = (\n r''\n r'\\s*'\n r\"\\s*a\"\n- r'\\s*a: int

      '\n+ r'\\s*\\s*a:'\n+ r\"\\sint

      \"\n r\"Description of a\\.
      \"\n r\"\\s*
      \"\n r\"\\s*\"\n@@ -120,10 +123,13 @@ class MockEstimator:\n html_param_b = (\n r''\n r'.*'\n r\"\\s*b\"\n- r'\\s*b: str

      '\n+ r'\\s*\\s*b:'\n+ r\"\\sstr

      \"\n r\"\\s*
      \"\n r\"\\s*\"\n )" } ], "reviews": [ { "id": 3572101428, "user": "user_417fbbcd2f03", "state": "COMMENTED", "body": null, "submitted_at": "2025-12-12T14:43:33+00:00" }, { "id": 3572110390, "user": "user_417fbbcd2f03", "state": "APPROVED", "body": "Otherwise, it is an improvement. LGTM.", "submitted_at": "2025-12-12T14:46:04+00:00" }, { "id": 3572561279, "user": "user_32e669a27072", "state": "COMMENTED", "body": null, "submitted_at": "2025-12-12T16:08:22+00:00" }, { "id": 3574444528, "user": "user_04b4a5f4e2a8", "state": "COMMENTED", "body": "Looking at the `anchor-name` [support table](https://developer.mozilla.org/en-US/docs/Web/CSS/Reference/Properties/anchor-name#browser_compatibility) it is not supported in Firefox yet. \n\nWith this change, what does the tooltip look like in Firefox?", "submitted_at": "2025-12-13T15:48:35+00:00" }, { "id": 3575963830, "user": "user_04b4a5f4e2a8", "state": "APPROVED", "body": null, "submitted_at": "2025-12-14T23:34:06+00:00" } ], "review_comments": [ { "id": 2614448575, "user": "user_417fbbcd2f03", "body": "This is some remaining debugging I think.", "path": "sklearn/utils/_repr_html/tests/test_params.py", "line": null, "side": "RIGHT", "created_at": "2025-12-12T14:43:33+00:00" }, { "id": 2614788801, "user": "user_32e669a27072", "body": "🫣 Thanks", "path": "sklearn/utils/_repr_html/tests/test_params.py", "line": null, "side": "RIGHT", "created_at": "2025-12-12T16:08:22+00:00" } ], "meta": { "languages": [ "css", "py", "rst" ], "touches_tests": true, "review_state_summary": { "COMMENTED": 3, "APPROVED": 2 }, "meaningful_comment_count": 1, "has_approval": true, "has_changes_requested": false, "total_review_comments": 2 } } { "_id": "8d62687ea31ac034", "_schema_version": "1.0", "_cleaned_at": "2026-02-12T07:46:51.988888+00:00", "repo": "scikit-learn/scikit-learn", "repo_url": "https://github.com/scikit-learn/scikit-learn", "license_name": "BSD 3-Clause \"New\" or \"Revised\" License", "license_spdx": "BSD-3-Clause", "pr_number": 32883, "title": "TST Add `confusion_matrix_at_thresholds` to common tests", "body": "#### [NAME_REDACTED]/PRs\n\n#### What does this implement/fix? Explain your changes.\n`confusion_matrix_at_thresholds` was amended to a public function added in #30134. I think it would be worth adding to the common metric tests in `test_common.py`.\nThis would also fix one of the test failures in #32755\n\nAlso fixes `test_binary_sample_weight_invariance` - the curve metrics, as well as `CONTINUOUS_CLASSIFICATION_METRICS`, should also take `y_score` (i.e. unthresholded scores) NOT `y_pred`\n\n#### AI usage disclosure\n\nI used AI assistance for:\n- [ ] Code generation (e.g., when writing an implementation or fixing a bug)\n- [ ] Test/benchmark generation\n- [ ] Documentation (including examples)\n- [x] Research and understanding\n\n#### Any other comments?\n\ncc [USER_REDACTED] because this is related to #32755 and [USER_REDACTED] and [USER_REDACTED] who reviewed #30134", "author": "user_d16337ec046b", "created_at": "2025-12-11T02:21:30+00:00", "merged_at": "2025-12-15T11:50:37+00:00", "base_branch": "main", "head_branch": "tst_conf_mat_thres", "additions": 39, "deletions": 22, "changed_files": 1, "files": [ { "filename": "sklearn/metrics/tests/test_common.py", "status": "modified", "additions": 39, "deletions": 22, "changes": 61, "patch": "@@ -18,6 +18,7 @@\n classification_report,\n cohen_kappa_score,\n confusion_matrix,\n+ confusion_matrix_at_thresholds,\n coverage_error,\n d2_absolute_error_score,\n d2_brier_score,\n@@ -156,17 +157,13 @@\n \"balanced_accuracy_score\": balanced_accuracy_score,\n \"adjusted_balanced_accuracy_score\": partial(balanced_accuracy_score, adjusted=True),\n \"unnormalized_accuracy_score\": partial(accuracy_score, normalize=False),\n- # `confusion_matrix` returns absolute values and hence behaves unnormalized\n- # . Naming it with an unnormalized_ prefix is necessary for this module to\n- # skip sample_weight scaling checks which will fail for unnormalized\n- # metrics.\n- \"unnormalized_confusion_matrix\": confusion_matrix,\n+ \"confusion_matrix\": confusion_matrix,\n \"normalized_confusion_matrix\": lambda *args, **kwargs: (\n confusion_matrix(*args, **kwargs).astype(\"float\")\n / confusion_matrix(*args, **kwargs).sum(axis=1)[:, np.newaxis]\n ),\n- \"unnormalized_multilabel_confusion_matrix\": multilabel_confusion_matrix,\n- \"unnormalized_multilabel_confusion_matrix_sample\": partial(\n+ \"multilabel_confusion_matrix\": multilabel_confusion_matrix,\n+ \"multilabel_confusion_matrix_sample\": partial(\n multilabel_confusion_matrix, samplewise=True\n ),\n \"hamming_loss\": hamming_loss,\n@@ -240,6 +237,7 @@ def precision_recall_curve_padded_thresholds(*args, **kwargs):\n \n \n CURVE_METRICS = {\n+ \"confusion_matrix_at_thresholds\": confusion_matrix_at_thresholds,\n \"roc_curve\": roc_curve,\n \"precision_recall_curve\": precision_recall_curve_padded_thresholds,\n \"det_curve\": det_curve,\n@@ -305,7 +303,7 @@ def precision_recall_curve_padded_thresholds(*args, **kwargs):\n \"samples_recall_score\",\n \"samples_jaccard_score\",\n \"coverage_error\",\n- \"unnormalized_multilabel_confusion_matrix_sample\",\n+ \"multilabel_confusion_matrix_sample\",\n \"label_ranking_loss\",\n \"label_ranking_average_precision_score\",\n \"dcg_score\",\n@@ -327,6 +325,7 @@ def precision_recall_curve_padded_thresholds(*args, **kwargs):\n \"f2_score\",\n \"f0.5_score\",\n # curves\n+ \"confusion_matrix_at_thresholds\",\n \"roc_curve\",\n \"precision_recall_curve\",\n \"det_curve\",\n@@ -356,6 +355,7 @@ def precision_recall_curve_padded_thresholds(*args, **kwargs):\n \n # Metrics with a \"pos_label\" argument\n METRICS_WITH_POS_LABEL = {\n+ \"confusion_matrix_at_thresholds\",\n \"roc_curve\",\n \"precision_recall_curve\",\n \"det_curve\",\n@@ -377,7 +377,7 @@ def precision_recall_curve_padded_thresholds(*args, **kwargs):\n # TODO: Handle multi_class metrics that has a labels argument as well as a\n # decision function argument. e.g hinge_loss\n METRICS_WITH_LABELS = {\n- \"unnormalized_confusion_matrix\",\n+ \"confusion_matrix\",\n \"normalized_confusion_matrix\",\n \"roc_curve\",\n \"precision_recall_curve\",\n@@ -406,8 +406,8 @@ def precision_recall_curve_padded_thresholds(*args, **kwargs):\n \"macro_precision_score\",\n \"macro_recall_score\",\n \"macro_jaccard_score\",\n- \"unnormalized_multilabel_confusion_matrix\",\n- \"unnormalized_multilabel_confusion_matrix_sample\",\n+ \"multilabel_confusion_matrix\",\n+ \"multilabel_confusion_matrix_sample\",\n \"cohen_kappa_score\",\n \"log_loss\",\n \"d2_log_loss_score\",\n@@ -470,7 +470,7 @@ def precision_recall_curve_padded_thresholds(*args, **kwargs):\n \"micro_precision_score\",\n \"micro_recall_score\",\n \"micro_jaccard_score\",\n- \"unnormalized_multilabel_confusion_matrix\",\n+ \"multilabel_confusion_matrix\",\n \"samples_f0.5_score\",\n \"samples_f1_score\",\n \"samples_f2_score\",\n@@ -538,8 +538,9 @@ def precision_recall_curve_padded_thresholds(*args, **kwargs):\n \"adjusted_balanced_accuracy_score\",\n \"explained_variance_score\",\n \"r2_score\",\n- \"unnormalized_confusion_matrix\",\n+ \"confusion_matrix\",\n \"normalized_confusion_matrix\",\n+ \"confusion_matrix_at_thresholds\",\n \"roc_curve\",\n \"precision_recall_curve\",\n \"det_curve\",\n@@ -552,7 +553,7 @@ def precision_recall_curve_padded_thresholds(*args, **kwargs):\n \"weighted_f2_score\",\n \"weighted_precision_score\",\n \"weighted_jaccard_score\",\n- \"unnormalized_multilabel_confusion_matrix\",\n+ \"multilabel_confusion_matrix\",\n \"macro_f0.5_score\",\n \"macro_f2_score\",\n \"macro_precision_score\",\n@@ -575,6 +576,19 @@ def precision_recall_curve_padded_thresholds(*args, **kwargs):\n \"weighted_ovo_roc_auc\",\n }\n \n+WEIGHT_SCALE_DEPENDENT_METRICS = {\n+ # 'confusion_matrix' metrics returns absolute `tps`, `fps` etc values, which\n+ # are scaled by weights, so will vary e.g., scaling by 3 will result in 3 * `tps`\n+ \"confusion_matrix\",\n+ \"confusion_matrix_at_thresholds\",\n+ \"multilabel_confusion_matrix\",\n+ \"multilabel_confusion_matrix_sample\",\n+ # Metrics where we set `normalize=False`\n+ \"unnormalized_accuracy_score\",\n+ \"unnormalized_zero_one_loss\",\n+ \"unnormalized_log_loss\",\n+}\n+\n METRICS_REQUIRE_POSITIVE_Y = {\n \"mean_poisson_deviance\",\n \"mean_gamma_deviance\",\n@@ -1612,12 +1626,15 @@ def check_sample_weight_invariance(name, metric, y1, y2, sample_weight=None):\n % (weighted_score_zeroed, weighted_score_subset, name),\n )\n \n- if not name.startswith(\"unnormalized\"):\n- # check that the score is invariant under scaling of the weights by a\n- # common factor\n- # Due to numerical instability of floating points in `cumulative_sum` in\n- # `median_absolute_error`, it is not always equivalent when scaling by a float.\n- scaling_values = [2] if name == \"median_absolute_error\" else [2, 0.3]\n+ # Check the score is invariant under scaling of weights by a constant factor\n+ if name not in WEIGHT_SCALE_DEPENDENT_METRICS:\n+ # Numerical instability of floating points in `cumulative_sum` in\n+ # `median_absolute_error`, and in `diff` when in calculating collinear points\n+ # and points in between to drop `roc_curve` means they are not always\n+ # equivalent when scaling by a float.\n+ scaling_values = (\n+ [2] if name in {\"median_absolute_error\", \"roc_curve\"} else [2, 0.3]\n+ )\n for scaling in scaling_values:\n assert_allclose(\n weighted_score,\n@@ -1715,7 +1732,7 @@ def test_binary_sample_weight_invariance(name):\n y_pred = random_state.randint(0, 2, size=(n_samples,))\n y_score = random_state.random_sample(size=(n_samples,))\n metric = ALL_METRICS[name]\n- if name in CONTINUOUS_CLASSIFICATION_METRICS:\n+ if name in (CONTINUOUS_CLASSIFICATION_METRICS | CURVE_METRICS.keys()):\n check_sample_weight_invariance(name, metric, y_true, y_score)\n else:\n check_sample_weight_invariance(name, metric, y_true, y_pred)\n@@ -1816,7 +1833,7 @@ def test_no_averaging_labels():\n \n \n [USER_REDACTED].mark.parametrize(\n- \"name\", sorted(MULTILABELS_METRICS - {\"unnormalized_multilabel_confusion_matrix\"})\n+ \"name\", sorted(MULTILABELS_METRICS - {\"multilabel_confusion_matrix\"})\n )\n def test_multilabel_label_permutations_invariance(name):\n random_state = check_random_state(0)" } ], "reviews": [ { "id": 3565356967, "user": "user_d16337ec046b", "state": "COMMENTED", "body": null, "submitted_at": "2025-12-11T02:33:23+00:00" }, { "id": 3566457003, "user": "user_5819d17296ee", "state": "APPROVED", "body": "Thanks for the PR.", "submitted_at": "2025-12-11T09:15:13+00:00" }, { "id": 3566857492, "user": "user_d16337ec046b", "state": "COMMENTED", "body": null, "submitted_at": "2025-12-11T10:55:11+00:00" }, { "id": 3577760659, "user": "user_49a647962c6b", "state": "APPROVED", "body": null, "submitted_at": "2025-12-15T11:49:45+00:00" } ], "review_comments": [ { "id": 2608903262, "user": "user_d16337ec046b", "body": "In `roc_curve` we do:\n\nhttps://github.com/[USER_REDACTED]n/scikit-learn/blob/7f0900c265936eac9a89bba37eb19ee66208d46a/sklearn/metrics/_ranking.py#L1271-L1280\n\nwhen scaling by a float, `diff` can result in extra indices. Note that in `confusion_matrix_at_thresholds` we already use max floating point precision when calculating `tps` and `fps` with `cumulative_sum`.\n\nAlso note `drop_intermediate=True` is the default.\n\n
      \nDetails\n\nIn the test `test_binary_sample_weight_invariance`, with no scaling the indices are:\n\n```\noptimal_idxs=array([ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 15, 16, 17,\n18, 20, 21, 22, 23, 24, 25, 26, 29, 30, 32, 33, 34, 35, 36, 37, 38,\n39, 41, 42, 43, 44, 45, 46, 48, 49])\n```\n\nwith scaling 0.3, the indices are:\n\n```\noptimal_idxs=array([ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16,\n17, 18, 20, 21, 22, 23, 24, 25, 26, 29, 30, 32, 33, 34, 35, 36, 37,\n38, 39, 40, 41, 42, 43, 44, 45, 46, 48, 49])\n```\n\nthere are extra indices: 14 and 40 here\n\n
      ", "path": "sklearn/metrics/tests/test_common.py", "line": 1634, "side": "RIGHT", "created_at": "2025-12-11T02:33:23+00:00" }, { "id": 2609790245, "user": "user_5819d17296ee", "body": "I think we should define a test module constant `WEIGHT_SCALE_DEPENDENT_METRICS` with all the metric names that are expected to be dependent on the weight scale.", "path": "sklearn/metrics/tests/test_common.py", "line": null, "side": "RIGHT", "created_at": "2025-12-11T09:14:46+00:00" }, { "id": 2610126594, "user": "user_d16337ec046b", "body": "Just found:\n\nhttps://github.com/[USER_REDACTED]n/scikit-learn/blob/7f0900c265936eac9a89bba37eb19ee66208d46a/sklearn/metrics/tests/test_common.py#L159-L163\n\nit seems the current procedure is to add \"unnormalized\" to the start of any non-partial metrics to indicate scale invariance.\n\nI *think* it still would be nice to have `WEIGHT_SCALE_DEPENDENT_METRICS`, so you can see all the scale variant metrics in one place, but I am not 100% we shouldn't just stick to the old procedure...\n\nEdit: Added, but can easily undo that commit, let me know what you think", "path": "sklearn/metrics/tests/test_common.py", "line": null, "side": "RIGHT", "created_at": "2025-12-11T10:55:11+00:00" } ], "meta": { "languages": [ "py" ], "touches_tests": true, "review_state_summary": { "COMMENTED": 2, "APPROVED": 2 }, "meaningful_comment_count": 3, "has_approval": true, "has_changes_requested": false, "total_review_comments": 3 } } { "_id": "534d199540fc77e6", "_schema_version": "1.0", "_cleaned_at": "2026-02-12T07:46:51.991980+00:00", "repo": "scikit-learn/scikit-learn", "repo_url": "https://github.com/scikit-learn/scikit-learn", "license_name": "BSD 3-Clause \"New\" or \"Revised\" License", "license_spdx": "BSD-3-Clause", "pr_number": 32865, "title": "FIX add quickfix for pandas warning causing CI error", "body": "\n\n#### [NAME_REDACTED]/PRs\n\nFixes #32829 \n\n#### What does this implement/fix? Explain your changes.\nCatches the `Pandas4Warning` that causes a CI failure. \n\n#### Any other comments?\nI'm not sure if this makes sense, but AFAIU the main thing the test is checking is whether `TargetEncoder` works when `y` is read-only, so maybe the test could even be changed into explicitly creating a read-only `y` without the implicit pandas conversion? \n\nEdit: I changed the version check to use `sklearn.externals._packaging.version`.\n\n[USER_REDACTED] \n\n", "author": "user_34a090906ca4", "created_at": "2025-12-08T13:57:26+00:00", "merged_at": "2025-12-10T07:52:53+00:00", "base_branch": "main", "head_branch": "pandas_workaround", "additions": 22, "deletions": 1, "changed_files": 1, "files": [ { "filename": "sklearn/preprocessing/tests/test_target_encoder.py", "status": "modified", "additions": 22, "deletions": 1, "changes": 23, "patch": "@@ -1,4 +1,5 @@\n import re\n+import warnings\n \n import numpy as np\n import pytest\n@@ -20,6 +21,7 @@\n LabelEncoder,\n TargetEncoder,\n )\n+from sklearn.utils.fixes import parse_version\n \n \n def _encode_target(X_ordinal, y_numeric, n_categories, smooth):\n@@ -709,6 +711,25 @@ def test_pandas_copy_on_write():\n Non-regression test for gh-27879.\n \"\"\"\n pd = pytest.importorskip(\"pandas\", minversion=\"2.0\")\n- with pd.option_context(\"mode.copy_on_write\", True):\n+ # Pandas currently warns that setting copy_on_write will be removed in pandas 4\n+ # (and copy-on-write will always be enabled).\n+ # see https://github.com/[USER_REDACTED]n/scikit-learn/issues/32829\n+ # TODO: remove this workaround when pandas 4 is our minimum version\n+ if parse_version(pd.__version__) >= parse_version(\"4.0\"):\n df = pd.DataFrame({\"x\": [\"a\", \"b\", \"b\"], \"y\": [4.0, 5.0, 6.0]})\n TargetEncoder(target_type=\"continuous\").fit(df[[\"x\"]], df[\"y\"])\n+ else:\n+ with warnings.catch_warnings():\n+ expected_message = (\n+ \"Copy-on-Write can no longer be disabled, \"\n+ \"setting to False has no impact. This option will \"\n+ \"be removed in pandas 4.0.\"\n+ )\n+ warnings.filterwarnings(\n+ \"ignore\",\n+ message=re.escape(expected_message),\n+ category=DeprecationWarning,\n+ )\n+ with pd.option_context(\"mode.copy_on_write\", True):\n+ df = pd.DataFrame({\"x\": [\"a\", \"b\", \"b\"], \"y\": [4.0, 5.0, 6.0]})\n+ TargetEncoder(target_type=\"continuous\").fit(df[[\"x\"]], df[\"y\"])" } ], "reviews": [ { "id": 3556169929, "user": "user_5819d17296ee", "state": "COMMENTED", "body": null, "submitted_at": "2025-12-09T08:48:50+00:00" }, { "id": 3556184133, "user": "user_5819d17296ee", "state": "COMMENTED", "body": null, "submitted_at": "2025-12-09T08:51:40+00:00" }, { "id": 3561198615, "user": "user_fca2535bcd49", "state": "APPROVED", "body": "Thanks for the PR!", "submitted_at": "2025-12-10T07:52:36+00:00" } ], "review_comments": [ { "id": 2601653911, "user": "user_5819d17296ee", "body": "I took a look at the class hierarchy of the warning in the nightly build of pandas, and it is a subclass of the usual DeprecationWarning:\n\n```python\n>>> pd.errors.Pandas4Warning.__mro__ \n(pandas.errors.Pandas4Warning,\n pandas.errors.PandasDeprecationWarning,\n pandas.errors.PandasChangeWarning,\n DeprecationWarning,\n Warning,\n Exception,\n BaseException,\n object)\n```\n\nSo filtering those might work, irrespective of the Pandas version.\n\n```suggestion\n category=DeprecationWarning,\n```", "path": "sklearn/preprocessing/tests/test_target_encoder.py", "line": null, "side": "RIGHT", "created_at": "2025-12-09T08:48:50+00:00" }, { "id": 2601663235, "user": "user_5819d17296ee", "body": "Also: the `message` argument of `filterwarnings` is regular expression. So it's likely necessary to wrap the verbatim expected message as `re.escape(expected_warning_message)`.", "path": "sklearn/preprocessing/tests/test_target_encoder.py", "line": null, "side": "RIGHT", "created_at": "2025-12-09T08:51:40+00:00" } ], "meta": { "languages": [ "py" ], "touches_tests": true, "review_state_summary": { "COMMENTED": 2, "APPROVED": 1 }, "meaningful_comment_count": 2, "has_approval": true, "has_changes_requested": false, "total_review_comments": 2 } } { "_id": "10e38204b5d53e4a", "_schema_version": "1.0", "_cleaned_at": "2026-02-12T07:46:51.991980+00:00", "repo": "scikit-learn/scikit-learn", "repo_url": "https://github.com/scikit-learn/scikit-learn", "license_name": "BSD 3-Clause \"New\" or \"Revised\" License", "license_spdx": "BSD-3-Clause", "pr_number": 32860, "title": "Reverts the screening refactoring in enet_coordinate_descent_gram", "body": "\n\n#### [NAME_REDACTED]/PRs\n\nReverts #32197\n\n#### What does this implement/fix? Explain your changes.\n- This reverts the refactoring with respect to the screening in `enet_coordinate_descent_gram`\n\n#### AI usage disclosure\n\nI used AI assistance for:\n- [ ] Code generation (e.g., when writing an implementation or fixing a bug)\n- [ ] Test/benchmark generation\n- [ ] Documentation (including examples)\n- [ ] Research and understanding\n\n", "author": "user_3c90b5520ec5", "created_at": "2025-12-08T10:23:21+00:00", "merged_at": "2025-12-12T14:30:10+00:00", "base_branch": "main", "head_branch": "enet-gram-excluded-set", "additions": 41, "deletions": 68, "changed_files": 1, "files": [ { "filename": "sklearn/linear_model/_cd_fast.pyx", "status": "modified", "additions": 41, "deletions": 68, "changes": 109, "patch": "@@ -914,48 +914,6 @@ cdef (floating, floating) gap_enet_gram(\n return gap, dual_norm_XtA\n \n \n-cdef inline uint32_t screen_features_enet_gram(\n- const floating[:, ::1] Q,\n- const floating[::1] XtA,\n- floating[::1] w,\n- floating[::1] Qw,\n- uint32_t[::1] active_set,\n- uint8_t[::1] excluded_set,\n- floating alpha,\n- floating beta,\n- floating gap,\n- floating dual_norm_XtA,\n- uint32_t n_features,\n-) noexcept nogil:\n- \"\"\"Apply gap safe screening for all features within enet_coordinate_descent_gram\"\"\"\n- cdef floating d_j\n- cdef floating Xj_theta\n- cdef uint32_t n_active = 0\n- # Due to floating point issues, gap might be negative.\n- cdef floating radius = sqrt(2 * fabs(gap)) / alpha\n-\n- for j in range(n_features):\n- if Q[j, j] == 0:\n- w[j] = 0\n- excluded_set[j] = 1\n- continue\n-\n- Xj_theta = XtA[j] / fmax(alpha, dual_norm_XtA) # X[:,j] @ dual_theta\n- d_j = (1 - fabs(Xj_theta)) / sqrt(Q[j, j] + beta)\n- if d_j <= radius:\n- # include feature j\n- active_set[n_active] = j\n- excluded_set[j] = 0\n- n_active += 1\n- else:\n- # Qw -= w[j] * Q[j] # Update Qw = Q @ w\n- _axpy(n_features, -w[j], &Q[j, 0], 1, &Qw[0], 1)\n- w[j] = 0\n- excluded_set[j] = 1\n-\n- return n_active\n-\n-\n def enet_coordinate_descent_gram(\n floating[::1] w,\n floating alpha,\n@@ -1007,6 +965,9 @@ def enet_coordinate_descent_gram(\n cdef floating[::1] XtA = np.zeros(n_features, dtype=dtype)\n cdef floating y_norm2 = np.dot(y, y)\n \n+ cdef floating d_j\n+ cdef floating radius\n+ cdef floating Xj_theta\n cdef floating tmp\n cdef floating w_j\n cdef floating d_w_max\n@@ -1050,19 +1011,26 @@ def enet_coordinate_descent_gram(\n \n # [NAME_REDACTED] Rules, see https://arxiv.org/abs/1802.07481, Eq. 11\n if do_screening:\n- n_active = screen_features_enet_gram(\n- Q=Q,\n- XtA=XtA,\n- w=w,\n- Qw=Qw,\n- active_set=active_set,\n- excluded_set=excluded_set,\n- alpha=alpha,\n- beta=beta,\n- gap=gap,\n- dual_norm_XtA=dual_norm_XtA,\n- n_features=n_features,\n- )\n+ # Due to floating point issues, gap might be negative.\n+ radius = sqrt(2 * fabs(gap)) / alpha\n+ n_active = 0\n+ for j in range(n_features):\n+ if Q[j, j] == 0:\n+ w[j] = 0\n+ excluded_set[j] = 1\n+ continue\n+ Xj_theta = XtA[j] / fmax(alpha, dual_norm_XtA) # X[:,j] @ dual_theta\n+ d_j = (1 - fabs(Xj_theta)) / sqrt(Q[j, j] + beta)\n+ if d_j <= radius:\n+ # include feature j\n+ active_set[n_active] = j\n+ excluded_set[j] = 0\n+ n_active += 1\n+ else:\n+ # Qw -= w[j] * Q[j] # Update Qw = Q @ w\n+ _axpy(n_features, -w[j], &Q[j, 0], 1, &Qw[0], 1)\n+ w[j] = 0\n+ excluded_set[j] = 1\n \n for n_iter in range(max_iter):\n w_max = 0.0\n@@ -1116,19 +1084,24 @@ def enet_coordinate_descent_gram(\n \n # [NAME_REDACTED] Rules, see https://arxiv.org/abs/1802.07481, Eq. 11\n if do_screening:\n- n_active = screen_features_enet_gram(\n- Q=Q,\n- XtA=XtA,\n- w=w,\n- Qw=Qw,\n- active_set=active_set,\n- excluded_set=excluded_set,\n- alpha=alpha,\n- beta=beta,\n- gap=gap,\n- dual_norm_XtA=dual_norm_XtA,\n- n_features=n_features,\n- )\n+ # Due to floating point issues, gap might be negative.\n+ radius = sqrt(2 * fabs(gap)) / alpha\n+ n_active = 0\n+ for j in range(n_features):\n+ if excluded_set[j]:\n+ continue\n+ Xj_theta = XtA[j] / fmax(alpha, dual_norm_XtA) # X @ dual_theta\n+ d_j = (1 - fabs(Xj_theta)) / sqrt(Q[j, j] + beta)\n+ if d_j <= radius:\n+ # include feature j\n+ active_set[n_active] = j\n+ excluded_set[j] = 0\n+ n_active += 1\n+ else:\n+ # Qw -= w[j] * Q[j] # Update Qw = Q @ w\n+ _axpy(n_features, -w[j], &Q[j, 0], 1, &Qw[0], 1)\n+ w[j] = 0\n+ excluded_set[j] = 1\n \n else:\n # for/else, runs if for doesn't end with a `break`" } ], "reviews": [ { "id": 3551313359, "user": "user_5819d17296ee", "state": "COMMENTED", "body": "Could you please check the impact of this change with benchmark?", "submitted_at": "2025-12-08T10:30:55+00:00" }, { "id": 3551329795, "user": "user_3c90b5520ec5", "state": "COMMENTED", "body": null, "submitted_at": "2025-12-08T10:34:02+00:00" }, { "id": 3552337073, "user": "user_3c90b5520ec5", "state": "COMMENTED", "body": null, "submitted_at": "2025-12-08T14:23:17+00:00" }, { "id": 3571341831, "user": "user_22bafe4fe1a9", "state": "COMMENTED", "body": "While this PR is an improvement, I still prefer to revert #32197. The result of PR #32197 is more lines of code and one loop over features more (which is negligible).\n\n[USER_REDACTED] Please don't feel offended or under-appreciated. It is just my (personal/professional) opinion, which I was not able to give at that PR.", "submitted_at": "2025-12-12T11:04:41+00:00" }, { "id": 3571947646, "user": "user_22bafe4fe1a9", "state": "APPROVED", "body": "Thanks [USER_REDACTED]", "submitted_at": "2025-12-12T14:03:40+00:00" } ], "review_comments": [ { "id": 2598023450, "user": "user_5819d17296ee", "body": "Why do we need to introduce `excluded_set_computed`? Cannot we just do?\n\n```suggestion\n if excluded_set[j]:\n continue\n```", "path": "sklearn/linear_model/_cd_fast.pyx", "line": null, "side": "RIGHT", "created_at": "2025-12-08T10:30:36+00:00" }, { "id": 2598035969, "user": "user_3c90b5520ec5", "body": "This won't work. We have failing tests.", "path": "sklearn/linear_model/_cd_fast.pyx", "line": null, "side": "RIGHT", "created_at": "2025-12-08T10:34:02+00:00" }, { "id": 2598833557, "user": "user_3c90b5520ec5", "body": "Since we initialize this to `empty` we kind of need the additional `excluded_set[j] = 0` here, otherwise we run into problems.", "path": "sklearn/linear_model/_cd_fast.pyx", "line": null, "side": "RIGHT", "created_at": "2025-12-08T14:23:17+00:00" }, { "id": 2613790292, "user": "user_22bafe4fe1a9", "body": "Keep this line", "path": "sklearn/linear_model/_cd_fast.pyx", "line": 948, "side": "LEFT", "created_at": "2025-12-12T10:53:07+00:00" } ], "meta": { "languages": [ "pyx" ], "touches_tests": false, "review_state_summary": { "COMMENTED": 4, "APPROVED": 1 }, "meaningful_comment_count": 4, "has_approval": true, "has_changes_requested": false, "total_review_comments": 4 } } { "_id": "944e6047f080e2a1", "_schema_version": "1.0", "_cleaned_at": "2026-02-12T07:46:51.991980+00:00", "repo": "scikit-learn/scikit-learn", "repo_url": "https://github.com/scikit-learn/scikit-learn", "license_name": "BSD 3-Clause \"New\" or \"Revised\" License", "license_spdx": "BSD-3-Clause", "pr_number": 32853, "title": "FIX: Fixed duplicate column error appearing with FeatureUnion polars", "body": "When using FeatureUnion with set_config(transform_output=\"polars\"), the operation failed with polars.exceptions.DuplicateError because the ContainerAdapterProtocol.hstack() interface was incomplete: it didn't accept a `feature_names` parameter to apply column renaming before concatenation.\n\nFixes https://github.com/[USER_REDACTED]n/scikit-learn/issues/32852", "author": "user_20c837b3d4d8", "created_at": "2025-12-07T18:40:14+00:00", "merged_at": "2026-01-27T09:00:54+00:00", "base_branch": "main", "head_branch": "fix-featureunion-polars-duplicates", "additions": 28, "deletions": 10, "changed_files": 4, "files": [ { "filename": "doc/whats_new/upcoming_changes/sklearn.pipeline/32853.fix.rst", "status": "added", "additions": 1, "deletions": 0, "changes": 1, "patch": "@@ -0,0 +1 @@\n+- Fixed :class:`pipeline.FeatureUnion` to properly handle column renaming when using Polars output, preventing duplicate column names. By :user:`[NAME_REDACTED] `. :pr:`32853`\n\\ No newline at end of file" }, { "filename": "sklearn/pipeline.py", "status": "modified", "additions": 1, "deletions": 1, "changes": 2, "patch": "@@ -1995,7 +1995,7 @@ def _hstack(self, Xs):\n \n adapter = _get_container_adapter(\"transform\", self)\n if adapter and all(adapter.is_supported_container(X) for X in Xs):\n- return adapter.hstack(Xs)\n+ return adapter.hstack(Xs, self.get_feature_names_out())\n \n if any(sparse.issparse(f) for f in Xs):\n return sparse.hstack(Xs).tocsr()" }, { "filename": "sklearn/tests/test_pipeline.py", "status": "modified", "additions": 7, "deletions": 5, "changes": 12, "patch": "@@ -1850,20 +1850,22 @@ def test_pipeline_set_output_integration():\n assert_array_equal(feature_names_in_, log_reg_feature_names)\n \n \n-def test_feature_union_set_output():\n+[USER_REDACTED].mark.parametrize(\"df_library\", [\"pandas\", \"polars\"])\n+def test_feature_union_set_output(df_library):\n \"\"\"Test feature union with set_output API.\"\"\"\n- pd = pytest.importorskip(\"pandas\")\n+ lib = pytest.importorskip(df_library)\n \n X, _ = load_iris(as_frame=True, return_X_y=True)\n X_train, X_test = train_test_split(X, random_state=0)\n union = FeatureUnion([(\"scalar\", StandardScaler()), (\"pca\", PCA())])\n- union.set_output(transform=\"pandas\")\n+ union.set_output(transform=df_library)\n union.fit(X_train)\n \n X_trans = union.transform(X_test)\n- assert isinstance(X_trans, pd.DataFrame)\n+ assert isinstance(X_trans, lib.DataFrame)\n assert_array_equal(X_trans.columns, union.get_feature_names_out())\n- assert_array_equal(X_trans.index, X_test.index)\n+ if df_library == \"pandas\":\n+ assert_array_equal(X_trans.index, X_test.index)\n \n \n def test_feature_union_getitem():" }, { "filename": "sklearn/utils/_set_output.py", "status": "modified", "additions": 19, "deletions": 4, "changes": 23, "patch": "@@ -95,14 +95,18 @@ def rename_columns(self, X, columns):\n Container with new names.\n \"\"\"\n \n- def hstack(self, Xs):\n+ def hstack(self, Xs, feature_names=None):\n \"\"\"Stack containers horizontally (column-wise).\n \n Parameters\n ----------\n Xs : list of containers\n List of containers to stack.\n \n+ feature_names : array-like of str, default=None\n+ The feature names for the stacked container. If provided, the\n+ columns of the result will be renamed to these names.\n+\n Returns\n -------\n stacked_Xs : container\n@@ -147,9 +151,12 @@ def rename_columns(self, X, columns):\n X.columns = columns\n return X\n \n- def hstack(self, Xs):\n+ def hstack(self, Xs, feature_names=None):\n pd = check_library_installed(\"pandas\")\n- return pd.concat(Xs, axis=1)\n+ result = pd.concat(Xs, axis=1)\n+ if feature_names is not None:\n+ self.rename_columns(result, feature_names)\n+ return result\n \n \n class PolarsAdapter:\n@@ -178,8 +185,16 @@ def rename_columns(self, X, columns):\n X.columns = columns\n return X\n \n- def hstack(self, Xs):\n+ def hstack(self, Xs, feature_names=None):\n pl = check_library_installed(\"polars\")\n+ if feature_names is not None:\n+ # Rename columns in each X before concat to avoid duplicates\n+ start = 0\n+ for X in Xs:\n+ n_features = X.shape[1]\n+ names = feature_names[start : start + n_features]\n+ self.rename_columns(X, names)\n+ start += n_features\n return pl.concat(Xs, how=\"horizontal\")" } ], "reviews": [ { "id": 3552164724, "user": "user_5819d17296ee", "state": "COMMENTED", "body": "Thanks for the fix. It looks correct to me but I think the testing of pandas and polars should be decoupled:", "submitted_at": "2025-12-08T13:46:23+00:00" }, { "id": 3553689120, "user": "user_20c837b3d4d8", "state": "COMMENTED", "body": null, "submitted_at": "2025-12-08T19:19:01+00:00" }, { "id": 3706024499, "user": "user_5819d17296ee", "state": "APPROVED", "body": "Sorry for the late feedback. LGTM!", "submitted_at": "2026-01-26T13:25:19+00:00" }, { "id": 3706776879, "user": "user_d5b9cb906259", "state": "APPROVED", "body": "This looks good to me.\n\nOne small comment: for bug reports like https://github.com/[USER_REDACTED]n/scikit-learn/issues/32852 that come with a good and short reproducer we sometimes include an explicit test with the reproducer and a comment saying \"non regression test for gh-32852\". I think we test the relevant functionality already in `test_feature_union_set_output` (the reason it didn't catch the bug is because we didn't test with polars), but maybe it makes sense to add that non regression test\n\nWhen I checkout this PR locally and run the following snippet everything works:\n```python\nfrom sklearn.pipeline import FeatureUnion\nfrom sklearn.preprocessing import StandardScaler\nfrom sklearn import set_config\nimport numpy as np\nset_config(transform_output=\"polars\")\nX = np.array([[1, 2], [3, 4], [5, 6]])\nunion = FeatureUnion([\n (\"scaler1\", StandardScaler()),\n (\"scaler2\", StandardScaler())\n])\nresult = union.fit_transform(X)\n```", "submitted_at": "2026-01-26T16:07:04+00:00" } ], "review_comments": [ { "id": 2598699810, "user": "user_5819d17296ee", "body": "I would rather use `[USER_REDACTED].mark.parametrize(df_library, [\"pandas\", \"polars\"])` so that the full test is not marked as skipped if only one of the two libs is installed.", "path": "sklearn/tests/test_pipeline.py", "line": null, "side": "RIGHT", "created_at": "2025-12-08T13:45:01+00:00" }, { "id": 2599832136, "user": "user_20c837b3d4d8", "body": "Thanks for the feedback, very valid point, fixed it in the new commit.", "path": "sklearn/tests/test_pipeline.py", "line": null, "side": "RIGHT", "created_at": "2025-12-08T19:19:01+00:00" } ], "meta": { "languages": [ "py", "rst" ], "touches_tests": true, "review_state_summary": { "COMMENTED": 2, "APPROVED": 2 }, "meaningful_comment_count": 2, "has_approval": true, "has_changes_requested": false, "total_review_comments": 2 } } { "_id": "d57045eeb987f522", "_schema_version": "1.0", "_cleaned_at": "2026-02-12T07:46:51.991980+00:00", "repo": "scikit-learn/scikit-learn", "repo_url": "https://github.com/scikit-learn/scikit-learn", "license_name": "BSD 3-Clause \"New\" or \"Revised\" License", "license_spdx": "BSD-3-Clause", "pr_number": 32849, "title": "MNT Use consistent ruff version in pre-commit and linting", "body": "Noticed thanks to [USER_REDACTED] https://github.com/[USER_REDACTED]n/scikit-learn/pull/32813#pullrequestreview-3519391603\n\nSorry [USER_REDACTED] it would have been something you could have done indeed, but I only noticed your comment once I already did the work and was about to open the PR :sweat_smile:. Feel free to review my PR, in case you can spot something I missed.", "author": "user_fca2535bcd49", "created_at": "2025-12-06T07:17:54+00:00", "merged_at": "2025-12-18T09:04:02+00:00", "base_branch": "main", "head_branch": "use-consistent-ruff-version", "additions": 11, "deletions": 9, "changed_files": 5, "files": [ { "filename": ".pre-commit-config.yaml", "status": "modified", "additions": 2, "deletions": 0, "changes": 2, "patch": "@@ -7,6 +7,8 @@ repos:\n - id: end-of-file-fixer\n - id: trailing-whitespace\n - repo: https://github.com/astral-sh/ruff-pre-commit\n+ # WARNING if you update ruff version here, remember to update\n+ # sklearn/_min_dependencies.py and doc .rst files mentioning ruff==\n rev: v0.12.2\n hooks:\n - id: ruff-check" }, { "filename": "benchmarks/bench_tsne_mnist.py", "status": "modified", "additions": 1, "deletions": 1, "changes": 2, "patch": "@@ -15,14 +15,14 @@\n \n import numpy as np\n from joblib import Memory\n+from sklearn.utils._openmp_helpers import _openmp_effective_n_threads\n \n from sklearn.datasets import fetch_openml\n from sklearn.decomposition import PCA\n from sklearn.manifold import TSNE\n from sklearn.neighbors import NearestNeighbors\n from sklearn.utils import check_array\n from sklearn.utils import shuffle as _shuffle\n-from sklearn.utils._openmp_helpers import _openmp_effective_n_threads\n \n LOG_DIR = \"mnist_tsne_output\"\n if not os.path.exists(LOG_DIR):" }, { "filename": "doc/developers/development_setup.rst", "status": "modified", "additions": 6, "deletions": 6, "changes": 12, "patch": "@@ -129,7 +129,7 @@ the required packages.\n \n conda create -n sklearn-dev -c conda-forge ^\n python numpy scipy cython meson-python ninja ^\n- pytest pytest-cov ruff==0.11.2 mypy numpydoc ^\n+ pytest pytest-cov ruff==0.12.2 mypy numpydoc ^\n joblib threadpoolctl pre-commit\n \n Activate the newly created conda environment:\n@@ -167,7 +167,7 @@ the required packages.\n .. prompt::\n \n pip install wheel numpy scipy cython meson-python ninja ^\n- pytest pytest-cov ruff==0.11.2 mypy numpydoc ^\n+ pytest pytest-cov ruff==0.12.2 mypy numpydoc ^\n joblib threadpoolctl pre-commit\n \n \n@@ -199,7 +199,7 @@ the required packages.\n \n conda create -n sklearn-dev -c conda-forge python \\\n numpy scipy cython meson-python ninja \\\n- pytest pytest-cov ruff==0.11.2 mypy numpydoc \\\n+ pytest pytest-cov ruff==0.12.2 mypy numpydoc \\\n joblib threadpoolctl compilers llvm-openmp pre-commit\n \n and activate the newly created conda environment:\n@@ -244,7 +244,7 @@ the required packages.\n .. prompt::\n \n pip install wheel numpy scipy cython meson-python ninja \\\n- pytest pytest-cov ruff==0.11.2 mypy numpydoc \\\n+ pytest pytest-cov ruff==0.12.2 mypy numpydoc \\\n joblib threadpoolctl pre-commit\n \n .. tab-item:: Linux\n@@ -267,7 +267,7 @@ the required packages.\n \n conda create -n sklearn-dev -c conda-forge python \\\n numpy scipy cython meson-python ninja \\\n- pytest pytest-cov ruff==0.11.2 mypy numpydoc \\\n+ pytest pytest-cov ruff==0.12.2 mypy numpydoc \\\n joblib threadpoolctl compilers pre-commit\n \n and activate the newly created environment:\n@@ -327,7 +327,7 @@ the required packages.\n .. prompt::\n \n pip install wheel numpy scipy cython meson-python ninja \\\n- pytest pytest-cov ruff==0.11.2 mypy numpydoc \\\n+ pytest pytest-cov ruff==0.12.2 mypy numpydoc \\\n joblib threadpoolctl pre-commit" }, { "filename": "pyproject.toml", "status": "modified", "additions": 1, "deletions": 1, "changes": 2, "patch": "@@ -81,7 +81,7 @@ tests = [\n \"pandas>=1.5.0\",\n \"pytest>=7.1.2\",\n \"pytest-cov>=2.9.0\",\n- \"ruff>=0.11.7\",\n+ \"ruff>=0.12.2\",\n \"mypy>=1.15\",\n \"pyamg>=5.0.0\",\n \"polars>=0.20.30\"," }, { "filename": "sklearn/_min_dependencies.py", "status": "modified", "additions": 1, "deletions": 1, "changes": 2, "patch": "@@ -32,7 +32,7 @@\n \"memory_profiler\": (\"0.57.0\", \"benchmark, docs\"),\n \"pytest\": (PYTEST_MIN_VERSION, \"tests\"),\n \"pytest-cov\": (\"2.9.0\", \"tests\"),\n- \"ruff\": (\"0.11.7\", \"tests\"),\n+ \"ruff\": (\"0.12.2\", \"tests\"),\n \"mypy\": (\"1.15\", \"tests\"),\n \"pyamg\": (\"5.0.0\", \"tests\"),\n \"polars\": (\"0.20.30\", \"docs, tests\")," } ], "reviews": [ { "id": 3547457616, "user": "user_34a090906ca4", "state": "COMMENTED", "body": null, "submitted_at": "2025-12-06T11:43:39+00:00" }, { "id": 3547460821, "user": "user_34a090906ca4", "state": "COMMENTED", "body": null, "submitted_at": "2025-12-06T11:46:08+00:00" }, { "id": 3547469245, "user": "user_34a090906ca4", "state": "APPROVED", "body": "No worries [USER_REDACTED], it makes sense to update everything in one go and I didn't know which version to choose (I'd be happy to learn what the heuristic is here, though). I just have two comments on possible future improvements, otherwise LGTM!", "submitted_at": "2025-12-06T11:52:15+00:00" }, { "id": 3547493859, "user": "user_fca2535bcd49", "state": "COMMENTED", "body": null, "submitted_at": "2025-12-06T12:14:10+00:00" }, { "id": 3547511216, "user": "user_fca2535bcd49", "state": "COMMENTED", "body": null, "submitted_at": "2025-12-06T12:27:51+00:00" }, { "id": 3547929741, "user": "user_fca2535bcd49", "state": "COMMENTED", "body": null, "submitted_at": "2025-12-06T17:02:48+00:00" }, { "id": 3591485889, "user": "user_501030d9d7e3", "state": "APPROVED", "body": "That looks good to me, but is this really defining the same version in the CI as in `pre-commit`?\n\nI wonder if because of the `>=` a CI job would use the newest version of ruff available and only go down to until 0.12.2 if there are conflicting dependencies otherwise. (That might not be a big deal since it had worked out before, so this is just a comment).", "submitted_at": "2025-12-18T08:47:14+00:00" } ], "review_comments": [ { "id": 2594765377, "user": "user_34a090906ca4", "body": "We have tests comparing `_min_dependencies` with `readme`/`pyproject.toml`, I wonder if we should also include one to check the `pre-commit-config` for matching versions?", "path": ".pre-commit-config.yaml", "line": 12, "side": "RIGHT", "created_at": "2025-12-06T11:43:39+00:00" }, { "id": 2594767240, "user": "user_34a090906ca4", "body": "Small nit: To make the updating easier, we could add the ruff version here as a variable as well.\n\nIn general, I wonder, since we will also have upper bounds in the next release, do we need to specify more versions than only for ruff in the build environments?", "path": "doc/developers/development_setup.rst", "line": 68, "side": "RIGHT", "created_at": "2025-12-06T11:46:08+00:00" }, { "id": 2594790571, "user": "user_fca2535bcd49", "body": "good point, my personal opinion is that I am fine with the low-tech approach with a comment. I am not super convinced it's worth adding a test, because this affects only contributors not users. And even if the versions did not match it did not cause us any harm, basically we barely noticed..\n\nHaving said this if you think this is a fun thing to try and end up doing a PR and it's not too many lines of code to check the .pre-commit-config.yaml with our min-dependencies, I will happily review it :wink:.", "path": ".pre-commit-config.yaml", "line": 12, "side": "RIGHT", "created_at": "2025-12-06T12:14:10+00:00" }, { "id": 2594803200, "user": "user_fca2535bcd49", "body": "True good point, let's do that!", "path": "doc/developers/development_setup.rst", "line": 68, "side": "RIGHT", "created_at": "2025-12-06T12:27:51+00:00" }, { "id": 2595135041, "user": "user_fca2535bcd49", "body": "Actually looks like you can not use substitutions inside a `.. block` (or any inline markup). I tried and could not make it work.\n\nIt seems like a [limitation of docutils](https://sourceforge.net/p/docutils/feature-requests/53/) and sphinx is based on docutils. A similar thing is https://github.com/[USER_REDACTED]nx-doc/sphinx/issues/2793. There is a work-around with parse-literal or source-read-event in https://github.com/[USER_REDACTED]nx-doc/sphinx/issues/4054#issuecomment-329066548 and below.\n\nMaybe there is a sphinx way to do what we want, not sure but I am not going to spend more time on this :sweat_smile:.", "path": "doc/developers/development_setup.rst", "line": 68, "side": "RIGHT", "created_at": "2025-12-06T17:02:48+00:00" } ], "meta": { "languages": [ "py", "rst", "toml", "yaml" ], "touches_tests": false, "review_state_summary": { "COMMENTED": 5, "APPROVED": 2 }, "meaningful_comment_count": 5, "has_approval": true, "has_changes_requested": false, "total_review_comments": 5 } } { "_id": "5d3fd9deafb80446", "_schema_version": "1.0", "_cleaned_at": "2026-02-12T07:46:51.991980+00:00", "repo": "scikit-learn/scikit-learn", "repo_url": "https://github.com/scikit-learn/scikit-learn", "license_name": "BSD 3-Clause \"New\" or \"Revised\" License", "license_spdx": "BSD-3-Clause", "pr_number": 32846, "title": "Fix make sure enabling `array_api_dispatch=True` does not break any estimator on NumPy inputs", "body": "This is a follow-up to #32840. This should detect most possible silent breaking in future refactoring of helper functions that are used by [NAME_REDACTED] supporting and not supporting code in scikit-learn.\n\n#### AI usage disclosure\n\nI used AI assistance for:\n- [x] Mostly bad code suggestions that I had to re-edit manually to get the code working correctly\n- [ ] Test/benchmark generation\n- [ ] Documentation (including examples)\n- [ ] Research and understanding", "author": "user_5819d17296ee", "created_at": "2025-12-05T15:22:37+00:00", "merged_at": "2026-01-06T14:26:21+00:00", "base_branch": "main", "head_branch": "array-api-dispatch-should-not-break-estimators-on-numpy-inputs", "additions": 142, "deletions": 68, "changed_files": 6, "files": [ { "filename": "doc/whats_new/upcoming_changes/array-api/32846.fix.rst", "status": "added", "additions": 3, "deletions": 0, "changes": 3, "patch": "@@ -0,0 +1,3 @@\n+- Fixed a bug that would cause Cython-based estimators to fail when fit on\n+ NumPy inputs when setting `sklearn.set_config(array_api_dispatch=True)`. By\n+ :user:`[NAME_REDACTED] `." }, { "filename": "sklearn/decomposition/_dict_learning.py", "status": "modified", "additions": 1, "deletions": 1, "changes": 2, "patch": "@@ -1360,7 +1360,7 @@ def fit(self, X, y=None):\n if X.shape[1] != self.dictionary.shape[1]:\n raise ValueError(\n \"Dictionary and X have different numbers of features:\"\n- f\"dictionary.shape: {self.dictionary.shape} X.shape{X.shape}\"\n+ f\"dictionary.shape: {self.dictionary.shape} X.shape: {X.shape}\"\n )\n return self" }, { "filename": "sklearn/utils/_array_api.py", "status": "modified", "additions": 41, "deletions": 9, "changes": 50, "patch": "@@ -23,6 +23,11 @@\n __all__ = [\"xpx\"] # we import xpx here just to re-export it, need this to appease ruff\n \n _NUMPY_NAMESPACE_NAMES = {\"numpy\", \"sklearn.externals.array_api_compat.numpy\"}\n+REMOVE_TYPES_DEFAULT = (\n+ str,\n+ list,\n+ tuple,\n+)\n \n \n def yield_namespaces(include_numpy_namespaces=True):\n@@ -167,7 +172,7 @@ def _single_array_device(array):\n return array.device\n \n \n-def device(*array_list, remove_none=True, remove_types=(str,)):\n+def device(*array_list, remove_none=True, remove_types=REMOVE_TYPES_DEFAULT):\n \"\"\"Hardware device where the array data resides on.\n \n If the hardware device is not the same for all arrays, an error is raised.\n@@ -180,7 +185,7 @@ def device(*array_list, remove_none=True, remove_types=(str,)):\n remove_none : bool, default=True\n Whether to ignore None objects passed in array_list.\n \n- remove_types : tuple or list, default=(str,)\n+ remove_types : tuple or list, default=(str, list, tuple)\n Types to ignore in array_list.\n \n Returns\n@@ -290,7 +295,7 @@ def supported_float_dtypes(xp, device=None):\n return tuple(valid_float_dtypes)\n \n \n-def _remove_non_arrays(*arrays, remove_none=True, remove_types=(str,)):\n+def _remove_non_arrays(*arrays, remove_none=True, remove_types=REMOVE_TYPES_DEFAULT):\n \"\"\"Filter arrays to exclude None and/or specific types.\n \n Sparse arrays are always filtered out.\n@@ -303,7 +308,7 @@ def _remove_non_arrays(*arrays, remove_none=True, remove_types=(str,)):\n remove_none : bool, default=True\n Whether to ignore None objects passed in arrays.\n \n- remove_types : tuple or list, default=(str,)\n+ remove_types : tuple or list, default=(str, list, tuple)\n Types to ignore in the arrays.\n \n Returns\n@@ -328,7 +333,27 @@ def _remove_non_arrays(*arrays, remove_none=True, remove_types=(str,)):\n return filtered_arrays\n \n \n-def get_namespace(*arrays, remove_none=True, remove_types=(str,), xp=None):\n+def _unwrap_memoryviewslices(*arrays):\n+ # Since _cyutility._memoryviewslice is an implementation detail of the\n+ # Cython runtime, we would rather not introduce a possibly brittle\n+ # import statement to run `isinstance`-based filtering, hence the\n+ # attribute-based type inspection.\n+ unwrapped = []\n+ for a in arrays:\n+ a_type = type(a)\n+ if (\n+ a_type.__module__ == \"_cyutility\"\n+ and a_type.__name__ == \"_memoryviewslice\"\n+ and hasattr(a, \"base\")\n+ ):\n+ a = a.base\n+ unwrapped.append(a)\n+ return unwrapped\n+\n+\n+def get_namespace(\n+ *arrays, remove_none=True, remove_types=REMOVE_TYPES_DEFAULT, xp=None\n+):\n \"\"\"Get namespace of arrays.\n \n Introspect `arrays` arguments and return their common Array API compatible\n@@ -364,7 +389,7 @@ def get_namespace(*arrays, remove_none=True, remove_types=(str,), xp=None):\n remove_none : bool, default=True\n Whether to ignore None objects passed in arrays.\n \n- remove_types : tuple or list, default=(str,)\n+ remove_types : tuple or list, default=(str, list, tuple)\n Types to ignore in the arrays.\n \n xp : module, default=None\n@@ -399,12 +424,19 @@ def get_namespace(*arrays, remove_none=True, remove_types=(str,), xp=None):\n remove_types=remove_types,\n )\n \n+ # get_namespace can be called by [NAME_REDACTED] used both in\n+ # array API compatible code and non-array API Cython related code. To\n+ # support the latter on NumPy inputs without raising a TypeError, we\n+ # unwrap potential Cython memoryview slices here.\n+ arrays = _unwrap_memoryviewslices(*arrays)\n+\n if not arrays:\n return np_compat, False\n \n _check_array_api_dispatch(array_api_dispatch)\n \n- namespace, is_array_api_compliant = array_api_compat.get_namespace(*arrays), True\n+ namespace = array_api_compat.get_namespace(*arrays)\n+ is_array_api_compliant = True\n \n if namespace.__name__ == \"array_api_strict\" and hasattr(\n namespace, \"set_array_api_strict_flags\"\n@@ -415,7 +447,7 @@ def get_namespace(*arrays, remove_none=True, remove_types=(str,), xp=None):\n \n \n def get_namespace_and_device(\n- *array_list, remove_none=True, remove_types=(str,), xp=None\n+ *array_list, remove_none=True, remove_types=REMOVE_TYPES_DEFAULT, xp=None\n ):\n \"\"\"Combination into one single function of `get_namespace` and `device`.\n \n@@ -425,7 +457,7 @@ def get_namespace_and_device(\n Array objects.\n remove_none : bool, default=True\n Whether to ignore None objects passed in arrays.\n- remove_types : tuple or list, default=(str,)\n+ remove_types : tuple or list, default=(str, list, tuple)\n Types to ignore in the arrays.\n xp : module, default=None\n Precomputed array namespace module. When passed, typically from a caller" }, { "filename": "sklearn/utils/_test_common/instance_generator.py", "status": "modified", "additions": 20, "deletions": 4, "changes": 24, "patch": "@@ -46,7 +46,10 @@\n SparsePCA,\n TruncatedSVD,\n )\n-from sklearn.discriminant_analysis import LinearDiscriminantAnalysis\n+from sklearn.discriminant_analysis import (\n+ LinearDiscriminantAnalysis,\n+ QuadraticDiscriminantAnalysis,\n+)\n from sklearn.dummy import DummyClassifier\n from sklearn.ensemble import (\n AdaBoostClassifier,\n@@ -79,6 +82,7 @@\n SequentialFeatureSelector,\n )\n from sklearn.frozen import FrozenEstimator\n+from sklearn.impute import SimpleImputer\n from sklearn.kernel_approximation import (\n Nystroem,\n PolynomialCountSketch,\n@@ -559,11 +563,16 @@\n dict(solver=\"lbfgs\"),\n ],\n },\n- GaussianMixture: {\"check_dict_unchanged\": dict(max_iter=5, n_init=2)},\n+ GaussianMixture: {\n+ \"check_dict_unchanged\": dict(max_iter=5, n_init=2),\n+ \"check_array_api_input\": dict(\n+ max_iter=5, n_init=2, init_params=\"random_from_data\"\n+ ),\n+ },\n GaussianRandomProjection: {\"check_dict_unchanged\": dict(n_components=1)},\n+ GraphicalLasso: {\"check_array_api_input\": dict(max_iter=5, alpha=1.0)},\n IncrementalPCA: {\"check_dict_unchanged\": dict(batch_size=10, n_components=1)},\n Isomap: {\"check_dict_unchanged\": dict(n_components=1)},\n- KMeans: {\"check_dict_unchanged\": dict(max_iter=5, n_clusters=1, n_init=2)},\n # TODO(1.9) simplify when averaged_inverted_cdf is the default\n KBinsDiscretizer: {\n \"check_sample_weight_equivalence_on_dense_data\": [\n@@ -595,7 +604,11 @@\n strategy=\"quantile\", quantile_method=\"averaged_inverted_cdf\"\n ),\n },\n- KernelPCA: {\"check_dict_unchanged\": dict(n_components=1)},\n+ KernelPCA: {\n+ \"check_dict_unchanged\": dict(n_components=1),\n+ \"check_array_api_input\": dict(fit_inverse_transform=True),\n+ },\n+ KMeans: {\"check_dict_unchanged\": dict(max_iter=5, n_clusters=1, n_init=2)},\n LassoLars: {\"check_non_transformer_estimators_n_iter\": dict(alpha=0.0)},\n LatentDirichletAllocation: {\n \"check_dict_unchanged\": dict(batch_size=10, max_iter=5, n_components=1)\n@@ -693,6 +706,7 @@\n dict(solver=\"highs-ipm\"),\n ],\n },\n+ QuadraticDiscriminantAnalysis: {\"check_array_api_input\": dict(reg_param=1.0)},\n RBFSampler: {\"check_dict_unchanged\": dict(n_components=1)},\n Ridge: {\n \"check_sample_weight_equivalence_on_dense_data\": [\n@@ -720,7 +734,9 @@\n ],\n },\n SkewedChi2Sampler: {\"check_dict_unchanged\": dict(n_components=1)},\n+ SimpleImputer: {\"check_array_api_input\": dict(add_indicator=True)},\n SparseCoder: {\n+ \"check_array_api_input\": dict(dictionary=rng.normal(size=(5, 10))),\n \"check_estimators_dtypes\": dict(dictionary=rng.normal(size=(5, 5))),\n \"check_dtype_object\": dict(dictionary=rng.normal(size=(5, 10))),\n \"check_transformers_unfitted_stateless\": dict(" }, { "filename": "sklearn/utils/estimator_checks.py", "status": "modified", "additions": 71, "deletions": 47, "changes": 118, "patch": "@@ -196,9 +196,11 @@ def _yield_checks(estimator):\n yield check_estimators_pickle\n yield partial(check_estimators_pickle, readonly_memmap=True)\n \n- if tags.array_api_support:\n- for check in _yield_array_api_checks(estimator):\n- yield check\n+ for check in _yield_array_api_checks(\n+ estimator,\n+ only_numpy=not tags.array_api_support,\n+ ):\n+ yield check\n \n yield check_f_contiguous_array_estimator\n \n@@ -336,18 +338,30 @@ def _yield_outliers_checks(estimator):\n yield check_non_transformer_estimators_n_iter\n \n \n-def _yield_array_api_checks(estimator):\n- for (\n- array_namespace,\n- device,\n- dtype_name,\n- ) in yield_namespace_device_dtype_combinations():\n+def _yield_array_api_checks(estimator, only_numpy=False):\n+ if only_numpy:\n+ # Enabling array API dispatch and using NumPy inputs should not\n+ # change results, even if the estimator does not explicitly support\n+ # array API.\n yield partial(\n check_array_api_input,\n- array_namespace=array_namespace,\n- dtype_name=dtype_name,\n- device=device,\n+ array_namespace=\"numpy\",\n+ expect_only_array_outputs=False,\n )\n+ else:\n+ # These extended checks should pass for all estimators that declare\n+ # array API support in their tags.\n+ for (\n+ array_namespace,\n+ device,\n+ dtype_name,\n+ ) in yield_namespace_device_dtype_combinations():\n+ yield partial(\n+ check_array_api_input,\n+ array_namespace=array_namespace,\n+ dtype_name=dtype_name,\n+ device=device,\n+ )\n \n \n def _yield_all_checks(estimator, legacy: bool):\n@@ -1048,6 +1062,7 @@ def check_array_api_input(\n dtype_name=\"float64\",\n check_values=False,\n check_sample_weight=False,\n+ expect_only_array_outputs=True,\n ):\n \"\"\"Check that the estimator can work consistently with the Array API\n \n@@ -1057,17 +1072,25 @@ def check_array_api_input(\n When check_values is True, it also checks that calling the estimator on the\n array_api Array gives the same results as ndarrays.\n \n- When sample_weight is True, dummy sample weights are passed to the fit call.\n+ When check_sample_weight is True, dummy sample weights are passed to the\n+ fit call.\n+\n+ When expect_only_array_outputs is False, the check is looser: in particular\n+ it accepts non-array outputs such as sparse data structures. This is\n+ useful to test that enabling array API dispatch does not change the\n+ behavior of any estimator fed with NumPy inputs, even for estimators that\n+ do not support array API.\n \"\"\"\n xp = _array_api_for_tests(array_namespace, device)\n \n- X, y = make_classification(random_state=42)\n+ X, y = make_classification(n_samples=30, n_features=10, random_state=42)\n X = X.astype(dtype_name, copy=False)\n \n X = _enforce_estimator_tags_X(estimator_orig, X)\n y = _enforce_estimator_tags_y(estimator_orig, y)\n \n est = clone(estimator_orig)\n+ set_random_state(est)\n \n X_xp = xp.asarray(X, device=device)\n y_xp = xp.asarray(y, device=device)\n@@ -1193,47 +1216,48 @@ def check_array_api_input(\n f\"got {result_ns}.\"\n )\n \n- with config_context(array_api_dispatch=True):\n- assert array_device(result_xp) == array_device(X_xp)\n-\n- result_xp_np = _convert_to_numpy(result_xp, xp=xp)\n+ if expect_only_array_outputs:\n+ with config_context(array_api_dispatch=True):\n+ assert array_device(result_xp) == array_device(X_xp)\n \n- if check_values:\n- assert_allclose(\n- result,\n- result_xp_np,\n- err_msg=f\"{method} did not the return the same result\",\n- atol=_atol_for_type(X.dtype),\n- )\n- else:\n- if hasattr(result, \"shape\"):\n+ result_xp_np = _convert_to_numpy(result_xp, xp=xp)\n+ if check_values:\n+ assert_allclose(\n+ result,\n+ result_xp_np,\n+ err_msg=f\"{method} did not the return the same result\",\n+ atol=_atol_for_type(X.dtype),\n+ )\n+ elif hasattr(result, \"shape\"):\n assert result.shape == result_xp_np.shape\n assert result.dtype == result_xp_np.dtype\n \n if method_name == \"transform\" and hasattr(est, \"inverse_transform\"):\n inverse_result = est.inverse_transform(result)\n with config_context(array_api_dispatch=True):\n- invese_result_xp = est_xp.inverse_transform(result_xp)\n- inverse_result_ns = get_namespace(invese_result_xp)[0].__name__\n- assert inverse_result_ns == input_ns, (\n- \"'inverse_transform' output is in wrong namespace, expected\"\n- f\" {input_ns}, got {inverse_result_ns}.\"\n- )\n-\n- with config_context(array_api_dispatch=True):\n- assert array_device(invese_result_xp) == array_device(X_xp)\n-\n- invese_result_xp_np = _convert_to_numpy(invese_result_xp, xp=xp)\n- if check_values:\n- assert_allclose(\n- inverse_result,\n- invese_result_xp_np,\n- err_msg=\"inverse_transform did not the return the same result\",\n- atol=_atol_for_type(X.dtype),\n+ inverse_result_xp = est_xp.inverse_transform(result_xp)\n+\n+ if expect_only_array_outputs:\n+ with config_context(array_api_dispatch=True):\n+ inverse_result_ns = get_namespace(inverse_result_xp)[0].__name__\n+ assert inverse_result_ns == input_ns, (\n+ \"'inverse_transform' output is in wrong namespace, expected\"\n+ f\" {input_ns}, got {inverse_result_ns}.\"\n )\n- else:\n- assert inverse_result.shape == invese_result_xp_np.shape\n- assert inverse_result.dtype == invese_result_xp_np.dtype\n+ with config_context(array_api_dispatch=True):\n+ assert array_device(result_xp) == array_device(X_xp)\n+\n+ inverse_result_xp_np = _convert_to_numpy(inverse_result_xp, xp=xp)\n+ if check_values:\n+ assert_allclose(\n+ inverse_result,\n+ inverse_result_xp_np,\n+ err_msg=\"inverse_transform did not the return the same result\",\n+ atol=_atol_for_type(X.dtype),\n+ )\n+ elif hasattr(result, \"shape\"):\n+ assert inverse_result.shape == inverse_result_xp_np.shape\n+ assert inverse_result.dtype == inverse_result_xp_np.dtype\n \n \n def check_array_api_input_and_values(" }, { "filename": "sklearn/utils/tests/test_array_api.py", "status": "modified", "additions": 6, "deletions": 7, "changes": 13, "patch": "@@ -50,8 +50,8 @@\n from sklearn.utils.fixes import _IS_32BIT, CSR_CONTAINERS, np_version, parse_version\n \n \n-[USER_REDACTED].mark.parametrize(\"X\", [numpy.asarray([1, 2, 3]), [1, 2, 3]])\n-def test_get_namespace_ndarray_default(X):\n+[USER_REDACTED].mark.parametrize(\"X\", [numpy.asarray([1, 2, 3]), [1, 2, 3], (1, 2, 3)])\n+def test_get_namespace_ndarray_or_similar_default(X):\n \"\"\"Check that get_namespace returns NumPy wrapper\"\"\"\n xp_out, is_array_api_compliant = get_namespace(X)\n assert xp_out is np_compat\n@@ -71,14 +71,13 @@ def test_get_namespace_ndarray_creation_device():\n \n \n [USER_REDACTED]_if_array_api_compat_not_configured\n-def test_get_namespace_ndarray_with_dispatch():\n+[USER_REDACTED].mark.parametrize(\"X\", [numpy.asarray([1, 2, 3]), [1, 2, 3], (1, 2, 3)])\n+def test_get_namespace_ndarray_or_similar_default_with_dispatch(X):\n \"\"\"Test get_namespace on NumPy ndarrays.\"\"\"\n \n- X_np = numpy.asarray([[1, 2, 3]])\n-\n with config_context(array_api_dispatch=True):\n- xp_out, is_array_api_compliant = get_namespace(X_np)\n- assert is_array_api_compliant\n+ xp_out, is_array_api_compliant = get_namespace(X)\n+ assert is_array_api_compliant == isinstance(X, numpy.ndarray)\n \n # In the future, NumPy should become API compliant library and we should have\n # assert xp_out is numpy" } ], "reviews": [ { "id": 3545237883, "user": "user_5819d17296ee", "state": "COMMENTED", "body": null, "submitted_at": "2025-12-05T15:24:35+00:00" }, { "id": 3545309739, "user": "user_5819d17296ee", "state": "COMMENTED", "body": null, "submitted_at": "2025-12-05T15:42:06+00:00" }, { "id": 3545539605, "user": "user_5819d17296ee", "state": "COMMENTED", "body": null, "submitted_at": "2025-12-05T16:42:45+00:00" }, { "id": 3545564693, "user": "user_5819d17296ee", "state": "COMMENTED", "body": null, "submitted_at": "2025-12-05T16:49:14+00:00" }, { "id": 3555494167, "user": "user_bf0b6c7acb9c", "state": "COMMENTED", "body": null, "submitted_at": "2025-12-09T05:14:08+00:00" }, { "id": 3557517872, "user": "user_3c90b5520ec5", "state": "COMMENTED", "body": "Thank you for the PR [USER_REDACTED]", "submitted_at": "2025-12-09T13:48:08+00:00" }, { "id": 3557790062, "user": "user_5819d17296ee", "state": "COMMENTED", "body": null, "submitted_at": "2025-12-09T14:34:45+00:00" }, { "id": 3557844499, "user": "user_5819d17296ee", "state": "COMMENTED", "body": null, "submitted_at": "2025-12-09T14:45:26+00:00" }, { "id": 3557847226, "user": "user_5819d17296ee", "state": "COMMENTED", "body": null, "submitted_at": "2025-12-09T14:46:01+00:00" }, { "id": 3557916185, "user": "user_5819d17296ee", "state": "COMMENTED", "body": null, "submitted_at": "2025-12-09T15:00:01+00:00" }, { "id": 3558333294, "user": "user_3c90b5520ec5", "state": "COMMENTED", "body": null, "submitted_at": "2025-12-09T16:12:38+00:00" }, { "id": 3558402826, "user": "user_3c90b5520ec5", "state": "APPROVED", "body": "LGTM. Thank you [USER_REDACTED]", "submitted_at": "2025-12-09T16:27:55+00:00" }, { "id": 3566903628, "user": "user_d16337ec046b", "state": "APPROVED", "body": "LGTM, thanks for the other fixes here. Nits only", "submitted_at": "2025-12-12T04:22:16+00:00" }, { "id": 3576421429, "user": "user_fca2535bcd49", "state": "COMMENTED", "body": null, "submitted_at": "2025-12-15T05:24:34+00:00" }, { "id": 3610540268, "user": "user_5819d17296ee", "state": "COMMENTED", "body": null, "submitted_at": "2025-12-24T10:07:40+00:00" }, { "id": 3610542646, "user": "user_5819d17296ee", "state": "COMMENTED", "body": null, "submitted_at": "2025-12-24T10:08:50+00:00" }, { "id": 3610610946, "user": "user_5819d17296ee", "state": "COMMENTED", "body": null, "submitted_at": "2025-12-24T10:35:29+00:00" }, { "id": 3611692958, "user": "user_d16337ec046b", "state": "COMMENTED", "body": null, "submitted_at": "2025-12-25T00:36:22+00:00" }, { "id": 3630913158, "user": "user_d5b9cb906259", "state": "COMMENTED", "body": null, "submitted_at": "2026-01-06T13:32:32+00:00" }, { "id": 3630927897, "user": "user_d5b9cb906259", "state": "APPROVED", "body": "One tweak to a comment, for me it made it easier to understand. Otherwise LGTM, let's merge", "submitted_at": "2026-01-06T13:36:14+00:00" }, { "id": 3630943746, "user": "user_3c90b5520ec5", "state": "COMMENTED", "body": null, "submitted_at": "2026-01-06T13:41:26+00:00" } ], "review_comments": [ { "id": 2593067894, "user": "user_5819d17296ee", "body": "Note to reviewers: I considered adding `_cyutility._memoryviewslice` to the list of `removed_types` but since it's a private internal detail of Cython, I thought it would be too brittle and went for a more direct handling of unexpected types in `get_namespace` inputs.", "path": "sklearn/utils/_array_api.py", "line": null, "side": "RIGHT", "created_at": "2025-12-05T15:24:35+00:00" }, { "id": 2593121669, "user": "user_5819d17296ee", "body": "Actually, the try/except approach is conflicting with our test that except `TypeError` on mixed namespaces. Let me iterate.", "path": "sklearn/utils/_array_api.py", "line": null, "side": "RIGHT", "created_at": "2025-12-05T15:42:06+00:00" }, { "id": 2593304734, "user": "user_5819d17296ee", "body": "I think there are around 15 estimators that would have failed the updated common test. However, I would need to add the common test to the 1.7.X branch to know the list of estimators that are fixed by [NAME_REDACTED] to 1.8. I am a bit lazy to do that.", "path": "doc/whats_new/upcoming_changes/array-api/32846.fix.rst", "line": 3, "side": "RIGHT", "created_at": "2025-12-05T16:42:45+00:00" }, { "id": 2593323101, "user": "user_5819d17296ee", "body": "I think we could make the motivation behind this hackery a bit more explicit with an inline comment. Let's wait for the CI to complete before accepting this suggestion.\n\n```suggestion\ndef _unwrap_memoryviewslices(*arrays):\n # Since _cyutility._memoryviewslice is an implementation detail of the\n # Cython runtime, we would rather not introduce a possibly brittle\n # import statement to run `isinstance`-based filtering, hence the\n # attribute-based type inspection.\n```", "path": "sklearn/utils/_array_api.py", "line": 336, "side": "RIGHT", "created_at": "2025-12-05T16:49:13+00:00" }, { "id": 2601123066, "user": "user_bf0b6c7acb9c", "body": "I've added the tests to the `1.7.X` branch. These are the failures:\n\n
      \n[NAME_REDACTED]\n\n```bash\nFAILED sklearn/decomposition/tests/test_dict_learning.py::test_max_iter - Failed: DID NOT WARN. No warnings of type (,) were emitted.\n Emitted warnings: [].\n\nFAILED sklearn/decomposition/tests/test_dict_learning.py::test_sparse_coder_estimator - AttributeError: property 'n_features_in_' of 'SparseCoder' object has no setter\n\nFAILED sklearn/decomposition/tests/test_dict_learning.py::test_sparse_coder_parallel_mmap - AttributeError: property 'n_features_in_' of 'SparseCoder' object has no setter\n\nFAILED sklearn/decomposition/tests/test_dict_learning.py::test_sparse_coder_common_transformer - AttributeError: property 'n_features_in_' of 'SparseCoder' object has no setter\n\nFAILED sklearn/decomposition/tests/test_dict_learning.py::test_get_feature_names_out[SparseCoder] - AttributeError: property 'n_features_in_' of 'SparseCoder' object has no setter\n\nFAILED sklearn/tests/test_common.py::test_estimators[GenericUnivariateSelect()-check_array_api_input(array_namespace=numpy,expect_only_array_outputs=False)] - ValueError: X has a different shape than during fitting.\n\nFAILED sklearn/tests/test_common.py::test_estimators[RFE(estimator=LogisticRegression(C=1))-check_array_api_input(array_namespace=numpy,expect_only_array_outputs=False)] - ValueError: X has 10 features, but LogisticRegression is expecting 5 features as input.\n\nFAILED sklearn/tests/test_common.py::test_estimators[RFECV(cv=3,estimator=LogisticRegression(C=1))-check_array_api_input(array_namespace=numpy,expect_only_array_outputs=False)] - ValueError: X has a different shape than during fitting.\n\nFAILED sklearn/tests/test_common.py::test_estimators[SelectFdr(alpha=0.5)-check_array_api_input(array_namespace=numpy,expect_only_array_outputs=False)] - ValueError: X has a different shape than during fitting.\n\nFAILED sklearn/tests/test_common.py::test_estimators[SelectFpr()-check_array_api_input(array_namespace=numpy,expect_only_array_outputs=False)] - ValueError: X has a different shape than during fitting.\n\nFAILED sklearn/tests/test_common.py::test_estimators[SelectFromModel(estimator=SGDRegressor(random_state=0))-check_array_api_input(array_namespace=numpy,expect_only_array_outputs=False)] - ValueError: X has a different shape than during fitting.\n\nFAILED sklearn/tests/test_common.py::test_estimators[SelectFwe()-check_array_api_input(array_namespace=numpy,expect_only_array_outputs=False)] - ValueError: X has a different shape than during fitting.\n\nFAILED sklearn/tests/test_common.py::test_estimators[SelectKBest(k=1)-check_array_api_input(array_namespace=numpy,expect_only_array_outputs=False)] - ValueError: X has a different shape than during fitting.\n\nFAILED sklearn/tests/test_common.py::test_estimators[SelectPercentile()-check_array_api_input(array_namespace=numpy,expect_only_array_outputs=False)] - ValueError: X has a different shape than during fitting.\n\nFAILED sklearn/tests/test_common.py::test_estimators[SequentialFeatureSelector(cv=3,estimator=LogisticRegression(C=1))-check_array_api_input(array_namespace=numpy,expect_only_array_outputs=False)] - ValueError: X has a different shape than during fitting.\n\nFAILED sklearn/tests/test_common.py::test_estimators[TransformedTargetRegressor()-check_array_api_input(array_namespace=numpy,expect_only_array_outputs=False)] - TypeError: int() argument must be a string, a bytes-like object or a real number, not 'slice'\n\nFAILED sklearn/tests/test_docstring_parameters.py::test_fit_docstring_attributes[SparseCoder-SparseCoder] - AttributeError: property 'n_features_in_' of 'SparseCoder' object has no setter\n\nFAILED sklearn/utils/tests/test_estimator_checks.py::test_estimator_with_set_output - TypeError: DataFrame is not a supported array type\n```\n
      \n\nI didn't check every random seed. My local branch is [here](https://github.com/[USER_REDACTED]n/scikit-learn/tree/1.7.X_32846).\n\nDoes this help?", "path": "doc/whats_new/upcoming_changes/array-api/32846.fix.rst", "line": 3, "side": "RIGHT", "created_at": "2025-12-09T05:14:08+00:00" }, { "id": 2602717371, "user": "user_3c90b5520ec5", "body": "```suggestion\n # unwrap potential Cython memoryview slices here.\n```", "path": "sklearn/utils/_array_api.py", "line": null, "side": "RIGHT", "created_at": "2025-12-09T13:38:48+00:00" }, { "id": 2602751949, "user": "user_3c90b5520ec5", "body": "How come the above checks are present within\n```\nif expect_only_array_outputs:\n```\nBut these aren't?", "path": "sklearn/utils/estimator_checks.py", "line": null, "side": "RIGHT", "created_at": "2025-12-09T13:46:46+00:00" }, { "id": 2602938023, "user": "user_5819d17296ee", "body": "Thanks!\n\n> Does this help?\n\nI am not sure. I have the feeling that many of those failures are a bit unrelated.\n\nIf people don't mind, I think we can live with a terse changelog entry for this fix.", "path": "doc/whats_new/upcoming_changes/array-api/32846.fix.rst", "line": 3, "side": "RIGHT", "created_at": "2025-12-09T14:34:45+00:00" }, { "id": 2602981393, "user": "user_5819d17296ee", "body": "I thought about it and I don't think we need to put this assertion under the `if expect_only_array_outputs` condition. Let's consider the following patter:\n\n```python\nX_trans = est.fit_transform(X_input, y_input)\nX_inverse = est.inverse_transform(X_trans)\n```\n\nIn this test, `X_input` is always an array, but `X_trans` could be a sparse matrix (hence the need for `expect_only_array_outputs` when anything about `X_trans`).\n\nSince `X_input` is always an array in this test, I think we can assume that `X_inverse` has always a similar dense container because it mathematically lives in the same space as `X_input`, even if `X_trans` requires a sparse datastructure (because it leaves in a higher dimensional and sparse representation space).\n\nAlso: the CI is green, so I guess this assumption is correct empirically so far in scikit-learn.\n\nBut since estimator checks can be used by [NAME_REDACTED], maybe we don't want to impose this somewhat arbitrary expected rule to hold for other libraries?", "path": "sklearn/utils/estimator_checks.py", "line": null, "side": "RIGHT", "created_at": "2025-12-09T14:45:26+00:00" }, { "id": 2602983516, "user": "user_5819d17296ee", "body": "Let me update the PR to relax this.", "path": "sklearn/utils/estimator_checks.py", "line": null, "side": "RIGHT", "created_at": "2025-12-09T14:46:01+00:00" }, { "id": 2603037751, "user": "user_5819d17296ee", "body": "Done in bb4702b.", "path": "sklearn/utils/estimator_checks.py", "line": null, "side": "RIGHT", "created_at": "2025-12-09T15:00:01+00:00" }, { "id": 2603352705, "user": "user_3c90b5520ec5", "body": "I think the change log seems okay.", "path": "doc/whats_new/upcoming_changes/array-api/32846.fix.rst", "line": 3, "side": "RIGHT", "created_at": "2025-12-09T16:12:38+00:00" }, { "id": 2610166032, "user": "user_d16337ec046b", "body": "```suggestion\n remove_types : tuple or list, default=(str, list, tuple)\n```", "path": "sklearn/utils/_array_api.py", "line": null, "side": "RIGHT", "created_at": "2025-12-11T11:08:02+00:00" }, { "id": 2610180015, "user": "user_d16337ec046b", "body": "```suggestion\n remove_types : tuple or list, default=(str, list, tuple)\n```", "path": "sklearn/utils/_array_api.py", "line": null, "side": "RIGHT", "created_at": "2025-12-11T11:12:46+00:00" }, { "id": 2610185284, "user": "user_d16337ec046b", "body": "```suggestion\n remove_types : tuple or list, default=(str, list, tuple)\n```", "path": "sklearn/utils/_array_api.py", "line": null, "side": "RIGHT", "created_at": "2025-12-11T11:14:36+00:00" }, { "id": 2612849505, "user": "user_d16337ec046b", "body": "nit, to match test above\n```suggestion\ndef test_get_namespace_ndarray_or_similar_default_with_dispatch(X):\n```", "path": "sklearn/utils/tests/test_array_api.py", "line": null, "side": "RIGHT", "created_at": "2025-12-12T04:05:12+00:00" }, { "id": 2612876511, "user": "user_d16337ec046b", "body": "Could you expand on this? I was confused just reading this, but https://github.com/[USER_REDACTED]n/scikit-learn/pull/32846/changes#r2602981393 cleared it up for me.", "path": "sklearn/utils/estimator_checks.py", "line": null, "side": "RIGHT", "created_at": "2025-12-12T04:21:51+00:00" }, { "id": 2617990488, "user": "user_fca2535bcd49", "body": "I think you need a `config_context` here otherwise this assert statement will always pass, checking that None == None. This was noted some time ago by [NAME_REDACTED]://github.com/scikit-learn/scikit-learn/pull/31814.\n\nMaybe we should do something about it because it's easy to fall into this trap. One potential idea was to add an `assert_same_device` that uses `array_api_compat.device` and does not depend on `config_context(array_api_dispatch=True)` (and a similar assert function like `assert_same_namespace`). Also maybe it would be nice to have a better name than device for our config_context-dependent device function since I find the clash with `array_api_compat.device` a tiny bit confusing.\n\n```suggestion\n with config_context(array_api_dispatch=True):\n assert array_device(result_xp) == array_device(X_xp)\n```", "path": "sklearn/utils/estimator_checks.py", "line": null, "side": "RIGHT", "created_at": "2025-12-15T05:24:34+00:00" }, { "id": 2645330618, "user": "user_5819d17296ee", "body": "```suggestion\n When expect_only_array_outputs is False, the check is looser: in particular\n it accepts non-array outputs such as sparse data structures. This is\n useful to test that enabling array API dispatch does not change the \n behavior of any estimator fed with NumPy inputs, even for estimators that\n do not support array API.\n```", "path": "sklearn/utils/estimator_checks.py", "line": null, "side": "RIGHT", "created_at": "2025-12-24T10:07:40+00:00" }, { "id": 2645332845, "user": "user_5819d17296ee", "body": "I pushed 969f06a as an attempt to clarify this.", "path": "sklearn/utils/estimator_checks.py", "line": null, "side": "RIGHT", "created_at": "2025-12-24T10:08:50+00:00" }, { "id": 2645385387, "user": "user_5819d17296ee", "body": "```suggestion\n useful to test that enabling array API dispatch does not change the\n```", "path": "sklearn/utils/estimator_checks.py", "line": null, "side": "RIGHT", "created_at": "2025-12-24T10:35:28+00:00" }, { "id": 2646380312, "user": "user_d16337ec046b", "body": "Thanks! Feel free to merge when you're ready!", "path": "sklearn/utils/estimator_checks.py", "line": null, "side": "RIGHT", "created_at": "2025-12-25T00:36:22+00:00" }, { "id": 2664940319, "user": "user_d5b9cb906259", "body": "```suggestion\n # Enabling array API dispatch and using NumPy inputs should not\n # change results, even if the estimator does not explicitly support\n # array API.\n```", "path": "sklearn/utils/estimator_checks.py", "line": null, "side": "RIGHT", "created_at": "2026-01-06T13:32:31+00:00" }, { "id": 2664966649, "user": "user_3c90b5520ec5", "body": "I think the suggested changes in the comment make sense.", "path": "sklearn/utils/estimator_checks.py", "line": null, "side": "RIGHT", "created_at": "2026-01-06T13:41:25+00:00" } ], "meta": { "languages": [ "py", "rst" ], "touches_tests": true, "review_state_summary": { "COMMENTED": 18, "APPROVED": 3 }, "meaningful_comment_count": 24, "has_approval": true, "has_changes_requested": false, "total_review_comments": 24 } } { "_id": "d55e38339b9d54c1", "_schema_version": "1.0", "_cleaned_at": "2026-02-12T07:46:51.991980+00:00", "repo": "scikit-learn/scikit-learn", "repo_url": "https://github.com/scikit-learn/scikit-learn", "license_name": "BSD 3-Clause \"New\" or \"Revised\" License", "license_spdx": "BSD-3-Clause", "pr_number": 32845, "title": "ENH/FIX: make coordinate descent solver converge for ridge regression", "body": "#### [NAME_REDACTED]/PRs\nWarnings for `alpha=0` / `l1_ratio=0` where introduced in #620. A note that Enet with dual gap as stopping criterion does not converge was mentioned in https://github.com/[USER_REDACTED]n/scikit-learn/pull/19620#issue-822947581.\n\n#### What does this implement/fix? Explain your changes.\nThis PR makes the coordinate descent solver of `Lasso` and `ElasticNet` etc. converge for Ridge regression.\n\n##### [NAME_REDACTED] prevents convergence of the CD solver in the main branch is that the dual gap is not valid for `alpha=0` / `l1_ratio=0`. Fortunately, there is an alternative dual gap available, see #22836.\n\n#### Any other comments?\n- There are some surprising results, see the new `test_enet_ols_consistency`.\n- `test_coordinate_descent.py` now passes without warnings (`pytest -We sklearn/linear_model/tests/test_coordinate_descent.py`).", "author": "user_22bafe4fe1a9", "created_at": "2025-12-05T14:49:52+00:00", "merged_at": "2025-12-31T14:44:08+00:00", "base_branch": "main", "head_branch": "cd_gap4ridge", "additions": 376, "deletions": 178, "changed_files": 5, "files": [ { "filename": "doc/whats_new/upcoming_changes/sklearn.linear_model/32845.enhancement.rst", "status": "added", "additions": 7, "deletions": 0, "changes": 7, "patch": "@@ -0,0 +1,7 @@\n+- :class:`linear_model.ElasticNet`, :class:`linear_model.ElasticNetCV` and\n+ :func:`linear_model.enet_path`\n+ now are able to fit Ridge regression, i.e. setting `l1_ratio=0`.\n+ Before this PR, the stopping criterion was a formulation of the dual gap that breaks\n+ down for `l1_ratio=0`. Now, an alternative dual gap formulation is used for this\n+ setting. This reduces the noise of raised warnings.\n+ By :user:`[NAME_REDACTED] `." }, { "filename": "sklearn/linear_model/_cd_fast.pyx", "status": "modified", "additions": 275, "deletions": 134, "changes": 409, "patch": "@@ -98,6 +98,30 @@ message_ridge = (\n )\n \n \n+cdef inline floating dual_gap_formulation_A(\n+ floating alpha, # L1 penalty\n+ floating beta, # L1 penalty\n+ floating w_l1_norm,\n+ floating w_l2_norm2,\n+ floating R_norm2, # R @ R\n+ floating Ry, # R @ y\n+ floating dual_norm_XtA,\n+) noexcept nogil:\n+ \"\"\"Compute dual gap according to formulation A.\"\"\"\n+ cdef floating gap, primal, dual\n+ cdef floating scale # Scaling factor to achieve dual feasible point.\n+\n+ primal = 0.5 * (R_norm2 + beta * w_l2_norm2) + alpha * w_l1_norm\n+\n+ if (dual_norm_XtA > alpha):\n+ scale = alpha / dual_norm_XtA\n+ else:\n+ scale = 1.0\n+ dual = -0.5 * (scale ** 2) * (R_norm2 + beta * w_l2_norm2) + scale * Ry\n+ gap = primal - dual\n+ return gap\n+\n+\n cdef (floating, floating) gap_enet(\n int n_samples,\n int n_features,\n@@ -110,47 +134,71 @@ cdef (floating, floating) gap_enet(\n floating[::1] XtA, # XtA = X.T @ R - beta * w is calculated inplace\n bint positive,\n ) noexcept nogil:\n- \"\"\"Compute dual gap for use in enet_coordinate_descent.\"\"\"\n+ \"\"\"Compute dual gap for use in enet_coordinate_descent.\n+\n+ alpha > 0: formulation A of the duality gap\n+ alpha = 0 & beta > 0: formulation B of the duality gap\n+ alpha = beta = 0: OLS first order condition (=gradient)\n+ \"\"\"\n cdef floating gap = 0.0\n cdef floating dual_norm_XtA\n cdef floating R_norm2\n- cdef floating w_norm2 = 0.0\n- cdef floating l1_norm\n- cdef floating A_norm2\n- cdef floating const_\n+ cdef floating Ry\n+ cdef floating w_l1_norm\n+ cdef floating w_l2_norm2 = 0.0\n+\n+ # w_l2_norm2 = w @ w\n+ if beta > 0:\n+ w_l2_norm2 = _dot(n_features, &w[0], 1, &w[0], 1)\n+ # R_norm2 = R @ R\n+ R_norm2 = _dot(n_samples, &R[0], 1, &R[0], 1)\n+ # Ry = R @ y\n+ if not (alpha == 0 and beta == 0):\n+ Ry = _dot(n_samples, &R[0], 1, &y[0], 1)\n+\n+ if alpha == 0:\n+ # XtA = X.T @ R\n+ _gemv(\n+ ColMajor, Trans, n_samples, n_features, 1.0, &X[0, 0],\n+ n_samples, &R[0], 1, 0, &XtA[0], 1,\n+ )\n+ # ||X'R||_2^2\n+ dual_norm_XtA = _dot(n_features, &XtA[0], 1, &XtA[0], 1)\n+ if beta == 0:\n+ # This is OLS, no dual gap available. Resort to first order condition\n+ # X'R = 0\n+ # gap = ||X'R||_2^2\n+ # Compare with stopping criterion of LSQR.\n+ gap = dual_norm_XtA\n+ return gap, dual_norm_XtA\n+ # This is Ridge regression, we use formulation B for the dual gap.\n+ gap = R_norm2 + 0.5 * beta * w_l2_norm2 - Ry\n+ gap += 1 / (2 * beta) * dual_norm_XtA\n+ return gap, dual_norm_XtA\n \n # XtA = X.T @ R - beta * w\n _copy(n_features, &w[0], 1, &XtA[0], 1)\n _gemv(ColMajor, Trans, n_samples, n_features, 1.0, &X[0, 0],\n n_samples, &R[0], 1,\n -beta, &XtA[0], 1)\n \n+ # dual_norm_XtA\n if positive:\n dual_norm_XtA = max(n_features, &XtA[0])\n else:\n dual_norm_XtA = abs_max(n_features, &XtA[0])\n \n- # R_norm2 = R @ R\n- R_norm2 = _dot(n_samples, &R[0], 1, &R[0], 1)\n-\n- # w_norm2 = w @ w\n- if beta > 0:\n- w_norm2 = _dot(n_features, &w[0], 1, &w[0], 1)\n-\n- if (dual_norm_XtA > alpha):\n- const_ = alpha / dual_norm_XtA\n- A_norm2 = R_norm2 * (const_ ** 2)\n- gap = 0.5 * (R_norm2 + A_norm2)\n- else:\n- const_ = 1.0\n- gap = R_norm2\n-\n- l1_norm = _asum(n_features, &w[0], 1)\n-\n- gap += (\n- alpha * l1_norm\n- - const_ * _dot(n_samples, &R[0], 1, &y[0], 1) # R @ y\n- + 0.5 * beta * (1 + const_ ** 2) * w_norm2\n+ # w_l1_norm = np.sum(np.abs(w))\n+ w_l1_norm = _asum(n_features, &w[0], 1)\n+\n+ gap = dual_gap_formulation_A(\n+ alpha=alpha,\n+ beta=beta,\n+ w_l1_norm=w_l1_norm,\n+ w_l2_norm2=w_l2_norm2,\n+ R_norm2=R_norm2,\n+ Ry=Ry,\n+ dual_norm_XtA=dual_norm_XtA,\n )\n return gap, dual_norm_XtA\n \n@@ -178,31 +226,49 @@ def enet_coordinate_descent(\n \n The dual for beta = 0, see e.g. [Fercoq 2015] with v = alpha * theta, is\n \n- D(v) = -1/2 ||v||_2^2 + y v\n+ D(v) = -1/2 ||v||_2^2 + y' v (formulation A)\n \n with dual feasible condition ||X^T v||_inf <= alpha.\n For beta > 0, one uses extended versions of X and y by adding n_features rows\n \n X -> ( X) y -> (y)\n (sqrt(beta) I) (0)\n \n- Note that the residual y - X w is an important ingredient for the estimation of a\n- dual feasible point v.\n+ Note that the residual R = y - X w is an important ingredient for the estimation of\n+ a dual feasible point v.\n At optimum of primal w* and dual v*, one has\n \n- v = y* - X w*\n+ v* = y - X w*\n \n The duality gap is\n \n G(w, v) = P(w) - D(v) <= P(w) - P(w*)\n \n+ Strong duality holds: G(w*, v*) = 0.\n+ For testing convergence, one uses G(w, v) with current w and uses\n+\n+ v = R if ||X^T R||_inf <= alpha\n+ v = R * alpha / ||X^T R||_inf else\n+\n The final stopping criterion is based on the duality gap\n \n tol ||y||_2^2 <= G(w, v)\n \n The tolerance here is multiplied by ||y||_2^2 to have an inequality that scales the\n same on both sides and because one has G(0, 0) = 1/2 ||y||_2^2.\n \n+ Note:\n+ The above dual D(v) and duality gap G require alpha > 0 because of the dual\n+ feasible condition.\n+ There is, however, an alternative dual formulation, see [Dünner 2016] 5.2.3 and\n+ https://github.com/[USER_REDACTED]n/scikit-learn/issues/22836:\n+\n+ D(v) = -1/2 ||v||_2^2 + y' v\n+ -1/(2 beta) sum_j (|X_j' v| - alpha)_+^2 (formulation B)\n+\n+ The dual feasible set is v element real numbers. It requires beta > 0, but\n+ alpha = 0 is allowed. Strong duality holds and at optimum, v* = y - X w*.\n+\n Returns\n -------\n w : ndarray of shape (n_features,)\n@@ -225,6 +291,11 @@ def enet_coordinate_descent(\n [NAME_REDACTED], [NAME_REDACTED], [NAME_REDACTED]. (2015)\n Mind the duality gap: safer rules for the Lasso\n https://arxiv.org/abs/1505.03410\n+\n+ .. [Dünner 2016]\n+ Celestine Dünner, [NAME_REDACTED], Martin Takác, [NAME_REDACTED]. (2016).\n+ [NAME_REDACTED] and Certificates. In ICML 2016.\n+ https://arxiv.org/abs/1602.05205\n \"\"\"\n \n if floating is float:\n@@ -266,9 +337,9 @@ def enet_coordinate_descent(\n cdef uint32_t rand_r_state_seed = rng.randint(0, RAND_R_MAX)\n cdef uint32_t* rand_r_state = &rand_r_state_seed\n \n- if alpha == 0 and beta == 0:\n- warnings.warn(\"Coordinate descent with no regularization may lead to \"\n- \"unexpected results and is discouraged.\")\n+ if alpha == 0:\n+ # No screeing without L1-penalty.\n+ do_screening = False\n \n if do_screening:\n active_set = np.empty(n_features, dtype=np.uint32) # map [:n_active] -> j\n@@ -387,7 +458,7 @@ def enet_coordinate_descent(\n with gil:\n message = (\n message_conv +\n- f\" Duality gap: {gap:.3e}, tolerance: {tol:.3e}\"\n+ f\" Duality gap: {gap:.6e}, tolerance: {tol:.3e}\"\n )\n if alpha < np.finfo(np.float64).eps:\n message += \"\\n\" + message_ridge\n@@ -448,16 +519,61 @@ cdef (floating, floating) gap_enet_sparse(\n floating[::1] XtA, # XtA = X.T @ R - beta * w is calculated inplace\n bint positive,\n ) noexcept nogil:\n- \"\"\"Compute dual gap for use in sparse_enet_coordinate_descent.\"\"\"\n+ \"\"\"Compute dual gap for use in sparse_enet_coordinate_descent.\n+\n+ alpha > 0: formulation A of the duality gap\n+ alpha = 0 & beta > 0: formulation B of the duality gap\n+ alpha = beta = 0: OLS first order condition (=gradient)\n+ \"\"\"\n cdef floating gap = 0.0\n cdef floating dual_norm_XtA\n cdef floating R_norm2\n- cdef floating w_norm2 = 0.0\n- cdef floating l1_norm\n- cdef floating A_norm2\n- cdef floating const_\n+ cdef floating Ry\n+ cdef floating w_l1_norm\n+ cdef floating w_l2_norm2 = 0.0\n cdef unsigned int i, j\n \n+ # w_l2_norm2 = w @ w\n+ if beta > 0:\n+ w_l2_norm2 = _dot(n_features, &w[0], 1, &w[0], 1)\n+ # R_norm2 = R @ R\n+ if no_sample_weights:\n+ R_norm2 = _dot(n_samples, &R[0], 1, &R[0], 1)\n+ else:\n+ R_norm2 = 0.0\n+ for i in range(n_samples):\n+ # R is already multiplied by sample_weight\n+ if sample_weight[i] != 0:\n+ R_norm2 += (R[i] ** 2) / sample_weight[i]\n+ # Ry = R @ y\n+ if not (alpha == 0 and beta == 0):\n+ # Note that with sample_weight, R equals R*sw and y is just y, such that\n+ # Ry = (sw * R) @ y, as it should be.\n+ Ry = _dot(n_samples, &R[0], 1, &y[0], 1)\n+\n+ if alpha == 0:\n+ # XtA = X.T @ R\n+ for j in range(n_features):\n+ XtA[j] = 0.0\n+ for i in range(X_indptr[j], X_indptr[j + 1]):\n+ XtA[j] += X_data[i] * R[X_indices[i]]\n+\n+ if center:\n+ XtA[j] -= X_mean[j] * R_sum\n+ # ||X'R||_2^2\n+ dual_norm_XtA = _dot(n_features, &XtA[0], 1, &XtA[0], 1)\n+ if beta == 0:\n+ # This is OLS, no dual gap available. Resort to first order condition\n+ # X'R = 0\n+ # gap = ||X'R||_2^2\n+ # Compare with stopping criterion of LSQR.\n+ gap = dual_norm_XtA\n+ return gap, dual_norm_XtA\n+ # This is Ridge regression, we use formulation B for the dual gap.\n+ gap = R_norm2 + 0.5 * beta * w_l2_norm2 - Ry\n+ gap += 1 / (2 * beta) * dual_norm_XtA\n+ return gap, dual_norm_XtA\n+\n # XtA = X.T @ R - beta * w\n # sparse X.T @ dense R\n for j in range(n_features):\n@@ -469,39 +585,23 @@ cdef (floating, floating) gap_enet_sparse(\n XtA[j] -= X_mean[j] * R_sum\n XtA[j] -= beta * w[j]\n \n+ # dual_norm_XtA\n if positive:\n dual_norm_XtA = max(n_features, &XtA[0])\n else:\n dual_norm_XtA = abs_max(n_features, &XtA[0])\n \n- # R_norm2 = R @ R\n- if no_sample_weights:\n- R_norm2 = _dot(n_samples, &R[0], 1, &R[0], 1)\n- else:\n- R_norm2 = 0.0\n- for i in range(n_samples):\n- # R is already multiplied by sample_weight\n- if sample_weight[i] != 0:\n- R_norm2 += (R[i] ** 2) / sample_weight[i]\n-\n- # w_norm2 = w @ w\n- if beta > 0:\n- w_norm2 = _dot(n_features, &w[0], 1, &w[0], 1)\n-\n- if (dual_norm_XtA > alpha):\n- const_ = alpha / dual_norm_XtA\n- A_norm2 = R_norm2 * const_**2\n- gap = 0.5 * (R_norm2 + A_norm2)\n- else:\n- const_ = 1.0\n- gap = R_norm2\n-\n- l1_norm = _asum(n_features, &w[0], 1)\n-\n- gap += (\n- alpha * l1_norm\n- - const_ * _dot(n_samples, &R[0], 1, &y[0], 1) # R @ y\n- + 0.5 * beta * (1 + const_ ** 2) * w_norm2\n+ # w_l1_norm = np.sum(np.abs(w))\n+ w_l1_norm = _asum(n_features, &w[0], 1)\n+\n+ gap = dual_gap_formulation_A(\n+ alpha=alpha,\n+ beta=beta,\n+ w_l1_norm=w_l1_norm,\n+ w_l2_norm2=w_l2_norm2,\n+ R_norm2=R_norm2,\n+ Ry=Ry,\n+ dual_norm_XtA=dual_norm_XtA,\n )\n return gap, dual_norm_XtA\n \n@@ -606,6 +706,10 @@ def sparse_enet_coordinate_descent(\n cdef bint center = False\n cdef bint no_sample_weights = sample_weight is None\n \n+ if alpha == 0:\n+ # No screeing without L1-penalty.\n+ do_screening = False\n+\n if do_screening:\n active_set = np.empty(n_features, dtype=np.uint32) # map [:n_active] -> j\n excluded_set = np.empty(n_features, dtype=np.uint8)\n@@ -843,7 +947,7 @@ def sparse_enet_coordinate_descent(\n with gil:\n message = (\n message_conv +\n- f\" Duality gap: {gap:.3e}, tolerance: {tol:.3e}\"\n+ f\" Duality gap: {gap:.6e}, tolerance: {tol:.3e}\"\n )\n if alpha < np.finfo(np.float64).eps:\n message += \"\\n\" + message_ridge\n@@ -863,53 +967,75 @@ cdef (floating, floating) gap_enet_gram(\n floating[::1] XtA, # XtA = X.T @ R - beta * w is calculated inplace\n bint positive,\n ) noexcept nogil:\n- \"\"\"Compute dual gap for use in enet_coordinate_descent.\"\"\"\n+ \"\"\"Compute dual gap for use in enet_coordinate_descent.\n+\n+ alpha > 0: formulation A of the duality gap\n+ alpha = 0 & beta > 0: formulation B of the duality gap\n+ alpha = beta = 0: OLS first order condition (=gradient)\n+ \"\"\"\n cdef floating gap = 0.0\n cdef floating dual_norm_XtA\n cdef floating R_norm2\n- cdef floating w_norm2 = 0.0\n- cdef floating l1_norm\n- cdef floating A_norm2\n- cdef floating const_\n+ cdef floating Ry\n+ cdef floating w_l1_norm\n+ cdef floating w_l2_norm2 = 0.0\n cdef floating q_dot_w\n cdef floating wQw\n cdef unsigned int j\n \n+ # w_l2_norm2 = w @ w\n+ if beta > 0:\n+ w_l2_norm2 = _dot(n_features, &w[0], 1, &w[0], 1)\n # q_dot_w = w @ q\n q_dot_w = _dot(n_features, &w[0], 1, &q[0], 1)\n+ # wQw = w @ Q @ w\n+ wQw = _dot(n_features, &w[0], 1, &Qw[0], 1)\n+ # R_norm2 = R @ R, residual R = y - Xw\n+ R_norm2 = y_norm2 + wQw - 2.0 * q_dot_w\n+ # Ry = R @ y\n+ if not (alpha == 0 and beta == 0):\n+ # Note that R'y = (y - Xw)' y = ||y||_2^2 - w'X'y = y_norm2 - q_dot_w\n+ Ry = y_norm2 - q_dot_w\n+\n+ if alpha == 0:\n+ # XtA = X'R\n+ for j in range(n_features):\n+ XtA[j] = q[j] - Qw[j]\n+ # ||X'R||_2^2\n+ dual_norm_XtA = _dot(n_features, &XtA[0], 1, &XtA[0], 1)\n+ if beta == 0:\n+ # This is OLS, no dual gap available. Resort to first order condition\n+ # X'R = 0\n+ # gap = ||X'R||_2^2\n+ # Compare with stopping criterion of LSQR.\n+ gap = dual_norm_XtA\n+ return gap, dual_norm_XtA\n+ # This is Ridge regression, we use formulation B for the dual gap.\n+ gap = R_norm2 + 0.5 * beta * w_l2_norm2 - Ry\n+ gap += 1 / (2 * beta) * dual_norm_XtA\n+ return gap, dual_norm_XtA\n \n # XtA = X.T @ R - beta * w = X.T @ y - X.T @ X @ w - beta * w\n for j in range(n_features):\n XtA[j] = q[j] - Qw[j] - beta * w[j]\n \n+ # dual_norm_XtA\n if positive:\n dual_norm_XtA = max(n_features, &XtA[0])\n else:\n dual_norm_XtA = abs_max(n_features, &XtA[0])\n \n- # wQw = w @ Q @ w\n- wQw = _dot(n_features, &w[0], 1, &Qw[0], 1)\n- # R_norm2 = R @ R\n- R_norm2 = y_norm2 + wQw - 2.0 * q_dot_w\n-\n- # w_norm2 = w @ w\n- if beta > 0:\n- w_norm2 = _dot(n_features, &w[0], 1, &w[0], 1)\n-\n- if (dual_norm_XtA > alpha):\n- const_ = alpha / dual_norm_XtA\n- A_norm2 = R_norm2 * (const_ ** 2)\n- gap = 0.5 * (R_norm2 + A_norm2)\n- else:\n- const_ = 1.0\n- gap = R_norm2\n-\n- l1_norm = _asum(n_features, &w[0], 1)\n-\n- gap += (\n- alpha * l1_norm\n- - const_ * (y_norm2 - q_dot_w) # -const_ * R @ y\n- + 0.5 * beta * (1 + const_ ** 2) * w_norm2\n+ # w_l1_norm = np.sum(np.abs(w))\n+ w_l1_norm = _asum(n_features, &w[0], 1)\n+\n+ gap = dual_gap_formulation_A(\n+ alpha=alpha,\n+ beta=beta,\n+ w_l1_norm=w_l1_norm,\n+ w_l2_norm2=w_l2_norm2,\n+ R_norm2=R_norm2,\n+ Ry=Ry,\n+ dual_norm_XtA=dual_norm_XtA,\n )\n return gap, dual_norm_XtA\n \n@@ -987,11 +1113,8 @@ def enet_coordinate_descent_gram(\n cdef uint32_t* rand_r_state = &rand_r_state_seed\n \n if alpha == 0:\n- warnings.warn(\n- \"Coordinate descent without L1 regularization may \"\n- \"lead to unexpected results and is discouraged. \"\n- \"Set l1_ratio > 0 to add L1 regularization.\"\n- )\n+ # No screeing without L1-penalty.\n+ do_screening = False\n \n if do_screening:\n active_set = np.empty(n_features, dtype=np.uint32) # map [:n_active] -> j\n@@ -1108,8 +1231,10 @@ def enet_coordinate_descent_gram(\n with gil:\n message = (\n message_conv +\n- f\" Duality gap: {gap:.3e}, tolerance: {tol:.3e}\"\n+ f\" Duality gap: {gap:.6e}, tolerance: {tol:.3e}\"\n )\n+ if alpha < np.finfo(np.float64).eps:\n+ message += \"\\n\" + message_ridge\n warnings.warn(message, ConvergenceWarning)\n \n return np.asarray(w), gap, tol, n_iter + 1\n@@ -1145,12 +1270,39 @@ cdef (floating, floating) gap_enet_multi_task(\n cdef floating gap = 0.0\n cdef floating dual_norm_XtA\n cdef floating R_norm2\n- cdef floating w_norm2 = 0.0\n- cdef floating l21_norm\n- cdef floating A_norm2\n- cdef floating const_\n+ cdef floating Ry\n+ cdef floating w_l21_norm\n+ cdef floating w_l2_norm2 = 0.0\n cdef unsigned int t, j\n \n+ # w_l2_norm2 = linalg.norm(W, ord=\"fro\") ** 2\n+ if l2_reg > 0:\n+ w_l2_norm2 = _dot(n_features * n_tasks, &W[0, 0], 1, &W[0, 0], 1)\n+ # R_norm2 = linalg.norm(R, ord=\"fro\") ** 2\n+ R_norm2 = _dot(n_samples * n_tasks, &R[0, 0], 1, &R[0, 0], 1)\n+ # Ry = np.sum(R * Y)\n+ if not (l1_reg == 0 and l2_reg == 0):\n+ Ry = _dot(n_samples * n_tasks, &R[0, 0], 1, &Y[0, 0], 1)\n+\n+ if l1_reg == 0:\n+ # XtA = X.T @ R\n+ for j in range(n_features):\n+ for t in range(n_tasks):\n+ XtA[j, t] = _dot(n_samples, &X[0, j], 1, &R[0, t], 1)\n+ # ||X'R||_2^2\n+ dual_norm_XtA = _dot(n_features * n_tasks, &XtA[0, 0], 1, &XtA[0, 0], 1)\n+ if l2_reg == 0:\n+ # This is OLS, no dual gap available. Resort to first order condition\n+ # X'R = 0\n+ # gap = ||X'R||_2^2\n+ # Compare with stopping criterion of LSQR.\n+ gap = dual_norm_XtA\n+ return gap, dual_norm_XtA\n+ # This is Ridge regression, we use formulation B for the dual gap.\n+ gap = R_norm2 + 0.5 * l2_reg * w_l2_norm2 - Ry\n+ gap += 1 / (2 * l2_reg) * dual_norm_XtA\n+ return gap, dual_norm_XtA\n+\n # XtA = X.T @ R - l2_reg * W.T\n for j in range(n_features):\n for t in range(n_tasks):\n@@ -1164,30 +1316,19 @@ cdef (floating, floating) gap_enet_multi_task(\n if XtA_row_norms[j] > dual_norm_XtA:\n dual_norm_XtA = XtA_row_norms[j]\n \n- # R_norm2 = linalg.norm(R, ord=\"fro\") ** 2\n- R_norm2 = _dot(n_samples * n_tasks, &R[0, 0], 1, &R[0, 0], 1)\n-\n- # w_norm2 = linalg.norm(W, ord=\"fro\") ** 2\n- if l2_reg > 0:\n- w_norm2 = _dot(n_features * n_tasks, &W[0, 0], 1, &W[0, 0], 1)\n-\n- if (dual_norm_XtA > l1_reg):\n- const_ = l1_reg / dual_norm_XtA\n- A_norm2 = R_norm2 * (const_ ** 2)\n- gap = 0.5 * (R_norm2 + A_norm2)\n- else:\n- const_ = 1.0\n- gap = R_norm2\n-\n- # l21_norm = np.sqrt(np.sum(W ** 2, axis=0)).sum()\n- l21_norm = 0.0\n+ # w_l21_norm = np.sqrt(np.sum(W ** 2, axis=0)).sum()\n+ w_l21_norm = 0.0\n for ii in range(n_features):\n- l21_norm += _nrm2(n_tasks, &W[0, ii], 1)\n-\n- gap += (\n- l1_reg * l21_norm\n- - const_ * _dot(n_samples * n_tasks, &R[0, 0], 1, &Y[0, 0], 1) # np.sum(R * Y)\n- + 0.5 * l2_reg * (1 + const_ ** 2) * w_norm2\n+ w_l21_norm += _nrm2(n_tasks, &W[0, ii], 1)\n+\n+ gap = dual_gap_formulation_A(\n+ alpha=l1_reg,\n+ beta=l2_reg,\n+ w_l1_norm=w_l21_norm,\n+ w_l2_norm2=w_l2_norm2,\n+ R_norm2=R_norm2,\n+ Ry=Ry,\n+ dual_norm_XtA=dual_norm_XtA,\n )\n return gap, dual_norm_XtA\n \n@@ -1274,10 +1415,8 @@ def enet_coordinate_descent_multi_task(\n cdef uint32_t* rand_r_state = &rand_r_state_seed\n \n if l1_reg == 0:\n- warnings.warn(\n- \"Coordinate descent with l1_reg=0 may lead to unexpected\"\n- \" results and is discouraged.\"\n- )\n+ # No screeing without L1-penalty.\n+ do_screening = False\n \n if do_screening:\n active_set = np.empty(n_features, dtype=np.uint32) # map [:n_active] -> j\n@@ -1429,8 +1568,10 @@ def enet_coordinate_descent_multi_task(\n with gil:\n message = (\n message_conv +\n- f\" Duality gap: {gap:.3e}, tolerance: {tol:.3e}\"\n+ f\" Duality gap: {gap:.6e}, tolerance: {tol:.3e}\"\n )\n+ if l1_reg < np.finfo(np.float64).eps:\n+ message += \"\\n\" + message_ridge\n warnings.warn(message, ConvergenceWarning)\n \n return np.asarray(W), gap, tol, n_iter + 1" }, { "filename": "sklearn/linear_model/_coordinate_descent.py", "status": "modified", "additions": 4, "deletions": 5, "changes": 9, "patch": "@@ -124,9 +124,8 @@ def _alpha_grid(\n \n l1_ratio : float, default=1.0\n The elastic net mixing parameter, with ``0 < l1_ratio <= 1``.\n- For ``l1_ratio = 0`` the penalty is an L2 penalty. (currently not\n- supported) ``For l1_ratio = 1`` it is an L1 penalty. For\n- ``0 < l1_ratio <1``, the penalty is a combination of L1 and L2.\n+ For ``l1_ratio = 0``, there would be no L1 penalty which is not supported\n+ for the generation of alphas.\n \n eps : float, default=1e-3\n Length of the path. ``eps=1e-3`` means that\n@@ -439,15 +438,15 @@ def enet_path(\n \n For multi-output tasks it is::\n \n- (1 / (2 * n_samples)) * ||Y - XW||_Fro^2\n+ 1 / (2 * n_samples) * ||Y - XW||_Fro^2\n + alpha * l1_ratio * ||W||_21\n + 0.5 * alpha * (1 - l1_ratio) * ||W||_Fro^2\n \n Where::\n \n ||W||_21 = \\\\sum_i \\\\sqrt{\\\\sum_j w_{ij}^2}\n \n- i.e. the sum of norm of each row.\n+ i.e. the sum of L2-norm of each row (task) (i=feature, j=task)\n \n Read more in the :ref:`[NAME_REDACTED] `." }, { "filename": "sklearn/linear_model/tests/test_coordinate_descent.py", "status": "modified", "additions": 77, "deletions": 38, "changes": 115, "patch": "@@ -18,6 +18,7 @@\n Lasso,\n LassoCV,\n LassoLarsCV,\n+ LinearRegression,\n MultiTaskElasticNet,\n MultiTaskElasticNetCV,\n MultiTaskLasso,\n@@ -580,16 +581,14 @@ def test_uniform_targets():\n for model in models_single_task:\n for y_values in (0, 5):\n y1.fill(y_values)\n- with ignore_warnings(category=ConvergenceWarning):\n- assert_array_equal(model.fit(X_train, y1).predict(X_test), y1)\n+ assert_array_equal(model.fit(X_train, y1).predict(X_test), y1)\n assert_array_equal(model.alphas_, [np.finfo(float).resolution] * 3)\n \n for model in models_multi_task:\n for y_values in (0, 5):\n y2[:, 0].fill(y_values)\n y2[:, 1].fill(2 * y_values)\n- with ignore_warnings(category=ConvergenceWarning):\n- assert_array_equal(model.fit(X_train, y2).predict(X_test), y2)\n+ assert_array_equal(model.fit(X_train, y2).predict(X_test), y2)\n assert_array_equal(model.alphas_, [np.finfo(float).resolution] * 3)\n \n \n@@ -969,15 +968,14 @@ def test_check_input_false():\n X, y, _, _ = build_dataset(n_samples=20, n_features=10)\n X = check_array(X, order=\"F\", dtype=\"float64\")\n y = check_array(X, order=\"F\", dtype=\"float64\")\n- clf = ElasticNet(selection=\"cyclic\", tol=1e-8)\n+ clf = ElasticNet(selection=\"cyclic\", tol=1e-7)\n # Check that no error is raised if data is provided in the right format\n clf.fit(X, y, check_input=False)\n # With check_input=False, an exhaustive check is not made on y but its\n # dtype is still cast in _preprocess_data to X's dtype. So the test should\n # pass anyway\n X = check_array(X, order=\"F\", dtype=\"float32\")\n- with ignore_warnings(category=ConvergenceWarning):\n- clf.fit(X, y, check_input=False)\n+ clf.fit(X, y, check_input=False)\n # With no input checking, providing X in C order should result in false\n # computation\n X = check_array(X, order=\"C\", dtype=\"float64\")\n@@ -1093,7 +1091,6 @@ def test_enet_float_precision():\n )\n \n \n-[USER_REDACTED].mark.filterwarnings(\"ignore::sklearn.exceptions.ConvergenceWarning\")\n def test_enet_l1_ratio():\n # Test that an error message is raised if an estimator that\n # uses _alpha_grid is called with l1_ratio=0\n@@ -1111,31 +1108,25 @@ def test_enet_l1_ratio():\n with pytest.raises(ValueError, match=msg):\n MultiTaskElasticNetCV(l1_ratio=0, random_state=42).fit(X, y[:, None])\n \n- # Test that l1_ratio=0 with alpha>0 produces user warning\n- warning_message = (\n- \"Coordinate descent without L1 regularization may \"\n- \"lead to unexpected results and is discouraged. \"\n- \"Set l1_ratio > 0 to add L1 regularization.\"\n- )\n+ # But no error for ElasticNetCV with l1_ratio=0 and alpha>0.\n est = ElasticNetCV(l1_ratio=[0], alphas=[1])\n- with pytest.warns(UserWarning, match=warning_message):\n+ with warnings.catch_warnings():\n+ warnings.simplefilter(\"error\")\n est.fit(X, y)\n \n # Test that l1_ratio=0 is allowed if we supply a grid manually\n alphas = [0.1, 10]\n estkwds = {\"alphas\": alphas, \"random_state\": 42}\n est_desired = ElasticNetCV(l1_ratio=0.00001, **estkwds)\n est = ElasticNetCV(l1_ratio=0, **estkwds)\n- with ignore_warnings():\n- est_desired.fit(X, y)\n- est.fit(X, y)\n+ est_desired.fit(X, y)\n+ est.fit(X, y)\n assert_array_almost_equal(est.coef_, est_desired.coef_, decimal=5)\n \n est_desired = MultiTaskElasticNetCV(l1_ratio=0.00001, **estkwds)\n est = MultiTaskElasticNetCV(l1_ratio=0, **estkwds)\n- with ignore_warnings():\n- est.fit(X, y[:, None])\n- est_desired.fit(X, y[:, None])\n+ est.fit(X, y[:, None])\n+ est_desired.fit(X, y[:, None])\n assert_array_almost_equal(est.coef_, est_desired.coef_, decimal=5)\n \n \n@@ -1553,39 +1544,85 @@ def test_enet_sample_weight_does_not_overwrite_sample_weight(check_input):\n assert_array_equal(sample_weight, sample_weight_1_25)\n \n \n-[USER_REDACTED].mark.filterwarnings(\"ignore::sklearn.exceptions.ConvergenceWarning\")\n-[USER_REDACTED].mark.parametrize(\"ridge_alpha\", [1e-1, 1.0, 1e6])\n-def test_enet_ridge_consistency(ridge_alpha):\n+[USER_REDACTED].mark.parametrize(\"ridge_alpha\", [1e-6, 1e-1, 1.0, 1e6])\n+[USER_REDACTED].mark.parametrize(\n+ [\"precompute\", \"n_targets\"], [(False, 1), (True, 1), (False, 3)]\n+)\n+def test_enet_ridge_consistency(ridge_alpha, precompute, n_targets):\n # Check that ElasticNet(l1_ratio=0) converges to the same solution as Ridge\n # provided that the value of alpha is adapted.\n- #\n- # XXX: this test does not pass for weaker regularization (lower values of\n- # ridge_alpha): it could be either a problem of ElasticNet or Ridge (less\n- # likely) and depends on the dataset statistics: lower values for\n- # effective_rank are more problematic in particular.\n \n rng = np.random.RandomState(42)\n n_samples = 300\n X, y = make_regression(\n n_samples=n_samples,\n n_features=100,\n+ n_targets=n_targets,\n effective_rank=10,\n n_informative=50,\n random_state=rng,\n )\n sw = rng.uniform(low=0.01, high=10, size=X.shape[0])\n- alpha = 1.0\n- common_params = dict(\n- tol=1e-12,\n+\n+ if n_targets == 1:\n+ sw_arg = dict(sample_weight=sw)\n+ else:\n+ # MultiTaskElasticNet does not support sample weights (yet).\n+ sw_arg = dict()\n+\n+ ridge = Ridge(alpha=ridge_alpha, solver=\"svd\").fit(X, y, **sw_arg)\n+\n+ tol = 1e-11 if ridge_alpha >= 1e-2 else 1e-16\n+ if n_targets == 1:\n+ alpha_enet = ridge_alpha / sw.sum()\n+ enet = ElasticNet(alpha=alpha_enet, l1_ratio=0, precompute=precompute, tol=tol)\n+ else:\n+ alpha_enet = ridge_alpha / n_samples\n+ enet = MultiTaskElasticNet(alpha=alpha_enet, l1_ratio=0, tol=tol)\n+ enet.fit(X, y, **sw_arg)\n+\n+ # The CD solver using the gram matrix (precompute = True) loses numerical precision\n+ # by [NAME_REDACTED] of matrices like Q=X'X (=gram) and\n+ # R^2 = y^2 + wQw - 2yQw (=square of residuals).\n+ rtol = 1e-5 if precompute else 1e-7\n+ assert_allclose(enet.coef_, ridge.coef_, rtol=rtol)\n+ assert_allclose(enet.intercept_, ridge.intercept_)\n+\n+\n+[USER_REDACTED].mark.filterwarnings(\"ignore:With alpha=0, this algorithm:UserWarning\")\n+[USER_REDACTED].mark.parametrize(\"precompute\", [False, True])\n+[USER_REDACTED].mark.parametrize(\"effective_rank\", [None, 10])\n+def test_enet_ols_consistency(precompute, effective_rank):\n+ \"\"\"Test that ElasticNet(alpha=0) converges to the same solution as OLS.\"\"\"\n+ rng = np.random.RandomState(42)\n+ n_samples = 300\n+ X, y = make_regression(\n+ n_samples=n_samples,\n+ n_features=100,\n+ effective_rank=effective_rank,\n+ n_informative=50,\n+ random_state=rng,\n )\n- ridge = Ridge(alpha=alpha, **common_params).fit(X, y, sample_weight=sw)\n+ sw = rng.uniform(low=0.01, high=10, size=X.shape[0])\n \n- alpha_enet = alpha / sw.sum()\n- enet = ElasticNet(alpha=alpha_enet, l1_ratio=0, **common_params).fit(\n+ ols = LinearRegression().fit(X, y, sample_weight=sw)\n+ enet = ElasticNet(alpha=0, precompute=precompute, tol=1e-15).fit(\n X, y, sample_weight=sw\n )\n- assert_allclose(ridge.coef_, enet.coef_)\n- assert_allclose(ridge.intercept_, enet.intercept_)\n+\n+ # Might be a singular problem, so check for same predictions\n+ assert_allclose(enet.predict(X), ols.predict(X))\n+ # and for similar objective function (squared error)\n+ se_ols = np.sum((y - ols.predict(X)) ** 2)\n+ se_enet = np.sum((y - enet.predict(X)) ** 2)\n+ if precompute:\n+ assert se_ols <= 1e-20\n+ assert se_enet <= 1e-20\n+ else:\n+ assert se_enet <= se_ols <= 1e-20 # Who would have thought that?\n+ # We check equal coefficients, but \"only\" with absolute tolerance.\n+ assert_allclose(enet.coef_, ols.coef_, atol=1e-11)\n+ assert_allclose(enet.intercept_, ols.intercept_, atol=1e-12)\n \n \n [USER_REDACTED].mark.parametrize(\n@@ -1769,7 +1806,9 @@ def test_linear_model_cv_alphas_n_alphas_unset(Estimator):\n \n # TODO(1.9): remove\n [USER_REDACTED].mark.filterwarnings(\"ignore:'n_alphas' was deprecated in 1.7\")\n-[USER_REDACTED].mark.filterwarnings(\"ignore:.*with no regularization.*:UserWarning\")\n+[USER_REDACTED].mark.filterwarnings(\n+ \"ignore:With alpha=0, this algorithm does not converge well.*:UserWarning\"\n+)\n [USER_REDACTED].mark.parametrize(\n \"Estimator\", [ElasticNetCV, LassoCV, MultiTaskLassoCV, MultiTaskElasticNetCV]\n )" }, { "filename": "sklearn/linear_model/tests/test_sparse_coordinate_descent.py", "status": "modified", "additions": 13, "deletions": 1, "changes": 14, "patch": "@@ -271,11 +271,18 @@ def test_path_parameters(csc_container):\n \n [USER_REDACTED].mark.parametrize(\"Model\", [Lasso, ElasticNet, LassoCV, ElasticNetCV])\n [USER_REDACTED].mark.parametrize(\"fit_intercept\", [False, True])\n+[USER_REDACTED].mark.parametrize(\"l1_ratio\", [0.5, 0])\n [USER_REDACTED].mark.parametrize(\"n_samples, n_features\", [(24, 6), (6, 24)])\n [USER_REDACTED].mark.parametrize(\"with_sample_weight\", [True, False])\n [USER_REDACTED].mark.parametrize(\"csc_container\", CSC_CONTAINERS)\n def test_sparse_dense_equality(\n- Model, fit_intercept, n_samples, n_features, with_sample_weight, csc_container\n+ Model,\n+ fit_intercept,\n+ l1_ratio,\n+ n_samples,\n+ n_features,\n+ with_sample_weight,\n+ csc_container,\n ):\n X, y = make_regression(\n n_samples=n_samples,\n@@ -292,6 +299,11 @@ def test_sparse_dense_equality(\n sw = None\n Xs = csc_container(X)\n params = {\"fit_intercept\": fit_intercept, \"tol\": 1e-6}\n+ if Model != ElasticNet:\n+ if l1_ratio == 0:\n+ return\n+ else:\n+ params[\"l1_ratio\"] = l1_ratio\n reg_dense = Model(**params).fit(X, y, sample_weight=sw)\n reg_sparse = Model(**params).fit(Xs, y, sample_weight=sw)\n if fit_intercept:" } ], "reviews": [ { "id": 3573635477, "user": "user_22bafe4fe1a9", "state": "COMMENTED", "body": null, "submitted_at": "2025-12-12T21:20:39+00:00" }, { "id": 3574490272, "user": "user_bf0b6c7acb9c", "state": "APPROVED", "body": "LGTM! Thanks, [USER_REDACTED]!\n\nI just have a few questions for my own understanding.", "submitted_at": "2025-12-13T17:57:08+00:00" }, { "id": 3581443066, "user": "user_22bafe4fe1a9", "state": "COMMENTED", "body": null, "submitted_at": "2025-12-16T05:58:11+00:00" }, { "id": 3581452760, "user": "user_22bafe4fe1a9", "state": "COMMENTED", "body": null, "submitted_at": "2025-12-16T06:01:45+00:00" }, { "id": 3620917190, "user": "user_3c90b5520ec5", "state": "APPROVED", "body": "Looks good [USER_REDACTED] \nThank you for the PR", "submitted_at": "2025-12-31T14:02:03+00:00" } ], "review_comments": [ { "id": 2615609735, "user": "user_22bafe4fe1a9", "body": "I find this quite surprising.\n\nNote: The test passes with `se_enet < se_ols`, e.g. `4.8032617180978374e-23 < 2.031868402489036e-22`. This means the CD solver of `ElasticNet`, indeed, finds better solutions than `LinearRegression`!", "path": "sklearn/linear_model/tests/test_coordinate_descent.py", "line": 1622, "side": "RIGHT", "created_at": "2025-12-12T21:20:39+00:00" }, { "id": 2616438320, "user": "user_bf0b6c7acb9c", "body": "I understand that this is an implementation detail. However, would it be useful to include this mathematical detail in the [user guide](https://scikit-learn.org/stable/modules/linear_model.html#mathematical-details), given that Formulation A is already covered?", "path": "sklearn/linear_model/_cd_fast.pyx", "line": 176, "side": "RIGHT", "created_at": "2025-12-13T17:47:55+00:00" }, { "id": 2616441902, "user": "user_bf0b6c7acb9c", "body": "Can we use `assert_allclose` here, since we want to check that `ElasticNet(alpha=0.0)` converges to `Ridge`? Also, I'm curious. --- what surprised you, aside from floating-point effects?", "path": "sklearn/linear_model/tests/test_coordinate_descent.py", "line": 1622, "side": "RIGHT", "created_at": "2025-12-13T17:55:21+00:00" }, { "id": 2621899391, "user": "user_22bafe4fe1a9", "body": "The formulation B is - so far - only used in the edge case of no L1 penalty. Therefore, I‘d be hesitant to add it to the user guide.\n\nIf later, in a later PR, we decide to make more use of it, the sure, let’s include it. For the time being it is at least documented in issue #22836.", "path": "sklearn/linear_model/_cd_fast.pyx", "line": 176, "side": "RIGHT", "created_at": "2025-12-16T05:58:10+00:00" }, { "id": 2621907462, "user": "user_22bafe4fe1a9", "body": "Yes, assert_allclose to zero would also work. But it would hide the fact that the squared error of enet gets closer to zero than ols!", "path": "sklearn/linear_model/tests/test_coordinate_descent.py", "line": 1622, "side": "RIGHT", "created_at": "2025-12-16T06:01:45+00:00" }, { "id": 2655417616, "user": "user_3c90b5520ec5", "body": "```suggestion\n The above dual D(v) and duality gap G require alpha > 0 because of the dual\n```", "path": "sklearn/linear_model/_cd_fast.pyx", "line": null, "side": "RIGHT", "created_at": "2025-12-31T13:38:48+00:00" } ], "meta": { "languages": [ "py", "pyx", "rst" ], "touches_tests": true, "review_state_summary": { "COMMENTED": 3, "APPROVED": 2 }, "meaningful_comment_count": 6, "has_approval": true, "has_changes_requested": false, "total_review_comments": 6 } } { "_id": "b09af109e537559a", "_schema_version": "1.0", "_cleaned_at": "2026-02-12T07:46:52.007714+00:00", "repo": "scikit-learn/scikit-learn", "repo_url": "https://github.com/scikit-learn/scikit-learn", "license_name": "BSD 3-Clause \"New\" or \"Revised\" License", "license_spdx": "BSD-3-Clause", "pr_number": 32840, "title": "Fix `_safe_indexing` with non integer arrays on array API inputs", "body": "This is a fix for #32837.\n\nWhile investigating the issue above, I realized that we needed unittest for array API support for `_safe_indexing`.\n\nI am not yet sure if this problem already existing in 1.7 or not. If it was I will add a changelog entry.", "author": "user_5819d17296ee", "created_at": "2025-12-04T15:29:28+00:00", "merged_at": "2025-12-05T14:09:16+00:00", "base_branch": "main", "head_branch": "fix-array-api-indexing", "additions": 65, "deletions": 9, "changed_files": 3, "files": [ { "filename": "sklearn/utils/_array_api.py", "status": "modified", "additions": 1, "deletions": 1, "changes": 2, "patch": "@@ -469,7 +469,7 @@ def move_to(*arrays, xp, device):\n `array` may contain `None` entries, these are left unchanged.\n \n Sparse arrays are accepted (as pass through) if the reference namespace is\n- Numpy, in which case they are returned unchanged. Otherwise a `TypeError`\n+ NumPy, in which case they are returned unchanged. Otherwise a `TypeError`\n is raised.\n \n Parameters" }, { "filename": "sklearn/utils/_indexing.py", "status": "modified", "additions": 18, "deletions": 2, "changes": 20, "patch": "@@ -36,8 +36,24 @@ def _array_indexing(array, key, key_dtype, axis):\n \"\"\"Index an array or scipy.sparse consistently across NumPy version.\"\"\"\n xp, is_array_api, device_ = get_namespace_and_device(array)\n if is_array_api:\n- key = move_to(key, xp=xp, device=device_)\n- return xp.take(array, key, axis=axis)\n+ if hasattr(key, \"shape\"):\n+ key = move_to(key, xp=xp, device=device_)\n+ elif isinstance(key, (int, slice)):\n+ # Passthrough for valid __getitem__ inputs as noted in the array\n+ # API spec.\n+ pass\n+ else:\n+ key = xp.asarray(key, device=device_)\n+\n+ if hasattr(key, \"dtype\"):\n+ if xp.isdtype(key.dtype, \"integral\"):\n+ return xp.take(array, key, axis=axis)\n+ elif xp.isdtype(key.dtype, \"bool\"):\n+ # Array API does not support boolean indexing for n-dim arrays\n+ # yet hence the need to turn to equivalent integer indexing.\n+ indices = xp.arange(array.shape[axis], device=device_)\n+ return xp.take(array, indices[key], axis=axis)\n+\n if issparse(array) and key_dtype == \"bool\":\n key = np.asarray(key)\n if isinstance(key, tuple):" }, { "filename": "sklearn/utils/tests/test_indexing.py", "status": "modified", "additions": 46, "deletions": 6, "changes": 52, "patch": "@@ -10,7 +10,10 @@\n from sklearn.externals._packaging.version import parse as parse_version\n from sklearn.utils import _safe_indexing, resample, shuffle\n from sklearn.utils._array_api import (\n+ _convert_to_numpy,\n _get_namespace_device_dtype_ids,\n+ device,\n+ move_to,\n yield_namespace_device_dtype_combinations,\n )\n from sklearn.utils._indexing import (\n@@ -22,6 +25,7 @@\n from sklearn.utils._testing import (\n _array_api_for_tests,\n _convert_container,\n+ assert_allclose,\n assert_allclose_dense_sparse,\n assert_array_equal,\n skip_if_array_api_compat_not_configured,\n@@ -108,22 +112,22 @@ def test_determine_key_type_slice_error():\n \n [USER_REDACTED]_if_array_api_compat_not_configured\n [USER_REDACTED].mark.parametrize(\n- \"array_namespace, device, dtype_name\",\n+ \"array_namespace, device_, dtype_name\",\n yield_namespace_device_dtype_combinations(),\n ids=_get_namespace_device_dtype_ids,\n )\n-def test_determine_key_type_array_api(array_namespace, device, dtype_name):\n- xp = _array_api_for_tests(array_namespace, device)\n+def test_determine_key_type_array_api(array_namespace, device_, dtype_name):\n+ xp = _array_api_for_tests(array_namespace, device_)\n \n with sklearn.config_context(array_api_dispatch=True):\n- int_array_key = xp.asarray([1, 2, 3])\n+ int_array_key = xp.asarray([1, 2, 3], device=device_)\n assert _determine_key_type(int_array_key) == \"int\"\n \n- bool_array_key = xp.asarray([True, False, True])\n+ bool_array_key = xp.asarray([True, False, True], device=device_)\n assert _determine_key_type(bool_array_key) == \"bool\"\n \n try:\n- complex_array_key = xp.asarray([1 + 1j, 2 + 2j, 3 + 3j])\n+ complex_array_key = xp.asarray([1 + 1j, 2 + 2j, 3 + 3j], device=device_)\n except TypeError:\n # Complex numbers are not supported by [NAME_REDACTED]\n complex_array_key = None\n@@ -133,6 +137,42 @@ def test_determine_key_type_array_api(array_namespace, device, dtype_name):\n _determine_key_type(complex_array_key)\n \n \n+[USER_REDACTED]_if_array_api_compat_not_configured\n+[USER_REDACTED].mark.parametrize(\n+ \"array_namespace, device_, dtype_name\",\n+ yield_namespace_device_dtype_combinations(),\n+ ids=_get_namespace_device_dtype_ids,\n+)\n+[USER_REDACTED].mark.parametrize(\n+ \"indexing_key\",\n+ (\n+ 0,\n+ -1,\n+ [1, 3],\n+ np.array([1, 3]),\n+ slice(1, 2),\n+ [True, False, True, True],\n+ np.asarray([False, False, False, False]),\n+ ),\n+)\n+[USER_REDACTED].mark.parametrize(\"axis\", [0, 1])\n+def test_safe_indexing_array_api_support(\n+ array_namespace, device_, dtype_name, indexing_key, axis\n+):\n+ xp = _array_api_for_tests(array_namespace, device_)\n+\n+ array_to_index_np = np.arange(16).reshape(4, 4)\n+ expected_result = _safe_indexing(array_to_index_np, indexing_key, axis=axis)\n+ array_to_index_xp = move_to(array_to_index_np, xp=xp, device=device_)\n+\n+ with sklearn.config_context(array_api_dispatch=True):\n+ indexed_array_xp = _safe_indexing(array_to_index_xp, indexing_key, axis=axis)\n+ assert device(indexed_array_xp) == device(array_to_index_xp)\n+ assert indexed_array_xp.dtype == array_to_index_xp.dtype\n+\n+ assert_allclose(_convert_to_numpy(indexed_array_xp, xp=xp), expected_result)\n+\n+\n [USER_REDACTED].mark.parametrize(\n \"array_type\", [\"list\", \"array\", \"sparse\", \"dataframe\", \"polars\", \"pyarrow\"]\n )" } ], "reviews": [ { "id": 3540997544, "user": "user_3c90b5520ec5", "state": "APPROVED", "body": "LGTM. Thank you [USER_REDACTED]", "submitted_at": "2025-12-04T16:49:32+00:00" }, { "id": 3543472092, "user": "user_bf0b6c7acb9c", "state": "APPROVED", "body": "Just one minor comment. Otherwise, LGTM! Thanks, [USER_REDACTED]!", "submitted_at": "2025-12-05T07:42:57+00:00" }, { "id": 3544768487, "user": "user_5819d17296ee", "state": "COMMENTED", "body": null, "submitted_at": "2025-12-05T13:26:28+00:00" } ], "review_comments": [ { "id": 2589831407, "user": "user_3c90b5520ec5", "body": "Do we need this here considering that this is the default return statement anyways at the end?", "path": "sklearn/utils/_indexing.py", "line": null, "side": "RIGHT", "created_at": "2025-12-04T16:49:04+00:00" }, { "id": 2591712352, "user": "user_bf0b6c7acb9c", "body": "I ran the CI locally with the `else` block commented out, and it passed with CUDA. Even the code mentioned in #32837 compiled without any issues. So I think it's safe to remove it here.", "path": "sklearn/utils/_indexing.py", "line": null, "side": "RIGHT", "created_at": "2025-12-05T07:42:03+00:00" }, { "id": 2592692826, "user": "user_5819d17296ee", "body": "It's logically equivalent to remove those lines because array API inputs can never be tuples or sparse datastructures. I originally found the explicit else close more explicit but it's true that it's redundant. Let's remove it.\n\n```suggestion\n```", "path": "sklearn/utils/_indexing.py", "line": null, "side": "RIGHT", "created_at": "2025-12-05T13:26:28+00:00" } ], "meta": { "languages": [ "py" ], "touches_tests": true, "review_state_summary": { "APPROVED": 2, "COMMENTED": 1 }, "meaningful_comment_count": 3, "has_approval": true, "has_changes_requested": false, "total_review_comments": 3 } } { "_id": "682ddf24de2f189d", "_schema_version": "1.0", "_cleaned_at": "2026-02-12T07:46:52.007714+00:00", "repo": "scikit-learn/scikit-learn", "repo_url": "https://github.com/scikit-learn/scikit-learn", "license_name": "BSD 3-Clause \"New\" or \"Revised\" License", "license_spdx": "BSD-3-Clause", "pr_number": 32839, "title": "MAINT Remove CSS template substitution in estimators' HTML Display", "body": "\n\n#### [NAME_REDACTED]/PRs\n\n#32834\n\n#### What does this implement/fix? Explain your changes.\nMaybe the template/substitution can be avoided. \nThe css doesn't change for each estimator, so why do we need a dynamic selector?\n\nEdit: Removed `#$id` to `estimator.css` to avoid the dynamic behaviour. Added a selector called `css-selector` instead. \nOn `estimator.py` I'm adding a class with the same name - `css-selector`.\nThat way we don't need to substitute the id number, that I believe it's not needed. \nWorked locally with vscode and jupyter notebook.\n\n#### AI usage disclosure\n\nI used AI assistance for:\n- [ ] Code generation (e.g., when writing an implementation or fixing a bug)\n- [ ] Test/benchmark generation\n- [ ] Documentation (including examples)\n- [ ] Research and understanding\n\n#### Any other comments?\n\n", "author": "user_32e669a27072", "created_at": "2025-12-04T13:58:53+00:00", "merged_at": "2026-01-08T06:09:46+00:00", "base_branch": "main", "head_branch": "duplicate", "additions": 50, "deletions": 52, "changed_files": 2, "files": [ { "filename": "sklearn/utils/_repr_html/estimator.css", "status": "modified", "additions": 45, "deletions": 45, "changes": 90, "patch": "@@ -1,4 +1,4 @@\n-#$id {\n+.sk-global {\n /* Definition of color scheme common for light and dark mode */\n --sklearn-color-text: #000;\n --sklearn-color-text-muted: #666;\n@@ -15,30 +15,30 @@\n --sklearn-color-fitted-level-3: cornflowerblue;\n }\n \n-#$id.light {\n+.sk-global.light {\n /* Specific color for light theme */\n --sklearn-color-text-on-default-background: black;\n --sklearn-color-background: white;\n --sklearn-color-border-box: black;\n --sklearn-color-icon: #696969;\n }\n \n-#$id.dark {\n+.sk-global.dark {\n --sklearn-color-text-on-default-background: white;\n --sklearn-color-background: #111;\n --sklearn-color-border-box: white;\n --sklearn-color-icon: #878787;\n }\n \n-#$id {\n+.sk-global {\n color: var(--sklearn-color-text);\n }\n \n-#$id pre {\n+.sk-global pre {\n padding: 0;\n }\n \n-#$id input.sk-hidden--visually {\n+.sk-global input.sk-hidden--visually {\n border: 0;\n clip: rect(1px 1px 1px 1px);\n clip: rect(1px, 1px, 1px, 1px);\n@@ -50,15 +50,15 @@\n width: 1px;\n }\n \n-#$id div.sk-dashed-wrapped {\n+.sk-global div.sk-dashed-wrapped {\n border: 1px dashed var(--sklearn-color-line);\n margin: 0 0.4em 0.5em 0.4em;\n box-sizing: border-box;\n padding-bottom: 0.4em;\n background-color: var(--sklearn-color-background);\n }\n \n-#$id div.sk-container {\n+.sk-global div.sk-container {\n /* jupyter's `normalize.less` sets `[hidden] { display: none; }`\n but bootstrap.min.css set `[hidden] { display: none !important; }`\n so we also need the `!important` here to be able to override the\n@@ -68,7 +68,7 @@\n position: relative;\n }\n \n-#$id div.sk-text-repr-fallback {\n+.sk-global div.sk-text-repr-fallback {\n display: none;\n }\n \n@@ -84,43 +84,43 @@ div.sk-item {\n \n /* Parallel-specific style estimator block */\n \n-#$id div.sk-parallel-item::after {\n+.sk-global div.sk-parallel-item::after {\n content: \"\";\n width: 100%;\n border-bottom: 2px solid var(--sklearn-color-text-on-default-background);\n flex-grow: 1;\n }\n \n-#$id div.sk-parallel {\n+.sk-global div.sk-parallel {\n display: flex;\n align-items: stretch;\n justify-content: center;\n background-color: var(--sklearn-color-background);\n position: relative;\n }\n \n-#$id div.sk-parallel-item {\n+.sk-global div.sk-parallel-item {\n display: flex;\n flex-direction: column;\n }\n \n-#$id div.sk-parallel-item:first-child::after {\n+.sk-global div.sk-parallel-item:first-child::after {\n align-self: flex-end;\n width: 50%;\n }\n \n-#$id div.sk-parallel-item:last-child::after {\n+.sk-global div.sk-parallel-item:last-child::after {\n align-self: flex-start;\n width: 50%;\n }\n \n-#$id div.sk-parallel-item:only-child::after {\n+.sk-global div.sk-parallel-item:only-child::after {\n width: 0;\n }\n \n /* Serial-specific style estimator block */\n \n-#$id div.sk-serial {\n+.sk-global div.sk-serial {\n display: flex;\n flex-direction: column;\n align-items: center;\n@@ -138,14 +138,14 @@ clickable and can be expanded/collapsed.\n \n /* Pipeline and ColumnTransformer style (default) */\n \n-#$id div.sk-toggleable {\n+.sk-global div.sk-toggleable {\n /* Default theme specific background. It is overwritten whether we have a\n specific estimator or a Pipeline/ColumnTransformer */\n background-color: var(--sklearn-color-background);\n }\n \n /* Toggleable label */\n-#$id label.sk-toggleable__label {\n+.sk-global label.sk-toggleable__label {\n cursor: pointer;\n display: flex;\n width: 100%;\n@@ -158,118 +158,118 @@ clickable and can be expanded/collapsed.\n gap: 0.5em;\n }\n \n-#$id label.sk-toggleable__label .caption {\n+.sk-global label.sk-toggleable__label .caption {\n font-size: 0.6rem;\n font-weight: lighter;\n color: var(--sklearn-color-text-muted);\n }\n \n-#$id label.sk-[REDACTED]:before {\n+.sk-global label.sk-[REDACTED]:before {\n /* Arrow on the left of the label */\n content: \"▸\";\n float: left;\n margin-right: 0.25em;\n color: var(--sklearn-color-icon);\n }\n \n-#$id label.sk-[REDACTED]:hover:before {\n+.sk-global label.sk-[REDACTED]:hover:before {\n color: var(--sklearn-color-text);\n }\n \n /* Toggleable content - dropdown */\n \n-#$id div.sk-toggleable__content {\n+.sk-global div.sk-toggleable__content {\n display: none;\n text-align: left;\n /* unfitted */\n background-color: var(--sklearn-color-unfitted-level-0);\n }\n \n-#$id div.sk-toggleable__content.fitted {\n+.sk-global div.sk-toggleable__content.fitted {\n /* fitted */\n background-color: var(--sklearn-color-fitted-level-0);\n }\n \n-#$id div.sk-toggleable__content pre {\n+.sk-global div.sk-toggleable__content pre {\n margin: 0.2em;\n border-radius: 0.25em;\n color: var(--sklearn-color-text);\n /* unfitted */\n background-color: var(--sklearn-color-unfitted-level-0);\n }\n \n-#$id div.sk-toggleable__content.fitted pre {\n+.sk-global div.sk-toggleable__content.fitted pre {\n /* unfitted */\n background-color: var(--sklearn-color-fitted-level-0);\n }\n \n-#$id input.sk-toggleable__control:checked~div.sk-toggleable__content {\n+.sk-global input.sk-toggleable__control:checked~div.sk-toggleable__content {\n /* Expand drop-down */\n display: block;\n width: 100%;\n overflow: visible;\n }\n \n-#$id input.sk-toggleable__control:checked~label.sk-[REDACTED]:before {\n+.sk-global input.sk-toggleable__control:checked~label.sk-[REDACTED]:before {\n content: \"▾\";\n }\n \n /* Pipeline/ColumnTransformer-specific style */\n \n-#$id div.sk-label input.sk-toggleable__control:checked~label.sk-toggleable__label {\n+.sk-global div.sk-label input.sk-toggleable__control:checked~label.sk-toggleable__label {\n color: var(--sklearn-color-text);\n background-color: var(--sklearn-color-unfitted-level-2);\n }\n \n-#$id div.sk-label.fitted input.sk-toggleable__control:checked~label.sk-toggleable__label {\n+.sk-global div.sk-label.fitted input.sk-toggleable__control:checked~label.sk-toggleable__label {\n background-color: var(--sklearn-color-fitted-level-2);\n }\n \n /* Estimator-specific style */\n \n /* Colorize estimator box */\n-#$id div.sk-estimator input.sk-toggleable__control:checked~label.sk-toggleable__label {\n+.sk-global div.sk-estimator input.sk-toggleable__control:checked~label.sk-toggleable__label {\n /* unfitted */\n background-color: var(--sklearn-color-unfitted-level-2);\n }\n \n-#$id div.sk-estimator.fitted input.sk-toggleable__control:checked~label.sk-toggleable__label {\n+.sk-global div.sk-estimator.fitted input.sk-toggleable__control:checked~label.sk-toggleable__label {\n /* fitted */\n background-color: var(--sklearn-color-fitted-level-2);\n }\n \n-#$id div.sk-label label.sk-toggleable__label,\n-#$id div.sk-label label {\n+.sk-global div.sk-label label.sk-toggleable__label,\n+.sk-global div.sk-label label {\n /* The background is the default theme color */\n color: var(--sklearn-color-text-on-default-background);\n }\n \n /* On hover, darken the color of the background */\n-#$id div.sk-label:hover label.sk-toggleable__label {\n+.sk-global div.sk-label:hover label.sk-toggleable__label {\n color: var(--sklearn-color-text);\n background-color: var(--sklearn-color-unfitted-level-2);\n }\n \n /* Label box, darken color on hover, fitted */\n-#$id div.sk-label.fitted:hover label.sk-toggleable__label.fitted {\n+.sk-global div.sk-label.fitted:hover label.sk-toggleable__label.fitted {\n color: var(--sklearn-color-text);\n background-color: var(--sklearn-color-fitted-level-2);\n }\n \n /* Estimator label */\n \n-#$id div.sk-label label {\n+.sk-global div.sk-label label {\n font-family: monospace;\n font-weight: bold;\n line-height: 1.2em;\n }\n \n-#$id div.sk-label-container {\n+.sk-global div.sk-label-container {\n text-align: center;\n }\n \n /* Estimator-specific */\n-#$id div.sk-estimator {\n+.sk-global div.sk-estimator {\n font-family: monospace;\n border: 1px dotted var(--sklearn-color-border-box);\n border-radius: 0.25em;\n@@ -279,18 +279,18 @@ clickable and can be expanded/collapsed.\n background-color: var(--sklearn-color-unfitted-level-0);\n }\n \n-#$id div.sk-estimator.fitted {\n+.sk-global div.sk-estimator.fitted {\n /* fitted */\n background-color: var(--sklearn-color-fitted-level-0);\n }\n \n /* on hover */\n-#$id div.sk-estimator:hover {\n+.sk-global div.sk-estimator:hover {\n /* unfitted */\n background-color: var(--sklearn-color-unfitted-level-2);\n }\n \n-#$id div.sk-estimator.fitted:hover {\n+.sk-global div.sk-estimator.fitted:hover {\n /* fitted */\n background-color: var(--sklearn-color-fitted-level-2);\n }\n@@ -381,7 +381,7 @@ div.sk-label-container:hover .sk-estimator-doc-link.fitted:hover,\n \n /* \"?\"-specific style due to the `` HTML tag */\n \n-#$id a.estimator_doc_link {\n+.sk-global a.estimator_doc_link {\n float: right;\n font-size: 1rem;\n line-height: 1em;\n@@ -396,22 +396,22 @@ div.sk-label-container:hover .sk-estimator-doc-link.fitted:hover,\n border: var(--sklearn-color-unfitted-level-1) 1pt solid;\n }\n \n-#$id a.estimator_doc_link.fitted {\n+.sk-global a.estimator_doc_link.fitted {\n /* fitted */\n background-color: var(--sklearn-color-fitted-level-0);\n border: var(--sklearn-color-fitted-level-1) 1pt solid;\n color: var(--sklearn-color-fitted-level-1);\n }\n \n /* On hover */\n-#$id a.estimator_doc_link:hover {\n+.sk-global a.estimator_doc_link:hover {\n /* unfitted */\n background-color: var(--sklearn-color-unfitted-level-3);\n color: var(--sklearn-color-background);\n text-decoration: none;\n }\n \n-#$id a.estimator_doc_link.fitted:hover {\n+.sk-global a.estimator_doc_link.fitted:hover {\n /* fitted */\n background-color: var(--sklearn-color-fitted-level-3);\n }" }, { "filename": "sklearn/utils/_repr_html/estimator.py", "status": "modified", "additions": 5, "deletions": 7, "changes": 12, "patch": "@@ -6,7 +6,6 @@\n from inspect import isclass\n from io import StringIO\n from pathlib import Path\n-from string import Template\n \n from sklearn import config_context\n \n@@ -203,7 +202,8 @@ def _write_label_html(\n )\n \n fmt_str = (\n- f'{label_html}
      '\n@@ -424,7 +424,7 @@ def estimator_html_repr(estimator):\n >>> from sklearn.utils._repr_html.estimator import estimator_html_repr\n >>> from sklearn.linear_model import LogisticRegression\n >>> estimator_html_repr(LogisticRegression())\n- '\"\n+ f\"\"\n f\"\"\n- f'
      '\n+ f'
      '\n '
      '\n f\"
      {html.escape(estimator_str)}
      {fallback_msg}\"\n \"
      \"" } ], "reviews": [ { "id": 3574445319, "user": "user_04b4a5f4e2a8", "state": "COMMENTED", "body": "From memory, I had the `$id` because I did not know how dynamic the CSS would be in the future. For example, lets say we had a CSS very specific to a particular estimator, then the `id` prevents that CSS from impacting all the other estimators.\n\nFrom looking at the code now, I do not think thats the case, so I'm okay with a global selector.\n\n(An interesting follow is to only write the CSS on the **first** repr call that is also in Jupyter, so it does not get copied over and over again.)", "submitted_at": "2025-12-13T15:54:37+00:00" }, { "id": 3604279118, "user": "user_32e669a27072", "state": "COMMENTED", "body": null, "submitted_at": "2025-12-22T14:24:23+00:00" }, { "id": 3627790004, "user": "user_417fbbcd2f03", "state": "APPROVED", "body": "So it looks good from what I read here. Next steps would be to implement the shadow DOM.\n\nInterestingly, I saw that even with a shadow DOM in `skrub`, the rendering is broken in Marimo (https://github.com/skrub-data/skrub/issues/1817). It is something to have a look at when implementing such option.", "submitted_at": "2026-01-05T17:32:11+00:00" }, { "id": 3629027920, "user": "user_04b4a5f4e2a8", "state": "COMMENTED", "body": null, "submitted_at": "2026-01-06T01:48:08+00:00" }, { "id": 3630555619, "user": "user_32e669a27072", "state": "COMMENTED", "body": null, "submitted_at": "2026-01-06T11:26:03+00:00" }, { "id": 3630573433, "user": "user_32e669a27072", "state": "COMMENTED", "body": null, "submitted_at": "2026-01-06T11:32:36+00:00" }, { "id": 3630661256, "user": "user_32e669a27072", "state": "COMMENTED", "body": null, "submitted_at": "2026-01-06T12:05:30+00:00" }, { "id": 3637843649, "user": "user_04b4a5f4e2a8", "state": "APPROVED", "body": null, "submitted_at": "2026-01-08T06:09:31+00:00" } ], "review_comments": [ { "id": 2616379753, "user": "user_04b4a5f4e2a8", "body": "Can this be prefixed with `sk`, i.e. `.sk-css-selector`? There is the edge case where another library may add CSS to the page with the same name and override our selector.", "path": "sklearn/utils/_repr_html/estimator.css", "line": null, "side": "RIGHT", "created_at": "2025-12-13T15:51:00+00:00" }, { "id": 2640048178, "user": "user_32e669a27072", "body": "This is done. Thanks.", "path": "sklearn/utils/_repr_html/estimator.css", "line": null, "side": "RIGHT", "created_at": "2025-12-22T14:24:23+00:00" }, { "id": 2663310880, "user": "user_04b4a5f4e2a8", "body": "Is it required to have `sk-css-selector` here?", "path": "sklearn/utils/_repr_html/estimator.py", "line": null, "side": "RIGHT", "created_at": "2026-01-06T01:46:53+00:00" }, { "id": 2663312571, "user": "user_04b4a5f4e2a8", "body": "`sk-css-selector` does not really describe what this selector is for, besides that it is a selector. Do you see a better name for this? Some options are: `.sk-root`, `.sk-all` or `.sk-global`.", "path": "sklearn/utils/_repr_html/estimator.css", "line": null, "side": "RIGHT", "created_at": "2026-01-06T01:48:06+00:00" }, { "id": 2664611524, "user": "user_32e669a27072", "body": "I think so. If we remove it, this doesn't work:\n```\n#$id input.sk-hidden--visually {\n border: 0;\n clip: rect(1px 1px 1px 1px);\n clip: rect(1px, 1px, 1px, 1px);\n height: 1px;\n margin: -1px;\n overflow: hidden;\n padding: 0;\n position: absolute;\n width: 1px;\n}\n```\n[That code is here](https://github.com/[USER_REDACTED]n/scikit-learn/blob/173b8d51ecd9586dba2559e3389609ed5cd66f61/sklearn/utils/_repr_html/estimator.css#L41)", "path": "sklearn/utils/_repr_html/estimator.py", "line": null, "side": "RIGHT", "created_at": "2026-01-06T11:26:03+00:00" }, { "id": 2664627837, "user": "user_32e669a27072", "body": "... I did try to remove it anyway and adjusted the css but I couldn't make it work. Unless I'm missing something.", "path": "sklearn/utils/_repr_html/estimator.py", "line": null, "side": "RIGHT", "created_at": "2026-01-06T11:32:36+00:00" }, { "id": 2664709950, "user": "user_32e669a27072", "body": "Thanks. I changed it.", "path": "sklearn/utils/_repr_html/estimator.css", "line": null, "side": "RIGHT", "created_at": "2026-01-06T12:05:30+00:00" } ], "meta": { "languages": [ "css", "py" ], "touches_tests": false, "review_state_summary": { "COMMENTED": 6, "APPROVED": 2 }, "meaningful_comment_count": 7, "has_approval": true, "has_changes_requested": false, "total_review_comments": 7 } } { "_id": "3877411b4e6e49c3", "_schema_version": "1.0", "_cleaned_at": "2026-02-12T07:46:52.007714+00:00", "repo": "scikit-learn/scikit-learn", "repo_url": "https://github.com/scikit-learn/scikit-learn", "license_name": "BSD 3-Clause \"New\" or \"Revised\" License", "license_spdx": "BSD-3-Clause", "pr_number": 32838, "title": "FIX Make `get_namespace` handle pandas dataframe input", "body": "#### [NAME_REDACTED]/PRs\nCloses #32836\n\n\n#### What does this implement/fix? Explain your changes.\n\nA pandas DataFrame or Series does not have a namespace associated to it in the array API. As such we should filter it out, like we do for sparse arrays, before trying to determine the namespace. This means that for `get_namespace(a_df)` (with array API enabled) we get the NumPy compat namespace back as `xp`. I think this makes sense.\n\n#### AI usage disclosure\n\nI used AI assistance for:\n- [x] Code generation (e.g., when writing an implementation or fixing a bug)\n\t- Cursor's tab complete helped adapt the test cases from `test_get_namespace_ndarray_with_dispatch` which I used as starting point\n\n#### Any other comments?\n\nHow do we solve the problem that we can't import `_is_pandas_df_or_series` from `sklearn.utils.validation` as it causes a circular import. Duplicating it feels a bit weird, but I can't think of a great alternative. We could use `hasattr(array, \"iloc\")` to detect \"pandas-ness\"?\n\nBefore discussing how we best detect \"pandas-ness\" we should agree that filtering `DataFrame` and `Series`out (like sparse arrays) is the right approach.\n\ncc [USER_REDACTED]", "author": "user_d5b9cb906259", "created_at": "2025-12-04T13:38:00+00:00", "merged_at": "2025-12-05T16:59:36+00:00", "base_branch": "main", "head_branch": "fix-get_namespace-for-df", "additions": 267, "deletions": 141, "changed_files": 13, "files": [ { "filename": "doc/whats_new/upcoming_changes/array-api/32838.fix.rst", "status": "added", "additions": 2, "deletions": 0, "changes": 2, "patch": "@@ -0,0 +1,2 @@\n+- Estimators with array API support no longer reject dataframe inputs when array API support is enabled.\n+ By :user:`[NAME_REDACTED] `" }, { "filename": "sklearn/compose/_column_transformer.py", "status": "modified", "additions": 3, "deletions": 3, "changes": 6, "patch": "@@ -20,6 +20,7 @@\n from sklearn.pipeline import _fit_transform_one, _name_estimators, _transform_one\n from sklearn.preprocessing import FunctionTransformer\n from sklearn.utils import Bunch\n+from sklearn.utils._dataframe import is_pandas_df\n from sklearn.utils._indexing import (\n _determine_key_type,\n _get_column_indices,\n@@ -47,7 +48,6 @@\n _check_feature_names_in,\n _check_n_features,\n _get_feature_names,\n- _is_pandas_df,\n _num_samples,\n check_array,\n check_is_fitted,\n@@ -773,7 +773,7 @@ def _validate_output(self, result):\n except ImportError:\n return\n for Xs, name in zip(result, names):\n- if not _is_pandas_df(Xs):\n+ if not is_pandas_df(Xs):\n continue\n for col_name, dtype in Xs.dtypes.to_dict().items():\n if getattr(dtype, \"na_value\", None) is not pd.NA:\n@@ -1064,7 +1064,7 @@ def transform(self, X, **params):\n # were not present in fit time, and the order of the columns doesn't\n # matter.\n fit_dataframe_and_transform_dataframe = hasattr(self, \"feature_names_in_\") and (\n- _is_pandas_df(X) or hasattr(X, \"__dataframe__\")\n+ is_pandas_df(X) or hasattr(X, \"__dataframe__\")\n )\n \n n_samples = _num_samples(X)" }, { "filename": "sklearn/ensemble/_hist_gradient_boosting/gradient_boosting.py", "status": "modified", "additions": 2, "deletions": 2, "changes": 4, "patch": "@@ -40,6 +40,7 @@\n from sklearn.model_selection import train_test_split\n from sklearn.preprocessing import FunctionTransformer, LabelEncoder, OrdinalEncoder\n from sklearn.utils import check_random_state, compute_sample_weight, resample\n+from sklearn.utils._dataframe import is_pandas_df\n from sklearn.utils._missing import is_scalar_nan\n from sklearn.utils._openmp_helpers import _openmp_effective_n_threads\n from sklearn.utils._param_validation import Interval, RealNotInt, StrOptions\n@@ -48,7 +49,6 @@\n _check_monotonic_cst,\n _check_sample_weight,\n _check_y,\n- _is_pandas_df,\n check_array,\n check_consistent_length,\n check_is_fitted,\n@@ -371,7 +371,7 @@ def _check_categorical_features(self, X):\n # fixed in main and maybe included in 2.2.1, see\n # https://github.com/[USER_REDACTED]ndas-dev/pandas/pull/57173.\n # Also pandas versions < 1.5.1 do not support the dataframe interchange\n- if _is_pandas_df(X):\n+ if is_pandas_df(X):\n X_is_dataframe = True\n categorical_columns_mask = np.asarray(X.dtypes == \"category\")\n elif hasattr(X, \"__dataframe__\"):" }, { "filename": "sklearn/feature_selection/_base.py", "status": "modified", "additions": 2, "deletions": 2, "changes": 4, "patch": "@@ -12,11 +12,11 @@\n \n from sklearn.base import TransformerMixin\n from sklearn.utils import _safe_indexing, check_array, safe_sqr\n+from sklearn.utils._dataframe import is_pandas_df\n from sklearn.utils._set_output import _get_output_config\n from sklearn.utils._tags import get_tags\n from sklearn.utils.validation import (\n _check_feature_names_in,\n- _is_pandas_df,\n check_is_fitted,\n validate_data,\n )\n@@ -100,7 +100,7 @@ def transform(self, X):\n # Preserve X when X is a dataframe and the output is configured to\n # be pandas.\n output_config_dense = _get_output_config(\"transform\", estimator=self)[\"dense\"]\n- preserve_X = output_config_dense != \"default\" and _is_pandas_df(X)\n+ preserve_X = output_config_dense != \"default\" and is_pandas_df(X)\n \n # note: we use get_tags instead of __sklearn_tags__ because this is a\n # public Mixin." }, { "filename": "sklearn/inspection/_plot/decision_boundary.py", "status": "modified", "additions": 2, "deletions": 3, "changes": 5, "patch": "@@ -8,13 +8,12 @@\n from sklearn.base import is_regressor\n from sklearn.preprocessing import LabelEncoder\n from sklearn.utils import _safe_indexing\n+from sklearn.utils._dataframe import is_pandas_df, is_polars_df\n from sklearn.utils._optional_dependencies import check_matplotlib_support\n from sklearn.utils._response import _get_response_values\n from sklearn.utils._set_output import _get_adapter_from_container\n from sklearn.utils.validation import (\n _is_arraylike_not_scalar,\n- _is_pandas_df,\n- _is_polars_df,\n _num_features,\n check_is_fitted,\n )\n@@ -496,7 +495,7 @@ def from_estimator(\n )\n \n X_grid = np.c_[xx0.ravel(), xx1.ravel()]\n- if _is_pandas_df(X) or _is_polars_df(X):\n+ if is_pandas_df(X) or is_polars_df(X):\n adapter = _get_adapter_from_container(X)\n X_grid = adapter.create_container(\n X_grid," }, { "filename": "sklearn/preprocessing/_function_transformer.py", "status": "modified", "additions": 3, "deletions": 4, "changes": 7, "patch": "@@ -7,6 +7,7 @@\n import numpy as np\n \n from sklearn.base import BaseEstimator, TransformerMixin, _fit_context\n+from sklearn.utils._dataframe import is_pandas_df, is_polars_df\n from sklearn.utils._param_validation import StrOptions\n from sklearn.utils._repr_html.estimator import _VisualBlock\n from sklearn.utils._set_output import _get_adapter_from_container, _get_output_config\n@@ -15,8 +16,6 @@\n _allclose_dense_sparse,\n _check_feature_names_in,\n _get_feature_names,\n- _is_pandas_df,\n- _is_polars_df,\n check_array,\n validate_data,\n )\n@@ -302,9 +301,9 @@ def transform(self, X):\n \"a {0} DataFrame to follow the `set_output` API or `feature_names_out`\"\n \" should be defined.\"\n )\n- if output_config == \"pandas\" and not _is_pandas_df(out):\n+ if output_config == \"pandas\" and not is_pandas_df(out):\n warnings.warn(warn_msg.format(\"pandas\"))\n- elif output_config == \"polars\" and not _is_polars_df(out):\n+ elif output_config == \"polars\" and not is_polars_df(out):\n warnings.warn(warn_msg.format(\"polars\"))\n \n return out" }, { "filename": "sklearn/utils/_array_api.py", "status": "modified", "additions": 3, "deletions": 0, "changes": 3, "patch": "@@ -16,6 +16,7 @@\n from sklearn.externals import array_api_compat\n from sklearn.externals import array_api_extra as xpx\n from sklearn.externals.array_api_compat import numpy as np_compat\n+from sklearn.utils._dataframe import is_df_or_series\n from sklearn.utils.fixes import parse_version\n \n # TODO: complete __all__\n@@ -320,6 +321,8 @@ def _remove_non_arrays(*arrays, remove_none=True, remove_types=(str,)):\n continue\n if sp.issparse(array):\n continue\n+ if is_df_or_series(array):\n+ continue\n filtered_arrays.append(array)\n \n return filtered_arrays" }, { "filename": "sklearn/utils/_dataframe.py", "status": "added", "additions": 123, "deletions": 0, "changes": 123, "patch": "@@ -0,0 +1,123 @@\n+\"\"\"Functions to determine if an object is a dataframe or series.\"\"\"\n+\n+# Authors: The scikit-learn developers\n+# SPDX-License-Identifier: BSD-3-Clause\n+\n+import sys\n+\n+\n+def is_df_or_series(X):\n+ \"\"\"[NAME_REDACTED] if the X is a dataframe or series.\n+\n+ Parameters\n+ ----------\n+ X : {array-like, dataframe}\n+ The array-like or dataframe object to check.\n+\n+ Returns\n+ -------\n+ bool\n+ True if the X is a dataframe or series, False otherwise.\n+ \"\"\"\n+ return is_pandas_df_or_series(X) or is_polars_df_or_series(X) or is_pyarrow_data(X)\n+\n+\n+def is_pandas_df_or_series(X):\n+ \"\"\"[NAME_REDACTED] if the X is a pandas dataframe or series.\n+\n+ Parameters\n+ ----------\n+ X : {array-like, dataframe}\n+ The array-like or dataframe object to check.\n+\n+ Returns\n+ -------\n+ bool\n+ True if the X is a pandas dataframe or series, False otherwise.\n+ \"\"\"\n+ try:\n+ pd = sys.modules[\"pandas\"]\n+ except KeyError:\n+ return False\n+ return isinstance(X, (pd.DataFrame, pd.Series))\n+\n+\n+def is_pandas_df(X):\n+ \"\"\"[NAME_REDACTED] if the X is a pandas dataframe.\n+\n+ Parameters\n+ ----------\n+ X : {array-like, dataframe}\n+ The array-like or dataframe object to check.\n+\n+ Returns\n+ -------\n+ bool\n+ True if the X is a pandas dataframe, False otherwise.\n+ \"\"\"\n+ try:\n+ pd = sys.modules[\"pandas\"]\n+ except KeyError:\n+ return False\n+ return isinstance(X, pd.DataFrame)\n+\n+\n+def is_pyarrow_data(X):\n+ \"\"\"[NAME_REDACTED] if the X is a pyarrow Table, RecordBatch, Array or ChunkedArray.\n+\n+ Parameters\n+ ----------\n+ X : {array-like, dataframe}\n+ The array-like or dataframe object to check.\n+\n+ Returns\n+ -------\n+ bool\n+ True if the X is a pyarrow Table, RecordBatch, Array or ChunkedArray,\n+ False otherwise.\n+ \"\"\"\n+ try:\n+ pa = sys.modules[\"pyarrow\"]\n+ except KeyError:\n+ return False\n+ return isinstance(X, (pa.Table, pa.RecordBatch, pa.Array, pa.ChunkedArray))\n+\n+\n+def is_polars_df_or_series(X):\n+ \"\"\"[NAME_REDACTED] if the X is a polars dataframe or series.\n+\n+ Parameters\n+ ----------\n+ X : {array-like, dataframe}\n+ The array-like or dataframe object to check.\n+\n+ Returns\n+ -------\n+ bool\n+ True if the X is a polars dataframe or series, False otherwise.\n+ \"\"\"\n+ try:\n+ pl = sys.modules[\"polars\"]\n+ except KeyError:\n+ return False\n+ return isinstance(X, (pl.DataFrame, pl.Series))\n+\n+\n+def is_polars_df(X):\n+ \"\"\"[NAME_REDACTED] if the X is a polars dataframe.\n+\n+ Parameters\n+ ----------\n+ X : {array-like, dataframe}\n+ The array-like or dataframe object to check.\n+\n+ Returns\n+ -------\n+ bool\n+ True if the X is a polarsdataframe, False otherwise.\n+ \"\"\"\n+ try:\n+ pl = sys.modules[\"polars\"]\n+ except KeyError:\n+ return False\n+ return isinstance(X, pl.DataFrame)" }, { "filename": "sklearn/utils/_indexing.py", "status": "modified", "additions": 9, "deletions": 7, "changes": 16, "patch": "@@ -16,15 +16,17 @@\n get_namespace_and_device,\n move_to,\n )\n+from sklearn.utils._dataframe import (\n+ is_pandas_df,\n+ is_polars_df_or_series,\n+ is_pyarrow_data,\n+)\n from sklearn.utils._param_validation import Interval, validate_params\n from sklearn.utils.extmath import _approximate_mode\n from sklearn.utils.fixes import PYARROW_VERSION_BELOW_17\n from sklearn.utils.validation import (\n _check_sample_weight,\n _is_arraylike_not_scalar,\n- _is_pandas_df,\n- _is_polars_df_or_series,\n- _is_pyarrow_data,\n _use_interchange_protocol,\n check_array,\n check_consistent_length,\n@@ -325,21 +327,21 @@ def _safe_indexing(X, indices, *, axis=0):\n if (\n axis == 1\n and indices_dtype == \"str\"\n- and not (_is_pandas_df(X) or _use_interchange_protocol(X))\n+ and not (is_pandas_df(X) or _use_interchange_protocol(X))\n ):\n raise ValueError(\n \"Specifying the columns using strings is only supported for dataframes.\"\n )\n \n if hasattr(X, \"iloc\"):\n- # TODO: we should probably use _is_pandas_df_or_series(X) instead but:\n+ # TODO: we should probably use is_pandas_df_or_series(X) instead but:\n # 1) Currently, it (probably) works for dataframes compliant to pandas' API.\n # 2) Updating would require updating some tests such as\n # test_train_test_split_mock_pandas.\n return _pandas_indexing(X, indices, indices_dtype, axis=axis)\n- elif _is_polars_df_or_series(X):\n+ elif is_polars_df_or_series(X):\n return _polars_indexing(X, indices, indices_dtype, axis=axis)\n- elif _is_pyarrow_data(X):\n+ elif is_pyarrow_data(X):\n return _pyarrow_indexing(X, indices, indices_dtype, axis=axis)\n elif _use_interchange_protocol(X): # pragma: no cover\n # Once the dataframe X is converted into its dataframe interchange protocol" }, { "filename": "sklearn/utils/tests/test_array_api.py", "status": "modified", "additions": 30, "deletions": 0, "changes": 30, "patch": "@@ -43,6 +43,7 @@\n from sklearn.utils._testing import (\n SkipTest,\n _array_api_for_tests,\n+ _convert_container,\n assert_array_equal,\n skip_if_array_api_compat_not_configured,\n )\n@@ -84,6 +85,35 @@ def test_get_namespace_ndarray_with_dispatch():\n assert xp_out is np_compat\n \n \n+[USER_REDACTED]_if_array_api_compat_not_configured\n+[USER_REDACTED].mark.parametrize(\n+ \"constructor_name\", [\"pyarrow\", \"dataframe\", \"polars\", \"series\"]\n+)\n+def test_get_namespace_df_with_dispatch(constructor_name):\n+ \"\"\"Test get_namespace on dataframes and series.\"\"\"\n+\n+ df = _convert_container([[1, 4, 2], [3, 3, 6]], constructor_name)\n+ with config_context(array_api_dispatch=True):\n+ xp_out, is_array_api_compliant = get_namespace(df)\n+ assert not is_array_api_compliant\n+\n+ # When operating on dataframes or series the Numpy namespace is\n+ # the right thing to use.\n+ assert xp_out is np_compat\n+\n+\n+[USER_REDACTED]_if_array_api_compat_not_configured\n+def test_get_namespace_sparse_with_dispatch():\n+ \"\"\"Test get_namespace on sparse arrays.\"\"\"\n+ with config_context(array_api_dispatch=True):\n+ xp_out, is_array_api_compliant = get_namespace(sp.csr_array([[1, 2, 3]]))\n+ assert not is_array_api_compliant\n+\n+ # When operating on sparse arrays the Numpy namespace is\n+ # the right thing to use.\n+ assert xp_out is np_compat\n+\n+\n [USER_REDACTED]_if_array_api_compat_not_configured\n def test_get_namespace_array_api(monkeypatch):\n \"\"\"Test get_namespace for ArrayAPI arrays.\"\"\"" }, { "filename": "sklearn/utils/tests/test_dataframe.py", "status": "added", "additions": 84, "deletions": 0, "changes": 84, "patch": "@@ -0,0 +1,84 @@\n+\"\"\"Tests for dataframe detection functions.\"\"\"\n+\n+import numpy as np\n+import pytest\n+\n+from sklearn._min_dependencies import dependent_packages\n+from sklearn.utils._dataframe import is_df_or_series, is_pandas_df, is_polars_df\n+from sklearn.utils._testing import _convert_container\n+\n+\n+[USER_REDACTED].mark.parametrize(\"constructor_name\", [\"pyarrow\", \"dataframe\", \"polars\"])\n+def test_is_df_or_series(constructor_name):\n+ df = _convert_container([[1, 4, 2], [3, 3, 6]], constructor_name)\n+\n+ assert is_df_or_series(df)\n+ assert not is_df_or_series(np.asarray([1, 2, 3]))\n+\n+\n+[USER_REDACTED].mark.parametrize(\"constructor_name\", [\"pyarrow\", \"dataframe\", \"polars\"])\n+def test_is_pandas_df_other_libraries(constructor_name):\n+ df = _convert_container([[1, 4, 2], [3, 3, 6]], constructor_name)\n+ if constructor_name in (\"pyarrow\", \"polars\"):\n+ assert not is_pandas_df(df)\n+ else:\n+ assert is_pandas_df(df)\n+\n+\n+def test_is_pandas_df():\n+ \"\"\"Check behavior of is_pandas_df when pandas is installed.\"\"\"\n+ pd = pytest.importorskip(\"pandas\")\n+ df = pd.DataFrame([[1, 2, 3]])\n+ assert is_pandas_df(df)\n+ assert not is_pandas_df(np.asarray([1, 2, 3]))\n+ assert not is_pandas_df(1)\n+\n+\n+def test_is_pandas_df_pandas_not_installed(hide_available_pandas):\n+ \"\"\"Check is_pandas_df when pandas is not installed.\"\"\"\n+\n+ assert not is_pandas_df(np.asarray([1, 2, 3]))\n+ assert not is_pandas_df(1)\n+\n+\n+[USER_REDACTED].mark.parametrize(\n+ \"constructor_name, minversion\",\n+ [\n+ (\"pyarrow\", dependent_packages[\"pyarrow\"][0]),\n+ (\"dataframe\", dependent_packages[\"pandas\"][0]),\n+ (\"polars\", dependent_packages[\"polars\"][0]),\n+ ],\n+)\n+def test_is_polars_df_other_libraries(constructor_name, minversion):\n+ df = _convert_container(\n+ [[1, 4, 2], [3, 3, 6]],\n+ constructor_name,\n+ minversion=minversion,\n+ )\n+ if constructor_name in (\"pyarrow\", \"dataframe\"):\n+ assert not is_polars_df(df)\n+ else:\n+ assert is_polars_df(df)\n+\n+\n+def test_is_polars_df_for_duck_typed_polars_dataframe():\n+ \"\"\"Check is_polars_df for object that looks like a polars dataframe\"\"\"\n+\n+ class NotAPolarsDataFrame:\n+ def __init__(self):\n+ self.columns = [1, 2, 3]\n+ self.schema = \"my_schema\"\n+\n+ not_a_polars_df = NotAPolarsDataFrame()\n+ assert not is_polars_df(not_a_polars_df)\n+\n+\n+def test_is_polars_df():\n+ \"\"\"Check that is_polars_df return False for non-dataframe objects.\"\"\"\n+\n+ class LooksLikePolars:\n+ def __init__(self):\n+ self.columns = [\"a\", \"b\"]\n+ self.schema = [\"a\", \"b\"]\n+\n+ assert not is_polars_df(LooksLikePolars())" }, { "filename": "sklearn/utils/tests/test_validation.py", "status": "modified", "additions": 0, "deletions": 71, "changes": 71, "patch": "@@ -14,7 +14,6 @@\n \n import sklearn\n from sklearn._config import config_context\n-from sklearn._min_dependencies import dependent_packages\n from sklearn.base import BaseEstimator\n from sklearn.datasets import make_blobs\n from sklearn.ensemble import RandomForestRegressor\n@@ -77,8 +76,6 @@\n _estimator_has,\n _get_feature_names,\n _is_fitted,\n- _is_pandas_df,\n- _is_polars_df,\n _num_features,\n _num_samples,\n _to_object_array,\n@@ -1995,63 +1992,6 @@ def test_get_feature_names_dataframe_protocol(constructor_name, minversion):\n assert_array_equal(feature_names, columns)\n \n \n-[USER_REDACTED].mark.parametrize(\"constructor_name\", [\"pyarrow\", \"dataframe\", \"polars\"])\n-def test_is_pandas_df_other_libraries(constructor_name):\n- df = _convert_container([[1, 4, 2], [3, 3, 6]], constructor_name)\n- if constructor_name in (\"pyarrow\", \"polars\"):\n- assert not _is_pandas_df(df)\n- else:\n- assert _is_pandas_df(df)\n-\n-\n-def test_is_pandas_df():\n- \"\"\"Check behavior of is_pandas_df when pandas is installed.\"\"\"\n- pd = pytest.importorskip(\"pandas\")\n- df = pd.DataFrame([[1, 2, 3]])\n- assert _is_pandas_df(df)\n- assert not _is_pandas_df(np.asarray([1, 2, 3]))\n- assert not _is_pandas_df(1)\n-\n-\n-def test_is_pandas_df_pandas_not_installed(hide_available_pandas):\n- \"\"\"Check _is_pandas_df when pandas is not installed.\"\"\"\n-\n- assert not _is_pandas_df(np.asarray([1, 2, 3]))\n- assert not _is_pandas_df(1)\n-\n-\n-[USER_REDACTED].mark.parametrize(\n- \"constructor_name, minversion\",\n- [\n- (\"pyarrow\", dependent_packages[\"pyarrow\"][0]),\n- (\"dataframe\", dependent_packages[\"pandas\"][0]),\n- (\"polars\", dependent_packages[\"polars\"][0]),\n- ],\n-)\n-def test_is_polars_df_other_libraries(constructor_name, minversion):\n- df = _convert_container(\n- [[1, 4, 2], [3, 3, 6]],\n- constructor_name,\n- minversion=minversion,\n- )\n- if constructor_name in (\"pyarrow\", \"dataframe\"):\n- assert not _is_polars_df(df)\n- else:\n- assert _is_polars_df(df)\n-\n-\n-def test_is_polars_df_for_duck_typed_polars_dataframe():\n- \"\"\"Check _is_polars_df for object that looks like a polars dataframe\"\"\"\n-\n- class NotAPolarsDataFrame:\n- def __init__(self):\n- self.columns = [1, 2, 3]\n- self.schema = \"my_schema\"\n-\n- not_a_polars_df = NotAPolarsDataFrame()\n- assert not _is_polars_df(not_a_polars_df)\n-\n-\n def test_get_feature_names_numpy():\n \"\"\"Get feature names return None for numpy arrays.\"\"\"\n X = np.array([[1, 2, 3], [4, 5, 6]])\n@@ -2322,17 +2262,6 @@ def test_column_or_1d():\n column_or_1d(y)\n \n \n-def test__is_polars_df():\n- \"\"\"Check that _is_polars_df return False for non-dataframe objects.\"\"\"\n-\n- class LooksLikePolars:\n- def __init__(self):\n- self.columns = [\"a\", \"b\"]\n- self.schema = [\"a\", \"b\"]\n-\n- assert not _is_polars_df(LooksLikePolars())\n-\n-\n def test_check_array_writeable_np():\n \"\"\"Check the behavior of check_array when a writeable array is requested\n without copy if possible, on numpy arrays." }, { "filename": "sklearn/utils/validation.py", "status": "modified", "additions": 4, "deletions": 49, "changes": 53, "patch": "@@ -5,7 +5,6 @@\n \n import numbers\n import operator\n-import sys\n import warnings\n from collections.abc import Sequence\n from contextlib import suppress\n@@ -30,6 +29,7 @@\n get_namespace,\n get_namespace_and_device,\n )\n+from sklearn.utils._dataframe import is_pandas_df, is_pandas_df_or_series\n from sklearn.utils._isfinite import FiniteStatus, cy_isfinite\n from sklearn.utils._tags import get_tags\n from sklearn.utils.fixes import (\n@@ -312,7 +312,7 @@ def _use_interchange_protocol(X):\n to ensure strict behavioral backward compatibility with older versions of\n scikit-learn.\n \"\"\"\n- return not _is_pandas_df(X) and hasattr(X, \"__dataframe__\")\n+ return not is_pandas_df(X) and hasattr(X, \"__dataframe__\")\n \n \n def _num_features(X):\n@@ -1129,7 +1129,7 @@ def is_sparse(dtype):\n # ensure that the output is writeable, even if avoidable, to not overwrite\n # the user's data by surprise.\n \n- if _is_pandas_df_or_series(array_orig):\n+ if is_pandas_df_or_series(array_orig):\n try:\n # In pandas >= 3, np.asarray(df), called earlier in check_array,\n # returns a read-only intermediate array. It can be made writeable\n@@ -2307,51 +2307,6 @@ def _check_method_params(X, params, indices=None):\n return method_params_validated\n \n \n-def _is_pandas_df_or_series(X):\n- \"\"\"[NAME_REDACTED] if the X is a pandas dataframe or series.\"\"\"\n- try:\n- pd = sys.modules[\"pandas\"]\n- except KeyError:\n- return False\n- return isinstance(X, (pd.DataFrame, pd.Series))\n-\n-\n-def _is_pandas_df(X):\n- \"\"\"[NAME_REDACTED] if the X is a pandas dataframe.\"\"\"\n- try:\n- pd = sys.modules[\"pandas\"]\n- except KeyError:\n- return False\n- return isinstance(X, pd.DataFrame)\n-\n-\n-def _is_pyarrow_data(X):\n- \"\"\"[NAME_REDACTED] if the X is a pyarrow Table, RecordBatch, Array or ChunkedArray.\"\"\"\n- try:\n- pa = sys.modules[\"pyarrow\"]\n- except KeyError:\n- return False\n- return isinstance(X, (pa.Table, pa.RecordBatch, pa.Array, pa.ChunkedArray))\n-\n-\n-def _is_polars_df_or_series(X):\n- \"\"\"[NAME_REDACTED] if the X is a polars dataframe or series.\"\"\"\n- try:\n- pl = sys.modules[\"polars\"]\n- except KeyError:\n- return False\n- return isinstance(X, (pl.DataFrame, pl.Series))\n-\n-\n-def _is_polars_df(X):\n- \"\"\"[NAME_REDACTED] if the X is a polars dataframe.\"\"\"\n- try:\n- pl = sys.modules[\"polars\"]\n- except KeyError:\n- return False\n- return isinstance(X, pl.DataFrame)\n-\n-\n def _get_feature_names(X):\n \"\"\"Get feature names from X.\n \n@@ -2375,7 +2330,7 @@ def _get_feature_names(X):\n feature_names = None\n \n # extract feature names for support array containers\n- if _is_pandas_df(X):\n+ if is_pandas_df(X):\n # Make sure we can inspect columns names from pandas, even with\n # versions too old to expose a working implementation of\n # __dataframe__.column_names() and avoid introducing any" } ], "reviews": [ { "id": 3540854581, "user": "user_5819d17296ee", "state": "COMMENTED", "body": "Thanks. I think this is the correct fix but it needs to be generalized, see below.", "submitted_at": "2025-12-04T16:24:31+00:00" }, { "id": 3543479168, "user": "user_d5b9cb906259", "state": "COMMENTED", "body": null, "submitted_at": "2025-12-05T07:44:35+00:00" }, { "id": 3545072951, "user": "user_5819d17296ee", "state": "APPROVED", "body": "LGTM as it is, but feel free to to implement https://github.com/[USER_REDACTED]n/scikit-learn/pull/32838/files#r2591717992 as well.", "submitted_at": "2025-12-05T14:43:03+00:00" } ], "review_comments": [ { "id": 2589733480, "user": "user_5819d17296ee", "body": "We probably need something similar for any type of dataframe/series: pandas, polars, pyarrow.", "path": "sklearn/utils/_array_api.py", "line": 325, "side": "RIGHT", "created_at": "2025-12-04T16:21:57+00:00" }, { "id": 2589736278, "user": "user_5819d17296ee", "body": "I would rather move that to a new `sklearn/utils/_dataframe.py` submodule instead of duplication.", "path": "sklearn/utils/_array_api.py", "line": null, "side": "RIGHT", "created_at": "2025-12-04T16:22:45+00:00" }, { "id": 2589741977, "user": "user_5819d17296ee", "body": "```suggestion\n if _is_any_supported_df_or_series(array):\n```", "path": "sklearn/utils/_array_api.py", "line": null, "side": "RIGHT", "created_at": "2025-12-04T16:24:20+00:00" }, { "id": 2591717992, "user": "user_d5b9cb906259", "body": "Investigate parametrizing this on pandas, pyarrow, polars instead of having one test per dataframe library.", "path": "sklearn/utils/tests/test_array_api.py", "line": null, "side": "RIGHT", "created_at": "2025-12-05T07:44:35+00:00" } ], "meta": { "languages": [ "py", "rst" ], "touches_tests": true, "review_state_summary": { "COMMENTED": 2, "APPROVED": 1 }, "meaningful_comment_count": 4, "has_approval": true, "has_changes_requested": false, "total_review_comments": 4 } } { "_id": "6bbccfdc5880efbe", "_schema_version": "1.0", "_cleaned_at": "2026-02-12T07:46:52.007714+00:00", "repo": "scikit-learn/scikit-learn", "repo_url": "https://github.com/scikit-learn/scikit-learn", "license_name": "BSD 3-Clause \"New\" or \"Revised\" License", "license_spdx": "BSD-3-Clause", "pr_number": 32832, "title": "CI: Make one tracking isssue per build for the unit-tests GHA", "body": "\n\n#### [NAME_REDACTED]/PRs\n\n\nAddresses this comment : https://github.com/[USER_REDACTED]n/scikit-learn/pull/32797#issuecomment-3589914268\n\n#### What does this implement/fix? Explain your changes.\n\nInstead of opening a single issue if any of the tests in the matrix failed, now independent issues for each matrix entry are generated. \n\nAlso allow the update tracking issue action to trigger on manually triggered actions.\n\n#### AI usage disclosure\n\nI used AI assistance for:\n- [x] Code generation (e.g., when writing an implementation or fixing a bug)\n- [ ] Test/benchmark generation\n- [ ] Documentation (including examples)\n- [x] Research and understanding\n\n#### Any other comments?\n\nIt is a bit more complex to achieve than what I anticipated. I could not do it using a job running after all the matrix jobs of unit-tests, as github does not allow to access all outptuts of a matrix of jobs, so only a global status of the whole matrix (\"success\" if all jobs succeeded, \"failure\" if at least one failed) can be obtained in another job. \n\nThus I had to use an extra step in the unit-tests job, but using another workflow (i.e. `uses: ./.github/workflows/update_tracking_issue.yml`) cannot be done as a step, only as a job, so I had to re-implement it, creating some code duplication. But it also allowed to tweak the CI log URL to point to the log of the specific job rather than the whole workflow. And since github does not expose the job id necessary for this URL, I also had to add a step to get this id using the REST API. \n\nI tested it on my fork, for example it created and commented https://github.com/[USER_REDACTED]ncoisPgm/scikit-learn/issues/23\n", "author": "user_afd8fdca88a2", "created_at": "2025-12-03T15:35:23+00:00", "merged_at": "2025-12-17T17:09:19+00:00", "base_branch": "main", "head_branch": "one_issue_per_build", "additions": 50, "deletions": 14, "changed_files": 3, "files": [ { "filename": ".github/workflows/unit-tests.yml", "status": "modified", "additions": 19, "deletions": 8, "changes": 27, "patch": "@@ -205,11 +205,22 @@ jobs:\n token: ${{ secrets.CODECOV_TOKEN }}\n disable_search: true\n \n- update-tracker:\n- uses: ./.github/workflows/update_tracking_issue.yml\n- if: ${{ always() }}\n- needs: [unit-tests]\n- with:\n- job_status: ${{ needs.unit-tests.result }}\n- secrets:\n- BOT_GITHUB_TOKEN: ${{ secrets.BOT_GITHUB_TOKEN }}\n+ - name: Update tracking issue\n+ if: ${{ always() && (github.event_name == 'schedule' || github.event_name == 'workflow_dispatch')}}\n+ run: |\n+ set -ex\n+ if [[ ${{ job.status }} == \"success\" ]]; then\n+ TESTS_PASSED=true\n+ else\n+ TESTS_PASSED=false\n+ fi\n+\n+ pip install defusedxml PyGithub\n+ python maint_tools/update_tracking_issue.py \\\n+ ${{ secrets.BOT_GITHUB_TOKEN }} \\\n+ \"$GITHUB_WORKFLOW ${{ matrix.name }}\" \\\n+ \"$GITHUB_REPOSITORY\" \\\n+ https://github.com/$GITHUB_REPOSITORY/actions/runs/$GITHUB_RUN_ID \\\n+ --tests-passed $TESTS_PASSED \\\n+ --auto-close false \\\n+ --job-name \"${{ matrix.name }}\"" }, { "filename": ".github/workflows/update_tracking_issue.yml", "status": "modified", "additions": 1, "deletions": 1, "changes": 2, "patch": "@@ -27,7 +27,7 @@ on:\n jobs:\n update_tracking_issue:\n runs-on: ubuntu-latest\n- if: github.repository == 'scikit-learn/scikit-learn' && github.event_name == 'schedule'\n+ if: github.repository == 'scikit-learn/scikit-learn' && (github.event_name == 'schedule' || github.event_name == 'workflow_dispatch')\n steps:\n - uses: actions/checkout@v5\n - uses: actions/setup-python@v6" }, { "filename": "maint_tools/update_tracking_issue.py", "status": "modified", "additions": 30, "deletions": 5, "changes": 35, "patch": "@@ -13,6 +13,7 @@\n \n import argparse\n import sys\n+import warnings\n from datetime import datetime, timezone\n from pathlib import Path\n \n@@ -28,12 +29,21 @@\n parser.add_argument(\"ci_name\", help=\"Name of CI run instance\")\n parser.add_argument(\"issue_repo\", help=\"Repo to track issues\")\n parser.add_argument(\"link_to_ci_run\", help=\"URL to link to\")\n+parser.add_argument(\n+ \"--job-name\",\n+ help=(\n+ \"Name of the job. If provided the job ID will be added to the log URL so that\"\n+ \" it points to log of the job and not the whole workflow.\"\n+ ),\n+ default=None,\n+)\n parser.add_argument(\"--junit-file\", help=\"JUnit file to determine if tests passed\")\n parser.add_argument(\n \"--tests-passed\",\n help=(\n \"If --tests-passed is true, then the original issue is closed if the issue \"\n- \"exists. If tests-passed is false, then the an issue is updated or created.\"\n+ \"exists, unless --auto-close is set to false. If tests-passed is false, then \"\n+ \"the issue is updated or created.\"\n ),\n )\n parser.add_argument(\n@@ -62,6 +72,23 @@\n title_query = f\"CI failed on {args.ci_name}\"\n title = f\"⚠️ {title_query} (last failure: {date_str}) ⚠️\"\n \n+url = args.link_to_ci_run\n+\n+if args.job_name is not None:\n+ run_id = int(args.link_to_ci_run.split(\"/\")[-1])\n+ workflow_run = issue_repo.get_workflow_run(run_id)\n+ jobs = workflow_run.jobs()\n+\n+ for job in jobs:\n+ if job.name == args.job_name:\n+ url = f\"{url}/job/{job.id}\"\n+ break\n+ else:\n+ warnings.warn(\n+ f\"Job '{args.job_name}' not found, the URL in the issue will link to the\"\n+ \" whole workflow's log rather than the job's one.\"\n+ )\n+\n \n def get_issue():\n login = gh.get_user().login\n@@ -76,7 +103,7 @@ def get_issue():\n \n def create_or_update_issue(body=\"\"):\n # Interact with GitHub API to create issue\n- link = f\"[{args.ci_name}]({args.link_to_ci_run})\"\n+ link = f\"[{args.ci_name}]({url})\"\n issue = get_issue()\n \n max_body_length = 60_000\n@@ -107,9 +134,7 @@ def close_issue_if_opened():\n issue = get_issue()\n if issue is not None:\n header_str = \"## CI is no longer failing!\"\n- comment_str = (\n- f\"{header_str} ✅\\n\\n[Successful run]({args.link_to_ci_run}) on {date_str}\"\n- )\n+ comment_str = f\"{header_str} ✅\\n\\n[Successful run]({url}) on {date_str}\"\n \n print(f\"Commented on issue #{issue.number}\")\n # New comment if \"## CI is no longer failing!\" comment does not exist" } ], "reviews": [ { "id": 3577057444, "user": "user_fca2535bcd49", "state": "COMMENTED", "body": null, "submitted_at": "2025-12-15T08:46:32+00:00" }, { "id": 3577673457, "user": "user_afd8fdca88a2", "state": "COMMENTED", "body": null, "submitted_at": "2025-12-15T11:22:47+00:00" }, { "id": 3577834691, "user": "user_fca2535bcd49", "state": "COMMENTED", "body": null, "submitted_at": "2025-12-15T12:12:13+00:00" }, { "id": 3587904990, "user": "user_afd8fdca88a2", "state": "COMMENTED", "body": null, "submitted_at": "2025-12-17T14:02:26+00:00" }, { "id": 3588209521, "user": "user_fca2535bcd49", "state": "COMMENTED", "body": "I think moving the logic to the Python script was a good move. Minor comments, and this can go in, thanks!", "submitted_at": "2025-12-17T15:23:18+00:00" }, { "id": 3588288714, "user": "user_fca2535bcd49", "state": "COMMENTED", "body": null, "submitted_at": "2025-12-17T15:27:21+00:00" }, { "id": 3588332930, "user": "user_afd8fdca88a2", "state": "COMMENTED", "body": null, "submitted_at": "2025-12-17T15:36:05+00:00" }, { "id": 3588342383, "user": "user_afd8fdca88a2", "state": "COMMENTED", "body": null, "submitted_at": "2025-12-17T15:38:12+00:00" }, { "id": 3588347715, "user": "user_afd8fdca88a2", "state": "COMMENTED", "body": null, "submitted_at": "2025-12-17T15:39:24+00:00" }, { "id": 3588384259, "user": "user_afd8fdca88a2", "state": "COMMENTED", "body": null, "submitted_at": "2025-12-17T15:47:23+00:00" }, { "id": 3588459494, "user": "user_fca2535bcd49", "state": "COMMENTED", "body": null, "submitted_at": "2025-12-17T16:05:33+00:00" }, { "id": 3588465306, "user": "user_afd8fdca88a2", "state": "COMMENTED", "body": null, "submitted_at": "2025-12-17T16:06:58+00:00" }, { "id": 3588470282, "user": "user_fca2535bcd49", "state": "COMMENTED", "body": null, "submitted_at": "2025-12-17T16:08:14+00:00" }, { "id": 3588510771, "user": "user_fca2535bcd49", "state": "COMMENTED", "body": null, "submitted_at": "2025-12-17T16:17:23+00:00" }, { "id": 3588513624, "user": "user_fca2535bcd49", "state": "APPROVED", "body": "Thanks for the PR, this looks good to me!", "submitted_at": "2025-12-17T16:17:53+00:00" } ], "review_comments": [ { "id": 2618499337, "user": "user_fca2535bcd49", "body": "I am wondering whether this can not made a bit simpler with `gh api`. Also I don't think you need to use `BOT_GITHUB_TOKEN` and can use the `GITHUB_TOKEN` which has the necessary read permissions.", "path": ".github/workflows/unit-tests.yml", "line": null, "side": "RIGHT", "created_at": "2025-12-15T08:46:32+00:00" }, { "id": 2619012231, "user": "user_afd8fdca88a2", "body": "I can look into it. Then do you think it'd be better to make a standalone python script for this step, or to merge it to the next step by modifying `maint_tools/update_tracking_issue.py` to accept a new flag that would tell it to grab the job id ?\n\nI didn't know there were differences in permissions between the tokens, I believe it's set in repo settings that aren't public so I cannot really check and try to mimic those in my fork.", "path": ".github/workflows/unit-tests.yml", "line": null, "side": "RIGHT", "created_at": "2025-12-15T11:22:47+00:00" }, { "id": 2619155398, "user": "user_fca2535bcd49", "body": "That's a good point, probably updating `update_tracking_issue.py` is preferrable indeed. Maybe `--append-job-id`, `--link-to-matrix-job-log` or a better name for the potential additional `job/$jobid` at the end of the URL? To be honest it almost feels like the logic for the job log URL should be done in the python script rather than provided externally but I don't know how easy this is.\n\nThis would make my point about tokens not relevant since you would use `GIHUB_BOT_TOKEN` for everything.", "path": ".github/workflows/unit-tests.yml", "line": null, "side": "RIGHT", "created_at": "2025-12-15T12:12:13+00:00" }, { "id": 2627195632, "user": "user_afd8fdca88a2", "body": "So with the new commits I implemented it, after a couple of tests on my fork it seems to work just fine.\nI went for a `--job-name` flag because we need to provide the name of the matrix job to find its ID, it's not the most explicit name but I tried to be clear in the help message. \n\nAlso, I was wondering why the `update_tracking_issue.py` does not use `if __name__ == \"__main__\"`. If there's no specific reason, I'd be happy to do the refactor. I would find it much clearer. But maybe it's outside of the scope of this PR.", "path": ".github/workflows/unit-tests.yml", "line": null, "side": "RIGHT", "created_at": "2025-12-17T14:02:26+00:00" }, { "id": 2627451423, "user": "user_fca2535bcd49", "body": "This is supposed to be a warning right not an exception? If that's the case use `warnings.warn(...)`", "path": "maint_tools/update_tracking_issue.py", "line": null, "side": "RIGHT", "created_at": "2025-12-17T15:10:45+00:00" }, { "id": 2627493270, "user": "user_fca2535bcd49", "body": "The help is slightly incorrect actually, `--test-passed` is about the message and the fact that it is closed or not depends on `--auto-close`.\n\nTo be honest this can be done in another PR, I let you choose.", "path": "maint_tools/update_tracking_issue.py", "line": null, "side": "RIGHT", "created_at": "2025-12-17T15:21:36+00:00" }, { "id": 2627515595, "user": "user_fca2535bcd49", "body": "> Also, I was wondering why the update_tracking_issue.py does not use if __name__ == \"__main__\". If there's no specific reason, I'd be happy to do the refactor. I would find it much clearer. But maybe it's outside of the scope of this PR.\n\nI don't think there is a very good reason other than simplicity, easier debuggability (most of the variables are global variables and easily accessible), and maybe a zest of slopiness/laziness (which you know sometimes is a reasonable approach). Feel free to do a follow up PR improving this if you think this is important :wink:.", "path": ".github/workflows/unit-tests.yml", "line": null, "side": "RIGHT", "created_at": "2025-12-17T15:27:21+00:00" }, { "id": 2627549773, "user": "user_afd8fdca88a2", "body": "Yes I was thinking a warning is enough, then the URL will point to the whole workflow log. I think it's better than breaking the whole action.", "path": "maint_tools/update_tracking_issue.py", "line": null, "side": "RIGHT", "created_at": "2025-12-17T15:36:05+00:00" }, { "id": 2627557406, "user": "user_afd8fdca88a2", "body": "I don't think it is really important, but I don't see a reason not to do it as I'm already working on it.", "path": ".github/workflows/unit-tests.yml", "line": null, "side": "RIGHT", "created_at": "2025-12-17T15:38:12+00:00" }, { "id": 2627561921, "user": "user_afd8fdca88a2", "body": "I might as well do it here and save you from having to review an extra PR ;)", "path": "maint_tools/update_tracking_issue.py", "line": null, "side": "RIGHT", "created_at": "2025-12-17T15:39:24+00:00" }, { "id": 2627590768, "user": "user_afd8fdca88a2", "body": "Looking back at the code, I think the message is just missing the fact that to close the issue `--auto-close` must be true too, but otherwise, the fact that the issue is created/updated or closed is indeed determined by [NAME_REDACTED] `--test-passed` value. So it's not just about the message.", "path": "maint_tools/update_tracking_issue.py", "line": null, "side": "RIGHT", "created_at": "2025-12-17T15:47:23+00:00" }, { "id": 2627655068, "user": "user_fca2535bcd49", "body": "This is not needed anymore, right?", "path": ".github/workflows/unit-tests.yml", "line": null, "side": "RIGHT", "created_at": "2025-12-17T16:05:33+00:00" }, { "id": 2627659977, "user": "user_afd8fdca88a2", "body": "Ah yes, thanks for catching it !", "path": ".github/workflows/unit-tests.yml", "line": null, "side": "RIGHT", "created_at": "2025-12-17T16:06:58+00:00" }, { "id": 2627664325, "user": "user_fca2535bcd49", "body": "Looks good now, thanks!", "path": "maint_tools/update_tracking_issue.py", "line": null, "side": "RIGHT", "created_at": "2025-12-17T16:08:13+00:00" }, { "id": 2627698604, "user": "user_fca2535bcd49", "body": "Just as a note for our future selves. This is not directly related to the PR, but this makes sure that when triggering wheels workflow manually via workflow_dispatch, it will also update the tracking issue. In particular this is consistent with the unit tests behaviour. I think this is fine to leave in this PR.", "path": ".github/workflows/update_tracking_issue.yml", "line": 30, "side": "RIGHT", "created_at": "2025-12-17T16:17:23+00:00" } ], "meta": { "languages": [ "py", "yml" ], "touches_tests": false, "review_state_summary": { "COMMENTED": 14, "APPROVED": 1 }, "meaningful_comment_count": 15, "has_approval": true, "has_changes_requested": false, "total_review_comments": 15 } } { "_id": "7f11c9456bfc7365", "_schema_version": "1.0", "_cleaned_at": "2026-02-12T07:46:52.007714+00:00", "repo": "scikit-learn/scikit-learn", "repo_url": "https://github.com/scikit-learn/scikit-learn", "license_name": "BSD 3-Clause \"New\" or \"Revised\" License", "license_spdx": "BSD-3-Clause", "pr_number": 32826, "title": "TST add tests for pyproject minimum dependency checks", "body": "\n\n#### [NAME_REDACTED]/PRs\n\nRelated to https://github.com/[USER_REDACTED]n/scikit-learn/pull/32790#issuecomment-3589272892\n\n#### What does this implement/fix? Explain your changes.\nThis adds a test using a minimal pyproject sample, to test that the tests actually work with upper bounds. \nI had to restructure the code a bit in order to use a test string instead of the toml file. \nLet me know if this is what you had in mind [USER_REDACTED].\n\n#### Any other comments?\n\nI noticed that there are also no tests testing the mismatch conditions of package versions. Adding this would be fairly straight forward now, but I'm not sure if these files are actually touched manually, and if this would make sense? \n\n", "author": "user_34a090906ca4", "created_at": "2025-12-01T16:31:51+00:00", "merged_at": "2025-12-22T08:44:46+00:00", "base_branch": "main", "head_branch": "test_upper_bounds", "additions": 185, "deletions": 63, "changed_files": 1, "files": [ { "filename": "sklearn/tests/test_min_dependencies_readme.py", "status": "modified", "additions": 185, "deletions": 63, "changes": 248, "patch": "@@ -2,6 +2,7 @@\n \n import os\n import re\n+import tomllib\n from collections import defaultdict\n from pathlib import Path\n \n@@ -11,18 +12,79 @@\n from sklearn._min_dependencies import dependent_packages\n from sklearn.utils.fixes import parse_version\n \n-min_depencies_tag_to_packages_without_version = defaultdict(list)\n-for package, (min_version, extras) in dependent_packages.items():\n- for extra in extras.split(\", \"):\n- min_depencies_tag_to_packages_without_version[extra].append(package)\n+# minimal dependencies and pyproject definitions for testing the pyproject tests\n \n-pyproject_section_to_min_dependencies_tag = {\n- \"build-system.requires\": \"build\",\n- \"project.dependencies\": \"install\",\n+TOY_MIN_DEPENDENCIES_PY_INFO = {\n+ \"joblib\": (\"1.3.0\", \"install\"),\n+ \"scipy\": (\"1.10.0\", \"build, install\"),\n+ \"conda-lock\": (\"3.0.1\", \"maintenance\"),\n }\n-for tag in min_depencies_tag_to_packages_without_version:\n- section = f\"project.optional-dependencies.{tag}\"\n- pyproject_section_to_min_dependencies_tag[section] = tag\n+\n+TOY_MATCHING_PYPROJECT_SECTIONS = \"\"\"\n+[project]\n+dependencies = [\"joblib>=1.3.0\", \"scipy>=1.10.0\"]\n+[project.optional-dependencies]\n+build = [\"scipy>=1.10.0\"]\n+install = [\"joblib>=1.3.0\", \"scipy>=1.10.0\"]\n+maintenance = [\"conda-lock==3.0.1\"]\n+[build-system]\n+requires = [\"scipy>=1.10.0\"]\n+\"\"\"\n+\n+TOY_MATCHING_PYPROJECT_SECTIONS_WITH_UPPER_BOUND = \"\"\"\n+[project]\n+dependencies = [\"joblib>=1.3.0,<2.0\", \"scipy>=1.10.0\"]\n+[project.optional-dependencies]\n+build = [\"scipy>=1.10.0,<1.19.0\"]\n+install = [\"joblib>=1.3.0,<2.0\", \"scipy>=1.10.0\"]\n+maintenance = [\"conda-lock==3.0.1\"]\n+[build-system]\n+requires = [\"scipy>=1.10.0,<1.19.0\"]\n+\"\"\"\n+\n+TOY_WRONG_SYMBOL_PYPROJECT_SECTIONS = \"\"\"\n+[project]\n+dependencies = [\"scipy<1.10.0\"]\n+[project.optional-dependencies]\n+build = [\"scipy>=1.10.0\"]\n+install = [\"scipy>=1.10.0\"]\n+maintenance = [\"conda-lock==3.0.1\"]\n+[build-system]\n+requires = [\"scipy>=1.10.0\"]\n+\"\"\"\n+\n+TOY_MISSING_PACKAGE_PYPROJECT_SECTIONS = \"\"\"\n+[project]\n+dependencies = [\"scipy>=1.10.0\"]\n+[project.optional-dependencies]\n+build = [\"scipy>=1.10.0\"]\n+install = [\"scipy>=1.10.0\"]\n+maintenance = [\"conda-lock==3.0.1\"]\n+[build-system]\n+requires = [\"scipy>=1.10.0\"]\n+\"\"\"\n+\n+TOY_ADDITIONAL_PACKAGE_PYPROJECT_SECTIONS = \"\"\"\n+[project]\n+dependencies = [\"joblib>=1.3.0\", \"scipy>=1.10.0\"]\n+[project.optional-dependencies]\n+build = [\"scipy>=1.10.0\", \"package_not_in_min_dependencies_py_file>=4.2\"]\n+install = [\"joblib>=1.3.0\", \"scipy>=1.10.0\"]\n+maintenance = [\"conda-lock==3.0.1\"]\n+[build-system]\n+requires = [\"scipy>=1.10.0\"]\n+\"\"\"\n+\n+TOY_NON_MATCHING_VERSION_PYPROJECT_SECTIONS = \"\"\"\n+[project]\n+dependencies = [\"joblib>=1.42.0\", \"scipy>=1.10.0\"]\n+[project.optional-dependencies]\n+build = [\"scipy>=1.10.0\"]\n+install = [\"joblib>=1.3.0\", \"scipy>=1.10.0\"]\n+maintenance = [\"conda-lock==3.0.1\"]\n+[build-system]\n+requires = [\"scipy>=1.10.0\"]\n+\"\"\"\n \n \n def test_min_dependencies_readme():\n@@ -66,18 +128,79 @@ def test_min_dependencies_readme():\n assert version == min_version, message\n \n \n-def check_pyproject_section(\n- pyproject_section, min_dependencies_tag, skip_version_check_for=None\n-):\n- # tomllib is available in Python 3.11\n- tomllib = pytest.importorskip(\"tomllib\")\n+def extract_packages_and_pyproject_tags(dependencies):\n+ min_depencies_tag_to_packages_without_version = defaultdict(list)\n+ for package, (min_version, tags) in dependencies.items():\n+ for t in tags.split(\", \"):\n+ min_depencies_tag_to_packages_without_version[t].append(package)\n+\n+ pyproject_section_to_min_dependencies_tag = {\n+ \"build-system.requires\": \"build\",\n+ \"project.dependencies\": \"install\",\n+ }\n+ for tag in min_depencies_tag_to_packages_without_version:\n+ section = f\"project.optional-dependencies.{tag}\"\n+ pyproject_section_to_min_dependencies_tag[section] = tag\n+\n+ return (\n+ min_depencies_tag_to_packages_without_version,\n+ pyproject_section_to_min_dependencies_tag,\n+ )\n+\n+\n+def check_pyproject_sections(pyproject_toml, min_dependencies):\n+ packages, pyproject_tags = extract_packages_and_pyproject_tags(min_dependencies)\n+\n+ for pyproject_section, min_dependencies_tag in pyproject_tags.items():\n+ # Special situation for numpy: we have numpy>=2 in\n+ # build-system.requires to make sure we build wheels against numpy>=2.\n+ # TODO remove this when our minimum supported numpy version is >=2.\n+ skip_version_check_for = (\n+ [\"numpy\"] if pyproject_section == \"build-system.requires\" else []\n+ )\n+\n+ expected_packages = packages[min_dependencies_tag]\n+\n+ pyproject_section_keys = pyproject_section.split(\".\")\n+ info = pyproject_toml\n+ # iterate through nested keys to get packages and version\n+ for key in pyproject_section_keys:\n+ info = info[key]\n+\n+ pyproject_build_min_versions = {}\n+ # Assuming pyproject.toml build section has something like \"my-package>=2.3.0\"\n+ pattern = r\"([\\w-]+)\\s*[>=]=\\s*([\\d\\w.]+)\"\n+ for requirement in info:\n+ match = re.search(pattern, requirement)\n+ if match is None:\n+ raise NotImplementedError(\n+ f\"{requirement} does not match expected regex {pattern!r}. \"\n+ \"Only >= and == are supported for version requirements\"\n+ )\n+\n+ package, version = match.group(1), match.group(2)\n \n- if skip_version_check_for is None:\n- skip_version_check_for = []\n+ pyproject_build_min_versions[package] = version\n \n- expected_packages = min_depencies_tag_to_packages_without_version[\n- min_dependencies_tag\n- ]\n+ msg = f\"Packages in {pyproject_section} differ from _min_depencies.py\"\n+\n+ assert sorted(pyproject_build_min_versions) == sorted(expected_packages), msg\n+\n+ for package, version in pyproject_build_min_versions.items():\n+ version = parse_version(version)\n+ expected_min_version = parse_version(min_dependencies[package][0])\n+ if package in skip_version_check_for:\n+ continue\n+\n+ message = (\n+ f\"{package} has inconsistent minimum versions in pyproject.toml and\"\n+ f\" _min_depencies.py: {version} != {expected_min_version}\"\n+ )\n+ assert version == expected_min_version, message\n+\n+\n+def test_min_dependencies_pyproject_toml():\n+ \"\"\"Check versions in pyproject.toml is consistent with _min_dependencies.\"\"\"\n \n root_directory = Path(sklearn.__file__).parent.parent\n pyproject_toml_path = root_directory / \"pyproject.toml\"\n@@ -90,54 +213,53 @@ def check_pyproject_section(\n with pyproject_toml_path.open(\"rb\") as f:\n pyproject_toml = tomllib.load(f)\n \n- pyproject_section_keys = pyproject_section.split(\".\")\n- info = pyproject_toml\n- for key in pyproject_section_keys:\n- info = info[key]\n-\n- pyproject_build_min_versions = {}\n- # Assuming pyproject.toml build section has something like \"my-package>=2.3.0\"\n- # Warning: if you try to modify this regex, bear in mind that there can be upper\n- # bounds in release branches so \"my-package>=2.3.0,<2.5.0\"\n- pattern = r\"([\\w-]+)\\s*[>=]=\\s*([\\d\\w.]+)\"\n- for requirement in info:\n- match = re.search(pattern, requirement)\n- if match is None:\n- raise NotImplementedError(\n- f\"{requirement} does not match expected regex {pattern!r}. \"\n- \"Only >= and == are supported for version requirements\"\n- )\n-\n- package, version = match.group(1), match.group(2)\n+ check_pyproject_sections(pyproject_toml, dependent_packages)\n \n- pyproject_build_min_versions[package] = version\n \n- assert sorted(pyproject_build_min_versions) == sorted(expected_packages)\n+[USER_REDACTED].mark.parametrize(\n+ \"example_pyproject\",\n+ [\n+ TOY_MATCHING_PYPROJECT_SECTIONS,\n+ TOY_MATCHING_PYPROJECT_SECTIONS_WITH_UPPER_BOUND,\n+ ],\n+)\n+def test_check_matching_pyproject_section(example_pyproject):\n+ \"\"\"Test the version check for matching packages.\"\"\"\n \n- for package, version in pyproject_build_min_versions.items():\n- version = parse_version(version)\n- expected_min_version = parse_version(dependent_packages[package][0])\n- if package in skip_version_check_for:\n- continue\n+ pyproject_toml = tomllib.loads(example_pyproject)\n \n- message = (\n- f\"{package} has inconsistent minimum versions in pyproject.toml and\"\n- f\" _min_depencies.py: {version} != {expected_min_version}\"\n- )\n- assert version == expected_min_version, message\n+ check_pyproject_sections(pyproject_toml, TOY_MIN_DEPENDENCIES_PY_INFO)\n \n \n [USER_REDACTED].mark.parametrize(\n- \"pyproject_section, min_dependencies_tag\",\n- pyproject_section_to_min_dependencies_tag.items(),\n+ \"example_non_matching_pyproject, error_msg\",\n+ [\n+ (\n+ TOY_WRONG_SYMBOL_PYPROJECT_SECTIONS,\n+ \".* does not match expected regex .*. \"\n+ \"Only >= and == are supported for version requirements\",\n+ ),\n+ (\n+ TOY_MISSING_PACKAGE_PYPROJECT_SECTIONS,\n+ \"Packages in .* differ from _min_depencies.py\",\n+ ),\n+ (\n+ TOY_ADDITIONAL_PACKAGE_PYPROJECT_SECTIONS,\n+ \"Packages in .* differ from _min_depencies.py\",\n+ ),\n+ (\n+ TOY_NON_MATCHING_VERSION_PYPROJECT_SECTIONS,\n+ \".* has inconsistent minimum versions in pyproject.toml and\"\n+ \" _min_depencies.py: .* != .*\",\n+ ),\n+ ],\n )\n-def test_min_dependencies_pyproject_toml(pyproject_section, min_dependencies_tag):\n- \"\"\"Check versions in pyproject.toml is consistent with _min_dependencies.\"\"\"\n- # NumPy is more complex because build-time (>=1.25) and run-time (>=1.19.5)\n- # requirement currently don't match\n- skip_version_check_for = [\"numpy\"] if min_dependencies_tag == \"build\" else None\n- check_pyproject_section(\n- pyproject_section,\n- min_dependencies_tag,\n- skip_version_check_for=skip_version_check_for,\n- )\n+def test_check_non_matching_pyproject_section(\n+ example_non_matching_pyproject, error_msg\n+):\n+ \"\"\"Test the version check for non-matching packages and versions.\"\"\"\n+\n+ pyproject_toml = tomllib.loads(example_non_matching_pyproject)\n+\n+ with pytest.raises(Exception, match=error_msg):\n+ check_pyproject_sections(pyproject_toml, TOY_MIN_DEPENDENCIES_PY_INFO)" } ], "reviews": [ { "id": 3535534230, "user": "user_fca2535bcd49", "state": "COMMENTED", "body": null, "submitted_at": "2025-12-03T15:10:22+00:00" }, { "id": 3535577444, "user": "user_fca2535bcd49", "state": "COMMENTED", "body": null, "submitted_at": "2025-12-03T15:19:48+00:00" }, { "id": 3536845773, "user": "user_34a090906ca4", "state": "COMMENTED", "body": null, "submitted_at": "2025-12-03T20:40:10+00:00" }, { "id": 3536956697, "user": "user_34a090906ca4", "state": "COMMENTED", "body": null, "submitted_at": "2025-12-03T21:15:20+00:00" }, { "id": 3536967561, "user": "user_34a090906ca4", "state": "COMMENTED", "body": null, "submitted_at": "2025-12-03T21:19:19+00:00" }, { "id": 3536978384, "user": "user_34a090906ca4", "state": "COMMENTED", "body": null, "submitted_at": "2025-12-03T21:23:25+00:00" }, { "id": 3536982211, "user": "user_34a090906ca4", "state": "COMMENTED", "body": null, "submitted_at": "2025-12-03T21:24:52+00:00" }, { "id": 3536987949, "user": "user_34a090906ca4", "state": "COMMENTED", "body": null, "submitted_at": "2025-12-03T21:27:01+00:00" }, { "id": 3536992863, "user": "user_34a090906ca4", "state": "COMMENTED", "body": null, "submitted_at": "2025-12-03T21:28:38+00:00" }, { "id": 3537034796, "user": "user_34a090906ca4", "state": "COMMENTED", "body": null, "submitted_at": "2025-12-03T21:39:02+00:00" }, { "id": 3537041954, "user": "user_34a090906ca4", "state": "COMMENTED", "body": null, "submitted_at": "2025-12-03T21:41:07+00:00" }, { "id": 3537087055, "user": "user_34a090906ca4", "state": "COMMENTED", "body": null, "submitted_at": "2025-12-03T21:53:06+00:00" }, { "id": 3561655274, "user": "user_5819d17296ee", "state": "COMMENTED", "body": "Please find a pass of review below.", "submitted_at": "2025-12-10T10:03:04+00:00" }, { "id": 3582035991, "user": "user_fca2535bcd49", "state": "COMMENTED", "body": null, "submitted_at": "2025-12-16T09:02:11+00:00" }, { "id": 3582205011, "user": "user_34a090906ca4", "state": "COMMENTED", "body": null, "submitted_at": "2025-12-16T09:42:58+00:00" }, { "id": 3582267041, "user": "user_fca2535bcd49", "state": "COMMENTED", "body": null, "submitted_at": "2025-12-16T09:58:12+00:00" }, { "id": 3582329943, "user": "user_fca2535bcd49", "state": "COMMENTED", "body": null, "submitted_at": "2025-12-16T10:13:34+00:00" }, { "id": 3594635181, "user": "user_34a090906ca4", "state": "COMMENTED", "body": null, "submitted_at": "2025-12-18T19:09:10+00:00" }, { "id": 3597465978, "user": "user_fca2535bcd49", "state": "COMMENTED", "body": null, "submitted_at": "2025-12-19T08:10:48+00:00" }, { "id": 3599235331, "user": "user_34a090906ca4", "state": "COMMENTED", "body": null, "submitted_at": "2025-12-19T16:32:44+00:00" }, { "id": 3603060465, "user": "user_fca2535bcd49", "state": "APPROVED", "body": null, "submitted_at": "2025-12-22T08:10:25+00:00" } ], "review_comments": [ { "id": 2585505855, "user": "user_fca2535bcd49", "body": "This can be removed as the previous comment was saying this is needed for Python<3.11 where tomllib was not part of the standard library but our minimum Python dependency is Python 3.11.", "path": "sklearn/tests/test_min_dependencies_readme.py", "line": null, "side": "RIGHT", "created_at": "2025-12-03T15:10:22+00:00" }, { "id": 2585541208, "user": "user_fca2535bcd49", "body": "Thanks for the PR! This seems to go in the direction I had in mind, I'll try to have a closer look at one point.\n\nGeneral comment: the more you can reduce the diff, the more this will make the reviewer's life (my life in this particular case) easier 😉. For example, it seems like you move global variables `min_dependencies_tag_to_packages_without_version` and `pyproject_section_to_min_dependencies_tag` to a function but this function is called once.\n\nMaybe you have a good reason to do it and I would be curious to hear about it, but as a reviewer, I am expecting an \"easy\" PR to review and I have to take 5-10 minutes to understand just this part and that doesn't help keeping this PR in the \"easy to review\" category 😅.", "path": "sklearn/tests/test_min_dependencies_readme.py", "line": 131, "side": "RIGHT", "created_at": "2025-12-03T15:19:48+00:00" }, { "id": 2586545729, "user": "user_34a090906ca4", "body": "I moved the global variables into a function in order to create them either from the min_dependencies or the test_dependencies, meaning the function is only called once, but the parameter passed from `test_min_dependencies_pyproject_toml` and `test_check_pyproject_section_with_upper_bounds` differs. \nOne could integrate the code into `check_pyproject_sections`, but since it is sort of a pre-processing step, I decided to keep it as an own function.", "path": "sklearn/tests/test_min_dependencies_readme.py", "line": 131, "side": "RIGHT", "created_at": "2025-12-03T20:40:10+00:00" }, { "id": 2586632225, "user": "user_34a090906ca4", "body": "I tried to move the function to the same place as the global variables to make it easier to compare, but github still aligned the wrong parts, so I'll try to mark the changes below instead.", "path": "sklearn/tests/test_min_dependencies_readme.py", "line": 131, "side": "RIGHT", "created_at": "2025-12-03T21:15:20+00:00" }, { "id": 2586641316, "user": "user_34a090906ca4", "body": "Here, it now iterates over the argument `dependencies` instead of the global imported `dependent_packages` \n\n(I took the liberty of also renaming `extras` to `tags`, because it took my a while to figure out what \"extras\" are.)", "path": "sklearn/tests/test_min_dependencies_readme.py", "line": 133, "side": "RIGHT", "created_at": "2025-12-03T21:19:20+00:00" }, { "id": 2586651221, "user": "user_34a090906ca4", "body": "I replaced the parametrization in the existing test with a for-loop here, to enable iterating over either the whole actual `pyproject.toml` or the given test subset.", "path": "sklearn/tests/test_min_dependencies_readme.py", "line": 154, "side": "RIGHT", "created_at": "2025-12-03T21:23:25+00:00" }, { "id": 2586654436, "user": "user_34a090906ca4", "body": "Because the tags are only available at this stage, the definition of the skip packages has to happen here now.", "path": "sklearn/tests/test_min_dependencies_readme.py", "line": null, "side": "RIGHT", "created_at": "2025-12-03T21:24:52+00:00" }, { "id": 2586659446, "user": "user_34a090906ca4", "body": "I added a comment here because it took me a while to understand the following loop and what `info` actually contains at the end.", "path": "sklearn/tests/test_min_dependencies_readme.py", "line": 166, "side": "RIGHT", "created_at": "2025-12-03T21:27:01+00:00" }, { "id": 2586664137, "user": "user_34a090906ca4", "body": "The remainder of this function is almost unchanged except for one extra indentation because of the loop above and one other change marked below.", "path": "sklearn/tests/test_min_dependencies_readme.py", "line": 166, "side": "RIGHT", "created_at": "2025-12-03T21:28:38+00:00" }, { "id": 2586696884, "user": "user_34a090906ca4", "body": "This parametrization is replaced by [NAME_REDACTED] `check_pyproject_sections(`", "path": "sklearn/tests/test_min_dependencies_readme.py", "line": 132, "side": "LEFT", "created_at": "2025-12-03T21:39:02+00:00" }, { "id": 2586702029, "user": "user_34a090906ca4", "body": "Reading in the actual pyproject.toml file is now happening here, and the parsed version is passed to `check_pyproject_sections` (to enable passing a test version in the new test)", "path": "sklearn/tests/test_min_dependencies_readme.py", "line": 205, "side": "RIGHT", "created_at": "2025-12-03T21:41:07+00:00" }, { "id": 2586733220, "user": "user_34a090906ca4", "body": "Here, the version is compared to the given `min_dependencies`, not the global imported `dependent_packages` (as in line 119 in the old version)", "path": "sklearn/tests/test_min_dependencies_readme.py", "line": 191, "side": "RIGHT", "created_at": "2025-12-03T21:53:06+00:00" }, { "id": 2605949419, "user": "user_5819d17296ee", "body": "I think we could use more explicit variable names to convey that those are not expected to match the currently used version numbers.\n\n```suggestion\nEXAMPLE_MIN_DEPENDENT_PACKAGES = {\n```", "path": "sklearn/tests/test_min_dependencies_readme.py", "line": null, "side": "RIGHT", "created_at": "2025-12-10T09:52:53+00:00" }, { "id": 2605950476, "user": "user_5819d17296ee", "body": "```suggestion\nEXAMPLE_EXPECTED_PYPROJECT_SECTIONS_WITH_UPPER_BOUND = \"\"\"\n```", "path": "sklearn/tests/test_min_dependencies_readme.py", "line": null, "side": "RIGHT", "created_at": "2025-12-10T09:53:11+00:00" }, { "id": 2605956375, "user": "user_5819d17296ee", "body": "Maybe add a similar example pyproject without the upper bounds to also test the check function against it?", "path": "sklearn/tests/test_min_dependencies_readme.py", "line": 43, "side": "RIGHT", "created_at": "2025-12-10T09:54:51+00:00" }, { "id": 2605983707, "user": "user_5819d17296ee", "body": "Please also expand the test to also checks that a meaningful exception is raised when inconsistent arguments are passed to `check_pyproject_sections`.", "path": "sklearn/tests/test_min_dependencies_readme.py", "line": null, "side": "RIGHT", "created_at": "2025-12-10T10:02:23+00:00" }, { "id": 2622398215, "user": "user_fca2535bcd49", "body": "I guess you can remove those 2 lines since there is a test checking this now? Basically I added this comment because there was not test before and to remind people of this edge case.\n```suggestion\n```", "path": "sklearn/tests/test_min_dependencies_readme.py", "line": null, "side": "RIGHT", "created_at": "2025-12-16T09:02:11+00:00" }, { "id": 2622535012, "user": "user_34a090906ca4", "body": "I was wondering, should we also check the upper bounds explicitly?\nFor now, the regex just ignores them and only the matching min versions are checked.", "path": "sklearn/tests/test_min_dependencies_readme.py", "line": null, "side": "RIGHT", "created_at": "2025-12-16T09:42:58+00:00" }, { "id": 2622593960, "user": "user_fca2535bcd49", "body": "I would say YAGNI (not needed) for now.", "path": "sklearn/tests/test_min_dependencies_readme.py", "line": null, "side": "RIGHT", "created_at": "2025-12-16T09:58:12+00:00" }, { "id": 2622648092, "user": "user_fca2535bcd49", "body": "I think it doesn't make too much sense to have `scipy==1.10.0` in some sections and `scipy>=1.10.0` in others.\n\nI am trying to think hard to find a use case for mixing `>=` and `==` but I can not find one.\n\nI think the only use case for `==` is for `conda-lock`. Here is what I would recommend as good/realistic enough:\n- use scipy>=1.10.0 in all the `EXAMPLE_` variables\n- add conda-lock==3.0.1 in all the `EXAMPLE_` variables\n\nIn an ideal world you would also check that `>=` and `==` is used consistently in all the sections for a given package. Right now I think this is not worth spending too much time on this.", "path": "sklearn/tests/test_min_dependencies_readme.py", "line": null, "side": "RIGHT", "created_at": "2025-12-16T10:13:34+00:00" }, { "id": 2632325328, "user": "user_34a090906ca4", "body": "I inserted the `==` randomly for one package to keep the examples as small as possible, but still have a check for both allowed operators. If you insist on realistic examples, I can apply your suggested change, but in terms of testing functionality, this doesn't really add anything.\n\nAnd yes, testing for consistent use across pyproject sections could probably make sense at some point (but maybe even as a separate test).", "path": "sklearn/tests/test_min_dependencies_readme.py", "line": null, "side": "RIGHT", "created_at": "2025-12-18T19:09:10+00:00" }, { "id": 2634127884, "user": "user_fca2535bcd49", "body": "I pushed some tweaks, hopefully you don't mind too much :sweat_smile:. Please double-check them to make sure I didn't miss something :pray:.\n\nThe main \"important\" change in my eyes is that the toy data (i.e. the `EXAMPLE_` variables) is realistic. Basically someone like me seeing that we use a mix of `scipy==` and `scipy>=` would \n1. be surprised, why are we doing this is there a good reason? Minimizing suprise is a good thing in general.\n2. maybe spend 1-2 hours looking at the history of `main` and previous release branches figuring out whether this surprising pattern corresponds to an edge case that we used at one point in the past.\n\nSince I think the `==` is only used for conda-lock at this point, I added conda-lock in the toy data.", "path": "sklearn/tests/test_min_dependencies_readme.py", "line": null, "side": "RIGHT", "created_at": "2025-12-19T08:10:48+00:00" }, { "id": 2635634210, "user": "user_34a090906ca4", "body": "Avoiding confusion sounds like a valid goal. Thanks for adding the changes. LGTM.", "path": "sklearn/tests/test_min_dependencies_readme.py", "line": null, "side": "RIGHT", "created_at": "2025-12-19T16:32:44+00:00" } ], "meta": { "languages": [ "py" ], "touches_tests": true, "review_state_summary": { "COMMENTED": 20, "APPROVED": 1 }, "meaningful_comment_count": 23, "has_approval": true, "has_changes_requested": false, "total_review_comments": 23 } } { "_id": "4a3f2b01e17cefde", "_schema_version": "1.0", "_cleaned_at": "2026-02-12T07:46:52.023342+00:00", "repo": "scikit-learn/scikit-learn", "repo_url": "https://github.com/scikit-learn/scikit-learn", "license_name": "BSD 3-Clause \"New\" or \"Revised\" License", "license_spdx": "BSD-3-Clause", "pr_number": 32825, "title": "Add new default max_samples=None in Bagging estimators", "body": "#### [NAME_REDACTED]/PRs\n\nFixes #32805. Follow-up to #31414. \n\n#### What does this implement/fix? Explain your changes.\n\nWe add a new option `max_samples=None` in Bagging estimators, with the meaning of \"draw exactly n_samples\", and we make it the new default. This ensures that the number of bootstrap samples used (a crucial hyperparameter in bagging) will be the same across the 1.7 -> 1.8 transition, and makes the changes introduced in #31414 less disruptive when fitting with sample_weight:\n- in 1.7 and before, the default max_samples=1.0 was drawing `n_samples` (discarding sample_weight)\n- in #31414, the default max_samples=1.0 draws `sample_weight.sum()`. This can potentially lead to catastrophic fits if for some reason the `sample_weight` are very small or normalized to one for example. We do raise an error in that case, but the changes may still be drastic and surprising to users in less extreme cases.\n- here we add the new default `max_samples=None`, which always draws `n_samples` as in 1.7.\n\ncc [USER_REDACTED] [USER_REDACTED] [USER_REDACTED]", "author": "user_e43769eee4e2", "created_at": "2025-12-01T16:15:28+00:00", "merged_at": "2025-12-05T10:30:43+00:00", "base_branch": "main", "head_branch": "bagging_max_samples", "additions": 139, "deletions": 36, "changed_files": 4, "files": [ { "filename": "doc/whats_new/upcoming_changes/sklearn.ensemble/31414.fix.rst", "status": "removed", "additions": 0, "deletions": 7, "changes": 7, "patch": "@@ -1,7 +0,0 @@\n-- :class:`ensemble.BaggingClassifier`, :class:`ensemble.BaggingRegressor`\n- and :class:`ensemble.IsolationForest` now use `sample_weight` to draw\n- the samples instead of forwarding them multiplied by a uniformly sampled\n- mask to the underlying estimators. Furthermore, `max_samples` is now\n- interpreted as a fraction of `sample_weight.sum()` instead of `X.shape[0]`\n- when passed as a float.\n- By :user:`[NAME_REDACTED] `." }, { "filename": "doc/whats_new/upcoming_changes/sklearn.ensemble/32825.fix.rst", "status": "added", "additions": 8, "deletions": 0, "changes": 8, "patch": "@@ -0,0 +1,8 @@\n+- :class:`ensemble.BaggingClassifier`, :class:`ensemble.BaggingRegressor` and\n+ :class:`ensemble.IsolationForest` now use `sample_weight` to draw the samples\n+ instead of forwarding them multiplied by a uniformly sampled mask to the\n+ underlying estimators. Furthermore, when `max_samples` is a float, it is now\n+ interpreted as a fraction of `sample_weight.sum()` instead of `X.shape[0]`.\n+ The new default `max_samples=None` draws `X.shape[0]` samples, irrespective\n+ of `sample_weight`.\n+ By :user:`[NAME_REDACTED] `. :pr:`31414` and" }, { "filename": "sklearn/ensemble/_bagging.py", "status": "modified", "additions": 73, "deletions": 23, "changes": 96, "patch": "@@ -46,6 +46,63 @@\n MAX_INT = np.iinfo(np.int32).max\n \n \n+def _get_n_samples_bootstrap(n_samples, max_samples, sample_weight):\n+ \"\"\"\n+ Get the number of samples in a bootstrap sample.\n+\n+ Parameters\n+ ----------\n+ n_samples : int\n+ Number of samples in the dataset.\n+\n+ max_samples : None, int or float\n+ The maximum number of samples to draw.\n+\n+ - If None, then draw `n_samples` samples.\n+ - If int, then draw `max_samples` samples.\n+ - If float, then draw `max_samples * n_samples` unweighted samples or\n+ `max_samples * sample_weight.sum()` weighted samples.\n+\n+ sample_weight : array of shape (n_samples,) or None\n+ Sample weights with frequency semantics when `max_samples` is explicitly\n+ set to a float or integer value. When keeping the `max_samples=None` default\n+ value, the equivalence between fitting with integer weighted data points or\n+ integer repeated data points is no longer guaranteed because the effective\n+ bootstrap size is no longer guaranteed to be equivalent.\n+\n+ Returns\n+ -------\n+ n_samples_bootstrap : int\n+ The total number of samples to draw for the bootstrap sample.\n+ \"\"\"\n+ if max_samples is None:\n+ return n_samples\n+ elif isinstance(max_samples, Integral):\n+ return max_samples\n+\n+ if sample_weight is None:\n+ weighted_n_samples = n_samples\n+ weighted_n_samples_msg = f\"the number of samples is {weighted_n_samples} \"\n+ else:\n+ weighted_n_samples = sample_weight.sum()\n+ weighted_n_samples_msg = (\n+ f\"the total sum of sample weights is {weighted_n_samples} \"\n+ )\n+\n+ # max_samples Real fractional value relative to weighted_n_samples\n+ n_samples_bootstrap = max(int(max_samples * weighted_n_samples), 1)\n+ # Warn when number of bootstrap samples is suspiciously small\n+ # This heuristic for \"suspiciously small\" might be adapted if found\n+ # unsuitable in practice\n+ if n_samples_bootstrap < max(10, n_samples ** (1 / 3)):\n+ warn(\n+ f\"Using the fractional value {max_samples=} when {weighted_n_samples_msg}\"\n+ f\"results in a low number ({n_samples_bootstrap}) of bootstrap samples. \"\n+ \"We recommend passing `max_samples` as an integer instead.\"\n+ )\n+ return n_samples_bootstrap\n+\n+\n def _generate_indices(random_state, bootstrap, n_population, n_samples):\n \"\"\"Draw randomly sampled indices.\"\"\"\n # Draw sample indices\n@@ -273,6 +330,7 @@ class BaseBagging(BaseEnsemble, metaclass=ABCMeta):\n \"estimator\": [HasMethods([\"fit\", \"predict\"]), None],\n \"n_estimators\": [Interval(Integral, 1, None, closed=\"left\")],\n \"max_samples\": [\n+ None,\n Interval(Integral, 1, None, closed=\"left\"),\n Interval(RealNotInt, 0, 1, closed=\"right\"),\n ],\n@@ -295,7 +353,7 @@ def __init__(\n estimator=None,\n n_estimators=10,\n *,\n- max_samples=1.0,\n+ max_samples=None,\n max_features=1.0,\n bootstrap=True,\n bootstrap_features=False,\n@@ -340,7 +398,9 @@ def fit(self, X, y, sample_weight=None, **fit_params):\n Sample weights. If None, then samples are equally weighted. Used as\n probabilities to sample the training set. Note that the expected\n frequency semantics for the `sample_weight` parameter are only\n- fulfilled when sampling with replacement `bootstrap=True`.\n+ fulfilled when sampling with replacement `bootstrap=True` and using\n+ a float or integer `max_samples` (instead of the default\n+ `max_samples=None`).\n \n **fit_params : dict\n Parameters to pass to the underlying estimators.\n@@ -462,20 +522,7 @@ def _fit(\n if max_samples is None:\n max_samples = self.max_samples\n \n- if not isinstance(max_samples, numbers.Integral):\n- if sample_weight is None:\n- max_samples = max(int(max_samples * X.shape[0]), 1)\n- else:\n- sw_sum = np.sum(sample_weight)\n- if sw_sum <= 1:\n- raise ValueError(\n- f\"The total sum of sample weights is {sw_sum}, which prevents \"\n- \"resampling with a fractional value for max_samples=\"\n- f\"{max_samples}. Either pass max_samples as an integer or \"\n- \"use a larger sample_weight.\"\n- )\n- max_samples = max(int(max_samples * sw_sum), 1)\n-\n+ max_samples = _get_n_samples_bootstrap(X.shape[0], max_samples, sample_weight)\n if not self.bootstrap and max_samples > X.shape[0]:\n raise ValueError(\n f\"Effective max_samples={max_samples} must be <= n_samples=\"\n@@ -728,13 +775,14 @@ class BaggingClassifier(ClassifierMixin, BaseBagging):\n n_estimators : int, default=10\n The number of base estimators in the ensemble.\n \n- max_samples : int or float, default=1.0\n+ max_samples : int or float, default=None\n The number of samples to draw from X to train each base estimator (with\n replacement by default, see `bootstrap` for more details).\n \n+ - If None, then draw `X.shape[0]` samples irrespective of `sample_weight`.\n - If int, then draw `max_samples` samples.\n- - If float, then draw `max_samples * X.shape[0]` unweighted samples\n- or `max_samples * sample_weight.sum()` weighted samples.\n+ - If float, then draw `max_samples * X.shape[0]` unweighted samples or\n+ `max_samples * sample_weight.sum()` weighted samples.\n \n max_features : int or float, default=1.0\n The number of features to draw from X to train each base estimator (\n@@ -867,7 +915,7 @@ def __init__(\n estimator=None,\n n_estimators=10,\n *,\n- max_samples=1.0,\n+ max_samples=None,\n max_features=1.0,\n bootstrap=True,\n bootstrap_features=False,\n@@ -1239,12 +1287,14 @@ class BaggingRegressor(RegressorMixin, BaseBagging):\n n_estimators : int, default=10\n The number of base estimators in the ensemble.\n \n- max_samples : int or float, default=1.0\n+ max_samples : int or float, default=None\n The number of samples to draw from X to train each base estimator (with\n replacement by default, see `bootstrap` for more details).\n \n+ - If None, then draw `X.shape[0]` samples irrespective of `sample_weight`.\n - If int, then draw `max_samples` samples.\n- - If float, then draw `max_samples * X.shape[0]` samples.\n+ - If float, then draw `max_samples * X.shape[0]` unweighted samples or\n+ `max_samples * sample_weight.sum()` weighted samples.\n \n max_features : int or float, default=1.0\n The number of features to draw from X to train each base estimator (\n@@ -1368,7 +1418,7 @@ def __init__(\n estimator=None,\n n_estimators=10,\n *,\n- max_samples=1.0,\n+ max_samples=None,\n max_features=1.0,\n bootstrap=True,\n bootstrap_features=False," }, { "filename": "sklearn/ensemble/tests/test_bagging.py", "status": "modified", "additions": 58, "deletions": 6, "changes": 64, "patch": "@@ -6,6 +6,7 @@\n # SPDX-License-Identifier: BSD-3-Clause\n \n import re\n+import warnings\n from itertools import cycle, product\n \n import joblib\n@@ -26,6 +27,7 @@\n RandomForestClassifier,\n RandomForestRegressor,\n )\n+from sklearn.ensemble._bagging import _get_n_samples_bootstrap\n from sklearn.feature_selection import SelectKBest\n from sklearn.linear_model import LogisticRegression, Perceptron\n from sklearn.model_selection import GridSearchCV, ParameterGrid, train_test_split\n@@ -706,16 +708,17 @@ def test_warning_bootstrap_sample_weight():\n def test_invalid_sample_weight_max_samples_bootstrap_combinations():\n X, y = iris.data, iris.target\n \n- # Case 1: small weights and fractional max_samples would lead to sampling\n- # less than 1 sample, which is not allowed.\n+ # Case 1: small weights and fractional max_samples lead to a small\n+ # number of bootstrap samples, which raises a UserWarning.\n clf = BaggingClassifier(max_samples=1.0)\n sample_weight = np.ones_like(y) / (2 * len(y))\n expected_msg = (\n- r\"The total sum of sample weights is 0.5(\\d*), which prevents resampling with \"\n- r\"a fractional value for max_samples=1\\.0\\. Either pass max_samples as an \"\n- r\"integer or use a larger sample_weight\\.\"\n+ \"Using the fractional value max_samples=1.0 when \"\n+ r\"the total sum of sample weights is 0.5(\\d*) \"\n+ r\"results in a low number \\(1\\) of bootstrap samples. \"\n+ \"We recommend passing `max_samples` as an integer.\"\n )\n- with pytest.raises(ValueError, match=expected_msg):\n+ with pytest.warns(UserWarning, match=expected_msg):\n clf.fit(X, y, sample_weight=sample_weight)\n \n # Case 2: large weights and bootstrap=False would lead to sampling without\n@@ -813,6 +816,55 @@ def test_draw_indices_using_sample_weight(\n assert_allclose(estimator.y_, y[samples])\n \n \n+def test_get_n_samples_bootstrap():\n+ n_samples, max_samples, sample_weight = 10, None, \"not_used\"\n+ assert _get_n_samples_bootstrap(n_samples, max_samples, sample_weight) == n_samples\n+\n+ n_samples, max_samples, sample_weight = 10, 5, \"not_used\"\n+ assert (\n+ _get_n_samples_bootstrap(n_samples, max_samples, sample_weight) == max_samples\n+ )\n+\n+ n_samples, max_samples, sample_weight = 10, 1e-5, None\n+ assert _get_n_samples_bootstrap(n_samples, max_samples, sample_weight) == 1\n+\n+ n_samples, max_samples, sample_weight = 10, 0.66, None\n+ warning_msg = \".+the number of samples.+low number.+max_samples.+as an integer\"\n+ with pytest.warns(UserWarning, match=warning_msg):\n+ assert _get_n_samples_bootstrap(n_samples, max_samples, sample_weight) == int(\n+ max_samples * n_samples\n+ )\n+\n+ n_samples, max_samples, sample_weight = 10, 1e-5, None\n+ with pytest.warns(UserWarning, match=warning_msg):\n+ assert _get_n_samples_bootstrap(n_samples, max_samples, sample_weight) == 1\n+\n+ warning_msg_with_weights = (\n+ \".+the total sum of sample weights.+low number.+max_samples.+as an integer\"\n+ )\n+ rng = np.random.default_rng(0)\n+ n_samples, max_samples, sample_weight = 1_000_000, 1e-5, rng.uniform(size=1_000_000)\n+ with pytest.warns(UserWarning, match=warning_msg_with_weights):\n+ assert _get_n_samples_bootstrap(n_samples, max_samples, sample_weight) == int(\n+ max_samples * sample_weight.sum()\n+ )\n+\n+ sample_weight = np.ones(3)\n+ with warnings.catch_warnings():\n+ warnings.simplefilter(\"error\")\n+\n+ n_samples, max_samples, sample_weight = 100, 30, None\n+ assert (\n+ _get_n_samples_bootstrap(n_samples, max_samples, sample_weight)\n+ == max_samples\n+ )\n+\n+ n_samples, max_samples, sample_weight = 100, 0.5, rng.uniform(size=100)\n+ assert _get_n_samples_bootstrap(n_samples, max_samples, sample_weight) == int(\n+ max_samples * sample_weight.sum()\n+ )\n+\n+\n def test_oob_score_removed_on_warm_start():\n X, y = make_hastie_10_2(n_samples=100, random_state=1)" } ], "reviews": [ { "id": 3525912524, "user": "user_e43769eee4e2", "state": "COMMENTED", "body": null, "submitted_at": "2025-12-01T16:28:08+00:00" }, { "id": 3525930660, "user": "user_e43769eee4e2", "state": "COMMENTED", "body": null, "submitted_at": "2025-12-01T16:31:14+00:00" }, { "id": 3526102967, "user": "user_566c02088fba", "state": "APPROVED", "body": "LGTM. A few comments/questions, but nothing blocking.", "submitted_at": "2025-12-01T17:35:39+00:00" }, { "id": 3529003227, "user": "user_e43769eee4e2", "state": "COMMENTED", "body": null, "submitted_at": "2025-12-02T09:05:53+00:00" }, { "id": 3529070870, "user": "user_e43769eee4e2", "state": "COMMENTED", "body": null, "submitted_at": "2025-12-02T09:21:09+00:00" }, { "id": 3529107125, "user": "user_e43769eee4e2", "state": "COMMENTED", "body": null, "submitted_at": "2025-12-02T09:28:27+00:00" }, { "id": 3535433879, "user": "user_fca2535bcd49", "state": "COMMENTED", "body": null, "submitted_at": "2025-12-03T14:49:04+00:00" }, { "id": 3535441631, "user": "user_fca2535bcd49", "state": "COMMENTED", "body": null, "submitted_at": "2025-12-03T14:50:46+00:00" }, { "id": 3535107703, "user": "user_5819d17296ee", "state": "COMMENTED", "body": "I agree, the behavior might be less surprising for `sample_weight` users. But we do lose the strict weight/repetition equivalence (frequency semantics) when using the default `max_samples=None`.\n\nBut's it's easy to restore the frequency semantics by [NAME_REDACTED] `max_samples=1.0` explicitly (or alternatively `max_samples=some_integer_of_choice`) after making a conscious decision, so maybe this is not a big deal.", "submitted_at": "2025-12-03T14:52:02+00:00" }, { "id": 3535570626, "user": "user_e43769eee4e2", "state": "COMMENTED", "body": null, "submitted_at": "2025-12-03T15:18:12+00:00" }, { "id": 3535640809, "user": "user_5819d17296ee", "state": "COMMENTED", "body": null, "submitted_at": "2025-12-03T15:33:49+00:00" }, { "id": 3535654142, "user": "user_5819d17296ee", "state": "COMMENTED", "body": null, "submitted_at": "2025-12-03T15:36:34+00:00" }, { "id": 3535673700, "user": "user_5819d17296ee", "state": "APPROVED", "body": "Assuming that we are all ok with explicitly not implementing frequency weights by [NAME_REDACTED] estimator, I am fine with the contents of this PR.\n\nAt least the docstring should be explicit enough.\n\ncc [USER_REDACTED] [USER_REDACTED].", "submitted_at": "2025-12-03T15:40:32+00:00" }, { "id": 3535676820, "user": "user_e43769eee4e2", "state": "COMMENTED", "body": null, "submitted_at": "2025-12-03T15:41:07+00:00" }, { "id": 3535679046, "user": "user_fca2535bcd49", "state": "COMMENTED", "body": null, "submitted_at": "2025-12-03T15:41:24+00:00" }, { "id": 3535719763, "user": "user_fca2535bcd49", "state": "COMMENTED", "body": null, "submitted_at": "2025-12-03T15:47:42+00:00" }, { "id": 3539387086, "user": "user_fca2535bcd49", "state": "COMMENTED", "body": null, "submitted_at": "2025-12-04T11:01:54+00:00" }, { "id": 3539461573, "user": "user_566c02088fba", "state": "COMMENTED", "body": null, "submitted_at": "2025-12-04T11:17:01+00:00" }, { "id": 3539481953, "user": "user_566c02088fba", "state": "COMMENTED", "body": null, "submitted_at": "2025-12-04T11:21:21+00:00" }, { "id": 3543687165, "user": "user_9cabc0c64225", "state": "APPROVED", "body": null, "submitted_at": "2025-12-05T08:53:32+00:00" } ], "review_comments": [ { "id": 2577784053, "user": "user_e43769eee4e2", "body": "Instead of raising an error when `sample_weigth.sum() < 1` as in #31414, here we always return something $\\geq 1$, but we raise a warning if for any reason (small sample_weight, or small dataset or small max_samples value) the final number of bootstrap samples is \"small\" (now it is hardcoded in `_get_n_samples_bootstrap` than less than 10 is small).", "path": "sklearn/ensemble/tests/test_bagging.py", "line": 721, "side": "RIGHT", "created_at": "2025-12-01T16:28:08+00:00" }, { "id": 2577797613, "user": "user_e43769eee4e2", "body": "Same function as in #31529. Will be refactored in #31529 once this PR is merged.", "path": "sklearn/ensemble/_bagging.py", "line": 52, "side": "RIGHT", "created_at": "2025-12-01T16:31:14+00:00" }, { "id": 2577926324, "user": "user_566c02088fba", "body": "Is it ok to have two \"conflicting\" change logs in the same release? \n\nOr would it be better to edit the previous change log?", "path": "doc/whats_new/upcoming_changes/sklearn.ensemble/32825.fix", "line": null, "side": "RIGHT", "created_at": "2025-12-01T17:09:21+00:00" }, { "id": 2577950402, "user": "user_566c02088fba", "body": "```suggestion\n if n_samples_bootstrap < max(10, n_samples ** (1/3)):\n```\n\nI find that hard to believe someone would want to sample less than `cubic_root(n_samples)`.\nI mean, if you made the effort to load and preprocess 1M rows, you probably want to use more than 100 samples in your model.\nI even hesitate with `sqrt(n_samples)`: but maybe that would make this warning too frequent? Maybe a compromise at `n_samples ** 0.4`? 😅", "path": "sklearn/ensemble/_bagging.py", "line": null, "side": "RIGHT", "created_at": "2025-12-01T17:16:21+00:00" }, { "id": 2577954517, "user": "user_566c02088fba", "body": "nit: rename `n_samples_total` to `weighted_n_samples`?", "path": "sklearn/ensemble/_bagging.py", "line": null, "side": "RIGHT", "created_at": "2025-12-01T17:17:38+00:00" }, { "id": 2577958833, "user": "user_566c02088fba", "body": "Would it be ok to import this function in random forests even if it's private? (the logic will be the same right?)", "path": "sklearn/ensemble/_bagging.py", "line": 49, "side": "RIGHT", "created_at": "2025-12-01T17:18:57+00:00" }, { "id": 2580277512, "user": "user_e43769eee4e2", "body": "For me the two changelogs are not in conflict, but complement each other.\n\n31414.fix.rst states that:\n> Furthermore, `max_samples` is now\n interpreted as a fraction of `sample_weight.sum()` instead of `X.shape[0]`\n when passed as a float.\n\nIt remains true in this PR (for float max_samples). This PR just adds the None max_samples option.", "path": "doc/whats_new/upcoming_changes/sklearn.ensemble/32825.fix", "line": null, "side": "RIGHT", "created_at": "2025-12-02T09:05:53+00:00" }, { "id": 2580329106, "user": "user_e43769eee4e2", "body": "We can do a little refactoring in #31529 after this one is merged, as indeed I think both forest and bagging now share the same logic for the number of bootstrap samples. I think it's ok to have a few private function import , but we can make `_get_n_samples_bootstrap` public and maybe relocate it if need be in #31529.", "path": "sklearn/ensemble/_bagging.py", "line": 49, "side": "RIGHT", "created_at": "2025-12-02T09:21:09+00:00" }, { "id": 2580354429, "user": "user_e43769eee4e2", "body": "No idea what a suspiciously \"small\" `n_samples_bootstrap` could be in general, I let you and other reviewers decide a good heuristic :)", "path": "sklearn/ensemble/_bagging.py", "line": null, "side": "RIGHT", "created_at": "2025-12-02T09:28:27+00:00" }, { "id": 2585166714, "user": "user_5819d17296ee", "body": "```suggestion\n \"We recommend passing `max_samples` as an integer instead.\"\n```", "path": "sklearn/ensemble/_bagging.py", "line": null, "side": "RIGHT", "created_at": "2025-12-03T13:41:43+00:00" }, { "id": 2585168190, "user": "user_5819d17296ee", "body": "I like the cubic root heuristic, floored by 10.", "path": "sklearn/ensemble/_bagging.py", "line": null, "side": "RIGHT", "created_at": "2025-12-03T13:42:10+00:00" }, { "id": 2585170700, "user": "user_5819d17296ee", "body": "```suggestion\n - If None, then draw `X.shape[0]` samples irrespective of `sample_weight`.\n```", "path": "sklearn/ensemble/_bagging.py", "line": null, "side": "RIGHT", "created_at": "2025-12-03T13:42:57+00:00" }, { "id": 2585423870, "user": "user_fca2535bcd49", "body": "You need this file to be a `.rst`, in an ideal world, CI would complain, but it looks like it does not ...\n\nI noticed because I was not able to find the changelog entry in the rendered HTML ...", "path": "doc/whats_new/upcoming_changes/sklearn.ensemble/32825.fix", "line": 1, "side": "RIGHT", "created_at": "2025-12-03T14:49:04+00:00" }, { "id": 2585430483, "user": "user_fca2535bcd49", "body": "At the same time you can decide to merge the two changelog entries if that is simpler to understand from a user perspective. IIRC changelog entries are merged by [NAME_REDACTED] (not 100% sure) and depending on how much activity has gone into this module, they may not be close to each other.\n\nOne way to do this is something like I did in https://github.com/[USER_REDACTED]n/scikit-learn/pull/32831. Basically you use a single changelog entry and you mention one PR with `:pr:` in the text and the other one is added automatically based on the filename.", "path": "doc/whats_new/upcoming_changes/sklearn.ensemble/32825.fix", "line": null, "side": "RIGHT", "created_at": "2025-12-03T14:50:46+00:00" }, { "id": 2585431110, "user": "user_5819d17296ee", "body": "Maybe we can help advanced users make an informed choice about the `max_features` value here.\n\n```suggestion\n Sample weights with frequency semantics when `max_features` is explicitly\n set to a float or integer value. When keeping the `max_features=None` default\n value, the equivalence between fitting with integer weighted data points or\n integer repeated data points is no longer guaranteed because the effective\n bootstrap size is no longer guaranteed to be equivalent.\n```", "path": "sklearn/ensemble/_bagging.py", "line": null, "side": "RIGHT", "created_at": "2025-12-03T14:50:57+00:00" }, { "id": 2585535235, "user": "user_e43769eee4e2", "body": "[USER_REDACTED] good catch for the missing extension! I tried your hack by [NAME_REDACTED] in the new one (and removing the old one). The output of towncrier seems okay:\n\n```rst\n:mod:`sklearn.ensemble`\n-----------------------\n\n- |Fix| :class:`ensemble.BaggingClassifier`, :class:`ensemble.BaggingRegressor` and\n :class:`ensemble.IsolationForest` now use `sample_weight` to draw the samples\n instead of forwarding them multiplied by a uniformly sampled mask to the\n underlying estimators. Furthermore, `max_samples` is now interpreted as a\n fraction of `sample_weight.sum()` instead of `X.shape[0]` when passed as a\n float. The new default `max_samples=None` draws `X.shape[0]` samples,\n irrespective of `sample_weight`. \n By :user:`[NAME_REDACTED] `. :pr:`31414` and :pr:`32825`\n```", "path": "doc/whats_new/upcoming_changes/sklearn.ensemble/32825.fix", "line": null, "side": "RIGHT", "created_at": "2025-12-03T15:18:12+00:00" }, { "id": 2585593475, "user": "user_5819d17296ee", "body": "For reviewers, I updated the notebooks of our sample weight analyzer, in particular this want to highlight the fact that `max_samples=None` breaks frequency weights semantics:\n\nhttps://github.com/[USER_REDACTED]nath-xoc/sample-weight-audit-nondet/blob/main/reports/sklearn_estimators_sample_weight_audit_investigative_plots.ipynb\n\nThe p-value is very small: the null-hypothesis that fitting with integer weights is equivalent to fitting with repeated data points is rejected.\n\nEditing the cell to select either `max_samples=1.0` or `max_samples=100` restores large p-values, even when increasing `n_stochastic_fits` meaning that we cannot reject the null-hypothesis that frequency weights semantics are respected.", "path": "sklearn/ensemble/_bagging.py", "line": 71, "side": "RIGHT", "created_at": "2025-12-03T15:33:49+00:00" }, { "id": 2585603571, "user": "user_5819d17296ee", "body": "Alternatively, you could keep both `doc/whats_new/upcoming_changes/sklearn.ensemble/31414.fix.rst` and `doc/whats_new/upcoming_changes/sklearn.ensemble/32825.fix.rst` and make sure that they have the same text and not PR number in them. As a result, the towncrier tool will merge this.", "path": "doc/whats_new/upcoming_changes/sklearn.ensemble/32825.fix.rst", "line": 8, "side": "RIGHT", "created_at": "2025-12-03T15:36:34+00:00" }, { "id": 2585621983, "user": "user_e43769eee4e2", "body": "Yes, we could recommend: \n1. `max_samples` = some_integer as the safest choice for `sample_weight` semantics (repeated/weighted equivalence for integer weights and safe with rescaled weights)\n2. `max_samples` = some_float as the second best (repeated/weighted equivalence for integer weights but unsafe with rescaled weights)\n3. default `max_samples = None` does not respect the repeated/weighted equivalence for integer weights", "path": "sklearn/ensemble/_bagging.py", "line": 71, "side": "RIGHT", "created_at": "2025-12-03T15:41:07+00:00" }, { "id": 2585623531, "user": "user_fca2535bcd49", "body": "Yep, but personally as I said in https://github.com/[USER_REDACTED]n/scikit-learn/pull/32831 I find this towncrier functionality a bit too magical and prefer the `:pr:` way which feels simpler and more understandable ... I actually saw Christian use the `:pr:` way and quite liked it.", "path": "doc/whats_new/upcoming_changes/sklearn.ensemble/32825.fix.rst", "line": 8, "side": "RIGHT", "created_at": "2025-12-03T15:41:24+00:00" }, { "id": 2585653399, "user": "user_fca2535bcd49", "body": "Just out of curiousity, do you have some kind of an explanation for cubic root for people without strong intuitions like me?\n\nRight now this is what I am reading:\n- 10 seems like a reasonable minimum samples in a bootstrap (curious why as well :wink:)\n- for 1000 samples cubic root is 10 great that goes back to the 10 samples in a bootstrap heuristic\n- for 1e6 samples cubic root is 100, that kind of seems right (curious why as well :wink:)", "path": "sklearn/ensemble/_bagging.py", "line": null, "side": "RIGHT", "created_at": "2025-12-03T15:47:42+00:00" }, { "id": 2588574851, "user": "user_fca2535bcd49", "body": "Looks like you may want to update the comment here and mentions that this is a heuristic to avoid bootstrap with too few samples. Bonus points if you add a few words about the heuristic 😉\n\nHere is a proposal that you should not follow 😜 \n\n```py\n# magic cubic root heuristic: you are not supposed to understand this, don't even try!\n# Please don't touch this line or the universe may collapse\n```", "path": "sklearn/ensemble/_bagging.py", "line": null, "side": "RIGHT", "created_at": "2025-12-04T11:01:54+00:00" }, { "id": 2588634750, "user": "user_566c02088fba", "body": "We want to detect a \"suspiciously small\" `n_samples_bootstrap`. \n\nA \"suspiciously small\" `n_samples_bootstrap` depends on `n_samples`, so we want to find a threshold that depends on `n_samples`. So we're looking for a function `f(n_samples)` that should be:\n- simple: it's just a warning, we want to keep a simple logic\n- non-decreasing\n- growing slower than a linear function: the more samples you have, the more you may want to brutally down-sample your dataset.\n\n=> `n_samples ** alpha` is a good candidate.\n\nWhy taking 1/3 for this `alpha`? It's a trade-off between two things:\n- raising the warning too often\n- not raising it when `n_samples_bootstrap` is small by mistake\n\nI could imagine my self wanting to use `n_samples_bootstrap = 10_000` for a 1B samples dataset, so 1/2 is too big. But I can't imagine wanting to use `n_samples_bootstrap = 1_000` in this case, so 1/3 is not too big.", "path": "sklearn/ensemble/_bagging.py", "line": null, "side": "RIGHT", "created_at": "2025-12-04T11:17:01+00:00" }, { "id": 2588650198, "user": "user_566c02088fba", "body": "It could be:\n\n```Python\n# raise a warning if n_samples_bootstrap is suspiciously small \n# the heuristic for \"suspiciously small \" might be adapted if found unsuitable in practice\n```", "path": "sklearn/ensemble/_bagging.py", "line": null, "side": "RIGHT", "created_at": "2025-12-04T11:21:21+00:00" } ], "meta": { "languages": [ "py", "rst" ], "touches_tests": true, "review_state_summary": { "COMMENTED": 17, "APPROVED": 3 }, "meaningful_comment_count": 24, "has_approval": true, "has_changes_requested": false, "total_review_comments": 24 } } { "_id": "2e2669d5d1310486", "_schema_version": "1.0", "_cleaned_at": "2026-02-12T07:46:52.023342+00:00", "repo": "scikit-learn/scikit-learn", "repo_url": "https://github.com/scikit-learn/scikit-learn", "license_name": "BSD 3-Clause \"New\" or \"Revised\" License", "license_spdx": "BSD-3-Clause", "pr_number": 32813, "title": "MNT: Fix `pre-commit run --all-files`", "body": "Currently `pre-commit run --all-files` fails, which damages the contributor experience\n\nI know better than to get into discussions related to https://github.com/[USER_REDACTED]n/scikit-learn/issues/32500, so I've left that alone, but this at least ensures that running `pre-commit` in a current PR doesn't result in unrelated changes\n\n\n\n#### [NAME_REDACTED]/PRs\n\n\n#### What does this implement/fix? Explain your changes.\n\n#### Any other comments?\n\n\n\n", "author": "user_a748edeef6bb", "created_at": "2025-11-28T15:17:30+00:00", "merged_at": "2026-01-05T15:18:49+00:00", "base_branch": "main", "head_branch": "pre-commit-fix", "additions": 9, "deletions": 11, "changed_files": 4, "files": [ { "filename": "doc/about.rst", "status": "modified", "additions": 6, "deletions": 8, "changes": 14, "patch": "@@ -263,7 +263,7 @@ Bronze sponsors\n \n .. div:: text-box\n \n- `NVIDIA `_ supports scikit-learn through their sponsorship and employs full-time core maintainer [NAME_REDACTED]. \n+ `NVIDIA `_ supports scikit-learn through their sponsorship and employs full-time core maintainer [NAME_REDACTED].\n \n .. div:: image-box\n \n@@ -525,7 +525,7 @@ list of events.\n Donating to the project\n =======================\n \n-If you have found scikit-learn to be useful in your work, research, or company, \n+If you have found scikit-learn to be useful in your work, research, or company,\n please consider making a donation to the project commensurate with your resources.\n There are several options for making donations:\n \n@@ -558,21 +558,19 @@ There are several options for making donations:\n able to make a donation with a company match as high as 100%. Our project\n ID is `433725 `_.\n \n-All donations are managed by `NumFOCUS `_, a 501(c)(3) \n+All donations are managed by `NumFOCUS `_, a 501(c)(3)\n non-profit organization based in Austin, Texas, USA. The NumFOCUS board\n-consists of `SciPy community members `_. \n+consists of `SciPy community members `_.\n Contributions are tax-deductible to the extent allowed by law.\n \n .. rubric:: Notes\n \n-Contributions support the maintenance of the project, including development, \n-documentation, infrastructure and coding sprints. \n+Contributions support the maintenance of the project, including development,\n+documentation, infrastructure and coding sprints.\n \n \n scikit-learn Swag\n -----------------\n Official scikit-learn swag is available for purchase at the `NumFOCUS online store\n `_.\n A portion of the proceeds from each sale goes to support the scikit-learn project.\n-\n-" }, { "filename": "doc/maintainers_emeritus.rst", "status": "modified", "additions": 1, "deletions": 1, "changes": 2, "patch": "@@ -40,4 +40,4 @@\n - [NAME_REDACTED]\n - [NAME_REDACTED]\n - [NAME_REDACTED]\n-- [NAME_REDACTED]\n\\ No newline at end of file\n+- [NAME_REDACTED]" }, { "filename": "doc/modules/manifold.rst", "status": "modified", "additions": 1, "deletions": 1, "changes": 2, "patch": "@@ -522,7 +522,7 @@ Formally, the loss function of classical MDS (strain) is given by\n \n where :math:`Z` is the :math:`n \\times d` embedding matrix whose rows are\n :math:`z_i^T`, :math:`\\|\\cdot\\|_F` denotes the Frobenius norm, and\n-:math:`B` is the Gram matrix with elements :math:`b_{ij}`, \n+:math:`B` is the Gram matrix with elements :math:`b_{ij}`,\n given by :math:`B = -\\frac{1}{2}C\\Delta C`.\n Here :math:`C\\Delta C` is the double-centered matrix of squared dissimilarities,\n with :math:`\\Delta` being the matrix of squared input dissimilarities" }, { "filename": "pyproject.toml", "status": "modified", "additions": 1, "deletions": 1, "changes": 2, "patch": "@@ -291,7 +291,7 @@ package = \"sklearn\" # name of your package\n whatsnew_pattern = 'doc/whatsnew/upcoming_changes/[^/]+/\\d+\\.[^.]+\\.rst'\n \n [tool.codespell]\n-skip = [\"./.git\", \"*.svg\", \"./.mypy_cache\", \"./sklearn/feature_extraction/_stop_words.py\", \"./sklearn/feature_extraction/tests/test_text.py\", \"./doc/_build\", \"./doc/auto_examples\", \"./doc/modules/generated\"]\n+skip = [\"./.git\", \"*.svg\", \"./.mypy_cache\", \"*sklearn/feature_extraction/_stop_words.py\", \"*sklearn/feature_extraction/tests/test_text.py\", \"./doc/_build\", \"./doc/auto_examples\", \"./doc/modules/generated\"]\n ignore-words = \"build_tools/codespell_ignore_words.txt\"\n \n [tool.towncrier]" } ], "reviews": [ { "id": 3519391603, "user": "user_a748edeef6bb", "state": "COMMENTED", "body": null, "submitted_at": "2025-11-28T15:39:35+00:00" }, { "id": 3519551628, "user": "user_fca2535bcd49", "state": "COMMENTED", "body": null, "submitted_at": "2025-11-28T16:56:29+00:00" }, { "id": 3519567073, "user": "user_fca2535bcd49", "state": "COMMENTED", "body": null, "submitted_at": "2025-11-28T17:05:13+00:00" }, { "id": 3529368333, "user": "user_34a090906ca4", "state": "COMMENTED", "body": null, "submitted_at": "2025-12-02T10:26:19+00:00" }, { "id": 3529445232, "user": "user_34a090906ca4", "state": "COMMENTED", "body": null, "submitted_at": "2025-12-02T10:46:37+00:00" }, { "id": 3622938378, "user": "user_a748edeef6bb", "state": "COMMENTED", "body": null, "submitted_at": "2026-01-02T11:06:17+00:00" }, { "id": 3622939055, "user": "user_a748edeef6bb", "state": "COMMENTED", "body": null, "submitted_at": "2026-01-02T11:06:48+00:00" }, { "id": 3626370396, "user": "user_34a090906ca4", "state": "APPROVED", "body": "Thank you, [USER_REDACTED]!\n\nI checked the PR out locally and can confirm that all checks pass when running `pre-commit run --all-files` (also after merging main, just to make sure).", "submitted_at": "2026-01-05T10:49:46+00:00" }, { "id": 3626988624, "user": "user_49a647962c6b", "state": "COMMENTED", "body": null, "submitted_at": "2026-01-05T14:07:31+00:00" }, { "id": 3627086222, "user": "user_a748edeef6bb", "state": "COMMENTED", "body": null, "submitted_at": "2026-01-05T14:30:38+00:00" }, { "id": 3627100121, "user": "user_34a090906ca4", "state": "COMMENTED", "body": null, "submitted_at": "2026-01-05T14:34:43+00:00" }, { "id": 3627103488, "user": "user_a748edeef6bb", "state": "COMMENTED", "body": null, "submitted_at": "2026-01-05T14:35:42+00:00" }, { "id": 3627135483, "user": "user_49a647962c6b", "state": "APPROVED", "body": null, "submitted_at": "2026-01-05T14:43:38+00:00" } ], "review_comments": [ { "id": 2572013629, "user": "user_a748edeef6bb", "body": "this is the version in the dev guide https://github.com/[USER_REDACTED]n/scikit-learn/blob/a9876111036fca025c26448eff072b3ab6e6208b/doc/developers/development_setup.rst#L132", "path": ".pre-commit-config.yaml", "line": null, "side": "RIGHT", "created_at": "2025-11-28T15:39:35+00:00" }, { "id": 2572158106, "user": "user_fca2535bcd49", "body": "Good catch, I would guess we forgot to update the dev guide, so I would update the dev guide instead.", "path": ".pre-commit-config.yaml", "line": null, "side": "RIGHT", "created_at": "2025-11-28T16:56:29+00:00" }, { "id": 2572171844, "user": "user_fca2535bcd49", "body": "Can we do the same but in pyproject.toml where we already have a `tool.codespell` section?", "path": ".pre-commit-config.yaml", "line": null, "side": "RIGHT", "created_at": "2025-11-28T17:05:13+00:00" }, { "id": 2580570443, "user": "user_34a090906ca4", "body": "In pyproject.toml we actually have this:\n```\n[tool.codespell]\nskip = [\"./.git\", \"*.svg\", \"./.mypy_cache\", \"./sklearn/feature_extraction/_stop_words.py\", \"./sklearn/feature_extraction/tests/test_text.py\", \"./doc/_build\", \"./doc/auto_examples\", \"./doc/modules/generated\"]\n```\nbut when [trying out pyrefly](https://github.com/[USER_REDACTED]n/scikit-learn/pull/32737) I also noticed that I had to remove the `./` from the two `.py` file paths for it to actually skip these files.", "path": ".pre-commit-config.yaml", "line": null, "side": "RIGHT", "created_at": "2025-12-02T10:26:19+00:00" }, { "id": 2580635869, "user": "user_34a090906ca4", "body": "In pyproject.toml and _min_dependencies.py it is actually `0.11.7`. Should it be 0.12.2 everywhere (the most current version is 0.14.7)?\nI can then open a separate PR to make the docs consistent (ruff is the only package for which a version is explicitly specified there).", "path": ".pre-commit-config.yaml", "line": null, "side": "RIGHT", "created_at": "2025-12-02T10:46:37+00:00" }, { "id": 2657526633, "user": "user_a748edeef6bb", "body": "thanks, can confirm that removing `./` fixes it (both when running `codespell` directly, and when running it via `pre-commit`)", "path": ".pre-commit-config.yaml", "line": null, "side": "RIGHT", "created_at": "2026-01-02T11:06:16+00:00" }, { "id": 2657527412, "user": "user_a748edeef6bb", "body": "😄 but not in CI by [NAME_REDACTED], taking a look\n\n---\n\nlooks like a glob does the trick", "path": ".pre-commit-config.yaml", "line": null, "side": "RIGHT", "created_at": "2026-01-02T11:06:48+00:00" }, { "id": 2661622987, "user": "user_49a647962c6b", "body": "I'm so confused as why these files are added here.", "path": "doc/whats_new/upcoming_changes/sklearn.cluster/31973.fix.rst", "line": null, "side": "RIGHT", "created_at": "2026-01-05T14:07:28+00:00" }, { "id": 2661703932, "user": "user_a748edeef6bb", "body": "hmm something went wrong, updating now", "path": "doc/whats_new/upcoming_changes/sklearn.cluster/31973.fix.rst", "line": null, "side": "RIGHT", "created_at": "2026-01-05T14:30:38+00:00" }, { "id": 2661715851, "user": "user_34a090906ca4", "body": "Oh, I overlooked that they are added as new files here. I think they are still here because this PR was opened before the last release. `ruff` fixed some whitespace \"issues\" in them, but I guess they get removed once the release is out, so they should probably be removed here as well?", "path": "doc/whats_new/upcoming_changes/sklearn.cluster/31973.fix.rst", "line": null, "side": "RIGHT", "created_at": "2026-01-05T14:34:43+00:00" }, { "id": 2661718790, "user": "user_a748edeef6bb", "body": "yup thanks, embarassing merge conflict (non-)resolution here 🙈 😳 \n\nhave updated, thanks!", "path": "doc/whats_new/upcoming_changes/sklearn.cluster/31973.fix.rst", "line": null, "side": "RIGHT", "created_at": "2026-01-05T14:35:42+00:00" } ], "meta": { "languages": [ "rst", "toml" ], "touches_tests": false, "review_state_summary": { "COMMENTED": 11, "APPROVED": 2 }, "meaningful_comment_count": 11, "has_approval": true, "has_changes_requested": false, "total_review_comments": 11 } } { "_id": "4ce638afbff82fc0", "_schema_version": "1.0", "_cleaned_at": "2026-02-12T07:46:52.023342+00:00", "repo": "scikit-learn/scikit-learn", "repo_url": "https://github.com/scikit-learn/scikit-learn", "license_name": "BSD 3-Clause \"New\" or \"Revised\" License", "license_spdx": "BSD-3-Clause", "pr_number": 32810, "title": "CI Move pylatest_pip_openblas_pandas to [NAME_REDACTED]", "body": "This moves `pylatest_pip_openblas_pandas` job from Azure to [NAME_REDACTED] on it together with [USER_REDACTED].\n\nPart of #32434.", "author": "user_501030d9d7e3", "created_at": "2025-11-28T14:38:04+00:00", "merged_at": "2025-12-01T13:43:37+00:00", "base_branch": "main", "head_branch": "migrate1", "additions": 18, "deletions": 15, "changed_files": 2, "files": [ { "filename": ".github/workflows/unit-tests.yml", "status": "modified", "additions": 18, "deletions": 1, "changes": 19, "patch": "@@ -125,14 +125,31 @@ jobs:\n os: ubuntu-24.04-arm\n DISTRIB: conda\n LOCK_FILE: build_tools/github/pymin_conda_forge_arm_linux-aarch64_conda.lock\n+\n+ # Linux environment to test the latest available dependencies.\n+ # It runs tests requiring lightgbm, pandas and PyAMG.\n+ - name: Linux pylatest_pip_openblas_pandas\n+ os: ubuntu-24.04\n+ DISTRIB: conda\n+ LOCK_FILE: build_tools/azure/pylatest_pip_openblas_pandas_linux-64_conda.lock\n+ SKLEARN_TESTS_GLOBAL_RANDOM_SEED: 3 # non-default seed\n+ SCIPY_ARRAY_API: 1\n+ CHECK_PYTEST_SOFT_DEPENDENCY: true\n+ SKLEARN_WARNINGS_AS_ERRORS: 1\n+ # disable pytest-xdist to have 1 job where OpenMP and BLAS are not single\n+ # threaded because by [NAME_REDACTED] (sklearn/conftest.py)\n+ # makes sure that they are single threaded in each xdist subprocess.\n+ PYTEST_XDIST_VERSION: none\n+ PIP_BUILD_ISOLATION: true\n+\n - name: macOS pylatest_conda_forge_arm\n os: macOS-15\n DISTRIB: conda\n LOCK_FILE: build_tools/azure/pylatest_conda_forge_osx-arm64_conda.lock\n SKLEARN_TESTS_GLOBAL_RANDOM_SEED: 5 # non-default seed\n SCIPY_ARRAY_API: 1\n PYTORCH_ENABLE_MPS_FALLBACK: 1\n- CHECK_PYTEST_SOFT_DEPENDENCY: 'true'\n+ CHECK_PYTEST_SOFT_DEPENDENCY: true\n \n env: ${{ matrix }}" }, { "filename": "azure-pipelines.yml", "status": "modified", "additions": 0, "deletions": 14, "changes": 14, "patch": "@@ -183,20 +183,6 @@ jobs:\n SKLEARN_ENABLE_DEBUG_CYTHON_DIRECTIVES: '1'\n SKLEARN_RUN_FLOAT32_TESTS: '1'\n SKLEARN_TESTS_GLOBAL_RANDOM_SEED: '2' # non-default seed\n- # Linux environment to test the latest available dependencies.\n- # It runs tests requiring lightgbm, pandas and PyAMG.\n- pylatest_pip_openblas_pandas:\n- DISTRIB: 'conda-pip-latest'\n- LOCK_FILE: './build_tools/azure/pylatest_pip_openblas_pandas_linux-64_conda.lock'\n- CHECK_PYTEST_SOFT_DEPENDENCY: 'true'\n- SKLEARN_WARNINGS_AS_ERRORS: '1'\n- SKLEARN_TESTS_GLOBAL_RANDOM_SEED: '3' # non-default seed\n- # disable pytest-xdist to have 1 job where OpenMP and BLAS are not single\n- # threaded because by [NAME_REDACTED] (sklearn/conftest.py)\n- # makes sure that they are single threaded in each xdist subprocess.\n- PYTEST_XDIST_VERSION: 'none'\n- PIP_BUILD_ISOLATION: 'true'\n- SCIPY_ARRAY_API: '1'\n \n - template: build_tools/azure/posix-docker.yml\n parameters:" } ], "reviews": [ { "id": 3520495723, "user": "user_fca2535bcd49", "state": "COMMENTED", "body": null, "submitted_at": "2025-11-29T05:57:06+00:00" }, { "id": 3524269228, "user": "user_501030d9d7e3", "state": "COMMENTED", "body": null, "submitted_at": "2025-12-01T10:25:07+00:00" }, { "id": 3524889867, "user": "user_fca2535bcd49", "state": "COMMENTED", "body": null, "submitted_at": "2025-12-01T13:02:57+00:00" }, { "id": 3524890558, "user": "user_fca2535bcd49", "state": "APPROVED", "body": "LGTM, thanks!", "submitted_at": "2025-12-01T13:03:08+00:00" }, { "id": 3524961587, "user": "user_501030d9d7e3", "state": "COMMENTED", "body": null, "submitted_at": "2025-12-01T13:20:21+00:00" } ], "review_comments": [ { "id": 2572825636, "user": "user_fca2535bcd49", "body": "I looked at `install.sh`, I think this is an historical quirk [^1], this can be replaced by [NAME_REDACTED]:\n```suggestion\n DISTRIB: 'conda'\n```\n\nThe fact that packages are installed with pip in already part of the build name `pylatest_pip_...` so I don't think there is much point of keeping it in the `DISTRIB`.\n\n[^1]: probably we were handling things differently in the past in `install.sh` but now the fact that we are installing the packages with `pip` is part of the lock-file.", "path": ".github/workflows/unit-tests.yml", "line": null, "side": "RIGHT", "created_at": "2025-11-29T05:57:06+00:00" }, { "id": 2576503329, "user": "user_501030d9d7e3", "body": "Yes, I see, it matches with `[[ \"$DISTRIB\" == \"conda\"* ]]` and there is no specific check if `DISTRIB == \"conda-pip-latest\"`.\n\nThough I need to admit, before our discussion I would have been confused seeing \"pip\" in the job name while DISTRIB is set to something starting with \"conda.\" I would have thought that's an error. Would renaming DISTRIB to something like INSTALL_METHOD help to clarify its more the purpose? Just a thought.", "path": ".github/workflows/unit-tests.yml", "line": null, "side": "RIGHT", "created_at": "2025-12-01T10:25:07+00:00" }, { "id": 2576994266, "user": "user_fca2535bcd49", "body": "Yeah the naming is not ideal but at the same time it has been like this for a while (mostly for historical reasons) and it doesn't bother me too much ...\n\nIn my mind the `DISTRIB` is one of the variable to drive the possible variations in `build_tools/install.sh`. \n- `DISTRIB=conda*` means the environment is installed from a conda-lock lock-file \n - sometimes we need additional tweaks on top of the lock-file e.g. `DISTRIB=conda-pip-scipy-dev` which installs development versions of numpy, scipy, etc ...\n - I guess `conda-pip-latest` also had additional tweaks at one point but not anymore since all the info comes from the lock-file\n- sometimes we use the system Python and DISTRIB is kind of a Linux distribution (hence I guess the original name `DISTRIB` probably means \"distribution\") e.g. `ubuntu` or `debian-32`\n\nMaybe it's something we could revisit once the Azure -> GHA migration is over?", "path": ".github/workflows/unit-tests.yml", "line": null, "side": "RIGHT", "created_at": "2025-12-01T13:02:57+00:00" }, { "id": 2577052863, "user": "user_501030d9d7e3", "body": "> Maybe it's something we could revisit once the Azure -> GHA migration is over?\n\nYes, I think it will be useful to use a more speaking name sometime in the future.", "path": ".github/workflows/unit-tests.yml", "line": null, "side": "RIGHT", "created_at": "2025-12-01T13:20:21+00:00" } ], "meta": { "languages": [ "yml" ], "touches_tests": false, "review_state_summary": { "COMMENTED": 4, "APPROVED": 1 }, "meaningful_comment_count": 4, "has_approval": true, "has_changes_requested": false, "total_review_comments": 4 } } { "_id": "4c35214eaed16fb4", "_schema_version": "1.0", "_cleaned_at": "2026-02-12T07:46:52.038957+00:00", "repo": "tensorflow/tensorflow", "repo_url": "https://github.com/tensorflow/tensorflow", "license_name": "Apache License 2.0", "license_spdx": "Apache-2.0", "pr_number": 109808, "title": "Update requirements.in and setup.py.tpl and generate lock files", "body": null, "author": "user_2f832b18679d", "created_at": "2026-02-05T19:50:31+00:00", "merged_at": "2026-02-06T19:26:05+00:00", "base_branch": "r2.21", "head_branch": "r2.21", "additions": 920, "deletions": 276, "changed_files": 10, "files": [ { "filename": "ci/official/requirements_updater/numpy1_requirements/requirements.in", "status": "modified", "additions": 2, "deletions": 2, "changes": 4, "patch": "@@ -18,8 +18,8 @@ auditwheel >= 6.1.0\n # Note that here we want the latest version that matches TF major.minor version\n # Note that we must use nightly here as these are used in nightly jobs\n # For release jobs, we will pin these on the release branch\n-keras-nightly ~= 3.12.0.dev\n-tb-nightly ~= 2.20.0.a\n+keras ~= 3.12.0\n+tensorboard ~= 2.20.0\n # For new protobuf, if V.x.y is gencode version, then runtime version U must be\n # V <= U <= V+1\n # More info at https://protobuf.dev/support/cross-version-runtime-guarantee/" }, { "filename": "ci/official/requirements_updater/numpy1_requirements/requirements_lock_3_10.txt", "status": "modified", "additions": 146, "deletions": 54, "changes": 200, "patch": "@@ -2,26 +2,26 @@\n # This file is autogenerated by [NAME_REDACTED] 3.10\n # by [NAME_REDACTED]:\n #\n-# bazel run //ci/official/requirements_updater:requirements.update\n+# bazel run //ci/official/requirements_updater/numpy1_requirements:requirements_310.update\n #\n absl-py==2.2.2 \\\n --hash=sha256:bf25b2c2eed013ca456918c453d687eab4e8309fba81ee2f4c1a6aa2494175eb \\\n --hash=sha256:e5797bc6abe45f64fd95dc06394ca3f2bedf3b5d895e9da691c9ee3397d70092\n # via\n- # keras-nightly\n- # tb-nightly\n+ # keras\n+ # tensorboard\n astor==0.7.1 \\\n --hash=sha256:95c30d87a6c2cf89aa628b87398466840f0ad8652f88eb173125a6df8533fb8d \\\n --hash=sha256:fb503b9e2fdd05609fbf557b916b4a7824171203701660f0c55bbf5a7a68713e\n- # via -r ci/official/requirements_updater/requirements.in\n+ # via -r ci/official/requirements_updater/numpy1_requirements/requirements.in\n astunparse==1.6.3 \\\n --hash=sha256:5ad93a8456f0d084c3456d059fd9a92cce667963232cbf763eac3bc5b7940872 \\\n --hash=sha256:c2652417f2c8b5bb325c885ae329bdf3f86424075c4fd1a128674bc6fba4b8e8\n- # via -r ci/official/requirements_updater/requirements.in\n+ # via -r ci/official/requirements_updater/numpy1_requirements/requirements.in\n auditwheel==6.3.0 \\\n --hash=sha256:05c70a234fa14c140aa6d9076135d9550962d95849911b8d5d0419a3add09f00 \\\n --hash=sha256:31cbd8045d4ff6776f79bef328b5fd563e5ecc8ae82ea34b6fe5e76efe2a84eb\n- # via -r ci/official/requirements_updater/requirements.in\n+ # via -r ci/official/requirements_updater/numpy1_requirements/requirements.in\n certifi==2025.1.31 \\\n --hash=sha256:3d5da6925056f6f18f119200434a4780a94263f10d1c21d032a6f6b2baa20651 \\\n --hash=sha256:ca78db4565a652026a4db2bcdf68f2fb589ea80d0be70e03929ed730746b84fe\n@@ -123,20 +123,20 @@ charset-normalizer==3.4.1 \\\n dill==0.3.7 \\\n --hash=sha256:76b122c08ef4ce2eedcd4d1abd8e641114bfc6c2867f49f3c41facf65bf19f5e \\\n --hash=sha256:cc1c8b182eb3013e24bd475ff2e9295af86c1a38eb1aff128dac8962a9ce3c03\n- # via -r ci/official/requirements_updater/requirements.in\n+ # via -r ci/official/requirements_updater/numpy1_requirements/requirements.in\n flatbuffers==25.9.23 \\\n --hash=sha256:255538574d6cb6d0a79a17ec8bc0d30985913b87513a01cce8bcdb6b4c44d0e2 \\\n --hash=sha256:676f9fa62750bb50cf531b42a0a2a118ad8f7f797a511eda12881c016f093b12\n- # via -r ci/official/requirements_updater/requirements.in\n+ # via -r ci/official/requirements_updater/numpy1_requirements/requirements.in\n gast==0.4.0 \\\n --hash=sha256:40feb7b8b8434785585ab224d1568b857edb18297e5a3047f1ba012bc83b42c1 \\\n --hash=sha256:b7adcdd5adbebf1adf17378da5ba3f543684dbec47b1cda1f3997e573cd542c4\n- # via -r ci/official/requirements_updater/requirements.in\n+ # via -r ci/official/requirements_updater/numpy1_requirements/requirements.in\n google-pasta==0.2.0 \\\n --hash=sha256:4612951da876b1a10fe3960d7226f0c7682cf901e16ac06e473b267a5afa8954 \\\n --hash=sha256:b32482794a366b5366a32c92a9a9201b107821889935a02b3e51f6b432ea84ed \\\n --hash=sha256:c9f2c8dfc8f96d0d5808299920721be30c9eec37f2389f28904f454565c8a16e\n- # via -r ci/official/requirements_updater/requirements.in\n+ # via -r ci/official/requirements_updater/numpy1_requirements/requirements.in\n grpcio==1.71.0 \\\n --hash=sha256:0ab8b2864396663a5b0b0d6d79495657ae85fa37dcb6498a2669d067c65c11ea \\\n --hash=sha256:0fa05ee31a20456b13ae49ad2e5d585265f71dd19fbd9ef983c28f926d45d0a7 \\\n@@ -190,8 +190,8 @@ grpcio==1.71.0 \\\n --hash=sha256:f9a412f55bb6e8f3bb000e020dbc1e709627dcb3a56f6431fa7076b4c1aab0db \\\n --hash=sha256:f9c30c464cb2ddfbc2ddf9400287701270fdc0f14be5f08a1e3939f1e749b455\n # via\n- # -r ci/official/requirements_updater/requirements.in\n- # tb-nightly\n+ # -r ci/official/requirements_updater/numpy1_requirements/requirements.in\n+ # tensorboard\n h5py==3.13.0 \\\n --hash=sha256:10894c55d46df502d82a7a4ed38f9c3fdbcb93efb42e25d275193e093071fade \\\n --hash=sha256:1870e46518720023da85d0895a1960ff2ce398c5671eac3b1a41ec696b7105c3 \\\n@@ -220,19 +220,19 @@ h5py==3.13.0 \\\n --hash=sha256:f35640e81b03c02a88b8bf99fb6a9d3023cc52f7c627694db2f379e0028f2868 \\\n --hash=sha256:fb267ce4b83f9c42560e9ff4d30f60f7ae492eacf9c7ede849edf8c1b860e16b\n # via\n- # -r ci/official/requirements_updater/requirements.in\n- # keras-nightly\n+ # -r ci/official/requirements_updater/numpy1_requirements/requirements.in\n+ # keras\n idna==3.10 \\\n --hash=sha256:12f65c9b470abda6dc35cf8e63cc574b1c52b11df2c86030af0ac09b01b13ea9 \\\n --hash=sha256:946d195a0d259cbba61165e88e65941f16e9b36ea6ddb97f00452bae8b1287d3\n # via requests\n jax==0.4.7 \\\n --hash=sha256:5e7002d74db25f97c99b979d4ba1233b1ef26e1597e5fc468ad11d1c8a9dc4f8\n- # via -r ci/official/requirements_updater/requirements.in\n-keras-nightly==3.12.0.dev2025100703 \\\n- --hash=sha256:6b9dfb3814d707abf5555f56268f072daec13f2540da3aeeb7531a819ebb4567 \\\n- --hash=sha256:e29434e49bac3360f86af6e1548d94b0a2fda4e793685bc43b49867132ab16e5\n- # via -r ci/official/requirements_updater/requirements.in\n+ # via -r ci/official/requirements_updater/numpy1_requirements/requirements.in\n+keras==3.12.1 \\\n+ --hash=sha256:3cb760b3fec105db4d893dd717daafdd0e35457a8201502c1ba8bedfaf334a71 \\\n+ --hash=sha256:c340f8a25362398b20500c64e290f6ee280c6aeec51e1044eb8d759b32dc272a\n+ # via -r ci/official/requirements_updater/numpy1_requirements/requirements.in\n libclang==18.1.1 \\\n --hash=sha256:0b2e143f0fac830156feb56f9231ff8338c20aecfe72b4ffe96f19e5a1dbb69a \\\n --hash=sha256:3f0e1f49f04d3cd198985fea0511576b0aee16f9ff0e0f0cad7f9c57ec3c20e8 \\\n@@ -244,14 +244,14 @@ libclang==18.1.1 \\\n --hash=sha256:a1214966d08d73d971287fc3ead8dfaf82eb07fb197680d8b3859dbbbbf78250 \\\n --hash=sha256:c533091d8a3bbf7460a00cb6c1a71da93bffe148f172c7d03b1c31fbf8aa2a0b \\\n --hash=sha256:cf4a99b05376513717ab5d82a0db832c56ccea4fd61a69dbb7bccf2dfb207dbe\n- # via -r ci/official/requirements_updater/requirements.in\n+ # via -r ci/official/requirements_updater/numpy1_requirements/requirements.in\n lit==17.0.6 \\\n --hash=sha256:dfa9af9b55fc4509a56be7bf2346f079d7f4a242d583b9f2e0b078fd0abae31b\n- # via -r ci/official/requirements_updater/requirements.in\n+ # via -r ci/official/requirements_updater/numpy1_requirements/requirements.in\n markdown==3.8 \\\n --hash=sha256:794a929b79c5af141ef5ab0f2f642d0f7b1872981250230e72682346f7cc90dc \\\n --hash=sha256:7df81e63f0df5c4b24b7d156eb81e4690595239b7d70937d0409f1b0de319c6f\n- # via tb-nightly\n+ # via tensorboard\n markdown-it-py==3.0.0 \\\n --hash=sha256:355216845c60bd96232cd8d8c40e8f9765cc86f46880e43a8fd22dc1a1a8cab1 \\\n --hash=sha256:e3f60a94fa066dc52ec76661e37c851cb232d92f9886b15cb560aaada2df8feb\n@@ -349,13 +349,13 @@ ml-dtypes==0.5.1 \\\n --hash=sha256:d13755f8e8445b3870114e5b6240facaa7cb0c3361e54beba3e07fa912a6e12b \\\n --hash=sha256:fd918d4e6a4e0c110e2e05be7a7814d10dc1b95872accbf6512b80a109b71ae1\n # via\n- # -r ci/official/requirements_updater/requirements.in\n+ # -r ci/official/requirements_updater/numpy1_requirements/requirements.in\n # jax\n- # keras-nightly\n+ # keras\n namex==0.0.9 \\\n --hash=sha256:7bd4e4a2cc3876592111609fdf4cbe6ff19883adbe6b3b40d842fd340f77025e \\\n --hash=sha256:8adfea9da5cea5be8f4e632349b4669e30172c7859e1fd97459fdf3b17469253\n- # via keras-nightly\n+ # via keras\n numpy==1.26.4 \\\n --hash=sha256:03a8c78d01d9781b28a6989f6fa1bb2c4f2d51201cf99d3dd875df6fbd96b23b \\\n --hash=sha256:08beddf13648eb95f8d867350f6a018a4be2e5ad54c8d8caed89ebca558b2818 \\\n@@ -394,14 +394,14 @@ numpy==1.26.4 \\\n --hash=sha256:f870204a840a60da0b12273ef34f7051e98c3b5961b61b0c2c1be6dfd64fbcd3 \\\n --hash=sha256:ffa75af20b44f8dba823498024771d5ac50620e6915abac414251bd971b4529f\n # via\n- # -r ci/official/requirements_updater/requirements.in\n+ # -r ci/official/requirements_updater/numpy1_requirements/requirements.in\n # h5py\n # jax\n- # keras-nightly\n+ # keras\n # ml-dtypes\n # opt-einsum\n # scipy\n- # tb-nightly\n+ # tensorboard\n nvidia-cublas-cu12==12.5.3.2 \\\n --hash=sha256:4960f3dc5f39699acadf76fa6d94b10a2a00f2956c2c442efa299fb22b0748f3 \\\n --hash=sha256:7d0191251180de606023d396b94d66f66470a0ae96d1dbb906c7656ea0f71eda \\\n@@ -514,7 +514,7 @@ opt-einsum==3.3.0 \\\n --hash=sha256:2455e59e3947d3c275477df7f5205b30635e266fe6dc300e3d9f9646bfcea147 \\\n --hash=sha256:59f6475f77bbc37dcf7cd748519c0ec60722e91e63ca114e68821c0c54a46549\n # via\n- # -r ci/official/requirements_updater/requirements.in\n+ # -r ci/official/requirements_updater/numpy1_requirements/requirements.in\n # jax\n optree==0.16.0 \\\n --hash=sha256:0dd607bfbf59ecf92b069af18e8a41b0d8628e21f2de5a738fad039d0a89d9d4 \\\n@@ -590,19 +590,112 @@ optree==0.16.0 \\\n --hash=sha256:eeccc740b72b58efa9795ab831a678a42341def48b9e5956c6b1e588c6fa3ddf \\\n --hash=sha256:f08aaa1c2ae092b3e662125ad19860046c63d7451d41be133ddd6594920e295e \\\n --hash=sha256:f703d7926c36eebdd56fc08aabefcf32a8b7292a9dd4468e56b0ab61bf6214bd\n- # via keras-nightly\n+ # via keras\n packaging==23.2 \\\n --hash=sha256:048fb0e9405036518eaaf48a55953c750c11e1a1b68e0dd1a9d62ed0c092cfc5 \\\n --hash=sha256:8c491190033a9af7e1d931d0b5dacc2ef47509b34dd0de67ed209b5203fc88c7\n # via\n- # -r ci/official/requirements_updater/requirements.in\n+ # -r ci/official/requirements_updater/numpy1_requirements/requirements.in\n # auditwheel\n- # keras-nightly\n- # tb-nightly\n+ # keras\n+ # tensorboard\n+pillow==12.1.0 \\\n+ --hash=sha256:00162e9ca6d22b7c3ee8e61faa3c3253cd19b6a37f126cad04f2f88b306f557d \\\n+ --hash=sha256:079af2fb0c599c2ec144ba2c02766d1b55498e373b3ac64687e43849fbbef5bc \\\n+ --hash=sha256:0b022eaaf709541b391ee069f0022ee5b36c709df71986e3f7be312e46f42c84 \\\n+ --hash=sha256:0c27407a2d1b96774cbc4a7594129cc027339fd800cd081e44497722ea1179de \\\n+ --hash=sha256:0ddedfaa8b5f0b4ffbc2fa87b556dc59f6bb4ecb14a53b33f9189713ae8053c0 \\\n+ --hash=sha256:0deedf2ea233722476b3a81e8cdfbad786f7adbed5d848469fa59fe52396e4ef \\\n+ --hash=sha256:0ed07dca4a8464bada6139ab38f5382f83e5f111698caf3191cb8dbf27d908b4 \\\n+ --hash=sha256:0fde7ec5538ab5095cc02df38ee99b0443ff0e1c847a045554cf5f9af1f4aa82 \\\n+ --hash=sha256:15c794d74303828eaa957ff8070846d0efe8c630901a1c753fdc63850e19ecd9 \\\n+ --hash=sha256:1a949604f73eb07a8adab38c4fe50791f9919344398bdc8ac6b307f755fc7030 \\\n+ --hash=sha256:1f345e7bc9d7f368887c712aa5054558bad44d2a301ddf9248599f4161abc7c0 \\\n+ --hash=sha256:1fcc52d86ce7a34fd17cb04e87cfdb164648a3662a6f20565910a99653d66c18 \\\n+ --hash=sha256:21e686a21078b0f9cb8c8a961d99e6a4ddb88e0fc5ea6e130172ddddc2e5221a \\\n+ --hash=sha256:2415373395a831f53933c23ce051021e79c8cd7979822d8cc478547a3f4da8ef \\\n+ --hash=sha256:277518bf4fe74aa91489e1b20577473b19ee70fb97c374aa50830b279f25841b \\\n+ --hash=sha256:27b9baecb428899db6c0de572d6d305cfaf38ca1596b5c0542a5182e3e74e8c6 \\\n+ --hash=sha256:29a4cef9cb672363926f0470afc516dbf7305a14d8c54f7abbb5c199cd8f8179 \\\n+ --hash=sha256:3413c2ae377550f5487991d444428f1a8ae92784aac79caa8b1e3b89b175f77e \\\n+ --hash=sha256:351889afef0f485b84078ea40fe33727a0492b9af3904661b0abbafee0355b72 \\\n+ --hash=sha256:3ffaa2f0659e2f740473bcf03c702c39a8d4b2b7ffc629052028764324842c64 \\\n+ --hash=sha256:40a8e3b9e8773876d6e30daed22f016509e3987bab61b3b7fe309d7019a87451 \\\n+ --hash=sha256:414b9a78e14ffeb98128863314e62c3f24b8a86081066625700b7985b3f529bd \\\n+ --hash=sha256:43aca0a55ce1eefc0aefa6253661cb54571857b1a7b2964bd8a1e3ef4b729924 \\\n+ --hash=sha256:43b4899cfd091a9693a1278c4982f3e50f7fb7cff5153b05174b4afc9593b616 \\\n+ --hash=sha256:461f9dfdafa394c59cd6d818bdfdbab4028b83b02caadaff0ffd433faf4c9a7a \\\n+ --hash=sha256:4f9f6a650743f0ddee5593ac9e954ba1bdbc5e150bc066586d4f26127853ab94 \\\n+ --hash=sha256:53d8b764726d3af1a138dd353116f774e3862ec7e3794e0c8781e30db0f35dfc \\\n+ --hash=sha256:565c986f4b45c020f5421a4cea13ef294dde9509a8577f29b2fc5edc7587fff8 \\\n+ --hash=sha256:5c5ae0a06e9ea030ab786b0251b32c7e4ce10e58d983c0d5c56029455180b5b9 \\\n+ --hash=sha256:5cb7bc1966d031aec37ddb9dcf15c2da5b2e9f7cc3ca7c54473a20a927e1eb91 \\\n+ --hash=sha256:5da841d81b1a05ef940a8567da92decaa15bc4d7dedb540a8c219ad83d91808a \\\n+ --hash=sha256:5fee4c04aad8932da9f8f710af2c1a15a83582cfb884152a9caa79d4efcdbf9c \\\n+ --hash=sha256:609e89d9f90b581c8d16358c9087df76024cf058fa693dd3e1e1620823f39670 \\\n+ --hash=sha256:6258f3260986990ba2fa8a874f8b6e808cf5abb51a94015ca3dc3c68aa4f30ea \\\n+ --hash=sha256:64efdf00c09e31efd754448a383ea241f55a994fd079866b92d2bbff598aad91 \\\n+ --hash=sha256:65b80c1ee7e14a87d6a068dd3b0aea268ffcabfe0498d38661b00c5b4b22e74c \\\n+ --hash=sha256:6741e6f3074a35e47c77b23a4e4f2d90db3ed905cb1c5e6e0d49bff2045632bc \\\n+ --hash=sha256:681088909d7e8fa9e31b9799aaa59ba5234c58e5e4f1951b4c4d1082a2e980e0 \\\n+ --hash=sha256:6b7a9d1db5dad90e2991645874f708e87d9a3c370c243c2d7684d28f7e133e6b \\\n+ --hash=sha256:7315f9137087c4e0ee73a761b163fc9aa3b19f5f606a7fc08d83fd3e4379af65 \\\n+ --hash=sha256:742aea052cf5ab5034a53c3846165bc3ce88d7c38e954120db0ab867ca242661 \\\n+ --hash=sha256:75af0b4c229ac519b155028fa1be632d812a519abba9b46b20e50c6caa184f19 \\\n+ --hash=sha256:7b5dd7cbae20285cdb597b10eb5a2c13aa9de6cde9bb64a3c1317427b1db1ae1 \\\n+ --hash=sha256:7d6daa89a00b58c37cb1747ec9fb7ac3bc5ffd5949f5888657dfddde6d1312e0 \\\n+ --hash=sha256:800429ac32c9b72909c671aaf17ecd13110f823ddb7db4dfef412a5587c2c24e \\\n+ --hash=sha256:806f3987ffe10e867bab0ddad45df1148a2b98221798457fa097ad85d6e8bc75 \\\n+ --hash=sha256:808b99604f7873c800c4840f55ff389936ef1948e4e87645eaf3fccbc8477ac4 \\\n+ --hash=sha256:80941e6d573197a0c28f394753de529bb436b1ca990ed6e765cf42426abc39f8 \\\n+ --hash=sha256:84cabc7095dd535ca934d57e9ce2a72ffd216e435a84acb06b2277b1de2689bd \\\n+ --hash=sha256:8637e29d13f478bc4f153d8daa9ffb16455f0a6cb287da1b432fdad2bfbd66c7 \\\n+ --hash=sha256:896866d2d436563fa2a43a9d72f417874f16b5545955c54a64941e87c1376c61 \\\n+ --hash=sha256:8e178e3e99d3c0ea8fc64b88447f7cac8ccf058af422a6cedc690d0eadd98c51 \\\n+ --hash=sha256:907bfa8a9cb790748a9aa4513e37c88c59660da3bcfffbd24a7d9e6abf224551 \\\n+ --hash=sha256:9212d6b86917a2300669511ed094a9406888362e085f2431a7da985a6b124f45 \\\n+ --hash=sha256:92a7fe4225365c5e3a8e598982269c6d6698d3e783b3b1ae979e7819f9cd55c1 \\\n+ --hash=sha256:935b9d1aed48fcfb3f838caac506f38e29621b44ccc4f8a64d575cb1b2a88644 \\\n+ --hash=sha256:97e9993d5ed946aba26baf9c1e8cf18adbab584b99f452ee72f7ee8acb882796 \\\n+ --hash=sha256:983976c2ab753166dc66d36af6e8ec15bb511e4a25856e2227e5f7e00a160587 \\\n+ --hash=sha256:9f5fefaca968e700ad1a4a9de98bf0869a94e397fe3524c4c9450c1445252304 \\\n+ --hash=sha256:a332ac4ccb84b6dde65dbace8431f3af08874bf9770719d32a635c4ef411b18b \\\n+ --hash=sha256:a40905599d8079e09f25027423aed94f2823adaf2868940de991e53a449e14a8 \\\n+ --hash=sha256:a6dfc2af5b082b635af6e08e0d1f9f1c4e04d17d4e2ca0ef96131e85eda6eb17 \\\n+ --hash=sha256:a786bf667724d84aa29b5db1c61b7bfdde380202aaca12c3461afd6b71743171 \\\n+ --hash=sha256:a83e0850cb8f5ac975291ebfc4170ba481f41a28065277f7f735c202cd8e0af3 \\\n+ --hash=sha256:aa0c9cc0b82b14766a99fbe6084409972266e82f459821cd26997a488a7261a7 \\\n+ --hash=sha256:b17fbdbe01c196e7e159aacb889e091f28e61020a8abeac07b68079b6e626988 \\\n+ --hash=sha256:b63e13dd27da389ed9475b3d28510f0f954bca0041e8e551b2a4eb1eab56a39a \\\n+ --hash=sha256:b6e53e82ec2db0717eabb276aa56cf4e500c9a7cec2c2e189b55c24f65a3e8c0 \\\n+ --hash=sha256:bb0984b30e973f7e2884362b7d23d0a348c7143ee559f38ef3eaab640144204c \\\n+ --hash=sha256:bc11908616c8a283cf7d664f77411a5ed2a02009b0097ff8abbba5e79128ccf2 \\\n+ --hash=sha256:bdec5e43377761c5dbca620efb69a77f6855c5a379e32ac5b158f54c84212b14 \\\n+ --hash=sha256:bef9768cab184e7ae6e559c032e95ba8d07b3023c289f79a2bd36e8bf85605a5 \\\n+ --hash=sha256:c990547452ee2800d8506c4150280757f88532f3de2a58e3022e9b179107862a \\\n+ --hash=sha256:ca94b6aac0d7af2a10ba08c0f888b3d5114439b6b3ef39968378723622fed377 \\\n+ --hash=sha256:cad302dc10fac357d3467a74a9561c90609768a6f73a1923b0fd851b6486f8b0 \\\n+ --hash=sha256:d0a7735df32ccbcc98b98a1ac785cc4b19b580be1bdf0aeb5c03223220ea09d5 \\\n+ --hash=sha256:d70347c8a5b7ccd803ec0c85c8709f036e6348f1e6a5bf048ecd9c64d3550b8b \\\n+ --hash=sha256:d70534cea9e7966169ad29a903b99fc507e932069a881d0965a1a84bb57f6c6d \\\n+ --hash=sha256:db44d5c160a90df2d24a24760bbd37607d53da0b34fb546c4c232af7192298ac \\\n+ --hash=sha256:e115c15e3bc727b1ca3e641a909f77f8ca72a64fff150f666fcc85e57701c26c \\\n+ --hash=sha256:e2479c7f02f9d505682dc47df8c0ea1fc5e264c4d1629a5d63fe3e2334b89554 \\\n+ --hash=sha256:e5dcbe95016e88437ecf33544ba5db21ef1b8dd6e1b434a2cb2a3d605299e643 \\\n+ --hash=sha256:e6bdb408f7c9dd2a5ff2b14a3b0bb6d4deb29fb9961e6eb3ae2031ae9a5cec13 \\\n+ --hash=sha256:e75d3dba8fc1ddfec0cd752108f93b83b4f8d6ab40e524a95d35f016b9683b09 \\\n+ --hash=sha256:efdc140e7b63b8f739d09a99033aa430accce485ff78e6d311973a67b6bf3208 \\\n+ --hash=sha256:f10c98f49227ed8383d28174ee95155a675c4ed7f85e2e573b04414f7e371bda \\\n+ --hash=sha256:f188028b5af6b8fb2e9a76ac0f841a575bd1bd396e46ef0840d9b88a48fdbcea \\\n+ --hash=sha256:f188d580bd870cda1e15183790d1cc2fa78f666e76077d103edf048eed9c356e \\\n+ --hash=sha256:f45bd71d1fa5e5749587613037b172e0b3b23159d1c00ef2fc920da6f470e6f0 \\\n+ --hash=sha256:f61333d817698bdcdd0f9d7793e365ac3d2a21c1f1eb02b32ad6aefb8d8ea831 \\\n+ --hash=sha256:fb125d860738a09d363a88daa0f59c4533529a90e564785e20fe875b200b6dbd\n+ # via tensorboard\n portpicker==1.6.0 \\\n --hash=sha256:b2787a41404cf7edbe29b07b9e0ed863b09f2665dcc01c1eb0c2261c1e7d0755 \\\n --hash=sha256:bd507fd6f96f65ee02781f2e674e9dc6c99bbfa6e3c39992e3916204c9d431fa\n- # via -r ci/official/requirements_updater/requirements.in\n+ # via -r ci/official/requirements_updater/numpy1_requirements/requirements.in\n protobuf==6.31.1 \\\n --hash=sha256:0414e3aa5a5f3ff423828e1e6a6e907d6c65c1d5b7e6e975793d5590bdeecc16 \\\n --hash=sha256:426f59d2964864a1a366254fa703b8632dcec0790d8862d30034d8245e1cd447 \\\n@@ -614,8 +707,8 @@ protobuf==6.31.1 \\\n --hash=sha256:a40fc12b84c154884d7d4c4ebd675d5b3b5283e155f324049ae396b95ddebc39 \\\n --hash=sha256:d8cac4c982f0b957a4dc73a80e2ea24fab08e679c0de9deb835f4a12d69aca9a\n # via\n- # -r ci/official/requirements_updater/requirements.in\n- # tb-nightly\n+ # -r ci/official/requirements_updater/numpy1_requirements/requirements.in\n+ # tensorboard\n psutil==7.0.0 \\\n --hash=sha256:101d71dc322e3cffd7cea0650b09b3d08b8e7c4109dd6809fe452dfd00e58b25 \\\n --hash=sha256:1e744154a6580bc968a0195fd25e80432d3afec619daf145b9e5ba16cc1d688e \\\n@@ -639,11 +732,11 @@ pygments==2.19.1 \\\n requests==2.32.4 \\\n --hash=sha256:27babd3cda2a6d50b30443204ee89830707d396671944c998b5975b031ac2b2c \\\n --hash=sha256:27d0316682c8a29834d3264820024b62a36942083d52caf2f14c0591336d3422\n- # via -r ci/official/requirements_updater/requirements.in\n+ # via -r ci/official/requirements_updater/numpy1_requirements/requirements.in\n rich==14.0.0 \\\n --hash=sha256:1c9491e1951aac09caffd42f448ee3d04e58923ffe14993f6e83068dc395d7e0 \\\n --hash=sha256:82f1bc23a6a21ebca4ae0c45af9bdbc492ed20231dcb63f297d6d1021a9d5725\n- # via keras-nightly\n+ # via keras\n scipy==1.14.1 \\\n --hash=sha256:0c2f95de3b04e26f5f3ad5bb05e74ba7f68b837133a4492414b3afd79dfe540e \\\n --hash=sha256:1729560c906963fc8389f6aac023739ff3983e727b1a4d87696b7bf108316a79 \\\n@@ -679,27 +772,26 @@ scipy==1.14.1 \\\n --hash=sha256:edaf02b82cd7639db00dbff629995ef185c8df4c3ffa71a5562a595765a06ce1 \\\n --hash=sha256:fef8c87f8abfb884dac04e97824b61299880c43f4ce675dd2cbeadd3c9b466d2\n # via\n- # -r ci/official/requirements_updater/requirements.in\n+ # -r ci/official/requirements_updater/numpy1_requirements/requirements.in\n # jax\n six==1.17.0 \\\n --hash=sha256:4721f391ed90541fddacab5acf947aa0d3dc7d27b2e1e8eda2be8970586c3274 \\\n --hash=sha256:ff70335d468e7eb6ec65b95b99d3a2836546063f63acc5171de367e834932a81\n # via\n # astunparse\n # google-pasta\n- # tb-nightly\n-tb-nightly==2.20.0a20250424 \\\n- --hash=sha256:62ad3a4ce94cba2bb59538dd481999ede10927304d6f7fa0e9a23df9d24a779e\n- # via -r ci/official/requirements_updater/requirements.in\n tblib==2.0.0 \\\n --hash=sha256:9100bfa016b047d5b980d66e7efed952fbd20bd85b56110aaf473cb97d18709a \\\n --hash=sha256:a6df30f272c08bf8be66e0775fad862005d950a6b8449b94f7c788731d70ecd7\n- # via -r ci/official/requirements_updater/requirements.in\n+ # via -r ci/official/requirements_updater/numpy1_requirements/requirements.in\n+tensorboard==2.20.0 \\\n+ --hash=sha256:9dc9f978cb84c0723acf9a345d96c184f0293d18f166bb8d59ee098e6cfaaba6\n+ # via -r ci/official/requirements_updater/numpy1_requirements/requirements.in\n tensorboard-data-server==0.7.2 \\\n --hash=sha256:7e0610d205889588983836ec05dc098e80f97b7e7bbff7e994ebb78f578d0ddb \\\n --hash=sha256:9fe5d24221b29625dbc7328b0436ca7fc1c23de4acf4d272f1180856e32f9f60 \\\n --hash=sha256:ef687163c24185ae9754ed5650eb5bc4d84ff257aabdc33f0cc6f74d8ba54530\n- # via tb-nightly\n+ # via tensorboard\n tensorflow-io-gcs-filesystem==0.37.1 ; python_version <= \"3.12\" \\\n --hash=sha256:0df00891669390078a003cedbdd3b8e645c718b111917535fa1d7725e95cdb95 \\\n --hash=sha256:249c12b830165841411ba71e08215d0e94277a49c551e6dd5d72aab54fe5491b \\\n@@ -717,16 +809,16 @@ tensorflow-io-gcs-filesystem==0.37.1 ; python_version <= \"3.12\" \\\n --hash=sha256:fbb33f1745f218464a59cecd9a18e32ca927b0f4d77abd8f8671b645cc1a182f \\\n --hash=sha256:fe8dcc6d222258a080ac3dfcaaaa347325ce36a7a046277f6b3e19abc1efb3c5 \\\n --hash=sha256:ffebb6666a7bfc28005f4fbbb111a455b5e7d6cd3b12752b7050863ecb27d5cc\n- # via -r ci/official/requirements_updater/requirements.in\n+ # via -r ci/official/requirements_updater/numpy1_requirements/requirements.in\n termcolor==2.3.0 \\\n --hash=sha256:3afb05607b89aed0ffe25202399ee0867ad4d3cb4180d98aaf8eefa6a5f7d475 \\\n --hash=sha256:b5b08f68937f138fe92f6c089b99f1e2da0ae56c52b78bf7075fd95420fd9a5a\n- # via -r ci/official/requirements_updater/requirements.in\n+ # via -r ci/official/requirements_updater/numpy1_requirements/requirements.in\n typing-extensions==4.14.1 \\\n --hash=sha256:38b39f4aeeab64884ce9f74c94263ef78f3c22467c8724005483154c26648d36 \\\n --hash=sha256:d1e1e3b58374dc93031d6eda2420a48ea44a36c2b4766a4fdeb3710755731d76\n # via\n- # -r ci/official/requirements_updater/requirements.in\n+ # -r ci/official/requirements_updater/numpy1_requirements/requirements.in\n # optree\n # rich\n urllib3==2.6.3 \\\n@@ -736,12 +828,12 @@ urllib3==2.6.3 \\\n werkzeug==3.1.5 \\\n --hash=sha256:5111e36e91086ece91f93268bb39b4a35c1e6f1feac762c9c822ded0a4e322dc \\\n --hash=sha256:6a548b0e88955dd07ccb25539d7d0cc97417ee9e179677d22c7041c8f078ce67\n- # via tb-nightly\n+ # via tensorboard\n wheel==0.41.3 \\\n --hash=sha256:488609bc63a29322326e05560731bf7bfea8e48ad646e1f5e40d366607de0942 \\\n --hash=sha256:4d4987ce51a49370ea65c0bfd2234e8ce80a12780820d9dc462597a6e60d0841\n # via\n- # -r ci/official/requirements_updater/requirements.in\n+ # -r ci/official/requirements_updater/numpy1_requirements/requirements.in\n # astunparse\n wrapt==1.16.0 \\\n --hash=sha256:0d2691979e93d06a95a26257adb7bfd0c93818e89b1406f5a28f36e0d8c1e1fc \\\n@@ -814,7 +906,7 @@ wrapt==1.16.0 \\\n --hash=sha256:f6b2d0c6703c988d334f297aa5df18c45e97b0af3679bb75059e0e0bd8b1069d \\\n --hash=sha256:f8212564d49c50eb4565e502814f694e240c55551a5f1bc841d4fcaabb0a9b8a \\\n --hash=sha256:ffa565331890b90056c01db69c0fe634a776f8019c143a5ae265f9c6bc4bd6d4\n- # via -r ci/official/requirements_updater/requirements.in\n+ # via -r ci/official/requirements_updater/numpy1_requirements/requirements.in\n zstandard==0.23.0 \\\n --hash=sha256:034b88913ecc1b097f528e42b539453fa82c3557e414b3de9d5632c80439a473 \\\n --hash=sha256:0a7f0804bb3799414af278e9ad51be25edf67f78f916e08afdb983e74161b916 \\\n@@ -913,12 +1005,12 @@ zstandard==0.23.0 \\\n --hash=sha256:fd30d9c67d13d891f2360b2a120186729c111238ac63b43dbd37a5a40670b8ca \\\n --hash=sha256:fd7699e8fd9969f455ef2926221e0233f81a2542921471382e77a9e2f2b57f4b \\\n --hash=sha256:fe3b385d996ee0822fd46528d9f0443b880d4d05528fd26a9119a54ec3f91c69\n- # via -r ci/official/requirements_updater/requirements.in\n+ # via -r ci/official/requirements_updater/numpy1_requirements/requirements.in\n \n # The following packages are considered to be unsafe in a requirements file:\n setuptools==78.1.1 \\\n --hash=sha256:c3a9c4211ff4c309edb8b8c4f1cbfa7ae324c4ba9f91ff254e3d305b9fd54561 \\\n --hash=sha256:fcc17fd9cd898242f6b4adfaca46137a9edef687f43e6f78469692a5e70d851d\n # via\n- # -r ci/official/requirements_updater/requirements.in\n- # tb-nightly\n+ # -r ci/official/requirements_updater/numpy1_requirements/requirements.in\n+ # tensorboard" }, { "filename": "ci/official/requirements_updater/numpy1_requirements/requirements_lock_3_11.txt", "status": "modified", "additions": 146, "deletions": 54, "changes": 200, "patch": "@@ -2,26 +2,26 @@\n # This file is autogenerated by [NAME_REDACTED] 3.11\n # by [NAME_REDACTED]:\n #\n-# bazel run //ci/official/requirements_updater:requirements.update\n+# bazel run //ci/official/requirements_updater/numpy1_requirements:requirements_311.update\n #\n absl-py==2.2.2 \\\n --hash=sha256:bf25b2c2eed013ca456918c453d687eab4e8309fba81ee2f4c1a6aa2494175eb \\\n --hash=sha256:e5797bc6abe45f64fd95dc06394ca3f2bedf3b5d895e9da691c9ee3397d70092\n # via\n- # keras-nightly\n- # tb-nightly\n+ # keras\n+ # tensorboard\n astor==0.7.1 \\\n --hash=sha256:95c30d87a6c2cf89aa628b87398466840f0ad8652f88eb173125a6df8533fb8d \\\n --hash=sha256:fb503b9e2fdd05609fbf557b916b4a7824171203701660f0c55bbf5a7a68713e\n- # via -r ci/official/requirements_updater/requirements.in\n+ # via -r ci/official/requirements_updater/numpy1_requirements/requirements.in\n astunparse==1.6.3 \\\n --hash=sha256:5ad93a8456f0d084c3456d059fd9a92cce667963232cbf763eac3bc5b7940872 \\\n --hash=sha256:c2652417f2c8b5bb325c885ae329bdf3f86424075c4fd1a128674bc6fba4b8e8\n- # via -r ci/official/requirements_updater/requirements.in\n+ # via -r ci/official/requirements_updater/numpy1_requirements/requirements.in\n auditwheel==6.3.0 \\\n --hash=sha256:05c70a234fa14c140aa6d9076135d9550962d95849911b8d5d0419a3add09f00 \\\n --hash=sha256:31cbd8045d4ff6776f79bef328b5fd563e5ecc8ae82ea34b6fe5e76efe2a84eb\n- # via -r ci/official/requirements_updater/requirements.in\n+ # via -r ci/official/requirements_updater/numpy1_requirements/requirements.in\n certifi==2025.1.31 \\\n --hash=sha256:3d5da6925056f6f18f119200434a4780a94263f10d1c21d032a6f6b2baa20651 \\\n --hash=sha256:ca78db4565a652026a4db2bcdf68f2fb589ea80d0be70e03929ed730746b84fe\n@@ -123,20 +123,20 @@ charset-normalizer==3.4.1 \\\n dill==0.3.7 \\\n --hash=sha256:76b122c08ef4ce2eedcd4d1abd8e641114bfc6c2867f49f3c41facf65bf19f5e \\\n --hash=sha256:cc1c8b182eb3013e24bd475ff2e9295af86c1a38eb1aff128dac8962a9ce3c03\n- # via -r ci/official/requirements_updater/requirements.in\n+ # via -r ci/official/requirements_updater/numpy1_requirements/requirements.in\n flatbuffers==25.9.23 \\\n --hash=sha256:255538574d6cb6d0a79a17ec8bc0d30985913b87513a01cce8bcdb6b4c44d0e2 \\\n --hash=sha256:676f9fa62750bb50cf531b42a0a2a118ad8f7f797a511eda12881c016f093b12\n- # via -r ci/official/requirements_updater/requirements.in\n+ # via -r ci/official/requirements_updater/numpy1_requirements/requirements.in\n gast==0.4.0 \\\n --hash=sha256:40feb7b8b8434785585ab224d1568b857edb18297e5a3047f1ba012bc83b42c1 \\\n --hash=sha256:b7adcdd5adbebf1adf17378da5ba3f543684dbec47b1cda1f3997e573cd542c4\n- # via -r ci/official/requirements_updater/requirements.in\n+ # via -r ci/official/requirements_updater/numpy1_requirements/requirements.in\n google-pasta==0.2.0 \\\n --hash=sha256:4612951da876b1a10fe3960d7226f0c7682cf901e16ac06e473b267a5afa8954 \\\n --hash=sha256:b32482794a366b5366a32c92a9a9201b107821889935a02b3e51f6b432ea84ed \\\n --hash=sha256:c9f2c8dfc8f96d0d5808299920721be30c9eec37f2389f28904f454565c8a16e\n- # via -r ci/official/requirements_updater/requirements.in\n+ # via -r ci/official/requirements_updater/numpy1_requirements/requirements.in\n grpcio==1.71.0 \\\n --hash=sha256:0ab8b2864396663a5b0b0d6d79495657ae85fa37dcb6498a2669d067c65c11ea \\\n --hash=sha256:0fa05ee31a20456b13ae49ad2e5d585265f71dd19fbd9ef983c28f926d45d0a7 \\\n@@ -190,8 +190,8 @@ grpcio==1.71.0 \\\n --hash=sha256:f9a412f55bb6e8f3bb000e020dbc1e709627dcb3a56f6431fa7076b4c1aab0db \\\n --hash=sha256:f9c30c464cb2ddfbc2ddf9400287701270fdc0f14be5f08a1e3939f1e749b455\n # via\n- # -r ci/official/requirements_updater/requirements.in\n- # tb-nightly\n+ # -r ci/official/requirements_updater/numpy1_requirements/requirements.in\n+ # tensorboard\n h5py==3.13.0 \\\n --hash=sha256:10894c55d46df502d82a7a4ed38f9c3fdbcb93efb42e25d275193e093071fade \\\n --hash=sha256:1870e46518720023da85d0895a1960ff2ce398c5671eac3b1a41ec696b7105c3 \\\n@@ -220,19 +220,19 @@ h5py==3.13.0 \\\n --hash=sha256:f35640e81b03c02a88b8bf99fb6a9d3023cc52f7c627694db2f379e0028f2868 \\\n --hash=sha256:fb267ce4b83f9c42560e9ff4d30f60f7ae492eacf9c7ede849edf8c1b860e16b\n # via\n- # -r ci/official/requirements_updater/requirements.in\n- # keras-nightly\n+ # -r ci/official/requirements_updater/numpy1_requirements/requirements.in\n+ # keras\n idna==3.10 \\\n --hash=sha256:12f65c9b470abda6dc35cf8e63cc574b1c52b11df2c86030af0ac09b01b13ea9 \\\n --hash=sha256:946d195a0d259cbba61165e88e65941f16e9b36ea6ddb97f00452bae8b1287d3\n # via requests\n jax==0.4.7 \\\n --hash=sha256:5e7002d74db25f97c99b979d4ba1233b1ef26e1597e5fc468ad11d1c8a9dc4f8\n- # via -r ci/official/requirements_updater/requirements.in\n-keras-nightly==3.12.0.dev2025100703 \\\n- --hash=sha256:6b9dfb3814d707abf5555f56268f072daec13f2540da3aeeb7531a819ebb4567 \\\n- --hash=sha256:e29434e49bac3360f86af6e1548d94b0a2fda4e793685bc43b49867132ab16e5\n- # via -r ci/official/requirements_updater/requirements.in\n+ # via -r ci/official/requirements_updater/numpy1_requirements/requirements.in\n+keras==3.12.1 \\\n+ --hash=sha256:3cb760b3fec105db4d893dd717daafdd0e35457a8201502c1ba8bedfaf334a71 \\\n+ --hash=sha256:c340f8a25362398b20500c64e290f6ee280c6aeec51e1044eb8d759b32dc272a\n+ # via -r ci/official/requirements_updater/numpy1_requirements/requirements.in\n libclang==18.1.1 \\\n --hash=sha256:0b2e143f0fac830156feb56f9231ff8338c20aecfe72b4ffe96f19e5a1dbb69a \\\n --hash=sha256:3f0e1f49f04d3cd198985fea0511576b0aee16f9ff0e0f0cad7f9c57ec3c20e8 \\\n@@ -244,14 +244,14 @@ libclang==18.1.1 \\\n --hash=sha256:a1214966d08d73d971287fc3ead8dfaf82eb07fb197680d8b3859dbbbbf78250 \\\n --hash=sha256:c533091d8a3bbf7460a00cb6c1a71da93bffe148f172c7d03b1c31fbf8aa2a0b \\\n --hash=sha256:cf4a99b05376513717ab5d82a0db832c56ccea4fd61a69dbb7bccf2dfb207dbe\n- # via -r ci/official/requirements_updater/requirements.in\n+ # via -r ci/official/requirements_updater/numpy1_requirements/requirements.in\n lit==17.0.6 \\\n --hash=sha256:dfa9af9b55fc4509a56be7bf2346f079d7f4a242d583b9f2e0b078fd0abae31b\n- # via -r ci/official/requirements_updater/requirements.in\n+ # via -r ci/official/requirements_updater/numpy1_requirements/requirements.in\n markdown==3.8 \\\n --hash=sha256:794a929b79c5af141ef5ab0f2f642d0f7b1872981250230e72682346f7cc90dc \\\n --hash=sha256:7df81e63f0df5c4b24b7d156eb81e4690595239b7d70937d0409f1b0de319c6f\n- # via tb-nightly\n+ # via tensorboard\n markdown-it-py==3.0.0 \\\n --hash=sha256:355216845c60bd96232cd8d8c40e8f9765cc86f46880e43a8fd22dc1a1a8cab1 \\\n --hash=sha256:e3f60a94fa066dc52ec76661e37c851cb232d92f9886b15cb560aaada2df8feb\n@@ -349,13 +349,13 @@ ml-dtypes==0.5.1 \\\n --hash=sha256:d13755f8e8445b3870114e5b6240facaa7cb0c3361e54beba3e07fa912a6e12b \\\n --hash=sha256:fd918d4e6a4e0c110e2e05be7a7814d10dc1b95872accbf6512b80a109b71ae1\n # via\n- # -r ci/official/requirements_updater/requirements.in\n+ # -r ci/official/requirements_updater/numpy1_requirements/requirements.in\n # jax\n- # keras-nightly\n+ # keras\n namex==0.0.8 \\\n --hash=sha256:32a50f6c565c0bb10aa76298c959507abdc0e850efe085dc38f3440fcb3aa90b \\\n --hash=sha256:7ddb6c2bb0e753a311b7590f84f6da659dd0c05e65cb89d519d54c0a250c0487\n- # via keras-nightly\n+ # via keras\n numpy==1.26.4 \\\n --hash=sha256:03a8c78d01d9781b28a6989f6fa1bb2c4f2d51201cf99d3dd875df6fbd96b23b \\\n --hash=sha256:08beddf13648eb95f8d867350f6a018a4be2e5ad54c8d8caed89ebca558b2818 \\\n@@ -394,14 +394,14 @@ numpy==1.26.4 \\\n --hash=sha256:f870204a840a60da0b12273ef34f7051e98c3b5961b61b0c2c1be6dfd64fbcd3 \\\n --hash=sha256:ffa75af20b44f8dba823498024771d5ac50620e6915abac414251bd971b4529f\n # via\n- # -r ci/official/requirements_updater/requirements.in\n+ # -r ci/official/requirements_updater/numpy1_requirements/requirements.in\n # h5py\n # jax\n- # keras-nightly\n+ # keras\n # ml-dtypes\n # opt-einsum\n # scipy\n- # tb-nightly\n+ # tensorboard\n nvidia-cublas-cu12==12.5.3.2 \\\n --hash=sha256:4960f3dc5f39699acadf76fa6d94b10a2a00f2956c2c442efa299fb22b0748f3 \\\n --hash=sha256:7d0191251180de606023d396b94d66f66470a0ae96d1dbb906c7656ea0f71eda \\\n@@ -514,7 +514,7 @@ opt-einsum==3.3.0 \\\n --hash=sha256:2455e59e3947d3c275477df7f5205b30635e266fe6dc300e3d9f9646bfcea147 \\\n --hash=sha256:59f6475f77bbc37dcf7cd748519c0ec60722e91e63ca114e68821c0c54a46549\n # via\n- # -r ci/official/requirements_updater/requirements.in\n+ # -r ci/official/requirements_updater/numpy1_requirements/requirements.in\n # jax\n optree==0.16.0 \\\n --hash=sha256:0dd607bfbf59ecf92b069af18e8a41b0d8628e21f2de5a738fad039d0a89d9d4 \\\n@@ -590,19 +590,112 @@ optree==0.16.0 \\\n --hash=sha256:eeccc740b72b58efa9795ab831a678a42341def48b9e5956c6b1e588c6fa3ddf \\\n --hash=sha256:f08aaa1c2ae092b3e662125ad19860046c63d7451d41be133ddd6594920e295e \\\n --hash=sha256:f703d7926c36eebdd56fc08aabefcf32a8b7292a9dd4468e56b0ab61bf6214bd\n- # via keras-nightly\n+ # via keras\n packaging==23.2 \\\n --hash=sha256:048fb0e9405036518eaaf48a55953c750c11e1a1b68e0dd1a9d62ed0c092cfc5 \\\n --hash=sha256:8c491190033a9af7e1d931d0b5dacc2ef47509b34dd0de67ed209b5203fc88c7\n # via\n- # -r ci/official/requirements_updater/requirements.in\n+ # -r ci/official/requirements_updater/numpy1_requirements/requirements.in\n # auditwheel\n- # keras-nightly\n- # tb-nightly\n+ # keras\n+ # tensorboard\n+pillow==12.1.0 \\\n+ --hash=sha256:00162e9ca6d22b7c3ee8e61faa3c3253cd19b6a37f126cad04f2f88b306f557d \\\n+ --hash=sha256:079af2fb0c599c2ec144ba2c02766d1b55498e373b3ac64687e43849fbbef5bc \\\n+ --hash=sha256:0b022eaaf709541b391ee069f0022ee5b36c709df71986e3f7be312e46f42c84 \\\n+ --hash=sha256:0c27407a2d1b96774cbc4a7594129cc027339fd800cd081e44497722ea1179de \\\n+ --hash=sha256:0ddedfaa8b5f0b4ffbc2fa87b556dc59f6bb4ecb14a53b33f9189713ae8053c0 \\\n+ --hash=sha256:0deedf2ea233722476b3a81e8cdfbad786f7adbed5d848469fa59fe52396e4ef \\\n+ --hash=sha256:0ed07dca4a8464bada6139ab38f5382f83e5f111698caf3191cb8dbf27d908b4 \\\n+ --hash=sha256:0fde7ec5538ab5095cc02df38ee99b0443ff0e1c847a045554cf5f9af1f4aa82 \\\n+ --hash=sha256:15c794d74303828eaa957ff8070846d0efe8c630901a1c753fdc63850e19ecd9 \\\n+ --hash=sha256:1a949604f73eb07a8adab38c4fe50791f9919344398bdc8ac6b307f755fc7030 \\\n+ --hash=sha256:1f345e7bc9d7f368887c712aa5054558bad44d2a301ddf9248599f4161abc7c0 \\\n+ --hash=sha256:1fcc52d86ce7a34fd17cb04e87cfdb164648a3662a6f20565910a99653d66c18 \\\n+ --hash=sha256:21e686a21078b0f9cb8c8a961d99e6a4ddb88e0fc5ea6e130172ddddc2e5221a \\\n+ --hash=sha256:2415373395a831f53933c23ce051021e79c8cd7979822d8cc478547a3f4da8ef \\\n+ --hash=sha256:277518bf4fe74aa91489e1b20577473b19ee70fb97c374aa50830b279f25841b \\\n+ --hash=sha256:27b9baecb428899db6c0de572d6d305cfaf38ca1596b5c0542a5182e3e74e8c6 \\\n+ --hash=sha256:29a4cef9cb672363926f0470afc516dbf7305a14d8c54f7abbb5c199cd8f8179 \\\n+ --hash=sha256:3413c2ae377550f5487991d444428f1a8ae92784aac79caa8b1e3b89b175f77e \\\n+ --hash=sha256:351889afef0f485b84078ea40fe33727a0492b9af3904661b0abbafee0355b72 \\\n+ --hash=sha256:3ffaa2f0659e2f740473bcf03c702c39a8d4b2b7ffc629052028764324842c64 \\\n+ --hash=sha256:40a8e3b9e8773876d6e30daed22f016509e3987bab61b3b7fe309d7019a87451 \\\n+ --hash=sha256:414b9a78e14ffeb98128863314e62c3f24b8a86081066625700b7985b3f529bd \\\n+ --hash=sha256:43aca0a55ce1eefc0aefa6253661cb54571857b1a7b2964bd8a1e3ef4b729924 \\\n+ --hash=sha256:43b4899cfd091a9693a1278c4982f3e50f7fb7cff5153b05174b4afc9593b616 \\\n+ --hash=sha256:461f9dfdafa394c59cd6d818bdfdbab4028b83b02caadaff0ffd433faf4c9a7a \\\n+ --hash=sha256:4f9f6a650743f0ddee5593ac9e954ba1bdbc5e150bc066586d4f26127853ab94 \\\n+ --hash=sha256:53d8b764726d3af1a138dd353116f774e3862ec7e3794e0c8781e30db0f35dfc \\\n+ --hash=sha256:565c986f4b45c020f5421a4cea13ef294dde9509a8577f29b2fc5edc7587fff8 \\\n+ --hash=sha256:5c5ae0a06e9ea030ab786b0251b32c7e4ce10e58d983c0d5c56029455180b5b9 \\\n+ --hash=sha256:5cb7bc1966d031aec37ddb9dcf15c2da5b2e9f7cc3ca7c54473a20a927e1eb91 \\\n+ --hash=sha256:5da841d81b1a05ef940a8567da92decaa15bc4d7dedb540a8c219ad83d91808a \\\n+ --hash=sha256:5fee4c04aad8932da9f8f710af2c1a15a83582cfb884152a9caa79d4efcdbf9c \\\n+ --hash=sha256:609e89d9f90b581c8d16358c9087df76024cf058fa693dd3e1e1620823f39670 \\\n+ --hash=sha256:6258f3260986990ba2fa8a874f8b6e808cf5abb51a94015ca3dc3c68aa4f30ea \\\n+ --hash=sha256:64efdf00c09e31efd754448a383ea241f55a994fd079866b92d2bbff598aad91 \\\n+ --hash=sha256:65b80c1ee7e14a87d6a068dd3b0aea268ffcabfe0498d38661b00c5b4b22e74c \\\n+ --hash=sha256:6741e6f3074a35e47c77b23a4e4f2d90db3ed905cb1c5e6e0d49bff2045632bc \\\n+ --hash=sha256:681088909d7e8fa9e31b9799aaa59ba5234c58e5e4f1951b4c4d1082a2e980e0 \\\n+ --hash=sha256:6b7a9d1db5dad90e2991645874f708e87d9a3c370c243c2d7684d28f7e133e6b \\\n+ --hash=sha256:7315f9137087c4e0ee73a761b163fc9aa3b19f5f606a7fc08d83fd3e4379af65 \\\n+ --hash=sha256:742aea052cf5ab5034a53c3846165bc3ce88d7c38e954120db0ab867ca242661 \\\n+ --hash=sha256:75af0b4c229ac519b155028fa1be632d812a519abba9b46b20e50c6caa184f19 \\\n+ --hash=sha256:7b5dd7cbae20285cdb597b10eb5a2c13aa9de6cde9bb64a3c1317427b1db1ae1 \\\n+ --hash=sha256:7d6daa89a00b58c37cb1747ec9fb7ac3bc5ffd5949f5888657dfddde6d1312e0 \\\n+ --hash=sha256:800429ac32c9b72909c671aaf17ecd13110f823ddb7db4dfef412a5587c2c24e \\\n+ --hash=sha256:806f3987ffe10e867bab0ddad45df1148a2b98221798457fa097ad85d6e8bc75 \\\n+ --hash=sha256:808b99604f7873c800c4840f55ff389936ef1948e4e87645eaf3fccbc8477ac4 \\\n+ --hash=sha256:80941e6d573197a0c28f394753de529bb436b1ca990ed6e765cf42426abc39f8 \\\n+ --hash=sha256:84cabc7095dd535ca934d57e9ce2a72ffd216e435a84acb06b2277b1de2689bd \\\n+ --hash=sha256:8637e29d13f478bc4f153d8daa9ffb16455f0a6cb287da1b432fdad2bfbd66c7 \\\n+ --hash=sha256:896866d2d436563fa2a43a9d72f417874f16b5545955c54a64941e87c1376c61 \\\n+ --hash=sha256:8e178e3e99d3c0ea8fc64b88447f7cac8ccf058af422a6cedc690d0eadd98c51 \\\n+ --hash=sha256:907bfa8a9cb790748a9aa4513e37c88c59660da3bcfffbd24a7d9e6abf224551 \\\n+ --hash=sha256:9212d6b86917a2300669511ed094a9406888362e085f2431a7da985a6b124f45 \\\n+ --hash=sha256:92a7fe4225365c5e3a8e598982269c6d6698d3e783b3b1ae979e7819f9cd55c1 \\\n+ --hash=sha256:935b9d1aed48fcfb3f838caac506f38e29621b44ccc4f8a64d575cb1b2a88644 \\\n+ --hash=sha256:97e9993d5ed946aba26baf9c1e8cf18adbab584b99f452ee72f7ee8acb882796 \\\n+ --hash=sha256:983976c2ab753166dc66d36af6e8ec15bb511e4a25856e2227e5f7e00a160587 \\\n+ --hash=sha256:9f5fefaca968e700ad1a4a9de98bf0869a94e397fe3524c4c9450c1445252304 \\\n+ --hash=sha256:a332ac4ccb84b6dde65dbace8431f3af08874bf9770719d32a635c4ef411b18b \\\n+ --hash=sha256:a40905599d8079e09f25027423aed94f2823adaf2868940de991e53a449e14a8 \\\n+ --hash=sha256:a6dfc2af5b082b635af6e08e0d1f9f1c4e04d17d4e2ca0ef96131e85eda6eb17 \\\n+ --hash=sha256:a786bf667724d84aa29b5db1c61b7bfdde380202aaca12c3461afd6b71743171 \\\n+ --hash=sha256:a83e0850cb8f5ac975291ebfc4170ba481f41a28065277f7f735c202cd8e0af3 \\\n+ --hash=sha256:aa0c9cc0b82b14766a99fbe6084409972266e82f459821cd26997a488a7261a7 \\\n+ --hash=sha256:b17fbdbe01c196e7e159aacb889e091f28e61020a8abeac07b68079b6e626988 \\\n+ --hash=sha256:b63e13dd27da389ed9475b3d28510f0f954bca0041e8e551b2a4eb1eab56a39a \\\n+ --hash=sha256:b6e53e82ec2db0717eabb276aa56cf4e500c9a7cec2c2e189b55c24f65a3e8c0 \\\n+ --hash=sha256:bb0984b30e973f7e2884362b7d23d0a348c7143ee559f38ef3eaab640144204c \\\n+ --hash=sha256:bc11908616c8a283cf7d664f77411a5ed2a02009b0097ff8abbba5e79128ccf2 \\\n+ --hash=sha256:bdec5e43377761c5dbca620efb69a77f6855c5a379e32ac5b158f54c84212b14 \\\n+ --hash=sha256:bef9768cab184e7ae6e559c032e95ba8d07b3023c289f79a2bd36e8bf85605a5 \\\n+ --hash=sha256:c990547452ee2800d8506c4150280757f88532f3de2a58e3022e9b179107862a \\\n+ --hash=sha256:ca94b6aac0d7af2a10ba08c0f888b3d5114439b6b3ef39968378723622fed377 \\\n+ --hash=sha256:cad302dc10fac357d3467a74a9561c90609768a6f73a1923b0fd851b6486f8b0 \\\n+ --hash=sha256:d0a7735df32ccbcc98b98a1ac785cc4b19b580be1bdf0aeb5c03223220ea09d5 \\\n+ --hash=sha256:d70347c8a5b7ccd803ec0c85c8709f036e6348f1e6a5bf048ecd9c64d3550b8b \\\n+ --hash=sha256:d70534cea9e7966169ad29a903b99fc507e932069a881d0965a1a84bb57f6c6d \\\n+ --hash=sha256:db44d5c160a90df2d24a24760bbd37607d53da0b34fb546c4c232af7192298ac \\\n+ --hash=sha256:e115c15e3bc727b1ca3e641a909f77f8ca72a64fff150f666fcc85e57701c26c \\\n+ --hash=sha256:e2479c7f02f9d505682dc47df8c0ea1fc5e264c4d1629a5d63fe3e2334b89554 \\\n+ --hash=sha256:e5dcbe95016e88437ecf33544ba5db21ef1b8dd6e1b434a2cb2a3d605299e643 \\\n+ --hash=sha256:e6bdb408f7c9dd2a5ff2b14a3b0bb6d4deb29fb9961e6eb3ae2031ae9a5cec13 \\\n+ --hash=sha256:e75d3dba8fc1ddfec0cd752108f93b83b4f8d6ab40e524a95d35f016b9683b09 \\\n+ --hash=sha256:efdc140e7b63b8f739d09a99033aa430accce485ff78e6d311973a67b6bf3208 \\\n+ --hash=sha256:f10c98f49227ed8383d28174ee95155a675c4ed7f85e2e573b04414f7e371bda \\\n+ --hash=sha256:f188028b5af6b8fb2e9a76ac0f841a575bd1bd396e46ef0840d9b88a48fdbcea \\\n+ --hash=sha256:f188d580bd870cda1e15183790d1cc2fa78f666e76077d103edf048eed9c356e \\\n+ --hash=sha256:f45bd71d1fa5e5749587613037b172e0b3b23159d1c00ef2fc920da6f470e6f0 \\\n+ --hash=sha256:f61333d817698bdcdd0f9d7793e365ac3d2a21c1f1eb02b32ad6aefb8d8ea831 \\\n+ --hash=sha256:fb125d860738a09d363a88daa0f59c4533529a90e564785e20fe875b200b6dbd\n+ # via tensorboard\n portpicker==1.6.0 \\\n --hash=sha256:b2787a41404cf7edbe29b07b9e0ed863b09f2665dcc01c1eb0c2261c1e7d0755 \\\n --hash=sha256:bd507fd6f96f65ee02781f2e674e9dc6c99bbfa6e3c39992e3916204c9d431fa\n- # via -r ci/official/requirements_updater/requirements.in\n+ # via -r ci/official/requirements_updater/numpy1_requirements/requirements.in\n protobuf==6.31.1 \\\n --hash=sha256:0414e3aa5a5f3ff423828e1e6a6e907d6c65c1d5b7e6e975793d5590bdeecc16 \\\n --hash=sha256:426f59d2964864a1a366254fa703b8632dcec0790d8862d30034d8245e1cd447 \\\n@@ -614,8 +707,8 @@ protobuf==6.31.1 \\\n --hash=sha256:a40fc12b84c154884d7d4c4ebd675d5b3b5283e155f324049ae396b95ddebc39 \\\n --hash=sha256:d8cac4c982f0b957a4dc73a80e2ea24fab08e679c0de9deb835f4a12d69aca9a\n # via\n- # -r ci/official/requirements_updater/requirements.in\n- # tb-nightly\n+ # -r ci/official/requirements_updater/numpy1_requirements/requirements.in\n+ # tensorboard\n psutil==7.0.0 \\\n --hash=sha256:101d71dc322e3cffd7cea0650b09b3d08b8e7c4109dd6809fe452dfd00e58b25 \\\n --hash=sha256:1e744154a6580bc968a0195fd25e80432d3afec619daf145b9e5ba16cc1d688e \\\n@@ -639,11 +732,11 @@ pygments==2.19.1 \\\n requests==2.32.4 \\\n --hash=sha256:27babd3cda2a6d50b30443204ee89830707d396671944c998b5975b031ac2b2c \\\n --hash=sha256:27d0316682c8a29834d3264820024b62a36942083d52caf2f14c0591336d3422\n- # via -r ci/official/requirements_updater/requirements.in\n+ # via -r ci/official/requirements_updater/numpy1_requirements/requirements.in\n rich==14.0.0 \\\n --hash=sha256:1c9491e1951aac09caffd42f448ee3d04e58923ffe14993f6e83068dc395d7e0 \\\n --hash=sha256:82f1bc23a6a21ebca4ae0c45af9bdbc492ed20231dcb63f297d6d1021a9d5725\n- # via keras-nightly\n+ # via keras\n scipy==1.14.1 \\\n --hash=sha256:0c2f95de3b04e26f5f3ad5bb05e74ba7f68b837133a4492414b3afd79dfe540e \\\n --hash=sha256:1729560c906963fc8389f6aac023739ff3983e727b1a4d87696b7bf108316a79 \\\n@@ -679,27 +772,26 @@ scipy==1.14.1 \\\n --hash=sha256:edaf02b82cd7639db00dbff629995ef185c8df4c3ffa71a5562a595765a06ce1 \\\n --hash=sha256:fef8c87f8abfb884dac04e97824b61299880c43f4ce675dd2cbeadd3c9b466d2\n # via\n- # -r ci/official/requirements_updater/requirements.in\n+ # -r ci/official/requirements_updater/numpy1_requirements/requirements.in\n # jax\n six==1.17.0 \\\n --hash=sha256:4721f391ed90541fddacab5acf947aa0d3dc7d27b2e1e8eda2be8970586c3274 \\\n --hash=sha256:ff70335d468e7eb6ec65b95b99d3a2836546063f63acc5171de367e834932a81\n # via\n # astunparse\n # google-pasta\n- # tb-nightly\n-tb-nightly==2.20.0a20250419 \\\n- --hash=sha256:41ba72431b88a87ed07e284cb244c29cd5dc42b1dd5970436f4e1bec9684e0f0\n- # via -r ci/official/requirements_updater/requirements.in\n tblib==2.0.0 \\\n --hash=sha256:9100bfa016b047d5b980d66e7efed952fbd20bd85b56110aaf473cb97d18709a \\\n --hash=sha256:a6df30f272c08bf8be66e0775fad862005d950a6b8449b94f7c788731d70ecd7\n- # via -r ci/official/requirements_updater/requirements.in\n+ # via -r ci/official/requirements_updater/numpy1_requirements/requirements.in\n+tensorboard==2.20.0 \\\n+ --hash=sha256:9dc9f978cb84c0723acf9a345d96c184f0293d18f166bb8d59ee098e6cfaaba6\n+ # via -r ci/official/requirements_updater/numpy1_requirements/requirements.in\n tensorboard-data-server==0.7.2 \\\n --hash=sha256:7e0610d205889588983836ec05dc098e80f97b7e7bbff7e994ebb78f578d0ddb \\\n --hash=sha256:9fe5d24221b29625dbc7328b0436ca7fc1c23de4acf4d272f1180856e32f9f60 \\\n --hash=sha256:ef687163c24185ae9754ed5650eb5bc4d84ff257aabdc33f0cc6f74d8ba54530\n- # via tb-nightly\n+ # via tensorboard\n tensorflow-io-gcs-filesystem==0.37.1 ; python_version <= \"3.12\" \\\n --hash=sha256:0df00891669390078a003cedbdd3b8e645c718b111917535fa1d7725e95cdb95 \\\n --hash=sha256:249c12b830165841411ba71e08215d0e94277a49c551e6dd5d72aab54fe5491b \\\n@@ -717,16 +809,16 @@ tensorflow-io-gcs-filesystem==0.37.1 ; python_version <= \"3.12\" \\\n --hash=sha256:fbb33f1745f218464a59cecd9a18e32ca927b0f4d77abd8f8671b645cc1a182f \\\n --hash=sha256:fe8dcc6d222258a080ac3dfcaaaa347325ce36a7a046277f6b3e19abc1efb3c5 \\\n --hash=sha256:ffebb6666a7bfc28005f4fbbb111a455b5e7d6cd3b12752b7050863ecb27d5cc\n- # via -r ci/official/requirements_updater/requirements.in\n+ # via -r ci/official/requirements_updater/numpy1_requirements/requirements.in\n termcolor==2.3.0 \\\n --hash=sha256:3afb05607b89aed0ffe25202399ee0867ad4d3cb4180d98aaf8eefa6a5f7d475 \\\n --hash=sha256:b5b08f68937f138fe92f6c089b99f1e2da0ae56c52b78bf7075fd95420fd9a5a\n- # via -r ci/official/requirements_updater/requirements.in\n+ # via -r ci/official/requirements_updater/numpy1_requirements/requirements.in\n typing-extensions==4.14.1 \\\n --hash=sha256:38b39f4aeeab64884ce9f74c94263ef78f3c22467c8724005483154c26648d36 \\\n --hash=sha256:d1e1e3b58374dc93031d6eda2420a48ea44a36c2b4766a4fdeb3710755731d76\n # via\n- # -r ci/official/requirements_updater/requirements.in\n+ # -r ci/official/requirements_updater/numpy1_requirements/requirements.in\n # optree\n urllib3==2.6.3 \\\n --hash=sha256:1b62b6884944a57dbe321509ab94fd4d3b307075e0c2eae991ac71ee15ad38ed \\\n@@ -735,12 +827,12 @@ urllib3==2.6.3 \\\n werkzeug==3.1.5 \\\n --hash=sha256:5111e36e91086ece91f93268bb39b4a35c1e6f1feac762c9c822ded0a4e322dc \\\n --hash=sha256:6a548b0e88955dd07ccb25539d7d0cc97417ee9e179677d22c7041c8f078ce67\n- # via tb-nightly\n+ # via tensorboard\n wheel==0.41.3 \\\n --hash=sha256:488609bc63a29322326e05560731bf7bfea8e48ad646e1f5e40d366607de0942 \\\n --hash=sha256:4d4987ce51a49370ea65c0bfd2234e8ce80a12780820d9dc462597a6e60d0841\n # via\n- # -r ci/official/requirements_updater/requirements.in\n+ # -r ci/official/requirements_updater/numpy1_requirements/requirements.in\n # astunparse\n wrapt==1.16.0 \\\n --hash=sha256:0d2691979e93d06a95a26257adb7bfd0c93818e89b1406f5a28f36e0d8c1e1fc \\\n@@ -813,7 +905,7 @@ wrapt==1.16.0 \\\n --hash=sha256:f6b2d0c6703c988d334f297aa5df18c45e97b0af3679bb75059e0e0bd8b1069d \\\n --hash=sha256:f8212564d49c50eb4565e502814f694e240c55551a5f1bc841d4fcaabb0a9b8a \\\n --hash=sha256:ffa565331890b90056c01db69c0fe634a776f8019c143a5ae265f9c6bc4bd6d4\n- # via -r ci/official/requirements_updater/requirements.in\n+ # via -r ci/official/requirements_updater/numpy1_requirements/requirements.in\n zstandard==0.23.0 \\\n --hash=sha256:034b88913ecc1b097f528e42b539453fa82c3557e414b3de9d5632c80439a473 \\\n --hash=sha256:0a7f0804bb3799414af278e9ad51be25edf67f78f916e08afdb983e74161b916 \\\n@@ -912,12 +1004,12 @@ zstandard==0.23.0 \\\n --hash=sha256:fd30d9c67d13d891f2360b2a120186729c111238ac63b43dbd37a5a40670b8ca \\\n --hash=sha256:fd7699e8fd9969f455ef2926221e0233f81a2542921471382e77a9e2f2b57f4b \\\n --hash=sha256:fe3b385d996ee0822fd46528d9f0443b880d4d05528fd26a9119a54ec3f91c69\n- # via -r ci/official/requirements_updater/requirements.in\n+ # via -r ci/official/requirements_updater/numpy1_requirements/requirements.in\n \n # The following packages are considered to be unsafe in a requirements file:\n setuptools==78.1.1 \\\n --hash=sha256:c3a9c4211ff4c309edb8b8c4f1cbfa7ae324c4ba9f91ff254e3d305b9fd54561 \\\n --hash=sha256:fcc17fd9cd898242f6b4adfaca46137a9edef687f43e6f78469692a5e70d851d\n # via\n- # -r ci/official/requirements_updater/requirements.in\n- # tb-nightly\n+ # -r ci/official/requirements_updater/numpy1_requirements/requirements.in\n+ # tensorboard" }, { "filename": "ci/official/requirements_updater/numpy1_requirements/requirements_lock_3_12.txt", "status": "modified", "additions": 146, "deletions": 54, "changes": 200, "patch": "@@ -2,26 +2,26 @@\n # This file is autogenerated by [NAME_REDACTED] 3.12\n # by [NAME_REDACTED]:\n #\n-# bazel run //ci/official/requirements_updater:requirements.update\n+# bazel run //ci/official/requirements_updater/numpy1_requirements:requirements_312.update\n #\n absl-py==2.2.2 \\\n --hash=sha256:bf25b2c2eed013ca456918c453d687eab4e8309fba81ee2f4c1a6aa2494175eb \\\n --hash=sha256:e5797bc6abe45f64fd95dc06394ca3f2bedf3b5d895e9da691c9ee3397d70092\n # via\n- # keras-nightly\n- # tb-nightly\n+ # keras\n+ # tensorboard\n astor==0.7.1 \\\n --hash=sha256:95c30d87a6c2cf89aa628b87398466840f0ad8652f88eb173125a6df8533fb8d \\\n --hash=sha256:fb503b9e2fdd05609fbf557b916b4a7824171203701660f0c55bbf5a7a68713e\n- # via -r ci/official/requirements_updater/requirements.in\n+ # via -r ci/official/requirements_updater/numpy1_requirements/requirements.in\n astunparse==1.6.3 \\\n --hash=sha256:5ad93a8456f0d084c3456d059fd9a92cce667963232cbf763eac3bc5b7940872 \\\n --hash=sha256:c2652417f2c8b5bb325c885ae329bdf3f86424075c4fd1a128674bc6fba4b8e8\n- # via -r ci/official/requirements_updater/requirements.in\n+ # via -r ci/official/requirements_updater/numpy1_requirements/requirements.in\n auditwheel==6.3.0 \\\n --hash=sha256:05c70a234fa14c140aa6d9076135d9550962d95849911b8d5d0419a3add09f00 \\\n --hash=sha256:31cbd8045d4ff6776f79bef328b5fd563e5ecc8ae82ea34b6fe5e76efe2a84eb\n- # via -r ci/official/requirements_updater/requirements.in\n+ # via -r ci/official/requirements_updater/numpy1_requirements/requirements.in\n certifi==2025.1.31 \\\n --hash=sha256:3d5da6925056f6f18f119200434a4780a94263f10d1c21d032a6f6b2baa20651 \\\n --hash=sha256:ca78db4565a652026a4db2bcdf68f2fb589ea80d0be70e03929ed730746b84fe\n@@ -123,20 +123,20 @@ charset-normalizer==3.4.1 \\\n dill==0.3.7 \\\n --hash=sha256:76b122c08ef4ce2eedcd4d1abd8e641114bfc6c2867f49f3c41facf65bf19f5e \\\n --hash=sha256:cc1c8b182eb3013e24bd475ff2e9295af86c1a38eb1aff128dac8962a9ce3c03\n- # via -r ci/official/requirements_updater/requirements.in\n+ # via -r ci/official/requirements_updater/numpy1_requirements/requirements.in\n flatbuffers==25.9.23 \\\n --hash=sha256:255538574d6cb6d0a79a17ec8bc0d30985913b87513a01cce8bcdb6b4c44d0e2 \\\n --hash=sha256:676f9fa62750bb50cf531b42a0a2a118ad8f7f797a511eda12881c016f093b12\n- # via -r ci/official/requirements_updater/requirements.in\n+ # via -r ci/official/requirements_updater/numpy1_requirements/requirements.in\n gast==0.4.0 \\\n --hash=sha256:40feb7b8b8434785585ab224d1568b857edb18297e5a3047f1ba012bc83b42c1 \\\n --hash=sha256:b7adcdd5adbebf1adf17378da5ba3f543684dbec47b1cda1f3997e573cd542c4\n- # via -r ci/official/requirements_updater/requirements.in\n+ # via -r ci/official/requirements_updater/numpy1_requirements/requirements.in\n google-pasta==0.2.0 \\\n --hash=sha256:4612951da876b1a10fe3960d7226f0c7682cf901e16ac06e473b267a5afa8954 \\\n --hash=sha256:b32482794a366b5366a32c92a9a9201b107821889935a02b3e51f6b432ea84ed \\\n --hash=sha256:c9f2c8dfc8f96d0d5808299920721be30c9eec37f2389f28904f454565c8a16e\n- # via -r ci/official/requirements_updater/requirements.in\n+ # via -r ci/official/requirements_updater/numpy1_requirements/requirements.in\n grpcio==1.71.0 \\\n --hash=sha256:0ab8b2864396663a5b0b0d6d79495657ae85fa37dcb6498a2669d067c65c11ea \\\n --hash=sha256:0fa05ee31a20456b13ae49ad2e5d585265f71dd19fbd9ef983c28f926d45d0a7 \\\n@@ -190,8 +190,8 @@ grpcio==1.71.0 \\\n --hash=sha256:f9a412f55bb6e8f3bb000e020dbc1e709627dcb3a56f6431fa7076b4c1aab0db \\\n --hash=sha256:f9c30c464cb2ddfbc2ddf9400287701270fdc0f14be5f08a1e3939f1e749b455\n # via\n- # -r ci/official/requirements_updater/requirements.in\n- # tb-nightly\n+ # -r ci/official/requirements_updater/numpy1_requirements/requirements.in\n+ # tensorboard\n h5py==3.13.0 \\\n --hash=sha256:10894c55d46df502d82a7a4ed38f9c3fdbcb93efb42e25d275193e093071fade \\\n --hash=sha256:1870e46518720023da85d0895a1960ff2ce398c5671eac3b1a41ec696b7105c3 \\\n@@ -220,19 +220,19 @@ h5py==3.13.0 \\\n --hash=sha256:f35640e81b03c02a88b8bf99fb6a9d3023cc52f7c627694db2f379e0028f2868 \\\n --hash=sha256:fb267ce4b83f9c42560e9ff4d30f60f7ae492eacf9c7ede849edf8c1b860e16b\n # via\n- # -r ci/official/requirements_updater/requirements.in\n- # keras-nightly\n+ # -r ci/official/requirements_updater/numpy1_requirements/requirements.in\n+ # keras\n idna==3.10 \\\n --hash=sha256:12f65c9b470abda6dc35cf8e63cc574b1c52b11df2c86030af0ac09b01b13ea9 \\\n --hash=sha256:946d195a0d259cbba61165e88e65941f16e9b36ea6ddb97f00452bae8b1287d3\n # via requests\n jax==0.4.7 \\\n --hash=sha256:5e7002d74db25f97c99b979d4ba1233b1ef26e1597e5fc468ad11d1c8a9dc4f8\n- # via -r ci/official/requirements_updater/requirements.in\n-keras-nightly==3.12.0.dev2025100703 \\\n- --hash=sha256:6b9dfb3814d707abf5555f56268f072daec13f2540da3aeeb7531a819ebb4567 \\\n- --hash=sha256:e29434e49bac3360f86af6e1548d94b0a2fda4e793685bc43b49867132ab16e5\n- # via -r ci/official/requirements_updater/requirements.in\n+ # via -r ci/official/requirements_updater/numpy1_requirements/requirements.in\n+keras==3.12.1 \\\n+ --hash=sha256:3cb760b3fec105db4d893dd717daafdd0e35457a8201502c1ba8bedfaf334a71 \\\n+ --hash=sha256:c340f8a25362398b20500c64e290f6ee280c6aeec51e1044eb8d759b32dc272a\n+ # via -r ci/official/requirements_updater/numpy1_requirements/requirements.in\n libclang==18.1.1 \\\n --hash=sha256:0b2e143f0fac830156feb56f9231ff8338c20aecfe72b4ffe96f19e5a1dbb69a \\\n --hash=sha256:3f0e1f49f04d3cd198985fea0511576b0aee16f9ff0e0f0cad7f9c57ec3c20e8 \\\n@@ -244,14 +244,14 @@ libclang==18.1.1 \\\n --hash=sha256:a1214966d08d73d971287fc3ead8dfaf82eb07fb197680d8b3859dbbbbf78250 \\\n --hash=sha256:c533091d8a3bbf7460a00cb6c1a71da93bffe148f172c7d03b1c31fbf8aa2a0b \\\n --hash=sha256:cf4a99b05376513717ab5d82a0db832c56ccea4fd61a69dbb7bccf2dfb207dbe\n- # via -r ci/official/requirements_updater/requirements.in\n+ # via -r ci/official/requirements_updater/numpy1_requirements/requirements.in\n lit==17.0.6 \\\n --hash=sha256:dfa9af9b55fc4509a56be7bf2346f079d7f4a242d583b9f2e0b078fd0abae31b\n- # via -r ci/official/requirements_updater/requirements.in\n+ # via -r ci/official/requirements_updater/numpy1_requirements/requirements.in\n markdown==3.8 \\\n --hash=sha256:794a929b79c5af141ef5ab0f2f642d0f7b1872981250230e72682346f7cc90dc \\\n --hash=sha256:7df81e63f0df5c4b24b7d156eb81e4690595239b7d70937d0409f1b0de319c6f\n- # via tb-nightly\n+ # via tensorboard\n markdown-it-py==3.0.0 \\\n --hash=sha256:355216845c60bd96232cd8d8c40e8f9765cc86f46880e43a8fd22dc1a1a8cab1 \\\n --hash=sha256:e3f60a94fa066dc52ec76661e37c851cb232d92f9886b15cb560aaada2df8feb\n@@ -349,13 +349,13 @@ ml-dtypes==0.5.1 \\\n --hash=sha256:d13755f8e8445b3870114e5b6240facaa7cb0c3361e54beba3e07fa912a6e12b \\\n --hash=sha256:fd918d4e6a4e0c110e2e05be7a7814d10dc1b95872accbf6512b80a109b71ae1\n # via\n- # -r ci/official/requirements_updater/requirements.in\n+ # -r ci/official/requirements_updater/numpy1_requirements/requirements.in\n # jax\n- # keras-nightly\n+ # keras\n namex==0.0.9 \\\n --hash=sha256:7bd4e4a2cc3876592111609fdf4cbe6ff19883adbe6b3b40d842fd340f77025e \\\n --hash=sha256:8adfea9da5cea5be8f4e632349b4669e30172c7859e1fd97459fdf3b17469253\n- # via keras-nightly\n+ # via keras\n numpy==1.26.4 \\\n --hash=sha256:03a8c78d01d9781b28a6989f6fa1bb2c4f2d51201cf99d3dd875df6fbd96b23b \\\n --hash=sha256:08beddf13648eb95f8d867350f6a018a4be2e5ad54c8d8caed89ebca558b2818 \\\n@@ -394,14 +394,14 @@ numpy==1.26.4 \\\n --hash=sha256:f870204a840a60da0b12273ef34f7051e98c3b5961b61b0c2c1be6dfd64fbcd3 \\\n --hash=sha256:ffa75af20b44f8dba823498024771d5ac50620e6915abac414251bd971b4529f\n # via\n- # -r ci/official/requirements_updater/requirements.in\n+ # -r ci/official/requirements_updater/numpy1_requirements/requirements.in\n # h5py\n # jax\n- # keras-nightly\n+ # keras\n # ml-dtypes\n # opt-einsum\n # scipy\n- # tb-nightly\n+ # tensorboard\n nvidia-cublas-cu12==12.5.3.2 \\\n --hash=sha256:4960f3dc5f39699acadf76fa6d94b10a2a00f2956c2c442efa299fb22b0748f3 \\\n --hash=sha256:7d0191251180de606023d396b94d66f66470a0ae96d1dbb906c7656ea0f71eda \\\n@@ -514,7 +514,7 @@ opt-einsum==3.3.0 \\\n --hash=sha256:2455e59e3947d3c275477df7f5205b30635e266fe6dc300e3d9f9646bfcea147 \\\n --hash=sha256:59f6475f77bbc37dcf7cd748519c0ec60722e91e63ca114e68821c0c54a46549\n # via\n- # -r ci/official/requirements_updater/requirements.in\n+ # -r ci/official/requirements_updater/numpy1_requirements/requirements.in\n # jax\n optree==0.16.0 \\\n --hash=sha256:0dd607bfbf59ecf92b069af18e8a41b0d8628e21f2de5a738fad039d0a89d9d4 \\\n@@ -590,19 +590,112 @@ optree==0.16.0 \\\n --hash=sha256:eeccc740b72b58efa9795ab831a678a42341def48b9e5956c6b1e588c6fa3ddf \\\n --hash=sha256:f08aaa1c2ae092b3e662125ad19860046c63d7451d41be133ddd6594920e295e \\\n --hash=sha256:f703d7926c36eebdd56fc08aabefcf32a8b7292a9dd4468e56b0ab61bf6214bd\n- # via keras-nightly\n+ # via keras\n packaging==23.2 \\\n --hash=sha256:048fb0e9405036518eaaf48a55953c750c11e1a1b68e0dd1a9d62ed0c092cfc5 \\\n --hash=sha256:8c491190033a9af7e1d931d0b5dacc2ef47509b34dd0de67ed209b5203fc88c7\n # via\n- # -r ci/official/requirements_updater/requirements.in\n+ # -r ci/official/requirements_updater/numpy1_requirements/requirements.in\n # auditwheel\n- # keras-nightly\n- # tb-nightly\n+ # keras\n+ # tensorboard\n+pillow==12.1.0 \\\n+ --hash=sha256:00162e9ca6d22b7c3ee8e61faa3c3253cd19b6a37f126cad04f2f88b306f557d \\\n+ --hash=sha256:079af2fb0c599c2ec144ba2c02766d1b55498e373b3ac64687e43849fbbef5bc \\\n+ --hash=sha256:0b022eaaf709541b391ee069f0022ee5b36c709df71986e3f7be312e46f42c84 \\\n+ --hash=sha256:0c27407a2d1b96774cbc4a7594129cc027339fd800cd081e44497722ea1179de \\\n+ --hash=sha256:0ddedfaa8b5f0b4ffbc2fa87b556dc59f6bb4ecb14a53b33f9189713ae8053c0 \\\n+ --hash=sha256:0deedf2ea233722476b3a81e8cdfbad786f7adbed5d848469fa59fe52396e4ef \\\n+ --hash=sha256:0ed07dca4a8464bada6139ab38f5382f83e5f111698caf3191cb8dbf27d908b4 \\\n+ --hash=sha256:0fde7ec5538ab5095cc02df38ee99b0443ff0e1c847a045554cf5f9af1f4aa82 \\\n+ --hash=sha256:15c794d74303828eaa957ff8070846d0efe8c630901a1c753fdc63850e19ecd9 \\\n+ --hash=sha256:1a949604f73eb07a8adab38c4fe50791f9919344398bdc8ac6b307f755fc7030 \\\n+ --hash=sha256:1f345e7bc9d7f368887c712aa5054558bad44d2a301ddf9248599f4161abc7c0 \\\n+ --hash=sha256:1fcc52d86ce7a34fd17cb04e87cfdb164648a3662a6f20565910a99653d66c18 \\\n+ --hash=sha256:21e686a21078b0f9cb8c8a961d99e6a4ddb88e0fc5ea6e130172ddddc2e5221a \\\n+ --hash=sha256:2415373395a831f53933c23ce051021e79c8cd7979822d8cc478547a3f4da8ef \\\n+ --hash=sha256:277518bf4fe74aa91489e1b20577473b19ee70fb97c374aa50830b279f25841b \\\n+ --hash=sha256:27b9baecb428899db6c0de572d6d305cfaf38ca1596b5c0542a5182e3e74e8c6 \\\n+ --hash=sha256:29a4cef9cb672363926f0470afc516dbf7305a14d8c54f7abbb5c199cd8f8179 \\\n+ --hash=sha256:3413c2ae377550f5487991d444428f1a8ae92784aac79caa8b1e3b89b175f77e \\\n+ --hash=sha256:351889afef0f485b84078ea40fe33727a0492b9af3904661b0abbafee0355b72 \\\n+ --hash=sha256:3ffaa2f0659e2f740473bcf03c702c39a8d4b2b7ffc629052028764324842c64 \\\n+ --hash=sha256:40a8e3b9e8773876d6e30daed22f016509e3987bab61b3b7fe309d7019a87451 \\\n+ --hash=sha256:414b9a78e14ffeb98128863314e62c3f24b8a86081066625700b7985b3f529bd \\\n+ --hash=sha256:43aca0a55ce1eefc0aefa6253661cb54571857b1a7b2964bd8a1e3ef4b729924 \\\n+ --hash=sha256:43b4899cfd091a9693a1278c4982f3e50f7fb7cff5153b05174b4afc9593b616 \\\n+ --hash=sha256:461f9dfdafa394c59cd6d818bdfdbab4028b83b02caadaff0ffd433faf4c9a7a \\\n+ --hash=sha256:4f9f6a650743f0ddee5593ac9e954ba1bdbc5e150bc066586d4f26127853ab94 \\\n+ --hash=sha256:53d8b764726d3af1a138dd353116f774e3862ec7e3794e0c8781e30db0f35dfc \\\n+ --hash=sha256:565c986f4b45c020f5421a4cea13ef294dde9509a8577f29b2fc5edc7587fff8 \\\n+ --hash=sha256:5c5ae0a06e9ea030ab786b0251b32c7e4ce10e58d983c0d5c56029455180b5b9 \\\n+ --hash=sha256:5cb7bc1966d031aec37ddb9dcf15c2da5b2e9f7cc3ca7c54473a20a927e1eb91 \\\n+ --hash=sha256:5da841d81b1a05ef940a8567da92decaa15bc4d7dedb540a8c219ad83d91808a \\\n+ --hash=sha256:5fee4c04aad8932da9f8f710af2c1a15a83582cfb884152a9caa79d4efcdbf9c \\\n+ --hash=sha256:609e89d9f90b581c8d16358c9087df76024cf058fa693dd3e1e1620823f39670 \\\n+ --hash=sha256:6258f3260986990ba2fa8a874f8b6e808cf5abb51a94015ca3dc3c68aa4f30ea \\\n+ --hash=sha256:64efdf00c09e31efd754448a383ea241f55a994fd079866b92d2bbff598aad91 \\\n+ --hash=sha256:65b80c1ee7e14a87d6a068dd3b0aea268ffcabfe0498d38661b00c5b4b22e74c \\\n+ --hash=sha256:6741e6f3074a35e47c77b23a4e4f2d90db3ed905cb1c5e6e0d49bff2045632bc \\\n+ --hash=sha256:681088909d7e8fa9e31b9799aaa59ba5234c58e5e4f1951b4c4d1082a2e980e0 \\\n+ --hash=sha256:6b7a9d1db5dad90e2991645874f708e87d9a3c370c243c2d7684d28f7e133e6b \\\n+ --hash=sha256:7315f9137087c4e0ee73a761b163fc9aa3b19f5f606a7fc08d83fd3e4379af65 \\\n+ --hash=sha256:742aea052cf5ab5034a53c3846165bc3ce88d7c38e954120db0ab867ca242661 \\\n+ --hash=sha256:75af0b4c229ac519b155028fa1be632d812a519abba9b46b20e50c6caa184f19 \\\n+ --hash=sha256:7b5dd7cbae20285cdb597b10eb5a2c13aa9de6cde9bb64a3c1317427b1db1ae1 \\\n+ --hash=sha256:7d6daa89a00b58c37cb1747ec9fb7ac3bc5ffd5949f5888657dfddde6d1312e0 \\\n+ --hash=sha256:800429ac32c9b72909c671aaf17ecd13110f823ddb7db4dfef412a5587c2c24e \\\n+ --hash=sha256:806f3987ffe10e867bab0ddad45df1148a2b98221798457fa097ad85d6e8bc75 \\\n+ --hash=sha256:808b99604f7873c800c4840f55ff389936ef1948e4e87645eaf3fccbc8477ac4 \\\n+ --hash=sha256:80941e6d573197a0c28f394753de529bb436b1ca990ed6e765cf42426abc39f8 \\\n+ --hash=sha256:84cabc7095dd535ca934d57e9ce2a72ffd216e435a84acb06b2277b1de2689bd \\\n+ --hash=sha256:8637e29d13f478bc4f153d8daa9ffb16455f0a6cb287da1b432fdad2bfbd66c7 \\\n+ --hash=sha256:896866d2d436563fa2a43a9d72f417874f16b5545955c54a64941e87c1376c61 \\\n+ --hash=sha256:8e178e3e99d3c0ea8fc64b88447f7cac8ccf058af422a6cedc690d0eadd98c51 \\\n+ --hash=sha256:907bfa8a9cb790748a9aa4513e37c88c59660da3bcfffbd24a7d9e6abf224551 \\\n+ --hash=sha256:9212d6b86917a2300669511ed094a9406888362e085f2431a7da985a6b124f45 \\\n+ --hash=sha256:92a7fe4225365c5e3a8e598982269c6d6698d3e783b3b1ae979e7819f9cd55c1 \\\n+ --hash=sha256:935b9d1aed48fcfb3f838caac506f38e29621b44ccc4f8a64d575cb1b2a88644 \\\n+ --hash=sha256:97e9993d5ed946aba26baf9c1e8cf18adbab584b99f452ee72f7ee8acb882796 \\\n+ --hash=sha256:983976c2ab753166dc66d36af6e8ec15bb511e4a25856e2227e5f7e00a160587 \\\n+ --hash=sha256:9f5fefaca968e700ad1a4a9de98bf0869a94e397fe3524c4c9450c1445252304 \\\n+ --hash=sha256:a332ac4ccb84b6dde65dbace8431f3af08874bf9770719d32a635c4ef411b18b \\\n+ --hash=sha256:a40905599d8079e09f25027423aed94f2823adaf2868940de991e53a449e14a8 \\\n+ --hash=sha256:a6dfc2af5b082b635af6e08e0d1f9f1c4e04d17d4e2ca0ef96131e85eda6eb17 \\\n+ --hash=sha256:a786bf667724d84aa29b5db1c61b7bfdde380202aaca12c3461afd6b71743171 \\\n+ --hash=sha256:a83e0850cb8f5ac975291ebfc4170ba481f41a28065277f7f735c202cd8e0af3 \\\n+ --hash=sha256:aa0c9cc0b82b14766a99fbe6084409972266e82f459821cd26997a488a7261a7 \\\n+ --hash=sha256:b17fbdbe01c196e7e159aacb889e091f28e61020a8abeac07b68079b6e626988 \\\n+ --hash=sha256:b63e13dd27da389ed9475b3d28510f0f954bca0041e8e551b2a4eb1eab56a39a \\\n+ --hash=sha256:b6e53e82ec2db0717eabb276aa56cf4e500c9a7cec2c2e189b55c24f65a3e8c0 \\\n+ --hash=sha256:bb0984b30e973f7e2884362b7d23d0a348c7143ee559f38ef3eaab640144204c \\\n+ --hash=sha256:bc11908616c8a283cf7d664f77411a5ed2a02009b0097ff8abbba5e79128ccf2 \\\n+ --hash=sha256:bdec5e43377761c5dbca620efb69a77f6855c5a379e32ac5b158f54c84212b14 \\\n+ --hash=sha256:bef9768cab184e7ae6e559c032e95ba8d07b3023c289f79a2bd36e8bf85605a5 \\\n+ --hash=sha256:c990547452ee2800d8506c4150280757f88532f3de2a58e3022e9b179107862a \\\n+ --hash=sha256:ca94b6aac0d7af2a10ba08c0f888b3d5114439b6b3ef39968378723622fed377 \\\n+ --hash=sha256:cad302dc10fac357d3467a74a9561c90609768a6f73a1923b0fd851b6486f8b0 \\\n+ --hash=sha256:d0a7735df32ccbcc98b98a1ac785cc4b19b580be1bdf0aeb5c03223220ea09d5 \\\n+ --hash=sha256:d70347c8a5b7ccd803ec0c85c8709f036e6348f1e6a5bf048ecd9c64d3550b8b \\\n+ --hash=sha256:d70534cea9e7966169ad29a903b99fc507e932069a881d0965a1a84bb57f6c6d \\\n+ --hash=sha256:db44d5c160a90df2d24a24760bbd37607d53da0b34fb546c4c232af7192298ac \\\n+ --hash=sha256:e115c15e3bc727b1ca3e641a909f77f8ca72a64fff150f666fcc85e57701c26c \\\n+ --hash=sha256:e2479c7f02f9d505682dc47df8c0ea1fc5e264c4d1629a5d63fe3e2334b89554 \\\n+ --hash=sha256:e5dcbe95016e88437ecf33544ba5db21ef1b8dd6e1b434a2cb2a3d605299e643 \\\n+ --hash=sha256:e6bdb408f7c9dd2a5ff2b14a3b0bb6d4deb29fb9961e6eb3ae2031ae9a5cec13 \\\n+ --hash=sha256:e75d3dba8fc1ddfec0cd752108f93b83b4f8d6ab40e524a95d35f016b9683b09 \\\n+ --hash=sha256:efdc140e7b63b8f739d09a99033aa430accce485ff78e6d311973a67b6bf3208 \\\n+ --hash=sha256:f10c98f49227ed8383d28174ee95155a675c4ed7f85e2e573b04414f7e371bda \\\n+ --hash=sha256:f188028b5af6b8fb2e9a76ac0f841a575bd1bd396e46ef0840d9b88a48fdbcea \\\n+ --hash=sha256:f188d580bd870cda1e15183790d1cc2fa78f666e76077d103edf048eed9c356e \\\n+ --hash=sha256:f45bd71d1fa5e5749587613037b172e0b3b23159d1c00ef2fc920da6f470e6f0 \\\n+ --hash=sha256:f61333d817698bdcdd0f9d7793e365ac3d2a21c1f1eb02b32ad6aefb8d8ea831 \\\n+ --hash=sha256:fb125d860738a09d363a88daa0f59c4533529a90e564785e20fe875b200b6dbd\n+ # via tensorboard\n portpicker==1.6.0 \\\n --hash=sha256:b2787a41404cf7edbe29b07b9e0ed863b09f2665dcc01c1eb0c2261c1e7d0755 \\\n --hash=sha256:bd507fd6f96f65ee02781f2e674e9dc6c99bbfa6e3c39992e3916204c9d431fa\n- # via -r ci/official/requirements_updater/requirements.in\n+ # via -r ci/official/requirements_updater/numpy1_requirements/requirements.in\n protobuf==6.31.1 \\\n --hash=sha256:0414e3aa5a5f3ff423828e1e6a6e907d6c65c1d5b7e6e975793d5590bdeecc16 \\\n --hash=sha256:426f59d2964864a1a366254fa703b8632dcec0790d8862d30034d8245e1cd447 \\\n@@ -614,8 +707,8 @@ protobuf==6.31.1 \\\n --hash=sha256:a40fc12b84c154884d7d4c4ebd675d5b3b5283e155f324049ae396b95ddebc39 \\\n --hash=sha256:d8cac4c982f0b957a4dc73a80e2ea24fab08e679c0de9deb835f4a12d69aca9a\n # via\n- # -r ci/official/requirements_updater/requirements.in\n- # tb-nightly\n+ # -r ci/official/requirements_updater/numpy1_requirements/requirements.in\n+ # tensorboard\n psutil==7.0.0 \\\n --hash=sha256:101d71dc322e3cffd7cea0650b09b3d08b8e7c4109dd6809fe452dfd00e58b25 \\\n --hash=sha256:1e744154a6580bc968a0195fd25e80432d3afec619daf145b9e5ba16cc1d688e \\\n@@ -639,11 +732,11 @@ pygments==2.19.1 \\\n requests==2.32.4 \\\n --hash=sha256:27babd3cda2a6d50b30443204ee89830707d396671944c998b5975b031ac2b2c \\\n --hash=sha256:27d0316682c8a29834d3264820024b62a36942083d52caf2f14c0591336d3422\n- # via -r ci/official/requirements_updater/requirements.in\n+ # via -r ci/official/requirements_updater/numpy1_requirements/requirements.in\n rich==14.0.0 \\\n --hash=sha256:1c9491e1951aac09caffd42f448ee3d04e58923ffe14993f6e83068dc395d7e0 \\\n --hash=sha256:82f1bc23a6a21ebca4ae0c45af9bdbc492ed20231dcb63f297d6d1021a9d5725\n- # via keras-nightly\n+ # via keras\n scipy==1.14.1 \\\n --hash=sha256:0c2f95de3b04e26f5f3ad5bb05e74ba7f68b837133a4492414b3afd79dfe540e \\\n --hash=sha256:1729560c906963fc8389f6aac023739ff3983e727b1a4d87696b7bf108316a79 \\\n@@ -679,27 +772,26 @@ scipy==1.14.1 \\\n --hash=sha256:edaf02b82cd7639db00dbff629995ef185c8df4c3ffa71a5562a595765a06ce1 \\\n --hash=sha256:fef8c87f8abfb884dac04e97824b61299880c43f4ce675dd2cbeadd3c9b466d2\n # via\n- # -r ci/official/requirements_updater/requirements.in\n+ # -r ci/official/requirements_updater/numpy1_requirements/requirements.in\n # jax\n six==1.17.0 \\\n --hash=sha256:4721f391ed90541fddacab5acf947aa0d3dc7d27b2e1e8eda2be8970586c3274 \\\n --hash=sha256:ff70335d468e7eb6ec65b95b99d3a2836546063f63acc5171de367e834932a81\n # via\n # astunparse\n # google-pasta\n- # tb-nightly\n-tb-nightly==2.20.0a20250424 \\\n- --hash=sha256:62ad3a4ce94cba2bb59538dd481999ede10927304d6f7fa0e9a23df9d24a779e\n- # via -r ci/official/requirements_updater/requirements.in\n tblib==2.0.0 \\\n --hash=sha256:9100bfa016b047d5b980d66e7efed952fbd20bd85b56110aaf473cb97d18709a \\\n --hash=sha256:a6df30f272c08bf8be66e0775fad862005d950a6b8449b94f7c788731d70ecd7\n- # via -r ci/official/requirements_updater/requirements.in\n+ # via -r ci/official/requirements_updater/numpy1_requirements/requirements.in\n+tensorboard==2.20.0 \\\n+ --hash=sha256:9dc9f978cb84c0723acf9a345d96c184f0293d18f166bb8d59ee098e6cfaaba6\n+ # via -r ci/official/requirements_updater/numpy1_requirements/requirements.in\n tensorboard-data-server==0.7.2 \\\n --hash=sha256:7e0610d205889588983836ec05dc098e80f97b7e7bbff7e994ebb78f578d0ddb \\\n --hash=sha256:9fe5d24221b29625dbc7328b0436ca7fc1c23de4acf4d272f1180856e32f9f60 \\\n --hash=sha256:ef687163c24185ae9754ed5650eb5bc4d84ff257aabdc33f0cc6f74d8ba54530\n- # via tb-nightly\n+ # via tensorboard\n tensorflow-io-gcs-filesystem==0.37.1 ; python_version <= \"3.12\" \\\n --hash=sha256:0df00891669390078a003cedbdd3b8e645c718b111917535fa1d7725e95cdb95 \\\n --hash=sha256:249c12b830165841411ba71e08215d0e94277a49c551e6dd5d72aab54fe5491b \\\n@@ -717,16 +809,16 @@ tensorflow-io-gcs-filesystem==0.37.1 ; python_version <= \"3.12\" \\\n --hash=sha256:fbb33f1745f218464a59cecd9a18e32ca927b0f4d77abd8f8671b645cc1a182f \\\n --hash=sha256:fe8dcc6d222258a080ac3dfcaaaa347325ce36a7a046277f6b3e19abc1efb3c5 \\\n --hash=sha256:ffebb6666a7bfc28005f4fbbb111a455b5e7d6cd3b12752b7050863ecb27d5cc\n- # via -r ci/official/requirements_updater/requirements.in\n+ # via -r ci/official/requirements_updater/numpy1_requirements/requirements.in\n termcolor==2.3.0 \\\n --hash=sha256:3afb05607b89aed0ffe25202399ee0867ad4d3cb4180d98aaf8eefa6a5f7d475 \\\n --hash=sha256:b5b08f68937f138fe92f6c089b99f1e2da0ae56c52b78bf7075fd95420fd9a5a\n- # via -r ci/official/requirements_updater/requirements.in\n+ # via -r ci/official/requirements_updater/numpy1_requirements/requirements.in\n typing-extensions==4.14.1 \\\n --hash=sha256:38b39f4aeeab64884ce9f74c94263ef78f3c22467c8724005483154c26648d36 \\\n --hash=sha256:d1e1e3b58374dc93031d6eda2420a48ea44a36c2b4766a4fdeb3710755731d76\n # via\n- # -r ci/official/requirements_updater/requirements.in\n+ # -r ci/official/requirements_updater/numpy1_requirements/requirements.in\n # optree\n urllib3==2.6.3 \\\n --hash=sha256:1b62b6884944a57dbe321509ab94fd4d3b307075e0c2eae991ac71ee15ad38ed \\\n@@ -735,12 +827,12 @@ urllib3==2.6.3 \\\n werkzeug==3.1.5 \\\n --hash=sha256:5111e36e91086ece91f93268bb39b4a35c1e6f1feac762c9c822ded0a4e322dc \\\n --hash=sha256:6a548b0e88955dd07ccb25539d7d0cc97417ee9e179677d22c7041c8f078ce67\n- # via tb-nightly\n+ # via tensorboard\n wheel==0.41.3 \\\n --hash=sha256:488609bc63a29322326e05560731bf7bfea8e48ad646e1f5e40d366607de0942 \\\n --hash=sha256:4d4987ce51a49370ea65c0bfd2234e8ce80a12780820d9dc462597a6e60d0841\n # via\n- # -r ci/official/requirements_updater/requirements.in\n+ # -r ci/official/requirements_updater/numpy1_requirements/requirements.in\n # astunparse\n wrapt==1.16.0 \\\n --hash=sha256:0d2691979e93d06a95a26257adb7bfd0c93818e89b1406f5a28f36e0d8c1e1fc \\\n@@ -813,7 +905,7 @@ wrapt==1.16.0 \\\n --hash=sha256:f6b2d0c6703c988d334f297aa5df18c45e97b0af3679bb75059e0e0bd8b1069d \\\n --hash=sha256:f8212564d49c50eb4565e502814f694e240c55551a5f1bc841d4fcaabb0a9b8a \\\n --hash=sha256:ffa565331890b90056c01db69c0fe634a776f8019c143a5ae265f9c6bc4bd6d4\n- # via -r ci/official/requirements_updater/requirements.in\n+ # via -r ci/official/requirements_updater/numpy1_requirements/requirements.in\n zstandard==0.23.0 \\\n --hash=sha256:034b88913ecc1b097f528e42b539453fa82c3557e414b3de9d5632c80439a473 \\\n --hash=sha256:0a7f0804bb3799414af278e9ad51be25edf67f78f916e08afdb983e74161b916 \\\n@@ -912,12 +1004,12 @@ zstandard==0.23.0 \\\n --hash=sha256:fd30d9c67d13d891f2360b2a120186729c111238ac63b43dbd37a5a40670b8ca \\\n --hash=sha256:fd7699e8fd9969f455ef2926221e0233f81a2542921471382e77a9e2f2b57f4b \\\n --hash=sha256:fe3b385d996ee0822fd46528d9f0443b880d4d05528fd26a9119a54ec3f91c69\n- # via -r ci/official/requirements_updater/requirements.in\n+ # via -r ci/official/requirements_updater/numpy1_requirements/requirements.in\n \n # The following packages are considered to be unsafe in a requirements file:\n setuptools==78.1.1 \\\n --hash=sha256:c3a9c4211ff4c309edb8b8c4f1cbfa7ae324c4ba9f91ff254e3d305b9fd54561 \\\n --hash=sha256:fcc17fd9cd898242f6b4adfaca46137a9edef687f43e6f78469692a5e70d851d\n # via\n- # -r ci/official/requirements_updater/requirements.in\n- # tb-nightly\n+ # -r ci/official/requirements_updater/numpy1_requirements/requirements.in\n+ # tensorboard" }, { "filename": "ci/official/requirements_updater/requirements.in", "status": "modified", "additions": 2, "deletions": 2, "changes": 4, "patch": "@@ -18,8 +18,8 @@ auditwheel >= 6.1.0\n # Note that here we want the latest version that matches TF major.minor version\n # Note that we must use nightly here as these are used in nightly jobs\n # For release jobs, we will pin these on the release branch\n-keras-nightly ~= 3.12.0.dev\n-tb-nightly ~= 2.20.0.a\n+keras ~= 3.12.0\n+tensorboard ~= 2.20.0\n # For new protobuf, if V.x.y is gencode version, then runtime version U must be\n # V <= U <= V+1\n # More info at https://protobuf.dev/support/cross-version-runtime-guarantee/" }, { "filename": "requirements_lock_3_10.txt", "status": "modified", "additions": 119, "deletions": 27, "changes": 146, "patch": "@@ -8,8 +8,8 @@ absl-py==2.2.2 \\\n --hash=sha256:bf25b2c2eed013ca456918c453d687eab4e8309fba81ee2f4c1a6aa2494175eb \\\n --hash=sha256:e5797bc6abe45f64fd95dc06394ca3f2bedf3b5d895e9da691c9ee3397d70092\n # via\n- # keras-nightly\n- # tb-nightly\n+ # keras\n+ # tensorboard\n astor==0.7.1 \\\n --hash=sha256:95c30d87a6c2cf89aa628b87398466840f0ad8652f88eb173125a6df8533fb8d \\\n --hash=sha256:fb503b9e2fdd05609fbf557b916b4a7824171203701660f0c55bbf5a7a68713e\n@@ -191,7 +191,7 @@ grpcio==1.71.0 \\\n --hash=sha256:f9c30c464cb2ddfbc2ddf9400287701270fdc0f14be5f08a1e3939f1e749b455\n # via\n # -r ci/official/requirements_updater/requirements.in\n- # tb-nightly\n+ # tensorboard\n h5py==3.13.0 \\\n --hash=sha256:10894c55d46df502d82a7a4ed38f9c3fdbcb93efb42e25d275193e093071fade \\\n --hash=sha256:1870e46518720023da85d0895a1960ff2ce398c5671eac3b1a41ec696b7105c3 \\\n@@ -221,17 +221,17 @@ h5py==3.13.0 \\\n --hash=sha256:fb267ce4b83f9c42560e9ff4d30f60f7ae492eacf9c7ede849edf8c1b860e16b\n # via\n # -r ci/official/requirements_updater/requirements.in\n- # keras-nightly\n+ # keras\n idna==3.10 \\\n --hash=sha256:12f65c9b470abda6dc35cf8e63cc574b1c52b11df2c86030af0ac09b01b13ea9 \\\n --hash=sha256:946d195a0d259cbba61165e88e65941f16e9b36ea6ddb97f00452bae8b1287d3\n # via requests\n jax==0.4.7 \\\n --hash=sha256:5e7002d74db25f97c99b979d4ba1233b1ef26e1597e5fc468ad11d1c8a9dc4f8\n # via -r ci/official/requirements_updater/requirements.in\n-keras-nightly==3.12.0.dev2025100703 \\\n- --hash=sha256:6b9dfb3814d707abf5555f56268f072daec13f2540da3aeeb7531a819ebb4567 \\\n- --hash=sha256:e29434e49bac3360f86af6e1548d94b0a2fda4e793685bc43b49867132ab16e5\n+keras==3.12.1 \\\n+ --hash=sha256:3cb760b3fec105db4d893dd717daafdd0e35457a8201502c1ba8bedfaf334a71 \\\n+ --hash=sha256:c340f8a25362398b20500c64e290f6ee280c6aeec51e1044eb8d759b32dc272a\n # via -r ci/official/requirements_updater/requirements.in\n libclang==18.1.1 \\\n --hash=sha256:0b2e143f0fac830156feb56f9231ff8338c20aecfe72b4ffe96f19e5a1dbb69a \\\n@@ -251,7 +251,7 @@ lit==17.0.6 \\\n markdown==3.8 \\\n --hash=sha256:794a929b79c5af141ef5ab0f2f642d0f7b1872981250230e72682346f7cc90dc \\\n --hash=sha256:7df81e63f0df5c4b24b7d156eb81e4690595239b7d70937d0409f1b0de319c6f\n- # via tb-nightly\n+ # via tensorboard\n markdown-it-py==3.0.0 \\\n --hash=sha256:355216845c60bd96232cd8d8c40e8f9765cc86f46880e43a8fd22dc1a1a8cab1 \\\n --hash=sha256:e3f60a94fa066dc52ec76661e37c851cb232d92f9886b15cb560aaada2df8feb\n@@ -351,11 +351,11 @@ ml-dtypes==0.5.1 \\\n # via\n # -r ci/official/requirements_updater/requirements.in\n # jax\n- # keras-nightly\n+ # keras\n namex==0.0.9 \\\n --hash=sha256:7bd4e4a2cc3876592111609fdf4cbe6ff19883adbe6b3b40d842fd340f77025e \\\n --hash=sha256:8adfea9da5cea5be8f4e632349b4669e30172c7859e1fd97459fdf3b17469253\n- # via keras-nightly\n+ # via keras\n numpy==2.1.3 \\\n --hash=sha256:016d0f6f5e77b0f0d45d77387ffa4bb89816b57c835580c3ce8e099ef830befe \\\n --hash=sha256:02135ade8b8a84011cbb67dc44e07c58f28575cf9ecf8ab304e51c05528c19f0 \\\n@@ -416,11 +416,11 @@ numpy==2.1.3 \\\n # -r ci/official/requirements_updater/requirements.in\n # h5py\n # jax\n- # keras-nightly\n+ # keras\n # ml-dtypes\n # opt-einsum\n # scipy\n- # tb-nightly\n+ # tensorboard\n nvidia-cublas-cu12==12.5.3.2 \\\n --hash=sha256:4960f3dc5f39699acadf76fa6d94b10a2a00f2956c2c442efa299fb22b0748f3 \\\n --hash=sha256:7d0191251180de606023d396b94d66f66470a0ae96d1dbb906c7656ea0f71eda \\\n@@ -609,15 +609,108 @@ optree==0.16.0 \\\n --hash=sha256:eeccc740b72b58efa9795ab831a678a42341def48b9e5956c6b1e588c6fa3ddf \\\n --hash=sha256:f08aaa1c2ae092b3e662125ad19860046c63d7451d41be133ddd6594920e295e \\\n --hash=sha256:f703d7926c36eebdd56fc08aabefcf32a8b7292a9dd4468e56b0ab61bf6214bd\n- # via keras-nightly\n+ # via keras\n packaging==23.2 \\\n --hash=sha256:048fb0e9405036518eaaf48a55953c750c11e1a1b68e0dd1a9d62ed0c092cfc5 \\\n --hash=sha256:8c491190033a9af7e1d931d0b5dacc2ef47509b34dd0de67ed209b5203fc88c7\n # via\n # -r ci/official/requirements_updater/requirements.in\n # auditwheel\n- # keras-nightly\n- # tb-nightly\n+ # keras\n+ # tensorboard\n+pillow==12.1.0 \\\n+ --hash=sha256:00162e9ca6d22b7c3ee8e61faa3c3253cd19b6a37f126cad04f2f88b306f557d \\\n+ --hash=sha256:079af2fb0c599c2ec144ba2c02766d1b55498e373b3ac64687e43849fbbef5bc \\\n+ --hash=sha256:0b022eaaf709541b391ee069f0022ee5b36c709df71986e3f7be312e46f42c84 \\\n+ --hash=sha256:0c27407a2d1b96774cbc4a7594129cc027339fd800cd081e44497722ea1179de \\\n+ --hash=sha256:0ddedfaa8b5f0b4ffbc2fa87b556dc59f6bb4ecb14a53b33f9189713ae8053c0 \\\n+ --hash=sha256:0deedf2ea233722476b3a81e8cdfbad786f7adbed5d848469fa59fe52396e4ef \\\n+ --hash=sha256:0ed07dca4a8464bada6139ab38f5382f83e5f111698caf3191cb8dbf27d908b4 \\\n+ --hash=sha256:0fde7ec5538ab5095cc02df38ee99b0443ff0e1c847a045554cf5f9af1f4aa82 \\\n+ --hash=sha256:15c794d74303828eaa957ff8070846d0efe8c630901a1c753fdc63850e19ecd9 \\\n+ --hash=sha256:1a949604f73eb07a8adab38c4fe50791f9919344398bdc8ac6b307f755fc7030 \\\n+ --hash=sha256:1f345e7bc9d7f368887c712aa5054558bad44d2a301ddf9248599f4161abc7c0 \\\n+ --hash=sha256:1fcc52d86ce7a34fd17cb04e87cfdb164648a3662a6f20565910a99653d66c18 \\\n+ --hash=sha256:21e686a21078b0f9cb8c8a961d99e6a4ddb88e0fc5ea6e130172ddddc2e5221a \\\n+ --hash=sha256:2415373395a831f53933c23ce051021e79c8cd7979822d8cc478547a3f4da8ef \\\n+ --hash=sha256:277518bf4fe74aa91489e1b20577473b19ee70fb97c374aa50830b279f25841b \\\n+ --hash=sha256:27b9baecb428899db6c0de572d6d305cfaf38ca1596b5c0542a5182e3e74e8c6 \\\n+ --hash=sha256:29a4cef9cb672363926f0470afc516dbf7305a14d8c54f7abbb5c199cd8f8179 \\\n+ --hash=sha256:3413c2ae377550f5487991d444428f1a8ae92784aac79caa8b1e3b89b175f77e \\\n+ --hash=sha256:351889afef0f485b84078ea40fe33727a0492b9af3904661b0abbafee0355b72 \\\n+ --hash=sha256:3ffaa2f0659e2f740473bcf03c702c39a8d4b2b7ffc629052028764324842c64 \\\n+ --hash=sha256:40a8e3b9e8773876d6e30daed22f016509e3987bab61b3b7fe309d7019a87451 \\\n+ --hash=sha256:414b9a78e14ffeb98128863314e62c3f24b8a86081066625700b7985b3f529bd \\\n+ --hash=sha256:43aca0a55ce1eefc0aefa6253661cb54571857b1a7b2964bd8a1e3ef4b729924 \\\n+ --hash=sha256:43b4899cfd091a9693a1278c4982f3e50f7fb7cff5153b05174b4afc9593b616 \\\n+ --hash=sha256:461f9dfdafa394c59cd6d818bdfdbab4028b83b02caadaff0ffd433faf4c9a7a \\\n+ --hash=sha256:4f9f6a650743f0ddee5593ac9e954ba1bdbc5e150bc066586d4f26127853ab94 \\\n+ --hash=sha256:53d8b764726d3af1a138dd353116f774e3862ec7e3794e0c8781e30db0f35dfc \\\n+ --hash=sha256:565c986f4b45c020f5421a4cea13ef294dde9509a8577f29b2fc5edc7587fff8 \\\n+ --hash=sha256:5c5ae0a06e9ea030ab786b0251b32c7e4ce10e58d983c0d5c56029455180b5b9 \\\n+ --hash=sha256:5cb7bc1966d031aec37ddb9dcf15c2da5b2e9f7cc3ca7c54473a20a927e1eb91 \\\n+ --hash=sha256:5da841d81b1a05ef940a8567da92decaa15bc4d7dedb540a8c219ad83d91808a \\\n+ --hash=sha256:5fee4c04aad8932da9f8f710af2c1a15a83582cfb884152a9caa79d4efcdbf9c \\\n+ --hash=sha256:609e89d9f90b581c8d16358c9087df76024cf058fa693dd3e1e1620823f39670 \\\n+ --hash=sha256:6258f3260986990ba2fa8a874f8b6e808cf5abb51a94015ca3dc3c68aa4f30ea \\\n+ --hash=sha256:64efdf00c09e31efd754448a383ea241f55a994fd079866b92d2bbff598aad91 \\\n+ --hash=sha256:65b80c1ee7e14a87d6a068dd3b0aea268ffcabfe0498d38661b00c5b4b22e74c \\\n+ --hash=sha256:6741e6f3074a35e47c77b23a4e4f2d90db3ed905cb1c5e6e0d49bff2045632bc \\\n+ --hash=sha256:681088909d7e8fa9e31b9799aaa59ba5234c58e5e4f1951b4c4d1082a2e980e0 \\\n+ --hash=sha256:6b7a9d1db5dad90e2991645874f708e87d9a3c370c243c2d7684d28f7e133e6b \\\n+ --hash=sha256:7315f9137087c4e0ee73a761b163fc9aa3b19f5f606a7fc08d83fd3e4379af65 \\\n+ --hash=sha256:742aea052cf5ab5034a53c3846165bc3ce88d7c38e954120db0ab867ca242661 \\\n+ --hash=sha256:75af0b4c229ac519b155028fa1be632d812a519abba9b46b20e50c6caa184f19 \\\n+ --hash=sha256:7b5dd7cbae20285cdb597b10eb5a2c13aa9de6cde9bb64a3c1317427b1db1ae1 \\\n+ --hash=sha256:7d6daa89a00b58c37cb1747ec9fb7ac3bc5ffd5949f5888657dfddde6d1312e0 \\\n+ --hash=sha256:800429ac32c9b72909c671aaf17ecd13110f823ddb7db4dfef412a5587c2c24e \\\n+ --hash=sha256:806f3987ffe10e867bab0ddad45df1148a2b98221798457fa097ad85d6e8bc75 \\\n+ --hash=sha256:808b99604f7873c800c4840f55ff389936ef1948e4e87645eaf3fccbc8477ac4 \\\n+ --hash=sha256:80941e6d573197a0c28f394753de529bb436b1ca990ed6e765cf42426abc39f8 \\\n+ --hash=sha256:84cabc7095dd535ca934d57e9ce2a72ffd216e435a84acb06b2277b1de2689bd \\\n+ --hash=sha256:8637e29d13f478bc4f153d8daa9ffb16455f0a6cb287da1b432fdad2bfbd66c7 \\\n+ --hash=sha256:896866d2d436563fa2a43a9d72f417874f16b5545955c54a64941e87c1376c61 \\\n+ --hash=sha256:8e178e3e99d3c0ea8fc64b88447f7cac8ccf058af422a6cedc690d0eadd98c51 \\\n+ --hash=sha256:907bfa8a9cb790748a9aa4513e37c88c59660da3bcfffbd24a7d9e6abf224551 \\\n+ --hash=sha256:9212d6b86917a2300669511ed094a9406888362e085f2431a7da985a6b124f45 \\\n+ --hash=sha256:92a7fe4225365c5e3a8e598982269c6d6698d3e783b3b1ae979e7819f9cd55c1 \\\n+ --hash=sha256:935b9d1aed48fcfb3f838caac506f38e29621b44ccc4f8a64d575cb1b2a88644 \\\n+ --hash=sha256:97e9993d5ed946aba26baf9c1e8cf18adbab584b99f452ee72f7ee8acb882796 \\\n+ --hash=sha256:983976c2ab753166dc66d36af6e8ec15bb511e4a25856e2227e5f7e00a160587 \\\n+ --hash=sha256:9f5fefaca968e700ad1a4a9de98bf0869a94e397fe3524c4c9450c1445252304 \\\n+ --hash=sha256:a332ac4ccb84b6dde65dbace8431f3af08874bf9770719d32a635c4ef411b18b \\\n+ --hash=sha256:a40905599d8079e09f25027423aed94f2823adaf2868940de991e53a449e14a8 \\\n+ --hash=sha256:a6dfc2af5b082b635af6e08e0d1f9f1c4e04d17d4e2ca0ef96131e85eda6eb17 \\\n+ --hash=sha256:a786bf667724d84aa29b5db1c61b7bfdde380202aaca12c3461afd6b71743171 \\\n+ --hash=sha256:a83e0850cb8f5ac975291ebfc4170ba481f41a28065277f7f735c202cd8e0af3 \\\n+ --hash=sha256:aa0c9cc0b82b14766a99fbe6084409972266e82f459821cd26997a488a7261a7 \\\n+ --hash=sha256:b17fbdbe01c196e7e159aacb889e091f28e61020a8abeac07b68079b6e626988 \\\n+ --hash=sha256:b63e13dd27da389ed9475b3d28510f0f954bca0041e8e551b2a4eb1eab56a39a \\\n+ --hash=sha256:b6e53e82ec2db0717eabb276aa56cf4e500c9a7cec2c2e189b55c24f65a3e8c0 \\\n+ --hash=sha256:bb0984b30e973f7e2884362b7d23d0a348c7143ee559f38ef3eaab640144204c \\\n+ --hash=sha256:bc11908616c8a283cf7d664f77411a5ed2a02009b0097ff8abbba5e79128ccf2 \\\n+ --hash=sha256:bdec5e43377761c5dbca620efb69a77f6855c5a379e32ac5b158f54c84212b14 \\\n+ --hash=sha256:bef9768cab184e7ae6e559c032e95ba8d07b3023c289f79a2bd36e8bf85605a5 \\\n+ --hash=sha256:c990547452ee2800d8506c4150280757f88532f3de2a58e3022e9b179107862a \\\n+ --hash=sha256:ca94b6aac0d7af2a10ba08c0f888b3d5114439b6b3ef39968378723622fed377 \\\n+ --hash=sha256:cad302dc10fac357d3467a74a9561c90609768a6f73a1923b0fd851b6486f8b0 \\\n+ --hash=sha256:d0a7735df32ccbcc98b98a1ac785cc4b19b580be1bdf0aeb5c03223220ea09d5 \\\n+ --hash=sha256:d70347c8a5b7ccd803ec0c85c8709f036e6348f1e6a5bf048ecd9c64d3550b8b \\\n+ --hash=sha256:d70534cea9e7966169ad29a903b99fc507e932069a881d0965a1a84bb57f6c6d \\\n+ --hash=sha256:db44d5c160a90df2d24a24760bbd37607d53da0b34fb546c4c232af7192298ac \\\n+ --hash=sha256:e115c15e3bc727b1ca3e641a909f77f8ca72a64fff150f666fcc85e57701c26c \\\n+ --hash=sha256:e2479c7f02f9d505682dc47df8c0ea1fc5e264c4d1629a5d63fe3e2334b89554 \\\n+ --hash=sha256:e5dcbe95016e88437ecf33544ba5db21ef1b8dd6e1b434a2cb2a3d605299e643 \\\n+ --hash=sha256:e6bdb408f7c9dd2a5ff2b14a3b0bb6d4deb29fb9961e6eb3ae2031ae9a5cec13 \\\n+ --hash=sha256:e75d3dba8fc1ddfec0cd752108f93b83b4f8d6ab40e524a95d35f016b9683b09 \\\n+ --hash=sha256:efdc140e7b63b8f739d09a99033aa430accce485ff78e6d311973a67b6bf3208 \\\n+ --hash=sha256:f10c98f49227ed8383d28174ee95155a675c4ed7f85e2e573b04414f7e371bda \\\n+ --hash=sha256:f188028b5af6b8fb2e9a76ac0f841a575bd1bd396e46ef0840d9b88a48fdbcea \\\n+ --hash=sha256:f188d580bd870cda1e15183790d1cc2fa78f666e76077d103edf048eed9c356e \\\n+ --hash=sha256:f45bd71d1fa5e5749587613037b172e0b3b23159d1c00ef2fc920da6f470e6f0 \\\n+ --hash=sha256:f61333d817698bdcdd0f9d7793e365ac3d2a21c1f1eb02b32ad6aefb8d8ea831 \\\n+ --hash=sha256:fb125d860738a09d363a88daa0f59c4533529a90e564785e20fe875b200b6dbd\n+ # via tensorboard\n portpicker==1.6.0 \\\n --hash=sha256:b2787a41404cf7edbe29b07b9e0ed863b09f2665dcc01c1eb0c2261c1e7d0755 \\\n --hash=sha256:bd507fd6f96f65ee02781f2e674e9dc6c99bbfa6e3c39992e3916204c9d431fa\n@@ -634,7 +727,7 @@ protobuf==6.31.1 \\\n --hash=sha256:d8cac4c982f0b957a4dc73a80e2ea24fab08e679c0de9deb835f4a12d69aca9a\n # via\n # -r ci/official/requirements_updater/requirements.in\n- # tb-nightly\n+ # tensorboard\n psutil==7.0.0 \\\n --hash=sha256:101d71dc322e3cffd7cea0650b09b3d08b8e7c4109dd6809fe452dfd00e58b25 \\\n --hash=sha256:1e744154a6580bc968a0195fd25e80432d3afec619daf145b9e5ba16cc1d688e \\\n@@ -662,7 +755,7 @@ requests==2.32.4 \\\n rich==14.0.0 \\\n --hash=sha256:1c9491e1951aac09caffd42f448ee3d04e58923ffe14993f6e83068dc395d7e0 \\\n --hash=sha256:82f1bc23a6a21ebca4ae0c45af9bdbc492ed20231dcb63f297d6d1021a9d5725\n- # via keras-nightly\n+ # via keras\n scipy==1.14.1 \\\n --hash=sha256:0c2f95de3b04e26f5f3ad5bb05e74ba7f68b837133a4492414b3afd79dfe540e \\\n --hash=sha256:1729560c906963fc8389f6aac023739ff3983e727b1a4d87696b7bf108316a79 \\\n@@ -706,19 +799,18 @@ six==1.17.0 \\\n # via\n # astunparse\n # google-pasta\n- # tb-nightly\n-tb-nightly==2.20.0a20250424 \\\n- --hash=sha256:62ad3a4ce94cba2bb59538dd481999ede10927304d6f7fa0e9a23df9d24a779e\n- # via -r ci/official/requirements_updater/requirements.in\n tblib==2.0.0 \\\n --hash=sha256:9100bfa016b047d5b980d66e7efed952fbd20bd85b56110aaf473cb97d18709a \\\n --hash=sha256:a6df30f272c08bf8be66e0775fad862005d950a6b8449b94f7c788731d70ecd7\n # via -r ci/official/requirements_updater/requirements.in\n+tensorboard==2.20.0 \\\n+ --hash=sha256:9dc9f978cb84c0723acf9a345d96c184f0293d18f166bb8d59ee098e6cfaaba6\n+ # via -r ci/official/requirements_updater/requirements.in\n tensorboard-data-server==0.7.2 \\\n --hash=sha256:7e0610d205889588983836ec05dc098e80f97b7e7bbff7e994ebb78f578d0ddb \\\n --hash=sha256:9fe5d24221b29625dbc7328b0436ca7fc1c23de4acf4d272f1180856e32f9f60 \\\n --hash=sha256:ef687163c24185ae9754ed5650eb5bc4d84ff257aabdc33f0cc6f74d8ba54530\n- # via tb-nightly\n+ # via tensorboard\n tensorflow-io-gcs-filesystem==0.37.1 ; python_version <= \"3.12\" \\\n --hash=sha256:0df00891669390078a003cedbdd3b8e645c718b111917535fa1d7725e95cdb95 \\\n --hash=sha256:249c12b830165841411ba71e08215d0e94277a49c551e6dd5d72aab54fe5491b \\\n@@ -755,10 +847,10 @@ urllib3==2.6.3 \\\n werkzeug==3.1.5 \\\n --hash=sha256:5111e36e91086ece91f93268bb39b4a35c1e6f1feac762c9c822ded0a4e322dc \\\n --hash=sha256:6a548b0e88955dd07ccb25539d7d0cc97417ee9e179677d22c7041c8f078ce67\n- # via tb-nightly\n-wheel==0.46.2 \\\n- --hash=sha256:33ae60725d69eaa249bc1982e739943c23b34b58d51f1cb6253453773aca6e65 \\\n- --hash=sha256:3d79e48fde9847618a5a181f3cc35764c349c752e2fe911e65fa17faab9809b0\n+ # via tensorboard\n+wheel==0.41.3 \\\n+ --hash=sha256:488609bc63a29322326e05560731bf7bfea8e48ad646e1f5e40d366607de0942 \\\n+ --hash=sha256:4d4987ce51a49370ea65c0bfd2234e8ce80a12780820d9dc462597a6e60d0841\n # via\n # -r ci/official/requirements_updater/requirements.in\n # astunparse\n@@ -940,4 +1032,4 @@ setuptools==78.1.1 \\\n --hash=sha256:fcc17fd9cd898242f6b4adfaca46137a9edef687f43e6f78469692a5e70d851d\n # via\n # -r ci/official/requirements_updater/requirements.in\n- # tb-nightly\n+ # tensorboard" }, { "filename": "requirements_lock_3_11.txt", "status": "modified", "additions": 119, "deletions": 27, "changes": 146, "patch": "@@ -8,8 +8,8 @@ absl-py==2.2.2 \\\n --hash=sha256:bf25b2c2eed013ca456918c453d687eab4e8309fba81ee2f4c1a6aa2494175eb \\\n --hash=sha256:e5797bc6abe45f64fd95dc06394ca3f2bedf3b5d895e9da691c9ee3397d70092\n # via\n- # keras-nightly\n- # tb-nightly\n+ # keras\n+ # tensorboard\n astor==0.7.1 \\\n --hash=sha256:95c30d87a6c2cf89aa628b87398466840f0ad8652f88eb173125a6df8533fb8d \\\n --hash=sha256:fb503b9e2fdd05609fbf557b916b4a7824171203701660f0c55bbf5a7a68713e\n@@ -191,7 +191,7 @@ grpcio==1.71.0 \\\n --hash=sha256:f9c30c464cb2ddfbc2ddf9400287701270fdc0f14be5f08a1e3939f1e749b455\n # via\n # -r ci/official/requirements_updater/requirements.in\n- # tb-nightly\n+ # tensorboard\n h5py==3.13.0 \\\n --hash=sha256:10894c55d46df502d82a7a4ed38f9c3fdbcb93efb42e25d275193e093071fade \\\n --hash=sha256:1870e46518720023da85d0895a1960ff2ce398c5671eac3b1a41ec696b7105c3 \\\n@@ -221,17 +221,17 @@ h5py==3.13.0 \\\n --hash=sha256:fb267ce4b83f9c42560e9ff4d30f60f7ae492eacf9c7ede849edf8c1b860e16b\n # via\n # -r ci/official/requirements_updater/requirements.in\n- # keras-nightly\n+ # keras\n idna==3.10 \\\n --hash=sha256:12f65c9b470abda6dc35cf8e63cc574b1c52b11df2c86030af0ac09b01b13ea9 \\\n --hash=sha256:946d195a0d259cbba61165e88e65941f16e9b36ea6ddb97f00452bae8b1287d3\n # via requests\n jax==0.4.7 \\\n --hash=sha256:5e7002d74db25f97c99b979d4ba1233b1ef26e1597e5fc468ad11d1c8a9dc4f8\n # via -r ci/official/requirements_updater/requirements.in\n-keras-nightly==3.12.0.dev2025100703 \\\n- --hash=sha256:6b9dfb3814d707abf5555f56268f072daec13f2540da3aeeb7531a819ebb4567 \\\n- --hash=sha256:e29434e49bac3360f86af6e1548d94b0a2fda4e793685bc43b49867132ab16e5\n+keras==3.12.1 \\\n+ --hash=sha256:3cb760b3fec105db4d893dd717daafdd0e35457a8201502c1ba8bedfaf334a71 \\\n+ --hash=sha256:c340f8a25362398b20500c64e290f6ee280c6aeec51e1044eb8d759b32dc272a\n # via -r ci/official/requirements_updater/requirements.in\n libclang==18.1.1 \\\n --hash=sha256:0b2e143f0fac830156feb56f9231ff8338c20aecfe72b4ffe96f19e5a1dbb69a \\\n@@ -251,7 +251,7 @@ lit==17.0.6 \\\n markdown==3.8 \\\n --hash=sha256:794a929b79c5af141ef5ab0f2f642d0f7b1872981250230e72682346f7cc90dc \\\n --hash=sha256:7df81e63f0df5c4b24b7d156eb81e4690595239b7d70937d0409f1b0de319c6f\n- # via tb-nightly\n+ # via tensorboard\n markdown-it-py==3.0.0 \\\n --hash=sha256:355216845c60bd96232cd8d8c40e8f9765cc86f46880e43a8fd22dc1a1a8cab1 \\\n --hash=sha256:e3f60a94fa066dc52ec76661e37c851cb232d92f9886b15cb560aaada2df8feb\n@@ -351,11 +351,11 @@ ml-dtypes==0.5.1 \\\n # via\n # -r ci/official/requirements_updater/requirements.in\n # jax\n- # keras-nightly\n+ # keras\n namex==0.0.8 \\\n --hash=sha256:32a50f6c565c0bb10aa76298c959507abdc0e850efe085dc38f3440fcb3aa90b \\\n --hash=sha256:7ddb6c2bb0e753a311b7590f84f6da659dd0c05e65cb89d519d54c0a250c0487\n- # via keras-nightly\n+ # via keras\n numpy==2.1.3 \\\n --hash=sha256:016d0f6f5e77b0f0d45d77387ffa4bb89816b57c835580c3ce8e099ef830befe \\\n --hash=sha256:02135ade8b8a84011cbb67dc44e07c58f28575cf9ecf8ab304e51c05528c19f0 \\\n@@ -416,11 +416,11 @@ numpy==2.1.3 \\\n # -r ci/official/requirements_updater/requirements.in\n # h5py\n # jax\n- # keras-nightly\n+ # keras\n # ml-dtypes\n # opt-einsum\n # scipy\n- # tb-nightly\n+ # tensorboard\n nvidia-cublas-cu12==12.5.3.2 \\\n --hash=sha256:4960f3dc5f39699acadf76fa6d94b10a2a00f2956c2c442efa299fb22b0748f3 \\\n --hash=sha256:7d0191251180de606023d396b94d66f66470a0ae96d1dbb906c7656ea0f71eda \\\n@@ -609,15 +609,108 @@ optree==0.16.0 \\\n --hash=sha256:eeccc740b72b58efa9795ab831a678a42341def48b9e5956c6b1e588c6fa3ddf \\\n --hash=sha256:f08aaa1c2ae092b3e662125ad19860046c63d7451d41be133ddd6594920e295e \\\n --hash=sha256:f703d7926c36eebdd56fc08aabefcf32a8b7292a9dd4468e56b0ab61bf6214bd\n- # via keras-nightly\n+ # via keras\n packaging==23.2 \\\n --hash=sha256:048fb0e9405036518eaaf48a55953c750c11e1a1b68e0dd1a9d62ed0c092cfc5 \\\n --hash=sha256:8c491190033a9af7e1d931d0b5dacc2ef47509b34dd0de67ed209b5203fc88c7\n # via\n # -r ci/official/requirements_updater/requirements.in\n # auditwheel\n- # keras-nightly\n- # tb-nightly\n+ # keras\n+ # tensorboard\n+pillow==12.1.0 \\\n+ --hash=sha256:00162e9ca6d22b7c3ee8e61faa3c3253cd19b6a37f126cad04f2f88b306f557d \\\n+ --hash=sha256:079af2fb0c599c2ec144ba2c02766d1b55498e373b3ac64687e43849fbbef5bc \\\n+ --hash=sha256:0b022eaaf709541b391ee069f0022ee5b36c709df71986e3f7be312e46f42c84 \\\n+ --hash=sha256:0c27407a2d1b96774cbc4a7594129cc027339fd800cd081e44497722ea1179de \\\n+ --hash=sha256:0ddedfaa8b5f0b4ffbc2fa87b556dc59f6bb4ecb14a53b33f9189713ae8053c0 \\\n+ --hash=sha256:0deedf2ea233722476b3a81e8cdfbad786f7adbed5d848469fa59fe52396e4ef \\\n+ --hash=sha256:0ed07dca4a8464bada6139ab38f5382f83e5f111698caf3191cb8dbf27d908b4 \\\n+ --hash=sha256:0fde7ec5538ab5095cc02df38ee99b0443ff0e1c847a045554cf5f9af1f4aa82 \\\n+ --hash=sha256:15c794d74303828eaa957ff8070846d0efe8c630901a1c753fdc63850e19ecd9 \\\n+ --hash=sha256:1a949604f73eb07a8adab38c4fe50791f9919344398bdc8ac6b307f755fc7030 \\\n+ --hash=sha256:1f345e7bc9d7f368887c712aa5054558bad44d2a301ddf9248599f4161abc7c0 \\\n+ --hash=sha256:1fcc52d86ce7a34fd17cb04e87cfdb164648a3662a6f20565910a99653d66c18 \\\n+ --hash=sha256:21e686a21078b0f9cb8c8a961d99e6a4ddb88e0fc5ea6e130172ddddc2e5221a \\\n+ --hash=sha256:2415373395a831f53933c23ce051021e79c8cd7979822d8cc478547a3f4da8ef \\\n+ --hash=sha256:277518bf4fe74aa91489e1b20577473b19ee70fb97c374aa50830b279f25841b \\\n+ --hash=sha256:27b9baecb428899db6c0de572d6d305cfaf38ca1596b5c0542a5182e3e74e8c6 \\\n+ --hash=sha256:29a4cef9cb672363926f0470afc516dbf7305a14d8c54f7abbb5c199cd8f8179 \\\n+ --hash=sha256:3413c2ae377550f5487991d444428f1a8ae92784aac79caa8b1e3b89b175f77e \\\n+ --hash=sha256:351889afef0f485b84078ea40fe33727a0492b9af3904661b0abbafee0355b72 \\\n+ --hash=sha256:3ffaa2f0659e2f740473bcf03c702c39a8d4b2b7ffc629052028764324842c64 \\\n+ --hash=sha256:40a8e3b9e8773876d6e30daed22f016509e3987bab61b3b7fe309d7019a87451 \\\n+ --hash=sha256:414b9a78e14ffeb98128863314e62c3f24b8a86081066625700b7985b3f529bd \\\n+ --hash=sha256:43aca0a55ce1eefc0aefa6253661cb54571857b1a7b2964bd8a1e3ef4b729924 \\\n+ --hash=sha256:43b4899cfd091a9693a1278c4982f3e50f7fb7cff5153b05174b4afc9593b616 \\\n+ --hash=sha256:461f9dfdafa394c59cd6d818bdfdbab4028b83b02caadaff0ffd433faf4c9a7a \\\n+ --hash=sha256:4f9f6a650743f0ddee5593ac9e954ba1bdbc5e150bc066586d4f26127853ab94 \\\n+ --hash=sha256:53d8b764726d3af1a138dd353116f774e3862ec7e3794e0c8781e30db0f35dfc \\\n+ --hash=sha256:565c986f4b45c020f5421a4cea13ef294dde9509a8577f29b2fc5edc7587fff8 \\\n+ --hash=sha256:5c5ae0a06e9ea030ab786b0251b32c7e4ce10e58d983c0d5c56029455180b5b9 \\\n+ --hash=sha256:5cb7bc1966d031aec37ddb9dcf15c2da5b2e9f7cc3ca7c54473a20a927e1eb91 \\\n+ --hash=sha256:5da841d81b1a05ef940a8567da92decaa15bc4d7dedb540a8c219ad83d91808a \\\n+ --hash=sha256:5fee4c04aad8932da9f8f710af2c1a15a83582cfb884152a9caa79d4efcdbf9c \\\n+ --hash=sha256:609e89d9f90b581c8d16358c9087df76024cf058fa693dd3e1e1620823f39670 \\\n+ --hash=sha256:6258f3260986990ba2fa8a874f8b6e808cf5abb51a94015ca3dc3c68aa4f30ea \\\n+ --hash=sha256:64efdf00c09e31efd754448a383ea241f55a994fd079866b92d2bbff598aad91 \\\n+ --hash=sha256:65b80c1ee7e14a87d6a068dd3b0aea268ffcabfe0498d38661b00c5b4b22e74c \\\n+ --hash=sha256:6741e6f3074a35e47c77b23a4e4f2d90db3ed905cb1c5e6e0d49bff2045632bc \\\n+ --hash=sha256:681088909d7e8fa9e31b9799aaa59ba5234c58e5e4f1951b4c4d1082a2e980e0 \\\n+ --hash=sha256:6b7a9d1db5dad90e2991645874f708e87d9a3c370c243c2d7684d28f7e133e6b \\\n+ --hash=sha256:7315f9137087c4e0ee73a761b163fc9aa3b19f5f606a7fc08d83fd3e4379af65 \\\n+ --hash=sha256:742aea052cf5ab5034a53c3846165bc3ce88d7c38e954120db0ab867ca242661 \\\n+ --hash=sha256:75af0b4c229ac519b155028fa1be632d812a519abba9b46b20e50c6caa184f19 \\\n+ --hash=sha256:7b5dd7cbae20285cdb597b10eb5a2c13aa9de6cde9bb64a3c1317427b1db1ae1 \\\n+ --hash=sha256:7d6daa89a00b58c37cb1747ec9fb7ac3bc5ffd5949f5888657dfddde6d1312e0 \\\n+ --hash=sha256:800429ac32c9b72909c671aaf17ecd13110f823ddb7db4dfef412a5587c2c24e \\\n+ --hash=sha256:806f3987ffe10e867bab0ddad45df1148a2b98221798457fa097ad85d6e8bc75 \\\n+ --hash=sha256:808b99604f7873c800c4840f55ff389936ef1948e4e87645eaf3fccbc8477ac4 \\\n+ --hash=sha256:80941e6d573197a0c28f394753de529bb436b1ca990ed6e765cf42426abc39f8 \\\n+ --hash=sha256:84cabc7095dd535ca934d57e9ce2a72ffd216e435a84acb06b2277b1de2689bd \\\n+ --hash=sha256:8637e29d13f478bc4f153d8daa9ffb16455f0a6cb287da1b432fdad2bfbd66c7 \\\n+ --hash=sha256:896866d2d436563fa2a43a9d72f417874f16b5545955c54a64941e87c1376c61 \\\n+ --hash=sha256:8e178e3e99d3c0ea8fc64b88447f7cac8ccf058af422a6cedc690d0eadd98c51 \\\n+ --hash=sha256:907bfa8a9cb790748a9aa4513e37c88c59660da3bcfffbd24a7d9e6abf224551 \\\n+ --hash=sha256:9212d6b86917a2300669511ed094a9406888362e085f2431a7da985a6b124f45 \\\n+ --hash=sha256:92a7fe4225365c5e3a8e598982269c6d6698d3e783b3b1ae979e7819f9cd55c1 \\\n+ --hash=sha256:935b9d1aed48fcfb3f838caac506f38e29621b44ccc4f8a64d575cb1b2a88644 \\\n+ --hash=sha256:97e9993d5ed946aba26baf9c1e8cf18adbab584b99f452ee72f7ee8acb882796 \\\n+ --hash=sha256:983976c2ab753166dc66d36af6e8ec15bb511e4a25856e2227e5f7e00a160587 \\\n+ --hash=sha256:9f5fefaca968e700ad1a4a9de98bf0869a94e397fe3524c4c9450c1445252304 \\\n+ --hash=sha256:a332ac4ccb84b6dde65dbace8431f3af08874bf9770719d32a635c4ef411b18b \\\n+ --hash=sha256:a40905599d8079e09f25027423aed94f2823adaf2868940de991e53a449e14a8 \\\n+ --hash=sha256:a6dfc2af5b082b635af6e08e0d1f9f1c4e04d17d4e2ca0ef96131e85eda6eb17 \\\n+ --hash=sha256:a786bf667724d84aa29b5db1c61b7bfdde380202aaca12c3461afd6b71743171 \\\n+ --hash=sha256:a83e0850cb8f5ac975291ebfc4170ba481f41a28065277f7f735c202cd8e0af3 \\\n+ --hash=sha256:aa0c9cc0b82b14766a99fbe6084409972266e82f459821cd26997a488a7261a7 \\\n+ --hash=sha256:b17fbdbe01c196e7e159aacb889e091f28e61020a8abeac07b68079b6e626988 \\\n+ --hash=sha256:b63e13dd27da389ed9475b3d28510f0f954bca0041e8e551b2a4eb1eab56a39a \\\n+ --hash=sha256:b6e53e82ec2db0717eabb276aa56cf4e500c9a7cec2c2e189b55c24f65a3e8c0 \\\n+ --hash=sha256:bb0984b30e973f7e2884362b7d23d0a348c7143ee559f38ef3eaab640144204c \\\n+ --hash=sha256:bc11908616c8a283cf7d664f77411a5ed2a02009b0097ff8abbba5e79128ccf2 \\\n+ --hash=sha256:bdec5e43377761c5dbca620efb69a77f6855c5a379e32ac5b158f54c84212b14 \\\n+ --hash=sha256:bef9768cab184e7ae6e559c032e95ba8d07b3023c289f79a2bd36e8bf85605a5 \\\n+ --hash=sha256:c990547452ee2800d8506c4150280757f88532f3de2a58e3022e9b179107862a \\\n+ --hash=sha256:ca94b6aac0d7af2a10ba08c0f888b3d5114439b6b3ef39968378723622fed377 \\\n+ --hash=sha256:cad302dc10fac357d3467a74a9561c90609768a6f73a1923b0fd851b6486f8b0 \\\n+ --hash=sha256:d0a7735df32ccbcc98b98a1ac785cc4b19b580be1bdf0aeb5c03223220ea09d5 \\\n+ --hash=sha256:d70347c8a5b7ccd803ec0c85c8709f036e6348f1e6a5bf048ecd9c64d3550b8b \\\n+ --hash=sha256:d70534cea9e7966169ad29a903b99fc507e932069a881d0965a1a84bb57f6c6d \\\n+ --hash=sha256:db44d5c160a90df2d24a24760bbd37607d53da0b34fb546c4c232af7192298ac \\\n+ --hash=sha256:e115c15e3bc727b1ca3e641a909f77f8ca72a64fff150f666fcc85e57701c26c \\\n+ --hash=sha256:e2479c7f02f9d505682dc47df8c0ea1fc5e264c4d1629a5d63fe3e2334b89554 \\\n+ --hash=sha256:e5dcbe95016e88437ecf33544ba5db21ef1b8dd6e1b434a2cb2a3d605299e643 \\\n+ --hash=sha256:e6bdb408f7c9dd2a5ff2b14a3b0bb6d4deb29fb9961e6eb3ae2031ae9a5cec13 \\\n+ --hash=sha256:e75d3dba8fc1ddfec0cd752108f93b83b4f8d6ab40e524a95d35f016b9683b09 \\\n+ --hash=sha256:efdc140e7b63b8f739d09a99033aa430accce485ff78e6d311973a67b6bf3208 \\\n+ --hash=sha256:f10c98f49227ed8383d28174ee95155a675c4ed7f85e2e573b04414f7e371bda \\\n+ --hash=sha256:f188028b5af6b8fb2e9a76ac0f841a575bd1bd396e46ef0840d9b88a48fdbcea \\\n+ --hash=sha256:f188d580bd870cda1e15183790d1cc2fa78f666e76077d103edf048eed9c356e \\\n+ --hash=sha256:f45bd71d1fa5e5749587613037b172e0b3b23159d1c00ef2fc920da6f470e6f0 \\\n+ --hash=sha256:f61333d817698bdcdd0f9d7793e365ac3d2a21c1f1eb02b32ad6aefb8d8ea831 \\\n+ --hash=sha256:fb125d860738a09d363a88daa0f59c4533529a90e564785e20fe875b200b6dbd\n+ # via tensorboard\n portpicker==1.6.0 \\\n --hash=sha256:b2787a41404cf7edbe29b07b9e0ed863b09f2665dcc01c1eb0c2261c1e7d0755 \\\n --hash=sha256:bd507fd6f96f65ee02781f2e674e9dc6c99bbfa6e3c39992e3916204c9d431fa\n@@ -634,7 +727,7 @@ protobuf==6.31.1 \\\n --hash=sha256:d8cac4c982f0b957a4dc73a80e2ea24fab08e679c0de9deb835f4a12d69aca9a\n # via\n # -r ci/official/requirements_updater/requirements.in\n- # tb-nightly\n+ # tensorboard\n psutil==7.0.0 \\\n --hash=sha256:101d71dc322e3cffd7cea0650b09b3d08b8e7c4109dd6809fe452dfd00e58b25 \\\n --hash=sha256:1e744154a6580bc968a0195fd25e80432d3afec619daf145b9e5ba16cc1d688e \\\n@@ -662,7 +755,7 @@ requests==2.32.4 \\\n rich==14.0.0 \\\n --hash=sha256:1c9491e1951aac09caffd42f448ee3d04e58923ffe14993f6e83068dc395d7e0 \\\n --hash=sha256:82f1bc23a6a21ebca4ae0c45af9bdbc492ed20231dcb63f297d6d1021a9d5725\n- # via keras-nightly\n+ # via keras\n scipy==1.14.1 \\\n --hash=sha256:0c2f95de3b04e26f5f3ad5bb05e74ba7f68b837133a4492414b3afd79dfe540e \\\n --hash=sha256:1729560c906963fc8389f6aac023739ff3983e727b1a4d87696b7bf108316a79 \\\n@@ -706,19 +799,18 @@ six==1.17.0 \\\n # via\n # astunparse\n # google-pasta\n- # tb-nightly\n-tb-nightly==2.20.0a20250419 \\\n- --hash=sha256:41ba72431b88a87ed07e284cb244c29cd5dc42b1dd5970436f4e1bec9684e0f0\n- # via -r ci/official/requirements_updater/requirements.in\n tblib==2.0.0 \\\n --hash=sha256:9100bfa016b047d5b980d66e7efed952fbd20bd85b56110aaf473cb97d18709a \\\n --hash=sha256:a6df30f272c08bf8be66e0775fad862005d950a6b8449b94f7c788731d70ecd7\n # via -r ci/official/requirements_updater/requirements.in\n+tensorboard==2.20.0 \\\n+ --hash=sha256:9dc9f978cb84c0723acf9a345d96c184f0293d18f166bb8d59ee098e6cfaaba6\n+ # via -r ci/official/requirements_updater/requirements.in\n tensorboard-data-server==0.7.2 \\\n --hash=sha256:7e0610d205889588983836ec05dc098e80f97b7e7bbff7e994ebb78f578d0ddb \\\n --hash=sha256:9fe5d24221b29625dbc7328b0436ca7fc1c23de4acf4d272f1180856e32f9f60 \\\n --hash=sha256:ef687163c24185ae9754ed5650eb5bc4d84ff257aabdc33f0cc6f74d8ba54530\n- # via tb-nightly\n+ # via tensorboard\n tensorflow-io-gcs-filesystem==0.37.1 ; python_version <= \"3.12\" \\\n --hash=sha256:0df00891669390078a003cedbdd3b8e645c718b111917535fa1d7725e95cdb95 \\\n --hash=sha256:249c12b830165841411ba71e08215d0e94277a49c551e6dd5d72aab54fe5491b \\\n@@ -754,10 +846,10 @@ urllib3==2.6.3 \\\n werkzeug==3.1.5 \\\n --hash=sha256:5111e36e91086ece91f93268bb39b4a35c1e6f1feac762c9c822ded0a4e322dc \\\n --hash=sha256:6a548b0e88955dd07ccb25539d7d0cc97417ee9e179677d22c7041c8f078ce67\n- # via tb-nightly\n-wheel==0.46.2 \\\n- --hash=sha256:33ae60725d69eaa249bc1982e739943c23b34b58d51f1cb6253453773aca6e65 \\\n- --hash=sha256:3d79e48fde9847618a5a181f3cc35764c349c752e2fe911e65fa17faab9809b0\n+ # via tensorboard\n+wheel==0.41.3 \\\n+ --hash=sha256:488609bc63a29322326e05560731bf7bfea8e48ad646e1f5e40d366607de0942 \\\n+ --hash=sha256:4d4987ce51a49370ea65c0bfd2234e8ce80a12780820d9dc462597a6e60d0841\n # via\n # -r ci/official/requirements_updater/requirements.in\n # astunparse\n@@ -939,4 +1031,4 @@ setuptools==78.1.1 \\\n --hash=sha256:fcc17fd9cd898242f6b4adfaca46137a9edef687f43e6f78469692a5e70d851d\n # via\n # -r ci/official/requirements_updater/requirements.in\n- # tb-nightly\n+ # tensorboard" }, { "filename": "requirements_lock_3_12.txt", "status": "modified", "additions": 119, "deletions": 27, "changes": 146, "patch": "@@ -8,8 +8,8 @@ absl-py==2.2.2 \\\n --hash=sha256:bf25b2c2eed013ca456918c453d687eab4e8309fba81ee2f4c1a6aa2494175eb \\\n --hash=sha256:e5797bc6abe45f64fd95dc06394ca3f2bedf3b5d895e9da691c9ee3397d70092\n # via\n- # keras-nightly\n- # tb-nightly\n+ # keras\n+ # tensorboard\n astor==0.7.1 \\\n --hash=sha256:95c30d87a6c2cf89aa628b87398466840f0ad8652f88eb173125a6df8533fb8d \\\n --hash=sha256:fb503b9e2fdd05609fbf557b916b4a7824171203701660f0c55bbf5a7a68713e\n@@ -191,7 +191,7 @@ grpcio==1.71.0 \\\n --hash=sha256:f9c30c464cb2ddfbc2ddf9400287701270fdc0f14be5f08a1e3939f1e749b455\n # via\n # -r ci/official/requirements_updater/requirements.in\n- # tb-nightly\n+ # tensorboard\n h5py==3.13.0 \\\n --hash=sha256:10894c55d46df502d82a7a4ed38f9c3fdbcb93efb42e25d275193e093071fade \\\n --hash=sha256:1870e46518720023da85d0895a1960ff2ce398c5671eac3b1a41ec696b7105c3 \\\n@@ -221,17 +221,17 @@ h5py==3.13.0 \\\n --hash=sha256:fb267ce4b83f9c42560e9ff4d30f60f7ae492eacf9c7ede849edf8c1b860e16b\n # via\n # -r ci/official/requirements_updater/requirements.in\n- # keras-nightly\n+ # keras\n idna==3.10 \\\n --hash=sha256:12f65c9b470abda6dc35cf8e63cc574b1c52b11df2c86030af0ac09b01b13ea9 \\\n --hash=sha256:946d195a0d259cbba61165e88e65941f16e9b36ea6ddb97f00452bae8b1287d3\n # via requests\n jax==0.4.7 \\\n --hash=sha256:5e7002d74db25f97c99b979d4ba1233b1ef26e1597e5fc468ad11d1c8a9dc4f8\n # via -r ci/official/requirements_updater/requirements.in\n-keras-nightly==3.12.0.dev2025100703 \\\n- --hash=sha256:6b9dfb3814d707abf5555f56268f072daec13f2540da3aeeb7531a819ebb4567 \\\n- --hash=sha256:e29434e49bac3360f86af6e1548d94b0a2fda4e793685bc43b49867132ab16e5\n+keras==3.12.1 \\\n+ --hash=sha256:3cb760b3fec105db4d893dd717daafdd0e35457a8201502c1ba8bedfaf334a71 \\\n+ --hash=sha256:c340f8a25362398b20500c64e290f6ee280c6aeec51e1044eb8d759b32dc272a\n # via -r ci/official/requirements_updater/requirements.in\n libclang==18.1.1 \\\n --hash=sha256:0b2e143f0fac830156feb56f9231ff8338c20aecfe72b4ffe96f19e5a1dbb69a \\\n@@ -251,7 +251,7 @@ lit==17.0.6 \\\n markdown==3.8 \\\n --hash=sha256:794a929b79c5af141ef5ab0f2f642d0f7b1872981250230e72682346f7cc90dc \\\n --hash=sha256:7df81e63f0df5c4b24b7d156eb81e4690595239b7d70937d0409f1b0de319c6f\n- # via tb-nightly\n+ # via tensorboard\n markdown-it-py==3.0.0 \\\n --hash=sha256:355216845c60bd96232cd8d8c40e8f9765cc86f46880e43a8fd22dc1a1a8cab1 \\\n --hash=sha256:e3f60a94fa066dc52ec76661e37c851cb232d92f9886b15cb560aaada2df8feb\n@@ -351,11 +351,11 @@ ml-dtypes==0.5.1 \\\n # via\n # -r ci/official/requirements_updater/requirements.in\n # jax\n- # keras-nightly\n+ # keras\n namex==0.0.9 \\\n --hash=sha256:7bd4e4a2cc3876592111609fdf4cbe6ff19883adbe6b3b40d842fd340f77025e \\\n --hash=sha256:8adfea9da5cea5be8f4e632349b4669e30172c7859e1fd97459fdf3b17469253\n- # via keras-nightly\n+ # via keras\n numpy==2.1.3 \\\n --hash=sha256:016d0f6f5e77b0f0d45d77387ffa4bb89816b57c835580c3ce8e099ef830befe \\\n --hash=sha256:02135ade8b8a84011cbb67dc44e07c58f28575cf9ecf8ab304e51c05528c19f0 \\\n@@ -416,11 +416,11 @@ numpy==2.1.3 \\\n # -r ci/official/requirements_updater/requirements.in\n # h5py\n # jax\n- # keras-nightly\n+ # keras\n # ml-dtypes\n # opt-einsum\n # scipy\n- # tb-nightly\n+ # tensorboard\n nvidia-cublas-cu12==12.5.3.2 \\\n --hash=sha256:4960f3dc5f39699acadf76fa6d94b10a2a00f2956c2c442efa299fb22b0748f3 \\\n --hash=sha256:7d0191251180de606023d396b94d66f66470a0ae96d1dbb906c7656ea0f71eda \\\n@@ -609,15 +609,108 @@ optree==0.16.0 \\\n --hash=sha256:eeccc740b72b58efa9795ab831a678a42341def48b9e5956c6b1e588c6fa3ddf \\\n --hash=sha256:f08aaa1c2ae092b3e662125ad19860046c63d7451d41be133ddd6594920e295e \\\n --hash=sha256:f703d7926c36eebdd56fc08aabefcf32a8b7292a9dd4468e56b0ab61bf6214bd\n- # via keras-nightly\n+ # via keras\n packaging==23.2 \\\n --hash=sha256:048fb0e9405036518eaaf48a55953c750c11e1a1b68e0dd1a9d62ed0c092cfc5 \\\n --hash=sha256:8c491190033a9af7e1d931d0b5dacc2ef47509b34dd0de67ed209b5203fc88c7\n # via\n # -r ci/official/requirements_updater/requirements.in\n # auditwheel\n- # keras-nightly\n- # tb-nightly\n+ # keras\n+ # tensorboard\n+pillow==12.1.0 \\\n+ --hash=sha256:00162e9ca6d22b7c3ee8e61faa3c3253cd19b6a37f126cad04f2f88b306f557d \\\n+ --hash=sha256:079af2fb0c599c2ec144ba2c02766d1b55498e373b3ac64687e43849fbbef5bc \\\n+ --hash=sha256:0b022eaaf709541b391ee069f0022ee5b36c709df71986e3f7be312e46f42c84 \\\n+ --hash=sha256:0c27407a2d1b96774cbc4a7594129cc027339fd800cd081e44497722ea1179de \\\n+ --hash=sha256:0ddedfaa8b5f0b4ffbc2fa87b556dc59f6bb4ecb14a53b33f9189713ae8053c0 \\\n+ --hash=sha256:0deedf2ea233722476b3a81e8cdfbad786f7adbed5d848469fa59fe52396e4ef \\\n+ --hash=sha256:0ed07dca4a8464bada6139ab38f5382f83e5f111698caf3191cb8dbf27d908b4 \\\n+ --hash=sha256:0fde7ec5538ab5095cc02df38ee99b0443ff0e1c847a045554cf5f9af1f4aa82 \\\n+ --hash=sha256:15c794d74303828eaa957ff8070846d0efe8c630901a1c753fdc63850e19ecd9 \\\n+ --hash=sha256:1a949604f73eb07a8adab38c4fe50791f9919344398bdc8ac6b307f755fc7030 \\\n+ --hash=sha256:1f345e7bc9d7f368887c712aa5054558bad44d2a301ddf9248599f4161abc7c0 \\\n+ --hash=sha256:1fcc52d86ce7a34fd17cb04e87cfdb164648a3662a6f20565910a99653d66c18 \\\n+ --hash=sha256:21e686a21078b0f9cb8c8a961d99e6a4ddb88e0fc5ea6e130172ddddc2e5221a \\\n+ --hash=sha256:2415373395a831f53933c23ce051021e79c8cd7979822d8cc478547a3f4da8ef \\\n+ --hash=sha256:277518bf4fe74aa91489e1b20577473b19ee70fb97c374aa50830b279f25841b \\\n+ --hash=sha256:27b9baecb428899db6c0de572d6d305cfaf38ca1596b5c0542a5182e3e74e8c6 \\\n+ --hash=sha256:29a4cef9cb672363926f0470afc516dbf7305a14d8c54f7abbb5c199cd8f8179 \\\n+ --hash=sha256:3413c2ae377550f5487991d444428f1a8ae92784aac79caa8b1e3b89b175f77e \\\n+ --hash=sha256:351889afef0f485b84078ea40fe33727a0492b9af3904661b0abbafee0355b72 \\\n+ --hash=sha256:3ffaa2f0659e2f740473bcf03c702c39a8d4b2b7ffc629052028764324842c64 \\\n+ --hash=sha256:40a8e3b9e8773876d6e30daed22f016509e3987bab61b3b7fe309d7019a87451 \\\n+ --hash=sha256:414b9a78e14ffeb98128863314e62c3f24b8a86081066625700b7985b3f529bd \\\n+ --hash=sha256:43aca0a55ce1eefc0aefa6253661cb54571857b1a7b2964bd8a1e3ef4b729924 \\\n+ --hash=sha256:43b4899cfd091a9693a1278c4982f3e50f7fb7cff5153b05174b4afc9593b616 \\\n+ --hash=sha256:461f9dfdafa394c59cd6d818bdfdbab4028b83b02caadaff0ffd433faf4c9a7a \\\n+ --hash=sha256:4f9f6a650743f0ddee5593ac9e954ba1bdbc5e150bc066586d4f26127853ab94 \\\n+ --hash=sha256:53d8b764726d3af1a138dd353116f774e3862ec7e3794e0c8781e30db0f35dfc \\\n+ --hash=sha256:565c986f4b45c020f5421a4cea13ef294dde9509a8577f29b2fc5edc7587fff8 \\\n+ --hash=sha256:5c5ae0a06e9ea030ab786b0251b32c7e4ce10e58d983c0d5c56029455180b5b9 \\\n+ --hash=sha256:5cb7bc1966d031aec37ddb9dcf15c2da5b2e9f7cc3ca7c54473a20a927e1eb91 \\\n+ --hash=sha256:5da841d81b1a05ef940a8567da92decaa15bc4d7dedb540a8c219ad83d91808a \\\n+ --hash=sha256:5fee4c04aad8932da9f8f710af2c1a15a83582cfb884152a9caa79d4efcdbf9c \\\n+ --hash=sha256:609e89d9f90b581c8d16358c9087df76024cf058fa693dd3e1e1620823f39670 \\\n+ --hash=sha256:6258f3260986990ba2fa8a874f8b6e808cf5abb51a94015ca3dc3c68aa4f30ea \\\n+ --hash=sha256:64efdf00c09e31efd754448a383ea241f55a994fd079866b92d2bbff598aad91 \\\n+ --hash=sha256:65b80c1ee7e14a87d6a068dd3b0aea268ffcabfe0498d38661b00c5b4b22e74c \\\n+ --hash=sha256:6741e6f3074a35e47c77b23a4e4f2d90db3ed905cb1c5e6e0d49bff2045632bc \\\n+ --hash=sha256:681088909d7e8fa9e31b9799aaa59ba5234c58e5e4f1951b4c4d1082a2e980e0 \\\n+ --hash=sha256:6b7a9d1db5dad90e2991645874f708e87d9a3c370c243c2d7684d28f7e133e6b \\\n+ --hash=sha256:7315f9137087c4e0ee73a761b163fc9aa3b19f5f606a7fc08d83fd3e4379af65 \\\n+ --hash=sha256:742aea052cf5ab5034a53c3846165bc3ce88d7c38e954120db0ab867ca242661 \\\n+ --hash=sha256:75af0b4c229ac519b155028fa1be632d812a519abba9b46b20e50c6caa184f19 \\\n+ --hash=sha256:7b5dd7cbae20285cdb597b10eb5a2c13aa9de6cde9bb64a3c1317427b1db1ae1 \\\n+ --hash=sha256:7d6daa89a00b58c37cb1747ec9fb7ac3bc5ffd5949f5888657dfddde6d1312e0 \\\n+ --hash=sha256:800429ac32c9b72909c671aaf17ecd13110f823ddb7db4dfef412a5587c2c24e \\\n+ --hash=sha256:806f3987ffe10e867bab0ddad45df1148a2b98221798457fa097ad85d6e8bc75 \\\n+ --hash=sha256:808b99604f7873c800c4840f55ff389936ef1948e4e87645eaf3fccbc8477ac4 \\\n+ --hash=sha256:80941e6d573197a0c28f394753de529bb436b1ca990ed6e765cf42426abc39f8 \\\n+ --hash=sha256:84cabc7095dd535ca934d57e9ce2a72ffd216e435a84acb06b2277b1de2689bd \\\n+ --hash=sha256:8637e29d13f478bc4f153d8daa9ffb16455f0a6cb287da1b432fdad2bfbd66c7 \\\n+ --hash=sha256:896866d2d436563fa2a43a9d72f417874f16b5545955c54a64941e87c1376c61 \\\n+ --hash=sha256:8e178e3e99d3c0ea8fc64b88447f7cac8ccf058af422a6cedc690d0eadd98c51 \\\n+ --hash=sha256:907bfa8a9cb790748a9aa4513e37c88c59660da3bcfffbd24a7d9e6abf224551 \\\n+ --hash=sha256:9212d6b86917a2300669511ed094a9406888362e085f2431a7da985a6b124f45 \\\n+ --hash=sha256:92a7fe4225365c5e3a8e598982269c6d6698d3e783b3b1ae979e7819f9cd55c1 \\\n+ --hash=sha256:935b9d1aed48fcfb3f838caac506f38e29621b44ccc4f8a64d575cb1b2a88644 \\\n+ --hash=sha256:97e9993d5ed946aba26baf9c1e8cf18adbab584b99f452ee72f7ee8acb882796 \\\n+ --hash=sha256:983976c2ab753166dc66d36af6e8ec15bb511e4a25856e2227e5f7e00a160587 \\\n+ --hash=sha256:9f5fefaca968e700ad1a4a9de98bf0869a94e397fe3524c4c9450c1445252304 \\\n+ --hash=sha256:a332ac4ccb84b6dde65dbace8431f3af08874bf9770719d32a635c4ef411b18b \\\n+ --hash=sha256:a40905599d8079e09f25027423aed94f2823adaf2868940de991e53a449e14a8 \\\n+ --hash=sha256:a6dfc2af5b082b635af6e08e0d1f9f1c4e04d17d4e2ca0ef96131e85eda6eb17 \\\n+ --hash=sha256:a786bf667724d84aa29b5db1c61b7bfdde380202aaca12c3461afd6b71743171 \\\n+ --hash=sha256:a83e0850cb8f5ac975291ebfc4170ba481f41a28065277f7f735c202cd8e0af3 \\\n+ --hash=sha256:aa0c9cc0b82b14766a99fbe6084409972266e82f459821cd26997a488a7261a7 \\\n+ --hash=sha256:b17fbdbe01c196e7e159aacb889e091f28e61020a8abeac07b68079b6e626988 \\\n+ --hash=sha256:b63e13dd27da389ed9475b3d28510f0f954bca0041e8e551b2a4eb1eab56a39a \\\n+ --hash=sha256:b6e53e82ec2db0717eabb276aa56cf4e500c9a7cec2c2e189b55c24f65a3e8c0 \\\n+ --hash=sha256:bb0984b30e973f7e2884362b7d23d0a348c7143ee559f38ef3eaab640144204c \\\n+ --hash=sha256:bc11908616c8a283cf7d664f77411a5ed2a02009b0097ff8abbba5e79128ccf2 \\\n+ --hash=sha256:bdec5e43377761c5dbca620efb69a77f6855c5a379e32ac5b158f54c84212b14 \\\n+ --hash=sha256:bef9768cab184e7ae6e559c032e95ba8d07b3023c289f79a2bd36e8bf85605a5 \\\n+ --hash=sha256:c990547452ee2800d8506c4150280757f88532f3de2a58e3022e9b179107862a \\\n+ --hash=sha256:ca94b6aac0d7af2a10ba08c0f888b3d5114439b6b3ef39968378723622fed377 \\\n+ --hash=sha256:cad302dc10fac357d3467a74a9561c90609768a6f73a1923b0fd851b6486f8b0 \\\n+ --hash=sha256:d0a7735df32ccbcc98b98a1ac785cc4b19b580be1bdf0aeb5c03223220ea09d5 \\\n+ --hash=sha256:d70347c8a5b7ccd803ec0c85c8709f036e6348f1e6a5bf048ecd9c64d3550b8b \\\n+ --hash=sha256:d70534cea9e7966169ad29a903b99fc507e932069a881d0965a1a84bb57f6c6d \\\n+ --hash=sha256:db44d5c160a90df2d24a24760bbd37607d53da0b34fb546c4c232af7192298ac \\\n+ --hash=sha256:e115c15e3bc727b1ca3e641a909f77f8ca72a64fff150f666fcc85e57701c26c \\\n+ --hash=sha256:e2479c7f02f9d505682dc47df8c0ea1fc5e264c4d1629a5d63fe3e2334b89554 \\\n+ --hash=sha256:e5dcbe95016e88437ecf33544ba5db21ef1b8dd6e1b434a2cb2a3d605299e643 \\\n+ --hash=sha256:e6bdb408f7c9dd2a5ff2b14a3b0bb6d4deb29fb9961e6eb3ae2031ae9a5cec13 \\\n+ --hash=sha256:e75d3dba8fc1ddfec0cd752108f93b83b4f8d6ab40e524a95d35f016b9683b09 \\\n+ --hash=sha256:efdc140e7b63b8f739d09a99033aa430accce485ff78e6d311973a67b6bf3208 \\\n+ --hash=sha256:f10c98f49227ed8383d28174ee95155a675c4ed7f85e2e573b04414f7e371bda \\\n+ --hash=sha256:f188028b5af6b8fb2e9a76ac0f841a575bd1bd396e46ef0840d9b88a48fdbcea \\\n+ --hash=sha256:f188d580bd870cda1e15183790d1cc2fa78f666e76077d103edf048eed9c356e \\\n+ --hash=sha256:f45bd71d1fa5e5749587613037b172e0b3b23159d1c00ef2fc920da6f470e6f0 \\\n+ --hash=sha256:f61333d817698bdcdd0f9d7793e365ac3d2a21c1f1eb02b32ad6aefb8d8ea831 \\\n+ --hash=sha256:fb125d860738a09d363a88daa0f59c4533529a90e564785e20fe875b200b6dbd\n+ # via tensorboard\n portpicker==1.6.0 \\\n --hash=sha256:b2787a41404cf7edbe29b07b9e0ed863b09f2665dcc01c1eb0c2261c1e7d0755 \\\n --hash=sha256:bd507fd6f96f65ee02781f2e674e9dc6c99bbfa6e3c39992e3916204c9d431fa\n@@ -634,7 +727,7 @@ protobuf==6.31.1 \\\n --hash=sha256:d8cac4c982f0b957a4dc73a80e2ea24fab08e679c0de9deb835f4a12d69aca9a\n # via\n # -r ci/official/requirements_updater/requirements.in\n- # tb-nightly\n+ # tensorboard\n psutil==7.0.0 \\\n --hash=sha256:101d71dc322e3cffd7cea0650b09b3d08b8e7c4109dd6809fe452dfd00e58b25 \\\n --hash=sha256:1e744154a6580bc968a0195fd25e80432d3afec619daf145b9e5ba16cc1d688e \\\n@@ -662,7 +755,7 @@ requests==2.32.4 \\\n rich==14.0.0 \\\n --hash=sha256:1c9491e1951aac09caffd42f448ee3d04e58923ffe14993f6e83068dc395d7e0 \\\n --hash=sha256:82f1bc23a6a21ebca4ae0c45af9bdbc492ed20231dcb63f297d6d1021a9d5725\n- # via keras-nightly\n+ # via keras\n scipy==1.14.1 \\\n --hash=sha256:0c2f95de3b04e26f5f3ad5bb05e74ba7f68b837133a4492414b3afd79dfe540e \\\n --hash=sha256:1729560c906963fc8389f6aac023739ff3983e727b1a4d87696b7bf108316a79 \\\n@@ -706,19 +799,18 @@ six==1.17.0 \\\n # via\n # astunparse\n # google-pasta\n- # tb-nightly\n-tb-nightly==2.20.0a20250424 \\\n- --hash=sha256:62ad3a4ce94cba2bb59538dd481999ede10927304d6f7fa0e9a23df9d24a779e\n- # via -r ci/official/requirements_updater/requirements.in\n tblib==2.0.0 \\\n --hash=sha256:9100bfa016b047d5b980d66e7efed952fbd20bd85b56110aaf473cb97d18709a \\\n --hash=sha256:a6df30f272c08bf8be66e0775fad862005d950a6b8449b94f7c788731d70ecd7\n # via -r ci/official/requirements_updater/requirements.in\n+tensorboard==2.20.0 \\\n+ --hash=sha256:9dc9f978cb84c0723acf9a345d96c184f0293d18f166bb8d59ee098e6cfaaba6\n+ # via -r ci/official/requirements_updater/requirements.in\n tensorboard-data-server==0.7.2 \\\n --hash=sha256:7e0610d205889588983836ec05dc098e80f97b7e7bbff7e994ebb78f578d0ddb \\\n --hash=sha256:9fe5d24221b29625dbc7328b0436ca7fc1c23de4acf4d272f1180856e32f9f60 \\\n --hash=sha256:ef687163c24185ae9754ed5650eb5bc4d84ff257aabdc33f0cc6f74d8ba54530\n- # via tb-nightly\n+ # via tensorboard\n tensorflow-io-gcs-filesystem==0.37.1 ; python_version <= \"3.12\" \\\n --hash=sha256:0df00891669390078a003cedbdd3b8e645c718b111917535fa1d7725e95cdb95 \\\n --hash=sha256:249c12b830165841411ba71e08215d0e94277a49c551e6dd5d72aab54fe5491b \\\n@@ -754,10 +846,10 @@ urllib3==2.6.3 \\\n werkzeug==3.1.5 \\\n --hash=sha256:5111e36e91086ece91f93268bb39b4a35c1e6f1feac762c9c822ded0a4e322dc \\\n --hash=sha256:6a548b0e88955dd07ccb25539d7d0cc97417ee9e179677d22c7041c8f078ce67\n- # via tb-nightly\n-wheel==0.46.2 \\\n- --hash=sha256:33ae60725d69eaa249bc1982e739943c23b34b58d51f1cb6253453773aca6e65 \\\n- --hash=sha256:3d79e48fde9847618a5a181f3cc35764c349c752e2fe911e65fa17faab9809b0\n+ # via tensorboard\n+wheel==0.41.3 \\\n+ --hash=sha256:488609bc63a29322326e05560731bf7bfea8e48ad646e1f5e40d366607de0942 \\\n+ --hash=sha256:4d4987ce51a49370ea65c0bfd2234e8ce80a12780820d9dc462597a6e60d0841\n # via\n # -r ci/official/requirements_updater/requirements.in\n # astunparse\n@@ -939,4 +1031,4 @@ setuptools==78.1.1 \\\n --hash=sha256:fcc17fd9cd898242f6b4adfaca46137a9edef687f43e6f78469692a5e70d851d\n # via\n # -r ci/official/requirements_updater/requirements.in\n- # tb-nightly\n+ # tensorboard" }, { "filename": "requirements_lock_3_13.txt", "status": "modified", "additions": 119, "deletions": 27, "changes": 146, "patch": "@@ -8,8 +8,8 @@ absl-py==2.3.0 \\\n --hash=sha256:9824a48b654a306168f63e0d97714665f8490b8d89ec7bf2efc24bf67cf579b3 \\\n --hash=sha256:d96fda5c884f1b22178852f30ffa85766d50b99e00775ea626c23304f582fc4f\n # via\n- # keras-nightly\n- # tb-nightly\n+ # keras\n+ # tensorboard\n astor==0.7.1 \\\n --hash=sha256:95c30d87a6c2cf89aa628b87398466840f0ad8652f88eb173125a6df8533fb8d \\\n --hash=sha256:fb503b9e2fdd05609fbf557b916b4a7824171203701660f0c55bbf5a7a68713e\n@@ -191,7 +191,7 @@ grpcio==1.71.0 \\\n --hash=sha256:f9c30c464cb2ddfbc2ddf9400287701270fdc0f14be5f08a1e3939f1e749b455\n # via\n # -r ci/official/requirements_updater/requirements.in\n- # tb-nightly\n+ # tensorboard\n h5py==3.13.0 \\\n --hash=sha256:10894c55d46df502d82a7a4ed38f9c3fdbcb93efb42e25d275193e093071fade \\\n --hash=sha256:1870e46518720023da85d0895a1960ff2ce398c5671eac3b1a41ec696b7105c3 \\\n@@ -221,17 +221,17 @@ h5py==3.13.0 \\\n --hash=sha256:fb267ce4b83f9c42560e9ff4d30f60f7ae492eacf9c7ede849edf8c1b860e16b\n # via\n # -r ci/official/requirements_updater/requirements.in\n- # keras-nightly\n+ # keras\n idna==3.10 \\\n --hash=sha256:12f65c9b470abda6dc35cf8e63cc574b1c52b11df2c86030af0ac09b01b13ea9 \\\n --hash=sha256:946d195a0d259cbba61165e88e65941f16e9b36ea6ddb97f00452bae8b1287d3\n # via requests\n jax==0.4.7 \\\n --hash=sha256:5e7002d74db25f97c99b979d4ba1233b1ef26e1597e5fc468ad11d1c8a9dc4f8\n # via -r ci/official/requirements_updater/requirements.in\n-keras-nightly==3.12.0.dev2025100703 \\\n- --hash=sha256:6b9dfb3814d707abf5555f56268f072daec13f2540da3aeeb7531a819ebb4567 \\\n- --hash=sha256:e29434e49bac3360f86af6e1548d94b0a2fda4e793685bc43b49867132ab16e5\n+keras==3.12.1 \\\n+ --hash=sha256:3cb760b3fec105db4d893dd717daafdd0e35457a8201502c1ba8bedfaf334a71 \\\n+ --hash=sha256:c340f8a25362398b20500c64e290f6ee280c6aeec51e1044eb8d759b32dc272a\n # via -r ci/official/requirements_updater/requirements.in\n libclang==18.1.1 \\\n --hash=sha256:0b2e143f0fac830156feb56f9231ff8338c20aecfe72b4ffe96f19e5a1dbb69a \\\n@@ -251,7 +251,7 @@ lit==17.0.6 \\\n markdown==3.8 \\\n --hash=sha256:794a929b79c5af141ef5ab0f2f642d0f7b1872981250230e72682346f7cc90dc \\\n --hash=sha256:7df81e63f0df5c4b24b7d156eb81e4690595239b7d70937d0409f1b0de319c6f\n- # via tb-nightly\n+ # via tensorboard\n markdown-it-py==3.0.0 \\\n --hash=sha256:355216845c60bd96232cd8d8c40e8f9765cc86f46880e43a8fd22dc1a1a8cab1 \\\n --hash=sha256:e3f60a94fa066dc52ec76661e37c851cb232d92f9886b15cb560aaada2df8feb\n@@ -351,11 +351,11 @@ ml-dtypes==0.5.1 \\\n # via\n # -r ci/official/requirements_updater/requirements.in\n # jax\n- # keras-nightly\n+ # keras\n namex==0.0.9 \\\n --hash=sha256:7bd4e4a2cc3876592111609fdf4cbe6ff19883adbe6b3b40d842fd340f77025e \\\n --hash=sha256:8adfea9da5cea5be8f4e632349b4669e30172c7859e1fd97459fdf3b17469253\n- # via keras-nightly\n+ # via keras\n numpy==2.1.3 \\\n --hash=sha256:016d0f6f5e77b0f0d45d77387ffa4bb89816b57c835580c3ce8e099ef830befe \\\n --hash=sha256:02135ade8b8a84011cbb67dc44e07c58f28575cf9ecf8ab304e51c05528c19f0 \\\n@@ -416,11 +416,11 @@ numpy==2.1.3 \\\n # -r ci/official/requirements_updater/requirements.in\n # h5py\n # jax\n- # keras-nightly\n+ # keras\n # ml-dtypes\n # opt-einsum\n # scipy\n- # tb-nightly\n+ # tensorboard\n nvidia-cublas-cu12==12.5.3.2 \\\n --hash=sha256:4960f3dc5f39699acadf76fa6d94b10a2a00f2956c2c442efa299fb22b0748f3 \\\n --hash=sha256:7d0191251180de606023d396b94d66f66470a0ae96d1dbb906c7656ea0f71eda \\\n@@ -609,15 +609,108 @@ optree==0.16.0 \\\n --hash=sha256:eeccc740b72b58efa9795ab831a678a42341def48b9e5956c6b1e588c6fa3ddf \\\n --hash=sha256:f08aaa1c2ae092b3e662125ad19860046c63d7451d41be133ddd6594920e295e \\\n --hash=sha256:f703d7926c36eebdd56fc08aabefcf32a8b7292a9dd4468e56b0ab61bf6214bd\n- # via keras-nightly\n+ # via keras\n packaging==23.2 \\\n --hash=sha256:048fb0e9405036518eaaf48a55953c750c11e1a1b68e0dd1a9d62ed0c092cfc5 \\\n --hash=sha256:8c491190033a9af7e1d931d0b5dacc2ef47509b34dd0de67ed209b5203fc88c7\n # via\n # -r ci/official/requirements_updater/requirements.in\n # auditwheel\n- # keras-nightly\n- # tb-nightly\n+ # keras\n+ # tensorboard\n+pillow==12.1.0 \\\n+ --hash=sha256:00162e9ca6d22b7c3ee8e61faa3c3253cd19b6a37f126cad04f2f88b306f557d \\\n+ --hash=sha256:079af2fb0c599c2ec144ba2c02766d1b55498e373b3ac64687e43849fbbef5bc \\\n+ --hash=sha256:0b022eaaf709541b391ee069f0022ee5b36c709df71986e3f7be312e46f42c84 \\\n+ --hash=sha256:0c27407a2d1b96774cbc4a7594129cc027339fd800cd081e44497722ea1179de \\\n+ --hash=sha256:0ddedfaa8b5f0b4ffbc2fa87b556dc59f6bb4ecb14a53b33f9189713ae8053c0 \\\n+ --hash=sha256:0deedf2ea233722476b3a81e8cdfbad786f7adbed5d848469fa59fe52396e4ef \\\n+ --hash=sha256:0ed07dca4a8464bada6139ab38f5382f83e5f111698caf3191cb8dbf27d908b4 \\\n+ --hash=sha256:0fde7ec5538ab5095cc02df38ee99b0443ff0e1c847a045554cf5f9af1f4aa82 \\\n+ --hash=sha256:15c794d74303828eaa957ff8070846d0efe8c630901a1c753fdc63850e19ecd9 \\\n+ --hash=sha256:1a949604f73eb07a8adab38c4fe50791f9919344398bdc8ac6b307f755fc7030 \\\n+ --hash=sha256:1f345e7bc9d7f368887c712aa5054558bad44d2a301ddf9248599f4161abc7c0 \\\n+ --hash=sha256:1fcc52d86ce7a34fd17cb04e87cfdb164648a3662a6f20565910a99653d66c18 \\\n+ --hash=sha256:21e686a21078b0f9cb8c8a961d99e6a4ddb88e0fc5ea6e130172ddddc2e5221a \\\n+ --hash=sha256:2415373395a831f53933c23ce051021e79c8cd7979822d8cc478547a3f4da8ef \\\n+ --hash=sha256:277518bf4fe74aa91489e1b20577473b19ee70fb97c374aa50830b279f25841b \\\n+ --hash=sha256:27b9baecb428899db6c0de572d6d305cfaf38ca1596b5c0542a5182e3e74e8c6 \\\n+ --hash=sha256:29a4cef9cb672363926f0470afc516dbf7305a14d8c54f7abbb5c199cd8f8179 \\\n+ --hash=sha256:3413c2ae377550f5487991d444428f1a8ae92784aac79caa8b1e3b89b175f77e \\\n+ --hash=sha256:351889afef0f485b84078ea40fe33727a0492b9af3904661b0abbafee0355b72 \\\n+ --hash=sha256:3ffaa2f0659e2f740473bcf03c702c39a8d4b2b7ffc629052028764324842c64 \\\n+ --hash=sha256:40a8e3b9e8773876d6e30daed22f016509e3987bab61b3b7fe309d7019a87451 \\\n+ --hash=sha256:414b9a78e14ffeb98128863314e62c3f24b8a86081066625700b7985b3f529bd \\\n+ --hash=sha256:43aca0a55ce1eefc0aefa6253661cb54571857b1a7b2964bd8a1e3ef4b729924 \\\n+ --hash=sha256:43b4899cfd091a9693a1278c4982f3e50f7fb7cff5153b05174b4afc9593b616 \\\n+ --hash=sha256:461f9dfdafa394c59cd6d818bdfdbab4028b83b02caadaff0ffd433faf4c9a7a \\\n+ --hash=sha256:4f9f6a650743f0ddee5593ac9e954ba1bdbc5e150bc066586d4f26127853ab94 \\\n+ --hash=sha256:53d8b764726d3af1a138dd353116f774e3862ec7e3794e0c8781e30db0f35dfc \\\n+ --hash=sha256:565c986f4b45c020f5421a4cea13ef294dde9509a8577f29b2fc5edc7587fff8 \\\n+ --hash=sha256:5c5ae0a06e9ea030ab786b0251b32c7e4ce10e58d983c0d5c56029455180b5b9 \\\n+ --hash=sha256:5cb7bc1966d031aec37ddb9dcf15c2da5b2e9f7cc3ca7c54473a20a927e1eb91 \\\n+ --hash=sha256:5da841d81b1a05ef940a8567da92decaa15bc4d7dedb540a8c219ad83d91808a \\\n+ --hash=sha256:5fee4c04aad8932da9f8f710af2c1a15a83582cfb884152a9caa79d4efcdbf9c \\\n+ --hash=sha256:609e89d9f90b581c8d16358c9087df76024cf058fa693dd3e1e1620823f39670 \\\n+ --hash=sha256:6258f3260986990ba2fa8a874f8b6e808cf5abb51a94015ca3dc3c68aa4f30ea \\\n+ --hash=sha256:64efdf00c09e31efd754448a383ea241f55a994fd079866b92d2bbff598aad91 \\\n+ --hash=sha256:65b80c1ee7e14a87d6a068dd3b0aea268ffcabfe0498d38661b00c5b4b22e74c \\\n+ --hash=sha256:6741e6f3074a35e47c77b23a4e4f2d90db3ed905cb1c5e6e0d49bff2045632bc \\\n+ --hash=sha256:681088909d7e8fa9e31b9799aaa59ba5234c58e5e4f1951b4c4d1082a2e980e0 \\\n+ --hash=sha256:6b7a9d1db5dad90e2991645874f708e87d9a3c370c243c2d7684d28f7e133e6b \\\n+ --hash=sha256:7315f9137087c4e0ee73a761b163fc9aa3b19f5f606a7fc08d83fd3e4379af65 \\\n+ --hash=sha256:742aea052cf5ab5034a53c3846165bc3ce88d7c38e954120db0ab867ca242661 \\\n+ --hash=sha256:75af0b4c229ac519b155028fa1be632d812a519abba9b46b20e50c6caa184f19 \\\n+ --hash=sha256:7b5dd7cbae20285cdb597b10eb5a2c13aa9de6cde9bb64a3c1317427b1db1ae1 \\\n+ --hash=sha256:7d6daa89a00b58c37cb1747ec9fb7ac3bc5ffd5949f5888657dfddde6d1312e0 \\\n+ --hash=sha256:800429ac32c9b72909c671aaf17ecd13110f823ddb7db4dfef412a5587c2c24e \\\n+ --hash=sha256:806f3987ffe10e867bab0ddad45df1148a2b98221798457fa097ad85d6e8bc75 \\\n+ --hash=sha256:808b99604f7873c800c4840f55ff389936ef1948e4e87645eaf3fccbc8477ac4 \\\n+ --hash=sha256:80941e6d573197a0c28f394753de529bb436b1ca990ed6e765cf42426abc39f8 \\\n+ --hash=sha256:84cabc7095dd535ca934d57e9ce2a72ffd216e435a84acb06b2277b1de2689bd \\\n+ --hash=sha256:8637e29d13f478bc4f153d8daa9ffb16455f0a6cb287da1b432fdad2bfbd66c7 \\\n+ --hash=sha256:896866d2d436563fa2a43a9d72f417874f16b5545955c54a64941e87c1376c61 \\\n+ --hash=sha256:8e178e3e99d3c0ea8fc64b88447f7cac8ccf058af422a6cedc690d0eadd98c51 \\\n+ --hash=sha256:907bfa8a9cb790748a9aa4513e37c88c59660da3bcfffbd24a7d9e6abf224551 \\\n+ --hash=sha256:9212d6b86917a2300669511ed094a9406888362e085f2431a7da985a6b124f45 \\\n+ --hash=sha256:92a7fe4225365c5e3a8e598982269c6d6698d3e783b3b1ae979e7819f9cd55c1 \\\n+ --hash=sha256:935b9d1aed48fcfb3f838caac506f38e29621b44ccc4f8a64d575cb1b2a88644 \\\n+ --hash=sha256:97e9993d5ed946aba26baf9c1e8cf18adbab584b99f452ee72f7ee8acb882796 \\\n+ --hash=sha256:983976c2ab753166dc66d36af6e8ec15bb511e4a25856e2227e5f7e00a160587 \\\n+ --hash=sha256:9f5fefaca968e700ad1a4a9de98bf0869a94e397fe3524c4c9450c1445252304 \\\n+ --hash=sha256:a332ac4ccb84b6dde65dbace8431f3af08874bf9770719d32a635c4ef411b18b \\\n+ --hash=sha256:a40905599d8079e09f25027423aed94f2823adaf2868940de991e53a449e14a8 \\\n+ --hash=sha256:a6dfc2af5b082b635af6e08e0d1f9f1c4e04d17d4e2ca0ef96131e85eda6eb17 \\\n+ --hash=sha256:a786bf667724d84aa29b5db1c61b7bfdde380202aaca12c3461afd6b71743171 \\\n+ --hash=sha256:a83e0850cb8f5ac975291ebfc4170ba481f41a28065277f7f735c202cd8e0af3 \\\n+ --hash=sha256:aa0c9cc0b82b14766a99fbe6084409972266e82f459821cd26997a488a7261a7 \\\n+ --hash=sha256:b17fbdbe01c196e7e159aacb889e091f28e61020a8abeac07b68079b6e626988 \\\n+ --hash=sha256:b63e13dd27da389ed9475b3d28510f0f954bca0041e8e551b2a4eb1eab56a39a \\\n+ --hash=sha256:b6e53e82ec2db0717eabb276aa56cf4e500c9a7cec2c2e189b55c24f65a3e8c0 \\\n+ --hash=sha256:bb0984b30e973f7e2884362b7d23d0a348c7143ee559f38ef3eaab640144204c \\\n+ --hash=sha256:bc11908616c8a283cf7d664f77411a5ed2a02009b0097ff8abbba5e79128ccf2 \\\n+ --hash=sha256:bdec5e43377761c5dbca620efb69a77f6855c5a379e32ac5b158f54c84212b14 \\\n+ --hash=sha256:bef9768cab184e7ae6e559c032e95ba8d07b3023c289f79a2bd36e8bf85605a5 \\\n+ --hash=sha256:c990547452ee2800d8506c4150280757f88532f3de2a58e3022e9b179107862a \\\n+ --hash=sha256:ca94b6aac0d7af2a10ba08c0f888b3d5114439b6b3ef39968378723622fed377 \\\n+ --hash=sha256:cad302dc10fac357d3467a74a9561c90609768a6f73a1923b0fd851b6486f8b0 \\\n+ --hash=sha256:d0a7735df32ccbcc98b98a1ac785cc4b19b580be1bdf0aeb5c03223220ea09d5 \\\n+ --hash=sha256:d70347c8a5b7ccd803ec0c85c8709f036e6348f1e6a5bf048ecd9c64d3550b8b \\\n+ --hash=sha256:d70534cea9e7966169ad29a903b99fc507e932069a881d0965a1a84bb57f6c6d \\\n+ --hash=sha256:db44d5c160a90df2d24a24760bbd37607d53da0b34fb546c4c232af7192298ac \\\n+ --hash=sha256:e115c15e3bc727b1ca3e641a909f77f8ca72a64fff150f666fcc85e57701c26c \\\n+ --hash=sha256:e2479c7f02f9d505682dc47df8c0ea1fc5e264c4d1629a5d63fe3e2334b89554 \\\n+ --hash=sha256:e5dcbe95016e88437ecf33544ba5db21ef1b8dd6e1b434a2cb2a3d605299e643 \\\n+ --hash=sha256:e6bdb408f7c9dd2a5ff2b14a3b0bb6d4deb29fb9961e6eb3ae2031ae9a5cec13 \\\n+ --hash=sha256:e75d3dba8fc1ddfec0cd752108f93b83b4f8d6ab40e524a95d35f016b9683b09 \\\n+ --hash=sha256:efdc140e7b63b8f739d09a99033aa430accce485ff78e6d311973a67b6bf3208 \\\n+ --hash=sha256:f10c98f49227ed8383d28174ee95155a675c4ed7f85e2e573b04414f7e371bda \\\n+ --hash=sha256:f188028b5af6b8fb2e9a76ac0f841a575bd1bd396e46ef0840d9b88a48fdbcea \\\n+ --hash=sha256:f188d580bd870cda1e15183790d1cc2fa78f666e76077d103edf048eed9c356e \\\n+ --hash=sha256:f45bd71d1fa5e5749587613037b172e0b3b23159d1c00ef2fc920da6f470e6f0 \\\n+ --hash=sha256:f61333d817698bdcdd0f9d7793e365ac3d2a21c1f1eb02b32ad6aefb8d8ea831 \\\n+ --hash=sha256:fb125d860738a09d363a88daa0f59c4533529a90e564785e20fe875b200b6dbd\n+ # via tensorboard\n portpicker==1.6.0 \\\n --hash=sha256:b2787a41404cf7edbe29b07b9e0ed863b09f2665dcc01c1eb0c2261c1e7d0755 \\\n --hash=sha256:bd507fd6f96f65ee02781f2e674e9dc6c99bbfa6e3c39992e3916204c9d431fa\n@@ -634,7 +727,7 @@ protobuf==6.31.1 \\\n --hash=sha256:d8cac4c982f0b957a4dc73a80e2ea24fab08e679c0de9deb835f4a12d69aca9a\n # via\n # -r ci/official/requirements_updater/requirements.in\n- # tb-nightly\n+ # tensorboard\n psutil==7.0.0 \\\n --hash=sha256:101d71dc322e3cffd7cea0650b09b3d08b8e7c4109dd6809fe452dfd00e58b25 \\\n --hash=sha256:1e744154a6580bc968a0195fd25e80432d3afec619daf145b9e5ba16cc1d688e \\\n@@ -662,7 +755,7 @@ requests==2.32.4 \\\n rich==14.0.0 \\\n --hash=sha256:1c9491e1951aac09caffd42f448ee3d04e58923ffe14993f6e83068dc395d7e0 \\\n --hash=sha256:82f1bc23a6a21ebca4ae0c45af9bdbc492ed20231dcb63f297d6d1021a9d5725\n- # via keras-nightly\n+ # via keras\n scipy==1.14.1 \\\n --hash=sha256:0c2f95de3b04e26f5f3ad5bb05e74ba7f68b837133a4492414b3afd79dfe540e \\\n --hash=sha256:1729560c906963fc8389f6aac023739ff3983e727b1a4d87696b7bf108316a79 \\\n@@ -706,19 +799,18 @@ six==1.17.0 \\\n # via\n # astunparse\n # google-pasta\n- # tb-nightly\n-tb-nightly==2.20.0a20250424 \\\n- --hash=sha256:62ad3a4ce94cba2bb59538dd481999ede10927304d6f7fa0e9a23df9d24a779e\n- # via -r ci/official/requirements_updater/requirements.in\n tblib==2.0.0 \\\n --hash=sha256:9100bfa016b047d5b980d66e7efed952fbd20bd85b56110aaf473cb97d18709a \\\n --hash=sha256:a6df30f272c08bf8be66e0775fad862005d950a6b8449b94f7c788731d70ecd7\n # via -r ci/official/requirements_updater/requirements.in\n+tensorboard==2.20.0 \\\n+ --hash=sha256:9dc9f978cb84c0723acf9a345d96c184f0293d18f166bb8d59ee098e6cfaaba6\n+ # via -r ci/official/requirements_updater/requirements.in\n tensorboard-data-server==0.7.2 \\\n --hash=sha256:7e0610d205889588983836ec05dc098e80f97b7e7bbff7e994ebb78f578d0ddb \\\n --hash=sha256:9fe5d24221b29625dbc7328b0436ca7fc1c23de4acf4d272f1180856e32f9f60 \\\n --hash=sha256:ef687163c24185ae9754ed5650eb5bc4d84ff257aabdc33f0cc6f74d8ba54530\n- # via tb-nightly\n+ # via tensorboard\n termcolor==2.3.0 \\\n --hash=sha256:3afb05607b89aed0ffe25202399ee0867ad4d3cb4180d98aaf8eefa6a5f7d475 \\\n --hash=sha256:b5b08f68937f138fe92f6c089b99f1e2da0ae56c52b78bf7075fd95420fd9a5a\n@@ -736,10 +828,10 @@ urllib3==2.6.3 \\\n werkzeug==3.1.5 \\\n --hash=sha256:5111e36e91086ece91f93268bb39b4a35c1e6f1feac762c9c822ded0a4e322dc \\\n --hash=sha256:6a548b0e88955dd07ccb25539d7d0cc97417ee9e179677d22c7041c8f078ce67\n- # via tb-nightly\n-wheel==0.46.2 \\\n- --hash=sha256:33ae60725d69eaa249bc1982e739943c23b34b58d51f1cb6253453773aca6e65 \\\n- --hash=sha256:3d79e48fde9847618a5a181f3cc35764c349c752e2fe911e65fa17faab9809b0\n+ # via tensorboard\n+wheel==0.41.3 \\\n+ --hash=sha256:488609bc63a29322326e05560731bf7bfea8e48ad646e1f5e40d366607de0942 \\\n+ --hash=sha256:4d4987ce51a49370ea65c0bfd2234e8ce80a12780820d9dc462597a6e60d0841\n # via\n # -r ci/official/requirements_updater/requirements.in\n # astunparse\n@@ -921,4 +1013,4 @@ setuptools==78.1.1 \\\n --hash=sha256:fcc17fd9cd898242f6b4adfaca46137a9edef687f43e6f78469692a5e70d851d\n # via\n # -r ci/official/requirements_updater/requirements.in\n- # tb-nightly\n+ # tensorboard" }, { "filename": "tensorflow/tools/pip_package/setup.py.tpl", "status": "modified", "additions": 2, "deletions": 2, "changes": 4, "patch": "@@ -123,8 +123,8 @@ REQUIRED_PACKAGES = [\n # dependencies on the release branch is updated to the stable releases (RC\n # or final). For example, 'keras-nightly ~= 2.14.0.dev' will be replaced by\n # 'keras >= 2.14.0rc0, < 2.15' on the release branch after the branch cut.\n- 'tb-nightly ~= 2.20.0.a',\n- 'keras-nightly >= 3.12.0.dev',\n+ 'tensorboard ~= 2.20.0',\n+ 'keras >= 3.12.0',\n 'numpy >= 1.26.0',\n # Starting with 3.15, only MacOS 14 and 15 are supported.\n 'h5py >= 3.11.0, < 3.15.0'," } ], "reviews": [ { "id": 3764242414, "user": "user_bde0b4e99946", "state": "APPROVED", "body": null, "submitted_at": "2026-02-06T17:09:50+00:00" }, { "id": 3764572356, "user": "user_bde0b4e99946", "state": "APPROVED", "body": null, "submitted_at": "2026-02-06T18:30:50+00:00" }, { "id": 3764580487, "user": "user_bde0b4e99946", "state": "COMMENTED", "body": null, "submitted_at": "2026-02-06T18:33:25+00:00" }, { "id": 3764666257, "user": "user_bde0b4e99946", "state": "APPROVED", "body": null, "submitted_at": "2026-02-06T18:57:07+00:00" }, { "id": 3764768192, "user": "user_85febeead85a", "state": "APPROVED", "body": "LGTM", "submitted_at": "2026-02-06T19:25:58+00:00" } ], "review_comments": [ { "id": 2775487832, "user": "user_bde0b4e99946", "body": "can you please toll back this change in all numpy lock files? hermetic CUDA shouldn't be removed", "path": "ci/official/requirements_updater/numpy1_requirements/requirements_lock_3_10.txt", "line": 405, "side": "LEFT", "created_at": "2026-02-06T18:33:26+00:00" } ], "meta": { "languages": [ "in", "tpl", "txt" ], "touches_tests": false, "review_state_summary": { "APPROVED": 4, "COMMENTED": 1 }, "meaningful_comment_count": 1, "has_approval": true, "has_changes_requested": false, "total_review_comments": 1 } } { "_id": "e1ee70d96ccf0c12", "_schema_version": "1.0", "_cleaned_at": "2026-02-12T07:46:52.038957+00:00", "repo": "psf/requests", "repo_url": "https://github.com/psf/requests", "license_name": "Apache License 2.0", "license_spdx": "Apache-2.0", "pr_number": 4442, "title": "Reduce overall memory usage by [NAME_REDACTED] writing a protected function", "body": "In response to issue #4313 , I removed the cgi module import and added a parse_header function nested inside get_encoding_from_headers in utils.py. I have run the tests both before and after making these changes. The test_util cases all passed before and they still do now. Please let me know about any suggestions to this code.", "author": "user_137c7bb40eac", "created_at": "2017-12-31T21:15:20+00:00", "merged_at": "2018-01-04T22:32:40+00:00", "base_branch": "master", "head_branch": "master", "additions": 67, "deletions": 3, "changed_files": 3, "files": [ { "filename": "AUTHORS.rst", "status": "modified", "additions": 1, "deletions": 0, "changes": 1, "patch": "@@ -181,3 +181,4 @@ Patches and Suggestions\n - [NAME_REDACTED] <[EMAIL_REDACTED]> ([CONTRIBUTOR_REDACTED])\n - [NAME_REDACTED] ([CONTRIBUTOR_REDACTED])\n - Nehal J Wani ([CONTRIBUTOR_REDACTED])\n+- [NAME_REDACTED] ([CONTRIBUTOR_REDACTED])" }, { "filename": "requests/utils.py", "status": "modified", "additions": 26, "deletions": 2, "changes": 28, "patch": "@@ -8,7 +8,6 @@\n that are also useful for external consumption.\n \"\"\"\n \n-import cgi\n import codecs\n import collections\n import contextlib\n@@ -447,6 +446,31 @@ def get_encodings_from_content(content):\n xml_re.findall(content))\n \n \n+def _parse_content_type_header(header):\n+ \"\"\"Returns content type and parameters from given header\n+\n+ :param header: string\n+ :return: tuple containing content type and dictionary of\n+ parameters\n+ \"\"\"\n+\n+ tokens = header.split(';')\n+ content_type, params = tokens[0].strip(), tokens[1:]\n+ params_dict = {}\n+ items_to_strip = \"\\\"' \"\n+\n+ for param in params:\n+ param = param.strip()\n+ if param:\n+ key, value = param, True\n+ index_of_equals = param.find(\"=\")\n+ if index_of_equals != -1:\n+ key = param[:index_of_equals].strip(items_to_strip)\n+ value = param[index_of_equals + 1:].strip(items_to_strip)\n+ params_dict[key] = value\n+ return content_type, params_dict\n+\n+\n def get_encoding_from_headers(headers):\n \"\"\"Returns encodings from given HTTP [NAME_REDACTED].\n \n@@ -459,7 +483,7 @@ def get_encoding_from_headers(headers):\n if not content_type:\n return None\n \n- content_type, params = cgi.parse_header(content_type)\n+ content_type, params = _parse_content_type_header(content_type)\n \n if 'charset' in params:\n return params['charset'].strip(\"'\\\"\")" }, { "filename": "tests/test_utils.py", "status": "modified", "additions": 40, "deletions": 1, "changes": 41, "patch": "@@ -13,7 +13,7 @@\n from requests.structures import CaseInsensitiveDict\n from requests.utils import (\n address_in_network, dotted_netmask, extract_zipped_paths,\n- get_auth_from_url, get_encoding_from_headers,\n+ get_auth_from_url, _parse_content_type_header, get_encoding_from_headers,\n get_encodings_from_content, get_environ_proxies,\n guess_filename, guess_json_utf, is_ipv4_address,\n is_valid_cidr, iter_slices, parse_dict_header,\n@@ -470,6 +470,45 @@ def test_parse_dict_header(value, expected):\n assert parse_dict_header(value) == expected\n \n \n+[USER_REDACTED].mark.parametrize(\n+ 'value, expected', (\n+ (\n+ 'application/xml',\n+ ('application/xml', {})\n+ ),\n+ (\n+ 'application/json ; charset=utf-8',\n+ ('application/json', {'charset': 'utf-8'})\n+ ),\n+ (\n+ 'text/plain',\n+ ('text/plain', {})\n+ ),\n+ (\n+ 'multipart/form-data; boundary = something ; boundary2=\\'something_else\\' ; no_equals ',\n+ ('multipart/form-data', {'boundary': 'something', 'boundary2': 'something_else', 'no_equals': True})\n+ ),\n+ (\n+ 'multipart/form-data; boundary = something ; boundary2=\"something_else\" ; no_equals ',\n+ ('multipart/form-data', {'boundary': 'something', 'boundary2': 'something_else', 'no_equals': True})\n+ ),\n+ (\n+ 'multipart/form-data; boundary = something ; \\'boundary2=something_else\\' ; no_equals ',\n+ ('multipart/form-data', {'boundary': 'something', 'boundary2': 'something_else', 'no_equals': True})\n+ ),\n+ (\n+ 'multipart/form-data; boundary = something ; \"boundary2=something_else\" ; no_equals ',\n+ ('multipart/form-data', {'boundary': 'something', 'boundary2': 'something_else', 'no_equals': True})\n+ ),\n+ (\n+ 'application/json ; ; ',\n+ ('application/json', {})\n+ )\n+ ))\n+def test__parse_content_type_header(value, expected):\n+ assert _parse_content_type_header(value) == expected\n+\n+\n [USER_REDACTED].mark.parametrize(\n 'value, expected', (\n (" } ], "reviews": [ { "id": 86061133, "user": "user_0fa58b6f3572", "state": "CHANGES_REQUESTED", "body": null, "submitted_at": "2018-01-01T12:16:08+00:00" }, { "id": 86065792, "user": "user_137c7bb40eac", "state": "COMMENTED", "body": null, "submitted_at": "2018-01-01T16:53:10+00:00" }, { "id": 86065804, "user": "user_137c7bb40eac", "state": "COMMENTED", "body": null, "submitted_at": "2018-01-01T16:54:22+00:00" }, { "id": 86380024, "user": "user_0fa58b6f3572", "state": "CHANGES_REQUESTED", "body": null, "submitted_at": "2018-01-03T14:23:10+00:00" }, { "id": 86470746, "user": "user_137c7bb40eac", "state": "COMMENTED", "body": null, "submitted_at": "2018-01-03T19:41:19+00:00" }, { "id": 86654533, "user": "user_b08fb5f52ea1", "state": "COMMENTED", "body": null, "submitted_at": "2018-01-04T14:50:24+00:00" }, { "id": 86656705, "user": "user_b08fb5f52ea1", "state": "COMMENTED", "body": null, "submitted_at": "2018-01-04T14:57:37+00:00" }, { "id": 86658793, "user": "user_b08fb5f52ea1", "state": "COMMENTED", "body": null, "submitted_at": "2018-01-04T15:04:32+00:00" }, { "id": 86691525, "user": "user_b08fb5f52ea1", "state": "COMMENTED", "body": null, "submitted_at": "2018-01-04T16:47:37+00:00" }, { "id": 86692500, "user": "user_b08fb5f52ea1", "state": "COMMENTED", "body": null, "submitted_at": "2018-01-04T16:50:51+00:00" }, { "id": 86778851, "user": "user_0fa58b6f3572", "state": "APPROVED", "body": null, "submitted_at": "2018-01-04T22:32:10+00:00" } ], "review_comments": [ { "id": 159154678, "user": "user_0fa58b6f3572", "body": "I'm not convinced this is going to be correct. I think having an `=` inside the parameter value is acceptable if it's quoted. We should probably then use `param.split('=', 1)` to ensure we only split on the first found =.", "path": "requests/utils.py", "line": null, "side": "RIGHT", "created_at": "2018-01-01T12:14:59+00:00" }, { "id": 159154683, "user": "user_0fa58b6f3572", "body": "Please add a space, e.g.,\n\n```py\nreturn content_type, params_dict\n```", "path": "requests/utils.py", "line": null, "side": "RIGHT", "created_at": "2018-01-01T12:15:19+00:00" }, { "id": 159154692, "user": "user_0fa58b6f3572", "body": "Why does this need to be an inner function? Why can't we define it at the module level as `_parse_header`?", "path": "requests/utils.py", "line": null, "side": "RIGHT", "created_at": "2018-01-01T12:15:41+00:00" }, { "id": 159159457, "user": "user_137c7bb40eac", "body": "Thanks for your suggestions.", "path": "requests/utils.py", "line": null, "side": "RIGHT", "created_at": "2018-01-01T16:53:10+00:00" }, { "id": 159159472, "user": "user_137c7bb40eac", "body": "Ill check it out. Thank you", "path": "requests/utils.py", "line": null, "side": "RIGHT", "created_at": "2018-01-01T16:54:22+00:00" }, { "id": 159433889, "user": "user_0fa58b6f3572", "body": "If `content_type` is checked above and this is a private function, do we need the guard at the top of the function above? If the check above is ever removed, we could end up with a `TypeError` when we effectively do `content_type, params = None`.", "path": "requests/utils.py", "line": 486, "side": "RIGHT", "created_at": "2018-01-03T14:16:56+00:00" }, { "id": 159434030, "user": "user_0fa58b6f3572", "body": "I don't think this is necessary. Can we do\n\n```py\ntokens = header.split(';', 1)\ncontent_type, params_list = tokens[0].strip(), tokens[1:]\nif len(params_list) < 1:\n return content_type, {}\nparams = params_list[0]\n```\n\nIf I understand correctly that's the effect of this otherwise. It's simple, clearer, and doesn't require us to string concatenation which results in a new allocation and isn't terribly efficient.\n\n```py\n>>> a = [1]\n>>> b, c = a[0], a[1:]\n>>> b, c\n(1, [])\n```", "path": "requests/utils.py", "line": null, "side": "RIGHT", "created_at": "2018-01-03T14:17:40+00:00" }, { "id": 159435111, "user": "user_0fa58b6f3572", "body": "The above said, if we weren't restricting it to split once we could simplify the code further and do:\n\n```\ntokens = header.split(';')\ncontent_type, params = tokens[0].strip(), tokens[1:]\nparams_dict = {}. # Using dict is actually slower than a dictionary literal. Weird but tru\nfor param in params:\n # ... What you have below\n\nreturn content_type, params_dict\n```", "path": "requests/utils.py", "line": null, "side": "RIGHT", "created_at": "2018-01-03T14:22:59+00:00" }, { "id": 159510147, "user": "user_137c7bb40eac", "body": "That is pretty nice. Didn't know a[1:] would not throw an index out of bounds... nice.", "path": "requests/utils.py", "line": null, "side": "RIGHT", "created_at": "2018-01-03T19:41:19+00:00" }, { "id": 159669261, "user": "user_b08fb5f52ea1", "body": "Can we not call `param = param.strip()` before the `if param` and save a call to `param.isspace()`?\n\nie Is this:\n```python\nfor param in params:\n param = param.strip()\n if param:\n # Continue here...\n```\nthe same as this\n```python\nfor param in params:\n if param and not param.isspace():\n param = param.strip()\n # Continue here...\n```\nin all situations?", "path": "requests/utils.py", "line": null, "side": "RIGHT", "created_at": "2018-01-04T14:50:24+00:00" }, { "id": 159671056, "user": "user_b08fb5f52ea1", "body": "Might be able to get rid of the list comprehension here by using `param.find('=')` and checking for a non-negative? Definitely would be faster. Something to the tune of:\n\n```python\nkey, value = param, True\nindex = param.find('=')\nif index != -1:\n key = param[:index].strip('\\'\" ')\n value = param[index+1:].strip('\\'\" ')\n```", "path": "requests/utils.py", "line": null, "side": "RIGHT", "created_at": "2018-01-04T14:57:37+00:00" }, { "id": 159672845, "user": "user_b08fb5f52ea1", "body": "Can you also add a test case with double-quotes around the value? ie: `boundary = \"something\";` should return `{'boundary': 'something'}`.", "path": "tests/test_utils.py", "line": null, "side": "RIGHT", "created_at": "2018-01-04T15:04:32+00:00" }, { "id": 159699818, "user": "user_b08fb5f52ea1", "body": "Can you remove the `slice()` usage here? Using bracket-slice notation is more readable and faster.\n\n`param[:index_of_equals]` and `param[index_of_equals+1:]`", "path": "requests/utils.py", "line": null, "side": "RIGHT", "created_at": "2018-01-04T16:47:37+00:00" }, { "id": 159700680, "user": "user_b08fb5f52ea1", "body": "Still would like to see a test-case containing this scenario.", "path": "tests/test_utils.py", "line": null, "side": "RIGHT", "created_at": "2018-01-04T16:50:50+00:00" } ], "meta": { "languages": [ "py", "rst" ], "touches_tests": true, "review_state_summary": { "CHANGES_REQUESTED": 2, "COMMENTED": 8, "APPROVED": 1 }, "meaningful_comment_count": 14, "has_approval": true, "has_changes_requested": true, "total_review_comments": 14 } } { "_id": "3f4eebd970b23d0e", "_schema_version": "1.0", "_cleaned_at": "2026-02-12T07:46:52.038957+00:00", "repo": "psf/requests", "repo_url": "https://github.com/psf/requests", "license_name": "Apache License 2.0", "license_spdx": "Apache-2.0", "pr_number": 4427, "title": "Use hostname not netloc", "body": "Fixes #4275 and fixes #4158 by [NAME_REDACTED]/IP to urllib's `proxy_bypass` function which was timing out further down in `socket.gethostbyname` when passed a hostname or IP that contained authentication credentials.\n\nWhile fixing the parameter passed to `proxy_bypass`, I also took the chance to replace other uses of `netloc` with `hostname` in the `should_bypass_function`.", "author": "user_f3356220b302", "created_at": "2017-12-12T15:08:10+00:00", "merged_at": "2018-01-16T14:07:26+00:00", "base_branch": "master", "head_branch": "4275-use-hostname-not-netloc", "additions": 37, "deletions": 11, "changed_files": 4, "files": [ { "filename": "AUTHORS.rst", "status": "modified", "additions": 1, "deletions": 0, "changes": 1, "patch": "@@ -182,3 +182,4 @@ Patches and Suggestions\n - [NAME_REDACTED] ([CONTRIBUTOR_REDACTED])\n - Nehal J Wani ([CONTRIBUTOR_REDACTED])\n - [NAME_REDACTED] ([CONTRIBUTOR_REDACTED])\n+- [NAME_REDACTED] ([CONTRIBUTOR_REDACTED])" }, { "filename": "HISTORY.rst", "status": "modified", "additions": 2, "deletions": 1, "changes": 3, "patch": "@@ -17,7 +17,8 @@ dev\n - Fixed issue where loading the default certificate bundle from a zip archive\n would raise an ``IOError``\n - Fixed issue with unexpected ``ImportError`` on windows system which do not support ``winreg`` module\n-\n+- DNS resolution in proxy bypass no longer includes the username and password in\n+ the request. This also fixes the issue of DNS queries failing on macOS.\n \n 2.18.4 (2017-08-15)\n +++++++++++++++++++" }, { "filename": "requests/utils.py", "status": "modified", "additions": 11, "deletions": 8, "changes": 19, "patch": "@@ -703,28 +703,31 @@ def should_bypass_proxies(url, no_proxy):\n no_proxy_arg = no_proxy\n if no_proxy is None:\n no_proxy = get_proxy('no_proxy')\n- netloc = urlparse(url).netloc\n+ parsed = urlparse(url)\n \n if no_proxy:\n # We need to check whether we match here. We need to see if we match\n- # the end of the netloc, both with and without the port.\n+ # the end of the hostname, both with and without the port.\n no_proxy = (\n host for host in no_proxy.replace(' ', '').split(',') if host\n )\n \n- ip = netloc.split(':')[0]\n- if is_ipv4_address(ip):\n+ if is_ipv4_address(parsed.hostname):\n for proxy_ip in no_proxy:\n if is_valid_cidr(proxy_ip):\n- if address_in_network(ip, proxy_ip):\n+ if address_in_network(parsed.hostname, proxy_ip):\n return True\n- elif ip == proxy_ip:\n+ elif parsed.hostname == proxy_ip:\n # If no_proxy ip was defined in plain IP notation instead of cidr notation &\n # matches the IP of the index\n return True\n else:\n+ host_with_port = parsed.hostname\n+ if parsed.port:\n+ host_with_port += ':{0}'.format(parsed.port)\n+\n for host in no_proxy:\n- if netloc.endswith(host) or netloc.split(':')[0].endswith(host):\n+ if parsed.hostname.endswith(host) or host_with_port.endswith(host):\n # The URL does match something in no_proxy, so we don't want\n # to apply the proxies on this URL.\n return True\n@@ -737,7 +740,7 @@ def should_bypass_proxies(url, no_proxy):\n # legitimate problems.\n with set_environ('no_proxy', no_proxy_arg):\n try:\n- bypass = proxy_bypass(netloc)\n+ bypass = proxy_bypass(parsed.hostname)\n except (TypeError, socket.gaierror):\n bypass = False" }, { "filename": "tests/test_utils.py", "status": "modified", "additions": 23, "deletions": 2, "changes": 25, "patch": "@@ -614,6 +614,7 @@ def test_urldefragauth(url, expected):\n ('http://172.16.1.1/', True),\n ('http://172.16.1.1:5000/', True),\n ('http://localhost.localdomain:5000/v1.0/', True),\n+ ('http://google.com:6000/', True),\n ('http://172.16.1.12/', False),\n ('http://172.16.1.12:5000/', False),\n ('http://google.com:5000/v1.0/', False),\n@@ -622,11 +623,31 @@ def test_should_bypass_proxies(url, expected, monkeypatch):\n \"\"\"Tests for function should_bypass_proxies to check if proxy\n can be bypassed or not\n \"\"\"\n- monkeypatch.setenv('no_proxy', '192.168.0.0/24,127.0.0.1,localhost.localdomain,172.16.1.1')\n- monkeypatch.setenv('NO_PROXY', '192.168.0.0/24,127.0.0.1,localhost.localdomain,172.16.1.1')\n+ monkeypatch.setenv('no_proxy', '192.168.0.0/24,127.0.0.1,localhost.localdomain,172.16.1.1, google.com:6000')\n+ monkeypatch.setenv('NO_PROXY', '192.168.0.0/24,127.0.0.1,localhost.localdomain,172.16.1.1, google.com:6000')\n assert should_bypass_proxies(url, no_proxy=None) == expected\n \n \n+[USER_REDACTED].mark.parametrize(\n+ 'url, expected', (\n+ ('http://172.16.1.1/', '172.16.1.1'),\n+ ('http://172.16.1.1:5000/', '172.16.1.1'),\n+ ('http://user:pass@172.16.1.1', '172.16.1.1'),\n+ ('http://user:pass@172.16.1.1:5000', '172.16.1.1'),\n+ ('http://hostname/', 'hostname'),\n+ ('http://hostname:5000/', 'hostname'),\n+ ('http://user:pass@hostname', 'hostname'),\n+ ('http://user:pass@hostname:5000', 'hostname'),\n+ ))\n+def test_should_bypass_proxies_pass_only_hostname(url, expected, mocker):\n+ \"\"\"The proxy_bypass function should be called with a hostname or IP without\n+ a port number or auth credentials.\n+ \"\"\"\n+ proxy_bypass = mocker.patch('requests.utils.proxy_bypass')\n+ should_bypass_proxies(url, no_proxy=None)\n+ proxy_bypass.assert_called_once_with(expected)\n+\n+\n [USER_REDACTED].mark.parametrize(\n 'cookiejar', (\n compat.cookielib.CookieJar()," } ], "reviews": [ { "id": 86685816, "user": "user_dbf2a999bd6d", "state": "DISMISSED", "body": "Thanks for contributing to Requests, [USER_REDACTED]! I think this looks pretty good from my perspective, it reduces the parsing we're having to do on our end which I think is probably a good thing.\n\nI did leave a couple brief notes on one line, but once those are addressed, I think we can consider merging this. That is barring any major concerns from another maintainer.\n\nAlso while you're addressing the other comment, would you mind adding an entry to our HISTORY.rst with your change, and squashing your commits? Thanks!", "submitted_at": "2018-01-04T16:35:21+00:00" }, { "id": 88987984, "user": "user_0fa58b6f3572", "state": "DISMISSED", "body": "This looks good to me.", "submitted_at": "2018-01-16T05:22:58+00:00" }, { "id": 89106146, "user": "user_0fa58b6f3572", "state": "APPROVED", "body": null, "submitted_at": "2018-01-16T14:07:21+00:00" } ], "review_comments": [ { "id": 159694979, "user": "user_dbf2a999bd6d", "body": "A couple notes here. The `port` attribute is either an `int` or `None`, which means a case like http://localhost being passed to `urlparse` would yield `localhost:None` here. While that's unlikely to affect matching, I'm not sure that's what we want to be doing.\n\nThe second thing is we're still planning to support python 2.6 until 3.0.0 is released which means this format statement won't work as is. We'll need to provide something along the lines of `{0}:{1}` instead to avoid the ValueError.", "path": "requests/utils.py", "line": null, "side": "RIGHT", "created_at": "2018-01-04T16:28:57+00:00" } ], "meta": { "languages": [ "py", "rst" ], "touches_tests": true, "review_state_summary": { "DISMISSED": 2, "APPROVED": 1 }, "meaningful_comment_count": 1, "has_approval": true, "has_changes_requested": false, "total_review_comments": 1 } } { "_id": "b3d3190a1b533428", "_schema_version": "1.0", "_cleaned_at": "2026-02-12T07:46:52.038957+00:00", "repo": "psf/requests", "repo_url": "https://github.com/psf/requests", "license_name": "Apache License 2.0", "license_spdx": "Apache-2.0", "pr_number": 4377, "title": "#4373, fix possible winreg value type difference", "body": null, "author": "user_d54e4af39804", "created_at": "2017-11-07T14:25:49+00:00", "merged_at": "2017-11-20T20:01:05+00:00", "base_branch": "master", "head_branch": "master", "additions": 10, "deletions": 3, "changed_files": 2, "files": [ { "filename": "requests/utils.py", "status": "modified", "additions": 4, "deletions": 2, "changes": 6, "patch": "@@ -52,8 +52,10 @@ def proxy_bypass_registry(host):\n try:\n internetSettings = winreg.OpenKey(winreg.HKEY_CURRENT_USER,\n r'Software\\Microsoft\\Windows\\CurrentVersion\\[NAME_REDACTED]')\n- proxyEnable = winreg.QueryValueEx(internetSettings,\n- 'ProxyEnable')[0]\n+ # ProxyEnable could be REG_SZ or REG_DWORD, normalizing it\n+ proxyEnable = int(winreg.QueryValueEx(internetSettings,\n+ 'ProxyEnable')[0])\n+ # ProxyOverride is almost always a string\n proxyOverride = winreg.QueryValueEx(internetSettings,\n 'ProxyOverride')[0]\n except OSError:" }, { "filename": "tests/test_utils.py", "status": "modified", "additions": 6, "deletions": 1, "changes": 7, "patch": "@@ -5,6 +5,7 @@\n import filecmp\n from io import BytesIO\n import zipfile\n+from collections import deque\n \n import pytest\n from requests import compat\n@@ -666,14 +667,17 @@ def Close(self):\n pass\n \n ie_settings = RegHandle()\n+ proxyEnableValues = deque([1, \"1\"])\n \n def OpenKey(key, subkey):\n return ie_settings\n \n def QueryValueEx(key, value_name):\n if key is ie_settings:\n if value_name == 'ProxyEnable':\n- return [1]\n+ # this could be a string (REG_SZ) or a 32-bit number (REG_DWORD)\n+ proxyEnableValues.rotate()\n+ return [proxyEnableValues[0]]\n elif value_name == 'ProxyOverride':\n return [override]\n \n@@ -684,6 +688,7 @@ def QueryValueEx(key, value_name):\n monkeypatch.setenv('NO_PROXY', '')\n monkeypatch.setattr(winreg, 'OpenKey', OpenKey)\n monkeypatch.setattr(winreg, 'QueryValueEx', QueryValueEx)\n+ assert should_bypass_proxies(url, None) == expected\n \n \n [USER_REDACTED].mark.parametrize(" } ], "reviews": [ { "id": 74899701, "user": "user_f068c71fd303", "state": "CHANGES_REQUESTED", "body": "Cool, looks plausible to me. Can you write some tests for each case? It's sufficient to monkeypatch `QueryValueEx` for these tests, as we never run on Windows.", "submitted_at": "2017-11-07T20:39:43+00:00" }, { "id": 75247587, "user": "user_f068c71fd303", "state": "COMMENTED", "body": null, "submitted_at": "2017-11-08T21:01:14+00:00" }, { "id": 75448574, "user": "user_d54e4af39804", "state": "COMMENTED", "body": null, "submitted_at": "2017-11-09T14:11:27+00:00" }, { "id": 77905403, "user": "user_f068c71fd303", "state": "APPROVED", "body": "Great, thanks for this!", "submitted_at": "2017-11-20T20:00:48+00:00" } ], "review_comments": [ { "id": 149795373, "user": "user_f068c71fd303", "body": "This is not sufficient, as it has never been used. However, you're right that this never actually tests anything, which isn't great. This was supposed to call `should_bypass_proxies`: want to add that call, and then parametrise this test based on the return value of `QueryValueEx` with `ProxyEnable`?", "path": "tests/test_utils.py", "line": null, "side": "RIGHT", "created_at": "2017-11-08T21:01:14+00:00" }, { "id": 149970998, "user": "user_d54e4af39804", "body": "Let me try adding some real assertions here. Need to find a Windows first, though.", "path": "tests/test_utils.py", "line": null, "side": "RIGHT", "created_at": "2017-11-09T14:11:27+00:00" } ], "meta": { "languages": [ "py" ], "touches_tests": true, "review_state_summary": { "CHANGES_REQUESTED": 1, "COMMENTED": 2, "APPROVED": 1 }, "meaningful_comment_count": 2, "has_approval": true, "has_changes_requested": true, "total_review_comments": 2 } } { "_id": "79227f53b6069679", "_schema_version": "1.0", "_cleaned_at": "2026-02-12T07:46:52.038957+00:00", "repo": "psf/requests", "repo_url": "https://github.com/psf/requests", "license_name": "Apache License 2.0", "license_spdx": "Apache-2.0", "pr_number": 4356, "title": "Check if host is invalid for proxy", "body": "According to RFC3986, the authority section can be empty for a given URL,\nhowever, for a proxy URL, it shouldn't be. This patch adds a check to verify\nthat the parsed URL will have a valid host before creating the proxy manager.\n\nFixes #4353", "author": "user_d3616b6e671d", "created_at": "2017-10-26T14:41:40+00:00", "merged_at": "2017-11-15T22:16:34+00:00", "base_branch": "master", "head_branch": "fix-4353", "additions": 26, "deletions": 2, "changed_files": 5, "files": [ { "filename": "AUTHORS.rst", "status": "modified", "additions": 1, "deletions": 0, "changes": 1, "patch": "@@ -180,3 +180,4 @@ Patches and Suggestions\n - [NAME_REDACTED] <[EMAIL_REDACTED]> ([CONTRIBUTOR_REDACTED])\n - [NAME_REDACTED] <[EMAIL_REDACTED]> ([CONTRIBUTOR_REDACTED])\n - [NAME_REDACTED] ([CONTRIBUTOR_REDACTED])\n+- Nehal J Wani ([CONTRIBUTOR_REDACTED])" }, { "filename": "HISTORY.rst", "status": "modified", "additions": 1, "deletions": 0, "changes": 1, "patch": "@@ -9,6 +9,7 @@ dev\n **Improvements**\n \n - Warn user about possible slowdown when using cryptography version < 1.3.4\n+- Check for invalid host in proxy URL, before forwarding request to adapter.\n \n **Bugfixes**" }, { "filename": "requests/adapters.py", "status": "modified", "additions": 6, "deletions": 1, "changes": 7, "patch": "@@ -13,6 +13,7 @@\n \n from urllib3.poolmanager import PoolManager, proxy_from_url\n from urllib3.response import HTTPResponse\n+from urllib3.util import parse_url\n from urllib3.util import Timeout as TimeoutSauce\n from urllib3.util.retry import Retry\n from urllib3.exceptions import ClosedPoolError\n@@ -34,7 +35,7 @@\n from .structures import CaseInsensitiveDict\n from .cookies import extract_cookies_to_jar\n from .exceptions import (ConnectionError, ConnectTimeout, ReadTimeout, SSLError,\n- ProxyError, RetryError, InvalidSchema)\n+ ProxyError, RetryError, InvalidSchema, InvalidProxyURL)\n from .auth import _basic_auth_str\n \n try:\n@@ -300,6 +301,10 @@ def get_connection(self, url, proxies=None):\n \n if proxy:\n proxy = prepend_scheme_if_needed(proxy, 'http')\n+ proxy_url = parse_url(proxy)\n+ if not proxy_url.host:\n+ raise InvalidProxyURL(\"Please check proxy URL. It is malformed\"\n+ \" and could be missing the host.\")\n proxy_manager = self.proxy_manager_for(proxy)\n conn = proxy_manager.connection_from_url(url)\n else:" }, { "filename": "requests/exceptions.py", "status": "modified", "additions": 4, "deletions": 0, "changes": 4, "patch": "@@ -85,6 +85,10 @@ class InvalidHeader(RequestException, ValueError):\n \"\"\"The header value provided was somehow invalid.\"\"\"\n \n \n+class InvalidProxyURL(InvalidURL):\n+ \"\"\"The proxy URL provided is invalid.\"\"\"\n+\n+\n class ChunkedEncodingError(RequestException):\n \"\"\"The server declared chunked encoding but sent an invalid chunk.\"\"\"" }, { "filename": "tests/test_requests.py", "status": "modified", "additions": 14, "deletions": 1, "changes": 15, "patch": "@@ -23,7 +23,7 @@\n from requests.exceptions import (\n ConnectionError, ConnectTimeout, InvalidSchema, InvalidURL,\n MissingSchema, ReadTimeout, Timeout, RetryError, TooManyRedirects,\n- ProxyError, InvalidHeader, UnrewindableBodyError, SSLError)\n+ ProxyError, InvalidHeader, UnrewindableBodyError, SSLError, InvalidProxyURL)\n from requests.models import PreparedRequest\n from requests.structures import CaseInsensitiveDict\n from requests.sessions import SessionRedirectMixin\n@@ -526,6 +526,19 @@ def test_proxy_error(self):\n with pytest.raises(ProxyError):\n requests.get('http://localhost:1', proxies={'http': 'non-resolvable-address'})\n \n+ def test_proxy_error_on_bad_url(self, httpbin, httpbin_secure):\n+ with pytest.raises(InvalidProxyURL):\n+ requests.get(httpbin_secure(), proxies={'https': 'http:/badproxyurl:3128'})\n+\n+ with pytest.raises(InvalidProxyURL):\n+ requests.get(httpbin(), proxies={'http': 'http://:8080'})\n+\n+ with pytest.raises(InvalidProxyURL):\n+ requests.get(httpbin_secure(), proxies={'https': 'https://'})\n+\n+ with pytest.raises(InvalidProxyURL):\n+ requests.get(httpbin(), proxies={'http': 'http:///example.com:8080'})\n+\n def test_basicauth_with_netrc(self, httpbin):\n auth = ('user', 'pass')\n wrong_auth = ('wronguser', 'wrongpass')" } ], "reviews": [ { "id": 72223686, "user": "user_dbf2a999bd6d", "state": "CHANGES_REQUESTED", "body": "[USER_REDACTED] thanks for contributing to Requests! I've left a couple notes below that I'd like to see addressed before we can look at merging this.\n\nWe'll also want to wait for a glance from [USER_REDACTED] since he may have ideas about how he wanted this implemented.", "submitted_at": "2017-10-26T14:58:32+00:00" }, { "id": 72227336, "user": "user_dbf2a999bd6d", "state": "COMMENTED", "body": null, "submitted_at": "2017-10-26T15:01:56+00:00" }, { "id": 72233666, "user": "user_d3616b6e671d", "state": "COMMENTED", "body": null, "submitted_at": "2017-10-26T15:18:20+00:00" }, { "id": 72237224, "user": "user_d3616b6e671d", "state": "COMMENTED", "body": null, "submitted_at": "2017-10-26T15:27:17+00:00" }, { "id": 72238954, "user": "user_dbf2a999bd6d", "state": "COMMENTED", "body": null, "submitted_at": "2017-10-26T15:31:53+00:00" }, { "id": 72240086, "user": "user_dbf2a999bd6d", "state": "COMMENTED", "body": null, "submitted_at": "2017-10-26T15:34:47+00:00" }, { "id": 72241331, "user": "user_0fa58b6f3572", "state": "CHANGES_REQUESTED", "body": null, "submitted_at": "2017-10-26T15:38:31+00:00" }, { "id": 72295290, "user": "user_d3616b6e671d", "state": "COMMENTED", "body": null, "submitted_at": "2017-10-26T18:27:20+00:00" }, { "id": 72295426, "user": "user_d3616b6e671d", "state": "COMMENTED", "body": null, "submitted_at": "2017-10-26T18:27:44+00:00" }, { "id": 72296191, "user": "user_dbf2a999bd6d", "state": "CHANGES_REQUESTED", "body": "One last nit and I think we're set from my end.\n\nWe'll also want a final sign off from [USER_REDACTED] to make sure his issues have been sufficiently addressed.", "submitted_at": "2017-10-26T18:32:34+00:00" }, { "id": 72300871, "user": "user_dbf2a999bd6d", "state": "CHANGES_REQUESTED", "body": null, "submitted_at": "2017-10-26T18:45:07+00:00" }, { "id": 72308189, "user": "user_d3616b6e671d", "state": "COMMENTED", "body": null, "submitted_at": "2017-10-26T19:10:12+00:00" }, { "id": 72308240, "user": "user_d3616b6e671d", "state": "COMMENTED", "body": null, "submitted_at": "2017-10-26T19:10:20+00:00" }, { "id": 72703298, "user": "user_dbf2a999bd6d", "state": "DISMISSED", "body": "I think this looks good to me. Thanks [USER_REDACTED]!", "submitted_at": "2017-10-29T16:58:12+00:00" }, { "id": 75008882, "user": "user_dbf2a999bd6d", "state": "DISMISSED", "body": "Thanks [USER_REDACTED]! Since we haven't heard back from [USER_REDACTED] and it appears his concerns have been addressed I think this is good to go. Would you mind adding a small HISTORY entry and, if you'd like, add yourself to the AUTHORS file too.", "submitted_at": "2017-11-08T07:33:27+00:00" }, { "id": 75024231, "user": "user_0fa58b6f3572", "state": "CHANGES_REQUESTED", "body": null, "submitted_at": "2017-11-08T08:53:21+00:00" }, { "id": 75072176, "user": "user_d3616b6e671d", "state": "COMMENTED", "body": null, "submitted_at": "2017-11-08T11:54:07+00:00" }, { "id": 75966553, "user": "user_dbf2a999bd6d", "state": "COMMENTED", "body": null, "submitted_at": "2017-11-12T18:12:55+00:00" }, { "id": 75966613, "user": "user_dbf2a999bd6d", "state": "CHANGES_REQUESTED", "body": "I left a [comment](https://github.com/requests/requests/pull/4356#discussion_r150418262) above, I'd prefer to see answered before merging.", "submitted_at": "2017-11-12T18:15:09+00:00" }, { "id": 76180744, "user": "user_914d3c3c4b66", "state": "COMMENTED", "body": null, "submitted_at": "2017-11-13T17:18:08+00:00" }, { "id": 76765349, "user": "user_0fa58b6f3572", "state": "COMMENTED", "body": null, "submitted_at": "2017-11-15T12:27:10+00:00" }, { "id": 76794454, "user": "user_d3616b6e671d", "state": "COMMENTED", "body": null, "submitted_at": "2017-11-15T14:14:38+00:00" }, { "id": 76898321, "user": "user_0fa58b6f3572", "state": "APPROVED", "body": null, "submitted_at": "2017-11-15T19:16:19+00:00" }, { "id": 76949450, "user": "user_dbf2a999bd6d", "state": "APPROVED", "body": null, "submitted_at": "2017-11-15T22:16:06+00:00" } ], "review_comments": [ { "id": 147167624, "user": "user_dbf2a999bd6d", "body": "Let's make this error message a bit clearer and say why the URL is invalid.", "path": "requests/adapters.py", "line": null, "side": "RIGHT", "created_at": "2017-10-26T14:53:26+00:00" }, { "id": 147168545, "user": "user_dbf2a999bd6d", "body": "It may be easier to split this into its own test. Otherwise, let's at least add a comment stating why this should fail differently than the one above.", "path": "tests/test_requests.py", "line": null, "side": "RIGHT", "created_at": "2017-10-26T14:55:24+00:00" }, { "id": 147170615, "user": "user_dbf2a999bd6d", "body": "You also don't need to wrap the Exception instance in parens after `raise`.\n\ni.e.\n```python\nraise ProxyError(\"URL for proxy is invalid: {}\".format(proxy))\n```", "path": "requests/adapters.py", "line": null, "side": "RIGHT", "created_at": "2017-10-26T15:01:55+00:00" }, { "id": 147175634, "user": "user_d3616b6e671d", "body": "To gauge the exact reason is a bit tricky. Because, several things can trigger this code path. It's not always a missing host. It could also just be typos like:\n```\n- missing '/' in http://\n- additional '/' after http://\n```", "path": "requests/adapters.py", "line": null, "side": "RIGHT", "created_at": "2017-10-26T15:18:20+00:00" }, { "id": 147178600, "user": "user_d3616b6e671d", "body": "I added 4 test cases in the new commit as a different test.", "path": "tests/test_requests.py", "line": null, "side": "RIGHT", "created_at": "2017-10-26T15:27:17+00:00" }, { "id": 147180137, "user": "user_dbf2a999bd6d", "body": "[USER_REDACTED] we prefer to avoid making requests live servers from the test suite. Can you please use the httpbin fixture like the other tests? Thanks!", "path": "tests/test_requests.py", "line": null, "side": "RIGHT", "created_at": "2017-10-26T15:31:53+00:00" }, { "id": 147181141, "user": "user_dbf2a999bd6d", "body": "So I get that it isn't completely clear what's causing this error but *something* in the URL will be causing our parser to think the host doesn't exist. Steering the user in that direction seems better than an ambiguous invalidity.", "path": "requests/adapters.py", "line": null, "side": "RIGHT", "created_at": "2017-10-26T15:34:47+00:00" }, { "id": 147182221, "user": "user_0fa58b6f3572", "body": "This is really not a helpful message. Instead it should probably say that the proxy URL was missing the host and cannot be used. The URL should be checked. We likely also do not want to include the proxy URL in the exception message because that my have sensitive credential information and we don't want to accidentally leak that on behalf of the user", "path": "requests/adapters.py", "line": null, "side": "RIGHT", "created_at": "2017-10-26T15:38:12+00:00" }, { "id": 147182291, "user": "user_0fa58b6f3572", "body": "+1 to [USER_REDACTED]'s request", "path": "tests/test_requests.py", "line": null, "side": "RIGHT", "created_at": "2017-10-26T15:38:28+00:00" }, { "id": 147227900, "user": "user_d3616b6e671d", "body": "Okay, I've updated the tests to use httpbin", "path": "tests/test_requests.py", "line": null, "side": "RIGHT", "created_at": "2017-10-26T18:27:20+00:00" }, { "id": 147228021, "user": "user_d3616b6e671d", "body": "Updated the error message.", "path": "requests/adapters.py", "line": null, "side": "RIGHT", "created_at": "2017-10-26T18:27:43+00:00" }, { "id": 147228652, "user": "user_dbf2a999bd6d", "body": "Could you end this last sentence with a period?", "path": "requests/adapters.py", "line": null, "side": "RIGHT", "created_at": "2017-10-26T18:30:02+00:00" }, { "id": 147232636, "user": "user_dbf2a999bd6d", "body": "Sorry, one more note. It would probably be good to make sure we're testing with a more common looking host too. Just so we're disambiguating between what could be a valid path (`/idontexist`).\ne.g.\n```Python\nhttp:///example.com:8080\n```", "path": "tests/test_requests.py", "line": null, "side": "RIGHT", "created_at": "2017-10-26T18:44:48+00:00" }, { "id": 147239057, "user": "user_d3616b6e671d", "body": "Sure, done.", "path": "requests/adapters.py", "line": null, "side": "RIGHT", "created_at": "2017-10-26T19:10:11+00:00" }, { "id": 147239096, "user": "user_d3616b6e671d", "body": "Updated.", "path": "tests/test_requests.py", "line": null, "side": "RIGHT", "created_at": "2017-10-26T19:10:20+00:00" }, { "id": 149605850, "user": "user_0fa58b6f3572", "body": "Why inherit from `ValueError` here? Is this so folks can catch `ValueError` across all versions of requests (before and after this fix)? If so, I think it might be better to just make this inherit from `ProxyError` and allow folks to do `except (InvalidProxyURL, ValueError):` in their code to catch both.", "path": "requests/exceptions.py", "line": null, "side": "RIGHT", "created_at": "2017-11-08T08:52:21+00:00" }, { "id": 149647598, "user": "user_d3616b6e671d", "body": "Okay, makes sense. I have updated the PR.", "path": "requests/exceptions.py", "line": null, "side": "RIGHT", "created_at": "2017-11-08T11:54:07+00:00" }, { "id": 150418262, "user": "user_dbf2a999bd6d", "body": "Sorry, I missed this comment when it was requested. [USER_REDACTED], I think we may want the `ValueError` here.\n\nAll of our other \"Invalid*\" exceptions inherit from `ValueError` because they're legitimate syntax/value errors. Having it be only `ProxyError` is awkward because this isn't actually a `ConnectionError`, it's raised before anything is sent. If anything this is closer to our `InvalidURL` exception.", "path": "requests/exceptions.py", "line": null, "side": "RIGHT", "created_at": "2017-11-12T18:12:55+00:00" }, { "id": 150606218, "user": "user_914d3c3c4b66", "body": "This explanation for reverting \n\n```python\nclass InvalidProxyURL(ProxyError):\n```\n\nback to \n\n```python\nclass InvalidProxyURL(ProxyError, ValueError):\n```\n\nmakes sense to me.", "path": "requests/exceptions.py", "line": null, "side": "RIGHT", "created_at": "2017-11-13T17:18:08+00:00" }, { "id": 151111826, "user": "user_0fa58b6f3572", "body": "I have to say that I'm on the fence.\n\nFor one thing, I don't think we should ever have been inheriting from `ValueError` except in cases where backwards compatibility was an issue. I suspect we started inheriting from `ValueError` so old code would continue to work without users having to update things. Once we did that the first time, it became a pattern that people copied and pasted. In general, I'll say it seems like a bad pattern to follow.\n\nWith that said, this can be resolved by [NAME_REDACTED] from `InvalidURL` as you pointed out. This is a special case of an invalid URL and you're right, [USER_REDACTED], that it isn't a `ConnectionError`.\n\nSo if we change this to inherit from `InvalidURL` that seems to be the best way to move forward [USER_REDACTED]", "path": "requests/exceptions.py", "line": null, "side": "RIGHT", "created_at": "2017-11-15T12:27:09+00:00" }, { "id": 151136517, "user": "user_d3616b6e671d", "body": "I have made the change to make `InvalidProxyURL` inherit from `InvalidURL`", "path": "requests/exceptions.py", "line": null, "side": "RIGHT", "created_at": "2017-11-15T14:14:37+00:00" } ], "meta": { "languages": [ "py", "rst" ], "touches_tests": true, "review_state_summary": { "CHANGES_REQUESTED": 6, "COMMENTED": 14, "DISMISSED": 2, "APPROVED": 2 }, "meaningful_comment_count": 20, "has_approval": true, "has_changes_requested": true, "total_review_comments": 21 } } { "_id": "a1a95a47ce3e7cad", "_schema_version": "1.0", "_cleaned_at": "2026-02-12T07:46:52.054596+00:00", "repo": "psf/requests", "repo_url": "https://github.com/psf/requests", "license_name": "Apache License 2.0", "license_spdx": "Apache-2.0", "pr_number": 4352, "title": "Add something to the docs about hooks on Session()", "body": "I had to work this out by [NAME_REDACTED] for `Session` – better to put it front-and-centre in the docs.", "author": "user_f2d49c73befa", "created_at": "2017-10-23T07:31:21+00:00", "merged_at": "2017-10-24T18:50:03+00:00", "base_branch": "master", "head_branch": "hooks-on-sessions", "additions": 26, "deletions": 2, "changed_files": 1, "files": [ { "filename": "docs/user/advanced.rst", "status": "modified", "additions": 26, "deletions": 2, "changes": 28, "patch": "@@ -436,7 +436,7 @@ You can assign a hook function on a per-request basis by passing a\n ``{hook_name: callback_function}`` dictionary to the ``hooks`` request\n parameter::\n \n- hooks=dict(response=print_url)\n+ hooks={'response': print_url}\n \n That ``callback_function`` will receive a chunk of data as its first\n argument.\n@@ -452,12 +452,36 @@ If the callback function returns a value, it is assumed that it is to\n replace the data that was passed in. If the function doesn't return\n anything, nothing else is effected.\n \n+::\n+\n+ def record_hook(r, *args, **kwargs):\n+ r.hook_called = True\n+ return r\n+\n Let's print some request method arguments at runtime::\n \n- >>> requests.get('http://httpbin.org', hooks=dict(response=print_url))\n+ >>> requests.get('http://httpbin.org', hooks={'response': print_url})\n+ http://httpbin.org\n+ \n+\n+You can add multiple hooks to a single request. Let's call two hooks at once::\n+\n+ >>> r = requests.get('http://httpbin.org', hooks={'response': [print_url, record_hook]})\n+ >>> r.hook_called\n+ True\n+\n+You can also add hooks to a ``Session`` instance. Any hooks you add will then\n+be called on every request made to the session. For example::\n+\n+ >>> s = requests.Session()\n+ >>> s.hooks['response'].append(print_url)\n+ >>> s.get('http://httpbin.org')\n http://httpbin.org\n \n \n+A ``Session`` can have multiple hooks, which will be called in the order\n+they are added.\n+\n .. _custom-auth:\n \n [NAME_REDACTED]" } ], "reviews": [ { "id": 71147894, "user": "user_0fa58b6f3572", "state": "CHANGES_REQUESTED", "body": "We need to be more clear about what a session's hooks dictionary looks like. This should also be clarified above by [NAME_REDACTED] also provide *multiple* hooks. For example\n\n```py\nrequests.get('http://httpbinorg', hooks={'response': [hook0, hook1]})\n```\n\nMaybe we should also stop using `dict()` since that's so incredibly slow.", "submitted_at": "2017-10-23T11:31:31+00:00" }, { "id": 71602380, "user": "user_0fa58b6f3572", "state": "APPROVED", "body": "I'm happy with this.", "submitted_at": "2017-10-24T17:21:22+00:00" }, { "id": 71631708, "user": "user_dbf2a999bd6d", "state": "APPROVED", "body": "I am too, thanks [USER_REDACTED]!", "submitted_at": "2017-10-24T18:49:51+00:00" } ], "review_comments": [ { "id": 146236577, "user": "user_0fa58b6f3572", "body": "This should be:\n\n```\ns.hooks['response'].append(print_url)\n```\n\nAs we keep a list of hooks", "path": "docs/user/advanced.rst", "line": null, "side": "RIGHT", "created_at": "2017-10-23T11:30:14+00:00" } ], "meta": { "languages": [ "rst" ], "touches_tests": false, "review_state_summary": { "CHANGES_REQUESTED": 1, "APPROVED": 2 }, "meaningful_comment_count": 1, "has_approval": true, "has_changes_requested": true, "total_review_comments": 1 } } { "_id": "0f1314b11e16e758", "_schema_version": "1.0", "_cleaned_at": "2026-02-12T07:46:52.054596+00:00", "repo": "psf/requests", "repo_url": "https://github.com/psf/requests", "license_name": "Apache License 2.0", "license_spdx": "Apache-2.0", "pr_number": 4332, "title": "Warn about possible slowness on older versions of pyOpenSSL", "body": "Give a warning when `cryptography < 1.3.4` and `pyOpenSSL < 16.0.0` as discussed in #4309", "author": "user_95e34d61a2fe", "created_at": "2017-10-10T17:24:31+00:00", "merged_at": "2017-10-14T15:41:03+00:00", "base_branch": "master", "head_branch": "pyopenssl-warning", "additions": 18, "deletions": 0, "changed_files": 3, "files": [ { "filename": "AUTHORS.rst", "status": "modified", "additions": 1, "deletions": 0, "changes": 1, "patch": "@@ -178,3 +178,4 @@ Patches and Suggestions\n - [NAME_REDACTED] ([CONTRIBUTOR_REDACTED])\n - [NAME_REDACTED] ([CONTRIBUTOR_REDACTED])\n - [NAME_REDACTED] <[EMAIL_REDACTED]> ([CONTRIBUTOR_REDACTED])\n+- [NAME_REDACTED] <[EMAIL_REDACTED]> ([CONTRIBUTOR_REDACTED])" }, { "filename": "HISTORY.rst", "status": "modified", "additions": 2, "deletions": 0, "changes": 2, "patch": "@@ -8,6 +8,8 @@ dev\n \n **Improvements**\n \n+- Warn user about possible slowdown when using cryptography version < 1.3.4\n+\n **Bugfixes**\n \n - Parsing empty ``Link`` headers with ``parse_header_links()`` no longer return one bogus entry" }, { "filename": "requests/__init__.py", "status": "modified", "additions": 15, "deletions": 0, "changes": 15, "patch": "@@ -71,6 +71,17 @@ def check_compatibility(urllib3_version, chardet_version):\n assert patch >= 2\n \n \n+def _check_cryptography(cryptography_version):\n+ # cryptography < 1.3.4\n+ try:\n+ cryptography_version = list(map(int, cryptography_version.split('.')))\n+ except ValueError:\n+ return\n+\n+ if cryptography_version < [1, 3, 4]:\n+ warning = 'Old version of cryptography ({0}) may cause slowdown.'.format(cryptography_version)\n+ warnings.warn(warning, RequestsDependencyWarning)\n+\n # Check imported dependencies for compatibility.\n try:\n check_compatibility(urllib3.__version__, chardet.__version__)\n@@ -83,6 +94,10 @@ def check_compatibility(urllib3_version, chardet_version):\n try:\n from urllib3.contrib import pyopenssl\n pyopenssl.inject_into_urllib3()\n+\n+ # Check cryptography version\n+ from cryptography import __version__ as cryptography_version\n+ _check_cryptography(cryptography_version)\n except ImportError:\n pass" } ], "reviews": [ { "id": 68441978, "user": "user_0fa58b6f3572", "state": "COMMENTED", "body": null, "submitted_at": "2017-10-10T22:10:30+00:00" }, { "id": 68442346, "user": "user_0fa58b6f3572", "state": "COMMENTED", "body": null, "submitted_at": "2017-10-10T22:12:12+00:00" }, { "id": 68442559, "user": "user_0fa58b6f3572", "state": "COMMENTED", "body": null, "submitted_at": "2017-10-10T22:13:15+00:00" }, { "id": 68442619, "user": "user_0fa58b6f3572", "state": "COMMENTED", "body": null, "submitted_at": "2017-10-10T22:13:33+00:00" }, { "id": 68475789, "user": "user_dbf2a999bd6d", "state": "COMMENTED", "body": null, "submitted_at": "2017-10-11T02:07:58+00:00" }, { "id": 68476495, "user": "user_dbf2a999bd6d", "state": "CHANGES_REQUESTED", "body": null, "submitted_at": "2017-10-11T02:15:25+00:00" }, { "id": 68685641, "user": "user_dbf2a999bd6d", "state": "CHANGES_REQUESTED", "body": "Thanks for getting this updated [USER_REDACTED]! This is moving in the right direction. I've left a few more notes inline that we may want to address.", "submitted_at": "2017-10-11T17:30:43+00:00" }, { "id": 69263704, "user": "user_dbf2a999bd6d", "state": "CHANGES_REQUESTED", "body": "This is looking much better! I left one last minor comment. If you could also squash your commits into one, that would be really helpful. Thanks for taking the time to work through this, [USER_REDACTED]!", "submitted_at": "2017-10-13T15:27:29+00:00" }, { "id": 69281220, "user": "user_dbf2a999bd6d", "state": "COMMENTED", "body": null, "submitted_at": "2017-10-13T16:24:13+00:00" }, { "id": 69281421, "user": "user_dbf2a999bd6d", "state": "COMMENTED", "body": null, "submitted_at": "2017-10-13T16:24:56+00:00" }, { "id": 69285707, "user": "user_dbf2a999bd6d", "state": "DISMISSED", "body": "This looks good to me, thanks [USER_REDACTED]!", "submitted_at": "2017-10-13T16:42:25+00:00" }, { "id": 69380745, "user": "user_f068c71fd303", "state": "CHANGES_REQUESTED", "body": null, "submitted_at": "2017-10-14T02:12:17+00:00" }, { "id": 69382737, "user": "user_f068c71fd303", "state": "CHANGES_REQUESTED", "body": "Cool, looks good. Mind updating the changelog? Then we should be good to go.", "submitted_at": "2017-10-14T03:51:07+00:00" }, { "id": 69394767, "user": "user_f068c71fd303", "state": "APPROVED", "body": "Cool, thanks a bunch!", "submitted_at": "2017-10-14T15:40:16+00:00" } ], "review_comments": [ { "id": 143866538, "user": "user_0fa58b6f3572", "body": "This should be a private function. We really shouldn't be exposing this as part of our API.", "path": "requests/__init__.py", "line": null, "side": "RIGHT", "created_at": "2017-10-10T22:10:30+00:00" }, { "id": 143866848, "user": "user_0fa58b6f3572", "body": "I feel like there's a bifurcation. Below we check that `'OpenSSL' in sys.modules` why not do this check there too? Further, is there another `OpenSSL` module that we might import that isn't `pyOpenSSL`? What is this check protecting against?", "path": "requests/__init__.py", "line": null, "side": "RIGHT", "created_at": "2017-10-10T22:12:12+00:00" }, { "id": 143867037, "user": "user_0fa58b6f3572", "body": "This will always be false since no relesaed version of cryptography is `16.0.0` or higher. I think this was meant to be `pyopenssl_version`", "path": "requests/__init__.py", "line": null, "side": "RIGHT", "created_at": "2017-10-10T22:13:15+00:00" }, { "id": 143867083, "user": "user_0fa58b6f3572", "body": "Is the issue for old versions of `pyOpenSSL` or `cryptography`.", "path": "requests/__init__.py", "line": null, "side": "RIGHT", "created_at": "2017-10-10T22:13:33+00:00" }, { "id": 143897083, "user": "user_dbf2a999bd6d", "body": "To clarify, I believe the comment says we want to verify `pyOpenSSL` is installed, and if it is check that `cryptography` is at least 1.3.4 which is our minimum requirement. We haven't done any testing to see how far back you need to go with `cryptography` for the slowdown to occur, but 1.3.4 should be sufficient.", "path": "requests/__init__.py", "line": null, "side": "RIGHT", "created_at": "2017-10-11T02:07:58+00:00" }, { "id": 143897716, "user": "user_dbf2a999bd6d", "body": "I also don't think we actually need the check to be this complicated. We're already checking for `pyOpenSSL` with our `inject_pyopenssl_into_urllib3` above. A simple helper function that checks cryptography's version meets or exceeds our threshold (supposedly 1.3.4), and otherwise displays a warning, should be sufficient.", "path": "requests/__init__.py", "line": null, "side": "RIGHT", "created_at": "2017-10-11T02:15:19+00:00" }, { "id": 144078723, "user": "user_dbf2a999bd6d", "body": "This should really be _check_cryptography because that's what we're concerned about.", "path": "requests/__init__.py", "line": null, "side": "RIGHT", "created_at": "2017-10-11T17:22:36+00:00" }, { "id": 144079219, "user": "user_dbf2a999bd6d", "body": "So we don't really care about the version of pyOpenSSL, the only reason it's significant is 16.0 is where a version constraint for cryptography > 1.0 is put in place. Let's remove this check and just launch the warning if cryptography doesn't meet our requirement. That's the source of the slowdown.", "path": "requests/__init__.py", "line": null, "side": "RIGHT", "created_at": "2017-10-11T17:24:24+00:00" }, { "id": 144080444, "user": "user_dbf2a999bd6d", "body": "No need to pass both of these. We don't actually care about the pyOpenSSL version as I stated above, just that it's being imported for urllib3.\n\nWe can do the check with something like:\n```\nfrom cryptography import __version__ as cryptography_version\n```\n\nThis allows us to have to only worry about the import error.", "path": "requests/__init__.py", "line": null, "side": "RIGHT", "created_at": "2017-10-11T17:28:27+00:00" }, { "id": 144080654, "user": "user_dbf2a999bd6d", "body": "Let's move this into the `_check_cryptography` function.", "path": "requests/__init__.py", "line": null, "side": "RIGHT", "created_at": "2017-10-11T17:29:09+00:00" }, { "id": 144584188, "user": "user_dbf2a999bd6d", "body": "One petty nit and we're set here I think. Mind lowecasing the cryptography package name here, below in the warning message, and in the try/except comment?", "path": "requests/__init__.py", "line": null, "side": "RIGHT", "created_at": "2017-10-13T15:23:17+00:00" }, { "id": 144599048, "user": "user_dbf2a999bd6d", "body": "Sorry before we squash this import is also not being used anymore.", "path": "requests/__init__.py", "line": null, "side": "RIGHT", "created_at": "2017-10-13T16:24:13+00:00" }, { "id": 144599222, "user": "user_dbf2a999bd6d", "body": "And cryptography is still capitalized here.", "path": "requests/__init__.py", "line": null, "side": "RIGHT", "created_at": "2017-10-13T16:24:56+00:00" }, { "id": 144683540, "user": "user_f068c71fd303", "body": "This check will break if for any reason cryptography has a non-numerical version string. As in other places, we should aim to tolerate that by [NAME_REDACTED] version numbers will be fine.", "path": "requests/__init__.py", "line": null, "side": "RIGHT", "created_at": "2017-10-14T02:12:14+00:00" } ], "meta": { "languages": [ "py", "rst" ], "touches_tests": false, "review_state_summary": { "COMMENTED": 7, "CHANGES_REQUESTED": 5, "DISMISSED": 1, "APPROVED": 1 }, "meaningful_comment_count": 14, "has_approval": true, "has_changes_requested": true, "total_review_comments": 14 } } { "_id": "17aa3b2b3d524e14", "_schema_version": "1.0", "_cleaned_at": "2026-02-12T07:46:52.054596+00:00", "repo": "psf/requests", "repo_url": "https://github.com/psf/requests", "license_name": "Apache License 2.0", "license_spdx": "Apache-2.0", "pr_number": 4328, "title": "Remove redundant Python 2.6 stuff", "body": "Same as https://github.com/requests/requests/pull/4326 but for the proposed/3.0.0 branch.\n\nThe good news is nearly everything was already in this branch from https://github.com/requests/requests/pull/4118, except for tidying up some OrderedDict compat stuff.\n\nAlso, pytest>=3.0.0 is required for the Python 3.3 build, otherwise:\n```\npy.test -n 8 --boxed --junitxml=report.xml\nTraceback (most recent call last):\n File \"/home/travis/virtualenv/python3.3.6/bin/py.test\", line 11, in \n sys.exit(main())\n File \"/home/travis/virtualenv/python3.3.6/lib/python3.3/site-packages/_pytest/config.py\", line 39, in main\n config = _prepareconfig(args, plugins)\n File \"/home/travis/virtualenv/python3.3.6/lib/python3.3/site-packages/_pytest/config.py\", line 118, in _prepareconfig\n pluginmanager=pluginmanager, args=args)\n File \"/home/travis/virtualenv/python3.3.6/lib/python3.3/site-packages/_pytest/vendored_packages/pluggy.py\", line 724, in __call__\n return self._hookexec(self, self._nonwrappers + self._wrappers, kwargs)\n File \"/home/travis/virtualenv/python3.3.6/lib/python3.3/site-packages/_pytest/vendored_packages/pluggy.py\", line 338, in _hookexec\n return self._inner_hookexec(hook, methods, kwargs)\n File \"/home/travis/virtualenv/python3.3.6/lib/python3.3/site-packages/_pytest/vendored_packages/pluggy.py\", line 333, in \n _MultiCall(methods, kwargs, hook.spec_opts).execute()\n File \"/home/travis/virtualenv/python3.3.6/lib/python3.3/site-packages/_pytest/vendored_packages/pluggy.py\", line 595, in execute\n return _wrapped_call(hook_impl.function(*args), self.execute)\n File \"/home/travis/virtualenv/python3.3.6/lib/python3.3/site-packages/_pytest/vendored_packages/pluggy.py\", line 249, in _wrapped_call\n wrap_controller.send(call_outcome)\n File \"/home/travis/virtualenv/python3.3.6/lib/python3.3/site-packages/_pytest/helpconfig.py\", line 28, in pytest_cmdline_parse\n config = outcome.get_result()\n File \"/home/travis/virtualenv/python3.3.6/lib/python3.3/site-packages/_pytest/vendored_packages/pluggy.py\", line 278, in get_result\n raise ex[1].with_traceback(ex[2])\n File \"/home/travis/virtualenv/python3.3.6/lib/python3.3/site-packages/_pytest/vendored_packages/pluggy.py\", line 264, in __init__\n self.result = func()\n File \"/home/travis/virtualenv/python3.3.6/lib/python3.3/site-packages/_pytest/vendored_packages/pluggy.py\", line 596, in execute\n res = hook_impl.function(*args)\n File \"/home/travis/virtualenv/python3.3.6/lib/python3.3/site-packages/_pytest/config.py\", line 861, in pytest_cmdline_parse\n self.parse(args)\n File \"/home/travis/virtualenv/python3.3.6/lib/python3.3/site-packages/_pytest/config.py\", line 966, in parse\n self._preparse(args, addopts=addopts)\n File \"/home/travis/virtualenv/python3.3.6/lib/python3.3/site-packages/_pytest/config.py\", line 927, in _preparse\n self.pluginmanager.load_setuptools_entrypoints(\"pytest11\")\n File \"/home/travis/virtualenv/python3.3.6/lib/python3.3/site-packages/_pytest/vendored_packages/pluggy.py\", line 501, in load_setuptools_entrypoints\n plugin = ep.load()\n File \"/home/travis/virtualenv/python3.3.6/lib/python3.3/site-packages/pkg_resources/__init__.py\", line 2404, in load\n self.require(*args, **kwargs)\n File \"/home/travis/virtualenv/python3.3.6/lib/python3.3/site-packages/pkg_resources/__init__.py\", line 2427, in require\n items = working_set.resolve(reqs, env, installer, extras=self.extras)\n File \"/home/travis/virtualenv/python3.3.6/lib/python3.3/site-packages/pkg_resources/__init__.py\", line 872, in resolve\n raise VersionConflict(dist, req).with_context(dependent_req)\npkg_resources.VersionConflict: (pytest 2.9.2 (/home/travis/virtualenv/python3.3.6/lib/python3.3/site-packages), Requirement.parse('pytest>=3.0.0'))\n```\nhttps://travis-ci.org/hugovk/requests/jobs/284048190\n\nThe other CI failures are related to cookies and also occur in latest master and fresh builds of proposed/3.0.0.", "author": "user_eef3c6ba6f45", "created_at": "2017-10-06T06:09:11+00:00", "merged_at": "2017-10-19T16:58:54+00:00", "base_branch": "proposed/3.0.0", "head_branch": "rm-2.6", "additions": 15, "deletions": 15, "changed_files": 7, "files": [ { "filename": "3.0-HISTORY.rst", "status": "modified", "additions": 3, "deletions": 0, "changes": 3, "patch": "@@ -3,6 +3,9 @@\n \n - Support for Python 2.6 has been dropped.\n \n+ - The ``OrderedDict`` import no longer exists in compat.py because it is part\n+ of ``collections`` in Python 2.7 and newer.\n+\n - Simplified logic for determining Content-Length and Transfer-Encoding.\n Requests will now avoid setting both headers on the same request, and\n raise an exception if this is done manually by a user." }, { "filename": "AUTHORS.rst", "status": "modified", "additions": 1, "deletions": 0, "changes": 1, "patch": "@@ -182,3 +182,4 @@ Patches and Suggestions\n - [NAME_REDACTED] ([CONTRIBUTOR_REDACTED])\n - [NAME_REDACTED] <[EMAIL_REDACTED]> ([CONTRIBUTOR_REDACTED])\n - [NAME_REDACTED] <[EMAIL_REDACTED]> ([CONTRIBUTOR_REDACTED])\n+- Hugo van Kemenade ([CONTRIBUTOR_REDACTED])" }, { "filename": "requests/compat.py", "status": "modified", "additions": 0, "deletions": 3, "changes": 3, "patch": "@@ -39,8 +39,6 @@\n from Cookie import Morsel\n from StringIO import StringIO\n \n- from urllib3.packages.ordered_dict import OrderedDict\n-\n builtin_str = str\n bytes = str\n str = unicode\n@@ -54,7 +52,6 @@\n from http import cookiejar as cookielib\n from http.cookies import Morsel\n from io import StringIO\n- from collections import OrderedDict\n \n builtin_str = str\n str = str" }, { "filename": "requests/sessions.py", "status": "modified", "additions": 2, "deletions": 2, "changes": 4, "patch": "@@ -10,11 +10,11 @@\n import os\n import platform\n import time\n-from collections import Mapping\n+from collections import Mapping, OrderedDict\n from datetime import timedelta\n \n from .auth import _basic_auth_str\n-from .compat import cookielib, OrderedDict, urljoin, urlparse, is_py3, str\n+from .compat import cookielib, urljoin, urlparse, is_py3, str\n from .cookies import (\n cookiejar_from_dict, extract_cookies_to_jar, RequestsCookieJar,\n merge_cookies, _copy_cookie_jar)" }, { "filename": "requests/structures.py", "status": "modified", "additions": 1, "deletions": 3, "changes": 4, "patch": "@@ -9,8 +9,6 @@\n \n import collections\n \n-from .compat import OrderedDict\n-\n \n class CaseInsensitiveDict(collections.MutableMapping):\n \"\"\"A case-insensitive ``dict``-like object.\n@@ -40,7 +38,7 @@ class CaseInsensitiveDict(collections.MutableMapping):\n \"\"\"\n \n def __init__(self, data=None, **kwargs):\n- self._store = OrderedDict()\n+ self._store = collections.OrderedDict()\n if data is None:\n data = {}\n self.update(data, **kwargs)" }, { "filename": "requests/utils.py", "status": "modified", "additions": 2, "deletions": 2, "changes": 4, "patch": "@@ -26,7 +26,7 @@\n from ._internal_utils import to_native_string\n from .compat import parse_http_list as _parse_list_header\n from .compat import (\n- quote, urlparse, bytes, str, OrderedDict, unquote, getproxies,\n+ quote, urlparse, bytes, str, unquote, getproxies,\n proxy_bypass, urlunparse, basestring, integer_types, is_py2, is_py3,\n proxy_bypass_environment, getproxies_environment)\n from .cookies import cookiejar_from_dict\n@@ -238,7 +238,7 @@ def from_key_val_list(value):\n if isinstance(value, (str, bytes, bool, int)):\n raise ValueError('cannot encode objects that are not 2-tuples')\n \n- return OrderedDict(value)\n+ return collections.OrderedDict(value)\n \n \n def to_key_val_list(value):" }, { "filename": "tests/test_requests.py", "status": "modified", "additions": 6, "deletions": 5, "changes": 11, "patch": "@@ -18,7 +18,7 @@\n from requests.auth import HTTPDigestAuth, _basic_auth_str\n from requests.compat import (\n Morsel, cookielib, getproxies, str, urlparse,\n- builtin_str, OrderedDict)\n+ builtin_str)\n from requests.cookies import (\n cookiejar_from_dict, morsel_to_cookie)\n from requests.exceptions import (\n@@ -144,7 +144,8 @@ def test_params_are_added_before_fragment(self, url, expected):\n assert request.url == expected\n \n def test_params_original_order_is_preserved_by_default(self):\n- param_ordered_dict = OrderedDict((('z', 1), ('a', 1), ('k', 1), ('d', 1)))\n+ param_ordered_dict = collections.OrderedDict(\n+ (('z', 1), ('a', 1), ('k', 1), ('d', 1)))\n session = requests.Session()\n request = requests.Request('GET', 'http://example.com/', params=param_ordered_dict)\n prep = session.prepare_request(request)\n@@ -539,11 +540,11 @@ def test_headers_on_session_with_None_are_not_sent(self, httpbin):\n def test_headers_preserve_order(self, httpbin):\n \"\"\"Preserve order when headers provided as OrderedDict.\"\"\"\n ses = requests.Session()\n- ses.headers = OrderedDict()\n+ ses.headers = collections.OrderedDict()\n ses.headers['Accept-Encoding'] = 'identity'\n ses.headers['First'] = '1'\n ses.headers['Second'] = '2'\n- headers = OrderedDict([('Third', '3'), ('Fourth', '4')])\n+ headers = collections.OrderedDict([('Third', '3'), ('Fourth', '4')])\n headers['Fifth'] = '5'\n headers['Second'] = '222'\n req = requests.Request('GET', httpbin('get'), headers=headers)\n@@ -2103,7 +2104,7 @@ def test_chunked_upload_with_manually_set_content_length_header_raises_error(sel\n \"\"\"Ensure that if a user manually sets a content length header, when\n the data is chunked, that an InvalidHeader error is raised.\n \"\"\"\n- data = (i for i in [b'a', b'b', b'c']) \n+ data = (i for i in [b'a', b'b', b'c'])\n url = httpbin('post')\n with pytest.raises(InvalidHeader):\n r = requests.post(url, data=data, headers={'Content-Length': 'foo'})" } ], "reviews": [ { "id": 69429140, "user": "user_dbf2a999bd6d", "state": "CHANGES_REQUESTED", "body": "Alright, I think this is sensible since we were only using the special `OrdredDict` import for 2.6 and already import `collections` in most places.\n\nA few final notes, you'll need to rebase this branch onto the current `proposed/3.0.0` branch and wait for a patched version of `pytest-httpbin` to be released so we can get green tests. We could also use a CHANGELOG entry stating that the `OrderedDict` import no longer exists in `compat.py`. \n\nI'd also encourage you to add yourself to the AUTHORS.rst for this branch if you'd like.\n\nIf anyone else from [USER_REDACTED]/core want to give this a glace, I think this is about ready to go.\n\nThanks again for putting this together, [USER_REDACTED]!", "submitted_at": "2017-10-15T21:21:36+00:00" }, { "id": 69442792, "user": "user_f068c71fd303", "state": "DISMISSED", "body": "Looks good. Merge when you feel satisfied [USER_REDACTED].", "submitted_at": "2017-10-16T02:20:23+00:00" }, { "id": 69907607, "user": "user_eef3c6ba6f45", "state": "COMMENTED", "body": null, "submitted_at": "2017-10-17T14:37:28+00:00" }, { "id": 69914467, "user": "user_dbf2a999bd6d", "state": "CHANGES_REQUESTED", "body": "Found one more thing in the final pass.", "submitted_at": "2017-10-17T14:57:55+00:00" }, { "id": 70609425, "user": "user_dbf2a999bd6d", "state": "APPROVED", "body": null, "submitted_at": "2017-10-19T16:58:00+00:00" } ], "review_comments": [ { "id": 144731278, "user": "user_dbf2a999bd6d", "body": "We've removed the requirement for python 3.3 in the 3.0.0 branch, so lets save this change for a separate PR if it's really needed. (Although, I think the requirements.txt was removed on master and that should now be reflected on this branch)", "path": "requirements.txt", "line": null, "side": "RIGHT", "created_at": "2017-10-15T20:43:15+00:00" }, { "id": 145150639, "user": "user_eef3c6ba6f45", "body": "I've removed this commit and rebased onto current proposed/3.0.0 and update AUTHORS.rst on this branch.", "path": "requirements.txt", "line": null, "side": "RIGHT", "created_at": "2017-10-17T14:37:28+00:00" }, { "id": 145156547, "user": "user_dbf2a999bd6d", "body": "It looks like this is a cli example. We don't want the \"collection\" lead here. The interpreter is just showing the returned objects repr. Same with the line below this.", "path": "requests/utils.py", "line": null, "side": "RIGHT", "created_at": "2017-10-17T14:55:54+00:00" } ], "meta": { "languages": [ "py", "rst" ], "touches_tests": true, "review_state_summary": { "CHANGES_REQUESTED": 2, "DISMISSED": 1, "COMMENTED": 1, "APPROVED": 1 }, "meaningful_comment_count": 3, "has_approval": true, "has_changes_requested": true, "total_review_comments": 3 } } { "_id": "73a6b2ad93824e17", "_schema_version": "1.0", "_cleaned_at": "2026-02-12T07:46:52.054596+00:00", "repo": "psf/requests", "repo_url": "https://github.com/psf/requests", "license_name": "Apache License 2.0", "license_spdx": "Apache-2.0", "pr_number": 4240, "title": "Adding header name to exception", "body": "Adds the name of the header to the invalid header exception raised on TypeError.\n\nFixes #4239", "author": "user_b509fb1beff4", "created_at": "2017-08-11T19:49:57+00:00", "merged_at": "2017-08-12T14:41:27+00:00", "base_branch": "master", "head_branch": "master", "additions": 9, "deletions": 5, "changed_files": 3, "files": [ { "filename": "HISTORY.rst", "status": "modified", "additions": 1, "deletions": 0, "changes": 1, "patch": "@@ -7,6 +7,7 @@ dev\n +++\n \n **Improvements**\n+- Error messages for invalid headers now include the header name for easier debugging\n \n **Bugfixes**" }, { "filename": "requests/utils.py", "status": "modified", "additions": 2, "deletions": 2, "changes": 4, "patch": "@@ -868,8 +868,8 @@ def check_header_validity(header):\n if not pat.match(value):\n raise InvalidHeader(\"Invalid return character or leading space in header: %s\" % name)\n except TypeError:\n- raise InvalidHeader(\"Header value %s must be of type str or bytes, \"\n- \"not %s\" % (value, type(value)))\n+ raise InvalidHeader(\"Value for header {%s: %s} must be of type str or \"\n+ \"bytes, not %s\" % (name, value, type(value)))\n \n \n def urldefragauth(url):" }, { "filename": "tests/test_requests.py", "status": "modified", "additions": 6, "deletions": 3, "changes": 9, "patch": "@@ -1401,14 +1401,17 @@ def test_header_value_not_str(self, httpbin):\n headers_list = {'baz': ['foo', 'bar']}\n \n # Test for int\n- with pytest.raises(InvalidHeader):\n+ with pytest.raises(InvalidHeader) as excinfo:\n r = requests.get(httpbin('get'), headers=headers_int)\n+ assert 'foo' in str(excinfo.value)\n # Test for dict\n- with pytest.raises(InvalidHeader):\n+ with pytest.raises(InvalidHeader) as excinfo:\n r = requests.get(httpbin('get'), headers=headers_dict)\n+ assert 'bar' in str(excinfo.value)\n # Test for list\n- with pytest.raises(InvalidHeader):\n+ with pytest.raises(InvalidHeader) as excinfo:\n r = requests.get(httpbin('get'), headers=headers_list)\n+ assert 'baz' in str(excinfo.value)\n \n def test_header_no_return_chars(self, httpbin):\n \"\"\"Ensure that a header containing return character sequences raise an" } ], "reviews": [ { "id": 55893144, "user": "user_dbf2a999bd6d", "state": "DISMISSED", "body": "I left a suggestion on possible wording changes but this looks good to me. Thanks [USER_REDACTED]!", "submitted_at": "2017-08-11T19:58:55+00:00" }, { "id": 55894487, "user": "user_b509fb1beff4", "state": "COMMENTED", "body": null, "submitted_at": "2017-08-11T20:03:14+00:00" }, { "id": 55897035, "user": "user_dbf2a999bd6d", "state": "CHANGES_REQUESTED", "body": "One minor tweak and I think this will be set 😊", "submitted_at": "2017-08-11T20:17:54+00:00" }, { "id": 55897611, "user": "user_b509fb1beff4", "state": "COMMENTED", "body": null, "submitted_at": "2017-08-11T20:19:18+00:00" }, { "id": 55939315, "user": "user_f068c71fd303", "state": "CHANGES_REQUESTED", "body": "Cool, looks good! Mind adding a note to `HISTORY.rst`? When we have that I'll merge. 😁", "submitted_at": "2017-08-12T08:21:18+00:00" }, { "id": 55943632, "user": "user_dbf2a999bd6d", "state": "DISMISSED", "body": null, "submitted_at": "2017-08-12T13:20:22+00:00" }, { "id": 55945182, "user": "user_f068c71fd303", "state": "APPROVED", "body": null, "submitted_at": "2017-08-12T14:41:19+00:00" } ], "review_comments": [ { "id": 132771941, "user": "user_dbf2a999bd6d", "body": "This may read a little clear if the name and/or value are wrapped in quotes.\n\nPerhaps even adjusting the wording to something like \"Header {name}: {value} must have a value of string or bytes, not {type}\".", "path": "requests/utils.py", "line": null, "side": "RIGHT", "created_at": "2017-08-11T19:56:58+00:00" }, { "id": 132773022, "user": "user_b509fb1beff4", "body": "Makes sense, I'll add that in really quick. Thanks for the feedback!", "path": "requests/utils.py", "line": null, "side": "RIGHT", "created_at": "2017-08-11T20:03:14+00:00" }, { "id": 132775147, "user": "user_dbf2a999bd6d", "body": "Mind adding a space after the colon?", "path": "requests/utils.py", "line": null, "side": "RIGHT", "created_at": "2017-08-11T20:16:09+00:00" }, { "id": 132775260, "user": "user_dbf2a999bd6d", "body": "Mind adding a space after the colon?", "path": "requests/utils.py", "line": null, "side": "RIGHT", "created_at": "2017-08-11T20:17:01+00:00" }, { "id": 132775607, "user": "user_b509fb1beff4", "body": "On it!", "path": "requests/utils.py", "line": null, "side": "RIGHT", "created_at": "2017-08-11T20:19:18+00:00" } ], "meta": { "languages": [ "py", "rst" ], "touches_tests": true, "review_state_summary": { "DISMISSED": 2, "COMMENTED": 2, "CHANGES_REQUESTED": 2, "APPROVED": 1 }, "meaningful_comment_count": 4, "has_approval": true, "has_changes_requested": true, "total_review_comments": 5 } } { "_id": "41f005187aeebba7", "_schema_version": "1.0", "_cleaned_at": "2026-02-12T07:46:52.054596+00:00", "repo": "psf/requests", "repo_url": "https://github.com/psf/requests", "license_name": "Apache License 2.0", "license_spdx": "Apache-2.0", "pr_number": 4183, "title": "Fix help ssl check", "body": "This will resolve the test failures discovered in #4182. We were retrieving the `OPENSSL_VERSION_NUMBER` from the system `ssl` module in all cases before now. This attribute doesn't exist in Python 2.6 causing new tests for the `info()` method to fail. This patch will return an empty value for Python 2.6 since we don't seem to have a way to reliably check the openssl version.\n\n[USER_REDACTED] [USER_REDACTED], I've pushed this branch up to the requests repo directly, so feel free to chop this up or do anything you feel is necessary to get #4182 moving. I don't know that the provided test is especially useful, but it does show that the fix here works.", "author": "user_dbf2a999bd6d", "created_at": "2017-07-03T23:47:34+00:00", "merged_at": "2017-07-04T08:16:03+00:00", "base_branch": "master", "head_branch": "fix_help_ssl_check", "additions": 28, "deletions": 3, "changed_files": 2, "files": [ { "filename": "requests/help.py", "status": "modified", "additions": 7, "deletions": 3, "changes": 10, "patch": "@@ -85,12 +85,16 @@ def info():\n 'version': getattr(cryptography, '__version__', ''),\n }\n \n+ # OPENSSL_VERSION_NUMBER doesn't exist in the Python 2.6 ssl module.\n+ system_ssl = getattr(ssl, 'OPENSSL_VERSION_NUMBER', None)\n+ system_ssl_info = {\n+ 'version': '%x' % system_ssl if system_ssl is not None else ''\n+ }\n+\n return {\n 'platform': platform_info,\n 'implementation': implementation_info,\n- 'system_ssl': {\n- 'version': '%x' % ssl.OPENSSL_VERSION_NUMBER,\n- },\n+ 'system_ssl': system_ssl_info,\n 'using_pyopenssl': pyopenssl is not None,\n 'pyOpenSSL': pyopenssl_info,\n 'urllib3': urllib3_info," }, { "filename": "tests/test_help.py", "status": "added", "additions": 21, "deletions": 0, "changes": 21, "patch": "@@ -0,0 +1,21 @@\n+# -*- encoding: utf-8\n+\n+import sys\n+\n+import pytest\n+\n+from requests.help import info\n+\n+\n+[USER_REDACTED].mark.skipif(sys.version_info[:2] != (2,6), reason=\"Only run on Python 2.6\")\n+def test_system_ssl_py26():\n+ \"\"\"OPENSSL_VERSION_NUMBER isn't provided in Python 2.6, verify we don't\n+ blow up in this case.\n+ \"\"\"\n+ assert info()['system_ssl'] == {'version': ''}\n+\n+\n+[USER_REDACTED].mark.skipif(sys.version_info < (2,7), reason=\"Only run on Python 2.7+\")\n+def test_system_ssl():\n+ \"\"\"Verify we're actually setting system_ssl when it should be available.\"\"\"\n+ assert info()['system_ssl']['version'] != ''" } ], "reviews": [ { "id": 47778346, "user": "user_f2d49c73befa", "state": "COMMENTED", "body": null, "submitted_at": "2017-07-04T06:03:19+00:00" }, { "id": 47781938, "user": "user_dbf2a999bd6d", "state": "COMMENTED", "body": null, "submitted_at": "2017-07-04T06:35:46+00:00" }, { "id": 47782711, "user": "user_f068c71fd303", "state": "APPROVED", "body": "This looks sensible, thanks [USER_REDACTED]!", "submitted_at": "2017-07-04T06:41:56+00:00" } ], "review_comments": [ { "id": 125394533, "user": "user_f2d49c73befa", "body": "This test file would also pass if there was never anything interesting in `system_ssl`.\n\nHow about a second test that asserts that on Pythons >2.6, the `version` key is non-empty?", "path": "tests/test_help.py", "line": 15, "side": "RIGHT", "created_at": "2017-07-04T06:03:19+00:00" }, { "id": 125397878, "user": "user_dbf2a999bd6d", "body": "Yep, that seems reasonable if we're going to be testing for this specifically. I've added that into the test commit, if we decide to merge that part of the PR.", "path": "tests/test_help.py", "line": 15, "side": "RIGHT", "created_at": "2017-07-04T06:35:46+00:00" } ], "meta": { "languages": [ "py" ], "touches_tests": true, "review_state_summary": { "COMMENTED": 2, "APPROVED": 1 }, "meaningful_comment_count": 2, "has_approval": true, "has_changes_requested": false, "total_review_comments": 2 } } { "_id": "b29b1d852e87fdee", "_schema_version": "1.0", "_cleaned_at": "2026-02-12T07:46:52.054596+00:00", "repo": "psf/requests", "repo_url": "https://github.com/psf/requests", "license_name": "Apache License 2.0", "license_spdx": "Apache-2.0", "pr_number": 4182, "title": "Add idna version info to requests.help", "body": "Resolves #4180.", "author": "user_f2d49c73befa", "created_at": "2017-07-03T22:32:02+00:00", "merged_at": "2017-07-27T20:54:10+00:00", "base_branch": "master", "head_branch": "idna-version", "additions": 26, "deletions": 0, "changed_files": 3, "files": [ { "filename": "HISTORY.rst", "status": "modified", "additions": 2, "deletions": 0, "changes": 2, "patch": "@@ -8,6 +8,8 @@ dev\n \n **Improvements**\n \n+- Running ``$ python -m requests.help`` now includes the installed version of idna.\n+\n **Bugfixes**\n \n 2.18.2 (2017-07-25)" }, { "filename": "requests/help.py", "status": "modified", "additions": 5, "deletions": 0, "changes": 5, "patch": "@@ -6,6 +6,7 @@\n import sys\n import ssl\n \n+import idna\n import urllib3\n import chardet\n \n@@ -84,6 +85,9 @@ def info():\n cryptography_info = {\n 'version': getattr(cryptography, '__version__', ''),\n }\n+ idna_info = {\n+ 'version': getattr(idna, '__version__', ''),\n+ }\n \n # OPENSSL_VERSION_NUMBER doesn't exist in the Python 2.6 ssl module.\n system_ssl = getattr(ssl, 'OPENSSL_VERSION_NUMBER', None)\n@@ -100,6 +104,7 @@ def info():\n 'urllib3': urllib3_info,\n 'chardet': chardet_info,\n 'cryptography': cryptography_info,\n+ 'idna': idna_info,\n 'requests': {\n 'version': requests_version,\n }," }, { "filename": "tests/test_help.py", "status": "modified", "additions": 19, "deletions": 0, "changes": 19, "patch": "@@ -19,3 +19,22 @@ def test_system_ssl_py26():\n def test_system_ssl():\n \"\"\"Verify we're actually setting system_ssl when it should be available.\"\"\"\n assert info()['system_ssl']['version'] != ''\n+\n+\n+class VersionedPackage(object):\n+ def __init__(self, version):\n+ self.__version__ = version\n+\n+\n+def test_idna_without_version_attribute(mocker):\n+ \"\"\"Older versions of IDNA don't provide a __version__ attribute, verify\n+ that if we have such a package, we don't blow up.\n+ \"\"\"\n+ mocker.patch('requests.help.idna', new=None)\n+ assert info()['idna'] == {'version': ''}\n+\n+\n+def test_idna_with_version_attribute(mocker):\n+ \"\"\"Verify we're actually setting idna version when it should be available.\"\"\"\n+ mocker.patch('requests.help.idna', new=VersionedPackage('2.6'))\n+ assert info()['idna'] == {'version': '2.6'}" } ], "reviews": [ { "id": 52686045, "user": "user_dbf2a999bd6d", "state": "CHANGES_REQUESTED", "body": null, "submitted_at": "2017-07-27T15:05:10+00:00" }, { "id": 52777941, "user": "user_f2d49c73befa", "state": "COMMENTED", "body": null, "submitted_at": "2017-07-27T20:33:54+00:00" }, { "id": 52779584, "user": "user_dbf2a999bd6d", "state": "APPROVED", "body": "Alright, this looks good to me. Thanks [USER_REDACTED]! ✨", "submitted_at": "2017-07-27T20:39:54+00:00" } ], "review_comments": [ { "id": 129868051, "user": "user_dbf2a999bd6d", "body": "Sorry, one final note and I think we're set here. Could we get the second underscore for the closing dunder on version (`__version_` -> `__version__`). Once that's done I think I'm happy with this.", "path": "tests/test_help.py", "line": null, "side": "RIGHT", "created_at": "2017-07-27T15:04:29+00:00" }, { "id": 129951850, "user": "user_f2d49c73befa", "body": "Fixed.", "path": "tests/test_help.py", "line": null, "side": "RIGHT", "created_at": "2017-07-27T20:33:54+00:00" } ], "meta": { "languages": [ "py", "rst" ], "touches_tests": true, "review_state_summary": { "CHANGES_REQUESTED": 1, "COMMENTED": 1, "APPROVED": 1 }, "meaningful_comment_count": 1, "has_approval": true, "has_changes_requested": true, "total_review_comments": 2 } } { "_id": "ad526d0143a7af61", "_schema_version": "1.0", "_cleaned_at": "2026-02-12T07:46:52.054596+00:00", "repo": "psf/requests", "repo_url": "https://github.com/psf/requests", "license_name": "Apache License 2.0", "license_spdx": "Apache-2.0", "pr_number": 4173, "title": "Pass pool_kwargs rather than updating connection_pool_kw", "body": "This addresses an issue where making HTTPS through proxies used the\ndefault urllib3 connection pool settings.\n\nfixes #3633", "author": "user_3fcef11dbef3", "created_at": "2017-06-24T23:12:46+00:00", "merged_at": "2017-06-27T13:54:40+00:00", "base_branch": "proposed/3.0.0", "head_branch": "https-proxy-issue", "additions": 270, "deletions": 79, "changed_files": 2, "files": [ { "filename": "requests/adapters.py", "status": "modified", "additions": 72, "deletions": 79, "changes": 151, "patch": "@@ -10,10 +10,6 @@\n \n import os.path\n import socket\n-try:\n- from threading import RLock\n-except ImportError: # threading is an optional module and may not be present.\n- from dummy_threading import RLock\n \n from urllib3.poolmanager import PoolManager, proxy_from_url\n from urllib3.response import HTTPResponse\n@@ -53,6 +49,67 @@ def SOCKSProxyManager(*args, **kwargs):\n DEFAULT_POOL_TIMEOUT = None\n \n \n+def _pool_kwargs(verify, cert):\n+ \"\"\"Create a dictionary of keyword arguments to pass to a\n+ :class:`PoolManager ` with the\n+ necessary SSL configuration.\n+\n+ :param verify: Whether we should actually verify the certificate;\n+ optionally a path to a CA certificate bundle or\n+ directory of CA certificates.\n+ :param cert: The path to the client certificate and key, if any.\n+ This can either be the path to the certificate and\n+ key concatenated in a single file, or as a tuple of\n+ (cert_file, key_file).\n+ \"\"\"\n+ pool_kwargs = {}\n+ if verify:\n+\n+ cert_loc = None\n+\n+ # Allow self-specified cert location.\n+ if verify is not True:\n+ cert_loc = verify\n+\n+ if not cert_loc:\n+ cert_loc = DEFAULT_CA_BUNDLE_PATH\n+\n+ if not cert_loc or not os.path.exists(cert_loc):\n+ raise IOError(\"Could not find a suitable TLS CA certificate bundle, \"\n+ \"invalid path: {0}\".format(cert_loc))\n+\n+ pool_kwargs['cert_reqs'] = 'CERT_REQUIRED'\n+\n+ if not os.path.isdir(cert_loc):\n+ pool_kwargs['ca_certs'] = cert_loc\n+ pool_kwargs['ca_cert_dir'] = None\n+ else:\n+ pool_kwargs['ca_cert_dir'] = cert_loc\n+ pool_kwargs['ca_certs'] = None\n+ else:\n+ pool_kwargs['cert_reqs'] = 'CERT_NONE'\n+ pool_kwargs['ca_certs'] = None\n+ pool_kwargs['ca_cert_dir'] = None\n+\n+ if cert:\n+ if not isinstance(cert, basestring):\n+ pool_kwargs['cert_file'] = cert[0]\n+ pool_kwargs['key_file'] = cert[1]\n+ else:\n+ pool_kwargs['cert_file'] = cert\n+ pool_kwargs['key_file'] = None\n+\n+ cert_file = pool_kwargs['cert_file']\n+ key_file = pool_kwargs['key_file']\n+ if cert_file and not os.path.exists(cert_file):\n+ raise IOError(\"Could not find the TLS certificate file, \"\n+ \"invalid path: {0}\".format(cert_file))\n+ if key_file and not os.path.exists(key_file):\n+ raise IOError(\"Could not find the TLS key file, \"\n+ \"invalid path: {0}\".format(key_file))\n+ return pool_kwargs\n+\n+\n class BaseAdapter(object):\n \"\"\"The Base Transport Adapter\"\"\"\n \n@@ -126,7 +183,6 @@ def __init__(self, pool_connections=DEFAULT_POOLSIZE,\n self._pool_connections = pool_connections\n self._pool_maxsize = pool_maxsize\n self._pool_block = pool_block\n- self._pool_kw_lock = RLock()\n \n self.init_poolmanager(pool_connections, pool_maxsize, block=pool_block)\n \n@@ -139,7 +195,6 @@ def __setstate__(self, state):\n # self.poolmanager uses a lambda function, which isn't pickleable.\n self.proxy_manager = {}\n self.config = {}\n- self._pool_kw_lock = RLock()\n \n for attr, value in state.items():\n setattr(self, attr, value)\n@@ -204,65 +259,6 @@ def proxy_manager_for(self, proxy, **proxy_kwargs):\n \n return manager\n \n- def _update_poolmanager_ssl_kw(self, verify, cert):\n- \"\"\"Update the :class:`PoolManager `\n- connection_pool_kw with the necessary SSL configuration. This method\n- should not be called from user code, and is only exposed for use when\n- subclassing the :class:`HTTPAdapter `.\n-\n- :param verify: Whether we should actually verify the certificate;\n- optionally a path to a CA certificate bundle or\n- directory of CA certificates.\n- :param cert: The path to the client certificate and key, if any.\n- This can either be the path to the certificate and\n- key concatenated in a single file, or as a tuple of\n- (cert_file, key_file).\n- \"\"\"\n- if verify:\n-\n- cert_loc = None\n-\n- # Allow self-specified cert location.\n- if verify is not True:\n- cert_loc = verify\n-\n- if not cert_loc:\n- cert_loc = DEFAULT_CA_BUNDLE_PATH\n-\n- if not cert_loc or not os.path.exists(cert_loc):\n- raise IOError(\"Could not find a suitable TLS CA certificate bundle, \"\n- \"invalid path: {0}\".format(cert_loc))\n-\n- self.poolmanager.connection_pool_kw['cert_reqs'] = 'CERT_REQUIRED'\n-\n- if not os.path.isdir(cert_loc):\n- self.poolmanager.connection_pool_kw['ca_certs'] = cert_loc\n- self.poolmanager.connection_pool_kw['ca_cert_dir'] = None\n- else:\n- self.poolmanager.connection_pool_kw['ca_cert_dir'] = cert_loc\n- self.poolmanager.connection_pool_kw['ca_certs'] = None\n- else:\n- self.poolmanager.connection_pool_kw['cert_reqs'] = 'CERT_NONE'\n- self.poolmanager.connection_pool_kw['ca_certs'] = None\n- self.poolmanager.connection_pool_kw['ca_cert_dir'] = None\n-\n- if cert:\n- if not isinstance(cert, basestring):\n- self.poolmanager.connection_pool_kw['cert_file'] = cert[0]\n- self.poolmanager.connection_pool_kw['key_file'] = cert[1]\n- else:\n- self.poolmanager.connection_pool_kw['cert_file'] = cert\n- self.poolmanager.connection_pool_kw['key_file'] = None\n-\n- cert_file = self.poolmanager.connection_pool_kw['cert_file']\n- key_file = self.poolmanager.connection_pool_kw['key_file']\n- if cert_file and not os.path.exists(cert_file):\n- raise IOError(\"Could not find the TLS certificate file, \"\n- \"invalid path: {0}\".format(cert_file))\n- if key_file and not os.path.exists(key_file):\n- raise IOError(\"Could not find the TLS key file, \"\n- \"invalid path: {0}\".format(key_file))\n-\n def build_response(self, req, resp):\n \"\"\"Builds a :class:`Response ` object from a urllib3\n response. This should not be called from user code, and is only exposed\n@@ -309,21 +305,18 @@ def get_connection(self, url, proxies=None, verify=None, cert=None):\n :param proxies: (optional) A Requests-style dictionary of proxies used on this request.\n :rtype: urllib3.ConnectionPool\n \"\"\"\n- with self._pool_kw_lock:\n- if url.lower().startswith('https'):\n- self._update_poolmanager_ssl_kw(verify, cert)\n-\n- proxy = select_proxy(url, proxies)\n+ pool_kwargs = _pool_kwargs(verify, cert)\n+ proxy = select_proxy(url, proxies)\n \n- if proxy:\n- proxy = prepend_scheme_if_needed(proxy, 'http')\n- proxy_manager = self.proxy_manager_for(proxy)\n- conn = proxy_manager.connection_from_url(url)\n- else:\n- # Only scheme should be lower case\n- parsed = urlparse(url)\n- url = parsed.geturl()\n- conn = self.poolmanager.connection_from_url(url)\n+ if proxy:\n+ proxy = prepend_scheme_if_needed(proxy, 'http')\n+ proxy_manager = self.proxy_manager_for(proxy)\n+ conn = proxy_manager.connection_from_url(url, pool_kwargs=pool_kwargs)\n+ else:\n+ # Only scheme should be lower case\n+ parsed = urlparse(url)\n+ url = parsed.geturl()\n+ conn = self.poolmanager.connection_from_url(url, pool_kwargs=pool_kwargs)\n \n return conn" }, { "filename": "tests/test_requests.py", "status": "modified", "additions": 198, "deletions": 0, "changes": 198, "patch": "@@ -31,6 +31,7 @@\n from requests.sessions import SessionRedirectMixin\n from requests.models import urlencode\n from requests.hooks import default_hooks\n+from requests.utils import DEFAULT_CA_BUNDLE_PATH\n \n from .compat import StringIO, u\n from .utils import override_environ\n@@ -2765,3 +2766,200 @@ def test_parameters_for_nonstandard_schemes(self, input, params, expected):\n r = requests.Request('GET', url=input, params=params)\n p = r.prepare()\n assert p.url == expected\n+\n+\n+class TestGetConnection(object):\n+ \"\"\"\n+ Tests for the :meth:`requests.adapters.HTTPAdapter.get_connection` that assert\n+ the connections are correctly configured.\n+ \"\"\"\n+ [USER_REDACTED].mark.parametrize(\n+ 'proxies, verify, cert, expected',\n+ (\n+ (\n+ {},\n+ True,\n+ None,\n+ {\n+ 'cert_reqs': 'CERT_REQUIRED',\n+ 'ca_certs': DEFAULT_CA_BUNDLE_PATH,\n+ 'ca_cert_dir': None,\n+ 'cert_file': None,\n+ 'key_file': None,\n+ },\n+ ),\n+ (\n+ {},\n+ False,\n+ None,\n+ {\n+ 'cert_reqs': 'CERT_NONE',\n+ 'ca_certs': None,\n+ 'ca_cert_dir': None,\n+ 'cert_file': None,\n+ 'key_file': None,\n+ },\n+ ),\n+ (\n+ {},\n+ __file__,\n+ None,\n+ {\n+ 'cert_reqs': 'CERT_REQUIRED',\n+ 'ca_certs': __file__,\n+ 'ca_cert_dir': None,\n+ 'cert_file': None,\n+ 'key_file': None,\n+ },\n+ ),\n+ (\n+ {},\n+ os.path.dirname(__file__),\n+ None,\n+ {\n+ 'cert_reqs': 'CERT_REQUIRED',\n+ 'ca_certs': None,\n+ 'ca_cert_dir': os.path.dirname(__file__),\n+ 'cert_file': None,\n+ 'key_file': None,\n+ },\n+ ),\n+ (\n+ {},\n+ True,\n+ None,\n+ {\n+ 'cert_reqs': 'CERT_REQUIRED',\n+ 'ca_certs': DEFAULT_CA_BUNDLE_PATH,\n+ 'ca_cert_dir': None,\n+ 'cert_file': None,\n+ 'key_file': None,\n+ },\n+ ),\n+ (\n+ {},\n+ True,\n+ __file__,\n+ {\n+ 'cert_reqs': 'CERT_REQUIRED',\n+ 'ca_certs': DEFAULT_CA_BUNDLE_PATH,\n+ 'ca_cert_dir': None,\n+ 'cert_file': __file__,\n+ 'key_file': None,\n+ },\n+ ),\n+ (\n+ {},\n+ True,\n+ (__file__, __file__),\n+ {\n+ 'cert_reqs': 'CERT_REQUIRED',\n+ 'ca_certs': DEFAULT_CA_BUNDLE_PATH,\n+ 'ca_cert_dir': None,\n+ 'cert_file': __file__,\n+ 'key_file': __file__,\n+ },\n+ ),\n+ (\n+ {},\n+ True,\n+ (__file__, __file__),\n+ {\n+ 'cert_reqs': 'CERT_REQUIRED',\n+ 'ca_certs': DEFAULT_CA_BUNDLE_PATH,\n+ 'ca_cert_dir': None,\n+ 'cert_file': __file__,\n+ 'key_file': __file__,\n+ },\n+ ),\n+ (\n+ {'http': 'http://proxy.example.com', 'https': 'http://proxy.example.com'},\n+ True,\n+ None,\n+ {\n+ 'cert_reqs': 'CERT_REQUIRED',\n+ 'ca_certs': DEFAULT_CA_BUNDLE_PATH,\n+ 'ca_cert_dir': None,\n+ 'cert_file': None,\n+ 'key_file': None,\n+ },\n+ ),\n+ (\n+ {'http': 'http://proxy.example.com', 'https': 'http://proxy.example.com'},\n+ os.path.dirname(__file__),\n+ None,\n+ {\n+ 'cert_reqs': 'CERT_REQUIRED',\n+ 'ca_certs': None,\n+ 'ca_cert_dir': os.path.dirname(__file__),\n+ 'cert_file': None,\n+ 'key_file': None,\n+ },\n+ ),\n+ (\n+ {'http': 'http://proxy.example.com', 'https': 'http://proxy.example.com'},\n+ __file__,\n+ None,\n+ {\n+ 'cert_reqs': 'CERT_REQUIRED',\n+ 'ca_certs': __file__,\n+ 'ca_cert_dir': None,\n+ 'cert_file': None,\n+ 'key_file': None,\n+ },\n+ ),\n+ (\n+ {'http': 'http://proxy.example.com', 'https': 'http://proxy.example.com'},\n+ True,\n+ __file__,\n+ {\n+ 'cert_reqs': 'CERT_REQUIRED',\n+ 'ca_certs': DEFAULT_CA_BUNDLE_PATH,\n+ 'ca_cert_dir': None,\n+ 'cert_file': __file__,\n+ 'key_file': None,\n+ },\n+ ),\n+ (\n+ {'http': 'http://proxy.example.com', 'https': 'http://proxy.example.com'},\n+ True,\n+ (__file__, __file__),\n+ {\n+ 'cert_reqs': 'CERT_REQUIRED',\n+ 'ca_certs': DEFAULT_CA_BUNDLE_PATH,\n+ 'ca_cert_dir': None,\n+ 'cert_file': __file__,\n+ 'key_file': __file__,\n+ },\n+ ),\n+ )\n+ )\n+ def test_get_https_connection(self, proxies, verify, cert, expected):\n+ \"\"\"Assert connections are configured correctly.\"\"\"\n+ adapter = requests.adapters.HTTPAdapter()\n+ connection = adapter.get_connection(\n+ 'https://example.com', proxies=proxies, verify=verify, cert=cert)\n+ actual_config = {}\n+ for key, value in connection.__dict__.items():\n+ if key in expected:\n+ actual_config[key] = value\n+ assert actual_config == expected\n+\n+ [USER_REDACTED].mark.parametrize(\n+ 'verify, cert',\n+ (\n+ ('a/path/that/does/not/exist', None),\n+ (True, 'a/path/that/does/not/exist'),\n+ (True, (__file__, 'a/path/that/does/not/exist')),\n+ (True, ('a/path/that/does/not/exist', __file__)),\n+ )\n+ )\n+ def test_cert_files_missing(self, verify, cert):\n+ \"\"\"\n+ Assert an IOError is raised when one of the certificate files or\n+ directories can't be found.\n+ \"\"\"\n+ adapter = requests.adapters.HTTPAdapter()\n+ with pytest.raises(IOError) as excinfo:\n+ adapter.get_connection('https://example.com', verify=verify, cert=cert)\n+ excinfo.match('invalid path: a/path/that/does/not/exist')" } ], "reviews": [ { "id": 46142470, "user": "user_f068c71fd303", "state": "CHANGES_REQUESTED", "body": "Hrm, this might be a breaking change. Not sure though: our docstring implies we wanted users to override that method, but maybe the underscore in front means we didn't mean it?", "submitted_at": "2017-06-25T10:28:08+00:00" }, { "id": 46146980, "user": "user_3fcef11dbef3", "state": "COMMENTED", "body": null, "submitted_at": "2017-06-25T14:39:34+00:00" }, { "id": 46148532, "user": "user_f068c71fd303", "state": "COMMENTED", "body": null, "submitted_at": "2017-06-25T15:53:37+00:00" }, { "id": 46554116, "user": "user_f068c71fd303", "state": "APPROVED", "body": "LGTM. Thanks!", "submitted_at": "2017-06-27T13:54:33+00:00" } ], "review_comments": [ { "id": 123895350, "user": "user_f068c71fd303", "body": "Don't have static methods: they're just not very useful. Either we should decide users can't override this, in which case this should be a function, or we should decide they can and it becomes an instance method.", "path": "requests/adapters.py", "line": null, "side": "RIGHT", "created_at": "2017-06-25T10:27:06+00:00" }, { "id": 123900411, "user": "user_3fcef11dbef3", "body": "I can't think of a particularly good reason for someone to want to override this, so a function sounds fine me. If someone really objects to the behaviour for some unforeseen reason, they can override ``get_connection`` and build the pool kwargs their own way.", "path": "requests/adapters.py", "line": null, "side": "RIGHT", "created_at": "2017-06-25T14:39:34+00:00" }, { "id": 123902204, "user": "user_f068c71fd303", "body": "Yeah, that works for me. Function is the way to go then!", "path": "requests/adapters.py", "line": null, "side": "RIGHT", "created_at": "2017-06-25T15:53:37+00:00" } ], "meta": { "languages": [ "py" ], "touches_tests": true, "review_state_summary": { "CHANGES_REQUESTED": 1, "COMMENTED": 2, "APPROVED": 1 }, "meaningful_comment_count": 3, "has_approval": true, "has_changes_requested": true, "total_review_comments": 3 } } { "_id": "af7ad6a4b5206394", "_schema_version": "1.0", "_cleaned_at": "2026-02-12T07:46:52.054596+00:00", "repo": "psf/requests", "repo_url": "https://github.com/psf/requests", "license_name": "Apache License 2.0", "license_spdx": "Apache-2.0", "pr_number": 4144, "title": "Convert version compatibility checks to warnings", "body": "This patch will convert the dependency exceptions into warnings, preventing the forced halt while importing Requests. I condensed the message into a single response, but we can expand that out if needed. It just seemed like another place for updates to be forgotten.\n\nI'd also like to test this function, but due to the requirements changing with each release, it's hard to write something that won't need to be updated in parallel. We could look at parsing the requirements out of `requires` but that seems less than ideal. If I'm being honest, I'm not crazy about expanding the code around this any more than we absolutely have to.", "author": "user_dbf2a999bd6d", "created_at": "2017-06-08T21:07:53+00:00", "merged_at": "2017-06-09T01:40:08+00:00", "base_branch": "master", "head_branch": "move_compat_to_warn", "additions": 35, "deletions": 22, "changed_files": 2, "files": [ { "filename": "requests/__init__.py", "status": "modified", "additions": 30, "deletions": 22, "changes": 52, "patch": "@@ -40,34 +40,44 @@\n :license: Apache 2.0, see LICENSE for more details.\n \"\"\"\n \n-# Check urllib3 for compatibility.\n import urllib3\n-urllib3_version = urllib3.__version__.split('.')\n-# Sometimes, urllib3 only reports its version as 16.1.\n-if len(urllib3_version) == 2:\n- urllib3_version.append('0')\n-major, minor, patch = urllib3_version\n-major, minor, patch = int(major), int(minor), int(patch)\n-# urllib3 >= 1.21.1, < 1.22\n-try:\n+import chardet\n+import warnings\n+from .exceptions import RequestsDependencyWarning\n+\n+\n+def check_compatibility(urllib3_version, chardet_version):\n+ urllib3_version = urllib3_version.split('.')\n+ assert urllib3_version != ['dev'] # Verify urllib3 isn't installed from git.\n+\n+ # Sometimes, urllib3 only reports its version as 16.1.\n+ if len(urllib3_version) == 2:\n+ urllib3_version.append('0')\n+\n+ # Check urllib3 for compatibility.\n+ major, minor, patch = urllib3_version # noqa: F811\n+ major, minor, patch = int(major), int(minor), int(patch)\n+ # urllib3 >= 1.21.1, < 1.22\n assert major == 1\n assert minor >= 21\n assert minor <= 22\n-except AssertionError:\n- raise RuntimeError('Requests dependency \\'urllib3\\' must be version >= 1.21.1, < 1.22!')\n-\n \n-# Check chardet for compatibility.\n-import chardet\n-major, minor, patch = chardet.__version__.split('.')[:3]\n-major, minor, patch = int(major), int(minor), int(patch)\n-# chardet >= 3.0.2, < 3.1.0\n-try:\n+ # Check chardet for compatibility.\n+ major, minor, patch = chardet_version.split('.')[:3]\n+ major, minor, patch = int(major), int(minor), int(patch)\n+ # chardet >= 3.0.2, < 3.1.0\n assert major == 3\n assert minor < 1\n assert patch >= 2\n-except AssertionError:\n- raise RuntimeError('Requests dependency \\'chardet\\' must be version >= 3.0.2, < 3.1.0!')\n+\n+\n+# Check imported dependencies for compatibility.\n+try:\n+ check_compatibility(urllib3.__version__, chardet.__version__)\n+except (AssertionError, ValueError):\n+ warnings.warn(\"urllib3 ({0}) or chardet ({1}) doesn't match a supported \"\n+ \"version!\".format(urllib3.__version__, chardet.__version__),\n+ RequestsDependencyWarning)\n \n # Attempt to enable urllib3's SNI support, if possible\n try:\n@@ -76,8 +86,6 @@\n except ImportError:\n pass\n \n-import warnings\n-\n # urllib3's DependencyWarnings should be silenced.\n from urllib3.exceptions import DependencyWarning\n warnings.simplefilter('ignore', DependencyWarning)" }, { "filename": "requests/exceptions.py", "status": "modified", "additions": 5, "deletions": 0, "changes": 5, "patch": "@@ -115,3 +115,8 @@ class RequestsWarning(Warning):\n class FileModeWarning(RequestsWarning, DeprecationWarning):\n \"\"\"A file was opened in text mode, but Requests determined its binary length.\"\"\"\n pass\n+\n+\n+class RequestsDependencyWarning(RequestsWarning):\n+ \"\"\"An imported dependency doesn't match the expected version range.\"\"\"\n+ pass" } ], "reviews": [ { "id": 43015463, "user": "user_f068c71fd303", "state": "DISMISSED", "body": "Cool, if you can clean up the builds I think I'll be happy with this!", "submitted_at": "2017-06-08T21:13:39+00:00" }, { "id": 43018394, "user": "user_f068c71fd303", "state": "APPROVED", "body": "Still good for me. =)", "submitted_at": "2017-06-08T21:27:06+00:00" }, { "id": 43140622, "user": "user_0fa58b6f3572", "state": "COMMENTED", "body": null, "submitted_at": "2017-06-09T12:30:45+00:00" } ], "review_comments": [ { "id": 121114198, "user": "user_0fa58b6f3572", "body": "Also, my complaint about using assert statements stands. Anyone using `python -O` will skip these checks and any version incompatibilities we have will shoot them in the face.", "path": "requests/__init__.py", "line": 51, "side": "RIGHT", "created_at": "2017-06-09T12:30:45+00:00" } ], "meta": { "languages": [ "py" ], "touches_tests": false, "review_state_summary": { "DISMISSED": 1, "APPROVED": 1, "COMMENTED": 1 }, "meaningful_comment_count": 1, "has_approval": true, "has_changes_requested": false, "total_review_comments": 1 } } { "_id": "0025812762f00496", "_schema_version": "1.0", "_cleaned_at": "2026-02-12T07:46:52.054596+00:00", "repo": "psf/requests", "repo_url": "https://github.com/psf/requests", "license_name": "Apache License 2.0", "license_spdx": "Apache-2.0", "pr_number": 4134, "title": "Raise exceptions in utils.set_environ", "body": "fixes #4127", "author": "user_bb3409131871", "created_at": "2017-06-06T21:30:12+00:00", "merged_at": "2017-06-09T18:34:56+00:00", "base_branch": "master", "head_branch": "master", "additions": 37, "deletions": 10, "changed_files": 4, "files": [ { "filename": "AUTHORS.rst", "status": "modified", "additions": 1, "deletions": 0, "changes": 1, "patch": "@@ -184,3 +184,4 @@ Patches and Suggestions\n - [NAME_REDACTED] ([CONTRIBUTOR_REDACTED])\n - [NAME_REDACTED] ([CONTRIBUTOR_REDACTED])\n - [NAME_REDACTED] ([CONTRIBUTOR_REDACTED])\n+- [NAME_REDACTED] <[EMAIL_REDACTED]> ([CONTRIBUTOR_REDACTED])" }, { "filename": "HISTORY.rst", "status": "modified", "additions": 1, "deletions": 1, "changes": 2, "patch": "@@ -15,6 +15,7 @@ dev\n \n - Resolve installation failure if multiprocessing is not available\n - Resolve tests crash if multiprocessing is not able to determine the number of CPU cores\n+- Resolve error swallowing in utils set_environ generator\n \n \n 2.17.3 (2017-05-29)\n@@ -1481,4 +1482,3 @@ This is not a backwards compatible change.\n \n * Frustration\n * Conception\n-" }, { "filename": "requests/utils.py", "status": "modified", "additions": 7, "deletions": 7, "changes": 14, "patch": "@@ -612,18 +612,18 @@ def set_environ(env_name, value):\n the environment variable 'env_name'.\n \n If 'value' is None, do nothing\"\"\"\n- if value is not None:\n+ value_changed = value is not None\n+ if value_changed:\n old_value = os.environ.get(env_name)\n os.environ[env_name] = value\n try:\n yield\n finally:\n- if value is None:\n- return\n- if old_value is None:\n- del os.environ[env_name]\n- else:\n- os.environ[env_name] = old_value\n+ if value_changed:\n+ if old_value is None:\n+ del os.environ[env_name]\n+ else:\n+ os.environ[env_name] = old_value\n \n \n def should_bypass_proxies(url, no_proxy):" }, { "filename": "tests/test_utils.py", "status": "modified", "additions": 28, "deletions": 2, "changes": 30, "patch": "@@ -1,6 +1,7 @@\n # -*- coding: utf-8 -*-\n \n import os\n+import copy\n from io import BytesIO\n \n import pytest\n@@ -17,7 +18,7 @@\n requote_uri, select_proxy, should_bypass_proxies, super_len,\n to_key_val_list, to_native_string,\n unquote_header_value, unquote_unreserved,\n- urldefragauth, add_dict_to_cookiejar)\n+ urldefragauth, add_dict_to_cookiejar, set_environ)\n from requests._internal_utils import unicode_is_ascii\n \n from .compat import StringIO, cStringIO\n@@ -651,4 +652,29 @@ def QueryValueEx(key, value_name):\n monkeypatch.setenv('NO_PROXY', '')\n monkeypatch.setattr(winreg, 'OpenKey', OpenKey)\n monkeypatch.setattr(winreg, 'QueryValueEx', QueryValueEx)\n- assert should_bypass_proxies(url, no_proxy=None) == expected\n+\n+\n+[USER_REDACTED].mark.parametrize(\n+ 'env_name, value', (\n+ ('no_proxy', '192.168.0.0/24,127.0.0.1,localhost.localdomain'),\n+ ('no_proxy', None),\n+ ('a_new_key', '192.168.0.0/24,127.0.0.1,localhost.localdomain'),\n+ ('a_new_key', None),\n+ ))\n+def test_set_environ(env_name, value):\n+ \"\"\"Tests set_environ will set environ values and will restore the environ.\"\"\"\n+ environ_copy = copy.deepcopy(os.environ)\n+ with set_environ(env_name, value):\n+ assert os.environ.get(env_name) == value\n+\n+ assert os.environ == environ_copy\n+\n+\n+def test_set_environ_raises_exception():\n+ \"\"\"Tests set_environ will raise exceptions in context when the\n+ value parameter is None.\"\"\"\n+ with pytest.raises(Exception) as exception:\n+ with set_environ('test1', None):\n+ raise Exception('Expected exception')\n+\n+ assert 'Expected exception' in str(exception.value)" } ], "reviews": [ { "id": 42457473, "user": "user_dbf2a999bd6d", "state": "DISMISSED", "body": "Thanks for putting this together, [USER_REDACTED]! Overall, this looks good and seems to be a fairly sensible approach to the problem. The only thing that I might suggest adding is a simple test showing exceptions are properly raised from inside `set_environ` now.\n\nWe're currently having some issues with our windows CI environment, so we'll need to wait for that to be resolved before merging. I'd also like [USER_REDACTED] or [USER_REDACTED] to give this a glance if/when they have a free moment.\n\nFeel free to add yourself to the AUTHORS.rst if you'd like. Thanks for you first contribution to Requests!", "submitted_at": "2017-06-06T21:47:54+00:00" }, { "id": 42527196, "user": "user_f068c71fd303", "state": "CHANGES_REQUESTED", "body": "Thanks for this! As [USER_REDACTED] suggested, a test here would be really valuable to make sure we haven't regressed the behaviour.", "submitted_at": "2017-06-07T07:54:00+00:00" }, { "id": 42603133, "user": "user_bb3409131871", "state": "COMMENTED", "body": null, "submitted_at": "2017-06-07T13:33:25+00:00" }, { "id": 43180143, "user": "user_bb3409131871", "state": "COMMENTED", "body": null, "submitted_at": "2017-06-09T15:05:55+00:00" }, { "id": 43183779, "user": "user_f068c71fd303", "state": "CHANGES_REQUESTED", "body": "Cool, just some small notes, but this looks much better: great work!", "submitted_at": "2017-06-09T15:21:13+00:00" }, { "id": 43187722, "user": "user_f068c71fd303", "state": "CHANGES_REQUESTED", "body": "Cool, looks good. If you can add a changelog entry to `HISTORY.rst` and then squash your commits down we'll be good to go.", "submitted_at": "2017-06-09T15:33:42+00:00" }, { "id": 43194400, "user": "user_dbf2a999bd6d", "state": "CHANGES_REQUESTED", "body": "Hey [USER_REDACTED], this is looking good! I have a couple of minor notes on docstring cleanup, and an outstanding question. I wouldn't change anything with the conditional until [USER_REDACTED] determines if I'm overly paranoid :)", "submitted_at": "2017-06-09T16:07:36+00:00" }, { "id": 43199225, "user": "user_f068c71fd303", "state": "COMMENTED", "body": null, "submitted_at": "2017-06-09T16:19:35+00:00" }, { "id": 43227942, "user": "user_dbf2a999bd6d", "state": "DISMISSED", "body": "Alright, I think I'm happy with this, thanks [USER_REDACTED]! Once [USER_REDACTED] has a chance to re-review, we should be ready to merge.", "submitted_at": "2017-06-09T18:23:52+00:00" }, { "id": 43230467, "user": "user_f068c71fd303", "state": "APPROVED", "body": "Looks good to me!", "submitted_at": "2017-06-09T18:34:29+00:00" } ], "review_comments": [ { "id": 120556669, "user": "user_f068c71fd303", "body": "Hrm, I don't love the two separate `yield` statements here. Do you mind refactoring the old `finally` statement to invert the conditional on `if value is None: return` and to instead have `if value is not None` then do the dance with `old_value`.", "path": "requests/utils.py", "line": null, "side": "RIGHT", "created_at": "2017-06-07T07:53:40+00:00" }, { "id": 120625559, "user": "user_bb3409131871", "body": "[USER_REDACTED] will set this refactor up and add a test", "path": "requests/utils.py", "line": null, "side": "RIGHT", "created_at": "2017-06-07T13:33:25+00:00" }, { "id": 121149444, "user": "user_bb3409131871", "body": "[USER_REDACTED] refactored the finally statement, let me know if this is more what you would like to see there, also added tests", "path": "requests/utils.py", "line": null, "side": "RIGHT", "created_at": "2017-06-09T15:05:55+00:00" }, { "id": 121152628, "user": "user_f068c71fd303", "body": "We don't need this newline.", "path": "requests/utils.py", "line": null, "side": "RIGHT", "created_at": "2017-06-09T15:18:57+00:00" }, { "id": 121152683, "user": "user_f068c71fd303", "body": "`None` is implicit in `get`, you can leave it out.", "path": "requests/utils.py", "line": null, "side": "RIGHT", "created_at": "2017-06-09T15:19:11+00:00" }, { "id": 121162019, "user": "user_dbf2a999bd6d", "body": "[USER_REDACTED] what are your thoughts on adding `value_changed = value is not None`, and using that single value for both conditionals? The fact these two checks are bound is implicit and has the potential to get out of sync as soon as one changes.", "path": "requests/utils.py", "line": null, "side": "RIGHT", "created_at": "2017-06-09T15:58:55+00:00" }, { "id": 121162843, "user": "user_dbf2a999bd6d", "body": "Could we end this with a period and either bring the `\"\"\"` up to the same line or wrap the text down? We don't have a hard cap at 80 characters in Requests.", "path": "tests/test_utils.py", "line": null, "side": "RIGHT", "created_at": "2017-06-09T16:02:25+00:00" }, { "id": 121162870, "user": "user_dbf2a999bd6d", "body": "`.`", "path": "tests/test_utils.py", "line": null, "side": "RIGHT", "created_at": "2017-06-09T16:02:32+00:00" }, { "id": 121166515, "user": "user_f068c71fd303", "body": "Works for me!", "path": "requests/utils.py", "line": null, "side": "RIGHT", "created_at": "2017-06-09T16:19:35+00:00" } ], "meta": { "languages": [ "py", "rst" ], "touches_tests": true, "review_state_summary": { "DISMISSED": 2, "CHANGES_REQUESTED": 4, "COMMENTED": 3, "APPROVED": 1 }, "meaningful_comment_count": 8, "has_approval": true, "has_changes_requested": true, "total_review_comments": 9 } } { "_id": "e54197915ec0fabc", "_schema_version": "1.0", "_cleaned_at": "2026-02-12T07:46:52.054596+00:00", "repo": "psf/requests", "repo_url": "https://github.com/psf/requests", "license_name": "Apache License 2.0", "license_spdx": "Apache-2.0", "pr_number": 4118, "title": "Drop python2.6 support", "body": "Drop support for python2.6. Fixes #3928\n\nNote that this targets the 3.0.0 branch, not master.", "author": "user_f9ae2b8b4864", "created_at": "2017-05-30T22:33:15+00:00", "merged_at": "2017-07-26T19:59:40+00:00", "base_branch": "proposed/3.0.0", "head_branch": "drop-py26", "additions": 41, "deletions": 65, "changed_files": 18, "files": [ { "filename": ".travis.yml", "status": "modified", "additions": 5, "deletions": 5, "changes": 10, "patch": "@@ -1,7 +1,6 @@\n sudo: false\n language: python\n python:\n- - \"2.6\"\n - \"2.7\"\n - \"3.3\"\n - \"3.4\"\n@@ -10,20 +9,21 @@ python:\n # - \"3.7-dev\"\n # - \"pypy\" -- appears to hang\n # - \"pypy3\"\n+matrix:\n+ allow_failures:\n+ - python: 3.7-dev\n # command to install dependencies\n install: \"make\"\n # command to run tests\n script:\n- - |\n- if [[ \"$TRAVIS_PYTHON_VERSION\" != \"2.6\" ]] ; then make test-readme; fi\n+ - make test-readme\n - make ci\n cache: pip\n jobs:\n include:\n - stage: test\n script:\n- - |\n- if [[ \"$TRAVIS_PYTHON_VERSION\" != \"2.6\" ]] ; then make test-readme; fi\n+ - make test-readme\n - make ci\n - stage: coverage\n python: 3.6" }, { "filename": "3.0-HISTORY.rst", "status": "modified", "additions": 2, "deletions": 0, "changes": 2, "patch": "@@ -1,6 +1,8 @@\n 3.0.0 (2017-xx-xx)\n ++++++++++++++++++\n \n+- Support for Python 2.6 has been dropped.\n+\n - Simplified logic for determining Content-Length and Transfer-Encoding.\n Requests will now avoid setting both headers on the same request, and\n raise an exception if this is done manually by a user." }, { "filename": "AUTHORS.rst", "status": "modified", "additions": 1, "deletions": 1, "changes": 2, "patch": "@@ -128,7 +128,7 @@ Patches and Suggestions\n - [NAME_REDACTED] <[EMAIL_REDACTED]> ([CONTRIBUTOR_REDACTED])\n - [NAME_REDACTED] <[EMAIL_REDACTED]> ([CONTRIBUTOR_REDACTED])\n - [NAME_REDACTED] <[EMAIL_REDACTED]> ([CONTRIBUTOR_REDACTED])\n-- [NAME_REDACTED] <[EMAIL_REDACTED]> ([CONTRIBUTOR_REDACTED])\n+- [NAME_REDACTED] <[EMAIL_REDACTED]> ([CONTRIBUTOR_REDACTED])\n - Łukasz Langa <[EMAIL_REDACTED]>\n - [NAME_REDACTED] <[EMAIL_REDACTED]>\n - [NAME_REDACTED] ([CONTRIBUTOR_REDACTED])" }, { "filename": "README.rst", "status": "modified", "additions": 1, "deletions": 1, "changes": 2, "patch": "@@ -81,7 +81,7 @@ Requests is ready for today's web.\n - ``.netrc`` Support\n - [NAME_REDACTED]\n \n-Requests officially supports Python 2.6–2.7 & 3.3–3.7, and runs great on PyPy.\n+Requests officially supports Python 2.7 & 3.3–3.7, and runs great on PyPy.\n \n Installation\n ------------" }, { "filename": "docs/community/faq.rst", "status": "modified", "additions": 1, "deletions": 2, "changes": 3, "patch": "@@ -54,7 +54,6 @@ Python 3 Support?\n Yes! Here's a list of Python platforms that are officially\n supported:\n \n-* Python 2.6\n * Python 2.7\n * Python 3.3\n * Python 3.4\n@@ -69,7 +68,7 @@ These errors occur when :ref:`SSL certificate verification `\n fails to match the certificate the server responds with to the hostname\n Requests thinks it's contacting. If you're certain the server's SSL setup is\n correct (for example, because you can visit the site with your browser) and\n-you're using Python 2.6 or 2.7, a possible explanation is that you need\n+you're using Python 2.7, a possible explanation is that you need\n Server-Name-Indication.\n \n `Server-Name-Indication`_, or SNI, is an official extension to SSL where the" }, { "filename": "docs/dev/todo.rst", "status": "modified", "additions": 0, "deletions": 1, "changes": 1, "patch": "@@ -49,7 +49,6 @@ [NAME_REDACTED] currently supports the following versions of Python:\n \n-- Python 2.6\n - Python 2.7\n - Python 3.3\n - Python 3.4" }, { "filename": "docs/index.rst", "status": "modified", "additions": 1, "deletions": 1, "changes": 2, "patch": "@@ -104,7 +104,7 @@ Requests is ready for today's web.\n - [NAME_REDACTED]\n - ``.netrc`` Support\n \n-Requests officially supports Python 2.6–2.7 & 3.3–3.7, and runs great on PyPy.\n+Requests officially supports Python 2.7 & 3.3–3.7, and runs great on PyPy.\n \n \n The User Guide" }, { "filename": "requests/__init__.py", "status": "modified", "additions": 1, "deletions": 6, "changes": 7, "patch": "@@ -100,12 +100,7 @@\n \n # Set default logging handler to avoid \"No handler found\" warnings.\n import logging\n-try: # Python 2.7+\n- from logging import NullHandler\n-except ImportError:\n- class NullHandler(logging.Handler):\n- def emit(self, record):\n- pass\n+from logging import NullHandler\n \n logging.getLogger(__name__).addHandler(NullHandler())" }, { "filename": "requests/adapters.py", "status": "modified", "additions": 3, "deletions": 5, "changes": 8, "patch": "@@ -187,8 +187,7 @@ def __init__(self, pool_connections=DEFAULT_POOLSIZE,\n self.init_poolmanager(pool_connections, pool_maxsize, block=pool_block)\n \n def __getstate__(self):\n- return dict((attr, getattr(self, attr, None)) for attr in\n- self.__attrs__)\n+ return {attr: getattr(self, attr, None) for attr in self.__attrs__}\n \n def __setstate__(self, state):\n # Can't handle by adding 'proxy_manager' to self.__attrs__ because\n@@ -478,11 +477,10 @@ def send(self, request, stream=False, timeout=None, verify=True, cert=None, prox\n \n # Receive the response from the server\n try:\n- # For Python 2.7+ versions, use buffering of HTTP\n- # responses\n+ # For Python 2.7, use buffering of HTTP responses\n r = low_conn.getresponse(buffering=True)\n except TypeError:\n- # For compatibility with Python 2.6 versions and back\n+ # For Python 3.3+ versions, this is the default\n r = low_conn.getresponse()\n \n resp = HTTPResponse.from_httplib(" }, { "filename": "requests/cookies.py", "status": "modified", "additions": 15, "deletions": 14, "changes": 29, "patch": "@@ -440,20 +440,21 @@ def create_cookie(name, value, **kwargs):\n By default, the pair of `name` and `value` will be set for the domain ''\n and sent on every request (this is sometimes called a \"supercookie\").\n \"\"\"\n- result = dict(\n- version=0,\n- name=name,\n- value=value,\n- port=None,\n- domain='',\n- path='/',\n- secure=False,\n- expires=None,\n- discard=True,\n- comment=None,\n- comment_url=None,\n- rest={'HttpOnly': None},\n- rfc2109=False,)\n+ result = {\n+ 'version': 0,\n+ 'name': name,\n+ 'value': value,\n+ 'port': None,\n+ 'domain': '',\n+ 'path': '/',\n+ 'secure': False,\n+ 'expires': None,\n+ 'discard': True,\n+ 'comment': None,\n+ 'comment_url': None,\n+ 'rest': {'HttpOnly': None},\n+ 'rfc2109': False,\n+ }\n \n badargs = set(kwargs) - set(result)\n if badargs:" }, { "filename": "requests/hooks.py", "status": "modified", "additions": 2, "deletions": 2, "changes": 4, "patch": "@@ -15,14 +15,14 @@\n \n \n def default_hooks():\n- return dict((event, []) for event in HOOKS)\n+ return {event: [] for event in HOOKS}\n \n # TODO: response is the only one\n \n \n def dispatch_hook(key, hooks, hook_data, **kwargs):\n \"\"\"Dispatches a hook dictionary on a given piece of data.\"\"\"\n- hooks = hooks or dict()\n+ hooks = hooks or {}\n hooks = hooks.get(key)\n if hooks:\n if hasattr(hooks, '__call__'):" }, { "filename": "requests/models.py", "status": "modified", "additions": 1, "deletions": 4, "changes": 5, "patch": "@@ -653,10 +653,7 @@ def __getstate__(self):\n if not self._content_consumed:\n self.content\n \n- return dict(\n- (attr, getattr(self, attr, None))\n- for attr in self.__attrs__\n- )\n+ return {attr: getattr(self, attr, None) for attr in self.__attrs__}\n \n def __setstate__(self, state):\n for name, value in state.items():" }, { "filename": "requests/sessions.py", "status": "modified", "additions": 1, "deletions": 1, "changes": 2, "patch": "@@ -736,7 +736,7 @@ def mount(self, prefix, adapter):\n self.adapters[key] = self.adapters.pop(key)\n \n def __getstate__(self):\n- state = dict((attr, getattr(self, attr, None)) for attr in self.__attrs__)\n+ state = {attr: getattr(self, attr, None) for attr in self.__attrs__}\n return state\n \n def __setstate__(self, state):" }, { "filename": "requests/utils.py", "status": "modified", "additions": 1, "deletions": 15, "changes": 16, "patch": "@@ -679,22 +679,8 @@ def should_bypass_proxies(url, no_proxy):\n # to apply the proxies on this URL.\n return True\n \n- # If the system proxy settings indicate that this URL should be bypassed,\n- # don't proxy.\n- # The proxy_bypass function is incredibly buggy on OS X in early versions\n- # of Python 2.6, so allow this call to fail. Only catch the specific\n- # exceptions we've seen, though: this call failing in other ways can reveal\n- # legitimate problems.\n with set_environ('no_proxy', no_proxy_arg):\n- try:\n- bypass = proxy_bypass(netloc)\n- except (TypeError, socket.gaierror):\n- bypass = False\n-\n- if bypass:\n- return True\n-\n- return False\n+ return bool(proxy_bypass(netloc))\n \n \n def get_environ_proxies(url, no_proxy=None):" }, { "filename": "setup.py", "status": "modified", "additions": 2, "deletions": 3, "changes": 5, "patch": "@@ -80,7 +80,7 @@ def run_tests(self):\n '[NAME_REDACTED] :: English',\n 'License :: OSI Approved :: [NAME_REDACTED]',\n '[NAME_REDACTED] :: Python',\n- '[NAME_REDACTED] :: Python :: 2.6',\n+ '[NAME_REDACTED] :: Python :: 2',\n '[NAME_REDACTED] :: Python :: 2.7',\n '[NAME_REDACTED] :: Python :: 3',\n '[NAME_REDACTED] :: Python :: 3.3',\n@@ -95,7 +95,6 @@ def run_tests(self):\n extras_require={\n 'security': ['pyOpenSSL>=0.14', 'cryptography>=1.3.4', 'idna>=2.0.0'],\n 'socks': ['PySocks>=1.5.6, !=1.5.7'],\n- 'socks:sys_platform == \"win32\" and (python_version == \"2.7\" or python_version == \"2.6\")': ['win_inet_pton'],\n+ 'socks:sys_platform == \"win32\" and python_version == \"2.7\"': ['win_inet_pton'],\n },\n )\n-" }, { "filename": "tests/test_requests.py", "status": "modified", "additions": 1, "deletions": 1, "changes": 2, "patch": "@@ -933,7 +933,7 @@ def test_https_warnings(self, httpbin_secure, httpbin_ca_bundle):\n \n def test_urlencoded_get_query_multivalued_param(self, httpbin):\n \n- r = requests.get(httpbin('get'), params=dict(test=['foo', 'baz']))\n+ r = requests.get(httpbin('get'), params={'test': ['foo', 'baz']})\n assert r.status_code == 200\n assert r.url == httpbin('get?test=foo&test=baz')" }, { "filename": "tests/test_utils.py", "status": "modified", "additions": 1, "deletions": 1, "changes": 2, "patch": "@@ -566,7 +566,7 @@ def test_add_dict_to_cookiejar(cookiejar):\n cookiedict = {'test': 'cookies',\n 'good': 'cookies'}\n cj = add_dict_to_cookiejar(cookiejar, cookiedict)\n- cookies = dict((cookie.name, cookie.value) for cookie in cj)\n+ cookies = {cookie.name: cookie.value for cookie in cj}\n assert cookiedict == cookies" }, { "filename": "tox.ini", "status": "modified", "additions": 2, "deletions": 2, "changes": 4, "patch": "@@ -1,8 +1,8 @@\n [tox]\n-envlist = py26,py27,py33,py34,py35,py36\n+envlist = py27,py33,py34,py35,py36\n \n [testenv]\n \n commands =\n pip install -e .[socks]\n- python setup.py test\n\\ No newline at end of file\n+ python setup.py test" } ], "reviews": [ { "id": 41944025, "user": "user_278727a2e287", "state": "COMMENTED", "body": "I believe you can drop the [`NullHandler`](https://github.com/hobarrera/requests/blob/drop-py26/requests/__init__.py#L76-L81) workaround.\n\n---\n\nThe code could now use set literals and dict/set comprehension. Thoughts on converting the code as part of this commit? Using [flake8-comprehensions](https://pypi.python.org/pypi/flake8-comprehensions) I discovered the following:\n\n```\n./requests/models.py:659:16: C402 Unnecessary generator - rewrite as a dict comprehension.\n./requests/hooks.py:18:12: C402 Unnecessary generator - rewrite as a dict comprehension.\n./requests/hooks.py:25:22: C408 Unnecessary dict call - rewrite as a literal.\n./requests/adapters.py:133:16: C402 Unnecessary generator - rewrite as a dict comprehension.\n./requests/sessions.py:758:17: C402 Unnecessary generator - rewrite as a dict comprehension.\n./requests/cookies.py:441:14: C408 Unnecessary dict call - rewrite as a literal.\n./tests/test_utils.py:569:15: C402 Unnecessary generator - rewrite as a dict comprehension.\n./tests/test_requests.py:933:49: C408 Unnecessary dict call - rewrite as a literal.\n```", "submitted_at": "2017-06-04T15:52:51+00:00" }, { "id": 41944507, "user": "user_36df932e8b7a", "state": "COMMENTED", "body": null, "submitted_at": "2017-06-04T15:53:43+00:00" }, { "id": 41945978, "user": "user_f9ae2b8b4864", "state": "COMMENTED", "body": null, "submitted_at": "2017-06-04T16:59:54+00:00" }, { "id": 41946004, "user": "user_f9ae2b8b4864", "state": "COMMENTED", "body": null, "submitted_at": "2017-06-04T17:00:58+00:00" }, { "id": 44175968, "user": "user_dbf2a999bd6d", "state": "DISMISSED", "body": "Alright, I think we're close to calling this good. For the time being, it looks like we'll need to work around 2.6 builds failing on proposed/3.0.0.\n\n[USER_REDACTED], [USER_REDACTED], any final thoughts here? I think this looks good from my end.", "submitted_at": "2017-06-14T23:40:01+00:00" } ], "review_comments": [ { "id": 120012901, "user": "user_278727a2e287", "body": "Good that this one was removed, but there should exist a trove classifier for `'[NAME_REDACTED] :: Python :: 2'` as requests still supports Python 2 in some capacity.", "path": "setup.py", "line": 83, "side": "LEFT", "created_at": "2017-06-04T15:32:55+00:00" }, { "id": 120013482, "user": "user_36df932e8b7a", "body": "+1", "path": "setup.py", "line": 83, "side": "LEFT", "created_at": "2017-06-04T15:53:43+00:00" }, { "id": 120015038, "user": "user_f9ae2b8b4864", "body": "Added `'[NAME_REDACTED] :: Python :: 2'` Keep in mind that `2.7` is still there as well.", "path": "setup.py", "line": 83, "side": "LEFT", "created_at": "2017-06-04T16:59:54+00:00" }, { "id": 120015063, "user": "user_f9ae2b8b4864", "body": "The comments for this bit were oddly out of date; only this branch works on python3, while the above fails (with `TypeError`).", "path": "requests/adapters.py", "line": 484, "side": "RIGHT", "created_at": "2017-06-04T17:00:58+00:00" } ], "meta": { "languages": [ "ini", "py", "rst", "yml" ], "touches_tests": true, "review_state_summary": { "COMMENTED": 4, "DISMISSED": 1 }, "meaningful_comment_count": 3, "has_approval": false, "has_changes_requested": false, "total_review_comments": 4 } } { "_id": "042a2325660a0be2", "_schema_version": "1.0", "_cleaned_at": "2026-02-12T07:46:52.054596+00:00", "repo": "psf/requests", "repo_url": "https://github.com/psf/requests", "license_name": "Apache License 2.0", "license_spdx": "Apache-2.0", "pr_number": 4114, "title": "Catch error if multiprocessing is not available or is unable to determine the number of CPUs", "body": "resolves #4113", "author": "user_29dd6fcbac0e", "created_at": "2017-05-30T10:03:05+00:00", "merged_at": "2017-05-30T12:54:32+00:00", "base_branch": "master", "head_branch": "master", "additions": 9, "deletions": 2, "changed_files": 2, "files": [ { "filename": "HISTORY.rst", "status": "modified", "additions": 4, "deletions": 0, "changes": 4, "patch": "@@ -8,6 +8,10 @@ dev\n \n **Bugfixes**\n \n+- Resolve installation failure if multiprocessing is not available\n+- Resolve tests crash if multiprocessing is not able to determine the number of CPU cores\n+\n+\n 2.17.3 (2017-05-29)\n +++++++++++++++++++" }, { "filename": "setup.py", "status": "modified", "additions": 5, "deletions": 2, "changes": 7, "patch": "@@ -8,7 +8,6 @@\n \n from setuptools import setup\n from setuptools.command.test import test as TestCommand\n-from multiprocessing import cpu_count\n \n here = os.path.abspath(os.path.dirname(__file__))\n \n@@ -17,7 +16,11 @@ class PyTest(TestCommand):\n \n def initialize_options(self):\n TestCommand.initialize_options(self)\n- self.pytest_args = ['-n', str(cpu_count()), '--boxed']\n+ try:\n+ from multiprocessing import cpu_count\n+ self.pytest_args = ['-n', str(cpu_count()), '--boxed']\n+ except (ImportError, NotImplementedError):\n+ self.pytest_args = ['-n', '1', '--boxed']\n \n def finalize_options(self):\n TestCommand.finalize_options(self)" } ], "reviews": [ { "id": 40912507, "user": "user_f068c71fd303", "state": "CHANGES_REQUESTED", "body": "Thanks for this, it looks good! Can you rebase onto the current master and add a note to the changelog please?", "submitted_at": "2017-05-30T10:49:58+00:00" }, { "id": 40935403, "user": "user_f068c71fd303", "state": "CHANGES_REQUESTED", "body": "Cool, this is almost ready to go: there's a small typo though.", "submitted_at": "2017-05-30T12:44:02+00:00" }, { "id": 40937779, "user": "user_f068c71fd303", "state": "APPROVED", "body": "Cool, this looks like a good bugfix. I'll try to get it out by Thursday, but I want to confirm that there's nothing else lurking before I do that.", "submitted_at": "2017-05-30T12:53:54+00:00" } ], "review_comments": [ { "id": 119088050, "user": "user_f068c71fd303", "body": "This should be `installation`.", "path": "HISTORY.rst", "line": null, "side": "RIGHT", "created_at": "2017-05-30T12:43:38+00:00" } ], "meta": { "languages": [ "py", "rst" ], "touches_tests": false, "review_state_summary": { "CHANGES_REQUESTED": 2, "APPROVED": 1 }, "meaningful_comment_count": 1, "has_approval": true, "has_changes_requested": true, "total_review_comments": 1 } } { "_id": "e55a343ea75a5cbe", "_schema_version": "1.0", "_cleaned_at": "2026-02-12T07:46:52.070120+00:00", "repo": "psf/requests", "repo_url": "https://github.com/psf/requests", "license_name": "Apache License 2.0", "license_spdx": "Apache-2.0", "pr_number": 4100, "title": "Remove session redirect cache", "body": "Addresses #4055. Essentially, this just strips out the redirect cache in `sessions.py`.\n\nI ran the tests and didn't find any side effects of removing the cache. This is my first PR to requests, so let me know if there's any additional steps that need to be done.\n\nThanks!", "author": "user_b0ca6b20c750", "created_at": "2017-05-29T16:56:29+00:00", "merged_at": "2017-05-29T17:14:43+00:00", "base_branch": "master", "head_branch": "remove-redirect-cache", "additions": 0, "deletions": 26, "changed_files": 1, "files": [ { "filename": "requests/sessions.py", "status": "modified", "additions": 0, "deletions": 26, "changes": 26, "patch": "@@ -13,8 +13,6 @@\n from collections import Mapping\n from datetime import timedelta\n \n-from urllib3._collections import RecentlyUsedContainer\n-\n from .auth import _basic_auth_str\n from .compat import cookielib, is_py3, OrderedDict, urljoin, urlparse\n from .cookies import (\n@@ -39,8 +37,6 @@\n # formerly defined here, reexposed here for backward compatibility\n from .models import REDIRECT_STATI\n \n-REDIRECT_CACHE_SIZE = 1000\n-\n # Preferred clock, based on which one is more accurate on a given system.\n if platform.system() == 'Windows':\n try: # Python 3.3+\n@@ -158,9 +154,6 @@ def resolve_redirects(self, resp, req, stream=False, timeout=None,\n url = requote_uri(url)\n \n prepared_request.url = to_native_string(url)\n- # Cache the url, unless it redirects to itself.\n- if resp.is_permanent_redirect and req.url != prepared_request.url:\n- self.redirect_cache[req.url] = prepared_request.url\n \n self.rebuild_method(prepared_request, resp)\n \n@@ -393,9 +386,6 @@ def __init__(self):\n self.mount('https://', HTTPAdapter())\n self.mount('http://', HTTPAdapter())\n \n- # Only store 1000 redirects to prevent using infinite memory\n- self.redirect_cache = RecentlyUsedContainer(REDIRECT_CACHE_SIZE)\n-\n def __enter__(self):\n return self\n \n@@ -623,16 +613,6 @@ def send(self, request, **kwargs):\n stream = kwargs.get('stream')\n hooks = request.hooks\n \n- # Resolve URL in redirect cache, if available.\n- if allow_redirects:\n- checked_urls = set()\n- while request.url in self.redirect_cache:\n- checked_urls.add(request.url)\n- new_url = self.redirect_cache.get(request.url)\n- if new_url in checked_urls:\n- break\n- request.url = new_url\n-\n # Get the appropriate adapter to use\n adapter = self.get_adapter(url=request.url)\n \n@@ -745,18 +725,12 @@ def mount(self, prefix, adapter):\n \n def __getstate__(self):\n state = dict((attr, getattr(self, attr, None)) for attr in self.__attrs__)\n- state['redirect_cache'] = dict(self.redirect_cache)\n return state\n \n def __setstate__(self, state):\n- redirect_cache = state.pop('redirect_cache', {})\n for attr, value in state.items():\n setattr(self, attr, value)\n \n- self.redirect_cache = RecentlyUsedContainer(REDIRECT_CACHE_SIZE)\n- for redirect, to in redirect_cache.items():\n- self.redirect_cache[redirect] = to\n-\n \n def session():\n \"\"\"" } ], "reviews": [ { "id": 40807198, "user": "user_dbf2a999bd6d", "state": "APPROVED", "body": "Thanks for contributing to Requests, [USER_REDACTED]! We'll wait on merging until one of the other maintainers signs off, but this looks from my end.\n\nGreat work! ✨", "submitted_at": "2017-05-29T17:06:13+00:00" }, { "id": 40807783, "user": "user_36df932e8b7a", "state": "COMMENTED", "body": null, "submitted_at": "2017-05-29T17:12:37+00:00" } ], "review_comments": [ { "id": 118967374, "user": "user_36df932e8b7a", "body": "I hated this code. So glad it's going. \n\nHope I'm not responsible for it landing in the codebase. I probably am :)", "path": "requests/sessions.py", "line": 627, "side": "LEFT", "created_at": "2017-05-29T17:12:37+00:00" } ], "meta": { "languages": [ "py" ], "touches_tests": false, "review_state_summary": { "APPROVED": 1, "COMMENTED": 1 }, "meaningful_comment_count": 1, "has_approval": true, "has_changes_requested": false, "total_review_comments": 1 } } { "_id": "ab1c6aaf37d2af43", "_schema_version": "1.0", "_cleaned_at": "2026-02-12T07:46:52.070120+00:00", "repo": "psf/requests", "repo_url": "https://github.com/psf/requests", "license_name": "Apache License 2.0", "license_spdx": "Apache-2.0", "pr_number": 4066, "title": "API improvements", "body": "- `Response.next`\n\nRelated: #4065.", "author": "user_36df932e8b7a", "created_at": "2017-05-27T01:15:12+00:00", "merged_at": "2017-05-27T01:33:29+00:00", "base_branch": "master", "head_branch": "next", "additions": 36, "deletions": 20, "changed_files": 2, "files": [ { "filename": "requests/models.py", "status": "modified", "additions": 8, "deletions": 2, "changes": 10, "patch": "@@ -593,6 +593,7 @@ def __init__(self):\n \n self._content = False\n self._content_consumed = False\n+ self._next = None\n \n #: [NAME_REDACTED] of responded HTTP Status, e.g. 404 or 200.\n self.status_code = None\n@@ -706,12 +707,17 @@ def is_redirect(self):\n \n [USER_REDACTED]\n def is_permanent_redirect(self):\n- \"\"\"True if this Response one of the permanent versions of redirect\"\"\"\n+ \"\"\"True if this Response one of the permanent versions of redirect.\"\"\"\n return ('location' in self.headers and self.status_code in (codes.moved_permanently, codes.permanent_redirect))\n \n+ [USER_REDACTED]\n+ def next(self):\n+ \"\"\"Returns a PreparedRequest for the next request in a redirect chain, if there is one.\"\"\"\n+ return self._next\n+\n [USER_REDACTED]\n def apparent_encoding(self):\n- \"\"\"The apparent encoding, provided by [NAME_REDACTED]\"\"\"\n+ \"\"\"The apparent encoding, provided by [NAME_REDACTED]\"\"\"\n return chardet.detect(self.content)['encoding']\n \n def iter_content(self, chunk_size=1, decode_unicode=False):" }, { "filename": "requests/sessions.py", "status": "modified", "additions": 28, "deletions": 18, "changes": 46, "patch": "@@ -114,8 +114,8 @@ def get_redirect_target(self, resp):\n return None\n \n def resolve_redirects(self, resp, req, stream=False, timeout=None,\n- verify=True, cert=None, proxies=None, **adapter_kwargs):\n- \"\"\"Receives a Response. Returns a generator of Responses.\"\"\"\n+ verify=True, cert=None, proxies=None, yield_requests=False, **adapter_kwargs):\n+ \"\"\"Receives a Response. Returns a generator of Responses or Requests.\"\"\"\n \n hist = [] # keep track of history\n \n@@ -203,22 +203,26 @@ def resolve_redirects(self, resp, req, stream=False, timeout=None,\n # Override the original request.\n req = prepared_request\n \n- resp = self.send(\n- req,\n- stream=stream,\n- timeout=timeout,\n- verify=verify,\n- cert=cert,\n- proxies=proxies,\n- allow_redirects=False,\n- **adapter_kwargs\n- )\n+ if yield_requests:\n+ yield req\n+ else:\n \n- extract_cookies_to_jar(self.cookies, prepared_request, resp.raw)\n+ resp = self.send(\n+ req,\n+ stream=stream,\n+ timeout=timeout,\n+ verify=verify,\n+ cert=cert,\n+ proxies=proxies,\n+ allow_redirects=False,\n+ **adapter_kwargs\n+ )\n \n- # extract redirect url, if any, for the next loop\n- url = self.get_redirect_target(resp)\n- yield resp\n+ extract_cookies_to_jar(self.cookies, prepared_request, resp.raw)\n+\n+ # extract redirect url, if any, for the next loop\n+ url = self.get_redirect_target(resp)\n+ yield resp\n \n def rebuild_auth(self, prepared_request, response):\n \"\"\"When being redirected we may want to strip authentication from the\n@@ -597,8 +601,7 @@ def delete(self, url, **kwargs):\n return self.request('DELETE', url, **kwargs)\n \n def send(self, request, **kwargs):\n- \"\"\"\n- Send a given PreparedRequest.\n+ \"\"\"Send a given PreparedRequest.\n \n :rtype: requests.Response\n \"\"\"\n@@ -668,6 +671,13 @@ def send(self, request, **kwargs):\n r = history.pop()\n r.history = history\n \n+ # If redirects aren't being followed, store the response on the Request for Response.next().\n+ if not allow_redirects:\n+ try:\n+ r._next = self.resolve_redirects(r, request, yield_requests=True, **kwargs).next()\n+ except StopIteration:\n+ pass\n+\n if not stream:\n r.content" } ], "reviews": [ { "id": 40641936, "user": "user_0fa58b6f3572", "state": "COMMENTED", "body": null, "submitted_at": "2017-05-27T01:19:34+00:00" }, { "id": 40641953, "user": "user_36df932e8b7a", "state": "COMMENTED", "body": null, "submitted_at": "2017-05-27T01:20:21+00:00" }, { "id": 40641986, "user": "user_36df932e8b7a", "state": "COMMENTED", "body": null, "submitted_at": "2017-05-27T01:21:35+00:00" }, { "id": 40641993, "user": "user_36df932e8b7a", "state": "COMMENTED", "body": null, "submitted_at": "2017-05-27T01:22:02+00:00" }, { "id": 40642006, "user": "user_0fa58b6f3572", "state": "COMMENTED", "body": null, "submitted_at": "2017-05-27T01:22:39+00:00" }, { "id": 40642007, "user": "user_36df932e8b7a", "state": "COMMENTED", "body": null, "submitted_at": "2017-05-27T01:22:43+00:00" }, { "id": 40642017, "user": "user_36df932e8b7a", "state": "COMMENTED", "body": null, "submitted_at": "2017-05-27T01:23:07+00:00" }, { "id": 40642023, "user": "user_0fa58b6f3572", "state": "COMMENTED", "body": null, "submitted_at": "2017-05-27T01:23:28+00:00" }, { "id": 40642048, "user": "user_0fa58b6f3572", "state": "COMMENTED", "body": null, "submitted_at": "2017-05-27T01:24:48+00:00" }, { "id": 40642058, "user": "user_36df932e8b7a", "state": "COMMENTED", "body": null, "submitted_at": "2017-05-27T01:25:13+00:00" }, { "id": 40642069, "user": "user_0fa58b6f3572", "state": "COMMENTED", "body": null, "submitted_at": "2017-05-27T01:25:35+00:00" }, { "id": 40642086, "user": "user_0fa58b6f3572", "state": "COMMENTED", "body": null, "submitted_at": "2017-05-27T01:26:20+00:00" }, { "id": 40642127, "user": "user_36df932e8b7a", "state": "COMMENTED", "body": null, "submitted_at": "2017-05-27T01:27:54+00:00" }, { "id": 40643457, "user": "user_36df932e8b7a", "state": "COMMENTED", "body": null, "submitted_at": "2017-05-27T02:32:03+00:00" }, { "id": 41181613, "user": "user_f068c71fd303", "state": "COMMENTED", "body": null, "submitted_at": "2017-05-31T09:46:17+00:00" } ], "review_comments": [ { "id": 118809995, "user": "user_0fa58b6f3572", "body": "Why have this when we already have `session.send`?", "path": "requests/models.py", "line": null, "side": "RIGHT", "created_at": "2017-05-27T01:19:34+00:00" }, { "id": 118810004, "user": "user_36df932e8b7a", "body": "more intuitive. i dabbled about it alot when i was writing it originally, and i opted out, decided that i could always add it back in later — i think it's time for it to go in. it's just a nice shortcut.", "path": "requests/models.py", "line": null, "side": "RIGHT", "created_at": "2017-05-27T01:20:21+00:00" }, { "id": 118810048, "user": "user_36df932e8b7a", "body": "`Response.next().send(session)` is kinda nice", "path": "requests/models.py", "line": null, "side": "RIGHT", "created_at": "2017-05-27T01:21:35+00:00" }, { "id": 118810060, "user": "user_36df932e8b7a", "body": "a lot better than `session.send(Response.next())` imo", "path": "requests/models.py", "line": null, "side": "RIGHT", "created_at": "2017-05-27T01:22:02+00:00" }, { "id": 118810070, "user": "user_0fa58b6f3572", "body": "Yield requests maybe?", "path": "requests/sessions.py", "line": null, "side": "RIGHT", "created_at": "2017-05-27T01:22:39+00:00" }, { "id": 118810072, "user": "user_36df932e8b7a", "body": "i can peel that out if you're really against it — i think it's harmless though, and just smooths out the api a bit", "path": "requests/models.py", "line": null, "side": "RIGHT", "created_at": "2017-05-27T01:22:43+00:00" }, { "id": 118810086, "user": "user_36df932e8b7a", "body": "sure!", "path": "requests/sessions.py", "line": null, "side": "RIGHT", "created_at": "2017-05-27T01:23:07+00:00" }, { "id": 118810090, "user": "user_0fa58b6f3572", "body": "I see no difference, except that one is more intuitive for people already using that API. Sessions send requests, requests don't send sessions.", "path": "requests/models.py", "line": null, "side": "RIGHT", "created_at": "2017-05-27T01:23:28+00:00" }, { "id": 118810120, "user": "user_0fa58b6f3572", "body": "If this isn't doing anything, why isn't it just a property?", "path": "requests/models.py", "line": null, "side": "RIGHT", "created_at": "2017-05-27T01:24:48+00:00" }, { "id": 118810130, "user": "user_36df932e8b7a", "body": "hmmmm", "path": "requests/models.py", "line": null, "side": "RIGHT", "created_at": "2017-05-27T01:25:13+00:00" }, { "id": 118810146, "user": "user_0fa58b6f3572", "body": "\"Harmless\" seems in conflict with \"Extra surface area that doesn't seem to provide much benefit\"", "path": "requests/models.py", "line": null, "side": "RIGHT", "created_at": "2017-05-27T01:25:35+00:00" }, { "id": 118810161, "user": "user_0fa58b6f3572", "body": "Also, `next_request` would be more intuitive.", "path": "requests/models.py", "line": null, "side": "RIGHT", "created_at": "2017-05-27T01:26:16+00:00" }, { "id": 118810202, "user": "user_36df932e8b7a", "body": "i remember why i left this off now.", "path": "requests/models.py", "line": null, "side": "RIGHT", "created_at": "2017-05-27T01:27:54+00:00" }, { "id": 118811413, "user": "user_36df932e8b7a", "body": "if responses recorded their sent arguments, this would have made sense.", "path": "requests/models.py", "line": null, "side": "RIGHT", "created_at": "2017-05-27T02:32:03+00:00" }, { "id": 119315555, "user": "user_f068c71fd303", "body": "Ok, so I just stumbled across this in the code, and this is *very* confusing. Despite this being a generator, it is a generator that can literally be iterated only once in this mode before it starts doing something stupid (where \"stupid\" is that it repeatedly runs the same processing). That's not actually written down anywhere, so it would probably help us to at least say that the \"yield requests\" mode can only yield *one* request.", "path": "requests/sessions.py", "line": 207, "side": "RIGHT", "created_at": "2017-05-31T09:46:17+00:00" } ], "meta": { "languages": [ "py" ], "touches_tests": false, "review_state_summary": { "COMMENTED": 15 }, "meaningful_comment_count": 13, "has_approval": false, "has_changes_requested": false, "total_review_comments": 15 } } { "_id": "e2f1113ca6f3b85a", "_schema_version": "1.0", "_cleaned_at": "2026-02-12T07:46:52.070120+00:00", "repo": "psf/requests", "repo_url": "https://github.com/psf/requests", "license_name": "Apache License 2.0", "license_spdx": "Apache-2.0", "pr_number": 4050, "title": "AttributeError error raised when `files` file-pointer (fp) resolves to None", "body": "The library raises NoneType error when file-pointer (fp) resolves to None.\n\n```\n>>> from requests import post\n>>> r = post(\"https://example.com\", files={\"file-name\": None})\nAttributeError: 'NoneType' object has no attribute 'read'\n```\n\nHowever, when a param value or json field is None they are not included in the request body.\n\n```\n>>> from requests import get\n>>> r = get(\"https://example.com\", params={\"file-name\": None})\n>>> r.request.url\n```\n\nThis commit makes the beahviour consistent for files.", "author": "user_057bcc779862", "created_at": "2017-05-23T17:50:04+00:00", "merged_at": "2018-05-17T20:56:18+00:00", "base_branch": "master", "head_branch": "master", "additions": 15, "deletions": 1, "changed_files": 4, "files": [ { "filename": "AUTHORS.rst", "status": "modified", "additions": 1, "deletions": 0, "changes": 1, "patch": "@@ -187,3 +187,4 @@ Patches and Suggestions\n - Nehal J Wani ([CONTRIBUTOR_REDACTED])\n - [NAME_REDACTED] ([CONTRIBUTOR_REDACTED])\n - [NAME_REDACTED] ([CONTRIBUTOR_REDACTED])\n+- [NAME_REDACTED] ([CONTRIBUTOR_REDACTED])" }, { "filename": "HISTORY.rst", "status": "modified", "additions": 1, "deletions": 0, "changes": 1, "patch": "@@ -23,6 +23,7 @@ dev\n - DNS resolution in proxy bypass no longer includes the username and password in\n the request. This also fixes the issue of DNS queries failing on macOS.\n - Properly normalize adapter prefixes for url comparison.\n+- Passing ``None`` as a file pointer to the ``files`` param no longer raises an exception.\n \n 2.18.4 (2017-08-15)\n +++++++++++++++++++" }, { "filename": "requests/models.py", "status": "modified", "additions": 5, "deletions": 1, "changes": 6, "patch": "@@ -155,8 +155,12 @@ def _encode_files(files, data):\n \n if isinstance(fp, (str, bytes, bytearray)):\n fdata = fp\n- else:\n+ elif hasattr(fp, 'read'):\n fdata = fp.read()\n+ elif fp is None:\n+ continue\n+ else:\n+ fdata = fp\n \n rf = RequestField(name=k, data=fdata, filename=fn, headers=fh)\n rf.make_multipart(content_type=ft)" }, { "filename": "tests/test_requests.py", "status": "modified", "additions": 8, "deletions": 0, "changes": 8, "patch": "@@ -676,6 +676,14 @@ def test_POSTBIN_GET_POST_FILES(self, httpbin):\n with pytest.raises(ValueError):\n requests.post(url, files=['bad file data'])\n \n+ def test_invalid_files_input(self, httpbin):\n+\n+ url = httpbin('post')\n+ post = requests.post(url,\n+ files={\"random-file-1\": None, \"random-file-2\": 1})\n+ assert b'name=\"random-file-1\"' not in post.request.body\n+ assert b'name=\"random-file-2\"' in post.request.body\n+\n def test_POSTBIN_SEEKED_OBJECT_WITH_NO_ITER(self, httpbin):\n \n class TestStream(object):" } ], "reviews": [ { "id": 39828665, "user": "user_f068c71fd303", "state": "DISMISSED", "body": "This seems pretty reasonable! Do you mind also adding a test?", "submitted_at": "2017-05-23T18:26:52+00:00" }, { "id": 40093513, "user": "user_5aa2dfb060a3", "state": "COMMENTED", "body": null, "submitted_at": "2017-05-24T17:21:17+00:00" }, { "id": 40664098, "user": "user_36df932e8b7a", "state": "COMMENTED", "body": null, "submitted_at": "2017-05-28T04:13:06+00:00" }, { "id": 121068804, "user": "user_dbf2a999bd6d", "state": "CHANGES_REQUESTED", "body": "Hey [USER_REDACTED], I've created a branch on the Requests repository titled \"none_filepointer\". \n\nYou can use `git fetch` to pull down the branch locally and cherry pick your commit. If you don't have a remote url for Requests, you can use [this guide](https://help.github.com/articles/adding-a-remote/) to get one set up.\n\nI've added one additional comment that I'd like [USER_REDACTED] to weigh in on, and then I think we're set.", "submitted_at": "2018-05-17T14:34:06+00:00" }, { "id": 121076142, "user": "user_0fa58b6f3572", "state": "COMMENTED", "body": null, "submitted_at": "2018-05-17T14:48:57+00:00" }, { "id": 121082339, "user": "user_dbf2a999bd6d", "state": "COMMENTED", "body": null, "submitted_at": "2018-05-17T15:02:11+00:00" }, { "id": 121172785, "user": "user_057bcc779862", "state": "COMMENTED", "body": null, "submitted_at": "2018-05-17T18:54:35+00:00" }, { "id": 121176706, "user": "user_dbf2a999bd6d", "state": "COMMENTED", "body": null, "submitted_at": "2018-05-17T19:06:27+00:00" }, { "id": 121184058, "user": "user_0fa58b6f3572", "state": "COMMENTED", "body": null, "submitted_at": "2018-05-17T19:29:43+00:00" }, { "id": 121186751, "user": "user_dbf2a999bd6d", "state": "COMMENTED", "body": null, "submitted_at": "2018-05-17T19:38:22+00:00" }, { "id": 121212973, "user": "user_dbf2a999bd6d", "state": "APPROVED", "body": null, "submitted_at": "2018-05-17T20:55:58+00:00" } ], "review_comments": [ { "id": 118069700, "user": "user_f068c71fd303", "body": "I'd rather we explicitly look for `None`. Do you mind making this change?", "path": "requests/models.py", "line": null, "side": "RIGHT", "created_at": "2017-05-23T18:26:38+00:00" }, { "id": 118313332, "user": "user_5aa2dfb060a3", "body": "Sorry that I randomly come out of nowhere once in a blue moon to give review comments so ignore my comment if you like :) But hasattr has a small edge case which can cause an unexpected error in Python 2. You can refer to the link here:\nhttps://hynek.me/articles/hasattr/\n\nThe article does mention that if you know what you are doing then its all good. My recommendation is to use getattr with default value of None to avoid AttributeError", "path": "requests/models.py", "line": 158, "side": "RIGHT", "created_at": "2017-05-24T17:21:17+00:00" }, { "id": 118832722, "user": "user_36df932e8b7a", "body": "[USER_REDACTED] that's because properties in python2 aren't attributes. very known and undertstood functionality.", "path": "requests/models.py", "line": 158, "side": "RIGHT", "created_at": "2017-05-28T04:13:05+00:00" }, { "id": 188980399, "user": "user_dbf2a999bd6d", "body": "In this case, are we expecting the objects `__str__` representation to be sufficient? We currently blow up on things like `datetime` or `dict`, but this may have unexpected results.\n\nIf we're OK with the above, would it make more sense to reorg the conditionals to check for `read`, `None` and then everything else would be `fdata = fp`?\n\ne.g.\n```python\nif hasattr(fp, 'read'):\n fdata = fp.read()\nelif fp is None:\n continue\nelse:\n fdata = fp\n```", "path": "requests/models.py", "line": 162, "side": "RIGHT", "created_at": "2018-05-17T14:33:46+00:00" }, { "id": 188986297, "user": "user_0fa58b6f3572", "body": "So the code that will eventually handle this is [here](https://github.com/urllib3/urllib3/blob/c8c98c473ab30f427fe05057f2ceded10ec93153/urllib3/filepost.py#L78..L90). \n\nHonestly, at this point, we *could* simplify the conditional but I'd rather leave it and let it blow up for folks. In 3.0, I'd love to have this else branch raise an exception, though.", "path": "requests/models.py", "line": 162, "side": "RIGHT", "created_at": "2018-05-17T14:48:57+00:00" }, { "id": 188991186, "user": "user_dbf2a999bd6d", "body": "Alright, I'm on board with that. [USER_REDACTED] would you mind removing this `else` conditional to keep our existing functionality. We'll look at adding a more explicit exception in 3.0. Thanks!", "path": "requests/models.py", "line": 162, "side": "RIGHT", "created_at": "2018-05-17T15:02:11+00:00" }, { "id": 189065554, "user": "user_057bcc779862", "body": "[USER_REDACTED] \n\n```python\nelse:\n fdata = fp\n\nrf = RequestField(name=k, data=fdata, filename=fn, headers=fh)\n```\n\nGetting rid of else part will result in fdata being an unbound variable. Should we set it to fdata=None in else and let it blow up or leave things as is?", "path": "requests/models.py", "line": 162, "side": "RIGHT", "created_at": "2018-05-17T18:54:35+00:00" }, { "id": 189068901, "user": "user_dbf2a999bd6d", "body": "Urgh, yep. Ok so [USER_REDACTED] we may just want to put the exception in now. Non-file objects were already exploding on the read call so they never worked.\n\nWe *could* make sure the exception inherits from AttributeError if we want to ensure we’re not breaking anyone currently relying on this defect for flow control.", "path": "requests/models.py", "line": 162, "side": "RIGHT", "created_at": "2018-05-17T19:06:27+00:00" }, { "id": 189074857, "user": "user_0fa58b6f3572", "body": "[USER_REDACTED] I'd rather never inherit from `AttributeError` if possible. That is just a world of pain. We've done this in the past, but that means if people are putting too much code in their `try/except` block, we may cause them to enter an exception handling block.\n\nIn short, I think the code as is may be safe right now. If we want to be extra magical, we could do `fdata = str(fp)` but I really don't want to add that behaviour at all. Let's just leave this as is, I guess and plan to add the exception in 3.0", "path": "requests/models.py", "line": 162, "side": "RIGHT", "created_at": "2018-05-17T19:29:43+00:00" }, { "id": 189076966, "user": "user_dbf2a999bd6d", "body": "Sounds good! I think I misread your first response, so we should be set then.", "path": "requests/models.py", "line": 162, "side": "RIGHT", "created_at": "2018-05-17T19:38:22+00:00" } ], "meta": { "languages": [ "py", "rst" ], "touches_tests": true, "review_state_summary": { "DISMISSED": 1, "COMMENTED": 8, "CHANGES_REQUESTED": 1, "APPROVED": 1 }, "meaningful_comment_count": 10, "has_approval": true, "has_changes_requested": true, "total_review_comments": 10 } } { "_id": "6f0e3e1c09abc68a", "_schema_version": "1.0", "_cleaned_at": "2026-02-12T07:46:52.070120+00:00", "repo": "psf/requests", "repo_url": "https://github.com/psf/requests", "license_name": "Apache License 2.0", "license_spdx": "Apache-2.0", "pr_number": 4036, "title": "Pin sphinx", "body": "This will fix the build issues in Python 2.6 due to Sphinx's new requirement of `typing` in versions 1.6+. This pinning (capping) should only be in place until a solution for representing markers is introduced in Pipfile.\n\nWhile we're here doing cleanup, I've also removed the no longer needed `pipenv lock` before each build. Some preliminary tests show it saving 15-20% on the total build time for CI. We can scrap that though if it's not inline with the goal of the PR, getting the build working.", "author": "user_dbf2a999bd6d", "created_at": "2017-05-17T22:16:11+00:00", "merged_at": "2017-05-17T22:47:49+00:00", "base_branch": "master", "head_branch": "pin_sphinx", "additions": 79, "deletions": 117, "changed_files": 3, "files": [ { "filename": "Makefile", "status": "modified", "additions": 0, "deletions": 1, "changes": 1, "patch": "@@ -2,7 +2,6 @@\n \n init:\n \tpip install pipenv\n-\tpipenv lock\n \tpipenv install --dev\n \tpipenv run pip install -e .[socks]" }, { "filename": "Pipfile", "status": "modified", "additions": 2, "deletions": 2, "changes": 4, "patch": "@@ -6,8 +6,8 @@ verify_ssl = true\n pytest = \">=2.8.0\"\n codecov = \"*\"\n pytest-httpbin = \"==0.0.7\"\n-sphinx = \"*\"\n pytest-mock = \"*\"\n pytest-cov = \"*\"\n-pysocks = \"*\"\n alabaster = \"*\"\n+Sphinx = \"<=1.5.5\"\n+PySocks = \"*\"" }, { "filename": "Pipfile.lock", "status": "modified", "additions": 77, "deletions": 114, "changes": 191, "patch": "@@ -1,153 +1,116 @@\n {\n+ \"_meta\": {\n+ \"hash\": {\n+ \"sha256\": \"a26ef57f42fa3da7d70d1c1decb4e6445a6ff66e47c9094ddc9ab8e1f4c0a5b6\"\n+ },\n+ \"requires\": {},\n+ \"sources\": [\n+ {\n+ \"url\": \"https://pypi.python.org/simple\",\n+ \"verify_ssl\": true\n+ }\n+ ]\n+ },\n \"default\": {},\n \"develop\": {\n- \"snowballstemmer\": {\n- \"version\": \"==1.2.1\",\n- \"hash\": \"sha256:9f3bcd3c401c3e862ec0ebe6d2c069ebc012ce142cce209c098ccb5b09136e89\"\n- },\n- \"Werkzeug\": {\n- \"version\": \"==0.11.15\",\n- \"hash\": \"sha256:c6f6f89124df0514d886782c658c3e12f2caaa94da34cee3fd82eebf4ebf052b\"\n- },\n- \"six\": {\n- \"version\": \"==1.10.0\",\n- \"hash\": \"sha256:0ff78c403d9bccf5a425a6d31a12aa6b47f1c21ca4dc2573a7e2f32a97335eb1\"\n- },\n- \"funcsigs\": {\n- \"version\": \"==1.0.2\",\n- \"hash\": \"sha256:330cc27ccbf7f1e992e69fef78261dc7c6569012cf397db8d3de0234e6c937ca\"\n+ \"alabaster\": {\n+ \"version\": \"==0.7.10\"\n },\n- \"coverage\": {\n- \"version\": \"==4.3.4\",\n- \"hash\": \"sha256:36407249a0b6669c6ad4425b0f29685579df745480c03afa70f101f09f4eead3\"\n+ \"appdirs\": {\n+ \"version\": \"==1.4.3\"\n },\n- \"Flask\": {\n- \"version\": \"==0.12\",\n- \"hash\": \"sha256:7f03bb2c255452444f7265eddb51601806e5447b6f8a2d50bbc77a654a14c118\"\n+ \"babel\": {\n+ \"version\": \"==2.4.0\"\n },\n- \"alabaster\": {\n- \"version\": \"==0.7.9\",\n- \"hash\": \"sha256:d3e64a74919373d6d4d1d36bd717206584cb64cbb0532dfce3bc2081cba6817b\"\n+ \"click\": {\n+ \"version\": \"==6.7\"\n },\n- \"pytest-mock\": {\n- \"version\": \"==1.5.0\",\n- \"hash\": \"sha256:8e0fd43280c717f36920b60356bd713291b81a61704c94bc13aae9a12ef7fbd8\"\n+ \"codecov\": {\n+ \"version\": \"==2.0.9\"\n },\n- \"packaging\": {\n- \"version\": \"==16.8\",\n- \"hash\": \"sha256:99276dc6e3a7851f32027a68f1095cd3f77c148091b092ea867a351811cfe388\"\n+ \"coverage\": {\n+ \"version\": \"==4.4.1\"\n },\n- \"MarkupSafe\": {\n- \"version\": \"==0.23\",\n- \"hash\": \"sha256:a4ec1aff59b95a14b45eb2e23761a0179e98319da5a7eb76b56ea8cdc7b871c3\"\n+ \"decorator\": {\n+ \"version\": \"==4.0.11\"\n },\n- \"pytz\": {\n- \"version\": \"==2016.10\",\n- \"hash\": \"sha256:a1ea35e87a63c7825846d5b5c81d23d668e8a102d3b1b465ce95afe1b3a2e065\"\n+ \"docutils\": {\n+ \"version\": \"==0.13.1\"\n },\n- \"codecov\": {\n- \"version\": \"==2.0.5\",\n- \"hash\": \"sha256:9fb0cd4a43fe538b4ea229607d0a7d65b00f9bfb37bb6af60a17f4ac33707334\"\n+ \"flask\": {\n+ \"version\": \"==0.12.2\"\n },\n- \"pytest-httpbin\": {\n- \"version\": \"==0.2.3\",\n- \"hash\": \"sha256:c5b698dfa474ffc9caebcb35e34346b753eb226aea5c2e1b69fefedbcf161bf8\"\n+ \"funcsigs\": {\n+ \"version\": \"==1.0.2\"\n },\n \"httpbin\": {\n- \"version\": \"==0.5.0\",\n- \"hash\": \"sha256:710069973216d4bbf9ab6757f1e9a1f3be05832ce77da023adce0a98dfeecfee\"\n+ \"version\": \"==0.5.0\"\n },\n- \"pyparsing\": {\n- \"version\": \"==2.1.10\",\n- \"hash\": \"sha256:67101d7acee692962f33dd30b5dce079ff532dd9aa99ff48d52a3dad51d2fe84\"\n+ \"imagesize\": {\n+ \"version\": \"==0.7.1\"\n },\n- \"click\": {\n- \"version\": \"==6.7\",\n- \"hash\": \"sha256:29f99fc6125fbc931b758dc053b3114e55c77a6e4c6c3a2674a2dc986016381d\"\n+ \"itsdangerous\": {\n+ \"version\": \"==0.24\"\n },\n- \"appdirs\": {\n- \"version\": \"==1.4.0\",\n- \"hash\": \"sha256:85e58578db8f29538f3109c11250c2a5514a2fcdc9890d9b2fe777eb55517736\"\n+ \"jinja2\": {\n+ \"version\": \"==2.9.6\"\n },\n- \"imagesize\": {\n- \"version\": \"==0.7.1\",\n- \"hash\": \"sha256:6ebdc9e0ad188f9d1b2cdd9bc59cbe42bf931875e829e7a595e6b3abdc05cdfb\"\n+ \"markupsafe\": {\n+ \"version\": \"==1.0\"\n },\n- \"argparse\": {\n- \"version\": \"==1.4.0\",\n- \"hash\": \"sha256:c31647edb69fd3d465a847ea3157d37bed1f95f19760b11a47aa91c04b666314\"\n+ \"mock\": {\n+ \"version\": \"==2.0.0\"\n },\n- \"sphinx\": {\n- \"version\": \"==1.5.2\",\n- \"hash\": \"sha256:57c8636e1d23f6c01fb19911a8f255f1b4934ba69feb55bd4dd0f097ebb04f05\"\n+ \"packaging\": {\n+ \"version\": \"==16.8\"\n },\n \"pbr\": {\n- \"version\": \"==1.10.0\",\n- \"hash\": \"sha256:f5cf7265a80636ecff66806d13494cbf9d77a3758a65fd8b4d4d4bee81b0c375\"\n- },\n- \"babel\": {\n- \"version\": \"==2.3.4\",\n- \"hash\": \"sha256:3318ed2960240d61cbc6558858ee00c10eed77a6508c4d1ed8e6f7f48399c975\"\n+ \"version\": \"==3.0.0\"\n },\n \"py\": {\n- \"version\": \"==1.4.32\",\n- \"hash\": \"sha256:2d4bba2e25fff58140e6bdce1e485e89bb59776adbe01d490baa6b1f37a3dd6b\"\n+ \"version\": \"==1.4.33\"\n },\n- \"pytest-cov\": {\n- \"version\": \"==2.4.0\",\n- \"hash\": \"sha256:10e37e876f49ddec80d6c83a54b657157f1387ebc0f7755285f8c156130014a1\"\n+ \"pygments\": {\n+ \"version\": \"==2.2.0\"\n+ },\n+ \"pyparsing\": {\n+ \"version\": \"==2.2.0\"\n+ },\n+ \"pysocks\": {\n+ \"version\": \"==1.6.7\"\n },\n \"pytest\": {\n- \"version\": \"==3.0.6\",\n- \"hash\": \"sha256:da0ab50c7eec0683bc24f1c1137db1f4111752054ecdad63125e7ec71316b813\"\n+ \"version\": \"==3.0.7\"\n },\n- \"docutils\": {\n- \"version\": \"==0.13.1\",\n- \"hash\": \"sha256:de454f1015958450b72641165c08afe7023cd7e3944396448f2fb1b0ccba9d77\"\n+ \"pytest-cov\": {\n+ \"version\": \"==2.5.1\"\n },\n- \"Pygments\": {\n- \"version\": \"==2.2.0\",\n- \"hash\": \"sha256:78f3f434bcc5d6ee09020f92ba487f95ba50f1e3ef83ae96b9d5ffa1bab25c5d\"\n+ \"pytest-httpbin\": {\n+ \"version\": \"==0.0.7\"\n },\n- \"Jinja2\": {\n- \"version\": \"==2.9.5\",\n- \"hash\": \"sha256:a7b7438120dbe76a8e735ef7eba6048eaf4e0b7dbc530e100812f8ec462a4d50\"\n+ \"pytest-mock\": {\n+ \"version\": \"==1.6.0\"\n },\n- \"decorator\": {\n- \"version\": \"==4.0.11\",\n- \"hash\": \"sha256:73cbaadb8bc4e3c65fe1100773d56331a2d756cc0f5c7b9d8d5d5223fe04f600\"\n+ \"pytz\": {\n+ \"version\": \"==2017.2\"\n+ },\n+ \"requests\": {\n+ \"version\": \"==2.14.2\"\n },\n \"setuptools\": {\n- \"version\": \"==34.1.0\",\n- \"hash\": \"sha256:edd9d39782fe38b9c533002b2e6fdf06498793cbd29266accdcc519431d4b7ba\"\n+ \"version\": \"==35.0.2\"\n },\n- \"requests\": {\n- \"version\": \"==2.13.0\",\n- \"hash\": \"sha256:1a720e8862a41aa22e339373b526f508ef0c8988baf48b84d3fc891a8e237efb\"\n+ \"six\": {\n+ \"version\": \"==1.10.0\"\n },\n- \"itsdangerous\": {\n- \"version\": \"==0.24\",\n- \"hash\": \"sha256:cbb3fcf8d3e33df861709ecaf89d9e6629cff0a217bc2848f1b41cd30d360519\"\n+ \"snowballstemmer\": {\n+ \"version\": \"==1.2.1\"\n },\n- \"pysocks\": {\n- \"version\": \"==1.6.6\",\n- \"hash\": \"sha256:02419a225ff5dcfc3c9695ef8fc9b4d8cc99658e650c6d4718d4c8f451e63f41\"\n+ \"sphinx\": {\n+ \"version\": \"==1.5.5\"\n },\n- \"mock\": {\n- \"version\": \"==2.0.0\",\n- \"hash\": \"sha256:5ce3c71c5545b472da17b72268978914d0252980348636840bd34a00b5cc96c1\"\n- }\n- },\n- \"_meta\": {\n- \"sources\": [\n- {\n- \"url\": \"https://pypi.python.org/simple\",\n- \"verify_ssl\": true\n- }\n- ],\n- \"requires\": {},\n- \"hash\": {\n- \"sha256\": \"0b4728fe74b683054ddde5b9dba7dd674ce17b6726764407a9779b4fdd0afd47\"\n+ \"werkzeug\": {\n+ \"version\": \"==0.12.2\"\n }\n }\n-}\n\\ No newline at end of file\n+}" } ], "reviews": [ { "id": 38805361, "user": "user_f068c71fd303", "state": "COMMENTED", "body": null, "submitted_at": "2017-05-17T22:32:59+00:00" }, { "id": 38806015, "user": "user_dbf2a999bd6d", "state": "COMMENTED", "body": null, "submitted_at": "2017-05-17T22:37:08+00:00" }, { "id": 38806914, "user": "user_f068c71fd303", "state": "COMMENTED", "body": null, "submitted_at": "2017-05-17T22:43:27+00:00" }, { "id": 38807543, "user": "user_f068c71fd303", "state": "APPROVED", "body": null, "submitted_at": "2017-05-17T22:47:45+00:00" } ], "review_comments": [ { "id": 117125714, "user": "user_f068c71fd303", "body": "Is this necessary? This should only be run on `init`.", "path": "Makefile", "line": 5, "side": "LEFT", "created_at": "2017-05-17T22:32:59+00:00" }, { "id": 117126338, "user": "user_dbf2a999bd6d", "body": "Sorry, are you asking if the removal is necessary, or the locking?\n\nWe can leave this in, but it's an extra 4-5 minutes of CI time that doesn't actually need to run. Pipenv is no longer worrying about hashes on a package specific level, so platform conflicts aren't a problem now. If there is an actual change to the Pipfile not represented, Pipenv will rebuild things without this command, otherwise it uses the current Pipfile.lock.\n\nLike I said, we can not include this commit here, but this line should be removed at some point.\n\nEdit: `init` runs every time we start a build with `make` which means we perform the same expensive action on every build.", "path": "Makefile", "line": 5, "side": "LEFT", "created_at": "2017-05-17T22:37:08+00:00" }, { "id": 117127183, "user": "user_f068c71fd303", "body": "Ok, I don't mind removing it. =)", "path": "Makefile", "line": 5, "side": "LEFT", "created_at": "2017-05-17T22:43:27+00:00" } ], "meta": { "languages": [ "lock" ], "touches_tests": false, "review_state_summary": { "COMMENTED": 3, "APPROVED": 1 }, "meaningful_comment_count": 3, "has_approval": true, "has_changes_requested": false, "total_review_comments": 3 } } { "_id": "ccfe8aa6c2d40e6a", "_schema_version": "1.0", "_cleaned_at": "2026-02-12T07:46:52.070120+00:00", "repo": "psf/requests", "repo_url": "https://github.com/psf/requests", "license_name": "Apache License 2.0", "license_spdx": "Apache-2.0", "pr_number": 4033, "title": "Test that the readme renders in CI.", "body": "Resolves #4030.", "author": "user_f068c71fd303", "created_at": "2017-05-17T17:47:58+00:00", "merged_at": "2017-05-18T01:41:01+00:00", "base_branch": "master", "head_branch": "issue/4030", "additions": 8, "deletions": 2, "changed_files": 4, "files": [ { "filename": ".travis.yml", "status": "modified", "additions": 2, "deletions": 0, "changes": 2, "patch": "@@ -14,6 +14,8 @@ python:\n install: \"make\"\n # command to run tests\n script:\n+ - |\n+ if [[ \"$TRAVIS_PYTHON_VERSION\" != \"2.6\" ]] ; then make test-readme; fi\n - make coverage\n after_success:\n - pipenv run codecov" }, { "filename": "HISTORY.rst", "status": "modified", "additions": 1, "deletions": 1, "changes": 2, "patch": "@@ -47,7 +47,7 @@ Release History\n **Bugfixes**\n \n - Much improved handling of non-ASCII ``Location`` header values in redirects.\n- Fewer ``UnicodeDecodeError``s are encountered on Python 2, and Python 3 now\n+ Fewer ``UnicodeDecodeErrors`` are encountered on Python 2, and Python 3 now\n correctly understands that Latin-1 is unlikely to be the correct encoding.\n - If an attempt to ``seek`` file to find out its length fails, we now\n appropriately handle that by [NAME_REDACTED]" }, { "filename": "Makefile", "status": "modified", "additions": 3, "deletions": 0, "changes": 3, "patch": "@@ -10,6 +10,9 @@ test:\n \t# the -k flag, like \"py.test -k test_path_is_not_double_encoded\"\n \tpipenv run py.test tests\n \n+test-readme:\n+\tpipenv run python setup.py check -r -s\n+\n coverage:\n \tpipenv run py.test --cov-config .coveragerc --verbose --cov-report term --cov-report xml --cov=requests tests" }, { "filename": "Pipfile", "status": "modified", "additions": 2, "deletions": 1, "changes": 3, "patch": "@@ -9,5 +9,6 @@ pytest-httpbin = \"==0.0.7\"\n pytest-mock = \"*\"\n pytest-cov = \"*\"\n alabaster = \"*\"\n+readme_renderer = \"*\"\n Sphinx = \"<=1.5.5\"\n-PySocks = \"*\"\n+PySocks = \"*\"\n\\ No newline at end of file" } ], "reviews": [ { "id": 38821137, "user": "user_0fa58b6f3572", "state": "APPROVED", "body": null, "submitted_at": "2017-05-18T00:37:47+00:00" }, { "id": 38821459, "user": "user_0fa58b6f3572", "state": "CHANGES_REQUESTED", "body": null, "submitted_at": "2017-05-18T00:40:41+00:00" }, { "id": 38822713, "user": "user_f068c71fd303", "state": "COMMENTED", "body": null, "submitted_at": "2017-05-18T00:53:47+00:00" }, { "id": 38824019, "user": "user_0fa58b6f3572", "state": "APPROVED", "body": null, "submitted_at": "2017-05-18T01:08:21+00:00" } ], "review_comments": [ { "id": 117141189, "user": "user_0fa58b6f3572", "body": "This shouldn't be run on Python 2.6. It seems `readme-renderer` doesn't support 2.6.", "path": ".travis.yml", "line": null, "side": "RIGHT", "created_at": "2017-05-18T00:40:38+00:00" }, { "id": 117142372, "user": "user_f068c71fd303", "body": "Agh, that's a pain. Ok.", "path": ".travis.yml", "line": null, "side": "RIGHT", "created_at": "2017-05-18T00:53:47+00:00" } ], "meta": { "languages": [ "rst", "yml" ], "touches_tests": false, "review_state_summary": { "APPROVED": 2, "CHANGES_REQUESTED": 1, "COMMENTED": 1 }, "meaningful_comment_count": 2, "has_approval": true, "has_changes_requested": true, "total_review_comments": 2 } } { "_id": "60a4df3721209b15", "_schema_version": "1.0", "_cleaned_at": "2026-02-12T07:46:52.070120+00:00", "repo": "psf/requests", "repo_url": "https://github.com/psf/requests", "license_name": "Apache License 2.0", "license_spdx": "Apache-2.0", "pr_number": 3991, "title": "Remove some unused imports.", "body": null, "author": "user_d7d6ef67d567", "created_at": "2017-04-25T20:52:20+00:00", "merged_at": "2017-04-26T12:09:35+00:00", "base_branch": "master", "head_branch": "unused-imports", "additions": 5, "deletions": 6, "changed_files": 4, "files": [ { "filename": "requests/adapters.py", "status": "modified", "additions": 1, "deletions": 1, "changes": 2, "patch": "@@ -19,7 +19,7 @@\n from .compat import urlparse, basestring\n from .utils import (DEFAULT_CA_BUNDLE_PATH, get_encoding_from_headers,\n prepend_scheme_if_needed, get_auth_from_url, urldefragauth,\n- select_proxy, to_native_string)\n+ select_proxy)\n from .structures import CaseInsensitiveDict\n from .packages.urllib3.exceptions import ClosedPoolError\n from .packages.urllib3.exceptions import ConnectTimeoutError" }, { "filename": "requests/auth.py", "status": "modified", "additions": 0, "deletions": 1, "changes": 1, "patch": "@@ -20,7 +20,6 @@\n from .cookies import extract_cookies_to_jar\n from ._internal_utils import to_native_string\n from .utils import parse_dict_header\n-from .status_codes import codes\n \n CONTENT_TYPE_FORM_URLENCODED = 'application/x-www-form-urlencoded'\n CONTENT_TYPE_MULTI_PART = 'multipart/form-data'" }, { "filename": "requests/models.py", "status": "modified", "additions": 2, "deletions": 2, "changes": 4, "patch": "@@ -16,7 +16,7 @@\n # such as in [NAME_REDACTED] https://github.com/[USER_REDACTED]nethreitz/requests/issues/3578.\n import encodings.idna\n \n-from io import BytesIO, UnsupportedOperation\n+from io import UnsupportedOperation\n from .hooks import default_hooks\n from .structures import CaseInsensitiveDict\n \n@@ -36,7 +36,7 @@\n stream_decode_response_unicode, to_key_val_list, parse_header_links,\n iter_slices, guess_json_utf, super_len, check_header_validity)\n from .compat import (\n- cookielib, urlunparse, urlsplit, urlencode, str, bytes, StringIO,\n+ cookielib, urlunparse, urlsplit, urlencode, str, bytes,\n is_py2, chardet, builtin_str, basestring)\n from .compat import json as complexjson\n from .status_codes import codes" }, { "filename": "requests/utils.py", "status": "modified", "additions": 2, "deletions": 2, "changes": 4, "patch": "@@ -27,8 +27,8 @@\n from .compat import (\n quote, urlparse, bytes, str, OrderedDict, unquote, getproxies,\n proxy_bypass, urlunparse, basestring, integer_types)\n-from .cookies import RequestsCookieJar, cookiejar_from_dict\n-from .structures import CaseInsensitiveDict, TimedCache, TimedCacheManaged\n+from .cookies import cookiejar_from_dict\n+from .structures import CaseInsensitiveDict, TimedCacheManaged\n from .exceptions import (\n InvalidURL, InvalidHeader, FileModeWarning, UnrewindableBodyError)" } ], "reviews": [ { "id": 34689806, "user": "user_f068c71fd303", "state": "CHANGES_REQUESTED", "body": "Looks good aside from the chardet change.", "submitted_at": "2017-04-25T21:09:12+00:00" }, { "id": 34690237, "user": "user_d7d6ef67d567", "state": "COMMENTED", "body": null, "submitted_at": "2017-04-25T21:10:37+00:00" }, { "id": 34821060, "user": "user_0fa58b6f3572", "state": "APPROVED", "body": "Thanks [USER_REDACTED]", "submitted_at": "2017-04-26T12:08:47+00:00" }, { "id": 34821218, "user": "user_f068c71fd303", "state": "APPROVED", "body": "Indeed, thanks! :sparkles: :cake: :sparkles:", "submitted_at": "2017-04-26T12:09:29+00:00" } ], "review_comments": [ { "id": 113312356, "user": "user_f068c71fd303", "body": "Can you remove the changes from this file please? This is a third-party package we vendor unchanged.", "path": "requests/packages/chardet/chardetect.py", "line": null, "side": "LEFT", "created_at": "2017-04-25T21:08:53+00:00" }, { "id": 113312739, "user": "user_d7d6ef67d567", "body": "Thanks, I hadn't spotted that.", "path": "requests/packages/chardet/chardetect.py", "line": null, "side": "LEFT", "created_at": "2017-04-25T21:10:37+00:00" } ], "meta": { "languages": [ "py" ], "touches_tests": false, "review_state_summary": { "CHANGES_REQUESTED": 1, "COMMENTED": 1, "APPROVED": 2 }, "meaningful_comment_count": 2, "has_approval": true, "has_changes_requested": true, "total_review_comments": 2 } } { "_id": "1cfdb1088737479c", "_schema_version": "1.0", "_cleaned_at": "2026-02-12T07:46:52.070120+00:00", "repo": "psf/requests", "repo_url": "https://github.com/psf/requests", "license_name": "Apache License 2.0", "license_spdx": "Apache-2.0", "pr_number": 3984, "title": "Fix the additional newline generated by iter_lines() caused by a '\\r\\n' pair being separated in two different chunks.", "body": "When a \"\\r\\n\" CRLF pair is splitted into two chunks accidentally, iter_lines() generates two line breaks instead of one. This patch fixes the incorrect behavior and closes issue #3980.", "author": "user_abbc93680c09", "created_at": "2017-04-21T13:48:45+00:00", "merged_at": "2017-04-26T15:07:46+00:00", "base_branch": "proposed/3.0.0", "head_branch": "pcman@fix_iter_lines", "additions": 87, "deletions": 38, "changed_files": 2, "files": [ { "filename": "requests/models.py", "status": "modified", "additions": 21, "deletions": 0, "changes": 21, "patch": "@@ -776,7 +776,11 @@ def iter_lines(self, chunk_size=ITER_CHUNK_SIZE, decode_unicode=None, delimiter=\n \n .. note:: This method is not reentrant safe.\n \"\"\"\n+ carriage_return = u'\\r' if decode_unicode else b'\\r'\n+ line_feed = u'\\n' if decode_unicode else b'\\n'\n+\n pending = None\n+ last_chunk_ends_with_cr = False\n \n for chunk in self.iter_content(chunk_size=chunk_size,\n decode_unicode=decode_unicode):\n@@ -796,6 +800,23 @@ def iter_lines(self, chunk_size=ITER_CHUNK_SIZE, decode_unicode=None, delimiter=\n if delimiter:\n lines = chunk.split(delimiter)\n else:\n+ # Python splitlines() supports the universal newline (PEP 278).\n+ # That means, '\\r', '\\n', and '\\r\\n' are all treated as end of\n+ # line. If the last chunk ends with '\\r', and the current chunk\n+ # starts with '\\n', they should be merged and treated as only\n+ # *one* new line separator '\\r\\n' by splitlines().\n+ # This rule only applies when splitlines() is used.\n+\n+ # The last chunk ends with '\\r', so the '\\n' at chunk[0]\n+ # is just the second half of a '\\r\\n' pair rather than a\n+ # new line break. Just skip it.\n+ skip_first_char = last_chunk_ends_with_cr and chunk.startswith(line_feed)\n+ last_chunk_ends_with_cr = chunk.endswith(carriage_return)\n+ if skip_first_char:\n+ chunk = chunk[1:]\n+ # it's possible that after stripping the '\\n' then chunk becomes empty\n+ if not chunk:\n+ continue\n lines = chunk.splitlines()\n \n # Calling `.split(delimiter)` will always end with whatever text" }, { "filename": "tests/test_requests.py", "status": "modified", "additions": 66, "deletions": 38, "changes": 104, "patch": "@@ -1303,57 +1303,76 @@ def test_response_lines(self):\n might not be lined up ideally.\n \"\"\"\n mock_chunks = [\n- 'This \\r\\n',\n- '',\n- 'is\\r',\n- '\\n',\n- 'a',\n- ' ',\n- '',\n- '',\n- 'test.',\n- '\\r',\n- '\\n',\n- 'end.',\n+ b'This \\r\\n',\n+ b'',\n+ b'is\\r',\n+ b'\\n',\n+ b'a',\n+ b' ',\n+ b'',\n+ b'',\n+ b'test.',\n+ b'\\r',\n+ b'\\n',\n+ b'end.',\n ]\n- mock_data = ''.join(mock_chunks)\n+ mock_data = b''.join(mock_chunks)\n+ unicode_mock_data = mock_data.decode('utf-8')\n \n- mock_iter_content = lambda *args, **kwargs: (e for e in mock_chunks)\n+ def mock_iter_content(*args, **kwargs):\n+ if kwargs.get(\"decode_unicode\"):\n+ return (e.decode('utf-8') for e in mock_chunks)\n+ return (e for e in mock_chunks)\n \n r = requests.Response()\n r._content_consumed = True\n r.iter_content = mock_iter_content\n \n- assert list(r.iter_lines(delimiter='\\r\\n')) == mock_data.split('\\r\\n')\n+ # decode_unicode=None, output raw bytes\n+ assert list(r.iter_lines(delimiter=b'\\r\\n')) == mock_data.split(b'\\r\\n')\n \n- # Because '\\n' is a single line-end, when `iter_lines()` receives\n- # the chunks containing a single '\\n', it emits '' as a line -- whereas\n- # `.splitlines()` combines with the '\\r' and splits on `\\r\\n`.\n+ # decode_unicode=True, output unicode strings\n+ assert list(r.iter_lines(decode_unicode=True, delimiter=u'\\r\\n')) == unicode_mock_data.split(u'\\r\\n')\n+\n+ # When delimiter is None, we should yield the same result as splitlines()\n+ # which supports the universal newline.\n+ # '\\r', '\\n', and '\\r\\n' are all treated as one line break.\n+\n+ # decode_unicode=None, output raw bytes\n result = list(r.iter_lines())\n- assert result != mock_data.splitlines()\n- assert result[2] == ''\n- assert result[4] == ''\n+ assert result == mock_data.splitlines()\n+\n+ # decode_unicode=True, output unicode strings\n+ result = list(r.iter_lines(decode_unicode=True))\n+ assert result == unicode_mock_data.splitlines()\n+\n # If we change all the line breaks to `\\r`, we should be okay.\n- mock_chunks = [chunk.replace('\\n', '\\r') for chunk in mock_chunks]\n- mock_data = ''.join(mock_chunks)\n+ # decode_unicode=None, output raw bytes\n+ mock_chunks = [chunk.replace(b'\\n', b'\\r') for chunk in mock_chunks]\n+ mock_data = b''.join(mock_chunks)\n assert list(r.iter_lines()) == mock_data.splitlines()\n \n+ # decode_unicode=True, output unicode strings\n+ unicode_mock_data = mock_data.decode('utf-8')\n+ assert list(r.iter_lines(decode_unicode=True)) == unicode_mock_data.splitlines()\n+\n \n [USER_REDACTED].mark.parametrize(\n 'content, expected_no_delimiter, expected_delimiter', (\n- ([''], [], []),\n- (['line\\n'], ['line'], ['line\\n']),\n- (['line', '\\n'], ['line'], ['line\\n']),\n- (['line\\r\\n'], ['line'], ['line', '']),\n+ ([b''], [], []),\n+ ([b'line\\n'], [u'line'], [u'line\\n']),\n+ ([b'line', b'\\n'], [u'line'], [u'line\\n']),\n+ ([b'line\\r\\n'], [u'line'], [u'line', u'']),\n # Empty chunk in the end of stream, same behavior as the previous\n- (['line\\r\\n', ''], ['line'], ['line', '']),\n- (['line', '\\r\\n'], ['line'], ['line', '']),\n- (['a\\r', '\\nb\\r'], ['a', '', 'b'], ['a', 'b\\r']),\n- (['a\\n', '\\nb'], ['a', '', 'b'], ['a\\n\\nb']),\n- (['a\\r\\n','\\rb\\n'], ['a', '', 'b'], ['a', '\\rb\\n']),\n- (['a\\nb', 'c'], ['a', 'bc'], ['a\\nbc']),\n- (['a\\n', '\\rb', '\\r\\nc'], ['a', '', 'b', 'c'], ['a\\n\\rb', 'c']),\n- (['a\\r\\nb', '', 'c'], ['a', 'bc'], ['a', 'bc']) # Empty chunk with pending data\n+ ([b'line\\r\\n', b''], [u'line'], [u'line', u'']),\n+ ([b'line', b'\\r\\n'], [u'line'], [u'line', u'']),\n+ ([b'a\\r', b'\\nb\\r'], [u'a', u'b'], [u'a', u'b\\r']),\n+ ([b'a\\r', b'\\n', b'\\nb'], [u'a', u'', u'b'], [u'a', u'\\nb']),\n+ ([b'a\\n', b'\\nb'], [u'a', u'', u'b'], [u'a\\n\\nb']),\n+ ([b'a\\r\\n', b'\\rb\\n'], [u'a', u'', u'b'], [u'a', u'\\rb\\n']),\n+ ([b'a\\nb', b'c'], [u'a', u'bc'], [u'a\\nbc']),\n+ ([b'a\\n', b'\\rb', b'\\r\\nc'], [u'a', u'', u'b', u'c'], [u'a\\n\\rb', u'c']),\n+ ([b'a\\r\\nb', b'', b'c'], [u'a', u'bc'], [u'a', u'bc']) # Empty chunk with pending data\n ))\n def test_response_lines_parametrized(self, content, expected_no_delimiter, expected_delimiter):\n \"\"\"\n@@ -1363,13 +1382,22 @@ def test_response_lines_parametrized(self, content, expected_no_delimiter, expec\n https://github.com/[USER_REDACTED]nethreitz/requests/pull/2431#issuecomment-72333964\n \"\"\"\n mock_chunks = content\n- mock_iter_content = lambda *args, **kwargs: (e for e in mock_chunks)\n+ def mock_iter_content(*args, **kwargs):\n+ if kwargs.get(\"decode_unicode\"):\n+ return (e.decode('utf-8') for e in mock_chunks)\n+ return (e for e in mock_chunks)\n \n r = requests.Response()\n r._content_consumed = True\n r.iter_content = mock_iter_content\n- assert list(r.iter_lines()) == expected_no_delimiter\n- assert list(r.iter_lines(delimiter='\\r\\n')) == expected_delimiter\n+\n+ # decode_unicode=True, output unicode strings\n+ assert list(r.iter_lines(decode_unicode=True)) == expected_no_delimiter\n+ assert list(r.iter_lines(decode_unicode=True, delimiter='\\r\\n')) == expected_delimiter\n+\n+ # decode_unicode=None, output raw bytes\n+ assert list(r.iter_lines()) == [line.encode('utf-8') for line in expected_no_delimiter]\n+ assert list(r.iter_lines(delimiter=b'\\r\\n')) == [line.encode('utf-8') for line in expected_delimiter]\n \n def test_prepared_request_is_pickleable(self, httpbin):\n p = requests.Request('GET', httpbin('get')).prepare()" } ], "reviews": [ { "id": 34036003, "user": "user_f068c71fd303", "state": "CHANGES_REQUESTED", "body": "Cool, this patch looks broadly right! I've left a few minor structural notes in the diff.\n\nAdditionally, it'd be good if you could add a test that reproduces this problem and demonstrates that it's fixed. Should be easily enough done with careful choice of body and chunk size.", "submitted_at": "2017-04-21T14:25:21+00:00" }, { "id": 34037445, "user": "user_abbc93680c09", "state": "COMMENTED", "body": null, "submitted_at": "2017-04-21T14:28:22+00:00" }, { "id": 34093745, "user": "user_dbf2a999bd6d", "state": "COMMENTED", "body": null, "submitted_at": "2017-04-21T18:28:39+00:00" }, { "id": 34149703, "user": "user_abbc93680c09", "state": "COMMENTED", "body": null, "submitted_at": "2017-04-22T03:58:02+00:00" }, { "id": 34152670, "user": "user_f068c71fd303", "state": "CHANGES_REQUESTED", "body": null, "submitted_at": "2017-04-22T07:50:16+00:00" }, { "id": 34153258, "user": "user_abbc93680c09", "state": "COMMENTED", "body": null, "submitted_at": "2017-04-22T08:34:12+00:00" }, { "id": 34156470, "user": "user_0fa58b6f3572", "state": "COMMENTED", "body": null, "submitted_at": "2017-04-22T12:36:17+00:00" }, { "id": 34156871, "user": "user_abbc93680c09", "state": "COMMENTED", "body": null, "submitted_at": "2017-04-22T12:53:05+00:00" }, { "id": 34156881, "user": "user_abbc93680c09", "state": "COMMENTED", "body": null, "submitted_at": "2017-04-22T12:54:01+00:00" }, { "id": 34167217, "user": "user_f068c71fd303", "state": "CHANGES_REQUESTED", "body": "Cool, this is looking really good. A few minor stylistic notes for you.", "submitted_at": "2017-04-22T22:20:41+00:00" }, { "id": 34279166, "user": "user_f068c71fd303", "state": "CHANGES_REQUESTED", "body": null, "submitted_at": "2017-04-24T12:27:09+00:00" }, { "id": 34461054, "user": "user_abbc93680c09", "state": "COMMENTED", "body": null, "submitted_at": "2017-04-25T03:07:48+00:00" }, { "id": 34461587, "user": "user_abbc93680c09", "state": "COMMENTED", "body": null, "submitted_at": "2017-04-25T03:14:54+00:00" }, { "id": 34486801, "user": "user_f068c71fd303", "state": "COMMENTED", "body": null, "submitted_at": "2017-04-25T07:33:50+00:00" }, { "id": 34487004, "user": "user_f068c71fd303", "state": "COMMENTED", "body": null, "submitted_at": "2017-04-25T07:35:00+00:00" }, { "id": 34487060, "user": "user_f068c71fd303", "state": "APPROVED", "body": "So this is now looking good except for my possible concern about the readability of our two alternative approaches. I'd like either [USER_REDACTED] or [USER_REDACTED] to weigh in there, if possible.", "submitted_at": "2017-04-25T07:35:23+00:00" }, { "id": 34538082, "user": "user_0fa58b6f3572", "state": "CHANGES_REQUESTED", "body": null, "submitted_at": "2017-04-25T11:44:02+00:00" }, { "id": 34577415, "user": "user_dbf2a999bd6d", "state": "COMMENTED", "body": null, "submitted_at": "2017-04-25T14:20:18+00:00" }, { "id": 34820748, "user": "user_0fa58b6f3572", "state": "APPROVED", "body": "This looks fine to me.", "submitted_at": "2017-04-26T12:07:28+00:00" }, { "id": 34821101, "user": "user_f068c71fd303", "state": "CHANGES_REQUESTED", "body": "Looks good to me too. Do you want to squash the commits down just for cleanliness sake? Then I'll go ahead and merge.", "submitted_at": "2017-04-26T12:09:01+00:00" }, { "id": 34870694, "user": "user_f068c71fd303", "state": "APPROVED", "body": "Not at all, thank you for working with us to get this ready to go. Well done! ✨ :cake: :sparkles:", "submitted_at": "2017-04-26T15:07:39+00:00" } ], "review_comments": [ { "id": 112698737, "user": "user_f068c71fd303", "body": "Let's hoist the result of these two `else` calls to the top of the function, rather than check it twice each time around the loop:\n\n```python\ncarriage_return = u'\\r' if decode_unicode else b'\\r'\nline_feed = u'\\n' if decode_unicode else b'\\r'\n```", "path": "requests/models.py", "line": null, "side": "RIGHT", "created_at": "2017-04-21T14:22:38+00:00" }, { "id": 112699072, "user": "user_f068c71fd303", "body": "We should expand this comment to explain that this only affects the `splitlines` case because `splitlines` will treat any of `\\r`, `\\r\\n`, and `\\n` as newlines, and so splitting `\\r\\n` into two chunks will get misleading results.", "path": "requests/models.py", "line": null, "side": "RIGHT", "created_at": "2017-04-21T14:24:03+00:00" }, { "id": 112699199, "user": "user_f068c71fd303", "body": "It would also be good to hoist this into the block that holds the `splitlines` call, as we don't need to do this processing in any other situation.", "path": "requests/models.py", "line": null, "side": "RIGHT", "created_at": "2017-04-21T14:24:36+00:00" }, { "id": 112700068, "user": "user_abbc93680c09", "body": "OK, will do that.", "path": "requests/models.py", "line": null, "side": "RIGHT", "created_at": "2017-04-21T14:28:22+00:00" }, { "id": 112750569, "user": "user_dbf2a999bd6d", "body": "One thing to keep in mind here is the final line of the file ending in `\\r\\n`. If we split at `\\r`, we get a final one byte line of `\\n`. This code makes chunk equivalent to `''` and `''.splitlines()` will result in an empty list. You'll get an index out of bounds with the call `lines[-1]` below.\n\nProbably a rarer edge case but something we should cover.", "path": "requests/models.py", "line": null, "side": "RIGHT", "created_at": "2017-04-21T18:28:39+00:00" }, { "id": 112802065, "user": "user_abbc93680c09", "body": "Fixed. Thanks.", "path": "requests/models.py", "line": null, "side": "RIGHT", "created_at": "2017-04-22T03:58:02+00:00" }, { "id": 112804908, "user": "user_f068c71fd303", "body": "Why has the condition been doubled up here? Under what circumstances will `line[-1][-1]` be falsey?", "path": "requests/models.py", "line": null, "side": "RIGHT", "created_at": "2017-04-22T07:46:44+00:00" }, { "id": 112804913, "user": "user_f068c71fd303", "body": "Again, this should be brought into the if branch above.", "path": "requests/models.py", "line": null, "side": "RIGHT", "created_at": "2017-04-22T07:47:10+00:00" }, { "id": 112804923, "user": "user_f068c71fd303", "body": "These tests run on Python 2, so Unicode strings must be prefixed with `u`", "path": "tests/test_requests.py", "line": null, "side": "RIGHT", "created_at": "2017-04-22T07:48:24+00:00" }, { "id": 112804937, "user": "user_f068c71fd303", "body": "Again, your test seems to show that all the unprefixed strings are intended to be Unicode: they need to be prefixed", "path": "tests/test_requests.py", "line": null, "side": "RIGHT", "created_at": "2017-04-22T07:50:11+00:00" }, { "id": 112805532, "user": "user_abbc93680c09", "body": "Sorry I forgot to remove them. It should be prevented by [NAME_REDACTED][1:].", "path": "requests/models.py", "line": null, "side": "RIGHT", "created_at": "2017-04-22T08:34:12+00:00" }, { "id": 112808824, "user": "user_0fa58b6f3572", "body": "Wasn't universal newline support dropped in Python 3? I know you can no longer get a TextIOBuffer object that supports that. How does that affect splitting strings?", "path": "requests/models.py", "line": 803, "side": "RIGHT", "created_at": "2017-04-22T12:34:09+00:00" }, { "id": 112808835, "user": "user_0fa58b6f3572", "body": "Why is there an extra space between `and` and `lines[-1][-1]`?", "path": "requests/models.py", "line": null, "side": "RIGHT", "created_at": "2017-04-22T12:34:54+00:00" }, { "id": 112809228, "user": "user_abbc93680c09", "body": "Well, splitlines() actually supports a superset of universal newline.\nFYI: https://docs.python.org/3/library/stdtypes.html#str.splitlines\nThe unicode strings supports a superset of universal newline.\nHowever, the new python 3 bytes behaves differently.\nhttps://docs.python.org/3/library/stdtypes.html#bytes.splitlines\nIn both cases, however, the '\\r', '\\n', and '\\r\\n' rule still apply.", "path": "requests/models.py", "line": 803, "side": "RIGHT", "created_at": "2017-04-22T12:53:05+00:00" }, { "id": 112809236, "user": "user_abbc93680c09", "body": "removed.", "path": "requests/models.py", "line": null, "side": "RIGHT", "created_at": "2017-04-22T12:54:01+00:00" }, { "id": 112820053, "user": "user_f068c71fd303", "body": "Minor nit: as there are inverted commas around `'\\r'` in the line above, they should be added here around `\\n`.", "path": "requests/models.py", "line": null, "side": "RIGHT", "created_at": "2017-04-22T22:18:17+00:00" }, { "id": 112820068, "user": "user_f068c71fd303", "body": "Minor nit: should be `*one*`, not `\"one\"`.", "path": "requests/models.py", "line": null, "side": "RIGHT", "created_at": "2017-04-22T22:18:52+00:00" }, { "id": 112929801, "user": "user_f068c71fd303", "body": "Oooh, just noticed a subtle misbehaviour. Imagine we get the following chunks:\n\n```python\n[b'this is a string\\r', b'\\n', b'\\nso is this']\n```\n\nThis will not do the right thing: we'll strip *two* newline characters, rather than emit an empty line. That is, we'll emit: `[b'this is a string', b'so is this']` instead of `[b'this is a string', b'', b'so is this']`, which is what we *should* emit.\n\nThis is because a chunk that is *just* a `\\n` causes an early continue, above, without resetting the value of the `last_chunk_ends_with_cr` boolean. Essentially it gets completely ignored. That's not right.\n\nIt'd be good to add a test case (or modify an existing one) to include that case, and then fix it up by [NAME_REDACTED] before the `if not chunk: continue` clause.", "path": "requests/models.py", "line": null, "side": "RIGHT", "created_at": "2017-04-24T12:15:33+00:00" }, { "id": 112930599, "user": "user_f068c71fd303", "body": "We can probably collapse this line into the one above it as with the other assertions:\n\n```python\nassert list(r.iter_lines()) == mock_data.splitlines()\n```", "path": "tests/test_requests.py", "line": 1343, "side": "RIGHT", "created_at": "2017-04-24T12:20:19+00:00" }, { "id": 113098987, "user": "user_abbc93680c09", "body": "This piece of code seems to be outdated. I didnt' see it in the current HEAD.", "path": "tests/test_requests.py", "line": 1343, "side": "RIGHT", "created_at": "2017-04-25T03:07:48+00:00" }, { "id": 113099559, "user": "user_abbc93680c09", "body": "[USER_REDACTED] Nice catch! Sorry that I overlooked such a simple check. Just add a simple fix along with a test case for it. BTW, I did not hoist the flag per your request. It will look somewhat like this:\n```\n # a temp variable is needed here and I cannot find a good variable naming that is not confusing\n old_last_chunk_ends_with_cr = last_chunk_ends_with_cr\n last_chunk_ends_with_cr = chunk.endswith(carriage_return)\n if old_last_chunk_ends_with_cr and chunk.startswith(line_feed):\n chunk = chunk[1:]\n if not chunk:\n continue\n```\nAlso this yields an unnecessary method call endwiths('\\r') since when chun[1:] is empty we already know the result is False. So I prefer just setting the flag to False though it looks like code duplication at first glance.\n```\nif not chunk:\n last_chunk_ends_with_cr = False\n```\nSimple and readable.", "path": "requests/models.py", "line": null, "side": "RIGHT", "created_at": "2017-04-25T03:14:53+00:00" }, { "id": 113124383, "user": "user_f068c71fd303", "body": "Hrm. I don't know if I think it's more readable to do it this way. It means there are two places in the code that set this variable, instead of just one, which forces the reader to ask themselves *why* it was done this way. I don't know that the efficiency gains are worth it. 🤔", "path": "requests/models.py", "line": null, "side": "RIGHT", "created_at": "2017-04-25T07:33:50+00:00" }, { "id": 113124567, "user": "user_f068c71fd303", "body": "Yup, you're right.", "path": "tests/test_requests.py", "line": 1343, "side": "RIGHT", "created_at": "2017-04-25T07:35:00+00:00" }, { "id": 113172022, "user": "user_0fa58b6f3572", "body": "Now that I understand what concerns [USER_REDACTED] has, I agree. I think this could be better written as:\n\n```py\nchunk_startswith_line_feed = last_chunk_ends_with_cr and chunk.startswith(line_feed)\nlast_chunk_ends_with_cr = chunk.endswith(carriage_return)\nif chunk_startswith_line_feed:\n chunk = chunk[1:]\n if not chunk:\n continue\nlines = chunk.splitlines()\n```\n\nThis properly *explains* the condition on this line with a descriptive variable name. It avoids the `old_last_chunk_ends_with_cr` variable and it keeps things concise and easy to reason about.", "path": "requests/models.py", "line": null, "side": "RIGHT", "created_at": "2017-04-25T11:43:58+00:00" }, { "id": 113207852, "user": "user_dbf2a999bd6d", "body": "Yep, I'm on board with [USER_REDACTED]'s suggestion. That seems the most readable option out of what's been suggested.\n\nThe only minor input I have is standardizing the use of `_` in `ends_with` vs `startswith` in the variable names.", "path": "requests/models.py", "line": null, "side": "RIGHT", "created_at": "2017-04-25T14:20:18+00:00" } ], "meta": { "languages": [ "py" ], "touches_tests": true, "review_state_summary": { "CHANGES_REQUESTED": 6, "COMMENTED": 12, "APPROVED": 3 }, "meaningful_comment_count": 24, "has_approval": true, "has_changes_requested": true, "total_review_comments": 25 } } { "_id": "2220b573eddd9f30", "_schema_version": "1.0", "_cleaned_at": "2026-02-12T07:46:52.070120+00:00", "repo": "psf/requests", "repo_url": "https://github.com/psf/requests", "license_name": "Apache License 2.0", "license_spdx": "Apache-2.0", "pr_number": 3983, "title": "Add appveyor testing of Requests.", "body": "In general it'd be good to have more testing, but it's also possible that via PR #3979 we'll get unexpected different behaviour on Windows than on other platforms. For this reason, we should start also testing on Windows.\n\nThis PR takes the configuration used for urllib3, updates it for Requests, and then provides it. We'll still need to actually enable Appveyor so that it'll try to build, which I cannot do as I don't have admin on the repo. [USER_REDACTED], mind giving that a try?", "author": "user_f068c71fd303", "created_at": "2017-04-21T11:09:03+00:00", "merged_at": "2017-04-24T16:49:25+00:00", "base_branch": "master", "head_branch": "appveyor", "additions": 290, "deletions": 0, "changed_files": 2, "files": [ { "filename": "_appveyor/install.ps1", "status": "added", "additions": 229, "deletions": 0, "changes": 229, "patch": "@@ -0,0 +1,229 @@\n+# Sample script to install Python and pip under Windows\n+# Authors: [NAME_REDACTED], [NAME_REDACTED], [NAME_REDACTED], and [NAME_REDACTED]\n+# License: CC0 1.0 Universal: http://creativecommons.org/publicdomain/zero/1.0/\n+\n+$MINICONDA_URL = \"http://repo.continuum.io/miniconda/\"\n+$BASE_URL = \"https://www.python.org/ftp/python/\"\n+$GET_PIP_URL = \"https://bootstrap.pypa.io/get-pip.py\"\n+$GET_PIP_PATH = \"C:\\get-pip.py\"\n+\n+$PYTHON_PRERELEASE_REGEX = @\"\n+(?x)\n+(?\\d+)\n+\\.\n+(?\\d+)\n+\\.\n+(?\\d+)\n+(?[a-z]{1,2}\\d+)\n+\"@\n+\n+\n+function Download ($filename, $url) {\n+ $webclient = [NAME_REDACTED]\n+\n+ $basedir = $pwd.Path + \"\\\"\n+ $filepath = $basedir + $filename\n+ if (Test-Path $filename) {\n+ Write-Host \"Reusing\" $filepath\n+ return $filepath\n+ }\n+\n+ # Download and retry up to 3 times in case of network transient errors.\n+ Write-Host \"Downloading\" $filename \"from\" $url\n+ $retry_attempts = 2\n+ for ($i = 0; $i -lt $retry_attempts; $i++) {\n+ try {\n+ $webclient.DownloadFile($url, $filepath)\n+ break\n+ }\n+ Catch [Exception]{\n+ Start-Sleep 1\n+ }\n+ }\n+ if (Test-Path $filepath) {\n+ Write-Host \"File saved at\" $filepath\n+ } else {\n+ # Retry once to get the error message if any at the last try\n+ $webclient.DownloadFile($url, $filepath)\n+ }\n+ return $filepath\n+}\n+\n+\n+function ParsePythonVersion ($python_version) {\n+ if ($python_version -match $PYTHON_PRERELEASE_REGEX) {\n+ return ([int]$matches.major, [int]$matches.minor, [int]$matches.micro,\n+ $matches.prerelease)\n+ }\n+ $version_obj = [version]$python_version\n+ return ($version_obj.major, $version_obj.minor, $version_obj.build, \"\")\n+}\n+\n+\n+function DownloadPython ($python_version, $platform_suffix) {\n+ $major, $minor, $micro, $prerelease = ParsePythonVersion $python_version\n+\n+ if (($major -le 2 -and $micro -eq 0) `\n+ -or ($major -eq 3 -and $minor -le 2 -and $micro -eq 0) `\n+ ) {\n+ $dir = \"$major.$minor\"\n+ $python_version = \"$major.$minor$prerelease\"\n+ } else {\n+ $dir = \"$major.$minor.$micro\"\n+ }\n+\n+ if ($prerelease) {\n+ if (($major -le 2) `\n+ -or ($major -eq 3 -and $minor -eq 1) `\n+ -or ($major -eq 3 -and $minor -eq 2) `\n+ -or ($major -eq 3 -and $minor -eq 3) `\n+ ) {\n+ $dir = \"$dir/prev\"\n+ }\n+ }\n+\n+ if (($major -le 2) -or ($major -le 3 -and $minor -le 4)) {\n+ $ext = \"msi\"\n+ if ($platform_suffix) {\n+ $platform_suffix = \".$platform_suffix\"\n+ }\n+ } else {\n+ $ext = \"exe\"\n+ if ($platform_suffix) {\n+ $platform_suffix = \"-$platform_suffix\"\n+ }\n+ }\n+\n+ $filename = \"python-$python_version$platform_suffix.$ext\"\n+ $url = \"$BASE_URL$dir/$filename\"\n+ $filepath = Download $filename $url\n+ return $filepath\n+}\n+\n+\n+function InstallPython ($python_version, $architecture, $python_home) {\n+ Write-Host \"[NAME_REDACTED]\" $python_version \"for\" $architecture \"bit architecture to\" $python_home\n+ if (Test-Path $python_home) {\n+ Write-Host $python_home \"already exists, skipping.\"\n+ return $false\n+ }\n+ if ($architecture -eq \"32\") {\n+ $platform_suffix = \"\"\n+ } else {\n+ $platform_suffix = \"amd64\"\n+ }\n+ $installer_path = DownloadPython $python_version $platform_suffix\n+ $installer_ext = [System.IO.Path]::GetExtension($installer_path)\n+ Write-Host \"Installing $installer_path to $python_home\"\n+ $install_log = $python_home + \".log\"\n+ if ($installer_ext -eq '.msi') {\n+ InstallPythonMSI $installer_path $python_home $install_log\n+ } else {\n+ InstallPythonEXE $installer_path $python_home $install_log\n+ }\n+ if (Test-Path $python_home) {\n+ Write-Host \"Python $python_version ($architecture) installation complete\"\n+ } else {\n+ Write-Host \"Failed to install Python in $python_home\"\n+ Get-Content -Path $install_log\n+ Exit 1\n+ }\n+}\n+\n+\n+function InstallPythonEXE ($exepath, $python_home, $install_log) {\n+ $install_args = \"/quiet InstallAllUsers=1 TargetDir=$python_home\"\n+ RunCommand $exepath $install_args\n+}\n+\n+\n+function InstallPythonMSI ($msipath, $python_home, $install_log) {\n+ $install_args = \"/qn /log $install_log /i $msipath TARGETDIR=$python_home\"\n+ $uninstall_args = \"/qn /x $msipath\"\n+ RunCommand \"msiexec.exe\" $install_args\n+ if (-not(Test-Path $python_home)) {\n+ Write-Host \"Python seems to be installed else-where, reinstalling.\"\n+ RunCommand \"msiexec.exe\" $uninstall_args\n+ RunCommand \"msiexec.exe\" $install_args\n+ }\n+}\n+\n+function RunCommand ($command, $command_args) {\n+ Write-Host $command $command_args\n+ Start-Process -FilePath $command -ArgumentList $command_args -Wait -Passthru\n+}\n+\n+\n+function InstallPip ($python_home) {\n+ $pip_path = $python_home + \"\\Scripts\\pip.exe\"\n+ $python_path = $python_home + \"\\python.exe\"\n+ if (-not(Test-Path $pip_path)) {\n+ Write-Host \"Installing pip...\"\n+ $webclient = [NAME_REDACTED]\n+ $webclient.DownloadFile($GET_PIP_URL, $GET_PIP_PATH)\n+ Write-Host \"Executing:\" $python_path $GET_PIP_PATH\n+ & $python_path $GET_PIP_PATH\n+ } else {\n+ Write-Host \"pip already installed.\"\n+ }\n+}\n+\n+\n+function DownloadMiniconda ($python_version, $platform_suffix) {\n+ if ($python_version -eq \"3.4\") {\n+ $filename = \"Miniconda3-3.5.5-Windows-\" + $platform_suffix + \".exe\"\n+ } else {\n+ $filename = \"Miniconda-3.5.5-Windows-\" + $platform_suffix + \".exe\"\n+ }\n+ $url = $MINICONDA_URL + $filename\n+ $filepath = Download $filename $url\n+ return $filepath\n+}\n+\n+\n+function InstallMiniconda ($python_version, $architecture, $python_home) {\n+ Write-Host \"[NAME_REDACTED]\" $python_version \"for\" $architecture \"bit architecture to\" $python_home\n+ if (Test-Path $python_home) {\n+ Write-Host $python_home \"already exists, skipping.\"\n+ return $false\n+ }\n+ if ($architecture -eq \"32\") {\n+ $platform_suffix = \"x86\"\n+ } else {\n+ $platform_suffix = \"x86_64\"\n+ }\n+ $filepath = DownloadMiniconda $python_version $platform_suffix\n+ Write-Host \"Installing\" $filepath \"to\" $python_home\n+ $install_log = $python_home + \".log\"\n+ $args = \"/S /D=$python_home\"\n+ Write-Host $filepath $args\n+ Start-Process -FilePath $filepath -ArgumentList $args -Wait -Passthru\n+ if (Test-Path $python_home) {\n+ Write-Host \"Python $python_version ($architecture) installation complete\"\n+ } else {\n+ Write-Host \"Failed to install Python in $python_home\"\n+ Get-Content -Path $install_log\n+ Exit 1\n+ }\n+}\n+\n+\n+function InstallMinicondaPip ($python_home) {\n+ $pip_path = $python_home + \"\\Scripts\\pip.exe\"\n+ $conda_path = $python_home + \"\\Scripts\\conda.exe\"\n+ if (-not(Test-Path $pip_path)) {\n+ Write-Host \"Installing pip...\"\n+ $args = \"install --yes pip\"\n+ Write-Host $conda_path $args\n+ Start-Process -FilePath \"$conda_path\" -ArgumentList $args -Wait -Passthru\n+ } else {\n+ Write-Host \"pip already installed.\"\n+ }\n+}\n+\n+function main () {\n+ InstallPython $env:PYTHON_VERSION $env:PYTHON_ARCH $env:PYTHON\n+ InstallPip $env:PYTHON\n+}\n+\n+main\n\\ No newline at end of file" }, { "filename": "appveyor.yml", "status": "added", "additions": 61, "deletions": 0, "changes": 61, "patch": "@@ -0,0 +1,61 @@\n+# AppVeyor.yml from https://github.com/ogrisel/python-appveyor-demo\n+# License: CC0 1.0 Universal: http://creativecommons.org/publicdomain/zero/1.0/\n+\n+build: off\n+\n+environment:\n+ matrix:\n+ - PYTHON: \"C:\\\\Python266-x64\"\n+ PYTHON_VERSION: \"2.6.6\"\n+ PYTHON_ARCH: \"64\"\n+ TOXENV: \"py26\"\n+\n+ - PYTHON: \"C:\\\\Python27-x64\"\n+ PYTHON_VERSION: \"2.7.x\"\n+ PYTHON_ARCH: \"64\"\n+ TOXENV: \"py27\"\n+\n+ - PYTHON: \"C:\\\\Python33-x64\"\n+ PYTHON_VERSION: \"3.3.x\"\n+ PYTHON_ARCH: \"64\"\n+ TOXENV: \"py33\"\n+\n+ - PYTHON: \"C:\\\\Python34-x64\"\n+ PYTHON_VERSION: \"3.4.x\"\n+ PYTHON_ARCH: \"64\"\n+ TOXENV: \"py34\"\n+\n+ - PYTHON: \"C:\\\\Python35-x64\"\n+ PYTHON_VERSION: \"3.5.x\"\n+ PYTHON_ARCH: \"64\"\n+ TOXENV: \"py35\"\n+\n+ - PYTHON: \"C:\\\\Python36-x64\"\n+ PYTHON_VERSION: \"3.6.x\"\n+ PYTHON_ARCH: \"64\"\n+ TOXENV: \"py36\"\n+\n+install:\n+ # [NAME_REDACTED] (from the official .msi of http://python.org) and pip when\n+ # not already installed.\n+ - ps: if (-not(Test-Path($env:PYTHON))) { & _appveyor\\install.ps1 }\n+\n+ # Prepend newly installed Python to the PATH of this build (this cannot be\n+ # done from inside the powershell script as it would require to restart\n+ # the parent CMD process).\n+ - \"SET PATH=%PYTHON%;%PYTHON%\\\\Scripts;%PATH%\"\n+\n+ # Check that we have the expected version and architecture for Python\n+ - \"python --version\"\n+ - \"python -c \\\"import struct; print(struct.calcsize('P') * 8)\\\"\"\n+\n+ # Upgrade to the latest version of pip to avoid it displaying warnings\n+ # about it being out of date.\n+ - \"pip install --disable-pip-version-check --user --upgrade pip\"\n+ - \"mingw32-make\"\n+\n+test_script:\n+ - \"mingw32-make coverage\"\n+\n+on_success:\n+ - \"pipenv run codecov\"" } ], "reviews": [ { "id": 34156613, "user": "user_0fa58b6f3572", "state": "COMMENTED", "body": null, "submitted_at": "2017-04-22T12:42:57+00:00" }, { "id": 34156712, "user": "user_dbf2a999bd6d", "state": "COMMENTED", "body": null, "submitted_at": "2017-04-22T12:45:02+00:00" }, { "id": 34167159, "user": "user_f068c71fd303", "state": "COMMENTED", "body": null, "submitted_at": "2017-04-22T22:15:06+00:00" }, { "id": 34167162, "user": "user_f068c71fd303", "state": "COMMENTED", "body": null, "submitted_at": "2017-04-22T22:15:15+00:00" }, { "id": 34225003, "user": "user_f068c71fd303", "state": "COMMENTED", "body": null, "submitted_at": "2017-04-24T07:23:35+00:00" }, { "id": 34267373, "user": "user_dbf2a999bd6d", "state": "APPROVED", "body": "Looks good to me if [USER_REDACTED] is happy.", "submitted_at": "2017-04-24T11:06:39+00:00" } ], "review_comments": [ { "id": 112808983, "user": "user_0fa58b6f3572", "body": "Didn't we drop support for 2.6?", "path": "appveyor.yml", "line": 8, "side": "RIGHT", "created_at": "2017-04-22T12:42:37+00:00" }, { "id": 112808988, "user": "user_0fa58b6f3572", "body": "Is 3.6 not supported on AppVeyor?", "path": "appveyor.yml", "line": 31, "side": "RIGHT", "created_at": "2017-04-22T12:42:50+00:00" }, { "id": 112809080, "user": "user_dbf2a999bd6d", "body": "Not until 3.0 was the decision I believe.", "path": "appveyor.yml", "line": 8, "side": "RIGHT", "created_at": "2017-04-22T12:45:02+00:00" }, { "id": 112819995, "user": "user_f068c71fd303", "body": "Correct.", "path": "appveyor.yml", "line": 8, "side": "RIGHT", "created_at": "2017-04-22T22:15:05+00:00" }, { "id": 112819999, "user": "user_f068c71fd303", "body": "It should be, this was just an oversight.", "path": "appveyor.yml", "line": 31, "side": "RIGHT", "created_at": "2017-04-22T22:15:15+00:00" }, { "id": 112879004, "user": "user_f068c71fd303", "body": "Ok, added", "path": "appveyor.yml", "line": 31, "side": "RIGHT", "created_at": "2017-04-24T07:23:35+00:00" } ], "meta": { "languages": [ "ps1", "yml" ], "touches_tests": false, "review_state_summary": { "COMMENTED": 5, "APPROVED": 1 }, "meaningful_comment_count": 4, "has_approval": true, "has_changes_requested": false, "total_review_comments": 6 } } { "_id": "3fb669c9f6799c0d", "_schema_version": "1.0", "_cleaned_at": "2026-02-12T07:46:52.070120+00:00", "repo": "psf/requests", "repo_url": "https://github.com/psf/requests", "license_name": "Apache License 2.0", "license_spdx": "Apache-2.0", "pr_number": 3979, "title": "improve proxy bypass on Windows", "body": "See #3976", "author": "user_9b28562a5818", "created_at": "2017-04-20T13:42:43+00:00", "merged_at": "2017-05-04T14:18:30+00:00", "base_branch": "master", "head_branch": "bypass-proxy", "additions": 113, "deletions": 177, "changed_files": 6, "files": [ { "filename": "HISTORY.rst", "status": "modified", "additions": 2, "deletions": 0, "changes": 2, "patch": "@@ -15,6 +15,8 @@ Release History\n resolution on Windows.\n - Added ``win_inet_pton`` as conditional dependency for the ``[socks]`` extra\n on Windows with Python 2.7.\n+- Changed the proxy bypass implementation on Windows: the proxy bypass\n+ check doesn't use forward and reverse DNS requests anymore\n \n 2.13.0 (2017-01-24)\n +++++++++++++++++++" }, { "filename": "requests/compat.py", "status": "modified", "additions": 4, "deletions": 2, "changes": 6, "patch": "@@ -37,7 +37,9 @@\n # ---------\n \n if is_py2:\n- from urllib import quote, unquote, quote_plus, unquote_plus, urlencode, getproxies, proxy_bypass\n+ from urllib import (\n+ quote, unquote, quote_plus, unquote_plus, urlencode, getproxies,\n+ proxy_bypass, proxy_bypass_environment, getproxies_environment)\n from urlparse import urlparse, urlunparse, urljoin, urlsplit, urldefrag\n from urllib2 import parse_http_list\n import cookielib\n@@ -54,7 +56,7 @@\n \n elif is_py3:\n from urllib.parse import urlparse, urlunparse, urljoin, urlsplit, urlencode, quote, unquote, quote_plus, unquote_plus, urldefrag\n- from urllib.request import parse_http_list, getproxies, proxy_bypass\n+ from urllib.request import parse_http_list, getproxies, proxy_bypass, proxy_bypass_environment, getproxies_environment\n from http import cookiejar as cookielib\n from http.cookies import Morsel\n from io import StringIO" }, { "filename": "requests/structures.py", "status": "modified", "additions": 0, "deletions": 89, "changes": 89, "patch": "@@ -8,12 +8,9 @@\n \"\"\"\n \n import collections\n-import time\n \n from .compat import OrderedDict\n \n-current_time = getattr(time, 'monotonic', time.time)\n-\n \n class CaseInsensitiveDict(collections.MutableMapping):\n \"\"\"A case-insensitive ``dict``-like object.\n@@ -106,89 +103,3 @@ def __getitem__(self, key):\n \n def get(self, key, default=None):\n return self.__dict__.get(key, default)\n-\n-\n-class TimedCacheManaged(object):\n- \"\"\"\n- Wrap a function call in a timed cache\n- \"\"\"\n- def __init__(self, fnc):\n- self.fnc = fnc\n- self.cache = TimedCache()\n-\n- def __call__(self, *args, **kwargs):\n- key = args[0]\n- found = None\n- try:\n- found = self.cache[key]\n- except KeyError:\n- found = self.fnc(key, **kwargs)\n- self.cache[key] = found\n-\n- return found\n-\n-\n-class TimedCache(collections.MutableMapping):\n- \"\"\"\n- Evicts entries after expiration_secs. If none are expired and maxlen is hit,\n- will evict the oldest cached entry\n- \"\"\"\n- def __init__(self, maxlen=32, expiration_secs=60):\n- \"\"\"\n- :param maxlen: most number of entries to hold on to\n- :param expiration_secs: the number of seconds to hold on\n- to entries\n- \"\"\"\n- self.maxlen = maxlen\n- self.expiration_secs = expiration_secs\n- self._dict = OrderedDict()\n-\n- def __repr__(self):\n- return '' % \\\n- (self.maxlen, len(self._dict), self.expiration_secs)\n-\n- def __iter__(self):\n- return ((key, value[1]) for key, value in self._dict.items())\n-\n- def __delitem__(self, item):\n- del self._dict[item]\n-\n- def __getitem__(self, key):\n- \"\"\"\n- Look up an item in the cache. If the item\n- has already expired, it will be invalidated and not returned\n-\n- :param key: which entry to look up\n- :return: the value in the cache, or None\n- \"\"\"\n- occurred, value = self._dict[key]\n- now = int(current_time())\n-\n- if now - occurred > self.expiration_secs:\n- del self._dict[key]\n- raise KeyError(key)\n- else:\n- return value\n-\n- def __setitem__(self, key, value):\n- \"\"\"\n- Locates the value at lookup key, if cache is full, will evict the\n- oldest entry\n-\n- :param key: the key to search the cache for\n- :param value: the value to be added to the cache\n- \"\"\"\n- now = int(current_time())\n-\n- while len(self._dict) >= self.maxlen:\n- self._dict.popitem(last=False)\n-\n- self._dict[key] = (now, value)\n-\n- def __len__(self):\n- \"\"\":return: the length of the cache\"\"\"\n- return len(self._dict)\n-\n- def clear(self):\n- \"\"\"Clears the cache\"\"\"\n- return self._dict.clear()" }, { "filename": "requests/utils.py", "status": "modified", "additions": 53, "deletions": 13, "changes": 66, "patch": "@@ -14,6 +14,7 @@\n import contextlib\n import io\n import os\n+import platform\n import re\n import socket\n import struct\n@@ -26,9 +27,10 @@\n from .compat import parse_http_list as _parse_list_header\n from .compat import (\n quote, urlparse, bytes, str, OrderedDict, unquote, getproxies,\n- proxy_bypass, urlunparse, basestring, integer_types)\n+ proxy_bypass, urlunparse, basestring, integer_types, is_py3,\n+ proxy_bypass_environment, getproxies_environment)\n from .cookies import cookiejar_from_dict\n-from .structures import CaseInsensitiveDict, TimedCacheManaged\n+from .structures import CaseInsensitiveDict\n from .exceptions import (\n InvalidURL, InvalidHeader, FileModeWarning, UnrewindableBodyError)\n \n@@ -37,6 +39,54 @@\n DEFAULT_CA_BUNDLE_PATH = certs.where()\n \n \n+if platform.system() == 'Windows':\n+ # provide a proxy_bypass version on Windows without DNS lookups\n+\n+ def proxy_bypass_registry(host):\n+ if is_py3:\n+ import winreg\n+ else:\n+ import _winreg as winreg\n+ try:\n+ internetSettings = winreg.OpenKey(winreg.HKEY_CURRENT_USER,\n+ r'Software\\Microsoft\\Windows\\CurrentVersion\\[NAME_REDACTED]')\n+ proxyEnable = winreg.QueryValueEx(internetSettings,\n+ 'ProxyEnable')[0]\n+ proxyOverride = winreg.QueryValueEx(internetSettings,\n+ 'ProxyOverride')[0]\n+ except OSError:\n+ return False\n+ if not proxyEnable or not proxyOverride:\n+ return False\n+\n+ # make a check value list from the registry entry: replace the\n+ # '' string by [NAME_REDACTED] the corresponding\n+ # canonical entry.\n+ proxyOverride = proxyOverride.split(';')\n+ # now check if we match one of the registry values.\n+ for test in proxyOverride:\n+ if test == '':\n+ if '.' not in host:\n+ return True\n+ test = test.replace(\".\", r\"\\.\") # mask dots\n+ test = test.replace(\"*\", r\".*\") # change glob sequence\n+ test = test.replace(\"?\", r\".\") # change glob char\n+ if re.match(test, host, re.I):\n+ return True\n+ return False\n+\n+ def proxy_bypass(host): # noqa\n+ \"\"\"[NAME_REDACTED], if the host should be bypassed.\n+\n+ Checks proxy settings gathered from the environment, if specified,\n+ or the registry.\n+ \"\"\"\n+ if getproxies_environment():\n+ return proxy_bypass_environment(host)\n+ else:\n+ return proxy_bypass_registry(host)\n+\n+\n def dict_to_sequence(d):\n \"\"\"Returns an internal sequence dictionary update.\"\"\"\n \n@@ -577,16 +627,6 @@ def set_environ(env_name, value):\n os.environ[env_name] = old_value\n \n \n-[USER_REDACTED]\n-def _proxy_bypass_cached(netloc):\n- \"\"\"\n- Looks for netloc in the cache, if not found, will call proxy_bypass\n- for the netloc and store its result in the cache\n-\n- :rtype: bool\n- \"\"\"\n- return proxy_bypass(netloc)\n-\n def should_bypass_proxies(url, no_proxy):\n \"\"\"\n Returns whether we should bypass proxies or not.\n@@ -634,7 +674,7 @@ def should_bypass_proxies(url, no_proxy):\n # legitimate problems.\n with set_environ('no_proxy', no_proxy_arg):\n try:\n- bypass = _proxy_bypass_cached(netloc)\n+ bypass = proxy_bypass(netloc)\n except (TypeError, socket.gaierror):\n bypass = False" }, { "filename": "tests/test_structures.py", "status": "modified", "additions": 1, "deletions": 73, "changes": 74, "patch": "@@ -2,7 +2,7 @@\n \n import pytest\n \n-from requests.structures import CaseInsensitiveDict, LookupDict, TimedCache, TimedCacheManaged\n+from requests.structures import CaseInsensitiveDict, LookupDict\n \n \n class TestCaseInsensitiveDict:\n@@ -74,75 +74,3 @@ def test_getitem(self, key, value):\n [USER_REDACTED]_item_parameters\n def test_get(self, key, value):\n assert self.lookup_dict.get(key) == value\n-\n-\n-class TestTimedCache(object):\n- [USER_REDACTED].fixture(autouse=True)\n- def setup(self):\n- self.any_value = 'some value'\n- self.expiration_secs = 60\n- self.cache = TimedCache(expiration_secs=self.expiration_secs)\n- yield\n- self.cache.clear()\n-\n- def test_get(self):\n- self.cache['a'] = self.any_value\n- assert self.cache['a'] is self.any_value\n-\n- def test_repr(self):\n- repr = str(self.cache)\n- assert repr == ''\n-\n- def test_get_expired_item(self, mocker):\n- self.cache = TimedCache(maxlen=1, expiration_secs=self.expiration_secs)\n-\n- mocker.patch('requests.structures.current_time', lambda: 0)\n- self.cache['a'] = self.any_value\n- mocker.patch('requests.structures.current_time', lambda: self.expiration_secs + 1)\n- assert self.cache.get('a') is None\n-\n- def test_evict_first_entry_when_full(self, mocker):\n- self.cache = TimedCache(maxlen=2, expiration_secs=2)\n- mocker.patch('requests.structures.current_time', lambda: 0)\n- self.cache['a'] = self.any_value\n- mocker.patch('requests.structures.current_time', lambda: 1)\n- self.cache['b'] = self.any_value\n- mocker.patch('requests.structures.current_time', lambda: 3)\n- self.cache['c'] = self.any_value\n- assert len(self.cache) is 2\n- with pytest.raises(KeyError, message='Expected key not found'):\n- self.cache['a']\n- assert self.cache['b'] is self.any_value\n- assert self.cache['c'] is self.any_value\n-\n- def test_delete_item_removes_item(self):\n- self.cache['a'] = self.any_value\n- del self.cache['a']\n- with pytest.raises(KeyError, message='Expected key not found'):\n- self.cache['a']\n-\n- def test_iterating_hides_timestamps(self):\n- self.cache['a'] = 1\n- self.cache['b'] = 2\n- expected = [('a', 1), ('b', 2)]\n- actual = [(key, val) for key, val in self.cache]\n- assert expected == actual\n-\n-\n-class TestTimedCacheManagedDecorator(object):\n- def test_caches_repeated_calls(self, mocker):\n- mocker.patch('requests.structures.current_time', lambda: 0)\n-\n- nonlocals = {'value': 0}\n-\n- [USER_REDACTED]\n- def some_method(x):\n- nonlocals['value'] = nonlocals['value'] + x\n- return nonlocals['value']\n-\n- first_result = some_method(1)\n- assert first_result is 1\n- second_result = some_method(1)\n- assert second_result is 1\n- third_result = some_method(2)\n- assert third_result is 3" }, { "filename": "tests/test_utils.py", "status": "modified", "additions": 53, "deletions": 0, "changes": 53, "patch": "@@ -1,5 +1,6 @@\n # -*- coding: utf-8 -*-\n \n+import os\n from io import BytesIO\n \n import pytest\n@@ -599,3 +600,55 @@ def test_should_bypass_proxies_no_proxy(\n no_proxy = '192.168.0.0/24,127.0.0.1,localhost.localdomain,172.16.1.1'\n # Test 'no_proxy' argument\n assert should_bypass_proxies(url, no_proxy=no_proxy) == expected\n+\n+\n+[USER_REDACTED].mark.skipif(os.name != 'nt', reason='Test only on Windows')\n+[USER_REDACTED].mark.parametrize(\n+ 'url, expected, override', (\n+ ('http://192.168.0.1:5000/', True, None),\n+ ('http://192.168.0.1/', True, None),\n+ ('http://172.16.1.1/', True, None),\n+ ('http://172.16.1.1:5000/', True, None),\n+ ('http://localhost.localdomain:5000/v1.0/', True, None),\n+ ('http://172.16.1.22/', False, None),\n+ ('http://172.16.1.22:5000/', False, None),\n+ ('http://google.com:5000/v1.0/', False, None),\n+ ('http://mylocalhostname:5000/v1.0/', True, ''),\n+ ('http://192.168.0.1/', False, ''),\n+ ))\n+def test_should_bypass_proxies_win_registry(url, expected, override,\n+ monkeypatch):\n+ \"\"\"Tests for function should_bypass_proxies to check if proxy\n+ can be bypassed or not with Windows registry settings\n+ \"\"\"\n+ if override is None:\n+ override = '192.168.*;127.0.0.1;localhost.localdomain;172.16.1.1'\n+ if compat.is_py3:\n+ import winreg\n+ else:\n+ import _winreg as winreg\n+\n+ class RegHandle:\n+ def Close(self):\n+ pass\n+\n+ ie_settings = RegHandle()\n+\n+ def OpenKey(key, subkey):\n+ return ie_settings\n+\n+ def QueryValueEx(key, value_name):\n+ if key is ie_settings:\n+ if value_name == 'ProxyEnable':\n+ return [1]\n+ elif value_name == 'ProxyOverride':\n+ return [override]\n+\n+ monkeypatch.setenv('http_proxy', '')\n+ monkeypatch.setenv('https_proxy', '')\n+ monkeypatch.setenv('ftp_proxy', '')\n+ monkeypatch.setenv('no_proxy', '')\n+ monkeypatch.setenv('NO_PROXY', '')\n+ monkeypatch.setattr(winreg, 'OpenKey', OpenKey)\n+ monkeypatch.setattr(winreg, 'QueryValueEx', QueryValueEx)\n+ assert should_bypass_proxies(url, no_proxy=None) == expected" } ], "reviews": [ { "id": 33793505, "user": "user_f068c71fd303", "state": "CHANGES_REQUESTED", "body": "Hrm, we may need to enable appveyor to ensure that this stuff actually works.", "submitted_at": "2017-04-20T15:07:18+00:00" }, { "id": 35972474, "user": "user_9b28562a5818", "state": "COMMENTED", "body": null, "submitted_at": "2017-05-03T09:24:34+00:00" }, { "id": 36100575, "user": "user_dbf2a999bd6d", "state": "CHANGES_REQUESTED", "body": "This looks like a good start [USER_REDACTED]! I left a couple notes with some outstanding questions from my end. A couple are just stylistic nits but the others are on functionality.", "submitted_at": "2017-05-03T18:40:38+00:00" }, { "id": 36134642, "user": "user_9b28562a5818", "state": "COMMENTED", "body": null, "submitted_at": "2017-05-03T20:49:11+00:00" }, { "id": 36136809, "user": "user_9b28562a5818", "state": "COMMENTED", "body": null, "submitted_at": "2017-05-03T20:57:39+00:00" }, { "id": 36198465, "user": "user_f068c71fd303", "state": "CHANGES_REQUESTED", "body": "Cool, so this is looking really good! I'd love to see if we can get the test coverage up a bit higher, and I've left a note in the diff. :smile:", "submitted_at": "2017-05-04T07:18:00+00:00" }, { "id": 36207496, "user": "user_9b28562a5818", "state": "COMMENTED", "body": null, "submitted_at": "2017-05-04T08:13:27+00:00" }, { "id": 36210858, "user": "user_f068c71fd303", "state": "COMMENTED", "body": null, "submitted_at": "2017-05-04T08:31:24+00:00" }, { "id": 36260140, "user": "user_f068c71fd303", "state": "APPROVED", "body": "Ok, I think I'm happy. Time to see what [USER_REDACTED] thinks.", "submitted_at": "2017-05-04T13:00:03+00:00" }, { "id": 36261877, "user": "user_dbf2a999bd6d", "state": "APPROVED", "body": "Looks good to me!", "submitted_at": "2017-05-04T13:07:31+00:00" }, { "id": 36262604, "user": "user_f068c71fd303", "state": "CHANGES_REQUESTED", "body": "Ok then, one last request. Can you add notes to the changelog to note that a) we've changed our strategy for looking up proxy bypass information on Windows, and b) we've removed the proxy bypass cache as it's no longer needed? Just want to make sure we have a good reference in case these things have unforseen bugs, and I bet I'll forget that there were two things in this PR when it comes to writing the changelog later. :grin:", "submitted_at": "2017-05-04T13:10:51+00:00" }, { "id": 36268959, "user": "user_f068c71fd303", "state": "APPROVED", "body": "Alright, let's do it!", "submitted_at": "2017-05-04T13:35:43+00:00" } ], "review_comments": [ { "id": 112475315, "user": "user_f068c71fd303", "body": "This comment is confusing: what is it trying to say?", "path": "requests/utils.py", "line": null, "side": "RIGHT", "created_at": "2017-04-20T14:57:03+00:00" }, { "id": 112475519, "user": "user_f068c71fd303", "body": "We may as well just use booleans.", "path": "requests/utils.py", "line": null, "side": "RIGHT", "created_at": "2017-04-20T14:57:48+00:00" }, { "id": 112476041, "user": "user_f068c71fd303", "body": "What is this for?", "path": "requests/utils.py", "line": null, "side": "RIGHT", "created_at": "2017-04-20T14:59:32+00:00" }, { "id": 112476460, "user": "user_f068c71fd303", "body": "We can probably unify these two lines.", "path": "requests/utils.py", "line": 67, "side": "RIGHT", "created_at": "2017-04-20T15:00:55+00:00" }, { "id": 112477868, "user": "user_f068c71fd303", "body": "May as well just import this directly from compat.", "path": "tests/test_utils.py", "line": null, "side": "RIGHT", "created_at": "2017-04-20T15:06:11+00:00" }, { "id": 114502837, "user": "user_9b28562a5818", "body": "Then we would need a platform check in compat and winreg could be `None` on non Windows platforms...", "path": "tests/test_utils.py", "line": null, "side": "RIGHT", "created_at": "2017-05-03T09:24:34+00:00" }, { "id": 114618715, "user": "user_dbf2a999bd6d", "body": "Is there a reason this is `1` and not `True` like the other return values? If so, we should probably add a comment explaining why.", "path": "requests/utils.py", "line": null, "side": "RIGHT", "created_at": "2017-05-03T18:26:20+00:00" }, { "id": 114619528, "user": "user_dbf2a999bd6d", "body": "It may be better to follow something closer to the import convention of the other modules, rather than use `\\`.\n```python\nfrom urllib import (\n quote, unquote, quote_plus, unquote_plus, urlencode, getproxies,\n proxy_bypass, proxy_bypass_environment, getproxies_environment)\n```", "path": "requests/compat.py", "line": null, "side": "RIGHT", "created_at": "2017-05-03T18:29:56+00:00" }, { "id": 114620765, "user": "user_dbf2a999bd6d", "body": "Could we remove this extra line here.", "path": "requests/utils.py", "line": null, "side": "RIGHT", "created_at": "2017-05-03T18:35:26+00:00" }, { "id": 114621390, "user": "user_dbf2a999bd6d", "body": "This seems to return a boolean but the docstring states it returns a dictionary of scheme to proxy mappings. It may be a good idea to clarify this case.", "path": "requests/utils.py", "line": 87, "side": "RIGHT", "created_at": "2017-05-03T18:38:06+00:00" }, { "id": 114649810, "user": "user_9b28562a5818", "body": "Nope, I forgot this one 🙈", "path": "requests/utils.py", "line": null, "side": "RIGHT", "created_at": "2017-05-03T20:49:11+00:00" }, { "id": 114651759, "user": "user_9b28562a5818", "body": "Somehow I copied the wrong docstring, I'll fix this :)", "path": "requests/utils.py", "line": 87, "side": "RIGHT", "created_at": "2017-05-03T20:57:39+00:00" }, { "id": 114711039, "user": "user_f068c71fd303", "body": "Rather than use `os.name`, might it be better to use `platform.system`?", "path": "requests/utils.py", "line": null, "side": "RIGHT", "created_at": "2017-05-04T07:15:27+00:00" }, { "id": 114719068, "user": "user_9b28562a5818", "body": "[USER_REDACTED] Should I remove this one, I don't think this is really necessary...", "path": "requests/utils.py", "line": null, "side": "RIGHT", "created_at": "2017-05-04T08:13:27+00:00" }, { "id": 114722329, "user": "user_f068c71fd303", "body": "Yeah, let's do that: there's no need to tolerate this `ImportError` I don't think.", "path": "requests/utils.py", "line": null, "side": "RIGHT", "created_at": "2017-05-04T08:31:24+00:00" } ], "meta": { "languages": [ "py", "rst" ], "touches_tests": true, "review_state_summary": { "CHANGES_REQUESTED": 4, "COMMENTED": 5, "APPROVED": 3 }, "meaningful_comment_count": 15, "has_approval": true, "has_changes_requested": true, "total_review_comments": 15 } } { "_id": "d1ea72e929714c1f", "_schema_version": "1.0", "_cleaned_at": "2026-02-12T07:46:52.085742+00:00", "repo": "psf/requests", "repo_url": "https://github.com/psf/requests", "license_name": "Apache License 2.0", "license_spdx": "Apache-2.0", "pr_number": 3969, "title": "fix handle of non-ascii location on redirects issue #3888", "body": "fix for #3888", "author": "user_58bf12d651f4", "created_at": "2017-04-17T18:34:45+00:00", "merged_at": "2017-04-18T16:20:23+00:00", "base_branch": "master", "head_branch": "master", "additions": 14, "deletions": 11, "changed_files": 2, "files": [ { "filename": "requests/sessions.py", "status": "modified", "additions": 11, "deletions": 2, "changes": 13, "patch": "@@ -12,7 +12,7 @@\n from datetime import datetime\n \n from .auth import _basic_auth_str\n-from .compat import cookielib, OrderedDict, urljoin, urlparse\n+from .compat import cookielib, is_py3, OrderedDict, urljoin, urlparse\n from .cookies import (\n cookiejar_from_dict, extract_cookies_to_jar, RequestsCookieJar, merge_cookies)\n from .models import Request, PreparedRequest, DEFAULT_REDIRECT_LIMIT\n@@ -90,7 +90,16 @@ class SessionRedirectMixin(object):\n def get_redirect_target(self, resp):\n \"\"\"Receives a Response. Returns a redirect URI or ``None``\"\"\"\n if resp.is_redirect:\n- return resp.headers['location']\n+ location = resp.headers['location']\n+ # Currently the underlying http module on py3 decode headers\n+ # in latin1, but empirical evidence suggests that latin1 is very\n+ # rarely used with non-ASCII characters in HTTP headers.\n+ # It is more likely to get UTF8 header rather than latin1.\n+ # This causes incorrect handling of UTF8 encoded location headers.\n+ # To solve this, we re-encode the location in latin1.\n+ if is_py3:\n+ location = location.encode('latin1')\n+ return to_native_string(location, 'utf8')\n return None\n \n def resolve_redirects(self, resp, req, stream=False, timeout=None," }, { "filename": "tests/test_lowlevel.py", "status": "modified", "additions": 3, "deletions": 9, "changes": 12, "patch": "@@ -3,7 +3,6 @@\n import pytest\n import threading\n import requests\n-from requests.compat import quote, is_py3\n \n from tests.testserver.server import Server, consume_socket_content\n \n@@ -208,8 +207,7 @@ def test_use_proxy_from_environment(httpbin, var, scheme):\n \n def test_redirect_rfc1808_to_non_ascii_location():\n path = u'š'\n- expected_path = quote(path.encode('utf8')).encode('ascii')\n- expected_path_py3 = b'%C3%85%C2%A1'\n+ expected_path = b'%C5%A1'\n redirect_request = [] # stores the second request to the server\n \n def redirect_resp_handler(sock):\n@@ -233,11 +231,7 @@ def redirect_resp_handler(sock):\n assert r.status_code == 200\n assert len(r.history) == 1\n assert r.history[0].status_code == 301\n-\n- # currently Python3 not handling non-ASCII redirects (issue #3888)\n- if is_py3:\n- assert redirect_request[0].startswith(b'GET /' + expected_path_py3 + b' HTTP/1.1')\n- else:\n- assert redirect_request[0].startswith(b'GET /' + expected_path + b' HTTP/1.1')\n+ assert redirect_request[0].startswith(b'GET /' + expected_path + b' HTTP/1.1')\n+ assert r.url == u'{0}/{1}'.format(url, expected_path.decode('ascii'))\n \n close_server.set()" } ], "reviews": [ { "id": 33073600, "user": "user_f068c71fd303", "state": "CHANGES_REQUESTED", "body": "Cool, so in general I'm happy with this. I have some notes about the code comments, and I'd also like [USER_REDACTED] and [USER_REDACTED] to weigh in if they can.", "submitted_at": "2017-04-17T19:50:14+00:00" }, { "id": 33085589, "user": "user_58bf12d651f4", "state": "COMMENTED", "body": null, "submitted_at": "2017-04-17T20:41:48+00:00" }, { "id": 33085716, "user": "user_58bf12d651f4", "state": "COMMENTED", "body": null, "submitted_at": "2017-04-17T20:42:21+00:00" }, { "id": 33084936, "user": "user_dbf2a999bd6d", "state": "CHANGES_REQUESTED", "body": "For the most part this looks good to me 😊 I left a couple comments on the test but otherwise, I think things are good. Thanks for putting this together [USER_REDACTED]!", "submitted_at": "2017-04-17T20:44:03+00:00" }, { "id": 33091956, "user": "user_58bf12d651f4", "state": "COMMENTED", "body": null, "submitted_at": "2017-04-17T21:11:01+00:00" }, { "id": 33092069, "user": "user_58bf12d651f4", "state": "COMMENTED", "body": null, "submitted_at": "2017-04-17T21:11:35+00:00" }, { "id": 33092143, "user": "user_58bf12d651f4", "state": "COMMENTED", "body": null, "submitted_at": "2017-04-17T21:11:58+00:00" }, { "id": 33102540, "user": "user_f068c71fd303", "state": "APPROVED", "body": "Cool, so I'm happy!", "submitted_at": "2017-04-17T22:08:20+00:00" }, { "id": 33118339, "user": "user_dbf2a999bd6d", "state": "APPROVED", "body": null, "submitted_at": "2017-04-18T00:05:18+00:00" }, { "id": 33276693, "user": "user_0fa58b6f3572", "state": "APPROVED", "body": null, "submitted_at": "2017-04-18T16:06:05+00:00" } ], "review_comments": [ { "id": 111806074, "user": "user_f068c71fd303", "body": "s/underling/underlying/", "path": "requests/sessions.py", "line": null, "side": "RIGHT", "created_at": "2017-04-17T19:46:59+00:00" }, { "id": 111806519, "user": "user_f068c71fd303", "body": "So I think this comment needs to have a bit more elaboration. Specifically, we need to talk about why we think we're more likely to get UTF-8 encoded location headers than Latin-1: specifically, because empirical evidence suggests that latin-1 is very rarely used with non-ASCII characters in HTTP headers.", "path": "requests/sessions.py", "line": null, "side": "RIGHT", "created_at": "2017-04-17T19:49:12+00:00" }, { "id": 111816350, "user": "user_dbf2a999bd6d", "body": "It seems like it might be more resilient/explicit to hard code the expected path here? It would divest us from relying on `quote` in the test, saves us an import, and hopefully clear up this line a bit.\n\nAt the very least, a comment on what we're doing here seems good.", "path": "tests/test_lowlevel.py", "line": null, "side": "RIGHT", "created_at": "2017-04-17T20:38:41+00:00" }, { "id": 111816618, "user": "user_dbf2a999bd6d", "body": "We're kind of testing the test here. Perhaps also adding a check that `r.url` is what we expect would be helpful?", "path": "tests/test_lowlevel.py", "line": 234, "side": "RIGHT", "created_at": "2017-04-17T20:40:07+00:00" }, { "id": 111816839, "user": "user_dbf2a999bd6d", "body": "I agree with [USER_REDACTED]. Also this is a minor nit, but capitals and periods would be great here 😊", "path": "requests/sessions.py", "line": null, "side": "RIGHT", "created_at": "2017-04-17T20:41:14+00:00" }, { "id": 111816957, "user": "user_58bf12d651f4", "body": "added more info about the issue.", "path": "requests/sessions.py", "line": null, "side": "RIGHT", "created_at": "2017-04-17T20:41:48+00:00" }, { "id": 111817072, "user": "user_58bf12d651f4", "body": "yes :)", "path": "requests/sessions.py", "line": null, "side": "RIGHT", "created_at": "2017-04-17T20:42:21+00:00" }, { "id": 111822803, "user": "user_58bf12d651f4", "body": "added capitals and periods [USER_REDACTED], im not native english so feel free to help me rephrase it.", "path": "requests/sessions.py", "line": null, "side": "RIGHT", "created_at": "2017-04-17T21:11:01+00:00" }, { "id": 111822903, "user": "user_58bf12d651f4", "body": "agree changed", "path": "tests/test_lowlevel.py", "line": null, "side": "RIGHT", "created_at": "2017-04-17T21:11:35+00:00" }, { "id": 111822968, "user": "user_58bf12d651f4", "body": "agree, added assert for url", "path": "tests/test_lowlevel.py", "line": 234, "side": "RIGHT", "created_at": "2017-04-17T21:11:58+00:00" } ], "meta": { "languages": [ "py" ], "touches_tests": true, "review_state_summary": { "CHANGES_REQUESTED": 2, "COMMENTED": 5, "APPROVED": 3 }, "meaningful_comment_count": 9, "has_approval": true, "has_changes_requested": true, "total_review_comments": 10 } } { "_id": "9afef1d3279e9883", "_schema_version": "1.0", "_cleaned_at": "2026-02-12T07:46:52.085742+00:00", "repo": "psf/requests", "repo_url": "https://github.com/psf/requests", "license_name": "Apache License 2.0", "license_spdx": "Apache-2.0", "pr_number": 3963, "title": "fix unicode decode error on py2 when handling redirect without scheme", "body": "as discussed on #3959 , fix the UnicodeDecodeError happening because implicit decoding of str string into unicode while using python2.\n\nThis issue happens when handling redirection without scheme (i.e. Location: //URL) on python2 and only if the location is unicode.\n\nFirst time applying a PR on GitHub so let me know if there is something I can do to make it better :).\n\nThanks,\nShmulik", "author": "user_58bf12d651f4", "created_at": "2017-04-12T16:49:28+00:00", "merged_at": "2017-04-14T20:13:50+00:00", "base_branch": "master", "head_branch": "master", "additions": 40, "deletions": 3, "changed_files": 3, "files": [ { "filename": "AUTHORS.rst", "status": "modified", "additions": 1, "deletions": 1, "changes": 2, "patch": "@@ -179,4 +179,4 @@ Patches and Suggestions\n - [NAME_REDACTED] ([CONTRIBUTOR_REDACTED])\n - [NAME_REDACTED] ([CONTRIBUTOR_REDACTED])\n - [NAME_REDACTED] ([CONTRIBUTOR_REDACTED])\n-\n+- [NAME_REDACTED] ([CONTRIBUTOR_REDACTED])" }, { "filename": "requests/sessions.py", "status": "modified", "additions": 1, "deletions": 1, "changes": 2, "patch": "@@ -122,7 +122,7 @@ def resolve_redirects(self, resp, req, stream=False, timeout=None,\n # Handle redirection without scheme (see: RFC 1808 Section 4)\n if url.startswith('//'):\n parsed_rurl = urlparse(resp.url)\n- url = '%s:%s' % (parsed_rurl.scheme, url)\n+ url = '%s:%s' % (to_native_string(parsed_rurl.scheme), url)\n \n # The scheme should be lower case...\n parsed = urlparse(url)" }, { "filename": "tests/test_lowlevel.py", "status": "modified", "additions": 38, "deletions": 1, "changes": 39, "patch": "@@ -1,9 +1,9 @@\n # -*- coding: utf-8 -*-\n \n-import os\n import pytest\n import threading\n import requests\n+from requests.compat import quote, is_py3\n \n from tests.testserver.server import Server, consume_socket_content\n \n@@ -204,3 +204,40 @@ def test_use_proxy_from_environment(httpbin, var, scheme):\n \n # it had actual content (not checking for SOCKS protocol for now)\n assert len(fake_proxy.handler_results[0]) > 0\n+\n+\n+def test_redirect_rfc1808_to_non_ascii_location():\n+ path = u'š'\n+ expected_path = quote(path.encode('utf8')).encode('ascii')\n+ expected_path_py3 = b'%C3%85%C2%A1'\n+ redirect_request = [] # stores the second request to the server\n+\n+ def redirect_resp_handler(sock):\n+ consume_socket_content(sock, timeout=0.5)\n+ location = u'//{0}:{1}/{2}'.format(host, port, path)\n+ sock.send(\n+ b'HTTP/1.1 301 Moved Permanently\\r\\n'\n+ b'Content-Length: 0\\r\\n'\n+ b'Location: ' + location.encode('utf8') + b'\\r\\n'\n+ b'\\r\\n'\n+ )\n+ redirect_request.append(consume_socket_content(sock, timeout=0.5))\n+ sock.send(b'HTTP/1.1 200 OK\\r\\n\\r\\n')\n+\n+ close_server = threading.Event()\n+ server = Server(redirect_resp_handler, wait_to_close_event=close_server)\n+\n+ with server as (host, port):\n+ url = u'http://{0}:{1}'.format(host, port)\n+ r = requests.get(url=url, allow_redirects=True)\n+ assert r.status_code == 200\n+ assert len(r.history) == 1\n+ assert r.history[0].status_code == 301\n+\n+ # currently Python3 not handling non-ASCII redirects (issue #3888)\n+ if is_py3:\n+ assert redirect_request[0].startswith(b'GET /' + expected_path_py3 + b' HTTP/1.1')\n+ else:\n+ assert redirect_request[0].startswith(b'GET /' + expected_path + b' HTTP/1.1')\n+\n+ close_server.set()" } ], "reviews": [ { "id": 32432542, "user": "user_dbf2a999bd6d", "state": "CHANGES_REQUESTED", "body": "Hey [USER_REDACTED], thanks so much for opening your first PR with Requests! I've left a couple notes inline on things that'll need to be fixed, but this is a really good start. Let us know if you have any questions.", "submitted_at": "2017-04-12T17:29:31+00:00" }, { "id": 32460419, "user": "user_f068c71fd303", "state": "CHANGES_REQUESTED", "body": "Agreed, this is a good start! Just a few extra notes on top of [USER_REDACTED]'s review.", "submitted_at": "2017-04-12T18:43:47+00:00" }, { "id": 32486646, "user": "user_58bf12d651f4", "state": "COMMENTED", "body": null, "submitted_at": "2017-04-12T20:35:04+00:00" }, { "id": 32693565, "user": "user_dbf2a999bd6d", "state": "COMMENTED", "body": null, "submitted_at": "2017-04-13T17:38:49+00:00" }, { "id": 32693615, "user": "user_dbf2a999bd6d", "state": "APPROVED", "body": null, "submitted_at": "2017-04-13T17:38:58+00:00" }, { "id": 32769882, "user": "user_f068c71fd303", "state": "COMMENTED", "body": null, "submitted_at": "2017-04-14T01:16:33+00:00" }, { "id": 32802247, "user": "user_58bf12d651f4", "state": "COMMENTED", "body": null, "submitted_at": "2017-04-14T08:46:05+00:00" }, { "id": 32813494, "user": "user_f068c71fd303", "state": "COMMENTED", "body": null, "submitted_at": "2017-04-14T10:30:05+00:00" }, { "id": 32820624, "user": "user_58bf12d651f4", "state": "COMMENTED", "body": null, "submitted_at": "2017-04-14T12:02:28+00:00" }, { "id": 32820770, "user": "user_f068c71fd303", "state": "COMMENTED", "body": null, "submitted_at": "2017-04-14T12:04:16+00:00" }, { "id": 32828299, "user": "user_58bf12d651f4", "state": "COMMENTED", "body": null, "submitted_at": "2017-04-14T13:21:17+00:00" }, { "id": 32890328, "user": "user_f068c71fd303", "state": "APPROVED", "body": "Ok cool, I think I'm happy. Thanks for working with us through the code review. This is a nice improvement!", "submitted_at": "2017-04-14T20:13:45+00:00" } ], "review_comments": [ { "id": 111203525, "user": "user_dbf2a999bd6d", "body": "[USER_REDACTED] could we confirm that the redirected URL is what we expect here?", "path": "tests/test_lowlevel.py", "line": null, "side": "RIGHT", "created_at": "2017-04-12T16:51:05+00:00" }, { "id": 111211579, "user": "user_dbf2a999bd6d", "body": "Unfortunately, neither `%` or `format` work on byte strings in Python 3 prior to 3.5. This means this string will need to be constructed another way. Either using `join` on multiple byte strings, or the `+` operator will probably be the best way to approach this for all Python versions.", "path": "tests/test_lowlevel.py", "line": null, "side": "RIGHT", "created_at": "2017-04-12T17:27:01+00:00" }, { "id": 111229169, "user": "user_f068c71fd303", "body": "Any reason this shouldn't be a get?", "path": "tests/test_lowlevel.py", "line": null, "side": "RIGHT", "created_at": "2017-04-12T18:42:08+00:00" }, { "id": 111253525, "user": "user_58bf12d651f4", "body": "Hey [USER_REDACTED] thanks for the quick review!\n\nI would be glad to make it happen but the issue is that current decoding into native string of headers makes Location header on python2 encoded string and on python3 decoded string. so this test won't be consistent across python version.\n\nbefore this PR we get for the same test the following redirected URL:\npython3: http://localhost:58792/?%C3%85%C2%A0\npython2: UnicodeDecodeError (due to implicit decoding into unicode on string formatting)\n\nthis PR only fixes the python2 UnicodeDecodeError (python3 behaves the same).\n\nthere is an encoding issue #3888 which leads to inconsistency between python versions as each python version handles different type of strings.\n\nI agree that this PR is far from solving #3888 (which I'll be happy to discuss about possible solutions).\n\nMy ideas are (just note a few, regardless of order):\n\n1. keep this PR as is\n2. add xfail for this test\n3. test only `the resolve_redirects()` function\n4. discuss possible for solution for #3888 that I might implement in the same PR\n5. leave all as is and ignore this PR\n\nof course I am open to any suggestions :smile:", "path": "tests/test_lowlevel.py", "line": null, "side": "RIGHT", "created_at": "2017-04-12T20:35:04+00:00" }, { "id": 111445306, "user": "user_dbf2a999bd6d", "body": "Thanks for the suggestions, [USER_REDACTED]! It's a bit unfortunate that we're further exposing the inconsistent functionality between versions by [NAME_REDACTED], this fixes the problem it's intended to address so I guess we can pass on this check until #3888 is fixed.", "path": "tests/test_lowlevel.py", "line": null, "side": "RIGHT", "created_at": "2017-04-13T17:38:49+00:00" }, { "id": 111515999, "user": "user_f068c71fd303", "body": "I'd be ok adding a check on Python version to let us make the correct assertion.", "path": "tests/test_lowlevel.py", "line": null, "side": "RIGHT", "created_at": "2017-04-14T01:16:33+00:00" }, { "id": 111548106, "user": "user_58bf12d651f4", "body": "add the assertion for url.\nplease let me know if there is a better way or more common way to ignore this assertion for python3.\n\nplease let me know if any other changes needed :smile:", "path": "tests/test_lowlevel.py", "line": null, "side": "RIGHT", "created_at": "2017-04-14T08:46:05+00:00" }, { "id": 111558793, "user": "user_f068c71fd303", "body": "Right now we should probably assert what Python 3 *does* do, even if it's wrong, and just put a note on that assertion to fix it up when we change #3888.", "path": "tests/test_lowlevel.py", "line": null, "side": "RIGHT", "created_at": "2017-04-14T10:30:05+00:00" }, { "id": 111565612, "user": "user_58bf12d651f4", "body": "agree, changed it", "path": "tests/test_lowlevel.py", "line": null, "side": "RIGHT", "created_at": "2017-04-14T12:02:28+00:00" }, { "id": 111565743, "user": "user_f068c71fd303", "body": "Ok, one last note. It's slightly nicer to save this into a mutable object in the enclosing scope (e.g. a list) and then put the assertion in the enclosing function rather than the socket handler. assertions in the socket handler *do* work, but it's usually nicer to let the socket handler run to completion rather than blow it up and possibly leak it.", "path": "tests/test_lowlevel.py", "line": null, "side": "RIGHT", "created_at": "2017-04-14T12:04:16+00:00" }, { "id": 111572518, "user": "user_58bf12d651f4", "body": "once again this is probably better :smile: . I hope I understand you correctly (changed it again).", "path": "tests/test_lowlevel.py", "line": null, "side": "RIGHT", "created_at": "2017-04-14T13:21:17+00:00" } ], "meta": { "languages": [ "py", "rst" ], "touches_tests": true, "review_state_summary": { "CHANGES_REQUESTED": 2, "COMMENTED": 8, "APPROVED": 2 }, "meaningful_comment_count": 11, "has_approval": true, "has_changes_requested": true, "total_review_comments": 11 } } { "_id": "4163402c84551d39", "_schema_version": "1.0", "_cleaned_at": "2026-02-12T07:46:52.085742+00:00", "repo": "psf/requests", "repo_url": "https://github.com/psf/requests", "license_name": "Apache License 2.0", "license_spdx": "Apache-2.0", "pr_number": 3943, "title": "HTTPAdapter.send() timeout defaults", "body": "This PR allows to use urllib3 ``Timeout`` objects as ``timeout`` argument in ``HTTPAdapter.send()``.\n\nBesides it omits the ``timeout`` argument when calling ``conn.urlopen()`` if ``HTTPAdapter.send()`` is called without a timeout. This allows setting a default timeout at connection pool level:\n`adapter.poolmanager.connection_pool_kw['timeout'] = urllib3.Timeout(...)`", "author": "user_022358132a45", "created_at": "2017-03-29T15:42:47+00:00", "merged_at": "2017-04-03T15:45:12+00:00", "base_branch": "master", "head_branch": "timeout", "additions": 32, "deletions": 9, "changed_files": 2, "files": [ { "filename": "requests/adapters.py", "status": "modified", "additions": 3, "deletions": 1, "changes": 4, "patch": "@@ -391,7 +391,7 @@ def send(self, request, stream=False, timeout=None, verify=True, cert=None, prox\n :param timeout: (optional) How long to wait for the server to send\n data before giving up, as a float, or a :ref:`(connect timeout,\n read timeout) ` tuple.\n- :type timeout: float or tuple\n+ :type timeout: float or tuple or urllib3 Timeout object\n :param verify: (optional) Either a boolean, in which case it controls whether\n we verify the server's TLS certificate, or a string, in which case it\n must be a path to a CA bundle to use\n@@ -418,6 +418,8 @@ def send(self, request, stream=False, timeout=None, verify=True, cert=None, prox\n \"timeout tuple, or a single float to set \"\n \"both timeouts to the same value\".format(timeout))\n raise ValueError(err)\n+ elif isinstance(timeout, TimeoutSauce):\n+ pass\n else:\n timeout = TimeoutSauce(connect=timeout, read=timeout)" }, { "filename": "tests/test_requests.py", "status": "modified", "additions": 29, "deletions": 8, "changes": 37, "patch": "@@ -33,6 +33,7 @@\n \n from .compat import StringIO, u\n from .utils import override_environ\n+from requests.packages.urllib3.util import Timeout as Urllib3Timeout\n \n # Requests to this URL should always fail with a connection timeout (nothing\n # listening on that port)\n@@ -2013,7 +2014,12 @@ def test_invalid_timeout(self, httpbin, timeout, error_text):\n requests.get(httpbin('get'), timeout=timeout)\n assert error_text in str(e)\n \n- def test_none_timeout(self, httpbin):\n+ [USER_REDACTED].mark.parametrize(\n+ 'timeout', (\n+ None,\n+ Urllib3Timeout(connect=None, read=None)\n+ ))\n+ def test_none_timeout(self, httpbin, timeout):\n \"\"\"Check that you can set None as a valid timeout value.\n \n To actually test this behavior, we'd want to check that setting the\n@@ -2022,27 +2028,42 @@ def test_none_timeout(self, httpbin):\n Instead we verify that setting the timeout to None does not prevent the\n request from succeeding.\n \"\"\"\n- r = requests.get(httpbin('get'), timeout=None)\n+ r = requests.get(httpbin('get'), timeout=timeout)\n assert r.status_code == 200\n \n- def test_read_timeout(self, httpbin):\n+ [USER_REDACTED].mark.parametrize(\n+ 'timeout', (\n+ (None, 0.1),\n+ Urllib3Timeout(connect=None, read=0.1)\n+ ))\n+ def test_read_timeout(self, httpbin, timeout):\n try:\n- requests.get(httpbin('delay/10'), timeout=(None, 0.1))\n+ requests.get(httpbin('delay/10'), timeout=timeout)\n pytest.fail('The recv() request should time out.')\n except ReadTimeout:\n pass\n \n- def test_connect_timeout(self):\n+ [USER_REDACTED].mark.parametrize(\n+ 'timeout', (\n+ (0.1, None),\n+ Urllib3Timeout(connect=0.1, read=None)\n+ ))\n+ def test_connect_timeout(self, timeout):\n try:\n- requests.get(TARPIT, timeout=(0.1, None))\n+ requests.get(TARPIT, timeout=timeout)\n pytest.fail('The connect() request should time out.')\n except ConnectTimeout as e:\n assert isinstance(e, ConnectionError)\n assert isinstance(e, Timeout)\n \n- def test_total_timeout_connect(self):\n+ [USER_REDACTED].mark.parametrize(\n+ 'timeout', (\n+ (0.1, 0.1),\n+ Urllib3Timeout(connect=0.1, read=0.1)\n+ ))\n+ def test_total_timeout_connect(self, timeout):\n try:\n- requests.get(TARPIT, timeout=(0.1, 0.1))\n+ requests.get(TARPIT, timeout=timeout)\n pytest.fail('The connect() request should time out.')\n except ConnectTimeout:\n pass" } ], "reviews": [ { "id": 29761510, "user": "user_f068c71fd303", "state": "CHANGES_REQUESTED", "body": "Thanks for this! I've left some notes in the diff.", "submitted_at": "2017-03-29T15:46:37+00:00" }, { "id": 29770900, "user": "user_022358132a45", "state": "COMMENTED", "body": null, "submitted_at": "2017-03-29T16:18:18+00:00" }, { "id": 29798710, "user": "user_f068c71fd303", "state": "COMMENTED", "body": null, "submitted_at": "2017-03-29T18:05:58+00:00" }, { "id": 30006547, "user": "user_022358132a45", "state": "COMMENTED", "body": null, "submitted_at": "2017-03-30T14:22:56+00:00" }, { "id": 30011707, "user": "user_f068c71fd303", "state": "CHANGES_REQUESTED", "body": "Cool, this is really good. I'd absolutely love it if we could come up with a test for this as well so that we can cover that line of code. Do you mind writing one?", "submitted_at": "2017-03-30T14:39:17+00:00" }, { "id": 30446500, "user": "user_f068c71fd303", "state": "CHANGES_REQUESTED", "body": "Good idea! However, rather than copy the tests, we should use [py.test's parametrizing fixture](https://docs.pytest.org/en/latest/parametrize.html#pytest-mark-parametrize-parametrizing-test-functions) to handle this, which will reduce the amount of duplicate code we write, and indicate very clearly to the person reading the tests that these two things are expected to behave *identically*.", "submitted_at": "2017-04-03T07:11:32+00:00" }, { "id": 30533727, "user": "user_f068c71fd303", "state": "APPROVED", "body": "Great, this looks really good! Thanks for dealing with the code review process. I'll merge this assuming all the tests pass. :sparkles: :cake: :sparkles:", "submitted_at": "2017-04-03T14:35:24+00:00" }, { "id": 30536722, "user": "user_f068c71fd303", "state": "CHANGES_REQUESTED", "body": null, "submitted_at": "2017-04-03T14:46:00+00:00" }, { "id": 30554441, "user": "user_f068c71fd303", "state": "APPROVED", "body": null, "submitted_at": "2017-04-03T15:45:02+00:00" } ], "review_comments": [ { "id": 108712281, "user": "user_f068c71fd303", "body": "Can this be moved lower down the list? A timeout object isn't a tuple, so the original `isinstance(tuple)` check won't catch it, so let's try to avoid rearranging the code too much.", "path": "requests/adapters.py", "line": null, "side": "RIGHT", "created_at": "2017-03-29T15:45:19+00:00" }, { "id": 108712561, "user": "user_f068c71fd303", "body": "Unfortunately, this change is breaking. You'll either need to remove the default timeout change, or move this PR to the 3.0 branch.\n\nYou're also welcome to split this PR into two parts, the first bit making just the non-breaking changes against the master branch and the second bit making the breaking ones against 3.0.", "path": "requests/adapters.py", "line": null, "side": "RIGHT", "created_at": "2017-03-29T15:46:28+00:00" }, { "id": 108720832, "user": "user_022358132a45", "body": "Hmm. Is it really breaking?\nLooking at urllib3, leaving out the timeout argument will result in calling ``connectionpool.HTTPConnectionPool._get_timeout(_Default)``, which will use ``Timeout.DEFAULT_TIMEOUT`` if the ``HTTPConnectionPool`` had been initialized without a timeout. And ``Timeout.from_float(DEFAULT_TIMEOUT)`` yields the same result as if it had been called with ``None``: https://github.com/shazow/urllib3/blob/master/urllib3/util/timeout.py#L117\n\nSo the results should be the same...", "path": "requests/adapters.py", "line": null, "side": "RIGHT", "created_at": "2017-03-29T16:18:18+00:00" }, { "id": 108746595, "user": "user_f068c71fd303", "body": "Nope, they aren't the same. They both validate to the identity, but that identity is then used as the actual timeout. Note: https://github.com/shazow/urllib3/blob/master/urllib3/util/timeout.py#L33", "path": "requests/adapters.py", "line": null, "side": "RIGHT", "created_at": "2017-03-29T18:05:58+00:00" }, { "id": 108939512, "user": "user_022358132a45", "body": "Ah - ok. Your are right.\nI removed the change for ``timeout`` is ``None``.", "path": "requests/adapters.py", "line": null, "side": "RIGHT", "created_at": "2017-03-30T14:22:56+00:00" }, { "id": 109435630, "user": "user_f068c71fd303", "body": "Ah, so the tests are failing because you've aliased this name (`Timeout`) with the name of an exception. Might be worth changing this to `from requests.packages.urllib3.util import Timeout as Urllib3Timeout` or something similar.", "path": "tests/test_requests.py", "line": null, "side": "RIGHT", "created_at": "2017-04-03T14:45:57+00:00" } ], "meta": { "languages": [ "py" ], "touches_tests": true, "review_state_summary": { "CHANGES_REQUESTED": 4, "COMMENTED": 3, "APPROVED": 2 }, "meaningful_comment_count": 6, "has_approval": true, "has_changes_requested": true, "total_review_comments": 6 } } { "_id": "4d17e351377d292a", "_schema_version": "1.0", "_cleaned_at": "2026-02-12T07:46:52.085742+00:00", "repo": "psf/requests", "repo_url": "https://github.com/psf/requests", "license_name": "Apache License 2.0", "license_spdx": "Apache-2.0", "pr_number": 3927, "title": "Raise IOError when providing an invalid path to a CA bundle or …", "body": "Use IOError whenever invalid paths are used for ssl certificates (#3926)", "author": "user_3d94569530c9", "created_at": "2017-03-17T22:03:26+00:00", "merged_at": "2017-03-22T20:41:08+00:00", "base_branch": "master", "head_branch": "raise_IOError_invalid_certificate_files", "additions": 40, "deletions": 8, "changed_files": 4, "files": [ { "filename": "requests/adapters.py", "status": "modified", "additions": 18, "deletions": 5, "changes": 23, "patch": "@@ -64,7 +64,9 @@ def send(self, request, stream=False, timeout=None, verify=True,\n data before giving up, as a float, or a :ref:`(connect timeout,\n read timeout) ` tuple.\n :type timeout: float or tuple\n- :param verify: (optional) Whether to verify SSL certificates.\n+ :param verify: (optional) Either a boolean, in which case it controls whether we verify\n+ the server's TLS certificate, or a string, in which case it must be a path\n+ to a CA bundle to use\n :param cert: (optional) Any user-provided SSL certificate to be trusted.\n :param proxies: (optional) The proxies dictionary to apply to the request.\n \"\"\"\n@@ -202,7 +204,9 @@ def cert_verify(self, conn, url, verify, cert):\n \n :param conn: The urllib3 connection object associated with the cert.\n :param url: The requested URL.\n- :param verify: Whether we should actually verify the certificate.\n+ :param verify: Either a boolean, in which case it controls whether we verify\n+ the server's TLS certificate, or a string, in which case it must be a path\n+ to a CA bundle to use\n :param cert: The SSL certificate to verify.\n \"\"\"\n if url.lower().startswith('https') and verify:\n@@ -216,8 +220,9 @@ def cert_verify(self, conn, url, verify, cert):\n if not cert_loc:\n cert_loc = DEFAULT_CA_BUNDLE_PATH\n \n- if not cert_loc:\n- raise Exception(\"Could not find a suitable SSL CA certificate bundle.\")\n+ if not cert_loc or not os.path.exists(cert_loc):\n+ raise IOError(\"Could not find a suitable TLS CA certificate bundle, \"\n+ \"invalid path: {0}\".format(cert_loc))\n \n conn.cert_reqs = 'CERT_REQUIRED'\n \n@@ -236,6 +241,12 @@ def cert_verify(self, conn, url, verify, cert):\n conn.key_file = cert[1]\n else:\n conn.cert_file = cert\n+ if conn.cert_file and not os.path.exists(conn.cert_file):\n+ raise IOError(\"Could not find the TLS certificate file, \"\n+ \"invalid path: {0}\".format(conn.cert_file))\n+ if conn.key_file and not os.path.exists(conn.key_file):\n+ raise IOError(\"Could not find the TLS key file, \"\n+ \"invalid path: {0}\".format(conn.key_file))\n \n def build_response(self, req, resp):\n \"\"\"Builds a :class:`Response ` object from a urllib3\n@@ -381,7 +392,9 @@ def send(self, request, stream=False, timeout=None, verify=True, cert=None, prox\n data before giving up, as a float, or a :ref:`(connect timeout,\n read timeout) ` tuple.\n :type timeout: float or tuple\n- :param verify: (optional) Whether to verify SSL certificates.\n+ :param verify: (optional) Either a boolean, in which case it controls whether\n+ we verify the server's TLS certificate, or a string, in which case it\n+ must be a path to a CA bundle to use\n :param cert: (optional) Any user-provided SSL certificate to be trusted.\n :param proxies: (optional) The proxies dictionary to apply to the request.\n :rtype: requests.Response" }, { "filename": "requests/api.py", "status": "modified", "additions": 3, "deletions": 1, "changes": 4, "patch": "@@ -36,7 +36,9 @@ def request(method, url, **kwargs):\n :param allow_redirects: (optional) Boolean. Enable/disable GET/OPTIONS/POST/PUT/PATCH/DELETE/HEAD redirection. Defaults to ``True``.\n :type allow_redirects: bool\n :param proxies: (optional) Dictionary mapping protocol to the URL of the proxy.\n- :param verify: (optional) whether the SSL cert will be verified. A CA_BUNDLE path can also be provided. Defaults to ``True``.\n+ :param verify: (optional) Either a boolean, in which case it controls whether we verify\n+ the server's TLS certificate, or a string, in which case it must be a path\n+ to a CA bundle to use. Defaults to ``True``.\n :param stream: (optional) if ``False``, the response content will be immediately downloaded.\n :param cert: (optional) if String, path to ssl client cert file (.pem). If Tuple, ('cert', 'key') pair.\n :return: :class:`Response ` object" }, { "filename": "requests/sessions.py", "status": "modified", "additions": 3, "deletions": 2, "changes": 5, "patch": "@@ -460,8 +460,9 @@ def request(self, method, url,\n hostname to the URL of the proxy.\n :param stream: (optional) whether to immediately download the response\n content. Defaults to ``False``.\n- :param verify: (optional) whether the SSL cert will be verified.\n- A CA_BUNDLE path can also be provided. Defaults to ``True``.\n+ :param verify: (optional) Either a boolean, in which case it controls whether we verify\n+ the server's TLS certificate, or a string, in which case it must be a path\n+ to a CA bundle to use. Defaults to ``True``.\n :param cert: (optional) if String, path to ssl client cert file (.pem).\n If Tuple, ('cert', 'key') pair.\n :rtype: requests.Response" }, { "filename": "tests/test_requests.py", "status": "modified", "additions": 16, "deletions": 0, "changes": 16, "patch": "@@ -769,6 +769,22 @@ def test_unicode_header_name(self, httpbin):\n def test_pyopenssl_redirect(self, httpbin_secure, httpbin_ca_bundle):\n requests.get(httpbin_secure('status', '301'), verify=httpbin_ca_bundle)\n \n+ def test_invalid_ca_certificate_path(self, httpbin_secure):\n+ INVALID_PATH = '/garbage'\n+ with pytest.raises(IOError) as e:\n+ requests.get(httpbin_secure(), verify=INVALID_PATH)\n+ assert str(e.value) == 'Could not find a suitable TLS CA certificate bundle, invalid path: {0}'.format(INVALID_PATH)\n+\n+ def test_invalid_ssl_certificate_files(self, httpbin_secure):\n+ INVALID_PATH = '/garbage'\n+ with pytest.raises(IOError) as e:\n+ requests.get(httpbin_secure(), cert=INVALID_PATH)\n+ assert str(e.value) == 'Could not find the TLS certificate file, invalid path: {0}'.format(INVALID_PATH)\n+\n+ with pytest.raises(IOError) as e:\n+ requests.get(httpbin_secure(), cert=('.', INVALID_PATH))\n+ assert str(e.value) == 'Could not find the TLS key file, invalid path: {0}'.format(INVALID_PATH)\n+\n def test_https_warnings(self, httpbin_secure, httpbin_ca_bundle):\n \"\"\"warnings are emitted with requests.get\"\"\"\n if HAS_MODERN_SSL or HAS_PYOPENSSL:" } ], "reviews": [ { "id": 27750730, "user": "user_f068c71fd303", "state": "CHANGES_REQUESTED", "body": "So, *in general* this is reasonable. There are some concerns about \"look before you leap\" here: in an ideal world we'd try to catch the error and diagnose after the fact, but that doesn't work well. So I think I'm in general ok with this, modulo a few concerns I have inline.", "submitted_at": "2017-03-19T15:26:05+00:00" }, { "id": 27807211, "user": "user_f068c71fd303", "state": "CHANGES_REQUESTED", "body": "Thanks for addressing the review! I have a few more smaller notes.", "submitted_at": "2017-03-20T10:18:57+00:00" }, { "id": 28503733, "user": "user_f068c71fd303", "state": "APPROVED", "body": "Ok, I think I'm happy with this. Thanks so much! :sparkles:", "submitted_at": "2017-03-22T20:35:51+00:00" } ], "review_comments": [ { "id": 106809376, "user": "user_f068c71fd303", "body": "Why did this conditional get inverted?", "path": "requests/adapters.py", "line": null, "side": "RIGHT", "created_at": "2017-03-19T15:23:32+00:00" }, { "id": 106809403, "user": "user_f068c71fd303", "body": "You can't make this change in a backwards compatible way: the current code allows for tuples longer than length two.", "path": "requests/adapters.py", "line": null, "side": "RIGHT", "created_at": "2017-03-19T15:24:32+00:00" }, { "id": 106866240, "user": "user_f068c71fd303", "body": "So, this docstring needs to be reworded. Let's have it be: `Either a boolean, in which case it controls whether we verify the server's TLS certificate, or a string, in which case it must be a path to a CA bundle to use`.", "path": "requests/adapters.py", "line": null, "side": "RIGHT", "created_at": "2017-03-20T10:16:26+00:00" }, { "id": 106866506, "user": "user_f068c71fd303", "body": "For new exception strings, can we use the acronym `TLS` instead of the acronym `SSL`? I don't want to change the string in the block above because people may be checking the actual string message, but these ones should use the proper name for the protocol.", "path": "requests/adapters.py", "line": null, "side": "RIGHT", "created_at": "2017-03-20T10:18:01+00:00" }, { "id": 106866645, "user": "user_f068c71fd303", "body": "For these tests, can you use the `httpbin_secure` fixture like the tests above? We want to avoid making live web requests in our tests.", "path": "tests/test_requests.py", "line": null, "side": "RIGHT", "created_at": "2017-03-20T10:18:45+00:00" } ], "meta": { "languages": [ "py" ], "touches_tests": true, "review_state_summary": { "CHANGES_REQUESTED": 2, "APPROVED": 1 }, "meaningful_comment_count": 5, "has_approval": true, "has_changes_requested": true, "total_review_comments": 5 } } { "_id": "518bd3f653340028", "_schema_version": "1.0", "_cleaned_at": "2026-02-12T07:46:52.085742+00:00", "repo": "psf/requests", "repo_url": "https://github.com/psf/requests", "license_name": "Apache License 2.0", "license_spdx": "Apache-2.0", "pr_number": 3923, "title": "Rebase #3745 and add some tests", "body": "2 years after the original #2431, and after #3745\nI encountered the strange behavior of `r.iter_lines()`, found this and tried to complete it.\nRebased once more and added more tests using the breakdown of [USER_REDACTED] https://github.com/[USER_REDACTED]nethreitz/requests/pull/2431#issuecomment-72333964", "author": "user_a886f6ee857b", "created_at": "2017-03-14T18:41:10+00:00", "merged_at": "2017-03-16T09:53:04+00:00", "base_branch": "proposed/3.0.0", "head_branch": "3.0.0-iter_lines", "additions": 107, "deletions": 8, "changed_files": 2, "files": [ { "filename": "requests/models.py", "status": "modified", "additions": 28, "deletions": 5, "changes": 33, "patch": "@@ -776,23 +776,46 @@ def iter_lines(self, chunk_size=ITER_CHUNK_SIZE, decode_unicode=None, delimiter=\n \n .. note:: This method is not reentrant safe.\n \"\"\"\n-\n pending = None\n \n- for chunk in self.iter_content(chunk_size=chunk_size, decode_unicode=decode_unicode):\n+ for chunk in self.iter_content(chunk_size=chunk_size,\n+ decode_unicode=decode_unicode):\n+ # Skip any null responses: if there is pending data it is necessarily an\n+ # incomplete chunk, so if we don't have more data we don't want to bother\n+ # trying to get it. Unconsumed pending data will be yielded anyway in the\n+ # end of the loop if the stream ends.\n+ if not chunk:\n+ continue\n \n+ # Consume any pending data\n if pending is not None:\n chunk = pending + chunk\n+ pending = None\n \n+ # Either split on a line, or split on a specified delimiter\n if delimiter:\n lines = chunk.split(delimiter)\n else:\n lines = chunk.splitlines()\n \n- if lines and lines[-1] and chunk and lines[-1][-1] == chunk[-1]:\n+ # Calling `.split(delimiter)` will always end with whatever text\n+ # remains beyond the delimiter, or '' if the delimiter is the end\n+ # of the text. On the other hand, `.splitlines()` doesn't include\n+ # a '' if the text ends in a line delimiter.\n+ #\n+ # For example:\n+ #\n+ # 'abc\\ndef\\n'.split('\\n') ~> ['abc', 'def', '']\n+ # 'abc\\ndef\\n'.splitlines() ~> ['abc', 'def']\n+ #\n+ # So if we have a specified delimiter, we always pop the final\n+ # item and prepend it to the next chunk.\n+ #\n+ # If we're using `splitlines()`, we only do this if the chunk\n+ # ended midway through a line.\n+ incomplete_line = lines[-1] and lines[-1][-1] == chunk[-1]\n+ if delimiter or incomplete_line:\n pending = lines.pop()\n- else:\n- pending = None\n \n for line in lines:\n yield line" }, { "filename": "tests/test_requests.py", "status": "modified", "additions": 79, "deletions": 3, "changes": 82, "patch": "@@ -1296,6 +1296,81 @@ def test_request_and_response_are_pickleable(self, httpbin):\n assert r.request.url == pr.request.url\n assert r.request.headers == pr.request.headers\n \n+\n+ def test_response_lines(self):\n+ \"\"\"\n+ iter_lines should be able to handle data dribbling in which delimiters\n+ might not be lined up ideally.\n+ \"\"\"\n+ mock_chunks = [\n+ 'This \\r\\n',\n+ '',\n+ 'is\\r',\n+ '\\n',\n+ 'a',\n+ ' ',\n+ '',\n+ '',\n+ 'test.',\n+ '\\r',\n+ '\\n',\n+ 'end.',\n+ ]\n+ mock_data = ''.join(mock_chunks)\n+\n+ mock_iter_content = lambda *args, **kwargs: (e for e in mock_chunks)\n+\n+ r = requests.Response()\n+ r._content_consumed = True\n+ r.iter_content = mock_iter_content\n+\n+ assert list(r.iter_lines(delimiter='\\r\\n')) == mock_data.split('\\r\\n')\n+\n+ # Because '\\n' is a single line-end, when `iter_lines()` receives\n+ # the chunks containing a single '\\n', it emits '' as a line -- whereas\n+ # `.splitlines()` combines with the '\\r' and splits on `\\r\\n`.\n+ result = list(r.iter_lines())\n+ assert result != mock_data.splitlines()\n+ assert result[2] == ''\n+ assert result[4] == ''\n+ # If we change all the line breaks to `\\r`, we should be okay.\n+ mock_chunks = [chunk.replace('\\n', '\\r') for chunk in mock_chunks]\n+ mock_data = ''.join(mock_chunks)\n+ assert list(r.iter_lines()) == mock_data.splitlines()\n+\n+\n+ [USER_REDACTED].mark.parametrize(\n+ 'content, expected_no_delimiter, expected_delimiter', (\n+ ([''], [], []),\n+ (['line\\n'], ['line'], ['line\\n']),\n+ (['line', '\\n'], ['line'], ['line\\n']),\n+ (['line\\r\\n'], ['line'], ['line', '']),\n+ # Empty chunk in the end of stream, same behavior as the previous\n+ (['line\\r\\n', ''], ['line'], ['line', '']),\n+ (['line', '\\r\\n'], ['line'], ['line', '']),\n+ (['a\\r', '\\nb\\r'], ['a', '', 'b'], ['a', 'b\\r']),\n+ (['a\\n', '\\nb'], ['a', '', 'b'], ['a\\n\\nb']),\n+ (['a\\r\\n','\\rb\\n'], ['a', '', 'b'], ['a', '\\rb\\n']),\n+ (['a\\nb', 'c'], ['a', 'bc'], ['a\\nbc']),\n+ (['a\\n', '\\rb', '\\r\\nc'], ['a', '', 'b', 'c'], ['a\\n\\rb', 'c']),\n+ (['a\\r\\nb', '', 'c'], ['a', 'bc'], ['a', 'bc']) # Empty chunk with pending data\n+ ))\n+ def test_response_lines_parametrized(self, content, expected_no_delimiter, expected_delimiter):\n+ \"\"\"\n+ Test a lot of potential chunk splits to ensure consistency of\n+ iter_lines(delimiter=x), as well as the legacy behavior of\n+ iter_lines() without delimiter\n+ https://github.com/[USER_REDACTED]nethreitz/requests/pull/2431#issuecomment-72333964\n+ \"\"\"\n+ mock_chunks = content\n+ mock_iter_content = lambda *args, **kwargs: (e for e in mock_chunks)\n+\n+ r = requests.Response()\n+ r._content_consumed = True\n+ r.iter_content = mock_iter_content\n+ assert list(r.iter_lines()) == expected_no_delimiter\n+ assert list(r.iter_lines(delimiter='\\r\\n')) == expected_delimiter\n+\n def test_prepared_request_is_pickleable(self, httpbin):\n p = requests.Request('GET', httpbin('get')).prepare()\n \n@@ -1741,11 +1816,12 @@ def test_json_param_post_should_not_override_data_param(self, httpbin):\n prep = r.prepare()\n assert 'stuff=elixr' == prep.body\n \n- def test_response_iter_lines(self, httpbin):\n+ [USER_REDACTED].mark.parametrize('decode_unicode', (True, False))\n+ def test_response_iter_lines(self, httpbin, decode_unicode):\n r = requests.get(httpbin('stream/4'), stream=True)\n assert r.status_code == 200\n-\n- it = r.iter_lines()\n+ r.encoding = 'utf-8'\n+ it = r.iter_lines(decode_unicode=decode_unicode)\n next(it)\n assert len(list(it)) == 3" } ], "reviews": [ { "id": 26904365, "user": "user_f068c71fd303", "state": "CHANGES_REQUESTED", "body": "Cool, so this generally looks really good! I have one small note.", "submitted_at": "2017-03-14T19:10:20+00:00" }, { "id": 26966228, "user": "user_a886f6ee857b", "state": "COMMENTED", "body": null, "submitted_at": "2017-03-15T00:21:23+00:00" }, { "id": 26967914, "user": "user_a886f6ee857b", "state": "COMMENTED", "body": null, "submitted_at": "2017-03-15T00:34:22+00:00" }, { "id": 27022436, "user": "user_f068c71fd303", "state": "COMMENTED", "body": null, "submitted_at": "2017-03-15T09:18:03+00:00" }, { "id": 27047809, "user": "user_a886f6ee857b", "state": "COMMENTED", "body": null, "submitted_at": "2017-03-15T11:18:31+00:00" }, { "id": 27051628, "user": "user_f068c71fd303", "state": "APPROVED", "body": "Ok, I think I'm happy with this. Thanks for pushing this over the line! I'll try to dive into what's going on with the tests.", "submitted_at": "2017-03-15T11:41:12+00:00" }, { "id": 27051718, "user": "user_f068c71fd303", "state": "CHANGES_REQUESTED", "body": "Ok, so the tests are failing because of a bytes/string incompatibility. Want to take a look?", "submitted_at": "2017-03-15T11:41:49+00:00" }, { "id": 27148713, "user": "user_f068c71fd303", "state": "COMMENTED", "body": null, "submitted_at": "2017-03-15T17:46:44+00:00" }, { "id": 27154916, "user": "user_a886f6ee857b", "state": "COMMENTED", "body": null, "submitted_at": "2017-03-15T18:08:04+00:00" }, { "id": 27190611, "user": "user_dbf2a999bd6d", "state": "COMMENTED", "body": null, "submitted_at": "2017-03-15T20:33:45+00:00" }, { "id": 27191644, "user": "user_dbf2a999bd6d", "state": "COMMENTED", "body": null, "submitted_at": "2017-03-15T20:37:54+00:00" }, { "id": 27204404, "user": "user_a886f6ee857b", "state": "COMMENTED", "body": null, "submitted_at": "2017-03-15T21:33:24+00:00" }, { "id": 27204980, "user": "user_a886f6ee857b", "state": "COMMENTED", "body": null, "submitted_at": "2017-03-15T21:36:15+00:00" }, { "id": 27292957, "user": "user_f068c71fd303", "state": "APPROVED", "body": "Cool, we seem to have resolved everything outstanding. Nicely done!", "submitted_at": "2017-03-16T09:52:45+00:00" } ], "review_comments": [ { "id": 106000692, "user": "user_f068c71fd303", "body": "Should this check move after the pending data logic?", "path": "requests/models.py", "line": null, "side": "RIGHT", "created_at": "2017-03-14T19:07:50+00:00" }, { "id": 106060294, "user": "user_a886f6ee857b", "body": "You're right\nFixed and added tests for this behavior :ok_hand:\n\nI don't know if it's licit to receive empty chunks in the middle of a stream, but I guess it's possible in theory. (and it would work)", "path": "requests/models.py", "line": null, "side": "RIGHT", "created_at": "2017-03-15T00:21:23+00:00" }, { "id": 106061933, "user": "user_a886f6ee857b", "body": "Actually I replied too fast: if we want to return the same result on\n`['line\\r\\n']` and `['line\\r\\n', '']` (which seems right),\nwe need to keep this check on top\n\nOtherwise we consume `pending` and discard it\n\nI think it's safe to discard empty chunks early, `pending` will be carried to the next non-empty chunk", "path": "requests/models.py", "line": null, "side": "RIGHT", "created_at": "2017-03-15T00:34:22+00:00" }, { "id": 106116333, "user": "user_f068c71fd303", "body": "> I don't know if it's licit to receive empty chunks in the middle of a stream, but I guess it's possible in theory. (and it would work)\n\nurllib3 won't give them to us, but people like putting things that aren't urllib3 underneath us, and they might. So we should tolerate it.\n\nAs to your note about wanting to return the same result, I think that makes sense. But we should add a comment to say that \"pending is necessarily an incomplete chunk, and so if we don't have more data we don't want to bother trying to get it\".", "path": "requests/models.py", "line": null, "side": "RIGHT", "created_at": "2017-03-15T09:18:03+00:00" }, { "id": 106140637, "user": "user_a886f6ee857b", "body": "Done 👌", "path": "requests/models.py", "line": null, "side": "RIGHT", "created_at": "2017-03-15T11:18:31+00:00" }, { "id": 106236069, "user": "user_f068c71fd303", "body": "So, to be clear, the error in this fix was assuming that we need to tolerate `str` here. The tests were in error, not the code: `iter_content` is required to always yield `bytes`. You'll find if you go through the tests and use `bytes` everywhere the problem goes away. :grin: So we don't need this.", "path": "requests/models.py", "line": null, "side": "RIGHT", "created_at": "2017-03-15T17:46:44+00:00" }, { "id": 106241853, "user": "user_a886f6ee857b", "body": "I'm confused: I checked in a normal usage (outside of the tests) and could reproduce the issue:\nwith Python2 I get `str`, and with Python3 I get `bytes` (and if I use `iter_lines(decode_unicode=True)`\nI get `str` (Py3) or `unicode` (Py2)\n\nThe previous code wasn't accepting bytes (and was working only with Python 2)\n\nThis failed on Python3 before my last fix:\n```\nr = requests.get(\"https://github.com\", stream=True)\nlist(r.iter_lines())\n```\nTypeError: endswith first arg must be bytes or a tuple of bytes, not int\n\nThat's why I don't think the tests were in error (a test that I didn't write was failing, `test_response_iter_lines`)", "path": "requests/models.py", "line": null, "side": "RIGHT", "created_at": "2017-03-15T18:08:04+00:00" }, { "id": 106275460, "user": "user_dbf2a999bd6d", "body": "[USER_REDACTED] The issue here seems to be stemming from 46e3fdd in #3745. The conditional on master, and prior to that commit, is done by [NAME_REDACTED] of each string/bytestring. When retrieving a single index from a bytestring in Python 3 it returns an integer representation of the byte. This works in the case of `lines[-1] and lines[-1][-1] == chunk[-1]` but not `lines[-1] and lines[-1].endswith(chunk[-1])`.\n\nI'd suggest we simply move back to using the original double indexing, rather than introducing more logic to handle the seemingly unneeded `endswith`.", "path": "requests/models.py", "line": null, "side": "RIGHT", "created_at": "2017-03-15T20:33:45+00:00" }, { "id": 106276486, "user": "user_dbf2a999bd6d", "body": "Also, I'm not sure if you're going to back this commit out, but if not, `decode_unicode` doesn't seem to be used for anything here in this tests current configuration.", "path": "tests/test_requests.py", "line": 1820, "side": "RIGHT", "created_at": "2017-03-15T20:37:54+00:00" }, { "id": 106288441, "user": "user_a886f6ee857b", "body": "Thanks, I missed that... much neater. It works fine with a simple indexing in all cases.", "path": "requests/models.py", "line": null, "side": "RIGHT", "created_at": "2017-03-15T21:33:24+00:00" }, { "id": 106288968, "user": "user_a886f6ee857b", "body": "Nice catch\nI overwrote the commit, and fixed the unused `decode_unicode` parameter :ok_hand:", "path": "tests/test_requests.py", "line": 1820, "side": "RIGHT", "created_at": "2017-03-15T21:36:14+00:00" } ], "meta": { "languages": [ "py" ], "touches_tests": true, "review_state_summary": { "CHANGES_REQUESTED": 2, "COMMENTED": 10, "APPROVED": 2 }, "meaningful_comment_count": 10, "has_approval": true, "has_changes_requested": true, "total_review_comments": 11 } } { "_id": "0e88c1a64a551521", "_schema_version": "1.0", "_cleaned_at": "2026-02-12T07:46:52.085742+00:00", "repo": "psf/requests", "repo_url": "https://github.com/psf/requests", "license_name": "Apache License 2.0", "license_spdx": "Apache-2.0", "pr_number": 3903, "title": "fix #3902 Add proposed documentation change for post data", "body": null, "author": "user_c18855421329", "created_at": "2017-03-01T19:07:25+00:00", "merged_at": "2017-05-27T21:25:48+00:00", "base_branch": "master", "head_branch": "master", "additions": 41, "deletions": 2, "changed_files": 2, "files": [ { "filename": "AUTHORS.rst", "status": "modified", "additions": 1, "deletions": 1, "changes": 2, "patch": "@@ -179,4 +179,4 @@ Patches and Suggestions\n - [NAME_REDACTED] ([CONTRIBUTOR_REDACTED])\n - [NAME_REDACTED] ([CONTRIBUTOR_REDACTED])\n - [NAME_REDACTED] ([CONTRIBUTOR_REDACTED])\n-\n+- [NAME_REDACTED] ([CONTRIBUTOR_REDACTED])" }, { "filename": "docs/user/quickstart.rst", "status": "modified", "additions": 40, "deletions": 1, "changes": 41, "patch": "@@ -234,6 +234,45 @@ dictionary of data will automatically be form-encoded when the request is made::\n ...\n }\n \n+You can also pass a list of tuples to the ``data`` argument. This is particularly\n+useful when the form has multiple elements that use the same key::\n+\n+ >>> payload = (('key1', 'value1'), ('key1', 'value2'))\n+ >>> r = requests.post('http://httpbin.org/post', data=payload)\n+ >>> print(r.text)\n+ {\n+ ...\n+ \"form\": {\n+ \"key1\": [\n+ \"value1\",\n+ \"value2\"\n+ ]\n+ },\n+ ...\n+ }\n+\n+Value of each payload element can be a scalar or an iterable::\n+\n+ >>> payload = (('key1', ('value1', 1, (1, 2))), {'key2', ('value2', 2)})\n+ >>> r = requests.post('http://httpbin.org/post', data=payload)\n+ >>> print(r.text)\n+ {\n+ ...\n+ \"form\": {\n+ \"key1\": [\n+ \"value1\",\n+ \"1\",\n+ \"1\",\n+ \"2\"\n+ ],\n+ \"key2\": [\n+ \"value2\",\n+ \"2\"\n+ ]\n+ },\n+ ...\n+ }\n+\n There are many times that you want to send data that is not form-encoded. If\n you pass in a ``string`` instead of a ``dict``, that data will be posted directly.\n \n@@ -485,7 +524,7 @@ Timeouts\n --------\n \n You can tell Requests to stop waiting for a response after a given number of\n-seconds with the ``timeout`` parameter. Nearly all production code should use \n+seconds with the ``timeout`` parameter. Nearly all production code should use\n this parameter in nearly all requests. Failure to do so can cause your program\n to hang indefinitely::" } ], "reviews": [ { "id": 24568983, "user": "user_f068c71fd303", "state": "CHANGES_REQUESTED", "body": "Thanks for this! I have a few small notes, but this seems pretty good to me.", "submitted_at": "2017-03-01T19:37:40+00:00" }, { "id": 24621243, "user": "user_c18855421329", "state": "COMMENTED", "body": null, "submitted_at": "2017-03-01T23:43:35+00:00" }, { "id": 24622224, "user": "user_c18855421329", "state": "COMMENTED", "body": null, "submitted_at": "2017-03-01T23:50:03+00:00" }, { "id": 24677944, "user": "user_f068c71fd303", "state": "COMMENTED", "body": null, "submitted_at": "2017-03-02T08:51:16+00:00" }, { "id": 40080848, "user": "user_36df932e8b7a", "state": "COMMENTED", "body": null, "submitted_at": "2017-05-24T16:33:24+00:00" }, { "id": 40080985, "user": "user_36df932e8b7a", "state": "COMMENTED", "body": null, "submitted_at": "2017-05-24T16:34:10+00:00" } ], "review_comments": [ { "id": 103770019, "user": "user_f068c71fd303", "body": "This should begin \"The value\". Also, let's avoid the word \"scalar\": let's say \"single element\".", "path": "docs/user/quickstart.rst", "line": 254, "side": "RIGHT", "created_at": "2017-03-01T19:34:44+00:00" }, { "id": 103770381, "user": "user_f068c71fd303", "body": "We try not to document that we accept non-string elements here, in part because we don't promise to support them.", "path": "docs/user/quickstart.rst", "line": 256, "side": "RIGHT", "created_at": "2017-03-01T19:36:14+00:00" }, { "id": 103819139, "user": "user_c18855421329", "body": "Thanks. Sounds good.", "path": "docs/user/quickstart.rst", "line": 254, "side": "RIGHT", "created_at": "2017-03-01T23:43:35+00:00" }, { "id": 103820057, "user": "user_c18855421329", "body": "In that case, this section goes away. I can just delete this section so only tuples section above remains. Does that sound good?", "path": "docs/user/quickstart.rst", "line": 256, "side": "RIGHT", "created_at": "2017-03-01T23:50:03+00:00" }, { "id": 103875142, "user": "user_f068c71fd303", "body": "Works for me. 👍", "path": "docs/user/quickstart.rst", "line": 256, "side": "RIGHT", "created_at": "2017-03-02T08:51:16+00:00" }, { "id": 118301928, "user": "user_36df932e8b7a", "body": "Agreed.", "path": "docs/user/quickstart.rst", "line": 254, "side": "RIGHT", "created_at": "2017-05-24T16:33:24+00:00" }, { "id": 118302048, "user": "user_36df932e8b7a", "body": ":sparkles: :cake: :sparkes:", "path": "docs/user/quickstart.rst", "line": 256, "side": "RIGHT", "created_at": "2017-05-24T16:33:56+00:00" } ], "meta": { "languages": [ "rst" ], "touches_tests": false, "review_state_summary": { "CHANGES_REQUESTED": 1, "COMMENTED": 5 }, "meaningful_comment_count": 6, "has_approval": false, "has_changes_requested": true, "total_review_comments": 7 } } { "_id": "ec22aa5e54714a8f", "_schema_version": "1.0", "_cleaned_at": "2026-02-12T07:46:52.085742+00:00", "repo": "psf/requests", "repo_url": "https://github.com/psf/requests", "license_name": "Apache License 2.0", "license_spdx": "Apache-2.0", "pr_number": 3897, "title": "Refactor Prepare Body", "body": "This PR supersedes #3338 with the branch brought up to date, as well as a few minor changes, including logic tweaks based on updates to `super_len` since the original PR.\n\nThis will forcibly prevent the transmission of headers that include both Content-Length and Transfer-Encoding, as well as simplify redundant code we use for both `prepare_content_length` and `prepare_body`. All the credit here goes to [USER_REDACTED], the original creator of this PR.", "author": "user_dbf2a999bd6d", "created_at": "2017-02-28T21:59:09+00:00", "merged_at": "2017-03-02T14:40:58+00:00", "base_branch": "proposed/3.0.0", "head_branch": "prep_body", "additions": 96, "deletions": 23, "changed_files": 5, "files": [ { "filename": "3.0-HISTORY.rst", "status": "modified", "additions": 4, "deletions": 0, "changes": 4, "patch": "@@ -1,6 +1,10 @@\n 3.0.0 (2017-xx-xx)\n ++++++++++++++++++\n \n+- Simplified logic for determining Content-Length and Transfer-Encoding.\n+ Requests will now avoid setting both headers on the same request, and\n+ raise an exception if this is done manually by a user.\n+\n - Remove the HTTPProxyAuth class in favor of supporting proxy auth via\n the proxies parameter." }, { "filename": "requests/exceptions.py", "status": "modified", "additions": 5, "deletions": 0, "changes": 5, "patch": "@@ -104,9 +104,14 @@ class StreamConsumedError(RequestException, TypeError):\n class RetryError(RequestException):\n \"\"\"Custom retries logic failed\"\"\"\n \n+\n class UnrewindableBodyError(RequestException):\n \"\"\"Requests encountered an error when trying to rewind a body\"\"\"\n \n+\n+class InvalidBodyError(RequestException, ValueError):\n+ \"\"\"An invalid request body was specified\"\"\"\n+\n # Warnings" }, { "filename": "requests/models.py", "status": "modified", "additions": 23, "deletions": 22, "changes": 45, "patch": "@@ -32,12 +32,14 @@\n LocationParseError, ConnectionError)\n from .exceptions import (\n HTTPError, MissingScheme, InvalidURL, ChunkedEncodingError,\n- ContentDecodingError, ConnectionError, StreamConsumedError)\n+ ContentDecodingError, ConnectionError, StreamConsumedError,\n+ InvalidHeader, InvalidBodyError)\n from ._internal_utils import to_native_string, unicode_is_ascii\n from .utils import (\n guess_filename, get_auth_from_url, requote_uri,\n stream_decode_response_unicode, to_key_val_list, parse_header_links,\n- iter_slices, guess_json_utf, super_len, check_header_validity)\n+ iter_slices, guess_json_utf, super_len, check_header_validity,\n+ is_stream)\n from .compat import (\n cookielib, urlunparse, urlsplit, urlencode, str, bytes, StringIO,\n is_py2, chardet, builtin_str, basestring)\n@@ -466,17 +468,7 @@ def prepare_body(self, data, files, json=None):\n if not isinstance(body, bytes):\n body = body.encode('utf-8')\n \n- is_stream = all([\n- hasattr(data, '__iter__'),\n- not isinstance(data, (basestring, list, tuple, collections.Mapping))\n- ])\n-\n- try:\n- length = super_len(data)\n- except (TypeError, AttributeError, UnsupportedOperation):\n- length = None\n-\n- if is_stream:\n+ if is_stream(data):\n body = data\n \n if getattr(body, 'tell', None) is not None:\n@@ -493,10 +485,6 @@ def prepare_body(self, data, files, json=None):\n if files:\n raise NotImplementedError('Streamed bodies and files are mutually exclusive.')\n \n- if length:\n- self.headers['Content-Length'] = builtin_str(length)\n- else:\n- self.headers['Transfer-Encoding'] = 'chunked'\n else:\n # Multi-part file uploads.\n if files:\n@@ -509,27 +497,40 @@ def prepare_body(self, data, files, json=None):\n else:\n content_type = 'application/x-www-form-urlencoded'\n \n- self.prepare_content_length(body)\n-\n # Add content-type if it wasn't explicitly provided.\n if content_type and ('content-type' not in self.headers):\n self.headers['Content-Type'] = content_type\n \n+ self.prepare_content_length(body)\n self.body = body\n \n def prepare_content_length(self, body):\n- \"\"\"[NAME_REDACTED] header based on request method and body\"\"\"\n+ \"\"\"[NAME_REDACTED] header.\n+ \n+ If the length of the body of the request can be computed, Content-Length\n+ is set using ``super_len``. If user has manually set either a\n+ Transfer-Encoding or Content-Length header when it should not be set\n+ (they should be mutually exclusive) an InvalidHeader\n+ error will be raised.\n+ \"\"\"\n if body is not None:\n length = super_len(body)\n+\n if length:\n- # If length exists, set it. Otherwise, we fallback\n- # to Transfer-Encoding: chunked.\n self.headers['Content-Length'] = builtin_str(length)\n+ elif is_stream(body):\n+ self.headers['Transfer-Encoding'] = 'chunked'\n+ else:\n+ raise InvalidBodyError('Non-null body must have length or be streamable.')\n elif self.method not in ('GET', 'HEAD') and self.headers.get('Content-Length') is None:\n # [NAME_REDACTED] to 0 for methods that can have a body\n # but don't provide one. (i.e. not GET or HEAD)\n self.headers['Content-Length'] = '0'\n \n+ if 'Transfer-Encoding' in self.headers and 'Content-Length' in self.headers:\n+ raise InvalidHeader('[NAME_REDACTED]: Both Transfer-Encoding and '\n+ 'Content-Length are set.')\n+\n def prepare_auth(self, auth, url=''):\n \"\"\"Prepares the given HTTP auth data.\"\"\"" }, { "filename": "requests/utils.py", "status": "modified", "additions": 8, "deletions": 0, "changes": 8, "patch": "@@ -865,6 +865,7 @@ def urldefragauth(url):\n \n return urlunparse((scheme, netloc, path, params, query, ''))\n \n+\n def rewind_body(prepared_request):\n \"\"\"Move file pointer back to its recorded starting position\n so it can be read again on redirect.\n@@ -878,3 +879,10 @@ def rewind_body(prepared_request):\n \"body for redirect.\")\n else:\n raise UnrewindableBodyError(\"Unable to rewind request body for redirect.\")\n+\n+\n+def is_stream(data):\n+ \"\"\"Given data, determines if it should be sent as a stream.\"\"\"\n+ is_iterable = getattr(data, '__iter__', False)\n+ is_io_type = not isinstance(data, (basestring, list, tuple, collections.Mapping))\n+ return is_iterable and is_io_type" }, { "filename": "tests/test_requests.py", "status": "modified", "additions": 56, "deletions": 1, "changes": 57, "patch": "@@ -25,7 +25,7 @@\n from requests.exceptions import (\n ConnectionError, ConnectTimeout, InvalidScheme, InvalidURL,\n MissingScheme, ReadTimeout, Timeout, RetryError, TooManyRedirects,\n- ProxyError, InvalidHeader, UnrewindableBodyError)\n+ ProxyError, InvalidHeader, UnrewindableBodyError, InvalidBodyError)\n from requests.models import PreparedRequest\n from requests.structures import CaseInsensitiveDict\n from requests.sessions import SessionRedirectMixin\n@@ -1924,6 +1924,61 @@ def test_chunked_upload_does_not_set_content_length_header(self, httpbin):\n assert 'Transfer-Encoding' in prepared_request.headers\n assert 'Content-Length' not in prepared_request.headers\n \n+ def test_chunked_upload_with_manually_set_content_length_header_raises_error(self, httpbin):\n+ \"\"\"Ensure that if a user manually sets a content length header, when\n+ the data is chunked, that an InvalidHeader error is raised.\n+ \"\"\"\n+ data = (i for i in [b'a', b'b', b'c']) \n+ url = httpbin('post')\n+ with pytest.raises(InvalidHeader):\n+ r = requests.post(url, data=data, headers={'Content-Length': 'foo'})\n+\n+ def test_content_length_with_manually_set_transfer_encoding_raises_error(self, httpbin):\n+ \"\"\"Ensure that if a user manually sets a Transfer-Encoding header when\n+ data is not chunked that an InvalidHeader error is raised.\n+ \"\"\"\n+ data = 'test data'\n+ url = httpbin('post')\n+ with pytest.raises(InvalidHeader):\n+ r = requests.post(url, data=data, headers={'Transfer-Encoding': 'chunked'})\n+\n+ def test_null_body_does_not_raise_error(self, httpbin):\n+ url = httpbin('post')\n+ try:\n+ requests.post(url, data=None)\n+ except InvalidHeader:\n+ pytest.fail('InvalidHeader error raised unexpectedly.')\n+\n+ [USER_REDACTED].mark.parametrize(\n+ 'body, expected', (\n+ (None, ('Content-Length', '0')),\n+ ('test_data', ('Content-Length', '9')),\n+ (io.BytesIO(b'test_data'), ('Content-Length', '9')),\n+ (StringIO.StringIO(''), ('Transfer-Encoding', 'chunked'))\n+ ))\n+ def test_prepare_content_length(self, httpbin, body, expected):\n+ \"\"\"Test prepare_content_length creates expected header.\"\"\"\n+ prep = requests.PreparedRequest()\n+ prep.headers = {}\n+ prep.method = 'POST'\n+\n+ # [NAME_REDACTED] is set appropriately.\n+ key, value = expected\n+ prep.prepare_content_length(body)\n+ assert prep.headers[key] == value\n+\n+ def test_prepare_content_length_with_bad_body(self, httpbin):\n+ \"\"\"Test prepare_content_length raises exception with unsendable body.\"\"\"\n+ # Initialize minimum required PreparedRequest.\n+ prep = requests.PreparedRequest()\n+ prep.headers = {}\n+ prep.method = 'POST'\n+\n+ with pytest.raises(InvalidBodyError) as e:\n+ # Send object that isn't iterable and has no accessible content.\n+ prep.prepare_content_length(object())\n+ assert \"Non-null body must have length or be streamable.\" in str(e)\n+\n def test_custom_redirect_mixin(self, httpbin):\n \"\"\"Tests a custom mixin to overwrite ``get_redirect_target``." } ], "reviews": [ { "id": 24364360, "user": "user_dbf2a999bd6d", "state": "COMMENTED", "body": null, "submitted_at": "2017-02-28T23:05:35+00:00" }, { "id": 24474585, "user": "user_f068c71fd303", "state": "CHANGES_REQUESTED", "body": "Cool, so this mostly looks good. Just a few notes. =)", "submitted_at": "2017-03-01T13:27:10+00:00" }, { "id": 24488041, "user": "user_dbf2a999bd6d", "state": "COMMENTED", "body": null, "submitted_at": "2017-03-01T14:24:14+00:00" }, { "id": 24488238, "user": "user_dbf2a999bd6d", "state": "COMMENTED", "body": null, "submitted_at": "2017-03-01T14:25:01+00:00" }, { "id": 24506663, "user": "user_f068c71fd303", "state": "COMMENTED", "body": null, "submitted_at": "2017-03-01T15:33:40+00:00" }, { "id": 24528275, "user": "user_dbf2a999bd6d", "state": "COMMENTED", "body": null, "submitted_at": "2017-03-01T16:49:26+00:00" }, { "id": 24536017, "user": "user_f068c71fd303", "state": "CHANGES_REQUESTED", "body": "Cool, this looks good. Can we get a changelog entry for it explaining the change thoroughly? This is the kind of thing that will trip people up in migration. :grin:\n\nThen I should be ready to give you a green tick.", "submitted_at": "2017-03-01T17:19:30+00:00" }, { "id": 24567137, "user": "user_f068c71fd303", "state": "CHANGES_REQUESTED", "body": null, "submitted_at": "2017-03-01T19:27:14+00:00" }, { "id": 24570734, "user": "user_dbf2a999bd6d", "state": "COMMENTED", "body": null, "submitted_at": "2017-03-01T19:42:16+00:00" }, { "id": 24707986, "user": "user_f068c71fd303", "state": "CHANGES_REQUESTED", "body": "Looks like you committed a `.swo` file. :cry:", "submitted_at": "2017-03-02T11:28:31+00:00" }, { "id": 24745278, "user": "user_f068c71fd303", "state": "APPROVED", "body": "Cool, this looks good to me. Thanks [USER_REDACTED]! :sparkles: :cake: :sparkles:", "submitted_at": "2017-03-02T14:40:30+00:00" } ], "review_comments": [ { "id": 103574046, "user": "user_dbf2a999bd6d", "body": "Only minor note I have here is we've added an `InvalidHeader` exception since this PR was created which could likely be used instead of this. I didn't want to tweak the original work too much in the initial pass though. Thoughts?", "path": "requests/exceptions.py", "line": null, "side": "RIGHT", "created_at": "2017-02-28T23:05:35+00:00" }, { "id": 103681197, "user": "user_f068c71fd303", "body": "Yeah, might be better to use that new exception, or possibly to make this a child exception of `InvalidHeader`.", "path": "requests/exceptions.py", "line": null, "side": "RIGHT", "created_at": "2017-03-01T13:21:30+00:00" }, { "id": 103681257, "user": "user_f068c71fd303", "body": "I don't think this is ever imported, is it?", "path": "requests/models.py", "line": 524, "side": "RIGHT", "created_at": "2017-03-01T13:21:57+00:00" }, { "id": 103681627, "user": "user_f068c71fd303", "body": "Did we need to get rid of this comment?", "path": "requests/models.py", "line": null, "side": "RIGHT", "created_at": "2017-03-01T13:24:05+00:00" }, { "id": 103693788, "user": "user_dbf2a999bd6d", "body": "Nope, I think that was probably a bad merge conflict resolution.", "path": "requests/models.py", "line": null, "side": "RIGHT", "created_at": "2017-03-01T14:24:14+00:00" }, { "id": 103693989, "user": "user_dbf2a999bd6d", "body": "It wasn't but it should be added now. Thoughts on adding a test to ensure hitting this block?", "path": "requests/models.py", "line": 524, "side": "RIGHT", "created_at": "2017-03-01T14:25:01+00:00" }, { "id": 103711645, "user": "user_f068c71fd303", "body": "I think we should do that, yeah. Ideally we'd cover all of this logic if we can.", "path": "requests/models.py", "line": 524, "side": "RIGHT", "created_at": "2017-03-01T15:33:40+00:00" }, { "id": 103731853, "user": "user_dbf2a999bd6d", "body": "Alright, the other tests from #3338 cover the other two cases according to pytest. We now have 100% coverage over `prepare_content_length` with the new test. This should be set after the build completes, unless you have further notes.", "path": "requests/models.py", "line": 524, "side": "RIGHT", "created_at": "2017-03-01T16:49:26+00:00" }, { "id": 103768291, "user": "user_f068c71fd303", "body": "We probably don't need this paragraph. 😎", "path": "3.0-HISTORY.rst", "line": null, "side": "RIGHT", "created_at": "2017-03-01T19:27:10+00:00" }, { "id": 103771639, "user": "user_dbf2a999bd6d", "body": "A little too thorough I guess 😉\n\nUpdated.", "path": "3.0-HISTORY.rst", "line": null, "side": "RIGHT", "created_at": "2017-03-01T19:42:16+00:00" } ], "meta": { "languages": [ "py", "rst" ], "touches_tests": true, "review_state_summary": { "COMMENTED": 6, "CHANGES_REQUESTED": 4, "APPROVED": 1 }, "meaningful_comment_count": 10, "has_approval": true, "has_changes_requested": true, "total_review_comments": 10 } } { "_id": "b6feb7f4157b70cf", "_schema_version": "1.0", "_cleaned_at": "2026-02-12T07:46:52.085742+00:00", "repo": "psf/requests", "repo_url": "https://github.com/psf/requests", "license_name": "Apache License 2.0", "license_spdx": "Apache-2.0", "pr_number": 3885, "title": "Cache proxy bypass", "body": "Added simple cache over `urllib.proxy_bypass` to remedy #2988. Holds on to entries for a minute. Once it reaches its max size, will evict the first entry that is the oldest.\n\nAdded tests over the structure, did not add a test that `should_bypass_proxies` invokes the cache.\n\nThis is my first pull request; please let me know if I've overlooked something.\n\nAdditionally, when I check out master, run `make coverage` in pipenv, the test named 'TestRequests.test_proxy_error' fails. This is still the only failing test when I use my branch. The error is `ConnectionError: ('Connection aborted.', BadStatusLine(\"''\",))`. Is there some additional setup I need to do to run the test suite?", "author": "user_665a4a36e33a", "created_at": "2017-02-22T04:21:30+00:00", "merged_at": "2017-02-27T08:56:44+00:00", "base_branch": "master", "head_branch": "cache_proxy_bypass", "additions": 175, "deletions": 3, "changed_files": 4, "files": [ { "filename": "AUTHORS.rst", "status": "modified", "additions": 1, "deletions": 0, "changes": 1, "patch": "@@ -178,4 +178,5 @@ Patches and Suggestions\n - [NAME_REDACTED] <[EMAIL_REDACTED]> ([CONTRIBUTOR_REDACTED])\n - [NAME_REDACTED] ([CONTRIBUTOR_REDACTED])\n - [NAME_REDACTED] ([CONTRIBUTOR_REDACTED])\n+- [NAME_REDACTED] ([CONTRIBUTOR_REDACTED])" }, { "filename": "requests/structures.py", "status": "modified", "additions": 89, "deletions": 0, "changes": 89, "patch": "@@ -8,9 +8,12 @@\n \"\"\"\n \n import collections\n+import time\n \n from .compat import OrderedDict\n \n+current_time = getattr(time, 'monotonic', time.time)\n+\n \n class CaseInsensitiveDict(collections.MutableMapping):\n \"\"\"A case-insensitive ``dict``-like object.\n@@ -103,3 +106,89 @@ def __getitem__(self, key):\n \n def get(self, key, default=None):\n return self.__dict__.get(key, default)\n+\n+\n+class TimedCacheManaged(object):\n+ \"\"\"\n+ Wrap a function call in a timed cache\n+ \"\"\"\n+ def __init__(self, fnc):\n+ self.fnc = fnc\n+ self.cache = TimedCache()\n+\n+ def __call__(self, *args, **kwargs):\n+ key = args[0]\n+ found = None\n+ try:\n+ found = self.cache[key]\n+ except KeyError:\n+ found = self.fnc(key, **kwargs)\n+ self.cache[key] = found\n+\n+ return found\n+\n+\n+class TimedCache(collections.MutableMapping):\n+ \"\"\"\n+ Evicts entries after expiration_secs. If none are expired and maxlen is hit,\n+ will evict the oldest cached entry\n+ \"\"\"\n+ def __init__(self, maxlen=32, expiration_secs=60):\n+ \"\"\"\n+ :param maxlen: most number of entries to hold on to\n+ :param expiration_secs: the number of seconds to hold on\n+ to entries\n+ \"\"\"\n+ self.maxlen = maxlen\n+ self.expiration_secs = expiration_secs\n+ self._dict = OrderedDict()\n+\n+ def __repr__(self):\n+ return '' % \\\n+ (self.maxlen, len(self._dict), self.expiration_secs)\n+\n+ def __iter__(self):\n+ return map(lambda kv: (kv[0], kv[1][1]), self._dict.items()).__iter__()\n+\n+ def __delitem__(self, item):\n+ return self._dict.__delitem__(item)\n+\n+ def __getitem__(self, key):\n+ \"\"\"\n+ Look up an item in the cache. If the item\n+ has already expired, it will be invalidated and not returned\n+\n+ :param key: which entry to look up\n+ :return: the value in the cache, or None\n+ \"\"\"\n+ occurred, value = self._dict[key]\n+ now = int(current_time())\n+\n+ if now - occurred > self.expiration_secs:\n+ del self._dict[key]\n+ raise KeyError\n+ else:\n+ return value\n+\n+ def __setitem__(self, key, value):\n+ \"\"\"\n+ Locates the value at lookup key, if cache is full, will evict the\n+ oldest entry\n+\n+ :param key: the key to search the cache for\n+ :param value: the value to be added to the cache\n+ \"\"\"\n+ now = int(current_time())\n+\n+ while len(self._dict) >= self.maxlen:\n+ self._dict.popitem(last=False)\n+\n+ return self._dict.__setitem__(key, (now, value))\n+\n+ def __len__(self):\n+ \"\"\":return: the length of the cache\"\"\"\n+ return len(self._dict)\n+\n+ def clear(self):\n+ \"\"\"Clears the cache\"\"\"\n+ return self._dict.clear()" }, { "filename": "requests/utils.py", "status": "modified", "additions": 12, "deletions": 2, "changes": 14, "patch": "@@ -28,7 +28,7 @@\n quote, urlparse, bytes, str, OrderedDict, unquote, getproxies,\n proxy_bypass, urlunparse, basestring, integer_types)\n from .cookies import RequestsCookieJar, cookiejar_from_dict\n-from .structures import CaseInsensitiveDict\n+from .structures import CaseInsensitiveDict, TimedCache, TimedCacheManaged\n from .exceptions import (\n InvalidURL, InvalidHeader, FileModeWarning, UnrewindableBodyError)\n \n@@ -579,6 +579,16 @@ def set_environ(env_name, value):\n os.environ[env_name] = old_value\n \n \n+[USER_REDACTED]\n+def _proxy_bypass_cached(netloc):\n+ \"\"\"\n+ Looks for netloc in the cache, if not found, will call proxy_bypass\n+ for the netloc and store its result in the cache\n+\n+ :rtype: bool\n+ \"\"\"\n+ return proxy_bypass(netloc)\n+\n def should_bypass_proxies(url, no_proxy):\n \"\"\"\n Returns whether we should bypass proxies or not.\n@@ -626,7 +636,7 @@ def should_bypass_proxies(url, no_proxy):\n # legitimate problems.\n with set_environ('no_proxy', no_proxy_arg):\n try:\n- bypass = proxy_bypass(netloc)\n+ bypass = _proxy_bypass_cached(netloc)\n except (TypeError, socket.gaierror):\n bypass = False" }, { "filename": "tests/test_structures.py", "status": "modified", "additions": 73, "deletions": 1, "changes": 74, "patch": "@@ -2,7 +2,7 @@\n \n import pytest\n \n-from requests.structures import CaseInsensitiveDict, LookupDict\n+from requests.structures import CaseInsensitiveDict, LookupDict, TimedCache, TimedCacheManaged\n \n \n class TestCaseInsensitiveDict:\n@@ -74,3 +74,75 @@ def test_getitem(self, key, value):\n [USER_REDACTED]_item_parameters\n def test_get(self, key, value):\n assert self.lookup_dict.get(key) == value\n+\n+\n+class TestTimedCache(object):\n+ [USER_REDACTED].fixture(autouse=True)\n+ def setup(self):\n+ self.any_value = 'some value'\n+ self.expiration_secs = 60\n+ self.cache = TimedCache(expiration_secs=self.expiration_secs)\n+ yield\n+ self.cache.clear()\n+\n+ def test_get(self):\n+ self.cache['a'] = self.any_value\n+ assert self.cache['a'] is self.any_value\n+\n+ def test_repr(self):\n+ repr = str(self.cache)\n+ assert repr == ''\n+\n+ def test_get_expired_item(self, mocker):\n+ self.cache = TimedCache(maxlen=1, expiration_secs=self.expiration_secs)\n+\n+ mocker.patch('requests.structures.current_time', lambda: 0)\n+ self.cache['a'] = self.any_value\n+ mocker.patch('requests.structures.current_time', lambda: self.expiration_secs + 1)\n+ assert self.cache.get('a') is None\n+\n+ def test_evict_first_entry_when_full(self, mocker):\n+ self.cache = TimedCache(maxlen=2, expiration_secs=2)\n+ mocker.patch('requests.structures.current_time', lambda: 0)\n+ self.cache['a'] = self.any_value\n+ mocker.patch('requests.structures.current_time', lambda: 1)\n+ self.cache['b'] = self.any_value\n+ mocker.patch('requests.structures.current_time', lambda: 3)\n+ self.cache['c'] = self.any_value\n+ assert len(self.cache) is 2\n+ with pytest.raises(KeyError, message='Expected key not found'):\n+ self.cache['a']\n+ assert self.cache['b'] is self.any_value\n+ assert self.cache['c'] is self.any_value\n+\n+ def test_delete_item_removes_item(self):\n+ self.cache['a'] = self.any_value\n+ del self.cache['a']\n+ with pytest.raises(KeyError, message='Expected key not found'):\n+ self.cache['a']\n+\n+ def test_iterating_hides_timestamps(self):\n+ self.cache['a'] = 1\n+ self.cache['b'] = 2\n+ expected = [('a', 1), ('b', 2)]\n+ actual = [(key, val) for key, val in self.cache]\n+ assert expected == actual\n+\n+\n+class TestTimedCacheManagedDecorator(object):\n+ def test_caches_repeated_calls(self, mocker):\n+ mocker.patch('requests.structures.current_time', lambda: 0)\n+\n+ nonlocals = {'value': 0}\n+\n+ [USER_REDACTED]\n+ def some_method(x):\n+ nonlocals['value'] = nonlocals['value'] + x\n+ return nonlocals['value']\n+\n+ first_result = some_method(1)\n+ assert first_result is 1\n+ second_result = some_method(1)\n+ assert second_result is 1\n+ third_result = some_method(2)\n+ assert third_result is 3" } ], "reviews": [ { "id": 23159215, "user": "user_f068c71fd303", "state": "CHANGES_REQUESTED", "body": "Cool, so this is a good start! I've left some notes inline in the diff.", "submitted_at": "2017-02-22T08:49:24+00:00" }, { "id": 23282529, "user": "user_665a4a36e33a", "state": "COMMENTED", "body": null, "submitted_at": "2017-02-22T17:37:08+00:00" }, { "id": 23282597, "user": "user_665a4a36e33a", "state": "COMMENTED", "body": null, "submitted_at": "2017-02-22T17:37:24+00:00" }, { "id": 23282629, "user": "user_665a4a36e33a", "state": "COMMENTED", "body": null, "submitted_at": "2017-02-22T17:37:34+00:00" }, { "id": 23282700, "user": "user_f068c71fd303", "state": "COMMENTED", "body": null, "submitted_at": "2017-02-22T17:37:53+00:00" }, { "id": 23282774, "user": "user_665a4a36e33a", "state": "COMMENTED", "body": null, "submitted_at": "2017-02-22T17:38:10+00:00" }, { "id": 23283971, "user": "user_665a4a36e33a", "state": "COMMENTED", "body": null, "submitted_at": "2017-02-22T17:42:50+00:00" }, { "id": 23284791, "user": "user_665a4a36e33a", "state": "COMMENTED", "body": null, "submitted_at": "2017-02-22T17:46:14+00:00" }, { "id": 23284980, "user": "user_665a4a36e33a", "state": "COMMENTED", "body": null, "submitted_at": "2017-02-22T17:47:00+00:00" }, { "id": 23426819, "user": "user_f068c71fd303", "state": "CHANGES_REQUESTED", "body": "Cool, this is generally looking really good: substantial progress! I've written some more notes.", "submitted_at": "2017-02-23T09:15:20+00:00" }, { "id": 23546519, "user": "user_665a4a36e33a", "state": "COMMENTED", "body": null, "submitted_at": "2017-02-23T18:11:55+00:00" }, { "id": 23546632, "user": "user_665a4a36e33a", "state": "COMMENTED", "body": null, "submitted_at": "2017-02-23T18:12:25+00:00" }, { "id": 23546891, "user": "user_665a4a36e33a", "state": "COMMENTED", "body": null, "submitted_at": "2017-02-23T18:13:29+00:00" }, { "id": 23547054, "user": "user_665a4a36e33a", "state": "COMMENTED", "body": null, "submitted_at": "2017-02-23T18:14:12+00:00" }, { "id": 23547141, "user": "user_665a4a36e33a", "state": "COMMENTED", "body": null, "submitted_at": "2017-02-23T18:14:36+00:00" }, { "id": 23551581, "user": "user_665a4a36e33a", "state": "COMMENTED", "body": null, "submitted_at": "2017-02-23T18:33:43+00:00" }, { "id": 23586495, "user": "user_f068c71fd303", "state": "CHANGES_REQUESTED", "body": "Awesome, really close now! A couple of minor stylistic notes and one request to expand a test slightly and we're good to go!", "submitted_at": "2017-02-23T21:10:55+00:00" }, { "id": 23588815, "user": "user_665a4a36e33a", "state": "COMMENTED", "body": null, "submitted_at": "2017-02-23T21:16:03+00:00" }, { "id": 23588916, "user": "user_665a4a36e33a", "state": "COMMENTED", "body": null, "submitted_at": "2017-02-23T21:16:34+00:00" }, { "id": 23588958, "user": "user_665a4a36e33a", "state": "COMMENTED", "body": null, "submitted_at": "2017-02-23T21:16:44+00:00" }, { "id": 23598217, "user": "user_f068c71fd303", "state": "CHANGES_REQUESTED", "body": "Sorry, I missed some extra whitespace. 😔 Let's clear all of that up and then we will be good to go. 👍", "submitted_at": "2017-02-23T21:57:56+00:00" }, { "id": 23604227, "user": "user_f068c71fd303", "state": "APPROVED", "body": "Cool, I'm happy with this! As this is a big-ish change in functionality, I'd like to give [USER_REDACTED] a chance to review before I merge, but if he doesn't get time I'll merge it Monday. Great work [USER_REDACTED]!", "submitted_at": "2017-02-23T22:22:16+00:00" }, { "id": 25124946, "user": "user_0fa58b6f3572", "state": "COMMENTED", "body": "I'll submit these updates in a separate pull request", "submitted_at": "2017-03-04T15:02:54+00:00" } ], "review_comments": [ { "id": 102406393, "user": "user_f068c71fd303", "body": "So, this is basically a `collections.MutableMapping`! We should make it *actually* be one, because that gives us a number of handy-dandy convenience methods.", "path": "requests/structures.py", "line": null, "side": "RIGHT", "created_at": "2017-02-22T08:33:10+00:00" }, { "id": 102406530, "user": "user_f068c71fd303", "body": "So, generally speaking it is better to implement `get` in terms of `__getitem__` than the other way around. `__getitem__` should almost always maintain dict-like behaviour of raising `KeyError` if the entry is not present, rather than returning `None`. The core concern here is that it needs to be possible to distinguish between \"key not present in dictionary\" and \"key present with a value of `None`\".", "path": "requests/structures.py", "line": null, "side": "RIGHT", "created_at": "2017-02-22T08:34:08+00:00" }, { "id": 102406809, "user": "user_f068c71fd303", "body": "This logic is wrong. Happily, it doesn't matter: if you make this a subclass of `MutableMapping` you don't actually need to implement this method at all, we get it for free.", "path": "requests/structures.py", "line": null, "side": "RIGHT", "created_at": "2017-02-22T08:35:42+00:00" }, { "id": 102407049, "user": "user_f068c71fd303", "body": "So, this is a problem.\n\n*If possible* we'd like to use `time.monotonic` instead, as `time.time` can go backwards. So I think in this module you'll need to feature detect on import to see whether `time.monotonic` is present and to prefer it if it is.", "path": "requests/structures.py", "line": null, "side": "RIGHT", "created_at": "2017-02-22T08:37:18+00:00" }, { "id": 102407154, "user": "user_f068c71fd303", "body": "Same note about monotonic time.", "path": "requests/structures.py", "line": null, "side": "RIGHT", "created_at": "2017-02-22T08:37:55+00:00" }, { "id": 102407206, "user": "user_f068c71fd303", "body": "You're wrapping this paragraph *very* short. Feel free to go all the way out to 89 columns!", "path": "requests/structures.py", "line": null, "side": "RIGHT", "created_at": "2017-02-22T08:38:16+00:00" }, { "id": 102407275, "user": "user_f068c71fd303", "body": "While we're here, can you add a blank line separating the paragraph blurb from the `:param:` directives?", "path": "requests/structures.py", "line": null, "side": "RIGHT", "created_at": "2017-02-22T08:38:40+00:00" }, { "id": 102407489, "user": "user_f068c71fd303", "body": "This complete search can probably be avoided by [NAME_REDACTED] `OrderedDict`, can't it? urllib3 includes one that works on all the Python versions we support, so you can import that and use it as the base implementation to save ourselves this iterative walk.", "path": "requests/structures.py", "line": null, "side": "RIGHT", "created_at": "2017-02-22T08:40:05+00:00" }, { "id": 102407689, "user": "user_f068c71fd303", "body": "My suggestion is that this be reimplemented as a generic decorator, rather than written to specifically handle `proxy_bypass`. That way we get a much easier time of testing the timed cache and all the relevant code. =)", "path": "requests/utils.py", "line": null, "side": "RIGHT", "created_at": "2017-02-22T08:41:31+00:00" }, { "id": 102408709, "user": "user_f068c71fd303", "body": "Let's avoid making this an old-style class by putting `(object)` as well.", "path": "tests/test_structures.py", "line": null, "side": "RIGHT", "created_at": "2017-02-22T08:47:52+00:00" }, { "id": 102524217, "user": "user_665a4a36e33a", "body": "Thanks. To clarify, you're saying if `time.monotonic` is not present, it's ok to fall back to `time.time`?", "path": "requests/structures.py", "line": null, "side": "RIGHT", "created_at": "2017-02-22T17:37:08+00:00" }, { "id": 102524272, "user": "user_665a4a36e33a", "body": "Will update.", "path": "requests/structures.py", "line": null, "side": "RIGHT", "created_at": "2017-02-22T17:37:24+00:00" }, { "id": 102524304, "user": "user_665a4a36e33a", "body": "Will update.", "path": "requests/structures.py", "line": null, "side": "RIGHT", "created_at": "2017-02-22T17:37:33+00:00" }, { "id": 102524405, "user": "user_f068c71fd303", "body": "Yes.", "path": "requests/structures.py", "line": null, "side": "RIGHT", "created_at": "2017-02-22T17:37:52+00:00" }, { "id": 102524477, "user": "user_665a4a36e33a", "body": "Will update.", "path": "tests/test_structures.py", "line": null, "side": "RIGHT", "created_at": "2017-02-22T17:38:10+00:00" }, { "id": 102525622, "user": "user_665a4a36e33a", "body": "Will update to have TimedCache inherit `collections.MutableMapping`", "path": "requests/structures.py", "line": null, "side": "RIGHT", "created_at": "2017-02-22T17:42:50+00:00" }, { "id": 102526425, "user": "user_665a4a36e33a", "body": "Will update.", "path": "requests/structures.py", "line": null, "side": "RIGHT", "created_at": "2017-02-22T17:46:14+00:00" }, { "id": 102526604, "user": "user_665a4a36e33a", "body": "Will replace `self._dict` with an `OrderedDict`.", "path": "requests/structures.py", "line": null, "side": "RIGHT", "created_at": "2017-02-22T17:47:00+00:00" }, { "id": 102666805, "user": "user_f068c71fd303", "body": "You can have a slightly wider docstring than this! :grin:", "path": "requests/structures.py", "line": null, "side": "RIGHT", "created_at": "2017-02-23T09:06:25+00:00" }, { "id": 102666915, "user": "user_f068c71fd303", "body": "This should be `TimedCache`, and it should also provide the `expiration_secs`.", "path": "requests/structures.py", "line": null, "side": "RIGHT", "created_at": "2017-02-23T09:07:05+00:00" }, { "id": 102667271, "user": "user_f068c71fd303", "body": "You don't need to implement this: `collections.MutableMapping` will do it for you.", "path": "requests/structures.py", "line": null, "side": "RIGHT", "created_at": "2017-02-23T09:09:23+00:00" }, { "id": 102667469, "user": "user_f068c71fd303", "body": "This can be more cleanly expressed as:\n\n```python\nwhile len(self._dict) >= self.maxlen:\n self._dict.popitem(last=False)\n```", "path": "requests/structures.py", "line": null, "side": "RIGHT", "created_at": "2017-02-23T09:10:33+00:00" }, { "id": 102667700, "user": "user_f068c71fd303", "body": "This one we also technically get for free from `MutableMapping`, but in this case we can do it much faster than the generic implementation so I'm happy to have this override.", "path": "requests/structures.py", "line": 194, "side": "RIGHT", "created_at": "2017-02-23T09:11:54+00:00" }, { "id": 102668250, "user": "user_f068c71fd303", "body": "Heh, so this is a good test, but it mostly tests implementation details. For this, it's enough to just mock out the time and then write a small function that constantly returns an incrementing value, then wrap it in the decorator and use the timer to demonstrate the behaviour.\n\nGenerally speaking, avoiding mocks is a good thing wherever we can. =)", "path": "tests/test_structures.py", "line": null, "side": "RIGHT", "created_at": "2017-02-23T09:14:49+00:00" }, { "id": 102778992, "user": "user_665a4a36e33a", "body": "Fixed", "path": "requests/structures.py", "line": null, "side": "RIGHT", "created_at": "2017-02-23T18:11:55+00:00" }, { "id": 102779101, "user": "user_665a4a36e33a", "body": "Fixed", "path": "requests/structures.py", "line": null, "side": "RIGHT", "created_at": "2017-02-23T18:12:25+00:00" }, { "id": 102779339, "user": "user_665a4a36e33a", "body": "Fixed", "path": "requests/structures.py", "line": null, "side": "RIGHT", "created_at": "2017-02-23T18:13:29+00:00" }, { "id": 102779491, "user": "user_665a4a36e33a", "body": "Agreed. Updated.", "path": "requests/structures.py", "line": null, "side": "RIGHT", "created_at": "2017-02-23T18:14:12+00:00" }, { "id": 102779570, "user": "user_665a4a36e33a", "body": "Good to know. I've left the override intact.", "path": "requests/structures.py", "line": 194, "side": "RIGHT", "created_at": "2017-02-23T18:14:36+00:00" }, { "id": 102783950, "user": "user_665a4a36e33a", "body": "Ok. I've re-made the test more along these lines. Let me know what you think.", "path": "tests/test_structures.py", "line": null, "side": "RIGHT", "created_at": "2017-02-23T18:33:43+00:00" }, { "id": 102817531, "user": "user_f068c71fd303", "body": "Really minor nit, we don't need this blank line.", "path": "requests/structures.py", "line": null, "side": "RIGHT", "created_at": "2017-02-23T21:05:35+00:00" }, { "id": 102817889, "user": "user_f068c71fd303", "body": "Same again, don't need this blank line.", "path": "requests/utils.py", "line": null, "side": "RIGHT", "created_at": "2017-02-23T21:07:24+00:00" }, { "id": 102817964, "user": "user_f068c71fd303", "body": "This again can be flowed out to column 79 as well.", "path": "requests/utils.py", "line": null, "side": "RIGHT", "created_at": "2017-02-23T21:07:48+00:00" }, { "id": 102818535, "user": "user_f068c71fd303", "body": "Should also check that a different argument doesn't return a cached value.", "path": "tests/test_structures.py", "line": 146, "side": "RIGHT", "created_at": "2017-02-23T21:10:24+00:00" }, { "id": 102819787, "user": "user_665a4a36e33a", "body": "Removed", "path": "requests/structures.py", "line": null, "side": "RIGHT", "created_at": "2017-02-23T21:16:03+00:00" }, { "id": 102819885, "user": "user_665a4a36e33a", "body": "Fixed", "path": "requests/utils.py", "line": null, "side": "RIGHT", "created_at": "2017-02-23T21:16:34+00:00" }, { "id": 102819920, "user": "user_665a4a36e33a", "body": "Removed", "path": "requests/utils.py", "line": null, "side": "RIGHT", "created_at": "2017-02-23T21:16:44+00:00" }, { "id": 102828765, "user": "user_f068c71fd303", "body": "This one.", "path": "requests/structures.py", "line": null, "side": "RIGHT", "created_at": "2017-02-23T21:54:49+00:00" }, { "id": 102828822, "user": "user_f068c71fd303", "body": "This one", "path": "requests/structures.py", "line": null, "side": "RIGHT", "created_at": "2017-02-23T21:55:07+00:00" }, { "id": 102828876, "user": "user_f068c71fd303", "body": "This one", "path": "requests/structures.py", "line": null, "side": "RIGHT", "created_at": "2017-02-23T21:55:24+00:00" }, { "id": 102828935, "user": "user_f068c71fd303", "body": "This one", "path": "requests/structures.py", "line": null, "side": "RIGHT", "created_at": "2017-02-23T21:55:40+00:00" }, { "id": 102828996, "user": "user_f068c71fd303", "body": "This one", "path": "tests/test_structures.py", "line": null, "side": "RIGHT", "created_at": "2017-02-23T21:56:00+00:00" }, { "id": 102829060, "user": "user_f068c71fd303", "body": "This one", "path": "tests/test_structures.py", "line": null, "side": "RIGHT", "created_at": "2017-02-23T21:56:19+00:00" }, { "id": 102829116, "user": "user_f068c71fd303", "body": "This one.", "path": "tests/test_structures.py", "line": null, "side": "RIGHT", "created_at": "2017-02-23T21:56:33+00:00" }, { "id": 104289400, "user": "user_0fa58b6f3572", "body": "I'm curious why we don't just build a generator here.\n\n1. `map()` is slow and `lambda` s are slow. This intentional on Guido's part.\n2. Calling `__iter__` is really poor form.\n3. This would be far simpler and easier to read as\n\n```py\nreturn ((key, value[1]) for key, value in self._dict.items())\n```", "path": "requests/structures.py", "line": 151, "side": "RIGHT", "created_at": "2017-03-04T14:55:32+00:00" }, { "id": 104289439, "user": "user_0fa58b6f3572", "body": "Why not write this as:\n\n```py\ndel self._dict[item]\n```\n\n`__delitem__` doesn't return anything so there's no need to worry about returning something here. And it would avoid calling the dunder method directly, which I'll repeat, is poor form.", "path": "requests/structures.py", "line": 154, "side": "RIGHT", "created_at": "2017-03-04T14:56:52+00:00" }, { "id": 104289476, "user": "user_0fa58b6f3572", "body": "This should raise a `KeyError` with the key as an argument, e.g., `KeyError(key)`.", "path": "requests/structures.py", "line": 169, "side": "RIGHT", "created_at": "2017-03-04T14:57:52+00:00" }, { "id": 104289545, "user": "user_0fa58b6f3572", "body": "Again, `__setitem__` doesn't return anything. This should just be\n\n```py\nself._dict[key] = (now, value)\n```\n\nThere's no need to obfuscate any of this.", "path": "requests/structures.py", "line": 186, "side": "RIGHT", "created_at": "2017-03-04T14:58:54+00:00" } ], "meta": { "languages": [ "py", "rst" ], "touches_tests": true, "review_state_summary": { "CHANGES_REQUESTED": 4, "COMMENTED": 18, "APPROVED": 1 }, "meaningful_comment_count": 34, "has_approval": true, "has_changes_requested": true, "total_review_comments": 48 } } { "_id": "3ed62f2316562c68", "_schema_version": "1.0", "_cleaned_at": "2026-02-12T07:46:52.101366+00:00", "repo": "psf/requests", "repo_url": "https://github.com/psf/requests", "license_name": "Apache License 2.0", "license_spdx": "Apache-2.0", "pr_number": 3874, "title": "variable name consistency", "body": "Just need to clean up a few variable names.", "author": "user_dbf2a999bd6d", "created_at": "2017-02-14T16:27:56+00:00", "merged_at": "2017-02-21T19:04:25+00:00", "base_branch": "proposed/3.0.0", "head_branch": "merge_cleanup", "additions": 5, "deletions": 5, "changed_files": 1, "files": [ { "filename": "requests/sessions.py", "status": "modified", "additions": 5, "deletions": 5, "changes": 10, "patch": "@@ -87,13 +87,13 @@ def merge_hooks(request_hooks, session_hooks, dict_class=OrderedDict):\n \n \n class SessionRedirectMixin(object):\n- def get_redirect_target(self, resp):\n+ def get_redirect_target(self, response):\n \"\"\"Receives a Response. Returns a redirect URI or ``None``\"\"\"\n- if resp.is_redirect:\n+ if response.is_redirect:\n if not is_valid_location(response):\n raise InvalidHeader('Response contains multiple Location headers. '\n 'Unable to perform redirect.')\n- return resp.headers['location']\n+ return response.headers['location']\n return None\n \n def resolve_redirects(self, response, request, stream=False, timeout=None,\n@@ -113,8 +113,8 @@ def resolve_redirects(self, response, request, stream=False, timeout=None,\n \n # Update history and keep track of redirects.\n # response.history must ignore the original request in this loop\n- hist.append(response)\n- response.history = hist[1:]\n+ history.append(response)\n+ response.history = history[1:]\n \n try:\n response.content # Consume socket so it can be released" } ], "reviews": [ { "id": 21796914, "user": "user_f068c71fd303", "state": "CHANGES_REQUESTED", "body": "One small note.", "submitted_at": "2017-02-14T16:28:57+00:00" }, { "id": 21797430, "user": "user_dbf2a999bd6d", "state": "COMMENTED", "body": null, "submitted_at": "2017-02-14T16:30:35+00:00" }, { "id": 21798129, "user": "user_0fa58b6f3572", "state": "APPROVED", "body": "I've requested Kenneth's input here because I know he has opinions but I've frankly forgotten them on this topic.", "submitted_at": "2017-02-14T16:33:12+00:00" }, { "id": 21798152, "user": "user_f068c71fd303", "state": "APPROVED", "body": "I'm definitely happy with this adjustment.", "submitted_at": "2017-02-14T16:33:16+00:00" }, { "id": 23042273, "user": "user_36df932e8b7a", "state": "COMMENTED", "body": "👍", "submitted_at": "2017-02-21T19:05:06+00:00" } ], "review_comments": [ { "id": 101078144, "user": "user_f068c71fd303", "body": "Let's call the other instances `history`, rather than call this `hist`.", "path": "requests/sessions.py", "line": null, "side": "RIGHT", "created_at": "2017-02-14T16:28:52+00:00" }, { "id": 101078636, "user": "user_dbf2a999bd6d", "body": ":+1:", "path": "requests/sessions.py", "line": null, "side": "RIGHT", "created_at": "2017-02-14T16:30:35+00:00" } ], "meta": { "languages": [ "py" ], "touches_tests": false, "review_state_summary": { "CHANGES_REQUESTED": 1, "COMMENTED": 2, "APPROVED": 2 }, "meaningful_comment_count": 1, "has_approval": true, "has_changes_requested": true, "total_review_comments": 2 } } { "_id": "419426fdadb1cc65", "_schema_version": "1.0", "_cleaned_at": "2026-02-12T07:46:52.101366+00:00", "repo": "django/django", "repo_url": "https://github.com/django/django", "license_name": "BSD 3-Clause \"New\" or \"Revised\" License", "license_spdx": "BSD-3-Clause", "pr_number": 20340, "title": "Fixed #36712 -- Evaluated type annotations lazily in template tag registration.", "body": "#### Trac ticket number\nticket-36712\n\n#### Branch description\nPython 3.14 introduces [deferred evaluation of type annotations](https://docs.python.org/3/whatsnew/3.14.html#whatsnew314-deferred-annotations), which can make headaches around circular definitions go away.\n\n`inspect.getfullargspec` wasn't updated to take the new `annotation_format` arg that was provided to let inspecting libraries (us) avoid eagerly evaluating user annotations, see https://github.com/[USER_REDACTED]n/cpython/issues/141560.\n\nOne solution would have been to copy and paste the entire function--along with importing the seven or eight other symbols it needed--and do the tweak, long-term forking the implementation.\n\nInstead, patching the module helper anticipating the change we want Python to make felt more future-proof and sufficiently self-documenting. However, I'm happy to swap this out for a copy-and-paste approach if that's preferable, but we'd want to redistribute the python license in that case, I suppose?\n\nIdeally, this will be reverted when an upstream solution is available for https://github.com/[USER_REDACTED]n/cpython/issues/141560.\n\n[NAME_REDACTED] for the report and [NAME_REDACTED] for the first iteration and test.\n\n#### Checklist\n- [x] This PR targets the `main` branch. \n- [x] The commit message is written in past tense, mentions the ticket number, and ends with a period.\n- [x] I have checked the \"Has patch\" ticket flag in the Trac system.\n- [x] I have added or updated relevant tests.\n- [x] I have added or updated relevant docs, including release notes if applicable.\n- [x] I have attached screenshots in both light and dark modes for any UI changes.", "author": "user_3a67c55598c5", "created_at": "2025-11-30T00:12:42+00:00", "merged_at": "2025-12-02T01:48:54+00:00", "base_branch": "main", "head_branch": "jtw/getfullargspec", "additions": 138, "deletions": 32, "changed_files": 8, "files": [ { "filename": "django/contrib/admin/templatetags/base.py", "status": "modified", "additions": 5, "deletions": 3, "changes": 8, "patch": "@@ -1,6 +1,7 @@\n from inspect import getfullargspec\n \n from django.template.library import InclusionNode, parse_bits\n+from django.utils.inspect import lazy_annotations\n \n \n class InclusionAdminNode(InclusionNode):\n@@ -11,9 +12,10 @@ class InclusionAdminNode(InclusionNode):\n \n def __init__(self, parser, token, func, template_name, takes_context=True):\n self.template_name = template_name\n- params, varargs, varkw, defaults, kwonly, kwonly_defaults, _ = getfullargspec(\n- func\n- )\n+ with lazy_annotations():\n+ params, varargs, varkw, defaults, kwonly, kwonly_defaults, _ = (\n+ getfullargspec(func)\n+ )\n bits = token.split_contents()\n args, kwargs = parse_bits(\n parser," }, { "filename": "django/template/base.py", "status": "modified", "additions": 3, "deletions": 1, "changes": 4, "patch": "@@ -60,6 +60,7 @@\n from django.utils.deprecation import django_file_prefixes\n from django.utils.formats import localize\n from django.utils.html import conditional_escape\n+from django.utils.inspect import lazy_annotations\n from django.utils.regex_helper import _lazy_re_compile\n from django.utils.safestring import SafeData, SafeString, mark_safe\n from django.utils.text import get_text_list, smart_split, unescape_string_literal\n@@ -825,7 +826,8 @@ def args_check(name, func, provided):\n # Check to see if a decorator is providing the real function.\n func = inspect.unwrap(func)\n \n- args, _, _, defaults, _, _, _ = inspect.getfullargspec(func)\n+ with lazy_annotations():\n+ args, _, _, defaults, _, _, _ = inspect.getfullargspec(func)\n alen = len(args)\n dlen = len(defaults or [])\n # Not enough OR Too many" }, { "filename": "django/template/library.py", "status": "modified", "additions": 31, "deletions": 28, "changes": 59, "patch": "@@ -4,6 +4,7 @@\n from inspect import getfullargspec, unwrap\n \n from django.utils.html import conditional_escape\n+from django.utils.inspect import lazy_annotations\n \n from .base import Node, Template, token_kwargs\n from .exceptions import TemplateSyntaxError\n@@ -110,15 +111,16 @@ def hello(*args, **kwargs):\n \"\"\"\n \n def dec(func):\n- (\n- params,\n- varargs,\n- varkw,\n- defaults,\n- kwonly,\n- kwonly_defaults,\n- _,\n- ) = getfullargspec(unwrap(func))\n+ with lazy_annotations():\n+ (\n+ params,\n+ varargs,\n+ varkw,\n+ defaults,\n+ kwonly,\n+ kwonly_defaults,\n+ _,\n+ ) = getfullargspec(unwrap(func))\n function_name = name or func.__name__\n \n [USER_REDACTED](func)\n@@ -165,16 +167,16 @@ def hello(content):\n \n def dec(func):\n nonlocal end_name\n-\n- (\n- params,\n- varargs,\n- varkw,\n- defaults,\n- kwonly,\n- kwonly_defaults,\n- _,\n- ) = getfullargspec(unwrap(func))\n+ with lazy_annotations():\n+ (\n+ params,\n+ varargs,\n+ varkw,\n+ defaults,\n+ kwonly,\n+ kwonly_defaults,\n+ _,\n+ ) = getfullargspec(unwrap(func))\n function_name = name or func.__name__\n \n if end_name is None:\n@@ -249,15 +251,16 @@ def show_results(poll):\n \"\"\"\n \n def dec(func):\n- (\n- params,\n- varargs,\n- varkw,\n- defaults,\n- kwonly,\n- kwonly_defaults,\n- _,\n- ) = getfullargspec(unwrap(func))\n+ with lazy_annotations():\n+ (\n+ params,\n+ varargs,\n+ varkw,\n+ defaults,\n+ kwonly,\n+ kwonly_defaults,\n+ _,\n+ ) = getfullargspec(unwrap(func))\n function_name = name or func.__name__\n \n [USER_REDACTED](func)" }, { "filename": "django/utils/inspect.py", "status": "modified", "additions": 32, "deletions": 0, "changes": 32, "patch": "@@ -1,11 +1,19 @@\n import functools\n import inspect\n+import threading\n+from contextlib import contextmanager\n \n from django.utils.version import PY314\n \n if PY314:\n import annotationlib\n \n+ lock = threading.Lock()\n+ safe_signature_from_callable = functools.partial(\n+ inspect._signature_from_callable,\n+ annotation_format=annotationlib.Format.FORWARDREF,\n+ )\n+\n \n [USER_REDACTED].lru_cache(maxsize=512)\n def _get_func_parameters(func, remove_first):\n@@ -98,3 +106,27 @@ def is_module_level_function(func):\n return False\n \n return True\n+\n+\n+[USER_REDACTED]\n+def lazy_annotations():\n+ \"\"\"\n+ inspect.getfullargspec eagerly evaluates type annotations. To add\n+ compatibility with Python 3.14+ deferred evaluation, patch the module-level\n+ helper to provide the annotation_format that we are using elsewhere.\n+\n+ This private helper could be removed when there is an upstream solution for\n+ https://github.com/[USER_REDACTED]n/cpython/issues/141560.\n+\n+ This context manager is not reentrant.\n+ \"\"\"\n+ if not PY314:\n+ yield\n+ return\n+ with lock:\n+ original_helper = inspect._signature_from_callable\n+ inspect._signature_from_callable = safe_signature_from_callable\n+ try:\n+ yield\n+ finally:\n+ inspect._signature_from_callable = original_helper" }, { "filename": "docs/releases/5.2.9.txt", "status": "modified", "additions": 4, "deletions": 0, "changes": 4, "patch": "@@ -26,3 +26,7 @@ Bugfixes\n :class:`~django.http.HttpResponseRedirect` and\n :class:`~django.http.HttpResponsePermanentRedirect` for URLs longer than 2048\n characters. The limit is now 16384 characters (:ticket:`36743`).\n+\n+* Fixed a crash on Python 3.14+ that prevented template tag functions from\n+ being registered when their type annotations required deferred evaluation\n+ (:ticket:`36712`)." }, { "filename": "tests/admin_views/test_templatetags.py", "status": "modified", "additions": 20, "deletions": 0, "changes": 20, "patch": "@@ -1,13 +1,17 @@\n import datetime\n+import unittest\n \n from django.contrib.admin import ModelAdmin\n from django.contrib.admin.templatetags.admin_list import date_hierarchy\n from django.contrib.admin.templatetags.admin_modify import submit_row\n+from django.contrib.admin.templatetags.base import InclusionAdminNode\n from django.contrib.auth import get_permission_codename\n from django.contrib.auth.admin import UserAdmin\n from django.contrib.auth.models import User\n+from django.template.base import Token, TokenType\n from django.test import RequestFactory, TestCase\n from django.urls import reverse\n+from django.utils.version import PY314\n \n from .admin import ArticleAdmin, site\n from .models import Article, Question\n@@ -131,6 +135,22 @@ def test_override_change_list_template_tags(self):\n self.assertContains(response, \"override-pagination\")\n self.assertContains(response, \"override-search_form\")\n \n+ [USER_REDACTED].skipUnless(PY314, \"Deferred annotations are Python 3.14+ only\")\n+ def test_inclusion_admin_node_deferred_annotation(self):\n+ def action(arg: SomeType = None): # NOQA: F821\n+ pass\n+\n+ # This used to raise TypeError via the underlying call to\n+ # inspect.getfullargspec(), which is not ready for deferred\n+ # evaluation of annotations.\n+ InclusionAdminNode(\n+ parser=object(),\n+ token=Token(token_type=TokenType.TEXT, contents=\"a\"),\n+ func=action,\n+ template_name=\"test.html\",\n+ takes_context=False,\n+ )\n+\n \n class DateHierarchyTests(TestCase):\n factory = RequestFactory()" }, { "filename": "tests/template_tests/test_library.py", "status": "modified", "additions": 26, "deletions": 0, "changes": 26, "patch": "@@ -1,8 +1,10 @@\n import functools\n+import unittest\n \n from django.template import Library\n from django.template.base import Node\n from django.test import SimpleTestCase\n+from django.utils.version import PY314\n \n \n class FilterRegistrationTests(SimpleTestCase):\n@@ -78,6 +80,14 @@ def func():\n self.assertIs(func_wrapped, func)\n self.assertTrue(hasattr(func_wrapped, \"cache_info\"))\n \n+ [USER_REDACTED].skipUnless(PY314, \"Deferred annotations are Python 3.14+ only\")\n+ def test_inclusion_tag_deferred_annotation(self):\n+ [USER_REDACTED].library.inclusion_tag(\"template.html\")\n+ def func(arg: SomeType): # NOQA: F821\n+ return \"\"\n+\n+ self.assertIn(\"func\", self.library.tags)\n+\n \n class SimpleTagRegistrationTests(SimpleTestCase):\n def setUp(self):\n@@ -104,6 +114,14 @@ def func():\n \n self.assertIn(\"name\", self.library.tags)\n \n+ [USER_REDACTED].skipUnless(PY314, \"Deferred annotations are Python 3.14+ only\")\n+ def test_tag_deferred_annotation(self):\n+ [USER_REDACTED].library.simple_tag\n+ def func(parser, token: SomeType): # NOQA: F821\n+ return Node()\n+\n+ self.assertIn(\"func\", self.library.tags)\n+\n def test_simple_tag_invalid(self):\n msg = \"Invalid arguments provided to simple_tag\"\n with self.assertRaisesMessage(ValueError, msg):\n@@ -145,6 +163,14 @@ def func(content):\n \n self.assertIn(\"name\", self.library.tags)\n \n+ [USER_REDACTED].skipUnless(PY314, \"Deferred annotations are Python 3.14+ only\")\n+ def test_simple_block_tag_deferred_annotation(self):\n+ [USER_REDACTED].library.simple_block_tag\n+ def func(content: SomeType): # NOQA: F821\n+ return content\n+\n+ self.assertIn(\"func\", self.library.tags)\n+\n def test_simple_block_tag_invalid(self):\n msg = \"Invalid arguments provided to simple_block_tag\"\n with self.assertRaisesMessage(ValueError, msg):" }, { "filename": "tests/template_tests/test_parser.py", "status": "modified", "additions": 17, "deletions": 0, "changes": 17, "patch": "@@ -3,6 +3,8 @@\n These are *not* examples to be copied in user code.\n \"\"\"\n \n+import unittest\n+\n from django.template import Library, TemplateSyntaxError\n from django.template.base import (\n FilterExpression,\n@@ -15,6 +17,7 @@\n )\n from django.template.defaultfilters import register as filter_library\n from django.test import SimpleTestCase\n+from django.utils.version import PY314\n \n \n class ParserTests(SimpleTestCase):\n@@ -240,3 +243,17 @@ def test_filter_numeric_argument_parsing(self):\n FilterExpression(num, p).resolve({})\n with self.assertRaises(TemplateSyntaxError):\n FilterExpression(f\"0|default:{num}\", p).resolve({})\n+\n+ [USER_REDACTED].skipUnless(PY314, \"Deferred annotations are Python 3.14+ only\")\n+ def test_filter_deferred_annotation(self):\n+ register = Library()\n+\n+ [USER_REDACTED].filter(\"example\")\n+ def example_filter(value: str, arg: SomeType): # NOQA: F821\n+ return f\"{value}_{arg}\"\n+\n+ result = FilterExpression.args_check(\n+ \"example\", example_filter, [\"extra_example\"]\n+ )\n+\n+ self.assertIs(result, True)" } ], "reviews": [ { "id": 3524845484, "user": "user_34c3f4acb8a8", "state": "COMMENTED", "body": null, "submitted_at": "2025-12-01T12:51:35+00:00" }, { "id": 3526455674, "user": "user_00dac951cdbf", "state": "COMMENTED", "body": "Looks good, added a few naming suggestions. Thank you! 🌟", "submitted_at": "2025-12-01T19:45:35+00:00" }, { "id": 3527544323, "user": "user_3a67c55598c5", "state": "COMMENTED", "body": null, "submitted_at": "2025-12-01T23:35:09+00:00" }, { "id": 3527545927, "user": "user_3a67c55598c5", "state": "COMMENTED", "body": null, "submitted_at": "2025-12-01T23:36:11+00:00" }, { "id": 3527602425, "user": "user_3a67c55598c5", "state": "COMMENTED", "body": null, "submitted_at": "2025-12-02T00:08:30+00:00" }, { "id": 3527792551, "user": "user_00dac951cdbf", "state": "APPROVED", "body": "LGTM, thanks!!!", "submitted_at": "2025-12-02T01:43:41+00:00" } ], "review_comments": [ { "id": 2576958451, "user": "user_34c3f4acb8a8", "body": "Nit: For non-3.14 versions, this adds a lock around evaluting arguments. It's probably not huge, but in especially hot contexts it adds unnecessary extra work and could impact throughput. Perhaps worth a short-circuit for non-3.14 to avoid the lock?\n\n```python\nif not PY314:\n yield\nelse:\n with lock:\n ...\n```", "path": "django/utils/inspect.py", "line": 126, "side": "RIGHT", "created_at": "2025-12-01T12:51:35+00:00" }, { "id": 2578207946, "user": "user_00dac951cdbf", "body": "Should this `lock` also be inside the `if PY314:` guard?", "path": "django/utils/inspect.py", "line": null, "side": "RIGHT", "created_at": "2025-12-01T18:34:27+00:00" }, { "id": 2578372192, "user": "user_00dac951cdbf", "body": "I would suggest using the slightly shorter:\n\n```suggestion\n helper_was_replaced = False\n```", "path": "django/utils/inspect.py", "line": null, "side": "RIGHT", "created_at": "2025-12-01T19:39:25+00:00" }, { "id": 2578376018, "user": "user_00dac951cdbf", "body": "How about:\n\n```suggestion\ndef lazy_deferred_annotations():\n```", "path": "django/utils/inspect.py", "line": null, "side": "RIGHT", "created_at": "2025-12-01T19:40:59+00:00" }, { "id": 2578385882, "user": "user_00dac951cdbf", "body": "Is the bug in 5.2? or in 5.2.8? ideally we should be explicit about that. Also how about:\n\n```suggestion\n* Fixed a crashed in Django 5.2 and Python 3.14+ that prevented template tag\n functions from being registered when their type annotations required deferred\n evaluation (:ticket:`36712`).\n```", "path": "docs/releases/5.2.9.txt", "line": null, "side": "RIGHT", "created_at": "2025-12-01T19:45:13+00:00" }, { "id": 2579083832, "user": "user_3a67c55598c5", "body": "Good call -- I had it like this, then changed it, because from the perspective of the finally block, it could be unclear what \"replaced\" means: replaced before the context was entered, or during the `try`? \n\nBut this isn't necessarily helping, so I'll revert.", "path": "django/utils/inspect.py", "line": null, "side": "RIGHT", "created_at": "2025-12-01T23:35:09+00:00" }, { "id": 2579085320, "user": "user_3a67c55598c5", "body": "Maybe more than a bug it's a missing piece of the support for Python 3.14. I'll update this like the note in 5.1.4.", "path": "docs/releases/5.2.9.txt", "line": null, "side": "RIGHT", "created_at": "2025-12-01T23:36:11+00:00" }, { "id": 2579133267, "user": "user_3a67c55598c5", "body": "No reason to have to `getattr` for this below, since we're relying on it here. This helper hasn't changed in python for a long time, it's likely pretty stable.", "path": "django/utils/inspect.py", "line": 13, "side": "RIGHT", "created_at": "2025-12-02T00:08:30+00:00" } ], "meta": { "languages": [ "py", "txt" ], "touches_tests": true, "review_state_summary": { "COMMENTED": 5, "APPROVED": 1 }, "meaningful_comment_count": 8, "has_approval": true, "has_changes_requested": false, "total_review_comments": 8 } } { "_id": "45d35a2df3999b60", "_schema_version": "1.0", "_cleaned_at": "2026-02-12T07:46:52.101366+00:00", "repo": "django/django", "repo_url": "https://github.com/django/django", "license_name": "BSD 3-Clause \"New\" or \"Revised\" License", "license_spdx": "BSD-3-Clause", "pr_number": 20338, "title": "Refs #36036 -- Added m dimension to GEOSCoordSeq.", "body": "#### Trac ticket number\n\n\nticket-36036\n\n#### Branch description\nAs per the suggestion in https://github.com/[USER_REDACTED]ngo/django/pull/19013#issuecomment-2816751388 this adds M dimension support to `coordseq`.\n\n#### Checklist\n- [x] This PR targets the `main` branch. \n- [x] The commit message is written in past tense, mentions the ticket number, and ends with a period.\n- [ ] I have checked the \"Has patch\" ticket flag in the Trac system.\n- [ ] I have added or updated relevant tests.\n- [ ] I have added or updated relevant docs, including release notes if applicable.\n- [ ] I have attached screenshots in both light and dark modes for any UI changes.", "author": "user_cb2fc5a53d8e", "created_at": "2025-11-28T20:03:08+00:00", "merged_at": "2026-02-09T13:44:08+00:00", "base_branch": "main", "head_branch": "coordseq_m", "additions": 233, "deletions": 16, "changed_files": 4, "files": [ { "filename": "django/contrib/gis/geos/coordseq.py", "status": "modified", "additions": 72, "deletions": 11, "changes": 83, "patch": "@@ -9,7 +9,7 @@\n from django.contrib.gis.geos import prototypes as capi\n from django.contrib.gis.geos.base import GEOSBase\n from django.contrib.gis.geos.error import GEOSException\n-from django.contrib.gis.geos.libgeos import CS_PTR\n+from django.contrib.gis.geos.libgeos import CS_PTR, geos_version_tuple\n from django.contrib.gis.shortcuts import numpy\n \n \n@@ -20,6 +20,8 @@ class GEOSCoordSeq(GEOSBase):\n \n def __init__(self, ptr, z=False):\n \"Initialize from a GEOS pointer.\"\n+ # TODO when dropping support for GEOS 3.13 the z argument can be\n+ # deprecated in favor of using the GEOS function GEOSCoordSeq_hasZ.\n if not isinstance(ptr, CS_PTR):\n raise TypeError(\"Coordinate sequence should initialize with a CS_PTR.\")\n self._ptr = ptr\n@@ -58,6 +60,12 @@ def __setitem__(self, index, value):\n if self.dims == 3 and self._z:\n n_args = 3\n point_setter = self._set_point_3d\n+ elif self.dims == 3 and self.hasm:\n+ n_args = 3\n+ point_setter = self._set_point_3d_m\n+ elif self.dims == 4 and self._z and self.hasm:\n+ n_args = 4\n+ point_setter = self._set_point_4d\n else:\n n_args = 2\n point_setter = self._set_point_2d\n@@ -74,7 +82,7 @@ def _checkindex(self, index):\n \n def _checkdim(self, dim):\n \"Check the given dimension.\"\n- if dim < 0 or dim > 2:\n+ if dim < 0 or dim > 3:\n raise GEOSException(f'Invalid ordinate dimension: \"{dim:d}\"')\n \n def _get_x(self, index):\n@@ -86,6 +94,9 @@ def _get_y(self, index):\n def _get_z(self, index):\n return capi.cs_getz(self.ptr, index, byref(c_double()))\n \n+ def _get_m(self, index):\n+ return capi.cs_getm(self.ptr, index, byref(c_double()))\n+\n def _set_x(self, index, value):\n capi.cs_setx(self.ptr, index, value)\n \n@@ -95,16 +106,36 @@ def _set_y(self, index, value):\n def _set_z(self, index, value):\n capi.cs_setz(self.ptr, index, value)\n \n+ def _set_m(self, index, value):\n+ capi.cs_setm(self.ptr, index, value)\n+\n [USER_REDACTED]\n def _point_getter(self):\n- return self._get_point_3d if self.dims == 3 and self._z else self._get_point_2d\n+ if self.dims == 3 and self._z:\n+ return self._get_point_3d\n+ elif self.dims == 3 and self.hasm:\n+ return self._get_point_3d_m\n+ elif self.dims == 4 and self._z and self.hasm:\n+ return self._get_point_4d\n+ return self._get_point_2d\n \n def _get_point_2d(self, index):\n return (self._get_x(index), self._get_y(index))\n \n def _get_point_3d(self, index):\n return (self._get_x(index), self._get_y(index), self._get_z(index))\n \n+ def _get_point_3d_m(self, index):\n+ return (self._get_x(index), self._get_y(index), self._get_m(index))\n+\n+ def _get_point_4d(self, index):\n+ return (\n+ self._get_x(index),\n+ self._get_y(index),\n+ self._get_z(index),\n+ self._get_m(index),\n+ )\n+\n def _set_point_2d(self, index, value):\n x, y = value\n self._set_x(index, x)\n@@ -116,6 +147,19 @@ def _set_point_3d(self, index, value):\n self._set_y(index, y)\n self._set_z(index, z)\n \n+ def _set_point_3d_m(self, index, value):\n+ x, y, m = value\n+ self._set_x(index, x)\n+ self._set_y(index, y)\n+ self._set_m(index, m)\n+\n+ def _set_point_4d(self, index, value):\n+ x, y, z, m = value\n+ self._set_x(index, x)\n+ self._set_y(index, y)\n+ self._set_z(index, z)\n+ self._set_m(index, m)\n+\n # #### Ordinate getting and setting routines ####\n def getOrdinate(self, dimension, index):\n \"Return the value for the given dimension and index.\"\n@@ -153,6 +197,14 @@ def setZ(self, index, value):\n \"Set Z with the value at the given index.\"\n self.setOrdinate(2, index, value)\n \n+ def getM(self, index):\n+ \"Get M with the value at the given index.\"\n+ return self.getOrdinate(3, index)\n+\n+ def setM(self, index, value):\n+ \"Set M with the value at the given index.\"\n+ self.setOrdinate(3, index, value)\n+\n # ### Dimensions ###\n [USER_REDACTED]\n def size(self):\n@@ -172,6 +224,18 @@ def hasz(self):\n \"\"\"\n return self._z\n \n+ [USER_REDACTED]\n+ def hasm(self):\n+ \"\"\"\n+ Return whether this coordinate sequence has M dimension.\n+ \"\"\"\n+ if geos_version_tuple() >= (3, 14):\n+ return capi.cs_hasm(self._ptr)\n+ else:\n+ raise NotImplementedError(\n+ \"GEOSCoordSeq with an M dimension requires GEOS 3.14+.\"\n+ )\n+\n # ### [NAME_REDACTED] ###\n def clone(self):\n \"Clone this coordinate sequence.\"\n@@ -180,16 +244,13 @@ def clone(self):\n [USER_REDACTED]\n def kml(self):\n \"Return the KML representation for the coordinates.\"\n- # Getting the substitution string depending on whether the coordinates\n- # have a Z dimension.\n if self.hasz:\n- substr = \"%s,%s,%s \"\n+ coords = [f\"{coord[0]},{coord[1]},{coord[2]}\" for coord in self]\n else:\n- substr = \"%s,%s,0 \"\n- return (\n- \"%s\"\n- % \"\".join(substr % self[i] for i in range(len(self))).strip()\n- )\n+ coords = [f\"{coord[0]},{coord[1]},0\" for coord in self]\n+\n+ coordinate_string = \" \".join(coords)\n+ return f\"{coordinate_string}\"\n \n [USER_REDACTED]\n def tuple(self):" }, { "filename": "django/contrib/gis/geos/prototypes/__init__.py", "status": "modified", "additions": 3, "deletions": 0, "changes": 3, "patch": "@@ -8,12 +8,15 @@\n create_cs,\n cs_clone,\n cs_getdims,\n+ cs_getm,\n cs_getordinate,\n cs_getsize,\n cs_getx,\n cs_gety,\n cs_getz,\n+ cs_hasm,\n cs_is_ccw,\n+ cs_setm,\n cs_setordinate,\n cs_setx,\n cs_sety," }, { "filename": "django/contrib/gis/geos/prototypes/coordseq.py", "status": "modified", "additions": 23, "deletions": 4, "changes": 27, "patch": "@@ -1,7 +1,15 @@\n from ctypes import POINTER, c_byte, c_double, c_int, c_uint\n \n-from django.contrib.gis.geos.libgeos import CS_PTR, GEOM_PTR, GEOSFuncFactory\n-from django.contrib.gis.geos.prototypes.errcheck import GEOSException, last_arg_byref\n+from django.contrib.gis.geos.libgeos import (\n+ CS_PTR,\n+ GEOM_PTR,\n+ GEOSFuncFactory,\n+)\n+from django.contrib.gis.geos.prototypes.errcheck import (\n+ GEOSException,\n+ check_predicate,\n+ last_arg_byref,\n+)\n \n \n # ## Error-checking routines specific to coordinate sequences. ##\n@@ -67,6 +75,12 @@ def errcheck(result, func, cargs):\n return result\n \n \n+class CsUnaryPredicate(GEOSFuncFactory):\n+ argtypes = [CS_PTR]\n+ restype = c_byte\n+ errcheck = staticmethod(check_predicate)\n+\n+\n # ## [NAME_REDACTED] ctypes prototypes ##\n \n # [NAME_REDACTED] constructors & cloning.\n@@ -78,20 +92,25 @@ def errcheck(result, func, cargs):\n cs_getordinate = CsOperation(\"GEOSCoordSeq_getOrdinate\", ordinate=True, get=True)\n cs_setordinate = CsOperation(\"GEOSCoordSeq_setOrdinate\", ordinate=True)\n \n-# For getting, x, y, z\n+# For getting, x, y, z, m\n cs_getx = CsOperation(\"GEOSCoordSeq_getX\", get=True)\n cs_gety = CsOperation(\"GEOSCoordSeq_getY\", get=True)\n cs_getz = CsOperation(\"GEOSCoordSeq_getZ\", get=True)\n+cs_getm = CsOperation(\"GEOSCoordSeq_getM\", get=True)\n \n-# For setting, x, y, z\n+# For setting, x, y, z, m\n cs_setx = CsOperation(\"GEOSCoordSeq_setX\")\n cs_sety = CsOperation(\"GEOSCoordSeq_setY\")\n cs_setz = CsOperation(\"GEOSCoordSeq_setZ\")\n+cs_setm = CsOperation(\"GEOSCoordSeq_setM\")\n \n # These routines return size & dimensions.\n cs_getsize = CsInt(\"GEOSCoordSeq_getSize\")\n cs_getdims = CsInt(\"GEOSCoordSeq_getDimensions\")\n \n+# [NAME_REDACTED]\n+cs_hasm = CsUnaryPredicate(\"GEOSCoordSeq_hasM\")\n+\n cs_is_ccw = GEOSFuncFactory(\n \"GEOSCoordSeq_isCCW\", restype=c_int, argtypes=[CS_PTR, POINTER(c_byte)]\n )" }, { "filename": "tests/gis_tests/geos_tests/test_coordseq.py", "status": "modified", "additions": 135, "deletions": 1, "changes": 136, "patch": "@@ -1,4 +1,11 @@\n-from django.contrib.gis.geos import LineString\n+import math\n+from unittest import skipIf\n+from unittest.mock import patch\n+\n+from django.contrib.gis.geos import GEOSGeometry, LineString\n+from django.contrib.gis.geos import prototypes as capi\n+from django.contrib.gis.geos.coordseq import GEOSCoordSeq\n+from django.contrib.gis.geos.libgeos import geos_version_tuple\n from django.test import SimpleTestCase\n \n \n@@ -13,3 +20,130 @@ def test_getitem(self):\n with self.subTest(i):\n with self.assertRaisesMessage(IndexError, msg):\n coord_seq[i]\n+\n+ [USER_REDACTED](geos_version_tuple() < (3, 14), \"GEOS M support requires 3.14+\")\n+ def test_has_m(self):\n+ geom = GEOSGeometry(\"POINT ZM (1 2 3 4)\")\n+ coord_seq = GEOSCoordSeq(capi.get_cs(geom.ptr), z=True)\n+ self.assertIs(coord_seq.hasm, True)\n+\n+ geom = GEOSGeometry(\"POINT Z (1 2 3)\")\n+ coord_seq = GEOSCoordSeq(capi.get_cs(geom.ptr), z=True)\n+ self.assertIs(coord_seq.hasm, False)\n+\n+ geom = GEOSGeometry(\"POINT M (1 2 3)\")\n+ coord_seq = GEOSCoordSeq(capi.get_cs(geom.ptr), z=False)\n+ self.assertIs(coord_seq.hasm, True)\n+\n+ [USER_REDACTED](geos_version_tuple() < (3, 14), \"GEOS M support requires 3.14+\")\n+ def test_get_set_m(self):\n+ geom = GEOSGeometry(\"POINT ZM (1 2 3 4)\")\n+ coord_seq = GEOSCoordSeq(capi.get_cs(geom.ptr), z=True)\n+ self.assertEqual(coord_seq.tuple, (1, 2, 3, 4))\n+ self.assertEqual(coord_seq.getM(0), 4)\n+ coord_seq.setM(0, 10)\n+ self.assertEqual(coord_seq.tuple, (1, 2, 3, 10))\n+ self.assertEqual(coord_seq.getM(0), 10)\n+\n+ geom = GEOSGeometry(\"POINT M (1 2 4)\")\n+ coord_seq = GEOSCoordSeq(capi.get_cs(geom.ptr), z=False)\n+ self.assertEqual(coord_seq.tuple, (1, 2, 4))\n+ self.assertEqual(coord_seq.getM(0), 4)\n+ coord_seq.setM(0, 10)\n+ self.assertEqual(coord_seq.tuple, (1, 2, 10))\n+ self.assertEqual(coord_seq.getM(0), 10)\n+ self.assertIs(math.isnan(coord_seq.getZ(0)), True)\n+\n+ [USER_REDACTED](geos_version_tuple() < (3, 14), \"GEOS M support requires 3.14+\")\n+ def test_setitem(self):\n+ geom = GEOSGeometry(\"POINT ZM (1 2 3 4)\")\n+ coord_seq = GEOSCoordSeq(capi.get_cs(geom.ptr), z=True)\n+ coord_seq[0] = (10, 20, 30, 40)\n+ self.assertEqual(coord_seq.tuple, (10, 20, 30, 40))\n+\n+ geom = GEOSGeometry(\"POINT M (1 2 4)\")\n+ coord_seq = GEOSCoordSeq(capi.get_cs(geom.ptr), z=False)\n+ coord_seq[0] = (10, 20, 40)\n+ self.assertEqual(coord_seq.tuple, (10, 20, 40))\n+ self.assertEqual(coord_seq.getM(0), 40)\n+ self.assertIs(math.isnan(coord_seq.getZ(0)), True)\n+\n+ [USER_REDACTED](geos_version_tuple() < (3, 14), \"GEOS M support requires 3.14+\")\n+ def test_kml_m_dimension(self):\n+ geom = GEOSGeometry(\"POINT ZM (1 2 3 4)\")\n+ coord_seq = GEOSCoordSeq(capi.get_cs(geom.ptr), z=True)\n+ self.assertEqual(coord_seq.kml, \"1.0,2.0,3.0\")\n+ geom = GEOSGeometry(\"POINT M (1 2 4)\")\n+ coord_seq = GEOSCoordSeq(capi.get_cs(geom.ptr), z=False)\n+ self.assertEqual(coord_seq.kml, \"1.0,2.0,0\")\n+\n+ [USER_REDACTED](geos_version_tuple() < (3, 14), \"GEOS M support requires 3.14+\")\n+ def test_clone_m_dimension(self):\n+ geom = GEOSGeometry(\"POINT ZM (1 2 3 4)\")\n+ coord_seq = GEOSCoordSeq(capi.get_cs(geom.ptr), z=True)\n+ clone = coord_seq.clone()\n+ self.assertEqual(clone.tuple, (1, 2, 3, 4))\n+ self.assertIs(clone.hasz, True)\n+ self.assertIs(clone.hasm, True)\n+\n+ geom = GEOSGeometry(\"POINT M (1 2 4)\")\n+ coord_seq = GEOSCoordSeq(capi.get_cs(geom.ptr), z=False)\n+ clone = coord_seq.clone()\n+ self.assertEqual(clone.tuple, (1, 2, 4))\n+ self.assertIs(clone.hasz, False)\n+ self.assertIs(clone.hasm, True)\n+\n+ [USER_REDACTED](geos_version_tuple() < (3, 14), \"GEOS M support requires 3.14+\")\n+ def test_dims(self):\n+ geom = GEOSGeometry(\"POINT ZM (1 2 3 4)\")\n+ coord_seq = GEOSCoordSeq(capi.get_cs(geom.ptr), z=True)\n+ self.assertEqual(coord_seq.dims, 4)\n+\n+ geom = GEOSGeometry(\"POINT M (1 2 4)\")\n+ coord_seq = GEOSCoordSeq(capi.get_cs(geom.ptr), z=False)\n+ self.assertEqual(coord_seq.dims, 3)\n+\n+ geom = GEOSGeometry(\"POINT Z (1 2 3)\")\n+ coord_seq = GEOSCoordSeq(capi.get_cs(geom.ptr), z=True)\n+ self.assertEqual(coord_seq.dims, 3)\n+\n+ geom = GEOSGeometry(\"POINT (1 2)\")\n+ coord_seq = GEOSCoordSeq(capi.get_cs(geom.ptr), z=False)\n+ self.assertEqual(coord_seq.dims, 2)\n+\n+ def test_size(self):\n+ geom = GEOSGeometry(\"POINT (1 2)\")\n+ coord_seq = GEOSCoordSeq(capi.get_cs(geom.ptr), z=False)\n+ self.assertEqual(coord_seq.size, 1)\n+\n+ geom = GEOSGeometry(\"POINT M (1 2 4)\")\n+ coord_seq = GEOSCoordSeq(capi.get_cs(geom.ptr), z=False)\n+ self.assertEqual(coord_seq.size, 1)\n+\n+ [USER_REDACTED](geos_version_tuple() < (3, 14), \"GEOS M support requires 3.14+\")\n+ def test_iscounterclockwise(self):\n+ geom = GEOSGeometry(\"LINEARRING ZM (0 0 3 0, 1 0 0 2, 0 1 1 3, 0 0 3 4)\")\n+ coord_seq = GEOSCoordSeq(capi.get_cs(geom.ptr), z=True)\n+ self.assertEqual(\n+ coord_seq.tuple,\n+ (\n+ (0.0, 0.0, 3.0, 0.0),\n+ (1.0, 0.0, 0.0, 2.0),\n+ (0.0, 1.0, 1.0, 3.0),\n+ (0.0, 0.0, 3.0, 4.0),\n+ ),\n+ )\n+ self.assertIs(coord_seq.is_counterclockwise, True)\n+\n+ def test_m_support_error(self):\n+ geom = GEOSGeometry(\"POINT M (1 2 4)\")\n+ coord_seq = GEOSCoordSeq(capi.get_cs(geom.ptr), z=True)\n+ msg = \"GEOSCoordSeq with an M dimension requires GEOS 3.14+.\"\n+\n+ # mock geos_version_tuple to be 3.13.13\n+ with patch(\n+ \"django.contrib.gis.geos.coordseq.geos_version_tuple\",\n+ return_value=(3, 13, 13),\n+ ):\n+ with self.assertRaisesMessage(NotImplementedError, msg):\n+ coord_seq.hasm" } ], "reviews": [ { "id": 3543568303, "user": "user_946c87d4ebeb", "state": "COMMENTED", "body": "Awesome work, thanks a lot!\n\nQuestion: shouldn't we also safeguard the `_get_m`/`set_m` method against usage with GEOS < 3.14 (like for `hasm`)?\n\nYour comment on the PR could be also added somewhere to the PR content itself, otherwise I fear it may be forgotten and lost in the PR ocean.", "submitted_at": "2025-12-05T08:16:59+00:00" }, { "id": 3549522779, "user": "user_946c87d4ebeb", "state": "APPROVED", "body": null, "submitted_at": "2025-12-07T19:24:58+00:00" }, { "id": 3764554497, "user": "user_3a67c55598c5", "state": "APPROVED", "body": "Thank you!", "submitted_at": "2026-02-06T19:25:19+00:00" }, { "id": 3766773499, "user": "user_cb2fc5a53d8e", "state": "COMMENTED", "body": null, "submitted_at": "2026-02-07T09:29:04+00:00" }, { "id": 3767073029, "user": "user_3a67c55598c5", "state": "COMMENTED", "body": null, "submitted_at": "2026-02-07T13:31:22+00:00" }, { "id": 3767073403, "user": "user_3a67c55598c5", "state": "COMMENTED", "body": null, "submitted_at": "2026-02-07T13:31:38+00:00" } ], "review_comments": [ { "id": 2775461628, "user": "user_3a67c55598c5", "body": "I think, like the other recent PR, this should be strictly less than (3, 14) to account for patch updates.", "path": "tests/gis_tests/geos_tests/test_coordseq.py", "line": null, "side": "RIGHT", "created_at": "2026-02-06T18:25:53+00:00" }, { "id": 2775464429, "user": "user_3a67c55598c5", "body": "... and then you might even catch that here with 3, 13, 13 or similar.", "path": "tests/gis_tests/geos_tests/test_coordseq.py", "line": null, "side": "RIGHT", "created_at": "2026-02-06T18:26:42+00:00" }, { "id": 2775477617, "user": "user_3a67c55598c5", "body": "'requires'?", "path": "django/contrib/gis/geos/coordseq.py", "line": null, "side": "RIGHT", "created_at": "2026-02-06T18:30:19+00:00" }, { "id": 2775668580, "user": "user_3a67c55598c5", "body": "This is 0-indexed 🤯 !", "path": "django/contrib/gis/geos/coordseq.py", "line": 86, "side": "RIGHT", "created_at": "2026-02-06T19:25:05+00:00" }, { "id": 2777320818, "user": "user_cb2fc5a53d8e", "body": "```suggestion\n [USER_REDACTED](geos_version_tuple()[:2] < (3, 14), \"GEOS M support requires 3.14+\")\n```\n\nDoes this work for you?", "path": "tests/gis_tests/geos_tests/test_coordseq.py", "line": null, "side": "RIGHT", "created_at": "2026-02-07T09:29:04+00:00" }, { "id": 2777549066, "user": "user_3a67c55598c5", "body": "Elsewhere we just do:\n```suggestion\n [USER_REDACTED](geos_version_tuple() < (3, 14), \"GEOS M support requires 3.14+\")\n```", "path": "tests/gis_tests/geos_tests/test_coordseq.py", "line": null, "side": "RIGHT", "created_at": "2026-02-07T13:31:22+00:00" }, { "id": 2777549328, "user": "user_3a67c55598c5", "body": "(I don't mind either way, just noting what we already have.)", "path": "tests/gis_tests/geos_tests/test_coordseq.py", "line": null, "side": "RIGHT", "created_at": "2026-02-07T13:31:38+00:00" } ], "meta": { "languages": [ "py" ], "touches_tests": true, "review_state_summary": { "COMMENTED": 4, "APPROVED": 2 }, "meaningful_comment_count": 7, "has_approval": true, "has_changes_requested": false, "total_review_comments": 7 } } { "_id": "32e4a039c959e687", "_schema_version": "1.0", "_cleaned_at": "2026-02-12T07:46:52.101366+00:00", "repo": "django/django", "repo_url": "https://github.com/django/django", "license_name": "BSD 3-Clause \"New\" or \"Revised\" License", "license_spdx": "BSD-3-Clause", "pr_number": 20330, "title": "Extended scripts with more utilities.", "body": "Follow up of a523d5c8336f5f7f5e24a1cc8034ce65aedec3c6.", "author": "user_00dac951cdbf", "created_at": "2025-11-26T16:26:10+00:00", "merged_at": "2025-11-26T23:05:32+00:00", "base_branch": "main", "head_branch": "add-handling-of-eol-branch-to-scripts", "additions": 179, "deletions": 6, "changed_files": 3, "files": [ { "filename": "docs/internals/howto-release-django.txt", "status": "modified", "additions": 27, "deletions": 5, "changes": 32, "patch": "@@ -471,12 +471,25 @@ Building the artifacts\n .. admonition:: Optionally use helper scripts\n \n You can streamline some of the steps below using helper scripts from the\n- Wiki:\n+ ``scripts`` folder:\n \n- * `Release script\n- `_\n- * `Test new version script\n- `_\n+ * Release script example run:\n+\n+ .. code-block:: shell\n+\n+ $ PGP_KEY_ID= PGP_KEY_URL= DEST_FOLDER=~/releases scripts/do_django_release.py\n+\n+ * Test new version script:\n+\n+ .. code-block:: shell\n+\n+ $ VERSION=5.2.1 scripts/test_new_version.sh\n+\n+ * Confirm release signature script:\n+\n+ .. code-block:: shell\n+\n+ $ VERSION=5.2.1 scripts/confirm_release.sh\n \n #. Tag the release using ``git tag``. For example:\n \n@@ -692,6 +705,15 @@ You're almost done! All that's left to do now is:\n #. Update djangoproject.com's download page (`example PR\n `__).\n \n+ #. Process the older versions that will reach End-Of-Mainstream and/or\n+ End-Of-Life support when this final release is published:\n+\n+ #. Ensure that the EOL versions are mentioned in the blog post. `Example\n+ `_.\n+\n+ #. Create a tag for the EOL stable branch and delete the stable branch.\n+ Inspect and use the ``scripts/archive_eol_stable_branches.py`` helper.\n+\n #. If this was a security release, update :doc:`/releases/security` with\n details of the issues addressed." }, { "filename": "scripts/archive_eol_stable_branches.py", "status": "added", "additions": 151, "deletions": 0, "changes": 151, "patch": "@@ -0,0 +1,151 @@\n+#! /usr/bin/env python3\n+import argparse\n+import os\n+import subprocess\n+import sys\n+\n+\n+def run(cmd, *, cwd=None, env=None, dry_run=True):\n+ \"\"\"Run a command with optional dry-run behavior.\"\"\"\n+ environ = os.environ.copy()\n+ if env:\n+ environ.update(env)\n+ if dry_run:\n+ print(\"[DRY RUN]\", \" \".join(cmd))\n+ else:\n+ print(\"[EXECUTE]\", \" \".join(cmd))\n+ try:\n+ result = subprocess.check_output(\n+ cmd, cwd=cwd, env=environ, stderr=subprocess.STDOUT\n+ )\n+ except subprocess.CalledProcessError as e:\n+ result = e.output\n+ print(\" [ERROR]\", result)\n+ raise\n+ else:\n+ print(\" [RESULT]\", result)\n+ return result.decode().strip()\n+\n+\n+def validate_env(checkout_dir):\n+ if not checkout_dir:\n+ sys.exit(\"Error: checkout directory not provided (--checkout-dir).\")\n+ if not os.path.exists(checkout_dir):\n+ sys.exit(f\"Error: checkout directory '{checkout_dir}' does not exist.\")\n+ if not os.path.isdir(checkout_dir):\n+ sys.exit(f\"Error: '{checkout_dir}' is not a directory.\")\n+\n+\n+def get_remote_branches(checkout_dir, include_fn):\n+ \"\"\"Return list of remote branches filtered by include_fn.\"\"\"\n+ result = run(\n+ [\"git\", \"branch\", \"--list\", \"-r\"],\n+ cwd=checkout_dir,\n+ dry_run=False,\n+ )\n+ branches = [b.strip() for b in result.split(\"\\n\") if b.strip()]\n+ return [b for b in branches if include_fn(b)]\n+\n+\n+def get_branch_info(checkout_dir, branch):\n+ \"\"\"Return (commit_hash, last_update_date) for a given branch.\"\"\"\n+ commit_hash = run([\"git\", \"rev-parse\", branch], cwd=checkout_dir, dry_run=False)\n+ last_update = run(\n+ [\"git\", \"show\", branch, \"--format=format:%ai\", \"-s\"],\n+ cwd=checkout_dir,\n+ dry_run=False,\n+ )\n+ return commit_hash, last_update\n+\n+\n+def create_tag(checkout_dir, branch, commit_hash, last_update, *, dry_run=True):\n+ \"\"\"Create a tag locally for a given branch at its last update.\"\"\"\n+ tag_name = branch.replace(\"origin/\", \"\", 1)\n+ msg = f'\"Tagged {tag_name} for EOL stable branch removal.\"'\n+ run(\n+ [\"git\", \"tag\", \"--sign\", \"--message\", msg, tag_name, commit_hash],\n+ cwd=checkout_dir,\n+ env={\"GIT_COMMITTER_DATE\": last_update},\n+ dry_run=dry_run,\n+ )\n+ return tag_name\n+\n+\n+def delete_remote_and_local_branch(checkout_dir, branch, *, dry_run=True):\n+ \"\"\"Delete a remote branch from origin and the maching local branch.\"\"\"\n+ try:\n+ run(\n+ [\"git\", \"branch\", \"-D\", branch],\n+ cwd=checkout_dir,\n+ dry_run=dry_run,\n+ )\n+ except subprocess.CalledProcessError:\n+ print(f\"[ERROR] Local branch {branch} can not be deleted.\")\n+\n+ run(\n+ [\"git\", \"push\", \"origin\", \"--delete\", branch.replace(\"origin/\", \"\", 1)],\n+ cwd=checkout_dir,\n+ dry_run=dry_run,\n+ )\n+\n+\n+def main():\n+ parser = argparse.ArgumentParser(\n+ description=\"[NAME_REDACTED] branches into tags and optionally delete them.\"\n+ )\n+ parser.add_argument(\n+ \"--checkout-dir\", required=True, help=\"Path to Django git checkout\"\n+ )\n+ parser.add_argument(\n+ \"--dry-run\",\n+ action=\"store_true\",\n+ help=\"Print commands instead of executing them\",\n+ )\n+ parser.add_argument(\n+ \"--branches\", nargs=\"*\", help=\"Specific remote branches to include (optional)\"\n+ )\n+ args = parser.parse_args()\n+\n+ validate_env(args.checkout_dir)\n+ dry_run = args.dry_run\n+ checkout_dir = args.checkout_dir\n+\n+ if args.branches:\n+ wanted = set(f\"origin/{b}\" for b in args.branches)\n+ else:\n+ wanted = set()\n+\n+ branches = get_remote_branches(checkout_dir, include_fn=lambda b: b in wanted)\n+ if not branches:\n+ print(\"No branches matched inclusion criteria.\")\n+ return\n+\n+ print(\"\\nMatched branches:\")\n+ print(\"\\n\".join(branches))\n+ print()\n+\n+ branch_updates = {b: get_branch_info(checkout_dir, b) for b in branches}\n+ print(\"\\nLast updates:\")\n+ for b, (h, d) in branch_updates.items():\n+ print(f\"{b}\\t{h}\\t{d}\")\n+\n+ if (\n+ input(\"\\nDelete remote branches and create tags? [y/N]: \").strip().lower()\n+ == \"y\"\n+ ):\n+ for b, (commit_hash, last_update_date) in branch_updates.items():\n+ print(f\"Creating tag for {b} at {commit_hash=} with {last_update_date=}\")\n+ create_tag(checkout_dir, b, commit_hash, last_update_date, dry_run=dry_run)\n+ print(f\"Deleting remote branch {b}\")\n+ delete_remote_and_local_branch(checkout_dir, b, dry_run=dry_run)\n+ run(\n+ [\"git\", \"push\", \"--tags\"],\n+ cwd=checkout_dir,\n+ dry_run=dry_run,\n+ )\n+\n+ print(\"Done.\")\n+\n+\n+if __name__ == \"__main__\":\n+ main()" }, { "filename": "scripts/confirm_release.sh", "status": "modified", "additions": 1, "deletions": 1, "changes": 2, "patch": "@@ -25,7 +25,7 @@ echo \"Download checksum file ...\"\n curl --fail --output \"$CHECKSUM_FILE\" \"${MEDIA_URL_PREFIX}/pgp/${CHECKSUM_FILE}\"\n \n echo \"Verify checksum file ...\"\n-if [ -n \"${GPG_KEY}\" ] ; then\n+if [ -n \"${GPG_KEY:-}\" ] ; then\n gpg --recv-keys \"${GPG_KEY}\"\n fi\n gpg --verify \"${CHECKSUM_FILE}\"" } ], "reviews": [ { "id": 3511822786, "user": "user_3a67c55598c5", "state": "APPROVED", "body": "Looks good 😎", "submitted_at": "2025-11-26T16:45:12+00:00" }, { "id": 3511891194, "user": "user_00dac951cdbf", "state": "COMMENTED", "body": null, "submitted_at": "2025-11-26T16:56:02+00:00" }, { "id": 3511923036, "user": "user_3a67c55598c5", "state": "COMMENTED", "body": null, "submitted_at": "2025-11-26T17:01:45+00:00" }, { "id": 3511926178, "user": "user_00dac951cdbf", "state": "COMMENTED", "body": null, "submitted_at": "2025-11-26T17:02:26+00:00" } ], "review_comments": [ { "id": 2565711807, "user": "user_3a67c55598c5", "body": "I'm not familiar with this syntax, can you throw me a hint?", "path": "scripts/confirm_release.sh", "line": 28, "side": "RIGHT", "created_at": "2025-11-26T16:42:26+00:00" }, { "id": 2565720968, "user": "user_3a67c55598c5", "body": "Is this \"EOL or end-of-mainstream support versions\"? Otherwise I wasn't sure why end-of-mainstream... was referenced.", "path": "docs/internals/howto-release-django.txt", "line": null, "side": "RIGHT", "created_at": "2025-11-26T16:45:03+00:00" }, { "id": 2565767716, "user": "user_00dac951cdbf", "body": "The example blogpost shows how, on some final releases, we announce the end of extended support for a version (full EOL) and the end of mainstream support for other (security support still available). Does that help in any way?", "path": "docs/internals/howto-release-django.txt", "line": null, "side": "RIGHT", "created_at": "2025-11-26T16:56:02+00:00" }, { "id": 2565790973, "user": "user_3a67c55598c5", "body": "Great, that's what I thought. Then I would suggest:\n\n\"Ensure that the EOL versions\" -> \"Ensure that the EOL or End-of-Mainstream support versions\"", "path": "docs/internals/howto-release-django.txt", "line": null, "side": "RIGHT", "created_at": "2025-11-26T17:01:45+00:00" }, { "id": 2565793712, "user": "user_00dac951cdbf", "body": "Sure! This bash syntax is used to set a default if the `GPG_KEY` var is not defined. Without it, I was getting:\n```\nscripts/confirm_release.sh: line 28: GPG_KEY: unbound variable\n```\nsince we are running the scripts in a pedantic-ish manner where `set -u` complains about undefined variables.", "path": "scripts/confirm_release.sh", "line": 28, "side": "RIGHT", "created_at": "2025-11-26T17:02:26+00:00" } ], "meta": { "languages": [ "py", "sh", "txt" ], "touches_tests": false, "review_state_summary": { "APPROVED": 1, "COMMENTED": 3 }, "meaningful_comment_count": 5, "has_approval": true, "has_changes_requested": false, "total_review_comments": 5 } } { "_id": "734b02f94a65d5c4", "_schema_version": "1.0", "_cleaned_at": "2026-02-12T07:46:52.101366+00:00", "repo": "django/django", "repo_url": "https://github.com/django/django", "license_name": "BSD 3-Clause \"New\" or \"Revised\" License", "license_spdx": "BSD-3-Clause", "pr_number": 20329, "title": "Closed pool when parallel test runner encounters unpicklable exceptions.", "body": "**Before**\n```py\nmultiprocessing.pool.MaybeEncodingError: Error sending result: ''. Reason: 'TypeError(\"cannot pickle 'BufferedReader' instances\")'\nException ignored while calling deallocator :\nTraceback (most recent call last):\n File \"/Library/Frameworks/Python.framework/Versions/3.14/lib/python3.14/multiprocessing/pool.py\", line 268, in __del__\nResourceWarning: unclosed running multiprocessing pool \n```\n**After**\n```py\nmultiprocessing.pool.MaybeEncodingError: Error sending result: ''. Reason: 'TypeError(\"cannot pickle 'BufferedReader' instances\")'\n```\n\nTo reproduce, cause a failure in `tests/servers` by [NAME_REDACTED]:\n```diff\ndiff --git a/django/test/testcases.py b/django/test/testcases.py\nindex c587f770a6..40e785f5dc 100644\n--- a/django/test/testcases.py\n+++ b/django/test/testcases.py\n@@ -1824,11 +1824,11 @@ class LiveServerTestCase(TransactionTestCase):\n \n [USER_REDACTED]\n def setUpClass(cls):\n- super().setUpClass()\n cls.enterClassContext(\n modify_settings(ALLOWED_HOSTS={\"append\": cls.allowed_host})\n )\n cls._start_server_thread()\n+ super().setUpClass()\n \n [USER_REDACTED]\n def _start_server_thread(cls):\n```", "author": "user_3a67c55598c5", "created_at": "2025-11-26T15:04:45+00:00", "merged_at": "2025-12-03T21:04:22+00:00", "base_branch": "main", "head_branch": "jtw/close-pool", "additions": 31, "deletions": 33, "changed_files": 2, "files": [ { "filename": "django/test/runner.py", "status": "modified", "additions": 29, "deletions": 30, "changes": 59, "patch": "@@ -567,7 +567,14 @@ def run(self, result):\n \"\"\"\n self.initialize_suite()\n counter = multiprocessing.Value(ctypes.c_int, 0)\n- pool = multiprocessing.Pool(\n+ args = [\n+ (self.runner_class, index, subsuite, self.failfast, self.buffer)\n+ for index, subsuite in enumerate(self.subsuites)\n+ ]\n+ # Don't buffer in the main process to avoid error propagation issues.\n+ result.buffer = False\n+\n+ with multiprocessing.Pool(\n processes=self.processes,\n initializer=functools.partial(_safe_init_worker, self.init_worker.__func__),\n initargs=[\n@@ -579,38 +586,30 @@ def run(self, result):\n self.debug_mode,\n self.used_aliases,\n ],\n- )\n- args = [\n- (self.runner_class, index, subsuite, self.failfast, self.buffer)\n- for index, subsuite in enumerate(self.subsuites)\n- ]\n- # Don't buffer in the main process to avoid error propagation issues.\n- result.buffer = False\n-\n- test_results = pool.imap_unordered(self.run_subsuite.__func__, args)\n-\n- while True:\n- if result.shouldStop:\n- pool.terminate()\n- break\n-\n- try:\n- subsuite_index, events = test_results.next(timeout=0.1)\n- except multiprocessing.TimeoutError as err:\n- if counter.value < 0:\n- err.add_note(\"ERROR: _init_worker failed, see prior traceback\")\n+ ) as pool:\n+ test_results = pool.imap_unordered(self.run_subsuite.__func__, args)\n+\n+ while True:\n+ if result.shouldStop:\n+ pool.terminate()\n+ break\n+\n+ try:\n+ subsuite_index, events = test_results.next(timeout=0.1)\n+ except multiprocessing.TimeoutError as err:\n+ if counter.value < 0:\n+ err.add_note(\"ERROR: _init_worker failed, see prior traceback\")\n+ raise\n+ continue\n+ except StopIteration:\n pool.close()\n- raise\n- continue\n- except StopIteration:\n- pool.close()\n- break\n+ break\n \n- tests = list(self.subsuites[subsuite_index])\n- for event in events:\n- self.handle_event(result, tests, event)\n+ tests = list(self.subsuites[subsuite_index])\n+ for event in events:\n+ self.handle_event(result, tests, event)\n \n- pool.join()\n+ pool.join()\n \n return result" }, { "filename": "tests/test_runner/test_parallel.py", "status": "modified", "additions": 2, "deletions": 3, "changes": 5, "patch": "@@ -309,9 +309,8 @@ def fake_next(*args, **kwargs):\n test_result.shouldStop = True\n return (0, remote_result.events)\n \n- mock_pool.return_value.imap_unordered.return_value = unittest.mock.Mock(\n- next=fake_next\n- )\n+ mock_imap = mock_pool.return_value.__enter__.return_value.imap_unordered\n+ mock_imap.return_value = unittest.mock.Mock(next=fake_next)\n pts.run(test_result)\n \n self.assertIn(\"ValueError: woops\", test_result.errors[0][1])" } ], "reviews": [ { "id": 3511465955, "user": "user_057de2f3b132", "state": "APPROVED", "body": null, "submitted_at": "2025-11-26T15:18:53+00:00" }, { "id": 3511605122, "user": "user_cdda8932ec17", "state": "APPROVED", "body": "Do you know if there is a reason why we don't use `pool` as a context manager?\n\nIt looks likes something `__exit__` should handle by itself?", "submitted_at": "2025-11-26T15:46:48+00:00" }, { "id": 3532344626, "user": "user_057de2f3b132", "state": "COMMENTED", "body": null, "submitted_at": "2025-12-02T22:34:16+00:00" }, { "id": 3532399110, "user": "user_3a67c55598c5", "state": "COMMENTED", "body": null, "submitted_at": "2025-12-02T22:54:42+00:00" }, { "id": 3536885716, "user": "user_057de2f3b132", "state": "APPROVED", "body": null, "submitted_at": "2025-12-03T20:53:10+00:00" } ], "review_comments": [ { "id": 2582973946, "user": "user_057de2f3b132", "body": "I think we don't need the `pool.close()` on the line below this now.", "path": "django/test/runner.py", "line": 604, "side": "RIGHT", "created_at": "2025-12-02T22:28:57+00:00" }, { "id": 2583021202, "user": "user_3a67c55598c5", "body": "I get the following when I try that (given that we only `break` and not `raise`):\n\n```py\n File \"/Users/jwalls/django/django/test/runner.py\", line 611, in run\n pool.join()\n ~~~~~~~~~^^\n File \"/Library/Frameworks/Python.framework/Versions/3.14/lib/python3.14/multiprocessing/pool.py\", line 662, in join\n raise ValueError(\"Pool is still running\")\nValueError: Pool is still running\n```", "path": "django/test/runner.py", "line": 604, "side": "RIGHT", "created_at": "2025-12-02T22:54:42+00:00" } ], "meta": { "languages": [ "py" ], "touches_tests": true, "review_state_summary": { "APPROVED": 3, "COMMENTED": 2 }, "meaningful_comment_count": 2, "has_approval": true, "has_changes_requested": false, "total_review_comments": 2 } } { "_id": "619310db88c4db2a", "_schema_version": "1.0", "_cleaned_at": "2026-02-12T07:46:52.101366+00:00", "repo": "django/django", "repo_url": "https://github.com/django/django", "license_name": "BSD 3-Clause \"New\" or \"Revised\" License", "license_spdx": "BSD-3-Clause", "pr_number": 20321, "title": "Fixed #29257 -- [NAME_REDACTED] when attempting to close a possibly already-closed cursor.", "body": "#### Trac ticket number\n\nticket-29257\n\n#### Branch description\nWhen ``cursor.execute()`` raises an exception and ``cursor.close()`` also raises, Django used to surface the ``cursor.close()`` error, adding noise to the original execution failure and producing misleading messages such as: \"cursor _django_curs_xxx does not exist\".\n\nThis patch ensures that the original ``execute()`` exception is preserved without unnecessary context. A regression test is included to verify that ``cursor.close()`` errors do not distract from the real underlying exception.\n\n#### Checklist\n- [x] This PR targets the `main` branch. \n- [x] The commit message is written in past tense, mentions the ticket number, and ends with a period.\n- [x] I have checked the \"Has patch\" ticket flag in the Trac system.\n- [x] I have added or updated relevant tests.\n- [ ] I have added or updated relevant docs, including release notes if applicable.\n- [ ] I have attached screenshots in both light and dark modes for any UI changes.", "author": "user_b787990f7421", "created_at": "2025-11-25T18:38:28+00:00", "merged_at": "2026-01-06T20:15:56+00:00", "base_branch": "main", "head_branch": "ticket-29257-clean", "additions": 32, "deletions": 5, "changed_files": 2, "files": [ { "filename": "django/db/models/sql/compiler.py", "status": "modified", "additions": 5, "deletions": 2, "changes": 7, "patch": "@@ -1629,9 +1629,12 @@ def execute_sql(\n cursor = self.connection.cursor()\n try:\n cursor.execute(sql, params)\n- except Exception:\n+ except Exception as e:\n # Might fail for server-side cursors (e.g. connection closed)\n- cursor.close()\n+ try:\n+ cursor.close()\n+ except DatabaseError:\n+ raise e from None\n raise\n \n if result_type == ROW_COUNT:" }, { "filename": "tests/queries/test_sqlcompiler.py", "status": "modified", "additions": 27, "deletions": 3, "changes": 30, "patch": "@@ -1,11 +1,14 @@\n-from django.db import DEFAULT_DB_ALIAS, connection\n+from unittest import mock\n+\n+from django.db import DEFAULT_DB_ALIAS, DatabaseError, connection\n from django.db.models.sql import Query\n-from django.test import SimpleTestCase\n+from django.db.models.sql.compiler import SQLCompiler\n+from django.test import TestCase\n \n from .models import Item\n \n \n-class SQLCompilerTest(SimpleTestCase):\n+class SQLCompilerTest(TestCase):\n def test_repr(self):\n query = Query(Item)\n compiler = query.get_compiler(DEFAULT_DB_ALIAS, connection)\n@@ -15,3 +18,24 @@ def test_repr(self):\n f\" \"\n f\"using='default'>\",\n )\n+\n+ def test_execute_sql_suppresses_cursor_closing_failure_on_exception(self):\n+ query = Query(Item)\n+ compiler = SQLCompiler(query, connection, None)\n+ cursor = mock.MagicMock()\n+\n+ # When execution fails, the cursor may have been closed.\n+ # Django's attempt to close it again will fail, and needs catching.\n+ execute_err = DatabaseError(\"execute failed\")\n+ cursor.execute.side_effect = execute_err\n+ cursor.close.side_effect = DatabaseError(\"close failed\")\n+\n+ with mock.patch.object(connection, \"cursor\", return_value=cursor):\n+ with self.assertRaises(DatabaseError) as ctx:\n+ compiler.execute_sql(\"SELECT 1\", [])\n+\n+ # There is no irrelevant context from trying to close a closed cursor.\n+ exc = ctx.exception\n+ self.assertIs(exc, execute_err)\n+ self.assertIsNone(exc.__cause__)\n+ self.assertTrue(exc.__suppress_context__)" } ], "reviews": [ { "id": 3584706834, "user": "user_3a67c55598c5", "state": "COMMENTED", "body": "Good stuff [USER_REDACTED], with some polish this should be good to go!", "submitted_at": "2025-12-16T20:04:05+00:00" }, { "id": 3627398291, "user": "user_3a67c55598c5", "state": "COMMENTED", "body": null, "submitted_at": "2026-01-05T15:50:48+00:00" }, { "id": 3627423546, "user": "user_3a67c55598c5", "state": "APPROVED", "body": "Thanks [USER_REDACTED] 👍.\n\nI moved the test to `SQLCompilerTest` and adjusted it slightly. Looks good!", "submitted_at": "2026-01-05T16:11:43+00:00" } ], "review_comments": [ { "id": 2624538705, "user": "user_3a67c55598c5", "body": "```suggestion\n except DatabaseError:\n```", "path": "django/db/models/sql/compiler.py", "line": null, "side": "RIGHT", "created_at": "2025-12-16T19:49:43+00:00" }, { "id": 2624539518, "user": "user_3a67c55598c5", "body": "Please remove the comments.", "path": "django/db/models/sql/compiler.py", "line": null, "side": "RIGHT", "created_at": "2025-12-16T19:50:03+00:00" }, { "id": 2624540432, "user": "user_3a67c55598c5", "body": "Please move this comment into the new inner except.", "path": "django/db/models/sql/compiler.py", "line": 1633, "side": "RIGHT", "created_at": "2025-12-16T19:50:24+00:00" }, { "id": 2624545645, "user": "user_3a67c55598c5", "body": "Assert against `ctx.exception.__cause__` and `__suppress_context__` similar to `test_fetch_mode_raise_forward` and others.", "path": "tests/queries/test_execute_sql.py", "line": null, "side": "RIGHT", "created_at": "2025-12-16T19:52:12+00:00" }, { "id": 2624547551, "user": "user_3a67c55598c5", "body": "You can remove most of these comments. You can leave the execution fails & closing fails comments if you like, as that's the interesting part -- the fact that we need nested failures.", "path": "tests/queries/test_execute_sql.py", "line": null, "side": "RIGHT", "created_at": "2025-12-16T19:52:53+00:00" }, { "id": 2624566342, "user": "user_3a67c55598c5", "body": "The original exception was already raised, it just had extra context, so I'd suggest tweaking this title.", "path": "tests/queries/test_execute_sql.py", "line": null, "side": "RIGHT", "created_at": "2025-12-16T20:00:04+00:00" }, { "id": 2624575895, "user": "user_3a67c55598c5", "body": "You can remove the model:\n\n```diff\ndiff --git a/tests/queries/test_execute_sql.py b/tests/queries/test_execute_sql.py\nindex 6e9e578093..213ac21f53 100644\n--- a/tests/queries/test_execute_sql.py\n+++ b/tests/queries/test_execute_sql.py\n@@ -1,21 +1,15 @@\n from unittest import mock\n \n-from django.db import DatabaseError, connection, models\n+from django.db import DatabaseError, connection\n from django.db.models.sql.compiler import SQLCompiler\n from django.db.models.sql.query import Query\n from django.test import TestCase\n \n \n-class DummyModel(models.Model):\n- class Meta:\n- app_label = \"tests\"\n- managed = False\n-\n-\n class ExecuteSqlCursorCloseErrorTests(TestCase):\n def test_execute_sql_raises_original_exception_when_close_fails(self):\n # Build compiler\n- query = Query(DummyModel)\n+ query = Query(None)\n compiler = SQLCompiler(query, connection, None)\n \n # Fake cursor\n```", "path": "tests/queries/test_execute_sql.py", "line": null, "side": "RIGHT", "created_at": "2025-12-16T20:03:33+00:00" }, { "id": 2661962850, "user": "user_3a67c55598c5", "body": "I'll adjust this for you.", "path": "tests/queries/test_execute_sql.py", "line": null, "side": "RIGHT", "created_at": "2026-01-05T15:50:47+00:00" }, { "id": 2661979887, "user": "user_3a67c55598c5", "body": "Django uses unittest-style asserts.", "path": "tests/queries/test_execute_sql.py", "line": null, "side": "RIGHT", "created_at": "2026-01-05T15:56:07+00:00" } ], "meta": { "languages": [ "py" ], "touches_tests": true, "review_state_summary": { "COMMENTED": 2, "APPROVED": 1 }, "meaningful_comment_count": 9, "has_approval": true, "has_changes_requested": false, "total_review_comments": 9 } } { "_id": "9cd41837cc7cc792", "_schema_version": "1.0", "_cleaned_at": "2026-02-12T07:46:52.101366+00:00", "repo": "django/django", "repo_url": "https://github.com/django/django", "license_name": "BSD 3-Clause \"New\" or \"Revised\" License", "license_spdx": "BSD-3-Clause", "pr_number": 20312, "title": "Fixed #36112 -- Added fallback in last_executed_query() on Oracle and PostgreSQL.", "body": "#### Trac ticket number\nticket-36112\n\n#### Branch description\nThis PR fixes the issue described in ticket #36112, where ``DatabaseOperations.last_executed_query()`` in the Oracle backend may return ``None`` when a query fails. This causes SQL formatting to crash under ``--debug-sql``.\n\nFollowing the core team’s guidance on the ticket ([NAME_REDACTED] & [NAME_REDACTED]), backend implementations should fall back to ``super().last_executed_query()`` rather than returning ``None``.\n\nThis patch:\n- Adds the fallback for Oracle.\n- Matches the expected backend contract.\n- Has no behavioral impact on successful queries.\n- Only affects debug/inspection paths.\n- Requires no new tests (ticket metadata: Needs tests: no).\n\nThis completes the cleanup after #36380.\n\n#### Checklist\n- [x] This PR targets the `main` branch. \n- [x] The commit message is written in past tense, mentions the ticket number, and ends with a period.\n- [x] I have checked the \"Has patch\" ticket flag in the Trac system.\n- [x] I have added or updated relevant tests.\n- [ ] I have added or updated relevant docs, including release notes if applicable.\n- [ ] I have attached screenshots in both light and dark modes for any UI changes.", "author": "user_b787990f7421", "created_at": "2025-11-24T15:18:48+00:00", "merged_at": "2025-12-27T09:42:25+00:00", "base_branch": "main", "head_branch": "ticket-36112-last-executed-query-fallback", "additions": 21, "deletions": 4, "changed_files": 3, "files": [ { "filename": "django/db/backends/oracle/operations.py", "status": "modified", "additions": 5, "deletions": 1, "changes": 6, "patch": "@@ -352,7 +352,11 @@ def last_executed_query(self, cursor, sql, params):\n statement = statement.replace(\n key, force_str(params[key], errors=\"replace\")\n )\n- return statement\n+ return (\n+ super().last_executed_query(cursor, sql, params)\n+ if statement is None\n+ else statement\n+ )\n \n def last_insert_id(self, cursor, table_name, pk_name):\n sq_name = self._get_sequence_name(cursor, strip_quotes(table_name), pk_name)" }, { "filename": "django/db/backends/postgresql/operations.py", "status": "modified", "additions": 3, "deletions": 3, "changes": 6, "patch": "@@ -302,11 +302,11 @@ def last_executed_query(self, cursor, sql, params):\n try:\n return self.compose_sql(sql, params)\n except errors.DataError:\n- return None\n+ return super().last_executed_query(cursor, sql, params)\n else:\n if cursor._query and cursor._query.query is not None:\n return cursor._query.query.decode()\n- return None\n+ return super().last_executed_query(cursor, sql, params)\n \n else:\n \n@@ -315,7 +315,7 @@ def last_executed_query(self, cursor, sql, params):\n # The query attribute is a Psycopg extension to the DB API 2.0.\n if cursor.query is not None:\n return cursor.query.decode()\n- return None\n+ return super().last_executed_query(cursor, sql, params)\n \n if is_psycopg3:" }, { "filename": "tests/backends/base/test_operations.py", "status": "modified", "additions": 13, "deletions": 0, "changes": 13, "patch": "@@ -171,6 +171,19 @@ class DatabaseOperationTests(TestCase):\n def setUp(self):\n self.ops = BaseDatabaseOperations(connection=connection)\n \n+ def test_last_executed_query_base_fallback(self):\n+ sql = \"INVALID SQL\"\n+ params = []\n+ with connection.cursor() as cursor:\n+ cursor.close()\n+ try:\n+ cursor.execute(sql, params)\n+ except connection.features.closed_cursor_error_class:\n+ pass\n+ self.assertIsNotNone(\n+ connection.ops.last_executed_query(cursor, sql, params),\n+ )\n+\n [USER_REDACTED](\"can_distinct_on_fields\")\n def test_distinct_on_fields(self):\n msg = \"DISTINCT ON fields is not supported by [NAME_REDACTED]\"" } ], "reviews": [ { "id": 3512568186, "user": "user_5501cd6d3dc8", "state": "COMMENTED", "body": null, "submitted_at": "2025-11-26T19:57:10+00:00" }, { "id": 3513904509, "user": "user_5501cd6d3dc8", "state": "COMMENTED", "body": null, "submitted_at": "2025-11-27T07:52:28+00:00" }, { "id": 3513912478, "user": "user_5501cd6d3dc8", "state": "COMMENTED", "body": null, "submitted_at": "2025-11-27T07:55:14+00:00" }, { "id": 3529270578, "user": "user_5501cd6d3dc8", "state": "COMMENTED", "body": null, "submitted_at": "2025-12-02T10:06:23+00:00" }, { "id": 3529277607, "user": "user_5501cd6d3dc8", "state": "COMMENTED", "body": null, "submitted_at": "2025-12-02T10:08:10+00:00" }, { "id": 3529284680, "user": "user_5501cd6d3dc8", "state": "COMMENTED", "body": null, "submitted_at": "2025-12-02T10:09:38+00:00" }, { "id": 3613876694, "user": "user_5501cd6d3dc8", "state": "COMMENTED", "body": null, "submitted_at": "2025-12-26T20:51:17+00:00" }, { "id": 3613884734, "user": "user_5501cd6d3dc8", "state": "APPROVED", "body": null, "submitted_at": "2025-12-26T21:04:08+00:00" } ], "review_comments": [ { "id": 2566338258, "user": "user_5501cd6d3dc8", "body": "This is not a regression test. TBH it is not a test at all.", "path": "tests/backends/base/test_base.py", "line": null, "side": "RIGHT", "created_at": "2025-11-26T19:57:10+00:00" }, { "id": 2567491066, "user": "user_5501cd6d3dc8", "body": "Why do you need a new instance of `DatabaseOperations`? Also it should be enough to check that result of `last_executed_query()` is not `None`.\n```suggestion\n\n[USER_REDACTED](connection.vendor == \"oracle\", \"Oracle specific tests\")\nclass TestLastExecutedQueryFallback(TestCase):\n def test_last_executed_query_fallback(self):\n class FakeCursor:\n # Simulates a cursor lacking the `statement` attribute\n pass\n\n cursor = FakeCursor()\n sql = \"SELECT 1\"\n params = []\n\n self.assertIsNotNone(connection.ops.last_executed_query(cursor, sql, params))\n```\n\nWe could also use a real cursor with an invalid SQL statement, e.g.\n```\nwith connection.cursor() as cursor:\n sql = \"INVALID SQL\"\n params = []\n cursor.execute(sql, params)\n self.assertEqual(connection.ops.last_executed_query(cursor, sql, params), sql)\n```", "path": "tests/backends/oracle/test_last_executed_query.py", "line": null, "side": "RIGHT", "created_at": "2025-11-27T07:52:28+00:00" }, { "id": 2567498111, "user": "user_5501cd6d3dc8", "body": "As far as I'm aware it's unnecessary.", "path": "django/db/backends/oracle/operations.py", "line": null, "side": "RIGHT", "created_at": "2025-11-27T07:55:13+00:00" }, { "id": 2580489793, "user": "user_5501cd6d3dc8", "body": "`assertIsNotNone` is redundant\n```suggestion\n self.assertEqual(result, sql)\n```", "path": "tests/backends/oracle/test_last_executed_query.py", "line": null, "side": "RIGHT", "created_at": "2025-12-02T10:06:22+00:00" }, { "id": 2580496057, "user": "user_5501cd6d3dc8", "body": "As far as I'm aware, this test should pass for all database backends, so we can move it to the \n`tests.backends.base.test_operations.DatabaseOperationTests` class.", "path": "tests/backends/oracle/test_last_executed_query.py", "line": null, "side": "RIGHT", "created_at": "2025-12-02T10:08:10+00:00" }, { "id": 2580501766, "user": "user_5501cd6d3dc8", "body": "I think we should use `super().last_executed_query()` only when `statement` is None\n```suggestion\n return super().last_executed_query(cursor, sql, params) if statement is None else statement \n```", "path": "django/db/backends/oracle/operations.py", "line": null, "side": "RIGHT", "created_at": "2025-12-02T10:09:38+00:00" }, { "id": 2648658295, "user": "user_5501cd6d3dc8", "body": "This test pass even without a fix, you need to `close()` the cursor to have a proper regression test.\n```suggestion\n cursor.close()\n cursor.execute(sql, params)\n```", "path": "tests/backends/base/test_operations.py", "line": 180, "side": "RIGHT", "created_at": "2025-12-26T20:51:17+00:00" } ], "meta": { "languages": [ "py" ], "touches_tests": true, "review_state_summary": { "COMMENTED": 7, "APPROVED": 1 }, "meaningful_comment_count": 7, "has_approval": true, "has_changes_requested": false, "total_review_comments": 7 } } { "_id": "54744f87ee7b1b4d", "_schema_version": "1.0", "_cleaned_at": "2026-02-12T07:46:52.101366+00:00", "repo": "django/django", "repo_url": "https://github.com/django/django", "license_name": "BSD 3-Clause \"New\" or \"Revised\" License", "license_spdx": "BSD-3-Clause", "pr_number": 20309, "title": "Fixed #36030 -- Fixed precision loss in division of Decimal literals on SQLite.", "body": "#### Trac ticket number\nticket-36030\n\n#### Branch description\n\nOn SQLite, ``SQLiteNumericMixin.as_sqlite()`` currently wraps all ``DecimalField`` expressions in ``CAST(... AS NUMERIC)``, including literal ``Value(Decimal(...))`` expressions.\nFor these literals, the cast is unnecessary and differs from how other backends pass Decimal parameters.\n\nThe solution decouples ``Value`` from ``SQLiteNumericMixin`` by implementing a dedicated ``as_sqlite`` method that explicitly casts ``Decimal`` literals to ``REAL``, ensuring correct floating-point arithmetic is used. To prevent regressions, the implementation retains the existing ``CAST(... AS NUMERIC)`` wrapper for ``non-Decimal`` types (such as integers) when they are output to a DecimalField.\n\n**Tests**\nA new regression test, ``test_decimal_division_literal_value``, has been added to ``BasicExpressionsTests`` to verify that division yields the correct fractional precision on all backends.\n\n#### Checklist\n- [x] This PR targets the `main` branch.\n- [x] The commit message is written in past tense, mentions the ticket number, and ends with a period.\n- [x] I have checked the \"Has patch\" flag on the Trac ticket.\n- [x] I have added or updated relevant tests.\n- [ ] I have added or updated relevant docs, including release notes if applicable.\n- [ ] I have attached screenshots in light/dark modes for UI changes (N/A).", "author": "user_b787990f7421", "created_at": "2025-11-24T09:31:04+00:00", "merged_at": "2026-01-20T15:42:29+00:00", "base_branch": "main", "head_branch": "ticket-36030-sqlite-decimal-cast", "additions": 23, "deletions": 1, "changed_files": 2, "files": [ { "filename": "django/db/models/expressions.py", "status": "modified", "additions": 13, "deletions": 1, "changes": 14, "patch": "@@ -1141,7 +1141,7 @@ def allowed_default(self):\n \n \n [USER_REDACTED](path=\"django.db.models.Value\")\n-class Value(SQLiteNumericMixin, Expression):\n+class Value(Expression):\n \"\"\"Represent a wrapped value as a node within an expression.\"\"\"\n \n # Provide a default value for `for_save` in order to allow unresolved\n@@ -1182,6 +1182,18 @@ def as_sql(self, compiler, connection):\n return \"NULL\", []\n return \"%s\", [val]\n \n+ def as_sqlite(self, compiler, connection, **extra_context):\n+ sql, params = self.as_sql(compiler, connection, **extra_context)\n+ try:\n+ if self.output_field.get_internal_type() == \"DecimalField\":\n+ if isinstance(self.value, Decimal):\n+ sql = \"(CAST(%s AS REAL))\" % sql\n+ else:\n+ sql = \"(CAST(%s AS NUMERIC))\" % sql\n+ except FieldError:\n+ pass\n+ return sql, params\n+\n def resolve_expression(\n self, query=None, allow_joins=True, reuse=None, summarize=False, for_save=False\n ):" }, { "filename": "tests/expressions/tests.py", "status": "modified", "additions": 10, "deletions": 0, "changes": 10, "patch": "@@ -137,6 +137,16 @@ def test_annotate_values_aggregate(self):\n )\n self.assertEqual(companies[\"result\"], 2395)\n \n+ def test_decimal_division_literal_value(self):\n+ \"\"\"\n+ Division with a literal Decimal value preserves precision.\n+ \"\"\"\n+ num = Number.objects.create(integer=2)\n+ obj = Number.objects.annotate(\n+ val=F(\"integer\") / Value(Decimal(\"3.0\"), output_field=DecimalField())\n+ ).get(pk=num.pk)\n+ self.assertAlmostEqual(obj.val, Decimal(\"0.6667\"), places=4)\n+\n def test_annotate_values_filter(self):\n companies = (\n Company.objects.annotate(" } ], "reviews": [ { "id": 3621982362, "user": "user_29c7f89aae54", "state": "APPROVED", "body": "This appears to fix the problem as far as I can tell. Your test passes with the fix and fails without it (which is what we want). Same is true for the repro case at the top of the ticket. I personally would have been inclined to write the test so that it's verifying the correctness of the observable outcome (along the lines of that repro case), rather than the mechanics of the solution. But I'll leave it to those higher up the food chain than I am to decide whether that should prevent the PR from being accepted and applied.", "submitted_at": "2026-01-01T17:34:25+00:00" }, { "id": 3671302369, "user": "user_3a67c55598c5", "state": "COMMENTED", "body": "Thanks, nice start [USER_REDACTED] 👍", "submitted_at": "2026-01-16T15:18:02+00:00" }, { "id": 3671536892, "user": "user_29c7f89aae54", "state": "COMMENTED", "body": null, "submitted_at": "2026-01-16T15:48:22+00:00" }, { "id": 3671615447, "user": "user_3a67c55598c5", "state": "COMMENTED", "body": null, "submitted_at": "2026-01-16T16:07:05+00:00" }, { "id": 3671975249, "user": "user_29c7f89aae54", "state": "COMMENTED", "body": null, "submitted_at": "2026-01-16T17:34:19+00:00" }, { "id": 3672000676, "user": "user_3a67c55598c5", "state": "COMMENTED", "body": null, "submitted_at": "2026-01-16T17:41:22+00:00" }, { "id": 3678319676, "user": "user_3a67c55598c5", "state": "APPROVED", "body": null, "submitted_at": "2026-01-19T14:19:08+00:00" } ], "review_comments": [ { "id": 2698862894, "user": "user_3a67c55598c5", "body": "Instead of adding an if/else switch here, did you consider just implementing `Value.as_sqlite()` and removing this mixin from that class?", "path": "django/db/models/expressions.py", "line": null, "side": "RIGHT", "created_at": "2026-01-16T15:03:45+00:00" }, { "id": 2698880947, "user": "user_3a67c55598c5", "body": "We avoid preambles like \"verify\" in test docstrings.", "path": "tests/expressions/test_sqlite.py", "line": null, "side": "RIGHT", "created_at": "2026-01-16T15:08:01+00:00" }, { "id": 2698881728, "user": "user_3a67c55598c5", "body": "\"behavior\" isn't specific.", "path": "tests/expressions/test_sqlite.py", "line": null, "side": "RIGHT", "created_at": "2026-01-16T15:08:11+00:00" }, { "id": 2698885469, "user": "user_3a67c55598c5", "body": "As [USER_REDACTED] mentioned, we usually avoid asserting over the underlying SQL. The other test should be sufficient.", "path": "tests/expressions/test_sqlite.py", "line": null, "side": "RIGHT", "created_at": "2026-01-16T15:09:08+00:00" }, { "id": 2698895065, "user": "user_3a67c55598c5", "body": "I think we want this test to run on all backends. So instead of placing it in a `test_sqlite` file, can you place it right after the test that was added for this casting behavior in the first place, i.e. right after `test_filter_decimal_annotation()`?", "path": "tests/expressions/test_sqlite.py", "line": null, "side": "RIGHT", "created_at": "2026-01-16T15:11:40+00:00" }, { "id": 2698915464, "user": "user_3a67c55598c5", "body": "If we're only comparing four places, I'd adjust the second arg to use four places.", "path": "tests/expressions/test_sqlite.py", "line": null, "side": "RIGHT", "created_at": "2026-01-16T15:17:03+00:00" }, { "id": 2698917175, "user": "user_3a67c55598c5", "body": "I think you can chop this comment.", "path": "tests/expressions/test_sqlite.py", "line": null, "side": "RIGHT", "created_at": "2026-01-16T15:17:27+00:00" }, { "id": 2699035518, "user": "user_29c7f89aae54", "body": "Hi, [USER_REDACTED]. The original ticket was not specific to SQLite (the original reporter was using PostgreSQL), but the ticket was repurposed (based on an interpretation of what [USER_REDACTED] intended in the comment she posted December 20, 2024 when the ticket was accepted) narrowing it to the SQLite back end. Should we restore the broader focus of the ticket? I don't believe the new test will pass with PostgreSQL unless the PR is expanded (in the direction of the previous PR which was rejected).", "path": "tests/expressions/test_sqlite.py", "line": null, "side": "RIGHT", "created_at": "2026-01-16T15:48:22+00:00" }, { "id": 2699104906, "user": "user_3a67c55598c5", "body": "This test as written passes on postgres (and currently runs on postgres; there is no skip decorator on it).", "path": "tests/expressions/test_sqlite.py", "line": null, "side": "RIGHT", "created_at": "2026-01-16T16:07:05+00:00" }, { "id": 2699392279, "user": "user_29c7f89aae54", "body": "You're absolutely right. I stand corrected. 😊", "path": "tests/expressions/test_sqlite.py", "line": null, "side": "RIGHT", "created_at": "2026-01-16T17:34:19+00:00" }, { "id": 2699412217, "user": "user_3a67c55598c5", "body": "no worries, appreciate having your eyes on it!", "path": "tests/expressions/test_sqlite.py", "line": null, "side": "RIGHT", "created_at": "2026-01-16T17:41:22+00:00" }, { "id": 2704961829, "user": "user_3a67c55598c5", "body": "Thanks, I think this is a good idea for now given that we are checking `self.value` below. We may find similar edge cases with the other expressions that would involve different kinds of introspection `self.cases`, `self.source_expressions`, etc., but we can cross that bridge later.", "path": "django/db/models/expressions.py", "line": 1185, "side": "RIGHT", "created_at": "2026-01-19T14:18:05+00:00" } ], "meta": { "languages": [ "py" ], "touches_tests": true, "review_state_summary": { "APPROVED": 2, "COMMENTED": 5 }, "meaningful_comment_count": 12, "has_approval": true, "has_changes_requested": false, "total_review_comments": 12 } } { "_id": "f96a9f6e0b607f8a", "_schema_version": "1.0", "_cleaned_at": "2026-02-12T07:46:52.101366+00:00", "repo": "django/django", "repo_url": "https://github.com/django/django", "license_name": "BSD 3-Clause \"New\" or \"Revised\" License", "license_spdx": "BSD-3-Clause", "pr_number": 20303, "title": "Fixed #36751 -- Fixed empty filtered aggregation crash over annotated queryset.", "body": "#### Trac ticket number\nticket-36404\n\n#### Branch description\nRegression in b8e5a8a9a2a767f584cbe89a878a42363706f939.\n\nRefs ticket-36404.\n\nThe `replace_expressions` method was innapropriately dealing with falsey but not `None` source expressions causing them to also be potentially evaluated when `__bool__` was invoked (e.g. `QuerySet.__bool__` evalutates the query).\n\nThe changes introduced in b8e5a8a9a2, which were to deal with a similar issue, surfaced the problem as aggregation over an annotated queryset requires an inlining (or pushdown) of aggregate references which is achieved through `replace_expressions`.\n\nIn cases where an empty `Q` objects was provided as an aggregate filter, such as when the admin facetting feature was used as reported, it would wrongly be turned into `None`, instead of an empty `WhereNode`, causing a crash at aggregate filter compilation.\n\nNote that the crash signature differed depending on whether or not the backend natively supports aggregate filtering (`supports_aggregate_filter_clause`) as the fallback, which makes use `Case` / `When` expressions, would result in a `TypeError` instead of a `NoneType` `AttributeError`.\n\nThanks [USER_REDACTED] for the report, Antoliny and [USER_REDACTED] for the triage.", "author": "user_cdda8932ec17", "created_at": "2025-11-23T16:49:28+00:00", "merged_at": "2025-11-24T11:14:38+00:00", "base_branch": "main", "head_branch": "ticket-36751", "additions": 34, "deletions": 1, "changed_files": 4, "files": [ { "filename": "django/db/models/expressions.py", "status": "modified", "additions": 1, "deletions": 1, "changes": 2, "patch": "@@ -426,7 +426,7 @@ def replace_expressions(self, replacements):\n clone = self.copy()\n clone.set_source_expressions(\n [\n- expr.replace_expressions(replacements) if expr else None\n+ None if expr is None else expr.replace_expressions(replacements)\n for expr in source_expressions\n ]\n )" }, { "filename": "docs/releases/5.2.9.txt", "status": "modified", "additions": 4, "deletions": 0, "changes": 4, "patch": "@@ -16,3 +16,7 @@ Bugfixes\n \n * Fixed a bug in Django 5.2 on PostgreSQL where ``bulk_create()`` did not apply\n a field's custom query placeholders (:ticket:`36748`).\n+\n+* Fixed a regression in Django 5.2.2 that caused a crash when using aggregate\n+ functions with an empty ``Q`` filter over a queryset with annotations\n+ (:ticket:`36751`)." }, { "filename": "tests/aggregation/test_filter_argument.py", "status": "modified", "additions": 11, "deletions": 0, "changes": 11, "patch": "@@ -88,6 +88,17 @@ def test_empty_filtered_aggregates(self):\n agg = Count(\"pk\", filter=Q())\n self.assertEqual(Author.objects.aggregate(count=agg)[\"count\"], 3)\n \n+ def test_empty_filtered_aggregates_with_annotation(self):\n+ agg = Count(\"pk\", filter=Q())\n+ self.assertEqual(\n+ Author.objects.annotate(\n+ age_annotation=F(\"age\"),\n+ ).aggregate(\n+ count=agg\n+ )[\"count\"],\n+ 3,\n+ )\n+\n def test_double_filtered_aggregates(self):\n agg = Sum(\"age\", filter=Q(Q(name=\"test2\") & ~Q(name=\"test\")))\n self.assertEqual(Author.objects.aggregate(age=agg)[\"age\"], 60)" }, { "filename": "tests/expressions/tests.py", "status": "modified", "additions": 18, "deletions": 0, "changes": 18, "patch": "@@ -1571,6 +1571,24 @@ def test_get_expression_for_validation_only_one_source_expression(self):\n with self.assertRaisesMessage(ValueError, msg):\n expression.get_expression_for_validation()\n \n+ def test_replace_expressions_falsey(self):\n+ class AssignableExpression(Expression):\n+ def __init__(self, *source_expressions):\n+ super().__init__()\n+ self.set_source_expressions(list(source_expressions))\n+\n+ def get_source_expressions(self):\n+ return self.source_expressions\n+\n+ def set_source_expressions(self, exprs):\n+ self.source_expressions = exprs\n+\n+ expression = AssignableExpression()\n+ falsey = Q()\n+ expression.set_source_expressions([falsey])\n+ replaced = expression.replace_expressions({\"replacement\": Expression()})\n+ self.assertEqual(replaced.get_source_expressions(), [falsey])\n+\n \n class ExpressionsNumericTests(TestCase):\n [USER_REDACTED]" } ], "reviews": [ { "id": 3497930488, "user": "user_f3baca6f249c", "state": "COMMENTED", "body": "I can confirm that this PR resolves the issue observed in ticket-36751 👍", "submitted_at": "2025-11-23T18:32:03+00:00" }, { "id": 3498174806, "user": "user_cdda8932ec17", "state": "COMMENTED", "body": null, "submitted_at": "2025-11-24T01:46:45+00:00" } ], "review_comments": [ { "id": 2554485923, "user": "user_cdda8932ec17", "body": "I wanted to use `Expression` directly but it doesn't allow assignment of `source_expressions`\n\nhttps://github.com/[USER_REDACTED]ngo/django/blob/ec60df6d1ea8939a316d9b180faa0b4ef2e83606/django/db/models/expressions.py#L212-L213", "path": "tests/expressions/tests.py", "line": 1575, "side": "RIGHT", "created_at": "2025-11-24T01:44:23+00:00" }, { "id": 2554486756, "user": "user_cdda8932ec17", "body": "We could use any object with a `__bool__() -> False` but I figured it was simpler to use `Q` directly since it's the case that triggered the reported problem.", "path": "tests/expressions/tests.py", "line": 1587, "side": "RIGHT", "created_at": "2025-11-24T01:45:50+00:00" }, { "id": 2554487267, "user": "user_cdda8932ec17", "body": "As mentionned in the commit message this would have caused objects such as `QuerySet` to be evaluated as replacement as well (since `QuerySet.__bool__` executes the query).", "path": "django/db/models/expressions.py", "line": 429, "side": "RIGHT", "created_at": "2025-11-24T01:46:42+00:00" } ], "meta": { "languages": [ "py", "txt" ], "touches_tests": true, "review_state_summary": { "COMMENTED": 2 }, "meaningful_comment_count": 3, "has_approval": false, "has_changes_requested": false, "total_review_comments": 3 } } { "_id": "2e04ca8575374a61", "_schema_version": "1.0", "_cleaned_at": "2026-02-12T07:46:52.116991+00:00", "repo": "django/django", "repo_url": "https://github.com/django/django", "license_name": "BSD 3-Clause \"New\" or \"Revised\" License", "license_spdx": "BSD-3-Clause", "pr_number": 20302, "title": "Fixed #36620 -- Fixed workflow to summarize coverage in PRs.", "body": "ref - https://github.com/[USER_REDACTED]ngo/django/pull/19777#issuecomment-3567658385\n\nThe coverage workflow was reporting \"No lines with coverage information in this diff\" even when PRs contained changes to Python files that were executed during tests.\n\nsince we switched to `pull_request_target`, which by [NAME_REDACTED] **base branch** (main) instead of the PR branch. \n\n### [NAME_REDACTED] explicit checkout of the PR branch using `ref: ${{ github.event.pull_request.head.sha }}`:\n\n```yaml\n- name: Checkout\n uses: actions/checkout@v5\n with:\n ref: ${{ github.event.pull_request.head.sha }} # ← Checkout PR code\n fetch-depth: 0\n persist-credentials: false\n```", "author": "user_29c6277a8a3f", "created_at": "2025-11-23T09:41:30+00:00", "merged_at": "2025-12-04T15:25:21+00:00", "base_branch": "main", "head_branch": "fix-coverage", "additions": 149, "deletions": 0, "changed_files": 4, "files": [ { "filename": ".github/workflows/coverage_comment.yml", "status": "added", "additions": 72, "deletions": 0, "changes": 72, "patch": "@@ -0,0 +1,72 @@\n+name: [NAME_REDACTED]\n+\n+on:\n+ workflow_run:\n+ workflows: [\"[NAME_REDACTED]\"]\n+ types:\n+ - completed\n+\n+permissions:\n+ contents: read\n+ pull-requests: write\n+\n+jobs:\n+ comment:\n+ if: >\n+ github.event.workflow_run.event == 'pull_request' &&\n+ github.event.workflow_run.conclusion == 'success' &&\n+ github.repository == 'django/django' &&\n+ github.event.workflow_run.pull_requests[0] != null\n+ name: [NAME_REDACTED]\n+ runs-on: ubuntu-latest\n+ timeout-minutes: 60\n+ steps:\n+ - name: Download diff coverage report\n+ uses: actions/download-artifact@v4\n+ with:\n+ name: diff-coverage-report-${{ github.event.workflow_run.pull_requests[0].number }}\n+ github-token: ${{ secrets.GITHUB_TOKEN }}\n+ run-id: ${{ github.event.workflow_run.id }}\n+\n+ - name: Post/update PR comment\n+ env:\n+ PR_NUMBER: ${{ github.event.workflow_run.pull_requests[0].number }}\n+ uses: actions/github-script@v8\n+ with:\n+ script: |\n+ const fs = require('fs');\n+ const reportPath = 'diff-cover-report.md';\n+ let body = 'No coverage data available.';\n+ if (fs.existsSync(reportPath)) {\n+ body = fs.readFileSync(reportPath, 'utf8');\n+ }\n+ const commentBody = '### 📊 [NAME_REDACTED] for Changed Files\\n\\n```\\n' + body + '\\n```\\n\\n**Note:** Missing lines are warnings only. Some lines may not be covered by [NAME_REDACTED] are database-specific.\\n\\nFor more information about code coverage on pull requests, see the [contributing documentation](https://docs.djangoproject.com/en/dev/internals/contributing/writing-code/unit-tests/#code-coverage-on-pull-requests).';\n+\n+ const prNumber = parseInt(process.env.PR_NUMBER);\n+ if (isNaN(prNumber)) {\n+ core.setFailed('PR number is not available or invalid.');\n+ return;\n+ }\n+ \n+ const { data: comments } = await github.rest.issues.listComments({\n+ owner: context.repo.owner,\n+ repo: context.repo.repo,\n+ issue_number: prNumber,\n+ });\n+ \n+ for (const c of comments) {\n+ if ((c.body || '').includes('📊 [NAME_REDACTED] for Changed Files')) {\n+ await github.rest.issues.deleteComment({\n+ owner: context.repo.owner,\n+ repo: context.repo.repo,\n+ comment_id: c.id,\n+ });\n+ }\n+ }\n+\n+ await github.rest.issues.createComment({\n+ owner: context.repo.owner,\n+ repo: context.repo.repo,\n+ issue_number: prNumber,\n+ body: commentBody,\n+ });" }, { "filename": ".github/workflows/coverage_tests.yml", "status": "added", "additions": 75, "deletions": 0, "changes": 75, "patch": "@@ -0,0 +1,75 @@\n+name: [NAME_REDACTED]\n+\n+on:\n+ pull_request:\n+ paths-ignore:\n+ - 'docs/**'\n+ - '**/*.md'\n+\n+concurrency:\n+ group: ${{ github.workflow }}-${{ github.ref }}\n+ cancel-in-progress: true\n+\n+permissions:\n+ contents: read\n+\n+jobs:\n+ coverage:\n+ if: github.repository == 'django/django'\n+ name: [NAME_REDACTED] (Windows)\n+ runs-on: windows-latest\n+ timeout-minutes: 60\n+ steps:\n+ - name: Checkout\n+ uses: actions/checkout@v5\n+ with:\n+ fetch-depth: 0\n+ persist-credentials: false\n+\n+ - name: Set up Python\n+ uses: actions/setup-python@v6\n+ with:\n+ python-version: '3.14'\n+ cache: 'pip'\n+ cache-dependency-path: 'tests/requirements/py3.txt'\n+\n+ - name: Install dependencies\n+ run: |\n+ python -m pip install --upgrade pip wheel\n+ python -m pip install -r tests/requirements/py3.txt -e .\n+ python -m pip install 'coverage[toml]' diff-cover\n+\n+ - name: Run tests with coverage\n+ env:\n+ PYTHONPATH: ${{ github.workspace }}/tests\n+ COVERAGE_PROCESS_START: ${{ github.workspace }}/tests/.coveragerc\n+ RUNTESTS_DIR: ${{ github.workspace }}/tests\n+ run: |\n+ python -Wall tests/runtests.py -v2\n+\n+ - name: Generate coverage report\n+ if: success()\n+ env:\n+ COVERAGE_RCFILE: ${{ github.workspace }}/tests/.coveragerc\n+ RUNTESTS_DIR: ${{ github.workspace }}/tests\n+ run: |\n+ python -m coverage combine\n+ python -m coverage report --show-missing\n+ python -m coverage xml -o tests/coverage.xml\n+\n+ - name: Generate diff coverage report\n+ if: success()\n+ run: |\n+ if (Test-Path 'tests/coverage.xml') {\n+ diff-cover tests/coverage.xml --compare-branch=origin/main --fail-under=0 > diff-cover-report.md\n+ } else {\n+ Set-Content -Path diff-cover-report.md -Value 'No coverage data available.'\n+ }\n+\n+ - name: Upload diff coverage report\n+ if: success()\n+ uses: actions/upload-artifact@v4\n+ with:\n+ name: diff-coverage-report-${{ github.event.pull_request.number }}\n+ path: diff-cover-report.md\n+ retention-days: 1" }, { "filename": ".github/workflows/tests.yml", "status": "modified", "additions": 1, "deletions": 0, "changes": 1, "patch": "@@ -19,6 +19,7 @@ permissions:\n \n jobs:\n windows:\n+ if: github.event_name == 'push'\n runs-on: windows-latest\n strategy:\n matrix:" }, { "filename": "zizmor.yml", "status": "modified", "additions": 1, "deletions": 0, "changes": 1, "patch": "@@ -1,6 +1,7 @@\n rules:\n dangerous-triggers:\n ignore:\n+ - coverage_comment.yml\n - labels.yml\n - new_contributor_pr.yml\n unpinned-uses:" } ], "reviews": [ { "id": 3497897614, "user": "user_3a67c55598c5", "state": "COMMENTED", "body": "Thanks for the quick response 👍", "submitted_at": "2025-11-23T17:12:38+00:00" }, { "id": 3497907698, "user": "user_29c6277a8a3f", "state": "COMMENTED", "body": null, "submitted_at": "2025-11-23T17:28:32+00:00" }, { "id": 3497908065, "user": "user_29c6277a8a3f", "state": "COMMENTED", "body": null, "submitted_at": "2025-11-23T17:29:41+00:00" }, { "id": 3497911368, "user": "user_3a67c55598c5", "state": "COMMENTED", "body": null, "submitted_at": "2025-11-23T17:37:12+00:00" }, { "id": 3497912511, "user": "user_29c6277a8a3f", "state": "COMMENTED", "body": null, "submitted_at": "2025-11-23T17:40:45+00:00" }, { "id": 3497917680, "user": "user_3a67c55598c5", "state": "COMMENTED", "body": null, "submitted_at": "2025-11-23T17:56:10+00:00" }, { "id": 3501347175, "user": "user_29c6277a8a3f", "state": "COMMENTED", "body": null, "submitted_at": "2025-11-24T16:47:33+00:00" }, { "id": 3506874044, "user": "user_3a67c55598c5", "state": "COMMENTED", "body": null, "submitted_at": "2025-11-25T21:22:25+00:00" }, { "id": 3532106230, "user": "user_3a67c55598c5", "state": "COMMENTED", "body": "Thanks for the updates 👍", "submitted_at": "2025-12-02T21:09:41+00:00" }, { "id": 3534624043, "user": "user_29c6277a8a3f", "state": "COMMENTED", "body": null, "submitted_at": "2025-12-03T11:32:21+00:00" }, { "id": 3535141732, "user": "user_3a67c55598c5", "state": "COMMENTED", "body": "Looking great, after this round I'll test on my fork.", "submitted_at": "2025-12-03T13:49:32+00:00" }, { "id": 3535144724, "user": "user_3a67c55598c5", "state": "COMMENTED", "body": null, "submitted_at": "2025-12-03T13:50:16+00:00" }, { "id": 3535293398, "user": "user_29c6277a8a3f", "state": "COMMENTED", "body": null, "submitted_at": "2025-12-03T14:18:40+00:00" }, { "id": 3535758295, "user": "user_3a67c55598c5", "state": "COMMENTED", "body": null, "submitted_at": "2025-12-03T15:55:32+00:00" }, { "id": 3536051045, "user": "user_3a67c55598c5", "state": "COMMENTED", "body": "Great, this is working well!", "submitted_at": "2025-12-03T17:19:55+00:00" }, { "id": 3536282060, "user": "user_29c6277a8a3f", "state": "COMMENTED", "body": null, "submitted_at": "2025-12-03T17:58:57+00:00" }, { "id": 3536312572, "user": "user_29c6277a8a3f", "state": "COMMENTED", "body": null, "submitted_at": "2025-12-03T18:08:33+00:00" }, { "id": 3536410875, "user": "user_3a67c55598c5", "state": "COMMENTED", "body": null, "submitted_at": "2025-12-03T18:38:03+00:00" }, { "id": 3536547488, "user": "user_29c6277a8a3f", "state": "COMMENTED", "body": null, "submitted_at": "2025-12-03T19:14:02+00:00" }, { "id": 3536652660, "user": "user_3a67c55598c5", "state": "COMMENTED", "body": null, "submitted_at": "2025-12-03T19:44:22+00:00" }, { "id": 3539153746, "user": "user_29c6277a8a3f", "state": "COMMENTED", "body": null, "submitted_at": "2025-12-04T10:16:42+00:00" }, { "id": 3540174444, "user": "user_3a67c55598c5", "state": "COMMENTED", "body": null, "submitted_at": "2025-12-04T13:56:55+00:00" }, { "id": 3540528931, "user": "user_3a67c55598c5", "state": "APPROVED", "body": "Thanks [USER_REDACTED], really appreciate the extra care here.", "submitted_at": "2025-12-04T15:18:38+00:00" } ], "review_comments": [ { "id": 2554209789, "user": "user_3a67c55598c5", "body": "Can we use this as an opportunity to revisit the need for `pull_request_target`? I see the earlier draft of the feature PR on your fork used `pull_request` and `permissions: pull-requests: write` -- can you catch me up on why that was removed?", "path": ".github/workflows/coverage.yml", "line": null, "side": "RIGHT", "created_at": "2025-11-23T17:12:07+00:00" }, { "id": 2554210071, "user": "user_3a67c55598c5", "body": "please revert.", "path": ".github/workflows/coverage.yml", "line": null, "side": "RIGHT", "created_at": "2025-11-23T17:12:35+00:00" }, { "id": 2554218365, "user": "user_29c6277a8a3f", "body": "cause `pull_request` doesn't have write permissions for PRs from forks.\nsee - [ref](https://docs.github.com/en/actions/reference/workflows-and-actions/events-that-trigger-workflows#pull_request_target)", "path": ".github/workflows/coverage.yml", "line": null, "side": "RIGHT", "created_at": "2025-11-23T17:28:32+00:00" }, { "id": 2554218890, "user": "user_29c6277a8a3f", "body": "added this as sarah suggested [here](https://github.com/0saurabh0/django/pull/6#issuecomment-3219300658)\nShould I remove?", "path": ".github/workflows/coverage.yml", "line": null, "side": "RIGHT", "created_at": "2025-11-23T17:29:41+00:00" }, { "id": 2554222454, "user": "user_3a67c55598c5", "body": "We should have the newline like Sarah mentioned, but as I see in the diff the PR removes the newline.", "path": ".github/workflows/coverage.yml", "line": null, "side": "RIGHT", "created_at": "2025-11-23T17:37:12+00:00" }, { "id": 2554224150, "user": "user_29c6277a8a3f", "body": "ah, my bad.\nwill do.", "path": ".github/workflows/coverage.yml", "line": null, "side": "RIGHT", "created_at": "2025-11-23T17:40:45+00:00" }, { "id": 2554232041, "user": "user_3a67c55598c5", "body": "Right, okay. Based on my level of understanding right now, I'm not comfortable checking out user-controlled code under a `pull_request_target` action.\n\nThe advice here (granted it's 4 years old) is to have a two-workflow solution that passes the diff report as an artifact to the workflow with the write permission:\nhttps://securitylab.github.com/resources/github-actions-preventing-pwn-requests/", "path": ".github/workflows/coverage.yml", "line": null, "side": "RIGHT", "created_at": "2025-11-23T17:56:10+00:00" }, { "id": 2557031325, "user": "user_29c6277a8a3f", "body": "> Right, okay. Based on my level of understanding right now, I'm not comfortable checking out user-controlled code under a `pull_request_target` action.\n\nwe can't run user code, but can use the code for git diff (passive data reading)? right?", "path": ".github/workflows/coverage.yml", "line": null, "side": "RIGHT", "created_at": "2025-11-24T16:47:33+00:00" }, { "id": 2561463881, "user": "user_3a67c55598c5", "body": "We can check out user code under the `pull_request` trigger, not the `pull_request_target` one, because it limits secrets access and write permissions. The existing `python_matrix.yml` and `tests.yml` do this. So the idea would be to run the user code under that safer sandbox, generate the artifact, and then pass it along to the workflow that will write the comment (under the `pull_request_target` trigger).", "path": ".github/workflows/coverage.yml", "line": null, "side": "RIGHT", "created_at": "2025-11-25T21:22:25+00:00" }, { "id": 2582776028, "user": "user_3a67c55598c5", "body": "My idea behind splitting the workflows was to avoid having to checkout out an untrusted ref under `pull_request_target` or `pull-requests: write`, so are we able to just skip this? (If not, I imagine we could move generating the diff-cover artifact into the other workflow.)\n```suggestion\n```", "path": ".github/workflows/coverage-comment.yml", "line": null, "side": "RIGHT", "created_at": "2025-12-02T21:06:02+00:00" }, { "id": 2582782368, "user": "user_3a67c55598c5", "body": "Need a newline instead of indentation, same in the other file.", "path": ".github/workflows/coverage-comment.yml", "line": null, "side": "RIGHT", "created_at": "2025-12-02T21:08:45+00:00" }, { "id": 2582782833, "user": "user_3a67c55598c5", "body": "The other workflow files use underscores.", "path": "zizmor.yml", "line": null, "side": "RIGHT", "created_at": "2025-12-02T21:08:58+00:00" }, { "id": 2584756104, "user": "user_29c6277a8a3f", "body": "yes, updated", "path": ".github/workflows/coverage-comment.yml", "line": null, "side": "RIGHT", "created_at": "2025-12-03T11:32:21+00:00" }, { "id": 2585195996, "user": "user_3a67c55598c5", "body": "Now that we have two workflows, can we use the `workflow_call` [trigger](https://docs.github.com/en/actions/how-tos/reuse-automations/reuse-workflows) to avoid this ignore?", "path": "zizmor.yml", "line": 4, "side": "RIGHT", "created_at": "2025-12-03T13:50:16+00:00" }, { "id": 2585309553, "user": "user_29c6277a8a3f", "body": "With `workflow_call`, wouldn't the called workflow would inherit the limited permissions from the fork PR context and couldn't post comments?", "path": "zizmor.yml", "line": 4, "side": "RIGHT", "created_at": "2025-12-03T14:18:40+00:00" }, { "id": 2585685387, "user": "user_3a67c55598c5", "body": "Ah got it, thanks. Testing on my fork now.", "path": "zizmor.yml", "line": 4, "side": "RIGHT", "created_at": "2025-12-03T15:55:32+00:00" }, { "id": 2585914588, "user": "user_3a67c55598c5", "body": "This would be nice to avoid windows shell commands\n\n```suggestion\n runs-on: ubuntu-latest\n```", "path": ".github/workflows/coverage_comment.yml", "line": null, "side": "RIGHT", "created_at": "2025-12-03T16:56:13+00:00" }, { "id": 2585916822, "user": "user_3a67c55598c5", "body": "If we're extracting the pr number here, do we need to have a pr_number.txt artifact?", "path": ".github/workflows/coverage_comment.yml", "line": null, "side": "RIGHT", "created_at": "2025-12-03T16:56:53+00:00" }, { "id": 2585939027, "user": "user_3a67c55598c5", "body": "Pardon me if asked before, but does this need a `push` trigger?", "path": ".github/workflows/coverage_tests.yml", "line": 4, "side": "RIGHT", "created_at": "2025-12-03T17:03:39+00:00" }, { "id": 2585948115, "user": "user_3a67c55598c5", "body": "We recently added timeout-minutes: 60 to all jobs, so please add that here also.", "path": ".github/workflows/coverage_tests.yml", "line": 4, "side": "RIGHT", "created_at": "2025-12-03T17:06:30+00:00" }, { "id": 2585956184, "user": "user_3a67c55598c5", "body": "I didn't mention before, but this duplicates exactly the configuration of tests.yml (other than enabling coverage). What do you think: should we just rely on this workflow to run tests, and then limit the tests.yml job to run on pushes to main (instead of PRs?)\n\nIf we do that, then we will want to remove the `branches: main` limitation we added earlier in the coverage tests workflow (so we can still get runs on backport PRs).", "path": ".github/workflows/coverage_tests.yml", "line": 32, "side": "RIGHT", "created_at": "2025-12-03T17:09:02+00:00" }, { "id": 2586110284, "user": "user_29c6277a8a3f", "body": "hmm, we should be able to use that directly.\nchecking locally.", "path": ".github/workflows/coverage_comment.yml", "line": null, "side": "RIGHT", "created_at": "2025-12-03T17:58:57+00:00" }, { "id": 2586136018, "user": "user_29c6277a8a3f", "body": "I don’t think so, this workflow is specifically meant to generate coverage reports for PR comments, and `coverage_comment.yml` only runs when the triggering workflow was a pull request. Push events wouldn’t generate PR comments anyway.", "path": ".github/workflows/coverage_tests.yml", "line": 4, "side": "RIGHT", "created_at": "2025-12-03T18:08:33+00:00" }, { "id": 2586217855, "user": "user_3a67c55598c5", "body": "Got it, was just curious if the event would still trigger when pushing additional commits to a PR, looks like it should 👍", "path": ".github/workflows/coverage_tests.yml", "line": 4, "side": "RIGHT", "created_at": "2025-12-03T18:38:03+00:00" }, { "id": 2586314137, "user": "user_29c6277a8a3f", "body": "I see the duplication concern, but :\n- The coverage workflow only triggers on `django/**/*.py` and `tests/**/*.py` changes - PRs that modify test fixtures, templates, or config files wouldn't run ANY tests.\n- JavaScript tests would stop running on PRs.\n- Could we instead just remove the branches: - main restriction from the coverage workflow (so backport PRs get coverage too) and accept the ~5 min duplication on PRs to main? \nOr should we broaden the `paths` filter in the coverage workflow to match the `paths-ignore` behavior of `tests.yml`?\"\n\ndon't know if I'm overthinking, but let me know.", "path": ".github/workflows/coverage_tests.yml", "line": 32, "side": "RIGHT", "created_at": "2025-12-03T19:14:01+00:00" }, { "id": 2586395383, "user": "user_3a67c55598c5", "body": "> Or should we broaden the paths filter in the coverage workflow to match the paths-ignore behavior of tests.yml?\"\n\nI like this, it goes back in the direction you had originally but now we have a concrete reason to prefer it 👍 . There aren't so many PRs that only touch javascript.", "path": ".github/workflows/coverage_tests.yml", "line": 32, "side": "RIGHT", "created_at": "2025-12-03T19:44:21+00:00" }, { "id": 2588405428, "user": "user_29c6277a8a3f", "body": "Accessing `pull_requests[0]` without null-checking could result in `NaN` being passed to GitHub API calls. While the job condition requires `event == 'pull_request'`, the `pull_requests` array may be empty in edge cases;\nand can lead to breaking subsequent API operations?\n\nyou think we need to catch this?", "path": ".github/workflows/coverage_comment.yml", "line": 27, "side": "RIGHT", "created_at": "2025-12-04T10:16:42+00:00" }, { "id": 2589191311, "user": "user_3a67c55598c5", "body": "Yes, it's easy enough, let's null check.", "path": ".github/workflows/coverage_comment.yml", "line": 27, "side": "RIGHT", "created_at": "2025-12-04T13:56:55+00:00" }, { "id": 2589484703, "user": "user_3a67c55598c5", "body": "Just leaving a comment for visibility -- we decided to limit this to push events to reduce the exact duplication (on PRs) of the test configuration with and without coverage enabled. We can revisit this once we're ready to start testing more configurations on github actions.", "path": ".github/workflows/tests.yml", "line": 22, "side": "RIGHT", "created_at": "2025-12-04T15:15:30+00:00" } ], "meta": { "languages": [ "yml" ], "touches_tests": false, "review_state_summary": { "COMMENTED": 22, "APPROVED": 1 }, "meaningful_comment_count": 29, "has_approval": true, "has_changes_requested": false, "total_review_comments": 29 } } { "_id": "fdd6a467d63f2140", "_schema_version": "1.0", "_cleaned_at": "2026-02-12T07:46:52.116991+00:00", "repo": "django/django", "repo_url": "https://github.com/django/django", "license_name": "BSD 3-Clause \"New\" or \"Revised\" License", "license_spdx": "BSD-3-Clause", "pr_number": 20295, "title": "Fixed #36747 -- Added support for parsing weeks in django.utils.dateparse.parse_duration().", "body": "#### Trac ticket number\n\n\nticket-36747 \n\n#### Branch description\nAdded support for parsing weeks in ISO 8601 duration strings (e.g., 'P4W') within django.utils.dateparse.parse_duration(). Previously, this would return None.\n\nThis PR also updates the docstrings and documentation to explicitly clarify that while ISO 8601 duration parsing is supported, years (Y) and months (M) remain unsupported\n\n#### Checklist\n- [x] This PR targets the `main` branch. \n- [x] The commit message is written in past tense, mentions the ticket number, and ends with a period.\n- [x] I have checked the \"Has patch\" ticket flag in the Trac system.\n- [x] I have added or updated relevant tests.\n- [x] I have added or updated relevant docs, including release notes if applicable.\n- [ ] I have attached screenshots in both light and dark modes for any UI changes.", "author": "user_95f516637e24", "created_at": "2025-11-22T12:25:40+00:00", "merged_at": "2025-12-17T15:19:05+00:00", "base_branch": "main", "head_branch": "ticket-36747", "additions": 19, "deletions": 4, "changed_files": 4, "files": [ { "filename": "django/utils/dateparse.py", "status": "modified", "additions": 3, "deletions": 2, "changes": 5, "patch": "@@ -40,6 +40,7 @@\n iso8601_duration_re = _lazy_re_compile(\n r\"^(?P[-+]?)\"\n r\"P\"\n+ r\"(?:(?P\\d+([.,]\\d+)?)W)?\"\n r\"(?:(?P\\d+([.,]\\d+)?)D)?\"\n r\"(?:T\"\n r\"(?:(?P\\d+([.,]\\d+)?)H)?\"\n@@ -134,8 +135,8 @@ def parse_duration(value):\n \n The preferred format for durations in Django is '%d %H:%M:%S.%f'.\n \n- Also supports ISO 8601 representation and PostgreSQL's day-time interval\n- format.\n+ Also supports ISO 8601 representation (excluding years and months) and\n+ PostgreSQL's day-time interval format.\n \"\"\"\n match = (\n standard_duration_re.match(value)" }, { "filename": "docs/ref/utils.txt", "status": "modified", "additions": 9, "deletions": 0, "changes": 9, "patch": "@@ -147,6 +147,15 @@ The functions defined in this module share the following properties:\n ``P4DT1H15M20S`` which is equivalent to ``4 1:15:20``) or PostgreSQL's\n day-time interval format (e.g. ``3 days 04:05:06``).\n \n+ .. admonition:: Years and months not supported\n+\n+ ISO 8601 years (``Y``) and months (``M``) are unsupported as they\n+ cannot be represented by :class:`~datetime.timedelta`.\n+\n+ .. versionchanged:: 6.1\n+\n+ ISO 8601 duration parsing now supports weeks (``PnW``).\n+\n ``django.utils.decorators``\n ===========================" }, { "filename": "docs/releases/6.1.txt", "status": "modified", "additions": 2, "deletions": 1, "changes": 3, "patch": "@@ -321,7 +321,8 @@ URLs\n Utilities\n ~~~~~~~~~\n \n-* ...\n+* :func:`~django.utils.dateparse.parse_duration` now supports ISO 8601\n+ durations expressed in weeks (``PnW``).\n \n Validators\n ~~~~~~~~~~" }, { "filename": "tests/utils_tests/test_dateparse.py", "status": "modified", "additions": 5, "deletions": 1, "changes": 6, "patch": "@@ -194,7 +194,11 @@ def test_iso_8601(self):\n test_values = (\n (\"P4Y\", None),\n (\"P4M\", None),\n- (\"P4W\", None),\n+ (\"P4W\", timedelta(weeks=4)),\n+ (\"P0.5W\", timedelta(weeks=0.5)),\n+ (\"P0,5W\", timedelta(weeks=0.5)),\n+ (\"-P0.5W\", timedelta(weeks=-0.5)),\n+ (\"P1W1D\", timedelta(weeks=1, days=1)),\n (\"P4D\", timedelta(days=4)),\n (\"-P1D\", timedelta(days=-1)),\n (\"P0.5D\", timedelta(hours=12))," } ], "reviews": [ { "id": 3584493218, "user": "user_3a67c55598c5", "state": "COMMENTED", "body": "Thanks [USER_REDACTED] 👍 .\n\nI just reclassified this to a new feature on Trac, could you add some docs?", "submitted_at": "2025-12-16T18:43:25+00:00" }, { "id": 3588144928, "user": "user_3a67c55598c5", "state": "APPROVED", "body": "Thanks for the updates ⭐ \n\nI pushed tiny edits to docs.", "submitted_at": "2025-12-17T15:04:47+00:00" } ], "review_comments": [ { "id": 2624354241, "user": "user_3a67c55598c5", "body": "Please add a `versionchanged` directive and a release note.", "path": "docs/ref/utils.txt", "line": null, "side": "RIGHT", "created_at": "2025-12-16T18:41:40+00:00" }, { "id": 2627396055, "user": "user_3a67c55598c5", "body": "I'll move some of this into the text above. The rule of thumb is that the versionchanged directive shouldn't contain any information we want to keep forever, as when 6.1 goes EOL, we drop this whole directive.", "path": "docs/ref/utils.txt", "line": null, "side": "RIGHT", "created_at": "2025-12-17T14:56:24+00:00" }, { "id": 2627397593, "user": "user_3a67c55598c5", "body": "Ticket numbers only necessary for regressions in patch release notes.", "path": "docs/releases/6.1.txt", "line": null, "side": "RIGHT", "created_at": "2025-12-17T14:56:49+00:00" }, { "id": 2627406484, "user": "user_3a67c55598c5", "body": "Also, make sure to indent.", "path": "docs/ref/utils.txt", "line": null, "side": "RIGHT", "created_at": "2025-12-17T14:59:11+00:00" }, { "id": 2627415655, "user": "user_3a67c55598c5", "body": "Using `~django` helps reduce the verbosity of the link text.", "path": "docs/releases/6.1.txt", "line": null, "side": "RIGHT", "created_at": "2025-12-17T15:01:32+00:00" } ], "meta": { "languages": [ "py", "txt" ], "touches_tests": true, "review_state_summary": { "COMMENTED": 1, "APPROVED": 1 }, "meaningful_comment_count": 5, "has_approval": true, "has_changes_requested": false, "total_review_comments": 5 } } { "_id": "accc14593aad66eb", "_schema_version": "1.0", "_cleaned_at": "2026-02-12T07:46:52.116991+00:00", "repo": "django/django", "repo_url": "https://github.com/django/django", "license_name": "BSD 3-Clause \"New\" or \"Revised\" License", "license_spdx": "BSD-3-Clause", "pr_number": 20288, "title": "Fixed #36714 -- Fixed context sharing for signals.", "body": "#### Trac ticket number\n\n\n[ticket-36714](https://code.djangoproject.com/ticket/36714)\n\n#### Branch description\n\nAsync signals lose `ContextVar` state due to use of `asyncio.gather`. Fixed it by sharing a context between tasks.\n\nRelated MR - https://github.com/[USER_REDACTED]ngo/asgiref/pull/536\n\n#### Checklist\n- [x] This PR targets the `main` branch. \n- [x] The commit message is written in past tense, mentions the ticket number, and ends with a period.\n- [x] I have checked the \"Has patch\" ticket flag in the Trac system.\n- [x] I have added or updated relevant tests.\n- [ ] I have added or updated relevant docs, including release notes if applicable. \n- [ ] I have attached screenshots in both light and dark modes for any UI changes.", "author": "user_355f7c5b898b", "created_at": "2025-11-21T13:11:17+00:00", "merged_at": "2025-12-29T14:48:11+00:00", "base_branch": "main", "head_branch": "ticket_36714", "additions": 273, "deletions": 20, "changed_files": 2, "files": [ { "filename": "django/dispatch/dispatcher.py", "status": "modified", "additions": 37, "deletions": 20, "changes": 57, "patch": "@@ -1,4 +1,5 @@\n import asyncio\n+import contextvars\n import logging\n import threading\n import weakref\n@@ -22,26 +23,45 @@ def _make_id(target):\n NO_RECEIVERS = object()\n \n \n-async def _gather(*coros):\n+def _restore_context(context):\n+ \"\"\"\n+ Check for changes in contextvars, and set them to the current\n+ context for downstream consumers.\n+ \"\"\"\n+ for cvar in context:\n+ cvalue = context.get(cvar)\n+ try:\n+ if cvar.get() != cvalue:\n+ cvar.set(cvalue)\n+ except LookupError:\n+ cvar.set(cvalue)\n+\n+\n+async def _run_parallel(*coros):\n+ \"\"\"\n+ Execute multiple asynchronous coroutines in parallel,\n+ sharing the current context between them.\n+ \"\"\"\n+ context = contextvars.copy_context()\n+\n if len(coros) == 0:\n return []\n \n- if len(coros) == 1:\n- return [await coros[0]]\n-\n async def run(i, coro):\n results[i] = await coro\n \n try:\n async with asyncio.TaskGroup() as tg:\n results = [None] * len(coros)\n for i, coro in enumerate(coros):\n- tg.create_task(run(i, coro))\n+ tg.create_task(run(i, coro), context=context)\n return results\n except BaseExceptionGroup as exception_group:\n if len(exception_group.exceptions) == 1:\n raise exception_group.exceptions[0]\n raise\n+ finally:\n+ _restore_context(context=context)\n \n \n class Signal:\n@@ -233,7 +253,7 @@ def send(self, sender, **named):\n if async_receivers:\n \n async def asend():\n- async_responses = await _gather(\n+ async_responses = await _run_parallel(\n *(\n receiver(signal=self, sender=sender, **named)\n for receiver in async_receivers\n@@ -275,6 +295,7 @@ async def asend(self, sender, **named):\n ):\n return []\n sync_receivers, async_receivers = self._live_receivers(sender)\n+\n if sync_receivers:\n \n [USER_REDACTED]_to_async\n@@ -290,14 +311,12 @@ def sync_send():\n async def sync_send():\n return []\n \n- responses, async_responses = await _gather(\n- sync_send(),\n- _gather(\n- *(\n- receiver(signal=self, sender=sender, **named)\n- for receiver in async_receivers\n- )\n- ),\n+ responses = await sync_send()\n+ async_responses = await _run_parallel(\n+ *(\n+ receiver(signal=self, sender=sender, **named)\n+ for receiver in async_receivers\n+ )\n )\n responses.extend(zip(async_receivers, async_responses))\n return responses\n@@ -362,7 +381,7 @@ async def asend_and_wrap_exception(receiver):\n return response\n \n async def asend():\n- async_responses = await _gather(\n+ async_responses = await _run_parallel(\n *(\n asend_and_wrap_exception(receiver)\n for receiver in async_receivers\n@@ -436,11 +455,9 @@ async def asend_and_wrap_exception(receiver):\n return err\n return response\n \n- responses, async_responses = await _gather(\n- sync_send(),\n- _gather(\n- *(asend_and_wrap_exception(receiver) for receiver in async_receivers),\n- ),\n+ responses = await sync_send()\n+ async_responses = await _run_parallel(\n+ *(asend_and_wrap_exception(receiver) for receiver in async_receivers),\n )\n responses.extend(zip(async_receivers, async_responses))\n return responses" }, { "filename": "tests/signals/tests.py", "status": "modified", "additions": 236, "deletions": 0, "changes": 236, "patch": "@@ -1,3 +1,4 @@\n+import contextvars\n from unittest import mock\n \n from asgiref.sync import markcoroutinefunction\n@@ -645,3 +646,238 @@ async def test_asend_robust_only_async_receivers(self):\n \n result = await signal.asend_robust(self.__class__)\n self.assertEqual(result, [(async_handler, 1)])\n+\n+\n+class TestReceiversContextVarsSharing(SimpleTestCase):\n+ def setUp(self):\n+ self.ctx_var = contextvars.ContextVar(\"test_var\", default=0)\n+\n+ class CtxSyncHandler:\n+ def __init__(self, ctx_var):\n+ self.ctx_var = ctx_var\n+ self.values = []\n+\n+ def __call__(self, **kwargs):\n+ val = self.ctx_var.get()\n+ self.ctx_var.set(val + 1)\n+ self.values.append(self.ctx_var.get())\n+ return self.ctx_var.get()\n+\n+ class CtxAsyncHandler:\n+ def __init__(self, ctx_var):\n+ self.ctx_var = ctx_var\n+ self.values = []\n+ markcoroutinefunction(self)\n+\n+ async def __call__(self, **kwargs):\n+ val = self.ctx_var.get()\n+ self.ctx_var.set(val + 1)\n+ self.values.append(self.ctx_var.get())\n+ return self.ctx_var.get()\n+\n+ self.CtxSyncHandler = CtxSyncHandler\n+ self.CtxAsyncHandler = CtxAsyncHandler\n+\n+ async def test_asend_correct_contextvars_sharing_async_receivers(self):\n+ handler1 = self.CtxAsyncHandler(self.ctx_var)\n+ handler2 = self.CtxAsyncHandler(self.ctx_var)\n+ signal = dispatch.Signal()\n+ signal.connect(handler1)\n+ signal.connect(handler2)\n+\n+ # set custom value outer signal\n+ self.ctx_var.set(1)\n+\n+ await signal.asend(self.__class__)\n+\n+ self.assertEqual(len(handler1.values), 1)\n+ self.assertEqual(len(handler2.values), 1)\n+ self.assertEqual(sorted([*handler1.values, *handler2.values]), [2, 3])\n+ self.assertEqual(self.ctx_var.get(), 3)\n+\n+ async def test_asend_correct_contextvars_sharing_sync_receivers(self):\n+ handler1 = self.CtxSyncHandler(self.ctx_var)\n+ handler2 = self.CtxSyncHandler(self.ctx_var)\n+ signal = dispatch.Signal()\n+ signal.connect(handler1)\n+ signal.connect(handler2)\n+\n+ # set custom value outer signal\n+ self.ctx_var.set(1)\n+\n+ await signal.asend(self.__class__)\n+\n+ self.assertEqual(len(handler1.values), 1)\n+ self.assertEqual(len(handler2.values), 1)\n+ self.assertEqual(sorted([*handler1.values, *handler2.values]), [2, 3])\n+ self.assertEqual(self.ctx_var.get(), 3)\n+\n+ async def test_asend_correct_contextvars_sharing_mix_receivers(self):\n+ handler1 = self.CtxSyncHandler(self.ctx_var)\n+ handler2 = self.CtxAsyncHandler(self.ctx_var)\n+ signal = dispatch.Signal()\n+ signal.connect(handler1)\n+ signal.connect(handler2)\n+\n+ # set custom value outer signal\n+ self.ctx_var.set(1)\n+\n+ await signal.asend(self.__class__)\n+\n+ self.assertEqual(len(handler1.values), 1)\n+ self.assertEqual(len(handler2.values), 1)\n+ self.assertEqual(sorted([*handler1.values, *handler2.values]), [2, 3])\n+ self.assertEqual(self.ctx_var.get(), 3)\n+\n+ async def test_asend_robust_correct_contextvars_sharing_async_receivers(self):\n+ handler1 = self.CtxAsyncHandler(self.ctx_var)\n+ handler2 = self.CtxAsyncHandler(self.ctx_var)\n+ signal = dispatch.Signal()\n+ signal.connect(handler1)\n+ signal.connect(handler2)\n+\n+ # set custom value outer signal\n+ self.ctx_var.set(1)\n+\n+ await signal.asend_robust(self.__class__)\n+\n+ self.assertEqual(len(handler1.values), 1)\n+ self.assertEqual(len(handler2.values), 1)\n+ self.assertEqual(sorted([*handler1.values, *handler2.values]), [2, 3])\n+ self.assertEqual(self.ctx_var.get(), 3)\n+\n+ async def test_asend_robust_correct_contextvars_sharing_sync_receivers(self):\n+ handler1 = self.CtxSyncHandler(self.ctx_var)\n+ handler2 = self.CtxSyncHandler(self.ctx_var)\n+ signal = dispatch.Signal()\n+ signal.connect(handler1)\n+ signal.connect(handler2)\n+\n+ # set custom value outer signal\n+ self.ctx_var.set(1)\n+\n+ await signal.asend_robust(self.__class__)\n+\n+ self.assertEqual(len(handler1.values), 1)\n+ self.assertEqual(len(handler2.values), 1)\n+ self.assertEqual(sorted([*handler1.values, *handler2.values]), [2, 3])\n+ self.assertEqual(self.ctx_var.get(), 3)\n+\n+ async def test_asend_robust_correct_contextvars_sharing_mix_receivers(self):\n+ handler1 = self.CtxSyncHandler(self.ctx_var)\n+ handler2 = self.CtxAsyncHandler(self.ctx_var)\n+ signal = dispatch.Signal()\n+ signal.connect(handler1)\n+ signal.connect(handler2)\n+\n+ # set custom value outer signal\n+ self.ctx_var.set(1)\n+\n+ await signal.asend_robust(self.__class__)\n+\n+ self.assertEqual(len(handler1.values), 1)\n+ self.assertEqual(len(handler2.values), 1)\n+ self.assertEqual(sorted([*handler1.values, *handler2.values]), [2, 3])\n+ self.assertEqual(self.ctx_var.get(), 3)\n+\n+ def test_send_correct_contextvars_sharing_async_receivers(self):\n+ handler1 = self.CtxAsyncHandler(self.ctx_var)\n+ handler2 = self.CtxAsyncHandler(self.ctx_var)\n+ signal = dispatch.Signal()\n+ signal.connect(handler1)\n+ signal.connect(handler2)\n+\n+ # set custom value outer signal\n+ self.ctx_var.set(1)\n+\n+ signal.send(self.__class__)\n+\n+ self.assertEqual(len(handler1.values), 1)\n+ self.assertEqual(len(handler2.values), 1)\n+ self.assertEqual(sorted([*handler1.values, *handler2.values]), [2, 3])\n+ self.assertEqual(self.ctx_var.get(), 3)\n+\n+ def test_send_correct_contextvars_sharing_sync_receivers(self):\n+ handler1 = self.CtxSyncHandler(self.ctx_var)\n+ handler2 = self.CtxSyncHandler(self.ctx_var)\n+ signal = dispatch.Signal()\n+ signal.connect(handler1)\n+ signal.connect(handler2)\n+\n+ # set custom value outer signal\n+ self.ctx_var.set(1)\n+\n+ signal.send(self.__class__)\n+\n+ self.assertEqual(len(handler1.values), 1)\n+ self.assertEqual(len(handler2.values), 1)\n+ self.assertEqual(sorted([*handler1.values, *handler2.values]), [2, 3])\n+ self.assertEqual(self.ctx_var.get(), 3)\n+\n+ def test_send_correct_contextvars_sharing_mix_receivers(self):\n+ handler1 = self.CtxSyncHandler(self.ctx_var)\n+ handler2 = self.CtxAsyncHandler(self.ctx_var)\n+ signal = dispatch.Signal()\n+ signal.connect(handler1)\n+ signal.connect(handler2)\n+\n+ # set custom value outer signal\n+ self.ctx_var.set(1)\n+\n+ signal.send(self.__class__)\n+\n+ self.assertEqual(len(handler1.values), 1)\n+ self.assertEqual(len(handler2.values), 1)\n+ self.assertEqual(sorted([*handler1.values, *handler2.values]), [2, 3])\n+ self.assertEqual(self.ctx_var.get(), 3)\n+\n+ def test_send_robust_correct_contextvars_sharing_async_receivers(self):\n+ handler1 = self.CtxAsyncHandler(self.ctx_var)\n+ handler2 = self.CtxAsyncHandler(self.ctx_var)\n+ signal = dispatch.Signal()\n+ signal.connect(handler1)\n+ signal.connect(handler2)\n+\n+ # set custom value outer signal\n+ self.ctx_var.set(1)\n+\n+ signal.send_robust(self.__class__)\n+\n+ self.assertEqual(len(handler1.values), 1)\n+ self.assertEqual(len(handler2.values), 1)\n+ self.assertEqual(sorted([*handler1.values, *handler2.values]), [2, 3])\n+ self.assertEqual(self.ctx_var.get(), 3)\n+\n+ def test_send_robust_correct_contextvars_sharing_sync_receivers(self):\n+ handler1 = self.CtxSyncHandler(self.ctx_var)\n+ handler2 = self.CtxSyncHandler(self.ctx_var)\n+ signal = dispatch.Signal()\n+ signal.connect(handler1)\n+ signal.connect(handler2)\n+\n+ # set custom value outer signal\n+ self.ctx_var.set(1)\n+\n+ signal.send_robust(self.__class__)\n+\n+ self.assertEqual(len(handler1.values), 1)\n+ self.assertEqual(len(handler2.values), 1)\n+ self.assertEqual(sorted([*handler1.values, *handler2.values]), [2, 3])\n+ self.assertEqual(self.ctx_var.get(), 3)\n+\n+ def test_send_robust_correct_contextvars_sharing_mix_receivers(self):\n+ handler1 = self.CtxSyncHandler(self.ctx_var)\n+ handler2 = self.CtxAsyncHandler(self.ctx_var)\n+ signal = dispatch.Signal()\n+ signal.connect(handler1)\n+ signal.connect(handler2)\n+\n+ # set custom value outer signal\n+ self.ctx_var.set(1)\n+\n+ signal.send_robust(self.__class__)\n+\n+ self.assertEqual(len(handler1.values), 1)\n+ self.assertEqual(len(handler2.values), 1)\n+ self.assertEqual(sorted([*handler1.values, *handler2.values]), [2, 3])\n+ self.assertEqual(self.ctx_var.get(), 3)" } ], "reviews": [ { "id": 3492711117, "user": "user_355f7c5b898b", "state": "COMMENTED", "body": null, "submitted_at": "2025-11-21T13:12:05+00:00" }, { "id": 3540993130, "user": "user_355f7c5b898b", "state": "COMMENTED", "body": null, "submitted_at": "2025-12-04T16:48:06+00:00" }, { "id": 3588508913, "user": "user_3a67c55598c5", "state": "COMMENTED", "body": "Thanks [USER_REDACTED] 👍", "submitted_at": "2025-12-17T16:47:48+00:00" }, { "id": 3595750471, "user": "user_3a67c55598c5", "state": "COMMENTED", "body": null, "submitted_at": "2025-12-18T23:57:19+00:00" }, { "id": 3604806783, "user": "user_355f7c5b898b", "state": "COMMENTED", "body": null, "submitted_at": "2025-12-22T16:40:44+00:00" }, { "id": 3604822218, "user": "user_355f7c5b898b", "state": "COMMENTED", "body": null, "submitted_at": "2025-12-22T16:45:53+00:00" }, { "id": 3604896790, "user": "user_3a67c55598c5", "state": "APPROVED", "body": "Thank you!", "submitted_at": "2025-12-22T17:07:26+00:00" } ], "review_comments": [ { "id": 2549721274, "user": "user_355f7c5b898b", "body": "I tried using `.subTest` to reduce the number of tests for `asend/asend_robust` and `send/send_robust`, but the error output became unreadable.\n\n```\n File \"/Users/m.havelya/work/django/django/test/testcases.py\", line 87, in is_pickable\n pickle.loads(pickle.dumps(obj))\n ^^^^^^^^^^^^^^^\n\n ....\n\n File \"/Users/m.havelya/work/django/django/test/testcases.py\", line 325, in __getstate__\n if key in pickable_state or not is_pickable(value):\n ^^^^^^^\n File \"/Users/m.havelya/work/django/django/test/testcases.py\", line 87, in is_pickable\n pickle.loads(pickle.dumps(obj))\n ^^^^^^^^^^^^^^^\n File \"/Users/m.havelya/work/django/django/test/testcases.py\", line 325, in __getstate__\n if key in pickable_state or not is_pickable(value):\n ^^^^^^^\nRecursionError: maximum recursion depth exceeded\n\n----------------------------------------------------------------------\nRan 31 tests in 0.439s\n\nFAILED (errors=1)\n```\n\nSo I dropped the idea. Using separate tests is more readable.", "path": "tests/signals/tests.py", "line": 681, "side": "RIGHT", "created_at": "2025-11-21T13:12:05+00:00" }, { "id": 2589828115, "user": "user_355f7c5b898b", "body": "Summary:\n\n- Removed the `len(coros) == 1` optimization. It doesn’t appear to provide any real benefit.\n\n```\n┏━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┳━━━━━━━━━┳━━━━━━━━━┳━━━━━━━━━┳━━━━━━━━━━━━━━━━━┳━━━━━━━━━━━━━━━━━┳━━━━━━━━━━━━━━━━━┓\n┃ Benchmark ┃ Min ┃ Max ┃ Mean ┃ Min (+) ┃ Max (+) ┃ Mean (+) ┃\n┡━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━╇━━━━━━━━━╇━━━━━━━━━╇━━━━━━━━━╇━━━━━━━━━━━━━━━━━╇━━━━━━━━━━━━━━━━━╇━━━━━━━━━━━━━━━━━┩\n│ TaskGroup instead of create_task │ 0.001 │ 0.001 │ 0.001 │ 0.001 (1.1x) │ 0.002 (-1.1x) │ 0.001 (1.1x) │\n└──────────────────────────────────┴─────────┴─────────┴─────────┴─────────────────┴─────────────────┴─────────────────┘\n```\n\n- All coroutines now share the same context, which is restored to the current context after completion.\n\nbtw:\n\n- `_restore_context` is just a copy-paste from the `asgiref` library", "path": "django/dispatch/dispatcher.py", "line": null, "side": "RIGHT", "created_at": "2025-12-04T16:48:06+00:00" }, { "id": 2627697128, "user": "user_3a67c55598c5", "body": "Should we update the docstrings for `asend()`/`asend_robust()` now? It reads, \"If any receivers are asynchronous, they are grouped and executed concurrently...\", which is a little bit ambiguous, but if \"they\" is \"all the receivers\", then they're not all concurrent anymore.", "path": "django/dispatch/dispatcher.py", "line": 319, "side": "RIGHT", "created_at": "2025-12-17T16:17:01+00:00" }, { "id": 2627755315, "user": "user_3a67c55598c5", "body": "I see we're coping this from `asgiref`. Is that only because it's marked as private? We could ask Carlton if he minds us importing it and/or if he wants to make it public in the next release.", "path": "django/dispatch/dispatcher.py", "line": null, "side": "RIGHT", "created_at": "2025-12-17T16:31:33+00:00" }, { "id": 2627809498, "user": "user_3a67c55598c5", "body": "Also, it would be nice to lift this up out of the function definition.", "path": "django/dispatch/dispatcher.py", "line": null, "side": "RIGHT", "created_at": "2025-12-17T16:47:28+00:00" }, { "id": 2633063601, "user": "user_3a67c55598c5", "body": "Never mind, looking at the context right before this, I guess \"they\" means the asynchronous ones, so this should be fine.", "path": "django/dispatch/dispatcher.py", "line": 319, "side": "RIGHT", "created_at": "2025-12-18T23:57:19+00:00" }, { "id": 2640493507, "user": "user_355f7c5b898b", "body": "- Is that only because it's marked as private? - yes 😌\n\n- We could ask Carlton if he minds us importing it and/or if he wants to make it public in the next release - it's much more robust to keep them separate", "path": "django/dispatch/dispatcher.py", "line": null, "side": "RIGHT", "created_at": "2025-12-22T16:40:43+00:00" }, { "id": 2640505886, "user": "user_355f7c5b898b", "body": "- Also, it would be nice to lift this up out of the function definition.\n\ndone 🙂", "path": "django/dispatch/dispatcher.py", "line": null, "side": "RIGHT", "created_at": "2025-12-22T16:45:53+00:00" } ], "meta": { "languages": [ "py" ], "touches_tests": true, "review_state_summary": { "COMMENTED": 6, "APPROVED": 1 }, "meaningful_comment_count": 8, "has_approval": true, "has_changes_requested": false, "total_review_comments": 8 } } { "_id": "11d91681eeb26827", "_schema_version": "1.0", "_cleaned_at": "2026-02-12T07:46:52.116991+00:00", "repo": "django/django", "repo_url": "https://github.com/django/django", "license_name": "BSD 3-Clause \"New\" or \"Revised\" License", "license_spdx": "BSD-3-Clause", "pr_number": 20287, "title": "Fixed #32568 -- Replaced obvious mark_safe usages with SafeString for performance.", "body": "#### Trac ticket number\n\n\nticket-32568\n\n#### Branch description\nI have replace `mark_safe` with `SafeString` .\n\n#### Checklist\n- [X] This PR targets the `main` branch. \n- [ ] The commit message is written in past tense, mentions the ticket number, and ends with a period.\n- [x] I have checked the \"Has patch\" ticket flag in the Trac system.\n- [ ] I have added or updated relevant tests.\n- [ ] I have added or updated relevant docs, including release notes if applicable.\n- [ ] I have attached screenshots in both light and dark modes for any UI changes.", "author": "user_a7be60241a0e", "created_at": "2025-11-21T07:20:34+00:00", "merged_at": "2025-12-17T17:15:18+00:00", "base_branch": "main", "head_branch": "fix-32568", "additions": 5, "deletions": 5, "changed_files": 2, "files": [ { "filename": "django/contrib/admin/templatetags/admin_list.py", "status": "modified", "additions": 4, "deletions": 4, "changes": 8, "patch": "@@ -25,7 +25,7 @@\n from django.urls import NoReverseMatch\n from django.utils import formats, timezone\n from django.utils.html import format_html\n-from django.utils.safestring import mark_safe\n+from django.utils.safestring import SafeString, mark_safe\n from django.utils.text import capfirst\n from django.utils.translation import gettext as _\n \n@@ -103,11 +103,11 @@ def result_headers(cl):\n if field_name == \"action_checkbox\":\n aria_label = _(\"Select all objects on this page for an action\")\n yield {\n- \"text\": mark_safe(\n+ \"text\": SafeString(\n f''\n ),\n- \"class_attrib\": mark_safe(' class=\"action-checkbox-column\"'),\n+ \"class_attrib\": SafeString(' class=\"action-checkbox-column\"'),\n \"sortable\": False,\n }\n continue\n@@ -256,7 +256,7 @@ def link_in_col(is_first, field_name, cl):\n f, (models.DateField, models.TimeField, models.ForeignKey)\n ):\n row_classes.append(\"nowrap\")\n- row_class = mark_safe(' class=\"%s\"' % \" \".join(row_classes))\n+ row_class = SafeString(' class=\"%s\"' % \" \".join(row_classes))\n # If list_display_links not defined, add the link tag to the first\n # field\n if link_to_changelist:" }, { "filename": "django/utils/html.py", "status": "modified", "additions": 1, "deletions": 1, "changes": 2, "patch": "@@ -397,7 +397,7 @@ def handle_word(\n attrs=nofollow_attr,\n url=trimmed,\n )\n- return mark_safe(f\"{lead}{middle}{trail}\")\n+ return SafeString(f\"{lead}{middle}{trail}\")\n else:\n if safe_input:\n return mark_safe(word)" } ], "reviews": [ { "id": 3584076856, "user": "user_3a67c55598c5", "state": "COMMENTED", "body": "[USER_REDACTED] 👋 \n\nThe changes to the source look fine, but please revert the changes to tests. Then I can look in more detail. Also please retitle your commit & PR to match the contributing guidelines. Thanks.", "submitted_at": "2025-12-16T16:55:30+00:00" }, { "id": 3588203068, "user": "user_3a67c55598c5", "state": "COMMENTED", "body": "Thanks, just a bit more to tidy up. Also, PR & commits should be capitalized in headline case and past tense:\n```\nFixed #12345 -- Replaced ...\n```", "submitted_at": "2025-12-17T15:10:56+00:00" }, { "id": 3588380300, "user": "user_3a67c55598c5", "state": "APPROVED", "body": "Thanks 👍", "submitted_at": "2025-12-17T15:46:36+00:00" }, { "id": 3588419378, "user": "user_3a67c55598c5", "state": "COMMENTED", "body": null, "submitted_at": "2025-12-17T15:56:01+00:00" }, { "id": 3588516093, "user": "user_a7be60241a0e", "state": "COMMENTED", "body": null, "submitted_at": "2025-12-17T16:18:21+00:00" }, { "id": 3588543346, "user": "user_a7be60241a0e", "state": "COMMENTED", "body": null, "submitted_at": "2025-12-17T16:23:07+00:00" }, { "id": 3588686011, "user": "user_3a67c55598c5", "state": "APPROVED", "body": "Thanks [USER_REDACTED], and thanks [USER_REDACTED] for the review.", "submitted_at": "2025-12-17T16:57:42+00:00" } ], "review_comments": [ { "id": 2627445692, "user": "user_3a67c55598c5", "body": "There are still changes to test files here.", "path": "tests/admin_views/admin.py", "line": null, "side": "RIGHT", "created_at": "2025-12-17T15:09:15+00:00" }, { "id": 2627620439, "user": "user_3a67c55598c5", "body": "On second thought, can you revert this also? It's the only one that's not a a literal string (in other words, where we can't guarantee the type is exactly `str`. There could be a lazy object with a custom `replace` method that relies on this somehow.", "path": "django/contrib/admindocs/utils.py", "line": null, "side": "RIGHT", "created_at": "2025-12-17T15:55:48+00:00" }, { "id": 2627702376, "user": "user_a7be60241a0e", "body": "thanks for catching this. Yes there might case where title(value) could be None or", "path": "django/contrib/admindocs/utils.py", "line": null, "side": "RIGHT", "created_at": "2025-12-17T16:18:21+00:00" }, { "id": 2627725051, "user": "user_a7be60241a0e", "body": "something could have been done but i'm not confident\n```\ndef strip_p_tags(value):\n if value is None:\n return \"\"\n return SafeString(str(value).replace(\"

      \", \"\").replace(\"

      \", \"\"))\n```", "path": "django/contrib/admindocs/utils.py", "line": null, "side": "RIGHT", "created_at": "2025-12-17T16:23:07+00:00" } ], "meta": { "languages": [ "py" ], "touches_tests": false, "review_state_summary": { "COMMENTED": 5, "APPROVED": 2 }, "meaningful_comment_count": 4, "has_approval": true, "has_changes_requested": false, "total_review_comments": 4 } } { "_id": "de20b346f8e89cac", "_schema_version": "1.0", "_cleaned_at": "2026-02-12T07:46:52.116991+00:00", "repo": "django/django", "repo_url": "https://github.com/django/django", "license_name": "BSD 3-Clause \"New\" or \"Revised\" License", "license_spdx": "BSD-3-Clause", "pr_number": 20286, "title": "Refs #21961 -- Added DatabaseFeatures.supports_on_delete_db_(cascade/null) feature flags.", "body": "Needed on MongoDB.", "author": "user_657e90e5ae46", "created_at": "2025-11-21T02:34:04+00:00", "merged_at": "2025-11-24T11:03:36+00:00", "base_branch": "main", "head_branch": "supports_on_delete_db-skips", "additions": 181, "deletions": 48, "changed_files": 12, "files": [ { "filename": "django/db/backends/base/features.py", "status": "modified", "additions": 3, "deletions": 1, "changes": 4, "patch": "@@ -393,8 +393,10 @@ class BaseDatabaseFeatures:\n # subqueries?\n supports_tuple_comparison_against_subquery = True\n \n- # Does the backend support DEFAULT as delete option?\n+ # Does the backend support CASCADE, DEFAULT, NULL as delete options?\n+ supports_on_delete_db_cascade = True\n supports_on_delete_db_default = True\n+ supports_on_delete_db_null = True\n \n # Collation names for use by [NAME_REDACTED]\n test_collations = {" }, { "filename": "django/db/models/fields/related.py", "status": "modified", "additions": 36, "deletions": 19, "changes": 55, "patch": "@@ -12,6 +12,7 @@\n from django.db.models.constants import LOOKUP_SEP\n from django.db.models.deletion import (\n CASCADE,\n+ DB_CASCADE,\n DB_SET_DEFAULT,\n DB_SET_NULL,\n DO_NOTHING,\n@@ -1056,9 +1057,38 @@ def check(self, **kwargs):\n *self._check_unique(),\n ]\n \n+ def _check_on_delete_db_support(self, on_delete, feature_flag, databases):\n+ for db in databases:\n+ if not router.allow_migrate_model(db, self.model):\n+ continue\n+ connection = connections[db]\n+ if feature_flag in self.model._meta.required_db_features or getattr(\n+ connection.features, feature_flag\n+ ):\n+ continue\n+ no_db_option_name = on_delete.__name__.removeprefix(\"DB_\")\n+ yield checks.Error(\n+ f\"{connection.display_name} does not support a {on_delete.__name__}.\",\n+ hint=f\"Change the on_delete rule to {no_db_option_name}.\",\n+ obj=self,\n+ id=\"fields.E324\",\n+ )\n+\n def _check_on_delete(self, databases):\n on_delete = getattr(self.remote_field, \"on_delete\", None)\n errors = []\n+ if on_delete == DB_CASCADE:\n+ errors.extend(\n+ self._check_on_delete_db_support(\n+ on_delete, \"supports_on_delete_db_cascade\", databases\n+ )\n+ )\n+ if on_delete == DB_SET_NULL:\n+ errors.extend(\n+ self._check_on_delete_db_support(\n+ on_delete, \"supports_on_delete_db_null\", databases\n+ )\n+ )\n if on_delete in [DB_SET_NULL, SET_NULL] and not self.null:\n errors.append(\n checks.Error(\n@@ -1092,25 +1122,12 @@ def _check_on_delete(self, databases):\n id=\"fields.E322\",\n )\n )\n- for db in databases:\n- if not router.allow_migrate_model(db, self.model):\n- continue\n- connection = connections[db]\n- if not (\n- \"supports_on_delete_db_default\"\n- in self.model._meta.required_db_features\n- or connection.features.supports_on_delete_db_default\n- ):\n- errors.append(\n- checks.Error(\n- f\"{connection.display_name} does not support a \"\n- \"DB_SET_DEFAULT.\",\n- hint=\"Change the on_delete rule to SET_DEFAULT.\",\n- obj=self,\n- id=\"fields.E324\",\n- ),\n- )\n- elif not isinstance(self.remote_field.model, str) and on_delete != DO_NOTHING:\n+ errors.extend(\n+ self._check_on_delete_db_support(\n+ on_delete, \"supports_on_delete_db_default\", databases\n+ )\n+ )\n+ if not isinstance(self.remote_field.model, str) and on_delete != DO_NOTHING:\n # Database and Python variants cannot be mixed in a chain of\n # model references.\n is_db_on_delete = isinstance(on_delete, DatabaseOnDelete)" }, { "filename": "docs/ref/checks.txt", "status": "modified", "additions": 2, "deletions": 1, "changes": 3, "patch": "@@ -309,7 +309,8 @@ Related fields\n ``db_default`` value.\n * **fields.E323**: Field specifies database/Python-level on_delete variant, but\n referenced model uses python/database-level variant.\n-* **fields.E324**: ```` does not support ``DB_SET_DEFAULT``.\n+* **fields.E324**: ```` does not support\n+ ````.\n * **fields.E330**: ``ManyToManyField``\\s cannot be unique.\n * **fields.E331**: Field specifies a many-to-many relation through model\n ````, which has not been installed." }, { "filename": "tests/admin_utils/models.py", "status": "modified", "additions": 3, "deletions": 0, "changes": 3, "patch": "@@ -55,6 +55,9 @@ class DBCascade(models.Model):\n def __str__(self):\n return str(self.num)\n \n+ class Meta:\n+ required_db_features = {\"supports_on_delete_db_cascade\"}\n+\n \n class Event(models.Model):\n date = models.DateTimeField(auto_now_add=True)" }, { "filename": "tests/admin_utils/tests.py", "status": "modified", "additions": 2, "deletions": 1, "changes": 3, "patch": "@@ -21,7 +21,7 @@\n from django.contrib.auth.templatetags.auth import render_password_as_hash\n from django.core.validators import EMPTY_VALUES\n from django.db import DEFAULT_DB_ALIAS, models\n-from django.test import SimpleTestCase, TestCase, override_settings\n+from django.test import SimpleTestCase, TestCase, override_settings, skipUnlessDBFeature\n from django.test.utils import isolate_apps\n from django.utils.formats import localize\n from django.utils.safestring import mark_safe\n@@ -115,6 +115,7 @@ def test_relation_on_abstract(self):\n n.collect([Vehicle.objects.first()])\n \n \n+[USER_REDACTED](\"supports_on_delete_db_cascade\")\n class DBNestedObjectsTests(NestedObjectsTests):\n \"\"\"\n [NAME_REDACTED] but with a model that makes use of DB_CASCADE" }, { "filename": "tests/delete/models.py", "status": "modified", "additions": 13, "deletions": 13, "changes": 26, "patch": "@@ -49,17 +49,26 @@ class RelatedDbOptionParent(models.Model):\n p = models.ForeignKey(RelatedDbOptionGrandParent, models.DB_CASCADE, null=True)\n \n \n-class RelatedDbOption(models.Model):\n+class CascadeDbModel(models.Model):\n name = models.CharField(max_length=30)\n+ db_cascade = models.ForeignKey(\n+ RelatedDbOptionParent, models.DB_CASCADE, related_name=\"db_cascade_set\"\n+ )\n+\n+ class Meta:\n+ required_db_features = {\"supports_on_delete_db_cascade\"}\n+\n+\n+class SetNullDbModel(models.Model):\n db_setnull = models.ForeignKey(\n RelatedDbOptionParent,\n models.DB_SET_NULL,\n null=True,\n related_name=\"db_setnull_set\",\n )\n- db_cascade = models.ForeignKey(\n- RelatedDbOptionParent, models.DB_CASCADE, related_name=\"db_cascade_set\"\n- )\n+\n+ class Meta:\n+ required_db_features = {\"supports_on_delete_db_null\"}\n \n \n class SetDefaultDbModel(models.Model):\n@@ -159,15 +168,6 @@ def create_a(name):\n return a\n \n \n-def create_related_db_option(name):\n- a = RelatedDbOption(name=name)\n- for name in [\"db_setnull\", \"db_cascade\"]:\n- r = RelatedDbOptionParent.objects.create()\n- setattr(a, name, r)\n- a.save()\n- return a\n-\n-\n class M(models.Model):\n m2m = models.ManyToManyField(R, related_name=\"m_set\")\n m2m_through = models.ManyToManyField(R, through=\"MR\", related_name=\"m_through_set\")" }, { "filename": "tests/delete/tests.py", "status": "modified", "additions": 11, "deletions": 7, "changes": 18, "patch": "@@ -15,6 +15,7 @@\n Avatar,\n B,\n Base,\n+ CascadeDbModel,\n Child,\n DeleteBottom,\n DeleteTop,\n@@ -34,16 +35,15 @@\n RChild,\n RChildChild,\n Referrer,\n- RelatedDbOption,\n RelatedDbOptionGrandParent,\n RelatedDbOptionParent,\n RProxy,\n S,\n SetDefaultDbModel,\n+ SetNullDbModel,\n T,\n User,\n create_a,\n- create_related_db_option,\n get_default_r,\n )\n \n@@ -81,10 +81,13 @@ def test_setnull(self):\n a = A.objects.get(pk=a.pk)\n self.assertIsNone(a.setnull)\n \n+ [USER_REDACTED](\"supports_on_delete_db_null\")\n def test_db_setnull(self):\n- a = create_related_db_option(\"db_setnull\")\n+ a = SetNullDbModel.objects.create(\n+ db_setnull=RelatedDbOptionParent.objects.create()\n+ )\n a.db_setnull.delete()\n- a = RelatedDbOption.objects.get(pk=a.pk)\n+ a = SetNullDbModel.objects.get(pk=a.pk)\n self.assertIsNone(a.db_setnull)\n \n def test_setdefault(self):\n@@ -394,20 +397,21 @@ def test_bulk(self):\n self.assertNumQueries(5, s.delete)\n self.assertFalse(S.objects.exists())\n \n+ [USER_REDACTED](\"supports_on_delete_db_cascade\")\n def test_db_cascade(self):\n related_db_op = RelatedDbOptionParent.objects.create(\n p=RelatedDbOptionGrandParent.objects.create()\n )\n- RelatedDbOption.objects.bulk_create(\n+ CascadeDbModel.objects.bulk_create(\n [\n- RelatedDbOption(db_cascade=related_db_op)\n+ CascadeDbModel(db_cascade=related_db_op)\n for _ in range(2 * GET_ITERATOR_CHUNK_SIZE)\n ]\n )\n with self.assertNumQueries(1):\n results = related_db_op.delete()\n self.assertEqual(results, (1, {\"delete.RelatedDbOptionParent\": 1}))\n- self.assertFalse(RelatedDbOption.objects.exists())\n+ self.assertFalse(CascadeDbModel.objects.exists())\n self.assertFalse(RelatedDbOptionParent.objects.exists())\n \n def test_instance_update(self):" }, { "filename": "tests/inspectdb/models.py", "status": "modified", "additions": 6, "deletions": 0, "changes": 6, "patch": "@@ -178,3 +178,9 @@ class DbOnDeleteModel(models.Model):\n fk_set_null = models.ForeignKey(\n DigitsInColumnName, on_delete=models.DB_SET_NULL, null=True\n )\n+\n+ class Meta:\n+ required_db_features = {\n+ \"supports_on_delete_db_cascade\",\n+ \"supports_on_delete_db_null\",\n+ }" }, { "filename": "tests/inspectdb/tests.py", "status": "modified", "additions": 5, "deletions": 1, "changes": 6, "patch": "@@ -301,7 +301,11 @@ def test_foreign_key_to_field(self):\n out.getvalue(),\n )\n \n- [USER_REDACTED](\"can_introspect_foreign_keys\")\n+ [USER_REDACTED](\n+ \"can_introspect_foreign_keys\",\n+ \"supports_on_delete_db_cascade\",\n+ \"supports_on_delete_db_null\",\n+ )\n def test_foreign_key_db_on_delete(self):\n out = StringIO()\n call_command(\"inspectdb\", \"inspectdb_dbondeletemodel\", stdout=out)" }, { "filename": "tests/introspection/models.py", "status": "modified", "additions": 10, "deletions": 1, "changes": 11, "patch": "@@ -112,11 +112,20 @@ class Meta:\n required_db_features = {\"supports_comments\"}\n \n \n-class DbOnDeleteModel(models.Model):\n+class DbOnDeleteCascadeModel(models.Model):\n fk_do_nothing = models.ForeignKey(Country, on_delete=models.DO_NOTHING)\n fk_db_cascade = models.ForeignKey(City, on_delete=models.DB_CASCADE)\n+\n+ class Meta:\n+ required_db_features = {\"supports_on_delete_db_cascade\"}\n+\n+\n+class DbOnDeleteSetNullModel(models.Model):\n fk_set_null = models.ForeignKey(Reporter, on_delete=models.DB_SET_NULL, null=True)\n \n+ class Meta:\n+ required_db_features = {\"supports_on_delete_db_null\"}\n+\n \n class DbOnDeleteSetDefaultModel(models.Model):\n fk_db_set_default = models.ForeignKey(" }, { "filename": "tests/introspection/tests.py", "status": "modified", "additions": 17, "deletions": 4, "changes": 21, "patch": "@@ -10,8 +10,9 @@\n Comment,\n Country,\n DbCommentModel,\n- DbOnDeleteModel,\n+ DbOnDeleteCascadeModel,\n DbOnDeleteSetDefaultModel,\n+ DbOnDeleteSetNullModel,\n District,\n Reporter,\n UniqueConstraintConditionModel,\n@@ -244,11 +245,11 @@ def test_get_relations(self):\n editor.add_field(Article, body)\n self.assertEqual(relations, expected_relations)\n \n- [USER_REDACTED](\"can_introspect_foreign_keys\")\n- def test_get_relations_db_on_delete(self):\n+ [USER_REDACTED](\"can_introspect_foreign_keys\", \"supports_on_delete_db_cascade\")\n+ def test_get_relations_db_on_delete_cascade(self):\n with connection.cursor() as cursor:\n relations = connection.introspection.get_relations(\n- cursor, DbOnDeleteModel._meta.db_table\n+ cursor, DbOnDeleteCascadeModel._meta.db_table\n )\n \n if connection.vendor == \"mysql\" and connection.mysql_is_mariadb:\n@@ -259,6 +260,18 @@ def test_get_relations_db_on_delete(self):\n expected_relations = {\n \"fk_db_cascade_id\": (\"id\", City._meta.db_table, DB_CASCADE),\n \"fk_do_nothing_id\": (\"id\", Country._meta.db_table, no_db_on_delete),\n+ }\n+ self.assertEqual(relations, expected_relations)\n+\n+ [USER_REDACTED](\"can_introspect_foreign_keys\", \"supports_on_delete_db_null\")\n+ def test_get_relations_db_on_delete_null(self):\n+ with connection.cursor() as cursor:\n+ relations = connection.introspection.get_relations(\n+ cursor, DbOnDeleteSetNullModel._meta.db_table\n+ )\n+\n+ # {field_name: (field_name_other_table, other_table, db_on_delete)}\n+ expected_relations = {\n \"fk_set_null_id\": (\"id\", Reporter._meta.db_table, DB_SET_NULL),\n }\n self.assertEqual(relations, expected_relations)" }, { "filename": "tests/invalid_models_tests/test_relative_fields.py", "status": "modified", "additions": 73, "deletions": 0, "changes": 73, "patch": "@@ -2288,6 +2288,41 @@ class FooBar(models.Model):\n [USER_REDACTED]_apps(\"invalid_models_tests\")\n class DatabaseLevelOnDeleteTests(TestCase):\n \n+ def test_db_cascade_support(self):\n+ class Parent(models.Model):\n+ pass\n+\n+ class Child(models.Model):\n+ parent = models.ForeignKey(Parent, models.DB_CASCADE)\n+\n+ field = Child._meta.get_field(\"parent\")\n+ expected = (\n+ []\n+ if connection.features.supports_on_delete_db_cascade\n+ else [\n+ Error(\n+ f\"{connection.display_name} does not support a DB_CASCADE.\",\n+ hint=\"Change the on_delete rule to CASCADE.\",\n+ obj=field,\n+ id=\"fields.E324\",\n+ )\n+ ]\n+ )\n+ self.assertEqual(field.check(databases=self.databases), expected)\n+\n+ def test_db_cascade_required_db_features(self):\n+ class Parent(models.Model):\n+ pass\n+\n+ class Child(models.Model):\n+ parent = models.ForeignKey(Parent, models.DB_CASCADE)\n+\n+ class Meta:\n+ required_db_features = {\"supports_on_delete_db_cascade\"}\n+\n+ field = Child._meta.get_field(\"parent\")\n+ self.assertEqual(field.check(databases=self.databases), [])\n+\n def test_db_set_default_support(self):\n class Parent(models.Model):\n pass\n@@ -2349,6 +2384,41 @@ class Child(models.Model):\n ],\n )\n \n+ def test_db_set_null_support(self):\n+ class Parent(models.Model):\n+ pass\n+\n+ class Child(models.Model):\n+ parent = models.ForeignKey(Parent, models.DB_SET_NULL, null=True)\n+\n+ field = Child._meta.get_field(\"parent\")\n+ expected = (\n+ []\n+ if connection.features.supports_on_delete_db_null\n+ else [\n+ Error(\n+ f\"{connection.display_name} does not support a DB_SET_NULL.\",\n+ hint=\"Change the on_delete rule to SET_NULL.\",\n+ obj=field,\n+ id=\"fields.E324\",\n+ )\n+ ]\n+ )\n+ self.assertEqual(field.check(databases=self.databases), expected)\n+\n+ def test_db_set_null_required_db_features(self):\n+ class Parent(models.Model):\n+ pass\n+\n+ class Child(models.Model):\n+ parent = models.ForeignKey(Parent, models.DB_SET_NULL, null=True)\n+\n+ class Meta:\n+ required_db_features = {\"supports_on_delete_db_null\"}\n+\n+ field = Child._meta.get_field(\"parent\")\n+ self.assertEqual(field.check(databases=self.databases), [])\n+\n def test_python_db_chain(self):\n class GrandParent(models.Model):\n pass\n@@ -2376,6 +2446,7 @@ class Child(models.Model):\n ],\n )\n \n+ [USER_REDACTED](\"supports_on_delete_db_null\")\n def test_db_python_chain(self):\n class GrandParent(models.Model):\n pass\n@@ -2403,6 +2474,7 @@ class Child(models.Model):\n ],\n )\n \n+ [USER_REDACTED](\"supports_on_delete_db_cascade\")\n def test_db_python_chain_auto_created(self):\n class GrandParent(models.Model):\n pass\n@@ -2430,6 +2502,7 @@ class Child(models.Model):\n ],\n )\n \n+ [USER_REDACTED](\"supports_on_delete_db_null\")\n def test_db_do_nothing_chain(self):\n class GrandParent(models.Model):\n pass" } ], "reviews": [ { "id": 3496921710, "user": "user_657e90e5ae46", "state": "COMMENTED", "body": null, "submitted_at": "2025-11-22T19:40:39+00:00" }, { "id": 3497422051, "user": "user_5501cd6d3dc8", "state": "COMMENTED", "body": null, "submitted_at": "2025-11-23T06:06:05+00:00" }, { "id": 3497524433, "user": "user_057de2f3b132", "state": "APPROVED", "body": "Looks good to me! I have a couple minor suggestions, but nothing blocking.", "submitted_at": "2025-11-23T09:24:19+00:00" } ], "review_comments": [ { "id": 2553321510, "user": "user_657e90e5ae46", "body": "Maybe this should be renamed to `CascadeDbModel`?", "path": "tests/delete/models.py", "line": 59, "side": "RIGHT", "created_at": "2025-11-22T19:40:39+00:00" }, { "id": 2553809310, "user": "user_5501cd6d3dc8", "body": "Agreed, renamed.", "path": "tests/delete/models.py", "line": 59, "side": "RIGHT", "created_at": "2025-11-23T06:06:05+00:00" }, { "id": 2553904847, "user": "user_057de2f3b132", "body": "```suggestion\n if (\n feature_flag in self.model._meta.required_db_features\n or getattr(connection.features, feature_flag)\n ):\n continue\n no_db_option_name = on_delete.__name__.removeprefix(\"DB_\")\n errors.append(\n checks.Error(\n f\"{connection.display_name} does not support a \"\n f\"{on_delete.__name__}.\",\n hint=f\"Change the on_delete rule to {no_db_option_name}.\",\n obj=self,\n id=\"fields.E324\",\n ),\n )\n```", "path": "django/db/models/fields/related.py", "line": null, "side": "RIGHT", "created_at": "2025-11-23T09:20:24+00:00" }, { "id": 2553909821, "user": "user_057de2f3b132", "body": "We could also make this helper method a generator and `yield` the `Error`s.", "path": "django/db/models/fields/related.py", "line": null, "side": "RIGHT", "created_at": "2025-11-23T09:22:25+00:00" } ], "meta": { "languages": [ "py", "txt" ], "touches_tests": true, "review_state_summary": { "COMMENTED": 2, "APPROVED": 1 }, "meaningful_comment_count": 4, "has_approval": true, "has_changes_requested": false, "total_review_comments": 4 } } { "_id": "6f1b6c6d4aef8dc7", "_schema_version": "1.0", "_cleaned_at": "2026-02-12T07:46:52.116991+00:00", "repo": "django/django", "repo_url": "https://github.com/django/django", "license_name": "BSD 3-Clause \"New\" or \"Revised\" License", "license_spdx": "BSD-3-Clause", "pr_number": 20285, "title": "Refs #36619 -- Added third-party licenses to accompany vendored eslint configuration files.", "body": "Missed in #19899.\n\nSources:\nhttps://github.com/[USER_REDACTED]nt/eslint/blob/main/LICENSE\nhttps://github.com/[USER_REDACTED]ndresorhus/globals/blob/main/license", "author": "user_3a67c55598c5", "created_at": "2025-11-20T22:56:09+00:00", "merged_at": "2025-11-26T16:39:02+00:00", "base_branch": "main", "head_branch": "eslint-config-license", "additions": 34, "deletions": 0, "changed_files": 2, "files": [ { "filename": "eslint-recommended.js", "status": "modified", "additions": 22, "deletions": 0, "changes": 22, "patch": "@@ -1,5 +1,27 @@\n /* https://github.com/[USER_REDACTED]nt/eslint/blob/v9.36.0/packages/js/src/configs/eslint-recommended.js */\n \n+/*\n+[NAME_REDACTED] and other contributors, \n+\n+Permission is hereby granted, free of charge, to any person obtaining a copy\n+of this software and associated documentation files (the \"Software\"), to deal\n+in the Software without restriction, including without limitation the rights\n+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n+copies of the Software, and to permit persons to whom the Software is\n+furnished to do so, subject to the following conditions:\n+\n+The above copyright notice and this permission notice shall be included in\n+all copies or substantial portions of the Software.\n+\n+THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n+THE SOFTWARE.\n+*/\n+\n /**\n * [USER_REDACTED] Configuration applied when a user configuration extends from\n * eslint:recommended." }, { "filename": "globals.js", "status": "modified", "additions": 12, "deletions": 0, "changes": 12, "patch": "@@ -1,5 +1,17 @@\n /* https://github.com/[USER_REDACTED]ndresorhus/globals/blob/v16.4.0/globals.json */\n \n+/*\n+MIT License\n+\n+Copyright (c) [NAME_EMAIL_REDACTED] (https://sindresorhus.com)\n+\n+Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:\n+\n+The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.\n+\n+THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n+*/\n+\n \"use strict\";" } ], "reviews": [ { "id": 3490410016, "user": "user_3a67c55598c5", "state": "COMMENTED", "body": null, "submitted_at": "2025-11-20T23:01:47+00:00" }, { "id": 3511235737, "user": "user_057de2f3b132", "state": "APPROVED", "body": null, "submitted_at": "2025-11-26T14:28:31+00:00" } ], "review_comments": [ { "id": 2547978772, "user": "user_3a67c55598c5", "body": "This might be optional since we're not packaging these files, but I didn't want to *forget* to package this file later if we add to it.", "path": "MANIFEST.in", "line": null, "side": "RIGHT", "created_at": "2025-11-20T23:01:47+00:00" } ], "meta": { "languages": [ "js" ], "touches_tests": false, "review_state_summary": { "COMMENTED": 1, "APPROVED": 1 }, "meaningful_comment_count": 1, "has_approval": true, "has_changes_requested": false, "total_review_comments": 1 } } { "_id": "ebc334a041681ee2", "_schema_version": "1.0", "_cleaned_at": "2026-02-12T07:46:52.116991+00:00", "repo": "django/django", "repo_url": "https://github.com/django/django", "license_name": "BSD 3-Clause \"New\" or \"Revised\" License", "license_spdx": "BSD-3-Clause", "pr_number": 20282, "title": "Refs #36735 -- Supported shift parameter for UUID7 on PostgreSQL.", "body": "#### Trac ticket number\nticket-36735\n\n#### Branch description\nExpand on #20101 to support the [`shift` parameter for `UUID7` on PostgreSQL](https://www.postgresql.org/docs/current/functions-uuid.html).\n\n#### Checklist\n- [x] This PR targets the `main` branch. \n- [ ] The commit message is written in past tense, mentions the ticket number, and ends with a period.\n- [ ] I have checked the \"Has patch\" ticket flag in the Trac system.\n- [x] I have added or updated relevant tests.\n- [x] I have added or updated relevant docs, including release notes if applicable.\n- [x] I have attached screenshots in both light and dark modes for any UI changes.", "author": "user_057de2f3b132", "created_at": "2025-11-20T22:15:43+00:00", "merged_at": "2025-12-12T16:50:37+00:00", "base_branch": "main", "head_branch": "uuid7-shift", "additions": 64, "deletions": 5, "changed_files": 7, "files": [ { "filename": "django/db/backends/base/features.py", "status": "modified", "additions": 1, "deletions": 0, "changes": 1, "patch": "@@ -428,6 +428,7 @@ class BaseDatabaseFeatures:\n \n supports_uuid4_function = False\n supports_uuid7_function = False\n+ supports_uuid7_function_shift = False\n \n def __init__(self, connection):\n self.connection = connection" }, { "filename": "django/db/backends/postgresql/features.py", "status": "modified", "additions": 4, "deletions": 0, "changes": 4, "patch": "@@ -85,6 +85,10 @@ class DatabaseFeatures(BaseDatabaseFeatures):\n def supports_uuid7_function(self):\n return self.is_postgresql_18\n \n+ [USER_REDACTED]_property\n+ def supports_uuid7_function_shift(self):\n+ return self.is_postgresql_18\n+\n [USER_REDACTED]_property\n def django_test_skips(self):\n skips = {" }, { "filename": "django/db/models/functions/uuid.py", "status": "modified", "additions": 21, "deletions": 4, "changes": 25, "patch": "@@ -37,13 +37,30 @@ def as_oracle(self, compiler, connection, **extra_context):\n \n class UUID7(Func):\n function = \"UUIDV7\"\n- arity = 0\n+ arity = 1\n output_field = UUIDField()\n \n+ def __init__(self, shift=None, **extra):\n+ super().__init__(shift, **extra)\n+\n+ def _parse_expressions(self, *expressions):\n+ if expressions[0] is None:\n+ expressions = expressions[1:]\n+ return super()._parse_expressions(*expressions)\n+\n def as_sql(self, compiler, connection, **extra_context):\n- if connection.features.supports_uuid7_function:\n- return super().as_sql(compiler, connection, **extra_context)\n- raise NotSupportedError(\"UUID7 is not supported on this database backend.\")\n+ if not connection.features.supports_uuid7_function:\n+ raise NotSupportedError(\"UUID7 is not supported on this database backend.\")\n+\n+ if len(self.source_expressions) == 1:\n+ if not connection.features.supports_uuid7_function_shift:\n+ msg = (\n+ \"The shift argument to UUID7 is not supported \"\n+ \"on this database backend.\"\n+ )\n+ raise NotSupportedError(msg)\n+\n+ return super().as_sql(compiler, connection, **extra_context)\n \n def as_postgresql(self, compiler, connection, **extra_context):\n if connection.features.supports_uuid7_function:" }, { "filename": "docs/ref/models/database-functions.txt", "status": "modified", "additions": 9, "deletions": 1, "changes": 10, "patch": "@@ -1901,7 +1901,7 @@ generated using a cryptographically secure method.\n \n .. versionadded:: 6.1\n \n-.. class:: UUID7()\n+.. class:: UUID7(shift=None)\n \n Generates a :rfc:`version 7 UUID <9562#section-5.7>`, which starts with a\n time-based component.\n@@ -1911,6 +1911,14 @@ time-based component.\n Available on PostgreSQL version 18 or later, MariaDB version 11.7 or later,\n and SQLite on Python version 3.14 or later.\n \n+.. admonition:: ``shift``\n+\n+ On PostgreSQL, ``UUID7`` also supports an optional ``shift`` value, which\n+ can be used to offset the timestamp of the generated UUID. This should be a\n+ :class:`datetime.timedelta` or an expression with an ``output_field`` of\n+ :class:`~django.db.models.DurationField`. A positive value will shift the\n+ timestamp into the future and a negative value into the past.\n+\n Window functions\n ================" }, { "filename": "tests/db_functions/migrations/0002_create_test_models.py", "status": "modified", "additions": 1, "deletions": 0, "changes": 1, "patch": "@@ -92,6 +92,7 @@ class Migration(migrations.Migration):\n name=\"UUIDModel\",\n fields=[\n (\"uuid\", models.UUIDField(null=True)),\n+ (\"shift\", models.DurationField(null=True)),\n ],\n ),\n ]" }, { "filename": "tests/db_functions/models.py", "status": "modified", "additions": 1, "deletions": 0, "changes": 1, "patch": "@@ -59,3 +59,4 @@ class FloatModel(models.Model):\n \n class UUIDModel(models.Model):\n uuid = models.UUIDField(null=True)\n+ shift = models.DurationField(null=True)" }, { "filename": "tests/db_functions/test_uuid.py", "status": "modified", "additions": 27, "deletions": 0, "changes": 27, "patch": "@@ -1,4 +1,5 @@\n import uuid\n+from datetime import datetime, timedelta, timezone\n \n from django.db import NotSupportedError, connection\n from django.db.models.functions import UUID4, UUID7\n@@ -31,6 +32,24 @@ def test_uuid7(self):\n self.assertEqual(m1.uuid.version, 7)\n self.assertNotEqual(m1.uuid, m2.uuid)\n \n+ [USER_REDACTED](\"supports_uuid7_function_shift\")\n+ def test_uuid7_shift(self):\n+ now = datetime.now(timezone.utc)\n+ past = datetime(2005, 11, 16, tzinfo=timezone.utc)\n+ shift = past - now\n+ m = UUIDModel.objects.create(uuid=UUID7(shift))\n+ self.assertTrue(str(m.uuid).startswith(\"0107965e-e40\"), m.uuid)\n+\n+ [USER_REDACTED](\"supports_uuid7_function_shift\")\n+ def test_uuid7_shift_duration_field(self):\n+ now = datetime.now(timezone.utc)\n+ past = datetime(2005, 11, 16, tzinfo=timezone.utc)\n+ shift = past - now\n+ m = UUIDModel.objects.create(shift=shift)\n+ UUIDModel.objects.update(uuid=UUID7(\"shift\"))\n+ m.refresh_from_db()\n+ self.assertTrue(str(m.uuid).startswith(\"0107965e-e40\"), m.uuid)\n+\n [USER_REDACTED](\"supports_uuid4_function\")\n def test_uuid4_unsupported(self):\n if connection.vendor == \"mysql\":\n@@ -62,3 +81,11 @@ def test_uuid7_unsupported(self):\n \n with self.assertRaisesMessage(NotSupportedError, msg):\n UUIDModel.objects.update(uuid=UUID7())\n+\n+ [USER_REDACTED](\"supports_uuid7_function\")\n+ [USER_REDACTED](\"supports_uuid7_function_shift\")\n+ def test_uuid7_shift_unsupported(self):\n+ msg = \"The shift argument to UUID7 is not supported on this database backend.\"\n+\n+ with self.assertRaisesMessage(NotSupportedError, msg):\n+ UUIDModel.objects.update(uuid=UUID7(shift=timedelta(hours=12)))" } ], "reviews": [ { "id": 3564707398, "user": "user_057de2f3b132", "state": "COMMENTED", "body": null, "submitted_at": "2025-12-10T22:09:22+00:00" }, { "id": 3569445023, "user": "user_3a67c55598c5", "state": "COMMENTED", "body": null, "submitted_at": "2025-12-11T21:47:12+00:00" }, { "id": 3569487180, "user": "user_3a67c55598c5", "state": "COMMENTED", "body": "Thanks [USER_REDACTED] 👍", "submitted_at": "2025-12-11T22:19:39+00:00" }, { "id": 3569591510, "user": "user_057de2f3b132", "state": "COMMENTED", "body": null, "submitted_at": "2025-12-11T22:36:41+00:00" }, { "id": 3569619872, "user": "user_3a67c55598c5", "state": "COMMENTED", "body": null, "submitted_at": "2025-12-11T22:49:43+00:00" }, { "id": 3569621733, "user": "user_057de2f3b132", "state": "COMMENTED", "body": null, "submitted_at": "2025-12-11T22:50:45+00:00" }, { "id": 3572631469, "user": "user_3a67c55598c5", "state": "APPROVED", "body": "Thank you 🎉", "submitted_at": "2025-12-12T16:22:43+00:00" } ], "review_comments": [ { "id": 2608390592, "user": "user_057de2f3b132", "body": "I don't think setting this to `arity = 1` (as suggested in https://github.com/[USER_REDACTED]ngo/django/pull/20101#discussion_r2608226079) makes sense, so I've just removed it again. The problem is that setting `arity = 1` means that `shift` becomes required, rather than optional. I'm open to suggestions if there's something I've missed here.", "path": "django/db/models/functions/uuid.py", "line": 40, "side": "LEFT", "created_at": "2025-12-10T22:09:22+00:00" }, { "id": 2612172223, "user": "user_3a67c55598c5", "body": "Makes sense, I forgot we wouldn't have access to the connection's feature flags to do the switch inside `__init__()`. EDIT: I'll propose something below.", "path": "django/db/models/functions/uuid.py", "line": 40, "side": "LEFT", "created_at": "2025-12-11T21:47:12+00:00" }, { "id": 2612209395, "user": "user_3a67c55598c5", "body": "I think we can leverage the order of operations in the `Func` constructor to avoid reimplementing args checking from scratch. This works to get us args checking:\n\n```diff\ndiff --git a/django/db/models/functions/uuid.py b/django/db/models/functions/uuid.py\nindex c41f58d11b..7059798ff3 100644\n--- a/django/db/models/functions/uuid.py\n+++ b/django/db/models/functions/uuid.py\n@@ -37,13 +37,16 @@ class UUID4(Func):\n \n class UUID7(Func):\n function = \"UUIDV7\"\n+ arity = 1\n output_field = UUIDField()\n \n def __init__(self, shift=None, **extra):\n- if shift is None:\n- super().__init__(**extra)\n- else:\n- super().__init__(shift, **extra)\n+ super().__init__(shift, **extra)\n+\n+ def _parse_expressions(self, *expressions):\n+ if expressions[0] is None:\n+ expressions = expressions[1:]\n+ return super()._parse_expressions(*expressions)\n \n def as_sql(self, compiler, connection, **extra_context):\n if not connection.features.supports_uuid7_function:\n```", "path": "django/db/models/functions/uuid.py", "line": 40, "side": "LEFT", "created_at": "2025-12-11T22:02:18+00:00" }, { "id": 2612217387, "user": "user_3a67c55598c5", "body": "I'd probably just add `shift` to the existing model, unless you think that makes the test harder to grok?", "path": "tests/db_functions/models.py", "line": null, "side": "RIGHT", "created_at": "2025-12-11T22:04:12+00:00" }, { "id": 2612234718, "user": "user_3a67c55598c5", "body": "I'd chop, we have other save & reload tests.\n```suggestion\n```", "path": "tests/db_functions/test_uuid.py", "line": null, "side": "RIGHT", "created_at": "2025-12-11T22:09:06+00:00" }, { "id": 2612250867, "user": "user_3a67c55598c5", "body": "These assertions are failing for me:\n```py\nSystem check identified no issues (46 silenced).\nFFs\n======================================================================\nFAIL: test_uuid7_shift (db_functions.test_uuid.TestUUID.test_uuid7_shift)\n----------------------------------------------------------------------\nTraceback (most recent call last):\n File \"/django/source/tests/db_functions/test_uuid.py\", line 44, in test_uuid7_shift\n self.assertTrue(str(m.uuid).startswith(\"0107965e-e400\"))\nAssertionError: False is not true\n\n----------------------------------------------------------------------\n(0.005) INSERT INTO \"db_functions_uuidmodel\" (\"uuid\")\nVALUES (UUIDV7('-7331 days 1:44:20.748468'::interval)) RETURNING \"db_functions_uuidmodel\".\"id\",\n \"db_functions_uuidmodel\".\"uuid\"; args=(datetime.timedelta(days=-7331, seconds=6260, microseconds=748468),); alias=default\n(0.001) SELECT \"db_functions_uuidmodel\".\"id\",\n \"db_functions_uuidmodel\".\"uuid\"\nFROM \"db_functions_uuidmodel\"\nWHERE \"db_functions_uuidmodel\".\"id\" = 5\nLIMIT 21; args=(5,); alias=default\n\n======================================================================\nFAIL: test_uuid7_shift_duration_field (db_functions.test_uuid.TestUUID.test_uuid7_shift_duration_field)\n----------------------------------------------------------------------\nTraceback (most recent call last):\n File \"/django/source/tests/db_functions/test_uuid.py\", line 56, in test_uuid7_shift_duration_field\n self.assertTrue(str(m.uuid).startswith(\"0107965e-e400\"))\nAssertionError: False is not true\n\n----------------------------------------------------------------------\n(0.001) INSERT INTO \"db_functions_uuiddurationmodel\" (\"uuid\",\n \"shift\")\nVALUES (NULL, '-7331 days 1:44:20.725522'::interval) RETURNING \"db_functions_uuiddurationmodel\".\"id\"; args=(None, datetime.timedelta(days=-7331, seconds=6260, microseconds=725522)); alias=default\n(0.001) UPDATE \"db_functions_uuiddurationmodel\"\nSET \"uuid\" = UUIDV7(\"db_functions_uuiddurationmodel\".\"shift\"); args=(); alias=default\n(0.001) SELECT \"db_functions_uuiddurationmodel\".\"id\",\n \"db_functions_uuiddurationmodel\".\"uuid\",\n \"db_functions_uuiddurationmodel\".\"shift\"\nFROM \"db_functions_uuiddurationmodel\"\nWHERE \"db_functions_uuiddurationmodel\".\"id\" = 5\nLIMIT 21; args=(5,); alias=default\n\n----------------------------------------------------------------------\nRan 3 tests in 0.042s\n\nFAILED (failures=2, skipped=1)\n```", "path": "tests/db_functions/test_uuid.py", "line": null, "side": "RIGHT", "created_at": "2025-12-11T22:16:09+00:00" }, { "id": 2612252745, "user": "user_3a67c55598c5", "body": "Backticks around UUID7", "path": "docs/ref/models/database-functions.txt", "line": null, "side": "RIGHT", "created_at": "2025-12-11T22:17:02+00:00" }, { "id": 2612291190, "user": "user_057de2f3b132", "body": "I wonder if this is a timezone difference making the calculation a bit off somewhere.\n\nIt would be useful to see what the uuid actually starts with - if it's only different in the last hexdigit, I think it may be just a precision/timing difference.", "path": "tests/db_functions/test_uuid.py", "line": null, "side": "RIGHT", "created_at": "2025-12-11T22:36:41+00:00" }, { "id": 2612315206, "user": "user_3a67c55598c5", "body": "Sure thing. Maybe worth tweaking the assertion so it's always there.\n\n```py\nAssertionError: False is not true : 0107965e-e40a-7380-b548-5e3709b94f41\nAssertionError: False is not true : 0107965e-e406-72a3-9cf2-ac4f75411952\n```", "path": "tests/db_functions/test_uuid.py", "line": null, "side": "RIGHT", "created_at": "2025-12-11T22:49:43+00:00" }, { "id": 2612316993, "user": "user_057de2f3b132", "body": "Yeah, looks like it's just a precision issue in the last hexdigit of the timestamp part.", "path": "tests/db_functions/test_uuid.py", "line": null, "side": "RIGHT", "created_at": "2025-12-11T22:50:45+00:00" } ], "meta": { "languages": [ "py", "txt" ], "touches_tests": true, "review_state_summary": { "COMMENTED": 6, "APPROVED": 1 }, "meaningful_comment_count": 10, "has_approval": true, "has_changes_requested": false, "total_review_comments": 10 } } { "_id": "70ad8ff73fef33f6", "_schema_version": "1.0", "_cleaned_at": "2026-02-12T07:46:52.116991+00:00", "repo": "django/django", "repo_url": "https://github.com/django/django", "license_name": "BSD 3-Clause \"New\" or \"Revised\" License", "license_spdx": "BSD-3-Clause", "pr_number": 20279, "title": "A few scripts to rule them all.", "body": "#### Branch description\nUnify location of maintainer's scripts and avoid packaging them.\n\nMore details: https://forum.djangoproject.com/t/avoid-packaging-scripts-folder/43296\n\nScripts were taken from:\n* https://code.djangoproject.com/wiki/MergerTips\n* https://code.djangoproject.com/wiki/ReleaseScript\n* https://code.djangoproject.com/wiki/ReleaseTestNewVersion\n* https://djangoci.com/job/confirm-release/ (currently not working there but works locally)\n\n#### Checklist\n- [X] This PR targets the `main` branch. \n- [X] The commit message is written in past tense, mentions the ticket number, and ends with a period.", "author": "user_00dac951cdbf", "created_at": "2025-11-20T16:59:49+00:00", "merged_at": "2025-11-21T18:36:25+00:00", "base_branch": "main", "head_branch": "scripts-to-rule-them-all", "additions": 367, "deletions": 1, "changed_files": 5, "files": [ { "filename": "MANIFEST.in", "status": "modified", "additions": 1, "deletions": 1, "changes": 2, "patch": "@@ -11,6 +11,6 @@ graft django\n graft docs\n graft extras\n graft js_tests\n-graft scripts\n graft tests\n global-exclude *.py[co]\n+prune scripts" }, { "filename": "scripts/backport.sh", "status": "added", "additions": 35, "deletions": 0, "changes": 35, "patch": "@@ -0,0 +1,35 @@\n+#!/bin/bash\n+\n+# Backport helper for Django stable branches.\n+\n+set -xue\n+\n+if [ -z $1 ]; then\n+ echo \"Full hash of commit to backport is required.\"\n+ exit\n+fi\n+\n+BRANCH_NAME=`git branch | sed -n '/\\* stable\\//s///p'`\n+echo $BRANCH_NAME\n+\n+# Ensure clean working directory\n+git reset --hard\n+\n+REV=$1\n+\n+TMPFILE=tmplog.tmp\n+\n+# Cherry-pick the commit\n+git cherry-pick ${REV}\n+\n+# Create new log message by [NAME_REDACTED]\n+git log --pretty=format:\"[${BRANCH_NAME}] %s%n%n%b%nBackport of ${REV} from main.\" HEAD^..HEAD \\\n+ | grep -v '^BP$' > ${TMPFILE}\n+\n+# Commit new log message\n+git commit --amend -F ${TMPFILE}\n+\n+# Clean up temporary files\n+rm -f ${TMPFILE}\n+\n+git show" }, { "filename": "scripts/confirm_release.sh", "status": "added", "additions": 57, "deletions": 0, "changes": 57, "patch": "@@ -0,0 +1,57 @@\n+#! /bin/bash\n+\n+set -xue\n+\n+CHECKSUM_FILE=\"Django-${VERSION}.checksum.txt\"\n+MEDIA_URL_PREFIX=\"https://media.djangoproject.com\"\n+RELEASE_URL_PREFIX=\"https://www.djangoproject.com/m/releases/\"\n+DOWNLOAD_PREFIX=\"https://www.djangoproject.com/download\"\n+\n+if [[ ! \"${VERSION}\" =~ ^[0-9]+\\.[0-9]+(\\.[0-9]+|a[0-9]+|b[0-9]+|rc[0-9]+)?$ ]] ; then\n+ echo \"Not a valid version\"\n+fi\n+\n+rm -rf \"${VERSION}\"\n+mkdir \"${VERSION}\"\n+cd \"${VERSION}\"\n+\n+function cleanup {\n+ cd ..\n+ rm -rf \"${VERSION}\"\n+}\n+trap cleanup EXIT\n+\n+echo \"Download checksum file ...\"\n+curl --fail --output \"$CHECKSUM_FILE\" \"${MEDIA_URL_PREFIX}/pgp/${CHECKSUM_FILE}\"\n+\n+echo \"Verify checksum file ...\"\n+if [ -n \"${GPG_KEY}\" ] ; then\n+ gpg --recv-keys \"${GPG_KEY}\"\n+fi\n+gpg --verify \"${CHECKSUM_FILE}\"\n+\n+echo \"Finding release artifacts ...\"\n+mapfile -t RELEASE_ARTIFACTS < <(grep \"${DOWNLOAD_PREFIX}\" \"${CHECKSUM_FILE}\")\n+\n+echo \"Found these release artifacts: \"\n+for ARTIFACT_URL in \"${RELEASE_ARTIFACTS[@]}\" ; do\n+ echo \"- $ARTIFACT_URL\"\n+done\n+\n+echo \"Downloading artifacts ...\"\n+for ARTIFACT_URL in \"${RELEASE_ARTIFACTS[@]}\" ; do\n+ ARTIFACT_ACTUAL_URL=$(curl --head --write-out '%{redirect_url}' --output /dev/null --silent \"${ARTIFACT_URL}\")\n+ curl --location --fail --output \"$(basename \"${ARTIFACT_ACTUAL_URL}\")\" \"${ARTIFACT_ACTUAL_URL}\"\n+\n+done\n+\n+echo \"Verifying artifact hashes ...\"\n+# The `2> /dev/null` moves notes like \"sha256sum: WARNING: 60 lines are improperly formatted\"\n+# to /dev/null. That's fine because the return code of the script is still set on error and a\n+# wrong checksum will still show up as `FAILED`\n+echo \"- MD5 checksums\"\n+md5sum --check \"${CHECKSUM_FILE}\" 2> /dev/null\n+echo \"- SHA1 checksums\"\n+sha1sum --check \"${CHECKSUM_FILE}\" 2> /dev/null\n+echo \"- SHA256 checksums\"\n+sha256sum --check \"${CHECKSUM_FILE}\" 2> /dev/null" }, { "filename": "scripts/do_django_release.py", "status": "added", "additions": 226, "deletions": 0, "changes": 226, "patch": "@@ -0,0 +1,226 @@\n+#! /usr/bin/env python\n+\n+\"\"\"Helper to build and publish Django artifacts.\n+\n+Original author: [NAME_REDACTED].\n+Other authors: [NAME_REDACTED], [NAME_REDACTED].\n+\n+\"\"\"\n+\n+import hashlib\n+import os\n+import re\n+import subprocess\n+from datetime import date\n+\n+PGP_KEY_ID = os.getenv(\"PGP_KEY_ID\")\n+PGP_KEY_URL = os.getenv(\"PGP_KEY_URL\")\n+PGP_EMAIL = os.getenv(\"PGP_EMAIL\")\n+DEST_FOLDER = os.path.expanduser(os.getenv(\"DEST_FOLDER\"))\n+\n+assert (\n+ PGP_KEY_ID\n+), \"Missing PGP_KEY_ID: Set this env var to your PGP key ID (used for signing).\"\n+assert (\n+ PGP_KEY_URL\n+), \"Missing PGP_KEY_URL: Set this env var to your PGP public key URL (for fetching).\"\n+assert DEST_FOLDER and os.path.exists(\n+ DEST_FOLDER\n+), \"Missing DEST_FOLDER: Set this env var to the local path to place the artifacts.\"\n+\n+\n+checksum_file_text = \"\"\"This file contains MD5, SHA1, and SHA256 checksums for the\n+source-code tarball and wheel files of Django {django_version}, released {release_date}.\n+\n+To use this file, you will need a working install of PGP or other\n+compatible public-key encryption software. You will also need to have\n+the Django release manager's public key in your keyring. This key has\n+the ID ``{pgp_key_id}`` and can be imported from the MIT\n+keyserver, for example, if using the open-source GNU [NAME_REDACTED]\n+implementation of PGP:\n+\n+ gpg --keyserver pgp.mit.edu --recv-key {pgp_key_id}\n+\n+or via the GitHub API:\n+\n+ curl {pgp_key_url} | gpg --import -\n+\n+Once the key is imported, verify this file:\n+\n+ gpg --verify {checksum_file_name}\n+\n+Once you have verified this file, you can use normal MD5, SHA1, or SHA256\n+checksumming applications to generate the checksums of the Django\n+package and compare them to the checksums listed below.\n+\n+Release packages\n+================\n+\n+https://www.djangoproject.com/download/{django_version}/tarball/\n+https://www.djangoproject.com/download/{django_version}/wheel/\n+\n+MD5 checksums\n+=============\n+\n+{md5_tarball} {tarball_name}\n+{md5_wheel} {wheel_name}\n+\n+SHA1 checksums\n+==============\n+\n+{sha1_tarball} {tarball_name}\n+{sha1_wheel} {wheel_name}\n+\n+SHA256 checksums\n+================\n+\n+{sha256_tarball} {tarball_name}\n+{sha256_wheel} {wheel_name}\n+\n+\"\"\"\n+\n+\n+def build_artifacts():\n+ from build.__main__ import main as build_main\n+\n+ build_main([])\n+\n+\n+def do_checksum(checksum_algo, release_file):\n+ with open(os.path.join(dist_path, release_file), \"rb\") as f:\n+ return checksum_algo(f.read()).hexdigest()\n+\n+\n+# Ensure the working directory is clean.\n+subprocess.call([\"git\", \"clean\", \"-fdx\"])\n+\n+django_repo_path = os.path.abspath(os.path.curdir)\n+dist_path = os.path.join(django_repo_path, \"dist\")\n+\n+# Build release files.\n+build_artifacts()\n+release_files = os.listdir(dist_path)\n+wheel_name = None\n+tarball_name = None\n+for f in release_files:\n+ if f.endswith(\".whl\"):\n+ wheel_name = f\n+ if f.endswith(\".tar.gz\"):\n+ tarball_name = f\n+\n+assert wheel_name is not None\n+assert tarball_name is not None\n+\n+django_version = wheel_name.split(\"-\")[1]\n+django_major_version = \".\".join(django_version.split(\".\")[:2])\n+\n+artifacts_path = os.path.join(os.path.expanduser(DEST_FOLDER), django_version)\n+os.makedirs(artifacts_path, exist_ok=True)\n+\n+# Chop alpha/beta/rc suffix\n+match = re.search(\"[abrc]\", django_major_version)\n+if match:\n+ django_major_version = django_major_version[: match.start()]\n+\n+release_date = date.today().strftime(\"%B %-d, %Y\")\n+checksum_file_name = f\"Django-{django_version}.checksum.txt\"\n+checksum_file_kwargs = dict(\n+ release_date=release_date,\n+ pgp_key_id=PGP_KEY_ID,\n+ django_version=django_version,\n+ pgp_key_url=PGP_KEY_URL,\n+ checksum_file_name=checksum_file_name,\n+ wheel_name=wheel_name,\n+ tarball_name=tarball_name,\n+)\n+checksums = (\n+ (\"md5\", hashlib.md5),\n+ (\"sha1\", hashlib.sha1),\n+ (\"sha256\", hashlib.sha256),\n+)\n+for checksum_name, checksum_algo in checksums:\n+ checksum_file_kwargs[f\"{checksum_name}_tarball\"] = do_checksum(\n+ checksum_algo, tarball_name\n+ )\n+ checksum_file_kwargs[f\"{checksum_name}_wheel\"] = do_checksum(\n+ checksum_algo, wheel_name\n+ )\n+\n+# Create the checksum file\n+checksum_file_text = checksum_file_text.format(**checksum_file_kwargs)\n+checksum_file_path = os.path.join(artifacts_path, checksum_file_name)\n+with open(checksum_file_path, \"wb\") as f:\n+ f.write(checksum_file_text.encode(\"ascii\"))\n+\n+print(\"\\n\\nDiffing release with checkout for sanity check.\")\n+\n+# Unzip and diff...\n+unzip_command = [\n+ \"unzip\",\n+ \"-q\",\n+ os.path.join(dist_path, wheel_name),\n+ \"-d\",\n+ os.path.join(dist_path, django_major_version),\n+]\n+subprocess.run(unzip_command)\n+diff_command = [\n+ \"diff\",\n+ \"-qr\",\n+ \"./django/\",\n+ os.path.join(dist_path, django_major_version, \"django\"),\n+]\n+subprocess.run(diff_command)\n+subprocess.run(\n+ [\n+ \"rm\",\n+ \"-rf\",\n+ os.path.join(dist_path, django_major_version),\n+ ]\n+)\n+\n+print(\"\\n\\n=> Commands to run NOW:\")\n+\n+# Sign the checksum file, this may prompt for a passphrase.\n+pgp_email = f\"-u {PGP_EMAIL} \" if PGP_EMAIL else \"\"\n+print(f\"gpg --clearsign {pgp_email}--digest-algo SHA256 {checksum_file_path}\")\n+# Create, verify and push tag\n+print(f'git tag --sign --message=\"Tag {django_version}\" {django_version}')\n+print(f\"git tag --verify {django_version}\")\n+\n+# Copy binaries outside the current repo tree to avoid lossing them.\n+subprocess.run([\"cp\", \"-r\", dist_path, artifacts_path])\n+\n+# Make the binaries available to the world\n+print(\n+ \"\\n\\n=> These ONLY 15 MINUTES BEFORE RELEASE TIME (consider new terminal \"\n+ \"session with isolated venv)!\"\n+)\n+\n+# Upload the checksum file and release artifacts to the djangoproject admin.\n+print(\n+ \"\\n==> ACTION Add tarball, wheel, and checksum files to the Release entry at:\"\n+ f\"https://www.djangoproject.com/admin/releases/release/{django_version}\"\n+)\n+print(\n+ f\"* Tarball and wheel from {artifacts_path}\\n\"\n+ f\"* Signed checksum {checksum_file_path}.asc\"\n+)\n+\n+# Test the new version and confirm the signature using Jenkins.\n+print(\"\\n==> ACTION Test the release artifacts:\")\n+print(f\"VERSION={django_version} test_new_version.sh\")\n+\n+print(\"\\n==> ACTION Run confirm-release job:\")\n+print(f\"VERSION={django_version} confirm_release.sh\")\n+\n+# Upload to PyPI.\n+print(\"\\n==> ACTION Upload to PyPI, ensure your release venv is activated:\")\n+print(f\"cd {artifacts_path}\")\n+print(\"pip install -U pip twine\")\n+print(\"twine upload --repository django dist/*\")\n+\n+# Push the tags.\n+print(\"\\n==> ACTION Push the tags:\")\n+print(\"git push --tags\")\n+\n+print(\"\\n\\nDONE!!!\")" }, { "filename": "scripts/test_new_version.sh", "status": "added", "additions": 48, "deletions": 0, "changes": 48, "patch": "@@ -0,0 +1,48 @@\n+#! /bin/bash\n+\n+# Original author: [NAME_REDACTED].\n+\n+set -xue\n+\n+cd /tmp\n+\n+RELEASE_VERSION=\"${VERSION}\"\n+if [[ -z \"$RELEASE_VERSION\" ]]; then\n+ echo \"Please set VERSION as env var\"\n+ exit 1\n+fi\n+\n+PKG_TAR=$(curl -Ls -o /dev/null -w '%{url_effective}' https://www.djangoproject.com/download/$RELEASE_VERSION/tarball/)\n+echo $PKG_TAR\n+\n+PKG_WHL=$(curl -Ls -o /dev/null -w '%{url_effective}' https://www.djangoproject.com/download/$RELEASE_VERSION/wheel/)\n+echo $PKG_WHL\n+\n+python3 -m venv django-pip\n+. django-pip/bin/activate\n+python -m pip install --no-cache-dir $PKG_TAR\n+django-admin startproject test_one\n+cd test_one\n+./manage.py --help # Ensure executable bits\n+python manage.py migrate\n+python manage.py runserver\n+\n+deactivate\n+cd ..\n+rm -rf test_one\n+rm -rf django-pip\n+\n+\n+python3 -m venv django-pip-wheel\n+. django-pip-wheel/bin/activate\n+python -m pip install --no-cache-dir $PKG_WHL\n+django-admin startproject test_one\n+cd test_one\n+./manage.py --help # Ensure executable bits\n+python manage.py migrate\n+python manage.py runserver\n+\n+deactivate\n+cd ..\n+rm -rf test_one\n+rm -rf django-pip-wheel" } ], "reviews": [ { "id": 3490495150, "user": "user_3a67c55598c5", "state": "APPROVED", "body": "LGTM!\n\n(spotted a typo for \"artifacts\" in the second commit msg)\n\nI'll look forward to managing improvements over pull requests instead of via the wiki.", "submitted_at": "2025-11-20T23:20:59+00:00" }, { "id": 3490646677, "user": "user_657e90e5ae46", "state": "COMMENTED", "body": "You needn't credit me.", "submitted_at": "2025-11-21T00:38:03+00:00" }, { "id": 3492393352, "user": "user_00dac951cdbf", "state": "COMMENTED", "body": null, "submitted_at": "2025-11-21T11:41:34+00:00" } ], "review_comments": [ { "id": 2548138540, "user": "user_657e90e5ae46", "body": "What's this?", "path": "scripts/backport.sh", "line": null, "side": "RIGHT", "created_at": "2025-11-21T00:31:56+00:00" }, { "id": 2549491334, "user": "user_00dac951cdbf", "body": "Good catch, it comes from the script in the wiki and I never paid attention to that part. Will remove it.", "path": "scripts/backport.sh", "line": null, "side": "RIGHT", "created_at": "2025-11-21T11:41:34+00:00" } ], "meta": { "languages": [ "in", "py", "sh" ], "touches_tests": false, "review_state_summary": { "APPROVED": 1, "COMMENTED": 2 }, "meaningful_comment_count": 2, "has_approval": true, "has_changes_requested": false, "total_review_comments": 2 } } { "_id": "46b6b155df1e6378", "_schema_version": "1.0", "_cleaned_at": "2026-02-12T07:46:52.132616+00:00", "repo": "django/django", "repo_url": "https://github.com/django/django", "license_name": "BSD 3-Clause \"New\" or \"Revised\" License", "license_spdx": "BSD-3-Clause", "pr_number": 20274, "title": "Fixed #36741 -- [NAME_REDACTED]() bulk-friendliness discussion from bulk_update() caveats.", "body": "#### Trac ticket number\nticket-36741\n\n#### Branch description\nThis PR adds a link in the `bulk_update()` caveats section of the QuerySet\ndocumentation to the admonition about `Model.save()` being not bulk-friendly \n(:ref:`model_save_bulk_friendly`) in `topics/db/models.txt`.\n\nThis provides clearer guidance on why `save()` methods and `pre_save`/`post_save`\nsignals are not triggered during bulk operations, making the relationship between\n`bulk_update()` and overridden model methods more explicit.\n\n#### Checklist\n- [x] This PR targets the `main` branch.\n- [x] The commit message is written in past tense, mentions the ticket number indirectly through the PR/trac reference, and ends with a period.\n- [x] I have checked the \"Has patch\" ticket flag in the Trac system.\n- [ ] I have added or updated relevant tests. *(N/A — docs-only change)*\n- [x] I have added or updated relevant docs. \n- [ ] I have attached screenshots in both light and dark modes for any UI changes. *(N/A — no UI changes)*", "author": "user_b787990f7421", "created_at": "2025-11-20T06:06:59+00:00", "merged_at": "2025-11-21T22:06:18+00:00", "base_branch": "main", "head_branch": "ticket-36741-bulk-update-doc-link", "additions": 15, "deletions": 10, "changed_files": 2, "files": [ { "filename": "docs/ref/models/querysets.txt", "status": "modified", "additions": 13, "deletions": 10, "changes": 23, "patch": "@@ -2432,7 +2432,8 @@ are), and returns created objects as a list, in the same order as provided:\n \n This has a number of caveats though:\n \n-* The model's ``save()`` method will not be called, and the ``pre_save`` and\n+* The model's ``save()`` method :ref:`will not be called\n+ `, and the ``pre_save`` and\n ``post_save`` signals will not be sent.\n * It does not work with child models in a multi-table inheritance scenario.\n * If the model's primary key is an :class:`~django.db.models.AutoField` or has\n@@ -2513,7 +2514,8 @@ than iterating through the list of models and calling ``save()`` on each of\n them, but it has a few caveats:\n \n * You cannot update the model's primary key.\n-* Each model's ``save()`` method isn't called, and the\n+* Each model's ``save()`` method :ref:`isn't called\n+ `, and the\n :attr:`~django.db.models.signals.pre_save` and\n :attr:`~django.db.models.signals.post_save` signals aren't sent.\n * If updating a large number of columns in a large number of rows, the SQL\n@@ -2999,7 +3001,8 @@ and calling ``save()``.\n such filter conditions on MySQL.\n \n Finally, realize that ``update()`` does an update at the SQL level and, thus,\n-does not call any ``save()`` methods on your models, nor does it emit the\n+method :ref:`does not call` any\n+``save()`` methods on your models, nor does it emit the\n :attr:`~django.db.models.signals.pre_save` or\n :attr:`~django.db.models.signals.post_save` signals (which are a consequence of\n calling :meth:`Model.save() `). If you want to\n@@ -3072,13 +3075,13 @@ This cascade behavior is customizable via the\n :attr:`~django.db.models.ForeignKey.on_delete` argument to the\n :class:`~django.db.models.ForeignKey`.\n \n-The ``delete()`` method does a bulk delete and does not call any ``delete()``\n-methods on your models. It does, however, emit the\n-:data:`~django.db.models.signals.pre_delete` and\n-:data:`~django.db.models.signals.post_delete` signals for all deleted objects\n-(including cascaded deletions). Signals won't be sent when ``DB_CASCADE`` is\n-used. Also, ``delete()`` doesn't return information about objects deleted from\n-database variants (``DB_*``) of the\n+The ``delete()`` method does a bulk delete and :ref:`does not call\n+` any ``delete()`` methods on your\n+models. It does, however, emit the :data:`~django.db.models.signals.pre_delete`\n+and :data:`~django.db.models.signals.post_delete` signals for all deleted\n+objects (including cascaded deletions). Signals won't be sent when\n+``DB_CASCADE`` is used. Also, ``delete()`` doesn't return information about\n+objects deleted from database variants (``DB_*``) of the\n :attr:`~django.db.models.ForeignKey.on_delete` argument, e.g. ``DB_CASCADE``.\n \n Django won’t need to fetch objects into memory when deleting them in the" }, { "filename": "docs/topics/db/models.txt", "status": "modified", "additions": 2, "deletions": 0, "changes": 2, "patch": "@@ -964,6 +964,8 @@ example::\n \n See :ref:`ref-models-update-fields` for more details.\n \n+.. _methods-not-called-on-bulk-operations:\n+\n .. admonition:: Overridden model methods are not called on bulk operations\n \n Note that the :meth:`~Model.delete` method for an object is not" } ], "reviews": [ { "id": 3489921085, "user": "user_3a67c55598c5", "state": "COMMENTED", "body": "Thanks, be sure to build the docs to ensure they build 👍", "submitted_at": "2025-11-20T21:04:00+00:00" }, { "id": 3493404476, "user": "user_3a67c55598c5", "state": "APPROVED", "body": "Thanks for the PR 👍 .\n\nI added the same link in a few analogous places.\n\nWelcome aboard ⛵️!", "submitted_at": "2025-11-21T16:00:04+00:00" } ], "review_comments": [ { "id": 2547661816, "user": "user_3a67c55598c5", "body": "Let's remove this and just make the existing text below a link.", "path": "docs/ref/models/querysets.txt", "line": null, "side": "RIGHT", "created_at": "2025-11-20T21:02:36+00:00" }, { "id": 2547663067, "user": "user_3a67c55598c5", "body": "\"isn't called\" could be a Sphinx link to your new target.", "path": "docs/ref/models/querysets.txt", "line": null, "side": "RIGHT", "created_at": "2025-11-20T21:02:56+00:00" }, { "id": 2547665397, "user": "user_3a67c55598c5", "body": "Bulk-friendly was colloquial shorthand from the ticket discussion. Let's try something like `methods-not-called-on-bulk-operations`", "path": "docs/topics/db/models.txt", "line": null, "side": "RIGHT", "created_at": "2025-11-20T21:03:42+00:00" } ], "meta": { "languages": [ "txt" ], "touches_tests": false, "review_state_summary": { "COMMENTED": 1, "APPROVED": 1 }, "meaningful_comment_count": 3, "has_approval": true, "has_changes_requested": false, "total_review_comments": 3 } } { "_id": "f9d355ee66fa266e", "_schema_version": "1.0", "_cleaned_at": "2026-02-12T07:46:52.132616+00:00", "repo": "django/django", "repo_url": "https://github.com/django/django", "license_name": "BSD 3-Clause \"New\" or \"Revised\" License", "license_spdx": "BSD-3-Clause", "pr_number": 20271, "title": "Fixed #36305 -- Added documentation indentation guidelines to contributing docs.", "body": "#### Trac ticket number\n\n\nticket-36305\n\n#### Fixed\n- Corrected directive content indentation in:\n - `docs/ref/checks.txt`\n - `docs/ref/middleware.txt`\n- Ensured all directive descriptions, options, and inner content follow\n Sphinx’s indentation rules (4 spaces).\n- Wrapped long lines to meet Django’s 79-character documentation guideline.\n- Added a guideline explaining directive content indentation to:\n - `docs/internals/contributing/writing-documentation.txt`\n \n#### Checklist\n- [x] This PR targets the `main` branch. \n- [x] The commit message is written in past tense, mentions the ticket number, and ends with a period.\n- [x] I have checked the \"Has patch\" ticket flag in the Trac system.\n- [ ] I have added or updated relevant tests.\n- [x] I have added or updated relevant docs, including release notes if applicable.\n- [ ] I have attached screenshots in both light and dark modes for any UI changes.", "author": "user_bf0d176c89c9", "created_at": "2025-11-19T17:04:00+00:00", "merged_at": "2025-12-22T19:42:00+00:00", "base_branch": "main", "head_branch": "ticket_36305", "additions": 122, "deletions": 83, "changed_files": 3, "files": [ { "filename": "docs/internals/contributing/writing-documentation.txt", "status": "modified", "additions": 37, "deletions": 0, "changes": 37, "patch": "@@ -420,6 +420,43 @@ documentation:\n * Use :rst:role:`:cve:` to reference a [NAME_REDACTED] and\n Exposures (CVE) identifier. For example, use ``:cve:`2019-14232```.\n \n+* When documenting Python objects (classes, methods, attributes, etc.) using\n+ `Sphinx directives`__ such as ``.. class::``, ``.. method::``, and\n+ ``.. attribute::``, all content must be properly indented to ensure correct\n+ rendering and to support features like automatic table of contents\n+ generation.\n+\n+ Follow these rules:\n+\n+ * The directive itself remains flush with the left margin (no indentation).\n+ * All descriptive text under the directive must be indented by 4 spaces.\n+ * Multi-line descriptions must keep the same indentation level.\n+ * Nested directives (for example, methods inside a class) require an\n+ additional 4 spaces of indentation to maintain hierarchy.\n+ * Field lists (such as ``:param:``, ``:returns:``, etc.) must align with the\n+ directive's content level.\n+\n+ Example:\n+\n+ .. code-block:: rst\n+\n+ .. class:: MyClass\n+\n+ A brief description of the class.\n+\n+ .. method:: my_method(arg1, arg2)\n+\n+ Method description.\n+\n+ :param arg1: Description of the first parameter\n+ :param arg2: Description of the second parameter\n+\n+ .. attribute:: my_attribute\n+\n+ Attribute description.\n+\n+__ https://www.sphinx-doc.org/en/master/usage/restructuredtext/basics.html\n+\n Django-specific markup\n ======================" }, { "filename": "docs/ref/checks.txt", "status": "modified", "additions": 36, "deletions": 36, "changes": 72, "patch": "@@ -19,42 +19,42 @@ API reference\n \n .. class:: CheckMessage(level, msg, hint=None, obj=None, id=None)\n \n-The warnings and errors raised by [NAME_REDACTED] instances of\n-``CheckMessage``. An instance encapsulates a single reportable error or\n-warning. It also provides context and hints applicable to the message, and a\n-unique identifier that is used for filtering purposes.\n-\n-Constructor arguments are:\n-\n-``level``\n- The severity of the message. Use one of the predefined values: ``DEBUG``,\n- ``INFO``, ``WARNING``, ``ERROR``, ``CRITICAL``. If the level is greater or\n- equal to ``ERROR``, then Django will prevent management commands from\n- executing. Messages with level lower than ``ERROR`` (i.e. warnings) are\n- reported to the console, but can be silenced.\n-\n-``msg``\n- A short (less than 80 characters) string describing the problem. The string\n- should *not* contain newlines.\n-\n-``hint``\n- A single-line string providing a hint for fixing the problem. If no hint\n- can be provided, or the hint is self-evident from the error message, the\n- hint can be omitted, or a value of ``None`` can be used.\n-\n-``obj``\n- Optional. An object providing context for the message (for example, the\n- model where the problem was discovered). The object should be a model,\n- field, or manager or any other object that defines a ``__str__()`` method.\n- The method is used while reporting all messages and its result precedes the\n- message.\n-\n-``id``\n- Optional string. A unique identifier for the issue. Identifiers should\n- follow the pattern ``applabel.X001``, where ``X`` is one of the letters\n- ``CEWID``, indicating the message severity (``C`` for criticals, ``E`` for\n- errors and so). The number can be allocated by [NAME_REDACTED], but should\n- be unique within that application.\n+ The warnings and errors raised by [NAME_REDACTED] instances of\n+ ``CheckMessage``. An instance encapsulates a single reportable error or\n+ warning. It also provides context and hints applicable to the message, and\n+ a unique identifier that is used for filtering purposes.\n+\n+ Constructor arguments are:\n+\n+ ``level``\n+ The severity of the message. Use one of the predefined values: ``DEBUG``\n+ , ``INFO``, ``WARNING``, ``ERROR``, ``CRITICAL``. If the level is\n+ greater or equal to ``ERROR``, then Django will prevent management\n+ commands from executing. Messages with level lower than ``ERROR``\n+ (i.e. warnings) are reported to the console, but can be silenced.\n+\n+ ``msg``\n+ A short (less than 80 characters) string describing the problem. The\n+ string should *not* contain newlines.\n+\n+ ``hint``\n+ A single-line string providing a hint for fixing the problem. If no hint\n+ can be provided, or the hint is self-evident from the error message, the\n+ hint can be omitted, or a value of ``None`` can be used.\n+\n+ ``obj``\n+ Optional. An object providing context for the message (for example, the\n+ model where the problem was discovered). The object should be a model,\n+ field, or manager or any other object that defines a ``__str__()``\n+ method. The method is used while reporting all messages and its result\n+ precedes the message.\n+\n+ ``id``\n+ Optional string. A unique identifier for the issue. Identifiers should\n+ follow the pattern ``applabel.X001``, where ``X`` is one of the letters\n+ ``CEWID``, indicating the message severity (``C`` for criticals, ``E``\n+ for errors and so). The number can be allocated by [NAME_REDACTED], but\n+ should be unique within that application.\n \n There are subclasses to make creating messages with common levels easier. When\n using them you can omit the ``level`` argument because it is implied by the" }, { "filename": "docs/ref/middleware.txt", "status": "modified", "additions": 49, "deletions": 47, "changes": 96, "patch": "@@ -147,14 +147,14 @@ Conditional GET middleware\n \n .. class:: ConditionalGetMiddleware\n \n-Handles conditional GET operations. If the response doesn't have an ``ETag``\n-header, the middleware adds one if needed. If the response has an ``ETag`` or\n-``Last-Modified`` header, and the request has ``If-None-Match`` or\n-``If-Modified-Since``, the response is replaced by an\n-:class:`~django.http.HttpResponseNotModified`.\n+ Handles conditional GET operations. If the response doesn't have an\n+ ``ETag`` header, the middleware adds one if needed. If the response has an\n+ ``ETag`` or ``Last-Modified`` header, and the request has ``If-None-Match``\n+ or ``If-Modified-Since``, the response is replaced by an\n+ :class:`~django.http.HttpResponseNotModified`.\n \n-You can handle conditional GET operations with individual views using the\n-:func:`~django.views.decorators.http.conditional_page` decorator.\n+ You can handle conditional GET operations with individual views using the\n+ :func:`~django.views.decorators.http.conditional_page` decorator.\n \n Locale middleware\n -----------------\n@@ -170,9 +170,9 @@ Locale middleware\n ``LocaleMiddleware`` and override the attribute to customize the\n redirects issued by [NAME_REDACTED]\n \n-Enables language selection based on data from the request. It customizes\n-content for each user. See the :doc:`internationalization documentation\n-`.\n+ Enables language selection based on data from the request. It customizes\n+ content for each user. See the :doc:`internationalization documentation\n+ `.\n \n Message middleware\n ------------------\n@@ -182,8 +182,8 @@ Message middleware\n \n .. class:: MessageMiddleware\n \n-Enables cookie- and session-based message support. See the\n-:doc:`messages documentation `.\n+ Enables cookie- and session-based message support. See the\n+ :doc:`messages documentation `.\n \n .. _security-middleware:\n \n@@ -202,19 +202,19 @@ Security middleware\n \n .. class:: SecurityMiddleware\n \n-The ``django.middleware.security.SecurityMiddleware`` provides several security\n-enhancements to the request/response cycle. Each one can be independently\n-enabled or disabled with a setting.\n+ The ``django.middleware.security.SecurityMiddleware`` provides several\n+ security enhancements to the request/response cycle. Each one can be\n+ independently enabled or disabled with a setting.\n \n-* :setting:`SECURE_CONTENT_TYPE_NOSNIFF`\n-* :setting:`SECURE_CROSS_ORIGIN_OPENER_POLICY`\n-* :setting:`SECURE_HSTS_INCLUDE_SUBDOMAINS`\n-* :setting:`SECURE_HSTS_PRELOAD`\n-* :setting:`SECURE_HSTS_SECONDS`\n-* :setting:`SECURE_REDIRECT_EXEMPT`\n-* :setting:`SECURE_REFERRER_POLICY`\n-* :setting:`SECURE_SSL_HOST`\n-* :setting:`SECURE_SSL_REDIRECT`\n+ * :setting:`SECURE_CONTENT_TYPE_NOSNIFF`\n+ * :setting:`SECURE_CROSS_ORIGIN_OPENER_POLICY`\n+ * :setting:`SECURE_HSTS_INCLUDE_SUBDOMAINS`\n+ * :setting:`SECURE_HSTS_PRELOAD`\n+ * :setting:`SECURE_HSTS_SECONDS`\n+ * :setting:`SECURE_REDIRECT_EXEMPT`\n+ * :setting:`SECURE_REFERRER_POLICY`\n+ * :setting:`SECURE_SSL_HOST`\n+ * :setting:`SECURE_SSL_REDIRECT`\n \n .. _http-strict-transport-security:\n \n@@ -339,11 +339,13 @@ this setting are:\n Instructs the browser to send the full URL as the referrer for same-origin\n links, and only the origin for cross-origin links.\n \n-``same-origin`` Instructs the browser to send a full URL, but only for\n-same-origin links. No referrer will be sent for cross-origin links.\n+``same-origin``\n+ Instructs the browser to send a full URL, but only for\n+ same-origin links. No referrer will be sent for cross-origin links.\n \n-``strict-origin`` Instructs the browser to send only the origin, not the full\n-URL, and to send no referrer when a protocol downgrade occurs.\n+``strict-origin``\n+ Instructs the browser to send only the origin, not the full\n+ URL, and to send no referrer when a protocol downgrade occurs.\n \n ``strict-origin-when-cross-origin``\n Instructs the browser to send the full URL when the link is same-origin and\n@@ -470,8 +472,8 @@ Session middleware\n \n .. class:: SessionMiddleware\n \n-Enables session support. See the :doc:`session documentation\n-`.\n+ Enables session support. See the :doc:`session documentation\n+ `.\n \n Site middleware\n ---------------\n@@ -481,8 +483,8 @@ Site middleware\n \n .. class:: CurrentSiteMiddleware\n \n-Adds the ``site`` attribute representing the current site to every incoming\n-``HttpRequest`` object. See the :ref:`sites documentation `.\n+ Adds the ``site`` attribute representing the current site to every incoming\n+ ``HttpRequest`` object. See the :ref:`sites documentation `.\n \n Authentication middleware\n -------------------------\n@@ -492,9 +494,9 @@ Authentication middleware\n \n .. class:: AuthenticationMiddleware\n \n-Adds the ``user`` attribute, representing the currently-logged-in user, to\n-every incoming ``HttpRequest`` object. See :ref:`Authentication in web requests\n-`.\n+ Adds the ``user`` attribute, representing the currently-logged-in user, to\n+ every incoming ``HttpRequest`` object. See :ref:`Authentication in web\n+ requests `.\n \n .. class:: LoginRequiredMiddleware\n \n@@ -573,14 +575,14 @@ Customize the login URL or field name for authenticated views with the\n \n .. class:: RemoteUserMiddleware\n \n-Middleware for utilizing web server provided authentication. See\n-:doc:`/howto/auth-remote-user` for usage details.\n+ Middleware for utilizing web server provided authentication. See\n+ :doc:`/howto/auth-remote-user` for usage details.\n \n .. class:: PersistentRemoteUserMiddleware\n \n-Middleware for utilizing web server provided authentication when enabled only\n-on the login page. See :ref:`persistent-remote-user-middleware-howto` for usage\n-details.\n+ Middleware for utilizing web server provided authentication when enabled\n+ only on the login page. See :ref:`persistent-remote-user-middleware-howto`\n+ for usage details.\n \n CSRF protection middleware\n --------------------------\n@@ -589,12 +591,12 @@ CSRF protection middleware\n \n .. class:: CsrfViewMiddleware\n \n-Adds protection against [NAME_REDACTED] Forgeries by [NAME_REDACTED]\n-fields to POST forms and checking requests for the correct value. See the\n-:doc:`[NAME_REDACTED] Forgery protection documentation `.\n+ Adds protection against [NAME_REDACTED] Forgeries by [NAME_REDACTED]\n+ fields to POST forms and checking requests for the correct value. See the\n+ :doc:`[NAME_REDACTED] Forgery protection documentation `.\n \n-You can add [NAME_REDACTED] Forgery protection to individual views using the\n-:func:`~django.views.decorators.csrf.csrf_protect` decorator.\n+ You can add [NAME_REDACTED] Forgery protection to individual views\n+ using the :func:`~django.views.decorators.csrf.csrf_protect` decorator.\n \n ``X-Frame-Options`` middleware\n ------------------------------\n@@ -603,8 +605,8 @@ You can add [NAME_REDACTED] Forgery protection to individual views using the\n \n .. class:: XFrameOptionsMiddleware\n \n-Simple :doc:`clickjacking protection via the X-Frame-Options header\n-`.\n+ Simple :doc:`clickjacking protection via the X-Frame-Options header\n+ `.\n \n [NAME_REDACTED] middleware\n ----------------------------------" } ], "reviews": [ { "id": 3600163083, "user": "user_3a67c55598c5", "state": "COMMENTED", "body": "Thanks 👍", "submitted_at": "2025-12-19T21:22:24+00:00" }, { "id": 3605067032, "user": "user_3a67c55598c5", "state": "APPROVED", "body": "Thanks ⭐", "submitted_at": "2025-12-22T17:45:36+00:00" } ], "review_comments": [ { "id": 2636330872, "user": "user_3a67c55598c5", "body": "This change isn't necessary.", "path": "docs/ref/checks.txt", "line": null, "side": "RIGHT", "created_at": "2025-12-19T21:18:39+00:00" } ], "meta": { "languages": [ "txt" ], "touches_tests": false, "review_state_summary": { "COMMENTED": 1, "APPROVED": 1 }, "meaningful_comment_count": 1, "has_approval": true, "has_changes_requested": false, "total_review_comments": 1 } } { "_id": "94d25fd46f28ac83", "_schema_version": "1.0", "_cleaned_at": "2026-02-12T07:46:52.132616+00:00", "repo": "django/django", "repo_url": "https://github.com/django/django", "license_name": "BSD 3-Clause \"New\" or \"Revised\" License", "license_spdx": "BSD-3-Clause", "pr_number": 20269, "title": "Fixed #36744 -- Improved scrypt password hasher doc.", "body": "#### Trac ticket number\n\n\nticket-36744\n\n#### Branch description\n\nImproved scrypt password hasher documentation.\n\n- Corrected work_factor description and its requirements.\n- Added block_size description.\n- Changed parallelism description to mention computations, rather than threads (currently it's not multithreaded.)\n- For all of the above, added standard scrypt terminology (N, r, p).\n- Mentioned that in multithreaded implementations, parallelism also influences the memory requirements.\n\n#### Checklist\n- [x] This PR targets the `main` branch. \n- [x] The commit message is written in past tense, mentions the ticket number, and ends with a period.\n- [x] I have checked the \"Has patch\" ticket flag in the Trac system.\n- [ ] I have added or updated relevant tests.\n- [ ] I have added or updated relevant docs, including release notes if applicable.\n- [ ] I have attached screenshots in both light and dark modes for any UI changes.", "author": "user_ea26dc5a17c2", "created_at": "2025-11-19T00:36:02+00:00", "merged_at": "2025-12-04T08:23:01+00:00", "base_branch": "main", "head_branch": "ticket_36744", "additions": 10, "deletions": 4, "changed_files": 1, "files": [ { "filename": "docs/topics/auth/passwords.txt", "status": "modified", "additions": 10, "deletions": 4, "changes": 14, "patch": "@@ -285,15 +285,18 @@ follows:\n \n scrypt_ has the following attributes that can be customized:\n \n-#. ``work_factor`` controls the number of iterations within the hash.\n-#. ``block_size``\n-#. ``parallelism`` controls how many threads will run in parallel.\n+#. ``work_factor`` controls the number of iterations within the hash and the\n+ size of memory for computation (*N*). It must be a power of 2.\n+#. ``block_size`` controls the internal block size (*r*), tuning the algorithm\n+ to memory latency.\n+#. ``parallelism`` controls how many independent computations may run in\n+ parallel (*p*).\n #. ``maxmem`` limits the maximum size of memory that can be used during the\n computation of the hash. Defaults to ``0``, which means the default\n limitation from the OpenSSL library.\n \n We've chosen reasonable defaults, but you may wish to tune it up or down,\n-depending on your security needs and available processing power.\n+depending on your security needs and available processing power and memory.\n \n .. admonition:: Estimating memory usage\n \n@@ -304,6 +307,9 @@ depending on your security needs and available processing power.\n so you may need to tweak ``maxmem`` when changing the ``work_factor`` or\n ``block_size`` values.\n \n+ If the underlying implementation of scrypt_ is fully multithreaded, the\n+ memory requirement is multiplied by the ``parallelism`` value.\n+\n .. _password-upgrades:\n \n Password upgrading" } ], "reviews": [ { "id": 3534512293, "user": "user_5501cd6d3dc8", "state": "COMMENTED", "body": null, "submitted_at": "2025-12-03T11:04:56+00:00" }, { "id": 3534524150, "user": "user_5501cd6d3dc8", "state": "COMMENTED", "body": null, "submitted_at": "2025-12-03T11:07:33+00:00" }, { "id": 3534528824, "user": "user_5501cd6d3dc8", "state": "COMMENTED", "body": null, "submitted_at": "2025-12-03T11:08:24+00:00" }, { "id": 3534559629, "user": "user_ea26dc5a17c2", "state": "COMMENTED", "body": null, "submitted_at": "2025-12-03T11:15:22+00:00" }, { "id": 3534579508, "user": "user_ea26dc5a17c2", "state": "COMMENTED", "body": null, "submitted_at": "2025-12-03T11:19:47+00:00" }, { "id": 3534582027, "user": "user_5501cd6d3dc8", "state": "COMMENTED", "body": null, "submitted_at": "2025-12-03T11:20:31+00:00" }, { "id": 3534641678, "user": "user_ea26dc5a17c2", "state": "COMMENTED", "body": null, "submitted_at": "2025-12-03T11:37:21+00:00" }, { "id": 3534661467, "user": "user_ea26dc5a17c2", "state": "COMMENTED", "body": null, "submitted_at": "2025-12-03T11:43:13+00:00" }, { "id": 3534814519, "user": "user_5501cd6d3dc8", "state": "COMMENTED", "body": null, "submitted_at": "2025-12-03T12:27:22+00:00" }, { "id": 3534922460, "user": "user_ea26dc5a17c2", "state": "COMMENTED", "body": null, "submitted_at": "2025-12-03T12:58:10+00:00" }, { "id": 3534957196, "user": "user_5501cd6d3dc8", "state": "COMMENTED", "body": null, "submitted_at": "2025-12-03T13:07:19+00:00" }, { "id": 3534996941, "user": "user_ea26dc5a17c2", "state": "COMMENTED", "body": null, "submitted_at": "2025-12-03T13:16:55+00:00" }, { "id": 3538599173, "user": "user_5501cd6d3dc8", "state": "APPROVED", "body": "[USER_REDACTED] Thanks :+1: Welcome aboard :boat:", "submitted_at": "2025-12-04T07:54:03+00:00" } ], "review_comments": [ { "id": 2584668774, "user": "user_5501cd6d3dc8", "body": "I think that mentioning `N`, `r`, and `p` is confusing, not helpful, especially that we use ``work_factor``, ``block_size``, and ``parallelism`` in the following explanation. I'd remove them.", "path": "docs/topics/auth/passwords.txt", "line": 293, "side": "RIGHT", "created_at": "2025-12-03T11:04:56+00:00" }, { "id": 2584677243, "user": "user_5501cd6d3dc8", "body": "TBH _\"controls the computational and memory cost parameter\"_ doesn't say anything. How it controls them? with the new wording we have more questions and less answers. I would revert this change.\n```suggestion\n#. ``work_factor`` controls the number of iterations within the hash. It\n must be a power of 2.\n```", "path": "docs/topics/auth/passwords.txt", "line": null, "side": "RIGHT", "created_at": "2025-12-03T11:07:33+00:00" }, { "id": 2584680288, "user": "user_5501cd6d3dc8", "body": "```suggestion\n```", "path": "docs/topics/auth/passwords.txt", "line": 312, "side": "RIGHT", "created_at": "2025-12-03T11:08:23+00:00" }, { "id": 2584703448, "user": "user_ea26dc5a17c2", "body": "The thing is N, r, p are the standard parameters for scrypt. If you see or request any recommendation for proper scrypt parameters, you always get them in terms of N, r, p. For example, search for \"scrypt recommended parameters\". Django uses non-standard names for them, so at least documentation should make it easy to map what everyone else uses to Django's world.", "path": "docs/topics/auth/passwords.txt", "line": 293, "side": "RIGHT", "created_at": "2025-12-03T11:15:22+00:00" }, { "id": 2584718018, "user": "user_ea26dc5a17c2", "body": "It's not easy to explain how it controls them without explaining the whole algorithm. Perhaps, it should say \"sets the computational and memory cost\"? The original \"number of iterations within the hash\" is only partially true, since it doesn't explain the memory size which is also set by N.", "path": "docs/topics/auth/passwords.txt", "line": null, "side": "RIGHT", "created_at": "2025-12-03T11:19:47+00:00" }, { "id": 2584720382, "user": "user_5501cd6d3dc8", "body": "These are single letter variables :smile: there is nothing \"standard\" in them, IMO. For example, for me, `n` and `p` are rather parameters for binomial distribution :upside_down_face:", "path": "docs/topics/auth/passwords.txt", "line": 293, "side": "RIGHT", "created_at": "2025-12-03T11:20:31+00:00" }, { "id": 2584771251, "user": "user_ea26dc5a17c2", "body": "They are standard in the sense that they are defined in the [scrypt paper](https://www.tarsnap.com/scrypt/scrypt.pdf) and [RFC 7912](https://www.rfc-editor.org/rfc/rfc7914#section-2), and the fact that they are used everywhere to define scrypt parameters, e.g. [OWASP recommendations](https://cheatsheetseries.owasp.org/cheatsheets/Password_Storage_Cheat_Sheet.html#scrypt).", "path": "docs/topics/auth/passwords.txt", "line": 293, "side": "RIGHT", "created_at": "2025-12-03T11:37:21+00:00" }, { "id": 2584788203, "user": "user_ea26dc5a17c2", "body": "> For example, for me, n and p are rather parameters for binomial distribution 🙃\n\nExactly -- wouldn't you be confused if you'd have to use parameters for binomial distribution, but instead of `n` and `p`, they would be called 𝖅 and ☋, and documentation won't point out what they really mean?", "path": "docs/topics/auth/passwords.txt", "line": 293, "side": "RIGHT", "created_at": "2025-12-03T11:43:13+00:00" }, { "id": 2584920176, "user": "user_5501cd6d3dc8", "body": "OK, you convinced me.", "path": "docs/topics/auth/passwords.txt", "line": 293, "side": "RIGHT", "created_at": "2025-12-03T12:27:22+00:00" }, { "id": 2585015382, "user": "user_ea26dc5a17c2", "body": "I've changed it to:\n\n\"controls the number of iterations within the hash and the size of memory for computation (*N*); must be a power of 2.\"\n\ni.e. added \"and the size of memory for computation\" to the previous description.", "path": "docs/topics/auth/passwords.txt", "line": null, "side": "RIGHT", "created_at": "2025-12-03T12:58:10+00:00" }, { "id": 2585045142, "user": "user_5501cd6d3dc8", "body": "We normally try to avoid semicolons in docs. Can you rewrite it a bit?", "path": "docs/topics/auth/passwords.txt", "line": null, "side": "RIGHT", "created_at": "2025-12-03T13:07:19+00:00" }, { "id": 2585078445, "user": "user_ea26dc5a17c2", "body": "Sure, changed to \". It must be a power of 2\". Sounds fine?", "path": "docs/topics/auth/passwords.txt", "line": null, "side": "RIGHT", "created_at": "2025-12-03T13:16:55+00:00" } ], "meta": { "languages": [ "txt" ], "touches_tests": false, "review_state_summary": { "COMMENTED": 12, "APPROVED": 1 }, "meaningful_comment_count": 12, "has_approval": true, "has_changes_requested": false, "total_review_comments": 12 } } { "_id": "0bba5b319278cecb", "_schema_version": "1.0", "_cleaned_at": "2026-02-12T07:46:52.132616+00:00", "repo": "django/django", "repo_url": "https://github.com/django/django", "license_name": "BSD 3-Clause \"New\" or \"Revised\" License", "license_spdx": "BSD-3-Clause", "pr_number": 20267, "title": "Fixed #26609 -- Extended fields.E004 system check for unordered iterables.", "body": "Co-Authored-By: [NAME_REDACTED] <[EMAIL_REDACTED]\n\nticket-26609", "author": "user_5501cd6d3dc8", "created_at": "2025-11-18T17:04:34+00:00", "merged_at": "2025-11-19T07:22:44+00:00", "base_branch": "main", "head_branch": "issue-26609", "additions": 44, "deletions": 8, "changed_files": 3, "files": [ { "filename": "django/db/models/fields/__init__.py", "status": "modified", "additions": 5, "deletions": 3, "changes": 8, "patch": "@@ -316,11 +316,13 @@ def _check_choices(self):\n if not self.choices:\n return []\n \n- if not isinstance(self.choices, Iterable) or isinstance(self.choices, str):\n+ if not isinstance(self.choices, Iterable) or isinstance(\n+ self.choices, (str, set, frozenset)\n+ ):\n return [\n checks.Error(\n- \"'choices' must be a mapping (e.g. a dictionary) or an iterable \"\n- \"(e.g. a list or tuple).\",\n+ \"'choices' must be a mapping (e.g. a dictionary) or an \"\n+ \"ordered iterable (e.g. a list or tuple, but not a set).\",\n obj=self,\n id=\"fields.E004\",\n )" }, { "filename": "docs/ref/checks.txt", "status": "modified", "additions": 1, "deletions": 1, "changes": 2, "patch": "@@ -167,7 +167,7 @@ Model fields\n * **fields.E003**: ``pk`` is a reserved word that cannot be used as a field\n name.\n * **fields.E004**: ``choices`` must be a mapping (e.g. a dictionary) or an\n- iterable (e.g. a list or tuple).\n+ ordered iterable (e.g. a list or tuple, but not a set).\n * **fields.E005**: ``choices`` must be a mapping of actual values to human\n readable names or an iterable containing ``(actual value, human readable\n name)`` tuples." }, { "filename": "tests/invalid_models_tests/test_ordinary_fields.py", "status": "modified", "additions": 38, "deletions": 4, "changes": 42, "patch": "@@ -199,8 +199,8 @@ class Model(models.Model):\n field.check(),\n [\n Error(\n- \"'choices' must be a mapping (e.g. a dictionary) or an iterable \"\n- \"(e.g. a list or tuple).\",\n+ \"'choices' must be a mapping (e.g. a dictionary) or an \"\n+ \"ordered iterable (e.g. a list or tuple, but not a set).\",\n obj=field,\n id=\"fields.E004\",\n ),\n@@ -906,8 +906,42 @@ class Model(models.Model):\n field.check(),\n [\n Error(\n- \"'choices' must be a mapping (e.g. a dictionary) or an iterable \"\n- \"(e.g. a list or tuple).\",\n+ \"'choices' must be a mapping (e.g. a dictionary) or an \"\n+ \"ordered iterable (e.g. a list or tuple, but not a set).\",\n+ obj=field,\n+ id=\"fields.E004\",\n+ ),\n+ ],\n+ )\n+\n+ def test_unordered_choices_set(self):\n+ class Model(models.Model):\n+ field = models.IntegerField(choices={1, 2, 3})\n+\n+ field = Model._meta.get_field(\"field\")\n+ self.assertEqual(\n+ field.check(),\n+ [\n+ Error(\n+ \"'choices' must be a mapping (e.g. a dictionary) or an \"\n+ \"ordered iterable (e.g. a list or tuple, but not a set).\",\n+ obj=field,\n+ id=\"fields.E004\",\n+ ),\n+ ],\n+ )\n+\n+ def test_unordered_choices_frozenset(self):\n+ class Model(models.Model):\n+ field = models.IntegerField(choices=frozenset({1, 2, 3}))\n+\n+ field = Model._meta.get_field(\"field\")\n+ self.assertEqual(\n+ field.check(),\n+ [\n+ Error(\n+ \"'choices' must be a mapping (e.g. a dictionary) or an \"\n+ \"ordered iterable (e.g. a list or tuple, but not a set).\",\n obj=field,\n id=\"fields.E004\",\n )," } ], "reviews": [ { "id": 3478946670, "user": "user_cdda8932ec17", "state": "APPROVED", "body": null, "submitted_at": "2025-11-18T17:23:45+00:00" }, { "id": 3478966228, "user": "user_5501cd6d3dc8", "state": "COMMENTED", "body": null, "submitted_at": "2025-11-18T17:28:33+00:00" }, { "id": 3483361752, "user": "user_194c2ef4033e", "state": "COMMENTED", "body": null, "submitted_at": "2025-11-19T15:23:36+00:00" } ], "review_comments": [ { "id": 2539076876, "user": "user_cdda8932ec17", "body": "Ahh I always assumed `frozenset` was subclass of `set` but it makes sense that it isn't (e.g. it doesn't have an `add` method).", "path": "django/db/models/fields/__init__.py", "line": 320, "side": "RIGHT", "created_at": "2025-11-18T17:23:32+00:00" }, { "id": 2539091817, "user": "user_5501cd6d3dc8", "body": "> Ahh I always assumed `frozenset` was subclass of `set` ....\n\n![giphy](https://github.com/[USER_REDACTED]nts/assets/f0d9f81c-df72-45f9-bbb7-422b18a4f081)\n\n:sweat_smile:", "path": "django/db/models/fields/__init__.py", "line": 320, "side": "RIGHT", "created_at": "2025-11-18T17:28:32+00:00" }, { "id": 2542498015, "user": "user_194c2ef4033e", "body": "But they are both subclasses of [`collections.abc.Set`](https://docs.python.org/3/library/collections.abc.html#collections.abc.Set).", "path": "django/db/models/fields/__init__.py", "line": 320, "side": "RIGHT", "created_at": "2025-11-19T15:23:35+00:00" } ], "meta": { "languages": [ "py", "txt" ], "touches_tests": true, "review_state_summary": { "APPROVED": 1, "COMMENTED": 2 }, "meaningful_comment_count": 3, "has_approval": true, "has_changes_requested": false, "total_review_comments": 3 } } { "_id": "373dfb6e2ef0255a", "_schema_version": "1.0", "_cleaned_at": "2026-02-12T07:46:52.132616+00:00", "repo": "django/django", "repo_url": "https://github.com/django/django", "license_name": "BSD 3-Clause \"New\" or \"Revised\" License", "license_spdx": "BSD-3-Clause", "pr_number": 20184, "title": "Fixed #36708 -- Initialized formset to None in ChangeList.__init__().", "body": "#### Trac ticket number\n\nticket-36708\n\n#### Branch description\n\nThis PR adds a default formset = None attribute to the ChangeList class.\nThe Ticket describes how when Django instantiates ChangeList through ModelAdmin, it assigns formset dynamically.\nHowever, when developers create their own custom ChangeList instances, formset may not be set, leading to an AttributeError in templates.\nDefining formset as a class-level field (attribute) makes sure that behaviour is a bit more consistent \n\n#### Checklist\n- [x] This PR targets the `main` branch. \n- [x] The commit message is written in past tense, mentions the ticket number, and ends with a period.\n- [ ] I have checked the \"Has patch\" ticket flag in the Trac system.\n- [ ] I have added or updated relevant tests.\n- [ ] I have added or updated relevant docs, including release notes if applicable.\n- [ ] I have attached screenshots in both light and dark modes for any UI changes.", "author": "user_39de4ee5824c", "created_at": "2025-11-17T14:19:39+00:00", "merged_at": "2026-01-12T18:34:15+00:00", "base_branch": "main", "head_branch": "ticket-36708", "additions": 7, "deletions": 19, "changed_files": 3, "files": [ { "filename": "django/contrib/admin/options.py", "status": "modified", "additions": 6, "deletions": 13, "changes": 19, "patch": "@@ -2050,11 +2050,6 @@ def changelist_view(self, request, extra_context=None):\n # me back\" button on the action confirmation page.\n return HttpResponseRedirect(request.get_full_path())\n \n- # If we're allowing changelist editing, we need to construct a formset\n- # for the changelist given all the fields to be edited. Then we'll\n- # use the formset to validate/process POSTed data.\n- formset = cl.formset = None\n-\n # Handle POSTed bulk-edit data.\n if request.method == \"POST\" and cl.list_editable and \"_save\" in request.POST:\n if not self.has_change_permission(request):\n@@ -2063,13 +2058,11 @@ def changelist_view(self, request, extra_context=None):\n modified_objects = self._get_list_editable_queryset(\n request, FormSet.get_default_prefix()\n )\n- formset = cl.formset = FormSet(\n- request.POST, request.FILES, queryset=modified_objects\n- )\n- if formset.is_valid():\n+ cl.formset = FormSet(request.POST, request.FILES, queryset=modified_objects)\n+ if cl.formset.is_valid():\n changecount = 0\n with transaction.atomic(using=router.db_for_write(self.model)):\n- for form in formset.forms:\n+ for form in cl.formset.forms:\n if form.has_changed():\n obj = self.save_form(request, form, change=True)\n self.save_model(request, obj, form, change=True)\n@@ -2095,11 +2088,11 @@ def changelist_view(self, request, extra_context=None):\n # Handle GET -- construct a formset for display.\n elif cl.list_editable and self.has_change_permission(request):\n FormSet = self.get_changelist_formset(request)\n- formset = cl.formset = FormSet(queryset=cl.result_list)\n+ cl.formset = FormSet(queryset=cl.result_list)\n \n # Build the list of media to be used by [NAME_REDACTED]\n- if formset:\n- media = self.media + formset.media\n+ if cl.formset:\n+ media = self.media + cl.formset.media\n else:\n media = self.media" }, { "filename": "django/contrib/admin/views/main.py", "status": "modified", "additions": 1, "deletions": 1, "changes": 2, "patch": "@@ -101,7 +101,7 @@ def __init__(\n self.preserved_filters = model_admin.get_preserved_filters(request)\n self.sortable_by = sortable_by\n self.search_help_text = search_help_text\n-\n+ self.formset = None\n # Get search parameters from the query string.\n _search_form = self.search_form_class(request.GET)\n if not _search_form.is_valid():" }, { "filename": "tests/admin_changelist/tests.py", "status": "modified", "additions": 0, "deletions": 5, "changes": 5, "patch": "@@ -240,7 +240,6 @@ def test_result_list_empty_changelist_value(self):\n request.user = self.superuser\n m = ChildAdmin(Child, custom_site)\n cl = m.get_changelist_instance(request)\n- cl.formset = None\n template = Template(\n \"{% load admin_list %}{% spaceless %}{% result_list cl %}{% endspaceless %}\"\n )\n@@ -285,7 +284,6 @@ def test_result_list_set_empty_value_display_on_admin_site(self):\n admin.site.empty_value_display = \"???\"\n m = ChildAdmin(Child, admin.site)\n cl = m.get_changelist_instance(request)\n- cl.formset = None\n template = Template(\n \"{% load admin_list %}{% spaceless %}{% result_list cl %}{% endspaceless %}\"\n )\n@@ -310,7 +308,6 @@ def test_result_list_set_empty_value_display_in_model_admin(self):\n request.user = self.superuser\n m = EmptyValueChildAdmin(Child, admin.site)\n cl = m.get_changelist_instance(request)\n- cl.formset = None\n template = Template(\n \"{% load admin_list %}{% spaceless %}{% result_list cl %}{% endspaceless %}\"\n )\n@@ -341,7 +338,6 @@ def test_result_list_html(self):\n request.user = self.superuser\n m = ChildAdmin(Child, custom_site)\n cl = m.get_changelist_instance(request)\n- cl.formset = None\n template = Template(\n \"{% load admin_list %}{% spaceless %}{% result_list cl %}{% endspaceless %}\"\n )\n@@ -370,7 +366,6 @@ def test_action_checkbox_for_model_with_dunder_html(self):\n request = self._mocked_authenticated_request(\"/grandchild/\", self.superuser)\n m = GrandChildAdmin(GrandChild, custom_site)\n cl = m.get_changelist_instance(request)\n- cl.formset = None\n template = Template(\n \"{% load admin_list %}{% spaceless %}{% result_list cl %}{% endspaceless %}\"\n )" } ], "reviews": [ { "id": 3475182523, "user": "user_45c2e5489720", "state": "COMMENTED", "body": "Thank you for working on this [USER_REDACTED] ⭐️\n\nAs Ben mentioned in the ticket, by [NAME_REDACTED] `formset` attribute on `ChangeList`, it seems we’ll need to update the parts in the `changelist_view` method where `formset` was being assigned dynamically.\n\n```diff --git a/django/contrib/admin/options.py b/django/contrib/admin/options.py\nindex 6c202c8e61..62856cebfb 100644\n--- a/django/contrib/admin/options.py\n+++ b/django/contrib/admin/options.py\n@@ -2050,11 +2050,6 @@ class ModelAdmin(BaseModelAdmin):\n # me back\" button on the action confirmation page.\n return HttpResponseRedirect(request.get_full_path())\n \n- # If we're allowing changelist editing, we need to construct a formset\n- # for the changelist given all the fields to be edited. Then we'll\n- # use the formset to validate/process POSTed data.\n- formset = cl.formset = None\n-\n # Handle POSTed bulk-edit data.\n if request.method == \"POST\" and cl.list_editable and \"_save\" in request.POST:\n if not self.has_change_permission(request):\n@@ -2063,13 +2058,13 @@ class ModelAdmin(BaseModelAdmin):\n modified_objects = self._get_list_editable_queryset(\n request, FormSet.get_default_prefix()\n )\n- formset = cl.formset = FormSet(\n+ cl.formset = FormSet(\n request.POST, request.FILES, queryset=modified_objects\n )\n- if formset.is_valid():\n+ if cl.formset.is_valid():\n changecount = 0\n with transaction.atomic(using=router.db_for_write(self.model)):\n- for form in formset.forms:\n+ for form in cl.formset.forms:\n if form.has_changed():\n obj = self.save_form(request, form, change=True)\n self.save_model(request, obj, form, change=True)\n@@ -2095,11 +2090,11 @@ class ModelAdmin(BaseModelAdmin):\n # Handle GET -- construct a formset for display.\n elif cl.list_editable and self.has_change_permission(request):\n FormSet = self.get_changelist_formset(request)\n- formset = cl.formset = FormSet(queryset=cl.result_list)\n+ cl.formset = FormSet(queryset=cl.result_list)\n \n # Build the list of media to be used by [NAME_REDACTED]\n- if formset:\n- media = self.media + formset.media\n+ if cl.formset:\n+ media = self.media + cl.formset.media\n else:\n media = self.media\n\n```", "submitted_at": "2025-11-18T01:54:06+00:00" }, { "id": 3480092455, "user": "user_45c2e5489720", "state": "COMMENTED", "body": "Thank you for update [USER_REDACTED] ⭐️\n\nI left small comments :)", "submitted_at": "2025-11-18T23:40:58+00:00" }, { "id": 3480706872, "user": "user_39de4ee5824c", "state": "COMMENTED", "body": null, "submitted_at": "2025-11-19T03:55:36+00:00" }, { "id": 3480707797, "user": "user_39de4ee5824c", "state": "COMMENTED", "body": null, "submitted_at": "2025-11-19T03:56:20+00:00" }, { "id": 3584790863, "user": "user_3a67c55598c5", "state": "COMMENTED", "body": "Thanks 👍", "submitted_at": "2025-12-16T20:23:37+00:00" }, { "id": 3584833111, "user": "user_3a67c55598c5", "state": "COMMENTED", "body": null, "submitted_at": "2025-12-16T20:31:27+00:00" }, { "id": 3647671081, "user": "user_39de4ee5824c", "state": "COMMENTED", "body": null, "submitted_at": "2026-01-11T13:04:28+00:00" }, { "id": 3651549049, "user": "user_3a67c55598c5", "state": "APPROVED", "body": "Thanks [USER_REDACTED] ⭐", "submitted_at": "2026-01-12T16:03:50+00:00" } ], "review_comments": [ { "id": 2539961196, "user": "user_45c2e5489720", "body": "It looks like the lint issue is occurring in this part.\nRemoving that line should resolve it!", "path": "django/contrib/admin/options.py", "line": null, "side": "RIGHT", "created_at": "2025-11-18T23:39:05+00:00" }, { "id": 2539962753, "user": "user_45c2e5489720", "body": "It seems that `noqa` won’t be necessary 🤔", "path": "django/contrib/admin/views/main.py", "line": null, "side": "RIGHT", "created_at": "2025-11-18T23:40:08+00:00" }, { "id": 2540434159, "user": "user_39de4ee5824c", "body": "oh boy! that was a stupid oversight sorry 😅\ni mistook options for main ig", "path": "django/contrib/admin/options.py", "line": null, "side": "RIGHT", "created_at": "2025-11-19T03:55:35+00:00" }, { "id": 2540435119, "user": "user_39de4ee5824c", "body": "yep, i thought that snakeoil fix (#type:ignore) would work here \ni have removed this ✅\nit passes the test now", "path": "django/contrib/admin/views/main.py", "line": null, "side": "RIGHT", "created_at": "2025-11-19T03:56:20+00:00" }, { "id": 2624610523, "user": "user_3a67c55598c5", "body": "I could see value in leaving `cl.formset = None` here to just avoid any pollution from prior calls. [USER_REDACTED] wdyt?", "path": "django/contrib/admin/options.py", "line": 2056, "side": "LEFT", "created_at": "2025-12-16T20:17:09+00:00" }, { "id": 2624625329, "user": "user_3a67c55598c5", "body": "Can we make this an instance attribute instead?", "path": "django/contrib/admin/views/main.py", "line": null, "side": "RIGHT", "created_at": "2025-12-16T20:23:22+00:00" }, { "id": 2624645464, "user": "user_3a67c55598c5", "body": "Never mind -- `cl` is an instance. `cl` meaning \"changelist\", who knew? 😄", "path": "django/contrib/admin/options.py", "line": 2056, "side": "LEFT", "created_at": "2025-12-16T20:31:27+00:00" }, { "id": 2679525740, "user": "user_39de4ee5824c", "body": "I have made this change ✅", "path": "django/contrib/admin/views/main.py", "line": null, "side": "RIGHT", "created_at": "2026-01-11T13:04:27+00:00" } ], "meta": { "languages": [ "py" ], "touches_tests": true, "review_state_summary": { "COMMENTED": 7, "APPROVED": 1 }, "meaningful_comment_count": 8, "has_approval": true, "has_changes_requested": false, "total_review_comments": 8 } } { "_id": "e9763fdde63ee6f8", "_schema_version": "1.0", "_cleaned_at": "2026-02-12T07:46:52.132616+00:00", "repo": "django/django", "repo_url": "https://github.com/django/django", "license_name": "BSD 3-Clause \"New\" or \"Revised\" License", "license_spdx": "BSD-3-Clause", "pr_number": 20183, "title": "Fixed #36737 -- Escaped C1 control characters in escapejs.", "body": "#### Trac ticket number\n\n\nticket-[#36737](https://code.djangoproject.com/ticket/36737)\n\n#### Branch description\nIn Ticket 36737 there was a discussion on C0 control characters of ASCII value and it was a relatively an easy issue to solve I felt that I could tackle the given problem. which was simply solved by [NAME_REDACTED] loop \nI would like to apologize to any problem or error I have caused. \n\n#### Checklist\n- [ ] This PR targets the `main` branch. \n- [ ] The commit message is written in past tense, mentions the ticket number, and ends with a period.\n- [ ] I have checked the \"Has patch\" ticket flag in the Trac system.\n- [ ] I have added or updated relevant tests.\n- [ ] I have added or updated relevant docs, including release notes if applicable.\n- [ ] I have attached screenshots in both light and dark modes for any UI changes.", "author": "user_0e181fb278e9", "created_at": "2025-11-17T10:33:53+00:00", "merged_at": "2025-11-20T14:35:59+00:00", "base_branch": "main", "head_branch": "ticket_36737", "additions": 9, "deletions": 2, "changed_files": 2, "files": [ { "filename": "django/utils/html.py", "status": "modified", "additions": 6, "deletions": 2, "changes": 8, "patch": "@@ -7,6 +7,7 @@\n from collections import deque\n from collections.abc import Mapping\n from html.parser import HTMLParser\n+from itertools import chain\n from urllib.parse import parse_qsl, quote, unquote, urlencode, urlsplit, urlunsplit\n \n from django.conf import settings\n@@ -76,8 +77,11 @@ def escape(text):\n ord(\"\\u2029\"): \"\\\\u2029\",\n }\n \n-# Escape every ASCII character with a value less than 32.\n-_js_escapes.update((ord(\"%c\" % z), \"\\\\u%04X\" % z) for z in range(32))\n+# Escape every ASCII character with a value less than 32 (C0), 127(C0),\n+# or 128-159(C1).\n+_js_escapes.update(\n+ (ord(\"%c\" % z), \"\\\\u%04X\" % z) for z in chain(range(32), range(0x7F, 0xA0))\n+)\n \n \n [USER_REDACTED]_lazy(SafeString)" }, { "filename": "tests/utils_tests/test_html.py", "status": "modified", "additions": 3, "deletions": 0, "changes": 3, "patch": "@@ -244,6 +244,9 @@ def test_escapejs(self):\n \"paragraph separator:\\\\u2029and line separator:\\\\u2028\",\n ),\n (\"`\", \"\\\\u0060\"),\n+ (\"\\u007f\", \"\\\\u007F\"),\n+ (\"\\u0080\", \"\\\\u0080\"),\n+ (\"\\u009f\", \"\\\\u009F\"),\n )\n for value, output in items:\n with self.subTest(value=value, output=output):" } ], "reviews": [ { "id": 3472893895, "user": "user_3a67c55598c5", "state": "COMMENTED", "body": "Thanks for the PR 👍 \n\nPlease add two tests to `TestUtilsHtml.test_escapejs` cases:\n- U+007F (DELETE)\n- another C1 control character", "submitted_at": "2025-11-17T14:11:32+00:00" }, { "id": 3472964367, "user": "user_0e181fb278e9", "state": "COMMENTED", "body": null, "submitted_at": "2025-11-17T14:22:12+00:00" }, { "id": 3472970914, "user": "user_0e181fb278e9", "state": "COMMENTED", "body": null, "submitted_at": "2025-11-17T14:23:40+00:00" }, { "id": 3473284876, "user": "user_3a67c55598c5", "state": "COMMENTED", "body": null, "submitted_at": "2025-11-17T15:24:39+00:00" }, { "id": 3473366780, "user": "user_0e181fb278e9", "state": "COMMENTED", "body": null, "submitted_at": "2025-11-17T15:43:10+00:00" }, { "id": 3473913959, "user": "user_3a67c55598c5", "state": "CHANGES_REQUESTED", "body": "I don't see the requested tests anywhere.", "submitted_at": "2025-11-17T17:51:05+00:00" }, { "id": 3476558832, "user": "user_34c3f4acb8a8", "state": "COMMENTED", "body": null, "submitted_at": "2025-11-18T09:44:23+00:00" }, { "id": 3476571915, "user": "user_c332d334e171", "state": "COMMENTED", "body": null, "submitted_at": "2025-11-18T09:46:35+00:00" }, { "id": 3479068994, "user": "user_3a67c55598c5", "state": "COMMENTED", "body": null, "submitted_at": "2025-11-18T17:58:16+00:00" }, { "id": 3480883844, "user": "user_0e181fb278e9", "state": "COMMENTED", "body": null, "submitted_at": "2025-11-19T05:30:24+00:00" }, { "id": 3483039095, "user": "user_3a67c55598c5", "state": "COMMENTED", "body": null, "submitted_at": "2025-11-19T14:28:39+00:00" }, { "id": 3483351125, "user": "user_3a67c55598c5", "state": "COMMENTED", "body": "Thanks, almost there! 👍", "submitted_at": "2025-11-19T15:21:40+00:00" }, { "id": 3484321851, "user": "user_3a67c55598c5", "state": "COMMENTED", "body": null, "submitted_at": "2025-11-19T19:08:22+00:00" }, { "id": 3484324880, "user": "user_3a67c55598c5", "state": "COMMENTED", "body": null, "submitted_at": "2025-11-19T19:09:17+00:00" }, { "id": 3484326746, "user": "user_3a67c55598c5", "state": "APPROVED", "body": "Thanks for the PR!", "submitted_at": "2025-11-19T19:09:51+00:00" } ], "review_comments": [ { "id": 2534220595, "user": "user_3a67c55598c5", "body": "Please revert.", "path": ".gitignore", "line": null, "side": "RIGHT", "created_at": "2025-11-17T14:08:53+00:00" }, { "id": 2534274840, "user": "user_0e181fb278e9", "body": "So sorry I was a bit confused and went down a rabbit hole I will revert and work thanks", "path": ".gitignore", "line": null, "side": "RIGHT", "created_at": "2025-11-17T14:22:12+00:00" }, { "id": 2534280420, "user": "user_0e181fb278e9", "body": "I made a major mistake went down some rabbit hole which led to this \nthanks", "path": ".gitignore", "line": null, "side": "RIGHT", "created_at": "2025-11-17T14:23:40+00:00" }, { "id": 2534520115, "user": "user_3a67c55598c5", "body": "Please keep the period at the end.", "path": "django/utils/html.py", "line": null, "side": "RIGHT", "created_at": "2025-11-17T15:24:39+00:00" }, { "id": 2534586641, "user": "user_0e181fb278e9", "body": "[NAME_REDACTED]", "path": "django/utils/html.py", "line": null, "side": "RIGHT", "created_at": "2025-11-17T15:43:10+00:00" }, { "id": 2537169158, "user": "user_34c3f4acb8a8", "body": "Nit: Suggest keeping the comment as prose\n```suggestion\n# Escape every ASCII character with a value less than 32 (C0) and 127-159(C1).\n```", "path": "django/utils/html.py", "line": null, "side": "RIGHT", "created_at": "2025-11-18T09:44:23+00:00" }, { "id": 2537179876, "user": "user_c332d334e171", "body": "```suggestion\n (\"\\u009F\", \"\\u009F\"),\n```", "path": "tests/utils_tests/test_html.py", "line": null, "side": "RIGHT", "created_at": "2025-11-18T09:46:22+00:00" }, { "id": 2537180633, "user": "user_c332d334e171", "body": "```suggestion\n (\"\\u007F\", \"\\u007F\"),\n```", "path": "tests/utils_tests/test_html.py", "line": null, "side": "RIGHT", "created_at": "2025-11-18T09:46:29+00:00" }, { "id": 2539170208, "user": "user_3a67c55598c5", "body": "These should all be escaped\n```suggestion\n (\"\\u007f\", \"\\\\u007F\"),\n (\"\\u0080\", \"\\\\u0080\"),\n (\"\\u009f\", \"\\\\u009F\"),\n```", "path": "tests/utils_tests/test_html.py", "line": null, "side": "RIGHT", "created_at": "2025-11-18T17:55:21+00:00" }, { "id": 2540597502, "user": "user_0e181fb278e9", "body": "Major doubt I have checked my code works but during the implementation of test cases throws an ` Asserstion error` that similar test executed separately runs perfectly \nI have been stuck with this for a while", "path": "tests/utils_tests/test_html.py", "line": null, "side": "RIGHT", "created_at": "2025-11-19T05:30:23+00:00" }, { "id": 2542253819, "user": "user_3a67c55598c5", "body": "The test passes for me when I correct the expected results.", "path": "tests/utils_tests/test_html.py", "line": null, "side": "RIGHT", "created_at": "2025-11-19T14:28:39+00:00" }, { "id": 2542489782, "user": "user_3a67c55598c5", "body": "You can just do this once if you `from itertools import chain`. Also please don't include 127 with the C1 range, it's C0.\n```suggestion\n# Escape every ASCII character with a value less than 32 (C0), 127 (C0),\n# or 128-159(C1).\n_js_escapes.update(\n (ord(\"%c\" % z), \"\\\\u%04X\" % z) for z in chain(range(32), range(0x7F, 0xA0))\n)\n```", "path": "django/utils/html.py", "line": null, "side": "RIGHT", "created_at": "2025-11-19T15:21:21+00:00" }, { "id": 2543233340, "user": "user_3a67c55598c5", "body": "```suggestion\n# Escape every ASCII character with a value less than 32 (C0), 127(C0)\n```", "path": "django/utils/html.py", "line": null, "side": "RIGHT", "created_at": "2025-11-19T19:08:22+00:00" }, { "id": 2543235742, "user": "user_3a67c55598c5", "body": "```suggestion\n# Escape every ASCII character with a value less than 32 (C0), 127(C0),\n# or 128-159(C1).\n```", "path": "django/utils/html.py", "line": null, "side": "RIGHT", "created_at": "2025-11-19T19:09:17+00:00" } ], "meta": { "languages": [ "py" ], "touches_tests": true, "review_state_summary": { "COMMENTED": 13, "CHANGES_REQUESTED": 1, "APPROVED": 1 }, "meaningful_comment_count": 14, "has_approval": true, "has_changes_requested": true, "total_review_comments": 14 } } { "_id": "795f29c11aedefac", "_schema_version": "1.0", "_cleaned_at": "2026-02-12T07:46:52.132616+00:00", "repo": "django/django", "repo_url": "https://github.com/django/django", "license_name": "BSD 3-Clause \"New\" or \"Revised\" License", "license_spdx": "BSD-3-Clause", "pr_number": 20182, "title": "Fixed #36280 -- Replaced exception checks with assertRaisesMessage()", "body": "#### Trac ticket number\n\n\nticket-36280\n\n#### Branch description\n1. **Replaced `cm.exception.messages` assertions with `assertRaisesMessage()` where applicable.**\n Skipped refactoring in cases where:\n\n * `cm.exception.message_dict` is used (multiple lines unsupported by `assertRaisesMessage()`).\n * `.error_list[0].code` or other exception metadata is tested.\n\n2. **Replaced `try/except` blocks catching `AssertionError` with `assertRaisesMessage()`.**\n to maintain the code format.\n\n#### Checklist\n- [x] This PR targets the `main` branch. \n- [x] The commit message is written in past tense, mentions the ticket number, and ends with a period.\n- [ ] I have checked the \"Has patch\" ticket flag in the Trac system.\n- [x] I have added or updated relevant tests.\n- [x] I have added or updated relevant docs, including release notes if applicable.\n- [x] I have attached screenshots in both light and dark modes for any UI changes.", "author": "user_f5eee7dbaa84", "created_at": "2025-11-16T19:23:52+00:00", "merged_at": "2025-12-03T14:18:10+00:00", "base_branch": "main", "head_branch": "fix36280", "additions": 100, "deletions": 152, "changed_files": 4, "files": [ { "filename": "tests/auth_tests/test_validators.py", "status": "modified", "additions": 10, "deletions": 14, "changes": 24, "patch": "@@ -202,24 +202,24 @@ def test_validate(self):\n self.assertEqual(cm.exception.messages, [expected_error % \"username\"])\n self.assertEqual(cm.exception.error_list[0].code, \"password_too_similar\")\n \n- with self.assertRaises(ValidationError) as cm:\n+ msg = expected_error % \"email address\"\n+ with self.assertRaisesMessage(ValidationError, msg):\n UserAttributeSimilarityValidator().validate(\"example.com\", user=user)\n- self.assertEqual(cm.exception.messages, [expected_error % \"email address\"])\n \n- with self.assertRaises(ValidationError) as cm:\n+ msg = expected_error % \"first name\"\n+ with self.assertRaisesMessage(ValidationError, msg):\n UserAttributeSimilarityValidator(\n user_attributes=[\"first_name\"],\n max_similarity=0.3,\n ).validate(\"testclient\", user=user)\n- self.assertEqual(cm.exception.messages, [expected_error % \"first name\"])\n # max_similarity=1 doesn't allow passwords that are identical to the\n # attribute's value.\n- with self.assertRaises(ValidationError) as cm:\n+ msg = expected_error % \"first name\"\n+ with self.assertRaisesMessage(ValidationError, msg):\n UserAttributeSimilarityValidator(\n user_attributes=[\"first_name\"],\n max_similarity=1,\n ).validate(user.first_name, user=user)\n- self.assertEqual(cm.exception.messages, [expected_error % \"first name\"])\n # Very low max_similarity is rejected.\n msg = \"max_similarity must be at least 0.1\"\n with self.assertRaisesMessage(ValueError, msg):\n@@ -240,11 +240,9 @@ class TestUser(models.Model):\n def username(self):\n return \"foobar\"\n \n- with self.assertRaises(ValidationError) as cm:\n+ msg = \"The password is too similar to the username.\"\n+ with self.assertRaisesMessage(ValidationError, msg):\n UserAttributeSimilarityValidator().validate(\"foobar\", user=TestUser())\n- self.assertEqual(\n- cm.exception.messages, [\"The password is too similar to the username.\"]\n- )\n \n def test_help_text(self):\n self.assertEqual(\n@@ -294,18 +292,16 @@ def test_validate(self):\n expected_error = \"This password is too common.\"\n self.assertIsNone(CommonPasswordValidator().validate(\"a-safe-password\"))\n \n- with self.assertRaises(ValidationError) as cm:\n+ with self.assertRaisesMessage(ValidationError, expected_error):\n CommonPasswordValidator().validate(\"godzilla\")\n- self.assertEqual(cm.exception.messages, [expected_error])\n \n def test_common_hexed_codes(self):\n expected_error = \"This password is too common.\"\n common_hexed_passwords = [\"asdfjkl:\", \"ठ:\"]\n for password in common_hexed_passwords:\n with self.subTest(password=password):\n- with self.assertRaises(ValidationError) as cm:\n+ with self.assertRaisesMessage(ValidationError, expected_error):\n CommonPasswordValidator().validate(password)\n- self.assertEqual(cm.exception.messages, [expected_error])\n \n def test_validate_custom_list(self):\n path = os.path.join(" }, { "filename": "tests/postgres_tests/test_array.py", "status": "modified", "additions": 14, "deletions": 32, "changes": 46, "patch": "@@ -1087,12 +1087,9 @@ def test_blank_true(self):\n def test_with_size(self):\n field = ArrayField(models.IntegerField(), size=3)\n field.clean([1, 2, 3], None)\n- with self.assertRaises(exceptions.ValidationError) as cm:\n+ msg = \"List contains 4 items, it should contain no more than 3.\"\n+ with self.assertRaisesMessage(exceptions.ValidationError, msg):\n field.clean([1, 2, 3, 4], None)\n- self.assertEqual(\n- cm.exception.messages[0],\n- \"List contains 4 items, it should contain no more than 3.\",\n- )\n \n def test_with_size_singular(self):\n field = ArrayField(models.IntegerField(), size=1)\n@@ -1156,21 +1153,15 @@ def test_valid(self):\n \n def test_to_python_fail(self):\n field = SimpleArrayField(forms.IntegerField())\n- with self.assertRaises(exceptions.ValidationError) as cm:\n+ msg = \"Item 1 in the array did not validate: Enter a whole number.\"\n+ with self.assertRaisesMessage(exceptions.ValidationError, msg):\n field.clean(\"a,b,9\")\n- self.assertEqual(\n- cm.exception.messages[0],\n- \"Item 1 in the array did not validate: Enter a whole number.\",\n- )\n \n def test_validate_fail(self):\n field = SimpleArrayField(forms.CharField(required=True))\n- with self.assertRaises(exceptions.ValidationError) as cm:\n+ msg = \"Item 3 in the array did not validate: This field is required.\"\n+ with self.assertRaisesMessage(exceptions.ValidationError, msg):\n field.clean(\"a,b,\")\n- self.assertEqual(\n- cm.exception.messages[0],\n- \"Item 3 in the array did not validate: This field is required.\",\n- )\n \n def test_validate_fail_base_field_error_params(self):\n field = SimpleArrayField(forms.CharField(max_length=2))\n@@ -1203,12 +1194,9 @@ def test_validate_fail_base_field_error_params(self):\n \n def test_validators_fail(self):\n field = SimpleArrayField(forms.RegexField(\"[a-e]{2}\"))\n- with self.assertRaises(exceptions.ValidationError) as cm:\n+ msg = \"Item 1 in the array did not validate: Enter a valid value.\"\n+ with self.assertRaisesMessage(exceptions.ValidationError, msg):\n field.clean(\"a,bc,de\")\n- self.assertEqual(\n- cm.exception.messages[0],\n- \"Item 1 in the array did not validate: Enter a valid value.\",\n- )\n \n def test_delimiter(self):\n field = SimpleArrayField(forms.CharField(), delimiter=\"|\")\n@@ -1227,21 +1215,15 @@ def test_prepare_value(self):\n \n def test_max_length(self):\n field = SimpleArrayField(forms.CharField(), max_length=2)\n- with self.assertRaises(exceptions.ValidationError) as cm:\n+ msg = \"List contains 3 items, it should contain no more than 2.\"\n+ with self.assertRaisesMessage(exceptions.ValidationError, msg):\n field.clean(\"a,b,c\")\n- self.assertEqual(\n- cm.exception.messages[0],\n- \"List contains 3 items, it should contain no more than 2.\",\n- )\n \n def test_min_length(self):\n field = SimpleArrayField(forms.CharField(), min_length=4)\n- with self.assertRaises(exceptions.ValidationError) as cm:\n+ msg = \"List contains 3 items, it should contain no fewer than 4.\"\n+ with self.assertRaisesMessage(exceptions.ValidationError, msg):\n field.clean(\"a,b,c\")\n- self.assertEqual(\n- cm.exception.messages[0],\n- \"List contains 3 items, it should contain no fewer than 4.\",\n- )\n \n def test_min_length_singular(self):\n field = SimpleArrayField(forms.IntegerField(), min_length=2)\n@@ -1252,9 +1234,9 @@ def test_min_length_singular(self):\n \n def test_required(self):\n field = SimpleArrayField(forms.CharField(), required=True)\n- with self.assertRaises(exceptions.ValidationError) as cm:\n+ msg = \"This field is required.\"\n+ with self.assertRaisesMessage(exceptions.ValidationError, msg):\n field.clean(\"\")\n- self.assertEqual(cm.exception.messages[0], \"This field is required.\")\n \n def test_model_field_formfield(self):\n model_field = ArrayField(models.CharField(max_length=27))" }, { "filename": "tests/postgres_tests/test_ranges.py", "status": "modified", "additions": 24, "deletions": 24, "changes": 48, "patch": "@@ -842,21 +842,21 @@ def test_integer_incorrect_data_type(self):\n \n def test_integer_invalid_lower(self):\n field = pg_forms.IntegerRangeField()\n- with self.assertRaises(exceptions.ValidationError) as cm:\n+ msg = \"Enter a whole number.\"\n+ with self.assertRaisesMessage(exceptions.ValidationError, msg):\n field.clean([\"a\", \"2\"])\n- self.assertEqual(cm.exception.messages[0], \"Enter a whole number.\")\n \n def test_integer_invalid_upper(self):\n field = pg_forms.IntegerRangeField()\n- with self.assertRaises(exceptions.ValidationError) as cm:\n+ msg = \"Enter a whole number.\"\n+ with self.assertRaisesMessage(exceptions.ValidationError, msg):\n field.clean([\"1\", \"b\"])\n- self.assertEqual(cm.exception.messages[0], \"Enter a whole number.\")\n \n def test_integer_required(self):\n field = pg_forms.IntegerRangeField(required=True)\n- with self.assertRaises(exceptions.ValidationError) as cm:\n+ msg = \"This field is required.\"\n+ with self.assertRaisesMessage(exceptions.ValidationError, msg):\n field.clean([\"\", \"\"])\n- self.assertEqual(cm.exception.messages[0], \"This field is required.\")\n value = field.clean([1, \"\"])\n self.assertEqual(value, NumericRange(1, None))\n \n@@ -884,21 +884,21 @@ def test_decimal_incorrect_data_type(self):\n \n def test_decimal_invalid_lower(self):\n field = pg_forms.DecimalRangeField()\n- with self.assertRaises(exceptions.ValidationError) as cm:\n+ msg = \"Enter a number.\"\n+ with self.assertRaisesMessage(exceptions.ValidationError, msg):\n field.clean([\"a\", \"3.1415926\"])\n- self.assertEqual(cm.exception.messages[0], \"Enter a number.\")\n \n def test_decimal_invalid_upper(self):\n field = pg_forms.DecimalRangeField()\n- with self.assertRaises(exceptions.ValidationError) as cm:\n+ msg = \"Enter a number.\"\n+ with self.assertRaisesMessage(exceptions.ValidationError, msg):\n field.clean([\"1.61803399\", \"b\"])\n- self.assertEqual(cm.exception.messages[0], \"Enter a number.\")\n \n def test_decimal_required(self):\n field = pg_forms.DecimalRangeField(required=True)\n- with self.assertRaises(exceptions.ValidationError) as cm:\n+ msg = \"This field is required.\"\n+ with self.assertRaisesMessage(exceptions.ValidationError, msg):\n field.clean([\"\", \"\"])\n- self.assertEqual(cm.exception.messages[0], \"This field is required.\")\n value = field.clean([\"1.61803399\", \"\"])\n self.assertEqual(value, NumericRange(Decimal(\"1.61803399\"), None))\n \n@@ -926,21 +926,21 @@ def test_date_incorrect_data_type(self):\n \n def test_date_invalid_lower(self):\n field = pg_forms.DateRangeField()\n- with self.assertRaises(exceptions.ValidationError) as cm:\n+ msg = \"Enter a valid date.\"\n+ with self.assertRaisesMessage(exceptions.ValidationError, msg):\n field.clean([\"a\", \"2013-04-09\"])\n- self.assertEqual(cm.exception.messages[0], \"Enter a valid date.\")\n \n def test_date_invalid_upper(self):\n field = pg_forms.DateRangeField()\n- with self.assertRaises(exceptions.ValidationError) as cm:\n+ msg = \"Enter a valid date.\"\n+ with self.assertRaisesMessage(exceptions.ValidationError, msg):\n field.clean([\"2013-04-09\", \"b\"])\n- self.assertEqual(cm.exception.messages[0], \"Enter a valid date.\")\n \n def test_date_required(self):\n field = pg_forms.DateRangeField(required=True)\n- with self.assertRaises(exceptions.ValidationError) as cm:\n+ msg = \"This field is required.\"\n+ with self.assertRaisesMessage(exceptions.ValidationError, msg):\n field.clean([\"\", \"\"])\n- self.assertEqual(cm.exception.messages[0], \"This field is required.\")\n value = field.clean([\"1976-04-16\", \"\"])\n self.assertEqual(value, DateRange(datetime.date(1976, 4, 16), None))\n \n@@ -986,21 +986,21 @@ def test_datetime_incorrect_data_type(self):\n \n def test_datetime_invalid_lower(self):\n field = pg_forms.DateTimeRangeField()\n- with self.assertRaises(exceptions.ValidationError) as cm:\n+ msg = \"Enter a valid date/time.\"\n+ with self.assertRaisesMessage(exceptions.ValidationError, msg):\n field.clean([\"45\", \"2013-04-09 11:45\"])\n- self.assertEqual(cm.exception.messages[0], \"Enter a valid date/time.\")\n \n def test_datetime_invalid_upper(self):\n field = pg_forms.DateTimeRangeField()\n- with self.assertRaises(exceptions.ValidationError) as cm:\n+ msg = \"Enter a valid date/time.\"\n+ with self.assertRaisesMessage(exceptions.ValidationError, msg):\n field.clean([\"2013-04-09 11:45\", \"sweet pickles\"])\n- self.assertEqual(cm.exception.messages[0], \"Enter a valid date/time.\")\n \n def test_datetime_required(self):\n field = pg_forms.DateTimeRangeField(required=True)\n- with self.assertRaises(exceptions.ValidationError) as cm:\n+ msg = \"This field is required.\"\n+ with self.assertRaisesMessage(exceptions.ValidationError, msg):\n field.clean([\"\", \"\"])\n- self.assertEqual(cm.exception.messages[0], \"This field is required.\")\n value = field.clean([\"2013-04-09 11:45\", \"\"])\n self.assertEqual(\n value, DateTimeTZRange(datetime.datetime(2013, 4, 9, 11, 45), None)" }, { "filename": "tests/test_client_regress/tests.py", "status": "modified", "additions": 52, "deletions": 82, "changes": 134, "patch": "@@ -309,15 +309,13 @@ def test_no_context(self):\n # The no template case doesn't mess with the template assertions\n self.assertTemplateNotUsed(response, \"GET Template\")\n \n- try:\n+ msg = \"No templates used to render the response\"\n+ with self.assertRaisesMessage(AssertionError, msg):\n self.assertTemplateUsed(response, \"GET Template\")\n- except AssertionError as e:\n- self.assertIn(\"No templates used to render the response\", str(e))\n \n- try:\n+ msg = \"No templates used to render the response\"\n+ with self.assertRaisesMessage(AssertionError, msg):\n self.assertTemplateUsed(response, \"GET Template\", msg_prefix=\"abc\")\n- except AssertionError as e:\n- self.assertIn(\"abc: No templates used to render the response\", str(e))\n \n msg = \"No templates used to render the response\"\n with self.assertRaisesMessage(AssertionError, msg):\n@@ -400,23 +398,19 @@ def test_redirect_page(self):\n \"\"\"\n # This page will redirect with code 301, not 302\n response = self.client.get(\"/permanent_redirect_view/\")\n- try:\n+ msg = (\n+ \"Response didn't redirect as expected: Response code was 301 \"\n+ \"(expected 302)\"\n+ )\n+ with self.assertRaisesMessage(AssertionError, msg):\n self.assertRedirects(response, \"/get_view/\")\n- except AssertionError as e:\n- self.assertIn(\n- \"Response didn't redirect as expected: Response code was 301 \"\n- \"(expected 302)\",\n- str(e),\n- )\n \n- try:\n+ msg = (\n+ \"abc: Response didn't redirect as expected: Response code was 301 \"\n+ \"(expected 302)\"\n+ )\n+ with self.assertRaisesMessage(AssertionError, msg):\n self.assertRedirects(response, \"/get_view/\", msg_prefix=\"abc\")\n- except AssertionError as e:\n- self.assertIn(\n- \"abc: Response didn't redirect as expected: Response code was 301 \"\n- \"(expected 302)\",\n- str(e),\n- )\n \n def test_followed_redirect_unexpected_initial_status_code(self):\n response = self.client.get(\"/permanent_redirect_view/\", follow=True)\n@@ -452,63 +446,49 @@ def test_lost_query(self):\n parameters.\n \"\"\"\n response = self.client.get(\"/redirect_view/\", {\"var\": \"value\"})\n- try:\n+ msg = \"Response redirected to '/get_view/?var=value', expected '/get_view/'\"\n+ with self.assertRaisesMessage(AssertionError, msg):\n self.assertRedirects(response, \"/get_view/\")\n- except AssertionError as e:\n- self.assertIn(\n- \"Response redirected to '/get_view/?var=value', expected '/get_view/'\",\n- str(e),\n- )\n \n- try:\n+ msg = (\n+ \"abc: Response redirected to '/get_view/?var=value', expected '/get_view/'\"\n+ )\n+ with self.assertRaisesMessage(AssertionError, msg):\n self.assertRedirects(response, \"/get_view/\", msg_prefix=\"abc\")\n- except AssertionError as e:\n- self.assertIn(\n- \"abc: Response redirected to '/get_view/?var=value', expected \"\n- \"'/get_view/'\",\n- str(e),\n- )\n \n def test_incorrect_target(self):\n \"An assertion is raised if the response redirects to another target\"\n response = self.client.get(\"/permanent_redirect_view/\")\n- try:\n+ msg = (\n+ \"Response didn't redirect as expected: Response code was 301 (expected 302)\"\n+ )\n+ with self.assertRaisesMessage(AssertionError, msg):\n # Should redirect to get_view\n self.assertRedirects(response, \"/some_view/\")\n- except AssertionError as e:\n- self.assertIn(\n- \"Response didn't redirect as expected: Response code was 301 \"\n- \"(expected 302)\",\n- str(e),\n- )\n \n def test_target_page(self):\n \"\"\"\n An assertion is raised if the response redirect target cannot be\n retrieved as expected.\n \"\"\"\n response = self.client.get(\"/double_redirect_view/\")\n- try:\n+ msg = (\n+ \"Couldn't retrieve redirection page '/permanent_redirect_view/': \"\n+ \"response code was 301 (expected 200)\"\n+ )\n+ with self.assertRaisesMessage(AssertionError, msg):\n # The redirect target responds with a 301 code, not 200\n self.assertRedirects(response, \"http://testserver/permanent_redirect_view/\")\n- except AssertionError as e:\n- self.assertIn(\n- \"Couldn't retrieve redirection page '/permanent_redirect_view/': \"\n- \"response code was 301 (expected 200)\",\n- str(e),\n- )\n \n- try:\n+ msg = (\n+ \"abc: Couldn't retrieve redirection page '/permanent_redirect_view/': \"\n+ \"response code was 301 (expected 200)\"\n+ )\n+ with self.assertRaisesMessage(AssertionError, msg):\n # The redirect target responds with a 301 code, not 200\n self.assertRedirects(\n response, \"http://testserver/permanent_redirect_view/\", msg_prefix=\"abc\"\n )\n- except AssertionError as e:\n- self.assertIn(\n- \"abc: Couldn't retrieve redirection page '/permanent_redirect_view/': \"\n- \"response code was 301 (expected 200)\",\n- str(e),\n- )\n \n def test_redirect_chain(self):\n \"You can follow a redirect chain of multiple redirects\"\n@@ -632,23 +612,18 @@ def test_redirect_chain_on_non_redirect_page(self):\n \"\"\"\n # This page will redirect with code 301, not 302\n response = self.client.get(\"/get_view/\", follow=True)\n- try:\n+ msg = (\n+ \"Response didn't redirect as expected: Response code was 200 (expected 302)\"\n+ )\n+ with self.assertRaisesMessage(AssertionError, msg):\n self.assertRedirects(response, \"/get_view/\")\n- except AssertionError as e:\n- self.assertIn(\n- \"Response didn't redirect as expected: Response code was 200 \"\n- \"(expected 302)\",\n- str(e),\n- )\n \n- try:\n+ msg = (\n+ \"abc: Response didn't redirect as expected: Response code was 200 \"\n+ \"(expected 302)\"\n+ )\n+ with self.assertRaisesMessage(AssertionError, msg):\n self.assertRedirects(response, \"/get_view/\", msg_prefix=\"abc\")\n- except AssertionError as e:\n- self.assertIn(\n- \"abc: Response didn't redirect as expected: Response code was 200 \"\n- \"(expected 302)\",\n- str(e),\n- )\n \n def test_redirect_on_non_redirect_page(self):\n \"\"\"\n@@ -657,23 +632,18 @@ def test_redirect_on_non_redirect_page(self):\n \"\"\"\n # This page will redirect with code 301, not 302\n response = self.client.get(\"/get_view/\")\n- try:\n+ msg = (\n+ \"Response didn't redirect as expected: Response code was 200 (expected 302)\"\n+ )\n+ with self.assertRaisesMessage(AssertionError, msg):\n self.assertRedirects(response, \"/get_view/\")\n- except AssertionError as e:\n- self.assertIn(\n- \"Response didn't redirect as expected: Response code was 200 \"\n- \"(expected 302)\",\n- str(e),\n- )\n \n- try:\n+ msg = (\n+ \"abc: Response didn't redirect as expected: Response code was 200 \"\n+ \"(expected 302)\"\n+ )\n+ with self.assertRaisesMessage(AssertionError, msg):\n self.assertRedirects(response, \"/get_view/\", msg_prefix=\"abc\")\n- except AssertionError as e:\n- self.assertIn(\n- \"abc: Response didn't redirect as expected: Response code was 200 \"\n- \"(expected 302)\",\n- str(e),\n- )\n \n def test_redirect_scheme(self):\n \"\"\"" } ], "reviews": [ { "id": 3532026119, "user": "user_3a67c55598c5", "state": "COMMENTED", "body": "Thanks for the PR. The ticket mentions `postgres_tests/test_hstore.py`, but I don't see any changes there. Please be sure you've grepped around for relevant files to edit. \nPlease also use a period in the commit message.\n\nWill be glad to take another look then 👍", "submitted_at": "2025-12-02T20:43:14+00:00" }, { "id": 3534504365, "user": "user_f5eee7dbaa84", "state": "COMMENTED", "body": null, "submitted_at": "2025-12-03T11:03:06+00:00" }, { "id": 3535249365, "user": "user_3a67c55598c5", "state": "APPROVED", "body": "Thanks for the contribution ⭐", "submitted_at": "2025-12-03T14:09:19+00:00" } ], "review_comments": [ { "id": 2582715526, "user": "user_3a67c55598c5", "body": "Try not to introduce new newlines; it bloats the diff.", "path": "tests/auth_tests/test_validators.py", "line": null, "side": "RIGHT", "created_at": "2025-12-02T20:40:21+00:00" }, { "id": 2584662143, "user": "user_f5eee7dbaa84", "body": "done , removed the newline and also added a fullstop", "path": "tests/auth_tests/test_validators.py", "line": null, "side": "RIGHT", "created_at": "2025-12-03T11:03:05+00:00" } ], "meta": { "languages": [ "py" ], "touches_tests": true, "review_state_summary": { "COMMENTED": 2, "APPROVED": 1 }, "meaningful_comment_count": 2, "has_approval": true, "has_changes_requested": false, "total_review_comments": 2 } } { "_id": "31d24b98e4972f18", "_schema_version": "1.0", "_cleaned_at": "2026-02-12T07:46:52.148241+00:00", "repo": "django/django", "repo_url": "https://github.com/django/django", "license_name": "BSD 3-Clause \"New\" or \"Revised\" License", "license_spdx": "BSD-3-Clause", "pr_number": 20101, "title": "Fixed #36735 -- Added UUID4 and UUID7 database functions", "body": "#### Trac ticket number\nticket-36735\n\n#### Branch description\nAdds the `UUID4` and `UUID7` database functions.\n\n#### Checklist\n- [x] This PR targets the `main` branch. \n- [x] The commit message is written in past tense, mentions the ticket number, and ends with a period.\n- [x] I have checked the \"Has patch\" ticket flag in the Trac system.\n- [x] I have added or updated relevant tests.\n- [x] I have added or updated relevant docs, including release notes if applicable.\n- [x] I have attached screenshots in both light and dark modes for any UI changes.", "author": "user_057de2f3b132", "created_at": "2025-11-15T19:27:35+00:00", "merged_at": "2025-12-12T16:17:08+00:00", "base_branch": "main", "head_branch": "uuid47-functions", "additions": 233, "deletions": 0, "changed_files": 14, "files": [ { "filename": "django/db/backends/base/features.py", "status": "modified", "additions": 3, "deletions": 0, "changes": 3, "patch": "@@ -426,6 +426,9 @@ class BaseDatabaseFeatures:\n # that should be skipped for this database.\n django_test_skips = {}\n \n+ supports_uuid4_function = False\n+ supports_uuid7_function = False\n+\n def __init__(self, connection):\n self.connection = connection" }, { "filename": "django/db/backends/mysql/features.py", "status": "modified", "additions": 12, "deletions": 0, "changes": 12, "patch": "@@ -232,3 +232,15 @@ def allows_group_by_selected_pks(self):\n [USER_REDACTED]_property\n def supports_any_value(self):\n return not self.connection.mysql_is_mariadb\n+\n+ [USER_REDACTED]_property\n+ def supports_uuid4_function(self):\n+ if self.connection.mysql_is_mariadb:\n+ return self.connection.mysql_version >= (11, 7)\n+ return False\n+\n+ [USER_REDACTED]_property\n+ def supports_uuid7_function(self):\n+ if self.connection.mysql_is_mariadb:\n+ return self.connection.mysql_version >= (11, 7)\n+ return False" }, { "filename": "django/db/backends/oracle/features.py", "status": "modified", "additions": 4, "deletions": 0, "changes": 4, "patch": "@@ -224,3 +224,7 @@ def bare_select_suffix(self):\n def supports_tuple_lookups(self):\n # Support is known to be missing on 23.2 but available on 23.4.\n return self.connection.oracle_version >= (23, 4)\n+\n+ [USER_REDACTED]_property\n+ def supports_uuid4_function(self):\n+ return self.connection.oracle_version >= (23, 9)" }, { "filename": "django/db/backends/postgresql/features.py", "status": "modified", "additions": 5, "deletions": 0, "changes": 5, "patch": "@@ -79,6 +79,11 @@ class DatabaseFeatures(BaseDatabaseFeatures):\n }\n test_now_utc_template = \"STATEMENT_TIMESTAMP() AT TIME ZONE 'UTC'\"\n insert_test_table_with_defaults = \"INSERT INTO {} DEFAULT VALUES\"\n+ supports_uuid4_function = True\n+\n+ [USER_REDACTED]_property\n+ def supports_uuid7_function(self):\n+ return self.is_postgresql_18\n \n [USER_REDACTED]_property\n def django_test_skips(self):" }, { "filename": "django/db/backends/sqlite3/_functions.py", "status": "modified", "additions": 16, "deletions": 0, "changes": 16, "patch": "@@ -27,6 +27,7 @@\n tan,\n )\n from re import search as re_search\n+from uuid import uuid4\n \n from django.db.backends.utils import (\n split_tzname_delta,\n@@ -35,6 +36,10 @@\n )\n from django.utils import timezone\n from django.utils.duration import duration_microseconds\n+from django.utils.version import PY314\n+\n+if PY314:\n+ from uuid import uuid7\n \n \n def register(connection):\n@@ -81,6 +86,9 @@ def register(connection):\n connection.create_aggregate(\"VAR_POP\", 1, VarPop)\n connection.create_aggregate(\"VAR_SAMP\", 1, VarSamp)\n connection.create_aggregate(\"ANY_VALUE\", 1, AnyValue)\n+ connection.create_function(\"UUIDV4\", 0, _sqlite_uuid4)\n+ if PY314:\n+ connection.create_function(\"UUIDV7\", 0, _sqlite_uuid7)\n # Some math functions are enabled by [NAME_REDACTED] 3.35+.\n sql = \"select sqlite_compileoption_used('ENABLE_MATH_FUNCTIONS')\"\n if not connection.execute(sql).fetchone()[0]:\n@@ -496,6 +504,14 @@ def _sqlite_tan(x):\n return tan(x)\n \n \n+def _sqlite_uuid4():\n+ return uuid4().hex\n+\n+\n+def _sqlite_uuid7():\n+ return uuid7().hex\n+\n+\n class ListAggregate(list):\n step = list.append" }, { "filename": "django/db/backends/sqlite3/features.py", "status": "modified", "additions": 6, "deletions": 0, "changes": 6, "patch": "@@ -5,6 +5,7 @@\n from django.db.backends.base.features import BaseDatabaseFeatures\n from django.db.utils import OperationalError\n from django.utils.functional import cached_property\n+from django.utils.version import PY314\n \n from .base import Database\n \n@@ -59,6 +60,11 @@ class DatabaseFeatures(BaseDatabaseFeatures):\n can_return_columns_from_insert = True\n can_return_rows_from_bulk_insert = True\n can_return_rows_from_update = True\n+ supports_uuid4_function = True\n+\n+ [USER_REDACTED]_property\n+ def supports_uuid7_function(self):\n+ return PY314\n \n [USER_REDACTED]_property\n def django_test_skips(self):" }, { "filename": "django/db/models/functions/__init__.py", "status": "modified", "additions": 4, "deletions": 0, "changes": 4, "patch": "@@ -78,6 +78,7 @@\n Trim,\n Upper,\n )\n+from .uuid import UUID4, UUID7\n from .window import (\n CumeDist,\n DenseRank,\n@@ -178,6 +179,9 @@\n \"Substr\",\n \"Trim\",\n \"Upper\",\n+ # uuid\n+ \"UUID4\",\n+ \"UUID7\",\n # window\n \"CumeDist\",\n \"DenseRank\"," }, { "filename": "django/db/models/functions/uuid.py", "status": "added", "additions": 68, "deletions": 0, "changes": 68, "patch": "@@ -0,0 +1,68 @@\n+from django.db import NotSupportedError\n+from django.db.models.expressions import Func\n+from django.db.models.fields import UUIDField\n+\n+\n+class UUID4(Func):\n+ function = \"UUIDV4\"\n+ arity = 0\n+ output_field = UUIDField()\n+\n+ def as_sql(self, compiler, connection, **extra_context):\n+ if connection.features.supports_uuid4_function:\n+ return super().as_sql(compiler, connection, **extra_context)\n+ raise NotSupportedError(\"UUID4 is not supported on this database backend.\")\n+\n+ def as_postgresql(self, compiler, connection, **extra_context):\n+ if connection.features.is_postgresql_18:\n+ return self.as_sql(compiler, connection, **extra_context)\n+ return self.as_sql(\n+ compiler, connection, function=\"GEN_RANDOM_UUID\", **extra_context\n+ )\n+\n+ def as_mysql(self, compiler, connection, **extra_context):\n+ if not connection.features.supports_uuid4_function:\n+ if connection.mysql_is_mariadb:\n+ raise NotSupportedError(\"UUID4 requires MariaDB version 11.7 or later.\")\n+ raise NotSupportedError(\"UUID4 is not supported on MySQL.\")\n+ return self.as_sql(compiler, connection, function=\"UUID_V4\", **extra_context)\n+\n+ def as_oracle(self, compiler, connection, **extra_context):\n+ if not connection.features.supports_uuid4_function:\n+ raise NotSupportedError(\n+ \"UUID4 requires Oracle version 23ai/26ai (23.9) or later.\"\n+ )\n+ return self.as_sql(compiler, connection, function=\"UUID\", **extra_context)\n+\n+\n+class UUID7(Func):\n+ function = \"UUIDV7\"\n+ arity = 0\n+ output_field = UUIDField()\n+\n+ def as_sql(self, compiler, connection, **extra_context):\n+ if connection.features.supports_uuid7_function:\n+ return super().as_sql(compiler, connection, **extra_context)\n+ raise NotSupportedError(\"UUID7 is not supported on this database backend.\")\n+\n+ def as_postgresql(self, compiler, connection, **extra_context):\n+ if connection.features.supports_uuid7_function:\n+ return self.as_sql(compiler, connection, **extra_context)\n+ raise NotSupportedError(\"UUID7 requires PostgreSQL version 18 or later.\")\n+\n+ # PY314: When dropping support for 3.14, remove the entire method.\n+ def as_sqlite(self, compiler, connection, **extra_context):\n+ if connection.features.supports_uuid7_function:\n+ return self.as_sql(compiler, connection, **extra_context)\n+ raise NotSupportedError(\n+ \"UUID7 on SQLite requires Python version 3.14 or later.\"\n+ )\n+\n+ def as_mysql(self, compiler, connection, **extra_context):\n+ if connection.features.supports_uuid7_function:\n+ return self.as_sql(\n+ compiler, connection, function=\"UUID_V7\", **extra_context\n+ )\n+ if connection.mysql_is_mariadb:\n+ raise NotSupportedError(\"UUID7 requires MariaDB version 11.7 or later.\")\n+ raise NotSupportedError(\"UUID7 is not supported on MySQL.\")" }, { "filename": "docs/ref/contrib/postgres/functions.txt", "status": "modified", "additions": 5, "deletions": 0, "changes": 5, "patch": "@@ -21,6 +21,11 @@ Usage example:\n >>> from django.contrib.postgres.functions import RandomUUID\n >>> Article.objects.update(uuid=RandomUUID())\n \n+.. admonition:: Use :class:`django.db.models.functions.UUID4` instead.\n+\n+ :class:`django.db.models.functions.UUID4` is a cross-database version of\n+ this function. ``RandomUUID`` may be deprecated in the future.\n+\n ``TransactionNow``\n ==================" }, { "filename": "docs/ref/models/database-functions.txt", "status": "modified", "additions": 33, "deletions": 0, "changes": 33, "patch": "@@ -1878,6 +1878,39 @@ Usage example:\n \n .. _window-functions:\n \n+UUID functions\n+==============\n+\n+``UUID4``\n+---------\n+\n+.. versionadded:: 6.1\n+\n+.. class:: UUID4()\n+\n+Generates a :rfc:`version 4 UUID <9562#section-5.4>`, which is random and is\n+generated using a cryptographically secure method.\n+\n+.. admonition:: Availability\n+\n+ Available on PostgreSQL, SQLite, MariaDB version 11.7 or later, and Oracle\n+ 23ai/26ai (23.9) or later.\n+\n+``UUID7``\n+---------\n+\n+.. versionadded:: 6.1\n+\n+.. class:: UUID7()\n+\n+Generates a :rfc:`version 7 UUID <9562#section-5.7>`, which starts with a\n+time-based component.\n+\n+.. admonition:: Availability\n+\n+ Available on PostgreSQL version 18 or later, MariaDB version 11.7 or later,\n+ and SQLite on Python version 3.14 or later.\n+\n Window functions\n ================" }, { "filename": "docs/releases/6.1.txt", "status": "modified", "additions": 3, "deletions": 0, "changes": 3, "patch": "@@ -263,6 +263,9 @@ Models\n :ref:`negative array indexing ` on Oracle\n 21c+.\n \n+* The new :class:`~django.db.models.functions.UUID4` and\n+ :class:`~django.db.models.functions.UUID7` database functions were added.\n+\n Pagination\n ~~~~~~~~~~" }, { "filename": "tests/db_functions/migrations/0002_create_test_models.py", "status": "modified", "additions": 6, "deletions": 0, "changes": 6, "patch": "@@ -88,4 +88,10 @@ class Migration(migrations.Migration):\n (\"f2\", models.FloatField(null=True, blank=True)),\n ],\n ),\n+ migrations.CreateModel(\n+ name=\"UUIDModel\",\n+ fields=[\n+ (\"uuid\", models.UUIDField(null=True)),\n+ ],\n+ ),\n ]" }, { "filename": "tests/db_functions/models.py", "status": "modified", "additions": 4, "deletions": 0, "changes": 4, "patch": "@@ -55,3 +55,7 @@ class IntegerModel(models.Model):\n class FloatModel(models.Model):\n f1 = models.FloatField(null=True, blank=True)\n f2 = models.FloatField(null=True, blank=True)\n+\n+\n+class UUIDModel(models.Model):\n+ uuid = models.UUIDField(null=True)" }, { "filename": "tests/db_functions/test_uuid.py", "status": "added", "additions": 64, "deletions": 0, "changes": 64, "patch": "@@ -0,0 +1,64 @@\n+import uuid\n+\n+from django.db import NotSupportedError, connection\n+from django.db.models.functions import UUID4, UUID7\n+from django.test import TestCase\n+from django.test.testcases import skipIfDBFeature, skipUnlessDBFeature\n+\n+from .models import UUIDModel\n+\n+\n+class TestUUID(TestCase):\n+ [USER_REDACTED](\"supports_uuid4_function\")\n+ def test_uuid4(self):\n+ m1 = UUIDModel.objects.create()\n+ m2 = UUIDModel.objects.create()\n+ UUIDModel.objects.update(uuid=UUID4())\n+ m1.refresh_from_db()\n+ m2.refresh_from_db()\n+ self.assertIsInstance(m1.uuid, uuid.UUID)\n+ self.assertEqual(m1.uuid.version, 4)\n+ self.assertNotEqual(m1.uuid, m2.uuid)\n+\n+ [USER_REDACTED](\"supports_uuid7_function\")\n+ def test_uuid7(self):\n+ m1 = UUIDModel.objects.create()\n+ m2 = UUIDModel.objects.create()\n+ UUIDModel.objects.update(uuid=UUID7())\n+ m1.refresh_from_db()\n+ m2.refresh_from_db()\n+ self.assertIsInstance(m1.uuid, uuid.UUID)\n+ self.assertEqual(m1.uuid.version, 7)\n+ self.assertNotEqual(m1.uuid, m2.uuid)\n+\n+ [USER_REDACTED](\"supports_uuid4_function\")\n+ def test_uuid4_unsupported(self):\n+ if connection.vendor == \"mysql\":\n+ if connection.mysql_is_mariadb:\n+ msg = \"UUID4 requires MariaDB version 11.7 or later.\"\n+ else:\n+ msg = \"UUID4 is not supported on MySQL.\"\n+ elif connection.vendor == \"oracle\":\n+ msg = \"UUID4 requires Oracle version 23ai/26ai (23.9) or later.\"\n+ else:\n+ msg = \"UUID4 is not supported on this database backend.\"\n+\n+ with self.assertRaisesMessage(NotSupportedError, msg):\n+ UUIDModel.objects.update(uuid=UUID4())\n+\n+ [USER_REDACTED](\"supports_uuid7_function\")\n+ def test_uuid7_unsupported(self):\n+ if connection.vendor == \"mysql\":\n+ if connection.mysql_is_mariadb:\n+ msg = \"UUID7 requires MariaDB version 11.7 or later.\"\n+ else:\n+ msg = \"UUID7 is not supported on MySQL.\"\n+ elif connection.vendor == \"postgresql\":\n+ msg = \"UUID7 requires PostgreSQL version 18 or later.\"\n+ elif connection.vendor == \"sqlite\":\n+ msg = \"UUID7 on SQLite requires Python version 3.14 or later.\"\n+ else:\n+ msg = \"UUID7 is not supported on this database backend.\"\n+\n+ with self.assertRaisesMessage(NotSupportedError, msg):\n+ UUIDModel.objects.update(uuid=UUID7())" } ], "reviews": [ { "id": 3483926111, "user": "user_34c3f4acb8a8", "state": "APPROVED", "body": null, "submitted_at": "2025-11-19T17:22:26+00:00" }, { "id": 3483935882, "user": "user_057de2f3b132", "state": "COMMENTED", "body": null, "submitted_at": "2025-11-19T17:23:46+00:00" }, { "id": 3484629969, "user": "user_8fc305198eb3", "state": "COMMENTED", "body": "Nice, moving fast!", "submitted_at": "2025-11-19T20:32:53+00:00" }, { "id": 3484648946, "user": "user_8fc305198eb3", "state": "COMMENTED", "body": null, "submitted_at": "2025-11-19T20:35:39+00:00" }, { "id": 3485167693, "user": "user_c332d334e171", "state": "COMMENTED", "body": null, "submitted_at": "2025-11-20T00:03:49+00:00" }, { "id": 3488109634, "user": "user_606ba1f2b93c", "state": "COMMENTED", "body": null, "submitted_at": "2025-11-20T14:17:03+00:00" }, { "id": 3488142967, "user": "user_606ba1f2b93c", "state": "COMMENTED", "body": null, "submitted_at": "2025-11-20T14:23:50+00:00" }, { "id": 3489611736, "user": "user_057de2f3b132", "state": "COMMENTED", "body": null, "submitted_at": "2025-11-20T19:35:34+00:00" }, { "id": 3498083863, "user": "user_8fc305198eb3", "state": "COMMENTED", "body": null, "submitted_at": "2025-11-23T23:21:38+00:00" }, { "id": 3498084339, "user": "user_8fc305198eb3", "state": "COMMENTED", "body": null, "submitted_at": "2025-11-23T23:22:45+00:00" }, { "id": 3520387519, "user": "user_7f4cd02cae13", "state": "APPROVED", "body": null, "submitted_at": "2025-11-29T02:26:01+00:00" }, { "id": 3520604756, "user": "user_c332d334e171", "state": "COMMENTED", "body": null, "submitted_at": "2025-11-29T09:00:32+00:00" }, { "id": 3521298701, "user": "user_5501cd6d3dc8", "state": "COMMENTED", "body": null, "submitted_at": "2025-11-30T13:52:18+00:00" }, { "id": 3561006707, "user": "user_c332d334e171", "state": "COMMENTED", "body": null, "submitted_at": "2025-12-10T10:59:15+00:00" }, { "id": 3561996304, "user": "user_5501cd6d3dc8", "state": "COMMENTED", "body": null, "submitted_at": "2025-12-10T11:05:54+00:00" }, { "id": 3562013103, "user": "user_c332d334e171", "state": "COMMENTED", "body": null, "submitted_at": "2025-12-10T11:10:34+00:00" }, { "id": 3562024569, "user": "user_c332d334e171", "state": "COMMENTED", "body": null, "submitted_at": "2025-12-10T11:13:35+00:00" }, { "id": 3562053097, "user": "user_5501cd6d3dc8", "state": "COMMENTED", "body": null, "submitted_at": "2025-12-10T11:21:27+00:00" }, { "id": 3562386297, "user": "user_057de2f3b132", "state": "COMMENTED", "body": null, "submitted_at": "2025-12-10T12:47:06+00:00" }, { "id": 3562404637, "user": "user_5501cd6d3dc8", "state": "COMMENTED", "body": null, "submitted_at": "2025-12-10T12:51:57+00:00" }, { "id": 3564465991, "user": "user_5501cd6d3dc8", "state": "COMMENTED", "body": null, "submitted_at": "2025-12-10T21:01:48+00:00" }, { "id": 3564469127, "user": "user_5501cd6d3dc8", "state": "COMMENTED", "body": null, "submitted_at": "2025-12-10T21:02:58+00:00" }, { "id": 3564473177, "user": "user_5501cd6d3dc8", "state": "COMMENTED", "body": null, "submitted_at": "2025-12-10T21:04:17+00:00" }, { "id": 3564007871, "user": "user_3a67c55598c5", "state": "COMMENTED", "body": "Looking really good, thanks all for reviews!\n\nMain interest at this point for me is finalizing the deprecation warnings.", "submitted_at": "2025-12-10T21:07:20+00:00" }, { "id": 3564502948, "user": "user_3a67c55598c5", "state": "COMMENTED", "body": null, "submitted_at": "2025-12-10T21:12:57+00:00" }, { "id": 3564511978, "user": "user_3a67c55598c5", "state": "COMMENTED", "body": null, "submitted_at": "2025-12-10T21:16:04+00:00" }, { "id": 3564533773, "user": "user_057de2f3b132", "state": "COMMENTED", "body": null, "submitted_at": "2025-12-10T21:22:47+00:00" }, { "id": 3564580120, "user": "user_3a67c55598c5", "state": "COMMENTED", "body": null, "submitted_at": "2025-12-10T21:34:23+00:00" }, { "id": 3564648782, "user": "user_057de2f3b132", "state": "COMMENTED", "body": null, "submitted_at": "2025-12-10T21:54:38+00:00" }, { "id": 3564661136, "user": "user_057de2f3b132", "state": "COMMENTED", "body": null, "submitted_at": "2025-12-10T21:57:06+00:00" }, { "id": 3564664009, "user": "user_057de2f3b132", "state": "COMMENTED", "body": null, "submitted_at": "2025-12-10T21:57:46+00:00" }, { "id": 3564665542, "user": "user_057de2f3b132", "state": "COMMENTED", "body": null, "submitted_at": "2025-12-10T21:58:11+00:00" }, { "id": 3564669788, "user": "user_057de2f3b132", "state": "COMMENTED", "body": null, "submitted_at": "2025-12-10T21:59:03+00:00" }, { "id": 3564674937, "user": "user_057de2f3b132", "state": "COMMENTED", "body": null, "submitted_at": "2025-12-10T22:00:00+00:00" }, { "id": 3564694401, "user": "user_3a67c55598c5", "state": "COMMENTED", "body": null, "submitted_at": "2025-12-10T22:04:28+00:00" }, { "id": 3564762984, "user": "user_057de2f3b132", "state": "COMMENTED", "body": null, "submitted_at": "2025-12-10T22:30:05+00:00" }, { "id": 3564765363, "user": "user_3a67c55598c5", "state": "APPROVED", "body": "Lovely, thank you! I'll wait till end of week to merge in case any other reviewers had pending comments.", "submitted_at": "2025-12-10T22:31:09+00:00" }, { "id": 3566289976, "user": "user_c332d334e171", "state": "APPROVED", "body": "Great works. LGTM", "submitted_at": "2025-12-11T08:29:30+00:00" }, { "id": 3566341063, "user": "user_606ba1f2b93c", "state": "APPROVED", "body": "Great work! thank you 🏆", "submitted_at": "2025-12-11T08:44:28+00:00" }, { "id": 3567335646, "user": "user_3a67c55598c5", "state": "COMMENTED", "body": null, "submitted_at": "2025-12-11T13:00:44+00:00" } ], "review_comments": [ { "id": 2542930482, "user": "user_34c3f4acb8a8", "body": "Nit: Should there be assertions for the type and version of `m2.uuid`?", "path": "tests/db_functions/test_uuid.py", "line": 20, "side": "RIGHT", "created_at": "2025-11-19T17:21:16+00:00" }, { "id": 2542938281, "user": "user_057de2f3b132", "body": "We could do, but I don't think there's a big benefit either way.", "path": "tests/db_functions/test_uuid.py", "line": 20, "side": "RIGHT", "created_at": "2025-11-19T17:23:46+00:00" }, { "id": 2543474426, "user": "user_8fc305198eb3", "body": "Do `from uuid import uuid4, uuid7` to avoid the attribute lookup in the functions - micro optimisation but since these functions can be called many times in a query I think it makes sense. uuid7 will need guarding with PY314.", "path": "django/db/backends/sqlite3/_functions.py", "line": null, "side": "RIGHT", "created_at": "2025-11-19T20:31:40+00:00" }, { "id": 2543491072, "user": "user_8fc305198eb3", "body": "I think it would be better to describe it as \"Generates a version 7 UUID, which starts with a time-based component.\", or similar. There maybe be other \"time-based UUIDs\" in the future. Likewise above.\n\nMaybe there's a UUID spec we can link to as well.", "path": "docs/ref/models/database-functions.txt", "line": null, "side": "RIGHT", "created_at": "2025-11-19T20:35:15+00:00" }, { "id": 2543920454, "user": "user_c332d334e171", "body": "Good point, Adam. UUIDv7 isn’t the only time-based UUID. UUIDv1 and UUIDv6 are also time-based formats (v1 uses a timestamp + MAC/clock sequence, v6 is the reordered variant). v7 is simply the Unix-timestamp version of the same family.\n\nThe UUID spec lists all three time-based versions here:\nhttps://www.rfc-editor.org/rfc/rfc9562.html\n\nSo something like “Generates a version 7 UUID, which begins with a time-based component” or “Generates a version 7 UUID starting with a timestamp-based prefix.” is clearer and avoids mixing it with v1/v6.", "path": "docs/ref/models/database-functions.txt", "line": null, "side": "RIGHT", "created_at": "2025-11-20T00:03:49+00:00" }, { "id": 2546238662, "user": "user_606ba1f2b93c", "body": "Since `RandomUUID()` may have been used in migrations as a `db_default`, doesn't it have to remain for use in historical migrations?", "path": "django/contrib/postgres/functions.py", "line": null, "side": "RIGHT", "created_at": "2025-11-20T14:17:03+00:00" }, { "id": 2546262213, "user": "user_606ba1f2b93c", "body": "Regardless of the above, I'd also add \"RandomUUID is deprecated\" to the deprecation message, and a `skip_file_prefixes=django_file_prefixes()` to the `warn`, so a user is pointed to where they need to change.", "path": "django/contrib/postgres/functions.py", "line": null, "side": "RIGHT", "created_at": "2025-11-20T14:23:50+00:00" }, { "id": 2547432896, "user": "user_057de2f3b132", "body": "Yeah, I'm not entirely happy with this approach.\n\nFor `Field` subclasses, we can move the deprecation to the checks framework with `system_check_deprecated_details` (and later `system_check_removed_details`), but these aren't set up for expressions and I think it would be out of scope for this PR to add something like that.", "path": "django/contrib/postgres/functions.py", "line": null, "side": "RIGHT", "created_at": "2025-11-20T19:35:34+00:00" }, { "id": 2554405257, "user": "user_8fc305198eb3", "body": "Maybe we can just say \"Generates a UUID, version 7.\" with a link to the spec? The reference docs here aren't really intended to be the place to learn about the nuances between the different options.", "path": "docs/ref/models/database-functions.txt", "line": null, "side": "RIGHT", "created_at": "2025-11-23T23:21:37+00:00" }, { "id": 2554405884, "user": "user_8fc305198eb3", "body": "If this is merged, django-upgrade can gain a fixer for `RandomUUID` -> `UUID4`, which would affect migrations too. That would help users of django-upgrade, at least.", "path": "django/contrib/postgres/functions.py", "line": null, "side": "RIGHT", "created_at": "2025-11-23T23:22:45+00:00" }, { "id": 2572907198, "user": "user_c332d334e171", "body": "I like the Adam's proposal.\nWhat others think?\nHow do you think we want to solve this RandomUUID question here?", "path": "django/contrib/postgres/functions.py", "line": null, "side": "RIGHT", "created_at": "2025-11-29T09:00:32+00:00" }, { "id": 2573669121, "user": "user_5501cd6d3dc8", "body": "```suggestion\n return self.connection.oracle_version >= (23, 9)\n```", "path": "django/db/backends/oracle/features.py", "line": null, "side": "RIGHT", "created_at": "2025-11-30T13:52:17+00:00" }, { "id": 2606165338, "user": "user_c332d334e171", "body": "```suggestion\n raise NotSupportedError(\"UUID4 requires Oracle version 26ai or later.\")\n```", "path": "django/db/models/functions/uuid.py", "line": null, "side": "RIGHT", "created_at": "2025-12-10T10:51:20+00:00" }, { "id": 2606167199, "user": "user_c332d334e171", "body": "```suggestion\n 23.9 (26ai) or later.\n```", "path": "docs/ref/models/database-functions.txt", "line": null, "side": "RIGHT", "created_at": "2025-12-10T10:51:42+00:00" }, { "id": 2606191096, "user": "user_c332d334e171", "body": "I know that based on the docs using `UUID` is OK, but what if we explicitly use the version number `UUID(4)`?\n\n> UUID can optionally take as input a version_specifier of NUMBER type. UUID(0) and UUID(4) are equivalent to UUID() in that in both cases a version 4 variant 1 UUID is returned.\n> Versions other than 4 and 0 return an error.\n\nSo, if in the future the `UUID` will change or be deprecated (like `GEN_RANDOM_UUID` in PG) we don't have to change nothing here.", "path": "django/db/models/functions/uuid.py", "line": 35, "side": "RIGHT", "created_at": "2025-12-10T10:58:48+00:00" }, { "id": 2606212734, "user": "user_5501cd6d3dc8", "body": "26ai is not a precise error message. `UUID` was added in `23.9` so between `23ai` (`23.4`) and 26ai (`23.26`).", "path": "django/db/models/functions/uuid.py", "line": null, "side": "RIGHT", "created_at": "2025-12-10T11:05:54+00:00" }, { "id": 2606226940, "user": "user_c332d334e171", "body": "I was trying to update the error message based on this comment of yours:\nhttps://github.com/[USER_REDACTED]ngo/django/pull/20101#issuecomment-3592316394\n\n> It seems that UUID is not available in Oracle 23ai, maybe only in 26ai (23.9)\n\nfrom which I understand that the sentence:\n\n> \"UUID4 requires Oracle version 23ai or later.\"\n\nis not correct.\n\nI don't know exactly how the Oracle version number works, so please update it :-)", "path": "django/db/models/functions/uuid.py", "line": null, "side": "RIGHT", "created_at": "2025-12-10T11:10:34+00:00" }, { "id": 2606236361, "user": "user_c332d334e171", "body": "> ... `UUID` was added in `23.9` ...\n\nMaybe this error message is more precise?\n\n> \"UUID4 requires Oracle version 23.9 or later.\"", "path": "django/db/models/functions/uuid.py", "line": null, "side": "RIGHT", "created_at": "2025-12-10T11:13:35+00:00" }, { "id": 2606259798, "user": "user_5501cd6d3dc8", "body": "> I don't know exactly how the Oracle version number works, so please update it :-)\n\nno one knows :upside_down_face:", "path": "django/db/models/functions/uuid.py", "line": null, "side": "RIGHT", "created_at": "2025-12-10T11:21:27+00:00" }, { "id": 2606533826, "user": "user_057de2f3b132", "body": "I don't think this brings us any benefit.", "path": "django/db/models/functions/uuid.py", "line": 35, "side": "RIGHT", "created_at": "2025-12-10T12:47:06+00:00" }, { "id": 2606549024, "user": "user_5501cd6d3dc8", "body": "I'd use the same wording that I proposed in #20362, so `23ai/26ai (23.9)`, e.g.\n\n_\"UUID4 requires Oracle version 23ai/26ai (23.9) or later.\"_", "path": "django/db/models/functions/uuid.py", "line": null, "side": "RIGHT", "created_at": "2025-12-10T12:51:57+00:00" }, { "id": 2607840889, "user": "user_3a67c55598c5", "body": "Let's keep the new test for the deprecation warning but also keep the old test since it's still supported for now. All you should have to do is `warnings.catch_warnings(action=\"ignore\", category=...)`", "path": "tests/postgres_tests/test_functions.py", "line": 32, "side": "LEFT", "created_at": "2025-12-10T18:49:52+00:00" }, { "id": 2607897034, "user": "user_3a67c55598c5", "body": "We should take the opportunity to add `arity` on new built-in functions:\n```suggestion\n function = \"UUIDV4\"\n arity = 0\n```", "path": "django/db/models/functions/uuid.py", "line": 7, "side": "RIGHT", "created_at": "2025-12-10T19:09:33+00:00" }, { "id": 2607897466, "user": "user_3a67c55598c5", "body": "We should take a decision about whether to add `arity = 0` here also, even though postgres has an optional `shift` argument, or leave it without. I don't think the shift is part of our cross-db abstraction here, so I'm okay with `arity = 0` and forcing people to subclass `Func` themselves if they want a shift. WDYT?", "path": "django/db/models/functions/uuid.py", "line": 41, "side": "RIGHT", "created_at": "2025-12-10T19:09:42+00:00" }, { "id": 2607952140, "user": "user_3a67c55598c5", "body": "We definitely need to keep the class forever. Whether to deprecate it is, I think, bound up with Lily's point about `system_check_deprecated_details` gaining support for inspecting `db_default`. If we don't want to do that in this PR, then we should remove the deprecation.", "path": "django/contrib/postgres/functions.py", "line": null, "side": "RIGHT", "created_at": "2025-12-10T19:28:20+00:00" }, { "id": 2607960300, "user": "user_3a67c55598c5", "body": "This will be pretty noisy for existing migrations. Did you look into whether you could `catch_warnings` anywhere inside the migration loader?", "path": "django/contrib/postgres/functions.py", "line": null, "side": "RIGHT", "created_at": "2025-12-10T19:31:17+00:00" }, { "id": 2608161415, "user": "user_3a67c55598c5", "body": "This will help when grepping for `PY314` three years from now. :-)\n```suggestion\n # PY314: When dropping support for 3.14, remove the entire method.\n def as_sqlite(self, compiler, connection, **extra_context):\n```", "path": "django/db/models/functions/uuid.py", "line": 54, "side": "RIGHT", "created_at": "2025-12-10T20:47:41+00:00" }, { "id": 2608178417, "user": "user_3a67c55598c5", "body": "Most of the other 0-argument functions still document `**extra` here, but some don't, so I'll leave it to you.", "path": "docs/ref/models/database-functions.txt", "line": 1889, "side": "RIGHT", "created_at": "2025-12-10T20:54:26+00:00" }, { "id": 2608181512, "user": "user_3a67c55598c5", "body": "Project style is to use `admonition:: ` with a heading rather than bare note. Maybe \"availability\"?", "path": "docs/ref/models/database-functions.txt", "line": null, "side": "RIGHT", "created_at": "2025-12-10T20:55:33+00:00" }, { "id": 2608200027, "user": "user_5501cd6d3dc8", "body": "I think we should try to avoid adding an invalid function when Python > 3.14 is used. Maybe:\n```python\ndef _sqlite_uuid7():\n if PY314:\n from uuid import uuid7\n\n return uuid7().hex\n else:\n return None\n```\nor raise an error in `else...`.", "path": "django/db/backends/sqlite3/_functions.py", "line": null, "side": "RIGHT", "created_at": "2025-12-10T21:01:47+00:00" }, { "id": 2608202744, "user": "user_5501cd6d3dc8", "body": "We have a directive for RFCs: `:rfc:`.", "path": "docs/ref/models/database-functions.txt", "line": null, "side": "RIGHT", "created_at": "2025-12-10T21:02:58+00:00" }, { "id": 2608205772, "user": "user_5501cd6d3dc8", "body": "```suggestion\n \"UUID7 on SQLite requires Python version 3.14 or later.\"\n```", "path": "django/db/models/functions/uuid.py", "line": null, "side": "RIGHT", "created_at": "2025-12-10T21:04:17+00:00" }, { "id": 2608208743, "user": "user_3a67c55598c5", "body": "I don't think it's worth removing these class attributes -- we're breaking backward compatibility for subclasses that might be using different `template` or `function` or `output_field`.", "path": "django/contrib/postgres/functions.py", "line": 5, "side": "LEFT", "created_at": "2025-12-10T21:05:37+00:00" }, { "id": 2608211211, "user": "user_3a67c55598c5", "body": "Reminder for when you've finalized the deprecation strategy: Please add a `# RemovedInDjango70Warning` with instructions about how to alter the code.", "path": "django/contrib/postgres/functions.py", "line": null, "side": "RIGHT", "created_at": "2025-12-10T21:06:44+00:00" }, { "id": 2608226079, "user": "user_3a67c55598c5", "body": "Oh, I just saw #20282. In that case let's definitely use `arity=0` here and then in #20282 we can change to `arity=1` and then raise in `__init__` for providing `shift` on unsupported backends before delegating to the super's arity checks.", "path": "django/db/models/functions/uuid.py", "line": 41, "side": "RIGHT", "created_at": "2025-12-10T21:12:57+00:00" }, { "id": 2608234157, "user": "user_3a67c55598c5", "body": "Since we probably don't want to do that, I think I prefer either the system check or not deprecating.", "path": "django/contrib/postgres/functions.py", "line": null, "side": "RIGHT", "created_at": "2025-12-10T21:16:04+00:00" }, { "id": 2608251263, "user": "user_057de2f3b132", "body": "I think I'll just remove the deprecation. We could document the new alternative, but anything more than that is too much hassle without the check infrastructure, which I don't want to add. This could be revisited if someone else adds it. Should we have a ticket for that?", "path": "django/contrib/postgres/functions.py", "line": null, "side": "RIGHT", "created_at": "2025-12-10T21:22:46+00:00" }, { "id": 2608288501, "user": "user_3a67c55598c5", "body": "> Should we have a ticket for that?\n\nSure, but I would say a new-features issue: \"make it possible to deprecate expressions\". Let me know if you don't have a cycle for that, I could toss something quickly over the wall.", "path": "django/contrib/postgres/functions.py", "line": null, "side": "RIGHT", "created_at": "2025-12-10T21:34:23+00:00" }, { "id": 2608344831, "user": "user_057de2f3b132", "body": "I think we probably shouldn't document `**extra` here or in other 0-argument functions, since if I understand correctly using `extra` would be a no-op.\n\nAs an aside, for the other functions I'm not sure how discoverable it is what `**extra` means - I think it's documented on `Func` itself, but that's on a completely different page.", "path": "docs/ref/models/database-functions.txt", "line": 1889, "side": "RIGHT", "created_at": "2025-12-10T21:54:38+00:00" }, { "id": 2608354633, "user": "user_057de2f3b132", "body": "The deprecation has been removed.", "path": "django/contrib/postgres/functions.py", "line": null, "side": "RIGHT", "created_at": "2025-12-10T21:57:06+00:00" }, { "id": 2608356932, "user": "user_057de2f3b132", "body": "I put an `if PY314:` guard around registering the function instead.", "path": "django/db/backends/sqlite3/_functions.py", "line": null, "side": "RIGHT", "created_at": "2025-12-10T21:57:46+00:00" }, { "id": 2608358170, "user": "user_057de2f3b132", "body": "This is moot since I removed the deprecation.", "path": "tests/postgres_tests/test_functions.py", "line": 32, "side": "LEFT", "created_at": "2025-12-10T21:58:11+00:00" }, { "id": 2608361122, "user": "user_057de2f3b132", "body": "Yeah, please open one! Thanks!", "path": "django/contrib/postgres/functions.py", "line": null, "side": "RIGHT", "created_at": "2025-12-10T21:59:03+00:00" }, { "id": 2608364593, "user": "user_057de2f3b132", "body": "This is moot since I've removed the deprecation, but otherwise a good point.", "path": "django/contrib/postgres/functions.py", "line": 5, "side": "LEFT", "created_at": "2025-12-10T21:59:59+00:00" }, { "id": 2608379474, "user": "user_3a67c55598c5", "body": "Actually you can pass in template overrides. It verges on a mess, but might have a silver of value for 3rd party backends. See ticket-35459 for where we're discussing whether to rip it out of everywhere it's not currently documented.", "path": "docs/ref/models/database-functions.txt", "line": 1889, "side": "RIGHT", "created_at": "2025-12-10T22:04:28+00:00" }, { "id": 2608439267, "user": "user_057de2f3b132", "body": "I added a comment there, but in this case I think it's fine to require subclassing to change the `template`.", "path": "docs/ref/models/database-functions.txt", "line": 1889, "side": "RIGHT", "created_at": "2025-12-10T22:30:05+00:00" }, { "id": 2610500483, "user": "user_3a67c55598c5", "body": "I added this note.", "path": "docs/ref/contrib/postgres/functions.txt", "line": 27, "side": "RIGHT", "created_at": "2025-12-11T13:00:44+00:00" } ], "meta": { "languages": [ "py", "txt" ], "touches_tests": true, "review_state_summary": { "APPROVED": 5, "COMMENTED": 35 }, "meaningful_comment_count": 47, "has_approval": true, "has_changes_requested": false, "total_review_comments": 47 } } { "_id": "2e7943046d39bc20", "_schema_version": "1.0", "_cleaned_at": "2026-02-12T07:46:52.148241+00:00", "repo": "django/django", "repo_url": "https://github.com/django/django", "license_name": "BSD 3-Clause \"New\" or \"Revised\" License", "license_spdx": "BSD-3-Clause", "pr_number": 20098, "title": "Fixed #36733 -- Escaped attributes in Stylesheet.__str__.", "body": "#### Trac ticket number\n\n\nticket-36733\n\n#### Branch description\nThis PR fixes incorrect behavior in `Stylesheet.__str__()` where attribute values (URL, mimetype, media) were not HTML-escaped. \nThe fix applies `django.utils.html.escape()` to all attribute values and includes a dedicated test ensuring correct escaping.\n\n#### Checklist\n- [x] This PR targets the `main` branch. \n- [x] The commit message is written in past tense, mentions the ticket number, and ends with a period.\n- [x] I have checked the \"Has patch\" ticket flag in the Trac system.\n- [x] I have added or updated relevant tests.\n- [x] I have added or updated relevant docs, including release notes if applicable.\n- [ ] I have attached screenshots in both light and dark modes for any UI changes.", "author": "user_95f516637e24", "created_at": "2025-11-15T05:08:54+00:00", "merged_at": "2025-11-18T22:15:31+00:00", "base_branch": "main", "head_branch": "ticket-36733-escape-stylesheet-attributes", "additions": 40, "deletions": 22, "changed_files": 4, "files": [ { "filename": "django/utils/feedgenerator.py", "status": "modified", "additions": 7, "deletions": 6, "changes": 13, "patch": "@@ -28,6 +28,7 @@\n from io import StringIO\n from urllib.parse import urlparse\n \n+from django.forms.utils import flatatt\n from django.utils.encoding import iri_to_uri\n from django.utils.xmlutils import SimplerXMLGenerator\n \n@@ -95,12 +96,12 @@ def mimetype(self):\n return self._mimetype\n \n def __str__(self):\n- data = [f'href=\"{self.url}\"']\n- if self.mimetype is not None:\n- data.append(f'type=\"{self.mimetype}\"')\n- if self.media is not None:\n- data.append(f'media=\"{self.media}\"')\n- return \" \".join(data)\n+ attrs = {\n+ \"href\": iri_to_uri(self._url),\n+ \"type\": self.mimetype,\n+ \"media\": self.media,\n+ }\n+ return flatatt(attrs).strip()\n \n def __repr__(self):\n return repr((self.url, self.mimetype, self.media))" }, { "filename": "docs/releases/5.2.9.txt", "status": "modified", "additions": 4, "deletions": 1, "changes": 5, "patch": "@@ -9,4 +9,7 @@ Django 5.2.9 fixes several bugs in 5.2.8.\n Bugfixes\n ========\n \n-* ...\n+* Fixed a bug in Django 5.2 where\n+ ``django.utils.feedgenerator.Stylesheet.__str__()`` did not escape\n+ the ``url``, ``mimetype``, and ``media`` attributes, potentially leading\n+ to invalid XML markup (:ticket:`36733`)." }, { "filename": "tests/syndication_tests/tests.py", "status": "modified", "additions": 14, "deletions": 14, "changes": 28, "patch": "@@ -578,51 +578,51 @@ def test_stylesheets_none(self):\n def test_stylesheets(self):\n testdata = [\n # Plain strings.\n- (\"/test.xsl\", 'href=\"/test.xsl\" type=\"text/xsl\" media=\"screen\"'),\n- (\"/test.xslt\", 'href=\"/test.xslt\" type=\"text/xsl\" media=\"screen\"'),\n- (\"/test.css\", 'href=\"/test.css\" type=\"text/css\" media=\"screen\"'),\n+ (\"/test.xsl\", 'href=\"/test.xsl\" media=\"screen\" type=\"text/xsl\"'),\n+ (\"/test.xslt\", 'href=\"/test.xslt\" media=\"screen\" type=\"text/xsl\"'),\n+ (\"/test.css\", 'href=\"/test.css\" media=\"screen\" type=\"text/css\"'),\n (\"/test\", 'href=\"/test\" media=\"screen\"'),\n (\n \"https://example.com/test.xsl\",\n- 'href=\"https://example.com/test.xsl\" type=\"text/xsl\" media=\"screen\"',\n+ 'href=\"https://example.com/test.xsl\" media=\"screen\" type=\"text/xsl\"',\n ),\n (\n \"https://example.com/test.css\",\n- 'href=\"https://example.com/test.css\" type=\"text/css\" media=\"screen\"',\n+ 'href=\"https://example.com/test.css\" media=\"screen\" type=\"text/css\"',\n ),\n (\n \"https://example.com/test\",\n 'href=\"https://example.com/test\" media=\"screen\"',\n ),\n- (\"/♥.xsl\", 'href=\"/%E2%99%A5.xsl\" type=\"text/xsl\" media=\"screen\"'),\n+ (\"/♥.xsl\", 'href=\"/%E2%99%A5.xsl\" media=\"screen\" type=\"text/xsl\"'),\n (\n static(\"stylesheet.xsl\"),\n- 'href=\"/static/stylesheet.xsl\" type=\"text/xsl\" media=\"screen\"',\n+ 'href=\"/static/stylesheet.xsl\" media=\"screen\" type=\"text/xsl\"',\n ),\n (\n static(\"stylesheet.css\"),\n- 'href=\"/static/stylesheet.css\" type=\"text/css\" media=\"screen\"',\n+ 'href=\"/static/stylesheet.css\" media=\"screen\" type=\"text/css\"',\n ),\n (static(\"stylesheet\"), 'href=\"/static/stylesheet\" media=\"screen\"'),\n (\n reverse(\"syndication-xsl-stylesheet\"),\n- 'href=\"/syndication/stylesheet.xsl\" type=\"text/xsl\" media=\"screen\"',\n+ 'href=\"/syndication/stylesheet.xsl\" media=\"screen\" type=\"text/xsl\"',\n ),\n (\n reverse_lazy(\"syndication-xsl-stylesheet\"),\n- 'href=\"/syndication/stylesheet.xsl\" type=\"text/xsl\" media=\"screen\"',\n+ 'href=\"/syndication/stylesheet.xsl\" media=\"screen\" type=\"text/xsl\"',\n ),\n # Stylesheet objects.\n (\n Stylesheet(\"/test.xsl\"),\n- 'href=\"/test.xsl\" type=\"text/xsl\" media=\"screen\"',\n+ 'href=\"/test.xsl\" media=\"screen\" type=\"text/xsl\"',\n ),\n (Stylesheet(\"/test.xsl\", mimetype=None), 'href=\"/test.xsl\" media=\"screen\"'),\n (Stylesheet(\"/test.xsl\", media=None), 'href=\"/test.xsl\" type=\"text/xsl\"'),\n (Stylesheet(\"/test.xsl\", mimetype=None, media=None), 'href=\"/test.xsl\"'),\n (\n Stylesheet(\"/test.xsl\", mimetype=\"text/xml\"),\n- 'href=\"/test.xsl\" type=\"text/xml\" media=\"screen\"',\n+ 'href=\"/test.xsl\" media=\"screen\" type=\"text/xml\"',\n ),\n ]\n for stylesheet, expected in testdata:\n@@ -642,12 +642,12 @@ def test_stylesheets_instructions_are_at_the_top(self):\n self.assertEqual(doc.childNodes[0].nodeName, \"xml-stylesheet\")\n self.assertEqual(\n doc.childNodes[0].data,\n- 'href=\"/stylesheet1.xsl\" type=\"text/xsl\" media=\"screen\"',\n+ 'href=\"/stylesheet1.xsl\" media=\"screen\" type=\"text/xsl\"',\n )\n self.assertEqual(doc.childNodes[1].nodeName, \"xml-stylesheet\")\n self.assertEqual(\n doc.childNodes[1].data,\n- 'href=\"/stylesheet2.xsl\" type=\"text/xsl\" media=\"screen\"',\n+ 'href=\"/stylesheet2.xsl\" media=\"screen\" type=\"text/xsl\"',\n )\n \n def test_stylesheets_typeerror_if_str_or_stylesheet(self):" }, { "filename": "tests/utils_tests/test_feedgenerator.py", "status": "modified", "additions": 15, "deletions": 1, "changes": 16, "patch": "@@ -156,6 +156,20 @@ def test_stylesheet_keeps_lazy_urls(self):\n stylesheet = feedgenerator.Stylesheet(SimpleLazyObject(m))\n m.assert_not_called()\n self.assertEqual(\n- str(stylesheet), 'href=\"test.css\" type=\"text/css\" media=\"screen\"'\n+ str(stylesheet), 'href=\"test.css\" media=\"screen\" type=\"text/css\"'\n )\n m.assert_called_once()\n+\n+ def test_stylesheet_attribute_escaping(self):\n+ style = feedgenerator.Stylesheet(\n+ url='http://example.com/style.css?foo=\"bar\"&baz=<>',\n+ mimetype='text/css; charset=\"utf-8\"',\n+ media='screen and (max-width: \"600px\")',\n+ )\n+\n+ self.assertEqual(\n+ str(style),\n+ 'href=\"http://example.com/style.css?foo=%22bar%22&baz=%3C%3E\" '\n+ 'media=\"screen and (max-width: "600px")\" '\n+ 'type=\"text/css; charset="utf-8"\"',\n+ )" } ], "reviews": [ { "id": 3470537790, "user": "user_3a67c55598c5", "state": "COMMENTED", "body": "Thanks for picking this up. I'll take a closer look tomorrow, but in the meantime can you add a release note in the style of the other notes for bugs in new 5.2 features?", "submitted_at": "2025-11-16T22:21:44+00:00" }, { "id": 3473811931, "user": "user_34c3f4acb8a8", "state": "COMMENTED", "body": null, "submitted_at": "2025-11-17T17:24:03+00:00" }, { "id": 3474265782, "user": "user_3a67c55598c5", "state": "COMMENTED", "body": null, "submitted_at": "2025-11-17T20:05:41+00:00" }, { "id": 3476731569, "user": "user_34c3f4acb8a8", "state": "COMMENTED", "body": null, "submitted_at": "2025-11-18T10:12:17+00:00" }, { "id": 3479057350, "user": "user_3a67c55598c5", "state": "APPROVED", "body": "Thank you!", "submitted_at": "2025-11-18T17:52:45+00:00" } ], "review_comments": [ { "id": 2534936310, "user": "user_34c3f4acb8a8", "body": "Suggestion: It might be nice to use `django.forms.utils.flatatt` here, since it handles both joining the values together and escaping them", "path": "django/utils/feedgenerator.py", "line": null, "side": "RIGHT", "created_at": "2025-11-17T17:24:03+00:00" }, { "id": 2535283570, "user": "user_3a67c55598c5", "body": "Please mention the version i.e. \"Fixed a bug in Django 5.2\"", "path": "docs/releases/5.2.9.txt", "line": null, "side": "RIGHT", "created_at": "2025-11-17T19:30:08+00:00" }, { "id": 2535288327, "user": "user_3a67c55598c5", "body": "You can chop this docstring; we favor descriptive method names instead (which you have done).", "path": "tests/utils_tests/test_feedgenerator.py", "line": null, "side": "RIGHT", "created_at": "2025-11-17T19:31:59+00:00" }, { "id": 2535342950, "user": "user_3a67c55598c5", "body": "Why do we need `iri_to_uri` here?", "path": "django/utils/feedgenerator.py", "line": null, "side": "RIGHT", "created_at": "2025-11-17T19:54:07+00:00" }, { "id": 2535368961, "user": "user_3a67c55598c5", "body": "It is unfortunate to have to update the tests, but I agree with [USER_REDACTED] that delegating to `flatatt` is nicer.\n\n[USER_REDACTED] are you up for updating the tests? What hurts is that we don't have an `assertInXML` helper like we do for `assertInHTML`.", "path": "django/utils/feedgenerator.py", "line": null, "side": "RIGHT", "created_at": "2025-11-17T20:05:30+00:00" }, { "id": 2537299479, "user": "user_34c3f4acb8a8", "body": "Nit: Looks like `flatatt` excludes `None` already: \n\nhttps://github.com/[USER_REDACTED]ngo/django/blob/3c005b5f79bf6d71f3f4c3692ed670e1722b0fb6/django/forms/utils.py#L37", "path": "django/utils/feedgenerator.py", "line": null, "side": "RIGHT", "created_at": "2025-11-18T10:12:17+00:00" } ], "meta": { "languages": [ "py", "txt" ], "touches_tests": true, "review_state_summary": { "COMMENTED": 4, "APPROVED": 1 }, "meaningful_comment_count": 6, "has_approval": true, "has_changes_requested": false, "total_review_comments": 6 } } { "_id": "f95934a4a76e1813", "_schema_version": "1.0", "_cleaned_at": "2026-02-12T07:46:52.148241+00:00", "repo": "django/django", "repo_url": "https://github.com/django/django", "license_name": "BSD 3-Clause \"New\" or \"Revised\" License", "license_spdx": "BSD-3-Clause", "pr_number": 20094, "title": "Fixed #36141 -- Checked for applied replaced migrations recursively.", "body": "#### Trac ticket number\n\n\nticket-36141\n\n#### Branch description\nWhen we check for consistent migrations history during \"migrate\", we try to consider squash migrations as applied, when all the files that they replace are applied. However this check must be done recursively, as we now allow multiple levels of squashing.\n\n#### Checklist\n- [x] This PR targets the `main` branch. \n- [x] The commit message is written in past tense, mentions the ticket number, and ends with a period.\n- [x] I have checked the \"Has patch\" ticket flag in the Trac system.\n- [x] I have added or updated relevant tests.\n- [x] I have added or updated relevant docs, including release notes if applicable.\n- [x] I have attached screenshots in both light and dark modes for any UI changes.", "author": "user_9cbf8c202a52", "created_at": "2025-11-13T23:53:26+00:00", "merged_at": "2025-11-18T13:10:26+00:00", "base_branch": "main", "head_branch": "36141_check_applied_migrations_recursively", "additions": 71, "deletions": 7, "changed_files": 3, "files": [ { "filename": "django/db/migrations/executor.py", "status": "modified", "additions": 1, "deletions": 2, "changes": 3, "patch": "@@ -304,8 +304,7 @@ def check_replacements(self):\n \"\"\"\n applied = self.recorder.applied_migrations()\n for key, migration in self.loader.replacements.items():\n- all_applied = all(m in applied for m in migration.replaces)\n- if all_applied and key not in applied:\n+ if key not in applied and self.loader.all_replaced_applied(key, applied):\n self.recorder.record_applied(*key)\n \n def detect_soft_applied(self, project_state, migration):" }, { "filename": "django/db/migrations/loader.py", "status": "modified", "additions": 16, "deletions": 5, "changes": 21, "patch": "@@ -356,11 +356,8 @@ def check_consistent_history(self, connection):\n if parent not in applied:\n # Skip unapplied squashed migrations that have all of their\n # `replaces` applied.\n- if parent in self.replacements:\n- if all(\n- m in applied for m in self.replacements[parent].replaces\n- ):\n- continue\n+ if self.all_replaced_applied(parent.key, applied):\n+ continue\n raise InconsistentMigrationHistory(\n \"Migration {}.{} is applied before its dependency \"\n \"{}.{} on database '{}'.\".format(\n@@ -372,6 +369,20 @@ def check_consistent_history(self, connection):\n )\n )\n \n+ def all_replaced_applied(self, migration_key, applied):\n+ \"\"\"\n+ Checks (recursively) whether all replaced migrations are applied.\n+ \"\"\"\n+ if migration_key in self.replacements:\n+ for replaced_key in self.replacements[migration_key].replaces:\n+ if replaced_key not in applied and not self.all_replaced_applied(\n+ replaced_key, applied\n+ ):\n+ return False\n+ return True\n+\n+ return False\n+\n def detect_conflicts(self):\n \"\"\"\n Look through the loaded graph and detect any conflicts - apps" }, { "filename": "tests/migrations/test_commands.py", "status": "modified", "additions": 54, "deletions": 0, "changes": 54, "patch": "@@ -3161,6 +3161,60 @@ def test_double_replaced_migrations_are_recorded(self):\n ]\n self.assertNotIn(\"migrations\", applied_app_labels)\n \n+ def test_double_replaced_migrations_are_checked_correctly(self):\n+ \"\"\"\n+ If replaced migrations are already applied and replacing migrations\n+ are not, then migrate should not fail with\n+ InconsistentMigrationHistory.\n+ \"\"\"\n+ with self.temporary_migration_module():\n+ call_command(\n+ \"makemigrations\",\n+ \"migrations\",\n+ \"--empty\",\n+ interactive=False,\n+ verbosity=0,\n+ )\n+ call_command(\n+ \"makemigrations\",\n+ \"migrations\",\n+ \"--empty\",\n+ interactive=False,\n+ verbosity=0,\n+ )\n+ call_command(\n+ \"makemigrations\",\n+ \"migrations\",\n+ \"--empty\",\n+ interactive=False,\n+ verbosity=0,\n+ )\n+ call_command(\n+ \"makemigrations\",\n+ \"migrations\",\n+ \"--empty\",\n+ interactive=False,\n+ verbosity=0,\n+ )\n+ call_command(\"migrate\", \"migrations\", interactive=False, verbosity=0)\n+ call_command(\n+ \"squashmigrations\",\n+ \"migrations\",\n+ \"0001\",\n+ \"0002\",\n+ interactive=False,\n+ verbosity=0,\n+ )\n+ call_command(\n+ \"squashmigrations\",\n+ \"migrations\",\n+ \"0001_initial_squashed\",\n+ \"0003\",\n+ interactive=False,\n+ verbosity=0,\n+ )\n+ call_command(\"migrate\", \"migrations\", interactive=False, verbosity=0)\n+\n def test_squashmigrations_initial_attribute(self):\n with self.temporary_migration_module(\n module=\"migrations.test_migrations\"" } ], "reviews": [ { "id": 3466843879, "user": "user_3a67c55598c5", "state": "COMMENTED", "body": null, "submitted_at": "2025-11-14T21:18:56+00:00" }, { "id": 3466907766, "user": "user_3a67c55598c5", "state": "APPROVED", "body": "Thank you!\n\n> Do you mean this [docs](https://docs.djangoproject.com/en/dev/topics/migrations/#migration-squashing)?\n\nYep, the bit that led to the original triage decision about \"making sure that they run migrate\". I guess if we just read this as strong advice, then it's fine to leave it and batch these other improvements up later.", "submitted_at": "2025-11-14T21:36:13+00:00" } ], "review_comments": [ { "id": 2528961826, "user": "user_3a67c55598c5", "body": "Just noting for others: the checking for cycles is done earlier, in `replace_migration()`. I can't find a way to cause recursion errors that wouldn't be caught there.", "path": "django/db/migrations/loader.py", "line": 374, "side": "RIGHT", "created_at": "2025-11-14T21:18:56+00:00" } ], "meta": { "languages": [ "py" ], "touches_tests": true, "review_state_summary": { "COMMENTED": 1, "APPROVED": 1 }, "meaningful_comment_count": 1, "has_approval": true, "has_changes_requested": false, "total_review_comments": 1 } } { "_id": "68668f3adac4bf54", "_schema_version": "1.0", "_cleaned_at": "2026-02-12T07:46:52.148241+00:00", "repo": "django/django", "repo_url": "https://github.com/django/django", "license_name": "BSD 3-Clause \"New\" or \"Revised\" License", "license_spdx": "BSD-3-Clause", "pr_number": 20087, "title": "Fixed #36730 -- Fixed constraint validation crash for excluded FK attnames.", "body": "#### Trac ticket number\n\nticket-36730\n\n#### Branch description\n\nFix a regression in Django 6.0, with a suitable test.\n\n#### Checklist\n- [x] This PR targets the `main` branch. \n- [x] The commit message is written in past tense, mentions the ticket number, and ends with a period.\n- [x] I have checked the \"Has patch\" ticket flag in the Trac system.\n- [x] I have added or updated relevant tests.\n- [x] I have added or updated relevant docs, including release notes if applicable.\n- [x] I have attached screenshots in both light and dark modes for any UI changes.", "author": "user_8fc305198eb3", "created_at": "2025-11-12T19:50:09+00:00", "merged_at": "2025-11-13T09:03:51+00:00", "base_branch": "main", "head_branch": "ticket_36730", "additions": 39, "deletions": 2, "changed_files": 3, "files": [ { "filename": "django/db/models/constraints.py", "status": "modified", "additions": 5, "deletions": 2, "changes": 7, "patch": "@@ -51,9 +51,12 @@ def remove_sql(self, model, schema_editor):\n def _expression_refs_exclude(cls, model, expression, exclude):\n get_field = model._meta.get_field\n for field_name, *__ in model._get_expr_references(expression):\n- if field_name in exclude:\n+ if field_name == \"pk\":\n+ field = model._meta.pk\n+ else:\n+ field = get_field(field_name)\n+ if field_name in exclude or field.name in exclude:\n return True\n- field = get_field(field_name)\n if field.generated and cls._expression_refs_exclude(\n model, field.expression, exclude\n ):" }, { "filename": "tests/model_forms/models.py", "status": "modified", "additions": 19, "deletions": 0, "changes": 19, "patch": "@@ -543,3 +543,22 @@ class Meta:\n violation_error_message=\"Price must be greater than zero.\",\n ),\n ]\n+\n+\n+class AttnameConstraintsModel(models.Model):\n+ left = models.ForeignKey(\n+ \"self\", related_name=\"+\", null=True, on_delete=models.SET_NULL\n+ )\n+ right = models.ForeignKey(\n+ \"self\", related_name=\"+\", null=True, on_delete=models.SET_NULL\n+ )\n+\n+ class Meta:\n+ required_db_features = {\"supports_table_check_constraints\"}\n+ constraints = [\n+ models.CheckConstraint(\n+ name=\"%(app_label)s_%(class)s_left_not_right\",\n+ # right_id here is the ForeignKey's attname, not name.\n+ condition=~models.Q(left=models.F(\"right_id\")),\n+ ),\n+ ]" }, { "filename": "tests/model_forms/tests.py", "status": "modified", "additions": 15, "deletions": 0, "changes": 15, "patch": "@@ -30,6 +30,7 @@\n from .models import (\n Article,\n ArticleStatus,\n+ AttnameConstraintsModel,\n Author,\n Author1,\n Award,\n@@ -3766,3 +3767,17 @@ def test_check_constraint_refs_excluded_field(self):\n self.assertEqual(\n full_form.errors, {\"__all__\": [\"Price must be greater than zero.\"]}\n )\n+\n+ def test_check_constraint_refs_excluded_field_attname(self):\n+ left = AttnameConstraintsModel.objects.create()\n+ instance = AttnameConstraintsModel.objects.create(left=left)\n+ data = {\n+ \"left\": str(left.id),\n+ \"right\": \"\",\n+ }\n+ AttnameConstraintsModelForm = modelform_factory(\n+ AttnameConstraintsModel, fields=\"__all__\"\n+ )\n+ full_form = AttnameConstraintsModelForm(data, instance=instance)\n+ self.assertFalse(full_form.is_valid())\n+ self.assertEqual(full_form.errors, {\"right\": [\"This field is required.\"]})" } ], "reviews": [ { "id": 3455665082, "user": "user_5501cd6d3dc8", "state": "COMMENTED", "body": null, "submitted_at": "2025-11-12T21:52:37+00:00" }, { "id": 3456098515, "user": "user_8fc305198eb3", "state": "COMMENTED", "body": null, "submitted_at": "2025-11-12T23:49:01+00:00" }, { "id": 3458228362, "user": "user_5501cd6d3dc8", "state": "COMMENTED", "body": null, "submitted_at": "2025-11-13T08:08:20+00:00" }, { "id": 3458302629, "user": "user_5501cd6d3dc8", "state": "APPROVED", "body": "[USER_REDACTED] Thanks :+1:", "submitted_at": "2025-11-13T08:21:00+00:00" } ], "review_comments": [ { "id": 2519928779, "user": "user_5501cd6d3dc8", "body": "We need to handle `pk` separately (ticket-27944):\n```python\nif field_name == \"pk\":\n field = model._meta.pk\nelse:\n field = get_field(field_name)\nif field.name in exclude:\n return True\n```", "path": "django/db/models/constraints.py", "line": 59, "side": "RIGHT", "created_at": "2025-11-12T21:52:37+00:00" }, { "id": 2520238975, "user": "user_8fc305198eb3", "body": "Cheers!", "path": "django/db/models/constraints.py", "line": 59, "side": "RIGHT", "created_at": "2025-11-12T23:49:01+00:00" }, { "id": 2522180621, "user": "user_5501cd6d3dc8", "body": "EDIT ~The same flag should be checked in `test_check_constraint_refs_excluded_field_attname`.~ Nvd", "path": "tests/model_forms/models.py", "line": 557, "side": "RIGHT", "created_at": "2025-11-13T08:08:19+00:00" } ], "meta": { "languages": [ "py" ], "touches_tests": true, "review_state_summary": { "COMMENTED": 3, "APPROVED": 1 }, "meaningful_comment_count": 2, "has_approval": true, "has_changes_requested": false, "total_review_comments": 3 } } { "_id": "3a0ad865330c0fc5", "_schema_version": "1.0", "_cleaned_at": "2026-02-12T07:46:52.148241+00:00", "repo": "django/django", "repo_url": "https://github.com/django/django", "license_name": "BSD 3-Clause \"New\" or \"Revised\" License", "license_spdx": "BSD-3-Clause", "pr_number": 20086, "title": "Fixed #36728 -- Validate template tag `context` argument at definition time, rather than compile time", "body": "#### Trac ticket number\n\n\nticket-36728\n\n#### Branch description\n\nPreviously, the `context` argument was validated at template compile time, rather than tag definition time. \n\nBecause the function parsing was already done at definition time, the performance benefits are going to be miniscule at best, since the validation is simply checking list members. Therefore, benchmarking is likely to only produce noise. Similarly, because compiled templates are cached, the improvement for most projects will also be small. However, doing the work once per tag, rather than once per tag use is still better, and could make a small improvement for larger codebases.\n\nNote that because of this eagerness, it's possible this is a breaking change, as previously invalid but unused tags will raise errors when loaded. This is likely a niche enough issue not to worry about.\n\n#### Checklist\n- [ ] This PR targets the `main` branch. \n- [ ] The commit message is written in past tense, mentions the ticket number, and ends with a period.\n- [ ] I have checked the \"Has patch\" ticket flag in the Trac system.\n- [ ] I have added or updated relevant tests.\n- [ ] I have added or updated relevant docs, including release notes if applicable.\n- [ ] I have attached screenshots in both light and dark modes for any UI changes.", "author": "user_34c3f4acb8a8", "created_at": "2025-11-12T17:47:00+00:00", "merged_at": "2025-12-05T15:06:48+00:00", "base_branch": "main", "head_branch": "36728-eager-template-tag-argument-validation", "additions": 94, "deletions": 159, "changed_files": 8, "files": [ { "filename": "django/contrib/admin/templatetags/admin_list.py", "status": "modified", "additions": 6, "deletions": 1, "changes": 7, "patch": "@@ -76,6 +76,7 @@ def pagination(cl):\n [USER_REDACTED].tag(name=\"pagination\")\n def pagination_tag(parser, token):\n return InclusionAdminNode(\n+ \"pagination\",\n parser,\n token,\n func=pagination,\n@@ -361,6 +362,7 @@ def result_list(cl):\n [USER_REDACTED].tag(name=\"result_list\")\n def result_list_tag(parser, token):\n return InclusionAdminNode(\n+ \"result_list\",\n parser,\n token,\n func=result_list,\n@@ -476,6 +478,7 @@ def link(filters):\n [USER_REDACTED].tag(name=\"date_hierarchy\")\n def date_hierarchy_tag(parser, token):\n return InclusionAdminNode(\n+ \"date_hierarchy\",\n parser,\n token,\n func=date_hierarchy,\n@@ -500,6 +503,7 @@ def search_form(cl):\n [USER_REDACTED].tag(name=\"search_form\")\n def search_form_tag(parser, token):\n return InclusionAdminNode(\n+ \"search_form\",\n parser,\n token,\n func=search_form,\n@@ -532,14 +536,15 @@ def admin_actions(context):\n [USER_REDACTED].tag(name=\"admin_actions\")\n def admin_actions_tag(parser, token):\n return InclusionAdminNode(\n- parser, token, func=admin_actions, template_name=\"actions.html\"\n+ \"admin_actions\", parser, token, func=admin_actions, template_name=\"actions.html\"\n )\n \n \n [USER_REDACTED].tag(name=\"change_list_object_tools\")\n def change_list_object_tools_tag(parser, token):\n \"\"\"Display the row of change list object tools.\"\"\"\n return InclusionAdminNode(\n+ \"change_list_object_tools\",\n parser,\n token,\n func=lambda context: context," }, { "filename": "django/contrib/admin/templatetags/admin_modify.py", "status": "modified", "additions": 3, "deletions": 1, "changes": 4, "patch": "@@ -51,6 +51,7 @@ def prepopulated_fields_js(context):\n [USER_REDACTED].tag(name=\"prepopulated_fields_js\")\n def prepopulated_fields_js_tag(parser, token):\n return InclusionAdminNode(\n+ \"prepopulated_fields_js\",\n parser,\n token,\n func=prepopulated_fields_js,\n@@ -115,14 +116,15 @@ def submit_row(context):\n [USER_REDACTED].tag(name=\"submit_row\")\n def submit_row_tag(parser, token):\n return InclusionAdminNode(\n- parser, token, func=submit_row, template_name=\"submit_line.html\"\n+ \"submit_row\", parser, token, func=submit_row, template_name=\"submit_line.html\"\n )\n \n \n [USER_REDACTED].tag(name=\"change_form_object_tools\")\n def change_form_object_tools_tag(parser, token):\n \"\"\"Display the row of change form object tools.\"\"\"\n return InclusionAdminNode(\n+ \"change_form_object_tools\",\n parser,\n token,\n func=lambda context: context," }, { "filename": "django/contrib/admin/templatetags/base.py", "status": "modified", "additions": 11, "deletions": 2, "changes": 13, "patch": "@@ -1,5 +1,6 @@\n from inspect import getfullargspec\n \n+from django.template.exceptions import TemplateSyntaxError\n from django.template.library import InclusionNode, parse_bits\n from django.utils.inspect import lazy_annotations\n \n@@ -10,12 +11,21 @@ class InclusionAdminNode(InclusionNode):\n or globally.\n \"\"\"\n \n- def __init__(self, parser, token, func, template_name, takes_context=True):\n+ def __init__(self, name, parser, token, func, template_name, takes_context=True):\n self.template_name = template_name\n with lazy_annotations():\n params, varargs, varkw, defaults, kwonly, kwonly_defaults, _ = (\n getfullargspec(func)\n )\n+ if takes_context:\n+ if params and params[0] == \"context\":\n+ del params[0]\n+ else:\n+ function_name = func.__name__\n+ raise TemplateSyntaxError(\n+ f\"{name!r} sets takes_context=True so {function_name!r} \"\n+ \"must have a first argument of 'context'\"\n+ )\n bits = token.split_contents()\n args, kwargs = parse_bits(\n parser,\n@@ -26,7 +36,6 @@ def __init__(self, parser, token, func, template_name, takes_context=True):\n defaults,\n kwonly,\n kwonly_defaults,\n- takes_context,\n bits[0],\n )\n super().__init__(func, takes_context, args, kwargs, filename=None)" }, { "filename": "django/template/library.py", "status": "modified", "additions": 40, "deletions": 28, "changes": 68, "patch": "@@ -123,6 +123,15 @@ def dec(func):\n ) = getfullargspec(unwrap(func))\n function_name = name or func.__name__\n \n+ if takes_context:\n+ if params and params[0] == \"context\":\n+ del params[0]\n+ else:\n+ raise TemplateSyntaxError(\n+ f\"{function_name!r} is decorated with takes_context=True so it \"\n+ \"must have a first argument of 'context'\"\n+ )\n+\n [USER_REDACTED](func)\n def compile_func(parser, token):\n bits = token.split_contents()[1:]\n@@ -139,7 +148,6 @@ def compile_func(parser, token):\n defaults,\n kwonly,\n kwonly_defaults,\n- takes_context,\n function_name,\n )\n return SimpleNode(func, takes_context, args, kwargs, target_var)\n@@ -182,26 +190,32 @@ def dec(func):\n if end_name is None:\n end_name = f\"end{function_name}\"\n \n- [USER_REDACTED](func)\n- def compile_func(parser, token):\n- tag_params = params.copy()\n+ if takes_context:\n+ if len(params) >= 2 and params[1] == \"content\":\n+ del params[1]\n+ else:\n+ raise TemplateSyntaxError(\n+ f\"{function_name!r} is decorated with takes_context=True so\"\n+ \" it must have a first argument of 'context' and a second \"\n+ \"argument of 'content'\"\n+ )\n \n- if takes_context:\n- if len(tag_params) >= 2 and tag_params[1] == \"content\":\n- del tag_params[1]\n- else:\n- raise TemplateSyntaxError(\n- f\"{function_name!r} is decorated with takes_context=True so\"\n- \" it must have a first argument of 'context' and a second \"\n- \"argument of 'content'\"\n- )\n- elif tag_params and tag_params[0] == \"content\":\n- del tag_params[0]\n+ if params and params[0] == \"context\":\n+ del params[0]\n else:\n raise TemplateSyntaxError(\n- f\"'{function_name}' must have a first argument of 'content'\"\n+ f\"{function_name!r} is decorated with takes_context=True so it \"\n+ \"must have a first argument of 'context'\"\n )\n+ elif params and params[0] == \"content\":\n+ del params[0]\n+ else:\n+ raise TemplateSyntaxError(\n+ f\"{function_name!r} must have a first argument of 'content'\"\n+ )\n \n+ [USER_REDACTED](func)\n+ def compile_func(parser, token):\n bits = token.split_contents()[1:]\n target_var = None\n if len(bits) >= 2 and bits[-2] == \"as\":\n@@ -214,13 +228,12 @@ def compile_func(parser, token):\n args, kwargs = parse_bits(\n parser,\n bits,\n- tag_params,\n+ params,\n varargs,\n varkw,\n defaults,\n kwonly,\n kwonly_defaults,\n- takes_context,\n function_name,\n )\n \n@@ -263,6 +276,15 @@ def dec(func):\n ) = getfullargspec(unwrap(func))\n function_name = name or func.__name__\n \n+ if takes_context:\n+ if params and params[0] == \"context\":\n+ params = params[1:]\n+ else:\n+ raise TemplateSyntaxError(\n+ f\"{function_name!r} is decorated with takes_context=True so it \"\n+ \"must have a first argument of 'context'\"\n+ )\n+\n [USER_REDACTED](func)\n def compile_func(parser, token):\n bits = token.split_contents()[1:]\n@@ -275,7 +297,6 @@ def compile_func(parser, token):\n defaults,\n kwonly,\n kwonly_defaults,\n- takes_context,\n function_name,\n )\n return InclusionNode(\n@@ -394,22 +415,13 @@ def parse_bits(\n defaults,\n kwonly,\n kwonly_defaults,\n- takes_context,\n name,\n ):\n \"\"\"\n Parse bits for template tag helpers simple_tag and inclusion_tag, in\n particular by [NAME_REDACTED] by [NAME_REDACTED] arguments.\n \"\"\"\n- if takes_context:\n- if params and params[0] == \"context\":\n- params = params[1:]\n- else:\n- raise TemplateSyntaxError(\n- \"'%s' is decorated with takes_context=True so it must \"\n- \"have a first argument of 'context'\" % name\n- )\n args = []\n kwargs = {}\n unhandled_params = list(params)" }, { "filename": "tests/admin_views/test_templatetags.py", "status": "modified", "additions": 1, "deletions": 0, "changes": 1, "patch": "@@ -144,6 +144,7 @@ def action(arg: SomeType = None): # NOQA: F821\n # inspect.getfullargspec(), which is not ready for deferred\n # evaluation of annotations.\n InclusionAdminNode(\n+ \"test\",\n parser=object(),\n token=Token(token_type=TokenType.TEXT, contents=\"a\"),\n func=action," }, { "filename": "tests/template_tests/templatetags/custom.py", "status": "modified", "additions": 0, "deletions": 56, "changes": 56, "patch": "@@ -268,62 +268,6 @@ def simple_unlimited_args_kwargs_block(content, one, two=\"hi\", *args, **kwargs):\n )\n \n \n-[USER_REDACTED].simple_block_tag(takes_context=True)\n-def simple_block_tag_without_context_parameter(arg):\n- \"\"\"Expected simple_block_tag_without_context_parameter __doc__\"\"\"\n- return \"Expected result\"\n-\n-\n-[USER_REDACTED].simple_block_tag\n-def simple_tag_without_content_parameter(arg):\n- \"\"\"Expected simple_tag_without_content_parameter __doc__\"\"\"\n- return \"Expected result\"\n-\n-\n-[USER_REDACTED].simple_block_tag(takes_context=True)\n-def simple_tag_with_context_without_content_parameter(context, arg):\n- \"\"\"Expected simple_tag_with_context_without_content_parameter __doc__\"\"\"\n- return \"Expected result\"\n-\n-\n-[USER_REDACTED].simple_tag(takes_context=True)\n-def simple_tag_without_context_parameter(arg):\n- \"\"\"Expected simple_tag_without_context_parameter __doc__\"\"\"\n- return \"Expected result\"\n-\n-\n-simple_tag_without_context_parameter.anything = (\n- \"Expected simple_tag_without_context_parameter __dict__\"\n-)\n-\n-\n-[USER_REDACTED].simple_block_tag(takes_context=True)\n-def simple_tag_takes_context_without_params_block():\n- \"\"\"Expected simple_tag_takes_context_without_params_block __doc__\"\"\"\n- return \"Expected result\"\n-\n-\n-[USER_REDACTED].simple_tag(takes_context=True)\n-def simple_tag_takes_context_without_params():\n- \"\"\"Expected simple_tag_takes_context_without_params __doc__\"\"\"\n- return \"Expected result\"\n-\n-\n-simple_tag_takes_context_without_params.anything = (\n- \"Expected simple_tag_takes_context_without_params __dict__\"\n-)\n-\n-\n-[USER_REDACTED].simple_block_tag\n-def simple_block_tag_without_content():\n- return \"Expected result\"\n-\n-\n-[USER_REDACTED].simple_block_tag(takes_context=True)\n-def simple_block_tag_with_context_without_content():\n- return \"Expected result\"\n-\n-\n [USER_REDACTED].simple_tag(takes_context=True)\n def escape_naive(context):\n \"\"\"A tag that doesn't even think about escaping issues\"\"\"" }, { "filename": "tests/template_tests/templatetags/inclusion.py", "status": "modified", "additions": 0, "deletions": 22, "changes": 22, "patch": "@@ -269,28 +269,6 @@ def inclusion_unlimited_args_kwargs(one, two=\"hi\", *args, **kwargs):\n )\n \n \n-[USER_REDACTED].inclusion_tag(\"inclusion.html\", takes_context=True)\n-def inclusion_tag_without_context_parameter(arg):\n- \"\"\"Expected inclusion_tag_without_context_parameter __doc__\"\"\"\n- return {}\n-\n-\n-inclusion_tag_without_context_parameter.anything = (\n- \"Expected inclusion_tag_without_context_parameter __dict__\"\n-)\n-\n-\n-[USER_REDACTED].inclusion_tag(\"inclusion.html\", takes_context=True)\n-def inclusion_tag_takes_context_without_params():\n- \"\"\"Expected inclusion_tag_takes_context_without_params __doc__\"\"\"\n- return {}\n-\n-\n-inclusion_tag_takes_context_without_params.anything = (\n- \"Expected inclusion_tag_takes_context_without_params __dict__\"\n-)\n-\n-\n [USER_REDACTED].inclusion_tag(\"inclusion_extends1.html\")\n def inclusion_extends1():\n return {}" }, { "filename": "tests/template_tests/test_custom.py", "status": "modified", "additions": 33, "deletions": 49, "changes": 82, "patch": "@@ -2,7 +2,7 @@\n \n from django.template import Context, Engine, TemplateSyntaxError\n from django.template.base import Node\n-from django.template.library import InvalidTemplateLibrary\n+from django.template.library import InvalidTemplateLibrary, Library\n from django.test import SimpleTestCase\n from django.test.utils import extend_sys_path\n \n@@ -216,10 +216,6 @@ def test_simple_tag_registration(self):\n self.verify_tag(\n custom.simple_unlimited_args_kwargs, \"simple_unlimited_args_kwargs\"\n )\n- self.verify_tag(\n- custom.simple_tag_without_context_parameter,\n- \"simple_tag_without_context_parameter\",\n- )\n \n def test_simple_tag_missing_context(self):\n # The 'context' parameter must be present when takes_context is True\n@@ -228,19 +224,21 @@ def test_simple_tag_missing_context(self):\n \"takes_context=True so it must have a first argument of 'context'\"\n )\n with self.assertRaisesMessage(TemplateSyntaxError, msg):\n- self.engine.from_string(\n- \"{% load custom %}{% simple_tag_without_context_parameter 123 %}\"\n- )\n+\n+ [USER_REDACTED]().simple_tag(takes_context=True)\n+ def simple_tag_without_context_parameter(arg):\n+ return \"Expected result\"\n \n def test_simple_tag_missing_context_no_params(self):\n msg = (\n \"'simple_tag_takes_context_without_params' is decorated with \"\n \"takes_context=True so it must have a first argument of 'context'\"\n )\n with self.assertRaisesMessage(TemplateSyntaxError, msg):\n- self.engine.from_string(\n- \"{% load custom %}{% simple_tag_takes_context_without_params %}\"\n- )\n+\n+ [USER_REDACTED]().simple_tag(takes_context=True)\n+ def simple_tag_takes_context_without_params():\n+ return \"Expected result\"\n \n \n class SimpleBlockTagTests(TagTestCase):\n@@ -423,18 +421,6 @@ def test_simple_block_tag_errors(self):\n \"of: endsimple_one_default_block.\",\n \"{% load custom %}{% simple_one_default_block %}Some content\",\n ),\n- (\n- \"'simple_tag_without_content_parameter' must have a first argument \"\n- \"of 'content'\",\n- \"{% load custom %}{% simple_tag_without_content_parameter %}\",\n- ),\n- (\n- \"'simple_tag_with_context_without_content_parameter' is decorated with \"\n- \"takes_context=True so it must have a first argument of 'context' and \"\n- \"a second argument of 'content'\",\n- \"{% load custom %}\"\n- \"{% simple_tag_with_context_without_content_parameter %}\",\n- ),\n ]\n \n for entry in errors:\n@@ -485,32 +471,32 @@ def test_simple_block_tag_missing_context(self):\n \"takes_context=True so it must have a first argument of 'context'\"\n )\n with self.assertRaisesMessage(TemplateSyntaxError, msg):\n- self.engine.from_string(\n- \"{% load custom %}{% simple_block_tag_without_context_parameter 123 %}\"\n- \"{% endsimple_block_tag_without_context_parameter %}\"\n- )\n+\n+ [USER_REDACTED]().simple_block_tag(takes_context=True)\n+ def simple_block_tag_without_context_parameter(arg):\n+ return \"Expected result\"\n \n def test_simple_block_tag_missing_context_no_params(self):\n msg = (\n \"'simple_tag_takes_context_without_params_block' is decorated with \"\n \"takes_context=True so it must have a first argument of 'context'\"\n )\n with self.assertRaisesMessage(TemplateSyntaxError, msg):\n- self.engine.from_string(\n- \"{% load custom %}{% simple_tag_takes_context_without_params_block %}\"\n- \"{% endsimple_tag_takes_context_without_params_block %}\"\n- )\n+\n+ [USER_REDACTED]().simple_block_tag(takes_context=True)\n+ def simple_tag_takes_context_without_params_block():\n+ return \"Expected result\"\n \n def test_simple_block_tag_missing_content(self):\n # The 'content' parameter must be present when takes_context is True\n msg = (\n \"'simple_block_tag_without_content' must have a first argument of 'content'\"\n )\n with self.assertRaisesMessage(TemplateSyntaxError, msg):\n- self.engine.from_string(\n- \"{% load custom %}{% simple_block_tag_without_content %}\"\n- \"{% endsimple_block_tag_without_content %}\"\n- )\n+\n+ [USER_REDACTED]().simple_block_tag\n+ def simple_block_tag_without_content():\n+ return \"Expected result\"\n \n def test_simple_block_tag_with_context_missing_content(self):\n # The 'content' parameter must be present when takes_context is True\n@@ -520,10 +506,10 @@ def test_simple_block_tag_with_context_missing_content(self):\n \"second argument of 'content'\"\n )\n with self.assertRaisesMessage(TemplateSyntaxError, msg):\n- self.engine.from_string(\n- \"{% load custom %}{% simple_block_tag_with_context_without_content %}\"\n- \"{% endsimple_block_tag_with_context_without_content %}\"\n- )\n+\n+ [USER_REDACTED]().simple_block_tag(takes_context=True)\n+ def simple_block_tag_with_context_without_content():\n+ return \"Expected result\"\n \n def test_simple_block_gets_context(self):\n c = Context({\"name\": \"Jack & Jill\"})\n@@ -720,19 +706,21 @@ def test_include_tag_missing_context(self):\n \"takes_context=True so it must have a first argument of 'context'\"\n )\n with self.assertRaisesMessage(TemplateSyntaxError, msg):\n- self.engine.from_string(\n- \"{% load inclusion %}{% inclusion_tag_without_context_parameter 123 %}\"\n- )\n+\n+ [USER_REDACTED]().inclusion_tag(\"inclusion.html\", takes_context=True)\n+ def inclusion_tag_without_context_parameter(arg):\n+ return {}\n \n def test_include_tag_missing_context_no_params(self):\n msg = (\n \"'inclusion_tag_takes_context_without_params' is decorated with \"\n \"takes_context=True so it must have a first argument of 'context'\"\n )\n with self.assertRaisesMessage(TemplateSyntaxError, msg):\n- self.engine.from_string(\n- \"{% load inclusion %}{% inclusion_tag_takes_context_without_params %}\"\n- )\n+\n+ [USER_REDACTED]().inclusion_tag(\"inclusion.html\", takes_context=True)\n+ def inclusion_tag_takes_context_without_params():\n+ return {}\n \n def test_inclusion_tags_from_template(self):\n c = Context({\"value\": 42})\n@@ -822,10 +810,6 @@ def test_inclusion_tag_registration(self):\n self.verify_tag(\n inclusion.inclusion_only_unlimited_args, \"inclusion_only_unlimited_args\"\n )\n- self.verify_tag(\n- inclusion.inclusion_tag_without_context_parameter,\n- \"inclusion_tag_without_context_parameter\",\n- )\n self.verify_tag(inclusion.inclusion_tag_use_l10n, \"inclusion_tag_use_l10n\")\n self.verify_tag(\n inclusion.inclusion_unlimited_args_kwargs, \"inclusion_unlimited_args_kwargs\"" } ], "reviews": [ { "id": 3464065869, "user": "user_34c3f4acb8a8", "state": "COMMENTED", "body": null, "submitted_at": "2025-11-14T09:56:00+00:00" }, { "id": 3501613945, "user": "user_8fc305198eb3", "state": "COMMENTED", "body": null, "submitted_at": "2025-11-24T18:03:29+00:00" }, { "id": 3541233222, "user": "user_3a67c55598c5", "state": "COMMENTED", "body": "Looks good 👍 \n\nCan you resolve the merge conflict and update `test_inclusion_admin_node_deferred_annotation`?\n\nCommit message could use tweaks:\n- past tense and full stop\n- mention `content` also?", "submitted_at": "2025-12-04T17:51:51+00:00" }, { "id": 3545010692, "user": "user_3a67c55598c5", "state": "COMMENTED", "body": null, "submitted_at": "2025-12-05T14:27:14+00:00" }, { "id": 3545019718, "user": "user_3a67c55598c5", "state": "APPROVED", "body": "Thanks!", "submitted_at": "2025-12-05T14:29:36+00:00" } ], "review_comments": [ { "id": 2526810573, "user": "user_34c3f4acb8a8", "body": "Thought: This pattern is used quite a bit in this file - should it be extracted into a function?", "path": "django/contrib/admin/templatetags/base.py", "line": 20, "side": "RIGHT", "created_at": "2025-11-14T09:56:00+00:00" }, { "id": 2557241360, "user": "user_8fc305198eb3", "body": "Given the difference in indexes, I would say no.", "path": "django/contrib/admin/templatetags/base.py", "line": 20, "side": "RIGHT", "created_at": "2025-11-24T18:03:28+00:00" }, { "id": 2589982688, "user": "user_3a67c55598c5", "body": "Should we clarify here that `context` should already be popped?", "path": "django/template/library.py", "line": 423, "side": "RIGHT", "created_at": "2025-12-04T17:34:59+00:00" }, { "id": 2590031709, "user": "user_3a67c55598c5", "body": "I'm open to it, but I'm also okay leaving as is.", "path": "django/contrib/admin/templatetags/base.py", "line": 20, "side": "RIGHT", "created_at": "2025-12-04T17:51:34+00:00" }, { "id": 2592882856, "user": "user_3a67c55598c5", "body": "I guess it depends on the use.", "path": "django/template/library.py", "line": 423, "side": "RIGHT", "created_at": "2025-12-05T14:27:14+00:00" } ], "meta": { "languages": [ "py" ], "touches_tests": true, "review_state_summary": { "COMMENTED": 4, "APPROVED": 1 }, "meaningful_comment_count": 5, "has_approval": true, "has_changes_requested": false, "total_review_comments": 5 } } { "_id": "a7212d8348eae38a", "_schema_version": "1.0", "_cleaned_at": "2026-02-12T07:46:52.148241+00:00", "repo": "django/django", "repo_url": "https://github.com/django/django", "license_name": "BSD 3-Clause \"New\" or \"Revised\" License", "license_spdx": "BSD-3-Clause", "pr_number": 20085, "title": "Fixed #26379 - Documented that first filter() chained to a RelatedManager is sticky.", "body": "#### Trac ticket number\n\nticket-26379\n\n#### Branch description\nDocument that first filter() chained to a RelatedManager is sticky. Add heading \"Filters on RelatedManager\" to docs/topics/db/queries.txt. Document the sticky filter behaviour with a query example based on the models Author [NAME_REDACTED] top of the docs page.\n\n#### Checklist\n- [x] This PR targets the `main` branch. \n- [x] The commit message is written in past tense, mentions the ticket number, and ends with a period.\n- [x] I have checked the \"Has patch\" ticket flag in the Trac system.\n- [ ] I have added or updated relevant tests.\n- [x] I have added or updated relevant docs, including release notes if applicable.\n- [ ] I have attached screenshots in both light and dark modes for any UI changes.", "author": "user_1fb3bfd0f3e7", "created_at": "2025-11-12T15:22:00+00:00", "merged_at": "2025-11-17T20:14:42+00:00", "base_branch": "main", "head_branch": "ticket_26379", "additions": 67, "deletions": 0, "changed_files": 1, "files": [ { "filename": "docs/topics/db/queries.txt", "status": "modified", "additions": 67, "deletions": 0, "changes": 67, "patch": "@@ -655,6 +655,8 @@ contained in a single :meth:`~django.db.models.query.QuerySet.filter` call.\n ... )\n , , \n \n+.. _exclude-implementation:\n+\n .. note::\n \n The behavior of :meth:`~django.db.models.query.QuerySet.filter` for queries\n@@ -1966,6 +1968,71 @@ relationships accept primary key values. For example, if ``e1`` and ``e2`` are\n a.entry_set.set([e1, e2])\n a.entry_set.set([e1.pk, e2.pk])\n \n+Filtering on many-to-many relationships\n+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n+\n+When calling ``filter()`` on a many-to-many relationship, be aware that the\n+join between ``Entry`` and the intermediary model to ``Author`` is performed\n+only once, resulting in a restrictive, or \"sticky\", filter. Consider the\n+following example:\n+\n+.. code-block:: pycon\n+\n+ >>> from datetime import date\n+ >>> batucada = Blog.objects.create(name=\"[NAME_REDACTED]\")\n+ >>> e = Entry.objects.create(\n+ ... blog=batucada,\n+ ... headline=\"Supporting social movements with drums\",\n+ ... pub_date=date(2019, 6, 14),\n+ ... )\n+\n+ >>> gloria = Author.objects.create(name=\"Gloria\")\n+ >>> anna = Author.objects.create(name=\"Anna\")\n+ >>> e.authors.add(gloria, anna)\n+\n+ >>> anna.entry_set.filter(authors__name=\"Gloria\")\n+ \n+\n+This filtered query is looking for blog entries that are co-authored by\n+``anna`` and ``gloria``. You would expect it to return the entry ``e``.\n+However, the filter condition, which traverses the many-to-many\n+relationship between ``Entry`` and ``Author``, yields an empty\n+``QuerySet``.\n+\n+Since the join between ``Entry`` and the intermediary model to ``Author``\n+happens only once, no single object of the joined models - i.e., a relation\n+between one author [NAME_REDACTED] - can fulfill the query condition (entries\n+that are co-authored by ``anna`` and ``gloria``). You can circumvent this\n+behavior by [NAME_REDACTED] ``filter()`` calls, resulting in two\n+separate joins and thus a more permissive filter:\n+\n+.. code-block:: pycon\n+\n+ >>> anna.entry_set.filter().filter(authors__name=\"Gloria\")\n+ ]>\n+\n+.. admonition:: exclude() is also sticky\n+\n+ Please note that for this example,\n+ :meth:`~django.db.models.query.QuerySet.exclude` behaves similarly\n+ to :meth:`~django.db.models.query.QuerySet.filter` despite being\n+ implemented differently. When traversing the many-to-many relationship,\n+ it does not exclude the entry ``e`` despite being co-authored [NAME_REDACTED]:\n+\n+ >>> anna.entry_set.exclude(authors__name=\"Gloria\")\n+ ]>\n+\n+ When chaining a second ``exclude()`` call, an empty ``QuerySet`` is\n+ returned, as expected:\n+\n+ >>> anna.entry_set.exclude().exclude(authors__name=\"Gloria\")\n+ \n+\n+ However, in other cases, :meth:`~django.db.models.query.QuerySet.exclude`\n+ behaves differently from :meth:`~django.db.models.query.QuerySet.filter`.\n+ See the :ref:`note ` in the \"Spanning multi-valued\n+ relationships\" section above.\n+\n One-to-one relationships\n ------------------------" } ], "reviews": [ { "id": 3455459247, "user": "user_3a67c55598c5", "state": "COMMENTED", "body": "Great start [USER_REDACTED]. I agreed with your hesitance to get too digressive here. Just a few questions.", "submitted_at": "2025-11-12T21:42:33+00:00" }, { "id": 3455647916, "user": "user_3a67c55598c5", "state": "COMMENTED", "body": null, "submitted_at": "2025-11-12T21:49:34+00:00" }, { "id": 3458386823, "user": "user_1fb3bfd0f3e7", "state": "COMMENTED", "body": null, "submitted_at": "2025-11-13T08:35:20+00:00" }, { "id": 3458582805, "user": "user_1fb3bfd0f3e7", "state": "COMMENTED", "body": null, "submitted_at": "2025-11-13T09:12:45+00:00" }, { "id": 3458613758, "user": "user_1fb3bfd0f3e7", "state": "COMMENTED", "body": null, "submitted_at": "2025-11-13T09:18:13+00:00" }, { "id": 3458972914, "user": "user_1fb3bfd0f3e7", "state": "COMMENTED", "body": null, "submitted_at": "2025-11-13T10:22:37+00:00" }, { "id": 3459007054, "user": "user_1fb3bfd0f3e7", "state": "COMMENTED", "body": null, "submitted_at": "2025-11-13T10:28:20+00:00" }, { "id": 3459017184, "user": "user_1fb3bfd0f3e7", "state": "COMMENTED", "body": null, "submitted_at": "2025-11-13T10:30:00+00:00" }, { "id": 3459805012, "user": "user_3a67c55598c5", "state": "COMMENTED", "body": null, "submitted_at": "2025-11-13T13:29:24+00:00" }, { "id": 3459865491, "user": "user_3a67c55598c5", "state": "COMMENTED", "body": null, "submitted_at": "2025-11-13T13:43:24+00:00" }, { "id": 3467930831, "user": "user_1fb3bfd0f3e7", "state": "COMMENTED", "body": null, "submitted_at": "2025-11-15T10:33:45+00:00" }, { "id": 3474151496, "user": "user_3a67c55598c5", "state": "APPROVED", "body": "Thanks for the PR, [USER_REDACTED], this looks great!", "submitted_at": "2025-11-17T19:23:54+00:00" } ], "review_comments": [ { "id": 2519787620, "user": "user_3a67c55598c5", "body": "To my knowledge we depend on object persistence across shell examples, but here we're depending on objects created before in a \"note\" section, which feels more separate to me. Regrettably, as much as I've enjoyed wringing more value out of this example, (yoko & taylor blogging together?!), we might just create new blog entries, no?", "path": "docs/topics/db/queries.txt", "line": null, "side": "RIGHT", "created_at": "2025-11-12T20:52:48+00:00" }, { "id": 2519841480, "user": "user_3a67c55598c5", "body": "The syntax of using a model instance directly as the right-hand-side of a filter hasn't been introduced in this doc thus far; it's clarified at the end under \"Queries over related objects\". Given that, perhaps we want to query like `authors__name=\"[NAME_REDACTED]\"`? I'm unsure. When clarified, it does say it ~works like other model fields, so maybe this isn't something to fuss over.", "path": "docs/topics/db/queries.txt", "line": null, "side": "RIGHT", "created_at": "2025-11-12T21:14:47+00:00" }, { "id": 2519867813, "user": "user_3a67c55598c5", "body": "This just applies to m2m fields, yes? This filter on a reverse FK involves s `RelatedManager` but isn't sticky:\n\n```py\nclass Author(models.Model):\n name = models.CharField(max_length=200)\n email = models.EmailField()\n \nclass Entry(models.Model):\n mod_date = models.DateField(default=date.today)\n author = models.ForeignKey(Author, on_delete=models.SET_NULL, null=True)\n```\n```py\n yoko = Author.objects.create(name=\"Yoko\")\n taylor = Author.objects.create(name='Taylor')\n e1 = Entry.objects.create(author=yoko)\n print(type(yoko.entry_set))\n qs = yoko.entry_set.filter(author__name=\"Taylor\")\n print(qs.query)\n print(qs)\n```\n```py\n.\nRelatedManager'>\nSELECT \"app_entry\".\"id\", \"app_entry\".\"mod_date\", \"app_entry\".\"author_id\" FROM \"app_entry\"\n INNER JOIN \"app_author\" ON (\"app_entry\".\"author_id\" = \"app_author\".\"id\") WHERE (\"app_entry\".\"author_id\" = 1 AND \"app_author\".\"name\" = Taylor)\n\n\n```\n\nIn other words, `qs` is no different than this qs2 following your mentioned workaround:\n```py\nqs2 = yoko.entry_set.filter().filter(author__name=\"Taylor\")\n```\n\nThe docstring helped me:\nhttps://github.com/[USER_REDACTED]ngo/django/blob/a1ce852e52f45da7528446cef3a1f02416531771/django/db/models/query.py#L2096-L2101\n\nGiven that, I think this just needs a small wording adjustment to deemphasize the RelatedManager-ness and reemphasize the m2m-ness.", "path": "docs/topics/db/queries.txt", "line": null, "side": "RIGHT", "created_at": "2025-11-12T21:26:44+00:00" }, { "id": 2519872158, "user": "user_3a67c55598c5", "body": "Curious, does `exclude()` behave the same? We have one weirdness doc'd here:\n\nhttps://github.com/[USER_REDACTED]ngo/django/blob/a1ce852e52f45da7528446cef3a1f02416531771/docs/topics/db/queries.txt#L660-L664", "path": "docs/topics/db/queries.txt", "line": null, "side": "RIGHT", "created_at": "2025-11-12T21:28:45+00:00" }, { "id": 2519878316, "user": "user_3a67c55598c5", "body": "I think backticks are better here for the variable names to make sure it doesn't accidentally get translated. Same for `e2`. But perhaps you won't have a variable name for yoko after all if you don't save the value of `create()`.", "path": "docs/topics/db/queries.txt", "line": null, "side": "RIGHT", "created_at": "2025-11-12T21:30:44+00:00" }, { "id": 2519896937, "user": "user_3a67c55598c5", "body": "This query is pretty weird (understandably, it's a workaround). It might help to restate what it's doing. (Above, after \"fulfills the query condition\", I'm not quite sure what the condition is.) Am I right that it's getting entries that are co-authored [NAME_REDACTED] & Taylor?", "path": "docs/topics/db/queries.txt", "line": null, "side": "RIGHT", "created_at": "2025-11-12T21:38:39+00:00" }, { "id": 2519899518, "user": "user_3a67c55598c5", "body": "This doc hasn't introduced the table naming behavior for m2m through models, perhaps we should remove mention of tables and prefer wording like \"two separate joins traversing Entry to Author\"?\n\nOther mentions of \"table\" are pretty scant in this doc, describing instead the model instance abstraction.", "path": "docs/topics/db/queries.txt", "line": null, "side": "RIGHT", "created_at": "2025-11-12T21:39:53+00:00" }, { "id": 2519916303, "user": "user_3a67c55598c5", "body": "There could be an alternative here that leaves the reader in a bit less suspense, not needing to read to the end to finally find out what \"sticky\" is. Having sat with this, can you think of anything? Maybe:\n\nbe aware that the first filter call reuses the blah blah blah—in other words, it's \"sticky\".", "path": "docs/topics/db/queries.txt", "line": null, "side": "RIGHT", "created_at": "2025-11-12T21:47:12+00:00" }, { "id": 2522318010, "user": "user_1fb3bfd0f3e7", "body": "I will change the query to authors__name=\"[NAME_REDACTED]\". That will make it clearer.", "path": "docs/topics/db/queries.txt", "line": null, "side": "RIGHT", "created_at": "2025-11-13T08:35:20+00:00" }, { "id": 2522477288, "user": "user_1fb3bfd0f3e7", "body": "You're right. I noticed it too, but was unsure how to reword it.", "path": "docs/topics/db/queries.txt", "line": null, "side": "RIGHT", "created_at": "2025-11-13T09:12:44+00:00" }, { "id": 2522502897, "user": "user_1fb3bfd0f3e7", "body": "Yes, that's right. I will make that more explicit.", "path": "docs/topics/db/queries.txt", "line": null, "side": "RIGHT", "created_at": "2025-11-13T09:18:13+00:00" }, { "id": 2522802667, "user": "user_1fb3bfd0f3e7", "body": "It is probably coherent to talk about exclude() in this context as well. I tried exclude() with our so-far example: https://dryorm.xterm.info/ebqiqyqf. I suppose this behaviour can be called \"different from filter()\", since e2 is returned despite having taylor as a co-author. i need some time to understand the underlying SQL WHERE clause...", "path": "docs/topics/db/queries.txt", "line": null, "side": "RIGHT", "created_at": "2025-11-13T10:22:37+00:00" }, { "id": 2522830621, "user": "user_1fb3bfd0f3e7", "body": "Yes, I also noticed that table names are not present on this doc page. I can reword as you suggest. This also aligns with not getting lost in database-level details. Although it was essential for my understanding of the problem that the join happens from \"entry\" against \"entry_authors\" and not against \"author\".", "path": "docs/topics/db/queries.txt", "line": null, "side": "RIGHT", "created_at": "2025-11-13T10:28:20+00:00" }, { "id": 2522838873, "user": "user_1fb3bfd0f3e7", "body": "I will try. I really struggled with a concise explanation and felt the need to move to the example as quickly as possible.", "path": "docs/topics/db/queries.txt", "line": null, "side": "RIGHT", "created_at": "2025-11-13T10:30:00+00:00" }, { "id": 2523477352, "user": "user_3a67c55598c5", "body": "That's fair!", "path": "docs/topics/db/queries.txt", "line": null, "side": "RIGHT", "created_at": "2025-11-13T13:29:24+00:00" }, { "id": 2523524698, "user": "user_3a67c55598c5", "body": "Ah, okay. I feel like that's the same class of behavior as what I linked to as \"one weirdness\" above. Simon discusses this in his \"What the JOIN?\" [talk](https://youtu.be/Twp8GQkh8H0?si=_pCMKU9mpcDLzQyT&t=2382) at 39:41, \"when negating against a multi-valued relationship...\" and calls it a \"subquery pushdown\".\n\nI don't feel like we have to document the weirdness in detail twice, but I'm open to a sentence that clarifies or maybe links to the other section with details 🤔", "path": "docs/topics/db/queries.txt", "line": null, "side": "RIGHT", "created_at": "2025-11-13T13:43:24+00:00" }, { "id": 2529768351, "user": "user_1fb3bfd0f3e7", "body": "After looking into the exclude() behaviour a bit deeper, I would say that in this case, it behaves similarly to filter(), although implemented differently:\n- single exclude(): co-authored [NAME_REDACTED] despite matching the exclude criteria\n- double exclude(): co-authored [NAME_REDACTED] expected\n\nhttps://dryorm.xterm.info/t6p0rdrc", "path": "docs/topics/db/queries.txt", "line": null, "side": "RIGHT", "created_at": "2025-11-15T10:33:45+00:00" }, { "id": 2535202290, "user": "user_3a67c55598c5", "body": "This reads perfectly, thank you ⭐", "path": "docs/topics/db/queries.txt", "line": null, "side": "RIGHT", "created_at": "2025-11-17T19:00:52+00:00" }, { "id": 2535213724, "user": "user_3a67c55598c5", "body": "We avoid bare notes in favor of an `admonition:: my heading` so that we can use a heading (I'll add one for you).", "path": "docs/topics/db/queries.txt", "line": null, "side": "RIGHT", "created_at": "2025-11-17T19:04:14+00:00" }, { "id": 2535247413, "user": "user_3a67c55598c5", "body": "I see. Just like the filter() example, the sticky scenario is excluding on something that logically can't exist (a single row referring to both authors). I like how you got this expressed without drowning in details 👍", "path": "docs/topics/db/queries.txt", "line": null, "side": "RIGHT", "created_at": "2025-11-17T19:16:57+00:00" }, { "id": 2535248469, "user": "user_3a67c55598c5", "body": "New version reads well here.", "path": "docs/topics/db/queries.txt", "line": null, "side": "RIGHT", "created_at": "2025-11-17T19:17:29+00:00" } ], "meta": { "languages": [ "txt" ], "touches_tests": false, "review_state_summary": { "COMMENTED": 11, "APPROVED": 1 }, "meaningful_comment_count": 21, "has_approval": true, "has_changes_requested": false, "total_review_comments": 21 } } { "_id": "a6f757b2f428fc19", "_schema_version": "1.0", "_cleaned_at": "2026-02-12T07:46:52.148241+00:00", "repo": "django/django", "repo_url": "https://github.com/django/django", "license_name": "BSD 3-Clause \"New\" or \"Revised\" License", "license_spdx": "BSD-3-Clause", "pr_number": 20075, "title": "Fixed #36053 -- Corrected DOM structure for FilteredSelectMultiple widget label in admin", "body": "#### Trac ticket number\n\n\nticket-36053\n\n#### Branch description\nThis change corrects the DOM structure of the FilteredSelectMultiple widget in the Django admin. Previously, the label and add-related link were misaligned due to the selector div being inserted at the beginning of the container. \nThe updated logic now inserts the selector div immediately after the widget, ensuring proper layout and visual consistency between the label, selector, and add link.\nAlso, removed the tests that were checking for the div at the beginning, as they’re no longer relevant.\n\"Captura\n\"Captura\n\"Captura\n\"Captura\n\n#### Checklist\n- [x] This PR targets the `main` branch. \n- [x] The commit message is written in past tense, mentions the ticket number, and ends with a period.\n- [x] I have checked the \"Has patch\" ticket flag in the Trac system.\n- [x] I have added or updated relevant tests.\n- [ ] I have added or updated relevant docs, including release notes if applicable.\n- [x] I have attached screenshots in both light and dark modes for any UI changes.", "author": "user_cad4bfff7ac8", "created_at": "2025-11-10T11:41:00+00:00", "merged_at": "2025-11-11T21:31:16+00:00", "base_branch": "main", "head_branch": "ticket_36053", "additions": 7, "deletions": 5, "changed_files": 2, "files": [ { "filename": "django/contrib/admin/static/admin/js/SelectFilter2.js", "status": "modified", "additions": 2, "deletions": 3, "changes": 5, "patch": "@@ -32,9 +32,8 @@ Requires core.js and SelectBox.js.\n \n //
      or
      \n const selector_div = quickElement('div', from_box.parentNode);\n- // Make sure the selector div is at the beginning so that the\n- // add link would be displayed to the right of the widget.\n- from_box.parentNode.prepend(selector_div);\n+ // Make sure the selector div appears between the label and the add link.\n+ from_box.parentNode.insertBefore(selector_div, from_box.nextSibling);\n selector_div.className = is_stacked ? 'selector stacked' : 'selector';\n \n //
      " }, { "filename": "js_tests/admin/SelectFilter2.test.js", "status": "modified", "additions": 5, "deletions": 2, "changes": 7, "patch": "@@ -10,8 +10,11 @@ QUnit.test('init', function(assert) {\n $('
      This is helpful.
      ').appendTo('#test');\n $('').appendTo('#test');\n SelectFilter.init('id', 'things', 0);\n- assert.equal($('#test').children().first().prop(\"tagName\"), \"DIV\");\n- assert.equal($('#test').children().first().attr(\"class\"), \"selector\");\n+ assert.deepEqual(\n+ Array.from($('#test')[0].children).map(child => child.tagName),\n+ [\"LABEL\", \"DIV\", \"DIV\"]\n+ );\n+ assert.equal($('.helptext')[0].nextSibling.getAttribute(\"class\"), \"selector\");\n assert.equal($('.selector-available label').text().trim(), \"Available things\");\n assert.equal($('.selector-available label').attr(\"id\"), \"id_from_label\");\n assert.equal($('.selector-chosen label').text().trim(), \"Chosen things\");" } ], "reviews": [ { "id": 3445326541, "user": "user_3a67c55598c5", "state": "COMMENTED", "body": "Thanks for the PR 🥇 \n\nDid some manual testing, looks good. I think we need some tests though. I don't know if we can adjust the existing ones or if it's better to try to adapt the new ones from #19394. (One of the new tests from #19394 fails, but I don't know if it's a realistic scenario.) Can you offer your view?", "submitted_at": "2025-11-10T22:02:35+00:00" }, { "id": 3447562799, "user": "user_cad4bfff7ac8", "state": "COMMENTED", "body": null, "submitted_at": "2025-11-11T11:20:32+00:00" }, { "id": 3449683128, "user": "user_3a67c55598c5", "state": "APPROVED", "body": "Thanks 👍 \n\n(I pushed small edits to tests.)", "submitted_at": "2025-11-11T19:38:10+00:00" } ], "review_comments": [ { "id": 2512102135, "user": "user_3a67c55598c5", "body": "Can you revert this? We'll clean it up when we add a formatter.", "path": "django/contrib/admin/static/admin/js/SelectFilter2.js", "line": 129, "side": "LEFT", "created_at": "2025-11-10T22:01:11+00:00" }, { "id": 2512103276, "user": "user_3a67c55598c5", "body": "Can we instead add some tests perhaps like the ones on #19394?", "path": "js_tests/admin/SelectFilter2.test.js", "line": 14, "side": "LEFT", "created_at": "2025-11-10T22:01:36+00:00" }, { "id": 2513846517, "user": "user_cad4bfff7ac8", "body": "I've created a new test that checks if the label, div selector, and add link exist, and verifies if the div selector is between the label and the add link.", "path": "js_tests/admin/SelectFilter2.test.js", "line": 14, "side": "LEFT", "created_at": "2025-11-11T11:20:32+00:00" } ], "meta": { "languages": [ "js" ], "touches_tests": true, "review_state_summary": { "COMMENTED": 2, "APPROVED": 1 }, "meaningful_comment_count": 3, "has_approval": true, "has_changes_requested": false, "total_review_comments": 3 } } { "_id": "37927d9c0812b5a0", "_schema_version": "1.0", "_cleaned_at": "2026-02-12T07:46:52.163867+00:00", "repo": "django/django", "repo_url": "https://github.com/django/django", "license_name": "BSD 3-Clause \"New\" or \"Revised\" License", "license_spdx": "BSD-3-Clause", "pr_number": 20074, "title": "Fixed #36722 -- Moved AutoFieldMixin validate_autopk_value() check to get_db_prep_save.", "body": "#### Trac ticket number\n\n\nticket-36722\n\n#### Checklist\n- [x] This PR targets the `main` branch. \n- [x] The commit message is written in past tense, mentions the ticket number, and ends with a period.\n- [x] I have checked the \"Has patch\" ticket flag in the Trac system.\n- [x] I have added or updated relevant tests.\n- [ ] I have added or updated relevant docs, including release notes if applicable.\n- [ ] I have attached screenshots in both light and dark modes for any UI changes.", "author": "user_606ba1f2b93c", "created_at": "2025-11-10T11:29:59+00:00", "merged_at": "2025-12-05T14:35:15+00:00", "base_branch": "main", "head_branch": "ticket-36722", "additions": 18, "deletions": 6, "changed_files": 2, "files": [ { "filename": "django/db/models/fields/__init__.py", "status": "modified", "additions": 8, "deletions": 4, "changes": 12, "patch": "@@ -2842,10 +2842,14 @@ def validate(self, value, model_instance):\n pass\n \n def get_db_prep_value(self, value, connection, prepared=False):\n- if not prepared:\n- value = self.get_prep_value(value)\n- value = connection.ops.validate_autopk_value(value)\n- return value\n+ return value if prepared else self.get_prep_value(value)\n+\n+ def get_db_prep_save(self, value, connection):\n+ if hasattr(value, \"as_sql\"):\n+ return value\n+ value = self.get_prep_value(value)\n+ value = connection.ops.validate_autopk_value(value)\n+ return self.get_db_prep_value(value, connection=connection, prepared=True)\n \n def contribute_to_class(self, cls, name, **kwargs):\n if cls._meta.auto_field:" }, { "filename": "tests/backends/tests.py", "status": "modified", "additions": 10, "deletions": 2, "changes": 12, "patch": "@@ -19,6 +19,7 @@\n from django.db.backends.base.base import BaseDatabaseWrapper\n from django.db.backends.signals import connection_created\n from django.db.backends.utils import CursorWrapper\n+from django.db.models import BigAutoField, Value\n from django.db.models.sql.constants import CURSOR\n from django.test import (\n TestCase,\n@@ -966,7 +967,7 @@ def test_thread_sharing_count(self):\n connection.dec_thread_sharing()\n \n \n-class MySQLPKZeroTests(TestCase):\n+class MySQLAutoPKZeroTests(TestCase):\n \"\"\"\n Zero as id for AutoField should raise exception in MySQL, because MySQL\n does not allow zero for autoincrement primary key if the\n@@ -975,8 +976,15 @@ class MySQLPKZeroTests(TestCase):\n \n [USER_REDACTED](\"allows_auto_pk_0\")\n def test_zero_as_autoval(self):\n- with self.assertRaises(ValueError):\n+ msg = \"The database backend does not accept 0 as a value for AutoField.\"\n+ with self.assertRaisesMessage(ValueError, msg):\n Square.objects.create(id=0, root=0, square=1)\n+ with self.assertRaisesMessage(ValueError, msg):\n+ Square.objects.create(id=Value(0, BigAutoField()), root=0, square=1)\n+\n+ [USER_REDACTED](\"allows_auto_pk_0\")\n+ def test_no_error_when_filtering_with_expression(self):\n+ self.assertSequenceEqual(Square.objects.filter(id=Value(0, BigAutoField())), ())\n \n \n class DBConstraintTestCase(TestCase):" } ], "reviews": [ { "id": 3443207195, "user": "user_606ba1f2b93c", "state": "COMMENTED", "body": null, "submitted_at": "2025-11-10T13:16:34+00:00" }, { "id": 3536987116, "user": "user_3a67c55598c5", "state": "COMMENTED", "body": "Thanks [USER_REDACTED] 👍", "submitted_at": "2025-12-03T21:43:11+00:00" }, { "id": 3543628087, "user": "user_606ba1f2b93c", "state": "COMMENTED", "body": null, "submitted_at": "2025-12-05T08:36:45+00:00" }, { "id": 3544818486, "user": "user_3a67c55598c5", "state": "APPROVED", "body": null, "submitted_at": "2025-12-05T13:41:15+00:00" } ], "review_comments": [ { "id": 2510541734, "user": "user_606ba1f2b93c", "body": "This was raising \"The database backend does not accept 0 as a value for AutoField\" for me on MySQL. `complex() == 0` is `True`. (`IntegerFieldTests` is subclassed by [NAME_REDACTED])", "path": "tests/model_fields/test_integerfield.py", "line": 201, "side": "LEFT", "created_at": "2025-11-10T13:16:34+00:00" }, { "id": 2586658762, "user": "user_3a67c55598c5", "body": "This no longer feeds get_prep_value() into validate_autopk_value(). Should we instead gather the result of `get_db_prep_value` and validate _that_?", "path": "django/db/models/fields/__init__.py", "line": 2851, "side": "RIGHT", "created_at": "2025-12-03T21:26:44+00:00" }, { "id": 2586706569, "user": "user_3a67c55598c5", "body": "The original test with `complex()` passes with my suggestion to validate the prepped value.", "path": "tests/model_fields/test_integerfield.py", "line": 201, "side": "LEFT", "created_at": "2025-12-03T21:43:00+00:00" }, { "id": 2591847110, "user": "user_606ba1f2b93c", "body": "Done, thanks! 🚀", "path": "django/db/models/fields/__init__.py", "line": 2851, "side": "RIGHT", "created_at": "2025-12-05T08:36:45+00:00" } ], "meta": { "languages": [ "py" ], "touches_tests": true, "review_state_summary": { "COMMENTED": 3, "APPROVED": 1 }, "meaningful_comment_count": 4, "has_approval": true, "has_changes_requested": false, "total_review_comments": 4 } } { "_id": "35a096a2ec4f7100", "_schema_version": "1.0", "_cleaned_at": "2026-02-12T07:46:52.163867+00:00", "repo": "django/django", "repo_url": "https://github.com/django/django", "license_name": "BSD 3-Clause \"New\" or \"Revised\" License", "license_spdx": "BSD-3-Clause", "pr_number": 20070, "title": "Fixed #36718 -- Added JSONField support for negative array indexing on Oracle 21c+.", "body": "ticket-36718", "author": "user_606ba1f2b93c", "created_at": "2025-11-08T15:10:34+00:00", "merged_at": "2025-11-21T10:20:12+00:00", "base_branch": "main", "head_branch": "oracle-negative-array-step", "additions": 18, "deletions": 2, "changed_files": 4, "files": [ { "filename": "django/db/backends/oracle/features.py", "status": "modified", "additions": 4, "deletions": 1, "changes": 5, "patch": "@@ -76,7 +76,6 @@ class DatabaseFeatures(BaseDatabaseFeatures):\n requires_compound_order_by_subquery = True\n allows_multiple_constraints_on_same_fields = False\n supports_json_field_contains = False\n- supports_json_negative_indexing = False\n supports_collation_on_textfield = False\n supports_on_delete_db_default = False\n supports_no_precision_decimalfield = True\n@@ -91,6 +90,10 @@ class DatabaseFeatures(BaseDatabaseFeatures):\n \"INSERT INTO {} VALUES (DEFAULT, DEFAULT, DEFAULT)\"\n )\n \n+ [USER_REDACTED]_property\n+ def supports_json_negative_indexing(self):\n+ return self.connection.oracle_version >= (21,)\n+\n [USER_REDACTED]_property\n def django_test_skips(self):\n skips = {" }, { "filename": "django/db/backends/oracle/operations.py", "status": "modified", "additions": 5, "deletions": 0, "changes": 5, "patch": "@@ -729,3 +729,8 @@ def conditional_expression_supported_in_where_clause(self, expression):\n if isinstance(expression, RawSQL) and expression.conditional:\n return True\n return False\n+\n+ def format_json_path_numeric_index(self, num):\n+ if num < 0:\n+ return \"[last-%s]\" % abs(num + 1) # Indexing is zero-based.\n+ return super().format_json_path_numeric_index(num)" }, { "filename": "docs/releases/6.1.txt", "status": "modified", "additions": 4, "deletions": 0, "changes": 4, "patch": "@@ -254,6 +254,10 @@ Models\n ` are no longer required to be\n set on Oracle, PostgreSQL, and SQLite.\n \n+* :class:`~django.db.models.JSONField` now supports\n+ :ref:`negative array indexing ` on Oracle\n+ 21c+.\n+\n Pagination\n ~~~~~~~~~~" }, { "filename": "docs/topics/db/queries.txt", "status": "modified", "additions": 5, "deletions": 1, "changes": 6, "patch": "@@ -1184,14 +1184,18 @@ directly, but you can still use dictionary unpacking to use it in a query:\n >>> Dog.objects.filter(**{\"data__owner__other_pets__-1__name\": \"Fishy\"})\n ]>\n \n-.. admonition:: MySQL, MariaDB, and Oracle\n+.. admonition:: MySQL, MariaDB, and Oracle < 21c\n \n Negative JSON array indices are not supported.\n \n .. versionchanged:: 6.0\n \n SQLite support for negative JSON array indices was added.\n \n+.. versionchanged:: 6.1\n+\n+ Oracle 21c+ support for negative JSON array indices was added.\n+\n If the key you wish to query by [NAME_REDACTED] of another lookup, use\n the :lookup:`contains ` lookup instead." } ], "reviews": [ { "id": 3489763184, "user": "user_5501cd6d3dc8", "state": "COMMENTED", "body": "[USER_REDACTED] Thanks :+1: Suggested small improvements to docs.", "submitted_at": "2025-11-20T20:19:06+00:00" }, { "id": 3491955961, "user": "user_606ba1f2b93c", "state": "COMMENTED", "body": null, "submitted_at": "2025-11-21T09:48:55+00:00" }, { "id": 3491986350, "user": "user_5501cd6d3dc8", "state": "APPROVED", "body": "[USER_REDACTED] Thanks for updates :+1:", "submitted_at": "2025-11-21T09:55:27+00:00" } ], "review_comments": [ { "id": 2547541120, "user": "user_5501cd6d3dc8", "body": "Why it is in the `Features deprecated` section? Please move it to the `Models`. We also use the present tense in release notes, e.g.\n```\n* :class:`~django.db.models.JSONField` now supports\n :ref:`negative array indexing ` on Oracle 21c+.\n```", "path": "docs/releases/6.1.txt", "line": null, "side": "RIGHT", "created_at": "2025-11-20T20:14:41+00:00" }, { "id": 2547544103, "user": "user_5501cd6d3dc8", "body": "I'd use the same wording as for `SQLite`.\n```suggestion\n Oracle 21c+ support for negative JSON array indices was added.\n```", "path": "docs/topics/db/queries.txt", "line": null, "side": "RIGHT", "created_at": "2025-11-20T20:15:45+00:00" }, { "id": 2549155542, "user": "user_606ba1f2b93c", "body": "Thanks!", "path": "docs/releases/6.1.txt", "line": null, "side": "RIGHT", "created_at": "2025-11-21T09:48:55+00:00" } ], "meta": { "languages": [ "py", "txt" ], "touches_tests": false, "review_state_summary": { "COMMENTED": 2, "APPROVED": 1 }, "meaningful_comment_count": 2, "has_approval": true, "has_changes_requested": false, "total_review_comments": 3 } } { "_id": "fc9028dfff6db7e3", "_schema_version": "1.0", "_cleaned_at": "2026-02-12T07:46:52.163867+00:00", "repo": "django/django", "repo_url": "https://github.com/django/django", "license_name": "BSD 3-Clause \"New\" or \"Revised\" License", "license_spdx": "BSD-3-Clause", "pr_number": 20067, "title": "Fixed #27380 -- Added \"raw\" argument to m2m_changed signals.", "body": "ticket-27380", "author": "user_5501cd6d3dc8", "created_at": "2025-11-07T10:02:03+00:00", "merged_at": "2025-12-17T17:37:18+00:00", "base_branch": "main", "head_branch": "issue-27380-raw", "additions": 207, "deletions": 21, "changed_files": 7, "files": [ { "filename": "django/core/serializers/base.py", "status": "modified", "additions": 2, "deletions": 2, "changes": 4, "patch": "@@ -290,11 +290,11 @@ def __repr__(self):\n def save(self, save_m2m=True, using=None, **kwargs):\n # Call save on the Model baseclass directly. This bypasses any\n # model-defined save. The save is also forced to be raw.\n- # raw=True is passed to any pre/post_save signals.\n+ # raw=True is passed to any pre/post_save and m2m_changed signals.\n models.Model.save_base(self.object, using=using, raw=True, **kwargs)\n if self.m2m_data and save_m2m:\n for accessor_name, object_list in self.m2m_data.items():\n- getattr(self.object, accessor_name).set(object_list)\n+ getattr(self.object, accessor_name).set_base(object_list, raw=True)\n \n # prevent a second (possibly accidental) call to save() from saving\n # the m2m data twice." }, { "filename": "django/db/models/fields/related_descriptors.py", "status": "modified", "additions": 57, "deletions": 16, "changes": 73, "patch": "@@ -1262,15 +1262,16 @@ def count(self):\n else:\n return super().count()\n \n- def add(self, *objs, through_defaults=None):\n- self._remove_prefetched_objects()\n- db = router.db_for_write(self.through, instance=self.instance)\n+ def _add_base(self, *objs, through_defaults=None, using=None, raw=False):\n+ db = using or router.db_for_write(self.through, instance=self.instance)\n with transaction.atomic(using=db, savepoint=False):\n self._add_items(\n self.source_field_name,\n self.target_field_name,\n *objs,\n through_defaults=through_defaults,\n+ using=db,\n+ raw=raw,\n )\n # If this is a symmetrical m2m relation to self, add the mirror\n # entry in the m2m table.\n@@ -1280,8 +1281,15 @@ def add(self, *objs, through_defaults=None):\n self.source_field_name,\n *objs,\n through_defaults=through_defaults,\n+ using=db,\n+ raw=raw,\n )\n \n+ def add(self, *objs, through_defaults=None):\n+ self._remove_prefetched_objects()\n+ db = router.db_for_write(self.through, instance=self.instance)\n+ self._add_base(*objs, through_defaults=through_defaults, using=db)\n+\n add.alters_data = True\n \n async def aadd(self, *objs, through_defaults=None):\n@@ -1291,9 +1299,16 @@ async def aadd(self, *objs, through_defaults=None):\n \n aadd.alters_data = True\n \n+ def _remove_base(self, *objs, using=None, raw=False):\n+ db = using or router.db_for_write(self.through, instance=self.instance)\n+ self._remove_items(\n+ self.source_field_name, self.target_field_name, *objs, using=db, raw=raw\n+ )\n+\n def remove(self, *objs):\n self._remove_prefetched_objects()\n- self._remove_items(self.source_field_name, self.target_field_name, *objs)\n+ db = router.db_for_write(self.through, instance=self.instance)\n+ self._remove_base(*objs, using=db)\n \n remove.alters_data = True\n \n@@ -1302,8 +1317,8 @@ async def aremove(self, *objs):\n \n aremove.alters_data = True\n \n- def clear(self):\n- db = router.db_for_write(self.through, instance=self.instance)\n+ def _clear_base(self, using=None, raw=False):\n+ db = using or router.db_for_write(self.through, instance=self.instance)\n with transaction.atomic(using=db, savepoint=False):\n signals.m2m_changed.send(\n sender=self.through,\n@@ -1313,8 +1328,8 @@ def clear(self):\n model=self.model,\n pk_set=None,\n using=db,\n+ raw=raw,\n )\n- self._remove_prefetched_objects()\n filters = self._build_remove_filters(super().get_queryset().using(db))\n self.through._default_manager.using(db).filter(filters).delete()\n \n@@ -1326,25 +1341,34 @@ def clear(self):\n model=self.model,\n pk_set=None,\n using=db,\n+ raw=raw,\n )\n \n+ def clear(self):\n+ self._remove_prefetched_objects()\n+ db = router.db_for_write(self.through, instance=self.instance)\n+ self._clear_base(using=db)\n+\n clear.alters_data = True\n \n async def aclear(self):\n return await sync_to_async(self.clear)()\n \n aclear.alters_data = True\n \n- def set(self, objs, *, clear=False, through_defaults=None):\n+ def set_base(self, objs, *, clear=False, through_defaults=None, raw=False):\n # Force evaluation of `objs` in case it's a queryset whose value\n # could be affected by `manager.clear()`. Refs #19816.\n objs = tuple(objs)\n \n db = router.db_for_write(self.through, instance=self.instance)\n with transaction.atomic(using=db, savepoint=False):\n+ self._remove_prefetched_objects()\n if clear:\n- self.clear()\n- self.add(*objs, through_defaults=through_defaults)\n+ self._clear_base(using=db, raw=raw)\n+ self._add_base(\n+ *objs, through_defaults=through_defaults, using=db, raw=raw\n+ )\n else:\n old_ids = set(\n self.using(db).values_list(\n@@ -1364,8 +1388,13 @@ def set(self, objs, *, clear=False, through_defaults=None):\n else:\n new_objs.append(obj)\n \n- self.remove(*old_ids)\n- self.add(*new_objs, through_defaults=through_defaults)\n+ self._remove_base(*old_ids, using=db, raw=raw)\n+ self._add_base(\n+ *new_objs, through_defaults=through_defaults, using=db, raw=raw\n+ )\n+\n+ def set(self, objs, *, clear=False, through_defaults=None):\n+ self.set_base(objs, clear=clear, through_defaults=through_defaults)\n \n set.alters_data = True\n \n@@ -1516,7 +1545,13 @@ def _get_add_plan(self, db, source_field_name):\n )\n \n def _add_items(\n- self, source_field_name, target_field_name, *objs, through_defaults=None\n+ self,\n+ source_field_name,\n+ target_field_name,\n+ *objs,\n+ through_defaults=None,\n+ using=None,\n+ raw=False,\n ):\n # source_field_name: the PK fieldname in join table for the source\n # object target_field_name: the PK fieldname in join table for the\n@@ -1527,7 +1562,7 @@ def _add_items(\n \n through_defaults = dict(resolve_callables(through_defaults or {}))\n target_ids = self._get_target_ids(target_field_name, objs)\n- db = router.db_for_write(self.through, instance=self.instance)\n+ db = using or router.db_for_write(self.through, instance=self.instance)\n can_ignore_conflicts, must_send_signals, can_fast_add = self._get_add_plan(\n db, source_field_name\n )\n@@ -1559,6 +1594,7 @@ def _add_items(\n model=self.model,\n pk_set=missing_target_ids,\n using=db,\n+ raw=raw,\n )\n # Add the ones that aren't there already.\n self.through._default_manager.using(db).bulk_create(\n@@ -1584,9 +1620,12 @@ def _add_items(\n model=self.model,\n pk_set=missing_target_ids,\n using=db,\n+ raw=raw,\n )\n \n- def _remove_items(self, source_field_name, target_field_name, *objs):\n+ def _remove_items(\n+ self, source_field_name, target_field_name, *objs, using=None, raw=False\n+ ):\n # source_field_name: the PK colname in join table for the source\n # object target_field_name: the PK colname in join table for the\n # target object *objs - objects to remove. Either object instances,\n@@ -1603,7 +1642,7 @@ def _remove_items(self, source_field_name, target_field_name, *objs):\n else:\n old_ids.add(obj)\n \n- db = router.db_for_write(self.through, instance=self.instance)\n+ db = using or router.db_for_write(self.through, instance=self.instance)\n with transaction.atomic(using=db, savepoint=False):\n # Send a signal to the other end if need be.\n signals.m2m_changed.send(\n@@ -1614,6 +1653,7 @@ def _remove_items(self, source_field_name, target_field_name, *objs):\n model=self.model,\n pk_set=old_ids,\n using=db,\n+ raw=raw,\n )\n target_model_qs = super().get_queryset()\n if target_model_qs._has_filters():\n@@ -1633,6 +1673,7 @@ def _remove_items(self, source_field_name, target_field_name, *objs):\n model=self.model,\n pk_set=old_ids,\n using=db,\n+ raw=raw,\n )\n \n return ManyRelatedManager" }, { "filename": "docs/ref/signals.txt", "status": "modified", "additions": 13, "deletions": 0, "changes": 13, "patch": "@@ -303,6 +303,15 @@ Arguments sent with this signal:\n ``using``\n The database alias being used.\n \n+``raw``\n+\n+ .. versionadded:: 6.1\n+\n+ A boolean; ``True`` if the model is saved exactly as presented\n+ (i.e. when loading a :ref:`fixture `). One should not\n+ query/modify other records in the database as the database might not be in\n+ a consistent state yet.\n+\n For example, if a ``Pizza`` can have multiple ``Topping`` objects, modeled\n like this::\n \n@@ -357,6 +366,8 @@ [NAME_REDACTED]\n ``pk_set`` ``{t.id}`` (since only ``Topping t`` was added to the relation)\n \n ``using`` ``\"default\"`` (since the default router sends writes here)\n+\n+``raw`` ``False`` (since it is not loaded from a fixture)\n ============== ============================================================\n \n And if we would then do something like this:\n@@ -387,6 +398,8 @@ [NAME_REDACTED]\n relation)\n \n ``using`` ``\"default\"`` (since the default router sends writes here)\n+\n+``raw`` ``False`` (since it is not loaded from a fixture)\n ============== ============================================================\n \n ``class_prepared``" }, { "filename": "docs/releases/6.1.txt", "status": "modified", "additions": 4, "deletions": 0, "changes": 4, "patch": "@@ -237,6 +237,10 @@ [NAME_REDACTED]\n ``suggest_on_error`` argument to ``True`` by [NAME_REDACTED] 3.14, enabling\n suggestions for mistyped subcommand names and argument choices.\n \n+* The :djadmin:`loaddata` command now calls\n+ :data:`~django.db.models.signals.m2m_changed` signals with ``raw=True`` when\n+ loading fixtures.\n+\n Migrations\n ~~~~~~~~~~" }, { "filename": "docs/topics/db/fixtures.txt", "status": "modified", "additions": 7, "deletions": 2, "changes": 9, "patch": "@@ -118,8 +118,9 @@ How fixtures are saved to the database\n \n When fixture files are processed, the data is saved to the database as is.\n Model defined :meth:`~django.db.models.Model.save` methods are not called, and\n-any :data:`~django.db.models.signals.pre_save` or\n-:data:`~django.db.models.signals.post_save` signals will be called with\n+any :data:`~django.db.models.signals.pre_save`,\n+:data:`~django.db.models.signals.post_save`, or\n+:data:`~django.db.models.signals.m2m_changed` signals will be called with\n ``raw=True`` since the instance only contains attributes that are local to the\n model. You may, for example, want to disable handlers that access\n related fields that aren't present during fixture loading and would otherwise\n@@ -163,6 +164,10 @@ You could also write a decorator to encapsulate this logic::\n Just be aware that this logic will disable the signals whenever fixtures are\n deserialized, not just during :djadmin:`loaddata`.\n \n+.. versionchanged:: 6.1\n+\n+ The ``raw`` argument was added to ``m2m_changed`` signals.\n+\n Compressed fixtures\n ===================" }, { "filename": "tests/m2m_signals/tests.py", "status": "modified", "additions": 123, "deletions": 0, "changes": 123, "patch": "@@ -35,6 +35,7 @@ def m2m_changed_signal_receiver(self, signal, sender, **kwargs):\n \"action\": kwargs[\"action\"],\n \"reverse\": kwargs[\"reverse\"],\n \"model\": kwargs[\"model\"],\n+ \"raw\": kwargs[\"raw\"],\n }\n if kwargs[\"pk_set\"]:\n message[\"objects\"] = list(\n@@ -114,6 +115,7 @@ def test_m2m_relations_add_remove_clear(self):\n \"action\": \"pre_add\",\n \"reverse\": False,\n \"model\": Part,\n+ \"raw\": False,\n \"objects\": [self.doors, self.engine, self.wheelset],\n }\n )\n@@ -123,6 +125,7 @@ def test_m2m_relations_add_remove_clear(self):\n \"action\": \"post_add\",\n \"reverse\": False,\n \"model\": Part,\n+ \"raw\": False,\n \"objects\": [self.doors, self.engine, self.wheelset],\n }\n )\n@@ -136,6 +139,7 @@ def test_m2m_relations_add_remove_clear(self):\n \"action\": \"pre_add\",\n \"reverse\": True,\n \"model\": Car,\n+ \"raw\": False,\n \"objects\": [self.bmw, self.toyota],\n }\n )\n@@ -145,6 +149,7 @@ def test_m2m_relations_add_remove_clear(self):\n \"action\": \"post_add\",\n \"reverse\": True,\n \"model\": Car,\n+ \"raw\": False,\n \"objects\": [self.bmw, self.toyota],\n }\n )\n@@ -163,13 +168,15 @@ def test_m2m_relations_signals_remove_relation(self):\n \"action\": \"pre_remove\",\n \"reverse\": False,\n \"model\": Part,\n+ \"raw\": False,\n \"objects\": [self.airbag, self.engine],\n },\n {\n \"instance\": self.vw,\n \"action\": \"post_remove\",\n \"reverse\": False,\n \"model\": Part,\n+ \"raw\": False,\n \"objects\": [self.airbag, self.engine],\n },\n ],\n@@ -188,6 +195,7 @@ def test_m2m_relations_signals_give_the_self_vw_some_optional_parts(self):\n \"action\": \"pre_add\",\n \"reverse\": False,\n \"model\": Part,\n+ \"raw\": False,\n \"objects\": [self.airbag, self.sunroof],\n }\n )\n@@ -197,6 +205,7 @@ def test_m2m_relations_signals_give_the_self_vw_some_optional_parts(self):\n \"action\": \"post_add\",\n \"reverse\": False,\n \"model\": Part,\n+ \"raw\": False,\n \"objects\": [self.airbag, self.sunroof],\n }\n )\n@@ -210,6 +219,7 @@ def test_m2m_relations_signals_give_the_self_vw_some_optional_parts(self):\n \"action\": \"pre_add\",\n \"reverse\": True,\n \"model\": Car,\n+ \"raw\": False,\n \"objects\": [self.bmw, self.toyota],\n }\n )\n@@ -219,6 +229,7 @@ def test_m2m_relations_signals_give_the_self_vw_some_optional_parts(self):\n \"action\": \"post_add\",\n \"reverse\": True,\n \"model\": Car,\n+ \"raw\": False,\n \"objects\": [self.bmw, self.toyota],\n }\n )\n@@ -237,13 +248,15 @@ def test_m2m_relations_signals_reverse_relation_with_custom_related_name(self):\n \"action\": \"pre_remove\",\n \"reverse\": True,\n \"model\": Car,\n+ \"raw\": False,\n \"objects\": [self.vw],\n },\n {\n \"instance\": self.airbag,\n \"action\": \"post_remove\",\n \"reverse\": True,\n \"model\": Car,\n+ \"raw\": False,\n \"objects\": [self.vw],\n },\n ],\n@@ -261,12 +274,14 @@ def test_m2m_relations_signals_clear_all_parts_of_the_self_vw(self):\n \"action\": \"pre_clear\",\n \"reverse\": False,\n \"model\": Part,\n+ \"raw\": False,\n },\n {\n \"instance\": self.vw,\n \"action\": \"post_clear\",\n \"reverse\": False,\n \"model\": Part,\n+ \"raw\": False,\n },\n ],\n )\n@@ -283,12 +298,14 @@ def test_m2m_relations_signals_all_the_doors_off_of_cars(self):\n \"action\": \"pre_clear\",\n \"reverse\": True,\n \"model\": Car,\n+ \"raw\": False,\n },\n {\n \"instance\": self.doors,\n \"action\": \"post_clear\",\n \"reverse\": True,\n \"model\": Car,\n+ \"raw\": False,\n },\n ],\n )\n@@ -306,12 +323,14 @@ def test_m2m_relations_signals_reverse_relation(self):\n \"action\": \"pre_clear\",\n \"reverse\": True,\n \"model\": Car,\n+ \"raw\": False,\n },\n {\n \"instance\": self.airbag,\n \"action\": \"post_clear\",\n \"reverse\": True,\n \"model\": Car,\n+ \"raw\": False,\n },\n ],\n )\n@@ -330,6 +349,7 @@ def test_m2m_relations_signals_alternative_ways(self):\n \"action\": \"pre_add\",\n \"reverse\": False,\n \"model\": Part,\n+ \"raw\": False,\n \"objects\": [p6],\n }\n )\n@@ -339,6 +359,7 @@ def test_m2m_relations_signals_alternative_ways(self):\n \"action\": \"post_add\",\n \"reverse\": False,\n \"model\": Part,\n+ \"raw\": False,\n \"objects\": [p6],\n }\n )\n@@ -352,6 +373,7 @@ def test_m2m_relations_signals_alternative_ways(self):\n \"action\": \"pre_remove\",\n \"reverse\": False,\n \"model\": Part,\n+ \"raw\": False,\n \"objects\": [p6],\n }\n )\n@@ -361,6 +383,7 @@ def test_m2m_relations_signals_alternative_ways(self):\n \"action\": \"post_remove\",\n \"reverse\": False,\n \"model\": Part,\n+ \"raw\": False,\n \"objects\": [p6],\n }\n )\n@@ -370,6 +393,7 @@ def test_m2m_relations_signals_alternative_ways(self):\n \"action\": \"pre_add\",\n \"reverse\": False,\n \"model\": Part,\n+ \"raw\": False,\n \"objects\": [self.doors, self.engine, self.wheelset],\n }\n )\n@@ -379,6 +403,7 @@ def test_m2m_relations_signals_alternative_ways(self):\n \"action\": \"post_add\",\n \"reverse\": False,\n \"model\": Part,\n+ \"raw\": False,\n \"objects\": [self.doors, self.engine, self.wheelset],\n }\n )\n@@ -397,6 +422,7 @@ def test_m2m_relations_signals_clearing_removing(self):\n \"action\": \"pre_clear\",\n \"reverse\": False,\n \"model\": Part,\n+ \"raw\": False,\n }\n )\n expected_messages.append(\n@@ -405,6 +431,7 @@ def test_m2m_relations_signals_clearing_removing(self):\n \"action\": \"post_clear\",\n \"reverse\": False,\n \"model\": Part,\n+ \"raw\": False,\n }\n )\n expected_messages.append(\n@@ -413,6 +440,7 @@ def test_m2m_relations_signals_clearing_removing(self):\n \"action\": \"pre_add\",\n \"reverse\": False,\n \"model\": Part,\n+ \"raw\": False,\n \"objects\": [self.doors, self.engine, self.wheelset],\n }\n )\n@@ -422,6 +450,7 @@ def test_m2m_relations_signals_clearing_removing(self):\n \"action\": \"post_add\",\n \"reverse\": False,\n \"model\": Part,\n+ \"raw\": False,\n \"objects\": [self.doors, self.engine, self.wheelset],\n }\n )\n@@ -435,6 +464,7 @@ def test_m2m_relations_signals_clearing_removing(self):\n \"action\": \"pre_remove\",\n \"reverse\": False,\n \"model\": Part,\n+ \"raw\": False,\n \"objects\": [self.engine],\n }\n )\n@@ -444,6 +474,7 @@ def test_m2m_relations_signals_clearing_removing(self):\n \"action\": \"post_remove\",\n \"reverse\": False,\n \"model\": Part,\n+ \"raw\": False,\n \"objects\": [self.engine],\n }\n )\n@@ -464,6 +495,7 @@ def test_m2m_relations_signals_when_inheritance(self):\n \"action\": \"pre_add\",\n \"reverse\": False,\n \"model\": Part,\n+ \"raw\": False,\n \"objects\": [self.doors],\n }\n )\n@@ -473,6 +505,7 @@ def test_m2m_relations_signals_when_inheritance(self):\n \"action\": \"post_add\",\n \"reverse\": False,\n \"model\": Part,\n+ \"raw\": False,\n \"objects\": [self.doors],\n }\n )\n@@ -485,6 +518,7 @@ def test_m2m_relations_signals_when_inheritance(self):\n \"action\": \"pre_add\",\n \"reverse\": True,\n \"model\": Car,\n+ \"raw\": False,\n \"objects\": [c4b],\n }\n )\n@@ -494,6 +528,7 @@ def test_m2m_relations_signals_when_inheritance(self):\n \"action\": \"post_add\",\n \"reverse\": True,\n \"model\": Car,\n+ \"raw\": False,\n \"objects\": [c4b],\n }\n )\n@@ -519,13 +554,15 @@ def test_m2m_relations_with_self_add_friends(self):\n \"action\": \"pre_add\",\n \"reverse\": False,\n \"model\": Person,\n+ \"raw\": False,\n \"objects\": [self.bob, self.chuck],\n },\n {\n \"instance\": self.alice,\n \"action\": \"post_add\",\n \"reverse\": False,\n \"model\": Person,\n+ \"raw\": False,\n \"objects\": [self.bob, self.chuck],\n },\n ],\n@@ -542,13 +579,15 @@ def test_m2m_relations_with_self_add_fan(self):\n \"action\": \"pre_add\",\n \"reverse\": False,\n \"model\": Person,\n+ \"raw\": False,\n \"objects\": [self.daisy],\n },\n {\n \"instance\": self.alice,\n \"action\": \"post_add\",\n \"reverse\": False,\n \"model\": Person,\n+ \"raw\": False,\n \"objects\": [self.daisy],\n },\n ],\n@@ -565,13 +604,97 @@ def test_m2m_relations_with_self_add_idols(self):\n \"action\": \"pre_add\",\n \"reverse\": True,\n \"model\": Person,\n+ \"raw\": False,\n \"objects\": [self.alice, self.bob],\n },\n {\n \"instance\": self.chuck,\n \"action\": \"post_add\",\n \"reverse\": True,\n \"model\": Person,\n+ \"raw\": False,\n+ \"objects\": [self.alice, self.bob],\n+ },\n+ ],\n+ )\n+\n+ def test_m2m_relations_set_base_raw(self):\n+ self.chuck.idols.add(self.daisy)\n+ self._initialize_signal_person()\n+ self.chuck.idols.set_base([self.alice, self.bob], raw=True)\n+ self.assertEqual(\n+ self.m2m_changed_messages,\n+ [\n+ {\n+ \"instance\": self.chuck,\n+ \"action\": \"pre_remove\",\n+ \"reverse\": True,\n+ \"model\": Person,\n+ \"raw\": True,\n+ \"objects\": [self.daisy],\n+ },\n+ {\n+ \"instance\": self.chuck,\n+ \"action\": \"post_remove\",\n+ \"reverse\": True,\n+ \"model\": Person,\n+ \"raw\": True,\n+ \"objects\": [self.daisy],\n+ },\n+ {\n+ \"instance\": self.chuck,\n+ \"action\": \"pre_add\",\n+ \"reverse\": True,\n+ \"model\": Person,\n+ \"raw\": True,\n+ \"objects\": [self.alice, self.bob],\n+ },\n+ {\n+ \"instance\": self.chuck,\n+ \"action\": \"post_add\",\n+ \"reverse\": True,\n+ \"model\": Person,\n+ \"raw\": True,\n+ \"objects\": [self.alice, self.bob],\n+ },\n+ ],\n+ )\n+\n+ def test_m2m_relations_set_base_raw_clear(self):\n+ self.chuck.idols.set([self.daisy, self.bob])\n+ self._initialize_signal_person()\n+ self.chuck.idols.set_base([self.alice, self.bob], clear=True, raw=True)\n+ self.assertEqual(\n+ self.m2m_changed_messages,\n+ [\n+ {\n+ \"instance\": self.chuck,\n+ \"action\": \"pre_clear\",\n+ \"reverse\": True,\n+ \"model\": Person,\n+ \"raw\": True,\n+ },\n+ {\n+ \"instance\": self.chuck,\n+ \"action\": \"post_clear\",\n+ \"reverse\": True,\n+ \"model\": Person,\n+ \"raw\": True,\n+ },\n+ {\n+ \"instance\": self.chuck,\n+ \"action\": \"pre_add\",\n+ \"reverse\": True,\n+ \"model\": Person,\n+ \"raw\": True,\n+ \"objects\": [self.alice, self.bob],\n+ },\n+ {\n+ \"instance\": self.chuck,\n+ \"action\": \"post_add\",\n+ \"reverse\": True,\n+ \"model\": Person,\n+ \"raw\": True,\n \"objects\": [self.alice, self.bob],\n },\n ]," }, { "filename": "tests/serializers/test_data.py", "status": "modified", "additions": 1, "deletions": 1, "changes": 2, "patch": "@@ -112,7 +112,7 @@ def fk_create(pk, klass, data):\n def m2m_create(pk, klass, data):\n instance = klass(id=pk)\n models.Model.save_base(instance, raw=True)\n- instance.data.set(data)\n+ instance.data.set_base(data, raw=True)\n return [instance]" } ], "reviews": [ { "id": 3584896071, "user": "user_3a67c55598c5", "state": "COMMENTED", "body": "Thanks 👍", "submitted_at": "2025-12-16T21:06:25+00:00" }, { "id": 3588555645, "user": "user_5501cd6d3dc8", "state": "COMMENTED", "body": null, "submitted_at": "2025-12-17T16:25:56+00:00" }, { "id": 3588574111, "user": "user_5501cd6d3dc8", "state": "COMMENTED", "body": null, "submitted_at": "2025-12-17T16:30:21+00:00" }, { "id": 3588660350, "user": "user_3a67c55598c5", "state": "APPROVED", "body": "Separate commits make sense to me!", "submitted_at": "2025-12-17T16:51:18+00:00" }, { "id": 3590022434, "user": "user_8fc305198eb3", "state": "COMMENTED", "body": "Nicely done.", "submitted_at": "2025-12-17T23:14:02+00:00" } ], "review_comments": [ { "id": 2624700249, "user": "user_3a67c55598c5", "body": "I take it you prefer the explicitness of doing this here versus relying on the `or ...` in `_add_base()`?", "path": "django/db/models/fields/related_descriptors.py", "line": 1290, "side": "RIGHT", "created_at": "2025-12-16T20:53:09+00:00" }, { "id": 2624738674, "user": "user_3a67c55598c5", "body": "I think for consistency we should add `raw` to the tables below (\"the arguments sent ... would be:\")", "path": "docs/ref/signals.txt", "line": 313, "side": "RIGHT", "created_at": "2025-12-16T21:05:18+00:00" }, { "id": 2627735369, "user": "user_5501cd6d3dc8", "body": "Good catch :dart: Added.", "path": "docs/ref/signals.txt", "line": 313, "side": "RIGHT", "created_at": "2025-12-17T16:25:56+00:00" }, { "id": 2627751636, "user": "user_5501cd6d3dc8", "body": "I wanted to keep all hook consistent also with other related descriptors.", "path": "django/db/models/fields/related_descriptors.py", "line": 1290, "side": "RIGHT", "created_at": "2025-12-17T16:30:21+00:00" }, { "id": 2628939061, "user": "user_8fc305198eb3", "body": "Shouldn't there also be a release note like \"The `m2m_changed` signal now supports a `raw` argument.\" ?", "path": "docs/releases/6.1.txt", "line": 242, "side": "RIGHT", "created_at": "2025-12-17T23:13:40+00:00" } ], "meta": { "languages": [ "py", "txt" ], "touches_tests": true, "review_state_summary": { "COMMENTED": 4, "APPROVED": 1 }, "meaningful_comment_count": 5, "has_approval": true, "has_changes_requested": false, "total_review_comments": 5 } } { "_id": "2bbdad344858914f", "_schema_version": "1.0", "_cleaned_at": "2026-02-12T07:46:52.163867+00:00", "repo": "tiangolo/fastapi", "repo_url": "https://github.com/fastapi/fastapi", "license_name": "MIT License", "license_spdx": "MIT", "pr_number": 13371, "title": "🌐 Add Ukrainian translation for `docs/uk/docs/tutorial/testing.md`", "body": null, "author": "user_c36c155012b4", "created_at": "2025-02-14T04:00:54+00:00", "merged_at": "2025-02-28T14:12:19+00:00", "base_branch": "master", "head_branch": "translation-uk/testing", "additions": 240, "deletions": 0, "changed_files": 1, "files": [ { "filename": "docs/uk/docs/tutorial/testing.md", "status": "added", "additions": 240, "deletions": 0, "changes": 240, "patch": "@@ -0,0 +1,240 @@\n+# Тестування\n+\n+Тестування **FastAPI** додатків є простим та ефективним завдяки бібліотеці
      Starlette, яка базується на HTTPX.\n+Оскільки HTTPX розроблений на основі Requests, його API є інтуїтивно зрозумілим для тих, хто вже знайомий з Requests.\n+\n+З його допомогою Ви можете використовувати pytest безпосередньо з **FastAPI**.\n+\n+## Використання `TestClient`\n+\n+/// info | Інформація\n+\n+Щоб використовувати `TestClient`, спочатку встановіть `httpx`.\n+\n+Переконайтеся, що Ви створили [віртуальне середовище](../virtual-environments.md){.internal-link target=_blank}, активували його, а потім встановили саму бібліотеку, наприклад:\n+\n+```console\n+$ pip install httpx\n+```\n+\n+///\n+\n+Імпортуйте `TestClient`.\n+\n+Створіть `TestClient`, передавши йому Ваш застосунок **FastAPI**.\n+\n+Створюйте функції з іменами, що починаються з `test_` (це стандартна угода для `pytest`).\n+\n+Використовуйте об'єкт `TestClient` так само як і `httpx`.\n+\n+Записуйте прості `assert`-вирази зі стандартними виразами Python, які потрібно перевірити (це також стандарт для `pytest`).\n+\n+{* ../../docs_src/app_testing/tutorial001.py hl[2,12,15:18] *}\n+\n+\n+/// tip | Порада\n+\n+Зверніть увагу, що тестові функції — це звичайні `def`, а не `async def`.\n+\n+Виклики клієнта також звичайні, без використання `await`.\n+\n+Це дозволяє використовувати `pytest` без зайвих ускладнень.\n+\n+///\n+\n+/// note | Технічні деталі\n+\n+Ви також можете використовувати `from starlette.testclient import TestClient`.\n+\n+**FastAPI** надає той самий `starlette.testclient` під назвою `fastapi.testclient` для зручності розробників, але він безпосередньо походить із Starlette.\n+\n+///\n+\n+/// tip | Порада\n+\n+Якщо Вам потрібно викликати `async`-функції у ваших тестах, окрім відправлення запитів до FastAPI-застосунку (наприклад, асинхронні функції роботи з базою даних), перегляньте [Асинхронні тести](../advanced/async-tests.md){.internal-link target=_blank} у розширеному керівництві.\n+\n+///\n+\n+## Розділення тестів\n+\n+У реальному застосунку Ваші тести, ймовірно, будуть в окремому файлі.\n+\n+Також Ваш **FastAPI**-застосунок може складатися з кількох файлів або модулів тощо.\n+\n+### Файл застосунку **FastAPI**\n+\n+Припустимо, у Вас є структура файлів, описана в розділі [Більші застосунки](bigger-applications.md){.internal-link target=_blank}:\n+\n+```\n+.\n+├── app\n+│   ├── __init__.py\n+│   └── main.py\n+```\n+У файлі `main.py` знаходиться Ваш застосунок **FastAPI** :\n+\n+{* ../../docs_src/app_testing/main.py *}\n+\n+### Файл тестування\n+\n+Ви можете створити файл `test_main.py` з Вашими тестами. Він може знаходитися в тому ж пакеті Python (у тій самій директорії з файлом `__init__.py`):\n+\n+\n+``` hl_lines=\"5\"\n+.\n+├── app\n+│   ├── __init__.py\n+│   ├── main.py\n+│   └── test_main.py\n+```\n+\n+Оскільки цей файл знаходиться в тому ж пакеті, Ви можете використовувати відносний імпорт, щоб імпортувати об'єкт `app` із модуля `main` (`main.py`):\n+\n+{* ../../docs_src/app_testing/test_main.py hl[3] *}\n+\n+\n+...і написати код для тестів так само як і раніше.\n+\n+## Тестування: розширений приклад\n+\n+Тепер розширимо цей приклад і додамо більше деталей, щоб побачити, як тестувати різні частини.\n+\n+### Розширений файл застосунку **FastAPI**\n+\n+Залишимо ту саму структуру файлів:\n+\n+```\n+.\n+├── app\n+│   ├── __init__.py\n+│   ├── main.py\n+│   └── test_main.py\n+```\n+\n+Припустимо, що тепер файл `main.py` із Вашим **FastAPI**-застосунком містить додаткові операції шляху (**path operations**).\n+\n+Він має `GET`-операцію, яка може повертати помилку.\n+\n+Він має `POST`-операцію, яка може повертати кілька помилок.\n+\n+Обидві операції шляху вимагають заголовок `X-Token`.\n+\n+//// tab | Python 3.10+\n+\n+```Python\n+{!> ../../docs_src/app_testing/app_b_an_py310/main.py!}\n+```\n+\n+////\n+\n+//// tab | Python 3.9+\n+\n+```Python\n+{!> ../../docs_src/app_testing/app_b_an_py39/main.py!}\n+```\n+\n+////\n+\n+//// tab | Python 3.8+\n+\n+```Python\n+{!> ../../docs_src/app_testing/app_b_an/main.py!}\n+```\n+\n+////\n+\n+//// tab | Python 3.10+ non-Annotated\n+\n+/// tip | Порада\n+\n+Бажано використовувати версію з `Annotated`, якщо це можливо\n+\n+///\n+\n+```Python\n+{!> ../../docs_src/app_testing/app_b_py310/main.py!}\n+```\n+\n+////\n+\n+//// tab | Python 3.8+ non-Annotated\n+\n+/// tip | Порада\n+\n+Бажано використовувати версію з `Annotated`, якщо це можливо\n+\n+///\n+\n+```Python\n+{!> ../../docs_src/app_testing/app_b/main.py!}\n+```\n+\n+////\n+\n+### Розширений тестовий файл\n+\n+Потім Ви можете оновити `test_main.py`, додавши розширені тести:\n+\n+{* ../../docs_src/app_testing/app_b/test_main.py *}\n+\n+Коли Вам потрібно передати клієнту інформацію в запиті, але Ви не знаєте, як це зробити, Ви можете пошукати (наприклад, у Google) спосіб реалізації в `httpx`, або навіть у `requests`, оскільки HTTPX розроблений на основі дизайну Requests.\n+\n+Далі Ви просто повторюєте ці ж дії у ваших тестах.\n+\n+Наприклад:\n+\n+* Щоб передати *path* або *query* параметр, додайте його безпосередньо до URL.\n+* Щоб передати тіло JSON, передайте Python-об'єкт (наприклад, `dict`) у параметр `json`.\n+* Якщо потрібно надіслати *[NAME_REDACTED]* замість JSON, використовуйте параметр `data`.\n+* Щоб передати заголовки *headers*, використовуйте `dict` у параметрі `headers`.\n+* Для *cookies* використовуйте `dict` у параметрі `cookies`.\n+\n+Докладніше про передачу даних у бекенд (за допомогою `httpx` або `TestClient`) можна знайти в документації HTTPX.\n+\n+/// info | Інформація\n+\n+Зверніть увагу, що `TestClient` отримує дані, які можна конвертувати в JSON, а не Pydantic-моделі.\n+Якщо у Вас є Pydantic-модель у тесті, і Ви хочете передати її дані в додаток під час тестування, Ви можете використати `jsonable_encoder`, описаний у розділі [JSON [NAME_REDACTED]](encoder.md){.internal-link target=_blank}.\n+\n+///\n+\n+## Запуск тестів\n+\n+Після цього вам потрібно встановити `pytest`.\n+\n+Переконайтеся, що Ви створили [віртуальне середовище]{.internal-link target=_blank}, активували його і встановили необхідні пакети, наприклад:\n+\n+
      \n+\n+```console\n+$ pip install pytest\n+\n+---> 100%\n+```\n+\n+
      \n+\n+`pytest` автоматично знайде файли з тестами, виконає їх і надасть вам результати.\n+\n+Запустіть тести за допомогою:\n+\n+
      \n+\n+```console\n+$ pytest\n+\n+================ test session starts ================\n+platform linux -- Python 3.6.9, pytest-5.3.5, py-1.8.1, pluggy-0.13.1\n+rootdir: /home/user/code/superawesome-cli/app\n+plugins: forked-1.1.3, xdist-1.31.0, cov-2.8.1\n+collected 6 items\n+\n+---> 100%\n+\n+test_main.py ...... [100%]\n+\n+================= 1 passed in 0.03s =================\n+```\n+\n+
      " } ], "reviews": [ { "id": 2616939094, "user": "user_787e19aded2a", "state": "APPROVED", "body": null, "submitted_at": "2025-02-14T07:22:07+00:00" }, { "id": 2624988175, "user": "user_9ee0ae83e609", "state": "CHANGES_REQUESTED", "body": null, "submitted_at": "2025-02-18T20:47:43+00:00" }, { "id": 2627860674, "user": "user_9ee0ae83e609", "state": "APPROVED", "body": null, "submitted_at": "2025-02-19T20:02:21+00:00" }, { "id": 2637654037, "user": "user_84458f05cf3c", "state": "COMMENTED", "body": "Looking good from a structural point of view! Only found one case where `tip` got translated directly by accident.", "submitted_at": "2025-02-24T16:00:56+00:00" }, { "id": 2637707699, "user": "user_c36c155012b4", "state": "COMMENTED", "body": null, "submitted_at": "2025-02-24T16:18:08+00:00" }, { "id": 2650869484, "user": "user_2a237e38e06b", "state": "APPROVED", "body": "Great, thank you [USER_REDACTED]! :cake: \n\nAnd thanks for the reviews [USER_REDACTED], [USER_REDACTED], [USER_REDACTED] :coffee:", "submitted_at": "2025-02-28T14:11:38+00:00" } ], "review_comments": [ { "id": 1960564612, "user": "user_9ee0ae83e609", "body": "```suggestion\nЗ його допомогою Ви можете використовувати pytest безпосередньо з **FastAPI**.\n```", "path": "docs/uk/docs/tutorial/testing.md", "line": null, "side": "RIGHT", "created_at": "2025-02-18T20:42:57+00:00" }, { "id": 1960564820, "user": "user_9ee0ae83e609", "body": "```suggestion\nПереконайтеся, що Ви створили [віртуальне середовище](../virtual-environments.md){.internal-link target=_blank}, активували його, а потім встановили саму бібліотеку, наприклад:\n```", "path": "docs/uk/docs/tutorial/testing.md", "line": null, "side": "RIGHT", "created_at": "2025-02-18T20:43:10+00:00" }, { "id": 1960565214, "user": "user_9ee0ae83e609", "body": "```suggestion\nСтворіть `TestClient`, передавши йому Ваш застосунок **FastAPI**.\n```", "path": "docs/uk/docs/tutorial/testing.md", "line": null, "side": "RIGHT", "created_at": "2025-02-18T20:43:29+00:00" }, { "id": 1960566017, "user": "user_9ee0ae83e609", "body": "```suggestion\nЯкщо Вам потрібно викликати `async`-функції у ваших тестах, окрім відправлення запитів до FastAPI-застосунку (наприклад, асинхронні функції роботи з базою даних), перегляньте [Асинхронні тести](../advanced/async-tests.md){.internal-link target=_blank} у розширеному керівництві.\n```", "path": "docs/uk/docs/tutorial/testing.md", "line": null, "side": "RIGHT", "created_at": "2025-02-18T20:44:11+00:00" }, { "id": 1960566323, "user": "user_9ee0ae83e609", "body": "```suggestion\nУ реальному застосунку Ваші тести, ймовірно, будуть в окремому файлі.\n```", "path": "docs/uk/docs/tutorial/testing.md", "line": null, "side": "RIGHT", "created_at": "2025-02-18T20:44:27+00:00" }, { "id": 1960566485, "user": "user_9ee0ae83e609", "body": "```suggestion\nТакож Ваш **FastAPI**-застосунок може складатися з кількох файлів або модулів тощо.\n```", "path": "docs/uk/docs/tutorial/testing.md", "line": null, "side": "RIGHT", "created_at": "2025-02-18T20:44:36+00:00" }, { "id": 1960566677, "user": "user_9ee0ae83e609", "body": "```suggestion\nПрипустимо, у Вас є структура файлів, описана в розділі [Більші застосунки](bigger-applications.md){.internal-link target=_blank}:\n```", "path": "docs/uk/docs/tutorial/testing.md", "line": null, "side": "RIGHT", "created_at": "2025-02-18T20:44:46+00:00" }, { "id": 1960566859, "user": "user_9ee0ae83e609", "body": "```suggestion\nУ файлі `main.py` знаходиться Ваш застосунок **FastAPI** :\n```", "path": "docs/uk/docs/tutorial/testing.md", "line": null, "side": "RIGHT", "created_at": "2025-02-18T20:44:57+00:00" }, { "id": 1960567263, "user": "user_9ee0ae83e609", "body": "```suggestion\nОскільки цей файл знаходиться в тому ж пакеті, Ви можете використовувати відносний імпорт, щоб імпортувати об'єкт `app` із модуля `main` (`main.py`):\n```", "path": "docs/uk/docs/tutorial/testing.md", "line": null, "side": "RIGHT", "created_at": "2025-02-18T20:45:18+00:00" }, { "id": 1960567619, "user": "user_9ee0ae83e609", "body": "```suggestion\nПрипустимо, що тепер файл `main.py` із Вашим **FastAPI**-застосунком містить додаткові операції шляху (**path operations**).\n```", "path": "docs/uk/docs/tutorial/testing.md", "line": null, "side": "RIGHT", "created_at": "2025-02-18T20:45:36+00:00" }, { "id": 1960567837, "user": "user_9ee0ae83e609", "body": "```suggestion\nВи можете створити файл `test_main.py` з Вашими тестами. Він може знаходитися в тому ж пакеті Python (у тій самій директорії з файлом `__init__.py`):\n```", "path": "docs/uk/docs/tutorial/testing.md", "line": null, "side": "RIGHT", "created_at": "2025-02-18T20:45:48+00:00" }, { "id": 1960568381, "user": "user_9ee0ae83e609", "body": "```suggestion\nПотім Ви можете оновити `test_main.py`, додавши розширені тести:\n```", "path": "docs/uk/docs/tutorial/testing.md", "line": null, "side": "RIGHT", "created_at": "2025-02-18T20:46:20+00:00" }, { "id": 1960568556, "user": "user_9ee0ae83e609", "body": "```suggestion\nКоли Вам потрібно передати клієнту інформацію в запиті, але Ви не знаєте, як це зробити, Ви можете пошукати (наприклад, у Google) спосіб реалізації в `httpx`, або навіть у `requests`, оскільки HTTPX розроблений на основі дизайну Requests.\n```", "path": "docs/uk/docs/tutorial/testing.md", "line": null, "side": "RIGHT", "created_at": "2025-02-18T20:46:29+00:00" }, { "id": 1960568979, "user": "user_9ee0ae83e609", "body": "```suggestion\nДалі Ви просто повторюєте ці ж дії у ваших тестах.\n```", "path": "docs/uk/docs/tutorial/testing.md", "line": null, "side": "RIGHT", "created_at": "2025-02-18T20:46:53+00:00" }, { "id": 1960569471, "user": "user_9ee0ae83e609", "body": "```suggestion\nЯкщо у Вас є Pydantic-модель у тесті, і Ви хочете передати її дані в додаток під час тестування, Ви можете використати `jsonable_encoder`, описаний у розділі [JSON [NAME_REDACTED]](encoder.md){.internal-link target=_blank}.\n```", "path": "docs/uk/docs/tutorial/testing.md", "line": null, "side": "RIGHT", "created_at": "2025-02-18T20:47:20+00:00" }, { "id": 1960569738, "user": "user_9ee0ae83e609", "body": "```suggestion\nПереконайтеся, що Ви створили [віртуальне середовище]{.internal-link target=_blank}, активували його і встановили необхідні пакети, наприклад:\n```", "path": "docs/uk/docs/tutorial/testing.md", "line": null, "side": "RIGHT", "created_at": "2025-02-18T20:47:33+00:00" }, { "id": 1967951526, "user": "user_84458f05cf3c", "body": "```suggestion\n/// tip | Порада\n```", "path": "docs/uk/docs/tutorial/testing.md", "line": null, "side": "RIGHT", "created_at": "2025-02-24T15:59:36+00:00" }, { "id": 1967982251, "user": "user_c36c155012b4", "body": "thank you :)", "path": "docs/uk/docs/tutorial/testing.md", "line": null, "side": "RIGHT", "created_at": "2025-02-24T16:18:08+00:00" } ], "meta": { "languages": [ "md" ], "touches_tests": false, "review_state_summary": { "APPROVED": 3, "CHANGES_REQUESTED": 1, "COMMENTED": 2 }, "meaningful_comment_count": 18, "has_approval": true, "has_changes_requested": true, "total_review_comments": 18 } } { "_id": "36a08919a2c8ade3", "_schema_version": "1.0", "_cleaned_at": "2026-02-12T07:46:52.163867+00:00", "repo": "tiangolo/fastapi", "repo_url": "https://github.com/fastapi/fastapi", "license_name": "MIT License", "license_spdx": "MIT", "pr_number": 13370, "title": "🌐 Add Ukrainian translation for `docs/uk/docs/tutorial/debugging.md`", "body": null, "author": "user_c36c155012b4", "created_at": "2025-02-14T03:29:49+00:00", "merged_at": "2025-02-28T14:24:45+00:00", "base_branch": "master", "head_branch": "translation-uk/debugging", "additions": 112, "deletions": 0, "changed_files": 1, "files": [ { "filename": "docs/uk/docs/tutorial/debugging.md", "status": "added", "additions": 112, "deletions": 0, "changes": 112, "patch": "@@ -0,0 +1,112 @@\n+# Налагодження (Debugging)\n+\n+Ви можете під'єднати дебагер у Вашому редакторі коду, наприклад, у [NAME_REDACTED] або PyCharm.\n+\n+## Виклик `uvicorn`\n+\n+У Вашому FastAPI-додатку імпортуйте та запустіть `uvicorn` безпосередньо:\n+\n+{* ../../docs_src/debugging/tutorial001.py hl[1,15] *}\n+\n+### Про `__name__ == \"__main__\"`\n+\n+Головна мета використання `__name__ == \"__main__\"` — це забезпечення виконання певного коду тільки тоді, коли файл запускається безпосередньо:\n+\n+
      \n+\n+```console\n+$ python myapp.py\n+```\n+\n+
      \n+\n+але не виконується при його імпорті в інший файл, наприклад:\n+\n+```Python\n+from myapp import app\n+```\n+\n+#### Детальніше\n+\n+Припустимо, Ваш файл називається `myapp.py`.\n+\n+Якщо Ви запустите його так:\n+\n+
      \n+\n+```console\n+$ python myapp.py\n+```\n+\n+
      \n+\n+тоді внутрішня змінна `__name__`, яка створюється автоматично Python, матиме значення `\"__main__\"`.\n+\n+Отже, цей блок коду:\n+\n+```Python\n+ uvicorn.run(app, host=\"0.0.0.0\", port=8000)\n+```\n+\n+буде виконаний.\n+\n+---\n+\n+Це не станеться, якщо Ви імпортуєте цей модуль (файл).\n+\n+Якщо у Вас є інший файл, наприклад `importer.py`, з наступним кодом:\n+\n+```Python\n+from myapp import app\n+\n+# Додатковий код\n+```\n+\n+У цьому випадку автоматично створена змінна у файлі `myapp.py` не матиме значення змінної `__name__` як `\"__main__\"`.\n+\n+Отже, рядок:\n+\n+```Python\n+ uvicorn.run(app, host=\"0.0.0.0\", port=8000)\n+```\n+\n+не буде виконано.\n+\n+/// info | Інформація\n+\n+Більш детальну інформацію можна знайти в офіційній документації Python.\n+\n+///\n+\n+## Запуск коду з вашим дебагером\n+\n+Оскільки Ви запускаєте сервер Uvicorn безпосередньо з Вашого коду, Ви можете запустити вашу Python програму (ваш FastAPI додаток) безпосередньо з дебагера.\n+\n+---\n+\n+Наприклад, у [NAME_REDACTED] Ви можете:\n+\n+* Перейдіть на вкладку \"Debug\".\n+* Натисніть \"Add configuration...\".\n+* Виберіть \"Python\"\n+* Запустіть дебагер з опцією \"`Python: [NAME_REDACTED] ([NAME_REDACTED])`\".\n+\n+Це запустить сервер з Вашим **FastAPI** кодом, зупиниться на точках зупину тощо.\n+\n+Ось як це може виглядати:\n+\n+\n+\n+---\n+Якщо Ви використовуєте PyCharm, ви можете:\n+\n+* Відкрити меню \"Run\".\n+* Вибрати опцію \"Debug...\".\n+* Потім з'явиться контекстне меню.\n+* Вибрати файл для налагодження (у цьому випадку, `main.py`).\n+\n+Це запустить сервер з Вашим **FastAPI** кодом, зупиниться на точках зупину тощо.\n+\n+Ось як це може виглядати:\n+\n+" } ], "reviews": [ { "id": 2616936466, "user": "user_787e19aded2a", "state": "APPROVED", "body": null, "submitted_at": "2025-02-14T07:20:13+00:00" }, { "id": 2623521691, "user": "user_489e2b951069", "state": "APPROVED", "body": null, "submitted_at": "2025-02-18T13:10:21+00:00" }, { "id": 2624997344, "user": "user_9ee0ae83e609", "state": "CHANGES_REQUESTED", "body": null, "submitted_at": "2025-02-18T20:50:17+00:00" }, { "id": 2627862045, "user": "user_9ee0ae83e609", "state": "APPROVED", "body": null, "submitted_at": "2025-02-19T20:03:05+00:00" }, { "id": 2637668494, "user": "user_84458f05cf3c", "state": "COMMENTED", "body": "Looking good from a structural point of view! 🎉", "submitted_at": "2025-02-24T16:04:31+00:00" }, { "id": 2650902460, "user": "user_2a237e38e06b", "state": "APPROVED", "body": "Thanks [USER_REDACTED]! :cake: \n\nAnd thanks all for the reviews :coffee:", "submitted_at": "2025-02-28T14:24:26+00:00" } ], "review_comments": [ { "id": 1960570366, "user": "user_9ee0ae83e609", "body": "```suggestion\nВи можете під'єднати дебагер у Вашому редакторі коду, наприклад, у [NAME_REDACTED] або PyCharm.\n```", "path": "docs/uk/docs/tutorial/debugging.md", "line": null, "side": "RIGHT", "created_at": "2025-02-18T20:48:06+00:00" }, { "id": 1960570552, "user": "user_9ee0ae83e609", "body": "```suggestion\nУ Вашому FastAPI-додатку імпортуйте та запустіть `uvicorn` безпосередньо:\n```", "path": "docs/uk/docs/tutorial/debugging.md", "line": null, "side": "RIGHT", "created_at": "2025-02-18T20:48:16+00:00" }, { "id": 1960570846, "user": "user_9ee0ae83e609", "body": "```suggestion\nПрипустимо, Ваш файл називається `myapp.py`.\n```", "path": "docs/uk/docs/tutorial/debugging.md", "line": null, "side": "RIGHT", "created_at": "2025-02-18T20:48:33+00:00" }, { "id": 1960570992, "user": "user_9ee0ae83e609", "body": "```suggestion\nЯкщо Ви запустите його так:\n```", "path": "docs/uk/docs/tutorial/debugging.md", "line": null, "side": "RIGHT", "created_at": "2025-02-18T20:48:40+00:00" }, { "id": 1960571203, "user": "user_9ee0ae83e609", "body": "```suggestion\nЦе не станеться, якщо Ви імпортуєте цей модуль (файл).\n```", "path": "docs/uk/docs/tutorial/debugging.md", "line": null, "side": "RIGHT", "created_at": "2025-02-18T20:48:53+00:00" }, { "id": 1960571335, "user": "user_9ee0ae83e609", "body": "```suggestion\nЯкщо у Вас є інший файл, наприклад `importer.py`, з наступним кодом:\n```", "path": "docs/uk/docs/tutorial/debugging.md", "line": null, "side": "RIGHT", "created_at": "2025-02-18T20:49:01+00:00" }, { "id": 1960571675, "user": "user_9ee0ae83e609", "body": "```suggestion\nОскільки Ви запускаєте сервер Uvicorn безпосередньо з Вашого коду, Ви можете запустити вашу Python програму (ваш FastAPI додаток) безпосередньо з дебагера.\n```", "path": "docs/uk/docs/tutorial/debugging.md", "line": null, "side": "RIGHT", "created_at": "2025-02-18T20:49:22+00:00" }, { "id": 1960571803, "user": "user_9ee0ae83e609", "body": "```suggestion\nНаприклад, у [NAME_REDACTED] Ви можете:\n```", "path": "docs/uk/docs/tutorial/debugging.md", "line": null, "side": "RIGHT", "created_at": "2025-02-18T20:49:30+00:00" }, { "id": 1960572094, "user": "user_9ee0ae83e609", "body": "```suggestion\nЦе запустить сервер з Вашим **FastAPI** кодом, зупиниться на точках зупину тощо.\n```", "path": "docs/uk/docs/tutorial/debugging.md", "line": null, "side": "RIGHT", "created_at": "2025-02-18T20:49:46+00:00" }, { "id": 1960572242, "user": "user_9ee0ae83e609", "body": "```suggestion\nЯкщо Ви використовуєте PyCharm, ви можете:\n```", "path": "docs/uk/docs/tutorial/debugging.md", "line": null, "side": "RIGHT", "created_at": "2025-02-18T20:49:55+00:00" }, { "id": 1960572451, "user": "user_9ee0ae83e609", "body": "```suggestion\nЦе запустить сервер з Вашим **FastAPI** кодом, зупиниться на точках зупину тощо.\n```", "path": "docs/uk/docs/tutorial/debugging.md", "line": null, "side": "RIGHT", "created_at": "2025-02-18T20:50:09+00:00" } ], "meta": { "languages": [ "md" ], "touches_tests": false, "review_state_summary": { "APPROVED": 4, "CHANGES_REQUESTED": 1, "COMMENTED": 1 }, "meaningful_comment_count": 11, "has_approval": true, "has_changes_requested": true, "total_review_comments": 11 } } { "_id": "a936cfacec56f6a7", "_schema_version": "1.0", "_cleaned_at": "2026-02-12T07:46:52.163867+00:00", "repo": "tiangolo/fastapi", "repo_url": "https://github.com/fastapi/fastapi", "license_name": "MIT License", "license_spdx": "MIT", "pr_number": 13362, "title": "🌐 Add Ukrainian translation for `docs/uk/docs/tutorial/query-params.md`", "body": null, "author": "user_c36c155012b4", "created_at": "2025-02-12T21:37:38+00:00", "merged_at": "2025-02-28T14:23:55+00:00", "base_branch": "master", "head_branch": "translate-uk/query-params", "additions": 192, "deletions": 0, "changed_files": 1, "files": [ { "filename": "docs/uk/docs/tutorial/query-params.md", "status": "added", "additions": 192, "deletions": 0, "changes": 192, "patch": "@@ -0,0 +1,192 @@\n+# Query Параметри\n+\n+Коли Ви оголошуєте інші параметри функції, які не є частиною параметрів шляху, вони автоматично інтерпретуються як \"query\" параметри.\n+\n+{* ../../docs_src/query_params/tutorial001.py hl[9] *}\n+\n+Query параметри — це набір пар ключ-значення, що йдуть після символу `?` в URL, розділені символами `&`.\n+\n+Наприклад, в URL:\n+\n+```\n+http://127.0.0.1:8000/items/?skip=0&limit=10\n+```\n+\n+...query параметрами є:\n+\n+* `skip`: зі значенням `0`\n+* `limit`: зі значенням `10`\n+\n+Оскільки вони є частиною URL, вони \"за замовчуванням\" є рядками.\n+\n+Але коли Ви оголошуєте їх із типами Python (у наведеному прикладі як `int`), вони перетворюються на цей тип і проходять перевірку відповідності.\n+\n+Увесь той самий процес, який застосовується до параметрів шляху, також застосовується до query параметрів:\n+\n+* Підтримка в редакторі (автодоповнення, перевірка помилок)\n+* \"Парсинг\" даних\n+* Валідація даних\n+* Автоматична документація\n+\n+\n+## Значення за замовчуванням\n+\n+Оскільки query параметри не є фіксованою частиною шляху, вони можуть бути необов’язковими та мати значення за замовчуванням.\n+\n+У наведеному вище прикладі вони мають значення за замовчуванням: `skip=0` і `limit=10`.\n+\n+Отже, результат переходу за URL:\n+\n+```\n+http://127.0.0.1:8000/items/\n+```\n+буде таким самим, як і перехід за посиланням:\n+\n+```\n+http://127.0.0.1:8000/items/?skip=0&limit=10\n+```\n+\n+Але якщо Ви перейдете, наприклад, за посиланням:\n+\n+```\n+http://127.0.0.1:8000/items/?skip=20\n+```\n+\n+Значення параметрів у вашій функції будуть такими:\n+\n+* `skip=20`: оскільки Ви вказали його в URL\n+* `limit=10`: оскільки це значення за замовчуванням\n+\n+## Необов'язкові параметри\n+\n+Аналогічно, Ви можете оголосити необов’язкові query параметри, встановивши для них значення за замовчуванням `None`:\n+\n+{* ../../docs_src/query_params/tutorial002_py310.py hl[7] *}\n+\n+У цьому випадку параметр функції `q` буде необов’язковим і за замовчуванням матиме значення `None`.\n+\n+/// check | Примітка\n+\n+Також зверніть увагу, що **FastAPI** достатньо розумний, щоб визначити, що параметр шляху `item_id` є параметром шляху, а `q` — ні, отже, це query параметр.\n+\n+///\n+\n+## Перетворення типу Query параметра\n+\n+Ви також можете оголошувати параметри типу `bool`, і вони будуть автоматично конвертовані:\n+\n+{* ../../docs_src/query_params/tutorial003_py310.py hl[7] *}\n+\n+У цьому випадку, якщо Ви звернетесь до:\n+\n+\n+```\n+http://127.0.0.1:8000/items/foo?short=1\n+```\n+\n+або\n+\n+```\n+http://127.0.0.1:8000/items/foo?short=True\n+```\n+\n+або\n+\n+```\n+http://127.0.0.1:8000/items/foo?short=true\n+```\n+\n+або\n+\n+```\n+http://127.0.0.1:8000/items/foo?short=on\n+```\n+\n+або\n+\n+```\n+http://127.0.0.1:8000/items/foo?short=yes\n+```\n+\n+або будь-який інший варіант написання (великі літери, перша літера велика тощо), ваша функція побачить параметр `short` зі значенням `True` з типом даних `bool`. В іншому випадку – `False`.\n+\n+## Кілька path і query параметрів\n+\n+Ви можете одночасно оголошувати кілька path і query параметрів, і **FastAPI** автоматично визначить, який з них до чого належить.\n+\n+\n+Не потрібно дотримуватись певного порядку їх оголошення.\n+\n+Вони визначаються за назвою:\n+\n+{* ../../docs_src/query_params/tutorial004_py310.py hl[6,8] *}\n+\n+## Обов’язкові Query параметри\n+\n+Якщо Ви оголошуєте значення за замовчуванням для параметрів, які не є path-параметрами (у цьому розділі ми бачили поки що лише path параметри), тоді вони стають необов’язковими.\n+\n+Якщо Ви не хочете вказувати конкретні значення, але хочете зробити параметр опціональним, задайте `None` як значення за замовчуванням.\n+\n+Але якщо Ви хочете зробити query параметр обов’язковим, просто не вказуйте для нього значення за замовчуванням:\n+\n+{* ../../docs_src/query_params/tutorial005.py hl[6:7] *}\n+\n+Тут `needy` – обов’язковий query параметр типу `str`.\n+\n+Якщо Ви відкриєте у браузері URL-адресу:\n+\n+```\n+http://127.0.0.1:8000/items/foo-item\n+```\n+\n+...без додавання обов’язкового параметра `needy`, Ви побачите помилку:\n+\n+```JSON\n+{\n+ \"detail\": [\n+ {\n+ \"type\": \"missing\",\n+ \"loc\": [\n+ \"query\",\n+ \"needy\"\n+ ],\n+ \"msg\": \"Field required\",\n+ \"input\": null,\n+ \"url\": \"https://errors.pydantic.dev/2.1/v/missing\"\n+ }\n+ ]\n+}\n+```\n+\n+Оскільки `needy` є обов’язковим параметром, вам потрібно вказати його в URL:\n+\n+```\n+http://127.0.0.1:8000/items/foo-item?needy=sooooneedy\n+```\n+\n+...цей запит поверне:\n+\n+```JSON\n+{\n+ \"item_id\": \"foo-item\",\n+ \"needy\": \"sooooneedy\"\n+}\n+```\n+\n+\n+Звичайно, Ви можете визначити деякі параметри як обов’язкові, інші зі значенням за замовчуванням, а ще деякі — повністю опціональні:\n+\n+{* ../../docs_src/query_params/tutorial006_py310.py hl[8] *}\n+\n+У цьому випадку є 3 query параметри:\n+\n+* `needy`, обов’язковий `str`.\n+* `skip`, `int` зі значенням за замовчуванням `0`.\n+* `limit`, опціональний `int`.\n+\n+\n+/// tip | Підказка\n+\n+Ви також можете використовувати `Enum`-и, так само як і з [Path Parameters](path-params.md#predefined-values){.internal-link target=_blank}.\n+\n+///" } ], "reviews": [ { "id": 2613268932, "user": "user_dac146a60e0c", "state": "APPROVED", "body": null, "submitted_at": "2025-02-12T21:38:36+00:00" }, { "id": 2613286100, "user": "user_787e19aded2a", "state": "APPROVED", "body": null, "submitted_at": "2025-02-12T21:48:41+00:00" }, { "id": 2623898972, "user": "user_568843bce6ca", "state": "COMMENTED", "body": "Just a formatting nitpick :sweat_smile:", "submitted_at": "2025-02-18T15:09:48+00:00" }, { "id": 2627863144, "user": "user_9ee0ae83e609", "state": "APPROVED", "body": null, "submitted_at": "2025-02-19T20:03:42+00:00" }, { "id": 2637682166, "user": "user_84458f05cf3c", "state": "COMMENTED", "body": "Looking good from a structural point of view! 🥳", "submitted_at": "2025-02-24T16:09:49+00:00" }, { "id": 2650899556, "user": "user_2a237e38e06b", "state": "APPROVED", "body": "Great, thank you [USER_REDACTED]! :cookie: \n\nAnd thanks for the help and reviews [USER_REDACTED], [USER_REDACTED], [USER_REDACTED], [USER_REDACTED], [USER_REDACTED] :coffee:", "submitted_at": "2025-02-28T14:23:19+00:00" } ], "review_comments": [ { "id": 1959940446, "user": "user_568843bce6ca", "body": "```suggestion\n* `limit`: зі значенням `10`\n```", "path": "docs/uk/docs/tutorial/query-params.md", "line": null, "side": "RIGHT", "created_at": "2025-02-18T15:06:49+00:00" }, { "id": 1967967644, "user": "user_84458f05cf3c", "body": "```suggestion\nОскільки `needy` є обов’язковим параметром, вам потрібно вказати його в URL:\n```", "path": "docs/uk/docs/tutorial/query-params.md", "line": null, "side": "RIGHT", "created_at": "2025-02-24T16:09:14+00:00" } ], "meta": { "languages": [ "md" ], "touches_tests": false, "review_state_summary": { "APPROVED": 4, "COMMENTED": 2 }, "meaningful_comment_count": 2, "has_approval": true, "has_changes_requested": false, "total_review_comments": 2 } } { "_id": "d52c1a424b64381f", "_schema_version": "1.0", "_cleaned_at": "2026-02-12T07:46:52.163867+00:00", "repo": "tiangolo/fastapi", "repo_url": "https://github.com/fastapi/fastapi", "license_name": "MIT License", "license_spdx": "MIT", "pr_number": 13354, "title": "🌐 Add Ukrainian translation for `docs/uk/docs/tutorial/path-params.md`", "body": null, "author": "user_c36c155012b4", "created_at": "2025-02-12T04:35:34+00:00", "merged_at": "2025-02-28T14:21:46+00:00", "base_branch": "master", "head_branch": "translation-uk/path-params", "additions": 261, "deletions": 0, "changed_files": 1, "files": [ { "filename": "docs/uk/docs/tutorial/path-params.md", "status": "added", "additions": 261, "deletions": 0, "changes": 261, "patch": "@@ -0,0 +1,261 @@\n+# Path Параметри\n+\n+Ви можете визначити \"параметри\" або \"змінні\" шляху, використовуючи синтаксис форматованих рядків:\n+\n+{* ../../docs_src/path_params/tutorial001.py hl[6:7] *}\n+\n+Значення параметра шляху `item_id` передається у функцію як аргумент `item_id`.\n+\n+Якщо запустити цей приклад та перейти за посиланням http://127.0.0.1:8000/items/foo, то отримаємо таку відповідь:\n+\n+```JSON\n+{\"item_id\":\"foo\"}\n+```\n+\n+## Path параметри з типами\n+\n+Ви можете визначити тип параметра шляху у функції, використовуючи стандартні анотації типів Python:\n+\n+{* ../../docs_src/path_params/tutorial002.py hl[7] *}\n+\n+У такому випадку `item_id` визначається як `int`.\n+\n+/// check | Примітка\n+\n+Це дасть можливість підтримки редактора всередині функції з перевірками помилок, автодоповнення тощо.\n+\n+///\n+\n+## Перетворення даних\n+\n+Якщо запустити цей приклад і перейти за посиланням http://127.0.0.1:8000/items/3, то отримаєте таку відповідь:\n+\n+```JSON\n+{\"item_id\":3}\n+```\n+\n+/// check | Примітка\n+\n+Зверніть увагу, що значення, яке отримала (і повернула) ваша функція, — це `3`. Це Python `int`, а не рядок `\"3\"`.\n+\n+Отже, з таким оголошенням типу **FastAPI** автоматично виконує \"парсинг\" запитів.\n+\n+///\n+\n+## Перевірка даних\n+\n+Якщо ж відкрити у браузері посилання http://127.0.0.1:8000/items/foo, то побачимо цікаву HTTP-помилку:\n+\n+```JSON\n+{\n+ \"detail\": [\n+ {\n+ \"type\": \"int_parsing\",\n+ \"loc\": [\n+ \"path\",\n+ \"item_id\"\n+ ],\n+ \"msg\": \"Input should be a valid integer, unable to parse string as an integer\",\n+ \"input\": \"foo\",\n+ \"url\": \"https://errors.pydantic.dev/2.1/v/int_parsing\"\n+ }\n+ ]\n+}\n+```\n+тому що параметр шляху має значення `\"foo\"`, яке не є типом `int`.\n+\n+Таку саму помилку отримаємо, якщо передати `float` замість `int`, як бачимо, у цьому прикладі: http://127.0.0.1:8000/items/4.2\n+\n+/// check | Примітка\n+\n+Отже, **FastAPI** надає перевірку типів з таким самим оголошенням типу в Python.\n+\n+Зверніть увагу, що помилка також чітко вказує саме на те місце, де валідація не пройшла.\n+\n+Це неймовірно корисно під час розробки та дебагінгу коду, що взаємодіє з вашим API.\n+\n+///\n+\n+## Документація\n+\n+Тепер коли відкриєте свій браузер за посиланням http://127.0.0.1:8000/docs, то побачите автоматично згенеровану, інтерактивну API-документацію:\n+\n+\n+\n+/// check | Примітка\n+\n+Знову ж таки, лише з цим самим оголошенням типу в Python, FastAPI надає вам автоматичну, інтерактивну документацію (з інтеграцією Swagger UI).\n+\n+Зверніть увагу, що параметр шляху оголошений як ціле число.\n+\n+\n+///\n+\n+## Переваги стандартизації, альтернативна документація\n+\n+І оскільки згенерована схема відповідає стандарту OpenAPI, існує багато сумісних інструментів.\n+\n+З цієї причини FastAPI також надає альтернативну документацію API (використовуючи ReDoc), до якої можна отримати доступ за посиланням http://127.0.0.1:8000/redoc:\n+\n+\n+\n+Таким чином, існує багато сумісних інструментів, включаючи інструменти для генерації коду для багатьох мов.\n+\n+\n+## Pydantic\n+\n+Вся валідація даних виконується за лаштунками за допомогою Pydantic, тому Ви отримуєте всі переваги від його використання. І можете бути впевнені, що все в надійних руках.\n+\n+Ви можете використовувати ті самі оголошення типів з `str`, `float`, `bool` та багатьма іншими складними типами даних.\n+\n+Декілька з них будуть розглянуті в наступних розділах посібника.\n+\n+## Порядок має значення\n+\n+При створенні *операцій шляху* можуть виникати ситуації, коли шлях фіксований.\n+\n+Наприклад, `/users/me`. Припустимо, що це шлях для отримання даних про поточного користувача.\n+\n+А також у вас може бути шлях `/users/{user_id}`, щоб отримати дані про конкретного користувача за його ID.\n+\n+Оскільки *операції шляху* оцінюються по черзі, Ви повинні переконатися, що шлях для `/users/me` оголошений перед шляхом для `/users/{user_id}`:\n+\n+{* ../../docs_src/path_params/tutorial003.py hl[6,11] *}\n+\n+Інакше шлях для `/users/{user_id}` також буде відповідати для `/users/me`, \"вважаючи\", що він отримує параметр `user_id` зі значенням `\"me\"`.\n+\n+Аналогічно, Ви не можете оголосити операцію шляху:\n+\n+{* ../../docs_src/path_params/tutorial003b.py hl[6,11] *}\n+\n+Перша операція буде завжди використовуватися, оскільки шлях збігається першим.\n+## Попередньо визначені значення\n+\n+Якщо у вас є *операція шляху*, яка приймає *параметр шляху*, але Ви хочете, щоб можливі допустимі значення *параметра шляху* були попередньо визначені, Ви можете використати стандартний Python Enum.\n+\n+### Створення класу `Enum`\n+\n+Імпортуйте `Enum` і створіть підклас, що наслідується від `str` та `Enum`.\n+\n+Наслідуючи від `str`, документація API зможе визначити, що значення повинні бути типу `string`, і правильно їх відобразить.\n+\n+Після цього створіть атрибути класу з фіксованими значеннями, які будуть доступними допустимими значеннями:\n+\n+{* ../../docs_src/path_params/tutorial005.py hl[1,6:9] *}\n+\n+/// info | Додаткова інформація\n+\n+Перелічення (або enums) доступні в Python починаючи з версії 3.4.\n+\n+///\n+\n+/// tip | Порада\n+\n+Якщо вам цікаво, \"AlexNet\", \"ResNet\" та \"LeNet\" — це просто назви ML моделей [NAME_REDACTED].\n+\n+///\n+\n+\n+### Оголосіть *параметр шляху*\n+\n+Потім створіть *параметр шляху* з анотацією типу, використовуючи створений вами клас enum (`ModelName`):\n+\n+{* ../../docs_src/path_params/tutorial005.py hl[16] *}\n+\n+### Перевірка документації\n+\n+Оскільки доступні значення для *параметра шляху* визначені заздалегідь, інтерактивна документація зможе красиво їх відобразити:\n+\n+\n+\n+### Робота з *перелічуваннями* у Python\n+\n+Значення *параметра шляху* буде елементом *перелічування*.\n+\n+#### Порівняння *елементів перелічування*\n+\n+Ви можете порівнювати його з *елементами перелічування* у створеному вами enum `ModelName`:\n+\n+{* ../../docs_src/path_params/tutorial005.py hl[17] *}\n+\n+#### Отримання *значення перелічування*\n+\n+Ви можете отримати фактичне значення (у цьому випадку це `str`), використовуючи `model_name.value`, або загалом `your_enum_member.value`:\n+\n+{* ../../docs_src/path_params/tutorial005.py hl[20] *}\n+\n+/// tip | Порада\n+\n+Ви також можете отримати доступ до значення `\"lenet\"`, використовуючи `ModelName.lenet.value`.\n+\n+///\n+\n+\n+#### Повернення *елементів перелічування*\n+\n+Ви можете повертати *елементи перелічування* з вашої *операції шляху*, навіть вкладені у JSON-тіло (наприклад, `dict`).\n+\n+Вони будуть перетворені на відповідні значення (у цьому випадку рядки) перед поверненням клієнту:\n+\n+{* ../../docs_src/path_params/tutorial005.py hl[18,21,23] *}\n+\n+На стороні клієнта Ви отримаєте відповідь у форматі JSON, наприклад:\n+\n+```JSON\n+{\n+ \"model_name\": \"alexnet\",\n+ \"message\": \"[NAME_REDACTED] FTW!\"\n+}\n+```\n+\n+## Path-параметри, що містять шляхи\n+\n+Припустимо, у вас є *операція шляху* з маршрутом `/files/{file_path}`.\n+\n+Але вам потрібно, щоб `file_path` містив *шлях*, наприклад `home/johndoe/myfile.txt`.\n+\n+Отже, URL для цього файлу виглядатиме так: `/files/home/johndoe/myfile.txt`.\n+\n+\n+\n+### Підтримка OpenAPI\n+\n+OpenAPI не підтримує спосіб оголошення *параметра шляху*, що містить *шлях* всередині, оскільки це може призвести до сценаріїв, які складно тестувати та визначати.\n+\n+Однак (одначе), Ви все одно можете зробити це в **FastAPI**, використовуючи один із внутрішніх інструментів Starlette.\n+\n+Документація все ще працюватиме, хоча й не додаватиме опису про те, що параметр повинен містити шлях.\n+\n+### Конвертер шляху\n+\n+Використовуючи опцію безпосередньо зі Starlette, Ви можете оголосити *параметр шляху*, що містить *шлях*, використовуючи URL на кшталт:\n+\n+```\n+/files/{file_path:path}\n+```\n+У цьому випадку ім'я параметра — `file_path`, а остання частина `:path` вказує на те, що параметр повинен відповідати будь-якому *шляху*.\n+\n+Отже, Ви можете використати його так:\n+\n+{* ../../docs_src/path_params/tutorial004.py hl[6] *}\n+\n+/// tip | Порада\n+\n+Вам може знадобитися, щоб параметр містив `/home/johndoe/myfile.txt` із початковою косою рискою (`/`).\n+\n+У такому випадку URL виглядатиме так: `/files//home/johndoe/myfile.txt`, із подвійною косою рискою (`//`) між `files` і `home`.\n+\n+///\n+\n+## Підсумок\n+\n+З **FastAPI**, використовуючи короткі, інтуїтивно зрозумілі та стандартні оголошення типів Python, Ви отримуєте:\n+\n+* Підтримку в редакторі: перевірка помилок, автодоповнення тощо.\n+* \"Парсинг\" даних\n+* Валідацію даних\n+* Анотацію API та автоматичну документацію\n+\n+І вам потрібно оголосити їх лише один раз.\n+\n+Це, ймовірно, основна видима перевага **FastAPI** порівняно з альтернативними фреймворками (окрім високої продуктивності)." } ], "reviews": [ { "id": 2612145805, "user": "user_489e2b951069", "state": "APPROVED", "body": null, "submitted_at": "2025-02-12T14:37:32+00:00" }, { "id": 2612511744, "user": "user_dac146a60e0c", "state": "APPROVED", "body": null, "submitted_at": "2025-02-12T16:18:03+00:00" }, { "id": 2627866044, "user": "user_9ee0ae83e609", "state": "APPROVED", "body": null, "submitted_at": "2025-02-19T20:05:12+00:00" }, { "id": 2637689719, "user": "user_84458f05cf3c", "state": "COMMENTED", "body": "As usual [USER_REDACTED] this is looking good from a structural point of view. Thanks for all your hard work translating these pages! 🙏 🚀 🤩", "submitted_at": "2025-02-24T16:14:39+00:00" }, { "id": 2650893124, "user": "user_2a237e38e06b", "state": "APPROVED", "body": "Thanks [USER_REDACTED]! :cake: \n\nAnd thanks all for the reviews :coffee:", "submitted_at": "2025-02-28T14:20:57+00:00" } ], "review_comments": [ { "id": 1967972179, "user": "user_84458f05cf3c", "body": "```suggestion\n\n```", "path": "docs/uk/docs/tutorial/path-params.md", "line": null, "side": "RIGHT", "created_at": "2025-02-24T16:12:02+00:00" } ], "meta": { "languages": [ "md" ], "touches_tests": false, "review_state_summary": { "APPROVED": 4, "COMMENTED": 1 }, "meaningful_comment_count": 1, "has_approval": true, "has_changes_requested": false, "total_review_comments": 1 } } { "_id": "365e7a6b00cf39c2", "_schema_version": "1.0", "_cleaned_at": "2026-02-12T07:46:52.179504+00:00", "repo": "tiangolo/fastapi", "repo_url": "https://github.com/fastapi/fastapi", "license_name": "MIT License", "license_spdx": "MIT", "pr_number": 13333, "title": "🌐 Add Korean translation for `docs/ko/docs/tutorial/security/oauth2-jwt.md`", "body": "Hello! This is my first translation, so it may be lacking a lot.\n\n~~If there are any Korean translation guidelines in this repo, please let me know.~~\nI found discussion(#3167) late and corrected it a little more.\n\nI would greatly appreciate any feedback 🙇‍♀️\n\n## ✏️ Note\n\n1️⃣ There is some paraphrasing. Some sentences have been reconstructed to a level that is easy for Koreans to read without damaging the meaning of the original text. (I think that simple word translations could be handled well by [NAME_REDACTED])\n\n2️⃣ For consistency within the [security](https://fastapi.tiangolo.com/ko/tutorial/security/) subdocuments, I translated \"password\" into \"패스워드\" according to the `simple-oauth2.md`, instead of \"비밀번호\"", "author": "user_dfad060db61c", "created_at": "2025-02-08T05:41:23+00:00", "merged_at": "2025-03-10T12:29:03+00:00", "base_branch": "master", "head_branch": "feature/translation-docs-ko-oauth2-jwt", "additions": 273, "deletions": 0, "changed_files": 1, "files": [ { "filename": "docs/ko/docs/tutorial/security/oauth2-jwt.md", "status": "added", "additions": 273, "deletions": 0, "changes": 273, "patch": "@@ -0,0 +1,273 @@\n+# 패스워드 해싱을 이용한 OAuth2, JWT 토큰을 사용하는 Bearer 인증\n+\n+모든 보안 흐름을 구성했으므로, 이제 JWT 토큰과 패스워드 해싱을 사용해 애플리케이션을 안전하게 만들 것입니다.\n+\n+이 코드는 실제로 애플리케이션에서 패스워드를 해싱하여 DB에 저장하는 등의 작업에 활용할 수 있습니다.\n+\n+이전 장에 이어서 시작해 봅시다.\n+\n+## JWT\n+\n+JWT 는 \"JSON [NAME_REDACTED]\" 을 의미합니다.\n+\n+JSON 객체를 공백이 없는 긴 문자열로 인코딩하는 표준이며, 다음과 같은 형태입니다:\n+\n+```\n+eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c\n+```\n+\n+JWT는 암호화되지 않아 누구든지 토큰에서 정보를 복원할 수 있습니다.\n+\n+하지만 JWT는 서명되어 있습니다. 그래서 자신이 발급한 토큰을 받았을 때, 실제로 자신이 발급한게 맞는지 검증할 수 있습니다.\n+\n+만료 기간이 일주일인 토큰을 발행했다고 가정해 봅시다. 다음 날 사용자가 토큰을 가져왔을 때, 그 사용자가 시스템에 여전히 로그인되어 있다는 것을 알 수 있습니다.\n+\n+일주일 뒤에는 토큰이 만료될 것이고, 사용자는 인가되지 않아 새 토큰을 받기 위해 다시 로그인해야 할 것입니다. 만약 사용자(또는 제3자)가 토큰을 수정하거나 만료일을 변경하면, 서명이 일치하지 않기 때문에 알아챌 수 있을 것입니다.\n+\n+만약 JWT 토큰을 다뤄보고, 작동 방식도 알아보고 싶다면 https://jwt.io 을 확인하십시오.\n+\n+## `PyJWT` 설치\n+\n+파이썬으로 JWT 토큰을 생성하고 검증하려면 `PyJWT` 를 설치해야 합니다.\n+\n+[가상환경](../../virtual-environments.md){.internal-link target=_blank} 을 만들고 활성화한 다음 `pyjwt` 를 설치하십시오:\n+\n+
      \n+\n+```console\n+$ pip install pyjwt\n+\n+---> 100%\n+```\n+\n+
      \n+\n+/// info | 참고\n+\n+RSA나 ECDSA 같은 전자 서명 알고리즘을 사용하려면, `pyjwt[crypto]`라는 암호화 라이브러리 의존성을 설치해야 합니다.\n+\n+더 자세한 내용은 PyJWT 설치 에서 확인할 수 있습니다.\n+\n+///\n+\n+## 패스워드 해싱\n+\n+\"해싱(Hashing)\"은 어떤 내용(여기서는 패스워드)을 해석할 수 없는 일련의 바이트 집합(단순 문자열)으로 변환하는 것을 의미합니다.\n+\n+동일한 내용(똑같은 패스워드)을 해싱하면 동일한 문자열을 얻습니다.\n+\n+하지만 그 문자열을 다시 패스워드로 되돌릴 수는 없습니다.\n+\n+### 패스워드를 해싱하는 이유\n+\n+데이터베이스를 탈취당하더라도, 침입자는 사용자의 평문 패스워드 대신 해시 값만 얻을 수 있습니다.\n+\n+따라서 침입자는 훔친 사용자 패스워드를 다른 시스템에서 활용할 수 없습니다. (대다수 사용자가 여러 시스템에서 동일한 패스워드를 사용하기 때문에 평문 패스워드가 유출되면 위험합니다.)\n+\n+## `passlib` 설치\n+\n+PassLib는 패스워드 해시를 다루는 훌륭한 파이썬 패키지입니다.\n+\n+많은 안전한 해시 알고리즘과 도구들을 지원합니다.\n+\n+추천하는 알고리즘은 \"Bcrypt\"입니다.\n+\n+[가상환경](../../virtual-environments.md){.internal-link target=_blank} 을 만들고 활성화한 다음 PassLib와 Bcrypt를 설치하십시오:\n+\n+
      \n+\n+```console\n+$ pip install \"passlib[bcrypt]\"\n+\n+---> 100%\n+```\n+\n+
      \n+\n+/// tip | 팁\n+\n+`passlib`를 사용하여, **Django**, **Flask** 의 보안 플러그인이나 다른 도구로 생성한 패스워드를 읽을 수 있도록 설정할 수도 있습니다.\n+\n+예를 들자면, FastAPI 애플리케이션과 Django 애플리케이션이 같은 데이터베이스에서 데이터를 공유할 수 있습니다. 또는 같은 데이터베이스를 사용하여 Django 애플리케이션을 점진적으로 마이그레이션 할 수도 있습니다.\n+\n+그리고 사용자는 FastAPI 애플리케이션과 Django 애플리케이션에 동시에 로그인할 수 있습니다.\n+\n+///\n+\n+## 패스워드의 해시와 검증\n+\n+필요한 도구를 `passlib`에서 임포트합니다.\n+\n+PassLib \"컨텍스트(context)\"를 생성합니다. 이것은 패스워드를 해싱하고 검증하는데 사용합니다.\n+\n+/// tip | 팁\n+\n+PassLib 컨텍스트는 다양한 해싱 알고리즘을 사용할 수 있는 기능을 제공하며, 더 이상 사용이 권장되지 않는 오래된 해싱 알고리즘을 검증하는 기능도 포함되어 있습니다.\n+\n+예를 들어, 다른 시스템(Django 같은)에서 생성한 패스워드를 읽고 검증할 수 있으며, 새로운 패스워드를 Bcrypt 같은 다른 알고리즘으로 해싱할 수도 있습니다.\n+\n+그리고 동시에 그런 모든 알고리즘과 호환성을 유지합니다.\n+\n+///\n+\n+사용자로부터 받은 패스워드를 해싱하는 유틸리티 함수를 생성합니다.\n+\n+그리고 받은 패스워드가 저장된 해시와 일치하는지 검증하는 또 다른 유틸리티 함수도 생성합니다.\n+\n+그리고 사용자를 인증하고 반환하는 또 다른 함수도 생성합니다.\n+\n+{* ../../docs_src/security/tutorial004_an_py310.py hl[8,49,56:57,60:61,70:76] *}\n+\n+/// note\n+\n+새로운 (가짜) 데이터베이스 `fake_users_db`를 확인하면, 해시 처리된 패스워드가 어떻게 생겼는지 볼 수 있습니다: `\"$2b$12$EixZaYVK1fsbw1ZfbX3OXePaWxn96p36WQoeG6Lruj3vjPGga31lW\"`.\n+\n+///\n+\n+## JWT 토큰 처리\n+\n+설치된 모듈을 임포트 합니다.\n+\n+JWT 토큰 서명에 사용될 임의의 비밀키를 생성합니다.\n+\n+안전한 임의의 비밀키를 생성하려면 다음 명령어를 사용하십시오:\n+\n+
      \n+\n+```console\n+$ openssl rand -hex 32\n+\n+09d25e094faa6ca2556c818166b7a9563b93f7099f6f0f4caa6cf63b88e8d3e7\n+```\n+\n+
      \n+\n+그리고 생성한 비밀키를 복사해 변수 `SECRET_KEY`에 대입합니다. (이 예제의 변수 값을 그대로 사용하지 마십시오.)\n+\n+JWT 토큰을 서명하는 데 사용될 알고리즘을 위한 변수 `ALGORITHM` 을 생성하고 `\"HS256\"` 으로 설정합니다.\n+\n+토큰 만료 기간을 위한 변수를 생성합니다.\n+\n+응답을 위한 토큰 엔드포인트에 사용될 Pydantic 모델을 정의합니다.\n+\n+새 액세스 토큰을 생성하기 위한 유틸리티 함수를 생성합니다.\n+\n+{* ../../docs_src/security/tutorial004_an_py310.py hl[4,7,13:15,29:31,79:87] *}\n+\n+## 의존성 수정\n+\n+`get_current_user` 함수를 이전과 동일한 토큰을 받도록 수정하되, 이번에는 JWT 토큰을 사용하도록 합니다.\n+\n+받은 토큰을 디코딩하여 검증한 후 현재 사용자를 반환합니다.\n+\n+토큰이 유효하지 않다면 HTTP 오류를 반환합니다.\n+\n+{* ../../docs_src/security/tutorial004_an_py310.py hl[90:107] *}\n+\n+## `/token` 경로 작업 수정\n+\n+토큰의 만료 시각을 설정하기 위해 `timedelta` 를 생성합니다.\n+\n+실제 JWT 액세스 토큰을 생성하여 반환합니다.\n+\n+{* ../../docs_src/security/tutorial004_an_py310.py hl[118:133] *}\n+\n+### JWT \"주체(subject)\" `sub`에 대한 기술 세부 사항\n+\n+JWT 명세에 따르면 토큰의 주체를 포함하는 `sub`라는 키가 있습니다.\n+\n+사용 여부는 선택사항이지만, 사용자의 식별 정보를 저장할 수 있으므로 여기서는 이를 사용합니다.\n+\n+JWT는 사용자를 식별하고 사용자가 API를 직접 사용할 수 있도록 허용하는 것 외에도 다른 용도로 사용될 수도 있습니다.\n+\n+예를 들어 \"자동차\"나 \"블로그 게시물\"을 식별하는 데 사용할 수 있습니다.\n+\n+그리고 \"자동차를 운전하다\"나 \"블로그 게시물을 수정하다\"처럼 해당 엔터티에 대한 권한을 추가할 수 있습니다.\n+\n+그 후 이 JWT 토큰을 사용자(또는 봇)에게 제공하면, 그들은 계정을 따로 만들 필요 없이 API가 생성한 JWT 토큰만으로 작업(자동차 운전 또는 블로그 게시물 편집)을 수행할 수 있습니다.\n+\n+이러한 개념을 활용하면 JWT는 훨씬 더 복잡한 시나리오에도 사용할 수 있습니다.\n+\n+이 경우 여러 엔터티가 동일한 ID를 가질 수 있습니다. 예를 들어 foo라는 ID를 가진 사용자, 자동차, 블로그 게시물이 있을 수 있습니다.\n+\n+그래서 ID 충돌을 방지하기 위해, 사용자의 JWT 토큰을 생성할 때 접두사로 `sub` 키를 추가할 수 있습니다. 예를 들어 `username:` 을 붙이는 방식입니다. 이 예제에서는 `sub` 값이 `username:johndoe`이 될 수 있습니다.\n+\n+가장 중요한 점은 `sub` 키는 전체 애플리케이션에서 고유한 식별자가 되어야 하며 문자열이어야 한다는 점입니다.\n+\n+## 확인해봅시다\n+\n+서버를 실행하고 문서로 이동하십시오: http://127.0.0.1:8000/docs.\n+\n+다음과 같은 사용자 인터페이스를 볼 수 있습니다:\n+\n+\n+\n+이전과 같은 방법으로 애플리케이션에 인증하십시오.\n+\n+다음 인증 정보를 사용하십시오:\n+\n+Username: `johndoe`\n+Password: `secret`\n+\n+/// check\n+\n+코드 어디에도 평문 패스워드 \"`secret`\" 이 없다는 점에 유의하십시오. 해시된 버전만 있습니다.\n+\n+///\n+\n+\n+\n+`/users/me/` 를 호출하면 다음과 같은 응답을 얻을 수 있습니다:\n+\n+```JSON\n+{\n+ \"username\": \"johndoe\",\n+ \"email\": \"[EMAIL_REDACTED]\",\n+ \"full_name\": \"[NAME_REDACTED]\",\n+ \"disabled\": false\n+}\n+```\n+\n+\n+\n+개발자 도구를 열어보면 전송된 데이터에 토큰만 포함된 것을 확인할 수 있습니다. 패스워드는 사용자를 인증하고 액세스 토큰을 받기 위한 첫 번째 요청에만 전송되며, 이후에는 전송되지 않습니다:\n+\n+\n+\n+/// note\n+\n+`Bearer `로 시작하는 `Authorization` 헤더에 주목하십시오.\n+\n+///\n+\n+## `scopes` 의 고급 사용법\n+\n+OAuth2는 \"스코프(scopes)\" 라는 개념을 갖고 있습니다.\n+\n+이를 사용하여 JWT 토큰에 특정 권한 집합을 추가할 수 있습니다.\n+\n+그 후 이 토큰을 사용자에게 직접 제공하거나 제3자에게 제공하여, 특정 제한사항 하에있는 API와 통신하도록 할 수 있습니다.\n+\n+**FastAPI** 에서의 사용 방법과 통합 방식은 **심화 사용자 안내서** 에서 자세히 배울 수 있습니다.\n+\n+## 요약\n+\n+지금까지 살펴본 내용을 바탕으로, OAuth2와 JWT 같은 표준을 사용하여 안전한 **FastAPI** 애플리케이션을 만들 수 있습니다.\n+\n+거의 모든 프레임워크에서 보안 처리는 상당히 복잡한 주제입니다.\n+\n+이를 단순화하는 많은 패키지는 데이터 모델, 데이터베이스, 사용 가능한 기능들에 대해 여러 제약이 있습니다. 그리고 지나치게 단순화하는 일부 패키지들은 심각한 보안 결함을 가질 수도 있습니다.\n+\n+---\n+\n+**FastAPI** 는 어떤 데이터베이스, 데이터 모델, 도구도 강요하지 않습니다.\n+\n+프로젝트에 가장 적합한 것을 선택할 수 있는 유연성을 제공합니다.\n+\n+그리고 `passlib` 와 `PyJWT` 처럼 잘 관리되고 널리 사용되는 패키지들을 바로 사용할 수 있습니다. **FastAPI** 는 외부 패키지 통합을 위해 복잡한 메커니즘이 필요하지 않기 때문입니다.\n+\n+그러나 유연성, 견고성, 보안성을 해치지 않으면서 과정을 단순화할 수 있는 도구들을 제공합니다.\n+\n+그리고 OAuth2와 같은 표준 프로토콜을 비교적 간단한 방법으로 구현하고 사용할 수 있습니다.\n+\n+더 세분화된 권한 체계를 위해 OAuth2의 \"스코프\"를 사용하는 방법은 **심화 사용자 안내서**에서 더 자세히 배울 수 있습니다. OAuth2의 스코프는 제3자 애플리케이션이 사용자를 대신해 그들의 API와 상호작용하도록 권한을 부여하기 위해, Facebook, Google, GitHub, Microsoft, Twitter 등의 많은 대형 인증 제공업체들이 사용하는 메커니즘입니다." } ], "reviews": [ { "id": 2605039757, "user": "user_a1942c3a9ec0", "state": "COMMENTED", "body": "What a huge document!", "submitted_at": "2025-02-10T09:32:48+00:00" }, { "id": 2609182478, "user": "user_dfad060db61c", "state": "COMMENTED", "body": null, "submitted_at": "2025-02-11T15:48:57+00:00" }, { "id": 2609215831, "user": "user_dfad060db61c", "state": "COMMENTED", "body": null, "submitted_at": "2025-02-11T15:58:56+00:00" }, { "id": 2609394812, "user": "user_dfad060db61c", "state": "COMMENTED", "body": null, "submitted_at": "2025-02-11T16:54:40+00:00" }, { "id": 2610590658, "user": "user_a1942c3a9ec0", "state": "APPROVED", "body": "LGTM 🚀", "submitted_at": "2025-02-12T01:22:40+00:00" }, { "id": 2625413397, "user": "user_08f3ccdc57a3", "state": "COMMENTED", "body": null, "submitted_at": "2025-02-19T01:20:04+00:00" }, { "id": 2625424174, "user": "user_08f3ccdc57a3", "state": "COMMENTED", "body": null, "submitted_at": "2025-02-19T01:25:04+00:00" }, { "id": 2625427900, "user": "user_08f3ccdc57a3", "state": "COMMENTED", "body": null, "submitted_at": "2025-02-19T01:28:58+00:00" }, { "id": 2625434759, "user": "user_08f3ccdc57a3", "state": "COMMENTED", "body": null, "submitted_at": "2025-02-19T01:36:12+00:00" }, { "id": 2625443632, "user": "user_08f3ccdc57a3", "state": "COMMENTED", "body": null, "submitted_at": "2025-02-19T01:46:04+00:00" }, { "id": 2625448437, "user": "user_08f3ccdc57a3", "state": "COMMENTED", "body": null, "submitted_at": "2025-02-19T01:51:12+00:00" }, { "id": 2625448706, "user": "user_08f3ccdc57a3", "state": "COMMENTED", "body": null, "submitted_at": "2025-02-19T01:51:30+00:00" }, { "id": 2625453104, "user": "user_08f3ccdc57a3", "state": "COMMENTED", "body": null, "submitted_at": "2025-02-19T01:56:13+00:00" }, { "id": 2625455301, "user": "user_08f3ccdc57a3", "state": "COMMENTED", "body": null, "submitted_at": "2025-02-19T01:58:30+00:00" }, { "id": 2625455513, "user": "user_08f3ccdc57a3", "state": "COMMENTED", "body": null, "submitted_at": "2025-02-19T01:58:44+00:00" }, { "id": 2625457706, "user": "user_08f3ccdc57a3", "state": "COMMENTED", "body": null, "submitted_at": "2025-02-19T02:01:05+00:00" }, { "id": 2625461344, "user": "user_08f3ccdc57a3", "state": "COMMENTED", "body": null, "submitted_at": "2025-02-19T02:05:12+00:00" }, { "id": 2625465171, "user": "user_08f3ccdc57a3", "state": "COMMENTED", "body": null, "submitted_at": "2025-02-19T02:09:30+00:00" }, { "id": 2625468700, "user": "user_08f3ccdc57a3", "state": "COMMENTED", "body": null, "submitted_at": "2025-02-19T02:13:13+00:00" }, { "id": 2625471376, "user": "user_08f3ccdc57a3", "state": "COMMENTED", "body": null, "submitted_at": "2025-02-19T02:16:14+00:00" }, { "id": 2625474335, "user": "user_08f3ccdc57a3", "state": "COMMENTED", "body": "hi. i left some comment for you. \nHere's a tip: when you've written a long sentence, read it out loud to yourself. Then you can find something awkward in yours.", "submitted_at": "2025-02-19T02:19:35+00:00" }, { "id": 2627185048, "user": "user_dfad060db61c", "state": "COMMENTED", "body": null, "submitted_at": "2025-02-19T15:28:40+00:00" }, { "id": 2627217114, "user": "user_dfad060db61c", "state": "COMMENTED", "body": null, "submitted_at": "2025-02-19T15:38:58+00:00" }, { "id": 2629959473, "user": "user_dfad060db61c", "state": "COMMENTED", "body": null, "submitted_at": "2025-02-20T14:02:16+00:00" }, { "id": 2633747987, "user": "user_dfad060db61c", "state": "COMMENTED", "body": null, "submitted_at": "2025-02-21T17:17:06+00:00" }, { "id": 2633750034, "user": "user_dfad060db61c", "state": "COMMENTED", "body": null, "submitted_at": "2025-02-21T17:18:08+00:00" }, { "id": 2633751701, "user": "user_dfad060db61c", "state": "COMMENTED", "body": null, "submitted_at": "2025-02-21T17:18:59+00:00" }, { "id": 2633753876, "user": "user_dfad060db61c", "state": "COMMENTED", "body": null, "submitted_at": "2025-02-21T17:19:44+00:00" }, { "id": 2633756815, "user": "user_dfad060db61c", "state": "COMMENTED", "body": null, "submitted_at": "2025-02-21T17:20:27+00:00" }, { "id": 2633766723, "user": "user_dfad060db61c", "state": "COMMENTED", "body": null, "submitted_at": "2025-02-21T17:23:12+00:00" }, { "id": 2660324359, "user": "user_08f3ccdc57a3", "state": "COMMENTED", "body": null, "submitted_at": "2025-03-05T08:29:51+00:00" }, { "id": 2660340980, "user": "user_08f3ccdc57a3", "state": "APPROVED", "body": "lgtm [USER_REDACTED] 👍\nsorry for late response im stuck irl\n\n문장이 훨씬 좋아졌네요!! 승인 늦어서 죄송해요ㅠㅠ 고생하셨습니다!", "submitted_at": "2025-03-05T08:36:46+00:00" } ], "review_comments": [ { "id": 1948613583, "user": "user_a1942c3a9ec0", "body": "just little change\n```suggestion\nJSON 객체를 공백이 없는 긴 문자열로 인코딩하는 표준이며, 다음과 같은 형태입니다:\n```", "path": "docs/ko/docs/tutorial/security/oauth2-jwt.md", "line": null, "side": "RIGHT", "created_at": "2025-02-10T08:49:16+00:00" }, { "id": 1948617859, "user": "user_a1942c3a9ec0", "body": "```suggestion\n일주일 뒤에는 토큰이 만료될 것이고, 사용자는 인가되지 않아 새 토큰을 받기 위해 다시 로그인해야 할 것입니다. 만약 사용자(또는 제3자)가 토큰을 수정하거나 만료일을 변경하면 서명이 일치하지 않아 알아챌 수 있을 것입니다.\n```\n\n\"be authorized\" is more like '인가' rather then '인증'", "path": "docs/ko/docs/tutorial/security/oauth2-jwt.md", "line": null, "side": "RIGHT", "created_at": "2025-02-10T08:51:49+00:00" }, { "id": 1948684958, "user": "user_a1942c3a9ec0", "body": "```suggestion\n### JWT \"주체(subject)\" `sub`에 대한 기술 세부 사항\n```\nin general \"subject\" can be translated to \"주제\" in korean, but when it comes to JWT it is more natural with \"주체\". because as this document says, sub contains 'user's identifier' its mean sub contains who owned this token\n\nmore solid [specification](https://datatracker.ietf.org/doc/html/rfc7519#section-4.1.2) is here, just for fun!", "path": "docs/ko/docs/tutorial/security/oauth2-jwt.md", "line": null, "side": "RIGHT", "created_at": "2025-02-10T09:15:51+00:00" }, { "id": 1948688887, "user": "user_a1942c3a9ec0", "body": "```suggestion\nJWT 명세에 따르면 토큰의 주체를 포함하는 `sub`라는 키가 있습니다.\n```", "path": "docs/ko/docs/tutorial/security/oauth2-jwt.md", "line": null, "side": "RIGHT", "created_at": "2025-02-10T09:18:24+00:00" }, { "id": 1948690322, "user": "user_a1942c3a9ec0", "body": "The meaning of subject is clarified as **'주체'** and preserving the meaning of **'there is'** in the original text.", "path": "docs/ko/docs/tutorial/security/oauth2-jwt.md", "line": null, "side": "RIGHT", "created_at": "2025-02-10T09:19:24+00:00" }, { "id": 1948704102, "user": "user_a1942c3a9ec0", "body": "```suggestion\n그 후 이 토큰을 사용자에게 직접 제공하거나 제3자에게 제공하여, 특정 제한사항 하에있는 API와 통신하도록 할 수 있습니다.\n```\nThe reason I changed the translation to \"특정 제한사항 하에있는 API\" is to avoid the potential misinterpretation that the restrictions are applied to the token itself, rather than to the API interaction.", "path": "docs/ko/docs/tutorial/security/oauth2-jwt.md", "line": null, "side": "RIGHT", "created_at": "2025-02-10T09:28:01+00:00" }, { "id": 1948707984, "user": "user_a1942c3a9ec0", "body": "```suggestion\n개발자 도구를 열어보면 전송된 데이터에 토큰만 포함된 것을 확인할 수 있습니다. 패스워드는 사용자 인증하고 액세스 토큰을 받기 위한 첫 번째 요청에만 전송되며, 이후에는 전송되지 않습니다:\n```", "path": "docs/ko/docs/tutorial/security/oauth2-jwt.md", "line": null, "side": "RIGHT", "created_at": "2025-02-10T09:30:34+00:00" }, { "id": 1948708748, "user": "user_a1942c3a9ec0", "body": "```suggestion\n다음과 같은 사용자 인터페이스를 볼 수 있습니다:\n```", "path": "docs/ko/docs/tutorial/security/oauth2-jwt.md", "line": null, "side": "RIGHT", "created_at": "2025-02-10T09:31:03+00:00" }, { "id": 1948709732, "user": "user_a1942c3a9ec0", "body": "```suggestion\n안전한 임의의 비밀 키를 생성하려면 다음 명령어를 사용하십시오:\n```", "path": "docs/ko/docs/tutorial/security/oauth2-jwt.md", "line": null, "side": "RIGHT", "created_at": "2025-02-10T09:31:36+00:00" }, { "id": 1948710308, "user": "user_a1942c3a9ec0", "body": "```suggestion\n[가상환경](../../virtual-environments.md){.internal-link target=_blank} 을 만들고 활성화한 다음 PassLib와 Bcrypt를 설치하십시오:\n```", "path": "docs/ko/docs/tutorial/security/oauth2-jwt.md", "line": null, "side": "RIGHT", "created_at": "2025-02-10T09:31:58+00:00" }, { "id": 1948710961, "user": "user_a1942c3a9ec0", "body": "```suggestion\n[가상환경](../../virtual-environments.md){.internal-link target=_blank} 을 만들고 활성화한 다음 `pyjwt` 를 설치하십시오:\n```", "path": "docs/ko/docs/tutorial/security/oauth2-jwt.md", "line": null, "side": "RIGHT", "created_at": "2025-02-10T09:32:19+00:00" }, { "id": 1951105432, "user": "user_dfad060db61c", "body": "Good point. I will accept your suggestion and change it to \"인가\"\nI mistakenly translated it as \"인증,\" focusing on the part where the user sign in again.", "path": "docs/ko/docs/tutorial/security/oauth2-jwt.md", "line": null, "side": "RIGHT", "created_at": "2025-02-11T15:48:57+00:00" }, { "id": 1951124142, "user": "user_dfad060db61c", "body": "Thank you for the great suggestion. It seems much easier to understand now.", "path": "docs/ko/docs/tutorial/security/oauth2-jwt.md", "line": null, "side": "RIGHT", "created_at": "2025-02-11T15:58:56+00:00" }, { "id": 1951227634, "user": "user_dfad060db61c", "body": "Thank you for the feedback. I have applied the suggested changes.\n\nI looked up the meanings of \"[주제](https://ko.dict.naver.com/#/entry/koko/13fe731acbee494d9af254a3f41e4a72\n)\" and \"[주체](https://ko.dict.naver.com/#/entry/koko/6c77c156f4e44b6d87a5a79b62ea5606)\" and I believe \"주체\" is more appropriate.\nAdditionally, I searched for how \"subject\" in JWT is commonly translated. But unfortunately, I couldn't find any other Korean documents.", "path": "docs/ko/docs/tutorial/security/oauth2-jwt.md", "line": null, "side": "RIGHT", "created_at": "2025-02-11T16:54:40+00:00" }, { "id": 1960810753, "user": "user_08f3ccdc57a3", "body": "there is some lost in translation\n```suggestion\n만약 JWT 토큰을 다뤄보고, 작동 방식도 알아보고 싶다면 https://jwt.io 을 확인하십시오.\n```", "path": "docs/ko/docs/tutorial/security/oauth2-jwt.md", "line": null, "side": "RIGHT", "created_at": "2025-02-19T01:20:04+00:00" }, { "id": 1960816784, "user": "user_08f3ccdc57a3", "body": "```suggestion\n추천하는 알고리즘은 \"Bcrypt\"입니다.\n```\nit sounds more naturally", "path": "docs/ko/docs/tutorial/security/oauth2-jwt.md", "line": null, "side": "RIGHT", "created_at": "2025-02-19T01:25:04+00:00" }, { "id": 1960819553, "user": "user_08f3ccdc57a3", "body": "```suggestion\n`passlib`를 사용하여, **Django**, **Flask** 의 보안 플러그인이나 다른 도구로 생성한 패스워드도 읽도록 설정할 수 있습니다.\n```", "path": "docs/ko/docs/tutorial/security/oauth2-jwt.md", "line": null, "side": "RIGHT", "created_at": "2025-02-19T01:28:57+00:00" }, { "id": 1960824242, "user": "user_08f3ccdc57a3", "body": "```suggestion\nPassLib 컨텍스트는 더 이상 사용되지 않는 오래된 알고리즘(※검증만 허용)을 포함해, 다른 해시 알고리즘을 사용하는 기능도 있습니다.\n```", "path": "docs/ko/docs/tutorial/security/oauth2-jwt.md", "line": null, "side": "RIGHT", "created_at": "2025-02-19T01:36:12+00:00" }, { "id": 1960830487, "user": "user_08f3ccdc57a3", "body": "```suggestion\n그리고 (그런 식으로 활용된) 모든 알고리즘과 동시에 호환되도록 만들 수 있습니다.\n```\nfixed lost in translation", "path": "docs/ko/docs/tutorial/security/oauth2-jwt.md", "line": null, "side": "RIGHT", "created_at": "2025-02-19T01:46:03+00:00" }, { "id": 1960833917, "user": "user_08f3ccdc57a3", "body": "```suggestion\n그리고 입력받은 패스워드가 저장된 해시와 일치하는지 검증하는 또 다른 유틸리티 함수도 생성합니다.\n```", "path": "docs/ko/docs/tutorial/security/oauth2-jwt.md", "line": null, "side": "RIGHT", "created_at": "2025-02-19T01:51:11+00:00" }, { "id": 1960834104, "user": "user_08f3ccdc57a3", "body": "```suggestion\n사용자로부터 입력받은 패스워드를 해싱하는 유틸리티 함수를 생성합니다.\n```", "path": "docs/ko/docs/tutorial/security/oauth2-jwt.md", "line": null, "side": "RIGHT", "created_at": "2025-02-19T01:51:30+00:00" }, { "id": 1960837241, "user": "user_08f3ccdc57a3", "body": "```suggestion\n새로운(가짜) 데이터베이스 `fake_users_db`를 확인하면, 해시 처리된 패스워드가 어떻게 생겼는지 확인할 수 있습니다.\n```\nfixed lost.\nmaybe it's better to read loudly irl.\n손실된 내용을 고쳤습니다.\n현실에서 소리내서 읽어보시는 걸 추천드려요.", "path": "docs/ko/docs/tutorial/security/oauth2-jwt.md", "line": null, "side": "RIGHT", "created_at": "2025-02-19T01:56:13+00:00" }, { "id": 1960838765, "user": "user_08f3ccdc57a3", "body": "```suggestion\n그리고 생성한 비밀키를 복사해 변수 `SECRET_KEY`에 대입합니다. (이 예제의 변수 값을 그대로 사용하지 마십시오.)\n```", "path": "docs/ko/docs/tutorial/security/oauth2-jwt.md", "line": null, "side": "RIGHT", "created_at": "2025-02-19T01:58:30+00:00" }, { "id": 1960838902, "user": "user_08f3ccdc57a3", "body": "```suggestion\nJWT 토큰 서명에 사용될 임의의 비밀키를 생성합니다.\n\n안전한 임의의 비밀키를 생성하려면 다음 명령어를 사용하십시오:\n```", "path": "docs/ko/docs/tutorial/security/oauth2-jwt.md", "line": null, "side": "RIGHT", "created_at": "2025-02-19T01:58:44+00:00" }, { "id": 1960840425, "user": "user_08f3ccdc57a3", "body": "```suggestion\n새 액세스 토큰을 생성하기 위한 유틸리티 함수를 생성합니다.\n```", "path": "docs/ko/docs/tutorial/security/oauth2-jwt.md", "line": null, "side": "RIGHT", "created_at": "2025-02-19T02:01:05+00:00" }, { "id": 1960843110, "user": "user_08f3ccdc57a3", "body": "```suggestion\n통신 엔드포인트에서 토큰 응답에 사용될 Pydantic 모델을 정의합니다.\n```", "path": "docs/ko/docs/tutorial/security/oauth2-jwt.md", "line": null, "side": "RIGHT", "created_at": "2025-02-19T02:05:11+00:00" }, { "id": 1960845747, "user": "user_08f3ccdc57a3", "body": "good. \n이 부분 번역 좋네요", "path": "docs/ko/docs/tutorial/security/oauth2-jwt.md", "line": null, "side": "RIGHT", "created_at": "2025-02-19T02:09:30+00:00" }, { "id": 1960848275, "user": "user_08f3ccdc57a3", "body": "```suggestion\n개발자 도구를 열어보면 전송된 데이터에 토큰만 포함된 것을 확인할 수 있습니다. 패스워드는 사용자 인증과 액세스 토큰을 받기 위한 첫 번째 요청에만 전송되며, 이후에는 전송되지 않습니다:\n```", "path": "docs/ko/docs/tutorial/security/oauth2-jwt.md", "line": null, "side": "RIGHT", "created_at": "2025-02-19T02:13:13+00:00" }, { "id": 1960850243, "user": "user_08f3ccdc57a3", "body": "```suggestion\n그리고 **FastAPI** 는 외부 패키지 통합을 위해 복잡한 메커니즘이 필요하지 않으므로, `passlib` 와 `PyJWT` 처럼 잘 관리되고 널리 사용되는 패키지들을 바로 사용할 수 있습니다.\n```", "path": "docs/ko/docs/tutorial/security/oauth2-jwt.md", "line": null, "side": "RIGHT", "created_at": "2025-02-19T02:16:13+00:00" }, { "id": 1961896689, "user": "user_dfad060db61c", "body": "I agree. Thank you for your help.", "path": "docs/ko/docs/tutorial/security/oauth2-jwt.md", "line": null, "side": "RIGHT", "created_at": "2025-02-19T15:28:40+00:00" }, { "id": 1961915659, "user": "user_dfad060db61c", "body": "I didn't think deeply and followed the English spacing. I'll fix it.", "path": "docs/ko/docs/tutorial/security/oauth2-jwt.md", "line": null, "side": "RIGHT", "created_at": "2025-02-19T15:38:58+00:00" }, { "id": 1963623770, "user": "user_dfad060db61c", "body": "I made a big mistake. I'll fix it. Thank you :)", "path": "docs/ko/docs/tutorial/security/oauth2-jwt.md", "line": null, "side": "RIGHT", "created_at": "2025-02-20T14:02:16+00:00" }, { "id": 1965903447, "user": "user_dfad060db61c", "body": "변경했습니다. 감사합니다. \n다만, 콤마 앞뒤로 `확인`이 두 번 나오니 부자연스러워서 `~ 볼 수 있습니다.`로 수정했습니다.", "path": "docs/ko/docs/tutorial/security/oauth2-jwt.md", "line": null, "side": "RIGHT", "created_at": "2025-02-21T17:17:05+00:00" }, { "id": 1965904672, "user": "user_dfad060db61c", "body": "수정했습니다. 원문에서 사용자 인증과 액세스 토큰 발급 둘 다 첫 번째 요청에서 이루어지는걸로 해석하였고, \n제안하신 내용 대신 `사용자를 인증하고 액세스 토큰을 받기 위한 첫 번째 요청` 으로 변경했습니다.", "path": "docs/ko/docs/tutorial/security/oauth2-jwt.md", "line": null, "side": "RIGHT", "created_at": "2025-02-21T17:18:08+00:00" }, { "id": 1965905796, "user": "user_dfad060db61c", "body": "`바로`가 더 적절하다는 데 동의하여 수정했습니다.\n그리고 다음 라인과의 연결성을 위해 콤마를 기준으로 두 문장으로 나누었습니다.", "path": "docs/ko/docs/tutorial/security/oauth2-jwt.md", "line": null, "side": "RIGHT", "created_at": "2025-02-21T17:18:59+00:00" }, { "id": 1965906671, "user": "user_dfad060db61c", "body": "원문 그대로 `토큰 엔드포인트`로 수정했습니다.", "path": "docs/ko/docs/tutorial/security/oauth2-jwt.md", "line": null, "side": "RIGHT", "created_at": "2025-02-21T17:19:44+00:00" }, { "id": 1965907653, "user": "user_dfad060db61c", "body": "감사합니다. ‘여러 알고리즘과 동시에 호환된다’기 보다는,\n앞 라인의 내용에 더해 ‘새 패스워드를 다른 알고리즘으로 해싱해도 호환된다’로 이해하여 약간 다른 방향으로 수정하였습니다.", "path": "docs/ko/docs/tutorial/security/oauth2-jwt.md", "line": null, "side": "RIGHT", "created_at": "2025-02-21T17:20:27+00:00" }, { "id": 1965910941, "user": "user_dfad060db61c", "body": "의견 주신대로 수정하였습니다.\n더불어, 문득 패스워드를 꼭 **입력**받는게 아닐수도 있겠다는 생각이 들어, `입력받은 패스워드` 대신 `받은 패스워드`로 변경했습니다. (원문도 a received password)", "path": "docs/ko/docs/tutorial/security/oauth2-jwt.md", "line": null, "side": "RIGHT", "created_at": "2025-02-21T17:23:12+00:00" }, { "id": 1980923197, "user": "user_08f3ccdc57a3", "body": "오 이게 훨씬 자연스러운거같아요! 고생하셨습니다", "path": "docs/ko/docs/tutorial/security/oauth2-jwt.md", "line": null, "side": "RIGHT", "created_at": "2025-03-05T08:29:51+00:00" } ], "meta": { "languages": [ "md" ], "touches_tests": false, "review_state_summary": { "COMMENTED": 30, "APPROVED": 2 }, "meaningful_comment_count": 39, "has_approval": true, "has_changes_requested": false, "total_review_comments": 39 } } { "_id": "15407a4fbf333b2b", "_schema_version": "1.0", "_cleaned_at": "2026-02-12T07:46:52.179504+00:00", "repo": "tiangolo/fastapi", "repo_url": "https://github.com/fastapi/fastapi", "license_name": "MIT License", "license_spdx": "MIT", "pr_number": 13330, "title": "🌐 Add Japanese translation for `docs/ja/docs/tutorial/cookie-param-models.md`", "body": "This PR is a translation of docs/ja/docs/tutorial/cookie-param-models.md. I'm Japanese.\n\nTranslating the cookie jokes was difficult. \nIn the `` tag sections, I kept the original text alongside the translation so both are displayed together.", "author": "user_e2ddc2fa3a94", "created_at": "2025-02-06T15:42:54+00:00", "merged_at": "2025-02-28T14:21:27+00:00", "base_branch": "master", "head_branch": "ja-cookie-param-models.md", "additions": 77, "deletions": 0, "changed_files": 1, "files": [ { "filename": "docs/ja/docs/tutorial/cookie-param-models.md", "status": "added", "additions": 77, "deletions": 0, "changes": 77, "patch": "@@ -0,0 +1,77 @@\n+# クッキーパラメータモデル\n+\n+もし関連する**複数のクッキー**から成るグループがあるなら、それらを宣言するために、**Pydanticモデル**を作成できます。🍪\n+\n+こうすることで、**複数の場所**で**そのPydanticモデルを再利用**でき、バリデーションやメタデータを、すべてのクッキーパラメータに対して一度に宣言できます。😎\n+\n+/// note | 備考\n+\n+この機能は、FastAPIのバージョン `0.115.0` からサポートされています。🤓\n+\n+///\n+\n+/// tip | 豆知識\n+\n+これと同じテクニックは `Query` 、 `Cookie` 、 `Header` にも適用できます。 😎\n+\n+///\n+\n+## クッキーにPydanticモデルを使用する\n+\n+必要な複数の**クッキー**パラメータを**Pydanticモデル**で宣言し、さらに、それを `Cookie` として宣言しましょう:\n+\n+{* ../../docs_src/cookie_param_models/tutorial001_an_py310.py hl[9:12,16] *}\n+\n+**FastAPI**は、リクエストの**クッキー**から**それぞれのフィールド**のデータを**抽出**し、定義された**Pydanticモデル**を提供します。\n+\n+## ドキュメントの確認\n+\n+対話的APIドキュメントUI `/docs` で、定義されているクッキーを確認できます:\n+\n+
      \n+\n+
      \n+\n+/// info | 備考\n+\n+\n+**ブラウザがクッキーを処理し**ていますが、特別な方法で内部的に処理を行っているために、**JavaScript**からは簡単に操作**できない**ことに留意してください。\n+\n+**対話的APIドキュメントUI** `/docs` にアクセスすれば、*パスオペレーション*に関するクッキーの**ドキュメンテーション**を確認できます。\n+\n+しかし、たとえ**クッキーデータを入力して**「Execute」をクリックしても、対話的APIドキュメントUIは**JavaScript**で動作しているためクッキーは送信されず、まるで値を入力しなかったかのような**エラー**メッセージが表示されます。\n+\n+///\n+\n+## 余分なクッキーを禁止する\n+\n+特定の(あまり一般的ではないかもしれない)ケースで、受け付けるクッキーを**制限**する必要があるかもしれません。\n+\n+あなたのAPIは独自の クッキー同意 を管理する能力を持っています。 🤪🍪\n+\n+Pydanticのモデルの Configuration を利用して、 `extra` フィールドを `forbid` とすることができます。\n+\n+{* ../../docs_src/cookie_param_models/tutorial002_an_py39.py hl[10] *}\n+\n+もしクライアントが**余分なクッキー**を送ろうとすると、**エラー**レスポンスが返されます。\n+\n+どうせAPIに拒否されるのにあなたの同意を得ようと精一杯努力する可哀想なクッキーバナーたち... 🍪\n+\n+例えば、クライアントがクッキー `santa_tracker` を `good-list-please` という値で送ろうとすると、`santa_tracker` という クッキーが許可されていない ことを通知する**エラー**レスポンスが返されます:\n+\n+```json\n+{\n+ \"detail\": [\n+ {\n+ \"type\": \"extra_forbidden\",\n+ \"loc\": [\"cookie\", \"santa_tracker\"],\n+ \"msg\": \"Extra inputs are not permitted\",\n+ \"input\": \"good-list-please\",\n+ }\n+ ]\n+}\n+```\n+\n+## まとめ\n+\n+**FastAPI**では、**クッキー**を宣言するために、**Pydanticモデル**を使用できます。😎" } ], "reviews": [ { "id": 2635487622, "user": "user_472f326cb34f", "state": "CHANGES_REQUESTED", "body": "Thank you for translating this document.\nThere are few type misses existing, but I think this is almost complete translating!", "submitted_at": "2025-02-23T09:31:26+00:00" }, { "id": 2637524318, "user": "user_e2ddc2fa3a94", "state": "COMMENTED", "body": null, "submitted_at": "2025-02-24T15:27:00+00:00" }, { "id": 2638696607, "user": "user_472f326cb34f", "state": "COMMENTED", "body": null, "submitted_at": "2025-02-24T23:29:14+00:00" }, { "id": 2638696894, "user": "user_472f326cb34f", "state": "APPROVED", "body": null, "submitted_at": "2025-02-24T23:29:29+00:00" }, { "id": 2638843145, "user": "user_37857fec7f20", "state": "APPROVED", "body": "Thank you for your good job!", "submitted_at": "2025-02-25T01:03:03+00:00" }, { "id": 2641059459, "user": "user_e2ddc2fa3a94", "state": "COMMENTED", "body": null, "submitted_at": "2025-02-25T13:23:25+00:00" }, { "id": 2641165488, "user": "user_472f326cb34f", "state": "APPROVED", "body": null, "submitted_at": "2025-02-25T13:58:41+00:00" }, { "id": 2650420609, "user": "user_84458f05cf3c", "state": "COMMENTED", "body": null, "submitted_at": "2025-02-28T10:55:58+00:00" }, { "id": 2650456571, "user": "user_e2ddc2fa3a94", "state": "COMMENTED", "body": null, "submitted_at": "2025-02-28T11:13:59+00:00" }, { "id": 2650890081, "user": "user_2a237e38e06b", "state": "APPROVED", "body": "Thank you [USER_REDACTED]! :cake: \n\nAnd thanks all for the reviews :coffee:", "submitted_at": "2025-02-28T14:19:48+00:00" } ], "review_comments": [ { "id": 1966721975, "user": "user_472f326cb34f", "body": "I think \"クッキーでも食べて'で'ください\" is type miss. As you said, Translating this joke is difficult...", "path": "docs/ja/docs/tutorial/cookie-param-models.md", "line": null, "side": "RIGHT", "created_at": "2025-02-23T09:27:46+00:00" }, { "id": 1966722372, "user": "user_472f326cb34f", "body": "I want to know why you translate this as \"モデルの configuration\", if you are okay.", "path": "docs/ja/docs/tutorial/cookie-param-models.md", "line": null, "side": "RIGHT", "created_at": "2025-02-23T09:30:00+00:00" }, { "id": 1967873297, "user": "user_e2ddc2fa3a94", "body": "I'm okay. In this context, 'configuration' refers to 'model_config' ([Configuration](https://docs.pydantic.dev/latest/api/config/#pydantic.config.ConfigDict.extra)) in Pydantic , so I thought it would be better not to translate the word. If I translated 'configuration' as '設定' or something similar, it might be harder to recognize that it refers to 'model_config'.", "path": "docs/ja/docs/tutorial/cookie-param-models.md", "line": null, "side": "RIGHT", "created_at": "2025-02-24T15:27:00+00:00" }, { "id": 1968570194, "user": "user_472f326cb34f", "body": "Thank you four your replying!\nI see. I think the \"configuration\" refers pydantic's Configuration, it acts as a proper noun phrase.\nSo it may be better to change to Uppercased first character(Configuration), and/or remove \"の\" before \"モデル\"(Pydanticモデルのconfiguration) , I think.\nBut I think keeping it as current one is not bad, too.", "path": "docs/ja/docs/tutorial/cookie-param-models.md", "line": null, "side": "RIGHT", "created_at": "2025-02-24T23:29:14+00:00" }, { "id": 1969777456, "user": "user_e2ddc2fa3a94", "body": "I agree with your suggestion and have changed 'configuration' to 'Configuration'. Thank you for your advice!", "path": "docs/ja/docs/tutorial/cookie-param-models.md", "line": null, "side": "RIGHT", "created_at": "2025-02-25T13:23:25+00:00" }, { "id": 1975216602, "user": "user_84458f05cf3c", "body": "[USER_REDACTED]: for each of the comments on this PR, if you have resolved them, could you mark them as such with the button \"Resolve conversation\"? This helps us see what the state of the PR is, and whether there are any open issues to address or not. Thanks!", "path": "docs/ja/docs/tutorial/cookie-param-models.md", "line": null, "side": "RIGHT", "created_at": "2025-02-28T10:55:58+00:00" }, { "id": 1975238778, "user": "user_e2ddc2fa3a94", "body": "[USER_REDACTED] Thank you for your message! I've marked them as resolved.", "path": "docs/ja/docs/tutorial/cookie-param-models.md", "line": null, "side": "RIGHT", "created_at": "2025-02-28T11:13:59+00:00" } ], "meta": { "languages": [ "md" ], "touches_tests": false, "review_state_summary": { "CHANGES_REQUESTED": 1, "COMMENTED": 5, "APPROVED": 4 }, "meaningful_comment_count": 7, "has_approval": true, "has_changes_requested": true, "total_review_comments": 7 } } { "_id": "cd29fad804820438", "_schema_version": "1.0", "_cleaned_at": "2026-02-12T07:46:52.179504+00:00", "repo": "tiangolo/fastapi", "repo_url": "https://github.com/fastapi/fastapi", "license_name": "MIT License", "license_spdx": "MIT", "pr_number": 13327, "title": "🌐 Add Russian translation for `docs/ru/docs/advanced/response-cookies.md`", "body": "…e-cookies.md", "author": "user_0cc05bcc4fb5", "created_at": "2025-02-06T07:46:25+00:00", "merged_at": "2025-02-15T11:15:23+00:00", "base_branch": "master", "head_branch": "docs", "additions": 48, "deletions": 0, "changed_files": 1, "files": [ { "filename": "docs/ru/docs/advanced/response-cookies.md", "status": "added", "additions": 48, "deletions": 0, "changes": 48, "patch": "@@ -0,0 +1,48 @@\n+\n+# Cookies в ответе\n+\n+## Использование параметра `Response`\n+\n+Вы можете объявить параметр типа `Response` в вашей функции эндпоинта.\n+\n+Затем установить cookies в этом временном объекте ответа.\n+\n+{* ../../docs_src/response_cookies/tutorial002.py hl[1, 8:9] *}\n+\n+После этого можно вернуть любой объект, как и раньше (например, `dict`, объект модели базы данных и так далее).\n+\n+Если вы указали `response_model`, он всё равно будет использоваться для фильтрации и преобразования возвращаемого объекта.\n+\n+**FastAPI** извлечет cookies (а также заголовки и коды состояния) из временного ответа и включит их в окончательный ответ, содержащий ваше возвращаемое значение, отфильтрованное через `response_model`.\n+\n+Вы также можете объявить параметр типа Response в зависимостях и устанавливать cookies (и заголовки) там.\n+\n+## Возвращение `Response` напрямую\n+\n+Вы также можете установить cookies, если возвращаете `Response` напрямую в вашем коде.\n+\n+Для этого создайте объект `Response`, как описано в разделе [Возвращение ответа напрямую](response-directly.md){.target=_blank}.\n+\n+Затем установите cookies и верните этот объект:\n+\n+{* ../../docs_src/response_cookies/tutorial001.py hl[10:12] *}\n+\n+/// tip | Примечание\n+Имейте в виду, что если вы возвращаете ответ напрямую, вместо использования параметра `Response`, **FastAPI** отправит его без дополнительной обработки.\n+\n+Убедитесь, что ваши данные имеют корректный тип. Например, они должны быть совместимы с JSON, если вы используете `JSONResponse`.\n+\n+Также убедитесь, что вы не отправляете данные, которые должны были быть отфильтрованы через `response_model`.\n+///\n+\n+### Дополнительная информация\n+\n+/// note | Технические детали\n+Вы также можете использовать `from starlette.responses import Response` или `from starlette.responses import JSONResponse`.\n+\n+**FastAPI** предоставляет `fastapi.responses`, которые являются теми же объектами, что и `starlette.responses`, просто для удобства. Однако большинство доступных типов ответов поступает непосредственно из **Starlette**.\n+\n+Для установки заголовков и cookies `Response` используется часто, поэтому **FastAPI** также предоставляет его через `fastapi.responses`.\n+///\n+\n+Чтобы увидеть все доступные параметры и настройки, ознакомьтесь с документацией Starlette." } ], "reviews": [ { "id": 2601414829, "user": "user_9e49ba0b4492", "state": "COMMENTED", "body": null, "submitted_at": "2025-02-07T11:05:03+00:00" }, { "id": 2601964781, "user": "user_9e49ba0b4492", "state": "COMMENTED", "body": null, "submitted_at": "2025-02-07T15:00:15+00:00" }, { "id": 2602029313, "user": "user_9e49ba0b4492", "state": "CHANGES_REQUESTED", "body": null, "submitted_at": "2025-02-07T15:22:26+00:00" }, { "id": 2602937509, "user": "user_568843bce6ca", "state": "COMMENTED", "body": null, "submitted_at": "2025-02-07T21:59:22+00:00" }, { "id": 2604127989, "user": "user_9e49ba0b4492", "state": "CHANGES_REQUESTED", "body": null, "submitted_at": "2025-02-09T07:52:35+00:00" }, { "id": 2604455879, "user": "user_df3ddbc43209", "state": "APPROVED", "body": "Good job", "submitted_at": "2025-02-09T20:54:02+00:00" }, { "id": 2604860638, "user": "user_9e49ba0b4492", "state": "CHANGES_REQUESTED", "body": null, "submitted_at": "2025-02-10T07:18:24+00:00" }, { "id": 2604925413, "user": "user_9e49ba0b4492", "state": "APPROVED", "body": null, "submitted_at": "2025-02-10T07:55:21+00:00" }, { "id": 2609122499, "user": "user_ab7b29c58fd5", "state": "APPROVED", "body": null, "submitted_at": "2025-02-11T15:28:43+00:00" }, { "id": 2609235855, "user": "user_6d7d83efab20", "state": "APPROVED", "body": null, "submitted_at": "2025-02-11T16:04:59+00:00" } ], "review_comments": [ { "id": 1946336210, "user": "user_9e49ba0b4492", "body": "Вместо \"функция обработки маршрута\", лучше использовать \"функция обработки пути\", \"функция эндпоинта\" или \"функция операции пути\".\nТак как в документации формулировка \"функция обработки маршрута\" нигде не встречается. А три других предложенных варианта встречаются в тех или иных уже переведенных разделах документации.", "path": "docs/ru/docs/advanced/response-cookies.md", "line": null, "side": "RIGHT", "created_at": "2025-02-07T10:47:03+00:00" }, { "id": 1946340246, "user": "user_9e49ba0b4492", "body": "Здесь можно опустить слова \"вы можете\", чтобы они не повторялись в каждом абзаце.", "path": "docs/ru/docs/advanced/response-cookies.md", "line": null, "side": "RIGHT", "created_at": "2025-02-07T10:50:12+00:00" }, { "id": 1946348051, "user": "user_9e49ba0b4492", "body": "Здесь неверно переведено.\nПравильнее будет:\n\"**FastAPI** извлечет cookies (а также заголовки и коды состояния) из временного ответа и включит их в окончательный ответ ...\"", "path": "docs/ru/docs/advanced/response-cookies.md", "line": null, "side": "RIGHT", "created_at": "2025-02-07T10:56:04+00:00" }, { "id": 1946357772, "user": "user_9e49ba0b4492", "body": "Для этих \"информационных окошек\" есть четкое правило как переводить:\n\n> You can translate info boxes like /// warning with for example /// warning | Achtung. But do not change the word immediately after the ///, it determines the color of the info box.\n\n[[NAME_REDACTED] - Contributing](https://fastapi.tiangolo.com/contributing/#translation-specific-tips-and-guidelines)", "path": "docs/ru/docs/advanced/response-cookies.md", "line": null, "side": "RIGHT", "created_at": "2025-02-07T11:03:51+00:00" }, { "id": 1946358714, "user": "user_9e49ba0b4492", "body": "Для этих \"информационных окошек\" есть четкое правило как переводить:\n\n> You can translate info boxes like /// warning with for example /// warning | Achtung. But do not change the word immediately after the ///, it determines the color of the info box.\n\n[[NAME_REDACTED] - Contributing](https://fastapi.tiangolo.com/contributing/#translation-specific-tips-and-guidelines)", "path": "docs/ru/docs/advanced/response-cookies.md", "line": null, "side": "RIGHT", "created_at": "2025-02-07T11:04:37+00:00" }, { "id": 1946663731, "user": "user_9e49ba0b4492", "body": "En документацию при переводе не стоит трогать", "path": "docs/en/docs/advanced/response-cookies.md", "line": null, "side": "RIGHT", "created_at": "2025-02-07T14:57:18+00:00" }, { "id": 1946700800, "user": "user_9e49ba0b4492", "body": "/// tip | Примечание", "path": "docs/ru/docs/advanced/response-cookies.md", "line": null, "side": "RIGHT", "created_at": "2025-02-07T15:20:10+00:00" }, { "id": 1947249184, "user": "user_568843bce6ca", "body": "Hi [USER_REDACTED], please revert this change. :sweat_smile:", "path": "docs/en/docs/advanced/response-cookies.md", "line": null, "side": "RIGHT", "created_at": "2025-02-07T21:59:22+00:00" }, { "id": 1948017168, "user": "user_9e49ba0b4492", "body": "## Использование параметра `Response`", "path": "docs/ru/docs/advanced/response-cookies.md", "line": null, "side": "RIGHT", "created_at": "2025-02-09T06:14:45+00:00" }, { "id": 1948017435, "user": "user_9e49ba0b4492", "body": "Вы можете объявить параметр типа `Response` в вашей *функции эндпоинта*.", "path": "docs/ru/docs/advanced/response-cookies.md", "line": 6, "side": "RIGHT", "created_at": "2025-02-09T06:16:42+00:00" }, { "id": 1948017558, "user": "user_9e49ba0b4492", "body": "Затем установить cookies в этом *временном* объекте ответа.", "path": "docs/ru/docs/advanced/response-cookies.md", "line": 8, "side": "RIGHT", "created_at": "2025-02-09T06:17:49+00:00" }, { "id": 1948018220, "user": "user_9e49ba0b4492", "body": "Вы также можете объявить параметр типа `Response` в зависимостях и устанавливать cookies (и заголовки) там.", "path": "docs/ru/docs/advanced/response-cookies.md", "line": null, "side": "RIGHT", "created_at": "2025-02-09T06:23:58+00:00" }, { "id": 1948018290, "user": "user_9e49ba0b4492", "body": "## Возвращение `Response` напрямую", "path": "docs/ru/docs/advanced/response-cookies.md", "line": null, "side": "RIGHT", "created_at": "2025-02-09T06:24:39+00:00" }, { "id": 1948502907, "user": "user_9e49ba0b4492", "body": "Для установки заголовков и cookies `Response` используется часто, поэтому **FastAPI** также предоставляет его через `fastapi.Response`.", "path": "docs/ru/docs/advanced/response-cookies.md", "line": null, "side": "RIGHT", "created_at": "2025-02-10T07:16:35+00:00" } ], "meta": { "languages": [ "md" ], "touches_tests": false, "review_state_summary": { "COMMENTED": 3, "CHANGES_REQUESTED": 3, "APPROVED": 4 }, "meaningful_comment_count": 14, "has_approval": true, "has_changes_requested": true, "total_review_comments": 14 } } { "_id": "f985147426838ea6", "_schema_version": "1.0", "_cleaned_at": "2026-02-12T07:46:52.179504+00:00", "repo": "tiangolo/fastapi", "repo_url": "https://github.com/fastapi/fastapi", "license_name": "MIT License", "license_spdx": "MIT", "pr_number": 13324, "title": "🌐 Update Chinese translation for `docs/zh/docs/deployment/manually.md`", "body": "Update zh translation for `docs/zh/docs/deployment/manually.md`.", "author": "user_6fcb07a75ce9", "created_at": "2025-02-04T22:40:06+00:00", "merged_at": "2025-03-31T08:14:47+00:00", "base_branch": "master", "head_branch": "translate/manually", "additions": 78, "deletions": 80, "changed_files": 1, "files": [ { "filename": "docs/zh/docs/deployment/manually.md", "status": "modified", "additions": 78, "deletions": 80, "changes": 158, "patch": "@@ -1,159 +1,157 @@\n-# 手动运行服务器 - Uvicorn\n+# 手动运行服务器\n \n-在远程服务器计算机上运行 **FastAPI** 应用程序所需的主要东西是 ASGI 服务器程序,例如 **Uvicorn**。\n+## 使用 `fastapi run` 命令\n \n-有 3 个主要可选方案:\n+简而言之,使用 `fastapi run` 来运行您的 FastAPI 应用程序:\n \n-* Uvicorn:高性能 ASGI 服务器。\n-* Hypercorn:与 HTTP/2 和 Trio 等兼容的 ASGI 服务器。\n-* Daphne:为 [NAME_REDACTED] 构建的 ASGI 服务器。\n-\n-## 服务器主机和服务器程序\n-\n-关于名称,有一个小细节需要记住。 💡\n-\n-“**服务器**”一词通常用于指远程/云计算机(物理机或虚拟机)以及在该计算机上运行的程序(例如 Uvicorn)。\n+
      \n \n-请记住,当您一般读到“服务器”这个名词时,它可能指的是这两者之一。\n+```console\n+$ fastapi run main.py\n \n-当提到远程主机时,通常将其称为**服务器**,但也称为**机器**(machine)、**VM**(虚拟机)、**节点**。 这些都是指某种类型的远程计算机,通常运行 Linux,您可以在其中运行程序。\n+ FastAPI Starting production server 🚀\n \n+ Searching for package file structure from directories\n+ with __init__.py files\n+ Importing from /home/user/code/awesomeapp\n \n-## 安装服务器程序\n+ module 🐍 main.py\n \n-您可以使用以下命令安装 ASGI 兼容服务器:\n+ code Importing the FastAPI app object from the module with\n+ the following code:\n \n-//// tab | Uvicorn\n+ from main import app\n \n-* Uvicorn,一个快如闪电 ASGI 服务器,基于 uvloop 和 httptools 构建。\n+ app Using import string: main:app\n \n-
      \n+ server Server started at http://0.0.0.0:8000\n+ server Documentation at http://0.0.0.0:8000/docs\n \n-```console\n-$ pip install \"uvicorn[standard]\"\n+ Logs:\n \n----> 100%\n+ INFO Started server process [2306215]\n+ INFO Waiting for application startup.\n+ INFO Application startup complete.\n+ INFO Uvicorn running on http://0.0.0.0:8000 (Press CTRL+C\n+ to quit)\n ```\n \n
      \n \n-/// tip\n+这在大多数情况下都能正常运行。😎\n \n-通过添加`standard`,Uvicorn 将安装并使用一些推荐的额外依赖项。\n+例如,您可以使用该命令在容器、服务器等环境中启动您的 **FastAPI** 应用。\n \n-其中包括`uvloop`,它是`asyncio`的高性能替代品,它提供了巨大的并发性能提升。\n+## ASGI 服务器\n \n-///\n+让我们深入了解一些细节。\n \n-////\n+FastAPI 使用了一种用于构建 [NAME_REDACTED] 框架和服务器的标准,称为 ASGI。FastAPI 本质上是一个 ASGI Web 框架。\n \n-//// tab | Hypercorn\n+要在远程服务器上运行 **FastAPI** 应用(或任何其他 ASGI 应用),您需要一个 ASGI 服务器程序,例如 **Uvicorn**。它是 `fastapi` 命令默认使用的 ASGI 服务器。\n \n-* Hypercorn,一个也与 HTTP/2 兼容的 ASGI 服务器。\n-\n-
      \n+除此之外,还有其他一些可选的 ASGI 服务器,例如:\n \n-```console\n-$ pip install hypercorn\n-\n----> 100%\n-```\n-\n-
      \n+* Uvicorn:高性能 ASGI 服务器。\n+* Hypercorn:与 HTTP/2 和 Trio 等兼容的 ASGI 服务器。\n+* Daphne:为 [NAME_REDACTED] 构建的 ASGI 服务器。\n+* Granian:基于 Rust 的 HTTP 服务器,专为 Python 应用设计。\n+* NGINX Unit:NGINX Unit 是一个轻量级且灵活的 Web 应用运行时环境。\n \n-...或任何其他 ASGI 服务器。\n+## 服务器主机和服务器程序\n \n-////\n+关于名称,有一个小细节需要记住。 💡\n \n-## 运行服务器程序\n+“**服务器**”一词通常用于指远程/云计算机(物理机或虚拟机)以及在该计算机上运行的程序(例如 Uvicorn)。\n \n-您可以按照之前教程中的相同方式运行应用程序,但不使用`--reload`选项,例如:\n+请记住,当您一般读到“服务器”这个名词时,它可能指的是这两者之一。\n \n-//// tab | Uvicorn\n+当提到远程主机时,通常将其称为**服务器**,但也称为**机器**(machine)、**VM**(虚拟机)、**节点**。 这些都是指某种类型的远程计算机,通常运行 Linux,您可以在其中运行程序。\n \n-
      \n \n-```console\n-$ uvicorn main:app --host 0.0.0.0 --port 80\n+## 安装服务器程序\n \n-INFO: Uvicorn running on http://0.0.0.0:80 (Press CTRL+C to quit)\n-```\n+当您安装 FastAPI 时,它自带一个生产环境服务器——Uvicorn,并且您可以使用 `fastapi run` 命令来启动它。\n \n-
      \n+不过,您也可以手动安装 ASGI 服务器。\n \n-////\n+请确保您创建并激活一个[虚拟环境](../virtual-environments.md){.internal-link target=_blank},然后再安装服务器应用程序。\n \n-//// tab | Hypercorn\n+例如,要安装 Uvicorn,可以运行以下命令:\n \n
      \n \n ```console\n-$ hypercorn main:app --bind 0.0.0.0:80\n+$ pip install \"uvicorn[standard]\"\n \n-Running on 0.0.0.0:8080 over http (CTRL + C to quit)\n+---> 100%\n ```\n \n
      \n \n-////\n+类似的流程也适用于任何其他 ASGI 服务器程序。\n \n-/// warning\n+/// tip\n \n-如果您正在使用`--reload`选项,请记住删除它。\n+通过添加 `standard` 选项,Uvicorn 将安装并使用一些推荐的额外依赖项。\n \n- `--reload` 选项消耗更多资源,并且更不稳定。\n+其中包括 `uvloop`,这是 `asyncio` 的高性能替代方案,能够显著提升并发性能。\n \n- 它在**开发**期间有很大帮助,但您**不应该**在**生产环境**中使用它。\n+当您使用 `pip install \"fastapi[standard]\"` 安装 FastAPI 时,实际上也会安装 `uvicorn[standard]`。\n \n ///\n \n-## Hypercorn with Trio\n-\n-Starlette 和 **FastAPI** 基于 AnyIO, 所以它们才能同时与 Python 的标准库 asyncioTrio 兼容。\n-\n-尽管如此,Uvicorn 目前仅与 asyncio 兼容,并且通常使用 `uvloop`, 它是`asyncio`的高性能替代品。\n-\n-但如果你想直接使用**Trio**,那么你可以使用**Hypercorn**,因为它支持它。 ✨\n-\n-### 安装具有 Trio 的 Hypercorn\n+## 运行服务器程序\n \n-首先,您需要安装具有 Trio 支持的 Hypercorn:\n+如果您手动安装了 ASGI 服务器,通常需要以特定格式传递一个导入字符串,以便服务器能够正确导入您的 FastAPI 应用:\n \n
      \n \n ```console\n-$ pip install \"hypercorn[trio]\"\n----> 100%\n+$ uvicorn main:app --host 0.0.0.0 --port 80\n+\n+INFO: Uvicorn running on http://0.0.0.0:80 (Press CTRL+C to quit)\n ```\n \n
      \n \n-### Run with Trio\n+/// note\n \n-然后你可以传递值`trio`给命令行选项`--worker-class`:\n+命令 `uvicorn main:app` 的含义如下:\n \n-
      \n+* `main`:指的是 `main.py` 文件(即 Python “模块”)。\n+* `app`:指的是 `main.py` 文件中通过 `app = FastAPI()` 创建的对象。\n \n-```console\n-$ hypercorn main:app --worker-class trio\n+它等价于以下导入语句:\n+\n+```Python\n+from main import app\n ```\n \n-
      \n+///\n+\n+每种 ASGI 服务器程序通常都会有类似的命令,您可以在它们的官方文档中找到更多信息。\n+\n+/// warning\n+\n+Uvicorn 和其他服务器支持 `--reload` 选项,该选项在开发过程中非常有用。\n \n-这将通过您的应用程序启动 Hypercorn,并使用 Trio 作为后端。\n+但 `--reload` 选项会消耗更多资源,且相对不稳定。\n \n-现在您可以在应用程序内部使用 Trio。 或者更好的是,您可以使用 AnyIO,使您的代码与 Trio 和 asyncio 兼容。 🎉\n+它对于**开发阶段**非常有帮助,但在**生产环境**中**不应该**使用。\n+\n+///\n \n ## 部署概念\n \n-这些示例运行服务器程序(例如 Uvicorn),启动**单个进程**,在所有 IP(`0.0.0.0`)上监听预定义端口(例如`80`)。\n+这些示例运行服务器程序(例如 Uvicorn),启动**单个进程**,在所有 IP(`0.0.0.0`)上监听预定义端口(例如`80`)。\n \n 这是基本思路。 但您可能需要处理一些其他事情,例如:\n \n * 安全性 - HTTPS\n * 启动时运行\n * 重新启动\n-* Replication(运行的进程数)\n+* 复制(运行的进程数)\n * 内存\n * 开始前的步骤" } ], "reviews": [ { "id": 2710499369, "user": "user_d7f5981f1dc1", "state": "APPROVED", "body": "Missed a part in the translation, the rest looks good to me.", "submitted_at": "2025-03-24T14:04:46+00:00" }, { "id": 2728251290, "user": "user_500626e531fe", "state": "APPROVED", "body": null, "submitted_at": "2025-03-31T05:04:19+00:00" } ], "review_comments": [ { "id": 2010244442, "user": "user_d7f5981f1dc1", "body": "您此处漏翻了", "path": "docs/zh/docs/deployment/manually.md", "line": null, "side": "RIGHT", "created_at": "2025-03-24T14:00:12+00:00" } ], "meta": { "languages": [ "md" ], "touches_tests": false, "review_state_summary": { "APPROVED": 2 }, "meaningful_comment_count": 0, "has_approval": true, "has_changes_requested": false, "total_review_comments": 1 } } { "_id": "6fe3302c01dd0d2f", "_schema_version": "1.0", "_cleaned_at": "2026-02-12T07:46:52.179504+00:00", "repo": "tiangolo/fastapi", "repo_url": "https://github.com/fastapi/fastapi", "license_name": "MIT License", "license_spdx": "MIT", "pr_number": 13317, "title": "🌐 Update Portuguese Translation for `docs/pt/docs/deployment/https.md`", "body": null, "author": "user_8935aac7e330", "created_at": "2025-02-03T17:43:31+00:00", "merged_at": "2025-02-07T22:03:00+00:00", "base_branch": "master", "head_branch": "docs/update-https", "additions": 171, "deletions": 23, "changed_files": 1, "files": [ { "filename": "docs/pt/docs/deployment/https.md", "status": "modified", "additions": 171, "deletions": 23, "changes": 194, "patch": "@@ -14,38 +14,186 @@ Para aprender o básico de HTTPS de uma perspectiva do usuário, verifique SNI.\n- * Esta extensão SNI permite que um único servidor (com um único endereço IP) tenha vários certificados HTTPS e atenda a vários domínios / aplicativos HTTPS.\n- * Para que isso funcione, um único componente (programa) em execução no servidor, ouvindo no endereço IP público, deve ter todos os certificados HTTPS no servidor.\n-* Depois de obter uma conexão segura, o protocolo de comunicação ainda é HTTP.\n- * Os conteúdos são criptografados, embora sejam enviados com o protocolo HTTP.\n+ * No entanto, existe uma **solução** para isso.\n+* Há uma **extensão** para o protocolo **TLS** (aquele que lida com a criptografia no nível TCP, antes do HTTP) chamado **SNI**.\n+ * Esta extensão SNI permite que um único servidor (com um **único endereço IP**) tenha **vários certificados HTTPS** e atenda a **vários domínios / aplicativos HTTPS**.\n+ * Para que isso funcione, um **único** componente (programa) em execução no servidor, ouvindo no **endereço IP público**, deve ter **todos os certificados HTTPS** no servidor.\n+* **Depois** de obter uma conexão segura, o protocolo de comunicação **ainda é HTTP**.\n+ * Os conteúdos são **criptografados**, embora sejam enviados com o **protocolo HTTP**.\n \n-É uma prática comum ter um programa/servidor HTTP em execução no servidor (máquina, host, etc.) e gerenciar todas as partes HTTPS: enviando as solicitações HTTP descriptografadas para o aplicativo HTTP real em execução no mesmo servidor (a aplicação **FastAPI**, neste caso), pegue a resposta HTTP do aplicativo, criptografe-a usando o certificado apropriado e envie-a de volta ao cliente usando HTTPS. Este servidor é frequentemente chamado de TLS [NAME_REDACTED].\n+É uma prática comum ter um **programa/servidor HTTP** em execução no servidor (máquina, host, etc.) e **gerenciar todas as partes HTTPS**: **recebendo as requisições encriptadas**, enviando as **solicitações HTTP descriptografadas** para o aplicativo HTTP real em execução no mesmo servidor (a aplicação **FastAPI**, neste caso), pegue a **resposta HTTP** do aplicativo, **criptografe-a** usando o **certificado HTTPS** apropriado e envie-a de volta ao cliente usando **HTTPS**. Este servidor é frequentemente chamado de **Proxy de Terminação TLS**.\n+\n+Algumas das opções que você pode usar como Proxy de Terminação TLS são:\n+\n+* Traefik (que também pode gerenciar a renovação de certificados)\n+* Caddy (que também pode gerenciar a renovação de certificados)\n+* Nginx\n+* HAProxy\n \n ## [NAME_REDACTED]\n \n-Antes de [NAME_REDACTED], esses certificados HTTPS eram vendidos por terceiros confiáveis.\n+Antes de [NAME_REDACTED], esses **certificados HTTPS** eram vendidos por terceiros confiáveis.\n \n O processo de aquisição de um desses certificados costumava ser complicado, exigia bastante papelada e os certificados eram bastante caros.\n \n-Mas então [NAME_REDACTED] foi criado.\n+Mas então o **[NAME_REDACTED]** foi criado.\n \n-Ele é um projeto da [NAME_REDACTED] que fornece certificados HTTPS gratuitamente. De forma automatizada. Esses certificados usam toda a segurança criptográfica padrão e têm vida curta (cerca de 3 meses), então a segurança é realmente melhor por causa de sua vida útil reduzida.\n+Ele é um projeto da [NAME_REDACTED] que fornece **certificados HTTPS gratuitamente** . De forma automatizada. Esses certificados usam toda a segurança criptográfica padrão e têm vida curta (cerca de 3 meses), então a **segurança é, na verdade, melhor** por causa de sua vida útil reduzida.\n \n Os domínios são verificados com segurança e os certificados são gerados automaticamente. Isso também permite automatizar a renovação desses certificados.\n \n-A ideia é automatizar a aquisição e renovação desses certificados, para que você tenha HTTPS seguro, de graça e para sempre.\n+A ideia é automatizar a aquisição e renovação desses certificados, para que você tenha **HTTPS seguro, de graça e para sempre**.\n+\n+## HTTPS para Desenvolvedores\n+\n+Aqui está um exemplo de como uma API HTTPS poderia ser estruturada, passo a passo, com foco principal nas ideias relevantes para desenvolvedores.\n+\n+### Nome do domínio\n+\n+A etapa inicial provavelmente seria **adquirir** algum **nome de domínio**. Então, você iria configurá-lo em um servidor DNS (possivelmente no mesmo provedor em nuvem).\n+\n+Você provavelmente usaria um servidor em nuvem (máquina virtual) ou algo parecido, e ele teria fixed **Endereço IP público**.\n+\n+No(s) servidor(es) DNS, você configuraria um registro (`registro A`) para apontar **seu domínio** para o **endereço IP público do seu servidor**.\n+\n+Você provavelmente fará isso apenas uma vez, na primeira vez em que tudo estiver sendo configurado.\n+\n+/// tip | Dica\n+\n+Essa parte do Nome do Domínio se dá muito antes do HTTPS, mas como tudo depende do domínio e endereço IP público, vale a pena mencioná-la aqui.\n+\n+///\n+\n+### DNS\n+\n+Agora vamos focar em todas as partes que realmente fazem parte do HTTPS.\n+\n+Primeiro, o navegador iria verificar com os **servidores DNS** qual o **IP do domínio**, nesse caso, `someapp.example.com`.\n+\n+Os servidores DNS iriam informar o navegador para utilizar algum **endereço IP** específico. Esse seria o endereço IP público em uso no seu servidor, que você configurou nos servidores DNS.\n+\n+\n+\n+### Início do Handshake TLS\n+\n+O navegador então irá comunicar-se com esse endereço IP na **porta 443** (a porta HTTPS).\n+\n+A primeira parte dessa comunicação é apenas para estabelecer a conexão entre o cliente e o servidor e para decidir as chaves criptográficas a serem utilizadas, etc.\n+\n+\n+\n+Esse interação entre o cliente e o servidor para estabelecer uma conexão TLS é chamada de **Handshake TLS**.\n+\n+### TLS com a Extensão SNI\n+\n+**Apenas um processo** no servidor pode se conectar a uma **porta** em um **endereço IP**. Poderiam existir outros processos conectados em outras portas desse mesmo endereço IP, mas apenas um para cada combinação de endereço IP e porta.\n+\n+TLS (HTTPS) usa a porta `443` por padrão. Então essa é a porta que precisamos.\n+\n+Como apenas um único processo pode se comunicar com essa porta, o processo que faria isso seria o **Proxy de Terminação TLS**.\n+\n+O Proxy de Terminação TLS teria acesso a um ou mais **certificados TLS** (certificados HTTPS).\n+\n+Utilizando a **extensão SNI** discutida acima, o Proxy de Terminação TLS iria checar qual dos certificados TLS (HTTPS) disponíveis deve ser usado para essa conexão, utilizando o que corresponda ao domínio esperado pelo cliente.\n+\n+Nesse caso, ele usaria o certificado para `someapp.example.com`.\n+\n+\n+\n+O cliente já **confia** na entidade que gerou o certificado TLS (nesse caso, o [NAME_REDACTED], mas veremos sobre isso mais tarde), então ele pode **verificar** que o certificado é válido.\n+\n+Então, utilizando o certificado, o cliente e o Proxy de Terminação TLS **decidem como encriptar** o resto da **comunicação TCP**. Isso completa a parte do **Handshake TLS**.\n+\n+Após isso, o cliente e o servidor possuem uma **conexão TCP encriptada**, que é provida pelo TLS. E então eles podem usar essa conexão para começar a **comunicação HTTP** propriamente dita.\n+\n+E isso resume o que é **HTTPS**, apenas **HTTP** simples dentro de uma **conexão TLS segura** em vez de uma conexão TCP pura (não encriptada).\n+\n+/// tip | Dica\n+\n+Percebe que a encriptação da comunicação acontece no **nível do TCP**, não no nível do HTTP.\n+\n+///\n+\n+### Solicitação HTTPS\n+\n+Agora que o cliente e servidor (especialmente o navegador e o Proxy de Terminação TLS) possuem uma **conexão TCP encriptada**, eles podem iniciar a **comunicação HTTP**.\n+\n+Então, o cliente envia uma **solicitação HTTPS**. Que é apenas uma solicitação HTTP sobre uma conexão TLS encriptada.\n+\n+\n+\n+### Desencriptando a Solicitação\n+\n+O Proxy de Terminação TLS então usaria a encriptação combinada para **desencriptar a solicitação**, e transmitiria a **solicitação básica (desencriptada)** para o processo executando a aplicação (por exemplo, um processo com Uvicorn executando a aplicação FastAPI).\n+\n+\n+\n+### Resposta HTTP\n+\n+A aplicação processaria a solicitação e retornaria uma **resposta HTTP básica (não encriptada)** para o Proxy de Terminação TLS.\n+\n+\n+\n+### Resposta HTTPS\n+\n+O Proxy de Terminação TLS iria **encriptar a resposta** utilizando a criptografia combinada anteriormente (que foi definida com o certificado para `someapp.example.com`), e devolveria para o navegador.\n+\n+No próximo passo, o navegador verifica que a resposta é válida e encriptada com a chave criptográfica correta, etc. E depois **desencripta a resposta** e a processa.\n+\n+\n+\n+O cliente (navegador) saberá que a resposta vem do servidor correto por que ela usa a criptografia que foi combinada entre eles usando o **certificado HTTPS** anterior.\n+\n+### Múltiplas Aplicações\n+\n+Podem existir **múltiplas aplicações** em execução no mesmo servidor (ou servidores), por exemplo: outras APIs ou um banco de dados.\n+\n+Apenas um processo pode estar vinculado a um IP e porta (o Proxy de Terminação TLS, por exemplo), mas outras aplicações/processos também podem estar em execução no(s) servidor(es), desde que não tentem usar a mesma **combinação de IP público e porta**.\n+\n+\n+\n+Dessa forma, o Proxy de Terminação TLS pode gerenciar o HTTPS e os certificados de **múltiplos domínios**, para múltiplas aplicações, e então transmitir as requisições para a aplicação correta em cada caso.\n+\n+### Renovação de Certificados\n+\n+Em algum momento futuro, cada certificado irá **expirar** (aproximadamente 3 meses após a aquisição).\n+\n+E então, haverá outro programa (em alguns casos pode ser o próprio Proxy de Terminação TLS) que irá interagir com o [NAME_REDACTED] e renovar o(s) certificado(s).\n+\n+\n+\n+Os **certificados TLS** são **associados com um nome de domínio**, e não a um endereço IP.\n+\n+Então para renovar os certificados, o programa de renovação precisa **provar** para a autoridade ([NAME_REDACTED]) que ele realmente **possui e controla esse domínio**>\n+\n+Para fazer isso, e acomodar as necessidades de diferentes aplicações, existem diferentes opções para esse programa. Algumas escolhas populares são:\n+\n+* **Modificar alguns registros DNS**\n+ * Para isso, o programa de renovação precisa ter suporte as APIs do provedor DNS, então, dependendo do provedor DNS que você utilize, isso pode ou não ser uma opção viável.\n+* **Executar como um servidor** (ao menos durante o processo de aquisição do certificado) no endereço IP público associado com o domínio.\n+ * Como dito anteriormente, apenas um processo pode estar ligado a uma porta e IP específicos.\n+ * Essa é uma dos motivos que fazem utilizar o mesmo Proxy de Terminação TLS para gerenciar a renovação de certificados ser tão útil.\n+ * Caso contrário, você pode ter que parar a execução do Proxy de Terminação TLS momentaneamente, inicializar o programa de renovação para renovar os certificados, e então reiniciar o Proxy de Terminação TLS. Isso não é o ideal, já que sua(s) aplicação(ões) não vão estar disponíveis enquanto o Proxy de Terminação TLS estiver desligado.\n+\n+Todo esse processo de renovação, enquanto o aplicativo ainda funciona, é uma das principais razões para preferir um **sistema separado para gerenciar HTTPS** com um Proxy de Terminação TLS em vez de usar os certificados TLS no servidor da aplicação diretamente (e.g. com o Uvicorn).\n+\n+## Recapitulando\n+\n+Possuir **HTTPS** habilitado na sua aplicação é bastante importante, e até **crítico** na maioria dos casos. A maior parte do esforço que você tem que colocar sobre o HTTPS como desenvolvedor está em **entender esses conceitos** e como eles funcionam.\n+\n+Mas uma vez que você saiba o básico de **HTTPS para desenvolvedores**, você pode combinar e configurar diferentes ferramentas facilmente para gerenciar tudo de uma forma simples.\n+\n+Em alguns dos próximos capítulos, eu mostrarei para você vários exemplos concretos de como configurar o **HTTPS** para aplicações **FastAPI**. 🔒" } ], "reviews": [ { "id": 2592089201, "user": "user_e10da7d15f57", "state": "APPROVED", "body": null, "submitted_at": "2025-02-04T08:33:09+00:00" }, { "id": 2595324602, "user": "user_178cb4401e94", "state": "APPROVED", "body": "Really great [USER_REDACTED] 😎 \n\nJust one silly suggestion :D", "submitted_at": "2025-02-05T11:08:33+00:00" }, { "id": 2598377714, "user": "user_178cb4401e94", "state": "APPROVED", "body": "🚀", "submitted_at": "2025-02-06T11:17:25+00:00" } ], "review_comments": [ { "id": 1942660354, "user": "user_178cb4401e94", "body": "I think it sounds a little strange without the article.\n\nI prefer to translate as \"Mas então **o** [NAME_REDACTED]...\"\n\nBut it's not wrong, it's just a suggestion 🤓", "path": "docs/pt/docs/deployment/https.md", "line": null, "side": "RIGHT", "created_at": "2025-02-05T10:57:39+00:00" }, { "id": 1942673252, "user": "user_178cb4401e94", "body": "I think you accidentally hit enter here :D\n\n![emoji](https://github.com/[USER_REDACTED]nts/assets/db42ba39-81cf-4463-9c21-5436f09add48)", "path": "docs/pt/docs/deployment/https.md", "line": null, "side": "RIGHT", "created_at": "2025-02-05T11:07:23+00:00" } ], "meta": { "languages": [ "md" ], "touches_tests": false, "review_state_summary": { "APPROVED": 3 }, "meaningful_comment_count": 2, "has_approval": true, "has_changes_requested": false, "total_review_comments": 2 } } { "_id": "725dafca070b3061", "_schema_version": "1.0", "_cleaned_at": "2026-02-12T07:46:52.179504+00:00", "repo": "tiangolo/fastapi", "repo_url": "https://github.com/fastapi/fastapi", "license_name": "MIT License", "license_spdx": "MIT", "pr_number": 13304, "title": "🌐 Add Japanese translation for `docs/ja/docs/virtual-environments.md`", "body": "This PR is a translation of virtual-environments.md. I'm Japanese.", "author": "user_e2ddc2fa3a94", "created_at": "2025-02-01T17:39:19+00:00", "merged_at": "2025-03-19T12:22:33+00:00", "base_branch": "master", "head_branch": "ja-virtual-environments.md", "additions": 831, "deletions": 0, "changed_files": 1, "files": [ { "filename": "docs/ja/docs/virtual-environments.md", "status": "added", "additions": 831, "deletions": 0, "changes": 831, "patch": "@@ -0,0 +1,831 @@\n+# 仮想環境\n+\n+Pythonプロジェクトの作業では、**仮想環境**(または類似の仕組み)を使用し、プロジェクトごとにインストールするパッケージを分離するべきでしょう。\n+\n+/// info | 情報\n+\n+もし、仮想環境の概要や作成方法、使用方法について既にご存知なら、このセクションをスキップすることができます。🤓\n+\n+///\n+\n+/// tip | 豆知識\n+\n+**仮想環境**は、**環境変数**とは異なります。\n+\n+**環境変数**は、プログラムが使用できるシステム内の変数です。\n+\n+**仮想環境**は、ファイルをまとめたディレクトリのことです。\n+\n+///\n+\n+/// info | 情報\n+このページでは、**仮想環境**の使用方法と、そのはたらきについて説明します。\n+\n+もし**すべてを管理するツール**(Pythonのインストールも含む)を導入する準備ができているなら、uv をお試しください。\n+\n+///\n+\n+## プロジェクトの作成\n+\n+まず、プロジェクト用のディレクトリを作成します。\n+\n+私は通常 home/user ディレクトリの中に `code` というディレクトリを用意していて、プロジェクトごとに1つのディレクトリをその中に作成しています。\n+\n+
      \n+\n+```console\n+// Go to the home directory\n+$ cd\n+// Create a directory for all your code projects\n+$ mkdir code\n+// Enter into that code directory\n+$ cd code\n+// Create a directory for this project\n+$ mkdir awesome-project\n+// Enter into that project directory\n+$ cd awesome-project\n+```\n+\n+
      \n+\n+## 仮想環境の作成\n+\n+Pythonプロジェクトでの**初めての**作業を開始する際には、**プロジェクト内**に仮想環境を作成してください。\n+\n+/// tip | 豆知識\n+\n+これを行うのは、**プロジェクトごとに1回だけ**です。作業のたびに行う必要はありません。\n+\n+///\n+\n+//// tab | `venv`\n+\n+仮想環境を作成するには、Pythonに付属している `venv` モジュールを使用できます。\n+\n+
      \n+\n+```console\n+$ python -m venv .venv\n+```\n+\n+
      \n+\n+/// details | このコマンドの意味\n+\n+- `python` : `python` というプログラムを呼び出します\n+- `-m` : モジュールをスクリプトとして呼び出します。どのモジュールを呼び出すのか、この次に指定します\n+- `venv` : 通常Pythonに付随してインストールされる `venv`モジュールを使用します\n+- `.venv` : 仮想環境を`.venv`という新しいディレクトリに作成します\n+\n+///\n+\n+////\n+\n+//// tab | `uv`\n+\n+もし `uv` をインストール済みなら、仮想環境を作成するために `uv` を使うこともできます。\n+\n+
      \n+\n+```console\n+$ uv venv\n+```\n+\n+
      \n+\n+/// tip | 豆知識\n+\n+デフォルトでは、 `uv` は `.venv` というディレクトリに仮想環境を作成します。\n+\n+ただし、追加の引数にディレクトリ名を与えてカスタマイズすることもできます。\n+\n+///\n+\n+////\n+\n+このコマンドは `.venv` というディレクトリに新しい仮想環境を作成します。\n+\n+/// details | `.venv` またはその他の名前\n+\n+仮想環境を別のディレクトリに作成することも可能ですが、 `.venv` と名付けるのが一般的な慣習です。\n+\n+///\n+\n+## 仮想環境の有効化\n+\n+実行されるPythonコマンドやインストールされるパッケージが新しく作成した仮想環境を使用するよう、その仮想環境を有効化しましょう。\n+\n+/// tip | 豆知識\n+\n+そのプロジェクトの作業で**新しいターミナルセッション**を開始する際には、**毎回**有効化が必要です。\n+\n+///\n+\n+//// tab | Linux, macOS\n+\n+
      \n+\n+```console\n+$ source .venv/bin/activate\n+```\n+\n+
      \n+\n+////\n+\n+//// tab | [NAME_REDACTED]\n+\n+
      \n+\n+```console\n+$ .venv\\Scripts\\Activate.ps1\n+```\n+\n+
      \n+\n+////\n+\n+//// tab | [NAME_REDACTED]\n+\n+もしWindowsでBashを使用している場合 ([NAME_REDACTED]など):\n+\n+
      \n+\n+```console\n+$ source .venv/Scripts/activate\n+```\n+\n+
      \n+\n+////\n+\n+/// tip | 豆知識\n+\n+**新しいパッケージ**を仮想環境にインストールするときには、再度**有効化**してください。\n+\n+こうすることで、そのパッケージがインストールした**ターミナル(CLI)プログラム**を使用する場合に、仮想環境内のものが確実に使われ、グローバル環境にインストールされている別のもの(おそらく必要なものとは異なるバージョン)を誤って使用することを防ぎます。\n+\n+///\n+\n+## 仮想環境が有効であることを確認する\n+\n+仮想環境が有効である(前のコマンドが正常に機能した)ことを確認します。\n+\n+/// tip | 豆知識\n+\n+これは**任意**ですが、すべてが期待通りに機能し、意図した仮想環境を使用していることを**確認する**良い方法です。\n+\n+///\n+\n+//// tab | Linux, macOS, [NAME_REDACTED]\n+\n+
      \n+\n+```console\n+$ which python\n+\n+/home/user/code/awesome-project/.venv/bin/python\n+```\n+\n+
      \n+\n+`.venv/bin/python` にある `python` バイナリが、プロジェクト(この場合は `awesome-project` )内に表示されていれば、正常に動作しています 🎉。\n+\n+////\n+\n+//// tab | [NAME_REDACTED]\n+\n+
      \n+\n+``` console\n+$ Get-Command python\n+\n+C:\\Users\\user\\code\\awesome-project\\.venv\\Scripts\\python\n+```\n+\n+
      \n+\n+`.venv\\Scripts\\python` にある `python` バイナリが、プロジェクト(この場合は `awesome-project` )内に表示されていれば、正常に動作しています 🎉。\n+\n+////\n+\n+## `pip` をアップグレードする\n+\n+/// tip | 豆知識\n+\n+もし `uv` を使用している場合は、 `pip` の代わりに `uv` を使ってインストールを行うため、 `pip` をアップグレードする必要はありません 😎。\n+\n+///\n+\n+もしパッケージのインストールに `pip`(Pythonに標準で付属しています)を使用しているなら、 `pip` を最新バージョンに**アップグレード**しましょう。\n+\n+パッケージのインストール中に発生する想定外のエラーの多くは、最初に `pip` をアップグレードしておくだけで解決されます。\n+\n+/// tip | 豆知識\n+\n+通常、これは仮想環境を作成した直後に**一度だけ**実行します。\n+\n+///\n+\n+仮想環境が有効であることを(上で説明したコマンドで)確認し、アップグレードを実行しましょう:\n+\n+
      \n+\n+```console\n+$ python -m pip install --upgrade pip\n+\n+---> 100%\n+```\n+\n+
      \n+\n+## `.gitignore` を追加する\n+\n+**Git**を使用している場合(使用するべきでしょう)、 `.gitignore` ファイルを追加して、 `.venv` 内のあらゆるファイルをGitの管理対象から除外します。\n+\n+/// tip | 豆知識\n+\n+もし `uv` を使用して仮想環境を作成した場合、すでにこの作業は済んでいるので、この手順をスキップできます 😎。\n+\n+///\n+\n+/// tip | 豆知識\n+\n+これも、仮想環境を作成した直後に**一度だけ**実行します。\n+\n+///\n+\n+
      \n+\n+```console\n+$ echo \"*\" > .venv/.gitignore\n+```\n+\n+
      \n+\n+/// details | このコマンドの意味\n+\n+- `echo \"*\"` : ターミナルに `*` というテキストを「表示」しようとします。(次の部分によってその動作が少し変わります)\n+- `>` : `>` の左側のコマンドがターミナルに表示しようとする内容を、ターミナルには表示せず、 `>` の右側のファイルに書き込みます。\n+- `.gitignore` : `*` を書き込むファイル名。\n+\n+ここで、Gitにおける `*` は「すべて」を意味するので、このコマンドによって `.venv` ディレクトリ内のすべてがGitに無視されるようになります。\n+\n+このコマンドは以下のテキストを持つ `.gitignore` ファイルを作成します:\n+\n+```gitignore\n+*\n+```\n+\n+///\n+\n+## パッケージのインストール\n+\n+仮想環境を有効化した後、その中でパッケージをインストールできます。\n+\n+/// tip | 豆知識\n+\n+プロジェクトに必要なパッケージをインストールまたはアップグレードする場合、これを**一度**実行します。\n+\n+もし新しいパッケージを追加したり、バージョンをアップグレードする必要がある場合は、もう**一度この手順を繰り返し**ます。\n+\n+///\n+\n+### パッケージを直接インストールする\n+\n+急いでいて、プロジェクトのパッケージ要件を宣言するファイルを使いたくない場合、パッケージを直接インストールできます。\n+\n+/// tip | 豆知識\n+\n+プログラムが必要とするパッケージとバージョンをファイル(例えば `requirements.txt` や `pyproject.toml` )に記載しておくのは、(とても)良い考えです。\n+\n+///\n+\n+//// tab | `pip`\n+\n+
      \n+\n+```console\n+$ pip install \"fastapi[standard]\"\n+\n+---> 100%\n+```\n+\n+
      \n+\n+////\n+\n+//// tab | `uv`\n+\n+もし `uv` を使用できるなら:\n+\n+
      \n+\n+```console\n+$ uv pip install \"fastapi[standard]\"\n+---> 100%\n+```\n+\n+
      \n+\n+////\n+\n+### `requirements.txt` からインストールする\n+\n+もし `requirements.txt` があるなら、パッケージのインストールに使用できます。\n+\n+//// tab | `pip`\n+\n+
      \n+\n+```console\n+$ pip install -r requirements.txt\n+---> 100%\n+```\n+\n+
      \n+\n+////\n+\n+//// tab | `uv`\n+\n+もし `uv` を使用できるなら:\n+\n+
      \n+\n+```console\n+$ uv pip install -r requirements.txt\n+---> 100%\n+```\n+\n+
      \n+\n+////\n+\n+/// details | `requirements.txt`\n+\n+パッケージが記載された `requirements.txt` は以下のようになっています:\n+\n+```requirements.txt\n+fastapi[standard]==0.113.0\n+pydantic==2.8.0\n+```\n+\n+///\n+\n+## プログラムを実行する\n+\n+仮想環境を有効化した後、プログラムを実行できます。この際、仮想環境内のPythonと、そこにインストールしたパッケージが使用されます。\n+\n+
      \n+\n+```console\n+$ python main.py\n+\n+[NAME_REDACTED]\n+```\n+\n+
      \n+\n+## エディタの設定\n+\n+プロジェクトではおそらくエディタを使用するでしょう。コード補完やインラインエラーの表示ができるように、作成した仮想環境をエディタでも使えるよう設定してください。(多くの場合、自動検出されます)\n+\n+設定例:\n+\n+* VS Code\n+* PyCharm\n+\n+/// tip | 豆知識\n+\n+この設定は通常、仮想環境を作成した際に**一度だけ**行います。\n+\n+///\n+\n+## 仮想環境の無効化\n+\n+プロジェクトの作業が終了したら、その仮想環境を**無効化**できます。\n+\n+
      \n+\n+```console\n+$ deactivate\n+```\n+\n+
      \n+\n+これにより、 `python` コマンドを実行しても、そのプロジェクト用(のパッケージがインストールされた)仮想環境から `python` プログラムを呼び出そうとはしなくなります。\n+\n+## 作業準備完了\n+\n+ここまでで、プロジェクトの作業を始める準備が整いました。\n+\n+/// tip | 豆知識\n+\n+上記の内容を理解したいですか?\n+\n+もしそうなら、以下を読み進めてください。👇🤓\n+\n+///\n+\n+## なぜ仮想環境?\n+\n+FastAPIを使った作業をするには、 [Python](https://www.python.org/) のインストールが必要です。\n+\n+それから、FastAPIや、使用したいその他の**パッケージ**を**インストール**する必要があります。\n+\n+パッケージをインストールするには、通常、Python に付属する `pip` コマンド (または同様の代替コマンド) を使用します。\n+\n+ただし、`pip` を直接使用すると、パッケージは**グローバルなPython環境**(OS全体にインストールされたPython環境)にインストールされます。\n+\n+### 問題点\n+\n+では、グローバルPython環境にパッケージをインストールすることの問題点は何でしょうか?\n+\n+ある時点で、あなたは**異なるパッケージ**に依存する多くのプログラムを書くことになるでしょう。そして、これらの中には同じパッケージの**異なるバージョン**に依存するものも出てくるでしょう。😱\n+\n+例えば、 `philosophers-stone` (賢者の石)というプロジェクトを作成するとします。このプログラムは **`harry` (ハリー)というパッケージのバージョン `1`**に依存しています。そのため、 `harry` (ハリー)をインストールする必要があります。\n+\n+```mermaid\n+flowchart LR\n+ stone(philosophers-stone) -->|requires| harry-1[harry v1]\n+```\n+\n+それから、 `prisoner-of-azkaban` (アズカバンの囚人)という別のプロジェクトを作成したとします。このプロジェクトも `harry` (ハリー)に依存していますが、**`harry` (ハリー)のバージョン `3`**が必要です。\n+\n+```mermaid\n+flowchart LR\n+ azkaban(prisoner-of-azkaban) --> |requires| harry-3[harry v3]\n+```\n+\n+しかし、ここで問題になるのは、もしローカルの**仮想環境**ではなくグローバル(環境)にパッケージをインストールするなら、 `harry` (ハリー)のどのバージョンをインストールするか選ばないといけないことです。\n+\n+例えば、 `philosophers-stone` (賢者の石)を実行するには、まず `harry` (ハリー)のバージョン `1` をインストールする必要があります:\n+\n+
      \n+\n+```console\n+$ pip install \"harry==1\"\n+```\n+\n+
      \n+\n+これにより、`harry` (ハリー)バージョン1がグローバルなPython環境にインストールされます。\n+\n+```mermaid\n+flowchart LR\n+ subgraph global[global env]\n+ harry-1[harry v1]\n+ end\n+ subgraph stone-project[philosophers-stone project]\n+ stone(philosophers-stone) -->|requires| harry-1\n+ end\n+```\n+\n+しかし、 `prisoner-of-azkaban` (アズカバンの囚人)を実行したい場合は、`harry` (ハリー)のバージョン `1` をアンインストールし、`harry` (ハリー)のバージョン `3` をインストールし直す必要があります。(あるいは、単に`harry` (ハリー)のバージョン `3` をインストールすることで、自動的にバージョン `1` がアンインストールされます)\n+\n+
      \n+\n+```console\n+$ pip install \"harry==3\"\n+```\n+\n+
      \n+\n+このようにして、グローバル環境への `harry` (ハリー)のバージョン `3` のインストールが完了します。\n+\n+それから、 `philosophers-stone` (賢者の石)を再び実行しようとすると、このプログラムは `harry` (ハリー)のバージョン `1` が必要なため、**動作しなくなる**可能性があります。\n+\n+```mermaid\n+flowchart LR\n+ subgraph global[global env]\n+ harry-1[harry v1]\n+ style harry-1 fill:#ccc,stroke-dasharray: 5 5\n+ harry-3[harry v3]\n+ end\n+ subgraph stone-project[philosophers-stone project]\n+ stone(philosophers-stone) -.-x|⛔️| harry-1\n+ end\n+ subgraph azkaban-project[prisoner-of-azkaban project]\n+ azkaban(prisoner-of-azkaban) --> |requires| harry-3\n+ end\n+```\n+\n+/// tip | 豆知識\n+\n+Pythonのパッケージでは、**新しいバージョン**で**互換性を損なう変更を避ける**よう努めるのが一般的ですが、それでも注意が必要です。すべてが正常に動作することをテストで確認してから、意図的に指定して新しいバージョンをインストールするのが良いでしょう。\n+\n+///\n+\n+あなたのすべての**プロジェクトが依存している**、**多数の**他の**パッケージ**が上記の問題を抱えていると想像してください。これは管理が非常に困難です。そして、**互換性のないバージョン**のパッケージを使ってプロジェクトを実行し、なぜ動作しないのか分からなくなるでしょう。\n+\n+また、使用しているOS(Linux、Windows、macOS など)によっては、Pythonがすでにインストールされていることがあります。この場合、特定のバージョンのパッケージが**OSの動作に必要である**ことがあります。グローバル環境にパッケージをインストールすると、OSに付属するプログラムを**壊してしまう**可能性があります。\n+\n+## パッケージのインストール先\n+\n+Pythonをインストールしたとき、ファイルを含んだいくつかのディレクトリが作成されます。\n+\n+これらの中には、インストールされたパッケージを保存するためのものもあります。\n+\n+以下のコマンドを実行したとき:\n+\n+
      \n+\n+```console\n+// Don't run this now, it's just an example 🤓\n+$ pip install \"fastapi[standard]\"\n+---> 100%\n+```\n+\n+
      \n+\n+FastAPIのコードを含む圧縮ファイルが、通常は [PyPI](https://pypi.org/project/fastapi/) からダウンロードされます。\n+\n+また、FastAPIが依存する他のパッケージも**ダウンロード**されます。\n+\n+それから、これらのファイルは**解凍**され、コンピュータのあるディレクトリに配置されます。\n+\n+デフォルトでは、これらのファイルはPythonのインストール時に作成されるディレクトリ、つまり**グローバル環境**に配置されます。\n+\n+## 仮想環境とは\n+\n+すべてのパッケージをグローバル環境に配置することによって生じる問題の解決策は、作業する**プロジェクトごとの仮想環境**を使用することです。\n+\n+仮想環境は**ディレクトリ**であり、グローバル環境と非常に似ていて、一つのプロジェクトで使う特定のパッケージ群をインストールできる場所です。\n+\n+このようにして、それぞれのプロジェクトが独自の仮想環境(`.venv` ディレクトリ)に独自のパッケージ群を持つことができます。\n+\n+```mermaid\n+flowchart TB\n+ subgraph stone-project[philosophers-stone project]\n+ stone(philosophers-stone) --->|requires| harry-1\n+ subgraph venv1[.venv]\n+ harry-1[harry v1]\n+ end\n+ end\n+ subgraph azkaban-project[prisoner-of-azkaban project]\n+ azkaban(prisoner-of-azkaban) --->|requires| harry-3\n+ subgraph venv2[.venv]\n+ harry-3[harry v3]\n+ end\n+ end\n+ stone-project ~~~ azkaban-project\n+```\n+\n+## 仮想環境の有効化とは\n+\n+仮想環境を有効にしたとき、例えば次のコマンドを実行した場合を考えます:\n+\n+//// tab | Linux, macOS\n+\n+
      \n+\n+```console\n+$ source .venv/bin/activate\n+```\n+\n+
      \n+\n+////\n+\n+//// tab | [NAME_REDACTED]\n+\n+
      \n+\n+```console\n+$ .venv\\Scripts\\Activate.ps1\n+```\n+\n+
      \n+\n+////\n+\n+//// tab | [NAME_REDACTED]\n+\n+あるいは、WindowsでBashを使用している場合 ([NAME_REDACTED]など):\n+\n+
      \n+\n+```console\n+$ source .venv/Scripts/activate\n+```\n+\n+
      \n+\n+////\n+\n+これによって、いくつかの [環境変数](environment-variables.md){.internal-link target=_blank} が作成・修正され、次に実行されるコマンドで使用できるようになります。\n+\n+これらの環境変数のひとつに、 `PATH` 変数があります。\n+\n+/// tip | 豆知識\n+\n+`PATH` 変数についての詳細は [環境変数](environment-variables.md#path環境変数){.internal-link target=_blank} を参照してください。\n+\n+///\n+\n+仮想環境を有効にすると、その仮想環境のパス `.venv/bin` (LinuxとmacOS)、あるいは `.venv\\Scripts` (Windows)が `PATH` 変数に追加されます。\n+\n+その環境を有効にする前の `PATH` 変数が次のようになっているとします。\n+\n+//// tab | Linux, macOS\n+\n+```plaintext\n+/usr/bin:/bin:/usr/sbin:/sbin\n+```\n+\n+これは、OSが以下のディレクトリ中でプログラムを探すことを意味します:\n+\n+* `/usr/bin`\n+* `/bin`\n+* `/usr/sbin`\n+* `/sbin`\n+\n+////\n+\n+//// tab | Windows\n+\n+```plaintext\n+C:\\Windows\\System32\n+```\n+\n+これは、OSが以下のディレクトリ中でプログラムを探すことを意味します:\n+\n+* `C:\\Windows\\System32`\n+\n+////\n+\n+仮想環境を有効にすると、 `PATH` 変数は次のようになります。\n+\n+//// tab | Linux, macOS\n+\n+```plaintext\n+/home/user/code/awesome-project/.venv/bin:/usr/bin:/bin:/usr/sbin:/sbin\n+```\n+\n+これは、OSが他のディレクトリを探すより前に、最初に以下のディレクトリ中でプログラムを探し始めることを意味します:\n+\n+```plaintext\n+/home/user/code/awesome-project/.venv/bin\n+```\n+\n+そのため、ターミナルで `python` と入力した際に、OSはPythonプログラムを以下のパスで発見し、使用します。\n+\n+```plaintext\n+/home/user/code/awesome-project/.venv/bin/python\n+```\n+\n+////\n+\n+//// tab | Windows\n+\n+```plaintext\n+C:\\Users\\user\\code\\awesome-project\\.venv\\Scripts;C:\\Windows\\System32\n+```\n+\n+これは、OSが他のディレクトリを探すより前に、最初に以下のディレクトリ中でプログラムを探し始めることを意味します:\n+\n+```plaintext\n+C:\\Users\\user\\code\\awesome-project\\.venv\\Scripts\n+```\n+\n+そのため、ターミナルで `python` と入力した際に、OSはPythonプログラムを以下のパスで発見し、使用します。\n+\n+```plaintext\n+C:\\Users\\user\\code\\awesome-project\\.venv\\Scripts\\python\n+```\n+\n+////\n+\n+重要な点は、仮想環境のパスを `PATH` 変数の**先頭**に配置することです。OSは利用可能な他のPythonを見つけるより**前に**、この仮想環境のPythonを見つけるようになります。このようにして、 `python` を実行したときに、他の `python` (例えばグローバル環境の `python` )ではなく、**その仮想環境の**Pythonを使用するようになります。\n+\n+仮想環境を有効にして変更されることは他にもありますが、これが最も重要な変更のひとつです。\n+\n+## 仮想環境の確認\n+\n+仮想環境が有効かどうか、例えば次のように確認できます。:\n+\n+//// tab | Linux, macOS, [NAME_REDACTED]\n+\n+
      \n+\n+```console\n+$ which python\n+\n+/home/user/code/awesome-project/.venv/bin/python\n+```\n+\n+
      \n+\n+////\n+\n+//// tab | [NAME_REDACTED]\n+\n+
      \n+\n+```console\n+$ Get-Command python\n+\n+C:\\Users\\user\\code\\awesome-project\\.venv\\Scripts\\python\n+```\n+\n+
      \n+\n+////\n+\n+これは、使用される `python` プログラムが**その仮想環境の**ものであることを意味します。\n+\n+LinuxやmacOSでは `which` を、Windows PowerShellでは `Get-Command` を使用します。\n+\n+このコマンドの動作は、 `PATH`変数に設定された**それぞれのパスを順に**確認していき、呼ばれている `python` プログラムを探します。そして、見つかり次第そのプログラムへの**パスを表示します**。\n+\n+最も重要なことは、 `python` が呼ばれたときに、まさにこのコマンドで確認した \"`python`\" が実行されることです。\n+\n+こうして、自分が想定通りの仮想環境にいるかを確認できます。\n+\n+/// tip | 豆知識\n+\n+ある仮想環境を有効にし、そのPythonを使用したまま**他のプロジェクトに移動して**しまうことは簡単に起こり得ます。\n+\n+そして、その第二のプロジェクトは動作しないでしょう。なぜなら別のプロジェクトの仮想環境の**誤ったPython**を使用しているからです。\n+\n+そのため、どの `python` が使用されているのか確認できることは役立ちます。🤓\n+\n+///\n+\n+## なぜ仮想環境を無効化するのか\n+\n+例えば、`philosophers-stone` (賢者の石)というプロジェクトで作業をしていて、**その仮想環境を有効にし**、必要なパッケージをインストールしてその環境内で作業を進めているとします。\n+\n+それから、**別のプロジェクト**、 `prisoner-of-azkaban` (アズカバンの囚人)に取り掛かろうとします。\n+\n+そのプロジェクトディレクトリへ移動します:\n+\n+
      \n+\n+```console\n+$ cd ~/code/prisoner-of-azkaban\n+```\n+\n+
      \n+\n+もし `philosophers-stone` (賢者の石)の仮想環境を無効化していないと、`python` を実行したとき、 ターミナルは `philosophers-stone` (賢者の石)のPythonを使用しようとします。\n+\n+
      \n+\n+```console\n+$ cd ~/code/prisoner-of-azkaban\n+\n+$ python main.py\n+\n+// Error importing sirius, it's not installed 😱\n+Traceback (most recent call last):\n+ File \"main.py\", line 1, in \n+ import sirius\n+```\n+\n+
      \n+\n+しかし、その仮想環境を無効化し、 `prisoner-of-azkaban` (アズカバンの囚人)のための新しい仮想環境を有効にすれば、 `python` を実行したときに `prisoner-of-azkaban` (アズカバンの囚人)の仮想環境の Python が使用されるようになります。\n+\n+
      \n+\n+```console\n+$ cd ~/code/prisoner-of-azkaban\n+\n+// You don't need to be in the old directory to deactivate, you can do it wherever you are, even after going to the other project 😎\n+$ deactivate\n+\n+// Activate the virtual environment in prisoner-of-azkaban/.venv 🚀\n+$ source .venv/bin/activate\n+\n+// Now when you run python, it will find the package sirius installed in this virtual environment ✨\n+$ python main.py\n+\n+I solemnly swear 🐺\n+```\n+\n+
      \n+\n+## 代替手段\n+\n+これは、あらゆる仕組みを**根本から**学ぶためのシンプルな入門ガイドです。\n+\n+仮想環境、パッケージの依存関係(requirements)、プロジェクトの管理には、多くの**代替手段**があります。\n+\n+準備が整い、パッケージの依存関係、仮想環境など**プロジェクト全体の管理**ツールを使いたいと考えたら、uv を試してみることをおすすめします。\n+\n+`uv` では以下のような多くのことができます:\n+\n+* 異なるバージョンも含めた**Python のインストール**\n+* プロジェクトごとの**仮想環境**の管理\n+* **パッケージ**のインストール\n+* プロジェクトのパッケージの**依存関係やバージョン**の管理\n+* パッケージとそのバージョンの、依存関係を含めた**厳密な**組み合わせを保持し、これによって、本番環境で、開発環境と全く同じようにプロジェクトを実行できる(これは**locking**と呼ばれます)\n+* その他のさまざまな機能\n+\n+## まとめ\n+\n+ここまで読みすべて理解したなら、世間の多くの開発者と比べて、仮想環境について**あなたはより多くのことを知っています**。🤓\n+\n+これらの詳細を知ることは、将来、複雑に見える何かのデバッグにきっと役立つでしょう。しかし、その頃には、あなたは**そのすべての動作を根本から**理解しているでしょう。😎" } ], "reviews": [ { "id": 2640667320, "user": "user_472f326cb34f", "state": "CHANGES_REQUESTED", "body": "I appreciate all your hard work.\nThere are some typo or something to fix, I found.\n\nThank you for your contributing.", "submitted_at": "2025-02-25T15:01:49+00:00" }, { "id": 2650904053, "user": "user_472f326cb34f", "state": "APPROVED", "body": "I checked this again, and I can't find problem on it.\nSo I approved this.\n\nThank you for your great works!", "submitted_at": "2025-02-28T14:25:02+00:00" } ], "review_comments": [ { "id": 1969562463, "user": "user_472f326cb34f", "body": "maybe プログラムが使用できる because original is \"can be used by programs\"...?", "path": "docs/ja/docs/virtual-environments.md", "line": null, "side": "RIGHT", "created_at": "2025-02-25T11:16:07+00:00" }, { "id": 1969565113, "user": "user_472f326cb34f", "body": "I think することができます is more softer than していただいて構いません", "path": "docs/ja/docs/virtual-environments.md", "line": null, "side": "RIGHT", "created_at": "2025-02-25T11:17:55+00:00" }, { "id": 1969640339, "user": "user_472f326cb34f", "body": "意図的して seems typo\n\n```suggestion\nPythonのパッケージでは、**新しいバージョン**で**互換性を損なう変更を避ける**よう努めるのが一般的ですが、それでも注意が必要です。すべてが正常に動作することをテストで確認してから、意図的に指定して新しいバージョンをインストールするのが良いでしょう。\n```", "path": "docs/ja/docs/virtual-environments.md", "line": null, "side": "RIGHT", "created_at": "2025-02-25T12:08:40+00:00" }, { "id": 1969926803, "user": "user_472f326cb34f", "body": "Before this line, \"です\" or \"ます\" was used in end of line.\n```suggestion\nパッケージが記載された `requirements.txt` は以下のようになっています:\n```", "path": "docs/ja/docs/virtual-environments.md", "line": null, "side": "RIGHT", "created_at": "2025-02-25T14:43:36+00:00" }, { "id": 1969936649, "user": "user_472f326cb34f", "body": "```suggestion\n例えば、`philosophers-stone` (賢者の石)というプロジェクトで作業をしていて、**その仮想環境を有効にし**、必要なパッケージをインストールしてその環境内で作業を進めているとします。\n```", "path": "docs/ja/docs/virtual-environments.md", "line": null, "side": "RIGHT", "created_at": "2025-02-25T14:48:48+00:00" }, { "id": 1969946312, "user": "user_472f326cb34f", "body": "Original one is \"You go to that project:\"\nSo, it may be better to change like this:\n ```suggestion\nそのプロジェクトディレクトリへ移動します:\n```", "path": "docs/ja/docs/virtual-environments.md", "line": null, "side": "RIGHT", "created_at": "2025-02-25T14:52:52+00:00" } ], "meta": { "languages": [ "md" ], "touches_tests": false, "review_state_summary": { "CHANGES_REQUESTED": 1, "APPROVED": 1 }, "meaningful_comment_count": 6, "has_approval": true, "has_changes_requested": true, "total_review_comments": 6 } } { "_id": "2d53e2136bc315d3", "_schema_version": "1.0", "_cleaned_at": "2026-02-12T07:46:52.179504+00:00", "repo": "tiangolo/fastapi", "repo_url": "https://github.com/fastapi/fastapi", "license_name": "MIT License", "license_spdx": "MIT", "pr_number": 13279, "title": "🌐 Add Russian translation for `docs/ru/docs/advanced/websockets.md`", "body": null, "author": "user_9e49ba0b4492", "created_at": "2025-01-29T16:49:00+00:00", "merged_at": "2025-02-03T13:33:40+00:00", "base_branch": "master", "head_branch": "translate-lang-ru-websockets", "additions": 186, "deletions": 0, "changed_files": 1, "files": [ { "filename": "docs/ru/docs/advanced/websockets.md", "status": "added", "additions": 186, "deletions": 0, "changes": 186, "patch": "@@ -0,0 +1,186 @@\n+# Веб-сокеты\n+\n+Вы можете использовать веб-сокеты в **FastAPI**.\n+\n+## Установка `WebSockets`\n+\n+Убедитесь, что [виртуальная среда](../virtual-environments.md){.internal-link target=_blank} создана, активируйте её и установите `websockets`:\n+\n+
      \n+\n+```console\n+$ pip install websockets\n+\n+---> 100%\n+```\n+\n+
      \n+\n+## Клиент WebSockets\n+\n+### Рабочее приложение\n+\n+Скорее всего, в вашей реальной продуктовой системе есть фронтенд, реализованный при помощи современных фреймворков React, Vue.js или Angular.\n+\n+И наверняка для взаимодействия с бекендом через веб-сокеты вы будете использовать средства фронтенда.\n+\n+Также у вас может быть нативное мобильное приложение, коммуницирующее непосредственно с веб-сокетами на бекенд-сервере.\n+\n+Либо вы можете сделать какой-либо другой способ взаимодействия с веб-сокетами.\n+\n+---\n+\n+Но для этого примера мы воспользуемся очень простым HTML документом с небольшими вставками JavaScript кода.\n+\n+Конечно же это неоптимально, и на практике так делать не стоит.\n+\n+В реальных приложениях стоит воспользоваться одним из вышеупомянутых способов.\n+\n+Для примера нам нужен наиболее простой способ, который позволит сосредоточиться на серверной части веб-сокетов и получить рабочий код:\n+\n+{* ../../docs_src/websockets/tutorial001.py hl[2,6:38,41:43] *}\n+\n+## Создание `websocket`\n+\n+Создайте `websocket` в своем **FastAPI** приложении:\n+\n+{* ../../docs_src/websockets/tutorial001.py hl[1,46:47] *}\n+\n+/// note | Технические детали\n+\n+Вы также можете использовать `from starlette.websockets import WebSocket`.\n+\n+**FastAPI** напрямую предоставляет тот же самый `WebSocket` просто для удобства. На самом деле это `WebSocket` из Starlette.\n+\n+///\n+\n+## Ожидание и отправка сообщений\n+\n+Через эндпоинт веб-сокета вы можете получать и отправлять сообщения.\n+\n+{* ../../docs_src/websockets/tutorial001.py hl[48:52] *}\n+\n+Вы можете получать и отправлять двоичные, текстовые и JSON данные.\n+\n+## Проверка в действии\n+\n+Если ваш файл называется `main.py`, то запустите приложение командой:\n+\n+
      \n+\n+```console\n+$ fastapi dev main.py\n+\n+INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit)\n+```\n+\n+
      \n+\n+Откройте браузер по адресу http://127.0.0.1:8000.\n+\n+Вы увидите следующую простенькую страницу:\n+\n+\n+\n+Вы можете набирать сообщения в поле ввода и отправлять их:\n+\n+\n+\n+И ваше **FastAPI** приложение с веб-сокетами ответит:\n+\n+\n+\n+Вы можете отправлять и получать множество сообщений:\n+\n+\n+\n+И все они будут использовать одно и то же веб-сокет соединение.\n+\n+## Использование `Depends` и не только\n+\n+Вы можете импортировать из `fastapi` и использовать в эндпоинте вебсокета:\n+\n+* `Depends`\n+* `Security`\n+* `Cookie`\n+* `Header`\n+* `Path`\n+* `Query`\n+\n+Они работают так же, как и в других FastAPI эндпоинтах/*операциях пути*:\n+\n+{* ../../docs_src/websockets/tutorial002_an_py310.py hl[68:69,82] *}\n+\n+/// info | Примечание\n+\n+В веб-сокете вызывать `HTTPException` не имеет смысла. Вместо этого нужно использовать `WebSocketException`.\n+\n+Закрывающий статус код можно использовать из valid codes defined in the specification.\n+\n+///\n+\n+### Веб-сокеты с зависимостями: проверка в действии\n+\n+Если ваш файл называется `main.py`, то запустите приложение командой:\n+\n+
      \n+\n+```console\n+$ fastapi dev main.py\n+\n+INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit)\n+```\n+\n+
      \n+\n+Откройте браузер по адресу http://127.0.0.1:8000.\n+\n+Там вы можете задать:\n+\n+* \"Item ID\", используемый в пути.\n+* \"Token\", используемый как query-параметр.\n+\n+/// tip | Подсказка\n+\n+Обратите внимание, что query-параметр `token` будет обработан в зависимости.\n+\n+///\n+\n+Теперь вы можете подключиться к веб-сокету и начинать отправку и получение сообщений:\n+\n+\n+\n+## Обработка отключений и работа с несколькими клиентами\n+\n+Если веб-сокет соединение закрыто, то `await websocket.receive_text()` вызовет исключение `WebSocketDisconnect`, которое можно поймать и обработать как в этом примере:\n+\n+{* ../../docs_src/websockets/tutorial003_py39.py hl[79:81] *}\n+\n+Чтобы воспроизвести пример:\n+\n+* Откройте приложение в нескольких вкладках браузера.\n+* Отправьте из них сообщения.\n+* Затем закройте одну из вкладок.\n+\n+Это вызовет исключение `WebSocketDisconnect`, и все остальные клиенты получат следующее сообщение:\n+\n+```\n+Client #1596980209979 left the chat\n+```\n+\n+/// tip | Примечание\n+\n+Приложение выше - это всего лишь простой минимальный пример, демонстрирующий обработку и передачу сообщений нескольким веб-сокет соединениям.\n+\n+Но имейте в виду, что это будет работать только в одном процессе и только пока он активен, так как всё обрабатывается в простом списке в оперативной памяти.\n+\n+Если нужно что-то легко интегрируемое с FastAPI, но более надежное и с поддержкой Redis, PostgreSQL или другого, то можно воспользоваться encode/broadcaster.\n+\n+///\n+\n+## Дополнительная информация\n+\n+Для более глубокого изучения темы воспользуйтесь документацией Starlette:\n+\n+* The `WebSocket` class.\n+* [NAME_REDACTED] handling." } ], "reviews": [ { "id": 2582133068, "user": "user_6d7d83efab20", "state": "CHANGES_REQUESTED", "body": null, "submitted_at": "2025-01-29T22:09:42+00:00" }, { "id": 2583107869, "user": "user_9e49ba0b4492", "state": "COMMENTED", "body": null, "submitted_at": "2025-01-30T07:22:23+00:00" }, { "id": 2583121231, "user": "user_9e49ba0b4492", "state": "COMMENTED", "body": null, "submitted_at": "2025-01-30T07:26:44+00:00" }, { "id": 2583146690, "user": "user_9e49ba0b4492", "state": "COMMENTED", "body": null, "submitted_at": "2025-01-30T07:44:30+00:00" }, { "id": 2584183770, "user": "user_df3ddbc43209", "state": "COMMENTED", "body": null, "submitted_at": "2025-01-30T15:12:09+00:00" }, { "id": 2584273600, "user": "user_6d7d83efab20", "state": "COMMENTED", "body": null, "submitted_at": "2025-01-30T15:38:45+00:00" }, { "id": 2584793838, "user": "user_9e49ba0b4492", "state": "COMMENTED", "body": null, "submitted_at": "2025-01-30T19:03:42+00:00" }, { "id": 2585087798, "user": "user_6d7d83efab20", "state": "COMMENTED", "body": null, "submitted_at": "2025-01-30T21:22:37+00:00" }, { "id": 2585090110, "user": "user_6d7d83efab20", "state": "APPROVED", "body": "Предлагаю заменить `In Production` на `Рабочее приложение`\n\nВнесла две опциональные поправки (не настаиваю)", "submitted_at": "2025-01-30T21:27:01+00:00" }, { "id": 2585095479, "user": "user_6d7d83efab20", "state": "COMMENTED", "body": null, "submitted_at": "2025-01-30T21:27:22+00:00" }, { "id": 2587094206, "user": "user_3cf7e8d7d8b1", "state": "APPROVED", "body": null, "submitted_at": "2025-01-31T15:32:17+00:00" }, { "id": 2588336341, "user": "user_df3ddbc43209", "state": "APPROVED", "body": null, "submitted_at": "2025-02-01T13:13:33+00:00" } ], "review_comments": [ { "id": 1934522925, "user": "user_6d7d83efab20", "body": "```suggestion\nВы можете использовать веб-сокеты в **FastAPI**.\n```", "path": "docs/ru/docs/advanced/websockets.md", "line": null, "side": "RIGHT", "created_at": "2025-01-29T20:15:21+00:00" }, { "id": 1934524405, "user": "user_6d7d83efab20", "body": "```suggestion\nУбедитесь, что [виртуальная среда](../virtual-environments.md){.internal-link target=_blank} создана, активируйте её и установите `websockets`:\n```", "path": "docs/ru/docs/advanced/websockets.md", "line": null, "side": "RIGHT", "created_at": "2025-01-29T20:16:28+00:00" }, { "id": 1934525627, "user": "user_6d7d83efab20", "body": "```suggestion\n## Клиент WebSockets\n```", "path": "docs/ru/docs/advanced/websockets.md", "line": null, "side": "RIGHT", "created_at": "2025-01-29T20:17:34+00:00" }, { "id": 1934537130, "user": "user_6d7d83efab20", "body": "```suggestion\n### Продуктовая системы (Production)", "path": "docs/ru/docs/advanced/websockets.md", "line": null, "side": "RIGHT", "created_at": "2025-01-29T20:27:01+00:00" }, { "id": 1934541567, "user": "user_6d7d83efab20", "body": "```suggestion\nСкорее всего, в вашей реальной продуктовой системе есть фронтенд, реализованный при помощи современных фреймворков React, Vue.js или Angular.\n```", "path": "docs/ru/docs/advanced/websockets.md", "line": null, "side": "RIGHT", "created_at": "2025-01-29T20:30:46+00:00" }, { "id": 1934552200, "user": "user_6d7d83efab20", "body": "```suggestion\nИ наверняка для взаимодействия с бекендом через веб-сокеты вы будете использовать приложения фронтенда.\n```", "path": "docs/ru/docs/advanced/websockets.md", "line": null, "side": "RIGHT", "created_at": "2025-01-29T20:40:46+00:00" }, { "id": 1934576978, "user": "user_6d7d83efab20", "body": "```suggestion\nИли, возможно, у вас реализован какой-либо другой способ взаимодействия с веб-сокетами.\n```", "path": "docs/ru/docs/advanced/websockets.md", "line": null, "side": "RIGHT", "created_at": "2025-01-29T20:59:34+00:00" }, { "id": 1934604666, "user": "user_6d7d83efab20", "body": "```suggestion\nТакже у вас может быть нативное мобильное приложение, коммуницирующее непосредственно с веб-сокетами на бекенд-сервере.\n```", "path": "docs/ru/docs/advanced/websockets.md", "line": null, "side": "RIGHT", "created_at": "2025-01-29T21:04:11+00:00" }, { "id": 1934636713, "user": "user_6d7d83efab20", "body": "```suggestion\nНо для этого примера мы воспользуемся очень простым HTML документом с небольшими вставками JavaScript кода.\n```", "path": "docs/ru/docs/advanced/websockets.md", "line": null, "side": "RIGHT", "created_at": "2025-01-29T21:08:15+00:00" }, { "id": 1934645666, "user": "user_6d7d83efab20", "body": "```suggestion\nКонечно же это неоптимально, и на практике так делать не стоит.\n```", "path": "docs/ru/docs/advanced/websockets.md", "line": null, "side": "RIGHT", "created_at": "2025-01-29T21:09:43+00:00" }, { "id": 1934656893, "user": "user_6d7d83efab20", "body": "```suggestion\nВ реальном приложении у вас будет одно из двух - либо фронтенд приложение, либо нативное мобильное приложение.\n```", "path": "docs/ru/docs/advanced/websockets.md", "line": 37, "side": "RIGHT", "created_at": "2025-01-29T21:16:34+00:00" }, { "id": 1934664365, "user": "user_6d7d83efab20", "body": "```suggestion\nНо в данном примере нам нужен наиболее простой способ, который позволит сосредоточиться на серверной части веб-сокетов и получить рабочий код.\n```", "path": "docs/ru/docs/advanced/websockets.md", "line": null, "side": "RIGHT", "created_at": "2025-01-29T21:24:06+00:00" }, { "id": 1934666460, "user": "user_6d7d83efab20", "body": "```suggestion\n## Создание `веб-сокета`\n```", "path": "docs/ru/docs/advanced/websockets.md", "line": 43, "side": "RIGHT", "created_at": "2025-01-29T21:26:02+00:00" }, { "id": 1934669922, "user": "user_6d7d83efab20", "body": "```suggestion\nЧерез эндпоинт веб-сокета вы можете получать и отправлять сообщения.\n```", "path": "docs/ru/docs/advanced/websockets.md", "line": null, "side": "RIGHT", "created_at": "2025-01-29T21:29:35+00:00" }, { "id": 1934690074, "user": "user_6d7d83efab20", "body": "```suggestion\n## Проверка в действии\n```", "path": "docs/ru/docs/advanced/websockets.md", "line": null, "side": "RIGHT", "created_at": "2025-01-29T21:41:42+00:00" }, { "id": 1934692460, "user": "user_6d7d83efab20", "body": "```suggestion\n### Веб-сокеты с зависимостями: проверка в действии\n```", "path": "docs/ru/docs/advanced/websockets.md", "line": null, "side": "RIGHT", "created_at": "2025-01-29T21:43:52+00:00" }, { "id": 1934699990, "user": "user_6d7d83efab20", "body": "```suggestion\nТеперь вы можете подключиться к веб-сокету и начинать отправку и получение сообщений:\n```", "path": "docs/ru/docs/advanced/websockets.md", "line": null, "side": "RIGHT", "created_at": "2025-01-29T21:49:59+00:00" }, { "id": 1934701304, "user": "user_6d7d83efab20", "body": "```suggestion\n## Обработка отключений и работа с несколькими клиентами\n```", "path": "docs/ru/docs/advanced/websockets.md", "line": null, "side": "RIGHT", "created_at": "2025-01-29T21:51:24+00:00" }, { "id": 1934702513, "user": "user_6d7d83efab20", "body": "```suggestion\nЧтобы воспроизвести пример:\n```", "path": "docs/ru/docs/advanced/websockets.md", "line": null, "side": "RIGHT", "created_at": "2025-01-29T21:52:39+00:00" }, { "id": 1934709732, "user": "user_6d7d83efab20", "body": "```suggestion\nПриложение выше - это всего лишь простой минимальный пример, демонстрирующий обработку и передачу сообщений нескольким веб-сокет соединениям.\n```", "path": "docs/ru/docs/advanced/websockets.md", "line": null, "side": "RIGHT", "created_at": "2025-01-29T21:57:23+00:00" }, { "id": 1934716571, "user": "user_6d7d83efab20", "body": "`В продакшене`: как-то не звучит ... и ничего хорошего в голову не приходит ...", "path": "docs/ru/docs/advanced/websockets.md", "line": null, "side": "RIGHT", "created_at": "2025-01-29T22:02:51+00:00" }, { "id": 1934725406, "user": "user_6d7d83efab20", "body": "нужно пояснить что мы имеем ввиду под \"вышеупомянутым\" :smile:", "path": "docs/ru/docs/advanced/websockets.md", "line": 37, "side": "RIGHT", "created_at": "2025-01-29T22:08:30+00:00" }, { "id": 1935121905, "user": "user_9e49ba0b4492", "body": "Может тут лучше использовать термин \"виртуальное окружение\" - все так говорят, разве нет?", "path": "docs/ru/docs/advanced/websockets.md", "line": null, "side": "RIGHT", "created_at": "2025-01-30T07:22:22+00:00" }, { "id": 1935130830, "user": "user_9e49ba0b4492", "body": "Тоже ничего толкового в голову не пришло(( Был вариант: \"реально работающая система\"...", "path": "docs/ru/docs/advanced/websockets.md", "line": null, "side": "RIGHT", "created_at": "2025-01-30T07:26:44+00:00" }, { "id": 1935147385, "user": "user_9e49ba0b4492", "body": "Но ведь и в оригинале это не пояснено. Если в переводе в таких случаях дописывать, то получится что перевод начнет \"расходиться\" с оригиналом и жить своей жизнью.", "path": "docs/ru/docs/advanced/websockets.md", "line": 37, "side": "RIGHT", "created_at": "2025-01-30T07:44:30+00:00" }, { "id": 1935779865, "user": "user_df3ddbc43209", "body": "Звучит :)\n```suggestion\nВы можете отправлять и получать множество сообщений:\n```", "path": "docs/ru/docs/advanced/websockets.md", "line": null, "side": "RIGHT", "created_at": "2025-01-30T15:09:15+00:00" }, { "id": 1935780901, "user": "user_df3ddbc43209", "body": "```suggestion\nОни работают так же, как и в других FastAPI эндпоинтах/*операциях пути*:\n```", "path": "docs/ru/docs/advanced/websockets.md", "line": null, "side": "RIGHT", "created_at": "2025-01-30T15:09:50+00:00" }, { "id": 1935781704, "user": "user_df3ddbc43209", "body": "```suggestion\nНо имейте в виду, что это будет работать только в одном процессе и только пока он активен, так как всё обрабатывается в простом списке в оперативной памяти.\n```", "path": "docs/ru/docs/advanced/websockets.md", "line": null, "side": "RIGHT", "created_at": "2025-01-30T15:10:17+00:00" }, { "id": 1935832434, "user": "user_6d7d83efab20", "body": "Это нужно поправить. Выберите вариант, который вам больше нравится. :smile:", "path": "docs/ru/docs/advanced/websockets.md", "line": null, "side": "RIGHT", "created_at": "2025-01-30T15:38:45+00:00" }, { "id": 1936141922, "user": "user_9e49ba0b4492", "body": "Отдельным PR поправлю термин \"виртуальная среда\" во всей документации позже.", "path": "docs/ru/docs/advanced/websockets.md", "line": null, "side": "RIGHT", "created_at": "2025-01-30T19:03:42+00:00" }, { "id": 1936314719, "user": "user_6d7d83efab20", "body": "```suggestion\nДля этого примера мы воспользуемся очень простым HTML документом с небольшими вставками JavaScript кода.\n```", "path": "docs/ru/docs/advanced/websockets.md", "line": 33, "side": "RIGHT", "created_at": "2025-01-30T21:22:36+00:00" }, { "id": 1936319579, "user": "user_6d7d83efab20", "body": "предлагаю вариант: Рабочее приложение", "path": "docs/ru/docs/advanced/websockets.md", "line": null, "side": "RIGHT", "created_at": "2025-01-30T21:27:22+00:00" } ], "meta": { "languages": [ "md" ], "touches_tests": false, "review_state_summary": { "CHANGES_REQUESTED": 1, "COMMENTED": 8, "APPROVED": 3 }, "meaningful_comment_count": 32, "has_approval": true, "has_changes_requested": true, "total_review_comments": 32 } } { "_id": "0bbb1bdc48928d01", "_schema_version": "1.0", "_cleaned_at": "2026-02-12T07:46:52.195116+00:00", "repo": "tiangolo/fastapi", "repo_url": "https://github.com/fastapi/fastapi", "license_name": "MIT License", "license_spdx": "MIT", "pr_number": 13265, "title": "🌐 Add Korean translation for `docs/ko/docs/advanced/custom-response.md`", "body": "## 내용\n이 PR은 `docs/ko/docs/advanced/custom-response.md` 파일에 대한 한국어 번역을 추가합니다. FastAPI 프로젝트에 두 번째로 기여하는 PR이며, 공식 문서를 기반으로 번역을 완료했습니다.\n\n## 참고 사항\n- 문서에서 **\"Custom\"**을 **\"사용자 정의\"**로 번역하여 맥락에 맞는 표현을 사용했습니다.\n- 번역 작업은 최신 FastAPI 문서를 기반으로 진행되었으며, 원본의 Markdown 구조 및 코드 블록은 그대로 유지했습니다.\n\n## 번역 기준\n- 번역 과정에서 다음 용어를 사용했습니다:\n - **Custom**: 사용자 정의\n - **[NAME_REDACTED]**: 응답 클래스\n - **HTMLResponse**: HTML 응답\n - **[NAME_REDACTED]**: 미디어 타입\n\n## 작업 이력\n- 관련 커밋: `🌐 Add Korean translation for docs/ko/docs/advanced/custom-response.md`\n\n## 기여 메시지\n이 PR은 저의 두 번째 오픈소스 기여입니다. 번역 스타일이나 프로세스에서 부족한 점이 있다면 적극적으로 피드백을 반영하겠습니다.\n\n## 검토 요청\n- 번역 내용이 자연스럽고 명확한지 확인 부탁드립니다.\n- **\"Custom\"**을 **\"사용자 정의\"**로 번역한 부분이 적절한지 검토 부탁드립니다.\n- 문서 포맷이나 번역 스타일에서 개선이 필요한 부분에 대한 의견을 주시면 감사하겠습니다.", "author": "user_2cb152fbdf94", "created_at": "2025-01-28T17:35:25+00:00", "merged_at": "2025-02-15T11:21:21+00:00", "base_branch": "master", "head_branch": "korean-translation-custom-response", "additions": 313, "deletions": 0, "changed_files": 1, "files": [ { "filename": "docs/ko/docs/advanced/custom-response.md", "status": "added", "additions": 313, "deletions": 0, "changes": 313, "patch": "@@ -0,0 +1,313 @@\n+# 사용자 정의 응답 - HTML, Stream, 파일, 기타\n+\n+기본적으로, **FastAPI** 응답을 `JSONResponse`를 사용하여 반환합니다.\n+\n+이를 재정의 하려면 [응답을 직접 반환하기](response-directly.md){.internal-link target=_blank}에서 본 것처럼 `Response`를 직접 반환하면 됩니다.\n+\n+그러나 `Response` (또는 `JSONResponse`와 같은 하위 클래스)를 직접 반환하면, 데이터가 자동으로 변환되지 않으며 (심지어 `response_model`을 선언했더라도), 문서화가 자동으로 생성되지 않습니다(예를 들어, 생성된 OpenAPI의 일부로 HTTP 헤더 `Content-Type`에 특정 \"미디어 타입\"을 포함하는 경우).\n+\n+하지만 *경로 작업 데코레이터*에서 `response_class` 매개변수를 사용하여 원하는 `Response`(예: 모든 `Response` 하위 클래스)를 선언할 수도 있습니다.\n+\n+*경로 작업 함수*에서 반환하는 내용은 해당 `Response`안에 포함됩니다.\n+\n+그리고 만약 그 `Response`가 `JSONResponse`와 `UJSONResponse`의 경우 처럼 JSON 미디어 타입(`application/json`)을 가지고 있다면, *경로 작업 데코레이터*에서 선언한 Pydantic의 `response_model`을 사용해 자동으로 변환(및 필터링) 됩니다.\n+\n+/// note | 참고\n+\n+미디어 타입이 없는 응답 클래스를 사용하는 경우, FastAPI는 응답에 내용이 없을 것으로 예상하므로 생성된 OpenAPI 문서에서 응답 형식을 문서화하지 않습니다.\n+\n+///\n+\n+## `ORJSONResponse` 사용하기\n+\n+예를 들어, 성능을 극대화하려는 경우, orjson을 설치하여 사용하고 응답을 `ORJSONResponse`로 설정할 수 있습니다.\n+\n+사용하고자 하는 `Response` 클래스(하위 클래스)를 임포트한 후, **경로 작업 데코레이터*에서 선언하세요.\n+\n+대규모 응답의 경우, 딕셔너리를 반환하는 것보다 `Response`를 반환하는 것이 훨씬 빠릅니다.\n+\n+이유는 기본적으로, FastAPI가 내부의 모든 항목을 검사하고 JSON으로 직렬화할 수 있는지 확인하기 때문입니다. 이는 사용자 안내서에서 설명된 [JSON 호환 가능 인코더](../tutorial/encoder.md){.internal-link target=_blank}를 사용하는 방식과 동일합니다. 이를 통해 데이터베이스 모델과 같은 **임의의 객체**를 반환할 수 있습니다.\n+\n+하지만 반환하는 내용이 **JSON으로 직렬화 가능**하다고 확신하는 경우, 해당 내용을 응답 클래스에 직접 전달할 수 있으며, FastAPI가 반환 내용을 `jsonable_encoder`를 통해 처리한 뒤 응답 클래스에 전달하는 오버헤드를 피할 수 있습니다.\n+\n+{* ../../docs_src/custom_response/tutorial001b.py hl[2,7] *}\n+\n+/// info | 정보\n+\n+`response_class` 매개변수는 응답의 \"미디어 타입\"을 정의하는 데에도 사용됩니다.\n+\n+이 경우, HTTP 헤더 `Content-Type`은 `application/json`으로 설정됩니다.\n+\n+그리고 이는 OpenAPI에 그대로 문서화됩니다.\n+\n+///\n+\n+/// tip | 팁\n+\n+`ORJSONResponse`는 FastAPI에서만 사용할 수 있고 Starlette에서는 사용할 수 없습니다.\n+\n+///\n+\n+## HTML 응답\n+\n+**FastAPI**에서 HTML 응답을 직접 반환하려면 `HTMLResponse`를 사용하세요.\n+\n+* `HTMLResponse`를 임포트 합니다.\n+* *경로 작업 데코레이터*의 `response_class` 매개변수로 `HTMLResponse`를 전달합니다.\n+\n+{* ../../docs_src/custom_response/tutorial002.py hl[2,7] *}\n+\n+/// info | 정보\n+\n+`response_class` 매개변수는 응답의 \"미디어 타입\"을 정의하는 데에도 사용됩니다.\n+\n+이 경우, HTTP 헤더 `Content-Type`은 `text/html`로 설정됩니다.\n+\n+그리고 이는 OpenAPI에 그대로 문서화 됩니다.\n+\n+///\n+\n+### `Response` 반환하기\n+\n+[응답을 직접 반환하기](response-directly.md){.internal-link target=_blank}에서 본 것 처럼, *경로 작업*에서 응답을 직접 반환하여 재정의할 수도 있습니다.\n+\n+위의 예제와 동일하게 `HTMLResponse`를 반환하는 코드는 다음과 같을 수 있습니다:\n+\n+{* ../../docs_src/custom_response/tutorial003.py hl[2,7,19] *}\n+\n+/// warning | 경고\n+\n+*경로 작업 함수*에서 직접 반환된 `Response`는 OpenAPI에 문서화되지 않습니다(예를들어, `Content-Type`이 문서화되지 않음) 자동 대화형 문서에서도 표시되지 않습니다.\n+\n+///\n+\n+/// info | 정보\n+\n+물론 실제 `Content-Type` 헤더, 상태 코드 등은 반환된 `Response` 객체에서 가져옵니다.\n+\n+///\n+\n+### OpenAPI에 문서화하고 `Response` 재정의 하기\n+\n+함수 내부에서 응답을 재정의하면서 동시에 OpenAPI에서 \"미디어 타입\"을 문서화하고 싶다면, `response_class` 매게변수를 사용하면서 `Response` 객체를 반환할 수 있습니다.\n+\n+이 경우 `response_class`는 OpenAPI *경로 작업*을 문서화하는 데만 사용되고, 실제로는 여러분이 반환한 `Response`가 그대로 사용됩니다.\n+\n+### `HTMLResponse`직접 반환하기\n+\n+예를 들어, 다음과 같이 작성할 수 있습니다:\n+\n+{* ../../docs_src/custom_response/tutorial004.py hl[7,21,23] *}\n+\n+이 예제에서, `generate_html_response()` 함수는 HTML을 `str`로 반환하는 대신 이미 `Response`를 생성하고 반환합니다.\n+\n+`generate_html_response()`를 호출한 결과를 반환함으로써, 기본적인 **FastAPI** 기본 동작을 재정의 하는 `Response`를 이미 반환하고 있습니다.\n+\n+하지만 `response_class`에 `HTMLResponse`를 함께 전달했기 때문에, FastAPI는 이를 OpenAPI 및 대화형 문서에서 `text/html`로 HTML을 문서화 하는 방법을 알 수 있습니다.\n+\n+\n+\n+## 사용 가능한 응답들\n+\n+다음은 사용할 수 있는 몇가지 응답들 입니다.\n+\n+`Response`를 사용하여 다른 어떤 것도 반환 할수 있으며, 직접 하위 클래스를 만들 수도 있습니다.\n+\n+/// note | 기술 세부사항\n+\n+`from starlette.responses import HTMLResponse`를 사용할 수도 있습니다.\n+\n+**FastAPI**는 개발자인 여러분의 편의를 위해 `starlette.responses`를 `fastapi.responses`로 제공 하지만, 대부분의 사용 가능한 응답은 Starlette에서 직접 가져옵니다.\n+\n+///\n+\n+### `Response`\n+\n+기본 `Response` 클래스는 다른 모든 응답 클래스의 부모 클래스 입니다.\n+\n+이 클래스를 직접 반환할 수 있습니다.\n+\n+다음 매개변수를 받을 수 있습니다:\n+\n+* `content` - `str` 또는 `bytes`.\n+* `status_code` - HTTP 상태코드를 나타내는 `int`.\n+* `headers` - 문자열로 이루어진 `dict`.\n+* `media_type` - 미디어 타입을 나타내는 `str` 예: `\"text/html\"`.\n+\n+FastAPI (실제로는 Starlette)가 자동으로 `Content-Length` 헤더를 포함시킵니다. 또한 `media_type`에 기반하여 `Content-Type` 헤더를 포함하며, 텍스트 타입의 경우 문자 집합을 추가 합니다.\n+\n+{* ../../docs_src/response_directly/tutorial002.py hl[1,18] *}\n+\n+### `HTMLResponse`\n+\n+텍스트 또는 바이트를 받아 HTML 응답을 반환합니다. 위에서 설명한 내용과 같습니다.\n+\n+### `PlainTextResponse`\n+\n+텍스트 또는 바이트를 받아 일반 텍스트 응답을 반환합니다.\n+\n+{* ../../docs_src/custom_response/tutorial005.py hl[2,7,9] *}\n+\n+### `JSONResponse`\n+\n+데이터를 받아 `application/json`으로 인코딩된 응답을 반환합니다.\n+\n+이는 위에서 설명했듯이 **FastAPI**에서 기본적으로 사용되는 응답 형식입니다.\n+\n+### `ORJSONResponse`\n+\n+ `orjson`을 사용하여 빠른 JSON 응답을 제공하는 대안입니다. 위에서 설명한 내용과 같습니다.\n+\n+/// info | 정보\n+\n+이를 사용하려면 `orjson`을 설치해야합니다. 예: `pip install orjson`.\n+\n+///\n+\n+### `UJSONResponse`\n+\n+`ujson`을 사용한 또 다른 JSON 응답 형식입니다.\n+\n+/// info | 정보\n+\n+이 응답을 사용하려면 `ujson`을 설치해야합니다. 예: 'pip install ujson`.\n+\n+///\n+\n+/// warning | 경고\n+\n+`ujson` 은 일부 예외 경우를 처리하는 데 있어 Python 내장 구현보다 덜 엄격합니다.\n+\n+///\n+\n+{* ../../docs_src/custom_response/tutorial001.py hl[2,7] *}\n+\n+/// tip | 팁\n+\n+`ORJSONResponse`가 더 빠른 대안일 가능성이 있습니다.\n+\n+///\n+\n+### `RedirectResponse`\n+\n+HTTP 리디렉션 응답을 반환합니다. 기본적으로 상태 코드는 307(임시 리디렉션)으로 설정됩니다.\n+\n+`RedirectResponse`를 직접 반환할 수 있습니다.\n+\n+{* ../../docs_src/custom_response/tutorial006.py hl[2,9] *}\n+\n+---\n+\n+또는 `response_class` 매개변수에서 사용할 수도 있습니다:\n+\n+\n+{* ../../docs_src/custom_response/tutorial006b.py hl[2,7,9] *}\n+\n+이 경우, *경로 작업* 함수에서 URL을 직접 반환할 수 있습니다.\n+\n+이 경우, 사용되는 `status_code`는 `RedirectResponse`의 기본값인 `307` 입니다.\n+\n+---\n+\n+`status_code` 매개변수를 `response_class` 매개변수와 함께 사용할 수도 있습니다:\n+\n+{* ../../docs_src/custom_response/tutorial006c.py hl[2,7,9] *}\n+\n+### `StreamingResponse`\n+\n+비동기 제너레이터 또는 일반 제너레이터/이터레이터를 받아 응답 본문을 스트리밍 합니다.\n+\n+{* ../../docs_src/custom_response/tutorial007.py hl[2,14] *}\n+\n+#### 파일과 같은 객체를 사용한 `StreamingResponse`\n+\n+파일과 같은 객체(예: `open()`으로 반환된 객체)가 있는 경우, 해당 파일과 같은 객체를 반복(iterate)하는 제너레이터 함수를 만들 수 있습니다.\n+\n+이 방식으로, 파일 전체를 메모리에 먼저 읽어들일 필요 없이, 제너레이터 함수를 `StreamingResponse`에 전달하여 반환할 수 있습니다.\n+\n+이 방식은 클라우드 스토리지, 비디오 처리 등의 다양한 라이브러리와 함께 사용할 수 있습니다.\n+\n+{* ../../docs_src/custom_response/tutorial008.py hl[2,10:12,14] *}\n+\n+1. 이것이 제너레이터 함수입니다. `yield` 문을 포함하고 있으므로 \"제너레이터 함수\"입니다.\n+2. `with` 블록을 사용함으로써, 제너레이터 함수가 완료된 후 파일과 같은 객체가 닫히도록 합니다. 즉, 응답 전송이 끝난 후 닫힙니다.\n+3. 이 `yield from`은 함수가 `file_like`라는 객체를 반복(iterate)하도록 합니다. 반복된 각 부분은 이 제너레이터 함수(`iterfile`)에서 생성된 것처럼 `yield` 됩니다.\n+\n+ 이렇게 하면 \"생성(generating)\" 작업을 내부적으로 다른 무언가에 위임하는 제너레이터 함수가 됩니다.\n+\n+ 이 방식을 사용하면 `with` 블록 안에서 파일을 열 수 있어, 작업이 완료된 후 파일과 같은 객체가 닫히는 것을 보장할 수 있습니다.\n+\n+/// tip | 팁\n+\n+여기서 표준 `open()`을 사용하고 있기 때문에 `async`와 `await`를 지원하지 않습니다. 따라서 경로 작업은 일반 `def`로 선언합니다.\n+\n+///\n+\n+### `FileResponse`\n+\n+파일을 비동기로 스트리밍하여 응답합니다.\n+\n+다른 응답 유형과는 다른 인수를 사용하여 객체를 생성합니다:\n+\n+* `path` - 스트리밍할 파일의 경로.\n+* `headers` - 딕셔너리 형식의 사용자 정의 헤더.\n+* `media_type` - 미디어 타입을 나타내는 문자열. 설정되지 않은 경우 파일 이름이나 경로를 사용하여 추론합니다.\n+* `filename` - 설정된 경우 응답의 `Content-Disposition`에 포함됩니다.\n+\n+파일 응답에는 적절한 `Content-Length`, `Last-Modified`, 및 `ETag` 헤더가 포함됩니다.\n+\n+{* ../../docs_src/custom_response/tutorial009.py hl[2,10] *}\n+\n+또한 `response_class` 매개변수를 사용할 수도 있습니다:\n+\n+{* ../../docs_src/custom_response/tutorial009b.py hl[2,8,10] *}\n+\n+이 경우, 경로 작업 함수에서 파일 경로를 직접 반환할 수 있습니다.\n+\n+## 사용자 정의 응답 클래스\n+\n+`Response`를 상속받아 사용자 정의 응답 클래스를 생성하고 사용할 수 있습니다.\n+\n+예를 들어, 포함된 `ORJSONResponse` 클래스에서 사용되지 않는 설정으로 orjson을 사용하고 싶다고 가정해봅시다.\n+\n+만약 들여쓰기 및 포맷된 JSON을 반환하고 싶다면, `orjson.OPT_INDENT_2` 옵션을 사용할 수 있습니다.\n+\n+`CustomORJSONResponse`를 생성할 수 있습니다. 여기서 핵심은 `Response.render(content)` 메서드를 생성하여 내용을 `bytes`로 반환하는 것입니다:\n+\n+{* ../../docs_src/custom_response/tutorial009c.py hl[9:14,17] *}\n+\n+이제 다음 대신:\n+\n+```json\n+{\"message\": \"[NAME_REDACTED]\"}\n+```\n+\n+이 응답은 이렇게 반환됩니다:\n+\n+```json\n+{\n+ \"message\": \"[NAME_REDACTED]\"\n+}\n+```\n+\n+물론 JSON 포맷팅보다 더 유용하게 활용할 방법을 찾을 수 있을 것입니다. 😉\n+\n+## 기본 응답 클래스\n+\n+**FastAPI** 클래스 객체 또는 `APIRouter`를 생성할 때 기본적으로 사용할 응답 클래스를 지정할 수 있습니다.\n+\n+이를 정의하는 매개변수는 `default_response_class`입니다.\n+\n+아래 예제에서 **FastAPI**는 모든 경로 작업에서 기본적으로 `JSONResponse` 대신 `ORJSONResponse`를 사용합니다.\n+\n+{* ../../docs_src/custom_response/tutorial010.py hl[2,4] *}\n+\n+/// tip | 팁\n+\n+여전히 이전처럼 *경로 작업*에서 `response_class`를 재정의할 수 있습니다.\n+\n+///\n+\n+## 추가 문서화\n+\n+OpenAPI에서 `responses`를 사용하여 미디어 타입 및 기타 세부 정보를 선언할 수도 있습니다: [OpenAPI에서 추가 응답](additional-responses.md){.internal-link target=_blank}." } ], "reviews": [ { "id": 2601727697, "user": "user_a1942c3a9ec0", "state": "CHANGES_REQUESTED", "body": null, "submitted_at": "2025-02-07T13:35:59+00:00" }, { "id": 2601764012, "user": "user_a1942c3a9ec0", "state": "COMMENTED", "body": null, "submitted_at": "2025-02-07T13:43:44+00:00" }, { "id": 2601816022, "user": "user_a1942c3a9ec0", "state": "CHANGES_REQUESTED", "body": null, "submitted_at": "2025-02-07T14:02:38+00:00" }, { "id": 2605354574, "user": "user_a1942c3a9ec0", "state": "CHANGES_REQUESTED", "body": null, "submitted_at": "2025-02-10T10:39:25+00:00" }, { "id": 2605647173, "user": "user_a1942c3a9ec0", "state": "APPROVED", "body": "LGTM 🚀", "submitted_at": "2025-02-10T12:42:34+00:00" }, { "id": 2612558110, "user": "user_dfad060db61c", "state": "COMMENTED", "body": "Great translation! I have left a few review comments. Please take a look :)\n\n\\* It would be better if you could mark the resolved comments as \"resolved\" for easier review.", "submitted_at": "2025-02-12T17:35:13+00:00" }, { "id": 2614008958, "user": "user_2cb152fbdf94", "state": "COMMENTED", "body": null, "submitted_at": "2025-02-13T06:48:16+00:00" }, { "id": 2618036545, "user": "user_dfad060db61c", "state": "APPROVED", "body": "LGTM 🔥", "submitted_at": "2025-02-14T15:00:07+00:00" } ], "review_comments": [ { "id": 1946524248, "user": "user_a1942c3a9ec0", "body": "Thank you for your \b[NAME_REDACTED]!\nI noticed that in lines 9, 11, and 13, \"path operation\" is translated as \"경로 작업.\" Therefore, please change any instance of \"경로 작동\" to \"경로 작업\" for consistency.", "path": "docs/ko/docs/advanced/custom-response.md", "line": null, "side": "RIGHT", "created_at": "2025-02-07T13:27:31+00:00" }, { "id": 1946545671, "user": "user_a1942c3a9ec0", "body": "In my opinion, translating \"overhead\" simply as \"추가적인 시간\" is a somewhat limited interpretation. Generally, \"overhead\" doesn't refer solely to time but to the extra processing cost (e.g., time, memory, computation, etc.) incurred when performing a particular task or process.\n\nCurrently, there isn't an established translation for \"overhead\" in the Korean version of the documentation. Moreover, in [the German translation of the FastAPI benchmarks document](https://fastapi.tiangolo.com/de/benchmarks/)—which is one of the most frequently referenced sources for this term—\"overhead\" is left unchanged. Considering these examples, it might be best for us to use \"overhead\" as is in our translation, to avoid any confusion and to convey the original meaning accurately.\n\nTherefore, instead of translating \"overhead\" as \"추가적인 시간,\" it's preferable to leave it as \"오버헤드.\"", "path": "docs/ko/docs/advanced/custom-response.md", "line": null, "side": "RIGHT", "created_at": "2025-02-07T13:43:38+00:00" }, { "id": 1946574841, "user": "user_a1942c3a9ec0", "body": "Since \"import\" is a [Python-specific keyword](https://docs.python.org/3.13/reference/import.html), retaining it as \"임포트\" preserves its intended meaning. I recommend keeping it as is.\n\n[NAME_REDACTED] translated documents, such as [body-fields](https://fastapi.tiangolo.com/ko/tutorial/body-fields/#field) and [body-nested-models](https://fastapi.tiangolo.com/ko/tutorial/body-nested-models/#typing-list), directly translate the term \"import\" as \"임포트.\"\n\nthis review include line 25 and 55", "path": "docs/ko/docs/advanced/custom-response.md", "line": null, "side": "RIGHT", "created_at": "2025-02-07T14:02:33+00:00" }, { "id": 1948813336, "user": "user_a1942c3a9ec0", "body": "```suggestion\n* `HTMLResponse`를 임포트합니다.\n```\nminor typo", "path": "docs/ko/docs/advanced/custom-response.md", "line": null, "side": "RIGHT", "created_at": "2025-02-10T10:39:02+00:00" }, { "id": 1953024333, "user": "user_dfad060db61c", "body": "```suggestion\n대규모 응답의 경우, 딕셔너리를 반환하는 것보다 `Response`를 반환하는 것이 훨씬 빠릅니다.\n```\n파이썬 자료형 Dictionary를 의미하므로 `사전`보다는 `딕셔너리`로 사용하는 것이 좋아 보입니다.\n[파이썬 공식 용어집](https://docs.python.org/ko/3.13/glossary.html#term-dictionary)에서도 `딕셔너리`로 사용하고 있습니다.", "path": "docs/ko/docs/advanced/custom-response.md", "line": null, "side": "RIGHT", "created_at": "2025-02-12T16:35:05+00:00" }, { "id": 1953042556, "user": "user_dfad060db61c", "body": "```suggestion\n이 예제에서, `generate_html_response()` 함수는 HTML을 `str`로 반환하는 대신 이미 `Response`를 생성하고 반환합니다.\n```", "path": "docs/ko/docs/advanced/custom-response.md", "line": null, "side": "RIGHT", "created_at": "2025-02-12T16:46:27+00:00" }, { "id": 1953066624, "user": "user_dfad060db61c", "body": "```suggestion\n`ujson` 은 일부 예외 경우를 처리하는 데 있어 Python 내장 구현보다 덜 엄격합니다.\n```\n문장의 순서를 바꾸어 의미를 보다 명확히 하였습니다.", "path": "docs/ko/docs/advanced/custom-response.md", "line": null, "side": "RIGHT", "created_at": "2025-02-12T17:00:46+00:00" }, { "id": 1953076359, "user": "user_dfad060db61c", "body": "```suggestion\n비동기 제너레이터 또는 일반 제너레이터/이터레이터를 받아 응답 본문을 스트리밍 합니다.\n```\n[파이썬 공식 용어집](https://docs.python.org/ko/3.13/glossary.html#term-generator)에 따라,\ngenerator를 `생성기` 보다 `제너레이터` 그대로 번역하는게 어떨지 의견드립니다.", "path": "docs/ko/docs/advanced/custom-response.md", "line": null, "side": "RIGHT", "created_at": "2025-02-12T17:07:22+00:00" }, { "id": 1953079269, "user": "user_dfad060db61c", "body": "```suggestion\n파일과 같은 객체(예: `open()`으로 반환된 객체)가 있는 경우, 해당 파일과 같은 객체를 반복(iterate)하는 제너레이터 함수를 만들 수 있습니다.\n```", "path": "docs/ko/docs/advanced/custom-response.md", "line": null, "side": "RIGHT", "created_at": "2025-02-12T17:09:20+00:00" }, { "id": 1953081025, "user": "user_dfad060db61c", "body": "```suggestion\n이 방식으로, 파일 전체를 메모리에 먼저 읽어들일 필요 없이, 제너레이터 함수를 `StreamingResponse`에 전달하여 반환할 수 있습니다.\n```", "path": "docs/ko/docs/advanced/custom-response.md", "line": null, "side": "RIGHT", "created_at": "2025-02-12T17:10:34+00:00" }, { "id": 1953081864, "user": "user_dfad060db61c", "body": "```suggestion\n1. 이것이 제너레이터 함수입니다. `yield` 문을 포함하고 있으므로 \"제너레이터 함수\"입니다.\n```", "path": "docs/ko/docs/advanced/custom-response.md", "line": null, "side": "RIGHT", "created_at": "2025-02-12T17:11:07+00:00" }, { "id": 1953082646, "user": "user_dfad060db61c", "body": "```suggestion\n2. `with` 블록을 사용함으로써, 제너레이터 함수가 완료된 후 파일과 같은 객체가 닫히도록 합니다. 즉, 응답 전송이 끝난 후 닫힙니다.\n```", "path": "docs/ko/docs/advanced/custom-response.md", "line": null, "side": "RIGHT", "created_at": "2025-02-12T17:11:37+00:00" }, { "id": 1953085039, "user": "user_dfad060db61c", "body": "```suggestion\n3. 이 `yield from`은 함수가 `file_like`라는 객체를 반복(iterate)하도록 합니다. 반복된 각 부분은 이 제너레이터 함수(`iterfile`)에서 생성된 것처럼 `yield` 됩니다.\n```", "path": "docs/ko/docs/advanced/custom-response.md", "line": null, "side": "RIGHT", "created_at": "2025-02-12T17:13:14+00:00" }, { "id": 1953085933, "user": "user_dfad060db61c", "body": "```suggestion\n 이렇게 하면 \"생성(generating)\" 작업을 내부적으로 다른 무언가에 위임하는 제너레이터 함수가 됩니다.\n```", "path": "docs/ko/docs/advanced/custom-response.md", "line": null, "side": "RIGHT", "created_at": "2025-02-12T17:13:48+00:00" }, { "id": 1953095596, "user": "user_dfad060db61c", "body": "```suggestion\n 이 방식을 사용하면 `with` 블록 안에서 파일을 열 수 있어, 작업이 완료된 후 파일과 같은 객체가 닫히는 것을 보장할 수 있습니다.\n```\n`블록 안에서 파일을 열 수 있어, ...`, `블록 안에 파일을 여는 코드를 작성 할 수 있어, ...` 처럼,\n`with` 블록 안에 무엇을 포함시키는 지를 표현해주면, 이해하기 더 쉬울거 같아 제안 드립니다.", "path": "docs/ko/docs/advanced/custom-response.md", "line": null, "side": "RIGHT", "created_at": "2025-02-12T17:19:58+00:00" }, { "id": 1953099173, "user": "user_dfad060db61c", "body": "```suggestion\n* `headers` - 딕셔너리 형식의 사용자 정의 헤더.\n```", "path": "docs/ko/docs/advanced/custom-response.md", "line": null, "side": "RIGHT", "created_at": "2025-02-12T17:22:28+00:00" }, { "id": 1953101142, "user": "user_dfad060db61c", "body": "```suggestion\n`CustomORJSONResponse`를 생성할 수 있습니다. 여기서 핵심은 `Response.render(content)` 메서드를 생성하여 내용을 `bytes`로 반환하는 것입니다:\n```", "path": "docs/ko/docs/advanced/custom-response.md", "line": null, "side": "RIGHT", "created_at": "2025-02-12T17:23:49+00:00" }, { "id": 1953103907, "user": "user_dfad060db61c", "body": "```suggestion\n**FastAPI** 클래스 객체 또는 `APIRouter`를 생성할 때 기본적으로 사용할 응답 클래스를 지정할 수 있습니다.\n```", "path": "docs/ko/docs/advanced/custom-response.md", "line": null, "side": "RIGHT", "created_at": "2025-02-12T17:25:43+00:00" }, { "id": 1953911004, "user": "user_2cb152fbdf94", "body": "오 감사합니다 ㅎㅎ", "path": "docs/ko/docs/advanced/custom-response.md", "line": null, "side": "RIGHT", "created_at": "2025-02-13T06:48:16+00:00" } ], "meta": { "languages": [ "md" ], "touches_tests": false, "review_state_summary": { "CHANGES_REQUESTED": 3, "COMMENTED": 3, "APPROVED": 2 }, "meaningful_comment_count": 19, "has_approval": true, "has_changes_requested": true, "total_review_comments": 19 } } { "_id": "736faaf93a0b37ca", "_schema_version": "1.0", "_cleaned_at": "2026-02-12T07:46:52.195116+00:00", "repo": "tiangolo/fastapi", "repo_url": "https://github.com/fastapi/fastapi", "license_name": "MIT License", "license_spdx": "MIT", "pr_number": 13262, "title": "🌐 Update Korean translation for `docs/ko/docs/help-fastapi.md`", "body": "## [NAME_REDACTED] PR adds a Korean translation for the `docs/ko/docs/help-fastapi.md` file.\nI have modified and translated the format that does not render correctly in Markdown, based on the official English documentation.\n\n\"Screenshot\n\n## Notes\n\n- The `docs/ko/docs/help-fastapi.md` file has not been translated since the first translation (#4139).\n- The translation and format modifications were based on `docs/en/docs/help-fastapi.md`.\n\nhttps://github.com/fastapi/fastapi/blob/b6f6818d76f312fe30d798e52fff16927649db0a/docs/en/docs/help-fastapi.md?plain=1#L1-L269", "author": "user_caad3e3c1c43", "created_at": "2025-01-27T05:31:48+00:00", "merged_at": "2025-02-15T11:37:59+00:00", "base_branch": "master", "head_branch": "docs-help-fastapi", "additions": 197, "deletions": 90, "changed_files": 1, "files": [ { "filename": "docs/ko/docs/help-fastapi.md", "status": "modified", "additions": 197, "deletions": 90, "changes": 287, "patch": "@@ -1,162 +1,269 @@\n-* # FastAPI 지원 - 도움말 받기\n+# FastAPI 지원 - 도움 받기\n \n- **FastAPI** 가 마음에 드시나요?\n+**FastAPI** 가 마음에 드시나요?\n \n- FastAPI, 다른 사용자, 개발자를 응원하고 싶으신가요?\n+FastAPI, 다른 사용자, 개발자를 응원하고 싶으신가요?\n \n- 혹은 **FastAPI** 에 대해 도움이 필요하신가요?\n+혹은 **FastAPI** 에 대해 도움이 필요하신가요?\n \n- 아주 간단하게 응원할 수 있습니다 (몇 번의 클릭만으로).\n+아주 간단하게 응원할 수 있습니다 (몇 번의 클릭만으로).\n \n- 또한 도움을 받을 수 있는 방법도 몇 가지 있습니다.\n+또한 도움을 받을 수 있는 방법도 몇 가지 있습니다.\n \n- ## 뉴스레터 구독\n+## 뉴스레터 구독\n \n- [**FastAPI와 친구** 뉴스레터](https://github.com/fastapi/fastapi/blob/master/newsletter)를 구독하여 최신 정보를 유지할 수 있습니다{.internal-link target=_blank}:\n+[**FastAPI and friends** 뉴스레터](newsletter.md){.internal-link target=\\_blank}를 구독하여 최신 정보를 유지할 수 있습니다:\n \n- - FastAPI 와 그 친구들에 대한 뉴스 🚀\n- - 가이드 📝\n- - 특징 ✨\n- - 획기적인 변화 🚨\n- - 팁과 요령 ✅\n+* FastAPI and friends에 대한 뉴스 🚀\n+* 가이드 📝\n+* 기능 ✨\n+* 획기적인 변화 🚨\n+* 팁과 요령 ✅\n \n- ## 트위터에서 FastAPI 팔로우하기\n+## 트위터에서 FastAPI 팔로우하기\n \n- [Follow [USER_REDACTED] on **Twitter**](https://twitter.com/fastapi) 를 팔로우하여 **FastAPI** 에 대한 최신 뉴스를 얻을 수 있습니다. 🐦\n+**Twitter**의 [USER_REDACTED]를 팔로우하여 **FastAPI** 에 대한 최신 뉴스를 얻을 수 있습니다. 🐦\n \n- ## Star **FastAPI** in GitHub\n+## Star **FastAPI** in GitHub\n \n- GitHub에서 FastAPI에 \"star\"를 붙일 수 있습니다(오른쪽 상단의 star 버튼을 클릭): https://github.com/fastapi/fastapi. ⭐️\n+GitHub에서 FastAPI에 \"star\"를 붙일 수 있습니다 (오른쪽 상단의 star 버튼을 클릭): https://github.com/fastapi/fastapi. ⭐️\n \n- 스타를 늘림으로써, 다른 사용자들이 좀 더 쉽게 찾을 수 있고, 많은 사람들에게 유용한 것임을 나타낼 수 있습니다.\n+스타를 늘림으로써, 다른 사용자들이 좀 더 쉽게 찾을 수 있고, 많은 사람들에게 유용한 것임을 나타낼 수 있습니다.\n \n- ## GitHub 저장소에서 릴리즈 확인\n+## GitHub 저장소에서 릴리즈 확인\n \n- GitHub에서 FastAPI를 \"watch\"할 수 있습니다 (오른쪽 상단 watch 버튼을 클릭): https://github.com/fastapi/fastapi. 👀\n+GitHub에서 FastAPI를 \"watch\"할 수 있습니다 (오른쪽 상단 watch 버튼을 클릭): https://github.com/fastapi/fastapi. 👀\n \n- 여기서 \"Releases only\"을 선택할 수 있습니다.\n+여기서 \"Releases only\"을 선택할 수 있습니다.\n \n- 이렇게하면, **FastAPI** 의 버그 수정 및 새로운 기능의 구현 등의 새로운 자료 (최신 버전)이 있을 때마다 (이메일) 통지를 받을 수 있습니다.\n+이렇게하면, **FastAPI** 의 버그 수정 및 새로운 기능의 구현 등의 새로운 자료 (최신 버전)이 있을 때마다 (이메일) 통지를 받을 수 있습니다.\n \n- ## 개발자와의 연결\n+## 개발자와의 연결\n \n- 개발자인 [me (Sebastián Ramírez / `tiangolo`)](https://tiangolo.com/) 와 연락을 취할 수 있습니다.\n+개발자(Sebastián Ramírez / `tiangolo`)와 연락을 취할 수 있습니다.\n \n- 여러분은 할 수 있습니다:\n+여러분은 할 수 있습니다:\n \n- - [**GitHub**에서 팔로우하기](https://github.com/[USER_REDACTED]).\n- - 당신에게 도움이 될 저의 다른 오픈소스 프로젝트를 확인하십시오.\n- - 새로운 오픈소스 프로젝트를 만들었을 때 확인하려면 팔로우 하십시오.\n+* **GitHub**에서 팔로우하기..\n+ * 당신에게 도움이 될 저의 다른 오픈소스 프로젝트를 확인하십시오.\n+ * 새로운 오픈소스 프로젝트를 만들었을 때 확인하려면 팔로우 하십시오.\n+* **Twitter** 또는 Mastodon에서 팔로우하기.\n+ * FastAPI의 사용 용도를 알려주세요 (그것을 듣는 것을 좋아합니다).\n+ * 발표나 새로운 툴 출시 소식을 받아보십시오.\n+ * **Twitter**의 [USER_REDACTED]를 팔로우 (별도 계정에서) 할 수 있습니다.\n+* **LinkedIn**에서 팔로우하기..\n+ * 새로운 툴의 발표나 출시 소식을 받아보십시오. (단, Twitter를 더 자주 사용합니다 🤷‍♂).\n+* **Dev.to** 또는 **Medium**에서 제가 작성한 내용을 읽어 보십시오 (또는 팔로우).\n+ * 다른 기사나 아이디어들을 읽고, 제가 만들어왔던 툴에 대해서도 읽으십시오.\n+ * 새로운 기사를 읽기 위해 팔로우 하십시오.\n \n- - [**Twitter**에서 팔로우하기](https://twitter.com/tiangolo).\n- - FastAPI의 사용 용도를 알려주세요 (그것을 듣는 것을 좋아합니다).\n- - 발표 또는 새로운 툴 출시할 때 들으십시오.\n- - [follow [USER_REDACTED] on Twitter](https://twitter.com/fastapi) (별도 계정에서) 할 수 있습니다.\n+## **FastAPI**에 대한 트윗\n \n- - [**Linkedin**에서의 연결](https://www.linkedin.com/in/tiangolo/).\n- - 새로운 툴의 발표나 릴리스를 들을 수 있습니다 (단, Twitter를 더 자주 사용합니다 🤷‍♂).\n+**FastAPI**에 대해 트윗 하고 FastAPI가 마음에 드는 이유를 알려주세요. 🎉\n \n- - [**Dev.to**](https://dev.to/tiangolo) 또는 [**Medium**](https://medium.com/[USER_REDACTED])에서 제가 작성한 내용을 읽어 보십시오(또는 팔로우).\n- - 다른 기사나 아이디어들을 읽고, 제가 만들어왔던 툴에 대해서도 읽으십시오.\n- - 새로운 기사를 읽기 위해 팔로우 하십시오.\n+**FastAPI**가 어떻게 사용되고 있는지, 어떤 점이 마음에 들었는지, 어떤 프로젝트/회사에서 사용하고 있는지 등에 대해 듣고 싶습니다.\n \n- ## **FastAPI**에 대한 트윗\n+## FastAPI에 투표하기\n \n- [**FastAPI**에 대해 트윗](https://twitter.com/compose/tweet?text=I'm loving [USER_REDACTED] because... https://github.com/fastapi/fastapi) 하고 FastAPI가 마음에 드는 이유를 알려주세요. 🎉\n+* Slant에서 **FastAPI** 에 대해 투표하십시오.\n+* AlternativeTo에서 **FastAPI** 에 대해 투표하십시오.\n+* StackShare에서 **FastAPI** 에 대해 투표하십시오.\n \n- **FastAPI**가 어떻게 사용되고 있는지, 어떤 점이 마음에 들었는지, 어떤 프로젝트/회사에서 사용하고 있는지 등에 대해 듣고 싶습니다.\n+## GitHub의 이슈로 다른사람 돕기\n \n- ## FastAPI에 투표하기\n+다른 사람들의 질문에 도움을 줄 수 있습니다:\n \n- - [Slant에서 **FastAPI** 에 대해 투표하십시오](https://www.slant.co/options/34241/~fastapi-review).\n- - [AlternativeTo**FastAPI** 에 대해 투표하십시오](https://alternativeto.net/software/fastapi/).\n+* GitHub 디스커션\n+* GitHub 이슈\n \n- ## GitHub의 이슈로 다른사람 돕기\n+많은 경우, 여러분은 이미 그 질문에 대한 답을 알고 있을 수도 있습니다. 🤓\n \n- [존재하는 이슈](https://github.com/fastapi/fastapi/issues)를 확인하고 그것을 시도하고 도와줄 수 있습니다. 대부분의 경우 이미 답을 알고 있는 질문입니다. 🤓\n+만약 많은 사람들의 문제를 도와준다면, 공식적인 [FastAPI 전문가](fastapi-people.md#fastapi-experts){.internal-link target=\\_blank} 가 될 것입니다. 🎉\n \n- 많은 사람들의 문제를 도와준다면, 공식적인 [FastAPI 전문가](https://github.com/fastapi/fastapi/blob/master/docs/en/docs/fastapi-people.md#experts) 가 될 수 있습니다{.internal-link target=_blank}. 🎉\n+가장 중요한 점은: 친절하려고 노력하는 것입니다. 사람들은 좌절감을 안고 오며, 많은 경우 최선의 방식으로 질문하지 않을 수도 있습니다. 하지만 최대한 친절하게 대하려고 노력하세요. 🤗\n \n- ## GitHub 저장소 보기\n+**FastAPI** 커뮤니티의 목표는 친절하고 환영하는 것입니다. 동시에, 괴롭힘이나 무례한 행동을 받아들이지 마세요. 우리는 서로를 돌봐야 합니다.\n \n- GitHub에서 FastAPI를 \"watch\"할 수 있습니다 (오른쪽 상단 watch 버튼을 클릭): https://github.com/fastapi/fastapi. 👀\n+---\n \n- \"Releases only\" 대신 \"Watching\"을 선택하면 다른 사용자가 새로운 issue를 생성할 때 알림이 수신됩니다.\n+다른 사람들의 질문 (디스커션 또는 이슈에서) 해결을 도울 수 있는 방법은 다음과 같습니다.\n \n- 그런 다음 이런 issues를 해결 할 수 있도록 도움을 줄 수 있습니다.\n+### 질문 이해하기\n \n- ## 이슈 생성하기\n+* 질문하는 사람이 가진 **목적**과 사용 사례를 이해할 수 있는지 확인하세요.\n \n- GitHub 저장소에 [새로운 이슈 생성](https://github.com/fastapi/fastapi/issues/new/choose) 을 할 수 있습니다, 예를들면 다음과 같습니다:\n+* 질문 (대부분은 질문입니다)이 **명확**한지 확인하세요.\n \n- - **질문**을 하거나 **문제**에 대해 질문합니다.\n- - 새로운 **기능**을 제안 합니다.\n+* 많은 경우, 사용자가 가정한 해결책에 대한 질문을 하지만, 더 **좋은** 해결책이 있을 수 있습니다. 문제와 사용 사례를 더 잘 이해하면 더 나은 **대안적인 해결책**을 제안할 수 있습니다.\n \n- **참고**: 만약 이슈를 생성한다면, 저는 여러분에게 다른 사람들을 도와달라고 부탁할 것입니다. 😉\n+* 질문을 이해할 수 없다면, 더 **자세한 정보**를 요청하세요.\n \n- ## Pull Request를 만드십시오\n+### 문제 재현하기\n \n- Pull Requests를 이용하여 소스코드에 [컨트리뷰트](https://github.com/fastapi/fastapi/blob/master/docs/en/docs/contributing.md){.internal-link target=_blank} 할 수 있습니다. 예를 들면 다음과 같습니다:\n+대부분의 경우, 질문은 질문자의 **원본 코드**와 관련이 있습니다.\n \n- - 문서에서 찾은 오타를 수정할 때.\n+많은 경우, 코드의 일부만 복사해서 올리지만, 그것만으로는 **문제를 재현**하기에 충분하지 않습니다.\n \n- - FastAPI를 [편집하여](https://github.com/fastapi/fastapi/edit/master/docs/en/data/external_links.yml) 작성했거나 찾은 문서, 비디오 또는 팟캐스트를 공유할 때.\n+* 질문자에게 최소한의 재현 가능한 예제를 제공해달라고 요청하세요. 이렇게 하면 코드를 **복사-붙여넣기**하여 직접 실행하고, 동일한 오류나 동작을 확인하거나 사용 사례를 더 잘 이해할 수 있습니다.\n \n- - 해당 섹션의 시작 부분에 링크를 추가했는지 확인하십시오.\n+* 너그러운 마음이 든다면, 문제 설명만을 기반으로 직접 **예제를 만들어**볼 수도 있습니다. 하지만, 이는 시간이 많이 걸릴 수 있으므로, 먼저 질문을 명확히 해달라고 요청하는 것이 좋습니다.\n \n- - 당신의 언어로 [문서 번역하는데](https://github.com/fastapi/fastapi/blob/master/docs/en/docs/contributing.md#translations){.internal-link target=_blank} 기여할 때.\n+### 해결책 제안하기\n \n- - 또한 다른 사용자가 만든 번역을 검토하는데 도움을 줄 수도 있습니다.\n+* 질문을 충분히 이해한 후에는 가능한 **답변**을 제공할 수 있습니다.\n \n- - 새로운 문서의 섹션을 제안할 때.\n+* 많은 경우, 질문자의 **근본적인 문제나 사용 사례**를 이해하는 것이 중요합니다. 그들이 시도하는 방법보다 더 나은 해결책이 있을 수 있기 때문입니다.\n \n- - 기존 문제/버그를 수정할 때.\n+### 해결 요청하기\n \n- - 새로운 feature를 추가할 때.\n+질문자가 답변을 확인하고 나면, 당신이 문제를 해결했을 가능성이 높습니다. 축하합니다, **당신은 영웅입니다**! 🦸\n \n- ## 채팅에 참여하십시오\n+* 이제 문제를 해결했다면, 질문자에게 다음을 요청할 수 있습니다.\n \n- 👥 [디스코드 채팅 서버](https://discord.gg/VQjSZaeJmf) 👥 에 가입하고 FastAPI 커뮤니티에서 다른 사람들과 어울리세요.\n+ * GitHub 디스커션에서: 댓글을 **답변**으로 표시하도록 요청하세요.\n+ * GitHub 이슈에서: 이슈를 **닫아달라고** 요청하세요.\n \n- /// tip\n+## GitHub 저장소 보기\n \n- 질문이 있는 경우, [GitHub 이슈 ](https://github.com/fastapi/fastapi/issues/new/choose) 에서 질문하십시오, [FastAPI 전문가](https://github.com/fastapi/fastapi/blob/master/docs/en/docs/fastapi-people.md#experts) 의 도움을 받을 가능성이 높습니다{.internal-link target=_blank} .\n+GitHub에서 FastAPI를 \"watch\"할 수 있습니다 (오른쪽 상단 watch 버튼을 클릭): https://github.com/fastapi/fastapi. 👀\n \n- ///\n+\"Releases only\" 대신 \"Watching\"을 선택하면, 새로운 이슈나 질문이 생성될 때 알림을 받을 수 있습니다. 또한, 특정하게 새로운 이슈, 디스커션, PR 등만 알림 받도록 설정할 수도 있습니다.\n \n- ```\n- 다른 일반적인 대화에서만 채팅을 사용하십시오.\n- ```\n+그런 다음 이런 이슈들을 해결 할 수 있도록 도움을 줄 수 있습니다.\n \n- 기존 [지터 채팅](https://gitter.im/fastapi/fastapi) 이 있지만 채널과 고급기능이 없어서 대화를 하기가 조금 어렵기 때문에 지금은 디스코드가 권장되는 시스템입니다.\n+## 이슈 생성하기\n \n- ### 질문을 위해 채팅을 사용하지 마십시오\n+GitHub 저장소에 새로운 이슈 생성을 할 수 있습니다, 예를들면 다음과 같습니다:\n \n- 채팅은 더 많은 \"자유로운 대화\"를 허용하기 때문에, 너무 일반적인 질문이나 대답하기 어려운 질문을 쉽게 질문을 할 수 있으므로, 답변을 받지 못할 수 있습니다.\n+* **질문**을 하거나 **문제**에 대해 질문합니다.\n+* 새로운 **기능**을 제안 합니다.\n \n- GitHub 이슈에서의 템플릿은 올바른 질문을 작성하도록 안내하여 더 쉽게 좋은 답변을 얻거나 질문하기 전에 스스로 문제를 해결할 수도 있습니다. 그리고 GitHub에서는 시간이 조금 걸리더라도 항상 모든 것에 답할 수 있습니다. 채팅 시스템에서는 개인적으로 그렇게 할 수 없습니다. 😅\n+**참고**: 만약 이슈를 생성한다면, 저는 여러분에게 다른 사람들을 도와달라고 부탁할 것입니다. 😉\n \n- 채팅 시스템에서의 대화 또한 GitHub에서 처럼 쉽게 검색할 수 없기 때문에 대화 중에 질문과 답변이 손실될 수 있습니다. 그리고 GitHub 이슈에 있는 것만 [FastAPI 전문가](https://github.com/fastapi/fastapi/blob/master/docs/en/docs/fastapi-people.md#experts)가 되는 것으로 간주되므로{.internal-link target=_blank} , GitHub 이슈에서 더 많은 관심을 받을 것입니다.\n+## Pull Requests 리뷰하기\n \n- 반면, 채팅 시스템에는 수천 명의 사용자가 있기 때문에, 거의 항상 대화 상대를 찾을 가능성이 높습니다. 😄\n+다른 사람들의 pull request를 리뷰하는 데 도움을 줄 수 있습니다.\n \n- ## 개발자 스폰서가 되십시오\n+다시 한번 말하지만, 최대한 친절하게 리뷰해 주세요. 🤗\n \n- [GitHub 스폰서](https://github.com/[USER_REDACTED]nsors/tiangolo) 를 통해 개발자를 경제적으로 지원할 수 있습니다.\n+---\n \n- 감사하다는 말로 커피를 ☕️ 한잔 사줄 수 있습니다. 😄\n+Pull Rrquest를 리뷰할 때 고려해야 할 사항과 방법은 다음과 같습니다:\n \n- 또한 FastAPI의 실버 또는 골드 스폰서가 될 수 있습니다. 🏅🎉\n+### 문제 이해하기\n \n- ## FastAPI를 강화하는 도구의 스폰서가 되십시오\n+* 먼저, 해당 pull request가 해결하려는 **문제를 이해하는지** 확인하세요. GitHub 디스커션 또는 이슈에서 더 긴 논의가 있었을 수도 있습니다.\n \n- 문서에서 보았듯이, FastAPI는 Starlette과 Pydantic 라는 거인의 어깨에 타고 있습니다.\n+* Pull request가 필요하지 않을 가능성도 있습니다. **다른 방식**으로 문제를 해결할 수 있다면, 그 방법을 제안하거나 질문할 수 있습니다.\n \n- 다음의 스폰서가 될 수 있습니다\n+### 스타일에 너무 신경 쓰지 않기\n \n- - [[NAME_REDACTED] (Pydantic)](https://github.com/[USER_REDACTED]nsors/samuelcolvin)\n- - [Encode (Starlette, Uvicorn)](https://github.com/[USER_REDACTED]nsors/encode)\n+* 커밋 메시지 스타일 같은 것에 너무 신경 쓰지 않아도 됩니다. 저는 직접 커밋을 수정하여 squash and merge를 수행할 것입니다.\n \n- ------\n+* 코드 스타일 규칙도 걱정할 필요 없습니다. 이미 자동화된 도구들이 이를 검사하고 있습니다.\n \n- 감사합니다! 🚀\n+스타일이나 일관성 관련 요청이 필요한 경우, 제가 직접 요청하거나 필요한 변경 사항을 추가 커밋으로 수정할 것입니다.\n+\n+### 코드 확인하기\n+\n+* 코드를 읽고, **논리적으로 타당**한지 확인한 후 로컬에서 실행하여 문제가 해결되는지 확인하세요.\n+\n+* 그런 다음, 확인했다고 **댓글**을 남겨 주세요. 그래야 제가 검토했음을 알 수 있습니다.\n+\n+/// info\n+\n+불행히도, 제가 단순히 여러 개의 승인만으로 PR을 신뢰할 수는 없습니다.\n+\n+3개, 5개 이상의 승인이 달린 PR이 실제로는 깨져 있거나, 버그가 있거나, 주장하는 문제를 해결하지 못하는 경우가 여러 번 있었습니다. 😅\n+\n+따라서, 정말로 코드를 읽고 실행한 뒤, 댓글로 확인 내용을 남겨 주는 것이 매우 중요합니다. 🤓\n+\n+///\n+\n+* PR을 더 단순하게 만들 수 있다면 그렇게 요청할 수 있지만, 너무 까다로울 필요는 없습니다. 주관적인 견해가 많이 있을 수 있기 때문입니다 (그리고 저도 제 견해가 있을 거예요 🙈). 따라서 핵심적인 부분에 집중하는 것이 좋습니다.\n+\n+### 테스트\n+\n+* PR에 **테스트**가 포함되어 있는지 확인하는 데 도움을 주세요.\n+\n+* PR을 적용하기 전에 테스트가 **실패**하는지 확인하세요. 🚨\n+\n+* PR을 적용한 후 테스트가 **통과**하는지 확인하세요. ✅\n+\n+* 많은 PR에는 테스트가 없습니다. 테스트를 추가하도록 **상기**시켜줄 수도 있고, 직접 테스트를 **제안**할 수도 있습니다. 이는 시간이 많이 소요되는 부분 중 하나이며, 그 부분을 많이 도와줄 수 있습니다.\n+\n+* 그리고 시도한 내용을 댓글로 남겨주세요. 그러면 제가 확인했다는 걸 알 수 있습니다. 🤓\n+\n+## Pull Request를 만드십시오\n+\n+Pull Requests를 이용하여 소스코드에 [컨트리뷰트](contributing.md){.internal-link target=\\_blank} 할 수 있습니다. 예를 들면 다음과 같습니다:\n+\n+* 문서에서 발견한 오타를 수정할 때.\n+* FastAPI 관련 문서, 비디오 또는 팟캐스트를 작성했거나 발견하여 이 파일을 편집하여 공유할 때.\n+ * 해당 섹션의 시작 부분에 링크를 추가해야 합니다.\n+* 당신의 언어로 [문서 번역하는데](contributing.md#translations){.internal-link target=\\_blank} 기여할 때.\n+ * 다른 사람이 작성한 번역을 검토하는 것도 도울 수 있습니다.\n+* 새로운 문서의 섹션을 제안할 때.\n+* 기존 문제/버그를 수정할 때.\n+ * 테스트를 반드시 추가해야 합니다.\n+* 새로운 feature를 추가할 때.\n+ * 테스트를 반드시 추가해야 합니다.\n+ * 관련 문서가 필요하다면 반드시 추가해야 합니다.\n+\n+## FastAPI 유지 관리에 도움 주기\n+\n+**FastAPI**의 유지 관리를 도와주세요! 🤓\n+\n+할 일이 많고, 그 중 대부분은 **여러분**이 할 수 있습니다.\n+\n+지금 할 수 있는 주요 작업은:\n+\n+* [GitHub에서 다른 사람들의 질문에 도움 주기](#github_1){.internal-link target=_blank} (위의 섹션을 참조하세요).\n+* [Pull Request 리뷰하기](#pull-requests){.internal-link target=_blank} (위의 섹션을 참조하세요).\n+\n+이 두 작업이 **가장 많은 시간을 소모**하는 일입니다. 그것이 FastAPI 유지 관리의 주요 작업입니다.\n+\n+이 작업을 도와주신다면, **FastAPI 유지 관리에 도움을 주는 것**이며 그것이 **더 빠르고 더 잘 발전하는 것**을 보장하는 것입니다. 🚀\n+\n+## 채팅에 참여하십시오\n+\n+👥 디스코드 채팅 서버 👥 에 가입하고 FastAPI 커뮤니티에서 다른 사람들과 어울리세요.\n+\n+/// tip\n+\n+질문이 있는 경우, GitHub 디스커션 에서 질문하십시오, [[NAME_REDACTED]](fastapi-people.md#fastapi-experts){.internal-link target=_blank} 의 도움을 받을 가능성이 높습니다.\n+\n+다른 일반적인 대화에서만 채팅을 사용하십시오.\n+\n+///\n+\n+### 질문을 위해 채팅을 사용하지 마십시오\n+\n+채팅은 더 많은 \"자유로운 대화\"를 허용하기 때문에, 너무 일반적인 질문이나 대답하기 어려운 질문을 쉽게 질문을 할 수 있으므로, 답변을 받지 못할 수 있습니다.\n+\n+GitHub 이슈에서의 템플릿은 올바른 질문을 작성하도록 안내하여 더 쉽게 좋은 답변을 얻거나 질문하기 전에 스스로 문제를 해결할 수도 있습니다. 그리고 GitHub에서는 시간이 조금 걸리더라도 항상 모든 것에 답할 수 있습니다. 채팅 시스템에서는 개인적으로 그렇게 할 수 없습니다. 😅\n+\n+채팅 시스템에서의 대화 또한 GitHub에서 처럼 쉽게 검색할 수 없기 때문에 대화 중에 질문과 답변이 손실될 수 있습니다. 그리고 GitHub 이슈에 있는 것만 [[NAME_REDACTED]](fastapi-people.md#fastapi-experts){.internal-link target=_blank}가 되는 것으로 간주되므로, GitHub 이슈에서 더 많은 관심을 받을 것입니다.\n+\n+반면, 채팅 시스템에는 수천 명의 사용자가 있기 때문에, 거의 항상 대화 상대를 찾을 가능성이 높습니다. 😄\n+\n+## 개발자 스폰서가 되십시오\n+\n+GitHub 스폰서 를 통해 개발자를 경제적으로 지원할 수 있습니다.\n+\n+감사하다는 말로 커피를 ☕️ 한잔 사줄 수 있습니다. 😄\n+\n+또한 FastAPI의 실버 또는 골드 스폰서가 될 수 있습니다. 🏅🎉\n+\n+## FastAPI를 강화하는 도구의 스폰서가 되십시오\n+\n+문서에서 보았듯이, FastAPI는 Starlette과 Pydantic 라는 거인의 어깨에 타고 있습니다.\n+\n+다음의 스폰서가 될 수 있습니다\n+\n+* [NAME_REDACTED] (Pydantic)\n+* Encode (Starlette, Uvicorn)\n+\n+---\n+\n+감사합니다! 🚀" } ], "reviews": [ { "id": 2603871515, "user": "user_a1942c3a9ec0", "state": "COMMENTED", "body": null, "submitted_at": "2025-02-08T15:35:57+00:00" }, { "id": 2604147761, "user": "user_a1942c3a9ec0", "state": "APPROVED", "body": "LGTM 🚀", "submitted_at": "2025-02-09T08:20:25+00:00" }, { "id": 2604289986, "user": "user_dfad060db61c", "state": "COMMENTED", "body": "Thank you for your update. I'm happy that the markdown has been rendered correctly :)", "submitted_at": "2025-02-09T15:43:07+00:00" }, { "id": 2604542195, "user": "user_dfad060db61c", "state": "COMMENTED", "body": null, "submitted_at": "2025-02-10T01:32:59+00:00" }, { "id": 2605645814, "user": "user_dfad060db61c", "state": "APPROVED", "body": "LGTM 🔥", "submitted_at": "2025-02-10T12:41:59+00:00" } ], "review_comments": [ { "id": 1947840846, "user": "user_a1942c3a9ec0", "body": "```suggestion\n* 기능 ✨\n```\n\nIn the previous translation work, \"feature\" was rendered as \"특징,\" but in this context, it seems more natural to translate it as \"기능.\" What do you think?", "path": "docs/ko/docs/help-fastapi.md", "line": null, "side": "RIGHT", "created_at": "2025-02-08T15:05:24+00:00" }, { "id": 1947842755, "user": "user_a1942c3a9ec0", "body": "```suggestion\n[**FastAPI and friends** 뉴스레터](newsletter.md){.internal-link target=\\_blank}를 구독하여 최신 정보를 유지할 수 있습니다:\n```\n\"FastAPI and friends\" is considered a proper noun referring to FastAPI and its related projects in this context. Therefore, I suggest keeping \"FastAPI and friends\" in English rather than translating it. What do you think about this approach?\n\nFor reference, the [독일어 번역버전](https://fastapi.tiangolo.com/de/help-fastapi/#newsletter-abonnieren) retains the original text.", "path": "docs/ko/docs/help-fastapi.md", "line": null, "side": "RIGHT", "created_at": "2025-02-08T15:17:47+00:00" }, { "id": 1947842831, "user": "user_a1942c3a9ec0", "body": "```suggestion\n* FastAPI and friends에 대한 뉴스 🚀\n```", "path": "docs/ko/docs/help-fastapi.md", "line": null, "side": "RIGHT", "created_at": "2025-02-08T15:18:18+00:00" }, { "id": 1947844921, "user": "user_a1942c3a9ec0", "body": "```suggestion\n * 발표나 새로운 툴 출시 소식을 받아보십시오.\n```\n\nthe previous translation rendered \"hear\" as \"들으십시오,\" which sounds unnatural in Korean, and it suggests changing it to \"소식을 받아보십시오\"", "path": "docs/ko/docs/help-fastapi.md", "line": null, "side": "RIGHT", "created_at": "2025-02-08T15:31:12+00:00" }, { "id": 1947845784, "user": "user_a1942c3a9ec0", "body": "```suggestion\n * 새로운 툴의 발표나 출시 소식을 받아보십시오. (단, Twitter를 더 자주 사용합니다 🤷‍♂).\n```", "path": "docs/ko/docs/help-fastapi.md", "line": null, "side": "RIGHT", "created_at": "2025-02-08T15:34:43+00:00" }, { "id": 1948131301, "user": "user_dfad060db61c", "body": "```suggestion\n개발자(Sebastián Ramírez / `tiangolo`)와 연락을 취할 수 있습니다.\n```\nI think it would be better if you modify it to \"개발자와 연락을\" or \"개발자인 저와 연락을\"", "path": "docs/ko/docs/help-fastapi.md", "line": null, "side": "RIGHT", "created_at": "2025-02-09T15:20:17+00:00" }, { "id": 1948133800, "user": "user_dfad060db61c", "body": "```suggestion\n\"Releases only\" 대신 \"Watching\"을 선택하면, 새로운 이슈나 질문이 생성될 때 알림을 받을 수 있습니다. 또한, 특정하게 새로운 이슈, 디스커션, PR 등만 알림 받도록 설정할 수도 있습니다.\n```\nI think It would be better to translate \"issue\"→\"이슈\" and \"discussion\"→\"디스커션\" in lines 130, 132.\nBecause \"이슈\" and \"디스커션\" are already used in lines 72, 89, and 123.", "path": "docs/ko/docs/help-fastapi.md", "line": null, "side": "RIGHT", "created_at": "2025-02-09T15:32:39+00:00" }, { "id": 1948302732, "user": "user_dfad060db61c", "body": "```suggestion\n그런 다음 이런 이슈들을 해결 할 수 있도록 도움을 줄 수 있습니다.\n```\nI noticed that one of \"issue\" was missed in the translation 😭", "path": "docs/ko/docs/help-fastapi.md", "line": null, "side": "RIGHT", "created_at": "2025-02-10T01:32:59+00:00" } ], "meta": { "languages": [ "md" ], "touches_tests": false, "review_state_summary": { "COMMENTED": 3, "APPROVED": 2 }, "meaningful_comment_count": 8, "has_approval": true, "has_changes_requested": false, "total_review_comments": 8 } } { "_id": "bf377438eb25297e", "_schema_version": "1.0", "_cleaned_at": "2026-02-12T07:46:52.195116+00:00", "repo": "tiangolo/fastapi", "repo_url": "https://github.com/fastapi/fastapi", "license_name": "MIT License", "license_spdx": "MIT", "pr_number": 13259, "title": "📝 Update testing events documentation", "body": "`lifespan` should be included in th document, instead of only `startup` and `shutdown`", "author": "user_21d6a1943f4f", "created_at": "2025-01-26T00:56:22+00:00", "merged_at": "2025-08-31T10:29:21+00:00", "base_branch": "master", "head_branch": "master", "additions": 57, "deletions": 2, "changed_files": 3, "files": [ { "filename": "docs/en/docs/advanced/testing-events.md", "status": "modified", "additions": 9, "deletions": 2, "changes": 11, "patch": "@@ -1,5 +1,12 @@\n-# [NAME_REDACTED]: startup - shutdown { #testing-events-startup-shutdown }\n+# [NAME_REDACTED]: lifespan and startup - shutdown { #testing-events-lifespan-and-startup-shutdown }\n \n-When you need your event handlers (`startup` and `shutdown`) to run in your tests, you can use the `TestClient` with a `with` statement:\n+When you need `lifespan` to run in your tests, you can use the `TestClient` with a `with` statement:\n+\n+{* ../../docs_src/app_testing/tutorial004.py hl[9:15,18,27:28,30:32,41:43] *}\n+\n+\n+You can read more details about the [\"Running lifespan in tests in the official Starlette documentation site.\"](https://www.starlette.io/lifespan/#running-lifespan-in-tests)\n+\n+For the deprecated `startup` and `shutdown` events, you can use the `TestClient` as follows:\n \n {* ../../docs_src/app_testing/tutorial003.py hl[9:12,20:24] *}" }, { "filename": "docs_src/app_testing/tutorial004.py", "status": "added", "additions": 43, "deletions": 0, "changes": 43, "patch": "@@ -0,0 +1,43 @@\n+from contextlib import asynccontextmanager\n+\n+from fastapi import FastAPI\n+from fastapi.testclient import TestClient\n+\n+items = {}\n+\n+\n+[USER_REDACTED]\n+async def lifespan(app: FastAPI):\n+ items[\"foo\"] = {\"name\": \"Fighters\"}\n+ items[\"bar\"] = {\"name\": \"Tenders\"}\n+ yield\n+ # clean up items\n+ items.clear()\n+\n+\n+app = FastAPI(lifespan=lifespan)\n+\n+\n+[USER_REDACTED].get(\"/items/{item_id}\")\n+async def read_items(item_id: str):\n+ return items[item_id]\n+\n+\n+def test_read_items():\n+ # Before the lifespan starts, \"items\" is still empty\n+ assert items == {}\n+\n+ with TestClient(app) as client:\n+ # Inside the \"with TestClient\" block, the lifespan starts and items added\n+ assert items == {\"foo\": {\"name\": \"Fighters\"}, \"bar\": {\"name\": \"Tenders\"}}\n+\n+ response = client.get(\"/items/foo\")\n+ assert response.status_code == 200\n+ assert response.json() == {\"name\": \"Fighters\"}\n+\n+ # After the requests is done, the items are still there\n+ assert items == {\"foo\": {\"name\": \"Fighters\"}, \"bar\": {\"name\": \"Tenders\"}}\n+\n+ # The end of the \"with TestClient\" block simulates terminating the app, so\n+ # the lifespan ends and items are cleaned up\n+ assert items == {}" }, { "filename": "tests/test_tutorial/test_testing/test_tutorial004.py", "status": "added", "additions": 5, "deletions": 0, "changes": 5, "patch": "@@ -0,0 +1,5 @@\n+from docs_src.app_testing.tutorial004 import test_read_items\n+\n+\n+def test_main():\n+ test_read_items()" } ], "reviews": [ { "id": 3019315372, "user": "user_29e85f9a8e75", "state": "COMMENTED", "body": "[USER_REDACTED], thanks for your interest in FastAPI!\n\nLGTM in general!\nLet's discuss my suggestions", "submitted_at": "2025-07-15T08:37:10+00:00" }, { "id": 3019677706, "user": "user_21d6a1943f4f", "state": "COMMENTED", "body": null, "submitted_at": "2025-07-15T10:18:21+00:00" }, { "id": 3019770639, "user": "user_21d6a1943f4f", "state": "COMMENTED", "body": null, "submitted_at": "2025-07-15T10:51:01+00:00" }, { "id": 3019794030, "user": "user_21d6a1943f4f", "state": "COMMENTED", "body": null, "submitted_at": "2025-07-15T10:59:34+00:00" }, { "id": 3019798302, "user": "user_29e85f9a8e75", "state": "COMMENTED", "body": null, "submitted_at": "2025-07-15T11:01:01+00:00" }, { "id": 3019808086, "user": "user_21d6a1943f4f", "state": "COMMENTED", "body": null, "submitted_at": "2025-07-15T11:04:39+00:00" }, { "id": 3020357270, "user": "user_29e85f9a8e75", "state": "APPROVED", "body": "LGTM\n\n[USER_REDACTED], thanks!", "submitted_at": "2025-07-15T13:37:27+00:00" }, { "id": 3171557743, "user": "user_2a237e38e06b", "state": "APPROVED", "body": "Thanks! I tweaked it a bit, it's now ready. 🚀", "submitted_at": "2025-08-31T10:27:10+00:00" } ], "review_comments": [ { "id": 2206838994, "user": "user_29e85f9a8e75", "body": "To ensure the code with startup\\shutdown is still tested, I would split this code example into two separate: first is for `lifespan`, second is for `startup` and `shutdown`.\nWe can add the warning that it's deprecated outside the code block.\nWhat do you think?", "path": "docs_src/app_testing/tutorial003.py", "line": null, "side": "RIGHT", "created_at": "2025-07-15T08:34:15+00:00" }, { "id": 2206843721, "user": "user_29e85f9a8e75", "body": "Should we add \"lifespan\" here?", "path": "docs/en/docs/advanced/testing-events.md", "line": null, "side": "RIGHT", "created_at": "2025-07-15T08:36:25+00:00" }, { "id": 2207077688, "user": "user_21d6a1943f4f", "body": "Two files? OK, I agreed", "path": "docs_src/app_testing/tutorial003.py", "line": null, "side": "RIGHT", "created_at": "2025-07-15T10:18:21+00:00" }, { "id": 2207140254, "user": "user_21d6a1943f4f", "body": "However, I can't pass the test. I don't how to solve this.\n\n```\n==================================== ERRORS ====================================\n____ ERROR collecting tests/test_tutorial/test_testing/test_tutorial003.py _____\ntests/test_tutorial/test_testing/test_tutorial003.py:1: in \n from docs_src.app_testing.tutorial003 import test_read_items\ndocs_src/app_testing/tutorial003.py:9: in \n [USER_REDACTED].on_event(\"startup\")\n ^^^^^^^^^^^^^^^^^^^^^^^\n/opt/hostedtoolcache/Python/3.12.11/x64/lib/python3.12/site-packages/typing_extensions.py:2955: in wrapper\n warnings.warn(msg, category=category, stacklevel=stacklevel + 1)\nE DeprecationWarning: \nE on_event is deprecated, use lifespan event handlers instead.\nE \nE Read more about it in the\nE [FastAPI docs for [NAME_REDACTED]](https://fastapi.tiangolo.com/advanced/events/).\n=========================== short test summary info ============================\nERROR tests/test_tutorial/test_testing/test_tutorial003.py - DeprecationWarning: \n on_event is deprecated, use lifespan event handlers instead.\n\n Read more about it in the\n [FastAPI docs for [NAME_REDACTED]](https://fastapi.tiangolo.com/advanced/events/).\n!!!!!!!!!!!!!!!!!!!! Interrupted: 1 error during collection !!!!!!!!!!!!!!!!!!!!\n```\n\nWell, I can't simply add `with pytest.warns(DeprecationWarning):` in a tutorial...\n\n```python\nimport pytest\nfrom fastapi import FastAPI\nfrom fastapi.testclient import TestClient\n\napp = FastAPI()\n\nitems = {}\n\nwith pytest.warns(DeprecationWarning):\n [USER_REDACTED].on_event(\"startup\")\n async def startup_event():\n items[\"foo\"] = {\"name\": \"Fighters\"}\n items[\"bar\"] = {\"name\": \"Tenders\"}\n\n[USER_REDACTED].get(\"/items/{item_id}\")\nasync def read_items(item_id: str):\n return items[item_id]\n\ndef test_read_items():\n with TestClient(app) as client:\n response = client.get(\"/items/foo\")\n assert response.status_code == 200\n assert response.json() == {\"name\": \"Fighters\"}", "path": "docs_src/app_testing/tutorial003.py", "line": null, "side": "RIGHT", "created_at": "2025-07-15T10:51:01+00:00" }, { "id": 2207155856, "user": "user_21d6a1943f4f", "body": "yes\n\n> [NAME_REDACTED]: lifespan and startup - shutdown", "path": "docs/en/docs/advanced/testing-events.md", "line": null, "side": "RIGHT", "created_at": "2025-07-15T10:59:34+00:00" }, { "id": 2207159264, "user": "user_29e85f9a8e75", "body": "Look at the original code of `tests/test_tutorial/test_testing/test_tutorial003.py`:\n```python\ndef test_main():\n with pytest.warns(DeprecationWarning):\n from docs_src.app_testing.tutorial003 import test_read_items\n test_read_items()\n```", "path": "docs_src/app_testing/tutorial003.py", "line": null, "side": "RIGHT", "created_at": "2025-07-15T11:01:01+00:00" }, { "id": 2207165455, "user": "user_21d6a1943f4f", "body": "oh! I missed this.\n\nSorry, I basically forgot the content of this PR...hh", "path": "docs_src/app_testing/tutorial003.py", "line": null, "side": "RIGHT", "created_at": "2025-07-15T11:04:39+00:00" } ], "meta": { "languages": [ "md", "py" ], "touches_tests": true, "review_state_summary": { "COMMENTED": 6, "APPROVED": 2 }, "meaningful_comment_count": 7, "has_approval": true, "has_changes_requested": false, "total_review_comments": 7 } } { "_id": "169b29c4b6d152d0", "_schema_version": "1.0", "_cleaned_at": "2026-02-12T07:46:52.195116+00:00", "repo": "tiangolo/fastapi", "repo_url": "https://github.com/fastapi/fastapi", "license_name": "MIT License", "license_spdx": "MIT", "pr_number": 13257, "title": "🌐 Add Korean translation for `docs/ko/docs/tutorial/dependencies/dependencies-with-yield.md`", "body": "## 내용\n이 PR은 `docs/ko/docs/tutorial/dependencies/dependencies-with-yield.md` 파일에 대한 한국어 번역을 추가합니다. FastAPI 프로젝트에 처음으로 기여하는 PR이며, 공식 문서를 기반으로 번역을 완료했습니다.\n\n## 참고 사항\n- 기존 PR(#4087)이 같은 파일을 번역하는 작업으로 보입니다. 그러나 해당 PR은 2022년 7월 4일에 닫혔고, 이후 병합되지 않았습니다.\n- 이전 PR이 왜 병합되지 않았는지 명확하지 않아 새로운 작업을 진행하게 되었습니다. 혹시 병합되지 않은 이유가 있다면 알려주시면 감사하겠습니다.\n- 이번 번역 작업은 최신 FastAPI 문서를 기반으로 진행되었습니다.\n\n## 번역 기준\n- 번역 과정에서 다음 용어를 사용했습니다:\n - Dependency: 의존성\n - Path Operation: 경로 작업\n - HTTPException: HTTP 예외\n- 문서의 원본 포맷(Markdown 구조 및 코드 블록)을 그대로 유지했습니다.\n\n## 작업 이력\n- 관련 커밋: `🌐 Add Korean translation for docs/ko/docs/tutorial/dependencies/dependencies-with-yield.md`\n\n## 처음 기여에 대한 메시지\n- 이번 PR은 저의 첫 번째 오픈소스 기여입니다. 혹시나 포맷, 프로세스, 또는 번역 스타일에 부족한 부분이 있다면 피드백을 주시면 감사하겠습니다. 기여자로서 성장할 수 있도록 배울 준비가 되어 있습니다.\n\n## 검토 요청\n- 번역 내용이 자연스러운지와 기술 용어가 적절하게 사용되었는지 검토 부탁드립니다.\n- 기존 PR(#4087)과 중복 작업인지, 아니면 기존 작업에서 개선이 필요한 부분이 있어야 병합되지 않았는지에 대한 의견도 부탁드립니다.\n\n---\n\nPR에 대한 피드백과 조언을 적극적으로 반영하겠습니다. 새로운 기여자를 위한 도움을 주셔서 감사합니다!", "author": "user_2cb152fbdf94", "created_at": "2025-01-25T13:11:58+00:00", "merged_at": "2025-02-09T14:54:10+00:00", "base_branch": "master", "head_branch": "korean-translation-dependencies-with-yield", "additions": 275, "deletions": 0, "changed_files": 1, "files": [ { "filename": "docs/ko/docs/tutorial/dependencies/dependencies-with-yield.md", "status": "added", "additions": 275, "deletions": 0, "changes": 275, "patch": "@@ -0,0 +1,275 @@\n+# yield를 사용하는 의존성\n+\n+FastAPI는 작업 완료 후 추가 단계를 수행하는 의존성을 지원합니다.\n+\n+이를 구현하려면 `return` 대신 `yield`를 사용하고, 추가로 실행할 단계 (코드)를 그 뒤에 작성하세요.\n+\n+/// tip | 팁\n+\n+각 의존성마다 `yield`는 한 번만 사용해야 합니다.\n+\n+///\n+\n+/// note | 기술 세부사항\n+\n+다음과 함께 사용할 수 있는 모든 함수:\n+\n+* `[USER_REDACTED].contextmanager` 또는\n+* `[USER_REDACTED].asynccontextmanager`\n+\n+는 **FastAPI**의 의존성으로 사용할 수 있습니다.\n+\n+사실, FastAPI는 내부적으로 이 두 데코레이터를 사용합니다.\n+\n+///\n+\n+## `yield`를 사용하는 데이터베이스 의존성\n+\n+예를 들어, 이 기능을 사용하면 데이터베이스 세션을 생성하고 작업이 끝난 후에 세션을 종료할 수 있습니다.\n+\n+응답을 생성하기 전에는 `yield`문을 포함하여 그 이전의 코드만이 실행됩니다:\n+\n+{* ../../docs_src/dependencies/tutorial007.py hl[2:4] *}\n+\n+yield된 값은 *경로 작업* 및 다른 의존성들에 주입되는 값 입니다:\n+\n+{* ../../docs_src/dependencies/tutorial007.py hl[4] *}\n+\n+`yield`문 다음의 코드는 응답을 생성한 후 보내기 전에 실행됩니다:\n+\n+{* ../../docs_src/dependencies/tutorial007.py hl[5:6] *}\n+\n+/// tip | 팁\n+\n+`async` 함수와 일반 함수 모두 사용할 수 있습니다.\n+\n+**FastAPI**는 일반 의존성과 마찬가지로 각각의 함수를 올바르게 처리할 것입니다.\n+\n+///\n+\n+## `yield`와 `try`를 사용하는 의존성\n+\n+`yield`를 사용하는 의존성에서 `try` 블록을 사용한다면, 의존성을 사용하는 도중 발생한 모든 예외를 받을 수 있습니다.\n+\n+예를 들어, 다른 의존성이나 *경로 작업*의 중간에 데이터베이스 트랜잭션 \"롤백\"이 발생하거나 다른 오류가 발생한다면, 해당 예외를 의존성에서 받을 수 있습니다.\n+\n+따라서, 의존성 내에서 `except SomeException`을 사용하여 특정 예외를 처리할 수 있습니다.\n+\n+마찬가지로, `finally`를 사용하여 예외 발생 여부와 관계 없이 종료 단계까 실행되도록 할 수 있습니다.\n+\n+{* ../../docs_src/dependencies/tutorial007.py hl[3,5] *}\n+\n+## `yield`를 사용하는 하위 의존성\n+\n+모든 크기와 형태의 하위 의존성과 하위 의존성의 \"트리\"도 가질 수 있으며, 이들 모두가 `yield`를 사용할 수 있습니다.\n+\n+**FastAPI**는 `yield`를 사용하는 각 의존성의 \"종료 코드\"가 올바른 순서로 실행되도록 보장합니다.\n+\n+예를 들어, `dependency_c`는 `dependency_b`에 의존할 수 있고, `dependency_b`는 `dependency_a`에 의존할 수 있습니다.\n+\n+{* ../../docs_src/dependencies/tutorial008_an_py39.py hl[6,14,22] *}\n+\n+이들 모두는 `yield`를 사용할 수 있습니다.\n+\n+이 경우 `dependency_c`는 종료 코드를 실행하기 위해, `dependency_b`의 값 (여기서는 `dep_b`로 명명)이 여전히 사용 가능해야 합니다.\n+\n+그리고, `dependency_b`는 종료 코드를 위해 `dependency_a`의 값 (여기서는 `dep_a`로 명명) 이 사용 가능해야 합니다.\n+\n+{* ../../docs_src/dependencies/tutorial008_an_py39.py hl[18:19,26:27] *}\n+\n+같은 방식으로, `yield`를 사용하는 의존성과 `return`을 사용하는 의존성을 함께 사용할 수 있으며, 이들 중 일부가 다른 것들에 의존할 수 있습니다.\n+\n+그리고 `yield`를 사용하는 다른 여러 의존성을 필요로 하는 단일 의존성을 가질 수도 있습니다.\n+\n+원하는 의존성을 원하는 대로 조합할 수 있습니다.\n+\n+**FastAPI**는 모든 것이 올바른 순서로 실행되도록 보장합니다.\n+\n+/// note | 기술 세부사항\n+\n+파이썬의 [NAME_REDACTED] 덕분에 이 기능이 작동합니다.\n+\n+**FastAPI**는 이를 내부적으로 컨텍스트 관리자를 사용하여 구현합니다.\n+\n+///\n+\n+## `yield`와 `HTTPException`를 사용하는 의존성\n+\n+`yield`와 `try` 블록이 있는 의존성을 사용하여 예외를 처리할 수 있다는 것을 알게 되었습니다.\n+\n+같은 방식으로, `yield` 이후의 종료 코드에서 `HTTPException`이나 유사한 예외를 발생시킬 수 있습니다.\n+\n+/// tip | 팁\n+\n+이는 다소 고급 기술이며, 대부분의 경우 경로 연산 함수 등 나머지 애플리케이션 코드 내부에서 예외 (`HTTPException` 포함)를 발생시킬 수 있으므로 실제로는 필요하지 않을 것입니다.\n+\n+하지만 필요한 경우 사용할 수 있습니다. 🤓\n+\n+///\n+\n+{* ../../docs_src/dependencies/tutorial008b_an_py39.py hl[18:22,31] *}\n+\n+예외를 처리하고(또는 추가로 다른 `HTTPException`을 발생시키기 위해) 사용할 수 있는 또 다른 방법은 [사용자 정의 예외 처리기](../handling-errors.md#install-custom-exception-handlers){.internal-link target=_blank}를 생성하는 것 입니다.\n+\n+## `yield`와 `except`를 사용하는 의존성\n+\n+`yield`를 사용하는 의존성에서 `except`를 사용하여 예외를 포착하고 예외를 다시 발생시키지 않거나 (또는 새 예외를 발생시키지 않으면), FastAPI는 해당 예외가 발생했는지 알 수 없습니다. 이는 일반적인 Python 방식과 동일합니다:\n+\n+{* ../../docs_src/dependencies/tutorial008c_an_py39.py hl[15:16] *}\n+\n+이 경우, `HTTPException`이나 유사한 예외를 발생시키지 않기 때문에 클라이언트는 HTTP 500 [NAME_REDACTED] 응답을 보게 되지만, 서버는 어떤 오류가 발생했는지에 대한 **로그**나 다른 표시를 전혀 가지지 않게 됩니다. 😱\n+\n+### `yield`와 `except`를 사용하는 의존성에서 항상 `raise` 하기\n+\n+`yield`가 있는 의존성에서 예외를 잡았을 때는 `HTTPException`이나 유사한 예외를 새로 발생시키지 않는 한, 반드시 원래의 예외를 다시 발생시켜야 합니다.\n+\n+`raise`를 사용하여 동일한 예외를 다시 발생시킬 수 있습니다:\n+\n+{* ../../docs_src/dependencies/tutorial008d_an_py39.py hl[17] *}\n+\n+이제 클라이언트는 동일한 *HTTP 500 [NAME_REDACTED]* 오류 응답을 받게 되지만, 서버 로그에는 사용자 정의 예외인 `InternalError\"가 기록됩니다. 😎\n+\n+## `yield`를 사용하는 의존성의 실행 순서\n+\n+실행 순서는 아래 다이어그램과 거의 비슷합니다. 시간은 위에서 아래로 흐릅니다. 그리고 각 열은 상호 작용하거나 코드를 실행하는 부분 중 하나입니다.\n+\n+```mermaid\n+sequenceDiagram\n+\n+participant client as Client\n+participant handler as Exception handler\n+participant dep as Dep with yield\n+participant operation as Path Operation\n+participant tasks as Background tasks\n+\n+ Note over client,operation: Can raise exceptions, including HTTPException\n+ client ->> dep: Start request\n+ Note over dep: Run code up to yield\n+ opt raise Exception\n+ dep -->> handler: [NAME_REDACTED]\n+ handler -->> client: HTTP error response\n+ end\n+ dep ->> operation: Run dependency, e.g. DB session\n+ opt raise\n+ operation -->> dep: [NAME_REDACTED] (e.g. HTTPException)\n+ opt handle\n+ dep -->> dep: Can catch exception, raise a new HTTPException, raise other exception\n+ end\n+ handler -->> client: HTTP error response\n+ end\n+\n+ operation ->> client: Return response to client\n+ Note over client,operation: Response is already sent, can't change it anymore\n+ opt Tasks\n+ operation -->> tasks: Send background tasks\n+ end\n+ opt Raise other exception\n+ tasks -->> tasks: Handle exceptions in the background task code\n+ end\n+```\n+\n+/// info | 정보\n+\n+클라이언트에 **하나의 응답** 만 전송됩니다. 이는 오류 응답 중 하나일 수도 있고,*경로 작업*에서 생성된 응답일 수도 있습니다.\n+\n+이러한 응답 중 하나가 전송된 후에는 다른 응답을 보낼 수 없습니다.\n+\n+///\n+\n+/// tip | 팁\n+\n+이 다이어그램은 `HTTPException`을 보여주지만, `yield`를 사용하는 의존성에서 처리한 예외나 [사용자 정의 예외처리기](../handling-errors.md#install-custom-exception-handlers){.internal-link target=_blank}.를 사용하여 처리한 다른 예외도 발생시킬 수 있습니다.\n+\n+어떤 예외가 발생하든, `HTTPException`을 포함하여 yield를 사용하는 의존성으로 전달됩니다. 대부분의 경우 예외를 다시 발생시키거나 새로운 예외를 발생시켜야 합니다.\n+\n+///\n+\n+## `yield`, `HTTPException`, `except` 및 백그라운드 작업을 사용하는 의존성\n+\n+/// warning | 경고\n+\n+이러한 기술적 세부 사항은 대부분 필요하지 않으므로 이 섹션을 건너뛰고 아래에서 계속 진행해도 됩니다.\n+\n+이러한 세부 정보는 주로 FastAPI 0.106.0 이전 버전에서 `yield`가 있는 의존성의 리소스를 백그라운드 작업에서 사용했던 경우메 유용합니다.\n+\n+///\n+\n+### `yield`와 `except`를 사용하는 의존성, 기술 세부사항\n+\n+FastAPI 0.110.0 이전에는 `yield`가 포함된 의존성을 사용한 후 해당 의존성에서 `except`가 포함된 예외를 캡처하고 다시 예외를 발생시키지 않으면 예외가 자동으로 예외 핸들러 또는 내부 서버 오류 핸들러로 발생/전달되었습니다.\n+\n+이는 처리기 없이 전달된 예외(내부 서버 오류)에서 처리되지 않은 메모리 소비를 수정하고 일반 파이썬 코드의 동작과 일치하도록 하기 위해 0.110.0 버전에서 변경되었습니다.\n+\n+### 백그라운드 작업과 `yield`를 사용하는 의존성, 기술 세부사항\n+\n+FastAPI 0.106.0 이전에는 `yield` 이후에 예외를 발생시키는 것이 불가능했습니다. `yield`가 있는 의존성 종료 코드는 응답이 전송된 이후에 실행되었기 때문에, [예외 처리기](../handling-errors.md#install-custom-exception-handlers){.internal-link target=_blank}가 이미 실행된 상태였습니다.\n+\n+이는 주로 백그라운드 작업 내에서 의존성에서 \"yield된\" 동일한 객체를 사용할 수 있도록 하기 위해 이런 방식으로 설계되었습니다. 종료 코드는 백그라운드 작업이 완료된 후에 실행되었기 때문입니다\n+\n+하지만 이렇게 하면 리소스를 불필요하게 양보한 의존성(예: 데이터베이스 연결)에서 보유하면서 응답이 네트워크를 통해 이동할 때까지 기다리는 것을 의미하기 때문에 FastAPI 0.106.0에서 변경되었습니다.\n+\n+/// tip | 팁\n+\n+또한 백그라운드 작업은 일반적으로 자체 리소스(예: 자체 데이터베이스 연결)를 사용하여 별도로 처리해야 하는 독립적인 로직 집합입니다.\n+\n+따라서 이렇게 하면 코드가 더 깔끔해집니다.\n+\n+///\n+\n+만약 이전에 이러한 동작에 의존했다면, 이제는 백그라운드 작업 내부에서 백그라운드 작업을 위한 리소스를 생성하고, `yield`가 있는 의존성의 리소스에 의존하지 않는 데이터만 내부적으로 사용해야합니다.\n+\n+예를 들어, 동일한 데이터베이스 세션을 사용하는 대신, 백그라운드 작업 내부에서 새로운 데이터베이스 세션을 생성하고 이 새로운 세션을 사용하여 데이터베이스에서 객체를 가져와야 합니다. 그리고 데이터베이스 객체를 백그라운드 작업 함수의 매개변수로 직접 전달하는 대신, 해당 객체의 ID를 전달한 다음 백그라운드 작업 함수 내부에서 객체를 다시 가져와야 합니다\n+\n+## 컨텍스트 관리자\n+\n+### \"컨텍스트 관리자\"란?\n+\n+\"컨텍스트 관리자\"는 Python에서 `with` 문에서 사용할 수 있는 모든 객체를 의미합니다.\n+\n+예를 들어, `with`를 사용하여 파일을 읽을 수 있습니다:\n+\n+```Python\n+with open(\"./somefile.txt\") as f:\n+ contents = f.read()\n+ print(contents)\n+```\n+\n+내부적으로 `open(\"./somefile.txt\")` 는 \"컨텍스트 관리자([NAME_REDACTED])\"라고 불리는 객체를 생성합니다.\n+\n+`with` 블록이 끝나면, 예외가 발생했더라도 파일을 닫도록 보장합니다.\n+\n+`yield`가 있는 의존성을 생성하면 **FastAPI**는 내부적으로 이를 위한 컨텍스트 매니저를 생성하고 다른 관련 도구들과 결합합니다.\n+\n+### `yield`를 사용하는 의존성에서 컨텍스트 관리자 사용하기\n+\n+/// warning | 경고\n+\n+이것은 어느 정도 \"고급\" 개념입니다.\n+\n+**FastAPI**를 처음 시작하는 경우 지금은 이 부분을 건너뛰어도 좋습니다.\n+\n+///\n+\n+Python에서는 다음을 통해 컨텍스트 관리자를 생성할 수 있습니다. 두 가지 메서드가 있는 클래스를 생성합니다: `__enter__()` and `__exit__()`.\n+\n+**FastAPI**의 `yield`가 있는 의존성 내에서\n+`with` 또는 `async with`문을 사용하여 이들을 활용할 수 있습니다:\n+\n+{* ../../docs_src/dependencies/tutorial010.py hl[1:9,13] *}\n+\n+/// tip | 팁\n+\n+컨텍스트 관리자를 생성하는 또 다른 방법은 다음과 같습니다:\n+\n+* `[USER_REDACTED].contextmanager` 또는\n+* `[USER_REDACTED].asynccontextmanager`\n+\n+이들은 단일 `yield`가 있는 함수를 꾸미는 데 사용합니다.\n+\n+이것이 **FastAPI**가 `yield`가 있는 의존성을 위해 내부적으로 사용하는 방식입니다.\n+\n+하지만 FastAPI 의존성에는 이러한 데코레이터를 사용할 필요가 없습니다(그리고 사용해서도 안됩니다).\n+\n+FastAPI가 내부적으로 이를 처리해 줄 것입니다.\n+\n+///" } ], "reviews": [ { "id": 2588303127, "user": "user_caad3e3c1c43", "state": "CHANGES_REQUESTED", "body": null, "submitted_at": "2025-02-01T09:51:29+00:00" }, { "id": 2588356027, "user": "user_caad3e3c1c43", "state": "APPROVED", "body": null, "submitted_at": "2025-02-01T15:42:10+00:00" }, { "id": 2601866642, "user": "user_a1942c3a9ec0", "state": "CHANGES_REQUESTED", "body": null, "submitted_at": "2025-02-07T14:22:12+00:00" }, { "id": 2601905209, "user": "user_a1942c3a9ec0", "state": "COMMENTED", "body": null, "submitted_at": "2025-02-07T14:35:44+00:00" }, { "id": 2603862110, "user": "user_2cb152fbdf94", "state": "COMMENTED", "body": "I have addressed all the requested changes. Thanks for the review! 🚀", "submitted_at": "2025-02-08T14:49:01+00:00" }, { "id": 2603862848, "user": "user_2cb152fbdf94", "state": "COMMENTED", "body": null, "submitted_at": "2025-02-08T14:54:14+00:00" }, { "id": 2603862949, "user": "user_2cb152fbdf94", "state": "COMMENTED", "body": null, "submitted_at": "2025-02-08T14:54:50+00:00" }, { "id": 2603875715, "user": "user_caad3e3c1c43", "state": "APPROVED", "body": null, "submitted_at": "2025-02-08T15:31:21+00:00" }, { "id": 2603895846, "user": "user_a1942c3a9ec0", "state": "APPROVED", "body": "[NAME_REDACTED]!", "submitted_at": "2025-02-08T16:04:20+00:00" } ], "review_comments": [ { "id": 1938238366, "user": "user_caad3e3c1c43", "body": "```suggestion\nFastAPI는 작업 완료 후 추가 단계를 수행하는 의존성을 지원합니다.\n```", "path": "docs/ko/docs/tutorial/dependencies/dependencies-with-yield.md", "line": null, "side": "RIGHT", "created_at": "2025-02-01T09:25:52+00:00" }, { "id": 1938238517, "user": "user_caad3e3c1c43", "body": "```suggestion\n이를 구현하려면 `return` 대신 `yield`를 사용하고, 추가로 실행할 단계 (코드)를 그 뒤에 작성하세요.\n```", "path": "docs/ko/docs/tutorial/dependencies/dependencies-with-yield.md", "line": null, "side": "RIGHT", "created_at": "2025-02-01T09:26:33+00:00" }, { "id": 1938239061, "user": "user_caad3e3c1c43", "body": "```suggestion\n어떤 크기와 형태의 하위 의존성과 하위 의존성의 \"트리\"도 가질 수 있으며, 이들 모두가 `yield`를 사용할 수 있습니다.\n```\n\n영어 원문에선 `\"trees\" of sub-dependencies`라고 표현하고 있어 변경을 추천드립니다.", "path": "docs/ko/docs/tutorial/dependencies/dependencies-with-yield.md", "line": null, "side": "RIGHT", "created_at": "2025-02-01T09:31:14+00:00" }, { "id": 1938239859, "user": "user_caad3e3c1c43", "body": "`` 링크가 원문과 동일한데 아래와 같이 링크가 깨지는군요\nGitHub Actions에서 설정 문제가 있나보네요\n\n\"Screenshot", "path": "docs/ko/docs/tutorial/dependencies/dependencies-with-yield.md", "line": 90, "side": "RIGHT", "created_at": "2025-02-01T09:37:45+00:00" }, { "id": 1938240216, "user": "user_caad3e3c1c43", "body": "```suggestion\n이는 다소 고급 기술이며, 대부분의 경우 경로 연산 함수 등 나머지 애플리케이션 코드 내부에서 예외 (`HTTPException` 포함)를 발생시킬 수 있으므로 실제로는 필요하지 않을 것입니다.\n```", "path": "docs/ko/docs/tutorial/dependencies/dependencies-with-yield.md", "line": null, "side": "RIGHT", "created_at": "2025-02-01T09:40:21+00:00" }, { "id": 1938240448, "user": "user_caad3e3c1c43", "body": "```suggestion\n이 경우, `HTTPException`이나 유사한 예외를 발생시키지 않기 때문에 클라이언트는 HTTP 500 [NAME_REDACTED] 응답을 보게 되지만, 서버는 어떤 오류가 발생했는지에 대한 **로그**나 다른 표시를 전혀 가지지 않게 됩니다. 😱\n```", "path": "docs/ko/docs/tutorial/dependencies/dependencies-with-yield.md", "line": null, "side": "RIGHT", "created_at": "2025-02-01T09:41:21+00:00" }, { "id": 1938240646, "user": "user_caad3e3c1c43", "body": "```suggestion\n실행 순서는 아래 다이어그램과 거의 비슷합니다. 시간은 위에서 아래로 흐릅니다. 그리고 각 열은 상호 작용하거나 코드를 실행하는 부분 중 하나입니다.\n```", "path": "docs/ko/docs/tutorial/dependencies/dependencies-with-yield.md", "line": null, "side": "RIGHT", "created_at": "2025-02-01T09:42:48+00:00" }, { "id": 1938240714, "user": "user_caad3e3c1c43", "body": "```suggestion\n이러한 세부 정보는 주로 FastAPI 0.106.0 이전 버전에서 `yield`가 있는 의존성의 리소스를 백그라운드 작업에서 사용했던 경우메 유용합니다.\n```", "path": "docs/ko/docs/tutorial/dependencies/dependencies-with-yield.md", "line": null, "side": "RIGHT", "created_at": "2025-02-01T09:43:54+00:00" }, { "id": 1938240743, "user": "user_caad3e3c1c43", "body": "```suggestion\n### `yield`와 `except`를 사용하는 의존성, 기술 세부사항\n```", "path": "docs/ko/docs/tutorial/dependencies/dependencies-with-yield.md", "line": null, "side": "RIGHT", "created_at": "2025-02-01T09:44:17+00:00" }, { "id": 1938240867, "user": "user_caad3e3c1c43", "body": "```suggestion\n### 백그라운드 작업과 `yield`를 사용하는 의존성, 기술 세부사항\n```", "path": "docs/ko/docs/tutorial/dependencies/dependencies-with-yield.md", "line": null, "side": "RIGHT", "created_at": "2025-02-01T09:45:42+00:00" }, { "id": 1938241064, "user": "user_caad3e3c1c43", "body": "```suggestion\nFastAPI 0.106.0 이전에는 `yield` 이후에 예외를 발생시키는 것이 불가능했습니다. `yield`가 있는 의존성 종료 코드는 응답이 전송된 이후에 실행되었기 때문에, [예외 처리기](../handling-errors.md#install-custom-exception-handlers){.internal-link target=_blank}가 이미 실행된 상태였습니다.\n```", "path": "docs/ko/docs/tutorial/dependencies/dependencies-with-yield.md", "line": null, "side": "RIGHT", "created_at": "2025-02-01T09:46:23+00:00" }, { "id": 1938241732, "user": "user_caad3e3c1c43", "body": "```suggestion\nPython에서는 다음을 통해 컨텍스트 관리자를 생성할 수 있습니다. 두 가지 메서드가 있는 클래스를 생성합니다: `__enter__()` and `__exit__()`.\n```", "path": "docs/ko/docs/tutorial/dependencies/dependencies-with-yield.md", "line": null, "side": "RIGHT", "created_at": "2025-02-01T09:49:31+00:00" }, { "id": 1946604260, "user": "user_a1942c3a9ec0", "body": "At line 38, \"yield statement\" is translated as \"yield 문\", but at line 30, it is translated simply as \"yield\". It would be more appropriate to consistently use \"yield 문\" in both cases.", "path": "docs/ko/docs/tutorial/dependencies/dependencies-with-yield.md", "line": null, "side": "RIGHT", "created_at": "2025-02-07T14:22:07+00:00" }, { "id": 1946628025, "user": "user_a1942c3a9ec0", "body": "n the sentence \"You can have sub-dependencies and 'trees' of sub-dependencies of any size and shape, and any or all of them can use yield,\" rather than explicitly translating \"any\" as \"어떤,\" it would be more natural to translate it as \"모든\" (all).", "path": "docs/ko/docs/tutorial/dependencies/dependencies-with-yield.md", "line": null, "side": "RIGHT", "created_at": "2025-02-07T14:35:30+00:00" }, { "id": 1947839099, "user": "user_2cb152fbdf94", "body": "[USER_REDACTED] Thanks for the feedback! I have applied the suggested changes. 🚀", "path": "docs/ko/docs/tutorial/dependencies/dependencies-with-yield.md", "line": null, "side": "RIGHT", "created_at": "2025-02-08T14:54:14+00:00" }, { "id": 1947839211, "user": "user_2cb152fbdf94", "body": "[USER_REDACTED] Thanks for the feedback! I have applied the suggested changes. 🚀", "path": "docs/ko/docs/tutorial/dependencies/dependencies-with-yield.md", "line": null, "side": "RIGHT", "created_at": "2025-02-08T14:54:50+00:00" } ], "meta": { "languages": [ "md" ], "touches_tests": false, "review_state_summary": { "CHANGES_REQUESTED": 2, "APPROVED": 3, "COMMENTED": 4 }, "meaningful_comment_count": 16, "has_approval": true, "has_changes_requested": true, "total_review_comments": 16 } } { "_id": "a0eaa2a2889e480e", "_schema_version": "1.0", "_cleaned_at": "2026-02-12T07:46:52.195116+00:00", "repo": "tiangolo/fastapi", "repo_url": "https://github.com/fastapi/fastapi", "license_name": "MIT License", "license_spdx": "MIT", "pr_number": 13227, "title": "🌐 Add Russian translation for `docs/ru/docs/advanced/async-tests.md`", "body": null, "author": "user_9e49ba0b4492", "created_at": "2025-01-18T11:48:37+00:00", "merged_at": "2025-01-27T15:36:13+00:00", "base_branch": "master", "head_branch": "translate-lang-ru-async-tests", "additions": 99, "deletions": 0, "changed_files": 1, "files": [ { "filename": "docs/ru/docs/advanced/async-tests.md", "status": "added", "additions": 99, "deletions": 0, "changes": 99, "patch": "@@ -0,0 +1,99 @@\n+# Асинхронное тестирование\n+\n+Вы уже видели как тестировать **FastAPI** приложение, используя имеющийся класс `TestClient`. К этому моменту вы видели только как писать тесты в синхронном стиле без использования `async` функций.\n+\n+Возможность использования асинхронных функций в ваших тестах может быть полезнa, когда, например, вы асинхронно обращаетесь к вашей базе данных. Представьте, что вы хотите отправить запросы в ваше FastAPI приложение, а затем при помощи асинхронной библиотеки для работы с базой данных удостовериться, что ваш бекэнд корректно записал данные в базу данных.\n+\n+Давайте рассмотрим, как мы можем это реализовать.\n+\n+## pytest.mark.anyio\n+\n+Если мы хотим вызывать асинхронные функции в наших тестах, то наши тестовые функции должны быть асинхронными. AnyIO предоставляет для этого отличный плагин, который позволяет нам указывать, какие тестовые функции должны вызываться асинхронно.\n+\n+## HTTPX\n+\n+Даже если **FastAPI** приложение использует обычные функции `def` вместо `async def`, это все равно `async` приложение 'под капотом'.\n+\n+Чтобы работать с асинхронным FastAPI приложением в ваших обычных тестовых функциях `def`, используя стандартный pytest, `TestClient` внутри себя делает некоторую магию. Но эта магия перестает работать, когда мы используем его внутри асинхронных функций. Запуская наши тесты асинхронно, мы больше не можем использовать `TestClient` внутри наших тестовых функций.\n+\n+`TestClient` основан на HTTPX, и, к счастью, мы можем использовать его (`HTTPX`) напрямую для тестирования API.\n+\n+## Пример\n+\n+В качестве простого примера, давайте рассмотрим файловую структуру, схожую с описанной в [Большие приложения](../tutorial/bigger-applications.md){.internal-link target=_blank} и [Тестирование](../tutorial/testing.md){.internal-link target=_blank}:\n+\n+```\n+.\n+├── app\n+│   ├── __init__.py\n+│   ├── main.py\n+│   └── test_main.py\n+```\n+\n+Файл `main.py`:\n+\n+{* ../../docs_src/async_tests/main.py *}\n+\n+Файл `test_main.py` содержит тесты для `main.py`, теперь он может выглядеть так:\n+\n+{* ../../docs_src/async_tests/test_main.py *}\n+\n+## Запуск тестов\n+\n+Вы можете запустить свои тесты как обычно:\n+\n+
      \n+\n+```console\n+$ pytest\n+\n+---> 100%\n+```\n+\n+
      \n+\n+## Подробнее\n+\n+Маркер `[USER_REDACTED].mark.anyio` говорит pytest, что тестовая функция должна быть вызвана асинхронно:\n+\n+{* ../../docs_src/async_tests/test_main.py hl[7] *}\n+\n+/// tip | Подсказка\n+\n+Обратите внимание, что тестовая функция теперь `async def` вместо простого `def`, как это было при использовании `TestClient`.\n+\n+///\n+\n+Затем мы можем создать `AsyncClient` со ссылкой на приложение и посылать асинхронные запросы, используя `await`.\n+\n+{* ../../docs_src/async_tests/test_main.py hl[9:12] *}\n+\n+Это эквивалентно следующему:\n+\n+```Python\n+response = client.get('/')\n+```\n+\n+...которое мы использовали для отправки наших запросов с `TestClient`.\n+\n+/// tip | Подсказка\n+\n+Обратите внимание, что мы используем async/await с `AsyncClient` - запрос асинхронный.\n+\n+///\n+\n+/// warning | Внимание\n+\n+Если ваше приложение полагается на lifespan события, то `AsyncClient` не запустит эти события. Чтобы обеспечить их срабатывание используйте `LifespanManager` из florimondmanca/asgi-lifespan.\n+\n+///\n+\n+## Вызов других асинхронных функций\n+\n+Теперь тестовая функция стала асинхронной, поэтому внутри нее вы можете вызывать также и другие `async` функции, не связанные с отправлением запросов в ваше FastAPI приложение. Как если бы вы вызывали их в любом другом месте вашего кода.\n+\n+/// tip | Подсказка\n+\n+Если вы столкнулись с `RuntimeError: Task attached to a different loop` при вызове асинхронных функций в ваших тестах (например, при использовании [NAME_REDACTED]), то не забывайте инициализировать объекты, которым нужен цикл событий (event loop), только внутри асинхронных функций, например, в `'[USER_REDACTED].on_event(\"startup\")` callback.\n+\n+///" } ], "reviews": [ { "id": 2560412125, "user": "user_6d7d83efab20", "state": "CHANGES_REQUESTED", "body": null, "submitted_at": "2025-01-18T12:31:07+00:00" }, { "id": 2560422760, "user": "user_9e49ba0b4492", "state": "COMMENTED", "body": null, "submitted_at": "2025-01-18T13:23:58+00:00" }, { "id": 2560423068, "user": "user_9e49ba0b4492", "state": "COMMENTED", "body": null, "submitted_at": "2025-01-18T13:26:21+00:00" }, { "id": 2560425117, "user": "user_9e49ba0b4492", "state": "COMMENTED", "body": null, "submitted_at": "2025-01-18T13:34:51+00:00" }, { "id": 2560427950, "user": "user_6d7d83efab20", "state": "COMMENTED", "body": null, "submitted_at": "2025-01-18T13:51:04+00:00" }, { "id": 2560428728, "user": "user_6d7d83efab20", "state": "APPROVED", "body": null, "submitted_at": "2025-01-18T13:53:59+00:00" }, { "id": 2560429543, "user": "user_9e49ba0b4492", "state": "COMMENTED", "body": null, "submitted_at": "2025-01-18T13:58:29+00:00" }, { "id": 2570653371, "user": "user_df3ddbc43209", "state": "COMMENTED", "body": null, "submitted_at": "2025-01-23T18:12:53+00:00" }, { "id": 2570670897, "user": "user_9e49ba0b4492", "state": "COMMENTED", "body": null, "submitted_at": "2025-01-23T18:21:02+00:00" }, { "id": 2570795656, "user": "user_3cf7e8d7d8b1", "state": "APPROVED", "body": "Спасибо :3", "submitted_at": "2025-01-23T19:07:58+00:00" }, { "id": 2570821173, "user": "user_df3ddbc43209", "state": "APPROVED", "body": null, "submitted_at": "2025-01-23T19:21:10+00:00" }, { "id": 2574156299, "user": "user_de3bba089aca", "state": "APPROVED", "body": null, "submitted_at": "2025-01-26T07:13:47+00:00" }, { "id": 2574274933, "user": "user_6d7d83efab20", "state": "COMMENTED", "body": null, "submitted_at": "2025-01-26T13:08:36+00:00" } ], "review_comments": [ { "id": 1921052593, "user": "user_6d7d83efab20", "body": "```suggestion\nВозможность использования асинхронных функций в ваших тестах может быть полезнa, когда, например, вы асинхронно обращаетесь к вашей базе данных. Представьте, что вы хотите отправить запросы в ваше FastAPI приложение, а затем при помощи асинхронной библиотеки для работы с базой данных удостовериться, что ваш бекэнд корректно записал данные в базу данных.\n```", "path": "docs/ru/docs/advanced/async-tests.md", "line": null, "side": "RIGHT", "created_at": "2025-01-18T12:03:13+00:00" }, { "id": 1921053069, "user": "user_6d7d83efab20", "body": "```suggestion\nДаже если **FastAPI** приложение использует обычные функции `def` вместо `async def`, 'под капотом' это все равно `асинхронное` приложение .\n```", "path": "docs/ru/docs/advanced/async-tests.md", "line": 15, "side": "RIGHT", "created_at": "2025-01-18T12:06:46+00:00" }, { "id": 1921053898, "user": "user_6d7d83efab20", "body": "```suggestion\n`TestClient` основан на HTTPX, и, к счастью, мы можем использовать его (`HTTPX`) напрямую для тестирования API.\n```", "path": "docs/ru/docs/advanced/async-tests.md", "line": null, "side": "RIGHT", "created_at": "2025-01-18T12:11:25+00:00" }, { "id": 1921054055, "user": "user_6d7d83efab20", "body": "имеет смысл пояснить, что мы имеем в виду именно `HTTPX`", "path": "docs/ru/docs/advanced/async-tests.md", "line": null, "side": "RIGHT", "created_at": "2025-01-18T12:12:24+00:00" }, { "id": 1921054527, "user": "user_6d7d83efab20", "body": "```suggestion\nЗатем мы можем создать `AsyncClient` со ссылкой на приложение и посылать асинхронные запросы, используя `await`.\n```", "path": "docs/ru/docs/advanced/async-tests.md", "line": null, "side": "RIGHT", "created_at": "2025-01-18T12:16:29+00:00" }, { "id": 1921055141, "user": "user_6d7d83efab20", "body": "```suggestion\nЕсли вы столкнулись с `RuntimeError: Task attached to a different loop` при вызове асинхронных функций в ваших тестах (например, при использовании [NAME_REDACTED]), то не забывайте инициализировать объекты, которым нужен цикл событий (event loop), только внутри асинхронных функций, например, в `'[USER_REDACTED].on_event(\"startup\")` callback.\n```", "path": "docs/ru/docs/advanced/async-tests.md", "line": null, "side": "RIGHT", "created_at": "2025-01-18T12:19:52+00:00" }, { "id": 1921055248, "user": "user_6d7d83efab20", "body": "здесь имеет смысл указать оригинальный английский термин", "path": "docs/ru/docs/advanced/async-tests.md", "line": null, "side": "RIGHT", "created_at": "2025-01-18T12:20:35+00:00" }, { "id": 1921056028, "user": "user_6d7d83efab20", "body": "это предложение получилось слишком запутанным, было бы хорошо его как-то перефразировать.", "path": "docs/ru/docs/advanced/async-tests.md", "line": null, "side": "RIGHT", "created_at": "2025-01-18T12:25:46+00:00" }, { "id": 1921063802, "user": "user_9e49ba0b4492", "body": "В [Contributing](https://fastapi.tiangolo.com/contributing/#translation-specific-tips-and-guidelines) один из пунктов гласит:\n\n> Do not change anything enclosed in \"``\" (inline code).\n\nПоэтому, наверное, не стоит переводить `async`.", "path": "docs/ru/docs/advanced/async-tests.md", "line": 15, "side": "RIGHT", "created_at": "2025-01-18T13:23:58+00:00" }, { "id": 1921064262, "user": "user_9e49ba0b4492", "body": "Абсолютно согласен!", "path": "docs/ru/docs/advanced/async-tests.md", "line": null, "side": "RIGHT", "created_at": "2025-01-18T13:26:21+00:00" }, { "id": 1921065659, "user": "user_9e49ba0b4492", "body": "Теперь тестовая функция стала асинхронной, поэтому внутри нее вы можете вызывать также и другие `async` функции, не связанные с отправлением запросов в ваше FastAPI приложение. Как если бы вы вызывали их в любом другом месте вашего кода.\n\nТак лучше?", "path": "docs/ru/docs/advanced/async-tests.md", "line": null, "side": "RIGHT", "created_at": "2025-01-18T13:34:51+00:00" }, { "id": 1921068292, "user": "user_6d7d83efab20", "body": "да, так лучше :+1:", "path": "docs/ru/docs/advanced/async-tests.md", "line": null, "side": "RIGHT", "created_at": "2025-01-18T13:51:04+00:00" }, { "id": 1921069439, "user": "user_9e49ba0b4492", "body": "Поправил", "path": "docs/ru/docs/advanced/async-tests.md", "line": null, "side": "RIGHT", "created_at": "2025-01-18T13:58:29+00:00" }, { "id": 1927448983, "user": "user_df3ddbc43209", "body": "```suggestion\nДавайте рассмотрим, как мы можем это реализовать.\n```", "path": "docs/ru/docs/advanced/async-tests.md", "line": null, "side": "RIGHT", "created_at": "2025-01-23T18:12:52+00:00" }, { "id": 1927461409, "user": "user_9e49ba0b4492", "body": "Две головы хорошо, а три лучше! Спасибо!", "path": "docs/ru/docs/advanced/async-tests.md", "line": null, "side": "RIGHT", "created_at": "2025-01-23T18:21:02+00:00" }, { "id": 1929679235, "user": "user_de3bba089aca", "body": "Какая-то устаревшая информация. Не нужно как-то специально помечать асинхронные тесты...", "path": "docs/ru/docs/advanced/async-tests.md", "line": 9, "side": "RIGHT", "created_at": "2025-01-26T07:13:40+00:00" }, { "id": 1929769035, "user": "user_6d7d83efab20", "body": "Если асинхронные тесты не помечать, то они будут пропускаться:\n\n```\nPytestUnhandledCoroutineWarning: async def functions are not natively supported and have been skipped.\n You need to install a suitable plugin for your async framework, for example:\n - anyio\n - pytest-asyncio\n - pytest-tornasync\n - pytest-trio\n - pytest-twisted\n warnings.warn(PytestUnhandledCoroutineWarning(msg.format(nodeid)))\n\n-- Docs: https://docs.pytest.org/en/stable/how-to/capture-warnings.html\n\n```\n\nPytest не поддерживает выполнение асинхронных тестов. Для поддержки асинхронных тестов нужно устанавливать доп. плагины (см. выше), под каждый плагин нужны свои настройки. Для `anyio` это одна из опций.", "path": "docs/ru/docs/advanced/async-tests.md", "line": 9, "side": "RIGHT", "created_at": "2025-01-26T13:08:36+00:00" } ], "meta": { "languages": [ "md" ], "touches_tests": false, "review_state_summary": { "CHANGES_REQUESTED": 1, "COMMENTED": 8, "APPROVED": 4 }, "meaningful_comment_count": 16, "has_approval": true, "has_changes_requested": true, "total_review_comments": 17 } } { "_id": "97ed6766249d4bad", "_schema_version": "1.0", "_cleaned_at": "2026-02-12T07:46:52.211178+00:00", "repo": "tiangolo/fastapi", "repo_url": "https://github.com/fastapi/fastapi", "license_name": "MIT License", "license_spdx": "MIT", "pr_number": 13226, "title": "🌐 Add Japanese translation for `docs/ja/docs/environment-variables.md`", "body": "This PR is a translation of docs/ja/docs/environment-variables.md. I'm Japanese.\n\nIn the original text of this page, parts that seemed more suitable as \"info\" were labeled as \"tip.\"\nFor now, I have left them as \"tip\". (not translate into \"豆知識\")", "author": "user_e2ddc2fa3a94", "created_at": "2025-01-18T08:52:25+00:00", "merged_at": "2025-01-27T15:39:04+00:00", "base_branch": "master", "head_branch": "ja-environment-variables.md", "additions": 301, "deletions": 0, "changed_files": 1, "files": [ { "filename": "docs/ja/docs/environment-variables.md", "status": "added", "additions": 301, "deletions": 0, "changes": 301, "patch": "@@ -0,0 +1,301 @@\n+# 環境変数\n+\n+/// tip\n+\n+もし、「環境変数」とは何か、それをどう使うかを既に知っている場合は、このセクションをスキップして構いません。\n+\n+///\n+\n+環境変数(**env var**とも呼ばれる)はPythonコードの**外側**、つまり**OS**に存在する変数で、Pythonから読み取ることができます。(他のプログラムでも同様に読み取れます。)\n+\n+環境変数は、アプリケーションの**設定**の管理や、Pythonの**インストール**などに役立ちます。\n+\n+## 環境変数の作成と使用\n+\n+環境変数は**シェル(ターミナル)**内で**作成**して使用でき、それらにPythonは不要です。\n+\n+//// tab | Linux, macOS, [NAME_REDACTED]\n+\n+
      \n+\n+```console\n+// You could create an env var MY_NAME with\n+$ export MY_NAME=\"[NAME_REDACTED]\"\n+\n+// Then you could use it with other programs, like\n+$ echo \"Hello $MY_NAME\"\n+\n+[NAME_REDACTED]\n+```\n+\n+
      \n+\n+////\n+\n+//// tab | [NAME_REDACTED]\n+\n+
      \n+\n+\n+```console\n+// Create an env var MY_NAME\n+$ $Env:MY_NAME = \"[NAME_REDACTED]\"\n+\n+// Use it with other programs, like\n+$ echo \"Hello $Env:MY_NAME\"\n+\n+[NAME_REDACTED]\n+```\n+\n+
      \n+\n+////\n+\n+## Pythonで環境変数を読み取る\n+\n+環境変数をPythonの**外側**、ターミナル(や他の方法)で作成し、**Python内で読み取る**こともできます。\n+\n+例えば、以下のような`main.py`ファイルを用意します:\n+\n+```Python hl_lines=\"3\"\n+import os\n+\n+name = os.getenv(\"MY_NAME\", \"World\")\n+print(f\"Hello {name} from Python\")\n+```\n+\n+/// tip\n+\n+`os.getenv()` の第2引数は、デフォルトで返される値を指定します。\n+\n+この引数を省略するとデフォルト値として`None`が返されますが、ここではデフォルト値として`\"World\"`を指定しています。\n+\n+///\n+\n+次に、このPythonプログラムを呼び出します。\n+\n+//// tab | Linux, macOS, [NAME_REDACTED]\n+\n+
      \n+\n+```console\n+// Here we don't set the env var yet\n+$ python main.py\n+\n+// As we didn't set the env var, we get the default value\n+\n+[NAME_REDACTED] from Python\n+\n+// But if we create an environment variable first\n+$ export MY_NAME=\"[NAME_REDACTED]\"\n+\n+// And then call the program again\n+$ python main.py\n+\n+// Now it can read the environment variable\n+\n+[NAME_REDACTED] from Python\n+```\n+\n+
      \n+\n+////\n+\n+//// tab | [NAME_REDACTED]\n+\n+
      \n+\n+```console\n+// Here we don't set the env var yet\n+$ python main.py\n+\n+// As we didn't set the env var, we get the default value\n+\n+[NAME_REDACTED] from Python\n+\n+// But if we create an environment variable first\n+$ $Env:MY_NAME = \"[NAME_REDACTED]\"\n+\n+// And then call the program again\n+$ python main.py\n+\n+// Now it can read the environment variable\n+\n+[NAME_REDACTED] from Python\n+```\n+\n+
      \n+\n+////\n+\n+環境変数はコードの外側で設定し、内側から読み取ることができるので、他のファイルと一緒に(`git`に)保存する必要がありません。そのため、環境変数をコンフィグレーションや**設定**に使用することが一般的です。\n+\n+また、**特定のプログラムの呼び出し**のための環境変数を、そのプログラムのみ、その実行中に限定して利用できるよう作成できます。\n+\n+そのためには、プログラム起動コマンドと同じコマンドライン上の、起動コマンド直前で環境変数を作成してください。\n+\n+
      \n+\n+```console\n+// Create an env var MY_NAME in line for this program call\n+$ MY_NAME=\"[NAME_REDACTED]\" python main.py\n+\n+// Now it can read the environment variable\n+\n+[NAME_REDACTED] from Python\n+\n+// The env var no longer exists afterwards\n+$ python main.py\n+\n+[NAME_REDACTED] from Python\n+```\n+\n+
      \n+\n+/// tip\n+\n+詳しくは The Twelve-Factor App: Config を参照してください。\n+\n+///\n+\n+## 型とバリデーション\n+\n+環境変数は**テキスト文字列**のみを扱うことができます。これは、環境変数がPython外部に存在し、他のプログラムやシステム全体(Linux、Windows、macOS間の互換性を含む)と連携する必要があるためです。\n+\n+つまり、Pythonが環境変数から読み取る**あらゆる値**は **`str`型となり**、他の型への変換やバリデーションはコード内で行う必要があります。\n+\n+環境変数を使用して**アプリケーション設定**を管理する方法については、[高度なユーザーガイド - Settings and [NAME_REDACTED]](./advanced/settings.md){.internal-link target=_blank}で詳しく学べます。\n+\n+## `PATH`環境変数\n+\n+**`PATH`**という**特別な**環境変数があります。この環境変数は、OS(Linux、macOS、Windows)が実行するプログラムを発見するために使用されます。\n+\n+`PATH`変数は、複数のディレクトリのパスから成る長い文字列です。このパスはLinuxやMacOSの場合は`:`で、Windowsの場合は`;`で区切られています。\n+\n+例えば、`PATH`環境変数は次のような文字列かもしれません:\n+\n+//// tab | Linux, macOS\n+\n+```plaintext\n+/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin\n+```\n+\n+これは、OSはプログラムを見つけるために以下のディレクトリを探す、ということを意味します:\n+\n+* `/usr/local/bin`\n+* `/usr/bin`\n+* `/bin`\n+* `/usr/sbin`\n+* `/sbin`\n+\n+////\n+\n+//// tab | Windows\n+\n+```plaintext\n+C:\\[NAME_REDACTED]\\Python312\\Scripts;C:\\[NAME_REDACTED]\\Python312;C:\\Windows\\System32\n+```\n+\n+これは、OSはプログラムを見つけるために以下のディレクトリを探す、ということを意味します:\n+\n+* `C:\\[NAME_REDACTED]\\Python312\\Scripts`\n+* `C:\\[NAME_REDACTED]\\Python312`\n+* `C:\\Windows\\System32`\n+\n+////\n+\n+ターミナル上で**コマンド**を入力すると、 OSはそのプログラムを見つけるために、`PATH`環境変数のリストに記載された**それぞれのディレクトリを探し**ます。\n+\n+例えば、ターミナル上で`python`を入力すると、OSは`python`によって呼ばれるプログラムを見つけるために、そのリストの**先頭のディレクトリ**を最初に探します。\n+\n+OSは、もしそのプログラムをそこで発見すれば**実行し**ますが、そうでなければリストの**他のディレクトリ**を探していきます。\n+\n+### PythonのインストールとPATH環境変数の更新\n+\n+Pythonのインストール時に`PATH`環境変数を更新したいか聞かれるかもしれません。\n+\n+/// tab | Linux, macOS\n+\n+Pythonをインストールして、そのプログラムが`/opt/custompython/bin`というディレクトリに配置されたとします。\n+\n+もし、`PATH`環境変数を更新するように答えると、`PATH`環境変数に`/opt/custompython/bin`が追加されます。\n+\n+`PATH`環境変数は以下のように更新されるでしょう:\n+\n+``` plaintext\n+/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin:/opt/custompython/bin\n+```\n+\n+このようにして、ターミナルで`python`と入力したときに、OSは`/opt/custompython/bin`(リストの末尾のディレクトリ)にあるPythonプログラムを見つけ、使用します。\n+\n+///\n+\n+/// tab | Windows\n+\n+Pythonをインストールして、そのプログラムが`C:\\opt\\custompython\\bin`というディレクトリに配置されたとします。\n+\n+もし、`PATH`環境変数を更新するように答えると、`PATH`環境変数に`C:\\opt\\custompython\\bin`が追加されます。\n+\n+`PATH`環境変数は以下のように更新されるでしょう:\n+\n+```plaintext\n+C:\\[NAME_REDACTED]\\Python312\\Scripts;C:\\[NAME_REDACTED]\\Python312;C:\\Windows\\System32;C:\\opt\\custompython\\bin\n+```\n+\n+このようにして、ターミナルで`python`と入力したときに、OSは`C:\\opt\\custompython\\bin\\python`(リストの末尾のディレクトリ)にあるPythonプログラムを見つけ、使用します。\n+\n+///\n+\n+つまり、ターミナルで以下のコマンドを入力すると:\n+\n+
      \n+\n+``` console\n+$ python\n+```\n+\n+
      \n+\n+/// tab | Linux, macOS\n+\n+OSは`/opt/custompython/bin`にある`python`プログラムを**見つけ**て実行します。\n+\n+これは、次のコマンドを入力した場合とほとんど同等です:\n+\n+
      \n+\n+```console\n+$ /opt/custompython/bin/python\n+```\n+\n+
      \n+\n+///\n+\n+/// tab | Windows\n+\n+OSは`C:\\opt\\custompython\\bin\\python`にある`python`プログラムを**見つけ**て実行します。\n+\n+これは、次のコマンドを入力した場合とほとんど同等です:\n+\n+
      \n+\n+```console\n+$ C:\\opt\\custompython\\bin\\python\n+```\n+\n+
      \n+\n+///\n+\n+この情報は、[[NAME_REDACTED]](virtual-environments.md) について学ぶ際にも役立ちます。\n+\n+## まとめ\n+\n+これで、**環境変数**とは何か、Pythonでどのように使用するかについて、基本的な理解が得られたはずです。\n+\n+環境変数についての詳細は、Wikipedia: [NAME_REDACTED] を参照してください。\n+\n+環境変数の用途や適用方法が最初は直感的ではないかもしれませんが、開発中のさまざまなシナリオで繰り返し登場します。そのため、基本を知っておくことが重要です。\n+\n+たとえば、この情報は次のセクションで扱う[[NAME_REDACTED]](virtual-environments.md)にも関連します。" } ], "reviews": [ { "id": 2574005342, "user": "user_9a4a033d7317", "state": "COMMENTED", "body": "[USER_REDACTED] \n翻訳ありがとうございます!\nいくつか気になったところについてコメントしておきました🙏", "submitted_at": "2025-01-25T12:57:49+00:00" }, { "id": 2574192067, "user": "user_9a4a033d7317", "state": "APPROVED", "body": "LGTM!", "submitted_at": "2025-01-26T10:12:52+00:00" } ], "review_comments": [ { "id": 1929535319, "user": "user_9a4a033d7317", "body": "目次構成は原文と揃うようにしておく方が良いかなと思います\n\n```suggestion\n\n### PythonのインストールとPATH環境変数の更新\n\n```\n\n\"スクリーンショット\n\n\"スクリーンショット", "path": "docs/ja/docs/environment-variables.md", "line": null, "side": "RIGHT", "created_at": "2025-01-25T12:34:29+00:00" }, { "id": 1929537054, "user": "user_9a4a033d7317", "body": "ここも原文にない見出しが足されることで目次構成が変わってしまうのが気になりました。\n\nここは、前にある「This way, when you type python in the terminal, ...」を受けての「So, if you type: (python)」で、両者似たようなことを言っているので、自分ならこんな感じにしそうです\n\n```suggestion\n\nつまり、ターミナルで以下のコマンドを入力すると:\n```", "path": "docs/ja/docs/environment-variables.md", "line": null, "side": "RIGHT", "created_at": "2025-01-25T12:45:48+00:00" }, { "id": 1929537575, "user": "user_9a4a033d7317", "body": "おそらくこうかなと思います\n```suggestion\nもし、`PATH`環境変数を更新するように答えると、`PATH`環境変数に`/opt/custompython/bin`が追加されます。\n```", "path": "docs/ja/docs/environment-variables.md", "line": null, "side": "RIGHT", "created_at": "2025-01-25T12:48:40+00:00" }, { "id": 1929537618, "user": "user_9a4a033d7317", "body": "ここも同じくです\n```suggestion\nもし、`PATH`環境変数を更新するように答えると、`PATH`環境変数に`C:\\opt\\custompython\\bin`が追加されます。\n```", "path": "docs/ja/docs/environment-variables.md", "line": null, "side": "RIGHT", "created_at": "2025-01-25T12:49:00+00:00" }, { "id": 1929537902, "user": "user_9a4a033d7317", "body": "おそらくこんな感じかなと思います\n```suggestion\nこのようにして、ターミナルで`python`と入力したときに、OSは`/opt/custompython/bin`(リストの末尾のディレクトリ)にあるPythonプログラムを見つけ、使用します。\n```", "path": "docs/ja/docs/environment-variables.md", "line": null, "side": "RIGHT", "created_at": "2025-01-25T12:51:44+00:00" }, { "id": 1929537933, "user": "user_9a4a033d7317", "body": "ここも同じくです\n```suggestion\nこのようにして、ターミナルで`python`と入力したときに、OSは`C:\\opt\\custompython\\bin\\python`(リストの末尾のディレクトリ)にあるPythonプログラムを見つけ、使用します。\n```", "path": "docs/ja/docs/environment-variables.md", "line": null, "side": "RIGHT", "created_at": "2025-01-25T12:52:03+00:00" } ], "meta": { "languages": [ "md" ], "touches_tests": false, "review_state_summary": { "COMMENTED": 1, "APPROVED": 1 }, "meaningful_comment_count": 6, "has_approval": true, "has_changes_requested": false, "total_review_comments": 6 } } { "_id": "4a01a7711e2962e6", "_schema_version": "1.0", "_cleaned_at": "2026-02-12T07:46:52.211178+00:00", "repo": "tiangolo/fastapi", "repo_url": "https://github.com/fastapi/fastapi", "license_name": "MIT License", "license_spdx": "MIT", "pr_number": 13207, "title": "🐛 Fix OpenAPI schema support for computed fields when using `separate_input_output_schemas=False`", "body": "This demonstrates how the output schema differs when the FastAPI app runs with different values for `separate_input_output_schemas` - namely, the computed fields are omitted.\n\nInitially reported here: https://github.com/fastapi/fastapi/discussions/10342", "author": "user_da8699ffe3e0", "created_at": "2025-01-14T18:51:26+00:00", "merged_at": "2025-12-02T09:22:08+00:00", "base_branch": "master", "head_branch": "test-computed-fields-unseparated", "additions": 17, "deletions": 4, "changed_files": 2, "files": [ { "filename": "fastapi/_compat/v2.py", "status": "modified", "additions": 12, "deletions": 2, "changes": 14, "patch": "@@ -180,8 +180,13 @@ def get_schema_from_model_field(\n ],\n separate_input_output_schemas: bool = True,\n ) -> Dict[str, Any]:\n+ computed_fields = field._type_adapter.core_schema.get(\"schema\", {}).get(\n+ \"computed_fields\", []\n+ )\n override_mode: Union[Literal[\"validation\"], None] = (\n- None if separate_input_output_schemas else \"validation\"\n+ None\n+ if (separate_input_output_schemas or len(computed_fields) > 0)\n+ else \"validation\"\n )\n # This expects that GenerateJsonSchema was already used to generate the definitions\n json_schema = field_mapping[(field, override_mode or field.mode)]\n@@ -203,9 +208,14 @@ def get_definitions(\n Dict[Tuple[ModelField, Literal[\"validation\", \"serialization\"]], JsonSchemaValue],\n Dict[str, Dict[str, Any]],\n ]:\n+ has_computed_fields: bool = any(\n+ field._type_adapter.core_schema.get(\"schema\", {}).get(\"computed_fields\", [])\n+ for field in fields\n+ )\n+\n schema_generator = GenerateJsonSchema(ref_template=REF_TEMPLATE)\n override_mode: Union[Literal[\"validation\"], None] = (\n- None if separate_input_output_schemas else \"validation\"\n+ None if (separate_input_output_schemas or has_computed_fields) else \"validation\"\n )\n validation_fields = [field for field in fields if field.mode == \"validation\"]\n serialization_fields = [field for field in fields if field.mode == \"serialization\"]" }, { "filename": "tests/test_computed_fields.py", "status": "modified", "additions": 5, "deletions": 2, "changes": 7, "patch": "@@ -6,8 +6,9 @@\n \n \n [USER_REDACTED].fixture(name=\"client\")\n-def get_client():\n- app = FastAPI()\n+def get_client(request):\n+ separate_input_output_schemas = request.param\n+ app = FastAPI(separate_input_output_schemas=separate_input_output_schemas)\n \n from pydantic import BaseModel, computed_field\n \n@@ -32,6 +33,7 @@ def read_responses() -> Rectangle:\n return client\n \n \n+[USER_REDACTED].mark.parametrize(\"client\", [True, False], indirect=True)\n [USER_REDACTED].mark.parametrize(\"path\", [\"/\", \"/responses\"])\n [USER_REDACTED]_pydanticv2\n def test_get(client: TestClient, path: str):\n@@ -40,6 +42,7 @@ def test_get(client: TestClient, path: str):\n assert response.json() == {\"width\": 3, \"length\": 4, \"area\": 12}\n \n \n+[USER_REDACTED].mark.parametrize(\"client\", [True, False], indirect=True)\n [USER_REDACTED]_pydanticv2\n def test_openapi_schema(client: TestClient):\n response = client.get(\"/openapi.json\")" } ], "reviews": [ { "id": 3137108208, "user": "user_84458f05cf3c", "state": "COMMENTED", "body": null, "submitted_at": "2025-08-20T15:17:42+00:00" }, { "id": 3529069358, "user": "user_2a237e38e06b", "state": "APPROVED", "body": "Nice, thank you [USER_REDACTED]! 🚀 \n\nAnd thanks for the help and work here [USER_REDACTED] and [USER_REDACTED] 🙌 🍰 \n\nThis will be available in FastAPI 0.123.4, released in the next hours. 🎉", "submitted_at": "2025-12-02T09:20:49+00:00" } ], "review_comments": [ { "id": 2288512317, "user": "user_84458f05cf3c", "body": "Not too happy with this solution, perhaps we should copy the given `schema_generator` instead?", "path": "fastapi/_compat.py", "line": null, "side": "RIGHT", "created_at": "2025-08-20T15:17:41+00:00" } ], "meta": { "languages": [ "py" ], "touches_tests": true, "review_state_summary": { "COMMENTED": 1, "APPROVED": 1 }, "meaningful_comment_count": 1, "has_approval": true, "has_changes_requested": false, "total_review_comments": 1 } } { "_id": "e443c16985902ebe", "_schema_version": "1.0", "_cleaned_at": "2026-02-12T07:46:52.211178+00:00", "repo": "tiangolo/fastapi", "repo_url": "https://github.com/fastapi/fastapi", "license_name": "MIT License", "license_spdx": "MIT", "pr_number": 13205, "title": "🌐 Add Portuguese translation for `docs/pt/docs/tutorial/security/oauth2-jwt.md`", "body": null, "author": "user_178cb4401e94", "created_at": "2025-01-13T12:04:16+00:00", "merged_at": "2025-01-15T20:16:13+00:00", "base_branch": "master", "head_branch": "features/translate-oauth-2-jwt-pt", "additions": 274, "deletions": 0, "changed_files": 1, "files": [ { "filename": "docs/pt/docs/tutorial/security/oauth2-jwt.md", "status": "added", "additions": 274, "deletions": 0, "changes": 274, "patch": "@@ -0,0 +1,274 @@\n+# OAuth2 com Senha (e hashing), Bearer com tokens JWT\n+\n+Agora que temos todo o fluxo de segurança, vamos tornar a aplicação realmente segura, usando tokens JWT e hashing de senhas seguras.\n+\n+Este código é algo que você pode realmente usar na sua aplicação, salvar os hashes das senhas no seu banco de dados, etc.\n+\n+Vamos começar de onde paramos no capítulo anterior e incrementá-lo.\n+\n+## Sobre o JWT\n+\n+JWT significa \"JSON [NAME_REDACTED]\".\n+\n+É um padrão para codificar um objeto JSON em uma string longa e densa sem espaços. Ele se parece com isso:\n+\n+```\n+eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c\n+```\n+\n+Ele não é criptografado, então qualquer pessoa pode recuperar as informações do seu conteúdo.\n+\n+Mas ele é assinado. Assim, quando você recebe um token que você emitiu, você pode verificar que foi realmente você quem o emitiu.\n+\n+Dessa forma, você pode criar um token com um prazo de expiração, digamos, de 1 semana. E então, quando o usuário voltar no dia seguinte com o token, você sabe que ele ainda está logado no seu sistema.\n+\n+Depois de uma semana, o token expirará e o usuário não estará autorizado, precisando fazer login novamente para obter um novo token. E se o usuário (ou uma terceira parte) tentar modificar o token para alterar a expiração, você seria capaz de descobrir isso, pois as assinaturas não iriam corresponder.\n+\n+Se você quiser brincar com tokens JWT e ver como eles funcionam, visite https://jwt.io.\n+\n+## Instalar `PyJWT`\n+\n+Nós precisamos instalar o `PyJWT` para criar e verificar os tokens JWT em Python.\n+\n+Certifique-se de criar um [ambiente virtual](../../virtual-environments.md){.internal-link target=_blank}, ativá-lo e então instalar o `pyjwt`:\n+\n+
      \n+\n+```console\n+$ pip install pyjwt\n+\n+---> 100%\n+```\n+\n+
      \n+\n+/// info | Informação\n+\n+Se você pretente utilizar algoritmos de assinatura digital como o RSA ou o ECDSA, você deve instalar a dependência da biblioteca de criptografia `pyjwt[crypto]`.\n+\n+Você pode ler mais sobre isso na documentação de instalação do PyJWT.\n+\n+///\n+\n+## Hashing de senhas\n+\n+\"Hashing\" significa converter algum conteúdo (uma senha neste caso) em uma sequência de bytes (apenas uma string) que parece um monte de caracteres sem sentido.\n+\n+Sempre que você passar exatamente o mesmo conteúdo (exatamente a mesma senha), você obterá exatamente o mesmo resultado.\n+\n+Mas não é possível converter os caracteres sem sentido de volta para a senha original.\n+\n+### Por que usar hashing de senhas\n+\n+Se o seu banco de dados for roubado, o invasor não terá as senhas em texto puro dos seus usuários, apenas os hashes.\n+\n+Então, o invasor não poderá tentar usar essas senhas em outro sistema (como muitos usuários utilizam a mesma senha em vários lugares, isso seria perigoso).\n+\n+## Instalar o `passlib`\n+\n+O PassLib é uma excelente biblioteca Python para lidar com hashes de senhas.\n+\n+Ele suporta muitos algoritmos de hashing seguros e utilitários para trabalhar com eles.\n+\n+O algoritmo recomendado é o \"Bcrypt\".\n+\n+Certifique-se de criar um [ambiente virtual](../../virtual-environments.md){.internal-link target=_blank}, ativá-lo e então instalar o PassLib com Bcrypt:\n+\n+
      \n+\n+```console\n+$ pip install \"passlib[bcrypt]\"\n+\n+---> 100%\n+```\n+\n+
      \n+\n+/// tip | Dica\n+\n+Com o `passlib`, você poderia até configurá-lo para ser capaz de ler senhas criadas pelo **Django**, um plug-in de segurança do **Flask** ou muitos outros.\n+\n+Assim, você poderia, por exemplo, compartilhar os mesmos dados de um aplicativo Django em um banco de dados com um aplicativo FastAPI. Ou migrar gradualmente uma aplicação Django usando o mesmo banco de dados.\n+\n+E seus usuários poderiam fazer login tanto pela sua aplicação Django quanto pela sua aplicação **FastAPI**, ao mesmo tempo.\n+\n+///\n+\n+## Criar o hash e verificar as senhas\n+\n+Importe as ferramentas que nós precisamos de `passlib`.\n+\n+Crie um \"contexto\" do PassLib. Este será usado para criar o hash e verificar as senhas.\n+\n+/// tip | Dica\n+\n+O contexto do PassLib também possui funcionalidades para usar diferentes algoritmos de hashing, incluindo algoritmos antigos que estão obsoletos, apenas para permitir verificá-los, etc.\n+\n+Por exemplo, você poderia usá-lo para ler e verificar senhas geradas por outro sistema (como Django), mas criar o hash de novas senhas com um algoritmo diferente, como o Bcrypt.\n+\n+E ser compatível com todos eles ao mesmo tempo.\n+\n+///\n+\n+Crie uma função utilitária para criar o hash de uma senha fornecida pelo usuário.\n+\n+E outra função utilitária para verificar se uma senha recebida corresponde ao hash armazenado.\n+\n+E outra para autenticar e retornar um usuário.\n+\n+{* ../../docs_src/security/tutorial004_an_py310.py hl[8,49,56:57,60:61,70:76] *}\n+\n+/// note | Nota\n+\n+Se você verificar o novo banco de dados (falso) `fake_users_db`, você verá como o hash da senha se parece agora: `\"$2b$12$EixZaYVK1fsbw1ZfbX3OXePaWxn96p36WQoeG6Lruj3vjPGga31lW\"`.\n+\n+///\n+\n+## Manipular tokens JWT\n+\n+Importe os módulos instalados.\n+\n+Crie uma chave secreta aleatória que será usada para assinar os tokens JWT.\n+\n+Para gerar uma chave secreta aleatória e segura, use o comando:\n+\n+
      \n+\n+```console\n+$ openssl rand -hex 32\n+\n+09d25e094faa6ca2556c818166b7a9563b93f7099f6f0f4caa6cf63b88e8d3e7\n+```\n+\n+
      \n+\n+E copie a saída para a variável `SECRET_KEY` (não use a do exemplo).\n+\n+Crie uma variável `ALGORITHM` com o algoritmo usado para assinar o token JWT e defina como `\"HS256\"`.\n+\n+Crie uma variável para a expiração do token.\n+\n+Defina um modelo Pydantic que será usado no endpoint de token para a resposta.\n+\n+Crie uma função utilitária para gerar um novo token de acesso.\n+\n+{* ../../docs_src/security/tutorial004_an_py310.py hl[4,7,13:15,29:31,79:87] *}\n+\n+## Atualize as dependências\n+\n+Atualize `get_current_user` para receber o mesmo token de antes, mas desta vez, usando tokens JWT.\n+\n+Decodifique o token recebido, verifique-o e retorne o usuário atual.\n+\n+Se o token for inválido, retorne um erro HTTP imediatamente.\n+\n+{* ../../docs_src/security/tutorial004_an_py310.py hl[90:107] *}\n+\n+## Atualize a *operação de rota* `/token`\n+\n+Crie um `timedelta` com o tempo de expiração do token.\n+\n+Crie um token de acesso JWT real e o retorne.\n+\n+{* ../../docs_src/security/tutorial004_an_py310.py hl[118:133] *}\n+\n+### Detalhes técnicos sobre o \"sujeito\" `sub` do JWT\n+\n+A especificação JWT diz que existe uma chave `sub`, com o sujeito do token.\n+\n+É opcional usá-la, mas é onde você colocaria a identificação do usuário, então nós estamos usando aqui.\n+\n+O JWT pode ser usado para outras coisas além de identificar um usuário e permitir que ele execute operações diretamente na sua API.\n+\n+Por exemplo, você poderia identificar um \"carro\" ou uma \"postagem de blog\".\n+\n+Depois, você poderia adicionar permissões sobre essa entidade, como \"dirigir\" (para o carro) ou \"editar\" (para o blog).\n+\n+E então, poderia dar esse token JWT para um usuário (ou bot), e ele poderia usá-lo para realizar essas ações (dirigir o carro ou editar o blog) sem sequer precisar ter uma conta, apenas com o token JWT que sua API gerou para isso.\n+\n+Usando essas ideias, o JWT pode ser usado para cenários muito mais sofisticados.\n+\n+Nesses casos, várias dessas entidades poderiam ter o mesmo ID, digamos `foo` (um usuário `foo`, um carro `foo` e uma postagem de blog `foo`).\n+\n+Então, para evitar colisões de ID, ao criar o token JWT para o usuário, você poderia prefixar o valor da chave `sub`, por exemplo, com `username:`. Assim, neste exemplo, o valor de `sub` poderia ser: `username:johndoe`.\n+\n+O importante a se lembrar é que a chave `sub` deve ter um identificador único em toda a aplicação e deve ser uma string.\n+\n+## Testando\n+\n+Execute o servidor e vá para a documentação: http://127.0.0.1:8000/docs.\n+\n+Você verá a interface de usuário assim:\n+\n+\n+\n+Autorize a aplicação da mesma maneira que antes.\n+\n+Usando as credenciais:\n+\n+Username: `johndoe`\n+Password: `secret`\n+\n+/// check | Verifique\n+\n+Observe que em nenhuma parte do código está a senha em texto puro \"`secret`\", nós temos apenas o hash.\n+\n+///\n+\n+\n+\n+Chame o endpoint `/users/me/`, você receberá o retorno como:\n+\n+```JSON\n+{\n+ \"username\": \"johndoe\",\n+ \"email\": \"[EMAIL_REDACTED]\",\n+ \"full_name\": \"[NAME_REDACTED]\",\n+ \"disabled\": false\n+}\n+```\n+\n+\n+\n+Se você abrir as ferramentas de desenvolvedor, poderá ver que os dados enviados incluem apenas o token. A senha é enviada apenas na primeira requisição para autenticar o usuário e obter o token de acesso, mas não é enviada nas próximas requisições:\n+\n+\n+\n+/// note | Nota\n+\n+Perceba que o cabeçalho `Authorization`, com o valor que começa com `Bearer `.\n+\n+///\n+\n+## Uso avançado com `scopes`\n+\n+O OAuth2 tem a noção de \"scopes\" (escopos).\n+\n+Você pode usá-los para adicionar um conjunto específico de permissões a um token JWT.\n+\n+Então, você pode dar este token diretamente a um usuário ou a uma terceira parte para interagir com sua API com um conjunto de restrições.\n+\n+Você pode aprender como usá-los e como eles são integrados ao **FastAPI** mais adiante no **Guia Avançado do Usuário**.\n+\n+\n+## Recapitulação\n+\n+Com o que você viu até agora, você pode configurar uma aplicação **FastAPI** segura usando padrões como OAuth2 e JWT.\n+\n+Em quase qualquer framework, lidar com a segurança se torna rapidamente um assunto bastante complexo.\n+\n+Muitos pacotes que simplificam bastante isso precisam fazer muitas concessões com o modelo de dados, o banco de dados e os recursos disponíveis. E alguns desses pacotes que simplificam demais na verdade têm falhas de segurança subjacentes.\n+\n+---\n+\n+O **FastAPI** não faz nenhuma concessão com nenhum banco de dados, modelo de dados ou ferramenta.\n+\n+Ele oferece toda a flexibilidade para você escolher as opções que melhor se ajustam ao seu projeto.\n+\n+E você pode usar diretamente muitos pacotes bem mantidos e amplamente utilizados, como `passlib` e `PyJWT`, porque o **FastAPI** não exige mecanismos complexos para integrar pacotes externos.\n+\n+Mas ele fornece as ferramentas para simplificar o processo o máximo possível, sem comprometer a flexibilidade, robustez ou segurança.\n+\n+E você pode usar e implementar protocolos padrão seguros, como o OAuth2, de uma maneira relativamente simples.\n+\n+Você pode aprender mais no **Guia Avançado do Usuário** sobre como usar os \"scopes\" do OAuth2 para um sistema de permissões mais refinado, seguindo esses mesmos padrões. O OAuth2 com scopes é o mecanismo usado por muitos provedores grandes de autenticação, como o Facebook, Google, GitHub, Microsoft, Twitter, etc. para autorizar aplicativos de terceiros a interagir com suas APIs em nome de seus usuários." } ], "reviews": [ { "id": 2548841028, "user": "user_e10da7d15f57", "state": "APPROVED", "body": "Excellent, soon we will have the whole documentation translated.\n\n[USER_REDACTED], do you have time to review this good work and provide your approval?", "submitted_at": "2025-01-14T05:25:10+00:00" }, { "id": 2550592193, "user": "user_afc2ad817d84", "state": "COMMENTED", "body": "very good!! I only pointed out 3 corrections. great work 🚀", "submitted_at": "2025-01-14T17:59:54+00:00" }, { "id": 2552249425, "user": "user_178cb4401e94", "state": "COMMENTED", "body": null, "submitted_at": "2025-01-15T11:04:16+00:00" }, { "id": 2552940133, "user": "user_afc2ad817d84", "state": "APPROVED", "body": "LGTM!", "submitted_at": "2025-01-15T14:35:24+00:00" } ], "review_comments": [ { "id": 1915347392, "user": "user_afc2ad817d84", "body": "this sentence remained", "path": "docs/pt/docs/tutorial/security/oauth2-jwt.md", "line": null, "side": "RIGHT", "created_at": "2025-01-14T17:50:45+00:00" }, { "id": 1915353522, "user": "user_afc2ad817d84", "body": "```suggestion\nPerceba que o cabeçalho `Authorization`, com o valor que começa com `Bearer `.\n```", "path": "docs/pt/docs/tutorial/security/oauth2-jwt.md", "line": null, "side": "RIGHT", "created_at": "2025-01-14T17:55:10+00:00" }, { "id": 1915363557, "user": "user_afc2ad817d84", "body": "Here's a very underground correction: \"etc\" doesn't allow a comma after its use, the correct option is to just use the \".\".\n\n```suggestion\nVocê pode aprender mais no **Guia Avançado do Usuário** sobre como usar os \"scopes\" do OAuth2 para um sistema de permissões mais refinado, seguindo esses mesmos padrões. O OAuth2 com scopes é o mecanismo usado por muitos provedores grandes de autenticação, como o Facebook, Google, GitHub, Microsoft, Twitter, etc. para autorizar aplicativos de terceiros a interagir com suas APIs em nome de seus usuários.\n```", "path": "docs/pt/docs/tutorial/security/oauth2-jwt.md", "line": null, "side": "RIGHT", "created_at": "2025-01-14T17:59:02+00:00" }, { "id": 1916363968, "user": "user_178cb4401e94", "body": "Wow, I had no idea about that @_@", "path": "docs/pt/docs/tutorial/security/oauth2-jwt.md", "line": null, "side": "RIGHT", "created_at": "2025-01-15T11:04:16+00:00" } ], "meta": { "languages": [ "md" ], "touches_tests": false, "review_state_summary": { "APPROVED": 2, "COMMENTED": 2 }, "meaningful_comment_count": 4, "has_approval": true, "has_changes_requested": false, "total_review_comments": 4 } } { "_id": "c1f7480050ce3a21", "_schema_version": "1.0", "_cleaned_at": "2026-02-12T07:46:52.211178+00:00", "repo": "tiangolo/fastapi", "repo_url": "https://github.com/fastapi/fastapi", "license_name": "MIT License", "license_spdx": "MIT", "pr_number": 13183, "title": "✅ Simplify tests for request_form_models", "body": "#13150", "author": "user_568843bce6ca", "created_at": "2025-01-08T19:38:21+00:00", "merged_at": "2025-01-19T22:39:18+00:00", "base_branch": "master", "head_branch": "tests-request-form-models", "additions": 50, "deletions": 1284, "changed_files": 9, "files": [ { "filename": "tests/test_tutorial/test_request_form_models/test_tutorial001.py", "status": "modified", "additions": 15, "deletions": 4, "changes": 19, "patch": "@@ -1,13 +1,24 @@\n+import importlib\n+\n import pytest\n from dirty_equals import IsDict\n from fastapi.testclient import TestClient\n \n+from ...utils import needs_py39\n+\n \n-[USER_REDACTED].fixture(name=\"client\")\n-def get_client():\n- from docs_src.request_form_models.tutorial001 import app\n+[USER_REDACTED].fixture(\n+ name=\"client\",\n+ params=[\n+ \"tutorial001\",\n+ \"tutorial001_an\",\n+ pytest.param(\"tutorial001_an_py39\", marks=needs_py39),\n+ ],\n+)\n+def get_client(request: pytest.FixtureRequest):\n+ mod = importlib.import_module(f\"docs_src.request_form_models.{request.param}\")\n \n- client = TestClient(app)\n+ client = TestClient(mod.app)\n return client" }, { "filename": "tests/test_tutorial/test_request_form_models/test_tutorial001_an.py", "status": "removed", "additions": 0, "deletions": 232, "changes": 232, "patch": "@@ -1,232 +0,0 @@\n-import pytest\n-from dirty_equals import IsDict\n-from fastapi.testclient import TestClient\n-\n-\n-[USER_REDACTED].fixture(name=\"client\")\n-def get_client():\n- from docs_src.request_form_models.tutorial001_an import app\n-\n- client = TestClient(app)\n- return client\n-\n-\n-def test_post_body_form(client: TestClient):\n- response = client.post(\"/login/\", data={\"username\": \"Foo\", \"password\": \"secret\"})\n- assert response.status_code == 200\n- assert response.json() == {\"username\": \"Foo\", \"password\": \"secret\"}\n-\n-\n-def test_post_body_form_no_password(client: TestClient):\n- response = client.post(\"/login/\", data={\"username\": \"Foo\"})\n- assert response.status_code == 422\n- assert response.json() == IsDict(\n- {\n- \"detail\": [\n- {\n- \"type\": \"missing\",\n- \"loc\": [\"body\", \"password\"],\n- \"msg\": \"Field required\",\n- \"input\": {\"username\": \"Foo\"},\n- }\n- ]\n- }\n- ) | IsDict(\n- # TODO: remove when deprecating Pydantic v1\n- {\n- \"detail\": [\n- {\n- \"loc\": [\"body\", \"password\"],\n- \"msg\": \"field required\",\n- \"type\": \"value_error.missing\",\n- }\n- ]\n- }\n- )\n-\n-\n-def test_post_body_form_no_username(client: TestClient):\n- response = client.post(\"/login/\", data={\"password\": \"secret\"})\n- assert response.status_code == 422\n- assert response.json() == IsDict(\n- {\n- \"detail\": [\n- {\n- \"type\": \"missing\",\n- \"loc\": [\"body\", \"username\"],\n- \"msg\": \"Field required\",\n- \"input\": {\"password\": \"secret\"},\n- }\n- ]\n- }\n- ) | IsDict(\n- # TODO: remove when deprecating Pydantic v1\n- {\n- \"detail\": [\n- {\n- \"loc\": [\"body\", \"username\"],\n- \"msg\": \"field required\",\n- \"type\": \"value_error.missing\",\n- }\n- ]\n- }\n- )\n-\n-\n-def test_post_body_form_no_data(client: TestClient):\n- response = client.post(\"/login/\")\n- assert response.status_code == 422\n- assert response.json() == IsDict(\n- {\n- \"detail\": [\n- {\n- \"type\": \"missing\",\n- \"loc\": [\"body\", \"username\"],\n- \"msg\": \"Field required\",\n- \"input\": {},\n- },\n- {\n- \"type\": \"missing\",\n- \"loc\": [\"body\", \"password\"],\n- \"msg\": \"Field required\",\n- \"input\": {},\n- },\n- ]\n- }\n- ) | IsDict(\n- # TODO: remove when deprecating Pydantic v1\n- {\n- \"detail\": [\n- {\n- \"loc\": [\"body\", \"username\"],\n- \"msg\": \"field required\",\n- \"type\": \"value_error.missing\",\n- },\n- {\n- \"loc\": [\"body\", \"password\"],\n- \"msg\": \"field required\",\n- \"type\": \"value_error.missing\",\n- },\n- ]\n- }\n- )\n-\n-\n-def test_post_body_json(client: TestClient):\n- response = client.post(\"/login/\", json={\"username\": \"Foo\", \"password\": \"secret\"})\n- assert response.status_code == 422, response.text\n- assert response.json() == IsDict(\n- {\n- \"detail\": [\n- {\n- \"type\": \"missing\",\n- \"loc\": [\"body\", \"username\"],\n- \"msg\": \"Field required\",\n- \"input\": {},\n- },\n- {\n- \"type\": \"missing\",\n- \"loc\": [\"body\", \"password\"],\n- \"msg\": \"Field required\",\n- \"input\": {},\n- },\n- ]\n- }\n- ) | IsDict(\n- # TODO: remove when deprecating Pydantic v1\n- {\n- \"detail\": [\n- {\n- \"loc\": [\"body\", \"username\"],\n- \"msg\": \"field required\",\n- \"type\": \"value_error.missing\",\n- },\n- {\n- \"loc\": [\"body\", \"password\"],\n- \"msg\": \"field required\",\n- \"type\": \"value_error.missing\",\n- },\n- ]\n- }\n- )\n-\n-\n-def test_openapi_schema(client: TestClient):\n- response = client.get(\"/openapi.json\")\n- assert response.status_code == 200, response.text\n- assert response.json() == {\n- \"openapi\": \"3.1.0\",\n- \"info\": {\"title\": \"FastAPI\", \"version\": \"0.1.0\"},\n- \"paths\": {\n- \"/login/\": {\n- \"post\": {\n- \"responses\": {\n- \"200\": {\n- \"description\": \"[NAME_REDACTED]\",\n- \"content\": {\"application/json\": {\"schema\": {}}},\n- },\n- \"422\": {\n- \"description\": \"[NAME_REDACTED]\",\n- \"content\": {\n- \"application/json\": {\n- \"schema\": {\n- \"$ref\": \"#/components/schemas/HTTPValidationError\"\n- }\n- }\n- },\n- },\n- },\n- \"summary\": \"Login\",\n- \"operationId\": \"login_login__post\",\n- \"requestBody\": {\n- \"content\": {\n- \"application/x-www-form-urlencoded\": {\n- \"schema\": {\"$ref\": \"#/components/schemas/FormData\"}\n- }\n- },\n- \"required\": True,\n- },\n- }\n- }\n- },\n- \"components\": {\n- \"schemas\": {\n- \"FormData\": {\n- \"properties\": {\n- \"username\": {\"type\": \"string\", \"title\": \"Username\"},\n- \"password\": {\"type\": \"string\", \"title\": \"Password\"},\n- },\n- \"type\": \"object\",\n- \"required\": [\"username\", \"password\"],\n- \"title\": \"FormData\",\n- },\n- \"ValidationError\": {\n- \"title\": \"ValidationError\",\n- \"required\": [\"loc\", \"msg\", \"type\"],\n- \"type\": \"object\",\n- \"properties\": {\n- \"loc\": {\n- \"title\": \"Location\",\n- \"type\": \"array\",\n- \"items\": {\n- \"anyOf\": [{\"type\": \"string\"}, {\"type\": \"integer\"}]\n- },\n- },\n- \"msg\": {\"title\": \"Message\", \"type\": \"string\"},\n- \"type\": {\"title\": \"[NAME_REDACTED]\", \"type\": \"string\"},\n- },\n- },\n- \"HTTPValidationError\": {\n- \"title\": \"HTTPValidationError\",\n- \"type\": \"object\",\n- \"properties\": {\n- \"detail\": {\n- \"title\": \"Detail\",\n- \"type\": \"array\",\n- \"items\": {\"$ref\": \"#/components/schemas/ValidationError\"},\n- }\n- },\n- },\n- }\n- },\n- }" }, { "filename": "tests/test_tutorial/test_request_form_models/test_tutorial001_an_py39.py", "status": "removed", "additions": 0, "deletions": 240, "changes": 240, "patch": "@@ -1,240 +0,0 @@\n-import pytest\n-from dirty_equals import IsDict\n-from fastapi.testclient import TestClient\n-\n-from tests.utils import needs_py39\n-\n-\n-[USER_REDACTED].fixture(name=\"client\")\n-def get_client():\n- from docs_src.request_form_models.tutorial001_an_py39 import app\n-\n- client = TestClient(app)\n- return client\n-\n-\n-[USER_REDACTED]_py39\n-def test_post_body_form(client: TestClient):\n- response = client.post(\"/login/\", data={\"username\": \"Foo\", \"password\": \"secret\"})\n- assert response.status_code == 200\n- assert response.json() == {\"username\": \"Foo\", \"password\": \"secret\"}\n-\n-\n-[USER_REDACTED]_py39\n-def test_post_body_form_no_password(client: TestClient):\n- response = client.post(\"/login/\", data={\"username\": \"Foo\"})\n- assert response.status_code == 422\n- assert response.json() == IsDict(\n- {\n- \"detail\": [\n- {\n- \"type\": \"missing\",\n- \"loc\": [\"body\", \"password\"],\n- \"msg\": \"Field required\",\n- \"input\": {\"username\": \"Foo\"},\n- }\n- ]\n- }\n- ) | IsDict(\n- # TODO: remove when deprecating Pydantic v1\n- {\n- \"detail\": [\n- {\n- \"loc\": [\"body\", \"password\"],\n- \"msg\": \"field required\",\n- \"type\": \"value_error.missing\",\n- }\n- ]\n- }\n- )\n-\n-\n-[USER_REDACTED]_py39\n-def test_post_body_form_no_username(client: TestClient):\n- response = client.post(\"/login/\", data={\"password\": \"secret\"})\n- assert response.status_code == 422\n- assert response.json() == IsDict(\n- {\n- \"detail\": [\n- {\n- \"type\": \"missing\",\n- \"loc\": [\"body\", \"username\"],\n- \"msg\": \"Field required\",\n- \"input\": {\"password\": \"secret\"},\n- }\n- ]\n- }\n- ) | IsDict(\n- # TODO: remove when deprecating Pydantic v1\n- {\n- \"detail\": [\n- {\n- \"loc\": [\"body\", \"username\"],\n- \"msg\": \"field required\",\n- \"type\": \"value_error.missing\",\n- }\n- ]\n- }\n- )\n-\n-\n-[USER_REDACTED]_py39\n-def test_post_body_form_no_data(client: TestClient):\n- response = client.post(\"/login/\")\n- assert response.status_code == 422\n- assert response.json() == IsDict(\n- {\n- \"detail\": [\n- {\n- \"type\": \"missing\",\n- \"loc\": [\"body\", \"username\"],\n- \"msg\": \"Field required\",\n- \"input\": {},\n- },\n- {\n- \"type\": \"missing\",\n- \"loc\": [\"body\", \"password\"],\n- \"msg\": \"Field required\",\n- \"input\": {},\n- },\n- ]\n- }\n- ) | IsDict(\n- # TODO: remove when deprecating Pydantic v1\n- {\n- \"detail\": [\n- {\n- \"loc\": [\"body\", \"username\"],\n- \"msg\": \"field required\",\n- \"type\": \"value_error.missing\",\n- },\n- {\n- \"loc\": [\"body\", \"password\"],\n- \"msg\": \"field required\",\n- \"type\": \"value_error.missing\",\n- },\n- ]\n- }\n- )\n-\n-\n-[USER_REDACTED]_py39\n-def test_post_body_json(client: TestClient):\n- response = client.post(\"/login/\", json={\"username\": \"Foo\", \"password\": \"secret\"})\n- assert response.status_code == 422, response.text\n- assert response.json() == IsDict(\n- {\n- \"detail\": [\n- {\n- \"type\": \"missing\",\n- \"loc\": [\"body\", \"username\"],\n- \"msg\": \"Field required\",\n- \"input\": {},\n- },\n- {\n- \"type\": \"missing\",\n- \"loc\": [\"body\", \"password\"],\n- \"msg\": \"Field required\",\n- \"input\": {},\n- },\n- ]\n- }\n- ) | IsDict(\n- # TODO: remove when deprecating Pydantic v1\n- {\n- \"detail\": [\n- {\n- \"loc\": [\"body\", \"username\"],\n- \"msg\": \"field required\",\n- \"type\": \"value_error.missing\",\n- },\n- {\n- \"loc\": [\"body\", \"password\"],\n- \"msg\": \"field required\",\n- \"type\": \"value_error.missing\",\n- },\n- ]\n- }\n- )\n-\n-\n-[USER_REDACTED]_py39\n-def test_openapi_schema(client: TestClient):\n- response = client.get(\"/openapi.json\")\n- assert response.status_code == 200, response.text\n- assert response.json() == {\n- \"openapi\": \"3.1.0\",\n- \"info\": {\"title\": \"FastAPI\", \"version\": \"0.1.0\"},\n- \"paths\": {\n- \"/login/\": {\n- \"post\": {\n- \"responses\": {\n- \"200\": {\n- \"description\": \"[NAME_REDACTED]\",\n- \"content\": {\"application/json\": {\"schema\": {}}},\n- },\n- \"422\": {\n- \"description\": \"[NAME_REDACTED]\",\n- \"content\": {\n- \"application/json\": {\n- \"schema\": {\n- \"$ref\": \"#/components/schemas/HTTPValidationError\"\n- }\n- }\n- },\n- },\n- },\n- \"summary\": \"Login\",\n- \"operationId\": \"login_login__post\",\n- \"requestBody\": {\n- \"content\": {\n- \"application/x-www-form-urlencoded\": {\n- \"schema\": {\"$ref\": \"#/components/schemas/FormData\"}\n- }\n- },\n- \"required\": True,\n- },\n- }\n- }\n- },\n- \"components\": {\n- \"schemas\": {\n- \"FormData\": {\n- \"properties\": {\n- \"username\": {\"type\": \"string\", \"title\": \"Username\"},\n- \"password\": {\"type\": \"string\", \"title\": \"Password\"},\n- },\n- \"type\": \"object\",\n- \"required\": [\"username\", \"password\"],\n- \"title\": \"FormData\",\n- },\n- \"ValidationError\": {\n- \"title\": \"ValidationError\",\n- \"required\": [\"loc\", \"msg\", \"type\"],\n- \"type\": \"object\",\n- \"properties\": {\n- \"loc\": {\n- \"title\": \"Location\",\n- \"type\": \"array\",\n- \"items\": {\n- \"anyOf\": [{\"type\": \"string\"}, {\"type\": \"integer\"}]\n- },\n- },\n- \"msg\": {\"title\": \"Message\", \"type\": \"string\"},\n- \"type\": {\"title\": \"[NAME_REDACTED]\", \"type\": \"string\"},\n- },\n- },\n- \"HTTPValidationError\": {\n- \"title\": \"HTTPValidationError\",\n- \"type\": \"object\",\n- \"properties\": {\n- \"detail\": {\n- \"title\": \"Detail\",\n- \"type\": \"array\",\n- \"items\": {\"$ref\": \"#/components/schemas/ValidationError\"},\n- }\n- },\n- },\n- }\n- },\n- }" }, { "filename": "tests/test_tutorial/test_request_form_models/test_tutorial002.py", "status": "modified", "additions": 14, "deletions": 5, "changes": 19, "patch": "@@ -1,14 +1,23 @@\n+import importlib\n+\n import pytest\n from fastapi.testclient import TestClient\n \n-from tests.utils import needs_pydanticv2\n+from ...utils import needs_py39, needs_pydanticv2\n \n \n-[USER_REDACTED].fixture(name=\"client\")\n-def get_client():\n- from docs_src.request_form_models.tutorial002 import app\n+[USER_REDACTED].fixture(\n+ name=\"client\",\n+ params=[\n+ \"tutorial002\",\n+ \"tutorial002_an\",\n+ pytest.param(\"tutorial002_an_py39\", marks=needs_py39),\n+ ],\n+)\n+def get_client(request: pytest.FixtureRequest):\n+ mod = importlib.import_module(f\"docs_src.request_form_models.{request.param}\")\n \n- client = TestClient(app)\n+ client = TestClient(mod.app)\n return client" }, { "filename": "tests/test_tutorial/test_request_form_models/test_tutorial002_an.py", "status": "removed", "additions": 0, "deletions": 196, "changes": 196, "patch": "@@ -1,196 +0,0 @@\n-import pytest\n-from fastapi.testclient import TestClient\n-\n-from tests.utils import needs_pydanticv2\n-\n-\n-[USER_REDACTED].fixture(name=\"client\")\n-def get_client():\n- from docs_src.request_form_models.tutorial002_an import app\n-\n- client = TestClient(app)\n- return client\n-\n-\n-[USER_REDACTED]_pydanticv2\n-def test_post_body_form(client: TestClient):\n- response = client.post(\"/login/\", data={\"username\": \"Foo\", \"password\": \"secret\"})\n- assert response.status_code == 200\n- assert response.json() == {\"username\": \"Foo\", \"password\": \"secret\"}\n-\n-\n-[USER_REDACTED]_pydanticv2\n-def test_post_body_extra_form(client: TestClient):\n- response = client.post(\n- \"/login/\", data={\"username\": \"Foo\", \"password\": \"secret\", \"extra\": \"extra\"}\n- )\n- assert response.status_code == 422\n- assert response.json() == {\n- \"detail\": [\n- {\n- \"type\": \"extra_forbidden\",\n- \"loc\": [\"body\", \"extra\"],\n- \"msg\": \"Extra inputs are not permitted\",\n- \"input\": \"extra\",\n- }\n- ]\n- }\n-\n-\n-[USER_REDACTED]_pydanticv2\n-def test_post_body_form_no_password(client: TestClient):\n- response = client.post(\"/login/\", data={\"username\": \"Foo\"})\n- assert response.status_code == 422\n- assert response.json() == {\n- \"detail\": [\n- {\n- \"type\": \"missing\",\n- \"loc\": [\"body\", \"password\"],\n- \"msg\": \"Field required\",\n- \"input\": {\"username\": \"Foo\"},\n- }\n- ]\n- }\n-\n-\n-[USER_REDACTED]_pydanticv2\n-def test_post_body_form_no_username(client: TestClient):\n- response = client.post(\"/login/\", data={\"password\": \"secret\"})\n- assert response.status_code == 422\n- assert response.json() == {\n- \"detail\": [\n- {\n- \"type\": \"missing\",\n- \"loc\": [\"body\", \"username\"],\n- \"msg\": \"Field required\",\n- \"input\": {\"password\": \"secret\"},\n- }\n- ]\n- }\n-\n-\n-[USER_REDACTED]_pydanticv2\n-def test_post_body_form_no_data(client: TestClient):\n- response = client.post(\"/login/\")\n- assert response.status_code == 422\n- assert response.json() == {\n- \"detail\": [\n- {\n- \"type\": \"missing\",\n- \"loc\": [\"body\", \"username\"],\n- \"msg\": \"Field required\",\n- \"input\": {},\n- },\n- {\n- \"type\": \"missing\",\n- \"loc\": [\"body\", \"password\"],\n- \"msg\": \"Field required\",\n- \"input\": {},\n- },\n- ]\n- }\n-\n-\n-[USER_REDACTED]_pydanticv2\n-def test_post_body_json(client: TestClient):\n- response = client.post(\"/login/\", json={\"username\": \"Foo\", \"password\": \"secret\"})\n- assert response.status_code == 422, response.text\n- assert response.json() == {\n- \"detail\": [\n- {\n- \"type\": \"missing\",\n- \"loc\": [\"body\", \"username\"],\n- \"msg\": \"Field required\",\n- \"input\": {},\n- },\n- {\n- \"type\": \"missing\",\n- \"loc\": [\"body\", \"password\"],\n- \"msg\": \"Field required\",\n- \"input\": {},\n- },\n- ]\n- }\n-\n-\n-[USER_REDACTED]_pydanticv2\n-def test_openapi_schema(client: TestClient):\n- response = client.get(\"/openapi.json\")\n- assert response.status_code == 200, response.text\n- assert response.json() == {\n- \"openapi\": \"3.1.0\",\n- \"info\": {\"title\": \"FastAPI\", \"version\": \"0.1.0\"},\n- \"paths\": {\n- \"/login/\": {\n- \"post\": {\n- \"responses\": {\n- \"200\": {\n- \"description\": \"[NAME_REDACTED]\",\n- \"content\": {\"application/json\": {\"schema\": {}}},\n- },\n- \"422\": {\n- \"description\": \"[NAME_REDACTED]\",\n- \"content\": {\n- \"application/json\": {\n- \"schema\": {\n- \"$ref\": \"#/components/schemas/HTTPValidationError\"\n- }\n- }\n- },\n- },\n- },\n- \"summary\": \"Login\",\n- \"operationId\": \"login_login__post\",\n- \"requestBody\": {\n- \"content\": {\n- \"application/x-www-form-urlencoded\": {\n- \"schema\": {\"$ref\": \"#/components/schemas/FormData\"}\n- }\n- },\n- \"required\": True,\n- },\n- }\n- }\n- },\n- \"components\": {\n- \"schemas\": {\n- \"FormData\": {\n- \"properties\": {\n- \"username\": {\"type\": \"string\", \"title\": \"Username\"},\n- \"password\": {\"type\": \"string\", \"title\": \"Password\"},\n- },\n- \"additionalProperties\": False,\n- \"type\": \"object\",\n- \"required\": [\"username\", \"password\"],\n- \"title\": \"FormData\",\n- },\n- \"ValidationError\": {\n- \"title\": \"ValidationError\",\n- \"required\": [\"loc\", \"msg\", \"type\"],\n- \"type\": \"object\",\n- \"properties\": {\n- \"loc\": {\n- \"title\": \"Location\",\n- \"type\": \"array\",\n- \"items\": {\n- \"anyOf\": [{\"type\": \"string\"}, {\"type\": \"integer\"}]\n- },\n- },\n- \"msg\": {\"title\": \"Message\", \"type\": \"string\"},\n- \"type\": {\"title\": \"[NAME_REDACTED]\", \"type\": \"string\"},\n- },\n- },\n- \"HTTPValidationError\": {\n- \"title\": \"HTTPValidationError\",\n- \"type\": \"object\",\n- \"properties\": {\n- \"detail\": {\n- \"title\": \"Detail\",\n- \"type\": \"array\",\n- \"items\": {\"$ref\": \"#/components/schemas/ValidationError\"},\n- }\n- },\n- },\n- }\n- },\n- }" }, { "filename": "tests/test_tutorial/test_request_form_models/test_tutorial002_an_py39.py", "status": "removed", "additions": 0, "deletions": 203, "changes": 203, "patch": "@@ -1,203 +0,0 @@\n-import pytest\n-from fastapi.testclient import TestClient\n-\n-from tests.utils import needs_py39, needs_pydanticv2\n-\n-\n-[USER_REDACTED].fixture(name=\"client\")\n-def get_client():\n- from docs_src.request_form_models.tutorial002_an_py39 import app\n-\n- client = TestClient(app)\n- return client\n-\n-\n-[USER_REDACTED]_pydanticv2\n-[USER_REDACTED]_py39\n-def test_post_body_form(client: TestClient):\n- response = client.post(\"/login/\", data={\"username\": \"Foo\", \"password\": \"secret\"})\n- assert response.status_code == 200\n- assert response.json() == {\"username\": \"Foo\", \"password\": \"secret\"}\n-\n-\n-[USER_REDACTED]_pydanticv2\n-[USER_REDACTED]_py39\n-def test_post_body_extra_form(client: TestClient):\n- response = client.post(\n- \"/login/\", data={\"username\": \"Foo\", \"password\": \"secret\", \"extra\": \"extra\"}\n- )\n- assert response.status_code == 422\n- assert response.json() == {\n- \"detail\": [\n- {\n- \"type\": \"extra_forbidden\",\n- \"loc\": [\"body\", \"extra\"],\n- \"msg\": \"Extra inputs are not permitted\",\n- \"input\": \"extra\",\n- }\n- ]\n- }\n-\n-\n-[USER_REDACTED]_pydanticv2\n-[USER_REDACTED]_py39\n-def test_post_body_form_no_password(client: TestClient):\n- response = client.post(\"/login/\", data={\"username\": \"Foo\"})\n- assert response.status_code == 422\n- assert response.json() == {\n- \"detail\": [\n- {\n- \"type\": \"missing\",\n- \"loc\": [\"body\", \"password\"],\n- \"msg\": \"Field required\",\n- \"input\": {\"username\": \"Foo\"},\n- }\n- ]\n- }\n-\n-\n-[USER_REDACTED]_pydanticv2\n-[USER_REDACTED]_py39\n-def test_post_body_form_no_username(client: TestClient):\n- response = client.post(\"/login/\", data={\"password\": \"secret\"})\n- assert response.status_code == 422\n- assert response.json() == {\n- \"detail\": [\n- {\n- \"type\": \"missing\",\n- \"loc\": [\"body\", \"username\"],\n- \"msg\": \"Field required\",\n- \"input\": {\"password\": \"secret\"},\n- }\n- ]\n- }\n-\n-\n-[USER_REDACTED]_pydanticv2\n-[USER_REDACTED]_py39\n-def test_post_body_form_no_data(client: TestClient):\n- response = client.post(\"/login/\")\n- assert response.status_code == 422\n- assert response.json() == {\n- \"detail\": [\n- {\n- \"type\": \"missing\",\n- \"loc\": [\"body\", \"username\"],\n- \"msg\": \"Field required\",\n- \"input\": {},\n- },\n- {\n- \"type\": \"missing\",\n- \"loc\": [\"body\", \"password\"],\n- \"msg\": \"Field required\",\n- \"input\": {},\n- },\n- ]\n- }\n-\n-\n-[USER_REDACTED]_pydanticv2\n-[USER_REDACTED]_py39\n-def test_post_body_json(client: TestClient):\n- response = client.post(\"/login/\", json={\"username\": \"Foo\", \"password\": \"secret\"})\n- assert response.status_code == 422, response.text\n- assert response.json() == {\n- \"detail\": [\n- {\n- \"type\": \"missing\",\n- \"loc\": [\"body\", \"username\"],\n- \"msg\": \"Field required\",\n- \"input\": {},\n- },\n- {\n- \"type\": \"missing\",\n- \"loc\": [\"body\", \"password\"],\n- \"msg\": \"Field required\",\n- \"input\": {},\n- },\n- ]\n- }\n-\n-\n-[USER_REDACTED]_pydanticv2\n-[USER_REDACTED]_py39\n-def test_openapi_schema(client: TestClient):\n- response = client.get(\"/openapi.json\")\n- assert response.status_code == 200, response.text\n- assert response.json() == {\n- \"openapi\": \"3.1.0\",\n- \"info\": {\"title\": \"FastAPI\", \"version\": \"0.1.0\"},\n- \"paths\": {\n- \"/login/\": {\n- \"post\": {\n- \"responses\": {\n- \"200\": {\n- \"description\": \"[NAME_REDACTED]\",\n- \"content\": {\"application/json\": {\"schema\": {}}},\n- },\n- \"422\": {\n- \"description\": \"[NAME_REDACTED]\",\n- \"content\": {\n- \"application/json\": {\n- \"schema\": {\n- \"$ref\": \"#/components/schemas/HTTPValidationError\"\n- }\n- }\n- },\n- },\n- },\n- \"summary\": \"Login\",\n- \"operationId\": \"login_login__post\",\n- \"requestBody\": {\n- \"content\": {\n- \"application/x-www-form-urlencoded\": {\n- \"schema\": {\"$ref\": \"#/components/schemas/FormData\"}\n- }\n- },\n- \"required\": True,\n- },\n- }\n- }\n- },\n- \"components\": {\n- \"schemas\": {\n- \"FormData\": {\n- \"properties\": {\n- \"username\": {\"type\": \"string\", \"title\": \"Username\"},\n- \"password\": {\"type\": \"string\", \"title\": \"Password\"},\n- },\n- \"additionalProperties\": False,\n- \"type\": \"object\",\n- \"required\": [\"username\", \"password\"],\n- \"title\": \"FormData\",\n- },\n- \"ValidationError\": {\n- \"title\": \"ValidationError\",\n- \"required\": [\"loc\", \"msg\", \"type\"],\n- \"type\": \"object\",\n- \"properties\": {\n- \"loc\": {\n- \"title\": \"Location\",\n- \"type\": \"array\",\n- \"items\": {\n- \"anyOf\": [{\"type\": \"string\"}, {\"type\": \"integer\"}]\n- },\n- },\n- \"msg\": {\"title\": \"Message\", \"type\": \"string\"},\n- \"type\": {\"title\": \"[NAME_REDACTED]\", \"type\": \"string\"},\n- },\n- },\n- \"HTTPValidationError\": {\n- \"title\": \"HTTPValidationError\",\n- \"type\": \"object\",\n- \"properties\": {\n- \"detail\": {\n- \"title\": \"Detail\",\n- \"type\": \"array\",\n- \"items\": {\"$ref\": \"#/components/schemas/ValidationError\"},\n- }\n- },\n- },\n- }\n- },\n- }" }, { "filename": "tests/test_tutorial/test_request_form_models/test_tutorial002_pv1.py", "status": "modified", "additions": 21, "deletions": 5, "changes": 26, "patch": "@@ -1,24 +1,35 @@\n+import importlib\n+\n import pytest\n from fastapi.testclient import TestClient\n \n-from tests.utils import needs_pydanticv1\n+from ...utils import needs_py39, needs_pydanticv1\n \n \n-[USER_REDACTED].fixture(name=\"client\")\n-def get_client():\n- from docs_src.request_form_models.tutorial002_pv1 import app\n+[USER_REDACTED].fixture(\n+ name=\"client\",\n+ params=[\n+ \"tutorial002_pv1\",\n+ \"tutorial002_pv1_an\",\n+ pytest.param(\"tutorial002_pv1_an_py39\", marks=needs_py39),\n+ ],\n+)\n+def get_client(request: pytest.FixtureRequest):\n+ mod = importlib.import_module(f\"docs_src.request_form_models.{request.param}\")\n \n- client = TestClient(app)\n+ client = TestClient(mod.app)\n return client\n \n \n+# TODO: remove when deprecating Pydantic v1\n [USER_REDACTED]_pydanticv1\n def test_post_body_form(client: TestClient):\n response = client.post(\"/login/\", data={\"username\": \"Foo\", \"password\": \"secret\"})\n assert response.status_code == 200\n assert response.json() == {\"username\": \"Foo\", \"password\": \"secret\"}\n \n \n+# TODO: remove when deprecating Pydantic v1\n [USER_REDACTED]_pydanticv1\n def test_post_body_extra_form(client: TestClient):\n response = client.post(\n@@ -36,6 +47,7 @@ def test_post_body_extra_form(client: TestClient):\n }\n \n \n+# TODO: remove when deprecating Pydantic v1\n [USER_REDACTED]_pydanticv1\n def test_post_body_form_no_password(client: TestClient):\n response = client.post(\"/login/\", data={\"username\": \"Foo\"})\n@@ -51,6 +63,7 @@ def test_post_body_form_no_password(client: TestClient):\n }\n \n \n+# TODO: remove when deprecating Pydantic v1\n [USER_REDACTED]_pydanticv1\n def test_post_body_form_no_username(client: TestClient):\n response = client.post(\"/login/\", data={\"password\": \"secret\"})\n@@ -66,6 +79,7 @@ def test_post_body_form_no_username(client: TestClient):\n }\n \n \n+# TODO: remove when deprecating Pydantic v1\n [USER_REDACTED]_pydanticv1\n def test_post_body_form_no_data(client: TestClient):\n response = client.post(\"/login/\")\n@@ -86,6 +100,7 @@ def test_post_body_form_no_data(client: TestClient):\n }\n \n \n+# TODO: remove when deprecating Pydantic v1\n [USER_REDACTED]_pydanticv1\n def test_post_body_json(client: TestClient):\n response = client.post(\"/login/\", json={\"username\": \"Foo\", \"password\": \"secret\"})\n@@ -106,6 +121,7 @@ def test_post_body_json(client: TestClient):\n }\n \n \n+# TODO: remove when deprecating Pydantic v1\n [USER_REDACTED]_pydanticv1\n def test_openapi_schema(client: TestClient):\n response = client.get(\"/openapi.json\")" }, { "filename": "tests/test_tutorial/test_request_form_models/test_tutorial002_pv1_an.py", "status": "removed", "additions": 0, "deletions": 196, "changes": 196, "patch": "@@ -1,196 +0,0 @@\n-import pytest\n-from fastapi.testclient import TestClient\n-\n-from tests.utils import needs_pydanticv1\n-\n-\n-[USER_REDACTED].fixture(name=\"client\")\n-def get_client():\n- from docs_src.request_form_models.tutorial002_pv1_an import app\n-\n- client = TestClient(app)\n- return client\n-\n-\n-# TODO: remove when deprecating Pydantic v1\n-[USER_REDACTED]_pydanticv1\n-def test_post_body_form(client: TestClient):\n- response = client.post(\"/login/\", data={\"username\": \"Foo\", \"password\": \"secret\"})\n- assert response.status_code == 200\n- assert response.json() == {\"username\": \"Foo\", \"password\": \"secret\"}\n-\n-\n-# TODO: remove when deprecating Pydantic v1\n-[USER_REDACTED]_pydanticv1\n-def test_post_body_extra_form(client: TestClient):\n- response = client.post(\n- \"/login/\", data={\"username\": \"Foo\", \"password\": \"secret\", \"extra\": \"extra\"}\n- )\n- assert response.status_code == 422\n- assert response.json() == {\n- \"detail\": [\n- {\n- \"type\": \"value_error.extra\",\n- \"loc\": [\"body\", \"extra\"],\n- \"msg\": \"extra fields not permitted\",\n- }\n- ]\n- }\n-\n-\n-# TODO: remove when deprecating Pydantic v1\n-[USER_REDACTED]_pydanticv1\n-def test_post_body_form_no_password(client: TestClient):\n- response = client.post(\"/login/\", data={\"username\": \"Foo\"})\n- assert response.status_code == 422\n- assert response.json() == {\n- \"detail\": [\n- {\n- \"type\": \"value_error.missing\",\n- \"loc\": [\"body\", \"password\"],\n- \"msg\": \"field required\",\n- }\n- ]\n- }\n-\n-\n-# TODO: remove when deprecating Pydantic v1\n-[USER_REDACTED]_pydanticv1\n-def test_post_body_form_no_username(client: TestClient):\n- response = client.post(\"/login/\", data={\"password\": \"secret\"})\n- assert response.status_code == 422\n- assert response.json() == {\n- \"detail\": [\n- {\n- \"type\": \"value_error.missing\",\n- \"loc\": [\"body\", \"username\"],\n- \"msg\": \"field required\",\n- }\n- ]\n- }\n-\n-\n-# TODO: remove when deprecating Pydantic v1\n-[USER_REDACTED]_pydanticv1\n-def test_post_body_form_no_data(client: TestClient):\n- response = client.post(\"/login/\")\n- assert response.status_code == 422\n- assert response.json() == {\n- \"detail\": [\n- {\n- \"type\": \"value_error.missing\",\n- \"loc\": [\"body\", \"username\"],\n- \"msg\": \"field required\",\n- },\n- {\n- \"type\": \"value_error.missing\",\n- \"loc\": [\"body\", \"password\"],\n- \"msg\": \"field required\",\n- },\n- ]\n- }\n-\n-\n-# TODO: remove when deprecating Pydantic v1\n-[USER_REDACTED]_pydanticv1\n-def test_post_body_json(client: TestClient):\n- response = client.post(\"/login/\", json={\"username\": \"Foo\", \"password\": \"secret\"})\n- assert response.status_code == 422, response.text\n- assert response.json() == {\n- \"detail\": [\n- {\n- \"type\": \"value_error.missing\",\n- \"loc\": [\"body\", \"username\"],\n- \"msg\": \"field required\",\n- },\n- {\n- \"type\": \"value_error.missing\",\n- \"loc\": [\"body\", \"password\"],\n- \"msg\": \"field required\",\n- },\n- ]\n- }\n-\n-\n-# TODO: remove when deprecating Pydantic v1\n-[USER_REDACTED]_pydanticv1\n-def test_openapi_schema(client: TestClient):\n- response = client.get(\"/openapi.json\")\n- assert response.status_code == 200, response.text\n- assert response.json() == {\n- \"openapi\": \"3.1.0\",\n- \"info\": {\"title\": \"FastAPI\", \"version\": \"0.1.0\"},\n- \"paths\": {\n- \"/login/\": {\n- \"post\": {\n- \"responses\": {\n- \"200\": {\n- \"description\": \"[NAME_REDACTED]\",\n- \"content\": {\"application/json\": {\"schema\": {}}},\n- },\n- \"422\": {\n- \"description\": \"[NAME_REDACTED]\",\n- \"content\": {\n- \"application/json\": {\n- \"schema\": {\n- \"$ref\": \"#/components/schemas/HTTPValidationError\"\n- }\n- }\n- },\n- },\n- },\n- \"summary\": \"Login\",\n- \"operationId\": \"login_login__post\",\n- \"requestBody\": {\n- \"content\": {\n- \"application/x-www-form-urlencoded\": {\n- \"schema\": {\"$ref\": \"#/components/schemas/FormData\"}\n- }\n- },\n- \"required\": True,\n- },\n- }\n- }\n- },\n- \"components\": {\n- \"schemas\": {\n- \"FormData\": {\n- \"properties\": {\n- \"username\": {\"type\": \"string\", \"title\": \"Username\"},\n- \"password\": {\"type\": \"string\", \"title\": \"Password\"},\n- },\n- \"additionalProperties\": False,\n- \"type\": \"object\",\n- \"required\": [\"username\", \"password\"],\n- \"title\": \"FormData\",\n- },\n- \"ValidationError\": {\n- \"title\": \"ValidationError\",\n- \"required\": [\"loc\", \"msg\", \"type\"],\n- \"type\": \"object\",\n- \"properties\": {\n- \"loc\": {\n- \"title\": \"Location\",\n- \"type\": \"array\",\n- \"items\": {\n- \"anyOf\": [{\"type\": \"string\"}, {\"type\": \"integer\"}]\n- },\n- },\n- \"msg\": {\"title\": \"Message\", \"type\": \"string\"},\n- \"type\": {\"title\": \"[NAME_REDACTED]\", \"type\": \"string\"},\n- },\n- },\n- \"HTTPValidationError\": {\n- \"title\": \"HTTPValidationError\",\n- \"type\": \"object\",\n- \"properties\": {\n- \"detail\": {\n- \"title\": \"Detail\",\n- \"type\": \"array\",\n- \"items\": {\"$ref\": \"#/components/schemas/ValidationError\"},\n- }\n- },\n- },\n- }\n- },\n- }" }, { "filename": "tests/test_tutorial/test_request_form_models/test_tutorial002_pv1_an_p39.py", "status": "removed", "additions": 0, "deletions": 203, "changes": 203, "patch": "@@ -1,203 +0,0 @@\n-import pytest\n-from fastapi.testclient import TestClient\n-\n-from tests.utils import needs_py39, needs_pydanticv1\n-\n-\n-[USER_REDACTED].fixture(name=\"client\")\n-def get_client():\n- from docs_src.request_form_models.tutorial002_pv1_an_py39 import app\n-\n- client = TestClient(app)\n- return client\n-\n-\n-# TODO: remove when deprecating Pydantic v1\n-[USER_REDACTED]_pydanticv1\n-[USER_REDACTED]_py39\n-def test_post_body_form(client: TestClient):\n- response = client.post(\"/login/\", data={\"username\": \"Foo\", \"password\": \"secret\"})\n- assert response.status_code == 200\n- assert response.json() == {\"username\": \"Foo\", \"password\": \"secret\"}\n-\n-\n-# TODO: remove when deprecating Pydantic v1\n-[USER_REDACTED]_pydanticv1\n-[USER_REDACTED]_py39\n-def test_post_body_extra_form(client: TestClient):\n- response = client.post(\n- \"/login/\", data={\"username\": \"Foo\", \"password\": \"secret\", \"extra\": \"extra\"}\n- )\n- assert response.status_code == 422\n- assert response.json() == {\n- \"detail\": [\n- {\n- \"type\": \"value_error.extra\",\n- \"loc\": [\"body\", \"extra\"],\n- \"msg\": \"extra fields not permitted\",\n- }\n- ]\n- }\n-\n-\n-# TODO: remove when deprecating Pydantic v1\n-[USER_REDACTED]_pydanticv1\n-[USER_REDACTED]_py39\n-def test_post_body_form_no_password(client: TestClient):\n- response = client.post(\"/login/\", data={\"username\": \"Foo\"})\n- assert response.status_code == 422\n- assert response.json() == {\n- \"detail\": [\n- {\n- \"type\": \"value_error.missing\",\n- \"loc\": [\"body\", \"password\"],\n- \"msg\": \"field required\",\n- }\n- ]\n- }\n-\n-\n-# TODO: remove when deprecating Pydantic v1\n-[USER_REDACTED]_pydanticv1\n-[USER_REDACTED]_py39\n-def test_post_body_form_no_username(client: TestClient):\n- response = client.post(\"/login/\", data={\"password\": \"secret\"})\n- assert response.status_code == 422\n- assert response.json() == {\n- \"detail\": [\n- {\n- \"type\": \"value_error.missing\",\n- \"loc\": [\"body\", \"username\"],\n- \"msg\": \"field required\",\n- }\n- ]\n- }\n-\n-\n-# TODO: remove when deprecating Pydantic v1\n-[USER_REDACTED]_pydanticv1\n-[USER_REDACTED]_py39\n-def test_post_body_form_no_data(client: TestClient):\n- response = client.post(\"/login/\")\n- assert response.status_code == 422\n- assert response.json() == {\n- \"detail\": [\n- {\n- \"type\": \"value_error.missing\",\n- \"loc\": [\"body\", \"username\"],\n- \"msg\": \"field required\",\n- },\n- {\n- \"type\": \"value_error.missing\",\n- \"loc\": [\"body\", \"password\"],\n- \"msg\": \"field required\",\n- },\n- ]\n- }\n-\n-\n-# TODO: remove when deprecating Pydantic v1\n-[USER_REDACTED]_pydanticv1\n-[USER_REDACTED]_py39\n-def test_post_body_json(client: TestClient):\n- response = client.post(\"/login/\", json={\"username\": \"Foo\", \"password\": \"secret\"})\n- assert response.status_code == 422, response.text\n- assert response.json() == {\n- \"detail\": [\n- {\n- \"type\": \"value_error.missing\",\n- \"loc\": [\"body\", \"username\"],\n- \"msg\": \"field required\",\n- },\n- {\n- \"type\": \"value_error.missing\",\n- \"loc\": [\"body\", \"password\"],\n- \"msg\": \"field required\",\n- },\n- ]\n- }\n-\n-\n-# TODO: remove when deprecating Pydantic v1\n-[USER_REDACTED]_pydanticv1\n-[USER_REDACTED]_py39\n-def test_openapi_schema(client: TestClient):\n- response = client.get(\"/openapi.json\")\n- assert response.status_code == 200, response.text\n- assert response.json() == {\n- \"openapi\": \"3.1.0\",\n- \"info\": {\"title\": \"FastAPI\", \"version\": \"0.1.0\"},\n- \"paths\": {\n- \"/login/\": {\n- \"post\": {\n- \"responses\": {\n- \"200\": {\n- \"description\": \"[NAME_REDACTED]\",\n- \"content\": {\"application/json\": {\"schema\": {}}},\n- },\n- \"422\": {\n- \"description\": \"[NAME_REDACTED]\",\n- \"content\": {\n- \"application/json\": {\n- \"schema\": {\n- \"$ref\": \"#/components/schemas/HTTPValidationError\"\n- }\n- }\n- },\n- },\n- },\n- \"summary\": \"Login\",\n- \"operationId\": \"login_login__post\",\n- \"requestBody\": {\n- \"content\": {\n- \"application/x-www-form-urlencoded\": {\n- \"schema\": {\"$ref\": \"#/components/schemas/FormData\"}\n- }\n- },\n- \"required\": True,\n- },\n- }\n- }\n- },\n- \"components\": {\n- \"schemas\": {\n- \"FormData\": {\n- \"properties\": {\n- \"username\": {\"type\": \"string\", \"title\": \"Username\"},\n- \"password\": {\"type\": \"string\", \"title\": \"Password\"},\n- },\n- \"additionalProperties\": False,\n- \"type\": \"object\",\n- \"required\": [\"username\", \"password\"],\n- \"title\": \"FormData\",\n- },\n- \"ValidationError\": {\n- \"title\": \"ValidationError\",\n- \"required\": [\"loc\", \"msg\", \"type\"],\n- \"type\": \"object\",\n- \"properties\": {\n- \"loc\": {\n- \"title\": \"Location\",\n- \"type\": \"array\",\n- \"items\": {\n- \"anyOf\": [{\"type\": \"string\"}, {\"type\": \"integer\"}]\n- },\n- },\n- \"msg\": {\"title\": \"Message\", \"type\": \"string\"},\n- \"type\": {\"title\": \"[NAME_REDACTED]\", \"type\": \"string\"},\n- },\n- },\n- \"HTTPValidationError\": {\n- \"title\": \"HTTPValidationError\",\n- \"type\": \"object\",\n- \"properties\": {\n- \"detail\": {\n- \"title\": \"Detail\",\n- \"type\": \"array\",\n- \"items\": {\"$ref\": \"#/components/schemas/ValidationError\"},\n- }\n- },\n- },\n- }\n- },\n- }" } ], "reviews": [ { "id": 2542534726, "user": "user_84458f05cf3c", "state": "COMMENTED", "body": null, "submitted_at": "2025-01-10T14:10:32+00:00" }, { "id": 2546478670, "user": "user_84458f05cf3c", "state": "COMMENTED", "body": null, "submitted_at": "2025-01-13T12:28:12+00:00" }, { "id": 2546735427, "user": "user_84458f05cf3c", "state": "APPROVED", "body": null, "submitted_at": "2025-01-13T14:12:36+00:00" }, { "id": 2561106914, "user": "user_2a237e38e06b", "state": "APPROVED", "body": null, "submitted_at": "2025-01-19T22:38:39+00:00" } ], "review_comments": [ { "id": 1910427984, "user": "user_84458f05cf3c", "body": "Shouldn't this be a relative import?\n(same comment in the other 2 files)", "path": "tests/test_tutorial/test_request_form_models/test_tutorial001.py", "line": null, "side": "RIGHT", "created_at": "2025-01-10T14:10:32+00:00" }, { "id": 1913113718, "user": "user_84458f05cf3c", "body": "```suggestion\nfrom ...utils import needs_py39, needs_pydanticv2\n```", "path": "tests/test_tutorial/test_request_form_models/test_tutorial002.py", "line": null, "side": "RIGHT", "created_at": "2025-01-13T12:27:47+00:00" }, { "id": 1913114305, "user": "user_84458f05cf3c", "body": "```suggestion\nfrom ...utils import needs_py39, needs_pydanticv1\n```", "path": "tests/test_tutorial/test_request_form_models/test_tutorial002_pv1.py", "line": null, "side": "RIGHT", "created_at": "2025-01-13T12:28:02+00:00" } ], "meta": { "languages": [ "py" ], "touches_tests": true, "review_state_summary": { "COMMENTED": 2, "APPROVED": 2 }, "meaningful_comment_count": 3, "has_approval": true, "has_changes_requested": false, "total_review_comments": 3 } } { "_id": "7d35c8e216b45b92", "_schema_version": "1.0", "_cleaned_at": "2026-02-12T07:46:52.226800+00:00", "repo": "tiangolo/fastapi", "repo_url": "https://github.com/fastapi/fastapi", "license_name": "MIT License", "license_spdx": "MIT", "pr_number": 13179, "title": "✅ Simplify tests for header_params", "body": "#13150", "author": "user_568843bce6ca", "created_at": "2025-01-08T15:16:39+00:00", "merged_at": "2025-01-19T06:32:12+00:00", "base_branch": "master", "head_branch": "tests-header-params", "additions": 64, "deletions": 1286, "changed_files": 14, "files": [ { "filename": "tests/test_tutorial/test_header_params/test_tutorial001.py", "status": "modified", "additions": 20, "deletions": 4, "changes": 24, "patch": "@@ -1,10 +1,26 @@\n+import importlib\n+\n import pytest\n from dirty_equals import IsDict\n from fastapi.testclient import TestClient\n \n-from docs_src.header_params.tutorial001 import app\n+from ...utils import needs_py310\n+\n+\n+[USER_REDACTED].fixture(\n+ name=\"client\",\n+ params=[\n+ \"tutorial001\",\n+ pytest.param(\"tutorial001_py310\", marks=needs_py310),\n+ \"tutorial001_an\",\n+ pytest.param(\"tutorial001_an_py310\", marks=needs_py310),\n+ ],\n+)\n+def get_client(request: pytest.FixtureRequest):\n+ mod = importlib.import_module(f\"docs_src.header_params.{request.param}\")\n \n-client = TestClient(app)\n+ client = TestClient(mod.app)\n+ return client\n \n \n [USER_REDACTED].mark.parametrize(\n@@ -15,13 +31,13 @@\n (\"/items\", {\"User-Agent\": \"FastAPI test\"}, 200, {\"User-Agent\": \"FastAPI test\"}),\n ],\n )\n-def test(path, headers, expected_status, expected_response):\n+def test(path, headers, expected_status, expected_response, client: TestClient):\n response = client.get(path, headers=headers)\n assert response.status_code == expected_status\n assert response.json() == expected_response\n \n \n-def test_openapi_schema():\n+def test_openapi_schema(client: TestClient):\n response = client.get(\"/openapi.json\")\n assert response.status_code == 200\n assert response.json() == {" }, { "filename": "tests/test_tutorial/test_header_params/test_tutorial001_an.py", "status": "removed", "additions": 0, "deletions": 102, "changes": 102, "patch": "@@ -1,102 +0,0 @@\n-import pytest\n-from dirty_equals import IsDict\n-from fastapi.testclient import TestClient\n-\n-from docs_src.header_params.tutorial001_an import app\n-\n-client = TestClient(app)\n-\n-\n-[USER_REDACTED].mark.parametrize(\n- \"path,headers,expected_status,expected_response\",\n- [\n- (\"/items\", None, 200, {\"User-Agent\": \"testclient\"}),\n- (\"/items\", {\"X-Header\": \"notvalid\"}, 200, {\"User-Agent\": \"testclient\"}),\n- (\"/items\", {\"User-Agent\": \"FastAPI test\"}, 200, {\"User-Agent\": \"FastAPI test\"}),\n- ],\n-)\n-def test(path, headers, expected_status, expected_response):\n- response = client.get(path, headers=headers)\n- assert response.status_code == expected_status\n- assert response.json() == expected_response\n-\n-\n-def test_openapi_schema():\n- response = client.get(\"/openapi.json\")\n- assert response.status_code == 200\n- assert response.json() == {\n- \"openapi\": \"3.1.0\",\n- \"info\": {\"title\": \"FastAPI\", \"version\": \"0.1.0\"},\n- \"paths\": {\n- \"/items/\": {\n- \"get\": {\n- \"responses\": {\n- \"200\": {\n- \"description\": \"[NAME_REDACTED]\",\n- \"content\": {\"application/json\": {\"schema\": {}}},\n- },\n- \"422\": {\n- \"description\": \"[NAME_REDACTED]\",\n- \"content\": {\n- \"application/json\": {\n- \"schema\": {\n- \"$ref\": \"#/components/schemas/HTTPValidationError\"\n- }\n- }\n- },\n- },\n- },\n- \"summary\": \"[NAME_REDACTED]\",\n- \"operationId\": \"read_items_items__get\",\n- \"parameters\": [\n- {\n- \"required\": False,\n- \"schema\": IsDict(\n- {\n- \"anyOf\": [{\"type\": \"string\"}, {\"type\": \"null\"}],\n- \"title\": \"User-Agent\",\n- }\n- )\n- | IsDict(\n- # TODO: remove when deprecating Pydantic v1\n- {\"title\": \"User-Agent\", \"type\": \"string\"}\n- ),\n- \"name\": \"user-agent\",\n- \"in\": \"header\",\n- }\n- ],\n- }\n- }\n- },\n- \"components\": {\n- \"schemas\": {\n- \"ValidationError\": {\n- \"title\": \"ValidationError\",\n- \"required\": [\"loc\", \"msg\", \"type\"],\n- \"type\": \"object\",\n- \"properties\": {\n- \"loc\": {\n- \"title\": \"Location\",\n- \"type\": \"array\",\n- \"items\": {\n- \"anyOf\": [{\"type\": \"string\"}, {\"type\": \"integer\"}]\n- },\n- },\n- \"msg\": {\"title\": \"Message\", \"type\": \"string\"},\n- \"type\": {\"title\": \"[NAME_REDACTED]\", \"type\": \"string\"},\n- },\n- },\n- \"HTTPValidationError\": {\n- \"title\": \"HTTPValidationError\",\n- \"type\": \"object\",\n- \"properties\": {\n- \"detail\": {\n- \"title\": \"Detail\",\n- \"type\": \"array\",\n- \"items\": {\"$ref\": \"#/components/schemas/ValidationError\"},\n- }\n- },\n- },\n- }\n- },\n- }" }, { "filename": "tests/test_tutorial/test_header_params/test_tutorial001_an_py310.py", "status": "removed", "additions": 0, "deletions": 110, "changes": 110, "patch": "@@ -1,110 +0,0 @@\n-import pytest\n-from dirty_equals import IsDict\n-from fastapi.testclient import TestClient\n-\n-from ...utils import needs_py310\n-\n-\n-[USER_REDACTED].fixture(name=\"client\")\n-def get_client():\n- from docs_src.header_params.tutorial001_an_py310 import app\n-\n- client = TestClient(app)\n- return client\n-\n-\n-[USER_REDACTED]_py310\n-[USER_REDACTED].mark.parametrize(\n- \"path,headers,expected_status,expected_response\",\n- [\n- (\"/items\", None, 200, {\"User-Agent\": \"testclient\"}),\n- (\"/items\", {\"X-Header\": \"notvalid\"}, 200, {\"User-Agent\": \"testclient\"}),\n- (\"/items\", {\"User-Agent\": \"FastAPI test\"}, 200, {\"User-Agent\": \"FastAPI test\"}),\n- ],\n-)\n-def test(path, headers, expected_status, expected_response, client: TestClient):\n- response = client.get(path, headers=headers)\n- assert response.status_code == expected_status\n- assert response.json() == expected_response\n-\n-\n-[USER_REDACTED]_py310\n-def test_openapi_schema(client: TestClient):\n- response = client.get(\"/openapi.json\")\n- assert response.status_code == 200\n- assert response.json() == {\n- \"openapi\": \"3.1.0\",\n- \"info\": {\"title\": \"FastAPI\", \"version\": \"0.1.0\"},\n- \"paths\": {\n- \"/items/\": {\n- \"get\": {\n- \"responses\": {\n- \"200\": {\n- \"description\": \"[NAME_REDACTED]\",\n- \"content\": {\"application/json\": {\"schema\": {}}},\n- },\n- \"422\": {\n- \"description\": \"[NAME_REDACTED]\",\n- \"content\": {\n- \"application/json\": {\n- \"schema\": {\n- \"$ref\": \"#/components/schemas/HTTPValidationError\"\n- }\n- }\n- },\n- },\n- },\n- \"summary\": \"[NAME_REDACTED]\",\n- \"operationId\": \"read_items_items__get\",\n- \"parameters\": [\n- {\n- \"required\": False,\n- \"schema\": IsDict(\n- {\n- \"anyOf\": [{\"type\": \"string\"}, {\"type\": \"null\"}],\n- \"title\": \"User-Agent\",\n- }\n- )\n- | IsDict(\n- # TODO: remove when deprecating Pydantic v1\n- {\"title\": \"User-Agent\", \"type\": \"string\"}\n- ),\n- \"name\": \"user-agent\",\n- \"in\": \"header\",\n- }\n- ],\n- }\n- }\n- },\n- \"components\": {\n- \"schemas\": {\n- \"ValidationError\": {\n- \"title\": \"ValidationError\",\n- \"required\": [\"loc\", \"msg\", \"type\"],\n- \"type\": \"object\",\n- \"properties\": {\n- \"loc\": {\n- \"title\": \"Location\",\n- \"type\": \"array\",\n- \"items\": {\n- \"anyOf\": [{\"type\": \"string\"}, {\"type\": \"integer\"}]\n- },\n- },\n- \"msg\": {\"title\": \"Message\", \"type\": \"string\"},\n- \"type\": {\"title\": \"[NAME_REDACTED]\", \"type\": \"string\"},\n- },\n- },\n- \"HTTPValidationError\": {\n- \"title\": \"HTTPValidationError\",\n- \"type\": \"object\",\n- \"properties\": {\n- \"detail\": {\n- \"title\": \"Detail\",\n- \"type\": \"array\",\n- \"items\": {\"$ref\": \"#/components/schemas/ValidationError\"},\n- }\n- },\n- },\n- }\n- },\n- }" }, { "filename": "tests/test_tutorial/test_header_params/test_tutorial001_py310.py", "status": "removed", "additions": 0, "deletions": 110, "changes": 110, "patch": "@@ -1,110 +0,0 @@\n-import pytest\n-from dirty_equals import IsDict\n-from fastapi.testclient import TestClient\n-\n-from ...utils import needs_py310\n-\n-\n-[USER_REDACTED].fixture(name=\"client\")\n-def get_client():\n- from docs_src.header_params.tutorial001_py310 import app\n-\n- client = TestClient(app)\n- return client\n-\n-\n-[USER_REDACTED]_py310\n-[USER_REDACTED].mark.parametrize(\n- \"path,headers,expected_status,expected_response\",\n- [\n- (\"/items\", None, 200, {\"User-Agent\": \"testclient\"}),\n- (\"/items\", {\"X-Header\": \"notvalid\"}, 200, {\"User-Agent\": \"testclient\"}),\n- (\"/items\", {\"User-Agent\": \"FastAPI test\"}, 200, {\"User-Agent\": \"FastAPI test\"}),\n- ],\n-)\n-def test(path, headers, expected_status, expected_response, client: TestClient):\n- response = client.get(path, headers=headers)\n- assert response.status_code == expected_status\n- assert response.json() == expected_response\n-\n-\n-[USER_REDACTED]_py310\n-def test_openapi_schema(client: TestClient):\n- response = client.get(\"/openapi.json\")\n- assert response.status_code == 200\n- assert response.json() == {\n- \"openapi\": \"3.1.0\",\n- \"info\": {\"title\": \"FastAPI\", \"version\": \"0.1.0\"},\n- \"paths\": {\n- \"/items/\": {\n- \"get\": {\n- \"responses\": {\n- \"200\": {\n- \"description\": \"[NAME_REDACTED]\",\n- \"content\": {\"application/json\": {\"schema\": {}}},\n- },\n- \"422\": {\n- \"description\": \"[NAME_REDACTED]\",\n- \"content\": {\n- \"application/json\": {\n- \"schema\": {\n- \"$ref\": \"#/components/schemas/HTTPValidationError\"\n- }\n- }\n- },\n- },\n- },\n- \"summary\": \"[NAME_REDACTED]\",\n- \"operationId\": \"read_items_items__get\",\n- \"parameters\": [\n- {\n- \"required\": False,\n- \"schema\": IsDict(\n- {\n- \"anyOf\": [{\"type\": \"string\"}, {\"type\": \"null\"}],\n- \"title\": \"User-Agent\",\n- }\n- )\n- | IsDict(\n- # TODO: remove when deprecating Pydantic v1\n- {\"title\": \"User-Agent\", \"type\": \"string\"}\n- ),\n- \"name\": \"user-agent\",\n- \"in\": \"header\",\n- }\n- ],\n- }\n- }\n- },\n- \"components\": {\n- \"schemas\": {\n- \"ValidationError\": {\n- \"title\": \"ValidationError\",\n- \"required\": [\"loc\", \"msg\", \"type\"],\n- \"type\": \"object\",\n- \"properties\": {\n- \"loc\": {\n- \"title\": \"Location\",\n- \"type\": \"array\",\n- \"items\": {\n- \"anyOf\": [{\"type\": \"string\"}, {\"type\": \"integer\"}]\n- },\n- },\n- \"msg\": {\"title\": \"Message\", \"type\": \"string\"},\n- \"type\": {\"title\": \"[NAME_REDACTED]\", \"type\": \"string\"},\n- },\n- },\n- \"HTTPValidationError\": {\n- \"title\": \"HTTPValidationError\",\n- \"type\": \"object\",\n- \"properties\": {\n- \"detail\": {\n- \"title\": \"Detail\",\n- \"type\": \"array\",\n- \"items\": {\"$ref\": \"#/components/schemas/ValidationError\"},\n- }\n- },\n- },\n- }\n- },\n- }" }, { "filename": "tests/test_tutorial/test_header_params/test_tutorial002.py", "status": "modified", "additions": 21, "deletions": 4, "changes": 25, "patch": "@@ -1,10 +1,27 @@\n+import importlib\n+\n import pytest\n from dirty_equals import IsDict\n from fastapi.testclient import TestClient\n \n-from docs_src.header_params.tutorial002 import app\n+from ...utils import needs_py39, needs_py310\n+\n+\n+[USER_REDACTED].fixture(\n+ name=\"client\",\n+ params=[\n+ \"tutorial002\",\n+ pytest.param(\"tutorial002_py310\", marks=needs_py310),\n+ \"tutorial002_an\",\n+ pytest.param(\"tutorial002_an_py39\", marks=needs_py39),\n+ pytest.param(\"tutorial002_an_py310\", marks=needs_py310),\n+ ],\n+)\n+def get_client(request: pytest.FixtureRequest):\n+ mod = importlib.import_module(f\"docs_src.header_params.{request.param}\")\n \n-client = TestClient(app)\n+ client = TestClient(mod.app)\n+ return client\n \n \n [USER_REDACTED].mark.parametrize(\n@@ -26,13 +43,13 @@\n ),\n ],\n )\n-def test(path, headers, expected_status, expected_response):\n+def test(path, headers, expected_status, expected_response, client: TestClient):\n response = client.get(path, headers=headers)\n assert response.status_code == expected_status\n assert response.json() == expected_response\n \n \n-def test_openapi_schema():\n+def test_openapi_schema(client: TestClient):\n response = client.get(\"/openapi.json\")\n assert response.status_code == 200\n assert response.json() == {" }, { "filename": "tests/test_tutorial/test_header_params/test_tutorial002_an.py", "status": "removed", "additions": 0, "deletions": 113, "changes": 113, "patch": "@@ -1,113 +0,0 @@\n-import pytest\n-from dirty_equals import IsDict\n-from fastapi.testclient import TestClient\n-\n-from docs_src.header_params.tutorial002_an import app\n-\n-client = TestClient(app)\n-\n-\n-[USER_REDACTED].mark.parametrize(\n- \"path,headers,expected_status,expected_response\",\n- [\n- (\"/items\", None, 200, {\"strange_header\": None}),\n- (\"/items\", {\"X-Header\": \"notvalid\"}, 200, {\"strange_header\": None}),\n- (\n- \"/items\",\n- {\"strange_header\": \"FastAPI test\"},\n- 200,\n- {\"strange_header\": \"FastAPI test\"},\n- ),\n- (\n- \"/items\",\n- {\"strange-header\": \"Not really underscore\"},\n- 200,\n- {\"strange_header\": None},\n- ),\n- ],\n-)\n-def test(path, headers, expected_status, expected_response):\n- response = client.get(path, headers=headers)\n- assert response.status_code == expected_status\n- assert response.json() == expected_response\n-\n-\n-def test_openapi_schema():\n- response = client.get(\"/openapi.json\")\n- assert response.status_code == 200\n- assert response.json() == {\n- \"openapi\": \"3.1.0\",\n- \"info\": {\"title\": \"FastAPI\", \"version\": \"0.1.0\"},\n- \"paths\": {\n- \"/items/\": {\n- \"get\": {\n- \"responses\": {\n- \"200\": {\n- \"description\": \"[NAME_REDACTED]\",\n- \"content\": {\"application/json\": {\"schema\": {}}},\n- },\n- \"422\": {\n- \"description\": \"[NAME_REDACTED]\",\n- \"content\": {\n- \"application/json\": {\n- \"schema\": {\n- \"$ref\": \"#/components/schemas/HTTPValidationError\"\n- }\n- }\n- },\n- },\n- },\n- \"summary\": \"[NAME_REDACTED]\",\n- \"operationId\": \"read_items_items__get\",\n- \"parameters\": [\n- {\n- \"required\": False,\n- \"schema\": IsDict(\n- {\n- \"anyOf\": [{\"type\": \"string\"}, {\"type\": \"null\"}],\n- \"title\": \"[NAME_REDACTED]\",\n- }\n- )\n- | IsDict(\n- # TODO: remove when deprecating Pydantic v1\n- {\"title\": \"[NAME_REDACTED]\", \"type\": \"string\"}\n- ),\n- \"name\": \"strange_header\",\n- \"in\": \"header\",\n- }\n- ],\n- }\n- }\n- },\n- \"components\": {\n- \"schemas\": {\n- \"ValidationError\": {\n- \"title\": \"ValidationError\",\n- \"required\": [\"loc\", \"msg\", \"type\"],\n- \"type\": \"object\",\n- \"properties\": {\n- \"loc\": {\n- \"title\": \"Location\",\n- \"type\": \"array\",\n- \"items\": {\n- \"anyOf\": [{\"type\": \"string\"}, {\"type\": \"integer\"}]\n- },\n- },\n- \"msg\": {\"title\": \"Message\", \"type\": \"string\"},\n- \"type\": {\"title\": \"[NAME_REDACTED]\", \"type\": \"string\"},\n- },\n- },\n- \"HTTPValidationError\": {\n- \"title\": \"HTTPValidationError\",\n- \"type\": \"object\",\n- \"properties\": {\n- \"detail\": {\n- \"title\": \"Detail\",\n- \"type\": \"array\",\n- \"items\": {\"$ref\": \"#/components/schemas/ValidationError\"},\n- }\n- },\n- },\n- }\n- },\n- }" }, { "filename": "tests/test_tutorial/test_header_params/test_tutorial002_an_py310.py", "status": "removed", "additions": 0, "deletions": 121, "changes": 121, "patch": "@@ -1,121 +0,0 @@\n-import pytest\n-from dirty_equals import IsDict\n-from fastapi.testclient import TestClient\n-\n-from ...utils import needs_py310\n-\n-\n-[USER_REDACTED].fixture(name=\"client\")\n-def get_client():\n- from docs_src.header_params.tutorial002_an_py310 import app\n-\n- client = TestClient(app)\n- return client\n-\n-\n-[USER_REDACTED]_py310\n-[USER_REDACTED].mark.parametrize(\n- \"path,headers,expected_status,expected_response\",\n- [\n- (\"/items\", None, 200, {\"strange_header\": None}),\n- (\"/items\", {\"X-Header\": \"notvalid\"}, 200, {\"strange_header\": None}),\n- (\n- \"/items\",\n- {\"strange_header\": \"FastAPI test\"},\n- 200,\n- {\"strange_header\": \"FastAPI test\"},\n- ),\n- (\n- \"/items\",\n- {\"strange-header\": \"Not really underscore\"},\n- 200,\n- {\"strange_header\": None},\n- ),\n- ],\n-)\n-def test(path, headers, expected_status, expected_response, client: TestClient):\n- response = client.get(path, headers=headers)\n- assert response.status_code == expected_status\n- assert response.json() == expected_response\n-\n-\n-[USER_REDACTED]_py310\n-def test_openapi_schema(client: TestClient):\n- response = client.get(\"/openapi.json\")\n- assert response.status_code == 200\n- assert response.json() == {\n- \"openapi\": \"3.1.0\",\n- \"info\": {\"title\": \"FastAPI\", \"version\": \"0.1.0\"},\n- \"paths\": {\n- \"/items/\": {\n- \"get\": {\n- \"responses\": {\n- \"200\": {\n- \"description\": \"[NAME_REDACTED]\",\n- \"content\": {\"application/json\": {\"schema\": {}}},\n- },\n- \"422\": {\n- \"description\": \"[NAME_REDACTED]\",\n- \"content\": {\n- \"application/json\": {\n- \"schema\": {\n- \"$ref\": \"#/components/schemas/HTTPValidationError\"\n- }\n- }\n- },\n- },\n- },\n- \"summary\": \"[NAME_REDACTED]\",\n- \"operationId\": \"read_items_items__get\",\n- \"parameters\": [\n- {\n- \"required\": False,\n- \"schema\": IsDict(\n- {\n- \"anyOf\": [{\"type\": \"string\"}, {\"type\": \"null\"}],\n- \"title\": \"[NAME_REDACTED]\",\n- }\n- )\n- | IsDict(\n- # TODO: remove when deprecating Pydantic v1\n- {\"title\": \"[NAME_REDACTED]\", \"type\": \"string\"}\n- ),\n- \"name\": \"strange_header\",\n- \"in\": \"header\",\n- }\n- ],\n- }\n- }\n- },\n- \"components\": {\n- \"schemas\": {\n- \"ValidationError\": {\n- \"title\": \"ValidationError\",\n- \"required\": [\"loc\", \"msg\", \"type\"],\n- \"type\": \"object\",\n- \"properties\": {\n- \"loc\": {\n- \"title\": \"Location\",\n- \"type\": \"array\",\n- \"items\": {\n- \"anyOf\": [{\"type\": \"string\"}, {\"type\": \"integer\"}]\n- },\n- },\n- \"msg\": {\"title\": \"Message\", \"type\": \"string\"},\n- \"type\": {\"title\": \"[NAME_REDACTED]\", \"type\": \"string\"},\n- },\n- },\n- \"HTTPValidationError\": {\n- \"title\": \"HTTPValidationError\",\n- \"type\": \"object\",\n- \"properties\": {\n- \"detail\": {\n- \"title\": \"Detail\",\n- \"type\": \"array\",\n- \"items\": {\"$ref\": \"#/components/schemas/ValidationError\"},\n- }\n- },\n- },\n- }\n- },\n- }" }, { "filename": "tests/test_tutorial/test_header_params/test_tutorial002_an_py39.py", "status": "removed", "additions": 0, "deletions": 124, "changes": 124, "patch": "@@ -1,124 +0,0 @@\n-import pytest\n-from dirty_equals import IsDict\n-from fastapi.testclient import TestClient\n-\n-from ...utils import needs_py39\n-\n-\n-[USER_REDACTED].fixture(name=\"client\")\n-def get_client():\n- from docs_src.header_params.tutorial002_an_py39 import app\n-\n- client = TestClient(app)\n- return client\n-\n-\n-[USER_REDACTED]_py39\n-[USER_REDACTED].mark.parametrize(\n- \"path,headers,expected_status,expected_response\",\n- [\n- (\"/items\", None, 200, {\"strange_header\": None}),\n- (\"/items\", {\"X-Header\": \"notvalid\"}, 200, {\"strange_header\": None}),\n- (\n- \"/items\",\n- {\"strange_header\": \"FastAPI test\"},\n- 200,\n- {\"strange_header\": \"FastAPI test\"},\n- ),\n- (\n- \"/items\",\n- {\"strange-header\": \"Not really underscore\"},\n- 200,\n- {\"strange_header\": None},\n- ),\n- ],\n-)\n-def test(path, headers, expected_status, expected_response, client: TestClient):\n- response = client.get(path, headers=headers)\n- assert response.status_code == expected_status\n- assert response.json() == expected_response\n-\n-\n-[USER_REDACTED]_py39\n-def test_openapi_schema():\n- from docs_src.header_params.tutorial002_an_py39 import app\n-\n- client = TestClient(app)\n- response = client.get(\"/openapi.json\")\n- assert response.status_code == 200\n- assert response.json() == {\n- \"openapi\": \"3.1.0\",\n- \"info\": {\"title\": \"FastAPI\", \"version\": \"0.1.0\"},\n- \"paths\": {\n- \"/items/\": {\n- \"get\": {\n- \"responses\": {\n- \"200\": {\n- \"description\": \"[NAME_REDACTED]\",\n- \"content\": {\"application/json\": {\"schema\": {}}},\n- },\n- \"422\": {\n- \"description\": \"[NAME_REDACTED]\",\n- \"content\": {\n- \"application/json\": {\n- \"schema\": {\n- \"$ref\": \"#/components/schemas/HTTPValidationError\"\n- }\n- }\n- },\n- },\n- },\n- \"summary\": \"[NAME_REDACTED]\",\n- \"operationId\": \"read_items_items__get\",\n- \"parameters\": [\n- {\n- \"required\": False,\n- \"schema\": IsDict(\n- {\n- \"anyOf\": [{\"type\": \"string\"}, {\"type\": \"null\"}],\n- \"title\": \"[NAME_REDACTED]\",\n- }\n- )\n- | IsDict(\n- # TODO: remove when deprecating Pydantic v1\n- {\"title\": \"[NAME_REDACTED]\", \"type\": \"string\"}\n- ),\n- \"name\": \"strange_header\",\n- \"in\": \"header\",\n- }\n- ],\n- }\n- }\n- },\n- \"components\": {\n- \"schemas\": {\n- \"ValidationError\": {\n- \"title\": \"ValidationError\",\n- \"required\": [\"loc\", \"msg\", \"type\"],\n- \"type\": \"object\",\n- \"properties\": {\n- \"loc\": {\n- \"title\": \"Location\",\n- \"type\": \"array\",\n- \"items\": {\n- \"anyOf\": [{\"type\": \"string\"}, {\"type\": \"integer\"}]\n- },\n- },\n- \"msg\": {\"title\": \"Message\", \"type\": \"string\"},\n- \"type\": {\"title\": \"[NAME_REDACTED]\", \"type\": \"string\"},\n- },\n- },\n- \"HTTPValidationError\": {\n- \"title\": \"HTTPValidationError\",\n- \"type\": \"object\",\n- \"properties\": {\n- \"detail\": {\n- \"title\": \"Detail\",\n- \"type\": \"array\",\n- \"items\": {\"$ref\": \"#/components/schemas/ValidationError\"},\n- }\n- },\n- },\n- }\n- },\n- }" }, { "filename": "tests/test_tutorial/test_header_params/test_tutorial002_py310.py", "status": "removed", "additions": 0, "deletions": 124, "changes": 124, "patch": "@@ -1,124 +0,0 @@\n-import pytest\n-from dirty_equals import IsDict\n-from fastapi.testclient import TestClient\n-\n-from ...utils import needs_py310\n-\n-\n-[USER_REDACTED].fixture(name=\"client\")\n-def get_client():\n- from docs_src.header_params.tutorial002_py310 import app\n-\n- client = TestClient(app)\n- return client\n-\n-\n-[USER_REDACTED]_py310\n-[USER_REDACTED].mark.parametrize(\n- \"path,headers,expected_status,expected_response\",\n- [\n- (\"/items\", None, 200, {\"strange_header\": None}),\n- (\"/items\", {\"X-Header\": \"notvalid\"}, 200, {\"strange_header\": None}),\n- (\n- \"/items\",\n- {\"strange_header\": \"FastAPI test\"},\n- 200,\n- {\"strange_header\": \"FastAPI test\"},\n- ),\n- (\n- \"/items\",\n- {\"strange-header\": \"Not really underscore\"},\n- 200,\n- {\"strange_header\": None},\n- ),\n- ],\n-)\n-def test(path, headers, expected_status, expected_response, client: TestClient):\n- response = client.get(path, headers=headers)\n- assert response.status_code == expected_status\n- assert response.json() == expected_response\n-\n-\n-[USER_REDACTED]_py310\n-def test_openapi_schema():\n- from docs_src.header_params.tutorial002_py310 import app\n-\n- client = TestClient(app)\n- response = client.get(\"/openapi.json\")\n- assert response.status_code == 200\n- assert response.json() == {\n- \"openapi\": \"3.1.0\",\n- \"info\": {\"title\": \"FastAPI\", \"version\": \"0.1.0\"},\n- \"paths\": {\n- \"/items/\": {\n- \"get\": {\n- \"responses\": {\n- \"200\": {\n- \"description\": \"[NAME_REDACTED]\",\n- \"content\": {\"application/json\": {\"schema\": {}}},\n- },\n- \"422\": {\n- \"description\": \"[NAME_REDACTED]\",\n- \"content\": {\n- \"application/json\": {\n- \"schema\": {\n- \"$ref\": \"#/components/schemas/HTTPValidationError\"\n- }\n- }\n- },\n- },\n- },\n- \"summary\": \"[NAME_REDACTED]\",\n- \"operationId\": \"read_items_items__get\",\n- \"parameters\": [\n- {\n- \"required\": False,\n- \"schema\": IsDict(\n- {\n- \"anyOf\": [{\"type\": \"string\"}, {\"type\": \"null\"}],\n- \"title\": \"[NAME_REDACTED]\",\n- }\n- )\n- | IsDict(\n- # TODO: remove when deprecating Pydantic v1\n- {\"title\": \"[NAME_REDACTED]\", \"type\": \"string\"}\n- ),\n- \"name\": \"strange_header\",\n- \"in\": \"header\",\n- }\n- ],\n- }\n- }\n- },\n- \"components\": {\n- \"schemas\": {\n- \"ValidationError\": {\n- \"title\": \"ValidationError\",\n- \"required\": [\"loc\", \"msg\", \"type\"],\n- \"type\": \"object\",\n- \"properties\": {\n- \"loc\": {\n- \"title\": \"Location\",\n- \"type\": \"array\",\n- \"items\": {\n- \"anyOf\": [{\"type\": \"string\"}, {\"type\": \"integer\"}]\n- },\n- },\n- \"msg\": {\"title\": \"Message\", \"type\": \"string\"},\n- \"type\": {\"title\": \"[NAME_REDACTED]\", \"type\": \"string\"},\n- },\n- },\n- \"HTTPValidationError\": {\n- \"title\": \"HTTPValidationError\",\n- \"type\": \"object\",\n- \"properties\": {\n- \"detail\": {\n- \"title\": \"Detail\",\n- \"type\": \"array\",\n- \"items\": {\"$ref\": \"#/components/schemas/ValidationError\"},\n- }\n- },\n- },\n- }\n- },\n- }" }, { "filename": "tests/test_tutorial/test_header_params/test_tutorial003.py", "status": "modified", "additions": 23, "deletions": 10, "changes": 33, "patch": "@@ -1,32 +1,45 @@\n+import importlib\n+\n import pytest\n from dirty_equals import IsDict\n from fastapi.testclient import TestClient\n \n-from docs_src.header_params.tutorial003 import app\n+from ...utils import needs_py39, needs_py310\n+\n+\n+[USER_REDACTED].fixture(\n+ name=\"client\",\n+ params=[\n+ \"tutorial003\",\n+ pytest.param(\"tutorial003_py310\", marks=needs_py310),\n+ \"tutorial003_an\",\n+ pytest.param(\"tutorial003_an_py39\", marks=needs_py39),\n+ pytest.param(\"tutorial003_an_py310\", marks=needs_py310),\n+ ],\n+)\n+def get_client(request: pytest.FixtureRequest):\n+ mod = importlib.import_module(f\"docs_src.header_params.{request.param}\")\n \n-client = TestClient(app)\n+ client = TestClient(mod.app)\n+ return client\n \n \n [USER_REDACTED].mark.parametrize(\n \"path,headers,expected_status,expected_response\",\n [\n (\"/items\", None, 200, {\"X-Token values\": None}),\n (\"/items\", {\"x-token\": \"foo\"}, 200, {\"X-Token values\": [\"foo\"]}),\n- (\n- \"/items\",\n- [(\"x-token\", \"foo\"), (\"x-token\", \"bar\")],\n- 200,\n- {\"X-Token values\": [\"foo\", \"bar\"]},\n- ),\n+ # TODO: fix this, is it a bug?\n+ # (\"/items\", [(\"x-token\", \"foo\"), (\"x-token\", \"bar\")], 200, {\"X-Token values\": [\"foo\", \"bar\"]}),\n ],\n )\n-def test(path, headers, expected_status, expected_response):\n+def test(path, headers, expected_status, expected_response, client: TestClient):\n response = client.get(path, headers=headers)\n assert response.status_code == expected_status\n assert response.json() == expected_response\n \n \n-def test_openapi_schema():\n+def test_openapi_schema(client: TestClient):\n response = client.get(\"/openapi.json\")\n assert response.status_code == 200\n assert response.json() == {" }, { "filename": "tests/test_tutorial/test_header_params/test_tutorial003_an.py", "status": "removed", "additions": 0, "deletions": 110, "changes": 110, "patch": "@@ -1,110 +0,0 @@\n-import pytest\n-from dirty_equals import IsDict\n-from fastapi.testclient import TestClient\n-\n-from docs_src.header_params.tutorial003_an import app\n-\n-client = TestClient(app)\n-\n-\n-[USER_REDACTED].mark.parametrize(\n- \"path,headers,expected_status,expected_response\",\n- [\n- (\"/items\", None, 200, {\"X-Token values\": None}),\n- (\"/items\", {\"x-token\": \"foo\"}, 200, {\"X-Token values\": [\"foo\"]}),\n- # TODO: fix this, is it a bug?\n- # (\"/items\", [(\"x-token\", \"foo\"), (\"x-token\", \"bar\")], 200, {\"X-Token values\": [\"foo\", \"bar\"]}),\n- ],\n-)\n-def test(path, headers, expected_status, expected_response):\n- response = client.get(path, headers=headers)\n- assert response.status_code == expected_status\n- assert response.json() == expected_response\n-\n-\n-def test_openapi_schema():\n- response = client.get(\"/openapi.json\")\n- assert response.status_code == 200\n- assert response.json() == {\n- \"openapi\": \"3.1.0\",\n- \"info\": {\"title\": \"FastAPI\", \"version\": \"0.1.0\"},\n- \"paths\": {\n- \"/items/\": {\n- \"get\": {\n- \"summary\": \"[NAME_REDACTED]\",\n- \"operationId\": \"read_items_items__get\",\n- \"parameters\": [\n- {\n- \"required\": False,\n- \"schema\": IsDict(\n- {\n- \"title\": \"X-Token\",\n- \"anyOf\": [\n- {\"type\": \"array\", \"items\": {\"type\": \"string\"}},\n- {\"type\": \"null\"},\n- ],\n- }\n- )\n- | IsDict(\n- # TODO: remove when deprecating Pydantic v1\n- {\n- \"title\": \"X-Token\",\n- \"type\": \"array\",\n- \"items\": {\"type\": \"string\"},\n- }\n- ),\n- \"name\": \"x-token\",\n- \"in\": \"header\",\n- }\n- ],\n- \"responses\": {\n- \"200\": {\n- \"description\": \"[NAME_REDACTED]\",\n- \"content\": {\"application/json\": {\"schema\": {}}},\n- },\n- \"422\": {\n- \"description\": \"[NAME_REDACTED]\",\n- \"content\": {\n- \"application/json\": {\n- \"schema\": {\n- \"$ref\": \"#/components/schemas/HTTPValidationError\"\n- }\n- }\n- },\n- },\n- },\n- }\n- }\n- },\n- \"components\": {\n- \"schemas\": {\n- \"HTTPValidationError\": {\n- \"title\": \"HTTPValidationError\",\n- \"type\": \"object\",\n- \"properties\": {\n- \"detail\": {\n- \"title\": \"Detail\",\n- \"type\": \"array\",\n- \"items\": {\"$ref\": \"#/components/schemas/ValidationError\"},\n- }\n- },\n- },\n- \"ValidationError\": {\n- \"title\": \"ValidationError\",\n- \"required\": [\"loc\", \"msg\", \"type\"],\n- \"type\": \"object\",\n- \"properties\": {\n- \"loc\": {\n- \"title\": \"Location\",\n- \"type\": \"array\",\n- \"items\": {\n- \"anyOf\": [{\"type\": \"string\"}, {\"type\": \"integer\"}]\n- },\n- },\n- \"msg\": {\"title\": \"Message\", \"type\": \"string\"},\n- \"type\": {\"title\": \"[NAME_REDACTED]\", \"type\": \"string\"},\n- },\n- },\n- }\n- },\n- }" }, { "filename": "tests/test_tutorial/test_header_params/test_tutorial003_an_py310.py", "status": "removed", "additions": 0, "deletions": 118, "changes": 118, "patch": "@@ -1,118 +0,0 @@\n-import pytest\n-from dirty_equals import IsDict\n-from fastapi.testclient import TestClient\n-\n-from ...utils import needs_py310\n-\n-\n-[USER_REDACTED].fixture(name=\"client\")\n-def get_client():\n- from docs_src.header_params.tutorial003_an_py310 import app\n-\n- client = TestClient(app)\n- return client\n-\n-\n-[USER_REDACTED]_py310\n-[USER_REDACTED].mark.parametrize(\n- \"path,headers,expected_status,expected_response\",\n- [\n- (\"/items\", None, 200, {\"X-Token values\": None}),\n- (\"/items\", {\"x-token\": \"foo\"}, 200, {\"X-Token values\": [\"foo\"]}),\n- # TODO: fix this, is it a bug?\n- # (\"/items\", [(\"x-token\", \"foo\"), (\"x-token\", \"bar\")], 200, {\"X-Token values\": [\"foo\", \"bar\"]}),\n- ],\n-)\n-def test(path, headers, expected_status, expected_response, client: TestClient):\n- response = client.get(path, headers=headers)\n- assert response.status_code == expected_status\n- assert response.json() == expected_response\n-\n-\n-[USER_REDACTED]_py310\n-def test_openapi_schema(client: TestClient):\n- response = client.get(\"/openapi.json\")\n- assert response.status_code == 200\n- assert response.json() == {\n- \"openapi\": \"3.1.0\",\n- \"info\": {\"title\": \"FastAPI\", \"version\": \"0.1.0\"},\n- \"paths\": {\n- \"/items/\": {\n- \"get\": {\n- \"summary\": \"[NAME_REDACTED]\",\n- \"operationId\": \"read_items_items__get\",\n- \"parameters\": [\n- {\n- \"required\": False,\n- \"schema\": IsDict(\n- {\n- \"title\": \"X-Token\",\n- \"anyOf\": [\n- {\"type\": \"array\", \"items\": {\"type\": \"string\"}},\n- {\"type\": \"null\"},\n- ],\n- }\n- )\n- | IsDict(\n- # TODO: remove when deprecating Pydantic v1\n- {\n- \"title\": \"X-Token\",\n- \"type\": \"array\",\n- \"items\": {\"type\": \"string\"},\n- }\n- ),\n- \"name\": \"x-token\",\n- \"in\": \"header\",\n- }\n- ],\n- \"responses\": {\n- \"200\": {\n- \"description\": \"[NAME_REDACTED]\",\n- \"content\": {\"application/json\": {\"schema\": {}}},\n- },\n- \"422\": {\n- \"description\": \"[NAME_REDACTED]\",\n- \"content\": {\n- \"application/json\": {\n- \"schema\": {\n- \"$ref\": \"#/components/schemas/HTTPValidationError\"\n- }\n- }\n- },\n- },\n- },\n- }\n- }\n- },\n- \"components\": {\n- \"schemas\": {\n- \"HTTPValidationError\": {\n- \"title\": \"HTTPValidationError\",\n- \"type\": \"object\",\n- \"properties\": {\n- \"detail\": {\n- \"title\": \"Detail\",\n- \"type\": \"array\",\n- \"items\": {\"$ref\": \"#/components/schemas/ValidationError\"},\n- }\n- },\n- },\n- \"ValidationError\": {\n- \"title\": \"ValidationError\",\n- \"required\": [\"loc\", \"msg\", \"type\"],\n- \"type\": \"object\",\n- \"properties\": {\n- \"loc\": {\n- \"title\": \"Location\",\n- \"type\": \"array\",\n- \"items\": {\n- \"anyOf\": [{\"type\": \"string\"}, {\"type\": \"integer\"}]\n- },\n- },\n- \"msg\": {\"title\": \"Message\", \"type\": \"string\"},\n- \"type\": {\"title\": \"[NAME_REDACTED]\", \"type\": \"string\"},\n- },\n- },\n- }\n- },\n- }" }, { "filename": "tests/test_tutorial/test_header_params/test_tutorial003_an_py39.py", "status": "removed", "additions": 0, "deletions": 118, "changes": 118, "patch": "@@ -1,118 +0,0 @@\n-import pytest\n-from dirty_equals import IsDict\n-from fastapi.testclient import TestClient\n-\n-from ...utils import needs_py39\n-\n-\n-[USER_REDACTED].fixture(name=\"client\")\n-def get_client():\n- from docs_src.header_params.tutorial003_an_py39 import app\n-\n- client = TestClient(app)\n- return client\n-\n-\n-[USER_REDACTED]_py39\n-[USER_REDACTED].mark.parametrize(\n- \"path,headers,expected_status,expected_response\",\n- [\n- (\"/items\", None, 200, {\"X-Token values\": None}),\n- (\"/items\", {\"x-token\": \"foo\"}, 200, {\"X-Token values\": [\"foo\"]}),\n- # TODO: fix this, is it a bug?\n- # (\"/items\", [(\"x-token\", \"foo\"), (\"x-token\", \"bar\")], 200, {\"X-Token values\": [\"foo\", \"bar\"]}),\n- ],\n-)\n-def test(path, headers, expected_status, expected_response, client: TestClient):\n- response = client.get(path, headers=headers)\n- assert response.status_code == expected_status\n- assert response.json() == expected_response\n-\n-\n-[USER_REDACTED]_py39\n-def test_openapi_schema(client: TestClient):\n- response = client.get(\"/openapi.json\")\n- assert response.status_code == 200\n- assert response.json() == {\n- \"openapi\": \"3.1.0\",\n- \"info\": {\"title\": \"FastAPI\", \"version\": \"0.1.0\"},\n- \"paths\": {\n- \"/items/\": {\n- \"get\": {\n- \"summary\": \"[NAME_REDACTED]\",\n- \"operationId\": \"read_items_items__get\",\n- \"parameters\": [\n- {\n- \"required\": False,\n- \"schema\": IsDict(\n- {\n- \"title\": \"X-Token\",\n- \"anyOf\": [\n- {\"type\": \"array\", \"items\": {\"type\": \"string\"}},\n- {\"type\": \"null\"},\n- ],\n- }\n- )\n- | IsDict(\n- # TODO: remove when deprecating Pydantic v1\n- {\n- \"title\": \"X-Token\",\n- \"type\": \"array\",\n- \"items\": {\"type\": \"string\"},\n- }\n- ),\n- \"name\": \"x-token\",\n- \"in\": \"header\",\n- }\n- ],\n- \"responses\": {\n- \"200\": {\n- \"description\": \"[NAME_REDACTED]\",\n- \"content\": {\"application/json\": {\"schema\": {}}},\n- },\n- \"422\": {\n- \"description\": \"[NAME_REDACTED]\",\n- \"content\": {\n- \"application/json\": {\n- \"schema\": {\n- \"$ref\": \"#/components/schemas/HTTPValidationError\"\n- }\n- }\n- },\n- },\n- },\n- }\n- }\n- },\n- \"components\": {\n- \"schemas\": {\n- \"HTTPValidationError\": {\n- \"title\": \"HTTPValidationError\",\n- \"type\": \"object\",\n- \"properties\": {\n- \"detail\": {\n- \"title\": \"Detail\",\n- \"type\": \"array\",\n- \"items\": {\"$ref\": \"#/components/schemas/ValidationError\"},\n- }\n- },\n- },\n- \"ValidationError\": {\n- \"title\": \"ValidationError\",\n- \"required\": [\"loc\", \"msg\", \"type\"],\n- \"type\": \"object\",\n- \"properties\": {\n- \"loc\": {\n- \"title\": \"Location\",\n- \"type\": \"array\",\n- \"items\": {\n- \"anyOf\": [{\"type\": \"string\"}, {\"type\": \"integer\"}]\n- },\n- },\n- \"msg\": {\"title\": \"Message\", \"type\": \"string\"},\n- \"type\": {\"title\": \"[NAME_REDACTED]\", \"type\": \"string\"},\n- },\n- },\n- }\n- },\n- }" }, { "filename": "tests/test_tutorial/test_header_params/test_tutorial003_py310.py", "status": "removed", "additions": 0, "deletions": 118, "changes": 118, "patch": "@@ -1,118 +0,0 @@\n-import pytest\n-from dirty_equals import IsDict\n-from fastapi.testclient import TestClient\n-\n-from ...utils import needs_py310\n-\n-\n-[USER_REDACTED].fixture(name=\"client\")\n-def get_client():\n- from docs_src.header_params.tutorial003_py310 import app\n-\n- client = TestClient(app)\n- return client\n-\n-\n-[USER_REDACTED]_py310\n-[USER_REDACTED].mark.parametrize(\n- \"path,headers,expected_status,expected_response\",\n- [\n- (\"/items\", None, 200, {\"X-Token values\": None}),\n- (\"/items\", {\"x-token\": \"foo\"}, 200, {\"X-Token values\": [\"foo\"]}),\n- # TODO: fix this, is it a bug?\n- # (\"/items\", [(\"x-token\", \"foo\"), (\"x-token\", \"bar\")], 200, {\"X-Token values\": [\"foo\", \"bar\"]}),\n- ],\n-)\n-def test(path, headers, expected_status, expected_response, client: TestClient):\n- response = client.get(path, headers=headers)\n- assert response.status_code == expected_status\n- assert response.json() == expected_response\n-\n-\n-[USER_REDACTED]_py310\n-def test_openapi_schema(client: TestClient):\n- response = client.get(\"/openapi.json\")\n- assert response.status_code == 200\n- assert response.json() == {\n- \"openapi\": \"3.1.0\",\n- \"info\": {\"title\": \"FastAPI\", \"version\": \"0.1.0\"},\n- \"paths\": {\n- \"/items/\": {\n- \"get\": {\n- \"summary\": \"[NAME_REDACTED]\",\n- \"operationId\": \"read_items_items__get\",\n- \"parameters\": [\n- {\n- \"required\": False,\n- \"schema\": IsDict(\n- {\n- \"title\": \"X-Token\",\n- \"anyOf\": [\n- {\"type\": \"array\", \"items\": {\"type\": \"string\"}},\n- {\"type\": \"null\"},\n- ],\n- }\n- )\n- | IsDict(\n- # TODO: remove when deprecating Pydantic v1\n- {\n- \"title\": \"X-Token\",\n- \"type\": \"array\",\n- \"items\": {\"type\": \"string\"},\n- }\n- ),\n- \"name\": \"x-token\",\n- \"in\": \"header\",\n- }\n- ],\n- \"responses\": {\n- \"200\": {\n- \"description\": \"[NAME_REDACTED]\",\n- \"content\": {\"application/json\": {\"schema\": {}}},\n- },\n- \"422\": {\n- \"description\": \"[NAME_REDACTED]\",\n- \"content\": {\n- \"application/json\": {\n- \"schema\": {\n- \"$ref\": \"#/components/schemas/HTTPValidationError\"\n- }\n- }\n- },\n- },\n- },\n- }\n- }\n- },\n- \"components\": {\n- \"schemas\": {\n- \"HTTPValidationError\": {\n- \"title\": \"HTTPValidationError\",\n- \"type\": \"object\",\n- \"properties\": {\n- \"detail\": {\n- \"title\": \"Detail\",\n- \"type\": \"array\",\n- \"items\": {\"$ref\": \"#/components/schemas/ValidationError\"},\n- }\n- },\n- },\n- \"ValidationError\": {\n- \"title\": \"ValidationError\",\n- \"required\": [\"loc\", \"msg\", \"type\"],\n- \"type\": \"object\",\n- \"properties\": {\n- \"loc\": {\n- \"title\": \"Location\",\n- \"type\": \"array\",\n- \"items\": {\n- \"anyOf\": [{\"type\": \"string\"}, {\"type\": \"integer\"}]\n- },\n- },\n- \"msg\": {\"title\": \"Message\", \"type\": \"string\"},\n- \"type\": {\"title\": \"[NAME_REDACTED]\", \"type\": \"string\"},\n- },\n- },\n- }\n- },\n- }" } ], "reviews": [ { "id": 2542593727, "user": "user_84458f05cf3c", "state": "COMMENTED", "body": null, "submitted_at": "2025-01-10T14:34:18+00:00" }, { "id": 2543956569, "user": "user_568843bce6ca", "state": "COMMENTED", "body": null, "submitted_at": "2025-01-10T21:32:01+00:00" }, { "id": 2560928407, "user": "user_2a237e38e06b", "state": "APPROVED", "body": ":fire:", "submitted_at": "2025-01-19T06:31:43+00:00" } ], "review_comments": [ { "id": 1910459205, "user": "user_84458f05cf3c", "body": "This wasn't failing before? 🤔", "path": "tests/test_tutorial/test_header_params/test_tutorial003.py", "line": 33, "side": "RIGHT", "created_at": "2025-01-10T14:34:18+00:00" }, { "id": 1911442086, "user": "user_568843bce6ca", "body": "I updated the test to the latest version `test_tutorial003_an_py310.py`, which already included the comment, so I kept it", "path": "tests/test_tutorial/test_header_params/test_tutorial003.py", "line": 33, "side": "RIGHT", "created_at": "2025-01-10T21:32:01+00:00" } ], "meta": { "languages": [ "py" ], "touches_tests": true, "review_state_summary": { "COMMENTED": 2, "APPROVED": 1 }, "meaningful_comment_count": 2, "has_approval": true, "has_changes_requested": false, "total_review_comments": 2 } } { "_id": "3880e5498c0cf060", "_schema_version": "1.0", "_cleaned_at": "2026-02-12T07:46:52.226800+00:00", "repo": "tiangolo/fastapi", "repo_url": "https://github.com/fastapi/fastapi", "license_name": "MIT License", "license_spdx": "MIT", "pr_number": 13156, "title": "🌐 Update Portuguese translations", "body": "Update Portuguese translation for the files:\n- docs/pt/docs/tutorial/index.md\n- docs/pt/docs/tutorial/first-steps.md\n- docs/pt/docs/deployment/server-workers.md\n- docs/pt/docs/deployment/manually.md", "author": "user_d7807c4ad46b", "created_at": "2025-01-04T23:16:12+00:00", "merged_at": "2025-01-09T20:41:07+00:00", "base_branch": "master", "head_branch": "master", "additions": 130, "deletions": 157, "changed_files": 4, "files": [ { "filename": "docs/pt/docs/deployment/manually.md", "status": "modified", "additions": 27, "deletions": 39, "changes": 66, "patch": "@@ -7,45 +7,33 @@ Em resumo, utilize o comando `fastapi run` para inicializar sua aplicação Fast\n
      \n \n ```console\n-$ fastapi run main.py\n-INFO Using path main.py\n-INFO Resolved absolute path /home/user/code/awesomeapp/main.py\n-INFO Searching for package file structure from directories with __init__.py files\n-INFO Importing from /home/user/code/awesomeapp\n-\n- ╭─ Python module file ─╮\n- │ │\n- │ 🐍 main.py │\n- │ │\n- ╰──────────────────────╯\n-\n-INFO Importing module main\n-INFO Found importable FastAPI app\n-\n- ╭─ [NAME_REDACTED] app ─╮\n- │ │\n- │ from main import app │\n- │ │\n- ╰──────────────────────────╯\n-\n-INFO Using import string main:app\n-\n- ╭─────────── FastAPI CLI - Production mode ───────────╮\n- │ │\n- │ Serving at: http://0.0.0.0:8000 │\n- │ │\n- │ API docs: http://0.0.0.0:8000/docs │\n- │ │\n- │ Running in production mode, for development use: │\n- │ │\n- fastapi dev\n- │ │\n- ╰─────────────────────────────────────────────────────╯\n-\n-INFO: Started server process [2306215]\n-INFO: Waiting for application startup.\n-INFO: Application startup complete.\n-INFO: Uvicorn running on http://0.0.0.0:8000 (Press CTRL+C to quit)\n+$ fastapi run main.py\n+\n+ FastAPI Starting production server 🚀\n+\n+ Searching for package file structure from directories\n+ with __init__.py files\n+ Importing from /home/user/code/awesomeapp\n+\n+ module 🐍 main.py\n+\n+ code Importing the FastAPI app object from the module with\n+ the following code:\n+\n+ from main import app\n+\n+ app Using import string: main:app\n+\n+ server Server started at http://0.0.0.0:8000\n+ server Documentation at http://0.0.0.0:8000/docs\n+\n+ Logs:\n+\n+ INFO Started server process [2306215]\n+ INFO Waiting for application startup.\n+ INFO Application startup complete.\n+ INFO Uvicorn running on http://0.0.0.0:8000 (Press CTRL+C\n+ to quit)\n ```\n \n
      " }, { "filename": "docs/pt/docs/deployment/server-workers.md", "status": "modified", "additions": 37, "deletions": 50, "changes": 87, "patch": "@@ -36,56 +36,43 @@ Se você usar o comando `fastapi`:\n
      \n \n ```console\n-$
       fastapi run --workers 4 main.py\n-INFO     Using path main.py\n-INFO     Resolved absolute path /home/user/code/awesomeapp/main.py\n-INFO     Searching for package file structure from directories with __init__.py files\n-INFO     Importing from /home/user/code/awesomeapp\n-\n- ╭─ Python module file ─╮\n- │                      │\n- │  🐍 main.py          │\n- │                      │\n- ╰──────────────────────╯\n-\n-INFO     Importing module main\n-INFO     Found importable FastAPI app\n-\n- ╭─ [NAME_REDACTED] app ─╮\n- │                          │\n- │  from main import app    │\n- │                          │\n- ╰──────────────────────────╯\n-\n-INFO     Using import string main:app\n-\n- ╭─────────── FastAPI CLI - Production mode ───────────╮\n- │                                                     │\n- │  Serving at: http://0.0.0.0:8000                    │\n- │                                                     │\n- │  API docs: http://0.0.0.0:8000/docs                 │\n- │                                                     │\n- │  Running in production mode, for development use:   │\n- │                                                     │\n- fastapi dev\n- │                                                     │\n- ╰─────────────────────────────────────────────────────╯\n-\n-INFO:     Uvicorn running on http://0.0.0.0:8000 (Press CTRL+C to quit)\n-INFO:     Started parent process [27365]\n-INFO:     Started server process [27368]\n-INFO:     Waiting for application startup.\n-INFO:     Application startup complete.\n-INFO:     Started server process [27369]\n-INFO:     Waiting for application startup.\n-INFO:     Application startup complete.\n-INFO:     Started server process [27370]\n-INFO:     Waiting for application startup.\n-INFO:     Application startup complete.\n-INFO:     Started server process [27367]\n-INFO:     Waiting for application startup.\n-INFO:     Application startup complete.\n-
      \n+$ fastapi run --workers 4 main.py\n+\n+ FastAPI Starting production server 🚀\n+\n+ Searching for package file structure from directories with\n+ __init__.py files\n+ Importing from /home/user/code/awesomeapp\n+\n+ module 🐍 main.py\n+\n+ code Importing the FastAPI app object from the module with the\n+ following code:\n+\n+ from main import app\n+\n+ app Using import string: main:app\n+\n+ server Server started at http://0.0.0.0:8000\n+ server Documentation at http://0.0.0.0:8000/docs\n+\n+ Logs:\n+\n+ INFO Uvicorn running on http://0.0.0.0:8000 (Press CTRL+C to\n+ quit)\n+ INFO Started parent process [27365]\n+ INFO Started server process [27368]\n+ INFO Started server process [27369]\n+ INFO Started server process [27370]\n+ INFO Started server process [27367]\n+ INFO Waiting for application startup.\n+ INFO Waiting for application startup.\n+ INFO Waiting for application startup.\n+ INFO Waiting for application startup.\n+ INFO Application startup complete.\n+ INFO Application startup complete.\n+ INFO Application startup complete.\n+ INFO Application startup complete.\n ```\n \n
      " }, { "filename": "docs/pt/docs/tutorial/first-steps.md", "status": "modified", "additions": 30, "deletions": 42, "changes": 72, "patch": "@@ -11,26 +11,42 @@ Execute o servidor:\n
      \n \n ```console\n-$ uvicorn main:app --reload\n+$ fastapi dev main.py\n \n-INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit)\n-INFO: Started reloader process [28720]\n-INFO: Started server process [28722]\n-INFO: Waiting for application startup.\n-INFO: Application startup complete.\n-```\n+ FastAPI Starting development server 🚀\n \n-
      \n+ Searching for package file structure from directories\n+ with __init__.py files\n+ Importing from /home/user/code/awesomeapp\n \n-/// note | Nota\n+ module 🐍 main.py\n \n-O comando `uvicorn main:app` se refere a:\n+ code Importing the FastAPI app object from the module with\n+ the following code:\n \n-* `main`: o arquivo `main.py` (o \"módulo\" Python).\n-* `app`: o objeto criado no arquivo `main.py` com a linha `app = FastAPI()`.\n-* `--reload`: faz o servidor reiniciar após mudanças de código. Use apenas para desenvolvimento.\n+ from main import app\n \n-///\n+ app Using import string: main:app\n+\n+ server Server started at http://127.0.0.1:8000\n+ server Documentation at http://127.0.0.1:8000/docs\n+\n+ tip Running in development mode, for production use:\n+ fastapi run\n+\n+ Logs:\n+\n+ INFO Will watch for changes in these directories:\n+ ['/home/user/code/awesomeapp']\n+ INFO Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C\n+ to quit)\n+ INFO Started reloader process [383138] using WatchFiles\n+ INFO Started server process [383153]\n+ INFO Waiting for application startup.\n+ INFO Application startup complete.\n+```\n+\n+
      \n \n Na saída, temos:\n \n@@ -151,34 +167,6 @@ Aqui, a variável `app` será uma \"instância\" da classe `FastAPI`.\n \n Este será o principal ponto de interação para criar toda a sua API.\n \n-Este `app` é o mesmo referenciado por `uvicorn` no comando:\n-\n-
      \n-\n-```console\n-$ uvicorn main:app --reload\n-\n-INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit)\n-```\n-\n-
      \n-\n-Se você criar a sua aplicação como:\n-\n-{* ../../docs_src/first_steps/tutorial002.py hl[3] *}\n-\n-E colocar em um arquivo `main.py`, você iria chamar o `uvicorn` assim:\n-\n-
      \n-\n-```console\n-$ uvicorn main:my_awesome_api --reload\n-\n-INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit)\n-```\n-\n-
      \n-\n ### Passo 3: crie uma *rota*\n \n #### Rota" }, { "filename": "docs/pt/docs/tutorial/index.md", "status": "modified", "additions": 36, "deletions": 26, "changes": 62, "patch": "@@ -4,9 +4,7 @@ Esse tutorial mostra como usar o **FastAPI** com a maior parte de seus recursos,\n \n Cada seção constrói, gradualmente, sobre as anteriores, mas sua estrutura são tópicos separados, para que você possa ir a qualquer um específico e resolver suas necessidades específicas de API.\n \n-Ele também foi feito como referência futura.\n-\n-Então você poderá voltar e ver exatamente o que precisar.\n+Ele também foi construído para servir como uma referência futura, então você pode voltar e ver exatamente o que você precisa.\n \n ## Rode o código\n \n@@ -17,13 +15,39 @@ Para rodar qualquer um dos exemplos, copie o codigo para um arquivo `main.py`, e\n
      \n \n ```console\n-$ uvicorn main:app --reload\n+$ fastapi dev main.py\n+\n+ FastAPI Starting development server 🚀\n+\n+ Searching for package file structure from directories\n+ with __init__.py files\n+ Importing from /home/user/code/awesomeapp\n+\n+ module 🐍 main.py\n+\n+ code Importing the FastAPI app object from the module with\n+ the following code:\n+\n+ from main import app\n+\n+ app Using import string: main:app\n+\n+ server Server started at http://127.0.0.1:8000\n+ server Documentation at http://127.0.0.1:8000/docs\n+\n+ tip Running in development mode, for production use:\n+ fastapi run\n+\n+ Logs:\n \n-INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit)\n-INFO: Started reloader process [28720]\n-INFO: Started server process [28722]\n-INFO: Waiting for application startup.\n-INFO: Application startup complete.\n+ INFO Will watch for changes in these directories:\n+ ['/home/user/code/awesomeapp']\n+ INFO Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C\n+ to quit)\n+ INFO Started reloader process [383138] using WatchFiles\n+ INFO Started server process [383153]\n+ INFO Waiting for application startup.\n+ INFO Application startup complete.\n ```\n \n
      \n@@ -43,32 +67,18 @@ Para o tutorial, você deve querer instalá-lo com todas as dependências e recu\n
      \n \n ```console\n-$ pip install \"fastapi[all]\"\n+$ pip install \"fastapi[standard]\"\n \n ---> 100%\n ```\n \n
      \n \n-...isso também inclui o `uvicorn`, que você pode usar como o servidor que rodará seu código.\n-\n /// note | Nota\n \n-Você também pode instalar parte por parte.\n-\n-Isso é provavelmente o que você faria quando você quisesse lançar sua aplicação em produção:\n-\n-```\n-pip install fastapi\n-```\n-\n-Também instale o `uvicorn` para funcionar como servidor:\n-\n-```\n-pip install \"uvicorn[standard]\"\n-```\n+Quando você instala com pip install \"fastapi[standard]\", ele vem com algumas dependências opcionais padrão.\n \n-E o mesmo para cada dependência opcional que você quiser usar.\n+Se você não quiser ter essas dependências opcionais, pode instalar pip install fastapi em vez disso.\n \n ///" } ], "reviews": [ { "id": 2530915484, "user": "user_e10da7d15f57", "state": "APPROVED", "body": "It is good, but could you update your branch and pull request changes that can not cause conflicts?", "submitted_at": "2025-01-05T14:58:20+00:00" }, { "id": 2533163580, "user": "user_afc2ad817d84", "state": "COMMENTED", "body": "Just some fixes by [NAME_REDACTED] there is also the problem of conflict.", "submitted_at": "2025-01-07T02:42:47+00:00" }, { "id": 2539762731, "user": "user_178cb4401e94", "state": "APPROVED", "body": "✨", "submitted_at": "2025-01-09T12:13:17+00:00" } ], "review_comments": [ { "id": 1904756747, "user": "user_afc2ad817d84", "body": "```suggestion\nQuando você instala com `pip install \"fastapi[standard]\"`, ele vem com algumas dependências opcionais padrão.\n```", "path": "docs/pt/docs/tutorial/index.md", "line": 79, "side": "RIGHT", "created_at": "2025-01-06T23:58:32+00:00" }, { "id": 1904757101, "user": "user_afc2ad817d84", "body": "```suggestion\nSe você não quiser ter essas dependências opcionais, pode instalar `pip install fastapi` em vez disso.\n```", "path": "docs/pt/docs/tutorial/index.md", "line": 81, "side": "RIGHT", "created_at": "2025-01-06T23:59:10+00:00" } ], "meta": { "languages": [ "md" ], "touches_tests": false, "review_state_summary": { "APPROVED": 2, "COMMENTED": 1 }, "meaningful_comment_count": 2, "has_approval": true, "has_changes_requested": false, "total_review_comments": 2 } } { "_id": "223498427dd6dc85", "_schema_version": "1.0", "_cleaned_at": "2026-02-12T07:46:52.226800+00:00", "repo": "tiangolo/fastapi", "repo_url": "https://github.com/fastapi/fastapi", "license_name": "MIT License", "license_spdx": "MIT", "pr_number": 13154, "title": "🌐 Add Russian translation for `docs/ru/docs/tutorial/bigger-applications.md`", "body": null, "author": "user_6d7d83efab20", "created_at": "2025-01-04T13:37:48+00:00", "merged_at": "2025-01-23T09:46:41+00:00", "base_branch": "master", "head_branch": "translate-lang-ru-bigger-applications", "additions": 556, "deletions": 0, "changed_files": 1, "files": [ { "filename": "docs/ru/docs/tutorial/bigger-applications.md", "status": "added", "additions": 556, "deletions": 0, "changes": 556, "patch": "@@ -0,0 +1,556 @@\n+# Большие приложения, в которых много файлов\n+\n+При построении приложения или веб-API нам редко удается поместить всё в один файл.\n+\n+**FastAPI** предоставляет удобный инструментарий, который позволяет нам структурировать приложение, сохраняя при этом всю необходимую гибкость.\n+\n+/// info | Примечание\n+\n+Если вы раньше использовали Flask, то это аналог шаблонов Flask ([NAME_REDACTED]).\n+\n+///\n+\n+## Пример структуры приложения\n+\n+Давайте предположим, что наше приложение имеет следующую структуру:\n+\n+```\n+.\n+├── app\n+│   ├── __init__.py\n+│   ├── main.py\n+│   ├── dependencies.py\n+│   └── routers\n+│   │ ├── __init__.py\n+│   │ ├── items.py\n+│   │ └── users.py\n+│   └── internal\n+│   ├── __init__.py\n+│   └── admin.py\n+```\n+\n+/// tip | Подсказка\n+\n+Обратите внимание, что в каждом каталоге и подкаталоге имеется файл `__init__.py`\n+\n+Это как раз то, что позволяет импортировать код из одного файла в другой.\n+\n+Например, в файле `app/main.py` может быть следующая строка:\n+\n+```\n+from app.routers import items\n+```\n+\n+///\n+\n+* Всё помещается в каталоге `app`. В нём также находится пустой файл `app/__init__.py`. Таким образом, `app` является \"Python-пакетом\" (коллекцией модулей Python).\n+* Он содержит файл `app/main.py`. Данный файл является частью пакета (т.е. находится внутри каталога, содержащего файл `__init__.py`), и, соответственно, он является модулем пакета: `app.main`.\n+* Он также содержит файл `app/dependencies.py`, который также, как и `app/main.py`, является модулем: `app.dependencies`.\n+* Здесь также находится подкаталог `app/routers/`, содержащий `__init__.py`. Он является суб-пакетом: `app.routers`.\n+* Файл `app/routers/items.py` находится внутри пакета `app/routers/`. Таким образом, он является суб-модулем: `app.routers.items`.\n+* Точно также `app/routers/users.py` является ещё одним суб-модулем: `app.routers.users`.\n+* Подкаталог `app/internal/`, содержащий файл `__init__.py`, является ещё одним суб-пакетом: `app.internal`.\n+* А файл `app/internal/admin.py` является ещё одним суб-модулем: `app.internal.admin`.\n+\n+\n+\n+Та же самая файловая структура приложения, но с комментариями:\n+\n+```\n+.\n+├── app # \"app\" пакет\n+│   ├── __init__.py # этот файл превращает \"app\" в \"Python-пакет\"\n+│   ├── main.py # модуль \"main\", напр.: import app.main\n+│   ├── dependencies.py # модуль \"dependencies\", напр.: import app.dependencies\n+│   └── routers # суб-пакет \"routers\"\n+│   │ ├── __init__.py # превращает \"routers\" в суб-пакет\n+│   │ ├── items.py # суб-модуль \"items\", напр.: import app.routers.items\n+│   │ └── users.py # суб-модуль \"users\", напр.: import app.routers.users\n+│   └── internal # суб-пакет \"internal\"\n+│   ├── __init__.py # превращает \"internal\" в суб-пакет\n+│   └── admin.py # суб-модуль \"admin\", напр.: import app.internal.admin\n+```\n+\n+## `APIRouter`\n+\n+Давайте предположим, что для работы с пользователями используется отдельный файл (суб-модуль) `/app/routers/users.py`.\n+\n+Для лучшей организации приложения, вы хотите отделить операции пути, связанные с пользователями, от остального кода.\n+\n+Но так, чтобы эти операции по-прежнему оставались частью **FastAPI** приложения/веб-API (частью одного пакета)\n+\n+С помощью `APIRouter` вы можете создать *операции пути* (*эндпоинты*) для данного модуля.\n+\n+\n+### Импорт `APIRouter`\n+\n+Точно также, как и в случае с классом `FastAPI`, вам нужно импортировать и создать объект класса `APIRouter`.\n+\n+```Python hl_lines=\"1 3\" title=\"app/routers/users.py\"\n+{!../../docs_src/bigger_applications/app/routers/users.py!}\n+```\n+\n+### Создание *эндпоинтов* с помощью `APIRouter`\n+\n+В дальнейшем используйте `APIRouter` для объявления *эндпоинтов*, точно также, как вы используете класс `FastAPI`:\n+\n+```Python hl_lines=\"6 11 16\" title=\"app/routers/users.py\"\n+{!../../docs_src/bigger_applications/app/routers/users.py!}\n+```\n+\n+Вы можете думать об `APIRouter` как об \"уменьшенной версии\" класса FastAPI`.\n+\n+`APIRouter` поддерживает все те же самые опции.\n+\n+`APIRouter` поддерживает все те же самые параметры, такие как `parameters`, `responses`, `dependencies`, `tags`, и т. д.\n+\n+/// tip | Подсказка\n+\n+В данном примере, в качестве названия переменной используется `router`, но вы можете использовать любое другое имя.\n+\n+///\n+\n+Мы собираемся подключить данный `APIRouter` к нашему основному приложению на `FastAPI`, но сначала давайте проверим зависимости и создадим ещё один модуль с `APIRouter`.\n+\n+## Зависимости\n+\n+Нам понадобятся некоторые зависимости, которые мы будем использовать в разных местах нашего приложения.\n+\n+Мы поместим их в отдельный модуль `dependencies` (`app/dependencies.py`).\n+\n+Теперь мы воспользуемся простой зависимостью, чтобы прочитать кастомизированный `X-Token` из заголовка:\n+\n+//// tab | Python 3.9+\n+\n+```Python hl_lines=\"3 6-8\" title=\"app/dependencies.py\"\n+{!> ../../docs_src/bigger_applications/app_an_py39/dependencies.py!}\n+```\n+\n+////\n+\n+//// tab | Python 3.8+\n+\n+```Python hl_lines=\"1 5-7\" title=\"app/dependencies.py\"\n+{!> ../../docs_src/bigger_applications/app_an/dependencies.py!}\n+```\n+\n+////\n+\n+//// tab | Python 3.8+ non-Annotated\n+\n+/// tip | Подсказка\n+\n+Мы рекомендуем использовать версию `Annotated`, когда это возможно.\n+\n+///\n+\n+```Python hl_lines=\"1 4-6\" title=\"app/dependencies.py\"\n+{!> ../../docs_src/bigger_applications/app/dependencies.py!}\n+```\n+\n+////\n+\n+/// tip | Подсказка\n+\n+Для простоты мы воспользовались неким воображаемым заголовоком.\n+\n+В реальных случаях для получения наилучших результатов используйте интегрированные утилиты обеспечения безопасности [Security utilities](security/index.md){.internal-link target=_blank}.\n+\n+///\n+\n+## Ещё один модуль с `APIRouter`\n+\n+Давайте также предположим, что у вас есть *эндпоинты*, отвечающие за обработку \"items\", и они находятся в модуле `app/routers/items.py`.\n+\n+У вас определены следующие *операции пути* (*эндпоинты*):\n+\n+* `/items/`\n+* `/items/{item_id}`\n+\n+Тут всё точно также, как и в ситуации с `app/routers/users.py`.\n+\n+Но теперь мы хотим поступить немного умнее и слегка упростить код.\n+\n+Мы знаем, что все *эндпоинты* данного модуля имеют некоторые общие свойства:\n+\n+* Префикс пути: `/items`.\n+* Теги: (один единственный тег: `items`).\n+* Дополнительные ответы (responses)\n+* Зависимости: использование созданной нами зависимости `X-token`\n+\n+Таким образом, вместо того чтобы добавлять все эти свойства в функцию каждого отдельного *эндпоинта*,\n+мы добавим их в `APIRouter`.\n+\n+```Python hl_lines=\"5-10 16 21\" title=\"app/routers/items.py\"\n+{!../../docs_src/bigger_applications/app/routers/items.py!}\n+```\n+\n+Так как каждый *эндпоинт* начинается с символа `/`:\n+\n+```Python hl_lines=\"1\"\n+[USER_REDACTED].get(\"/{item_id}\")\n+async def read_item(item_id: str):\n+ ...\n+```\n+\n+...то префикс не должен заканчиваться символом `/`.\n+\n+В нашем случае префиксом является `/items`.\n+\n+Мы также можем добавить в наш маршрутизатор (router) список `тегов` (`tags`) и дополнительных `ответов` (`responses`), которые являются общими для каждого *эндпоинта*.\n+\n+И ещё мы можем добавить в наш маршрутизатор список `зависимостей`, которые должны вызываться при каждом обращении к *эндпоинтам*.\n+\n+/// tip | Подсказка\n+\n+Обратите внимание, что также, как и в случае с зависимостями в декораторах *эндпоинтов* ([dependencies in *path operation decorators*](dependencies/dependencies-in-path-operation-decorators.md){.internal-link target=_blank}), никакого значения в *функцию эндпоинта* передано не будет.\n+\n+///\n+\n+В результате мы получим следующие эндпоинты:\n+\n+* `/items/`\n+* `/items/{item_id}`\n+\n+...как мы и планировали.\n+\n+* Они будут помечены тегами из заданного списка, в нашем случае это `\"items\"`.\n+ * Эти теги особенно полезны для системы автоматической интерактивной документации (с использованием OpenAPI).\n+* Каждый из них будет включать предопределенные ответы `responses`.\n+* Каждый *эндпоинт* будет иметь список зависимостей (`dependencies`), исполняемых перед вызовом *эндпоинта*.\n+ * Если вы определили зависимости в самой операции пути, **то она также будет выполнена**.\n+ * Сначала выполняются зависимости маршрутизатора, затем вызываются зависимости, определенные в декораторе *эндпоинта* ([`dependencies` in the decorator](dependencies/dependencies-in-path-operation-decorators.md){.internal-link target=_blank}), и, наконец, обычные параметрические зависимости.\n+ * Вы также можете добавить зависимости безопасности с областями видимости (`scopes`) [`Security` dependencies with `scopes`](../advanced/security/oauth2-scopes.md){.internal-link target=_blank}.\n+\n+/// tip | Подсказка\n+\n+Например, с помощью зависимостей в `APIRouter` мы можем потребовать аутентификации для доступа ко всей группе *эндпоинтов*, не указывая зависимости для каждой отдельной функции *эндпоинта*.\n+\n+///\n+\n+/// check | Заметка\n+\n+Параметры `prefix`, `tags`, `responses` и `dependencies` относятся к функционалу **FastAPI**, помогающему избежать дублирования кода.\n+\n+///\n+\n+### Импорт зависимостей\n+\n+Наш код находится в модуле `app.routers.items` (файл `app/routers/items.py`).\n+\n+И нам нужно вызвать функцию зависимости из модуля `app.dependencies` (файл `app/dependencies.py`).\n+\n+Мы используем операцию относительного импорта `..` для импорта зависимости:\n+\n+```Python hl_lines=\"3\" title=\"app/routers/items.py\"\n+{!../../docs_src/bigger_applications/app/routers/items.py!}\n+```\n+\n+#### Как работает относительный импорт?\n+\n+/// tip | Подсказка\n+\n+Если вы прекрасно знаете, как работает импорт в Python, то переходите к следующему разделу.\n+\n+///\n+\n+Одна точка `.`, как в данном примере:\n+\n+```Python\n+from .dependencies import get_token_header\n+```\n+означает:\n+\n+* Начните с пакета, в котором находится данный модуль (файл `app/routers/items.py` расположен в каталоге `app/routers/`)...\n+* ... найдите модуль `dependencies` (файл `app/routers/dependencies.py`)...\n+* ... и импортируйте из него функцию `get_token_header`.\n+\n+К сожалению, такого файла не существует, и наши зависимости находятся в файле `app/dependencies.py`.\n+\n+Вспомните, как выглядит файловая структура нашего приложения:\n+\n+\n+\n+---\n+\n+Две точки `..`, как в данном примере:\n+\n+```Python\n+from ..dependencies import get_token_header\n+```\n+\n+означают:\n+\n+* Начните с пакета, в котором находится данный модуль (файл `app/routers/items.py` находится в каталоге `app/routers/`)...\n+* ... перейдите в родительский пакет (каталог `app/`)...\n+* ... найдите в нём модуль `dependencies` (файл `app/dependencies.py`)...\n+* ... и импортируйте из него функцию `get_token_header`.\n+\n+Это работает верно! 🎉\n+\n+---\n+\n+Аналогично, если бы мы использовали три точки `...`, как здесь:\n+\n+```Python\n+from ...dependencies import get_token_header\n+```\n+\n+то это бы означало:\n+\n+* Начните с пакета, в котором находится данный модуль (файл `app/routers/items.py` находится в каталоге `app/routers/`)...\n+* ... перейдите в родительский пакет (каталог `app/`)...\n+* ... затем перейдите в родительский пакет текущего пакета (такого пакета не существует, `app` находится на самом верхнем уровне 😱)...\n+* ... найдите в нём модуль `dependencies` (файл `app/dependencies.py`)...\n+* ... и импортируйте из него функцию `get_token_header`.\n+\n+Это будет относиться к некоторому пакету, находящемуся на один уровень выше чем `app/` и содержащему свой собственный файл `__init__.py`. Но ничего такого у нас нет. Поэтому это приведет к ошибке в нашем примере. 🚨\n+\n+Теперь вы знаете, как работает импорт в Python, и сможете использовать относительное импортирование в своих собственных приложениях любого уровня сложности. 🤓\n+\n+### Добавление пользовательских тегов (`tags`), ответов (`responses`) и зависимостей (`dependencies`)\n+\n+Мы не будем добавлять префикс `/items` и список тегов `tags=[\"items\"]` для каждого *эндпоинта*, т.к. мы уже их добавили с помощью `APIRouter`.\n+\n+Но помимо этого мы можем добавить новые теги для каждого отдельного *эндпоинта*, а также некоторые дополнительные ответы (`responses`), характерные для данного *эндпоинта*:\n+\n+```Python hl_lines=\"30-31\" title=\"app/routers/items.py\"\n+{!../../docs_src/bigger_applications/app/routers/items.py!}\n+```\n+\n+/// tip | Подсказка\n+\n+Последний *эндпоинт* будет иметь следующую комбинацию тегов: `[\"items\", \"custom\"]`.\n+\n+А также в его документации будут содержаться оба ответа: один для `404` и другой для `403`.\n+\n+///\n+\n+## Модуль main в `FastAPI`\n+\n+Теперь давайте посмотрим на модуль `app/main.py`.\n+\n+Именно сюда вы импортируете и именно здесь вы используете класс `FastAPI`.\n+\n+Это основной файл вашего приложения, который объединяет всё в одно целое.\n+\n+И теперь, когда большая часть логики приложения разделена на отдельные модули, основной файл `app/main.py` будет достаточно простым.\n+\n+### Импорт `FastAPI`\n+\n+Вы импортируете и создаете класс `FastAPI` как обычно.\n+\n+Мы даже можем объявить глобальные зависимости [global dependencies](dependencies/global-dependencies.md){.internal-link target=_blank}, которые будут объединены с зависимостями для каждого отдельного маршрутизатора:\n+\n+```Python hl_lines=\"1 3 7\" title=\"app/main.py\"\n+{!../../docs_src/bigger_applications/app/main.py!}\n+```\n+\n+### Импорт `APIRouter`\n+\n+Теперь мы импортируем другие суб-модули, содержащие `APIRouter`:\n+\n+```Python hl_lines=\"4-5\" title=\"app/main.py\"\n+{!../../docs_src/bigger_applications/app/main.py!}\n+```\n+\n+Так как файлы `app/routers/users.py` и `app/routers/items.py` являются суб-модулями одного и того же Python-пакета `app`, то мы сможем их импортировать, воспользовавшись операцией относительного импорта `.`.\n+\n+### Как работает импорт?\n+\n+Данная строка кода:\n+\n+```Python\n+from .routers import items, users\n+```\n+\n+означает:\n+\n+* Начните с пакета, в котором содержится данный модуль (файл `app/main.py` содержится в каталоге `app/`)...\n+* ... найдите суб-пакет `routers` (каталог `app/routers/`)...\n+* ... и из него импортируйте суб-модули `items` (файл `app/routers/items.py`) и `users` (файл `app/routers/users.py`)...\n+\n+В модуле `items` содержится переменная `router` (`items.router`), та самая, которую мы создали в файле `app/routers/items.py`, она является объектом класса `APIRouter`.\n+\n+И затем мы сделаем то же самое для модуля `users`.\n+\n+Мы также могли бы импортировать и другим методом:\n+\n+```Python\n+from app.routers import items, users\n+```\n+\n+/// info | Примечание\n+\n+Первая версия является примером относительного импорта:\n+\n+```Python\n+from .routers import items, users\n+```\n+\n+Вторая версия является примером абсолютного импорта:\n+\n+```Python\n+from app.routers import items, users\n+```\n+\n+Узнать больше о пакетах и модулях в Python вы можете из официальной документации Python о модулях\n+\n+///\n+\n+### Избегайте конфликтов имен\n+\n+Вместо того чтобы импортировать только переменную `router`, мы импортируем непосредственно суб-модуль `items`.\n+\n+Мы делаем это потому, что у нас есть ещё одна переменная `router` в суб-модуле `users`.\n+\n+Если бы мы импортировали их одну за другой, как показано в примере:\n+\n+```Python\n+from .routers.items import router\n+from .routers.users import router\n+```\n+\n+то переменная `router` из `users` переписал бы переменную `router` из `items`, и у нас не было бы возможности использовать их одновременно.\n+\n+Поэтому, для того чтобы использовать обе эти переменные в одном файле, мы импортировали соответствующие суб-модули:\n+\n+```Python hl_lines=\"5\" title=\"app/main.py\"\n+{!../../docs_src/bigger_applications/app/main.py!}\n+```\n+\n+### Подключение маршрутизаторов (`APIRouter`) для `users` и для `items`\n+\n+Давайте подключим маршрутизаторы (`router`) из суб-модулей `users` и `items`:\n+\n+```Python hl_lines=\"10-11\" title=\"app/main.py\"\n+{!../../docs_src/bigger_applications/app/main.py!}\n+```\n+\n+/// info | Примечание\n+\n+`users.router` содержит `APIRouter` из файла `app/routers/users.py`.\n+\n+А `items.router` содержит `APIRouter` из файла `app/routers/items.py`.\n+\n+///\n+\n+С помощью `app.include_router()` мы можем добавить каждый из маршрутизаторов (`APIRouter`) в основное приложение `FastAPI`.\n+\n+Он подключит все маршруты заданного маршрутизатора к нашему приложению.\n+\n+/// note | Технические детали\n+\n+Фактически, внутри он создаст все *операции пути* для каждой операции пути объявленной в `APIRouter`.\n+\n+И под капотом всё будет работать так, как будто бы мы имеем дело с одним файлом приложения.\n+\n+///\n+\n+/// check | Заметка\n+\n+При подключении маршрутизаторов не стоит беспокоиться о производительности.\n+\n+Операция подключения займёт микросекунды и понадобится только при запуске приложения.\n+\n+Таким образом, это не повлияет на производительность. ⚡\n+\n+///\n+\n+### Подключение `APIRouter` с пользовательскими префиксом (`prefix`), тегами (`tags`), ответами (`responses`), и зависимостями (`dependencies`)\n+\n+Теперь давайте представим, что ваша организация передала вам файл `app/internal/admin.py`.\n+\n+Он содержит `APIRouter` с некоторыми *эндпоитами* администрирования, которые ваша организация использует для нескольких проектов.\n+\n+В данном примере это сделать очень просто. Но давайте предположим, что поскольку файл используется для нескольких проектов,\n+то мы не можем модифицировать его, добавляя префиксы (`prefix`), зависимости (`dependencies`), теги (`tags`), и т.д. непосредственно в `APIRouter`:\n+\n+```Python hl_lines=\"3\" title=\"app/internal/admin.py\"\n+{!../../docs_src/bigger_applications/app/internal/admin.py!}\n+```\n+\n+Но, несмотря на это, мы хотим использовать кастомный префикс (`prefix`) для подключенного маршрутизатора (`APIRouter`), в результате чего, каждая *операция пути* будет начинаться с `/admin`. Также мы хотим защитить наш маршрутизатор с помощью зависимостей, созданных для нашего проекта. И ещё мы хотим включить теги (`tags`) и ответы (`responses`).\n+\n+Мы можем применить все вышеперечисленные настройки, не изменяя начальный `APIRouter`. Нам всего лишь нужно передать нужные параметры в `app.include_router()`.\n+\n+```Python hl_lines=\"14-17\" title=\"app/main.py\"\n+{!../../docs_src/bigger_applications/app/main.py!}\n+```\n+\n+Таким образом, оригинальный `APIRouter` не будет модифицирован, и мы сможем использовать файл `app/internal/admin.py` сразу в нескольких проектах организации.\n+\n+В результате, в нашем приложении каждый *эндпоинт* модуля `admin` будет иметь:\n+\n+* Префикс `/admin`.\n+* Тег `admin`.\n+* Зависимость `get_token_header`.\n+* Ответ `418`. 🍵\n+\n+Это будет иметь место исключительно для `APIRouter` в нашем приложении, и не затронет любой другой код, использующий его.\n+\n+Например, другие проекты, могут использовать тот же самый `APIRouter` с другими методами аутентификации.\n+\n+### Подключение отдельного *эндпоинта*\n+\n+Мы также можем добавить *эндпоинт* непосредственно в основное приложение `FastAPI`.\n+\n+Здесь мы это делаем ... просто, чтобы показать, что это возможно 🤷:\n+\n+```Python hl_lines=\"21-23\" title=\"app/main.py\"\n+{!../../docs_src/bigger_applications/app/main.py!}\n+```\n+\n+и это будет работать корректно вместе с другими *эндпоинтами*, добавленными с помощью `app.include_router()`.\n+\n+/// info | Сложные технические детали\n+\n+**Примечание**: это сложная техническая деталь, которую, скорее всего, **вы можете пропустить**.\n+\n+---\n+\n+Маршрутизаторы (`APIRouter`) не \"монтируются\" по-отдельности и не изолируются от остального приложения.\n+\n+Это происходит потому, что нужно включить их *эндпоинты* в OpenAPI схему и в интерфейс пользователя.\n+\n+В силу того, что мы не можем их изолировать и \"примонтировать\" независимо от остальных, *эндпоинты* клонируются (пересоздаются) и не подключаются напрямую.\n+\n+///\n+\n+## Проверка автоматической документации API\n+\n+Теперь запустите приложение:\n+\n+
      \n+\n+```console\n+$ fastapi dev app/main.py\n+\n+INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit)\n+```\n+\n+
      \n+\n+Откройте документацию по адресу http://127.0.0.1:8000/docs.\n+\n+Вы увидите автоматическую API документацию. Она включает в себя маршруты из суб-модулей, используя верные маршруты, префиксы и теги:\n+\n+\n+\n+## Подключение существующего маршрута через новый префикс (`prefix`)\n+\n+Вы можете использовать `.include_router()` несколько раз с одним и тем же маршрутом, применив различные префиксы.\n+\n+Это может быть полезным, если нужно предоставить доступ к одному и тому же API через различные префиксы, например, `/api/v1` и `/api/latest`.\n+\n+Это продвинутый способ, который вам может и не пригодится. Мы приводим его на случай, если вдруг вам это понадобится.\n+\n+## Включение одного маршрутизатора (`APIRouter`) в другой\n+\n+Точно так же, как вы включаете `APIRouter` в приложение `FastAPI`, вы можете включить `APIRouter` в другой `APIRouter`:\n+\n+```Python\n+router.include_router(other_router)\n+```\n+\n+Удостоверьтесь, что вы сделали это до того, как подключить маршрутизатор (`router`) к вашему `FastAPI` приложению, и *эндпоинты* маршрутизатора `other_router` были также подключены." } ], "reviews": [ { "id": 2530898673, "user": "user_3cf7e8d7d8b1", "state": "APPROVED", "body": "Спасибо! С новым годом!", "submitted_at": "2025-01-05T13:31:04+00:00" }, { "id": 2546113804, "user": "user_9e49ba0b4492", "state": "CHANGES_REQUESTED", "body": null, "submitted_at": "2025-01-13T11:32:49+00:00" }, { "id": 2547773551, "user": "user_6d7d83efab20", "state": "COMMENTED", "body": null, "submitted_at": "2025-01-13T20:15:22+00:00" }, { "id": 2547786557, "user": "user_6d7d83efab20", "state": "COMMENTED", "body": null, "submitted_at": "2025-01-13T20:20:27+00:00" }, { "id": 2547802087, "user": "user_6d7d83efab20", "state": "COMMENTED", "body": null, "submitted_at": "2025-01-13T20:27:19+00:00" }, { "id": 2547809039, "user": "user_6d7d83efab20", "state": "COMMENTED", "body": null, "submitted_at": "2025-01-13T20:30:13+00:00" }, { "id": 2547811449, "user": "user_6d7d83efab20", "state": "COMMENTED", "body": null, "submitted_at": "2025-01-13T20:31:19+00:00" }, { "id": 2547818978, "user": "user_6d7d83efab20", "state": "COMMENTED", "body": null, "submitted_at": "2025-01-13T20:34:27+00:00" }, { "id": 2547826801, "user": "user_6d7d83efab20", "state": "COMMENTED", "body": null, "submitted_at": "2025-01-13T20:37:50+00:00" }, { "id": 2547853772, "user": "user_6d7d83efab20", "state": "COMMENTED", "body": null, "submitted_at": "2025-01-13T20:48:28+00:00" }, { "id": 2547857907, "user": "user_6d7d83efab20", "state": "COMMENTED", "body": null, "submitted_at": "2025-01-13T20:50:09+00:00" }, { "id": 2547859086, "user": "user_6d7d83efab20", "state": "COMMENTED", "body": null, "submitted_at": "2025-01-13T20:50:44+00:00" }, { "id": 2547860475, "user": "user_6d7d83efab20", "state": "COMMENTED", "body": null, "submitted_at": "2025-01-13T20:51:26+00:00" }, { "id": 2547861763, "user": "user_6d7d83efab20", "state": "COMMENTED", "body": null, "submitted_at": "2025-01-13T20:52:01+00:00" }, { "id": 2547862800, "user": "user_6d7d83efab20", "state": "COMMENTED", "body": null, "submitted_at": "2025-01-13T20:52:27+00:00" }, { "id": 2547863876, "user": "user_6d7d83efab20", "state": "COMMENTED", "body": null, "submitted_at": "2025-01-13T20:52:57+00:00" }, { "id": 2547886923, "user": "user_6d7d83efab20", "state": "COMMENTED", "body": null, "submitted_at": "2025-01-13T21:02:34+00:00" }, { "id": 2547888784, "user": "user_6d7d83efab20", "state": "COMMENTED", "body": null, "submitted_at": "2025-01-13T21:03:23+00:00" }, { "id": 2547891797, "user": "user_6d7d83efab20", "state": "COMMENTED", "body": null, "submitted_at": "2025-01-13T21:04:43+00:00" }, { "id": 2547893365, "user": "user_6d7d83efab20", "state": "COMMENTED", "body": null, "submitted_at": "2025-01-13T21:05:14+00:00" }, { "id": 2547916755, "user": "user_6d7d83efab20", "state": "COMMENTED", "body": null, "submitted_at": "2025-01-13T21:14:12+00:00" }, { "id": 2550715004, "user": "user_9e49ba0b4492", "state": "COMMENTED", "body": null, "submitted_at": "2025-01-14T18:30:59+00:00" }, { "id": 2550833031, "user": "user_6d7d83efab20", "state": "COMMENTED", "body": null, "submitted_at": "2025-01-14T19:24:55+00:00" }, { "id": 2550900022, "user": "user_9e49ba0b4492", "state": "APPROVED", "body": null, "submitted_at": "2025-01-14T19:59:15+00:00" } ], "review_comments": [ { "id": 1912897339, "user": "user_9e49ba0b4492", "body": "Здесь вместо слова \"нечасто\" лучше использовать слово \"редко\" - это будет правильнее и более естественно.", "path": "docs/ru/docs/tutorial/bigger-applications.md", "line": null, "side": "RIGHT", "created_at": "2025-01-13T09:32:19+00:00" }, { "id": 1912950970, "user": "user_9e49ba0b4492", "body": "Здесь забыт предлог \"в\" - \"не будет передаваться в\".\nА также \"функции эндпоинта\" стоит перевести в единственное число - \"функция эндпоинта\", так как у одного эндпоинта не может быть несколько функций.", "path": "docs/ru/docs/tutorial/bigger-applications.md", "line": null, "side": "RIGHT", "created_at": "2025-01-13T10:11:57+00:00" }, { "id": 1912963733, "user": "user_9e49ba0b4492", "body": "Здесь вместо слова \"здесь\" лучше использовать слово \"там\" - \"найдите там модуль\". \"Там\" лучше отражает, что вы находитесь в другом пакете (в родительском), а не в том, в котором изначально начинали искать.", "path": "docs/ru/docs/tutorial/bigger-applications.md", "line": null, "side": "RIGHT", "created_at": "2025-01-13T10:22:09+00:00" }, { "id": 1912968376, "user": "user_9e49ba0b4492", "body": "В слове \"пользовательских\" отсутствует буква \"х\"", "path": "docs/ru/docs/tutorial/bigger-applications.md", "line": null, "side": "RIGHT", "created_at": "2025-01-13T10:25:46+00:00" }, { "id": 1912978186, "user": "user_9e49ba0b4492", "body": "\"использовать ..., воспользовавшись ...\" - получается \"тавтология\". Предлагаю следующий вариант:\n\"то мы сможем использовать `.` для того чтобы их импортировать при помощи относительного импорта\".", "path": "docs/ru/docs/tutorial/bigger-applications.md", "line": null, "side": "RIGHT", "created_at": "2025-01-13T10:33:28+00:00" }, { "id": 1912985986, "user": "user_9e49ba0b4492", "body": "Тут ошибка - вместо \"из одного файла\" должно быть \"в одном файле\". Да и \"обеими переменными\", я бы заменил на \"ими\".", "path": "docs/ru/docs/tutorial/bigger-applications.md", "line": null, "side": "RIGHT", "created_at": "2025-01-13T10:39:57+00:00" }, { "id": 1912988203, "user": "user_9e49ba0b4492", "body": "Здесь забыто \"| Примечание\"", "path": "docs/ru/docs/tutorial/bigger-applications.md", "line": null, "side": "RIGHT", "created_at": "2025-01-13T10:41:43+00:00" }, { "id": 1912993592, "user": "user_9e49ba0b4492", "body": "Здесь ошибка - в исходной документации имелось ввиду \"имеем дело с одним простым приложением\"", "path": "docs/ru/docs/tutorial/bigger-applications.md", "line": 446, "side": "RIGHT", "created_at": "2025-01-13T10:46:02+00:00" }, { "id": 1913003406, "user": "user_9e49ba0b4492", "body": "Выше (в одном из заголовков) \"custom\" уже был переведен как \"пользовательский\", поэтому для однообразия, и тут тоже стоит вместо слова \"кастомизированным\" использовать слово \"пользовательскими\" (в данном случае во множественном числе)", "path": "docs/ru/docs/tutorial/bigger-applications.md", "line": null, "side": "RIGHT", "created_at": "2025-01-13T10:53:41+00:00" }, { "id": 1913009332, "user": "user_9e49ba0b4492", "body": "Более точный перевод \"we can still share\" - \"мы **все еще** сможем использовать\", а \"projects in the organization\" - \"проектах организации\"", "path": "docs/ru/docs/tutorial/bigger-applications.md", "line": null, "side": "RIGHT", "created_at": "2025-01-13T10:58:09+00:00" }, { "id": 1913018600, "user": "user_9e49ba0b4492", "body": "\"это будет работать так, как нужно вместе с другими *эндпоинтами*\" - запутывает понимание. Однозначнее и понятнее будет - \"это будет работать корректно вместе с другими *эндпоинтами*\"", "path": "docs/ru/docs/tutorial/bigger-applications.md", "line": null, "side": "RIGHT", "created_at": "2025-01-13T11:05:55+00:00" }, { "id": 1913021054, "user": "user_9e49ba0b4492", "body": "Опять получается \"тавтология\" - \"покажем ..., чтобы показать\". Как вариант, можно прописать так - \"Здесь мы это делаем... просто, чтобы показать, что это возможно\"", "path": "docs/ru/docs/tutorial/bigger-applications.md", "line": null, "side": "RIGHT", "created_at": "2025-01-13T11:08:10+00:00" }, { "id": 1913031761, "user": "user_9e49ba0b4492", "body": "Почему тут появилось слово \"по-отдельности\"? В исходном тексте этого не упоминается - \"The APIRouters are not \"mounted\", they are not isolated from the rest of the application.\"", "path": "docs/ru/docs/tutorial/bigger-applications.md", "line": 512, "side": "RIGHT", "created_at": "2025-01-13T11:17:28+00:00" }, { "id": 1913036557, "user": "user_9e49ba0b4492", "body": "Здесь вместо \"включает в себя маршруты из суб-модулей, а также использует верные маршруты, префиксы и теги\" лучше будет \"включает в себя маршруты из суб-модулей, используя верные маршруты, префиксы и теги\"", "path": "docs/ru/docs/tutorial/bigger-applications.md", "line": null, "side": "RIGHT", "created_at": "2025-01-13T11:21:51+00:00" }, { "id": 1913755697, "user": "user_6d7d83efab20", "body": "```suggestion\nТак как файлы `app/routers/users.py` и `app/routers/items.py` являются суб-модулями одного и того же Python-пакета `app`, то мы сможем их импортировать, воспользовавшись операцией относительного импорта `.`.\n```", "path": "docs/ru/docs/tutorial/bigger-applications.md", "line": null, "side": "RIGHT", "created_at": "2025-01-13T20:15:22+00:00" }, { "id": 1913760987, "user": "user_6d7d83efab20", "body": "```suggestion\nПоэтому, для того чтобы использовать обе эти переменные в одном файле, мы импортировали соответствующие суб-модули:\n```", "path": "docs/ru/docs/tutorial/bigger-applications.md", "line": null, "side": "RIGHT", "created_at": "2025-01-13T20:20:27+00:00" }, { "id": 1913767677, "user": "user_6d7d83efab20", "body": "в исходной документации подразумевается, что под капотом все копируется в один общий файл, и приложение работает так, как будто-бы в нем существует один единственный файл `main.py`, где прописаны все маршруты.", "path": "docs/ru/docs/tutorial/bigger-applications.md", "line": 446, "side": "RIGHT", "created_at": "2025-01-13T20:27:19+00:00" }, { "id": 1913770563, "user": "user_6d7d83efab20", "body": "```suggestion\n### Подключение `APIRouter` с пользовательскими префиксом (`prefix`), тегами (`tags`), ответами (`responses`), и зависимостями (`dependencies`)\n```", "path": "docs/ru/docs/tutorial/bigger-applications.md", "line": null, "side": "RIGHT", "created_at": "2025-01-13T20:30:13+00:00" }, { "id": 1913771671, "user": "user_6d7d83efab20", "body": "```suggestion\nТаким образом, оригинальный `APIRouter` не будет модифицирован, и мы сможем использовать файл `app/internal/admin.py` сразу в нескольких проектах организации.\n```", "path": "docs/ru/docs/tutorial/bigger-applications.md", "line": null, "side": "RIGHT", "created_at": "2025-01-13T20:31:18+00:00" }, { "id": 1913774797, "user": "user_6d7d83efab20", "body": "```suggestion\nМы это делаем ... просто, чтобы показать, что это возможно 🤷:\n```", "path": "docs/ru/docs/tutorial/bigger-applications.md", "line": null, "side": "RIGHT", "created_at": "2025-01-13T20:34:26+00:00" }, { "id": 1913778070, "user": "user_6d7d83efab20", "body": "```suggestion\nи это будет работать корректно вместе с другими *эндпоинтами*, добавленными с помощью `app.include_router()`.\n```", "path": "docs/ru/docs/tutorial/bigger-applications.md", "line": null, "side": "RIGHT", "created_at": "2025-01-13T20:37:50+00:00" }, { "id": 1913788494, "user": "user_6d7d83efab20", "body": "Потому что в данном контексте \"isolated\" является пояснением к \"mounted\" :smiley: \n\n(оставлю как есть)", "path": "docs/ru/docs/tutorial/bigger-applications.md", "line": 512, "side": "RIGHT", "created_at": "2025-01-13T20:48:28+00:00" }, { "id": 1913790060, "user": "user_6d7d83efab20", "body": "```suggestion\nВы увидите автоматическую API документацию. Она включает в себя маршруты из суб-модулей, используя верные маршруты, префиксы и теги:\n```", "path": "docs/ru/docs/tutorial/bigger-applications.md", "line": null, "side": "RIGHT", "created_at": "2025-01-13T20:50:08+00:00" }, { "id": 1913790595, "user": "user_6d7d83efab20", "body": "```suggestion\nПри построении приложения или веб-API нам редко удается поместить всё в один файл.\n```", "path": "docs/ru/docs/tutorial/bigger-applications.md", "line": null, "side": "RIGHT", "created_at": "2025-01-13T20:50:44+00:00" }, { "id": 1913791235, "user": "user_6d7d83efab20", "body": "```suggestion\nОбратите внимание, что также, как и в случае с зависимостями в декораторах *эндпоинтов* ([dependencies in *path operation decorators*](dependencies/dependencies-in-path-operation-decorators.md){.internal-link target=_blank}), никакого значения в *функцию эндпоинта* передано не будет.\n```", "path": "docs/ru/docs/tutorial/bigger-applications.md", "line": null, "side": "RIGHT", "created_at": "2025-01-13T20:51:25+00:00" }, { "id": 1913791825, "user": "user_6d7d83efab20", "body": "```suggestion\n* ... найдите в нём модуль `dependencies` (файл `app/dependencies.py`)...\n```", "path": "docs/ru/docs/tutorial/bigger-applications.md", "line": null, "side": "RIGHT", "created_at": "2025-01-13T20:52:01+00:00" }, { "id": 1913792272, "user": "user_6d7d83efab20", "body": "```suggestion\n### Добавление пользовательских тегов (`tags`), ответов (`responses`) и зависимостей (`dependencies`)\n```", "path": "docs/ru/docs/tutorial/bigger-applications.md", "line": null, "side": "RIGHT", "created_at": "2025-01-13T20:52:27+00:00" }, { "id": 1913792752, "user": "user_6d7d83efab20", "body": "```suggestion\n/// info | Примечание\n```", "path": "docs/ru/docs/tutorial/bigger-applications.md", "line": null, "side": "RIGHT", "created_at": "2025-01-13T20:52:57+00:00" }, { "id": 1913802310, "user": "user_6d7d83efab20", "body": "здесь немного поменяла", "path": "docs/ru/docs/tutorial/bigger-applications.md", "line": null, "side": "RIGHT", "created_at": "2025-01-13T21:02:34+00:00" }, { "id": 1913803099, "user": "user_6d7d83efab20", "body": "здесь немного поменяла", "path": "docs/ru/docs/tutorial/bigger-applications.md", "line": null, "side": "RIGHT", "created_at": "2025-01-13T21:03:23+00:00" }, { "id": 1913804322, "user": "user_6d7d83efab20", "body": "небольшое изменение", "path": "docs/ru/docs/tutorial/bigger-applications.md", "line": null, "side": "RIGHT", "created_at": "2025-01-13T21:04:43+00:00" }, { "id": 1913804737, "user": "user_6d7d83efab20", "body": "внесла изменение", "path": "docs/ru/docs/tutorial/bigger-applications.md", "line": null, "side": "RIGHT", "created_at": "2025-01-13T21:05:14+00:00" }, { "id": 1913813803, "user": "user_6d7d83efab20", "body": "частично поправила\n(\"мы все еще сможем использовать\": может и точнее, но смысл теряется :smiley:)", "path": "docs/ru/docs/tutorial/bigger-applications.md", "line": null, "side": "RIGHT", "created_at": "2025-01-13T21:14:12+00:00" }, { "id": 1915412519, "user": "user_9e49ba0b4492", "body": "Слово \"Здесь\" в начале предложения не стоило убирать, ведь оно указывало на пример кода ниже.\nА без него тут появляется неоднозначность рода:\n1. \"Мы\" это кто? Все мы - как пользователи фреймворка FastAPI?\n2. делаем \"где\"? В своих проектах на FastAPI?", "path": "docs/ru/docs/tutorial/bigger-applications.md", "line": null, "side": "RIGHT", "created_at": "2025-01-14T18:30:59+00:00" }, { "id": 1915484262, "user": "user_6d7d83efab20", "body": "поправила", "path": "docs/ru/docs/tutorial/bigger-applications.md", "line": null, "side": "RIGHT", "created_at": "2025-01-14T19:24:55+00:00" } ], "meta": { "languages": [ "md" ], "touches_tests": false, "review_state_summary": { "APPROVED": 2, "CHANGES_REQUESTED": 1, "COMMENTED": 21 }, "meaningful_comment_count": 34, "has_approval": true, "has_changes_requested": true, "total_review_comments": 35 } } { "_id": "ea1b7565006ffa2d", "_schema_version": "1.0", "_cleaned_at": "2026-02-12T07:46:52.242325+00:00", "repo": "tiangolo/fastapi", "repo_url": "https://github.com/fastapi/fastapi", "license_name": "MIT License", "license_spdx": "MIT", "pr_number": 13135, "title": "👷‍♀️ Add script for [NAME_REDACTED] and update [NAME_REDACTED]", "body": "👷‍♀️ Add script for [NAME_REDACTED] and update [NAME_REDACTED]", "author": "user_568843bce6ca", "created_at": "2025-01-01T20:27:27+00:00", "merged_at": "2025-01-02T20:44:50+00:00", "base_branch": "master", "head_branch": "external-repos", "additions": 128, "deletions": 40, "changed_files": 6, "files": [ { "filename": ".github/workflows/topic-repos.yml", "status": "added", "additions": 40, "deletions": 0, "changes": 40, "patch": "@@ -0,0 +1,40 @@\n+name: Update Topic Repos\n+\n+on:\n+ schedule:\n+ - cron: \"0 12 1 * *\"\n+ workflow_dispatch:\n+\n+env:\n+ UV_SYSTEM_PYTHON: 1\n+\n+jobs:\n+ topic-repos:\n+ if: github.repository_owner == 'fastapi'\n+ runs-on: ubuntu-latest\n+ permissions:\n+ contents: write\n+ steps:\n+ - name: [NAME_REDACTED] context\n+ env:\n+ GITHUB_CONTEXT: ${{ toJson(github) }}\n+ run: echo \"$GITHUB_CONTEXT\"\n+ - uses: actions/checkout@v4\n+ - name: Set up Python\n+ uses: actions/setup-python@v5\n+ with:\n+ python-version: \"3.11\"\n+ - name: Setup uv\n+ uses: astral-sh/setup-uv@v5\n+ with:\n+ version: \"0.4.15\"\n+ enable-cache: true\n+ cache-dependency-glob: |\n+ requirements**.txt\n+ pyproject.toml\n+ - name: [NAME_REDACTED] dependencies\n+ run: uv pip install -r requirements-github-actions.txt\n+ - name: Update Topic Repos\n+ run: python ./scripts/topic_repos.py\n+ env:\n+ GITHUB_TOKEN: ${{ secrets.FASTAPI_PR_TOKEN }}" }, { "filename": "docs/en/data/topic_repos.yml", "status": "added", "additions": 0, "deletions": 0, "changes": 0, "patch": null }, { "filename": "docs/en/docs/external-links.md", "status": "modified", "additions": 7, "deletions": 4, "changes": 11, "patch": "@@ -28,9 +28,12 @@ If you have an article, project, tool, or anything related to **FastAPI** that i\n {% endfor %}\n {% endfor %}\n \n-## Projects\n+## [NAME_REDACTED]\n \n-[NAME_REDACTED] projects with the topic `fastapi`:\n+Most starred GitHub repositories with the topic `fastapi`:\n \n-
      \n-
      \n+{% for repo in topic_repos %}\n+\n+★ {{repo.stars}} - {{repo.name}} by @{{repo.owner_login}}.\n+\n+{% endfor %}" }, { "filename": "docs/en/docs/js/custom.js", "status": "modified", "additions": 0, "deletions": 36, "changes": 36, "patch": "@@ -1,25 +1,3 @@\n-const div = document.querySelector('.github-topic-projects')\n-\n-async function getDataBatch(page) {\n- const response = await fetch(`https://api.github.com/search/repositories?q=topic:fastapi&per_page=100&page=${page}`, { headers: { Accept: 'application/vnd.github.mercy-preview+json' } })\n- const data = await response.json()\n- return data\n-}\n-\n-async function getData() {\n- let page = 1\n- let data = []\n- let dataBatch = await getDataBatch(page)\n- data = data.concat(dataBatch.items)\n- const totalCount = dataBatch.total_count\n- while (data.length < totalCount) {\n- page += 1\n- dataBatch = await getDataBatch(page)\n- data = data.concat(dataBatch.items)\n- }\n- return data\n-}\n-\n function setupTermynal() {\n document.querySelectorAll(\".use-termynal\").forEach(node => {\n node.style.display = \"block\";\n@@ -158,20 +136,6 @@ async function showRandomAnnouncement(groupId, timeInterval) {\n }\n \n async function main() {\n- if (div) {\n- data = await getData()\n- div.innerHTML = '
        '\n- const ul = document.querySelector('.github-topic-projects ul')\n- data.forEach(v => {\n- if (v.full_name === 'fastapi/fastapi') {\n- return\n- }\n- const li = document.createElement('li')\n- li.innerHTML = `★ ${v.stargazers_count} - ${v.full_name} by @${v.owner.login}`\n- ul.append(li)\n- })\n- }\n-\n setupTermynal();\n showRandomAnnouncement('announce-left', 5000)\n showRandomAnnouncement('announce-right', 10000)" }, { "filename": "docs/en/mkdocs.yml", "status": "modified", "additions": 1, "deletions": 0, "changes": 1, "patch": "@@ -72,6 +72,7 @@ plugins:\n - members: ../en/data/members.yml\n - sponsors_badge: ../en/data/sponsors_badge.yml\n - sponsors: ../en/data/sponsors.yml\n+ - topic_repos: ../en/data/topic_repos.yml\n redirects:\n redirect_maps:\n deployment/deta.md: deployment/cloud.md" }, { "filename": "scripts/topic_repos.py", "status": "added", "additions": 80, "deletions": 0, "changes": 80, "patch": "@@ -0,0 +1,80 @@\n+import logging\n+import secrets\n+import subprocess\n+from pathlib import Path\n+\n+import yaml\n+from github import Github\n+from pydantic import BaseModel, SecretStr\n+from pydantic_settings import BaseSettings\n+\n+\n+class Settings(BaseSettings):\n+ github_repository: str\n+ github_token: SecretStr\n+\n+\n+class Repo(BaseModel):\n+ name: str\n+ html_url: str\n+ stars: int\n+ owner_login: str\n+ owner_html_url: str\n+\n+\n+def main() -> None:\n+ logging.basicConfig(level=logging.INFO)\n+ settings = Settings()\n+\n+ logging.info(f\"Using config: {settings.model_dump_json()}\")\n+ g = Github(settings.github_token.get_secret_value(), per_page=100)\n+ r = g.get_repo(settings.github_repository)\n+ repos = g.search_repositories(query=\"topic:fastapi\")\n+ repos_list = list(repos)\n+ final_repos: list[Repo] = []\n+ for repo in repos_list[:100]:\n+ if repo.full_name == settings.github_repository:\n+ continue\n+ final_repos.append(\n+ Repo(\n+ name=repo.name,\n+ html_url=repo.html_url,\n+ stars=repo.stargazers_count,\n+ owner_login=repo.owner.login,\n+ owner_html_url=repo.owner.html_url,\n+ )\n+ )\n+ data = [repo.model_dump() for repo in final_repos]\n+\n+ # Local development\n+ # repos_path = Path(\"../docs/en/data/topic_repos.yml\")\n+ repos_path = Path(\"./docs/en/data/topic_repos.yml\")\n+ repos_old_content = repos_path.read_text(encoding=\"utf-8\")\n+ new_repos_content = yaml.dump(data, sort_keys=False, width=200, allow_unicode=True)\n+ if repos_old_content == new_repos_content:\n+ logging.info(\"The data hasn't changed. Finishing.\")\n+ return\n+ repos_path.write_text(new_repos_content, encoding=\"utf-8\")\n+ logging.info(\"Setting up GitHub Actions git user\")\n+ subprocess.run([\"git\", \"config\", \"user.name\", \"github-actions\"], check=True)\n+ subprocess.run(\n+ [\"git\", \"config\", \"user.email\", \"[EMAIL_REDACTED]\"], check=True\n+ )\n+ branch_name = f\"fastapi-topic-repos-{secrets.token_hex(4)}\"\n+ logging.info(f\"Creating a new branch {branch_name}\")\n+ subprocess.run([\"git\", \"checkout\", \"-b\", branch_name], check=True)\n+ logging.info(\"Adding updated file\")\n+ subprocess.run([\"git\", \"add\", str(repos_path)], check=True)\n+ logging.info(\"Committing updated file\")\n+ message = \"👥 Update FastAPI GitHub topic repositories\"\n+ subprocess.run([\"git\", \"commit\", \"-m\", message], check=True)\n+ logging.info(\"Pushing branch\")\n+ subprocess.run([\"git\", \"push\", \"origin\", branch_name], check=True)\n+ logging.info(\"Creating PR\")\n+ pr = r.create_pull(title=message, body=message, base=\"master\", head=branch_name)\n+ logging.info(f\"Created PR: {pr.number}\")\n+ logging.info(\"Finished\")\n+\n+\n+if __name__ == \"__main__\":\n+ main()" } ], "reviews": [ { "id": 2528178337, "user": "user_2a237e38e06b", "state": "COMMENTED", "body": "Nice! :rocket: \n\nJust a couple of nitpicks. :nerd_face:", "submitted_at": "2025-01-02T20:34:51+00:00" }, { "id": 2528185338, "user": "user_568843bce6ca", "state": "COMMENTED", "body": null, "submitted_at": "2025-01-02T20:36:38+00:00" }, { "id": 2528188918, "user": "user_2a237e38e06b", "state": "APPROVED", "body": "Nice! :rocket: :sunglasses:", "submitted_at": "2025-01-02T20:40:02+00:00" } ], "review_comments": [ { "id": 1901237015, "user": "user_2a237e38e06b", "body": "Nice! I wanted to get rid of this. :fire:", "path": "docs/en/docs/js/custom.js", "line": 173, "side": "LEFT", "created_at": "2025-01-02T20:29:55+00:00" }, { "id": 1901238644, "user": "user_2a237e38e06b", "body": "```suggestion\n return\n```\n\nI see this was from a copy of the other scripts that were run with `if __name__ == \"__main__\"`, but as this is now in a function, we can just return to finish the execution here, we don't have to call `sys.exit(0)`", "path": "scripts/topic_repos.py", "line": null, "side": "RIGHT", "created_at": "2025-01-02T20:32:24+00:00" }, { "id": 1901239554, "user": "user_2a237e38e06b", "body": "```suggestion\n```\n\nThis is probably an old copy-paste log, by [NAME_REDACTED] finished yet. :sweat_smile:\n\nThere's already a log with \"Finished\" at the end so we can just remove this one.", "path": "scripts/topic_repos.py", "line": null, "side": "RIGHT", "created_at": "2025-01-02T20:33:48+00:00" }, { "id": 1901241236, "user": "user_568843bce6ca", "body": "My bad :sweat_smile:", "path": "scripts/topic_repos.py", "line": null, "side": "RIGHT", "created_at": "2025-01-02T20:36:37+00:00" } ], "meta": { "languages": [ "js", "md", "py", "yml" ], "touches_tests": false, "review_state_summary": { "COMMENTED": 2, "APPROVED": 1 }, "meaningful_comment_count": 4, "has_approval": true, "has_changes_requested": false, "total_review_comments": 4 } } { "_id": "4e2fba2b85f83da6", "_schema_version": "1.0", "_cleaned_at": "2026-02-12T07:46:52.242325+00:00", "repo": "tiangolo/fastapi", "repo_url": "https://github.com/fastapi/fastapi", "license_name": "MIT License", "license_spdx": "MIT", "pr_number": 13114, "title": "⬆ Update httpx requirement to >=0.23.0,<0.29.0", "body": "This is similar to a later pull request https://github.com/fastapi/fastapi/pull/13130, while this PR also updates tests for newer httpx.", "author": "user_6abef8aa6d4e", "created_at": "2024-12-28T06:45:48+00:00", "merged_at": "2025-07-26T10:49:23+00:00", "base_branch": "master", "head_branch": "httpx-0.28", "additions": 7, "deletions": 5, "changed_files": 3, "files": [ { "filename": "requirements-docs-tests.txt", "status": "modified", "additions": 1, "deletions": 1, "changes": 2, "patch": "@@ -1,4 +1,4 @@\n # For mkdocstrings and tests\n-httpx >=0.23.0,<0.28.0\n+httpx >=0.23.0,<0.29.0\n # For linting and generating docs versions\n ruff ==0.11.2" }, { "filename": "requirements-github-actions.txt", "status": "modified", "additions": 1, "deletions": 1, "changes": 2, "patch": "@@ -1,6 +1,6 @@\n PyGithub>=2.3.0,<3.0.0\n pydantic>=2.5.3,<3.0.0\n pydantic-settings>=2.1.0,<3.0.0\n-httpx>=0.27.0,<0.28.0\n+httpx>=0.27.0,<0.29.0\n pyyaml >=5.3.1,<7.0.0\n smokeshow" }, { "filename": "tests/test_tutorial/test_custom_request_and_route/test_tutorial002.py", "status": "modified", "additions": 5, "deletions": 3, "changes": 8, "patch": "@@ -1,4 +1,4 @@\n-from dirty_equals import IsDict\n+from dirty_equals import IsDict, IsOneOf\n from fastapi.testclient import TestClient\n \n from docs_src.custom_request_and_route.tutorial002 import app\n@@ -24,14 +24,16 @@ def test_exception_handler_body_access():\n \"input\": {\"numbers\": [1, 2, 3]},\n }\n ],\n- \"body\": '{\"numbers\": [1, 2, 3]}',\n+ # httpx 0.28.0 switches to compact JSON https://github.com/[USER_REDACTED]ncode/httpx/issues/3363\n+ \"body\": IsOneOf('{\"numbers\": [1, 2, 3]}', '{\"numbers\":[1,2,3]}'),\n }\n }\n ) | IsDict(\n # TODO: remove when deprecating Pydantic v1\n {\n \"detail\": {\n- \"body\": '{\"numbers\": [1, 2, 3]}',\n+ # httpx 0.28.0 switches to compact JSON https://github.com/[USER_REDACTED]ncode/httpx/issues/3363\n+ \"body\": IsOneOf('{\"numbers\": [1, 2, 3]}', '{\"numbers\":[1,2,3]}'),\n \"errors\": [\n {\n \"loc\": [\"body\"]," } ], "reviews": [ { "id": 3018986979, "user": "user_29e85f9a8e75", "state": "CHANGES_REQUESTED", "body": "Let's simplify tests a bit by using `dirty_equals.IsOneOf`?", "submitted_at": "2025-07-15T07:09:34+00:00" }, { "id": 3035360520, "user": "user_29e85f9a8e75", "state": "APPROVED", "body": "LGTM", "submitted_at": "2025-07-19T12:20:40+00:00" }, { "id": 3058003166, "user": "user_2a237e38e06b", "state": "APPROVED", "body": "Nice, thanks! 🚀", "submitted_at": "2025-07-26T10:49:13+00:00" } ], "review_comments": [ { "id": 2206602037, "user": "user_29e85f9a8e75", "body": "We can avoid duplicating this with the help of `dirty_equals.IsOneOf`:\n```python\n {\n \"detail\": {\n \"errors\": [\n {\n \"type\": \"list_type\",\n \"loc\": [\"body\"],\n \"msg\": \"Input should be a valid list\",\n \"input\": {\"numbers\": [1, 2, 3]},\n }\n ],\n \"body\": IsOneOf('{\"numbers\": [1, 2, 3]}', '{\"numbers\":[1,2,3]}'),\n }\n }\n\n```", "path": "tests/test_tutorial/test_custom_request_and_route/test_tutorial002.py", "line": null, "side": "RIGHT", "created_at": "2025-07-15T07:08:50+00:00" } ], "meta": { "languages": [ "py", "txt" ], "touches_tests": true, "review_state_summary": { "CHANGES_REQUESTED": 1, "APPROVED": 2 }, "meaningful_comment_count": 1, "has_approval": true, "has_changes_requested": true, "total_review_comments": 1 } } { "_id": "5c93d489eb9e2350", "_schema_version": "1.0", "_cleaned_at": "2026-02-12T07:46:52.242325+00:00", "repo": "tiangolo/fastapi", "repo_url": "https://github.com/fastapi/fastapi", "license_name": "MIT License", "license_spdx": "MIT", "pr_number": 13093, "title": "🌐 Add Korean translation for `docs/ko/docs/tutorial/sql-databases.md`", "body": "This PR translates docs/ko/docs/tutorial/sql-databases.md in Korean.\nrelated: #3167", "author": "user_5af78042eb56", "created_at": "2024-12-18T09:56:14+00:00", "merged_at": "2024-12-24T16:14:29+00:00", "base_branch": "master", "head_branch": "translate-sql-databases-ko", "additions": 360, "deletions": 0, "changed_files": 1, "files": [ { "filename": "docs/ko/docs/tutorial/sql-databases.md", "status": "added", "additions": 360, "deletions": 0, "changes": 360, "patch": "@@ -0,0 +1,360 @@\n+# SQL (관계형) 데이터베이스\n+\n+**FastAPI**에서 SQL(관계형) 데이터베이스 사용은 필수가 아닙니다. 여러분이 원하는 **어떤 데이터베이스든** 사용할 수 있습니다.\n+\n+여기서는 SQLModel을 사용하는 예제를 살펴보겠습니다.\n+\n+**SQLModel**은 SQLAlchemy와 Pydantic을 기반으로 구축되었습니다.SQLModel은 **SQL 데이터베이스**를 사용하는 FastAPI 애플리케이션에 완벽히 어울리도록 **FastAPI**의 제작자가 설계한 도구입니다.\n+\n+/// tip | 팁\n+\n+다른 SQL 또는 NoSQL 데이터베이스 라이브러리를 사용할 수도 있습니다 (일부는 \"ORM\"이라고도 불립니다), FastAPI는 특정 라이브러리의 사용을 강요하지 않습니다. 😎\n+\n+///\n+\n+SQLModel은 SQLAlchemy를 기반으로 하므로, SQLAlchemy에서 **지원하는 모든 데이터베이스**를 손쉽게 사용할 수 있습니다(SQLModel에서도 동일하게 지원됩니다). 예를 들면:\n+\n+* PostgreSQL\n+* MySQL\n+* SQLite\n+* Oracle\n+* Microsoft SQL Server 등.\n+\n+이 예제에서는 **SQLite**를 사용합니다. SQLite는 단일 파일을 사용하고 파이썬에서 기본적으로 지원하기 때문입니다. 따라서 이 예제를 그대로 복사하여 실행할 수 있습니다.\n+\n+나중에 실제 프로덕션 애플리케이션에서는 **PostgreSQL**과 같은 데이터베이스 서버를 사용하는 것이 좋습니다.\n+\n+/// tip | 팁\n+\n+**FastAPI**와 **PostgreSQL**를 포함하여 프론트엔드와 다양한 도구를 제공하는 공식 프로젝트 생성기가 있습니다: https://github.com/fastapi/full-stack-fastapi-template\n+\n+///\n+\n+이 튜토리얼은 매우 간단하고 짧습니다. 데이터베이스 기본 개념, SQL, 또는 더 복잡한 기능에 대해 배우고 싶다면, SQLModel 문서를 참고하세요.\n+\n+## `SQLModel` 설치하기\n+\n+먼저, [가상 환경](../virtual-environments.md){.internal-link target=_blank}을 생성하고 활성화한 다음, `sqlmodel`을 설치하세요:\n+\n+
        \n+\n+```console\n+$ pip install sqlmodel\n+---> 100%\n+```\n+\n+
        \n+\n+## 단일 모델로 애플리케이션 생성하기\n+\n+우선 단일 **SQLModel** 모델을 사용하여 애플리케이션의 가장 간단한 첫 번째 버전을 생성해보겠습니다.\n+\n+이후 **다중 모델**을 추가하여 보안과 유연성을 강화할 것입니다. 🤓\n+\n+### 모델 생성하기\n+\n+`SQLModel`을 가져오고 데이터베이스 모델을 생성합니다:\n+\n+{* ../../docs_src/sql_databases/tutorial001_an_py310.py ln[1:11] hl[7:11] *}\n+\n+`Hero` 클래스는 Pydantic 모델과 매우 유사합니다 (실제로 내부적으로 *Pydantic 모델이기도 합니다*).\n+\n+몇 가지 차이점이 있습니다:\n+\n+* `table=True`는 SQLModel에 이 모델이 *테이블 모델*이며, 단순한 데이터 모델이 아니라 SQL 데이터베이스의 **테이블**을 나타낸다는 것을 알려줍니다. (다른 일반적인 Pydantic 클래스처럼) 단순한 *데이터 모델*이 아닙니다.\n+\n+* `Field(primary_key=True)`는 SQLModel에 `id`가 SQL 데이터베이스의 **기본 키**임을 알려줍니다 (SQL 기본 키에 대한 자세한 내용은 SQLModel 문서를 참고하세요).\n+\n+ `int | None` 유형으로 설정하면, SQLModel은 해당 열이 SQL 데이터베이스에서 `INTEGER` 유형이며 `NULLABLE` 값이어야 한다는 것을 알 수 있습니다.\n+\n+* `Field(index=True)`는 SQLModel에 해당 열에 대해 **SQL 인덱스**를 생성하도록 지시합니다. 이를 통해 데이터베이스에서 이 열으로 필터링된 데이터를 읽을 때 더 빠르게 조회할 수 있습니다.\n+\n+ SQLModel은 `str`으로 선언된 항목이 SQL 데이터베이스에서 `TEXT` (또는 데이터베이스에 따라 `VARCHAR`) 유형의 열로 저장된다는 것을 인식합니다.\n+\n+### 엔진 생성하기\n+\n+SQLModel의 `engine` (내부적으로는 SQLAlchemy `engine`)은 데이터베이스에 대한 **연결을 유지**하는 역할을 합니다.\n+\n+**하나의 단일 engine 객체**를 통해 코드 전체에서 동일한 데이터베이스에 연결할 수 있습니다.\n+\n+{* ../../docs_src/sql_databases/tutorial001_an_py310.py ln[14:18] hl[14:15,17:18] *}\n+\n+`check_same_thread=False`를 사용하면 FastAPI에서 여러 스레드에서 동일한 SQLite 데이터베이스를 사용할 수 있습니다. 이는 **하나의 단일 요청**이 **여러 스레드**를 사용할 수 있기 때문에 필요합니다(예: 의존성에서 사용되는 경우).\n+\n+걱정하지 마세요. 코드가 구조화된 방식으로 인해, 이후에 **각 요청마다 단일 SQLModel *세션*을 사용**하도록 보장할 것입니다. 실제로 그것이 `check_same_thread`가 하려는 것입니다.\n+\n+### 테이블 생성하기\n+\n+그 다음 `SQLModel.metadata.create_all(engine)`을 사용하여 모든 *테이블 모델*의 **테이블을 생성**하는 함수를 추가합니다.\n+\n+{* ../../docs_src/sql_databases/tutorial001_an_py310.py ln[21:22] hl[21:22] *}\n+\n+### 세션 의존성 생성하기\n+\n+**`Session`**은 **메모리에 객체**를 저장하고 데이터에 필요한 모든 변경 사항을 추적한 후, **`engine`을 통해** 데이터베이스와 통신합니다.\n+\n+`yield`를 사용해 FastAPI의 **의존성**을 생성하여 각 요청마다 새로운 `Session`을 제공합니다. 이는 요청당 하나의 세션만 사용되도록 보장합니다. 🤓\n+\n+그런 다음 이 의존성을 사용하는 코드를 간소화하기 위해 `Annotated` 의존성 `SessionDep`을 생성합니다.\n+\n+{* ../../docs_src/sql_databases/tutorial001_an_py310.py ln[25:30] hl[25:27,30] *}\n+\n+### 시작 시 데이터베이스 테이블 생성하기\n+\n+애플리케이션 시작 시 데이터베이스 테이블을 생성합니다.\n+\n+{* ../../docs_src/sql_databases/tutorial001_an_py310.py ln[32:37] hl[35:37] *}\n+\n+여기서는 애플리케이션 시작 이벤트 시 테이블을 생성합니다.\n+\n+프로덕션 환경에서는 애플리케이션을 시작하기 전에 실행되는 마이그레이션 스크립트를 사용할 가능성이 높습니다. 🤓\n+\n+/// tip | 팁\n+\n+SQLModel은 Alembic을 감싸는 마이그레이션 유틸리티를 제공할 예정입니다. 하지만 현재 Alembic을 직접 사용할 수 있습니다.\n+\n+///\n+\n+### Hero 생성하기\n+\n+각 SQLModel 모델은 Pydantic 모델이기도 하므로, Pydantic 모델을 사용할 수 있는 **타입 어노테이**션에서 동일하게 사용할 수 있습니다.\n+\n+예를 들어, 파라미터를 `Hero` 타입으로 선언하면 **JSON 본문**에서 값을 읽어옵니다.\n+\n+마찬가지로, 함수의 **반환 타입**으로 선언하면 해당 데이터의 구조가 자동으로 생성되는 API 문서의 UI에 나타납니다.\n+\n+{* ../../docs_src/sql_databases/tutorial001_an_py310.py ln[40:45] hl[40:45] *}\n+\n+\n+\n+여기서 `SessionDep` 의존성 (즉, `Session`)을 사용하여 새로운 `Hero`를 `Session` 인스턴스에 추가하고, 데이터베이스에 변경 사항을 커밋하고, `hero` 데이터의 최신 상태를 갱신한 다음 이를 반환합니다.\n+\n+### Heroes 조회하기\n+\n+`select()`를 사용하여 데이터베이스에서 `Hero`를 **조회**할 수 있습니다. 결과에 페이지네이션을 적용하기 위해 `limit`와 `offset`을 포함할 수 있습니다.\n+\n+{* ../../docs_src/sql_databases/tutorial001_an_py310.py ln[48:55] hl[51:52,54] *}\n+\n+### 단일 Hero 조회하기\n+\n+단일 `Hero`를 **조회**할 수도 있습니다.\n+\n+{* ../../docs_src/sql_databases/tutorial001_an_py310.py ln[58:63] hl[60] *}\n+\n+### Hero 삭제하기\n+\n+`Hero`를 **삭제**하는 것도 가능합니다.\n+\n+{* ../../docs_src/sql_databases/tutorial001_an_py310.py ln[66:73] hl[71] *}\n+\n+### 애플리케이션 실행하기\n+\n+애플리케이션을 실행하려면 다음 명령을 사용합니다:\n+\n+
        \n+\n+```console\n+$ fastapi dev main.py\n+\n+INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit)\n+```\n+\n+
        \n+\n+그런 다음 `/docs` UI로 이동하면, **FastAPI**가 해당 **model들**을 사용하여 API **문서를 생성**하는 것으르 확인할 수 있습니다. 또한 이 모델들은 데이터를 직렬화하고 검증하는 데에도 사용됩니다.\n+\n+
        \n+\n+
        \n+\n+## 여러 모델로 애플리케이션 업데이트\n+\n+이제 애플리케이션을 약간 **리팩토링**하여 **보안**과 **유연성**을 개선해 보겠습니다.\n+\n+이전 애플리케이션의 UI를 보면, 지금까지는 클라이언트가 생성할 `Hero`의 `id`를 직접 지정할 수 있다는 것을 알 수 있습니다. 😱\n+\n+이는 허용되어선 안 됩니다. 클라이언트가 이미 데이터베이스에 저장된 `id`를 덮어쓸 위험이 있기 때문입니다. `id`는 **백엔드** 또는 **데이터베이스**가 결정해야 하며, **클라이언트**가 결정해서는 안 됩니다.\n+\n+또한 hero의 `secret_name`을 생성하긴 했지만, 지금까지는 이 값을 어디에서나 반환하고 있습니다. 이는 그다지 **비밀스럽지** 않습니다... 😅\n+\n+이러한 문제를 해결하기 위해 몇 가지 **추가 모델**을 추가할 것입니다. 바로 여기서 SQLModel이 빛을 발하게 됩니다. ✨\n+\n+### 여러 모델 생성하기\n+\n+**SQLModel**에서 `table=True`가 설정된 모델 클래스는 **테이블 모델**입니다.\n+\n+`table=True`가 없는 모델 클래스는 **데이터 모델**로, 이는 실제로 몇 가지 추가 기능이 포함된 Pydantic 모델에 불과합니다. 🤓\n+\n+SQLModel을 사용하면 **상속**을 통해 모든 경우에 필드를 **중복 선언하지 않아도** 됩니다.\n+\n+#### `HeroBase` - 기본 클래스\n+\n+모든 모델에서 **공유되는 필드**를 가진 `HeroBase` 모델을 시작해 봅시다:\n+\n+* `name`\n+* `age`\n+\n+{* ../../docs_src/sql_databases/tutorial002_an_py310.py ln[7:9] hl[7:9] *}\n+\n+#### `Hero` - *테이블 모델*\n+\n+다음으로 실제 *테이블 모델*인 `Hero`를 생성합니다. 이 모델은 다른 모델에는 항상 포함되는 건 아닌 **추가 필드**를 포함합니다:\n+\n+* `id`\n+* `secret_name`\n+\n+`Hero`는 `HeroBase`를 상속하므로 `HeroBase`에 선언된 필드도 포함합니다. 따라서 `Hero`는 다음 **필드들도** 가지게 됩니다:\n+\n+* `id`\n+* `name`\n+* `age`\n+* `secret_name`\n+\n+{* ../../docs_src/sql_databases/tutorial002_an_py310.py ln[7:14] hl[12:14] *}\n+\n+#### `HeroPublic` - 공개 *데이터 모델*\n+\n+다음으로 `HeroPublic` 모델을 생성합니다. 이 모델은 API 클라이언트에 **반환**되는 모델입니다.\n+\n+`HeroPublic`은 `HeroBase`와 동일한 필드를 가지며, `secret_name`은 포함하지 않습니다.\n+\n+마침내 우리의 heroes의 정체가 보호됩니다! 🥷\n+\n+또한 `id: int`를 다시 선언합니다. 이를 통해, API 클라이언트와 **계약**을 맺어 `id`가 항상 존재하며 항상 `int` 타입이라는 것을 보장합니다(`None`이 될 수 없습니다).\n+\n+/// tip | 팁\n+\n+반환 모델이 값이 항상 존재하고 항상 `int`(`None`이 아님)를 보장하는 것은 API 클라이언트에게 매우 유용합니다. 이를 통해 API와 통신하는 개발자가 훨씬 더 간단한 코드를 작성할 수 있습니다.\n+\n+또한 **자동으로 생성된 클라이언트**는 더 단순한 인터페이스를 제공하므로, API와 소통하는 개발자들이 훨씬 수월하게 작업할 수 있습니다. 😎\n+\n+///\n+\n+`HeroPublic`의 모든 필드는 `HeroBase`와 동일하며, `id`는 `int`로 선언됩니다(`None`이 아님):\n+\n+* `id`\n+* `name`\n+* `age`\n+* `secret_name`\n+\n+{* ../../docs_src/sql_databases/tutorial002_an_py310.py ln[7:18] hl[17:18] *}\n+\n+#### `HeroCreate` - hero 생성용 *데이터 모델*\n+\n+이제 `HeroCreate` 모델을 생성합니다. 이 모델은 클라이언트로부터 받은 데이터를 **검증**하는 역할을 합니다.\n+\n+`HeroCreate`는 `HeroBase와` 동일한 필드를 가지며, 추가로 `secret_name을` 포함합니다.\n+\n+클라이언트가 **새 hero을 생성**할 때 `secret_name`을 보내고, 이는 데이터베이스에 저장되지만, 해당 비밀 이름은 API를 통해 클라이언트에게 반환되지 않습니다.\n+\n+/// tip | 팁\n+\n+이 방식은 **비밀번호**를 처리하는 방법과 동일합니다. 비밀번호를 받지만, 이를 API에서 반환하지는 않습니다.\n+\n+비밀번호 값을 저장하기 전에 **해싱**하여 저장하고, **평문으로 저장하지 마십시오**.\n+\n+///\n+\n+`HeroCreate`의 필드는 다음과 같습니다:\n+\n+* `name`\n+* `age`\n+* `secret_name`\n+\n+{* ../../docs_src/sql_databases/tutorial002_an_py310.py ln[7:22] hl[21:22] *}\n+\n+#### `HeroUpdate` - hero 수정용 *데이터 모델*\n+\n+이전 애플리케이션에서는 **hero를 수정**할 방법이 없었지만, 이제 **다중 모델**을 통해 수정 기능을 추가할 수 있습니다. 🎉\n+\n+`HeroUpdate` *데이터 모델*은 약간 특별한데, 새 hero을 생성할 때 필요한 **모든 동일한 필드**를 가지지만, 모든 필드가 **선택적**(기본값이 있음)입니다. 이렇게 하면 hero을 수정할 때 수정하려는 필드만 보낼 수 있습니다.\n+\n+모든 **필드가 변경되기** 때문에(타입이 `None`을 포함하고, 기본값이 `None`으로 설정됨), 모든 필드를 **다시 선언**해야 합니다.\n+\n+엄밀히 말하면 `HeroBase`를 상속할 필요는 없습니다. 모든 필드를 다시 선언하기 때문입니다. 일관성을 위해 상속을 유지하긴 했지만, 필수는 아닙니다. 이는 개인적인 취향의 문제입니다. 🤷\n+\n+`HeroUpdate`의 필드는 다음과 같습니다:\n+\n+* `name`\n+* `age`\n+* `secret_name`\n+\n+{* ../../docs_src/sql_databases/tutorial002_an_py310.py ln[7:28] hl[25:28] *}\n+\n+### `HeroCreate`로 생성하고 `HeroPublic` 반환하기\n+\n+이제 **다중 모델**을 사용하므로 애플리케이션의 관련 부분을 업데이트할 수 있습니다.\n+\n+요청에서 `HeroCreate` *데이터 모델*을 받아 이를 기반으로 `Hero` *테이블 모델*을 생성합니다.\n+\n+이 새 *테이블 모델* `Hero`는 클라이언트에서 보낸 필드를 가지며, 데이터베이스에서 생성된 `id`도 포함합니다.\n+\n+그런 다음 함수를 통해 동일한 *테이블 모델* `Hero`를 반환합니다. 하지만 `response_model`로 `HeroPublic` *데이터 모델*을 선언했기 때문에, **FastAPI**는 `HeroPublic`을 사용하여 데이터를 검증하고 직렬화합니다.\n+\n+{* ../../docs_src/sql_databases/tutorial002_an_py310.py ln[56:62] hl[56:58] *}\n+\n+/// tip | 팁\n+\n+이제 **반환 타입 주석** `-> HeroPublic` 대신 `response_model=HeroPublic`을 사용합니다. 반환하는 값이 실제로 `HeroPublic`이 *아니기* 때문입니다.\n+\n+만약 `-> HeroPublic`으로 선언했다면, 에디터와 린터에서 반환값이 `HeroPublic`이 아니라 `Hero`라고 경고했을 것입니다. 이는 적절한 경고입니다.\n+\n+`response_model`에 선언함으로써 **FastAPI**가 이를 처리하도록 하고, 타입 어노테이션과 에디터 및 다른 도구의 도움에는 영향을 미치지 않도록 설정합니다.\n+\n+///\n+\n+### `HeroPublic`으로 Heroes 조회하기\n+\n+이전과 동일하게 `Hero`를 **조회**할 수 있습니다. 이번에도 `response_model=list[HeroPublic]`을 사용하여 데이터가 올바르게 검증되고 직렬화되도록 보장합니다.\n+\n+{* ../../docs_src/sql_databases/tutorial002_an_py310.py ln[65:72] hl[65] *}\n+\n+### `HeroPublic`으로 단일 Hero 조회하기\n+\n+단일 hero을 **조회**할 수도 있습니다:\n+\n+{* ../../docs_src/sql_databases/tutorial002_an_py310.py ln[75:80] hl[77] *}\n+\n+### `HeroUpdate`로 Hero 수정하기\n+\n+**hero를 수정**할 수도 있습니다. 이를 위해 HTTP `PATCH` 작업을 사용합니다.\n+\n+코드에서는 클라이언트가 보낸 데이터를 딕셔너리 형태(`dict`)로 가져옵니다. 이는 **클라이언트가 보낸 데이터만 포함**하며, 기본값으로 들어가는 값은 제외합니다. 이를 위해 `exclude_unset=True`를 사용합니다. 이것이 주요 핵심입니다. 🪄\n+\n+그런 다음, `hero_db.sqlmodel_update(hero_data)`를 사용하여 `hero_data`의 데이터를 `hero_db`에 업데이트합니다.\n+\n+{* ../../docs_src/sql_databases/tutorial002_an_py310.py ln[83:93] hl[83:84,88:89] *}\n+\n+### Hero 다시 삭제하기\n+\n+hero **삭제**는 이전과 거의 동일합니다.\n+\n+이번에는 모든 것을 리팩토링하고 싶은 욕구를 만족시키지 못할 것 같습니다. 😅\n+\n+{* ../../docs_src/sql_databases/tutorial002_an_py310.py ln[96:103] hl[101] *}\n+\n+### 애플리케이션 다시 실행하기\n+\n+다음 명령을 사용해 애플리케이션을 다시 실행할 수 있습니다:\n+\n+
        \n+\n+```console\n+$ fastapi dev main.py\n+\n+INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit)\n+```\n+\n+
        \n+\n+`/docs` API UI로 이동하면 업데이트된 것을 확인할 수 있습니다. 클라이언트가 영웅을 생성할 때 `id`를 제공할 필요가 없게 되는 등의 변화도 보입니다.\n+\n+
        \n+\n+
        \n+\n+## 요약\n+\n+**SQLModel**을 사용하여 SQL 데이터베이스와 상호작용하고, *데이터 모델* 및 *테이블 모델*로 코드를 간소화할 수 있습니다.\n+\n+더 많은 내용을 배우고 싶다면, **SQLModel** 문서를 참고하세요. SQLModel을 **FastAPI**와 함께 사용하는 것에 대한 더 긴 미니 튜토리얼도 제공합니다. 🚀" } ], "reviews": [ { "id": 2513140368, "user": "user_7e930c559d4e", "state": "COMMENTED", "body": "Great job! I've reviewed it, so please check it out 😄", "submitted_at": "2024-12-19T02:15:38+00:00" }, { "id": 2518669881, "user": "user_ed8298a0306d", "state": "APPROVED", "body": null, "submitted_at": "2024-12-21T14:31:48+00:00" }, { "id": 2519916027, "user": "user_7e930c559d4e", "state": "APPROVED", "body": "LGTM 🚀 \nIt's unimportant, but it's better for other reviewers if you \"resolve\" reviewed comments.", "submitted_at": "2024-12-23T05:29:19+00:00" } ], "review_comments": [ { "id": 1891015184, "user": "user_7e930c559d4e", "body": "```suggestion\n이 예제에서는 **SQLite**를 사용합니다. SQLite는 단일 파일을 사용하고 파이썬에서 기본적으로 지원하기 때문입니다. 따라서 이 예제를 그대로 복사하여 실행할 수 있습니다.\n```", "path": "docs/ko/docs/tutorial/sql-databases.md", "line": null, "side": "RIGHT", "created_at": "2024-12-19T01:19:19+00:00" }, { "id": 1891016116, "user": "user_7e930c559d4e", "body": "```suggestion\n/// tip | 팁\n```\nSee [Translation specific tips and guidelines](https://fastapi.tiangolo.com/contributing/#translation-specific-tips-and-guidelines).", "path": "docs/ko/docs/tutorial/sql-databases.md", "line": null, "side": "RIGHT", "created_at": "2024-12-19T01:21:08+00:00" }, { "id": 1891017125, "user": "user_7e930c559d4e", "body": "```suggestion\n`Hero` 클래스는 Pydantic 모델과 매우 유사합니다 (실제로 내부적으로 *Pydantic 모델이기도 합니다*).\n```\nmissed.", "path": "docs/ko/docs/tutorial/sql-databases.md", "line": null, "side": "RIGHT", "created_at": "2024-12-19T01:23:10+00:00" }, { "id": 1891020773, "user": "user_7e930c559d4e", "body": "```suggestion\n `int | None` 유형으로 설정하면, SQLModel은 해당 열이 SQL 데이터베이스에서 `INTEGER` 유형이며 `NULLABLE` 값이어야 한다는 것을 알 수 있습니다.\n```\nIt's natural, but you should follow the guidelines I mentioned above.\n\nIn the guidelines:\n> Do not change anything enclosed in \"``\" (inline code).", "path": "docs/ko/docs/tutorial/sql-databases.md", "line": null, "side": "RIGHT", "created_at": "2024-12-19T01:29:21+00:00" }, { "id": 1891023904, "user": "user_7e930c559d4e", "body": "Translating \"column\" to \"열\" is okay; it's not good for readers to use the same term with multiple terms.\nIn this case, \"열\" and \"컬럼\". Please translate it into one of the two.", "path": "docs/ko/docs/tutorial/sql-databases.md", "line": null, "side": "RIGHT", "created_at": "2024-12-19T01:35:10+00:00" }, { "id": 1891027954, "user": "user_7e930c559d4e", "body": "```suggestion\n**하나의 단일 `engine` 객체**를 통해 코드 전체에서 동일한 데이터베이스에 연결할 수 있습니다.\n```", "path": "docs/ko/docs/tutorial/sql-databases.md", "line": 78, "side": "RIGHT", "created_at": "2024-12-19T01:42:44+00:00" }, { "id": 1891029575, "user": "user_7e930c559d4e", "body": "```suggestion\n/// tip | 팁\n```", "path": "docs/ko/docs/tutorial/sql-databases.md", "line": null, "side": "RIGHT", "created_at": "2024-12-19T01:46:03+00:00" }, { "id": 1891030884, "user": "user_7e930c559d4e", "body": "```suggestion\n그런 다음 `/docs` UI로 이동하면, **FastAPI**가 해당 **model들**을 사용하여 API **문서를 생성**하는 것으르 확인할 수 있습니다. 또한 이 모델들은 데이터를 **직렬화**하고 **검증**하는 데에도 사용됩니다.\n```\nmissed bold.", "path": "docs/ko/docs/tutorial/sql-databases.md", "line": 164, "side": "RIGHT", "created_at": "2024-12-19T01:48:29+00:00" }, { "id": 1891033053, "user": "user_7e930c559d4e", "body": "```suggestion\n`table=True`가 없는 모델 클래스는 **데이터 모델**로, 이는 실제로 (몇 가지 추가 기능이 포함된) Pydantic 모델에 불과합니다. 🤓\n```\nIt does not matter, but you should respect the original sentence.", "path": "docs/ko/docs/tutorial/sql-databases.md", "line": 186, "side": "RIGHT", "created_at": "2024-12-19T01:52:29+00:00" }, { "id": 1891034400, "user": "user_7e930c559d4e", "body": "Untranslated 😂", "path": "docs/ko/docs/tutorial/sql-databases.md", "line": null, "side": "RIGHT", "created_at": "2024-12-19T01:54:41+00:00" }, { "id": 1891035301, "user": "user_7e930c559d4e", "body": "```suggestion\n/// tip | 팁\n```", "path": "docs/ko/docs/tutorial/sql-databases.md", "line": null, "side": "RIGHT", "created_at": "2024-12-19T01:56:09+00:00" }, { "id": 1891044581, "user": "user_7e930c559d4e", "body": "```suggestion\n/// tip | 팁\n```", "path": "docs/ko/docs/tutorial/sql-databases.md", "line": null, "side": "RIGHT", "created_at": "2024-12-19T02:12:35+00:00" }, { "id": 1891044898, "user": "user_7e930c559d4e", "body": "```suggestion\n`HeroUpdate`의 필드는 다음과 같습니다:\n```\nMissed backtick", "path": "docs/ko/docs/tutorial/sql-databases.md", "line": null, "side": "RIGHT", "created_at": "2024-12-19T02:13:14+00:00" }, { "id": 1891045149, "user": "user_7e930c559d4e", "body": "```suggestion\n/// 팁 | tip\n```", "path": "docs/ko/docs/tutorial/sql-databases.md", "line": null, "side": "RIGHT", "created_at": "2024-12-19T02:13:45+00:00" } ], "meta": { "languages": [ "md" ], "touches_tests": false, "review_state_summary": { "COMMENTED": 1, "APPROVED": 2 }, "meaningful_comment_count": 14, "has_approval": true, "has_changes_requested": false, "total_review_comments": 14 } } { "_id": "cae0993f360b343f", "_schema_version": "1.0", "_cleaned_at": "2026-02-12T07:46:52.242325+00:00", "repo": "tiangolo/fastapi", "repo_url": "https://github.com/fastapi/fastapi", "license_name": "MIT License", "license_spdx": "MIT", "pr_number": 13091, "title": "🌐 Add Chinese translation for `docs/zh/docs/advanced/openapi-webhooks.md`", "body": "Add Chinese translation for `docs/zh/docs/advanced/openapi-webhooks.md`.\n给 `docs/zh/docs/advanced/openapi-webhooks.md` 增加了中文翻译。", "author": "user_6fcb07a75ce9", "created_at": "2024-12-18T01:23:06+00:00", "merged_at": "2024-12-19T15:30:39+00:00", "base_branch": "master", "head_branch": "translate/openapi_webhooks", "additions": 55, "deletions": 0, "changed_files": 1, "files": [ { "filename": "docs/zh/docs/advanced/openapi-webhooks.md", "status": "added", "additions": 55, "deletions": 0, "changes": 55, "patch": "@@ -0,0 +1,55 @@\n+# OpenAPI 网络钩子\n+\n+有些情况下,您可能想告诉您的 API **用户**,您的应用程序可以携带一些数据调用*他们的*应用程序(给它们发送请求),通常是为了**通知**某种**事件**。\n+\n+这意味着,除了您的用户向您的 API 发送请求的一般情况,**您的 API**(或您的应用)也可以向**他们的系统**(他们的 API、他们的应用)**发送请求**。\n+\n+这通常被称为**网络钩子**(Webhook)。\n+\n+## 使用网络钩子的步骤\n+\n+通常的过程是**您**在代码中**定义**要发送的消息,即**请求的主体**。\n+\n+您还需要以某种方式定义您的应用程序将在**何时**发送这些请求或事件。\n+\n+**用户**会以某种方式(例如在某个网页仪表板上)定义您的应用程序发送这些请求应该使用的 **URL**。\n+\n+所有关于注册网络钩子的 URL 的**逻辑**以及发送这些请求的实际代码都由您决定。您可以在**自己的代码**中以任何想要的方式来编写它。\n+\n+## 使用 `FastAPI` 和 OpenAPI 文档化网络钩子\n+\n+使用 **FastAPI**,您可以利用 OpenAPI 来自定义这些网络钩子的名称、您的应用可以发送的 HTTP 操作类型(例如 `POST`、`PUT` 等)以及您的应用将发送的**请求体**。\n+\n+这能让您的用户更轻松地**实现他们的 API** 来接收您的**网络钩子**请求,他们甚至可能能够自动生成一些自己的 API 代码。\n+\n+/// info\n+\n+网络钩子在 OpenAPI 3.1.0 及以上版本中可用,FastAPI `0.99.0` 及以上版本支持。\n+\n+///\n+\n+## 带有网络钩子的应用程序\n+\n+当您创建一个 **FastAPI** 应用程序时,有一个 `webhooks` 属性可以用来定义网络钩子,方式与您定义*路径操作*的时候相同,例如使用 `[USER_REDACTED].webhooks.post()` 。\n+\n+{* ../../docs_src/openapi_webhooks/tutorial001.py hl[9:13,36:53] *}\n+\n+您定义的网络钩子将被包含在 `OpenAPI` 的架构中,并出现在自动生成的**文档 UI** 中。\n+\n+/// info\n+\n+`app.webhooks` 对象实际上只是一个 `APIRouter` ,与您在使用多个文件来构建应用程序时所使用的类型相同。\n+\n+///\n+\n+请注意,使用网络钩子时,您实际上并没有声明一个*路径*(比如 `/items/` ),您传递的文本只是这个网络钩子的**标识符**(事件的名称)。例如在 `[USER_REDACTED].webhooks.post(\"new-subscription\")` 中,网络钩子的名称是 `new-subscription` 。\n+\n+这是因为我们预计**您的用户**会以其他方式(例如通过网页仪表板)来定义他们希望接收网络钩子的请求的实际 **URL 路径**。\n+\n+### 查看文档\n+\n+现在您可以启动您的应用程序并访问 http://127.0.0.1:8000/docs.\n+\n+您会看到您的文档不仅有正常的*路径操作*显示,现在还多了一些**网络钩子**:\n+\n+" } ], "reviews": [ { "id": 2512730771, "user": "user_d7f5981f1dc1", "state": "CHANGES_REQUESTED", "body": "辛苦了!这是一些修改建议,供您参考!", "submitted_at": "2024-12-18T20:12:58+00:00" }, { "id": 2513373184, "user": "user_d7f5981f1dc1", "state": "APPROVED", "body": "LGTM :)", "submitted_at": "2024-12-19T05:20:45+00:00" }, { "id": 2513433890, "user": "user_acb6f8f8de23", "state": "APPROVED", "body": null, "submitted_at": "2024-12-19T06:06:46+00:00" } ], "review_comments": [ { "id": 1890756032, "user": "user_d7f5981f1dc1", "body": "有点小怪,改个语序试试🥰\n\n```suggestion\n有些情况下,您可能想告诉您的 API **用户**,您的应用程序可以携带一些数据调用*他们的*应用程序(给它们发送请求),通常是为了**通知**某种**事件**。\n```\n\n(遇到这种情况可以考虑一下是不是中文状语位置和英文不一样导致的)", "path": "docs/zh/docs/advanced/openapi-webhooks.md", "line": null, "side": "RIGHT", "created_at": "2024-12-18T19:45:46+00:00" }, { "id": 1890766772, "user": "user_d7f5981f1dc1", "body": "```suggestion\n这意味着,除了您的用户向您的 API 发送请求的一般情况,**您的 API**(或您的应用)也可以向**他们的系统**(他们的 API、他们的应用)**发送请求**。\n```\n\n- \"instead of\" 也可以对应汉语中的“除了……也”联词\n- 英文逗号 \",\" 在某些情况下可以尝试翻译为汉语顿号“、”", "path": "docs/zh/docs/advanced/openapi-webhooks.md", "line": null, "side": "RIGHT", "created_at": "2024-12-18T19:55:54+00:00" }, { "id": 1890769908, "user": "user_d7f5981f1dc1", "body": "```suggestion\n**用户**会以某种方式(例如在某个网页仪表板上)定义您的应用程序发送这些请求应该使用的 **URL**。\n```", "path": "docs/zh/docs/advanced/openapi-webhooks.md", "line": null, "side": "RIGHT", "created_at": "2024-12-18T19:58:59+00:00" }, { "id": 1890770877, "user": "user_d7f5981f1dc1", "body": "```suggestion\n所有关于注册网络钩子的 URL 的**逻辑**以及发送这些请求的实际代码都由您决定。您可以在**自己的代码**中以任何想要的方式来编写它。\n```", "path": "docs/zh/docs/advanced/openapi-webhooks.md", "line": null, "side": "RIGHT", "created_at": "2024-12-18T19:59:55+00:00" }, { "id": 1890776025, "user": "user_d7f5981f1dc1", "body": "```suggestion\n使用 **FastAPI**,您可以利用 OpenAPI 来自定义这些网络钩子的名称、您的应用可以发送的 HTTP 操作类型(例如 `POST`、`PUT` 等)以及您的应用将发送的**请求体**。\n```\n\n- 修复歧义\n- Yes 中英文之间应当空格,but also 一些中文标点符号可以视为自带空格", "path": "docs/zh/docs/advanced/openapi-webhooks.md", "line": null, "side": "RIGHT", "created_at": "2024-12-18T20:05:20+00:00" }, { "id": 1890778258, "user": "user_d7f5981f1dc1", "body": "```suggestion\n### 查看文档\n```", "path": "docs/zh/docs/advanced/openapi-webhooks.md", "line": null, "side": "RIGHT", "created_at": "2024-12-18T20:07:46+00:00" }, { "id": 1890782550, "user": "user_d7f5981f1dc1", "body": "这样会稍通顺一些,供您参考。\n\n```suggestion\n您会看到您的文档不仅有正常的*路径操作*显示,现在还多了一些**网络钩子**:\n```\n\n英文中很多单独使用的联词都可以对应到汉语中的成对联词。当包含联词的语句翻译后不通顺时,不妨试试补全对应的另一个汉语联词😎", "path": "docs/zh/docs/advanced/openapi-webhooks.md", "line": null, "side": "RIGHT", "created_at": "2024-12-18T20:12:15+00:00" } ], "meta": { "languages": [ "md" ], "touches_tests": false, "review_state_summary": { "CHANGES_REQUESTED": 1, "APPROVED": 2 }, "meaningful_comment_count": 7, "has_approval": true, "has_changes_requested": true, "total_review_comments": 7 } } { "_id": "36df2491654645ab", "_schema_version": "1.0", "_cleaned_at": "2026-02-12T07:46:52.242325+00:00", "repo": "tiangolo/fastapi", "repo_url": "https://github.com/fastapi/fastapi", "license_name": "MIT License", "license_spdx": "MIT", "pr_number": 13086, "title": "🌐 Add Indonesian translation for `docs/id/docs/tutorial/path-params.md`", "body": null, "author": "user_9a0cc1308ee2", "created_at": "2024-12-17T07:11:00+00:00", "merged_at": "2024-12-24T16:16:02+00:00", "base_branch": "master", "head_branch": "docs/id/docs/tutorial/path-params.md", "additions": 258, "deletions": 0, "changed_files": 1, "files": [ { "filename": "docs/id/docs/tutorial/path-params.md", "status": "added", "additions": 258, "deletions": 0, "changes": 258, "patch": "@@ -0,0 +1,258 @@\n+# Parameter Path\n+\n+\"parameter\" atau \"variabel\" path didefinisikan dengan sintaksis Python format string:\n+\n+{* ../../docs_src/path_params/tutorial001.py hl[6:7] *}\n+\n+Nilai parameter path `item_id` akan dikirim ke fungsi sebagai argument `item_id`:\n+\n+Jika anda menjalankan contoh berikut dan kunjungi http://127.0.0.1:8000/items/foo, anda akan melihat respon:\n+\n+```JSON\n+{\"item_id\":\"foo\"}\n+```\n+\n+## Parameter path dengan tipe data\n+\n+Tipe data parameter path bisa didefinisikan di dalam fungsi, menggunakan anotasi tipe data standar Python:\n+\n+{* ../../docs_src/path_params/tutorial002.py hl[7] *}\n+\n+Dalam hal ini `item_id` didefinisikan sebagai `int`.\n+\n+/// check | Periksa\n+\n+Penyunting kode anda bisa membantu periksa di dalam fungsi seperti pemeriksaan kesalahan, kelengkapan kode, dll.\n+\n+///\n+\n+## Konversi data\n+\n+Jika contoh berikut dijalankan dan diakses browser melalui http://127.0.0.1:8000/items/3, anda akan melihat respon:\n+\n+```JSON\n+{\"item_id\":3}\n+```\n+\n+/// check | Periksa\n+\n+Perhatikan nilai fungsi yang diterima (dan dihasilkan) adalah `3`, sebagai `int` di Python, dan bukan string `\"3\"`.\n+\n+Sehingga dengan deklarasi tipe data **FastAPI** memberikan request otomatis \"parsing\".\n+\n+///\n+\n+## [NAME_REDACTED]\n+\n+Tetapi jika di browser anda akses http://127.0.0.1:8000/items/foo, anda akan melihat pesan kesalahan HTTP:\n+\n+```JSON\n+{\n+ \"detail\": [\n+ {\n+ \"type\": \"int_parsing\",\n+ \"loc\": [\n+ \"path\",\n+ \"item_id\"\n+ ],\n+ \"msg\": \"Input should be a valid integer, unable to parse string as an integer\",\n+ \"input\": \"foo\",\n+ \"url\": \"https://errors.pydantic.dev/2.1/v/int_parsing\"\n+ }\n+ ]\n+}\n+```\n+\n+Karena parameter path `item_id` bernilai `\"foo\"` yang bukan tipe data `int`.\n+\n+Kesalahan yang sama akan muncul jika menggunakan `float` daripada `int`, seperti di: http://127.0.0.1:8000/items/4.2\n+\n+/// check | Periksa\n+\n+Dengan deklarasi tipe data Python, **FastAPI** melakukan validasi data.\n+\n+Perhatikan kesalahan tersebut juga menjelaskan validasi apa yang tidak sesuai.\n+\n+Validasi ini sangat membantu ketika mengembangkan dan men-*debug* kode yang berhubungan dengan API anda.\n+\n+///\n+\n+## Dokumentasi\n+\n+Ketika anda membuka browser di http://127.0.0.1:8000/docs, anda melihat dokumentasi API interaktif otomatis berikut:\n+\n+\n+\n+/// check | Periksa\n+\n+Dengan deklarasi tipe data Python yang sama, **FastAPI** membuat dokumentasi interaktif otomatis (terintegrasi Swagger UI).\n+\n+Perhatikan parameter path dideklarasikan sebagai integer.\n+\n+///\n+\n+## Keuntungan basis-standar, dokumentasi alternatif\n+\n+Karena skema yang dibuat berasal dari standar OpenAPI, maka banyak alat lain yang kompatibel.\n+\n+Sehingga **FastAPI** menyediakan dokumentasi alternatif (menggunakan ReDoc), yang bisa diakses di http://127.0.0.1:8000/redoc:\n+\n+\n+\n+Cara yang sama untuk menggunakan tools kompatibel lainnya. Termasuk alat membuat kode otomatis untuk banyak bahasa.\n+\n+## Pydantic\n+\n+Semua validasi data dikerjakan di belakang layar oleh Pydantic, sehingga anda mendapatkan banyak kemudahan. Anda juga tahu proses ini akan ditangani dengan baik.\n+\n+Anda bisa mendeklarasikan tipe data dengan `str`, `float`, `bool` dan banyak tipe data kompleks lainnya.\n+\n+Beberapa tipe di atas akan dibahas pada bab berikutnya tutorial ini.\n+\n+## Urutan berpengaruh\n+\n+Ketika membuat *operasi path*, anda bisa menghadapi kondisi dimana *path* nya sudah tetap.\n+\n+Seperti `/users/me`, untuk mendapatkan data user yang sedang aktif.\n+\n+Kemudian anda bisa memiliki path `/users/{user_id}` untuk mendapatkan data user tertentu melalui user ID.\n+\n+karena *operasi path* dievaluasi melalui urutan, anda harus memastikan path untuk `/users/me` dideklarasikan sebelum `/user/{user_id}`:\n+\n+{* ../../docs_src/path_params/tutorial003.py hl[6,11] *}\n+\n+Sebaliknya, path `/users/{user_id}` juga akan sesuai dengan `/users/me`, \"menganggap\" menerima parameter `user_id` dengan nilai `\"me\"`.\n+\n+Serupa, anda juga tidak bisa mendefinisikan operasi path:\n+\n+{* ../../docs_src/path_params/tutorial003b.py hl[6,11] *}\n+\n+Path pertama akan selalu digunakan karena path sesuai dengan yang pertama.\n+\n+## Nilai terdefinisi\n+\n+Jika ada *operasi path* yang menerima *parameter path*, tetapi anda ingin nilai valid *parameter path* sudah terdefinisi, anda bisa menggunakan standar Python `Enum`.\n+\n+### Membuat class `Enum`\n+\n+Import `Enum` dan buat *sub-class* warisan dari `str` dan `Enum`.\n+\n+Dengan warisan dari `str` dokumen API mengetahui nilai nya harus berjenis `string` supaya bisa digunakan dengan benar.\n+\n+Kemudian buat atribut *class* dengan nilai tetap *string* yang benar:\n+\n+{* ../../docs_src/path_params/tutorial005.py hl[1,6:9] *}\n+\n+/// info\n+\n+Enumerasi (atau enum) tersedia di Python sejak versi 3.4.\n+\n+///\n+\n+/// tip | Tips\n+\n+\"AlxexNet\", \"ResNet\", dan \"LeNet\" adalah nama model *[NAME_REDACTED]*.\n+\n+///\n+\n+### Mendeklarasikan *parameter path*\n+\n+Kemudian buat *parameter path* dengan tipe anotasi menggunakan *class* enum dari (`ModelName`)\n+\n+{* ../../docs_src/path_params/tutorial005.py hl[16] *}\n+\n+### Periksa dokumentasi\n+\n+Karena nilai yang tersedia untuk *parameter path* telah terdefinisi, dokumen interatik bisa memunculkan:\n+\n+\n+\n+### Bekerja dengan *enumarasi* Python\n+\n+Nilai *parameter path* akan menjadi *anggota enumerasi*.\n+\n+#### Membandingkan *anggota enumerasi*\n+\n+Anda bisa membandingkan parameter *path* dengan *anggota enumerasi* di enum `ModelName` yang anda buat:\n+\n+{* ../../docs_src/path_params/tutorial005.py hl[17] *}\n+\n+#### Mendapatkan *nilai enumerasi*\n+\n+Anda bisa mendapatkan nilai (`str` dalam kasus ini) menggunakan `model_name.value`, atau secara umum `anggota_enum_anda.value`:\n+\n+{* ../../docs_src/path_params/tutorial005.py hl[20] *}\n+\n+/// tip | Tips\n+\n+Anda bisa mengakses nilai `\"lenet\"` dnegan `ModelName.lenet.value`.\n+\n+///\n+\n+#### Menghasilkan *anggota enumerasi*\n+\n+Anda bisa menghasilkan *anggota enumerasi* dari *operasi path* bahkan di body JSON bersarang (contoh `dict`).\n+\n+They will be converted to their corresponding values (strings in this case) before returning them to the client:\n+\n+{* ../../docs_src/path_params/tutorial005.py hl[18,21,23] *}\n+\n+Klien akan mendapatkan respon JSON seperti berikut:\n+\n+```JSON\n+{\n+ \"model_name\": \"alexnet\",\n+ \"message\": \"[NAME_REDACTED] FTW!\"\n+}\n+```\n+\n+## Parameter path berisi path\n+\n+Misalkan terdapat *operasi path* dengan path `/files/{file_path}`.\n+\n+Tetapi anda memerlukan `file_path` itu berisi *path*, seperti like `home/johndoe/myfile.txt`.\n+\n+Sehingga URL untuk file tersebut akan seperti: `/files/home/johndoe/myfile.txt`.\n+\n+### [NAME_REDACTED]\n+\n+OpenAPI tidak bisa mendeklarasikan *parameter path* berisi *path* di dalamnya, karena menyebabkan kondisi yang sulit di*test* dan didefinisikan.\n+\n+Tetapi, di **FastAPI** anda tetap bisa melakukannya dengan menggunakan *tools* internal dari Starlette.\n+\n+Dan dokumentasi tetap berfungsi walaupun tidak menambahkan keterangan bahwa parameter harus berisi *path*.\n+\n+### Konverter path\n+\n+[NAME_REDACTED] anda bisa mendeklarasikan *parameter path* berisi *path* dengan URL seperti:\n+\n+```\n+/files/{file_path:path}\n+```\n+\n+Dikondisi ini nama parameter adalah `file_path` dan bagian terakhir `:path` menginformasikan parameter harus sesuai dengan setiap *path*.\n+\n+Sehingga anda bisa menggunakan:\n+\n+{* ../../docs_src/path_params/tutorial004.py hl[6] *}\n+\n+/// tip | Tips\n+\n+Anda mungkin perlu parameter berisi `/home/johndoe/myfile.txt` di awali garis belakang (`/`).\n+\n+Di kondisi ini, URL nya menjadi: `/files//home/johndoe/myfile.txt`, dengan dua garis belakang (`//`) di antara `files` dan `home`.\n+\n+///\n+\n+## Ringkasan\n+\n+Di **FastAPI** dengan menggunakan deklarasi tipe Python standar, pendek, intuitif, anda mendapatkan:\n+\n+* Dukungan editor: pemeriksaan kesalahan, autocompletion, dll.\n+* \"Parsing\" data.\n+* Validasi data.\n+* Annotasi API dan dokumentasi otomatis.\n+\n+Semua itu anda hanya perlu mendeklarasikan sekali saja.\n+\n+Ini adalah salah satu keunggulan **FastAPI** dibandingkan dengan *framework* lainnya (selain dari performa Python *native*c)" } ], "reviews": [ { "id": 2508244016, "user": "user_221aec9ffc1f", "state": "APPROVED", "body": "LGTM\n\nApproved as a native language", "submitted_at": "2024-12-17T09:03:20+00:00" }, { "id": 2510848908, "user": "user_8ac3fb00696b", "state": "COMMENTED", "body": null, "submitted_at": "2024-12-18T05:45:09+00:00" }, { "id": 2511188023, "user": "user_9a0cc1308ee2", "state": "COMMENTED", "body": null, "submitted_at": "2024-12-18T08:57:52+00:00" }, { "id": 2517169430, "user": "user_e5f553a5bf33", "state": "APPROVED", "body": "good translate", "submitted_at": "2024-12-20T09:49:45+00:00" } ], "review_comments": [ { "id": 1889645802, "user": "user_8ac3fb00696b", "body": "are you sure for displaying box these section and Tip section ?", "path": "docs/id/docs/tutorial/path-params.md", "line": null, "side": "RIGHT", "created_at": "2024-12-18T05:40:46+00:00" }, { "id": 1889855245, "user": "user_9a0cc1308ee2", "body": "[USER_REDACTED] Hi, thanks for the review. I have fixed this one", "path": "docs/id/docs/tutorial/path-params.md", "line": null, "side": "RIGHT", "created_at": "2024-12-18T08:57:51+00:00" } ], "meta": { "languages": [ "md" ], "touches_tests": false, "review_state_summary": { "APPROVED": 2, "COMMENTED": 2 }, "meaningful_comment_count": 2, "has_approval": true, "has_changes_requested": false, "total_review_comments": 2 } } { "_id": "cf1aba43b9cf42f3", "_schema_version": "1.0", "_cleaned_at": "2026-02-12T07:46:52.242325+00:00", "repo": "tiangolo/fastapi", "repo_url": "https://github.com/fastapi/fastapi", "license_name": "MIT License", "license_spdx": "MIT", "pr_number": 13079, "title": "🌐 Add Russian translation for `/docs/ru/docs/tutorial/sql-databases.md`", "body": null, "author": "user_6d7d83efab20", "created_at": "2024-12-15T22:07:52+00:00", "merged_at": "2024-12-17T21:20:20+00:00", "base_branch": "master", "head_branch": "translate-lang-ru-sql-databases", "additions": 358, "deletions": 0, "changed_files": 1, "files": [ { "filename": "docs/ru/docs/tutorial/sql-databases.md", "status": "added", "additions": 358, "deletions": 0, "changes": 358, "patch": "@@ -0,0 +1,358 @@\n+# SQL (реляционные) базы данных\n+\n+**FastAPI** не требует использования реляционной базы данных. Вы можете воспользоваться любой базой данных, которой хотите.\n+\n+В этом разделе мы продемонстрируем, как работать с SQLModel.\n+\n+Библиотека **SQLModel** построена на основе SQLAlchemy и Pydantic. Она была разработана автором **FastAPI** специально для приложений на основе FastAPI, которые используют **реляционные базы данных**.\n+\n+/// tip | Подсказка\n+\n+Вы можете воспользоваться любой библиотекой для работы с реляционными (SQL) или нереляционными (NoSQL) базами данных. (Их ещё называют **ORM** библиотеками). FastAPI не принуждает вас к использованию чего-либо конкретного. 😎\n+\n+///\n+\n+В основе SQLModel лежит SQLAlchemy, поэтому вы спокойно можете использовать любую базу данных, поддерживаемую SQLAlchemy (и, соответственно, поддерживаемую SQLModel), например:\n+\n+* PostgreSQL\n+* MySQL\n+* SQLite\n+* Oracle\n+* Microsoft SQL Server, и т.д.\n+\n+В данном примере мы будем использовать базу данных **SQLite**, т.к. она состоит из единственного файла и поддерживается встроенными библиотеками Python. Таким образом, вы сможете скопировать данный пример и запустить его как он есть.\n+\n+В дальнейшем, для продакшн-версии вашего приложения, возможно, вам стоит использовать серверную базу данных, например, **PostgreSQL**.\n+\n+/// tip | Подсказка\n+\n+Существует официальный генератор проектов на **FastAPI** и **PostgreSQL**, который также включает frontend и дополнительные инструменты https://github.com/fastapi/full-stack-fastapi-template\n+\n+///\n+\n+Это очень простое и короткое руководство, поэтому, если вы хотите узнать о базах данных в целом, об SQL, разобраться с более продвинутым функционалом, то воспользуйтесь документацией SQLModel.\n+\n+## Установка `SQLModel`\n+\n+Создайте виртуальное окружение [virtual environment](../virtual-environments.md){.internal-link target=_blank}, активируйте его и установите `sqlmodel`:\n+\n+
        \n+\n+```console\n+$ pip install sqlmodel\n+---> 100%\n+```\n+\n+
        \n+\n+## Создание приложения с единственной моделью\n+\n+Мы начнем с создания наиболее простой первой версии нашего приложения с одной единственной моделью **SQLModel**.\n+\n+В дальнейшем с помощью **дополнительных моделей** мы его улучшим и сделаем более безопасным и универсальным. 🤓\n+\n+### Создание моделей\n+\n+Импортируйте `SQLModel` и создайте модель базы данных:\n+\n+{* ../../docs_src/sql_databases/tutorial001_an_py310.py ln[1:11] hl[7:11] *}\n+\n+Класс `Hero` очень напоминает модель Pydantic (фактически, под капотом, *это и есть модель Pydantic*).\n+\n+Но есть и некоторые различия\n+\n+* `table=True` для SQLModel означает, что это *модель-таблица*, которая должна представлять **таблицу** в реляционной базе данных. Это не просто *модель данных* (в отличие от обычного класса в Pydantic).\n+\n+* `Field(primary_key=True)` для SQLModel означает, что поле `id` является первичным ключом в таблице базы данных (вы можете подробнее узнать о первичных ключах баз данных в документации по SQLModel).\n+\n+ Тип `int | None` сигнализирует для SQLModel, что столбец таблицы базы данных должен иметь тип `INTEGER`, или иметь пустое значение `NULL`.\n+\n+* `Field(index=True)` для SQLModel означает, что нужно создать **SQL индекс** для данного столбца. Это обеспечит более быстрый поиск при чтении данных, отфильтрованных по данному столбцу.\n+\n+ SQLModel будет знать, что данные типа `str`, будут представлены в базе данных как `TEXT` (или `VARCHAR`, в зависимости от типа базы данных).\n+\n+### Создание соединения с базой данных (Engine)\n+\n+В SQLModel объект соединения `engine` (по сути это `Engine` из SQLAlchemy) **содержит пул соединений** к базе данных.\n+\n+Для обеспечения всех подключений приложения к одной базе данных нужен только один объект соединения `engine`.\n+\n+{* ../../docs_src/sql_databases/tutorial001_an_py310.py ln[14:18] hl[14:15,17:18] *}\n+\n+Использование настройки `check_same_thread=False` позволяет FastAPI использовать одну и ту же SQLite базу данных в различных потоках (threads). Это необходимо, когда **один запрос** использует **более одного потока** (например, в зависимостях).\n+\n+Не беспокойтесь, учитывая структуру кода, мы позже позаботимся о том, чтобы использовать **отдельную SQLModel-сессию на каждый отдельный запрос**, это как раз то, что пытается обеспечить `check_same_thread`.\n+\n+### Создание таблиц\n+\n+Далее мы добавляем функцию, использующую `SQLModel.metadata.create_all(engine)`, для того, чтобы создать **таблицы** для каждой из **моделей таблицы**.\n+\n+{* ../../docs_src/sql_databases/tutorial001_an_py310.py ln[21:22] hl[21:22] *}\n+\n+### Создание зависимости Session\n+\n+Сессия базы данных (**`Session`**) хранит **объекты в памяти** и отслеживает любые необходимые изменения в данных, а затем **использует `engine`** для коммуникации с базой данных.\n+\n+Мы создадим FastAPI-**зависимость** с помощью `yield`, которая будет создавать новую сессию (Session) для каждого запроса. Это как раз и обеспечит использование отдельной сессии на каждый отдельный запрос. 🤓\n+\n+Затем мы создадим объявленную (`Annotated`) зависимость `SessionDep`. Мы сделаем это для того, чтобы упростить остальной код, который будет использовать эту зависимость.\n+\n+{* ../../docs_src/sql_databases/tutorial001_an_py310.py ln[25:30] hl[25:27,30] *}\n+\n+### Создание таблиц базы данных при запуске приложения\n+\n+Мы будем создавать таблицы базы данных при запуске приложения.\n+\n+{* ../../docs_src/sql_databases/tutorial001_an_py310.py ln[32:37] hl[35:37] *}\n+\n+В данном примере мы создаем таблицы при наступлении события запуска приложения.\n+\n+В продуктовом приложении вы, скорее всего, будете использовать скрипт для миграции базы данных, который выполняется перед запуском приложения. 🤓\n+\n+/// tip | Подсказка\n+\n+В SQLModel будут включены утилиты миграции, входящие в состав Alembic, но на данный момент вы просто можете использовать\n+Alembic напрямую.\n+\n+///\n+\n+### Создание героя (Hero)\n+\n+Каждая модель в SQLModel является также моделью Pydantic, поэтому вы можете использовать её при **объявлении типов**, точно также, как и модели Pydantic.\n+\n+Например, при объявлении параметра типа `Hero`, она будет считана из **тела JSON**.\n+\n+Точно также, вы можете использовать её при объявлении типа значения, возвращаемого функцией, и тогда структурированные данные будут отображены через пользовательский интерфейс автоматически сгенерированной документации FastAPI.\n+\n+{* ../../docs_src/sql_databases/tutorial001_an_py310.py ln[40:45] hl[40:45] *}\n+\n+Мы используем зависимость `SessionDep` (сессию базы данных) для того, чтобы добавить нового героя `Hero` в объект сессии (`Session`), сохранить изменения в базе данных, обновить данные героя и затем вернуть их.\n+\n+### Чтение данных о героях\n+\n+Мы можем **читать** данные героев из базы данных с помощью `select()`. Мы можем включить `limit` и `offset` для постраничного считывания результатов.\n+\n+{* ../../docs_src/sql_databases/tutorial001_an_py310.py ln[48:55] hl[51:52,54] *}\n+\n+### Чтение данных отдельного героя\n+\n+Мы можем прочитать данные отдельного героя (`Hero`).\n+\n+{* ../../docs_src/sql_databases/tutorial001_an_py310.py ln[58:63] hl[60] *}\n+\n+### Удаление данных героя\n+\n+Мы также можем удалить героя `Hero` из базы данных.\n+\n+{* ../../docs_src/sql_databases/tutorial001_an_py310.py ln[66:73] hl[71] *}\n+\n+### Запуск приложения\n+\n+Вы можете запустить приложение следующим образом:\n+\n+
        \n+\n+```console\n+$ fastapi dev main.py\n+\n+INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit)\n+```\n+\n+
        \n+\n+Далее перейдите в пользовательский интерфейс API `/docs`. Вы увидите, что **FastAPI** использует модели для создания документации API. Эти же модели используются для сериализации и проверки данных.\n+\n+
        \n+\n+
        \n+\n+## Добавление в приложение дополнительных (вспомогательных) моделей\n+\n+Теперь давайте проведём **рефакторинг** нашего приложения, чтобы сделать его более безопасным и более универсальным.\n+\n+Обратите внимание, что на данном этапе наше приложение позволяет на уровне клиента определять `id` создаваемого героя (`Hero`). 😱\n+\n+Мы не можем этого допустить, т.к. существует риск переписать уже присвоенные `id` в базе данных. Присвоение `id` должно происходить **на уровне бэкэнда (backend)** или **на уровне базы данных**, но никак **не на уровне клиента**.\n+\n+Кроме того, мы создаем секретное имя `secret_name` для героя, но пока что, мы возвращаем его повсеместно, и это слабо напоминает **секретность**... 😅\n+\n+Мы поправим это с помощью нескольких дополнительных (вспомогательных) моделей. Вот где SQLModel по-настоящему покажет себя. ✨\n+\n+### Создание дополнительных моделей\n+\n+В **SQLModel**, любая модель с параметром `table=True` является **моделью таблицы**.\n+\n+Любая модель, не содержащая `table=True` является **моделью данных**, это по сути обычные модели Pydantic (с несколько расширенным функционалом). 🤓\n+\n+С помощью SQLModel мы можем использовать **наследование**, что поможет нам **избежать дублирования** всех полей.\n+\n+#### Базовый класс `HeroBase`\n+\n+Давайте начнём с модели `HeroBase`, которая содержит поля, общие для всех моделей:\n+\n+* `name`\n+* `age`\n+\n+{* ../../docs_src/sql_databases/tutorial002_an_py310.py ln[7:9] hl[7:9] *}\n+\n+#### Модель таблицы `Hero`\n+\n+Далее давайте создадим **модель таблицы** `Hero` с дополнительными полями, которых может не быть в других моделях:\n+\n+* `id`\n+* `secret_name`\n+\n+Модель `Hero` наследует от `HeroBase`, и поэтому включает также поля из `HeroBase`. Таким образом, все поля, содержащиеся в `Hero`, будут следующими:\n+\n+* `id`\n+* `name`\n+* `age`\n+* `secret_name`\n+\n+{* ../../docs_src/sql_databases/tutorial002_an_py310.py ln[7:14] hl[12:14] *}\n+\n+#### Публичная модель данных `HeroPublic`\n+\n+Далее мы создадим модель `HeroPublic`. Мы будем возвращать её клиентам API.\n+\n+Она включает в себя те же поля, что и `HeroBase`, и, соответственно, поле `secret_name` в ней отсутствует.\n+\n+Наконец-то личность наших героев защищена! 🥷\n+\n+В модели `HeroPublic` также объявляется поле `id: int`. Мы как бы заключаем договоренность с API клиентом, на то, что передаваемые данные всегда должны содержать поле `id`, и это поле должно содержать целое число (и никогда не содержать `None`).\n+\n+/// tip | Подсказка\n+\n+Модель ответа, гарантирующая наличие поля со значением типа `int` (не `None`), очень полезна при разработке API клиентов. Определенность в передаваемых данных может обеспечить написание более простого кода.\n+\n+Также **автоматически генерируемые клиенты** будут иметь более простой интерфейс. И в результате жизнь разработчиков, использующих ваш API, станет значительно легче. 😎\n+\n+///\n+\n+`HeroPublic` содержит все поля `HeroBase`, а также поле `id`, объявленное как `int` (не `None`):\n+\n+* `id`\n+* `name`\n+* `age`\n+\n+{* ../../docs_src/sql_databases/tutorial002_an_py310.py ln[7:18] hl[17:18] *}\n+\n+#### Модель для создания героя `HeroCreate`\n+\n+Сейчас мы создадим модель `HeroCreate`. Эта модель будет использоваться для проверки данных, переданных клиентом.\n+\n+Она содержит те же поля, что и `HeroBase`, а также поле `secret_name`.\n+\n+Теперь, при создании нового героя, клиенты будут передавать секретное имя `secret_name`, которое будет сохранено в базе данных, но не будет возвращено в ответе API клиентам.\n+\n+/// tip | Подсказка\n+\n+Вот как нужно работать с **паролями**: получайте их, но не возвращайте их через API.\n+\n+Также хэшируйте значения паролей перед тем, как их сохранить. Ни в коем случае не храните пароли в открытом виде, как обычный текст.\n+\n+///\n+\n+Поля модели `HeroCreate`:\n+\n+* `name`\n+* `age`\n+* `secret_name`\n+\n+{* ../../docs_src/sql_databases/tutorial002_an_py310.py ln[7:22] hl[21:22] *}\n+\n+#### Модель для обновления данных героя `HeroUpdate`\n+\n+В предыдущих версиях нашей программы мы не могли обновить данные героя, теперь, воспользовавшись дополнительными моделями, мы сможем это сделать. 🎉\n+\n+Модель данных `HeroUpdate` в некотором смысле особенная. Она содержит все те же поля, что и модель создания героя, но все поля модели являются **необязательными**. (Все они имеют значение по умолчанию.) Таким образом, при обновлении данных героя, вам достаточно передать только те поля, которые требуют изменения.\n+\n+Поскольку **все поля по сути меняются** (теперь тип каждого поля допускает значение `None` и значение по умолчанию `None`), мы должны их **объявить заново**.\n+\n+Фактически, нам не нужно наследоваться от `HeroBase`, потому что мы будем заново объявлять все поля. Я оставлю наследование просто для поддержания общего стиля, но оно (наследование) здесь необязательно. 🤷\n+\n+Поля `HeroUpdate`:\n+\n+* `name`\n+* `age`\n+* `secret_name`\n+\n+{* ../../docs_src/sql_databases/tutorial002_an_py310.py ln[7:28] hl[25:28] *}\n+\n+### Создание героя с помощью `HeroCreate` и возвращение результатов с помощью `HeroPublic`\n+\n+Теперь, когда у нас есть дополнительные модели, мы можем обновить те части приложения, которые их используют.\n+\n+Вместе c запросом на создание героя мы получаем объект данных `HeroCreate`, и создаем на его основе объект модели таблицы `Hero`.\n+\n+Созданный объект *модели таблицы* `Hero` будет иметь все поля, переданные клиентом, а также поле `id`, сгенерированное базой данных.\n+\n+Далее функция вернёт объект *модели таблицы* `Hero`. Но поскольку, мы объявили `HeroPublic` как модель ответа, то **FastAPI** будет использовать именно её для проверки и сериализации данных.\n+\n+{* ../../docs_src/sql_databases/tutorial002_an_py310.py ln[56:62] hl[56:58] *}\n+\n+/// tip | Подсказка\n+\n+Теперь мы используем модель ответа `response_model=HeroPublic`, вместо того, чтобы объявить тип возвращаемого значения как `-> HeroPublic`. Мы это делаем потому, что тип возвращаемого значения не относится к `HeroPublic`.\n+\n+Если бы мы объявили тип возвращаемого значения как `-> HeroPublic`, то редактор и линтер начали бы ругаться (и вполне справедливо), что возвращаемое значение принадлежит типу `Hero`, а совсем не `HeroPublic`.\n+\n+Объявляя модель ответа в `response_model`, мы как бы говорим **FastAPI**: делай свое дело, не вмешиваясь в аннотацию типов и не полагаясь на помощь редактора или других инструментов.\n+\n+///\n+\n+### Чтение данных героев с помощью `HeroPublic`\n+\n+Мы можем проделать то же самое **для чтения данных** героев. Мы применим модель ответа `response_model=list[HeroPublic]`, и тем самым обеспечим правильную проверку и сериализацию данных.\n+\n+{* ../../docs_src/sql_databases/tutorial002_an_py310.py ln[65:72] hl[65] *}\n+\n+### Чтение данных отдельного героя с помощью `HeroPublic`\n+\n+Мы можем **прочитать** данные отдельного героя:\n+\n+{* ../../docs_src/sql_databases/tutorial002_an_py310.py ln[75:80] hl[77] *}\n+\n+### Обновление данных героя с помощью `HeroUpdate`\n+\n+Мы можем **обновить данные героя**. Для этого мы воспользуемся HTTP методом `PATCH`.\n+\n+В коде мы получаем объект словаря `dict` с данными, переданными клиентом (т.е. **только c данными, переданными клиентом**, исключая любые значения, которые могли бы быть там только потому, что они являются значениями по умолчанию). Для того чтобы сделать это, мы воспользуемся опцией `exclude_unset=True`. В этом главная хитрость. 🪄\n+\n+Затем мы применим `hero_db.sqlmodel_update(hero_data)`, и обновим `hero_db`, использовав данные `hero_data`.\n+\n+{* ../../docs_src/sql_databases/tutorial002_an_py310.py ln[83:93] hl[83:84,88:89] *}\n+\n+### Удалим героя ещё раз\n+\n+Операция **удаления** героя практически не меняется.\n+\n+В данном случае желание *`отрефакторить всё`* остаётся неудовлетворенным. 😅\n+\n+{* ../../docs_src/sql_databases/tutorial002_an_py310.py ln[96:103] hl[101] *}\n+\n+### Снова запустим приложение\n+\n+Вы можете снова запустить приложение:\n+\n+
        \n+\n+```console\n+$ fastapi dev main.py\n+\n+INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit)\n+```\n+\n+
        \n+\n+Если вы перейдете в пользовательский интерфейс API `/docs`, то вы увидите, что он был обновлен, и больше не принимает параметра `id` от клиента при создании нового героя, и т.д.\n+\n+
        \n+\n+
        \n+\n+## Резюме\n+\n+Вы можете использовать **SQLModel** для взаимодействия с реляционными базами данных, а также для упрощения работы с **моделями данных** и **моделями таблиц**.\n+\n+Вы можете узнать гораздо больше информации в документации по **SQLModel**. Там вы найдете более подробное мини-руководство по использованию SQLModel с **FastAPI**. 🚀" } ], "reviews": [ { "id": 2505948013, "user": "user_3cf7e8d7d8b1", "state": "APPROVED", "body": "Great - as always! Thanks!", "submitted_at": "2024-12-16T11:54:39+00:00" }, { "id": 2505941394, "user": "user_f0d9b35e93ea", "state": "APPROVED", "body": "Не маленькая страничка, однако. Хорошо постаралась :)", "submitted_at": "2024-12-16T12:20:11+00:00" }, { "id": 2508283251, "user": "user_6d7d83efab20", "state": "COMMENTED", "body": null, "submitted_at": "2024-12-17T09:17:05+00:00" }, { "id": 2508286268, "user": "user_6d7d83efab20", "state": "COMMENTED", "body": null, "submitted_at": "2024-12-17T09:18:17+00:00" } ], "review_comments": [ { "id": 1886668185, "user": "user_f0d9b35e93ea", "body": "```suggestion\nСуществует официальный пример проекта на **FastAPI** и **PostgreSQL**, который также включает frontend и дополнительные инструменты https://github.com/fastapi/full-stack-fastapi-template\n```\nКак вариант изменения. Генератор не подходит сюда.", "path": "docs/ru/docs/tutorial/sql-databases.md", "line": 29, "side": "RIGHT", "created_at": "2024-12-16T11:37:54+00:00" }, { "id": 1886672435, "user": "user_3cf7e8d7d8b1", "body": "```suggestion\nВ основе SQLModel лежит SQLAlchemy, поэтому вы спокойно можете использовать любую базу данных, поддерживаемую SQLAlchemy (и, соответственно, поддерживаемую SQLModel), например:\n```", "path": "docs/ru/docs/tutorial/sql-databases.md", "line": null, "side": "RIGHT", "created_at": "2024-12-16T11:41:08+00:00" }, { "id": 1886678010, "user": "user_3cf7e8d7d8b1", "body": "```suggestion\nВ дальнейшем, для продакшн-версии вашего приложения, возможно, вам стоит использовать серверную базу данных, например, **PostgreSQL**.\n```", "path": "docs/ru/docs/tutorial/sql-databases.md", "line": null, "side": "RIGHT", "created_at": "2024-12-16T11:45:46+00:00" }, { "id": 1886679650, "user": "user_3cf7e8d7d8b1", "body": "```suggestion\nСуществует официальный генератор проектов на **FastAPI** и **PostgreSQL**, который также включает frontend и дополнительные инструменты: https://github.com/fastapi/full-stack-fastapi-template\n```", "path": "docs/ru/docs/tutorial/sql-databases.md", "line": 29, "side": "RIGHT", "created_at": "2024-12-16T11:46:52+00:00" }, { "id": 1886682603, "user": "user_3cf7e8d7d8b1", "body": "```suggestion\nЭто очень простое и короткое руководство, поэтому, если вы хотите узнать о базах данных в целом, об SQL, разобраться с более продвинутым функционалом, то воспользуйтесь документацией SQLModel.", "path": "docs/ru/docs/tutorial/sql-databases.md", "line": null, "side": "RIGHT", "created_at": "2024-12-16T11:49:01+00:00" }, { "id": 1886688212, "user": "user_3cf7e8d7d8b1", "body": "```suggestion\n* `table=True` для SQLModel означает, что это *модель-таблица*, которая должна представлять **таблицу** в реляционной базе данных. Это не просто *модель данных* (в отличие от обычного класса в Pydantic).\n```", "path": "docs/ru/docs/tutorial/sql-databases.md", "line": null, "side": "RIGHT", "created_at": "2024-12-16T11:53:24+00:00" }, { "id": 1886720008, "user": "user_f0d9b35e93ea", "body": "```suggestion\nВ данном случае желание *`отрефакторить всё`* остаётся неудовлетворенным. 😅\n```\nОпционально", "path": "docs/ru/docs/tutorial/sql-databases.md", "line": null, "side": "RIGHT", "created_at": "2024-12-16T12:17:28+00:00" }, { "id": 1888165836, "user": "user_6d7d83efab20", "body": "По-моему это что-то вроде шаблонизатора проектов. На его основе можно создавать новые проекты. В общем, я посмотрю повнимательнее что это такое.", "path": "docs/ru/docs/tutorial/sql-databases.md", "line": 29, "side": "RIGHT", "created_at": "2024-12-17T09:17:05+00:00" }, { "id": 1888167725, "user": "user_6d7d83efab20", "body": "По поводу https://github.com/fastapi/full-stack-fastapi-template, я посмотрю повнимательнее что это такое и тогда поправлю.", "path": "docs/ru/docs/tutorial/sql-databases.md", "line": 29, "side": "RIGHT", "created_at": "2024-12-17T09:18:17+00:00" } ], "meta": { "languages": [ "md" ], "touches_tests": false, "review_state_summary": { "APPROVED": 2, "COMMENTED": 2 }, "meaningful_comment_count": 9, "has_approval": true, "has_changes_requested": false, "total_review_comments": 9 } } { "_id": "54f4401aacac9f00", "_schema_version": "1.0", "_cleaned_at": "2026-02-12T07:46:52.242325+00:00", "repo": "tiangolo/fastapi", "repo_url": "https://github.com/fastapi/fastapi", "license_name": "MIT License", "license_spdx": "MIT", "pr_number": 13074, "title": "🌐 Add Chinese translation for `docs/zh/docs/advanced/async-tests.md`", "body": "Add Chinese translation for `docs/zh/docs/advanced/async-tests.md`.\n给 `docs/zh/docs/advanced/async-tests.md` 增加了中文翻译。", "author": "user_6fcb07a75ce9", "created_at": "2024-12-14T22:51:59+00:00", "merged_at": "2024-12-17T21:49:06+00:00", "base_branch": "master", "head_branch": "translate/async_tests", "additions": 99, "deletions": 0, "changed_files": 1, "files": [ { "filename": "docs/zh/docs/advanced/async-tests.md", "status": "added", "additions": 99, "deletions": 0, "changes": 99, "patch": "@@ -0,0 +1,99 @@\n+# 异步测试\n+\n+您已经了解了如何使用 `TestClient` 测试 **FastAPI** 应用程序。但是到目前为止,您只了解了如何编写同步测试,而没有使用 `async` 异步函数。\n+\n+在测试中能够使用异步函数可能会很有用,比如当您需要异步查询数据库的时候。想象一下,您想要测试向 FastAPI 应用程序发送请求,然后验证您的后端是否成功在数据库中写入了正确的数据,与此同时您使用了异步的数据库的库。\n+\n+让我们看看如何才能实现这一点。\n+\n+## pytest.mark.anyio\n+\n+如果我们想在测试中调用异步函数,那么我们的测试函数必须是异步的。 AnyIO 为此提供了一个简洁的插件,它允许我们指定一些测试函数要异步调用。\n+\n+## HTTPX\n+\n+即使您的 **FastAPI** 应用程序使用普通的 `def` 函数而不是 `async def` ,它本质上仍是一个 `async` 异步应用程序。\n+\n+`TestClient` 在内部通过一些“魔法”操作,使得您可以在普通的 `def` 测试函数中调用异步的 FastAPI 应用程序,并使用标准的 pytest。但当我们在异步函数中使用它时,这种“魔法”就不再生效了。由于测试以异步方式运行,我们无法在测试函数中继续使用 `TestClient`。\n+\n+`TestClient` 是基于 HTTPX 的。幸运的是,我们可以直接使用它来测试API。\n+\n+## 示例\n+\n+举个简单的例子,让我们来看一个[更大的应用](../tutorial/bigger-applications.md){.internal-link target=_blank}和[测试](../tutorial/testing.md){.internal-link target=_blank}中描述的类似文件结构:\n+\n+```\n+.\n+├── app\n+│   ├── __init__.py\n+│   ├── main.py\n+│   └── test_main.py\n+```\n+\n+文件 `main.py` 将包含:\n+\n+{* ../../docs_src/async_tests/main.py *}\n+\n+文件 `test_main.py` 将包含针对 `main.py` 的测试,现在它可能看起来如下:\n+\n+{* ../../docs_src/async_tests/test_main.py *}\n+\n+## 运行测试\n+\n+您可以通过以下方式照常运行测试:\n+\n+
        \n+\n+```console\n+$ pytest\n+\n+---> 100%\n+```\n+\n+
        \n+\n+## 详细说明\n+\n+这个标记 `[USER_REDACTED].mark.anyio` 会告诉 pytest 该测试函数应该被异步调用:\n+\n+{* ../../docs_src/async_tests/test_main.py hl[7] *}\n+\n+/// tip\n+\n+请注意,测试函数现在用的是 `async def`,而不是像以前使用 `TestClient` 时那样只是 `def` 。\n+\n+///\n+\n+我们现在可以使用应用程序创建一个 `AsyncClient` ,并使用 `await` 向其发送异步请求。\n+\n+{* ../../docs_src/async_tests/test_main.py hl[9:12] *}\n+\n+这相当于:\n+\n+```Python\n+response = client.get('/')\n+```\n+\n+我们曾经通过它向 `TestClient` 发出请求。\n+\n+/// tip\n+\n+请注意,我们正在将 async/await 与新的 `AsyncClient` 一起使用——请求是异步的。\n+\n+///\n+\n+/// warning\n+\n+如果您的应用程序依赖于生命周期事件, `AsyncClient` 将不会触发这些事件。为了确保它们被触发,请使用 florimondmanca/asgi-lifespan 中的 `LifespanManager` 。\n+\n+///\n+\n+## 其他异步函数调用\n+\n+由于测试函数现在是异步的,因此除了在测试中向 FastAPI 应用程序发送请求之外,您现在还可以调用(和使用 `await` 等待)其他 `async` 异步函数,就和您在代码中的其他任何地方调用它们的方法一样。\n+\n+/// tip\n+\n+如果您在测试程序中集成异步函数调用的时候遇到一个 `RuntimeError: Task attached to a different loop` 的报错(例如,使用 MongoDB 的 MotorClient 时),请记住,只能在异步函数中实例化需要事件循环的对象,例如通过 `'[USER_REDACTED].on_event(\"startup\")` 回调函数进行初始化。\n+\n+///" } ], "reviews": [ { "id": 2504606388, "user": "user_d7f5981f1dc1", "state": "CHANGES_REQUESTED", "body": "为您提供一些优化建议,辛苦了!", "submitted_at": "2024-12-15T17:04:34+00:00" }, { "id": 2504621570, "user": "user_d7f5981f1dc1", "state": "APPROVED", "body": "辛苦了!\nThanks for your work!", "submitted_at": "2024-12-15T17:34:16+00:00" } ], "review_comments": [ { "id": 1885765236, "user": "user_d7f5981f1dc1", "body": "```suggestion\n在测试中能够使用异步函数可能会很有用,比如当您需要异步查询数据库的时候。想象一下,您想要测试向 FastAPI 应用程序发送请求,然后验证您的后端是否成功在数据库中写入了正确的数据,与此同时您使用了异步的数据库的库。\n```\n\n改几个字可能会更通顺一些,供您参考。", "path": "docs/zh/docs/advanced/async-tests.md", "line": null, "side": "RIGHT", "created_at": "2024-12-15T16:51:16+00:00" }, { "id": 1885766032, "user": "user_d7f5981f1dc1", "body": "```suggestion\n如果我们想在测试中调用异步函数,那么我们的测试函数必须是异步的。 AnyIO 为此提供了一个简洁的插件,它允许我们指定一些测试函数要异步调用。\n```\n\n汉语中,“如果”……“那么”是成对出现的联词,这与英语的表述习惯不同。", "path": "docs/zh/docs/advanced/async-tests.md", "line": null, "side": "RIGHT", "created_at": "2024-12-15T16:54:26+00:00" }, { "id": 1885767135, "user": "user_d7f5981f1dc1", "body": "```suggestion\n举个简单的例子,让我们来看一个[更大的应用](../tutorial/bigger-applications.md){.internal-link target=_blank}和[测试](../tutorial/testing.md){.internal-link target=_blank}中描述的类似文件结构:\n```\n\n更通俗易懂的说法,供您参考。", "path": "docs/zh/docs/advanced/async-tests.md", "line": null, "side": "RIGHT", "created_at": "2024-12-15T16:57:55+00:00" }, { "id": 1885767551, "user": "user_d7f5981f1dc1", "body": "```suggestion\n这个标记 `[USER_REDACTED].mark.anyio` 会告诉 pytest 该测试函数应该被异步调用:\n```\n\n试试将此处的被动语态翻译出来😎", "path": "docs/zh/docs/advanced/async-tests.md", "line": null, "side": "RIGHT", "created_at": "2024-12-15T16:59:54+00:00" }, { "id": 1885768449, "user": "user_d7f5981f1dc1", "body": "```suggestion\n请注意,我们正在将 async/await 与新的 `AsyncClient` 一起使用——请求是异步的。\n```\n\n此处破折号似乎不太对劲,应该换成中文破折号。或者也可以试试翻译成冒号“:”,您看看哪种方式更好。", "path": "docs/zh/docs/advanced/async-tests.md", "line": null, "side": "RIGHT", "created_at": "2024-12-15T17:03:09+00:00" } ], "meta": { "languages": [ "md" ], "touches_tests": false, "review_state_summary": { "CHANGES_REQUESTED": 1, "APPROVED": 1 }, "meaningful_comment_count": 5, "has_approval": true, "has_changes_requested": true, "total_review_comments": 5 } } { "_id": "1274cb5c1ce9540e", "_schema_version": "1.0", "_cleaned_at": "2026-02-12T07:46:52.257948+00:00", "repo": "tiangolo/fastapi", "repo_url": "https://github.com/fastapi/fastapi", "license_name": "MIT License", "license_spdx": "MIT", "pr_number": 13063, "title": "🌐 Add Korean translation for `docs/ko/docs/tutorial/extra-models.md`", "body": "다음과 같이 번역하였습니다.\n- unwrap -> 언랩(unwrap) #13061 의 accept 여부에 따라 번역 변경 예정\n- unwraping -> 언래핑(unwrapping) #13061 의 accept 여부에 따라 번역 변경 예정\n- type annotation -> 타입 어노테이션(type annotation)\n- argument value -> 인자 값(argument value)", "author": "user_a1942c3a9ec0", "created_at": "2024-12-12T11:02:28+00:00", "merged_at": "2025-05-30T13:38:33+00:00", "base_branch": "master", "head_branch": "translation/tutorial-extra-models", "additions": 223, "deletions": 0, "changed_files": 1, "files": [ { "filename": "docs/ko/docs/tutorial/extra-models.md", "status": "added", "additions": 223, "deletions": 0, "changes": 223, "patch": "@@ -0,0 +1,223 @@\n+# 추가 모델\n+\n+지난 예제에 이어서, 연관된 모델을 여러개 갖는 것은 흔한 일입니다.\n+\n+특히 사용자 모델의 경우에 그러한데, 왜냐하면:\n+\n+* **입력 모델** 은 비밀번호를 가져야 합니다.\n+* **출력 모델** 은 비밀번호를 가지면 안됩니다.\n+* **데이터베이스 모델** 은 해시처리된 비밀번호를 가질 것입니다.\n+\n+/// danger | 위험\n+\n+절대 사용자의 비밀번호를 평문으로 저장하지 마세요. 항상 이후에 검증 가능한 \"안전한 해시(secure hash)\"로 저장하세요.\n+\n+만약 이게 무엇인지 모르겠다면, [security chapters](security/simple-oauth2.md#password-hashing){.internal-link target=_blank}.에서 비밀번호 해시에 대해 배울 수 있습니다.\n+\n+///\n+\n+## 다중 모델\n+\n+아래는 비밀번호 필드와 해당 필드가 사용되는 위치를 포함하여, 각 모델들이 어떤 형태를 가질 수 있는지 전반적인 예시입니다:\n+\n+{* ../../docs_src/extra_models/tutorial001_py310.py hl[7,9,14,20,22,27:28,31:33,38:39] *}\n+\n+\n+/// info | 정보\n+\n+Pydantic v1에서는 해당 메서드가 `.dict()`로 불렸으며, Pydantic v2에서는 `.model_dump()`로 이름이 변경되었습니다. `.dict()`는 여전히 지원되지만 더 이상 권장되지 않습니다.\n+\n+여기에서 사용하는 예제는 Pydantic v1과의 호환성을 위해 `.dict()`를 사용하지만, Pydantic v2를 사용할 수 있다면 `.model_dump()`를 사용하는 것이 좋습니다.\n+\n+///\n+\n+### `**user_in.dict()` 에 대하여\n+\n+#### Pydantic의 `.dict()`\n+\n+`user_in`은 Pydantic 모델 클래스인 `UserIn`입니다.\n+\n+Pydantic 모델은 모델 데이터를 포함한 `dict`를 반환하는 `.dict()` 메서드를 제공합니다.\n+\n+따라서, 다음과 같이 Pydantic 객체 `user_in`을 생성할 수 있습니다:\n+\n+```Python\n+user_in = UserIn(username=\"john\", password=\"secret\", email=\"[EMAIL_REDACTED]\")\n+```\n+\n+그 다음, 다음과 같이 호출합니다:\n+\n+```Python\n+user_dict = user_in.dict()\n+```\n+\n+이제 변수 `user_dict`에 데이터가 포함된 `dict`를 가지게 됩니다(이는 Pydantic 모델 객체가 아닌 `dict`입니다).\n+\n+그리고 다음과 같이 호출하면:\n+\n+```Python\n+print(user_dict)\n+```\n+\n+Python의 `dict`가 다음과 같이 출력됩니다:\n+\n+```Python\n+{\n+ 'username': 'john',\n+ 'password': 'secret',\n+ 'email': '[EMAIL_REDACTED]',\n+ 'full_name': None,\n+}\n+```\n+\n+#### `dict` 언패킹(Unpacking)\n+\n+`user_dict`와 같은 `dict`를 함수(또는 클래스)에 `**user_dict`로 전달하면, Python은 이를 \"언팩(unpack)\"합니다. 이 과정에서 `user_dict`의 키와 값을 각각 키-값 인자로 직접 전달합니다.\n+\n+따라서, 위에서 생성한 `user_dict`를 사용하여 다음과 같이 작성하면:\n+\n+```Python\n+UserInDB(**user_dict)\n+```\n+\n+다음과 같은 결과를 생성합니다:\n+\n+```Python\n+UserInDB(\n+ username=\"john\",\n+ password=\"secret\",\n+ email=\"[EMAIL_REDACTED]\",\n+ full_name=None,\n+)\n+```\n+\n+혹은 더 정확히 말하자면, `user_dict`를 직접 사용하는 것은, 나중에 어떤 값이 추가되더라도 아래와 동일한 효과를 냅니다:\n+\n+```Python\n+UserInDB(\n+ username = user_dict[\"username\"],\n+ password = user_dict[\"password\"],\n+ email = user_dict[\"email\"],\n+ full_name = user_dict[\"full_name\"],\n+)\n+```\n+\n+#### 다른 모델 데이터로 새 Pydantic 모델 생성\n+\n+위의 예제에서 `user_in.dict()`로부터 `user_dict`를 생성한 것처럼, 아래 코드는:\n+\n+```Python\n+user_dict = user_in.dict()\n+UserInDB(**user_dict)\n+```\n+\n+다음과 동일합니다:\n+\n+```Python\n+UserInDB(**user_in.dict())\n+```\n+\n+...왜냐하면 `user_in.dict()`는 `dict`이며, 이를 `**`로 Python이 \"언팩(unpack)\"하도록 하여 `UserInDB`에 전달하기 때문입니다.\n+\n+따라서, 다른 Pydantic 모델의 데이터를 사용하여 새로운 Pydantic 모델을 생성할 수 있습니다.\n+\n+#### `dict` 언패킹(Unpacking)과 추가 키워드\n+\n+그리고 다음과 같이 추가 키워드 인자 `hashed_password=hashed_password`를 추가하면:\n+\n+```Python\n+UserInDB(**user_in.dict(), hashed_password=hashed_password)\n+```\n+\n+다음과 같은 결과를 생성합니다:\n+\n+```Python\n+UserInDB(\n+ username = user_dict[\"username\"],\n+ password = user_dict[\"password\"],\n+ email = user_dict[\"email\"],\n+ full_name = user_dict[\"full_name\"],\n+ hashed_password = hashed_password,\n+)\n+```\n+\n+/// warning | 경고\n+\n+추가적으로 제공된 함수 `fake_password_hasher`와 `fake_save_user`는 데이터 흐름을 시연하기 위한 예제일 뿐이며, 실제 보안을 제공하지 않습니다.\n+\n+///\n+\n+## 중복 줄이기\n+\n+코드 중복을 줄이는 것은 **FastAPI**의 핵심 아이디어 중 하나입니다.\n+\n+코드 중복은 버그, 보안 문제, 코드 비동기화 문제(한 곳은 업데이트되었지만 다른 곳은 업데이트되지 않는 문제) 등의 가능성을 증가시킵니다.\n+\n+그리고 이 모델들은 많은 데이터를 공유하면서 속성 이름과 타입을 중복하고 있습니다.\n+\n+더 나은 방법이 있습니다.\n+\n+`UserBase` 모델을 선언하여 다른 모델들의 기본(base)으로 사용할 수 있습니다. 그런 다음 이 모델을 상속받아 속성과 타입 선언(유형 선언, 검증 등)을 상속하는 서브클래스를 만들 수 있습니다.\n+\n+모든 데이터 변환, 검증, 문서화 등은 정상적으로 작동할 것입니다.\n+\n+이렇게 하면 각 모델 간의 차이점만 선언할 수 있습니다(평문 `password`가 있는 경우, `hashed_password`만 있는 경우, 혹은 비밀번호가 없는 경우):\n+\n+{* ../../docs_src/extra_models/tutorial002_py310.py hl[7,13:14,17:18,21:22] *}\n+\n+## `Union` 또는 `anyOf`\n+\n+두 가지 이상의 타입을 포함하는 `Union`으로 응답을 선언할 수 있습니다. 이는 응답이 그 중 하나의 타입일 수 있음을 의미합니다.\n+\n+OpenAPI에서는 이를 `anyOf`로 정의합니다.\n+\n+이를 위해 표준 Python 타입 힌트인 `typing.Union`을 사용할 수 있습니다:\n+\n+/// note | 참고\n+\n+`Union`을 정의할때는 더 구체적인 타입을 먼저 포함하고, 덜 구체적인 타입을 그 뒤에 나열해야합니다. 아래 예제에서는 `Union[PlaneItem, CarItem]` 를 보면, 더 구체적인 `PlaneItem`이 `CarItem`보다 앞에 위치합니다.\n+\n+///\n+\n+{* ../../docs_src/extra_models/tutorial003_py310.py hl[1,14:15,18:20,33] *}\n+\n+\n+### Python 3.10에서 `Union`\n+\n+위의 예제에서는 `response_model` 인자 값으로 `Union[PlaneItem, CarItem]`을 전달합니다.\n+\n+이 경우, 이를 **타입 어노테이션(type annotation)** 이 아닌 **인자 값(argument value)** 으로 전달하고 있기 때문에 Python 3.10에서도 `Union`을 사용해야 합니다.\n+\n+만약 타입 어노테이션에 사용한다면, 다음과 같이 수직 막대(|)를 사용할 수 있습니다:\n+\n+```Python\n+some_variable: PlaneItem | CarItem\n+```\n+\n+하지만 이를 `response_model=PlaneItem | CarItem`과 같이 할당하면 에러가 발생합니다. 이는 Python이 이를 타입 어노테이션으로 해석하지 않고, `PlaneItem`과 `CarItem` 사이의 **잘못된 연산(invalid operation)**을 시도하기 때문입니다\n+\n+## 모델 리스트\n+\n+마찬가지로, 객체 리스트 형태의 응답을 선언할 수도 있습니다.\n+\n+이를 위해 표준 Python의 `typing.List`를 사용하세요(또는 Python 3.9 이상에서는 단순히 `list`를 사용할 수 있습니다):\n+\n+{* ../../docs_src/extra_models/tutorial004_py39.py hl[18] *}\n+\n+\n+## 임의의 `dict` 응답\n+\n+Pydantic 모델을 사용하지 않고, 키와 값의 타입만 선언하여 평범한 임의의 `dict`로 응답을 선언할 수도 있습니다.\n+\n+이는 Pydantic 모델에 필요한 유효한 필드/속성 이름을 사전에 알 수 없는 경우에 유용합니다.\n+\n+이 경우, `typing.Dict`를 사용할 수 있습니다(또는 Python 3.9 이상에서는 단순히 `dict`를 사용할 수 있습니다):\n+\n+{* ../../docs_src/extra_models/tutorial005_py39.py hl[6] *}\n+\n+\n+## 요약\n+\n+여러 Pydantic 모델을 사용하고, 각 경우에 맞게 자유롭게 상속하세요.\n+\n+엔터티가 서로 다른 \"상태\"를 가져야 하는 경우, 엔터티당 단일 데이터 모델을 사용할 필요는 없습니다. 예를 들어, 사용자 \"엔터티\"가 `password`, `password_hash`, 또는 비밀번호가 없는 상태를 포함할 수 있는 경우처럼 말입니다." } ], "reviews": [ { "id": 2606321246, "user": "user_dfad060db61c", "state": "COMMENTED", "body": "Thank you for your excellent translation 👍 \nI’m not very fluent in English, so I wrote the comment in Korean to better express my thoughts. Please let me know if the comment needs to be written in English :)", "submitted_at": "2025-02-10T16:55:53+00:00" }, { "id": 2607888082, "user": "user_a1942c3a9ec0", "state": "COMMENTED", "body": null, "submitted_at": "2025-02-11T07:24:28+00:00" }, { "id": 2607889267, "user": "user_a1942c3a9ec0", "state": "COMMENTED", "body": null, "submitted_at": "2025-02-11T07:25:13+00:00" }, { "id": 2607919648, "user": "user_a1942c3a9ec0", "state": "COMMENTED", "body": null, "submitted_at": "2025-02-11T07:44:19+00:00" }, { "id": 2609123006, "user": "user_a1942c3a9ec0", "state": "COMMENTED", "body": null, "submitted_at": "2025-02-11T15:28:53+00:00" }, { "id": 2612067512, "user": "user_dfad060db61c", "state": "APPROVED", "body": "LGTM 🔥", "submitted_at": "2025-02-12T14:14:39+00:00" }, { "id": 2625608429, "user": "user_08f3ccdc57a3", "state": "COMMENTED", "body": null, "submitted_at": "2025-02-19T04:31:21+00:00" }, { "id": 2625621250, "user": "user_08f3ccdc57a3", "state": "COMMENTED", "body": null, "submitted_at": "2025-02-19T04:45:02+00:00" }, { "id": 2625638586, "user": "user_08f3ccdc57a3", "state": "COMMENTED", "body": null, "submitted_at": "2025-02-19T05:01:51+00:00" }, { "id": 2625640550, "user": "user_08f3ccdc57a3", "state": "CHANGES_REQUESTED", "body": null, "submitted_at": "2025-02-19T05:03:45+00:00" }, { "id": 2625652243, "user": "user_08f3ccdc57a3", "state": "COMMENTED", "body": null, "submitted_at": "2025-02-19T05:14:33+00:00" }, { "id": 2625652654, "user": "user_08f3ccdc57a3", "state": "COMMENTED", "body": null, "submitted_at": "2025-02-19T05:14:57+00:00" }, { "id": 2625654106, "user": "user_08f3ccdc57a3", "state": "COMMENTED", "body": null, "submitted_at": "2025-02-19T05:16:18+00:00" }, { "id": 2625656315, "user": "user_08f3ccdc57a3", "state": "CHANGES_REQUESTED", "body": null, "submitted_at": "2025-02-19T08:26:02+00:00" }, { "id": 2626001408, "user": "user_a1942c3a9ec0", "state": "COMMENTED", "body": null, "submitted_at": "2025-02-19T08:27:19+00:00" }, { "id": 2626003516, "user": "user_08f3ccdc57a3", "state": "COMMENTED", "body": null, "submitted_at": "2025-02-19T08:28:16+00:00" }, { "id": 2626015509, "user": "user_08f3ccdc57a3", "state": "COMMENTED", "body": null, "submitted_at": "2025-02-19T08:33:39+00:00" }, { "id": 2626019181, "user": "user_08f3ccdc57a3", "state": "COMMENTED", "body": null, "submitted_at": "2025-02-19T08:35:11+00:00" }, { "id": 2626020223, "user": "user_a1942c3a9ec0", "state": "COMMENTED", "body": null, "submitted_at": "2025-02-19T08:35:39+00:00" }, { "id": 2626050804, "user": "user_a1942c3a9ec0", "state": "COMMENTED", "body": null, "submitted_at": "2025-02-19T08:48:31+00:00" }, { "id": 2626061716, "user": "user_08f3ccdc57a3", "state": "COMMENTED", "body": null, "submitted_at": "2025-02-19T08:52:51+00:00" }, { "id": 2626064266, "user": "user_a1942c3a9ec0", "state": "COMMENTED", "body": null, "submitted_at": "2025-02-19T08:53:56+00:00" }, { "id": 2626067218, "user": "user_a1942c3a9ec0", "state": "COMMENTED", "body": null, "submitted_at": "2025-02-19T08:55:09+00:00" }, { "id": 2626077840, "user": "user_08f3ccdc57a3", "state": "COMMENTED", "body": null, "submitted_at": "2025-02-19T08:59:24+00:00" }, { "id": 2626081930, "user": "user_a1942c3a9ec0", "state": "COMMENTED", "body": null, "submitted_at": "2025-02-19T09:00:49+00:00" }, { "id": 2626086916, "user": "user_a1942c3a9ec0", "state": "COMMENTED", "body": null, "submitted_at": "2025-02-19T09:02:45+00:00" }, { "id": 2626146150, "user": "user_a1942c3a9ec0", "state": "COMMENTED", "body": null, "submitted_at": "2025-02-19T09:21:54+00:00" }, { "id": 2626153177, "user": "user_a1942c3a9ec0", "state": "COMMENTED", "body": null, "submitted_at": "2025-02-19T09:24:36+00:00" }, { "id": 2626179221, "user": "user_a1942c3a9ec0", "state": "COMMENTED", "body": null, "submitted_at": "2025-02-19T09:33:56+00:00" }, { "id": 2626405205, "user": "user_a1942c3a9ec0", "state": "COMMENTED", "body": null, "submitted_at": "2025-02-19T10:46:16+00:00" }, { "id": 2626427095, "user": "user_a1942c3a9ec0", "state": "COMMENTED", "body": null, "submitted_at": "2025-02-19T10:55:11+00:00" }, { "id": 2629466508, "user": "user_a1942c3a9ec0", "state": "COMMENTED", "body": null, "submitted_at": "2025-02-20T10:53:45+00:00" }, { "id": 2629537194, "user": "user_a1942c3a9ec0", "state": "COMMENTED", "body": null, "submitted_at": "2025-02-20T11:13:55+00:00" } ], "review_comments": [ { "id": 1949377574, "user": "user_dfad060db61c", "body": "```suggestion\n#### `dict` 언패킹(Unpacking)\n```\nYour PR #13061 is merged. 🙌", "path": "docs/ko/docs/tutorial/extra-models.md", "line": null, "side": "RIGHT", "created_at": "2025-02-10T15:50:50+00:00" }, { "id": 1949378208, "user": "user_dfad060db61c", "body": "```suggestion\n`user_dict`와 같은 `dict`를 함수(또는 클래스)에 `**user_dict`로 전달하면, Python은 이를 \"언팩(unpack)\"합니다. 이 과정에서 `user_dict`의 키와 값을 각각 키-값 인자로 직접 전달합니다.\n```", "path": "docs/ko/docs/tutorial/extra-models.md", "line": null, "side": "RIGHT", "created_at": "2025-02-10T15:51:13+00:00" }, { "id": 1949386191, "user": "user_dfad060db61c", "body": "```suggestion\n...왜냐하면 `user_in.dict()`는 `dict`이며, 이를 `**`로 Python이 \"언팩(unpack)\"하도록 하여 `UserInDB`에 전달하기 때문입니다.\n```", "path": "docs/ko/docs/tutorial/extra-models.md", "line": null, "side": "RIGHT", "created_at": "2025-02-10T15:54:44+00:00" }, { "id": 1949387051, "user": "user_dfad060db61c", "body": "```suggestion\n#### `dict` 언패킹(Unpacking)과 추가 키워드\n```", "path": "docs/ko/docs/tutorial/extra-models.md", "line": null, "side": "RIGHT", "created_at": "2025-02-10T15:55:11+00:00" }, { "id": 1949449418, "user": "user_dfad060db61c", "body": "```suggestion\n이 경우, 이를 **타입 어노테이션(type annotation)** 이 아닌 **인자 값(argument value)** 으로 전달하고 있기 때문에 Python 3.10에서도 `Union`을 사용해야 합니다.\n```\n타입 주석으로 번역할 경우 사람이 사용하는 주석(`/* */`나 `//` 같은)과 혼동될까 우려됩니다.\n[파이썬 공식 문서](https://docs.python.org/ko/3/glossary.html#term-annotation) 번역에 따라 `annotaion`을 `어노테이션`으로 번역하는건 어떨지 의견드립니다.", "path": "docs/ko/docs/tutorial/extra-models.md", "line": null, "side": "RIGHT", "created_at": "2025-02-10T16:19:16+00:00" }, { "id": 1949449786, "user": "user_dfad060db61c", "body": "```suggestion\n만약 타입 어노테이션에 사용한다면, 다음과 같이 수직 막대(|)를 사용할 수 있습니다:\n```", "path": "docs/ko/docs/tutorial/extra-models.md", "line": null, "side": "RIGHT", "created_at": "2025-02-10T16:19:20+00:00" }, { "id": 1949458219, "user": "user_dfad060db61c", "body": "```suggestion\n하지만 이를 `response_model=PlaneItem | CarItem`과 같이 할당하면 에러가 발생합니다. 이는 Python이 이를 타입 어노테이션으로 해석하지 않고, `PlaneItem`과 `CarItem` 사이의 **잘못된 연산(invalid operation)**을 시도하기 때문입니다\n```", "path": "docs/ko/docs/tutorial/extra-models.md", "line": null, "side": "RIGHT", "created_at": "2025-02-10T16:21:26+00:00" }, { "id": 1949484439, "user": "user_dfad060db61c", "body": "```suggestion\n절대 사용자의 비밀번호를 평문으로 저장하지 마세요. 항상 이후에 검증 가능한 \"안전한 해시(secure hash)\"로 저장하세요.\n```\n`유저`를 `사용자`로 번역하는게 어떨지 의견드립니다.\n\n한국어 문서 전체적으로 `유저`와 `사용자`를 혼용해서 사용하는걸로 보이긴 하나,\n바로 이전 문서인 [응답 모델](https://54a8563c.fastapitiangolo.pages.dev/ko/tutorial/response-model/)에서 사용자로 번역하였기에, 예제가 이어지는 해당 문서에서는 `사용자`로 작성하는게 자연스러울 것 같습니다.", "path": "docs/ko/docs/tutorial/extra-models.md", "line": null, "side": "RIGHT", "created_at": "2025-02-10T16:36:48+00:00" }, { "id": 1949485379, "user": "user_dfad060db61c", "body": "```suggestion\n특히 사용자 모델의 경우에 그러한데, 왜냐하면:\n```", "path": "docs/ko/docs/tutorial/extra-models.md", "line": null, "side": "RIGHT", "created_at": "2025-02-10T16:37:27+00:00" }, { "id": 1949491601, "user": "user_dfad060db61c", "body": "```suggestion\n엔터티가 서로 다른 \"상태\"를 가져야 하는 경우, 엔터티당 단일 데이터 모델을 사용할 필요는 없습니다. 예를 들어, 사용자 \"엔터티\"가 `password`, `password_hash`, 또는 비밀번호가 없는 상태를 포함할 수 있는 경우처럼 말입니다.\n```", "path": "docs/ko/docs/tutorial/extra-models.md", "line": null, "side": "RIGHT", "created_at": "2025-02-10T16:40:13+00:00" }, { "id": 1949506533, "user": "user_dfad060db61c", "body": "```suggestion\n혹은 더 정확히 말하자면, `user_dict`를 직접 사용하여, 미래에 어떤 내용이 포함되더라도 다음과 같이 생성합니다:\n```\n제가 제안드리는 문구가 적절한지는 모르겠습니다만, 문장을 끝맺어 주는게 이해하기 더 수월할 것 같습니다.", "path": "docs/ko/docs/tutorial/extra-models.md", "line": null, "side": "RIGHT", "created_at": "2025-02-10T16:48:05+00:00" }, { "id": 1950351642, "user": "user_a1942c3a9ec0", "body": "[USER_REDACTED] \ngood point, but let me check another korean translation references", "path": "docs/ko/docs/tutorial/extra-models.md", "line": null, "side": "RIGHT", "created_at": "2025-02-11T07:24:27+00:00" }, { "id": 1950352430, "user": "user_a1942c3a9ec0", "body": "[USER_REDACTED] \nanother good point! thanks you", "path": "docs/ko/docs/tutorial/extra-models.md", "line": null, "side": "RIGHT", "created_at": "2025-02-11T07:25:13+00:00" }, { "id": 1950370083, "user": "user_a1942c3a9ec0", "body": "[USER_REDACTED]\nThanks to you, I've noticed that most translated Korean documents tend to add sentence endings.\n\nWhile there are exceptions like the [tutorial/query-params](https://fastapi.tiangolo.com/ko/tutorial/query-params/) example, as long as completing the sentence doesn't change the original meaning, it seems like a good approach. \n\nI'll accept your suggestion!", "path": "docs/ko/docs/tutorial/extra-models.md", "line": null, "side": "RIGHT", "created_at": "2025-02-11T07:44:19+00:00" }, { "id": 1951069466, "user": "user_a1942c3a9ec0", "body": "Unfortunately, I couldn't find a suitable Korean translation for the term \"type annotation.\" Instead, I found that many documents need to be updated.\n\n[python-types](https://fastapi.tiangolo.com/ko/python-types/),\n[tutorial/body](https://fastapi.tiangolo.com/ko/tutorial/body/),\n[advanced/settings](https://fastapi.tiangolo.com/ko/advanced/settings/),\n[tutorial/body-nested-models](https://fastapi.tiangolo.com/ko/tutorial/body-nested-models/)", "path": "docs/ko/docs/tutorial/extra-models.md", "line": null, "side": "RIGHT", "created_at": "2025-02-11T15:28:53+00:00" }, { "id": 1960935380, "user": "user_08f3ccdc57a3", "body": "I think we have to focus on meaning of **extra** model.🤔\ncurrent Korean subject isn't clear when read this. \n\n``추가 모델``이라고 했는데, ``추가``라는 말이 엑스트라 모델에는 뜻이 잘 안드러나는 것 같아요. \n``여분 모델``이나 ``엑스트라 모델``을 그대로 쓰는 건 어떠세요? 한국에서는 ``엑스트라``라는 말을 자주 쓰긴 합니다.", "path": "docs/ko/docs/tutorial/extra-models.md", "line": 1, "side": "RIGHT", "created_at": "2025-02-19T04:31:21+00:00" }, { "id": 1960943906, "user": "user_08f3ccdc57a3", "body": "This sentence is not correct.\n🤔 원문이랑 아예 안맞는데요?\n(잠깐 고민해볼게요)", "path": "docs/ko/docs/tutorial/extra-models.md", "line": null, "side": "RIGHT", "created_at": "2025-02-19T04:45:02+00:00" }, { "id": 1960955716, "user": "user_08f3ccdc57a3", "body": "```suggestion\n혹은 좀 더 정확하게, `user_dict`를 직접 사용합니다. :\n(나중에 어떤 내용을 가지게 되더라도 *해당 딕셔너리의 모든 현재 키와 값을 자동으로 매개변수로 변환하여 전달한다. :역자 추가* )\n```\nadded detail", "path": "docs/ko/docs/tutorial/extra-models.md", "line": null, "side": "RIGHT", "created_at": "2025-02-19T05:01:51+00:00" }, { "id": 1960957002, "user": "user_08f3ccdc57a3", "body": "\"Or more exactly, using `user_dict` directly, with whatever contents it might have in the future:\"라는 문장을 좀 더 살펴볼게요.\n\n해당 문장의 앞에서 보여준 예시(매개변수들을 하나하나 명시적으로 입력하는 방식)는 현재 `user_dict`의 키와 값이 고정된 상태를 설명합니다. 하지만 실제로는 `user_dict`가 어떤 내용으로 구성되어 있는지에 따라 달라질 수 있기 때문에, 함수나 클래스에 `**user_dict`로 전달하면 *해당 딕셔너리의 모든 현재 키와 값을 자동으로 매개변수로 변환*하여 전달한다는 점을 **이번 문장에서** 강조하는 것입니다.\n\n즉, `user_dict`의 키와 값이 바뀔 경우에도 `**user_dict`를 사용하면 자동으로 새로운 키와 값이 매핑되어 함수에 전달됩니다. 딕셔너리의 구조가 변동될 수 있을 때 매우 유용한 방식이라는 것을 나타내는 설명입니다.\n\n원문 단어만으로는 사실 뉘앙스를 살리기 힘들어서... \n이정도는 추가해도 된다고 생각해요.", "path": "docs/ko/docs/tutorial/extra-models.md", "line": null, "side": "RIGHT", "created_at": "2025-02-19T05:03:35+00:00" }, { "id": 1960964768, "user": "user_08f3ccdc57a3", "body": "```suggestion\n#### 다른 모델 데이터로 새 Pydantic 모델 생성\n```", "path": "docs/ko/docs/tutorial/extra-models.md", "line": null, "side": "RIGHT", "created_at": "2025-02-19T05:14:33+00:00" }, { "id": 1960965023, "user": "user_08f3ccdc57a3", "body": "```suggestion\n...왜냐하면 `user_in.dict()`는 `dict`이며, 이를 `**`로 Python이 \"언팩\"하도록 하여 `UserInDB`에 전달하기 때문입니다.\n```", "path": "docs/ko/docs/tutorial/extra-models.md", "line": 120, "side": "RIGHT", "created_at": "2025-02-19T05:14:57+00:00" }, { "id": 1960965988, "user": "user_08f3ccdc57a3", "body": "```suggestion\n#### `dict` 언패킹과 여분 키워드\n```", "path": "docs/ko/docs/tutorial/extra-models.md", "line": 124, "side": "RIGHT", "created_at": "2025-02-19T05:16:18+00:00" }, { "id": 1960967642, "user": "user_08f3ccdc57a3", "body": "```suggestion\n그리고 다음과 같이 여분 키워드 인자 `hashed_password=hashed_password`를 추가하면:\n```", "path": "docs/ko/docs/tutorial/extra-models.md", "line": null, "side": "RIGHT", "created_at": "2025-02-19T05:18:21+00:00" }, { "id": 1960968991, "user": "user_08f3ccdc57a3", "body": "```suggestion\n지원된 추가적인 함수 `fake_password_hasher`와 `fake_save_user`는 데이터 흐름을 시연하기 위한 예제일 뿐이며, 실제 보안을 제공하지 않습니다.\n```", "path": "docs/ko/docs/tutorial/extra-models.md", "line": 146, "side": "RIGHT", "created_at": "2025-02-19T05:20:09+00:00" }, { "id": 1961192954, "user": "user_a1942c3a9ec0", "body": "[USER_REDACTED]\nThank you very much for reviewing my PR.\n\nWould you mind explaining why you prefer not to mix English with Korean in your commit messages? \nFor your reference, the term was recently updated from \"unwrap\" to \"unpack,\" and I intentionally included the English version to emphasize that change.", "path": "docs/ko/docs/tutorial/extra-models.md", "line": 120, "side": "RIGHT", "created_at": "2025-02-19T08:27:19+00:00" }, { "id": 1961194364, "user": "user_08f3ccdc57a3", "body": "이부분 깃허브 시스템상 잘못 표기된것 같은데\n코멘트 확인 부탁드립니다", "path": "docs/ko/docs/tutorial/extra-models.md", "line": null, "side": "RIGHT", "created_at": "2025-02-19T08:28:16+00:00" }, { "id": 1961202031, "user": "user_08f3ccdc57a3", "body": "[USER_REDACTED] \nthe term was recently updated from \"unwrap\" to \"unpack,\" <- idk about that 😮\ni just fixed repetition of words to make clear (ref: chinise docs and japanese docs)", "path": "docs/ko/docs/tutorial/extra-models.md", "line": 120, "side": "RIGHT", "created_at": "2025-02-19T08:33:38+00:00" }, { "id": 1961204246, "user": "user_08f3ccdc57a3", "body": "[USER_REDACTED] \nhere are the refs ( same content)\n- https://fastapi.tiangolo.com/ja/tutorial/extra-models \n- https://fastapi.tiangolo.com/zh/tutorial/extra-models", "path": "docs/ko/docs/tutorial/extra-models.md", "line": 120, "side": "RIGHT", "created_at": "2025-02-19T08:35:11+00:00" }, { "id": 1961204890, "user": "user_a1942c3a9ec0", "body": "[USER_REDACTED] \nThank you for your thorough review.\n\nI must admit that I had been pondering how best to translate the term `extra`. Initially, I prioritized examples from previously translated documents—most notably, the example at [[NAME_REDACTED] tutorial](https://fastapi.tiangolo.com/ko/tutorial/extra-data-types/), where `extra` was translated as `추가` (\"additional\").\n\nSince this document explains that it is not necessary to use only one Pydantic model to implement a particular use case, and that `additional` Pydantic models can also be used, I feel that `additional` better captures the intended nuance than `여분`.\n\nCould you please explain in detail which aspects led you to feel that `여분` was more appropriate?", "path": "docs/ko/docs/tutorial/extra-models.md", "line": 1, "side": "RIGHT", "created_at": "2025-02-19T08:35:39+00:00" }, { "id": 1961223757, "user": "user_a1942c3a9ec0", "body": "[USER_REDACTED] \nwhat an excellent reference! I always find it valuable to review translation examples from other languages.\n\nHowever, in our Korean translated documents, we have several similar instances, such as:\n- [경로 매개변수](https://fastapi.tiangolo.com/ko/tutorial/path-params/#_17)\n- [폼 모델](https://fastapi.tiangolo.com/ko/tutorial/request-form-models/#_3)\n- [교차 출처 리소스공유](https://fastapi.tiangolo.com/ko/tutorial/cors/#_3) \n...\n\nAdditionally, incorporating English alongside Korean can actually enhance clarity in conveying the intended meaning.\n\nI appreciate your review; however, if the rationale is \"fixed repetition of words to make clear,\" I find it difficult to agree with that approach, especially since other Korean translation documents follow this convention.", "path": "docs/ko/docs/tutorial/extra-models.md", "line": 120, "side": "RIGHT", "created_at": "2025-02-19T08:48:31+00:00" }, { "id": 1961230535, "user": "user_08f3ccdc57a3", "body": "ah i understood your ref.\ni thougth the context in the same kanji culture. \nnow, If that's your intention, no problem. 👍", "path": "docs/ko/docs/tutorial/extra-models.md", "line": 1, "side": "RIGHT", "created_at": "2025-02-19T08:52:51+00:00" }, { "id": 1961232236, "user": "user_a1942c3a9ec0", "body": "[USER_REDACTED] \nOh, I'm sorry. While reading another review, I accidentally marked this excellent review as resolved. Thank you for waiting.", "path": "docs/ko/docs/tutorial/extra-models.md", "line": null, "side": "RIGHT", "created_at": "2025-02-19T08:53:56+00:00" }, { "id": 1961234263, "user": "user_a1942c3a9ec0", "body": "[USER_REDACTED] \nI discovered my mistake and reopened your review; is it okay if I mark this one as resolved?", "path": "docs/ko/docs/tutorial/extra-models.md", "line": null, "side": "RIGHT", "created_at": "2025-02-19T08:55:09+00:00" }, { "id": 1961241177, "user": "user_08f3ccdc57a3", "body": "I think the problem is that the Korean rule was written too long ago.🤔(just written May, 2021. This is common with localization issues)\n\n🤔🤔🤔If you need to sync with older docs, your way is great", "path": "docs/ko/docs/tutorial/extra-models.md", "line": 120, "side": "RIGHT", "created_at": "2025-02-19T08:59:24+00:00" }, { "id": 1961243713, "user": "user_a1942c3a9ec0", "body": "[USER_REDACTED] \nyes your right, this sentence is not perfectly fit with original english document,\nbecause in previous review, we little twist it,\nand I 100% respect your point of view.\n\nlet's talk about this in the next conversation", "path": "docs/ko/docs/tutorial/extra-models.md", "line": null, "side": "RIGHT", "created_at": "2025-02-19T09:00:49+00:00" }, { "id": 1961246783, "user": "user_a1942c3a9ec0", "body": "you clean up duplicated word! thank you", "path": "docs/ko/docs/tutorial/extra-models.md", "line": null, "side": "RIGHT", "created_at": "2025-02-19T09:02:45+00:00" }, { "id": 1961282335, "user": "user_a1942c3a9ec0", "body": "[USER_REDACTED] \nHowever, I'm a bit confused now.\nIf I understood you correctly, you're arguing that the sentence emphasizes the `flexibility of unpacking, like with **user_dict—as its advantage` \n\nYet, when looking at the entire paragraph, it seems to simply indicate that you can directly use a dictionary's keys. Isn't it just presenting an alternative method rather than favoring one over the other? \n\nI haven't found any indication that one method is superior.\n\n## Unpacking a dict\n\nIf we take a dict like user_dict and pass it to a function (or class) with **user_dict, Python will \"unpack\" it. It will pass the keys and values of the user_dict directly as key-value arguments.\n\nSo, continuing with the user_dict from above, writing:\n```python\nUserInDB(**user_dict)\n```\n\nwould result in something equivalent to:\n\n```python\nUserInDB(\n username=\"john\",\n password=\"secret\",\n email=\"[EMAIL_REDACTED]\",\n full_name=None,\n)\n```\n\nOr more exactly, using user_dict directly, with whatever contents it might have in the future:\n\n```python\nUserInDB(\n username = user_dict[\"username\"],\n password = user_dict[\"password\"],\n email = user_dict[\"email\"],\n full_name = user_dict[\"full_name\"],\n)\n```", "path": "docs/ko/docs/tutorial/extra-models.md", "line": null, "side": "RIGHT", "created_at": "2025-02-19T09:21:53+00:00" }, { "id": 1961286813, "user": "user_a1942c3a9ec0", "body": "[USER_REDACTED] \n\nAnd then adding the extra keyword argument hashed_password=hashed_password, like in:\n\n`포함하면` -> `추가하면` is very acceptable, but why do you think `추가` -> `여분` in this sentence? I need some explain 😢", "path": "docs/ko/docs/tutorial/extra-models.md", "line": null, "side": "RIGHT", "created_at": "2025-02-19T09:24:36+00:00" }, { "id": 1961303001, "user": "user_a1942c3a9ec0", "body": "[USER_REDACTED] \nyeah you can think about the korean rule is written too long ago. \nbut in the reply section, as you know, we are talk about our standard.\n\nIt might come off as a bit blunt, but I think if we're going to change a convention, we should discuss it in our discussion forum.", "path": "docs/ko/docs/tutorial/extra-models.md", "line": 120, "side": "RIGHT", "created_at": "2025-02-19T09:33:56+00:00" }, { "id": 1961445642, "user": "user_a1942c3a9ec0", "body": "[USER_REDACTED] \nbased on our previous conversation, I think this issue has been resolved.", "path": "docs/ko/docs/tutorial/extra-models.md", "line": 124, "side": "RIGHT", "created_at": "2025-02-19T10:46:16+00:00" }, { "id": 1961459636, "user": "user_a1942c3a9ec0", "body": "[USER_REDACTED], regarding the sentence:\n\n> \"The supporting additional functions fake_password_hasher and fake_save_user are just to demo a possible flow of the data, but they of course are not providing any real security.\"\n\nI believe that using `추가적으로 제공된 함수` is more appropriate than `지원된 추가적인 함수` for the following reasons (and I’d love to hear your thoughts as well):\n\n1. It sounds odd to have both 지원된 and 추가적인 together.\n2. Although \"supporting\" might be translated as 지원된 on a word-for-word basis, the overall context suggests that it refers to functions that are additionally provided (as in the case of fake_password_hasher).", "path": "docs/ko/docs/tutorial/extra-models.md", "line": 146, "side": "RIGHT", "created_at": "2025-02-19T10:55:11+00:00" }, { "id": 1963334687, "user": "user_a1942c3a9ec0", "body": "[USER_REDACTED] \nI change `포함하면` to `추가하면` at this [commit](https://github.com/fastapi/fastapi/pull/13063/commits/900ba376762f1a5b71ed2463727ed0449b24b391)", "path": "docs/ko/docs/tutorial/extra-models.md", "line": null, "side": "RIGHT", "created_at": "2025-02-20T10:53:45+00:00" }, { "id": 1963378684, "user": "user_a1942c3a9ec0", "body": "[USER_REDACTED] \nI think this committed change makes sense. Please check out the [commit](https://github.com/fastapi/fastapi/pull/13063/commits/34884c4f114cfa8dbe3275c6d1286f7b6d1e5596) for details.", "path": "docs/ko/docs/tutorial/extra-models.md", "line": null, "side": "RIGHT", "created_at": "2025-02-20T11:13:55+00:00" } ], "meta": { "languages": [ "md" ], "touches_tests": false, "review_state_summary": { "COMMENTED": 30, "APPROVED": 1, "CHANGES_REQUESTED": 2 }, "meaningful_comment_count": 43, "has_approval": true, "has_changes_requested": true, "total_review_comments": 43 } } { "_id": "673e76c37f00fb46", "_schema_version": "1.0", "_cleaned_at": "2026-02-12T07:46:52.257948+00:00", "repo": "tiangolo/fastapi", "repo_url": "https://github.com/fastapi/fastapi", "license_name": "MIT License", "license_spdx": "MIT", "pr_number": 13051, "title": "🌐 Add Chinese translation for `docs/zh/docs/tutorial/sql-databases.md`", "body": "Add Chinese translation for `docs/zh/docs/tutorial/sql-databases.md`\n给 `docs/zh/docs/tutorial/sql-databases.md` 增加了中文翻译", "author": "user_6fcb07a75ce9", "created_at": "2024-12-09T21:24:07+00:00", "merged_at": "2024-12-15T17:11:14+00:00", "base_branch": "master", "head_branch": "translate/sql_databases", "additions": 360, "deletions": 0, "changed_files": 1, "files": [ { "filename": "docs/zh/docs/tutorial/sql-databases.md", "status": "added", "additions": 360, "deletions": 0, "changes": 360, "patch": "@@ -0,0 +1,360 @@\n+# SQL(关系型)数据库\n+\n+**FastAPI** 并不要求您使用 SQL(关系型)数据库。您可以使用**任何**想用的数据库。\n+\n+这里,我们来看一个使用 SQLModel 的示例。\n+\n+**SQLModel** 是基于 SQLAlchemy 和 Pydantic 构建的。它由 **FastAPI** 的同一作者制作,旨在完美匹配需要使用 **SQL 数据库**的 FastAPI 应用程序。\n+\n+/// tip\n+\n+您可以使用任何其他您想要的 SQL 或 NoSQL 数据库(在某些情况下称为 “ORM”),FastAPI 不会强迫您使用任何东西。😎\n+\n+///\n+\n+由于 SQLModel 基于 SQLAlchemy,因此您可以轻松使用任何由 SQLAlchemy **支持的数据库**(这也让它们被 SQLModel 支持),例如:\n+\n+* PostgreSQL\n+* MySQL\n+* SQLite\n+* Oracle\n+* Microsoft SQL Server 等.\n+\n+在这个例子中,我们将使用 **SQLite**,因为它使用单个文件,并且 Python 对其有集成支持。因此,您可以直接复制这个例子并运行。\n+\n+之后,对于您的生产应用程序,您可能会想要使用像 PostgreSQL 这样的数据库服务器。\n+\n+/// tip\n+\n+有一个使用 **FastAPI** 和 **PostgreSQL** 的官方的项目生成器,其中包括了前端和更多工具: https://github.com/fastapi/full-stack-fastapi-template\n+\n+///\n+\n+这是一个非常简单和简短的教程。如果您想了解一般的数据库、SQL 或更高级的功能,请查看 SQLModel 文档。\n+\n+## 安装 `SQLModel`\n+\n+首先,确保您创建并激活了[虚拟环境](../virtual-environments.md){.internal-link target=_blank},然后安装了 `sqlmodel` :\n+\n+
        \n+\n+```console\n+$ pip install sqlmodel\n+---> 100%\n+```\n+\n+
        \n+\n+## 创建含有单一模型的应用程序\n+\n+我们首先创建应用程序的最简单的第一个版本,只有一个 **SQLModel** 模型。\n+\n+稍后我们将通过下面的**多个模型**提高其安全性和多功能性。🤓\n+\n+### 创建模型\n+\n+导入 `SQLModel` 并创建一个数据库模型:\n+\n+{* ../../docs_src/sql_databases/tutorial001_an_py310.py ln[1:11] hl[7:11] *}\n+\n+`Hero` 类与 Pydantic 模型非常相似(实际上,从底层来看,它确实*就是一个 Pydantic 模型*)。\n+\n+有一些区别:\n+\n+* `table=True` 会告诉 SQLModel 这是一个*表模型*,它应该表示 SQL 数据库中的一个*表*,而不仅仅是一个*数据模型*(就像其他常规的 Pydantic 类一样)。\n+\n+* `Field(primary_key=True)` 会告诉 SQLModel `id` 是 SQL 数据库中的**主键**(您可以在 SQLModel 文档中了解更多关于 SQL 主键的信息)。\n+\n+ 把类型设置为 `int | None` ,SQLModel 就能知道该列在 SQL 数据库中应该是 `INTEGER` 类型,并且应该是 `NULLABLE` 。\n+\n+* `Field(index=True)` 会告诉 SQLModel 应该为此列创建一个 **SQL 索引**,这样在读取按此列过滤的数据时,程序能在数据库中进行更快的查找。\n+\n+ SQLModel 会知道声明为 `str` 的内容将是类型为 `TEXT` (或 `VARCHAR` ,具体取决于数据库)的 SQL 列。\n+\n+### 创建引擎(Engine)\n+\n+SQLModel 的引擎 `engine`(实际上它是一个 SQLAlchemy `engine` )是用来与数据库**保持连接**的。\n+\n+您只需构建**一个 `engine`**,来让您的所有代码连接到同一个数据库。\n+\n+{* ../../docs_src/sql_databases/tutorial001_an_py310.py ln[14:18] hl[14:15,17:18] *}\n+\n+使用 `check_same_thread=False` 可以让 FastAPI 在不同线程中使用同一个 SQLite 数据库。这很有必要,因为**单个请求**可能会使用**多个线程**(例如在依赖项中)。\n+\n+不用担心,我们会按照代码结构确保**每个请求使用一个单独的 SQLModel *会话***,这实际上就是 `check_same_thread` 想要实现的。\n+\n+### 创建表\n+\n+然后,我们来添加一个函数,使用 `SQLModel.metadata.create_all(engine)` 为所有*表模型***创建表**。\n+\n+{* ../../docs_src/sql_databases/tutorial001_an_py310.py ln[21:22] hl[21:22] *}\n+\n+### 创建会话(Session)依赖项\n+\n+**`Session`** 会存储**内存中的对象**并跟踪数据中所需更改的内容,然后它**使用 `engine`** 与数据库进行通信。\n+\n+我们会使用 `yield` 创建一个 FastAPI **依赖项**,为每个请求提供一个新的 `Session` 。这确保我们每个请求使用一个单独的会话。🤓\n+\n+然后我们创建一个 `Annotated` 的依赖项 `SessionDep` 来简化其他也会用到此依赖的代码。\n+\n+{* ../../docs_src/sql_databases/tutorial001_an_py310.py ln[25:30] hl[25:27,30] *}\n+\n+### 在启动时创建数据库表\n+\n+我们会在应用程序启动时创建数据库表。\n+\n+{* ../../docs_src/sql_databases/tutorial001_an_py310.py ln[32:37] hl[35:37] *}\n+\n+此处,在应用程序启动事件中,我们创建了表。\n+\n+而对于生产环境,您可能会用一个能够在启动应用程序之前运行的迁移脚本。🤓\n+\n+/// tip\n+\n+SQLModel 将会拥有封装 Alembic 的迁移工具,但目前您可以直接使用 Alembic。\n+\n+///\n+\n+### 创建 Hero 类\n+\n+因为每个 SQLModel 模型同时也是一个 Pydantic 模型,所以您可以在与 Pydantic 模型相同的**类型注释**中使用它。\n+\n+例如,如果您声明一个类型为 `Hero` 的参数,它将从 **JSON 主体**中读取数据。\n+\n+同样,您可以将其声明为函数的**返回类型**,然后数据的结构就会显示在自动生成的 API 文档界面中。\n+\n+{* ../../docs_src/sql_databases/tutorial001_an_py310.py ln[40:45] hl[40:45] *}\n+\n+\n+\n+这里,我们使用 `SessionDep` 依赖项(一个 `Session` )将新的 `Hero` 添加到 `Session` 实例中,提交更改到数据库,刷新 hero 中的数据,并返回它。\n+\n+### 读取 Hero 类\n+\n+我们可以使用 `select()` 从数据库中**读取** `Hero` 类,并利用 `limit` 和 `offset` 来对结果进行分页。\n+\n+{* ../../docs_src/sql_databases/tutorial001_an_py310.py ln[48:55] hl[51:52,54] *}\n+\n+### 读取单个 Hero\n+\n+我们可以**读取**单个 `Hero` 。\n+\n+{* ../../docs_src/sql_databases/tutorial001_an_py310.py ln[58:63] hl[60] *}\n+\n+### 删除单个 Hero\n+\n+我们也可以**删除**单个 `Hero` 。\n+\n+{* ../../docs_src/sql_databases/tutorial001_an_py310.py ln[66:73] hl[71] *}\n+\n+### 运行应用程序\n+\n+您可以运行这个应用程序:\n+\n+
        \n+\n+```console\n+$ fastapi dev main.py\n+\n+INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit)\n+```\n+\n+
        \n+\n+然后在 `/docs` UI 中,您能够看到 **FastAPI** 会用这些**模型**来**记录** API,并且还会用它们来**序列化**和**验证**数据。\n+\n+
        \n+\n+
        \n+\n+## 更新应用程序以支持多个模型\n+\n+现在让我们稍微**重构**一下这个应用,以提高**安全性**和**多功能性**。\n+\n+如果您查看之前的应用程序,您可以在 UI 界面中看到,到目前为止,由客户端决定要创建的 `Hero` 的 `id` 值。😱\n+\n+我们不应该允许这样做,因为他们可能会覆盖我们在数据库中已经分配的 `id` 。决定 `id` 的行为应该由**后端**或**数据库**来完成,**而非客户端**。\n+\n+此外,我们为 hero 创建了一个 `secret_name` ,但到目前为止,我们在各处都返回了它,这就不太**秘密**了……😅\n+\n+我们将通过添加一些**额外的模型**来解决这些问题,而 SQLModel 将在这里大放异彩。✨\n+\n+### 创建多个模型\n+\n+在 **SQLModel** 中,任何含有 `table=True` 属性的模型类都是一个**表模型**。\n+\n+任何不含有 `table=True` 属性的模型类都是**数据模型**,这些实际上只是 Pydantic 模型(附带一些小的额外功能)。🤓\n+\n+有了 SQLModel,我们就可以利用**继承**来在所有情况下**避免重复**所有字段。\n+\n+#### `HeroBase` - 基类\n+\n+我们从一个 `HeroBase` 模型开始,该模型具有所有模型**共享的字段**:\n+\n+* `name`\n+* `age`\n+\n+{* ../../docs_src/sql_databases/tutorial002_an_py310.py ln[7:9] hl[7:9] *}\n+\n+#### `Hero` - *表模型*\n+\n+接下来,我们创建 `Hero` ,实际的*表模型*,并添加那些不总是在其他模型中的**额外字段**:\n+\n+* `id`\n+* `secret_name`\n+\n+因为 `Hero` 继承自 HeroBase ,所以它**也**包含了在 `HeroBase` 中声明过的**字段**。因此 `Hero` 的所有字段为:\n+\n+* `id`\n+* `name`\n+* `age`\n+* `secret_name`\n+\n+{* ../../docs_src/sql_databases/tutorial002_an_py310.py ln[7:14] hl[12:14] *}\n+\n+#### `HeroPublic` - 公共*数据模型*\n+\n+接下来,我们创建一个 `HeroPublic` 模型,这是将**返回**给 API 客户端的模型。\n+\n+它包含与 `HeroBase` 相同的字段,因此不会包括 `secret_name` 。\n+\n+终于,我们英雄(hero)的身份得到了保护! 🥷\n+\n+它还重新声明了 `id: int` 。这样我们便与 API 客户端建立了一种**约定**,使他们始终可以期待 `id` 存在并且是一个整数 `int`(永远不会是 `None` )。\n+\n+/// tip\n+\n+确保返回模型始终提供一个值并且始终是 `int` (而不是 `None` )对 API 客户端非常有用,他们可以在这种确定性下编写更简单的代码。\n+\n+此外,**自动生成的客户端**将拥有更简洁的接口,这样与您的 API 交互的开发者就能更轻松地使用您的 API。😎\n+\n+///\n+\n+`HeroPublic` 中的所有字段都与 `HeroBase` 中的相同,其中 `id` 声明为 `int` (不是 `None` ):\n+\n+* `id`\n+* `name`\n+* `age`\n+* `secret_name`\n+\n+{* ../../docs_src/sql_databases/tutorial002_an_py310.py ln[7:18] hl[17:18] *}\n+\n+#### `HeroCreate` - 用于创建 hero 的*数据模型*\n+\n+现在我们创建一个 `HeroCreate` 模型,这是用于**验证**客户数据的模型。\n+\n+它不仅拥有与 `HeroBase` 相同的字段,还有 `secret_name` 。\n+\n+现在,当客户端**创建一个新的 hero** 时,他们会发送 `secret_name` ,它会被存储到数据库中,但这些 `secret_name` 不会通过 API 返回给客户端。\n+\n+/// tip\n+\n+这应当是**密码**被处理的方式:接收密码,但不要通过 API 返回它们。\n+\n+在存储密码之前,您还应该对密码的值进行**哈希**处理,**绝不要以明文形式存储它们**。\n+\n+///\n+\n+`HeroCreate` 的字段包括:\n+\n+* `name`\n+* `age`\n+* `secret_name`\n+\n+{* ../../docs_src/sql_databases/tutorial002_an_py310.py ln[7:22] hl[21:22] *}\n+\n+#### `HeroUpdate` - 用于更新 hero 的*数据模型*\n+\n+在之前的应用程序中,我们没有办法**更新 hero**,但现在有了**多个模型**,我们便能做到这一点了。🎉\n+\n+`HeroUpdate` *数据模型*有些特殊,它包含创建新 hero 所需的**所有相同字段**,但所有字段都是**可选的**(它们都有默认值)。这样,当您更新一个 hero 时,您可以只发送您想要更新的字段。\n+\n+因为所有**字段实际上**都发生了**变化**(类型现在包括 `None` ,并且它们现在有一个默认值 `None` ),我们需要**重新声明**它们。\n+\n+我们会重新声明所有字段,因此我们并不是真的需要从 `HeroBase` 继承。我会让它继承只是为了保持一致,但这并不必要。这更多是个人喜好的问题。🤷\n+\n+`HeroUpdate` 的字段包括:\n+\n+* `name`\n+* `age`\n+* `secret_name`\n+\n+{* ../../docs_src/sql_databases/tutorial002_an_py310.py ln[7:28] hl[25:28] *}\n+\n+### 使用 `HeroCreate` 创建并返回 `HeroPublic`\n+\n+既然我们有了**多个模型**,我们就可以对使用它们的应用程序部分进行更新。\n+\n+我们在请求中接收到一个 `HeroCreate` *数据模型*,然后从中创建一个 `Hero` *表模型*。\n+\n+这个新的*表模型* `Hero` 会包含客户端发送的字段,以及一个由数据库生成的 `id` 。\n+\n+然后我们将与函数中相同的*表模型* `Hero` 原样返回。但是由于我们使用 `HeroPublic` *数据模型*声明了 `response_model` ,**FastAPI** 会使用 `HeroPublic` 来验证和序列化数据。\n+\n+{* ../../docs_src/sql_databases/tutorial002_an_py310.py ln[56:62] hl[56:58] *}\n+\n+/// tip\n+\n+现在我们使用 `response_model=HeroPublic` 来代替**返回类型注释** `-> HeroPublic` ,因为我们返回的值实际上**并不是** `HeroPublic` 类型。\n+\n+如果我们声明了 `-> HeroPublic` ,您的编辑器和代码检查工具会抱怨(但也确实理所应当)您返回了一个 `Hero` 而不是一个 `HeroPublic` 。\n+\n+通过 `response_model` 的声明,我们让 **FastAPI** 按照它自己的方式处理,而不会干扰类型注解以及编辑器和其他工具提供的帮助。\n+\n+///\n+\n+### 用 `HeroPublic` 读取 Hero\n+\n+我们可以像之前一样**读取** `Hero` 。同样,使用 `response_model=list[HeroPublic]` 确保正确地验证和序列化数据。\n+\n+{* ../../docs_src/sql_databases/tutorial002_an_py310.py ln[65:72] hl[65] *}\n+\n+### 用 `HeroPublic` 读取单个 Hero\n+\n+我们可以**读取**单个 `hero` 。\n+\n+{* ../../docs_src/sql_databases/tutorial002_an_py310.py ln[75:80] hl[77] *}\n+\n+### 用 `HeroUpdate` 更新单个 Hero\n+\n+我们可以**更新**单个 `hero` 。为此,我们会使用 HTTP 的 `PATCH` 操作。\n+\n+在代码中,我们会得到一个 `dict` ,其中包含客户端发送的所有数据,**只有客户端发送的数据**,并排除了任何一个仅仅作为默认值存在的值。为此,我们使用 `exclude_unset=True` 。这是最主要的技巧。🪄\n+\n+然后我们会使用 `hero_db.sqlmodel_update(hero_data)` ,来利用 `hero_data` 的数据更新 `hero_db` 。\n+\n+{* ../../docs_src/sql_databases/tutorial002_an_py310.py ln[83:93] hl[83:84,88:89] *}\n+\n+### (又一次)删除单个 Hero\n+\n+**删除**一个 hero 基本保持不变。\n+\n+我们不会满足在这一部分中重构一切的愿望。😅\n+\n+{* ../../docs_src/sql_databases/tutorial002_an_py310.py ln[96:103] hl[101] *}\n+\n+### (又一次)运行应用程序\n+\n+您可以再运行一次应用程序:\n+\n+
        \n+\n+```console\n+$ fastapi dev main.py\n+\n+INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit)\n+```\n+\n+
        \n+\n+您会在 `/docs` API UI 看到它现在已经更新,并且在进行创建 hero 等操作时,它不会再期望从客户端接收 `id` 数据。\n+\n+
        \n+\n+
        \n+\n+## 总结\n+\n+您可以使用 **SQLModel** 与 SQL 数据库进行交互,并通过*数据模型*和*表模型*简化代码。\n+\n+您可以在 SQLModel 的文档中学习到更多内容,其中有一个更详细的关于如何将 SQLModel 与 FastAPI 一起使用的教程。🚀" } ], "reviews": [ { "id": 2490477225, "user": "user_63ed12e5198d", "state": "COMMENTED", "body": null, "submitted_at": "2024-12-10T00:38:37+00:00" }, { "id": 2490493452, "user": "user_63ed12e5198d", "state": "COMMENTED", "body": null, "submitted_at": "2024-12-10T00:46:41+00:00" }, { "id": 2492964991, "user": "user_6fcb07a75ce9", "state": "COMMENTED", "body": null, "submitted_at": "2024-12-10T16:51:20+00:00" }, { "id": 2493021005, "user": "user_6fcb07a75ce9", "state": "COMMENTED", "body": null, "submitted_at": "2024-12-10T17:12:49+00:00" }, { "id": 2494436363, "user": "user_63ed12e5198d", "state": "COMMENTED", "body": null, "submitted_at": "2024-12-11T06:33:00+00:00" }, { "id": 2497271225, "user": "user_6fcb07a75ce9", "state": "COMMENTED", "body": null, "submitted_at": "2024-12-11T23:55:47+00:00" }, { "id": 2497573803, "user": "user_63ed12e5198d", "state": "APPROVED", "body": null, "submitted_at": "2024-12-12T04:21:21+00:00" } ], "review_comments": [ { "id": 1876978492, "user": "user_63ed12e5198d", "body": "花哨应该有更贴切的翻译", "path": "docs/zh/docs/tutorial/sql-databases.md", "line": null, "side": "RIGHT", "created_at": "2024-12-10T00:38:37+00:00" }, { "id": 1876992071, "user": "user_63ed12e5198d", "body": "这是为什么是三个星号连着呀", "path": "docs/zh/docs/tutorial/sql-databases.md", "line": 88, "side": "RIGHT", "created_at": "2024-12-10T00:46:41+00:00" }, { "id": 1878466837, "user": "user_6fcb07a75ce9", "body": "谢谢回复!\n“表模型”是斜体,“创建表”是粗体,再加上词语之间没有空格,他俩的星号就连在了一起。\n不过markdown能够正确解析这个语法,目前看来没有问题。", "path": "docs/zh/docs/tutorial/sql-databases.md", "line": 88, "side": "RIGHT", "created_at": "2024-12-10T16:51:20+00:00" }, { "id": 1878500659, "user": "user_6fcb07a75ce9", "body": "我准备改为“高大上”,这样应该更符合汉语表达习惯。你觉得如何?", "path": "docs/zh/docs/tutorial/sql-databases.md", "line": null, "side": "RIGHT", "created_at": "2024-12-10T17:12:49+00:00" }, { "id": 1879423920, "user": "user_63ed12e5198d", "body": "参考这个:https://cn.bing.com/dict/search?q=fancy+term&qs=n&form=Z9LH5&sp=-1&lq=0&pq=fancy+term&sc=0-10&sk=&cvid=5C4F50FD82E34CEDABBB69161958D755&ghsh=0&ghacc=0&ghpl=\n\n建议:\n对象关系映射器([NAME_REDACTED],ORM),一个术语,用来指代一种库,其中某些类对应于 SQL 数据表,这些类的实例则对应于表中的行。", "path": "docs/zh/docs/tutorial/sql-databases.md", "line": null, "side": "RIGHT", "created_at": "2024-12-11T06:32:59+00:00" }, { "id": 1881172549, "user": "user_6fcb07a75ce9", "body": "谢谢!\n\n已修改。", "path": "docs/zh/docs/tutorial/sql-databases.md", "line": null, "side": "RIGHT", "created_at": "2024-12-11T23:55:47+00:00" } ], "meta": { "languages": [ "md" ], "touches_tests": false, "review_state_summary": { "COMMENTED": 6, "APPROVED": 1 }, "meaningful_comment_count": 5, "has_approval": true, "has_changes_requested": false, "total_review_comments": 6 } } { "_id": "e78285344f03bdc0", "_schema_version": "1.0", "_cleaned_at": "2026-02-12T07:46:52.257948+00:00", "repo": "tiangolo/fastapi", "repo_url": "https://github.com/fastapi/fastapi", "license_name": "MIT License", "license_spdx": "MIT", "pr_number": 13042, "title": "🌐 Add Indonesian translation for `docs/id/docs/tutorial/first-steps.md`", "body": "Hi, I notice the Indonesian translation for this section isn't maintained. Going forward I'd love to bring more contribution for Indonesian translation starting from this file [USER_REDACTED]", "author": "user_9a0cc1308ee2", "created_at": "2024-12-06T06:09:22+00:00", "merged_at": "2024-12-12T21:46:36+00:00", "base_branch": "master", "head_branch": "docs/id/docs/tutorial/first-steps.md", "additions": 332, "deletions": 0, "changed_files": 1, "files": [ { "filename": "docs/id/docs/tutorial/first-steps.md", "status": "added", "additions": 332, "deletions": 0, "changes": 332, "patch": "@@ -0,0 +1,332 @@\n+# [NAME_REDACTED]\n+\n+File FastAPI yang paling sederhana bisa seperti berikut:\n+\n+{* ../../docs_src/first_steps/tutorial001.py *}\n+\n+Salin file tersebut ke `main.py`.\n+\n+Jalankan di server:\n+\n+
        \n+\n+```console\n+$ fastapi dev main.py\n+INFO Using path main.py\n+INFO Resolved absolute path /home/user/code/awesomeapp/main.py\n+INFO Searching for package file structure from directories with __init__.py files\n+INFO Importing from /home/user/code/awesomeapp\n+\n+ ╭─ Python module file ─╮\n+ │ │\n+ │ 🐍 main.py │\n+ │ │\n+ ╰──────────────────────╯\n+\n+INFO Importing module main\n+INFO Found importable FastAPI app\n+\n+ ╭─ [NAME_REDACTED] app ─╮\n+ │ │\n+ │ from main import app │\n+ │ │\n+ ╰──────────────────────────╯\n+\n+INFO Using import string main:app\n+\n+ ╭────────── FastAPI CLI - Development mode ───────────╮\n+ │ │\n+ │ Serving at: http://127.0.0.1:8000 │\n+ │ │\n+ │ API docs: http://127.0.0.1:8000/docs │\n+ │ │\n+ │ Running in development mode, for production use: │\n+ │ │\n+ fastapi run\n+ │ │\n+ ╰─────────────────────────────────────────────────────╯\n+\n+INFO: Will watch for changes in these directories: ['/home/user/code/awesomeapp']\n+INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit)\n+INFO: Started reloader process [2265862] using WatchFiles\n+INFO: Started server process [2265873]\n+INFO: Waiting for application startup.\n+INFO: Application startup complete.\n+```\n+\n+
        \n+\n+Di output, terdapat sebaris pesan:\n+\n+```hl_lines=\"4\"\n+INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit)\n+```\n+\n+Baris tersebut menunjukan URL dimana app aktif di komputer anda.\n+\n+\n+### Mencoba aplikasi\n+\n+Buka browser di http://127.0.0.1:8000.\n+\n+Anda akan melihat response JSON sebagai berikut:\n+\n+```JSON\n+{\"message\": \"[NAME_REDACTED]\"}\n+```\n+\n+### Dokumen API interaktif\n+\n+Sekarang kunjungi http://127.0.0.1:8000/docs.\n+\n+Anda akan melihat dokumentasi API interaktif otomatis (dibuat oleh Swagger UI):\n+\n+![Swagger UI](https://fastapi.tiangolo.com/img/index/index-01-swagger-ui-simple.png)\n+\n+### Dokumen API alternatif\n+\n+Dan sekarang, kunjungi http://127.0.0.1:8000/redoc.\n+\n+Anda akan melihat dokumentasi alternatif otomatis (dibuat oleh ReDoc):\n+\n+![ReDoc](https://fastapi.tiangolo.com/img/index/index-02-redoc-simple.png)\n+\n+### OpenAPI\n+\n+**FastAPI** membuat sebuah \"schema\" dimana semua API anda menggunakan standar **OpenAPI** untuk mendefinisikan API.\n+\n+#### \"Schema\"\n+\n+\"schema\" adalah suatu definisi atau deskripsi dari sesuatu. Bukan kode yang mengimplementasi definisi tersebut. Ini hanyalah sebuah deskripsi abstrak.\n+\n+#### \"schema\" API\n+\n+Dalam hal ini, OpenAPI adalah spesifikasi yang menunjukan bagaimana untuk mendefinisikan sebuah skema di API anda.\n+\n+Definisi skema ini termasuk jalur API anda, parameter yang bisa diterima, dll.\n+\n+#### \"schema\" Data\n+\n+Istilah \"schema\" bisa juga merujuk ke struktur data, seperti konten JSON.\n+\n+Dalam kondisi ini, ini berarti attribut JSON dan tipe data yang dimiliki, dll.\n+\n+#### [NAME_REDACTED] and JSON\n+\n+\"schema\" OpenAPI mendefinisikan skema API dari API yang anda buat. Skema tersebut termasuk definisi (atau \"schema\") dari data yang dikirim atau diterima oleh API dari **JSON Schema**, skema data standar JSON.\n+\n+#### Lihat `openapi.json`\n+\n+Jika anda penasaran bagaimana skema OpenAPI polos seperti apa, FastAPI secara otomatis membuat JSON (schema) dengan deksripsi API anda.\n+\n+anda bisa melihatnya di: http://127.0.0.1:8000/openapi.json.\n+\n+Anda akan melihat JSON yang dimulai seperti:\n+\n+```JSON\n+{\n+ \"openapi\": \"3.1.0\",\n+ \"info\": {\n+ \"title\": \"FastAPI\",\n+ \"version\": \"0.1.0\"\n+ },\n+ \"paths\": {\n+ \"/items/\": {\n+ \"get\": {\n+ \"responses\": {\n+ \"200\": {\n+ \"description\": \"[NAME_REDACTED]\",\n+ \"content\": {\n+ \"application/json\": {\n+\n+\n+\n+...\n+```\n+\n+#### [NAME_REDACTED]\n+\n+[NAME_REDACTED] adalah tulang punggung dua sistem dokumentasi API interaktif yang ada di FastAPI.\n+\n+Ada banyak alternatif sistem dokumentasi lainnya yang semuanya berdasarkan OpenAPI. Anda bisa menambahkannya ke aplikasi **FastAPI** anda.\n+\n+Anda juga bisa menggunakan OpenAPI untuk membuat kode secara otomatis, untuk klien yang menggunakan API anda. Sebagai contoh, frontend, aplikasi mobile atau IoT.\n+\n+## Ringkasan, secara bertahap\n+\n+### Langkah 1: impor `FastAPI`\n+\n+{* ../../docs_src/first_steps/tutorial001.py hl[1] *}\n+\n+`FastAPI` adalah class Python yang menyediakan semua fungsionalitas API anda.\n+\n+/// note | [NAME_REDACTED]\n+\n+`FastAPI` adalah class turunan langsung dari `Starlette`.\n+\n+Anda bisa menggunakan semua fungsionalitas Starlette dengan `FastAPI` juga.\n+\n+///\n+\n+### Langkah 2: buat \"instance\" dari `FastAPI`\n+\n+{* ../../docs_src/first_steps/tutorial001.py hl[3] *}\n+\n+Di sini variabel `app` akan menjadi sebuah \"instance\" dari class `FastAPI`.\n+\n+Ini akan menjadi gerbang utama untuk membuat semua API anda.\n+\n+### Langkah 3: Buat *operasi path*\n+\n+#### Path\n+\n+\"Path\" atau jalur di sini merujuk ke bagian URL terakhir dimulai dari `/` pertama.\n+\n+Sehingga, URL seperti:\n+\n+```\n+https://example.com/items/foo\n+```\n+\n+...path-nya adalah:\n+\n+```\n+/items/foo\n+```\n+\n+/// info\n+\n+\"path\" juga biasa disebut \"endpoint\" atau \"route\".\n+\n+///\n+\n+ketika membuat API, \"path\" adalah jalan utama untuk memisahkan \"concern\" dan \"resources\".\n+\n+#### Operasi\n+\n+\"Operasi\" di sini merujuk ke salah satu dari metode HTTP berikut.\n+\n+Salah satu dari:\n+\n+* `POST`\n+* `GET`\n+* `PUT`\n+* `DELETE`\n+\n+...dan operasi lainnya yang unik:\n+\n+* `OPTIONS`\n+* `HEAD`\n+* `PATCH`\n+* `TRACE`\n+\n+Dalam protokol HTTP, anda bisa berkomunikasi ke setiap path menggunakan satu (atau lebih) metode di atas.\n+\n+---\n+\n+Ketika membuat API, anda umumnya menggunakan metode HTTP tertentu untuk proses tertentu.\n+\n+Umumnya menggunakan:\n+\n+* `POST`: untuk membuat data.\n+* `GET`: untuk membaca data.\n+* `PUT`: untuk memperbarui data.\n+* `DELETE`: untuk menghapus data.\n+\n+Sehingga, di OpanAPI, setiap metode HTTP ini disebut sebuah \"operasi\".\n+\n+Kita akan menyebut mereka juga \"**operasi**\".\n+\n+#### Mendefinisikan *dekorator operasi path*\n+\n+{* ../../docs_src/first_steps/tutorial001.py hl[6] *}\n+\n+`[USER_REDACTED].get(\"/\")` memberitahu **FastAPI** bahwa fungsi di bawahnya mengurusi request yang menuju ke:\n+\n+* path `/`\n+* menggunakan operasi get\n+\n+/// info | `[USER_REDACTED]` Info\n+\n+Sintaksis `[USER_REDACTED]` di Python disebut \"dekorator\".\n+\n+Dekorator ditempatkan di atas fungsi. Seperti sebuah topi cantik (Saya pikir istilah ini berasal dari situ).\n+\n+\"dekorator\" memanggil dan bekerja dengan fungsi yang ada di bawahnya\n+\n+Pada kondisi ini, dekorator ini memberi tahu **FastAPI** bahwa fungsi di bawah nya berhubungan dengan **path** `/` dengan **operasi** `get`.\n+\n+Sehingga disebut **dekorator operasi path**.\n+\n+///\n+\n+Operasi lainnya yang bisa digunakan:\n+\n+* `[USER_REDACTED].post()`\n+* `[USER_REDACTED].put()`\n+* `[USER_REDACTED].delete()`\n+\n+Dan operasi unik lainnya:\n+\n+* `[USER_REDACTED].options()`\n+* `[USER_REDACTED].head()`\n+* `[USER_REDACTED].patch()`\n+* `[USER_REDACTED].trace()`\n+\n+/// tip | Tips\n+\n+Jika anda bisa menggunakan operasi apa saja (metode HTTP).\n+\n+**FastAPI** tidak mengharuskan anda menggunakan operasi tertentu.\n+\n+Informasi di sini hanyalah sebagai panduan, bukan keharusan.\n+\n+Sebagai contoh, ketika menggunakan GraphQL, semua operasi umumnya hanya menggunakan `POST`.\n+\n+///\n+\n+### Langkah 4: mendefinisikan **fungsi operasi path**\n+\n+Ini \"**fungsi operasi path**\" kita:\n+\n+* **path**: adalah `/`.\n+* **operasi**: adalah `get`.\n+* **fungsi**: adalah fungsi yang ada di bawah dekorator (di bawah `[USER_REDACTED].get(\"/\")`).\n+\n+{* ../../docs_src/first_steps/tutorial001.py hl[7] *}\n+\n+Ini adalah fungsi Python.\n+\n+Fungsi ini dipanggil **FastAPI** setiap kali menerima request ke URL \"`/`\" dengan operasi `GET`.\n+\n+Di kondisi ini, ini adalah sebuah fungsi `async`.\n+\n+---\n+\n+Anda bisa mendefinisikan fungsi ini sebagai fungsi normal daripada `async def`:\n+\n+{* ../../docs_src/first_steps/tutorial003.py hl[7] *}\n+\n+/// note | Catatan\n+\n+Jika anda tidak tahu perbedaannya, kunjungi [Async: *\"Panduan cepat\"*](../async.md#in-a-hurry){.internal-link target=_blank}.\n+\n+///\n+\n+### Langkah 5: hasilkan konten\n+\n+{* ../../docs_src/first_steps/tutorial001.py hl[8] *}\n+\n+Anda bisa menghasilkan `dict`, `list`, nilai singular seperti `str`, `int`, dll.\n+\n+Anda juga bisa menghasilkan model Pydantic (anda akan belajar mengenai ini nanti).\n+\n+Ada banyak objek dan model yang secara otomatis dikonversi ke JSON (termasuk ORM, dll). Anda bisa menggunakan yang anda suka, kemungkinan sudah didukung.\n+\n+## Ringkasan\n+\n+* Impor `FastAPI`.\n+* Buat sebuah instance `app`.\n+* Tulis **dekorator operasi path** menggunakan dekorator seperti `[USER_REDACTED].get(\"/\")`.\n+* Definisikan **fungsi operasi path**; sebagai contoh, `def root(): ...`.\n+* Jalankan server development dengan perintah `fastapi dev`." } ], "reviews": [ { "id": 2494194534, "user": "user_221aec9ffc1f", "state": "APPROVED", "body": "LGTM 🚀", "submitted_at": "2024-12-11T03:09:21+00:00" }, { "id": 2497883056, "user": "user_e5f553a5bf33", "state": "COMMENTED", "body": "[NAME_REDACTED]", "submitted_at": "2024-12-12T06:35:29+00:00" }, { "id": 2497887903, "user": "user_e5f553a5bf33", "state": "APPROVED", "body": "its ok", "submitted_at": "2024-12-12T06:36:51+00:00" }, { "id": 2499093549, "user": "user_568843bce6ca", "state": "COMMENTED", "body": null, "submitted_at": "2024-12-12T11:32:52+00:00" }, { "id": 2500287414, "user": "user_9a0cc1308ee2", "state": "COMMENTED", "body": null, "submitted_at": "2024-12-12T17:07:31+00:00" } ], "review_comments": [ { "id": 1881895909, "user": "user_568843bce6ca", "body": "This is not displaying properly. Can you check it, please?\nYou can check the translation guidelines if you have any questions. Thanks!", "path": "docs/id/docs/tutorial/first-steps.md", "line": null, "side": "RIGHT", "created_at": "2024-12-12T11:32:52+00:00" }, { "id": 1882555910, "user": "user_9a0cc1308ee2", "body": "Hi [USER_REDACTED] thanks for the review. I have fixed improper code for text boxes so now all text boxes are displayed properly", "path": "docs/id/docs/tutorial/first-steps.md", "line": null, "side": "RIGHT", "created_at": "2024-12-12T17:07:31+00:00" } ], "meta": { "languages": [ "md" ], "touches_tests": false, "review_state_summary": { "APPROVED": 2, "COMMENTED": 3 }, "meaningful_comment_count": 2, "has_approval": true, "has_changes_requested": false, "total_review_comments": 2 } } { "_id": "b36bc37763d33dda", "_schema_version": "1.0", "_cleaned_at": "2026-02-12T07:46:52.257948+00:00", "repo": "pandas-dev/pandas", "repo_url": "https://github.com/pandas-dev/pandas", "license_name": "BSD 3-Clause \"New\" or \"Revised\" License", "license_spdx": "BSD-3-Clause", "pr_number": 63543, "title": "DOC: Inline docstrings of a batch of functions in `pandas/core/groupby/groupby.py`", "body": "retry\n\n- [ ] closes #62437 (Replace xxxx with the GitHub issue number)\n- [ ] [Tests added and passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#writing-tests) if fixing a bug or adding a new feature\n- [x] All [code checks passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit).\n- [ ] Added [type annotations](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#type-hints) to new arguments/methods/functions.\n- [ ] Added an entry in the latest `doc/source/whatsnew/vX.X.X.rst` file if fixing a bug or adding a new feature.\n- [ ] If I used AI to develop this pull request, I prompted it to follow `AGENTS.md`.", "author": "user_5b0b62fe7839", "created_at": "2026-01-02T12:14:21+00:00", "merged_at": "2026-01-05T17:39:54+00:00", "base_branch": "main", "head_branch": "inline_group_std", "additions": 105, "deletions": 63, "changed_files": 1, "files": [ { "filename": "pandas/core/groupby/groupby.py", "status": "modified", "additions": 105, "deletions": 63, "changes": 168, "patch": "@@ -158,14 +158,6 @@ class providing the base-class of operations.\n RollingGroupby,\n )\n \n-_common_see_also = \"\"\"\n- See Also\n- --------\n- Series.%(name)s : Apply a function %(name)s to a Series.\n- DataFrame.%(name)s : Apply a function %(name)s\n- to each row or column of a DataFrame.\n-\"\"\"\n-\n _groupby_agg_method_engine_template = \"\"\"\n Compute {fname} of group values.\n \n@@ -1975,8 +1967,6 @@ def _obj_1d_constructor(self) -> Callable:\n return self.obj._constructor\n \n [USER_REDACTED]\n- [USER_REDACTED](name=\"groupby\")\n- [USER_REDACTED](see_also=_common_see_also)\n def any(self, skipna: bool = True) -> NDFrameT:\n \"\"\"\n [NAME_REDACTED] if any value in the group is truthful, else False.\n@@ -1991,7 +1981,12 @@ def any(self, skipna: bool = True) -> NDFrameT:\n Series or [NAME_REDACTED] or Series of boolean values, where a value is True if any element\n is True within its respective group, False otherwise.\n- %(see_also)s\n+\n+ See Also\n+ --------\n+ Series.any : Apply function any to a Series.\n+ DataFrame.any : Apply function any to each row or column of a DataFrame.\n+\n Examples\n --------\n For SeriesGroupBy:\n@@ -2032,8 +2027,6 @@ def any(self, skipna: bool = True) -> NDFrameT:\n )\n \n [USER_REDACTED]\n- [USER_REDACTED](name=\"groupby\")\n- [USER_REDACTED](see_also=_common_see_also)\n def all(self, skipna: bool = True) -> NDFrameT:\n \"\"\"\n [NAME_REDACTED] if all values in the group are truthful, else False.\n@@ -2048,7 +2041,12 @@ def all(self, skipna: bool = True) -> NDFrameT:\n Series or [NAME_REDACTED] or Series of boolean values, where a value is True if all elements\n are True within its respective group, False otherwise.\n- %(see_also)s\n+\n+ See Also\n+ --------\n+ Series.all : Apply function all to a Series.\n+ DataFrame.all : Apply function all to each row or column of a DataFrame.\n+\n Examples\n --------\n \n@@ -2090,8 +2088,6 @@ def all(self, skipna: bool = True) -> NDFrameT:\n )\n \n [USER_REDACTED]\n- [USER_REDACTED](name=\"groupby\")\n- [USER_REDACTED](see_also=_common_see_also)\n def count(self) -> NDFrameT:\n \"\"\"\n Compute count of group, excluding missing values.\n@@ -2100,7 +2096,12 @@ def count(self) -> NDFrameT:\n -------\n Series or [NAME_REDACTED] of values within each group.\n- %(see_also)s\n+\n+ See Also\n+ --------\n+ Series.count : Apply function count to a Series.\n+ DataFrame.count : Apply function count to each row or column of a DataFrame.\n+\n Examples\n --------\n For SeriesGroupBy:\n@@ -2191,8 +2192,6 @@ def hfunc(bvalues: ArrayLike) -> ArrayLike:\n return result\n \n [USER_REDACTED]\n- [USER_REDACTED](name=\"groupby\")\n- [USER_REDACTED](see_also=_common_see_also)\n def mean(\n self,\n numeric_only: bool = False,\n@@ -2232,7 +2231,12 @@ def mean(\n -------\n pandas.Series or pandas.[NAME_REDACTED] of values within each group. Same object type as the caller.\n- %(see_also)s\n+\n+ See Also\n+ --------\n+ Series.mean : Apply function mean to a Series.\n+ DataFrame.mean : Apply function mean to each row or column of a DataFrame.\n+\n Examples\n --------\n >>> df = pd.DataFrame(\n@@ -2318,9 +2322,8 @@ def median(self, numeric_only: bool = False, skipna: bool = True) -> NDFrameT:\n \n See Also\n --------\n- Series.groupby : Apply a function groupby to a Series.\n- DataFrame.groupby : Apply a function groupby to each row or column of a\n- DataFrame.\n+ Series.median : Apply function median to a Series.\n+ DataFrame.median : Apply function median to each row or column of a DataFrame.\n \n Examples\n --------\n@@ -2392,8 +2395,6 @@ def median(self, numeric_only: bool = False, skipna: bool = True) -> NDFrameT:\n return result.__finalize__(self.obj, method=\"groupby\")\n \n [USER_REDACTED]\n- [USER_REDACTED](name=\"groupby\")\n- [USER_REDACTED](see_also=_common_see_also)\n def std(\n self,\n ddof: int = 1,\n@@ -2442,7 +2443,12 @@ def std(\n -------\n Series or [NAME_REDACTED] deviation of values within each group.\n- %(see_also)s\n+\n+ See Also\n+ --------\n+ Series.std : Apply function std to a Series.\n+ DataFrame.std : Apply function std to each row or column of a DataFrame.\n+\n Examples\n --------\n For SeriesGroupBy:\n@@ -2505,8 +2511,6 @@ def std(\n )\n \n [USER_REDACTED]\n- [USER_REDACTED](name=\"groupby\")\n- [USER_REDACTED](see_also=_common_see_also)\n def var(\n self,\n ddof: int = 1,\n@@ -2554,7 +2558,12 @@ def var(\n -------\n Series or [NAME_REDACTED] of values within each group.\n- %(see_also)s\n+\n+ See Also\n+ --------\n+ Series.var : Apply function var to a Series.\n+ DataFrame.var : Apply function var to each row or column of a DataFrame.\n+\n Examples\n --------\n For SeriesGroupBy:\n@@ -2846,8 +2855,6 @@ def sem(\n )\n \n [USER_REDACTED]\n- [USER_REDACTED](name=\"groupby\")\n- [USER_REDACTED](see_also=_common_see_also)\n def size(self) -> DataFrame | Series:\n \"\"\"\n Compute group sizes.\n@@ -2857,7 +2864,12 @@ def size(self) -> DataFrame | Series:\n DataFrame or [NAME_REDACTED] of rows in each group as a Series if as_index is True\n or a DataFrame if as_index is False.\n- %(see_also)s\n+\n+ See Also\n+ --------\n+ Series.size : Apply function size to a Series.\n+ DataFrame.size : Apply function size to each row or column of a DataFrame.\n+\n Examples\n --------\n \n@@ -4252,8 +4264,6 @@ def bfill(self, limit: int | None = None):\n \n [USER_REDACTED]\n [USER_REDACTED]\n- [USER_REDACTED](name=\"groupby\")\n- [USER_REDACTED](see_also=_common_see_also)\n def nth(self) -> GroupByNthSelector:\n \"\"\"\n Take the nth row from each group if n is an int, otherwise a subset of rows.\n@@ -4269,7 +4279,12 @@ def nth(self) -> GroupByNthSelector:\n -------\n Series or DataFrame\n N-th value within each group.\n- %(see_also)s\n+\n+ See Also\n+ --------\n+ Series.nth : Apply function nth to a Series.\n+ DataFrame.nth : Apply function nth to each row or column of a DataFrame.\n+\n Examples\n --------\n \n@@ -4751,8 +4766,6 @@ def cumcount(self, ascending: bool = True):\n return self._obj_1d_constructor(cumcounts, index)\n \n [USER_REDACTED]\n- [USER_REDACTED](name=\"groupby\")\n- [USER_REDACTED](see_also=_common_see_also)\n def rank(\n self,\n method: str = \"average\",\n@@ -4784,7 +4797,12 @@ def rank(\n -------\n [NAME_REDACTED] ranking of values within each group.\n- %(see_also)s\n+\n+ See Also\n+ --------\n+ Series.rank : Apply function rank to a Series.\n+ DataFrame.rank : Apply function rank to each row or column of a DataFrame.\n+\n Examples\n --------\n >>> df = pd.DataFrame(\n@@ -4838,8 +4856,6 @@ def rank(\n )\n \n [USER_REDACTED]\n- [USER_REDACTED](name=\"groupby\")\n- [USER_REDACTED](see_also=_common_see_also)\n def cumprod(self, numeric_only: bool = False, *args, **kwargs) -> NDFrameT:\n \"\"\"\n Cumulative product for each group.\n@@ -4858,7 +4874,12 @@ def cumprod(self, numeric_only: bool = False, *args, **kwargs) -> NDFrameT:\n -------\n Series or [NAME_REDACTED] product for each group. Same object type as the caller.\n- %(see_also)s\n+\n+ See Also\n+ --------\n+ Series.cumprod : Apply function cumprod to a Series.\n+ DataFrame.cumprod : Apply function cumprod to each row or column of a DataFrame.\n+\n Examples\n --------\n For SeriesGroupBy:\n@@ -4899,8 +4920,6 @@ def cumprod(self, numeric_only: bool = False, *args, **kwargs) -> NDFrameT:\n return self._cython_transform(\"cumprod\", numeric_only, **kwargs)\n \n [USER_REDACTED]\n- [USER_REDACTED](name=\"groupby\")\n- [USER_REDACTED](see_also=_common_see_also)\n def cumsum(self, numeric_only: bool = False, *args, **kwargs) -> NDFrameT:\n \"\"\"\n Cumulative sum for each group.\n@@ -4919,7 +4938,12 @@ def cumsum(self, numeric_only: bool = False, *args, **kwargs) -> NDFrameT:\n -------\n Series or [NAME_REDACTED] sum for each group. Same object type as the caller.\n- %(see_also)s\n+\n+ See Also\n+ --------\n+ Series.cumsum : Apply function cumsum to a Series.\n+ DataFrame.cumsum : Apply function cumsum to each row or column of a DataFrame.\n+\n Examples\n --------\n For SeriesGroupBy:\n@@ -4960,8 +4984,6 @@ def cumsum(self, numeric_only: bool = False, *args, **kwargs) -> NDFrameT:\n return self._cython_transform(\"cumsum\", numeric_only, **kwargs)\n \n [USER_REDACTED]\n- [USER_REDACTED](name=\"groupby\")\n- [USER_REDACTED](see_also=_common_see_also)\n def cummin(\n self,\n numeric_only: bool = False,\n@@ -4982,7 +5004,12 @@ def cummin(\n -------\n Series or [NAME_REDACTED] min for each group. Same object type as the caller.\n- %(see_also)s\n+\n+ See Also\n+ --------\n+ Series.cummin : Apply function cummin to a Series.\n+ DataFrame.cummin : Apply function cummin to each row or column of a DataFrame.\n+\n Examples\n --------\n For SeriesGroupBy:\n@@ -5031,8 +5058,6 @@ def cummin(\n )\n \n [USER_REDACTED]\n- [USER_REDACTED](name=\"groupby\")\n- [USER_REDACTED](see_also=_common_see_also)\n def cummax(\n self,\n numeric_only: bool = False,\n@@ -5053,7 +5078,12 @@ def cummax(\n -------\n Series or [NAME_REDACTED] max for each group. Same object type as the caller.\n- %(see_also)s\n+\n+ See Also\n+ --------\n+ Series.cummax : Apply function cummax to a Series.\n+ DataFrame.cummax : Apply function cummax to each row or column of a DataFrame.\n+\n Examples\n --------\n For SeriesGroupBy:\n@@ -5102,7 +5132,6 @@ def cummax(\n )\n \n [USER_REDACTED]\n- [USER_REDACTED](name=\"groupby\")\n def shift(\n self,\n periods: int | Sequence[int] = 1,\n@@ -5248,8 +5277,6 @@ def shift(\n )\n \n [USER_REDACTED]\n- [USER_REDACTED](name=\"groupby\")\n- [USER_REDACTED](see_also=_common_see_also)\n def diff(\n self,\n periods: int = 1,\n@@ -5269,7 +5296,12 @@ def diff(\n -------\n Series or [NAME_REDACTED] differences.\n- %(see_also)s\n+\n+ See Also\n+ --------\n+ Series.diff : Apply function diff to a Series.\n+ DataFrame.diff : Apply function diff to each row or column of a DataFrame.\n+\n Examples\n --------\n For SeriesGroupBy:\n@@ -5335,8 +5367,6 @@ def diff(\n return obj - shifted\n \n [USER_REDACTED]\n- [USER_REDACTED](name=\"groupby\")\n- [USER_REDACTED](see_also=_common_see_also)\n def pct_change(\n self,\n periods: int = 1,\n@@ -5365,7 +5395,13 @@ def pct_change(\n -------\n Series or [NAME_REDACTED] changes within each group.\n- %(see_also)s\n+\n+ See Also\n+ --------\n+ Series.pct_change : Apply function pct_change to a Series.\n+ DataFrame.pct_change : Apply function pct_change to each row or column of\n+ a DataFrame.\n+\n Examples\n --------\n \n@@ -5431,8 +5467,6 @@ def pct_change(\n return (filled / shifted) - 1\n \n [USER_REDACTED]\n- [USER_REDACTED](name=\"groupby\")\n- [USER_REDACTED](see_also=_common_see_also)\n def head(self, n: int = 5) -> NDFrameT:\n \"\"\"\n Return first n rows of each group.\n@@ -5451,7 +5485,12 @@ def head(self, n: int = 5) -> NDFrameT:\n -------\n Series or [NAME_REDACTED] of original Series or DataFrame as determined by n.\n- %(see_also)s\n+\n+ See Also\n+ --------\n+ Series.head : Apply function head to a Series.\n+ DataFrame.head : Apply function head to each row or column of a DataFrame.\n+\n Examples\n --------\n \n@@ -5468,8 +5507,6 @@ def head(self, n: int = 5) -> NDFrameT:\n return self._mask_selected_obj(mask)\n \n [USER_REDACTED]\n- [USER_REDACTED](name=\"groupby\")\n- [USER_REDACTED](see_also=_common_see_also)\n def tail(self, n: int = 5) -> NDFrameT:\n \"\"\"\n Return last n rows of each group.\n@@ -5488,7 +5525,12 @@ def tail(self, n: int = 5) -> NDFrameT:\n -------\n Series or [NAME_REDACTED] of original Series or DataFrame as determined by n.\n- %(see_also)s\n+\n+ See Also\n+ --------\n+ Series.tail : Apply function tail to a Series.\n+ DataFrame.tail : Apply function tail to each row or column of a DataFrame.\n+\n Examples\n --------" } ], "reviews": [ { "id": 3623632137, "user": "user_c9260bc45a59", "state": "APPROVED", "body": null, "submitted_at": "2026-01-02T18:01:31+00:00" }, { "id": 3623636281, "user": "user_c9260bc45a59", "state": "CHANGES_REQUESTED", "body": null, "submitted_at": "2026-01-02T18:03:49+00:00" }, { "id": 3624138756, "user": "user_5b0b62fe7839", "state": "COMMENTED", "body": null, "submitted_at": "2026-01-03T01:43:52+00:00" }, { "id": 3627817725, "user": "user_c9260bc45a59", "state": "APPROVED", "body": null, "submitted_at": "2026-01-05T17:38:53+00:00" } ], "review_comments": [ { "id": 2658163644, "user": "user_c9260bc45a59", "body": "```suggestion\n Series.any : Apply a function any to a Series.\n```\nThis was probably a typo before, but I think these should refer to the method of the same name on the Series/DataFrame object. Can you apply similar fixes to the other methods?", "path": "pandas/core/groupby/groupby.py", "line": null, "side": "RIGHT", "created_at": "2026-01-02T18:03:44+00:00" }, { "id": 2658637977, "user": "user_5b0b62fe7839", "body": "sure, thanks for pointing it out", "path": "pandas/core/groupby/groupby.py", "line": null, "side": "RIGHT", "created_at": "2026-01-03T01:43:52+00:00" } ], "meta": { "languages": [ "py" ], "touches_tests": false, "review_state_summary": { "APPROVED": 2, "CHANGES_REQUESTED": 1, "COMMENTED": 1 }, "meaningful_comment_count": 2, "has_approval": true, "has_changes_requested": true, "total_review_comments": 2 } } { "_id": "f0edea33471e85e0", "_schema_version": "1.0", "_cleaned_at": "2026-02-12T07:46:52.257948+00:00", "repo": "pandas-dev/pandas", "repo_url": "https://github.com/pandas-dev/pandas", "license_name": "BSD 3-Clause \"New\" or \"Revised\" License", "license_spdx": "BSD-3-Clause", "pr_number": 63541, "title": "DOC: Fix SA01,EX01 for pandas.DataFrame.from_arrow", "body": "- [x] closes #63540\n- [ ] [Tests added and passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#writing-tests) if fixing a bug or adding a new feature\n- [ ] All [code checks passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit).\n- [ ] Added [type annotations](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#type-hints) to new arguments/methods/functions.\n- [ ] Added an entry in the latest `doc/source/whatsnew/vX.X.X.rst` file if fixing a bug or adding a new feature.\n- [ ] If I used AI to develop this pull request, I prompted it to follow `AGENTS.md`.", "author": "user_8905a7db72f0", "created_at": "2026-01-02T10:44:10+00:00", "merged_at": "2026-01-05T17:28:48+00:00", "base_branch": "main", "head_branch": "pandas.DataFrame.from_arrow", "additions": 14, "deletions": 1, "changed_files": 2, "files": [ { "filename": "ci/code_checks.sh", "status": "modified", "additions": 0, "deletions": 1, "changes": 1, "patch": "@@ -70,7 +70,6 @@ if [[ -z \"$CHECK\" || \"$CHECK\" == \"docstrings\" ]]; then\n \"$BASE_DIR\"/scripts/validate_docstrings.py \\\n --format=actions \\\n -i ES01 `# For now it is ok if docstrings are missing the extended summary` \\\n- -i \"pandas.DataFrame.from_arrow SA01,EX01\" \\\n -i \"pandas.Series.from_arrow SA01,EX01\" \\\n -i \"pandas.Series.dt PR01\" `# Accessors are implemented as classes, but we do not document the Parameters section` \\\n -i \"pandas.Period.freq GL08\" \\" }, { "filename": "pandas/core/frame.py", "status": "modified", "additions": 14, "deletions": 0, "changes": 14, "patch": "@@ -1864,6 +1864,20 @@ def from_arrow(\n Returns\n -------\n DataFrame\n+\n+ See Also\n+ --------\n+ Series.from_arrow : Construct a Series from an Arrow object.\n+\n+ Examples\n+ --------\n+ >>> import pyarrow as pa\n+ >>> table = pa.table({\"a\": [1, 2, 3], \"b\": [\"x\", \"y\", \"z\"]})\n+ >>> pd.DataFrame.from_arrow(table)\n+ a b\n+ 0 1 x\n+ 1 2 y\n+ 2 3 z\n \"\"\"\n pa = import_optional_dependency(\"pyarrow\", min_version=\"14.0.0\")\n if not isinstance(data, pa.Table):" } ], "reviews": [ { "id": 3623638404, "user": "user_c9260bc45a59", "state": "COMMENTED", "body": null, "submitted_at": "2026-01-02T18:04:48+00:00" }, { "id": 3623667827, "user": "user_8905a7db72f0", "state": "COMMENTED", "body": null, "submitted_at": "2026-01-02T18:16:44+00:00" }, { "id": 3627775196, "user": "user_c9260bc45a59", "state": "APPROVED", "body": null, "submitted_at": "2026-01-05T17:28:37+00:00" } ], "review_comments": [ { "id": 2658165633, "user": "user_c9260bc45a59", "body": "pyarrow should be installed in our doc environment, so could you remove these doctest skips?", "path": "pandas/core/frame.py", "line": null, "side": "RIGHT", "created_at": "2026-01-02T18:04:48+00:00" }, { "id": 2658192793, "user": "user_8905a7db72f0", "body": "yes let me do that.", "path": "pandas/core/frame.py", "line": null, "side": "RIGHT", "created_at": "2026-01-02T18:16:44+00:00" } ], "meta": { "languages": [ "py", "sh" ], "touches_tests": false, "review_state_summary": { "COMMENTED": 2, "APPROVED": 1 }, "meaningful_comment_count": 2, "has_approval": true, "has_changes_requested": false, "total_review_comments": 2 } } { "_id": "c6980c54e60c54a3", "_schema_version": "1.0", "_cleaned_at": "2026-02-12T07:46:52.257948+00:00", "repo": "pandas-dev/pandas", "repo_url": "https://github.com/pandas-dev/pandas", "license_name": "BSD 3-Clause \"New\" or \"Revised\" License", "license_spdx": "BSD-3-Clause", "pr_number": 63539, "title": "DOC: Fix PR02 docstring validation errors for groupby.plot", "body": "- Remove `[USER_REDACTED]()` decorator from SeriesGroupBy.plot and DataFrameGroupBy.plot\n- Add explicit docstrings with Returns and See Also sections\n- Remove PR02 ignore entries from code_checks.sh\n\n```\n-i \"pandas.api.typing.DataFrameGroupBy.plot PR02\" \\\n-i \"pandas.api.typing.SeriesGroupBy.plot PR02\" \\\n```\n\nPart of #60365\n \n- [ ] closes #xxxx (Replace xxxx with the GitHub issue number)\n- [ ] [Tests added and passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#writing-tests) if fixing a bug or adding a new feature\n- [x] All [code checks passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit).\n- [ ] Added [type annotations](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#type-hints) to new arguments/methods/functions.\n- [ ] Added an entry in the latest `doc/source/whatsnew/vX.X.X.rst` file if fixing a bug or adding a new feature.\n- [ ] If I used AI to develop this pull request, I prompted it to follow `AGENTS.md`.", "author": "user_3ed4735128ff", "created_at": "2026-01-02T07:13:48+00:00", "merged_at": "2026-01-03T11:52:57+00:00", "base_branch": "main", "head_branch": "doc/fix-plot-docstring-pr02", "additions": 44, "deletions": 4, "changed_files": 2, "files": [ { "filename": "ci/code_checks.sh", "status": "modified", "additions": 0, "deletions": 2, "changes": 2, "patch": "@@ -78,8 +78,6 @@ if [[ -z \"$CHECK\" || \"$CHECK\" == \"docstrings\" ]]; then\n -i \"pandas.errors.ChainedAssignmentError SA01\" \\\n -i \"pandas.errors.IncompatibleFrequency SA01,SS06,EX01\" \\\n -i \"pandas.api.extensions.ExtensionArray.value_counts EX01,RT03,SA01\" \\\n- -i \"pandas.api.typing.DataFrameGroupBy.plot PR02\" \\\n- -i \"pandas.api.typing.SeriesGroupBy.plot PR02\" \\\n -i \"pandas.api.typing.Resampler.quantile PR01,PR07\" \\\n -i \"pandas.StringDtype.storage SA01\" \\\n -i \"pandas.StringDtype.na_value SA01\" \\" }, { "filename": "pandas/core/groupby/generic.py", "status": "modified", "additions": 44, "deletions": 2, "changes": 46, "patch": "@@ -1514,8 +1514,28 @@ def alt(obj):\n )\n \n [USER_REDACTED]\n- [USER_REDACTED](Series.plot.__doc__)\n def plot(self) -> GroupByPlot:\n+ \"\"\"\n+ Make plots of groups from a Series.\n+\n+ Uses the backend specified by [NAME_REDACTED] ``plotting.backend``.\n+ By default, matplotlib is used.\n+\n+ Returns\n+ -------\n+ GroupByPlot\n+ A plotting object that can be used to create plots for each group.\n+\n+ See Also\n+ --------\n+ Series.plot : Make plots of Series.\n+\n+ Examples\n+ --------\n+ >>> ser = pd.Series([1, 2, 3, 4, 5], index=[\"a\", \"a\", \"b\", \"b\", \"c\"])\n+ >>> g = ser.groupby(level=0)\n+ >>> g.plot() # doctest: +SKIP\n+ \"\"\"\n result = GroupByPlot(self)\n return result\n \n@@ -3528,8 +3548,30 @@ def kurt(\n )\n \n [USER_REDACTED]\n- [USER_REDACTED](DataFrame.plot.__doc__)\n def plot(self) -> GroupByPlot:\n+ \"\"\"\n+ Make plots of groups from a DataFrame.\n+\n+ Uses the backend specified by [NAME_REDACTED] ``plotting.backend``.\n+ By default, matplotlib is used.\n+\n+ Returns\n+ -------\n+ GroupByPlot\n+ A plotting object that can be used to create plots for each group.\n+\n+ See Also\n+ --------\n+ DataFrame.plot : Make plots of DataFrame.\n+\n+ Examples\n+ --------\n+ >>> df = pd.DataFrame(\n+ ... {\"A\": [1, 2, 3, 4], \"B\": [5, 6, 7, 8]}, index=[\"a\", \"a\", \"b\", \"b\"]\n+ ... )\n+ >>> g = df.groupby(level=0)\n+ >>> g.plot() # doctest: +SKIP\n+ \"\"\"\n result = GroupByPlot(self)\n return result" } ], "reviews": [ { "id": 3623089841, "user": "user_c1cc819e14db", "state": "CHANGES_REQUESTED", "body": "Looks good! I think we can might the first line just a bit more descriptive.", "submitted_at": "2026-01-02T13:02:05+00:00" }, { "id": 3623295396, "user": "user_3ed4735128ff", "state": "COMMENTED", "body": null, "submitted_at": "2026-01-02T14:56:33+00:00" }, { "id": 3624313528, "user": "user_c1cc819e14db", "state": "APPROVED", "body": "lgtm", "submitted_at": "2026-01-03T11:52:39+00:00" } ], "review_comments": [ { "id": 2657681310, "user": "user_c1cc819e14db", "body": "```suggestion\n Make plots of groups from a Series.\n```", "path": "pandas/core/groupby/generic.py", "line": null, "side": "RIGHT", "created_at": "2026-01-02T13:01:02+00:00" }, { "id": 2657681507, "user": "user_c1cc819e14db", "body": "```suggestion\n Make plots of groups from a DataFrame.\n```", "path": "pandas/core/groupby/generic.py", "line": null, "side": "RIGHT", "created_at": "2026-01-02T13:01:12+00:00" }, { "id": 2657857913, "user": "user_3ed4735128ff", "body": "Thanks for the review! I've applied your suggestions.", "path": "pandas/core/groupby/generic.py", "line": null, "side": "RIGHT", "created_at": "2026-01-02T14:56:33+00:00" } ], "meta": { "languages": [ "py", "sh" ], "touches_tests": false, "review_state_summary": { "CHANGES_REQUESTED": 1, "COMMENTED": 1, "APPROVED": 1 }, "meaningful_comment_count": 3, "has_approval": true, "has_changes_requested": true, "total_review_comments": 3 } } { "_id": "ae7d4edee7728730", "_schema_version": "1.0", "_cleaned_at": "2026-02-12T07:46:52.257948+00:00", "repo": "pandas-dev/pandas", "repo_url": "https://github.com/pandas-dev/pandas", "license_name": "BSD 3-Clause \"New\" or \"Revised\" License", "license_spdx": "BSD-3-Clause", "pr_number": 63537, "title": "DOC: Inline docstring in `pandas/io/json/_json.py`", "body": "- [ ] xref #62437 (Replace xxxx with the GitHub issue number)\n- [ ] [Tests added and passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#writing-tests) if fixing a bug or adding a new feature\n- [x] All [code checks passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit).\n- [ ] Added [type annotations](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#type-hints) to new arguments/methods/functions.\n- [ ] Added an entry in the latest `doc/source/whatsnew/vX.X.X.rst` file if fixing a bug or adding a new feature.\n- [ ] If I used AI to develop this pull request, I prompted it to follow `AGENTS.md`.", "author": "user_5b0b62fe7839", "created_at": "2026-01-02T03:43:39+00:00", "merged_at": "2026-01-06T02:52:40+00:00", "base_branch": "main", "head_branch": "inline_io_json", "additions": 53, "deletions": 49, "changed_files": 1, "files": [ { "filename": "pandas/io/json/_json.py", "status": "modified", "additions": 53, "deletions": 49, "changes": 102, "patch": "@@ -29,10 +29,7 @@\n from pandas._libs.tslibs import iNaT\n from pandas.compat._optional import import_optional_dependency\n from pandas.errors import AbstractMethodError\n-from pandas.util._decorators import (\n- doc,\n- set_module,\n-)\n+from pandas.util._decorators import set_module\n from pandas.util._validators import check_dtype_backend\n \n from pandas.core.dtypes.common import (\n@@ -53,7 +50,6 @@\n to_datetime,\n )\n from pandas.core.reshape.concat import concat\n-from pandas.core.shared_docs import _shared_docs\n \n from pandas.io._util import arrow_table_to_pandas\n from pandas.io.common import (\n@@ -500,10 +496,6 @@ def read_json(\n \n \n [USER_REDACTED]_module(\"pandas\")\n-[USER_REDACTED](\n- storage_options=_shared_docs[\"storage_options\"],\n- decompression_options=_shared_docs[\"decompression_options\"] % \"path_or_buf\",\n-)\n def read_json(\n path_or_buf: FilePath | ReadBuffer[str] | ReadBuffer[bytes],\n *,\n@@ -648,14 +640,39 @@ def read_json(\n for more information on ``chunksize``.\n This can only be passed if `lines=True`.\n If this is None, the file will be read into memory all at once.\n- {decompression_options}\n+\n+ compression : str or dict, default 'infer'\n+ For on-the-fly decompression of on-disk data. If 'infer' and 'path_or_buf' is\n+ path-like, then detect compression from the following extensions: '.gz',\n+ '.bz2', '.zip', '.xz', '.zst', '.tar', '.tar.gz', '.tar.xz' or '.tar.bz2'\n+ (otherwise no compression).\n+ If using 'zip' or 'tar', the ZIP file must contain only one data file to be\n+ read in.\n+ Set to ``None`` for no decompression.\n+ Can also be a dict with key ``'method'`` set\n+ to one of {``'zip'``, ``'gzip'``, ``'bz2'``, ``'zstd'``, ``'xz'``, ``'tar'``}\n+ and other key-value pairs are forwarded to\n+ ``zipfile.ZipFile``, ``gzip.GzipFile``,\n+ ``bz2.BZ2File``, ``zstandard.ZstdDecompressor``, ``lzma.LZMAFile`` or\n+ ``tarfile.TarFile``, respectively.\n+ As an example, the following could be passed for Zstandard decompression using a\n+ custom compression dictionary:\n+ ``compression={'method': 'zstd', 'dict_data': my_compression_dict}``.\n \n nrows : int, optional\n The number of lines from the line-delimited jsonfile that has to be read.\n This can only be passed if `lines=True`.\n If this is None, all the rows will be returned.\n \n- {storage_options}\n+ storage_options : dict, optional\n+ Extra options that make sense for a particular storage connection, e.g.\n+ host, port, username, password, etc. For HTTP(S) URLs the key-value pairs\n+ are forwarded to ``urllib.request.Request`` as header options. For other\n+ URLs (e.g. starting with \"s3://\", and \"gcs://\") the key-value pairs are\n+ forwarded to ``fsspec.open``. Please see ``fsspec`` and ``urllib`` for more\n+ details, and for more examples on storage options refer `here\n+ `_.\n \n dtype_backend : {{'numpy_nullable', 'pyarrow'}}\n Back-end data type applied to the resultant :class:`DataFrame`\n@@ -701,74 +718,61 @@ def read_json(\n Examples\n --------\n >>> from io import StringIO\n- >>> df = pd.DataFrame([['a', 'b'], ['c', 'd']],\n- ... index=['row 1', 'row 2'],\n- ... columns=['col 1', 'col 2'])\n+ >>> df = pd.DataFrame(\n+ ... [[\"a\", \"b\"], [\"c\", \"d\"]],\n+ ... index=[\"row 1\", \"row 2\"],\n+ ... columns=[\"col 1\", \"col 2\"],\n+ ... )\n \n Encoding/decoding a Dataframe using ``'split'`` formatted JSON:\n \n- >>> df.to_json(orient='split')\n- '\\\n-{{\\\n-\"columns\":[\"col 1\",\"col 2\"],\\\n-\"index\":[\"row 1\",\"row 2\"],\\\n-\"data\":[[\"a\",\"b\"],[\"c\",\"d\"]]\\\n-}}\\\n-'\n- >>> pd.read_json(StringIO(_), orient='split') # noqa: F821\n+ >>> df.to_json(orient=\"split\")\n+ '{\"columns\":[\"col 1\",\"col 2\"],\"index\":[\"row 1\",\"row 2\"],\"data\":[[\"a\",\"b\"],[\"c\",\"d\"]]}'\n+\n+ >>> pd.read_json(StringIO(_), orient=\"split\") # noqa: F821\n col 1 col 2\n row 1 a b\n row 2 c d\n \n Encoding/decoding a Dataframe using ``'index'`` formatted JSON:\n \n- >>> df.to_json(orient='index')\n- '{{\"row 1\":{{\"col 1\":\"a\",\"col 2\":\"b\"}},\"row 2\":{{\"col 1\":\"c\",\"col 2\":\"d\"}}}}'\n+ >>> df.to_json(orient=\"index\")\n+ '{\"row 1\":{\"col 1\":\"a\",\"col 2\":\"b\"},\"row 2\":{\"col 1\":\"c\",\"col 2\":\"d\"}}'\n \n- >>> pd.read_json(StringIO(_), orient='index') # noqa: F821\n+ >>> pd.read_json(StringIO(_), orient=\"index\") # noqa: F821\n col 1 col 2\n row 1 a b\n row 2 c d\n \n Encoding/decoding a Dataframe using ``'records'`` formatted JSON.\n Note that index labels are not preserved with this encoding.\n \n- >>> df.to_json(orient='records')\n- '[{{\"col 1\":\"a\",\"col 2\":\"b\"}},{{\"col 1\":\"c\",\"col 2\":\"d\"}}]'\n- >>> pd.read_json(StringIO(_), orient='records') # noqa: F821\n+ >>> df.to_json(orient=\"records\")\n+ '[{\"col 1\":\"a\",\"col 2\":\"b\"},{\"col 1\":\"c\",\"col 2\":\"d\"}]'\n+\n+ >>> pd.read_json(StringIO(_), orient=\"records\") # noqa: F821\n col 1 col 2\n 0 a b\n 1 c d\n \n Encoding with [NAME_REDACTED]\n \n- >>> df.to_json(orient='table')\n- '\\\n-{{\"schema\":{{\"fields\":[\\\n-{{\"name\":\"index\",\"type\":\"string\",\"extDtype\":\"str\"}},\\\n-{{\"name\":\"col 1\",\"type\":\"string\",\"extDtype\":\"str\"}},\\\n-{{\"name\":\"col 2\",\"type\":\"string\",\"extDtype\":\"str\"}}],\\\n-\"primaryKey\":[\"index\"],\\\n-\"pandas_version\":\"1.4.0\"}},\\\n-\"data\":[\\\n-{{\"index\":\"row 1\",\"col 1\":\"a\",\"col 2\":\"b\"}},\\\n-{{\"index\":\"row 2\",\"col 1\":\"c\",\"col 2\":\"d\"}}]\\\n-}}\\\n-'\n+ >>> df.to_json(orient=\"table\")\n+ '{\"schema\":{\"fields\":[{\"name\":\"index\",\"type\":\"string\",\"extDtype\":\"str\"},{\"name\":\"col 1\",\"type\":\"string\",\"extDtype\":\"str\"},{\"name\":\"col 2\",\"type\":\"string\",\"extDtype\":\"str\"}],\"primaryKey\":[\"index\"],\"pandas_version\":\"1.4.0\"},\"data\":[{\"index\":\"row 1\",\"col 1\":\"a\",\"col 2\":\"b\"},{\"index\":\"row 2\",\"col 1\":\"c\",\"col 2\":\"d\"}]}'\n \n The following example uses ``dtype_backend=\"numpy_nullable\"``\n \n- >>> data = '''{{\"index\": {{\"0\": 0, \"1\": 1}},\n- ... \"a\": {{\"0\": 1, \"1\": null}},\n- ... \"b\": {{\"0\": 2.5, \"1\": 4.5}},\n- ... \"c\": {{\"0\": true, \"1\": false}},\n- ... \"d\": {{\"0\": \"a\", \"1\": \"b\"}},\n- ... \"e\": {{\"0\": 1577.2, \"1\": 1577.1}}}}'''\n+ >>> data = '''{\"index\": {\"0\": 0, \"1\": 1},\n+ ... \"a\": {\"0\": 1, \"1\": null},\n+ ... \"b\": {\"0\": 2.5, \"1\": 4.5},\n+ ... \"c\": {\"0\": true, \"1\": false},\n+ ... \"d\": {\"0\": \"a\", \"1\": \"b\"},\n+ ... \"e\": {\"0\": 1577.2, \"1\": 1577.1}}'''\n >>> pd.read_json(StringIO(data), dtype_backend=\"numpy_nullable\")\n index a b c d e\n 0 0 1 2.5 True a 1577.2\n 1 1 4.5 False b 1577.1\n- \"\"\"\n+ \"\"\" # noqa: E501\n if orient == \"table\" and dtype:\n raise ValueError(\"cannot pass both dtype and orient='table'\")\n if orient == \"table\" and convert_axes:" } ], "reviews": [ { "id": 3628040363, "user": "user_c9260bc45a59", "state": "CHANGES_REQUESTED", "body": null, "submitted_at": "2026-01-05T18:50:43+00:00" }, { "id": 3629141976, "user": "user_c9260bc45a59", "state": "APPROVED", "body": null, "submitted_at": "2026-01-06T02:52:27+00:00" } ], "review_comments": [ { "id": 2662479191, "user": "user_c9260bc45a59", "body": "```suggestion\n```", "path": "pandas/io/json/_json.py", "line": null, "side": "RIGHT", "created_at": "2026-01-05T18:48:49+00:00" } ], "meta": { "languages": [ "py" ], "touches_tests": false, "review_state_summary": { "CHANGES_REQUESTED": 1, "APPROVED": 1 }, "meaningful_comment_count": 1, "has_approval": true, "has_changes_requested": true, "total_review_comments": 1 } } { "_id": "37ef1d7aba47b20c", "_schema_version": "1.0", "_cleaned_at": "2026-02-12T07:46:52.273576+00:00", "repo": "pandas-dev/pandas", "repo_url": "https://github.com/pandas-dev/pandas", "license_name": "BSD 3-Clause \"New\" or \"Revised\" License", "license_spdx": "BSD-3-Clause", "pr_number": 63535, "title": "DOC: Inline docstring in `pandas/io/common.py`", "body": "- [ ] xref #62437 (Replace xxxx with the GitHub issue number)\n- [ ] [Tests added and passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#writing-tests) if fixing a bug or adding a new feature\n- [x] All [code checks passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit).\n- [ ] Added [type annotations](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#type-hints) to new arguments/methods/functions.\n- [ ] Added an entry in the latest `doc/source/whatsnew/vX.X.X.rst` file if fixing a bug or adding a new feature.\n- [ ] If I used AI to develop this pull request, I prompted it to follow `AGENTS.md`.", "author": "user_5b0b62fe7839", "created_at": "2026-01-02T03:41:53+00:00", "merged_at": "2026-01-05T17:35:11+00:00", "base_branch": "main", "head_branch": "inline_io_common", "additions": 58, "deletions": 13, "changed_files": 1, "files": [ { "filename": "pandas/io/common.py", "status": "modified", "additions": 58, "deletions": 13, "changes": 71, "patch": "@@ -56,7 +56,6 @@\n ReadCsvBuffer,\n )\n from pandas.compat._optional import import_optional_dependency\n-from pandas.util._decorators import doc\n from pandas.util._exceptions import find_stack_level\n \n from pandas.core.dtypes.common import (\n@@ -67,8 +66,6 @@\n )\n from pandas.core.dtypes.generic import ABCMultiIndex\n \n-from pandas.core.shared_docs import _shared_docs\n-\n _VALID_URLS = set(uses_relative + uses_netloc + uses_params)\n _VALID_URLS.discard(\"\")\n _FSSPEC_URL_PATTERN = re.compile(r\"^[A-Za-z][A-Za-z0-9+\\-+.]*(::[A-Za-z0-9+\\-+.]+)*://\")\n@@ -296,10 +293,6 @@ def is_fsspec_url(url: FilePath | BaseBuffer) -> bool:\n )\n \n \n-[USER_REDACTED](\n- storage_options=_shared_docs[\"storage_options\"],\n- compression_options=_shared_docs[\"compression_options\"] % \"filepath_or_buffer\",\n-)\n def _get_filepath_or_buffer(\n filepath_or_buffer: FilePath | BaseBuffer,\n encoding: str = \"utf-8\",\n@@ -315,12 +308,36 @@ def _get_filepath_or_buffer(\n ----------\n filepath_or_buffer : a url, filepath (str or pathlib.Path),\n or buffer\n- {compression_options}\n+\n+ compression : str or dict, default 'infer'\n+ For on-the-fly compression of the output data. If 'infer' and\n+ 'filepath_or_buffer' is path-like, then detect compression from the\n+ following extensions: '.gz',\n+ '.bz2', '.zip', '.xz', '.zst', '.tar', '.tar.gz', '.tar.xz' or '.tar.bz2'\n+ (otherwise no compression).\n+ Set to ``None`` for no compression.\n+ Can also be a dict with key ``'method'`` set\n+ to one of {``'zip'``, ``'gzip'``, ``'bz2'``, ``'zstd'``, ``'xz'``, ``'tar'``}\n+ and other key-value pairs are forwarded to\n+ ``zipfile.ZipFile``, ``gzip.GzipFile``,\n+ ``bz2.BZ2File``, ``zstandard.ZstdCompressor``, ``lzma.LZMAFile`` or\n+ ``tarfile.TarFile``, respectively.\n+ As an example, the following could be passed for faster compression and to\n+ create a reproducible gzip archive:\n+ ``compression={'method': 'gzip', 'compresslevel': 1, 'mtime': 1}``.\n \n encoding : the encoding to use to decode bytes, default is 'utf-8'\n mode : str, optional\n \n- {storage_options}\n+ storage_options : dict, optional\n+ Extra options that make sense for a particular storage connection, e.g.\n+ host, port, username, password, etc. For HTTP(S) URLs the key-value pairs\n+ are forwarded to ``urllib.request.Request`` as header options. For other\n+ URLs (e.g. starting with \"s3://\", and \"gcs://\") the key-value pairs are\n+ forwarded to ``fsspec.open``. Please see ``fsspec`` and ``urllib`` for more\n+ details, and for more examples on storage options refer `here\n+ `_.\n \n \n Returns the dataclass IOArgs.\n@@ -550,7 +567,6 @@ def get_compression_method(\n return compression_method, compression_args\n \n \n-[USER_REDACTED](compression_options=_shared_docs[\"compression_options\"] % \"filepath_or_buffer\")\n def infer_compression(\n filepath_or_buffer: FilePath | BaseBuffer, compression: str | None\n ) -> str | None:\n@@ -564,7 +580,23 @@ def infer_compression(\n ----------\n filepath_or_buffer : str or file handle\n File path or object.\n- {compression_options}\n+\n+ compression : str or dict, default 'infer'\n+ For on-the-fly compression of the output data. If 'infer' and\n+ 'filepath_or_buffer' is path-like, then detect compression from the\n+ following extensions: '.gz',\n+ '.bz2', '.zip', '.xz', '.zst', '.tar', '.tar.gz', '.tar.xz' or '.tar.bz2'\n+ (otherwise no compression).\n+ Set to ``None`` for no compression.\n+ Can also be a dict with key ``'method'`` set\n+ to one of {``'zip'``, ``'gzip'``, ``'bz2'``, ``'zstd'``, ``'xz'``, ``'tar'``}\n+ and other key-value pairs are forwarded to\n+ ``zipfile.ZipFile``, ``gzip.GzipFile``,\n+ ``bz2.BZ2File``, ``zstandard.ZstdCompressor``, ``lzma.LZMAFile`` or\n+ ``tarfile.TarFile``, respectively.\n+ As an example, the following could be passed for faster compression and to\n+ create a reproducible gzip archive:\n+ ``compression={'method': 'gzip', 'compresslevel': 1, 'mtime': 1}``.\n \n Returns\n -------\n@@ -662,7 +694,6 @@ def get_handle(\n ) -> IOHandles[str] | IOHandles[bytes]: ...\n \n \n-[USER_REDACTED](compression_options=_shared_docs[\"compression_options\"] % \"path_or_buf\")\n def get_handle(\n path_or_buf: FilePath | BaseBuffer,\n mode: str,\n@@ -685,7 +716,21 @@ def get_handle(\n Mode to open path_or_buf with.\n encoding : str or None\n Encoding to use.\n- {compression_options}\n+ compression : str or dict, default 'infer'\n+ For on-the-fly compression of the output data. If 'infer' and 'path_or_buf'\n+ is path-like, then detect compression from the following extensions: '.gz',\n+ '.bz2', '.zip', '.xz', '.zst', '.tar', '.tar.gz', '.tar.xz' or '.tar.bz2'\n+ (otherwise no compression).\n+ Set to ``None`` for no compression.\n+ Can also be a dict with key ``'method'`` set\n+ to one of {``'zip'``, ``'gzip'``, ``'bz2'``, ``'zstd'``, ``'xz'``, ``'tar'``}\n+ and other key-value pairs are forwarded to\n+ ``zipfile.ZipFile``, ``gzip.GzipFile``,\n+ ``bz2.BZ2File``, ``zstandard.ZstdCompressor``, ``lzma.LZMAFile`` or\n+ ``tarfile.TarFile``, respectively.\n+ As an example, the following could be passed for faster compression and to\n+ create a reproducible gzip archive:\n+ ``compression={'method': 'gzip', 'compresslevel': 1, 'mtime': 1}``.\n \n May be a dict with key 'method' as compression mode\n and other keys as compression options if compression" } ], "reviews": [ { "id": 3623626243, "user": "user_c9260bc45a59", "state": "COMMENTED", "body": null, "submitted_at": "2026-01-02T17:58:31+00:00" }, { "id": 3623626468, "user": "user_c9260bc45a59", "state": "COMMENTED", "body": null, "submitted_at": "2026-01-02T17:58:42+00:00" }, { "id": 3623626672, "user": "user_c9260bc45a59", "state": "COMMENTED", "body": null, "submitted_at": "2026-01-02T17:58:52+00:00" }, { "id": 3627804743, "user": "user_c9260bc45a59", "state": "APPROVED", "body": null, "submitted_at": "2026-01-05T17:35:03+00:00" } ], "review_comments": [ { "id": 2658154235, "user": "user_c9260bc45a59", "body": "```suggestion\n```", "path": "pandas/io/common.py", "line": null, "side": "RIGHT", "created_at": "2026-01-02T17:58:31+00:00" }, { "id": 2658154570, "user": "user_c9260bc45a59", "body": "```suggestion\n```", "path": "pandas/io/common.py", "line": null, "side": "RIGHT", "created_at": "2026-01-02T17:58:42+00:00" }, { "id": 2658154745, "user": "user_c9260bc45a59", "body": "```suggestion\n```", "path": "pandas/io/common.py", "line": null, "side": "RIGHT", "created_at": "2026-01-02T17:58:52+00:00" } ], "meta": { "languages": [ "py" ], "touches_tests": false, "review_state_summary": { "COMMENTED": 3, "APPROVED": 1 }, "meaningful_comment_count": 3, "has_approval": true, "has_changes_requested": false, "total_review_comments": 3 } } { "_id": "ce2cc6d6469aee75", "_schema_version": "1.0", "_cleaned_at": "2026-02-12T07:46:52.273576+00:00", "repo": "pandas-dev/pandas", "repo_url": "https://github.com/pandas-dev/pandas", "license_name": "BSD 3-Clause \"New\" or \"Revised\" License", "license_spdx": "BSD-3-Clause", "pr_number": 63534, "title": "DOC: Inline docstring in `pandas/io/formats/xml.py`", "body": "- [ ] xref #62437 (Replace xxxx with the GitHub issue number)\n- [ ] [Tests added and passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#writing-tests) if fixing a bug or adding a new feature\n- [x] All [code checks passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit).\n- [ ] Added [type annotations](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#type-hints) to new arguments/methods/functions.\n- [ ] Added an entry in the latest `doc/source/whatsnew/vX.X.X.rst` file if fixing a bug or adding a new feature.\n- [ ] If I used AI to develop this pull request, I prompted it to follow `AGENTS.md`.", "author": "user_5b0b62fe7839", "created_at": "2026-01-02T03:26:05+00:00", "merged_at": "2026-01-05T17:37:53+00:00", "base_branch": "main", "head_branch": "inline_io_xml", "additions": 26, "deletions": 13, "changed_files": 1, "files": [ { "filename": "pandas/io/formats/xml.py", "status": "modified", "additions": 26, "deletions": 13, "changes": 39, "patch": "@@ -13,16 +13,11 @@\n )\n \n from pandas.errors import AbstractMethodError\n-from pandas.util._decorators import (\n- cache_readonly,\n- doc,\n-)\n+from pandas.util._decorators import cache_readonly\n \n from pandas.core.dtypes.common import is_list_like\n from pandas.core.dtypes.missing import isna\n \n-from pandas.core.shared_docs import _shared_docs\n-\n from pandas.io.common import get_handle\n from pandas.io.xml import get_data_from_filepath\n \n@@ -38,10 +33,6 @@\n from pandas import DataFrame\n \n \n-[USER_REDACTED](\n- storage_options=_shared_docs[\"storage_options\"],\n- compression_options=_shared_docs[\"compression_options\"] % \"path_or_buffer\",\n-)\n class _BaseXMLFormatter:\n \"\"\"\n Subclass for formatting data in XML.\n@@ -89,9 +80,31 @@ class _BaseXMLFormatter:\n stylesheet : str or file-like\n A URL, file, file-like object, or a raw string containing XSLT.\n \n- {compression_options}\n-\n- {storage_options}\n+ compression : str or dict, default 'infer'\n+ For on-the-fly compression of the output data. If 'infer' and 'path_or_buffer'\n+ is path-like, then detect compression from the following extensions: '.gz',\n+ '.bz2', '.zip', '.xz', '.zst', '.tar', '.tar.gz', '.tar.xz' or '.tar.bz2'\n+ (otherwise no compression).\n+ Set to ``None`` for no compression.\n+ Can also be a dict with key ``'method'`` set\n+ to one of {``'zip'``, ``'gzip'``, ``'bz2'``, ``'zstd'``, ``'xz'``, ``'tar'``}\n+ and other key-value pairs are forwarded to\n+ ``zipfile.ZipFile``, ``gzip.GzipFile``,\n+ ``bz2.BZ2File``, ``zstandard.ZstdCompressor``, ``lzma.LZMAFile`` or\n+ ``tarfile.TarFile``, respectively.\n+ As an example, the following could be passed for faster compression and to\n+ create a reproducible gzip archive:\n+ ``compression={'method': 'gzip', 'compresslevel': 1, 'mtime': 1}``.\n+\n+ storage_options : dict, optional\n+ Extra options that make sense for a particular storage connection, e.g.\n+ host, port, username, password, etc. For HTTP(S) URLs the key-value pairs\n+ are forwarded to ``urllib.request.Request`` as header options. For other\n+ URLs (e.g. starting with \"s3://\", and \"gcs://\") the key-value pairs are\n+ forwarded to ``fsspec.open``. Please see ``fsspec`` and ``urllib`` for more\n+ details, and for more examples on storage options refer `here\n+ `_.\n \n See also\n --------" } ], "reviews": [ { "id": 3623625211, "user": "user_c9260bc45a59", "state": "COMMENTED", "body": null, "submitted_at": "2026-01-02T17:57:49+00:00" }, { "id": 3627813415, "user": "user_c9260bc45a59", "state": "APPROVED", "body": null, "submitted_at": "2026-01-05T17:37:28+00:00" } ], "review_comments": [ { "id": 2658153386, "user": "user_c9260bc45a59", "body": "```suggestion\n```", "path": "pandas/io/formats/xml.py", "line": null, "side": "RIGHT", "created_at": "2026-01-02T17:57:49+00:00" } ], "meta": { "languages": [ "py" ], "touches_tests": false, "review_state_summary": { "COMMENTED": 1, "APPROVED": 1 }, "meaningful_comment_count": 1, "has_approval": true, "has_changes_requested": false, "total_review_comments": 1 } } { "_id": "c89f1a2dbd700c26", "_schema_version": "1.0", "_cleaned_at": "2026-02-12T07:46:52.273576+00:00", "repo": "pandas-dev/pandas", "repo_url": "https://github.com/pandas-dev/pandas", "license_name": "BSD 3-Clause \"New\" or \"Revised\" License", "license_spdx": "BSD-3-Clause", "pr_number": 63528, "title": "DOC: Inline docstrings for argmax and argmin in base.py", "body": "- Replaced dynamic [USER_REDACTED] decorators with hardcoded docstrings in pandas/core/base.py\n- Targeted methods: argmax, argmin\n- Fixes whitespace/formatting in examples to satisfy doctests\n- Part of #62437\n\n- [x] xref #62437 (Replace xxxx with the GitHub issue number)\n- [x] [Tests added and passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#writing-tests) if fixing a bug or adding a new feature\n- [x] All [code checks passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit).\n- [ ] Added [type annotations](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#type-hints) to new arguments/methods/functions.\n- [ ] Added an entry in the latest `doc/source/whatsnew/vX.X.X.rst` file if fixing a bug or adding a new feature.\n- [x] If I used AI to develop this pull request, I prompted it to follow `AGENTS.md`.", "author": "user_d883698d1d58", "created_at": "2026-01-01T17:44:54+00:00", "merged_at": "2026-01-05T17:30:13+00:00", "base_branch": "main", "head_branch": "doc-fix-argmax", "additions": 65, "deletions": 9, "changed_files": 1, "files": [ { "filename": "pandas/core/base.py", "status": "modified", "additions": 65, "deletions": 9, "changes": 74, "patch": "@@ -749,19 +749,18 @@ def empty(self) -> bool:\n \"\"\"\n return not self.size\n \n- [USER_REDACTED](op=\"max\", oppose=\"min\", value=\"largest\")\n def argmax(\n self, axis: AxisInt | None = None, skipna: bool = True, *args, **kwargs\n ) -> int:\n \"\"\"\n- Return int position of the {value} value in the Series.\n+ Return int position of the largest value in the Series.\n \n- If the {op}imum is achieved in multiple locations,\n+ If the maximum is achieved in multiple locations,\n the first row position is returned.\n \n Parameters\n ----------\n- axis : {{None}}\n+ axis : None\n Unused. Parameter needed for compatibility with DataFrame.\n skipna : bool, default True\n Exclude NA/null values. If the entire Series is NA, or if ``skipna=False``\n@@ -772,13 +771,13 @@ def argmax(\n Returns\n -------\n int\n- Row position of the {op}imum value.\n+ Row position of the maximum value.\n \n See Also\n --------\n- Series.arg{op} : Return position of the {op}imum value.\n- Series.arg{oppose} : Return position of the {oppose}imum value.\n- numpy.ndarray.arg{op} : Equivalent method for numpy arrays.\n+ Series.argmax : Return position of the maximum value.\n+ Series.argmin : Return position of the minimum value.\n+ numpy.ndarray.argmax : Equivalent method for numpy arrays.\n Series.idxmax : Return index label of the maximum values.\n Series.idxmin : Return index label of the minimum values.\n \n@@ -823,10 +822,67 @@ def argmax(\n # \"int\")\n return result # type: ignore[return-value]\n \n- [USER_REDACTED](argmax, op=\"min\", oppose=\"max\", value=\"smallest\")\n def argmin(\n self, axis: AxisInt | None = None, skipna: bool = True, *args, **kwargs\n ) -> int:\n+ \"\"\"\n+ Return int position of the smallest value in the Series.\n+\n+ If the minimum is achieved in multiple locations,\n+ the first row position is returned.\n+\n+ Parameters\n+ ----------\n+ axis : None\n+ Unused. Parameter needed for compatibility with DataFrame.\n+ skipna : bool, default True\n+ Exclude NA/null values. If the entire Series is NA, or if ``skipna=False``\n+ and there is an NA value, this method will raise a ``ValueError``.\n+ *args, **kwargs\n+ Additional arguments and keywords for compatibility with NumPy.\n+\n+ Returns\n+ -------\n+ int\n+ Row position of the minimum value.\n+\n+ See Also\n+ --------\n+ Series.argmin : Return position of the minimum value.\n+ Series.argmax : Return position of the maximum value.\n+ numpy.ndarray.argmin : Equivalent method for numpy arrays.\n+ Series.idxmin : Return index label of the minimum values.\n+ Series.idxmax : Return index label of the maximum values.\n+\n+ Examples\n+ --------\n+ Consider dataset containing cereal calories\n+\n+ >>> s = pd.Series(\n+ ... [100.0, 110.0, 120.0, 110.0],\n+ ... index=[\n+ ... \"[NAME_REDACTED]\",\n+ ... \"[NAME_REDACTED]\",\n+ ... \"[NAME_REDACTED]\",\n+ ... \"[NAME_REDACTED]\",\n+ ... ],\n+ ... )\n+ >>> s\n+ [NAME_REDACTED] 100.0\n+ [NAME_REDACTED] 110.0\n+ [NAME_REDACTED] 120.0\n+ [NAME_REDACTED] 110.0\n+ dtype: float64\n+\n+ >>> s.argmax()\n+ np.int64(2)\n+ >>> s.argmin()\n+ np.int64(0)\n+\n+ The maximum cereal calories is the third element and\n+ the minimum cereal calories is the first element,\n+ since series is zero-indexed.\n+ \"\"\"\n delegate = self._values\n nv.validate_minmax_axis(axis)\n skipna = nv.validate_argmax_with_skipna(skipna, args, kwargs)" } ], "reviews": [ { "id": 3622021532, "user": "user_c9260bc45a59", "state": "CHANGES_REQUESTED", "body": null, "submitted_at": "2026-01-01T19:31:48+00:00" }, { "id": 3623583457, "user": "user_d883698d1d58", "state": "COMMENTED", "body": null, "submitted_at": "2026-01-02T17:28:20+00:00" }, { "id": 3623586684, "user": "user_d883698d1d58", "state": "COMMENTED", "body": null, "submitted_at": "2026-01-02T17:30:09+00:00" }, { "id": 3627781188, "user": "user_c9260bc45a59", "state": "APPROVED", "body": null, "submitted_at": "2026-01-05T17:30:02+00:00" } ], "review_comments": [ { "id": 2656567346, "user": "user_c9260bc45a59", "body": "Can you avoid the doctest skips with your chages?", "path": "pandas/core/base.py", "line": null, "side": "RIGHT", "created_at": "2026-01-01T19:31:14+00:00" }, { "id": 2656567477, "user": "user_c9260bc45a59", "body": "```suggestion\n axis : None\n```", "path": "pandas/core/base.py", "line": null, "side": "RIGHT", "created_at": "2026-01-01T19:31:34+00:00" }, { "id": 2656567555, "user": "user_c9260bc45a59", "body": "```suggestion\n axis : None\n```", "path": "pandas/core/base.py", "line": null, "side": "RIGHT", "created_at": "2026-01-01T19:31:44+00:00" }, { "id": 2658113327, "user": "user_d883698d1d58", "body": "Removed the brackets.", "path": "pandas/core/base.py", "line": null, "side": "RIGHT", "created_at": "2026-01-02T17:28:19+00:00" }, { "id": 2658115742, "user": "user_d883698d1d58", "body": "Fixed! fixed the doctrings to pass the doctests and removed skips.", "path": "pandas/core/base.py", "line": null, "side": "RIGHT", "created_at": "2026-01-02T17:30:09+00:00" } ], "meta": { "languages": [ "py" ], "touches_tests": false, "review_state_summary": { "CHANGES_REQUESTED": 1, "COMMENTED": 2, "APPROVED": 1 }, "meaningful_comment_count": 5, "has_approval": true, "has_changes_requested": true, "total_review_comments": 5 } } { "_id": "8e5d96ad952d0193", "_schema_version": "1.0", "_cleaned_at": "2026-02-12T07:46:52.273576+00:00", "repo": "pandas-dev/pandas", "repo_url": "https://github.com/pandas-dev/pandas", "license_name": "BSD 3-Clause \"New\" or \"Revised\" License", "license_spdx": "BSD-3-Clause", "pr_number": 63522, "title": "BUG: pd.Grouper does not retain PyArrow index dtype", "body": "- [x] closes #63518 (Replace xxxx with the GitHub issue number)\n- [ ] [Tests added and passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#writing-tests) if fixing a bug or adding a new feature\n- [ ] All [code checks passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit).\n- [ ] Added [type annotations](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#type-hints) to new arguments/methods/functions.\n- [ ] Added an entry in the latest `doc/source/whatsnew/vX.X.X.rst` file if fixing a bug or adding a new feature.\n- [ ] If I used AI to develop this pull request, I prompted it to follow `AGENTS.md`.", "author": "user_c1cc819e14db", "created_at": "2025-12-31T16:39:28+00:00", "merged_at": "2026-01-01T19:28:24+00:00", "base_branch": "main", "head_branch": "bug_bingrouper_pyarrow_index", "additions": 29, "deletions": 0, "changed_files": 3, "files": [ { "filename": "doc/source/whatsnew/v3.0.0.rst", "status": "modified", "additions": 1, "deletions": 0, "changes": 1, "patch": "@@ -1358,6 +1358,7 @@ Groupby/resample/rolling\n - Bug in :meth:`.Rolling.var` and :meth:`.Rolling.std` computing incorrect results due to numerical instability. (:issue:`47721`, :issue:`52407`, :issue:`54518`, :issue:`55343`)\n - Bug in :meth:`DataFrame.groupby` methods when operating on NumPy-nullable data failing when the NA mask was not C-contiguous (:issue:`61031`)\n - Bug in :meth:`DataFrame.groupby` when grouping by a Series and that Series was modified after calling :meth:`DataFrame.groupby` but prior to the groupby operation (:issue:`63219`)\n+- Bug in :meth:`DataFrame.groupby` with a :class:`TimeGrouper` (e.g. ``pd.Grouper(freq=\"D\")``) not retaining PyArrow index dtype (:issue:`63518`)\n \n Reshaping\n ^^^^^^^^^" }, { "filename": "pandas/core/resample.py", "status": "modified", "additions": 2, "deletions": 0, "changes": 2, "patch": "@@ -242,6 +242,8 @@ def _get_binner(self):\n \"\"\"\n binner, bins, binlabels = self._get_binner_for_time()\n assert len(bins) == len(binlabels)\n+ if self._timegrouper._arrow_dtype is not None:\n+ binlabels = binlabels.astype(self._timegrouper._arrow_dtype)\n bin_grouper = BinGrouper(bins, binlabels, indexer=self._indexer)\n return binner, bin_grouper" }, { "filename": "pandas/tests/groupby/test_timegrouper.py", "status": "modified", "additions": 26, "deletions": 0, "changes": 26, "patch": "@@ -11,6 +11,8 @@\n import numpy as np\n import pytest\n \n+import pandas.util._test_decorators as td\n+\n import pandas as pd\n from pandas import (\n DataFrame,\n@@ -956,3 +958,27 @@ def test_groupby_agg_numba_timegrouper_with_nat(\n )\n expected_df = gb[[\"Quantity\"]].aggregate(\"mean\")\n tm.assert_frame_equal(result_df, expected_df)\n+\n+ [USER_REDACTED].skip_if_no(\"pyarrow\")\n+ def test_pyarrow_index_retention(self):\n+ # https://github.com/[USER_REDACTED]ndas-dev/pandas/issues/63518\n+ df = DataFrame(\n+ {\n+ \"a\": [1, 2, 3],\n+ },\n+ index=Index(\n+ [\n+ Timestamp(\"2013-01-01\"),\n+ Timestamp(\"2013-01-01\"),\n+ Timestamp(\"2013-01-02\"),\n+ ],\n+ dtype=\"timestamp[ns, America/Denver][pyarrow]\",\n+ ),\n+ )\n+ gb = df.groupby(Grouper(freq=\"D\"))\n+ result = gb._grouper.result_index\n+ expected = Index(\n+ [Timestamp(\"2013-01-01\"), Timestamp(\"2013-01-02\")],\n+ dtype=\"timestamp[ns, America/Denver][pyarrow]\",\n+ )\n+ tm.assert_index_equal(result, expected)" } ], "reviews": [ { "id": 3621477849, "user": "user_fb5fa0a10142", "state": "COMMENTED", "body": null, "submitted_at": "2025-12-31T22:12:26+00:00" }, { "id": 3621917145, "user": "user_c1cc819e14db", "state": "COMMENTED", "body": null, "submitted_at": "2026-01-01T15:25:49+00:00" }, { "id": 3621924168, "user": "user_fb5fa0a10142", "state": "COMMENTED", "body": null, "submitted_at": "2026-01-01T15:39:06+00:00" }, { "id": 3622020470, "user": "user_c9260bc45a59", "state": "APPROVED", "body": null, "submitted_at": "2026-01-01T19:28:07+00:00" } ], "review_comments": [ { "id": 2655932219, "user": "user_fb5fa0a10142", "body": "is there a reason why we have to do a cast-back approach instead of prevent-casting-away earlier on?", "path": "pandas/core/resample.py", "line": 245, "side": "RIGHT", "created_at": "2025-12-31T22:12:26+00:00" }, { "id": 2656430407, "user": "user_c1cc819e14db", "body": "It's not exactly a cast-back, the labels are generated directly via `date_range`.\n\nhttps://github.com/[USER_REDACTED]ndas-dev/pandas/blob/adf237214db1600e271fc5ff87b2a419f991a830/pandas/core/resample.py#L2590-L2599\n\nWe'd need to generate these as arrow-backed data. More generally, to avoid casting the index to a DatetimeIndex, we'd need a replacement for `generate_bins_dt64` which relies on NumPy data.", "path": "pandas/core/resample.py", "line": 245, "side": "RIGHT", "created_at": "2026-01-01T15:25:49+00:00" }, { "id": 2656438783, "user": "user_fb5fa0a10142", "body": "Thanks for explaining. No objections here.", "path": "pandas/core/resample.py", "line": 245, "side": "RIGHT", "created_at": "2026-01-01T15:39:06+00:00" } ], "meta": { "languages": [ "py", "rst" ], "touches_tests": true, "review_state_summary": { "COMMENTED": 3, "APPROVED": 1 }, "meaningful_comment_count": 3, "has_approval": true, "has_changes_requested": false, "total_review_comments": 3 } } { "_id": "725183e19ac98e0d", "_schema_version": "1.0", "_cleaned_at": "2026-02-12T07:46:52.273576+00:00", "repo": "pandas-dev/pandas", "repo_url": "https://github.com/pandas-dev/pandas", "license_name": "BSD 3-Clause \"New\" or \"Revised\" License", "license_spdx": "BSD-3-Clause", "pr_number": 63520, "title": "DOC: Inline docstring in `pandas/io/formats/style.py`", "body": "- [x] closes #62437 (Replace xxxx with the GitHub issue number)\n- [ ] [Tests added and passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#writing-tests) if fixing a bug or adding a new feature\n- [x] All [code checks passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit).\n- [ ] Added [type annotations](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#type-hints) to new arguments/methods/functions.\n- [ ] Added an entry in the latest `doc/source/whatsnew/vX.X.X.rst` file if fixing a bug or adding a new feature.\n- [ ] If I used AI to develop this pull request, I prompted it to follow `AGENTS.md`.", "author": "user_5b0b62fe7839", "created_at": "2025-12-31T06:37:27+00:00", "merged_at": "2026-01-01T19:24:23+00:00", "base_branch": "main", "head_branch": "inline_io_fmt_style", "additions": 439, "deletions": 191, "changed_files": 1, "files": [ { "filename": "pandas/io/formats/style.py", "status": "modified", "additions": 439, "deletions": 191, "changes": 630, "patch": "@@ -7,7 +7,6 @@\n import copy\n from functools import partial\n import operator\n-import textwrap\n from typing import (\n TYPE_CHECKING,\n Concatenate,\n@@ -20,10 +19,6 @@\n from pandas._config import get_option\n \n from pandas.compat._optional import import_optional_dependency\n-from pandas.util._decorators import (\n- Substitution,\n- doc,\n-)\n \n import pandas as pd\n from pandas import (\n@@ -35,8 +30,6 @@\n DataFrame,\n Series,\n )\n-from pandas.core.generic import NDFrame\n-from pandas.core.shared_docs import _shared_docs\n \n from pandas.io.formats.format import save_to_buffer\n \n@@ -83,34 +76,7 @@\n )\n \n from pandas import ExcelWriter\n-\n-\n-####\n-# [NAME_REDACTED]\n-\n-subset_args = \"\"\"subset : label, array-like, IndexSlice, optional\n- A valid 2d input to `DataFrame.loc[]`, or, in the case of a 1d input\n- or single key, to `DataFrame.loc[:, ]` where the columns are\n- prioritised, to limit ``data`` to *before* applying the function.\"\"\"\n-\n-properties_args = \"\"\"props : str, default None\n- CSS properties to use for highlighting. If ``props`` is given, ``color``\n- is not used.\"\"\"\n-\n-coloring_args = \"\"\"color : str, default '{default}'\n- Background color to use for highlighting.\"\"\"\n-\n-buffering_args = \"\"\"buf : str, path object, file-like object, optional\n- String, path object (implementing ``os.PathLike[str]``), or file-like\n- object implementing a string ``write()`` function. If ``None``, the result is\n- returned as a string.\"\"\"\n-\n-encoding_args = \"\"\"encoding : str, optional\n- Character encoding setting for file output (and meta tags if available).\n- Defaults to ``pandas.options.styler.render.encoding`` value of \"utf-8\".\"\"\"\n-\n-#\n-###\n+ from pandas.core.generic import NDFrame\n \n \n class Styler(StylerRenderer):\n@@ -541,25 +507,6 @@ def set_tooltips(\n \n return self\n \n- [USER_REDACTED](\n- NDFrame.to_excel,\n- klass=\"Styler\",\n- storage_options=_shared_docs[\"storage_options\"],\n- storage_options_versionadded=\"1.5.0\",\n- encoding_parameter=textwrap.dedent(\n- \"\"\"\\\n- encoding : str or None, default None\n- Unused parameter, present for compatibility.\n- \"\"\"\n- ),\n- verbose_parameter=textwrap.dedent(\n- \"\"\"\\\n- verbose : str, default True\n- Optional unused parameter, present for compatibility.\n- \"\"\"\n- ),\n- extra_parameters=\"\",\n- )\n def to_excel(\n self,\n excel_writer: FilePath | WriteExcelBuffer | ExcelWriter,\n@@ -581,6 +528,130 @@ def to_excel(\n storage_options: StorageOptions | None = None,\n autofilter: bool = False,\n ) -> None:\n+ \"\"\"\n+ [NAME_REDACTED] to an Excel sheet.\n+\n+ To write a single Styler to an Excel .xlsx file it is only necessary to\n+ specify a target file name. To write to multiple sheets it is necessary to\n+ create an `ExcelWriter` object with a target file name, and specify a sheet\n+ in the file to write to.\n+\n+ Multiple sheets may be written to by [NAME_REDACTED] `sheet_name`.\n+ With all data written to the file it is necessary to save the changes.\n+ Note that creating an `ExcelWriter` object with a file name that already exists\n+ will overwrite the existing file because the default mode is write.\n+\n+ Parameters\n+ ----------\n+ excel_writer : path-like, file-like, or ExcelWriter object\n+ File path or existing ExcelWriter.\n+ sheet_name : str, default 'Sheet1'\n+ Name of sheet which will contain DataFrame.\n+ na_rep : str, default ''\n+ Missing data representation.\n+ float_format : str, optional\n+ Format string for floating point numbers. For example\n+ ``float_format=\"%.2f\"`` will format 0.1234 to 0.12.\n+ columns : sequence or list of str, optional\n+ Columns to write.\n+ header : bool or list of str, default True\n+ Write out the column names. If a list of string is given it is\n+ assumed to be aliases for the column names.\n+ index : bool, default True\n+ Write row names (index).\n+ index_label : str or sequence, optional\n+ Column label for index column(s) if desired. If not specified, and\n+ `header` and `index` are True, then the index names are used. A\n+ sequence should be given if the DataFrame uses MultiIndex.\n+ startrow : int, default 0\n+ Upper left cell row to dump data frame.\n+ startcol : int, default 0\n+ Upper left cell column to dump data frame.\n+ engine : str, optional\n+ Write engine to use, 'openpyxl' or 'xlsxwriter'. You can also set this\n+ via the options ``io.excel.xlsx.writer`` or\n+ ``io.excel.xlsm.writer``.\n+ merge_cells : bool or 'columns', default False\n+ If True, write MultiIndex index and columns as merged cells.\n+ If 'columns', merge MultiIndex column cells only.\n+ encoding : str or None, default None\n+ Unused parameter, present for compatibility.\n+ inf_rep : str, default 'inf'\n+ Representation for infinity (there is no native representation for\n+ infinity in Excel).\n+ verbose : str, default True\n+ Optional unused parameter, present for compatibility.\n+ freeze_panes : tuple of int (length 2), optional\n+ Specifies the one-based bottommost row and rightmost column that\n+ is to be frozen.\n+ storage_options : dict, optional\n+ Extra options that make sense for a particular storage connection, e.g.\n+ host, port, username, password, etc. For HTTP(S) URLs the key-value pairs\n+ are forwarded to ``urllib.request.Request`` as header options. For other\n+ URLs (e.g. starting with \"s3://\", and \"gcs://\") the key-value pairs are\n+ forwarded to ``fsspec.open``. Please see ``fsspec`` and ``urllib`` for more\n+ details, and for more examples on storage options refer `here\n+ `_.\n+\n+ autofilter : bool, default False\n+ If True, add automatic filters to all columns.\n+\n+ See Also\n+ --------\n+ to_csv : [NAME_REDACTED] to a comma-separated values (csv) file.\n+ ExcelWriter : Class for writing DataFrame objects into excel sheets.\n+ read_excel : Read an Excel file into a pandas DataFrame.\n+ read_csv : Read a comma-separated values (csv) file into DataFrame.\n+ io.formats.style.Styler.to_excel : Add styles to Excel sheet.\n+\n+ Notes\n+ -----\n+ For compatibility with :meth:`~DataFrame.to_csv`,\n+ to_excel serializes lists and dicts to strings before writing.\n+\n+ Once a workbook has been saved it is not possible to write further\n+ data without rewriting the whole workbook.\n+\n+ pandas will check the number of rows, columns,\n+ and cell character count does not exceed Excel's limitations.\n+ All other limitations must be checked by [NAME_REDACTED]\n+\n+ Examples\n+ --------\n+\n+ Create, write to and save a workbook:\n+\n+ >>> df1 = pd.DataFrame(\n+ ... [[\"a\", \"b\"], [\"c\", \"d\"]],\n+ ... index=[\"row 1\", \"row 2\"],\n+ ... columns=[\"col 1\", \"col 2\"],\n+ ... )\n+ >>> df1.to_excel(\"output.xlsx\") # doctest: +SKIP\n+\n+ To specify the sheet name:\n+\n+ >>> df1.to_excel(\"output.xlsx\", sheet_name=\"Sheet_name_1\") # doctest: +SKIP\n+\n+ If you wish to write to more than one sheet in the workbook, it is\n+ necessary to specify an ExcelWriter object:\n+\n+ >>> df2 = df1.copy()\n+ >>> with pd.ExcelWriter(\"output.xlsx\") as writer: # doctest: +SKIP\n+ ... df1.to_excel(writer, sheet_name=\"Sheet_name_1\")\n+ ... df2.to_excel(writer, sheet_name=\"Sheet_name_2\")\n+\n+ ExcelWriter can also be used to append to an existing Excel file:\n+\n+ >>> with pd.ExcelWriter(\"output.xlsx\", mode=\"a\") as writer: # doctest: +SKIP\n+ ... df1.to_excel(writer, sheet_name=\"Sheet_name_3\")\n+\n+ To set the library that is used to write the Excel file,\n+ you can pass the `engine` keyword (the default engine is\n+ automatically chosen depending on the file extension):\n+\n+ >>> df1.to_excel(\"output1.xlsx\", engine=\"xlsxwriter\") # doctest: +SKIP\n+ \"\"\"\n from pandas.io.formats.excel import ExcelFormatter\n \n formatter = ExcelFormatter(\n@@ -676,8 +747,8 @@ def to_latex(\n ----------\n buf : str, path object, file-like object, or None, default None\n String, path object (implementing ``os.PathLike[str]``), or file-like\n- object implementing a string ``write()`` function. If None, the result is\n- returned as a string.\n+ object implementing a string ``write()`` function. If None, the result\n+ is returned as a string.\n column_format : str, optional\n The LaTeX column specification placed in location:\n \n@@ -1235,7 +1306,6 @@ def to_typst(\n max_columns: int | None = ...,\n ) -> str: ...\n \n- [USER_REDACTED](buf=buffering_args, encoding=encoding_args)\n def to_typst(\n self,\n buf: FilePath | WriteBuffer[str] | None = None,\n@@ -1253,8 +1323,13 @@ def to_typst(\n \n Parameters\n ----------\n- %(buf)s\n- %(encoding)s\n+ buf : str, path object, file-like object, optional\n+ String, path object (implementing ``os.PathLike[str]``), or file-like\n+ object implementing a string ``write()`` function. If ``None``, the result\n+ is returned as a string.\n+ encoding : str, optional\n+ Character encoding setting for file output (and meta tags if available).\n+ Defaults to ``pandas.options.styler.render.encoding`` value of \"utf-8\".\n sparse_index : bool, optional\n Whether to sparsify the display of a hierarchical index. Setting to False\n will display each explicit level element in a hierarchical key for each row.\n@@ -1354,7 +1429,6 @@ def to_html(\n **kwargs,\n ) -> str: ...\n \n- [USER_REDACTED](buf=buffering_args, encoding=encoding_args)\n def to_html(\n self,\n buf: FilePath | WriteBuffer[str] | None = None,\n@@ -1377,7 +1451,10 @@ def to_html(\n \n Parameters\n ----------\n- %(buf)s\n+ buf : str, path object, file-like object, optional\n+ String, path object (implementing ``os.PathLike[str]``), or file-like\n+ object implementing a string ``write()`` function. If ``None``, the result\n+ is returned as a string.\n table_uuid : str, optional\n Id attribute assigned to the HTML element in the format:\n \n@@ -1412,8 +1489,9 @@ def to_html(\n Rows and columns may be reduced if the number of total elements is\n large. This value is set to ``pandas.options.styler.render.max_elements``,\n which is 262144 (18 bit browser rendering).\n-\n- %(encoding)s\n+ encoding : str, optional\n+ Character encoding setting for file output (and meta tags if available).\n+ Defaults to ``pandas.options.styler.render.encoding`` value of \"utf-8\".\n doctype_html : bool, default False\n Whether to output a fully structured HTML file including all\n HTML elements, or just the core ``\n-\n-.. div:: sk-[REDACTED]\n-\n- .. div:: text-box\n-\n- The `Members `_ of\n- the `[NAME_REDACTED] at [NAME_REDACTED]\n- `_ help at maintaining and\n- improving the project through their financial support.\n-\n- .. div:: image-box\n-\n- .. table::\n- :class: image-subtable\n-\n- +----------+-----------+\n- | |chanel| |\n- +----------+-----------+\n- | |axa| | |bnp| |\n- +----------+-----------+\n- | |nvidia| |\n- +----------+-----------+\n- | |dataiku| |\n- +----------+-----------+\n- | |inria| |\n- +----------+-----------+\n+[NAME_REDACTED]\n+===============\n \n-..........\n+Founding sponsors\n+-----------------\n \n .. div:: sk-[REDACTED]\n \n .. div:: text-box\n \n- `NVidia `_ funds [NAME_REDACTED] since 2022\n- and is part of the scikit-learn consortium at Inria.\n+ `Inria `_ supports scikit-learn through their\n+ sponsorship.\n \n .. div:: image-box\n \n- .. image:: images/nvidia.png\n- :target: https://nvidia.com\n+ .. image:: images/inria-logo.jpg\n+ :target: https://www.inria.fr\n \n ..........\n \n-.. div:: sk-[REDACTED]\n-\n- .. div:: text-box\n-\n- `Microsoft `_ funds Andreas Müller since 2020.\n-\n- .. div:: image-box\n-\n- .. image:: images/microsoft.png\n- :target: https://microsoft.com\n-\n-...........\n-\n-.. div:: sk-[REDACTED]\n-\n- .. div:: text-box\n-\n- `[NAME_REDACTED] `_ funds [NAME_REDACTED] since 2022.\n-\n- .. div:: image-box\n-\n- .. image:: images/quansight-labs.png\n- :target: https://labs.quansight.org\n-\n-...........\n-\n-.. |czi| image:: images/czi.png\n- :target: https://chanzuckerberg.com\n-\n-.. |wellcome| image:: images/wellcome-trust.png\n- :target: https://wellcome.org/\n-\n-.. div:: sk-[REDACTED]\n-\n- .. div:: text-box\n-\n- `The Chan-Zuckerberg Initiative `_ and\n- `[NAME_REDACTED] `_ fund scikit-learn through the\n- `[NAME_REDACTED] Software for Science (EOSS) `_\n- cycle 6.\n-\n- It supports [NAME_REDACTED] and diversity & inclusion initiatives that will\n- be announced in the future.\n-\n- .. div:: image-box\n-\n- .. table::\n- :class: image-subtable\n-\n- +----------+----------------+\n- | |czi| | |wellcome| |\n- +----------+----------------+\n-\n-...........\n-\n-.. div:: sk-[REDACTED]\n-\n- .. div:: text-box\n-\n- `Tidelift `_ supports the project via their service\n- agreement.\n-\n- .. div:: image-box\n-\n- .. image:: images/Tidelift-logo-on-light.svg\n- :target: https://tidelift.com/\n-\n-...........\n-\n-\n-[NAME_REDACTED]\n+Gold sponsors\n -------------\n \n .. div:: sk-[REDACTED]\n \n .. div:: text-box\n \n- `[NAME_REDACTED] `_ funded [NAME_REDACTED] in 2022 and 2023,\n- and funded Thomas J. Fan from 2021 to 2023.\n+ `Chanel `_ supports scikit-learn through their\n+ sponsorship.\n \n .. div:: image-box\n \n- .. image:: images/quansight-labs.png\n- :target: https://labs.quansight.org\n-\n-...........\n-\n-.. div:: sk-[REDACTED]\n-\n- .. div:: text-box\n-\n- `[NAME_REDACTED] `_ funded Andreas Müller\n- (2016-2020).\n-\n- .. div:: image-box\n+ .. image:: images/chanel.png\n+ :target: https://www.chanel.com\n \n- .. image:: images/columbia.png\n- :target: https://columbia.edu\n+..........\n \n-........\n+Silver sponsors\n+---------------\n \n .. div:: sk-[REDACTED]\n \n .. div:: text-box\n \n- `The University of Sydney `_ funded [NAME_REDACTED]\n- (2017-2021).\n+ `BNP [NAME_REDACTED] `_ supports scikit-learn\n+ through their sponsorship.\n \n .. div:: image-box\n \n- .. image:: images/sydney-primary.jpeg\n- :target: https://sydney.edu.au/\n-\n-...........\n+ .. image:: images/bnp-paribas.jpg\n+ :target: https://group.bnpparibas/\n \n-.. div:: sk-[REDACTED]\n-\n- .. div:: text-box\n-\n- Andreas Müller received a grant to improve scikit-learn from the\n- `Alfred P. [NAME_REDACTED] `_ .\n- This grant supported the position of [NAME_REDACTED] and Thomas J. Fan.\n-\n- .. div:: image-box\n-\n- .. image:: images/sloan_banner.png\n- :target: https://sloan.org/\n+..........\n \n-.............\n+Bronze sponsors\n+---------------\n \n .. div:: sk-[REDACTED]\n \n .. div:: text-box\n \n- `INRIA `_ actively supports this project. It has\n- provided funding for [NAME_REDACTED] (2010-2012), [NAME_REDACTED]\n- (2012-2013) and [NAME_REDACTED] (2013-2017) to work on this project\n- full-time. It also hosts coding sprints and other events.\n+ `NVIDIA `_ supports scikit-learn through their sponsorship and employs full-time core maintainer [NAME_REDACTED]. \n \n .. div:: image-box\n \n- .. image:: images/inria-logo.jpg\n- :target: https://www.inria.fr\n+ .. image:: images/nvidia.png\n+ :target: https://nvidia.com\n \n-.....................\n+..........\n \n-.. div:: sk-[REDACTED]\n+Other contributions\n+-------------------\n \n- .. div:: text-box\n+.. |chanel| image:: images/chanel.png\n+ :target: https://www.chanel.com\n \n- `[NAME_REDACTED] for [NAME_REDACTED] `_\n- funded one year for a developer to work on the project full-time (2014-2015), 50%\n- of the time of [NAME_REDACTED] (2016-2017) and 50% of the time of Joris van den\n- Bossche (2017-2018).\n+.. |axa| image:: images/axa.png\n+ :target: https://www.axa.fr/\n \n- .. div:: image-box\n+.. |bnp| image:: images/bnp.png\n+ :target: https://www.bnpparibascardif.com/\n \n- .. image:: images/cds-logo.png\n- :target: http://www.datascience-paris-saclay.fr/\n+.. |bnpparibasgroup| image:: images/bnp-paribas.jpg\n+ :target: https://group.bnpparibas/\n \n-..........................\n+.. |dataiku| image:: images/dataiku.png\n+ :target: https://www.dataiku.com/\n \n-.. div:: sk-[REDACTED]\n+.. |nvidia| image:: images/nvidia.png\n+ :target: https://www.nvidia.com\n \n- .. div:: text-box\n+.. |inria| image:: images/inria-logo.jpg\n+ :target: https://www.inria.fr\n \n- `NYU [NAME_REDACTED] Environment `_\n- funded [NAME_REDACTED] (2014-2016) to work on this project. The Moore-Sloan\n- [NAME_REDACTED] also funds several students to work on the project\n- part-time.\n+.. raw:: html\n \n- .. div:: image-box\n+ \n \n-.. div:: sk-[REDACTED]\n \n- .. div:: text-box\n+* `Microsoft `_ funds Andreas Müller since 2020.\n \n- `Télécom Paristech `_ funded [NAME_REDACTED]\n- (2014), Tom Dupré la Tour (2015), Raghav RV (2015-2017), [NAME_REDACTED]\n- (2016-2017) and [NAME_REDACTED] (2017) to work on scikit-learn.\n \n- .. div:: image-box\n+* `[NAME_REDACTED] `_ funds [NAME_REDACTED] since 2022.\n \n- .. image:: images/telecom.png\n- :target: https://www.telecom-paristech.fr/\n+* `The Chan-Zuckerberg Initiative `_ and\n+ `[NAME_REDACTED] `_ fund scikit-learn through the\n+ `[NAME_REDACTED] Software for Science (EOSS) `_\n+ cycle 6.\n \n-.....................\n+ It supports [NAME_REDACTED] and diversity & inclusion initiatives that will\n+ be announced in the future.\n \n-.. div:: sk-[REDACTED]\n+* `Tidelift `_ supports the project via their service\n+ agreement.\n \n- .. div:: text-box\n+[NAME_REDACTED]\n+=============\n \n- `The Labex DigiCosme `_ funded [NAME_REDACTED]\n- (2015-2016), Tom Dupré la Tour (2015-2016 and 2017-2018), [NAME_REDACTED]\n- (2018-2019) to work part time on scikit-learn during their PhDs. It also\n- funded a scikit-learn coding sprint in 2015.\n+`[NAME_REDACTED] `_ funded [NAME_REDACTED] in 2022 and 2023,\n+and funded Thomas J. Fan from 2021 to 2023.\n \n- .. div:: image-box\n+`[NAME_REDACTED] `_ funded Andreas Müller\n+(2016-2020).\n \n- .. image:: images/digicosme.png\n- :target: https://digicosme.lri.fr\n+`The University of Sydney `_ funded [NAME_REDACTED]\n+(2017-2021).\n \n-.....................\n+Andreas Müller received a grant to improve scikit-learn from the\n+`Alfred P. [NAME_REDACTED] `_ .\n+This grant supported the position of [NAME_REDACTED] and Thomas J. Fan.\n \n-.. div:: sk-[REDACTED]\n+`INRIA `_ has provided funding for [NAME_REDACTED]\n+(2010-2012), [NAME_REDACTED] (2012-2013) and [NAME_REDACTED] (2013-2017) to\n+work on this project full-time. It also hosts coding sprints and other events.\n \n- .. div:: text-box\n+`[NAME_REDACTED] for [NAME_REDACTED] `_\n+funded one year for a developer to work on the project full-time (2014-2015), 50%\n+of the time of [NAME_REDACTED] (2016-2017) and 50% of the time of Joris van den\n+Bossche (2017-2018).\n \n- `The Chan-Zuckerberg Initiative `_ funded Nicolas\n- Hug to work full-time on scikit-learn in 2020.\n+`NYU [NAME_REDACTED] Environment `_\n+funded [NAME_REDACTED] (2014-2016) to work on this project. The Moore-Sloan\n+[NAME_REDACTED] also funds several students to work on the project\n+part-time.\n \n- .. div:: image-box\n+`Télécom Paristech `_ funded [NAME_REDACTED]\n+(2014), Tom Dupré la Tour (2015), Raghav RV (2015-2017), [NAME_REDACTED]\n+(2016-2017) and [NAME_REDACTED] (2017) to work on scikit-learn.\n \n- .. image:: images/czi.png\n- :target: https://chanzuckerberg.com\n+`The Labex DigiCosme `_ funded [NAME_REDACTED]\n+(2015-2016), Tom Dupré la Tour (2015-2016 and 2017-2018), [NAME_REDACTED]\n+(2018-2019) to work part time on scikit-learn during their PhDs. It also\n+funded a scikit-learn coding sprint in 2015.\n \n-......................\n+`The Chan-Zuckerberg Initiative `_ funded Nicolas\n+Hug to work full-time on scikit-learn in 2020.\n \n The following students were sponsored by `Google\n `_ to work on scikit-learn through\n@@ -582,6 +454,24 @@ the past:\n \n |hf|\n \n+ .. grid-item::\n+ :class: sd-text-center\n+ :child-align: center\n+\n+ |dataiku|\n+\n+ .. grid-item::\n+ :class: sd-text-center\n+ :child-align: center\n+\n+ |bnp|\n+\n+ .. grid-item::\n+ :class: sd-text-center\n+ :child-align: center\n+\n+ |axa|\n+\n \n Donations in Kind\n -----------------\n@@ -679,3 +569,5 @@ scikit-learn [NAME_REDACTED] scikit-learn swag is available for purchase at the `NumFOCUS online store\n `_.\n A portion of the proceeds from each sale goes to support the scikit-learn project.\n+\n+" }, { "filename": "doc/images/bnp-paribas.jpg", "status": "added", "additions": 0, "deletions": 0, "changes": 0, "patch": null }, { "filename": "doc/templates/index.html", "status": "modified", "additions": 1, "deletions": 3, "changes": 4, "patch": "@@ -294,10 +294,8 @@

        Who uses scikit-learn?

        \n \n \n \n- \n- \n+ \n \n- \n \n \n " } ], "reviews": [ { "id": 3411471737, "user": "user_fca2535bcd49", "state": "COMMENTED", "body": "Looks like the doc build is picky and complaining about too short underlines or something like this, let's try to fix them all at once.", "submitted_at": "2025-11-03T15:09:23+00:00" }, { "id": 3414133897, "user": "user_fca2535bcd49", "state": "APPROVED", "body": "Thanks for the PR, this seems fine to me!\n\nHaving someone outside Probabl give a quick look would be nice, e.g [USER_REDACTED] [USER_REDACTED] or [USER_REDACTED]?\n\nThe main change is the reorg of the funding section to display different tiers (gold, silver, etc ...) and update the information: \n- [this PR Funding section](https://output.circle-artifacts.com/output/job/746a7116-decc-454d-bc4b-cbc2cae68021/artifacts/0/doc/about.html#funding)\n- [dev website Funding section](https://scikit-learn.org/dev/about.html)", "submitted_at": "2025-11-04T05:36:59+00:00" }, { "id": 3419600387, "user": "user_d16337ec046b", "state": "APPROVED", "body": "A nit and a question but LGTM! Thanks", "submitted_at": "2025-11-05T04:00:09+00:00" }, { "id": 3422531363, "user": "user_4a6a3c89f56a", "state": "COMMENTED", "body": "Removing unnecessary JS code", "submitted_at": "2025-11-05T14:49:41+00:00" }, { "id": 3426387041, "user": "user_fca2535bcd49", "state": "COMMENTED", "body": null, "submitted_at": "2025-11-06T06:14:33+00:00" }, { "id": 3427158202, "user": "user_4a6a3c89f56a", "state": "COMMENTED", "body": null, "submitted_at": "2025-11-06T09:31:37+00:00" }, { "id": 3427293198, "user": "user_d5b9cb906259", "state": "APPROVED", "body": "Thanks for updating this and making it nicer to look at.\n\nA hand full of small comments. Otherwise looks good to me.", "submitted_at": "2025-11-06T10:06:08+00:00" }, { "id": 3427354785, "user": "user_4a6a3c89f56a", "state": "COMMENTED", "body": null, "submitted_at": "2025-11-06T10:14:55+00:00" }, { "id": 3427364551, "user": "user_4a6a3c89f56a", "state": "COMMENTED", "body": "Merging Nvidia's commitment description", "submitted_at": "2025-11-06T10:22:01+00:00" } ], "review_comments": [ { "id": 2486810503, "user": "user_fca2535bcd49", "body": "```suggestion\nFounding sponsors\n-----------------\n```", "path": "doc/about.rst", "line": null, "side": "RIGHT", "created_at": "2025-11-03T15:07:41+00:00" }, { "id": 2486811760, "user": "user_fca2535bcd49", "body": "```suggestion\n[NAME_REDACTED]\n===============\n```", "path": "doc/about.rst", "line": null, "side": "RIGHT", "created_at": "2025-11-03T15:08:06+00:00" }, { "id": 2486812693, "user": "user_fca2535bcd49", "body": "```suggestion\nSilver sponsors\n---------------\n```", "path": "doc/about.rst", "line": null, "side": "RIGHT", "created_at": "2025-11-03T15:08:22+00:00" }, { "id": 2486813315, "user": "user_fca2535bcd49", "body": "```suggestion\nBronze sponsors\n---------------\n```", "path": "doc/about.rst", "line": null, "side": "RIGHT", "created_at": "2025-11-03T15:08:34+00:00" }, { "id": 2492780573, "user": "user_d16337ec046b", "body": "```suggestion\n and employs the full-time core maintainers [NAME_REDACTED], [NAME_REDACTED],\n```\nsmall nit. I think this list is exhaustive (includes everyone) so we don't need 'such as'.", "path": "doc/about.rst", "line": null, "side": "RIGHT", "created_at": "2025-11-05T03:38:09+00:00" }, { "id": 2492828180, "user": "user_d16337ec046b", "body": "What does 'handle links' mean?", "path": "doc/about.rst", "line": null, "side": "RIGHT", "created_at": "2025-11-05T03:59:56+00:00" }, { "id": 2494848017, "user": "user_4a6a3c89f56a", "body": "That second part isn’t really needed here. It’s just a defensive fallback I added in case the page didn’t wrap its content in a #about element, or if the same script were reused elsewhere. Since on about.html everything is already inside the #about section, we can safely remove that second block. I guess.", "path": "doc/about.rst", "line": null, "side": "RIGHT", "created_at": "2025-11-05T14:44:27+00:00" }, { "id": 2494875045, "user": "user_4a6a3c89f56a", "body": "```suggestion\n```", "path": "doc/about.rst", "line": null, "side": "RIGHT", "created_at": "2025-11-05T14:49:01+00:00" }, { "id": 2494876701, "user": "user_4a6a3c89f56a", "body": "```suggestion\n```", "path": "doc/about.rst", "line": null, "side": "RIGHT", "created_at": "2025-11-05T14:49:17+00:00" }, { "id": 2497613144, "user": "user_fca2535bcd49", "body": "Is this really needed? Removing it would be simpler (less code to worry about). This would also be less surpring, opening the link in the same tab is the standard behaviour IMO.", "path": "doc/about.rst", "line": null, "side": "RIGHT", "created_at": "2025-11-06T06:14:33+00:00" }, { "id": 2498205117, "user": "user_4a6a3c89f56a", "body": "Fine, let me remove it to move forward.", "path": "doc/about.rst", "line": null, "side": "RIGHT", "created_at": "2025-11-06T09:30:25+00:00" }, { "id": 2498207517, "user": "user_4a6a3c89f56a", "body": "```suggestion\n```", "path": "doc/about.rst", "line": null, "side": "RIGHT", "created_at": "2025-11-06T09:31:12+00:00" }, { "id": 2498208510, "user": "user_4a6a3c89f56a", "body": "```suggestion\n```", "path": "doc/about.rst", "line": null, "side": "RIGHT", "created_at": "2025-11-06T09:31:31+00:00" }, { "id": 2498310099, "user": "user_d5b9cb906259", "body": "English language suggestion\n\n```suggestion\n `:probabl. `_ manages the whole sponsorship program\n```", "path": "doc/about.rst", "line": null, "side": "RIGHT", "created_at": "2025-11-06T10:01:50+00:00" }, { "id": 2498316970, "user": "user_d5b9cb906259", "body": "Do we need this final \"raw html\"? What does it do?", "path": "doc/about.rst", "line": null, "side": "RIGHT", "created_at": "2025-11-06T10:03:41+00:00" }, { "id": 2498323536, "user": "user_d5b9cb906259", "body": "Can we combine this with the sponsor entry a la: \"NVIDIA supports scikit-learn through their sponsorship and employs full-time core maintainer [NAME_REDACTED]\"", "path": "doc/about.rst", "line": null, "side": "RIGHT", "created_at": "2025-11-06T10:05:37+00:00" }, { "id": 2498354755, "user": "user_4a6a3c89f56a", "body": "Good idea.\n```suggestion\n```", "path": "doc/about.rst", "line": null, "side": "RIGHT", "created_at": "2025-11-06T10:14:55+00:00" }, { "id": 2498362543, "user": "user_4a6a3c89f56a", "body": "```suggestion\n `NVIDIA `_ supports scikit-learn through their sponsorship and employs full-time core maintainer [NAME_REDACTED]. \n```", "path": "doc/about.rst", "line": null, "side": "RIGHT", "created_at": "2025-11-06T10:17:22+00:00" }, { "id": 2498369286, "user": "user_4a6a3c89f56a", "body": "I remove it it is a leftover from early suggestions I guess. \n```suggestion\n```", "path": "doc/about.rst", "line": null, "side": "RIGHT", "created_at": "2025-11-06T10:19:29+00:00" } ], "meta": { "languages": [ "html", "jpg", "rst" ], "touches_tests": false, "review_state_summary": { "COMMENTED": 6, "APPROVED": 3 }, "meaningful_comment_count": 19, "has_approval": true, "has_changes_requested": false, "total_review_comments": 19 } } { "_id": "65838392a250a3bf", "_schema_version": "1.0", "_cleaned_at": "2026-02-12T07:46:52.627996+00:00", "repo": "scikit-learn/scikit-learn", "repo_url": "https://github.com/scikit-learn/scikit-learn", "license_name": "BSD 3-Clause \"New\" or \"Revised\" License", "license_spdx": "BSD-3-Clause", "pr_number": 32625, "title": "DOC: Move a large part of text comments from code to narrative", "body": "\n\n#### [NAME_REDACTED]/PRs\n\n\n#### What does this implement/fix? Explain your changes.\n\nIn the Post-tuning the decision threshold for cost-sensitive learning example, \nlet's move a large part of text comments from code to narrative.\nhttps://scikit-learn.org/dev/auto_examples/model_selection/plot_cost_sensitive_learning.html\n\n#### Any other comments?\n\n\n\n", "author": "user_38cd8edc5910", "created_at": "2025-10-31T19:03:35+00:00", "merged_at": "2025-11-04T14:03:33+00:00", "base_branch": "main", "head_branch": "post-tuning-example", "additions": 18, "deletions": 17, "changed_files": 1, "files": [ { "filename": "examples/model_selection/plot_cost_sensitive_learning.py", "status": "modified", "additions": 18, "deletions": 17, "changes": 35, "patch": "@@ -144,28 +144,29 @@ def fpr_score(y, y_pred, neg_label, pos_label):\n # credit and paid interests) than to grant a credit to a customer that will\n # default.\n #\n-# We define a python function that weight the confusion matrix and return the\n+# We define a python function that weighs the confusion matrix and returns the\n # overall cost.\n+# The rows of the confusion matrix hold the counts of observed classes\n+# while the columns hold counts of predicted classes. Recall that here we\n+# consider \"bad\" as the positive class (second row and column).\n+# Scikit-learn model selection tools expect that we follow a convention\n+# that \"higher\" means \"better\", hence the following gain matrix assigns\n+# negative gains (costs) to the two kinds of prediction errors:\n+#\n+# - a gain of `-1` for each false positive (\"good\" credit labeled as \"bad\"),\n+# - a gain of `-5` for each false negative (\"bad\" credit labeled as \"good\"),\n+# - a `0` gain for true positives and true negatives.\n+#\n+# Note that theoretically, given that our model is calibrated and our data\n+# set representative and large enough, we do not need to tune the\n+# threshold, but can safely set it to 1/5 of the cost ratio, as stated by\n+# Eq. (2) in Elkan's paper [2]_.\n import numpy as np\n \n \n def credit_gain_score(y, y_pred, neg_label, pos_label):\n cm = confusion_matrix(y, y_pred, labels=[neg_label, pos_label])\n- # The rows of the confusion matrix hold the counts of observed classes\n- # while the columns hold counts of predicted classes. Recall that here we\n- # consider \"bad\" as the positive class (second row and column).\n- # Scikit-learn model selection tools expect that we follow a convention\n- # that \"higher\" means \"better\", hence the following gain matrix assigns\n- # negative gains (costs) to the two kinds of prediction errors:\n- # - a gain of -1 for each false positive (\"good\" credit labeled as \"bad\"),\n- # - a gain of -5 for each false negative (\"bad\" credit labeled as \"good\"),\n- # The true positives and true negatives are assigned null gains in this\n- # metric.\n- #\n- # Note that theoretically, given that our model is calibrated and our data\n- # set representative and large enough, we do not need to tune the\n- # threshold, but can safely set it to the cost ration 1/5, as stated by Eq.\n- # (2) in Elkan paper [2]_.\n+\n gain_matrix = np.array(\n [\n [0, -1], # -1 gain for false positives\n@@ -688,6 +689,6 @@ def business_metric(y_true, y_pred, amount):\n # historical data (offline evaluation) should ideally be confirmed by A/B testing\n # on live data (online evaluation). Note however that A/B testing models is\n # beyond the scope of the scikit-learn library itself.\n-\n+#\n # At the end, we disable the configuration flag for metadata routing::\n sklearn.set_config(enable_metadata_routing=False)" } ], "reviews": [ { "id": 3412085708, "user": "user_3dde41c3e377", "state": "COMMENTED", "body": "Thanks for the PR [USER_REDACTED]!", "submitted_at": "2025-11-03T17:16:41+00:00" }, { "id": 3415076739, "user": "user_3dde41c3e377", "state": "COMMENTED", "body": null, "submitted_at": "2025-11-04T09:27:38+00:00" }, { "id": 3416649478, "user": "user_3dde41c3e377", "state": "APPROVED", "body": null, "submitted_at": "2025-11-04T14:03:23+00:00" } ], "review_comments": [ { "id": 2487261446, "user": "user_3dde41c3e377", "body": "This part is not rendering properly. Also some wording can simplify the last phrase.\n```suggestion\n#\n# - a gain of `-1` for each false positive (\"good\" credit labeled as \"bad\"),\n# - a gain of `-5` for each false negative (\"bad\" credit labeled as \"good\"),\n# - a `0` gain for true positives and true negatives.\n#\n```", "path": "examples/model_selection/plot_cost_sensitive_learning.py", "line": null, "side": "RIGHT", "created_at": "2025-11-03T17:14:43+00:00" }, { "id": 2489485459, "user": "user_3dde41c3e377", "body": "```suggestion\n```", "path": "examples/model_selection/plot_cost_sensitive_learning.py", "line": 159, "side": "RIGHT", "created_at": "2025-11-04T09:27:38+00:00" } ], "meta": { "languages": [ "py" ], "touches_tests": false, "review_state_summary": { "COMMENTED": 2, "APPROVED": 1 }, "meaningful_comment_count": 2, "has_approval": true, "has_changes_requested": false, "total_review_comments": 2 } } { "_id": "7696438331e4a79d", "_schema_version": "1.0", "_cleaned_at": "2026-02-12T07:46:52.627996+00:00", "repo": "scikit-learn/scikit-learn", "repo_url": "https://github.com/scikit-learn/scikit-learn", "license_name": "BSD 3-Clause \"New\" or \"Revised\" License", "license_spdx": "BSD-3-Clause", "pr_number": 32620, "title": "DOC add doc repo cleanup to release process", "body": "This adds cleanup of the doc repo to the release process to make sure we do the cleanup periodically not to reach the limit again.\n\ncc [USER_REDACTED] [USER_REDACTED]", "author": "user_49a647962c6b", "created_at": "2025-10-31T08:45:11+00:00", "merged_at": "2025-11-13T14:01:02+00:00", "base_branch": "main", "head_branch": "doc/cleanup", "additions": 22, "deletions": 0, "changed_files": 1, "files": [ { "filename": "doc/developers/maintainer.rst.template", "status": "modified", "additions": 22, "deletions": 0, "changes": 22, "patch": "@@ -120,6 +120,7 @@ [NAME_REDACTED]\n {% if key == \"rc\" -%}\n * [ ] Update the sklearn dev0 version in main branch\n {%- endif %}\n+ * [ ] Cleanup the doc repo to free up space\n * [ ] Set the version number in the release branch\n * [ ] Set an upper bound on build dependencies in the release branch\n * [ ] Generate the changelog in the release branch\n@@ -160,6 +161,27 @@ [NAME_REDACTED]\n the `tool.towncrier` section in `pyproject.toml`.\n {% endif %}\n \n+ - The `scikit-learn/scikit-learn.github.io` needs to be cleaned up so that ideally\n+ it stays <5GB in size. Before doing this, create a new fresh fork of the existing\n+ repo in your own user, to have a place with the history of the repo in case it's\n+ needed. These commands will purge the history from the repo.\n+\n+ .. prompt:: bash\n+\n+ # need a non-shallow copy, and using https is much faster than ssh here\n+ # note that this will be a large download size, up to 100GB (repo size limit)\n+ git clone https://github.com/[USER_REDACTED]n/scikit-learn.github.io.git\n+ cd scikit-learn.github.io\n+ git remote add write [EMAIL_REDACTED]:scikit-learn/scikit-learn.github.io.git\n+ # checkout an orphan branch w/o history\n+ git checkout --orphan temp_branch\n+ git add -A\n+ git commit -m \"Initial commit after purging history\"\n+ git branch -D main\n+ # rename current branch to main to replace it\n+ git branch -m main\n+ git push --force write main\n+\n - In the release branch, change the version number `__version__` in\n `sklearn/__init__.py` to `{{ version_full }}`." } ], "reviews": [ { "id": 3403169680, "user": "user_fca2535bcd49", "state": "APPROVED", "body": "Thanks a few minor questions and comments but this is already very useful.\n\nOne question: should we start by [NAME_REDACTED] major release or every minor release? I am not 100% sure how the maintainer templating works.", "submitted_at": "2025-10-31T09:13:43+00:00" }, { "id": 3403698719, "user": "user_49a647962c6b", "state": "COMMENTED", "body": null, "submitted_at": "2025-10-31T10:54:53+00:00" }, { "id": 3403702632, "user": "user_49a647962c6b", "state": "COMMENTED", "body": null, "submitted_at": "2025-10-31T10:55:55+00:00" }, { "id": 3403706620, "user": "user_49a647962c6b", "state": "COMMENTED", "body": null, "submitted_at": "2025-10-31T10:56:46+00:00" }, { "id": 3404434772, "user": "user_5819d17296ee", "state": "APPROVED", "body": "LGTM besides the following question:", "submitted_at": "2025-10-31T13:58:58+00:00" }, { "id": 3404438915, "user": "user_5819d17296ee", "state": "COMMENTED", "body": null, "submitted_at": "2025-10-31T13:59:42+00:00" }, { "id": 3459167261, "user": "user_49a647962c6b", "state": "COMMENTED", "body": null, "submitted_at": "2025-11-13T10:56:43+00:00" } ], "review_comments": [ { "id": 2480618632, "user": "user_fca2535bcd49", "body": "I guess you also need to sync `main` on your fork if the idea is to keep the history \"just in case\"?", "path": "doc/developers/maintainer.rst.template", "line": null, "side": "RIGHT", "created_at": "2025-10-31T09:05:04+00:00" }, { "id": 2480623457, "user": "user_fca2535bcd49", "body": "Just curious why not use https here too? Full disclosure: I have always used https and never bothered with `git clone git@` (mostly for simplicity, for a very long time I was afraid of the complexity of setting up SSH keys 😅)", "path": "doc/developers/maintainer.rst.template", "line": 175, "side": "RIGHT", "created_at": "2025-10-31T09:06:21+00:00" }, { "id": 2480638621, "user": "user_fca2535bcd49", "body": "Just curious do you know whether the indicative ~5GB acceptable size is for the `.git` or for the total size of the `git clone`. For one commit for scikit-learn `.git` is at `1.6G`, `git clone` is at 5.2G.\n\nMNE-Python which is using a similar strategy (squash commits every release) for one commit `2.3G` `git clone` `7.6G`.", "path": "doc/developers/maintainer.rst.template", "line": null, "side": "RIGHT", "created_at": "2025-10-31T09:10:40+00:00" }, { "id": 2480643061, "user": "user_fca2535bcd49", "body": "Maybe indicate that it may take a while (`git clone --depth 1` took a few minutes maybe for me so when you fetch the full history it may be a bit longer)", "path": "doc/developers/maintainer.rst.template", "line": 173, "side": "RIGHT", "created_at": "2025-10-31T09:11:57+00:00" }, { "id": 2481021876, "user": "user_49a647962c6b", "body": "changed this to \"new fresh fork\"", "path": "doc/developers/maintainer.rst.template", "line": null, "side": "RIGHT", "created_at": "2025-10-31T10:54:53+00:00" }, { "id": 2481025230, "user": "user_49a647962c6b", "body": "This is what I did, I don't want to bother with authentication of https and 2FA every time I clone something, so I setup my keys once, and never do GH authentication again locally.", "path": "doc/developers/maintainer.rst.template", "line": 175, "side": "RIGHT", "created_at": "2025-10-31T10:55:55+00:00" }, { "id": 2481028088, "user": "user_49a647962c6b", "body": "It's total size of the repo and its history, so includes `.git` folder. That's the recommendation, but the hard limit is 100GB.", "path": "doc/developers/maintainer.rst.template", "line": null, "side": "RIGHT", "created_at": "2025-10-31T10:56:46+00:00" }, { "id": 2481523202, "user": "user_5819d17296ee", "body": "Don't you need to commit anything? Or does `git branch -m main` creates a commit automatically?", "path": "doc/developers/maintainer.rst.template", "line": 183, "side": "RIGHT", "created_at": "2025-10-31T13:58:35+00:00" }, { "id": 2481526289, "user": "user_5819d17296ee", "body": "I think either would do. The point is not to forget about it.", "path": "doc/developers/maintainer.rst.template", "line": 175, "side": "RIGHT", "created_at": "2025-10-31T13:59:42+00:00" }, { "id": 2522963906, "user": "user_49a647962c6b", "body": "Yeah, in practice when the repo is so large, it makes quite a bit of a difference in the time it takes to finish this task", "path": "doc/developers/maintainer.rst.template", "line": 175, "side": "RIGHT", "created_at": "2025-11-13T10:55:21+00:00" }, { "id": 2522965113, "user": "user_49a647962c6b", "body": "Yep, forgot to put it here", "path": "doc/developers/maintainer.rst.template", "line": 183, "side": "RIGHT", "created_at": "2025-11-13T10:55:39+00:00" } ], "meta": { "languages": [ "template" ], "touches_tests": false, "review_state_summary": { "APPROVED": 2, "COMMENTED": 5 }, "meaningful_comment_count": 11, "has_approval": true, "has_changes_requested": false, "total_review_comments": 11 } } { "_id": "12e950469b154809", "_schema_version": "1.0", "_cleaned_at": "2026-02-12T07:46:52.627996+00:00", "repo": "scikit-learn/scikit-learn", "repo_url": "https://github.com/scikit-learn/scikit-learn", "license_name": "BSD 3-Clause \"New\" or \"Revised\" License", "license_spdx": "BSD-3-Clause", "pr_number": 32615, "title": "MAINT Clean up after Scipy min version to 1.10", "body": "Removed specific code used when `scipy` min version was < 1.10.\n\n[USER_REDACTED]", "author": "user_32e669a27072", "created_at": "2025-10-30T15:51:17+00:00", "merged_at": "2025-10-31T15:54:00+00:00", "base_branch": "main", "head_branch": "scipy", "additions": 27, "deletions": 140, "changed_files": 5, "files": [ { "filename": "sklearn/conftest.py", "status": "modified", "additions": 10, "deletions": 18, "changes": 28, "patch": "@@ -14,6 +14,7 @@\n import numpy as np\n import pytest\n from _pytest.doctest import DoctestItem\n+from scipy.datasets import face\n from threadpoolctl import threadpool_limits\n \n from sklearn._min_dependencies import PYTEST_MIN_VERSION\n@@ -56,24 +57,16 @@\n f\" should have pytest >= {PYTEST_MIN_VERSION} installed.\"\n )\n \n-scipy_datasets_require_network = sp_version >= parse_version(\"1.10\")\n-\n \n def raccoon_face_or_skip():\n- # SciPy >= 1.10 requires network to access to get data\n- if scipy_datasets_require_network:\n- run_network_tests = environ.get(\"SKLEARN_SKIP_NETWORK_TESTS\", \"1\") == \"0\"\n- if not run_network_tests:\n- raise SkipTest(\"test is enabled when SKLEARN_SKIP_NETWORK_TESTS=0\")\n-\n- try:\n- import pooch # noqa: F401\n- except ImportError:\n- raise SkipTest(\"test requires pooch to be installed\")\n-\n- from scipy.datasets import face\n- else:\n- from scipy.misc import face\n+ # SciPy requires network access to get data\n+ run_network_tests = environ.get(\"SKLEARN_SKIP_NETWORK_TESTS\", \"1\") == \"0\"\n+ if not run_network_tests:\n+ raise SkipTest(\"test is enabled when SKLEARN_SKIP_NETWORK_TESTS=0\")\n+ try:\n+ import pooch # noqa: F401\n+ except ImportError:\n+ raise SkipTest(\"test requires pooch to be installed\")\n \n return face(gray=True)\n \n@@ -91,8 +84,7 @@ def raccoon_face_or_skip():\n \"fetch_species_distributions_fxt\": fetch_species_distributions,\n }\n \n-if scipy_datasets_require_network:\n- dataset_fetchers[\"raccoon_face_fxt\"] = raccoon_face_or_skip\n+dataset_fetchers[\"raccoon_face_fxt\"] = raccoon_face_or_skip\n \n _SKIP32_MARK = pytest.mark.skipif(\n environ.get(\"SKLEARN_RUN_FLOAT32_TESTS\", \"0\") != \"1\"," }, { "filename": "sklearn/preprocessing/_data.py", "status": "modified", "additions": 2, "deletions": 3, "changes": 5, "patch": "@@ -35,7 +35,6 @@\n validate_params,\n )\n from sklearn.utils.extmath import _incremental_mean_and_var, row_norms\n-from sklearn.utils.fixes import _yeojohnson_lambda\n from sklearn.utils.sparsefuncs import (\n incr_mean_variance_axis,\n inplace_column_scale,\n@@ -3595,8 +3594,8 @@ def _neg_log_likelihood(lmbda):\n # the computation of lambda is influenced by [NAME_REDACTED] to\n # get rid of them\n x = x[~np.isnan(x)]\n-\n- return _yeojohnson_lambda(_neg_log_likelihood, x)\n+ _, lmbda = stats.yeojohnson(x, lmbda=None)\n+ return lmbda\n \n def _check_input(self, X, in_fit, check_positive=False, check_shape=False):\n \"\"\"Validate the input before fit and transform." }, { "filename": "sklearn/preprocessing/_polynomial.py", "status": "modified", "additions": 15, "deletions": 69, "changes": 84, "patch": "@@ -29,7 +29,6 @@\n )\n from sklearn.utils._mask import _get_mask\n from sklearn.utils._param_validation import Interval, StrOptions\n-from sklearn.utils.fixes import parse_version, sp_version\n from sklearn.utils.stats import _weighted_percentile\n from sklearn.utils.validation import (\n FLOAT_DTYPES,\n@@ -460,23 +459,6 @@ def transform(self, X):\n # edge case: deal with empty matrix\n XP = sparse.csr_matrix((n_samples, 0), dtype=X.dtype)\n else:\n- # `scipy.sparse.hstack` breaks in scipy<1.9.2\n- # when `n_output_features_ > max_int32`\n- all_int32 = all(mat.indices.dtype == np.int32 for mat in to_stack)\n- if (\n- sp_version < parse_version(\"1.9.2\")\n- and self.n_output_features_ > max_int32\n- and all_int32\n- ):\n- raise ValueError( # pragma: no cover\n- \"In scipy versions `<1.9.2`, the function `scipy.sparse.hstack`\"\n- \" produces negative columns when:\\n1. The output shape contains\"\n- \" `n_cols` too large to be represented by a 32bit signed\"\n- \" integer.\\n2. All sub-matrices to be stacked have indices of\"\n- \" dtype `np.int32`.\\nTo avoid this error, either use a version\"\n- \" of scipy `>=1.9.2` or alter the `PolynomialFeatures`\"\n- \" transformer to produce fewer than 2^31 output features\"\n- )\n XP = sparse.hstack(to_stack, dtype=X.dtype, format=\"csr\")\n elif sparse.issparse(X) and X.format == \"csc\" and self._max_degree < 4:\n return self.transform(X.tocsr()).tocsc()\n@@ -1027,27 +1009,14 @@ def transform(self, X):\n n_splines = self.bsplines_[0].c.shape[1]\n degree = self.degree\n \n- # TODO: Remove this condition, once scipy 1.10 is the minimum version.\n- # Only scipy >= 1.10 supports design_matrix(.., extrapolate=..).\n- # The default (implicit in scipy < 1.10) is extrapolate=False.\n- scipy_1_10 = sp_version >= parse_version(\"1.10.0\")\n- # Note: self.bsplines_[0].extrapolate is True for extrapolation in\n- # [\"periodic\", \"continue\"]\n- if scipy_1_10:\n- use_sparse = self.sparse_output\n- kwargs_extrapolate = {\"extrapolate\": self.bsplines_[0].extrapolate}\n- else:\n- use_sparse = self.sparse_output and not self.bsplines_[0].extrapolate\n- kwargs_extrapolate = dict()\n-\n # Note that scipy BSpline returns float64 arrays and converts input\n # x=X[:, i] to c-contiguous float64.\n n_out = self.n_features_out_ + n_features * (1 - self.include_bias)\n if X.dtype in FLOAT_DTYPES:\n dtype = X.dtype\n else:\n dtype = np.float64\n- if use_sparse:\n+ if self.sparse_output:\n output_list = []\n else:\n XBS = np.zeros((n_samples, n_out), dtype=dtype, order=self.order)\n@@ -1076,7 +1045,7 @@ def transform(self, X):\n else: # self.extrapolation in (\"continue\", \"error\")\n x = X[:, feature_idx]\n \n- if use_sparse:\n+ if self.sparse_output:\n # We replace the nan values in the input column by some\n # arbitrary, in-range, numerical value since\n # BSpline.design_matrix() would otherwise raise on any nan\n@@ -1098,8 +1067,11 @@ def transform(self, X):\n elif nan_row_indices.shape[0] > 0:\n x = x.copy() # avoid mutation of input data\n x[nan_row_indices] = np.nanmin(x)\n+\n+ # Note: self.bsplines_[0].extrapolate is True for extrapolation in\n+ # [\"periodic\", \"continue\"]\n XBS_sparse = BSpline.design_matrix(\n- x, spl.t, spl.k, **kwargs_extrapolate\n+ x, spl.t, spl.k, self.bsplines_[0].extrapolate\n )\n \n if self.extrapolation == \"periodic\":\n@@ -1127,7 +1099,7 @@ def transform(self, X):\n XBS[\n nan_row_indices, output_feature_idx : output_feature_idx + 1\n ] = 0\n- if use_sparse:\n+ if self.sparse_output:\n XBS_sparse = XBS\n \n else: # extrapolation in (\"constant\", \"linear\")\n@@ -1140,7 +1112,7 @@ def transform(self, X):\n X[:, feature_idx] <= xmax\n )\n \n- if use_sparse:\n+ if self.sparse_output:\n outside_range_mask = ~inside_range_mask\n x = X[:, feature_idx].copy()\n # Set to some arbitrary value within the range of values\n@@ -1167,7 +1139,7 @@ def transform(self, X):\n # 'continue' is already returned as is by [NAME_REDACTED] == \"error\":\n has_nan_output_values = False\n- if use_sparse:\n+ if self.sparse_output:\n # Early convert to CSR as the sparsity structure of this\n # block should not change anymore. This is needed to be able\n # to safely assume that `.data` is a 1D array.\n@@ -1192,7 +1164,7 @@ def transform(self, X):\n \n below_xmin_mask = X[:, feature_idx] < xmin\n if np.any(below_xmin_mask):\n- if use_sparse:\n+ if self.sparse_output:\n # Note: See comment about SparseEfficiencyWarning above.\n XBS_sparse = XBS_sparse.tolil()\n XBS_sparse[below_xmin_mask, :degree] = f_min[:degree]\n@@ -1207,7 +1179,7 @@ def transform(self, X):\n \n above_xmax_mask = X[:, feature_idx] > xmax\n if np.any(above_xmax_mask):\n- if use_sparse:\n+ if self.sparse_output:\n # Note: See comment about SparseEfficiencyWarning above.\n XBS_sparse = XBS_sparse.tolil()\n XBS_sparse[above_xmax_mask, -degree:] = f_max[-degree:]\n@@ -1240,7 +1212,7 @@ def transform(self, X):\n f_min[j]\n + (X[below_xmin_mask, feature_idx] - xmin) * fp_min[j]\n )\n- if use_sparse:\n+ if self.sparse_output:\n # Note: See comment about SparseEfficiencyWarning above.\n XBS_sparse = XBS_sparse.tolil()\n XBS_sparse[below_xmin_mask, j] = linear_extr\n@@ -1256,7 +1228,7 @@ def transform(self, X):\n f_max[k]\n + (X[above_xmax_mask, feature_idx] - xmax) * fp_max[k]\n )\n- if use_sparse:\n+ if self.sparse_output:\n # Note: See comment about SparseEfficiencyWarning above.\n XBS_sparse = XBS_sparse.tolil()\n XBS_sparse[above_xmax_mask, k : k + 1] = linear_extr[\n@@ -1267,38 +1239,12 @@ def transform(self, X):\n linear_extr\n )\n \n- if use_sparse:\n+ if self.sparse_output:\n XBS_sparse = XBS_sparse.tocsr()\n output_list.append(XBS_sparse)\n \n- if use_sparse:\n- # TODO: Remove this conditional error when the minimum supported version of\n- # SciPy is 1.9.2\n- # `scipy.sparse.hstack` breaks in scipy<1.9.2\n- # when `n_features_out_ > max_int32`\n- max_int32 = np.iinfo(np.int32).max\n- all_int32 = True\n- for mat in output_list:\n- all_int32 &= mat.indices.dtype == np.int32\n- if (\n- sp_version < parse_version(\"1.9.2\")\n- and self.n_features_out_ > max_int32\n- and all_int32\n- ):\n- raise ValueError(\n- \"In scipy versions `<1.9.2`, the function `scipy.sparse.hstack`\"\n- \" produces negative columns when:\\n1. The output shape contains\"\n- \" `n_cols` too large to be represented by a 32bit signed\"\n- \" integer.\\n. All sub-matrices to be stacked have indices of\"\n- \" dtype `np.int32`.\\nTo avoid this error, either use a version\"\n- \" of scipy `>=1.9.2` or alter the `SplineTransformer`\"\n- \" transformer to produce fewer than 2^31 output features\"\n- )\n+ if self.sparse_output:\n XBS = sparse.hstack(output_list, format=\"csr\")\n- elif self.sparse_output:\n- # TODO: Remove conversion to csr, once scipy 1.10 is the minimum version:\n- # Adjust format of XBS to sparse, for scipy versions < 1.10.0:\n- XBS = sparse.csr_matrix(XBS)\n \n if self.include_bias:\n return XBS" }, { "filename": "sklearn/preprocessing/tests/test_polynomial.py", "status": "modified", "additions": 0, "deletions": 17, "changes": 17, "patch": "@@ -36,8 +36,6 @@\n from sklearn.utils.fixes import (\n CSC_CONTAINERS,\n CSR_CONTAINERS,\n- parse_version,\n- sp_version,\n )\n \n \n@@ -1196,21 +1194,6 @@ def test_csr_polynomial_expansion_index_overflow(\n pf.fit(X)\n return\n \n- # When `n_features>=65535`, `scipy.sparse.hstack` may not use the right\n- # dtype for representing indices and indptr if `n_features` is still\n- # small enough so that each block matrix's indices and indptr arrays\n- # can be represented with `np.int32`. We test `n_features==65535`\n- # since it is guaranteed to run into this bug.\n- if (\n- sp_version < parse_version(\"1.9.2\")\n- and n_features == 65535\n- and degree == 2\n- and not interaction_only\n- ): # pragma: no cover\n- msg = r\"In scipy versions `<1.9.2`, the function `scipy.sparse.hstack`\"\n- with pytest.raises(ValueError, match=msg):\n- X_trans = pf.fit_transform(X)\n- return\n X_trans = pf.fit_transform(X)\n \n expected_dtype = np.int64 if num_combinations > np.iinfo(np.int32).max else np.int32" }, { "filename": "sklearn/utils/fixes.py", "status": "modified", "additions": 0, "deletions": 33, "changes": 33, "patch": "@@ -14,7 +14,6 @@\n import scipy\n import scipy.sparse.linalg\n import scipy.stats\n-from scipy import optimize\n \n try:\n import pandas as pd\n@@ -81,38 +80,6 @@ def _sparse_linalg_cg(A, b, **kwargs):\n return scipy.sparse.linalg.cg(A, b, **kwargs)\n \n \n-# TODO : remove this when required minimum version of SciPy >= 1.9.0\n-def _yeojohnson_lambda(_neg_log_likelihood, x):\n- \"\"\"Estimate the optimal Yeo-Johnson transformation parameter (lambda).\n-\n- This function provides a compatibility workaround for versions of SciPy\n- older than 1.9.0, where `scipy.stats.yeojohnson` did not return\n- the estimated lambda directly.\n-\n- Parameters\n- ----------\n- _neg_log_likelihood : callable\n- A function that computes the negative log-likelihood of the Yeo-Johnson\n- transformation for a given lambda. Used only for SciPy versions < 1.9.0.\n-\n- x : array-like\n- Input data to estimate the Yeo-Johnson transformation parameter.\n-\n- Returns\n- -------\n- lmbda : float\n- The estimated lambda parameter for the Yeo-Johnson transformation.\n- \"\"\"\n- min_scipy_version = \"1.9.0\"\n-\n- if sp_version < parse_version(min_scipy_version):\n- # choosing bracket -2, 2 like for boxcox\n- return optimize.brent(_neg_log_likelihood, brack=(-2, 2))\n-\n- _, lmbda = scipy.stats.yeojohnson(x, lmbda=None)\n- return lmbda\n-\n-\n # TODO: Fuse the modern implementations of _sparse_min_max and _sparse_nan_min_max\n # into the public min_max_axis function when SciPy 1.11 is the minimum supported\n # version and delete the backport in the else branch below." } ], "reviews": [ { "id": 3402619956, "user": "user_d16337ec046b", "state": "APPROVED", "body": "LGTM thanks!", "submitted_at": "2025-10-31T05:14:18+00:00" }, { "id": 3402831615, "user": "user_fca2535bcd49", "state": "COMMENTED", "body": null, "submitted_at": "2025-10-31T07:09:23+00:00" }, { "id": 3402834771, "user": "user_fca2535bcd49", "state": "COMMENTED", "body": "Thanks for the PR! A few minor comments but otherwise LGTM.", "submitted_at": "2025-10-31T07:14:55+00:00" }, { "id": 3403131465, "user": "user_32e669a27072", "state": "COMMENTED", "body": null, "submitted_at": "2025-10-31T08:56:33+00:00" }, { "id": 3403132310, "user": "user_32e669a27072", "state": "COMMENTED", "body": null, "submitted_at": "2025-10-31T08:56:45+00:00" }, { "id": 3403132950, "user": "user_32e669a27072", "state": "COMMENTED", "body": null, "submitted_at": "2025-10-31T08:56:51+00:00" }, { "id": 3403135549, "user": "user_32e669a27072", "state": "COMMENTED", "body": null, "submitted_at": "2025-10-31T08:57:19+00:00" }, { "id": 3404703845, "user": "user_fca2535bcd49", "state": "COMMENTED", "body": null, "submitted_at": "2025-10-31T15:01:16+00:00" }, { "id": 3404705962, "user": "user_fca2535bcd49", "state": "APPROVED", "body": "LGTM, thanks! I enabled auto-merge.", "submitted_at": "2025-10-31T15:01:53+00:00" }, { "id": 3780764630, "user": "user_796cbd74caad", "state": "COMMENTED", "body": null, "submitted_at": "2026-02-10T18:25:12+00:00" }, { "id": 3783187546, "user": "user_d16337ec046b", "state": "COMMENTED", "body": null, "submitted_at": "2026-02-11T07:09:07+00:00" }, { "id": 3783567072, "user": "user_32e669a27072", "state": "COMMENTED", "body": null, "submitted_at": "2026-02-11T08:59:13+00:00" } ], "review_comments": [ { "id": 2480348303, "user": "user_fca2535bcd49", "body": "I would use `self.sparse_output` everywhere. I guess `use_sparse` was defined only to cover more easily scipy < 1.10 and scipy >= 1.10", "path": "sklearn/preprocessing/_polynomial.py", "line": null, "side": "RIGHT", "created_at": "2025-10-31T07:09:23+00:00" }, { "id": 2480350819, "user": "user_fca2535bcd49", "body": "I would use `extrapolate=self.bsplines_[0].extrapolate` in the call where `kwargs_extrapolate` is used.\n\nSimilar thing as previous comment, `kwargs_extrapolate` was to cover more easily scipy < 1.10 and scipy >= 1.10", "path": "sklearn/preprocessing/_polynomial.py", "line": null, "side": "RIGHT", "created_at": "2025-10-31T07:10:58+00:00" }, { "id": 2480352322, "user": "user_fca2535bcd49", "body": "I would remove >= 1.10 here and only say SciPy requires network access to get data", "path": "sklearn/conftest.py", "line": null, "side": "RIGHT", "created_at": "2025-10-31T07:11:50+00:00" }, { "id": 2480356718, "user": "user_fca2535bcd49", "body": "Maybe move this import at the top of the file?", "path": "sklearn/conftest.py", "line": null, "side": "RIGHT", "created_at": "2025-10-31T07:14:31+00:00" }, { "id": 2480588199, "user": "user_32e669a27072", "body": "Done", "path": "sklearn/preprocessing/_polynomial.py", "line": null, "side": "RIGHT", "created_at": "2025-10-31T08:56:33+00:00" }, { "id": 2480588954, "user": "user_32e669a27072", "body": "Done", "path": "sklearn/preprocessing/_polynomial.py", "line": null, "side": "RIGHT", "created_at": "2025-10-31T08:56:45+00:00" }, { "id": 2480589359, "user": "user_32e669a27072", "body": "Done", "path": "sklearn/conftest.py", "line": null, "side": "RIGHT", "created_at": "2025-10-31T08:56:51+00:00" }, { "id": 2480591620, "user": "user_32e669a27072", "body": "Done", "path": "sklearn/conftest.py", "line": null, "side": "RIGHT", "created_at": "2025-10-31T08:57:19+00:00" }, { "id": 2481719195, "user": "user_fca2535bcd49", "body": "```suggestion\n # SciPy requires network access to get data\n```", "path": "sklearn/conftest.py", "line": null, "side": "RIGHT", "created_at": "2025-10-31T15:01:16+00:00" }, { "id": 2789552835, "user": "user_796cbd74caad", "body": "I think `_neg_log_likelihood` can also be cleaned, since now it uses `stats.yeojohnson`", "path": "sklearn/preprocessing/_data.py", "line": 3592, "side": "RIGHT", "created_at": "2026-02-10T18:25:00+00:00" }, { "id": 2791742848, "user": "user_d16337ec046b", "body": "Good point, [USER_REDACTED] are you interested in doing this?", "path": "sklearn/preprocessing/_data.py", "line": 3592, "side": "RIGHT", "created_at": "2026-02-11T07:09:07+00:00" }, { "id": 2792112936, "user": "user_32e669a27072", "body": "Yes, thanks for the suggestion.", "path": "sklearn/preprocessing/_data.py", "line": 3592, "side": "RIGHT", "created_at": "2026-02-11T08:59:13+00:00" } ], "meta": { "languages": [ "py" ], "touches_tests": true, "review_state_summary": { "APPROVED": 2, "COMMENTED": 10 }, "meaningful_comment_count": 8, "has_approval": true, "has_changes_requested": false, "total_review_comments": 12 } } { "_id": "8b36bcdc692e09bb", "_schema_version": "1.0", "_cleaned_at": "2026-02-12T07:46:52.627996+00:00", "repo": "tiangolo/sqlmodel", "repo_url": "https://github.com/fastapi/sqlmodel", "license_name": "MIT License", "license_spdx": "MIT", "pr_number": 1688, "title": "⬆️ Migrate to uv", "body": null, "author": "user_73ddcba46ff3", "created_at": "2025-12-23T02:46:38+00:00", "merged_at": "2026-01-04T19:54:22+00:00", "base_branch": "main", "head_branch": "migrate-to-uv", "additions": 2617, "deletions": 106, "changed_files": 17, "files": [ { "filename": ".github/dependabot.yml", "status": "modified", "additions": 1, "deletions": 1, "changes": 2, "patch": "@@ -8,7 +8,7 @@ updates:\n commit-message:\n prefix: ⬆\n # Python\n- - package-ecosystem: \"pip\"\n+ - package-ecosystem: \"uv\"\n directory: \"/\"\n schedule:\n interval: \"daily\"" }, { "filename": ".github/workflows/build-docs.yml", "status": "modified", "additions": 6, "deletions": 11, "changes": 17, "patch": "@@ -8,10 +8,6 @@ on:\n - opened\n - synchronize\n \n-env:\n- UV_SYSTEM_PYTHON: 1\n-\n-\n jobs:\n changes:\n runs-on: ubuntu-latest\n@@ -32,8 +28,8 @@ jobs:\n - README.md\n - docs/**\n - docs_src/**\n- - requirements-docs.txt\n - pyproject.toml\n+ - uv.lock\n - mkdocs.yml\n - mkdocs.env.yml\n - .github/workflows/build-docs.yml\n@@ -54,25 +50,24 @@ jobs:\n - name: Set up Python\n uses: actions/setup-python@v6\n with:\n- python-version: \"3.11\"\n+ python-version-file: \".python-version\"\n - name: Setup uv\n uses: astral-sh/setup-uv@v7\n with:\n- version: \"0.4.15\"\n enable-cache: true\n cache-dependency-glob: |\n- requirements**.txt\n pyproject.toml\n+ uv.lock\n - name: Install docs extras\n- run: uv pip install -r requirements-docs.txt\n+ run: uv sync --locked --no-dev --group docs\n - uses: actions/cache@v5\n with:\n key: mkdocs-cards-${{ github.ref }}\n path: .cache\n - name: Verify README\n- run: python ./scripts/docs.py verify-readme\n+ run: uv run ./scripts/docs.py verify-readme\n - name: [NAME_REDACTED]\n- run: python ./scripts/docs.py build\n+ run: uv run ./scripts/docs.py build\n - uses: actions/upload-artifact@v6\n with:\n name: docs-site" }, { "filename": ".github/workflows/deploy-docs.yml", "status": "modified", "additions": 6, "deletions": 10, "changes": 16, "patch": "@@ -12,9 +12,6 @@ permissions:\n pull-requests: write\n statuses: write\n \n-env:\n- UV_SYSTEM_PYTHON: 1\n-\n jobs:\n deploy-docs:\n runs-on: ubuntu-latest\n@@ -27,19 +24,18 @@ jobs:\n - name: Set up Python\n uses: actions/setup-python@v6\n with:\n- python-version: \"3.11\"\n+ python-version-file: \".python-version\"\n - name: Setup uv\n uses: astral-sh/setup-uv@v7\n with:\n- version: \"0.4.15\"\n enable-cache: true\n cache-dependency-glob: |\n- requirements**.txt\n pyproject.toml\n+ uv.lock\n - name: [NAME_REDACTED] dependencies\n- run: uv pip install -r requirements-github-actions.txt\n+ run: uv sync --locked --no-dev --group github-actions\n - name: [NAME_REDACTED] Pending\n- run: python ./scripts/deploy_docs_status.py\n+ run: uv run ./scripts/deploy_docs_status.py\n env:\n GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}\n COMMIT_SHA: ${{ github.event.workflow_run.head_sha }}\n@@ -70,14 +66,14 @@ jobs:\n command: pages deploy ./site --project-name=${{ env.PROJECT_NAME }} --branch=${{ env.BRANCH }}\n - name: [NAME_REDACTED] Error\n if: failure()\n- run: python ./scripts/deploy_docs_status.py\n+ run: uv run ./scripts/deploy_docs_status.py\n env:\n GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}\n COMMIT_SHA: ${{ github.event.workflow_run.head_sha }}\n RUN_ID: ${{ github.run_id }}\n STATE: \"error\"\n - name: [NAME_REDACTED]\n- run: python ./scripts/deploy_docs_status.py\n+ run: uv run ./scripts/deploy_docs_status.py\n env:\n GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}\n DEPLOY_URL: ${{ steps.deploy.outputs.deployment-url }}" }, { "filename": ".github/workflows/pre-commit.yml", "status": "modified", "additions": 2, "deletions": 5, "changes": 7, "patch": "@@ -40,18 +40,15 @@ jobs:\n - name: Set up Python\n uses: actions/setup-python@v6\n with:\n- python-version: \"3.14\"\n+ python-version-file: \".python-version\"\n - name: Setup uv\n uses: astral-sh/setup-uv@v7\n with:\n cache-dependency-glob: |\n- requirements**.txt\n pyproject.toml\n uv.lock\n - name: [NAME_REDACTED]\n- run: |\n- uv venv\n- uv pip install -r requirements.txt\n+ run: uv sync --locked\n - name: Run prek - pre-commit\n id: precommit\n run: uvx prek run --from-ref origin/${GITHUB_BASE_REF} --to-ref HEAD --show-diff-on-failure" }, { "filename": ".github/workflows/publish.yml", "status": "modified", "additions": 10, "deletions": 5, "changes": 15, "patch": "@@ -21,17 +21,22 @@ jobs:\n - sqlmodel-slim\n permissions:\n id-token: write\n+ contents: read\n steps:\n+ - name: [NAME_REDACTED] context\n+ env:\n+ GITHUB_CONTEXT: ${{ toJson(github) }}\n+ run: echo \"$GITHUB_CONTEXT\"\n - uses: actions/checkout@v6\n - name: Set up Python\n uses: actions/setup-python@v6\n with:\n- python-version: \"3.11\"\n- - name: Install build dependencies\n- run: pip install build\n+ python-version-file: \".python-version\"\n+ - name: Install uv\n+ uses: astral-sh/setup-uv@v7\n - name: Build distribution\n+ run: uv build\n env:\n TIANGOLO_BUILD_PACKAGE: ${{ matrix.package }}\n- run: python -m build\n - name: Publish\n- uses: pypa/gh-action-pypi-publish@v1.13.0\n+ run: uv publish" }, { "filename": ".github/workflows/smokeshow.yml", "status": "modified", "additions": 4, "deletions": 7, "changes": 11, "patch": "@@ -8,24 +8,21 @@ on:\n permissions:\n statuses: write\n \n-env:\n- UV_SYSTEM_PYTHON: 1\n-\n jobs:\n smokeshow:\n runs-on: ubuntu-latest\n steps:\n - uses: actions/checkout@v6\n - uses: actions/setup-python@v6\n with:\n- python-version: '3.13'\n+ python-version-file: \".python-version\"\n - name: Setup uv\n uses: astral-sh/setup-uv@v7\n with:\n cache-dependency-glob: |\n- requirements**.txt\n pyproject.toml\n- - run: uv pip install -r requirements-github-actions.txt\n+ uv.lock\n+ - run: uv sync --locked --no-dev --group github-actions\n - uses: actions/download-artifact@v7\n with:\n name: coverage-html\n@@ -36,7 +33,7 @@ jobs:\n - name: Upload coverage to Smokeshow\n run: |\n for i in 1 2 3 4 5; do\n- if smokeshow upload htmlcov; then\n+ if uv run smokeshow upload htmlcov; then\n echo \"Smokeshow upload success!\"\n break\n fi" }, { "filename": ".github/workflows/test-redistribute.yml", "status": "modified", "additions": 2, "deletions": 2, "changes": 4, "patch": "@@ -26,7 +26,7 @@ jobs:\n - name: Set up Python\n uses: actions/setup-python@v6\n with:\n- python-version: \"3.10\"\n+ python-version-file: \".python-version\"\n - name: Install build dependencies\n run: pip install build\n - name: Build source distribution\n@@ -40,7 +40,7 @@ jobs:\n - name: Install test dependencies\n run: |\n cd dist/sqlmodel*/\n- pip install -r requirements-tests.txt\n+ pip install --group tests --editable .\n env:\n TIANGOLO_BUILD_PACKAGE: ${{ matrix.package }}\n - name: Run source distribution tests" }, { "filename": ".github/workflows/test.yml", "status": "modified", "additions": 12, "deletions": 12, "changes": 24, "patch": "@@ -19,7 +19,7 @@ on:\n - cron: \"0 0 * * 1\"\n \n env:\n- UV_SYSTEM_PYTHON: 1\n+ UV_NO_SYNC: true\n \n jobs:\n test:\n@@ -42,6 +42,8 @@ jobs:\n python-version: \"3.13\"\n fail-fast: false\n runs-on: ${{ matrix.os }}\n+ env:\n+ UV_PYTHON: ${{ matrix.python-version }}\n steps:\n - uses: actions/checkout@v6\n - name: Set up Python\n@@ -51,22 +53,21 @@ jobs:\n - name: Setup uv\n uses: astral-sh/setup-uv@v7\n with:\n- version: \"0.4.15\"\n enable-cache: true\n cache-dependency-glob: |\n- requirements**.txt\n pyproject.toml\n+ uv.lock\n # Allow debugging with tmate\n - name: Setup tmate session\n uses: mxschmitt/action-tmate@v3\n if: ${{ github.event_name == 'workflow_dispatch' && github.event.inputs.debug_enabled == 'true' }}\n with:\n limit-access-to-actor: true\n - name: [NAME_REDACTED]\n- run: uv pip install -r requirements-tests.txt\n+ run: uv sync --locked --no-dev --group tests\n - run: mkdir coverage\n - name: Test\n- run: bash scripts/test.sh\n+ run: uv run bash scripts/test.sh\n env:\n COVERAGE_FILE: coverage/.coverage.${{ runner.os }}-py${{ matrix.python-version }}-${{ matrix.pydantic-version }}\n CONTEXT: ${{ runner.os }}-py${{ matrix.python-version }}\n@@ -85,33 +86,32 @@ jobs:\n - uses: actions/checkout@v6\n - uses: actions/setup-python@v6\n with:\n- python-version: '3.13'\n+ python-version-file: \".python-version\"\n - name: Setup uv\n uses: astral-sh/setup-uv@v7\n with:\n- version: \"0.4.15\"\n enable-cache: true\n cache-dependency-glob: |\n- requirements**.txt\n pyproject.toml\n+ uv.lock\n - name: Get coverage files\n uses: actions/download-artifact@v7\n with:\n pattern: coverage-*\n path: coverage\n merge-multiple: true\n - name: [NAME_REDACTED]\n- run: uv pip install -r requirements-tests.txt\n+ run: uv sync --locked --no-dev --group tests\n - run: ls -la coverage\n- - run: coverage combine coverage\n- - run: coverage html --title \"Coverage for ${{ github.sha }}\"\n+ - run: uv run coverage combine coverage\n+ - run: uv run coverage html --title \"Coverage for ${{ github.sha }}\"\n - name: Store coverage HTML\n uses: actions/upload-artifact@v6\n with:\n name: coverage-html\n path: htmlcov\n include-hidden-files: true\n- - run: coverage report --fail-under=99\n+ - run: uv run coverage report --fail-under=99\n \n # https://github.com/marketplace/actions/alls-green#why\n alls-green: # This job does nothing and is only used for the branch protection" }, { "filename": ".python-version", "status": "added", "additions": 1, "deletions": 0, "changes": 1, "patch": "@@ -0,0 +1 @@\n+3.9" }, { "filename": "docs/contributing.md", "status": "modified", "additions": 3, "deletions": 7, "changes": 10, "patch": "@@ -6,18 +6,14 @@ First, you might want to see the basic ways to [help SQLModel and get help](help\n \n If you already cloned the sqlmodel repository and you want to deep dive in the code, here are some guidelines to set up your environment.\n \n-### [NAME_REDACTED]\n+### [NAME_REDACTED] `uv`\n \n-Follow the instructions to create and activate a [virtual environment](virtual-environments.md){.internal-link target=_blank} for the internal code of `sqlmodel`.\n-\n-### [NAME_REDACTED] `pip`\n-\n-After activating the environment, install the required packages:\n+Create a virtual environment and install the required packages in one command:\n \n
        \n \n ```console\n-$ pip install -r requirements.txt\n+$ uv sync\n \n ---> 100%\n ```" }, { "filename": "pyproject.toml", "status": "modified", "additions": 43, "deletions": 2, "changes": 45, "patch": "@@ -47,6 +47,48 @@ Repository = \"https://github.com/fastapi/sqlmodel\"\n Issues = \"https://github.com/fastapi/sqlmodel/issues\"\n Changelog = \"https://sqlmodel.tiangolo.com/release-notes/\"\n \n+[dependency-groups]\n+dev = [\n+ { include-group = \"docs\" },\n+ { include-group = \"tests\" },\n+ \"prek>=0.2.24,<1.0.0\",\n+]\n+docs = [\n+ \"black>=22.10\",\n+ \"cairosvg==2.8.2\",\n+ \"griffe-typingdoc==0.3.0\",\n+ \"griffe-warnings-deprecated==1.1.0\",\n+ \"markdown-include-variants==0.0.8\",\n+ \"mdx-include>=1.4.1,<2.0.0\",\n+ \"mkdocs-macros-plugin==1.5.0\",\n+ \"mkdocs-material==9.7.1\",\n+ \"mkdocs-redirects>=1.2.1,<1.3.0\",\n+ \"mkdocstrings[python]==0.30.1\",\n+ \"pillow==11.3.0\",\n+ \"pyyaml>=5.3.1,<7.0.0\",\n+ \"typer==0.21.0\",\n+]\n+github-actions = [\n+ \"httpx>=0.27.0,<0.29.0\",\n+ \"pydantic>=2.5.3,<3.0.0\",\n+ \"pydantic-settings>=2.1.0,<3.0.0\",\n+ \"pygithub>=2.3.0,<3.0.0\",\n+ \"smokeshow>=0.5.0\",\n+]\n+tests = [\n+ \"black>=22.10\",\n+ \"coverage[toml]>=6.2,<8.0\",\n+ \"dirty-equals==0.11\",\n+ \"fastapi>=0.103.2,<0.129.0\",\n+ \"httpx==0.28.1\",\n+ \"jinja2==3.1.6\",\n+ \"mypy==1.19.1\",\n+ \"pre-commit>=2.17.0,<5.0.0\",\n+ \"pytest>=7.0.1,<9.0.0\",\n+ \"ruff==0.14.10\",\n+ \"typing-extensions==4.15.0\",\n+]\n+\n [tool.pdm]\n version = { source = \"file\", path = \"sqlmodel/__init__.py\" }\n distribution = true\n@@ -55,10 +97,9 @@ distribution = true\n source-includes = [\n \"tests/\",\n \"docs_src/\",\n- \"requirements*.txt\",\n \"scripts/\",\n \"sqlmodel/sql/expression.py.jinja2\",\n- ]\n+]\n \n [tool.tiangolo._internal-slim-build.packages.sqlmodel-slim.project]\n name = \"sqlmodel-slim\"" }, { "filename": "requirements-docs-tests.txt", "status": "removed", "additions": 0, "deletions": 2, "changes": 2, "patch": "@@ -1,2 +0,0 @@\n-# For mkdocstrings and code generator using templates\n-black >=22.10" }, { "filename": "requirements-docs.txt", "status": "removed", "additions": 0, "deletions": 19, "changes": 19, "patch": "@@ -1,19 +0,0 @@\n--e .\n--r requirements-docs-tests.txt\n-mkdocs-material==9.7.1\n-mdx-include >=1.4.1,<2.0.0\n-mkdocs-redirects>=1.2.1,<1.3.0\n-pyyaml >=5.3.1,<7.0.0\n-# For Material for MkDocs, Chinese search\n-# jieba==0.42.1\n-# For image processing by [NAME_REDACTED]\n-pillow==11.3.0\n-# For image processing by [NAME_REDACTED]\n-cairosvg==2.8.2\n-mkdocstrings[python]==0.30.1\n-griffe-typingdoc==0.3.0\n-griffe-warnings-deprecated==1.1.0\n-# For griffe, it formats with black\n-typer == 0.21.0\n-mkdocs-macros-plugin==1.5.0\n-markdown-include-variants==0.0.8" }, { "filename": "requirements-github-actions.txt", "status": "removed", "additions": 0, "deletions": 5, "changes": 5, "patch": "@@ -1,5 +0,0 @@\n-PyGithub>=2.3.0,<3.0.0\n-pydantic>=2.5.3,<3.0.0\n-pydantic-settings>=2.1.0,<3.0.0\n-httpx>=0.27.0,<0.29.0\n-smokeshow" }, { "filename": "requirements-tests.txt", "status": "removed", "additions": 0, "deletions": 12, "changes": 12, "patch": "@@ -1,12 +0,0 @@\n--e .\n--r requirements-docs-tests.txt\n-pytest >=7.0.1,<9.0.0\n-coverage[toml] >=6.2,<8.0\n-mypy ==1.19.1\n-ruff ==0.14.10\n-# For FastAPI tests\n-fastapi >=0.103.2,<0.129.0\n-httpx ==0.28.1\n-dirty-equals ==0.11\n-jinja2 ==3.1.6\n-typing-extensions ==4.15.0" }, { "filename": "requirements.txt", "status": "removed", "additions": 0, "deletions": 6, "changes": 6, "patch": "@@ -1,6 +0,0 @@\n--e .\n-\n--r requirements-tests.txt\n--r requirements-docs.txt\n-\n-prek>=0.2.24,<1.0.0" }, { "filename": "uv.lock", "status": "modified", "additions": 2527, "deletions": 0, "changes": 2527, "patch": null } ], "reviews": [ { "id": 3606527907, "user": "user_cb25746e1d00", "state": "APPROVED", "body": null, "submitted_at": "2025-12-23T04:45:40+00:00" }, { "id": 3625147414, "user": "user_2a237e38e06b", "state": "APPROVED", "body": "Excellent, thank you! 🙌 🚀", "submitted_at": "2026-01-04T19:49:57+00:00" } ], "review_comments": [ { "id": 2659886780, "user": "user_2a237e38e06b", "body": "```suggestion\n if uv run smokeshow upload htmlcov; then\n```", "path": ".github/workflows/smokeshow.yml", "line": null, "side": "RIGHT", "created_at": "2026-01-04T19:48:43+00:00" } ], "meta": { "languages": [ "lock", "md", "toml", "txt", "yml" ], "touches_tests": false, "review_state_summary": { "APPROVED": 2 }, "meaningful_comment_count": 1, "has_approval": true, "has_changes_requested": false, "total_review_comments": 1 } } { "_id": "9b5e2dca6eb16dee", "_schema_version": "1.0", "_cleaned_at": "2026-02-12T07:46:52.627996+00:00", "repo": "tiangolo/sqlmodel", "repo_url": "https://github.com/fastapi/sqlmodel", "license_name": "MIT License", "license_spdx": "MIT", "pr_number": 1578, "title": "⬆️ Add support for Python 3.14", "body": "Adding support for Python 3.14 by [NAME_REDACTED], adding the classifier, and fixing a compat issue with Pydantic.\n\nSince https://github.com/[USER_REDACTED]ntic/pydantic/pull/11991 (Pydantic 2.12.0 for Python 3.14), `annotations` are retrieved [differently](https://github.com/[USER_REDACTED]ntic/pydantic/pull/11991/files#diff-ea75a1ef1da6bb38913477e979605f6a05e2ffe8c28fe47d9b798c89ba436c7c). We need to do the same, or will end up with an empty `dict` in `class_dict[\"annotations\"]`, which will ultimately result in a `pydantic.errors.PydanticUserError` stating that a certain field requires a type annotation.\n\nThe implementation here should be bwd-compat for previous versions of Pydantic v2 (tested locally).\n\nNote that Pydantic v1 won't be supported on Python 3.14: https://github.com/[USER_REDACTED]ntic/pydantic/issues/11613#issuecomment-3242513660", "author": "user_84458f05cf3c", "created_at": "2025-09-26T12:41:15+00:00", "merged_at": "2025-10-08T16:26:34+00:00", "base_branch": "main", "head_branch": "feat/py314", "additions": 21, "deletions": 4, "changed_files": 3, "files": [ { "filename": ".github/workflows/test.yml", "status": "modified", "additions": 5, "deletions": 3, "changes": 8, "patch": "@@ -26,9 +26,8 @@ jobs:\n strategy:\n matrix:\n os: [ ubuntu-latest, windows-latest, macos-latest ]\n- python-version: [ \"3.13\" ]\n+ python-version: [ \"3.14\" ]\n pydantic-version:\n- - pydantic-v1\n - pydantic-v2\n include:\n - os: macos-latest\n@@ -47,7 +46,10 @@ jobs:\n python-version: \"3.12\"\n pydantic-version: pydantic-v1\n - os: ubuntu-latest\n- python-version: \"3.12\"\n+ python-version: \"3.13\"\n+ pydantic-version: pydantic-v1\n+ - os: macos-latest\n+ python-version: \"3.13\"\n pydantic-version: pydantic-v2\n fail-fast: false\n runs-on: ${{ matrix.os }}" }, { "filename": "pyproject.toml", "status": "modified", "additions": 1, "deletions": 0, "changes": 1, "patch": "@@ -26,6 +26,7 @@ classifiers = [\n \"[NAME_REDACTED] :: Python :: 3.11\",\n \"[NAME_REDACTED] :: Python :: 3.12\",\n \"[NAME_REDACTED] :: Python :: 3.13\",\n+ \"[NAME_REDACTED] :: Python :: 3.14\",\n \"Topic :: Database\",\n \"Topic :: Database :: [NAME_REDACTED]/Servers\",\n \"Topic :: Internet\"," }, { "filename": "sqlmodel/_compat.py", "status": "modified", "additions": 15, "deletions": 1, "changes": 16, "patch": "@@ -1,3 +1,4 @@\n+import sys\n import types\n from contextlib import contextmanager\n from contextvars import ContextVar\n@@ -123,7 +124,20 @@ def init_pydantic_private_attrs(new_object: InstanceOrType[\"SQLModel\"]) -> None:\n object.__setattr__(new_object, \"__pydantic_private__\", None)\n \n def get_annotations(class_dict: Dict[str, Any]) -> Dict[str, Any]:\n- return class_dict.get(\"__annotations__\", {}) # type: ignore[no-any-return]\n+ raw_annotations: Dict[str, Any] = class_dict.get(\"__annotations__\", {})\n+ if sys.version_info >= (3, 14) and \"__annotations__\" not in class_dict:\n+ # See https://github.com/[USER_REDACTED]ntic/pydantic/pull/11991\n+ from annotationlib import (\n+ Format,\n+ call_annotate_function,\n+ get_annotate_from_class_namespace,\n+ )\n+\n+ if annotate := get_annotate_from_class_namespace(class_dict):\n+ raw_annotations = call_annotate_function(\n+ annotate, format=Format.FORWARDREF\n+ )\n+ return raw_annotations\n \n def is_table_model_class(cls: Type[Any]) -> bool:\n config = getattr(cls, \"model_config\", {})" } ], "reviews": [ { "id": 3315087505, "user": "user_84458f05cf3c", "state": "COMMENTED", "body": null, "submitted_at": "2025-10-08T14:24:35+00:00" }, { "id": 3315636427, "user": "user_2a237e38e06b", "state": "APPROVED", "body": "Nice! And now we get to use `annotationlib`! 😎 🚀 \n\nI reviewed it thoroughly, read all the `annotationlib` docs and best practices document, and the implementation in Pydatnic. It all looks good to me. 🎉", "submitted_at": "2025-10-08T16:26:05+00:00" } ], "review_comments": [ { "id": 2414049442, "user": "user_84458f05cf3c", "body": "Note that https://github.com/fastapi/sqlmodel/discussions/1594 proposes an alternative implementation, using `class_dict.get(\"__annotate_func__\")`", "path": "sqlmodel/_compat.py", "line": 127, "side": "RIGHT", "created_at": "2025-10-08T14:24:35+00:00" } ], "meta": { "languages": [ "py", "toml", "yml" ], "touches_tests": false, "review_state_summary": { "COMMENTED": 1, "APPROVED": 1 }, "meaningful_comment_count": 1, "has_approval": true, "has_changes_requested": false, "total_review_comments": 1 } } { "_id": "49742a620b24e5d1", "_schema_version": "1.0", "_cleaned_at": "2026-02-12T07:46:52.643621+00:00", "repo": "tiangolo/sqlmodel", "repo_url": "https://github.com/fastapi/sqlmodel", "license_name": "MIT License", "license_spdx": "MIT", "pr_number": 1577, "title": "🐛 Fix `alias` support for Pydantic v2", "body": "## [NAME_REDACTED] PR fixes the Field(alias=\"...\") functionality that was broken in Pydantic v2 while maintaining full backward compatibility with Pydantic v1.\n\n## [NAME_REDACTED] v2, the `alias` parameter in SQLModel's `Field` function was not working correctly for validation and serialization. The issue was that Pydantic v2 requires explicit `validation_alias` and `serialization_alias` parameters, but SQLModel wasn't automatically propagating the `alias` value to these parameters.\n\n## Solution\n\n### Changes Made:\n\n1. **[NAME_REDACTED] function**:\n - Added `validation_alias` and `serialization_alias` parameters\n - Implemented version-specific parameter handling\n\n2. **Automatic alias propagation**:\n - ~~Modified `post_init_field_info` in `_compat.py` to automatically set `validation_alias` and `serialization_alias` from `alias` when not explicitly provided (Pydantic v2 only)~~ UPD YuriiMotov: updated it to just using `alias` value for `validation_alias` and `serialization_alias` if they are not specified directly\n\n3. **Backward compatibility**:\n - Filter out v2-only parameters from FieldInfo in Pydantic v1\n - Raise clear RuntimeError when v2 features are used with v1\n - Conditional test execution based on Pydantic version\n\n4. **Comprehensive testing**:\n - Added extensive test coverage for both Pydantic v1 and v2\n - Tests automatically skip v2-specific features when running with v1\n - Covers all alias scenarios including edge cases\n \n[NAME_REDACTED]. This is purely a bug fix with backward compatibility maintained.\n\n[NAME_REDACTED] #1536", "author": "user_6df47fc31203", "created_at": "2025-09-25T22:56:03+00:00", "merged_at": "2025-12-23T20:57:43+00:00", "base_branch": "main", "head_branch": "issue-1536-alias-pydantic-v2", "additions": 318, "deletions": 33, "changed_files": 2, "files": [ { "filename": "sqlmodel/main.py", "status": "modified", "additions": 61, "deletions": 33, "changes": 94, "patch": "@@ -218,6 +218,8 @@ def Field(\n *,\n default_factory: Optional[NoArgAnyCallable] = None,\n alias: Optional[str] = None,\n+ validation_alias: Optional[str] = None,\n+ serialization_alias: Optional[str] = None,\n title: Optional[str] = None,\n description: Optional[str] = None,\n exclude: Union[\n@@ -263,6 +265,8 @@ def Field(\n *,\n default_factory: Optional[NoArgAnyCallable] = None,\n alias: Optional[str] = None,\n+ validation_alias: Optional[str] = None,\n+ serialization_alias: Optional[str] = None,\n title: Optional[str] = None,\n description: Optional[str] = None,\n exclude: Union[\n@@ -317,6 +321,8 @@ def Field(\n *,\n default_factory: Optional[NoArgAnyCallable] = None,\n alias: Optional[str] = None,\n+ validation_alias: Optional[str] = None,\n+ serialization_alias: Optional[str] = None,\n title: Optional[str] = None,\n description: Optional[str] = None,\n exclude: Union[\n@@ -352,6 +358,8 @@ def Field(\n *,\n default_factory: Optional[NoArgAnyCallable] = None,\n alias: Optional[str] = None,\n+ validation_alias: Optional[str] = None,\n+ serialization_alias: Optional[str] = None,\n title: Optional[str] = None,\n description: Optional[str] = None,\n exclude: Union[\n@@ -390,43 +398,63 @@ def Field(\n schema_extra: Optional[Dict[str, Any]] = None,\n ) -> Any:\n current_schema_extra = schema_extra or {}\n+ # Extract possible alias settings from schema_extra so we can control precedence\n+ schema_validation_alias = current_schema_extra.pop(\"validation_alias\", None)\n+ schema_serialization_alias = current_schema_extra.pop(\"serialization_alias\", None)\n+ field_info_kwargs = {\n+ \"alias\": alias,\n+ \"title\": title,\n+ \"description\": description,\n+ \"exclude\": exclude,\n+ \"include\": include,\n+ \"const\": const,\n+ \"gt\": gt,\n+ \"ge\": ge,\n+ \"lt\": lt,\n+ \"le\": le,\n+ \"multiple_of\": multiple_of,\n+ \"max_digits\": max_digits,\n+ \"decimal_places\": decimal_places,\n+ \"min_items\": min_items,\n+ \"max_items\": max_items,\n+ \"unique_items\": unique_items,\n+ \"min_length\": min_length,\n+ \"max_length\": max_length,\n+ \"allow_mutation\": allow_mutation,\n+ \"regex\": regex,\n+ \"discriminator\": discriminator,\n+ \"repr\": repr,\n+ \"primary_key\": primary_key,\n+ \"foreign_key\": foreign_key,\n+ \"ondelete\": ondelete,\n+ \"unique\": unique,\n+ \"nullable\": nullable,\n+ \"index\": index,\n+ \"sa_type\": sa_type,\n+ \"sa_column\": sa_column,\n+ \"sa_column_args\": sa_column_args,\n+ \"sa_column_kwargs\": sa_column_kwargs,\n+ **current_schema_extra,\n+ }\n+ if IS_PYDANTIC_V2:\n+ # explicit params > schema_extra > alias propagation\n+ field_info_kwargs[\"validation_alias\"] = (\n+ validation_alias or schema_validation_alias or alias\n+ )\n+ field_info_kwargs[\"serialization_alias\"] = (\n+ serialization_alias or schema_serialization_alias or alias\n+ )\n+ else:\n+ if validation_alias or schema_validation_alias is not None:\n+ raise RuntimeError(\"validation_alias is not supported in Pydantic v1\")\n+ if serialization_alias or schema_serialization_alias is not None:\n+ raise RuntimeError(\"serialization_alias is not supported in Pydantic v1\")\n field_info = FieldInfo(\n default,\n default_factory=default_factory,\n- alias=alias,\n- title=title,\n- description=description,\n- exclude=exclude,\n- include=include,\n- const=const,\n- gt=gt,\n- ge=ge,\n- lt=lt,\n- le=le,\n- multiple_of=multiple_of,\n- max_digits=max_digits,\n- decimal_places=decimal_places,\n- min_items=min_items,\n- max_items=max_items,\n- unique_items=unique_items,\n- min_length=min_length,\n- max_length=max_length,\n- allow_mutation=allow_mutation,\n- regex=regex,\n- discriminator=discriminator,\n- repr=repr,\n- primary_key=primary_key,\n- foreign_key=foreign_key,\n- ondelete=ondelete,\n- unique=unique,\n- nullable=nullable,\n- index=index,\n- sa_type=sa_type,\n- sa_column=sa_column,\n- sa_column_args=sa_column_args,\n- sa_column_kwargs=sa_column_kwargs,\n- **current_schema_extra,\n+ **field_info_kwargs,\n )\n+\n post_init_field_info(field_info)\n return field_info" }, { "filename": "tests/test_aliases.py", "status": "added", "additions": 257, "deletions": 0, "changes": 257, "patch": "@@ -0,0 +1,257 @@\n+from typing import Type, Union\n+\n+import pytest\n+from pydantic import BaseModel, ValidationError\n+from pydantic import Field as PField\n+from sqlmodel import Field, SQLModel\n+from sqlmodel._compat import IS_PYDANTIC_V2\n+\n+from tests.conftest import needs_pydanticv1, needs_pydanticv2\n+\n+\"\"\"\n+Alias tests for SQLModel and Pydantic compatibility\n+\"\"\"\n+\n+\n+class PydanticUser(BaseModel):\n+ full_name: str = PField(alias=\"fullName\")\n+\n+\n+class SQLModelUser(SQLModel):\n+ full_name: str = Field(alias=\"fullName\")\n+\n+\n+# Models with config (validate_by_name=True)\n+if IS_PYDANTIC_V2:\n+\n+ class PydanticUserWithConfig(PydanticUser):\n+ model_config = {\"validate_by_name\": True}\n+\n+ class SQLModelUserWithConfig(SQLModelUser):\n+ model_config = {\"validate_by_name\": True}\n+\n+else:\n+\n+ class PydanticUserWithConfig(PydanticUser):\n+ class Config:\n+ allow_population_by_field_name = True\n+\n+ class SQLModelUserWithConfig(SQLModelUser):\n+ class Config:\n+ allow_population_by_field_name = True\n+\n+\n+[USER_REDACTED].mark.parametrize(\"model\", [PydanticUser, SQLModelUser])\n+def test_create_with_field_name(model: Union[Type[PydanticUser], Type[SQLModelUser]]):\n+ with pytest.raises(ValidationError):\n+ model(full_name=\"Alice\")\n+\n+\n+[USER_REDACTED].mark.parametrize(\"model\", [PydanticUserWithConfig, SQLModelUserWithConfig])\n+def test_create_with_field_name_with_config(\n+ model: Union[Type[PydanticUserWithConfig], Type[SQLModelUserWithConfig]],\n+):\n+ user = model(full_name=\"Alice\")\n+ assert user.full_name == \"Alice\"\n+\n+\n+[USER_REDACTED].mark.parametrize(\n+ \"model\",\n+ [PydanticUser, SQLModelUser, PydanticUserWithConfig, SQLModelUserWithConfig],\n+)\n+def test_create_with_alias(\n+ model: Union[\n+ Type[PydanticUser],\n+ Type[SQLModelUser],\n+ Type[PydanticUserWithConfig],\n+ Type[SQLModelUserWithConfig],\n+ ],\n+):\n+ user = model(fullName=\"Bob\") # using alias\n+ assert user.full_name == \"Bob\"\n+\n+\n+[USER_REDACTED].mark.parametrize(\"model\", [PydanticUserWithConfig, SQLModelUserWithConfig])\n+def test_create_with_both_prefers_alias(\n+ model: Union[Type[PydanticUserWithConfig], Type[SQLModelUserWithConfig]],\n+):\n+ user = model(full_name=\"IGNORED\", fullName=\"Charlie\")\n+ assert user.full_name == \"Charlie\" # alias should take precedence\n+\n+\n+[USER_REDACTED].mark.parametrize(\"model\", [PydanticUser, SQLModelUser])\n+def test_dict_default_uses_field_names(\n+ model: Union[Type[PydanticUser], Type[SQLModelUser]],\n+):\n+ user = model(fullName=\"Dana\")\n+ if IS_PYDANTIC_V2 or isinstance(user, SQLModel):\n+ data = user.model_dump()\n+ else:\n+ data = user.dict()\n+ assert \"full_name\" in data\n+ assert \"fullName\" not in data\n+ assert data[\"full_name\"] == \"Dana\"\n+\n+\n+[USER_REDACTED].mark.parametrize(\"model\", [PydanticUser, SQLModelUser])\n+def test_dict_by_alias_uses_aliases(\n+ model: Union[Type[PydanticUser], Type[SQLModelUser]],\n+):\n+ user = model(fullName=\"Dana\")\n+ if IS_PYDANTIC_V2 or isinstance(user, SQLModel):\n+ data = user.model_dump(by_alias=True)\n+ else:\n+ data = user.dict(by_alias=True)\n+ assert \"fullName\" in data\n+ assert \"full_name\" not in data\n+ assert data[\"fullName\"] == \"Dana\"\n+\n+\n+[USER_REDACTED].mark.parametrize(\"model\", [PydanticUser, SQLModelUser])\n+def test_json_by_alias(\n+ model: Union[Type[PydanticUser], Type[SQLModelUser]],\n+):\n+ user = model(fullName=\"Frank\")\n+ if IS_PYDANTIC_V2:\n+ json_data = user.model_dump_json(by_alias=True)\n+ else:\n+ json_data = user.json(by_alias=True)\n+ assert ('\"fullName\":\"Frank\"' in json_data) or ('\"fullName\": \"Frank\"' in json_data)\n+ assert \"full_name\" not in json_data\n+\n+\n+if IS_PYDANTIC_V2:\n+\n+ class PydanticUserV2(BaseModel):\n+ first_name: str = PField(\n+ validation_alias=\"firstName\", serialization_alias=\"f_name\"\n+ )\n+\n+ class SQLModelUserV2(SQLModel):\n+ first_name: str = Field(\n+ validation_alias=\"firstName\", serialization_alias=\"f_name\"\n+ )\n+else:\n+ # Dummy classes for Pydantic v1 to prevent import errors\n+ PydanticUserV2 = None\n+ SQLModelUserV2 = None\n+\n+\n+[USER_REDACTED]_pydanticv1\n+def test_validation_alias_runtimeerror_pydantic_v1():\n+ with pytest.raises(\n+ RuntimeError, match=\"validation_alias is not supported in Pydantic v1\"\n+ ):\n+ Field(validation_alias=\"foo\")\n+\n+\n+[USER_REDACTED]_pydanticv1\n+def test_serialization_alias_runtimeerror_pydantic_v1():\n+ with pytest.raises(\n+ RuntimeError, match=\"serialization_alias is not supported in Pydantic v1\"\n+ ):\n+ Field(serialization_alias=\"bar\")\n+\n+\n+[USER_REDACTED]_pydanticv2\n+[USER_REDACTED].mark.parametrize(\"model\", [PydanticUserV2, SQLModelUserV2])\n+def test_create_with_validation_alias(\n+ model: Union[Type[PydanticUserV2], Type[SQLModelUserV2]],\n+):\n+ user = model(firstName=\"John\")\n+ assert user.first_name == \"John\"\n+\n+\n+[USER_REDACTED]_pydanticv2\n+[USER_REDACTED].mark.parametrize(\"model\", [PydanticUserV2, SQLModelUserV2])\n+def test_serialize_with_serialization_alias(\n+ model: Union[Type[PydanticUserV2], Type[SQLModelUserV2]],\n+):\n+ user = model(firstName=\"Jane\")\n+ data = user.model_dump(by_alias=True)\n+ assert \"f_name\" in data\n+ assert \"firstName\" not in data\n+ assert \"first_name\" not in data\n+ assert data[\"f_name\"] == \"Jane\"\n+\n+\n+[USER_REDACTED]_pydanticv2\n+def test_schema_extra_validation_alias_sqlmodel_v2():\n+ class M(SQLModel):\n+ f: str = Field(schema_extra={\"validation_alias\": \"f_alias\"})\n+\n+ m = M.model_validate({\"f_alias\": \"asd\"})\n+ assert m.f == \"asd\"\n+\n+\n+[USER_REDACTED]_pydanticv2\n+def test_schema_extra_serialization_alias_sqlmodel_v2():\n+ class M(SQLModel):\n+ f: str = Field(schema_extra={\"serialization_alias\": \"f_out\"})\n+\n+ m = M(f=\"x\")\n+ data = m.model_dump(by_alias=True)\n+ assert \"f_out\" in data\n+ assert \"f\" not in data\n+ assert data[\"f_out\"] == \"x\"\n+\n+\n+[USER_REDACTED]_pydanticv1\n+def test_schema_extra_validation_alias_runtimeerror_pydantic_v1():\n+ with pytest.raises(\n+ RuntimeError, match=\"validation_alias is not supported in Pydantic v1\"\n+ ):\n+ Field(schema_extra={\"validation_alias\": \"x\"})\n+\n+\n+[USER_REDACTED]_pydanticv1\n+def test_schema_extra_serialization_alias_runtimeerror_pydantic_v1():\n+ with pytest.raises(\n+ RuntimeError, match=\"serialization_alias is not supported in Pydantic v1\"\n+ ):\n+ Field(schema_extra={\"serialization_alias\": \"y\"})\n+\n+\n+[USER_REDACTED]_pydanticv2\n+def test_alias_plus_validation_alias_prefers_validation_alias_sqlmodel_v2():\n+ class M(SQLModel):\n+ first_name: str = Field(alias=\"fullName\", validation_alias=\"v_name\")\n+\n+ m = M.model_validate({\"fullName\": \"A\", \"v_name\": \"B\"})\n+ assert m.first_name == \"B\"\n+\n+\n+[USER_REDACTED]_pydanticv2\n+def test_alias_plus_serialization_alias_prefers_serialization_alias_sqlmodel_v2():\n+ class M(SQLModel):\n+ first_name: str = Field(alias=\"fullName\", serialization_alias=\"f_name\")\n+\n+ m = M(fullName=\"Z\")\n+ data = m.model_dump(by_alias=True)\n+ assert \"f_name\" in data\n+ assert \"fullName\" not in data\n+ assert data[\"f_name\"] == \"Z\"\n+\n+\n+[USER_REDACTED]_pydanticv2\n+def test_alias_generator_works_sqlmodel_v2():\n+ class M(SQLModel):\n+ model_config = {\"alias_generator\": lambda s: \"gen_\" + s}\n+ f: str = Field()\n+\n+ m = M.model_validate({\"gen_f\": \"ok\"})\n+ assert m.f == \"ok\"\n+ data = m.model_dump(by_alias=True)\n+ assert \"gen_f\" in data and data[\"gen_f\"] == \"ok\"\n+\n+\n+[USER_REDACTED]_pydanticv2\n+def test_alias_generator_with_explicit_alias_prefers_field_alias_sqlmodel_v2():\n+ class M(SQLModel):\n+ model_config = {\"alias_generator\": lambda s: \"gen_\" + s}\n+ f: str = Field(alias=\"custom\")\n+\n+ m = M.model_validate({\"custom\": \"ok\"})\n+ assert m.f == \"ok\"\n+ data = m.model_dump(by_alias=True)\n+ assert \"custom\" in data and \"gen_f\" not in data" } ], "reviews": [ { "id": 3286133440, "user": "user_29e85f9a8e75", "state": "COMMENTED", "body": "The idea looks good to me!\n\nA couple of more things:\n* ~~I think it would be nice to use `alias` as a default value for DB column. It can then be overridden by `sa_column=Column(\"column_name\")`~~ - decided to handle it in separate PR later\n* ~~We should probably test how it works with alias generators specified in model's config (is it supported? - UPD: YES)~~ (done)\n\nPS: [USER_REDACTED], sorry, I only noticed you self-assigned this PR when I was about to press \"Submit review\".. Hope you don't mind I submitted this review)", "submitted_at": "2025-09-30T18:30:32+00:00" }, { "id": 3286806062, "user": "user_6df47fc31203", "state": "COMMENTED", "body": null, "submitted_at": "2025-09-30T21:46:56+00:00" }, { "id": 3286853932, "user": "user_6df47fc31203", "state": "COMMENTED", "body": null, "submitted_at": "2025-09-30T22:10:10+00:00" }, { "id": 3287010235, "user": "user_6df47fc31203", "state": "COMMENTED", "body": null, "submitted_at": "2025-09-30T23:24:33+00:00" }, { "id": 3287010872, "user": "user_6df47fc31203", "state": "COMMENTED", "body": null, "submitted_at": "2025-09-30T23:25:04+00:00" }, { "id": 3287012581, "user": "user_6df47fc31203", "state": "COMMENTED", "body": null, "submitted_at": "2025-09-30T23:26:06+00:00" }, { "id": 3287019412, "user": "user_6df47fc31203", "state": "COMMENTED", "body": null, "submitted_at": "2025-09-30T23:29:41+00:00" }, { "id": 3287022941, "user": "user_6df47fc31203", "state": "COMMENTED", "body": null, "submitted_at": "2025-09-30T23:31:51+00:00" }, { "id": 3303358854, "user": "user_29e85f9a8e75", "state": "COMMENTED", "body": null, "submitted_at": "2025-10-06T08:27:43+00:00" }, { "id": 3303401742, "user": "user_29e85f9a8e75", "state": "COMMENTED", "body": "Good! We are almost there)\n\nI added a few comments.\n\nTested it a bit more and found a use case that is broken with this PR applied.\nThis is the workaround people use for now. Although it's not documented and it's a misuse of `schema_extra`, I think it would be nice to support passing `validation_alias` and `serialization_alias` via `schema_extra`, and show a warning message in such cases.\n```py\nfrom sqlmodel import SQLModel, Field\n\nclass MyModel(SQLModel):\n f: str = Field(schema_extra={\"validation_alias\": \"f_alias\"})\n\nm = MyModel.model_validate({\"f_alias\": \"asd\"})\nassert m.f == \"asd\"\n```\n\nAlso, we may want to add more tests (just ideas):\n* `alias` + `validation_alias` = `validation_alias` takes precedence\n* `alias` + `serialization_alias` = `serialization_alias` takes precedence\n* `alias_generator` in model config\n* `alias_generator` in model config + `alias` for field = `alias` takes precedence\n* passing `validation_alias` and `serialization_alias` via `schema_extra`", "submitted_at": "2025-10-06T10:10:50+00:00" }, { "id": 3316763321, "user": "user_6df47fc31203", "state": "COMMENTED", "body": null, "submitted_at": "2025-10-08T23:04:27+00:00" }, { "id": 3316763441, "user": "user_6df47fc31203", "state": "COMMENTED", "body": null, "submitted_at": "2025-10-08T23:04:33+00:00" }, { "id": 3316961411, "user": "user_6df47fc31203", "state": "COMMENTED", "body": null, "submitted_at": "2025-10-09T01:42:33+00:00" }, { "id": 3319864281, "user": "user_29e85f9a8e75", "state": "APPROVED", "body": "LGTM!\n\nImplementation is not breaking. It also handles the workaround with \n```\nField(schema_extra={\"validation_alias\": \"field_alias\"})\n```\nthat people currently use.\n\nThe only use case it can break is if users use \n```\nField(schema_extra={\"validation_alias\": \"field_alias\"})\n```\nand want to use this model with both, Pydantic V1 and V2.\nIt will now raise \n```\nRuntimeError(\"validation_alias is not supported in Pydantic v1\")\n```\nfor Pydantic V1.\nBut it's easily fixable - just remove `validation_alias` (now `alias` works with both versions, so that workaround is not needed).\n\n#### [NAME_REDACTED]:\nSome tests are parameterized to be run with both, SQLModel and Pydantic models, to show that they behave the same way. If you don't like it, it's easy to remove it.\n\n[USER_REDACTED], thank you!", "submitted_at": "2025-10-09T17:03:12+00:00" }, { "id": 3609308204, "user": "user_2a237e38e06b", "state": "APPROVED", "body": "Awesome, thank you [USER_REDACTED]! 🚀 \n\nAnd thanks [USER_REDACTED]! 🍰 \n\nThis will be available in SQLModel 0.0.29, released in the next hours. 🎉", "submitted_at": "2025-12-23T20:56:54+00:00" } ], "review_comments": [ { "id": 2392413881, "user": "user_29e85f9a8e75", "body": "This function is declared inside the `if IS_PYDANTIC_V2:` block. So, this condition looks not necessary here.\nAm I missing something?", "path": "sqlmodel/_compat.py", "line": null, "side": "RIGHT", "created_at": "2025-09-30T17:59:10+00:00" }, { "id": 2392422553, "user": "user_29e85f9a8e75", "body": "Looks like we can move this outside of `if..else..` block to avoid duplication", "path": "sqlmodel/main.py", "line": null, "side": "RIGHT", "created_at": "2025-09-30T18:03:12+00:00" }, { "id": 2392444806, "user": "user_29e85f9a8e75", "body": "We should think whether we want to keep parameterizing tests with Pydantic models.\nInitially I parametrized tests with both, Pydantic and SQLModel models to show the difference in behavior between SQLModel and Pydantic models.\n\nIf it's useful to keep this parametrization in repo? 🤔\nTests would be a bit simpler without it, but on the other hand this way we ensure it works the same as with Pydantic model", "path": "tests/test_aliases.py", "line": 16, "side": "RIGHT", "created_at": "2025-09-30T18:11:37+00:00" }, { "id": 2392446448, "user": "user_29e85f9a8e75", "body": "We will need to remove unnecessary comments in final version", "path": "tests/test_aliases.py", "line": null, "side": "RIGHT", "created_at": "2025-09-30T18:12:18+00:00" }, { "id": 2392454534, "user": "user_29e85f9a8e75", "body": "```suggestion\n[USER_REDACTED]_pydanticv2\n```\n\nWe should use `[USER_REDACTED]_pydanticv2` decorator as [it's usually done](https://github.com/fastapi/sqlmodel/blob/69b20188bdfec20bcda11c2b73be3e3d571047a8/tests/test_annotated_uuid.py#L9) in this code base\n```\nfrom tests.conftest import needs_pydanticv2\n```", "path": "tests/test_aliases.py", "line": null, "side": "RIGHT", "created_at": "2025-09-30T18:16:14+00:00" }, { "id": 2392464519, "user": "user_29e85f9a8e75", "body": "We also need to test the logic with `RuntimeError` for Pydantic V1\n\n```py\n if validation_alias:\n raise RuntimeError(\"validation_alias is not supported in Pydantic v1\")\n if serialization_alias:\n raise RuntimeError(\"serialization_alias is not supported in Pydantic v1\")\n```", "path": "tests/test_aliases.py", "line": 137, "side": "RIGHT", "created_at": "2025-09-30T18:21:10+00:00" }, { "id": 2392474638, "user": "user_29e85f9a8e75", "body": "Pydantic's `validation_alias` type annotation is wider (`validation_alias: str | AliasPath | AliasChoices | None`), but I think it's fine if we only support `str` for now and extend it later", "path": "sqlmodel/main.py", "line": 221, "side": "RIGHT", "created_at": "2025-09-30T18:26:07+00:00" }, { "id": 2392903040, "user": "user_6df47fc31203", "body": "Added for backward compatibility with Pydantic v1.\nWithout this, Pydantic tests v1 would fail.", "path": "sqlmodel/_compat.py", "line": null, "side": "RIGHT", "created_at": "2025-09-30T21:46:55+00:00" }, { "id": 2392937768, "user": "user_6df47fc31203", "body": "Good catch! I've fixed this by [NAME_REDACTED] if/else block to avoid duplication.", "path": "sqlmodel/main.py", "line": null, "side": "RIGHT", "created_at": "2025-09-30T22:10:10+00:00" }, { "id": 2393049109, "user": "user_6df47fc31203", "body": "Added Tests to test the logic with RuntimeError", "path": "tests/test_aliases.py", "line": 137, "side": "RIGHT", "created_at": "2025-09-30T23:24:32+00:00" }, { "id": 2393049729, "user": "user_6df47fc31203", "body": "Removed unnecessary comments", "path": "tests/test_aliases.py", "line": null, "side": "RIGHT", "created_at": "2025-09-30T23:25:03+00:00" }, { "id": 2393050952, "user": "user_6df47fc31203", "body": "Personally, I think it’s useful to keep the parametrization for now, since it acts as a kind of integration test between the two libraries.", "path": "tests/test_aliases.py", "line": 16, "side": "RIGHT", "created_at": "2025-09-30T23:26:05+00:00" }, { "id": 2393055303, "user": "user_6df47fc31203", "body": "I don't have a strong preference on this.", "path": "sqlmodel/main.py", "line": 221, "side": "RIGHT", "created_at": "2025-09-30T23:29:40+00:00" }, { "id": 2393057683, "user": "user_6df47fc31203", "body": "Addressed the comment", "path": "tests/test_aliases.py", "line": null, "side": "RIGHT", "created_at": "2025-09-30T23:31:51+00:00" }, { "id": 2405320135, "user": "user_29e85f9a8e75", "body": "I just checked it with Python 3.11 and Pydantic 1.10.22 - tests passed.\nCould you please check it one more time?\n```py\n def post_init_field_info(field_info: FieldInfo) -> None:\n if field_info.alias and not field_info.validation_alias:\n field_info.validation_alias = field_info.alias\n if field_info.alias and not field_info.serialization_alias:\n field_info.serialization_alias = field_info.alias\n```", "path": "sqlmodel/_compat.py", "line": null, "side": "RIGHT", "created_at": "2025-10-06T08:27:43+00:00" }, { "id": 2405353223, "user": "user_29e85f9a8e75", "body": "```suggestion\n[USER_REDACTED]_pydanticv1\ndef test_serialization_alias_runtimeerror_pydantic_v1():\n```", "path": "tests/test_aliases.py", "line": null, "side": "RIGHT", "created_at": "2025-10-06T08:40:39+00:00" }, { "id": 2405354804, "user": "user_29e85f9a8e75", "body": "```suggestion\n[USER_REDACTED]_pydanticv1\ndef test_validation_alias_runtimeerror_pydantic_v1():\n```", "path": "tests/test_aliases.py", "line": null, "side": "RIGHT", "created_at": "2025-10-06T08:41:19+00:00" }, { "id": 2405458711, "user": "user_29e85f9a8e75", "body": "```suggestion\nfrom tests.conftest import needs_pydanticv1, needs_pydanticv2\n```", "path": "tests/test_aliases.py", "line": null, "side": "RIGHT", "created_at": "2025-10-06T09:20:17+00:00" }, { "id": 2415205570, "user": "user_6df47fc31203", "body": "Thanks fixed it.", "path": "tests/test_aliases.py", "line": null, "side": "RIGHT", "created_at": "2025-10-08T23:04:27+00:00" }, { "id": 2415205699, "user": "user_6df47fc31203", "body": "Thanks fixed it.", "path": "tests/test_aliases.py", "line": null, "side": "RIGHT", "created_at": "2025-10-08T23:04:33+00:00" }, { "id": 2415362542, "user": "user_6df47fc31203", "body": "You are right. I checked and tests passed. Thanks.", "path": "sqlmodel/_compat.py", "line": null, "side": "RIGHT", "created_at": "2025-10-09T01:42:32+00:00" } ], "meta": { "languages": [ "py" ], "touches_tests": true, "review_state_summary": { "COMMENTED": 13, "APPROVED": 2 }, "meaningful_comment_count": 21, "has_approval": true, "has_changes_requested": false, "total_review_comments": 21 } } { "_id": "15e65d67bcac963c", "_schema_version": "1.0", "_cleaned_at": "2026-02-12T07:46:52.643621+00:00", "repo": "tiangolo/sqlmodel", "repo_url": "https://github.com/fastapi/sqlmodel", "license_name": "MIT License", "license_spdx": "MIT", "pr_number": 1340, "title": "💚 Fix linting in CI", "body": "Recent PRs have been failing due to an issue with the linting step in the CI - I think caused by [NAME_REDACTED] Pydantic 2.11.\n\nOverview of issues and proposed fixes:\n\n- Elaborate type warning for `get_model_fields` in `_compat.py`. \n```\nsqlmodel/_compat.py:106: error: Argument 1 to \"__get__\" of \"deprecated_instance_property\" has incompatible type \"BaseModel | type[BaseModel]\"; expected \"BaseModel\" [arg-type]\nsqlmodel/_compat.py:106: error: Argument 2 to \"__get__\" of \"deprecated_instance_property\" has incompatible type \"type[BaseModel] | type[type[BaseModel]]\"; expected \"type[BaseModel]\" [arg-type]\n```\nI think it's fine to ignore this one?\n\n- `model_fields` in `SQLModelMetaclass` on the other hand, now can do without an ignore warning\n- `SQLModel.model_validate()` is supposed to overwrite `BaseModel.model_validate()` but an error gets raised because of the `update` input parameter, which is not present in `BaseModel.model_validate()`. The proposed solution here is to work via `**kwargs`, which I'm generally not a fan of, but the only other option I would see is adding yet another ignore, which feels wrong in this case.\n- `SQLModel.model_dump()` is supposed to overwrite `BaseModel.model_dump()` but an error gets raised because of `context` and `alias` having a wrong type, and `fallback` not being present. `fallback` was [introduced](https://github.com/[USER_REDACTED]ntic/pydantic/pull/11398) in Pydantic v2.11. So instead of restricting Pydantic, I suggest to (again) work via `**kwargs`.\n\nThe linting test is failing for Python 3.8 in different ways than for all other Python versions, probably because Python 3.8 support was [removed](https://github.com/[USER_REDACTED]ntic/pydantic/pull/11258) for Pydantic 2.11. Accordingly, I've updated the `test.yml` to skip the linting test for Python 3.8. This doesn't feel like a clean solution either, and I guess the other option is to (also) drop support for Python 3.8.", "author": "user_84458f05cf3c", "created_at": "2025-04-09T13:14:02+00:00", "merged_at": "2025-04-26T19:04:09+00:00", "base_branch": "main", "head_branch": "fix/ci", "additions": 19, "deletions": 7, "changed_files": 3, "files": [ { "filename": ".github/workflows/test.yml", "status": "modified", "additions": 1, "deletions": 1, "changes": 2, "patch": "@@ -67,7 +67,7 @@ jobs:\n if: matrix.pydantic-version == 'pydantic-v2'\n run: uv pip install --upgrade \"pydantic>=2.0.2,<3.0.0\"\n - name: Lint\n- if: matrix.pydantic-version == 'pydantic-v2'\n+ if: matrix.pydantic-version == 'pydantic-v2' && matrix.python-version != '3.8'\n run: bash scripts/lint.sh\n - run: mkdir coverage\n - name: Test" }, { "filename": "sqlmodel/_compat.py", "status": "modified", "additions": 8, "deletions": 1, "changes": 9, "patch": "@@ -103,7 +103,14 @@ def set_config_value(\n model.model_config[parameter] = value # type: ignore[literal-required]\n \n def get_model_fields(model: InstanceOrType[BaseModel]) -> Dict[str, \"FieldInfo\"]:\n- return model.model_fields\n+ # TODO: refactor the usage of this function to always pass the class\n+ # not the instance, and then remove this extra check\n+ # this is for compatibility with Pydantic v3\n+ if isinstance(model, type):\n+ use_model = model\n+ else:\n+ use_model = model.__class__\n+ return use_model.model_fields\n \n def get_fields_set(\n object: InstanceOrType[\"SQLModel\"]," }, { "filename": "sqlmodel/main.py", "status": "modified", "additions": 10, "deletions": 5, "changes": 15, "patch": "@@ -477,7 +477,7 @@ def Relationship(\n class SQLModelMetaclass(ModelMetaclass, DeclarativeMeta):\n __sqlmodel_relationships__: Dict[str, RelationshipInfo]\n model_config: SQLModelConfig\n- model_fields: Dict[str, FieldInfo] # type: ignore[assignment]\n+ model_fields: ClassVar[Dict[str, FieldInfo]]\n __config__: Type[SQLModelConfig]\n __fields__: Dict[str, ModelField] # type: ignore[assignment]\n \n@@ -839,7 +839,7 @@ def __tablename__(cls) -> str:\n return cls.__name__.lower()\n \n [USER_REDACTED]\n- def model_validate(\n+ def model_validate( # type: ignore[override]\n cls: Type[_TSQLModel],\n obj: Any,\n *,\n@@ -863,20 +863,25 @@ def model_dump(\n mode: Union[Literal[\"json\", \"python\"], str] = \"python\",\n include: Union[IncEx, None] = None,\n exclude: Union[IncEx, None] = None,\n- context: Union[Dict[str, Any], None] = None,\n- by_alias: bool = False,\n+ context: Union[Any, None] = None,\n+ by_alias: Union[bool, None] = None,\n exclude_unset: bool = False,\n exclude_defaults: bool = False,\n exclude_none: bool = False,\n round_trip: bool = False,\n warnings: Union[bool, Literal[\"none\", \"warn\", \"error\"]] = True,\n+ fallback: Union[Callable[[Any], Any], None] = None,\n serialize_as_any: bool = False,\n ) -> Dict[str, Any]:\n+ if PYDANTIC_MINOR_VERSION < (2, 11):\n+ by_alias = by_alias or False\n if PYDANTIC_MINOR_VERSION >= (2, 7):\n extra_kwargs: Dict[str, Any] = {\n \"context\": context,\n \"serialize_as_any\": serialize_as_any,\n }\n+ if PYDANTIC_MINOR_VERSION >= (2, 11):\n+ extra_kwargs[\"fallback\"] = fallback\n else:\n extra_kwargs = {}\n if IS_PYDANTIC_V2:\n@@ -896,7 +901,7 @@ def model_dump(\n return super().dict(\n include=include,\n exclude=exclude,\n- by_alias=by_alias,\n+ by_alias=by_alias or False,\n exclude_unset=exclude_unset,\n exclude_defaults=exclude_defaults,\n exclude_none=exclude_none," } ], "reviews": [ { "id": 2753867536, "user": "user_215f8a36c628", "state": "APPROVED", "body": null, "submitted_at": "2025-04-09T15:17:52+00:00" }, { "id": 2796340002, "user": "user_2a237e38e06b", "state": "APPROVED", "body": "Thank you [USER_REDACTED]! :rocket: \n\nI tweaked it a bit mainly to keep autocompletion and inline errors for final users. Although this reveals some areas that probably deserve some tweaking in the future. :thinking: \n\nI added some inline comments to share my mental process.\n\nThanks! :rocket:", "submitted_at": "2025-04-26T19:03:43+00:00" } ], "review_comments": [ { "id": 2061539455, "user": "user_2a237e38e06b", "body": "I was checking the error from Pydantic and I saw that they will deprecate accessing the `model_fields` from the instance in Pydantic v3, they should be accessed from the class (which makes sense).\n\nI updated this logic here to handle that future use case. In a subsequent PR we can refactor the internal usage of this function to only pass the class and not the instance.", "path": "sqlmodel/_compat.py", "line": 113, "side": "RIGHT", "created_at": "2025-04-26T18:37:04+00:00" }, { "id": 2061539665, "user": "user_2a237e38e06b", "body": "As the idea is that this should now be only in the class and not instances, I think it's good to type it right away. It won't affect at runtime if people are using it, but will start warning them in their linters, so they can start preparing for this change in Pydantic v3.", "path": "sqlmodel/main.py", "line": 480, "side": "RIGHT", "created_at": "2025-04-26T18:38:09+00:00" }, { "id": 2061540780, "user": "user_2a237e38e06b", "body": "I changed this to not use `kwargs` and instead ignore the type here, that way people will keep having autocompletion for the params, and kwargs won't swallow extra / invald params.\n\nSeeing this, I realize it was probably not the best idea to include the extra `update` here. :thinking: \n\nAlso, it's probably not needed for most use cases, maybe it would make sense to remove those docs, explain how to extend data to validate an object using just dicts, then deprecate using it, and finally at some point dropping the `update`... \n\nBut anyway, for now, it probably works to just `# type: ignore` and handle it on our side so that final users get the best developer experience / editor support.", "path": "sqlmodel/main.py", "line": 842, "side": "RIGHT", "created_at": "2025-04-26T18:42:19+00:00" }, { "id": 2061541161, "user": "user_2a237e38e06b", "body": "I like to keep the signature as close to the latest Pydantic, and then do the extra work internally to support the older versions, but this way people can get used to the new syntax and/or use it if they can already upgrade to the latest version.", "path": "sqlmodel/main.py", "line": 867, "side": "RIGHT", "created_at": "2025-04-26T18:43:29+00:00" }, { "id": 2061541310, "user": "user_2a237e38e06b", "body": "With this trick, we avoid the type when `by_alias` is `None`. :sweat_smile:", "path": "sqlmodel/main.py", "line": 904, "side": "RIGHT", "created_at": "2025-04-26T18:44:11+00:00" }, { "id": 2061546410, "user": "user_2a237e38e06b", "body": "With this we can handle older Pydantic versions but keep the most recent signature.", "path": "sqlmodel/main.py", "line": 877, "side": "RIGHT", "created_at": "2025-04-26T18:58:36+00:00" } ], "meta": { "languages": [ "py", "yml" ], "touches_tests": false, "review_state_summary": { "APPROVED": 2 }, "meaningful_comment_count": 6, "has_approval": true, "has_changes_requested": false, "total_review_comments": 6 } } { "_id": "93939701acc876c2", "_schema_version": "1.0", "_cleaned_at": "2026-02-12T07:46:52.643621+00:00", "repo": "tiangolo/sqlmodel", "repo_url": "https://github.com/fastapi/sqlmodel", "license_name": "MIT License", "license_spdx": "MIT", "pr_number": 1307, "title": "💚 Fix CI test suite for Windows and MacOS", "body": "Run the test suite not only on Ubuntu, but also on Windows and MacOS. \n\nTo avoid getting an exponential number of tests, limiting the testing of older Python versions to just a few different combinations. All in all, now the test suite should have 12 combinations to test (3x1x2 + 6), which is the same as before (6x2x1). So it shouldn't be slower, but it should cover more diverse cases.", "author": "user_84458f05cf3c", "created_at": "2025-02-21T15:14:15+00:00", "merged_at": "2025-09-17T22:19:41+00:00", "base_branch": "main", "head_branch": "feat/ci_again", "additions": 24, "deletions": 10, "changed_files": 3, "files": [ { "filename": ".github/workflows/test.yml", "status": "modified", "additions": 22, "deletions": 9, "changes": 31, "patch": "@@ -25,17 +25,30 @@ jobs:\n test:\n strategy:\n matrix:\n- os: [ ubuntu-latest ]\n- python-version:\n- - \"3.8\"\n- - \"3.9\"\n- - \"3.10\"\n- - \"3.11\"\n- - \"3.12\"\n- - \"3.13\"\n+ os: [ ubuntu-latest, windows-latest, macos-latest ]\n+ python-version: [ \"3.13\" ]\n pydantic-version:\n - pydantic-v1\n - pydantic-v2\n+ include:\n+ - os: macos-latest\n+ python-version: \"3.8\"\n+ pydantic-version: pydantic-v1\n+ - os: windows-latest\n+ python-version: \"3.9\"\n+ pydantic-version: pydantic-v2\n+ - os: ubuntu-latest\n+ python-version: \"3.10\"\n+ pydantic-version: pydantic-v1\n+ - os: macos-latest\n+ python-version: \"3.11\"\n+ pydantic-version: pydantic-v2\n+ - os: windows-latest\n+ python-version: \"3.12\"\n+ pydantic-version: pydantic-v1\n+ - os: ubuntu-latest\n+ python-version: \"3.12\"\n+ pydantic-version: pydantic-v2\n fail-fast: false\n runs-on: ${{ matrix.os }}\n steps:\n@@ -78,7 +91,7 @@ jobs:\n - name: Store coverage files\n uses: actions/upload-artifact@v4\n with:\n- name: coverage-${{ matrix.python-version }}-${{ matrix.pydantic-version }}\n+ name: coverage-${{ runner.os }}-${{ matrix.python-version }}-${{ matrix.pydantic-version }}\n path: coverage\n include-hidden-files: true" }, { "filename": "pyproject.toml", "status": "modified", "additions": 1, "deletions": 0, "changes": 1, "patch": "@@ -81,6 +81,7 @@ source = [\n ]\n context = '${CONTEXT}'\n dynamic_context = \"test_function\"\n+relative_files = true\n \n [tool.coverage.report]\n show_missing = true" }, { "filename": "tests/test_select_gen.py", "status": "modified", "additions": 1, "deletions": 1, "changes": 2, "patch": "@@ -13,7 +13,7 @@ def test_select_gen() -> None:\n env = os.environ.copy()\n env[\"CHECK_JINJA\"] = \"1\"\n result = subprocess.run(\n- [sys.executable, \"scripts/generate_select.py\"],\n+ [sys.executable, Path(\"scripts\") / \"generate_select.py\"],\n env=env,\n check=True,\n cwd=root_path," } ], "reviews": [ { "id": 2798841605, "user": "user_84458f05cf3c", "state": "COMMENTED", "body": null, "submitted_at": "2025-04-28T10:32:17+00:00" }, { "id": 3233486101, "user": "user_84458f05cf3c", "state": "COMMENTED", "body": null, "submitted_at": "2025-09-17T09:17:43+00:00" }, { "id": 3236440098, "user": "user_2a237e38e06b", "state": "APPROVED", "body": "Niceee! Thank you! 🙌 🚀", "submitted_at": "2025-09-17T22:19:27+00:00" } ], "review_comments": [ { "id": 2063382423, "user": "user_84458f05cf3c", "body": "The coverage test kept on giving this error for either MacOS or Windows:\n```\nNo source for code: '/Users/runner/work/sqlmodel/sqlmodel/docs_src/__init__.py'.\n```\nThis is fixed by [NAME_REDACTED] `relative_files` setting 🎉", "path": "pyproject.toml", "line": 84, "side": "RIGHT", "created_at": "2025-04-28T10:32:17+00:00" }, { "id": 2354865365, "user": "user_84458f05cf3c", "body": "The `env` stuff is basically the same fix as what was done in https://github.com/fastapi/sqlmodel/pull/969, but shortened.\n\n(we can probably also just keep the current way it's done on `main` - as long as the things in `os.environ` are passed to `env` as well)", "path": "tests/test_select_gen.py", "line": null, "side": "RIGHT", "created_at": "2025-09-17T09:17:42+00:00" } ], "meta": { "languages": [ "py", "toml", "yml" ], "touches_tests": true, "review_state_summary": { "COMMENTED": 2, "APPROVED": 1 }, "meaningful_comment_count": 2, "has_approval": true, "has_changes_requested": false, "total_review_comments": 2 } } { "_id": "03dd58a968609bdd", "_schema_version": "1.0", "_cleaned_at": "2026-02-12T07:46:52.643621+00:00", "repo": "tiangolo/sqlmodel", "repo_url": "https://github.com/fastapi/sqlmodel", "license_name": "MIT License", "license_spdx": "MIT", "pr_number": 1302, "title": "👷 Add retries to Smokeshow", "body": "Similar to https://github.com/fastapi/fastapi/pull/13151", "author": "user_84458f05cf3c", "created_at": "2025-02-20T09:00:52+00:00", "merged_at": "2025-02-20T09:15:20+00:00", "base_branch": "main", "head_branch": "feat/smokeshow", "additions": 11, "deletions": 2, "changed_files": 2, "files": [ { "filename": ".github/workflows/smokeshow.yml", "status": "modified", "additions": 11, "deletions": 1, "changes": 12, "patch": "@@ -35,7 +35,17 @@ jobs:\n path: htmlcov\n github-token: ${{ secrets.GITHUB_TOKEN }}\n run-id: ${{ github.event.workflow_run.id }}\n- - run: smokeshow upload htmlcov\n+ # Try 5 times to upload coverage to smokeshow\n+ - name: Upload coverage to Smokeshow\n+ run: |\n+ for i in 1 2 3 4 5; do\n+ if smokeshow upload htmlcov; then\n+ echo \"Smokeshow upload success!\"\n+ break\n+ fi\n+ echo \"Smokeshow upload error, sleep 1 sec and try again.\"\n+ sleep 1\n+ done\n env:\n SMOKESHOW_GITHUB_STATUS_DESCRIPTION: Coverage {coverage-percentage}\n SMOKESHOW_GITHUB_COVERAGE_THRESHOLD: 95" }, { "filename": ".github/workflows/test.yml", "status": "modified", "additions": 0, "deletions": 1, "changes": 1, "patch": "@@ -27,7 +27,6 @@ jobs:\n strategy:\n matrix:\n python-version:\n- - \"3.7\"\n - \"3.8\"\n - \"3.9\"\n - \"3.10\"" } ], "reviews": [ { "id": 2629142393, "user": "user_84458f05cf3c", "state": "COMMENTED", "body": null, "submitted_at": "2025-02-20T09:03:22+00:00" }, { "id": 2629177356, "user": "user_2a237e38e06b", "state": "APPROVED", "body": "Nice! Thanks! :rocket:", "submitted_at": "2025-02-20T09:15:09+00:00" } ], "review_comments": [ { "id": 1963123746, "user": "user_84458f05cf3c", "body": "This is just to pass the CI for now. In fact, I want to fix the test suite so that it runs again for Python 3.7 (see #1290 and #1301) but I'm running into issues with Smokeshow apparently hanging, and I want to see whether these retries will fix that. Once this is merged, I'll add support for 3.7 back into the test suite in #1301.", "path": ".github/workflows/test.yml", "line": 30, "side": "LEFT", "created_at": "2025-02-20T09:03:22+00:00" } ], "meta": { "languages": [ "yml" ], "touches_tests": false, "review_state_summary": { "COMMENTED": 1, "APPROVED": 1 }, "meaningful_comment_count": 1, "has_approval": true, "has_changes_requested": false, "total_review_comments": 1 } }