A tool to automatically convert old string literal formatting to f-strings
A tool to automatically convert old string literal formatting to f-strings
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!
Since 2.0, flynt is implemented in Rust and ships as a native executable in the
PyPI wheel — same CLI and output as 1.x, 10–20× faster, with parallel file
processing. The Python import API was removed (CLI-only); if you need
import flynt, pin flynt **Note (2.0 beta):** keep rev: '1.0.6'for now. Pointingrev` at a 2.0
checkout makes pre-commit build flynt from source, which requires a Rust toolchain. A wheel-backed hook (installing the prebuilt binary from PyPI) will ship with the final 2.0 release.
You can skip conversion of certain lines by adding # noqa [: anything else] flynt [anything else] or # flynt: skip
Since v0.71 flynt can be configured using pyproject.toml file on a per-project basis.
Use same arguments as in CLI, and add them to [tool.flynt] section. CLI arguments takes precedence over the config file.
It can also be configured globally with a toml file located in ~/.config/flynt.toml on Unix / ~/.flynt.toml on Windows.
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.
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.
ast.unparse is used to turn the transformed AST back into code.No open issues yet, or sync has not completed.