Skip to content

Instantly share code, notes, and snippets.

@alonho
alonho / gist:4571551
Last active December 11, 2015 08:09
mock globals and imports
from foo import SomeClass
import mock
a = 100
def global_variable():
with mock.patch(__name__ + '.a'):
print a
def class_patch():
# read about 'where to patch' to see why not patch 'foo.SomeClass'
@alonho
alonho / bench.py
Last active December 10, 2015 21:08
a timed contextmanager for easy benchmarking.
from Framework.Log.Log import logger
from contextlib import contextmanager
from time import time
@contextmanager
def timed(message):
''''
with timed('testing division'):
4 / 2
''''
@alonho
alonho / json_datetime.py
Created December 30, 2012 21:47
A symmetric-python-datetime-json-codec
from time import mktime
from dateutil.parser import parse
from datetime import datetime
from json import JSONEncoder, JSONDecoder
ISOTIME_IDENTIFITER = '$isotime'
EPOCHTIME_IDENTIFIER = '$epochtime'
class JsonDatetimeEncoder(JSONEncoder):
@alonho
alonho / flask_pdb.py
Created December 27, 2012 15:40
Flask: drop into pdb on exception
def drop_into_pdb(app, exception):
import sys
import pdb
import traceback
traceback.print_exc()
pdb.post_mortem(sys.exc_info()[2])
# somewhere in your code (probably if DEBUG is True)
flask.got_request_exception.connect(drop_into_pdb)
@alonho
alonho / egg_inspect.py
Created November 29, 2012 12:25
get the version of the current module
import os
import pkg_resources
def get_distribution(package):
'''
Can be called from within eggs in order to get the current distribution:
get_distribution(__package__)
__package__ is the same as __name__ except for script execution where __name__ equals '__main__'
@alonho
alonho / gist:2900231
Created June 9, 2012 09:18
traces from sqlite
{Alons-MacBook-Pro-2:cpytrace} % sqlite3 -header -column ./db.sqlite "select traces.id, time, tid, type, depth, modules.value, funcs.name, types.value, arg_values.value, arg_names.value from traces join funcs on (traces.func_id=funcs.id) join modules on (funcs.module_id=modules.id) join association on (traces.id=association.trace_id) join args on (association.arg_id=args.id) join arg_names on (args.name_id=arg_names.id) join arg_values on (args.value_id=arg_values.id) join types on (args.type_id=types.id);"
id time tid type depth value name value value value
---------- ---------------- ---------- ---------- ---------- ------------------------------------------------- ---------- ------------ ---------- ----------
1 1339232492.47153 2015967584 call 18 build/lib.macosx-10.4-x86_64-2.7/cpytrace/test.py fib <type 'int'> 3 n
2 1
@alonho
alonho / gist:2838190
Created May 30, 2012 18:38
ExitStack.__exit__
def __exit__(self, *exc_details):
if not self._exit_callbacks:
return
for cb in reversed(self._exit_callbacks):
try:
supress_exc = cb(*exc_details)
except:
exc_details = sys.exc_info()
else: