Parameters¶
This module provides a framework for defining and managing typed parameter sets.
It includes a base class for individual parameters with validation and serialization logic, and a base class for grouping these parameters into sets. Supported parameter types include strings, numerics (integers and floats), booleans, enums, and time/intervals.
Example¶
Consider the following example:
Code
1class CustomParameterSet(BaseParameterSet):
2 def __init__(
3 self,
4 name: str = "Custom",
5 ):
6 super().__init__(name=name)
7
8 self.add_parameters([
9 IntegerParameter(
10 name="batch_size",
11 minvalue=1
12 ),
13 EnumParameter(
14 name="search_direction",
15 choices=["depth first", "breadth first"]
16 ),
17 ])
18
19 @property
20 def batch_size(self) -> int:
21 return self["batch_size"]
22
23 @property
24 def search_direction(self):
25 return self["search_direction"]
26
27 def validate(self):
28 pass
Note a few key points to note:
After initialization, the parameter set is locked, and any modifications to the internal dictionary of parameters is not allowed. Exception: the values of the parameters can still be set.
The
add_parametersmethod is used to add parameters to the internal dictionary. Due to post-init locking, this method must be called in the constructor of the subclass.The
validatemethod is intended to be overridden by subclasses for custom validation logic. TheTypedParameterobjects are responsible for validating their respective parameter values, though sometimes it may be necessary to perform additional validation on the relative values of parameters. These can be implemented at the ParameterSet level.The
__getitem__method allows for parameter access using dictionary-like syntax, as is used on line 21 and 25. Use theTypedParameter-name as a ‘key’.
Tip
While not strictly necessary, it is recommended to add the property methods (line 19-25) for easy access and IDE support.
Reference¶
- exception algomancy_utils.baseparameterset.ParameterError(message)[source]¶
Bases:
ExceptionException raised for errors in parameter validation or management.
- class algomancy_utils.baseparameterset.ParameterType(*values)[source]¶
Bases:
StrEnumEnum representing the supported data types for parameters.
- STRING = 'string'¶
A simple string value
- INTEGER = 'integer'¶
A whole number (int)
- FLOAT = 'float'¶
A floating-point number (float)
- BOOLEAN = 'boolean'¶
A boolean value (True/False)
- ENUM = 'enum'¶
A single selection from a predefined set of choices
- MULTI_ENUM = 'multi_enum'¶
Multiple selections from a predefined set of choices
- TIME = 'time'¶
A specific point in time (datetime)
- INTERVAL = 'interval'¶
A range between two points in time (datetime, datetime)
- class algomancy_utils.baseparameterset.TypedParameter(name, parameter_type, required)[source]¶
Bases:
ABCAbstract base class for all typed parameters.
Provides core functionality for parameter identification, requirement checking, and value management. Subclasses must implement specific validation and value retrieval logic.
- Parameters:
name (str) – The unique identifier for the parameter.
parameter_type (ParameterType) – The data type of the parameter.
required (bool) – Whether the parameter must have a value assigned.
- abstract property value: Any¶
Returns the current value of the parameter, or its default if unset.
- set_validated_value(value)[source]¶
Validates and sets the value of the parameter.
- Parameters:
value (Any) – The value to validate and set.
- Raises:
ParameterError – If the value fails requirement or type-specific validation.
- class algomancy_utils.baseparameterset.StringParameter(name, value=None, required=True, default='default')[source]¶
Bases:
TypedParameterParameter representing a string value.
- Parameters:
name (str) – The unique identifier for the parameter.
value (str) – Optional initial string value.
required (bool) – Whether the parameter must have a value assigned. Defaults to True.
default (str) – The default string value if none is provided. Defaults to “default”.
- class algomancy_utils.baseparameterset.EnumParameter(name, choices, value=None, required=True)[source]¶
Bases:
TypedParameterParameter representing a single selection from a predefined set of choices.
- Parameters:
name (str) – The unique identifier for the parameter.
choices (list[str]) – A list of valid string options for the parameter.
value (str) – Optional initial selection.
required (bool) – Whether the parameter must have a value assigned. Defaults to True.
- class algomancy_utils.baseparameterset.MultiEnumParameter(name, choices, value=None, required=True)[source]¶
Bases:
TypedParameterParameter representing multiple selections from a predefined set of choices.
- Parameters:
name (str) – The unique identifier for the parameter.
choices (list[str]) – A list of valid string options for the parameter.
value (list[str]) – Optional list of initial selections.
required (bool) – Whether the parameter must have a value assigned. Defaults to True.
- class algomancy_utils.baseparameterset.NumericParameter(name, parameter_type, required, default, minvalue=None, maxvalue=None, value=None)[source]¶
Bases:
TypedParameter,ABCAbstract base class for numeric parameters (Integer and Float).
Supports range validation with minimum and maximum values.
- Parameters:
name (str) – The unique identifier for the parameter.
parameter_type (ParameterType) – ParameterType.INTEGER or ParameterType.FLOAT.
required (bool) – Whether the parameter must have a value assigned.
default – The default numeric value if none is provided.
minvalue (float) – Optional minimum allowed value.
maxvalue (float) – Optional maximum allowed value.
value (float) – Optional initial numeric value.
- class algomancy_utils.baseparameterset.FloatParameter(name, minvalue=None, maxvalue=None, value=None, required=True, default=1.0)[source]¶
Bases:
NumericParameterParameter representing a floating-point value.
- Parameters:
name (str) – The unique identifier for the parameter.
minvalue (float) – Optional minimum allowed value.
maxvalue (float) – Optional maximum allowed value.
value (float) – Optional initial numeric value.
required (bool) – Whether the parameter must have a value assigned. Defaults to True.
default (float) – The default float value if none is provided. Defaults to 1.0.
- class algomancy_utils.baseparameterset.IntegerParameter(name, minvalue=None, maxvalue=None, value=None, required=True, default=1)[source]¶
Bases:
NumericParameterParameter representing an integer value.
- Parameters:
name (str) – The unique identifier for the parameter.
minvalue (int) – Optional minimum allowed value.
maxvalue (int) – Optional maximum allowed value.
value (int) – Optional initial numeric value.
required (bool) – Whether the parameter must have a value assigned. Defaults to True.
default (int) – The default integer value if none is provided. Defaults to 1.
- class algomancy_utils.baseparameterset.BooleanParameter(name, value=None, required=True, default=False)[source]¶
Bases:
TypedParameterParameter representing a boolean value.
- Parameters:
name (str) – The unique identifier for the parameter.
value (bool) – Optional initial boolean value.
required (bool) – Whether the parameter must have a value assigned. Defaults to True.
default (bool) – The default boolean value if none is provided. Defaults to False.
- class algomancy_utils.baseparameterset.TimeParameter(name, value=None, required=True, default=None)[source]¶
Bases:
TypedParameterParameter representing a specific point in time.
- Parameters:
name (str) – The unique identifier for the parameter.
value (datetime | None) – Optional initial datetime value.
required (bool) – Whether the parameter must have a value assigned. Defaults to True.
default (datetime | None) – The default datetime value if none is provided.
- property default: datetime¶
Returns the default datetime, defaulting to today if unset.
- class algomancy_utils.baseparameterset.IntervalParameter(name, value=None, required=True, default=None)[source]¶
Bases:
TypedParameterParameter representing a time range between two points.
- Parameters:
name (str) – The unique identifier for the parameter.
value (list[datetime] | tuple[datetime, datetime] | None) – Optional initial interval (list or tuple of two datetimes).
required (bool) – Whether the parameter must have a value assigned. Defaults to True.
default (tuple[datetime, datetime] | None) – The default interval tuple if none is provided.
- property default_start: datetime¶
Returns the start of the default interval.
- property default_end: datetime¶
Returns the end of the default interval.
- class algomancy_utils.baseparameterset.PostInitMeta(name, bases, namespace, /, **kwargs)[source]¶
Bases:
ABCMetaMetaclass that automatically calls a _post_init method after instantiation.
- class algomancy_utils.baseparameterset.BaseParameterSet(*args, **kwargs)[source]¶
Bases:
ABCBase class for a collection of parameters. Implements PostInitMeta.
Manages a set of TypedParameter objects, providing methods for validation, serialization, and bulk value assignment.
After initialization, the parameter set is _locked_, which prevents the modification of the internal dictionary of parameters by add_parameters. This is to ensure that the parameter set remains consistent and predictable.
- Parameters:
name – A descriptive name for the parameter set.
- abstractmethod validate()[source]¶
Abstract method to perform custom validation on the entire parameter set.
Must be implemented by subclasses; can often be implemented by a simple pass statement.
Note
TypedParameters are individually validated, using the information as provided on creation. However, it may be desirable to perform additional validation based on the the relative values of parameters within the set. In such cases, validation should be performed in this method.
- Raises:
ParameterValidationError –
- get_parameters()[source]¶
Retrieves the dictionary of all parameters in the set.
- Returns:
A dictionary mapping parameter names to TypedParameter objects.
- Return type:
Dict[str, TypedParameter]
- contains(param_name)[source]¶
Checks if a parameter with the given name exists in the set.
- Parameters:
param_name (str) – The name to search for.
- Returns:
True if the parameter exists, False otherwise.
- Return type:
bool
- serialize()[source]¶
Serializes the parameter set to a JSON string.
- Returns:
A JSON string containing the set name and parameter values.
- classmethod deserialize(json_str)[source]¶
Creates a new instance of the parameter set from a JSON string.
- Parameters:
json_str (str) – The JSON string to deserialize.
- Returns:
A new instance of the class with values populated from the JSON.
- add_parameters(parameters)[source]¶
Adds multiple parameters to the set.
Only allowed before the set is locked (usually during __init__).
- Parameters:
parameters (list[TypedParameter]) – A list of TypedParameter objects to add.
- Raises:
ParameterError – If the set is already locked.
- set_values(values)[source]¶
Assigns and validates values for multiple parameters.
- Parameters:
values (dict[str, Any]) – A dictionary mapping parameter names to new values.
- Raises:
ParameterError – If a parameter name is not found or validation fails.
- set_validated_values(values)[source]¶
Assigns values and performs set-wide validation.
- Parameters:
values (dict[str, Any]) – A dictionary mapping parameter names to new values.
- get_values()[source]¶
Retrieves current values for all parameters.
- Returns:
A dictionary mapping parameter names to their current values.
- Return type:
dict[str, Any]
- has_inputs()[source]¶
Checks if the set contains any parameters.
- Returns:
True if the set is not empty, False otherwise.
- Return type:
bool
- class algomancy_utils.baseparameterset.EmptyParameters(*args, **kwargs)[source]¶
Bases:
BaseParameterSetA predefined empty parameter set.