Decorating callables
Key 2: Changing the behavior of callables.
Decorators are callable objects, which replace the original callable objects with some other objects. In this case, as we are replacing a callable with another object, what we mostly want mostly is the replaced object to be callable.
Language provides syntax to do so easily, but first, let's take a look at how we can manually do this:
>>> def wrap(func):
... def newfunc(*args):
... print("newfunc",args)
... return newfunc
...
>>> def realfunc(*args):
... print("real func",args)
...
>>>
>>> realfunc = wrap(realfunc)
>>>
>>> realfunc(1,2,4)
('newfunc', (1, 2, 4))With the decorator syntax, it becomes easy. Taking the definition of wrap and newfunc from the preceding code snippet, we get this:
>>> @wrap
... def realfunc(args):
... print("real func",args)
...
>>> realfunc(1,2,4)
('newfunc...