31

What is the difference between “Python decorators” and the “decorator pattern”?

When should I use Python decorators, and when should I use the decorator pattern?

I'm looking for examples of Python decorators and the decorator pattern accomplishing same.

@AcceptedAnswer

I know that Jakob Bowyer's answer is valid. Yet it's Srikar's answer that made me understand why.

After Srikar's answer, and studying the given resources, I've written this example, so I can visualize and understand Python decorators and the decorator pattern.

I must disagree with Srikar's "Python decorators are not an implementation of the decorator pattern". After what I've learned, I'm strongly convinced that Python decorators are an implementation of the decorator pattern. Just not in the classic way.

Also, I need to add that, despite the fact that Srikar said "Python decorators add functionality to functions and methods at definition time", you can easily use Python decorators at run time.

Yet, I still mark Srikar's answer as accepted, because it helped me understand the implementation of the decorator pattern in Python.

"""
Testing Python decorators against the decorator pattern
"""
def function(string):
    return string

def decorator(wrapped):
    def wrap(string):
        # Assume that this is something useful
        return wrapped(string.upper())
    return wrap

def method_decorator(wrapped):
    def wrap(instance, string):
        # Assume that this is something useful
        return wrapped(instance, string.upper())
    return wrap

@decorator
def decorated_function(string):
    print('! '.join(string.split(' ')))

class Class(object):
    def __init__(self):
        pass
    def something_useful(self, string):
        return string

class Decorator(object):
    def __init__(self, wrapped):
        self.wrapped = wrapped
    def something_useful(self, string):
        string = '! '.join(string.split(' '))
        return self.wrapped().something_useful(string)

    @method_decorator
    def decorated_and_useful(self,string):
        return self.something_useful(string)


if __name__ == '__main__':
    string = 'Lorem ipsum dolor sit amet.'
    print(function(string))                  # Plain function
    print(decorator(function)(string))       # Python decorator at run time
    print(decorated_function(string))        # Python decorator at definition time
    a = Class()
    print(a.something_useful(string))        # Plain method
    b = Decorator(Class)
    print(b.something_useful(string))        # Decorator pattern
    print(b.decorated_and_useful(string))    # Python decorator decorated the decorator pattern
5
  • 2
    @Srikar is correct. Here's another SO question that you might find interesting though!
    – mac
    Nov 30, 2011 at 16:00
  • 1
    @Srikar, I can't accept Snswer that do not resolve problem descriped in Question, sorry, but most of proposed solutions in my questions are not working.
    – seler
    Nov 30, 2011 at 16:11
  • 1
    FWIW, according to the Wikipedia article on Python decorators: "Despite the name, Python decorators are not an implementation of the decorator pattern". It goes on to explain why.
    – martineau
    Jun 8, 2013 at 13:11
  • Thanks @apcelent. This might help understand the topic to whoever gets here ;)
    – seler
    Dec 18, 2015 at 9:59
  • Srikar's answer is absolutely right. Decorators are no for run-time modification. My answer adds a little nuance, but his answer his answer is the best. codementor.io/@sheena/…
    – rfportilla
    Apr 8, 2020 at 21:22

2 Answers 2

37

Decorator Pattern - In object-oriented programming, the decorator pattern is a design pattern that allows behaviour to be added to an existing object dynamically. The decorator pattern can be used to extend (decorate) the functionality of a certain object at run-time, independently of other instances of the same class, provided some groundwork is done at design time.

Decorators in Python - Despite the name, Python decorators are not an implementation of the decorator pattern. The decorator pattern is a design pattern used in statically typed object-oriented programming languages to allow functionality to be added to objects at run time; Python decorators add functionality to functions and methods at definition time, and thus are a higher-level construct than decorator-pattern classes.

The decorator pattern itself is trivially implementable in Python, because the language is duck typed, and so is not usually considered as such. So in Python a decorator is any callable Python object that is used to modify a function, method or class definition.

I hope I made the difference clear. Just in case you did not completely understand, please go through these links. You will come out more than clear at the end of it -

1
  • "The decorator pattern itself is trivially implementable in Python, because the language is duck typed, and so is not usually considered as such. So in Python a decorator is any callable Python object that is used to modify a function, method or class definition." In Python, functions are objects; and a Python decorator (with @ syntax) is extending the functionality of that function object, independently of other functions (i.e., instances of the built-in function type). How is that not an implementation of the Decorator pattern? Aug 13, 2022 at 9:58
4

The difference is this:

(a) Python decorators are tied to an existing method and change the behavior of that method. Example:

@modifyBehavior
def original(myString):
    print myString

The behavior of original is overwritten. You can't use this to add a new functionality.

(b) Decorator pattern is about polymorphism. In your sample code above, the behavior of Decorator.something_useful is overwritten. The original method is lost. It's not really decorator pattern. You should be looking to enhance or add functionality, not replace a method. You should ensure that a.something_useful(string) returns the same thing as b.something_useful(string). In fact, in decorator pattern you would typically replace the original object. Here is what I mean:

class Class(object):
    def __init__(self):
        pass
    def something_useful(self, string):
        return string

class Decorator(object):
    def __init__(self, wrapped):
        self._wrapped = wrapped
    def withUnderscores(self, string):
        return '_'.join(string.split(' '))
    def __getattr__(self, name):
        return getattr(self._wrapped, name)


if __name__ == '__main__':
    string = 'Lorem ipsum dolor sit amet.'
    obj = Class()
    print('Original: ', obj.something_useful(string))
    #This has no underscore function.  Use decorator to add.
    obj = Decorator(obj)
    print('Replaced spaces: ', obj.withUnderscores(string))
    print('Original still works: ', obj.something_useful(string))

You can have several decorators to add functionality. This allows you to add only what you need when you need it. More reading: GoF

0

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.