_entity.py 1.5 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. from typing import List
  12. from .._entity._reload import _Reloader
  13. from ..notification import Notifier
  14. class _Entity:
  15. _ID_PREFIX: str
  16. _MANAGER_NAME: str
  17. _is_in_context = False
  18. _in_context_attributes_changed_collector: List
  19. def __enter__(self):
  20. self._is_in_context = True
  21. self._in_context_attributes_changed_collector = []
  22. return self
  23. def __exit__(self, exc_type, exc_value, exc_traceback):
  24. # If multiple entities is in context, the last to enter will be the first to exit
  25. self._is_in_context = False
  26. if hasattr(self, "_properties"):
  27. for to_delete_key in self._properties._pending_deletions:
  28. self._properties.data.pop(to_delete_key, None)
  29. self._properties.data.update(self._properties._pending_changes)
  30. _Reloader()._get_manager(self._MANAGER_NAME)._set(self)
  31. for event in self._in_context_attributes_changed_collector:
  32. Notifier.publish(event)