python-attrs / cattrs

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

Implement NoneType structuring. #406

Closed PIG208 closed 1 year ago

PIG208 commented 1 year ago

This is useful to have for custom structure hooks of union types that are also optional.

Tinche commented 1 year ago

I've been asked for this before and have been reluctant to add it since I don't want cattrs to become a kitchen sink and I've personally not needed it in the last 7 years (and I use cattrs a lot). Can you elaborate on the usecases you think it'd be helpful in?

PIG208 commented 1 year ago

I was using it when recursively calling converter.structure on the type args of Union. With this structure function I can do something like this:

def structure_union(value: object, target_type: Type[T]) -> T:
    type_args = get_args(targe t_type)
    errors = []
    for type_arg in type_args:
        try:
            return json_converter.structure(value, type_arg)
        except Exception as exc:
            errors.append(exc)
    raise UnionError(f"{value} cannot be structure as {target_type}", errors, target_type)

In hindsight, I think it is also quite easy to just special case NoneType or register a custom hook of my own. So it is not strictly necessary.