Last active
August 29, 2015 14:18
-
-
Save Lucretiel/2c694aa823b43882f428 to your computer and use it in GitHub Desktop.
Descriptor-based class function registry
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class FunctionNotFoundError(KeyError): | |
pass | |
class Registry: | |
def __init__(self): | |
self.registry = {} | |
def register(self, key): | |
def decorator(func): | |
self.registry[key] = func | |
return func | |
return decorator | |
def lookup(self, key): | |
try: | |
return self.registry[key] | |
except KeyError as e: | |
raise FunctionNotFoundError(key) from e | |
def make_bound(self, instance): | |
def bound(*args, **kwargs): | |
key, *args = args | |
return self.lookup(key)(instance, *args, **kwargs) | |
return bound | |
def __get__(self, instance, owner): | |
if instance is None: | |
return self | |
else: | |
return self.make_bound(instance) | |
# Example | |
class EventHandler: | |
registry = Registry() | |
@registry.register('event1') | |
def handle_event1(self, stuff): | |
print('event1', stuff) | |
@registry.register('event2') | |
def handle_event2(self, stuff): | |
print('event2', stuff) | |
def handle_event(self, event_type, stuff): | |
# Invoke the registry with self.registry and call it to do a lookup | |
return self.registry(event_type, stuff) | |
handler = EventHandler() | |
handler.handle_event('event1', 'hello') | |
handler.handle_event('event2', 'world') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment