You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

find_class_in_file.py 2.3 kB

4 years ago
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. """
  2. Copyright 2020 Tianshu AI Platform. All Rights Reserved.
  3. Licensed under the Apache License, Version 2.0 (the "License");
  4. you may not use this file except in compliance with the License.
  5. You may obtain a copy of the License at
  6. http://www.apache.org/licenses/LICENSE-2.0
  7. Unless required by applicable law or agreed to in writing, software
  8. distributed under the License is distributed on an "AS IS" BASIS,
  9. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. See the License for the specific language governing permissions and
  11. limitations under the License.
  12. """
  13. import re
  14. import inspect
  15. # from ac_opf.models import ac_model
  16. class FindClassInFile:
  17. """
  18. find class in the given module
  19. ### note ###
  20. There is only one class in the given module.
  21. If there are more than one classes, all of them will be omit except the first
  22. ############
  23. method: find
  24. args:
  25. module: object-> the given file or module
  26. encoding: string-> "utf8" by default
  27. output: tuple(string-> name of the class, object-> class)
  28. usage:
  29. # >>> import module
  30. #
  31. # >>> find_class_in_file = FindClassInFile()
  32. # >>> cls = find_class_in_file.find(module)
  33. #
  34. # >>> cls_instance = cls[1](args)
  35. """
  36. def __init__(self):
  37. pass
  38. def _open_file(self, path, encoding="utf8"):
  39. with open(path, "r", encoding=encoding) as f:
  40. data = f.readlines()
  41. for line in data:
  42. yield line
  43. def find(self, module, encoding="utf8"):
  44. path = module.__file__
  45. lines = self._open_file(path=path, encoding=encoding)
  46. cls = ""
  47. for line in lines:
  48. if "class " in line:
  49. cls = re.findall("class (.*?)[:(]", line)[0]
  50. if cls:
  51. break
  52. return self._valid(module, cls)
  53. def _valid(self, module, cls):
  54. members = inspect.getmembers(module)
  55. cand = [(i, j) for i, j in members if inspect.isclass(j) and (not inspect.isabstract(j)) and (i == cls)]
  56. if not cand:
  57. print("class not found in {}".format(module))
  58. return cand[0]
  59. if __name__ == "__main__":
  60. find_class_in_file = FindClassInFile()
  61. # cls = find_class_in_file.find(ac_model)
  62. # print(cls)

一站式算法开发平台、高性能分布式深度学习框架、先进算法模型库、视觉模型炼知平台、数据可视化分析平台等一系列平台及工具,在模型高效分布式训练、数据处理和可视分析、模型炼知和轻量化等技术上形成独特优势,目前已在产学研等各领域近千家单位及个人提供AI应用赋能