Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.format("text") syntax, instead of the "text".format() syntax, which I'd prefer.

Can I swap out the 'default formatter' somehow?

NOTE: This is just a small project, I don't need to worry about messing up libraries or anything.

like image 426
AlphaModder Avatar asked Oct 15 '15 23:10

AlphaModder


Video Answer


1 Answers

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.

class MyFormatter(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).

like image 86
mgilson Avatar answered Nov 15 '22 06:11

mgilson