astral-sh / ruff

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

Possible error when trying to fix with ICN001 #14439

Open tpgillam opened 2 hours ago

tpgillam commented 2 hours ago

I obtain errors with ICN001 when trying to apply autofix (in 'unsafe' mode) that should ideally convert the import from from A1.A2.AN import B to import A1.A2.AN.

For example, consider the following simple source file moo.py:

from math import sin

sin(42)

And then the following configuration for ruff in pyproject.toml

[project]
name = "moo"
version = "0.1.0"
readme = "README.md"
requires-python = ">=3.13"
dependencies = [
    "ruff>=0.7.4",
]

[tool.ruff.lint]
select = ["ICN001"]

[tool.ruff.lint.flake8-import-conventions.aliases]
"math.sin" = "math.sin"

I get the following error:

> uv run ruff check --fix --unsafe-fixes moo.py
error: Fix introduced a syntax error. Reverting all changes.

This indicates a bug in Ruff. If you could open an issue at:

    https://github.com/astral-sh/ruff/issues/new?title=%5BFix%20error%5D

...quoting the contents of `moo.py`, the rule codes ICN001, along with the `pyproject.toml` settings and executed command, we'd be very appreciative!

moo.py:1:18: ICN001 `math.sin` should be imported as `math.sin`
  |
1 | from math import sin
  |                  ^^^ ICN001
2 |
3 | sin(42)
  |
  = help: Alias `math.sin` to `math.sin`

Found 1 error.
[*] 1 fixable with the --fix option.

I'm not 100% sure that I'm not abusing the intention of this rule, since here I'm trying to use the rule to enforce the absence of an alias, rather than a conventional alias :)

dylwil3 commented 2 hours ago

Interesting... I think this is not quite what ICN001 was designed for. It's not possible to import (and then alias) a function like import mymodule.myfunction, which is what your user configuration is asking ICN001 to do.

Were you maybe looking for something like ICN003?