Skip to content

Commit

Permalink
[flake8-slots] Add plugin, add SLOT000, SLOT001 and SLOT002 (#…
Browse files Browse the repository at this point in the history
  • Loading branch information
qdegraaf authored and konstin committed Jun 13, 2023
1 parent 695a105 commit 945e923
Show file tree
Hide file tree
Showing 20 changed files with 441 additions and 11 deletions.
23 changes: 23 additions & 0 deletions LICENSE
Original file line number Diff line number Diff line change
Expand Up @@ -354,6 +354,29 @@ are:
SOFTWARE.
"""

- flake8-slots, licensed as follows:
"""
Copyright (c) 2021 Dominic Davis-Foster

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE
OR OTHER DEALINGS IN THE SOFTWARE.
"""

- flake8-todos, licensed as follows:
"""
Copyright (c) 2019 EclecticIQ. All rights reserved.
Expand Down
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -283,6 +283,7 @@ quality tools, including:
- [flake8-return](https://pypi.org/project/flake8-return/)
- [flake8-self](https://pypi.org/project/flake8-self/)
- [flake8-simplify](https://pypi.org/project/flake8-simplify/)
- [flake8-slots](https://pypi.org/project/flake8-slots/)
- [flake8-super](https://pypi.org/project/flake8-super/)
- [flake8-tidy-imports](https://pypi.org/project/flake8-tidy-imports/)
- [flake8-todos](https://pypi.org/project/flake8-todos/)
Expand Down
6 changes: 6 additions & 0 deletions crates/ruff/resources/test/fixtures/flake8_slots/SLOT000.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
class Bad(str): # SLOT000
pass


class Good(str): # Ok
__slots__ = ["foo"]
21 changes: 21 additions & 0 deletions crates/ruff/resources/test/fixtures/flake8_slots/SLOT001.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
class Bad(tuple): # SLOT001
pass


class Good(tuple): # Ok
__slots__ = ("foo",)


from typing import Tuple


class Bad(Tuple): # SLOT001
pass


class Bad(Tuple[str, int, float]): # SLOT001
pass


class Good(Tuple[str, int, float]): # OK
__slots__ = ("foo",)
14 changes: 14 additions & 0 deletions crates/ruff/resources/test/fixtures/flake8_slots/SLOT002.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
from collections import namedtuple
from typing import NamedTuple


class Bad(namedtuple("foo", ["str", "int"])): # SLOT002
pass


class Good(namedtuple("foo", ["str", "int"])): # OK
__slots__ = ("foo",)


class Good(NamedTuple): # Ok
pass
36 changes: 25 additions & 11 deletions crates/ruff/src/checkers/ast/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -48,9 +48,9 @@ use crate::rules::{
flake8_debugger, flake8_django, flake8_errmsg, flake8_future_annotations, flake8_gettext,
flake8_implicit_str_concat, flake8_import_conventions, flake8_logging_format, flake8_pie,
flake8_print, flake8_pyi, flake8_pytest_style, flake8_raise, flake8_return, flake8_self,
flake8_simplify, flake8_tidy_imports, flake8_type_checking, flake8_unused_arguments,
flake8_use_pathlib, flynt, mccabe, numpy, pandas_vet, pep8_naming, pycodestyle, pydocstyle,
pyflakes, pygrep_hooks, pylint, pyupgrade, ruff, tryceratops,
flake8_simplify, flake8_slots, flake8_tidy_imports, flake8_type_checking,
flake8_unused_arguments, flake8_use_pathlib, flynt, mccabe, numpy, pandas_vet, pep8_naming,
pycodestyle, pydocstyle, pyflakes, pygrep_hooks, pylint, pyupgrade, ruff, tryceratops,
};
use crate::settings::types::PythonVersion;
use crate::settings::{flags, Settings};
Expand Down Expand Up @@ -682,14 +682,16 @@ where
pylint::rules::return_in_init(self, stmt);
}
}
Stmt::ClassDef(ast::StmtClassDef {
name,
bases,
keywords,
decorator_list,
body,
range: _,
}) => {
Stmt::ClassDef(
class_def @ ast::StmtClassDef {
name,
bases,
keywords,
decorator_list,
body,
range: _,
},
) => {
if self.enabled(Rule::DjangoNullableModelStringField) {
self.diagnostics
.extend(flake8_django::rules::nullable_model_string_field(
Expand Down Expand Up @@ -818,6 +820,18 @@ where
if self.enabled(Rule::DuplicateBases) {
pylint::rules::duplicate_bases(self, name, bases);
}

if self.enabled(Rule::NoSlotsInStrSubclass) {
flake8_slots::rules::no_slots_in_str_subclass(self, stmt, class_def);
}

if self.enabled(Rule::NoSlotsInTupleSubclass) {
flake8_slots::rules::no_slots_in_tuple_subclass(self, stmt, class_def);
}

if self.enabled(Rule::NoSlotsInNamedtupleSubclass) {
flake8_slots::rules::no_slots_in_namedtuple_subclass(self, stmt, class_def);
}
}
Stmt::Import(ast::StmtImport { names, range: _ }) => {
if self.enabled(Rule::MultipleImportsOnOneLine) {
Expand Down
5 changes: 5 additions & 0 deletions crates/ruff/src/codes.rs
Original file line number Diff line number Diff line change
Expand Up @@ -782,6 +782,11 @@ pub fn code_to_rule(linter: Linter, code: &str) -> Option<(RuleGroup, Rule)> {
(Flake8Fixme, "003") => (RuleGroup::Unspecified, rules::flake8_fixme::rules::LineContainsXxx),
(Flake8Fixme, "004") => (RuleGroup::Unspecified, rules::flake8_fixme::rules::LineContainsHack),

// flake8-slots
(Flake8Slots, "000") => (RuleGroup::Unspecified, rules::flake8_slots::rules::NoSlotsInStrSubclass),
(Flake8Slots, "001") => (RuleGroup::Unspecified, rules::flake8_slots::rules::NoSlotsInTupleSubclass),
(Flake8Slots, "002") => (RuleGroup::Unspecified, rules::flake8_slots::rules::NoSlotsInNamedtupleSubclass),

_ => return None,
})
}
3 changes: 3 additions & 0 deletions crates/ruff/src/registry.rs
Original file line number Diff line number Diff line change
Expand Up @@ -137,6 +137,9 @@ pub enum Linter {
/// [flake8-self](https://pypi.org/project/flake8-self/)
#[prefix = "SLF"]
Flake8Self,
/// [flake8-slots](https://pypi.org/project/flake8-slots/)
#[prefix = "SLOT"]
Flake8Slots,
/// [flake8-simplify](https://pypi.org/project/flake8-simplify/)
#[prefix = "SIM"]
Flake8Simplify,
Expand Down
27 changes: 27 additions & 0 deletions crates/ruff/src/rules/flake8_slots/mod.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
//! Rules from [flake8-slots](https://pypi.org/project/flake8-slots/).
pub(crate) mod rules;

#[cfg(test)]
mod tests {
use std::path::Path;

use anyhow::Result;
use test_case::test_case;

use crate::registry::Rule;
use crate::test::test_path;
use crate::{assert_messages, settings};

#[test_case(Rule::NoSlotsInStrSubclass, Path::new("SLOT000.py"))]
#[test_case(Rule::NoSlotsInTupleSubclass, Path::new("SLOT001.py"))]
#[test_case(Rule::NoSlotsInNamedtupleSubclass, Path::new("SLOT002.py"))]
fn rules(rule_code: Rule, path: &Path) -> Result<()> {
let snapshot = format!("{}_{}", rule_code.noqa_code(), path.to_string_lossy());
let diagnostics = test_path(
Path::new("flake8_slots").join(path).as_path(),
&settings::Settings::for_rule(rule_code),
)?;
assert_messages!(snapshot, diagnostics);
Ok(())
}
}
27 changes: 27 additions & 0 deletions crates/ruff/src/rules/flake8_slots/rules/helpers.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
use rustpython_parser::ast::{self, Expr, Stmt};

/// Return `true` if the given body contains a `__slots__` assignment.
pub(super) fn has_slots(body: &[Stmt]) -> bool {
for stmt in body {
match stmt {
Stmt::Assign(ast::StmtAssign { targets, .. }) => {
for target in targets {
if let Expr::Name(ast::ExprName { id, .. }) = target {
if id.as_str() == "__slots__" {
return true;
}
}
}
}
Stmt::AnnAssign(ast::StmtAnnAssign { target, .. }) => {
if let Expr::Name(ast::ExprName { id, .. }) = target.as_ref() {
if id.as_str() == "__slots__" {
return true;
}
}
}
_ => {}
}
}
false
}
10 changes: 10 additions & 0 deletions crates/ruff/src/rules/flake8_slots/rules/mod.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
pub(crate) use no_slots_in_namedtuple_subclass::{
no_slots_in_namedtuple_subclass, NoSlotsInNamedtupleSubclass,
};
pub(crate) use no_slots_in_str_subclass::{no_slots_in_str_subclass, NoSlotsInStrSubclass};
pub(crate) use no_slots_in_tuple_subclass::{no_slots_in_tuple_subclass, NoSlotsInTupleSubclass};

mod helpers;
mod no_slots_in_namedtuple_subclass;
mod no_slots_in_str_subclass;
mod no_slots_in_tuple_subclass;
Original file line number Diff line number Diff line change
@@ -0,0 +1,84 @@
use rustpython_parser::ast;
use rustpython_parser::ast::{Expr, StmtClassDef};

use ruff_diagnostics::{Diagnostic, Violation};
use ruff_macros::{derive_message_formats, violation};
use ruff_python_ast::helpers::identifier_range;
use ruff_python_ast::prelude::Stmt;

use crate::checkers::ast::Checker;
use crate::rules::flake8_slots::rules::helpers::has_slots;

/// ## What it does
/// Checks for subclasses of `collections.namedtuple` that lack a `__slots__`
/// definition.
///
/// ## Why is this bad?
/// In Python, the `__slots__` attribute allows you to explicitly define the
/// attributes (instance variables) that a class can have. By default, Python
/// uses a dictionary to store an object's attributes, which incurs some memory
/// overhead. However, when `__slots__` is defined, Python uses a more compact
/// internal structure to store the object's attributes, resulting in memory
/// savings.
///
/// Subclasses of `namedtuple` inherit all the attributes and methods of the
/// built-in `namedtuple` class. Since tuples are typically immutable, they
/// don't require additional attributes beyond what the `namedtuple` class
/// provides. Defining `__slots__` for subclasses of `namedtuple` prevents the
/// creation of a dictionary for each instance, reducing memory consumption.
///
/// ## Example
/// ```python
/// from collections import namedtuple
///
///
/// class Foo(namedtuple("foo", ["str", "int"])):
/// pass
/// ```
///
/// Use instead:
/// ```python
/// from collections import namedtuple
///
///
/// class Foo(namedtuple("foo", ["str", "int"])):
/// __slots__ = ()
/// ```
///
/// ## References
/// - [Python documentation: `__slots__`](https://docs.python.org/3.7/reference/datamodel.html#slots)
#[violation]
pub struct NoSlotsInNamedtupleSubclass;

impl Violation for NoSlotsInNamedtupleSubclass {
#[derive_message_formats]
fn message(&self) -> String {
format!("Subclasses of `collections.namedtuple()` should define `__slots__`")
}
}

/// SLOT002
pub(crate) fn no_slots_in_namedtuple_subclass(
checker: &mut Checker,
stmt: &Stmt,
class: &StmtClassDef,
) {
if class.bases.iter().any(|base| {
let Expr::Call(ast::ExprCall { func, .. }) = base else {
return false;
};
checker
.semantic_model()
.resolve_call_path(func)
.map_or(false, |call_path| {
matches!(call_path.as_slice(), ["collections", "namedtuple"])
})
}) {
if !has_slots(&class.body) {
checker.diagnostics.push(Diagnostic::new(
NoSlotsInNamedtupleSubclass,
identifier_range(stmt, checker.locator),
));
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
use rustpython_parser::ast::{Stmt, StmtClassDef};

use ruff_diagnostics::{Diagnostic, Violation};
use ruff_macros::{derive_message_formats, violation};
use ruff_python_ast::helpers::identifier_range;

use crate::checkers::ast::Checker;
use crate::rules::flake8_slots::rules::helpers::has_slots;

/// ## What it does
/// Checks for subclasses of `str` that lack a `__slots__` definition.
///
/// ## Why is this bad?
/// In Python, the `__slots__` attribute allows you to explicitly define the
/// attributes (instance variables) that a class can have. By default, Python
/// uses a dictionary to store an object's attributes, which incurs some memory
/// overhead. However, when `__slots__` is defined, Python uses a more compact
/// internal structure to store the object's attributes, resulting in memory
/// savings.
///
/// Subclasses of `str` inherit all the attributes and methods of the built-in
/// `str` class. Since strings are typically immutable, they don't require
/// additional attributes beyond what the `str` class provides. Defining
/// `__slots__` for subclasses of `str` prevents the creation of a dictionary
/// for each instance, reducing memory consumption.
///
/// ## Example
/// ```python
/// class Foo(str):
/// pass
/// ```
///
/// Use instead:
/// ```python
/// class Foo(str):
/// __slots__ = ()
/// ```
///
/// ## References
/// - [Python documentation: `__slots__`](https://docs.python.org/3.7/reference/datamodel.html#slots)
#[violation]
pub struct NoSlotsInStrSubclass;

impl Violation for NoSlotsInStrSubclass {
#[derive_message_formats]
fn message(&self) -> String {
format!("Subclasses of `str` should define `__slots__`")
}
}

/// SLOT000
pub(crate) fn no_slots_in_str_subclass(checker: &mut Checker, stmt: &Stmt, class: &StmtClassDef) {
if class.bases.iter().any(|base| {
checker
.semantic_model()
.resolve_call_path(base)
.map_or(false, |call_path| {
matches!(call_path.as_slice(), ["" | "builtins", "str"])
})
}) {
if !has_slots(&class.body) {
checker.diagnostics.push(Diagnostic::new(
NoSlotsInStrSubclass,
identifier_range(stmt, checker.locator),
));
}
}
}
Loading

0 comments on commit 945e923

Please sign in to comment.