Created
May 27, 2020 22:56
-
-
Save mariobittencourt/4ff60bfdc5f906cc7502f7d618d177c0 to your computer and use it in GitHub Desktop.
Dynamic binding
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def method_dispatch(func): | |
dispatcher = functools.singledispatch(func) | |
def wrapper(*args, **kw): | |
return dispatcher.dispatch(args[1].__class__)(*args, **kw) | |
wrapper.register = dispatcher.register | |
functools.update_wrapper(wrapper, func) | |
return wrapper | |
class Payment: | |
# ... existing code | |
@method_dispatch | |
def apply(self, event: DomainEvent): | |
raise ValueError('Unknown event!') | |
@apply.register(PaymentCreated) | |
def _(self, event: PaymentCreated): | |
self._status = 'PENDING_PROCESSING' | |
self._amount_due = event.amount_due | |
def record_that(self, event: DomainEvent): | |
self.apply(event) | |
self.events.append(event) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment