How to use the datafiles.converters.Object.subclass function in datafiles

To help you get started, we’ve selected a few datafiles examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github jacebrowning / datafiles / datafiles / converters.py View on Github external
"""Infer the converter type from a dataclass, type, or annotation."""
    if name:
        log.debug(f'Mapping {name!r} of {cls!r} to converter')
    else:
        log.debug(f'Mapping {cls!r} to converter')

    if cls in _REGISTRY:
        converter: Any = _REGISTRY[cls]
        log.debug(f'Mapped {cls!r} to registered converter: {converter}')
        return converter

    if dataclasses.is_dataclass(cls):
        converters = {}
        for field in dataclasses.fields(cls):
            converters[field.name] = map_type(field.type, name=field.name)
        converter = Object.subclass(cls, converters)
        log.debug(f'Mapped {cls!r} to new converter: {converter}')
        return converter

    if hasattr(cls, '__origin__'):
        converter = None

        if cls.__origin__ == list:
            try:
                converter = map_type(cls.__args__[0])
            except TypeError as e:
                if '~T' in str(e):
                    e = TypeError(f"Type is required with 'List' annotation")
                raise e from None
            else:
                converter = List.subclass(converter)