PyLint 官方文档:https://pylint.pycqa.org/en/latest/index.html
问题:C0114(missing-module-docstring:缺失模块文档,即文件头部的注释文档)
问题提示:Missing module docstring.
问题描述:
Used when a module has no docstring. Empty modules do not require a docstring.
错误样例:
import sys # [missing-module-docstring]
def print_python_version():
print(sys.version)
正确样例:
"""Module providingFunction printing python version."""
import sys
def print_python_version():
print(sys.version)
问题:R1710(inconsistent-return-statements:函数或方法存在某个分支没有返回语句)
问题提示:Either all return statements in a function should return a expression, or none of them should.
问题描述:
According to PEP8, if any return statement returns an expression, any return statements where no value is returned should explicitly state this as return None, and an explicit return statement should be present at the end of the function (if reachable)
错误样例:
def get_the_answer(value: str) -> str | None: # [inconsistent-return-statements]
if value:
return value
正确样例:
def get_the_answer(value: str) -> str | None:
if value:
return value
return None
问题:W0107(unnecessary-pass:存在没有必要的 pass 语句)
问题提示:Unnecessary pass statement
问题描述:
Used when a “pass” statement that can be avoided is encountered.
报错样例:
class Foo:
"""Foo docstring."""
pass # [unnecessary-pass]
正确样例:
class Foo:
"""Foo docstring."""
问题:W0703(broad-except:捕获了过于笼统的异常)
问题提示:Catching too general exception %s
问题描述:
Used when an except catches a too general exception, possibly burying unrelated errors.
错误样例:
try:
1 / 0
except Exception: # [broad-exception-caught]
pass
正确样例:
try:
1 / 0
except ZeroDivisionError:
pass
问题:R1705(no-else-return:因为所有 if 语句和 elif 语句都直接 return,导致最后的 else 语句没有意义)
问题提示:
- Unnecessary “else” after “return”, remove the “else” and de-indent the code inside it
- Unnecessary “elif” after “return”, remove the leading “el” from “elif”(因为前面的 if 语句都直接 return,所以 elif 没有意义)
问题描述:
Used in order to highlight an unnecessary block of code following an if containing a return statement. As such, it will warn when it encounters an else following a chain of ifs, all of them containing a return statement.
错误样例:
def compare_numbers(a: int, b: int) -> int:
if a == b: # [no-else-return]
return 0
elif a < b:
return -1
else:
return 1
正确样例:
def compare_numbers(a: int, b: int) -> int:
if a == b:
return 0
if a < b:
return -1
return 1
问题:W1309(f-string-without-interpolation:使用了没有任何插值变量的 f-string)
问题提示:Using an f-string that does not have any interpolated variables
问题描述:
Used when we detect an f-string that does not use any interpolation variables, in which case it can be either a normal string or a bug in the code.
错误样例:
x = 1
y = 2
print(f"x + y = x + y") # [f-string-without-interpolation]
正确样例:
x = 1
y = 2
print(f"{x} + {y} = {x + y}")
问题:W0611(unused-import:存在引用了模块但没有使用)
问题提示:Unused %s
问题描述:
Used when an imported module or variable is not used.
错误样例 1:
from logging import getLogger
from pathlib import Path # [unused-import]
LOGGER = getLogger(__name__)
正确样例 1:
from logging import getLogger
LOGGER = getLogger(__name__)
错误样例 2:
from test import A
def func(a: "A"):
pass
正确样例 2:
from test import A
def func(a: A):
pass
问题:W0614(unused-wildcard-import:通过 from sthm import *
引用了别名但没有使用)
问题提示:Unused import(s) %s from wildcard import of %s
问题描述:
Used when an imported module or variable is not used from a 'from X import \*'
style import.
错误样例:
from abc import * # [unused-wildcard-import]
class Animal(ABC): ...
正确样例:
from abc import ABC
class Animal(ABC): ...
问题:R0801(duplicate-code:存在重复代码)
问题提示:Similar lines in %s files %s
问题描述:
Indicates that a set of similar lines has been detected among multiple file. This usually means that the code should be refactored to avoid this duplication.
问题:C0301(line-too-long:行过长)
问题提示:Line too long (%s/%s)
问题描述:
Used when a line is longer than a given number of characters.
补充说明:
If you attempt to disable this message via # pylint: disable=line-too-long
in a module with no code, you may receive a message for useless-suppression
. This is a false positive of useless-suppression
we can’t easily fix.
问题:C0115(missing-class-docstring:缺失类注释文档)
问题提示:Missing class docstring
问题描述:
Used when a class has no docstring. Even an empty class must have a docstring.
错误样例:
class Person: # [missing-class-docstring]
def __init__(self, first_name, last_name):
self.first_name = first_name
self.last_name = last_name
正确样例:
class Person:
"""Class representing a person"""
def __init__(self, first_name, last_name):
self.first_name = first_name
self.last_name = last_name
问题:W0237(arguments-renamed:重写的方法修改了参数名称)
问题提示:%s %s %r method
问题描述:
Used when a method parameter has a different name than in the implemented interface or in an overridden method.
错误样例:
class Fruit:
def brew(self, ingredient_name: str):
print(f"Brewing a {type(self)} with {ingredient_name}")
class Apple(Fruit):
...
class Orange(Fruit):
def brew(self, flavor: str): # [arguments-renamed]
print(f"Brewing an orange with {flavor}")
for fruit, ingredient_name in [[Orange(), "thyme"], [Apple(), "cinnamon"]]:
fruit.brew(ingredient_name=ingredient_name)
正确样例:
class Fruit:
def brew(self, ingredient_name: str):
print(f"Brewing a {type(self)} with {ingredient_name}")
class Apple(Fruit):
...
class Orange(Fruit):
def brew(self, ingredient_name: str):
print(f"Brewing an orange with {ingredient_name}")
for fruit, ingredient_name in [[Orange(), "thyme"], [Apple(), "cinnamon"]]:
fruit.brew(ingredient_name=ingredient_name)
问题:C0305(trailing-newlines:Python 文件结尾有超过 1 行空行)
问题提示:Trailing newlines
问题描述:
Used when there are trailing blank lines in a file.
问题:W0231(super-init-not-called:子类的 __init__
方法没有调用父类的 __init__
方法)
问题提示:__init__
method from base class %r is not called
问题描述:
Used when an ancestor class method has an init method which is not called by a derived class.
错误样例:
class Fruit:
def __init__(self, name="fruit"):
self.name = name
print("Creating a {self.name}")
class Apple(Fruit):
def __init__(self): # [super-init-not-called]
print("Creating an apple")
正确样例:
class Fruit:
def __init__(self, name="fruit"):
self.name = name
print(f"Creating a {self.name}")
class Apple(Fruit):
def __init__(self):
super().__init__("apple")
问题:C0208(use-sequence-for-iteration:如果可迭代对象只用来遍历的话,那么应该使用列表类型而不是集合)
问题提示:Use a sequence type when iterating over values
问题描述:
When iterating over values, sequence types (e.g., lists
, tuples
, ranges
) are more efficient than sets
.
错误样例:
for item in {"AA", "BB", "CC", "DD"}:
pass
正确样例:
for item in ["AA", "BB", "CC", "DD"]:
pass
问题:W1514(unspecified-encoding:使用 open 函数但没有明确指定编码类型)
问题提示:Using open without explicitly specifying an encoding
问题描述:
It is better to specify an encoding when opening documents. Using the system default implicitly can create problems on other operating systems. See https://peps.python.org/pep-0597/
错误样例:
def foo(file_path):
with open(file_path) as file: # [unspecified-encoding]
contents = file.read()
正确样例:
def foo(file_path):
with open(file_path, encoding="utf-8") as file:
contents = file.read()
问题:R1714:(consider-using-in:多个 or 的判断是否相等的条件语句,应该改为判断是否 in 集合)
问题提示:Consider merging these comparisons with ‘in’ by using ‘%s %sin (%s)’. Use a set instead if elements are hashable.
问题描述:
To check if a variable is equal to one of many values, combine the values into a set or tuple and check if the variable is contained “in” it instead of checking for equality against each of the values. This is faster and less verbose.
错误样例:
def fruit_is_round(fruit):
return fruit == "apple" or fruit == "orange" or fruit == "melon" # [consider-using-in]
正确样例:
def fruit_is_round(fruit):
return fruit in {"apple", "orange", "melon"}
问题:W0612(unused-variable:存在定义但没有使用的变量)
问题提示:Unused variable %r
问题描述:Used when a variable is defined but not used.
错误样例 1:
def print_fruits():
fruit1 = "orange"
fruit2 = "apple" # [unused-variable]
print(fruit1)
正确样例 1:
def print_fruits():
fruit1 = "orange"
fruit2 = "apple"
print(fruit1, fruit2)
错误样例 2:
for key, value in dictionary.items():
print(value)
正确样例 2:
for value in dictionary.values():
print(value)
问题:C0103(invalid-name:名称不满足 Python 规范)
问题提示:%s name “%s” doesn’t conform to %s
问题描述:
Used when the name doesn’t conform to naming rules associated to its type (constant, variable, class…).
错误样例:
class cat: # [invalid-name]
def Meow(self, NUMBER_OF_MEOW): # [invalid-name, invalid-name]
print("Meow" * NUMBER_OF_MEOW)
return NUMBER_OF_MEOW
Cat = cat().Meow(42) # [invalid-name]
正确样例:
class Cat:
def meow(self, number_of_meow):
print("Meow" * number_of_meow)
return number_of_meow
CAT = Cat().meow(42)
补充说明:
Pylint recognizes a number of different name types internally. With a few exceptions, the type of the name is governed by the location the assignment to a name is found in, and not the type of object assigned.
Name Type | Description |
---|---|
module | Module and package names, same as the file names. |
const | Module-level constants, any variable defined at module level that is not bound to a class object. |
class | Names in class statements, as well as names bound to class objects at module level. |
function | Functions, toplevel or nested in functions or methods. |
method | Methods, functions defined in class bodies. Includes static and class methods. |
attr | Attributes created on class instances inside methods. |
argument | Arguments to any function type, including lambdas. |
variable | Local variables in function scopes. |
class-attribute | Attributes defined in class bodies. |
class-const | Enum constants and class variables annotated with ClassVar |
inlinevar | Loop variables in list comprehensions and generator expressions. |
typevar | Type variable declared with TypeVar . |
By default, Pylint will enforce PEP8-suggested names.
问题:W0108(unnecessary-lambda:存在没有必要的 lambda 语句)
问题提示:Lambda may not be necessary
问题描述:
Used when the body of a lambda expression is a function call on the same argument list as the lambda itself; such lambda expressions are in all but a few cases replaceable with the function being called in the body of the lambda.
错误样例:
function = lambda x: print(x) # [unnecessary-lambda]
function("Hello world !")
df.apply(lambda x: str(x)) # [unnecessary-lambda]
正确样例:
print("Hello world !")
df.apply(str)
问题:R1733(unnecessary-dict-index-lookup:没有必要的字典查询)
问题提示:Unnecessary dictionary index lookup, use ‘%s’ instead
问题描述:
Emitted when iterating over the dictionary items (key-item pairs) and accessing the value by index lookup. The value can be accessed directly instead.
错误样例:
FRUITS = {"apple": 1, "orange": 10, "berry": 22}
for fruit_name, fruit_count in FRUITS.items():
print(FRUITS[fruit_name]) # [unnecessary-dict-index-lookup]
正确样例:
FRUITS = {"apple": 1, "orange": 10, "berry": 22}
for fruit_name, fruit_count in FRUITS.items():
print(fruit_count)
问题:W0622(redefined-builtin:重新定义了 build-in 名称)
问题提示:Redefining built-in %r
问题描述:Used when a variable or function override a built-in.
错误样例 1:
def map(): # [redefined-builtin]
pass
正确样例 1:
def map_iterable():
pass
错误样例 2:
type = "str"
正确样例 2:
d_type = "str"
问题:W0120(useless-else-on-loop:没有意义的循环 else)
问题提示:Else clause on loop without a break statement, remove the else and de-indent all the code inside it
问题描述:Loops should only have an else clause if they can exit early with a break statement, otherwise the statements under else should be on the same scope as the loop itself.
错误样例:
def find_even_number(numbers):
for x in numbers:
if x % 2 == 0:
return x
else: # [useless-else-on-loop]
print("Did not find an even number")
正确样例:
def find_even_number(numbers):
for x in numbers:
if x % 2 == 0:
return x
print("Did not find an even number")