Skip to content

Instantly share code, notes, and snippets.

View manuelinfosec's full-sized avatar
:octocat:
~ resolving merge conflicts

Manuel manuelinfosec

:octocat:
~ resolving merge conflicts
View GitHub Profile
def my_shiny_new_decorator(a_function_to_decorate):
# Inside, the decorator defines a function on the fly: the wrapper.
# This function is going to be wrapped around the original function
# so it can execute code before and after it.
def the_wrapper_around_the_original_function():
# Put here the code you want to be executed BEFORE the original
# function is called
print("Before the function runs")
def doSomethingBefore(func):
print("I do something before then I call the function you gave me")
print(func())
doSomethingBefore(scream)
# Outputs:
# I do something before then I call the function you gave me
# Yes!
# Get the function and assign it to a variable
talk = getTalk()
# You can see that `talk` is here a function object:
print(talk)
# Outputs : <function shout at 0xc1d2859b>
# The object is the one returned by the function:
print(talk())
# Outputs: Yes!
def getTalk(kind='shout'):
# We define functions on the fly
def shout(word='yes'):
return word.capitalize() + '!'
def whisper(word='yes'):
return word.lower() + '...'
# Then we return one of them
if kind == 'shout':
try:
print(whisper())
except NameError as e:
print(e)
# Outputs: "name 'whisper' is not defined"
def talk():
# Defining a function on the fly in `talk` ...
def whisper(word='yes'):
return word.lower() + '...'
# ... and using it right away!
print(whisper())
talk()
# Outputs: "yes..."
# deleting the shout() object
del shout
try:
# trying to access the deleted shout() object
print(shout())
except NameError as e:
print(e)
# Outputs: "name 'shout' is not defined"
print(scream())
# Outputs: 'Yes!'
scream = shout
def shout(word='yes'):
return word.capitalize() + '!'
print(shout())
# Outputs : 'Yes!'