Avoid Wildcard (Star) Imports

ID

python.avoid_star_import

Severity

low

Remediation Complexity

medium

Remediation Risk

low

Remediation Effort

medium

Resource

Code Smell

Language

Python

Tags

code-style, imports

Description

Reports from module import * statements. Wildcard imports pull every public name from the module into the current namespace, which makes it impossible to tell where a name came from when reading the file, masks shadowing bugs (a later wildcard import silently overrides an earlier one), and breaks static analysis tools that try to resolve undefined names.

from os import *           # FLAW
from .util import *        # FLAW

from os import path        # OK — explicit
import os                  # OK

Rationale

A reader of the file cannot tell whether an unfamiliar name comes from the local module, a wildcard-imported module, or is just undefined. Tooling has the same problem: type checkers, IDE go-to-definition, and undefined-name detection all degrade when wildcards are present.

A subset of cases — re-exporting from init.py — are arguably defensible, but they are usually better expressed via all plus explicit imports.

Remediation

Bind the names you actually use:

from os.path import join, dirname, basename

For re-export scenarios, declare all and import the names explicitly:

from .util import helper, validate
__all__ = ["helper", "validate"]

References