O'Reilly logo

Python Unlocked by Arun Tigeraniya

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required