Skip to main content

A human friendly format string builder

Project description

FString Builder

A simple Python library to enhance the API of the native Python f-string syntax.

This came about from needing to often refer back to the native format string syntax.
I found that configuring formatting options within the program was tricky and tedious.

For example, if I wanted a user-defined width for a given line, it was awkward to include it in every instance of that field. Many mistakes were made.

The API so far is what resulted after prototyping out the idea on a couple personal projects. This ended up working really well for the line formatting portions, I think it could be useful to others.

Installation

Install via pip:

$ pip install fstring-builder

Interface

The idea is to have a main FormatString object that is able to collect and manage items comprising that ultimate string. This object can build a format-ready string from its items.

Each item is either a simple string-like object that gets concatenated in place, or it is a ReplacementField, traditionally noted in f-strings with a format spec inside curly braces {<format_syntax>}.

The ReplacementField accepts all the options from a normal format string. By default, they are all None:

Name Type Description
name str Keyword name variable for the field
conversion ['s', 'r', 'a'] Convert the field to a string, repr, or ascii format
fill str Single string character to use as a fill
align ['<', '>', '^', '='] Align text left, right, center, or numeric-padded
sign ['+', '-', ' '] Sign characters for numeric types
z bool Coerce floating point numbers to positive 0
hashtag bool Use 'alternate' form for conversion
zero bool Pad numeric numbers with 0
width int Set a character width value for the field
grouping [',', '_'] Set the numeric grouping characters
precision int Floating point precision value
type str Format type characters, i.e. d, n, or f

Once your field parameters are set, each field can be built using the .build() method. Alternatively, each FormatString can build all its elements using its own .build().

The result of a .build() is a format-ready string, ie a string that you can call .format(**kwargs) on. The FormatString object has a convenience function .format(**kwargs) that builds and formats itself with any parameters passed.

Example

The following example creates a format ready string for a monetary currency. It could be expanded to provide for a more generic locale-aware currency formatter

import fstring_builder as fsb

# Simple currency format string
# f`${qty:>12,.2f}`

currency_fmt = fsb.FormatString(
    "$", 
    fsb.ReplacementField(
        name="qty",
        grouping=",",
        align="right",
        width=12,
        precision=2,
        type="float"
    )
)

print(currency_fmt)                     # "${qty:>12,.2f}"
print(currency_fmt.format(qty=312.5))   # "$      312.50"
print(currency_fmt.format(qty=15324))   # "$   15,324.00"

currency_fmt._width = 10
print(currency_fmt.format(qty=15324))   # "$ 15,324.00"

Chainable Methods

The parameters for ReplacementField objects can also be set after construction via methods. They are all chainable, allowing for something like:

import fstring_builder as fsb

currency_fmt = fsb.FormatString("$",
    fsb.ReplacementField(name="qty")
        .align(fsb.Align.RIGHT)
        .grouping(fsb.Grouping.COMMA)
        .width(12)
        .precision(2)
        .type(fsb.Type.Float.NUMERIC)
)

currency_fmt.build()

print(currency_fmt.format(qty=15324))       # "$   15,324.00"
print(currency_fmt.format(qty=-2157.25))    # "$   -2,157.25"
print(currency_fmt.format(qty=0))           # "$        0.00"

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

fstring_builder-0.2.0.tar.gz (17.4 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

fstring_builder-0.2.0-py3-none-any.whl (18.3 kB view details)

Uploaded Python 3

File details

Details for the file fstring_builder-0.2.0.tar.gz.

File metadata

  • Download URL: fstring_builder-0.2.0.tar.gz
  • Upload date:
  • Size: 17.4 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/4.0.1 CPython/3.9.15

File hashes

Hashes for fstring_builder-0.2.0.tar.gz
Algorithm Hash digest
SHA256 516ba5e99838d739fc5c64d10f42e7998fc806a50c996930eefe488910b511fc
MD5 03be96b15f1d32f41560acf890ab9a5d
BLAKE2b-256 a110073921e7a04aadaff1015aab6edffc13d0593adf524bd7a201cae90ff5e5

See more details on using hashes here.

File details

Details for the file fstring_builder-0.2.0-py3-none-any.whl.

File metadata

File hashes

Hashes for fstring_builder-0.2.0-py3-none-any.whl
Algorithm Hash digest
SHA256 4c85e6cdd3a237f8fb3af1db92c99e3f6f16e9b0a4e1fa6d4b56b96ebffd399a
MD5 0234b60f9ac1823866323ec717a507ef
BLAKE2b-256 a0e96125d2af050d11d23a573582c66cce4fba7b55649cffc55dc38161b268b6

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page