Created
April 15, 2020 17:36
-
-
Save tbrlpld/6994e999c0ff27fe370fb96964d203bd to your computer and use it in GitHub Desktop.
Python decorators
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
print(" NO AGRUMENTS ".center(30, "#")) | |
def this_adds_decoration(function_to_decorate): | |
def this_creates_decoration(): | |
print("Before") | |
function_to_decorate() | |
print("After") | |
# Return the created decoration to add it to a function | |
return this_creates_decoration | |
@this_adds_decoration | |
def normal_function(): | |
print("Normal output") | |
normal_function() | |
# Before | |
# Normal output | |
# After | |
print(" WTH AGRUMENTS ".center(30, "#")) | |
def this_adds_decoration_with_arguments(function_to_decorate): | |
def this_creates_decoration(*args, **kwargs): | |
print("Before") | |
print("I know already that name is: {0}".format(args[0])) | |
function_to_decorate(*args, **kwargs) | |
print("After") | |
# Return the created decoration to add it to a function | |
return this_creates_decoration | |
@this_adds_decoration_with_arguments | |
def greeting(name): | |
print("Hello {0}".format(name)) | |
greeting("You") | |
# Before | |
# I know already that name is: You | |
# Hello You | |
# After |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment