### Install pathtype Source: https://context7.com/xfrenette/pathtype/llms.txt Use pip to install the package. ```bash pip install pathtype ``` -------------------------------- ### Create an OR Validator with pathtype.validation.Any Source: https://github.com/xfrenette/pathtype/blob/main/README.md Combine validators using 'Any' to create a validator that passes if any of its constituent validators succeed. This example checks if the file name contains 'a' OR does not contain 'b'. ```python from pathtype.validation import Any or_validator = Any(must_have_a, must_not_have_b) parser.add_argument( ... type=pathtype.Path(validator=or_validator) ) ``` -------------------------------- ### Manually Control Validation Order with Custom Exists Validator Source: https://github.com/xfrenette/pathtype/blob/main/README.md To change validation order, instantiate predefined validators like Exists and include them in the 'validator' list. This example runs the custom validator before checking existence. ```python from pathtype.validation import Exists exist_validator = Exists() parser.add_argument( ... type=pathtype.Path(validator=[must_not_have_b, exist_validator]) ) ``` -------------------------------- ### Validate Non-Existent Text File Creation Source: https://github.com/xfrenette/pathtype/blob/main/README.md Combine multiple pathtype validations to ensure a file argument is a text file (*.txt), does not already exist, and that the user has permissions to create it. This implies the parent directory exists. ```python parser.add_argument( "--file", type=pathtype.Path(not_exists=True, creatable=True, name_matches_glob="*.txt") ) args = parser.parse_args(["--file", "path/to/my_file.txt"]) ``` -------------------------------- ### Validate file creation Source: https://context7.com/xfrenette/pathtype/llms.txt Ensures a file can be created by checking parent directory permissions. ```python import argparse import pathtype parser = argparse.ArgumentParser() # Validate file can be created (parent dir exists and is writable) parser.add_argument("--new-file", type=pathtype.Path(creatable=True)) # Validate file is writable OR can be created if it doesn't exist parser.add_argument("--output", type=pathtype.Path(writable_or_creatable=True)) args = parser.parse_args(["--new-file", "/tmp/new_data.json", "--output", "/tmp/results.csv"]) print(args.new_file.parent.exists()) # True ``` -------------------------------- ### Define path arguments with pathtype Source: https://context7.com/xfrenette/pathtype/llms.txt Use pathtype.Path to enforce constraints like file existence and naming patterns during argument parsing. ```python parser.add_argument( "--output", required=True, type=pathtype.Path( not_exists=True, creatable=True, # implies parent_exists=True name_matches_glob="*.csv" ) ) # Example usage args = parser.parse_args(["--input", "data.json", "--output", "results.csv"]) print(f"Reading from: {args.input}") print(f"Writing to: {args.output}") ``` -------------------------------- ### Validate file existence Source: https://context7.com/xfrenette/pathtype/llms.txt Checks if a path exists, does not exist, or if its parent directory exists. ```python import argparse import pathtype parser = argparse.ArgumentParser() # Validate file exists parser.add_argument("--input", type=pathtype.Path(exists=True)) # Validate file does NOT exist (for output files) parser.add_argument("--output", type=pathtype.Path(not_exists=True)) # Validate parent directory exists (file may or may not exist) parser.add_argument("--log", type=pathtype.Path(parent_exists=True)) # Example usage args = parser.parse_args(["--input", "/etc/hosts", "--output", "new_file.txt", "--log", "/tmp/myapp.log"]) print(args.input.exists()) # True ``` -------------------------------- ### Combine Predefined Exists Validation with Custom Validator Source: https://github.com/xfrenette/pathtype/blob/main/README.md Use the 'exists=True' argument in pathtype.Path to validate file existence before custom validation. Custom validators run after predefined ones. ```python parser.add_argument( ... type=pathtype.Path(validator=must_not_have_b, exists=True) ) ``` -------------------------------- ### Use built-in validation classes Source: https://context7.com/xfrenette/pathtype/llms.txt Utilize classes from pathtype.validation to control the order and granularity of path validation. ```python import argparse import pathlib import pathtype from pathtype.validation import ( Exists, NotExists, UserReadable, UserWritable, UserExecutable, ParentExists, ParentUserWritable, NameMatches, PathMatches ) # Create validator instances exists = Exists() readable = UserReadable() name_pattern = NameMatches(pattern=r"\.txt$") # Custom validator def validate_not_empty(path: pathlib.Path, arg: str): if path.exists() and path.stat().st_size == 0: raise argparse.ArgumentTypeError(f"file is empty: {arg}") # Control validation order: name pattern first, then existence, then custom validators = [name_pattern, exists, readable, validate_not_empty] parser = argparse.ArgumentParser() parser.add_argument("--file", type=pathtype.Path(validator=validators)) args = parser.parse_args(["--file", "document.txt"]) ``` -------------------------------- ### Convert CLI arguments to pathlib.Path Source: https://context7.com/xfrenette/pathtype/llms.txt Converts string arguments to pathlib.Path instances without performing any validation. ```python import argparse import pathtype parser = argparse.ArgumentParser() parser.add_argument("input_file", type=pathtype.Path()) args = parser.parse_args(["my_data.csv"]) print(type(args.input_file)) # print(args.input_file) # my_data.csv ``` -------------------------------- ### Use Single and Multiple Custom Validators with Path Source: https://github.com/xfrenette/pathtype/blob/main/README.md Integrate custom validators using the 'validator' parameter of pathtype.Path. Pass a single validator or a list for sequential execution. ```python parser = argparse.ArgumentParser() parser.add_argument( "--path-1", type=pathtype.Path(validator=must_have_a) ) parser.add_argument( "--path-2", type=pathtype.Path(validator=[must_have_a, must_not_have_b]) ) ``` -------------------------------- ### Create Custom Validators for File Name Checks Source: https://github.com/xfrenette/pathtype/blob/main/README.md Define functions that validate path names. 'must_have_a' checks for the presence of 'a', while 'must_not_have_b' ensures 'b' is absent. Both raise ArgumentTypeError if validation fails. ```python def must_have_a(path: pathlib.Path, arg: str): """Custom validator that fails if the file name doesn't contain the letter 'a'.""" if "a" not in path.name: raise argparse.ArgumentTypeError('The file name must have the letter "a"') def must_not_have_b(path: pathlib.Path, arg: str): """Custom validator that fails if the file name contains the letter 'b'.""" if "b" in path.name: raise argparse.ArgumentTypeError('The file name must NOT have the letter "b"') ``` -------------------------------- ### Validate file names with patterns Source: https://context7.com/xfrenette/pathtype/llms.txt Uses regular expressions or glob patterns to validate file names or full paths. ```python import argparse import pathtype parser = argparse.ArgumentParser() # Match file extension using regular expression parser.add_argument( "--image", type=pathtype.Path(name_matches_re=r"\.(png|jpe?g|gif)$") ) # Match file extension using glob pattern parser.add_argument( "--config", type=pathtype.Path(name_matches_glob="*.json") ) # Match full path using regular expression parser.add_argument( "--log", type=pathtype.Path(path_matches_re=r"/var/log/.+\.log$") ) # Match full path using glob pattern parser.add_argument( "--data", type=pathtype.Path(path_matches_glob="/home/*/*.csv") ) # Example: Image file validation args = parser.parse_args(["--image", "photo.jpeg", "--config", "settings.json"]) print(args.image.suffix) # .jpeg ``` -------------------------------- ### Combine validators with logical operators Source: https://context7.com/xfrenette/pathtype/llms.txt Use Any and All classes to create complex validation rules by combining multiple validator instances. ```python import argparse import pathtype from pathtype.validation import Any, All, Exists, UserReadable, NameMatches # Accept either JSON or YAML config files json_validator = NameMatches(glob="*.json") yaml_validator = NameMatches(glob="*.yaml") config_format = Any(json_validator, yaml_validator) parser = argparse.ArgumentParser() parser.add_argument( "--config", type=pathtype.Path( validator=[Exists(), UserReadable(), config_format] ) ) # More complex: file must exist AND (be readable OR be in /tmp) import pathlib def is_in_tmp(path: pathlib.Path, arg: str): if not str(path.resolve()).startswith("/tmp"): raise argparse.ArgumentTypeError("path not in /tmp") readable_or_tmp = Any(UserReadable(), is_in_tmp) complex_validator = All(Exists(), readable_or_tmp) parser.add_argument( "--data", type=pathtype.Path(validator=complex_validator) ) args = parser.parse_args(["--config", "app.yaml", "--data", "/tmp/data.bin"]) ``` -------------------------------- ### Validate file permissions Source: https://context7.com/xfrenette/pathtype/llms.txt Checks for read, write, or execute permissions using the current user's effective permissions. ```python import argparse import pathtype parser = argparse.ArgumentParser() # Validate file is readable (implies exists=True) parser.add_argument("--config", type=pathtype.Path(readable=True)) # Validate file is writable (implies exists=True) parser.add_argument("--data", type=pathtype.Path(writable=True)) # Validate file is executable (implies exists=True) parser.add_argument("--script", type=pathtype.Path(executable=True)) # Combine multiple permissions parser.add_argument("--file", type=pathtype.Path(readable=True, writable=True)) # Example usage args = parser.parse_args([ "--config", "/etc/hosts", "--data", "/tmp/output.txt", "--script", "/usr/bin/python3", "--file", "/tmp/test.txt" ]) ``` -------------------------------- ### Implement CLI Path Validation with pathtype Source: https://context7.com/xfrenette/pathtype/llms.txt Integrate pathtype into an argparse parser to enforce file existence, readability, and naming conventions. The resulting arguments are returned as validated pathlib.Path objects. ```python #!/usr/bin/env python3 """File converter CLI with comprehensive path validation.""" import argparse import pathlib import pathtype from pathtype.validation import Any, NameMatches def main(): parser = argparse.ArgumentParser( description="Convert data files between formats" ) # Input: must exist, be readable, be JSON or CSV input_format = Any( NameMatches(glob="*.json"), NameMatches(glob="*.csv") ) parser.add_argument( "-i", "--input", required=True, help="Input file (JSON or CSV)", type=pathtype.Path(readable=True, validator=input_format) ) # Output: writable or creatable, must be JSON or CSV output_format = Any( NameMatches(glob="*.json"), NameMatches(glob="*.csv") ) parser.add_argument( "-o", "--output", required=True, help="Output file (JSON or CSV)", type=pathtype.Path(writable_or_creatable=True, validator=output_format) ) # Optional log file parser.add_argument( "--log", help="Log file path", type=pathtype.Path(writable_or_creatable=True, name_matches_glob="*.log") ) args = parser.parse_args() # At this point, all paths are validated pathlib.Path instances print(f"Input: {args.input} (exists: {args.input.exists()})") print(f"Output: {args.output}") if args.log: print(f"Log: {args.log}") # Proceed with file conversion... input_data = args.input.read_text() # ... process data ... if __name__ == "__main__": main() # Usage: # python converter.py -i data.json -o output.csv --log conversion.log # # Error examples: # python converter.py -i missing.json -o out.csv # error: argument -i/--input: file doesn't exist (missing.json) # # python converter.py -i data.txt -o out.csv # error: argument -i/--input: glob "*.json" doesn't match data.txt ``` -------------------------------- ### Validate Image File Argument Source: https://github.com/xfrenette/pathtype/blob/main/README.md Use pathtype.Path as the type for an argparse argument to validate that the provided image file exists, is readable, and has a supported extension (PNG, GIF, JPEG). ```python import argparse import pathtype if __name__ == "__main__": parser = argparse.ArgumentParser() # We use `pathtype.Path` as the `type` argument to validate that the --image # argument is a readable image file (checks the file extension). parser.add_argument( "--image", required=True, help="Image file to open (PNG, GIF or JPEG supported)", type=pathtype.Path(readable=True, name_matches_re=r"\.(png|jpe?g|gif)$") ) # Path validations are done automatically by calling the next line, no need to # add code to validate that the path can be read and that it has the correct # extension. args = parser.parse_args() # args.image is an instance of pathlib.Path. And since using `readable` implies # `exists`, we know the file already exists and is readable by the current user. print(args.image.exists()) # True ``` -------------------------------- ### Combine multiple validation rules Source: https://context7.com/xfrenette/pathtype/llms.txt Applies multiple constraints to a single argument. ```python import argparse import pathtype parser = argparse.ArgumentParser() # Input file: must exist, be readable, and be a JSON file parser.add_argument( "--input", required=True, type=pathtype.Path( readable=True, # implies exists=True name_matches_glob="*.json" ) ) ``` -------------------------------- ### Convert Argument to Pathlib.Path Source: https://github.com/xfrenette/pathtype/blob/main/README.md Use pathtype.Path() as the type for an argparse argument to automatically convert the provided string argument into a pathlib.Path instance. ```python parser.add_argument( "my_arg", type=pathtype.Path() ) args = parser.parse_args() print(type(args.my_arg)) # >>> ``` -------------------------------- ### Implement custom path validators Source: https://context7.com/xfrenette/pathtype/llms.txt Define custom functions to perform complex validation logic on path objects, which can be passed individually or as a list to the validator parameter. ```python import argparse import pathlib import pathtype def validate_max_size(path: pathlib.Path, arg: str): """Validate file is smaller than 10MB.""" if path.exists(): size_mb = path.stat().st_size / (1024 * 1024) if size_mb > 10: raise argparse.ArgumentTypeError( f"file too large: {size_mb:.1f}MB (max 10MB)" ) def validate_in_home_dir(path: pathlib.Path, arg: str): """Validate path is inside user's home directory.""" import os resolved = pathlib.Path(os.path.abspath(os.path.expanduser(path))) home = pathlib.Path.home() if not str(resolved).startswith(str(home)): raise argparse.ArgumentTypeError( f"path must be in home directory: {resolved}" ) parser = argparse.ArgumentParser() # Single custom validator parser.add_argument( "--input", type=pathtype.Path(validator=validate_max_size, exists=True) ) # Multiple custom validators (executed sequentially) parser.add_argument( "--output", type=pathtype.Path(validator=[validate_in_home_dir, validate_max_size]) ) args = parser.parse_args(["--input", "data.txt", "--output", "~/results.txt"]) ``` -------------------------------- ### Define a Custom Path Validator Function Source: https://github.com/xfrenette/pathtype/blob/main/README.md Custom validators must accept a pathlib.Path object and the original string argument. Raise argparse.ArgumentTypeError, TypeError, or ValueError on failure. Return nothing on success. ```python def validator(path: pathlib.Path, arg: str) -> None: pass ``` -------------------------------- ### Custom Validator for Home Directory Path Source: https://github.com/xfrenette/pathtype/blob/main/README.md This validator checks if a provided path is located within the user's home directory. It raises an ArgumentTypeError if the path is outside the home directory. Ensure the path is expanded and resolved before comparison. ```python import os.path import pathlib import argparse import pathtype def is_inside_home_dir(path: pathlib.Path, arg: str): """Validate that the path is inside the current user's home directory.""" expanded_path = os.path.expanduser(path) resolved_path = pathlib.Path(os.path.abspath(expanded_path)) user_dir = pathlib.Path.home() # We check that `resolved_path` starts with the same directories as `user_dir` is_child = resolved_path.parts[:len(user_dir.parts)] == user_dir.parts if not is_child: raise argparse.ArgumentTypeError( f"path ({resolved_path}) is not in the user's home directory ({user_dir})" ) ``` ```python if __name__ == "__main__": parser = argparse.ArgumentParser() parser.add_argument( "--path", type=pathtype.Path(validator=is_inside_home_dir) ) # The following line won't raise any error args = parser.parse_args(["--path", "~/valid/path"]) print(repr(args.path)) # PosixPath('~/valid/path') # The following line will fail since the path is not inside the user's directory args = parser.parse_args(["--path", "/at-root"]) # Fails with this message: # usage: example.py [-h] [--path PATH] # example.py: error: argument --path: path (/at-root) is not in the user's home directory (/home/user) ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.