neuralib.argp.validator

Validator Usage Guide

Overview

This guide demonstrates how to use the validator builders provided by our library. Each section provides short examples followed by a reference table of the builder’s methods.

String Validation

Examples

Minimum String Length:

from neuralib.argp import validator

class Opt:
    # Must be at least 2 characters long
    a: str = argument('-a', validator.str.length_in_range(2, None))

opt = Opt()
opt.a = 'Hi'    # OK
opt.a = ''      # Raises ValueError

Regex Matching:

class Opt:
    # Must match a letter followed by a digit, e.g. 'a1', 'b9'
    a: str = argument('-a', validator.str.match(r'[a-z][0-9]'))

opt = Opt()
opt.a = 'a1'    # OK
opt.a = 'A1'    # Raises ValueError

Method Reference

Method

Description

length_in_range(a, b)

Enforces a string length in [a, b]. Either bound may be None.

match(pattern)

Checks if the string matches a given regex pattern.

starts_with(prefix)

Checks if the string starts with prefix.

ends_with(suffix)

Checks if the string ends with suffix.

contains(substring)

Checks if the string contains the given substring.

is_in(options)

Checks if the string is in the provided collection of allowed options.

Integer Validation

Examples

Integer Range:

class Opt:
    # Must be >= 2
    a: int = argument('-a', validator.int.in_range(2, None))

opt = Opt()
opt.a = 5   # OK
opt.a = 0   # Raises ValueError

Positivity:

class Opt:
    # Must be strictly positive
    a: int = argument('-a', validator.int.positive(include_zero=False))

opt = Opt()
opt.a = 10  # OK
opt.a = 0   # Raises ValueError

Method Reference

Method

Description

in_range(a, b)

Checks if integer is in [a, b]. Either bound may be None.

positive(include_zero=True)

Checks if integer is >= 0 (if include_zero=True) or > 0 otherwise.

negative(include_zero=True)

Checks if integer is <= 0 (if include_zero=True) or < 0 otherwise.

Float Validation

Examples

Range + NaN Handling:

class Opt:
    # Must be < 100, NaN not allowed
    a: float = argument('-a',
        validator.float.in_range(None, 100).allow_nan(False)
    )

opt = Opt()
opt.a = 3.14        # OK
opt.a = 123.45      # Raises ValueError (out of range)
opt.a = float('nan')# Raises ValueError (NaN not allowed)

Method Reference

Method

Description

in_range(a, b)

Checks if float is in the open interval (a, b).

in_range_closed(a, b)

Checks if float is in the closed interval [a, b].

allow_nan(allow=True)

Allows or disallows NaN values.

positive(include_zero=True)

Checks if float is >= 0 (if include_zero=True) or > 0 otherwise.

negative(include_zero=True)

Checks if float is <= 0 (if include_zero=True) or < 0 otherwise.

List Validation

Examples

List of Integers:

class Opt:
    # Must be a list of integers
    a: list[int] = argument('-a', validator.list(int))

opt = Opt()
opt.a = [1, 2, 3]    # OK
opt.a = ['a', 2]     # Raises ValueError

Item Validation:

class Opt:
    # Each item must be non-negative
    a: list[int] = argument('-a',
        validator.list(int).on_item(validator.int.positive(True))
    )

opt = Opt()
opt.a = [0, 2, 5]    # OK
opt.a = [1, -1]      # Raises ValueError

Method Reference

Method

Description

length_in_range(a, b)

Enforces list length in [a, b].

allow_empty(allow=True)

Allows or disallows an empty list.

on_item(validator)

Applies a validator to each list item.

Tuple Validation

Examples

Fixed-Length Tuple:

class Opt:
    # Must be (str, int, float)
    a: tuple[str, int, float] = argument(
        '-a', validator.tuple(str, int, float)
    )

opt = Opt()
opt.a = ('abc', 42, 3.14)   # OK
opt.a = ('abc', 42)        # Raises ValueError (too few elements)

Variable-Length:

class Opt:
    # Must be (str, int, ...) i.e. at least 'str + int', optionally more ints
    a: tuple[str, int, ...] = argument(
        '-a', validator.tuple(str, int, ...)
    )

opt = Opt()
opt.a = ('x', 10)            # OK
opt.a = ('x', 10, 20, 30)    # OK
opt.a = ('x',)               # Raises ValueError (missing int)

Item-Validation:

class Opt:
    # Must be (str, int, float).
    # The string must have a length <= 5,
    # and the int must be >= 0 and <= 100.
    a: tuple[str, int, float] = argument(
        '-a',
        validator.tuple(str, int, float)
            .on_item(0, validator.str.length_in_range(None, 5))
            .on_item(1, validator.int.in_range(0, 100))
    )

opt = Opt()

# Passes all checks: str length=3, int in range [0..100], float is fine
opt.a = ('hey', 42, 3.14)

# Fails because the string is too long:
opt.a = ('excessive', 42, 1.2)
# Raises ValueError: str length over 5: "excessive"

# Fails because integer is out of range:
opt.a = ('hi', 999, 2.5)
# Raises ValueError: value out of range [0, 100]: 999

Method Reference

Method

Description

on_item(indexes, validator)

Apply a validator to specific tuple positions, or None for all.

(constructor)

Pass one int (e.g. 3) to enforce a fixed-length tuple with no type checks, or a tuple of types like (str, int, float). The last type can be ... for variable length.

Path Validation

Examples

Path suffix:

class Opt:
    a: Path = argument('-a', validator.path.is_suffix(['.csv', '.npy']))

opt = Opt()
opt.a = Path('.../*.csv')    # OK
opt.a = Path('.../*.txt')    # Raises ValueError

Method Reference

Method

Description

is_suffix(suffix)

Check path suffix or in a list of suffixes

is_exists()

Check if path exists

is_file()

Check if path is a file

is_dir()

Check if path is a directory

Logical Combinators

Examples

OR Combination:

class Opt:
    # Must be int in [0,10] OR str length in [0,10]
    a: int | str = argument(
        '-a',
        validator.any(
            validator.int.in_range(0, 10),
            validator.str.length_in_range(0, 10)
        )
    )

opt = Opt()
opt.a = 5            # OK (int in [0..10])
opt.a = 'abc'        # OK (length=3)
opt.a = 50           # Raises ValueError

AND Combination:

class Opt:
    # Must be non-negative AND non-positive => zero
    a: int = argument('-a', validator.all(
        validator.int.positive(include_zero=True),
        validator.int.negative(include_zero=True)
    ))

opt = Opt()
opt.a = 0   # OK
opt.a = 1   # Raises ValueError
opt.a = -1  # Raises ValueError

Method Reference

Method/Class

Description

validator.any(...) or |

Combine validators with logical OR; passing at least one is enough.

validator.all(...) or &

Combine validators with logical AND; must pass them all.

OrValidatorBuilder

The class implementing OR logic.

AndValidatorBuilder

The class implementing AND logic.

Error Handling

If any validation fails: - A ValidatorFailError (or subclass) is raised, often rethrown as ValueError in higher-level frameworks.

exception neuralib.argp.validator.ValidatorFailError[source]
exception neuralib.argp.validator.ValidatorFailOnTypeError[source]

A special ValidatorFailError that is raised when type validation failure. It is used for Validator#any() to exclude some error message.

class neuralib.argp.validator.Validator[source]
class neuralib.argp.validator.LambdaValidator[source]
__init__(validator, message=None)[source]
Parameters:
  • validator (Callable[[T], bool])

  • message (str | Callable[[T], str] | None)

final class neuralib.argp.validator.ValidatorBuilder[source]
property str: StrValidatorBuilder
property int: IntValidatorBuilder
property float: FloatValidatorBuilder
tuple(element_type: int) TupleValidatorBuilder[source]
tuple(*element_type: type[T]) TupleValidatorBuilder
list(element_type=None)[source]
Parameters:

element_type (type[T] | None)

Return type:

ListValidatorBuilder

property path
classmethod all(*validator)[source]
Parameters:

validator (Callable[[T], bool])

Return type:

AndValidatorBuilder

classmethod any(*validator)[source]
Parameters:

validator (Callable[[T], bool])

Return type:

OrValidatorBuilder

classmethod optional()[source]
Return type:

Validator

classmethod non_none()[source]
Return type:

Validator

class neuralib.argp.validator.AbstractTypeValidatorBuilder[source]
__init__(value_type=None)[source]
Parameters:

value_type (type[T] | tuple[type[T], ...] | None)

optional()[source]
Return type:

Self

class neuralib.argp.validator.StrValidatorBuilder[source]
__init__()[source]
length_in_range(a, b, /)[source]

Enforce a string length range

Parameters:
  • a (int | None)

  • b (int | None)

Return type:

StrValidatorBuilder

match(r)[source]

Check if string matches a regular expression

Parameters:

r (str | Pattern)

Return type:

StrValidatorBuilder

starts_with(prefix)[source]

Check if string values start with a substring

Parameters:

prefix (str)

Return type:

StrValidatorBuilder

ends_with(suffix)[source]

Check if string values end with a substring

Parameters:

suffix (str)

Return type:

StrValidatorBuilder

contains(text)[source]

Check if string values contain a substring

Parameters:

text (str)

Return type:

StrValidatorBuilder

is_in(options)[source]

Check if string is one of the allow options

Parameters:

options (Collection[str])

Return type:

StrValidatorBuilder

class neuralib.argp.validator.IntValidatorBuilder[source]
__init__()[source]
in_range(a, b, /)[source]

Enforce a numeric range for int values

Parameters:
  • a (int | None)

  • b (int | None)

Return type:

IntValidatorBuilder

positive(include_zero=True)[source]

Check if an int value is positive or non-negative

negative(include_zero=True)[source]

Check if an int value is negative or non-positive.

class neuralib.argp.validator.FloatValidatorBuilder[source]
__init__()[source]
in_range(a, b, /)[source]

Enforce an open-interval numeric range (a < value < b)

Parameters:
  • a (float | None)

  • b (float | None)

Return type:

Self

in_range_closed(a, b, /)[source]

Enforce a closed-interval numeric range (a <= value <= b)

Parameters:
  • a (float | None)

  • b (float | None)

Return type:

Self

allow_nan(allow=True)[source]

Allow or disallow NaN (not a number) as a valid float

Parameters:

allow (bool)

Return type:

Self

positive(include_zero=True)[source]

Check if a float value is positive or non-negative

Return type:

Self

negative(include_zero=True)[source]

Check if a float value is negative or non-positive

Return type:

Self

class neuralib.argp.validator.ListValidatorBuilder[source]
__init__(element_type=None)[source]
Parameters:

element_type (type[T] | None)

length_in_range(a, b, /)[source]

Enforce a length range for lists

Parameters:
  • a (int | None)

  • b (int | None)

Return type:

Self

allow_empty(allow=True)[source]

Allow or disallow empty lists

Parameters:

allow (bool)

on_item(validator)[source]

Apply an additional validator to each item in the list

Parameters:

validator (Callable[[Any], bool]) – A callable that validates each item

Return type:

Self

class neuralib.argp.validator.TupleValidatorBuilder[source]
__init__(element_type)[source]
Parameters:

element_type (tuple[int] | tuple[type[T], ...])

on_item(item, validator)[source]

Apply a validator to specific tuple positions

Parameters:
  • item (int | list[int] | None) – A single index, a list of indices, or None for all indices

  • validator (Callable[[Any], bool]) – The validation callable to apply

Return type:

Self

class neuralib.argp.validator.PathValidatorBuilder[source]
__init__()[source]
is_suffix(suffix)[source]

Check path suffix or in a list of suffixes

Parameters:

suffix (str | list[str] | tuple[str, ...])

Return type:

Self

is_exists()[source]

Check if path exists

Return type:

Self

is_file()[source]

Check if path is a file

Return type:

Self

is_dir()[source]

Check if path is a directory

Return type:

Self

class neuralib.argp.validator.ListItemValidatorBuilder[source]
class neuralib.argp.validator.TupleItemValidatorBuilder[source]
__init__(item, validator)[source]
Parameters:
  • item (int | list[int] | None)

  • validator (Callable[[Any], bool])

class neuralib.argp.validator.OrValidatorBuilder[source]
__init__(*validator)[source]
Parameters:

validator (Callable[[Any], bool])

class neuralib.argp.validator.AndValidatorBuilder[source]
__init__(*validator)[source]
Parameters:

validator (Callable[[Any], bool])

neuralib.argp.validator.element_isinstance(e, t)[source]
Return type:

bool