新世界大门
A Code linter, is a static code analysis tool used to flag programming errors, bugs, stylistic errors, and suspicious constructs. The term originates from a Unix utility that examined C language source code. Like Google, “lint” became a verb that meant static checking your source code.
Code linter是一个静态代码分析工具,用于标记编程错误,错误,样式错误和可疑结构。 该术语源自检查C语言源代码的Unix实用程序。 像Google一样,“ lint”成为动词,表示要静态检查源代码。
Everyone knows that programming errors are bad. Some errors cause glitches that frustrate users. Others compromise the safety and security of a critical system.
每个人都知道编程错误是不好的。 某些错误会导致使用户感到沮丧的故障。 其他则损害了关键系统的安全性。
Linting is an essential process and code linters are available across programming languages. In this blog, we will talk specifically about the Python Linter aka Pylint. Pylint checks your code against the norms stated in the styling guide for Python as stated in PEP-8.
整理是必不可少的过程,代码短绒可用于各种编程语言。 在这篇博客中,我们将会对Python的短绒又名具体谈pylint的。 Pylint按照PEP-8中规定的Python样式指南中规定的规范检查您的代码。
Pylint is a tool that checks for errors in Python code, tries to enforce a coding standard and looks for code smells. It can also look for certain type errors, it can recommend suggestions about how particular blocks can be refactored and can offer you details about the code’s complexity.
Pylint是一种工具,可检查Python代码中的错误,尝试实施编码标准并查找代码气味。 它还可以查找某些类型错误,可以建议有关如何重构特定块的建议,并可以为您提供有关代码复杂性的详细信息。
Pylint will display a number of messages as it analyzes the code and it can also be used for displaying some statistics about the number of warnings and errors found in different files. The messages are classified under various categories such as errors and warnings.
Pylint在分析代码时将显示许多消息,也可以用于显示有关在不同文件中发现的警告和错误数量的一些统计信息。 消息分为各种类别,例如错误和警告。
Last but not least, the code is given an overall mark, based on the number and severity of the warnings and errors
最后但并非最不重要的一点是,根据警告和错误的数量和严重性,对代码进行总体标记
Gates of Implementation: A check when performed at multiple stages ensures no leakage. However the rule book (we will talk about it in the later sections) applied to each stage must be the same to avoid conflicts. Performing Pylint Checks in multiple stages also avoids rework and last minute changes/deviations from deployments/releases.
实施G的茨:当在多个阶段执行的检查可确保无泄漏。 但是,应用于每个阶段的规则手册(我们将在后面的部分中进行讨论)必须相同,以避免冲突。 分多个阶段执行Pylint检查还可以避免返工以及从部署/发行版的最后一刻更改/偏差。
1: This stage is the closest to all the groundwork and forms the first layer of straining your code against the quality filter. Pycharm stays the undebatable and undefeated champion of all the editors out there for Python. Integration of Pylint with Pycharm eases the lint checks with just the click of a button.
1 :此阶段是所有基础工作中最接近的阶段,它构成了使代码对质量过滤器产生压力的第一层。 Pycharm仍然是所有Python编辑器中无可争议的,不败的冠军。 Pylint与Pycharm的集成只需单击一个按钮即可简化皮棉检查。
As and when you keep building your code, you should get habituated with the check-as-you-go way of running checks. For that, let’s leverage the “External Tool” feature of the editor. The steps to integrate Pylint in the editor have been beautifully shared in one of the stack overflow answers.
当您继续构建代码时,您应该习惯于使用检查时的检查方式来运行检查。 为此,让我们利用编辑器的“外部工具”功能。 在堆栈溢出答案之一中,漂亮地共享了将Pylint集成到编辑器中的步骤。
You can set up pylint to work with PyCharm by following the next steps:
您可以按照以下步骤设置pylint与PyCharm一起使用:
Install pylint:
安装pylint:
$ pip install pylintLocate your pylint installation folder:
找到您的pylint安装文件夹:
$ which pylint # MacOS/Linux/usr/local/bin/pylint # this is just a possible output check yours$ where pylint # Windows %LocalAppData%\Programs\Python\Python36–32\Scripts\pylint.exe # possible locationOpen the PyCharm settings window with File -> Settings, then navigate to Tools -> External Tools in the sidebar. (Or search “external tools”)
使用File-> Settings打开PyCharm设置窗口,然后导航至侧栏中的Tools-> External Tools 。 (或搜索“外部工具”)
Setup an external tool by clicking on the + sign and filling the fields accordingly. In Program use the path you got when running which pylint, for the other values you can use the same of the image.
通过单击+号并相应地填充字段来设置外部工具。 在“程序”中,使用运行哪个pylint时获得的路径,对于其他值,您可以使用相同的图像。
To run pylint from Tools -> External Tools -> pylint:
要运行pylint从Tools -> External Tools -> pylint :
Look your output in the PyCharm terminal:
在PyCharm终端中查看输出:
2: The second gate enforces the 1st level of governance in the code quality. This gate prevents a developer from contributing any code (having lints) to the GIT repository. Git has various web-hooks that eases the development efforts. For the code linter, we will be using the pre-commit hook. It’s a simple script that gets triggered prior to any commit event.
2 :第二道门强制执行代码质量的第一级治理。 此门可防止开发人员向GIT存储库贡献任何代码(有棉绒)。 Git有各种Web挂钩,可简化开发工作。 对于代码linter,我们将使用pre-commit钩子。 这是一个简单的脚本,可在任何提交事件之前触发。
The pre-commit hook is run first, before you even type in a commit message. It’s used to inspect the snapshot that’s about to be committed, to see if you’ve forgotten something, to make sure tests run, or to examine whatever you need to inspect in the code. Exiting non-zero from this hook aborts the commit, although you can bypass it with git commit --no-verify. You can do things like check for code style (run lint or something equivalent), check for trailing whitespace (the default hook does exactly this), or check for appropriate documentation on new methods.
甚至在键入提交消息之前,都会先运行pre-commit挂钩。 它用于检查将要提交的快照,查看是否忘记了某些内容,确保测试能够运行或检查代码中需要检查的内容。 尽管可以使用git commit --no-verify绕过它,但从该挂钩中退出非零值会中止提交。 您可以执行以下操作,例如检查代码样式(运行lint或其他等效方法),检查结尾的空格(默认的钩子完全做到这一点)或检查有关新方法的适当文档。
A sample pre-commit hook for running Pylint has been shared here by Nick Fitzgerald. I recommend modifying this sample script slightly by implementing Python Argument Parser to enable dynamic value fetching from user instead of hard coding it within the code. For ex: you can set a default pass rank for the pylint checks while allowing the user to pass a value which would override the defaults. It also helps to choose the pylintrc file from the user if the need be.
Nick Fitzgerald在此共享了一个用于运行Pylint的预提交挂钩示例。 我建议通过实现Python Argument Parser稍微修改此示例脚本,以使能从用户获取动态值,而不是在代码中对其进行硬编码。 例如:您可以为pylint检查设置默认的通过等级,同时允许用户传递将覆盖默认值的值。 如果需要,它也有助于从用户选择pylintrc文件。
So far, we saw the gates that help us in implementing and governing the lint checks, however these 2 steps are totally dependent on a user/developer as it becomes their sole responsibility to implement the quality filters.
到目前为止,我们已经看到了帮助我们实施和管理皮棉检查的门,但是,这两个步骤完全取决于用户/开发人员,因为实施质量过滤器是他们的唯一责任。
Hence, the 3rd gate. This gate forms the final gate which strictly enforces the checks and cannot be bypassed.
因此,第三个门。 此门形成最终门,该门严格执行检查并且不能被绕过。
3: The integration of pylint checks with the CI/CD pipeline forms the bulletproof shield against quality compromises. Run the linter within your CI pipeline (set to trigger by a Pull Request) and pass/fail the Pipeline based on the results of the lint checks, thereby prohibiting the succession of your code from lower to higher branches (feature -> dev, dev -> master, etc).
3 :pylint检查与CI / CD管道的集成形成了防弹罩,可防止质量受损。 在CI管道中运行linter(设置为由“拉取请求”触发),并根据lint检查的结果通过/失败管道,从而禁止将代码从低级分支转移到高级分支(功能-> dev,dev ->大师等)。
For my demonstration, I am using CodeFresh to orchestrate the CI pipeline. In the below example, I am building a Python package and publishing it to a artifactory manager, JFROG. This pipeline is triggered whenever there is a Pull Request raised from feature branch to dev branch and the results are sent back to Git using a service hook registered between Codefresh and Git.
为了演示,我使用CodeFresh来编排CI管道。 在下面的示例中,我将构建一个Python包并将其发布到工件管理器JFROG 。 每当从功能分支到开发分支引发“拉取请求”时,都会触发此管道,并使用在Codefresh和Git之间注册的服务挂钩将结果发送回Git。
Hence, the reviewer can refer the automated checks before proceeding with the actions to be taken on the Pull Request. You can also set the build of CI pipeline to be triggered upon the merging of a PR, totally depends on you!
因此,审阅者可以在继续对拉取请求采取的操作之前参考自动检查。 您还可以将CI管道的构建设置为在PR合并时触发,这完全取决于您!
You would have noticed that I mentioned “pylintrc” a few times so far. This is the rule book that I mentioned at the beginning of this blog. It’s a config file for the pylint that states the various checks to be performed/skipped explicitly by deviating from generic PEP-8.
您可能已经注意到,到目前为止,我几次提到“ pylintrc”。 这是我在本博客开头提到的规则手册。 这是pylint的配置文件,该文件指出了与常规PEP-8有所不同的各种要明确执行/跳过的检查。
For ex: PEP-8, states that the max length of a line to be limited to 79 chars:
例如:PEP-8,指出一行的最大长度限制为79个字符:
Limit all lines to a maximum of 79 characters. For flowing long blocks of text with fewer structural restrictions (docstrings or comments), the line length should be limited to 72 characters.
限制所有行最多79个字符。 为了使较长的文本块具有较少的结构限制(文档字符串或注释),行长应限制为72个字符。
However, most of the teams/projects consider this unnecessary and are fine with limiting the line length to 100/120 characters. This override must be specified in the pylintrc file as:
但是,大多数团队/项目都认为这是不必要的,并且可以将行长限制为100/120个字符。 必须在pylintrc文件中将以下替代指定为:
[FORMAT]max-line-length=100Similarly, if you want to skip checking for Module doc-strings along with the above specification, the pylintrc would look as:
类似地,如果您要跳过对模块文档字符串以及上述规范的检查,则pylintrc将如下所示:
[FORMAT]max-line-length=100[MASTER]disable= C0114, # missing-module-docstringYou can generate a default rc file by using the pylint flag --generate-rcfile and set the overrides as required.
您可以使用pylint标志--generate-rcfile生成默认的rc文件,并根据需要设置替代值。
pylint --generate-rcfile > .pylintrcAlternatively, there are a lot of predefined pylintrc file available as open source. Feel free to refer any of those and tweak them according to your use case.
另外,有许多预定义的pylintrc文件可用作开源。 随意引用其中任何一个,并根据您的用例进行调整。
Invoking Pylint with a specific pylintrc file should be done as below:
使用特定的pylintrc文件调用Pylint的操作应如下:
pylint --rcfile <PATH_TO_RC_FILE> <PATH_TO_PY_MODULE/FILE>One of my favorite quotes on computer programming:
我最喜欢的计算机编程引述之一:
Any fool can write code that a computer can understand. Good programmers write code that humans can understand.
任何傻瓜都可以编写计算机可以理解的代码。 好的程序员编写人类可以理解的代码。
— Martin Fowler, 2008.
—马丁·福勒(Martin Fowler),2008年。
I hope the above blog post helped you in getting started with code linters. I strongly feel that the best way to improve one’s coding habits is to read through the comments raised by the editors as you start developing and try to rectify those then and there. As you start following pylint messages, you would also learn better ways of implementing the same functionality. It definitely helps!
我希望以上博客文章能帮助您入门代码短绒。 我强烈认为,改善自己的编码习惯的最佳方法是在开始开发时通读编辑提出的意见,并尝试在那时和那里进行纠正。 当您开始关注pylint消息时,您还将学习实现相同功能的更好方法。 绝对有帮助!
Coding with better standards and improved quality comes with practice and patience. The toughest task is to get started. Once you leave the shore and start sailing, trust the wind and it will propel you smoothly towards the zenith.
实践和耐心伴随着更好的标准和更高质量的编码。 最艰巨的任务是开始。 一旦您离开海岸开始航行,请相信风,它将平稳地将您推向顶峰。
As I always believe, start with one step at a time!
我一直相信,一次就开始吧!
翻译自: https://medium.com/@ankitkchoudhary/the-gates-of-code-quality-pylint-b8b38faab0ae
新世界大门
