The Twython module uses requests module internally.
I want to wrap/decorate request’s requests.post(*k, **kw) method so everything Twython makes a request.post(...) call it will be transparently decorated/wrapped without interfering with the Twython module.
If I edited the requests codebase that’d be easy enough but I’m curious how to solve the general problem of adding a decorator to an already defined function/method.
import requests
def magic_wrapper_doodad(...)
...
...
requests.post = magic_wrapper_doodad(my_function, requests.post) # plz?
import Twython
# thanks to the above magic, requests.post is wrapped just as if it was defined like:
@decorator
def trace(f, *args, **kw):
print("calling %s with args %s, %s" % (f.__name__, args, kw))
return f(*args, **kw)
...
... #inside requests.py now:
@trace
def post(self, *args, **kw):
...
how do I write magic_wrapper_doodad() – or some alternative code – so I can decorate the code like this?
Decorator
@notation is just syntactic sugar for calling the decorator callable with the decorated function and replacing the decorated function with the result.In other words, the following two examples are the exact same thing:
and the same applies to methods in class definitions.
Thus, you can simply decorate a class method by replacing the class method with the result of the decorator callable:
This is the same as if you had written:
Note that in your case
requestsis actually a module, not a class, but the same principles apply.