pydantic / pydantic-extra-types

Extra Pydantic types.

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

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

MarcBresson opened this issue · comments

Initial Checks

  • I have searched Google & GitHub for similar requests and couldn't find anything
  • I have read and followed the docs and still think this feature is missing

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

Hi @MarcBresson,

Thanks for the feature request! This looks similar to #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!

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 .