Skip to content

declearn.utils.create_types_registry

Create a TypesRegistry backing generic (de)serialization utils.

Note: this function may either be used to create a registy with an existing type as base through functional syntax, or be placed as a decorator for class-defining code

Parameters:

Name Type Description Default
base Optional[Type]

Base class that registered entries should inherit from. If None, return a class decorator.

None
name Optional[str]

Name of the registry, used to register or access classes using the generic register_type and access_registered utility functions. If None, use base.__name__

None

Returns:

Name Type Description
base type

The input base; hence this function may be used as a decorator to register classes in the source code.

Source code in declearn/utils/_register.py
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
def create_types_registry(
    base: Optional[Type] = None,
    name: Optional[str] = None,
) -> Type:
    """Create a TypesRegistry backing generic (de)serialization utils.

    Note: this function may either be used to create a registy with
          an existing type as base through functional syntax, or be
          placed as a decorator for class-defining code

    Parameters
    ----------
    base: type or None, default=None
        Base class that registered entries should inherit from.
        If None, return a class decorator.
    name: str or None, default=None
        Name of the registry, used to register or access classes
        using the generic `register_type` and `access_registered`
        utility functions.
        If None, use `base.__name__`

    Returns
    -------
    base: type
        The input `base`; hence this function may be used as
        a decorator to register classes in the source code.
    """
    # Case when the function is being used as a class decorator.
    if base is None:
        decorator = functools.partial(create_types_registry, name=name)
        return decorator  # type: ignore
    # Create the types registry, after checking it does not already exist.
    name = base.__name__ if name is None else name
    if name in REGISTRIES:
        raise KeyError(f"TypesRegistry '{name}' already exists.")
    REGISTRIES[name] = TypesRegistry(name, base)
    return base