Skip to content

Instantly share code, notes, and snippets.

View poros's full-sized avatar

Antonio Uccio Verardi poros

View GitHub Profile
@poros
poros / cache.py
Last active November 12, 2017 13:42
Caching with decorators
saved = {}
def web_lookup(url):
if url in saved:
return saverd[url]
page = urrlib.urlopen(url).read()
saved[url] = page
return page
# NEEDS TO BE A PURE FUNCTION, NO SIDE EFFECTS LIKE PRINT
@poros
poros / suppress.py
Last active October 4, 2015 17:47
Ignore exceptions context manager
try:
os.remove('somefile.tmp')
except OSError:
pass
# note: checking if the file exists before deletion leads to a race condition
# PYTHON 3
from contextlib import suppress
@poros
poros / multiprocessing_map.py
Created October 4, 2015 18:20
Process/thread pool for embarrassingly parallel problems
from multiprocessing import Pool
pool = Pool(4)
results = pool.map(urllib2.urlopen, urls)
pool.close()
pool.join()
# if you want threads instead of processes
from multiprocessing.dummy import Pool
@poros
poros / class_contextmanager.py
Last active October 4, 2015 23:01
Define a context manager class
class DBConnection(object):
def __init__(self, address):
self.crappy_db = CrappyDBConnection(address)
def __enter__(self):
self.crappy_db.connect()
return self # what is returned here will be availabe via "as"
def __exit__(self, exc_type, exc_val, exc_tb):
if exc_type == ConnectionError:
@poros
poros / generator_contextmanager.py
Last active October 4, 2015 23:02
Define a context manager generator
from contextlib import contextmanager
@contextmanager
def connect_to_db(address):
db = CrappyDBConnection(address)
try:
yield db
except ConnectionError:
logging.exception('Connection dropped')
db.cleanup('rollback')
@poros
poros / decorator_class_contextmanager.py
Last active October 25, 2015 16:08
Define a context manager usable as decorator
# USAGE
@track_entry_and_exit('widget loader')
def activity():
print('Some time consuming activity goes here')
load_widget()
with track_entry_and_exit('widget loader'):
print('Some time consuming activity goes here')
load_widget()
@poros
poros / decorator.py
Last active October 28, 2015 22:49
Define a decorator
@f1(arg)
@f2
def func(): pass
# is equivalent to
def func(): pass
func = f1(arg)(f2(func))
def my_decorator(a_function_to_decorate):
@poros
poros / sequence.py
Created October 5, 2015 00:33
Make something iterable
class RoutingTable(object):
def __init__(self, crappy_rt):
self.crappy_rt = crappy_rt
def __len__(self):
return self.crappy_rt.getSize()
def __getitem__(self, index):
if index >= len(self):
raise IndexError
@poros
poros / product.py
Last active October 5, 2015 22:37
Combine several sets of items
from itertools import product
product(('ENDPOINT1', 'ENDPOINT2'), ('GET', 'POST'), ('200', '404', '500'))
# returns a generator
[('ENDPOINT1', 'GET', '200'), ('ENDPOINT1', 'GET', '404'), ('ENDPOINT1', 'GET', '500'), ('ENDPOINT1', 'POST', '200'), ('ENDPOINT1', 'POST', '404'), ('ENDPOINT1', 'POST', '500'), ('ENDPOINT2', 'GET', '200'), ('ENDPOINT2', 'GET', '404'), ('ENDPOINT2', 'GET', '500'), ('ENDPOINT2', 'POST', '200'), ('ENDPOINT2', 'POST', '404'), ('ENDPOINT2', 'POST', '500')]
@poros
poros / super_dependency_injection.py
Created October 5, 2015 22:58
Use super() for dependency injection
from collection import Counter
from collection import OrderedDict
Counter('luppolo')
Counter({'p': 2, 'l': 2, 'o': 2, 'u': 1})
help(Counter)
| Method resolution order:
| Counter
| __builtin__.dict
| __builtin__.object