Skip to content

confingy.tracking#

tracking #

Lazy #

Bases: Generic[T]

A proxy that delays instantiation until the object is actually used.

This class wraps a configuration for an object and only creates the actual instance when the instantiate() method is called.

This class is returned by the lazy function or when using the Lazy classmethod on a @track-decorated class.

It can also be used as a type hint:

def process(model: Lazy[Model]):
    # model must be a Lazy[Model]
    actual_model = model.instantiate()

All internal attributes of the Lazy object are prepended with '_confingy_' to avoid
name collisions with the wrapped class's constructor arguments (including underscore-prefixed ones).

Source code in src/confingy/tracking.py
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
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
class Lazy(Generic[T]):
    """
    A proxy that delays instantiation until the object is actually used.

    This class wraps a configuration for an object and only creates the
    actual instance when the `instantiate()` method is called.

    This class is returned by the [lazy][confingy.tracking.lazy] function or when using the
    `Lazy` classmethod on a [@track][confingy.tracking.track]-decorated class.

    It can also be used as a type hint:
    ```python
    def process(model: Lazy[Model]):
        # model must be a Lazy[Model]
        actual_model = model.instantiate()

    All internal attributes of the Lazy object are prepended with '_confingy_' to avoid
    name collisions with the wrapped class's constructor arguments (including underscore-prefixed ones).
    ```
    """

    @classmethod
    def __get_pydantic_core_schema__(
        cls, source: Any, handler: GetCoreSchemaHandler
    ) -> CoreSchema:
        """Validate `Lazy[X]` type hints.

        The value must be a Lazy. If its class isn't `X` or a subclass (or a
        member of `X`, for unions), a warning is emitted rather than an error,
        since configs often rely on duck typing. See `_lazy_hint_targets` for the
        targets that match any Lazy.
        """
        args = get_args(source)
        targets = _lazy_hint_targets(args[0]) if args else ()

        def validate(value: Any) -> Any:
            if not isinstance(value, Lazy):
                raise ValueError(f"Expected a Lazy, got {type(value).__name__}")
            if targets and not _is_subclass_of_any(value._confingy_actual_cls, targets):
                _warn_lazy_hint_mismatch(targets, value._confingy_actual_cls)
            return value

        return core_schema.no_info_plain_validator_function(validate)

    def __init__(
        self,
        cls: type,  # Untyped to allow T to be covariant
        config: dict[str, Any],
        skip_validation: bool = False,
        *,
        _was_instantiated: bool = False,
        _skip_post_config_hook: bool = False,
    ):
        self._confingy_cls = cls
        self._confingy_config = config
        self._confingy_was_instantiated = _was_instantiated

        # Handle lazy factory functions
        if hasattr(cls, "_original_cls"):
            self._confingy_actual_cls = cast(Any, cls)._original_cls
        else:
            self._confingy_actual_cls = cls

        if G_DISABLE_VALIDATION:
            skip_validation = True

        _warn_if_params_shadow_lazy(self._confingy_actual_cls)

        # Create validation model if validation is enabled
        self._confingy_validation_model: type[BaseModel] | None = None
        if not skip_validation:
            self._confingy_validation_model = _create_validation_model(
                self._confingy_actual_cls
            )
            self._validate_config()

        # Store metadata for serialization
        self._confingy_lazy_info = {
            "class": get_class_name(self._confingy_actual_cls),
            "module": get_module_name(self._confingy_actual_cls),
            "class_hash": hash_class(self._confingy_actual_cls),
        }

        # Initialize hook guard flag
        self._confingy_in_hook = False

        # Run post-config hook on initial creation (unless skipped)
        if not _skip_post_config_hook:
            self._run_post_config_hook()

    def _validate_config(self):
        """Validate the configuration against the class's __init__ signature."""
        if self._confingy_validation_model is None:
            return
        try:
            self._confingy_validation_model(**self._confingy_config)
        except PydanticValidationError as e:
            raise ValidationError(
                e, self._confingy_actual_cls.__name__, self._confingy_config
            ) from None

    def _run_post_config_hook(
        self, saved_config: dict[str, Any] | None = None, changed_key: str | None = None
    ) -> None:
        """Run the __post_config__ hook if defined on the class.

        The hook is called after config creation or update. It receives the Lazy
        instance and can modify it via attribute access. The hook should return
        the (possibly modified) Lazy instance.

        Args:
            saved_config: The config state before modification for rollback (only for updates)
            changed_key: The key that was changed (None if called from __init__)
        """
        if not hasattr(self._confingy_actual_cls, "__post_config__"):
            return

        if self._confingy_in_hook:
            return  # Prevent recursion

        self._confingy_in_hook = True
        try:
            result = self._confingy_actual_cls.__post_config__(self, changed_key)
            # If hook returns a different Lazy, use its config
            if result is not None and result is not self:
                self._confingy_config = result._confingy_config

            # Re-validate after hook completes to catch any invalid modifications
            # (e.g., direct _config manipulation or invalid values from returned Lazy)
            self._validate_config()
        except Exception:
            # Rollback entire config on hook failure (only if this was an update)
            if changed_key is not None and saved_config is not None:
                self._confingy_config = saved_config
            raise
        finally:
            self._confingy_in_hook = False

    def __getattr__(self, name: str) -> Any:
        """Access configuration parameters as attributes.

        This allows direct access to the constructor arguments stored in the Lazy config,
        enabling easy inspection and chained access for nested Lazy objects.

        Examples:
            ```python
            lazy = MyDataset.lazy(data=[1,2,3], processor=Pipeline.lazy(scalers=[...]))
            lazy.data           # Returns [1,2,3]
            lazy.processor      # Returns the Pipeline Lazy
            lazy.processor.scalers  # Chained access works!
            ```
        """
        # Check if the attribute exists in the validated config
        # NOTE: Use __dict__ to avoid recursion with __getattr__
        if (
            "_confingy_config" in self.__dict__
            and name in self.__dict__["_confingy_config"]
        ):
            return self._confingy_config[name]
        # Use __dict__.get() to avoid recursion during unpickling
        # (when __getattr__ is called before __init__ completes)
        actual_cls = self.__dict__.get("_confingy_actual_cls")
        config = self.__dict__.get("_confingy_config", {})
        cls_name = (
            getattr(actual_cls, "__name__", "Unknown") if actual_cls else "Unknown"
        )
        raise AttributeError(
            f"'{cls_name}' has no parameter '{name}'. "
            f"Available parameters: {list(config.keys())}"
        )

    def __setattr__(self, name: str, value: Any) -> None:
        """Set configuration parameters as attributes with validation.

        Internal attributes (starting with '_confingy_') are set normally.
        Other attributes update the configuration and trigger validation.

        Examples:
            ```python
            lazy = MyDataset.lazy(data=[1,2,3], processor=p)
            lazy.data = [4,5,6]      # Updates config, validates
            lazy.processor = new_p   # Updates config, validates
            ```
        """
        # Internal confingy attributes are set normally on the object
        if name.startswith("_confingy_"):
            object.__setattr__(self, name, value)
            return

        # Ensure we're initialized
        if "_confingy_config" not in self.__dict__:
            raise AttributeError(
                f"Cannot set '{name}' - Lazy object not fully initialized"
            )

        # Check if this is a valid parameter
        if name not in self._confingy_config:
            raise AttributeError(
                f"'{self._confingy_actual_cls.__name__}' has no parameter '{name}'. "
                f"Available parameters: {list(self._confingy_config.keys())}"
            )

        # Save entire config before modification for potential rollback
        saved_config = self._confingy_config.copy()
        old_value = self._confingy_config[name]
        self._confingy_config[name] = value

        # Validate if validation is enabled
        if self._confingy_validation_model is not None:
            try:
                self._confingy_validation_model(**self._confingy_config)
            except PydanticValidationError as e:
                # Rollback on validation failure
                self._confingy_config[name] = old_value
                raise ValidationError(
                    e, self._confingy_actual_cls.__name__, self._confingy_config
                ) from None

        # Run post-config hook after successful update
        self._run_post_config_hook(saved_config=saved_config, changed_key=name)

    def get_config(self) -> dict[str, Any]:
        """
        Get a copy of the configuration used to create this lazy instance.
        The returned dictionary contains the constructor arguments for the lazy instance.
        """
        return self._confingy_config.copy()

    def copy(self, **updates: Any) -> "Lazy[T]":
        """
        Create a new Lazy instance with updated configuration.

        This provides an immutable update pattern - the original Lazy is unchanged,
        and a new Lazy is returned with the specified updates applied.

        Args:
            **updates: Keyword arguments to update in the new Lazy's config.
                      These override the original config values.

        Returns:
            A new Lazy instance with the updated configuration.

        Examples:
            ```python
            lazy = MyDataset.lazy(data=[1,2,3], processor=p)

            # Create a new Lazy with updated data
            new_lazy = lazy.copy(data=[4,5,6])

            # Original is unchanged
            assert lazy.data == [1,2,3]
            assert new_lazy.data == [4,5,6]

            # Chain copies for multiple updates
            another = lazy.copy(data=[7,8,9]).copy(processor=new_p)
            ```
        """
        # Start with current config
        new_config = self._confingy_config.copy()

        # Apply updates
        for key, value in updates.items():
            if key not in new_config:
                raise AttributeError(
                    f"'{self._confingy_actual_cls.__name__}' has no parameter '{key}'. "
                    f"Available parameters: {list(new_config.keys())}"
                )
            new_config[key] = value

        # Create new Lazy with updated config, preserving _was_instantiated
        # Skip validation if this Lazy came from lens() (type hints won't match)
        skip_val = (
            self._confingy_was_instantiated or self._confingy_validation_model is None
        )
        # Skip the post-config hook if we're being called from within a hook
        # (to prevent infinite recursion when hook uses copy() to return modified instance)
        skip_hook = self._confingy_in_hook
        return Lazy(
            self._confingy_cls,
            new_config,
            skip_validation=skip_val,
            _was_instantiated=self._confingy_was_instantiated,
            _skip_post_config_hook=skip_hook,
        )

    def instantiate(self) -> T:
        """Create and return an instance of the wrapped class.

        Each call creates a new instance - this is a factory method.

        Returns:
            A new instance of the wrapped class, constructed with the stored config.
        """
        logger.debug(f"Instantiating {self._confingy_actual_cls.__name__}")
        return _instantiate(self._confingy_actual_cls, self._confingy_config)

    def unlens(self) -> Any:
        """Reconstruct the object, preserving the original laziness structure.

        When a Lazy is created via `lens()` from a tracked instance, calling
        `unlens()` will instantiate it. When created from an existing Lazy,
        it remains a Lazy.

        This enables a round-trip: `lens(obj) -> modify -> unlens()` preserves
        whether each node was originally Lazy or instantiated.

        Only modified nodes and their ancestors are rebuilt: a node that was not
        changed after `lens()` is returned as the original object. A node shared
        by several parents is rebuilt once and stays shared.

        Returns:
            Either an instantiated object or a new Lazy, depending on how
            this Lazy was created.

        Examples:
            ```python
            # From tracked instance - unlens() instantiates
            obj = Outer(middle=Middle(inner=Inner(value=42)))
            l = lens(obj)
            l.middle.inner.value = 100
            new_obj = l.unlens()  # Returns Outer instance

            # From Lazy - unlens() returns Lazy
            lazy = Outer.lazy(middle=Middle.lazy(inner=Inner.lazy(value=42)))
            l = lens(lazy)
            l.middle.inner.value = 100
            new_lazy = l.unlens()  # Returns Lazy[Outer]
            ```
        """
        return self._unlens({})

    def _unlens(self, memo: dict[int, Any]) -> Any:
        """Implementation of `unlens()`, memoised by id so shared nodes stay shared."""
        if id(self) in memo:
            return memo[id(self)]

        from confingy.serde import HandlerRegistry

        handlers = HandlerRegistry.get_default_handlers()

        def unlens_value(value: Any) -> Any:
            """Recursively unlens a value, using handlers for containers."""
            if is_lazy_instance(value):
                return value._unlens(memo)

            # Use handlers for container types
            for handler in handlers:
                if handler.can_handle(value):
                    return handler.map_children(value, unlens_value)

            return value

        # Process all config values
        realized_config = {k: unlens_value(v) for k, v in self._confingy_config.items()}

        # Reuse the object this Lazy was lensed from if nothing changed
        source = self.__dict__.get("_confingy_source")
        source_config = None
        if is_lazy_instance(source):
            source_config = source._confingy_config
        elif is_tracked_instance(source):
            source_config = source._tracked_info["init_args"]

        result: Any
        if source_config is not None and _same_config(realized_config, source_config):
            result = source
        elif self._confingy_was_instantiated:
            # This Lazy was created from a tracked instance - instantiate. Use
            # _create_tracked_instance so the result stays tracked even if the
            # class isn't decorated (e.g. created with track(Cls, ...) or
            # deserialized from an undecorated class).
            result = _create_tracked_instance(
                self._confingy_actual_cls, (), realized_config, _validate=False
            )
        else:
            # This was originally a Lazy - return new Lazy
            # Always skip the post-config hook since unlens() is a structural
            # transformation, not a semantic creation. Hooks already ran on
            # setattr when values were modified.
            result = Lazy(
                self._confingy_cls, realized_config, _skip_post_config_hook=True
            )
        memo[id(self)] = result
        return result

    def __call__(self, *args: Any, **kwargs: Any) -> "Lazy[T]":
        """Make Lazy callable to support the lazy(Class)(...) pattern.

        When called with no arguments, returns self.
        When called with arguments, merges them into the config and returns a new Lazy.
        """
        if not args and not kwargs:
            return self

        # Merge provided args into config
        new_kwargs = _args_to_kwargs(
            self._confingy_cls, args, kwargs, include_defaults=False
        )
        merged_config = {**self._confingy_config, **new_kwargs}

        # Preserve _was_instantiated and skip_validation like copy() does
        skip_val = (
            self._confingy_was_instantiated or self._confingy_validation_model is None
        )
        return Lazy(
            self._confingy_cls,
            merged_config,
            skip_validation=skip_val,
            _was_instantiated=self._confingy_was_instantiated,
        )

    def __repr__(self) -> str:
        cls_name = getattr(
            self._confingy_actual_cls, "__name__", str(self._confingy_actual_cls)
        )
        config_preview = {k: v for k, v in list(self._confingy_config.items())[:3]}
        if len(self._confingy_config) > 3:
            config_preview["..."] = f"and {len(self._confingy_config) - 3} more"
        return f"Lazy<{cls_name}>(config={config_preview})"

    def __getstate__(self) -> dict:
        """Prepare state for pickling, excluding unpicklable validation model."""
        state = self.__dict__.copy()
        # Track whether validation was enabled before pickling
        state["_confingy_had_validation"] = (
            state["_confingy_validation_model"] is not None
        )
        # Remove the dynamically-created validation model - it can't be pickled
        state["_confingy_validation_model"] = None
        return state

    def __setstate__(self, state: dict) -> None:
        """Restore state after unpickling."""
        # Extract and remove the temporary flag
        had_validation = state.pop("_confingy_had_validation", True)
        self.__dict__.update(state)
        # Only rebuild validation model if it was originally enabled
        if had_validation:
            self._confingy_validation_model = _create_validation_model(
                self._confingy_actual_cls
            )
        else:
            self._confingy_validation_model = None

__get_pydantic_core_schema__ classmethod #

__get_pydantic_core_schema__(
    source: Any, handler: GetCoreSchemaHandler
) -> CoreSchema

Validate Lazy[X] type hints.

The value must be a Lazy. If its class isn't X or a subclass (or a member of X, for unions), a warning is emitted rather than an error, since configs often rely on duck typing. See _lazy_hint_targets for the targets that match any Lazy.

Source code in src/confingy/tracking.py
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
@classmethod
def __get_pydantic_core_schema__(
    cls, source: Any, handler: GetCoreSchemaHandler
) -> CoreSchema:
    """Validate `Lazy[X]` type hints.

    The value must be a Lazy. If its class isn't `X` or a subclass (or a
    member of `X`, for unions), a warning is emitted rather than an error,
    since configs often rely on duck typing. See `_lazy_hint_targets` for the
    targets that match any Lazy.
    """
    args = get_args(source)
    targets = _lazy_hint_targets(args[0]) if args else ()

    def validate(value: Any) -> Any:
        if not isinstance(value, Lazy):
            raise ValueError(f"Expected a Lazy, got {type(value).__name__}")
        if targets and not _is_subclass_of_any(value._confingy_actual_cls, targets):
            _warn_lazy_hint_mismatch(targets, value._confingy_actual_cls)
        return value

    return core_schema.no_info_plain_validator_function(validate)

__getattr__ #

__getattr__(name: str) -> Any

Access configuration parameters as attributes.

This allows direct access to the constructor arguments stored in the Lazy config, enabling easy inspection and chained access for nested Lazy objects.

Examples:

lazy = MyDataset.lazy(data=[1,2,3], processor=Pipeline.lazy(scalers=[...]))
lazy.data           # Returns [1,2,3]
lazy.processor      # Returns the Pipeline Lazy
lazy.processor.scalers  # Chained access works!
Source code in src/confingy/tracking.py
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
def __getattr__(self, name: str) -> Any:
    """Access configuration parameters as attributes.

    This allows direct access to the constructor arguments stored in the Lazy config,
    enabling easy inspection and chained access for nested Lazy objects.

    Examples:
        ```python
        lazy = MyDataset.lazy(data=[1,2,3], processor=Pipeline.lazy(scalers=[...]))
        lazy.data           # Returns [1,2,3]
        lazy.processor      # Returns the Pipeline Lazy
        lazy.processor.scalers  # Chained access works!
        ```
    """
    # Check if the attribute exists in the validated config
    # NOTE: Use __dict__ to avoid recursion with __getattr__
    if (
        "_confingy_config" in self.__dict__
        and name in self.__dict__["_confingy_config"]
    ):
        return self._confingy_config[name]
    # Use __dict__.get() to avoid recursion during unpickling
    # (when __getattr__ is called before __init__ completes)
    actual_cls = self.__dict__.get("_confingy_actual_cls")
    config = self.__dict__.get("_confingy_config", {})
    cls_name = (
        getattr(actual_cls, "__name__", "Unknown") if actual_cls else "Unknown"
    )
    raise AttributeError(
        f"'{cls_name}' has no parameter '{name}'. "
        f"Available parameters: {list(config.keys())}"
    )

__setattr__ #

__setattr__(name: str, value: Any) -> None

Set configuration parameters as attributes with validation.

Internal attributes (starting with 'confingy') are set normally. Other attributes update the configuration and trigger validation.

Examples:

lazy = MyDataset.lazy(data=[1,2,3], processor=p)
lazy.data = [4,5,6]      # Updates config, validates
lazy.processor = new_p   # Updates config, validates
Source code in src/confingy/tracking.py
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
def __setattr__(self, name: str, value: Any) -> None:
    """Set configuration parameters as attributes with validation.

    Internal attributes (starting with '_confingy_') are set normally.
    Other attributes update the configuration and trigger validation.

    Examples:
        ```python
        lazy = MyDataset.lazy(data=[1,2,3], processor=p)
        lazy.data = [4,5,6]      # Updates config, validates
        lazy.processor = new_p   # Updates config, validates
        ```
    """
    # Internal confingy attributes are set normally on the object
    if name.startswith("_confingy_"):
        object.__setattr__(self, name, value)
        return

    # Ensure we're initialized
    if "_confingy_config" not in self.__dict__:
        raise AttributeError(
            f"Cannot set '{name}' - Lazy object not fully initialized"
        )

    # Check if this is a valid parameter
    if name not in self._confingy_config:
        raise AttributeError(
            f"'{self._confingy_actual_cls.__name__}' has no parameter '{name}'. "
            f"Available parameters: {list(self._confingy_config.keys())}"
        )

    # Save entire config before modification for potential rollback
    saved_config = self._confingy_config.copy()
    old_value = self._confingy_config[name]
    self._confingy_config[name] = value

    # Validate if validation is enabled
    if self._confingy_validation_model is not None:
        try:
            self._confingy_validation_model(**self._confingy_config)
        except PydanticValidationError as e:
            # Rollback on validation failure
            self._confingy_config[name] = old_value
            raise ValidationError(
                e, self._confingy_actual_cls.__name__, self._confingy_config
            ) from None

    # Run post-config hook after successful update
    self._run_post_config_hook(saved_config=saved_config, changed_key=name)

get_config #

get_config() -> dict[str, Any]

Get a copy of the configuration used to create this lazy instance. The returned dictionary contains the constructor arguments for the lazy instance.

Source code in src/confingy/tracking.py
622
623
624
625
626
627
def get_config(self) -> dict[str, Any]:
    """
    Get a copy of the configuration used to create this lazy instance.
    The returned dictionary contains the constructor arguments for the lazy instance.
    """
    return self._confingy_config.copy()

copy #

copy(**updates: Any) -> Lazy[T]

Create a new Lazy instance with updated configuration.

This provides an immutable update pattern - the original Lazy is unchanged, and a new Lazy is returned with the specified updates applied.

Parameters:

Name Type Description Default
**updates Any

Keyword arguments to update in the new Lazy's config. These override the original config values.

{}

Returns:

Type Description
Lazy[T]

A new Lazy instance with the updated configuration.

Examples:

lazy = MyDataset.lazy(data=[1,2,3], processor=p)

# Create a new Lazy with updated data
new_lazy = lazy.copy(data=[4,5,6])

# Original is unchanged
assert lazy.data == [1,2,3]
assert new_lazy.data == [4,5,6]

# Chain copies for multiple updates
another = lazy.copy(data=[7,8,9]).copy(processor=new_p)
Source code in src/confingy/tracking.py
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
def copy(self, **updates: Any) -> "Lazy[T]":
    """
    Create a new Lazy instance with updated configuration.

    This provides an immutable update pattern - the original Lazy is unchanged,
    and a new Lazy is returned with the specified updates applied.

    Args:
        **updates: Keyword arguments to update in the new Lazy's config.
                  These override the original config values.

    Returns:
        A new Lazy instance with the updated configuration.

    Examples:
        ```python
        lazy = MyDataset.lazy(data=[1,2,3], processor=p)

        # Create a new Lazy with updated data
        new_lazy = lazy.copy(data=[4,5,6])

        # Original is unchanged
        assert lazy.data == [1,2,3]
        assert new_lazy.data == [4,5,6]

        # Chain copies for multiple updates
        another = lazy.copy(data=[7,8,9]).copy(processor=new_p)
        ```
    """
    # Start with current config
    new_config = self._confingy_config.copy()

    # Apply updates
    for key, value in updates.items():
        if key not in new_config:
            raise AttributeError(
                f"'{self._confingy_actual_cls.__name__}' has no parameter '{key}'. "
                f"Available parameters: {list(new_config.keys())}"
            )
        new_config[key] = value

    # Create new Lazy with updated config, preserving _was_instantiated
    # Skip validation if this Lazy came from lens() (type hints won't match)
    skip_val = (
        self._confingy_was_instantiated or self._confingy_validation_model is None
    )
    # Skip the post-config hook if we're being called from within a hook
    # (to prevent infinite recursion when hook uses copy() to return modified instance)
    skip_hook = self._confingy_in_hook
    return Lazy(
        self._confingy_cls,
        new_config,
        skip_validation=skip_val,
        _was_instantiated=self._confingy_was_instantiated,
        _skip_post_config_hook=skip_hook,
    )

instantiate #

instantiate() -> T

Create and return an instance of the wrapped class.

Each call creates a new instance - this is a factory method.

Returns:

Type Description
T

A new instance of the wrapped class, constructed with the stored config.

Source code in src/confingy/tracking.py
686
687
688
689
690
691
692
693
694
695
def instantiate(self) -> T:
    """Create and return an instance of the wrapped class.

    Each call creates a new instance - this is a factory method.

    Returns:
        A new instance of the wrapped class, constructed with the stored config.
    """
    logger.debug(f"Instantiating {self._confingy_actual_cls.__name__}")
    return _instantiate(self._confingy_actual_cls, self._confingy_config)

unlens #

unlens() -> Any

Reconstruct the object, preserving the original laziness structure.

When a Lazy is created via lens() from a tracked instance, calling unlens() will instantiate it. When created from an existing Lazy, it remains a Lazy.

This enables a round-trip: lens(obj) -> modify -> unlens() preserves whether each node was originally Lazy or instantiated.

Only modified nodes and their ancestors are rebuilt: a node that was not changed after lens() is returned as the original object. A node shared by several parents is rebuilt once and stays shared.

Returns:

Type Description
Any

Either an instantiated object or a new Lazy, depending on how

Any

this Lazy was created.

Examples:

# From tracked instance - unlens() instantiates
obj = Outer(middle=Middle(inner=Inner(value=42)))
l = lens(obj)
l.middle.inner.value = 100
new_obj = l.unlens()  # Returns Outer instance

# From Lazy - unlens() returns Lazy
lazy = Outer.lazy(middle=Middle.lazy(inner=Inner.lazy(value=42)))
l = lens(lazy)
l.middle.inner.value = 100
new_lazy = l.unlens()  # Returns Lazy[Outer]
Source code in src/confingy/tracking.py
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
def unlens(self) -> Any:
    """Reconstruct the object, preserving the original laziness structure.

    When a Lazy is created via `lens()` from a tracked instance, calling
    `unlens()` will instantiate it. When created from an existing Lazy,
    it remains a Lazy.

    This enables a round-trip: `lens(obj) -> modify -> unlens()` preserves
    whether each node was originally Lazy or instantiated.

    Only modified nodes and their ancestors are rebuilt: a node that was not
    changed after `lens()` is returned as the original object. A node shared
    by several parents is rebuilt once and stays shared.

    Returns:
        Either an instantiated object or a new Lazy, depending on how
        this Lazy was created.

    Examples:
        ```python
        # From tracked instance - unlens() instantiates
        obj = Outer(middle=Middle(inner=Inner(value=42)))
        l = lens(obj)
        l.middle.inner.value = 100
        new_obj = l.unlens()  # Returns Outer instance

        # From Lazy - unlens() returns Lazy
        lazy = Outer.lazy(middle=Middle.lazy(inner=Inner.lazy(value=42)))
        l = lens(lazy)
        l.middle.inner.value = 100
        new_lazy = l.unlens()  # Returns Lazy[Outer]
        ```
    """
    return self._unlens({})

__call__ #

__call__(*args: Any, **kwargs: Any) -> Lazy[T]

Make Lazy callable to support the lazy(Class)(...) pattern.

When called with no arguments, returns self. When called with arguments, merges them into the config and returns a new Lazy.

Source code in src/confingy/tracking.py
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
def __call__(self, *args: Any, **kwargs: Any) -> "Lazy[T]":
    """Make Lazy callable to support the lazy(Class)(...) pattern.

    When called with no arguments, returns self.
    When called with arguments, merges them into the config and returns a new Lazy.
    """
    if not args and not kwargs:
        return self

    # Merge provided args into config
    new_kwargs = _args_to_kwargs(
        self._confingy_cls, args, kwargs, include_defaults=False
    )
    merged_config = {**self._confingy_config, **new_kwargs}

    # Preserve _was_instantiated and skip_validation like copy() does
    skip_val = (
        self._confingy_was_instantiated or self._confingy_validation_model is None
    )
    return Lazy(
        self._confingy_cls,
        merged_config,
        skip_validation=skip_val,
        _was_instantiated=self._confingy_was_instantiated,
    )

__getstate__ #

__getstate__() -> dict

Prepare state for pickling, excluding unpicklable validation model.

Source code in src/confingy/tracking.py
821
822
823
824
825
826
827
828
829
830
def __getstate__(self) -> dict:
    """Prepare state for pickling, excluding unpicklable validation model."""
    state = self.__dict__.copy()
    # Track whether validation was enabled before pickling
    state["_confingy_had_validation"] = (
        state["_confingy_validation_model"] is not None
    )
    # Remove the dynamically-created validation model - it can't be pickled
    state["_confingy_validation_model"] = None
    return state

__setstate__ #

__setstate__(state: dict) -> None

Restore state after unpickling.

Source code in src/confingy/tracking.py
832
833
834
835
836
837
838
839
840
841
842
843
def __setstate__(self, state: dict) -> None:
    """Restore state after unpickling."""
    # Extract and remove the temporary flag
    had_validation = state.pop("_confingy_had_validation", True)
    self.__dict__.update(state)
    # Only rebuild validation model if it was originally enabled
    if had_validation:
        self._confingy_validation_model = _create_validation_model(
            self._confingy_actual_cls
        )
    else:
        self._confingy_validation_model = None

disable_validation #

disable_validation()

Context manager to disable validation for tracked and lazy objects.

Examples:

class NonTrackedObject:
    def __init__(self, value):
        self.value = value

class TrackedObject:
    def __init__(self, obj: NonTrackedObject):
        self.obj = obj

# Raises validation error
track(TrackedObject)(obj=NonTrackedObject(value=10))

with disable_validation():
    # No validation error
    track(TrackedObject)(obj=NonTrackedObject(value=10))
Source code in src/confingy/tracking.py
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
@contextmanager
def disable_validation():
    """
    Context manager to disable validation for tracked and lazy objects.

    Examples:
        ```python
        class NonTrackedObject:
            def __init__(self, value):
                self.value = value

        class TrackedObject:
            def __init__(self, obj: NonTrackedObject):
                self.obj = obj

        # Raises validation error
        track(TrackedObject)(obj=NonTrackedObject(value=10))

        with disable_validation():
            # No validation error
            track(TrackedObject)(obj=NonTrackedObject(value=10))
        ```
    """
    global G_DISABLE_VALIDATION
    previous = G_DISABLE_VALIDATION
    G_DISABLE_VALIDATION = True
    try:
        yield
    finally:
        G_DISABLE_VALIDATION = previous

is_class #

is_class(obj: Any) -> TypeGuard[type[Any]]

Check if an object is a class.

Source code in src/confingy/tracking.py
85
86
87
def is_class(obj: Any) -> TypeGuard[type[Any]]:
    """Check if an object is a class."""
    return isinstance(obj, type)

lazy #

lazy(cls: Callable[P, T]) -> Callable[P, Lazy[T]]
lazy(
    cls: Callable[P, T], *args: args, **kwargs: kwargs
) -> Lazy[T]
lazy(cls: Any, *args: Any, **kwargs: Any) -> Any

Create a lazy instance of a @track-decorated class.

This function provides explicit lazy instantiation. Classes should be decorated with @track, and then lazy is used when you want deferred instantiation.

Examples:

@track
class ExpensiveModel:
    def __init__(self, size: int):
        self.weights = np.random.randn(size, size)

# Normal instantiation (immediate)
model = ExpensiveModel(size=1000)

# Lazy instantiation (deferred) - two ways:
lazy_model = lazy(ExpensiveModel)(size=1000)  # Returns Lazy[ExpensiveModel]
# Or more directly:
lazy_model = lazy(ExpensiveModel, size=1000)  # Returns Lazy[ExpensiveModel]

# Access when needed
result = lazy_model.instantiate().forward(data)
Source code in src/confingy/tracking.py
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
def lazy(cls: Any, *args: Any, **kwargs: Any) -> Any:
    """
    Create a lazy instance of a [@track][confingy.tracking.track]-decorated class.

    This function provides explicit lazy instantiation. Classes should be
    decorated with [@track][confingy.tracking.track], and then [lazy][confingy.tracking.lazy]
    is used when you want deferred instantiation.

    Examples:
        ```python
        @track
        class ExpensiveModel:
            def __init__(self, size: int):
                self.weights = np.random.randn(size, size)

        # Normal instantiation (immediate)
        model = ExpensiveModel(size=1000)

        # Lazy instantiation (deferred) - two ways:
        lazy_model = lazy(ExpensiveModel)(size=1000)  # Returns Lazy[ExpensiveModel]
        # Or more directly:
        lazy_model = lazy(ExpensiveModel, size=1000)  # Returns Lazy[ExpensiveModel]

        # Access when needed
        result = lazy_model.instantiate().forward(data)
        ```
    """
    if not is_class(cls):
        raise TypeError(f"lazy() requires a class, got {type(cls)}")

    if args or kwargs:
        # Direct instantiation: lazy(Class, arg1, arg2, ...)
        init_kwargs = _args_to_kwargs(cls, args, kwargs)
        return Lazy(cls, init_kwargs)
    else:
        # Factory pattern: lazy(Class) returns a function
        def lazy_factory(*factory_args: Any, **factory_kwargs: Any) -> Lazy[T]:
            init_kwargs = _args_to_kwargs(cls, factory_args, factory_kwargs)
            return Lazy(cls, init_kwargs)

        return lazy_factory

lens #

lens(obj: Any) -> Lazy[Any]

Convert a tracked or Lazy instance to a Lazy for nested parameter updates.

This function provides a unified interface for modifying nested configurations. After making changes, call unlens() to reconstruct the object with the original laziness structure preserved.

Parameters:

Name Type Description Default
obj Any

Either a tracked instance (has _tracked_info) or a Lazy instance.

required

Returns:

Type Description
Lazy[Any]

A Lazy instance that can be modified via attribute access.

Examples:

@track
class Outer:
    def __init__(self, middle: Middle):
        self.middle = middle

@track
class Middle:
    def __init__(self, inner: Inner):
        self.inner = inner

@track
class Inner:
    def __init__(self, value: int):
        self.value = value

# Create a tracked instance
obj = Outer(middle=Middle(inner=Inner(value=42)))

# Use lens to modify nested values
l = lens(obj)
l.middle.inner.value = 100

# Reconstruct with original structure (all instantiated)
new_obj = l.unlens()
assert new_obj.middle.inner.value == 100

# Works with Lazy instances too
lazy_obj = Outer.lazy(middle=Middle.lazy(inner=Inner.lazy(value=42)))
l = lens(lazy_obj)
l.middle.inner.value = 100
new_lazy = l.unlens()  # Returns Lazy since original was Lazy

An object shared by several parents is lensed once, so editing it through one parent is visible through the others, and it stays shared after unlens().

Source code in src/confingy/tracking.py
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
def lens(obj: Any) -> Lazy[Any]:
    """
    Convert a tracked or Lazy instance to a Lazy for nested parameter updates.

    This function provides a unified interface for modifying nested configurations.
    After making changes, call `unlens()` to reconstruct the object with the
    original laziness structure preserved.

    Args:
        obj: Either a tracked instance (has `_tracked_info`) or a Lazy instance.

    Returns:
        A Lazy instance that can be modified via attribute access.

    Examples:
        ```python
        @track
        class Outer:
            def __init__(self, middle: Middle):
                self.middle = middle

        @track
        class Middle:
            def __init__(self, inner: Inner):
                self.inner = inner

        @track
        class Inner:
            def __init__(self, value: int):
                self.value = value

        # Create a tracked instance
        obj = Outer(middle=Middle(inner=Inner(value=42)))

        # Use lens to modify nested values
        l = lens(obj)
        l.middle.inner.value = 100

        # Reconstruct with original structure (all instantiated)
        new_obj = l.unlens()
        assert new_obj.middle.inner.value == 100

        # Works with Lazy instances too
        lazy_obj = Outer.lazy(middle=Middle.lazy(inner=Inner.lazy(value=42)))
        l = lens(lazy_obj)
        l.middle.inner.value = 100
        new_lazy = l.unlens()  # Returns Lazy since original was Lazy
        ```

    An object shared by several parents is lensed once, so editing it through one
    parent is visible through the others, and it stays shared after `unlens()`.
    """
    if not (is_lazy_instance(obj) or is_tracked_instance(obj)):
        raise TypeError(
            f"lens() requires a Lazy or tracked instance, got {type(obj).__name__}"
        )
    return _lens(obj, {})

track #

track(
    cls_or_instance: None = None, *, _validate: bool = True
) -> Callable[[C], C]
track(cls_or_instance: C, *, _validate: bool = True) -> C
track(
    cls_or_instance: Optional[Any] = None,
    *args: Any,
    _validate: bool = True,
    **kwargs: Any,
) -> Any

Track constructor arguments for serialization.

Can be used as a decorator or function to enable argument tracking for later serialization.

Parameters:

Name Type Description Default
_validate bool

Whether to validate constructor arguments with pydantic (default: True) can be overridden by the context manager disable_validation

True
Example
from confingy import track, save_config

@track
class Dataset:
    def __init__(self, path: str, size: int):
        self.path = path
        self.size = size

# Arguments are tracked and can be serialized
dataset = Dataset(path="/data", size=1000)
save_config(dataset, "config.json")

# Skip validation
@track(_validate=False)
class FastDataset:
    def __init__(self, path: str):
        self.path = path

You can also turn a tracked class into a lazy one:

lazy_dataset = Dataset.lazy(path="/data", size=1000)
Source code in src/confingy/tracking.py
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
def track(
    cls_or_instance: Optional[Any] = None,
    *args: Any,
    _validate: bool = True,
    **kwargs: Any,
) -> Any:
    """
    Track constructor arguments for serialization.

    Can be used as a decorator or function to enable argument tracking
    for later serialization.

    Args:
        _validate: Whether to validate constructor arguments with pydantic (default: True)
            can be overridden by the context manager [disable_validation][confingy.tracking.disable_validation]

    Example:
        ```python
        from confingy import track, save_config

        @track
        class Dataset:
            def __init__(self, path: str, size: int):
                self.path = path
                self.size = size

        # Arguments are tracked and can be serialized
        dataset = Dataset(path="/data", size=1000)
        save_config(dataset, "config.json")

        # Skip validation
        @track(_validate=False)
        class FastDataset:
            def __init__(self, path: str):
                self.path = path
        ```

        You can also turn a tracked class into a lazy one:

        ```python
        lazy_dataset = Dataset.lazy(path="/data", size=1000)
        ```
    """
    # Case 1: Called as @track() or @track(_validate=False) with parentheses - return decorator

    if G_DISABLE_VALIDATION:
        _validate = False

    if cls_or_instance is None:
        return functools.partial(track, _validate=_validate)

    # Case 2: Called with arguments - instantiate class with tracking
    if args or kwargs:
        return _track_with_args(cls_or_instance, args, kwargs, _validate=_validate)

    # Case 3: Called as @track decorator or track(instance)
    if is_class(cls_or_instance):
        return _track_class_decorator(cls_or_instance, _validate=_validate)
    else:
        return _track_existing_instance(cls_or_instance)

update #

update(parent_obj: Any) -> Callable[..., Any]

Create an updated version of a tracked or lazy object with new constructor arguments.

This function supports "inheritance" for confingy objects by allowing you to create a new instance with updated parameters while preserving the original object's type and validation behavior.

Parameters:

Name Type Description Default
parent_obj Any

Either a tracked instance (has _tracked_info) or a lazy instance (Lazy[T])

required

Returns:

Type Description
Callable[..., Any]

A function that accepts new constructor arguments and returns:

Callable[..., Any]
  • For tracked instances: A new tracked instance of the same type
Callable[..., Any]
  • For lazy instances: A new lazy instance with updated configuration

Examples:

# With tracked instances
@track
class Foo:
    def __init__(self, bar: str, baz: int = 10):
        self.bar = bar
        self.baz = baz

parent_foo = track(Foo)(bar="hello")
child_foo = update(parent_foo)(bar="world")  # bar="world", baz=10

# With lazy instances
parent_lazy = lazy(Foo)(bar="hello")
child_lazy = update(parent_lazy)(bar="world")  # Returns Lazy[Foo]
Source code in src/confingy/tracking.py
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
def update(parent_obj: Any) -> Callable[..., Any]:
    """
    Create an updated version of a tracked or lazy object with new constructor arguments.

    This function supports "inheritance" for confingy objects by allowing you to create
    a new instance with updated parameters while preserving the original object's type
    and validation behavior.

    Args:
        parent_obj: Either a tracked instance (has `_tracked_info`) or a lazy instance (`Lazy[T]`)

    Returns:
        A function that accepts new constructor arguments and returns:
        - For tracked instances: A new tracked instance of the same type
        - For lazy instances: A new lazy instance with updated configuration

    Examples:
        ```python
        # With tracked instances
        @track
        class Foo:
            def __init__(self, bar: str, baz: int = 10):
                self.bar = bar
                self.baz = baz

        parent_foo = track(Foo)(bar="hello")
        child_foo = update(parent_foo)(bar="world")  # bar="world", baz=10

        # With lazy instances
        parent_lazy = lazy(Foo)(bar="hello")
        child_lazy = update(parent_lazy)(bar="world")  # Returns Lazy[Foo]
        ```
    """

    def updater(*args: Any, **kwargs: Any) -> Any:
        # Handle Lazy instances
        if is_lazy_instance(parent_obj):
            # Get the original configuration
            original_config = parent_obj.get_config()

            # Merge with new arguments (new args take precedence)
            updated_config = original_config.copy()

            # Handle positional arguments by converting to kwargs
            if args:
                new_kwargs = _args_to_kwargs(
                    parent_obj._confingy_actual_cls,
                    args,
                    kwargs,
                    include_defaults=False,
                )
            else:
                new_kwargs = kwargs

            updated_config.update(new_kwargs)

            # Create a new Lazy instance with updated config
            return Lazy(parent_obj._confingy_cls, updated_config)

        # Handle tracked instances
        elif hasattr(parent_obj, "_tracked_info"):
            # Get the class directly from the object
            cls = parent_obj.__class__

            # Get original init args from tracked info
            original_args = parent_obj._tracked_info["init_args"]

            # Merge with new arguments (new args take precedence)
            updated_args = original_args.copy()

            # Handle positional arguments by converting to kwargs
            if args:
                new_kwargs = _args_to_kwargs(cls, args, kwargs, include_defaults=False)
            else:
                new_kwargs = kwargs

            updated_args.update(new_kwargs)

            # Create new tracked instance
            return _create_tracked_instance(cls, (), updated_args, _validate=True)

        else:
            raise TypeError(
                f"update() requires either a tracked instance (with _tracked_info) "
                f"or a Lazy instance, got {type(parent_obj)}"
            )

    return updater