I have a problem that can be simplified as follows: I have a particular set of objects that I want to modify in a particular way. So, it’s possible for me to write a function that modifies a single object and then create a decorator that applies that function to all of the objects in the set.
So, let’s suppose I have something like this:
def modify_all(f):
def fun(objs):
for o in objs:
f(o)
@modify_all
def modify(obj):
# Modify obj in some way.
modify(all_my_objs)
However, there may also be times when I just want to operate on one object by itself.
Is there a way to “undecorate” the modify function programmatically to get the original (single object) function back again? (Without just removing the decorator, I mean.) Or is there another approach that would be better to use in such a case?
Just for clarity and completeness, there’s quite a bit more going on in the actual modify_all decorator than is illustrated here. Both modify and modify_all have a certain amount of work to carry out, which is why I thought the decorator might be nice. Additionally, I have other variants of modify that can directly benefit from modify_all, which makes it even more useful. But I do sometimes need to do things using the original modify function. I know that I can always pass in a one-element set to “trick” it into working as-is, but I’m wondering if there’s a better way or a better design for the situation.
Alex had already posted something similar but it was my first thought too so I’ll go ahead and post it because it does sidestep Mike Grahams objection to it. (even if I don’t really agree with his objection: the fact that people don’t know about something is not a reason to not use it. This is how people continue to not know about it)
You could just call
undecorateto access the decorated function.another alternative would be to handle it like this: