1

An event mapper program receives a stream of events based on the event key attribute. Specific handler classes are required to handle that event.

My requirement is that I want to be able to add new event handlers in the future, without restarting the event mapper program.

I am able to load the specific event handler classes dynamically.

def loadClass(self,module,file_name,class_name):
    try:
        worker_module = getattr(__import__(module+'.'+file_name),file_name)
        return getattr(worker_module, class_name)
    except Exception as e: 
        print e
        return None

I need a mapping between the event key attribute and the specific module,file_name and class_name

I'm thinking of maintaining the mapping in a seperate file with this mapping infomation, and read that to map every event, but I'm hoping that there is a better way.

Gautham Kumaran
  • 421
  • 5
  • 15

2 Answers2

1

Could it be you are looking for dicts? I'm not quite sure what's your workflow (maybe clear that up), but what I understand is that:
event -> HandlerMapper reads event.key -> calls correct HandlerClass(event)

Which is exactly what a dictionary does:

#definition
handlers=dict()
handleEvent(event):
    if event.key in handlers:
        return handlers[event.key](event)
    else:
        #do magic to load class as HandlerClass
        handlers[event.key] = HandlerClass
        return handlers[event.key](event)

What I don't understand is why you need this loader-magic at all. To add new handlers, simply add the class after it's loaded (i.e. call handler['key_of_new_event'] = NewHandlerClass)

GammaSQ
  • 361
  • 1
  • 10
  • The workflow I'm looking for is exactly same as your code. but `#do magic` part is complex, because assuming that the event handler is never ending, maintaining a map in dict is not possible, because you cannot change the mapping at a latter point of time (that's why I'm maintaining in the file), but I'm sure there is a better way. One more problem is a class imported by a program in never interpreted again on repetitive imports, so once the class is read by event handler program, changes in the EventHandler classes are reflected in the event handler. – Gautham Kumaran Apr 03 '17 at 20:12
  • I'm still not sure I understand. The problem is that once a class is loaded, it may change and has to be reloaded at a later point? In that case, create a timeout-thread for each handler to remove it again after a certain amount of time perhaps? – GammaSQ Apr 04 '17 at 14:24
0

In java we try to get the name of the class with forname and using newInstance makes dynamic instanciation of the Class like this :

Class<?> clazz = Class.forName(className);
Constructor<?> ctor = clazz.getConstructor(String.class);
Object object = ctor.newInstance(new Object[] { ctorArgument });

In python try to see this url Does python have an equivalent to Java Class.forName()?

Community
  • 1
  • 1
Hilmi Reda
  • 94
  • 7