Skip to main content
gamedev.net
Python event class

Python event class

Trapper Zoid
Trapper Zoid
#ifdef TRAPPER_ZOID · · 1 min read
410 0

PRO Tired of ads? Read GameDev.net ad-free and help keep the community independent with GameDev Pro — $3/month.

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?

Discussion

Loading comments...