Skip to content

Commit 65f88a6

Browse files
authored
gh-92062: inspect.Parameter checks whether name is a keyword (GH-92065)
Fixes #92062.
1 parent 3a35b62 commit 65f88a6

File tree

3 files changed

+12
-3
lines changed

3 files changed

+12
-3
lines changed

Lib/inspect.py

+7-3
Original file line numberDiff line numberDiff line change
@@ -149,6 +149,7 @@
149149
import types
150150
import functools
151151
import builtins
152+
from keyword import iskeyword
152153
from operator import attrgetter
153154
from collections import namedtuple, OrderedDict
154155

@@ -1645,7 +1646,7 @@ def __new__(cls, filename, lineno, function, code_context, index, *, positions=N
16451646
instance = super().__new__(cls, filename, lineno, function, code_context, index)
16461647
instance.positions = positions
16471648
return instance
1648-
1649+
16491650
def __repr__(self):
16501651
return ('Traceback(filename={!r}, lineno={!r}, function={!r}, '
16511652
'code_context={!r}, index={!r}, positions={!r})'.format(
@@ -1683,7 +1684,7 @@ def getframeinfo(frame, context=1):
16831684
frame, *positions = (frame, lineno, *positions[1:])
16841685
else:
16851686
frame, *positions = (frame, *positions)
1686-
1687+
16871688
lineno = positions[0]
16881689

16891690
if not isframe(frame):
@@ -2707,7 +2708,10 @@ def __init__(self, name, kind, *, default=_empty, annotation=_empty):
27072708
self._kind = _POSITIONAL_ONLY
27082709
name = 'implicit{}'.format(name[1:])
27092710

2710-
if not name.isidentifier():
2711+
# It's possible for C functions to have a positional-only parameter
2712+
# where the name is a keyword, so for compatibility we'll allow it.
2713+
is_keyword = iskeyword(name) and self._kind is not _POSITIONAL_ONLY
2714+
if is_keyword or not name.isidentifier():
27112715
raise ValueError('{!r} is not a valid parameter name'.format(name))
27122716

27132717
self._name = name

Lib/test/test_inspect.py

+3
Original file line numberDiff line numberDiff line change
@@ -3604,6 +3604,9 @@ def test_signature_parameter_object(self):
36043604
with self.assertRaisesRegex(ValueError, 'not a valid parameter name'):
36053605
inspect.Parameter('1', kind=inspect.Parameter.VAR_KEYWORD)
36063606

3607+
with self.assertRaisesRegex(ValueError, 'not a valid parameter name'):
3608+
inspect.Parameter('from', kind=inspect.Parameter.VAR_KEYWORD)
3609+
36073610
with self.assertRaisesRegex(TypeError, 'name must be a str'):
36083611
inspect.Parameter(None, kind=inspect.Parameter.VAR_KEYWORD)
36093612

Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
:class:`inspect.Parameter` now raises :exc:`ValueError` if ``name`` is
2+
a keyword, in addition to the existing check that it is an identifier.

0 commit comments

Comments
 (0)