Hacker News new | past | comments | ask | show | jobs | submit login
Python Decorators: What they are underneath (crschmidt.net)
22 points by dhotson on Dec 30, 2008 | hide | past | favorite | 5 comments



The article that this article is responding to is useful in understanding as well.

http://sgillies.net/blog/858/how-to-decorate-python-gis-code...

This one as well.

http://www.artima.com/weblogs/viewpost.jsp?thread=240845


Thank you! I've been trying to wrap my head around decorators this past week. Definitely a good guide.


Really, the only thing you need to wrap your head around to understand decorators is the concept of first-class functions (functions that can take functions as parameters and return functions).

If you understand those, and how they can be useful, the only remaining step to python's decorators is a syntactic transformation.

  def decorate(func):
      def wrapper(*args, **kwargs):
          print "I'm decorated!"
          return func(*args, **kwargs)
      return wrapper


  @decorate
  def foo():
      print "I'm foo!"

Above, @decorate is equivalent to having foo = decorate(foo) underneath the definition of foo. Decorate takes a function X as a parameter, creates a function Y that takes whatever arguments, prints a statement, and returns the value of calling Y with whatever arguments. It then returns the object representing X.

If you need a bunch of good examples of how first-class functions can be extremely useful, go through a bit of SICP ( http://mitpress.mit.edu/sicp/full-text/book/book.html ). It's a challenging tome, but well worth the effort.


I didn't realize that Jython was out-of-date enough to miss decorators... I hope that Jython doesn't die.


"As of October 31, 2008, the Jython development team is proud to announce a new beta release: Jython 2.5b0!" http://www.jython.org/Project/

Jython is alive and well.




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: