Black是一個(gè)兼容PEP-8、零妥協(xié)的Python代碼格式化工具。使用它,你將欣然同意放棄對(duì)手動(dòng)格式化細(xì)節(jié)的控制。作為回報(bào),Black將回饋你速度、準(zhǔn)確性并使你免于pycodestyle(一種Python代碼風(fēng)格檢查器,用于檢查Python代碼是否符合PEP-8規(guī)范)的困擾。你將節(jié)省時(shí)間和精力,專注于更重要的事情。
安裝了Black之后,只要檢測(cè)到不符合規(guī)范的代碼風(fēng)格,它便會(huì)自動(dòng)幫你重新格式化。就是這么簡(jiǎn)單粗暴!
目前,該項(xiàng)目在GitHub上已經(jīng)積累了27.8k的Star。
項(xiàng)目地址:https://github.com/psf/black
無(wú)論你在查看什么項(xiàng)目,Black風(fēng)格的代碼都是統(tǒng)一的。格式會(huì)在短時(shí)間內(nèi)變得一目了然,這樣你可以專注于內(nèi)容。Black產(chǎn)生盡可能小的差異,使得代碼審查速度更快。
如下為格式化之前的代碼。
from seven_dwwarfs import Grumpy, Happy, Sleepy, Bashful, Sneezy, Dopey, Docx = { 'a':37,'b':42,'c':927}x = 123456789.123456789E123456789if very_long_variable_name is not None and \ very_long_variable_name.field > 0 or \ very_long_variable_name.is_debug: z = 'hello '+'world'else: world = 'world' a = 'hello {}'.format(world) f = rf'hello {world}'if (thisand that): y = 'hello ''world'#FIXME: https://github.com/psf/black/issues/26class Foo ( object ): def f (self ): return 37*-2 def g(self, x,y=42): return ydef f ( a: List[ int ]) : return 37-a[42-u : y**3]def very_important_function(template: str,*variables,file: os.PathLike,debug:bool=False,): '''Applies `variables` to the `template` and writes to `file`.''' with open(file, 'w') as f: ...# fmt: offcustom_formatting = [ 0, 1, 2, 3, 4, 5, 6, 7, 8,]# fmt: onregular_formatting = [ 0, 1, 2, 3, 4, 5, 6, 7, 8,]
如下為使用Black 22.3.0進(jìn)行格式化后,可以看到代碼變得清爽舒適了很多。
from seven_dwwarfs import Grumpy, Happy, Sleepy, Bashful, Sneezy, Dopey, Docx = {'a': 37, 'b': 42, 'c': 927}x = 123456789.123456789e123456789if ( very_long_variable_name is not None and very_long_variable_name.field > 0 or very_long_variable_name.is_debug): z = 'hello ' + 'world'else: world = 'world' a = 'hello {}'.format(world) f = rf'hello {world}'if this and that: y = 'hello ' 'world' # FIXME: https://github.com/psf/black/issues/26class Foo(object): def f(self): return 37 * -2 def g(self, x, y=42): return ydef f(a: List[int]): return 37 - a[42 - u : y**3]def very_important_function( template: str, *variables, file: os.PathLike, debug: bool = False,): '''Applies `variables` to the `template` and writes to `file`.''' with open(file, 'w') as f: ...# fmt: offcustom_formatting = [ 0, 1, 2, 3, 4, 5, 6, 7, 8,]# fmt: onregular_formatting = [ 0, 1, 2, 3, 4, 5, 6, 7, 8,]
安裝
你可以運(yùn)行pip install black安裝。Python版本需要3.6.2及以上。如果你想在Jupyter Notebooks中格式化代碼,則可以通過運(yùn)行pip install 'black[jupyter]'安裝。
你也可以從GitHub中直接安裝,具體命令如下。
pip install git+https://github.com/psf/black
使用
通過如下合理默認(rèn)值立即開始。
black {source_file_or_directory}
當(dāng)你無(wú)法作為腳本運(yùn)行Black時(shí),可以將它作為包運(yùn)行。
python -m black {source_file_or_directory}
目前,Black已經(jīng)成功地被很多大小項(xiàng)目使用。Black擁有齊全的測(cè)試套件、高效的并行測(cè)試以及作者自己的自動(dòng)格式化和并行持續(xù)集成運(yùn)行器。隨著Black變得越來越穩(wěn)定,未來不會(huì)再有大的格式變化了。風(fēng)格上的變化很大程度上是對(duì)bug報(bào)告的小修小補(bǔ)以及支持新的Python語(yǔ)法。
此外,作為一個(gè)放緩處理速度的安全措施,Black將檢查重新格式化后的代碼是否依然生成與原始代碼等效的有效AST。如果你有信心,盡情使用--fast。
聯(lián)系客服