Reputation: 21155
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?
Upvotes: 16
Views: 12337
Reputation: 4682
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
Upvotes: 26
Reputation: 2859
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)
Upvotes: 5
Reputation: 198777
They're decorators.
<shameless plug>
I have a blog post on the subject.
</shameless plug>
Upvotes: 12