Coverage for src/_griffe/agents/nodes/values.py: 53.57%

22 statements  

« prev     ^ index     » next       coverage.py v7.6.1, created at 2024-08-15 16:47 +0200

1# This module contains utilities for extracting attribute values. 

2 

3from __future__ import annotations 

4 

5import ast 

6import sys 

7from typing import TYPE_CHECKING 

8 

9from _griffe.logger import logger 

10 

11# YORE: EOL 3.8: Replace block with line 4. 

12if sys.version_info < (3, 9): 

13 from astunparse import unparse 

14else: 

15 from ast import unparse 

16 

17if TYPE_CHECKING: 

18 from pathlib import Path 

19 

20 

21def get_value(node: ast.AST | None) -> str | None: 

22 """Get the string representation of a node. 

23 

24 Parameters: 

25 node: The node to represent. 

26 

27 Returns: 

28 The representing code for the node. 

29 """ 

30 if node is None: 30 ↛ 31line 30 didn't jump to line 31 because the condition on line 30 was never true

31 return None 

32 return unparse(node) 

33 

34 

35def safe_get_value(node: ast.AST | None, filepath: str | Path | None = None) -> str | None: 

36 """Safely (no exception) get the string representation of a node. 

37 

38 Parameters: 

39 node: The node to represent. 

40 filepath: An optional filepath from where the node comes. 

41 

42 Returns: 

43 The representing code for the node. 

44 """ 

45 try: 

46 return get_value(node) 

47 except Exception as error: # noqa: BLE001 

48 message = f"Failed to represent node {node}" 

49 if filepath: 

50 message += f" at {filepath}:{node.lineno}" # type: ignore[union-attr] 

51 message += f": {error}" 

52 logger.exception(message) 

53 return None