Skip to content

values

Class info

Classes

Name Children Inherits
FieldError
promptantic.form.values
Input that can't become a value of the field (e.g. "abc" for a number).

    🛈 DocStrings

    Turning input into values, and checking a single field while it's being filled.

    The whole value is validated at the end (:mod:promptantic.form.target); these checks are what a renderer shows next to a field as the user types.

    FieldError

    Bases: ValueError

    Input that can't become a value of the field (e.g. "abc" for a number).

    Source code in src/promptantic/form/values.py
    class FieldError(ValueError):
        """Input that can't become a value of the field (e.g. "abc" for a number)."""
    

    field_errors

    field_errors(node: FormNode, value: Any) -> list[str]
    

    What's wrong with value for this field alone (empty when it fits).

    Covers the field's own constraints (length, pattern, format, bounds, item and key counts, allowed choices); the full document is validated at the end.

    Source code in src/promptantic/form/values.py
    def field_errors(node: FormNode, value: Any) -> list[str]:  # noqa: PLR0911
        """What's wrong with ``value`` for this field alone (empty when it fits).
    
        Covers the field's own constraints (length, pattern, format, bounds, item and
        key counts, allowed choices); the full document is validated at the end.
        """
        if value is None:
            return [] if node.nullable or node.kind in ("null", "any") else ["A value is required"]
        match node:
            case StringNode():
                return _string_errors(node, value)
            case NumberNode():
                return _number_errors(node, value)
            case ChoiceNode():
                allowed = [choice.value for choice in node.choices]
                return [] if value in allowed else ["Pick one of the options"]
            case ArrayNode():
                if not isinstance(value, list):
                    return ["Expected a list"]
                errors = []
                if node.min_items is not None and len(value) < node.min_items:
                    errors.append(f"At least {node.min_items} item(s)")
                if node.max_items is not None and len(value) > node.max_items:
                    errors.append(f"At most {node.max_items} item(s)")
                if node.unique and len({json.dumps(item, sort_keys=True) for item in value}) < len(
                    value
                ):
                    errors.append("Items must be unique")
                return errors
            case ObjectNode():
                if not isinstance(value, dict):
                    return ["Expected an object"]
                errors = [
                    f"{prop.label} is required"
                    for prop in node.properties
                    if prop.required and prop.name not in value
                ]
                if node.min_properties is not None and len(value) < node.min_properties:
                    errors.append(f"At least {node.min_properties} entries")
                if node.max_properties is not None and len(value) > node.max_properties:
                    errors.append(f"At most {node.max_properties} entries")
                return errors
            case _:
                return []
    

    initial_value

    initial_value(node: FormNode) -> Any | Unset
    

    The value a field starts with: its default, else :data:UNSET.

    Source code in src/promptantic/form/values.py
    def initial_value(node: FormNode) -> Any | Unset:
        """The value a field starts with: its default, else :data:`UNSET`."""
        return node.meta.default
    

    parse_text

    parse_text(node: StringNode | NumberNode | AnyNode, text: str) -> Any | Unset
    

    The value typed text stands for; :data:UNSET for empty input.

    Raises:

    Type Description
    FieldError

    text isn't a number (number fields) or JSON (free fields).

    Source code in src/promptantic/form/values.py
    def parse_text(node: StringNode | NumberNode | AnyNode, text: str) -> Any | Unset:
        """The value typed ``text`` stands for; :data:`UNSET` for empty input.
    
        Raises:
            FieldError: ``text`` isn't a number (number fields) or JSON (free fields).
        """
        if text == "" and not (isinstance(node, StringNode) and node.min_length == 0):
            return UNSET
        match node:
            case StringNode():
                return text
            case NumberNode(integer=True):
                try:
                    return int(text.strip().replace("_", ""))
                except ValueError:
                    msg = "Enter a whole number"
                    raise FieldError(msg) from None
            case NumberNode():
                try:
                    number = float(text.strip().replace("_", ""))
                except ValueError:
                    msg = "Enter a number"
                    raise FieldError(msg) from None
                if not math.isfinite(number):
                    msg = "Enter a finite number"
                    raise FieldError(msg)
                return int(number) if number.is_integer() and "." not in text else number
            case AnyNode():
                try:
                    return json.loads(text)
                except json.JSONDecodeError as exc:
                    msg = f"Enter JSON ({exc.msg})"
                    raise FieldError(msg) from None