Advanced decorator topics

Let's go over a few pieces of advice concerning decorators that did not fit into earlier sections.

Defining decorators with arguments

Decorators with arguments are an advanced topic. They can be implemented as types with a __call__ method, or as a triple-nested function. For example, the following two pieces of code behave the same.

def deco_using_func(key):
    def _deco(func):
        def inner(*args, **kwargs):
            print 'Hello from', key
            return func(*args, **kwargs)
        return inner
    return _deco

class deco_using_cls(object):
    def __init__(self, key):
        self.key = key
    def __call__(self, func):
        def inner(*args, **kwargs):
            print 'Hello from', self.key
            return func(*args, **kwargs)
        return inner

Either one would be hooked up as follows. Note that ...

Get Practical Maya Programming with Python now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.