Coverage for src/_griffe/agents/nodes/imports.py: 100.00%

12 statements  

« prev     ^ index     » next       coverage.py v7.6.2, created at 2024-10-12 01:34 +0200

1# This module contains utilities for working with imports and relative imports. 

2 

3from __future__ import annotations 

4 

5from typing import TYPE_CHECKING 

6 

7if TYPE_CHECKING: 

8 import ast 

9 

10 from _griffe.models import Module 

11 

12 

13def relative_to_absolute(node: ast.ImportFrom, name: ast.alias, current_module: Module) -> str: 

14 """Convert a relative import path to an absolute one. 

15 

16 Parameters: 

17 node: The "from ... import ..." AST node. 

18 name: The imported name. 

19 current_module: The module in which the import happens. 

20 

21 Returns: 

22 The absolute import path. 

23 """ 

24 level = node.level 

25 if level > 0 and current_module.is_package or current_module.is_subpackage: 

26 level -= 1 

27 while level > 0 and current_module.parent is not None: 

28 current_module = current_module.parent # type: ignore[assignment] 

29 level -= 1 

30 base = current_module.path + "." if node.level > 0 else "" 

31 node_module = node.module + "." if node.module else "" 

32 return base + node_module + name.name