Linter 与code formatter之python 编程起手式

1. Linter 与code formatter

Linting and code formatting are essential practices in software development, particularly in Python, to maintain code quality, readability, and consistency. Let’s delve into their functions and how to use them in PyCharm when working on PyTorch neural network models.

Linting 和代码格式化是软件开发(尤其是 Python)中保持代码质量、可读性和一致性的基本实践。

1.1 Linter

Functions of a Linter:Linter 的功能:

  1. Error Detection: Identifies syntactical errors and potential bugs in the code.错误检测:识别代码中的语法错误和潜在错误。
  2. Code Quality: Ensures the code adheres to a set of predefined coding standards or best practices (e.g., PEP 8 for Python).代码质量:确保代码遵循一组预定义的编码标准或最佳实践(例如,Python 的 PEP 8)。
  3. Code Smells: Detects patterns in the code that might indicate a problem, even if they are not actual errors (e.g., unused variables, improper naming conventions).代码气味:检测代码中可能指示问题的模式,即使它们不是实际错误(例如,未使用的变量、不正确的命名约定)。
  4. Refactoring Suggestions: Provides recommendations for code improvements and optimizations.重构建议:提供代码改进和优化的建议。

Using a Linter in PyCharm:在 PyCharm 中使用 Linter:

  1. Built-in Linter: PyCharm comes with built-in support for linters like Pylint and Flake8.内置 Linter:PyCharm 内置了对 Pylint 和 Flake8 等 linter 的支持。
  2. Enabling Linter:
    • Go to File -> Settings (or PyCharm -> Preferences on macOS).转到 File -> Settings (或 macOS 上的 PyCharm -> Preferences )。
    • Navigate to Editor -> Inspections.导航到 Editor -> Inspections
    • Enable the desired linter (e.g., Pylint, Flake8) and configure its settings.启用所需的 linter(例如 Pylint、Flake8)并配置其设置。
  3. Running the Linter: The linter will automatically run as you write code, highlighting issues directly in the editor. You can also manually run the linter on the entire project or specific files by right-clicking on the project or file and selecting Run Code Inspections.运行 Linter:linter 将在您编写代码时自动运行,直接在编辑器中突出显示问题。您还可以通过右键单击项目或文件并选择 Run Code Inspections 来手动对整个项目或特定文件运行 linter。

1.2 Code Formatter

Functions of a Code Formatter:代码格式化程序的功能:

  1. Consistent Formatting: Automatically formats code to adhere to a consistent style guide, such as PEP 8 for Python.一致的格式:自动格式化代码以遵循一致的风格指南,例如Python的PEP 8。
  2. Improved Readability: Makes code easier to read and understand by enforcing consistent indentation, spacing, and line breaks.提高可读性:通过强制执行一致的缩进、间距和换行,使代码更易于阅读和理解。
  3. Reduced Merge Conflicts: Consistent formatting reduces the likelihood of merge conflicts in version control systems caused by differing code styles.减少合并冲突:一致的格式减少了版本控制系统中因不同代码风格引起的合并冲突的可能性。

Using a Code Formatter in PyCharm:在 PyCharm 中使用代码格式化程序:

  1. Built-in Formatter: PyCharm has a built-in code formatter that adheres to PEP 8 standards.内置格式化程序:PyCharm 具有符合 PEP 8 标准的内置代码格式化程序。
  2. Configuring Formatter:配置格式化程序:
    • Go to File -> Settings (or PyCharm -> Preferences on macOS).转到 File -> Settings (或 macOS 上的 PyCharm -> Preferences )。
    • Navigate to Editor -> Code Style -> Python.导航到 Editor -> Code Style -> Python
    • Adjust the settings as needed for indentation, spaces, line breaks, etc.根据需要调整缩进、空格、换行符等设置。
  3. Formatting Code:
    • To format a specific file, open the file and press Ctrl+Alt+L (Windows/Linux) or Cmd+Alt+L (macOS).要格式化特定文件,请打开该文件并按 Ctrl+Alt+L (Windows/Linux) 或 Cmd+Alt+L (macOS)。
    • To format the entire project, select the project root, right-click, and choose Reformat Code.要格式化整个项目,请选择项目根目录,单击鼠标右键,然后选择 Reformat Code

2. Ruff

Ruff is an extremely fast linter and code formatter for Python, designed to provide the functionality of multiple tools in a single, efficient package. It can replace tools like Flake8, isort, pyupgrade, and more, offering significant performance improvements and comprehensive linting capabilities.

Ruff 是一款极其快速的 Python linter 和代码格式化程序,旨在在单个高效包中提供多个工具的功能。它可以取代 Flake8、isort、pyupgrade 等工具,提供显着的性能改进和全面的 linting 功能。

2.1 Features of Ruff

  1. Speed: Ruff is known for its speed, being significantly faster than traditional linters like Flake8.速度:Ruff 以其速度而闻名,比 Flake8 等传统的 linter 快得多。
  2. Comprehensive: It combines the functionalities of multiple tools, providing a wide range of linting and formatting checks.全面:它结合了多种工具的功能,提供广泛的 linting 和格式检查。
  3. Configurable: Ruff allows extensive configuration to suit various coding styles and project requirements.可配置:Ruff 允许进行广泛的配置,以适应各种编码风格和项目要求。
  4. Simple Setup: Easy to install and integrate into existing workflows.设置简单:易于安装并集成到现有工作流程中。

3. Pycharm 中配置ruff

To use Ruff in PyCharm, follow these steps:要在 PyCharm 中使用 Ruff,请按照下列步骤操作:

1. Install Ruff

First, you need to install Ruff. You can do this via pip:首先,您需要安装 Ruff。您可以通过 pip 执行此操作:

pip install ruff

3.1 方式1 – 推荐

Option A: Using External Tools Configuration选项 A:使用外部工具配置

  1. Add Ruff as an External Tool:

    • Go to File -> Settings (or PyCharm -> Preferences on macOS).转到 File -> Settings (或 macOS 上的 PyCharm -> Preferences )。
    • Navigate to Tools -> External Tools.导航到 Tools -> External Tools
    • Click the + icon to add a new tool.单击 + 图标添加新工具。
  2. Configure the Tool:配置工具:

    • Name: Ruff
    • Program: ruff (or the full path to the Ruff executable if it’s not in your PATH)程序: ruff (或者 Ruff 可执行文件的完整路径,如果它不在您的 PATH 中)
    • Arguments: check $FilePathRelativeToProjectRoot$
    • Working Directory: $ProjectFileDir$工作目录: $ProjectFileDir$
  3. Run Ruff:

    • To run Ruff, right-click on the file or directory in the Project view, go to External Tools, and select Ruff.要运行 Ruff,请右键单击“项目”视图中的文件或目录,转到 External Tools ,然后选择 Ruff

note:

注意上面的 Program 中的 ruff 是默认为 ruff 的可执行文件被添加到 环境变量中了, 如果只是在安装在对应的虚拟环境中, 此时,需要使用 which ruff, 来添加 /home/respecting_god/anaconda3/envs/torch2.0.1/bin/ruff 到program 一栏中;

Arguments: 中如果想要不仅 检查出 语法问题, 并且需要进一步自动修复的时候,改为
check --fix $FilePathRelativeToProjectRoot$

3.2 方式2

Option B: Using File Watchers (Optional)

  1. Install the File Watchers Plugin:安装文件观察器插件:

    • Go to File -> Settings -> Plugins.转到 File -> Settings -> Plugins
    • Search for File Watchers and install it.搜索 File Watchers 并安装它。
  2. Configure File Watcher for Ruff:为 Ruff 配置文件观察器:

    • Go to File -> Settings -> Tools -> File Watchers.转到 File -> Settings -> Tools -> File Watchers
    • Click the + icon to add a new watcher.单击 + 图标添加新的观察者。
    • Set it up as follows:
      • File Type: Python
      • Scope: Current File
      • Program: ruff
      • Arguments: check $FilePathRelativeToProjectRoot$
      • Output Paths: Leave blank (or set as needed for your project)输出路径:留空(或根据项目需要进行设置)
  3. Run Ruff Automatically:

    • The file watcher will automatically run Ruff whenever you save a Python file.每当您保存 Python 文件时,文件观察器都会自动运行 Ruff。

Using Ruff in the Command Line在命令行中使用 Ruff

In addition to using Ruff within PyCharm, you can also run it from the command line for more comprehensive checks across your entire project:除了在 PyCharm 中使用 Ruff 之外,您还可以从命令行运行它,以便对整个项目进行更全面的检查:

ruff check .

This command will check all Python files in the current directory and subdirectories.该命令将检查当前目录和子目录中的所有Python文件。

Configuration File for Ruff

Ruff supports configuration files to customize its behavior. Create a .ruff.toml or pyproject.toml file in your project root and specify your settings. Example:Ruff 支持配置文件来自定义其行为。在项目根目录中创建 .ruff.tomlpyproject.toml 文件并指定您的设置。例子:

# .ruff.toml
[tool.ruff]
line-length = 88
select = ["E", "F", "W"]
ignore = ["E203", "E266", "E501", "W503"]

This configuration sets the maximum line length and specifies which error codes to check or ignore.此配置设置最大行长度并指定要检查或忽略的错误代码。

3.3 添加到环境变量中

ChatGPT:

The error you’re encountering indicates that PyCharm cannot find the ruff executable. This can happen if ruff is not installed in a location that is included in your system’s PATH. To resolve this, you can specify the full path to the ruff executable when configuring it in PyCharm.您遇到的错误表明 PyCharm 找不到 ruff 可执行文件。如果 ruff 未安装在系统 PATH 中包含的位置,则可能会发生这种情况。要解决此问题,您可以在 PyCharm 中配置 ruff 可执行文件时指定它的完整路径。

Here are the detailed steps to ensure ruff is correctly set up in PyCharm:以下是确保在 PyCharm 中正确设置 ruff 的详细步骤:

Step-by-Step Guide分步指南

1. Verify Ruff Installation

First, ensure ruff is installed and find out where it is located. You can do this by running the following command in your terminal:首先,确保安装了 ruff 并找出它的位置。您可以通过在终端中运行以下命令来完成此操作:

which ruff

This command will return the path to the ruff executable, for example, /usr/local/bin/ruff.此命令将返回 ruff 可执行文件的路径,例如 /usr/local/bin/ruff

2. Add Ruff as an External Tool in PyCharm2. 在 PyCharm 中添加 Ruff 作为外部工具
  1. Open PyCharm Settings:

    • Go to File -> Settings (or PyCharm -> Preferences on macOS).转到 File -> Settings (或 macOS 上的 PyCharm -> Preferences )。
  2. Navigate to External Tools:

    • In the settings window, navigate to Tools -> External Tools.在设置窗口中,导航至 Tools -> External Tools
  3. Add a New Tool:

    • Click the + icon to add a new external tool.单击 + 图标添加新的外部工具。
  4. Configure the External Tool:

    • Name: Ruff
    • Program: Enter the full path to the ruff executable found in the previous step (e.g., /usr/local/bin/ruff).程序:输入上一步中找到的 ruff 可执行文件的完整路径(例如 /usr/local/bin/ruff )。
    • Arguments: check $FilePathRelativeToProjectRoot$
    • Working Directory: $ProjectFileDir$工作目录: $ProjectFileDir$

    Your configuration should look something like this:您的配置应该如下所示:

    • Name: Ruff
    • Program: /usr/local/bin/ruff (replace with the actual path from the which ruff command)程序: /usr/local/bin/ruff (替换为 which ruff 命令中的实际路径)
    • Arguments: check $FilePathRelativeToProjectRoot$
    • Working Directory: $ProjectFileDir$工作目录: $ProjectFileDir$
  5. Apply and Close:申请并关闭:

    • Click OK to save your settings and close the configuration window.单击 OK 保存您的设置并关闭配置窗口。
3. Run Ruff in PyCharm

To run Ruff on your project files:要在项目文件上运行 Ruff:

  1. Right-click on the file or directory in the Project view where you want to run Ruff.在项目视图中右键单击要运行 Ruff 的文件或目录。
  2. Select External Tools -> Ruff.
4. Optional: Add Ruff to PATH (if necessary)

If you prefer to have Ruff available globally, you can add it to your system’s PATH:如果您希望 Ruff 在全球范围内可用,您可以将其添加到系统的 PATH 中:

  • Linux/MacOS:Linux/MacOS:

    • Edit your shell configuration file (e.g., .bashrc, .zshrc) and add the following line:编辑您的 shell 配置文件(例如 .bashrc.zshrc )并添加以下行:

      export PATH="$PATH:/path/to/ruff"
      
    • Replace /path/to/ruff with the directory containing the ruff executable.将 /path/to/ruff 替换为包含 ruff 可执行文件的目录。

    • Reload the shell configuration:重新加载外壳配置:

      source ~/.bashrc
      # or
      source ~/.zshrc
      
  • Windows:

    • Open the Start Search, type in “env”, and select “Edit the system environment variables”.打开“开始搜索”,输入“env”,然后选择“编辑系统环境变量”。
    • In the System Properties window, click on the “Environment Variables” button.在“系统属性”窗口中,单击“环境变量”按钮。
    • In the Environment Variables window, find the PATH variable in the “System variables” section and click “Edit”.在“环境变量”窗口中,在“系统变量”部分中找到 PATH 变量,然后单击“编辑”。
    • Add the directory containing ruff.exe to the PATH.将包含 ruff.exe 的目录添加到 PATH。

Workflow with PyTorch and PyCharm使用 PyTorch 和 PyCharm 的工作流程

When writing and designing neural network models using PyTorch in PyCharm, integrating linters and code formatters can significantly enhance your development process:在 PyCharm 中使用 PyTorch 编写和设计神经网络模型时,集成 linter 和代码格式化程序可以显着增强您的开发过程:

  1. Write Code: As you write your PyTorch code, the linter will provide real-time feedback on potential issues, helping you catch errors early.编写代码:当您编写 PyTorch 代码时,linter 将提供有关潜在问题的实时反馈,帮助您尽早发现错误。
  2. Format Code: Regularly format your code using the code formatter to ensure consistency and readability.格式化代码:使用代码格式化程序定期格式化代码,以确保一致性和可读性。
  3. Review Linter Warnings: Pay attention to the linter’s warnings and suggestions to improve your code quality.查看 Linter 警告:注意 linter 的警告和建议,以提高代码质量。
  4. Run Unit Tests: Complement linting and formatting with thorough unit testing to ensure your neural network models function correctly.运行单元测试:通过彻底的单元测试补充 linting 和格式化,以确保您的神经网络模型正常运行。
  5. Refactor and Optimize: Use the linter’s suggestions to refactor and optimize your code, enhancing performance and maintainability.重构和优化:使用 linter 的建议来重构和优化代码,从而增强性能和可维护性。
  • 25
    点赞
  • 13
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
在选择使用Vue框架时,我们通常会面临选择Vue Linter或Vue Formatter的问题。Vue Linter(代码检查工具)和Vue Formatter(代码格式化工具)都有其自己的重要性和用途。 Vue Linter是一种强大的工具,可用于检查我们的代码是否符合Vue.js的最佳实践和代码规范。它会检查我们的代码中是否存在错误、潜在的问题和代码风格不一致之处。通过检查和警告,Vue Linter帮助我们在编写代码时保持一致性,并提高代码的可读性和可维护性。使用Vue Linter,我们可以确保我们团队中的所有开发者都遵循相同的代码规范,这有助于减少团队协作和代码审查的成本。 Vue Formatter是一种自动化工具,可用于自动为我们的代码设置正确的格式。它会根据我们所选择的代码风格规则,自动调整缩进、换行、空格等。通过使用Vue Formatter,我们可以确保项目中的代码风格一致,并避免人工修复代码格式的繁琐过程。这对于大型项目和多人协作来说尤为重要,因为不同开发者的代码格式可能存在差异,可能导致代码合并和维护的问题。 在选择Vue Linter或Vue Formatter时,我们需要根据项目的具体需求和团队的协作方式进行权衡。如果团队需要强制执行一致的代码规范,并且在编写代码时希望及时发现问题,那么选择Vue Linter是一个不错的选择。如果团队更关注代码风格的一致性和自动化,那么选择Vue Formatter会更合适。当然,更好的做法是结合使用这两者,以最大程度地确保代码的质量和可读性。 总而言之,Vue Linter和Vue Formatter都是非常有用的工具,在Vue开发中起到不可或缺的作用。通过合理选择和使用这些工具,我们可以更好地保证代码质量,提高团队开发的效率和协作能力。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值