• entries
    383
  • comments
    1075
  • views
    352603

Python event class

Sign in to follow this  

72 views

I've thrown together a Python version of the signal/event class I have as the cornerstone of my C++ game engine:


class Event:
"""Event class: stores a list of functions that can be all called in sequence.
A one-to-many type function construct.
"""

def __init__(self):
self.func_list = []

def __call__(self, *args):
# call the functions with *args
for f in self.func_list:
try:
f(*args)
except:
# exceptions are ignored for now: later maybe they should be logged?
pass


def bind(self, f, priority=0):
"Binds a function to the callable list, with a sorting priority value (higher means earlier)"
if callable(f):
f.event_priority = priority
self.func_list.append(f)
self.func_list.sort(lambda x,y: y.event_priority - x.event_priority)


def unbind(self, f):
"Unbinds (removes) a function from the callable event list"
try:
self.func_list.remove(f)
except ValueError:
pass



I've only done a few simple command line tests on this, but the basic principle appears to be sound. I'm impressed that it's so simple - my C++ version took me days to write and debug, while this one only took me about twenty minutes, and most of that was looking up how to do things in Python. Admittely it's probably not as streamlined as my C++ version using FastDelegates, but if it's not a bottleneck then who cares?
Sign in to follow this  


0 Comments


Recommended Comments

There are no comments to display.

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now