PathValidator#
- class tollan.config.types.PathValidator(path_type: None | Literal['file', 'dir', 'new'] = None, exists: bool = True, resolve: bool = True)[source]#
Bases:
objectValidator for Path types with rootpath context support.
This validator provides automatic handling of rootpath from validation context, optional path resolution, and existence/type checking. It follows the validation chain: rootpath → resolve → exists → type check.
- Parameters:
path_type (None | Literal["file", "dir", "new"]) – Type of path to validate: - “file”: Must be an existing file - “dir”: Must be an existing directory - “new”: Must not exist, but parent must exist - None: No type-specific validation
exists (bool, default=True) – Whether to check if path exists (ignored for path_type=”new”)
resolve (bool, default=True) – Whether to resolve path to absolute (expanduser + resolve)
Examples
>>> from pydantic import BaseModel >>> from pathlib import Path >>> class Config(BaseModel): ... file: Annotated[Path, PathValidator(exists=False)] >>> # Validate with rootpath context >>> config = Config.model_validate( ... {"file": "data.txt"}, ... context={"rootpath": "/base/dir"} ... ) >>> str(config.file) '/base/dir/data.txt'
Attributes Summary
Methods Summary
resolve_path(path, info)Resolve path to absolute.
validate_exists(path, info)Ensure path exists.
validate_path_rootpath(path, info)Handle rootpath from validation context.
Attributes Documentation
Methods Documentation
- static resolve_path(path: Path, info: ValidationInfo) Path[source]#
Resolve path to absolute.
Expands user home directory (~) and resolves to absolute path.
- Parameters:
path (Path) – Path to resolve
info (ValidationInfo) – Pydantic validation info (unused but required by interface)
- Returns:
Absolute path with user home directory expanded
- Return type:
Path
- static validate_exists(path: Path, info: ValidationInfo) Path[source]#
Ensure path exists.
- Parameters:
path (Path) – Path to validate
info (ValidationInfo) – Pydantic validation info
- Returns:
The validated path if it exists
- Return type:
Path
- Raises:
ValueError – If path does not exist
- static validate_path_rootpath(path: Any, info: ValidationInfo) Path[source]#
Handle rootpath from validation context.
This runs before Path validation, joining the input with rootpath from context if present.
- Parameters:
path (Any) – Input path (string or Path object)
info (ValidationInfo) – Pydantic validation info with optional rootpath in context
- Returns:
Path joined with rootpath if present, otherwise original path
- Return type:
Path
- Raises:
TypeError – If path is not a string or Path object