Skip to content

Commit 40f81e1

Browse files
[3.12] gh-130164: Fix inspect.Signature.bind() handling of positional-only args without defaults (GH-130192) (GH-132259)
Follow-up to 9c15202. (cherry picked from commit dab456d) Co-authored-by: Jacob Walls <[email protected]>
1 parent aab69a8 commit 40f81e1

File tree

3 files changed

+12
-2
lines changed

3 files changed

+12
-2
lines changed

Lib/inspect.py

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3161,6 +3161,9 @@ def _bind(self, args, kwargs, *, partial=False):
31613161
break
31623162
elif param.name in kwargs:
31633163
if param.kind == _POSITIONAL_ONLY:
3164+
if param.default is _empty:
3165+
msg = f'missing a required positional-only argument: {param.name!r}'
3166+
raise TypeError(msg)
31643167
# Raise a TypeError once we are sure there is no
31653168
# **kwargs param later.
31663169
pos_only_param_in_kwargs.append(param)

Lib/test/test_inspect/test_inspect.py

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -4701,7 +4701,11 @@ class TestSignatureBind(unittest.TestCase):
47014701
def call(func, *args, **kwargs):
47024702
sig = inspect.signature(func)
47034703
ba = sig.bind(*args, **kwargs)
4704-
return func(*ba.args, **ba.kwargs)
4704+
# Prevent unexpected success of assertRaises(TypeError, ...)
4705+
try:
4706+
return func(*ba.args, **ba.kwargs)
4707+
except TypeError as e:
4708+
raise AssertionError from e
47054709

47064710
def test_signature_bind_empty(self):
47074711
def test():
@@ -4901,7 +4905,7 @@ def test(a_po, b_po, c_po=3, /, foo=42, *, bar=50, **kwargs):
49014905
self.assertEqual(self.call(test, 1, 2, c_po=4),
49024906
(1, 2, 3, 42, 50, {'c_po': 4}))
49034907

4904-
with self.assertRaisesRegex(TypeError, "missing 2 required positional arguments"):
4908+
with self.assertRaisesRegex(TypeError, "missing a required positional-only argument: 'a_po'"):
49054909
self.call(test, a_po=1, b_po=2)
49064910

49074911
def without_var_kwargs(c_po=3, d_po=4, /):
Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
Fixed failure to raise :exc:`TypeError` in :meth:`inspect.Signature.bind`
2+
for positional-only arguments provided by keyword when a variadic keyword
3+
argument (e.g. ``**kwargs``) is present.

0 commit comments

Comments
 (0)