How do I get pydantic to report a violation if a YAML mapping to an optional attribute omits the space after the colon?

  Kiến thức lập trình

The assertion at the end of the following code fails because there is no space between walk and True in the yaml:

from pydantic import BaseModel
from pydantic_yaml import parse_yaml_raw_as
from typing import List

class path_cls (BaseModel):
    path : str
    walk : bool = False
    other : bool = False

class myschema (BaseModel):
    paths: List[path_cls]

y = """
---
paths:
- {path: .., walk:True }
- {path: ../../somefolder }
"""

data = parse_yaml_raw_as(myschema, y)
assert data.paths[0].walk

Since walk:True represents a valid YAML scalar, and because walk is an optional attribute in path_cls, neither the parser nor the validator see a problem.

In my schema, there will never be a case where {key:value, scalar} makes sense.

How do I get pydantic to recognize walk:True as an error? And is there a general solution that would flag a bad mapping of any optional attribute?

LEAVE A COMMENT