Skip to content

Rule suggestion: require direct imports within a package instead of importing through re-exports #4491

Description

@gorewilliams

Following up on astral-sh/ruff#19559, where @ntBre suggested opening a ty issue to discuss this.

I’d like an opt-in rule that discourages modules within a package from importing symbols through that package’s re-exports, requiring imports from the defining module instead.

When writing packages, I often re-export functions and classes in __init__.py to provide a convenient public API. Those imports are useful for external consumers, but using them internally can introduce circular imports and make dependencies harder to follow.

For example:

  • supercoolpkg/http_error.py defines HTTPError.
  • supercoolpkg/__init__.py explicitly re-exports it with from .http_error import HTTPError as HTTPError.
  • supercoolpkg/http_client.py imports it with from supercoolpkg import HTTPError.

The proposed rule would flag the import in http_client.py and suggest from supercoolpkg.http_error import HTTPError. External consumers could continue using from supercoolpkg import HTTPError.

This differs from #200, which proposes an implicit-reexport rule for runtime files. Here, the re-export is explicit and intentional: the goal is to discourage internal use of it, regardless of whether it is declared through a redundant alias or __all__.

Would this make sense as a separate opt-in rule in ty?

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    importsModule resolution, site-packages discovery, import-related diagnosticslintLabel for features that we would implement as lint rules, not core type checker features

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions