I am working on some code to organize our event definition/category mapping. Our goal is to be able to define "event names" as well as associate categories, its pretty much a static process. What we want is people using constants and not a bunch of strings everywhere. We also need somewhere to validate events/categories, as well as do some lookup things like getting events by categories and vice versa.
class EventMapping(object)
def __init__(self, name, categories):
self.name = name
self.categories= categories
EventRegistry.register(self)
def __eq__(self, obj):
if(isinstance(obj, str)):
return obj==self.name
if(isinstance(obj, EventMapping)):
return obj.name ==self.name
and obj.categories==self.categories
return False
def __repr__(self):
return self.name
class Event():
class MyCompontent():
ComponentEvent = EventMapping("ComponentEvent", None)
ComponentEventWCategory = EventMapping("ComponentEvent"
, [Category.MyComponent.Useful])
class Data():
Created =EventMapping("Created", [Category.Data.All, Category.Data.Count]
Updated= EventMapping("Updated", [Category.Data.All]
Deleted= EventMapping("Deleted", [Category.Data.All, Category.Data.Count]
class Category():
class MyComponent():
Useful = "Useful"
class Data():
All= "All"
Count= "Count"
class EventRegistry():
@staticmethod
def register( eventMapping):
eventName= eventMapping.name
#store locally...
@staticmethod
def events(category):
#retreive events by category
@staticmethod
def category(event_name):
#retreive categories by event name
There are a couple of things I don't like:
In the EventRegistry class I store storing them twice, once in an Event Dictionary key being the name, and value a list of categories. The second is the opposite Category dictionary keyed by category name and a list of events. Is there a better way to achieve this? I basically need an easy way to look up by name or category.
Should I just create two registries? One for Categories one for Events?
When it comes to using the Events we do it like:
self.subscribe(Event.MyComponent.Useful)self.subscribe(Category.MyComponent.Useful)
we then use the registry to validate the event exists, as well as deliver the message. Is there an easier way to achieve the package like namespaces?
Just looking for some feedback on better ways to do it, or a pattern to follow. I have searched around and can't find anything. Even if you know of some module i can look at and get a better feel for a better way to do it, ill be glad to look into that as well.