What is a decorator used for?

Question:

Many documents online concern about the syntax of decorator. But I want to know where and how is the decorator used? Is the decorator just used to execute extra codes before and after the decorated function? Or maybe there is other usage?

Asked By: hbprotoss

||

Answers:

The decorator syntax is powerful:

@decorator
def foo(...):
    ...

is equivalent to

def foo(...):
    ...
foo = decorator(foo)

That means that decorators can do basically anything — they don’t have to have any relation to the decorated function! Examples include:

  • memoising a recursive function (functools.lru_cache)
  • logging all calls to a function
  • implementing the descriptor functionality (property)
  • marking a method as static (staticmethod)
Answered By: Katriel

A good practical example would be from Python’s very own unittest framework where it makes use of decorators to skip tests and expected failures:

Skipping a test is simply a matter of using the skip() decorator or
one of its conditional variants.

Basic skipping looks like this:

class MyTestCase(unittest.TestCase):

    @unittest.skip("demonstrating skipping")
    def test_nothing(self):
        self.fail("shouldn't happen")

    @unittest.skipIf(mylib.__version__ < (1, 3),
                     "not supported in this library version")
    def test_format(self):
        # Tests that work for only a certain version of the library.
        pass

    @unittest.skipUnless(sys.platform.startswith("win"), "requires Windows")
    def test_windows_support(self):
        # windows specific testing code
        pass
Answered By: GSP

An decorator wraps around an method or even a whole class and delivers the ability to manipulate for example the call of an method. I very often use an @Singleton decorator to create an singleton.

Decorators are extremely powerful and really cool concept.

Look at this book for understanding them: http://amzn.com/B006ZHJSIM

Answered By: Thomas Spycher
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.