I’m writing a modding API for my game and I want to allow users to tell the game engine to run their mod’s function immediately before or after one of the API functions, in other words to “extend” the functions.
Before now modders had to rewrite the function to add functionality to it which meant digging in the game’s sourcecode, which I think sucks for them.
Right now I’m thinking of something like this:
def moddersFunction():
pass
myAPI.extendFunction('functionName', 'before-or-after', moddersFunction, extraArgs=[])
Now what will be comparably clean way to implement this?
In other words, what would the internals of myAPI.extendFunction look like if you were to write it?
I’m thinking of having a dictionary which myAPI.extendFunction will add functions to and the functions in my API will check and run the mod’s function if it has been set (“registered”).
But this means adding the code which checks the dictionary in every single function in my modding API which I want to allow to be extended (even if it’s just a single function call which does the check and function calling itself, it seems to much itself).
I’m wondering if there’s some neat Python trick which will allow such “extending” of functions without “butchering” (maybe I’m exaggerating) the existing sourcecode of my game’s API.
I would do something along the following lines:
Any “extendable” function can now be decorated like so:
Now you can use
square.add_pre()andsquare.add_post()to register functions that would automatically get called before and after each call tosquare():