Skip to content

unused-import (F401)#

Derived from the Pyflakes linter.

Fix is sometimes available.

What it does#

Checks for unused imports.

Why is this bad?#

Unused imports add a performance overhead at runtime, and risk creating import cycles. They also increase the cognitive load of reading the code.

If an import statement is used to check for the availability or existence of a module, consider using importlib.util.find_spec instead.

If an import statement is used to re-export a symbol as part of a module's public interface, consider using a "redundant" import alias, which instructs Ruff (and other tools) to respect the re-export, and avoid marking it as unused, as in:

from module import member as member

Fix safety#

When ignore_init_module_imports is disabled, fixes can remove for unused imports in __init__ files. These fixes are considered unsafe because they can change the public interface.

Example#

import numpy as np  # unused import


def area(radius):
    return 3.14 * radius**2

Use instead:

def area(radius):
    return 3.14 * radius**2

To check the availability of a module, use importlib.util.find_spec:

from importlib.util import find_spec

if find_spec("numpy") is not None:
    print("numpy is installed")
else:
    print("numpy is not installed")

Options#

References#