from functools import wraps def one(func=None): """decorates signals for executing only one time Exemple Usage -- from django.core.mail import EmailMultiAlternatives from django.template.loader import render_to_string from django.contrib.auth.models import User @one def user_welcome(sender, instance, created, **kwargs): # Send a welcome email if created == True and isinstance(instance, User): instance.message_set.create(message=_(u"Ho, Welcome %s!" % instance)) subject, from_email, to = 'Welcome !', 'from@example.com', instance.email text_content = render_to_string('mail/welcome.html', { 'user': instance }) msg = EmailMultiAlternatives(subject, text_content, from_email, [to]) msg.send() """ E = '_exec_one_time' @wraps(func) def wrapper(*args, **kwargs): try: instance = kwargs['instance'] e = getattr(instance, E, []) c = func.__name__ if c not in e: e.append(c) setattr(instance, E, e) return func(*args, **kwargs) except: return func(*args, **kwargs) return wrapper