keleshev / schema

Schema validation just got Pythonic
MIT License
2.86k stars 214 forks source link

Is it possible to specify a Hook based on absent key? #274

Open redruin1 opened 2 years ago

redruin1 commented 2 years ago

Suppose I have some data with a key that is desired but not necessary:

some_data = {
    "required_key_1": [ ... ],
    "required_key_2": [ ... ],
    "optional_data": "expected and desired, but not absolutely needed"
}

I'd like to have it setup where if optional_data is absent, it calls a logging function outputting a warning (i.e. "Expected 'optional_data'; are you sure your data is valid?"). Of course, optional_data is not required and can be inferred if needed using Optional.

I'd like to setup a Hook to output this warning if the key is not present in the data, but Hook only seems to have a callback for if the key is detected. Is there any way to get this functionality? Something like:

schema = Schema({
    "required_key_1": list,
    "required_key_2": list,
    Expected("optional_data"): str # or Expected(Optional("optional_data"))
})