Source code for esrf_pathlib._schemas.fields.concept

from typing import Any
from typing import Callable
from typing import List
from typing import Optional
from typing import Type
from typing import Union

from .. import errors
from ..definitions.types import ConceptValueType
from ..identifier import SchemaIdentifier
from .base import Field


[docs] class PathConcept(Field): """Concept that is part of an ESRF path. For example beamline, proposal, collection, etc.""" def __init__( self, name: str, description: str, schema_identifier: SchemaIdentifier, regex: str, deserializer: Union[Callable[[str], ConceptValueType], Type[Any]] = str, serializer: Union[Callable[[ConceptValueType], str], Type[Any]] = str, score: int = 1, default_value: Any = None, examples: Optional[List[str]] = None, ): """ :param name: name used in path template placeholders :param description: for documentation :param schema_identifier: schema that defines the concept (could be used in other schemas) :param regex: value use in path template placeholders :param deserializer: convert the string value used in the path to a python object (default: ``str``) :param serializer: convert a python object to the string value used in the path (default: ``str``) :param score: score used when calculating a matching score between a path template and a path string or concept value dict :param default_value: used when generating a path from a concept value dict """ super().__init__( name=name, description=description, schema_identifier=schema_identifier, value_generator=deserializer, value_serializer=serializer, examples=examples, ) self._description = description self._regex = regex self._deserializer = deserializer self._serializer = serializer self._score = score self._default_value = default_value @property def regex(self) -> str: return self._regex @property def score(self) -> int: return self._score
[docs] def deserialize(self, string_value: Optional[str]) -> ConceptValueType: """String value used in the path to Python object. :raises PathConceptMatchError: """ if string_value is None: return None try: return self._deserializer(string_value) except Exception as ex: raise errors.PathConceptMatchError( f"{self.name!r} deserialization failed for {string_value!r}" ) from ex
[docs] def serialize( self, py_value: ConceptValueType, raise_on_missing: bool = True ) -> str: """Python object to string value used in the path. When missing and ``raise_on_missing=False`` the value ``"*"`` is returned. :raises PathConceptValueError: """ if py_value is None: if raise_on_missing: raise errors.PathConceptWithoutValue(f"{self.name!r} is not defined") return "*" try: return self._serializer(py_value) except Exception as ex: raise errors.PathConceptMatchError( f"{self.name!r} serialization failed for {py_value}" ) from ex