Skip to content

Commit 00d7940

Browse files
authored
Fix default_value for kwonlyargs with no default (#2261)
Refs #2213. Requesting the default value for a kwonlyarg with no default would fail with an IndexError, it now correctly raises a NoDefault exception. This issue arose after changes in PR #2240.
1 parent ec912f9 commit 00d7940

File tree

2 files changed

+20
-2
lines changed

2 files changed

+20
-2
lines changed

astroid/nodes/node_classes.py

+4-2
Original file line numberDiff line numberDiff line change
@@ -947,8 +947,10 @@ def default_value(self, argname):
947947
]
948948

949949
index = _find_arg(argname, self.kwonlyargs)[0]
950-
if index is not None and self.kw_defaults[index] is not None:
951-
return self.kw_defaults[index]
950+
if (index is not None) and (len(self.kw_defaults) > index):
951+
if self.kw_defaults[index] is not None:
952+
return self.kw_defaults[index]
953+
raise NoDefault(func=self.parent, name=argname)
952954

953955
index = _find_arg(argname, args)[0]
954956
if index is not None:

tests/test_inference.py

+16
Original file line numberDiff line numberDiff line change
@@ -38,6 +38,7 @@
3838
AstroidTypeError,
3939
AttributeInferenceError,
4040
InferenceError,
41+
NoDefault,
4142
NotFoundError,
4243
)
4344
from astroid.objects import ExceptionInstance
@@ -146,6 +147,21 @@ def meth3(self, d=attr):
146147

147148
ast = parse(CODE, __name__)
148149

150+
def test_arg_keyword_no_default_value(self):
151+
node = extract_node(
152+
"""
153+
class Sensor:
154+
def __init__(self, *, description): #@
155+
self._id = description.key
156+
"""
157+
)
158+
with self.assertRaises(NoDefault):
159+
node.args.default_value("description")
160+
161+
node = extract_node("def apple(color, *args, name: str, **kwargs): ...")
162+
with self.assertRaises(NoDefault):
163+
node.args.default_value("name")
164+
149165
def test_infer_abstract_property_return_values(self) -> None:
150166
module = parse(
151167
"""

0 commit comments

Comments
 (0)