Skip to content

Commit 9cd9104

Browse files
committed
fix default_value for kwonlyargs with no default
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 arised after changes in PR #2240.
1 parent ec912f9 commit 9cd9104

File tree

2 files changed

+19
-3
lines changed

2 files changed

+19
-3
lines changed

astroid/nodes/node_classes.py

+5-2
Original file line numberDiff line numberDiff line change
@@ -947,8 +947,11 @@ 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+
else:
954+
raise NoDefault(func=self.parent, name=argname)
952955

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

tests/test_inference.py

+14-1
Original file line numberDiff line numberDiff line change
@@ -38,7 +38,7 @@
3838
AstroidTypeError,
3939
AttributeInferenceError,
4040
InferenceError,
41-
NotFoundError,
41+
NotFoundError, NoDefault,
4242
)
4343
from astroid.objects import ExceptionInstance
4444

@@ -146,6 +146,19 @@ def meth3(self, d=attr):
146146

147147
ast = parse(CODE, __name__)
148148

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

0 commit comments

Comments
 (0)