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

Improve consistency between linter rules in determining whether a function is property #12581

Merged
merged 1 commit into from
Jul 30, 2024
Merged
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
Expand Up @@ -71,3 +71,18 @@ def nested():
return 5

print("I never return")


from functools import cached_property

class Baz:
# OK
@cached_property
def baz(self) -> str:
"""
Do something

Args:
num (int): A number
"""
return 'test'
Original file line number Diff line number Diff line change
Expand Up @@ -38,3 +38,12 @@ def attribute_var_args(self, *args): # [property-with-parameters]
@property
def attribute_var_kwargs(self, **kwargs): #[property-with-parameters]
return {key: value * 2 for key, value in kwargs.items()}


from functools import cached_property


class Cached:
@cached_property
def cached_prop(self, value): # [property-with-parameters]
...
32 changes: 9 additions & 23 deletions crates/ruff_linter/src/rules/pydoclint/rules/check_docstring.rs
Original file line number Diff line number Diff line change
Expand Up @@ -439,27 +439,6 @@ fn extract_raised_exception<'a>(
None
}

// Checks if a function has a `@property` decorator
fn is_property(definition: &Definition, checker: &Checker) -> bool {
let Some(function) = definition.as_function_def() else {
return false;
};

let Some(last_decorator) = function.decorator_list.last() else {
return false;
};

checker
.semantic()
.resolve_qualified_name(&last_decorator.expression)
.is_some_and(|qualified_name| {
matches!(
qualified_name.segments(),
["", "property"] | ["functools", "cached_property"]
)
})
}

/// DOC201, DOC202, DOC501, DOC502
pub(crate) fn check_docstring(
checker: &mut Checker,
Expand Down Expand Up @@ -498,8 +477,15 @@ pub(crate) fn check_docstring(
};

// DOC201
if checker.enabled(Rule::DocstringMissingReturns) {
if !is_property(definition, checker) && docstring_sections.returns.is_none() {
if checker.enabled(Rule::DocstringMissingReturns) && docstring_sections.returns.is_none() {
let extra_property_decorators = checker
.settings
.pydocstyle
.property_decorators
.iter()
.map(|decorator| QualifiedName::from_dotted_name(decorator))
.collect::<Vec<QualifiedName>>();
Comment on lines +481 to +487
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think I'm reviewing the PRs in the wrong order. This is now behind your new iterator and no longer requires collecting?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think I'm reviewing the PRs in the wrong order.

You are, yes :-) This is the first PR in the stack, and the other two PRs are based on top of this branch.

But as I mentioned in #12582 (comment), I think we still need to collect ~always even with my new iterator, because the common pattern seems to be to do something like this:

for decorator in decorators {
    if extra_properties.any(|property| property == decorator) {
        return true;
    }
}

If extra_properties is an iterator there, it could be exhausted after the first iteration of the outer for loop

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We can Clone the iterator to avoid this

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Oh, good point.

if !definition.is_property(&extra_property_decorators, checker.semantic()) {
if let Some(body_return) = body_entries.returns.first() {
let diagnostic = Diagnostic::new(DocstringMissingReturns, body_return.range());
diagnostics.push(diagnostic);
Expand Down
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The changes to this file increase the scope of this rule. We could therefore make the changes to this rule a preview-only change. However, I don't see it as a significant increase in scope: I doubt there will be many new hits on user code as a result of this change. The error that the rule is trying to catch is pretty uncommon, anyway.

Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
use ruff_diagnostics::{Diagnostic, Violation};
use ruff_macros::{derive_message_formats, violation};
use ruff_python_ast::name::QualifiedName;
use ruff_python_ast::{identifier::Identifier, Decorator, Parameters, Stmt};
use ruff_python_semantic::analyze::visibility::is_property;

use crate::checkers::ast::Checker;

Expand Down Expand Up @@ -55,10 +57,14 @@ pub(crate) fn property_with_parameters(
return;
}
let semantic = checker.semantic();
if decorator_list
let extra_property_decorators = checker
.settings
.pydocstyle
.property_decorators
.iter()
.any(|decorator| semantic.match_builtin_expr(&decorator.expression, "property"))
{
.map(|decorator| QualifiedName::from_dotted_name(decorator))
.collect::<Vec<QualifiedName>>();
if is_property(decorator_list, &extra_property_decorators, semantic) {
checker
.diagnostics
.push(Diagnostic::new(PropertyWithParameters, stmt.identifier()));
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -42,3 +42,12 @@ property_with_parameters.py:39:9: PLR0206 Cannot have defined parameters for pro
| ^^^^^^^^^^^^^^^^^^^^ PLR0206
40 | return {key: value * 2 for key, value in kwargs.items()}
|

property_with_parameters.py:48:9: PLR0206 Cannot have defined parameters for properties
|
46 | class Cached:
47 | @cached_property
48 | def cached_prop(self, value): # [property-with-parameters]
| ^^^^^^^^^^^ PLR0206
49 | ...
|
18 changes: 16 additions & 2 deletions crates/ruff_python_semantic/src/definition.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,13 +6,16 @@ use std::ops::Deref;
use std::path::Path;

use ruff_index::{newtype_index, IndexSlice, IndexVec};
use ruff_python_ast::{self as ast, Stmt};
use ruff_python_ast::name::QualifiedName;
use ruff_python_ast::{self as ast, Stmt, StmtFunctionDef};
use ruff_text_size::{Ranged, TextRange};

use crate::analyze::visibility::{
class_visibility, function_visibility, method_visibility, module_visibility, Visibility,
class_visibility, function_visibility, is_property, method_visibility, module_visibility,
Visibility,
};
use crate::model::all::DunderAllName;
use crate::SemanticModel;

/// Id uniquely identifying a definition in a program.
#[newtype_index]
Expand Down Expand Up @@ -148,6 +151,17 @@ impl<'a> Definition<'a> {
)
}

pub fn is_property(
&self,
extra_properties: &[QualifiedName],
semantic: &SemanticModel,
) -> bool {
self.as_function_def()
.is_some_and(|StmtFunctionDef { decorator_list, .. }| {
is_property(decorator_list, extra_properties, semantic)
})
}

Comment on lines +154 to +164
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I wonder if it's worth having this method in definition if it only ever is called from pylint rules. I would move it upwards next to the lint rule.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'd prefer to have it here, so that it can be easily reused by other rules that we add in the future

/// Return the name of the definition.
pub fn name(&self) -> Option<&'a str> {
match self {
Expand Down
Loading