astral-sh / ruff

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

Converting `__file__` to a named path variable triggers E402 #13303

Open ncoghlan opened 1 week ago

ncoghlan commented 1 week ago

While the E402 detection makes some allowances for sys.path manipulation, it still doesn't like it if __file__ gets assigned to a variable, as in code like:

_THIS_DIR = Path(__file__).parent
_REPO_DIR = _THIS_DIR.parent

if find_spec("some_project_module") is None:
    sys.path.append(str(_REPO_DIR / "src"))
from some_project_module import relevant_api

This inline version is correctly detected as permitted sys.path manipulation:

if find_spec("some_project_module") is None:
    sys.path.append(str(Path(__file__).parent.parent / "src"))
from some_project_module import relevant_api

While #noqa: E402 makes the error go away in the first case, it doesn't seem right that it triggers a lint error while the more cryptic inline version gets a free pass. At the same time, tracing and allowing __file__ manipulation would presumably be difficult, so wontfix may be the right response here.

MichaReiser commented 1 week ago

Thanks for opening this. We may bel able to do better here once Ruff uses type inference.