推荐学习书目
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
guyskk
V2EX  ›  Python

如何简化下面这些代码,避免 copy?

  •  
  •   guyskk ·
    guyskk · Jul 7, 2016 · 3546 views
    This topic created in 3624 days ago, the information mentioned may be changed or developed.

    我需要写很多的校验函数,这些校验函数都有 default=None, optional=False, desc=None这几个参数。

    def int_validater(min=0, max=1024,
                      default=None, optional=False, desc=None):
        def validater(value):
            if value is None:
                if default is not None:
                    return default
                elif optional:
                    return None
                else:
                    raise Invalid("required")
            try:
                v = int(value)
            except ValueError:
                raise Invalid("invalid int")
            if v < min:
                raise Invalid("value must >= %d" % min)
            elif v > max:
                raise Invalid("value must <= %d" % max)
            return v
        return validater
    
    
    def bool_validater(default=None, optional=False, desc=None):
        def validater(value):
            if value is None:
                if default is not None:
                    return default
                elif optional:
                    return None
                else:
                    raise Invalid("required")
            if isinstance(value, bool):
                return value
            else:
                raise Invalid("invalid bool")
        return validater
    

    这些校验函数用法类似这样:

    validater = int_validater(0,10,default=5)
    validater(-1) # raise Invalid("value must >= %d" % min)
    validater(20) # raise Invalid("value must <= %d" % max)
    

    怎么简化代码,避免 copy? 我试了用装饰器,但是不能处理好参数顺序,装饰后的函数原型因该是下面这样:

    wraped_validater(default=None, optional=False, desc=None,*args,**kwargs)
    

    如果int_validater(0,10,default=5),这样 0 和 10 对应的是 optional 和 desc ,而不是*args 。

    10 replies    2016-07-08 10:49:37 +08:00
    am241
        1
    am241  
       Jul 7, 2016 via Android
    看前半段想说装饰器,结果被抢答否定了
    suber
        2
    suber  
       Jul 7, 2016 via iPhone
    你指定名字传参
    chevalier
        3
    chevalier  
       Jul 7, 2016   ❤️ 1
    有现成的轮子: voluptuous
    shyling
        4
    shyling  
       Jul 7, 2016 via Android   ❤️ 1
    不要用默认值的形式
    def func(*args,**kwargs)靠解析 args,kwargs 试试
    guyskk
        5
    guyskk  
    OP
       Jul 8, 2016
    @shyling 感谢,解决了

    ```
    def handle_default_optional_desc(some_validater):
    def wrapped_validater(*args, **kwargs):
    default = kwargs.pop("default", None)
    optional = kwargs.pop("optional", False)
    desc = kwargs.pop("desc", None)
    origin_validater = some_validater(*args, **kwargs)

    def validater(value):
    if value is None:
    if default is not None:
    return default
    elif optional:
    return None
    else:
    raise Invalid("required")
    return origin_validater(value)
    return validater

    return wrapped_validater
    ```
    guyskk
        6
    guyskk  
    OP
       Jul 8, 2016
    @guyskk 缩进全没了。。怎么贴代码啊
    ruanimal
        10
    ruanimal  
       Jul 8, 2016
    你这个需要多重装饰器。。
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   4156 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 40ms · UTC 05:19 · PVG 13:19 · LAX 22:19 · JFK 01:19
    ♥ Do have faith in what you're doing.