From b4013d720a13e14c5bb753cb8fac9f220d38028f Mon Sep 17 00:00:00 2001 From: Casper Welzel Andersen Date: Tue, 28 May 2024 14:46:46 +0200 Subject: [PATCH] Return existing class from generated_classes This is from `create_entity()`. If an existing class already exists in the `generated_classes` module, it is investigated whether the `entity` attribute matches the current entity, if yes, the class is returned, if no to any of those conditions a ValueError is raised. In the future, one could either extend the naming conventions of these classes to include more and more "parts" of the identity in order to get uniqueness, supporting having entity instance classes for the same entity with different versions. --- s7/factories/entity_factory.py | 26 ++++++++++++++++++++++++++ 1 file changed, 26 insertions(+) diff --git a/s7/factories/entity_factory.py b/s7/factories/entity_factory.py index 5f57c3e..416fd21 100644 --- a/s7/factories/entity_factory.py +++ b/s7/factories/entity_factory.py @@ -50,6 +50,9 @@ def create_entity( ) -> type[SOFT7EntityInstance]: """Create and return a SOFT7 entity as a pydantic model. + If the entity instance class has already been created, it will be returned + as is from the `generated_classes` module. + Parameters: entity: A SOFT7 entity (data model) or a string/path to a YAML file of the entity. @@ -66,6 +69,29 @@ def create_entity( # Split the identity into its parts _, _, name = parse_identity(entity.identity) + # Check if the entity has already been created + existing_cls: type[SOFT7EntityInstance] | None = getattr( + module_namespace, f"{name.replace(' ', '')}Entity", None + ) + + if existing_cls and issubclass(existing_cls, SOFT7EntityInstance): + # Check the existing class' entity attribute + if existing_cls.entity == entity: + LOGGER.debug("The %s entity class already exists.", name) + return existing_cls + raise ValueError( + f"The {name} entity class already exists, but with a different SOFT7 " + "entity." + ) + + if existing_cls: + raise ValueError( + f"The {name} entity class already exists, but is not a SOFT7EntityInstance " + "type." + ) + + LOGGER.debug("Creating the %s entity class anew.", name) + # Create the entity model's dimensions dimensions: dict[str, tuple[Union[type[Optional[int]], object], Any]] = ( # Value must be a (, ) or (, ) tuple