astral-sh / ruff

An extremely fast Python linter and code formatter, written in Rust.
https://docs.astral.sh/ruff
MIT License
32.38k stars 1.08k forks source link

[Proposal] Mirror isort's float-to-top feature to autofix simple cases of E402 #6514

Open SummerStorm opened 1 year ago

SummerStorm commented 1 year ago

Minimal reproducible example

a = 1
import os 

Ruff output and Ruff version

$ ruff -V && ruff -v --ignore F401 --diff E402_violation.py
ruff 0.0.283
[2023-08-11][15:48:25][ruff_cli::resolve][DEBUG] Using Ruff default settings
[2023-08-11][15:48:25][ruff_cli::commands::run][DEBUG] Identified files to lint in: 1.5035ms
[2023-08-11][15:48:25][ruff_cli::diagnostics][DEBUG] Checking: /tmp/E402_violation.py
[2023-08-11][15:48:25][ruff_cli::commands::run][DEBUG] Checked 1 files in: 930.5µs

isort output (and expected Ruff output)

$ isort --float-to-top -diff E402_violation.py
import os

a = 1

isort has a useful float_to_top config where all non-indented imports are "floated" to the top of the file. I find this quite useful as I can import anywhere within the file, and the import will automatically "float" to the correct location. I propose that we add a float-to-top flag to mirror this behavior:

[tool.ruff.isort] 
float-to-top = true 

By enabling this flag, the user is signaling to Ruff that it should autofix all such trivial cases of E402. While E402 is impossible to fix in general, I believe that non-indented cases of E402 are autofixable in the vast majority of projects. Here are two cases where re-positioning non-indented imports might break things:

import sys
sys.path.append(some_module_path)
import some_module
import os
os.environ['LIB_CAN_THROW_ERROR_ON_IMPORT'] = 2
import lib
os.environ['LIB_CAN_THROW_ERROR_ON_IMPORT'] = 0 
charliermarsh commented 1 year ago

We definitely can fix this but for the reasons you describe it should probably be an opt-in fix once that feature ships.

SummerStorm commented 1 year ago

We definitely can fix this but for the reasons you describe it should probably be an opt-in fix once that feature ships.

Yes, I agree. The user must opt-in via some new flag such as:

[tool.ruff.isort] 
float-to-top = true 
adamstirk-ct commented 6 months ago

Is there any news on getting float-to-top added?