Removes unused imports and unused variables from Python code
—
Quality
Pending
Does it follow best practices?
Impact
Pending
No eval scenarios have been run
Core functionality for analyzing Python code with pyflakes and applying transformations to remove unused imports and variables. These functions form the heart of autoflake's code cleanup capabilities.
High-level functions that combine analysis and transformation to clean Python source code.
def fix_code(
source: str,
additional_imports: Iterable[str] | None = None,
expand_star_imports: bool = False,
remove_all_unused_imports: bool = False,
remove_duplicate_keys: bool = False,
remove_unused_variables: bool = False,
remove_rhs_for_unused_variables: bool = False,
ignore_init_module_imports: bool = False,
ignore_pass_statements: bool = False,
ignore_pass_after_docstring: bool = False
) -> str:
"""
Returns source code with unused imports and variables removed.
This is the main processing function that applies all filtering operations
to clean up Python source code while preserving structure and functionality.
Args:
source: Python source code to process
additional_imports: Iterable of modules to consider as unused imports
expand_star_imports: Replace star imports with specific imports
remove_all_unused_imports: Remove all unused imports, not just standard library
remove_duplicate_keys: Remove duplicate keys in dictionaries/sets
remove_unused_variables: Remove unused variable assignments
remove_rhs_for_unused_variables: Remove right-hand side of unused variable assignments
ignore_init_module_imports: Skip import removal in __init__.py files
ignore_pass_statements: Don't remove pass statements
ignore_pass_after_docstring: Don't remove pass after docstrings
Returns:
Cleaned source code as string
"""def filter_code(
source: str,
additional_imports: Iterable[str] | None = None,
expand_star_imports: bool = False,
ignore_init_module_imports: bool = False,
remove_all_unused_imports: bool = False,
remove_duplicate_keys: bool = False,
remove_unused_variables: bool = False,
remove_rhs_for_unused_variables: bool = False
) -> Iterable[str]:
"""
Yields lines of code with unused imports and variables removed.
Lower-level function that yields processed lines. Used internally by fix_code
but can be used directly for streaming processing of large files.
Args:
source: Python source code to process
additional_imports: Additional modules to remove
expand_star_imports: Replace star imports with specific imports
ignore_init_module_imports: Skip removal in __init__.py files
remove_all_unused_imports: Remove all unused imports
remove_duplicate_keys: Remove duplicate dictionary keys
remove_unused_variables: Remove unused variables
remove_rhs_for_unused_variables: Remove right-hand side of unused variable assignments
Yields:
Processed source code lines
"""Functions for analyzing Python source code to identify unused imports, variables, and other cleanup opportunities.
def check(source: str) -> Iterable[pyflakes.messages.Message]:
"""
Returns pyflakes messages for the given source code.
Provides direct access to pyflakes analysis results for custom processing
or integration with other tools.
Args:
source: Python source code to analyze
Returns:
Iterator of pyflakes Message objects describing issues found
"""Functions that extract specific information from pyflakes analysis results.
def unused_import_line_numbers(
messages: Iterable[pyflakes.messages.Message]
) -> Iterable[int]:
"""
Yields line numbers of unused imports from pyflakes messages.
Args:
messages: Pyflakes messages from code analysis
Yields:
Line numbers containing unused imports
"""def unused_import_module_name(
messages: Iterable[pyflakes.messages.Message]
) -> Iterable[tuple[int, str]]:
"""
Yields line number and module name of unused imports.
Args:
messages: Pyflakes messages from code analysis
Yields:
Tuples of (line_number, module_name) for unused imports
"""def star_import_used_line_numbers(
messages: Iterable[pyflakes.messages.Message]
) -> Iterable[int]:
"""
Yields line numbers where star imports are used.
Args:
messages: Pyflakes messages from code analysis
Yields:
Line numbers containing star import usage
"""def star_import_usage_undefined_name(
messages: Iterable[pyflakes.messages.Message]
) -> Iterable[tuple[int, str, str]]:
"""
Yields information about undefined names that might come from star imports.
Args:
messages: Pyflakes messages from code analysis
Yields:
Tuples of (line_number, undefined_name, possible_origin_module)
"""def unused_variable_line_numbers(
messages: Iterable[pyflakes.messages.Message]
) -> Iterable[int]:
"""
Yields line numbers of unused variables.
Args:
messages: Pyflakes messages from code analysis
Yields:
Line numbers containing unused variable assignments
"""def duplicate_key_line_numbers(
messages: Iterable[pyflakes.messages.Message],
source: str
) -> Iterable[int]:
"""
Yields line numbers of duplicate keys in dictionaries.
Args:
messages: Pyflakes messages from code analysis
source: Source code being analyzed
Yields:
Line numbers containing duplicate dictionary keys
"""def create_key_to_messages_dict(
messages: Iterable[pyflakes.messages.MultiValueRepeatedKeyLiteral]
) -> Mapping[Any, Iterable[pyflakes.messages.MultiValueRepeatedKeyLiteral]]:
"""
Creates mapping from keys to their duplicate key messages.
Args:
messages: Duplicate key messages from pyflakes
Returns:
Dictionary mapping keys to lists of messages
"""Functions for handling Python pass statements that may become redundant after removing unused code.
def filter_useless_pass(
source: str,
ignore_pass_statements: bool = False,
ignore_pass_after_docstring: bool = False
) -> Iterable[str]:
"""
Yields code with useless 'pass' statements removed.
Removes pass statements that are no longer needed after other code
has been removed, while preserving structurally necessary pass statements.
Args:
source: Python source code to process
ignore_pass_statements: Don't remove any pass statements
ignore_pass_after_docstring: Keep pass statements after docstrings
Yields:
Source code lines with useless pass statements removed
"""
```python { .api }
def useless_pass_line_numbers(
source: str,
ignore_pass_after_docstring: bool = False
) -> Iterable[int]:
"""
Yields line numbers of useless pass statements that can be removed.
Identifies pass statements that serve no structural purpose and can be
safely removed without affecting Python syntax or semantics.
Args:
source: Python source code to analyze
ignore_pass_after_docstring: Don't consider pass after docstrings as useless
Yields:
Line numbers containing useless pass statements
"""Classes that support the analysis and transformation process.
class ListReporter:
"""
Accumulates pyflakes messages in a list for programmatic access.
Inherits from pyflakes.reporter.Reporter and provides a way to collect
all analysis messages for further processing.
"""
def __init__(self) -> None:
"""Initialize the reporter with an empty message list."""
def flake(self, message: pyflakes.messages.Message) -> None:
"""
Add a pyflakes message to the accumulated list.
Args:
message: Pyflakes message to store
"""class FilterMultilineImport:
"""
Handles removal of unused imports from multiline import statements.
This class manages the complex logic needed to properly parse and filter
imports that span multiple lines while preserving proper Python syntax.
"""
def __init__(self, line: str) -> None:
"""
Initialize with the first line of a multiline import.
Args:
line: First line of the multiline import statement
"""
def __call__(self, line: str) -> FilterMultilineImport | str:
"""
Process the next line of the multiline import.
Args:
line: Next line to process
Returns:
Either a string (processed line) or self for continued processing
"""import autoflake
# Clean up simple unused imports
source = '''
import os
import sys
import unused_module
def hello():
print("Hello")
'''
cleaned = autoflake.fix_code(source, remove_all_unused_imports=True)
# Result: Only keeps 'print' and removes unused importsimport autoflake
# Get detailed analysis information
messages = list(autoflake.check(source_code))
unused_imports = list(autoflake.unused_import_line_numbers(messages))
unused_vars = list(autoflake.unused_variable_line_numbers(messages))
print(f"Unused imports on lines: {unused_imports}")
print(f"Unused variables on lines: {unused_vars}")import autoflake
# Advanced cleanup with all options
cleaned = autoflake.fix_code(
source_code,
remove_all_unused_imports=True,
remove_unused_variables=True,
remove_duplicate_keys=True,
expand_star_imports=True,
ignore_pass_after_docstring=True
)Install with Tessl CLI
npx tessl i tessl/pypi-autoflake