/remram.py Secret
Created
August 12, 2013 16:33
Version avec classe plutôt que closures pour http://sametmax.com/un-decorateur-pour-accepter-les-callbacks-en-python/
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
# -*- encoding: utf-8 -*- | |
import functools | |
class accept_callbacks(object): | |
def __init__(self, func): | |
# on va stocker tous les callbacks là dedans | |
self.callbacks = [] | |
functools.update_wrapper(self, func) | |
self.func = func | |
def __call__(self, *args, **kwargs): | |
# on appelle la fonction originale | |
result = self.func(*args, **kwargs) | |
# on appelle ensuite chaque callback en lui passant le resultat | |
# de la fonction ainsi que les paramètres qui avaient été passés | |
for callback in self.callbacks: | |
callback(result, *args, **kwargs) | |
# et on retourne le résultat | |
return result | |
def register_callback(self, cb): | |
self.callbacks.append(cb) | |
@accept_callbacks | |
def add(a, b): | |
return a + b | |
@add.register_callback | |
def mon_callback(result, a, b): | |
print("Ma fonction a été appelée avec a=%s et b=%s !" % (a, b)) | |
print("Elle a retourné le résultat '%s'" % result) | |
print(add(1, 1)) | |
## Ma fonction a été appelée avec a=1 et b=1 ! | |
## Elle a retourné le résultat '2' | |
## 2 |
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
# -*- encoding: utf-8 -*- | |
from functools import wraps | |
def accept_callbacks(func): | |
# on va stocker tous les callbacks là dedans | |
callbacks = [] | |
@wraps(func) | |
def wrapper(*args, **kwargs): | |
# on appelle la fonction originale | |
result = func(*args, **kwargs) | |
# on appelle ensuite chaque callback en lui passant le resultat | |
# de la fonction ainsi que les paramètres qui avaient été passés | |
for callback in callbacks: | |
callback(result, *args, **kwargs) | |
# et on retourne le résultat | |
return result | |
# on attache la liste des callbacks au wrapper pour y avoir accès depuis | |
# l'extérieur | |
wrapper.callbacks = callbacks | |
return wrapper | |
@accept_callbacks | |
def add(a, b): | |
return a + b | |
def mon_callback(result, a, b): | |
print("Ma fonction a été appelée avec a=%s et b=%s !" % (a, b)) | |
print("Elle a retourné le résultat '%s'" % result) | |
add.callbacks.append(mon_callback) | |
print(add(1, 1)) | |
## Ma fonction a été appelée avec a=1 et b=1 ! | |
## Elle a retourné le résultat '2' | |
## 2 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment