Skip to content

Commit

Permalink
leveraging attrs functionality to auto trigger post init hooks
Browse files Browse the repository at this point in the history
  • Loading branch information
ncilfone committed Mar 18, 2022
1 parent 8617af6 commit c747e3c
Show file tree
Hide file tree
Showing 2 changed files with 4 additions and 6 deletions.
7 changes: 4 additions & 3 deletions spock/backend/config.py
Expand Up @@ -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__,
Expand All @@ -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
Expand Down
3 changes: 0 additions & 3 deletions spock/backend/field_handlers.py
Expand Up @@ -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}"
Expand Down

0 comments on commit c747e3c

Please sign in to comment.