Coverage for phml\virtual_python\import_objects.py: 100%

27 statements  

« prev     ^ index     » next       coverage.py v6.5.0, created at 2022-12-08 15:02 -0600

1"""Dataclasses to hold information about python imports.""" 

2from __future__ import annotations 

3 

4 

5class PythonImport: 

6 """Base class defining required methods of import dataclasses.""" 

7 

8 def __init__(self): 

9 ... 

10 

11 

12class Import(PythonImport): 

13 """Helper object that stringifies the python ast Import. 

14 This is mainly to locally import things dynamically. 

15 """ 

16 

17 def __init__(self, modules: list[str]): 

18 super().__init__() 

19 self.modules = modules 

20 

21 @classmethod 

22 def from_node(cls, imp) -> Import: 

23 """Generates a new import object from a python ast Import. 

24 

25 Args: 

26 imp (ast.Import): Python ast object 

27 

28 Returns: 

29 Import: A new import object. 

30 """ 

31 return Import([alias.name for alias in imp.names]) 

32 

33 def __repr__(self) -> str: 

34 return f"Import(modules=[{', '.join(self.modules)}])" 

35 

36 def __str__(self) -> str: 

37 return f"import {', '.join(self.modules)}" 

38 

39 

40class ImportFrom(PythonImport): 

41 """Helper object that stringifies the python ast ImportFrom. 

42 This is mainly to locally import things dynamically. 

43 """ 

44 

45 def __init__(self, module: str, names: list[str]): 

46 super().__init__() 

47 self.module = module 

48 self.names = names 

49 

50 @classmethod 

51 def from_node(cls, imp) -> Import: 

52 """Generates a new import object from a python ast Import. 

53 

54 Args: 

55 imp (ast.Import): Python ast object 

56 

57 Returns: 

58 Import: A new import object. 

59 """ 

60 return ImportFrom(imp.module, [alias.name for alias in imp.names]) 

61 

62 def __repr__(self) -> str: 

63 return f"ImportFrom(module='{self.module}', names=[{', '.join(self.names)}])" 

64 

65 def __str__(self) -> str: 

66 return f"from {self.module} import {', '.join(self.names)}"