Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[pylint] Add missing return doc rule (W9011) #8843

Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
def return_good(a: int, b: int) -> int:
"""Returns sum of two integers.
:param a: first integer
:param b: second integer
:return: sum of parameters a and b
"""
return a + b


def no_return_good(a: int, b: int) -> None:
"""Prints the sum of two integers.
:param a: first integer
:param b: second integer
"""
print(a + b)


def no_return_also_good(a: int, b: int) -> None:
"""Prints the sum of two integers.
:param a: first integer
:param b: second integer
"""
print(a + b)
return None


def google_good(a: int, b: int):
"""Returns sum of two integers.

Args:
a: first integer
b: second integer

Returns:
sum
"""
return a + b


def numpy_good(a: int, b: int):
"""Returns sum of two integers.

Parameters
----------
a:
first integer
b:
second integer

Returns
-------
sum
"""
return a + b


def _private_good(a: int, b: int) -> None:
"""Returns sum of two integers.
:param a: first integer
:param b: second integer
"""
return a + b


def return_bad(a: int, b: int): # [missing-return-doc]
"""Returns sum of two integers.
:param a: first integer
:param b: second integer
"""
return a + b
6 changes: 5 additions & 1 deletion crates/ruff_linter/src/checkers/ast/analyze/definitions.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ use crate::checkers::ast::Checker;
use crate::codes::Rule;
use crate::docstrings::Docstring;
use crate::fs::relativize_path;
use crate::rules::{flake8_annotations, flake8_pyi, pydocstyle};
use crate::rules::{flake8_annotations, flake8_pyi, pydocstyle, pylint};
use crate::{docstrings, warn_user};

/// Run lint rules over all [`Definition`] nodes in the [`SemanticModel`].
Expand Down Expand Up @@ -78,6 +78,7 @@ pub(crate) fn definitions(checker: &mut Checker) {
Rule::UndocumentedPublicModule,
Rule::UndocumentedPublicNestedClass,
Rule::UndocumentedPublicPackage,
Rule::MissingReturnDoc,
]);

if !enforce_annotations && !enforce_docstrings && !enforce_stubs && !enforce_stubs_and_runtime {
Expand Down Expand Up @@ -197,6 +198,9 @@ pub(crate) fn definitions(checker: &mut Checker) {
if !pydocstyle::rules::not_empty(checker, &docstring) {
continue;
}
if checker.enabled(Rule::MissingReturnDoc) {
pylint::rules::missing_return_doc(checker, &docstring);
}
if checker.enabled(Rule::FitsOnOneLine) {
pydocstyle::rules::one_liner(checker, &docstring);
}
Expand Down
1 change: 1 addition & 0 deletions crates/ruff_linter/src/codes.rs
Original file line number Diff line number Diff line change
Expand Up @@ -286,6 +286,7 @@ pub fn code_to_rule(linter: Linter, code: &str) -> Option<(RuleGroup, Rule)> {
#[allow(deprecated)]
(Pylint, "W3201") => (RuleGroup::Nursery, rules::pylint::rules::BadDunderMethodName),
(Pylint, "W3301") => (RuleGroup::Stable, rules::pylint::rules::NestedMinMax),
(Pylint, "W9011") => (RuleGroup::Preview, rules::pylint::rules::MissingReturnDoc),

// flake8-async
(Flake8Async, "100") => (RuleGroup::Stable, rules::flake8_async::rules::BlockingHttpCallInAsyncFunction),
Expand Down
37 changes: 37 additions & 0 deletions crates/ruff_linter/src/rules/pylint/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,13 +13,16 @@ mod tests {
use test_case::test_case;

use crate::assert_messages;
use crate::message::Message;
use crate::registry::Rule;
use crate::rules::pydocstyle::settings::Convention;
use crate::rules::pylint;
use crate::settings::types::PythonVersion;
use crate::settings::LinterSettings;
use crate::test::test_path;

#[test_case(Rule::AndOrTernary, Path::new("and_or_ternary.py"))]
#[test_case(Rule::MissingReturnDoc, Path::new("missing_return_doc.py"))]
#[test_case(Rule::AssertOnStringLiteral, Path::new("assert_on_string_literal.py"))]
#[test_case(Rule::AwaitOutsideAsync, Path::new("await_outside_async.py"))]
#[test_case(Rule::BadOpenMode, Path::new("bad_open_mode.py"))]
Expand Down Expand Up @@ -303,6 +306,40 @@ mod tests {
Ok(())
}

fn missing_return_doc_convention(convention: Convention) -> Result<Vec<Message>> {
test_path(
Path::new("pylint/missing_return_doc.py"),
&LinterSettings {
pylint: pylint::settings::Settings {
convention: Some(convention),
..pylint::settings::Settings::default()
},
..LinterSettings::for_rules(vec![Rule::MissingReturnDoc])
},
)
}

#[test]
fn missing_return_doc_pep257() -> Result<()> {
let diagnostics = missing_return_doc_convention(Convention::Pep257)?;
assert_messages!(diagnostics);
Ok(())
}

#[test]
fn missing_return_doc_google() -> Result<()> {
let diagnostics = missing_return_doc_convention(Convention::Google)?;
assert_messages!(diagnostics);
Ok(())
}

#[test]
fn missing_return_doc_numpy() -> Result<()> {
let diagnostics = missing_return_doc_convention(Convention::Numpy)?;
assert_messages!(diagnostics);
Ok(())
}

#[test]
fn too_many_public_methods() -> Result<()> {
let diagnostics = test_path(
Expand Down
92 changes: 92 additions & 0 deletions crates/ruff_linter/src/rules/pylint/rules/missing_return_doc.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,92 @@
use once_cell::sync::Lazy;
use regex::Regex;
use std::fmt::Debug;

use ruff_diagnostics::{Diagnostic, Violation};
use ruff_macros::{derive_message_formats, violation};
use ruff_text_size::Ranged;

use crate::{
checkers::ast::Checker, docstrings::Docstring, rules::pydocstyle::settings::Convention,
};

/// ## What it does
/// Checks that docstring contains documentation on what is returned.
///
/// ## Why is this bad?
/// Docstrings are a good way to document the code,
/// and including information on the return value from a function helps to
/// understand what the function does.
///
/// ## Example
/// ```python
/// def integer_sum(a: int, b: int): # [missing-return-doc]
/// """Returns sum of two integers
/// :param a: first integer
/// :param b: second integer
/// """
/// return a + b
/// ```
///
/// Use instead:
/// ```python
/// def integer_sum(a: int, b: int) -> int:
/// """Returns sum of two integers
/// :param a: first integer
/// :param b: second integer
/// :return: sum of parameters a and b
/// """
/// return a + b
/// ```
///
/// ## Options
/// - `pylint.convention`
#[violation]
pub struct MissingReturnDoc;

impl Violation for MissingReturnDoc {
#[derive_message_formats]
fn message(&self) -> String {
format!("Docstring missing documentation on what is returned")
}
}

/// PLW9011
pub(crate) fn missing_return_doc(checker: &mut Checker, docstring: &Docstring) {
static REST: Lazy<Regex> = Lazy::new(|| Regex::new(":return:").unwrap());
static NUMPY: Lazy<Regex> = Lazy::new(|| Regex::new(r"Returns\n\s*-------\n").unwrap());
static GOOGLE: Lazy<Regex> = Lazy::new(|| Regex::new(r"Returns:\n").unwrap());

if let Some(convention) = checker.settings.pylint.convention {
let has_return_documentation = match convention {
Convention::Google => &GOOGLE,
Convention::Numpy => &NUMPY,
Convention::Pep257 => &REST,
}
.is_match(docstring.contents);

let is_public_method_with_return =
docstring
.definition
.as_function_def()
.map_or(false, |function| {
!function.name.starts_with('_')
&& function
.body
.iter()
.filter_map(|statement| statement.as_return_stmt())
.any(|return_statement| {
return_statement
.value
.as_deref()
.is_some_and(|value| !value.is_none_literal_expr())
})
});

if is_public_method_with_return && !has_return_documentation {
checker
.diagnostics
.push(Diagnostic::new(MissingReturnDoc, docstring.range()));
}
}
}
2 changes: 2 additions & 0 deletions crates/ruff_linter/src/rules/pylint/rules/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@ pub(crate) use logging::*;
pub(crate) use magic_value_comparison::*;
pub(crate) use manual_import_from::*;
pub(crate) use misplaced_bare_raise::*;
pub(crate) use missing_return_doc::*;
pub(crate) use named_expr_without_context::*;
pub(crate) use nested_min_max::*;
pub(crate) use no_self_use::*;
Expand Down Expand Up @@ -106,6 +107,7 @@ mod logging;
mod magic_value_comparison;
mod manual_import_from;
mod misplaced_bare_raise;
mod missing_return_doc;
mod named_expr_without_context;
mod nested_min_max;
mod no_self_use;
Expand Down
3 changes: 3 additions & 0 deletions crates/ruff_linter/src/rules/pylint/settings.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
use rustc_hash::FxHashSet;
use serde::{Deserialize, Serialize};

use crate::rules::pydocstyle::settings::Convention;
use ruff_macros::CacheKey;
use ruff_python_ast::{ExprNumberLiteral, LiteralExpressionRef, Number};

Expand Down Expand Up @@ -38,6 +39,7 @@ impl ConstantType {
pub struct Settings {
pub allow_magic_value_types: Vec<ConstantType>,
pub allow_dunder_method_names: FxHashSet<String>,
pub convention: Option<Convention>,
pub max_args: usize,
pub max_returns: usize,
pub max_bool_expr: usize,
Expand All @@ -51,6 +53,7 @@ impl Default for Settings {
Self {
allow_magic_value_types: vec![ConstantType::Str, ConstantType::Bytes],
allow_dunder_method_names: FxHashSet::default(),
convention: None,
max_args: 5,
max_returns: 6,
max_bool_expr: 5,
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
---
source: crates/ruff_linter/src/rules/pylint/mod.rs
---

Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
---
source: crates/ruff_linter/src/rules/pylint/mod.rs
---
missing_return_doc.py:2:5: PLW9011 Docstring missing documentation on what is returned
|
1 | def return_good(a: int, b: int) -> int:
2 | """Returns sum of two integers.
| _____^
3 | | :param a: first integer
4 | | :param b: second integer
5 | | :return: sum of parameters a and b
6 | | """
| |_______^ PLW9011
7 | return a + b
|

missing_return_doc.py:41:5: PLW9011 Docstring missing documentation on what is returned
|
40 | def numpy_good(a: int, b: int):
41 | """Returns sum of two integers.
| _____^
42 | |
43 | | Parameters
44 | | ----------
45 | | a:
46 | | first integer
47 | | b:
48 | | second integer
49 | |
50 | | Returns
51 | | -------
52 | | sum
53 | | """
| |_______^ PLW9011
54 | return a + b
|

missing_return_doc.py:66:5: PLW9011 Docstring missing documentation on what is returned
|
65 | def return_bad(a: int, b: int): # [missing-return-doc]
66 | """Returns sum of two integers.
| _____^
67 | | :param a: first integer
68 | | :param b: second integer
69 | | """
| |_______^ PLW9011
70 | return a + b
|


Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
---
source: crates/ruff_linter/src/rules/pylint/mod.rs
---
missing_return_doc.py:2:5: PLW9011 Docstring missing documentation on what is returned
|
1 | def return_good(a: int, b: int) -> int:
2 | """Returns sum of two integers.
| _____^
3 | | :param a: first integer
4 | | :param b: second integer
5 | | :return: sum of parameters a and b
6 | | """
| |_______^ PLW9011
7 | return a + b
|

missing_return_doc.py:28:5: PLW9011 Docstring missing documentation on what is returned
|
27 | def google_good(a: int, b: int):
28 | """Returns sum of two integers.
| _____^
29 | |
30 | | Args:
31 | | a: first integer
32 | | b: second integer
33 | |
34 | | Returns:
35 | | sum
36 | | """
| |_______^ PLW9011
37 | return a + b
|

missing_return_doc.py:66:5: PLW9011 Docstring missing documentation on what is returned
|
65 | def return_bad(a: int, b: int): # [missing-return-doc]
66 | """Returns sum of two integers.
| _____^
67 | | :param a: first integer
68 | | :param b: second integer
69 | | """
| |_______^ PLW9011
70 | return a + b
|


Loading
Loading