Skip to content

Commit

Permalink
pythongh-127537: Add __class_getitem__ to the python implementation o…
Browse files Browse the repository at this point in the history
…f functools.partial (python#127537)

(cherry picked from commit 401bba6)
  • Loading branch information
cfbolz authored and hauntsaninja committed Dec 27, 2024
1 parent f699151 commit e0f6344
Show file tree
Hide file tree
Showing 3 changed files with 29 additions and 0 deletions.
3 changes: 3 additions & 0 deletions Lib/functools.py
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down
21 changes: 21 additions & 0 deletions Lib/test/test_functools.py
Original file line number Diff line number Diff line change
Expand Up @@ -390,6 +390,27 @@ def __getitem__(self, key):
f = self.partial(object)
self.assertRaises(TypeError, f.__setstate__, BadSequence())

def test_partial_as_method(self):
class A:
meth = self.partial(capture, 1, a=2)
cmeth = classmethod(self.partial(capture, 1, a=2))
smeth = staticmethod(self.partial(capture, 1, a=2))

a = A()
self.assertEqual(A.meth(3, b=4), ((1, 3), {'a': 2, 'b': 4}))
self.assertEqual(A.cmeth(3, b=4), ((1, A, 3), {'a': 2, 'b': 4}))
self.assertEqual(A.smeth(3, b=4), ((1, 3), {'a': 2, 'b': 4}))
self.assertEqual(a.meth(3, b=4), ((1, a, 3), {'a': 2, 'b': 4}))
self.assertEqual(a.cmeth(3, b=4), ((1, A, 3), {'a': 2, 'b': 4}))
self.assertEqual(a.smeth(3, b=4), ((1, 3), {'a': 2, 'b': 4}))

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:
Expand Down
Original file line number Diff line number Diff line change
@@ -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.

0 comments on commit e0f6344

Please sign in to comment.