This lesson is part of the Automating Python Code Quality course.
In this lesson, you will learn,
- what autoflake is
- how to install autoflake
- how to use autoflake to remove unused imports
- how to use autoflake to remove unused variables.
What is autoflake?
autoflake is a tool that removes unused variables and unused imports from your Python code.
How to Install autoflake
To install autoflake, perform the following:
poetry add -D autoflake
autoflake can be run recursively (via
-r), or against a file. Examples of each are shown below:
$ autoflake -r . $ autoflake -r dir/* $ autoflake myfile.py
- autoflake only provides a diff of the purposed change (no changes are applied).
- autoflake only removes unused imports for modules that are part of the standard library:
For example, let’s say we have the following rouge Python script.
from rich import inspect import re # from math import * def example_function(): unused_var = "xyz" return True
If we were to run autoflake against it, we would get a result showing there was an issue with the file, and what would have been changed:
❯ autoflake 001_formatters/003_autoflake.py --- original/001_formatters/003_autoflake.py +++ fixed/001_formatters/003_autoflake.py @@ -1,7 +1,6 @@ from rich import inspect -import re # from math import *