Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

gh-92062: inspect.Parameter checks whether name is a keyword #92065

Merged
merged 3 commits into from
May 3, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 7 additions & 3 deletions Lib/inspect.py
Original file line number Diff line number Diff line change
Expand Up @@ -149,6 +149,7 @@
import types
import functools
import builtins
from keyword import iskeyword
from operator import attrgetter
from collections import namedtuple, OrderedDict

Expand Down Expand Up @@ -1645,7 +1646,7 @@ def __new__(cls, filename, lineno, function, code_context, index, *, positions=N
instance = super().__new__(cls, filename, lineno, function, code_context, index)
instance.positions = positions
return instance

def __repr__(self):
return ('Traceback(filename={!r}, lineno={!r}, function={!r}, '
'code_context={!r}, index={!r}, positions={!r})'.format(
Expand Down Expand Up @@ -1683,7 +1684,7 @@ def getframeinfo(frame, context=1):
frame, *positions = (frame, lineno, *positions[1:])
else:
frame, *positions = (frame, *positions)

lineno = positions[0]

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

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

self._name = name
Expand Down
3 changes: 3 additions & 0 deletions Lib/test/test_inspect.py
Original file line number Diff line number Diff line change
Expand Up @@ -3604,6 +3604,9 @@ def test_signature_parameter_object(self):
with self.assertRaisesRegex(ValueError, 'not a valid parameter name'):
inspect.Parameter('1', kind=inspect.Parameter.VAR_KEYWORD)

with self.assertRaisesRegex(ValueError, 'not a valid parameter name'):
inspect.Parameter('from', kind=inspect.Parameter.VAR_KEYWORD)

with self.assertRaisesRegex(TypeError, 'name must be a str'):
inspect.Parameter(None, kind=inspect.Parameter.VAR_KEYWORD)

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