PIP-Talk - Week 48

The topic for this week is: Refurb

Looking for a tool to help you with refurbishing and modernizing your Python codebases ? Then you will find this piptalk especially interesting.


Background

Lots of static analysis tools already exist, but none of them seem to be focused on making code more elegant, more readable, or more modern. That is where Refurb comes in.

Refurb is not a style/type checker. It is not meant as a first-line of defense for linting and finding bugs, it is meant for making good code even better.

Note: Refurb only supports Python 3.10. It can check Python 3.6 code and up, but Refurb itself must be ran through Python 3.10.

Licence: GPL-3.0


Example

Refurb is super easy to use. Just enter refurb <filename.py> or refurb <folder> to check the specified file/folder. Refurb will then analyze your code and suggest improvements.

The suggest improvements are easy to find and understand. You will get a reference to the source file and the concerned line of code.

Here is a simple output of some code:

refurb raw_storage/
...
raw_storage/raw_storage.py:81:24 [FURB108]: Replace `x == y or z == y` with `y in (x, z)`
raw_storage/raw_storage.py:205:43 [FURB119]: Replace `{str(x)}` with `{x}`
raw_storage/raw_storage.py:208:21 [FURB119]: Replace `{str(x)}` with `{x}`
raw_storage/raw_storage.py:208:21 [FURB119]: Replace `{str(x)}` with `{x}`

The actual code snippet that refurb is refering to:

parts = file.split(delimiter)
    if parts[-3] == '' or parts[-2] == '':
       ....

If you dont understand the result or find the result vague, you could lookup the refurb code to get a better explanation of the result.

refurb --explain FURB108  
                                                                         
When comparing a value to multiple possible options, don't use multiple
`or` checks, use a single `in` expr:

Bad:

if x == "abc" or x == "def":
    pass

Good:

if x in ("abc", "def"):
    pass

Summary

Refurb is a handy little tool that can help you to write better and a more pythonic code. ItÅ› also a great way to educate about new features in the python language, that you could have missed or forgotten


Install

pip install refurb

or

pipx install refurb

Sources