Created
December 16, 2021 10:55
-
-
Save ogvalt/6728534779b5332bf554a6b8e18dd110 to your computer and use it in GitHub Desktop.
Validate type of argument parsed by argparse
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
""" | |
# Usage: | |
import argparse | |
from argparse_pathtype import PathType | |
parser = argparse.ArgumentParser(description='Process some integers.') | |
parser.add_argument('--dir-models', required=True, type=PathType(path_to="dir"), | |
help='Directory where models are stored') | |
""" | |
from argparse import ArgumentTypeError | |
import pathlib | |
class PathType: | |
def __init__(self, path_to: str = 'file'): | |
""" | |
path_to: file, dir, symlink, None, or a function returning True for valid paths | |
None: don't care | |
""" | |
assert path_to in ('file', 'dir', 'symlink', None) or hasattr(path_to, '__call__') | |
self._type = path_to | |
def __call__(self, string: str): | |
resolved_path = pathlib.Path(string).resolve() | |
if not resolved_path.exists(): | |
raise ArgumentTypeError(f"path does not exist: '{string}', '{resolved_path}'") | |
if self._type is None: | |
pass | |
elif self._type == 'file' and not resolved_path.is_file(): | |
raise ArgumentTypeError(f"path is not a file: '{string}', '{resolved_path}'") | |
elif self._type == 'symlink' and not resolved_path.is_symlink(): | |
raise ArgumentTypeError(f"path is not a symlink: '{string}', '{resolved_path}'") | |
elif self._type == 'dir' and not resolved_path.is_dir(): | |
raise ArgumentTypeError(f"path is not a directory: '{string}', '{resolved_path}'") | |
return resolved_path |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment