Skip to content

module-import-not-at-top-of-file ignore after sys.path.insert #5557

@tgross35

Description

@tgross35

Sometimes you need to insert a path to be able to import something that's out of scope from your current file - in which case, the imports must come after the insert statement. For example, from Rust's repo:

from __future__ import absolute_import, division, print_function
import os
import unittest
# ...

bootstrap_dir = os.path.dirname(os.path.abspath(__file__))
sys.path.insert(0, bootstrap_dir)
import bootstrap # noqa: E402
import configure # noqa: E402

My suggestion is to ignore E402 module-import-not-at-top-of-file if it comes after a sys.path.insert statement.

There are legitimate uses of sys.path.insert, but it could be considered a hack or pitfall for new users - so I could understand potentially not wanting this behavior as the default. If this is the case, I would propose one of the following:

  • Create a configuration option such as ignore-after-sys-path-insert
  • Do this change as suggested, but create a separate lint that checks for sys.path.insert usage. The lint could theoretically be kind of smart and suggest possible alternatives for common misuses (adding __init__.py, importing directly, etc) but that kind of gets into evaluating the context

Metadata

Metadata

Assignees

No one assigned

    Labels

    needs-decisionAwaiting a decision from a maintainerruleImplementing or modifying a lint rule

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions