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

Change schema for one key based on value of another key #321

Open
DaveKLloyd opened this issue Jul 12, 2024 · 2 comments
Open

Change schema for one key based on value of another key #321

DaveKLloyd opened this issue Jul 12, 2024 · 2 comments

Comments

@DaveKLloyd
Copy link

DaveKLloyd commented Jul 12, 2024

I would like to make some keys Optional based on the value of another key. For example:

some_things:
      access: true
      option1: "option"
      option2: "other option"

If access = true option1 and option2 need to be there, if access is false those keys are optional. Actually they are useless, so not necessary.
I guess it doesn't have to be optional perhaps I could use ignore_extra_keys if access is false.

Can this be done. I have tried a bunch of things and no luck yet.

@mutricyl
Copy link

Would the following fit your needs ?

from schema import Schema, Or

schema = Schema({'some_things': Or({'access': True,
                                    'option1': str,
                                    'option2': str,
                                    },
                                   {'access': False})})

schema.validate({'some_things': {'access': False}}) # OK
schema.validate({'some_things': {'access': True,
                                 'option1': 'foo',
                                 'option2': 'bar'}}) # OK

schema.validate({'some_things': {'access': False,
                                 'option1': 'foo',
                                 'option2': 'bar'}}) # SchemaError

@DaveKLloyd
Copy link
Author

Awesome thanks, this works great.

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