Coverage for src/_griffe/agents/nodes/values.py: 43.48%
19 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 attribute values.
3from __future__ import annotations
5import ast
6from ast import unparse
7from typing import TYPE_CHECKING
9from _griffe.logger import logger
11if TYPE_CHECKING:
12 from pathlib import Path
15def get_value(node: ast.AST | None) -> str | None:
16 """Get the string representation of a node.
18 Parameters:
19 node: The node to represent.
21 Returns:
22 The representing code for the node.
23 """
24 if node is None: 24 ↛ 25line 24 didn't jump to line 25 because the condition on line 24 was never true
25 return None
26 return unparse(node)
29def safe_get_value(node: ast.AST | None, filepath: str | Path | None = None) -> str | None:
30 """Safely (no exception) get the string representation of a node.
32 Parameters:
33 node: The node to represent.
34 filepath: An optional filepath from where the node comes.
36 Returns:
37 The representing code for the node.
38 """
39 try:
40 return get_value(node)
41 except Exception as error:
42 message = f"Failed to represent node {node}"
43 if filepath:
44 message += f" at {filepath}:{node.lineno}" # type: ignore[union-attr]
45 message += f": {error}"
46 logger.exception(message)
47 return None