forked from Flexget/Flexget
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathevent.py
97 lines (73 loc) · 2.52 KB
/
event.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
"""
Provides small event framework
"""
from __future__ import unicode_literals, division, absolute_import
import logging
log = logging.getLogger('event')
_events = {}
class Event(object):
"""Represents one registered event."""
def __init__(self, name, func, priority=128):
self.name = name
self.func = func
self.priority = priority
def __call__(self, *args, **kwargs):
return self.func(*args, **kwargs)
def __eq__(self, other):
return self.priority == other.priority
def __lt__(self, other):
return self.priority < other.priority
def __gt__(self, other):
return self.priority > other.priority
def __str__(self):
return '<Event(name=%s,func=%s,priority=%s)>' % (self.name, self.func.__name__, self.priority)
__repr__ = __str__
def event(name, priority=128):
"""Register event to function with a decorator"""
def decorator(func):
add_event_handler(name, func, priority)
return func
return decorator
def get_events(name):
"""
:param String name: event name
:return: List of :class:`Event` for *name* ordered by priority
"""
if not name in _events:
raise KeyError('No such event %s' % name)
_events[name].sort(reverse=True)
return _events[name]
def add_event_handler(name, func, priority=128):
"""
:param string name: Event name
:param function func: Function that acts as event handler
:param priority: Priority for this hook
:return: Event created
:rtype: Event
:raises Exception: If *func* is already registered in an event
"""
events = _events.setdefault(name, [])
for event in events:
if event.func == func:
raise Exception('%s has already been registered as event listener under name %s' % (func.__name__, name))
log.trace('registered function %s to event %s' % (func.__name__, name))
event = Event(name, func, priority)
events.append(event)
return event
def remove_event_handler(name, func):
"""
.. warning:: Not implemented!
"""
# TODO: implement
raise NotImplementedError
def fire_event(name, *args, **kwargs):
"""
Trigger an event with *name*. If event is not hooked by anything nothing happens.
:param name: Name of event to be called
:param args: List of arguments passed to handler function
:param kwargs: Key Value arguments passed to handler function
"""
if not name in _events:
return
for event in get_events(name):
event(*args, **kwargs)