reasons.py 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  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. from typing import Dict, Set
  12. from .reason import Reason
  13. class ReasonCollection:
  14. """
  15. This class is used to store all the reasons to explain why some Taipy operations are not allowed.
  16. Because Taipy applications are natively multiuser, asynchronous, and dynamic,
  17. some functions might not be called in some specific contexts. You can protect
  18. such calls by calling other methods that return a Reasons object. It acts like a
  19. boolean: True if the operation can be performed and False otherwise.
  20. If the action cannot be performed, the Reasons object holds all the `reasons as a list
  21. of `Reason` objects. Each `Reason` holds an explanation of why the operation cannot be
  22. performed.
  23. """
  24. def __init__(self) -> None:
  25. self._reasons: Dict[str, Set[Reason]] = {}
  26. def _add_reason(self, entity_id: str, reason: Reason) -> "ReasonCollection":
  27. if entity_id not in self._reasons:
  28. self._reasons[entity_id] = set()
  29. self._reasons[entity_id].add(reason)
  30. return self
  31. def _remove_reason(self, entity_id: str, reason: Reason) -> "ReasonCollection":
  32. if entity_id in self._reasons and reason in self._reasons[entity_id]:
  33. self._reasons[entity_id].remove(reason)
  34. if len(self._reasons[entity_id]) == 0:
  35. del self._reasons[entity_id]
  36. return self
  37. def _entity_id_exists_in_reason(self, entity_id: str) -> bool:
  38. return entity_id in self._reasons
  39. def __bool__(self) -> bool:
  40. return len(self._reasons) == 0
  41. @property
  42. def reasons(self) -> str:
  43. """Retrieves a collection of reasons as a string that explains why the action cannot be performed.
  44. Returns:
  45. A string that contains all the reasons why the action cannot be performed.
  46. """
  47. if self._reasons:
  48. return "; ".join("; ".join([str(reason) for reason in reasons]) for reasons in self._reasons.values()) + "."
  49. return ""