Skip to content

F401: Improve message for attempted re-export of symbols in __init__ files  #5697

@duckinator

Description

@duckinator

Problem

A pattern I frequently use is to have __init__.py re-export __version__ from elsewhere, and run the release process whenever that file is modified on the main branch.

If I have __version__ = '1.2.3' directly in __init__.py, it's fine. If I do from .version import __version__, ruff complains about it being unused.

The real-world example where I encountered this is duckinator/bork.

Code

In blah/version.py:

__version__ = '1.2.3'

In blah/__init__.py:

from .version import __version__

Command & Output

The testcase consists of nothing but blah/version.py, blah/__init__.py.

puppy@orthrus.fox:~/ruff-testcase$ tree -a
.
└── blah
    ├── __init__.py
    └── version.py

2 directories, 2 files
puppy@orthrus.fox:~/ruff-testcase$ python3 -m venv ./venv && . venv/bin/activate && pip3 install ruff
Collecting ruff
  Using cached ruff-0.0.277-py3-none-freebsd_13_1_RELEASE_p6_amd64.whl
Installing collected packages: ruff
Successfully installed ruff-0.0.277

[notice] A new release of pip is available: 23.0.1 -> 23.1.2
[notice] To update, run: pip install --upgrade pip
(venv) puppy@orthrus.fox:~/ruff-testcase$ ruff --version
ruff 0.0.277
(venv) puppy@orthrus.fox:~/ruff-testcase$ cat blah/__init__.py
from .version import __version__
(venv) puppy@orthrus.fox:~/ruff-testcase$ cat blah/version.py
__version__ = '1.2.3'
(venv) puppy@orthrus.fox:~/ruff-testcase$ ruff check --isolated --select F401 blah/
blah/__init__.py:1:22: F401 [*] `.version.__version__` imported but unused
Found 1 error.
[*] 1 potentially fixable with the --fix option.
(venv) puppy@orthrus.fox:~/ruff-testcase$ 

Workaround

Just slap # noqa: F401 at the end of the line:

from .version import __version__  # noqa: F401

I feel like this shouldn't be necessary, though, which is why I opened this issue.

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions