Handy tool: pyupgrade

Tags: python, django, plone

An advantage of open source is that, ideally, you get to work with other programmers from different companies and different backgrounds and different toolchains. They do things differently and so you can pick out the choice bits and start using them yourself.

As an example, z3c.dependencychecker. A small tool I started in 2009 based on someone else’s script. The goal is to look at all the imports in your python code (or apps in django settings files or…) and compare them to the list of requirements in setup.py. What’s missing? What can be removed?

The last few weeks, gforcada did some nice modernization/cleanup. Removing support for older python versions, for instance. And a move from travis-ci to github actions. So I looked at the new action workflow and saw something new. Black, isort, flake8: I know and use them. But pyupgrade? What is that?

That’s how I discovered pyupgrade. Handy tool to upgrade your code to newer python versions. By default, it removes python 2.x stuff that is no longer needed, like # -*- coding: utf-8 -*- at the top of your file. super() calls no longer need to mention the super class. The is not that flake8 tells you to fix. That sort of thing.

pyupgrade --py38-plus upgrades your code to 3.8 (same kind of commands for other versions). So f-strings will be used. assertEqual/assertEquals. Dict comprehensions.

Real handy to quickly clean up your code! Recommended.

Update: Christian Ledermann pointed me at https://github.com/charliermarsh/ruff . Ruff implements a lot of the pyupgrade functionality (and flake8, bugbear, eradicate and lots of the other tools). And it is faaaaaast. I toyed with it in a personal project and it fixed quite some things. The only pyupgrade-related item I missed was the conversion to f-strings. But that will probably be added later.

 
vanrees.org logo

About me

My name is Reinout van Rees and I work a lot with Python (programming language) and Django (website framework). I live in The Netherlands and I'm happily married to Annie van Rees-Kooiman.

Weblog feeds

Most of my website content is in my weblog. You can keep up to date by subscribing to the automatic feeds (for instance with Google reader):