Coverage for src/_griffe/agents/nodes/assignments.py: 100.00%
21 statements
« prev ^ index » next coverage.py v7.6.2, created at 2024-10-12 01:34 +0200
« prev ^ index » next coverage.py v7.6.2, created at 2024-10-12 01:34 +0200
1# This module contains utilities for extracting information from assignment nodes.
3from __future__ import annotations
5import ast
6from typing import Any, Callable
9def _get_attribute_name(node: ast.Attribute) -> str:
10 return f"{get_name(node.value)}.{node.attr}"
13def _get_name_name(node: ast.Name) -> str:
14 return node.id
17_node_name_map: dict[type, Callable[[Any], str]] = {
18 ast.Name: _get_name_name,
19 ast.Attribute: _get_attribute_name,
20}
23def get_name(node: ast.AST) -> str:
24 """Extract name from an assignment node.
26 Parameters:
27 node: The node to extract names from.
29 Returns:
30 A list of names.
31 """
32 return _node_name_map[type(node)](node)
35def _get_assign_names(node: ast.Assign) -> list[str]:
36 names = (get_name(target) for target in node.targets)
37 return [name for name in names if name]
40def _get_annassign_names(node: ast.AnnAssign) -> list[str]:
41 name = get_name(node.target)
42 return [name] if name else []
45_node_names_map: dict[type, Callable[[Any], list[str]]] = {
46 ast.Assign: _get_assign_names,
47 ast.AnnAssign: _get_annassign_names,
48}
51def get_names(node: ast.AST) -> list[str]:
52 """Extract names from an assignment node.
54 Parameters:
55 node: The node to extract names from.
57 Returns:
58 A list of names.
59 """
60 return _node_names_map[type(node)](node)
63def get_instance_names(node: ast.AST) -> list[str]:
64 """Extract names from an assignment node, only for instance attributes.
66 Parameters:
67 node: The node to extract names from.
69 Returns:
70 A list of names.
71 """
72 return [name.split(".", 1)[1] for name in get_names(node) if name.startswith("self.")]