Debian Codegraph @

packages/griffelib/src/griffe/_internal/agents/nodes/values.py

raw symbols SCIP
1 # This module contains utilities for extracting attribute values.
2
3 from __future__ import annotations
4
5 import ast
6 from ast import unparse
7 from typing import TYPE_CHECKING
8
9 from griffe._internal.logger import logger
10
11 if TYPE_CHECKING:
12 from pathlib import Path
13
14
15 def get_value(node: ast.AST | None) -> str | None:
16 """Get the string representation of a node.
17
18 Parameters:
19 node: The node to represent.
20
21 Returns:
22 The representing code for the node.
23 """
24 if node is None:
25 return None
26 return unparse(node)
27
28
29 def 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.
31
32 Parameters:
33 node: The node to represent.
34 filepath: An optional filepath from where the node comes.
35
36 Returns:
37 The representing code for the node.
38 """
39 try:
40 return get_value(node)
41 except Exception as error: # noqa: BLE001
42 message = f"Failed to represent node {node}"
43 if filepath:
44 message += f" at {filepath}:{node.lineno}" # ty:ignore[unresolved-attribute]
45 message += f": {error}"
46 logger.exception(message)
47 return None