A tool to automatically convert old string literal formatting to f-strings

Overview

flynt - string formatting converter

Build Status Coverage PyPI version Downloads Code style: black

flynt is a command line tool to automatically convert a project's Python code from old "%-formatted" and .format(...) strings into Python 3.6+'s "f-strings".

F-Strings:

Not only are they more readable, more concise, and less prone to error than other ways of formatting, but they are also faster!

Installation

pip install flynt. It requires Python version 3.6+.

Usage

Flynt will modify the files it runs on. Add your project to version control system before using flynt.

To run: flynt {source_file_or_directory}

  • Given a single file, it will 'f-stringify' it: replace all applicable string formatting in this file (file will be modified).
  • Given a folder, it will search the folder recursively and f-stringify all the .py files it finds. It skips some hard-coded folder names: blacklist = {'.tox', 'venv', 'site-packages', '.eggs'}.

It turns the code it runs on into Python 3.6+, since 3.6 is when "f-strings" were introduced.

Command line options

From the output of flynt -h:

positional arguments:
  src                   source file(s) or directory

optional arguments:
  -h, --help            show this help message and exit
  -v, --verbose         run with verbose output
  -q, --quiet           run without output
  --no-multiline        convert only single line expressions
  -ll LINE_LENGTH, --line-length LINE_LENGTH
                        for expressions spanning multiple lines, convert only if the resulting single line will fit into the line length limit. Default value is 88 characters.
  -d, --dry-run         Do not change the files in-place and print the diff instead. Note that this must be used in conjunction with '--fail-on-change' when used for linting purposes.
  -s, --string          Interpret the input as a Python code snippet and print the converted version. The snippet must use single quotes or escaped double quotes.
  -tc, --transform-concats
                        Replace string concatenations (defined as + operations involving string literals) with f-strings. Available only if flynt is installed with 3.8+ interpreter.
  -f, --fail-on-change  Fail when changing files (for linting purposes)
  -a, --aggressive      Include conversions with potentially changed behavior.
  -e EXCLUDE [EXCLUDE ...], --exclude EXCLUDE [EXCLUDE ...]
                        ignore files with given strings in it's absolute path.
  --version             Print the current version number and exit.

Sample output of a successful run:

38f9d3a65222:~ ikkamens$ git clone https://github.com/pallets/flask.git
Cloning into 'flask'...
...
Resolving deltas: 100% (12203/12203), done.

38f9d3a65222:open_source ikkamens$ flynt flask
Running flynt v.0.40

Flynt run has finished. Stats:

Execution time:                            0.789s
Files modified:                            21
Character count reduction:                 299 (0.06%)

Per expression type:
Old style (`%`) expressions attempted:     40/42 (95.2%)
`.format(...)` calls attempted:            26/33 (78.8%)
F-string expressions created:              48
Out of all attempted transforms, 7 resulted in errors.
To find out specific error messages, use --verbose flag.

_-_._-_._-_._-_._-_._-_._-_._-_._-_._-_._-_._-_._-_._-_._-_._-_._-_._-_._-_._-_._-_._-_._-_._-_._-_.
Please run your tests before commiting. Did flynt get a perfect conversion? give it a star at:
~ https://github.com/ikamensh/flynt ~
Thank you for using flynt. Upgrade more projects and recommend it to your colleagues!

38f9d3a65222:~ ikkamens$

Pre-commit hook

To make sure all formatted strings are always converted to f-strings, you can add flynt to your pre-commit hooks.

Add a new section to .pre-commit-config.yaml:

-   repo: https://github.com/ikamensh/flynt/
    rev: ''
    hooks:
    -   id: flynt

This will run flynt on all modified files before commiting.

You can skip conversion of certain lines by adding # noqa [: anything else] flynt [anything else]

About

Read up on f-strings here:

After obsessively refactoring a project at work, and not even covering 50% of f-string candidates, I realized there was some place for automation. Also it was very interesting to work with ast module.

Dangers of conversion

It is not guaranteed that formatted strings will be exactly the same as before conversion.

'%s' % var is converted to f'{var}'. There is a case when this will behave different from the original - if var is a tuple of one element. In this case, %s displays the element, and f-string displays the tuple. Example:

foo = (1,)
print('%s' % foo) # prints '1'
print(f'{foo}')   # prints '(1,)'

Furthermore, some arguments cause formatting of strings to throw exceptions. One example where f-strings are inconsistent with previous formatting is %d vs {:d} - new format no longer accepts floats. While most cases are covered by taking the formatting specifiers to the f-strings format, the precise exception behaviour might differ as well. Make sure you have sufficient test coverage.

Other Credits / Dependencies / Links

  • astor is used to turn the transformed AST back into code.
  • Thanks to folks from pyddf for their support, advice and participation during spring hackathon 2019, in particular Holger Hass, Farid Muradov, Charlie Clark.
Owner
Elijah K
Software Engineer, Machine Learning.
Elijah K
Features terminal for python

Features Terminal V1.0 (23/10/2021) Um programa para linux com diferentes ferramentas! Recursos: Criador de QR code Gerador de senhas Teste de velocid

1 Oct 26, 2021
Multifunctional library for creating progress bars.

👋 Content Installation Using github Using pypi Quickstart Flags Useful links Documentation Pypi Changelog TODO Contributing FAQ Bar structure ⚙️ Inst

DenyS 27 Jan 01, 2023
Limit your docker image size with a simple CLI command. Perfect to be used inside your CI process.

docker-image-size-limit Limit your docker image size with a simple CLI command. Perfect to be used inside your CI process. Read the announcing post. I

wemake.services 102 Dec 14, 2022
CLI tool to computes CO2 emissions of HPC computations following green-algorithms.org methodology

gqueue gqueue is a CLI (command line interface) tool that computes carbon footprint of HPC computations on clusters running slurm. It follows the meth

4 Dec 10, 2021
Centauro - a command line tool with some network management functionality

Centauro Ferramenta de rede O Centauro é uma ferramenta de linha de comando com

1 Jan 01, 2022
WebApp Maker make web apps (Duh). It is open source and make with python and shell.

WebApp Maker make web apps (Duh). It is open source and make with python and shell. This app can take any website and turn it into an app. I highly recommend turning these few websites into webapps:

2 Jan 09, 2022
Collection of useful command line utilities and snippets to help you organise your workspace and improve workflow.

Collection of useful command line utilities and snippets to help you organise your workspace and improve workflow.

Dominik Tarnowski 3 Dec 26, 2021
A command line interface to interact with the Hypixel api allowing the user to get stats, leaderboards, etc

HyConsole is a way to get data on players and leaderboards from the Hypixel Minecraft server from the command line. Keep in mind I have no a

1 Feb 14, 2022
alternative cli util for update-alternatives

altb altb is a cli utility influenced by update-alternatives of ubuntu. Linked paths are added to $HOME/.local/bin according to XDG Base Directory Spe

Elran Shefer 8 Dec 07, 2022
Another (unofficial) Qt CLI Installer on multi-platforms

Another Qt installer(aqt) Release: Documentation: Test status: and Coverage: This is a utility alternative to the official graphical Qt installer, for

Hiroshi Miura 528 Jan 02, 2023
This is a tool for managing file notes through the command line

This is a tool for managing file notes through the command line

2 Jun 22, 2022
ICMP Reverse Shell written in Python 3 and with Scapy (backdoor/rev shell)

icmpdoor - ICMP Reverse Shell icmpdoor is an ICMP rev shell written in Python3 and scapy. Tested on Ubuntu 20.04, Debian 10 (Kali Linux), and Windows

Jeroen van Kessel 206 Dec 29, 2022
pypinfo is a simple CLI to access PyPI download statistics via Google's BigQuery.

pypinfo: View PyPI download statistics with ease. pypinfo is a simple CLI to access PyPI download statistics via Google's BigQuery. Installation pypin

Ofek Lev 351 Dec 26, 2022
git-partial-submodule is a command-line script for setting up and working with submodules while enabling them to use git's partial clone and sparse checkout features.

Partial Submodules for Git git-partial-submodule is a command-line script for setting up and working with submodules while enabling them to use git's

Nathan Reed 15 Sep 22, 2022
Command-line search tool for GitHub

cligh is a command-line search tool for GitHub.

1 Oct 02, 2022
Wappalyzer CLI tool to find Web Technologies

Wappalyzer CLI tool to find Web Technologies

GOKUL A.P 17 Dec 15, 2022
Rover is a command line interface application that allows through browse through mission data, images, metadata from the NASA Official Website

🤖 rover Rover is a command line interface application that allows through browse through mission data, images, metadata from the NASA Official Websit

Saketha Ramanjam 4 Jan 19, 2022
frogtrade9000 - a command-line Rich client for the freqtrade REST API

frogtrade9000 - a command-line Rich client for the freqtrade REST API I found FreqUI too cumbersome and slow on my Raspberry Pi 400 when running multi

Robert Davey 79 Dec 02, 2022
Projeto Reverse Shell For Python

Use com sabedoria!!! Modo de uso: Linux (inclui Android e Mac): - apt-get update - apt install python3 (ou "python" apenas) - git clone https://github

1 Jan 03, 2022
Notion-cli-list-manager - A simple command-line tool for managing Notion databases

A simple command-line tool for managing Notion List databases. ✨

Giacomo Salici 75 Dec 04, 2022