In this post, I wanted to share with you a tool that I've started to use more and more when working with Python, and that is AutoFlake. In a nutshell, AutoFlake is:
a tool that removes unused variables and unused imports from your Python code.
In other words, by cleaning up your code it makes it easier to read and maintain. Which overall improves your code quality, and will help you in getting your code to production grade.
Let's dive in...
$ pip install autoflake
Let's now run AutoFlake against a Python file. First, let's see the file before running AutoFlake.
$ cat test.py from pybatfish.client.asserts import * import re import rich def test_assert_no_duplicate_router_ids(bf_init): stale_variable = "xyz" assert assert_no_duplicate_router_ids(session=bf_init)
The options and syntax will be:
$ autoflake -i test.py \ --expand-star-imports \ --remove-unused-variables \ --remove-all-unused-imports
The options used are pretty self-explanatory. The only point to make is around
-i, which is for
in-place and tells AutoFlake to make the changes to the files.
After running AutoFlake we will now see our Python file has been updated (below). Good stuff.
from pybatfish.client.asserts import assert_no_duplicate_router_ids, assert_no_forwarding_loops, assert_no_incompatible_bgp_sessions, assert_no_incompatible_ospf_sessions, assert_no_unestablished_bgp_sessions def test_assert_no_duplicate_router_ids(bf_init): assert assert_no_duplicate_router_ids(session=bf_init)
Further formatting can then be applied via isort and black. In our case/example, to ensure the imports are ordered correctly and the imports are split across multiple lines.