Skip to content

Instantly share code, notes, and snippets.

@cathoderay
Created March 1, 2012 18:05
Show Gist options
  • Save cathoderay/1951739 to your computer and use it in GitHub Desktop.
Save cathoderay/1951739 to your computer and use it in GitHub Desktop.
decorators examples
#!/usr/bin/env python
"""
File: decorators.py
Description: decorators examples
Author: Ronald Kaiser <raios dot catodicos at gmail dot com>
"""
import time
# Let's begin with a simple decorator, that adds
# some behaviour to a lazy function
def simple_decorator(fn):
def wrapper():
# adding behaviour before execution
print "before execution"
fn()
# adding behaviour after execution
print "after execution"
return wrapper
@simple_decorator
def lazy_function():
print "zz..."
time.sleep(2)
# Calling the lazy function to see the result
lazy_function()
# Well, it works! =)
# Now, let's try a decorator for a function with arguments
def another_decorator(fn):
def wrapper(*args):
print "well, gonna sleep again"
fn(*args)
print "time to wake up!"
return wrapper
@another_decorator
def another_lazy_function(period, level):
print "%s..." % ('z'*level)
time.sleep(period)
# calling another lazy function
another_lazy_function(5, 5)
# Pretty nice, huh?!
# Decorators may receive a list of arguments too.
# Let's try with a function that fires
def load(level):
def wrap(fn):
def wrapper():
for i in range(level):
print '.'
time.sleep(0.5)
fn()
return wrapper
return wrap
@load(5)
def fire():
print "Bang!"
# let's try to bang!
fire()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment