Neovim for Beginners — Python Code Refactoring

Use Neovim and Refurb to modernize our Python codebase.

4 min readOct 8, 2022


Neovim for Beginners — Python Code Refactoring

In this article, let’s learn how to refactor and modernize our Python codebase. For general refactoring techniques, do check out the previous Neovim for Beginners — Refactoring article.

This article is part of the Neovim for Beginners series.

The Neovim configuration files are available in this repository.

Getting Started

As the Python programming language evolves over the years, our existing codebase could be obsolete. The newer version of Python could also provide better or more performing APIs that we can leverage.

Refurb is a Python tool for refurbishing and modernizing Python codebases. It can make the codebase more elegant, and modern.

We can install it using pip.

$ pip3 install refurb

E.g., below is a sample output by Refurb.

$ refurb [FURB109]: Use `in (x, y, z)` instead of `in [x, y, z]` [FURB101]: Use `y = Path(x).read_text()` instead of `with open(x, ...) as f: y =` [FURB102]: Replace `x.startswith(y) or x.startswith(z)` with `x.startswith((y, z))` [FURB105]: Use `print() instead of `print("")`

Refurb inspects the codebase and suggests how we can modernize the code.

Let’s explore different options to integrate Refurb with Neovim.

Quickfix List

Using the quickfix list, we can easily integrate Refurb with Neovim.

We can create a quickfix list using the :cexpr (:h :cexpr) command.

Using the command below, we create a quickfix list and populate it with the result of running Refurb on the current file. We open the quickfix list immediately once it is opened.

:cexpr system("refurb --quiet " . shellescape(expand("%"))) | copen

In the lua/config/whichkey.lua file, we add a keymapping when the file type is Python.




Software engineer, Data Science and ML practitioner.