Skip to content

Implemented the correct Decorator Pattern (Issue #150) #155

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Oct 9, 2016
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
46 changes: 27 additions & 19 deletions decorator.py
Original file line number Diff line number Diff line change
@@ -1,33 +1,41 @@
#!/usr/bin/env python
"""https://docs.python.org/2/library/functools.html#functools.wraps"""
"""https://stackoverflow.com/questions/739654/how-can-i-make-a-chain-of-function-decorators-in-python/739665#739665"""
"""
Reference: https://en.wikipedia.org/wiki/Decorator_pattern
"""

from functools import wraps

class TextTag(object):
"""Represents a base text tag"""
def __init__(self, text):
self._text = text

def makebold(fn):
return getwrapped(fn, "b")
def render(self):
return self._text


def makeitalic(fn):
return getwrapped(fn, "i")
class BoldWrapper(object):
"""Wraps a tag in <b>"""
def __init__(self, wrapped):
self._wrapped = wrapped

def render(self):
return "<b>{}</b>".format(self._wrapped.render())

def getwrapped(fn, tag):
@wraps(fn)
def wrapped():
return "<%s>%s</%s>" % (tag, fn(), tag)
return wrapped

class ItalicWrapper(object):
"""Wraps a tag in <i>"""
def __init__(self, wrapped):
self._wrapped = wrapped

@makebold
@makeitalic
def hello():
"""a decorated hello world"""
return "hello world"
def render(self):
return "<i>{}</i>".format(self._wrapped.render())

if __name__ == '__main__':
print('result:{} name:{} doc:{}'.format(hello(), hello.__name__, hello.__doc__))
simple_hello = TextTag("hello, world!")
special_hello = ItalicWrapper(BoldWrapper(simple_hello))
print("before:", simple_hello.render())
print("after:", special_hello.render())

### OUTPUT ###
# result:<b><i>hello world</i></b> name:hello doc:a decorated hello world
# before: hello, world!
# after: <i><b>hello, world!</b></i>