pydantic / pydantic-extra-types

Extra Pydantic types.
MIT License
176 stars 47 forks source link

Add a file type to check if a path is new without checking if its parent exists #155

Open MarcBresson opened 5 months ago

MarcBresson commented 5 months ago

Initial Checks

Description

Hello,

I am using Pydantic to validate some path the user is supposed to give:

from pydantic import BaseModel, FilePath, DirectoryPath, NewPath

class Inference(BaseModel):
    in_data: DirectoryPath
    out_data: NewPath
    model_path: FilePath

However, a validation error will be thrown if the user wants to create an entire new tree.

Proposal

The already existing NewPath checks that the path does not exist but its parent does exist. A type that only checks for the first condition would be great.

Here is my code to add this type if anyone is interested:

def new_path_and_parents(path: Path) -> Path:
    "Check if a specified path does not already exist"
    assert not path.exists(), f"{path} already exists"
    return path

NewPathAndParents: TypeAlias = Annotated[Path, AfterValidator(new_path_and_parents)]

Non relevant additional proposal

I also had the intention to suggest an annotation to create a folder directly so that if the folder is new, it is created. But because Pydantic validation happens all at once, if a validation fails, the folder would still be created and NewPathAndParents would fail at the next run. Here is the implementation if anyone wants it:

def create_folder_and_parents(path: Path) -> Path:
    path.mkdir(parents=True, exist_ok=True)
    return path

CreateFolder: TypeAlias = Annotated[Path, AfterValidator(create_folder_and_parents)]

Affected Components

sydney-runkle commented 5 months ago

Hi @MarcBresson,

Thanks for the feature request! This looks similar to https://github.com/pydantic/pydantic-extra-types/issues/149, at a first glance. I'm going to move this issue to pydantic-extra-types. I certainly think greater support for path-like types could fit well there!

MarcBresson commented 5 months ago

Thanks moving the issue

It is similar in the fact that it is about paths, but it is a new type that has not been suggested in #149 .