r""" Decorator to apply on the init of classes inheriting from [`ConfigMixin`] so that all the arguments are automatically sent to `self.register_for_config`. To ignore a specific argument accepted by the init but that shouldn't be registered in the config, use the `ignore_for_config` cl
(init)
| 606 | |
| 607 | |
| 608 | def register_to_config(init): |
| 609 | r""" |
| 610 | Decorator to apply on the init of classes inheriting from [`ConfigMixin`] so that all the arguments are |
| 611 | automatically sent to `self.register_for_config`. To ignore a specific argument accepted by the init but that |
| 612 | shouldn't be registered in the config, use the `ignore_for_config` class variable |
| 613 | |
| 614 | Warning: Once decorated, all private arguments (beginning with an underscore) are trashed and not sent to the init! |
| 615 | """ |
| 616 | |
| 617 | @functools.wraps(init) |
| 618 | def inner_init(self, *args, **kwargs): |
| 619 | # Ignore private kwargs in the init. |
| 620 | init_kwargs = {k: v for k, v in kwargs.items() if not k.startswith("_")} |
| 621 | config_init_kwargs = {k: v for k, v in kwargs.items() if k.startswith("_")} |
| 622 | if not isinstance(self, ConfigMixin): |
| 623 | raise RuntimeError( |
| 624 | f"`@register_for_config` was applied to {self.__class__.__name__} init method, but this class does " |
| 625 | "not inherit from `ConfigMixin`." |
| 626 | ) |
| 627 | |
| 628 | ignore = getattr(self, "ignore_for_config", []) |
| 629 | # Get positional arguments aligned with kwargs |
| 630 | new_kwargs = {} |
| 631 | signature = inspect.signature(init) |
| 632 | parameters = { |
| 633 | name: p.default for i, (name, p) in enumerate(signature.parameters.items()) if i > 0 and name not in ignore |
| 634 | } |
| 635 | for arg, name in zip(args, parameters.keys()): |
| 636 | new_kwargs[name] = arg |
| 637 | |
| 638 | # Then add all kwargs |
| 639 | new_kwargs.update( |
| 640 | { |
| 641 | k: init_kwargs.get(k, default) |
| 642 | for k, default in parameters.items() |
| 643 | if k not in ignore and k not in new_kwargs |
| 644 | } |
| 645 | ) |
| 646 | |
| 647 | # Take note of the parameters that were not present in the loaded config |
| 648 | if len(set(new_kwargs.keys()) - set(init_kwargs)) > 0: |
| 649 | new_kwargs["_use_default_values"] = list(set(new_kwargs.keys()) - set(init_kwargs)) |
| 650 | |
| 651 | new_kwargs = {**config_init_kwargs, **new_kwargs} |
| 652 | getattr(self, "register_to_config")(**new_kwargs) |
| 653 | init(self, *args, **init_kwargs) |
| 654 | |
| 655 | return inner_init |
| 656 | |
| 657 | |
| 658 | def flax_register_to_config(cls): |
nothing calls this directly
no outgoing calls
no test coverage detected