Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Implement NoneType structuring. #406

Closed
wants to merge 1 commit into from
Closed

Conversation

PIG208
Copy link
Contributor

@PIG208 PIG208 commented Aug 4, 2023

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

This is useful to have for custom structure hooks of union types
that are also optional.
@Tinche
Copy link
Member

Tinche commented Aug 4, 2023

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
Copy link
Contributor Author

PIG208 commented Aug 4, 2023

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.

@PIG208 PIG208 closed this Aug 5, 2023
@PIG208 PIG208 deleted the nonetype branch August 5, 2023 22:19
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants