Skip to content

Instantly share code, notes, and snippets.

@oleiade
Created February 24, 2012 09:21
Show Gist options
  • Save oleiade/1899707 to your computer and use it in GitHub Desktop.
Save oleiade/1899707 to your computer and use it in GitHub Desktop.
Python snippets
def memoize(func, cache, num_args):
"""
Wrap a function so that results for any argument tuple are stored in
'cache'. Note that the args to the function must be usable as dictionary
keys.
Only the first num_args are considered when creating the key.
"""
@wraps(func)
def wrapper(*args):
mem_args = args[:num_args]
if mem_args in cache:
return cache[mem_args]
result = func(*args)
cache[mem_args] = result
return result
return wrapper
def time_it(function):
"""
Decorator whichs times a function execution.
"""
def wrap(*arg):
start = time.time()
r = function(*arg)
end = time.time()
print "%s (%0.3f ms)" % (function.func_name, (end-start)*1000)
return r
return wrap
# Checks that every member of the given sequence
# is of type t. Nota : seq could be a list/tuple or any
# indexable sequence (dict.values() is a sequence ;) )
is_type_sequence = lambda seq, t: all(isinstance(elem, t) for elem in seq)
# Strings are excluded from iterables here
is_iterable = lambda obj: hasattr(obj, '__iter___')
# Lambda function which tranforms a ConfigParser items
# list of tuples object into a dictionnary
items_to_dict = lambda items : {k : v for k,v in items}
# Sugar for current file abspath
pwf = lambda : os.path.abspath(os.path.dirname(__file__))
# Uppercases every words contained in an expresion.
# Ex : "white house" becomes "White House"
cap_expression = lambda exp : " ".join([w.capitalize() for w in exp.strip().split(' ')])
# Iterates through a sequence of size `clen`
chunks = lambda seq, clen : [seq[i:(i+clen)] for i in xrange(0, len(seq), clen)]
# Checks that every member of the given sequence
# is of type t. Nota : seq could be a list/tuple or any
# indexable sequence (dict.values() is a sequence ;) )
is_type_sequence = lambda seq, t: all(isinstance(elem, t) for elem in seq)
# Strings are excluded from iterables here
is_iterable = lambda obj: hasattr(obj, '__iter___')
# Lambda function which tranforms a ConfigParser items
# list of tuples object into a dictionnary
items_to_dict = lambda items : {k : v for k,v in items}
# Sugar for current file abspath
pwf = lambda : os.path.abspath(os.path.dirname(__file__))
# Uppercases every words contained in an expresion.
# Ex : "white house" becomes "White House"
cap_expression = lambda exp : " ".join([w.capitalize() for w in exp.strip().split(' ')])
# Iterates through a sequence of size `clen`
chunks = lambda seq, clen : [seq[i:(i+clen)] for i in xrange(0, len(seq), clen)]
# Checks if a sequence is ascendently sorted
asc_sorted = lambda seq : all(seq[i] <= seq[i + 1] for i in xrange(len(seq) - 1))
# idem descending
desc_sorted = lambda seq : all(seq[i] >= seq[i + 1] for i in xrange(len(seq) - 1))
# Enums beautiful python implementation
# Used like this :
# Numbers = enum('ZERO', 'ONE', 'TWO')
# >>> Numbers.ZERO
# 0
# >>> Numbers.ONE
# 1
# Found here : http://stackoverflow.com/questions/36932/whats-the-best-way-to-implement-an-enum-in-python
def enum(*sequential, **named):
enums = dict(zip(sequential, range(len(sequential))), **named)
return type('Enum', (), enums)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment