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

cossatot opened this issue Oct 17, 2016 · 3 comments

Optional convert #105

cossatot opened this issue Oct 17, 2016 · 3 comments


Copy link

@cossatot cossatot commented Oct 17, 2016

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

Something like:

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.

Copy link

@Tinche 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.

Copy link

@cossatot cossatot commented Oct 18, 2016

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

Copy link

@hynek hynek commented Nov 20, 2016

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

@hynek hynek closed this in #173 May 10, 2017
hynek added a commit that referenced this issue May 10, 2017
Fixes #105
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
None yet
Linked pull requests

Successfully merging a pull request may close this issue.

None yet
3 participants