Skip to content

Instantly share code, notes, and snippets.

@mattvh
Last active December 21, 2020 00:49
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mattvh/30a7b7292866b83d5f3b875faeca7fde to your computer and use it in GitHub Desktop.
Save mattvh/30a7b7292866b83d5f3b875faeca7fde to your computer and use it in GitHub Desktop.
Example for Medium article "Python Decorators Explained"
def decorate(func):
print("Do something before func()")
func()
return func #return the original function, unmodified
@decorate
def hello():
print("Hello, world!")
import urllib.request, json
class XKCDThing(object):
def __init__(self):
self.subscribers = []
def subscriber(self, func):
self.subscribers.append(func)
return func
def publish(self, title, link):
for func in self.subscribers:
func(title, link)
def run(self):
url = "https://xkcd.com/info.0.json"
with urllib.request.urlopen(url) as req:
data = json.loads(req.read().decode())
title = data['safe_title']
link = data['img']
self.publish(title, link)
app = XKCDThing()
@app.subscriber
def eventHandler1(title, link):
print("Event handler 1 called!")
print(f"Title: {title}")
@app.subscriber
def eventHandler2(title, link):
print("Event handler 2 called!")
print(f"Link: {link}")
app.run()
def wrap(func):
def wrapper():
print("Say hello? Y/N")
if input() == "Y":
func()
else:
print("OK.")
return wrapper
@wrap
def hello():
print("Hello, world!")
hello()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment