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

Flag attribute as required / mandatory #490

Closed
elgalu opened this issue Jun 4, 2018 · 2 comments
Closed

Flag attribute as required / mandatory #490

elgalu opened this issue Jun 4, 2018 · 2 comments

Comments

@elgalu
Copy link
Contributor

elgalu commented Jun 4, 2018

Hi, thanks for this very useful library!

How do I flag attribute as required / mandatory?

I have this:

from traitlets import HasTraits, Unicode, TraitError, validate

class MyS3Class(HasTraits):
    s3_bucket_name = Unicode()

    @validate('s3_bucket_name')
    def _check(self, proposal):
        raise TraitError("this doesn't trigger unless explicit non empty string is set")

But @validate('s3_bucket_name') doesn't get triggered if the user doesn't pass a value.

object = MyS3Class()
# FAIL: doesn't trigger _check()

object = MyS3Class(s3_bucket_name='')
# FAIL: doesn't trigger _check()

object = MyS3Class(s3_bucket_name=' ')
# OK: properly triggers _check()
@elgalu
Copy link
Contributor Author

elgalu commented Jun 4, 2018

For now I will "manually" trigger validations via:

class MyS3Class(HasTraits):
    def __init__(self, **kwargs):
        super(MyS3Class, self).__init__(**kwargs)
        self.s3_bucket_name = self.s3_bucket_name

@rmorshea
Copy link
Contributor

rmorshea commented Apr 4, 2019

@elgalu I would do the following:

class MyS3Class(HasTraits):
    
    s3_bucket_name = Unicode()

    @validate("s3_bucket_name")
    def _validate_s3_bucket_name(self, proposal):
        if not proposal.value:
            raise ValueError("S3 bucket name cannot be empty.")

    def __init__(self, s3_bucket_name, **kwargs):
        super().__init__(**kwargs)
        self.s3_bucket_name = s3_bucket_name

This both enforces the fact that the trait must be provided when instantiated and that it not be empty.

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

No branches or pull requests

2 participants