PLAIN PYTHON · ZERO RUNTIME DEPS
Validate command-line inputs
Convert argparse strings deliberately and handle invalid command-line values.
Convert at the input boundary
argparse can produce strings; coerce=True lets the validation step explicitly convert supported values. The example supplies an argument list so it runs reproducibly; use parser.parse_args() for real command-line arguments.
import argparse
from zodify import validate
parser = argparse.ArgumentParser()
parser.add_argument("--port", required=True)
parser.add_argument("--debug", default="false")
schema = {"port": int, "debug": bool}
args = vars(parser.parse_args(["--port", "8080", "--debug", "yes"]))
assert validate(schema, args, coerce=True) == {"port": 8080, "debug": True}
try:
validate(schema, {"port": "not-a-port", "debug": "false"}, coerce=True)
except ValueError:
pass
else:
raise AssertionError("Expected conversion failure")
print("cli-input-validation: passed")
Expected output: cli-input-validation: passed
Keep the command-line contract small
The integer conversion checks a type, not a valid port range. Boolean conversion recognizes a small vocabulary. Handle errors with an application-controlled message if arguments may contain secrets.
For a single argument, argparse's built-in type or choices may be enough. Use a shared validation schema when the same shape also comes from another boundary.