Last active
February 10, 2020 06:37
-
-
Save UtkucanBykl/12ffbb4cc922d178d71fb11e24f54a52 to your computer and use it in GitHub Desktop.
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
from signal import Signal | |
from model import Model | |
pre_save = Signal() | |
post_save = Signal() | |
def post_save_method(): | |
print('post save method run') | |
def pre_save_method(): | |
print('pre save method run') | |
post_save.connect(post_save_method, sender=Model) | |
pre_save.connect(pre_save_method, sender=Model) | |
model = Model() | |
model.save() |
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
class Model: | |
def save(self): | |
pre_save.send(self) | |
# blabla | |
post_save.send(self) |
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
class Signal: | |
def __init__(self): | |
self._receivers = [] | |
def connect(self, receiver, name=None, sender=None): | |
if callable(receiver): | |
name = name or receiver.__name__ | |
receiver_data = { | |
'function': receiver, | |
'name': name, | |
'sender': sender | |
} | |
self._receivers.append(receiver_data) | |
else: | |
raise BaseException('Receiver must be callable') | |
def disconnect(self, receiver=None, name=None): | |
if receiver: | |
name = name or receiver.__name__ | |
for item in self._receivers: | |
if item['name'] == name: | |
del item | |
break | |
def send(self, instance): | |
for item in self._receivers: | |
if isinstance(instance, item['sender']) or item['sender'] is None: | |
item['function'].__call__() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment