今天写了一个三重 def 的 Python 函数

2015-07-27 21:14:32 +08:00
 iptux
# decorator wrapper for _Parser()
def Parser(cls, cache = False):
    def _fun(fun):
        def _Fun(*arg, **kw):
            # try get from cache
            if cache and (len(arg) >= 1 or '_id' in kw):
                _id = arg[0] if arg else kw['_id']
                o = Cacher(cls).get(_id)
                if o:
                    return o
            ret = fun(*arg, **kw)
            try:
                ret = _Parser(ret, cls)
            except Exception as e:
                logging.exception('failed to parse')
            return ret
        return _Fun
    return _fun

主要是为了对函数的返回值做解析并缓存

大概是这样用的

@Parser(Type, True)
def get_type(_id):
    ...

现在脑袋有点晕

3662 次点击
所在节点    Python
13 条回复
ligyxy
2015-07-27 21:26:09 +08:00
看看PEP上的例子就不晕了
gtv
2015-07-27 21:32:01 +08:00
len(arg) >= 1 可以优化为 if len?
gtv
2015-07-27 21:32:37 +08:00
说错了 if arg
gamexg
2015-07-27 22:12:11 +08:00
昨天也写了一个,也是缓存,不过我是在第二个函数内生成的cahce。
Python3 标准库自带了一个
julyclyde
2015-07-27 22:39:50 +08:00
没看懂调用方法……
Parser返回_fun,用_fun(cls)代替原cls?
hitsmaxft
2015-07-27 23:08:11 +08:00
足以见得python不支持匿名函数这个语法糖,非要偷懒用局部函数定义,是多么大的损失。
DeanThompson
2015-07-27 23:11:47 +08:00
julyclyde
2015-07-27 23:13:13 +08:00
@DeanThompson 我知道是decorator,但没见过这么厚的……想象力不够用了
bcxx
2015-07-27 23:13:50 +08:00
这种写法应该用 class 来代替的…… 重载 __call__ 方法就好了……

另外建议看看 pep8 ~,~
fatpa
2015-07-28 01:34:58 +08:00
不就是一装饰器么……………………
ffffwh
2015-07-28 09:33:31 +08:00
快去lambda神教洗洗脑
ryd994
2015-07-28 10:18:05 +08:00
外面两层可以lambda
yueyoum
2015-07-28 12:50:36 +08:00
1, PEP8
2, 多学学基础知识

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/208738

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX