utils.py 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. import os
  2. from typing import Callable, Generic, TypeVar
  3. T = TypeVar("T")
  4. class cached_property(Generic[T]):
  5. """
  6. cached-property from https://github.com/pydanny/cached-property
  7. Add typing support
  8. A property that is only computed once per instance and then replaces itself
  9. with an ordinary attribute. Deleting the attribute resets the property.
  10. Source: https://github.com/bottlepy/bottle/commit/fa7733e075da0d790d809aa3d2f53071897e6f76
  11. """
  12. def __init__(self, func: Callable[..., T]):
  13. self.func = func
  14. def __get__(self, obj, cls) -> T:
  15. if obj is None:
  16. return self
  17. value = obj.__dict__[self.func.__name__] = self.func(obj)
  18. return value
  19. def iter_folder(folder, is_dir=False, ext=None):
  20. """
  21. Args:
  22. folder (str):
  23. is_dir (bool): True to iter directories only
  24. ext (str): File extension, such as `.yaml`
  25. Yields:
  26. str: Absolute path of files
  27. """
  28. try:
  29. files = os.listdir(folder)
  30. except FileNotFoundError:
  31. return
  32. for file in files:
  33. sub = os.path.join(folder, file)
  34. if is_dir:
  35. if os.path.isdir(sub):
  36. yield sub.replace('\\\\', '/').replace('\\', '/')
  37. elif ext is not None:
  38. if not os.path.isdir(sub):
  39. _, extension = os.path.splitext(file)
  40. if extension == ext:
  41. yield os.path.join(folder, file).replace('\\\\', '/').replace('\\', '/')
  42. else:
  43. yield os.path.join(folder, file).replace('\\\\', '/').replace('\\', '/')