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

Optional convert #105

Closed
cossatot opened this issue Oct 17, 2016 · 3 comments
Closed

Optional convert #105

cossatot opened this issue Oct 17, 2016 · 3 comments

Comments

@cossatot
Copy link

Is it, or could it be, possible to have optional type conversion using the convert argument, with the same logic as validation?

Something like:

@attr.s
class Thing(object):
    x = attr.ib(default=None, convert=optional(float), validator=optional(validate_x))

Apologies if it's already supported; I just don't see how in the docs.

@Tinche
Copy link
Member

Tinche commented Oct 17, 2016

You can write this yourself, easily (and I have in one of my projects):

def opt(convert):
    """Invoke the subconverter only if the value is present."""
    def optional_converter(val):
        if val is None:
            return None
        return convert(val)
    return optional_converter

Now, I don't think it'd be possible to use the same callable (optional) as a validator factory AND a convert factory without changes to attrs itself.

@cossatot
Copy link
Author

Thanks, that's exactly what i was looking for.

@hynek
Copy link
Member

hynek commented Nov 20, 2016

I guess it would make sense to add it to attrs?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

3 participants