From 5e92aefcd49a7a4944d9b6c308cc7ae482a216b6 Mon Sep 17 00:00:00 2001 From: James Lu Date: Sat, 2 Sep 2017 21:15:59 -0700 Subject: [PATCH] Implement priorities in utils.add_hook() This changes world.hooks to store lists of tuples indicating (priority, hook_func). --- classes.py | 3 ++- coremods/corecommands.py | 5 +++-- utils.py | 11 ++++++++--- 3 files changed, 13 insertions(+), 6 deletions(-) diff --git a/classes.py b/classes.py index a204c4e..3007edb 100644 --- a/classes.py +++ b/classes.py @@ -226,7 +226,8 @@ class PyLinkNetworkCore(structures.DeprecatedAttributesObject, structures.CamelC command, hook_cmd) # Iterate over registered hook functions, catching errors accordingly. - for hook_func in world.hooks[hook_cmd]: + for hook_pair in world.hooks[hook_cmd]: + hook_func = hook_pair[1] try: log.debug('(%s) Calling hook function %s from plugin "%s"', self.name, hook_func, hook_func.__module__) diff --git a/coremods/corecommands.py b/coremods/corecommands.py index 19c1167..3f4ea6c 100644 --- a/coremods/corecommands.py +++ b/coremods/corecommands.py @@ -157,8 +157,9 @@ def unload(irc, source, args): del world.services['pylink'].commands[cmdname] # Remove any command hooks set by the plugin. - for hookname, hookfuncs in world.hooks.copy().items(): - for hookfunc in hookfuncs: + for hookname, hookpairs in world.hooks.copy().items(): + for hookpair in hookpairs: + hookfunc = hookpair[1] if hookfunc.__module__ == modulename: world.hooks[hookname].remove(hookfunc) # If the hookfuncs list is empty, remove it. diff --git a/utils.py b/utils.py index d5d91bf..caa6828 100644 --- a/utils.py +++ b/utils.py @@ -44,10 +44,15 @@ def add_cmd(func, name=None, **kwargs): world.services['pylink'].add_cmd(func, name=name, **kwargs) return func -def add_hook(func, command): - """Binds a hook function to the given command name.""" +def add_hook(func, command, priority=100): + """ + Binds a hook function to the given command name. + + A custom priority can also be given (defaults to 100), and hooks with + higher priority values will be called first.""" command = command.upper() - world.hooks[command].append(func) + world.hooks[command].append((priority, func)) + world.hooks[command].sort(key=lambda pair: pair[0], reverse=True) return func # DEPRECATED