alecthomas / voluptuous

CONTRIBUTIONS ONLY: Voluptuous, despite the name, is a Python data validation library.
https://pypi.org/project/voluptuous
BSD 3-Clause "New" or "Revised" License
1.81k stars 219 forks source link

Switch suggestion #525

Open jgardiner68 opened 2 weeks ago

jgardiner68 commented 2 weeks ago

ChatGPT suggested that this was valid -- it looks wonderful:

from voluptuous import Schema, Required, All, Length, Switch, Invalid

# Define the schema with Switch
schema = Schema({
    'issuetype': str,
    Switch('issuetype', {
        'Feature Request': Schema({
            Required('feature_details'): All(str, Length(min=10)),
        }),
        'Bug': Schema({
            Required('bug_report'): All(str, Length(min=5)),
        }),
    }),
})
alecthomas commented 2 weeks ago

It's also invalid Python. Classic ChatGPT.

ds-cbo commented 2 weeks ago

I haven't tested this, but I think you're looking for something along the lines of

schema = Schema(Any(
    {
        'issuetype': Equal("Feature Request"),
        'feature_details": ...,
    },
    {
        'issuetype': Equal("Bug"),
        'bug_report': ...,
    },
))

which imho also looks a lot clearer than what ChatGPT suggested