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

https://github.com/messense/optionaldict

  •  
  •   messense ·
    messense · May 9, 2015 · 3306 views
    This topic created in 4156 days ago, the information mentioned may be changed or developed.

    写类似下面的代码真的是 pain in ass:

    def test(a, b, c=None, d=None, e=None):
        ret = {
            'a': a,
            'b': b,
        }
        if c is not None:
            ret['c'] = c
        if d is not None:
            ret['d'] = d
        if e is not None:
            ret['e'] = e
        return ret
    

    使用 optionaldict 就清爽多啦:

    from optionaldict import optionaldict
    
    
    def test(a, b, c=None, d=None, e=None):
        ret = optionaldict(
            a=a,
            b=b,
            c=c,
            d=d,
            e=e
        )
        return ret
        # or if you prefer to return a built-in dict object:
        # return dict(ret)
    
    5 replies  •  2015-05-09 14:57:05 +08:00
    loading
        1
    loading  
       May 9, 2015
    很多时候,我们需要的是更多的判断,这个一般与具体业务有关,基本每一个都会不同,所以,我个人认为,您这也是挺疼的。

    ps:我指的是用户 post 来的数据。
    messense
        2
    messense  
    OP
       May 9, 2015
    @loading 哈哈,其实用户 post 来的数据我是用 JSON Schema 来校验的,不用那么蛋疼。倒是写一些 SDK 啊经常有一些参数可选蛮蛋疼。
    fy
        3
    fy  
       May 9, 2015
    这个挺好的,不过我一般都是先加进去,然后for in,如果遇到空值就del掉。

    让我更蛋疼的一个是我希望py可以从语法上原生支持有序字典,每次读一个json格式全乱了很蛋疼啊
    fy
        5
    fy  
       May 9, 2015
    @zhyu 我早已知道有这个类,但并没有与之匹配的原生语法支持。
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Privacy   ·   Solana   ·   944 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 35ms · UTC 19:06 · PVG 03:06 · LAX 12:06 · JFK 15:06
    ♥ Do have faith in what you're doing.