This article is participating in Python Theme Month. See the link to the event for more details

Rest cannot be enjoyed by lazy people~

preface

Python code needs to follow PEP8, otherwise ~ will not, of course, report an error, just a nasty wavy line, as shown below:

There are three wavy lines in these few lines of code. The irregularities are as follows:

(1) Importing the time module but not using it;

(2) Two empty lines are required between the import statement and the formal logical code.

(3) If the function has multiple arguments, there should be a space between each argument.

(4) After the end of the function code, should be newline.

This is only part of the PEP8 specification. There are tools that can help you automatically format your code to comply with PEP8 and say goodbye to squiggly lines. Here’s a brief introduction to mypy Flake8 Black ISort.

mypy

This section describes how to use the mypy module. For more information about how to use the mypy module, see * mypY official documentation *.

The role of mypy

Mypy is a static type checker for Python. We know python is a dynamically typed language. What’s the point of type checking for Python? The value of mYPy (Static type checking for Python applications) is that a statically typed language performs type checking by analyzing the source code before the program is run, and detects possible errors in the code in the application before it is run. The above text is from the *Fedora Chinese group *

Mypy installation and operation

The installation of mypy is simple: PIP install mypy. You need to install another module, typing, before you can use mypy. This module is used for type checking and mypy needs to use typing for type checking.

Here’s a simple code to test and understand what mypy does:

class People:
    def __init__(self, name, age) :
        self.name = name
        self.age = age


def info(peoples_list) :
    for people in peoples_list:
        if people.age < 18:
            print(f'{people.name}It's a child. ')


p1 = People('python'.10)
p2 = People('java'.20)

info([p1, p2])
info(p1)
Copy the code

Save this code to test.py and use mypy to check the above code:

mypy test.py
# Success: no issues found in 1 source file
Copy the code

By default, mypy does not alert your code to any errors. If Python3.6 or above is used, you can use the typing module to type your code. Then mypy can check your application against these type hints, such as adding a type hint to the info function:

from typing import List

def info(peoples_list: List[People]) - >None:
    for people in peoples_list:
        if people.age < 18:
            print(f'{people.name}It's a child. ')
Copy the code

Peoples_list: List[People] indicates that the parameter to the info function must be the List set People object.

->None Indicates that the info function returns None.

Now run mypy again, and you get the following:

mypy test.py
# test.py:20: error: Argument 1 to "info" has incompatible type "People"; expected "List[People]"
Copy the code

Mypy often generates errors where the library or package is not found, or if you don’t want to mention some errors, you can comment after the code:

info(p1)  # type: ignore
Copy the code

In addition to using mypy directly with commands and comments, mypy also supports reading configurations from files. The default mypy configuration file is.mypy.ini. The mypY configuration file contains two types of configurations: global configuration, which is mandatory, and local configuration. If the global configuration and local configuration conflict, the local configuration prevails.

# .mypy.ini

# Global configuration
[mypy]
ignore_missing_imports=true

# Partial configuration: all migrations files in test will be ignored
[mypy-test.migrations.*]
ignore_errors = True
Copy the code

For more configuration file options, see * official documentation *. Start mypy with a configuration file:

mypy --config-file /usr/local/config/.mypy.ini test.py
Copy the code

flake8

Here is a brief introduction to the use of Flake8, please refer to * official documentation * for more information.

The role of flake8

Flake8 is an official Python tool that helps you check if Python code is conforming to the specification. There is also a popular tool called Pylint. Here is a simple use of Flake8. Flake8 is an encapsulation of the following three tools:

PyFlakes
Pep8
NedBatchelder’s McCabe script
Copy the code

Flake8 is up and running

The installation of flake8 is also very simple: PIP installs flake8, and flake8 must be running in a Python3.5 or later interpreter.

You can use Flake8 to check whether a particular file is compliant or all files in a directory are compliant.

# Check a file
flake8 /usr/local/test.py  # test.py:20:26: W292 no newline at end of file

Check all files in a directory
flake8 /usr/local/code/
''' /usr/local/code/test.py:71:14: W292 no newline at end of file /usr/local/code/test1.py:15:80: E501 line too long (97 > 79 characters) /usr/local/code/test2.py:37:7: F821 undefined name 'l1' '''
Copy the code

If you want to check for one or more specific errors or ignore a particular error, you can use one of the following methods. Please refer to the official documentation for error codes:

flake8 --select E123,W503 path/to/code/  Check for specific errors
flake8 --ignore E24,W504 path/to/code/   Ignore specific errors
Copy the code

In addition to simply using Flake8, it is possible to control flake8 through the flake8 profile, which is usually named setup. CFG or tox. Ini or.flake, although the official flake8 profile is recommended to use the ini format. For configuration file options see *flake8 for a complete list of options *. Here is a simple configuration file format:

# tox.ini
[flake8]
# comment: ignored error W292
ignore = W292

# Check for errors starting with xx
select = B,C,E,F,W,T4,B9

# Unchecked files or directories
exclude = .git,__pycache__,docs/source/conf.py,old,build,dist
Copy the code

Using the configuration file to start Flake8 check the code:

flake8 --config=/usr/local/tox.ini /usr/local/code/
Copy the code

black

Black is Python’s official exit tool for checking code compliance with PEP8. It can be used to format entire files in a simpler way than mypy and Flake8.

PIP install Black is a simple way to format a specified file or all files in a specified directory.

# Format files in the directory
black /usr/local/code/

# Format the specified file
black /usr/local/test.py
Copy the code

The result is as follows:

# black Before execution
l = [
    1.2
]

dic = {
    'name':'python'.'age':10
}

# black after execution
l = [1.2]

dic = {"name": "python"."age": 10}
Copy the code

isort

The ISort tool, which automatically sorts and segments Python import statements, can format a large number of import structures into a readable typographic format.

PIP install isort. The use of isort can be run on a specific file or applied to a directory.

isort /usr/local/test.py  # Specify file
isort /usr/local/  # specifies all files in the directory
isort /usr/local/*.py  All py files in the # directory
Copy the code

If you want to see how the formatted result differs from the current one but don’t want to apply the formatted result, use –diff

isort test.py --diff
Copy the code

If you want to ignore the import of a line, just add a comment at the end of the line: isort:skip

import module  # isort: skip
Copy the code

It can also be formatted in Python using code:

import isort

isort.file("pythonfile.py")
Copy the code

One useful feature of isort is that it can be integrated into Git to check the code before committing it to Git.

Isort also supports a variety of standard configuration formats, allowing you to quickly integrate custom configurations into your project. You can manually specify the configuration path from the command line with –setiings-path, otherwise isort will have to traverse a lot of directories to find the right configuration file. The preferred configuration file format for isort is.isort. CFG. The first location where isort looks for configuration is.isort. CFG. There are other configuration files that you can refer to the official documentation. The following is an example of an ISORT configuration file. For more information on isort configuration options, see * documentation * :

# .isort.cfg
[settings]  # General configuration
profile=hug
src_paths=isort,test
Copy the code

conclusion

In the project development, reasonable use of these tools can make your code more beautiful and beautiful oh!

conclusion

The article was first published in the wechat public account program Yuan Xiaozhuang, synchronized with nuggets.

Please explain where it came from. If you pass by, please put out your cute little finger and click like before you go (╹▽╹)