Pydantic: Support jsonschema's const keyword.

Created on 26 Mar 2019  路  7Comments  路  Source: samuelcolvin/pydantic

Feature Request

https://json-schema.org/latest/json-schema-validation.html#rfc.section.6.1.3

This is a very useful feature for when structural subtyping just doesn't quite cut it and you need to differentiate two semantically different but structurally identical types.

Some ways that this could be implemented:

class Foo(pydantic.BaseModel):
    bar: pydantic.Constant = "baz"
class Foo(pydantic.BaseModel):
    bar: pydantic.constant("baz")

Which would each generate the following schema:

{
    "title": "Foo",
    "type": "object",
    "properties": {
        "bar": {
            "title": "Bar",
            "const": "baz"
        }
    },
    "required": ["bar"]
}

I'm happy to put some work in for this, if it's something that you're willing to support.

feature request help wanted

Most helpful comment

Sounds good!

I can imagine something like:

class Foo(BaseModel):
    bar: str = Schema("baz", const=True)

All 7 comments

Happy to support it, but better to use the Schema(...) class than misusing types.

@tiangolo you did all the JSON schema work, any thoughts?

Sounds good!

I can imagine something like:

class Foo(BaseModel):
    bar: str = Schema("baz", const=True)

makes lots of sense.

BTW, I found the time to have a stab at this yesterday. I'm still not particularly familiar with the code base as a whole, so I might have gone about it in completely the wrong way, but it seems to work at the very least.

If I interpret right foo: str = Field('bar', const=True) results in bar being an optional property since it has a default. How could I make it required?

I have structurally identical types, and want a required name variable that is constant for each type.

foo: str = Field(..., const=True)

This is in the docs, please read them first.

That doesn't set the constant value to 'bar' as I had in my example, unless I misunderstand you.
foo: typing.Literal['bar'] seems to be what I was looking for.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

marlonjan picture marlonjan  路  37Comments

cazgp picture cazgp  路  34Comments

Yolley picture Yolley  路  18Comments

jaheba picture jaheba  路  25Comments

dmfigol picture dmfigol  路  38Comments