Skip to content

Commit ab119c2

Browse files
authored
Add helper to iterate over all annotation nodes of Arguments (#2860)
1 parent 92e320f commit ab119c2

File tree

3 files changed

+35
-0
lines changed

3 files changed

+35
-0
lines changed

ChangeLog

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,11 @@ Release date: TBA
1616
Closes #2741
1717
Closes pylint-dev/pylint#6094
1818

19+
* Add helper to iterate over all annotations nodes of function arguments,
20+
``Arguments.get_annotations()``.
21+
22+
Refs #2860
23+
1924

2025
What's New in astroid 4.0.2?
2126
============================

astroid/nodes/node_classes.py

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1020,6 +1020,23 @@ def get_children(self):
10201020
if elt is not None:
10211021
yield elt
10221022

1023+
def get_annotations(self) -> Iterator[nodes.NodeNG]:
1024+
"""Iterate over all annotations nodes."""
1025+
for elt in self.posonlyargs_annotations:
1026+
if elt is not None:
1027+
yield elt
1028+
for elt in self.annotations:
1029+
if elt is not None:
1030+
yield elt
1031+
if self.varargannotation is not None:
1032+
yield self.varargannotation
1033+
1034+
for elt in self.kwonlyargs_annotations:
1035+
if elt is not None:
1036+
yield elt
1037+
if self.kwargannotation is not None:
1038+
yield self.kwargannotation
1039+
10231040
@decorators.raise_if_nothing_inferred
10241041
def _infer(
10251042
self: nodes.Arguments, context: InferenceContext | None = None, **kwargs: Any

tests/test_nodes.py

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2314,6 +2314,19 @@ def test_arguments_default_value():
23142314
assert node.args.default_value("flavor").value == "good"
23152315

23162316

2317+
def test_arguments_annotations():
2318+
node = extract_node(
2319+
"def fruit(eat: str, /, peel: bool, *args: int, trim: float, **kwargs: bytes): ..."
2320+
)
2321+
assert isinstance(node.args, nodes.Arguments)
2322+
annotation_names = [
2323+
ann.name for ann in node.args.get_annotations() if isinstance(ann, nodes.Name)
2324+
]
2325+
assert all(
2326+
name in annotation_names for name in ("str", "bool", "int", "float", "bytes")
2327+
)
2328+
2329+
23172330
def test_deprecated_nodes_import_from_toplevel():
23182331
# pylint: disable=import-outside-toplevel,no-name-in-module
23192332
with pytest.raises(

0 commit comments

Comments
 (0)