Coverage for phml\virtual_python\ImportObjects.py: 72%

29 statements  

« prev     ^ index     » next       coverage.py v6.5.0, created at 2022-11-30 09:38 -0600

1from __future__ import annotations 

2 

3 

4class PythonImport: 

5 def __init__(self): 

6 ... 

7 

8 def __str__(self) -> str: 

9 ... 

10 

11 def __repr__(self) -> str: 

12 ... 

13 

14 

15class Import(PythonImport): 

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

17 This is mainly to locally import things dynamically. 

18 """ 

19 

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

21 self.modules = modules 

22 

23 @classmethod 

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

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

26 

27 Args: 

28 imp (ast.Import): Python ast object 

29 

30 Returns: 

31 Import: A new import object. 

32 """ 

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

34 

35 def __repr__(self) -> str: 

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

37 

38 def __str__(self) -> str: 

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

40 

41 

42class ImportFrom(PythonImport): 

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

44 This is mainly to locally import things dynamically. 

45 """ 

46 

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

48 self.module = module 

49 self.names = names 

50 

51 @classmethod 

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

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

54 

55 Args: 

56 imp (ast.Import): Python ast object 

57 

58 Returns: 

59 Import: A new import object. 

60 """ 

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

62 

63 def __repr__(self) -> str: 

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

65 

66 def __str__(self) -> str: 

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