Ubuntu22.04下vscode安装python代码格式化(Format Document)black模块及设置
相关:
如何在vscode中支持python的annotation(注解,type checking)——通过设置pylance参数实现python注解的type checking
ubuntu22.04系统环境下使用vs code安装pylint检查python的代码错误
pylance是检查并发现coding中的错误。
pylint是检查代码格式是否规范并给出提示,而代码格式化工具如black是对不规范风格的代码进行自动修改,这两个工具一个是发现不规范的地方,一个是对不规范的地方进行修改,但是要知道的一点是这两个工具在使用时是没有任何关联的。
=================================================
在vscode中,按键 ctrl+shift+p,打开命令框,打开user settings:
设置格式化的工具,这里设置为black:
执行格式化:
设置并安装好black后对于想要格式化的代码文件使用快捷键,ctrl+shift+i,便可格式化。
不同操作系统下vscode的格式化快捷键并不同,这里给出linux系统下的快捷键链接:
https://code.visualstudio.com/shortcuts/keyboard-shortcuts-linux.pdf
===========================================
一个实例,下面的代码是没有格式化之前的:
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)
按键 ctrl+shift+i,后:
可以看到代码的格式变得好看了很多,这就是 格式化模块black的作用。其实,我个人是不建议使用代码格式化的,因为你在编写代码的时候就尽量遵照pep8的规范就好了,而这个代码格式化的工具都是在你写完代码后使用的,这种事后修补的方法还是不如事前修补。当然如果你是在企业里coding,因而需要遵照一定的代码格式自然可以使用代码格式化工具在代码写完后校验一下风格,这时候建议使用的代码格式化插件为yapf,这是Google的Python代码格式化程序,而个人coding的话还是在coding的时候就做好格式化是最好的了。
================================================
posted on 2022-07-02 13:32 Angry_Panda 阅读(2362) 评论(0) 编辑 收藏 举报
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步