refactor: replace wildcard imports with explicit imports in model __init__.py files#45452
refactor: replace wildcard imports with explicit imports in model __init__.py files#45452DavidSolanas wants to merge 2 commits into
Conversation
…nit__.py files Closes huggingface#45306
|
[For maintainers] Suggested jobs to run (before merge) run-slow: afmoe, aimv2, albert, align, altclip, apertus, arcee, aria, audio_spectrogram_transformer, audioflamingo3, auto, autoformer, aya_vision, bamba, bark, bart |
|
I'm not very knowledgeable about mypy, but this seems redundant to me: we're already defining in each module's For models specifically this was always a feature more than a bug: any object in the model module's |
|
Since my issue has been mentioned here: From my personal point of view, I believe that There is an even more extreme idea: Since the |
Fixes #45306
What and why
All
models/X/__init__.pyfiles usedfrom .module import *inside theTYPE_CHECKINGblock. This makes it impossible for static analysis tools(pyright, mypy, IDEs) to know which symbols are actually exported, and
creates silent namespace pollution risks.
This PR replaces every wildcard import with an explicit one derived from
the submodule's
__all__.Before (
models/bert/__init__.py):After:
How
The fix was generated mechanically: for each
models/X/__init__.py,parse the
TYPE_CHECKINGblock, read__all__from the referencedsubmodule, and emit an explicit import. Runtime behavior is completely
unchanged — only the
TYPE_CHECKINGbranch (used by type checkers, notat runtime) is affected.
Scope
__init__.pyfiles updatedsrc/transformers/models/__init__.pyandsrc/transformers/__init__.py(top-level aggregators) are out of scope — those require a separate
discussion about how the public namespace is defined
tests/utils/test_file_utils.py:23(from transformers import *) isintentional and left untouched
Known gaps (follow-up candidates)
A small number of wildcard imports could not be resolved automatically and
were left as-is:
tokenization_bloom.py,feature_extraction_detr.py)__all__(e.g.generation_dia.py, conversion scripts likeconvert_funnel_original_tf_checkpoint_to_pytorch.py)These can be addressed in follow-up PRs once the owning teams decide how
to handle them.
Testing