Skip to content

Instantly share code, notes, and snippets.

@Rustam-Z
Last active August 9, 2021 12:01
Show Gist options
  • Save Rustam-Z/6bb6432f279c0c2510b5d8b3d8efd797 to your computer and use it in GitHub Desktop.
Save Rustam-Z/6bb6432f279c0c2510b5d8b3d8efd797 to your computer and use it in GitHub Desktop.
Project: HTML generator with Python decorator
"""Project: HTML Generator
With the new html() decorator you can focus on
writing simple functions that return the
information you want to display on the webpage
and let the decorator take care of wrapping them
in the appropriate HTML tag.
"""
def html(open_tag, close_tag):
def decorator(func):
@wraps(func)
def wrapper(*args, **kwargs):
msg = func(*args, **kwargs)
return '{}{}{}'.format(open_tag, msg, close_tag)
# Return the decorated function
return wrapper
# Return the decorator
return decorator
# Make hello() return bold text
@html("<b>", "</b>")
def hello(name):
return 'Hello {}!'.format(name)
# Make goodbye() return italicized text
@html("<i>", "</i>")
def goodbye(name):
return 'Goodbye {}.'.format(name)
# Wrap the result of hello_goodbye() in <div> and </div>
@html("<div>", "</div>")
def hello_goodbye(name):
return '\n{}\n{}\n'.format(hello(name), goodbye(name))
print(hello('Alice'))
print(goodbye('Alice'))
print(hello_goodbye('Alice'))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment