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.
You can find the scripts and code for this course within the Automating Python Code Quality repo.

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

By default:

  • 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: re, os, etc.

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/
--- original/001_formatters/
+++ fixed/001_formatters/
@@ -1,7 +1,6 @@
 from rich import inspect
-import re
 # from math import *
Ready to Master Network Automation? Start Your Journey Today!
Our membership provides:
  • Full deep-dive course library (inc. Batfish, pyATS, Netmiko)
  • Code repositories inc. full course code, scripts and examples
  • 24x7 multi-vendor labs (Arista, Cisco, Juniper)
  • Private online community
  • Live monthly tech sessions
  • Access to tech session library

Join Now ➜
Close You've successfully subscribed to Packet Coders.
Close Success! Your account is fully activated, you now have access to all content.
Close Welcome back! You've successfully signed in.
Close Nearly there! To activate your account, please click the link in the email we just sent you.