python-attrs / cattrs

Composable custom class converters for attrs, dataclasses and friends.
https://catt.rs
MIT License
791 stars 110 forks source link

Preconfigured union for a "plain" python data structures #554

Open salotz opened 1 month ago

salotz commented 1 month ago

There are preconfigured converters for the various serialization formats, but I have found need for a converter specific to what I will call "plain" Python.

Basically:

PassThroughTypes: TypeAlias = str | bool | int | float | bytes | None

def python_make_converter(
    *args: Any,
    **kwargs: Any,
) -> PythonConverter:

    # configure specific overrides for this converter
    kwargs["unstruct_collection_overrides"] = {
        # rich built-in types are maintained, rather than all dumped
        # into lists
        Sequence: tuple,
        MutableSequence: list,
        Set: frozenset,
        MutableSet: set,
        Counter: lambda c: Counter(**{k: v for k, v in c}),
    }

    converter = PythonConverter(*args, **kwargs)

    # passthrough union types
    configure_union_passthrough(PassThroughTypes, converter)

    return converter

Just some context for what I am doing that warranted making this concrete versus the more plain cattrs.global_converter. I am using the converter to generate "patches" that all happens within Python and the above to be very useful.

I would propose that a new preconfigured converter be made similar to the others. But I can understand it not being high priority, in which case this issue may help someone else :)