Source code for esrf_pathlib._schemas.fields.derived
from typing import Callable
from typing import Dict
from typing import List
from typing import Optional
from .. import errors
from ..definitions.types import ConceptValueType
from ..identifier import SchemaIdentifier
from .base import Field
[docs]
class DerivedConcept(Field):
"""A concept not parsed from the path, but computed from other concepts."""
def __init__(
self,
name: str,
description: str,
schema_identifier: SchemaIdentifier,
derive_func: Callable[[Dict[str, ConceptValueType]], ConceptValueType],
derived_from: List[str],
examples: Optional[List[str]] = None,
):
super().__init__(
name=name,
description=description,
schema_identifier=schema_identifier,
value_generator=derive_func,
examples=examples,
)
self._derive_func = derive_func
self._derived_from = derived_from
[docs]
def derive(
self, concept_values: Dict[str, ConceptValueType], raise_on_missing: bool = True
) -> ConceptValueType:
"""
:raises PathConceptValueError:
"""
try:
values = dict()
for cname in self._derived_from:
if cname not in concept_values:
raise errors.PathConceptWithoutValue(cname)
values[cname] = concept_values[cname]
return self._derive_func(values)
except Exception as ex:
if raise_on_missing:
raise errors.PathConceptMatchError(self.name) from ex
return "*"