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

长代码(非字符串)如何满足 PEP8?

  •  
  •   flyaway · Jan 29, 2016 · 4336 views
    This topic created in 3786 days ago, the information mentioned may be changed or developed.

    一直很纠结对一些很长的列表表达式该如何改写使其满足 PEP8 的规范……比如如下代码:
    left_correct = sum([1 for ins in instances if self.is_acc(ins.left_label, ins.left_score)])

    直接拦腰砍断么……感觉很丑啊……

    16 replies    2016-02-01 09:10:08 +08:00
    billlee
        1
    billlee  
       Jan 29, 2016
    a_list = [a_long_expression(item)
           for item in another_list
           if another_expression(item)]
    flyaway
        2
    flyaway  
    OP
       Jan 29, 2016
    @billlee 这么砍貌似确实会好看一些……
    cxbig
        3
    cxbig  
       Jan 29, 2016
    - 拆成多行, assign 给多个变量
    - 用 alias 缩短长 fn/method
    xuboying
        4
    xuboying  
       Jan 29, 2016 via Android
    这种代码可读性好差
    ipconfiger
        5
    ipconfiger  
       Jan 29, 2016
    变量名起得长很容易就超标了.......
    raquelken
        6
    raquelken  
       Jan 29, 2016
    拆吧
    bigger_than_1 = lambda num: num > 1
    amount = len(filter(bigger_than_1, [1, 2, 3]))
    Delbert
        7
    Delbert  
       Jan 29, 2016
    @billlee 不应该是
    a_list = [a_long_expression(item) \
           for item in another_list \
           if another_expression(item)]
    么?
    flyaway
        8
    flyaway  
    OP
       Jan 30, 2016
    @xuboying 就是想知道如何写出可读性好的,且符合 pep8 规范的代码……
    fy
        9
    fy  
       Jan 30, 2016
    抓大放小,这种小细节就不必在意了,核心是可读性
    gkiwi
        10
    gkiwi  
       Jan 30, 2016
    觉的楼主的问题应该是,我写了不符合 pep8 规范的代码, pep8 检查器老报异常很烦人怎么办。。。
    这样子在需要的行后面加上 # noqa
    有图为证:
    gkiwi
        11
    gkiwi  
       Jan 30, 2016
    呃呃呃,图丢了,楼主自己 search 下 pep8 noqa 就晓得了~~
    gkiwi
        12
    gkiwi  
       Jan 30, 2016
    不过话说回来,对于特别长的表达式,还是换行是一种好的策略,毕竟代码是写给别人看的,阅读方便才是首要任务
    leavic
        13
    leavic  
       Jan 31, 2016
    you really need pycharm
    zjq426
        14
    zjq426  
       Jan 31, 2016
    拆行+1
    pynix
        15
    pynix  
       Feb 1, 2016
    ryd994
        16
    ryd994  
       Feb 1, 2016 via Android
    @Delbert 括号内会自动续行吧……
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   1049 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 63ms · UTC 22:45 · PVG 06:45 · LAX 15:45 · JFK 18:45
    ♥ Do have faith in what you're doing.