builder.py 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. class builder:
  2. """
  3. This is class responsible for building new items for database.
  4. """
  5. def __init__(self, target: object = None) -> None:
  6. """
  7. This create new builder, cleaning it by default.
  8. Parameters:
  9. target (object<target_type>): Object to work on
  10. """
  11. self.clear(target)
  12. @property
  13. def _target(self) -> object:
  14. """ Target to work on for child class. """
  15. return self.__target
  16. @property
  17. def result(self) -> object:
  18. """
  19. This return created object, or raise exception if it is not ready.
  20. Returns:
  21. (object<target_type>): Ready created object
  22. """
  23. if not self.__target.ready:
  24. raise TypeError("Can not read not ready result.")
  25. return self.__target
  26. def clear(self, target: object = None) -> None:
  27. """
  28. This drop previous object from builded, and set new one. When target
  29. is not set, it create empty object to work on.
  30. Parameters:
  31. target (object<target_type> | None): Target to work on or None
  32. """
  33. if target is not None:
  34. self.__target = target
  35. return
  36. self.__target = self.__target_type()
  37. def __init_subclass__(cls, target_type: type, **kwargs) -> None:
  38. """
  39. This create new class. It require target_type, which is class of new
  40. objects. It must have ready property, to check when new object is
  41. ready to load.
  42. Parameters:
  43. target_type(type): Type of target objects
  44. **kwargs: Rest of parameters
  45. """
  46. super().__init_subclass__(**kwargs)
  47. if not type(target_type.ready) is property:
  48. raise Exception("Builder can build only database items.")
  49. cls.__target_type = target_type