Monday, August 8, 2011

On StackOverflow: Understanding Python decorators

By Vasudev Ram - dancingbison.com | @vasudevram | jugad2.blogspot.com

Seen on Hacker News, a good thread on StackOverflow.com about Python decorators:

Understanding Python decorators: http://goo.gl/ZvnXb

Decorators in Python are a version of the Decorator design pattern.

A decorator is a Python language feature that allows you to wrap a function, with some code, using another function (called the decorator), _without_ modifying the code of the original function.

Decorators have many uses, but one of them that you may be able to guess from this description, is that you can use them to enhance the behavior of functions that you do not have the source code of, or which you do not want  to modify for some reason.

The thread starts off with a simple example - but of two chained decorators - which is still easy to understand. Some of the other explanations I've seen of decorators are not as clear as this brief one.

The example below that is somewhat longer, and is also clear and good; there are also a few more comments.

Overall, worth a read, if you do Python and want to know more about decorators.

Posted via email

- Vasudev Ram @ Dancing Bison


No comments: