Skip to content

arganic

arguments

Argument

Argument class.

Represents an argument with properties such as name, default value, and validation rules. Provides a method for validation.

Attributes:

  • name (str) –

    The name of the argument.

  • default ((Any, optional)) –

    The default value of the argument.

  • read_only (bool, default=True) –

    Whether the argument is read-only.

  • required (bool, default=True) –

    Whether the argument is required.

  • type ((Type | tuple[Type], optional)) –

    The data type(s) of the argument value.

  • validator ((Validator | tuple[Validator], optional)) –

    A Validator object or list of Validator objects used to validate the argument value.

  • choices ((tuple, optional)) –

    A tuple of choices the argument value can take.

Methods:

  • validate

    Validate the argument value based on the specified rules.

Examples:

Example of a full-featured argument construction:

from arganic.arguments import Argument, class_properties, ArgumentHandler  # Import Argument class.
from arganic.validators import MinLength, MaxLength  # Import validators


# Argument example
@class_properties(
    arg1=Argument(
        type=(str, list, tuple),  # Multiple types are supported.
        required=False,  # This argument is not required.
        default='first',  # A default value.
        read_only=False,  # This Argument/property is not writeable.
        choices=('first', 'second', ['first', 'second'], ('first', 'second')),  # Available choices.
        validator=(MinLength(1), MaxLength(10))  # Validators.
    )
)
class FullFeaturedArgument(ArgumentHandler):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

    def get_arg1(self) -> str | list | tuple:
        return self.get('arg1')


# 'first' value is allowed in choices options
ffa1 = FullFeaturedArgument(arg1='first')
print(ffa1.get_arg1())

# arg1 is not required and will take de the default value 'first'
ffa2 = FullFeaturedArgument()
print(ffa2.get_arg1())

# arg1 can be a tuple
ffa3 = FullFeaturedArgument(arg1=('first', 'second'))
print(ffa3.get_arg1())

# arg1 can be a list
ffa4 = FullFeaturedArgument(arg1=['first', 'second'])
print(ffa4.get_arg1())

# arg1 can be set
ffa4 = FullFeaturedArgument(arg1=['first', 'second'])
print(ffa4.get_arg1())
ffa4.set('arg1', 'second')
print(ffa4.get_arg1())

choices property

choices: tuple

Optional

A list of choices limiting the values that the supplied arguments can have.


default property

default: Any

Optional

The default value the argument will take if no value is provided.


name property

name: str

The argument name.


read_only property

read_only: bool

Default=True

The argument is read-only, so it can no longer be modified.


required property

required: bool

Default=True

The argument is required if the value is missing: an Exception will occur.


type property

type: Type | tuple[Type]

Optional

Defines the type(s) of values accepted for this argument, if the type provided is not valid an Exception will occur.


validator property

validator: Validator | tuple[Validator]

Optional

One or more instances of Validators constraining the value that an argument can have.


validate

validate(value: Any) -> bool

Validate the argument value based on the specified rules.

Parameters:

  • value (Any) –

    The value to validate.

Returns:

  • bool

    True if the value is valid, False otherwise.

Raises:

  • TypeError

    If the value is not of the specified type.

  • ValueError

    If the value is required but not provided, or if it is not among the specified choices.

ArgumentHandler

Handles arguments or properties for decorated classes, methods or functions.

Attributes


values: dict The provided arguments values validated and correctly formatted.

Methods:

  • get

    Retrieves the value of a specified argument or property.

  • set

    Sets the value of a specified argument or property.

values property

values: dict

The validated values.


get

get(key: str) -> Any

Retrieves the value of a specified argument or property.

Parameters:

  • key (str) –

    The key of the argument or property to retrieve.

Returns:

  • Any

    The value of the argument or property.

set

set(key: str, value: Any) -> None

Sets the value of arguments or properties to the specified key.

Parameters:

  • key (str) –

    The key of the argument to set.

  • value (Any) –

    The new value for the argument.

Raises:

  • ValueError

    if the argument is not writeable.

class_properties

class_properties(**_properties: Argument) -> Callable

Decorator for class properties.

A decorator for class properties allowing you to define the data managed by the class during construction and then access these values within the class.

Parameters:

  • _properties (Argument, default: {} ) –

    A dictionary of the Arguments the decorator will handle.

Returns:

  • Callable

    The decorator function.

function_arguments

function_arguments(**_arguments: Argument) -> Callable

Decorator for function arguments.

A decorator for functions allowing you to constrain the arguments provided during the call but also to find the correctly formatted values within the function.

Parameters:

  • _arguments (Argument, default: {} ) –

    A dictionary of the Arguments the decorator will handle.

Returns:

  • Callable

    The decorator function.

method_arguments

method_arguments(**_arguments: Argument) -> Callable

Decorator for method arguments.

A decorator for class methods allowing you to constrain the arguments provided during the call but also to find the correctly formatted values within the method.

Parameters:

  • _arguments (Argument, default: {} ) –

    A dictionary of the Arguments the decorator will handle.

Returns:

  • Callable

    The decorator function.

validators

Dir

Bases: Validator

Directory Validator.

validate

validate(value) -> bool

Test the existence of a directory according to the path provided.

Parameters:

  • value

    Path to the directory that must exist on the file system.

Returns:

  • bool

    True if the directory exists.

Raises:

  • FileNotFoundError

    If the directory does not exist on the file system.

Examples:

from arganic.arguments import function_arguments, Argument
from arganic.validators import Dir


@function_arguments(
    dir=Argument(
        type=str,
        validator=Dir()
    )
)
def dir_handler(*args, **kwargs) -> str:
    print(dir_handler.arguments.get('dir'))
    return dir_handler.arguments.get('dir')


# Validation
dir_handler(dir='tests/examples/validate_dir')

Email

Bases: Validator

Email address Validator.

validate

validate(value) -> bool

Validates the syntax of an email address.

Parameters:

  • value

    Email address whose syntax must be checked.

Returns:

  • bool

    If the value provided is a correct email address format.

Raises:

  • ValueError

    If the value provided is not a valid email address.

Examples:

from arganic.validators import Email
from arganic.arguments import function_arguments, Argument


@function_arguments(
    email=Argument(
        type=str,
        validator=Email()
    )
)
def email_handler(*args, **kwargs) -> str:
    print(email_handler.arguments.get('email'))
    return email_handler.arguments.get('email')


# Validation
email_handler(email='example@example.com')

File

Bases: Validator

File Validator

validate

validate(value) -> bool

Test the existence of a file according to the path provided.

Parameters:

  • value

    Path to the file that must exist on the file system.

Returns:

  • bool

    True if the file exists.

Raises:

  • FileNotFoundError

    If the file does not exist on the file system.

Examples:

from arganic.arguments import function_arguments, Argument
from arganic.validators import File


@function_arguments(
    file=Argument(
        type=str,
        validator=File()
    )
)
def file_handler(*args, **kwargs) -> str:
    print(file_handler.arguments.get('file'))
    return file_handler.arguments.get('file')


# Validation
file_handler(file='tests/examples/validate_dir/validate_file.txt')

MaxLength

Bases: Validator

Maximum length validator.

__init__

__init__(max_length: int) -> None

Max length Validator constructor.

Parameters:

  • max_length (int) –

    The maximum length that the values to validate must not exceed.

validate

validate(value) -> bool

Validates a value whose maximum length must not be greater than the value specified in the validator constructor.

The value must be of a type supporting the builtin len() Python function.

Parameters:

  • value

    The value to validate.

Returns:

  • bool

    True if the validation succeeded.

Raises:

  • TypeError

    If the length of the value is longer than the specified maximum length.

Examples:

from arganic.validators import MaxLength
from arganic.arguments import function_arguments, Argument


@function_arguments(
    max_len=Argument(
        type=str,
        validator=MaxLength(10)
    )
)
def max_len_10_handler(*args, **kwargs) -> str:
    print(max_len_10_handler.arguments.get('max_len'))
    return max_len_10_handler.arguments.get('max_len')


@function_arguments(
    max_len=Argument(
        type=str,
        validator=MaxLength(1)
    )
)
def max_len_1_handler(*args, **kwargs) -> str:
    print(max_len_1_handler.arguments.get('max_len'))
    return max_len_1_handler.arguments.get('max_len')


# Validation
max_len_10_handler(max_len='example')
# Validation
max_len_1_handler(max_len='e')

MinLength

Bases: Validator

Minimum length validator.

__init__

__init__(min_length: int) -> None

Max length Validator constructor.

Parameters:

  • min_length (int) –

    The minimum length that the value must be.

validate

validate(value) -> bool

Verifies that the provided value have a length must be at least the minimum value given in the validator constructor.

The value must be of a type supporting the builtin len() Python function.

Parameters:

  • value

    The value to validate.

Returns:

  • bool

    True if the validation succeeded.

Raises:

  • TypeError

    If the length of the value is shorter than the specified minimum length.

Examples:

from arganic.validators import MinLength
from arganic.arguments import function_arguments, Argument


@function_arguments(
    min_len=Argument(
        type=str,
        validator=MinLength(1)
    )
)
def min_len_1_handler(*args, **kwargs) -> str:
    return min_len_1_handler.arguments.get('min_len')


@function_arguments(
    min_len=Argument(
        type=str,
        validator=MinLength(10)
    )
)
def min_len_10_handler(*args, **kwargs) -> str:
    print(min_len_10_handler.arguments.get('min_len'))
    return min_len_10_handler.arguments.get('min_len')


# Validation
min_len_1_handler(min_len='example')
# Validation
min_len_1_handler(min_len='example1234')

Url

Bases: Validator

URL Validator.

validate

validate(value) -> bool

Validate if an URL is well formatted. supported protocols: http, https, ftp, ftps.

Parameters:

  • value

    The value of the URL to validate.

Returns:

  • bool

    True if the URL is well formatted.

Raises:

  • ValueError

    If the provided value is an invalid Url.

Examples:

from arganic.validators import Url
from arganic.arguments import function_arguments, Argument


@function_arguments(
    url=Argument(
        type=str,
        validator=Url()
    )
)
def url_handler(*args, **kwargs) -> str:
    print(url_handler.arguments.get('url'))
    return url_handler.arguments.get('url')


# Validation
url_handler(url='https://www.example.com')

Validator

Bases: ABC

Base class for validators.

It's possible to define your own validators by extending this class.

Examples:

Example of a custom validator.

from arganic.arguments import function_arguments, Argument
from arganic.validators import Validator


class CityValidator(Validator):
    """
    Custom validator class.
    """
    def validate(self, value) -> bool:
        if value in ('Geneva', 'Paris', 'Lyon', 'Madrid'):
            return True
        raise ValueError('Invalid value')


@function_arguments(
    start=Argument(
        type=str,
        validator=CityValidator()
    ),
    destination=Argument(
        type=str,
        validator=CityValidator()
    )
)
def drive(*args, **kwargs) -> None:
    print('Drive')
    print('start', drive.arguments.get('start'))
    print('destination', drive.arguments.get('destination'))
    return drive.arguments.values


drive(start='Geneva', destination='Paris')
drive(start='Lyon', destination='Geneva')
drive(start='Madrid', destination='Paris')

validate abstractmethod

validate(value) -> bool

Override this method on inherited classes.

Parameters:

  • value

    The value to validate.

Returns:

  • bool

    The validate() methods needs to return True if the validation pass or raises an exception if the validation fails.