Decorators and Properties

Austin Godber

@godber

July 2014

PEP 318 - Python 2.4

Background

  • Functions are objects.
  • Functions can be passed in as arguments and returned.

Identity Decorator (from @BrianHoldefehr)

In [9]:
def identity_decorator(func):
    def wrapper():
        func()
    return wrapper

def a_function():
    print "I'm a normal function."

decorated_function = identity_decorator(a_function)
decorated_function()
I'm a normal function.

Using the @ notation

In [10]:
@identity_decorator
def another_decorated_function():
    print "I too am a normal function"
    
another_decorated_function()
I too am a normal function

Notation

Using the @ and placing it before the function to be decorated puts it in-your-face.

  • Guido van Rossum (Fri Aug 6 16:45:51 CEST 2004)

Highlights the function modification instead of burying it at the end as a variable assignment.

Decorator Ordering

@dec2
@dec1
def function1():
    pass

equivalent to

def function1():
    pass
func = dec2(dec1(function1))

Passing Arguments to Decorators

You can do it.

In []:
 
In [1]:
def increment(val):
    return val + 1

increment(1)
Out[1]:
2

In Use

  • Click @click.command
  • Flask @app.route