All Projects → asottile → Future Fstrings

asottile / Future Fstrings

Licence: mit
A backport of fstrings to python<3.6

Programming Languages

python
139335 projects - #7 most used programming language
hack
652 projects

Build Status Azure DevOps coverage pre-commit.ci status

future-fstrings

A backport of fstrings to python<3.6.

Installation

pip install future-fstrings

Usage

Include the following encoding cookie at the top of your file (this replaces the utf-8 cookie if you already have it):

# -*- coding: future_fstrings -*-

And then write python3.6 fstring code as usual!

# -*- coding: future_fstrings -*-
thing = 'world'
print(f'hello {thing}')
$ python2.7 main.py
hello world

Showing transformed source

future-fstrings also includes a cli to show transformed source.

$ future-fstrings-show main.py
# -*- coding: future_fstrings -*-
thing = 'world'
print('hello {}'.format((thing)))

Transform source for micropython

The future-fstrings-show command can be used to transform source before distributing. This can allow you to write f-string code but target platforms which do not support f-strings, such as micropython.

To use this on modern versions of python, install using:

pip install future-fstrings[rewrite]

and then use future-fstrings-show as above.

For instance:

future-fstrings-show code.py > code_rewritten.py

How does this work?

future-fstrings has two parts:

  1. A utf-8 compatible codec which performs source manipulation
    • The codec first decodes the source bytes using the UTF-8 codec
    • The codec then leverages tokenize-rt to rewrite f-strings.
  2. A .pth file which registers a codec on interpreter startup.

when you aren't using normal site registration

in setups (such as aws lambda) where you utilize PYTHONPATH or sys.path instead of truly installed packages, the .pth magic above will not take.

for those circumstances, you'll need to manually initialize future-fstrings in a non-fstring wrapper. for instance:

import future_fstrings

future_fstrings.register()

from actual_main import main

if __name__ == '__main__':
    exit(main())

you may also like

Note that the project description data, including the texts, logos, images, and/or trademarks, for each open source project belongs to its rightful owner. If you wish to add or remove any projects, please contact us at [email protected].