From 6d1213dacc8c7ccddfa3b856fdd0fb9cd5199324 Mon Sep 17 00:00:00 2001 From: Nicholas Cilfone Date: Fri, 18 Mar 2022 09:55:17 -0400 Subject: [PATCH] Auto trigger post init hooks (#232) * Leverages attrs functionality to auto trigger post init hooks --- spock/backend/config.py | 7 ++++--- spock/backend/field_handlers.py | 3 --- 2 files changed, 4 insertions(+), 6 deletions(-) diff --git a/spock/backend/config.py b/spock/backend/config.py index 33ee29fc..920a0301 100644 --- a/spock/backend/config.py +++ b/spock/backend/config.py @@ -107,6 +107,10 @@ def _process_class(cls, kw_only: bool, make_init: bool, dynamic: bool): """ # Handles the MRO and gets old annotations bases, attrs_dict, merged_annotations = _base_attr(cls, kw_only, make_init, dynamic) + # Copy over the post init function -- borrow a bit from attrs library to add the __post__hook__ method to the + # init call via `"__attrs_post_init__"` + if hasattr(cls, "__post_hook__"): + attrs_dict.update({"__attrs_post_init__": cls.__post_hook__}) # Dynamically make an attr class obj = attr.make_class( name=cls.__name__, @@ -117,9 +121,6 @@ def _process_class(cls, kw_only: bool, make_init: bool, dynamic: bool): auto_attribs=True, init=make_init, ) - # Copy over the post init function - if hasattr(cls, "__post_hook__"): - obj.__post_hook__ = cls.__post_hook__ # For each class we dynamically create we need to register it within the system modules for pickle to work setattr(sys.modules["spock"].backend.config, obj.__name__, obj) # Swap the __doc__ string from cls to obj diff --git a/spock/backend/field_handlers.py b/spock/backend/field_handlers.py index e946185a..d0f9d085 100644 --- a/spock/backend/field_handlers.py +++ b/spock/backend/field_handlers.py @@ -799,9 +799,6 @@ def recurse_generate(cls, spock_cls: _C, builder_space: BuilderSpace): # error on instantiation try: spock_instance = spock_cls(**fields) - # If there is a __post_hook__ dunder method then call it - if hasattr(spock_cls, "__post_hook__"): - spock_instance.__post_hook__() except Exception as e: raise _SpockInstantiationError( f"Spock class `{spock_cls.__name__}` could not be instantiated -- attrs message: {e}"