Skip to content

Instantly share code, notes, and snippets.

@victorwyee
Created February 27, 2021 03:49
Show Gist options
  • Select an option

  • Save victorwyee/6b7e3ff754fa9ecbbaeef2545b265c23 to your computer and use it in GitHub Desktop.

Select an option

Save victorwyee/6b7e3ff754fa9ecbbaeef2545b265c23 to your computer and use it in GitHub Desktop.
Stop Writing Classes (Jack Diederich, PyCon US 2012)
class Greeting:
def __init__(self, greeting='hello'):
self.greeting = greeting
def greet(self, name):
return f'{self.greeting}! {name}'
greeting = Greeting('hola')
print(greeting.greet('bob'))
def greet(name):
ob = Greeting('hola')
print(ob.greet('bob))
return
def greet(greeting, target):
return f'{greeting}! {target}'
import functools
greet = functools.partial(greet, 'hola')
greet('bob')
# MuffinHash.py is a module containing two lines.
class MuffinHash(dict):
pass
# Everywhere in the code has
d = MuffinMail.MuffinHash.MuffinHash(foo=3) # d = {'foo': 3}
class API:
def __init__(self, key):
self.header = dict(apikey=key)
def call(self, method, params):
request = urllib2.Request(
self.url + method[0] + '/' + method[1],
urllib.urlencode(params),
self.header
)
try:
response = json.loads(urllib2.urlopen(request).read())
return response
except urllib2.HTTPError as error:
return dict(Error=str(error))
MUFFIN_API_URL = 'https://api.wbsrvc.com/%s/%s'
MUFFIN_API_KEY = 'SECRET-API-KEY'
def request(noun, verb, **params):
headers = {'apikey': MUFFIN_API_KEY}
request = urllib2.Request(
MUFFIN_API_URL % (noun, verb),
urllib.urlencode(params), headers)
return json.loads(urllib2.urlopen(request).read())
try:
get_article()
raise LookupError() # this raises an exception
except ArticleNotFound: # this catches an exception
pass
class Flow:
"""Base class for all Flow objects."""
pass
class Storage:
def put(self, data): _abstract()
def get(self): _abstract()
def _abstract(): raise NotImplementedError
class Cell:
def __init__(self, x, y, alive=True):
self.x = x
self.y = y
self.alive = alive
self.next = None
def neighbors(self):
yield (self.x + 1, self.y)
yield (self.x + 1, self.y + 1)
# ...
yield (self.x + 1, self.y)
class Board:
def __init__(self):
self.cells = {} # { (x, y) : Cell() }
def advance(self):
for (x, y), cell in self.cells.items():
if len(cell.neighbors) > 3:
cell.next = False
def neighbors(point):
x, y = point
yield x + 1, y
yield x - 1, y
yield x, y + 1
yield x, y - 1
yield x + 1, y + 1
yield x + 1, y - 1
yield x - 1, y + 1
yield x - 1, y - 1
def advance(board):
newstate = set()
recalc = board | set(itertools.chain(*map(neighbors, board)))
for point in recalc:
count = sum((neigh in board)
for neigh in neighbors(point))
if count == 3 or (count == 2 and point in board):
newstate.add(point)
return newstate
glider = set([(0, 0), (1, 0), (2, 0), (0, 1), (1, 2)])
for i in range(1000):
glider = advance(glider)
print(glider)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment