How Can I Override The Default String Formatter In Python?
Is there some way I can change the Formatter python's string.format() uses? I have a custom one (disables the check_unused_args method), but this requires me use the formatter.form
Solution 1:
Is there some way I can change the Formatter python's string.format() uses?
No. I think the rational is because it would lead to really confusing code. People would expect format_string.format(...)
to behave one way, and it would behave differently causing bugs and general sadness.
You can however, explicitly tell python that you want to use a different formatter.
classMyFormatter(string.Formatter):
"""This is my formatter which is better than the standard one."""# customization here ...
MyFormatter().format(format_string, *args, **kwargs)
By inheriting from string.Formatter
, you gain access to the entire Formatter
API which can make your custom formatter work better.
If that weren't enough, you can customize how objects format themselves using the __format__
hook method which Formatter
objects call (including the standard one).
Post a Comment for "How Can I Override The Default String Formatter In Python?"