Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
3 of 13 tasks
MarcBresson opened this issue Mar 9, 2024 · 2 comments
Open
3 of 13 tasks

Comments

@MarcBresson
Copy link

MarcBresson commented Mar 9, 2024

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

@sydney-runkle
Copy link
Member

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!

@sydney-runkle sydney-runkle transferred this issue from pydantic/pydantic Mar 12, 2024
@MarcBresson
Copy link
Author

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 .

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants