-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathregistry.py
38 lines (25 loc) · 1.12 KB
/
registry.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
"""Registry of validators to run on the header."""
from collections.abc import Callable
from pydantic import BaseModel
VALIDATORS_REGISTRY: dict[str, type[BaseModel]] = {}
"""Registry of validators to run on the header."""
def register_validator(
name: str, overwrite: bool = False
) -> Callable[[type[BaseModel]], type[BaseModel]]:
"""Register a validator in the registry.
This function is a decorator that registers a validator in the registry. The name
of the validator is used as the key in the registry.
Args:
name: The name of the validator.
overwrite: Whether to overwrite the validator if it already exists.
Returns:
The decorator function that registers the validator.
"""
def decorator(cls: type[BaseModel]) -> type[BaseModel]:
if not issubclass(cls, BaseModel):
raise TypeError("Validators must be subclasses of pydantic.BaseModel.")
if name in VALIDATORS_REGISTRY and not overwrite:
raise ValueError(f"Validator with name '{name}' already exists.")
VALIDATORS_REGISTRY[name] = cls
return cls
return decorator