Skip to content

Instantly share code, notes, and snippets.

@kived
Forked from clayote/trigger_decorator.py
Last active August 29, 2015 14:25
Show Gist options
  • Save kived/0ff5469f222934ac7840 to your computer and use it in GitHub Desktop.
Save kived/0ff5469f222934ac7840 to your computer and use it in GitHub Desktop.
Trying to make a decorator to make triggers lazily
from kivy.event import EventDispatcher
from kivy.clock import Clock
from functools import partial
class trigger(object):
"""Make a trigger from a method outside of your class's __init__."""
def __init__(self, func_or_timeout):
if callable(func_or_timeout):
self.func = func_or_timeout
self.timeout = 0
else:
self.func = None
self.timeout = func_or_timeout
def __call__(self, func):
self.func = func
return self
def __get__(self, instance, owner=None):
if instance is None:
# EventDispatcher iterates over its attributes before it instantiates.
# Don't try making any trigger in that case.
return
retval = Clock.create_trigger(
partial(self.func, instance), self.timeout
)
setattr(instance, self.func.__name__, retval)
return retval
class Salad(EventDispatcher):
def toss(self, *args):
pass
_trigger_toss = trigger(toss)
@trigger(2)
def _trigger_after_2_secs(self, *args):
pass
@trigger
def _trigger_serve(self, *args):
# for when a method should only be usable via trigger
pass
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment