Created
August 24, 2015 06:23
-
-
Save siteshen/96b4870e07569ff54c4e to your computer and use it in GitHub Desktop.
Some python util functions && classes
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #!/usr/bin/env python2 | |
| # -*- coding: utf-8 -*- | |
| import datetime | |
| import functools | |
| import time | |
| # logging | |
| # ======= | |
| def print_rect(lines): | |
| if isinstance(lines, basestring): | |
| lines = [lines] | |
| lines.insert(0, datetime.now().strftime('%Y-%m-%d %H:%M:%S')) | |
| max_len = max([len(l) for l in lines]) + 2 | |
| legend = '+' + '-' * max_len + '+' | |
| s = [legend, '\n'.join(['| %s%s |' % (l, ' ' * (max_len - len(l) - 2)) for l in lines]), legend] | |
| print '\n'.join(s) | |
| def logging(func): | |
| def inner(*args, **kwargs): | |
| pretty_name = '%s(args=%s, kwargs=%s)' % (func.__name__, args, kwargs) | |
| print_rect('%s start ...' % pretty_name) | |
| start = time.time() | |
| result = func(*args, **kwargs) | |
| end = time.time() | |
| print_rect('%s end %.1fs' % (pretty_name, end - start)) | |
| return result | |
| return inner | |
| # cache | |
| # ===== | |
| def hash_object(obj): | |
| if isinstance(obj, (tuple, list)): | |
| return (type(obj), tuple([hash_object(it) for it in obj])) | |
| elif isinstance(obj, dict): | |
| return (type(obj), tuple([(k, hash_object(v)) | |
| for (k, v) in obj.iteritems()])) | |
| else: | |
| return obj | |
| # https://wiki.python.org/moin/PythonDecoratorLibrary#Cached_Properties | |
| class Cached(object): | |
| def __init__(self, ttl=300): | |
| self.ttl = ttl | |
| self._cache = {} | |
| def __call__(self, fn, *args, **kwargs): | |
| @functools.wraps(fn) | |
| def decorated(*args, **kwargs): | |
| # TODO: a better hash function? | |
| key = hash_object((args, kwargs)) | |
| now = time.time() | |
| try: | |
| value, last_update = self._cache[key] | |
| if self.ttl > 0 and now - last_update > self.ttl: | |
| raise AttributeError | |
| except (KeyError, AttributeError): | |
| value = fn(*args, **kwargs) | |
| self._cache[key] = (value, now) | |
| return value | |
| return decorated |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment