Python Forum

Full Version: decorate an imported function?
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
is it possible to decorate a function that came with an imported module?  if so ... how?  what can be done this way?
from module import function

def decorator(func):
    def wrapper():
        # do some stuffs
        func()
        # do other stuffs
    
    return wrapper

any_func = decorator(function)
any_func()
Using decorator notation, no. But you can wrap as the previous answer shows.
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.