Skip to content

Plugins

labchain.base.base_clases.BasePlugin

Bases: ABC

Base class for all plugins in the framework.

This abstract class provides core functionality for attribute management, serialization, and type checking. It serves as the foundation for all plugin types in the framework, ensuring consistent behavior and interfaces.

Key Features
  • Automatic separation of public and private attributes
  • Type checking for methods using typeguard
  • Inheritance of type annotations from abstract methods
  • JSON serialization and deserialization
  • Rich representation for debugging
  • Strict attribute tracking rules for hash consistency
Attribute Rules
  1. Public attributes must be declared in init signature and passed to super().init()
  2. Alternatively, use **kwargs in init to allow dynamic public attributes
  3. Private attributes (_*) can be set freely as internal state
  4. Methods and special attributes (__*) are never tracked
Usage

To create a new plugin type, inherit from this class and implement the required methods. For example:

class MyCustomPlugin(BasePlugin):
    def __init__(self, param1: int, param2: str):
        super().__init__(param1=param1, param2=param2)
        self._internal_state = None  # Private: allowed

    def my_method(self):
        # Custom implementation
        pass

Attributes:

Name Type Description
_public_attributes dict

A dictionary containing all public attributes of the plugin.

_private_attributes dict

A dictionary containing all private attributes of the plugin.

Methods:

Name Description
__new__

Creates a new instance of the plugin and applies type checking.

__init__

Initializes the plugin instance, separating public and private attributes.

model_dump

Returns a copy of the public attributes.

dict

Alias for model_dump.

json

Returns a JSON-encodable representation of the public attributes.

item_dump

Returns a dictionary representation of the plugin, including its class name and parameters.

get_extra

Returns a copy of the private attributes.

model_validate

Validates and creates an instance from a dictionary.

Note

This class uses the ABC (Abstract Base Class) to define an interface that all plugins must adhere to. It also leverages Python's type hinting and the typeguard library for runtime type checking.

Source code in labchain/base/base_clases.py
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
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
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
class BasePlugin(ABC):
    """
    Base class for all plugins in the framework.

    This abstract class provides core functionality for attribute management,
    serialization, and type checking. It serves as the foundation for all plugin
    types in the framework, ensuring consistent behavior and interfaces.

    Key Features:
        - Automatic separation of public and private attributes
        - Type checking for methods using typeguard
        - Inheritance of type annotations from abstract methods
        - JSON serialization and deserialization
        - Rich representation for debugging
        - Strict attribute tracking rules for hash consistency

    Attribute Rules:
        1. Public attributes must be declared in __init__ signature and passed to super().__init__()
        2. Alternatively, use **kwargs in __init__ to allow dynamic public attributes
        3. Private attributes (_*) can be set freely as internal state
        4. Methods and special attributes (__*) are never tracked

    Usage:
        To create a new plugin type, inherit from this class and implement
        the required methods. For example:
        ```python
        class MyCustomPlugin(BasePlugin):
            def __init__(self, param1: int, param2: str):
                super().__init__(param1=param1, param2=param2)
                self._internal_state = None  # Private: allowed

            def my_method(self):
                # Custom implementation
                pass
        ```

    Attributes:
        _public_attributes (dict): A dictionary containing all public attributes of the plugin.
        _private_attributes (dict): A dictionary containing all private attributes of the plugin.

    Methods:
        __new__(cls, *args, **kwargs):
            Creates a new instance of the plugin and applies type checking.

        __init__(**kwargs):
            Initializes the plugin instance, separating public and private attributes.

        model_dump(**kwargs) -> dict:
            Returns a copy of the public attributes.

        dict(**kwargs) -> dict:
            Alias for model_dump.

        json(**kwargs) -> dict:
            Returns a JSON-encodable representation of the public attributes.

        item_dump(include=[], **kwargs) -> Dict[str, Any]:
            Returns a dictionary representation of the plugin, including its class name and parameters.

        get_extra() -> Dict[str, Any]:
            Returns a copy of the private attributes.

        model_validate(obj) -> BasePlugin:
            Validates and creates an instance from a dictionary.

    Note:
        This class uses the ABC (Abstract Base Class) to define an interface
        that all plugins must adhere to. It also leverages Python's type hinting
        and the typeguard library for runtime type checking.
    """

    _hash: str | None = None

    def __new__(cls: type[Self], *args: Any, **kwargs: Any) -> Self:
        """
        Create a new instance of the BasePlugin class.

        This method applies type checking to the __init__ method and all other methods,
        and inherits type annotations from abstract methods in parent classes.

        Args:
            *args Any: Variable length argument list.
            **kwargs Any: Arbitrary keyword arguments.

        Returns:
            BasePlugin: A new instance of the BasePlugin class.
        """
        instance = super().__new__(cls)

        # Get the signature of the __init__ method
        init_signature = inspect.signature(cls.__init__)

        # Check if __init__ has **kwargs parameter
        has_var_keyword = any(
            p.kind == inspect.Parameter.VAR_KEYWORD
            for p in init_signature.parameters.values()
        )

        # Initialize attribute dictionaries and store init signature
        instance.__dict__["_init_signature"] = init_signature
        instance.__dict__["_has_var_keyword"] = has_var_keyword

        # If **kwargs is present, ALL kwargs go to public/private attributes
        # Otherwise, only those in the signature
        if has_var_keyword:
            instance.__dict__["_public_attributes"] = {
                k: v for k, v in kwargs.items() if not k.startswith("_")
            }
            instance.__dict__["_private_attributes"] = {
                k: v for k, v in kwargs.items() if k.startswith("_")
            }
        else:
            instance.__dict__["_public_attributes"] = {
                k: v
                for k, v in kwargs.items()
                if not k.startswith("_") and k in init_signature.parameters
            }
            instance.__dict__["_private_attributes"] = {
                k: v
                for k, v in kwargs.items()
                if k.startswith("_") and k in init_signature.parameters
            }

        instance.__dict__["_initialization_complete"] = False

        # Store the original __init__ if not already wrapped
        if not hasattr(cls, "_original_init_stored"):
            original_init = cls.__init__

            # Apply typechecked FIRST to the original init (before wrapping)
            if original_init is not object.__init__:
                original_init = typechecked(original_init)

            def wrapped_init(self, *init_args, **init_kwargs):
                # Call the type-checked original __init__
                result = original_init(self, *init_args, **init_kwargs)
                # Automatically mark initialization as complete
                if type(self).__name__ == cls.__name__:
                    self.__dict__["_initialization_complete"] = True
                return result

            # Preserve metadata
            wrapped_init.__name__ = getattr(original_init, "__name__", "__init__")
            wrapped_init.__doc__ = getattr(original_init, "__doc__", None)

            # Replace __init__ with wrapped version
            cls.__init__ = wrapped_init  # type: ignore[method-assign]
            cls._original_init_stored = True

        # Inherit type annotations from abstract methods
        cls.__inherit_annotations()

        # Apply typechecked to all OTHER methods (not __init__, already done)
        for attr_name, attr_value in cls.__dict__.items():
            if inspect.isfunction(attr_value) and attr_name not in (
                "__init__",
                "__new__",
            ):
                setattr(cls, attr_name, typechecked(attr_value))

        return instance

    @classmethod
    def __inherit_annotations(cls):
        """
        Inherit type annotations from abstract methods in parent classes.

        This method is responsible for combining type annotations from abstract methods
        in parent classes with those in the concrete methods of the current class.
        This ensures that type hints are properly inherited and can be used for
        type checking and documentation purposes.

        Args:
            cls (type): The class on which this method is called.

        Note:
            This method modifies the `__annotations__` attribute of concrete methods
            in the class, combining them with annotations from corresponding abstract
            methods in parent classes.
        """
        for base in cls.__bases__:
            for name, method in base.__dict__.items():
                if getattr(method, "__isabstractmethod__", False):
                    if hasattr(cls, name):
                        concrete_method = getattr(cls, name)
                        abstract_annotations = get_type_hints(method)
                        concrete_annotations = get_type_hints(concrete_method)
                        combined_annotations = {
                            **abstract_annotations,
                            **concrete_annotations,
                        }
                        setattr(
                            concrete_method, "__annotations__", combined_annotations
                        )

    def __init__(self, **kwargs: Any):
        """
        Initialize the BasePlugin instance.

        This method is called after __new__ has set up the attribute dictionaries.
        It marks initialization as complete to enable strict attribute checking.

        Args:
            **kwargs (Any): Arbitrary keyword arguments that will be stored as attributes.
        """
        for key, value in kwargs.items():
            setattr(self, key, value)

    def __getattr__(self, name: str) -> Any:
        """
        Custom attribute getter that checks both public and private attribute dictionaries.

        Args:
            name (str): The name of the attribute to retrieve.

        Returns:
            Any: The value of the requested attribute.

        Raises:
            AttributeError: If the attribute is not found in either public or private dictionaries.
        """
        if name in self.__dict__.get("_public_attributes", {}):
            return self.__dict__["_public_attributes"][name]
        elif name in self.__dict__.get("_private_attributes", {}):
            return self.__dict__["_private_attributes"][name]
        raise AttributeError(
            f"'{self.__class__.__name__}' object has no attribute '{name}'"
        )

    def __setattr__(self, name: str, value: Any):
        """
        Custom attribute setter that separates public and private attributes.

        This method enforces the framework's attribute tracking rules:
        1. Private attributes (_*) can be set freely (internal state)
        2. Callables and special attributes (__*) are never tracked
        3. Public attributes must be declared in __init__ signature OR
           __init__ must have **kwargs to allow dynamic attributes
        4. Violation of rule 3 raises AttributeError with helpful message

        Args:
            name (str): The name of the attribute to set.
            value (Any): The value to assign to the attribute.

        Raises:
            AttributeError: If attempting to set an undeclared public attribute
                           without **kwargs in the constructor.
        """
        if "_public_attributes" not in self.__dict__:
            # During __new__ phase, use default behavior
            super().__setattr__(name, value)
            return

        # Skip callables and special attributes
        if callable(value) or name.startswith("__"):
            super().__setattr__(name, value)
            return

        initialization_complete = self.__dict__.get("_initialization_complete", False)

        # Private attributes are always allowed
        if name.startswith("_"):
            self.__dict__["_private_attributes"][name] = value
            super().__setattr__(name, value)
            return

        # For public attributes, check if allowed
        init_signature = self.__dict__.get("_init_signature")
        has_kwargs = self.__dict__.get("_has_var_keyword", False)

        is_init_param = init_signature and name in init_signature.parameters

        if not initialization_complete:
            # During initialization: only track if it's an init parameter OR we have **kwargs
            if is_init_param or has_kwargs:
                self.__dict__["_public_attributes"][name] = value
                super().__setattr__(name, value)
            else:
                # Trying to set a public attribute that's not in the signature and no **kwargs
                available_params = (
                    list(init_signature.parameters.keys()) if init_signature else []
                )
                available_params = [
                    p for p in available_params if p not in ("self", "args", "kwargs")
                ]

                raise AttributeError(
                    f"Cannot set public attribute '{name}' on {self.__class__.__name__}. "
                    f"This attribute is not declared in the __init__ signature.\n\n"
                    f"Available options:\n"
                    f"1. Add '{name}' to __init__ signature and pass to constructor:\n"
                    f"   def __init__(self, {', '.join(available_params + [name])}):\n"
                    f"       # Then instantiate with: {self.__class__.__name__}({', '.join(f'{p}=...' for p in available_params + [name])})\n\n"
                    f"2. Add **kwargs to __init__ to accept dynamic attributes:\n"
                    f"   def __init__(self, {', '.join(available_params)}, **kwargs):\n\n"
                    f"3. Make it private (internal state) by renaming to '_{name}'\n\n"
                    f"Current __init__ parameters: {available_params}"
                )
        else:
            # After initialization: can only update existing attributes or if we have **kwargs
            if has_kwargs or name in self.__dict__["_public_attributes"]:
                self.__dict__["_public_attributes"][name] = value
                super().__setattr__(name, value)
            else:
                available_params = (
                    list(init_signature.parameters.keys()) if init_signature else []
                )
                available_params = [
                    p for p in available_params if p not in ("self", "args", "kwargs")
                ]

                raise AttributeError(
                    f"Cannot set public attribute '{name}' on {self.__class__.__name__}. "
                    f"This attribute is not declared in the __init__ signature.\n\n"
                    f"Available options:\n"
                    f"1. Declare '{name}' in __init__ and pass to constructor\n"
                    f"2. Add **kwargs to __init__ for dynamic attributes\n"
                    f"3. Make it private by renaming to '_{name}'\n\n"
                    f"Current __init__ parameters: {available_params}"
                )

    def __repr__(self) -> str:
        """
        String representation of the plugin, showing its class name and public attributes.

        Returns:
            str: A string representation of the plugin.
        """
        return f"{self.__class__.__name__}({self._public_attributes})"

    def model_dump(self, **kwargs: Any) -> Dict[str, Any]:
        """
        Return a copy of the public attributes.

        Args:
            **kwargs (Any): Additional keyword arguments (not used in this method).

        Returns:
            Dict[str, Any]: A copy of the public attributes.
        """
        return self._public_attributes.copy()

    def dict(self, **kwargs: Any) -> Dict[str, Any]:
        """
        Alias for model_dump.

        Args:
            **kwargs (Any): Additional keyword arguments passed to model_dump.

        Returns:
            Dict[str, Any]: A copy of the public attributes.
        """
        return self.model_dump(**kwargs)

    def json(self, **kwargs: Any) -> Dict[str, Any]:
        """
        Return a JSON-encodable representation of the public attributes.

        Args:
            **kwargs (Any): Additional keyword arguments passed to jsonable_encoder.

        Returns:
            Dict[str, Any]: A JSON-encodable representation of the public attributes.
        """
        return jsonable_encoder(self._public_attributes, **kwargs)

    def item_dump(self, include=[], **kwargs: Any) -> Dict[str, Any]:
        """
        Return a dictionary representation of the plugin, including its class name and parameters.

        Args:
            include (list): A list of private attributes to include in the dump.
            **kwargs (Any): Additional keyword arguments passed to jsonable_encoder.

        Returns:
            Dict[str, Any]: A dictionary representation of the plugin.
        """
        included = {k: v for k, v in self._private_attributes.items() if k in include}
        dump = {
            "clazz": self.__class__.__name__,
            "version_hash": self._hash,
            "params": jsonable_encoder(
                self._public_attributes,
                custom_encoder={
                    BasePlugin: lambda v: v.item_dump(include=include, **kwargs),
                    type: lambda v: {
                        "clazz": v.__name__,
                        "version_hash": v._hash,
                    },
                    np.integer: lambda x: int(x),
                    np.floating: lambda x: float(x),
                },
                **kwargs,
            ),
        }
        if include != []:
            dump.update(
                **jsonable_encoder(
                    included,
                    custom_encoder={
                        BasePlugin: lambda v: v.item_dump(include=include, **kwargs),
                        type: lambda v: {
                            "clazz": v.__name__,
                            "version_hash": v._hash,
                        },
                        np.integer: lambda x: int(x),
                        np.floating: lambda x: float(x),
                    },
                    **kwargs,
                )
            )

        return dump

    def get_extra(self) -> Dict[str, Any]:
        """
        Return a copy of the private attributes.

        Returns:
            Dict[str, Any]: A copy of the private attributes.
        """
        return self._private_attributes.copy()

    def __getstate__(self) -> Dict[str, Any]:
        """
        Prepare the object for pickling.

        Returns:
            Dict[str, Any]: A copy of the object's __dict__.
        """
        state = self.__dict__.copy()
        return state

    def __setstate__(self, state: Dict[str, Any]):
        """
        Restore the object from its pickled state.

        Args:
            state (Dict[str, Any]): The pickled state of the object.
        """
        self.__dict__.update(state)

    @classmethod
    def model_validate(cls, obj: object) -> BasePlugin:
        """
        Validate and create an instance from a dictionary.

        Args:
            obj (Object): The object to validate and create an instance from.

        Returns:
            BasePlugin: An instance of the class.

        Raises:
            ValueError: If the input is not a dictionary.
        """
        if isinstance(obj, dict):
            return cls(**obj)
        raise ValueError(f"Cannot validate {type(obj)}")

    def __rich_repr__(self) -> Generator[Any, Any, Any]:
        """
        Rich representation of the plugin, used by the rich library.

        Yields:
            Generator[Any, Any, Any]: Key-value pairs of public attributes.
        """
        for key, value in self._public_attributes.items():
            yield key, value

    @staticmethod
    def build_from_dump(
        dump_dict: Dict[str, Any], factory: BaseFactory[BasePlugin]
    ) -> BasePlugin | Type[BasePlugin]:
        """
        Reconstruct a plugin instance from a dumped dictionary representation.

        This method handles nested plugin structures and uses a factory to create instances.

        Args:
            dump_dict (Dict[str, Any]): The dumped dictionary representation of the plugin.
            factory (BaseFactory[BasePlugin]): A factory for creating plugin instances.

        Returns:
            BasePlugin | Type[BasePlugin]: The reconstructed plugin instance or class.
        """

        clazz_name: str = dump_dict["clazz"]
        v_hash: str | None = dump_dict.get("version_hash")

        level_clazz: Type[BasePlugin] | None
        if v_hash and hasattr(factory, "get_version"):
            level_clazz = factory.get_version(clazz_name, v_hash)  # type: ignore
        else:
            level_clazz = factory.get(clazz_name)

        if level_clazz is None:
            raise ValueError(f"No class found for {clazz_name}")  # type: ignore

        if "params" in dump_dict:
            level_params: Dict[str, Any] = {}
            for k, v in dump_dict["params"].items():
                if isinstance(v, dict):
                    if "clazz" in v:
                        level_params[k] = BasePlugin.build_from_dump(v, factory)
                    else:
                        level_params[k] = v
                elif isinstance(v, list):
                    items: List[Any] = []
                    for i in v:
                        if isinstance(i, dict):
                            if "clazz" in i:
                                items.append(BasePlugin.build_from_dump(i, factory))
                            else:
                                items.append(i)
                        else:
                            items.append(i)

                    level_params[k] = items
                else:
                    level_params[k] = v
            return level_clazz(**level_params)
        else:
            return level_clazz

__getattr__(name)

Custom attribute getter that checks both public and private attribute dictionaries.

Parameters:

Name Type Description Default
name str

The name of the attribute to retrieve.

required

Returns:

Name Type Description
Any Any

The value of the requested attribute.

Raises:

Type Description
AttributeError

If the attribute is not found in either public or private dictionaries.

Source code in labchain/base/base_clases.py
def __getattr__(self, name: str) -> Any:
    """
    Custom attribute getter that checks both public and private attribute dictionaries.

    Args:
        name (str): The name of the attribute to retrieve.

    Returns:
        Any: The value of the requested attribute.

    Raises:
        AttributeError: If the attribute is not found in either public or private dictionaries.
    """
    if name in self.__dict__.get("_public_attributes", {}):
        return self.__dict__["_public_attributes"][name]
    elif name in self.__dict__.get("_private_attributes", {}):
        return self.__dict__["_private_attributes"][name]
    raise AttributeError(
        f"'{self.__class__.__name__}' object has no attribute '{name}'"
    )

__getstate__()

Prepare the object for pickling.

Returns:

Type Description
Dict[str, Any]

Dict[str, Any]: A copy of the object's dict.

Source code in labchain/base/base_clases.py
def __getstate__(self) -> Dict[str, Any]:
    """
    Prepare the object for pickling.

    Returns:
        Dict[str, Any]: A copy of the object's __dict__.
    """
    state = self.__dict__.copy()
    return state

__inherit_annotations() classmethod

Inherit type annotations from abstract methods in parent classes.

This method is responsible for combining type annotations from abstract methods in parent classes with those in the concrete methods of the current class. This ensures that type hints are properly inherited and can be used for type checking and documentation purposes.

Parameters:

Name Type Description Default
cls type

The class on which this method is called.

required
Note

This method modifies the __annotations__ attribute of concrete methods in the class, combining them with annotations from corresponding abstract methods in parent classes.

Source code in labchain/base/base_clases.py
@classmethod
def __inherit_annotations(cls):
    """
    Inherit type annotations from abstract methods in parent classes.

    This method is responsible for combining type annotations from abstract methods
    in parent classes with those in the concrete methods of the current class.
    This ensures that type hints are properly inherited and can be used for
    type checking and documentation purposes.

    Args:
        cls (type): The class on which this method is called.

    Note:
        This method modifies the `__annotations__` attribute of concrete methods
        in the class, combining them with annotations from corresponding abstract
        methods in parent classes.
    """
    for base in cls.__bases__:
        for name, method in base.__dict__.items():
            if getattr(method, "__isabstractmethod__", False):
                if hasattr(cls, name):
                    concrete_method = getattr(cls, name)
                    abstract_annotations = get_type_hints(method)
                    concrete_annotations = get_type_hints(concrete_method)
                    combined_annotations = {
                        **abstract_annotations,
                        **concrete_annotations,
                    }
                    setattr(
                        concrete_method, "__annotations__", combined_annotations
                    )

__init__(**kwargs)

Initialize the BasePlugin instance.

This method is called after new has set up the attribute dictionaries. It marks initialization as complete to enable strict attribute checking.

Parameters:

Name Type Description Default
**kwargs Any

Arbitrary keyword arguments that will be stored as attributes.

{}
Source code in labchain/base/base_clases.py
def __init__(self, **kwargs: Any):
    """
    Initialize the BasePlugin instance.

    This method is called after __new__ has set up the attribute dictionaries.
    It marks initialization as complete to enable strict attribute checking.

    Args:
        **kwargs (Any): Arbitrary keyword arguments that will be stored as attributes.
    """
    for key, value in kwargs.items():
        setattr(self, key, value)

__new__(*args, **kwargs)

Create a new instance of the BasePlugin class.

This method applies type checking to the init method and all other methods, and inherits type annotations from abstract methods in parent classes.

Parameters:

Name Type Description Default
*args Any

Variable length argument list.

required
**kwargs Any

Arbitrary keyword arguments.

required

Returns:

Name Type Description
BasePlugin Self

A new instance of the BasePlugin class.

Source code in labchain/base/base_clases.py
def __new__(cls: type[Self], *args: Any, **kwargs: Any) -> Self:
    """
    Create a new instance of the BasePlugin class.

    This method applies type checking to the __init__ method and all other methods,
    and inherits type annotations from abstract methods in parent classes.

    Args:
        *args Any: Variable length argument list.
        **kwargs Any: Arbitrary keyword arguments.

    Returns:
        BasePlugin: A new instance of the BasePlugin class.
    """
    instance = super().__new__(cls)

    # Get the signature of the __init__ method
    init_signature = inspect.signature(cls.__init__)

    # Check if __init__ has **kwargs parameter
    has_var_keyword = any(
        p.kind == inspect.Parameter.VAR_KEYWORD
        for p in init_signature.parameters.values()
    )

    # Initialize attribute dictionaries and store init signature
    instance.__dict__["_init_signature"] = init_signature
    instance.__dict__["_has_var_keyword"] = has_var_keyword

    # If **kwargs is present, ALL kwargs go to public/private attributes
    # Otherwise, only those in the signature
    if has_var_keyword:
        instance.__dict__["_public_attributes"] = {
            k: v for k, v in kwargs.items() if not k.startswith("_")
        }
        instance.__dict__["_private_attributes"] = {
            k: v for k, v in kwargs.items() if k.startswith("_")
        }
    else:
        instance.__dict__["_public_attributes"] = {
            k: v
            for k, v in kwargs.items()
            if not k.startswith("_") and k in init_signature.parameters
        }
        instance.__dict__["_private_attributes"] = {
            k: v
            for k, v in kwargs.items()
            if k.startswith("_") and k in init_signature.parameters
        }

    instance.__dict__["_initialization_complete"] = False

    # Store the original __init__ if not already wrapped
    if not hasattr(cls, "_original_init_stored"):
        original_init = cls.__init__

        # Apply typechecked FIRST to the original init (before wrapping)
        if original_init is not object.__init__:
            original_init = typechecked(original_init)

        def wrapped_init(self, *init_args, **init_kwargs):
            # Call the type-checked original __init__
            result = original_init(self, *init_args, **init_kwargs)
            # Automatically mark initialization as complete
            if type(self).__name__ == cls.__name__:
                self.__dict__["_initialization_complete"] = True
            return result

        # Preserve metadata
        wrapped_init.__name__ = getattr(original_init, "__name__", "__init__")
        wrapped_init.__doc__ = getattr(original_init, "__doc__", None)

        # Replace __init__ with wrapped version
        cls.__init__ = wrapped_init  # type: ignore[method-assign]
        cls._original_init_stored = True

    # Inherit type annotations from abstract methods
    cls.__inherit_annotations()

    # Apply typechecked to all OTHER methods (not __init__, already done)
    for attr_name, attr_value in cls.__dict__.items():
        if inspect.isfunction(attr_value) and attr_name not in (
            "__init__",
            "__new__",
        ):
            setattr(cls, attr_name, typechecked(attr_value))

    return instance

__repr__()

String representation of the plugin, showing its class name and public attributes.

Returns:

Name Type Description
str str

A string representation of the plugin.

Source code in labchain/base/base_clases.py
def __repr__(self) -> str:
    """
    String representation of the plugin, showing its class name and public attributes.

    Returns:
        str: A string representation of the plugin.
    """
    return f"{self.__class__.__name__}({self._public_attributes})"

__rich_repr__()

Rich representation of the plugin, used by the rich library.

Yields:

Type Description
Any

Generator[Any, Any, Any]: Key-value pairs of public attributes.

Source code in labchain/base/base_clases.py
def __rich_repr__(self) -> Generator[Any, Any, Any]:
    """
    Rich representation of the plugin, used by the rich library.

    Yields:
        Generator[Any, Any, Any]: Key-value pairs of public attributes.
    """
    for key, value in self._public_attributes.items():
        yield key, value

__setattr__(name, value)

Custom attribute setter that separates public and private attributes.

This method enforces the framework's attribute tracking rules: 1. Private attributes (_) can be set freely (internal state) 2. Callables and special attributes (__) are never tracked 3. Public attributes must be declared in init signature OR init must have **kwargs to allow dynamic attributes 4. Violation of rule 3 raises AttributeError with helpful message

Parameters:

Name Type Description Default
name str

The name of the attribute to set.

required
value Any

The value to assign to the attribute.

required

Raises:

Type Description
AttributeError

If attempting to set an undeclared public attribute without **kwargs in the constructor.

Source code in labchain/base/base_clases.py
def __setattr__(self, name: str, value: Any):
    """
    Custom attribute setter that separates public and private attributes.

    This method enforces the framework's attribute tracking rules:
    1. Private attributes (_*) can be set freely (internal state)
    2. Callables and special attributes (__*) are never tracked
    3. Public attributes must be declared in __init__ signature OR
       __init__ must have **kwargs to allow dynamic attributes
    4. Violation of rule 3 raises AttributeError with helpful message

    Args:
        name (str): The name of the attribute to set.
        value (Any): The value to assign to the attribute.

    Raises:
        AttributeError: If attempting to set an undeclared public attribute
                       without **kwargs in the constructor.
    """
    if "_public_attributes" not in self.__dict__:
        # During __new__ phase, use default behavior
        super().__setattr__(name, value)
        return

    # Skip callables and special attributes
    if callable(value) or name.startswith("__"):
        super().__setattr__(name, value)
        return

    initialization_complete = self.__dict__.get("_initialization_complete", False)

    # Private attributes are always allowed
    if name.startswith("_"):
        self.__dict__["_private_attributes"][name] = value
        super().__setattr__(name, value)
        return

    # For public attributes, check if allowed
    init_signature = self.__dict__.get("_init_signature")
    has_kwargs = self.__dict__.get("_has_var_keyword", False)

    is_init_param = init_signature and name in init_signature.parameters

    if not initialization_complete:
        # During initialization: only track if it's an init parameter OR we have **kwargs
        if is_init_param or has_kwargs:
            self.__dict__["_public_attributes"][name] = value
            super().__setattr__(name, value)
        else:
            # Trying to set a public attribute that's not in the signature and no **kwargs
            available_params = (
                list(init_signature.parameters.keys()) if init_signature else []
            )
            available_params = [
                p for p in available_params if p not in ("self", "args", "kwargs")
            ]

            raise AttributeError(
                f"Cannot set public attribute '{name}' on {self.__class__.__name__}. "
                f"This attribute is not declared in the __init__ signature.\n\n"
                f"Available options:\n"
                f"1. Add '{name}' to __init__ signature and pass to constructor:\n"
                f"   def __init__(self, {', '.join(available_params + [name])}):\n"
                f"       # Then instantiate with: {self.__class__.__name__}({', '.join(f'{p}=...' for p in available_params + [name])})\n\n"
                f"2. Add **kwargs to __init__ to accept dynamic attributes:\n"
                f"   def __init__(self, {', '.join(available_params)}, **kwargs):\n\n"
                f"3. Make it private (internal state) by renaming to '_{name}'\n\n"
                f"Current __init__ parameters: {available_params}"
            )
    else:
        # After initialization: can only update existing attributes or if we have **kwargs
        if has_kwargs or name in self.__dict__["_public_attributes"]:
            self.__dict__["_public_attributes"][name] = value
            super().__setattr__(name, value)
        else:
            available_params = (
                list(init_signature.parameters.keys()) if init_signature else []
            )
            available_params = [
                p for p in available_params if p not in ("self", "args", "kwargs")
            ]

            raise AttributeError(
                f"Cannot set public attribute '{name}' on {self.__class__.__name__}. "
                f"This attribute is not declared in the __init__ signature.\n\n"
                f"Available options:\n"
                f"1. Declare '{name}' in __init__ and pass to constructor\n"
                f"2. Add **kwargs to __init__ for dynamic attributes\n"
                f"3. Make it private by renaming to '_{name}'\n\n"
                f"Current __init__ parameters: {available_params}"
            )

__setstate__(state)

Restore the object from its pickled state.

Parameters:

Name Type Description Default
state Dict[str, Any]

The pickled state of the object.

required
Source code in labchain/base/base_clases.py
def __setstate__(self, state: Dict[str, Any]):
    """
    Restore the object from its pickled state.

    Args:
        state (Dict[str, Any]): The pickled state of the object.
    """
    self.__dict__.update(state)

build_from_dump(dump_dict, factory) staticmethod

Reconstruct a plugin instance from a dumped dictionary representation.

This method handles nested plugin structures and uses a factory to create instances.

Parameters:

Name Type Description Default
dump_dict Dict[str, Any]

The dumped dictionary representation of the plugin.

required
factory BaseFactory[BasePlugin]

A factory for creating plugin instances.

required

Returns:

Type Description
BasePlugin | Type[BasePlugin]

BasePlugin | Type[BasePlugin]: The reconstructed plugin instance or class.

Source code in labchain/base/base_clases.py
@staticmethod
def build_from_dump(
    dump_dict: Dict[str, Any], factory: BaseFactory[BasePlugin]
) -> BasePlugin | Type[BasePlugin]:
    """
    Reconstruct a plugin instance from a dumped dictionary representation.

    This method handles nested plugin structures and uses a factory to create instances.

    Args:
        dump_dict (Dict[str, Any]): The dumped dictionary representation of the plugin.
        factory (BaseFactory[BasePlugin]): A factory for creating plugin instances.

    Returns:
        BasePlugin | Type[BasePlugin]: The reconstructed plugin instance or class.
    """

    clazz_name: str = dump_dict["clazz"]
    v_hash: str | None = dump_dict.get("version_hash")

    level_clazz: Type[BasePlugin] | None
    if v_hash and hasattr(factory, "get_version"):
        level_clazz = factory.get_version(clazz_name, v_hash)  # type: ignore
    else:
        level_clazz = factory.get(clazz_name)

    if level_clazz is None:
        raise ValueError(f"No class found for {clazz_name}")  # type: ignore

    if "params" in dump_dict:
        level_params: Dict[str, Any] = {}
        for k, v in dump_dict["params"].items():
            if isinstance(v, dict):
                if "clazz" in v:
                    level_params[k] = BasePlugin.build_from_dump(v, factory)
                else:
                    level_params[k] = v
            elif isinstance(v, list):
                items: List[Any] = []
                for i in v:
                    if isinstance(i, dict):
                        if "clazz" in i:
                            items.append(BasePlugin.build_from_dump(i, factory))
                        else:
                            items.append(i)
                    else:
                        items.append(i)

                level_params[k] = items
            else:
                level_params[k] = v
        return level_clazz(**level_params)
    else:
        return level_clazz

dict(**kwargs)

Alias for model_dump.

Parameters:

Name Type Description Default
**kwargs Any

Additional keyword arguments passed to model_dump.

{}

Returns:

Type Description
Dict[str, Any]

Dict[str, Any]: A copy of the public attributes.

Source code in labchain/base/base_clases.py
def dict(self, **kwargs: Any) -> Dict[str, Any]:
    """
    Alias for model_dump.

    Args:
        **kwargs (Any): Additional keyword arguments passed to model_dump.

    Returns:
        Dict[str, Any]: A copy of the public attributes.
    """
    return self.model_dump(**kwargs)

get_extra()

Return a copy of the private attributes.

Returns:

Type Description
Dict[str, Any]

Dict[str, Any]: A copy of the private attributes.

Source code in labchain/base/base_clases.py
def get_extra(self) -> Dict[str, Any]:
    """
    Return a copy of the private attributes.

    Returns:
        Dict[str, Any]: A copy of the private attributes.
    """
    return self._private_attributes.copy()

item_dump(include=[], **kwargs)

Return a dictionary representation of the plugin, including its class name and parameters.

Parameters:

Name Type Description Default
include list

A list of private attributes to include in the dump.

[]
**kwargs Any

Additional keyword arguments passed to jsonable_encoder.

{}

Returns:

Type Description
Dict[str, Any]

Dict[str, Any]: A dictionary representation of the plugin.

Source code in labchain/base/base_clases.py
def item_dump(self, include=[], **kwargs: Any) -> Dict[str, Any]:
    """
    Return a dictionary representation of the plugin, including its class name and parameters.

    Args:
        include (list): A list of private attributes to include in the dump.
        **kwargs (Any): Additional keyword arguments passed to jsonable_encoder.

    Returns:
        Dict[str, Any]: A dictionary representation of the plugin.
    """
    included = {k: v for k, v in self._private_attributes.items() if k in include}
    dump = {
        "clazz": self.__class__.__name__,
        "version_hash": self._hash,
        "params": jsonable_encoder(
            self._public_attributes,
            custom_encoder={
                BasePlugin: lambda v: v.item_dump(include=include, **kwargs),
                type: lambda v: {
                    "clazz": v.__name__,
                    "version_hash": v._hash,
                },
                np.integer: lambda x: int(x),
                np.floating: lambda x: float(x),
            },
            **kwargs,
        ),
    }
    if include != []:
        dump.update(
            **jsonable_encoder(
                included,
                custom_encoder={
                    BasePlugin: lambda v: v.item_dump(include=include, **kwargs),
                    type: lambda v: {
                        "clazz": v.__name__,
                        "version_hash": v._hash,
                    },
                    np.integer: lambda x: int(x),
                    np.floating: lambda x: float(x),
                },
                **kwargs,
            )
        )

    return dump

json(**kwargs)

Return a JSON-encodable representation of the public attributes.

Parameters:

Name Type Description Default
**kwargs Any

Additional keyword arguments passed to jsonable_encoder.

{}

Returns:

Type Description
Dict[str, Any]

Dict[str, Any]: A JSON-encodable representation of the public attributes.

Source code in labchain/base/base_clases.py
def json(self, **kwargs: Any) -> Dict[str, Any]:
    """
    Return a JSON-encodable representation of the public attributes.

    Args:
        **kwargs (Any): Additional keyword arguments passed to jsonable_encoder.

    Returns:
        Dict[str, Any]: A JSON-encodable representation of the public attributes.
    """
    return jsonable_encoder(self._public_attributes, **kwargs)

model_dump(**kwargs)

Return a copy of the public attributes.

Parameters:

Name Type Description Default
**kwargs Any

Additional keyword arguments (not used in this method).

{}

Returns:

Type Description
Dict[str, Any]

Dict[str, Any]: A copy of the public attributes.

Source code in labchain/base/base_clases.py
def model_dump(self, **kwargs: Any) -> Dict[str, Any]:
    """
    Return a copy of the public attributes.

    Args:
        **kwargs (Any): Additional keyword arguments (not used in this method).

    Returns:
        Dict[str, Any]: A copy of the public attributes.
    """
    return self._public_attributes.copy()

model_validate(obj) classmethod

Validate and create an instance from a dictionary.

Parameters:

Name Type Description Default
obj Object

The object to validate and create an instance from.

required

Returns:

Name Type Description
BasePlugin BasePlugin

An instance of the class.

Raises:

Type Description
ValueError

If the input is not a dictionary.

Source code in labchain/base/base_clases.py
@classmethod
def model_validate(cls, obj: object) -> BasePlugin:
    """
    Validate and create an instance from a dictionary.

    Args:
        obj (Object): The object to validate and create an instance from.

    Returns:
        BasePlugin: An instance of the class.

    Raises:
        ValueError: If the input is not a dictionary.
    """
    if isinstance(obj, dict):
        return cls(**obj)
    raise ValueError(f"Cannot validate {type(obj)}")