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
« 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
5class PythonImport:
6 """Base class defining required methods of import dataclasses."""
8 def __init__(self):
9 ...
12class Import(PythonImport):
13 """Helper object that stringifies the python ast Import.
14 This is mainly to locally import things dynamically.
15 """
17 def __init__(self, modules: list[str]):
18 super().__init__()
19 self.modules = modules
21 @classmethod
22 def from_node(cls, imp) -> Import:
23 """Generates a new import object from a python ast Import.
25 Args:
26 imp (ast.Import): Python ast object
28 Returns:
29 Import: A new import object.
30 """
31 return Import([alias.name for alias in imp.names])
33 def __repr__(self) -> str:
34 return f"Import(modules=[{', '.join(self.modules)}])"
36 def __str__(self) -> str:
37 return f"import {', '.join(self.modules)}"
40class ImportFrom(PythonImport):
41 """Helper object that stringifies the python ast ImportFrom.
42 This is mainly to locally import things dynamically.
43 """
45 def __init__(self, module: str, names: list[str]):
46 super().__init__()
47 self.module = module
48 self.names = names
50 @classmethod
51 def from_node(cls, imp) -> Import:
52 """Generates a new import object from a python ast Import.
54 Args:
55 imp (ast.Import): Python ast object
57 Returns:
58 Import: A new import object.
59 """
60 return ImportFrom(imp.module, [alias.name for alias in imp.names])
62 def __repr__(self) -> str:
63 return f"ImportFrom(module='{self.module}', names=[{', '.join(self.names)}])"
65 def __str__(self) -> str:
66 return f"from {self.module} import {', '.join(self.names)}"