Reading through PEP 3101, it discusses how to subclass string.Formatter to define your own formats, but then you use it via myformatter.format(string)
. Is there a way to just make it work with f-strings?
E.g. I'm looking to do something like f"height = {height:.2f}"
but I want my own float formatter that handles certain special cases.
As I mentioned in comments F-strings are actually processed at compile time, not runtime. you can't override the default f-string formatter is due to how Python implements f-strings at a fundamental level.
For example if you run
f"height = {height:.2f}"
It effectively converts
"height = {}".format(format(height, '.2f'))
conversion happens during compilation, there's no way to "hook into" or modify this process at runtime.
What you can do is.
use decimal
Module for Precision Control.
Reference - https://realpython.com/how-to-python-f-string-format-float/
from decimal import Decimal
value = Decimal('1.23456789')
print(f"Value: {value:.2f}")
Output:
Value: 1.23
Decimal implements the format method and handles the standard format specifiers like .2f.
We aren't really "overriding" the default formatter here - it's implementing the existing format specification protocol.
As your goal is to handle special cases for float formatting, using Decimal could solve your problem...