Skip to content

Instantly share code, notes, and snippets.

@paulera
Created January 21, 2018 21:14
Show Gist options
  • Save paulera/80fec9f586b486a2b40d9e86b65b0506 to your computer and use it in GitHub Desktop.
Save paulera/80fec9f586b486a2b40d9e86b65b0506 to your computer and use it in GitHub Desktop.
Studying decorators and figuring out how to pass parameters. In this example, a decorator tag_decorate('h1') will wrap the result of a function in <h1>...</h1>
"""
Decorators with parameters study
In a simple decorator usage, the decorator function takes a callable object as
parameter (the function to be decorated, let's call it "target"), and returns
another callable which will be executed instead (let's call it "wrapper").
For this reason, it is essential that the wrapper accept the same parameters
as the target, and return an object of the same type.
The wrapper will have the target in scope, therefore can run it and return a
modified result.
When we want to pass a parameter for the decorator, we must make a function
that receives the parameter (therefore puts it in local scope), then
returns a real decorator (a function, which receives a callable, and returns
another callable that uses the passed one).
"""
def tag_decorate(tag):
"""
This function is not a decorator yet. When called with a parameter,
it will return an actual decorator that will have the parameter tag
in the scope
"""
def real_decorator(func):
"""
real_decorator is an actual decorator, which returns a callable
object (wrapper) with the same signature of the decorated function.
"""
def wrapper(param):
"""
wrapper will be called instead of the decorated function. It will
use the decorated function, modify the result and return a new string
"""
contents = func(param)
return "<{t}>{c}</{t}>".format(t=tag, c=contents)
return wrapper # this is the return of real_decorator
return real_decorator
@tag_decorate('h1')
def get_greet(planet):
return "Hello " + planet + "!"
print get_greet('Earth')
"""
result is
<h1>Hello Earth!</h1>
"""
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment