cinnamon package
Subpackages
- cinnamon.utility package
- Submodules
- cinnamon.utility.configuration module
- cinnamon.utility.exceptions module
- cinnamon.utility.inquirer module
- cinnamon.utility.registration module
- cinnamon.utility.sanity module
- Module contents
Submodules
cinnamon.command_line module
cinnamon.component module
cinnamon.configuration module
- class cinnamon.configuration.Configuration(**data)
Bases:
BaseModelA Configuration specifies the parameters of a Component. Configurations store parameters and allow flow control via conditions.
- add_condition(condition, name, description=None, tags=None)
Adds a condition to be validated.
- Parameters:
condition (
Callable[[Configuration],bool]) – a function that receives as input the currentConfigurationinstance and returns a boolean.name (
str) – unique identifier.description (
Optional[str]) – a string description for readability purposes.tags (
Optional[Set[str]]) – a set of string tags to mark the condition with metadata.
- Raises:
AlreadyExistingParameterException – if the provided name already exists in the Configuration instance.
- classmethod default()
Returns the default
Configurationinstance.- Return type:
TypeVar(C, bound= Configuration)- Returns:
Configurationinstance.
- property dependencies: Dict[str, RegistrationKey | Configuration]
- property expanded: bool
- property fields: Dict[str, FieldInfo]
- property has_at_least_two_variants: bool
- property has_variants: bool
- is_dependency(field_name, field)
- Return type:
bool
- meta: ClassVar[MetaDescriptor] = <cinnamon.configuration.FieldMetaProxy object>
- model_config: ClassVar[ConfigDict] = {'validate_default': True}
Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].
- model_copy(*, update=None, deep=False)
- !!! abstract “Usage Documentation”
[model_copy](../concepts/models.md#model-copy)
Returns a copy of the model.
- !!! note
The underlying instance’s [__dict__][object.__dict__] attribute is copied. This might have unexpected side effects if you store anything in it, on top of the model fields (e.g. the value of [cached properties][functools.cached_property]).
- Parameters:
update (
Optional[Mapping[str,Any]]) – Values to change/add in the new model. Note: the data is not validated before creating the new model. You should trust this data.deep (
bool) – Set to True to make a deep copy of the model.
- Return type:
Self- Returns:
New model instance.
- model_post_init(_Configuration__context)
Runs automatically right after Pydantic instantiates an object.
- Return type:
None
- classmethod retrieve(registration_key=None, name=None, namespace=None, tags=None)
- Syntactic sugar for retrieving a Configuration from a
RegistrationKeyin implicit format.
- Parameters:
registration_key (cinnamon.registry.Registration | None) – the
RegistrationKeyused to register theConfigurationclass.name (str | None) – the
namefield ofRegistrationKeytags (Tags) – the
tagsfield ofRegistrationKeynamespace (str | None) – the
namespacefield ofRegistrationKey
- Return type:
C
- Returns:
A
Configurationinstance- Raises:
InvalidConfigurationTypeException – if there’s a mismatch between the
Configurationclass usedduring registration and the type of the built Configuration – instance using the registered
constructor` method (see ConfigurationInfo arguments) –
- validate_conditions(strict=True)
Validates all provided conditions related to the
Configurationinstance. :rtype:ValidationResult- Args:
- strict: if True, a failed validation process will raise
InvalidConfigurationException
- Returns:
- A
ValidationResultthat stores the boolean result of the validation process along with an error message if the result is
False.
- A
- Raises:
ValidationFailureException: ifstrict = Trueand the validationprocess failed
- validate_variants()
- Return type:
TypeVar(C, bound= Configuration)
- property values: Dict[str, Any]
- property variants: List[Dict[str, Dict[str, Any]]]
- Computes all unique combinations of a configuration’s fields along
with their indices.
The baseline/default value always gets index 0. Subsequent unique variants get an increasing index (1, 2, …).
- cinnamon.configuration.Param(default=PydanticUndefined, *, description=None, tags=None, variants=None, **kwargs)
- Return type:
Any
cinnamon.registry module
- class cinnamon.registry.RegistrationKey(name, namespace=None, tags=None, description=None, metadata=None, special_tags=None)
Bases:
Generic[T]Compound key used for registration.
-
ATTRIBUTE_SEPARATOR:
str= '--'
-
HIERARCHY_SEPARATOR:
str= '.'
-
KEY_VALUE_SEPARATOR:
str= '='
-
MAX_TAGS_PER_LINE:
int= 6
- check_name(name)
- check_namespace(namespace)
- check_tags(tags)
- property compound_tags
- classmethod from_string(string_format)
Parses a
RegistrationKeyinstance from its string format.- Parameters:
string_format (
str) – the string format of aRegistrationKeyinstance.- Return type:
RegistrationKey[Any]- Returns:
The corresponding parsed
RegistrationKeyinstance
- from_tags_simplification(tags)
- Builds a new
RegistrationKeyfrom current instance by removing provided tags.
- Parameters:
tags (
Optional[Set[str]]) – a Tag set containing tags to remove- Return type:
RegistrationKey[TypeVar(T)]- Returns:
- A
RegistrationKeyinstance that is the same as the current instance but with
tagsremoved.
- A
- Builds a new
- from_variant(variant_kwargs, variant_indexes=None)
- Return type:
RegistrationKey[TypeVar(T)]
- property hierarchy_tags
- match(key, tags)
- Return type:
bool
- classmethod parse(registration_key=None, name=None, namespace=None, tags=None)
Parses a given
RegistrationKeyinstance. If the givenregistration_keyis in its string format, it is convertedto
RegistrationKeyinstance- Parameters:
registration_key (
Union[RegistrationKey,str,None]) – aRegistrationKeyinstance in its class instance or string formatname (
Optional[str]) – thenamefield ofRegistrationKeynamespace (
Optional[str]) – thenamespacefield ofRegistrationKeytags (
Optional[Set[str]]) – thetagsfield ofRegistrationKey
- Return type:
RegistrationKey[Any]- Returns:
The parsed
RegistrationKeyinstance
- sanitize_variant_tag(param_name, param_index, param_value)
- Return type:
str
- toJSON()
- to_pretty_string()
-
ATTRIBUTE_SEPARATOR:
- class cinnamon.registry.Registry
Bases:
objectThe registration registry. The registry has three main functionalities: - Storing/Retrieving registered
Configuration: via theConfigurationInfointernal wrapper.
Storing/Retrieving
ConfigurationtoComponentbindings: the binding
- operation allows to build a
Componentinstance from its registered
Configuration.
Storing/Retrieving registered built
Componentinstances: aComponent
instance can be registered as well to mimic Singleton behaviors. This functionality is useful is a single
Componentinstanceis used multiple times in a program.
- All the above functionalities require to specify a
RegistrationKey (either directly or indirectly).
-
REGISTRATION_CONTEXT:
RegistrationContext
-
REGISTRATION_METHODS:
Dict[str,Union[Callable,BufferedRegistration]]
- classmethod build(cls, directory, external_directories=None)
Main entrypoint of cinnamon. The registry checks provided directories for configurations to populate its
internal registry and build the dependency DAG.
- Eventually, the dependency DAG is expanded to account for variants
and invalid configurations.
- Parameters:
directory (
Union[Path,AnyStr]) – the main directory of the project containing configurations.external_directories (
Optional[List[Union[AnyStr,Path]]]) – external directories containing configurations.
- Returns:
a
ResolutionInfo` containing valid ``RegistrationKeyinvalid_keys: aResolutionInfo` containing invalid ``RegistrationKey- Return type:
valid_keys
- Raises:
RuntimeWarning – if duplicate namespaces are found.
InvalidDirectoryException – if one of the provided directories does not exist or is not a directory.
AlreadyExpandedException – if the dependency DAG has been expanded.
NotADAGException – if the dependency DAG is not a DAG.
DisconnectedGraphException – if, for some reason, the dependency DAG contains disconnected nodes.
This should never happen via cinnamon APIs, unless some manual intervention – on the dependency DAG is carried out.
- classmethod check_registration_graph()
Checks if the dependency DAG is valid.
- Raises:
AlreadyExpandedException – if the dependency DAG has been expanded.
NotADAGException – if the dependency DAG is not a DAG.
DisconnectedGraphException – if, for some reason, the dependency DAG contains disconnected nodes.
This should never happen via cinnamon APIs, unless some manual intervention – on the dependency DAG is carried out.
- Return type:
bool
- classmethod dag_resolution(cls)
Expands and resolves dependencies in registration DAG. The dependency traversal is done bottom-up by recursively expanding top nodes (i.e.,
RegistrationKeyinstances). Expanded keys are retrieved, and built for full validation.- Returns:
the set of valid registration keys invalid_keys:the set of invalid registration keys
- Return type:
valid_keys
- classmethod expand_configuration(key, valid_key_buffer=None, invalid_key_buffer=None)
- Return type:
Set[RegistrationKey[Any]]
-
expanded:
bool= False
- classmethod from_key(registration_key, **build_args)
- Return type:
TypeVar(T)
- classmethod in_graph(registration_key=None, name=None, namespace=None, tags=None)
- Return type:
bool
- classmethod in_registry(registration_key)
- Return type:
bool
- classmethod initialize()
- classmethod instantiate(registration_key=None, name=None, namespace=None, tags=None, expected_type=None, **build_args)
- Builds a
Componentinstance from its boundedConfiguration via the implicit
RegistrationKey.
- Parameters:
registration_key (
Union[RegistrationKey,str,None]) – theRegistrationKeyused to register theConfigurationclass.name (
Optional[str]) – thenameattribute ofRegistrationKeytags (
Optional[Set[str]]) – thetagsattribute ofRegistrationKeynamespace (
Optional[str]) – thenamespaceattribute ofRegistrationKeyexpected_type (
Optional[type]) – type of the component to be castbuild_args – additional custom component constructor args
- Return type:
Any- Returns:
The built component instance
- Raises:
InvalidConfigurationTypeException – if there’s a mismatch between the
Configurationclass used during registration and the type of the builtConfigurationinstance using the registeredconstructor` method (see ConfigurationInfo arguments) –
NotBoundException – if the
Configurationis not bound to any component.
- Builds a
- classmethod is_namespace_covered(registration_key)
- Return type:
bool
- classmethod load_registrations(cls, directory)
Imports a Python’s module for registration. The Registry looks for
register()andregister_method()decorators. These functions are the entry points for registrations: that is, where theRegistryAPIs are invoked to issue registrations.- Parameters:
directory (
Union[AnyStr,Path]) – path of the module- Raises:
InvalidDirectoryException – if the provided directory is not a directory or does not exist.
- classmethod parse_configuration_files(cls, directories)
- Runs a static code analyzer to inspect code scripts containing
cinnamon registrations with the goal of determining unique namespaces.
- Parameters:
directories (
List[Path]) – list of directories containing cinnamon registrations.- Returns:
unique list of namespaces mapping: mapping from namespace to pathlib.Path directories.
- Return type:
namespaces
- classmethod register_configuration(config, name, namespace, tags=None, component=None, run_method=None)
Registers a
Configurationin the registry. In particular, aConfigurationInfowrapper is stored in theRegistry.- Parameters:
config (
Configuration) – Configuration` instancename (
str) – thenamefield ofRegistrationKeynamespace (
str) – thenamespacefield ofRegistrationKeytags (
Optional[Set[str]]) – thetagsfield ofRegistrationKey,component (
Optional[str]) –Componentmodule path as stringrun_method (
Optional[str]) –Componentmethod to run when instantiating theComponentas runnable
- Returns:
- The built
RegistrationKeyinstance that can be used to retrieve the registered
ConfigurationInfo.
- The built
- Raises:
NotExpandedException – if the dependency DAG has not been expanded yet.
AlreadyRegisteredException – if the
RegistrationKeyis already usedNamespaceNotFoundException – if one of the dependencies of
RegistrationKeybelongs to a namespace not covered.
- classmethod resolve_configuration(config)
- Return type:
- classmethod resolve_external_directories(cls, external_directories)
Checks if provided directories are valid directories and exist.
- Parameters:
external_directories (
List[Union[AnyStr,Path]]) – directories to validate.- Returns:
validated directories as pathlib.Path instances
- Return type:
resolved_directories
- Raises:
InvalidDirectoryException – if any of the provided directories is not a directory or does not exist.
- classmethod retrieve_configuration(registration_key=None, name=None, namespace=None, tags=None)
- Retrieves a
Configurationinstance from the registry via its
RegistrationKey.
- Parameters:
registration_key (
Union[RegistrationKey,str,None]) – key used to register the configurationname (
Optional[str]) – thenamefield ofRegistrationKeynamespace (
Optional[str]) – thenamespacefield ofRegistrationKeytags (
Optional[Set[str]]) – thetagsfield ofRegistrationKey
- Returns:
the built configuration instance
- Return type:
config
- Retrieves a
- classmethod retrieve_configuration_info(registration_key=None, name=None, namespace=None, tags=None)
- Retrieves a
Configurationinstance from the registry via its
RegistrationKey.
- Parameters:
registration_key (
Union[RegistrationKey,str,None]) – key used to register the configurationname (
Optional[str]) – thenamefield ofRegistrationKeynamespace (
Optional[str]) – thenamespacefield ofRegistrationKeytags (
Optional[Set[str]]) – thetagsfield ofRegistrationKey
- Returns:
the built configuration instance
- Return type:
config
- Retrieves a
- classmethod retrieve_keys(names=None, namespaces=None, tags=None, special_tags=None, keys=None)
Retrieves
RegistrationKeyvia given name, tags, namespaces filters. The search can be limited to a fixed set of keys, optionally given in input.- Parameters:
names (
Union[List[str],str,None]) – a name or a list of names to filter registration keys.namespaces (
Union[List[str],str,None]) – a namespace or a list of namespaces to filter registration keys.tags (
Optional[Set[str]]) – a tag set to filter registration keys.special_tags (
Optional[Set[str]]) – a special tag set to filter registration keys.keys (
Optional[List[RegistrationKey[TypeVar(T)]]]) – an optional list ofRegistrationKeyon which to apply the search.
- Return type:
List[RegistrationKey[Any]]
Returns:
- classmethod retrieve_runnable_keys()
- Return type:
List[RegistrationKey[Any]]
- classmethod update_namespaces(cls, namespaces, module_mapping)
- cinnamon.registry.register(func)
- Return type:
Callable
- cinnamon.registry.register_method(name, namespace, tags=None, component=None, run_method=None)
- Return type:
Callable