一个助手函数和装饰器的集合,我偶尔使用它们来使我的生活井然有序。
mj-helpers的Python项目详细描述
我偶尔用来获取 我的生活井然有序。
安装
pip install mj_helpers
剖面图
用于分析函数调用的修饰程序。
用法:
from mj_helpers.decorators import profileit @profileit def foo(): return do_stuff()
在python外壳中:
>>> from .foo import foo >>> foo() >>> from pstats import Stats >>> stats = Stats('/tmp/foo.profile') >>> stats.sort_stats('cumulative').print_stats(50) Fri Nov 27 08:34:14 2015 /tmp/foo.profile 2 function calls in 0.000 seconds Ordered by: cumulative time ncalls tottime percall cumtime percall filename:lineno(function) 1 0.000 0.000 0.000 0.000 <ipython-input-8-8f35865ca12d>:1(foo) 1 0.000 0.000 0.000 0.000 {method 'disable' of '_lsprof.Profiler' objects}
如果通过pip或python setup.py安装:
mj_stats /tmp/foo.profile /tmp/bar.profile --sorting=cumulative --limit=50
日志功能IO
记录函数名、args和kwargs的日志修饰符。
在python中:
from mj_helpers.log_decorator import log_function_io @log_function_io def foo(bar, spam=None, *args, **kwargs): return do_stuff() class Thing(object): pass class Bar(object): @staticmethod @log_function_io def static_method(spam, eggs='eggs'): return True @classmethod @log_function_io def class_method(cls, foo='foo', bar=None): return False @log_function_io def function(self, thing): return Thing()
控制台:
>>> foo('a', *['first star', 'second star'], **{'something': 'boo'}) 2016-02-02 05:04:50,963 - __main__ - DEBUG - [FUN] foo [ARG] bar: 'a', spam: 'first star', something: 'boo' *('second star',) 2016-02-02 05:04:50,963 - __main__ - DEBUG - [FUN] foo [RET] None >>> Bar.static_method('spam') 2016-02-02 05:09:30,426 - __main__ - DEBUG - [FUN] static_method [ARG] spam: 'spam' 2016-02-02 05:09:30,426 - __main__ - DEBUG - [FUN] static_method [RET] True >>> Bar.class_method(bar='spam') 2016-02-02 05:11:39,753 - __main__ - DEBUG - [FUN] class_method [ARG] bar: 'spam' 2016-02-02 05:11:39,753 - __main__ - DEBUG - [FUN] class_method [RET] False >>> Bar().function(thing='spam') 2016-02-02 05:13:01,679 - __main__ - DEBUG - [FUN] function [ARG] thing: 'spam' 2016-02-02 05:13:01,679 - __main__ - DEBUG - [FUN] function [RET] <__main__.Thing object at 0x7f33d8627f90>
缓存
缓存decorator以帮助缓存函数调用/返回。
在python中:
from mj_helpers.decorators import cache_it @cache_it() def foo(bar, spam=None, *args, **kwargs): return do_stuff() # If using memoize instead of django's cache you can see the cache by: >>> cache_it._cache { <function foo at 0x7f4419daa848>: { "(('a', 'first star', 'second star'), (('something', 'boo'),))": (None, 1454391947.614329) } }