Skip to main content
Pre-release

This release is a pre-release and may not be stable for production use.

fstr

Build Status PyPI Code style: black License: MIT

1. Use f-string syntax in Python 2:

import fstr

x = 1
y = 2

template = fstr("{x} + {y} = {x + y}")

print(template.evaluate())
1 + 2 = 3

2. Use f-string syntax instead of str.format in both Python 2 and 3:

import fstr

common_error_message = fstr("function {function.__name__!r} failed because {error}")

def add(x, y):
    try:
        return x + y
    except Exception as e:
        msg = common_error_message.format(function=add, error=e)
        print(msg)

def sub(x, y):
    try:
        return x + y
    except Exception as e:
        msg = common_error_message.format(function=sub, error=e)
        print(msg)

add(1, "2")
sub("5", 3)
function 'add' failed because unsupported operand type(s) for +: 'int' and 'str'
function 'sub' failed because can only concatenate str (not "int") to str

Full PEP-498 Compliance

Other backward compatibility libraries for f-string syntax in Python 2 only implement some of the capabilities defined in the PEP's specification. The test cases for fstr were even lifted (with minor changes) from CPython's test suite.

Format Specifiers

Format specifiers may contain evaluated expressions.

import fstr
import decimal

width = 10
precision = 4
value = decimal.Decimal('12.34567')

fstr("result: {value:{width}.{precision}}").evaluate()
'result:      12.35'

Once expressions in a format specifier are evaluated (if necessary), format specifiers are not interpreted by the f-string evaluator. Just as in str.format(), they are merely passed in to the __format__() method of the object being formatted.

Lambdas In Expressions

import fstr

fstr("{(lambda x: x*2)(3)}").format()
'6'

Error Handling

Exact messages will vary depending on whether you are using Python<3.6 or not.


import fstr

fstr("x={x")
File "fstr", line 1
  x={x
      ^
SyntaxError: Mismatched braces in f-string.

import fstr

fstr("x={!x}")
File "fstr", line 1
  x={!x}
    ^
SyntaxError: Empty expresion not allowed.

Performance Considerations

fstr is not meant to be a replacement for python's f-string syntax. Rather it serves primarily as a slightly slower, but more convenient way to do string formatting in the cases where you might otherwise use str.format. Additionally Python's f-string syntax is able to make performance optimizations at compile time that are not afforded to either str.format or fstr.format. Given this we only compare fstr.format to str.format.

The performance of fstr differs depending on whether you:

  • Use Python<3.6 or not.
  • Define your f-string template ahead of time.

For example, this will be significantly slower

for i in range(10):
   s = fstr("{i}**2 = {i**2}").format(i=i)

than if you define your template outside the loop:

template = fstr("{i}**2 = {i**2}")

for i in range(10):
   s = template.format(i=i)

str.format vs fstr.format

from timeit import timeit

str_setup = "template = '{x}' * 10"
fstr_setup = "import fstr\ntemplate = fstr('{x}' * 10)"

str_result = timeit("template.format(x=1)", setup=str_setup, number=1000000)
fstr_result = timeit("template.format(x=1)", setup=fstr_setup, number=1000000)

print("str.format() : %s seconds" % str_result)
print("fstr.format() : %s seconds" % fstr_result)

Python < 3.6

str.format() : 0.741672992706 seconds
fstr.format() : 6.77992010117 seconds

Python >= 3.6

str.format: 0.7007193689933047 seconds
fstr.format: 0.9083925349987112 seconds

Metadata

Release files for fstr 0.1.0a2

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for fstr 0.1.0a2
File Size Uploaded
fstr-0.1.0a2.tar.gz 6.8 kB Details

Built distribution (wheel)

Table of built distributions (wheels) for fstr 0.1.0a2
File Interpreter ABI Platform
fstr-0.1.0a2-py3-none-any.whl Python 3 none any Details

Total release size: 13.8 kB

Release files / fstr-0.1.0a2.tar.gz

Download URL fstr-0.1.0a2.tar.gz
Size 6.8 kB
Tags Source
SHA-256 checksum
How to use checksums
c9ea83f18ad7e10e3f3d0b53a18fb2d9134ccd9c6c9f4998bde9022dd783ad9b
BLAKE2b-256 checksum
How to use checksums
e819d3f61d1ff62559f4fce0abcfe969d6d71865f391f1890305d0292664a7a8
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/1.12.1 pkginfo/1.4.2 requests/2.18.4 setuptools/39.2.0 requests-toolbelt/0.8.0 tqdm/4.26.0 CPython/3.6.5

Release files / fstr-0.1.0a2-py3-none-any.whl

Download URL fstr-0.1.0a2-py3-none-any.whl
Size 6.9 kB
Tags Python 3
SHA-256 checksum
How to use checksums
bd4b6e3b8fe7ff33a761fec109165ca990704b4a4c164171749a6842e9122488
BLAKE2b-256 checksum
How to use checksums
612157edec2a033ca59065e3bb51fa7364d10b2e4ccf4a15d5e61e3c0424b4dd
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/1.12.1 pkginfo/1.4.2 requests/2.18.4 setuptools/39.2.0 requests-toolbelt/0.8.0 tqdm/4.26.0 CPython/3.6.5

Release history Release notifications | RSS feed

This release

0.1.0a2 This release

2 release files

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page