Last active
August 9, 2021 12:01
-
-
Save Rustam-Z/6bb6432f279c0c2510b5d8b3d8efd797 to your computer and use it in GitHub Desktop.
Project: HTML generator with Python decorator
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
"""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