decorate an imported function? - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: General Coding Help (https://python-forum.io/forum-8.html) +--- Thread: decorate an imported function? (/thread-3319.html) |
decorate an imported function? - Skaperen - May-14-2017 is it possible to decorate a function that came with an imported module? if so ... how? what can be done this way? RE: decorate an imported function? - wavic - May-14-2017 from module import function def decorator(func): def wrapper(): # do some stuffs func() # do other stuffs return wrapper any_func = decorator(function) any_func() RE: decorate an imported function? - micseydel - May-14-2017 Using decorator notation, no. But you can wrap as the previous answer shows. RE: decorate an imported function? - nilamo - May-22-2017 In case it still isn't quite clear, a decorator is just syntactic sugar around wrapping something with something else, aliasing the original function, if you will. But there's no reason it has to be JUST for functions... >>> def wrapper(cls): ... class Eggs: ... def __init__(self, other): ... print("pretending to be {0}".format(other)) ... self.other = other() ... def inner(): ... return Eggs(cls) ... return inner ... >>> @wrapper ... class Spam: ... def __init__(self): ... print("SPAM!") ... >>> x = Spam() pretending to be <class '__main__.Spam'> SPAM!I can't actually think of a use for that which wouldn't be better served by just using inheritance, but if such a situation arises, it is possible. |