- Published on
Annotations AKA Decorators in Python
- Authors
- Name
- Yair Mark
- @yairmark
Today I came across some Python code where the one method had what looked like a Java annotation above it:
@property
def get_name():
return self.name
This is actually what is called a decorator in Python. It is simply a function that works on another function (a higher order function). The @method_name
is syntactic sugar for wrapping the method it is above.
For example say I wanted to print out hello
before every method call I would first define a function as follows:
def say_hello(fun):
def wrapper():
print("Hello")
fun()
return wrapper
I would then use it as:
@say_hello
def bar():
print("Bar")
bar()
It is important you return a function as in the above. If you by mistake do the following instead:
def say_hello(fun):
print("Hello")
fun()
@say_hello
def bar():
print("Bar")
bar()
You will get the following output and error (deocrator.py
is the name of the file where I had this example code in):
Hello
Bar
Traceback (most recent call last):
File "decorator.py", line 9, in <module>
bar()
TypeError: 'NoneType' object is not callable