推荐学习书目
Learn Python the Hard Way
Python Sites
PyPI - Python Package Index
http://diveintopython.org/toc/index.html
Pocoo
值得关注的项目
PyPy
Celery
Jinja2
Read the Docs
gevent
pyenv
virtualenv
Stackless Python
Beautiful Soup
结巴中文分词
Green Unicorn
Sentry
Shovel
Pyflakes
pytest
Python 编程
pep8 Checker
Styles
PEP 8
Google Python Style Guide
Code Style from The Hitchhiker's Guide
iptux
V2EX  ›  Python

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

  •  
  •   iptux · Jul 27, 2015 · 4760 views
    This topic created in 3969 days ago, the information mentioned may be changed or developed.
    # 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):
        ...
    

    现在脑袋有点晕

    13 replies    2015-07-28 12:50:36 +08:00
    ligyxy
        1
    ligyxy  
       Jul 27, 2015 via Android
    看看PEP上的例子就不晕了
    gtv
        2
    gtv  
       Jul 27, 2015
    len(arg) >= 1 可以优化为 if len?
    gtv
        3
    gtv  
       Jul 27, 2015
    说错了 if arg
    gamexg
        4
    gamexg  
       Jul 27, 2015 via Android
    昨天也写了一个,也是缓存,不过我是在第二个函数内生成的cahce。
    Python3 标准库自带了一个
    julyclyde
        5
    julyclyde  
       Jul 27, 2015
    没看懂调用方法……
    Parser返回_fun,用_fun(cls)代替原cls?
    hitsmaxft
        6
    hitsmaxft  
       Jul 27, 2015 via iPhone
    足以见得python不支持匿名函数这个语法糖,非要偷懒用局部函数定义,是多么大的损失。
    DeanThompson
        7
    DeanThompson  
       Jul 27, 2015
    julyclyde
        8
    julyclyde  
       Jul 27, 2015
    @DeanThompson 我知道是decorator,但没见过这么厚的……想象力不够用了
    bcxx
        9
    bcxx  
       Jul 27, 2015
    这种写法应该用 class 来代替的…… 重载 __call__ 方法就好了……

    另外建议看看 pep8 ~,~
    fatpa
        10
    fatpa  
       Jul 28, 2015
    不就是一装饰器么……………………
    ffffwh
        11
    ffffwh  
       Jul 28, 2015
    快去lambda神教洗洗脑
    ryd994
        12
    ryd994  
       Jul 28, 2015 via Android
    外面两层可以lambda
    yueyoum
        13
    yueyoum  
       Jul 28, 2015
    1, PEP8
    2, 多学学基础知识
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   1235 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 63ms · UTC 17:33 · PVG 01:33 · LAX 10:33 · JFK 13:33
    ♥ Do have faith in what you're doing.