-
-
Notifications
You must be signed in to change notification settings - Fork 10
Description
I know the primary reason for this library was to improve the error messages when validating config files, not to reinvent the way that these files are validated. Nevertheless, I think a really neat addition to this codebase would be if API functions like validate
, load_from_file
returned a mypy type-hinted version of the value based on the schema. Since we are already validating at runtime, it makes sense to statically validate the config afterwards.
Put simply, if I have some simple schema:
SCHEMA= cfgv.Map(
"Person",
"name",
cfgv.Required("name", cfgv.check_string),
cfgv.OptionalNoDefault("age", cfgv.check_int),
cfgv.NoAdditionalKeys(["name", "age"]),
)
Then I would like the signature of validate
to be like:
from typing import NamedTuple
class Person(NamedTuple):
name: str
age: int | None
def validate(value: Any, schema: ...) -> Person:
# do the validation
cast(Person, value)
return value
... for example. This means that once a value has passed through the cfgv.validate
function, it is now statically typed in code and mypy can take it from there. Obviously, I could just cast the result of validate to whatever type I like, however this duplicates the schema definition - once when I write cfgv.Required("name", cfgv.check_string)
and then again when I write name: str
.
Is this even possible?