Skip to content

Instantly share code, notes, and snippets.

View poros's full-sized avatar

Antonio Uccio Verardi poros

View GitHub Profile
@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 / 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 / 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 / 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 / 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 / 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 / multiple_vars.py
Created October 4, 2015 16:31
Update multiple state variables at once
def fibonacci(n):
x = 0
y = 1
for i in range(n):
print x
tmp = y
y = x + y
x = tmp
@poros
poros / chainmap.py
Created October 4, 2015 16:16
Overriding dictionaries
d = defaults.copy()
d.update(os.environ)
d.update(command_line_arguments)
# PYTHON3 ONLY!!!
from collections import ChainMap
d = ChainMap(command_line_arguments, os.environ, defaults)
# it's view, not a real dictionary. if you want something equivalent to a new one
d = ChainMap({}, command_line_arguments, os.environ, defaults)
@poros
poros / counter.py
Created October 4, 2015 16:03
Counting with dictionaries
colors = ['green', 'blue', 'green', 'red', 'blue', 'green']
d = {}
for color in colors:
if color not in d:
d[color] = 0
d[color] += 1
# slighlty better
@poros
poros / defaultdict.py
Created October 4, 2015 15:46
Grouping with dictionaries
d = {}
for name in names:
key = len(name)
if key not in d:
d[key] = []
d[key].append(name)
# slightly better
d = {}