Skip to content

hololinked.metadata.td.interaction_affordance.PropertyAffordance

Bases: DataSchema, InteractionAffordance, PropertyMetadata

Implements property affordance schema from Property descriptor object.

Schema
UML Diagram

Source code in repo/hololinked/hololinked/metadata/td/interaction_affordance.py
class PropertyAffordance(DataSchema, InteractionAffordance, PropertyMetadata):
    """
    Implements property affordance schema from `Property` descriptor object.

    [Schema](https://www.w3.org/TR/wot-thing-description11/#propertyaffordance) <br>
    [UML Diagram](https://docs.hololinked.dev/UML/PDF/InteractionAffordance.pdf) <br>
    """

    # [Supported Fields]() <br>
    observable: bool | None = None

    def __init__(self):
        super().__init__()

    @property
    def what(self) -> Enum:  # noqa: D102
        return ResourceTypes.PROPERTY

    @property
    def event_unique_identifier(self) -> str:
        """Unique identifier for the change event of an observable property."""
        return f"{self.thing_id}/{self.name}_change_event"

    def build(self) -> None:  # noqa: D102
        property = cast(Property, self.objekt)
        self.ds_build_from_property(property)
        if property.observable:
            self.observable = property.observable

    @classmethod
    def from_descriptor(cls, property: Property, owner: Thing | ThingMeta) -> PropertyAffordance:  # noqa: D102
        if not isinstance(property, Property):
            raise TypeError(f"property must be instance of Property, given type {type(property)}")
        affordance = PropertyAffordance()
        affordance.owner = owner
        affordance.objekt = property
        affordance.build()
        affordance.build_non_compliant_metadata()
        return affordance

    def to_descriptor(
        self,
        fget: Callable | None = None,
        fset: Callable | None = None,
        delegate: PropertyDelegate | None = None,
        validator: str = "pydantic",
    ) -> Property:
        """
        Create the `Property` this affordance describes.

        Parameters
        ----------
        fget: Callable, optional
            read handler, the value is stored on the `Thing` instance if not given
        fset: Callable, optional
            write handler, receives the validated value
        delegate: PropertyDelegate, optional
            reads and writes an attribute of another object, used instead of `fget` and `fset`
        validator: str
            name the validator of the value is registered under with `SchemaValidators`

        Returns
        -------
        Property
            the descriptor, not yet assigned to a class

        Raises
        ------
        ValueError
            if the value is stored (no `fget` or `delegate`) but the affordance gives no starting value, neither a
            `default` nor a `null` option
        """
        affordance = self.json()  # we need to convert to JSON because
        # dataschema validation of API first approach proceeds through a JSON schema validator
        # looks sort of circular, something to think about later.
        keywords = WoTSchema.declared_fields(DataSchema, skip_subclasses=(PropertyAffordance,))
        # a property-level const makes the property constant instead of constraining writes
        data_schema = {key: value for key, value in affordance.items() if key in keywords and key != "const"}
        # a null option allows None, the remaining options are the schema of the value
        options = data_schema.pop("oneOf", [])
        nullable = any(option.get("type") == "null" for option in options)
        options = [option for option in options if option.get("type") != "null"]
        if len(options) == 1:
            data_schema.update(options[0])
        elif options:
            data_schema["oneOf"] = options
        default = affordance.get("default", affordance.get("const"))
        constant = "const" in affordance
        if fget is None and delegate is None and default is None and not (nullable or constant):
            raise ValueError(f"property {self.name} needs a default or a null option in its schema")
        if self.writeOnly:
            warnings.warn(
                f"writeOnly of property {self.name} is not supported and is ignored",
                UserWarning,
                stacklevel=2,
            )
        model, _validator = None, None
        if data_schema:
            model, _validator = schema_validator(data_schema, f"{self.name}_value", validator)
        _property = Property(
            default=default,
            doc=self.description,
            label=self.title,
            constant=constant,
            readonly=bool(self.readOnly),
            allow_None=nullable,
            observable=bool(self.observable),
            model=model,
            fget=fget,
            fset=fset,
            delegate=delegate,
            deepcopy_default=isinstance(default, (dict, list)),
            metadata={"unit": self.unit} if self.unit is not None else None,
        )
        # override the builtin validator although it might be the same.
        _property._schema_validator = _validator
        return _property

Attributes

event_unique_identifier property

event_unique_identifier: str

Unique identifier for the change event of an observable property.

Functions

to_descriptor

to_descriptor(fget: Callable | None = None, fset: Callable | None = None, delegate: PropertyDelegate | None = None, validator: str = 'pydantic') -> Property

Create the Property this affordance describes.

Parameters:

Name Type Description Default

fget

Callable | None

read handler, the value is stored on the Thing instance if not given

None

fset

Callable | None

write handler, receives the validated value

None

delegate

PropertyDelegate | None

reads and writes an attribute of another object, used instead of fget and fset

None

validator

str

name the validator of the value is registered under with SchemaValidators

'pydantic'

Returns:

Type Description
Property

the descriptor, not yet assigned to a class

Raises:

Type Description
ValueError

if the value is stored (no fget or delegate) but the affordance gives no starting value, neither a default nor a null option

Source code in repo/hololinked/hololinked/metadata/td/interaction_affordance.py
def to_descriptor(
    self,
    fget: Callable | None = None,
    fset: Callable | None = None,
    delegate: PropertyDelegate | None = None,
    validator: str = "pydantic",
) -> Property:
    """
    Create the `Property` this affordance describes.

    Parameters
    ----------
    fget: Callable, optional
        read handler, the value is stored on the `Thing` instance if not given
    fset: Callable, optional
        write handler, receives the validated value
    delegate: PropertyDelegate, optional
        reads and writes an attribute of another object, used instead of `fget` and `fset`
    validator: str
        name the validator of the value is registered under with `SchemaValidators`

    Returns
    -------
    Property
        the descriptor, not yet assigned to a class

    Raises
    ------
    ValueError
        if the value is stored (no `fget` or `delegate`) but the affordance gives no starting value, neither a
        `default` nor a `null` option
    """
    affordance = self.json()  # we need to convert to JSON because
    # dataschema validation of API first approach proceeds through a JSON schema validator
    # looks sort of circular, something to think about later.
    keywords = WoTSchema.declared_fields(DataSchema, skip_subclasses=(PropertyAffordance,))
    # a property-level const makes the property constant instead of constraining writes
    data_schema = {key: value for key, value in affordance.items() if key in keywords and key != "const"}
    # a null option allows None, the remaining options are the schema of the value
    options = data_schema.pop("oneOf", [])
    nullable = any(option.get("type") == "null" for option in options)
    options = [option for option in options if option.get("type") != "null"]
    if len(options) == 1:
        data_schema.update(options[0])
    elif options:
        data_schema["oneOf"] = options
    default = affordance.get("default", affordance.get("const"))
    constant = "const" in affordance
    if fget is None and delegate is None and default is None and not (nullable or constant):
        raise ValueError(f"property {self.name} needs a default or a null option in its schema")
    if self.writeOnly:
        warnings.warn(
            f"writeOnly of property {self.name} is not supported and is ignored",
            UserWarning,
            stacklevel=2,
        )
    model, _validator = None, None
    if data_schema:
        model, _validator = schema_validator(data_schema, f"{self.name}_value", validator)
    _property = Property(
        default=default,
        doc=self.description,
        label=self.title,
        constant=constant,
        readonly=bool(self.readOnly),
        allow_None=nullable,
        observable=bool(self.observable),
        model=model,
        fget=fget,
        fset=fset,
        delegate=delegate,
        deepcopy_default=isinstance(default, (dict, list)),
        metadata={"unit": self.unit} if self.unit is not None else None,
    )
    # override the builtin validator although it might be the same.
    _property._schema_validator = _validator
    return _property

TD Supported Fields

Apart from the fields supported InteractionAffordance and DataSchema, the following is supported

field supported meaning default usage
observable ✔️ true if Property pushes change events Property.observable value