Author eric.smith
Recipients ascola, eric.smith, paul.j3, rhettinger, xmorel
Date 2020-12-08.19:35:29
SpamBayes Score -1.0
Marked as misclassified Yes
Message-id <1607456129.94.0.617824012481.issue42572@roundup.psfhosted.org>
In-reply-to
Content
The more I think about this, the more I think it shouldn't be in the stdlib. paul.j3 is correct that the simple case is just type=pathlib.Path.

For something more adventurous you could start with:

@dataclass(eq=True, frozen=True)
class ArgumentPath:
    must_exist: bool = False
    # Add other conditions as needed.

    def __call__(self, val):
        result = Path(val)
        if self.must_exist:
            if not result.exists():
                raise ValueError(f"path {result} must exist")
        return result

The reason I think this shouldn't be in the stdlib is that there are race conditions here between when you inspect the filesystem and when you'd actually use the path. What if the file was deleting, or it went from being a directory to a file?

I think the best advice is to use type=pathlib.Path, and handle anything else when you try to cd, or open, or whatever it is you're doing with the path.

It probably wouldn't hurt to document type=pathlib.Path in the argparse docs.
History
Date User Action Args
2020-12-08 19:35:29eric.smithsetrecipients: + eric.smith, rhettinger, xmorel, paul.j3, ascola
2020-12-08 19:35:29eric.smithsetmessageid: <1607456129.94.0.617824012481.issue42572@roundup.psfhosted.org>
2020-12-08 19:35:29eric.smithlinkissue42572 messages
2020-12-08 19:35:29eric.smithcreate