Skip to content

Instantly share code, notes, and snippets.

@hosackm
Created September 30, 2015 22:25
Show Gist options
  • Save hosackm/9142ef43ca91f6c23109 to your computer and use it in GitHub Desktop.
Save hosackm/9142ef43ca91f6c23109 to your computer and use it in GitHub Desktop.
Python decorators explained in a couple functions
# Two examples to remember how decorators should be written.
# The first has no arguments in the decorator
# The second shows how to pass arguments like @dec(...)
#no args to decorator tag. ie:
def decorator_name(func_getting_decorated):
def func_being_returned(args_to_func_getting_decorated):
#decoration step here
print "decoration occured"
#make sure the returned decorator does whatever
#the original func was supposed to here
func_getting_decorated(args_to_func_getting_decorated)
return func_being_returned
@decorator_name
def f(arg):
print "f() called with:", arg
"""
>>> f(3)
decoration occured
f() called with: 3
"""
#decorator tag using args
def decorator_name(dec_arg):
def dec_func(func):
def func_wrap(func_arg):
#do decoration step
print "decoration occured with:", dec_arg
func(func_arg)
return func_wrap
return dec_func
@decorator_name("I'm a decorator argument!")
def f2(arg):
print "f2() called with:", arg
"""
>>>f2(3)
decoration occured with: I'm a decorator argument!
f2() called with: 3
"""
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment