Jump to content

Connect SuperML | Leeroopedia MCP: Equip your AI agents with best practices, code verification, and debugging knowledge. Powered by Leeroo — building Organizational Superintelligence. Contact us at founders@leeroo.com.

Implementation:Huggingface Transformers Custom Init Isort

From Leeroopedia
Knowledge Sources
Domains Code_Quality, Import_System
Last Updated 2026-02-13 20:00 GMT

Overview

Concrete tool for sorting imports in the custom _import_structure dictionaries within Transformers __init__.py files.

Description

The custom_init_isort.py utility parses each __init__.py file that contains _import_structure, splits the code into indented blocks between the structure definition and TYPE_CHECKING, identifies dictionary keys (module names) via regex, sorts them alphabetically, and sorts the imported object names within each key following isort conventions (constants first, then classes, then functions, all case-insensitive). Standard isort/ruff tools cannot sort the custom _import_structure dictionary format used for delayed imports, making this utility necessary.

Usage

Run via make style to auto-sort init imports, or via make check-repo for validation-only mode.

Code Reference

Source Location

Signature

def sort_objects(objects: List[str]) -> List[str]:
    """Sort object names following isort conventions."""

def sort_objects_in_import(import_block: str) -> str:
    """Sort objects within a single _import_structure key."""

def sort_imports(init_content: str) -> str:
    """Sort all imports in an __init__.py file content string."""

def sort_imports_in_all_inits(check_only: bool = False) -> List[str]:
    """Sort imports across all Transformers __init__.py files."""

Import

python utils/custom_init_isort.py
python utils/custom_init_isort.py --check_only

I/O Contract

Inputs

Name Type Required Description
src/transformers/**/__init__.py Python files Yes Init files with _import_structure to sort
--check_only flag No Validate without modifying files

Outputs

Name Type Description
Sorted files Python files Init files with sorted _import_structure (unless --check_only)
Error report stdout Files that need sorting (if --check_only)

Usage Examples

Sorting Init Imports

# Sort all init files
python utils/custom_init_isort.py

# Check only (CI mode)
python utils/custom_init_isort.py --check_only

# Via Makefile
make style       # sorts
make check-repo  # checks

Related Pages

Page Connections

Double-click a node to navigate. Hold to expand connections.
Principle
Implementation
Heuristic
Environment