From f1a757607a5a53eaa79fe42da7da398d65296fff Mon Sep 17 00:00:00 2001 From: CF Bolz-Tereick Date: Fri, 27 Dec 2024 02:03:47 +0100 Subject: [PATCH] gh-127537: Add __class_getitem__ to the python implementation of functools.partial (#127537) (cherry picked from commit 401bba6b58497ce59e7b45ad33e43ae8c67abcb9) --- Lib/functools.py | 3 +++ Lib/test/test_functools.py | 7 +++++++ .../Library/2024-12-04-10-39-29.gh-issue-83662.CG1s3m.rst | 5 +++++ 3 files changed, 15 insertions(+) create mode 100644 Misc/NEWS.d/next/Library/2024-12-04-10-39-29.gh-issue-83662.CG1s3m.rst diff --git a/Lib/functools.py b/Lib/functools.py index f6849899e7578e..6025032bfaa233 100644 --- a/Lib/functools.py +++ b/Lib/functools.py @@ -340,6 +340,9 @@ def __setstate__(self, state): self.args = args self.keywords = kwds + __class_getitem__ = classmethod(GenericAlias) + + try: from _functools import partial except ImportError: diff --git a/Lib/test/test_functools.py b/Lib/test/test_functools.py index ff71fd53c08a69..dadcd04394b390 100644 --- a/Lib/test/test_functools.py +++ b/Lib/test/test_functools.py @@ -390,6 +390,13 @@ def __getitem__(self, key): f = self.partial(object) self.assertRaises(TypeError, f.__setstate__, BadSequence()) + def test_partial_genericalias(self): + alias = self.partial[int] + self.assertIs(alias.__origin__, self.partial) + self.assertEqual(alias.__args__, (int,)) + self.assertEqual(alias.__parameters__, ()) + + @unittest.skipUnless(c_functools, 'requires the C _functools module') class TestPartialC(TestPartial, unittest.TestCase): if c_functools: diff --git a/Misc/NEWS.d/next/Library/2024-12-04-10-39-29.gh-issue-83662.CG1s3m.rst b/Misc/NEWS.d/next/Library/2024-12-04-10-39-29.gh-issue-83662.CG1s3m.rst new file mode 100644 index 00000000000000..5e39933047993c --- /dev/null +++ b/Misc/NEWS.d/next/Library/2024-12-04-10-39-29.gh-issue-83662.CG1s3m.rst @@ -0,0 +1,5 @@ +Add missing ``__class_getitem__`` method to the Python implementation of +:func:`functools.partial`, to make it compatible with the C version. This is +mainly relevant for alternative Python implementations like PyPy and +GraalPy, because CPython will usually use the C-implementation of that +function.