一种新颖实用的功能工具
func的Python项目详细描述
以实用性为中心的一组奇特的功能工具。
灵感来自clojure,下划线和我自己的抽象。继续阅读以获得概述 或者read the docs。 或者直接跳到cheatsheet。
与python 2.6+、3.3+和pypy一起使用。
安装
pip install funcy
概述
从funcy导入内容以使事情发生:
fromfuncyimportwhatever,you,need
合并相同类型的集合 (适用于dict、set、list、tuple、迭代器甚至字符串):
merge(coll1,coll2,coll3,...)join(colls)merge_with(sum,dict1,dict2,...)
遍历集合,创建其转换(类似于映射但保留类型):
walk(str.upper,{'a','b'})# {'A', 'B'}walk(reversed,{'a':1,'b':2})# {1: 'a', 2: 'b'}walk_keys(double,{'a':1,'b':2})# {'aa': 1, 'bb': 2}walk_values(inc,{'a':1,'b':2})# {'a': 2, 'b': 3}
选择收藏的一部分:
select(even,{1,2,3,10,20})# {2,10,20}select(r'^a',('a','b','ab','ba'))# ('a','ab')select_keys(callable,{str:'',None:None})# {str: ''}compact({2,None,1,0})# {1,2}
操作序列:
take(4,iterate(double,1))# [1, 2, 4, 8]first(drop(3,count(10)))# 13lremove(even,[1,2,3])# [1, 3]lconcat([1,2],[5,6])# [1, 2, 5, 6]lcat(map(range,range(4)))# [0, 0, 1, 0, 1, 2]lmapcat(range,range(4))# sameflatten(nested_structure)# flat iterdistinct('abacbdd')# iter('abcd')lsplit(odd,range(5))# ([1, 3], [0, 2, 4])lsplit_at(2,range(5))# ([0, 1], [2, 3, 4])group_by(mod3,range(5))# {0: [0, 3], 1: [1, 4], 2: [2]}lpartition(2,range(5))# [[0, 1], [2, 3]]chunks(2,range(5))# iter: [0, 1], [2, 3], [4]pairwise(range(5))# iter: [0, 1], [1, 2], ...
以及功能:
partial(add,1)# inccurry(add)(1)(2)# 3compose(inc,double)(10)# 21complement(even)# oddall_fn(isa(int),even)# is_even_intone_third=rpartial(operator.div,3.0)has_suffix=rcurry(str.endswith)
轻松创建装饰程序:
@decoratordeflog(call):printcall._func.__name__,call._argsreturncall()
抽象控制流:
walk_values(silent(int),{'a':'1','b':'no'})# => {'a': 1, 'b': None}@oncedefinitialize():"..."withsuppress(OSError):os.remove('some.file')@ignore(ErrorRateExceeded)@limit_error_rate(fails=5,timeout=60)@retry(tries=2,errors=(HttpError,ServiceDown))defsome_unreliable_action(...):"..."classMyUser(AbstractBaseUser):@cached_propertydefpublic_phones(self):returnself.phones.filter(public=True)
易于调试:
squares={tap(x,'x'):tap(x*x,'x^2')forxin[3,4]}# x: 3# x^2: 9# ...@print_exitsdefsome_func(...):"..."@log_calls(log.info,errors=False)@log_errors(log.exception)defsome_suspicious_function(...):"..."withprint_durations('Creating models'):Model.objects.create(...)# ...# 10.2 ms in Creating models
潜入
funcy是我在几篇文章中解释的思想的一个体现:
运行测试
使用默认的python运行测试:
pip install -r test_requirements.txt py.test
要完全运行tox,需要安装所有受支持的python。这些是 2.6+、3.3+、pypy和pypy3。你可以在特定的环境下运行它,即使在没有意识的情况下 以上各项中:
tox -e py27 tox -e py36 tox -e lint