16

I've noticed in several examples i see things such as this:

# Comments explaining code i think
@innerclass

or:

def foo():
"""
 Basic Doc String
"""
@classmethod

Googling doesn't get me very far, for just a general definition of what this is. Also i cant find anything really in the python documentation.

What do these do?

UberJumper
  • 20,245
  • 19
  • 69
  • 87
  • @uberjumper - You should give the answer to abhinavg if you feel we both deserve it. I got some free traffic to my blog and they have less rep than me anyway. – Jason Baker Jun 02 '09 at 14:05

4 Answers4

26

They are called decorators. They are functions applied to other functions. Here is a copy of my answer to a similar question.

Python decorators add extra functionality to another function. An italics decorator could be like

def makeitalic(fn):
    def newFunc():
        return "<i>" + fn() + "</i>"
    return newFunc

Note that a function is defined inside a function. What it basically does is replace a function with the newly defined one. For example, I have this class

class foo:
    def bar(self):
        print "hi"
    def foobar(self):
        print "hi again"

Now say, I want both functions to print "---" after and before they are done. I could add a print "---" before and after each print statement. But because I don't like repeating myself, I will make a decorator

def addDashes(fn): # notice it takes a function as an argument
    def newFunction(self): # define a new function
        print "---"
        fn(self) # call the original function
        print "---"
    return newFunction
    # Return the newly defined function - it will "replace" the original

So now I can change my class to

class foo:
    @addDashes
    def bar(self):
        print "hi"

    @addDashes
    def foobar(self):
        print "hi again"

For more on decorators, check http://www.ibm.com/developerworks/linux/library/l-cpdecor.html

Abhinav Gupta
  • 4,602
  • 2
  • 23
  • 18
12

They're decorators.

<shameless plug> I have a blog post on the subject. </shameless plug>

Jason Baker
  • 192,085
  • 135
  • 376
  • 510
5

With

@function
def f():
    pass

you simply wrap function around f(). function is called a decorator.

It is just syntactic sugar for the following:

def f():
    pass
f=function(f)
wr.
  • 2,841
  • 1
  • 23
  • 27
1

it is a decorator syntax.

SilentGhost
  • 307,395
  • 66
  • 306
  • 293