cms-nanoAOD / correctionlib

A generic correction library
https://cms-nanoaod.github.io/correctionlib/
BSD 3-Clause "New" or "Revised" License
16 stars 20 forks source link

Runtime validator checks #6

Open IzaakWN opened 3 years ago

IzaakWN commented 3 years ago

The current pydantic Models are useful to create valid JSON files. One could add some more basic checks during generation, like checking

pydantic provides validator methods, e.g.

class Binning(Model):
    nodetype: Literal["binning"]
    input: str
    edges: List[float]
    "Edges of the binning, where edges[i] <= x < edges[i+1] => f(x, ...) = content[i](...)"
    content: List[Content]

    @validator('edges')
    def validate_edges(cls,edges,values):
        for i, lowedge in enumerate(edges[:-1]):
          if lowedge>=edges[i+1]:
            raise ValueError("bin edges not in increasing order: %s"%(edges))
        return edges

    @validator('content')
    def match_content_bins(cls,content,values):
        if 'edges' in values:
          nbins = len(values['edges'])-1
          if len(content)!=nbins:
            raise ValueError("number of content elements (%s) must match number of bins (%s)"%(len(content),nbins))
        return content

or one could override __init__. More examples are here. (pydantic errors are quite verbose, so I added some highlighting.)

nsmith- commented 3 years ago

This is a great addition. If you are willing, feel free to make a PR with the validators you wrote.