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] Implement import-outside-toplevel (C0415) #8298

Closed
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,20 @@
def print_python_version():
import sys # C0415

print(sys.version_info)

def print_python_version():
import sys, string # C0415

print(sys.version_info, string.ascii.digits)

# OK
import sys


def print_python_version():
print(sys.version_info)

# OK
if True:
import sys
3 changes: 3 additions & 0 deletions crates/ruff_linter/src/checkers/ast/analyze/statement.rs
Original file line number Diff line number Diff line change
Expand Up @@ -530,6 +530,9 @@ pub(crate) fn statement(stmt: &Stmt, checker: &mut Checker) {
if checker.enabled(Rule::ModuleImportNotAtTopOfFile) {
pycodestyle::rules::module_import_not_at_top_of_file(checker, stmt);
}
if checker.enabled(Rule::ImportOutsideToplevel) {
pylint::rules::import_outside_toplevel(checker, stmt, names);
}
if checker.enabled(Rule::GlobalStatement) {
for name in names {
if let Some(asname) = name.asname.as_ref() {
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 @@ -211,6 +211,7 @@ pub fn code_to_rule(linter: Linter, code: &str) -> Option<(RuleGroup, Rule)> {
(Pylint, "C0205") => (RuleGroup::Stable, rules::pylint::rules::SingleStringSlots),
(Pylint, "C0208") => (RuleGroup::Stable, rules::pylint::rules::IterationOverSet),
(Pylint, "C0414") => (RuleGroup::Stable, rules::pylint::rules::UselessImportAlias),
(Pylint, "C0415") => (RuleGroup::Preview, rules::pylint::rules::ImportOutsideToplevel),
(Pylint, "C2401") => (RuleGroup::Preview, rules::pylint::rules::NonAsciiName),
(Pylint, "C2403") => (RuleGroup::Preview, rules::pylint::rules::NonAsciiImportName),
#[allow(deprecated)]
Expand Down
1 change: 1 addition & 0 deletions crates/ruff_linter/src/rules/pylint/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -142,6 +142,7 @@ mod tests {
#[test_case(Rule::UnnecessaryLambda, Path::new("unnecessary_lambda.py"))]
#[test_case(Rule::NonAsciiImportName, Path::new("non_ascii_module_import.py"))]
#[test_case(Rule::NonAsciiName, Path::new("non_ascii_name.py"))]
#[test_case(Rule::ImportOutsideToplevel, Path::new("import_outside_toplevel.py"))]
fn rules(rule_code: Rule, path: &Path) -> Result<()> {
let snapshot = format!("{}_{}", rule_code.noqa_code(), path.to_string_lossy());
let diagnostics = test_path(
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
use ruff_diagnostics::{Diagnostic, Violation};
use ruff_macros::{derive_message_formats, violation};
use ruff_python_ast::{Alias, Stmt};
use ruff_text_size::Ranged;

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

/// ## What it does
/// Checks for import statements outside of the module level.
///
/// ## Why is this bad?
/// Module imports should be grouped at the top of the file at the module level
/// as required by PEP-8.
///
/// https://peps.python.org/pep-0008/#imports
#[violation]
pub struct ImportOutsideToplevel {
names: String,
}

impl Violation for ImportOutsideToplevel {
#[derive_message_formats]
fn message(&self) -> String {
let Self { names } = self;
format!("Import outside toplevel ({names})")
}
}

/// C0415
pub(crate) fn import_outside_toplevel(checker: &mut Checker, stmt: &Stmt, names: &[Alias]) {
if !checker.semantic().current_scope().kind.is_module() {
let names: String = names
.iter()
.map(|name| name.name.clone().to_string())
.collect::<Vec<String>>()
.join(", ");

checker.diagnostics.push(Diagnostic::new(
ImportOutsideToplevel { names },
stmt.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 @@ -17,6 +17,7 @@ pub(crate) use eq_without_hash::*;
pub(crate) use global_at_module_level::*;
pub(crate) use global_statement::*;
pub(crate) use global_variable_not_assigned::*;
pub(crate) use import_outside_toplevel::*;
pub(crate) use import_self::*;
pub(crate) use invalid_all_format::*;
pub(crate) use invalid_all_object::*;
Expand Down Expand Up @@ -85,6 +86,7 @@ mod eq_without_hash;
mod global_at_module_level;
mod global_statement;
mod global_variable_not_assigned;
mod import_outside_toplevel;
mod import_self;
mod invalid_all_format;
mod invalid_all_object;
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
---
source: crates/ruff_linter/src/rules/pylint/mod.rs
---
import_outside_toplevel.py:2:5: PLC0415 Import outside toplevel (sys)
|
1 | def print_python_version():
2 | import sys # C0415
| ^^^^^^^^^^ PLC0415
3 |
4 | print(sys.version_info)
|

import_outside_toplevel.py:7:5: PLC0415 Import outside toplevel (sys, string)
|
6 | def print_python_version():
7 | import sys, string # C0415
| ^^^^^^^^^^^^^^^^^^ PLC0415
8 |
9 | print(sys.version_info, string.ascii.digits)
|


1 change: 1 addition & 0 deletions ruff.schema.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Loading