亚洲中字慕日产2020,大陆极品少妇内射AAAAAA,无码av大香线蕉伊人久久,久久精品国产亚洲av麻豆网站

資訊專欄INFORMATION COLUMN

PyCharm使用autopep8按PEP8風(fēng)格自動(dòng)排版Python代碼

Sanchi / 3914人閱讀

摘要:應(yīng)該提供一種,且最好只提供一種,一目了然的解決方案當(dāng)然這是沒(méi)法一蹴而就的,除非你是荷蘭人固然,立刻著手好過(guò)永遠(yuǎn)不做。簡(jiǎn)而言之就是整個(gè)項(xiàng)目周期中越早暴露的問(wèn)題,其修復(fù)成本越低本文作者解釋說(shuō)這里的荷蘭人指的是的作者

前言

autopep8是一個(gè)將Python代碼自動(dòng)排版為PEP8風(fēng)格的小工具。它使用pep8工具來(lái)決定代碼中的哪部分需要被排版。autopep8可以修復(fù)大部分pep8工具中報(bào)告的排版問(wèn)題。

PyCharm使用autopep8按PEP8風(fēng)格自動(dòng)排版Python代碼
更新記錄

2018年12月27日 - 初稿

閱讀原文 - https://wsgzao.github.io/post...

擴(kuò)展閱讀

autopep8 - https://pypi.python.org/pypi/...

autopep8簡(jiǎn)介
使用 autopep8 前我們有必要先了解下 PEP 8 -- Style Guide for Python Code

autopep8 automatically formats Python code to conform to the PEP 8 style guide. It uses the pycodestyle utility to determine what parts of the code needs to be formatted. autopep8 is capable of fixing most of the formatting issues that can be reported by pycodestyle.

https://www.python.org/dev/pe...

https://pypi.python.org/pypi/...

安裝和使用autopep8

autopep8是一個(gè)開(kāi)源的命令行工具,它能夠?qū)ython代碼自動(dòng)格式化為PEP8風(fēng)格。autopep8使用pycodestyle工具來(lái)決定代碼中的哪部分需要被格式化,這能夠修復(fù)大部分pycodestyle工具中報(bào)告的排版問(wèn)題。autopep8本身也是一個(gè)Python語(yǔ)言編寫(xiě)的工具,因此,我們可以直接使用pip進(jìn)行安裝:

pip install autopep8
autopep8 --in-place optparse.py 

# To modify a file in place (with aggressive level 2):
autopep8 --in-place --aggressive --aggressive 

usage: autopep8 [-h] [--version] [-v] [-d] [-i] [--global-config filename]
                [--ignore-local-config] [-r] [-j n] [-p n] [-a]
                [--experimental] [--exclude globs] [--list-fixes]
                [--ignore errors] [--select errors] [--max-line-length n]
                [--line-range line line] [--hang-closing] [--exit-code]
                [files [files ...]]

Automatically formats Python code to conform to the PEP 8 style guide.

positional arguments:
  files                 files to format or "-" for standard in

optional arguments:
  -h, --help            show this help message and exit
  --version             show program"s version number and exit
  -v, --verbose         print verbose messages; multiple -v result in more
                        verbose messages
  -d, --diff            print the diff for the fixed source
  -i, --in-place        make changes to files in place
  --global-config filename
                        path to a global pep8 config file; if this file does
                        not exist then this is ignored (default:
                        ~/.config/pep8)
  --ignore-local-config
                        don"t look for and apply local config files; if not
                        passed, defaults are updated with any config files in
                        the project"s root directory
  -r, --recursive       run recursively over directories; must be used with
                        --in-place or --diff
  -j n, --jobs n        number of parallel jobs; match CPU count if value is
                        less than 1
  -p n, --pep8-passes n
                        maximum number of additional pep8 passes (default:
                        infinite)
  -a, --aggressive      enable non-whitespace changes; multiple -a result in
                        more aggressive changes
  --experimental        enable experimental fixes
  --exclude globs       exclude file/directory names that match these comma-
                        separated globs
  --list-fixes          list codes for fixes; used by --ignore and --select
  --ignore errors       do not fix these errors/warnings (default:
                        E226,E24,W50,W690)
  --select errors       fix only these errors/warnings (e.g. E4,W)
  --max-line-length n   set maximum allowed line length (default: 79)
  --line-range line line, --range line line
                        only fix errors found within this inclusive range of
                        line numbers (e.g. 1 99); line numbers are indexed at
                        1
  --hang-closing        hang-closing option passed to pycodestyle
  --exit-code           change to behavior of exit code. default behavior of
                        return value, 0 is no differences, 1 is error exit.
                        return 2 when add this option. 2 is exists
                        differences.

--in-place類似于sed命令的-i選項(xiàng),如果不包含--in-place選項(xiàng),則會(huì)將autopep8格式化以后的代碼直接輸出到控制臺(tái)。我們可以使用這種方式檢查autopep8的修改,使用--in-place則會(huì)直接將結(jié)果保存到源文件中。

我們來(lái)看一個(gè)完整的例子,本例中使用的代碼如下:

import os, sys  
 
def main():  
    print [item for item in os.listdir(".") if item.endswith(".py")];  
    print sys.version  
 
if __name__ == "__main__":  
    main() 

這段代碼存在三個(gè)問(wèn)題:

導(dǎo)入的時(shí)候,應(yīng)該每一行只導(dǎo)入一個(gè)包;

包導(dǎo)入和函數(shù)定義之間應(yīng)該空兩行;

Python代碼末尾不需要分號(hào)。

接下來(lái),我們將使用pycodestyple檢查這段代碼,然后使用autopep8將代碼格式化成符合PEP 8風(fēng)格的代碼。

使用pycodestyle檢查代碼可檢測(cè)到代碼中有三個(gè)地方不符合PEP 8規(guī)范,如下所示:

pycodestyle hello.py  
hello.py:1:10: E401 multiple imports on one line  
hello.py:3:1: E302 expected 2 blank lines, found 1  
hello.py:4:69: E703 statement ends with a semicolon 

使用autopep8格式能夠轉(zhuǎn)換Python代碼。在這個(gè)例子中,autopep8順利地幫我們修復(fù)了所有問(wèn)題,如下所示:

$ autopep8 hello.py  
import os  
import sys  
 
 
def main():  
    print [item for item in os.listdir(".") if item.endswith(".py")]  
    print sys.version  
 
 
if __name__ == "__main__":  
    main() 

這個(gè)時(shí)候如果查看源文件的話,會(huì)發(fā)現(xiàn)還是和原來(lái)一樣,并沒(méi)有修正為符合PEP 8規(guī)范的代碼。前面說(shuō)過(guò),不指定--in-place選項(xiàng),只會(huì)將結(jié)果輸出到命令行。如果我們使用--in-place選項(xiàng),將不會(huì)有任何輸出,autopep8會(huì)直接修改源文件。

$ autopep8 --in-place hello.py 

autopep8還存在--aggressive選項(xiàng),使用該選項(xiàng)會(huì)執(zhí)行更多實(shí)質(zhì)性的更改,可以多次使用以達(dá)到更佳的效果。

以官網(wǎng)為例我們編寫(xiě)一個(gè)test_autopep8.py

Before running autopep8.
import math, sys;

def example1():
    ####This is a long comment. This should be wrapped to fit within 72 characters.
    some_tuple=(   1,2, 3,"a"  );
    some_variable={"long":"Long code lines should be wrapped within 79 characters.",
    "other":[math.pi, 100,200,300,9876543210,"This is a long string that goes on"],
    "more":{"inner":"This whole logical line should be wrapped.",some_tuple:[1,
    20,300,40000,500000000,60000000000000000]}}
    return (some_tuple, some_variable)
def example2(): return {"has_key() is deprecated":True}.has_key({"f":2}.has_key(""));
class Example3(   object ):
    def __init__    ( self, bar ):
     #Comments should have a space after the hash.
     if bar : bar+=1;  bar=bar* bar   ; return bar
     else:
                    some_string = """
                       Indentation in multiline strings should not be touched.
Only actual code should be reindented.
"""
                    return (sys.path, some_string)
After running autopep8.
import math
import sys


def example1():
    # This is a long comment. This should be wrapped to fit within 72
    # characters.
    some_tuple = (1, 2, 3, "a")
    some_variable = {
        "long": "Long code lines should be wrapped within 79 characters.",
        "other": [
            math.pi,
            100,
            200,
            300,
            9876543210,
            "This is a long string that goes on"],
        "more": {
            "inner": "This whole logical line should be wrapped.",
            some_tuple: [
                1,
                20,
                300,
                40000,
                500000000,
                60000000000000000]}}
    return (some_tuple, some_variable)


def example2(): return ("" in {"f": 2}) in {"has_key() is deprecated": True}


class Example3(object):
    def __init__(self, bar):
        # Comments should have a space after the hash.
        if bar:
            bar += 1
            bar = bar * bar
            return bar
        else:
            some_string = """
                       Indentation in multiline strings should not be touched.
Only actual code should be reindented.
"""
            return (sys.path, some_string)
autopep8可以修復(fù)的問(wèn)題
autopep8 fixes the following issues reported by pycodestyle:

https://github.com/PyCQA/pyco...

E101 - Reindent all lines.
E11  - Fix indentation.
E121 - Fix indentation to be a multiple of four.
E122 - Add absent indentation for hanging indentation.
E123 - Align closing bracket to match opening bracket.
E124 - Align closing bracket to match visual indentation.
E125 - Indent to distinguish line from next logical line.
E126 - Fix over-indented hanging indentation.
E127 - Fix visual indentation.
E128 - Fix visual indentation.
E129 - Fix visual indentation.
E131 - Fix hanging indent for unaligned continuation line.
E133 - Fix missing indentation for closing bracket.
E20  - Remove extraneous whitespace.
E211 - Remove extraneous whitespace.
E22  - Fix extraneous whitespace around keywords.
E224 - Remove extraneous whitespace around operator.
E225 - Fix missing whitespace around operator.
E226 - Fix missing whitespace around arithmetic operator.
E227 - Fix missing whitespace around bitwise/shift operator.
E228 - Fix missing whitespace around modulo operator.
E231 - Add missing whitespace.
E241 - Fix extraneous whitespace around keywords.
E242 - Remove extraneous whitespace around operator.
E251 - Remove whitespace around parameter "=" sign.
E252 - Missing whitespace around parameter equals.
E26  - Fix spacing after comment hash for inline comments.
E265 - Fix spacing after comment hash for block comments.
E266 - Fix too many leading "#" for block comments.
E27  - Fix extraneous whitespace around keywords.
E301 - Add missing blank line.
E302 - Add missing 2 blank lines.
E303 - Remove extra blank lines.
E304 - Remove blank line following function decorator.
E305 - Expected 2 blank lines after end of function or class.
E306 - Expected 1 blank line before a nested definition.
E401 - Put imports on separate lines.
E402 - Fix module level import not at top of file
E501 - Try to make lines fit within --max-line-length characters.
E502 - Remove extraneous escape of newline.
E701 - Put colon-separated compound statement on separate lines.
E70  - Put semicolon-separated compound statement on separate lines.
E711 - Fix comparison with None.
E712 - Fix comparison with boolean.
E713 - Use "not in" for test for membership.
E714 - Use "is not" test for object identity.
E721 - Use "isinstance()" instead of comparing types directly.
E722 - Fix bare except.
E731 - Use a def when use do not assign a lambda expression.
W291 - Remove trailing whitespace.
W292 - Add a single newline at the end of the file.
W293 - Remove trailing whitespace on blank line.
W391 - Remove trailing blank lines.
W503 - Fix line break before binary operator.
W504 - Fix line break after binary operator.
W601 - Use "in" rather than "has_key()".
W602 - Fix deprecated form of raising exception.
W603 - Use "!=" instead of "<>"
W604 - Use "repr()" instead of backticks.
W605 - Fix invalid escape sequence "x".
W690 - Fix various deprecated code (via lib2to3).
Pycharm安裝autopep8

pip安裝autopep8: pip install autopep8

PyCharm -> Preferences -> Tools -> Extends Tools -> 點(diǎn)擊+加號(hào)

Name: autopep8
Tools settings:

Programs: autopep8

Parameters: --in-place --aggressive --aggressive $FilePath$

Working directory: $ProjectFileDir$

Advanced Options -> Output Filters: $FILE_PATH$:$LINE$:$COLUMN$:.*

Python之禪
最后以Python之禪作為結(jié)束語(yǔ)
 wangao@wangao-MAC  ~  python3
Python 3.7.1 (default, Nov  6 2018, 18:46:03)
[Clang 10.0.0 (clang-1000.11.45.5)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import this
The Zen of Python, by Tim Peters

Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren"t special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one-- and preferably only one --obvious way to do it.
Although that way may not be obvious at first unless you"re Dutch.
Now is better than never.
Although never is often better than *right* now.
If the implementation is hard to explain, it"s a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea -- let"s do more of those!
翻譯

美 優(yōu)于 丑

明確 優(yōu)于 隱晦 (1)

簡(jiǎn)單 優(yōu)于 復(fù)雜

復(fù)雜 也好過(guò) 繁復(fù) (2)

扁平 優(yōu)于 嵌套

稀疏 優(yōu)于 擁擠

可讀性很重要(3)

固然代碼實(shí)用與否 比潔癖更重要,

我們以為的特例也往往沒(méi)有特殊到必須打破上述規(guī)則的程度

除非刻意地靜默,

否則不要無(wú)故忽視異常(4)

如果遇到模棱兩可的邏輯,請(qǐng)不要自作聰明地瞎猜。

應(yīng)該提供一種,且最好只提供一種,一目了然的解決方案

當(dāng)然這是沒(méi)法一蹴而就的,除非你是荷蘭人(5)

固然,立刻著手 好過(guò) 永遠(yuǎn)不做。

然而,永遠(yuǎn)不做 也好過(guò) 不審慎思考一擼袖子就莽著干

如果你的實(shí)現(xiàn)很難解釋,它就一定不是個(gè)好主意

即使你的實(shí)現(xiàn)簡(jiǎn)單到爆,它也有可能是個(gè)好辦法

命名空間大法好,不搞不是地球人!

注釋

該引入的包一個(gè)一個(gè)列出來(lái)不要合并;不要用星號(hào);不要在方法里藏意想不到的的副作用,等等等等。還一個(gè)例子,另外一種著名的軟件設(shè)計(jì)原則 Convention over Configuration(約定優(yōu)于配置)如果做得不謹(jǐn)慎就會(huì)違背這條

SO: 必要的復(fù)雜邏輯是難免的,而繁復(fù)啰嗦的代碼是不可接受的

Readability counts 不能翻譯成可讀性計(jì)數(shù)啊喂

實(shí)操中很多人不注意 catch 完就 log 一下 就不管了,這樣不好。軟件界一般都講 Let it fail,學(xué)名為 Fail-fast 法則。簡(jiǎn)而言之就是整個(gè)項(xiàng)目周期中越早暴露的問(wèn)題,其修復(fù)成本越低

本文作者 Tim peters 解釋說(shuō)這里的荷蘭人指的是 Python 的作者 Guido van Rossum

文章版權(quán)歸作者所有,未經(jīng)允許請(qǐng)勿轉(zhuǎn)載,若此文章存在違規(guī)行為,您可以聯(lián)系管理員刪除。

轉(zhuǎn)載請(qǐng)注明本文地址:http://www.ezyhdfw.cn/yun/42883.html

相關(guān)文章

  • Pycharm配置autopep8教程,讓Python代碼更符合pep8規(guī)范

    摘要:一何為官方文檔中文翻譯轉(zhuǎn)二中配置本身是有風(fēng)格檢測(cè)的,當(dāng)你敲得代碼中不符合規(guī)范時(shí),會(huì)有下劃波浪線提示。如下圖所示最后博客鏈接翔參考機(jī)器學(xué)習(xí)入門(mén)安裝 一、何為pep8? PEP 8官方文檔 -- Style Guide for Python Code PEP8中文翻譯(轉(zhuǎn)) 二、Pycharm中配置pep8 Pycharm本身是有pep8風(fēng)格檢測(cè)的,當(dāng)你敲得代碼中不符合規(guī)范時(shí),會(huì)有下劃...

    tuantuan 評(píng)論0 收藏0
  • Emacs:最好的Python編輯器?

    摘要:這正是使用編輯器的基本形式。禁用啟動(dòng)消息即顯示所有教程信息的頁(yè)面。因此,只使用編輯器并且完美支持所有這些語(yǔ)言將會(huì)大大提高工作效率。結(jié)語(yǔ)正如你所見(jiàn),明顯是最好的編輯器。 本文是realpython.com繼《將Sublime Text 3打造為Python全棧開(kāi)發(fā)環(huán)境及》和《Vim與Python真乃天作之合》,又一篇關(guān)于如何配置Python IDE的文章。這一次,主角變成了與Vim同樣...

    Shimmer 評(píng)論0 收藏0
  • sublime text3配置<python篇>

    摘要:選中一個(gè)后,按此快捷鍵可以同時(shí)選中另一個(gè),同時(shí)多了另一個(gè)光標(biāo)在下面新開(kāi)一行在上面新開(kāi)一行刪除整行。向左單位性地移動(dòng)光標(biāo),快速移動(dòng)光標(biāo)。開(kāi)啟關(guān)閉側(cè)邊欄。插件能為提供括號(hào),引號(hào)這類高亮功能。用來(lái)安裝其官網(wǎng)上的所有主題。 古語(yǔ)有云,工欲善其事必先利其器。選擇一個(gè)好的工具,往往事半功倍。因?yàn)閭€(gè)人電腦原因,用 pycharm 太卡,所以想起了 sublime text,配置了一下,覺(jué)得挺好用。 ...

    陳江龍 評(píng)論0 收藏0
  • PyCharm使用心得

    摘要:我不是個(gè)偉大的程序員,我只是個(gè)有著一些優(yōu)秀習(xí)慣的好程序員更新記錄年月日初稿閱讀原文擴(kuò)展閱讀購(gòu)買(mǎi)和使用的產(chǎn)品大多數(shù)是付費(fèi)形式,但是對(duì)于教育行業(yè)卻實(shí)行免費(fèi)授權(quán)計(jì)劃,幾乎涵蓋所有產(chǎn)品,十分良心。 前言 PyCharm是大JB旗下的產(chǎn)品之一,對(duì)于廣大Python開(kāi)發(fā)者來(lái)說(shuō)應(yīng)該不會(huì)陌生,對(duì)于個(gè)人開(kāi)發(fā)者來(lái)說(shuō)用什么IDE(VIM/Sublime Text/Visual Studio Code)可能并...

    Chiclaim 評(píng)論0 收藏0
  • Sublime Text3配置使用教程整理

    摘要:安裝完添加如下配置可自動(dòng)在保存文件的時(shí)候格式化中文輸入法不能跟隨光標(biāo)嗎試試這個(gè)插件吧目前只支持和裝完之后,寫(xiě)作時(shí)右下角顯示語(yǔ)法為,可以按,直接就會(huì)生成,并在瀏覽器中顯示。 Win平臺(tái)上已經(jīng)打造了便攜版的Sublime Text3,但是,現(xiàn)在折騰Ubuntu不能同步過(guò)來(lái)使用了,寒假在家休息,整理一下安裝過(guò)程好了: 安裝sublime 在sublime text官網(wǎng)選擇合適的版本安裝。 u...

    Martin91 評(píng)論0 收藏0

發(fā)表評(píng)論

0條評(píng)論

最新活動(dòng)
閱讀需要支付1元查看
<