V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
推荐学习书目
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 · 2015-05-09 12:03:31 +08:00 · 2542 次点击
    这是一个创建于 3296 天前的主题,其中的信息可能已经有所发展或是发生改变。

    写类似下面的代码真的是 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 条回复    2015-05-09 14:57:05 +08:00
    loading
        1
    loading  
       2015-05-09 12:19:22 +08:00
    很多时候,我们需要的是更多的判断,这个一般与具体业务有关,基本每一个都会不同,所以,我个人认为,您这也是挺疼的。

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

    让我更蛋疼的一个是我希望py可以从语法上原生支持有序字典,每次读一个json格式全乱了很蛋疼啊
    fy
        5
    fy  
       2015-05-09 14:57:05 +08:00
    @zhyu 我早已知道有这个类,但并没有与之匹配的原生语法支持。
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   实用小工具   ·   1262 人在线   最高记录 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 29ms · UTC 23:39 · PVG 07:39 · LAX 16:39 · JFK 19:39
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.