From 2ff25cb4c6d5e7187a9b25da1b3bd40149d8284c Mon Sep 17 00:00:00 2001 From: CrazyBolillo Date: Sat, 22 Jul 2023 09:37:02 -0600 Subject: [PATCH] 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. --- astroid/nodes/node_classes.py | 6 ++++-- tests/test_inference.py | 16 ++++++++++++++++ 2 files changed, 20 insertions(+), 2 deletions(-) diff --git a/astroid/nodes/node_classes.py b/astroid/nodes/node_classes.py index 014955cf06..8e0dd7b902 100644 --- a/astroid/nodes/node_classes.py +++ b/astroid/nodes/node_classes.py @@ -947,8 +947,10 @@ def default_value(self, argname): ] index = _find_arg(argname, self.kwonlyargs)[0] - if index is not None and self.kw_defaults[index] is not None: - return self.kw_defaults[index] + if (index is not None) and (len(self.kw_defaults) > index): + if self.kw_defaults[index] is not None: + return self.kw_defaults[index] + raise NoDefault(func=self.parent, name=argname) index = _find_arg(argname, args)[0] if index is not None: diff --git a/tests/test_inference.py b/tests/test_inference.py index 290aa4be6a..770bca1c1c 100644 --- a/tests/test_inference.py +++ b/tests/test_inference.py @@ -38,6 +38,7 @@ AstroidTypeError, AttributeInferenceError, InferenceError, + NoDefault, NotFoundError, ) from astroid.objects import ExceptionInstance @@ -146,6 +147,21 @@ def meth3(self, d=attr): ast = parse(CODE, __name__) + def test_arg_keyword_no_default_value(self): + node = extract_node( + """ + class Sensor: + def __init__(self, *, description): #@ + self._id = description.key + """ + ) + with self.assertRaises(NoDefault): + node.args.default_value("description") + + node = extract_node("def apple(color, *args, name: str, **kwargs): ...") + with self.assertRaises(NoDefault): + node.args.default_value("name") + def test_infer_abstract_property_return_values(self) -> None: module = parse( """