str.format but with default values
Project description
FormatDefault
str.format
but with default values
Ideal for building a CLI program with format-able filepath arguments
Many existing string formatting tools use regex to find sections like %(param)s
, but regex can be fiddly and is not as flexible as str.format
when it comes to validating format spec.
Why reinvent the wheel when one can just pass an f
string-looking argument and allow Python (and this mini library) to do the heavy lifting, no regex required!
Example Usage
from FormatDefault import format_default
s = "Hello {x:#02x} {y} {y:#02x} {z}"
params = {"x": 100, "y": "hi"}
print(format_default(s, params))
# Hello 0x64 hi NA NA
import argparse
from FormatDefault import format_default
parser = argparse.ArgumentParser()
parser.add_argument("-o",
default = "YouTube/{uploader}/{title} - {camera_type} - {id}.{ext}"
)
args = parser.parse_args()
video_data = {
"id": "jNQXAC9IVRw", "title": "Me at the zoo",
"uploader": "jawed", "ext": "webm",
}
print(format_default(args.o, video_data))
# YouTube/jawed/Me at the zoo - NA - jNQXAC9IVRw.webm
How it works
format_default(s, params, default = "NA")
tries str.format
in a while-loop with a copy of params
.
format_default
catches KeyError
s from missing parameters and the parameter name is added to params
with the value default
.
The values in params
are wrapped in a wrapper class _DefaultWrapper
before being passed to str.format
. This wrapper class implements the __format__(self, fmt)
dunder method to intercept the format specifiers (parts after the colon, eg "#02x"
in "{foo = :#02x}"
).
_DefaultWrapper.__format__
catches ValueError
s from invalid format specifiers for its wrapped value and returns default
in this case.
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
Hashes for FormatDefault-1.0.1-py3-none-any.whl
Algorithm | Hash digest | |
---|---|---|
SHA256 | 87c9a59a2c2f26727960585722d5d274b477d01ac9cf708a46ed6a8d2e032be2 |
|
MD5 | 387f1dca5fd19ca81469fdbcd190795e |
|
BLAKE2b-256 | 45425566c1a7ec0817131a6fb7eb92541e45e96c6b1a7a1e561ca363935507ba |