tags:

views:

264

answers:

4

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?

+2  A: 

it is a decorator syntax.

SilentGhost
+7  A: 

They're decorators.

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

Jason Baker
Your shameless plug, was an extremely well written and clear article.
UberJumper
+2  A: 

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
+12  A: 

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

abhinavg
I wish i could give two people accepted solution. :(
UberJumper
FYI - the other answer is here: http://stackoverflow.com/questions/739654/understanding-python-decorators/739667#739667
Jason Baker