get_imported_var.py 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839
  1. # Copyright 2021-2024 Avaiga Private Limited
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
  4. # the License. You may obtain a copy of the License at
  5. #
  6. # http://www.apache.org/licenses/LICENSE-2.0
  7. #
  8. # Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
  9. # an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
  10. # specific language governing permissions and limitations under the License.
  11. import ast
  12. import inspect
  13. import typing as t
  14. from types import FrameType
  15. from .get_module_name import _get_absolute_module_name_from_ast, _get_module_name_from_frame
  16. def _get_imported_var(frame: FrameType) -> t.List[t.Tuple[str, str, str]]:
  17. st = ast.parse(inspect.getsource(frame))
  18. var_list: t.List[t.Tuple[str, str, str]] = []
  19. for node in ast.walk(st):
  20. if isinstance(node, ast.ImportFrom):
  21. # get the imported element as (name, asname, module)
  22. # ex: from module1 import a as x --> ("a", "x", "module1")
  23. frame_module_name = _get_module_name_from_frame(frame)
  24. node_module_name = ""
  25. if node.module and frame_module_name:
  26. node_module_name = _get_absolute_module_name_from_ast(str(frame_module_name), node.module, node.level)
  27. var_list.extend(
  28. (
  29. child_node.name,
  30. child_node.asname if child_node.asname is not None else child_node.name,
  31. node_module_name,
  32. )
  33. for child_node in node.names
  34. )
  35. return var_list