Resolve
objectory.resolve ¶
Provide a generic resolution utility for creating objects from an existing instance or an objectory configuration dictionary.
objectory.resolve.resolve_object ¶
resolve_object(
obj: T | dict[str, Any], cls: type[T] = object
) -> T
Resolve an instance of cls from an existing object or a
configuration dictionary.
If obj is already an instance of cls it is returned
as-is. If it is a :class:dict, it is treated as an
objectory factory configuration and instantiated via
:func:objectory.factory.
Note
Any :class:dict (including instances of dict
subclasses, e.g. Counter or OrderedDict) is always
treated as a factory configuration, even when it is already
a valid instance of cls. Do not use this function to
resolve objects whose expected type is itself a dict
subclass.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
obj
|
T | dict[str, Any]
|
Either a fully configured instance of |
required |
cls
|
type[T]
|
The expected type. Used to validate the resolved object,
whether |
object
|
Returns:
| Type | Description |
|---|---|
T
|
A configured instance of |
Raises:
| Type | Description |
|---|---|
IncorrectTypeFactoryError
|
If |
Example
>>> from datetime import date
>>> from objectory import resolve_object
>>> # From an existing instance:
>>> d = resolve_object(date(2020, 1, 1), cls=date)
>>> # From a configuration dictionary:
>>> d = resolve_object(
... {"_target_": "datetime.date", "year": 2020, "month": 1, "day": 1}, cls=date
... )