schema icon indicating copy to clipboard operation
schema copied to clipboard

Change schema for one key based on value of another key

Open DaveKLloyd opened this issue 1 year ago • 2 comments

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.

DaveKLloyd avatar Jul 12 '24 13:07 DaveKLloyd

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

mutricyl avatar Jul 13 '24 11:07 mutricyl

Awesome thanks, this works great.

DaveKLloyd avatar Jul 15 '24 16:07 DaveKLloyd

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.

Glad you found a way, but it sounds like you want the same thing that I wanted: https://github.com/keleshev/schema/issues/325

HorridModz avatar Aug 13 '25 21:08 HorridModz