MatrixEditor / caterpillar

A Python 3.12+ library to pack and unpack structured binary data.
https://matrixeditor.github.io/caterpillar/
GNU General Public License v3.0
16 stars 0 forks source link

[DEV] Annotation Registry #16

Closed MatrixEditor closed 1 day ago

MatrixEditor commented 1 day ago

Version 2.2.2 adds a new feature called "Annotation Registry", which will be responsible for storing converters for annotation values.

Example: implementation of automatic struct conversion

from caterpillar import registry

class StructTypeConverter(registry.TypeConverter): # new class to implement custom matching algorithm
    def matches(self, annotation: Any) -> bool:
        # the annotation must be a type and the __struct__ attribute must be present
        return isinstance(annotation, type) and getstruct(annotation) is not None

    def convert(self, annotation: Any, kwargs: dict) -> _StructLike:
        return getstruct(annotation) # won't return None, because of previous condition

# finally, add the new converter to existing ones
registry.annotation_registry.append(StructTypeConverter())

Fixes #15