ruff: False positive for unused import when bringing things forward in __init__.py
In myapp/forms/__init__.py:
from .login import LoginForm
In myapp/views/auth.py:
from myapp.forms import LoginForm`
ruff says that LoginForm in forms/__init__.py is unused, it’s totally wrong because views/auth.py imports and uses it
About this issue
- Original URL
- State: open
- Created 3 years ago
- Reactions: 1
- Comments: 21 (10 by maintainers)
I simply don’t think it’s a bug, I always define an
__all__in my__init__.pyfiles and it’s helpful to know I missed an object somewhere.Hey @robvdl thanks for the report. Unfortunately we don’t track imports across files, so the assumption is that you either disable
F401in__init__.pyfiles, or use some other mechanism to make it explicit that this is a re-export – for example, adding to__all__, or using the re-export convention offrom .login import LoginForm as LoginForm. (I know you already heard some of this above, but perhaps the re-export convention will be interesting to you.)Ideally we would be able to track these across files, so it’s fine to call it a bug (and we’re planning to explore multi-file analysis over the next few months). The only caveat is that… even then it’s not totally clear that it’d be safe to remove
from .login import Login, since you’re defining a public interface, and you could have users of your package that rely onLoginbeing exported there.As an aside, PyFlakes would also flag this. I’m not sure how you tested it, but PyFlakes doesn’t look across files either:
Regardless, thanks for the report! That we don’t detect these across files is a limitation.
Sorry I’m trying to legitimately report a bug here and I felt I was getting fight back, I didn’t realise you weren’t official devs.
It’s correct that it’s unused in
myapp/forms/__init__.py. The fix would be to define a__all__list/tuple in there too (as Ruff treats that as usage):I’m surprised to not see anyone mention of
Which is a canonical way to mark intended re-exports that type-checkers understand, and especially popular in stubs Edit: I missed Charlie did mention it in https://github.com/astral-sh/ruff/issues/10253#issuecomment-1981682998
That way you don’t have to explicitly list and maintain all names in
__all__Of course if you use useless-import-alias (PLC0414) now that will trigger, so you have to do:
So yeah, feel free to choose how you want to handle your package re-exports, and ignore the relevant code for
__init__.pyfiles.As long as it’s an option, I’d still prefer being explicit about my intended re-exports.
Ruff doesn’t support multifile analysis yet but we’re working towards bringing this capability to Ruff. But it will take a while and we then also have to change this specific rule implementation. TLDR: We’re moving toward a fix but it is a rather large undertaking.
Thank you, yeah in the mean time I have gone with the
__all__method which I am a little more comfortable with than doing something like this:I’ll leave it at that.